From 4638a1c71f1bf89001cacb3d7e8aca99e011f486 Mon Sep 17 00:00:00 2001 From: "lusendong.6789" Date: Sat, 12 Sep 2026 13:46:28 +0800 Subject: [PATCH 1/9] feat(lark): add approved goal channel payload delivery Signed-off-by: lusendong.6789 Co-authored-by: TRAE CLI --- docs/reference/protocols/README.md | 1 + .../goal-channel-frozen-payload-v0.md | 46 ++ loopx/cli_commands/goal_channel.py | 77 ++- loopx/extensions/lark/README.md | 53 +- loopx/extensions/lark/extension.toml | 6 +- loopx/extensions/lark/goal_channel.py | 6 + .../lark/goal_channel_delivery_contract.py | 73 +++ .../lark/goal_channel_message_delivery.py | 397 +++++++++++++ loopx/extensions/lark/goal_channel_payload.py | 527 ++++++++++++++++++ .../lark/periodic_report_delivery.py | 350 +----------- .../lark/presentation/periodic_report.py | 50 +- loopx/extensions/lark/provider.py | 2 + tests/extensions/test_goal_channel_payload.py | 407 ++++++++++++++ tests/extensions/test_lark_goal_channel.py | 93 ++++ .../test_lark_goal_channel_targets.py | 26 + ...t_periodic_report_goal_channel_delivery.py | 9 +- .../extensions/test_periodic_report_miaoda.py | 16 +- 17 files changed, 1729 insertions(+), 410 deletions(-) create mode 100644 docs/reference/protocols/goal-channel-frozen-payload-v0.md create mode 100644 loopx/extensions/lark/goal_channel_delivery_contract.py create mode 100644 loopx/extensions/lark/goal_channel_message_delivery.py create mode 100644 loopx/extensions/lark/goal_channel_payload.py create mode 100644 tests/extensions/test_goal_channel_payload.py diff --git a/docs/reference/protocols/README.md b/docs/reference/protocols/README.md index 65c6e9b9d0..0309c8dcfe 100644 --- a/docs/reference/protocols/README.md +++ b/docs/reference/protocols/README.md @@ -42,6 +42,7 @@ scanning a chronological list. - [`peer_agent_runtime_v1`](peer-agent-runtime-v1.md): Peer agent runtime v1 - [`peer_supervisor_v0`](peer-supervisor-v0.md): Peer supervisor v0 - [`periodic_report_v0`](periodic-report-v0.md): Periodic report v0 +- [`goal_channel_frozen_payload_v0`](goal-channel-frozen-payload-v0.md): exact-approval delivery of one frozen capability payload through a bound Goal Channel - [`review_batch_v0`](review-batch-v0.md): Review batch v0 - [`reward_memory_architecture_v0`](../../../loopx/capabilities/reward_memory/README.md): Reward memory architecture v0 - [`reward_memory_architecture_v0`](../../../loopx/capabilities/reward_memory/README.zh-CN.md): Reward memory architecture v0 (中文) diff --git a/docs/reference/protocols/goal-channel-frozen-payload-v0.md b/docs/reference/protocols/goal-channel-frozen-payload-v0.md new file mode 100644 index 0000000000..071a255e8f --- /dev/null +++ b/docs/reference/protocols/goal-channel-frozen-payload-v0.md @@ -0,0 +1,46 @@ +# Goal Channel frozen payload v0 + +Status: provider-backed, capability-neutral exact-approval delivery contract. + +`goal_channel_frozen_payload_request_v0` lets any producing capability submit +one final public-safe Markdown result for a LoopX Goal Channel. It does not +classify domain facts or make content safe. The producer retains responsibility +for semantics, sources, redaction, and the truthful `public_safe=true` +attestation. + +## Lifecycle + +1. The producer supplies a capability id, opaque payload ref, title, Markdown, + footer, and one `public_claim:action:` decision scope. +2. LoopX renders the final Lark card, hashes the canonical card, and stores the + content in an owner-local `0600` receipt. Public Todo state contains only + the receipt id, digest, scope, and execution requirements. +3. LoopX creates one blocked Agent delivery Todo and one User gate whose + `unblocks_todo_id` points to that successor. Approve consumes only the exact + required scope; reject or cancel keeps delivery blocked. +4. Delivery reloads both Todos and the private receipt. It fails closed unless + the gate is done with `approve`, the successor is open (or already done for + an exact replay), and its required decision scopes are empty. +5. The Lark extension resolves the route only from the durable Goal Channel + binding. The caller cannot select the chat, profile, Bot, sender, or mention + recipients. Binding drift after preparation invalidates the approval. +6. Before sending, LoopX verifies the project Bot and reads complete Bot-visible + channel history. An exact existing card is reused. Otherwise one + provider-idempotent message is sent. Provider-native sender, chat, and card + readback are required before the delivery Todo and receipt become satisfied. + +## Boundaries + +- Receipt content and provider identifiers stay in local-private runtime state. +- Public command results expose only opaque ids, digests, decision scopes, and + lifecycle status. +- Mention markup is rejected; audience selection belongs to a capability with + an explicit typed audience policy. +- The contract grants no standing publication authority. Every payload needs + its own exact gate unless another capability, such as Periodic Report, owns a + separately documented standing subscription. +- A successful provider write without exact native readback is not completion. + +This mechanism complements `content_ops_item_v0`: content-ops can track +provider-neutral item state without storing bodies, while this Lark extension +owns one concrete Goal Channel effect and its private payload receipt. diff --git a/loopx/cli_commands/goal_channel.py b/loopx/cli_commands/goal_channel.py index 2a763bdb54..a3047ecb2d 100644 --- a/loopx/cli_commands/goal_channel.py +++ b/loopx/cli_commands/goal_channel.py @@ -1,6 +1,7 @@ from __future__ import annotations import argparse +import json from collections.abc import Callable, Mapping from pathlib import Path from typing import Any @@ -14,10 +15,12 @@ configure_lark_goal_channel_automation, default_goal_channel_binding_path, default_goal_channel_target_path, + deliver_goal_channel_payload, doctor_lark_goal_channel, goal_channel_target_for_name, list_goal_channel_targets, notify_lark_goal_channel_gate, + prepare_goal_channel_payload, read_goal_channel_binding, read_goal_channel_targets, setup_lark_goal_channel, @@ -201,6 +204,31 @@ def register_goal_channel_commands( ) notify.add_argument("--execute", action="store_true") + prepare = sub.add_parser( + "prepare-payload", + help=( + "Freeze one capability-owned public payload and create its exact " + "approval successor. Dry-run unless --execute." + ), + ) + add_subcommand_format(prepare) + _add_common_args(prepare) + prepare.add_argument("--agent-id", required=True) + prepare.add_argument("--request-json", required=True) + prepare.add_argument("--execute", action="store_true") + + deliver = sub.add_parser( + "deliver-payload", + help=( + "Deliver one exactly approved frozen payload through the bound " + "project Bot. Dry-run unless --execute." + ), + ) + add_subcommand_format(deliver) + _add_common_args(deliver) + deliver.add_argument("--receipt-id", required=True) + deliver.add_argument("--execute", action="store_true") + register_goal_channel_runtime_commands(sub, add_subcommand_format) @@ -270,7 +298,7 @@ def _source_context( registry_path: Path, goal_id: str, binding_path_arg: str | None = None, -) -> tuple[dict[str, Any], Path, Path]: +) -> tuple[dict[str, Any], Path, Path, Path]: source_route = resolve_goal_source_runtime_route( registry_path=registry_path, goal_id=goal_id, @@ -288,7 +316,8 @@ def _source_context( if binding_path_arg else default_goal_channel_binding_path(source_registry_path) ) - return source_registry, source_registry_path, binding_path + source_runtime_root = Path(str(source_route["source_runtime_root"])) + return source_registry, source_registry_path, binding_path, source_runtime_root def _attach_goals( @@ -327,7 +356,7 @@ def _attach_goals( external_write_performed = False readback_verified = True for goal_id in unique_goal_ids: - source_registry, source_registry_path, binding_path = _source_context( + source_registry, source_registry_path, binding_path, _ = _source_context( registry=registry, registry_path=registry_path, goal_id=goal_id, @@ -428,7 +457,7 @@ def handle_goal_channel_command( ) if command == "runtime": assert goal_id is not None - source_registry, source_registry_path, _ = _source_context( + source_registry, source_registry_path, _, _ = _source_context( registry=registry, registry_path=registry_path, goal_id=goal_id, @@ -440,7 +469,7 @@ def handle_goal_channel_command( return 0 if payload.get("ok") else 1 if command == "configure" and bool(args.auto_notify_human_gates): assert goal_id is not None - _, source_registry_path, binding_path = _source_context( + _, source_registry_path, binding_path, _ = _source_context( registry=registry, registry_path=registry_path, goal_id=goal_id, @@ -471,7 +500,7 @@ def handle_goal_channel_command( return 1 if command == "configure" and not bool(args.auto_notify_human_gates): assert goal_id is not None - source_registry, _, binding_path = _source_context( + source_registry, _, binding_path, _ = _source_context( registry=registry, registry_path=registry_path, goal_id=goal_id, @@ -559,12 +588,19 @@ def handle_goal_channel_command( ) else: assert goal_id is not None - source_registry, source_registry_path, binding_path = _source_context( + ( + source_registry, + source_registry_path, + binding_path, + source_runtime_root, + ) = _source_context( registry=registry, registry_path=registry_path, goal_id=goal_id, binding_path_arg=getattr(args, "binding_path", None), ) + if command in {"prepare-payload", "deliver-payload"}: + target_path = _target_path(args, source_runtime_root) target_name = str(getattr(args, "target", None) or "") if not target_name: target_name = _binding_target_name(binding_path, goal_id) @@ -656,6 +692,33 @@ def handle_goal_channel_command( ), execute=execute, ) + elif command == "prepare-payload": + request_path = Path(str(args.request_json)).expanduser() + request = json.loads(request_path.read_text(encoding="utf-8")) + if not isinstance(request, dict): + raise ValueError( + "Goal Channel payload request must be an object" + ) + payload = prepare_goal_channel_payload( + request, + registry_path=source_registry_path, + runtime_root=source_runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=goal_id, + agent_id=args.agent_id, + execute=execute, + ) + elif command == "deliver-payload": + payload = deliver_goal_channel_payload( + receipt_id=args.receipt_id, + registry_path=source_registry_path, + runtime_root=source_runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=goal_id, + execute=execute, + ) else: raise ValueError(f"unknown goal-channel command: {command}") if payload.get("ok"): diff --git a/loopx/extensions/lark/README.md b/loopx/extensions/lark/README.md index bf8908c545..c7b83174c9 100644 --- a/loopx/extensions/lark/README.md +++ b/loopx/extensions/lark/README.md @@ -11,7 +11,7 @@ evidence, or recovery authority. | `lark-event-inbox` | Collect, inspect, reply to, and acknowledge bounded project feedback | [`event_inbox.py`](event_inbox.py), [`event_collector.py`](event_collector.py) | | `lark-reviewer-notification` | Send and verify a reviewer notification through a project-dedicated Lark app | [`reviewer_notification.py`](reviewer_notification.py) | | `lark-kanban-projection` | Render public-safe LoopX todo and control-plane projections into Lark Base | [`presentation/kanban.py`](presentation/kanban.py) | -| `lark-goal-channel` | Bind one verified Lark group and projection surface to one LoopX goal | [`goal_channel.py`](goal_channel.py), [`goal_channel_setup.py`](goal_channel_setup.py) | +| `lark-goal-channel` | Bind one verified Lark group and projection surface to one LoopX goal, including exact-approval delivery of frozen capability payloads | [`goal_channel.py`](goal_channel.py), [`goal_channel_payload.py`](goal_channel_payload.py) | | `lark-explore-projection` | Project canonical Explore results into Lark tables, cards, and whiteboards | [`presentation/explore_results.py`](presentation/explore_results.py) | | `lark-periodic-report-announcement` | Deliver a periodic report through the current Goal Channel's verified project Bot while mentioning only recipients selected by its typed audience plan | [`periodic_report_delivery.py`](periodic_report_delivery.py) | | `lark-periodic-report-source` | Bind and settle one exact Agent-selected Goal Channel source for a typed report action without classifying message text | [`periodic_report_request.py`](periodic_report_request.py) | @@ -71,6 +71,57 @@ collector, processing, reply, reaction, and acknowledgement lifecycle. The [Lark Kanban integration guide](../../../docs/integrations/lark-kanban-control-plane-adapter.md) documents projection configuration and lineage. +### Exact-approval capability payloads + +Any capability may hand LoopX one already public-safe Markdown result without +becoming coupled to Lark. The capability owns domain semantics, citations, and +redaction, and attests `public_safe=true`; LoopX freezes the final card, stores +it only in owner-local runtime state, and creates a blocked delivery Todo plus +an exact user gate. The public Todo stores only an opaque receipt id, digest, +and decision scope. + +Prepare a payload from a local request file: + +```bash +loopx goal-channel prepare-payload \ + --goal-id \ + --agent-id \ + --request-json + +loopx goal-channel prepare-payload \ + --goal-id \ + --agent-id \ + --request-json \ + --execute +``` + +The request uses `goal_channel_frozen_payload_request_v0` and supplies one +capability id, opaque payload ref, title, Markdown body, footer, and an exact +`public_claim:action:` decision scope. It cannot select a chat, profile, +Bot, sender, or mention recipient. Complete the generated user gate with +`decision_outcome=approve`, then preview and execute the receipt returned by +prepare: + +```bash +loopx goal-channel deliver-payload \ + --goal-id \ + --receipt-id gcp_ + +loopx goal-channel deliver-payload \ + --goal-id \ + --receipt-id gcp_ \ + --execute +``` + +Delivery fails before any provider write when the exact gate is not approved, +the frozen card changes, or the Goal Channel binding changes. Execution uses +only the bound project Bot, scans complete Bot-visible history for the exact +card before sending, and requires provider-native sender, chat, and content +readback. An exact retry therefore reuses the existing message instead of +sending a duplicate. Periodic reports keep their separate standing-subscription +authority and existing two-announcement workflow; they are not routed through +this one-shot approval contract. + ### Bounded group-history catch-up The event inbox can reconcile messages that predate the live event collector. diff --git a/loopx/extensions/lark/extension.toml b/loopx/extensions/lark/extension.toml index eadff25a03..be93114ae6 100644 --- a/loopx/extensions/lark/extension.toml +++ b/loopx/extensions/lark/extension.toml @@ -1,6 +1,6 @@ schema_version = "loopx_extension_manifest_v0" id = "loopx-lark" -version = "1.6.0" +version = "1.7.0" requires_loopx_api = ">=1,<2" permissions = [ "lark.inbox.read", @@ -82,9 +82,9 @@ title = "Lark Goal Channel" status = "active-preview" visibility = "public" real_world_anchor = "one verified Lark group and Kanban projection bound to one LoopX goal" -user_value = "Keep goal progress and human gates visible in one collaboration channel while LoopX remains the source of truth." +user_value = "Keep goal progress, human gates, and exactly approved capability results visible in one collaboration channel while LoopX remains the source of truth." entry_command = "loopx goal-channel setup --provider lark --goal-id " -next_real_step = "Install or upgrade and explicitly enable the bundled provider before configuring a Goal Channel." +next_real_step = "Install or upgrade and explicitly enable the bundled provider, configure a Goal Channel, then prepare and approve each non-subscription payload before delivery." [[provides]] id = "lark-explore-projection" diff --git a/loopx/extensions/lark/goal_channel.py b/loopx/extensions/lark/goal_channel.py index 5a2e957e95..d7b3fe9a6a 100644 --- a/loopx/extensions/lark/goal_channel.py +++ b/loopx/extensions/lark/goal_channel.py @@ -14,6 +14,10 @@ sync_lark_goal_channel, ) from .goal_channel_setup import setup_lark_goal_channel +from .goal_channel_payload import ( + deliver_goal_channel_payload, + prepare_goal_channel_payload, +) from .goal_channel_targets import ( GOAL_CHANNEL_TARGETS_SCHEMA_VERSION, add_lark_goal_channel_target, @@ -34,7 +38,9 @@ "default_goal_channel_binding_path", "default_goal_channel_target_path", "doctor_lark_goal_channel", + "deliver_goal_channel_payload", "notify_lark_goal_channel_gate", + "prepare_goal_channel_payload", "goal_channel_target_for_name", "list_goal_channel_targets", "read_goal_channel_binding", diff --git a/loopx/extensions/lark/goal_channel_delivery_contract.py b/loopx/extensions/lark/goal_channel_delivery_contract.py new file mode 100644 index 0000000000..3da9acb42a --- /dev/null +++ b/loopx/extensions/lark/goal_channel_delivery_contract.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +import hashlib +import json +import re +from collections.abc import Callable, Mapping +from typing import Any + + +_GOAL_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$") +_LARK_CHAT_ID_RE = re.compile(r"^oc_[A-Za-z0-9_-]+$") +_LARK_APP_ID_RE = re.compile(r"^cli_[A-Za-z0-9_-]+$") +_LARK_PROFILE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$") + + +def goal_channel_delivery_route( + goal_id: object, + resolve_goal_channel: Callable[[str], Mapping[str, Any]], +) -> dict[str, Any]: + safe_goal_id = str(goal_id or "").strip() + if not _GOAL_ID_RE.fullmatch(safe_goal_id): + raise ValueError("goal_id must be a stable LoopX Goal id") + binding = dict(resolve_goal_channel(safe_goal_id)) + channel = binding.get("channel") + identity = binding.get("identity") + if ( + binding.get("goal_id") != safe_goal_id + or binding.get("provider") != "lark" + or binding.get("enabled") is not True + or not isinstance(channel, Mapping) + or not isinstance(identity, Mapping) + ): + raise ValueError( + "Goal Channel delivery requires the enabled Lark Goal Channel binding" + ) + chat_id = str(channel.get("chat_id") or "").strip() + sender_profile = str(identity.get("sender_profile") or "").strip() + sender_identity = str(identity.get("sender_identity") or "").strip() + bot_app_id = str(identity.get("bot_app_id") or "").strip() + bot_display_name = str(identity.get("bot_display_name") or "").strip() + cli_bin = str(identity.get("cli_bin") or "lark-cli").strip() + if ( + identity.get("mode") != "project_bot" + or sender_identity != "bot" + or not _LARK_CHAT_ID_RE.fullmatch(chat_id) + or not _LARK_PROFILE_RE.fullmatch(sender_profile) + or sender_profile.lower() == "default" + or not _LARK_APP_ID_RE.fullmatch(bot_app_id) + or not bot_display_name + or not cli_bin + ): + raise ValueError( + "Goal Channel delivery requires a complete project_bot Goal Channel identity" + ) + return { + "goal_id": safe_goal_id, + "chat_id": chat_id, + "sender_profile": sender_profile, + "sender_identity": sender_identity, + "bot_app_id": bot_app_id, + "bot_display_name": bot_display_name, + "cli_bin": cli_bin, + } + + +def goal_channel_binding_digest(binding: Mapping[str, Any]) -> str: + encoded = json.dumps( + dict(binding), ensure_ascii=False, sort_keys=True, separators=(",", ":") + ).encode("utf-8") + return "sha256:" + hashlib.sha256(encoded).hexdigest() + + +__all__ = ["goal_channel_binding_digest", "goal_channel_delivery_route"] diff --git a/loopx/extensions/lark/goal_channel_message_delivery.py b/loopx/extensions/lark/goal_channel_message_delivery.py new file mode 100644 index 0000000000..2a2c4d04f2 --- /dev/null +++ b/loopx/extensions/lark/goal_channel_message_delivery.py @@ -0,0 +1,397 @@ +from __future__ import annotations + +import hashlib +import json +from collections.abc import Callable, Mapping +from pathlib import Path +from typing import Any + +from .goal_channel_contracts import binding_for_goal, read_goal_channel_binding +from .goal_channel_delivery_contract import goal_channel_delivery_route +from .goal_channel_targets import ( + goal_channel_target_for_name, + read_goal_channel_targets, +) +from .goal_channel_transport import ( + MESSAGE_ID_PATTERN, + auth_verified, + bot_membership_verified, + call, + chat_verified, + contains_exact_field, + find_first_string, + json_payload, + lark_args, + verified_app_id, +) +from .presentation.kanban import CommandRunner + + +def resolve_bound_goal_channel( + *, + binding_path: Path, + target_path: Path, + goal_id: str, + agent_id: str | None = None, +) -> dict[str, Any]: + payload = read_goal_channel_binding(binding_path) + raw = ( + binding_for_goal(payload, goal_id, agent_id=agent_id) + if agent_id is not None + else None + ) + if raw is None: + raw = binding_for_goal(payload, goal_id) + if raw is None: + raise ValueError("Goal Channel delivery requires one durable binding") + target_ref = str(raw.get("target_ref") or "").strip() + target = None + if target_ref: + target = goal_channel_target_for_name( + read_goal_channel_targets(target_path), target_ref + ) + if target is None: + raise ValueError("Goal Channel delivery target is missing") + resolved = binding_for_goal( + payload, + goal_id, + provider_target=target, + agent_id=( + agent_id + if agent_id is not None + and binding_for_goal(payload, goal_id, agent_id=agent_id) is not None + else None + ), + ) + if resolved is None: + raise ValueError("Goal Channel delivery binding is incomplete") + goal_channel_delivery_route(goal_id, lambda _goal_id: resolved) + return resolved + + +def _find_message(value: Any, message_id: str) -> Mapping[str, Any] | None: + if isinstance(value, Mapping): + if str(value.get("message_id") or "") == message_id: + return value + for child in value.values(): + found = _find_message(child, message_id) + if found is not None: + return found + elif isinstance(value, list): + for child in value: + found = _find_message(child, message_id) + if found is not None: + return found + return None + + +def _message_rows(value: Any) -> list[Mapping[str, Any]]: + rows: list[Mapping[str, Any]] = [] + if isinstance(value, Mapping): + message_id = str(value.get("message_id") or "") + if MESSAGE_ID_PATTERN.fullmatch(message_id): + rows.append(value) + for child in value.values(): + rows.extend(_message_rows(child)) + elif isinstance(value, list): + for child in value: + rows.extend(_message_rows(child)) + return rows + + +def _history_is_complete(value: Mapping[str, Any]) -> bool: + completeness: list[bool] = [] + for candidate in (value, value.get("data")): + if not isinstance(candidate, Mapping): + continue + if isinstance(candidate.get("has_more"), bool): + completeness.append(candidate["has_more"] is False) + meta = value.get("meta") + pagination = meta.get("pagination") if isinstance(meta, Mapping) else None + if isinstance(pagination, Mapping) and isinstance(pagination.get("complete"), bool): + completeness.append(pagination["complete"] is True) + return bool(completeness) and all(completeness) + + +def _message_card(value: Mapping[str, Any]) -> Mapping[str, Any] | None: + body = value.get("body") + content = body.get("content") if isinstance(body, Mapping) else None + if isinstance(content, Mapping): + return content + if not isinstance(content, str): + return None + try: + parsed = json.loads(content) + except json.JSONDecodeError: + return None + return parsed if isinstance(parsed, Mapping) else None + + +def _normalized_card_text(card: Mapping[str, Any]) -> str | None: + header = card.get("header") + elements = card.get("elements") + if not isinstance(header, Mapping) or not isinstance(elements, list): + return None + title = header.get("title") + title = title.get("content") if isinstance(title, Mapping) else None + if not isinstance(title, str) or not elements: + return None + first = elements[0] + first = first if isinstance(first, Mapping) else {} + text = first.get("text") + markdown = text.get("content") if isinstance(text, Mapping) else None + if not isinstance(markdown, str): + return None + footer = None + if len(elements) == 3 and elements[1] == {"tag": "hr"}: + note = elements[2] + note_elements = note.get("elements") if isinstance(note, Mapping) else None + if isinstance(note_elements, list) and len(note_elements) == 1: + note_text = note_elements[0] + footer = ( + note_text.get("content") if isinstance(note_text, Mapping) else None + ) + lines = [f'', markdown] + if isinstance(footer, str) and footer: + lines.extend(["---", f"📝 {footer}"]) + lines.append("") + return "\n".join(lines) + + +def _message_card_matches( + value: Mapping[str, Any], expected: Mapping[str, Any] | None +) -> bool: + if expected is None: + return False + if _message_card(value) == expected: + return True + content = value.get("content") + return isinstance(content, str) and content == _normalized_card_text(expected) + + +def _message_sender(value: Mapping[str, Any]) -> tuple[str, str]: + sender = value.get("sender") + sender = sender if isinstance(sender, Mapping) else {} + sender_type = str( + sender.get("sender_type") or value.get("sender_type") or "" + ).strip() + sender_id = str( + sender.get("id") or sender.get("sender_id") or value.get("sender_id") or "" + ).strip() + return sender_type, sender_id + + +class GoalChannelMessageDeliverySession: + """Verified project-Bot delivery with exact history dedupe and readback.""" + + def __init__( + self, + *, + goal_id: str, + binding: Mapping[str, Any], + history_start_at: str, + resolve_current_binding: Callable[[], Mapping[str, Any]], + runner: CommandRunner, + ) -> None: + self.goal_id = goal_id + self.binding = dict(binding) + self.history_start_at = history_start_at + self.resolve_current_binding = resolve_current_binding + self.runner = runner + self.route: dict[str, Any] = {} + self.expected_cards: dict[str, list[dict[str, Any]]] = {} + + def _existing_message( + self, card: Mapping[str, Any], route: Mapping[str, Any] + ) -> str | None: + result = call( + self.runner, + lark_args( + cli_bin=str(route["cli_bin"]), + profile=str(route["sender_profile"]), + tail=[ + "im", + "+chat-messages-list", + "--chat-id", + str(route["chat_id"]), + "--start", + self.history_start_at, + "--order", + "asc", + "--page-all", + "--page-limit", + "1000", + "--as", + "bot", + "--no-reactions", + "--format", + "json", + ], + ), + ) + payload = json_payload(result) + if result.get("returncode") != 0: + raise ValueError("Goal Channel delivery dedupe readback failed") + for message in _message_rows(payload): + sender_type, sender_app_id = _message_sender(message) + if ( + message.get("deleted") is not True + and str(message.get("chat_id") or "") == route["chat_id"] + and sender_type == "app" + and sender_app_id == route["bot_app_id"] + and _message_card_matches(message, card) + ): + return str(message["message_id"]) + if not _history_is_complete(payload): + raise ValueError("Goal Channel delivery dedupe history is incomplete") + return None + + def resolve(self, requested_goal_id: str) -> Mapping[str, Any]: + if requested_goal_id != self.goal_id: + raise ValueError("Goal Channel delivery goal identity changed") + return self.binding + + def verify(self, route: Mapping[str, Any]) -> bool: + cli_bin = str(route["cli_bin"]) + profile = str(route["sender_profile"]) + app_id = str(route["bot_app_id"]) + chat_id = str(route["chat_id"]) + verified = all( + ( + auth_verified( + runner=self.runner, + cli_bin=cli_bin, + profile=profile, + identity="bot", + expected_bot_name=str(route["bot_display_name"]), + ), + verified_app_id(runner=self.runner, cli_bin=cli_bin, profile=profile) + == app_id, + chat_verified( + runner=self.runner, + cli_bin=cli_bin, + profile=profile, + identity="bot", + chat_id=chat_id, + ), + bot_membership_verified( + runner=self.runner, + cli_bin=cli_bin, + profile=profile, + chat_id=chat_id, + app_id=app_id, + ), + ) + ) + if verified: + self.route = dict(route) + return verified + + def send( + self, card: Mapping[str, Any], key: str, route: Mapping[str, Any] + ) -> Mapping[str, Any]: + if dict(self.resolve_current_binding()) != self.binding: + raise ValueError("Goal Channel delivery binding drifted") + existing_message_id = self._existing_message(card, route) + if existing_message_id is not None: + self.expected_cards.setdefault(existing_message_id, []).append(dict(card)) + return { + "message_id": existing_message_id, + "semantic_dedupe_status": "existing_exact_message", + "external_write_performed": False, + } + result = call( + self.runner, + lark_args( + cli_bin=str(route["cli_bin"]), + profile=str(route["sender_profile"]), + tail=[ + "im", + "+messages-send", + "--chat-id", + str(route["chat_id"]), + "--content", + json.dumps(card, ensure_ascii=False, separators=(",", ":")), + "--msg-type", + "interactive", + "--idempotency-key", + f"loopx-{hashlib.sha256(key.encode()).hexdigest()[:32]}", + "--as", + "bot", + "--format", + "json", + ], + ), + ) + message_id = find_first_string( + json_payload(result), {"message_id"}, MESSAGE_ID_PATTERN + ) + if result.get("returncode") != 0 or not message_id: + raise ValueError("Goal Channel delivery send failed") + self.expected_cards.setdefault(message_id, []).append(dict(card)) + return { + "message_id": message_id, + "semantic_dedupe_status": "no_existing_exact_message", + "external_write_performed": True, + } + + def readback(self, message_id: str) -> Mapping[str, Any]: + result = call( + self.runner, + lark_args( + cli_bin=str(self.route["cli_bin"]), + profile=str(self.route["sender_profile"]), + tail=[ + "im", + "+messages-mget", + "--message-ids", + message_id, + "--as", + "bot", + "--no-reactions", + "--format", + "json", + ], + ), + ) + message = _find_message(json_payload(result), message_id) + sender_type, sender_app_id = ( + _message_sender(message) if message is not None else ("", "") + ) + expected_card = (self.expected_cards.get(message_id) or [None]).pop(0) + exact = bool( + result.get("returncode") == 0 + and message is not None + and contains_exact_field(message, "chat_id", str(self.route["chat_id"])) + and _message_card_matches(message, expected_card) + and sender_type == "app" + and sender_app_id == self.route["bot_app_id"] + and auth_verified( + runner=self.runner, + cli_bin=str(self.route["cli_bin"]), + profile=str(self.route["sender_profile"]), + identity="bot", + expected_bot_name=str(self.route["bot_display_name"]), + ) + and verified_app_id( + runner=self.runner, + cli_bin=str(self.route["cli_bin"]), + profile=str(self.route["sender_profile"]), + ) + == self.route["bot_app_id"] + ) + return { + "verified": exact, + "message_id": message_id, + "chat_id": self.route["chat_id"] if exact else None, + "sender_app_id": sender_app_id if exact else None, + "sender_identity": "bot" if exact else None, + "sender_evidence_source": "message_readback" if exact else None, + } + + +__all__ = [ + "GoalChannelMessageDeliverySession", + "goal_channel_delivery_route", + "resolve_bound_goal_channel", +] diff --git a/loopx/extensions/lark/goal_channel_payload.py b/loopx/extensions/lark/goal_channel_payload.py new file mode 100644 index 0000000000..78cfa6411f --- /dev/null +++ b/loopx/extensions/lark/goal_channel_payload.py @@ -0,0 +1,527 @@ +from __future__ import annotations + +import hashlib +import json +import re +from collections.abc import Mapping +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from ...control_plane.todos.contract import normalize_todo_decision_scope +from ...todos import add_goal_todo, complete_goal_todo, list_goal_todos +from .goal_channel_contracts import operation_packet +from .goal_channel_delivery_contract import ( + goal_channel_binding_digest, + goal_channel_delivery_route, +) +from .goal_channel_message_delivery import ( + GoalChannelMessageDeliverySession, + resolve_bound_goal_channel, +) +from .outbound import normalize_lark_outbound_text +from .presentation.kanban import CommandRunner, default_subprocess_runner +from .presentation.message_card import build_lark_markdown_reply_card +from .private_json import write_private_json_atomic + + +FROZEN_PAYLOAD_REQUEST_SCHEMA = "goal_channel_frozen_payload_request_v0" +FROZEN_PAYLOAD_RECEIPT_SCHEMA = "goal_channel_frozen_payload_receipt_v0" +_RECEIPT_ID_RE = re.compile(r"^gcp_[0-9a-f]{24}$") +_TOKEN_RE = re.compile(r"^[a-z][a-z0-9_.:-]{1,127}$") +_DIGEST_RE = re.compile(r"^sha256:[0-9a-f]{64}$") + + +def _canonical_digest(value: object) -> str: + encoded = json.dumps( + value, ensure_ascii=False, sort_keys=True, separators=(",", ":") + ).encode("utf-8") + return "sha256:" + hashlib.sha256(encoded).hexdigest() + + +def _required_text(value: object, label: str, *, maximum: int) -> str: + text = str(value or "").strip() + if not text: + raise ValueError(f"{label} is required") + if len(text) > maximum: + raise ValueError(f"{label} exceeds {maximum} characters") + return text + + +def _token(value: object, label: str) -> str: + token = str(value or "").strip().lower() + if not _TOKEN_RE.fullmatch(token): + raise ValueError(f"{label} must be a public-safe opaque token") + return token + + +def _decision_scope_text(scope: Mapping[str, Any]) -> str: + return f"{scope['kind']}:{scope['granularity']}:{scope['scope_key']}" + + +def _normalized_request(request: Mapping[str, Any]) -> dict[str, Any]: + allowed = { + "schema_version", + "capability_id", + "payload_ref", + "title", + "markdown", + "footer", + "decision_scope", + "public_safe", + } + extra = sorted(set(request) - allowed) + if extra: + raise ValueError(f"frozen payload request contains unsupported fields: {extra}") + if request.get("schema_version") != FROZEN_PAYLOAD_REQUEST_SCHEMA: + raise ValueError(f"request must use {FROZEN_PAYLOAD_REQUEST_SCHEMA}") + if request.get("public_safe") is not True: + raise ValueError( + "producing capability must attest that the frozen payload is public-safe" + ) + scope = normalize_todo_decision_scope(request.get("decision_scope")) + if ( + scope is None + or scope["kind"] != "public_claim" + or scope["granularity"] != "action" + or "*" in scope["scope_key"] + ): + raise ValueError( + "frozen Goal Channel payload requires a public_claim:action decision scope" + ) + title = _required_text(request.get("title"), "title", maximum=72) + footer = _required_text(request.get("footer"), "footer", maximum=96) + markdown = normalize_lark_outbound_text( + request.get("markdown"), limit=3600, preserve_format=True + ) + if re.search(r"<\s*at\b", markdown, re.IGNORECASE): + raise ValueError("frozen Goal Channel payload must not contain mentions") + card = build_lark_markdown_reply_card( + markdown, title=title, footer=footer, max_markdown_chars=3600 + ) + return { + "capability_id": _token(request.get("capability_id"), "capability_id"), + "payload_ref": _token(request.get("payload_ref"), "payload_ref"), + "title": title, + "markdown": markdown, + "footer": footer, + "decision_scope": scope, + "card": card, + "payload_digest": _canonical_digest(card), + } + + +def _receipt_identity( + *, + goal_id: str, + request: Mapping[str, Any], + binding_digest: str, + agent_id: str, +) -> str: + digest = _canonical_digest( + { + "goal_id": goal_id, + "capability_id": request["capability_id"], + "payload_ref": request["payload_ref"], + "payload_digest": request["payload_digest"], + "decision_scope": request["decision_scope"], + "binding_digest": binding_digest, + "agent_id": agent_id, + } + ) + return "gcp_" + digest.removeprefix("sha256:")[:24] + + +def _receipt_path(runtime_root: Path, goal_id: str, receipt_id: str) -> Path: + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,159}", goal_id): + raise ValueError("goal_id must be a stable LoopX Goal id") + if not _RECEIPT_ID_RE.fullmatch(receipt_id): + raise ValueError("receipt_id must be a Goal Channel frozen payload id") + return ( + runtime_root + / "goals" + / goal_id + / "goal_channel_payloads" + / f"{receipt_id}.json" + ) + + +def _read_receipt(runtime_root: Path, goal_id: str, receipt_id: str) -> dict[str, Any]: + path = _receipt_path(runtime_root, goal_id, receipt_id) + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise ValueError("Goal Channel frozen payload receipt is unavailable") from exc + if ( + not isinstance(payload, dict) + or payload.get("schema_version") != FROZEN_PAYLOAD_RECEIPT_SCHEMA + or payload.get("receipt_id") != receipt_id + or payload.get("goal_id") != goal_id + ): + raise ValueError("Goal Channel frozen payload receipt is invalid") + card = payload.get("card") + scope = normalize_todo_decision_scope(payload.get("decision_scope")) + if ( + not isinstance(card, Mapping) + or _canonical_digest(card) != payload.get("payload_digest") + or not _DIGEST_RE.fullmatch(str(payload.get("payload_digest") or "")) + or not _DIGEST_RE.fullmatch(str(payload.get("binding_digest") or "")) + or scope is None + or scope["kind"] != "public_claim" + or scope["granularity"] != "action" + or payload.get("status") not in {"approval_pending", "satisfied"} + or _receipt_identity( + goal_id=goal_id, + request=payload, + binding_digest=str(payload.get("binding_digest") or ""), + agent_id=str(payload.get("agent_id") or ""), + ) + != receipt_id + ): + raise ValueError("Goal Channel frozen payload receipt content drifted") + return payload + + +def prepare_goal_channel_payload( + request: Mapping[str, Any], + *, + registry_path: Path, + runtime_root: Path, + binding_path: Path, + target_path: Path, + goal_id: str, + agent_id: str, + execute: bool = False, +) -> dict[str, Any]: + """Freeze one capability-owned public payload behind an exact user gate.""" + + normalized = _normalized_request(request) + binding = resolve_bound_goal_channel( + binding_path=binding_path, + target_path=target_path, + goal_id=goal_id, + agent_id=agent_id, + ) + binding_digest = goal_channel_binding_digest(binding) + receipt_id = _receipt_identity( + goal_id=goal_id, + request=normalized, + binding_digest=binding_digest, + agent_id=agent_id, + ) + receipt_path = _receipt_path(runtime_root, goal_id, receipt_id) + if receipt_path.exists(): + receipt = _read_receipt(runtime_root, goal_id, receipt_id) + return operation_packet( + ok=True, + goal_id=goal_id, + operation="prepare_payload", + execute=execute, + status=str(receipt["status"]), + public_summary="reused the exact frozen Goal Channel payload", + idempotency_key=receipt_id, + receipt_id=receipt_id, + details={ + "capability_id": receipt["capability_id"], + "payload_digest": receipt["payload_digest"], + "decision_scope": _decision_scope_text(receipt["decision_scope"]), + "delivery_todo_id": receipt["delivery_todo_id"], + "approval_todo_id": receipt["approval_todo_id"], + "already_prepared": True, + }, + ) + + scope_text = _decision_scope_text(normalized["decision_scope"]) + digest_suffix = normalized["payload_digest"].removeprefix("sha256:")[:16] + delivery = add_goal_todo( + registry_path=registry_path, + goal_id=goal_id, + role="agent", + text=f"[P0] Deliver frozen Goal Channel payload {receipt_id}.", + status="blocked", + note=( + "Use only the frozen private receipt and the unchanged project_bot " + "Goal Channel binding; require exact provider-native readback." + ), + task_class="advancement_task", + action_kind="deliver_goal_channel_payload", + task_domain="provider_delivery", + capability_binding_ref=f"goal-channel:g{digest_suffix}", + required_write_scopes=["goal_channel/lark/messages"], + required_capabilities=["network", "lark_bot_message_write"], + target_capabilities=[normalized["capability_id"], "goal_channel"], + required_decision_scopes=[scope_text], + claimed_by=agent_id, + agent_id=agent_id, + runtime_root_arg=str(runtime_root), + dry_run=not execute, + ) + gate = add_goal_todo( + registry_path=registry_path, + goal_id=goal_id, + role="user", + text=( + "Approve the exact frozen public payload " + f"{receipt_id} ({normalized['payload_digest']}) for Goal Channel delivery." + ), + note=( + "Approval covers only this frozen card digest and current Goal Channel " + "binding; rejection or cancellation keeps delivery blocked." + ), + task_class="user_gate", + action_kind="approve_goal_channel_payload", + decision_scope=scope_text, + bound_agent=agent_id, + blocks_agent=agent_id, + unblocks_todo_id=str(delivery["todo_id"]), + agent_id=agent_id, + runtime_root_arg=str(runtime_root), + dry_run=not execute, + ) + receipt = { + "schema_version": FROZEN_PAYLOAD_RECEIPT_SCHEMA, + "receipt_id": receipt_id, + "goal_id": goal_id, + "capability_id": normalized["capability_id"], + "payload_ref": normalized["payload_ref"], + "payload_digest": normalized["payload_digest"], + "decision_scope": normalized["decision_scope"], + "binding_digest": binding_digest, + "agent_id": agent_id, + "created_at": datetime.now(timezone.utc).isoformat(), + "title": normalized["title"], + "markdown": normalized["markdown"], + "footer": normalized["footer"], + "card": normalized["card"], + "delivery_todo_id": delivery["todo_id"], + "approval_todo_id": gate["todo_id"], + "status": "approval_pending", + "delivery": None, + } + if execute: + write_private_json_atomic(receipt_path, receipt) + return operation_packet( + ok=True, + goal_id=goal_id, + operation="prepare_payload", + execute=execute, + status="approval_pending" if execute else "pending_execution", + public_summary=( + "froze one Goal Channel payload and created its exact approval gate" + if execute + else "validated one Goal Channel payload preparation" + ), + idempotency_key=receipt_id, + receipt_id=receipt_id, + details={ + "capability_id": normalized["capability_id"], + "payload_digest": normalized["payload_digest"], + "decision_scope": scope_text, + "delivery_todo_id": delivery["todo_id"], + "approval_todo_id": gate["todo_id"], + "already_prepared": False, + }, + ) + + +def _todo( + *, registry_path: Path, runtime_root: Path, goal_id: str, todo_id: str +) -> dict[str, Any] | None: + payload = list_goal_todos( + registry_path=registry_path, + goal_id=goal_id, + todo_id=todo_id, + runtime_root_arg=str(runtime_root), + ) + todo = payload.get("todo") + return dict(todo) if isinstance(todo, Mapping) else None + + +def _approval_verified( + *, receipt: Mapping[str, Any], registry_path: Path, runtime_root: Path +) -> tuple[dict[str, Any], dict[str, Any]]: + goal_id = str(receipt["goal_id"]) + delivery = _todo( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=goal_id, + todo_id=str(receipt["delivery_todo_id"]), + ) + gate = _todo( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=goal_id, + todo_id=str(receipt["approval_todo_id"]), + ) + expected_scope = normalize_todo_decision_scope(receipt["decision_scope"]) + expected_binding_ref = ( + "goal-channel:g" + str(receipt["payload_digest"]).removeprefix("sha256:")[:16] + ) + agent_id = str(receipt["agent_id"]) + if delivery is None or gate is None or expected_scope is None: + raise ValueError("frozen Goal Channel approval lifecycle is unavailable") + if ( + gate.get("status") != "done" + or gate.get("decision_outcome") != "approve" + or normalize_todo_decision_scope(gate.get("decision_scope")) != expected_scope + or gate.get("unblocks_todo_id") != delivery.get("todo_id") + or gate.get("action_kind") != "approve_goal_channel_payload" + or gate.get("blocks_agent") != agent_id + or gate.get("bound_agent") != agent_id + or receipt["receipt_id"] not in str(gate.get("text") or "") + or delivery.get("status") not in {"open", "done"} + or delivery.get("required_decision_scopes") + or delivery.get("action_kind") != "deliver_goal_channel_payload" + or delivery.get("claimed_by") != agent_id + or delivery.get("capability_binding_ref") != expected_binding_ref + or receipt["receipt_id"] not in str(delivery.get("text") or "") + ): + raise ValueError("frozen Goal Channel payload lacks exact approval") + return delivery, gate + + +def deliver_goal_channel_payload( + *, + receipt_id: str, + registry_path: Path, + runtime_root: Path, + binding_path: Path, + target_path: Path, + goal_id: str, + execute: bool = False, + runner: CommandRunner = default_subprocess_runner, +) -> dict[str, Any]: + """Deliver one approved frozen payload with exact dedupe and readback.""" + + receipt = _read_receipt(runtime_root, goal_id, receipt_id) + delivery_todo, _gate = _approval_verified( + receipt=receipt, registry_path=registry_path, runtime_root=runtime_root + ) + agent_id = str(receipt["agent_id"]) + binding = resolve_bound_goal_channel( + binding_path=binding_path, + target_path=target_path, + goal_id=goal_id, + agent_id=agent_id, + ) + if goal_channel_binding_digest(binding) != receipt["binding_digest"]: + raise ValueError("Goal Channel binding drifted after payload approval") + route = goal_channel_delivery_route(goal_id, lambda _goal_id: binding) + idempotency_key = _canonical_digest( + { + "goal_id": goal_id, + "payload_digest": receipt["payload_digest"], + "binding_digest": receipt["binding_digest"], + } + ) + if not execute: + return operation_packet( + ok=True, + goal_id=goal_id, + operation="deliver_payload", + execute=False, + status="pending_execution", + public_summary="validated one approved frozen Goal Channel payload", + idempotency_key=idempotency_key, + receipt_id=receipt_id, + details={ + "capability_id": receipt["capability_id"], + "payload_digest": receipt["payload_digest"], + "approval_verified": True, + }, + ) + + def resolve_current() -> Mapping[str, Any]: + return resolve_bound_goal_channel( + binding_path=binding_path, + target_path=target_path, + goal_id=goal_id, + agent_id=agent_id, + ) + + session = GoalChannelMessageDeliverySession( + goal_id=goal_id, + binding=binding, + history_start_at=str(receipt["created_at"]), + resolve_current_binding=resolve_current, + runner=runner, + ) + if session.verify(route) is not True: + raise ValueError("Goal Channel sender identity could not be verified") + sent = dict(session.send(receipt["card"], idempotency_key, route)) + message_id = str(sent.get("message_id") or "") + observed = dict(session.readback(message_id)) + verified = bool( + observed.get("verified") is True + and observed.get("message_id") == message_id + and observed.get("chat_id") == route["chat_id"] + and observed.get("sender_app_id") == route["bot_app_id"] + and observed.get("sender_identity") == "bot" + and observed.get("sender_evidence_source") == "message_readback" + ) + if not verified: + return operation_packet( + ok=False, + goal_id=goal_id, + operation="deliver_payload", + execute=True, + status="readback_unverified", + public_summary="Goal Channel delivery did not satisfy exact native readback", + external_write_performed=sent.get("external_write_performed") is True, + readback_verified=False, + idempotency_key=idempotency_key, + receipt_id=receipt_id, + blocker="readback_unverified", + ) + if delivery_todo.get("status") != "done": + completed = complete_goal_todo( + registry_path=registry_path, + goal_id=goal_id, + runtime_root_arg=str(runtime_root), + todo_id=str(delivery_todo["todo_id"]), + role="agent", + claimed_by=agent_id, + agent_id=agent_id, + no_followup=True, + evidence=( + "Exact frozen Goal Channel payload delivered with provider-native " + f"sender, chat, and content readback ({receipt['payload_digest']})." + ), + ) + if completed.get("ok") is not True: + raise ValueError("Goal Channel delivery Todo completion failed") + receipt["status"] = "satisfied" + receipt["delivery"] = { + "message_id": message_id, + "delivered_at": datetime.now(timezone.utc).isoformat(), + "readback_verified": True, + "semantic_dedupe_status": sent.get("semantic_dedupe_status"), + } + write_private_json_atomic(_receipt_path(runtime_root, goal_id, receipt_id), receipt) + return operation_packet( + ok=True, + goal_id=goal_id, + operation="deliver_payload", + execute=True, + status="satisfied", + public_summary="delivered one approved frozen Goal Channel payload with exact readback", + external_write_performed=sent.get("external_write_performed") is True, + readback_verified=True, + idempotency_key=idempotency_key, + receipt_id=receipt_id, + details={ + "capability_id": receipt["capability_id"], + "payload_digest": receipt["payload_digest"], + "approval_verified": True, + "delivery_todo_completed": True, + "semantic_dedupe_status": sent.get("semantic_dedupe_status"), + }, + ) + + +__all__ = [ + "FROZEN_PAYLOAD_RECEIPT_SCHEMA", + "FROZEN_PAYLOAD_REQUEST_SCHEMA", + "deliver_goal_channel_payload", + "prepare_goal_channel_payload", +] diff --git a/loopx/extensions/lark/periodic_report_delivery.py b/loopx/extensions/lark/periodic_report_delivery.py index 9debd1a635..0a2019d83e 100644 --- a/loopx/extensions/lark/periodic_report_delivery.py +++ b/loopx/extensions/lark/periodic_report_delivery.py @@ -1,8 +1,7 @@ from __future__ import annotations import hashlib -import json -from collections.abc import Callable, Mapping +from collections.abc import Mapping from datetime import datetime, timezone from pathlib import Path from typing import Any @@ -33,23 +32,12 @@ goal_from_registry, read_goal_channel_binding, ) +from .goal_channel_message_delivery import GoalChannelMessageDeliverySession from .goal_channel_targets import ( default_goal_channel_target_path, goal_channel_target_for_name, read_goal_channel_targets, ) -from .goal_channel_transport import ( - auth_verified, - bot_membership_verified, - call, - chat_verified, - contains_exact_field, - find_first_string, - json_payload, - lark_args, - MESSAGE_ID_PATTERN, - verified_app_id, -) from .presentation.kanban import CommandRunner, default_subprocess_runner from .presentation.periodic_report import periodic_report_lark_sink_adapter from ...registry import read_json @@ -212,120 +200,6 @@ def _resolved_goal_channel_binding( return resolved -def _find_message(value: Any, message_id: str) -> Mapping[str, Any] | None: - if isinstance(value, Mapping): - if str(value.get("message_id") or "") == message_id: - return value - for child in value.values(): - found = _find_message(child, message_id) - if found is not None: - return found - elif isinstance(value, list): - for child in value: - found = _find_message(child, message_id) - if found is not None: - return found - return None - - -def _message_rows(value: Any) -> list[Mapping[str, Any]]: - rows: list[Mapping[str, Any]] = [] - if isinstance(value, Mapping): - message_id = str(value.get("message_id") or "") - if MESSAGE_ID_PATTERN.fullmatch(message_id): - rows.append(value) - for child in value.values(): - rows.extend(_message_rows(child)) - elif isinstance(value, list): - for child in value: - rows.extend(_message_rows(child)) - return rows - - -def _history_is_complete(value: Mapping[str, Any]) -> bool: - completeness: list[bool] = [] - for candidate in (value, value.get("data")): - if not isinstance(candidate, Mapping): - continue - if isinstance(candidate.get("has_more"), bool): - completeness.append(candidate["has_more"] is False) - meta = value.get("meta") - pagination = meta.get("pagination") if isinstance(meta, Mapping) else None - if isinstance(pagination, Mapping) and isinstance(pagination.get("complete"), bool): - completeness.append(pagination["complete"] is True) - return bool(completeness) and all(completeness) - - -def _message_card(value: Mapping[str, Any]) -> Mapping[str, Any] | None: - body = value.get("body") - content = body.get("content") if isinstance(body, Mapping) else None - if isinstance(content, Mapping): - return content - if not isinstance(content, str): - return None - try: - parsed = json.loads(content) - except json.JSONDecodeError: - return None - return parsed if isinstance(parsed, Mapping) else None - - -def _normalized_card_text(card: Mapping[str, Any]) -> str | None: - """Match the lossless interactive-card projection returned by new CLIs.""" - - header = card.get("header") - elements = card.get("elements") - if not isinstance(header, Mapping) or not isinstance(elements, list): - return None - title = header.get("title") - title = title.get("content") if isinstance(title, Mapping) else None - if not isinstance(title, str) or not elements: - return None - first = elements[0] - first = first if isinstance(first, Mapping) else {} - text = first.get("text") - markdown = text.get("content") if isinstance(text, Mapping) else None - if not isinstance(markdown, str): - return None - footer = None - if len(elements) == 3 and elements[1] == {"tag": "hr"}: - note = elements[2] - note_elements = note.get("elements") if isinstance(note, Mapping) else None - if isinstance(note_elements, list) and len(note_elements) == 1: - note_text = note_elements[0] - footer = ( - note_text.get("content") if isinstance(note_text, Mapping) else None - ) - lines = [f'', markdown] - if isinstance(footer, str) and footer: - lines.extend(["---", f"📝 {footer}"]) - lines.append("") - return "\n".join(lines) - - -def _message_card_matches( - value: Mapping[str, Any], expected: Mapping[str, Any] | None -) -> bool: - if expected is None: - return False - if _message_card(value) == expected: - return True - content = value.get("content") - return isinstance(content, str) and content == _normalized_card_text(expected) - - -def _message_sender(value: Mapping[str, Any]) -> tuple[str, str]: - sender = value.get("sender") - sender = sender if isinstance(sender, Mapping) else {} - sender_type = str( - sender.get("sender_type") or value.get("sender_type") or "" - ).strip() - sender_id = str( - sender.get("id") or sender.get("sender_id") or value.get("sender_id") or "" - ).strip() - return sender_type, sender_id - - def _validate_extension_activation(value: Mapping[str, Any]) -> None: permissions = value.get("required_permissions") if ( @@ -428,224 +302,6 @@ def _normalized_delivery_request( return generation, authority, sink_id, idempotency_key, announcements, artifacts[0] -class _GoalChannelDeliverySession: - def __init__( - self, - *, - goal_id: str, - binding: Mapping[str, Any], - history_start_at: str, - resolve_current_binding: Callable[[], Mapping[str, Any]], - runner: CommandRunner, - ) -> None: - self.goal_id = goal_id - self.binding = dict(binding) - self.history_start_at = history_start_at - self.resolve_current_binding = resolve_current_binding - self.runner = runner - self.route: dict[str, Any] = {} - self.expected_cards: dict[str, list[dict[str, Any]]] = {} - - def _existing_message( - self, - card: Mapping[str, Any], - route: Mapping[str, Any], - ) -> str | None: - result = call( - self.runner, - lark_args( - cli_bin=str(route["cli_bin"]), - profile=str(route["sender_profile"]), - tail=[ - "im", - "+chat-messages-list", - "--chat-id", - str(route["chat_id"]), - "--start", - self.history_start_at, - "--order", - "asc", - "--page-all", - "--page-limit", - "1000", - "--as", - "bot", - "--no-reactions", - "--format", - "json", - ], - ), - ) - payload = json_payload(result) - if result.get("returncode") != 0: - raise ValueError("Goal Channel periodic report dedupe readback failed") - for message in _message_rows(payload): - sender_type, sender_app_id = _message_sender(message) - if ( - message.get("deleted") is not True - and str(message.get("chat_id") or "") == route["chat_id"] - and sender_type == "app" - and sender_app_id == route["bot_app_id"] - and _message_card_matches(message, card) - ): - return str(message["message_id"]) - if not _history_is_complete(payload): - raise ValueError( - "Goal Channel periodic report dedupe history is incomplete" - ) - return None - - def resolve(self, requested_goal_id: str) -> Mapping[str, Any]: - if requested_goal_id != self.goal_id: - raise ValueError("Goal Channel delivery goal identity changed") - return self.binding - - def verify(self, route: Mapping[str, Any]) -> bool: - cli_bin = str(route["cli_bin"]) - profile = str(route["sender_profile"]) - app_id = str(route["bot_app_id"]) - chat_id = str(route["chat_id"]) - checks = ( - auth_verified( - runner=self.runner, - cli_bin=cli_bin, - profile=profile, - identity="bot", - expected_bot_name=str(route["bot_display_name"]), - ), - verified_app_id( - runner=self.runner, - cli_bin=cli_bin, - profile=profile, - ) - == app_id, - chat_verified( - runner=self.runner, - cli_bin=cli_bin, - profile=profile, - identity="bot", - chat_id=chat_id, - ), - bot_membership_verified( - runner=self.runner, - cli_bin=cli_bin, - profile=profile, - chat_id=chat_id, - app_id=app_id, - ), - ) - verified = all(checks) - if verified: - self.route = dict(route) - return verified - - def send( - self, - card: Mapping[str, Any], - key: str, - route: Mapping[str, Any], - ) -> Mapping[str, Any]: - current_binding = dict(self.resolve_current_binding()) - if current_binding != self.binding: - raise ValueError("periodic report Goal Channel binding drifted") - existing_message_id = self._existing_message(card, route) - if existing_message_id is not None: - self.expected_cards.setdefault(existing_message_id, []).append(dict(card)) - return { - "message_id": existing_message_id, - "semantic_dedupe_status": "existing_exact_message", - "external_write_performed": False, - } - result = call( - self.runner, - lark_args( - cli_bin=str(route["cli_bin"]), - profile=str(route["sender_profile"]), - tail=[ - "im", - "+messages-send", - "--chat-id", - str(route["chat_id"]), - "--content", - json.dumps(card, ensure_ascii=False, separators=(",", ":")), - "--msg-type", - "interactive", - "--idempotency-key", - f"loopx-{hashlib.sha256(key.encode()).hexdigest()[:32]}", - "--as", - "bot", - "--format", - "json", - ], - ), - ) - message_id = find_first_string( - json_payload(result), {"message_id"}, MESSAGE_ID_PATTERN - ) - if result.get("returncode") != 0 or not message_id: - raise ValueError("Goal Channel periodic report send failed") - self.expected_cards.setdefault(message_id, []).append(dict(card)) - return { - "message_id": message_id, - "semantic_dedupe_status": "no_existing_exact_message", - "external_write_performed": True, - } - - def readback(self, message_id: str) -> Mapping[str, Any]: - result = call( - self.runner, - lark_args( - cli_bin=str(self.route["cli_bin"]), - profile=str(self.route["sender_profile"]), - tail=[ - "im", - "+messages-mget", - "--message-ids", - message_id, - "--as", - "bot", - "--no-reactions", - "--format", - "json", - ], - ), - ) - message = _find_message(json_payload(result), message_id) - sender_type, sender_app_id = ( - _message_sender(message) if message is not None else ("", "") - ) - expected_card = (self.expected_cards.get(message_id) or [None]).pop(0) - exact = bool( - result.get("returncode") == 0 - and message is not None - and contains_exact_field(message, "chat_id", str(self.route["chat_id"])) - and _message_card_matches(message, expected_card) - and sender_type == "app" - and sender_app_id == self.route["bot_app_id"] - and auth_verified( - runner=self.runner, - cli_bin=str(self.route["cli_bin"]), - profile=str(self.route["sender_profile"]), - identity="bot", - expected_bot_name=str(self.route["bot_display_name"]), - ) - and verified_app_id( - runner=self.runner, - cli_bin=str(self.route["cli_bin"]), - profile=str(self.route["sender_profile"]), - ) - == self.route["bot_app_id"] - ) - return { - "verified": exact, - "message_id": message_id, - "chat_id": self.route["chat_id"] if exact else None, - "sender_app_id": sender_app_id if exact else None, - "sender_identity": "bot" if exact else None, - "sender_evidence_source": "message_readback" if exact else None, - } - - def _delivery_status(*, satisfied: bool, execute: bool) -> str: if satisfied: return "satisfied" @@ -679,7 +335,7 @@ def deliver_periodic_report_to_goal_channel( goal_id=goal_id, expected_authority=authority, ) - session = _GoalChannelDeliverySession( + session = GoalChannelMessageDeliverySession( goal_id=goal_id, binding=binding, history_start_at=str(generation["document"]["generated_at"]), diff --git a/loopx/extensions/lark/presentation/periodic_report.py b/loopx/extensions/lark/presentation/periodic_report.py index 757e9ea5f6..6445c990c6 100644 --- a/loopx/extensions/lark/presentation/periodic_report.py +++ b/loopx/extensions/lark/presentation/periodic_report.py @@ -22,6 +22,7 @@ _normalize_periodic_report_release_readback, ) from ....capabilities.periodic_report.core import _reject_raw_keys +from ..goal_channel_delivery_contract import goal_channel_delivery_route from .message_card import build_lark_markdown_reply_card LarkSendEffect = Callable[ @@ -43,10 +44,6 @@ r"^]*>[^<>]*$", re.IGNORECASE, ) -_GOAL_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$") -_LARK_CHAT_ID_RE = re.compile(r"^oc_[A-Za-z0-9_-]+$") -_LARK_APP_ID_RE = re.compile(r"^cli_[A-Za-z0-9_-]+$") -_LARK_PROFILE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$") _CALLER_IDENTITY_OVERRIDE_KEYS = frozenset( { "bot_app_id", @@ -116,50 +113,7 @@ def _goal_channel_delivery_route( goal_id: object, resolve_goal_channel: LarkGoalChannelResolver, ) -> dict[str, Any]: - safe_goal_id = _required_text(goal_id, "goal_id") - if not _GOAL_ID_RE.fullmatch(safe_goal_id): - raise ValueError("goal_id must be a stable LoopX Goal id") - binding = dict(resolve_goal_channel(safe_goal_id)) - channel = binding.get("channel") - identity = binding.get("identity") - if ( - binding.get("goal_id") != safe_goal_id - or binding.get("provider") != "lark" - or binding.get("enabled") is not True - or not isinstance(channel, Mapping) - or not isinstance(identity, Mapping) - ): - raise ValueError( - "periodic report delivery requires the enabled Lark Goal Channel binding" - ) - chat_id = str(channel.get("chat_id") or "").strip() - sender_profile = str(identity.get("sender_profile") or "").strip() - sender_identity = str(identity.get("sender_identity") or "").strip() - bot_app_id = str(identity.get("bot_app_id") or "").strip() - bot_display_name = str(identity.get("bot_display_name") or "").strip() - cli_bin = str(identity.get("cli_bin") or "lark-cli").strip() - if ( - identity.get("mode") != "project_bot" - or sender_identity != "bot" - or not _LARK_CHAT_ID_RE.fullmatch(chat_id) - or not _LARK_PROFILE_RE.fullmatch(sender_profile) - or sender_profile.lower() == "default" - or not _LARK_APP_ID_RE.fullmatch(bot_app_id) - or not bot_display_name - or not cli_bin - ): - raise ValueError( - "periodic report delivery requires a complete project_bot Goal Channel identity" - ) - return { - "goal_id": safe_goal_id, - "chat_id": chat_id, - "sender_profile": sender_profile, - "sender_identity": sender_identity, - "bot_app_id": bot_app_id, - "bot_display_name": bot_display_name, - "cli_bin": cli_bin, - } + return goal_channel_delivery_route(goal_id, resolve_goal_channel) def _https_url(value: object, label: str) -> str: diff --git a/loopx/extensions/lark/provider.py b/loopx/extensions/lark/provider.py index 55bccc9b01..03183b5fd8 100644 --- a/loopx/extensions/lark/provider.py +++ b/loopx/extensions/lark/provider.py @@ -28,8 +28,10 @@ ), "loopx.extensions.lark.reviewer_notification": ("lark_reviewer_notification_sink",), "loopx.extensions.lark.goal_channel": ( + "deliver_goal_channel_payload", "doctor_lark_goal_channel", "notify_lark_goal_channel_gate", + "prepare_goal_channel_payload", "setup_lark_goal_channel", "sync_lark_goal_channel", ), diff --git a/tests/extensions/test_goal_channel_payload.py b/tests/extensions/test_goal_channel_payload.py new file mode 100644 index 0000000000..45fab5780f --- /dev/null +++ b/tests/extensions/test_goal_channel_payload.py @@ -0,0 +1,407 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from loopx.extensions.lark.goal_channel_contracts import ( + GOAL_CHANNEL_BINDING_SCHEMA_VERSION, + read_goal_channel_binding, + write_goal_channel_binding, +) +from loopx.extensions.lark.goal_channel_payload import ( + FROZEN_PAYLOAD_REQUEST_SCHEMA, + deliver_goal_channel_payload, + prepare_goal_channel_payload, +) +from loopx.extensions.lark.goal_channel_targets import add_lark_goal_channel_target +from loopx.status import parse_active_state_todos +from loopx.todos import complete_goal_todo + + +GOAL_ID = "goal-public-fixture" +AGENT_ID = "codex-public-delivery" +CHAT_ID = "oc_public_fixture" +APP_ID = "cli_public_fixture" +SCOPE = "public_claim:action:publish-public-fixture" + + +def _fixture(tmp_path: Path) -> tuple[Path, Path, Path, Path]: + project = tmp_path / "project" + project.mkdir() + state = project / "ACTIVE_GOAL_STATE.md" + state.write_text( + "---\n" + f"goal_id: {GOAL_ID}\n" + "updated_at: 2026-09-12T00:00:00+00:00\n" + "---\n\n" + "## User Todo\n\n" + "## Agent Todo\n", + encoding="utf-8", + ) + runtime_root = tmp_path / "runtime" + registry_path = project / ".loopx" / "registry.json" + registry_path.parent.mkdir() + registry_path.write_text( + json.dumps( + { + "common_runtime_root": str(runtime_root), + "goals": [ + { + "id": GOAL_ID, + "repo": str(project), + "state_file": "ACTIVE_GOAL_STATE.md", + "adapter": {"kind": "read_only_project_map_v0"}, + "coordination": { + "agent_model": "peer_v1", + "registered_agents": [AGENT_ID], + }, + } + ], + } + ), + encoding="utf-8", + ) + target_path = runtime_root / "goal-channel-targets.json" + add_lark_goal_channel_target( + target_path=target_path, + target_name="public-route", + chat_id=CHAT_ID, + chat_name="Public Fixture", + identity_mode="project_bot", + sender_profile="project-reporter", + sender_identity="bot", + bot_app_id=APP_ID, + bot_display_name="Project Reporter", + cli_bin="lark-cli", + execute=True, + ) + binding_path = registry_path.parent / "goal-channel.json" + _write_binding(binding_path) + return registry_path, runtime_root, binding_path, target_path + + +def _write_binding(binding_path: Path, *, target_ref: str = "public-route") -> None: + write_goal_channel_binding( + binding_path, + { + "schema_version": GOAL_CHANNEL_BINDING_SCHEMA_VERSION, + "bindings": { + GOAL_ID: { + "goal_id": GOAL_ID, + "provider": "lark", + "enabled": True, + "target_ref": target_ref, + "channel": {}, + "identity": {}, + } + }, + }, + ) + + +def _request( + *, markdown: str = "Validated fact.\n\nRecommended next research step." +) -> dict[str, Any]: + return { + "schema_version": FROZEN_PAYLOAD_REQUEST_SCHEMA, + "capability_id": "example-capability", + "payload_ref": "example-result-v1", + "title": "Public research result", + "markdown": markdown, + "footer": "LoopX verified result", + "decision_scope": SCOPE, + "public_safe": True, + } + + +def _prepare_and_approve( + registry_path: Path, runtime_root: Path, binding_path: Path, target_path: Path +) -> dict[str, Any]: + prepared = prepare_goal_channel_payload( + _request(), + registry_path=registry_path, + runtime_root=runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + execute=True, + ) + complete_goal_todo( + registry_path=registry_path, + runtime_root_arg=str(runtime_root), + goal_id=GOAL_ID, + todo_id=prepared["details"]["approval_todo_id"], + role="user", + decision_outcome="approve", + evidence="owner approved the exact frozen public payload", + ) + return prepared + + +def _runner(calls: list[list[str]]): + sent_cards: dict[str, dict[str, Any]] = {} + + def run( + args: list[str], _cwd: Path | None, _timeout: float | None + ) -> dict[str, Any]: + calls.append(args) + if "auth" in args and "status" in args: + payload = { + "ok": True, + "appId": APP_ID, + "identities": { + "bot": { + "available": True, + "verified": True, + "appName": "Project Reporter", + } + }, + } + elif "chats" in args and "get" in args: + payload = {"ok": True, "data": {"chat_id": CHAT_ID}} + elif "+chat-members-list" in args: + payload = {"ok": True, "data": {"bots": [{"app_id": APP_ID}]}} + elif "+chat-messages-list" in args: + payload = { + "ok": True, + "has_more": False, + "messages": [ + { + "message_id": message_id, + "chat_id": CHAT_ID, + "sender": {"sender_type": "app", "id": APP_ID}, + "deleted": False, + "body": {"content": json.dumps(card)}, + } + for message_id, card in sent_cards.items() + ], + } + elif "+messages-send" in args: + message_id = f"om_payload_fixture_{len(sent_cards) + 1}" + sent_cards[message_id] = json.loads(args[args.index("--content") + 1]) + payload = {"ok": True, "data": {"message_id": message_id}} + elif "+messages-mget" in args: + message_id = args[args.index("--message-ids") + 1] + payload = { + "ok": True, + "data": { + "items": [ + { + "message_id": message_id, + "chat_id": CHAT_ID, + "sender": {"sender_type": "app", "id": APP_ID}, + "body": {"content": json.dumps(sent_cards[message_id])}, + } + ] + }, + } + else: # pragma: no cover + raise AssertionError(args) + return {"returncode": 0, "stdout": json.dumps(payload), "stderr": ""} + + return run + + +def test_prepare_creates_blocked_successor_and_exact_user_gate(tmp_path: Path) -> None: + registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) + result = prepare_goal_channel_payload( + _request(), + registry_path=registry_path, + runtime_root=runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + execute=True, + ) + + assert result["status"] == "approval_pending" + state = registry_path.parent.parent / "ACTIVE_GOAL_STATE.md" + parsed = parse_active_state_todos( + state.read_text(encoding="utf-8"), item_limit=None + ) + delivery = next( + item + for item in parsed["agent_todos"]["items"] + if item["todo_id"] == result["details"]["delivery_todo_id"] + ) + gate = next( + item + for item in parsed["user_todos"]["items"] + if item["todo_id"] == result["details"]["approval_todo_id"] + ) + assert delivery["status"] == "blocked" + assert ( + delivery["required_decision_scopes"][0]["scope_key"] == "publish-public-fixture" + ) + assert gate["unblocks_todo_id"] == delivery["todo_id"] + assert gate["decision_scope"] == delivery["required_decision_scopes"][0] + assert "Validated fact" not in state.read_text(encoding="utf-8") + + +def test_prepare_preview_has_no_durable_write(tmp_path: Path) -> None: + registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) + state = registry_path.parent.parent / "ACTIVE_GOAL_STATE.md" + before = state.read_text(encoding="utf-8") + + result = prepare_goal_channel_payload( + _request(), + registry_path=registry_path, + runtime_root=runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + execute=False, + ) + + assert result["status"] == "pending_execution" + assert state.read_text(encoding="utf-8") == before + assert not (runtime_root / "goals" / GOAL_ID / "goal_channel_payloads").exists() + + +def test_delivery_fails_closed_before_exact_approval(tmp_path: Path) -> None: + registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) + prepared = prepare_goal_channel_payload( + _request(), + registry_path=registry_path, + runtime_root=runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + execute=True, + ) + calls: list[list[str]] = [] + + with pytest.raises(ValueError, match="lacks exact approval"): + deliver_goal_channel_payload( + receipt_id=prepared["receipt_id"], + registry_path=registry_path, + runtime_root=runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=GOAL_ID, + execute=True, + runner=_runner(calls), + ) + + assert calls == [] + + +def test_approved_delivery_is_verified_and_exact_replay_is_deduped( + tmp_path: Path, +) -> None: + registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) + prepared = _prepare_and_approve( + registry_path, runtime_root, binding_path, target_path + ) + calls: list[list[str]] = [] + runner = _runner(calls) + + first = deliver_goal_channel_payload( + receipt_id=prepared["receipt_id"], + registry_path=registry_path, + runtime_root=runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=GOAL_ID, + execute=True, + runner=runner, + ) + replay = deliver_goal_channel_payload( + receipt_id=prepared["receipt_id"], + registry_path=registry_path, + runtime_root=runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=GOAL_ID, + execute=True, + runner=runner, + ) + + assert first["status"] == replay["status"] == "satisfied" + assert first["external_write_performed"] is True + assert replay["external_write_performed"] is False + assert replay["details"]["semantic_dedupe_status"] == "existing_exact_message" + assert len([args for args in calls if "+messages-send" in args]) == 1 + + +def test_approved_payload_and_route_drift_fail_before_send(tmp_path: Path) -> None: + registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) + prepared = _prepare_and_approve( + registry_path, runtime_root, binding_path, target_path + ) + receipt_path = ( + runtime_root + / "goals" + / GOAL_ID + / "goal_channel_payloads" + / f"{prepared['receipt_id']}.json" + ) + receipt = json.loads(receipt_path.read_text(encoding="utf-8")) + receipt["card"]["header"]["title"]["content"] = "Changed after approval" + receipt_path.write_text(json.dumps(receipt), encoding="utf-8") + calls: list[list[str]] = [] + with pytest.raises(ValueError, match="content drifted"): + deliver_goal_channel_payload( + receipt_id=prepared["receipt_id"], + registry_path=registry_path, + runtime_root=runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=GOAL_ID, + execute=True, + runner=_runner(calls), + ) + assert calls == [] + + receipt_path.unlink() + prepared = _prepare_and_approve( + registry_path, runtime_root, binding_path, target_path + ) + binding = read_goal_channel_binding(binding_path) + binding["bindings"][GOAL_ID]["enabled"] = False + write_goal_channel_binding(binding_path, binding) + with pytest.raises(ValueError, match="enabled Lark Goal Channel binding"): + deliver_goal_channel_payload( + receipt_id=prepared["receipt_id"], + registry_path=registry_path, + runtime_root=runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=GOAL_ID, + execute=True, + runner=_runner(calls), + ) + assert calls == [] + + +def test_prepare_rejects_non_public_scope_and_mentions(tmp_path: Path) -> None: + registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) + request = _request() + request["decision_scope"] = "write_scope:action:publish-public-fixture" + with pytest.raises(ValueError, match="public_claim:action"): + prepare_goal_channel_payload( + request, + registry_path=registry_path, + runtime_root=runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + ) + with pytest.raises(ValueError, match="mention"): + prepare_goal_channel_payload( + _request(markdown='Someone'), + registry_path=registry_path, + runtime_root=runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + ) diff --git a/tests/extensions/test_lark_goal_channel.py b/tests/extensions/test_lark_goal_channel.py index 1726ae4a7c..cd505ba107 100644 --- a/tests/extensions/test_lark_goal_channel.py +++ b/tests/extensions/test_lark_goal_channel.py @@ -2105,6 +2105,99 @@ def capture_doctor(**kwargs: Any) -> dict[str, Any]: assert not (unrelated_two / ".loopx").exists() +def test_cli_prepare_payload_uses_source_registry_runtime( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + project = tmp_path / "canonical-project" + source_registry_path = project / ".loopx" / "registry.json" + source_registry_path.parent.mkdir(parents=True) + source_registry = _registry(project) + source_registry["goals"][0]["repo"] = str(project) + source_registry_path.write_text(json.dumps(source_registry), encoding="utf-8") + source_runtime = project / "runtime" + shared_runtime = tmp_path / "shared-runtime" + global_registry_path = shared_runtime / "registry.global.json" + global_registry_path.parent.mkdir(parents=True) + global_registry = { + **source_registry, + "registry_role": "global-local", + "common_runtime_root": str(shared_runtime), + } + global_registry["goals"] = [ + { + **source_registry["goals"][0], + "source_registry": str(source_registry_path), + } + ] + global_registry_path.write_text(json.dumps(global_registry), encoding="utf-8") + request_path = tmp_path / "payload.json" + request_path.write_text( + json.dumps({"schema_version": "goal_channel_frozen_payload_request_v0"}), + encoding="utf-8", + ) + captured: dict[str, Any] = {} + printed: dict[str, Any] = {} + + monkeypatch.setattr( + goal_channel_cli, + "resolve_extension_activation", + lambda *args, **kwargs: {"ok": True}, + ) + monkeypatch.setattr(goal_channel_cli, "_binding_target_name", lambda *args: "") + + def capture_prepare(request: dict[str, Any], **kwargs: Any) -> dict[str, Any]: + captured.update(kwargs) + captured["request"] = request + return { + "ok": True, + "goal_id": GOAL_ID, + "provider": "lark", + "operation": "prepare_payload", + "status": "pending_execution", + "execute": False, + "external_write_performed": False, + "readback_verified": False, + "public_summary": "validated", + } + + monkeypatch.setattr( + goal_channel_cli, "prepare_goal_channel_payload", capture_prepare + ) + result = goal_channel_cli.handle_goal_channel_command( + argparse.Namespace( + command="goal-channel", + goal_channel_command="prepare-payload", + goal_id=GOAL_ID, + agent_id="codex-public-delivery", + request_json=str(request_path), + binding_path=None, + target_path=None, + execute=False, + subcommand_format="json", + format=None, + ), + registry_path=global_registry_path, + runtime_root_arg=None, + print_payload=lambda payload, fmt, renderer: printed.update(payload), + output_format=lambda args: "json", + ) + + assert result == 0 + assert printed["ok"] is True + assert captured["registry_path"] == source_registry_path.resolve() + assert captured["runtime_root"] == source_runtime.resolve() + assert captured["binding_path"] == project / ".loopx" / "goal-channel.json" + assert ( + captured["target_path"] + == (source_runtime / "goal-channel-targets.json").resolve() + ) + assert captured["agent_id"] == "codex-public-delivery" + assert captured["request"] == { + "schema_version": "goal_channel_frozen_payload_request_v0" + } + + @pytest.mark.parametrize( ("remote_record_ids", "expected_ok", "expected_blocker"), [ diff --git a/tests/extensions/test_lark_goal_channel_targets.py b/tests/extensions/test_lark_goal_channel_targets.py index 039bdabb32..185b2587dc 100644 --- a/tests/extensions/test_lark_goal_channel_targets.py +++ b/tests/extensions/test_lark_goal_channel_targets.py @@ -154,10 +154,35 @@ def test_shared_target_cli_parses_add_setup_and_bounded_attach() -> None: "goal-second-public-fixture", ] ) + prepare = parser.parse_args( + [ + "goal-channel", + "prepare-payload", + "--goal-id", + GOAL_ID, + "--agent-id", + "codex-public-delivery", + "--request-json", + "payload.json", + ] + ) + deliver = parser.parse_args( + [ + "goal-channel", + "deliver-payload", + "--goal-id", + GOAL_ID, + "--receipt-id", + "gcp_0123456789abcdef01234567", + ] + ) assert target.goal_channel_target_command == "add" assert setup.target == "loopx-dev" assert attach.goal_id == [GOAL_ID, "goal-second-public-fixture"] + assert prepare.agent_id == "codex-public-delivery" + assert prepare.request_json == "payload.json" + assert deliver.receipt_id == "gcp_0123456789abcdef01234567" bounded = goal_channel_cli._attach_goals( registry={}, @@ -183,6 +208,7 @@ def test_effectful_attach_stops_after_first_failed_goal( {"goals": []}, tmp_path / ".loopx" / "registry.json", tmp_path / ".loopx" / "goal-channel.json", + tmp_path / "runtime", ), ) diff --git a/tests/extensions/test_periodic_report_goal_channel_delivery.py b/tests/extensions/test_periodic_report_goal_channel_delivery.py index 9a45dda180..daad5c5e56 100644 --- a/tests/extensions/test_periodic_report_goal_channel_delivery.py +++ b/tests/extensions/test_periodic_report_goal_channel_delivery.py @@ -35,11 +35,18 @@ write_periodic_report_publication_candidate, ) from loopx.extensions.lark import periodic_report_cli +from loopx.extensions.manifest import load_extension_manifest from loopx.presentation.renderers.periodic_report_markdown import ( periodic_report_markdown_renderer_adapter, ) +ROOT = Path(__file__).resolve().parents[2] +LARK_EXTENSION_VERSION = str( + load_extension_manifest(ROOT / "loopx/extensions/lark/extension.toml")["provider"][ + "version" + ] +) GOAL_ID = "goal-public-fixture" CHAT_ID = "oc_public_fixture" APP_ID = "cli_public_fixture" @@ -141,7 +148,7 @@ def _extension_activation() -> dict[str, Any]: return { "schema_version": "loopx_extension_activation_v0", "extension_id": "loopx-lark", - "provider_version": "1.6.0", + "provider_version": LARK_EXTENSION_VERSION, "revision": "publicfixture123", "enabled": True, "doctor_verified": True, diff --git a/tests/extensions/test_periodic_report_miaoda.py b/tests/extensions/test_periodic_report_miaoda.py index b8d0498245..b950e2e331 100644 --- a/tests/extensions/test_periodic_report_miaoda.py +++ b/tests/extensions/test_periodic_report_miaoda.py @@ -2,6 +2,7 @@ import json from copy import deepcopy +from pathlib import Path from typing import Any import pytest @@ -15,6 +16,7 @@ build_periodic_report_source_result, ) from loopx.cli import main +from loopx.extensions.manifest import load_extension_manifest from loopx.extensions.lark.miaoda_report import ( DELIVERY_INTENT_SCHEMA, LarkCliMiaodaProvider, @@ -31,6 +33,14 @@ ) +ROOT = Path(__file__).resolve().parents[2] +LARK_EXTENSION_VERSION = str( + load_extension_manifest(ROOT / "loopx/extensions/lark/extension.toml")["provider"][ + "version" + ] +) + + def _document() -> dict[str, Any]: source = build_periodic_report_source_result( source_id="release_notes", @@ -105,7 +115,7 @@ def _delivery_request() -> dict[str, Any]: }, "extension": { "extension_id": "loopx-lark", - "extension_version": "1.6.0", + "extension_version": LARK_EXTENSION_VERSION, "protocol": "periodic_report_sink_v0", }, } @@ -127,7 +137,7 @@ def _extension_activation() -> dict[str, Any]: return { "schema_version": "loopx_extension_activation_v0", "extension_id": "loopx-lark", - "provider_version": "1.6.0", + "provider_version": LARK_EXTENSION_VERSION, "revision": "publicfixture123", "enabled": True, "doctor_verified": True, @@ -147,7 +157,7 @@ def _sent_miaoda_delivery_receipt_inputs() -> tuple[ extension_receipts=[ { "extension_id": "loopx-lark", - "extension_version": "1.6.0", + "extension_version": LARK_EXTENSION_VERSION, "protocol": "periodic_report_sink_v0", "status": "ready", "readback_verified": True, From 23448528e50c79f694379c0a8613a3a913ae248d Mon Sep 17 00:00:00 2001 From: "lusendong.6789" Date: Sat, 12 Sep 2026 14:55:08 +0800 Subject: [PATCH 2/9] fix(lark): include next action in report notice Signed-off-by: lusendong.6789 Co-authored-by: TRAE CLI --- loopx/capabilities/periodic_report/README.md | 4 ++ .../lark/periodic_report_delivery.py | 44 +++++++++++++++++-- ...t_periodic_report_goal_channel_delivery.py | 24 +++++++++- 3 files changed, 68 insertions(+), 4 deletions(-) diff --git a/loopx/capabilities/periodic_report/README.md b/loopx/capabilities/periodic_report/README.md index 42fe107c48..14c68817c3 100644 --- a/loopx/capabilities/periodic_report/README.md +++ b/loopx/capabilities/periodic_report/README.md @@ -266,6 +266,10 @@ fails closed without a user/default-Bot fallback. Retries first scan the complet Goal Channel history from the frozen generation time and reuse only an exact card, chat, and Bot-sender match. Incomplete history fails closed instead of risking a duplicate; the stable provider idempotency key closes the concurrent-send race. +When the normalized report contains a primary typed `next_action`, the hosted +report announcement also carries its public-safe summary as a compact `下一步` +prompt. The hosted artifact remains authoritative, while the Channel card gives +an immediate direction and the same exact-card readback verifies that prompt. This is a built-in capability, not an extension: callers need the trigger, idempotency, retry, and receipt contract even when no provider is installed. diff --git a/loopx/extensions/lark/periodic_report_delivery.py b/loopx/extensions/lark/periodic_report_delivery.py index 0a2019d83e..d279c05b9c 100644 --- a/loopx/extensions/lark/periodic_report_delivery.py +++ b/loopx/extensions/lark/periodic_report_delivery.py @@ -41,6 +41,7 @@ from .presentation.kanban import CommandRunner, default_subprocess_runner from .presentation.periodic_report import periodic_report_lark_sink_adapter from ...registry import read_json +from ...presentation.public_safety import redact_public_text GOAL_CHANNEL_DELIVERY_REQUEST_SCHEMA = ( @@ -110,9 +111,43 @@ def _announcements(value: object) -> list[dict[str, str]]: return normalized -def _announcement_markdown(announcement: Mapping[str, str]) -> str: +def _next_action_guidance(document: Mapping[str, Any]) -> str | None: + primary_items: list[dict[str, Any]] = [] + for section in document.get("sections") or []: + if not isinstance(section, Mapping): + continue + for item in section.get("items") or []: + if ( + isinstance(item, Mapping) + and str(item.get("visibility") or "primary") == "primary" + ): + primary_items.append(dict(item)) + candidates = [ + item.get("summary") or item.get("title") + for item in primary_items + if item.get("content_kind") == "next_action" + ] + if not candidates: + candidates = [ + item.get("next_action") + for item in primary_items + if item.get("next_action") + ] + if not candidates: + return None + guidance = str(redact_public_text(candidates[0], limit=360)).strip() + return guidance or None + + +def _announcement_markdown( + announcement: Mapping[str, str], *, next_action: str | None +) -> str: if announcement["kind"] == "hosted_report": - return f"本期阶段周报已发布。\n\n[查看周报]({announcement['url']})" + guidance = f"\n\n下一步:{next_action}" if next_action else "" + return ( + f"本期阶段周报已发布。{guidance}" + f"\n\n[查看周报]({announcement['url']})" + ) return f"配套 Lark 文档已同步。\n\n[查看 Lark 文档]({announcement['url']})" @@ -357,9 +392,12 @@ def deliver_periodic_report_to_goal_channel( sink_id=sink_id, ) ) + next_action = _next_action_guidance(generation["document"]) message_results: list[dict[str, Any]] = [] for announcement in announcements: - content = _announcement_markdown(announcement) + content = _announcement_markdown( + announcement, next_action=next_action + ) result = registry.deliver( sink_id, { diff --git a/tests/extensions/test_periodic_report_goal_channel_delivery.py b/tests/extensions/test_periodic_report_goal_channel_delivery.py index daad5c5e56..98e3968825 100644 --- a/tests/extensions/test_periodic_report_goal_channel_delivery.py +++ b/tests/extensions/test_periodic_report_goal_channel_delivery.py @@ -59,7 +59,22 @@ def _generation_bundle() -> dict[str, Any]: source_kind="project_progress", status="complete", observed_at="2026-08-30T09:00:00Z", - sections=[], + sections=[ + { + "section_id": "next_actions", + "title": "下一步", + "order": 40, + "items": [ + { + "item_id": "next_action", + "title": "推进下一个已验证步骤", + "summary": "完成事实复核后推进下一个明确步骤。", + "content_kind": "next_action", + "value_rank": 90, + } + ], + } + ], ) document = build_periodic_report_document( title="阶段分析周报", @@ -510,6 +525,13 @@ def test_goal_channel_delivery_accepts_normalized_cli_card_readback( assert result["ok"] is True assert result["status"] == "satisfied" assert result["sink_result"]["readback_verified"] is True + send_calls = [args for args in calls if "+messages-send" in args] + hosted_card = json.loads( + send_calls[0][send_calls[0].index("--content") + 1] + ) + hosted_markdown = hosted_card["elements"][0]["text"]["content"] + assert "下一步:完成事实复核后推进下一个明确步骤。" in hosted_markdown + assert "https://example.com/reports/stage-1" in hosted_markdown assert len(result["sink_result"]["message_results"]) == 2 From d5908c73a224424d3601eb6b3121466c081cb5d8 Mon Sep 17 00:00:00 2001 From: "lusendong.6789" Date: Sat, 12 Sep 2026 19:13:27 +0800 Subject: [PATCH 3/9] fix(lark): bind report retries to rendered message Signed-off-by: lusendong.6789 Co-authored-by: TRAE CLI --- .../reference/protocols/periodic-report-v0.md | 5 +- loopx/extensions/lark/README.md | 4 + .../lark/periodic_report_delivery.py | 46 ++++-- ...t_periodic_report_goal_channel_delivery.py | 142 +++++++++++++++++- 4 files changed, 178 insertions(+), 19 deletions(-) diff --git a/docs/reference/protocols/periodic-report-v0.md b/docs/reference/protocols/periodic-report-v0.md index c5c6b07ccc..6d475db918 100644 --- a/docs/reference/protocols/periodic-report-v0.md +++ b/docs/reference/protocols/periodic-report-v0.md @@ -73,7 +73,10 @@ independently idempotent messages and each one must pass exact readback. Before each write, the provider scans the complete Goal Channel history from the frozen generation time and reuses an exact card, chat, and Bot-sender match. An incomplete history read fails closed; the provider's stable one-hour idempotency key covers -the remaining concurrent-send race. The command does not accept a chat, profile, +the remaining concurrent-send race. That provider key is versioned and bound to +the final announcement kind, title, body, and footer, so a renderer change after +an interrupted send cannot return an older, semantically different card under +the new retry. The command does not accept a chat, profile, App identity, or sender override. Instead, the Lark extension resolves the current Goal's local-private Goal Channel binding and requires `mode=project_bot`, Bot sender identity, a non-default diff --git a/loopx/extensions/lark/README.md b/loopx/extensions/lark/README.md index c7b83174c9..7ee14e568a 100644 --- a/loopx/extensions/lark/README.md +++ b/loopx/extensions/lark/README.md @@ -244,6 +244,10 @@ execute resolves only selected recipients and omits unrelated recipients. Raw The Goal Channel delivery command accepts exactly two ordered HTTPS entries (hosted report, then Lark document), emits two independently idempotent messages, and verifies the native sender App plus exact chat for each readback. +Each provider idempotency key binds the base delivery identity to the rendered +announcement kind, title, body, footer, and an explicit semantic version. A +renderer change therefore cannot make an upgraded retry reuse an older card +under the same provider key. Installation controls discoverability and provider lifecycle only. Every private chat, app, group, Base, document, or Miaoda target remains in ignored diff --git a/loopx/extensions/lark/periodic_report_delivery.py b/loopx/extensions/lark/periodic_report_delivery.py index d279c05b9c..814824e12d 100644 --- a/loopx/extensions/lark/periodic_report_delivery.py +++ b/loopx/extensions/lark/periodic_report_delivery.py @@ -49,7 +49,9 @@ ) GOAL_CHANNEL_DELIVERY_RESULT_SCHEMA = "periodic_report_goal_channel_delivery_result_v0" DELIVERY_INTENT_SCHEMA = "periodic_report_delivery_intent_v0" +ANNOUNCEMENT_IDEMPOTENCY_SCHEMA = "periodic_report_goal_channel_announcement_v1" _ANNOUNCEMENT_KINDS = ("hosted_report", "lark_document") +_ANNOUNCEMENT_FOOTER = "LoopX periodic report · Goal Channel" def _mapping(value: object, label: str) -> dict[str, Any]: @@ -129,9 +131,7 @@ def _next_action_guidance(document: Mapping[str, Any]) -> str | None: ] if not candidates: candidates = [ - item.get("next_action") - for item in primary_items - if item.get("next_action") + item.get("next_action") for item in primary_items if item.get("next_action") ] if not candidates: return None @@ -144,13 +144,32 @@ def _announcement_markdown( ) -> str: if announcement["kind"] == "hosted_report": guidance = f"\n\n下一步:{next_action}" if next_action else "" - return ( - f"本期阶段周报已发布。{guidance}" - f"\n\n[查看周报]({announcement['url']})" - ) + return f"本期阶段周报已发布。{guidance}\n\n[查看周报]({announcement['url']})" return f"配套 Lark 文档已同步。\n\n[查看 Lark 文档]({announcement['url']})" +def _announcement_idempotency_key( + *, + delivery_idempotency_key: str, + announcement: Mapping[str, str], + content: str, +) -> str: + material = "\0".join( + ( + ANNOUNCEMENT_IDEMPOTENCY_SCHEMA, + delivery_idempotency_key, + announcement["kind"], + announcement["title"], + content, + _ANNOUNCEMENT_FOOTER, + ) + ) + return ( + "periodic-report-announcement-v1:" + + hashlib.sha256(material.encode("utf-8")).hexdigest() + ) + + def _normalized_generation_bundle(raw: object) -> dict[str, Any]: supplied = _mapping(raw, "generation_bundle") if supplied.get("schema_version") != GENERATION_BUNDLE_SCHEMA: @@ -395,8 +414,11 @@ def deliver_periodic_report_to_goal_channel( next_action = _next_action_guidance(generation["document"]) message_results: list[dict[str, Any]] = [] for announcement in announcements: - content = _announcement_markdown( - announcement, next_action=next_action + content = _announcement_markdown(announcement, next_action=next_action) + announcement_idempotency_key = _announcement_idempotency_key( + delivery_idempotency_key=idempotency_key, + announcement=announcement, + content=content, ) result = registry.deliver( sink_id, @@ -409,9 +431,9 @@ def deliver_periodic_report_to_goal_channel( { "execute": bool(execute), "goal_id": goal_id, - "idempotency_key": f"{idempotency_key}:{announcement['kind']}", + "idempotency_key": announcement_idempotency_key, "title": announcement["title"], - "footer": "LoopX periodic report · Goal Channel", + "footer": _ANNOUNCEMENT_FOOTER, }, ) message_results.append({"kind": announcement["kind"], **result}) @@ -480,6 +502,7 @@ def deliver_periodic_report_to_goal_channel( "caller_identity_override_allowed": False, "exact_sender_and_chat_readback_required": True, "exact_history_dedupe_required": True, + "rendered_announcement_idempotency_bound": True, "sender_evidence_source": "message_readback", "external_writes_performed": sink_result.get("external_writes_performed") is True, @@ -488,6 +511,7 @@ def deliver_periodic_report_to_goal_channel( __all__ = [ + "ANNOUNCEMENT_IDEMPOTENCY_SCHEMA", "DELIVERY_INTENT_SCHEMA", "GOAL_CHANNEL_DELIVERY_REQUEST_SCHEMA", "GOAL_CHANNEL_DELIVERY_RESULT_SCHEMA", diff --git a/tests/extensions/test_periodic_report_goal_channel_delivery.py b/tests/extensions/test_periodic_report_goal_channel_delivery.py index 98e3968825..8d7f95ff2d 100644 --- a/tests/extensions/test_periodic_report_goal_channel_delivery.py +++ b/tests/extensions/test_periodic_report_goal_channel_delivery.py @@ -1,5 +1,6 @@ from __future__ import annotations +import hashlib import json from pathlib import Path from typing import Any @@ -25,10 +26,14 @@ resolve_goal_periodic_report_subscription, ) from loopx.extensions.lark.periodic_report_delivery import ( + ANNOUNCEMENT_IDEMPOTENCY_SCHEMA, DELIVERY_INTENT_SCHEMA, GOAL_CHANNEL_DELIVERY_REQUEST_SCHEMA, deliver_periodic_report_to_goal_channel, ) +from loopx.extensions.lark.presentation.message_card import ( + build_lark_markdown_reply_card, +) from loopx.capabilities.periodic_report.incremental import ( build_periodic_report_publication_candidate, read_periodic_report_publication_cursor, @@ -408,8 +413,15 @@ def test_explicit_goal_channel_binding_cannot_redirect_authorized_route( assert calls == [] -def _runner(calls: list[list[str]], *, normalized_readback: bool = False): - sent_cards: dict[str, dict[str, Any]] = {} +def _runner( + calls: list[list[str]], + *, + normalized_readback: bool = False, + initial_cards: dict[str, dict[str, Any]] | None = None, + provider_messages_by_key: dict[str, str] | None = None, +): + sent_cards: dict[str, dict[str, Any]] = dict(initial_cards or {}) + provider_cache = dict(provider_messages_by_key or {}) def run( args: list[str], @@ -454,8 +466,12 @@ def run( "has_more": False, } elif "+messages-send" in args: - message_id = f"{MESSAGE_ID}_{len(sent_cards) + 1}" - sent_cards[message_id] = json.loads(args[args.index("--content") + 1]) + provider_key = args[args.index("--idempotency-key") + 1] + message_id = provider_cache.get(provider_key) + if message_id is None: + message_id = f"{MESSAGE_ID}_{len(sent_cards) + 1}" + sent_cards[message_id] = json.loads(args[args.index("--content") + 1]) + provider_cache[provider_key] = message_id payload = {"ok": True, "data": {"message_id": message_id}} elif "+messages-mget" in args: message_id = args[args.index("--message-ids") + 1] @@ -526,9 +542,7 @@ def test_goal_channel_delivery_accepts_normalized_cli_card_readback( assert result["status"] == "satisfied" assert result["sink_result"]["readback_verified"] is True send_calls = [args for args in calls if "+messages-send" in args] - hosted_card = json.loads( - send_calls[0][send_calls[0].index("--content") + 1] - ) + hosted_card = json.loads(send_calls[0][send_calls[0].index("--content") + 1]) hosted_markdown = hosted_card["elements"][0]["text"]["content"] assert "下一步:完成事实复核后推进下一个明确步骤。" in hosted_markdown assert "https://example.com/reports/stage-1" in hosted_markdown @@ -576,6 +590,120 @@ def test_goal_channel_delivery_uses_only_the_bound_project_bot( assert send[send.index("--as") + 1] == "bot" assert "--profile" in send assert "project-reporter" in send + provider_key = send[send.index("--idempotency-key") + 1] + assert provider_key.startswith("loopx-") + assert sent["boundary"]["rendered_announcement_idempotency_bound"] is True + + +def test_goal_channel_provider_keys_are_bound_to_rendered_announcement( + tmp_path: Path, +) -> None: + registry_path = tmp_path / ".loopx" / "registry.json" + _write_registry(registry_path) + _write_binding(registry_path) + calls: list[list[str]] = [] + runner = _runner(calls) + + deliver_periodic_report_to_goal_channel( + _request(), + registry_path=registry_path, + runtime_root=tmp_path / "runtime", + goal_id=GOAL_ID, + extension_activation=_extension_activation(), + execute=True, + runner=runner, + ) + first_keys = [ + args[args.index("--idempotency-key") + 1] + for args in calls + if "+messages-send" in args + ] + + changed = _request() + next_action = changed["generation_bundle"]["document"]["sections"][0]["items"][0] + next_action["summary"] = "完成事实复核后执行新版明确步骤。" + changed["generation_bundle"] = build_periodic_report_generation_bundle( + document=changed["generation_bundle"]["document"], + artifacts=[ + periodic_report_markdown_renderer_adapter().render( + changed["generation_bundle"]["document"] + ) + ], + ) + deliver_periodic_report_to_goal_channel( + changed, + registry_path=registry_path, + runtime_root=tmp_path / "runtime", + goal_id=GOAL_ID, + extension_activation=_extension_activation(), + execute=True, + runner=runner, + ) + all_keys = [ + args[args.index("--idempotency-key") + 1] + for args in calls + if "+messages-send" in args + ] + + assert ANNOUNCEMENT_IDEMPOTENCY_SCHEMA.endswith("_v1") + assert len(first_keys) == 2 + assert len(all_keys) == 3 + assert all_keys[2] != first_keys[0] + assert len(set(all_keys)) == 3 + + +def test_upgraded_retry_does_not_reuse_legacy_key_for_changed_hosted_card( + tmp_path: Path, +) -> None: + registry_path = tmp_path / ".loopx" / "registry.json" + _write_registry(registry_path) + _write_binding(registry_path) + calls: list[list[str]] = [] + footer = "LoopX periodic report · Goal Channel" + old_hosted_id = f"{MESSAGE_ID}_legacy_hosted" + old_lark_id = f"{MESSAGE_ID}_legacy_lark" + old_cards = { + old_hosted_id: build_lark_markdown_reply_card( + "本期阶段周报已发布。\n\n[查看周报](https://example.com/reports/stage-1)", + title="阶段周报", + footer=footer, + ), + old_lark_id: build_lark_markdown_reply_card( + "配套 Lark 文档已同步。\n\n" + "[查看 Lark 文档](https://example.larksuite.com/docx/stage-1)", + title="配套 Lark 文档", + footer=footer, + ), + } + legacy_semantic_key = "periodic-report:goal-public-fixture:stage-1:hosted_report" + legacy_provider_key = ( + "loopx-" + hashlib.sha256(legacy_semantic_key.encode()).hexdigest()[:32] + ) + runner = _runner( + calls, + initial_cards=old_cards, + provider_messages_by_key={legacy_provider_key: old_hosted_id}, + ) + + recovered = deliver_periodic_report_to_goal_channel( + _request(), + registry_path=registry_path, + runtime_root=tmp_path / "runtime", + goal_id=GOAL_ID, + extension_activation=_extension_activation(), + execute=True, + runner=runner, + ) + + sends = [args for args in calls if "+messages-send" in args] + assert len(sends) == 1 + new_provider_key = sends[0][sends[0].index("--idempotency-key") + 1] + assert new_provider_key != legacy_provider_key + assert recovered["status"] == "satisfied" + assert [ + item["semantic_dedupe_status"] + for item in recovered["sink_result"]["message_results"] + ] == ["no_existing_exact_message", "existing_exact_message"] def test_goal_channel_delivery_reuses_exact_messages_after_interrupted_readback( From b698a24a97d7bd2e5e26237a61f429c32d4c63c8 Mon Sep 17 00:00:00 2001 From: "lusendong.6789" Date: Sun, 13 Sep 2026 10:58:40 +0800 Subject: [PATCH 4/9] fix(lark): serialize goal channel delivery authority Signed-off-by: lusendong.6789 Co-authored-by: TRAE CLI --- .../lark/goal_channel_message_delivery.py | 93 +++++++++------ loopx/extensions/lark/goal_channel_payload.py | 26 ++-- loopx/extensions/lark/goal_channel_targets.py | 56 +++++---- .../lark/periodic_report_delivery.py | 2 + tests/extensions/test_goal_channel_payload.py | 112 ++++++++++++++++++ 5 files changed, 224 insertions(+), 65 deletions(-) diff --git a/loopx/extensions/lark/goal_channel_message_delivery.py b/loopx/extensions/lark/goal_channel_message_delivery.py index 2a2c4d04f2..552e1ed16e 100644 --- a/loopx/extensions/lark/goal_channel_message_delivery.py +++ b/loopx/extensions/lark/goal_channel_message_delivery.py @@ -3,9 +3,11 @@ import hashlib import json from collections.abc import Callable, Mapping +from contextlib import ExitStack from pathlib import Path from typing import Any +from ...file_lock import exclusive_file_lock from .goal_channel_contracts import binding_for_goal, read_goal_channel_binding from .goal_channel_delivery_contract import goal_channel_delivery_route from .goal_channel_targets import ( @@ -189,12 +191,16 @@ def __init__( *, goal_id: str, binding: Mapping[str, Any], + binding_lock_path: Path, + target_lock_path: Path, history_start_at: str, resolve_current_binding: Callable[[], Mapping[str, Any]], runner: CommandRunner, ) -> None: self.goal_id = goal_id self.binding = dict(binding) + self.binding_lock_path = binding_lock_path + self.target_lock_path = target_lock_path self.history_start_at = history_start_at self.resolve_current_binding = resolve_current_binding self.runner = runner @@ -290,39 +296,60 @@ def verify(self, route: Mapping[str, Any]) -> bool: def send( self, card: Mapping[str, Any], key: str, route: Mapping[str, Any] ) -> Mapping[str, Any]: - if dict(self.resolve_current_binding()) != self.binding: - raise ValueError("Goal Channel delivery binding drifted") - existing_message_id = self._existing_message(card, route) - if existing_message_id is not None: - self.expected_cards.setdefault(existing_message_id, []).append(dict(card)) - return { - "message_id": existing_message_id, - "semantic_dedupe_status": "existing_exact_message", - "external_write_performed": False, - } - result = call( - self.runner, - lark_args( - cli_bin=str(route["cli_bin"]), - profile=str(route["sender_profile"]), - tail=[ - "im", - "+messages-send", - "--chat-id", - str(route["chat_id"]), - "--content", - json.dumps(card, ensure_ascii=False, separators=(",", ":")), - "--msg-type", - "interactive", - "--idempotency-key", - f"loopx-{hashlib.sha256(key.encode()).hexdigest()[:32]}", - "--as", - "bot", - "--format", - "json", - ], - ), - ) + with ExitStack() as locks: + # Match the writer order used by Goal Topic connect: the binding + # transaction owns the outer lock and target mutation the inner one. + locks.enter_context( + exclusive_file_lock( + self.binding_lock_path, operation="lark_goal_channel_delivery" + ) + ) + if self.target_lock_path != self.binding_lock_path: + locks.enter_context( + exclusive_file_lock( + self.target_lock_path, operation="lark_goal_channel_delivery" + ) + ) + if dict(self.resolve_current_binding()) != self.binding: + raise ValueError("Goal Channel delivery binding drifted") + existing_message_id = self._existing_message(card, route) + # The history lookup is a provider round trip. Recheck under the same + # lock used by binding writers immediately before either accepting + # the dedupe result or performing the external write. + if dict(self.resolve_current_binding()) != self.binding: + raise ValueError("Goal Channel delivery binding drifted") + if existing_message_id is not None: + self.expected_cards.setdefault(existing_message_id, []).append( + dict(card) + ) + return { + "message_id": existing_message_id, + "semantic_dedupe_status": "existing_exact_message", + "external_write_performed": False, + } + result = call( + self.runner, + lark_args( + cli_bin=str(route["cli_bin"]), + profile=str(route["sender_profile"]), + tail=[ + "im", + "+messages-send", + "--chat-id", + str(route["chat_id"]), + "--content", + json.dumps(card, ensure_ascii=False, separators=(",", ":")), + "--msg-type", + "interactive", + "--idempotency-key", + f"loopx-{hashlib.sha256(key.encode()).hexdigest()[:32]}", + "--as", + "bot", + "--format", + "json", + ], + ), + ) message_id = find_first_string( json_payload(result), {"message_id"}, MESSAGE_ID_PATTERN ) diff --git a/loopx/extensions/lark/goal_channel_payload.py b/loopx/extensions/lark/goal_channel_payload.py index 78cfa6411f..1cfe20ac93 100644 --- a/loopx/extensions/lark/goal_channel_payload.py +++ b/loopx/extensions/lark/goal_channel_payload.py @@ -8,7 +8,10 @@ from pathlib import Path from typing import Any -from ...control_plane.todos.contract import normalize_todo_decision_scope +from ...control_plane.todos.contract import ( + normalize_todo_claimed_by, + normalize_todo_decision_scope, +) from ...todos import add_goal_todo, complete_goal_todo, list_goal_todos from .goal_channel_contracts import operation_packet from .goal_channel_delivery_contract import ( @@ -195,19 +198,22 @@ def prepare_goal_channel_payload( ) -> dict[str, Any]: """Freeze one capability-owned public payload behind an exact user gate.""" + normalized_agent_id = normalize_todo_claimed_by(agent_id) + if normalized_agent_id is None: + raise ValueError("agent_id must be a valid Todo agent id") normalized = _normalized_request(request) binding = resolve_bound_goal_channel( binding_path=binding_path, target_path=target_path, goal_id=goal_id, - agent_id=agent_id, + agent_id=normalized_agent_id, ) binding_digest = goal_channel_binding_digest(binding) receipt_id = _receipt_identity( goal_id=goal_id, request=normalized, binding_digest=binding_digest, - agent_id=agent_id, + agent_id=normalized_agent_id, ) receipt_path = _receipt_path(runtime_root, goal_id, receipt_id) if receipt_path.exists(): @@ -251,8 +257,8 @@ def prepare_goal_channel_payload( required_capabilities=["network", "lark_bot_message_write"], target_capabilities=[normalized["capability_id"], "goal_channel"], required_decision_scopes=[scope_text], - claimed_by=agent_id, - agent_id=agent_id, + claimed_by=normalized_agent_id, + agent_id=normalized_agent_id, runtime_root_arg=str(runtime_root), dry_run=not execute, ) @@ -271,10 +277,10 @@ def prepare_goal_channel_payload( task_class="user_gate", action_kind="approve_goal_channel_payload", decision_scope=scope_text, - bound_agent=agent_id, - blocks_agent=agent_id, + bound_agent=normalized_agent_id, + blocks_agent=normalized_agent_id, unblocks_todo_id=str(delivery["todo_id"]), - agent_id=agent_id, + agent_id=normalized_agent_id, runtime_root_arg=str(runtime_root), dry_run=not execute, ) @@ -287,7 +293,7 @@ def prepare_goal_channel_payload( "payload_digest": normalized["payload_digest"], "decision_scope": normalized["decision_scope"], "binding_digest": binding_digest, - "agent_id": agent_id, + "agent_id": normalized_agent_id, "created_at": datetime.now(timezone.utc).isoformat(), "title": normalized["title"], "markdown": normalized["markdown"], @@ -442,6 +448,8 @@ def resolve_current() -> Mapping[str, Any]: session = GoalChannelMessageDeliverySession( goal_id=goal_id, binding=binding, + binding_lock_path=binding_path, + target_lock_path=target_path, history_start_at=str(receipt["created_at"]), resolve_current_binding=resolve_current, runner=runner, diff --git a/loopx/extensions/lark/goal_channel_targets.py b/loopx/extensions/lark/goal_channel_targets.py index db1b782106..c053176330 100644 --- a/loopx/extensions/lark/goal_channel_targets.py +++ b/loopx/extensions/lark/goal_channel_targets.py @@ -3,10 +3,12 @@ import json import re from collections.abc import Mapping +from contextlib import nullcontext from pathlib import Path from typing import Any from ...control_plane.runtime.public_safety import public_safe_compact_text +from ...file_lock import exclusive_file_lock from .goal_channel_contracts import operation_packet from .goal_channel_transport import APP_ID_PATTERN, CHAT_ID_PATTERN, OPEN_ID_PATTERN from .presentation.kanban import DEFAULT_CLI_BIN @@ -144,30 +146,38 @@ def add_lark_goal_channel_target( bot_display_name=bot_display_name, cli_bin=cli_bin, ) - payload = read_goal_channel_targets(target_path) - targets = dict(payload.get("targets") or {}) - existing = targets.get(target["name"]) - changed = existing != target - if execute and changed: - targets[str(target["name"])] = target - write_private_json_atomic( - target_path, - { - "schema_version": GOAL_CHANNEL_TARGETS_SCHEMA_VERSION, - "targets": targets, - }, - ) - readback = read_goal_channel_targets(target_path) - if goal_channel_target_for_name(readback, str(target["name"])) != target: - return operation_packet( - ok=False, - goal_id=None, - operation="target_add", - execute=True, - status="failed", - blocker="readback_mismatch", - public_summary="the shared Goal Channel target could not be read back", + mutation_lock = ( + exclusive_file_lock(target_path, operation="lark_goal_channel_target") + if execute + else nullcontext() + ) + with mutation_lock: + payload = read_goal_channel_targets(target_path) + targets = dict(payload.get("targets") or {}) + existing = targets.get(target["name"]) + changed = existing != target + if execute and changed: + targets[str(target["name"])] = target + write_private_json_atomic( + target_path, + { + "schema_version": GOAL_CHANNEL_TARGETS_SCHEMA_VERSION, + "targets": targets, + }, ) + readback = read_goal_channel_targets(target_path) + if goal_channel_target_for_name(readback, str(target["name"])) != target: + return operation_packet( + ok=False, + goal_id=None, + operation="target_add", + execute=True, + status="failed", + blocker="readback_mismatch", + public_summary=( + "the shared Goal Channel target could not be read back" + ), + ) status = ( "configured" if execute and changed diff --git a/loopx/extensions/lark/periodic_report_delivery.py b/loopx/extensions/lark/periodic_report_delivery.py index 814824e12d..d06fdcc90e 100644 --- a/loopx/extensions/lark/periodic_report_delivery.py +++ b/loopx/extensions/lark/periodic_report_delivery.py @@ -392,6 +392,8 @@ def deliver_periodic_report_to_goal_channel( session = GoalChannelMessageDeliverySession( goal_id=goal_id, binding=binding, + binding_lock_path=default_goal_channel_binding_path(registry_path), + target_lock_path=default_goal_channel_target_path(runtime_root), history_start_at=str(generation["document"]["generated_at"]), resolve_current_binding=lambda: _resolved_goal_channel_binding( registry_path=registry_path, diff --git a/tests/extensions/test_goal_channel_payload.py b/tests/extensions/test_goal_channel_payload.py index 45fab5780f..62f90bb6b4 100644 --- a/tests/extensions/test_goal_channel_payload.py +++ b/tests/extensions/test_goal_channel_payload.py @@ -331,6 +331,118 @@ def test_approved_delivery_is_verified_and_exact_replay_is_deduped( assert len([args for args in calls if "+messages-send" in args]) == 1 +def test_prepare_normalizes_agent_id_before_receipt_and_todos(tmp_path: Path) -> None: + registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) + prepared = prepare_goal_channel_payload( + _request(), + registry_path=registry_path, + runtime_root=runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=GOAL_ID, + agent_id=" CODEX PUBLIC DELIVERY ", + execute=True, + ) + receipt_path = ( + runtime_root + / "goals" + / GOAL_ID + / "goal_channel_payloads" + / f"{prepared['receipt_id']}.json" + ) + receipt = json.loads(receipt_path.read_text(encoding="utf-8")) + assert receipt["agent_id"] == AGENT_ID + + complete_goal_todo( + registry_path=registry_path, + runtime_root_arg=str(runtime_root), + goal_id=GOAL_ID, + todo_id=prepared["details"]["approval_todo_id"], + role="user", + decision_outcome="approve", + evidence="owner approved the normalized agent fixture", + ) + result = deliver_goal_channel_payload( + receipt_id=prepared["receipt_id"], + registry_path=registry_path, + runtime_root=runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=GOAL_ID, + execute=True, + runner=_runner([]), + ) + assert result["status"] == "satisfied" + + +def test_binding_mutation_during_history_scan_fails_before_send(tmp_path: Path) -> None: + registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) + prepared = _prepare_and_approve( + registry_path, runtime_root, binding_path, target_path + ) + calls: list[list[str]] = [] + base_runner = _runner(calls) + + def mutate_during_history( + args: list[str], cwd: Path | None, timeout: float | None + ) -> dict[str, Any]: + result = base_runner(args, cwd, timeout) + if "+chat-messages-list" in args: + binding = read_goal_channel_binding(binding_path) + binding["bindings"][GOAL_ID]["enabled"] = False + write_goal_channel_binding(binding_path, binding) + return result + + with pytest.raises(ValueError, match="Goal Channel delivery"): + deliver_goal_channel_payload( + receipt_id=prepared["receipt_id"], + registry_path=registry_path, + runtime_root=runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=GOAL_ID, + execute=True, + runner=mutate_during_history, + ) + + assert not any("+messages-send" in args for args in calls) + + +def test_target_mutation_during_history_scan_fails_before_send(tmp_path: Path) -> None: + registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) + prepared = _prepare_and_approve( + registry_path, runtime_root, binding_path, target_path + ) + calls: list[list[str]] = [] + base_runner = _runner(calls) + + def mutate_during_history( + args: list[str], cwd: Path | None, timeout: float | None + ) -> dict[str, Any]: + result = base_runner(args, cwd, timeout) + if "+chat-messages-list" in args: + targets = json.loads(target_path.read_text(encoding="utf-8")) + targets["targets"]["public-route"]["channel"]["chat_id"] = ( + "oc_changed_fixture" + ) + target_path.write_text(json.dumps(targets), encoding="utf-8") + return result + + with pytest.raises(ValueError, match="Goal Channel delivery binding drifted"): + deliver_goal_channel_payload( + receipt_id=prepared["receipt_id"], + registry_path=registry_path, + runtime_root=runtime_root, + binding_path=binding_path, + target_path=target_path, + goal_id=GOAL_ID, + execute=True, + runner=mutate_during_history, + ) + + assert not any("+messages-send" in args for args in calls) + + def test_approved_payload_and_route_drift_fail_before_send(tmp_path: Path) -> None: registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) prepared = _prepare_and_approve( From 533ed46ac1d9bb7940a069dc504e36945c542328 Mon Sep 17 00:00:00 2001 From: huangruiteng <14976749+huangruiteng@users.noreply.github.com> Date: Mon, 14 Sep 2026 02:25:54 +0800 Subject: [PATCH 5/9] feat(lark): add confirmed operation card flow Signed-off-by: huangruiteng <14976749+huangruiteng@users.noreply.github.com> --- apps/presentation/dashboard/src/data/chat.ts | 22 + .../personal-workspace/action-review-plan.ts | 1 + .../personal-workspace/context-drawer.tsx | 4 +- .../src/features/personal-workspace/i18n.tsx | 16 + .../personal-workspace-contract.test.mjs | 9 + .../personal-workspace-model.ts | 3 +- .../personal-workspace-page.tsx | 61 +- docs/reference/protocols/README.md | 1 - .../goal-channel-frozen-payload-v0.md | 46 - loopx/chat_action_store.py | 481 ++++++- loopx/chat_actions.py | 542 +++++++- loopx/cli_commands/goal_channel.py | 127 +- loopx/cli_commands/lark_inbox.py | 1 + loopx/extensions/lark/README.md | 84 +- loopx/extensions/lark/event_collector.py | 79 +- .../lark/event_collector_runtime.py | 365 ++++- loopx/extensions/lark/extension.toml | 4 +- loopx/extensions/lark/goal_channel.py | 14 +- .../extensions/lark/goal_channel_operation.py | 1188 +++++++++++++++++ loopx/extensions/lark/goal_channel_payload.py | 535 -------- loopx/extensions/lark/provider.py | 4 +- loopx/web/chat/asset-retention.json | 8 +- loopx/web/chat/assets/index-8CALBIjN.js | 129 ++ loopx/web/chat/assets/index-B-l9MJT-.js | 138 -- loopx/web/chat/assets/index-DGnmPxJU.js | 129 -- loopx/web/chat/assets/index-uHL7gp0q.js | 129 ++ loopx/web/chat/index.html | 2 +- packages/loopx-finance-execution/README.md | 29 + .../loopx-finance-execution/extension.toml | 16 + .../loopx-finance-execution/pyproject.toml | 18 + .../src/loopx_finance_execution/__init__.py | 5 + .../src/loopx_finance_execution/cli.py | 43 + .../src/loopx_finance_execution/simulator.py | 172 +++ .../test_finance_execution_simulator.py | 100 ++ tests/extensions/test_goal_channel_payload.py | 519 ------- .../test_lark_event_collector_runtime.py | 143 ++ tests/extensions/test_lark_goal_channel.py | 29 +- .../test_lark_goal_channel_operation.py | 777 +++++++++++ .../test_lark_goal_channel_targets.py | 30 +- tests/test_chat_operation_actions.py | 246 ++++ tests/test_license_metadata.py | 20 +- 41 files changed, 4680 insertions(+), 1589 deletions(-) delete mode 100644 docs/reference/protocols/goal-channel-frozen-payload-v0.md create mode 100644 loopx/extensions/lark/goal_channel_operation.py delete mode 100644 loopx/extensions/lark/goal_channel_payload.py create mode 100644 loopx/web/chat/assets/index-8CALBIjN.js delete mode 100644 loopx/web/chat/assets/index-B-l9MJT-.js delete mode 100644 loopx/web/chat/assets/index-DGnmPxJU.js create mode 100644 loopx/web/chat/assets/index-uHL7gp0q.js create mode 100644 packages/loopx-finance-execution/README.md create mode 100644 packages/loopx-finance-execution/extension.toml create mode 100644 packages/loopx-finance-execution/pyproject.toml create mode 100644 packages/loopx-finance-execution/src/loopx_finance_execution/__init__.py create mode 100644 packages/loopx-finance-execution/src/loopx_finance_execution/cli.py create mode 100644 packages/loopx-finance-execution/src/loopx_finance_execution/simulator.py create mode 100644 tests/extensions/test_finance_execution_simulator.py delete mode 100644 tests/extensions/test_goal_channel_payload.py create mode 100644 tests/extensions/test_lark_goal_channel_operation.py create mode 100644 tests/test_chat_operation_actions.py diff --git a/apps/presentation/dashboard/src/data/chat.ts b/apps/presentation/dashboard/src/data/chat.ts index 43c1c20fa8..68df1d2ae1 100644 --- a/apps/presentation/dashboard/src/data/chat.ts +++ b/apps/presentation/dashboard/src/data/chat.ts @@ -294,8 +294,29 @@ export const typedActionKindSchema = z.enum([ "monitor.update", "gate.resolve", "run.correct", + "operation.execute", ]); +const typedOperationEnvelopeSchema = z.object({ + schema_version: z.literal("loopx_operation_envelope_v0"), + lifecycle_state: z.enum([ + "prepared", + "awaiting_confirmation", + "claimed", + "outcome_observed", + ]), + operation_id: z.string().min(1), + confirmation_digest: z.string().min(1), + payload_digest: z.string().min(1), + projection_digest: z.string().min(1), + expires_at: z.string().min(1), + delivery: z.record(z.string(), z.unknown()).nullable(), + confirmation: z.record(z.string(), z.unknown()).nullable(), + claim: z.record(z.string(), z.unknown()).nullable(), + outcome: z.record(z.string(), z.unknown()).nullable(), + result_delivery: z.record(z.string(), z.unknown()).nullable().optional(), +}).passthrough(); + export const typedActionProposalSchema = z.object({ schema_version: z.literal("loopx_chat_action_proposal_v1"), proposal_id: z.string().min(1), @@ -315,6 +336,7 @@ export const typedActionProposalSchema = z.object({ error: z.record(z.string(), z.unknown()).nullable().optional(), checkpoint: z.record(z.string(), z.unknown()).nullable().optional(), regenerated_from: z.string().nullable().optional(), + operation: typedOperationEnvelopeSchema.nullable().optional(), created_at: z.string(), updated_at: z.string(), }); diff --git a/apps/presentation/dashboard/src/features/personal-workspace/action-review-plan.ts b/apps/presentation/dashboard/src/features/personal-workspace/action-review-plan.ts index 407cc86e9b..b7f492bdb6 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/action-review-plan.ts +++ b/apps/presentation/dashboard/src/features/personal-workspace/action-review-plan.ts @@ -20,6 +20,7 @@ export function compileActionReviewPlan(proposal: TypedActionProposal): ActionRe if ((lifecycle && proposal.gate != null) || proposal.status === "gated") return held("gated", "authority_gate"); if ((lifecycle && proposal.stale != null) || proposal.status === "stale") return held("refresh", "stale_proposal"); if (proposal.status === "applied") return proposal.receipt?.projection_verified === true + && (proposal.action_kind !== "operation.execute" || proposal.operation?.result_delivery != null) ? held("completed", "readback_verified") : held("repair", "readback_unverified"); if (proposal.status === "applying") return held("pending", "apply_pending"); if (proposal.status === "failed" || proposal.error != null) return held("repair", "apply_failed"); diff --git a/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx b/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx index 8ade7a2815..b7472b5124 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx @@ -989,8 +989,8 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention })() : null} {!readOnly && selection.item.workspaceCandidates?.length ?
{selection.item.workspaceCandidates.map((candidate) => )}
: null} {!readOnly && selection.item.status === "error" ? : !readOnly && selection.item.status !== "gated" ? : null} - {!readOnly && (["stale", "gated", "rejected"].includes(selection.item.status) || (selection.item.status === "ready" && selection.item.reviewPlan?.canApply === false)) ? : null} - {!readOnly && ["ready", "gated"].includes(selection.item.status) ?
: null} + {!readOnly && selection.item.actionKind !== "operation.execute" && (["stale", "gated", "rejected"].includes(selection.item.status) || (selection.item.status === "ready" && selection.item.reviewPlan?.canApply === false)) ? : null} + {!readOnly && selection.item.actionKind !== "operation.execute" && ["ready", "gated"].includes(selection.item.status) ?
: null} {!["applied", "applying"].includes(selection.item.status) ? : null} ) : null} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx b/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx index 979ef4b7f7..2366d39dc8 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx @@ -627,6 +627,10 @@ const en = { "proposal.field.initialTodos": "Initial tasks", "proposal.field.objective": "Objective", "proposal.field.operation": "Operation", + "proposal.field.operationState": "Operation state", + "proposal.field.resultDelivery": "Result delivery", + "proposal.field.confirmationBoundary": "Confirmation boundary", + "proposal.field.expiresAt": "Expires at", "proposal.field.permission": "Permission", "proposal.field.reason": "Reason", "proposal.field.stopCondition": "Stop condition", @@ -657,12 +661,16 @@ const en = { "proposal.impact.lifecycleResume": "After confirmation, the Goal becomes eligible for automatic scheduling and returns to Active Goals. Actual execution still follows quota, Gate, and Todo constraints.", "proposal.impact.lifecycleStop": "After confirmation, automatic progress stops and the Goal moves to the collapsed Stopped list. History, Todos, and evidence remain available for resuming.", "proposal.impact.protected": "This action must be completed through the protected LoopX write service.", + "proposal.impact.operation": "The exact terms are read-only here. Confirm or reject the same immutable request in the bound Feishu group; confirmation consumes one canonical claim.", "proposal.primary.apply": "Confirm and apply", "proposal.primary.goalCreate": "Create Goal and start first run", "proposal.primary.lifecycleDelete": "Delete Goal", "proposal.primary.lifecycleResume": "Resume Goal", "proposal.primary.lifecycleStop": "Stop Goal", "proposal.primary.todoStart": "Create task and start execution", + "proposal.primary.operationGroup": "Confirm in Feishu group", + "proposal.resultDelivery.verified": "Verified in the original group card", + "proposal.resultDelivery.pending": "Pending verified return to the original group card", "proposal.summary.goalCreate": "Create Goal: {title}", "proposal.summary.heartbeat": "Set a Heartbeat for the current Goal", "proposal.summary.lifecycleDelete": "Delete Goal: {title}", @@ -1601,6 +1609,10 @@ const zhCN: Record = { "proposal.field.initialTodos": "首个任务", "proposal.field.objective": "目标", "proposal.field.operation": "操作", + "proposal.field.operationState": "操作状态", + "proposal.field.resultDelivery": "结果回传", + "proposal.field.confirmationBoundary": "确认边界", + "proposal.field.expiresAt": "过期时间", "proposal.field.permission": "权限", "proposal.field.reason": "原因", "proposal.field.stopCondition": "停止条件", @@ -1631,12 +1643,16 @@ const zhCN: Record = { "proposal.impact.lifecycleResume": "确认后会恢复 Goal 的自动调度资格并移回 Active Goals;实际执行仍受 quota、Gate 和 Todo 约束。", "proposal.impact.lifecycleStop": "确认后会停止自动推进,并将 Goal 移入折叠的「已停止」列表;历史、Todo 和证据都会保留,可随时恢复。", "proposal.impact.protected": "该操作需要通过受保护的 LoopX 写入服务完成。", + "proposal.impact.operation": "这里仅展示同一份不可变条款。请在已绑定的飞书群确认或拒绝;确认只会消费一个规范 claim。", "proposal.primary.apply": "确认并应用", "proposal.primary.goalCreate": "创建 Goal 并开始首轮", "proposal.primary.lifecycleDelete": "删除 Goal", "proposal.primary.lifecycleResume": "恢复 Goal", "proposal.primary.lifecycleStop": "停止 Goal", "proposal.primary.todoStart": "创建任务并开始执行", + "proposal.primary.operationGroup": "前往飞书群确认", + "proposal.resultDelivery.verified": "已在原群卡片完成回读核验", + "proposal.resultDelivery.pending": "等待回传并核验原群卡片", "proposal.summary.goalCreate": "创建 Goal:{title}", "proposal.summary.heartbeat": "为当前 Goal 设置 Heartbeat", "proposal.summary.lifecycleDelete": "删除 Goal:{title}", diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs index 81e2237504..29c876535d 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs +++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs @@ -26,6 +26,7 @@ const dashboard = source("../../views/dashboard-page.tsx"); const tasks = source("./goal-tasks-view.tsx"); const status = source("../../data/status.ts"); const chatData = source("../../data/chat.ts"); +const actionReview = source("./action-review-plan.ts"); assert.match(model, /kind: "todo"/, "Todo has its own drawer selection"); for (const field of ["dependencies", "nextTransition", "ownerLabel", "todoId", "taskClass"]) { @@ -90,6 +91,14 @@ assert.doesNotMatch(router, /protectedActionIntent|protectedActionRules/, "Free- assert.doesNotMatch(router, /"goal\.update"/, "The browser Router type cannot emit a protected Goal action"); assert.doesNotMatch(page, /intentRoute\.actionKind === "goal\.update"|workspace-protected-/, "Free-text send has no legacy protected-action preview branch"); assert.match(chatData, /protected_action: protectedActionProposalSchema/, "Chat accepts one narrow semantic protected-action proposal"); +assert.match(chatData, /"operation\.execute"/, "Dashboard accepts canonical operation proposals"); +assert.match(chatData, /operation: typedOperationEnvelopeSchema\.nullable\(\)\.optional\(\)/, "Dashboard retains the canonical operation lifecycle"); +assert.match(page, /function operationProposalFields/, "Operation details have a dedicated safe projection"); +assert.doesNotMatch(page.match(/function operationProposalFields[\s\S]*?\n\}/)?.[0] ?? "", /authorized_principals|payload_digest|parameters\.payload/, "Operation details do not expose private authority or inline payloads"); +assert.match(page, /t\("proposal\.primary\.operationGroup"\)/, "Operation confirmation routes users to the bound group"); +assert.match(chatData, /result_delivery:/, "Dashboard retains operation result-delivery readback"); +assert.match(actionReview, /operation\.execute" \|\| proposal\.operation\?\.result_delivery != null/, "An operation is not complete in the Dashboard until result delivery is verified"); +assert.match(drawer, /selection\.item\.actionKind !== "operation\.execute"/, "Dashboard hides generic local controls for authenticated group operations"); assert.match(dashboard, /response\.protected_action/, "Agent semantic protected intent is projected only after the Chat response"); assert.match(dashboard, /normalizedMessage\.includes\(normalizedTarget\)/, "A model-invented protected target cannot reach typed preview"); assert.match(page, /if \(semanticPreview\) await createPreview\(semanticPreview\)/, "Semantic intent still enters the typed preview boundary"); diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts index 152004a8e2..9c35b03bad 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts +++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts @@ -215,7 +215,8 @@ export type WorkspaceActionPreview = { | "monitor.create" | "monitor.update" | "gate.resolve" - | "run.correct"; + | "run.correct" + | "operation.execute"; agentLabel?: string; fields: Array<{ key: string; label: string; value: string }>; goalId?: string; diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx index 3976e9aaf6..6e14af85f2 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx @@ -484,6 +484,46 @@ function proposalFields(parameters: Record, t: WorkspaceTransla })); } +function operationProposalFields(proposal: TypedActionProposal, t: WorkspaceTranslate) { + const projection = proposal.normalized_parameters.projection; + const safeProjection = projection && typeof projection === "object" + ? projection as Record + : {}; + const projectedFields = Array.isArray(safeProjection.fields) + ? safeProjection.fields.flatMap((field, index) => { + if (!field || typeof field !== "object") return []; + const item = field as Record; + if (typeof item.label !== "string" || typeof item.value !== "string") return []; + return [{ key: `projection:${index}`, label: item.label, value: item.value }]; + }).slice(0, 8) + : []; + return [ + { + key: "operation_state", + label: t("proposal.field.operationState"), + value: proposal.operation?.lifecycle_state ?? proposal.status, + }, + ...(proposal.operation?.lifecycle_state === "outcome_observed" ? [{ + key: "result_delivery", + label: t("proposal.field.resultDelivery"), + value: proposal.operation.result_delivery + ? t("proposal.resultDelivery.verified") + : t("proposal.resultDelivery.pending"), + }] : []), + ...projectedFields, + ...(typeof safeProjection.warning === "string" ? [{ + key: "warning", + label: t("proposal.field.confirmationBoundary"), + value: safeProjection.warning, + }] : []), + ...(proposal.operation?.expires_at ? [{ + key: "expires_at", + label: t("proposal.field.expiresAt"), + value: proposal.operation.expires_at, + }] : []), + ].slice(0, 10); +} + type GoalLifecycleOperation = "stop" | "resume" | "delete"; type GoalLifecycleProjection = { @@ -512,7 +552,14 @@ function workspaceProposal(proposal: TypedActionProposal, t: WorkspaceTranslate) const target = typeof proposal.normalized_parameters.target === "string" ? proposal.normalized_parameters.target : ""; - const localizedSummary = proposal.action_kind === "goal.create" + const operationProjection = proposal.normalized_parameters.projection; + const operationTitle = operationProjection && typeof operationProjection === "object" + && typeof (operationProjection as Record).title === "string" + ? String((operationProjection as Record).title) + : proposal.summary; + const localizedSummary = proposal.action_kind === "operation.execute" + ? operationTitle + : proposal.action_kind === "goal.create" ? t("proposal.summary.goalCreate", { title }) : proposal.action_kind === "heartbeat.bind" ? t("proposal.summary.heartbeat") @@ -528,9 +575,13 @@ function workspaceProposal(proposal: TypedActionProposal, t: WorkspaceTranslate) return { actionKind: proposal.action_kind, reviewPlan, - fields: proposalFields(proposal.normalized_parameters, t), + fields: proposal.action_kind === "operation.execute" + ? operationProposalFields(proposal, t) + : proposalFields(proposal.normalized_parameters, t), goalId: typeof proposal.normalized_parameters.goal_id === "string" ? proposal.normalized_parameters.goal_id : undefined, - impact: proposal.action_kind === "goal.create" + impact: proposal.action_kind === "operation.execute" + ? t("proposal.impact.operation") + : proposal.action_kind === "goal.create" ? t("proposal.impact.goalCreate") : proposal.action_kind === "goal.lifecycle" && lifecycleOperation === "stop" ? t("proposal.impact.lifecycleStop") @@ -548,7 +599,9 @@ function workspaceProposal(proposal: TypedActionProposal, t: WorkspaceTranslate) nextAction: typeof proposal.gate.next_action === "string" ? proposal.gate.next_action : undefined, summary: String(proposal.gate.summary ?? t("proposal.gate.default")), } : undefined, - primaryLabel: proposal.action_kind === "goal.create" ? t("proposal.primary.goalCreate") + primaryLabel: proposal.action_kind === "operation.execute" + ? t("proposal.primary.operationGroup") + : proposal.action_kind === "goal.create" ? t("proposal.primary.goalCreate") : proposal.action_kind === "goal.lifecycle" && lifecycleOperation === "stop" ? t("proposal.primary.lifecycleStop") : proposal.action_kind === "goal.lifecycle" && lifecycleOperation === "delete" diff --git a/docs/reference/protocols/README.md b/docs/reference/protocols/README.md index bc43cde20e..720d28754c 100644 --- a/docs/reference/protocols/README.md +++ b/docs/reference/protocols/README.md @@ -44,7 +44,6 @@ scanning a chronological list. - [`peer_agent_runtime_v1`](peer-agent-runtime-v1.md): Peer agent runtime v1 - [`peer_supervisor_v0`](peer-supervisor-v0.md): Peer supervisor v0 - [`periodic_report_v0`](periodic-report-v0.md): Periodic report v0 -- [`goal_channel_frozen_payload_v0`](goal-channel-frozen-payload-v0.md): exact-approval delivery of one frozen capability payload through a bound Goal Channel - [`review_batch_v0`](review-batch-v0.md): Review batch v0 - [`reward_memory_architecture_v0`](../../../loopx/capabilities/reward_memory/README.md): Reward memory architecture v0 - [`reward_memory_architecture_v0`](../../../loopx/capabilities/reward_memory/README.zh-CN.md): Reward memory architecture v0 (中文) diff --git a/docs/reference/protocols/goal-channel-frozen-payload-v0.md b/docs/reference/protocols/goal-channel-frozen-payload-v0.md deleted file mode 100644 index 071a255e8f..0000000000 --- a/docs/reference/protocols/goal-channel-frozen-payload-v0.md +++ /dev/null @@ -1,46 +0,0 @@ -# Goal Channel frozen payload v0 - -Status: provider-backed, capability-neutral exact-approval delivery contract. - -`goal_channel_frozen_payload_request_v0` lets any producing capability submit -one final public-safe Markdown result for a LoopX Goal Channel. It does not -classify domain facts or make content safe. The producer retains responsibility -for semantics, sources, redaction, and the truthful `public_safe=true` -attestation. - -## Lifecycle - -1. The producer supplies a capability id, opaque payload ref, title, Markdown, - footer, and one `public_claim:action:` decision scope. -2. LoopX renders the final Lark card, hashes the canonical card, and stores the - content in an owner-local `0600` receipt. Public Todo state contains only - the receipt id, digest, scope, and execution requirements. -3. LoopX creates one blocked Agent delivery Todo and one User gate whose - `unblocks_todo_id` points to that successor. Approve consumes only the exact - required scope; reject or cancel keeps delivery blocked. -4. Delivery reloads both Todos and the private receipt. It fails closed unless - the gate is done with `approve`, the successor is open (or already done for - an exact replay), and its required decision scopes are empty. -5. The Lark extension resolves the route only from the durable Goal Channel - binding. The caller cannot select the chat, profile, Bot, sender, or mention - recipients. Binding drift after preparation invalidates the approval. -6. Before sending, LoopX verifies the project Bot and reads complete Bot-visible - channel history. An exact existing card is reused. Otherwise one - provider-idempotent message is sent. Provider-native sender, chat, and card - readback are required before the delivery Todo and receipt become satisfied. - -## Boundaries - -- Receipt content and provider identifiers stay in local-private runtime state. -- Public command results expose only opaque ids, digests, decision scopes, and - lifecycle status. -- Mention markup is rejected; audience selection belongs to a capability with - an explicit typed audience policy. -- The contract grants no standing publication authority. Every payload needs - its own exact gate unless another capability, such as Periodic Report, owns a - separately documented standing subscription. -- A successful provider write without exact native readback is not completion. - -This mechanism complements `content_ops_item_v0`: content-ops can track -provider-neutral item state without storing bodies, while this Lark extension -owns one concrete Goal Channel effect and its private payload receipt. diff --git a/loopx/chat_action_store.py b/loopx/chat_action_store.py index e6e7379d2b..2968ce8f15 100644 --- a/loopx/chat_action_store.py +++ b/loopx/chat_action_store.py @@ -2,9 +2,10 @@ from __future__ import annotations -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone import hashlib import json +import math import os from pathlib import Path import re @@ -30,6 +31,7 @@ "monitor.update", "gate.resolve", "run.correct", + "operation.execute", } PROPOSAL_STATES = { "preview_ready", @@ -44,6 +46,13 @@ } RETRYABLE_PROPOSAL_STATES = {"preview_ready", "gated", "failed", "deferred"} +OPERATION_ENVELOPE_SCHEMA_VERSION = "loopx_operation_envelope_v0" +OPERATION_LIFECYCLE_STATES = { + "awaiting_confirmation", + "claimed", + "outcome_observed", +} + _OPAQUE_ID = re.compile(r"^[A-Za-z0-9._:-]{1,200}$") _LOCAL_PATH = re.compile( r"(?:^|[\s\"'])(?:/Users/|/home/|/private/|/var/folders/|/tmp/|~[/\\]|file://)", @@ -98,7 +107,11 @@ def _bounded_text(value: Any, *, field: str, limit: int = 4000) -> str: def _safe_json_value(value: Any, *, path: str = "payload") -> Any: - if value is None or isinstance(value, (bool, int, float)): + if value is None or isinstance(value, (bool, int)): + return value + if isinstance(value, float): + if not math.isfinite(value): + raise ValueError(f"{path} must contain finite JSON numbers") return value if isinstance(value, str): if _LOCAL_PATH.search(value) or _SENSITIVE_TEXT.search(value): @@ -126,6 +139,7 @@ def _safe_json_value(value: Any, *, path: str = "payload") -> Any: def _canonical_digest(payload: Mapping[str, Any]) -> str: encoded = json.dumps( payload, + allow_nan=False, ensure_ascii=False, sort_keys=True, separators=(",", ":"), @@ -158,7 +172,10 @@ def _read(self) -> dict[str, Any]: payload = json.loads(self.path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise ValueError("typed Chat action store is unreadable") from exc - if not isinstance(payload, dict) or payload.get("schema_version") != CHAT_ACTION_STORE_SCHEMA_VERSION: + if ( + not isinstance(payload, dict) + or payload.get("schema_version") != CHAT_ACTION_STORE_SCHEMA_VERSION + ): raise ValueError("typed Chat action store has an unsupported schema") if not isinstance(payload.get("proposals"), dict) or not isinstance( payload.get("idempotency"), dict @@ -218,10 +235,14 @@ def create_preview( if isinstance(existing_binding, dict): proposal_id = str(existing_binding.get("proposal_id") or "") if existing_binding.get("request_digest") != request_digest: - raise ActionConflictError("idempotency key already belongs to another preview") + raise ActionConflictError( + "idempotency key already belongs to another preview" + ) existing = payload["proposals"].get(proposal_id) if not isinstance(existing, dict): - raise ValueError("typed Chat action idempotency index is inconsistent") + raise ValueError( + "typed Chat action idempotency index is inconsistent" + ) return existing now = _utc_now() @@ -234,6 +255,7 @@ def create_preview( "request_digest": request_digest, "status": "preview_ready", "receipt": None, + "operation": None, "gate": None, "failure": None, "checkpoint": None, @@ -254,12 +276,417 @@ def create_preview( self._write(payload) return proposal + def arm_operation(self, proposal_id: str) -> dict[str, Any]: + """Turn one provider-neutral preview into the canonical confirmation gate. + + The immutable request already lives on the proposal. This method adds + only lifecycle state derived from that request; Lark, the Dashboard and + domain executors must all read this same envelope. + """ + + token = _opaque_id(proposal_id, field="proposal_id") + with exclusive_file_lock( + self.path, + agent_id="loopx-chat", + operation="arm_operation_confirmation", + ): + payload = self._read() + proposal = payload["proposals"].get(token) + if not isinstance(proposal, dict): + raise KeyError("typed Chat action proposal was not found") + if proposal.get("action_kind") != "operation.execute": + raise ActionConflictError( + "only operation.execute previews can be armed" + ) + existing = proposal.get("operation") + if isinstance(existing, dict): + if ( + existing.get("schema_version") != OPERATION_ENVELOPE_SCHEMA_VERSION + or existing.get("lifecycle_state") not in OPERATION_LIFECYCLE_STATES + ): + raise ValueError("typed operation envelope is malformed") + return proposal + if proposal.get("status") != "preview_ready": + raise ActionConflictError( + f"proposal in {proposal.get('status')} state cannot await confirmation" + ) + parameters = proposal.get("normalized_parameters") + if not isinstance(parameters, dict): + raise ValueError("typed operation parameters are malformed") + now = _utc_now() + confirmation_digest = _canonical_digest( + { + "action_kind": "operation.execute", + "normalized_parameters": parameters, + "request_digest": proposal.get("request_digest"), + } + ) + operation = { + "schema_version": OPERATION_ENVELOPE_SCHEMA_VERSION, + "operation_id": token, + "lifecycle_state": "awaiting_confirmation", + "confirmation_digest": confirmation_digest, + "payload_digest": parameters.get("payload_digest"), + "projection_digest": parameters.get("projection_digest"), + "executor_revision": ( + parameters.get("executor", {}).get("revision") + if isinstance(parameters.get("executor"), dict) + else None + ), + "destination_account_ref": parameters.get("destination_account_ref"), + "expires_at": parameters.get("expires_at"), + "authorized_principals": list( + parameters.get("authorized_principals") or [] + ), + "delivery": None, + "confirmation": None, + "claim": None, + "outcome": None, + "result_delivery": None, + "armed_at": now, + } + proposal["operation"] = _safe_json_value(operation, path="operation") + proposal["status"] = "gated" + proposal["gate"] = { + "kind": "human_operation_confirmation", + "summary": "This exact operation is awaiting an authenticated human decision.", + "next_action": "Use the bound operation card; ordinary typed-action apply is not confirmation.", + } + proposal["updated_at"] = now + self._write(payload) + return proposal + + def record_operation_delivery( + self, + proposal_id: str, + *, + delivery: Mapping[str, Any], + ) -> dict[str, Any]: + """Bind the exact provider message which may attest a later click.""" + + safe_delivery = _safe_json_value(dict(delivery), path="operation.delivery") + if not isinstance(safe_delivery, dict): + raise ValueError("operation delivery must be an object") + for field in ( + "provider", + "message_id", + "chat_id", + "app_id", + "binding_digest", + "card_digest", + "delivered_at", + ): + _bounded_text( + safe_delivery.get(field), + field=f"operation.delivery.{field}", + limit=512, + ) + token = _opaque_id(proposal_id, field="proposal_id") + with exclusive_file_lock( + self.path, + agent_id="loopx-chat", + operation="record_operation_delivery", + ): + payload = self._read() + proposal = payload["proposals"].get(token) + operation = ( + proposal.get("operation") if isinstance(proposal, dict) else None + ) + if not isinstance(operation, dict): + raise KeyError("typed operation was not found") + if operation.get("lifecycle_state") != "awaiting_confirmation": + existing = operation.get("delivery") + if isinstance(existing, dict) and existing == safe_delivery: + return proposal + raise ActionConflictError("operation is no longer awaiting delivery") + existing = operation.get("delivery") + if existing is not None: + if existing != safe_delivery: + raise ActionConflictError( + "operation is already bound to another provider message" + ) + return proposal + operation["delivery"] = safe_delivery + proposal["updated_at"] = _utc_now() + self._write(payload) + return proposal + + def decide_operation( + self, + proposal_id: str, + *, + decision: str, + confirmation: Mapping[str, Any], + ) -> dict[str, Any]: + """Atomically reject, or confirm and claim, one delivered operation. + + The transport owner must supply a verified callback envelope. A + successful confirmation consumes the operation in this transaction so + concurrent web/Lark clicks cannot both dispatch it. + """ + + selected_decision = str(decision or "").strip().lower() + if selected_decision not in {"confirm", "reject"}: + raise ValueError("operation decision must be confirm or reject") + safe_confirmation = _safe_json_value( + dict(confirmation), path="operation.confirmation" + ) + if not isinstance(safe_confirmation, dict): + raise ValueError("operation confirmation must be an object") + required = { + "provider", + "event_id", + "principal", + "message_id", + "chat_id", + "app_id", + "surface_kind", + "interaction_kind", + "confirmation_digest", + "card_digest", + "confirmed_at", + } + if set(safe_confirmation) != required: + raise ValueError("operation confirmation has unsupported or missing fields") + for field in required: + _bounded_text( + safe_confirmation.get(field), + field=f"operation.confirmation.{field}", + limit=512, + ) + token = _opaque_id(proposal_id, field="proposal_id") + with exclusive_file_lock( + self.path, + agent_id="loopx-chat", + operation="decide_operation", + ): + payload = self._read() + proposal = payload["proposals"].get(token) + operation = ( + proposal.get("operation") if isinstance(proposal, dict) else None + ) + if not isinstance(operation, dict): + raise KeyError("typed operation was not found") + existing_confirmation = operation.get("confirmation") + if isinstance(existing_confirmation, dict): + if ( + existing_confirmation.get("event_id") + == safe_confirmation["event_id"] + ): + return proposal + raise ActionConflictError("operation already consumed another decision") + if ( + proposal.get("status") != "gated" + or operation.get("lifecycle_state") != "awaiting_confirmation" + ): + raise ActionConflictError("operation is not awaiting confirmation") + delivery = operation.get("delivery") + if not isinstance(delivery, dict): + raise ActionConflictError("operation card delivery is not verified") + expected = { + "provider": delivery.get("provider"), + "message_id": delivery.get("message_id"), + "chat_id": delivery.get("chat_id"), + "app_id": delivery.get("app_id"), + "card_digest": delivery.get("card_digest"), + "confirmation_digest": operation.get("confirmation_digest"), + } + if any( + safe_confirmation.get(field) != value + for field, value in expected.items() + ): + raise ActionConflictError( + "operation callback does not match the delivered request" + ) + if safe_confirmation.get("principal") not in set( + operation.get("authorized_principals") or [] + ): + raise ActionConflictError( + "principal is not authorized for this operation" + ) + expires_at = datetime.fromisoformat( + str(operation.get("expires_at") or "").replace("Z", "+00:00") + ) + confirmed_at = datetime.fromisoformat( + str(safe_confirmation["confirmed_at"]).replace("Z", "+00:00") + ) + delivered_at = datetime.fromisoformat( + str(delivery.get("delivered_at") or "").replace("Z", "+00:00") + ) + if ( + expires_at.tzinfo is None + or confirmed_at.tzinfo is None + or delivered_at.tzinfo is None + ): + raise ValueError("operation timestamps require a timezone") + if confirmed_at < delivered_at - timedelta(minutes=5): + raise ActionConflictError( + "operation confirmation predates the delivered request" + ) + if confirmed_at > expires_at: + raise ActionConflictError("operation confirmation arrived after expiry") + now = _utc_now() + now_at = datetime.fromisoformat(now.replace("Z", "+00:00")) + if confirmed_at > now_at + timedelta(minutes=5): + raise ActionConflictError( + "operation confirmation timestamp is in the future" + ) + operation["confirmation"] = { + **safe_confirmation, + "decision": selected_decision, + } + if selected_decision == "reject": + operation["lifecycle_state"] = "outcome_observed" + operation["outcome"] = { + "schema_version": "loopx_operation_outcome_v0", + "outcome": "rejected_by_operator", + "projection_verified": True, + "observed_at": now, + } + proposal["status"] = "rejected" + proposal["rejected_at"] = now + proposal["receipt"] = operation["outcome"] + else: + operation["lifecycle_state"] = "claimed" + operation["claim"] = { + "claim_id": "claim-" + uuid.uuid4().hex, + "event_id": safe_confirmation["event_id"], + "claimed_at": now, + } + proposal["status"] = "applying" + proposal["gate"] = None + proposal["updated_at"] = now + self._write(payload) + return proposal + + def observe_operation_outcome( + self, + proposal_id: str, + *, + outcome: Mapping[str, Any], + ) -> dict[str, Any]: + """Persist the domain result without making it a retryable submission.""" + + safe_outcome = _safe_json_value(dict(outcome), path="operation.outcome") + if not isinstance(safe_outcome, dict): + raise ValueError("operation outcome must be an object") + if safe_outcome.get("schema_version") != "loopx_operation_outcome_v0": + raise ValueError("operation outcome schema is unsupported") + _opaque_id(safe_outcome.get("outcome"), field="operation.outcome.outcome") + if safe_outcome.get("projection_verified") is not True: + raise ValueError("operation outcome projection must be verified") + token = _opaque_id(proposal_id, field="proposal_id") + with exclusive_file_lock( + self.path, + agent_id="loopx-chat", + operation="observe_operation_outcome", + ): + payload = self._read() + proposal = payload["proposals"].get(token) + operation = ( + proposal.get("operation") if isinstance(proposal, dict) else None + ) + if not isinstance(operation, dict): + raise KeyError("typed operation was not found") + if operation.get("lifecycle_state") == "outcome_observed": + if operation.get("outcome") != safe_outcome: + raise ActionConflictError("operation outcome is already immutable") + return proposal + if ( + operation.get("lifecycle_state") != "claimed" + or proposal.get("status") != "applying" + ): + raise ActionConflictError( + "only a claimed operation can record an outcome" + ) + now = _utc_now() + operation["lifecycle_state"] = "outcome_observed" + operation["outcome"] = safe_outcome + proposal["status"] = "applied" + proposal["receipt"] = safe_outcome + proposal["applied_at"] = now + proposal["updated_at"] = now + self._write(payload) + return proposal + + def record_operation_result_delivery( + self, + proposal_id: str, + *, + delivery: Mapping[str, Any], + ) -> dict[str, Any]: + """Persist exact result-card readback without changing domain outcome.""" + + safe_delivery = _safe_json_value( + dict(delivery), path="operation.result_delivery" + ) + if not isinstance(safe_delivery, dict): + raise ValueError("operation result delivery must be an object") + required = { + "provider", + "message_id", + "chat_id", + "app_id", + "card_digest", + "transport", + "delivered_at", + } + if set(safe_delivery) != required: + raise ValueError( + "operation result delivery has unsupported or missing fields" + ) + for field in required: + _bounded_text( + safe_delivery.get(field), + field=f"operation.result_delivery.{field}", + limit=512, + ) + token = _opaque_id(proposal_id, field="proposal_id") + with exclusive_file_lock( + self.path, + agent_id="loopx-chat", + operation="record_operation_result_delivery", + ): + payload = self._read() + proposal = payload["proposals"].get(token) + operation = ( + proposal.get("operation") if isinstance(proposal, dict) else None + ) + if not isinstance(operation, dict): + raise KeyError("typed operation was not found") + if operation.get("lifecycle_state") != "outcome_observed": + raise ActionConflictError( + "operation outcome is unavailable for result delivery" + ) + source_delivery = operation.get("delivery") + if not isinstance(source_delivery, dict) or any( + safe_delivery.get(field) != source_delivery.get(field) + for field in ("provider", "message_id", "chat_id", "app_id") + ): + raise ActionConflictError( + "operation result delivery does not match the original card" + ) + existing = operation.get("result_delivery") + if isinstance(existing, dict): + if existing != safe_delivery: + raise ActionConflictError( + "operation result delivery is already immutable" + ) + return proposal + operation["result_delivery"] = safe_delivery + proposal["updated_at"] = _utc_now() + self._write(payload) + return proposal + def load(self, proposal_id: str) -> dict[str, Any] | None: token = _opaque_id(proposal_id, field="proposal_id") proposal = self._read()["proposals"].get(token) if proposal is None: return None - if not isinstance(proposal, dict) or proposal.get("status") not in PROPOSAL_STATES: + if ( + not isinstance(proposal, dict) + or proposal.get("status") not in PROPOSAL_STATES + ): raise ValueError("typed Chat action proposal is malformed") return proposal @@ -284,7 +711,9 @@ def list( context = context if isinstance(context, dict) else {} parameters = raw.get("normalized_parameters") parameters = parameters if isinstance(parameters, dict) else {} - proposal_goal = str(context.get("goal_id") or parameters.get("goal_id") or "") + proposal_goal = str( + context.get("goal_id") or parameters.get("goal_id") or "" + ) if selected_goal and proposal_goal != selected_goal: continue if selected_context and str(context.get("kind") or "") != selected_context: @@ -314,13 +743,29 @@ def cancel(self, proposal_id: str) -> dict[str, Any]: raise KeyError("typed Chat action proposal was not found") if proposal.get("status") == "cancelled": return proposal - if proposal.get("status") not in {"preview_ready", "gated", "failed", "deferred"}: + if proposal.get("status") not in { + "preview_ready", + "gated", + "failed", + "deferred", + }: raise ActionConflictError( f"proposal in {proposal.get('status')} state cannot be cancelled" ) now = _utc_now() proposal["status"] = "cancelled" proposal["cancelled_at"] = now + operation = proposal.get("operation") + if isinstance(operation, dict): + operation["lifecycle_state"] = "outcome_observed" + operation["outcome"] = { + "schema_version": "loopx_operation_outcome_v0", + "outcome": "cancelled_before_confirmation", + "projection_verified": True, + "observed_at": now, + } + proposal["receipt"] = operation["outcome"] + proposal["gate"] = None proposal["updated_at"] = now self._write(payload) return proposal @@ -336,7 +781,9 @@ def start_apply(self, proposal_id: str) -> dict[str, Any]: idempotent_states={"applying", "applied"}, ) - def mark_gated(self, proposal_id: str, *, gate: Mapping[str, Any]) -> dict[str, Any]: + def mark_gated( + self, proposal_id: str, *, gate: Mapping[str, Any] + ) -> dict[str, Any]: safe_gate = _safe_json_value(dict(gate), path="gate") if not isinstance(safe_gate, dict): raise ValueError("gate must be an object") @@ -399,7 +846,9 @@ def save_checkpoint( f"proposal in {proposal.get('status')} state cannot save a checkpoint" ) checkpoint = proposal.get("checkpoint") - checkpoint = dict(checkpoint) if isinstance(checkpoint, dict) else {"steps": {}} + checkpoint = ( + dict(checkpoint) if isinstance(checkpoint, dict) else {"steps": {}} + ) steps = checkpoint.get("steps") steps = dict(steps) if isinstance(steps, dict) else {} steps[safe_step] = safe_receipt @@ -431,7 +880,9 @@ def mark_deferred(self, proposal_id: str) -> dict[str, Any]: idempotent_states={"deferred"}, ) - def link_regeneration(self, proposal_id: str, *, regenerated_from: str) -> dict[str, Any]: + def link_regeneration( + self, proposal_id: str, *, regenerated_from: str + ) -> dict[str, Any]: token = _opaque_id(proposal_id, field="proposal_id") source = _opaque_id(regenerated_from, field="regenerated_from") with exclusive_file_lock( @@ -473,7 +924,9 @@ def _transition( if status in idempotent_states: return proposal if status not in from_states: - raise ActionConflictError(f"proposal in {status} state cannot become {to_state}") + raise ActionConflictError( + f"proposal in {status} state cannot become {to_state}" + ) proposal["status"] = to_state proposal.update(_safe_json_value(dict(updates), path="transition")) proposal["updated_at"] = _utc_now() @@ -506,7 +959,9 @@ def apply( if status == "applied": return proposal if status not in {"preview_ready", "applying"}: - raise ActionConflictError(f"proposal in {status} state cannot be applied") + raise ActionConflictError( + f"proposal in {status} state cannot be applied" + ) expected_fingerprint = str(proposal.get("expected_state_fingerprint") or "") now = _utc_now() if current_fingerprint != expected_fingerprint: diff --git a/loopx/chat_actions.py b/loopx/chat_actions.py index 457100e119..6c6e1ec108 100644 --- a/loopx/chat_actions.py +++ b/loopx/chat_actions.py @@ -2,6 +2,7 @@ from __future__ import annotations +from datetime import timedelta import hashlib import json from pathlib import Path @@ -41,8 +42,11 @@ "monitor.create", "monitor.update", "gate.resolve", + "operation.execute", } _OPAQUE_ID = re.compile(r"^[A-Za-z0-9._:-]{1,200}$") +_SHA256 = re.compile(r"^[0-9a-f]{64}$") +_AUTHORITY_PRINCIPAL = re.compile(r"^[a-z][a-z0-9._-]{0,30}:[A-Za-z0-9._:-]{1,200}$") # Runtime Endpoint ids and durable Goal agent ids are chosen independently, so # a family token collapses both onto the host that produced them: Endpoint # `codex` has to resolve to a registered `codex-main-control`. Every host that @@ -67,13 +71,18 @@ class ProtectedActionGate(ActionConflictError): """A typed preview is valid while its canonical write needs an explicit gate.""" - def __init__(self, action_kind: str, *, gate: Mapping[str, Any] | None = None) -> None: + def __init__( + self, action_kind: str, *, gate: Mapping[str, Any] | None = None + ) -> None: self.action_kind = action_kind - self.gate = dict(gate or { - "kind": "protected_action", - "summary": f"{action_kind} needs an explicit canonical LoopX write service.", - "next_action": "Keep this preview and complete the protected transition through its canonical LoopX service.", - }) + self.gate = dict( + gate + or { + "kind": "protected_action", + "summary": f"{action_kind} needs an explicit canonical LoopX write service.", + "next_action": "Keep this preview and complete the protected transition through its canonical LoopX service.", + } + ) self.proposal: dict[str, Any] | None = None super().__init__(self.gate["summary"]) @@ -93,7 +102,13 @@ def _text(value: Any, *, field: str, limit: int = 1000) -> str: def _digest(payload: Any) -> str: - stable = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + stable = json.dumps( + payload, + allow_nan=False, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ) return hashlib.sha256(stable.encode("utf-8")).hexdigest() @@ -139,7 +154,13 @@ def _monitor_metadata(parameters: Mapping[str, Any]) -> dict[str, str]: if stop_condition: if parse_timestamp(stop_condition) is not None: metadata["expires_at"] = stop_condition - elif stop_condition.lower() in {"watch_only", "watch-only", "watch", "continuous", "never"}: + elif stop_condition.lower() in { + "watch_only", + "watch-only", + "watch", + "continuous", + "never", + }: metadata["watch_only"] = "true" return metadata @@ -183,7 +204,11 @@ def _registry(self) -> dict[str, Any]: def _goal(self, goal_id: str) -> dict[str, Any]: goal = next( - (goal for goal in registry_goals(self._registry()) if str(goal.get("id") or "") == goal_id), + ( + goal + for goal in registry_goals(self._registry()) + if str(goal.get("id") or "") == goal_id + ), None, ) if goal is None: @@ -217,7 +242,8 @@ def _agent_eligibility( ( item for item in capabilities - if isinstance(item, Mapping) and str(item.get("agent_id") or "") == agent_id + if isinstance(item, Mapping) + and str(item.get("agent_id") or "") == agent_id ), None, ) @@ -230,8 +256,14 @@ def _agent_eligibility( if str(row.get("trust_scope") or "") not in {"read_only", "workspace_write"}: raise ValueError("selected Agent endpoint has an incompatible trust scope") endpoint_registry = getattr(self.runtime_controller, "endpoint_registry", None) - endpoint = endpoint_registry.get(agent_id) if endpoint_registry is not None else None - if endpoint is not None and project is not None and endpoint.location == "remote": + endpoint = ( + endpoint_registry.get(agent_id) if endpoint_registry is not None else None + ) + if ( + endpoint is not None + and project is not None + and endpoint.location == "remote" + ): mapped = endpoint.mapped_work_dir(project) if mapped == project and not endpoint.workspace_mapping: raise ValueError("remote Agent endpoint needs a workspace mapping") @@ -274,7 +306,11 @@ def _resolve_goal_agent(self, goal_id: str, endpoint_id: str) -> str: str(profile.get("adapter_kind") or ""), str(profile.get("provider") or ""), } - if any(self._agent_family(alias) == endpoint_family for alias in aliases if alias): + if any( + self._agent_family(alias) == endpoint_family + for alias in aliases + if alias + ): matches.append(agent_id) if len(matches) == 1: return matches[0] @@ -329,11 +365,199 @@ def _allowed_parameters( raise ValueError(f"unknown typed action parameter: {sorted(unknown)[0]}") return dict(parameters) - def _normalize(self, action_kind: str, parameters: Mapping[str, Any]) -> dict[str, Any]: + def _normalize( + self, action_kind: str, parameters: Mapping[str, Any] + ) -> dict[str, Any]: + if action_kind == "operation.execute": + values = self._allowed_parameters( + parameters, + allowed={ + "schema_version", + "goal_id", + "agent_id", + "domain", + "operation_kind", + "operation_schema", + "payload_ref", + "payload", + "payload_digest", + "projection", + "destination_account_ref", + "expires_at", + "authorized_principals", + "executor", + }, + ) + if values.get("schema_version") != "loopx_operation_request_v0": + raise ValueError( + "operation.execute requires loopx_operation_request_v0" + ) + goal_id = _opaque(values.get("goal_id"), field="goal_id") + goal = self._goal(goal_id) + agent_id = _opaque(values.get("agent_id"), field="agent_id") + if agent_id not in registered_agent_ids_for_goal(goal): + raise ValueError("operation agent_id must be registered for the Goal") + payload = values.get("payload") + if not isinstance(payload, Mapping): + raise ValueError("operation payload must be an object") + payload_digest = str(values.get("payload_digest") or "").strip() + if not _SHA256.fullmatch(payload_digest): + raise ValueError("operation payload_digest must be lowercase SHA-256") + if _digest(payload) != payload_digest: + raise ValueError("operation payload_digest does not match payload") + + projection = values.get("projection") + if not isinstance(projection, Mapping): + raise ValueError("operation projection must be an object") + projection_values = self._allowed_parameters( + projection, + allowed={ + "schema_version", + "title", + "subtitle", + "focus", + "fields", + "warning", + "simulated", + }, + ) + if ( + projection_values.get("schema_version") + != "loopx_operation_projection_v0" + ): + raise ValueError( + "operation projection requires loopx_operation_projection_v0" + ) + normalized_projection: dict[str, Any] = { + "schema_version": "loopx_operation_projection_v0", + "title": _text( + projection_values.get("title"), + field="projection.title", + limit=80, + ), + "subtitle": _text( + projection_values.get("subtitle"), + field="projection.subtitle", + limit=120, + ), + "focus": _text( + projection_values.get("focus"), + field="projection.focus", + limit=120, + ), + "warning": _text( + projection_values.get("warning"), + field="projection.warning", + limit=300, + ), + } + if not isinstance(projection_values.get("simulated"), bool): + raise ValueError("operation projection simulated must be true or false") + normalized_projection["simulated"] = projection_values["simulated"] + raw_fields = projection_values.get("fields") + if not isinstance(raw_fields, list) or not 1 <= len(raw_fields) <= 12: + raise ValueError("operation projection fields must contain 1-12 items") + normalized_fields: list[dict[str, str]] = [] + for index, raw_field in enumerate(raw_fields): + if not isinstance(raw_field, Mapping) or set(raw_field) != { + "label", + "value", + }: + raise ValueError( + f"operation projection field {index + 1} is invalid" + ) + normalized_fields.append( + { + "label": _text( + raw_field.get("label"), + field=f"projection.fields[{index}].label", + limit=40, + ), + "value": _text( + raw_field.get("value"), + field=f"projection.fields[{index}].value", + limit=120, + ), + } + ) + normalized_projection["fields"] = normalized_fields + + raw_executor = values.get("executor") + if not isinstance(raw_executor, Mapping) or set(raw_executor) != { + "extension_id", + "protocol", + "permission", + "revision", + }: + raise ValueError("operation executor binding is invalid") + executor = { + field: _opaque(raw_executor.get(field), field=f"executor.{field}") + for field in ( + "extension_id", + "protocol", + "permission", + "revision", + ) + } + expires_at = parse_timestamp( + _text(values.get("expires_at"), field="expires_at", limit=80) + ) + if expires_at is None: + raise ValueError("operation expires_at must be an ISO-8601 timestamp") + current = now_utc() + if not current < expires_at <= current + timedelta(days=7): + raise ValueError("operation expiry must be within the next seven days") + raw_principals = values.get("authorized_principals") + if ( + not isinstance(raw_principals, list) + or not 1 <= len(raw_principals) <= 20 + ): + raise ValueError( + "operation authorized_principals must contain 1-20 identities" + ) + principals: list[str] = [] + for raw_principal in raw_principals: + principal = str(raw_principal or "").strip() + if not _AUTHORITY_PRINCIPAL.fullmatch(principal): + raise ValueError( + "operation authorized_principals must use provider:subject values" + ) + if principal not in principals: + principals.append(principal) + return { + "schema_version": "loopx_operation_request_v0", + "goal_id": goal_id, + "agent_id": agent_id, + "domain": _opaque(values.get("domain"), field="domain"), + "operation_kind": _opaque( + values.get("operation_kind"), field="operation_kind" + ), + "operation_schema": _opaque( + values.get("operation_schema"), field="operation_schema" + ), + "payload_ref": _opaque(values.get("payload_ref"), field="payload_ref"), + "payload": dict(payload), + "payload_digest": payload_digest, + "projection": normalized_projection, + "projection_digest": _digest(normalized_projection), + "destination_account_ref": _opaque( + values.get("destination_account_ref"), + field="destination_account_ref", + ), + "expires_at": utc_isoformat(expires_at), + "authorized_principals": principals, + "executor": executor, + } if action_kind == "todo.create": values = self._allowed_parameters( parameters, - allowed={"goal_id", "text", "agent_id", "endpoint_id", "start_execution"}, + allowed={ + "goal_id", + "text", + "agent_id", + "endpoint_id", + "start_execution", + }, ) goal_id = _opaque(values.get("goal_id"), field="goal_id") self._goal(goal_id) @@ -390,7 +614,14 @@ def _normalize(self, action_kind: str, parameters: Mapping[str, Any]) -> dict[st "todo_id": _opaque(values.get("todo_id"), field="todo_id"), } operation = str(values.get("operation") or "edit").strip().lower() - if operation not in {"edit", "reassign", "block", "defer", "complete", "successor"}: + if operation not in { + "edit", + "reassign", + "block", + "defer", + "complete", + "successor", + }: raise ValueError( "todo.update operation must be edit, reassign, block, defer, complete, or successor" ) @@ -400,7 +631,9 @@ def _normalize(self, action_kind: str, parameters: Mapping[str, Any]) -> dict[st if values.get("status"): status = str(values["status"]).strip().lower() if status not in {"open", "blocked", "deferred"}: - raise ValueError("todo.update status must be open, blocked, or deferred") + raise ValueError( + "todo.update status must be open, blocked, or deferred" + ) result["status"] = status if values.get("note"): result["note"] = _text(values["note"], field="note", limit=600) @@ -453,7 +686,9 @@ def _normalize(self, action_kind: str, parameters: Mapping[str, Any]) -> dict[st "message": _text(values.get("message"), field="message", limit=4000), } if client_turn_id: - normalized["client_turn_id"] = _opaque(client_turn_id, field="client_turn_id") + normalized["client_turn_id"] = _opaque( + client_turn_id, field="client_turn_id" + ) return normalized if action_kind == "goal.create": values = self._allowed_parameters( @@ -473,7 +708,10 @@ def _normalize(self, action_kind: str, parameters: Mapping[str, Any]) -> dict[st }, ) goal_id = _opaque(values.get("goal_id"), field="goal_id") - if any(str(goal.get("id") or "") == goal_id for goal in registry_goals(self._registry())): + if any( + str(goal.get("id") or "") == goal_id + for goal in registry_goals(self._registry()) + ): raise ValueError("goal_id already exists in the active LoopX registry") result: dict[str, Any] = { "goal_id": goal_id, @@ -516,7 +754,8 @@ def _normalize(self, action_kind: str, parameters: Mapping[str, Any]) -> dict[st if not isinstance(values["initial_todos"], list): raise ValueError("initial_todos must be a list") result["initial_todos"] = [ - _text(item, field="initial_todos", limit=400) for item in values["initial_todos"][:20] + _text(item, field="initial_todos", limit=400) + for item in values["initial_todos"][:20] ] return result if action_kind == "goal.update": @@ -543,7 +782,9 @@ def _normalize(self, action_kind: str, parameters: Mapping[str, Any]) -> dict[st if action_kind == "goal.lifecycle": return self._normalize_goal_lifecycle(parameters) if action_kind == "agent.bind": - values = self._allowed_parameters(parameters, allowed={"goal_id", "agent_id"}) + values = self._allowed_parameters( + parameters, allowed={"goal_id", "agent_id"} + ) goal_id = _opaque(values.get("goal_id"), field="goal_id") self._goal(goal_id) agent_id = _opaque(values.get("agent_id"), field="agent_id") @@ -569,7 +810,9 @@ def _normalize(self, action_kind: str, parameters: Mapping[str, Any]) -> dict[st self._goal(goal_id) operation = str(values.get("operation") or "bind").strip().lower() if operation not in {"bind", "edit", "pause", "resume", "stop"}: - raise ValueError("heartbeat operation must be bind, edit, pause, resume, or stop") + raise ValueError( + "heartbeat operation must be bind, edit, pause, resume, or stop" + ) agent_id = _opaque(values.get("agent_id"), field="agent_id") self._agent_eligibility(agent_id) result: dict[str, Any] = { @@ -580,7 +823,9 @@ def _normalize(self, action_kind: str, parameters: Mapping[str, Any]) -> dict[st if values.get("cadence"): result["cadence"] = _normalize_cadence(values["cadence"]) if values.get("timezone"): - result["timezone"] = _text(values["timezone"], field="timezone", limit=80) + result["timezone"] = _text( + values["timezone"], field="timezone", limit=80 + ) if values.get("stop_condition"): result["stop_condition"] = _text( values["stop_condition"], field="stop_condition", limit=160 @@ -592,7 +837,9 @@ def _normalize(self, action_kind: str, parameters: Mapping[str, Any]) -> dict[st if operation == "bind" and not all( result.get(field) for field in ("cadence", "timezone", "stop_condition") ): - raise ValueError("heartbeat bind requires cadence, timezone, and stop_condition") + raise ValueError( + "heartbeat bind requires cadence, timezone, and stop_condition" + ) if operation == "edit" and len(result) == 3: raise ValueError("heartbeat edit requires a configuration change") return result @@ -624,7 +871,11 @@ def _normalize(self, action_kind: str, parameters: Mapping[str, Any]) -> dict[st if stop_cond_raw: raw_text = _text(stop_cond_raw, field="stop_condition", limit=160) parsed_ts = parse_timestamp(raw_text) - result["stop_condition"] = utc_isoformat(parsed_ts) if parsed_ts is not None else raw_text.lower() + result["stop_condition"] = ( + utc_isoformat(parsed_ts) + if parsed_ts is not None + else raw_text.lower() + ) if values.get("notification_rule"): result["notification_rule"] = _text( values["notification_rule"], field="notification_rule", limit=400 @@ -650,7 +901,9 @@ def _normalize(self, action_kind: str, parameters: Mapping[str, Any]) -> dict[st self._goal(goal_id) operation = str(values.get("operation") or "").strip().lower() if operation not in {"pause", "resume", "stop", "run_now", "edit"}: - raise ValueError("monitor.update operation must be pause, resume, stop, run_now, or edit") + raise ValueError( + "monitor.update operation must be pause, resume, stop, run_now, or edit" + ) result = { "goal_id": goal_id, "todo_id": _opaque(values.get("todo_id"), field="todo_id"), @@ -668,13 +921,21 @@ def _normalize(self, action_kind: str, parameters: Mapping[str, Any]) -> dict[st if values.get("cadence"): result["cadence"] = _normalize_cadence(values["cadence"]) if values.get("stop_condition"): - raw_stop = _text(values["stop_condition"], field="stop_condition", limit=160) + raw_stop = _text( + values["stop_condition"], field="stop_condition", limit=160 + ) parsed_ts = parse_timestamp(raw_stop) - result["stop_condition"] = utc_isoformat(parsed_ts) if parsed_ts is not None else raw_stop.lower() + result["stop_condition"] = ( + utc_isoformat(parsed_ts) + if parsed_ts is not None + else raw_stop.lower() + ) if values.get("session_id"): result["session_id"] = _opaque(values["session_id"], field="session_id") if operation == "edit" and len(result) == 4: - raise ValueError("monitor edit requires target, target_key, cadence, or stop_condition") + raise ValueError( + "monitor edit requires target, target_key, cadence, or stop_condition" + ) return result if action_kind == "gate.resolve": values = self._allowed_parameters( @@ -685,7 +946,9 @@ def _normalize(self, action_kind: str, parameters: Mapping[str, Any]) -> dict[st self._goal(goal_id) decision = str(values.get("decision") or "").strip().lower() if decision not in {"approve", "reject", "cancel", "defer"}: - raise ValueError("gate decision must be approve, reject, cancel, or defer") + raise ValueError( + "gate decision must be approve, reject, cancel, or defer" + ) result = { "goal_id": goal_id, "todo_id": _opaque(values.get("todo_id"), field="todo_id"), @@ -716,7 +979,9 @@ def _session_fingerprint(self, session_id: str, goal_id: str) -> str: } ) - def _project_for_goal_create(self, proposal: Mapping[str, Any]) -> tuple[Path, dict[str, Any]]: + def _project_for_goal_create( + self, proposal: Mapping[str, Any] + ) -> tuple[Path, dict[str, Any]]: parameters = proposal.get("normalized_parameters") context = proposal.get("context") if not isinstance(parameters, Mapping) or not isinstance(context, Mapping): @@ -737,7 +1002,8 @@ def _project_for_goal_create(self, proposal: Mapping[str, Any]) -> tuple[Path, d source_goal = goals[0] if source_goal is None and workspace_ref == "current": workspace_candidates = [ - root for root in self.workspace_roots + root + for root in self.workspace_roots if root.is_dir() and (root / ".git").exists() ] if len(workspace_candidates) == 1: @@ -761,7 +1027,8 @@ def _project_for_goal_create(self, proposal: Mapping[str, Any]) -> tuple[Path, d } elif source_goal is None and workspace_ref.startswith("workspace-"): workspace_candidates = [ - root for root in self.workspace_roots + root + for root in self.workspace_roots if root.is_dir() and (root / ".git").exists() ] selected = next( @@ -788,7 +1055,8 @@ def _project_for_goal_create(self, proposal: Mapping[str, Any]) -> tuple[Path, d } for index, root in enumerate( ( - root for root in self.workspace_roots + root + for root in self.workspace_roots if root.is_dir() and (root / ".git").exists() ), start=1, @@ -821,7 +1089,11 @@ def _apply_goal_create( self, proposal_id: str, proposal: dict[str, Any], parameters: dict[str, Any] ) -> dict[str, Any]: current_fingerprint = self._registry_fingerprint() - heartbeat = parameters.get("heartbeat") if isinstance(parameters.get("heartbeat"), dict) else {} + heartbeat = ( + parameters.get("heartbeat") + if isinstance(parameters.get("heartbeat"), dict) + else {} + ) goal_id = str(parameters["goal_id"]) existing_goal = next( ( @@ -836,7 +1108,9 @@ def _apply_goal_create( source_goal = existing_goal else: project, source_goal = self._project_for_goal_create(proposal) - self._agent_eligibility(str(parameters.get("agent_id") or "codex"), project=project) + self._agent_eligibility( + str(parameters.get("agent_id") or "codex"), project=project + ) self.store.save_checkpoint( proposal_id, step="workspace_validated", @@ -847,7 +1121,9 @@ def _apply_goal_create( ) recovering = existing_goal is not None if recovering: - existing_project = Path(str(existing_goal.get("repo") or "")).expanduser().resolve() + existing_project = ( + Path(str(existing_goal.get("repo") or "")).expanduser().resolve() + ) if existing_project != project: raise ProtectedActionGate( "goal.create", @@ -886,7 +1162,10 @@ def _apply_goal_create( parent_goal_id=str(source_goal.get("id") or "") or None, state_file=None, goal_doc=None, - adapter_kind=str((source_goal.get("adapter") or {}).get("kind") or "generic_project_goal_v0"), + adapter_kind=str( + (source_goal.get("adapter") or {}).get("kind") + or "generic_project_goal_v0" + ), adapter_status="connected", display_name=str(parameters.get("title") or "").strip() or None, onboarding_connection_validation="provider-prevalidated", @@ -930,7 +1209,11 @@ def _apply_goal_create( self.store.save_checkpoint( proposal_id, step="agent_bound", - receipt={"outcome": "agent_bound", "goal_id": goal_id, "agent_id": agent_id}, + receipt={ + "outcome": "agent_bound", + "goal_id": goal_id, + "agent_id": agent_id, + }, ) todo_ids: list[str] = [] for todo_text in parameters.get("initial_todos") or []: @@ -954,7 +1237,9 @@ def _apply_goal_create( ) projected = self._goal(goal_id) if agent_id and agent_id not in registered_agent_ids_for_goal(projected): - raise ValueError("Goal projection did not retain the selected Agent binding") + raise ValueError( + "Goal projection did not retain the selected Agent binding" + ) turn_result: dict[str, Any] | None = None session_id = "" first_turn_gate: dict[str, Any] | None = None @@ -1049,7 +1334,9 @@ def _apply_goal_create( "operation": "bind", "cadence": str(heartbeat.get("cadence") or "1d"), "timezone": str(heartbeat.get("timezone") or "UTC"), - "stop_condition": str(parameters.get("stop_condition") or "goal_complete"), + "stop_condition": str( + parameters.get("stop_condition") or "goal_complete" + ), } child_gate = self._heartbeat_gate(heartbeat_parameters).gate self.store.save_checkpoint( @@ -1058,7 +1345,9 @@ def _apply_goal_create( receipt={"outcome": "heartbeat_gate_ready", "gate": child_gate}, ) receipt = { - "receipt_id": _digest({"proposal_id": proposal_id, "goal_id": goal_id})[:32], + "receipt_id": _digest({"proposal_id": proposal_id, "goal_id": goal_id})[ + :32 + ], "outcome": "goal_created", "projection_verified": True, "resource_ids": { @@ -1087,9 +1376,17 @@ def _apply_agent_bind( goal_id = str(parameters["goal_id"]) agent_id = str(parameters["agent_id"]) existing = registered_agent_ids_for_goal(self._goal(goal_id)) - if agent_id in existing and current_fingerprint != proposal.get("expected_state_fingerprint"): + if agent_id in existing and current_fingerprint != proposal.get( + "expected_state_fingerprint" + ): receipt = { - "receipt_id": _digest({"proposal_id": proposal_id, "goal_id": goal_id, "agent_id": agent_id})[:32], + "receipt_id": _digest( + { + "proposal_id": proposal_id, + "goal_id": goal_id, + "agent_id": agent_id, + } + )[:32], "outcome": "agent_already_bound", "projection_verified": True, "resource_ids": {"goal_id": goal_id, "agent_id": agent_id}, @@ -1116,8 +1413,12 @@ def _apply_agent_bind( if agent_id not in projected: raise ValueError("Agent binding was not visible in the Goal projection") receipt = { - "receipt_id": _digest({"proposal_id": proposal_id, "goal_id": goal_id, "agent_id": agent_id})[:32], - "outcome": "agent_bound" if result.get("changed") else "agent_already_bound", + "receipt_id": _digest( + {"proposal_id": proposal_id, "goal_id": goal_id, "agent_id": agent_id} + )[:32], + "outcome": "agent_bound" + if result.get("changed") + else "agent_already_bound", "projection_verified": True, "resource_ids": {"goal_id": goal_id, "agent_id": agent_id}, } @@ -1140,7 +1441,12 @@ def _heartbeat_gate(self, parameters: dict[str, Any]) -> ProtectedActionGate: ) operation = str(parameters.get("operation") or "bind") gate_receipt = _digest( - {"goal_id": goal_id, "agent_id": agent_id, "operation": operation, "packet": packet} + { + "goal_id": goal_id, + "agent_id": agent_id, + "operation": operation, + "packet": packet, + } )[:32] return ProtectedActionGate( "heartbeat.bind", @@ -1182,11 +1488,14 @@ def _apply_monitor_create( if ( stop_condition and parse_timestamp(stop_condition) is None - and stop_condition.lower() not in {"watch_only", "watch-only", "watch", "continuous", "never"} + and stop_condition.lower() + not in {"watch_only", "watch-only", "watch", "continuous", "never"} ): resume_when = stop_condition metadata = _monitor_metadata(parameters) - if not (metadata.get("expires_at") or resume_when or metadata.get("watch_only")): + if not ( + metadata.get("expires_at") or resume_when or metadata.get("watch_only") + ): metadata["watch_only"] = "true" result = add_goal_todo( registry_path=self.registry_path, @@ -1203,10 +1512,18 @@ def _apply_monitor_create( ) todo_id = _opaque(result.get("todo_id"), field="todo_id") receipt = { - "receipt_id": _digest({"proposal_id": proposal_id, "goal_id": goal_id, "todo_id": todo_id})[:32], - "outcome": "monitor_already_exists" if result.get("already_exists") else "monitor_created", + "receipt_id": _digest( + {"proposal_id": proposal_id, "goal_id": goal_id, "todo_id": todo_id} + )[:32], + "outcome": "monitor_already_exists" + if result.get("already_exists") + else "monitor_created", "projection_verified": True, - "resource_ids": {"goal_id": goal_id, "todo_id": todo_id, "agent_id": agent_id}, + "resource_ids": { + "goal_id": goal_id, + "todo_id": todo_id, + "agent_id": agent_id, + }, } stored = self.store.apply( proposal_id, current_state_fingerprint=current_fingerprint, receipt=receipt @@ -1242,7 +1559,14 @@ def preview(self, request: Mapping[str, Any]) -> dict[str, Any]: eligibility = self._agent_eligibility(agent_id, project=project) else: eligibility = None - if action_kind == "todo.create": + if action_kind == "operation.execute": + fingerprint = _digest(normalized) + evidence = [ + "The provider-neutral operation envelope and immutable digests validated.", + "Execution remains unavailable until an authenticated transport claims this exact request.", + ] + permission = "protected" + elif action_kind == "todo.create": canonical_preview = build_todo_review_preview( registry_path=self.registry_path, goal_id=normalized["goal_id"], @@ -1262,10 +1586,16 @@ def preview(self, request: Mapping[str, Any]) -> dict[str, Any]: canonical_preview = self._run_todo_update(normalized, dry_run=True) if canonical_preview.get("ok") is not True: raise ValueError( - str(canonical_preview.get("error") or "Todo transition failed canonical dry-run validation") + str( + canonical_preview.get("error") + or "Todo transition failed canonical dry-run validation" + ) ) goal_fingerprint = self._goal_state_fingerprint(normalized["goal_id"]) - if action_kind == "monitor.update" and normalized.get("operation") == "run_now": + if ( + action_kind == "monitor.update" + and normalized.get("operation") == "run_now" + ): session_id = normalized.get("session_id") fingerprint = ( _digest( @@ -1289,7 +1619,9 @@ def preview(self, request: Mapping[str, Any]) -> dict[str, Any]: permission = "durable_write" else: fingerprint = self._registry_fingerprint() - evidence = ["Canonical LoopX contracts validated the bounded request shape."] + evidence = [ + "Canonical LoopX contracts validated the bounded request shape." + ] permission = "durable_write" if eligibility is not None: evidence.extend( @@ -1306,10 +1638,20 @@ def preview(self, request: Mapping[str, Any]) -> dict[str, Any]: expected_state_fingerprint=fingerprint, permission_classification=permission, validation_evidence=evidence, - available_transitions=["apply", "cancel"], - idempotency_key=_opaque(request.get("idempotency_key"), field="idempotency_key"), + available_transitions=( + ["cancel"] + if action_kind == "operation.execute" + else ["apply", "cancel"] + ), + idempotency_key=_opaque( + request.get("idempotency_key"), field="idempotency_key" + ), + ) + return ( + self.store.arm_operation(str(proposal["proposal_id"])) + if action_kind == "operation.execute" + else proposal ) - return proposal def load(self, proposal_id: str) -> dict[str, Any] | None: return self.store.load(proposal_id) @@ -1318,15 +1660,44 @@ def cancel(self, proposal_id: str) -> dict[str, Any]: return self.store.cancel(proposal_id) def reject(self, proposal_id: str) -> dict[str, Any]: + proposal = self.store.load(proposal_id) + if proposal is not None and proposal.get("action_kind") == "operation.execute": + raise ProtectedActionGate( + "operation.execute", + gate={ + "kind": "authenticated_operation_decision_required", + "summary": "Operation decisions must come from a bound authenticated surface.", + "next_action": "Use the original operation card to confirm or reject this request.", + }, + ) return self.store.mark_rejected(proposal_id) def defer(self, proposal_id: str) -> dict[str, Any]: + proposal = self.store.load(proposal_id) + if proposal is not None and proposal.get("action_kind") == "operation.execute": + raise ProtectedActionGate( + "operation.execute", + gate={ + "kind": "authenticated_operation_decision_required", + "summary": "Operation decisions must come from a bound authenticated surface.", + "next_action": "Use the original operation card to decide this request.", + }, + ) return self.store.mark_deferred(proposal_id) def regenerate(self, proposal_id: str) -> dict[str, Any]: proposal = self.store.load(proposal_id) if proposal is None: raise KeyError("typed Chat action proposal was not found") + if proposal.get("action_kind") == "operation.execute": + raise ProtectedActionGate( + "operation.execute", + gate={ + "kind": "new_operation_required", + "summary": "Material operation changes require a new immutable request.", + "next_action": "Prepare a new operation instead of regenerating this one.", + }, + ) if proposal.get("status") not in {"stale", "failed", "gated", "rejected"}: raise ActionConflictError( f"proposal in {proposal.get('status')} state cannot be regenerated" @@ -1349,7 +1720,19 @@ def apply(self, proposal_id: str) -> dict[str, Any]: if proposal is None: raise KeyError("typed Chat action proposal was not found") if proposal.get("status") == "applied": - return {"proposal": proposal, "turn": self._turn_from_receipt(proposal.get("receipt"))} + return { + "proposal": proposal, + "turn": self._turn_from_receipt(proposal.get("receipt")), + } + if proposal.get("action_kind") == "operation.execute": + raise ProtectedActionGate( + "operation.execute", + gate={ + "kind": "authenticated_operation_confirmation_required", + "summary": "A local apply request cannot attest a human operation confirmation.", + "next_action": "Confirm the exact request through its authenticated operation card.", + }, + ) proposal = self.store.start_apply(proposal_id) action_kind = str(proposal.get("action_kind") or "") parameters = proposal.get("normalized_parameters") @@ -1388,7 +1771,9 @@ def apply(self, proposal_id: str) -> dict[str, Any]: canonical_receipt = todo_step.get("canonical_receipt") if not isinstance(canonical_receipt, dict): raise ValueError("Todo creation checkpoint is malformed") - current_fingerprint = str(proposal.get("expected_state_fingerprint") or "") + current_fingerprint = str( + proposal.get("expected_state_fingerprint") or "" + ) else: current = build_todo_review_preview( registry_path=self.registry_path, @@ -1454,8 +1839,12 @@ def apply(self, proposal_id: str) -> dict[str, Any]: parameters.get("endpoint_id") or parameters["agent_id"] ) execution_step = steps.get("execution_started") - if isinstance(execution_step, dict) and execution_step.get("session_id"): - session_id = _opaque(execution_step.get("session_id"), field="session_id") + if isinstance(execution_step, dict) and execution_step.get( + "session_id" + ): + session_id = _opaque( + execution_step.get("session_id"), field="session_id" + ) turn_id = _opaque(execution_step.get("turn_id"), field="turn_id") created = False else: @@ -1520,7 +1909,9 @@ def apply(self, proposal_id: str) -> dict[str, Any]: project = Path(str(goal.get("repo") or ".")).expanduser().resolve() if not project.is_dir(): raise ValueError("the Goal project root is unavailable") - client_turn_id = str(parameters.get("client_turn_id") or f"action-{proposal_id}") + client_turn_id = str( + parameters.get("client_turn_id") or f"action-{proposal_id}" + ) turn, created = self.runtime_controller.submit_turn( session_id=str(parameters["session_id"]), client_turn_id=client_turn_id, @@ -1531,7 +1922,11 @@ def apply(self, proposal_id: str) -> dict[str, Any]: turn_id = _opaque(turn.get("turn_id"), field="turn_id") receipt = { "receipt_id": _digest( - {"proposal_id": proposal_id, "session_id": parameters["session_id"], "turn_id": turn_id} + { + "proposal_id": proposal_id, + "session_id": parameters["session_id"], + "turn_id": turn_id, + } )[:32], "outcome": "turn_created" if created else "turn_already_exists", "projection_verified": True, @@ -1548,20 +1943,29 @@ def apply(self, proposal_id: str) -> dict[str, Any]: ) return { "proposal": stored, - "turn": {"turn_id": turn_id, "status": str(turn.get("status") or "queued"), "created": created}, + "turn": { + "turn_id": turn_id, + "status": str(turn.get("status") or "queued"), + "created": created, + }, } raise ValueError(f"unsupported action_kind: {action_kind}") @staticmethod def _turn_from_receipt(receipt: Any) -> dict[str, Any] | None: - if not isinstance(receipt, dict) or not isinstance(receipt.get("resource_ids"), dict): + if not isinstance(receipt, dict) or not isinstance( + receipt.get("resource_ids"), dict + ): return None resource_ids = receipt["resource_ids"] if not resource_ids.get("turn_id"): return None return { - "session_id": str(resource_ids["session_id"]) if resource_ids.get("session_id") else None, + "session_id": str(resource_ids["session_id"]) + if resource_ids.get("session_id") + else None, "turn_id": str(resource_ids["turn_id"]), "status": "accepted", - "created": receipt.get("outcome") in {"turn_created", "task_execution_started"}, + "created": receipt.get("outcome") + in {"turn_created", "task_execution_started"}, } diff --git a/loopx/cli_commands/goal_channel.py b/loopx/cli_commands/goal_channel.py index a3047ecb2d..654eda8b78 100644 --- a/loopx/cli_commands/goal_channel.py +++ b/loopx/cli_commands/goal_channel.py @@ -2,10 +2,14 @@ import argparse import json +import tempfile from collections.abc import Callable, Mapping from pathlib import Path from typing import Any +from ..chat_action_store import ChatActionStore +from ..chat_actions import ChatActionService + from ..extensions.lark import ( LARK_EXTENSION_ID, LARK_GOAL_CHANNEL_PERMISSION, @@ -15,12 +19,11 @@ configure_lark_goal_channel_automation, default_goal_channel_binding_path, default_goal_channel_target_path, - deliver_goal_channel_payload, + deliver_goal_channel_operation_card, doctor_lark_goal_channel, goal_channel_target_for_name, list_goal_channel_targets, notify_lark_goal_channel_gate, - prepare_goal_channel_payload, read_goal_channel_binding, read_goal_channel_targets, setup_lark_goal_channel, @@ -205,28 +208,30 @@ def register_goal_channel_commands( notify.add_argument("--execute", action="store_true") prepare = sub.add_parser( - "prepare-payload", + "prepare-operation", help=( - "Freeze one capability-owned public payload and create its exact " - "approval successor. Dry-run unless --execute." + "Validate and persist one canonical typed-operation proposal. " + "Dry-run unless --execute." ), ) add_subcommand_format(prepare) _add_common_args(prepare) prepare.add_argument("--agent-id", required=True) + prepare.add_argument("--summary", required=True) + prepare.add_argument("--idempotency-key", required=True) prepare.add_argument("--request-json", required=True) prepare.add_argument("--execute", action="store_true") deliver = sub.add_parser( - "deliver-payload", + "deliver-operation", help=( - "Deliver one exactly approved frozen payload through the bound " - "project Bot. Dry-run unless --execute." + "Deliver one canonical typed-operation confirmation card through " + "the bound project Bot. Dry-run unless --execute." ), ) add_subcommand_format(deliver) _add_common_args(deliver) - deliver.add_argument("--receipt-id", required=True) + deliver.add_argument("--proposal-id", required=True) deliver.add_argument("--execute", action="store_true") register_goal_channel_runtime_commands(sub, add_subcommand_format) @@ -436,6 +441,82 @@ def _quota_packet( ) +def _prepare_goal_channel_operation( + *, + registry_path: Path, + runtime_root: Path, + goal_id: str, + agent_id: str, + summary: str, + idempotency_key: str, + request_path: Path, + execute: bool, +) -> dict[str, Any]: + request = json.loads(request_path.read_text(encoding="utf-8")) + if not isinstance(request, dict): + raise ValueError("operation request JSON must be an object") + parameters = {**request, "goal_id": goal_id, "agent_id": agent_id} + + def preview(store_root: Path) -> dict[str, Any]: + return ChatActionService( + store=ChatActionStore(store_root), + registry_path=registry_path, + ).preview( + { + "action_kind": "operation.execute", + "summary": summary, + "idempotency_key": idempotency_key, + "context": {"kind": "goal", "goal_id": goal_id}, + "normalized_parameters": parameters, + } + ) + + durable_store_root = runtime_root / "chat" / "actions" + if execute: + proposal = preview(durable_store_root) + readback = ChatActionStore(durable_store_root).load( + str(proposal["proposal_id"]) + ) + readback_verified = bool( + readback is not None + and readback.get("request_digest") == proposal.get("request_digest") + and readback.get("operation") == proposal.get("operation") + ) + if not readback_verified: + raise ValueError("operation proposal durable readback did not match") + else: + with tempfile.TemporaryDirectory(prefix="loopx-operation-preview-") as root: + proposal = preview(Path(root) / "actions") + readback_verified = False + operation = proposal.get("operation") + if not isinstance(operation, Mapping): + raise ValueError("operation preview did not produce a canonical envelope") + return operation_packet( + ok=True, + goal_id=goal_id, + operation="prepare_operation", + execute=execute, + status="awaiting_confirmation" if execute else "preview_ready", + public_summary=( + "persisted one canonical operation awaiting card delivery" + if execute + else "validated one canonical operation proposal without persistence" + ), + external_write_performed=False, + readback_verified=readback_verified, + idempotency_key=idempotency_key, + receipt_id=str(proposal["proposal_id"]) if execute else None, + details={ + "operation_id": str(proposal["proposal_id"]) if execute else None, + "lifecycle_state": operation["lifecycle_state"], + "confirmation_digest": operation["confirmation_digest"], + "payload_digest": operation["payload_digest"], + "projection_digest": operation["projection_digest"], + "durable_proposal_written": execute, + }, + ) + + def handle_goal_channel_command( args: argparse.Namespace, *, @@ -599,7 +680,7 @@ def handle_goal_channel_command( goal_id=goal_id, binding_path_arg=getattr(args, "binding_path", None), ) - if command in {"prepare-payload", "deliver-payload"}: + if command == "deliver-operation": target_path = _target_path(args, source_runtime_root) target_name = str(getattr(args, "target", None) or "") if not target_name: @@ -692,31 +773,25 @@ def handle_goal_channel_command( ), execute=execute, ) - elif command == "prepare-payload": - request_path = Path(str(args.request_json)).expanduser() - request = json.loads(request_path.read_text(encoding="utf-8")) - if not isinstance(request, dict): - raise ValueError( - "Goal Channel payload request must be an object" - ) - payload = prepare_goal_channel_payload( - request, + elif command == "prepare-operation": + payload = _prepare_goal_channel_operation( registry_path=source_registry_path, runtime_root=source_runtime_root, - binding_path=binding_path, - target_path=target_path, goal_id=goal_id, agent_id=args.agent_id, + summary=args.summary, + idempotency_key=args.idempotency_key, + request_path=Path(str(args.request_json)).expanduser(), execute=execute, ) - elif command == "deliver-payload": - payload = deliver_goal_channel_payload( - receipt_id=args.receipt_id, - registry_path=source_registry_path, + elif command == "deliver-operation": + payload = deliver_goal_channel_operation_card( + proposal_id=args.proposal_id, + action_store_root=source_runtime_root / "chat" / "actions", runtime_root=source_runtime_root, binding_path=binding_path, target_path=target_path, - goal_id=goal_id, + expected_goal_id=goal_id, execute=execute, ) else: diff --git a/loopx/cli_commands/lark_inbox.py b/loopx/cli_commands/lark_inbox.py index fee612784a..90e7aa4614 100644 --- a/loopx/cli_commands/lark_inbox.py +++ b/loopx/cli_commands/lark_inbox.py @@ -765,6 +765,7 @@ def handle_lark_inbox_command( project=args.project, config_path=args.config, lark_cli_executable=args.lark_cli_executable, + runtime_root=runtime_root_arg, node_executable=args.node_executable, ) else: diff --git a/loopx/extensions/lark/README.md b/loopx/extensions/lark/README.md index 05fcff5fba..fe82121fc9 100644 --- a/loopx/extensions/lark/README.md +++ b/loopx/extensions/lark/README.md @@ -11,7 +11,7 @@ evidence, or recovery authority. | `lark-event-inbox` | Collect, inspect, reply to, and acknowledge bounded project feedback | [`event_inbox.py`](event_inbox.py), [`event_collector.py`](event_collector.py) | | `lark-reviewer-notification` | Send and verify a reviewer notification through a project-dedicated Lark app | [`reviewer_notification.py`](reviewer_notification.py) | | `lark-kanban-projection` | Render public-safe LoopX todo and control-plane projections into Lark Base | [`presentation/kanban.py`](presentation/kanban.py) | -| `lark-goal-channel` | Bind one verified Lark group and projection surface to one LoopX goal, including exact-approval delivery of frozen capability payloads | [`goal_channel.py`](goal_channel.py), [`goal_channel_payload.py`](goal_channel_payload.py) | +| `lark-goal-channel` | Bind one verified Lark group and projection surface to one LoopX goal, including authenticated confirmation cards for canonical typed operations | [`goal_channel.py`](goal_channel.py), [`goal_channel_operation.py`](goal_channel_operation.py) | | `lark-explore-projection` | Project canonical Explore results into Lark tables, cards, and whiteboards | [`presentation/explore_results.py`](presentation/explore_results.py) | | `lark-periodic-report-announcement` | Deliver a periodic report through the current Goal Channel's verified project Bot while mentioning only recipients selected by its typed audience plan | [`periodic_report_delivery.py`](periodic_report_delivery.py) | | `lark-periodic-report-source` | Bind and settle one exact Agent-selected Goal Channel source for a typed report action without classifying message text | [`periodic_report_request.py`](periodic_report_request.py) | @@ -71,56 +71,64 @@ collector, processing, reply, reaction, and acknowledgement lifecycle. The [Lark Kanban integration guide](../../../docs/integrations/lark-kanban-control-plane-adapter.md) documents projection configuration and lineage. -### Exact-approval capability payloads +### Human-confirmed typed operations -Any capability may hand LoopX one already public-safe Markdown result without -becoming coupled to Lark. The capability owns domain semantics, citations, and -redaction, and attests `public_safe=true`; LoopX freezes the final card, stores -it only in owner-local runtime state, and creates a blocked delivery Todo plus -an exact user gate. The public Todo stores only an opaque receipt id, digest, -and decision scope. - -Prepare a payload from a local request file: +The Goal Channel may project a canonical `operation.execute` typed-action +proposal as one non-forwardable Card 2.0 confirmation card. The operation +envelope, lifecycle, exact digests, authorized operator set, claim, and outcome +remain in the Core Chat action store; Lark owns only authenticated transport, +callback provenance checks, and result-card readback. It does not create a +second User Todo or approval ledger. ```bash -loopx goal-channel prepare-payload \ - --goal-id \ - --agent-id \ - --request-json - -loopx goal-channel prepare-payload \ +loopx goal-channel prepare-operation \ --goal-id \ --agent-id \ - --request-json \ + --summary "Review one simulated order" \ + --idempotency-key \ + --request-json \ --execute -``` - -The request uses `goal_channel_frozen_payload_request_v0` and supplies one -capability id, opaque payload ref, title, Markdown body, footer, and an exact -`public_claim:action:` decision scope. It cannot select a chat, profile, -Bot, sender, or mention recipient. Complete the generated user gate with -`decision_outcome=approve`, then preview and execute the receipt returned by -prepare: -```bash -loopx goal-channel deliver-payload \ +loopx goal-channel deliver-operation \ --goal-id \ - --receipt-id gcp_ + --proposal-id -loopx goal-channel deliver-payload \ +loopx goal-channel deliver-operation \ --goal-id \ - --receipt-id gcp_ \ + --proposal-id \ --execute ``` -Delivery fails before any provider write when the exact gate is not approved, -the frozen card changes, or the Goal Channel binding changes. Execution uses -only the bound project Bot, scans complete Bot-visible history for the exact -card before sending, and requires provider-native sender, chat, and content -readback. An exact retry therefore reuses the existing message instead of -sending a duplicate. Periodic reports keep their separate standing-subscription -authority and existing two-announcement workflow; they are not routed through -this one-shot approval contract. +The request file contains the provider-neutral `loopx_operation_request_v0` +fields except `goal_id` and `agent_id`, which come from the CLI scope. Preparing +uses the canonical Chat action service and store; it does not create a Lark- or +finance-owned approval ledger. Preview mode validates in an ephemeral store and +writes nothing durable. + +Enable `operation_callbacks.enabled=true` in a v1 event collector config and +install that collector with the pinned LoopX runtime root. The service starts a +separate `card.action.trigger` consumer beside message capture because each +`lark-cli event consume` process owns one EventKey. Collector status reports +listener health separately from real callback evidence; a healthy process does +not prove the application console is configured to deliver callbacks. + +On click, LoopX verifies the original App, chat, message, immutable card digest, +operator allowlist, tenant membership, expiry, and globally unique event id. +Confirmation atomically claims the operation before dispatch. Exact event +replay reuses the existing claim/outcome, and a per-operation dispatch lock +prevents concurrent copies of that callback from invoking the executor twice. +The result update is not complete until the same card is read back with the +expected App, chat, message, and content digest. If that update is acknowledged +but cannot be verified, the canonical outcome remains durable and the collector +retries only the result-card patch after restart. A restart may also resume one +already-claimed request only when its exact executor permission, operation kind, +and destination prove that it is the bundled non-effectful M1 simulation; live or +otherwise effectful domain operations are never retried. Callback health, +recovered simulations, and recovered-result counts remain separate. The initial +finance executor is a +simulation-only optional package: it has no venue, signer, wallet, transfer, or +live-order permission. A successful SDK callback acknowledgement is never +reported as the domain execution receipt. ### Bounded group-history catch-up diff --git a/loopx/extensions/lark/event_collector.py b/loopx/extensions/lark/event_collector.py index 0953ade7b4..85321a78af 100644 --- a/loopx/extensions/lark/event_collector.py +++ b/loopx/extensions/lark/event_collector.py @@ -36,6 +36,7 @@ MAX_ROUTE_COUNT = 50 TURN_START_SYNC_MAX_LOOKBACK_SECONDS = 7 * 24 * 60 * 60 TURN_START_SYNC_MAX_OVERLAP_SECONDS = 5 * 60 +OPERATION_CALLBACK_EVENT_KEY = "card.action.trigger" Runner = Callable[..., subprocess.CompletedProcess[str]] @@ -130,6 +131,20 @@ def load_lark_event_collector_config( ) turn_start_sync_overlap = raw_turn_start_sync.get("overlap_seconds", 5) turn_start_sync_page_size = raw_turn_start_sync.get("page_size", 50) + raw_operation_callbacks = payload.get("operation_callbacks") + if raw_operation_callbacks is not None and not isinstance( + raw_operation_callbacks, Mapping + ): + raise TypeError("collector operation_callbacks must be an object") + raw_operation_callbacks = ( + raw_operation_callbacks if isinstance(raw_operation_callbacks, Mapping) else {} + ) + unknown_operation_callback_fields = set(raw_operation_callbacks) - {"enabled"} + if unknown_operation_callback_fields: + raise ValueError("collector operation_callbacks contains unsupported fields") + operation_callbacks_enabled = raw_operation_callbacks.get("enabled") is True + if operation_callbacks_enabled and schema_version == CONFIG_SCHEMA_VERSION_V0: + raise ValueError("collector operation_callbacks requires config v1") for label, value, lower, upper in ( ( "initial_lookback_seconds", @@ -307,6 +322,10 @@ def load_lark_event_collector_config( "overlap_seconds": turn_start_sync_overlap, "page_size": turn_start_sync_page_size, }, + "operation_callbacks": { + "enabled": operation_callbacks_enabled, + "event_key": OPERATION_CALLBACK_EVENT_KEY, + }, "routes": routes, } @@ -421,6 +440,9 @@ def _plan( runtime_root: str | Path | None = None, ) -> tuple[dict[str, Any], list[str], bytes]: executable = shutil.which(str(config["lark_cli_bin"])) + operation_runtime_missing = bool( + config["operation_callbacks"]["enabled"] and runtime_root is None + ) argv = _collector_argv( config, executable or str(config["lark_cli_bin"]), @@ -429,10 +451,16 @@ def _plan( service_payload = _service_payload(config, argv) return ( { - "ok": True, + "ok": not operation_runtime_missing, "schema_version": PLAN_SCHEMA_VERSION, "enabled": config["enabled"], - "status": "install_ready" if executable else "dependency_missing", + "status": ( + "pinned_runtime_required" + if operation_runtime_missing + else "install_ready" + if executable + else "dependency_missing" + ), "service_name": config["service_name"], "supervisor": config["supervisor"], "event_key": config["event_key"], @@ -446,9 +474,18 @@ def _plan( ), "route_count": len(config["routes"]), "multi_chat_routing": len(config["routes"]) > 1, + "operation_callbacks_enabled": config["operation_callbacks"]["enabled"], + "operation_callback_event_key": ( + config["operation_callbacks"]["event_key"] + if config["operation_callbacks"]["enabled"] + else None + ), + "operation_callback_console_configuration_preflighted": False, "lark_cli_available": executable is not None, "install_hint": ( - None + "Pass the pinned LoopX runtime root for operation callbacks." + if operation_runtime_missing + else None if executable else "Install and configure lark-cli, then rerun the collector plan." ), @@ -498,6 +535,8 @@ def install_lark_event_collector( plan, _, _ = _plan(config, runtime_root=runtime_root) if not config["enabled"]: raise ValueError("cannot install a disabled lark collector") + if plan["ok"] is not True: + return {**plan, "schema_version": INSTALL_SCHEMA_VERSION, "execute": execute} if not plan["lark_cli_available"]: return {**plan, "schema_version": INSTALL_SCHEMA_VERSION, "execute": execute} executable = shutil.which(str(config["lark_cli_bin"])) @@ -615,6 +654,23 @@ def inspect_lark_event_collector( config["supervisor"] != "launchd" or "state = running" in observed.stdout ) installed = service_path.is_file() + callback_status_path = ( + Path(config["project"]) + / ".loopx" + / "runtime" + / "lark-collector" + / "operation-callback-status.json" + ) + callback_status: Mapping[str, Any] = {} + try: + raw_callback_status = json.loads( + callback_status_path.read_text(encoding="utf-8") + ) + if isinstance(raw_callback_status, Mapping): + callback_status = raw_callback_status + except (OSError, json.JSONDecodeError): + pass + callbacks_enabled = config["operation_callbacks"]["enabled"] is True healthy = bool( config["enabled"] and plan["lark_cli_available"] @@ -646,6 +702,23 @@ def inspect_lark_event_collector( "all_routes_real_event_evidence_present": ( routes_with_event_evidence == len(config["routes"]) ), + "operation_callbacks_enabled": callbacks_enabled, + "operation_callback_listener_active": bool( + callbacks_enabled + and active + and callback_status.get("listener_active") is True + ), + "operation_callback_delivery_verified": bool( + callbacks_enabled + and callback_status.get("callback_delivery_verified") is True + ), + "operation_callback_verified_count": int( + callback_status.get("verified_callback_count") or 0 + ), + "operation_callback_last_evidence_at": callback_status.get( + "last_verified_callback_at" + ), + "operation_callback_console_configuration_preflighted": False, "thread_complete": all( route["inbox"]["thread_complete"] for route in config["routes"] ), diff --git a/loopx/extensions/lark/event_collector_runtime.py b/loopx/extensions/lark/event_collector_runtime.py index 84159b3882..b510277217 100644 --- a/loopx/extensions/lark/event_collector_runtime.py +++ b/loopx/extensions/lark/event_collector_runtime.py @@ -4,8 +4,10 @@ import re import signal import subprocess +import threading import time from collections.abc import Callable, Mapping, Sequence +from datetime import datetime, timezone from pathlib import Path from typing import Any @@ -19,6 +21,12 @@ _event_attention_kind, ingest_lark_event_inbox, ) +from .goal_channel_operation import ( + handle_goal_channel_operation_callback, + recover_goal_channel_operation_results, + recover_goal_channel_simulation_claims, +) +from .private_json import write_private_json_atomic APP_ID_PATTERN = re.compile(r"cli_[A-Za-z0-9_-]+") CommandRunner = Callable[..., subprocess.CompletedProcess[str]] @@ -332,6 +340,137 @@ def _consume_argv( ] +def _operation_callback_consume_argv( + config: Mapping[str, Any], command_prefix: Sequence[str] +) -> list[str]: + chat_ids = [str(route["chat_id"]) for route in config["routes"]] + chat_filter = " or ".join( + f".chat_id == {json.dumps(chat_id, ensure_ascii=False)}" for chat_id in chat_ids + ) + return [ + *command_prefix, + "--profile", + str(config["profile"]), + "event", + "consume", + "card.action.trigger", + "--as", + str(config["identity"]), + "--timeout", + str(config["consume_timeout"]), + "--jq", + f"select({chat_filter})", + "--quiet", + ] + + +def _operation_callback_status_path(project: str | Path) -> Path: + return ( + Path(project).expanduser().resolve() + / ".loopx" + / "runtime" + / "lark-collector" + / "operation-callback-status.json" + ) + + +def _read_operation_callback_status(project: str | Path) -> dict[str, Any]: + try: + payload = json.loads( + _operation_callback_status_path(project).read_text(encoding="utf-8") + ) + except (OSError, json.JSONDecodeError): + return {} + return dict(payload) if isinstance(payload, Mapping) else {} + + +def _write_operation_callback_status( + project: str | Path, + *, + listener_active: bool, + callback_delivery_verified: bool | None = None, + failure_kind: str | None = None, + consumer_returncode: int | None = None, + recovered_result_count_delta: int = 0, + result_delivery_failure_count_delta: int = 0, + recovered_simulation_count_delta: int = 0, + simulation_recovery_failure_count_delta: int = 0, +) -> dict[str, Any]: + prior = _read_operation_callback_status(project) + now = datetime.now(timezone.utc).isoformat() + verified_count = int(prior.get("verified_callback_count") or 0) + failure_count = int(prior.get("failed_callback_count") or 0) + recovered_result_count = int(prior.get("recovered_result_count") or 0) + result_delivery_failure_count = int(prior.get("result_delivery_failure_count") or 0) + recovered_simulation_count = int(prior.get("recovered_simulation_count") or 0) + simulation_recovery_failure_count = int( + prior.get("simulation_recovery_failure_count") or 0 + ) + if callback_delivery_verified is True: + verified_count += 1 + if failure_kind: + failure_count += 1 + payload = { + "schema_version": "lark_operation_callback_listener_status_v0", + "listener_active": listener_active, + "callback_delivery_verified": bool( + prior.get("callback_delivery_verified") is True + or callback_delivery_verified is True + ), + "verified_callback_count": verified_count, + "failed_callback_count": failure_count, + "recovered_result_count": ( + recovered_result_count + recovered_result_count_delta + ), + "result_delivery_failure_count": ( + result_delivery_failure_count + result_delivery_failure_count_delta + ), + "recovered_simulation_count": ( + recovered_simulation_count + recovered_simulation_count_delta + ), + "simulation_recovery_failure_count": ( + simulation_recovery_failure_count + simulation_recovery_failure_count_delta + ), + "last_verified_callback_at": ( + now + if callback_delivery_verified is True + else prior.get("last_verified_callback_at") + ), + "last_failure_kind": failure_kind or prior.get("last_failure_kind"), + "consumer_returncode": consumer_returncode, + "updated_at": now, + "private_content_returned": False, + } + write_private_json_atomic(_operation_callback_status_path(project), payload) + return payload + + +def _operation_transport_runner( + runner: CommandRunner, +) -> Callable[[list[str], Path | None, float | None], Mapping[str, Any]]: + def run( + argv: list[str], cwd: Path | None, timeout: float | None + ) -> Mapping[str, Any]: + try: + result = runner( + argv, + cwd=cwd, + capture_output=True, + text=True, + check=False, + timeout=timeout, + ) + except (OSError, subprocess.SubprocessError): + return {"returncode": 1, "stdout": "", "stderr": ""} + return { + "returncode": result.returncode, + "stdout": result.stdout, + "stderr": result.stderr, + } + + return run + + def lark_event_requires_reply_context_lookup( event: Mapping[str, Any], *, bot_display_name: str ) -> bool: @@ -445,6 +584,7 @@ def run_lark_event_collector( project: str | Path, config_path: str | Path, lark_cli_executable: str, + runtime_root: str | Path | None = None, node_executable: str | None = None, runner: CommandRunner = subprocess.run, ) -> dict[str, Any]: @@ -457,18 +597,167 @@ def run_lark_event_collector( if node_executable else _executable_prefix(lark_cli_executable) ) + callbacks_enabled = config["operation_callbacks"]["enabled"] is True + if callbacks_enabled and runtime_root is None: + raise ValueError( + "operation callback collection requires the pinned runtime root" + ) routes_by_chat = {str(route["chat_id"]): route for route in config["routes"]} + resolved_runtime_root = ( + Path(str(runtime_root)).expanduser().resolve() + if runtime_root is not None + else None + ) process = subprocess.Popen( _consume_argv(config, command_prefix), stdout=subprocess.PIPE, text=True, bufsize=1, ) + callback_process: subprocess.Popen[str] | None = None + callback_thread: threading.Thread | None = None + result_recovery_thread: threading.Thread | None = None + result_recovery_stop = threading.Event() + callback_stats = { + "received": 0, + "verified": 0, + "failed": 0, + } + result_recovery_stats = {"attempted": 0, "delivered": 0, "failed": 0} + simulation_recovery_stats = {"attempted": 0, "observed": 0, "failed": 0} + profile_app_id: str | None = None + profile_identity_checked = False + if callbacks_enabled: + profile_app_id = _profile_app_id( + runner=runner, + command_prefix=command_prefix, + profile=str(config["profile"]), + ) + profile_identity_checked = True + callback_process = subprocess.Popen( + _operation_callback_consume_argv(config, command_prefix), + stdout=subprocess.PIPE, + text=True, + bufsize=1, + ) + _write_operation_callback_status( + config["project"], + listener_active=True, + ) + + def consume_operation_callbacks() -> None: + assert callback_process is not None + assert callback_process.stdout is not None + transport_runner = _operation_transport_runner(runner) + for line in callback_process.stdout: + try: + payload = json.loads(line) + except json.JSONDecodeError: + continue + if not isinstance(payload, Mapping): + continue + callback_stats["received"] += 1 + try: + if profile_app_id is None: + raise ValueError( + "collector Bot application identity is unverified" + ) + receipt = handle_goal_channel_operation_callback( + payload, + runtime_root=resolved_runtime_root, + action_store_root=resolved_runtime_root / "chat" / "actions", + profile_app_id=profile_app_id, + cli_bin=lark_cli_executable, + profile=str(config["profile"]), + runner=transport_runner, + ) + if receipt.get("ok") is not True: + raise RuntimeError( + "operation callback result delivery was not verified" + ) + except Exception as exc: # noqa: BLE001 + callback_stats["failed"] += 1 + _write_operation_callback_status( + config["project"], + listener_active=True, + failure_kind=type(exc).__name__, + ) + continue + callback_stats["verified"] += 1 + _write_operation_callback_status( + config["project"], + listener_active=True, + callback_delivery_verified=True, + ) + + callback_thread = threading.Thread( + target=consume_operation_callbacks, + name="loopx-lark-operation-callbacks", + daemon=True, + ) + callback_thread.start() + + def recover_operation_results() -> None: + assert resolved_runtime_root is not None + while not result_recovery_stop.is_set(): + try: + simulation_result = recover_goal_channel_simulation_claims( + action_store_root=resolved_runtime_root / "chat" / "actions", + runtime_root=resolved_runtime_root, + ) + except Exception: # noqa: BLE001 + simulation_result = {"attempted": 1, "observed": 0, "failed": 1} + try: + result = recover_goal_channel_operation_results( + action_store_root=resolved_runtime_root / "chat" / "actions", + profile_app_id=str(profile_app_id or ""), + allowed_chat_ids=set(routes_by_chat), + cli_bin=lark_cli_executable, + profile=str(config["profile"]), + runner=_operation_transport_runner(runner), + ) + except Exception: # noqa: BLE001 + result = {"attempted": 1, "delivered": 0, "failed": 1} + for key in simulation_recovery_stats: + simulation_recovery_stats[key] += int( + simulation_result.get(key) or 0 + ) + for key in result_recovery_stats: + result_recovery_stats[key] += int(result.get(key) or 0) + if ( + result.get("delivered") + or result.get("failed") + or simulation_result.get("observed") + or simulation_result.get("failed") + ): + _write_operation_callback_status( + config["project"], + listener_active=True, + recovered_result_count_delta=int(result.get("delivered") or 0), + result_delivery_failure_count_delta=int( + result.get("failed") or 0 + ), + recovered_simulation_count_delta=int( + simulation_result.get("observed") or 0 + ), + simulation_recovery_failure_count_delta=int( + simulation_result.get("failed") or 0 + ), + ) + result_recovery_stop.wait(3) + + result_recovery_thread = threading.Thread( + target=recover_operation_results, + name="loopx-lark-operation-result-recovery", + daemon=True, + ) + result_recovery_thread.start() previous_handlers: dict[signal.Signals, Any] = {} def forward_signal(signum: int, _: object) -> None: - if process.poll() is None: - process.send_signal(signum) + for child in (process, callback_process): + if child is not None and child.poll() is None: + child.send_signal(signum) for signum in (signal.SIGTERM, signal.SIGINT): previous_handlers[signum] = signal.signal(signum, forward_signal) @@ -477,8 +766,6 @@ def forward_signal(signum: int, _: object) -> None: reply_to_bot_count = 0 self_message_skipped_count = 0 routed_chat_ids: set[str] = set() - profile_app_id: str | None = None - profile_identity_checked = False try: assert process.stdout is not None for line in process.stdout: @@ -570,23 +857,47 @@ def forward_signal(signum: int, _: object) -> None: reply_to_bot_count += int(enriched.get("reply_to_bot") is True) returncode = process.wait() finally: - if process.poll() is None: - process.terminate() + result_recovery_stop.set() + for child in (process, callback_process): + if child is None or child.poll() is not None: + continue + child.terminate() try: - process.wait(timeout=10) + child.wait(timeout=10) except subprocess.TimeoutExpired: - process.kill() - process.wait() + child.kill() + child.wait() + if callback_thread is not None: + callback_thread.join(timeout=10) + if result_recovery_thread is not None: + result_recovery_thread.join(timeout=10) + if callbacks_enabled: + _write_operation_callback_status( + config["project"], + listener_active=False, + consumer_returncode=( + callback_process.returncode + if callback_process is not None + else None + ), + ) for signum, handler in previous_handlers.items(): signal.signal(signum, handler) - return { - "ok": returncode == 0, + callback_returncode = ( + callback_process.returncode if callback_process is not None else 0 + ) + result = { + "ok": returncode == 0 and callback_returncode == 0, "schema_version": ( "lark_event_collector_run_v1" if config["schema_version"] == "lark_event_collector_config_v1" else "lark_event_collector_run_v0" ), - "status": "completed" if returncode == 0 else "consumer_failed", + "status": ( + "completed" + if returncode == 0 and callback_returncode == 0 + else "consumer_failed" + ), "captured_count": captured_count, "route_count": len(config["routes"]), "routed_route_count": len(routed_chat_ids), @@ -607,3 +918,33 @@ def forward_signal(signum: int, _: object) -> None: "local_paths_returned": False, "private_content_returned": False, } + if callbacks_enabled: + result.update( + { + "operation_callback_listener_started": True, + "operation_callback_received_count": callback_stats["received"], + "operation_callback_verified_count": callback_stats["verified"], + "operation_callback_failure_count": callback_stats["failed"], + "operation_callback_consumer_succeeded": callback_returncode == 0, + "operation_callback_console_configuration_preflighted": False, + "operation_result_recovery_attempt_count": result_recovery_stats[ + "attempted" + ], + "operation_result_recovery_verified_count": result_recovery_stats[ + "delivered" + ], + "operation_result_recovery_failure_count": result_recovery_stats[ + "failed" + ], + "operation_simulation_recovery_attempt_count": simulation_recovery_stats[ + "attempted" + ], + "operation_simulation_recovery_observed_count": simulation_recovery_stats[ + "observed" + ], + "operation_simulation_recovery_failure_count": simulation_recovery_stats[ + "failed" + ], + } + ) + return result diff --git a/loopx/extensions/lark/extension.toml b/loopx/extensions/lark/extension.toml index be93114ae6..26b971077f 100644 --- a/loopx/extensions/lark/extension.toml +++ b/loopx/extensions/lark/extension.toml @@ -82,9 +82,9 @@ title = "Lark Goal Channel" status = "active-preview" visibility = "public" real_world_anchor = "one verified Lark group and Kanban projection bound to one LoopX goal" -user_value = "Keep goal progress, human gates, and exactly approved capability results visible in one collaboration channel while LoopX remains the source of truth." +user_value = "Keep goal progress and authenticated human-confirmed operations visible in one collaboration channel while LoopX remains the source of truth." entry_command = "loopx goal-channel setup --provider lark --goal-id " -next_real_step = "Install or upgrade and explicitly enable the bundled provider, configure a Goal Channel, then prepare and approve each non-subscription payload before delivery." +next_real_step = "Install or upgrade the provider, configure a Goal Channel, and enable the separate card callback consumer before delivering typed-operation cards." [[provides]] id = "lark-explore-projection" diff --git a/loopx/extensions/lark/goal_channel.py b/loopx/extensions/lark/goal_channel.py index d7b3fe9a6a..825c38db98 100644 --- a/loopx/extensions/lark/goal_channel.py +++ b/loopx/extensions/lark/goal_channel.py @@ -14,9 +14,11 @@ sync_lark_goal_channel, ) from .goal_channel_setup import setup_lark_goal_channel -from .goal_channel_payload import ( - deliver_goal_channel_payload, - prepare_goal_channel_payload, +from .goal_channel_operation import ( + build_goal_channel_operation_card, + build_goal_channel_operation_result_card, + deliver_goal_channel_operation_card, + handle_goal_channel_operation_callback, ) from .goal_channel_targets import ( GOAL_CHANNEL_TARGETS_SCHEMA_VERSION, @@ -38,9 +40,11 @@ "default_goal_channel_binding_path", "default_goal_channel_target_path", "doctor_lark_goal_channel", - "deliver_goal_channel_payload", + "build_goal_channel_operation_card", + "build_goal_channel_operation_result_card", + "deliver_goal_channel_operation_card", "notify_lark_goal_channel_gate", - "prepare_goal_channel_payload", + "handle_goal_channel_operation_callback", "goal_channel_target_for_name", "list_goal_channel_targets", "read_goal_channel_binding", diff --git a/loopx/extensions/lark/goal_channel_operation.py b/loopx/extensions/lark/goal_channel_operation.py new file mode 100644 index 0000000000..efc0fbf0fe --- /dev/null +++ b/loopx/extensions/lark/goal_channel_operation.py @@ -0,0 +1,1188 @@ +from __future__ import annotations + +from datetime import datetime, timezone +import hashlib +import html +import json +import re +from collections.abc import Callable, Mapping +from pathlib import Path +from typing import Any + +from ...chat_action_store import ActionConflictError, ChatActionStore +from ...file_lock import exclusive_file_lock +from ...extensions.runtime import ( + default_extension_state_file, + execute_extension_runtime_binding, + resolve_extension_binding, +) +from .goal_channel_contracts import operation_packet +from .goal_channel_delivery_contract import ( + goal_channel_binding_digest, + goal_channel_delivery_route, +) +from .goal_channel_message_delivery import ( + GoalChannelMessageDeliverySession, + resolve_bound_goal_channel, +) +from .goal_channel_transport import call, json_payload, lark_args +from .presentation.kanban import CommandRunner, default_subprocess_runner + + +OPERATION_CARD_ACTION_SCHEMA_VERSION = "loopx_operation_card_action_v0" +OPERATION_CALLBACK_RECEIPT_SCHEMA_VERSION = "lark_operation_callback_receipt_v0" +OPERATION_EXECUTOR_CAPABILITY_ID = "human-confirmed-operation-executor" +_EVENT_ID = re.compile(r"^[A-Za-z0-9._:-]{1,240}$") +_MESSAGE_ID = re.compile(r"^om_[A-Za-z0-9_-]+$") +_CHAT_ID = re.compile(r"^oc_[A-Za-z0-9_-]+$") +_OPEN_ID = re.compile(r"^ou_[A-Za-z0-9_-]+$") + + +def _digest(value: object) -> str: + encoded = json.dumps( + value, ensure_ascii=False, sort_keys=True, separators=(",", ":") + ).encode() + return hashlib.sha256(encoded).hexdigest() + + +def _card_text(value: object) -> str: + text = html.escape(str(value or "").strip(), quote=True) + for character, entity in { + "*": "*", + "~": "~", + "[": "[", + "]": "]", + "(": "(", + ")": ")", + "#": "#", + "_": "_", + }.items(): + text = text.replace(character, entity) + return text + + +def _proposal_operation( + proposal: Mapping[str, Any], +) -> tuple[dict[str, Any], dict[str, Any]]: + parameters = proposal.get("normalized_parameters") + operation = proposal.get("operation") + if ( + proposal.get("action_kind") != "operation.execute" + or not isinstance(parameters, dict) + or not isinstance(operation, dict) + ): + raise ValueError("typed operation proposal is unavailable") + return parameters, operation + + +def _field_markdown(fields: list[Mapping[str, Any]]) -> str: + return "\n".join( + f"**{_card_text(field.get('label'))}**\n{_card_text(field.get('value'))}" + for field in fields + ) + + +def build_goal_channel_operation_card( + proposal: Mapping[str, Any], +) -> dict[str, Any]: + parameters, operation = _proposal_operation(proposal) + if operation.get("lifecycle_state") != "awaiting_confirmation": + raise ActionConflictError("operation is not awaiting confirmation") + projection = parameters.get("projection") + if not isinstance(projection, Mapping): + raise ValueError("operation projection is unavailable") + fields = projection.get("fields") + if not isinstance(fields, list) or not all( + isinstance(item, Mapping) for item in fields + ): + raise ValueError("operation projection fields are unavailable") + action_base = { + "schema_version": OPERATION_CARD_ACTION_SCHEMA_VERSION, + "operation_id": operation["operation_id"], + "confirmation_digest": operation["confirmation_digest"], + } + simulated = projection.get("simulated") is True + return { + "schema": "2.0", + "config": { + "update_multi": True, + "width_mode": "default", + "enable_forward": False, + "summary": {"content": str(projection["title"])}, + }, + "header": { + "title": {"tag": "plain_text", "content": str(projection["title"])}, + "subtitle": { + "tag": "plain_text", + "content": str(projection["subtitle"]), + }, + "template": "orange", + "icon": {"tag": "standard_icon", "token": "approval_colorful"}, + "text_tag_list": [ + { + "tag": "text_tag", + "text": { + "tag": "plain_text", + "content": "SIMULATION" if simulated else "待确认", + }, + "color": "yellow" if simulated else "orange", + } + ], + }, + "body": { + "direction": "vertical", + "padding": "12px 12px 20px 12px", + "vertical_spacing": "12px", + "elements": [ + { + "tag": "column_set", + "flex_mode": "none", + "columns": [ + { + "tag": "column", + "width": "weighted", + "weight": 1, + "background_style": "orange-50", + "corner_radius": "8px", + "padding": "12px", + "vertical_spacing": "2px", + "elements": [ + { + "tag": "markdown", + "content": ( + "**请求摘要**\n" + f"{_card_text(projection['focus'])}" + ), + } + ], + } + ], + }, + { + "tag": "column_set", + "flex_mode": "none", + "columns": [ + { + "tag": "column", + "width": "weighted", + "weight": 1, + "background_style": "grey-50", + "corner_radius": "8px", + "padding": "12px", + "vertical_spacing": "4px", + "elements": [ + { + "tag": "markdown", + "content": _field_markdown(fields), + } + ], + } + ], + }, + { + "tag": "column_set", + "flex_mode": "none", + "columns": [ + { + "tag": "column", + "width": "weighted", + "weight": 1, + "background_style": "red-50", + "corner_radius": "8px", + "padding": "12px", + "elements": [ + { + "tag": "markdown", + "content": ( + "**确认边界**\n" + f"{_card_text(projection['warning'])}" + ), + } + ], + } + ], + }, + { + "tag": "column_set", + "flex_mode": "bisect", + "horizontal_spacing": "12px", + "columns": [ + { + "tag": "column", + "elements": [ + { + "tag": "button", + "text": { + "tag": "plain_text", + "content": "确认模拟执行" + if simulated + else "确认执行", + }, + "type": "primary_filled", + "width": "fill", + "behaviors": [ + { + "type": "callback", + "value": { + **action_base, + "decision": "confirm", + }, + } + ], + "confirm": { + "title": { + "tag": "plain_text", + "content": "确认这个精确请求?", + }, + "text": { + "tag": "plain_text", + "content": "修改任何条款都需要创建新请求。", + }, + }, + } + ], + }, + { + "tag": "column", + "elements": [ + { + "tag": "button", + "text": {"tag": "plain_text", "content": "拒绝"}, + "type": "danger", + "width": "fill", + "behaviors": [ + { + "type": "callback", + "value": { + **action_base, + "decision": "reject", + }, + } + ], + } + ], + }, + ], + }, + ], + }, + } + + +def build_goal_channel_operation_result_card( + proposal: Mapping[str, Any], +) -> dict[str, Any]: + parameters, operation = _proposal_operation(proposal) + if operation.get("lifecycle_state") != "outcome_observed": + raise ActionConflictError("operation outcome is not available") + outcome = operation.get("outcome") + projection = parameters.get("projection") + if not isinstance(outcome, Mapping) or not isinstance(projection, Mapping): + raise ValueError("operation result projection is unavailable") + rejected = outcome.get("outcome") == "rejected_by_operator" + simulated = outcome.get("simulation") is True or projection.get("simulated") is True + template = "red" if rejected else "green" + result_label = "已拒绝" if rejected else "模拟完成" if simulated else "已完成" + summary = str(outcome.get("summary") or result_label) + return { + "schema": "2.0", + "config": { + "update_multi": True, + "width_mode": "default", + "enable_forward": False, + "summary": {"content": f"{projection['title']} · {result_label}"}, + }, + "header": { + "title": {"tag": "plain_text", "content": str(projection["title"])}, + "subtitle": { + "tag": "plain_text", + "content": str(projection["subtitle"]), + }, + "template": template, + "icon": {"tag": "standard_icon", "token": "approval_colorful"}, + "text_tag_list": [ + { + "tag": "text_tag", + "text": {"tag": "plain_text", "content": result_label}, + "color": "red" if rejected else "green", + } + ], + }, + "body": { + "direction": "vertical", + "padding": "12px 12px 20px 12px", + "vertical_spacing": "12px", + "elements": [ + { + "tag": "column_set", + "flex_mode": "none", + "columns": [ + { + "tag": "column", + "width": "weighted", + "weight": 1, + "background_style": f"{template}-50", + "corner_radius": "8px", + "padding": "12px", + "elements": [ + { + "tag": "markdown", + "content": f"**{result_label}**\n{_card_text(summary)}", + } + ], + } + ], + }, + { + "tag": "column_set", + "flex_mode": "none", + "columns": [ + { + "tag": "column", + "width": "weighted", + "weight": 1, + "background_style": "grey-50", + "corner_radius": "8px", + "padding": "12px", + "elements": [ + { + "tag": "markdown", + "content": ( + f"**Operation**\n{operation['operation_id']}\n" + f"**Digest**\n{operation['confirmation_digest'][:16]}…" + ), + "text_size": "notation", + } + ], + } + ], + }, + ], + }, + } + + +def deliver_goal_channel_operation_card( + *, + proposal_id: str, + action_store_root: Path, + runtime_root: Path, + binding_path: Path, + target_path: Path, + expected_goal_id: str | None = None, + execute: bool = False, + runner: CommandRunner = default_subprocess_runner, + executor_binding_resolver: ( + Callable[[Mapping[str, Any], Path], Mapping[str, Any]] | None + ) = None, +) -> dict[str, Any]: + store = ChatActionStore(action_store_root) + proposal = store.load(proposal_id) + if proposal is None: + raise ValueError("typed operation proposal was not found") + parameters, operation = _proposal_operation(proposal) + if operation.get("lifecycle_state") != "awaiting_confirmation": + raise ActionConflictError("operation is not awaiting confirmation") + goal_id = str(parameters["goal_id"]) + if expected_goal_id is not None and goal_id != expected_goal_id: + raise ActionConflictError("operation proposal belongs to another goal") + resolved_executor = dict( + executor_binding_resolver(parameters, runtime_root) + if executor_binding_resolver is not None + else _resolve_operation_executor_binding(parameters, runtime_root=runtime_root) + ) + if resolved_executor.get("revision") != parameters["executor"]["revision"]: + raise ActionConflictError("operation executor revision is not ready") + agent_id = str(parameters["agent_id"]) + binding = resolve_bound_goal_channel( + binding_path=binding_path, + target_path=target_path, + goal_id=goal_id, + agent_id=agent_id, + ) + route = goal_channel_delivery_route(goal_id, lambda _goal_id: binding) + card = build_goal_channel_operation_card(proposal) + card_digest = _digest(card) + key = str(operation["confirmation_digest"]) + if not execute: + return operation_packet( + ok=True, + goal_id=goal_id, + operation="deliver_operation_card", + execute=False, + status="pending_execution", + public_summary="validated one exact operation card for Goal Channel delivery", + idempotency_key=key, + receipt_id=proposal_id, + details={ + "operation_id": proposal_id, + "confirmation_digest": key, + "card_digest": card_digest, + "simulation": parameters["projection"]["simulated"] is True, + "executor_preflight_verified": True, + }, + ) + + def resolve_current() -> Mapping[str, Any]: + return resolve_bound_goal_channel( + binding_path=binding_path, + target_path=target_path, + goal_id=goal_id, + agent_id=agent_id, + ) + + session = GoalChannelMessageDeliverySession( + goal_id=goal_id, + binding=binding, + binding_lock_path=binding_path, + target_lock_path=target_path, + history_start_at=str(proposal["created_at"]), + resolve_current_binding=resolve_current, + runner=runner, + ) + if session.verify(route) is not True: + raise ValueError("Goal Channel sender identity could not be verified") + sent = dict(session.send(card, key, route)) + message_id = str(sent.get("message_id") or "") + observed = dict(session.readback(message_id)) + if not ( + observed.get("verified") is True + and observed.get("message_id") == message_id + and observed.get("chat_id") == route["chat_id"] + and observed.get("sender_app_id") == route["bot_app_id"] + ): + return operation_packet( + ok=False, + goal_id=goal_id, + operation="deliver_operation_card", + execute=True, + status="readback_unverified", + public_summary="operation card delivery lacked exact native readback", + external_write_performed=sent.get("external_write_performed") is True, + readback_verified=False, + idempotency_key=key, + receipt_id=proposal_id, + blocker="readback_unverified", + ) + store.record_operation_delivery( + proposal_id, + delivery={ + "provider": "lark", + "message_id": message_id, + "chat_id": route["chat_id"], + "app_id": route["bot_app_id"], + "binding_digest": goal_channel_binding_digest(binding), + "card_digest": card_digest, + "delivered_at": datetime.now(timezone.utc).isoformat(), + }, + ) + return operation_packet( + ok=True, + goal_id=goal_id, + operation="deliver_operation_card", + execute=True, + status="awaiting_confirmation", + public_summary="delivered one exact operation card with native readback", + external_write_performed=sent.get("external_write_performed") is True, + readback_verified=True, + idempotency_key=key, + receipt_id=proposal_id, + details={ + "operation_id": proposal_id, + "confirmation_digest": key, + "card_digest": card_digest, + "semantic_dedupe_status": sent.get("semantic_dedupe_status"), + "executor_preflight_verified": True, + }, + ) + + +def _callback_action(event: Mapping[str, Any]) -> dict[str, str]: + if event.get("type") != "card.action.trigger": + raise ValueError("operation callback event type is unsupported") + if event.get("action_tag") != "button": + raise ValueError("operation callback must come from a button") + raw = event.get("action_value") + try: + value = json.loads(raw) if isinstance(raw, str) else raw + except json.JSONDecodeError as exc: + raise ValueError("operation callback action_value is invalid") from exc + if not isinstance(value, Mapping) or set(value) != { + "schema_version", + "operation_id", + "confirmation_digest", + "decision", + }: + raise ValueError("operation callback action is incomplete") + if value.get("schema_version") != OPERATION_CARD_ACTION_SCHEMA_VERSION: + raise ValueError("operation callback action schema is unsupported") + decision = str(value.get("decision") or "") + if decision not in {"confirm", "reject"}: + raise ValueError("operation callback decision is unsupported") + return {key: str(value[key]) for key in value} + + +def _callback_timestamp(value: object) -> str: + token = str(value or "").strip() + if not token.isdigit() or len(token) > 16: + raise ValueError("operation callback timestamp is invalid") + return ( + datetime.fromtimestamp( + int(token) / 1000, + tz=timezone.utc, + ) + .isoformat() + .replace("+00:00", "Z") + ) + + +def _operator_membership_verified( + *, + runner: CommandRunner, + cli_bin: str, + profile: str, + chat_id: str, + operator_id: str, +) -> bool: + chat_result = call( + runner, + lark_args( + cli_bin=cli_bin, + profile=profile, + tail=[ + "im", + "chats", + "get", + "--chat-id", + chat_id, + "--as", + "bot", + "--format", + "json", + ], + ), + ) + member_result = call( + runner, + lark_args( + cli_bin=cli_bin, + profile=profile, + tail=[ + "im", + "+chat-members-list", + "--chat-id", + chat_id, + "--member-types", + "user", + "--member-id-type", + "open_id", + "--page-all", + "--as", + "bot", + "--format", + "json", + ], + ), + ) + if chat_result.get("returncode") != 0 or member_result.get("returncode") != 0: + return False + chat_payload = json_payload(chat_result) + member_payload = json_payload(member_result) + chat_tenant = _first_tenant_key(chat_payload) + member_tenant = _member_tenant_key(member_payload, operator_id) + return bool(chat_tenant and member_tenant and chat_tenant == member_tenant) + + +def _first_tenant_key(value: object) -> str | None: + if isinstance(value, Mapping): + candidate = value.get("tenant_key") + if isinstance(candidate, str) and candidate: + return candidate + for child in value.values(): + if found := _first_tenant_key(child): + return found + elif isinstance(value, list): + for child in value: + if found := _first_tenant_key(child): + return found + return None + + +def _member_tenant_key(value: object, operator_id: str) -> str | None: + if isinstance(value, Mapping): + identities = { + str(value.get(key) or "") + for key in ("member_id", "open_id", "operator_id", "id") + } + tenant_key = value.get("tenant_key") + if operator_id in identities and isinstance(tenant_key, str) and tenant_key: + return tenant_key + for child in value.values(): + if found := _member_tenant_key(child, operator_id): + return found + elif isinstance(value, list): + for child in value: + if found := _member_tenant_key(child, operator_id): + return found + return None + + +def _resolve_operation_executor_binding( + parameters: Mapping[str, Any], *, runtime_root: Path +) -> dict[str, Any]: + executor = parameters.get("executor") + if not isinstance(executor, Mapping): + raise ValueError("operation executor binding is unavailable") + return resolve_extension_binding( + str(executor["extension_id"]), + state_file=default_extension_state_file(runtime_root), + capability_id=OPERATION_EXECUTOR_CAPABILITY_ID, + protocol=str(executor["protocol"]), + permission=str(executor["permission"]), + ) + + +def _execute_claimed_operation( + proposal: Mapping[str, Any], *, runtime_root: Path +) -> dict[str, Any]: + parameters, operation = _proposal_operation(proposal) + claim = operation.get("claim") + executor = parameters.get("executor") + if not isinstance(claim, Mapping) or not isinstance(executor, Mapping): + raise ValueError("claimed operation executor binding is unavailable") + binding = _resolve_operation_executor_binding( + parameters, + runtime_root=runtime_root, + ) + if binding.get("revision") != executor.get("revision"): + raise ActionConflictError( + "operation executor revision changed after confirmation" + ) + result = execute_extension_runtime_binding( + binding, + request={ + "schema_version": "finance_operation_execute_request_v0", + "protocol": executor["protocol"], + "permission": executor["permission"], + "operation_id": operation["operation_id"], + "operation_kind": parameters["operation_kind"], + "operation_schema": parameters["operation_schema"], + "payload": parameters["payload"], + "payload_digest": operation["payload_digest"], + "confirmation_digest": operation["confirmation_digest"], + "claim_id": claim["claim_id"], + "executor_revision": executor["revision"], + "destination_account_ref": operation["destination_account_ref"], + }, + ) + if ( + result.get("schema_version") != "loopx_operation_outcome_v0" + or result.get("operation_id") != operation["operation_id"] + or result.get("payload_digest") != operation["payload_digest"] + or result.get("claim_id") != claim["claim_id"] + or result.get("executor_revision") != executor["revision"] + or result.get("simulation") is not True + or result.get("external_write_performed") is not False + ): + raise ValueError("operation executor outcome does not match the consumed claim") + return result + + +def _find_message(value: object, message_id: str) -> Mapping[str, Any] | None: + if isinstance(value, Mapping): + if str(value.get("message_id") or "") == message_id: + return value + for child in value.values(): + if found := _find_message(child, message_id): + return found + elif isinstance(value, list): + for child in value: + if found := _find_message(child, message_id): + return found + return None + + +def _message_card(value: Mapping[str, Any]) -> Mapping[str, Any] | None: + body = value.get("body") + raw = body.get("content") if isinstance(body, Mapping) else value.get("content") + try: + card = json.loads(raw) if isinstance(raw, str) else raw + except json.JSONDecodeError: + return None + return card if isinstance(card, Mapping) else None + + +def _result_card_readback_verified( + payload: Mapping[str, Any], + *, + message_id: str, + chat_id: str, + app_id: str, + card: Mapping[str, Any], +) -> bool: + message = _find_message(payload, message_id) + sender = message.get("sender") if isinstance(message, Mapping) else None + observed_card = _message_card(message) if isinstance(message, Mapping) else None + return bool( + payload.get("ok") is True + and isinstance(message, Mapping) + and str(message.get("chat_id") or "") == chat_id + and isinstance(sender, Mapping) + and sender.get("sender_type") == "app" + and sender.get("id") == app_id + and isinstance(observed_card, Mapping) + and _digest(observed_card) == _digest(card) + ) + + +def _read_result_card( + *, + runner: CommandRunner, + cli_bin: str, + profile: str, + message_id: str, +) -> tuple[Mapping[str, Any], bool]: + readback = call( + runner, + lark_args( + cli_bin=cli_bin, + profile=profile, + tail=[ + "im", + "+messages-mget", + "--message-ids", + message_id, + "--as", + "bot", + "--no-reactions", + "--format", + "json", + ], + ), + ) + return json_payload(readback), readback.get("returncode") == 0 + + +def _update_callback_card( + *, + runner: CommandRunner, + cli_bin: str, + profile: str, + token: str, + card: Mapping[str, Any], + message_id: str, + chat_id: str, + app_id: str, +) -> dict[str, bool]: + result = call( + runner, + lark_args( + cli_bin=cli_bin, + profile=profile, + tail=[ + "api", + "POST", + "/open-apis/interactive/v1/card/update", + "--as", + "bot", + "--data", + json.dumps( + {"token": token, "card": dict(card)}, + ensure_ascii=False, + separators=(",", ":"), + ), + ], + ), + ) + payload = json_payload(result) + write_performed = result.get("returncode") == 0 and payload.get("ok") is True + if not write_performed: + return {"external_write_performed": False, "readback_verified": False} + readback_payload, readback_ok = _read_result_card( + runner=runner, + cli_bin=cli_bin, + profile=profile, + message_id=message_id, + ) + verified = bool( + readback_ok + and _result_card_readback_verified( + readback_payload, + message_id=message_id, + chat_id=chat_id, + app_id=app_id, + card=card, + ) + ) + return { + "external_write_performed": True, + "readback_verified": verified, + } + + +def _patch_operation_result_card( + *, + runner: CommandRunner, + cli_bin: str, + profile: str, + card: Mapping[str, Any], + message_id: str, + chat_id: str, + app_id: str, +) -> dict[str, bool]: + result = call( + runner, + lark_args( + cli_bin=cli_bin, + profile=profile, + tail=[ + "im", + "messages", + "patch", + "--message-id", + message_id, + "--data", + json.dumps( + { + "content": json.dumps( + dict(card), + ensure_ascii=False, + separators=(",", ":"), + ) + }, + ensure_ascii=False, + separators=(",", ":"), + ), + "--as", + "bot", + "--format", + "json", + ], + ), + ) + payload = json_payload(result) + write_performed = result.get("returncode") == 0 and payload.get("ok") is True + if not write_performed: + return {"external_write_performed": False, "readback_verified": False} + readback_payload, readback_ok = _read_result_card( + runner=runner, + cli_bin=cli_bin, + profile=profile, + message_id=message_id, + ) + verified = readback_ok and _result_card_readback_verified( + readback_payload, + message_id=message_id, + chat_id=chat_id, + app_id=app_id, + card=card, + ) + return { + "external_write_performed": True, + "readback_verified": verified, + } + + +def recover_goal_channel_operation_results( + *, + action_store_root: Path, + profile_app_id: str, + allowed_chat_ids: set[str], + cli_bin: str, + profile: str, + runner: CommandRunner = default_subprocess_runner, + limit: int = 20, +) -> dict[str, int]: + """Retry only result-card delivery; never repeat a domain execution.""" + + store = ChatActionStore(action_store_root) + attempted = 0 + delivered = 0 + failed = 0 + for proposal in store.list(): + if attempted >= max(1, min(limit, 100)): + break + if proposal.get("action_kind") != "operation.execute": + continue + _parameters, operation = _proposal_operation(proposal) + delivery = operation.get("delivery") + if ( + operation.get("lifecycle_state") != "outcome_observed" + or isinstance(operation.get("result_delivery"), Mapping) + or not isinstance(delivery, Mapping) + or delivery.get("provider") != "lark" + or delivery.get("app_id") != profile_app_id + or delivery.get("chat_id") not in allowed_chat_ids + ): + continue + attempted += 1 + result_lock = store.root / f"{proposal['proposal_id']}.result-delivery.lock" + with exclusive_file_lock( + result_lock, + agent_id="loopx-lark-operation", + operation="recover_operation_result_delivery", + ): + current = store.load(str(proposal["proposal_id"])) + if current is None: + failed += 1 + continue + _current_parameters, current_operation = _proposal_operation(current) + if isinstance(current_operation.get("result_delivery"), Mapping): + continue + current_delivery = current_operation.get("delivery") + if not isinstance(current_delivery, Mapping): + failed += 1 + continue + result_card = build_goal_channel_operation_result_card(current) + result = _patch_operation_result_card( + runner=runner, + cli_bin=cli_bin, + profile=profile, + card=result_card, + message_id=str(current_delivery["message_id"]), + chat_id=str(current_delivery["chat_id"]), + app_id=str(current_delivery["app_id"]), + ) + if result["readback_verified"] is not True: + failed += 1 + continue + store.record_operation_result_delivery( + str(proposal["proposal_id"]), + delivery={ + "provider": "lark", + "message_id": str(current_delivery["message_id"]), + "chat_id": str(current_delivery["chat_id"]), + "app_id": str(current_delivery["app_id"]), + "card_digest": _digest(result_card), + "transport": "message_patch", + "delivered_at": datetime.now(timezone.utc).isoformat(), + }, + ) + delivered += 1 + return {"attempted": attempted, "delivered": delivered, "failed": failed} + + +def recover_goal_channel_simulation_claims( + *, + action_store_root: Path, + runtime_root: Path, + limit: int = 20, +) -> dict[str, int]: + """Resume only explicitly non-effectful M1 simulation claims after restart.""" + + store = ChatActionStore(action_store_root) + attempted = 0 + observed = 0 + failed = 0 + for proposal in store.list(status="applying"): + if attempted >= max(1, min(limit, 100)): + break + if proposal.get("action_kind") != "operation.execute": + continue + parameters, operation = _proposal_operation(proposal) + executor = parameters.get("executor") + if ( + operation.get("lifecycle_state") != "claimed" + or not isinstance(executor, Mapping) + or executor.get("permission") != "finance.operation.simulate" + or parameters.get("operation_kind") != "finance.order.simulate" + or operation.get("destination_account_ref") != "account:simulation" + ): + continue + attempted += 1 + dispatch_lock = store.root / f"{proposal['proposal_id']}.dispatch.lock" + with exclusive_file_lock( + dispatch_lock, + agent_id="loopx-lark-operation", + operation="recover_claimed_simulation", + ): + current = store.load(str(proposal["proposal_id"])) + if current is None: + failed += 1 + continue + _current_parameters, current_operation = _proposal_operation(current) + if current_operation.get("lifecycle_state") != "claimed": + continue + try: + outcome = _execute_claimed_operation( + current, + runtime_root=runtime_root, + ) + store.observe_operation_outcome( + str(proposal["proposal_id"]), outcome=outcome + ) + except (ActionConflictError, OSError, RuntimeError, ValueError): + failed += 1 + continue + observed += 1 + return {"attempted": attempted, "observed": observed, "failed": failed} + + +def handle_goal_channel_operation_callback( + event: Mapping[str, Any], + *, + runtime_root: Path, + action_store_root: Path, + profile_app_id: str, + cli_bin: str, + profile: str, + runner: CommandRunner = default_subprocess_runner, + executor: Callable[[Mapping[str, Any]], Mapping[str, Any]] | None = None, +) -> dict[str, Any]: + action = _callback_action(event) + callback_token = str(event.get("token") or "").strip() + if ( + not callback_token + or len(callback_token) > 2048 + or any(ord(character) < 32 for character in callback_token) + ): + raise ValueError("operation callback update token is invalid") + for field, pattern in ( + ("event_id", _EVENT_ID), + ("message_id", _MESSAGE_ID), + ("chat_id", _CHAT_ID), + ("operator_id", _OPEN_ID), + ): + if not pattern.fullmatch(str(event.get(field) or "")): + raise ValueError(f"operation callback {field} is invalid") + if str(event.get("host") or "") != "im_message": + raise ValueError("operation callback host is unsupported") + card_content = event.get("card_content") + try: + card = json.loads(card_content) if isinstance(card_content, str) else None + except json.JSONDecodeError as exc: + raise ValueError("operation callback card_content is invalid") from exc + if not isinstance(card, Mapping): + raise ValueError("operation callback requires exact card_content") + store = ChatActionStore(action_store_root) + proposal = store.load(action["operation_id"]) + if proposal is None: + raise ValueError("operation callback proposal was not found") + parameters, operation = _proposal_operation(proposal) + delivery = operation.get("delivery") + if not isinstance(delivery, Mapping): + raise ActionConflictError("operation card delivery was not recorded") + if action["confirmation_digest"] != operation.get("confirmation_digest"): + raise ActionConflictError("operation callback digest drifted") + if _digest(card) != delivery.get("card_digest"): + raise ActionConflictError("operation callback card content drifted") + if profile_app_id != delivery.get("app_id"): + raise ActionConflictError("operation callback app identity drifted") + operator_id = str(event["operator_id"]) + operator_principal = f"lark:{operator_id}" + chat_id = str(event["chat_id"]) + if operator_principal not in set(parameters.get("authorized_principals") or []): + raise ActionConflictError("principal is not authorized for this operation") + if not _operator_membership_verified( + runner=runner, + cli_bin=cli_bin, + profile=profile, + chat_id=chat_id, + operator_id=operator_id, + ): + raise ActionConflictError("operation callback tenant membership is unverified") + decided = store.decide_operation( + action["operation_id"], + decision=action["decision"], + confirmation={ + "provider": "lark", + "event_id": str(event["event_id"]), + "principal": operator_principal, + "message_id": str(event["message_id"]), + "chat_id": chat_id, + "app_id": profile_app_id, + "surface_kind": "group_message_card", + "interaction_kind": "button_callback", + "confirmation_digest": action["confirmation_digest"], + "card_digest": str(delivery["card_digest"]), + "confirmed_at": _callback_timestamp(event.get("timestamp")), + }, + ) + dispatch_lock = store.root / f"{action['operation_id']}.dispatch.lock" + with exclusive_file_lock( + dispatch_lock, + agent_id="loopx-lark-operation", + operation="dispatch_claimed_operation", + ): + current = store.load(action["operation_id"]) + if current is None: + raise ValueError("claimed operation disappeared before dispatch") + _parameters, current_operation = _proposal_operation(current) + if current_operation.get("lifecycle_state") == "claimed": + outcome = dict( + executor(current) + if executor is not None + else _execute_claimed_operation(current, runtime_root=runtime_root) + ) + current = store.observe_operation_outcome( + action["operation_id"], outcome=outcome + ) + decided = current + result_lock = store.root / f"{action['operation_id']}.result-delivery.lock" + with exclusive_file_lock( + result_lock, + agent_id="loopx-lark-operation", + operation="deliver_operation_callback_result", + ): + current = store.load(action["operation_id"]) + if current is None: + raise ValueError("operation disappeared before result delivery") + decided = current + result_card = build_goal_channel_operation_result_card(decided) + if isinstance(decided["operation"].get("result_delivery"), Mapping): + update = {"external_write_performed": False, "readback_verified": True} + else: + update = _update_callback_card( + runner=runner, + cli_bin=cli_bin, + profile=profile, + token=callback_token, + card=result_card, + message_id=str(delivery["message_id"]), + chat_id=str(delivery["chat_id"]), + app_id=str(delivery["app_id"]), + ) + if update["readback_verified"] is True: + decided = store.record_operation_result_delivery( + action["operation_id"], + delivery={ + "provider": "lark", + "message_id": str(delivery["message_id"]), + "chat_id": str(delivery["chat_id"]), + "app_id": str(delivery["app_id"]), + "card_digest": _digest(result_card), + "transport": "callback_update", + "delivered_at": datetime.now(timezone.utc).isoformat(), + }, + ) + update_verified = update["readback_verified"] + return { + "ok": update_verified, + "schema_version": OPERATION_CALLBACK_RECEIPT_SCHEMA_VERSION, + "operation_id": action["operation_id"], + "decision": action["decision"], + "lifecycle_state": decided["operation"]["lifecycle_state"], + "outcome": decided["operation"]["outcome"]["outcome"], + "claim_id": ( + decided["operation"]["claim"]["claim_id"] + if isinstance(decided["operation"].get("claim"), Mapping) + else None + ), + "callback_ack_is_execution_receipt": False, + "card_update_verified": update_verified, + "status": "outcome_observed" if update_verified else "result_delivery_pending", + "domain_external_write_performed": bool( + decided["operation"]["outcome"].get("external_write_performed") is True + ), + "external_write_performed": update["external_write_performed"], + } + + +__all__ = [ + "build_goal_channel_operation_card", + "build_goal_channel_operation_result_card", + "deliver_goal_channel_operation_card", + "handle_goal_channel_operation_callback", + "recover_goal_channel_operation_results", + "recover_goal_channel_simulation_claims", +] diff --git a/loopx/extensions/lark/goal_channel_payload.py b/loopx/extensions/lark/goal_channel_payload.py deleted file mode 100644 index 1cfe20ac93..0000000000 --- a/loopx/extensions/lark/goal_channel_payload.py +++ /dev/null @@ -1,535 +0,0 @@ -from __future__ import annotations - -import hashlib -import json -import re -from collections.abc import Mapping -from datetime import datetime, timezone -from pathlib import Path -from typing import Any - -from ...control_plane.todos.contract import ( - normalize_todo_claimed_by, - normalize_todo_decision_scope, -) -from ...todos import add_goal_todo, complete_goal_todo, list_goal_todos -from .goal_channel_contracts import operation_packet -from .goal_channel_delivery_contract import ( - goal_channel_binding_digest, - goal_channel_delivery_route, -) -from .goal_channel_message_delivery import ( - GoalChannelMessageDeliverySession, - resolve_bound_goal_channel, -) -from .outbound import normalize_lark_outbound_text -from .presentation.kanban import CommandRunner, default_subprocess_runner -from .presentation.message_card import build_lark_markdown_reply_card -from .private_json import write_private_json_atomic - - -FROZEN_PAYLOAD_REQUEST_SCHEMA = "goal_channel_frozen_payload_request_v0" -FROZEN_PAYLOAD_RECEIPT_SCHEMA = "goal_channel_frozen_payload_receipt_v0" -_RECEIPT_ID_RE = re.compile(r"^gcp_[0-9a-f]{24}$") -_TOKEN_RE = re.compile(r"^[a-z][a-z0-9_.:-]{1,127}$") -_DIGEST_RE = re.compile(r"^sha256:[0-9a-f]{64}$") - - -def _canonical_digest(value: object) -> str: - encoded = json.dumps( - value, ensure_ascii=False, sort_keys=True, separators=(",", ":") - ).encode("utf-8") - return "sha256:" + hashlib.sha256(encoded).hexdigest() - - -def _required_text(value: object, label: str, *, maximum: int) -> str: - text = str(value or "").strip() - if not text: - raise ValueError(f"{label} is required") - if len(text) > maximum: - raise ValueError(f"{label} exceeds {maximum} characters") - return text - - -def _token(value: object, label: str) -> str: - token = str(value or "").strip().lower() - if not _TOKEN_RE.fullmatch(token): - raise ValueError(f"{label} must be a public-safe opaque token") - return token - - -def _decision_scope_text(scope: Mapping[str, Any]) -> str: - return f"{scope['kind']}:{scope['granularity']}:{scope['scope_key']}" - - -def _normalized_request(request: Mapping[str, Any]) -> dict[str, Any]: - allowed = { - "schema_version", - "capability_id", - "payload_ref", - "title", - "markdown", - "footer", - "decision_scope", - "public_safe", - } - extra = sorted(set(request) - allowed) - if extra: - raise ValueError(f"frozen payload request contains unsupported fields: {extra}") - if request.get("schema_version") != FROZEN_PAYLOAD_REQUEST_SCHEMA: - raise ValueError(f"request must use {FROZEN_PAYLOAD_REQUEST_SCHEMA}") - if request.get("public_safe") is not True: - raise ValueError( - "producing capability must attest that the frozen payload is public-safe" - ) - scope = normalize_todo_decision_scope(request.get("decision_scope")) - if ( - scope is None - or scope["kind"] != "public_claim" - or scope["granularity"] != "action" - or "*" in scope["scope_key"] - ): - raise ValueError( - "frozen Goal Channel payload requires a public_claim:action decision scope" - ) - title = _required_text(request.get("title"), "title", maximum=72) - footer = _required_text(request.get("footer"), "footer", maximum=96) - markdown = normalize_lark_outbound_text( - request.get("markdown"), limit=3600, preserve_format=True - ) - if re.search(r"<\s*at\b", markdown, re.IGNORECASE): - raise ValueError("frozen Goal Channel payload must not contain mentions") - card = build_lark_markdown_reply_card( - markdown, title=title, footer=footer, max_markdown_chars=3600 - ) - return { - "capability_id": _token(request.get("capability_id"), "capability_id"), - "payload_ref": _token(request.get("payload_ref"), "payload_ref"), - "title": title, - "markdown": markdown, - "footer": footer, - "decision_scope": scope, - "card": card, - "payload_digest": _canonical_digest(card), - } - - -def _receipt_identity( - *, - goal_id: str, - request: Mapping[str, Any], - binding_digest: str, - agent_id: str, -) -> str: - digest = _canonical_digest( - { - "goal_id": goal_id, - "capability_id": request["capability_id"], - "payload_ref": request["payload_ref"], - "payload_digest": request["payload_digest"], - "decision_scope": request["decision_scope"], - "binding_digest": binding_digest, - "agent_id": agent_id, - } - ) - return "gcp_" + digest.removeprefix("sha256:")[:24] - - -def _receipt_path(runtime_root: Path, goal_id: str, receipt_id: str) -> Path: - if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,159}", goal_id): - raise ValueError("goal_id must be a stable LoopX Goal id") - if not _RECEIPT_ID_RE.fullmatch(receipt_id): - raise ValueError("receipt_id must be a Goal Channel frozen payload id") - return ( - runtime_root - / "goals" - / goal_id - / "goal_channel_payloads" - / f"{receipt_id}.json" - ) - - -def _read_receipt(runtime_root: Path, goal_id: str, receipt_id: str) -> dict[str, Any]: - path = _receipt_path(runtime_root, goal_id, receipt_id) - try: - payload = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError) as exc: - raise ValueError("Goal Channel frozen payload receipt is unavailable") from exc - if ( - not isinstance(payload, dict) - or payload.get("schema_version") != FROZEN_PAYLOAD_RECEIPT_SCHEMA - or payload.get("receipt_id") != receipt_id - or payload.get("goal_id") != goal_id - ): - raise ValueError("Goal Channel frozen payload receipt is invalid") - card = payload.get("card") - scope = normalize_todo_decision_scope(payload.get("decision_scope")) - if ( - not isinstance(card, Mapping) - or _canonical_digest(card) != payload.get("payload_digest") - or not _DIGEST_RE.fullmatch(str(payload.get("payload_digest") or "")) - or not _DIGEST_RE.fullmatch(str(payload.get("binding_digest") or "")) - or scope is None - or scope["kind"] != "public_claim" - or scope["granularity"] != "action" - or payload.get("status") not in {"approval_pending", "satisfied"} - or _receipt_identity( - goal_id=goal_id, - request=payload, - binding_digest=str(payload.get("binding_digest") or ""), - agent_id=str(payload.get("agent_id") or ""), - ) - != receipt_id - ): - raise ValueError("Goal Channel frozen payload receipt content drifted") - return payload - - -def prepare_goal_channel_payload( - request: Mapping[str, Any], - *, - registry_path: Path, - runtime_root: Path, - binding_path: Path, - target_path: Path, - goal_id: str, - agent_id: str, - execute: bool = False, -) -> dict[str, Any]: - """Freeze one capability-owned public payload behind an exact user gate.""" - - normalized_agent_id = normalize_todo_claimed_by(agent_id) - if normalized_agent_id is None: - raise ValueError("agent_id must be a valid Todo agent id") - normalized = _normalized_request(request) - binding = resolve_bound_goal_channel( - binding_path=binding_path, - target_path=target_path, - goal_id=goal_id, - agent_id=normalized_agent_id, - ) - binding_digest = goal_channel_binding_digest(binding) - receipt_id = _receipt_identity( - goal_id=goal_id, - request=normalized, - binding_digest=binding_digest, - agent_id=normalized_agent_id, - ) - receipt_path = _receipt_path(runtime_root, goal_id, receipt_id) - if receipt_path.exists(): - receipt = _read_receipt(runtime_root, goal_id, receipt_id) - return operation_packet( - ok=True, - goal_id=goal_id, - operation="prepare_payload", - execute=execute, - status=str(receipt["status"]), - public_summary="reused the exact frozen Goal Channel payload", - idempotency_key=receipt_id, - receipt_id=receipt_id, - details={ - "capability_id": receipt["capability_id"], - "payload_digest": receipt["payload_digest"], - "decision_scope": _decision_scope_text(receipt["decision_scope"]), - "delivery_todo_id": receipt["delivery_todo_id"], - "approval_todo_id": receipt["approval_todo_id"], - "already_prepared": True, - }, - ) - - scope_text = _decision_scope_text(normalized["decision_scope"]) - digest_suffix = normalized["payload_digest"].removeprefix("sha256:")[:16] - delivery = add_goal_todo( - registry_path=registry_path, - goal_id=goal_id, - role="agent", - text=f"[P0] Deliver frozen Goal Channel payload {receipt_id}.", - status="blocked", - note=( - "Use only the frozen private receipt and the unchanged project_bot " - "Goal Channel binding; require exact provider-native readback." - ), - task_class="advancement_task", - action_kind="deliver_goal_channel_payload", - task_domain="provider_delivery", - capability_binding_ref=f"goal-channel:g{digest_suffix}", - required_write_scopes=["goal_channel/lark/messages"], - required_capabilities=["network", "lark_bot_message_write"], - target_capabilities=[normalized["capability_id"], "goal_channel"], - required_decision_scopes=[scope_text], - claimed_by=normalized_agent_id, - agent_id=normalized_agent_id, - runtime_root_arg=str(runtime_root), - dry_run=not execute, - ) - gate = add_goal_todo( - registry_path=registry_path, - goal_id=goal_id, - role="user", - text=( - "Approve the exact frozen public payload " - f"{receipt_id} ({normalized['payload_digest']}) for Goal Channel delivery." - ), - note=( - "Approval covers only this frozen card digest and current Goal Channel " - "binding; rejection or cancellation keeps delivery blocked." - ), - task_class="user_gate", - action_kind="approve_goal_channel_payload", - decision_scope=scope_text, - bound_agent=normalized_agent_id, - blocks_agent=normalized_agent_id, - unblocks_todo_id=str(delivery["todo_id"]), - agent_id=normalized_agent_id, - runtime_root_arg=str(runtime_root), - dry_run=not execute, - ) - receipt = { - "schema_version": FROZEN_PAYLOAD_RECEIPT_SCHEMA, - "receipt_id": receipt_id, - "goal_id": goal_id, - "capability_id": normalized["capability_id"], - "payload_ref": normalized["payload_ref"], - "payload_digest": normalized["payload_digest"], - "decision_scope": normalized["decision_scope"], - "binding_digest": binding_digest, - "agent_id": normalized_agent_id, - "created_at": datetime.now(timezone.utc).isoformat(), - "title": normalized["title"], - "markdown": normalized["markdown"], - "footer": normalized["footer"], - "card": normalized["card"], - "delivery_todo_id": delivery["todo_id"], - "approval_todo_id": gate["todo_id"], - "status": "approval_pending", - "delivery": None, - } - if execute: - write_private_json_atomic(receipt_path, receipt) - return operation_packet( - ok=True, - goal_id=goal_id, - operation="prepare_payload", - execute=execute, - status="approval_pending" if execute else "pending_execution", - public_summary=( - "froze one Goal Channel payload and created its exact approval gate" - if execute - else "validated one Goal Channel payload preparation" - ), - idempotency_key=receipt_id, - receipt_id=receipt_id, - details={ - "capability_id": normalized["capability_id"], - "payload_digest": normalized["payload_digest"], - "decision_scope": scope_text, - "delivery_todo_id": delivery["todo_id"], - "approval_todo_id": gate["todo_id"], - "already_prepared": False, - }, - ) - - -def _todo( - *, registry_path: Path, runtime_root: Path, goal_id: str, todo_id: str -) -> dict[str, Any] | None: - payload = list_goal_todos( - registry_path=registry_path, - goal_id=goal_id, - todo_id=todo_id, - runtime_root_arg=str(runtime_root), - ) - todo = payload.get("todo") - return dict(todo) if isinstance(todo, Mapping) else None - - -def _approval_verified( - *, receipt: Mapping[str, Any], registry_path: Path, runtime_root: Path -) -> tuple[dict[str, Any], dict[str, Any]]: - goal_id = str(receipt["goal_id"]) - delivery = _todo( - registry_path=registry_path, - runtime_root=runtime_root, - goal_id=goal_id, - todo_id=str(receipt["delivery_todo_id"]), - ) - gate = _todo( - registry_path=registry_path, - runtime_root=runtime_root, - goal_id=goal_id, - todo_id=str(receipt["approval_todo_id"]), - ) - expected_scope = normalize_todo_decision_scope(receipt["decision_scope"]) - expected_binding_ref = ( - "goal-channel:g" + str(receipt["payload_digest"]).removeprefix("sha256:")[:16] - ) - agent_id = str(receipt["agent_id"]) - if delivery is None or gate is None or expected_scope is None: - raise ValueError("frozen Goal Channel approval lifecycle is unavailable") - if ( - gate.get("status") != "done" - or gate.get("decision_outcome") != "approve" - or normalize_todo_decision_scope(gate.get("decision_scope")) != expected_scope - or gate.get("unblocks_todo_id") != delivery.get("todo_id") - or gate.get("action_kind") != "approve_goal_channel_payload" - or gate.get("blocks_agent") != agent_id - or gate.get("bound_agent") != agent_id - or receipt["receipt_id"] not in str(gate.get("text") or "") - or delivery.get("status") not in {"open", "done"} - or delivery.get("required_decision_scopes") - or delivery.get("action_kind") != "deliver_goal_channel_payload" - or delivery.get("claimed_by") != agent_id - or delivery.get("capability_binding_ref") != expected_binding_ref - or receipt["receipt_id"] not in str(delivery.get("text") or "") - ): - raise ValueError("frozen Goal Channel payload lacks exact approval") - return delivery, gate - - -def deliver_goal_channel_payload( - *, - receipt_id: str, - registry_path: Path, - runtime_root: Path, - binding_path: Path, - target_path: Path, - goal_id: str, - execute: bool = False, - runner: CommandRunner = default_subprocess_runner, -) -> dict[str, Any]: - """Deliver one approved frozen payload with exact dedupe and readback.""" - - receipt = _read_receipt(runtime_root, goal_id, receipt_id) - delivery_todo, _gate = _approval_verified( - receipt=receipt, registry_path=registry_path, runtime_root=runtime_root - ) - agent_id = str(receipt["agent_id"]) - binding = resolve_bound_goal_channel( - binding_path=binding_path, - target_path=target_path, - goal_id=goal_id, - agent_id=agent_id, - ) - if goal_channel_binding_digest(binding) != receipt["binding_digest"]: - raise ValueError("Goal Channel binding drifted after payload approval") - route = goal_channel_delivery_route(goal_id, lambda _goal_id: binding) - idempotency_key = _canonical_digest( - { - "goal_id": goal_id, - "payload_digest": receipt["payload_digest"], - "binding_digest": receipt["binding_digest"], - } - ) - if not execute: - return operation_packet( - ok=True, - goal_id=goal_id, - operation="deliver_payload", - execute=False, - status="pending_execution", - public_summary="validated one approved frozen Goal Channel payload", - idempotency_key=idempotency_key, - receipt_id=receipt_id, - details={ - "capability_id": receipt["capability_id"], - "payload_digest": receipt["payload_digest"], - "approval_verified": True, - }, - ) - - def resolve_current() -> Mapping[str, Any]: - return resolve_bound_goal_channel( - binding_path=binding_path, - target_path=target_path, - goal_id=goal_id, - agent_id=agent_id, - ) - - session = GoalChannelMessageDeliverySession( - goal_id=goal_id, - binding=binding, - binding_lock_path=binding_path, - target_lock_path=target_path, - history_start_at=str(receipt["created_at"]), - resolve_current_binding=resolve_current, - runner=runner, - ) - if session.verify(route) is not True: - raise ValueError("Goal Channel sender identity could not be verified") - sent = dict(session.send(receipt["card"], idempotency_key, route)) - message_id = str(sent.get("message_id") or "") - observed = dict(session.readback(message_id)) - verified = bool( - observed.get("verified") is True - and observed.get("message_id") == message_id - and observed.get("chat_id") == route["chat_id"] - and observed.get("sender_app_id") == route["bot_app_id"] - and observed.get("sender_identity") == "bot" - and observed.get("sender_evidence_source") == "message_readback" - ) - if not verified: - return operation_packet( - ok=False, - goal_id=goal_id, - operation="deliver_payload", - execute=True, - status="readback_unverified", - public_summary="Goal Channel delivery did not satisfy exact native readback", - external_write_performed=sent.get("external_write_performed") is True, - readback_verified=False, - idempotency_key=idempotency_key, - receipt_id=receipt_id, - blocker="readback_unverified", - ) - if delivery_todo.get("status") != "done": - completed = complete_goal_todo( - registry_path=registry_path, - goal_id=goal_id, - runtime_root_arg=str(runtime_root), - todo_id=str(delivery_todo["todo_id"]), - role="agent", - claimed_by=agent_id, - agent_id=agent_id, - no_followup=True, - evidence=( - "Exact frozen Goal Channel payload delivered with provider-native " - f"sender, chat, and content readback ({receipt['payload_digest']})." - ), - ) - if completed.get("ok") is not True: - raise ValueError("Goal Channel delivery Todo completion failed") - receipt["status"] = "satisfied" - receipt["delivery"] = { - "message_id": message_id, - "delivered_at": datetime.now(timezone.utc).isoformat(), - "readback_verified": True, - "semantic_dedupe_status": sent.get("semantic_dedupe_status"), - } - write_private_json_atomic(_receipt_path(runtime_root, goal_id, receipt_id), receipt) - return operation_packet( - ok=True, - goal_id=goal_id, - operation="deliver_payload", - execute=True, - status="satisfied", - public_summary="delivered one approved frozen Goal Channel payload with exact readback", - external_write_performed=sent.get("external_write_performed") is True, - readback_verified=True, - idempotency_key=idempotency_key, - receipt_id=receipt_id, - details={ - "capability_id": receipt["capability_id"], - "payload_digest": receipt["payload_digest"], - "approval_verified": True, - "delivery_todo_completed": True, - "semantic_dedupe_status": sent.get("semantic_dedupe_status"), - }, - ) - - -__all__ = [ - "FROZEN_PAYLOAD_RECEIPT_SCHEMA", - "FROZEN_PAYLOAD_REQUEST_SCHEMA", - "deliver_goal_channel_payload", - "prepare_goal_channel_payload", -] diff --git a/loopx/extensions/lark/provider.py b/loopx/extensions/lark/provider.py index 03183b5fd8..f243c9c60f 100644 --- a/loopx/extensions/lark/provider.py +++ b/loopx/extensions/lark/provider.py @@ -28,10 +28,10 @@ ), "loopx.extensions.lark.reviewer_notification": ("lark_reviewer_notification_sink",), "loopx.extensions.lark.goal_channel": ( - "deliver_goal_channel_payload", + "deliver_goal_channel_operation_card", "doctor_lark_goal_channel", + "handle_goal_channel_operation_callback", "notify_lark_goal_channel_gate", - "prepare_goal_channel_payload", "setup_lark_goal_channel", "sync_lark_goal_channel", ), diff --git a/loopx/web/chat/asset-retention.json b/loopx/web/chat/asset-retention.json index d8fdca8e78..70e0fdb28d 100644 --- a/loopx/web/chat/asset-retention.json +++ b/loopx/web/chat/asset-retention.json @@ -13,8 +13,8 @@ "assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2", "assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2", "assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2", - "assets/index-B7B_kVDP.css", - "assets/index-DGnmPxJU.js" + "assets/index-8CALBIjN.js", + "assets/index-B7B_kVDP.css" ], [ "assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2", @@ -28,8 +28,8 @@ "assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2", "assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2", "assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2", - "assets/index-B-l9MJT-.js", - "assets/index-B7B_kVDP.css" + "assets/index-B7B_kVDP.css", + "assets/index-uHL7gp0q.js" ] ] } diff --git a/loopx/web/chat/assets/index-8CALBIjN.js b/loopx/web/chat/assets/index-8CALBIjN.js new file mode 100644 index 0000000000..c0bc0f2960 --- /dev/null +++ b/loopx/web/chat/assets/index-8CALBIjN.js @@ -0,0 +1,129 @@ +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,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},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,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),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var l=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&&ne(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&&ne(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var ee=new MessageChannel,te=ee.port2;ee.port1.onmessage=D,O=function(){te.postMessage(null)}}else O=function(){_(D,0)};function ne(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,ne(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}}}})),u=o(((e,t)=>{t.exports=l()})),d=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 ee(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var te=/\/+/g;function ne(e,t){return typeof e==`object`&&e&&e.key!=null?ee(``+e.key):t.toString(36)}function k(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 A(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,A(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+ne(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(te,`$&/`)+`/`),A(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(te,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{t.exports=d()})),p=o((e=>{var t=f();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=p()})),h=o((e=>{var t=u(),n=f(),r=m();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=I(null),se=I(null),ce=I(null),le=I(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)?Wd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Wd(t),e=Gd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}ae(oe),L(oe,e)}function de(){ae(oe),ae(se),ae(ce)}function fe(e){e.memoizedState!==null&&L(le,e);var t=oe.current,n=Gd(t,e.type);t!==n&&(L(se,e),L(oe,n))}function pe(e){se.current===e&&(ae(oe),ae(se)),le.current===e&&(ae(le),tp._currentValue=F)}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,R=t.unstable_getCurrentPriorityLevel,De=t.unstable_ImmediatePriority,Oe=t.unstable_UserBlockingPriority,ke=t.unstable_NormalPriority,Ae=t.unstable_LowPriority,je=t.unstable_IdlePriority,Me=t.log,z=t.unstable_setDisableYieldValue,B=null,Ne=null;function Pe(e){if(typeof Me==`function`&&z(e),Ne&&typeof Ne.setStrictMode==`function`)try{Ne.setStrictMode(B,e)}catch{}}var Fe=Math.clz32?Math.clz32:Le,V=Math.log,Ie=Math.LN2;function Le(e){return e>>>=0,e===0?32:31-(V(e)/Ie|0)|0}var Re=256,ze=262144,Be=4194304;function Ve(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 He(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=Ve(n))):i=Ve(o):i=Ve(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=Ve(n))):i=Ve(o)):i=Ve(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 Ue(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function We(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 Ge(){var e=Be;return Be<<=1,!(Be&62914560)&&(Be=4194304),e}function Ke(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function qe(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Je(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),sn=!1;if(on)try{var cn={};Object.defineProperty(cn,"passive",{get:function(){sn=!0}}),window.addEventListener(`test`,cn,cn),window.removeEventListener(`test`,cn,cn)}catch{sn=!1}var ln=null,un=null,dn=null;function fn(){if(dn)return dn;var e,t=un,n=t.length,r,i=`value`in ln?ln.value:ln.textContent,a=i.length;for(e=0;e=Wn),qn=` `,Jn=!1;function Yn(e,t){switch(e){case`keyup`:return Hn.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Xn(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Zn=!1;function Qn(e,t){switch(e){case`compositionend`:return Xn(t);case`keypress`:return t.which===32?(Jn=!0,qn):null;case`textInput`:return e=t.data,e===qn&&Jn?null:e;default:return null}}function $n(e,t){if(Zn)return e===`compositionend`||!Un&&Yn(e,t)?(e=fn(),dn=un=ln=null,Zn=!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=xr(n)}}function Cr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Cr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function wr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Nt(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=Nt(e.document)}return t}function Tr(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 Er=on&&`documentMode`in document&&11>=document.documentMode,Dr=null,Or=null,kr=null,Ar=!1;function jr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ar||Dr==null||Dr!==Nt(r)||(r=Dr,`selectionStart`in r&&Tr(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}),kr&&br(kr,r)||(kr=r,r=Od(Or,`onSelect`),0>=o,i-=o,Ci=1<<32-Fe(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),Mi&&Ti(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),Mi&&Ti(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 Mi&&Ti(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)}),Mi&&Ti(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&&wa(l)===r.type){n(e,r.sibling),c=a(r,o.props),ja(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===y?(c=ui(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=li(o.type,o.key,o.props,null,e.mode,c),ja(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}n(e,r);break}t(e,r),r=r.sibling}c=pi(o,e.mode,c),c.return=e,e=c}return s(e);case O:return o=wa(o),b(e,r,o,c)}if(M(o))return h(e,r,o,c);if(k(o)){if(l=k(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,Aa(o),c);if(o.$$typeof===C)return b(e,r,$i(e,o),c);Ma(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=di(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{ka=0;var i=b(e,t,n,r);return Oa=null,i}catch(t){if(t===ya||t===xa)throw t;var a=ai(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Pa=Na(!0),Fa=Na(!1),Ia=!1;function La(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ra(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 za(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Ba(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Vl&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=ni(e),ti(e,null,n),t}return Qr(e,r,t,n),ni(e)}function Va(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,Xe(e,n)}}function Ha(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 Ua=!1;function Wa(){if(Ua){var e=ua;if(e!==null)throw e}}function Ga(e,t,n,r){Ua=!1;var i=e.updateQueue;Ia=!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?(Wl&f)===f:(r&f)===f){f!==0&&f===la&&(Ua=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(m=g.payload,typeof m==`function`){d=m.call(_,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=g.payload,f=typeof m==`function`?m.call(_,d,f):m,f==null)break a;d=h({},d,f);break a;case 2:Ia=!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 Ka(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function qa(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=N.T,s={};N.T=s,Ps(e,!1,t,n);try{var c=i(),l=N.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Ns(e,t,pa(c,r),bu(e)):Ns(e,t,r,bu(e))}catch(n){Ns(e,t,{then:function(){},status:`rejected`,reason:n},bu())}finally{P.p=a,o!==null&&s.types!==null&&(o.types=s.types),N.T=o}}function Cs(){}function ws(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=Ts(e).queue;Ss(e,a,t,F,n===null?Cs:function(){return Es(e),n(r)})}function Ts(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:F,baseState:F,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fo,lastRenderedState:F},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fo,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Es(e){var t=Ts(e);t.next===null&&(t=e.alternate.memoizedState),Ns(e,t.next.queue,{},bu())}function Ds(){return H(tp)}function Os(){return Ao().memoizedState}function ks(){return Ao().memoizedState}function As(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=bu();e=za(n);var r=Ba(t,e,n);r!==null&&(Su(r,t,n),Va(r,t,n)),t={cache:aa()},e.payload=t;return}t=t.return}}function js(e,t,n){var r=bu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Fs(e)?Is(t,n):(n=$r(e,t,n,r),n!==null&&(Su(n,e,r),Ls(n,t,r)))}function Ms(e,t,n){Ns(e,t,n,bu())}function Ns(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Fs(e))Is(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,yr(s,o))return Qr(e,t,i,0),Hl===null&&Zr(),!1}catch{}if(n=$r(e,t,i,r),n!==null)return Su(n,e,r),Ls(n,t,r),!0}return!1}function Ps(e,t,n,r){if(r={lane:2,revertLane:md(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Fs(e)){if(t)throw Error(i(479))}else t=$r(e,n,r,2),t!==null&&Su(t,e,2)}function Fs(e){var t=e.alternate;return e===lo||t!==null&&t===lo}function Is(e,t){mo=po=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Ls(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Xe(e,n)}}var Rs={readContext:H,use:No,useCallback:bo,useContext:bo,useEffect:bo,useImperativeHandle:bo,useLayoutEffect:bo,useInsertionEffect:bo,useMemo:bo,useReducer:bo,useRef:bo,useState:bo,useDebugValue:bo,useDeferredValue:bo,useTransition:bo,useSyncExternalStore:bo,useId:bo,useHostTransitionStatus:bo,useFormState:bo,useActionState:bo,useOptimistic:bo,useMemoCache:bo,useCacheRefresh:bo};Rs.useEffectEvent=bo;var zs={readContext:H,use:No,useCallback:function(e,t){return ko().memoizedState=[e,t===void 0?null:t],e},useContext:H,useEffect:ls,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),ss(4194308,4,hs.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ss(4194308,4,e,t)},useInsertionEffect:function(e,t){ss(4,2,e,t)},useMemo:function(e,t){var n=ko();t=t===void 0?null:t;var r=e();if(ho){Pe(!0);try{e()}finally{Pe(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=ko();if(n!==void 0){var i=n(t);if(ho){Pe(!0);try{n(t)}finally{Pe(!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=js.bind(null,lo,e),[r.memoizedState,e]},useRef:function(e){var t=ko();return e={current:e},t.memoizedState=e},useState:function(e){e=Go(e);var t=e.queue,n=Ms.bind(null,lo,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:_s,useDeferredValue:function(e,t){return bs(ko(),e,t)},useTransition:function(){var e=Go(!1);return e=Ss.bind(null,lo,e.queue,!0,!1),ko().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=lo,a=ko();if(Mi){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Hl===null)throw Error(i(349));Wl&127||Bo(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,ls(Ho.bind(null,r,o,e),[e]),r.flags|=2048,as(9,{destroy:void 0},Vo.bind(null,r,o,n,t),null),n},useId:function(){var e=ko(),t=Hl.identifierPrefix;if(Mi){var n=wi,r=Ci;n=(r&~(1<<32-Fe(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=go++,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(Ld(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&&Nc(t)}}return Rc(t),Pc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Nc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=ce.current,zi(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=Ai,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[rt]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Pd(e.nodeValue,n)),e||Ii(t,!0)}else e=Ud(e).createTextNode(r),e[rt]=t,t.stateNode=e}return Rc(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=zi(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 Bi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Rc(t),e=!1}else n=Vi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(ao(t),t):(ao(t),null);if(t.flags&128)throw Error(i(558))}return Rc(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=zi(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 Bi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Rc(t),a=!1}else a=Vi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(ao(t),t):(ao(t),null)}return ao(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),Ic(t,t.updateQueue),Rc(t),null);case 4:return de(),e===null&&wd(t.stateNode.containerInfo),Rc(t),null;case 10:return qi(t.type),Rc(t),null;case 19:if(ae(oo),r=t.memoizedState,r===null)return Rc(t),null;if(a=!!(t.flags&128),o=r.rendering,o===null){if(a)Lc(r,!1);else{if(Zl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=so(e),o!==null){for(t.flags|=128,Lc(r,!1),e=o.updateQueue,t.updateQueue=e,Ic(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)ci(n,e),n=n.sibling;return L(oo,oo.current&1|2),Mi&&Ti(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ee()>cu&&(t.flags|=128,a=!0,Lc(r,!1),t.lanes=4194304)}}else{if(!a){if(e=so(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Ic(t,e),Lc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!Mi)return Rc(t),null}else 2*Ee()-r.renderingStartTime>cu&&n!==536870912&&(t.flags|=128,a=!0,Lc(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?(Rc(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ee(),e.sibling=null,n=oo.current,L(oo,a?n&1|2:n&1),Mi&&Ti(t,r.treeForkCount),e);case 22:case 23:return ao(t),Qa(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Rc(t),t.subtreeFlags&6&&(t.flags|=8192)):Rc(t),n=t.updateQueue,n!==null&&Ic(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&&ae(ha),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),qi(ia),Rc(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function Bc(e,t){switch(Oi(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return qi(ia),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(ao(t),t.alternate===null)throw Error(i(340));Bi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(ao(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));Bi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ae(oo),null;case 4:return de(),null;case 10:return qi(t.type),null;case 22:case 23:return ao(t),Qa(),e!==null&&ae(ha),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return qi(ia),null;case 25:return null;default:return null}}function Vc(e,t){switch(Oi(t),t.tag){case 3:qi(ia),de();break;case 26:case 27:case 5:pe(t);break;case 4:de();break;case 31:t.memoizedState!==null&&ao(t);break;case 13:ao(t);break;case 19:ae(oo);break;case 10:qi(t.type);break;case 22:case 23:ao(t),Qa(),e!==null&&ae(ha);break;case 24:qi(ia)}}function Hc(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){Zu(t,t.return,e)}}function Uc(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){Zu(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Zu(t,t.return,e)}}function Wc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{qa(t,n)}catch(t){Zu(e,e.return,t)}}}function Gc(e,t,n){n.props=Ks(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Zu(e,t,n)}}function Kc(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){Zu(e,t,n)}}function qc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){Zu(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){Zu(e,t,n)}else n.current=null}}function Jc(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){Zu(e,e.return,t)}}function Yc(e,t,n){try{var r=e.stateNode;Rd(r,e.type,n,t),r[it]=t}catch(t){Zu(e,e.return,t)}}function Xc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&ef(e.type)||e.tag===4}function Zc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Xc(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&&ef(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 Qc(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=Xt));else if(r!==4&&(r===27&&ef(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Qc(e,t,n),e=e.sibling;e!==null;)Qc(e,t,n),e=e.sibling}function $c(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&&ef(e.type)&&(n=e.stateNode),e=e.child,e!==null))for($c(e,t,n),e=e.sibling;e!==null;)$c(e,t,n),e=e.sibling}function el(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Ld(t,r,n),t[rt]=e,t[it]=n}catch(t){Zu(e,e.return,t)}}var tl=!1,nl=!1,rl=!1,il=typeof WeakSet==`function`?WeakSet:Set,al=null;function ol(e,t){if(e=e.containerInfo,Vd=up,e=wr(e),Tr(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(Hd={focusedElem:e,selectionRange:n},up=!1,al=t;al!==null;)if(t=al,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,al=e;else for(;al!==null;){switch(t=al,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`))),Ld(o,r,n),o[rt]=e,gt(o),r=o;break a;case`link`:var s=Wf(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=Sr(s,h),v=Sr(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,N.T=null,n=gu,gu=null;var o=fu,s=mu;if(du=0,pu=fu=null,mu=0,Vl&6)throw Error(i(331));var c=Vl;if(Vl|=4,Il(o.current),Ol(o,o.current,s,n),Vl=c,cd(0,!1),Ne&&typeof Ne.onPostCommitFiberRoot==`function`)try{Ne.onPostCommitFiberRoot(B,o)}catch{}return!0}finally{P.p=a,N.T=r,qu(e,t)}}function Xu(e,t,n){t=hi(n,t),t=Qs(e.stateNode,t,2),e=Ba(e,t,2),e!==null&&(qe(e,2),q(e))}function Zu(e,t,n){if(e.tag===3)Xu(e,e,n);else for(;t!==null;){if(t.tag===3){Xu(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(uu===null||!uu.has(r))){e=hi(n,e),n=$s(2),r=Ba(t,n,2),r!==null&&(ec(n,r,t,e),qe(r,2),q(r));break}}t=t.return}}function G(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Bl;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)||(Yl=!0,i.add(n),e=Qu.bind(null,e,t,n),t.then(e,e))}function Qu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Hl===e&&(Wl&n)===n&&(Zl===4||Zl===3&&(Wl&62914560)===Wl&&300>Ee()-ou?!(Vl&2)&&ku(e,0):eu|=n,nu===Wl&&(nu=0)),q(e)}function $u(e,t){t===0&&(t=Ge()),e=ei(e,t),e!==null&&(qe(e,t),q(e))}function ed(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),$u(e,n)}function K(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),$u(e,n)}function td(e,t){return Se(e,t)}var nd=null,rd=null,id=!1,ad=!1,od=!1,sd=0;function q(e){e!==rd&&e.next===null&&(rd===null?nd=rd=e:rd=rd.next=e),ad=!0,id||(id=!0,pd())}function cd(e,t){if(!od&&ad){od=!0;do for(var n=!1,r=nd;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-Fe(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=Wl,a=He(r,r===Hl?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||Ue(r,a)||(n=!0,fd(r,a))}r=r.next}while(n);od=!1}}function J(){ld()}function ld(){ad=id=!1;var e=0;sd!==0&&Jd()&&(e=sd);for(var t=Ee(),n=null,r=nd;r!==null;){var i=r.next,a=ud(r,t);a===0?(r.next=null,n===null?nd=i:n.next=i,i===null&&(rd=n)):(n=r,(e!==0||a&3)&&(ad=!0)),r=i}du!==0&&du!==5||cd(e,!1),sd!==0&&(sd=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&&zd(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function wf(e,t,n){var r=Cf;if(r&&typeof t==`string`&&t){var i=Ft(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),vf.has(i)||(vf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Ld(t,`link`,e),gt(t),r.head.appendChild(t)))}}function Tf(e){bf.D(e),wf(`dns-prefetch`,e,null)}function Ef(e,t){bf.C(e,t),wf(`preconnect`,e,t)}function Df(e,t,n){bf.L(e,t,n);var r=Cf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Ft(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Ft(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Ft(n.imageSizes)+`"]`)):i+=`[href="`+Ft(e)+`"]`;var a=i;switch(t){case`style`:a=Nf(e);break;case`script`:a=Lf(e)}_f.has(a)||(e=h({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),_f.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Pf(a))||t===`script`&&r.querySelector(Rf(a))||(t=r.createElement(`link`),Ld(t,`link`,e),gt(t),r.head.appendChild(t)))}}function Of(e,t){bf.m(e,t);var n=Cf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Ft(r)+`"][href="`+Ft(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Lf(e)}if(!_f.has(a)&&(e=h({rel:`modulepreload`,href:e},t),_f.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(Rf(a)))return}r=n.createElement(`link`),Ld(r,`link`,e),gt(r),n.head.appendChild(r)}}}function kf(e,t,n){bf.S(e,t,n);var r=Cf;if(r&&e){var i=ht(r).hoistableStyles,a=Nf(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Pf(a)))s.loading=5;else{e=h({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=_f.get(a))&&Vf(e,n);var c=o=r.createElement(`link`);gt(c),Ld(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,Bf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Af(e,t){bf.X(e,t);var n=Cf;if(n&&e){var r=ht(n).hoistableScripts,i=Lf(e),a=r.get(i);a||(a=n.querySelector(Rf(i)),a||(e=h({src:e,async:!0},t),(t=_f.get(i))&&Hf(e,t),a=n.createElement(`script`),gt(a),Ld(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function jf(e,t){bf.M(e,t);var n=Cf;if(n&&e){var r=ht(n).hoistableScripts,i=Lf(e),a=r.get(i);a||(a=n.querySelector(Rf(i)),a||(e=h({src:e,async:!0,type:`module`},t),(t=_f.get(i))&&Hf(e,t),a=n.createElement(`script`),gt(a),Ld(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Mf(e,t,n,r){var a=(a=ce.current)?yf(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=Nf(n.href),n=ht(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=Nf(n.href);var o=ht(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(Pf(e)))&&!o._p&&(s.instance=o,s.state.loading=5),_f.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},_f.set(e,n),o||If(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=Lf(n),n=ht(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 Nf(e){return`href="`+Ft(e)+`"`}function Pf(e){return`link[rel="stylesheet"][`+e+`]`}function Ff(e){return h({},e,{"data-precedence":e.precedence,precedence:null})}function If(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}),Ld(t,`link`,n),gt(t),e.head.appendChild(t))}function Lf(e){return`[src="`+Ft(e)+`"]`}function Rf(e){return`script[async]`+e}function zf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Ft(n.href)+`"]`);if(r)return t.instance=r,gt(r),r;var a=h({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),gt(r),Ld(r,`style`,a),Bf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Nf(n.href);var o=e.querySelector(Pf(a));if(o)return t.state.loading|=4,t.instance=o,gt(o),o;r=Ff(n),(a=_f.get(a))&&Vf(r,a),o=(e.ownerDocument||e).createElement(`link`),gt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Ld(o,`link`,r),t.state.loading|=4,Bf(o,n.precedence,e),t.instance=o;case`script`:return o=Lf(n.src),(a=e.querySelector(Rf(o)))?(t.instance=a,gt(a),a):(r=n,(a=_f.get(o))&&(r=h({},n),Hf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),gt(a),Ld(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,Bf(r,n.precedence,e));return t.instance}function Bf(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 Kf(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 qf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Jf(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=Nf(r.href),a=t.querySelector(Pf(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Zf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,gt(a);return}a=t.ownerDocument||t,r=Ff(r),(i=_f.get(i))&&Vf(r,i),a=a.createElement(`link`),gt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Ld(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=Zf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Yf=0;function Xf(e,t){return e.stylesheets&&e.count===0&&$f(e,e.stylesheets),0Yf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Zf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)$f(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Qf=null;function $f(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Qf=new Map,t.forEach(ep,e),Qf=null,Zf.call(e))}function ep(e,t){if(!(t.state.loading&4)){var n=Qf.get(e);if(n)var r=n.get(null);else{n=new Map,Qf.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=h()})),_=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},v=new class extends _{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},y={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},b=new class{#e=y;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function x(e){setTimeout(e,0)}var S=typeof window>`u`||`Deno`in globalThis;function C(){}function w(e,t){return typeof e==`function`?e(t):e}function T(e){return typeof e==`number`&&e>=0&&e!==1/0}function E(e,t){return Math.max(e+(t||0)-Date.now(),0)}function D(e,t){return typeof e==`function`?e(t):e}function O(e,t){return typeof e==`function`?e(t):e}function ee(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==ne(o,t.options))return!1}else if(!A(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function te(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(k(t.options.mutationKey)!==k(a))return!1}else if(!A(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function ne(e,t){return(t?.queryKeyHashFn||k)(e)}function k(e){return JSON.stringify(e,(e,t)=>P(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function A(e,t){return e===t?!0:typeof e==typeof t&&e&&t&&typeof e==`object`&&typeof t==`object`?Object.keys(t).every(n=>A(e[n],t[n])):!1}var j=Object.prototype.hasOwnProperty;function M(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=N(e)&&N(t);if(!r&&!(P(e)&&P(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l{b.setTimeout(t,e)})}function ie(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:M(e,t)}function I(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ae(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var L=Symbol();function oe(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===L?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function se(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var ce=(()=>{let e=()=>S;return{isServer(){return e()},setIsServer(t){e=t}}})();function le(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var ue=x;function de(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=ue,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var fe=de(),pe=new class extends _{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function me(e){return Math.min(1e3*2**e,3e4)}function he(e){return(e??`online`)!==`online`||pe.isOnline()}var ge=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function _e(e){let t=!1,n=0,r,i=le(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new ge(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>v.isFocused()&&(e.networkMode===`always`||pe.isOnline())&&e.canRun(),u=()=>he(e.networkMode)&&e.canRun(),d=e=>{a()||(r?.(),i.resolve(e))},f=e=>{a()||(r?.(),i.reject(e))},p=()=>new Promise(t=>{r=e=>{(a()||l())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),m=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(d).catch(r=>{if(a())return;let i=e.retry??(ce.isServer()?0:3),o=e.retryDelay??me,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&nl()?void 0:p()).then(()=>{t?f(r):m()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:u,start:()=>(u()?m():p().then(m),i)}}var ve=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),T(this.gcTime)&&(this.#e=b.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ce.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(b.clearTimeout(this.#e),this.#e=void 0)}};function ye(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{se(e,()=>t.signal,()=>n=!0)},u=oe(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?ae:I;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?xe:be,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:be(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(ct.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function be(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function xe(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var Se=class extends ve{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Te(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Te(this.options);e.data!==void 0&&(this.setState(we(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=ie(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(C).catch(C):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>O(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===L||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>D(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!E(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#a&&(this.#s||this.#c()?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}#c(){return this.state.fetchStatus===`paused`&&this.state.status===`pending`}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=oe(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?ye(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta}),this.#a=_e({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof ge&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#a.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof ge){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...Ce(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...we(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),fe.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Ce(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:he(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function we(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Te(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Ee=class extends ve{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||R(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=_e({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});let r=this.state.status===`pending`,i=!this.#r.canStart();try{if(r)t();else{this.#i({type:`pending`,variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:i})}let a=await this.#r.start();return await this.#n.config.onSuccess?.(a,e,this.state.context,this,n),await this.options.onSuccess?.(a,e,this.state.context,n),await this.#n.config.onSettled?.(a,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(a,null,e,this.state.context,n),this.#i({type:`success`,data:a}),a}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),fe.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function R(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var De=class extends _{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){let r=new Ee({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=Oe(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=Oe(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=Oe(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=Oe(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){fe.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>te(t,e))}findAll(e={}){return this.getAll().filter(t=>te(e,t))}notify(e){fe.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return fe.batch(()=>Promise.all(e.map(e=>e.continue().catch(C))))}};function Oe(e){return e.options.scope?.id}var ke=class extends _{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??ne(r,t),a=this.get(i);return a||(a=new Se({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){fe.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>ee(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>ee(e,t)):t}notify(e){fe.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){fe.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){fe.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Ae=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new ke,this.#t=e.mutationCache||new De,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=v.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=pe.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(D(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=w(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return fe.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;fe.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return fe.batch(()=>(n.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=fe.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(C).catch(C)}invalidateQueries(e,t={}){return fe.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=fe.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(C)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(C)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(D(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(C).catch(C)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(C).catch(C)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return pe.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(k(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{A(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(k(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{A(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=ne(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===L&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},je=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})),Me=o(((e,t)=>{t.exports=je()})),z=c(f(),1),B=Me(),Ne=z.createContext(void 0),Pe=({client:e,children:t})=>(z.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,B.jsx)(Ne.Provider,{value:e,children:t})),Fe=typeof window<`u`?z.useLayoutEffect:z.useEffect;function V(e){let t=z.useRef({value:e,prev:null}),n=t.current.value;return e!==n&&(t.current={value:e,prev:n}),t.current.prev}function Ie(e,t,n={},r={}){z.useEffect(()=>{if(!e.current||r.disabled||typeof IntersectionObserver!=`function`)return;let i=new IntersectionObserver(([e])=>{t(e)},n);return i.observe(e.current),()=>{i.disconnect()}},[t,n,r.disabled,e])}function Le(e){let t=z.useRef(null);return z.useImperativeHandle(e,()=>t.current,[]),t}function Re(e){return e[e.length-1]}function ze(e){return typeof e==`function`}function Be(e,t){return ze(e)?e(t):e}var Ve=Object.prototype.hasOwnProperty,He=Object.prototype.propertyIsEnumerable;function Ue(e){for(let t in e)if(Ve.call(e,t))return!0;return!1}var We=()=>Object.create(null),Ge=(e,t)=>Ke(e,t,We);function Ke(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=Xe(e)&&Xe(i);if(!a&&!(Je(e)&&Je(i)))return i;let o=a?e:qe(e);if(!o)return i;let s=a?i:qe(i);if(!s)return i;let c=o.length,l=s.length,u=a?Array(l):n(),d=0;for(let t=0;ti||!Ze(e[o],t[o],n)))return!1;return i===a}return!1}function Qe(e){let t,n,r=new Promise((e,r)=>{t=e,n=r});return r.status=`pending`,r.resolve=n=>{r.status=`resolved`,r.value=n,t(n),e?.(n)},r.reject=e=>{r.status=`rejected`,n(e)},r}function $e(e){return!!(e&&typeof e==`object`&&typeof e.then==`function`)}function et(e){return e.replace(/[\x00-\x1f\x7f]/g,``)}function tt(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return et(t)}var nt=[`http:`,`https:`,`mailto:`,`tel:`];function rt(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function it(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=tt(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=tt(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function at(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function ot(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n{e.next&&(e.prev?(e.prev.next=e.next,e.next.prev=e.prev,e.next=void 0,r&&(r.next=e,e.prev=r)):(e.next.prev=void 0,n=e.next,e.next=void 0,r&&(e.prev=r,r.next=e)),r=e)};return{get(e){let n=t.get(e);if(n)return i(n),n.value},set(a,o){if(t.size>=e&&n){let e=n;t.delete(e.key),e.next&&(n=e.next,e.next.prev=void 0),e===r&&(r=void 0)}let s=t.get(a);if(s)s.value=o,i(s);else{let e={key:a,value:o,prev:r};r&&(r.next=e),r=e,n||=e,t.set(a,e)}},clear(){t.clear(),n=void 0,r=void 0}}}var lt=4,ut=5;function dt(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=e.indexOf(`}`,t);return n===-1||t+1>=e.length?null:[t,n]}function ft(e,t,n=new Uint16Array(6)){let r=e.indexOf(`/`,t),i=r===-1?e.length:r,a=e.substring(t,i);if(!a||!a.includes(`$`))return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n;if(a===`$`){let r=e.length;return n[0]=2,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n}if(a.charCodeAt(0)===36)return n[0]=1,n[1]=t,n[2]=t+1,n[3]=i,n[4]=i,n[5]=i,n;let o=dt(a);if(o){let[r,s]=o,c=a.charCodeAt(r+1);if(c===45){if(r+2!e.parse&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=_t(1,n.fullPath??n.from,f,p,m);o=e,e.depth=a,e.parent=i,i.dynamic??=[],i.dynamic.push(e)}break}case 3:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),f=c&&!!(t||s),p=t?f?t:t.toLowerCase():void 0,m=s?f?s:s.toLowerCase():void 0,h=!l&&i.optional?.find(e=>!e.parse&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=_t(3,n.fullPath??n.from,f,p,m);o=e,e.parent=i,e.depth=a,i.optional??=[],i.optional.push(e)}break}case 2:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),l=c&&!!(t||s),f=t?l?t:t.toLowerCase():void 0,p=s?l?s:s.toLowerCase():void 0,m=_t(2,n.fullPath??n.from,l,f,p);o=m,m.parent=i,m.depth=a,i.wildcard??=[],i.wildcard.push(m)}}i=o}if(l&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf(`/`)+1)===95){let e=gt(n.fullPath??n.from);e.kind=ut,e.parent=i,a++,e.depth=a,i.pathless??=[],i.pathless.push(e),i=e}let u=(n.path||!n.children)&&!n.isRoot;if(u&&r.endsWith(`/`)){let e=gt(n.fullPath??n.from);e.kind=lt,e.parent=i,a++,e.depth=a,i.index=e,i=e}i.parse=l??null,i.priority=n.options?.params?.priority??0,u&&!i.route&&(i.route=n,i.fullPath=n.fullPath??n.from)}if(n.children)for(let r of n.children)pt(e,t,r,s,i,a,o)}function mt(e,t){if(e.parse&&!t.parse)return-1;if(!e.parse&&t.parse)return 1;if(e.parse&&t.parse&&(e.priority||t.priority))return t.priority-e.priority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function ht(e){if(e.pathless)for(let t of e.pathless)ht(t);if(e.static)for(let t of e.static.values())ht(t);if(e.staticInsensitive)for(let t of e.staticInsensitive.values())ht(t);if(e.dynamic?.length){e.dynamic.sort(mt);for(let t of e.dynamic)ht(t)}if(e.optional?.length){e.optional.sort(mt);for(let t of e.optional)ht(t)}if(e.wildcard?.length){e.wildcard.sort(mt);for(let t of e.wildcard)ht(t)}}function gt(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function _t(e,t,n,r,i){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,priority:0,caseSensitive:n,prefix:r,suffix:i}}function vt(e,t){let n=gt(`/`),r=new Uint16Array(6);for(let t of e)pt(!1,r,t,1,n,0);ht(n),t.masksTree=n,t.flatCache=ct(1e3)}function yt(e,t){e||=`/`;let n=t.flatCache.get(e);if(n)return n;let r=wt(e,t.masksTree);return t.flatCache.set(e,r),r}function bt(e,t,n,r,i){e||=`/`,r||=`/`;let a=t?`case\0${e}`:e,o=i.singleCache.get(a);return o||(o=gt(`/`),pt(t,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(a,o)),wt(r,o,n)}function xt(e,t,n=!1){let r=n?e:`nofuzz\0${e}`,i=t.matchCache.get(r);if(i!==void 0)return i;e||=`/`;let a;try{a=wt(e,t.segmentTree,n)}catch(e){if(e instanceof URIError)a=null;else throw e}return a&&(a.branch=Et(a.route)),t.matchCache.set(r,a),a}function St(e){return e===`/`?e:e.replace(/\/{1,}$/,``)}function Ct(e,t=!1,n){let r=gt(e.fullPath),i=new Uint16Array(6),a={},o={},s=0;return pt(t,i,e,1,r,0,e=>{if(n?.(e,s),e.id in a&&st(),a[e.id]=e,s!==0&&e.path){let t=St(e.fullPath);(!o[t]||e.fullPath.endsWith(`/`))&&(o[t]=e)}s++}),ht(r),{processedTree:{segmentTree:r,singleCache:ct(1e3),matchCache:ct(1e3),flatCache:null,masksTree:null},routesById:a,routesByPath:o}}function wt(e,t,n=!1){let r=e.split(`/`),i=Ot(e,r,t,n);if(!i)return null;let[a]=Tt(e,r,i);return{route:i.node.route,rawParams:a}}function Tt(e,t,n){let r=Dt(n.node),i=null,a=Object.create(null),o=n.extract?.part??0,s=n.extract?.node??0,c=n.extract?.path??0,l=n.extract?.segment??0;for(;s=0;e--){let n=i.wildcard[e],{prefix:r,suffix:a}=n;if(!(r&&(v||!(n.caseSensitive?y:b??=y.toLowerCase()).startsWith(r)))){if(a){if(v)continue;let e=t.slice(u).join(`/`).slice(-a.length);if((n.caseSensitive?e:e.toLowerCase())!==a)continue}s.push({node:n,index:o,skipped:d,depth:f+1,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}}if(i.optional){let e=d|1<=0;n--){let r=i.optional[n];s.push({node:r,index:u,skipped:e,depth:t,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}if(!v)for(let e=i.optional.length-1;e>=0;e--){let n=i.optional[e],{prefix:r,suffix:a}=n;if(r||a){let e=n.caseSensitive?y:b??=y.toLowerCase();if(r&&!e.startsWith(r)||a&&!e.endsWith(a))continue}s.push({node:n,index:u+1,skipped:d,depth:t,statics:p,dynamics:m,optionals:h+kt(o,u),extract:g,rawParams:_})}}if(!v&&i.dynamic&&y)for(let e=i.dynamic.length-1;e>=0;e--){let t=i.dynamic[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?y:b??=y.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}s.push({node:t,index:u+1,skipped:d,depth:f+1,statics:p,dynamics:m+kt(o,u),optionals:h,extract:g,rawParams:_})}if(!v&&i.staticInsensitive){let e=i.staticInsensitive.get(b??=y.toLowerCase());e&&s.push({node:e,index:u+1,skipped:d,depth:f+1,statics:p+kt(o,u),dynamics:m,optionals:h,extract:g,rawParams:_})}if(!v&&i.static){let e=i.static.get(y);e&&s.push({node:e,index:u+1,skipped:d,depth:f+1,statics:p+kt(o,u),dynamics:m,optionals:h,extract:g,rawParams:_})}if(i.pathless){let e=f+1;for(let t=i.pathless.length-1;t>=0;t--){let n=i.pathless[t];s.push({node:n,index:u,skipped:d,depth:e,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}}}if(l)return l;if(r&&c){let n=c.index;for(let e=0;ee.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===lt)>(e.node.kind===lt)||t.node.kind===lt==(e.node.kind===lt)&&t.depth>e.depth)))}function Nt(e){return Pt(e.filter(e=>e!==void 0).join(`/`))}function Pt(e){return e.replace(/\/{2,}/g,`/`)}function Ft(e){return e===`/`?e:e.replace(/^\/{1,}/,``)}function It(e){let t=e.length;return t>1&&e[t-1]===`/`?e.replace(/\/{1,}$/,``):e}function Lt(e){return It(Ft(e))}function Rt(e,t){return e?.endsWith(`/`)&&e!==`/`&&e!==`${t}/`?e.slice(0,-1):e}function zt(e,t,n){return Rt(e,n)===Rt(t,n)}function Bt({base:e,to:t,trailingSlash:n=`never`,cache:r}){let i=t.startsWith(`/`),a=!i&&t===`.`,o;if(r){o=i?t:a?e:e+`\0`+t;let n=r.get(o);if(n)return n}let s;if(a)s=e.split(`/`);else if(i)s=t.split(`/`);else{for(s=e.split(`/`);s.length>1&&Re(s)===``;)s.pop();let n=t.split(`/`);for(let e=0,t=n.length;e1&&(Re(s)===``?n===`never`&&s.pop():n===`always`&&s.push(``));let c=Pt(s.join(`/`))||`/`;return o&&r&&r.set(o,c),c}function Vt(e){let t=new Map(e.map(e=>[encodeURIComponent(e),e])),n=Array.from(t.keys()).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`),r=new RegExp(n,`g`);return e=>e.replace(r,e=>t.get(e)??e)}function Ht(e,t,n){let r=t[e];return typeof r==`string`?e===`_splat`?/^[a-zA-Z0-9\-._~!/]*$/.test(r)?r:r.split(`/`).map(e=>Wt(e,n)).join(`/`):Wt(r,n):r}function Ut({path:e,params:t,decoder:n,...r}){let i=!1,a=Object.create(null);if(!e||e===`/`)return{interpolatedPath:`/`,usedParams:a,isMissingParams:i};if(!e.includes(`$`))return{interpolatedPath:e,usedParams:a,isMissingParams:i};let o=e.length,s=0,c,l=``;for(;s{t[0]===`?`&&(t=t.substring(1));let n=Jt(t);for(let t in n){let r=n[t];if(typeof r==`string`)try{n[t]=e(r)}catch{}}return n}}function Qt(e,t){let n=typeof t==`function`;function r(r){if(typeof r==`object`&&r)try{return e(r)}catch{}else if(n&&typeof r==`string`)try{return t(r),e(r)}catch{}return r}return e=>{let t=Kt(e,r);return t?`?${t}`:``}}var $t=`__root__`;function en(e){if(e.statusCode=e.statusCode||e.code||307,!e._builtLocation&&!e.reloadDocument&&typeof e.href==`string`)try{new URL(e.href),e.reloadDocument=!0}catch{}let t=new Headers(e.headers);e.href&&t.get(`Location`)===null&&t.set(`Location`,e.href);let n=new Response(null,{status:e.statusCode,headers:t});if(n.options=e,e.throw)throw n;return n}function tn(e){return e instanceof Response&&!!e.options}var nn=e=>{if(!e.rendered)return e.rendered=!0,e.onReady?.()},rn=e=>e.stores.matchesId.get().some(t=>e.stores.matchStores.get(t)?.get()._forcePending),an=(e,t)=>!!(e.preload&&!e.router.stores.matchStores.has(t)),on=(e,t,n=!0)=>{let r={...e.router.options.context??{}},i=n?t:t-1;for(let t=0;t<=i;t++){let n=e.matches[t];if(!n)continue;let i=e.router.getMatch(n.id);i&&Object.assign(r,i.__routeContext,i.__beforeLoadContext)}return r},sn=(e,t)=>{if(!e.matches.length)return;let n=t.routeId,r=e.matches.findIndex(t=>t.routeId===e.router.routeTree.id),i=r>=0?r:0,a=n?e.matches.findIndex(e=>e.routeId===n):e.firstBadMatchIndex??e.matches.length-1;a<0&&(a=i);for(let t=a;t>=0;t--){let n=e.matches[t];if(e.router.looseRoutesById[n.routeId].options.notFoundComponent)return t}return n?a:i},cn=(e,t,n)=>{if(!(!tn(n)&&!Gt(n)))throw tn(n)&&n.redirectHandled&&!n.options.reloadDocument?n:(t&&(t._nonReactive.beforeLoadPromise?.resolve(),t._nonReactive.loaderPromise?.resolve(),t._nonReactive.beforeLoadPromise=void 0,t._nonReactive.loaderPromise=void 0,t._nonReactive.error=n,e.updateMatch(t.id,r=>({...r,status:tn(n)?`redirected`:Gt(n)?`notFound`:r.status===`pending`?`success`:r.status,context:on(e,t.index),isFetching:!1,error:n})),Gt(n)&&!n.routeId&&(n.routeId=t.routeId),t._nonReactive.loadPromise?.resolve()),tn(n)&&(e.rendered=!0,n.options._fromLocation=e.location,n.redirectHandled=!0,n=e.router.resolveRedirect(n)),n)},ln=(e,t)=>{let n=e.router.getMatch(t);return!!(!n||n._nonReactive.dehydrated)},un=(e,t,n)=>{let r=on(e,n);e.updateMatch(t,e=>({...e,context:r}))},dn=(e,t,n)=>{let{id:r,routeId:i}=e.matches[t],a=e.router.looseRoutesById[i];if(n instanceof Promise)throw n;e.firstBadMatchIndex??=t,cn(e,e.router.getMatch(r),n);try{a.options.onError?.(n)}catch(t){n=t,cn(e,e.router.getMatch(r),n)}e.updateMatch(r,e=>(e._nonReactive.beforeLoadPromise?.resolve(),e._nonReactive.beforeLoadPromise=void 0,e._nonReactive.loadPromise?.resolve(),{...e,error:n,status:`error`,isFetching:!1,updatedAt:Date.now(),abortController:new AbortController})),!e.preload&&!tn(n)&&!Gt(n)&&(e.serialError??=n)},fn=(e,t,n,r)=>{if(r._nonReactive.pendingTimeout!==void 0)return;let i=n.options.pendingMs??e.router.options.defaultPendingMs;if(e.onReady&&!an(e,t)&&(n.options.loader||n.options.beforeLoad||Cn(n))&&typeof i==`number`&&i!==1/0&&(n.options.pendingComponent??e.router.options?.defaultPendingComponent)){let t=setTimeout(()=>{nn(e)},i);r._nonReactive.pendingTimeout=t}},pn=(e,t,n)=>{let r=e.router.getMatch(t);if(!r._nonReactive.beforeLoadPromise&&!r._nonReactive.loaderPromise)return;fn(e,t,n,r);let i=()=>{let n=e.router.getMatch(t);n.preload&&(n.status===`redirected`||n.status===`notFound`)&&cn(e,n,n.error)};return r._nonReactive.beforeLoadPromise?r._nonReactive.beforeLoadPromise.then(i):i()},mn=(e,t,n,r)=>{let i=e.router.getMatch(t),a=i._nonReactive.loadPromise;i._nonReactive.loadPromise=Qe(()=>{a?.resolve(),a=void 0});let{paramsError:o,searchError:s}=i;o&&dn(e,n,o),s&&dn(e,n,s),fn(e,t,r,i);let c=new AbortController,l=!1,u=()=>{l||(l=!0,e.updateMatch(t,e=>({...e,isFetching:`beforeLoad`,fetchCount:e.fetchCount+1,abortController:c})))},d=()=>{i._nonReactive.beforeLoadPromise?.resolve(),i._nonReactive.beforeLoadPromise=void 0,e.updateMatch(t,e=>({...e,isFetching:!1}))};if(!r.options.beforeLoad){e.router.batch(()=>{u(),d()});return}i._nonReactive.beforeLoadPromise=Qe();let f={...on(e,n,!1),...i.__routeContext},{search:p,params:m,cause:h}=i,g=an(e,t),_={search:p,abortController:c,params:m,preload:g,context:f,location:e.location,navigate:t=>e.router.navigate({...t,_fromLocation:e.location}),buildLocation:e.router.buildLocation,cause:g?`preload`:h,matches:e.matches,routeId:r.id,...e.router.options.additionalContext},v=r=>{if(r===void 0){e.router.batch(()=>{u(),d()});return}(tn(r)||Gt(r))&&(u(),dn(e,n,r)),e.router.batch(()=>{u(),e.updateMatch(t,e=>({...e,__beforeLoadContext:r})),d()})},y;try{if(y=r.options.beforeLoad(_),$e(y))return u(),y.catch(t=>{dn(e,n,t)}).then(v)}catch(t){u(),dn(e,n,t)}v(y)},hn=(e,t)=>{let{id:n,routeId:r}=e.matches[t],i=e.router.looseRoutesById[r],a=()=>s(),o=()=>mn(e,n,t,i),s=()=>{if(ln(e,n))return;let t=pn(e,n,i);return $e(t)?t.then(o):o()};return a()},gn=(e,t,n)=>{let r=e.router.getMatch(t);if(!r||!n.options.head&&!n.options.scripts&&!n.options.headers)return;let i={ssr:e.router.options.ssr,matches:e.matches,match:r,params:r.params,loaderData:r.loaderData};return Promise.all([n.options.head?.(i),n.options.scripts?.(i),n.options.headers?.(i)]).then(([e,t,n])=>({meta:e?.meta,links:e?.links,headScripts:e?.scripts,headers:n,scripts:t,styles:e?.styles}))},_n=(e,t,n,r,i)=>{let a=t[r-1],{params:o,loaderDeps:s,abortController:c,cause:l}=e.router.getMatch(n),u=on(e,r),d=an(e,n);return{params:o,deps:s,preload:!!d,parentMatchPromise:a,abortController:c,context:u,location:e.location,navigate:t=>e.router.navigate({...t,_fromLocation:e.location}),cause:d?`preload`:l,route:i,...e.router.options.additionalContext}},vn=async(e,t,n,r,i)=>{try{let a=e.router.getMatch(n);try{Sn(i);let o=i.options.loader,s=typeof o==`function`?o:o?.handler,c=s?.(_n(e,t,n,r,i)),l=!!s&&$e(c);if((l||i._lazyPromise||i._componentsPromise||i.options.head||i.options.scripts||i.options.headers||a._nonReactive.minPendingPromise)&&e.updateMatch(n,e=>({...e,isFetching:`loader`})),s){let t=l?await c:c;cn(e,e.router.getMatch(n),t),t!==void 0&&e.updateMatch(n,e=>({...e,loaderData:t}))}i._lazyPromise&&await i._lazyPromise;let u=a._nonReactive.minPendingPromise;u&&await u,i._componentsPromise&&await i._componentsPromise,e.updateMatch(n,t=>({...t,error:void 0,context:on(e,r),status:`success`,isFetching:!1,updatedAt:Date.now()}))}catch(t){let o=t;if(o?.name===`AbortError`){if(a.abortController.signal.aborted){a._nonReactive.loaderPromise?.resolve(),a._nonReactive.loaderPromise=void 0;return}e.updateMatch(n,t=>({...t,status:t.status===`pending`?`success`:t.status,isFetching:!1,context:on(e,r)}));return}let s=a._nonReactive.minPendingPromise;s&&await s,Gt(t)&&await i.options.notFoundComponent?.preload?.(),cn(e,e.router.getMatch(n),t);try{i.options.onError?.(t)}catch(t){o=t,cn(e,e.router.getMatch(n),t)}!tn(o)&&!Gt(o)&&await Sn(i,[`errorComponent`]),e.updateMatch(n,t=>({...t,error:o,context:on(e,r),status:`error`,isFetching:!1}))}}catch(t){let r=e.router.getMatch(n);r&&(r._nonReactive.loaderPromise=void 0),cn(e,r,t)}},yn=async(e,t,n)=>{async function r(r,a,c,l,d){let f=Date.now()-a.updatedAt,p=r?d.options.preloadStaleTime??e.router.options.defaultPreloadStaleTime??3e4:d.options.staleTime??e.router.options.defaultStaleTime??0,m=d.options.shouldReload,h=typeof m==`function`?m(_n(e,t,i,n,d)):m,{status:g,invalid:_}=l,v=f>=p&&(!!e.forceStaleReload||l.cause===`enter`||c!==void 0&&c!==l.id);o=g===`success`&&(_||(h??v)),r&&d.options.preload===!1||(o&&!e.sync&&u?(s=!0,(async()=>{try{await vn(e,t,i,n,d);let r=e.router.getMatch(i);r._nonReactive.loaderPromise?.resolve(),r._nonReactive.loadPromise?.resolve(),r._nonReactive.loaderPromise=void 0,r._nonReactive.loadPromise=void 0}catch(t){tn(t)&&await e.router.navigate(t.options)}})()):g!==`success`||o?await vn(e,t,i,n,d):un(e,i,n))}let{id:i,routeId:a}=e.matches[n],o=!1,s=!1,c=e.router.looseRoutesById[a],l=c.options.loader,u=((typeof l==`function`?void 0:l?.staleReloadMode)??e.router.options.defaultStaleReloadMode)!==`blocking`;if(ln(e,i)){if(!e.router.getMatch(i))return e.matches[n];un(e,i,n)}else{let t=e.router.getMatch(i),o=e.router.stores.matchesId.get()[n],s=(o&&e.router.stores.matchStores.get(o)||null)?.routeId===a?o:e.router.stores.matches.get().find(e=>e.routeId===a)?.id,l=an(e,i);if(t._nonReactive.loaderPromise){if(t.status===`success`&&!e.sync&&!t.preload&&u)return t;await t._nonReactive.loaderPromise;let n=e.router.getMatch(i),a=n._nonReactive.error||n.error;a&&cn(e,n,a),n.status===`pending`&&await r(l,t,s,n,c)}else{let n=l&&!e.router.stores.matchStores.has(i),a=e.router.getMatch(i);a._nonReactive.loaderPromise=Qe(),n!==a.preload&&e.updateMatch(i,e=>({...e,preload:n})),await r(l,t,s,a,c)}}let d=e.router.getMatch(i);s||(d._nonReactive.loaderPromise?.resolve(),d._nonReactive.loadPromise?.resolve(),d._nonReactive.loadPromise=void 0),clearTimeout(d._nonReactive.pendingTimeout),d._nonReactive.pendingTimeout=void 0,s||(d._nonReactive.loaderPromise=void 0),d._nonReactive.dehydrated=void 0;let f=s?d.isFetching:!1;return f!==d.isFetching||d.invalid!==!1?(e.updateMatch(i,e=>({...e,isFetching:f,invalid:!1})),e.router.getMatch(i)):d};async function bn(e){let t=e,n=[];rn(t.router)&&nn(t);let r;for(let e=0;e({...e,...a?{status:`success`,globalNotFound:!0,error:void 0}:{status:`notFound`,error:l},isFetching:!1})),u=e,await Sn(r,[`notFoundComponent`])}else if(!t.preload){let e=t.matches[0];e.globalNotFound||t.router.getMatch(e.id)?.globalNotFound&&t.updateMatch(e.id,e=>({...e,globalNotFound:!1,error:void 0}))}if(t.serialError&&t.firstBadMatchIndex!==void 0){let e=t.router.looseRoutesById[t.matches[t.firstBadMatchIndex].routeId];await Sn(e,[`errorComponent`])}for(let e=0;e<=u;e++){let{id:n,routeId:r}=t.matches[e],i=t.router.looseRoutesById[r];try{let e=gn(t,n,i);if(e){let r=await e;t.updateMatch(n,e=>({...e,...r}))}}catch(e){console.error(`Error executing head for route ${r}:`,e)}}let d=nn(t);if($e(d)&&await d,l)throw l;if(t.serialError&&!t.preload&&!t.onReady)throw t.serialError;return t.matches}function xn(e,t){let n=t.map(t=>e.options[t]?.preload?.()).filter(Boolean);if(n.length!==0)return Promise.all(n)}function Sn(e,t=wn){!e._lazyLoaded&&e._lazyPromise===void 0&&(e.lazyFn?e._lazyPromise=e.lazyFn().then(t=>{let{id:n,...r}=t.options;Object.assign(e.options,r),e._lazyLoaded=!0,e._lazyPromise=void 0}):e._lazyLoaded=!0);let n=()=>e._componentsLoaded?void 0:t===wn?(()=>{if(e._componentsPromise===void 0){let t=xn(e,wn);t?e._componentsPromise=t.then(()=>{e._componentsLoaded=!0,e._componentsPromise=void 0}):e._componentsLoaded=!0}return e._componentsPromise})():xn(e,t);return e._lazyPromise?e._lazyPromise.then(n):n()}function Cn(e){for(let t of wn)if(e.options[t]?.preload)return!0;return!1}var wn=[`component`,`errorComponent`,`pendingComponent`,`notFoundComponent`];function Tn(e){return{input:({url:t})=>{for(let n of e)t=Dn(n,t);return t},output:({url:t})=>{for(let n=e.length-1;n>=0;n--)t=On(e[n],t);return t}}}function En(e){let t=Lt(e.basepath),n=`/${t}`,r=e.caseSensitive?n:n.toLowerCase(),i=`${r}/`;return{input:({url:t})=>{let a=e.caseSensitive?t.pathname:t.pathname.toLowerCase();return a===r?t.pathname=`/`:a.startsWith(i)&&(t.pathname=t.pathname.slice(n.length)),t},output:({url:e})=>(e.pathname=Nt([`/`,t,e.pathname]),e)}}function Dn(e,t){let n=e?.input?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function On(e,t){let n=e?.output?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function kn(e,t){let{createMutableStore:n,createReadonlyStore:r,batch:i,init:a}=t,o=new Map,s=new Map,c=new Map,l=n(e.status),u=n(e.loadedAt),d=n(e.isLoading),f=n(e.isTransitioning),p=n(e.location),m=n(e.resolvedLocation),h=n(e.statusCode),g=n(e.redirect),_=n([]),v=n([]),y=n([]),b=r(()=>An(o,_.get())),x=r(()=>An(s,v.get())),S=r(()=>An(c,y.get())),C=r(()=>_.get()[0]),w=r(()=>_.get().some(e=>o.get(e)?.get().status===`pending`)),T=r(()=>({locationHref:p.get().href,resolvedLocationHref:m.get()?.href,status:l.get()})),E=r(()=>({status:l.get(),loadedAt:u.get(),isLoading:d.get(),isTransitioning:f.get(),matches:b.get(),location:p.get(),resolvedLocation:m.get(),statusCode:h.get(),redirect:g.get()})),D=ct(64);function O(e){let t=D.get(e);return t||(t=r(()=>{let t=_.get();for(let n of t){let t=o.get(n);if(t&&t.routeId===e)return t.get()}}),D.set(e,t)),t}let ee={status:l,loadedAt:u,isLoading:d,isTransitioning:f,location:p,resolvedLocation:m,statusCode:h,redirect:g,matchesId:_,pendingIds:v,cachedIds:y,matches:b,pendingMatches:x,cachedMatches:S,firstId:C,hasPending:w,matchRouteDeps:T,matchStores:o,pendingMatchStores:s,cachedMatchStores:c,__store:E,getRouteMatchStore:O,setMatches:te,setPending:ne,setCached:k};te(e.matches),a?.(ee);function te(e){jn(e,o,_,n,i)}function ne(e){jn(e,s,v,n,i)}function k(e){jn(e,c,y,n,i)}return ee}function An(e,t){let n=[];for(let r of t){let t=e.get(r);t&&n.push(t.get())}return n}function jn(e,t,n,r,i){let a=e.map(e=>e.id),o=new Set(a);i(()=>{for(let e of t.keys())o.has(e)||t.delete(e);for(let n of e){let e=t.get(n.id);if(!e){let e=r(n);e.routeId=n.routeId,t.set(n.id,e);continue}e.routeId=n.routeId,e.get()!==n&&e.set(n)}ot(n.get(),a)||n.set(a)})}var Mn=`__TSR_index`,Nn=`popstate`,Pn=`beforeunload`;function Fn(e){let t=e.getLocation(),n=new Set,r=r=>{t=e.getLocation(),n.forEach(e=>e({location:t,action:r}))},i=n=>{e.notifyOnIndexChange??!0?r(n):t=e.getLocation()},a=async({task:n,navigateOpts:r,...i})=>{if(r?.ignoreBlocker??!1){n();return}let a=e.getBlockers?.()??[],o=i.type===`PUSH`||i.type===`REPLACE`;if(typeof document<`u`&&a.length&&o)for(let n of a){let r=zn(i.path,i.state);if(await n.blockerFn({currentLocation:t,nextLocation:r,action:i.type})){e.onBlocked?.();return}}n()};return{get location(){return t},get length(){return e.getLength()},subscribers:n,subscribe:e=>(n.add(e),()=>{n.delete(e)}),push:(n,i,o)=>{let s=t.state[Mn];i=In(s+1,i),a({task:()=>{e.pushState(n,i),r({type:`PUSH`})},navigateOpts:o,type:`PUSH`,path:n,state:i})},replace:(n,i,o)=>{let s=t.state[Mn];i=In(s,i),a({task:()=>{e.replaceState(n,i),r({type:`REPLACE`})},navigateOpts:o,type:`REPLACE`,path:n,state:i})},go:(t,n)=>{a({task:()=>{e.go(t),i({type:`GO`,index:t})},navigateOpts:n,type:`GO`})},back:t=>{a({task:()=>{e.back(t?.ignoreBlocker??!1),i({type:`BACK`})},navigateOpts:t,type:`BACK`})},forward:t=>{a({task:()=>{e.forward(t?.ignoreBlocker??!1),i({type:`FORWARD`})},navigateOpts:t,type:`FORWARD`})},canGoBack:()=>t.state[Mn]!==0,createHref:t=>e.createHref(t),block:t=>{if(!e.setBlockers)return()=>{};let n=e.getBlockers?.()??[];return e.setBlockers([...n,t]),()=>{let n=e.getBlockers?.()??[];e.setBlockers?.(n.filter(e=>e!==t))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:r}}function In(e,t){t||={};let n=Bn();return{...t,key:n,__TSR_key:n,[Mn]:e}}function Ln(e){let t=e?.window??(typeof document<`u`?window:void 0),n=t.history.pushState,r=t.history.replaceState,i=[],a=()=>i,o=e=>i=e,s=e?.createHref??(e=>e),c=e?.parseLocation??(()=>zn(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){let e=Bn();t.history.replaceState({[Mn]:0,key:e,__TSR_key:e},``)}let l=c(),u,d=!1,f=!1,p=!1,m=!1,h=()=>l,g,_,v=()=>{g&&(C._ignoreSubscribers=!0,(g.isPush?t.history.pushState:t.history.replaceState)(g.state,``,g.href),C._ignoreSubscribers=!1,g=void 0,_=void 0,u=void 0)},y=(e,t,n)=>{let r=s(t);_||(u=l),l=zn(t,n),g={href:r,state:n,isPush:g?.isPush||e===`push`},_||=Promise.resolve().then(()=>v())},b=e=>{l=c(),C.notify({type:e})},x=async()=>{if(f){f=!1;return}let e=c(),n=e.state[Mn]-l.state[Mn],r=n===1,i=n===-1,o=!r&&!i||d;d=!1;let s=o?`GO`:i?`BACK`:`FORWARD`,u=o?{type:`GO`,index:n}:{type:i?`BACK`:`FORWARD`};if(p)p=!1;else{let n=a();if(typeof document<`u`&&n.length){for(let r of n)if(await r.blockerFn({currentLocation:l,nextLocation:e,action:s})){f=!0,t.history.go(1),C.notify(u);return}}}l=c(),C.notify(u)},S=e=>{if(m){m=!1;return}let t=!1,n=a();if(typeof document<`u`&&n.length)for(let e of n){let n=e.enableBeforeUnload??!0;if(n===!0){t=!0;break}if(typeof n==`function`&&n()===!0){t=!0;break}}if(t)return e.preventDefault(),e.returnValue=``},C=Fn({getLocation:h,getLength:()=>t.history.length,pushState:(e,t)=>y(`push`,e,t),replaceState:(e,t)=>y(`replace`,e,t),back:e=>(e&&(p=!0),m=!0,t.history.back()),forward:e=>{e&&(p=!0),m=!0,t.history.forward()},go:e=>{d=!0,t.history.go(e)},createHref:e=>s(e),flush:v,destroy:()=>{t.history.pushState=n,t.history.replaceState=r,t.removeEventListener(Pn,S,{capture:!0}),t.removeEventListener(Nn,x)},onBlocked:()=>{u&&l!==u&&(l=u)},getBlockers:a,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(Pn,S,{capture:!0}),t.addEventListener(Nn,x),t.history.pushState=function(...e){let r=n.apply(t.history,e);return C._ignoreSubscribers||b(`PUSH`),r},t.history.replaceState=function(...e){let n=r.apply(t.history,e);return C._ignoreSubscribers||b(`REPLACE`),n},C}function Rn(e){let t=e.replace(/[\x00-\x1f\x7f]/g,``);return t.startsWith(`//`)&&(t=`/`+t.replace(/^\/+/,``)),t}function zn(e,t){let n=Rn(e),r=n.indexOf(`#`),i=n.indexOf(`?`),a=Bn();return{href:n,pathname:n.substring(0,r>0?i>0?Math.min(r,i):r:i>0?i:n.length),hash:r>-1?n.substring(r):``,search:i>-1?n.slice(i,r===-1?void 0:r):``,state:t||{[Mn]:0,key:a,__TSR_key:a}}}function Bn(){return(Math.random()+1).toString(36).substring(7)}function Vn(e,t){let n=t,r=e;return{fromLocation:n,toLocation:r,pathChanged:n?.pathname!==r.pathname,hrefChanged:n?.href!==r.href,hashChanged:n?.hash!==r.hash}}var Hn=new WeakMap,Un=class{constructor(e,t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this.resetNextScroll=!0,this.shouldViewTransition=void 0,this.isViewTransitionTypesSupported=void 0,this.subscribers=new Set,this.isScrollRestoring=!1,this.isScrollRestorationSetup=!1,this.routeBranchCache=new WeakMap,this.startTransition=e=>e(),this.update=e=>{let t=this.options,n=this.basepath??t?.basepath??`/`,r=this.basepath===void 0,i=t?.rewrite;if(this.options={...t,...e},this.isServer=this.options.isServer??typeof document>`u`,this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=Vt(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.history=this.options.history?this.options.history:Ln()),this.origin=this.options.origin,this.origin||=window?.origin&&window.origin!==`null`?window.origin:`http://localhost`,this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let e;this.resolvePathCache=ct(1e3),e=this.buildRouteTree(),this.setRoutes(e)}if(!this.stores&&this.latestLocation){let e=this.getStoreConfig(this);this.batch=e.batch,this.stores=kn(Kn(this.latestLocation),e),fr(this)}let a=!1,o=this.options.basepath??`/`,s=this.options.rewrite;if(r||n!==o||i!==s){this.basepath=o;let e=[],t=Lt(o);t&&t!==`/`&&e.push(En({basepath:o})),s&&e.push(s),this.rewrite=e.length===0?void 0:e.length===1?e[0]:Tn(e),this.history&&this.updateLatestLocation(),a=!0}a&&this.stores&&this.stores.location.set(this.latestLocation),typeof window<`u`&&`CSS`in window&&typeof window.CSS?.supports==`function`&&(this.isViewTransitionTypesSupported=window.CSS.supports(`selector(:active-view-transition-type(a))`))},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{let e=Ct(this.routeTree,this.options.caseSensitive,(e,t)=>{e.init({originalIndex:t})});return this.options.routeMasks&&vt(this.options.routeMasks,e.processedTree),e},this.subscribe=(e,t)=>{let n={eventType:e,fn:t};return this.subscribers.add(n),()=>{this.subscribers.delete(n)}},this.emit=e=>{this.subscribers.forEach(t=>{t.eventType===e.type&&t.fn(e)})},this.parseLocation=(e,t)=>{let n=({pathname:e,search:n,hash:r,href:i,state:a})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(e)){let i=this.options.parseSearch(n),o=this.options.stringifySearch(i);return{href:e+o+r,publicHref:e+o+r,pathname:it(e).path,external:!1,searchStr:o,search:Ge(t?.search,i),hash:it(r.slice(1)).path,state:Ke(t?.state,a)}}let o=new URL(i,this.origin),s=Dn(this.rewrite,o),c=this.options.parseSearch(s.search),l=this.options.stringifySearch(c);return s.search=l,{href:s.href.replace(s.origin,``),publicHref:i,pathname:it(s.pathname).path,external:!!this.rewrite&&s.origin!==this.origin,searchStr:l,search:Ge(t?.search,c),hash:it(s.hash.slice(1)).path,state:Ke(t?.state,a)}},r=n(e),{__tempLocation:i,__tempKey:a}=r.state;if(i&&(!a||a===this.tempLocationKey)){let e=n(i);return e.state.key=r.state.key,e.state.__TSR_key=r.state.__TSR_key,delete e.state.__tempLocation,{...e,maskedLocation:r}}return r},this.resolvePathWithBase=(e,t)=>Bt({base:e,to:t.includes(`//`)?Pt(t):t,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(e,t,n)=>typeof e==`string`?this.matchRoutesInternal({pathname:e,search:t},n):this.matchRoutesInternal(e,t),this.getMatchedRoutes=e=>Jn({pathname:e,routesById:this.routesById,processedTree:this.processedTree}),this.cancelMatch=e=>{let t=this.getMatch(e);t&&(t.abortController.abort(),clearTimeout(t._nonReactive.pendingTimeout),t._nonReactive.pendingTimeout=void 0)},this.cancelMatches=()=>{this.stores.pendingIds.get().forEach(e=>{this.cancelMatch(e)}),this.stores.matchesId.get().forEach(e=>{if(this.stores.pendingMatchStores.has(e))return;let t=this.stores.matchStores.get(e)?.get();t&&(t.status===`pending`||t.isFetching===`loader`)&&this.cancelMatch(e)})},this.buildLocation=e=>{let t=(t={})=>{let n=t._fromLocation||this.pendingBuiltLocation||this.latestLocation,r=this.matchRoutesLightweight(n);t.from;let i=t.unsafeRelative===`path`?n.pathname:t.from??r.fullPath,a=t.to?`${t.to}`:void 0,o=r.search,s=Object.assign(Object.create(null),r.params),c=a?.charCodeAt(0)===47?`/`:this.resolvePathWithBase(i,`.`),l=a?this.resolvePathWithBase(c,a):c,u=t.params===!1||t.params===null?Object.create(null):(t.params??!0)===!0?s:Object.assign(s,Be(t.params,s)),d=this.routesByPath[It(l)],f;if(d)f=this.getRouteBranch(d);else if(l.includes(`$`))f=[];else{let e=this.getMatchedRoutes(l);f=e.matchedRoutes,this.options.notFoundRoute&&(!e.foundRoute||e.foundRoute.path!==`/`&&e.routeParams[`**`])&&(f=[...f,this.options.notFoundRoute])}if(f.length&&Ue(u))for(let e of f){let t=e.options.params?.stringify??e.options.stringifyParams;if(t)try{Object.assign(u,t(u))}catch{}}let p=e.leaveParams?l:it(Ut({path:l,params:u,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path,m=o;if(e._includeValidateSearch&&this.options.search?.strict){let e={};f.forEach(t=>{if(t.options.validateSearch)try{Object.assign(e,qn(t.options.validateSearch,{...e,...m}))}catch{}}),m=e}m=Yn({search:m,dest:t,destRoutes:f,_includeValidateSearch:e._includeValidateSearch}),m=Ge(o,m);let h=this.options.stringifySearch(m),g=t.hash===!0?n.hash:t.hash?Be(t.hash,n.hash):void 0,_=g?`#${g}`:``,v=t.state===!0?n.state:t.state?Be(t.state,n.state):{};v=Ke(n.state,v);let y=`${p}${h}${_}`,b,x,S=!1;if(this.rewrite){let e=new URL(y,this.origin),t=On(this.rewrite,e);b=e.href.replace(e.origin,``),t.origin===this.origin?x=t.pathname+t.search+t.hash:(x=t.href,S=!0)}else b=at(y),x=b;return{publicHref:x,href:b,pathname:p,search:m,searchStr:h,state:v,hash:g??``,external:S,unmaskOnReload:t.unmaskOnReload}},n=(n={},r)=>{let i=t(n),a=r?t(r):void 0;if(!a){let n=Object.create(null);if(this.options.routeMasks){let o=yt(i.pathname,this.processedTree);if(o){Object.assign(n,o.rawParams);let{from:i,params:s,...c}=o.route,l=s===!1||s===null?Object.create(null):(s??!0)===!0?n:Object.assign(n,Be(s,n));r={from:e.from,...c,params:l},a=t(r)}}}return a&&(i.maskedLocation=a),i};return e.mask?n(e,{from:e.from,...e.mask}):n(e)},this.commitLocation=async({viewTransition:e,ignoreBlocker:t,...n})=>{let r,i=()=>{let e=[`key`,`__TSR_key`,`__TSR_index`,`__hashScrollIntoViewOptions`];e.forEach(e=>{n.state[e]=this.latestLocation.state[e]});let t=Ze(n.state,this.latestLocation.state);return e.forEach(e=>{delete n.state[e]}),t},a=It(this.latestLocation.href)===It(n.href),o=this.commitLocationPromise;if(this.commitLocationPromise=Qe(()=>{o?.resolve(),o=void 0}),a&&i())this.load();else{let{maskedLocation:i,hashScrollIntoView:a,...o}=n;i&&(o={...i,state:{...i.state,__tempKey:void 0,__tempLocation:{...o,search:o.searchStr,state:{...o.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(o.unmaskOnReload??this.options.unmaskOnReload??!1)&&(o.state.__tempKey=this.tempLocationKey)),o.state.__hashScrollIntoViewOptions=a??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=e,r=n.replace?`REPLACE`:`PUSH`,this.history[r===`REPLACE`?`replace`:`push`](o.publicHref,o.state,{ignoreBlocker:t})}return this.resetNextScroll=n.resetScroll??!0,this.history.subscribers.size||this.load(r?{action:{type:r}}:void 0),this.commitLocationPromise},this.buildAndCommitLocation=({replace:e,resetScroll:t,hashScrollIntoView:n,viewTransition:r,ignoreBlocker:i,href:a,...o}={})=>{if(a){let t=this.history.location.state.__TSR_index,n=zn(a,{__TSR_index:e?t:t+1}),r=new URL(n.pathname,this.origin);o.to=Dn(this.rewrite,r).pathname,o.search=this.options.parseSearch(n.search),o.hash=n.hash.slice(1)}let s=this.buildLocation({...o,_includeValidateSearch:!0});this.pendingBuiltLocation=s;let c=this.commitLocation({...s,viewTransition:r,replace:e,resetScroll:t,hashScrollIntoView:n,ignoreBlocker:i});return Promise.resolve().then(()=>{this.pendingBuiltLocation===s&&(this.pendingBuiltLocation=void 0)}),c},this.navigate=async({to:e,reloadDocument:t,href:n,publicHref:r,...i})=>{let a=!1;if(n)try{new URL(`${n}`),a=!0}catch{}if(a&&!t&&(t=!0),t){if(e!==void 0||!n){let t=this.buildLocation({to:e,...i});n??=t.publicHref,r??=t.publicHref}let t=!a&&r?r:n;if(rt(t,this.protocolAllowlist))return Promise.resolve();if(!i.ignoreBlocker){let e=this.history.getBlockers?.()??[];for(let t of e)if(t?.blockerFn&&await t.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:`PUSH`}))return Promise.resolve()}return i.replace?window.location.replace(t):window.location.href=t,Promise.resolve()}return this.buildAndCommitLocation({...i,href:n,to:e,_isNavigate:!0})},this.beforeLoad=()=>{this.cancelMatches(),this.updateLatestLocation();let e=this.matchRoutes(this.latestLocation),t=this.stores.cachedMatches.get().filter(t=>!e.some(e=>e.id===t.id));this.batch(()=>{this.stores.status.set(`pending`),this.stores.statusCode.set(200),this.stores.isLoading.set(!0),this.stores.location.set(this.latestLocation),this.stores.setPending(e),this.stores.setCached(t)})},this.load=async e=>{let t=e?.action?.type,n,r,i,a=this.stores.resolvedLocation.get()??this.stores.location.get();for(i=new Promise(o=>{this.startTransition(async()=>{try{this.beforeLoad(),t?Hn.set(this.latestLocation,t):Hn.delete(this.latestLocation);let n=this.latestLocation,r=Vn(n,this.stores.resolvedLocation.get());this.stores.redirect.get()||this.emit({type:`onBeforeNavigate`,...r}),this.emit({type:`onBeforeLoad`,...r}),await bn({router:this,sync:e?.sync,forceStaleReload:a.href===n.href,matches:this.stores.pendingMatches.get(),location:n,updateMatch:this.updateMatch,onReady:async()=>{this.startTransition(()=>{this.startViewTransition(async()=>{let e=null,t=null,n=null,r=null;this.batch(()=>{let i=this.stores.pendingMatches.get(),a=i.length,o=this.stores.matches.get();e=a?o.filter(e=>!this.stores.pendingMatchStores.has(e.id)):null;let s=new Set;for(let e of this.stores.pendingMatchStores.values())e.routeId&&s.add(e.routeId);let c=new Set;for(let e of this.stores.matchStores.values())e.routeId&&c.add(e.routeId);t=a?o.filter(e=>!s.has(e.routeId)):null,n=a?i.filter(e=>!c.has(e.routeId)):null,r=a?i.filter(e=>c.has(e.routeId)):o,this.stores.isLoading.set(!1),this.stores.loadedAt.set(Date.now()),a&&(this.stores.setMatches(i),this.stores.setPending([]),this.stores.setCached([...this.stores.cachedMatches.get(),...e.filter(e=>e.status!==`error`&&e.status!==`notFound`&&e.status!==`redirected`)]),this.clearExpiredCache())});for(let[e,i]of[[t,`onLeave`],[n,`onEnter`],[r,`onStay`]])if(e)for(let t of e)this.looseRoutesById[t.routeId].options[i]?.(t)})})}})}catch(e){tn(e)?(n=e,this.navigate({...n.options,replace:!0,ignoreBlocker:!0})):Gt(e)&&(r=e);let t=n?n.status:r?404:this.stores.matches.get().some(e=>e.status===`error`)?500:200;this.batch(()=>{this.stores.statusCode.set(t),this.stores.redirect.set(n)})}this.latestLoadPromise===i&&(this.commitLocationPromise?.resolve(),this.latestLoadPromise=void 0,this.commitLocationPromise=void 0),o()})}),this.latestLoadPromise=i,await i;this.latestLoadPromise&&i!==this.latestLoadPromise;)await this.latestLoadPromise;let o;this.hasNotFoundMatch()?o=404:this.stores.matches.get().some(e=>e.status===`error`)&&(o=500),o!==void 0&&this.stores.statusCode.set(o)},this.startViewTransition=e=>{let t=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,t&&typeof document<`u`&&`startViewTransition`in document&&typeof document.startViewTransition==`function`){let n;if(typeof t==`object`&&this.isViewTransitionTypesSupported){let r=this.latestLocation,i=this.stores.resolvedLocation.get(),a=typeof t.types==`function`?t.types(Vn(r,i)):t.types;if(a===!1){e();return}n={update:e,types:a}}else n=e;document.startViewTransition(n)}else e()},this.updateMatch=(e,t)=>{this.startTransition(()=>{let n=this.stores.pendingMatchStores.get(e);if(n){n.set(t);return}let r=this.stores.matchStores.get(e);if(r){r.set(t);return}let i=this.stores.cachedMatchStores.get(e);if(i){let n=t(i.get());n.status===`redirected`?this.stores.cachedMatchStores.delete(e)&&this.stores.cachedIds.set(t=>t.filter(t=>t!==e)):i.set(n)}})},this.getMatch=e=>this.stores.cachedMatchStores.get(e)?.get()??this.stores.pendingMatchStores.get(e)?.get()??this.stores.matchStores.get(e)?.get(),this.invalidate=e=>{let t=t=>e?.filter?.(t)??!0?{...t,invalid:!0,...e?.forcePending||t.status===`error`||t.status===`notFound`?{status:`pending`,error:void 0}:void 0}:t;return this.batch(()=>{this.stores.setMatches(this.stores.matches.get().map(t)),this.stores.setCached(this.stores.cachedMatches.get().map(t)),this.stores.setPending(this.stores.pendingMatches.get().map(t))}),this.shouldViewTransition=!1,this.load({sync:e?.sync})},this.getParsedLocationHref=e=>e.publicHref||`/`,this.resolveRedirect=e=>{let t=e.headers.get(`Location`);if(!e.options.href||e.options._builtLocation){let t=e.options._builtLocation??this.buildLocation(e.options),n=this.getParsedLocationHref(t);e.options.href=n,e.headers.set(`Location`,n)}else if(t)try{let n=new URL(t);if(this.origin&&n.origin===this.origin){let t=n.pathname+n.search+n.hash;e.options.href=t,e.headers.set(`Location`,t)}}catch{}if(e.options.href&&!e.options._builtLocation&&rt(e.options.href,this.protocolAllowlist))throw Error(`Redirect blocked: unsafe protocol`);return e.headers.get(`Location`)||e.headers.set(`Location`,e.options.href),e},this.clearCache=e=>{let t=e?.filter;t===void 0?this.stores.setCached([]):this.stores.setCached(this.stores.cachedMatches.get().filter(e=>!t(e)))},this.clearExpiredCache=()=>{let e=Date.now();this.clearCache({filter:t=>{let n=this.looseRoutesById[t.routeId];if(!n.options.loader)return!0;let r=(t.preload?n.options.preloadGcTime??this.options.defaultPreloadGcTime:n.options.gcTime??this.options.defaultGcTime)??3e5;return t.status===`error`||e-t.updatedAt>=r}})},this.loadRouteChunk=Sn,this.preloadRoute=async e=>{let t=e._builtLocation??this.buildLocation(e),n=this.matchRoutes(t,{throwOnError:!0,preload:!0,dest:e}),r=new Set([...this.stores.matchesId.get(),...this.stores.pendingIds.get()]),i=new Set([...r,...this.stores.cachedIds.get()]),a=n.filter(e=>!i.has(e.id));if(a.length){let e=this.stores.cachedMatches.get();this.stores.setCached([...e,...a])}try{return n=await bn({router:this,matches:n,location:t,preload:!0,updateMatch:(e,t)=>{r.has(e)?n=n.map(n=>n.id===e?t(n):n):this.updateMatch(e,t)}}),n}catch(e){if(tn(e))return e.options.reloadDocument?void 0:await this.preloadRoute({...e.options,_fromLocation:t});Gt(e)||console.error(e);return}},this.matchRoute=(e,t)=>{let n={...e,to:e.to?this.resolvePathWithBase(e.from||``,e.to):void 0,params:e.params||{},leaveParams:!0},r=this.buildLocation(n);if(t?.pending&&this.stores.status.get()!==`pending`)return!1;let i=(t?.pending===void 0?!this.stores.isLoading.get():t.pending)?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),a=bt(r.pathname,t?.caseSensitive??!1,t?.fuzzy??!1,i.pathname,this.processedTree);return!a||e.params&&!Ze(a.rawParams,e.params,{partial:!0})?!1:t?.includeSearch??!0?Ze(i.search,r.search,{partial:!0})?a.rawParams:!1:a.rawParams},this.hasNotFoundMatch=()=>this.stores.matches.get().some(e=>e.status===`notFound`||e.globalNotFound),this.getStoreConfig=t,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??`fuzzy`,stringifySearch:e.stringifySearch??Xt,parseSearch:e.parseSearch??Yt,protocolAllowlist:e.protocolAllowlist??nt}),typeof document<`u`&&(self.__TSR_ROUTER__=this)}isShell(){return!!this.options.isShell}isPrerendering(){return!!this.options.isPrerendering}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:n}){this.routesById=e,this.routesByPath=t,this.processedTree=n;let r=this.options.notFoundRoute;r&&(r.init({originalIndex:99999999999}),this.routesById[r.id]=r)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=Et(e),this.routeBranchCache.set(e,t)),t}get looseRoutesById(){return this.routesById}getParentContext(e){return e?.id?e.context??this.options.context??void 0:this.options.context??void 0}matchRoutesInternal(e,t){let n=this.getMatchedRoutes(e.pathname),{foundRoute:r,routeParams:i}=n,{matchedRoutes:a}=n,o=!1;(r?r.path!==`/`&&i[`**`]:It(e.pathname))&&(this.options.notFoundRoute?a=[...a,this.options.notFoundRoute]:o=!0);let s=o?Zn(this.options.notFoundMode,a):void 0,c=Array(a.length),l=new Map;for(let e of this.stores.matchStores.values())e.routeId&&l.set(e.routeId,e.get());for(let n=0;nthis.navigate({...t,_fromLocation:e}),buildLocation:this.buildLocation,cause:n.cause,abortController:n.abortController,preload:!!n.preload,matches:c,routeId:r.id};n.__routeContext=r.options.context(t)??void 0}n.context={...a,...n.__routeContext,...n.__beforeLoadContext}}}return c}matchRoutesLightweight(e){let{matchedRoutes:t,routeParams:n}=this.getMatchedRoutes(e.pathname),r=Re(t),i={...e.search};for(let e of t)try{Object.assign(i,qn(e.options.validateSearch,i))}catch{}let a=Re(this.stores.matchesId.get()),o=a&&this.stores.matchStores.get(a)?.get(),s=o&&o.routeId===r.id&&o.pathname===e.pathname,c;if(s)c=o.params;else{let e=Object.assign(Object.create(null),n);for(let n of t)try{Qn(n,e)}catch{}c=e}return{matchedRoutes:t,fullPath:r.fullPath,search:i,params:c}}},Wn=class extends Error{},Gn=class extends Error{};function Kn(e){return{loadedAt:0,isLoading:!1,isTransitioning:!1,status:`idle`,resolvedLocation:void 0,location:e,matches:[],statusCode:200}}function qn(e,t){if(e==null)return{};if(`~standard`in e){let n=e[`~standard`].validate(t);if(n instanceof Promise)throw new Wn(`Async validation not supported`);if(n.issues)throw new Wn(JSON.stringify(n.issues,void 0,2),{cause:n});return n.value}return`parse`in e?e.parse(t):typeof e==`function`?e(t):{}}function Jn({pathname:e,routesById:t,processedTree:n}){let r=Object.create(null),i=It(e),a,o=xt(i,n,!0);return o&&(a=o.route,Object.assign(r,o.rawParams)),{matchedRoutes:o?.branch||[t.__root__],routeParams:r,foundRoute:a}}function Yn({search:e,dest:t,destRoutes:n,_includeValidateSearch:r}){return Xn(n)(e,t,r??!1)}function Xn(e){let t={dest:null,_includeValidateSearch:!1,middlewares:[]};for(let n of e)`search`in n.options?n.options.search?.middlewares&&t.middlewares.push(...n.options.search.middlewares):(n.options.preSearchFilters||n.options.postSearchFilters)&&t.middlewares.push(({search:e,next:t})=>{let r=e;`preSearchFilters`in n.options&&n.options.preSearchFilters&&(r=n.options.preSearchFilters.reduce((e,t)=>t(e),e));let i=t(r);return`postSearchFilters`in n.options&&n.options.postSearchFilters?n.options.postSearchFilters.reduce((e,t)=>t(e),i):i}),n.options.validateSearch&&t.middlewares.push(({search:e,next:r})=>{let i=r(e);if(!t._includeValidateSearch)return i;try{return{...i,...qn(n.options.validateSearch,i)??void 0}}catch{return i}});t.middlewares.push(({search:e})=>{let n=t.dest;return n.search?n.search===!0?e:Be(n.search,e):{}});let n=(e,t,r)=>{if(e>=r.length)return t;let i=r[e];return i({search:t,next:t=>n(e+1,t,r)})};return function(e,r,i){return t.dest=r,t._includeValidateSearch=i,n(0,e,t.middlewares)}}function Zn(e,t){if(e!==`root`)for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.children)return n.id}return $t}function Qn(e,t){let n=e.options.params?.parse??e.options.parseParams;if(n){let e=n(t);if(e===!1)throw Error(`Route params.parse returned false for a matched route`);Object.assign(t,e)}}function $n(){try{return sessionStorage}catch{return}}var er=`tsr-scroll-restoration-v1_3`,tr=$n();function nr(){try{return JSON.parse(tr?.getItem(`tsr-scroll-restoration-v1_3`)||`{}`)}catch{return{}}}function rr(){try{tr?.setItem(er,JSON.stringify(ir))}catch{}}var ir=nr(),ar=`data-scroll-restoration-id`,or=e=>e.state.__TSR_key||e.href;function sr(e){let t=e.getAttribute(ar);if(t)return`[${ar}="${t}"]`;let n=``,r=e,i;for(;i=r.parentNode;){let e=1,t=r;for(;t=t.previousElementSibling;)e++;let a=`${r.localName}:nth-child(${e})`;n=n?`${a} > ${n}`:a,r=i}return n}var cr=!1,lr=`window`;function ur(e){try{return typeof e==`function`?e():document.querySelector(e)}catch{}}function dr(e){let t=[];for(let n of e){if(n===lr)continue;let e=ur(n);e&&t.push(e)}return t}function fr(e,t){if((t??e.options.scrollRestoration)&&(e.isScrollRestoring=!0),e.isScrollRestorationSetup)return;e.isScrollRestorationSetup=!0,cr=!1;let n=e.options.getScrollRestorationKey||or,r=new Map,i=(e,t,n)=>{let i=r.get(e)||{};i.scrollX=t,i.scrollY=n,r.set(e,i)};history.scrollRestoration=`manual`;let a=t=>{if(!(cr||!e.isScrollRestoring)){if(t.target===document)i(lr,scrollX,scrollY);else{let e=t.target;i(e,e.scrollLeft,e.scrollTop)}}},o=t=>{if(!e.isScrollRestoring)return;let n=ir[t]||={};for(let[e,t]of r)e===lr?n[lr]=t:e.isConnected&&(n[sr(e)]=t)};document.addEventListener(`scroll`,a,!0),e.subscribe(`onBeforeLoad`,e=>{e.fromLocation&&o(n(e.fromLocation)),r.clear()}),addEventListener(`pagehide`,()=>{o(n(e.stores.resolvedLocation.get()??e.stores.location.get())),rr()}),e.subscribe(`onRendered`,t=>{let i=e.options.scrollRestorationBehavior,a=e.options.scrollToTopSelectors,o=e.resetNextScroll,s;if(r.clear(),o||(e.resetNextScroll=!0),typeof e.options.scrollRestoration==`function`&&!e.options.scrollRestoration({location:e.latestLocation}))return;let c=n(t.toLocation),l=t.fromLocation&&n(t.fromLocation);if(e.isScrollRestoring&&l&&l!==c){let e=ir[l];if(e){let t=ir[c];for(let n in e){if(n===lr){if(o)continue}else{let e=ur(n);if(!e||o&&a&&(s??=dr(a),s.includes(e)))continue}t||=ir[c]={},t[n]??=e[n]}}}cr=!0;try{let n=t.toLocation.hash,r=t.toLocation.state.__hashScrollIntoViewOptions??!0,l=!1;if(o){let o=Hn.get(t.toLocation),u=n&&r&&(o===`PUSH`||o===`REPLACE`),d=e.isScrollRestoring?ir[c]:void 0;if(d)for(let e in d){let{scrollX:t,scrollY:n}=d[e];if(e===lr){if(u)continue;scrollTo({top:n,left:t,behavior:i}),l=!0}else{let r=ur(e);r&&(r.scrollLeft=t,r.scrollTop=n)}}if(!l&&!n){let e={top:0,left:0,behavior:i};if(scrollTo(e),a){s??=dr(a);for(let t of s)t.scrollTo(e)}}}!l&&n&&r&&document.getElementById(n)?.scrollIntoView(r)}finally{cr=!1}})}var pr=`Error preloading route! ☝️`,mr=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=e=>{this.originalIndex=e.originalIndex;let t=this.options,n=!t?.path&&!t?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=$t:this.parentRoute||st();let r=n?$t:t?.path;r&&r!==`/`&&(r=Ft(r));let i=t?.id||r,a=n?$t:Nt([this.parentRoute.id===`__root__`?``:this.parentRoute.id,i]);r===`__root__`&&(r=`/`),a!==`__root__`&&(a=Nt([`/`,a]));let o=a===`__root__`?`/`:Nt([this.parentRoute.fullPath,r]);this._path=r,this._id=a,this._fullPath=o,this._to=It(o)},this.addChildren=e=>this._addFileChildren(e),this._addFileChildren=e=>(Array.isArray(e)&&(this.children=e),typeof e==`object`&&e&&(this.children=Object.values(e)),this),this._addFileTypes=()=>this,this.updateLoader=e=>(Object.assign(this.options,e),this),this.update=e=>(Object.assign(this.options,e),this),this.lazy=e=>(this.lazyFn=e,this),this.redirect=e=>en({from:this.fullPath,...e}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw Error(`Route cannot have both an 'id' and a 'path' option.`)}},hr=class extends mr{constructor(e){super(e)}};function gr(e){let t=e.errorComponent??vr;return(0,B.jsx)(_r,{getResetKey:e.getResetKey,onCatch:e.onCatch,children:({error:n,reset:r})=>n?z.createElement(t,{error:n,reset:r}):e.children})}var _r=class extends z.Component{constructor(...e){super(...e),this.state={error:null}}static getDerivedStateFromProps(e,t){let n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:null}:{resetKey:n}}static getDerivedStateFromError(e){return{error:e}}reset(){this.setState({error:null})}componentDidCatch(e,t){this.props.onCatch&&this.props.onCatch(e,t)}render(){return this.props.children({error:this.state.error,reset:()=>{this.reset()}})}};function vr({error:e}){let[t,n]=z.useState(!1);return(0,B.jsxs)(`div`,{style:{padding:`.5rem`,maxWidth:`100%`},children:[(0,B.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`.5rem`},children:[(0,B.jsx)(`strong`,{style:{fontSize:`1rem`},children:`Something went wrong!`}),(0,B.jsx)(`button`,{style:{appearance:`none`,fontSize:`.6em`,border:`1px solid currentColor`,padding:`.1rem .2rem`,fontWeight:`bold`,borderRadius:`.25rem`},onClick:()=>n(e=>!e),children:t?`Hide Error`:`Show Error`})]}),(0,B.jsx)(`div`,{style:{height:`.25rem`}}),t?(0,B.jsx)(`div`,{children:(0,B.jsx)(`pre`,{style:{fontSize:`.7em`,border:`1px solid red`,borderRadius:`.25rem`,padding:`.3rem`,color:`red`,overflow:`auto`},children:e.message?(0,B.jsx)(`code`,{children:e.message}):null})}):null]})}function yr({children:e,fallback:t=null}){return br()?(0,B.jsx)(z.Fragment,{children:e}):(0,B.jsx)(z.Fragment,{children:t})}function br(){return z.useSyncExternalStore(xr,()=>!0,()=>!1)}function xr(){return()=>{}}var Sr=z.createContext(null);function Cr(e){return z.useContext(Sr)}var wr=z.createContext(void 0),Tr=z.createContext(void 0),Er=(e=>(e[e.None=0]=`None`,e[e.Mutable=1]=`Mutable`,e[e.Watching=2]=`Watching`,e[e.RecursedCheck=4]=`RecursedCheck`,e[e.Recursed=8]=`Recursed`,e[e.Dirty=16]=`Dirty`,e[e.Pending=32]=`Pending`,e))(Er||{});function Dr({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function Or(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var kr=[],Ar=0,{link:jr,unlink:Mr,propagate:Nr,checkDirty:Pr,shallowPropagate:Fr}=Dr({update(e){return e._update()},notify(e){kr[Lr++]=e,e.flags&=~Er.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=Er.Mutable|Er.Dirty,Vr(e))}}),Ir=0,Lr=0,Rr,zr=0;function Br(e){try{++zr,e()}finally{--zr||Hr()}}function Vr(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=Mr(n,e)}function Hr(){if(!(zr>0)){for(;Ir{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=Rr,o=t?.compare??Object.is;if(n)Rr=i,++Ar,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=Er.Mutable|Er.RecursedCheck);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{Rr=a,n&&(i.flags&=~Er.RecursedCheck),Vr(i)}}};return n?(i.flags=Er.Mutable|Er.Dirty,i.get=function(){let e=i.flags;if(e&Er.Dirty||e&Er.Pending&&Pr(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&Fr(e)}}else e&Er.Pending&&(i.flags=e&~Er.Pending);return Rr!==void 0&&jr(i,Rr,Ar),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(Nr(e),Fr(e),Hr())}},i}function Wr(e){let t=()=>{let t=Rr;Rr=n,++Ar,n.depsTail=void 0,n.flags=Er.Watching|Er.RecursedCheck;try{return e()}finally{Rr=t,n.flags&=~Er.RecursedCheck,Vr(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:Er.Watching|Er.RecursedCheck,notify(){let e=this.flags;e&Er.Dirty||e&Er.Pending&&Pr(this.deps,this)?t():this.flags=Er.Watching},stop(){this.flags=Er.None,this.depsTail=void 0,Vr(this)}};return t(),n}var Gr=o((e=>{var t=f();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 d=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?d:t.useSyncExternalStore})),Kr=o(((e,t)=>{t.exports=Gr()})),qr=o((e=>{var t=f(),n=Kr();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}})),Jr=o(((e,t)=>{t.exports=qr()}))();function Yr(e,t){return e===t}function Xr(e,t,n=Yr){let r=(0,z.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,z.useCallback)(()=>e?.get(),[e]);return(0,Jr.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var Zr={get:()=>void 0,subscribe:()=>({unsubscribe:()=>{}})};function Qr(e){let t=Cr(),n=z.useContext(e.from?Tr:wr),r=e.from??n,i=r?e.from?t.stores.getRouteMatchStore(r):t.stores.matchStores.get(r):void 0,a=z.useRef(void 0);return Xr(i??Zr,n=>{if((e.shouldThrow??!0)&&!n&&st(),n===void 0)return;let r=e.select?e.select(n):n;if(e.structuralSharing??t.options.defaultStructuralSharing){let e=Ke(a.current,r);return a.current=e,e}return r})}function $r(e){return Qr({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function ei(e){let{select:t,...n}=e;return Qr({...n,select:e=>t?t(e.loaderDeps):e.loaderDeps})}function ti(e){return Qr({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function ni(e){return Qr({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function ri(e){let t=Cr();return z.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function ii(e){let t=Cr(),n=ri(),r=z.useRef(null);return Fe(()=>{r.current!==e&&(n(e),r.current=e)},[t,e,n]),null}function ai(e){return Qr({...e,select:t=>e.select?e.select(t.context):t.context})}var oi=m();function si(e,t){let n=Cr(),r=Le(t),{activeProps:i,inactiveProps:a,activeOptions:o,to:s,preload:c,preloadDelay:l,preloadIntentProximity:u,hashScrollIntoView:d,replace:f,startTransition:p,resetScroll:m,viewTransition:h,children:g,target:_,disabled:v,style:y,className:b,onClick:x,onBlur:S,onFocus:C,onMouseEnter:w,onMouseLeave:T,onTouchStart:E,ignoreBlocker:D,params:O,search:ee,hash:te,state:ne,mask:k,reloadDocument:A,unsafeRelative:j,from:M,_fromLocation:N,...P}=e,F=br(),re=z.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),ie=Xr(n.stores.location,e=>e,(e,t)=>e.href===t.href),I=z.useMemo(()=>{let e={_fromLocation:ie,...re};return n.buildLocation(e)},[n,ie,re]),ae=I.maskedLocation?I.maskedLocation.publicHref:I.publicHref,L=I.maskedLocation?I.maskedLocation.external:I.external,oe=z.useMemo(()=>gi(ae,L,n.history,v),[v,L,ae,n.history]),se=z.useMemo(()=>{if(oe?.external)return rt(oe.href,n.protocolAllowlist)?void 0:oe.href;if(!_i(s)&&typeof s==`string`&&s.indexOf(`:`)!==-1)try{return new URL(s),rt(s,n.protocolAllowlist)?void 0:s}catch{}},[s,oe,n.protocolAllowlist]),ce=z.useMemo(()=>{if(se)return!1;if(o?.exact){if(!zt(ie.pathname,I.pathname,n.basepath))return!1}else{let e=Rt(ie.pathname,n.basepath),t=Rt(I.pathname,n.basepath);if(!(e.startsWith(t)&&(e.length===t.length||e[t.length]===`/`)))return!1}return(o?.includeSearch??!0)&&!Ze(ie.search,I.search,{partial:!o?.exact,ignoreUndefined:!o?.explicitUndefined})?!1:!o?.includeHash||F&&ie.hash===I.hash},[o?.exact,o?.explicitUndefined,o?.includeHash,o?.includeSearch,ie,se,F,I.hash,I.pathname,I.search,n.basepath]),le=ce?Be(i,{})??li:ci,ue=ce?ci:Be(a,{})??ci,de=[b,le.className,ue.className].filter(Boolean).join(` `),fe=(y||le.style||ue.style)&&{...y,...le.style,...ue.style},[pe,me]=z.useState(!1),he=z.useRef(!1),ge=e.reloadDocument||se?!1:c??n.options.defaultPreload,_e=l??n.options.defaultPreloadDelay??0,ve=z.useCallback(()=>{n.preloadRoute({...re,_builtLocation:I}).catch(e=>{console.warn(e),console.warn(pr)})},[n,re,I]);Ie(r,z.useCallback(e=>{e?.isIntersecting&&ve()},[ve]),mi,{disabled:!!v||ge!==`viewport`}),z.useEffect(()=>{he.current||!v&&ge===`render`&&(ve(),he.current=!0)},[v,ve,ge]);let ye=e=>{let t=e.currentTarget.getAttribute(`target`),r=_===void 0?t:_;if(!v&&!yi(e)&&!e.defaultPrevented&&(!r||r===`_self`)&&e.button===0){e.preventDefault(),(0,oi.flushSync)(()=>{me(!0)});let t=n.subscribe(`onResolved`,()=>{t(),me(!1)});n.navigate({...re,replace:f,resetScroll:m,hashScrollIntoView:d,startTransition:p,viewTransition:h,ignoreBlocker:D})}};if(se)return{...P,ref:r,href:se,...g&&{children:g},..._&&{target:_},...v&&{disabled:v},...y&&{style:y},...b&&{className:b},...x&&{onClick:x},...S&&{onBlur:S},...C&&{onFocus:C},...w&&{onMouseEnter:w},...T&&{onMouseLeave:T},...E&&{onTouchStart:E}};let be=e=>{if(v||ge!==`intent`)return;if(!_e){ve();return}let t=e.currentTarget;if(pi.has(t))return;let n=setTimeout(()=>{pi.delete(t),ve()},_e);pi.set(t,n)},xe=e=>{v||ge!==`intent`||ve()},Se=e=>{if(v||!ge||!_e)return;let t=e.currentTarget,n=pi.get(t);n&&(clearTimeout(n),pi.delete(t))};return{...P,...le,...ue,href:oe?.href,ref:r,onClick:hi([x,ye]),onBlur:hi([S,Se]),onFocus:hi([C,be]),onMouseEnter:hi([w,be]),onMouseLeave:hi([T,Se]),onTouchStart:hi([E,xe]),disabled:!!v,target:_,...fe&&{style:fe},...de&&{className:de},...v&&ui,...ce&&di,...F&&pe&&fi}}var ci={},li={className:`active`},ui={role:`link`,"aria-disabled":!0},di={"data-status":`active`,"aria-current":`page`},fi={"data-transitioning":`transitioning`},pi=new WeakMap,mi={rootMargin:`100px`},hi=e=>t=>{for(let n of e)if(n){if(t.defaultPrevented)return;n(t)}};function gi(e,t,n,r){if(!r)return t?{href:e,external:!0}:{href:n.createHref(e)||`/`,external:!1}}function _i(e){if(typeof e!=`string`)return!1;let t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var vi=z.forwardRef((e,t)=>{let{_asChild:n,...r}=e,{type:i,...a}=si(r,t),o=typeof r.children==`function`?r.children({isActive:a[`data-status`]===`active`}):r.children;if(!n){let{disabled:e,...t}=a;return z.createElement(`a`,t,o)}return z.createElement(n,a,o)});function yi(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var bi=class extends mr{constructor(e){super(e),this.useMatch=e=>Qr({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>ai({...e,from:this.id}),this.useSearch=e=>ni({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>ti({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>ei({...e,from:this.id}),this.useLoaderData=e=>$r({...e,from:this.id}),this.useNavigate=()=>ri({from:this.fullPath}),this.Link=z.forwardRef((e,t)=>(0,B.jsx)(vi,{ref:t,from:this.fullPath,...e}))}};function xi(e){return new bi(e)}var Si=class extends hr{constructor(e){super(e),this.useMatch=e=>Qr({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>ai({...e,from:this.id}),this.useSearch=e=>ni({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>ti({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>ei({...e,from:this.id}),this.useLoaderData=e=>$r({...e,from:this.id}),this.useNavigate=()=>ri({from:this.fullPath}),this.Link=z.forwardRef((e,t)=>(0,B.jsx)(vi,{ref:t,from:this.fullPath,...e}))}};function Ci(e){return new Si(e)}function wi(e){let t=Cr(),n=`not-found-${Xr(t.stores.location,e=>e.pathname)}-${Xr(t.stores.status,e=>e)}`;return(0,B.jsx)(gr,{getResetKey:()=>n,onCatch:(t,n)=>{if(Gt(t))e.onCatch?.(t,n);else throw t},errorComponent:({error:t})=>{if(Gt(t))return e.fallback?.(t);throw t},children:e.children})}function Ti(){return(0,B.jsx)(`p`,{children:`Not Found`})}function Ei(e){return(0,B.jsx)(B.Fragment,{children:e.children})}function Di(e,t,n){return t.options.notFoundComponent?(0,B.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,B.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,B.jsx)(Ti,{})}var Oi=z.memo(function({matchId:e}){let t=Cr(),n=t.stores.matchStores.get(e);n||st();let r=Xr(t.stores.loadedAt,e=>e),i=Xr(n,e=>e);return(0,B.jsx)(ki,{router:t,matchId:e,resetKey:r,matchState:z.useMemo(()=>{let e=i.routeId,n=t.routesById[e].parentRoute?.id;return{routeId:e,ssr:i.ssr,_displayPending:i._displayPending,parentRouteId:n}},[i._displayPending,i.routeId,i.ssr,t.routesById])})});function ki({router:e,matchId:t,resetKey:n,matchState:r}){let i=e.routesById[r.routeId],a=i.options.pendingComponent??e.options.defaultPendingComponent,o=a?(0,B.jsx)(a,{}):null,s=i.options.errorComponent??e.options.defaultErrorComponent,c=i.options.onCatch??e.options.defaultOnCatch,l=i.isRoot?i.options.notFoundComponent??e.options.notFoundRoute?.options.component:i.options.notFoundComponent,u=r.ssr===!1||r.ssr===`data-only`,d=(!i.isRoot||i.options.wrapInSuspense||u)&&(i.options.wrapInSuspense??a??(i.options.errorComponent?.preload||u))?z.Suspense:Ei,f=s?gr:Ei,p=l?wi:Ei;return(0,B.jsxs)(i.isRoot?i.options.shellComponent??Ei:Ei,{children:[(0,B.jsx)(wr.Provider,{value:t,children:(0,B.jsx)(d,{fallback:o,children:(0,B.jsx)(f,{getResetKey:()=>n,errorComponent:s||vr,onCatch:(e,t)=>{if(Gt(e))throw e.routeId??=r.routeId,e;c?.(e,t)},children:(0,B.jsx)(p,{fallback:e=>{if(e.routeId??=r.routeId,!l||e.routeId&&e.routeId!==r.routeId||!e.routeId&&!i.isRoot)throw e;return z.createElement(l,e)},children:u||r._displayPending?(0,B.jsx)(yr,{fallback:o,children:(0,B.jsx)(ji,{matchId:t})}):(0,B.jsx)(ji,{matchId:t})})})})}),r.parentRouteId===`__root__`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(Ai,{resetKey:n}),(e.options.scrollRestoration,null)]}):null]})}function Ai({resetKey:e}){let t=Cr(),n=z.useRef(void 0);return Fe(()=>{let e=t.latestLocation.href;(n.current===void 0||n.current!==e)&&(t.emit({type:`onRendered`,...Vn(t.stores.location.get(),t.stores.resolvedLocation.get())}),n.current=e)},[t.latestLocation.state.__TSR_key,e,t]),null}var ji=z.memo(function({matchId:e}){let t=Cr(),n=(e,n)=>t.getMatch(e.id)?._nonReactive[n]??e._nonReactive[n],r=t.stores.matchStores.get(e);r||st();let i=Xr(r,e=>e),a=i.routeId,o=t.routesById[a],s=z.useMemo(()=>{let e=(t.routesById[a].options.remountDeps??t.options.defaultRemountDeps)?.({routeId:a,loaderDeps:i.loaderDeps,params:i._strictParams,search:i._strictSearch});return e?JSON.stringify(e):void 0},[a,i.loaderDeps,i._strictParams,i._strictSearch,t.options.defaultRemountDeps,t.routesById]),c=z.useMemo(()=>{let e=o.options.component??t.options.defaultComponent;return e?(0,B.jsx)(e,{},s):(0,B.jsx)(Mi,{})},[s,o.options.component,t.options.defaultComponent]);if(i._displayPending)throw n(i,`displayPendingPromise`);if(i._forcePending)throw n(i,`minPendingPromise`);if(i.status===`pending`){let e=o.options.pendingMinMs??t.options.defaultPendingMinMs;if(e){let n=t.getMatch(i.id);if(n&&!n._nonReactive.minPendingPromise){let t=Qe();n._nonReactive.minPendingPromise=t,setTimeout(()=>{t.resolve(),n._nonReactive.minPendingPromise=void 0},e)}}throw n(i,`loadPromise`)}if(i.status===`notFound`)return Gt(i.error)||st(),Di(t,o,i.error);if(i.status===`redirected`)throw tn(i.error)||st(),n(i,`loadPromise`);if(i.status===`error`)throw i.error;return c}),Mi=z.memo(function(){let e=Cr(),t=z.useContext(wr),n,r=!1,i;{let a=t?e.stores.matchStores.get(t):void 0;[n,r]=Xr(a,e=>[e?.routeId,e?.globalNotFound??!1]),i=Xr(e.stores.matchesId,e=>e[e.findIndex(e=>e===t)+1])}let a=n?e.routesById[n]:void 0,o=e.options.defaultPendingComponent?(0,B.jsx)(e.options.defaultPendingComponent,{}):null;if(r)return a||st(),Di(e,a,void 0);if(!i)return null;let s=(0,B.jsx)(Oi,{matchId:i});return n===`__root__`?(0,B.jsx)(z.Suspense,{fallback:o,children:s}):s});function Ni(){let e=Cr(),t=z.useRef({router:e,mounted:!1}),[n,r]=z.useState(!1),i=Xr(e.stores.isLoading,e=>e),a=Xr(e.stores.hasPending,e=>e),o=V(i),s=i||n||a,c=V(s),l=i||a,u=V(l);return e.startTransition=e=>{r(!0),z.startTransition(()=>{e(),r(!1)})},z.useEffect(()=>{let t=e.history.subscribe(e.load),n=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return It(e.latestLocation.publicHref)!==It(n.publicHref)&&e.commitLocation({...n,replace:!0}),()=>{t()}},[e,e.history]),Fe(()=>{typeof window<`u`&&e.ssr||t.current.router===e&&t.current.mounted||(t.current={router:e,mounted:!0},(async()=>{try{await e.load()}catch(e){console.error(e)}})())},[e]),Fe(()=>{o&&!i&&e.emit({type:`onLoad`,...Vn(e.stores.location.get(),e.stores.resolvedLocation.get())})},[o,e,i]),Fe(()=>{u&&!l&&e.emit({type:`onBeforeRouteMount`,...Vn(e.stores.location.get(),e.stores.resolvedLocation.get())})},[l,u,e]),Fe(()=>{if(c&&!s){let t=Vn(e.stores.location.get(),e.stores.resolvedLocation.get());e.emit({type:`onResolved`,...t}),Br(()=>{e.stores.status.set(`idle`),e.stores.resolvedLocation.set(e.stores.location.get())})}},[s,c,e]),null}function Pi(){let e=Cr(),t=e.routesById.__root__.options.pendingComponent??e.options.defaultPendingComponent,n=t?(0,B.jsx)(t,{}):null,r=(0,B.jsxs)(typeof document<`u`&&e.ssr?Ei:z.Suspense,{fallback:n,children:[(0,B.jsx)(Ni,{}),(0,B.jsx)(Fi,{})]});return e.options.InnerWrap?(0,B.jsx)(e.options.InnerWrap,{children:r}):r}function Fi(){let e=Cr(),t=Xr(e.stores.firstId,e=>e),n=Xr(e.stores.loadedAt,e=>e),r=t?(0,B.jsx)(Oi,{matchId:t}):null;return(0,B.jsx)(wr.Provider,{value:t,children:e.options.disableGlobalCatchBoundary?r:(0,B.jsx)(gr,{getResetKey:()=>n,errorComponent:vr,onCatch:void 0,children:r})})}var Ii=e=>({createMutableStore:Ur,createReadonlyStore:Ur,batch:Br}),Li=e=>new Ri(e),Ri=class extends Un{constructor(e){super(e,Ii)}};function zi({router:e,children:t,...n}){Ue(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});let r=(0,B.jsx)(Sr.Provider,{value:e,children:t});return e.options.Wrap?(0,B.jsx)(e.options.Wrap,{children:r}):r}function Bi({router:e,...t}){return(0,B.jsx)(zi,{router:e,...t,children:(0,B.jsx)(Pi,{})})}var Vi=g(),Hi=(0,z.createContext)(null),Ui=`loopx-pw-locale`,Wi={en:{"acceptance.connected":`Connected`,"acceptance.mapped":`Project mapped`,"acceptance.refreshed":`State refreshed`,"acceptance.inspected":`Adapter inspected`,"acceptance.recorded":`Run recorded`,"acceptance.judged":`Feedback recorded`,"acceptance.approved":`Approval recorded`,"acceptance.ready":`Controller readiness recorded`,"acceptance.attentionSource":`Current status`,"acceptance.visionSource":`Agent acceptance criteria`,"acceptance.todoSource":`Task state`,"acceptance.runSource":`Fresh run evidence`,"acceptance.title":`Acceptance observations`,"acceptance.unavailable":`Acceptance observations are unavailable. Goal completion is unknown.`,"acceptance.partial":`Partial observations only. Completed tasks and an empty gap list do not prove Goal acceptance.`,"acceptance.gaps":`Evidence still required`,"acceptance.reasonUnknown":`Reason not provided by the source`,"acceptance.unknown":`Unknown`,"acceptance.required":`Required evidence or condition`,"acceptance.observed":`Observed at`,"acceptance.noGaps":`No gaps in the available observations. Full acceptance has not been assessed.`,"acceptance.guards":`Pending gates`,"acceptance.noGuards":`No pending gates in the available observations.`,"acceptance.scope":`Decision scope`,"acceptance.next":`Next action from current status`,"acceptance.historical_progress":`Recorded progress`,"acceptance.historical":`Historical lifecycle observations do not grant permission or certify acceptance.`,"acceptance.missing":`Sources not available:`,"acceptance.truncated":`Only the first 12 observations are shown.`,"common.actions":`Actions`,"common.agent":`Agent`,"common.allMessages":`All messages`,"common.cancel":`Cancel`,"common.close":`Close`,"common.closeActionReceipt":`Close action receipt`,"common.confirm":`Confirm`,"common.export":`Export`,"common.failed":`Failed`,"common.goal":`Goal`,"common.loading":`Loading…`,"common.none":`None`,"common.off":`Off`,"common.on":`On`,"common.open":`Open`,"common.owner":`Owner`,"common.readOnly":`Read only`,"common.recently":`Just now`,"common.status":`Status`,"common.task":`Task`,"common.you":`You`,"common.waiting":`Waiting`,"composer.addImage":`Add image`,"composer.agentProgress":`Ask Agent for a progress report`,"composer.agentProgressPrompt":`Give me a progress report for this Goal: completed, running, blocked, and next steps.`,"composer.attachImageHint":`Choose, paste, or drag an image`,"composer.clarifyDefer":`Deferring a Todo requires a deterministic resume condition. Add todo_done:, pr_merged:[owner/repo]#, capacity_available:, or resume_at:.`,"composer.clarifySingleAction":`This message contains multiple operations that may change state. Describe one operation at a time so each confirmation preview can be reviewed separately.`,"composer.createGoal":`Create Goal`,"composer.createGoalDraft":`Goal draft`,"composer.createGoalDraftDescription":`Complete the draft and send it. LoopX will show a confirmation preview first.`,"composer.createGoalDraftLead":`Create a long-term Goal:`,"composer.createGoalTemplate":`Create a long-term Goal: +Objective: +Completion criteria: +Execution boundary (optional): +Related repository (optional): +Notification method (optional):`,"composer.createGoalHint":`Insert a Goal template to review before creation`,"composer.draft":`Draft`,"composer.globalProgress":`Summarize all Goal progress`,"composer.globalProgressPrompt":`Summarize the latest progress and blockers for all active Goals.`,"composer.globalTasks":`Ask about global priorities`,"composer.globalTasksPrompt":`Which Goals need me, and what should I handle first?`,"composer.goalMessageHint":`Your message is delivered to {agent} in this Goal session.`,"composer.goalRunningHint":`{agent} is running {count} tasks · your message enters this session as guidance without interrupting it`,"composer.goalPlaceholder":`Ask or guide {goal}…`,"composer.imageAnalysisPrompt":`Analyze these images in the context of the current Goal and tell me the next step.`,"composer.imageCountError":`You can add up to {count} images.`,"composer.imagePicker":`Image file picker`,"composer.imageReadError":`Could not read image {name}.`,"composer.imageReadGenericError":`Could not read the image.`,"composer.imageSizeError":`Each image must be {size} MB or smaller.`,"composer.imageTypeError":`PNG, JPEG, WebP, and GIF images are supported.`,"composer.imagesPending":`Images to send`,"composer.immediate":`Send now`,"composer.managerMessageHint":`Your message goes to the LoopX Manager across Goals for global questions or Goal creation.`,"composer.managerPlaceholder":`Ask the LoopX Manager, or describe a new Goal…`,"composer.monitor":`Configure scheduled check`,"composer.monitorGoalQuestion":`Which Goal should receive the scheduled check?`,"composer.monitorTemplate":`Add a scheduled check for the current Goal: +Check target: +Frequency (supports 30 minutes / 2 hours / daily): Every 2 hours +Stop condition: Goal completes`,"composer.monitorTemplateWithoutGoal":`Configure a scheduled check: +Goal: +Check target: +Frequency: Every 2 hours +Stop condition: Goal completes`,"composer.monitorHint":`Fill in what to check, frequency, and stop condition before creation`,"composer.heartbeatGoalQuestion":`Which Goal should receive the Heartbeat?`,"composer.heartbeatTemplate":`Set a Heartbeat for the current Goal: +Frequency: Daily +Stop condition: Goal completes +Notification: Only notify me when needed`,"composer.heartbeatTemplateWithoutGoal":`Set up a Heartbeat: +Goal: +Frequency: Daily +Stop condition: Goal completes +Notification: Only notify me when needed`,"composer.nextAction":`Ask what’s next`,"composer.nextActionPrompt":`What should I do next?`,"composer.prepareDraft":`Insert a draft and review before sending`,"composer.send":`Send`,"composer.sendMessage":`Send a message to LoopX`,"composer.sendMessageHint":`Send message`,"composer.sentImageAlt":`Remove image {name}`,"conversation.agentPending":`Working…`,"conversation.close":`Close conversation receipt`,"conversation.convertHint":`Turn the Agent’s latest reply into a Task draft`,"conversation.full":`View full conversation`,"conversation.receipt":`Conversation receipt`,"conversation.replying":`Replying`,"conversation.title":`Manager conversation`,"conversation.toTask":`Convert to Task`,"digest.away":`Runs since your previous visit`,"digest.completed":`new completions`,"digest.failed":`new failed/interrupted runs`,"digest.needsYou":`currently need confirmation`,"feedback.applying":`Running: {title}`,"feedback.cancelFailed":`Cancel failed: {error}`,"feedback.completed":`Completed: {title}`,"feedback.executionFailed":`Execution failed: {error}`,"feedback.gateRequired":`Your confirmation is required: {summary}`,"feedback.notCompleted":`Not completed: {status}`,"feedback.goalRefreshFailed":`The Goal opened, but its latest state could not be refreshed. Use Refresh to try again.`,"feedback.preparingPreview":`Preparing confirmation preview: {title}`,"feedback.previewFailed":`Could not prepare the confirmation preview: {error}`,"feedback.sendFailed":`Send failed: {error}`,"feedback.sendGenericError":`Could not send the message. Try again later.`,"feedback.stale":`State changed, so nothing was applied. Generate a new confirmation preview.`,"feedback.taskDraftCreated":`Created a Task draft from the reply. Edit and send it to review the confirmation preview.`,"goal.defaultTitle":`New personal Goal`,"goal.initialTodo":`Work toward the completion criteria: {criteria}`,"goal.objectiveBoundary":`Execution boundary: {boundary}`,"goal.objectiveCompletion":`Completion criteria: {criteria}`,"drawer.advancedDiagnostics":`Advanced diagnostics`,"drawer.agentWorking":`Agent is continuing; the record updates automatically.`,"drawer.analysis":`Analyzing`,"drawer.apply":`Confirm and apply`,"drawer.applying":`Applying…`,"drawer.attentionBlocking":`Blocking an Agent`,"drawer.attentionWaiting":`Waiting for your decision`,"drawer.autoNotify":`Human-gate auto notifications`,"drawer.branch":`Branch`,"drawer.closeDetail":`Close details and return to {context}`,"drawer.connected":`Connected`,"drawer.correctionDescription":`The message keeps the current Goal, Todo, and Agent Session context.`,"drawer.correctionLabel":`Guide {agent}`,"drawer.correctionPlaceholder":`For example: focus on permission risks first and do not commit yet…`,"drawer.correctionSend":`Send guidance`,"drawer.correctionTextarea":`Enter guidance for Goal {goal}, Agent {agent}, Run {run}`,"drawer.copyRepository":`Copy repository identity`,"drawer.copyRepositoryDone":`Repository identity copied`,"drawer.copyRepositoryError":`Copy failed. Check browser clipboard permission.`,"drawer.copyRepositorySuccess":`Copied. You can paste it into another tool.`,"drawer.cost":`Cost 24h / 7d`,"drawer.costShort":`Cost`,"drawer.durationShort":`Duration`,"drawer.period24h":`24h`,"drawer.period7d":`7d`,"drawer.tokens":`Tokens 24h / 7d`,"drawer.tokensShort":`tokens`,"drawer.usageNotMeasured":`Not measured`,"drawer.currentGoal":`Current Goal`,"attentionDetail.title":`Request details`,"attentionDetail.request":`What is requested`,"attentionDetail.decision":`Decision requested`,"attentionDetail.unknownRequest":`Not specified; review the source before deciding`,"attentionDetail.open":`Open in current projection`,"attentionDetail.closed":`Closed`,"attentionDetail.deferred":`Deferred`,"attentionDetail.superseded":`Replaced`,"attentionDetail.unknown":`Status not provided`,"attentionDetail.unavailable":`The source has not confirmed this item; refresh before acting`,"attentionDetail.unknownReason":`The source has not provided a reason.`,"attentionDetail.targetTodo":`Linked Todo to unblock`,"attentionDetail.targetAgent":`Agent named by the request`,"attentionDetail.scope":`Declared decision scope`,"attentionDetail.notProvided":`Not provided`,"attentionDetail.replacement":`Replacement Todo`,"attentionDetail.openReplacement":`Open replacement`,"attentionDetail.boundary":`Reading this detail does not resolve a gate or grant authority. Available decisions require a fresh preview.`,"drawer.decisionDefaultEvidence":`No additional public-safe evidence is attached. The next step will still show a Preview first.`,"drawer.decisionDefaultReason":`This decision affects the next step of the current Todo.`,"drawer.decisionDefer":`Decide later`,"drawer.decisionMore":`More decisions`,"drawer.decisionReject":`Reject`,"drawer.decisionReview":`Review impact and decide`,"drawer.dependencies":`Dependencies`,"drawer.detailsAndActions":`Details & actions`,"drawer.duration":`Duration 24h / 7d`,"drawer.evidence":`Evidence`,"drawer.executionHistory":`Execution history`,"drawer.executionRecord":`Run record`,"drawer.executionRecordAndResult":`Execution & result`,"drawer.explainDecision":`Explain this decision`,"drawer.gateApproveHint":`Run one command in the terminal to complete approval:`,"drawer.gateRejectHint":`Replace approve with reject at the end to decline. This notice disappears after the command runs.`,"drawer.gateRequiresHost":`Host confirmation required`,"drawer.gateRequiresHostDescription":`This page cannot approve this protected permission change. Nothing was written by your click.`,"drawer.goalAutoRun":`Automatic runs for this Goal`,"drawer.goalChanges":`Pending changes for this Goal`,"drawer.goalDetails":`Goal details`,"drawer.group":`Group`,"drawer.inspectorFull":`Switch to full screen`,"drawer.inspectorFullView":`Full-screen view`,"drawer.inspectorHalf":`Switch to half screen`,"drawer.inspectorHalfView":`Half-screen view`,"drawer.lastNotification":`Latest notification`,"drawer.larkConfigure":`Configure Lark connection`,"drawer.larkConnect":`Connect Lark App`,"drawer.larkConnection":`Lark connection`,"drawer.larkNotConfigured":`Not configured`,"drawer.larkNotConfiguredDescription":`After setup, LoopX sends a Feishu notification when this Goal needs your confirmation.`,"drawer.managerChanges":`Pending Manager changes`,"drawer.moreActions":`More actions`,"drawer.moreRunActions":`More run actions`,"drawer.nextTransition":`Next transition`,"drawer.noExecutionHistory":`No execution history yet.`,"drawer.noRun":`Execution Session has not started`,"drawer.noRunDescription":`Run records will appear here after an Agent starts execution.`,"drawer.notAssigned":`Unassigned`,"drawer.notLinked":`Not linked`,"drawer.notSet":`Not set`,"drawer.outputDetails":`Output details`,"drawer.outputRecorded":`This output is recorded on the current Goal.`,"drawer.outputSafePreview":`Public-safe output preview`,"drawer.outputRun":`Run`,"drawer.outputTodo":`Todo`,"drawer.outputs":`Outputs from this run`,"drawer.previewUnavailable":`No public-safe inline preview is available for this output.`,"drawer.priority":`Priority`,"drawer.progress":`Progress`,"drawer.proposalApplied":`Applied. LoopX state will refresh.`,"drawer.proposalApplyFailed":`Apply failed. No changes were written.`,"drawer.proposalApplyFailedHint":`Refresh the Goal state and regenerate. If it still fails, keep this page open and inspect advanced diagnostics.`,"drawer.proposalClose":`Close`,"drawer.proposalDefer":`Later`,"drawer.proposalDeferred":`Deferred. You can apply it later or regenerate it.`,"drawer.proposalEnterGoal":`Open new Goal`,"drawer.proposalExplainer":`After confirmation, LoopX applies this change and shows the write result. Closing or canceling changes nothing.`,"drawer.proposalRecheck":`Recheck against latest state`,"drawer.proposalRegenerate":`Retry with latest state`,"drawer.proposalRejected":`Rejected. This change will not be written.`,"drawer.proposalStale":`Source state changed. Recheck against the latest state.`,"drawer.proposalViewGoal":`View updated Goal`,"drawer.reassign":`Reassign to`,"drawer.reassignSummary":`Reassign: {task}`,"drawer.reason":`Reason`,"drawer.recoveryDescription":`Local history is preserved. Choose a recovery path.`,"drawer.recoveryFailed":`Upstream Session recovery failed`,"drawer.recoveryNewSession":`Start a new Session with context`,"drawer.recoveryRetry":`Retry recovery`,"drawer.repositoryRole":`Execution workspace`,"drawer.repository":`Repository`,"drawer.replyMode":`Reply mode`,"drawer.subagentApplied":`Applied and verified against the shared Goal state.`,"drawer.subagentAppliedRefreshFailed":`Applied and verified. The status view could not refresh; retry the page refresh later.`,"drawer.subagentApplying":`Applying and verifying shared-state readback…`,"drawer.subagentApplyFailed":`Could not apply the sub-agent setting.`,"drawer.subagentChildLimit":`Current limit`,"drawer.subagentConfirmDisable":`Confirm turning off sub-agent execution`,"drawer.subagentConfirmEnable":`Confirm turning on sub-agent execution`,"drawer.subagentCurrentBoundary":`Current task-domain restriction`,"drawer.subagentDescription":`Allows the runtime to create temporary child agents for independent tasks only after Todo, quota, capability, and write-scope gates pass. It does not force parallel work or grant durable authority.`,"drawer.subagentDisable":`Preview turning off sub-agent execution`,"drawer.subagentDisableSummary":`New child-agent execution will be disabled for this Goal. Existing Todo ownership and execution records stay unchanged.`,"drawer.subagentDomainInvalid":`The selected task-domain restriction is invalid.`,"drawer.subagentDomainTodoCount":`{count} matching open Todos`,"drawer.subagentDomains":`Task-domain restriction (optional)`,"drawer.subagentDomainsEmpty":`No open advancement Todo declares task_domain. Leave this empty to keep child execution unrestricted by task domain.`,"drawer.subagentDomainsHint":`Leave every option clear to apply no task-domain filter. Selecting domains admits only matching typed Todos; all other execution gates still apply.`,"drawer.subagentDomainsUnrestricted":`No task-domain restriction`,"drawer.subagentEnable":`Preview turning on sub-agent execution`,"drawer.subagentLabel":`Per-Goal execution boundary`,"drawer.subagentModel":`Child model`,"drawer.subagentEffort":`Child reasoning effort`,"drawer.subagentModelDefault":`Host default`,"drawer.subagentLunaPreset":`Use Luna / max`,"drawer.subagentClearModel":`Clear model preference`,"drawer.subagentModelHint":`Use Preview configuration update to save this preference. It can be saved while execution is off; host support is checked at launch.`,"drawer.subagentModelRequired":`Choose a child model before setting reasoning effort.`,"drawer.subagentMaxChildren":`Maximum child agents`,"drawer.subagentNoChange":`The current Goal already matches this setting; nothing was written.`,"drawer.subagentPending":`Pending confirmation`,"drawer.subagentPreviewBoundary":`Preview configuration update`,"drawer.subagentPreviewFailed":`Could not create the sub-agent setting preview.`,"drawer.subagentPreviewing":`Checking the latest Goal state…`,"drawer.subagentPreviewReady":`Preview locked. Confirm to apply this Goal setting.`,"drawer.subagentPreviewSummary":`Allow up to {count} child agents. Task-domain restriction: {domains}.`,"drawer.subagentRemoteReadOnly":`This source is read only. Open the Goal on its host to change the setting.`,"drawer.subagentTitle":`Adaptive sub-agent execution`,"drawer.remoteDetailsDescription":`SSH sources expose public-safe status only and do not read connection settings from the source host.`,"drawer.remoteDetailsUnavailable":`Remote details are not projected`,"drawer.resumeNo":`No`,"drawer.resumeYes":`Yes`,"drawer.runDetails":`Execution Session`,"drawer.runInterrupt":`Interrupt this run`,"drawer.runLatest":`View latest execution`,"drawer.runNewSession":`Start new Session`,"drawer.runCloseSession":`Close Session`,"drawer.runRecordEmpty":`No run record yet. The Agent has not started this execution. Check waiting conditions or resume the Session under Details & actions.`,"drawer.runRecordProjected":`No step-by-step record is available. LoopX read {completed}/{total} projected steps{outputs}; inspect the Session under Details & actions.`,"drawer.runRecordProjectedOutputs":` and {count} outputs`,"drawer.runRoleAssistant":`Completed`,"drawer.runRoleSystem":`Needs review`,"drawer.runRoleUser":`Task received`,"drawer.runView":`Session views`,"drawer.scheduleAdd":`Add scheduled check`,"drawer.scheduleDefaultNotification":`Notify only when you are needed`,"drawer.scheduleDefaultStop":`Goal completes or owner stops it`,"drawer.scheduleDefaultTarget":`Wake according to this Goal’s LoopX schedule.`,"drawer.scheduleEdit":`Change to every 2 hours`,"drawer.scheduleLast":`Last run`,"drawer.scheduleLocalTimezone":`Local timezone`,"drawer.scheduleNext":`Next run`,"drawer.scheduleNeverRun":`Not run yet`,"drawer.scheduleNotification":`Notification`,"drawer.schedulePause":`Pause`,"drawer.schedulePending":`Waiting for schedule`,"drawer.scheduleResume":`Resume`,"drawer.scheduleRunNow":`Run now`,"drawer.scheduleStop":`Stop {kind}`,"drawer.scheduleStopCondition":`Stop condition`,"drawer.scheduleTimezone":`Timezone`,"drawer.sessionRecoverable":`Resumable`,"drawer.sessionStatus":`Session status`,"drawer.setupHeartbeat":`Set up Heartbeat`,"drawer.taskActions":`Pending Todo actions`,"drawer.taskAdvancement":`Advancement task`,"drawer.taskBlock":`Mark blocked`,"drawer.taskComplete":`Mark complete`,"drawer.taskCompletedNote":`This task is retained as a read-only record.`,"drawer.taskCompletedTitle":`Task completed`,"drawer.taskDefer":`Defer`,"drawer.taskDeferCondition":`Todo defer resume condition`,"drawer.taskDeferInvalid":`Unsupported condition format; use one of the deterministic conditions below.`,"drawer.taskDeferPlaceholder":`For example, resume_at:2026-09-14T09:00:00+08:00`,"drawer.taskDeferReview":`Review defer`,"drawer.taskDeferSupported":`Supports todo_done, pr_merged, capacity_available, and timezone-aware resume_at conditions.`,"drawer.taskDeferUntil":`Defer until`,"drawer.taskDetails":`Todo details`,"drawer.taskInfo":`Task information`,"drawer.taskManage":`Manage task`,"drawer.taskNextCompleted":`Create a follow-up task`,"drawer.taskNextOpen":`Advance or update status`,"drawer.taskOrdinary":`Task`,"drawer.taskStatusBlocked":`Blocked`,"drawer.taskStatusDeferred":`Deferred`,"drawer.resumeWhen":`Resume condition`,"drawer.resumeState":`Resume state`,"drawer.resumePending":`Waiting for condition`,"drawer.resumeReady":`Ready to resume`,"drawer.resumeReceipt":`Resume receipt`,"drawer.taskNextDeferred":`Wait for the resume condition, then reassess`,"drawer.taskNextResumeReady":`Resume condition met; awaiting lifecycle replan`,"drawer.taskStatusCompleted":`Completed`,"drawer.taskStatusOpen":`Ready`,"drawer.taskSuccessor":`Create follow-up Todo`,"drawer.taskSuccessorNote":`Owner marked this blocked while waiting for more context.`,"drawer.taskSuccessorSummary":`Create follow-up Todo: {task}`,"drawer.taskSuccessorText":`Follow-up work for {task}`,"drawer.taskType":`Task type`,"drawer.topic":`Topic`,"drawer.trigger":`Trigger`,"drawer.titleAttention":`Needs you`,"drawer.titleOutput":`Output details`,"drawer.titleProposalApplied":`Execution result`,"drawer.titleProposalConfirm":`Confirm execution`,"drawer.titleSchedule":`Scheduled check`,"drawer.unconfigured":`Not configured`,"drawer.workspaceCandidates":`Available workspaces`,"files.emptySummary":`Public-safe output`,"files.empty":`No files, outputs, or verified reports yet.`,"files.loadingReports":`Loading verified milestone reports…`,"files.reportDelta":`+{added} added · {changed} changed`,"files.reportAdded":`added`,"files.reportChanged":`changed`,"files.reportGeneration":`Generation`,"files.reportLoadFailed":`Could not load verified reports`,"files.reportPublication":`Publication`,"files.title":`Files & Outputs`,"files.verifiedReport":`Verified milestone report`,"header.agentUnavailable":`Unavailable`,"header.chatRuntime":`Chat`,"header.workAgentCount":`{count} work Agents`,"header.chat":`Chat`,"header.files":`Files`,"header.goalCapabilities":`Capability settings`,"header.goalCapabilitiesDescription":`Manage overrides and inherited machine defaults.`,"header.goalDetails":`Goal details`,"header.goalDetailsDescription":`Review status, usage, repository, notifications, and sessions.`,"header.goalSettings":`Goal settings`,"header.goalSettingsDescription":`Open Goal details or capability settings`,"header.goalNavigation":`Goal navigation`,"header.goalView":`Goal view`,"header.live":`Live`,"header.manager":`LoopX Manager`,"header.managerDescription":`Your personal workspace across Goals`,"header.managerOverview":`Overview`,"header.managerView":`Manager view`,"header.openGoalNavigation":`Open Goal navigation`,"header.readOnlySourceDescription":`{source} is displayed read-only through an SSH tunnel`,"header.refresh":`Refresh status`,"header.refreshDone":`Updated just now`,"header.refreshFailed":`Refresh failed`,"header.refreshing":`Refreshing`,"header.selectAgent":`Select Agent`,"header.selectChatRuntime":`Select chat runtime`,"header.tasks":`Tasks`,"header.themeBrutal":`Switch to brutal theme`,"header.themePaper":`Switch to default theme`,"home.blockingSummary":`{count} are blocking an Agent.`,"home.completedGoals":`Completed Goals`,"home.empty":`Nothing here`,"startup.goalLoading":`Loading status…`,"startup.goalError":`Could not load status`,"startup.progress":`{loaded} of {total} active Goals loaded`,"startup.partial":`Goal states are updating. Counts are incomplete.`,"startup.independent":`Other Goals remain available while this Goal loads.`,"startup.error.timeout":`The request timed out. Retry when the local service is ready.`,"startup.error.network":`The connection was interrupted. Retry to reconnect.`,"startup.error.service":`The local service is temporarily unavailable. Retry to continue.`,"startup.error.revision":`The Goal directory changed during loading. Refresh to synchronize.`,"startup.error.scope":`This Goal is no longer available in the selected source. Refresh the directory.`,"startup.error.invalid":`The status response could not be read. Refresh or check for a LoopX update.`,"startup.retry":`Retry`,"startup.retryFailed":`Retry failed Goals`,"startup.failedCount":`{count} Goals could not be loaded. Ready Goals remain available.`,"home.greeting":`Hi, I’m your LoopX Manager`,"home.history":`History`,"home.lane.needsYou":`Needs you`,"home.lane.needsYouDescription":`Waiting for your decision, authorization, or context`,"home.lane.observing":`Observing`,"home.lane.observingDescription":`Monitoring continuously and notifying you when something changes`,"home.lane.running":`Running`,"home.lane.runningDescription":`Agents are making progress and reporting back`,"home.lane.scheduled":`Scheduled`,"home.lane.scheduledDescription":`Queued until its time or prerequisite arrives`,"home.noActivity":`No activity yet`,"home.noFirstActivity":`Waiting for first activity`,"home.noCompletedGoals":`No completed Goals yet`,"home.preservedState":`State is preserved and can be resumed`,"home.stopped":`Stopped`,"home.systemHealth":`System health: {summary}`,"home.taskCount":`{count} Tasks`,"home.todayAt":`Today {time}`,"home.waitingCount":`You have {count} items to handle.`,"home.workspace":`Goal workspace`,"lark.allMessages":`All messages in this topic`,"lark.allTopicMessages":`All topic messages`,"lark.agentIngress":`Agent ingress`,"lark.agentAppPermissions":`Every selected Agent needs a Lark App that is ready for group mentions and replies.`,"lark.agentApps":`Lark App per Agent`,"lark.agentAppsDescription":`The default App is preselected. Assign a different compatible App when an Agent needs its own bot identity.`,"lark.agentAppSelection":`Lark App for {agent}`,"lark.appCreated":`App created`,"lark.appCreateFailed":`Creation failed`,"lark.appLoading":`Loading available Lark Apps…`,"lark.appPermissions":`This App can send connection messages, but lacks the bot permissions required to receive group mentions or reply automatically. Enable im:message.group_at_msg:readonly, im:message.send_as_bot, and the im.message.receive_v1 event, publish a new version, then refresh.`,"lark.appProfile":`Lark App`,"lark.apps":`Lark Apps`,"lark.autoReplyUnavailable":`Auto reply unavailable`,"lark.autoReplyReady":`Auto reply ready`,"lark.bindGoal":`Bind to Goal`,"lark.cancel":`Cancel`,"lark.cardinality":`One Lark App · many Goals · one isolated route per Agent`,"lark.capture":`Capture`,"lark.captureAddressed":`Only messages that mention or reply to the App`,"lark.captureAll":`All messages in this Goal topic`,"lark.captureScope":`Capture scope`,"lark.captureScopeDescription":`Controls which Topic messages enter LoopX without expanding Agent permissions.`,"lark.closeConnection":`Close connection dialog`,"lark.closeCreate":`Close create dialog`,"lark.closeSettings":`Close Lark settings`,"lark.connect":`Connect`,"lark.connectAllAgents":`Connect every registered Agent`,"lark.connectAllAgentsAction":`Connect {count} Agents`,"lark.connectAllAgentsDescription":`Create {count} isolated Agent Topics in one guided action. Send requests inside the matching Topic; each Agent keeps its own route and inbox.`,"lark.connectApp":`Connect Lark App`,"lark.connection":`Connection`,"lark.connections":`Connections`,"lark.configuration":`Lark configuration`,"lark.continueFeishu":`Continue in Feishu`,"lark.createAutomatically":`Create Goal topic automatically`,"lark.createAutomaticallyDescription":`A dedicated, Agent-labelled Topic will be created for every selected Agent.`,"lark.defaultAgentAppDescription":`Used to find the target group and as the default for every selected Agent. Per-Agent choices below override it.`,"lark.description":`Manage reusable Lark Apps and connect group chats to Goals through dedicated topics.`,"lark.editConnection":`Edit Lark Connection`,"lark.goalConnections":`{count} Goal connections`,"lark.goalTopicConnections":`Lark Goal Topic connections`,"lark.groupChat":`Group chat`,"lark.groupEmpty":`This bot has not joined a group that can be connected. Add it to a Feishu group first, then return to refresh or search.`,"lark.groupLoading":`Reading groups joined by this bot…`,"lark.groupSearch":`Search groups joined by this bot`,"lark.historyPermission":`Group-history permission (separate capability)`,"lark.health.eventProcessed":`{events} events processed, {replies} replies sent.`,"lark.health.eventUnverified":`Event subscription needs verification`,"lark.health.eventUnverifiedDetail":`The provider listener is ready, but no event has arrived. Enable im.message.receive_v1 and group mention permissions, publish a new version, then send a new @ mention inside this Agent Topic. Group-level messages fail closed when multiple Agent routes exist.`,"lark.health.ignoredSelf":`The bot’s own message was ignored to prevent duplicate replies.`,"lark.health.invalidRouting":`Invalid routing configuration`,"lark.health.invalidRoutingDetail":`The connection was safely disabled. Select a processing mode again and save.`,"lark.health.lastStatus":`Latest event status: {status}`,"lark.health.listening":`Listening`,"lark.health.messageContextPermission":`Message permission required`,"lark.health.messageContextPermissionDetail":`A message event arrived, but group context could not be read. Publish and authorize group message read access for this App.`,"lark.health.notAddressed":`Latest message did not directly @ the bot`,"lark.health.notAddressedDetail":`Listening is healthy. This connection only responds to direct @ mentions or replies to the bot.`,"lark.health.notStarted":`Listener not started`,"lark.health.notStartedDetail":`Refresh the connection or restart LoopX, then try again.`,"lark.health.processingFailed":`Message processing failed`,"lark.health.processingFailedDetail":`The message event arrived, but Agent processing failed. Review local diagnostics and retry.`,"lark.health.queued":`Queued in the Agent inbox`,"lark.health.queuedDetail":`The message will be processed asynchronously by {agent} without starting a general Chat Session.`,"lark.health.sourceDisconnected":`Event connection disconnected`,"lark.health.sourceDisconnectedDetail":`The event consumer exited unexpectedly. Check that the app profile uses Feishu for Feishu apps or Lark for international Lark, then inspect connection and subscription errors. LoopX is retrying; successful history queries do not prove live delivery.`,"lark.health.retrying":`Retrying listener`,"lark.health.retryingDetail":`Event listening was interrupted and LoopX is retrying automatically.`,"lark.health.routeAmbiguous":`Message matches multiple Goals`,"lark.health.routeAmbiguousDetail":`The same bot and group have multiple full-group capture connections. Use a separate bot for each Agent or keep only one full-group connection.`,"lark.health.routeMismatch":`Message did not match this Goal Topic`,"lark.health.routeMismatchDetail":`The event came from another group or Topic. Reconnect this Goal to the correct group, then send a new @ mention.`,"lark.health.routeUnavailable":`Message cannot be routed to the Goal`,"lark.health.routeUnavailableDetail":`Connection data is incomplete. Reconnect this Goal, then send a new @ mention.`,"lark.health.starting":`Starting`,"lark.health.startingDetail":`LoopX is starting message event listening for this App.`,"lark.health.unavailable":`Auto reply unavailable`,"lark.health.waiting":`Waiting`,"lark.incomingMessages":`Incoming messages`,"lark.ingressAsync":`Async inbox`,"lark.ingressAsyncDescription":`Write to the Agent private inbox for a later explicit drain.`,"lark.editPreservesIdentity":`Saving preserves this App, group and Topic. Old connections upgrade to the Agent inbox by default.`,"lark.conversationKind":`Connection purpose`,"lark.managerConversation":`Manager · live conversation`,"lark.workerConversation":`Worker Agent · background tasks`,"lark.managerConversationDescription":`The built-in manager responds as you chat and delegates long-running work to background Agents. Group and private conversations keep separate histories.`,"lark.ingressLegacy":`Upgrade available`,"lark.ingressLegacyDescription":`Save this connection to upgrade to the Agent inbox. Existing messages remain in the same Topic.`,"lark.ingressQueue":`Queuing`,"lark.ingressQueueDescription":`Enter the same Agent Session's bounded FIFO queue and run after the current Turn.`,"lark.ingressSteering":`Steering`,"lark.ingressSteeringDescription":`Deliver to the active Turn and reject safely when no exact active Turn exists.`,"lark.loading":`Loading Lark configuration…`,"lark.management":`Lark management`,"lark.openEventSettings":`Open Feishu event settings`,"lark.mentions":`Mentions`,"lark.mentionsOnly":`Mentions only`,"lark.needsMessagePermissions":`Needs message permissions`,"lark.needsSetup":`Needs setup`,"lark.newApp":`New Lark App`,"lark.noAgentConfigured":`No Agent configured`,"lark.noConnections":`No matching connections.`,"lark.noProfiles":`No lark-cli App profiles are available yet.`,"lark.profileName":`Profile name`,"lark.profileValidation":`Profile can contain only letters, numbers, periods, underscores, and hyphens.`,"lark.processing":`Processing`,"lark.region":`Region`,"lark.registerAnother":`+ Register another Lark App — Create through Feishu`,"lark.reopenFeishu":`Reopen Feishu`,"lark.settingsConfigure":`Configure {goal}`,"lark.settingsDisconnect":`Disconnect {goal}`,"lark.replyMode":`Reply mode`,"lark.replyModeDescription":`Replies are limited to the source Topic to prevent cross-group or cross-Goal delivery.`,"lark.reusableApps":`{count} reusable Apps`,"lark.reusableWorkspaceApp":`Reusable workspace App`,"lark.routesUnverified":`{count} Lark routes pending verification`,"lark.saveConnection":`Save connection`,"lark.searchConnections":`Search Lark connections`,"lark.searchPlaceholder":`Search Apps, groups, Goals, or topics`,"lark.setupCopy":`LoopX opens the official Feishu creation page through lark-cli. App credentials stay in the system Keychain; LoopX stores only the profile reference.`,"lark.someoneMentions":`Someone mentions the Agent`,"lark.targetAgent":`Target Agent`,"lark.targetAgentDescription":`Choose a registered Agent in this Goal. This connection delivers to one Agent; it does not broadcast or grant permissions. Steering and Queuing require that Agent's exact active Session.`,"lark.agentUnavailable":`{agent} · no longer available`,"lark.selectRegisteredAgent":`Select an available registered Agent before connecting. The previous Agent will not be replaced automatically.`,"lark.topicPreview":`Topic preview`,"lark.topicReply":`Topic reply`,"lark.trigger":`Trigger`,"lark.waitingFeishu":`Waiting for Feishu`,"lark.waitingFeishuDescription":`Complete Feishu authorization in the new window. This page updates automatically when it is ready.`,"lark.waitingLink":`Generating the official Feishu creation link…`,"lark.error.appCreate":`Lark App creation failed`,"lark.error.appRequired":`Select a Lark App profile.`,"lark.error.bind":`Connection failed`,"lark.error.bindPreview":`Connection preview failed`,"lark.error.configuration":`Could not load Lark configuration`,"lark.error.groupLookup":`Could not read groups joined by this bot. Check the bot status and try again.`,"lark.error.groupLoad":`Could not load group chats`,"lark.error.invalidApp":`The Lark App profile is unavailable or has not completed authorization.`,"lark.error.messagePermissions":`This App lacks the bot permissions required for automatic replies. Enable im:message.group_at_msg:readonly and im:message:send_as_bot, publish a new version, then refresh.`,"lark.error.provider":`The Feishu API call failed without a verified receipt. Try again later.`,"lark.error.setupPoll":`Could not read creation status`,"lark.error.setupStart":`Could not start Lark App creation`,"lark.error.cliExecutable":`The configured lark-cli was found but cannot run. Check the installation or launch arguments.`,"lark.error.cliMissing":`lark-cli was not found. Install lark-cli and restart LoopX.`,"lark.error.cliStart":`lark-cli failed to start. Check the installation and restart LoopX.`,"lark.error.disconnect":`Disconnect failed`,"notifications.autoNotify":`Send automatically when your confirmation is required`,"notifications.bind":`Bind notification group`,"notifications.bindConfirm":`Bind “{goal}” to “{target}”. LoopX will verify that the bot is in the group and send a confirmation message.`,"notifications.bindFailed":`Binding failed`,"notifications.bound":`Bound`,"notifications.confirmBind":`Confirm binding`,"notifications.description":`Send Goal changes that need your confirmation to a Feishu group. Bindings and automatic delivery use the existing channel.`,"notifications.disabled":`Disabled`,"notifications.group":`Notification group: {target}`,"notifications.loadFailed":`Could not load notification groups`,"notifications.noTargets":`No notification groups are available. Group delivery uses a private bot identity; configure one from the terminal first:`,"notifications.notBound":`Not bound`,"notifications.recent":`Latest {time}`,"notifications.sentCount":`{count} sent`,"notifications.settings":`Goal notification bindings`,"notifications.setupFailed":`Could not update settings`,"notifications.title":`Feishu group notifications`,"proposal.field.agentId":`Agent`,"proposal.field.cadence":`Frequency`,"proposal.field.completionCriteria":`Completion criteria`,"proposal.field.executionBoundary":`Execution boundary`,"proposal.field.goalId":`Goal ID`,"proposal.field.heartbeat":`Heartbeat`,"proposal.field.initialTodos":`Initial tasks`,"proposal.field.objective":`Objective`,"proposal.field.operation":`Operation`,"proposal.field.operationState":`Operation state`,"proposal.field.resultDelivery":`Result delivery`,"proposal.field.confirmationBoundary":`Confirmation boundary`,"proposal.field.expiresAt":`Expires at`,"proposal.field.permission":`Permission`,"proposal.field.reason":`Reason`,"proposal.field.stopCondition":`Stop condition`,"proposal.field.target":`Check target`,"proposal.field.timezone":`Timezone`,"proposal.field.title":`Title`,"proposal.field.workspace":`Execution workspace`,"actionReview.targetChanged":`The preview target does not match the requested Goal and operation. Generate a new preview.`,"actionReview.ready_stop":`Pausing is reversible. This validated preview can apply directly; completion still requires verified readback.`,"actionReview.resume_review":`Review before restoring automatic scheduling. Quota, gates and Todo constraints still apply.`,"actionReview.delete_review":`Review removal of this stopped Goal from the registries. Project files and history are preserved.`,"actionReview.action_review":`Review the target and impact before applying this proposal.`,"actionReview.protected_action":`This action needs explicit review. Confirmation cannot replace required authority.`,"actionReview.unknown_permission":`The permission classification is not recognized. Recheck the proposal before continuing.`,"actionReview.unknown_action":`This lifecycle operation is not recognized. Recheck the proposal before continuing.`,"actionReview.incomplete_proposal":`The preview is missing validation or an available apply transition. Generate a new preview.`,"actionReview.authority_gate":`A gate prevents execution. Resolve its requirements, then recheck the proposal.`,"actionReview.stale_proposal":`The source state changed. Generate a new preview; the previous decision no longer applies.`,"actionReview.apply_pending":`Execution is in progress. Wait for its result before retrying.`,"actionReview.readback_verified":`The action completed and its resulting state was verified.`,"actionReview.readback_unverified":`The action returned without verified readback. Completion is not confirmed; recheck the state.`,"actionReview.apply_failed":`Execution did not complete. Check the failure and regenerate the preview before retrying.`,"actionReview.inactive_proposal":`This proposal is no longer ready to execute. Recheck it before continuing.`,"proposal.gate.default":`Host confirmation required`,"proposal.impact.default":`After confirmation, the canonical LoopX service will write the state change.`,"proposal.impact.goalCreate":`After confirmation, LoopX will create the Goal and its initial Todo, then let the selected Agent start the first run.`,"proposal.impact.lifecycleDelete":`After confirmation, this stopped Goal is removed from the source and global registries. Project files, history state, and backups are preserved.`,"proposal.impact.lifecycleResume":`After confirmation, the Goal becomes eligible for automatic scheduling and returns to Active Goals. Actual execution still follows quota, Gate, and Todo constraints.`,"proposal.impact.lifecycleStop":`After confirmation, automatic progress stops and the Goal moves to the collapsed Stopped list. History, Todos, and evidence remain available for resuming.`,"proposal.impact.protected":`This action must be completed through the protected LoopX write service.`,"proposal.impact.operation":`The exact terms are read-only here. Confirm or reject the same immutable request in the bound Feishu group; confirmation consumes one canonical claim.`,"proposal.primary.apply":`Confirm and apply`,"proposal.primary.goalCreate":`Create Goal and start first run`,"proposal.primary.lifecycleDelete":`Delete Goal`,"proposal.primary.lifecycleResume":`Resume Goal`,"proposal.primary.lifecycleStop":`Stop Goal`,"proposal.primary.todoStart":`Create task and start execution`,"proposal.primary.operationGroup":`Confirm in Feishu group`,"proposal.resultDelivery.verified":`Verified in the original group card`,"proposal.resultDelivery.pending":`Pending verified return to the original group card`,"proposal.summary.goalCreate":`Create Goal: {title}`,"proposal.summary.heartbeat":`Set a Heartbeat for the current Goal`,"proposal.summary.lifecycleDelete":`Delete Goal: {title}`,"proposal.summary.lifecycleResume":`Resume Goal: {title}`,"proposal.summary.lifecycleStop":`Stop Goal: {title}`,"proposal.summary.monitor":`Create a scheduled check for the current Goal: {target}`,"proposal.workspace.current":`Current local workspace (no Repository bound)`,"proposal.workspace.named":`{workspace} (execution environment only; does not bind a repository)`,"proposal.workspaceGate.agentImpact":`Bind an Agent identity, then recheck the original action. No Goal has been written.`,"proposal.workspaceGate.agentTitle":`Bind an Agent first`,"proposal.workspaceGate.defaultSummary":`Select the Goal workspace.`,"proposal.workspaceGate.selectionImpact":`After selecting a workspace, LoopX will show the confirmation preview again. The selection itself does not write state.`,"proposal.workspaceGate.selectionTitle":`Select Goal workspace`,"projection.agentAdvancingGoal":`Agent is advancing the current Goal`,"projection.agentIdle":`Nothing needs your attention`,"projection.agentNeedsDecision":`Agent is waiting for your decision`,"projection.agentPreparingNextStep":`Agent is preparing the next step`,"projection.agentStopped":`Stopped by you; history, Todos, and evidence are preserved`,"projection.agentWaitingExternal":`Waiting for an external condition`,"projection.confirmAgentDecision":`Confirm the permission or decision the Agent needs next`,"projection.events24h":`{count} events in the last 24 hours`,"projection.firstReadOnlyAdapterCheck":`Run the first read-only adapter check and save progress`,"projection.goalVerified":`Goal state, Todos, and registration information verified`,"projection.latestRun":`Latest run`,"projection.latestValidation":`Latest validation`,"projection.nextUpdatePending":`Waiting for LoopX to update the next step`,"projection.publicSafeProjection":`Public-safe status projection`,"projection.refreshState":`Refresh LoopX status and confirm the current progress is still valid`,"projection.runEvidenceAvailable":`Run evidence is available`,"projection.runRecorded":`The latest LoopX run is recorded`,"projection.statusRefreshNeeded":`LoopX status needs to be refreshed`,"projection.todoStatusUpdated":`Todo status updated; confirming the next step`,"projection.validationRecorded":`The latest validation is recorded`,"runs.completed":`Completed`,"runs.failed":`Needs review`,"runs.interrupted":`Interrupted`,"runs.queued":`Scheduled`,"runs.ready":`Ready`,"runs.resumeFailed":`Recovery failed`,"runs.running":`Running`,"runs.unknown":`Unknown`,"runs.waiting":`Waiting`,"schedule.active":`Running`,"schedule.heartbeat":`Goal Heartbeat`,"schedule.monitor":`Scheduled & continuous task`,"schedule.paused":`Paused`,"schedule.summary":`Continuously checked under LoopX scheduling constraints`,"schedule.defaultTarget":`Check the current Goal for blockers, progress, and new outputs`,"schedule.unsupportedCalendar":`Scheduled checks do not currently support an exact weekday or time. Use a fixed interval such as “Every 30 minutes,” “Every 2 hours,” or “Daily.” The draft was preserved and no confirmation preview was created.`,"source.add":`Add source`,"source.addConfigured":`Add read-only source`,"source.addMethod":`Source setup method`,"source.addSsh":`Add SSH source`,"source.closeForm":`Close source form`,"source.configured":`Configured SSH`,"source.configuredCount":`Local SSH Hosts · {count}`,"source.configuredGroup":`Configured SSH Hosts · {count} (select to add)`,"source.connected":`Connected`,"source.connecting":`Connecting`,"source.controlPlane":`Control plane source`,"source.copy":`Copy`,"source.copyCommand":`Copy SSH tunnel command`,"source.copyError":`Could not copy the command. Copy it manually below.`,"source.copied":`Copied`,"source.description":`All explicit Hosts are loaded, including Include files. Wildcards are not listed. Run the command first; LoopX never reads SSH keys or configuration details.`,"source.host":`Local SSH Host`,"source.hostEmpty":`No explicit SSH Hosts are available in ~/.ssh/config.`,"source.hostLoadError":`Could not read local SSH Hosts.`,"source.hostPlaceholder":`Enter or search for a Host`,"source.invalid":`The SSH source settings are invalid.`,"source.loadingHosts":`Loading…`,"source.localInteractive":`Local interactive`,"source.localPort":`Local port`,"source.manual":`Manual URL`,"source.manualDescription":`Remote sources always remain read-only projections and never inherit local write permissions.`,"source.name":`Name`,"source.namePlaceholder":`Remote development machine`,"source.notAvailable":`Unavailable`,"source.readOnly":`SSH tunnel · read only`,"source.readOnlyNoticeDescription":`You can view Goals, Tasks, evidence, and run status. Writes, guidance, and Agent sessions remain on the source host.`,"source.readOnlyNoticeTitle":`Remote read-only projection`,"source.readOnlyWriteError":`Remote SSH tunnel sources are read-only projections and cannot perform control-plane writes.`,"source.refreshHosts":`Reload SSH Hosts`,"source.remove":`Remove source {source}`,"source.removeCurrent":`Remove current source`,"source.select":`Select control plane source`,"source.selectHost":`Select a configured SSH Host.`,"source.statusUrl":`Local forwarded URL`,"source.tunnelCommandPending":`Select a Host to generate the tunnel command`,"machine.absent":`Not configured`,"machine.action.create":`Create machine policy`,"machine.action.delete":`Remove machine policy`,"machine.action.unchanged":`No write required`,"machine.action.update":`Update machine policy`,"machine.applied":`Machine policy applied and read back successfully.`,"machine.applyError":`Machine policy could not be applied.`,"machine.applyPreview":`Apply reviewed preview`,"machine.changedNamespaces":`Changed namespaces`,"machine.capabilityCatalog":`Machine capability catalog`,"machine.capabilityEmpty":`No machine-configurable capabilities are registered.`,"machine.configured":`Configured`,"machine.confirmRollback":`Confirm rollback`,"machine.currentRevision":`Current revision`,"machine.currentValue":`Current machine value`,"machine.description":`Browse the same capability catalog as Goal settings. Configure supported machine defaults here; Goal-only capabilities are labeled explicitly.`,"capabilities.rawJson":`Advanced: raw JSON`,"machine.goalOnly":`This capability currently supports Goal configuration only. Open a Goal’s capability settings to configure it; no machine-wide default is applied.`,"machine.desiredRevision":`Desired revision`,"machine.editorUnavailable":`No editor is installed for this namespace`,"machine.editorUnavailableDescription":`The namespace remains visible in the registry. Install or upgrade its Dashboard editor before changing it.`,"machine.editorMode":`Editor mode`,"machine.liveDefault":`Live default; Goal override wins`,"machine.liveDefaultDescription":`Goals without an explicit override read the current machine policy at the capability’s next decision point. Changes and removal affect those existing Goals immediately; an explicit Goal override stays pinned.`,"machine.genericNamespaceDescription":`Edit this registered namespace as JSON. LoopX validates it with the capability-owned schema before previewing any write.`,"machine.jsonConfiguration":`Namespace configuration (JSON)`,"machine.jsonConfigurationHelp":`Only this namespace is updated. Other machine configuration is preserved, and Apply remains locked to the reviewed preview revision.`,"machine.jsonEditor":`JSON`,"machine.editJson":`Edit JSON`,"capabilities.jsonConfiguration":`Goal configuration (JSON)`,"capabilities.jsonHelp":`Edit registered fields for this Goal. Changes require a new preview before applying.`,"capabilities.jsonInvalid":`Enter a valid JSON object using only registered editable fields.`,"machine.backToForm":`Back to form`,"machine.jsonInvalid":`Enter one valid JSON object before previewing changes.`,"machine.loadError":`Machine configuration could not be loaded.`,"machine.machinePolicy":`Machine policy`,"machine.namespaceCount":`Registered namespaces`,"machine.namespaces":`Configuration namespaces`,"machine.periodicReport":`Periodic reports`,"machine.periodicReportDescription":`Default report policy for every Goal without an explicit override. Goal scheduling and delivery consume the effective configuration.`,"machine.periodicReportActivation":`Enabled means automatic delivery at validated stage boundaries`,"machine.periodicReportActivationDescription":`This is not a weekly timer. When LoopX validates a Goal stage completion, an Agent prepares and freezes the report, then automatically delivers it through the configured Goal Channel. The enabled subscription is standing delivery authority; failures and route drift stop closed for repair.`,"machine.changeQualityActivation":`Qualification is a quality gate, not new authority`,"machine.changeQualityActivationDescription":`Goals that inherit this policy qualify their exact final diff. safe_fix allows at most one bounded fix pass inside existing write authority; this setting never grants file, permission, or merge authority.`,"machine.replanCadenceActivation":`Review cadence changes timing, not execution authority`,"machine.replanCadenceActivationDescription":`Goals without an explicit override read this threshold before the next review decision. It does not create Turns, spend quota, or grant authority.`,"machine.preview":`Review exact machine change`,"machine.previewChanges":`Preview changes`,"machine.previewError":`A machine-policy preview could not be created.`,"machine.previewLocked":`Apply is locked to this exact revision. If machine state changes, LoopX requires a new preview.`,"machine.previewRollback":`Preview rollback`,"machine.previewRemoval":`Preview removal`,"machine.profilePreset":`Profile preset`,"machine.profilePresetHelp":`A capability-owned preset, such as weekly-progress.`,"machine.registry":`Typed registry`,"machine.requiredFields":`Enable requires a profile preset, Goal Channel route, and valid timezone.`,"machine.revision":`Machine revision`,"machine.revisionLockedReady":`All changes require a preview and apply only while that exact machine revision remains current.`,"machine.rollbackAvailable":`Rollback is available for the last apply`,"machine.rollbackDescription":`Preview the stored prior revision before restoring it.`,"machine.rollbackError":`The rollback could not be completed.`,"machine.rollbackPreviewDescription":`The prior revision is ready to restore. Confirm to apply this rollback.`,"machine.rolledBack":`The prior machine policy was restored and verified.`,"machine.removed":`Machine policy removed and the resulting configuration read back successfully.`,"machine.routeRef":`Goal Channel route`,"machine.routeRefHelp":`Use a public route alias; credentials and provider identifiers never enter this form.`,"machine.timezone":`Timezone`,"machine.timezoneHelp":`Use an IANA timezone, for example Asia/Shanghai.`,"machine.title":`Machine configuration`,"machine.unchanged":`Machine policy already matches this preview; nothing was written.`,"machine.visualEditor":`Guided`,"capabilities.atomicOverride":`Goal override is atomic`,"capabilities.atomicOverrideDescription":`A complete Goal value wins over the machine default. LoopX never mixes individual fields across scopes.`,"capabilities.applyFailed":`Goal capability changes were not applied.`,"capabilities.applyPreview":`Apply preview`,"capabilities.catalog":`Goal capability catalog`,"capabilities.chooseGoal":`Choose a Goal before inspecting its capabilities.`,"capabilities.defaultValue":`Declared default`,"capabilities.description":`Inspect the capabilities available to this Goal and the exact scope of each setting.`,"capabilities.editorPrepared":`Typed editor contract available`,"capabilities.effectiveSource":`Effective source`,"capabilities.empty":`No capability descriptors are available for this Goal.`,"capabilities.fields":`Registered fields`,"capabilities.goalPolicy":`Goal capability policy`,"capabilities.goalScope":`Goal`,"capabilities.goalValue":`Current Goal value`,"capabilities.loadFailed":`Could not load Goal capabilities`,"capabilities.loading":`Loading Goal capabilities…`,"capabilities.machineOnly":`This capability is configured only at machine scope.`,"capabilities.machineValue":`Live machine default`,"capabilities.machineScope":`Machine`,"capabilities.previewOnly":`Inspection is live. Goal writes remain unavailable until the revision-locked preview and apply path is connected.`,"capabilities.preview":`Revision-locked preview`,"capabilities.previewChanges":`Preview changes`,"capabilities.restoreInheritance":`Restore machine-default inheritance`,"capabilities.previewFailed":`Could not preview Goal capability changes.`,"capabilities.previewLocked":`Apply will re-check this exact plan revision and reject stale changes.`,"capabilities.partialWrite":`Goal value saved; shared projection needs reconciliation`,"capabilities.partialWriteDescription":`The source Goal configuration was written and read back. Its shared runtime projection did not synchronize, so do not submit the change again.`,"capabilities.refreshSource":`Refresh source value`,"capabilities.readOnly":`Read-only capability`,"capabilities.revisionLockedReady":`Changes require a preview and are applied only when its exact revision is still current.`,"capabilities.retry":`Retry`,"capabilities.source.capability_default":`Capability default`,"capabilities.source.goal_override":`Goal override`,"capabilities.source.machine_default":`Live machine default`,"capabilities.source.not_configured":`Not configured`,"capabilities.title":`Goal capabilities`,"settings.close":`Close settings`,"settings.appearance":`Appearance`,"settings.appearanceDescription":`Manage workspace display preferences in this browser.`,"settings.appearanceTabDescription":`Theme and display preferences`,"settings.capabilitiesTabDescription":`Capability overrides for this Goal`,"settings.back":`Back to workspace`,"settings.categories":`Settings categories`,"settings.description":`Manage workspace preferences and integrations.`,"settings.eyebrow":`Workspace preferences`,"settings.general":`General`,"settings.goalConnections":`Goal connections`,"settings.language":`Language`,"settings.languageDescription":`Choose the language used by the LoopX desktop workspace.`,"settings.languageEnglishDescription":`Use English for navigation, settings, and workspace controls.`,"settings.languageEnglish":`English`,"settings.languageSimplifiedChineseDescription":`Use Simplified Chinese for navigation, settings, and workspace controls.`,"settings.languageSimplifiedChinese":`Simplified Chinese`,"settings.languageStoredLocally":`This preference is stored only on this device.`,"settings.languageTabDescription":`Interface language for this device`,"settings.larkTabDescription":`Apps, group chats, and Goal Topic connections`,"settings.machineTabDescription":`Typed defaults shared by capabilities on this machine`,"settings.notifications":`Notifications`,"settings.open":`Settings`,"settings.themeDefault":`Paper`,"settings.themeDefaultDescription":`Calm and lightweight for long-running work.`,"settings.themeDescription":`Choose the workspace visual style. This preference is stored in the current browser.`,"settings.themeHighContrast":`High contrast`,"settings.themeHighContrastDescription":`Stronger borders and more prominent state blocks.`,"settings.themeLoopx":`LoopX standard`,"settings.themeLoopxDescription":`Precise monochrome surfaces, Geist type, and quiet hairline structure.`,"settings.title":`Settings`,"settings.workspaceDisplay":`Workspace display`,"settings.workspaceTheme":`Workspace theme`,"session.closeRecord":`Exit run record`,"session.details":`Session details`,"session.record":`Execution Session · Run record`,"session.recordDescription":`The timeline now shows messages and Turn records from this Session.`,"sidebar.createGoal":`Create Goal`,"sidebar.delete":`Delete`,"sidebar.deleteGoal":`Delete Goal`,"sidebar.manager":`LoopX Manager`,"sidebar.notifications":`Settings`,"sidebar.owner":`Personal workspace`,"sidebar.product":`Personal Agent workspace`,"sidebar.resume":`Resume`,"sidebar.resumeGoal":`Resume Goal`,"sidebar.stop":`Stop`,"tasks.historyLoading":`Loading history…`,"tasks.historyError":`History could not be loaded.`,"tasks.historyExpired":`History snapshot expired. Reload to continue.`,"tasks.historyRetry":`Reload`,"tasks.historyEnd":`End of completed history`,"tasks.historyMore":`Load more`,"tasks.historyLocalOnly":`Open this machine’s Dashboard to browse full history.`,"sidebar.sortGoals":`Reorder Goals`,"sidebar.dragGoal":`Drag to reorder, or use Reorder Goals`,"sidebar.moveUp":`Move {goal} up`,"sidebar.moveDown":`Move {goal} down`,"sidebar.goalMoved":`{goal} moved to position {position}`,"sidebar.orderNotSaved":`Order changed for this visit; browser storage is unavailable.`,"sidebar.stopGoal":`Stop Goal`,"sidebar.stopped":`Stopped`,"sidebar.stoppedLoading":`Loading stopped Goals`,"sidebar.stoppedLoadFailed":`Stopped Goals could not be loaded. Active Goals remain available.`,"sidebar.retryStopped":`Retry`,"state.completed":`Completed`,"state.needsRepair":`Needs repair`,"state.needsYou":`Needs you`,"state.quiet":`Quiet`,"state.running":`Running`,"state.stopped":`Stopped`,"state.waiting":`Waiting`,"tasks.blocked":`Blocked`,"tasks.agentLane":`Work Agent`,"tasks.agentLaneDescription":`Filter this Goal's projected work lanes`,"tasks.agentLaneFilter":`Filter by work Agent`,"tasks.allAgentLanes":`All Agents ({count})`,"tasks.chatAgentReplied":`Agent replied`,"tasks.chatPending":`Sent to Agent`,"tasks.chatPendingDescription":`Processing. Tasks update only after a task operation is confirmed.`,"tasks.chatRecent":`Recent conversation`,"tasks.chatUnchangedDescription":`This conversation did not directly change Tasks. Convert the reply to a Task draft and confirm it when execution is needed.`,"tasks.chatViewReply":`View reply`,"tasks.convertToTask":`Convert to Task`,"tasks.completed":`Completed`,"runs.discoveryPartial":`Some execution details are unavailable. Reconnecting; task summaries are not live execution status.`,"runs.discoveryOffline":`Execution service unavailable. Reconnecting; retained task summaries may be stale.`,"files.openConversation":`Go to conversation`,"files.exportSummary":`Export summary`,"tasks.viewDescription":`Decisions first, then work and recent completions`,"tasks.viewLabel":`Task view`,"tasks.listView":`List`,"tasks.boardView":`Board`,"tasks.completedSummary":`{count} tasks completed. Recent details are projected by the control plane when needed.`,"tasks.emptyCompleted":`No completed tasks yet.`,"tasks.emptyConfirm":`No tasks waiting for confirmation.`,"tasks.emptyRunning":`No queued or running tasks.`,"tasks.emptySchedules":`No scheduled tasks.`,"tasks.emptyGoal":`This Goal has no tasks yet. Describe the next step below and LoopX will show a confirmation preview first.`,"tasks.markComplete":`Mark complete: {name}`,"tasks.moreActions":`More actions: {name}`,"tasks.openExecution":`View execution: {name}`,"tasks.pending":`Pending`,"tasks.pendingAndRunning":`Queued / Running`,"tasks.scheduled":`Scheduled & continuous`,"tasks.sessionError":`Session issue`,"tasks.waiting":`Queued`,"tasks.waitingAge":`Waiting {age}`,"tasks.viewExecution":`View execution`,"tasks.viewResult":`View result`,"time.days":`{count} days`,"time.hours":`{count} hours`,"timeline.emptyGoal":`This Goal has no new activity`,"timeline.emptyGoalDescription":`Ask for progress or send new guidance.`,"timeline.emptyWorkspace":`Your workspace is quiet today`,"timeline.emptyWorkspaceDescription":`Describe a Goal to the LoopX Manager, or ask what deserves attention today.`,"timeline.gateHistory":`{count} historical Gates`,"timeline.pending":`Working…`,"timeline.runCompleted":`{run}: completed`,"timeline.review":`Review`,"timeline.reviewAndConfirm":`Review and confirm`,"timeline.waitingConfirmation":`Needs your confirmation`},"zh-CN":{"acceptance.connected":`已连接`,"acceptance.mapped":`已建立项目映射`,"acceptance.refreshed":`已刷新状态`,"acceptance.inspected":`已检查适配器`,"acceptance.recorded":`已记录执行`,"acceptance.judged":`已记录反馈`,"acceptance.approved":`已记录批准`,"acceptance.ready":`已记录控制器就绪`,"acceptance.attentionSource":`当前状态`,"acceptance.visionSource":`Agent 验收条件`,"acceptance.todoSource":`任务状态`,"acceptance.runSource":`最新执行证据`,"acceptance.title":`验收观察`,"acceptance.unavailable":`验收观测不可用,Goal 是否达成仍未知。`,"acceptance.partial":`当前仅有部分观测。任务完成或缺口列表为空,都不能证明 Goal 已通过验收。`,"acceptance.gaps":`仍需补充的证据`,"acceptance.reasonUnknown":`来源未提供原因`,"acceptance.unknown":`未知`,"acceptance.required":`所需证据或条件`,"acceptance.observed":`观测时间`,"acceptance.noGaps":`现有观测中没有缺口,尚未评估完整验收条件。`,"acceptance.guards":`待处理的门禁决策`,"acceptance.noGuards":`现有观测中没有待处理的门禁决策。`,"acceptance.scope":`决策范围`,"acceptance.next":`当前状态给出的下一步`,"acceptance.historical_progress":`已记录的历史进展`,"acceptance.historical":`历史生命周期记录不授予权限,也不代表通过验收。`,"acceptance.missing":`未获取的来源:`,"acceptance.truncated":`仅展示前 12 条观测。`,"common.actions":`操作`,"common.agent":`Agent`,"common.allMessages":`所有消息`,"common.cancel":`取消`,"common.close":`关闭`,"common.closeActionReceipt":`关闭操作回执`,"common.confirm":`确认`,"common.export":`导出`,"common.failed":`失败`,"common.goal":`Goal`,"common.loading":`加载中…`,"common.none":`无`,"common.off":`关闭`,"common.on":`开启`,"common.open":`打开`,"common.owner":`Owner`,"common.readOnly":`只读`,"common.recently":`刚刚`,"common.status":`状态`,"common.task":`Task`,"common.you":`你`,"common.waiting":`等待中`,"composer.addImage":`添加图片`,"composer.agentProgress":`向 Agent 获取进度报告`,"composer.agentProgressPrompt":`请给我一份当前 Goal 的进度报告:已完成、执行中、阻塞和下一步。`,"composer.attachImageHint":`选择、粘贴或拖入图片`,"composer.clarifyDefer":`暂缓 Todo 需要可自动判断的恢复条件。请补充 todo_done:、pr_merged:[owner/repo]#、capacity_available: 或 resume_at:<带时区 RFC3339 时间>。`,"composer.clarifySingleAction":`这句话包含多个可能修改状态的操作。请一次描述一项操作,我会逐项展示确认预览。`,"composer.createGoal":`创建新 Goal`,"composer.createGoalDraft":`Goal 草稿`,"composer.createGoalDraftDescription":`补充内容后发送,LoopX 会先展示待确认操作。`,"composer.createGoalDraftLead":`我想创建一个长期 Goal:`,"composer.createGoalTemplate":`我想创建一个长期 Goal: +目标: +完成标准: +执行边界(可选): +关联仓库(可选): +通知方式(可选):`,"composer.createGoalHint":`填入 Goal 模板草稿,检查后再创建`,"composer.draft":`草稿`,"composer.globalProgress":`汇总所有 Goal 进展`,"composer.globalProgressPrompt":`请帮我汇总所有活跃 Goal 的最新进展与阻塞。`,"composer.globalTasks":`询问全局待办`,"composer.globalTasksPrompt":`有哪些 Goal 正在等我?我现在该优先处理什么?`,"composer.goalMessageHint":`你的消息由 {agent} 在本 Goal 的会话中接收`,"composer.goalRunningHint":`{agent} 正在执行 {count} 个任务 · 你的消息作为纠偏进入本会话,不会打断执行`,"composer.goalPlaceholder":`询问或纠偏 {goal}…`,"composer.imageAnalysisPrompt":`请结合这些图片分析当前 Goal,并告诉我下一步。`,"composer.imageCountError":`最多添加 {count} 张图片。`,"composer.imagePicker":`图片文件选择器`,"composer.imageReadError":`无法读取图片 {name}`,"composer.imageReadGenericError":`图片读取失败。`,"composer.imageSizeError":`单张图片不能超过 {size}MB。`,"composer.imageTypeError":`支持 PNG、JPEG、WebP 和 GIF 图片。`,"composer.imagesPending":`待发送图片`,"composer.immediate":`立即发送`,"composer.managerMessageHint":`你的消息由 LoopX 管家跨 Goal 接收,支持全局询问与创建 Goal`,"composer.managerPlaceholder":`问问 LoopX 管家,或描述一个新 Goal…`,"composer.monitor":`配置定时检查`,"composer.monitorGoalQuestion":`为哪个 Goal 添加定时检查?`,"composer.monitorTemplate":`为当前 Goal 添加定时检查: +检查内容: +频率(支持 30 分钟 / 2 小时 / 每天):每 2 小时 +停止条件:Goal 完成`,"composer.monitorTemplateWithoutGoal":`配置定时检查: +Goal: +检查内容: +频率:每 2 小时 +停止条件:Goal 完成`,"composer.monitorHint":`先填写检查内容、频率和停止条件,不会立即创建`,"composer.heartbeatGoalQuestion":`为哪个 Goal 设置 Heartbeat?`,"composer.heartbeatTemplate":`为当前 Goal 设置 Heartbeat: +频率:每天 +停止条件:Goal 完成 +通知:仅在需要我时`,"composer.heartbeatTemplateWithoutGoal":`设置 Heartbeat: +Goal: +频率:每天 +停止条件:Goal 完成 +通知:仅在需要我时`,"composer.nextAction":`询问下一步`,"composer.nextActionPrompt":`我现在该做什么?`,"composer.prepareDraft":`填入编辑框,确认后再发送`,"composer.send":`发送`,"composer.sendMessage":`向 LoopX 发送消息`,"composer.sendMessageHint":`发送消息`,"composer.sentImageAlt":`移除图片 {name}`,"conversation.agentPending":`正在整理…`,"conversation.close":`关闭对话回执`,"conversation.convertHint":`将 Agent 最新回复转为 Task 草稿`,"conversation.full":`查看完整对话`,"conversation.receipt":`对话回执`,"conversation.replying":`正在回复`,"conversation.title":`管家对话`,"conversation.toTask":`转为 Task`,"digest.away":`自上次访问以来的运行记录`,"digest.completed":`新增完成运行`,"digest.failed":`新增失败或中断`,"digest.needsYou":`当前待确认`,"feedback.applying":`正在执行:{title}`,"feedback.cancelFailed":`取消失败:{error}`,"feedback.completed":`已完成:{title}`,"feedback.executionFailed":`执行失败:{error}`,"feedback.gateRequired":`需要你确认:{summary}`,"feedback.notCompleted":`操作未完成:{status}`,"feedback.goalRefreshFailed":`已打开 Goal,但暂时无法刷新最新状态。请点击刷新重试。`,"feedback.preparingPreview":`正在准备确认预览:{title}`,"feedback.previewFailed":`无法准备确认预览:{error}`,"feedback.sendFailed":`发送失败:{error}`,"feedback.sendGenericError":`消息发送失败,请稍后重试。`,"feedback.stale":`状态已变化,操作未执行,请重新生成确认预览。`,"feedback.taskDraftCreated":`已根据回复生成 Task 草稿。编辑后发送,LoopX 会先展示确认预览。`,"goal.defaultTitle":`新的个人 Goal`,"goal.initialTodo":`按完成标准推进:{criteria}`,"goal.objectiveBoundary":`执行边界:{boundary}`,"goal.objectiveCompletion":`完成标准:{criteria}`,"drawer.advancedDiagnostics":`高级诊断`,"drawer.agentWorking":`Agent 正在继续执行,记录会自动更新。`,"drawer.analysis":`正在分析`,"drawer.apply":`确认并应用`,"drawer.applying":`正在应用…`,"drawer.attentionBlocking":`正在阻塞 Agent`,"drawer.attentionWaiting":`等待你的决定`,"drawer.autoNotify":`Human-gate 自动通知`,"drawer.branch":`分支`,"drawer.closeDetail":`关闭详情:返回{context}`,"drawer.connected":`已连接`,"drawer.correctionDescription":`消息会沿用当前 Goal、Todo 与 Agent Session 上下文。`,"drawer.correctionLabel":`与 {agent} 纠偏`,"drawer.correctionPlaceholder":`例如:先关注权限风险,暂时不要提交…`,"drawer.correctionSend":`发送纠偏`,"drawer.correctionTextarea":`输入纠偏信息:Goal {goal},Agent {agent},Run {run}`,"drawer.copyRepository":`复制仓库标识`,"drawer.copyRepositoryDone":`已复制仓库标识`,"drawer.copyRepositoryError":`复制失败,请检查浏览器剪贴板权限。`,"drawer.copyRepositorySuccess":`已复制,可粘贴到其他工具。`,"drawer.cost":`成本 24h / 7d`,"drawer.costShort":`成本`,"drawer.durationShort":`时长`,"drawer.period24h":`24 小时`,"drawer.period7d":`7 天`,"drawer.tokens":`Token 24 小时 / 7 天`,"drawer.tokensShort":`Token`,"drawer.usageNotMeasured":`未采集`,"drawer.currentGoal":`当前 Goal`,"attentionDetail.title":`事项说明`,"attentionDetail.request":`需要你做什么`,"attentionDetail.decision":`需要作出决定`,"attentionDetail.unknownRequest":`来源未明确,请先查看来源再判断`,"attentionDetail.open":`当前投影中待处理`,"attentionDetail.closed":`已关闭`,"attentionDetail.deferred":`已推迟`,"attentionDetail.superseded":`已被替代`,"attentionDetail.unknown":`来源未提供状态`,"attentionDetail.unavailable":`来源尚未确认当前事项,请刷新后再操作`,"attentionDetail.unknownReason":`来源尚未提供原因。`,"attentionDetail.targetTodo":`关联的待解锁 Todo`,"attentionDetail.targetAgent":`事项指定的 Agent`,"attentionDetail.scope":`声明的决策范围`,"attentionDetail.notProvided":`来源未提供`,"attentionDetail.replacement":`替代 Todo`,"attentionDetail.openReplacement":`打开替代事项`,"attentionDetail.boundary":`阅读详情不会关闭 gate 或授予权限;作出决定前仍需新的操作预览。`,"drawer.decisionDefaultEvidence":`当前状态没有附加公开安全证据;下一步仍会先展示 Preview。`,"drawer.decisionDefaultReason":`该决定会影响当前 Todo 的下一步执行。`,"drawer.decisionDefer":`稍后决定`,"drawer.decisionMore":`更多决定`,"drawer.decisionReject":`拒绝`,"drawer.decisionReview":`查看影响并决定`,"drawer.dependencies":`依赖`,"drawer.detailsAndActions":`详情与操作`,"drawer.duration":`运行时长 24h / 7d`,"drawer.evidence":`证据`,"drawer.executionHistory":`执行历史`,"drawer.executionRecord":`运行记录`,"drawer.executionRecordAndResult":`执行过程与结果`,"drawer.explainDecision":`解释此决定`,"drawer.gateApproveHint":`在终端执行一条命令即可完成审批:`,"drawer.gateRejectHint":`不同意就把末尾的 approve 换成 reject。执行后这条提醒会自动消失。`,"drawer.gateRequiresHost":`需要宿主确认`,"drawer.gateRequiresHostDescription":`页面无权直接批准这类权限变更,你的点击没有写入任何内容。`,"drawer.goalAutoRun":`当前 Goal 的自动运行`,"drawer.goalChanges":`当前 Goal 的待确认变更`,"drawer.goalDetails":`Goal 详情`,"drawer.group":`群聊`,"drawer.inspectorFull":`切换到全屏`,"drawer.inspectorFullView":`全屏查看`,"drawer.inspectorHalf":`切换到半屏`,"drawer.inspectorHalfView":`半屏查看`,"drawer.lastNotification":`最近通知`,"drawer.larkConfigure":`管理 Lark connection`,"drawer.larkConnect":`连接 Lark App`,"drawer.larkConnection":`Lark connection`,"drawer.larkNotConfigured":`未配置`,"drawer.larkNotConfiguredDescription":`配置后,当这个 Goal 出现需要你确认的变更时,会自动发飞书通知。`,"drawer.managerChanges":`管家待确认变更`,"drawer.moreActions":`更多操作`,"drawer.moreRunActions":`更多运行操作`,"drawer.nextTransition":`下一转换`,"drawer.noExecutionHistory":`暂无执行记录。`,"drawer.noRun":`尚未启动执行 Session`,"drawer.noRunDescription":`Agent 开始执行后,运行记录会稳定显示在这里。`,"drawer.notAssigned":`未分配`,"drawer.notLinked":`未关联`,"drawer.notSet":`未设置`,"drawer.outputDetails":`产出详情`,"drawer.outputRecorded":`该产出已记录到当前 Goal。`,"drawer.outputSafePreview":`公开安全产出预览`,"drawer.outputRun":`Run`,"drawer.outputTodo":`Todo`,"drawer.outputs":`本次运行产出`,"drawer.previewUnavailable":`此产出没有可用的公开安全内联预览。`,"drawer.priority":`优先级`,"drawer.progress":`进度`,"drawer.proposalApplied":`已应用,LoopX 状态将刷新。`,"drawer.proposalApplyFailed":`应用失败,没有写入任何变更。`,"drawer.proposalApplyFailedHint":`请刷新 Goal 状态后重新生成;若仍失败,可保留此页并查看高级诊断。`,"drawer.proposalClose":`关闭`,"drawer.proposalDefer":`稍后`,"drawer.proposalDeferred":`已暂缓,可稍后继续应用或重新生成。`,"drawer.proposalEnterGoal":`进入新 Goal`,"drawer.proposalExplainer":`确认后,LoopX 会执行这项变更并显示写入结果。关闭或取消不会修改任何状态。`,"drawer.proposalRecheck":`按最新状态重新检查`,"drawer.proposalRegenerate":`基于最新状态重试`,"drawer.proposalRejected":`已拒绝,这项变更不会写入。`,"drawer.proposalStale":`来源状态已变化,请按最新状态重新检查。`,"drawer.proposalViewGoal":`查看更新后的 Goal`,"drawer.reassign":`改派给`,"drawer.reassignSummary":`重新分配:{task}`,"drawer.reason":`原因`,"drawer.recoveryDescription":`本地历史已经保留,请选择恢复路径。`,"drawer.recoveryFailed":`上游 Session 恢复失败`,"drawer.recoveryNewSession":`携带上下文开始新 Session`,"drawer.recoveryRetry":`重试恢复`,"drawer.repositoryRole":`执行工作区`,"drawer.repository":`仓库`,"drawer.replyMode":`回复方式`,"drawer.subagentApplied":`已写入,并通过共享 Goal 状态读回校验。`,"drawer.subagentAppliedRefreshFailed":`已写入并通过共享 Goal 状态读回;状态投影刷新失败,可稍后手动刷新。`,"drawer.subagentApplying":`正在写入并校验共享状态读回…`,"drawer.subagentApplyFailed":`子代理设置写入失败。`,"drawer.subagentChildLimit":`当前上限`,"drawer.subagentConfirmDisable":`确认关闭子代理执行`,"drawer.subagentConfirmEnable":`确认开启子代理执行`,"drawer.subagentCurrentBoundary":`当前任务领域限制`,"drawer.subagentDescription":`仅在 Todo、配额、能力和写入范围门禁全部通过后,允许运行时为相互独立的任务临时创建子代理;不会强制并行,也不会授予持久权限。`,"drawer.subagentDisable":`预览关闭子代理执行`,"drawer.subagentDisableSummary":`这个 Goal 将不再创建新的子代理;现有 Todo 归属和执行记录不受影响。`,"drawer.subagentDomainInvalid":`所选任务领域限制无效。`,"drawer.subagentDomainTodoCount":`匹配 {count} 个开放 Todo`,"drawer.subagentDomains":`任务领域限制(可选)`,"drawer.subagentDomainsEmpty":`当前没有开放的 advancement Todo 声明 task_domain;保持为空即可不按任务领域限制子代理执行。`,"drawer.subagentDomainsHint":`全部不选表示不按任务领域过滤;选择后只放行匹配且已声明领域的 Todo,其他执行门禁始终生效。`,"drawer.subagentDomainsUnrestricted":`不限制任务领域`,"drawer.subagentEnable":`预览开启子代理执行`,"drawer.subagentLabel":`Per-Goal 执行边界`,"drawer.subagentModel":`子 Agent 模型`,"drawer.subagentEffort":`子 Agent 推理档位`,"drawer.subagentModelDefault":`宿主默认`,"drawer.subagentLunaPreset":`使用 Luna / max`,"drawer.subagentClearModel":`清除模型偏好`,"drawer.subagentModelHint":`填写后通过“预览配置调整”保存,执行关闭时也可保存偏好;启动时须核验宿主支持情况。`,"drawer.subagentModelRequired":`设置推理档位前请先指定子 Agent 模型。`,"drawer.subagentMaxChildren":`最多子代理数`,"drawer.subagentNoChange":`当前 Goal 已是这个设置,没有写入任何内容。`,"drawer.subagentPending":`待确认`,"drawer.subagentPreviewBoundary":`预览配置调整`,"drawer.subagentPreviewFailed":`无法生成子代理设置预览。`,"drawer.subagentPreviewing":`正在核对最新 Goal 状态…`,"drawer.subagentPreviewReady":`预览已锁定,确认后才会写入这个 Goal。`,"drawer.subagentPreviewSummary":`最多允许创建 {count} 个子代理;任务领域限制:{domains}。`,"drawer.subagentRemoteReadOnly":`当前来源只读,请在 Goal 所在主机上修改。`,"drawer.subagentTitle":`自适应子代理执行`,"drawer.remoteDetailsDescription":`SSH 来源只展示公开安全状态,不读取来源主机上的连接配置。`,"drawer.remoteDetailsUnavailable":`远端详情未投影`,"drawer.resumeNo":`否`,"drawer.resumeYes":`是`,"drawer.runDetails":`执行 Session`,"drawer.runInterrupt":`中断本次运行`,"drawer.runLatest":`查看最近执行过程`,"drawer.runNewSession":`开始新 Session`,"drawer.runCloseSession":`关闭 Session`,"drawer.runRecordEmpty":`还没有运行记录。Agent 尚未开始这次执行;请在“详情与操作”查看等待条件或恢复 Session。`,"drawer.runRecordProjected":`当前没有可展示的逐步运行记录。LoopX 已读取到 {completed}/{total} 的投影进度{outputs};请在“详情与操作”检查 Session 状态。`,"drawer.runRecordProjectedOutputs":`和 {count} 项产出`,"drawer.runRoleAssistant":`已完成`,"drawer.runRoleSystem":`需检查`,"drawer.runRoleUser":`收到任务`,"drawer.runView":`Session 视图`,"drawer.scheduleAdd":`添加定时检查`,"drawer.scheduleDefaultNotification":`仅在需要你时通知`,"drawer.scheduleDefaultStop":`Goal 完成或 owner 停止`,"drawer.scheduleDefaultTarget":`由 LoopX 调度器按 Goal 配置唤醒。`,"drawer.scheduleEdit":`改为每 2 小时`,"drawer.scheduleLast":`上次执行`,"drawer.scheduleLocalTimezone":`本地时区`,"drawer.scheduleNext":`下次执行`,"drawer.scheduleNeverRun":`尚未执行`,"drawer.scheduleNotification":`通知`,"drawer.schedulePause":`暂停`,"drawer.schedulePending":`等待调度`,"drawer.scheduleResume":`恢复`,"drawer.scheduleRunNow":`立即运行`,"drawer.scheduleStop":`停止{kind}`,"drawer.scheduleStopCondition":`停止条件`,"drawer.scheduleTimezone":`时区`,"drawer.sessionRecoverable":`可恢复`,"drawer.sessionStatus":`会话状态`,"drawer.setupHeartbeat":`设置 Heartbeat`,"drawer.taskActions":`Todo 待确认操作`,"drawer.taskAdvancement":`推进任务`,"drawer.taskBlock":`标记阻塞`,"drawer.taskComplete":`标记完成`,"drawer.taskCompletedNote":`该任务保留为只读记录。`,"drawer.taskCompletedTitle":`任务已完成`,"drawer.taskDefer":`暂缓`,"drawer.taskDeferCondition":`Todo 暂缓恢复条件`,"drawer.taskDeferInvalid":`条件格式不受支持;请使用下列可判定条件。`,"drawer.taskDeferPlaceholder":`例如 resume_at:2026-09-14T09:00:00+08:00`,"drawer.taskDeferReview":`检查暂缓`,"drawer.taskDeferSupported":`支持 todo_done、pr_merged、capacity_available 与带时区的 resume_at 条件。`,"drawer.taskDeferUntil":`暂缓至`,"drawer.taskDetails":`Todo 详情`,"drawer.taskInfo":`任务信息`,"drawer.taskManage":`管理任务`,"drawer.taskNextCompleted":`可创建后续任务`,"drawer.taskNextOpen":`推进或更新状态`,"drawer.taskOrdinary":`普通任务`,"drawer.taskStatusBlocked":`受阻`,"drawer.taskStatusDeferred":`已延期`,"drawer.resumeWhen":`恢复条件`,"drawer.resumeState":`恢复状态`,"drawer.resumePending":`等待条件满足`,"drawer.resumeReady":`可恢复`,"drawer.resumeReceipt":`恢复回执`,"drawer.taskNextDeferred":`等待恢复条件满足后重新评估`,"drawer.taskNextResumeReady":`恢复条件已满足,等待生命周期重新规划`,"drawer.taskStatusCompleted":`已完成`,"drawer.taskStatusOpen":`待执行`,"drawer.taskSuccessor":`创建后续 Todo`,"drawer.taskSuccessorNote":`Owner 标记为阻塞,等待补充上下文。`,"drawer.taskSuccessorSummary":`创建后续 Todo:{task}`,"drawer.taskSuccessorText":`{task} 的后续工作`,"drawer.taskType":`任务类型`,"drawer.topic":`Topic`,"drawer.trigger":`触发方式`,"drawer.titleAttention":`需要你`,"drawer.titleOutput":`产出详情`,"drawer.titleProposalApplied":`执行结果`,"drawer.titleProposalConfirm":`确认执行`,"drawer.titleSchedule":`定时检查`,"drawer.unconfigured":`未配置`,"drawer.workspaceCandidates":`可选择的工作区`,"files.emptySummary":`公开安全产出`,"files.empty":`还没有文件、产出或已验证的阶段周报。`,"files.loadingReports":`正在加载已验证的阶段周报…`,"files.reportDelta":`+{added} 新增 · {changed} 变化`,"files.reportAdded":`新增`,"files.reportChanged":`变化`,"files.reportGeneration":`生成批次`,"files.reportLoadFailed":`无法加载已验证周报`,"files.reportPublication":`发布批次`,"files.title":`Files & Outputs`,"files.verifiedReport":`已验证阶段周报`,"header.agentUnavailable":`不可用`,"header.chatRuntime":`Chat`,"header.workAgentCount":`{count} 个工作 Agent`,"header.chat":`Chat`,"header.files":`Files`,"header.goalCapabilities":`能力配置`,"header.goalCapabilitiesDescription":`管理 Goal override 与继承的本机默认值。`,"header.goalDetails":`Goal 详情`,"header.goalDetailsDescription":`查看状态、用量、仓库、通知与 Session。`,"header.goalSettings":`Goal 设置`,"header.goalSettingsDescription":`打开 Goal 详情或能力配置`,"header.goalNavigation":`Goal 导航`,"header.goalView":`Goal 视图`,"header.live":`实时`,"header.manager":`LoopX 管家`,"header.managerDescription":`跨 Goal 的个人工作入口`,"header.managerOverview":`总览`,"header.managerView":`管家视图`,"header.openGoalNavigation":`打开 Goal 导航`,"header.readOnlySourceDescription":`{source} 通过 SSH 隧道只读展示`,"header.refresh":`刷新状态`,"header.refreshDone":`刚刚更新`,"header.refreshFailed":`刷新失败`,"header.refreshing":`刷新中`,"header.selectAgent":`选择 Agent`,"header.selectChatRuntime":`选择聊天 Runtime`,"header.tasks":`Tasks`,"header.themeBrutal":`切换到野兽主题`,"header.themePaper":`切换到默认主题`,"home.blockingSummary":`其中 {count} 项正在阻塞 Agent。`,"home.completedGoals":`已完成的 Goal`,"home.empty":`当前没有`,"startup.goalLoading":`正在加载状态…`,"startup.goalError":`状态加载失败`,"startup.progress":`已加载 {loaded} / {total} 个活跃 Goal`,"startup.partial":`Goal 状态正在逐个更新,当前统计尚不完整。`,"startup.independent":`此 Goal 的加载不会阻塞其他 Goal,你可以先查看已加载的内容。`,"startup.error.timeout":`读取超时,可在本地服务就绪后重试。`,"startup.error.network":`连接中断,请重试以重新连接。`,"startup.error.service":`本地服务暂时不可用,请重试继续加载。`,"startup.error.revision":`加载期间 Goal 目录发生变化,请刷新以同步。`,"startup.error.scope":`该 Goal 已不在当前来源中,请刷新目录。`,"startup.error.invalid":`无法解析状态响应,请刷新或检查 LoopX 更新。`,"startup.retry":`重试`,"startup.retryFailed":`重试失败的 Goal`,"startup.failedCount":`{count} 个 Goal 加载失败,已加载的 Goal 可继续使用。`,"home.greeting":`你好,我是 LoopX 管家`,"home.history":`历史`,"home.lane.needsYou":`需要你`,"home.lane.needsYouDescription":`等待你的决定、授权或补充信息`,"home.lane.observing":`观察中`,"home.lane.observingDescription":`持续监控,出现变化时再提醒你`,"home.lane.running":`执行中`,"home.lane.runningDescription":`Agent 正在推进并持续回传进展`,"home.lane.scheduled":`已安排`,"home.lane.scheduledDescription":`已经安排,等待时间或前置条件`,"home.noActivity":`尚无活动`,"home.noFirstActivity":`等待首次活动`,"home.noCompletedGoals":`还没有已完成的 Goal`,"home.preservedState":`保留状态,可随时恢复`,"home.stopped":`已停止`,"home.systemHealth":`系统健康:{summary}`,"home.taskCount":`{count} 个 Task`,"home.todayAt":`今天 {time}`,"home.waitingCount":`你有 {count} 项需要处理。`,"home.workspace":`Goal 工作区`,"lark.allMessages":`此 Topic 中的所有消息`,"lark.allTopicMessages":`所有 Topic 消息`,"lark.agentIngress":`Agent 入站方式`,"lark.agentAppPermissions":`每个选中的 Agent 都需要一个已具备群聊提及和回复能力的 Lark App。`,"lark.agentApps":`每个 Agent 的 Lark App`,"lark.agentAppsDescription":`默认使用上方 App;需要独立机器人身份时,可为 Agent 选择另一个兼容 App。`,"lark.agentAppSelection":`{agent} 的 Lark App`,"lark.appCreated":`App 已创建`,"lark.appCreateFailed":`创建失败`,"lark.appLoading":`正在加载可用的 Lark Apps…`,"lark.appPermissions":`该 App 能发送建联消息,但缺少接收群聊 @ 消息或自动回复所需的机器人权限。请开启 im:message.group_at_msg:readonly、im:message.send_as_bot 和事件 im.message.receive_v1,发布新版后刷新。`,"lark.appProfile":`Lark App`,"lark.apps":`Lark Apps`,"lark.autoReplyUnavailable":`自动回复暂不可用`,"lark.autoReplyReady":`自动回复可用`,"lark.bindGoal":`绑定到 Goal`,"lark.cancel":`取消`,"lark.cardinality":`一个 Lark App · 多个 Goal · 每个 Agent 一条隔离路由`,"lark.capture":`接收范围`,"lark.captureAddressed":`仅接收提及 App 或回复 App 的消息`,"lark.captureAll":`接收此 Goal Topic 中的所有消息`,"lark.captureScope":`接收范围`,"lark.captureScopeDescription":`决定哪些 Topic 消息会进入 LoopX;不会扩大 Agent 权限。`,"lark.closeConnection":`关闭连接弹窗`,"lark.closeCreate":`关闭创建弹窗`,"lark.closeSettings":`关闭 Lark 设置`,"lark.connect":`连接`,"lark.connectAllAgents":`连接全部已注册 Agent`,"lark.connectAllAgentsAction":`一键连接 {count} 个 Agent`,"lark.connectAllAgentsDescription":`一次引导创建 {count} 个隔离的 Agent Topic;请在对应 Topic 内发送请求,每个 Agent 保留独立路由和收件箱。`,"lark.connectApp":`连接 Lark App`,"lark.connection":`连接`,"lark.connections":`连接`,"lark.configuration":`Lark 配置`,"lark.continueFeishu":`在飞书中继续`,"lark.createAutomatically":`自动创建 Goal Topic`,"lark.createAutomaticallyDescription":`将为每个选中的 Agent 创建带 Agent 标识的专属 Topic。`,"lark.defaultAgentAppDescription":`用于查找目标群聊,并作为所有选中 Agent 的默认 App;下方的逐 Agent 选择可覆盖它。`,"lark.description":`管理可复用的 Lark App,并用独立 Topic 将群聊连接到 Goal。`,"lark.editConnection":`编辑 Lark 连接`,"lark.goalConnections":`{count} 个 Goal 连接`,"lark.goalTopicConnections":`Lark Goal Topic 连接`,"lark.groupChat":`群聊`,"lark.groupEmpty":`该机器人尚未加入可连接的群。请先在飞书群设置中添加这个机器人,再回来刷新或搜索。`,"lark.groupLoading":`正在读取该机器人已加入的群…`,"lark.groupSearch":`搜索该机器人已加入的群`,"lark.historyPermission":`历史补读权限(独立能力)`,"lark.health.eventProcessed":`已处理 {events} 条事件,成功回复 {replies} 条。`,"lark.health.eventUnverified":`事件订阅待验证`,"lark.health.eventUnverifiedDetail":`Provider listener 已就绪,但尚未收到消息事件。请启用 im.message.receive_v1、开通群聊 @ 消息权限并发布新版,然后在这个 Agent Topic 内发送新的 @ 消息;存在多条 Agent 路由时,群顶层消息会 fail closed。`,"lark.health.ignoredSelf":`已忽略机器人自身发送的消息,避免重复回复。`,"lark.health.invalidRouting":`路由配置无效`,"lark.health.invalidRoutingDetail":`连接已安全停用,请重新选择处理方式并保存。`,"lark.health.lastStatus":`最近事件状态:{status}`,"lark.health.listening":`监听中`,"lark.health.messageContextPermission":`消息权限不足`,"lark.health.messageContextPermissionDetail":`已收到消息事件,但无法读取群消息上下文。请发布并授权该 App 的群消息读取权限。`,"lark.health.notAddressed":`最近消息未直接 @ 机器人`,"lark.health.notAddressedDetail":`监听正常;当前连接只响应直接 @ 机器人或对机器人的回复。`,"lark.health.notStarted":`监听未启动`,"lark.health.notStartedDetail":`请刷新连接或重新启动 LoopX 后再试。`,"lark.health.processingFailed":`消息处理失败`,"lark.health.processingFailedDetail":`已收到消息事件,但 Agent 处理失败。请查看本地诊断后重试。`,"lark.health.queued":`已进入 Agent 收件箱`,"lark.health.queuedDetail":`消息由 {agent} 异步处理,不会启动通用 Chat Session。`,"lark.health.sourceDisconnected":`实时消息连接断开`,"lark.health.sourceDisconnectedDetail":`消息监听进程意外退出。请核对应用档案的平台:飞书应用选飞书,国际版 Lark 应用选 Lark,再检查连接及订阅错误。LoopX 正在重试;历史消息能读取,不代表能实时收消息。`,"lark.health.retrying":`监听重试中`,"lark.health.retryingDetail":`事件监听暂时中断,LoopX 正在自动重试。`,"lark.health.routeAmbiguous":`消息匹配多个 Goal`,"lark.health.routeAmbiguousDetail":`同一 Bot 和群聊存在多个完整群捕获连接。请让每个 Agent 使用独立 Bot,或只保留一个完整群连接。`,"lark.health.routeMismatch":`消息未匹配当前 Goal Topic`,"lark.health.routeMismatchDetail":`事件来自其他群聊或 Topic。请重新选择群聊并连接该 Goal,然后发送一条新的 @ 消息。`,"lark.health.routeUnavailable":`消息无法路由到 Goal`,"lark.health.routeUnavailableDetail":`当前连接信息不完整。请重新连接该 Goal 后再发送一条新的 @ 消息。`,"lark.health.starting":`正在启动`,"lark.health.startingDetail":`LoopX 正在启动该 App 的消息事件监听。`,"lark.health.unavailable":`自动回复不可用`,"lark.health.waiting":`等待处理`,"lark.incomingMessages":`接收消息`,"lark.ingressAsync":`异步收件箱`,"lark.ingressAsyncDescription":`写入 Agent 私有收件箱,等待后续显式处理。`,"lark.editPreservesIdentity":`保存会保留此 App、群和 Topic;旧连接默认升级为 Agent 异步收件箱。`,"lark.conversationKind":`连接用途`,"lark.managerConversation":`管家 · 同步对话`,"lark.workerConversation":`工作 Agent · 后台任务`,"lark.managerConversationDescription":`内置管家即时回应对话,长任务交给后台 Agent。群聊与私聊分别保存上下文。`,"lark.ingressLegacy":`待升级`,"lark.ingressLegacyDescription":`保存连接即可升级为 Agent 异步收件箱,已有消息保留在原 Topic 中。`,"lark.ingressQueue":`排队`,"lark.ingressQueueDescription":`进入同一 Agent Session 的有界 FIFO 队列,当前 Turn 完成后处理。`,"lark.ingressSteering":`实时引导`,"lark.ingressSteeringDescription":`投到当前活跃 Turn;没有精确活跃 Turn 时安全拒绝。`,"lark.loading":`加载 Lark 配置…`,"lark.management":`Lark 管理`,"lark.openEventSettings":`查看飞书事件配置`,"lark.mentions":`提及机器人`,"lark.mentionsOnly":`仅提及消息`,"lark.needsMessagePermissions":`需要消息权限`,"lark.needsSetup":`需要设置`,"lark.newApp":`新建 Lark App`,"lark.noAgentConfigured":`未配置 Agent`,"lark.noConnections":`暂无匹配的连接。`,"lark.noProfiles":`还没有可用的 lark-cli App profile。`,"lark.profileName":`Profile 名称`,"lark.profileValidation":`Profile 只能包含字母、数字、点、下划线和连字符。`,"lark.processing":`处理方式`,"lark.region":`区域`,"lark.registerAnother":`+ 注册另一个 Lark App — 通过飞书创建`,"lark.reopenFeishu":`重新打开飞书`,"lark.settingsConfigure":`配置 {goal}`,"lark.settingsDisconnect":`解绑 {goal}`,"lark.replyMode":`回复方式`,"lark.replyModeDescription":`当前只支持在来源 Topic 内回复,避免跨群或跨 Goal 投递。`,"lark.reusableApps":`{count} 个可复用 App`,"lark.reusableWorkspaceApp":`可复用工作区 App`,"lark.routesUnverified":`{count} 条 Lark 路由尚未验证`,"lark.saveConnection":`保存连接`,"lark.searchConnections":`搜索 Lark 连接`,"lark.searchPlaceholder":`搜索 App、群、Goal 或 Topic`,"lark.setupCopy":`LoopX 将通过 lark-cli 打开飞书官方创建页面。应用凭证保存在系统 Keychain,LoopX 只保留 profile 引用。`,"lark.someoneMentions":`有人提及 Agent`,"lark.targetAgent":`目标 Agent`,"lark.targetAgentDescription":`选择该 Goal 内已注册的 Agent。此连接只投递给一个 Agent,不广播、不授予新权限。实时引导与排队需要该 Agent 的精确活跃 Session。`,"lark.agentUnavailable":`{agent} · 已不可用`,"lark.selectRegisteredAgent":`请先选择可用的已注册 Agent;不会自动替换原先的接收者。`,"lark.topicPreview":`Topic 预览`,"lark.topicReply":`Topic 回复`,"lark.trigger":`触发方式`,"lark.waitingFeishu":`等待飞书完成创建`,"lark.waitingFeishuDescription":`请在新窗口中完成飞书授权,完成后会自动回到这里。`,"lark.waitingLink":`正在生成飞书官方创建链接…`,"lark.error.appCreate":`Lark App 创建失败`,"lark.error.appRequired":`请选择一个 Lark App profile。`,"lark.error.bind":`绑定失败`,"lark.error.bindPreview":`绑定预览失败`,"lark.error.configuration":`Lark 配置加载失败`,"lark.error.groupLookup":`无法读取该机器人已加入的群。请检查机器人状态后重试。`,"lark.error.groupLoad":`群聊加载失败`,"lark.error.invalidApp":`Lark App profile 不可用或尚未完成授权。`,"lark.error.messagePermissions":`该 App 缺少自动回复所需的机器人权限。请开启 im:message.group_at_msg:readonly 和 im:message:send_as_bot,发布新版后回来刷新重试。`,"lark.error.provider":`飞书 API 调用失败,且没有生成已验证回执。请稍后重试。`,"lark.error.setupPoll":`创建状态查询失败`,"lark.error.setupStart":`无法启动 Lark App 创建流程`,"lark.error.cliExecutable":`已找到配置的 lark-cli,但当前无法执行。请检查安装或启动参数。`,"lark.error.cliMissing":`未发现 lark-cli。请先安装 lark-cli,然后重新启动 LoopX。`,"lark.error.cliStart":`lark-cli 启动失败。请检查安装状态,然后重新启动 LoopX。`,"lark.error.disconnect":`解绑失败`,"notifications.autoNotify":`需要你确认时自动推送到群里`,"notifications.bind":`绑定到通知群`,"notifications.bindConfirm":`将把「{goal}」绑定到通知群「{target}」,绑定时会验证机器人在群内并发送一条确认消息。`,"notifications.bindFailed":`绑定失败`,"notifications.bound":`已绑定`,"notifications.confirmBind":`确认绑定`,"notifications.description":`把 Goal 里需要你确认的变更推送到飞书群。绑定和开关在这里完成,推送逻辑沿用现有通道。`,"notifications.disabled":`已停用`,"notifications.group":`通知群:{target}`,"notifications.loadFailed":`通知群列表加载失败`,"notifications.noTargets":`还没有可用的通知群。通知群涉及机器人私有身份,请先在终端配置一次:`,"notifications.notBound":`未绑定`,"notifications.recent":`最近 {time}`,"notifications.sentCount":`已发送 {count} 条`,"notifications.settings":`Goal 通知绑定`,"notifications.setupFailed":`设置失败`,"notifications.title":`飞书群通知`,"proposal.field.agentId":`Agent`,"proposal.field.cadence":`频率`,"proposal.field.completionCriteria":`完成标准`,"proposal.field.executionBoundary":`执行边界`,"proposal.field.goalId":`Goal ID`,"proposal.field.heartbeat":`Heartbeat`,"proposal.field.initialTodos":`首个任务`,"proposal.field.objective":`目标`,"proposal.field.operation":`操作`,"proposal.field.operationState":`操作状态`,"proposal.field.resultDelivery":`结果回传`,"proposal.field.confirmationBoundary":`确认边界`,"proposal.field.expiresAt":`过期时间`,"proposal.field.permission":`权限`,"proposal.field.reason":`原因`,"proposal.field.stopCondition":`停止条件`,"proposal.field.target":`检查内容`,"proposal.field.timezone":`时区`,"proposal.field.title":`标题`,"proposal.field.workspace":`执行工作区`,"actionReview.targetChanged":`预览目标与请求的 Goal 或操作不一致,请重新生成预览。`,"actionReview.ready_stop":`暂停可恢复。此预览已通过检查,可直接执行;完成仍需要读回验证。`,"actionReview.resume_review":`恢复自动调度前需要确认。实际执行仍受额度、Gate 和 Todo 约束。`,"actionReview.delete_review":`请确认从注册表移除这个已停止 Goal。项目文件与历史记录会保留。`,"actionReview.action_review":`执行前请检查此提案的目标与影响。`,"actionReview.protected_action":`此操作需要明确审阅。确认不能替代所需授权。`,"actionReview.unknown_permission":`无法识别权限分类。请重新检查提案后再继续。`,"actionReview.unknown_action":`无法识别此生命周期操作。请重新检查提案后再继续。`,"actionReview.incomplete_proposal":`预览缺少验证信息或可执行转换。请重新生成预览。`,"actionReview.authority_gate":`Gate 阻止执行。请满足其要求后重新检查提案。`,"actionReview.stale_proposal":`来源状态已变化。请重新生成预览,原决定不再适用。`,"actionReview.apply_pending":`正在执行,请等待读回结果后再重试。`,"actionReview.readback_verified":`操作已完成,结果状态已通过读回验证。`,"actionReview.readback_unverified":`操作返回但未通过读回验证。尚不能确认完成,请重新检查状态。`,"actionReview.apply_failed":`执行未完成。请检查失败原因并重新生成预览后再试。`,"actionReview.inactive_proposal":`此提案当前不可执行。请重新检查后再继续。`,"proposal.gate.default":`需要宿主确认`,"proposal.impact.default":`确认后会调用规范 LoopX 服务写入状态。`,"proposal.impact.goalCreate":`确认后会创建 Goal 和首个 Todo,并让选定 Agent 开始首轮推进。`,"proposal.impact.lifecycleDelete":`确认后会从 source registry 和 global registry 移除这个已停止 Goal;项目文件、历史状态文件和备份不会被删除。`,"proposal.impact.lifecycleResume":`确认后会恢复 Goal 的自动调度资格并移回 Active Goals;实际执行仍受 quota、Gate 和 Todo 约束。`,"proposal.impact.lifecycleStop":`确认后会停止自动推进,并将 Goal 移入折叠的「已停止」列表;历史、Todo 和证据都会保留,可随时恢复。`,"proposal.impact.protected":`该操作需要通过受保护的 LoopX 写入服务完成。`,"proposal.impact.operation":`这里仅展示同一份不可变条款。请在已绑定的飞书群确认或拒绝;确认只会消费一个规范 claim。`,"proposal.primary.apply":`确认并应用`,"proposal.primary.goalCreate":`创建 Goal 并开始首轮`,"proposal.primary.lifecycleDelete":`删除 Goal`,"proposal.primary.lifecycleResume":`恢复 Goal`,"proposal.primary.lifecycleStop":`停止 Goal`,"proposal.primary.todoStart":`创建任务并开始执行`,"proposal.primary.operationGroup":`前往飞书群确认`,"proposal.resultDelivery.verified":`已在原群卡片完成回读核验`,"proposal.resultDelivery.pending":`等待回传并核验原群卡片`,"proposal.summary.goalCreate":`创建 Goal:{title}`,"proposal.summary.heartbeat":`为当前 Goal 设置 Heartbeat`,"proposal.summary.lifecycleDelete":`删除 Goal:{title}`,"proposal.summary.lifecycleResume":`恢复 Goal:{title}`,"proposal.summary.lifecycleStop":`停止 Goal:{title}`,"proposal.summary.monitor":`为当前 Goal 创建定时检查:{target}`,"proposal.workspace.current":`当前本地工作区(未绑定 Repository)`,"proposal.workspace.named":`{workspace}(仅提供执行环境,不会自动关联仓库)`,"proposal.workspaceGate.agentImpact":`先完成 Agent 身份绑定,再重新检查原操作;当前没有写入 Goal。`,"proposal.workspaceGate.agentTitle":`先绑定 Agent`,"proposal.workspaceGate.defaultSummary":`请选择 Goal 所属工作区。`,"proposal.workspaceGate.selectionImpact":`选择工作区后会重新展示待确认操作,选择本身不会写入状态。`,"proposal.workspaceGate.selectionTitle":`选择 Goal 工作区`,"projection.agentAdvancingGoal":`Agent 正在推进当前 Goal`,"projection.agentIdle":`暂无需要你处理`,"projection.agentNeedsDecision":`Agent 等待你的决定`,"projection.agentPreparingNextStep":`Agent 正在整理下一步`,"projection.agentStopped":`已由你停止;历史、Todo 和证据仍保留`,"projection.agentWaitingExternal":`正在等待外部条件`,"projection.confirmAgentDecision":`请确认 Agent 下一步需要的权限或决策`,"projection.events24h":`24 小时内 {count} 个事件`,"projection.firstReadOnlyAdapterCheck":`执行首次只读适配检查并保存进度`,"projection.goalVerified":`Goal 状态、Todo 与注册信息已验证`,"projection.latestRun":`最近运行`,"projection.latestValidation":`最近验证`,"projection.nextUpdatePending":`等待 LoopX 更新下一步`,"projection.publicSafeProjection":`公开安全状态投影`,"projection.refreshState":`刷新 LoopX 状态,确认当前进度仍然有效`,"projection.runEvidenceAvailable":`存在可查看的运行证据`,"projection.runRecorded":`最近一次 LoopX 运行已经记录`,"projection.statusRefreshNeeded":`LoopX 状态需要刷新`,"projection.todoStatusUpdated":`Todo 状态已经更新,正在确认下一步`,"projection.validationRecorded":`最近验证已经记录`,"runs.completed":`已完成`,"runs.failed":`需检查`,"runs.interrupted":`已中断`,"runs.queued":`已安排`,"runs.ready":`可继续`,"runs.resumeFailed":`恢复失败`,"runs.running":`执行中`,"runs.unknown":`状态未知`,"runs.waiting":`等待条件`,"schedule.active":`执行中`,"schedule.heartbeat":`Goal Heartbeat`,"schedule.monitor":`定时与持续任务`,"schedule.paused":`已暂停`,"schedule.summary":`按 LoopX 调度约束持续检查`,"schedule.defaultTarget":`检查当前 Goal 的阻塞、进度与新产出`,"schedule.unsupportedCalendar":`当前定时检查不支持精确到星期或时刻的日历计划。请改用固定间隔,例如“每 30 分钟”“每 2 小时”或“每天”;草稿已保留,没有生成待确认操作。`,"source.add":`添加来源`,"source.addConfigured":`添加只读来源`,"source.addMethod":`来源添加方式`,"source.addSsh":`添加 SSH 隧道来源`,"source.closeForm":`关闭来源表单`,"source.configured":`已配置 SSH`,"source.configuredCount":`本机 SSH Host · {count} 个`,"source.configuredGroup":`已配置 SSH Host · {count}(点击快速添加)`,"source.connected":`已连接`,"source.connecting":`连接中`,"source.controlPlane":`控制面来源`,"source.copy":`复制`,"source.copyCommand":`复制 SSH 隧道命令`,"source.copyError":`无法复制命令,请手动复制下方命令。`,"source.copied":`已复制`,"source.description":`已读取全部显式 Host(含 Include);通配规则不会作为具体来源。先运行命令,LoopX 不读取密钥或配置细节。`,"source.host":`本机 SSH Host`,"source.hostEmpty":`~/.ssh/config 中没有可直接选择的显式 Host。`,"source.hostLoadError":`无法读取本机 SSH Host。`,"source.hostPlaceholder":`输入或搜索 Host`,"source.invalid":`SSH 来源参数无效。`,"source.loadingHosts":`正在读取…`,"source.localInteractive":`本机交互`,"source.localPort":`本地端口`,"source.manual":`手动 URL`,"source.manualDescription":`远端来源始终按只读投影处理,不继承本机写权限。`,"source.name":`名称`,"source.namePlaceholder":`远程开发机`,"source.notAvailable":`不可用`,"source.readOnly":`SSH 隧道 · 只读`,"source.readOnlyNoticeDescription":`你可以查看 Goal、Task、证据与运行状态;写入、纠偏和 Agent 会话仍留在来源主机。`,"source.readOnlyNoticeTitle":`远端只读投影`,"source.readOnlyWriteError":`远端 SSH 隧道来源是只读投影,不能执行控制面写入。`,"source.refreshHosts":`重新读取 SSH Host`,"source.remove":`移除来源 {source}`,"source.removeCurrent":`移除当前来源`,"source.select":`选择控制面来源`,"source.selectHost":`请选择已配置的 SSH Host。`,"source.statusUrl":`本地转发 URL`,"source.tunnelCommandPending":`选择 Host 后生成隧道命令`,"machine.absent":`尚未配置`,"machine.action.create":`创建机器策略`,"machine.action.delete":`移除机器策略`,"machine.action.unchanged":`无需写入`,"machine.action.update":`更新机器策略`,"machine.applied":`机器策略已应用,并通过回读校验。`,"machine.applyError":`无法应用机器策略。`,"machine.applyPreview":`应用已审阅预览`,"machine.changedNamespaces":`变更的 Namespace`,"machine.capabilityCatalog":`机器能力目录`,"machine.capabilityEmpty":`当前没有注册可在机器作用域配置的能力。`,"machine.configured":`已配置`,"machine.confirmRollback":`确认回滚`,"machine.currentRevision":`当前 Revision`,"machine.currentValue":`当前机器值`,"machine.description":`与 Goal 设置共用能力目录。在这里管理受支持的机器默认值;仅支持 Goal 配置的能力会明确标注。`,"capabilities.rawJson":`高级:原始 JSON`,"machine.goalOnly":`此能力目前仅支持 Goal 级配置。请打开具体 Goal 的能力设置进行配置;这里不会设置机器级默认值。`,"machine.desiredRevision":`目标 Revision`,"machine.editorUnavailable":`当前版本未安装此 Namespace 的编辑器`,"machine.editorUnavailableDescription":`它仍会显示在 Registry 中;安装或升级对应的 Dashboard 编辑器后才能修改。`,"machine.editorMode":`编辑模式`,"machine.liveDefault":`实时默认值;Goal 显式覆盖优先`,"machine.liveDefaultDescription":`没有显式覆盖的 Goal 会在该能力下一次决策时读取当前机器策略。修改或移除策略会立即影响这些已有 Goal;显式 Goal 覆盖保持固定。`,"machine.genericNamespaceDescription":`使用 JSON 编辑这个已注册 Namespace。LoopX 会先按 capability 自己拥有的 schema 校验,再允许预览写入。`,"machine.jsonConfiguration":`Namespace 配置(JSON)`,"machine.jsonConfigurationHelp":`只更新当前 Namespace;其他机器配置会保留,Apply 仍锁定到已审阅的 Preview Revision。`,"machine.jsonEditor":`JSON`,"machine.editJson":`编辑 JSON`,"capabilities.jsonConfiguration":`Goal 配置(JSON)`,"capabilities.jsonHelp":`仅编辑当前 Goal 的已注册字段。修改后需重新预览才能应用。`,"capabilities.jsonInvalid":`请输入合法的 JSON 对象,且仅包含已注册的可编辑字段。`,"machine.backToForm":`返回表单`,"machine.jsonInvalid":`请先填写一个合法的 JSON object,再预览变更。`,"machine.loadError":`无法读取机器配置。`,"machine.machinePolicy":`机器策略`,"machine.namespaceCount":`已注册 Namespace`,"machine.namespaces":`配置 Namespace`,"machine.periodicReport":`周期报告`,"machine.periodicReportDescription":`为所有未显式覆盖的 Goal 提供默认报告策略;Goal 调度与发送消费解析后的有效配置。`,"machine.periodicReportActivation":`开启后将在已验证的阶段节点自动投递`,"machine.periodicReportActivationDescription":`这不是每周定时器。当 LoopX 验证 Goal 已完成一个阶段时,Agent 会生成并冻结报告,随后通过配置的 Goal Channel 自动发送。启用此订阅即授予持续投递权;发送失败或路由漂移会 fail closed 并进入修复。`,"machine.changeQualityActivation":`质量验证是质量门禁,不是新增授权`,"machine.changeQualityActivationDescription":`继承该策略的 Goal 会验证最终精确 diff。safe_fix 只允许在既有写入权限内执行至多一次有界修复;此设置不会授予文件、权限或合并权。`,"machine.replanCadenceActivation":`复核周期只改变时机,不改变执行权限`,"machine.replanCadenceActivationDescription":`没有显式覆盖的 Goal 会在下一次复核决策前读取此阈值;它不会创建 Turn、消耗配额或授予权限。`,"machine.preview":`审阅机器配置变更`,"machine.previewChanges":`预览变更`,"machine.previewError":`无法生成机器策略预览。`,"machine.previewLocked":`应用操作锁定到当前 Revision;若机器状态变化,LoopX 会要求重新预览。`,"machine.previewRollback":`预览回滚`,"machine.previewRemoval":`预览移除`,"machine.profilePreset":`Profile preset`,"machine.profilePresetHelp":`由 capability 管理的 preset,例如 weekly-progress。`,"machine.registry":`Typed Registry`,"machine.requiredFields":`开启后必须填写 profile preset、Goal Channel route 与有效时区。`,"machine.revision":`机器 Revision`,"machine.revisionLockedReady":`所有变更必须先预览;只有对应的机器 Revision 仍然有效时才会应用。`,"machine.rollbackAvailable":`可回滚上一次应用`,"machine.rollbackDescription":`先预览已保存的前一 Revision,再决定是否恢复。`,"machine.rollbackError":`无法完成回滚。`,"machine.rollbackPreviewDescription":`前一 Revision 已准备恢复,请确认执行本次回滚。`,"machine.rolledBack":`已恢复前一版机器策略,并通过校验。`,"machine.removed":`机器策略已移除,并通过回读校验。`,"machine.routeRef":`Goal Channel route`,"machine.routeRefHelp":`只填写公开 route alias;凭据与 provider identifier 不会进入此表单。`,"machine.timezone":`时区`,"machine.timezoneHelp":`填写 IANA 时区,例如 Asia/Shanghai。`,"machine.title":`机器配置`,"machine.unchanged":`机器策略已与预览一致,本次没有写入。`,"machine.visualEditor":`引导式`,"capabilities.atomicOverride":`Goal override 按完整配置生效`,"capabilities.atomicOverrideDescription":`Goal 的完整配置优先于机器默认值;LoopX 不会在两个作用域之间逐字段拼接。`,"capabilities.applyFailed":`Goal 能力变更未写入。`,"capabilities.applyPreview":`应用此预览`,"capabilities.catalog":`Goal 能力目录`,"capabilities.chooseGoal":`请先选择一个 Goal,再查看它的能力配置。`,"capabilities.defaultValue":`声明的默认值`,"capabilities.description":`查看当前 Goal 可用的能力,以及每项配置的准确作用域。`,"capabilities.editorPrepared":`已注册 typed editor contract`,"capabilities.effectiveSource":`当前生效来源`,"capabilities.empty":`当前 Goal 没有可用的能力描述。`,"capabilities.fields":`已注册字段`,"capabilities.goalPolicy":`Goal 能力策略`,"capabilities.goalScope":`Goal`,"capabilities.goalValue":`当前 Goal 值`,"capabilities.loadFailed":`无法加载 Goal 能力`,"capabilities.loading":`正在加载 Goal 能力…`,"capabilities.machineOnly":`此能力只能在机器作用域配置。`,"capabilities.machineValue":`实时机器默认值`,"capabilities.machineScope":`机器`,"capabilities.previewOnly":`当前读取结果来自真实配置;在 revision-locked preview/apply 路径接通前,Dashboard 不会提供 Goal 写入控件。`,"capabilities.preview":`锁定 revision 的变更预览`,"capabilities.previewChanges":`预览变更`,"capabilities.restoreInheritance":`恢复继承机器默认值`,"capabilities.previewFailed":`无法预览 Goal 能力变更。`,"capabilities.previewLocked":`应用时会重新校验这一个 plan revision;过期变更将被拒绝。`,"capabilities.partialWrite":`Goal 值已保存;共享投影仍需修复`,"capabilities.partialWriteDescription":`源 Goal 配置已经写入并回读,但共享 runtime 投影尚未同步;请勿重复提交本次变更。`,"capabilities.refreshSource":`刷新源配置`,"capabilities.readOnly":`只读能力`,"capabilities.revisionLockedReady":`所有变更必须先预览;只有对应的精确 revision 仍然有效时才会写入。`,"capabilities.retry":`重试`,"capabilities.source.capability_default":`能力默认值`,"capabilities.source.goal_override":`Goal override`,"capabilities.source.machine_default":`实时机器默认值`,"capabilities.source.not_configured":`未配置`,"capabilities.title":`Goal 能力`,"settings.close":`关闭设置`,"settings.appearance":`外观`,"settings.appearanceDescription":`管理当前浏览器里的工作区显示偏好。`,"settings.appearanceTabDescription":`主题和显示偏好`,"settings.capabilitiesTabDescription":`当前 Goal 的能力覆盖配置`,"settings.back":`返回工作区`,"settings.categories":`设置分类`,"settings.description":`管理工作区偏好与集成。`,"settings.eyebrow":`工作区偏好`,"settings.general":`通用`,"settings.goalConnections":`Goal 连接`,"settings.language":`语言`,"settings.languageDescription":`选择 LoopX Desktop 工作区使用的界面语言。`,"settings.languageEnglishDescription":`使用英文显示导航、设置和工作区控件。`,"settings.languageEnglish":`English`,"settings.languageSimplifiedChineseDescription":`使用简体中文显示导航、设置和工作区控件。`,"settings.languageSimplifiedChinese":`简体中文`,"settings.languageStoredLocally":`此偏好仅保存在当前设备。`,"settings.languageTabDescription":`当前设备的界面语言`,"settings.larkTabDescription":`App、群聊和 Goal Topic 连接`,"settings.machineTabDescription":`本机各 Capability 共享的 typed defaults`,"settings.notifications":`通知`,"settings.open":`设置`,"settings.themeDefault":`纸张`,"settings.themeDefaultDescription":`安静、轻量,适合长期查看。`,"settings.themeDescription":`选择工作区的视觉风格。设置会保存在当前浏览器本地。`,"settings.themeHighContrast":`高对比`,"settings.themeHighContrastDescription":`更强边框和更醒目的状态块。`,"settings.themeLoopx":`LoopX 标准`,"settings.themeLoopxDescription":`精确的黑白界面、Geist 字体与安静的细线结构。`,"settings.title":`设置`,"settings.workspaceDisplay":`工作区显示`,"settings.workspaceTheme":`工作区主题`,"session.closeRecord":`退出运行记录`,"session.details":`Session 详情`,"session.record":`执行 Session · 运行记录`,"session.recordDescription":`当前时间线已切换到这次 Session 的消息与 Turn 记录。`,"sidebar.createGoal":`创建 Goal`,"sidebar.delete":`删除`,"sidebar.deleteGoal":`删除 Goal`,"sidebar.manager":`LoopX 管家`,"sidebar.notifications":`设置`,"sidebar.owner":`个人工作区`,"sidebar.product":`个人 Agent 工作区`,"sidebar.resume":`恢复`,"sidebar.resumeGoal":`恢复 Goal`,"sidebar.stop":`停止`,"tasks.historyLoading":`正在加载历史…`,"tasks.historyError":`历史加载失败,已显示的内容仍可查看。`,"tasks.historyExpired":`历史快照已过期,重新加载后可继续查看。`,"tasks.historyRetry":`重新加载`,"tasks.historyEnd":`已显示全部完成记录`,"tasks.historyMore":`加载更多`,"tasks.historyLocalOnly":`请打开这台机器的 Dashboard 查看完整历史。`,"sidebar.sortGoals":`调整 Goal 顺序`,"sidebar.dragGoal":`拖拽调整顺序,或使用列表排序按钮`,"sidebar.moveUp":`上移 {goal}`,"sidebar.moveDown":`下移 {goal}`,"sidebar.goalMoved":`{goal} 已移至第 {position} 位`,"sidebar.orderNotSaved":`顺序已在本次页面生效;浏览器存储不可用,无法保存。`,"sidebar.stopGoal":`停止 Goal`,"sidebar.stopped":`已停止`,"sidebar.stoppedLoading":`正在加载已停止 Goal`,"sidebar.stoppedLoadFailed":`已停止 Goal 加载失败,其他 Goal 仍可使用。`,"sidebar.retryStopped":`重试`,"state.completed":`已完成`,"state.needsRepair":`需修复`,"state.needsYou":`等你`,"state.quiet":`安静运行`,"state.running":`推进中`,"state.stopped":`已停止`,"state.waiting":`等待条件`,"tasks.blocked":`受阻`,"tasks.agentLane":`工作 Agent`,"tasks.agentLaneDescription":`筛选这个 Goal 下的工作泳道`,"tasks.agentLaneFilter":`按工作 Agent 筛选`,"tasks.allAgentLanes":`全部 Agent({count})`,"tasks.chatAgentReplied":`Agent 已回复`,"tasks.chatPending":`已发送给 Agent`,"tasks.chatPendingDescription":`正在处理;只有经过确认的任务操作才会更新 Tasks。`,"tasks.chatRecent":`最近对话`,"tasks.chatUnchangedDescription":`本次对话没有直接修改 Tasks。需要执行时,可先转成 Task 草稿并确认。`,"tasks.chatViewReply":`查看回复`,"tasks.convertToTask":`转为 Task`,"tasks.completed":`已完成`,"runs.discoveryPartial":`部分执行详情暂不可用,正在重连;任务摘要不代表实时执行状态。`,"runs.discoveryOffline":`执行服务暂不可用,正在重连;保留的任务摘要可能已过时。`,"files.openConversation":`前往会话`,"files.exportSummary":`导出摘要`,"tasks.viewDescription":`先处理待确认,再查看工作与完成记录`,"tasks.viewLabel":`任务视图`,"tasks.listView":`列表`,"tasks.boardView":`看板`,"tasks.completedSummary":`已完成 {count} 项,近期完成明细由控制面按需投影。`,"tasks.emptyCompleted":`还没有完成的任务。`,"tasks.emptyConfirm":`没有待确认的任务。`,"tasks.emptyRunning":`没有待执行或进行中的任务。`,"tasks.emptySchedules":`没有定时任务。`,"tasks.emptyGoal":`这个 Goal 还没有任务。用下面的输入框描述下一步,LoopX 会先展示待确认操作。`,"tasks.markComplete":`标记完成:{name}`,"tasks.moreActions":`更多操作:{name}`,"tasks.openExecution":`查看执行过程:{name}`,"tasks.pending":`待处理`,"tasks.pendingAndRunning":`待执行 / 进行中`,"tasks.scheduled":`定时与持续`,"tasks.sessionError":`Session 异常`,"tasks.waiting":`待执行`,"tasks.waitingAge":`已等待 {age}`,"tasks.viewExecution":`查看执行过程`,"tasks.viewResult":`查看结果`,"time.days":`{count} 天`,"time.hours":`{count} 小时`,"timeline.emptyGoal":`这个 Goal 还没有新动态`,"timeline.emptyGoalDescription":`你可以直接询问进度或下发新的纠偏信息。`,"timeline.emptyWorkspace":`今天的工作区很安静`,"timeline.emptyWorkspaceDescription":`向 LoopX 管家描述一个 Goal,或询问今天最值得关注的事情。`,"timeline.gateHistory":`{count} 项历史 Gate`,"timeline.pending":`正在整理…`,"timeline.runCompleted":`{run}:已完成`,"timeline.review":`查看处理方式`,"timeline.reviewAndConfirm":`查看并确认`,"timeline.waitingConfirmation":`待你确认`}};function Gi(e,t){return t?Object.entries(t).reduce((e,[t,n])=>e.replaceAll(`{${t}}`,String(n)),e):e}function Ki(){try{return window.localStorage.getItem(`loopx-pw-locale`)===`en`?`en`:`zh-CN`}catch{return`zh-CN`}}function qi({children:e}){let[t,n]=(0,z.useState)(Ki);function r(e){n(e);try{window.localStorage.setItem(Ui,e)}catch{}}(0,z.useEffect)(()=>{document.documentElement.lang=t},[t]);let i=(0,z.useMemo)(()=>({locale:t,setLocale:r,t:(e,n)=>Gi(Wi[t][e],n)}),[t]);return(0,B.jsx)(Hi.Provider,{value:i,children:e})}function Ji(){let e=(0,z.useContext)(Hi);if(!e)throw Error(`useWorkspaceI18n must be used within WorkspaceI18nProvider`);return e}function Yi(e,t){let n={安静运行:`state.quiet`,等你:`state.needsYou`,等待条件:`state.waiting`,推进中:`state.running`,需修复:`state.needsRepair`,已完成:`state.completed`,已停止:`state.stopped`}[e];return n?Wi[t][n]:e}function Xi(e,t){let n={busy:`runs.running`,completed:`runs.completed`,failed:`runs.failed`,queued:`runs.queued`,ready:`runs.ready`,resume_failed:`runs.resumeFailed`,running:`runs.running`,waiting:`runs.waiting`};return e?n[e]?t(n[e]):e:t(`runs.unknown`)}function Zi(e,t){if(!e)return null;let n=new Date(e).getTime();if(Number.isNaN(n))return null;let r=Date.now()-n;if(r<36e5)return null;let i=Math.floor(r/864e5);return i>=1?t(`time.days`,{count:i}):t(`time.hours`,{count:Math.floor(r/36e5)})}var Qi;function H(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;en?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var $i=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},ea=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Qi=globalThis).__zod_globalConfig??(Qi.__zod_globalConfig={});var ta=globalThis.__zod_globalConfig;function na(e){return e&&Object.assign(ta,e),ta}function ra(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function ia(e,t){return typeof t==`bigint`?t.toString():t}function aa(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function oa(e){return e==null}function sa(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function ca(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r){};function ga(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var _a=aa(()=>{if(ta.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function va(e){if(ga(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return ga(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function ya(e){return va(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var ba=new Set([`string`,`number`,`symbol`]);function xa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Sa(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function U(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Ca(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var wa={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ta(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Sa(e,fa(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return da(this,`shape`,e),e},checks:[]}))}function Ea(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Sa(e,fa(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return da(this,`shape`,r),r},checks:[]}))}function Da(e,t){if(!va(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Sa(e,fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return da(this,`shape`,n),n}}))}function Oa(e,t){if(!va(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Sa(e,fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return da(this,`shape`,n),n}}))}function ka(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Sa(e,fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return da(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function Aa(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return Sa(t,fa(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return da(this,`shape`,i),i},checks:[]}))}function ja(e,t,n){return Sa(t,fa(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return da(this,`shape`,i),i}}))}function Ma(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Fa(e){return typeof e==`string`?e:e?.message}function Ia(e,t,n){let r=e.message?e.message:Fa(e.inst?._zod.def?.error?.(e))??Fa(t?.error?.(e))??Fa(n.customError?.(e))??Fa(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function La(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Ra(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var za=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ia,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ba=H(`$ZodError`,za),Va=H(`$ZodError`,za,{Parent:Error});function Ha(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ua(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new $i;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Ia(e,a,na())));throw ha(t,i?.callee),t}return o.value},Ga=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Ia(e,a,na())));throw ha(t,i?.callee),t}return o.value},Ka=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new $i;return a.issues.length?{success:!1,error:new(e??Ba)(a.issues.map(e=>Ia(e,i,na())))}:{success:!0,data:a.value}},qa=Ka(Va),Ja=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>Ia(e,i,na())))}:{success:!0,data:a.value}},Ya=Ja(Va),Xa=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Wa(e)(t,n,i)},Za=e=>(t,n,r)=>Wa(e)(t,n,r),Qa=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ga(e)(t,n,i)},$a=e=>async(t,n,r)=>Ga(e)(t,n,r),eo=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ka(e)(t,n,i)},to=e=>(t,n,r)=>Ka(e)(t,n,r),no=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ja(e)(t,n,i)},ro=e=>async(t,n,r)=>Ja(e)(t,n,r),io=/^[cC][0-9a-z]{6,}$/,ao=/^[0-9a-z]+$/,oo=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,so=/^[0-9a-vA-V]{20}$/,co=/^[A-Za-z0-9]{27}$/,lo=/^[a-zA-Z0-9_-]{21}$/,uo=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,fo=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,po=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,mo=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ho=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function go(){return new RegExp(ho,`u`)}var _o=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,vo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,yo=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,bo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xo=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,So=/^[A-Za-z0-9_-]*$/,Co=/^https?$/,wo=/^\+[1-9]\d{6,14}$/,To=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,Eo=RegExp(`^${To}$`);function Do(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Oo(e){return RegExp(`^${Do(e)}$`)}function ko(e){let t=Do({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${To}T(?:${r})$`)}var Ao=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},jo=/^-?\d+$/,Mo=/^-?\d+(?:\.\d+)?$/,No=/^(?:true|false)$/i,Po=/^null$/i,Fo=/^[^A-Z]*$/,Io=/^[^a-z]*$/,Lo=H(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ro={number:`number`,bigint:`bigint`,object:`date`},zo=H(`$ZodCheckLessThan`,(e,t)=>{Lo.init(e,t);let n=Ro[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value{(t.inclusive?r.value<=t.value:r.value{Lo.init(e,t);let n=Ro[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Vo=H(`$ZodCheckMultipleOf`,(e,t)=>{Lo.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):ca(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Ho=H(`$ZodCheckNumberFormat`,(e,t)=>{Lo.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=wa[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=jo)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}sa&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Uo=H(`$ZodCheckMaxLength`,(e,t)=>{var n;Lo.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!oa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum{let r=n.value;if(r.length<=t.maximum)return;let i=La(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Wo=H(`$ZodCheckMinLength`,(e,t)=>{var n;Lo.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!oa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=La(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Go=H(`$ZodCheckLengthEquals`,(e,t)=>{var n;Lo.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!oa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=La(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ko=H(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Lo.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),qo=H(`$ZodCheckRegex`,(e,t)=>{Ko.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Jo=H(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Fo,Ko.init(e,t)}),Yo=H(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Io,Ko.init(e,t)}),Xo=H(`$ZodCheckIncludes`,(e,t)=>{Lo.init(e,t);let n=xa(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Zo=H(`$ZodCheckStartsWith`,(e,t)=>{Lo.init(e,t);let n=RegExp(`^${xa(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Qo=H(`$ZodCheckEndsWith`,(e,t)=>{Lo.init(e,t);let n=RegExp(`.*${xa(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),$o=H(`$ZodCheckOverwrite`,(e,t)=>{Lo.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),es=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(` +`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(` +`))}},ts={major:4,minor:4,patch:3},ns=H(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ts;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=Ma(e),i;for(let a of t){if(a._zod.def.when){if(Na(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new $i;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=Ma(e,t))});else{if(e.issues.length===t)continue;r||=Ma(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(Ma(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new $i;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new $i;return o.then(e=>t(e,r,a))}return t(o,r,a)}}ua(e,`~standard`,()=>({validate:t=>{try{let n=qa(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Ya(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),rs=H(`$ZodString`,(e,t)=>{ns.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ao(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),is=H(`$ZodStringFormat`,(e,t)=>{Ko.init(e,t),rs.init(e,t)}),as=H(`$ZodGUID`,(e,t)=>{t.pattern??=fo,is.init(e,t)}),os=H(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=po(e)}else t.pattern??=po();is.init(e,t)}),ss=H(`$ZodEmail`,(e,t)=>{t.pattern??=mo,is.init(e,t)}),cs=H(`$ZodURL`,(e,t)=>{is.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===Co.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),n.value=t.normalize?i.href:r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),ls=H(`$ZodEmoji`,(e,t)=>{t.pattern??=go(),is.init(e,t)}),us=H(`$ZodNanoID`,(e,t)=>{t.pattern??=lo,is.init(e,t)}),ds=H(`$ZodCUID`,(e,t)=>{t.pattern??=io,is.init(e,t)}),fs=H(`$ZodCUID2`,(e,t)=>{t.pattern??=ao,is.init(e,t)}),ps=H(`$ZodULID`,(e,t)=>{t.pattern??=oo,is.init(e,t)}),ms=H(`$ZodXID`,(e,t)=>{t.pattern??=so,is.init(e,t)}),hs=H(`$ZodKSUID`,(e,t)=>{t.pattern??=co,is.init(e,t)}),gs=H(`$ZodISODateTime`,(e,t)=>{t.pattern??=ko(t),is.init(e,t)}),_s=H(`$ZodISODate`,(e,t)=>{t.pattern??=Eo,is.init(e,t)}),vs=H(`$ZodISOTime`,(e,t)=>{t.pattern??=Oo(t),is.init(e,t)}),ys=H(`$ZodISODuration`,(e,t)=>{t.pattern??=uo,is.init(e,t)}),bs=H(`$ZodIPv4`,(e,t)=>{t.pattern??=_o,is.init(e,t),e._zod.bag.format=`ipv4`}),xs=H(`$ZodIPv6`,(e,t)=>{t.pattern??=vo,is.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),Ss=H(`$ZodCIDRv4`,(e,t)=>{t.pattern??=yo,is.init(e,t)}),Cs=H(`$ZodCIDRv6`,(e,t)=>{t.pattern??=bo,is.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function ws(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Ts=H(`$ZodBase64`,(e,t)=>{t.pattern??=xo,is.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{ws(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Es(e){if(!So.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return ws(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var Ds=H(`$ZodBase64URL`,(e,t)=>{t.pattern??=So,is.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Es(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Os=H(`$ZodE164`,(e,t)=>{t.pattern??=wo,is.init(e,t)});function ks(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var As=H(`$ZodJWT`,(e,t)=>{is.init(e,t),e._zod.check=n=>{ks(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),js=H(`$ZodNumber`,(e,t)=>{ns.init(e,t),e._zod.pattern=e._zod.bag.pattern??Mo,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Ms=H(`$ZodNumberFormat`,(e,t)=>{Ho.init(e,t),js.init(e,t)}),Ns=H(`$ZodBoolean`,(e,t)=>{ns.init(e,t),e._zod.pattern=No,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Ps=H(`$ZodNull`,(e,t)=>{ns.init(e,t),e._zod.pattern=Po,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),Fs=H(`$ZodUnknown`,(e,t)=>{ns.init(e,t),e._zod.parse=e=>e}),Is=H(`$ZodNever`,(e,t)=>{ns.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Ls(e,t,n){e.issues.length&&t.issues.push(...Pa(n,e.issues)),t.value[n]=e.value}var Rs=H(`$ZodArray`,(e,t)=>{ns.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;eLs(t,n,e))):Ls(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function zs(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...Pa(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function Bs(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Ca(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Vs(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>zs(e,n,i,t,u,d))):zs(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var Hs=H(`$ZodObject`,(e,t)=>{if(ns.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=aa(()=>Bs(t));ua(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=ga,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>zs(n,t,e,s,r,i))):zs(a,t,e,s,r,i)}return i?Vs(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Us=H(`$ZodObjectJIT`,(e,t)=>{Hs.init(e,t);let n=e._zod.parse,r=aa(()=>Bs(t)),i=e=>{let t=new es([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=pa(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=pa(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(` + if (${n}.issues.length) { + if (${o} in input) { + payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${o}, ...iss.path] : [${o}] + }))); + } + } + + if (${n}.value === undefined) { + if (${o} in input) { + newResult[${o}] = undefined; + } + } else { + newResult[${o}] = ${n}.value; + } + + `):c?t.write(` + if (${n}.issues.length) { + payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${o}, ...iss.path] : [${o}] + }))); + } + + if (${n}.value === undefined) { + if (${o} in input) { + newResult[${o}] = undefined; + } + } else { + newResult[${o}] = ${n}.value; + } + + `):t.write(` + const ${n}_present = ${o} in input; + if (${n}.issues.length) { + payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${o}, ...iss.path] : [${o}] + }))); + } + if (!${n}_present && !${n}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${o}] + }); + } + + if (${n}_present) { + if (${n}.value === undefined) { + newResult[${o}] = undefined; + } else { + newResult[${o}] = ${n}.value; + } + } + + `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=ga,s=!ta.jitless,c=s&&_a.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?Vs([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function Ws(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Ma(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Ia(e,r,na())))}),t)}var Gs=H(`$ZodUnion`,(e,t)=>{ns.init(e,t),ua(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),ua(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),ua(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),ua(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>sa(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Ws(t,r,e,i)):Ws(o,r,e,i)}}),Ks=H(`$ZodIntersection`,(e,t)=>{ns.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Js(e,t,n)):Js(e,i,a)}});function qs(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(va(e)&&va(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=qs(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;re.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),Ma(e))return e;let o=qs(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var Ys=H(`$ZodTuple`,(e,t)=>{ns.init(e,t);let n=t.items;e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({input:a,inst:e,expected:`tuple`,code:`invalid_type`}),r;r.value=[];let o=[],s=Xs(n,`optin`),c=Xs(n,`optout`);if(!t.rest){if(a.lengthn.length&&r.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:a,inst:e,origin:`array`})}let l=Array(n.length);for(let e=0;e{l[e]=t})):l[e]=t}if(t.rest){let e=n.length-1,s=a.slice(n.length);for(let n of s){e++;let a=t.rest._zod.run({value:n,issues:[]},i);a instanceof Promise?o.push(a.then(t=>Zs(t,r,e))):Zs(a,r,e)}}return o.length?Promise.all(o).then(()=>Qs(l,r,n,a,c)):Qs(l,r,n,a,c)}});function Xs(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!==`optional`)return n+1;return 0}function Zs(e,t,n){e.issues.length&&t.issues.push(...Pa(n,e.issues)),t.value[n]=e.value}function Qs(e,t,n,r,i){for(let a=0;a=i){t.value.length=a;break}t.issues.push(...Pa(a,n.issues))}t.value[a]=n.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}var $s=H(`$ZodRecord`,(e,t)=>{ns.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!va(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>Ia(e,r,na())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...Pa(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...Pa(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&Mo.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Ia(e,r,na())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...Pa(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...Pa(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),ec=H(`$ZodEnum`,(e,t)=>{ns.init(e,t);let n=ra(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>ba.has(typeof e)).map(e=>typeof e==`string`?xa(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),tc=H(`$ZodLiteral`,(e,t)=>{if(ns.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?xa(e):e?xa(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),nc=H(`$ZodTransform`,(e,t)=>{ns.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new ea(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new $i;return n.value=i,n.fallback=!0,n}});function rc(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var ic=H(`$ZodOptional`,(e,t)=>{ns.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,ua(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ua(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${sa(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>rc(e,r)):rc(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),ac=H(`$ZodExactOptional`,(e,t)=>{ic.init(e,t),ua(e._zod,`values`,()=>t.innerType._zod.values),ua(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),oc=H(`$ZodNullable`,(e,t)=>{ns.init(e,t),ua(e._zod,`optin`,()=>t.innerType._zod.optin),ua(e._zod,`optout`,()=>t.innerType._zod.optout),ua(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${sa(e.source)}|null)$`):void 0}),ua(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),sc=H(`$ZodDefault`,(e,t)=>{ns.init(e,t),e._zod.optin=`optional`,ua(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>cc(e,t)):cc(r,t)}});function cc(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var lc=H(`$ZodPrefault`,(e,t)=>{ns.init(e,t),e._zod.optin=`optional`,ua(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),uc=H(`$ZodNonOptional`,(e,t)=>{ns.init(e,t),ua(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>dc(t,e)):dc(i,e)}});function dc(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var fc=H(`$ZodCatch`,(e,t)=>{ns.init(e,t),e._zod.optin=`optional`,ua(e._zod,`optout`,()=>t.innerType._zod.optout),ua(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Ia(e,n,na()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Ia(e,n,na()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),pc=H(`$ZodPipe`,(e,t)=>{ns.init(e,t),ua(e._zod,`values`,()=>t.in._zod.values),ua(e._zod,`optin`,()=>t.in._zod.optin),ua(e._zod,`optout`,()=>t.out._zod.optout),ua(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>mc(e,t.in,n)):mc(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>mc(e,t.out,n)):mc(r,t.out,n)}});function mc(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var hc=H(`$ZodReadonly`,(e,t)=>{ns.init(e,t),ua(e._zod,`propValues`,()=>t.innerType._zod.propValues),ua(e._zod,`values`,()=>t.innerType._zod.values),ua(e._zod,`optin`,()=>t.innerType?._zod?.optin),ua(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(gc):gc(r)}});function gc(e){return e.value=Object.freeze(e.value),e}var _c=H(`$ZodCustom`,(e,t)=>{Lo.init(e,t),ns.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>vc(t,n,r,e));vc(i,n,r,e)}});function vc(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Ra(e))}}var yc,bc=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function xc(){return new bc}(yc=globalThis).__zod_globalRegistry??(yc.__zod_globalRegistry=xc());var Sc=globalThis.__zod_globalRegistry;function Cc(e,t){return new e({type:`string`,...U(t)})}function wc(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...U(t)})}function Tc(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...U(t)})}function Ec(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...U(t)})}function Dc(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...U(t)})}function Oc(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...U(t)})}function kc(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...U(t)})}function Ac(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...U(t)})}function jc(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...U(t)})}function Mc(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...U(t)})}function Nc(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...U(t)})}function Pc(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...U(t)})}function Fc(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...U(t)})}function Ic(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...U(t)})}function Lc(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...U(t)})}function Rc(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...U(t)})}function zc(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...U(t)})}function Bc(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...U(t)})}function Vc(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...U(t)})}function Hc(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...U(t)})}function Uc(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...U(t)})}function Wc(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...U(t)})}function Gc(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...U(t)})}function Kc(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...U(t)})}function qc(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...U(t)})}function Jc(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...U(t)})}function Yc(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...U(t)})}function Xc(e,t){return new e({type:`number`,checks:[],...U(t)})}function Zc(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...U(t)})}function Qc(e,t){return new e({type:`boolean`,...U(t)})}function $c(e,t){return new e({type:`null`,...U(t)})}function el(e){return new e({type:`unknown`})}function tl(e,t){return new e({type:`never`,...U(t)})}function nl(e,t){return new zo({check:`less_than`,...U(t),value:e,inclusive:!1})}function rl(e,t){return new zo({check:`less_than`,...U(t),value:e,inclusive:!0})}function il(e,t){return new Bo({check:`greater_than`,...U(t),value:e,inclusive:!1})}function al(e,t){return new Bo({check:`greater_than`,...U(t),value:e,inclusive:!0})}function ol(e,t){return new Vo({check:`multiple_of`,...U(t),value:e})}function sl(e,t){return new Uo({check:`max_length`,...U(t),maximum:e})}function cl(e,t){return new Wo({check:`min_length`,...U(t),minimum:e})}function ll(e,t){return new Go({check:`length_equals`,...U(t),length:e})}function ul(e,t){return new qo({check:`string_format`,format:`regex`,...U(t),pattern:e})}function dl(e){return new Jo({check:`string_format`,format:`lowercase`,...U(e)})}function fl(e){return new Yo({check:`string_format`,format:`uppercase`,...U(e)})}function pl(e,t){return new Xo({check:`string_format`,format:`includes`,...U(t),includes:e})}function ml(e,t){return new Zo({check:`string_format`,format:`starts_with`,...U(t),prefix:e})}function hl(e,t){return new Qo({check:`string_format`,format:`ends_with`,...U(t),suffix:e})}function gl(e){return new $o({check:`overwrite`,tx:e})}function _l(e){return gl(t=>t.normalize(e))}function vl(){return gl(e=>e.trim())}function yl(){return gl(e=>e.toLowerCase())}function bl(){return gl(e=>e.toUpperCase())}function xl(){return gl(e=>ma(e))}function Sl(e,t,n){return new e({type:`array`,element:t,...U(n)})}function Cl(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...U(n)})}function wl(e,t){let n=Tl(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Ra(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Ra(r))}},e(t.value,t)),t);return n}function Tl(e,t){let n=new Lo({check:`custom`,...U(t)});return n._zod.check=e,n}function El(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Sc,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function Dl(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,Dl(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&Al(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Ol(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function kl(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Ml(t,`input`,e.processors),output:Ml(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function Al(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return Al(r.element,n);if(r.type===`set`)return Al(r.valueType,n);if(r.type===`lazy`)return Al(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return Al(r.innerType,n);if(r.type===`intersection`)return Al(r.left,n)||Al(r.right,n);if(r.type===`record`||r.type===`map`)return Al(r.keyType,n)||Al(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:Al(r.in,n)||Al(r.out,n);if(r.type===`object`){for(let e in r.shape)if(Al(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(Al(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(Al(e,n))return!0;return!!(r.rest&&Al(r.rest,n))}return!1}var jl=(e,t={})=>n=>{let r=El({...n,processors:t});return Dl(e,r),Ol(r,e),kl(r,e)},Ml=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=El({...i??{},target:a,io:t,processors:n});return Dl(e,o),Ol(o,e),kl(o,e)},Nl={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Pl=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Nl[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Fl=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},Il=(e,t,n,r)=>{n.type=`boolean`},Ll=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Rl=(e,t,n,r)=>{n.not={}},zl=(e,t,n,r)=>{let i=e._zod.def,a=ra(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Bl=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Vl=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Hl=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Ul=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=Dl(a.element,t,{...r,path:[...r.path,`items`]})},Wl=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=Dl(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Dl(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Gl=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>Dl(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Kl=(e,t,n,r)=>{let i=e._zod.def,a=Dl(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=Dl(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},ql=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>Dl(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?Dl(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},Jl=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=Dl(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=Dl(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=Dl(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},Yl=(e,t,n,r)=>{let i=e._zod.def,a=Dl(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Xl=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Zl=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Ql=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},$l=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},eu=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;Dl(o,t,r);let s=t.seen.get(e);s.ref=o},tu=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},nu=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ru=H(`ZodISODateTime`,(e,t)=>{gs.init(e,t),ju.init(e,t)});function iu(e){return Kc(ru,e)}var au=H(`ZodISODate`,(e,t)=>{_s.init(e,t),ju.init(e,t)});function ou(e){return qc(au,e)}var su=H(`ZodISOTime`,(e,t)=>{vs.init(e,t),ju.init(e,t)});function cu(e){return Jc(su,e)}var lu=H(`ZodISODuration`,(e,t)=>{ys.init(e,t),ju.init(e,t)});function uu(e){return Yc(lu,e)}var du=(e,t)=>{Ba.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Ua(e,t)},flatten:{value:t=>Ha(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,ia,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,ia,2)}},isEmpty:{get(){return e.issues.length===0}}})},fu=H(`ZodError`,du),pu=H(`ZodError`,du,{Parent:Error}),mu=Wa(pu),hu=Ga(pu),gu=Ka(pu),_u=Ja(pu),vu=Xa(pu),yu=Za(pu),bu=Qa(pu),xu=$a(pu),Su=eo(pu),Cu=to(pu),wu=no(pu),Tu=ro(pu),Eu=new WeakMap;function Du(e,t,n){let r=Object.getPrototypeOf(e),i=Eu.get(r);if(i||(i=new Set,Eu.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var Ou=H(`ZodType`,(e,t)=>(ns.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Ml(e,`input`),output:Ml(e,`output`)}}),e.toJSONSchema=jl(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>mu(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>gu(e,t,n),e.parseAsync=async(t,n)=>hu(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>_u(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>vu(e,t,n),e.decode=(t,n)=>yu(e,t,n),e.encodeAsync=async(t,n)=>bu(e,t,n),e.decodeAsync=async(t,n)=>xu(e,t,n),e.safeEncode=(t,n)=>Su(e,t,n),e.safeDecode=(t,n)=>Cu(e,t,n),e.safeEncodeAsync=async(t,n)=>wu(e,t,n),e.safeDecodeAsync=async(t,n)=>Tu(e,t,n),Du(e,`ZodType`,{check(...e){let t=this.def;return this.clone(fa(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Sa(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Bd(e,t))},superRefine(e,t){return this.check(Vd(e,t))},overwrite(e){return this.check(gl(e))},optional(){return Sd(this)},exactOptional(){return wd(this)},nullable(){return Ed(this)},nullish(){return Sd(Ed(this))},nonoptional(e){return Md(this,e)},array(){return q(this)},or(e){return ud([this,e])},and(e){return fd(this,e)},transform(e){return Id(this,bd(e))},default(e){return Od(this,e)},prefault(e){return Ad(this,e)},catch(e){return Pd(this,e)},pipe(e){return Id(this,e)},readonly(){return Rd(this)},describe(e){let t=this.clone();return Sc.add(t,{description:e}),t},meta(...e){if(e.length===0)return Sc.get(this);let t=this.clone();return Sc.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return Sc.get(e)?.description},configurable:!0}),e)),ku=H(`_ZodString`,(e,t)=>{rs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pl(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Du(e,`_ZodString`,{regex(...e){return this.check(ul(...e))},includes(...e){return this.check(pl(...e))},startsWith(...e){return this.check(ml(...e))},endsWith(...e){return this.check(hl(...e))},min(...e){return this.check(cl(...e))},max(...e){return this.check(sl(...e))},length(...e){return this.check(ll(...e))},nonempty(...e){return this.check(cl(1,...e))},lowercase(e){return this.check(dl(e))},uppercase(e){return this.check(fl(e))},trim(){return this.check(vl())},normalize(...e){return this.check(_l(...e))},toLowerCase(){return this.check(yl())},toUpperCase(){return this.check(bl())},slugify(){return this.check(xl())}})}),Au=H(`ZodString`,(e,t)=>{rs.init(e,t),ku.init(e,t),e.email=t=>e.check(wc(Mu,t)),e.url=t=>e.check(Ac(Fu,t)),e.jwt=t=>e.check(Gc(Xu,t)),e.emoji=t=>e.check(jc(Iu,t)),e.guid=t=>e.check(Tc(Nu,t)),e.uuid=t=>e.check(Ec(Pu,t)),e.uuidv4=t=>e.check(Dc(Pu,t)),e.uuidv6=t=>e.check(Oc(Pu,t)),e.uuidv7=t=>e.check(kc(Pu,t)),e.nanoid=t=>e.check(Mc(Lu,t)),e.guid=t=>e.check(Tc(Nu,t)),e.cuid=t=>e.check(Nc(Ru,t)),e.cuid2=t=>e.check(Pc(zu,t)),e.ulid=t=>e.check(Fc(Bu,t)),e.base64=t=>e.check(Hc(qu,t)),e.base64url=t=>e.check(Uc(Ju,t)),e.xid=t=>e.check(Ic(Vu,t)),e.ksuid=t=>e.check(Lc(Hu,t)),e.ipv4=t=>e.check(Rc(Uu,t)),e.ipv6=t=>e.check(zc(Wu,t)),e.cidrv4=t=>e.check(Bc(Gu,t)),e.cidrv6=t=>e.check(Vc(Ku,t)),e.e164=t=>e.check(Wc(Yu,t)),e.datetime=t=>e.check(iu(t)),e.date=t=>e.check(ou(t)),e.time=t=>e.check(cu(t)),e.duration=t=>e.check(uu(t))});function W(e){return Cc(Au,e)}var ju=H(`ZodStringFormat`,(e,t)=>{is.init(e,t),ku.init(e,t)}),Mu=H(`ZodEmail`,(e,t)=>{ss.init(e,t),ju.init(e,t)}),Nu=H(`ZodGUID`,(e,t)=>{as.init(e,t),ju.init(e,t)}),Pu=H(`ZodUUID`,(e,t)=>{os.init(e,t),ju.init(e,t)}),Fu=H(`ZodURL`,(e,t)=>{cs.init(e,t),ju.init(e,t)}),Iu=H(`ZodEmoji`,(e,t)=>{ls.init(e,t),ju.init(e,t)}),Lu=H(`ZodNanoID`,(e,t)=>{us.init(e,t),ju.init(e,t)}),Ru=H(`ZodCUID`,(e,t)=>{ds.init(e,t),ju.init(e,t)}),zu=H(`ZodCUID2`,(e,t)=>{fs.init(e,t),ju.init(e,t)}),Bu=H(`ZodULID`,(e,t)=>{ps.init(e,t),ju.init(e,t)}),Vu=H(`ZodXID`,(e,t)=>{ms.init(e,t),ju.init(e,t)}),Hu=H(`ZodKSUID`,(e,t)=>{hs.init(e,t),ju.init(e,t)}),Uu=H(`ZodIPv4`,(e,t)=>{bs.init(e,t),ju.init(e,t)}),Wu=H(`ZodIPv6`,(e,t)=>{xs.init(e,t),ju.init(e,t)}),Gu=H(`ZodCIDRv4`,(e,t)=>{Ss.init(e,t),ju.init(e,t)}),Ku=H(`ZodCIDRv6`,(e,t)=>{Cs.init(e,t),ju.init(e,t)}),qu=H(`ZodBase64`,(e,t)=>{Ts.init(e,t),ju.init(e,t)}),Ju=H(`ZodBase64URL`,(e,t)=>{Ds.init(e,t),ju.init(e,t)}),Yu=H(`ZodE164`,(e,t)=>{Os.init(e,t),ju.init(e,t)}),Xu=H(`ZodJWT`,(e,t)=>{As.init(e,t),ju.init(e,t)}),Zu=H(`ZodNumber`,(e,t)=>{js.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fl(e,t,n,r),Du(e,`ZodNumber`,{gt(e,t){return this.check(il(e,t))},gte(e,t){return this.check(al(e,t))},min(e,t){return this.check(al(e,t))},lt(e,t){return this.check(nl(e,t))},lte(e,t){return this.check(rl(e,t))},max(e,t){return this.check(rl(e,t))},int(e){return this.check($u(e))},safe(e){return this.check($u(e))},positive(e){return this.check(il(0,e))},nonnegative(e){return this.check(al(0,e))},negative(e){return this.check(nl(0,e))},nonpositive(e){return this.check(rl(0,e))},multipleOf(e,t){return this.check(ol(e,t))},step(e,t){return this.check(ol(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function G(e){return Xc(Zu,e)}var Qu=H(`ZodNumberFormat`,(e,t)=>{Ms.init(e,t),Zu.init(e,t)});function $u(e){return Zc(Qu,e)}var ed=H(`ZodBoolean`,(e,t)=>{Ns.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Il(e,t,n,r)});function K(e){return Qc(ed,e)}var td=H(`ZodNull`,(e,t)=>{Ps.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ll(e,t,n,r)});function nd(e){return $c(td,e)}var rd=H(`ZodUnknown`,(e,t)=>{Fs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function id(){return el(rd)}var ad=H(`ZodNever`,(e,t)=>{Is.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rl(e,t,n,r)});function od(e){return tl(ad,e)}var sd=H(`ZodArray`,(e,t)=>{Rs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ul(e,t,n,r),e.element=t.element,Du(e,`ZodArray`,{min(e,t){return this.check(cl(e,t))},nonempty(e){return this.check(cl(1,e))},max(e,t){return this.check(sl(e,t))},length(e,t){return this.check(ll(e,t))},unwrap(){return this.element}})});function q(e,t){return Sl(sd,e,t)}var cd=H(`ZodObject`,(e,t)=>{Us.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wl(e,t,n,r),ua(e,`shape`,()=>t.shape),Du(e,`ZodObject`,{keyof(){return Y(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:id()})},loose(){return this.clone({...this._zod.def,catchall:id()})},strict(){return this.clone({...this._zod.def,catchall:od()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Da(this,e)},safeExtend(e){return Oa(this,e)},merge(e){return ka(this,e)},pick(e){return Ta(this,e)},omit(e){return Ea(this,e)},partial(...e){return Aa(xd,this,e[0])},required(...e){return ja(jd,this,e[0])}})});function J(e,t){return new cd({type:`object`,shape:e??{},...U(t)})}var ld=H(`ZodUnion`,(e,t)=>{Gs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gl(e,t,n,r),e.options=t.options});function ud(e,t){return new ld({type:`union`,options:e,...U(t)})}var dd=H(`ZodIntersection`,(e,t)=>{Ks.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kl(e,t,n,r)});function fd(e,t){return new dd({type:`intersection`,left:e,right:t})}var pd=H(`ZodTuple`,(e,t)=>{Ys.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ql(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function md(e,t,n){let r=t instanceof ns;return new pd({type:`tuple`,items:e,rest:r?t:null,...U(r?n:t)})}var hd=H(`ZodRecord`,(e,t)=>{$s.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jl(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function gd(e,t,n){return!t||!t._zod?new hd({type:`record`,keyType:W(),valueType:e,...U(t)}):new hd({type:`record`,keyType:e,valueType:t,...U(n)})}var _d=H(`ZodEnum`,(e,t)=>{ec.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zl(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new _d({...t,checks:[],...U(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new _d({...t,checks:[],...U(r),entries:i})}});function Y(e,t){return new _d({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...U(t)})}var vd=H(`ZodLiteral`,(e,t)=>{tc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bl(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function X(e,t){return new vd({type:`literal`,values:Array.isArray(e)?e:[e],...U(t)})}var yd=H(`ZodTransform`,(e,t)=>{nc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hl(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new ea(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Ra(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Ra(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function bd(e){return new yd({type:`transform`,transform:e})}var xd=H(`ZodOptional`,(e,t)=>{ic.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Sd(e){return new xd({type:`optional`,innerType:e})}var Cd=H(`ZodExactOptional`,(e,t)=>{ac.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wd(e){return new Cd({type:`optional`,innerType:e})}var Td=H(`ZodNullable`,(e,t)=>{oc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ed(e){return new Td({type:`nullable`,innerType:e})}var Dd=H(`ZodDefault`,(e,t)=>{sc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Od(e,t){return new Dd({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ya(t)}})}var kd=H(`ZodPrefault`,(e,t)=>{lc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ql(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ad(e,t){return new kd({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ya(t)}})}var jd=H(`ZodNonOptional`,(e,t)=>{uc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Md(e,t){return new jd({type:`nonoptional`,innerType:e,...U(t)})}var Nd=H(`ZodCatch`,(e,t)=>{fc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$l(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Pd(e,t){return new Nd({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var Fd=H(`ZodPipe`,(e,t)=>{pc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>eu(e,t,n,r),e.in=t.in,e.out=t.out});function Id(e,t){return new Fd({type:`pipe`,in:e,out:t})}var Ld=H(`ZodReadonly`,(e,t)=>{hc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>tu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Rd(e){return new Ld({type:`readonly`,innerType:e})}var zd=H(`ZodCustom`,(e,t)=>{_c.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vl(e,t,n,r)});function Bd(e,t={}){return Cl(zd,e,t)}function Vd(e,t){return wl(e,t)}var Hd=e=>typeof e==`string`&&e.trim()?e.trim():null;function Ud(e){let t=e.decision_scope&&typeof e.decision_scope==`object`&&!Array.isArray(e.decision_scope)?e.decision_scope:{},n=Hd(t.kind),r=Hd(t.granularity),i=Hd(t.scope_key),a=Hd(e.superseded_by);return{interaction:e.task_class===`user_gate`?`decision`:`unknown`,lifecycle:a?`superseded`:e.status===`deferred`?`deferred`:e.done===!0||[`done`,`completed`,`closed`,`archived`].includes(String(e.status))?`closed`:e.status===`open`||e.status===`blocked`?`open`:`unknown`,reason:Hd(e.note),evidence:Hd(e.evidence),blocksAgent:Hd(e.blocks_agent),unblocksTodoId:Hd(e.unblocks_todo_id),decisionScope:n&&r&&i?{kind:n,granularity:r,scopeKey:i}:null,supersededBy:a}}function Wd(e,t,n,r){return{...e,sourceId:t,goalTitle:r??e.goalTitle,details:n?e.details:{...e.details??Ud({}),lifecycle:`unavailable`}}}function Gd(e,t){return t.find(t=>t.sourceId===e.sourceId&&t.goalId===e.goalId&&t.todoId===e.todoId)||{...e,details:{...e.details??Ud({}),lifecycle:`unavailable`}}}function Kd(e,t){let n=e.details?.supersededBy;if(!(!n||n===e.todoId||e.details?.lifecycle===`unavailable`))return t.find(t=>t.sourceId===e.sourceId&&t.goalId===e.goalId&&t.todoId===n)}function qd(e){return![`closed`,`deferred`,`superseded`,`unavailable`].includes(e.details?.lifecycle??`unknown`)}var Jd={ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,runtime_root:`$HOME/.codex/loopx`,goal_count:1,run_count:8440,status_contract:{schema_version:2,minimum_dashboard_schema_version:2,producer:`loopx status`,reload_hint:`scripts/macos-dashboard-launchagent.sh restart`},usage_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.471166+00:00`,sample_run_count:20,proxy_note:`run-history proxy; excludes token counts and raw thread logs`,totals:{runs_24h:20,runs_7d:20,quota_spend_slots_24h:11,quota_spend_slots_7d:11,automation_run_count_24h:11,automation_run_count_7d:11,progress_signal_run_count_24h:9,progress_signal_run_count_7d:9},goals:[{goal_id:`loopx-meta`,runs_24h:20,runs_7d:20,quota_spend_slots_24h:11,quota_spend_slots_7d:11,automation_run_count_24h:11,automation_run_count_7d:11,progress_signal_run_count_24h:9,progress_signal_run_count_7d:9,project_share_24h:1}]},event_ledger_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.360662+00:00`,sample_run_count:20,proxy_note:`append-only run-history projection; compact event-class counts only`,event_classes:[`accounting`,`decision`,`evidence`,`state`,`work`],totals:{events_24h:20,events_7d:20,by_class_24h:{accounting:11,decision:0,evidence:0,state:0,work:9},by_class_7d:{accounting:11,decision:0,evidence:0,state:0,work:9}},goals:[{goal_id:`loopx-meta`,events_24h:20,events_7d:20,by_class_24h:{accounting:11,decision:0,evidence:0,state:0,work:9},by_class_7d:{accounting:11,decision:0,evidence:0,state:0,work:9},latest_event_class:`accounting`,latest_event_at:`2026-07-06T14:37:32+08:00`}]},promotion_readiness_summary:{available:!0,source:`run_history_full_scan`,goal_id:`loopx-meta`,generated_at:`2026-07-05T20:02:02+08:00`,classification:`canary_promotion_readiness_smoke_group`,delivery_batch_scale:`multi_surface`,delivery_outcome:`primary_goal_outcome`,recommended_action:`Canary promotion-readiness smoke passed; promotion may proceed after doctor/status reports fresh evidence.`,json_exists:!0,markdown_exists:!0,freshness_window_hours:24,freshness_status:`fresh`,is_fresh:!0,requires_readiness_run:!1,age_seconds:67624,age_hours:18.78,freshness_reference_time:`2026-07-06T06:49:06.408527+00:00`,sample_run_count:0,proxy_note:`canary promotion-readiness projection from append-only run history; exact evidence stays in run artifacts`},promotion_gate:{ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,runtime_root:`$HOME/.codex/loopx`,gate:`promotion_readiness`,gate_state:`ready`,can_promote:!0,should_warn:!1,non_blocking:!0,recommended_action:`promotion readiness is fresh`,readiness:{available:!0,goal_id:`loopx-meta`,generated_at:`2026-07-05T20:02:02+08:00`,classification:`canary_promotion_readiness_smoke_group`,delivery_batch_scale:`multi_surface`,delivery_outcome:`primary_goal_outcome`,recommended_action:`Canary promotion-readiness smoke passed; promotion may proceed after doctor/status reports fresh evidence.`,json_exists:!0,markdown_exists:!0,runtime_root:`$HOME/.codex/loopx`,freshness_window_hours:24,freshness_status:`fresh`,is_fresh:!0,requires_readiness_run:!1,age_seconds:67624,age_hours:18.78,freshness_reference_time:`2026-07-06T06:49:06.471087+00:00`}},decision_freshness_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.471133+00:00`,sample_run_count:20,window_days:7,proxy_note:`checkpointed decision freshness projection; rebase old decisions at the decision point before reuse`,summary:{decision_count:0,stale_count:0,rebase_required_count:0,fresh_count:0},items:[]},todo_index:JSON.parse(`{"schema_version":"todo_index_v0","source":"live_loopx_status_public_slice","total_count":12,"current_projected_count":12,"rollout_event_count":94,"item_limit":12,"items":[{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo update recorded for todo_1596c3a678bb","schema_version":"todo_index_item_v0","todo_id":"todo_1596c3a678bb","role":"agent","status":"open","title":"todo update recorded for todo_1596c3a678bb","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:33:32Z","latest_event_status":"open","event_count":7,"event_kinds":["todo_update"]},{"goal_id":"loopx-meta","index":24,"done":false,"text":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","schema_version":"todo_index_item_v0","todo_id":"todo_15bc0926a494","role":"agent","status":"open","priority":"P0-REVENUE MONITOR","title":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"github_public_reply_metadata_monitor","claimed_by":"codex-value-explorer","evidence":"autonomous replan: bounded current value-explorer monitor lane with explicit expires_at.","note":"Set bounded watch expiry for metadata-only public reply monitor; no catch-up after expiry.","updated_at":"2026-07-05T06:27:15+08:00"},{"goal_id":"loopx-meta","index":17,"done":false,"text":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","schema_version":"todo_index_item_v0","todo_id":"todo_2bf560b48a0c","role":"agent","status":"open","priority":"P0","title":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"legacy_open_pr_rename_blocker","claimed_by":"codex-main-control"},{"goal_id":"loopx-meta","index":23,"done":false,"text":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","schema_version":"todo_index_item_v0","todo_id":"todo_3ed1c4a69164","role":"agent","status":"open","priority":"P0","title":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"skillsbench_local_verifier_reward_collection","claimed_by":"codex-main-control","required_capabilities":["benchmark_runner"]},{"goal_id":"loopx-meta","index":32,"done":false,"text":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","schema_version":"todo_index_item_v0","todo_id":"todo_44907a5f355d","role":"agent","status":"blocked","priority":"P0","title":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_raw_new_rerun","claimed_by":"codex-main-control","evidence":"Public-safe redacted live LoopX text; inspect local status for the full row.","note":"Do not spend a full citation-check loopx rerun yet: #865 fixed scored output paths and #874 added bootstrap preflight attribution, but citation-check itself still preflights as apt+verifier bootstrap risk on ECS.","updated_at":"2026-06-29T00:49:36+08:00"},{"goal_id":"loopx-meta","index":39,"done":false,"text":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","schema_version":"todo_index_item_v0","todo_id":"todo_4762c790e583","role":"agent","status":"blocked","priority":"P0","title":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_remote_rerun","claimed_by":"codex-main-control","evidence":"A prior benchmark adapter change was validated before the legacy surface was archived. Current research uses the RFC-linked benchmark workspace and toolkit boundary smokes.","note":"2026-06-29: fixed host-local ACP idle/no-output root cause in PR #894. ACP protocol tool_call_count=0 is now distinguished from reverse-channel task-facing bridge activity; repeated codex_exec_bridge_idle_timeout withou…","updated_at":"2026-06-29T19:40:32+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_584f55f8f3b4","schema_version":"todo_index_item_v0","todo_id":"todo_584f55f8f3b4","role":"agent","status":"open","title":"todo add recorded for todo_584f55f8f3b4","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:48:49Z","latest_event_status":"open","event_count":3,"event_kinds":["todo_add","todo_update"]},{"goal_id":"loopx-meta","index":40,"done":false,"text":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","schema_version":"todo_index_item_v0","todo_id":"todo_62debf065fec","role":"agent","status":"blocked","priority":"P0 MONITOR","title":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"monitor_skillsbench_batch","claimed_by":"codex-main-control","evidence":"Observed 2026-06-30T02:52+08: active-state target_key=skillsbench-goal-baseline-30case-20260629T1826Z-r10; local ps/tmux/recent artifact search found no r10 batch process or compact artifact; no raw task/log/trajectory …","updated_at":"2026-06-30T02:54:54+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_93bc6439c521","schema_version":"todo_index_item_v0","todo_id":"todo_93bc6439c521","role":"agent","status":"open","title":"todo add recorded for todo_93bc6439c521","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_claim","latest_event_at":"2026-07-06T06:32:52Z","latest_event_status":"open","event_count":2,"event_kinds":["todo_add","todo_claim"]},{"goal_id":"loopx-meta","index":27,"done":false,"text":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","schema_version":"todo_index_item_v0","todo_id":"todo_aad7e9716927","role":"agent","status":"blocked","priority":"P0","title":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"run_goal_start_product_mode_matrix","claimed_by":"codex-main-control","evidence":"driver.status shows DONE raw then RUN loopx-goal-start with no running driver; raw benchmark_run.compact first_blocker=skillsbench_codex_acp_provider_zero_activity; source guard requires --host-local-acp-launch for Loop…","note":"Remote run group skillsbench-raw-new-goal-start-20260627T0420Z produced a material closeout for citation-check raw only; raw compact attribution is skillsbench_codex_acp_provider_zero_activity with official score missin…","updated_at":"2026-06-27T13:05:47+08:00"},{"goal_id":"loopx-meta","index":21,"done":false,"text":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","schema_version":"todo_index_item_v0","todo_id":"todo_aec1873c7f28","role":"agent","status":"open","priority":"P0 MONITOR","title":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","claimed_by":"codex-main-control","note":"2026-06-23 projection fix: this is monitor context for the powerlifting run, not an advancement next action; current executable path is SkillsBench build cache/prewarm repair.","updated_at":"2026-06-23T10:37:43+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_c02cb7d19607","schema_version":"todo_index_item_v0","todo_id":"todo_c02cb7d19607","role":"agent","status":"open","title":"todo add recorded for todo_c02cb7d19607","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_add","latest_event_at":"2026-07-06T03:47:54Z","latest_event_status":"open","event_count":1,"event_kinds":["todo_add"]}]}`),agent_management_projection:{schema_version:`agent_management_projection_v0`,mode:`read_only`,goal_id:`loopx-meta`,generated_at:`2026-07-06T06:49:06Z`,style_hint:null,truth_contract:{todo_is_runtime_work_item:!0,projection_is_writable:!1,introduces_task_runtime:!1,write_api:!1},source_summary:{registered_agent_count:4,projected_agent_count:4,todo_source:`live_loopx_status_public_slice`,public_safe_export:!0},agents:[{agent_id:`codex-main-control`,agent_model:`peer_v1`,profile_role:`release-validation`,state:`blocked`,next_action:`Continue projected todo todo_2bf560b48a0c.`,last_activity_at:`2026-06-29T00:49:36+08:00`,evidence_refs:[`todo:todo_e72afc24f04a:evidence`],goal_ids:[`loopx-meta`],stale_claim_hint:{state:`activity_missing`,claimed_by:`codex-main-control`,reason:`claimed open todo has no projected activity timestamp`,recommended_operator_action:`inspect evidence before considering reassignment`},current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_2bf560b48a0c`,goal_id:`loopx-meta`,role:`agent`,status:`open`,priority:`P0`,title:`Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harn…`,task_class:`blocker`,action_kind:`legacy_open_pr_rename_blocker`,claimed_by:`codex-main-control`}},{agent_id:`codex-product-capability`,agent_model:`peer_v1`,profile_role:`product-validation`,state:`monitoring`,next_action:`Continue projected todo todo_ded745761822.`,last_activity_at:`2026-07-06T06:29:53Z`,evidence_refs:[`todo:todo_ded745761822:evidence`],goal_ids:[`loopx-meta`],current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_ded745761822`,goal_id:`loopx-meta`,role:`agent`,status:`open`,priority:`P0-LOCAL`,title:`Public-safe redacted live LoopX text; inspect local status for the full row.`,task_class:`continuous_monitor`,action_kind:`Public-safe redacted live LoopX text; inspect local status for the full row.`,claimed_by:`codex-product-capability`,updated_at:`2026-07-04T20:22:45+08:00`}},{agent_id:`codex-side-bypass`,agent_model:`peer_v1`,profile_role:`implementation-validation`,state:`waiting`,next_action:`Inspect status projection before taking work.`,last_activity_at:`2026-07-06T06:32:16Z`,evidence_refs:[`rollout_event:todo_complete:todo_22c946938115`],goal_ids:[`loopx-meta`]},{agent_id:`codex-value-explorer`,agent_model:`peer_v1`,profile_role:`value-exploration`,state:`monitoring`,next_action:`Continue projected todo todo_584f55f8f3b4.`,last_activity_at:`2026-07-06T09:39:59+08:00`,evidence_refs:[`rollout_event:todo_update:todo_584f55f8f3b4`],goal_ids:[`loopx-meta`],current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_584f55f8f3b4`,goal_id:`loopx-meta`,role:`agent`,status:`open`,title:`todo add recorded for todo_584f55f8f3b4`}}]},contract:{ok:!0,summary:{errors:0,warnings:1,checks:6},errors:[],warnings:["loopx-meta: duplicate index rows raw=8444 unique=8440 unexpected=3 artifact_identity_collisions=2 artifact_collision_rows=3 reward_overlays=1; inspect with `loopx history --goal-id loopx-meta inspect-index-duplicates`; artifact identity collisions need review…"],checks:[`registry goals checked: 12`,`registry boundary: shared_local_registry push_allowed=False tracked=False ignored=False`,`user-gate scopes checked: 6 open multi-agent gates`,`runtime root resolved: $HOME/.codex/loopx`,`run-history goals=28 runs=10210`,`public boundary scan clean: 1218 files`]},global_registry:{available:!0,ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,current_registry:`$HOME/.codex/loopx/registry.global.json`,current_registry_is_global:!0,global_goal_count:12,current_goal_count:12,source_registry_count:7,summary:{high:0,action:8,info:0,checks:2,findings:8},findings:[{kind:`source_registry_missing`,severity:`action`,message:"`cc-test` source registry is missing",recommended_action:"reconnect `cc-test` from its project or archive it if the project is obsolete",goal_id:`cc-test`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-test` active state file is missing",recommended_action:"repair `cc-test` state_file or reconnect the project",goal_id:`cc-test`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`cc-tmp` source registry is missing",recommended_action:"reconnect `cc-tmp` from its project or archive it if the project is obsolete",goal_id:`cc-tmp`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-tmp` active state file is missing",recommended_action:"repair `cc-tmp` state_file or reconnect the project",goal_id:`cc-tmp`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`cc-tmp-xdrchpuaul` source registry is missing",recommended_action:"reconnect `cc-tmp-xdrchpuaul` from its project or archive it if the project is obsolete",goal_id:`cc-tmp-xdrchpuaul`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-tmp-xdrchpuaul` active state file is missing",recommended_action:"repair `cc-tmp-xdrchpuaul` state_file or reconnect the project",goal_id:`cc-tmp-xdrchpuaul`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`loopx-auto-research-e2e-probe-20260628-2225-goal` source registry is missing",recommended_action:"reconnect `loopx-auto-research-e2e-probe-20260628-2225-goal` from its project or archive it if the project is obsolete",goal_id:`loopx-auto-research-e2e-probe-20260628-2225-goal`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`loopx-auto-research-e2e-probe-20260628-2225-goal` active state file is missing",recommended_action:"repair `loopx-auto-research-e2e-probe-20260628-2225-goal` state_file or reconnect the project",goal_id:`loopx-auto-research-e2e-probe-20260628-2225-goal`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`}],checks:[`global registry goals checked: 12`,`global source registries checked: 7`]},attention_queue:JSON.parse(`{"available":true,"item_count":1,"needs_user_or_controller":0,"needs_controller":0,"needs_codex":1,"watching_external_evidence":0,"items":[{"goal_id":"loopx-meta","status":"skillsbench_codex_cli_goal_tail4_keepalive_relaunched","lifecycle_phase":"adapter_inspected","lifecycle_flags":["adapter_inspected"],"waiting_on":"codex","severity":"action","recommended_action":"Monitor run_group skillsbench-codex-cli-goal-xhigh-tail4-keepalive-20260706T143132CST using public compact/public artifacts only; once benchmark_run.compact.json lands for each case, classify launcher/case/solver/verifi…","source":"latest_run","quota":{"compute":1.0,"window_hours":24,"slot_minutes":1,"allowed_slots":1440,"spent_slots":97,"state":"eligible","reason":"1 compute quota; eligible for the next automatic agent turn"},"agent_todos":{"source_section":"Agent Todo","total_count":12,"open_count":12,"done_count":0,"items":[{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo update recorded for todo_1596c3a678bb","schema_version":"todo_index_item_v0","todo_id":"todo_1596c3a678bb","role":"agent","status":"open","title":"todo update recorded for todo_1596c3a678bb","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:33:32Z","latest_event_status":"open","event_count":7,"event_kinds":["todo_update"]},{"goal_id":"loopx-meta","index":24,"done":false,"text":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","schema_version":"todo_index_item_v0","todo_id":"todo_15bc0926a494","role":"agent","status":"open","priority":"P0-REVENUE MONITOR","title":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"github_public_reply_metadata_monitor","claimed_by":"codex-value-explorer","evidence":"autonomous replan: bounded current value-explorer monitor lane with explicit expires_at.","note":"Set bounded watch expiry for metadata-only public reply monitor; no catch-up after expiry.","updated_at":"2026-07-05T06:27:15+08:00"},{"goal_id":"loopx-meta","index":17,"done":false,"text":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","schema_version":"todo_index_item_v0","todo_id":"todo_2bf560b48a0c","role":"agent","status":"open","priority":"P0","title":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"legacy_open_pr_rename_blocker","claimed_by":"codex-main-control"},{"goal_id":"loopx-meta","index":23,"done":false,"text":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","schema_version":"todo_index_item_v0","todo_id":"todo_3ed1c4a69164","role":"agent","status":"open","priority":"P0","title":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"skillsbench_local_verifier_reward_collection","claimed_by":"codex-main-control","required_capabilities":["benchmark_runner"]},{"goal_id":"loopx-meta","index":32,"done":false,"text":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","schema_version":"todo_index_item_v0","todo_id":"todo_44907a5f355d","role":"agent","status":"blocked","priority":"P0","title":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_raw_new_rerun","claimed_by":"codex-main-control","evidence":"Public-safe redacted live LoopX text; inspect local status for the full row.","note":"Do not spend a full citation-check loopx rerun yet: #865 fixed scored output paths and #874 added bootstrap preflight attribution, but citation-check itself still preflights as apt+verifier bootstrap risk on ECS.","updated_at":"2026-06-29T00:49:36+08:00"},{"goal_id":"loopx-meta","index":39,"done":false,"text":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","schema_version":"todo_index_item_v0","todo_id":"todo_4762c790e583","role":"agent","status":"blocked","priority":"P0","title":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_remote_rerun","claimed_by":"codex-main-control","evidence":"A prior benchmark adapter change was validated before the legacy surface was archived. Current research uses the RFC-linked benchmark workspace and toolkit boundary smokes.","note":"2026-06-29: fixed host-local ACP idle/no-output root cause in PR #894. ACP protocol tool_call_count=0 is now distinguished from reverse-channel task-facing bridge activity; repeated codex_exec_bridge_idle_timeout withou…","updated_at":"2026-06-29T19:40:32+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_584f55f8f3b4","schema_version":"todo_index_item_v0","todo_id":"todo_584f55f8f3b4","role":"agent","status":"open","title":"todo add recorded for todo_584f55f8f3b4","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:48:49Z","latest_event_status":"open","event_count":3,"event_kinds":["todo_add","todo_update"]},{"goal_id":"loopx-meta","index":40,"done":false,"text":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","schema_version":"todo_index_item_v0","todo_id":"todo_62debf065fec","role":"agent","status":"blocked","priority":"P0 MONITOR","title":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"monitor_skillsbench_batch","claimed_by":"codex-main-control","evidence":"Observed 2026-06-30T02:52+08: active-state target_key=skillsbench-goal-baseline-30case-20260629T1826Z-r10; local ps/tmux/recent artifact search found no r10 batch process or compact artifact; no raw task/log/trajectory …","updated_at":"2026-06-30T02:54:54+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_93bc6439c521","schema_version":"todo_index_item_v0","todo_id":"todo_93bc6439c521","role":"agent","status":"open","title":"todo add recorded for todo_93bc6439c521","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_claim","latest_event_at":"2026-07-06T06:32:52Z","latest_event_status":"open","event_count":2,"event_kinds":["todo_add","todo_claim"]},{"goal_id":"loopx-meta","index":27,"done":false,"text":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","schema_version":"todo_index_item_v0","todo_id":"todo_aad7e9716927","role":"agent","status":"blocked","priority":"P0","title":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"run_goal_start_product_mode_matrix","claimed_by":"codex-main-control","evidence":"driver.status shows DONE raw then RUN loopx-goal-start with no running driver; raw benchmark_run.compact first_blocker=skillsbench_codex_acp_provider_zero_activity; source guard requires --host-local-acp-launch for Loop…","note":"Remote run group skillsbench-raw-new-goal-start-20260627T0420Z produced a material closeout for citation-check raw only; raw compact attribution is skillsbench_codex_acp_provider_zero_activity with official score missin…","updated_at":"2026-06-27T13:05:47+08:00"},{"goal_id":"loopx-meta","index":21,"done":false,"text":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","schema_version":"todo_index_item_v0","todo_id":"todo_aec1873c7f28","role":"agent","status":"open","priority":"P0 MONITOR","title":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","claimed_by":"codex-main-control","note":"2026-06-23 projection fix: this is monitor context for the powerlifting run, not an advancement next action; current executable path is SkillsBench build cache/prewarm repair.","updated_at":"2026-06-23T10:37:43+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_c02cb7d19607","schema_version":"todo_index_item_v0","todo_id":"todo_c02cb7d19607","role":"agent","status":"open","title":"todo add recorded for todo_c02cb7d19607","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_add","latest_event_at":"2026-07-06T03:47:54Z","latest_event_status":"open","event_count":1,"event_kinds":["todo_add"]}]}}]}`),run_history:{available:!0,goal_count:1,run_count:5,goals:[{id:`loopx-meta`,domain:`loopx-platform`,status:`active-read-only`,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`],registry_member:!0,legacy_runtime_goal:!1,adapter_kind:`harness_self_improvement`,adapter_status:`connected-read-only`,index_exists:!0,raw_index_records:8444,unique_runs:8440,quota:{compute:1,window_hours:24,slot_minutes:1,allowed_slots:1440,spent_slots:97,state:`waiting`,reason:`no active Codex-ready work is currently selected`},latest_runs:[{generated_at:`2026-07-06T14:37:32+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-value-explorer`,recommended_action:`审阅 PR #1524 的 Agent Management 面板视觉方向:workspace hint 与 stale claim hint 是否符合预期;确认后允许 codex-value-explorer 自合并。`,health_check:`quota safe-bypass operator gate; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:55+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-main-control`,recommended_action:`[P1] Repair SkillsBench post-run debug gate consistency for countable codex-cli-goal official-zero runs: when attempt_accounting is countable and case_closeout_complete=true, do not project first_blocker=loopx_closeout_…`,health_check:`quota should-run eligible; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:54+08:00`,goal_id:`loopx-meta`,classification:`skillsbench_codex_cli_goal_tail4_keepalive_relaunched`,agent_id:`codex-main-control`,progress_scope:`goal`,delivery_batch_scale:`single_surface`,delivery_outcome:`outcome_progress`,recommended_action:`Monitor run_group skillsbench-codex-cli-goal-xhigh-tail4-keepalive-20260706T143132CST using public compact/public artifacts only; once benchmark_run.compact.json lands for each case, classify launcher/case/solver/verifi…`,health_check:`state_file 1/1; registry_goal 1/1; authority_sources 10`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:34+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-side-bypass`,recommended_action:`[P0] Rerun real KNN visible auto-research after the successor-link fix and verify evaluator completion projects a second-round hypothesis/frontier or explicit completion gate without manual intervention; keep evidence p…`,health_check:`quota should-run eligible; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:32:57+08:00`,goal_id:`loopx-meta`,classification:`auto_research_successor_link_fix_merged`,agent_id:`codex-side-bypass`,progress_scope:`agent_lane`,delivery_batch_scale:`implementation`,delivery_outcome:`outcome_progress`,recommended_action:`[P0] Rerun real KNN visible auto-research after the successor-link fix and verify evaluator completion projects a second-round hypothesis/frontier or explicit completion gate without manual intervention; keep evidence p…`,health_check:`state_file 1/1; registry_goal 1/1; authority_sources 0`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]}]}]}},Yd=W().nullable(),Xd=J({schema_version:X(`goal_acceptance_observation_projection_v0`),goal_id:W(),read_only:X(!0),acceptance_assessed:X(!1),coverage:Y([`partial`,`unavailable`]),missing_sources:q(W()),truncated:K(),historical_progress:q(J({kind:W(),observed_at:Yd,source:W(),evidence_refs:q(W())})),acceptance_gaps:q(J({kind:W(),owner:Yd,reason:Yd,evidence_required:Yd,observed_at:Yd,source:W()})),guards:q(J({kind:W(),todo_id:Yd,blocks_agent:Yd,owner:Yd,reason:Yd,evidence_required:Yd,decision_scope:Yd})),next_action:Yd,next_action_source:Yd}),Zd=ud([W(),G(),K(),nd()]),Qd=gd(W(),Zd),$d=J({todo_id:W().optional(),priority:W().optional(),status:W(),title:W(),claimed_by:W().optional(),task_class:W().optional(),action_kind:W().optional()}),ef=J({gate_id:W(),kind:W(),status:W(),blocks:q(W()).optional()}),tf=J({todo_id:W().optional(),owner_agent:W().optional(),status:W().optional(),lease_until:W().optional(),write_scope:q(W()).optional()}),nf=J({generated_at:W().optional(),classification:W().optional(),summary:W().optional()}),rf=J({kind:W().optional().default(`warning`),message:ud([W(),q(W())]).optional().default(`compact source warning`)}).passthrough(),af=J({schema_version:X(`goal_channel_projection_v0`),mode:X(`read_only`),goal_id:W(),display_name:W(),generated_at:W().optional().nullable(),latest_status:W(),waiting_on:W(),next_action:W(),source_refs:gd(W(),Zd),decision_frame:J({user_action_required:K(),agent_action_required:K(),quiet_noop_allowed:K()}),quota:Qd,user_todos:q($d).default([]),agent_todos:q($d).default([]),open_gates:q(ef).default([]),active_leases:q(tf).default([]),artifacts:q(Qd).default([]),recent_events:q(nf).default([]),source_warnings:q(rf).default([]),truth_contract:J({event_ledger_is_source_of_truth:K(),projection_is_writable:K(),recompute_rule:W(),write_authority:W()})}),of=J({compute:G().optional().default(1),window_hours:G().optional().default(24),slot_minutes:G().optional().default(1),allowed_slots:G().optional().nullable(),spent_slots:G().optional().default(0),state:W().optional().nullable(),next_eligible_at:W().optional().nullable(),reason:W().optional().nullable(),blocked_action_scope:W().optional().nullable(),focus_wait:K().optional().nullable(),handoff_outcome_floor_block:K().optional().nullable(),safe_bypass_allowed:K().optional().default(!1),safe_bypass_kind:W().optional().nullable(),safe_bypass_policy:W().optional().nullable(),post_handoff_outcome_gap_streak:G().optional().nullable(),outcome_gap_threshold:G().optional().nullable(),must_advance:q(W()).optional().default([]),avoid:q(W()).optional().default([])}).transform(e=>{let t=Math.max(1,e.slot_minutes),n=Math.round(e.window_hours*60*e.compute/t);return{...e,slot_minutes:t,allowed_slots:e.allowed_slots??n}}),sf=J({self_repair:J({enabled:K().optional().default(!1),allow_health_blocker_repair:K().optional().default(!1),allow_waiting_projection_repair:K().optional().default(!1)}).optional().nullable()}).passthrough(),cf=J({model_config:J({model:W(),reasoning_effort:W().optional()}).optional(),mode:W().optional().default(`default`),orchestration_mode:W().optional().nullable(),spawn_allowed:K().optional().default(!1),allowed:K().optional().nullable(),max_children:G().optional().default(0),allowed_domains:q(W()).optional().default([])}).passthrough(),lf=J({label:W().optional().nullable(),path:W(),anchor:W().optional().nullable(),exists:K().optional().default(!1),resolved_path:W().optional().nullable()}),uf=J({index:G(),done:K(),text:W(),schema_version:W().optional().nullable(),todo_id:W().optional().nullable(),role:W().optional().nullable(),status:W().optional().nullable(),resume_when:W().optional().nullable(),resume_ready:K().optional().nullable(),resume_condition:gd(W(),id()).optional().nullable(),priority:W().optional().nullable(),title:W().optional().nullable(),archive_state:W().optional().nullable(),source_section:W().optional().nullable(),task_class:W().optional().nullable(),task_domain:W().optional().nullable(),action_kind:W().optional().nullable(),claimed_by:W().optional().nullable(),required_capabilities:q(W()).optional(),note:W().optional().nullable(),evidence:W().optional().nullable(),updated_at:W().optional().nullable(),review_materials:q(lf).optional().default([])}).passthrough(),df=J({source_section:W().optional().nullable(),total_count:G().optional().default(0),open_count:G().optional().default(0),done_count:G().optional().default(0),advancement_done_count:G().optional(),items:q(uf).optional().default([]),deferred_items:q(uf).optional()}),ff=uf.extend({goal_id:W(),source:W().optional().nullable(),event_count:G().optional().default(0),event_kinds:q(W()).optional().default([]),latest_event_kind:W().optional().nullable(),latest_event_at:W().optional().nullable(),latest_event_status:W().optional().nullable(),agent_id:W().optional().nullable()}).passthrough(),pf=J({schema_version:W().optional().nullable(),source:W().optional().nullable(),total_count:G().optional().default(0),current_projected_count:G().optional().default(0),rollout_event_count:G().optional().default(0),item_limit:G().optional().nullable(),items:q(ff).optional().default([])}),mf=J({kind:W().optional().nullable(),label:W().optional().nullable(),path_safe:K().optional().default(!1),branch:W().optional().nullable(),write_scope:q(W()).optional().default([])}).passthrough(),hf=J({state:W().optional().nullable(),claimed_by:W().optional().nullable(),last_activity_at:W().optional().nullable(),threshold_hours:G().optional().nullable(),reason:W().optional().nullable(),recommended_operator_action:W().optional().nullable()}).passthrough(),gf=J({schema_version:W().optional().nullable(),todo_id:W().optional().nullable(),goal_id:W().optional().nullable(),role:W().optional().nullable(),status:W().optional().nullable(),priority:W().optional().nullable(),title:W().optional().nullable(),task_class:W().optional().nullable(),action_kind:W().optional().nullable(),claimed_by:W().optional().nullable(),required_write_scopes:q(W()).optional().default([]),workspace_ref:mf.optional().nullable()}).passthrough(),_f=J({schema_version:W().optional().nullable(),from_agent:W().optional().nullable(),to_agent:W().optional().nullable(),intent:W().optional().nullable(),summary:W().optional().nullable(),blocker:W().optional().nullable(),suggested_next_action:W().optional().nullable(),evidence_refs:q(W()).optional().default([]),updated_at:W().optional().nullable()}).passthrough(),vf=J({agent_id:W(),role:W().optional().nullable(),state:W().optional().nullable(),current_todo:gf.optional().nullable(),next_action:W().optional().nullable(),last_activity_at:W().optional().nullable(),evidence_refs:q(W()).optional().default([]),handoff_refs:q(W()).optional().default([]),handoff_note:_f.optional().nullable(),workspace_ref:mf.optional().nullable(),stale_claim_hint:hf.optional().nullable(),blocked_on:gf.optional().nullable(),goal_ids:q(W()).optional().default([])}).passthrough(),yf=J({schema_version:W().optional().nullable(),mode:W().optional().nullable(),goal_id:W().optional().nullable(),generated_at:W().optional().nullable(),style_hint:J({preferred:W().optional().nullable(),license_boundary:W().optional().nullable()}).optional().nullable(),truth_contract:J({todo_is_runtime_work_item:K().optional().default(!0),projection_is_writable:K().optional().default(!1),introduces_task_runtime:K().optional().default(!1),write_api:K().optional().default(!1)}).optional().nullable(),source_summary:J({registered_agent_count:G().optional().default(0),projected_agent_count:G().optional().default(0),todo_source:W().optional().nullable()}).optional().nullable(),agents:q(vf).optional().default([])}).passthrough(),bf=J({goal_id:W(),configured:K().optional().default(!1),enabled:K().optional().default(!1),human_gate_auto_notify_enabled:K().optional().default(!1),target_ref:W().optional().nullable(),receipt_count:G().optional().default(0),last_notified_at:W().optional().nullable()}).passthrough(),xf=J({schema_version:W().optional().nullable(),generated_at:W().optional().nullable(),goals:q(bf).optional().default([])}).passthrough(),Sf=J({source_section:W().optional().nullable(),open:G().optional().default(0),done:G().optional().default(0),total:G().optional().default(0),advancement_done_count:G().optional(),next:W().optional().nullable(),next_index:G().optional().nullable(),items:q(uf).optional().default([]),recent_completed_advancement_items:q(uf).optional().default([])}),Cf=J({goal_id:W(),status:W().optional().nullable(),waiting_on:W().optional().nullable(),severity:W().optional().nullable(),index:G().optional().nullable(),text:W(),source:W().optional().nullable()}),wf=J({source:W().optional().nullable(),open_count:G().optional().default(0),items:q(Cf).optional().default([])}),Tf=J({goal_id:W(),status:W().optional().nullable(),waiting_on:W().optional().nullable(),quota_state:W().optional().nullable(),priority:W().optional().nullable(),todo_index:G().optional().nullable(),text:W(),source:W().optional().nullable()}),Ef=J({source:W().optional().nullable(),open_count:G().optional().default(0),items:q(Tf).optional().default([])}),Df=J({generated_at:W().optional().nullable(),classification:W().optional().nullable(),summary:W().optional().nullable()}),Of=J({kind:W().optional().nullable(),source:W().optional().nullable(),severity:W().optional().nullable(),requires_refresh_state:K().optional().default(!1),reason:W().optional().nullable(),active_state_updated_at:W().optional().nullable(),latest_run_generated_at:W().optional().nullable(),latest_run_state_updated_at:W().optional().nullable(),latest_run_classification:W().optional().nullable(),recommended_action:W().optional().nullable()}),kf=J({generated_at:W().optional().nullable(),classification:W().optional().nullable(),delivery_batch_scale:W().optional().nullable(),delivery_outcome:W().optional().nullable(),health_check:W().optional().nullable(),json_exists:K().optional().nullable(),markdown_exists:K().optional().nullable()}),Af=J({project_asset_backed:K().optional(),same_source_should_run:K().optional(),codex_ready:K().optional(),handoff_has_next_action:K().optional(),handoff_has_stop_condition:K().optional(),handoff_sanitized_surface:K().optional()}).catchall(K()),jf=J({ready:K().optional().default(!1),codex_ready:K().optional().default(!1),source:W().optional().nullable(),quota_state:W().optional().nullable(),checks:Af.optional().default({}),handoff_status:W().optional().nullable(),handoff_ready_at:W().optional().nullable(),handoff_ready_classification:W().optional().nullable(),post_handoff_run_seen:K().optional().default(!1),post_handoff_latest_run:kf.optional().nullable(),post_handoff_recent_runs:q(kf).optional().default([]),post_handoff_small_scale_streak:G().int().nonnegative().optional().default(0),post_handoff_outcome_gap_streak:G().int().nonnegative().optional().default(0),next_probe:W().optional().nullable()}),Mf=J({schema_version:W().optional().nullable(),kind:W().optional().nullable(),missing_roles:q(W()).optional().default([]),source:W().optional().nullable(),recommended_action:W().optional().nullable()}),Nf=J({owner:W(),gate:W(),next_action:W(),stop_condition:W(),user_todos:Sf.optional().nullable(),agent_todos:Sf.optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),orchestration:cf.optional().nullable(),latest_validation:Df.optional().nullable(),stale_latest_run_warning:Of.optional().nullable(),todo_projection_gap:Mf.optional().nullable()}),Pf=J({goal_id:W(),activation_state:Y([`active`,`stopped`]).optional().default(`active`),status:W(),waiting_on:W(),severity:W(),recommended_action:W(),project_asset:Nf.optional().nullable(),handoff_readiness:jf.optional().nullable(),source:W().optional(),operator_question:W().optional().nullable(),agent_command:W().optional().nullable(),lifecycle_phase:W().optional().nullable(),lifecycle_flags:q(W()).optional().default([]),controller_stage:W().optional().nullable(),missing_gates:q(W()).optional().default([]),next_handoff_condition:W().optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),user_todos:df.optional().nullable(),agent_todos:df.optional().nullable(),stale_latest_run_warning:Of.optional().nullable(),dependency_blockers:wf.optional().nullable(),todo_state_file:W().optional().nullable(),goal_channel_projection:af.optional().nullable()}),Ff=J({recorded_at:W().optional().nullable(),decision:W().optional().nullable(),reward:W().optional().nullable(),reason_summary:W().optional().nullable(),follow_up:W().optional().nullable()}),If=J({recorded_at:W().optional().nullable(),gate:W().optional().nullable(),decision:W().optional().nullable(),operator_question:W().optional().nullable(),reason_summary:W().optional().nullable(),follow_up:W().optional().nullable(),agent_command:W().optional().nullable()}),Lf=J({version:W().optional().nullable(),goal_id:W().optional().nullable(),run_id:W().optional().nullable(),gate_id:W().optional().nullable(),created_state_ref:W().optional().nullable(),created_policy_version:W().optional().nullable(),interrupt_payload:J({question:W().optional().nullable(),choices:q(W()).optional().default([])}).optional().nullable(),allowed_decisions:q(W()).optional().default([]),operator_decision:W().optional().nullable(),latest_state_ref:W().optional().nullable(),freshness_check:W().optional().nullable(),precondition_check:W().optional().nullable(),migration_or_rebase_result:W().optional().nullable(),resulting_action:W().optional().nullable(),validation_after_resume:W().optional().nullable()}),Rf=J({id:W().optional().nullable(),ok:K().optional().nullable(),review:W().optional().nullable()}),zf=J({classification:W().optional().nullable(),read_only_observer_ready:K().optional().nullable(),decision_advisor_ready:K().optional().nullable(),write_controller_ready:K().optional().nullable(),missing_gates:q(W()).optional().default([]),review_judgment:W().optional().nullable(),next_handoff_condition:W().optional().nullable(),gates:q(Rf).optional().default([])}),Bf=J({declared:K().optional().default(!1),required:K().optional().default(!1),path:W().optional().nullable(),path_exists:K().optional().nullable(),read_status:W().optional().nullable(),default_entry_count:G().optional().default(0),default_entries_checked:G().optional().default(0),default_entries_present:G().optional().default(0),topic_authority_count:G().optional().default(0),project_material_count:G().optional().default(0),project_material_repository_count:G().optional().default(0),project_material_owner_review_required_count:G().optional().default(0),project_material_stale_count:G().optional().default(0),project_material_current_authority_count:G().optional().default(0),deprecated_source_count:G().optional().default(0),conflict_risk:W().optional().nullable()}),Vf=J({adapter_kind:W().optional().nullable(),adapter_status:W().optional().nullable(),authority_source_count:G().optional().nullable(),authority_registry_declared:K().optional().nullable(),authority_registry_path_exists:K().optional().nullable(),authority_registry_default_entry_count:G().optional().nullable(),authority_registry_default_entries_present:G().optional().nullable(),topic_authority_count:G().optional().nullable(),project_material_count:G().optional().nullable(),project_material_repository_count:G().optional().nullable(),project_material_owner_review_required_count:G().optional().nullable(),project_material_stale_count:G().optional().nullable(),project_material_current_authority_count:G().optional().nullable(),authority_registry_conflict_risk:W().optional().nullable(),guard_count:G().optional().nullable(),sections_found:G().optional().nullable(),sections_checked:G().optional().nullable(),files_present:G().optional().nullable(),files_checked:G().optional().nullable()}),Hf=J({generated_at:W(),goal_id:W(),classification:W().optional().nullable(),lifecycle_phase:W().optional().nullable(),lifecycle_flags:q(W()).optional().default([]),recommended_action:W().optional().nullable(),health_check:W().optional().nullable(),active_task_count:G().optional().nullable(),active_priorities:gd(W(),id()).optional().nullable(),cache_check:W().optional().nullable(),json_exists:K().optional().default(!1),markdown_exists:K().optional().default(!1),human_reward:Ff.optional().nullable(),operator_gate:If.optional().nullable(),operator_gate_resume_contract:Lf.optional().nullable(),controller_readiness:zf.optional().nullable(),project_map:Vf.optional().nullable()}),Uf=J({acceptance_observation:Xd.optional().nullable().catch(null),id:W(),activation_state:Y([`active`,`stopped`]).optional().default(`active`),display_name:W().optional().nullable(),domain:W().optional().nullable(),status:W().optional().nullable(),lifecycle_phase:W().optional().nullable(),lifecycle_flags:q(W()).optional().default([]),registry_member:K().optional().default(!1),legacy_runtime_goal:K().optional().default(!1),adapter_kind:W().optional().nullable(),adapter_status:W().optional().nullable(),authority_registry:Bf.optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),spawn_policy:cf.optional().nullable(),orchestration:cf.optional().nullable(),coordination:J({agent_model:W().optional().nullable(),registered_agents:q(W()).optional().default([])}).optional().nullable(),index_exists:K().optional().default(!1),raw_index_records:G().optional().default(0),unique_runs:G().optional().default(0),latest_runs:q(Hf).optional().default([])}),Wf=J({available:K(),goal_count:G().optional().default(0),run_count:G().optional().default(0),goals:q(Uf).optional().default([]),recent_runs:q(Hf).optional().default([])}),Gf=J({kind:W(),severity:W(),message:W(),recommended_action:W(),goal_id:W().optional().nullable(),path:W().optional().nullable(),goal_ids:q(W()).optional().default([])}),Kf=J({available:K(),ok:K(),registry:W(),current_registry:W().optional().nullable(),current_registry_is_global:K().optional().default(!1),global_goal_count:G().optional().default(0),current_goal_count:G().optional().default(0),source_registry_count:G().optional().default(0),summary:J({high:G().optional().default(0),action:G().optional().default(0),info:G().optional().default(0),checks:G().optional().default(0),findings:G().optional().default(0)}),findings:q(Gf).optional().default([]),checks:q(W()).optional().default([])}),qf=J({runs_24h:G().optional().default(0),runs_7d:G().optional().default(0),quota_spend_slots_24h:G().optional().default(0),quota_spend_slots_7d:G().optional().default(0),automation_run_count_24h:G().optional().default(0),automation_run_count_7d:G().optional().default(0),progress_signal_run_count_24h:G().optional().default(0),progress_signal_run_count_7d:G().optional().default(0),input_tokens_24h:G().optional(),input_tokens_7d:G().optional(),output_tokens_24h:G().optional(),output_tokens_7d:G().optional(),cache_tokens_24h:G().optional(),cache_tokens_7d:G().optional(),cost_usd_24h:G().optional(),cost_usd_7d:G().optional(),duration_ms_24h:G().optional(),duration_ms_7d:G().optional()}),Jf=qf.extend({goal_id:W(),project_share_24h:G().optional().default(0)}),Yf=J({available:K().optional().default(!0),source:W().optional().default(`run_history`),generated_at:W().optional().nullable(),sample_run_count:G().optional().default(0),proxy_note:W().optional().nullable(),totals:qf.optional().default({runs_24h:0,runs_7d:0,quota_spend_slots_24h:0,quota_spend_slots_7d:0,automation_run_count_24h:0,automation_run_count_7d:0,progress_signal_run_count_24h:0,progress_signal_run_count_7d:0}),goals:q(Jf).optional().default([])}).optional().nullable(),Xf=J({accounting:G().optional().default(0),decision:G().optional().default(0),evidence:G().optional().default(0),state:G().optional().default(0),work:G().optional().default(0)}),Zf={accounting:0,decision:0,evidence:0,state:0,work:0},Qf=J({events_24h:G().optional().default(0),events_7d:G().optional().default(0),by_class_24h:Xf.optional().default(Zf),by_class_7d:Xf.optional().default(Zf)}),$f=Qf.extend({goal_id:W(),latest_event_class:W().optional().nullable(),latest_event_at:W().optional().nullable()}),ep={events_24h:0,events_7d:0,by_class_24h:Zf,by_class_7d:Zf},tp=J({available:K().optional().default(!0),source:W().optional().default(`run_history`),generated_at:W().optional().nullable(),sample_run_count:G().optional().default(0),proxy_note:W().optional().nullable(),event_classes:q(W()).optional().default([`accounting`,`decision`,`evidence`,`state`,`work`]),totals:Qf.optional().default(ep),goals:q($f).optional().default([])}).optional().nullable(),np=J({available:K().optional().default(!1),source:W().optional().default(`run_history`),goal_id:W().optional().nullable(),generated_at:W().optional().nullable(),classification:W().optional().nullable(),delivery_batch_scale:W().optional().nullable(),delivery_outcome:W().optional().nullable(),recommended_action:W().optional().nullable(),json_exists:K().optional().default(!1),markdown_exists:K().optional().default(!1),freshness_window_hours:G().optional().default(24),freshness_status:W().optional().nullable(),is_fresh:K().optional().default(!1),requires_readiness_run:K().optional().default(!0),age_seconds:G().optional().nullable(),age_hours:G().optional().nullable(),freshness_reference_time:W().optional().nullable(),sample_run_count:G().optional().default(0),proxy_note:W().optional().nullable(),reason:W().optional().nullable()}).optional().nullable(),rp=J({ok:K().optional().default(!0),registry:W().optional().nullable(),runtime_root:W().optional().nullable(),gate:W().optional().default(`promotion_readiness`),gate_state:W().optional().default(`warning`),can_promote:K().optional().default(!1),should_warn:K().optional().default(!0),non_blocking:K().optional().default(!0),recommended_action:W().optional().nullable(),warning_message:W().optional().nullable(),readiness:np.default(null)}).optional().nullable(),ip=J({decision_count:G().optional().default(0),stale_count:G().optional().default(0),rebase_required_count:G().optional().default(0),fresh_count:G().optional().default(0)}),ap=J({goal_id:W(),decision_kind:W().optional().nullable(),decision_at:W().optional().nullable(),classification:W().optional().nullable(),age_days:G().optional().nullable(),stale_by_age:K().optional().default(!1),newer_event_count_7d:G().optional().default(0),newer_event_classes_7d:Xf.optional().default(Zf),freshness_state:W().optional().nullable(),requires_decision_point_rebase:K().optional().default(!1),reason:W().optional().nullable()}),op=J({available:K().optional().default(!0),source:W().optional().default(`run_history`),generated_at:W().optional().nullable(),sample_run_count:G().optional().default(0),window_days:G().optional().default(7),proxy_note:W().optional().nullable(),summary:ip.optional().default({decision_count:0,stale_count:0,rebase_required_count:0,fresh_count:0}),items:q(ap).optional().default([])}).optional().nullable(),sp=J({schema_version:G().optional().default(0),minimum_dashboard_schema_version:G().optional().default(2),producer:W().optional().nullable(),reload_hint:W().optional().nullable()}).optional().default({schema_version:0,minimum_dashboard_schema_version:2,producer:null,reload_hint:`scripts/macos-dashboard-launchagent.sh restart`}),cp=J({schema_version:X(`loopx_goal_projection_scope_v0`),scope:Y([`all`,`active`,`stopped`]),complete:K(),projected_goal_count:G().int().nonnegative(),registry_goal_count:G().int().nonnegative(),registry_revision:W().optional().nullable()}),lp=J({source:W().optional().default(`serve-status`),status_url:W().optional().nullable(),health_url:W().optional().nullable(),review_material_url:W().optional().nullable(),presentation_surfaces_url:W().optional().nullable(),presentation_detail_url:W().optional().nullable(),periodic_report_index_url:W().optional().nullable(),periodic_report_detail_url:W().optional().nullable(),ssh_hosts_url:W().optional().nullable(),reward_dry_run_url:W().optional().nullable(),reward_append_url:W().optional().nullable(),reward_write_enabled:K().optional().default(!1),configure_goal_dry_run_url:W().optional().nullable(),configure_goal_apply_url:W().optional().nullable(),control_plane_write_enabled:K().optional().default(!1)}).optional().nullable(),up=J({extension_id:W().min(1),surface_id:W().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/),extension_revision:W().min(1),payload_sha256:W().regex(/^[0-9a-f]{64}$/)}).strict(),dp=J({extension_id:W().min(1),extension_revision:W().min(1),surface_id:W().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/),surface_kind:W().regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/),title:W().min(1),view_schema:W().regex(/^[a-z][a-z0-9_]*_v\d+$/),visibility:Y([`public-safe`,`owner-only`]),goal_id:W().min(1).nullable(),generated_at:W().min(1).nullable(),review_due_at:W().min(1).nullable(),diagnostic:W().min(1).nullable(),empty_state_title:W().min(1),empty_state_detail:W().min(1)}),fp=ud([dp.extend({state:Y([`ready`,`review_due`]),goal_id:W().min(1),generated_at:W().min(1),detail_ref:up}).strict(),dp.extend({state:X(`empty`),detail_ref:od().optional()}).strict(),dp.extend({state:X(`invalid`),diagnostic:W().min(1),detail_ref:od().optional()}).strict()]),pp=J({schema_version:X(`extension_presentation_surfaces_v0`),count:G().int().nonnegative(),ready_count:G().int().nonnegative(),review_due_count:G().int().nonnegative(),empty_count:G().int().nonnegative(),invalid_count:G().int().nonnegative(),items:q(fp)}).strict(),mp={schema_version:`extension_presentation_surfaces_v0`,count:0,ready_count:0,review_due_count:0,empty_count:0,invalid_count:0,items:[]};J({ok:X(!0),presentation_surfaces:pp}).strict();var hp=J({goal_id:W().min(1),agent_id:W().min(1),generation_id:W().min(1),content_sha256:W().regex(/^sha256:[0-9a-f]{64}$/)}).strict(),gp=J({goal_id:W().min(1),agent_id:W().min(1),generation_id:W().min(1),publication_id:W().min(1),delivered_at:W().min(1),predecessor_publication_id:W().min(1).nullable().optional(),detail_ref:hp}).strict(),_p=J({schema_version:X(`periodic_report_workspace_index_v0`),count:G().int().nonnegative(),items:q(gp)}),vp=_p.extend({returned_count:G().int().nonnegative(),total_count:G().int().nonnegative(),limit:G().int().nonnegative(),offset:G().int().nonnegative(),truncated:K()}).strict(),yp=_p.strict().transform(e=>({...e,returned_count:e.count,total_count:e.count,limit:e.count,offset:0,truncated:!1})),bp=J({ok:X(!0),periodic_reports:ud([vp,yp])}).strict(),xp=J({schema_version:X(`periodic_report_workspace_projection_v0`),goal_id:W().min(1),agent_id:W().min(1),generation_id:W().min(1),generated_at:W().min(1),title:W().min(1),summary:W().min(1),content_sha256:W().regex(/^sha256:[0-9a-f]{64}$/),period_window:J({start_at:W().min(1),end_at:W().min(1)}).strict(),interaction:J({attention_kind:X(`progress`),interaction:X(`inform`),delivery:X(`surface`),form:X(`milestone_report`),writable:X(!1)}).strict(),delta:J({added_count:G().int().nonnegative(),changed_count:G().int().nonnegative(),item_count:G().int().positive(),items:q(J({fact_id:W().min(1),source_ref:W().min(1),title:W().min(1),summary:W().min(1),status:W().min(1),content_kind:W().min(1),change_kind:Y([`added`,`changed`]),previous_status:W().min(1).optional()}).strict())}).strict(),publication:J({publication_id:W().min(1),delivered_at:W().min(1),predecessor_publication_id:W().min(1).nullable().optional(),cursor_id:W().min(1)}).strict(),truth_contract:J({published_cursor_is_source_of_truth:X(!0),generation_receipt_is_delivery_receipt:X(!1),projection_is_writable:X(!1),browser_write_api:X(!1)}).strict()}).strict(),Sp=J({ok:X(!0),projection:xp}).strict(),Cp=J({ok:K(),registry:W(),runtime_root:W(),goal_count:G(),run_count:G(),status_contract:sp,goal_projection:cp.optional().nullable().default(null),local_dashboard_api:lp,contract:J({ok:K(),summary:J({errors:G(),warnings:G(),checks:G()}),errors:q(W()),warnings:q(W()),checks:q(W()).optional().default([])}),global_registry:Kf.optional().default({available:!1,ok:!0,registry:``,current_registry:null,current_registry_is_global:!1,global_goal_count:0,current_goal_count:0,source_registry_count:0,summary:{high:0,action:0,info:0,checks:0,findings:0},findings:[],checks:[]}),attention_queue:J({available:K(),item_count:G(),needs_user_or_controller:G(),needs_controller:G().optional().default(0),needs_codex:G(),watching_external_evidence:G(),autonomous_backlog_candidates:Ef.optional().nullable(),items:q(Pf)}),run_history:Wf.optional().default({available:!1,goal_count:0,run_count:0,goals:[],recent_runs:[]}),event_ledger_summary:tp.default(null),promotion_readiness_summary:np.default(null),promotion_gate:rp.default(null),decision_freshness_summary:op.default(null),usage_summary:Yf.default(null),todo_index:pf.optional().nullable().default(null),agent_management_projection:yf.optional().nullable().default(null),goal_channel_notification_projection:xf.optional().nullable().default(null),presentation_surfaces:pp.optional().default(mp)});J({ok:K(),dry_run:K().optional().default(!0),appended:K().optional().default(!1),goal_id:W().optional().nullable(),raw_index_records_before:G().optional().nullable(),preview_id:W().optional().nullable(),selected_run:J({generated_at:W().optional().nullable(),classification:W().optional().nullable(),recommended_action:W().optional().nullable(),json_exists:K().optional().nullable(),markdown_exists:K().optional().nullable()}).optional().nullable(),human_reward:Ff.optional().nullable(),active_state_summary:W().optional().nullable(),project_agent_visibility:J({source_of_truth:W().optional().nullable(),history_command:W().optional().nullable(),active_state_role:W().optional().nullable(),review_packet_role:W().optional().nullable()}).optional().nullable(),error:W().optional().nullable()});function wp(e,t,n){let r=e.run_history.goals.map(e=>e.id===t&&e.activation_state!==n?{...e,activation_state:n}:e),i=e.attention_queue.items.map(e=>e.goal_id===t&&e.activation_state!==n?{...e,activation_state:n}:e),a=r.some((t,n)=>t!==e.run_history.goals[n]),o=i.some((t,n)=>t!==e.attention_queue.items[n]);return!a&&!o?e:{...e,attention_queue:o?{...e.attention_queue,items:i}:e.attention_queue,run_history:a?{...e.run_history,goals:r}:e.run_history}}function Tp(e,t){let n=e.run_history.goals.filter(e=>e.id!==t),r=e.attention_queue.items.filter(e=>e.goal_id!==t);return n.length===e.run_history.goals.length&&r.length===e.attention_queue.items.length?e:{...e,attention_queue:{...e.attention_queue,items:r},run_history:{...e.run_history,goals:n}}}function Ep(e){return Cp.parse(e)}function Dp(e){return e instanceof fu?e.issues.map(e=>`${e.path.join(`.`)||`root`}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}var Op=Ep(Jd),kp=J({ok:X(!0),schema_version:X(`loopx_workspace_directory_v1`),registry_revision:W(),goals:q(J({id:W(),display_name:W(),activation_state:Y([`active`,`stopped`]),registry_member:X(!0)}))});function Ap(e,t,n){let r=new URL(e,n);r.searchParams.delete(`goal_activation`),r.searchParams.delete(`goal_id`),r.searchParams.delete(`view`);for(let[e,n]of Object.entries(t))r.searchParams.set(e,n);return r.toString()}async function jp(e,t){let n=await fetch(Ap(e,{view:`workspace-directory`},t),{cache:`no-store`,signal:AbortSignal.timeout(5e3)});if(!n.ok)return null;let r=kp.safeParse(await n.json());return r.success?r.data:null}function Mp(e){return Ep({ok:!0,registry:``,runtime_root:``,goal_count:e.goals.length,run_count:0,local_dashboard_api:{},contract:{ok:!0,summary:{errors:0,warnings:0,checks:0},errors:[],warnings:[]},attention_queue:{available:!1,item_count:0,needs_user_or_controller:0,needs_codex:0,watching_external_evidence:0,items:[]},run_history:{available:!1,goal_count:e.goals.length,run_count:0,goals:e.goals,recent_runs:[]}})}async function Np(e,t,n,r,i,a,o){let s=[...n.goals],c=new Map;async function l(){for(;s.length&&i()&&!o?.aborted;){let l=s.findIndex(e=>e.id===a()),u=l>=0?l:s.findIndex(e=>e.activation_state===`active`);if(u<0)return;let d=s.splice(u,1)[0],f=(c.get(d.id)??0)+1;c.set(d.id,f);let p=new AbortController,m=!1,h=()=>p.abort();o?.addEventListener(`abort`,h,{once:!0});let g=setTimeout(()=>{m=!0,p.abort()},3e4),_=null;try{let a=await fetch(Ap(e,{goal_id:d.id},t),{cache:`no-store`,signal:p.signal});if(!a.ok)_=a.status===409?`revision`:a.status>=500?`service`:`scope`;else{let e=await a.json();if(e.workspace_registry_revision!==n.registry_revision)_=`revision`;else{let t=Ep(e);!t.run_history.goals.some(e=>e.id===d.id)||t.run_history.goals.some(e=>e.id!==d.id)?_=`scope`:i()&&!o?.aborted&&r(d.id,t,null)}}}catch(e){_=m?`timeout`:e instanceof TypeError?`network`:`invalid`}finally{clearTimeout(g),o?.removeEventListener(`abort`,h)}if(!i()||o?.aborted)return;_&&[`timeout`,`network`,`service`].includes(_)&&f<3?(await new Promise(e=>setTimeout(e,f*1e3)),s.push(d)):_&&r(d.id,null,_)}}await Promise.all([l(),l()])}var Pp=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),Fp=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),Ip=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),Lp=e=>{let t=Ip(e);return t.charAt(0).toUpperCase()+t.slice(1)},Rp={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`},zp=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},Bp=(0,z.createContext)({}),Vp=()=>(0,z.useContext)(Bp),Hp=(0,z.forwardRef)(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>{let{size:l=24,strokeWidth:u=2,absoluteStrokeWidth:d=!1,color:f=`currentColor`,className:p=``}=Vp()??{},m=r??d?Number(n??u)*24/Number(t??l):n??u;return(0,z.createElement)(`svg`,{ref:c,...Rp,width:t??l??Rp.width,height:t??l??Rp.height,stroke:e??f,strokeWidth:m,className:Pp(`lucide`,p,i),...!a&&!zp(s)&&{"aria-hidden":`true`},...s},[...o.map(([e,t])=>(0,z.createElement)(e,t)),...Array.isArray(a)?a:[a]])}),Z=(e,t)=>{let n=(0,z.forwardRef)(({className:n,...r},i)=>(0,z.createElement)(Hp,{ref:i,iconNode:t,className:Pp(`lucide-${Fp(Lp(e))}`,`lucide-${e}`,n),...r}));return n.displayName=Lp(e),n},Up=Z(`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`}]]),Wp=Z(`arrow-down`,[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]),Gp=Z(`arrow-left`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]),Kp=Z(`arrow-right`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]),qp=Z(`arrow-up-down`,[[`path`,{d:`m21 16-4 4-4-4`,key:`f6ql7i`}],[`path`,{d:`M17 20V4`,key:`1ejh1v`}],[`path`,{d:`m3 8 4-4 4 4`,key:`11wl7u`}],[`path`,{d:`M7 4v16`,key:`1glfcx`}]]),Jp=Z(`arrow-up`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),Yp=Z(`badge-check`,[[`path`,{d:`M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z`,key:`3c2336`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),Xp=Z(`bell`,[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}]]),Zp=Z(`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`}]]),Qp=Z(`braces`,[[`path`,{d:`M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1`,key:`ezmyqa`}],[`path`,{d:`M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1`,key:`e1hn23`}]]),$p=Z(`calendar-clock`,[[`path`,{d:`M16 14v2.2l1.6 1`,key:`fo4ql5`}],[`path`,{d:`M16 2v4`,key:`4m81vk`}],[`path`,{d:`M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5`,key:`1osxxc`}],[`path`,{d:`M3 10h5`,key:`r794hk`}],[`path`,{d:`M8 2v4`,key:`1cmpym`}],[`circle`,{cx:`16`,cy:`16`,r:`6`,key:`qoo3c4`}]]),em=Z(`check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),tm=Z(`chevron-down`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),nm=Z(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),rm=Z(`chevron-up`,[[`path`,{d:`m18 15-6-6-6 6`,key:`153udz`}]]),im=Z(`circle-alert`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`12`,x2:`12`,y1:`8`,y2:`12`,key:`1pkeuh`}],[`line`,{x1:`12`,x2:`12.01`,y1:`16`,y2:`16`,key:`4dfq90`}]]),am=Z(`circle-check`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),om=Z(`clipboard-check`,[[`rect`,{width:`8`,height:`4`,x:`8`,y:`2`,rx:`1`,ry:`1`,key:`tgr4d6`}],[`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`,key:`116196`}],[`path`,{d:`m9 14 2 2 4-4`,key:`df797q`}]]),sm=Z(`code-xml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),cm=Z(`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`}]]),lm=Z(`database`,[[`ellipse`,{cx:`12`,cy:`5`,rx:`9`,ry:`3`,key:`msslwz`}],[`path`,{d:`M3 5V19A9 3 0 0 0 21 19V5`,key:`1wlel7`}],[`path`,{d:`M3 12A9 3 0 0 0 21 12`,key:`mv7ke4`}]]),um=Z(`download`,[[`path`,{d:`M12 15V3`,key:`m9g1x1`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`path`,{d:`m7 10 5 5 5-5`,key:`brsn70`}]]),dm=Z(`ellipsis`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]]),fm=Z(`external-link`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),pm=Z(`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`}]]),mm=Z(`file-braces`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1`,key:`1oajmo`}],[`path`,{d:`M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1`,key:`mpwhp6`}]]),hm=Z(`file-check-corner`,[[`path`,{d:`M10.5 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v6`,key:`g5mvt7`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`m14 20 2 2 4-4`,key:`15kota`}]]),gm=Z(`file-text`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),_m=Z(`git-branch`,[[`path`,{d:`M15 6a9 9 0 0 0-9 9V3`,key:`1cii5b`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}]]),vm=Z(`git-compare-arrows`,[[`circle`,{cx:`5`,cy:`6`,r:`3`,key:`1qnov2`}],[`path`,{d:`M12 6h5a2 2 0 0 1 2 2v7`,key:`1yj91y`}],[`path`,{d:`m15 9-3-3 3-3`,key:`1lwv8l`}],[`circle`,{cx:`19`,cy:`18`,r:`3`,key:`1qljk2`}],[`path`,{d:`M12 18H7a2 2 0 0 1-2-2V9`,key:`16sdep`}],[`path`,{d:`m9 15 3 3-3 3`,key:`1m3kbl`}]]),ym=Z(`info`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]),bm=Z(`languages`,[[`path`,{d:`m5 8 6 6`,key:`1wu5hv`}],[`path`,{d:`m4 14 6-6 2-3`,key:`1k1g8d`}],[`path`,{d:`M2 5h12`,key:`or177f`}],[`path`,{d:`M7 2h1`,key:`1t2jsx`}],[`path`,{d:`m22 22-5-10-5 10`,key:`don7ne`}],[`path`,{d:`M14 18h6`,key:`1m8k6r`}]]),xm=Z(`layout-dashboard`,[[`rect`,{width:`7`,height:`9`,x:`3`,y:`3`,rx:`1`,key:`10lvy0`}],[`rect`,{width:`7`,height:`5`,x:`14`,y:`3`,rx:`1`,key:`16une8`}],[`rect`,{width:`7`,height:`9`,x:`14`,y:`12`,rx:`1`,key:`1hutg5`}],[`rect`,{width:`7`,height:`5`,x:`3`,y:`16`,rx:`1`,key:`ldoo1y`}]]),Sm=Z(`list-plus`,[[`path`,{d:`M16 5H3`,key:`m91uny`}],[`path`,{d:`M11 12H3`,key:`51ecnj`}],[`path`,{d:`M16 19H3`,key:`zzsher`}],[`path`,{d:`M18 9v6`,key:`1twb98`}],[`path`,{d:`M21 12h-6`,key:`bt1uis`}]]),Cm=Z(`loader-circle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),wm=Z(`maximize-2`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`m21 3-7 7`,key:`1l2asr`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M9 21H3v-6`,key:`wtvkvv`}]]),Tm=Z(`menu`,[[`path`,{d:`M4 5h16`,key:`1tepv9`}],[`path`,{d:`M4 12h16`,key:`1lakjw`}],[`path`,{d:`M4 19h16`,key:`1djgab`}]]),Em=Z(`message-circle-question-mark`,[[`path`,{d:`M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719`,key:`1sd12s`}],[`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`,key:`1u773s`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),Dm=Z(`message-square-text`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}],[`path`,{d:`M7 11h10`,key:`1twpyw`}],[`path`,{d:`M7 15h6`,key:`d9of3u`}],[`path`,{d:`M7 7h8`,key:`af5zfr`}]]),Om=Z(`minimize-2`,[[`path`,{d:`m14 10 7-7`,key:`oa77jy`}],[`path`,{d:`M20 10h-6V4`,key:`mjg0md`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M4 14h6v6`,key:`rmj7iw`}]]),km=Z(`moon`,[[`path`,{d:`M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401`,key:`kfwtm`}]]),Am=Z(`palette`,[[`path`,{d:`M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z`,key:`e79jfc`}],[`circle`,{cx:`13.5`,cy:`6.5`,r:`.5`,fill:`currentColor`,key:`1okk4w`}],[`circle`,{cx:`17.5`,cy:`10.5`,r:`.5`,fill:`currentColor`,key:`f64h9f`}],[`circle`,{cx:`6.5`,cy:`12.5`,r:`.5`,fill:`currentColor`,key:`qy21gx`}],[`circle`,{cx:`8.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`fotxhn`}]]),jm=Z(`paperclip`,[[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551`,key:`1miecu`}]]),Mm=Z(`pause`,[[`rect`,{x:`14`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`kaeet6`}],[`rect`,{x:`5`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`1wsw3u`}]]),Nm=Z(`play`,[[`path`,{d:`M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z`,key:`10ikf1`}]]),Pm=Z(`plus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]),Fm=Z(`radio`,[[`path`,{d:`M16.247 7.761a6 6 0 0 1 0 8.478`,key:`1fwjs5`}],[`path`,{d:`M19.075 4.933a10 10 0 0 1 0 14.134`,key:`ehdyv1`}],[`path`,{d:`M4.925 19.067a10 10 0 0 1 0-14.134`,key:`1q22gi`}],[`path`,{d:`M7.753 16.239a6 6 0 0 1 0-8.478`,key:`r2q7qm`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}]]),Im=Z(`refresh-cw`,[[`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,key:`v9h5vc`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}],[`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,key:`3uifl3`}],[`path`,{d:`M8 16H3v5`,key:`1cv678`}]]),Lm=Z(`rotate-ccw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),Rm=Z(`rotate-cw`,[[`path`,{d:`M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8`,key:`1p45f6`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}]]),zm=Z(`search`,[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]),Bm=Z(`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`}]]),Vm=Z(`server-cog`,[[`path`,{d:`m10.852 14.772-.383.923`,key:`11vil6`}],[`path`,{d:`M13.148 14.772a3 3 0 1 0-2.296-5.544l-.383-.923`,key:`1v3clb`}],[`path`,{d:`m13.148 9.228.383-.923`,key:`t2zzyc`}],[`path`,{d:`m13.53 15.696-.382-.924a3 3 0 1 1-2.296-5.544`,key:`1bxfiv`}],[`path`,{d:`m14.772 10.852.923-.383`,key:`k9m8cz`}],[`path`,{d:`m14.772 13.148.923.383`,key:`1xvhww`}],[`path`,{d:`M4.5 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-.5`,key:`tn8das`}],[`path`,{d:`M4.5 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-.5`,key:`1g2pve`}],[`path`,{d:`M6 18h.01`,key:`uhywen`}],[`path`,{d:`M6 6h.01`,key:`1utrut`}],[`path`,{d:`m9.228 10.852-.923-.383`,key:`1wtb30`}],[`path`,{d:`m9.228 13.148-.923.383`,key:`1a830x`}]]),Hm=Z(`server`,[[`rect`,{width:`20`,height:`8`,x:`2`,y:`2`,rx:`2`,ry:`2`,key:`ngkwjq`}],[`rect`,{width:`20`,height:`8`,x:`2`,y:`14`,rx:`2`,ry:`2`,key:`iecqi9`}],[`line`,{x1:`6`,x2:`6.01`,y1:`6`,y2:`6`,key:`16zg32`}],[`line`,{x1:`6`,x2:`6.01`,y1:`18`,y2:`18`,key:`nzw8ys`}]]),Um=Z(`settings-2`,[[`path`,{d:`M14 17H5`,key:`gfn3mx`}],[`path`,{d:`M19 7h-9`,key:`6i9tg`}],[`circle`,{cx:`17`,cy:`17`,r:`3`,key:`18b49y`}],[`circle`,{cx:`7`,cy:`7`,r:`3`,key:`dfmy0x`}]]),Wm=Z(`shield-check`,[[`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`}]]),Gm=Z(`sliders-horizontal`,[[`path`,{d:`M10 5H3`,key:`1qgfaw`}],[`path`,{d:`M12 19H3`,key:`yhmn1j`}],[`path`,{d:`M14 3v4`,key:`1sua03`}],[`path`,{d:`M16 17v4`,key:`1q0r14`}],[`path`,{d:`M21 12h-9`,key:`1o4lsq`}],[`path`,{d:`M21 19h-5`,key:`1rlt1p`}],[`path`,{d:`M21 5h-7`,key:`1oszz2`}],[`path`,{d:`M8 10v4`,key:`tgpxqk`}],[`path`,{d:`M8 12H3`,key:`a7s4jb`}]]),Km=Z(`sparkles`,[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]]),qm=Z(`square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),Jm=Z(`sun`,[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]),Ym=Z(`test-tube-diagonal`,[[`path`,{d:`M21 7 6.82 21.18a2.83 2.83 0 0 1-3.99-.01a2.83 2.83 0 0 1 0-4L17 3`,key:`1ub6xw`}],[`path`,{d:`m16 2 6 6`,key:`1gw87d`}],[`path`,{d:`M12 16H4`,key:`1cjfip`}]]),Xm=Z(`trash-2`,[[`path`,{d:`M10 11v6`,key:`nco0om`}],[`path`,{d:`M14 11v6`,key:`outv1u`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`,key:`miytrc`}],[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`,key:`e791ji`}]]),Zm=Z(`triangle-alert`,[[`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`}]]),Qm=Z(`unlink`,[[`path`,{d:`m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71`,key:`yqzxt4`}],[`path`,{d:`m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71`,key:`4qinb0`}],[`line`,{x1:`8`,x2:`8`,y1:`2`,y2:`5`,key:`1041cp`}],[`line`,{x1:`2`,x2:`5`,y1:`8`,y2:`8`,key:`14m1p5`}],[`line`,{x1:`16`,x2:`16`,y1:`19`,y2:`22`,key:`rzdirn`}],[`line`,{x1:`19`,x2:`22`,y1:`16`,y2:`16`,key:`ox905f`}]]),$m=Z(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]);function eh(e){return/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(e)||e.startsWith(`//`)}function th(e){return[`localhost`,`127.0.0.1`,`::1`,`[::1]`].includes(e)}function nh(e,t,n){let r=e.trim();if(!r)return{error:`status URL is empty`};let i;try{i=new URL(r,t)}catch{return{error:`status URL is invalid`}}let a=!eh(r),o=th(i.hostname);return!a&&!o?{error:`${n} must be relative or loopback`}:{source:{isLoopback:o,isRelative:a,url:r}}}function rh(e,t){return nh(e,t,`statusUrl`)}function ih(e,t){let n=nh(e,t,`Ops statusUrl`);return n.error?{error:`${n.error}; use showcase mode for public links.`}:n}function ah(e,t,n){let r=new URL(e,n);return r.searchParams.set(`goal_activation`,t),r.toString()}function oh(e,t){if(!t||!e.isLoopback)return null;try{let n=new URL(e.url,window.location.href),r=new URL(t,n.origin);return th(r.hostname)?r.toString():null}catch{return null}}function sh(e,t){return{detailUrl:oh(t,e.local_dashboard_api?.periodic_report_detail_url),indexUrl:oh(t,e.local_dashboard_api?.periodic_report_index_url)}}async function ch(e,t){let n=new URL(e);n.searchParams.set(`goal_id`,t),n.searchParams.set(`limit`,`100`),n.searchParams.set(`offset`,`0`);let r=await fetch(n,{cache:`no-store`});if(!r.ok)throw Error(`HTTP ${r.status} while loading published reports`);return bp.parse(await r.json()).periodic_reports}async function lh(e,t){let n=new URL(e);Object.entries(t).forEach(([e,t])=>n.searchParams.set(e,t));let r=await fetch(n,{cache:`no-store`});if(!r.ok)throw Error(`HTTP ${r.status} while loading published report detail`);return Sp.parse(await r.json()).projection}function uh(e,t,n){let r=e.find(e=>e.agentId===t&&e.available)??e.find(e=>e.agentId===n&&e.available)??e.find(e=>e.available);if(!r)throw Error(`Chat requires at least one available route`);return r}function dh(e){return!!(e&&typeof e==`object`&&e.session_invalidated===!0)}var fh=``.replace(/\/+$/,``);function ph(e){return!fh||/^https?:\/\//.test(e)?e:new URL(e,`${fh}/`).toString()}var mh=J({todo_id:W().nullable(),role:W().nullable(),status:W(),priority:W().nullable(),text:W(),action_kind:W().nullable(),task_class:W().nullable(),claimed_by:W().nullable(),evidence:W().nullable()}),hh=J({goal_id:W(),title:W(),objective:W(),status:W(),waiting_on:W().nullable(),severity:W().nullable(),gate:W(),next_action:W(),top_todo:mh.nullable(),todos:q(mh),evidence:q(W()),quota:J({state:W().nullable(),spent_slots:G().nullable(),allowed_slots:G().nullable(),reason:W().nullable()})});J({ok:K(),schema_version:X(`loopx_chat_status_v0`),selected_goal_id:W().nullable(),goal_count:G(),goals:q(hh)});var gh=J({ok:X(!0),schema_version:Y([`loopx_chat_capabilities_v0`,`loopx_chat_capabilities_v1`]),agent_backend:W(),sandbox:W(),approval_policy:W(),todo_write:W(),goal_subagent_configuration:W().optional(),goal_id:W().nullable(),streaming:K().optional(),resume:K().optional(),interrupt:K().optional(),typed_actions:K().optional(),action_kinds:q(W()).optional(),adapters:q(J({agent_id:W(),display_name:W(),adapter_kind:W(),available:K(),streaming:K(),resume:K(),interrupt:K(),location:W().optional(),source:W().optional(),tool_calls:K().optional(),trust_scope:W().optional()})).optional(),lark_cli:J({available:K(),source:W(),version:W().nullable(),error_code:W().nullable()}).optional()}),_h=J({kind:X(`todo`),text:W(),priority:Y([`P0`,`P1`,`P2`]),rationale:W()}),vh=J({operation:Y([`merge`,`release`,`deploy`,`delete`,`payment`]),target:W().min(1).max(160),summary:W().max(300)}),yh=J({schema_version:X(`loopx_chat_agent_response_v0`),message:W(),proposals:q(_h),protected_action:vh.nullable().optional().default(null),gate:J({kind:W(),summary:W(),next_action:W()}).nullable()}),bh=J({closed:X(!0),ok:X(!0),session_id:W().min(1)});J({dry_run:X(!0),ok:X(!0),preview_id:W().min(1),todo:J({goal_id:W().min(1),text:W(),todo_id:W().optional()})});var xh=J({schema_version:X(`loopx_chat_todo_receipt_v0`),receipt_id:W().min(1),preview_id:W().min(1),goal_id:W().min(1),todo_id:W().min(1),status:X(`applied`),outcome:Y([`todo_added`,`todo_already_exists`]),already_exists:K(),preview_revision:W().nullable()});J({applied:X(!0),ok:X(!0),receipt:xh,todo:J({text:W(),todo_id:W()})});var Sh=J({model_config:J({model:W(),reasoning_effort:W().optional()}).optional(),mode:W(),spawn_allowed:K(),max_children:G().int().nonnegative(),allowed_domains:q(W()).optional().default([])}).passthrough(),Ch=J({ok:X(!0),dry_run:K(),execute:K(),written:K(),changed:K(),goal_id:W().min(1),changed_fields:q(W()),before:J({orchestration:Sh}).passthrough(),after:J({orchestration:Sh}).passthrough(),preview_id:W().min(1),feature_summary:J({multi_subagent:Y([`off`,`enabled`])}).passthrough(),global_sync:J({required:K(),executed:K(),readback:J({status:W(),verified:K()}).passthrough()}).passthrough()}),wh=J({id:W().min(1),outcome:Y([`approved`,`rejected`,`cancelled`]),projectionVerified:K().nullable(),proposal:_h,receipt:xh.nullable()}).superRefine((e,t)=>{e.outcome===`approved`&&!e.receipt&&t.addIssue({code:`custom`,message:`approved decision history requires a Todo receipt`,path:[`receipt`]}),e.outcome!==`approved`&&e.receipt&&t.addIssue({code:`custom`,message:`zero-write decision history must not include a Todo receipt`,path:[`receipt`]})});J({schema_version:X(`loopx_chat_decision_history_v0`),goal_id:W().min(1),decisions:q(wh).max(24)});var Th=class extends Error{payload;constructor(e,t){super(e),this.payload=t}},Eh=Y([`goal.create`,`goal.update`,`goal.lifecycle`,`todo.create`,`todo.update`,`agent.bind`,`heartbeat.bind`,`monitor.create`,`monitor.update`,`gate.resolve`,`run.correct`,`operation.execute`]),Dh=J({schema_version:X(`loopx_operation_envelope_v0`),lifecycle_state:Y([`prepared`,`awaiting_confirmation`,`claimed`,`outcome_observed`]),operation_id:W().min(1),confirmation_digest:W().min(1),payload_digest:W().min(1),projection_digest:W().min(1),expires_at:W().min(1),delivery:gd(W(),id()).nullable(),confirmation:gd(W(),id()).nullable(),claim:gd(W(),id()).nullable(),outcome:gd(W(),id()).nullable(),result_delivery:gd(W(),id()).nullable().optional()}).passthrough(),Oh=J({schema_version:X(`loopx_chat_action_proposal_v1`),proposal_id:W().min(1),action_kind:Eh,summary:W().min(1),normalized_parameters:gd(W(),id()),context:gd(W(),id()),expected_state_fingerprint:W().min(1),permission_classification:W().min(1),validation_evidence:q(W().refine(e=>e.trim().length>0,`Validation evidence must be non-blank text`)),available_transitions:q(Y([`apply`,`cancel`,`regenerate`,`reject`,`defer`])),status:Y([`preview_ready`,`applying`,`gated`,`failed`,`rejected`,`deferred`,`cancelled`,`stale`,`applied`]),receipt:gd(W(),id()).nullable(),stale:gd(W(),id()).nullable(),gate:gd(W(),id()).nullable().optional(),error:gd(W(),id()).nullable().optional(),checkpoint:gd(W(),id()).nullable().optional(),regenerated_from:W().nullable().optional(),operation:Dh.nullable().optional(),created_at:W(),updated_at:W()}),kh=J({ok:X(!0),proposal:Oh});async function Ah(e){let t=await Ih(`/api/actions/preview`,{method:`POST`,body:JSON.stringify({action_kind:e.actionKind,context:e.context,idempotency_key:e.idempotencyKey,normalized_parameters:e.normalizedParameters,summary:e.summary})});return kh.parse(t).proposal}var jh=J({ok:X(!0),schema_version:X(`loopx_chat_action_list_v1`),proposals:q(Oh)});async function Mh(e={}){let t=new URLSearchParams;e.contextKind&&t.set(`context_kind`,e.contextKind),e.goalId&&t.set(`goal_id`,e.goalId);let n=t.size>0?`?${t.toString()}`:``;return jh.parse(await Ih(`/api/actions${n}`)).proposals}async function Nh(e){let t=await Ih(`/api/actions/${encodeURIComponent(e)}/apply`,{method:`POST`,body:`{}`});return J({ok:X(!0),proposal:Oh,turn:gd(W(),id()).nullable().optional()}).parse(t)}async function Ph(e){return kh.parse(await Ih(`/api/actions/${encodeURIComponent(e)}/cancel`,{method:`POST`,body:`{}`})).proposal}async function Fh(e,t){return kh.parse(await Ih(`/api/actions/${encodeURIComponent(e)}/${t}`,{method:`POST`,body:`{}`})).proposal}async function Ih(e,t){let n;try{n=await fetch(ph(e),{cache:`no-store`,...t,headers:{"Content-Type":`application/json`,...t?.headers}})}catch{throw new Th(`无法连接 LoopX Chat 服务。请确认 Dashboard 与 Chat 服务已启动且来自同一版本。`,{error_code:`chat_api_unavailable`})}let r=await n.text(),i=null;if(r.trim())try{i=JSON.parse(r)}catch{i=null}let a=i&&typeof i==`object`&&!Array.isArray(i)?i:{};if(!n.ok){let e=(a.proposal&&typeof a.proposal==`object`?a.proposal:null)?.status===`stale`?`来源状态已变化,请重新生成预览。`:null,t=n.status>=500?`LoopX Chat 服务暂时不可用(HTTP ${n.status})。请确认 Dashboard 与 Chat 服务已启动且来自同一版本。`:`LoopX Chat 请求失败(HTTP ${n.status})。`;throw new Th(e??String(a.error||t),Object.keys(a).length?a:{error_code:`chat_api_unavailable`,http_status:n.status})}if(i===null)throw new Th(`LoopX Chat 服务返回了无法识别的响应(HTTP ${n.status})。请确认 Dashboard 与 Chat 服务来自同一版本。`,{error_code:`invalid_chat_api_response`,http_status:n.status});return i}async function Lh(){return gh.parse(await Ih(`/api/chat/capabilities`))}async function Rh(e){return Ih(`/api/chat/projection-messages`,{method:`POST`,body:JSON.stringify({answer:e.answer,context_kind:e.contextKind,goal_id:e.goalId,question:e.question})})}async function zh(e,t=`codex`,n=`resume_latest`,r=`goal`){return Ih(`/api/chat/sessions`,{method:`POST`,body:JSON.stringify({goal_id:e,agent_id:t,mode:n,context_kind:r})})}async function Bh(e){return Ih(`/api/chat/sessions/${e}`)}async function Vh(e){let t=new URLSearchParams;return e.agentId&&t.set(`agent_id`,e.agentId),e.channelId&&t.set(`channel_id`,e.channelId),e.goalId&&t.set(`goal_id`,e.goalId),Ih(`/api/chat/sessions?${t.toString()}`)}function Hh(e){let t=new Map;for(let n of e)for(let e of n.messages)t.set(e.message_id,e);return[...t.values()].sort((e,t)=>e.created_at.localeCompare(t.created_at)||e.message_id.localeCompare(t.message_id))}async function Uh(e){let t=await Vh(e),n=await Promise.all(t.sessions.map(e=>Bh(e.session_id)));return{messages:Hh(n),sessions:t.sessions,snapshots:n}}async function Wh(e,t,n,r=[]){return Ih(`/api/chat/sessions/${e}/turns`,{method:`POST`,body:JSON.stringify({message:t,client_turn_id:n,...r.length?{attachments:r.map(e=>({data_url:e.dataUrl,id:e.id,mime_type:e.mimeType,name:e.name,size:e.size}))}:{}})})}function Gh(e){let t=e.split(` +`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(` +`);if(!t)return null;try{let e=JSON.parse(t);return!e.kind||!e.payload||typeof e.payload!=`object`?null:{event_id:String(e.event_id??``),sequence:Number(e.sequence??0),kind:String(e.kind),created_at:String(e.created_at??``),payload:e.payload}}catch{return null}}async function Kh(e,t,n){let r=``,i=0,a=!1;for(;!a&&i<4;){let o=typeof window>`u`?`http://127.0.0.1`:window.location.origin,s=new URL(ph(e),o);r&&s.searchParams.set(`after`,r);try{let e=await fetch(s,{cache:`no-store`,headers:{Accept:`text/event-stream`},signal:n});if(!e.ok||!e.body)throw new Th(`SSE HTTP ${e.status}`,{status:e.status});let o=e.body.getReader(),c=new TextDecoder,l=``;for(;;){let{done:e,value:n}=await o.read();l+=c.decode(n,{stream:!e}).replaceAll(`\r +`,` +`);let i=l.indexOf(` + +`);for(;i>=0;){let e=l.slice(0,i);l=l.slice(i+2);let n=Gh(e);n&&(n.event_id&&(r=n.event_id),t(n),a=[`turn.completed`,`turn.interrupted`,`turn.failed`].includes(n.kind)),i=l.indexOf(` + +`)}if(e||a)break}i=a?i:i+1}catch(e){if(n?.aborted||(i+=1,i>=4))throw e;await new Promise(e=>globalThis.setTimeout(e,250*2**(i-1)))}}if(!a)throw new Th(`Agent 事件流连接已断开。`,{reconnect_attempts:i})}async function qh(e,t){return Ih(`/api/chat/sessions/${e}/turns/${t}/interrupt`,{method:`POST`,body:`{}`})}async function Jh(e,t,n={}){let r=await Wh(e,t,n.clientTurnId??crypto.randomUUID(),n.attachments);return n.onPhase?.(`turn.accepted`,r.turn_id),Yh(e,r.turn_id,r.events_url,n)}async function Yh(e,t,n,r={}){let i=null,a={failure:null,interrupted:null};try{await Kh(n,e=>{r.onPhase?.(e.kind,t),(e.kind===`answer.delta`||e.kind===`assistant.delta`)&&r.onDelta?.(String(e.payload.text??``)),e.kind===`agent.phase`&&r.onActivity?.(String(e.payload.label??`Agent 正在处理`)),e.kind===`turn.completed`&&(i=e.payload.response),e.kind===`turn.failed`&&(a.failure=e.payload),e.kind===`turn.interrupted`&&(a.interrupted=e.payload)},r.signal)}catch(i){throw i instanceof Th&&!r.signal?.aborted?new Th(i.message,{...i.payload,events_url:n,reconnectable:!0,session_id:e,turn_id:t}):i}if(a.failure)throw new Th(String(a.failure.message||`Agent 回合失败。`),a.failure);if(a.interrupted)throw new Th(`Agent 回合已中断。`,{...a.interrupted,error_code:`turn_interrupted`,session_id:e,turn_id:t});return{response:yh.parse(i),sessionId:e,turnId:t}}async function Xh(e,t,n={}){return Yh(e,t,`/api/chat/sessions/${e}/turns/${t}/events`,n)}async function Zh(e){let t=bh.parse(await Ih(`/api/chat/sessions/${e}`,{keepalive:!0,method:`DELETE`}));if(t.session_id!==e)throw new Th(`Agent 会话关闭回执与本次请求不一致。`,{session_id:t.session_id});return t}async function Qh(e){return Ih(`/api/chat/sessions/${e}/resume`,{method:`POST`,body:`{}`})}function $h(e){return{goal_id:e.goalId,enabled:e.enabled,...e.modelConfig===void 0?{}:{model_config:e.modelConfig},...e.enabled?{max_children:e.maxChildren,allowed_domains:e.allowedDomains}:{}}}function eg(e,t){let n=e.after.orchestration,r=[...new Set(t.allowedDomains)],i=e.feature_summary.multi_subagent===`enabled`;if(!(e.goal_id===t.goalId&&i===t.enabled&&(t.modelConfig===void 0||JSON.stringify(n.model_config??null)===JSON.stringify(t.modelConfig))&&(t.enabled?n.max_children===t.maxChildren&&JSON.stringify(n.allowed_domains)===JSON.stringify(r):n.spawn_allowed===!1&&n.max_children===0)))throw new Th(`Goal 子代理配置回执与本次请求不一致,界面已停止更新。`,{after:e.after,goal_id:e.goal_id});return e}async function tg(e){let t=Ch.parse(await Ih(`/api/chat/goal-subagents/dry-run`,{method:`POST`,body:JSON.stringify($h(e))}));if(!t.dry_run||t.execute||t.written)throw new Th(`Goal 子代理预览返回了非预览回执,已停止进入确认状态。`,{result:t});return eg(t,e)}async function ng(e,t){let n=Ch.parse(await Ih(`/api/chat/goal-subagents/apply`,{method:`POST`,body:JSON.stringify({...$h(e),preview_id:t})}));if(n.preview_id!==t||n.dry_run||!n.execute)throw new Th(`Goal 子代理写入回执与本次确认不一致,界面已停止更新。`,{result:n});if(n.changed&&(!n.written||!n.global_sync.executed||!n.global_sync.readback.verified))throw new Th(`Goal 子代理设置未通过共享状态读回验证。`,{result:n});return eg(n,e)}var rg=J({ok:X(!0),targets:q(J({enabled:K(),provider:W(),target_name:W()}))});async function ig(){return rg.parse(await Ih(`/api/chat/goal-channel/targets`)).targets}var ag=J({ok:K(),blocker:W().optional(),public_summary:W().optional(),status:W().optional()});async function og(e){return ag.parse(await Ih(`/api/chat/goal-channel/setup`,{method:`POST`,body:JSON.stringify({execute:e.execute,goal_id:e.goalId,target:e.target})}))}async function sg(e){return ag.parse(await Ih(`/api/chat/goal-channel/configure`,{method:`POST`,body:JSON.stringify({auto_notify_human_gates:e.autoNotify,goal_id:e.goalId})}))}var cg=J({schema_version:X(`periodic_report_schedule_v0`),schedule_id:W(),rrule:W(),timezone:W()});J({schema_version:X(`periodic_report_machine_defaults_v0`),enabled:K(),inheritance:X(`live_machine_default`),profile_preset:W().optional(),route_ref:W().optional(),timezone:W(),schedule:cg.nullable().optional()});var lg=J({schema_version:X(`loopx_machine_configuration_v0`),namespaces:gd(W(),gd(W(),id()))}),ug=J({namespace:W(),title:W(),description:W(),schema_versions:q(W()).min(1),configuration_template:gd(W(),id()),template_status:Y([`ready`,`schema_only`])}),dg=J({schema_version:X(`machine_configuration_catalog_v0`),namespaces:q(ug)}),fg=J({key:W(),label:W(),description:W(),input_kind:Y([`boolean`,`number`,`select`,`string_list`,`text`,`periodic_report_schedule`]),nullable:K().optional(),required:K(),minimum:G().int().optional(),maximum:G().int().optional(),options:q(W()).optional()}),pg=J({schema_version:X(`capability_configuration_editor_v0`),editable:K(),supported_scopes:q(Y([`goal`,`machine`])),writable_scopes:q(Y([`goal`,`machine`])),fields:q(fg),read_only_reason:W().optional()}),mg=J({schema_version:X(`capability_configuration_catalog_v0`),capabilities:q(J({capability_id:W(),display_name:W(),description:W(),available_scopes:q(Y([`goal`,`machine`])),machine_namespace:W().optional(),goal_feature_id:W().optional(),effective_value_policy:X(`goal_override_over_live_machine_default`).optional(),availability:W().optional(),default:gd(W(),id()).optional(),current:gd(W(),id()).optional(),machine_current:gd(W(),id()).optional(),effective_configuration:J({schema_version:X(`capability_configuration_resolution_v0`),capability_id:W(),source:Y([`goal_override`,`machine_default`,`capability_default`,`not_configured`]),configuration:gd(W(),id()).nullable(),inherited:K(),goal_override_present:K(),machine_default_present:K(),effective_revision:W()}).optional(),documentation:gd(W(),id()).optional(),context_contribution:J({supported_phases:q(Y([`before_plan`,`before_delegate`,`after_delegate_result`])),target:X(`coordinator`),activation:X(`with_capability`),receipt_required:X(!0)}).optional(),configuration_editor:pg}))}),hg=J({ok:X(!0),schema_version:X(`goal_configuration_inspection_v0`),status:X(`configured`),goal_id:W(),revision:W(),available_capabilities:q(W()),capability_catalog:mg}),gg=J({ok:X(!0),goal_id:W(),capability_id:W(),changed_fields:q(W()),goal_configuration:gd(W(),id()).nullable(),capability_catalog:mg}),_g=gg.extend({schema_version:X(`goal_configuration_update_plan_v0`),status:X(`preview`),action:Y([`create`,`update`,`delete`,`unchanged`]),current_revision:W(),desired_revision:W(),base_revision:W(),plan_revision:W(),writes_required:G().int().nonnegative()}),vg=ud([gg.extend({schema_version:X(`goal_configuration_transaction_v0`),status:Y([`applied`,`unchanged`]),plan_revision:W(),applied_revision:W(),readback_verified:X(!0)}),J({ok:X(!1),schema_version:X(`goal_configuration_transaction_v0`),status:X(`partial_write`),goal_id:W(),capability_id:W(),plan_revision:W(),applied_revision:W().nullable(),source_written:X(!0),shared_sync_pending:X(!0),readback_verified:K(),changed_fields:q(W()),goal_configuration:gd(W(),id()).nullable(),capability_catalog:mg,error:W(),recommended_action:W()})]),yg=J({ok:X(!0),available_namespaces:q(W()),namespace_catalog:dg.optional().default({schema_version:`machine_configuration_catalog_v0`,namespaces:[]}),capability_catalog:mg,changed_namespaces:q(W()).optional().default([]),machine_configuration:lg.nullable().optional()}),bg=yg.extend({schema_version:X(`machine_configuration_inspection_v0`),status:Y([`configured`,`absent`]),revision:W()}),xg=yg.extend({schema_version:X(`machine_configuration_update_plan_v0`),status:X(`preview`),action:Y([`create`,`update`,`delete`,`unchanged`]),current_revision:W(),desired_revision:W(),plan_revision:W(),writes_required:G().int().nonnegative(),machine_configuration:lg.nullable()}),Sg=yg.extend({schema_version:X(`machine_configuration_transaction_v0`),status:Y([`applied`,`unchanged`]),plan_revision:W(),transaction_id:W().nullable(),readback_verified:X(!0),rollback_available:K(),applied_revision:W().optional(),prior_revision:W().optional()}),Cg=yg.extend({schema_version:X(`machine_configuration_rollback_plan_v0`),status:X(`preview`),action:Y([`delete`,`restore`,`unchanged`,`blocked`]),reason:W(),transaction_id:W(),plan_revision:W(),rollback_allowed:K(),writes_required:G().int().nonnegative()}),wg=yg.extend({schema_version:X(`machine_configuration_rollback_receipt_v0`),status:Y([`rolled_back`,`unchanged`]),transaction_id:W(),plan_revision:W(),rollback_id:W().nullable(),readback_verified:X(!0)});async function Tg(){return bg.parse(await Ih(`/api/chat/machine-configuration`))}async function Eg(e){let t=new URLSearchParams({goal_id:e});return hg.parse(await Ih(`/api/chat/goal-configuration?${t.toString()}`))}async function Dg(e,t,n){return _g.parse(await Ih(`/api/chat/goal-configuration/preview`,{method:`POST`,body:JSON.stringify({goal_id:e,capability_id:t,configuration:n})}))}async function Og(e,t,n,r){return vg.parse(await Ih(`/api/chat/goal-configuration/apply`,{method:`POST`,body:JSON.stringify({goal_id:e,capability_id:t,configuration:n,expected_plan_revision:r})}))}async function kg(e,t){return xg.parse(await Ih(`/api/chat/machine-configuration/preview`,{method:`POST`,body:JSON.stringify({namespace:e,namespace_configuration:t})}))}async function Ag(e,t,n){return Sg.parse(await Ih(`/api/chat/machine-configuration/apply`,{method:`POST`,body:JSON.stringify({expected_plan_revision:n,namespace:e,namespace_configuration:t})}))}async function jg(e){return xg.parse(await Ih(`/api/chat/machine-configuration/preview`,{method:`POST`,body:JSON.stringify({namespace:e,operation:`remove`})}))}async function Mg(e,t){return Sg.parse(await Ih(`/api/chat/machine-configuration/apply`,{method:`POST`,body:JSON.stringify({expected_plan_revision:t,namespace:e,operation:`remove`})}))}async function Ng(e){return Cg.parse(await Ih(`/api/chat/machine-configuration/rollback`,{method:`POST`,body:JSON.stringify({execute:!1,transaction_id:e})}))}async function Pg(e,t){return wg.parse(await Ih(`/api/chat/machine-configuration/rollback`,{method:`POST`,body:JSON.stringify({execute:!0,expected_plan_revision:t,transaction_id:e})}))}var Fg=J({ok:X(!0),goals:q(J({goal_id:W(),repository:J({branch:W(),identity:W(),label:W(),read_only:X(!0)})}))});async function Ig(){return Fg.parse(await Ih(`/api/chat/goals/contexts`)).goals}var Lg=J({ok:X(!0),apps:q(J({active:K(),app_ref:W(),brand:W(),health_error_code:W().nullable().default(null),label:W(),ready:K(),reply_ready:K().default(!1)}))});async function Rg(){return Lg.parse(await Ih(`/api/chat/lark/apps`)).apps}var zg=J({ok:X(!0),app_ref:W(),error:W().nullable(),setup_id:W(),status:Y([`starting`,`waiting_for_feishu`,`ready`,`failed`,`cancelled`]),verification_url:W().url().nullable()});async function Bg(e){return zg.parse(await Ih(`/api/chat/lark/app-setups`,{method:`POST`,body:JSON.stringify({app_ref:e.appRef,brand:e.brand})}))}async function Vg(e){return zg.parse(await Ih(`/api/chat/lark/app-setups/${encodeURIComponent(e)}`))}async function Hg(e){return zg.parse(await Ih(`/api/chat/lark/app-setups/${encodeURIComponent(e)}`,{method:`DELETE`}))}var Ug=[`invalid_event`,`binding_unavailable`,`chat_mismatch`,`topic_mismatch`,`route_ambiguous`,`self_message`,`invalid_routing_state`,`not_addressed`],Wg=J({ok:X(!0),chats:q(J({chat_id:W(),chat_name:W()}))});async function Gg(e,t){let n=new URLSearchParams({app_ref:e});return t&&n.set(`query`,t),Wg.parse(await Ih(`/api/chat/lark/chats?${n.toString()}`)).chats}var Kg=J({ok:X(!0),connections:q(J({conversation_kind:Y([`goal`,`manager`]).default(`goal`),agent_id:W().nullable().default(null),connection_id:W(),app_label:W(),app_ref:W(),capture_scope:Y([`addressed_only`,`configured_chat_all`]).default(`addressed_only`),chat_name:W(),enabled:K(),goal_id:W(),goal_title:W(),health_error_code:W().nullable().default(null),history_permission_guidance:J({action:X(`enable_application_scopes_and_publish`),api_document_url:W().url(),capability:X(`group_history_pagination`),identity:X(`bot`),required_scopes:md([X(`im:message.group_msg`),X(`im:message.group_msg.include_bot:read`)]),schema_version:X(`lark_bot_group_history_permission_guidance_v0`)}).nullable().default(null),incoming_mode:Y([`mentions`,`all`]),ingress_mode:Y([`live_steering`,`session_queue`,`async_inbox`,`direct_session`]).default(`async_inbox`),event_count:G().int().nonnegative().default(0),last_event_reason:Y(Ug).nullable().default(null).catch(null),last_event_status:W().nullable().default(null),listener_error_code:W().nullable().default(null),listener_status:Y([`starting`,`listening`,`retrying`,`stopped`]).nullable().default(null),replied_count:G().int().nonnegative().default(0),reply_ready:K().default(!1),reply_mode:X(`topic_reply`),session_bound:K().default(!1),target_ref:W(),topic_name:W(),topic_setup_required:K()}))});async function qg(){return Kg.parse(await Ih(`/api/chat/lark/connections`)).connections}async function Jg(e){return ag.parse(await Ih(`/api/chat/lark/connections`,{method:`POST`,body:JSON.stringify({...e.agentBindings?{agent_bindings:e.agentBindings.map(e=>({agent_id:e.agentId,app_ref:e.appRef}))}:{},...e.agentId?{agent_id:e.agentId}:{},...e.appRef?{app_ref:e.appRef}:{},...e.connectionId?{connection_id:e.connectionId}:{},conversation_kind:e.conversationKind??`goal`,capture_scope:e.captureScope,chat_id:e.chatId,chat_name:e.chatName,execute:e.execute,goal_id:e.goalId,incoming_mode:e.incomingMode,ingress_mode:e.ingressMode,reply_mode:e.replyMode})}))}async function Yg(e,t){let n=new URLSearchParams({goal_id:e,connection_id:t});return ag.parse(await Ih(`/api/chat/lark/connections?${n.toString()}`,{method:`DELETE`}))}function Xg(e){return{loadedUrl:null,projectionRevision:0,requestedUrl:e,selectionRevision:0,requestGeneration:0}}function Zg(e,t){return e.selectionRevision+=1,e.requestedUrl=t,e.selectionRevision}function Qg(e,t,n){if(n.background)return e.requestedUrl!==null||e.loadedUrl!==t?null:(e.requestGeneration+=1,{background:!0,projectionRevision:e.projectionRevision,selectionRevision:e.selectionRevision,url:t,generation:e.requestGeneration});let r=n.selectionRevision??e.selectionRevision+1;return n.selectionRevision!==void 0&&e.selectionRevision!==r?null:(e.selectionRevision=r,e.projectionRevision+=1,e.requestedUrl=t,e.requestGeneration+=1,{background:!1,projectionRevision:e.projectionRevision,selectionRevision:r,url:t,generation:e.requestGeneration})}function $g(e,t){return t.generation===e.requestGeneration&&e.projectionRevision===t.projectionRevision&&e.selectionRevision===t.selectionRevision}function e_(e,t){return $g(e,t)&&(!t.background||e.requestedUrl===null&&e.loadedUrl===t.url)}function t_(e,t,n){return t.get(e)===n}function n_(e,t,n,r){return e.filter(e=>t_(r(e),n,t))}function r_(e,t,n){let r=new Set,i=[];for(let a of[...e,...t]){let e=n(a);e==null||r.has(e)||(r.add(e),i.push(a))}return i}var i_=[`runs_24h`,`runs_7d`,`quota_spend_slots_24h`,`quota_spend_slots_7d`,`automation_run_count_24h`,`automation_run_count_7d`,`progress_signal_run_count_24h`,`progress_signal_run_count_7d`],a_=[`input_tokens_24h`,`input_tokens_7d`,`output_tokens_24h`,`output_tokens_7d`,`cache_tokens_24h`,`cache_tokens_7d`,`cost_usd_24h`,`cost_usd_7d`,`duration_ms_24h`,`duration_ms_7d`],o_=[`accounting`,`decision`,`evidence`,`state`,`work`],s_={accounting:0,decision:0,evidence:0,state:0,work:0},c_={runs_24h:0,runs_7d:0,quota_spend_slots_24h:0,quota_spend_slots_7d:0,automation_run_count_24h:0,automation_run_count_7d:0,progress_signal_run_count_24h:0,progress_signal_run_count_7d:0};function l_(e,t){let n={...e};for(let r of i_)n[r]=(Number(e[r])||0)+(Number(t[r])||0);for(let r of a_)(e[r]!==void 0||t[r]!==void 0)&&(n[r]=(e[r]??0)+(t[r]??0));return n}function u_(e,t){return!e.length||t<=0?e:e.map(e=>({...e,project_share_24h:Math.round((Number(e.runs_24h)||0)/t*1e3)/1e3}))}function d_(e,t){let n={...e};for(let r of o_)n[r]=(e[r]??0)+(t[r]??0);return n}function f_(e){let t={events_24h:0,events_7d:0,by_class_24h:{...s_},by_class_7d:{...s_}};for(let n of e)t.events_24h+=n.events_24h,t.events_7d+=n.events_7d,t.by_class_24h=d_(t.by_class_24h,n.by_class_24h),t.by_class_7d=d_(t.by_class_7d,n.by_class_7d);return t}function p_(e,t,n){if(!e&&!t)return null;let r=n_(e?.goals??[],`active`,n,e=>e.goal_id),i=n_(t?.goals??[],`stopped`,n,e=>e.goal_id),a=r_(r,i,e=>e.goal_id),o=f_(r),s=f_(i),c={events_24h:o.events_24h+s.events_24h,events_7d:o.events_7d+s.events_7d,by_class_24h:d_(o.by_class_24h,s.by_class_24h),by_class_7d:d_(o.by_class_7d,s.by_class_7d)};return{...e??t,goals:a,sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),totals:c}}function m_(e,t,n){if(!e&&!t)return null;let r=r_([...n_(e?.items??[],`active`,n,e=>e.goal_id),...n_(t?.items??[],`stopped`,n,e=>e.goal_id)],[],e=>`${e.goal_id}:${e.decision_kind??``}:${e.decision_at??``}`),i={decision_count:(e?.summary.decision_count??0)+(t?.summary.decision_count??0),stale_count:r.filter(e=>e.stale_by_age).length,rebase_required_count:(e?.summary.rebase_required_count??0)+(t?.summary.rebase_required_count??0),fresh_count:(e?.summary.fresh_count??0)+(t?.summary.fresh_count??0)};return{...e??t,items:r,sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),summary:i}}function h_(e,t){return r_([...e,...t].sort((e,t)=>t.generated_at.localeCompare(e.generated_at)),[],e=>`${e.goal_id}:${e.generated_at}:${e.classification??``}`)}function g_(e,t,n){let r=r_(n_(e.items,`active`,n,e=>e.goal_id),n_(t.items,`stopped`,n,e=>e.goal_id),e=>e.goal_id);return{...e,item_count:r.length,items:r,needs_controller:r.filter(e=>e.waiting_on===`controller`).length,needs_codex:r.filter(e=>e.waiting_on===`codex`).length,needs_user_or_controller:r.filter(e=>[`user_or_controller`,`controller`].includes(e.waiting_on)).length,watching_external_evidence:r.filter(e=>e.waiting_on===`external_evidence`).length}}function __(e){let t=e.todo_id?.trim()||``;return t?`${e.goal_id}:${t}`:`${e.goal_id}:synthetic:${e.role??``}:${e.index??``}:${e.text??``}`}function v_(e){let t={...c_};for(let n of e){for(let e of i_)t[e]+=Number(n[e])||0;for(let e of a_)n[e]!==void 0&&(t[e]=(t[e]??0)+n[e])}return t}function y_(e,t,n){if(!e&&!t)return null;let r=n_(e?.items??[],`active`,n,e=>e.goal_id),i=n_(t?.items??[],`stopped`,n,e=>e.goal_id),a=r_(r,i,__);return{...e??t,current_projected_count:r.length+i.length,items:a,rollout_event_count:a.reduce((e,t)=>e+(t.event_count??0),0),total_count:a.length}}function b_(e,t,n){if(!e&&!t)return null;let r=n_(e?.goals??[],`active`,n,e=>e.goal_id),i=n_(t?.goals??[],`stopped`,n,e=>e.goal_id),a=r_(r,i,e=>e.goal_id),o=l_(v_(r),v_(i));return{...e??t,goals:u_(a,Number(o.runs_24h)||0),sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),totals:o}}function x_(e,t,n){if(!e&&!t)return null;let r=(e?.agents??[]).filter(e=>e.goal_ids.some(e=>t_(e,n,`active`))||(e.current_todo?.goal_id?t_(e.current_todo.goal_id,n,`active`):!1)),i=(t?.agents??[]).filter(e=>e.goal_ids.some(e=>t_(e,n,`stopped`))||(e.current_todo?.goal_id?t_(e.current_todo.goal_id,n,`stopped`):!1)),a=r_(r,i,e=>e.agent_id).map(e=>{let t=i.find(t=>t.agent_id===e.agent_id);return t?{...e,goal_ids:Array.from(new Set([...e.goal_ids??[],...t.goal_ids]))}:e});return{...e??t,agents:a,source_summary:(e??t)?.source_summary?{...(e??t).source_summary,projected_agent_count:a.length,registered_agent_count:new Set(a.map(e=>e.agent_id)).size}:(e??t)?.source_summary}}function S_(e,t,n){if(!e&&!t)return null;let r=r_(n_(e?.goals??[],`active`,n,e=>e.goal_id),n_(t?.goals??[],`stopped`,n,e=>e.goal_id),e=>e.goal_id);return{...e??t,goals:r}}function C_(e,t){let n=t.goal_projection?.scope;if(n!==`active`&&n!==`stopped`)return t;let r=n,i=t.run_history.goals,a=e.run_history.goals,o=r_(r===`active`?i:a.filter(e=>e.activation_state!==`stopped`),r===`stopped`?i:a.filter(e=>e.activation_state===`stopped`),e=>e.id),s=new Map(o.map(e=>[e.id,e.activation_state])),c=r===`active`?t:e,l=r===`stopped`?t:e,u=e.goal_projection?.registry_revision??null,d=t.goal_projection?.registry_revision??null,f=u===null||d===null||u===d;return{...e,agent_management_projection:x_(c.agent_management_projection,l.agent_management_projection,s),attention_queue:g_(c.attention_queue,l.attention_queue,s),decision_freshness_summary:m_(c.decision_freshness_summary,l.decision_freshness_summary,s),event_ledger_summary:p_(c.event_ledger_summary,l.event_ledger_summary,s),goal_channel_notification_projection:S_(c.goal_channel_notification_projection,l.goal_channel_notification_projection,s),goal_projection:{schema_version:`loopx_goal_projection_scope_v0`,...t.goal_projection,complete:f,projected_goal_count:o.length,registry_goal_count:t.goal_projection?.registry_goal_count??0,scope:`all`},run_history:{...e.run_history,goal_count:o.length,goals:o,recent_runs:h_(c.run_history.recent_runs,l.run_history.recent_runs),run_count:c.run_history.run_count+l.run_history.run_count},todo_index:y_(c.todo_index,l.todo_index,s),usage_summary:b_(c.usage_summary,l.usage_summary,s)}}function w_(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`){if(Array.isArray(e)){var i=e.length;for(t=0;ttypeof e==`boolean`?`${e}`:e===0?`0`:e,D_=T_,O_=(e,t)=>n=>{if(t?.variants==null)return D_(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=E_(t)||E_(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return D_(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)},k_=(e,t)=>{let n=Array(e.length+t.length);for(let t=0;t({classGroupId:e,validator:t}),j_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),M_=`-`,N_=[],P_=`arbitrary..`,F_=e=>{let t=R_(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return L_(e);let n=e.split(M_);return I_(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?k_(i,t):t:i||N_}return n[e]||N_}}},I_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=I_(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(M_):e.slice(t).join(M_),s=a.length;for(let e=0;ee.slice(1,-1).indexOf(`:`)===-1?void 0:(()=>{let t=e.slice(1,-1),n=t.indexOf(`:`),r=t.slice(0,n);return r?P_+r:void 0})(),R_=e=>{let{theme:t,classGroups:n}=e;return z_(n,t)},z_=(e,t)=>{let n=j_();for(let r in e){let i=e[r];B_(i,n,r,t)}return n},B_=(e,t,n,r)=>{let i=e.length;for(let a=0;a{if(typeof e==`string`){H_(e,t,n);return}if(typeof e==`function`){U_(e,t,n,r);return}W_(e,t,n,r)},H_=(e,t,n)=>{let r=e===``?t:G_(t,e);r.classGroupId=n},U_=(e,t,n,r)=>{if(K_(e)){B_(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(A_(n,e))},W_=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e{let n=e,r=t.split(M_),i=r.length;for(let e=0;e`isThemeGetter`in e&&e.isThemeGetter===!0,q_=e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null),i=(i,a)=>{n[i]=a,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];if(t!==void 0)return t;if((t=r[e])!==void 0)return i(e,t),t},set(e,t){e in n?n[e]=t:i(e,t)}}},J_=`!`,Y_=`:`,X_=[],Z_=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),Q_=e=>{let{prefix:t,experimentalParseClassName:n}=e,r=e=>{let t=[],n=0,r=0,i=0,a,o=e.length;for(let s=0;si?a-i:void 0;return Z_(t,l,c,u)};if(t){let e=t+Y_,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):Z_(X_,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},$_=e=>{let t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{let n=[],r=[];for(let i=0;i0&&(r.sort(),n.push(...r),r=[]),n.push(a)):r.push(a)}return r.length>0&&(r.sort(),n.push(...r)),n}},ev=e=>({cache:q_(e.cacheSize),parseClassName:Q_(e),sortModifiers:$_(e),postfixLookupClassGroupIds:tv(e),...F_(e)}),tv=e=>{let t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let e=0;e{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a,postfixLookupClassGroupIds:o}=t,s=[],c=e.trim().split(nv),l=``;for(let e=c.length-1;e>=0;--e){let t=c[e],{isExternal:u,modifiers:d,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:m}=n(t);if(u){l=t+(l.length>0?` `+l:l);continue}let h=!!m,g;if(h){g=r(p.substring(0,m));let e=g&&o[g]?r(p):void 0;e&&e!==g&&(g=e,h=!1)}else g=r(p);if(!g){if(!h){l=t+(l.length>0?` `+l:l);continue}if(g=r(p),!g){l=t+(l.length>0?` `+l:l);continue}h=!1}let _=d.length===0?``:d.length===1?d[0]:a(d).join(`:`),v=f?_+J_:_,y=v+g;if(s.indexOf(y)>-1)continue;s.push(y);let b=i(g,h);for(let e=0;e0?` `+l:l)}return l},iv=(...e)=>{let t=0,n,r,i=``;for(;t{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r{let n,r,i,a,o=o=>(n=ev(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,a=s,s(o)),s=e=>{let t=r(e);if(t)return t;let a=rv(e,n);return i(e,a),a};return a=o,(...e)=>a(iv(...e))},sv=[],cv=e=>{let t=t=>t[e]||sv;return t.isThemeGetter=!0,t},lv=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,uv=/^\((?:(\w[\w-]*):)?(.+)\)$/i,dv=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,fv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,pv=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,mv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,hv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,gv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,_v=e=>dv.test(e),vv=e=>!!e&&!Number.isNaN(Number(e)),yv=e=>!!e&&Number.isInteger(Number(e)),bv=e=>e.endsWith(`%`)&&vv(e.slice(0,-1)),xv=e=>fv.test(e),Sv=()=>!0,Cv=e=>pv.test(e)&&!mv.test(e),wv=()=>!1,Tv=e=>hv.test(e),Ev=e=>gv.test(e),Dv=e=>!Q(e)&&!$(e),Ov=e=>e.startsWith(`@container`)&&(e[10]===`/`&&e[11]!==void 0||e[11]===`s`&&e[16]!==void 0&&e.startsWith(`-size/`,10)||e[11]===`n`&&e[18]!==void 0&&e.startsWith(`-normal/`,10)),kv=e=>Wv(e,Jv,wv),Q=e=>lv.test(e),Av=e=>Wv(e,Yv,Cv),jv=e=>Wv(e,Xv,vv),Mv=e=>Wv(e,Qv,Sv),Nv=e=>Wv(e,Zv,wv),Pv=e=>Wv(e,Kv,wv),Fv=e=>Wv(e,qv,Ev),Iv=e=>Wv(e,$v,Tv),$=e=>uv.test(e),Lv=e=>Gv(e,Yv),Rv=e=>Gv(e,Zv),zv=e=>Gv(e,Kv),Bv=e=>Gv(e,Jv),Vv=e=>Gv(e,qv),Hv=e=>Gv(e,$v,!0),Uv=e=>Gv(e,Qv,!0),Wv=(e,t,n)=>{let r=lv.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Gv=(e,t,n=!1)=>{let r=uv.exec(e);return r?r[1]?t(r[1]):n:!1},Kv=e=>e===`position`||e===`percentage`,qv=e=>e===`image`||e===`url`,Jv=e=>e===`length`||e===`size`||e===`bg-size`,Yv=e=>e===`length`,Xv=e=>e===`number`,Zv=e=>e===`family-name`,Qv=e=>e===`number`||e===`weight`,$v=e=>e===`shadow`,ey=ov(()=>{let e=cv(`color`),t=cv(`font`),n=cv(`text`),r=cv(`font-weight`),i=cv(`tracking`),a=cv(`leading`),o=cv(`breakpoint`),s=cv(`container`),c=cv(`spacing`),l=cv(`radius`),u=cv(`shadow`),d=cv(`inset-shadow`),f=cv(`text-shadow`),p=cv(`drop-shadow`),m=cv(`blur`),h=cv(`perspective`),g=cv(`aspect`),_=cv(`ease`),v=cv(`animate`),y=()=>[`auto`,`avoid`,`all`,`avoid-page`,`page`,`left`,`right`,`column`],b=()=>[`center`,`top`,`bottom`,`left`,`right`,`top-left`,`left-top`,`top-right`,`right-top`,`bottom-right`,`right-bottom`,`bottom-left`,`left-bottom`],x=()=>[...b(),$,Q],S=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],C=()=>[`auto`,`contain`,`none`],w=()=>[$,Q,c],T=()=>[_v,`full`,`auto`,...w()],E=()=>[yv,`none`,`subgrid`,$,Q],D=()=>[`auto`,{span:[`full`,yv,$,Q]},yv,$,Q],O=()=>[yv,`auto`,$,Q],ee=()=>[`auto`,`min`,`max`,`fr`,$,Q],te=()=>[`start`,`end`,`center`,`between`,`around`,`evenly`,`stretch`,`baseline`,`center-safe`,`end-safe`],ne=()=>[`start`,`end`,`center`,`stretch`,`center-safe`,`end-safe`],k=()=>[`auto`,...w()],A=()=>[_v,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...w()],j=()=>[_v,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...w()],M=()=>[_v,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...w()],N=()=>[e,$,Q],P=()=>[...b(),zv,Pv,{position:[$,Q]}],F=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],re=()=>[`auto`,`cover`,`contain`,Bv,kv,{size:[$,Q]}],ie=()=>[bv,Lv,Av],I=()=>[``,`none`,`full`,l,$,Q],ae=()=>[``,vv,Lv,Av],L=()=>[`solid`,`dashed`,`dotted`,`double`],oe=()=>[`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`],se=()=>[vv,bv,zv,Pv],ce=()=>[``,`none`,m,$,Q],le=()=>[`none`,vv,$,Q],ue=()=>[`none`,vv,$,Q],de=()=>[vv,$,Q],fe=()=>[_v,`full`,...w()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[xv],breakpoint:[xv],color:[Sv],container:[xv],"drop-shadow":[xv],ease:[`in`,`out`,`in-out`],font:[Dv],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[xv],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[xv],shadow:[xv],spacing:[`px`,vv],text:[xv],"text-shadow":[xv],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,_v,Q,$,g]}],container:[`container`],"container-type":[{"@container":[``,`normal`,`size`,$,Q]}],"container-named":[Ov],columns:[{columns:[vv,Q,$,s]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":[`auto`,`avoid`,`avoid-page`,`avoid-column`]}],"box-decoration":[{"box-decoration":[`slice`,`clone`]}],box:[{box:[`border`,`content`]}],display:[`block`,`inline-block`,`inline`,`flex`,`inline-flex`,`table`,`inline-table`,`table-caption`,`table-cell`,`table-column`,`table-column-group`,`table-footer-group`,`table-header-group`,`table-row-group`,`table-row`,`flow-root`,`grid`,`inline-grid`,`contents`,`list-item`,`hidden`],sr:[`sr-only`,`not-sr-only`],float:[{float:[`right`,`left`,`none`,`start`,`end`]}],clear:[{clear:[`left`,`right`,`both`,`none`,`start`,`end`]}],isolation:[`isolate`,`isolation-auto`],"object-fit":[{object:[`contain`,`cover`,`fill`,`none`,`scale-down`]}],"object-position":[{object:x()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:[`static`,`fixed`,`absolute`,`relative`,`sticky`],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{"inset-s":T(),start:T()}],end:[{"inset-e":T(),end:T()}],"inset-bs":[{"inset-bs":T()}],"inset-be":[{"inset-be":T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:[`visible`,`invisible`,`collapse`],z:[{z:[yv,`auto`,$,Q]}],basis:[{basis:[_v,`full`,`auto`,s,...w()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[vv,_v,`auto`,`initial`,`none`,Q]}],grow:[{grow:[``,vv,$,Q]}],shrink:[{shrink:[``,vv,$,Q]}],order:[{order:[yv,`first`,`last`,`none`,$,Q]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":[`row`,`col`,`dense`,`row-dense`,`col-dense`]}],"auto-cols":[{"auto-cols":ee()}],"auto-rows":[{"auto-rows":ee()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...te(),`normal`]}],"justify-items":[{"justify-items":[...ne(),`normal`]}],"justify-self":[{"justify-self":[`auto`,...ne()]}],"align-content":[{content:[`normal`,...te()]}],"align-items":[{items:[...ne(),{baseline:[``,`last`]}]}],"align-self":[{self:[`auto`,...ne(),{baseline:[``,`last`]}]}],"place-content":[{"place-content":te()}],"place-items":[{"place-items":[...ne(),`baseline`]}],"place-self":[{"place-self":[`auto`,...ne()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pbs:[{pbs:w()}],pbe:[{pbe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:k()}],mx:[{mx:k()}],my:[{my:k()}],ms:[{ms:k()}],me:[{me:k()}],mbs:[{mbs:k()}],mbe:[{mbe:k()}],mt:[{mt:k()}],mr:[{mr:k()}],mb:[{mb:k()}],ml:[{ml:k()}],"space-x":[{"space-x":w()}],"space-x-reverse":[`space-x-reverse`],"space-y":[{"space-y":w()}],"space-y-reverse":[`space-y-reverse`],size:[{size:A()}],"inline-size":[{inline:[`auto`,...j()]}],"min-inline-size":[{"min-inline":[`auto`,...j()]}],"max-inline-size":[{"max-inline":[`none`,...j()]}],"block-size":[{block:[`auto`,...M()]}],"min-block-size":[{"min-block":[`auto`,...M()]}],"max-block-size":[{"max-block":[`none`,...M()]}],w:[{w:[s,`screen`,...A()]}],"min-w":[{"min-w":[s,`screen`,`none`,...A()]}],"max-w":[{"max-w":[s,`screen`,`none`,`prose`,{screen:[o]},...A()]}],h:[{h:[`screen`,`lh`,...A()]}],"min-h":[{"min-h":[`screen`,`lh`,`none`,...A()]}],"max-h":[{"max-h":[`screen`,`lh`,...A()]}],"font-size":[{text:[`base`,n,Lv,Av]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,Uv,Mv]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,bv,Q]}],"font-family":[{font:[Rv,Nv,t]}],"font-features":[{"font-features":[Q]}],"fvn-normal":[`normal-nums`],"fvn-ordinal":[`ordinal`],"fvn-slashed-zero":[`slashed-zero`],"fvn-figure":[`lining-nums`,`oldstyle-nums`],"fvn-spacing":[`proportional-nums`,`tabular-nums`],"fvn-fraction":[`diagonal-fractions`,`stacked-fractions`],tracking:[{tracking:[i,$,Q]}],"line-clamp":[{"line-clamp":[vv,`none`,$,jv]}],leading:[{leading:[a,...w()]}],"list-image":[{"list-image":[`none`,$,Q]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,$,Q]}],"text-alignment":[{text:[`left`,`center`,`right`,`justify`,`start`,`end`]}],"placeholder-color":[{placeholder:N()}],"text-color":[{text:N()}],"text-decoration":[`underline`,`overline`,`line-through`,`no-underline`],"text-decoration-style":[{decoration:[...L(),`wavy`]}],"text-decoration-thickness":[{decoration:[vv,`from-font`,`auto`,$,Av]}],"text-decoration-color":[{decoration:N()}],"underline-offset":[{"underline-offset":[vv,`auto`,$,Q]}],"text-transform":[`uppercase`,`lowercase`,`capitalize`,`normal-case`],"text-overflow":[`truncate`,`text-ellipsis`,`text-clip`],"text-wrap":[{text:[`wrap`,`nowrap`,`balance`,`pretty`]}],indent:[{indent:w()}],"tab-size":[{tab:[yv,$,Q]}],"vertical-align":[{align:[`baseline`,`top`,`middle`,`bottom`,`text-top`,`text-bottom`,`sub`,`super`,$,Q]}],whitespace:[{whitespace:[`normal`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]}],break:[{break:[`normal`,`words`,`all`,`keep`]}],wrap:[{wrap:[`break-word`,`anywhere`,`normal`]}],hyphens:[{hyphens:[`none`,`manual`,`auto`]}],content:[{content:[`none`,$,Q]}],"bg-attachment":[{bg:[`fixed`,`local`,`scroll`]}],"bg-clip":[{"bg-clip":[`border`,`padding`,`content`,`text`]}],"bg-origin":[{"bg-origin":[`border`,`padding`,`content`]}],"bg-position":[{bg:P()}],"bg-repeat":[{bg:F()}],"bg-size":[{bg:re()}],"bg-image":[{bg:[`none`,{linear:[{to:[`t`,`tr`,`r`,`br`,`b`,`bl`,`l`,`tl`]},yv,$,Q],radial:[``,$,Q],conic:[yv,$,Q]},Vv,Fv]}],"bg-color":[{bg:N()}],"gradient-from-pos":[{from:ie()}],"gradient-via-pos":[{via:ie()}],"gradient-to-pos":[{to:ie()}],"gradient-from":[{from:N()}],"gradient-via":[{via:N()}],"gradient-to":[{to:N()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:ae()}],"border-w-x":[{"border-x":ae()}],"border-w-y":[{"border-y":ae()}],"border-w-s":[{"border-s":ae()}],"border-w-e":[{"border-e":ae()}],"border-w-bs":[{"border-bs":ae()}],"border-w-be":[{"border-be":ae()}],"border-w-t":[{"border-t":ae()}],"border-w-r":[{"border-r":ae()}],"border-w-b":[{"border-b":ae()}],"border-w-l":[{"border-l":ae()}],"divide-x":[{"divide-x":ae()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":ae()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...L(),`hidden`,`none`]}],"divide-style":[{divide:[...L(),`hidden`,`none`]}],"border-color":[{border:N()}],"border-color-x":[{"border-x":N()}],"border-color-y":[{"border-y":N()}],"border-color-s":[{"border-s":N()}],"border-color-e":[{"border-e":N()}],"border-color-bs":[{"border-bs":N()}],"border-color-be":[{"border-be":N()}],"border-color-t":[{"border-t":N()}],"border-color-r":[{"border-r":N()}],"border-color-b":[{"border-b":N()}],"border-color-l":[{"border-l":N()}],"divide-color":[{divide:N()}],"outline-style":[{outline:[...L(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[vv,$,Q]}],"outline-w":[{outline:[``,vv,Lv,Av]}],"outline-color":[{outline:N()}],shadow:[{shadow:[``,`none`,u,Hv,Iv]}],"shadow-color":[{shadow:N()}],"inset-shadow":[{"inset-shadow":[`none`,d,Hv,Iv]}],"inset-shadow-color":[{"inset-shadow":N()}],"ring-w":[{ring:ae()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:N()}],"ring-offset-w":[{"ring-offset":[vv,Av]}],"ring-offset-color":[{"ring-offset":N()}],"inset-ring-w":[{"inset-ring":ae()}],"inset-ring-color":[{"inset-ring":N()}],"text-shadow":[{"text-shadow":[`none`,f,Hv,Iv]}],"text-shadow-color":[{"text-shadow":N()}],opacity:[{opacity:[vv,$,Q]}],"mix-blend":[{"mix-blend":[...oe(),`plus-darker`,`plus-lighter`]}],"bg-blend":[{"bg-blend":oe()}],"mask-clip":[{"mask-clip":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]},`mask-no-clip`],"mask-composite":[{mask:[`add`,`subtract`,`intersect`,`exclude`]}],"mask-image-linear-pos":[{"mask-linear":[vv]}],"mask-image-linear-from-pos":[{"mask-linear-from":se()}],"mask-image-linear-to-pos":[{"mask-linear-to":se()}],"mask-image-linear-from-color":[{"mask-linear-from":N()}],"mask-image-linear-to-color":[{"mask-linear-to":N()}],"mask-image-t-from-pos":[{"mask-t-from":se()}],"mask-image-t-to-pos":[{"mask-t-to":se()}],"mask-image-t-from-color":[{"mask-t-from":N()}],"mask-image-t-to-color":[{"mask-t-to":N()}],"mask-image-r-from-pos":[{"mask-r-from":se()}],"mask-image-r-to-pos":[{"mask-r-to":se()}],"mask-image-r-from-color":[{"mask-r-from":N()}],"mask-image-r-to-color":[{"mask-r-to":N()}],"mask-image-b-from-pos":[{"mask-b-from":se()}],"mask-image-b-to-pos":[{"mask-b-to":se()}],"mask-image-b-from-color":[{"mask-b-from":N()}],"mask-image-b-to-color":[{"mask-b-to":N()}],"mask-image-l-from-pos":[{"mask-l-from":se()}],"mask-image-l-to-pos":[{"mask-l-to":se()}],"mask-image-l-from-color":[{"mask-l-from":N()}],"mask-image-l-to-color":[{"mask-l-to":N()}],"mask-image-x-from-pos":[{"mask-x-from":se()}],"mask-image-x-to-pos":[{"mask-x-to":se()}],"mask-image-x-from-color":[{"mask-x-from":N()}],"mask-image-x-to-color":[{"mask-x-to":N()}],"mask-image-y-from-pos":[{"mask-y-from":se()}],"mask-image-y-to-pos":[{"mask-y-to":se()}],"mask-image-y-from-color":[{"mask-y-from":N()}],"mask-image-y-to-color":[{"mask-y-to":N()}],"mask-image-radial":[{"mask-radial":[$,Q]}],"mask-image-radial-from-pos":[{"mask-radial-from":se()}],"mask-image-radial-to-pos":[{"mask-radial-to":se()}],"mask-image-radial-from-color":[{"mask-radial-from":N()}],"mask-image-radial-to-color":[{"mask-radial-to":N()}],"mask-image-radial-shape":[{"mask-radial":[`circle`,`ellipse`]}],"mask-image-radial-size":[{"mask-radial":[{closest:[`side`,`corner`],farthest:[`side`,`corner`]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[vv]}],"mask-image-conic-from-pos":[{"mask-conic-from":se()}],"mask-image-conic-to-pos":[{"mask-conic-to":se()}],"mask-image-conic-from-color":[{"mask-conic-from":N()}],"mask-image-conic-to-color":[{"mask-conic-to":N()}],"mask-mode":[{mask:[`alpha`,`luminance`,`match`]}],"mask-origin":[{"mask-origin":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]}],"mask-position":[{mask:P()}],"mask-repeat":[{mask:F()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":[`alpha`,`luminance`]}],"mask-image":[{mask:[`none`,$,Q]}],filter:[{filter:[``,`none`,$,Q]}],blur:[{blur:ce()}],brightness:[{brightness:[vv,$,Q]}],contrast:[{contrast:[vv,$,Q]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,Hv,Iv]}],"drop-shadow-color":[{"drop-shadow":N()}],grayscale:[{grayscale:[``,vv,$,Q]}],"hue-rotate":[{"hue-rotate":[vv,$,Q]}],invert:[{invert:[``,vv,$,Q]}],saturate:[{saturate:[vv,$,Q]}],sepia:[{sepia:[``,vv,$,Q]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,$,Q]}],"backdrop-blur":[{"backdrop-blur":ce()}],"backdrop-brightness":[{"backdrop-brightness":[vv,$,Q]}],"backdrop-contrast":[{"backdrop-contrast":[vv,$,Q]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,vv,$,Q]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[vv,$,Q]}],"backdrop-invert":[{"backdrop-invert":[``,vv,$,Q]}],"backdrop-opacity":[{"backdrop-opacity":[vv,$,Q]}],"backdrop-saturate":[{"backdrop-saturate":[vv,$,Q]}],"backdrop-sepia":[{"backdrop-sepia":[``,vv,$,Q]}],"border-collapse":[{border:[`collapse`,`separate`]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:[`auto`,`fixed`]}],caption:[{caption:[`top`,`bottom`]}],transition:[{transition:[``,`all`,`colors`,`opacity`,`shadow`,`transform`,`none`,$,Q]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[vv,`initial`,$,Q]}],ease:[{ease:[`linear`,`initial`,_,$,Q]}],delay:[{delay:[vv,$,Q]}],animate:[{animate:[`none`,v,$,Q]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,$,Q]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:le()}],"rotate-x":[{"rotate-x":le()}],"rotate-y":[{"rotate-y":le()}],"rotate-z":[{"rotate-z":le()}],scale:[{scale:ue()}],"scale-x":[{"scale-x":ue()}],"scale-y":[{"scale-y":ue()}],"scale-z":[{"scale-z":ue()}],"scale-3d":[`scale-3d`],skew:[{skew:de()}],"skew-x":[{"skew-x":de()}],"skew-y":[{"skew-y":de()}],transform:[{transform:[$,Q,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:fe()}],"translate-x":[{"translate-x":fe()}],"translate-y":[{"translate-y":fe()}],"translate-z":[{"translate-z":fe()}],"translate-none":[`translate-none`],zoom:[{zoom:[yv,$,Q]}],accent:[{accent:N()}],appearance:[{appearance:[`none`,`auto`]}],"caret-color":[{caret:N()}],"color-scheme":[{scheme:[`normal`,`dark`,`light`,`light-dark`,`only-dark`,`only-light`]}],cursor:[{cursor:[`auto`,`default`,`pointer`,`wait`,`text`,`move`,`help`,`not-allowed`,`none`,`context-menu`,`progress`,`cell`,`crosshair`,`vertical-text`,`alias`,`copy`,`no-drop`,`grab`,`grabbing`,`all-scroll`,`col-resize`,`row-resize`,`n-resize`,`e-resize`,`s-resize`,`w-resize`,`ne-resize`,`nw-resize`,`se-resize`,`sw-resize`,`ew-resize`,`ns-resize`,`nesw-resize`,`nwse-resize`,`zoom-in`,`zoom-out`,$,Q]}],"field-sizing":[{"field-sizing":[`fixed`,`content`]}],"pointer-events":[{"pointer-events":[`auto`,`none`]}],resize:[{resize:[`none`,``,`y`,`x`]}],"scroll-behavior":[{scroll:[`auto`,`smooth`]}],"scrollbar-thumb-color":[{"scrollbar-thumb":N()}],"scrollbar-track-color":[{"scrollbar-track":N()}],"scrollbar-gutter":[{"scrollbar-gutter":[`auto`,`stable`,`both`]}],"scrollbar-w":[{scrollbar:[`auto`,`thin`,`none`]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mbs":[{"scroll-mbs":w()}],"scroll-mbe":[{"scroll-mbe":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pbs":[{"scroll-pbs":w()}],"scroll-pbe":[{"scroll-pbe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:[`start`,`end`,`center`,`align-none`]}],"snap-stop":[{snap:[`normal`,`always`]}],"snap-type":[{snap:[`none`,`x`,`y`,`both`]}],"snap-strictness":[{snap:[`mandatory`,`proximity`]}],touch:[{touch:[`auto`,`none`,`manipulation`]}],"touch-x":[{"touch-pan":[`x`,`left`,`right`]}],"touch-y":[{"touch-pan":[`y`,`up`,`down`]}],"touch-pz":[`touch-pinch-zoom`],select:[{select:[`none`,`text`,`all`,`auto`]}],"will-change":[{"will-change":[`auto`,`scroll`,`contents`,`transform`,$,Q]}],fill:[{fill:[`none`,...N()]}],"stroke-w":[{stroke:[vv,Lv,Av,jv]}],stroke:[{stroke:[`none`,...N()]}],"forced-color-adjust":[{"forced-color-adjust":[`auto`,`none`]}]},conflictingClassGroups:{"container-named":[`container-type`],overflow:[`overflow-x`,`overflow-y`],overscroll:[`overscroll-x`,`overscroll-y`],inset:[`inset-x`,`inset-y`,`inset-bs`,`inset-be`,`start`,`end`,`top`,`right`,`bottom`,`left`],"inset-x":[`right`,`left`],"inset-y":[`top`,`bottom`],flex:[`basis`,`grow`,`shrink`],gap:[`gap-x`,`gap-y`],p:[`px`,`py`,`ps`,`pe`,`pbs`,`pbe`,`pt`,`pr`,`pb`,`pl`],px:[`pr`,`pl`],py:[`pt`,`pb`],m:[`mx`,`my`,`ms`,`me`,`mbs`,`mbe`,`mt`,`mr`,`mb`,`ml`],mx:[`mr`,`ml`],my:[`mt`,`mb`],size:[`w`,`h`],"font-size":[`leading`],"fvn-normal":[`fvn-ordinal`,`fvn-slashed-zero`,`fvn-figure`,`fvn-spacing`,`fvn-fraction`],"fvn-ordinal":[`fvn-normal`],"fvn-slashed-zero":[`fvn-normal`],"fvn-figure":[`fvn-normal`],"fvn-spacing":[`fvn-normal`],"fvn-fraction":[`fvn-normal`],"line-clamp":[`display`,`overflow`],rounded:[`rounded-s`,`rounded-e`,`rounded-t`,`rounded-r`,`rounded-b`,`rounded-l`,`rounded-ss`,`rounded-se`,`rounded-ee`,`rounded-es`,`rounded-tl`,`rounded-tr`,`rounded-br`,`rounded-bl`],"rounded-s":[`rounded-ss`,`rounded-es`],"rounded-e":[`rounded-se`,`rounded-ee`],"rounded-t":[`rounded-tl`,`rounded-tr`],"rounded-r":[`rounded-tr`,`rounded-br`],"rounded-b":[`rounded-br`,`rounded-bl`],"rounded-l":[`rounded-tl`,`rounded-bl`],"border-spacing":[`border-spacing-x`,`border-spacing-y`],"border-w":[`border-w-x`,`border-w-y`,`border-w-s`,`border-w-e`,`border-w-bs`,`border-w-be`,`border-w-t`,`border-w-r`,`border-w-b`,`border-w-l`],"border-w-x":[`border-w-r`,`border-w-l`],"border-w-y":[`border-w-t`,`border-w-b`],"border-color":[`border-color-x`,`border-color-y`,`border-color-s`,`border-color-e`,`border-color-bs`,`border-color-be`,`border-color-t`,`border-color-r`,`border-color-b`,`border-color-l`],"border-color-x":[`border-color-r`,`border-color-l`],"border-color-y":[`border-color-t`,`border-color-b`],translate:[`translate-x`,`translate-y`,`translate-none`],"translate-none":[`translate`,`translate-x`,`translate-y`,`translate-z`],"scroll-m":[`scroll-mx`,`scroll-my`,`scroll-ms`,`scroll-me`,`scroll-mbs`,`scroll-mbe`,`scroll-mt`,`scroll-mr`,`scroll-mb`,`scroll-ml`],"scroll-mx":[`scroll-mr`,`scroll-ml`],"scroll-my":[`scroll-mt`,`scroll-mb`],"scroll-p":[`scroll-px`,`scroll-py`,`scroll-ps`,`scroll-pe`,`scroll-pbs`,`scroll-pbe`,`scroll-pt`,`scroll-pr`,`scroll-pb`,`scroll-pl`],"scroll-px":[`scroll-pr`,`scroll-pl`],"scroll-py":[`scroll-pt`,`scroll-pb`],touch:[`touch-x`,`touch-y`,`touch-pz`],"touch-x":[`touch`],"touch-y":[`touch`],"touch-pz":[`touch`]},conflictingClassGroupModifiers:{"font-size":[`leading`]},postfixLookupClassGroups:[`container-type`],orderSensitiveModifiers:[`*`,`**`,`after`,`backdrop`,`before`,`details-content`,`file`,`first-letter`,`first-line`,`marker`,`placeholder`,`selection`]}});function ty(...e){return ey(T_(e))}var ny=O_(`inline-flex h-9 shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-md border px-3 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400 disabled:pointer-events-none disabled:opacity-50 dark:focus-visible:ring-zinc-500`,{variants:{variant:{primary:`border-slate-900 bg-slate-950 text-white hover:bg-slate-800 dark:border-zinc-100 dark:bg-zinc-50 dark:text-zinc-950 dark:hover:bg-zinc-200`,secondary:`border-slate-200 bg-white text-slate-900 hover:bg-slate-50 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-100 dark:hover:bg-zinc-900`,ghost:`border-transparent bg-transparent text-slate-700 hover:bg-slate-100 dark:text-zinc-300 dark:hover:bg-zinc-900`},size:{sm:`h-8 px-2 text-xs`,md:`h-9 px-3 text-sm`,icon:`h-9 w-9 px-0`}},defaultVariants:{variant:`secondary`,size:`md`}});function ry({className:e,variant:t,size:n,...r}){return(0,B.jsx)(`button`,{className:ty(ny({variant:t,size:n}),e),type:`button`,...r})}function iy({className:e,...t}){return(0,B.jsx)(`section`,{className:ty(`rounded-lg border border-slate-200/80 bg-white/95 text-slate-950 shadow-[0_1px_2px_rgba(15,23,42,0.04)] dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50`,e),...t})}function ay({className:e,...t}){return(0,B.jsx)(`div`,{className:ty(`p-4 pt-0`,e),...t})}var oy=[`codex`,`claude`,`kiro`,`trae`,`coco`,`openai`,`anthropic`],sy=new Set([`acp`,`status_projection`]);function cy(e){let t=e.trim().toLowerCase().replace(/_/gu,`-`);for(let e of oy)if(t===e||t.startsWith(`${e}-`))return e;return t}function ly(e,t){let n=t?.trim().toLowerCase()??``;return n.length>0&&!sy.has(n)?cy(n):cy(e)}var uy={stop:`ready_stop`,resume:`resume_review`,delete:`delete_review`},dy=e=>typeof e==`string`&&e.trim().length>0;function fy(e){let t={schemaVersion:`action_review_plan_v0`,proposalId:e.proposal_id,sourceFingerprint:e.expected_state_fingerprint},n=(e,n)=>({...t,interaction:e,reason:n,canApply:!1}),r=e.action_kind===`goal.lifecycle`;if(r&&e.gate!=null||e.status===`gated`)return n(`gated`,`authority_gate`);if(r&&e.stale!=null||e.status===`stale`)return n(`refresh`,`stale_proposal`);if(e.status===`applied`)return e.receipt?.projection_verified===!0&&(e.action_kind!==`operation.execute`||e.operation?.result_delivery!=null)?n(`completed`,`readback_verified`):n(`repair`,`readback_unverified`);if(e.status===`applying`)return n(`pending`,`apply_pending`);if(e.status===`failed`||e.error!=null)return n(`repair`,`apply_failed`);if(e.status!==`preview_ready`&&e.status!==`deferred`)return n(`inactive`,`inactive_proposal`);let i=(e,n=!0)=>({...t,interaction:`review`,reason:e,canApply:n});if(e.action_kind!==`goal.lifecycle`)return i(e.permission_classification===`protected`?`protected_action`:`action_review`);if(!(dy(e.proposal_id)&&dy(e.expected_state_fingerprint)&&Oh.shape.validation_evidence.safeParse(e.validation_evidence).success&&e.validation_evidence.length>0&&e.available_transitions.includes(`apply`)))return n(`refresh`,`incomplete_proposal`);let{operation:a,goal_id:o}=e.normalized_parameters;if(!dy(o)||e.context.goal_id!=null&&e.context.goal_id!==o)return n(`refresh`,`incomplete_proposal`);if(a!==`stop`&&a!==`resume`&&a!==`delete`)return i(`unknown_action`,!1);if(e.permission_classification===`protected`)return i(`protected_action`);if(e.permission_classification!==`durable_write`)return i(`unknown_permission`,!1);let s=uy[a];return s===`ready_stop`&&e.status===`preview_ready`?{...t,interaction:`direct`,reason:s,canApply:!0}:i(s===`ready_stop`?`action_review`:s)}function py(e){if(e.error_code===`action_stale`||e.error_code===`action_conflict`)return!0;let t=e.proposal;return typeof t==`object`&&!!t&&`status`in t&&t.status===`stale`}function my(e){return{blockingTodoCount:e.blockingTodoCount,goalNotifications:e.goalNotifications,goals:e.goals,openUserTodoCount:e.openUserTodoCount,systemHealth:e.systemHealth,attentionHistory:e.attentionHistory,userTodos:e.userTodos,workers:e.workers}}function hy(e,t){return e.goals.find(e=>e.goalId===t)?.title??t}function gy(e){return e.activationState===`stopped`||e.state===`已停止`?`stopped`:e.state===`已完成`?`history`:e.needsYou||e.state===`等你`?`needs_you`:e.state===`推进中`||e.state===`需修复`?`running`:e.state===`安静运行`?`observing`:`scheduled`}function _y(e){let t=e;return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function vy(e){return`$${e.toFixed(2)}`}function yy(e){let t=e;return t>=36e5?`${(t/36e5).toFixed(1)}h`:t>=6e4?`${(t/6e4).toFixed(1)}m`:t>=1e3?`${Math.round(t/1e3)}s`:`${t}ms`}function by(e,t,n){return e==null?t:n(e)}function xy(e){return!!(e&&[e.tokens24h,e.tokens7d,e.costUsd24h,e.costUsd7d,e.durationMs24h,e.durationMs7d].some(e=>e!=null))}function Sy(e,t){if(!xy(e))return null;let n=(e,n,r,i)=>{let a=[n==null?null:`${_y(n)} ${t.tokens}`,r==null?null:`${t.cost}: ${vy(r)}`,i==null?null:`${t.duration}: ${yy(i)}`].filter(e=>e!==null);return a.length?`${e} ${a.join(` · `)}`:null};return n(t.period7d,e.tokens7d,e.costUsd7d,e.durationMs7d)??n(t.period24h,e.tokens24h,e.costUsd24h,e.durationMs24h)}function Cy({ariaLabel:e,className:t,icon:n,onChange:r,options:i,prefixLabel:a,value:o}){let s=(0,z.useId)(),c=(0,z.useRef)(null),l=(0,z.useRef)(null),u=(0,z.useRef)(new Map),[d,f]=(0,z.useState)(!1),[p,m]=(0,z.useState)(o),h=i.find(e=>e.value===o)??i[0],g=i.filter(e=>!e.disabled);(0,z.useEffect)(()=>{if(!d)return;let e=e=>{c.current?.contains(e.target)||f(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[d]),(0,z.useEffect)(()=>{d&&u.current.get(p)?.focus()},[p,d]);function _(e){m(e)}function v(e=`selected`){let t=e===`last`?g.at(-1):g[0],n=e===`selected`&&h&&!h.disabled?h:t;n&&(f(!0),_(n.value))}function y({restoreFocus:e=!1}={}){f(!1),e&&l.current?.focus()}function b(e){e.disabled||(r(e.value),y({restoreFocus:!0}))}function x(e){if(!g.length)return;let t=g.findIndex(e=>e.value===p),n=t<0?0:(t+e+g.length)%g.length;_(g[n].value)}function S(e){e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),v(`selected`)):e.key===`ArrowUp`&&(e.preventDefault(),v(`last`))}function C(e,t){if(e.key===`ArrowDown`)e.preventDefault(),x(1);else if(e.key===`ArrowUp`)e.preventDefault(),x(-1);else if(e.key===`Home`)e.preventDefault(),g[0]&&_(g[0].value);else if(e.key===`End`){e.preventDefault();let t=g.at(-1);t&&_(t.value)}else e.key===`Enter`||e.key===` `?(e.preventDefault(),b(t)):e.key===`Escape`?(e.preventDefault(),y({restoreFocus:!0})):e.key===`Tab`&&y()}let w;return(0,B.jsxs)(`div`,{className:`personal-select${t?` ${t}`:``}`,ref:c,children:[(0,B.jsxs)(`button`,{"aria-controls":s,"aria-expanded":d,"aria-haspopup":`listbox`,"aria-label":e,className:`personal-select-trigger`,"data-value":o,onClick:()=>d?y():v(),onKeyDown:S,ref:l,role:`combobox`,type:`button`,children:[n?(0,B.jsx)(`span`,{className:`personal-select-icon`,children:n}):null,(0,B.jsxs)(`span`,{className:`personal-select-value`,children:[a?(0,B.jsx)(`small`,{children:a}):null,(0,B.jsx)(`span`,{children:h?.label??o})]}),(0,B.jsx)(tm,{"aria-hidden":!0,className:d?`is-open`:void 0,size:14})]}),d?(0,B.jsx)(`div`,{"aria-label":e,className:`personal-select-listbox`,id:s,role:`listbox`,children:i.map(e=>{let t=e.group&&e.group!==w;return w=e.group,(0,B.jsxs)(`div`,{className:`personal-select-option-wrap`,children:[t?(0,B.jsx)(`div`,{className:`personal-select-group-label`,children:e.group}):null,(0,B.jsxs)(`button`,{"aria-disabled":e.disabled||void 0,"aria-selected":e.value===o,className:`personal-select-option`,disabled:e.disabled,id:`${s}-${e.value.replace(/[^a-z0-9_-]/gi,`-`)}`,onClick:()=>b(e),onFocus:()=>m(e.value),onKeyDown:t=>C(t,e),ref:t=>{t?u.current.set(e.value,t):u.current.delete(e.value)},role:`option`,tabIndex:e.value===p?0:-1,type:`button`,children:[(0,B.jsx)(`span`,{children:e.label}),e.value===o?(0,B.jsx)(em,{"aria-hidden":!0,size:15}):null]})]},e.value)})}):null]})}function wy({agents:e,managerChatOpen:t,mobileNavigationOpen:n,onOpenGoalCapabilities:r,onOpenGoalDetail:i,onOpenManagerChat:a,onRefresh:o,onOpenNavigation:s,onSelectGoalTab:c,onSelectAgent:l,onReturnManagerHome:u,refreshState:d,readOnlySourceLabel:f,selectedAgentId:p,selectedGoal:m,selectedGoalTab:h}){let{locale:g,t:_}=Ji(),[v,y]=(0,z.useState)(!1),b=(0,z.useRef)(null),x=(0,z.useRef)(null);(0,z.useEffect)(()=>{if(!v)return;function e(e){x.current?.contains(e.target)||y(!1)}function t(e){e.key===`Escape`&&(y(!1),b.current?.focus())}return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[v]),(0,z.useEffect)(()=>y(!1),[m?.goalId]);function S(e){y(!1),e?.()}let C=m?Sy(m.usage,{cost:_(`drawer.costShort`),duration:_(`drawer.durationShort`),period24h:_(`drawer.period24h`),period7d:_(`drawer.period7d`),tokens:_(`drawer.tokensShort`)}):null;return(0,B.jsxs)(`header`,{className:`personal-channel-header`,children:[(0,B.jsx)(`button`,{"aria-expanded":n??!1,"aria-label":_(`header.openGoalNavigation`),className:`personal-icon-button personal-mobile-menu`,onClick:s,type:`button`,children:(0,B.jsx)(Tm,{size:18})}),(0,B.jsxs)(`div`,{className:`personal-channel-title`,children:[(0,B.jsx)(`h1`,{children:m?.title??_(`header.manager`)}),m?(0,B.jsx)(`p`,{children:m.loadState?_(m.loadState===`error`?`startup.goalError`:`startup.goalLoading`):`${m.agentLaneCount&&m.agentLaneCount>1?_(`header.workAgentCount`,{count:m.agentLaneCount}):m.agentLabel??m.agentId} · ${m.loadState?_(m.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Yi(m.state,g)}${C?` · ${C}`:``} · ${m.nextSentence}`}):null]}),m?(0,B.jsxs)(`nav`,{"aria-label":_(`header.goalView`),className:`personal-goal-tabs`,children:[(0,B.jsx)(`button`,{"aria-current":h===`chat`?`page`:void 0,onClick:()=>c(`chat`),type:`button`,children:_(`header.chat`)}),(0,B.jsx)(`button`,{"aria-current":h===`tasks`?`page`:void 0,onClick:()=>c(`tasks`),type:`button`,children:_(`header.tasks`)}),(0,B.jsx)(`button`,{"aria-current":h===`files`?`page`:void 0,onClick:()=>c(`files`),type:`button`,children:_(`header.files`)})]}):(0,B.jsxs)(`nav`,{"aria-label":_(`header.managerView`),className:`personal-goal-tabs`,children:[(0,B.jsx)(`button`,{"aria-current":t?void 0:`page`,onClick:u,type:`button`,children:_(`header.managerOverview`)}),(0,B.jsx)(`button`,{"aria-current":t?`page`:void 0,onClick:a,type:`button`,children:_(`header.chat`)})]}),(0,B.jsxs)(`div`,{className:`personal-channel-actions`,children:[m&&i&&r?(0,B.jsxs)(`div`,{className:`personal-goal-tools`,ref:x,children:[(0,B.jsxs)(`button`,{"aria-expanded":v,"aria-haspopup":`menu`,"aria-label":_(`header.goalSettingsDescription`),className:`personal-goal-tools-trigger`,onClick:()=>y(e=>!e),ref:b,title:_(`header.goalSettingsDescription`),type:`button`,children:[(0,B.jsx)(Gm,{"aria-hidden":!0,size:16}),(0,B.jsx)(`span`,{children:_(`header.goalSettings`)}),(0,B.jsx)(tm,{"aria-hidden":!0,size:13})]}),v?(0,B.jsxs)(`fieldset`,{"aria-label":_(`header.goalSettings`),className:`personal-goal-tools-menu`,children:[(0,B.jsxs)(`button`,{onClick:()=>S(i),type:`button`,children:[(0,B.jsx)(ym,{"aria-hidden":!0,size:17}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:_(`header.goalDetails`)})})]}),(0,B.jsxs)(`button`,{onClick:()=>S(r),type:`button`,children:[(0,B.jsx)(Gm,{"aria-hidden":!0,size:17}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:_(`header.goalCapabilities`)})})]})]}):null]}):null,f?(0,B.jsxs)(`span`,{className:`personal-read-only-source`,title:_(`header.readOnlySourceDescription`,{source:f}),children:[(0,B.jsx)(pm,{size:15}),f,(0,B.jsx)(`small`,{children:_(`common.readOnly`)})]}):(0,B.jsx)(Cy,{ariaLabel:_(`header.selectChatRuntime`),className:`personal-agent-select`,icon:(0,B.jsx)(Zp,{size:16}),onChange:l,options:e.map(e=>({disabled:!e.available,label:`${e.label}${e.available?``:` · ${_(`header.agentUnavailable`)}`}`,value:e.agentId})),prefixLabel:_(`header.chatRuntime`),value:p}),(0,B.jsxs)(`span`,{className:`personal-live-indicator`,children:[(0,B.jsx)(`i`,{}),_(`header.live`)]}),o?(0,B.jsxs)(`span`,{className:`personal-refresh-control is-${d??`idle`}`,children:[d===`loading`?(0,B.jsx)(`small`,{children:_(`header.refreshing`)}):d===`done`?(0,B.jsx)(`small`,{children:_(`header.refreshDone`)}):d===`error`?(0,B.jsx)(`small`,{children:_(`header.refreshFailed`)}):null,(0,B.jsx)(`button`,{"aria-label":_(d===`loading`?`header.refreshing`:`header.refresh`),className:`personal-icon-button`,disabled:d===`loading`,onClick:o,type:`button`,children:(0,B.jsx)(Im,{className:d===`loading`?`is-spinning`:void 0,size:17})})]}):null]})]})}function Ty({attention:e,onSelect:t}){let{t:n}=Ji(),r=Zi(e.updatedAt,n);return(0,B.jsxs)(`button`,{className:`personal-timeline-row personal-attention-row`,"data-testid":`personal-browse-row`,onClick:t,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-row-icon is-attention`,children:(0,B.jsx)(im,{size:18})}),(0,B.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,B.jsxs)(`small`,{children:[e.goalTitle??e.goalId,` · `,n(`home.lane.needsYou`),r?` · ${n(`tasks.waitingAge`,{age:r})}`:``]}),(0,B.jsx)(`strong`,{children:e.text})]}),(0,B.jsx)(`span`,{className:`personal-priority-dot is-${e.priority??(e.blocking?`high`:`medium`)}`}),(0,B.jsx)(`span`,{className:`personal-row-status ${e.blocking?`is-blocking`:`is-pending`}`,children:e.blocking?n(`tasks.blocked`):n(`tasks.pending`)}),(0,B.jsx)(nm,{size:17})]})}var Ey=/(`[^`\n]+`)|(\*\*[^*\n]+(\*[^*\n]*)?\*\*)|(\[[^\]\n]{1,120}\]\(https?:\/\/[^)\s]+\))/g;function Dy(e,t){let n=[],r=0,i=0;for(let a of e.matchAll(Ey)){let o=a.index??0;o>r&&n.push(e.slice(r,o));let s=a[0],c=`${t}-i${i++}`;if(s.startsWith("`"))n.push((0,B.jsx)(`code`,{className:`personal-md-code`,children:s.slice(1,-1)},c));else if(s.startsWith(`**`))n.push((0,B.jsx)(`strong`,{children:s.slice(2,-2)},c));else{let e=s.indexOf(`](`),t=s.slice(1,e),r=s.slice(e+2,-1);n.push((0,B.jsx)(`a`,{className:`personal-md-link`,href:r,rel:`noreferrer`,target:`_blank`,children:t},c))}r=o+s.length}return r{r.length>0&&(n.push({type:`paragraph`,lines:r}),r=[])},a=0;for(;a{let n=`b${t}`;if(e.type===`code`)return(0,B.jsx)(`pre`,{className:`personal-md-pre`,children:(0,B.jsx)(`code`,{children:e.text})},n);if(e.type===`heading`)return(0,B.jsx)(`p`,{className:`personal-md-heading is-h${e.level}`,children:Dy(e.text,n)},n);if(e.type===`list`){let t=e.items.map((e,t)=>(0,B.jsx)(`li`,{children:Dy(e,`${n}-${t}`)},`${n}-${t}`));return e.ordered?(0,B.jsx)(`ol`,{className:`personal-md-list`,children:t},n):(0,B.jsx)(`ul`,{className:`personal-md-list`,children:t},n)}return(0,B.jsx)(`p`,{children:e.lines.map((e,t)=>(0,B.jsxs)(z.Fragment,{children:[t>0?(0,B.jsx)(`br`,{}):null,Dy(e,`${n}-${t}`)]},`${n}-${t}`))},n)})})}function My({onSelect:e,output:t}){let{t:n}=Ji(),r=t.kind===`report`?gm:hm;return(0,B.jsxs)(`button`,{className:`personal-timeline-row personal-output-row`,"data-output-kind":t.kind,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-row-icon is-output`,children:(0,B.jsx)(r,{size:18})}),(0,B.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,B.jsxs)(`small`,{children:[t.goalTitle??t.goalId,` · `,t.agentLabel??`LoopX`]}),(0,B.jsx)(`strong`,{children:t.title}),t.summary?(0,B.jsx)(`span`,{children:t.summary}):null,t.report?(0,B.jsxs)(`small`,{children:[n(`files.reportDelta`,{added:t.report.addedCount,changed:t.report.changedCount}),` · `,n(`files.verifiedReport`)]}):null]}),t.createdAt?(0,B.jsx)(`time`,{children:t.createdAt}):null,(0,B.jsx)(nm,{size:17})]})}var Ny={completed:`runs.completed`,failed:`runs.failed`,interrupted:`runs.interrupted`,queued:`runs.queued`,running:`runs.running`,waiting:`runs.waiting`};function Py({onSelect:e,run:t}){let{t:n}=Ji(),r=t.totalSteps>0?Math.min(100,t.completedSteps/t.totalSteps*100):0;return(0,B.jsxs)(`button`,{"aria-label":`${n(`tasks.viewExecution`)}:${t.title}`,className:`personal-timeline-row personal-run-row`,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-row-icon is-run`,children:(0,B.jsx)(Zp,{size:18})}),(0,B.jsxs)(`span`,{className:`personal-run-identity`,children:[(0,B.jsx)(`small`,{children:t.goalTitle}),(0,B.jsx)(`strong`,{children:t.agentLabel})]}),(0,B.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,B.jsx)(`strong`,{children:t.title}),(0,B.jsx)(`small`,{children:t.latestActivity})]}),(0,B.jsxs)(`span`,{className:`personal-run-progress`,"aria-label":`${t.completedSteps}/${t.totalSteps}`,children:[(0,B.jsxs)(`small`,{children:[t.completedSteps,`/`,t.totalSteps]}),(0,B.jsx)(`i`,{children:(0,B.jsx)(`b`,{style:{width:`${r}%`}})})]}),(0,B.jsxs)(`span`,{className:`personal-row-status is-${t.status}`,children:[t.status===`running`?(0,B.jsx)(Cm,{className:`personal-spin`,size:14}):null,n(Ny[t.status])]}),t.sessionId?(0,B.jsx)(`span`,{className:`personal-run-open-label`,children:n(`tasks.viewExecution`)}):null,(0,B.jsx)(nm,{size:17})]})}function Fy({onSelect:e,schedule:t}){let{t:n}=Ji(),r=t.scheduleKind===`heartbeat`;return(0,B.jsxs)(`button`,{"aria-label":`${r?`Heartbeat`:n(`tasks.scheduled`)}:${t.label};${t.status??`active`}`,className:`personal-schedule-row`,onClick:e,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-schedule-icon`,children:r?(0,B.jsx)(Fm,{size:17}):(0,B.jsx)($p,{size:17})}),(0,B.jsxs)(`span`,{className:`personal-schedule-copy`,children:[(0,B.jsx)(`small`,{children:n(r?`schedule.heartbeat`:`schedule.monitor`)}),(0,B.jsx)(`strong`,{children:t.label}),(0,B.jsx)(`p`,{children:t.schedule??n(`schedule.summary`)})]}),(0,B.jsx)(`span`,{className:`personal-schedule-status is-${t.status??`active`}`,children:t.status===`paused`?n(`schedule.paused`):n(`schedule.active`)}),(0,B.jsx)(nm,{size:16})]})}function Iy({items:e,onSelect:t,selectedGoal:n}){let{t:r}=Ji();if(e.length===0)return(0,B.jsxs)(`div`,{className:`personal-timeline-empty`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Km,{size:20})}),(0,B.jsx)(`strong`,{children:r(n?`timeline.emptyGoal`:`timeline.emptyWorkspace`)}),(0,B.jsx)(`p`,{children:r(n?`timeline.emptyGoalDescription`:`timeline.emptyWorkspaceDescription`)})]});let i=[...e].reverse().find(e=>e.kind===`message`&&e.message.role!==`user`||e.kind===`proposal`&&[`applied`,`stale`,`error`,`gated`].includes(e.proposal.status)||e.kind===`run`&&e.run.status===`completed`),a=i?.kind===`message`?`${i.message.agentLabel??r(`header.manager`)}:${i.message.pending?r(`timeline.pending`):i.message.text}`:i?.kind===`proposal`?`${i.proposal.title}:${i.proposal.status}`:i?.kind===`run`?r(`timeline.runCompleted`,{run:i.run.title}):``,o=e.filter(e=>e.kind===`proposal`&&e.proposal.status===`gated`),s=e.filter(e=>e.kind!==`proposal`),c=e.filter(e=>e.kind===`proposal`&&e.proposal.status!==`gated`);function l(e){return e.kind===`attention`?(0,B.jsx)(Ty,{attention:e.attention,onSelect:()=>t({item:e.attention,kind:`attention`})},e.id):e.kind===`run`?(0,B.jsx)(Py,{onSelect:()=>t({item:e.run,kind:`run`}),run:e.run},e.id):e.kind===`output`?(0,B.jsx)(My,{onSelect:()=>t({item:e.output,kind:`output`}),output:e.output},e.id):e.kind===`schedule`?(0,B.jsx)(Fy,{onSelect:()=>t({item:e.schedule,kind:`schedule`}),schedule:e.schedule},e.id):e.kind===`proposal`?(0,B.jsxs)(`button`,{className:`personal-proposal-row is-${e.proposal.status}`,onClick:()=>t({item:e.proposal,kind:`proposal`}),type:`button`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Km,{size:17})}),(0,B.jsxs)(`span`,{children:[(0,B.jsxs)(`small`,{children:[e.proposal.actionKind,` · `,e.proposal.status]}),(0,B.jsx)(`strong`,{children:e.proposal.title}),(0,B.jsx)(`p`,{children:e.proposal.impact})]}),(0,B.jsx)(`b`,{children:e.proposal.status===`gated`?r(`timeline.review`):e.proposal.primaryLabel??r(`timeline.reviewAndConfirm`)})]},e.id):(0,B.jsxs)(`article`,{className:`personal-message is-${e.message.role}`,children:[e.message.role===`user`?null:(0,B.jsx)(`span`,{className:`personal-message-avatar`,children:(0,B.jsx)(Zp,{size:17})}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:e.message.role===`user`?r(`common.you`):e.message.agentLabel??r(`header.manager`)}),e.message.time?(0,B.jsx)(`time`,{children:e.message.time}):null]}),e.message.attachments?.length?(0,B.jsx)(`div`,{className:`personal-message-images`,children:e.message.attachments.map(e=>(0,B.jsx)(`img`,{alt:e.name,src:e.dataUrl},e.id))}):null,e.message.role===`user`?(0,B.jsx)(`p`,{children:e.message.text}):(0,B.jsx)(jy,{text:e.message.text}),e.message.pending?(0,B.jsx)(`span`,{className:`personal-message-pending`,children:r(`timeline.pending`)}):null]})]},e.id)}return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{"aria-atomic":`true`,"aria-live":`polite`,className:`personal-live-region`,role:`status`,children:a}),(0,B.jsxs)(`div`,{className:`personal-channel-timeline`,children:[s.map(l),o.length?(0,B.jsxs)(`details`,{className:`personal-gated-summary`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Km,{size:16})}),(0,B.jsx)(`strong`,{children:r(`timeline.waitingConfirmation`)}),(0,B.jsx)(`small`,{children:r(`timeline.gateHistory`,{count:o.length})})]}),(0,B.jsx)(`div`,{children:o.map(l)})]}):null,c.map(l)]})]})}function Ly({goal:e}){let{t}=Ji(),n={connected:t(`acceptance.connected`),mapped:t(`acceptance.mapped`),refreshed:t(`acceptance.refreshed`),adapter_inspected:t(`acceptance.inspected`),run_recorded:t(`acceptance.recorded`),reward_judged:t(`acceptance.judged`),operator_approved:t(`acceptance.approved`),controller_ready:t(`acceptance.ready`),attention_queue:t(`acceptance.attentionSource`),agent_vision:t(`acceptance.visionSource`),todo_projection:t(`acceptance.todoSource`),current_run:t(`acceptance.runSource`)},r=e=>n[e]??t(`acceptance.unknown`),i=e.acceptanceObservation,a=e.loadState||!i||i.goal_id!==e.goalId||i.coverage===`unavailable`;return(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-acceptance`,"aria-label":t(`acceptance.title`),children:[(0,B.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,B.jsx)(`h3`,{children:t(`acceptance.title`)}),(0,B.jsx)(`em`,{children:t(`common.readOnly`)})]}),(0,B.jsx)(`p`,{role:`status`,children:t(a?`acceptance.unavailable`:`acceptance.partial`)}),!a&&i?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h4`,{children:t(`acceptance.gaps`)}),i.acceptance_gaps.length?i.acceptance_gaps.map((e,n)=>(0,B.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,B.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.owner`)}),(0,B.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,B.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.observed`)}),(0,B.jsx)(`dd`,{children:e.observed_at??t(`acceptance.unknown`)})]})]})]},`${e.kind}:${e.owner}:${n}`)):(0,B.jsx)(`p`,{children:t(`acceptance.noGaps`)}),(0,B.jsx)(`h4`,{children:t(`acceptance.guards`)}),i.guards.length?i.guards.map((e,n)=>(0,B.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,B.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.owner`)}),(0,B.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),e.blocks_agent?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.agent`)}),(0,B.jsx)(`dd`,{children:e.blocks_agent})]}):null,e.todo_id?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.task`)}),(0,B.jsx)(`dd`,{children:e.todo_id})]}):null,(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,B.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.scope`)}),(0,B.jsx)(`dd`,{children:e.decision_scope??t(`acceptance.unknown`)})]})]})]},`${e.todo_id}:${n}`)):(0,B.jsx)(`p`,{children:t(`acceptance.noGuards`)}),(0,B.jsx)(`h4`,{children:t(`acceptance.next`)}),(0,B.jsx)(`p`,{children:i.next_action??t(`acceptance.unknown`)}),(0,B.jsxs)(`details`,{children:[(0,B.jsxs)(`summary`,{children:[t(`acceptance.historical_progress`),` · `,i.historical_progress.length]}),(0,B.jsx)(`p`,{children:t(`acceptance.historical`)}),i.historical_progress.map(e=>(0,B.jsxs)(`p`,{children:[(0,B.jsx)(`strong`,{children:r(e.kind)}),` · `,e.observed_at??t(`acceptance.unknown`),` `,e.evidence_refs.join(`, `)]},e.kind))]}),i.missing_sources.length?(0,B.jsxs)(`p`,{children:[t(`acceptance.missing`),` `,i.missing_sources.map(r).join(`, `)]}):null,i.truncated?(0,B.jsx)(`p`,{children:t(`acceptance.truncated`)}):null]}):null]})}function Ry({item:e,successor:t,onSelect:n}){let{t:r}=Ji(),i=e.details;return(0,B.jsxs)(`section`,{className:`personal-detail-card`,"aria-label":r(`attentionDetail.title`),children:[(0,B.jsx)(`h3`,{children:r(`attentionDetail.title`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.request`)}),(0,B.jsx)(`dd`,{children:r(i?.interaction===`decision`?`attentionDetail.decision`:`attentionDetail.unknownRequest`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`common.status`)}),(0,B.jsx)(`dd`,{children:r(`attentionDetail.${i?.lifecycle??`unknown`}`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`drawer.reason`)}),(0,B.jsx)(`dd`,{children:i?.reason??e.explanation??r(`attentionDetail.unknownReason`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Todo`}),(0,B.jsx)(`dd`,{children:e.todoId})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.targetTodo`)}),(0,B.jsx)(`dd`,{children:i?.unblocksTodoId??r(`attentionDetail.notProvided`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.targetAgent`)}),(0,B.jsx)(`dd`,{children:i?.blocksAgent??r(`attentionDetail.notProvided`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.scope`)}),(0,B.jsx)(`dd`,{children:i?.decisionScope?`${i.decisionScope.kind} · ${i.decisionScope.granularity} · ${i.decisionScope.scopeKey}`:r(`attentionDetail.notProvided`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`drawer.evidence`)}),(0,B.jsx)(`dd`,{children:i?.evidence??e.evidence??r(`drawer.decisionDefaultEvidence`)})]})]}),i?.supersededBy?(0,B.jsxs)(`p`,{children:[r(`attentionDetail.replacement`),`: `,i.supersededBy]}):null,t&&n?(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>n(t),type:`button`,children:r(`attentionDetail.openReplacement`)}):null,(0,B.jsx)(`p`,{children:r(`attentionDetail.boundary`)})]})}function zy(e){return e.replace(/\s+/gu,` `).trim()}function By(e,t){let n=RegExp(`(?:不要|不需要|无需|禁止|别|暂不|do not\\b|don't\\b|without\\b).{0,10}(?:${t.source})`,`iu`),r=RegExp(`(?:${t.source}).{0,10}(?:不要|不需要|无需|禁止|关闭)`,`iu`),i=RegExp(`disable\\b.{0,10}(?:${t.source})|(?:turn|switch|set)\\b.{0,10}(?:${t.source}).{0,10}\\boff\\b|(?:${t.source})\\s+(?:is\\s+)?disabled\\b`,`iu`);return n.test(e)||r.test(e)||i.test(e)}function Vy(e){return/(我现在该做什么|下一步|哪些\s*Goal\s*在等我|需要我|谁在等我|Agent\s*在做什么|当前进度|总结(?:今天)?进展)/iu.test(e)}function Hy(e){let t=/(怎么|如何|为什么|给.*建议|分析一下|解释|只读)/u.test(e),n=/(解决一下|修复一下|处理一下|执行一下|改一下|跑(?:一下)?测试|rebase|push|提交|推送)/iu.test(e);return!t&&n&&/(帮我|请|给我|直接|现在|开始|bytedcli|codebase|git|rebase|push|提交|推送)/iu.test(e)}function Uy(e){return zy(e).toLowerCase().match(/(?:^|[\s,,;;:((:]|到|至)(?todo_done:todo_[a-z0-9_-]{3,64}|pr_merged:(?:(?:[a-z0-9_.-]{1,80})\/(?:[a-z0-9_.-]{1,100}))?#[1-9][0-9]{0,8}|capacity_available:[a-z][a-z0-9_:-]{0,63}|resume_at:[1-9][0-9]{3}-[0-9]{2}-[0-9]{2}t[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,3})?(?:z|[+-][0-9]{2}:[0-9]{2}))(?=$|[\s,,。;;))])/iu)?.groups?.condition??null}function Wy(e,t){let n=zy(e),r=[],i=t.agents.find(e=>{let t=n.toLowerCase();return t.includes(e.agentId.toLowerCase())||t.includes(e.label.toLowerCase())}),a=t.todos.find(e=>n.includes(e.todoId)||n.includes(e.text)),o=/(刚刚|已经|已)(?:经)?\s*(新增|创建|添加)(?:的)?\s*(todo|待办|任务)/iu.test(n),s=!!t.goalId&&!By(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n);if(!t.goalId&&!By(n,/goal|目标/iu)&&/(创建|新建|设置|create|start|set up).{0,24}(goal|目标)/iu.test(n)&&r.push({actionKind:`goal.create`,confidence:.97,normalizedParameters:{heartbeat_enabled:!By(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n)}}),t.goalId&&s&&r.push({actionKind:`heartbeat.bind`,confidence:.96,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&!s&&!By(n,/定时|监控|监测|持续观察|scheduled check|monitor/iu)&&/(定时|监控|监测|每.{0,8}(分钟|小时|天)|持续观察|scheduled check|monitor|every.{0,12}(minute|hour|day)|daily)/iu.test(n)&&r.push({actionKind:`monitor.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&i&&!By(n,/绑定|负责|接管|管理/iu)&&/((让|交给).{0,20}(管理|负责|接管).{0,8}(goal|目标)|(绑定).{0,12}(goal|目标)|(goal|目标).{0,12}(交给|绑定|负责|接管))/iu.test(n)&&r.push({actionKind:`agent.bind`,confidence:.96,normalizedParameters:{agent_id:i.agentId,goal_id:t.goalId}}),t.goalId&&!o&&!By(n,RegExp(`todo|待办|任务`,`iu`))&&/(创建|新建|新增|添加|加一个|记一个).{0,16}(todo|待办|任务)|(todo|待办|任务).{0,12}(创建|新建|新增|添加)|(?:create|add)(?:\s+(?:a|an|new))?\s+(?:todo|task)|(?:todo|task).{0,12}(?:create|add)/iu.test(n)&&r.push({actionKind:`todo.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&Hy(n)&&r.push({actionKind:`todo.create`,confidence:.9,normalizedParameters:{goal_id:t.goalId,start_execution:!0}}),t.goalId&&a){let e=!By(n,/完成|做完|关闭/u)&&/完成|做完|关闭/u.test(n)?`complete`:!By(n,/阻塞|卡住/u)&&/阻塞|卡住/u.test(n)?`block`:!By(n,/暂缓|稍后|推迟/u)&&/暂缓|稍后|推迟/u.test(n)?`defer`:i&&!By(n,/交给|分配给|改派/u)&&/交给|分配给|改派/u.test(n)?`reassign`:null;if(e){let i=e===`defer`?Uy(n):null;if(e===`defer`&&!i)return{actionKind:`todo.update`,confidence:.97,missingFields:[`resume_when`],normalizedParameters:{goal_id:t.goalId,operation:e,todo_id:a.todoId},route:`clarify`};r.push({actionKind:`todo.update`,confidence:.97,normalizedParameters:{goal_id:t.goalId,operation:e,...i?{resume_when:i}:{},todo_id:a.todoId}})}}let c=[...new Map(r.map(e=>[e.actionKind,e])).values()];return c.length>1?{actionKind:null,confidence:.4,missingFields:[`single_intent`],normalizedParameters:{},route:`clarify`}:c.length===1?{...c[0],missingFields:[],route:`typed_action`}:!t.goalId&&Vy(n)?{actionKind:null,confidence:.98,missingFields:[],normalizedParameters:{},route:`projection`}:{actionKind:null,confidence:.75,missingFields:[],normalizedParameters:{},route:`agent_chat`}}function Gy(e,t,n){if(!e)return{};if(!t.trim())return{modelConfig:null};let r={model:t.trim()};return n&&(r.reasoning_effort=n),{modelConfig:r}}var Ky=[`a[href]`,`button:not([disabled])`,`textarea:not([disabled])`,`select:not([disabled])`,`input:not([disabled])`,`[tabindex]:not([tabindex='-1'])`].join(`,`),qy=[{key:`drawer.taskBlock`,operation:`block`},{key:`drawer.taskSuccessor`,operation:`successor_create`}],Jy=[{key:`drawer.decisionReject`,resolution:`reject`},{key:`drawer.decisionDefer`,resolution:`defer`}],Yy=Array.from({length:32},(e,t)=>t+1),Xy=/^[a-z][a-z0-9_.-]{0,63}$/u;function Zy(e){let t=String(e??``).trim().toLowerCase();return Xy.test(t)?t:null}function Qy(e,t){return e.enabled===t.enabled&&e.maxChildren===t.maxChildren&&JSON.stringify(e.modelConfig??null)===JSON.stringify(t.modelConfig??null)&&[...e.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)===[...t.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)}function $y({agents:e,attentionHistory:t=[],onSelectAttention:n,callbacks:r,goalNotifications:i=[],goals:a=[],inspectorExpanded:o=!1,larkConnections:s=[],onClose:c,onToggleInspectorSize:l,readOnly:u=!1,runs:d=[],selection:f}){let{locale:p,t:m}=Ji(),[h,g]=(0,z.useState)(``),[_,v]=(0,z.useState)(!1),[y,b]=(0,z.useState)(`idle`),[x,S]=(0,z.useState)(`record`),[C,w]=(0,z.useState)([]),[T,E]=(0,z.useState)(null),[D,O]=(0,z.useState)(2),[ee,te]=(0,z.useState)(``),[ne,k]=(0,z.useState)(``),[A,j]=(0,z.useState)(`idle`),[M,N]=(0,z.useState)(null),[P,F]=(0,z.useState)(null),re=(0,z.useRef)(null),ie=(0,z.useRef)(null),[I,ae]=(0,z.useState)(e.find(e=>e.available)?.agentId??`codex`),[L,oe]=(0,z.useState)(``),se=(0,z.useRef)(null),ce=(0,z.useRef)(null),le=(0,z.useRef)(null),ue=(0,z.useRef)(null),de=f.kind===`run`?`run:${f.item.runId}`:f.kind===`proposal`?`proposal:${f.item.previewId}`:f.kind===`todo`?`todo:${f.item.todoId}`:f.kind===`attention`?`attention:${f.item.todoId}`:f.kind===`output`?`output:${f.item.outputId}`:f.kind===`schedule`?`schedule:${f.item.scheduleId}`:`goal:${f.item.goalId}`;(0,z.useEffect)(()=>{b(`idle`),v(!1),S(`record`),oe(``);let e=f.kind===`goal`?f.item.subagentExecution:void 0;w(e?.allowedDomains??[]),te(e?.modelConfig?.model??``),k(e?.modelConfig?.reasoning_effort??``),O(e?.maxChildren?Math.min(e.maxChildren,32):2),E(null),j(`idle`),N(null),F(null),re.current=e??null,ie.current=null},[de]);let fe=f.kind===`goal`?f.item.subagentExecution:void 0;(0,z.useEffect)(()=>{let e=re.current,t=fe?!e||!Qy(e,fe):e!==null;if(re.current=fe??null,!P){t&&fe&&(w(fe.allowedDomains),te(fe.modelConfig?.model??``),k(fe.modelConfig?.reasoning_effort??``),O(fe.maxChildren||2),E(null),j(`idle`),N(null));return}let n=ie.current;(!fe||Qy(P,fe)||n&&!Qy(n,fe))&&(fe&&(w(fe.allowedDomains),te(fe.modelConfig?.model??``),k(fe.modelConfig?.reasoning_effort??``),O(fe.maxChildren||2)),ie.current=null,F(null))},[fe,P]),(0,z.useEffect)(()=>{let e=document.activeElement;e instanceof HTMLElement&&!ce.current?.contains(e)&&(le.current=e);let t=window.requestAnimationFrame(()=>ue.current?.focus());return()=>window.cancelAnimationFrame(t)},[de]);let pe=(0,z.useCallback)(()=>{let e=le.current;c(),window.requestAnimationFrame(()=>e?.focus())},[c]);(0,z.useEffect)(()=>{function e(e){if(e.key===`Escape`){e.preventDefault(),pe();return}if(e.key===`Tab`&&f.kind!==`todo`){let t=Array.from(ce.current?.querySelectorAll(Ky)??[]).filter(e=>!e.hasAttribute(`disabled`)&&e.getAttribute(`aria-hidden`)!==`true`);if(t.length===0)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n.focus())}}return document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`keydown`,e)}},[pe,f.kind]);let me=f.kind===`attention`?m(`drawer.titleAttention`):f.kind===`todo`?m(`drawer.taskDetails`):f.kind===`run`?m(`drawer.runDetails`):f.kind===`output`?m(`drawer.titleOutput`):f.kind===`proposal`?m(f.item.status===`applied`?`drawer.titleProposalApplied`:`drawer.titleProposalConfirm`):f.kind===`schedule`?f.item.scheduleKind===`heartbeat`?`Heartbeat`:m(`drawer.titleSchedule`):m(`drawer.goalDetails`),he=f.kind===`proposal`?f.item.goalId??`manager`:f.item.goalId,ge=f.kind===`attention`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`todo`||f.kind===`run`?f.item.goalTitle:f.kind===`output`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`goal`?f.item.title:f.kind===`schedule`?m(`drawer.goalAutoRun`):f.item.goalId?m(`drawer.goalChanges`):m(`drawer.managerChanges`),_e=f.kind===`goal`?d.find(e=>e.goalId===f.item.goalId&&!!e.sessionId)??d.find(e=>e.goalId===f.item.goalId):null,ve=f.kind===`run`&&(f.item.completedSteps>0||!!f.item.latestActivity||!!f.item.outputs?.length),ye=f.kind===`attention`?Zi(f.item.updatedAt,m):null,be=Uy(L);async function xe(){f.kind!==`run`||!h.trim()||(await r.onCorrectRun?.(f.item,h.trim()),g(``))}async function Se(e,t,n,i){if(t===`successor_create`){await r.onPreviewAction?.({actionKind:`todo.create`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-successor-${e.todoId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,text:m(`drawer.taskSuccessorText`,{task:e.text})},summary:m(`drawer.taskSuccessorSummary`,{task:e.text})});return}await r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:e.claimedBy??I,goal_id:e.goalId,operation:t,...t===`block`?{note:m(`drawer.taskSuccessorNote`)}:{},...t===`defer`&&i?{resume_when:i}:{},todo_id:e.todoId},summary:`${n}:${e.text}`})}async function Ce(e,t,n){u||!qd(e)||await r.onPreviewAction?.({actionKind:`gate.resolve`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-decision-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,decision:t,todo_id:e.todoId},summary:`${n}:${e.text}`})}let we=f.kind===`goal`?P??f.item.subagentExecution??{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0}:{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0},Te=A===`previewing`||A===`applying`,Ee=(()=>{if(f.kind!==`goal`)return[];let e=new Map;for(let t of we.allowedDomains){let n=Zy(t);n&&e.set(n,{matchingTodoCount:0,value:n})}if(we.domainCandidates)for(let t of we.domainCandidates){let n=Zy(t.domain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+t.matchingTodoCount,value:n})}else for(let t of f.item.agentTodos){if(t.done||t.taskClass!==`advancement_task`)continue;let n=Zy(t.taskDomain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+1,value:n})}return[...e.values()]})();function R(){w(we.allowedDomains),te(we.modelConfig?.model??``),k(we.modelConfig?.reasoning_effort??``),O(we.maxChildren||2),E(null),j(`idle`),N(null)}function De(){let e=[...new Set(C.map(e=>Zy(e)))];return e.every(e=>!!e)?e:null}function Oe(e,t){w(n=>t?[...n,e].filter((e,t,n)=>n.indexOf(e)===t):n.filter(t=>t!==e)),N(null),j(`idle`),E(null)}async function ke(e,t=e){if(f.kind!==`goal`||!r.onPreviewGoalSubagentConfiguration)return;let n=e?De():[];if(t&&!ee.trim()&&ne){j(`error`),E(m(`drawer.subagentModelRequired`));return}if(e&&!n){j(`error`),E(m(`drawer.subagentDomainInvalid`)),N(null);return}let i={allowedDomains:n??[],enabled:e,goalId:f.item.goalId,maxChildren:e?D:0,...Gy(t,ee,ne)};j(`previewing`),E(m(`drawer.subagentPreviewing`)),N(null);try{let e=await r.onPreviewGoalSubagentConfiguration(i);if(!e.changed){ie.current=fe??null,F({...e.configuration,domainCandidates:we.domainCandidates}),w(e.configuration.allowedDomains),te(e.configuration.modelConfig?.model??``),k(e.configuration.modelConfig?.reasoning_effort??``),O(e.configuration.maxChildren||2),j(`success`),E(m(`drawer.subagentNoChange`));return}N({...i,changed:e.changed,previewId:e.previewId}),j(`ready`),E(m(`drawer.subagentPreviewReady`))}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentPreviewFailed`))}}async function Ae(){if(!(!M||!r.onApplyGoalSubagentConfiguration)){j(`applying`),E(m(`drawer.subagentApplying`));try{let e=await r.onApplyGoalSubagentConfiguration({allowedDomains:M.allowedDomains,enabled:M.enabled,goalId:M.goalId,maxChildren:M.maxChildren,modelConfig:M.modelConfig,previewId:M.previewId});ie.current=fe??null,F({...e,domainCandidates:we.domainCandidates}),w(e.allowedDomains),te(e.modelConfig?.model??``),k(e.modelConfig?.reasoning_effort??``),O(e.maxChildren||2),j(`success`),E(m(`drawer.subagentApplied`)),N(null);try{await r.onRefresh?.()}catch{j(`warning`),E(m(`drawer.subagentAppliedRefreshFailed`))}}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentApplyFailed`))}}}return(0,B.jsxs)(`div`,{"aria-labelledby":`personal-drawer-title`,"aria-modal":f.kind===`todo`?void 0:`true`,className:`personal-context-drawer`,"data-context-kind":f.kind,ref:ce,role:`dialog`,children:[(0,B.jsxs)(`header`,{className:`personal-drawer-header${f.kind===`todo`?` is-task-inspector`:``}`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`h2`,{id:`personal-drawer-title`,ref:ue,tabIndex:-1,children:me}),(0,B.jsx)(`p`,{children:ge})]}),(0,B.jsxs)(`div`,{className:`personal-drawer-header-actions`,children:[f.kind===`todo`&&l?(0,B.jsx)(`button`,{"aria-label":m(o?`drawer.inspectorHalf`:`drawer.inspectorFull`),className:`personal-icon-button personal-inspector-size`,onClick:l,title:m(o?`drawer.inspectorHalfView`:`drawer.inspectorFullView`),type:`button`,children:o?(0,B.jsx)(Om,{size:17}):(0,B.jsx)(wm,{size:17})}):null,(0,B.jsxs)(`button`,{"aria-label":m(`drawer.closeDetail`,{context:ge}),className:`personal-icon-button personal-drawer-close`,onClick:pe,ref:se,type:`button`,children:[(0,B.jsx)(Gp,{className:`personal-mobile-back`,size:18}),(0,B.jsx)($m,{className:`personal-desktop-close`,size:18})]})]})]}),(0,B.jsxs)(`div`,{className:`personal-drawer-body`,children:[f.kind===`attention`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card is-attention`,children:[(0,B.jsx)(`small`,{children:f.item.blocking?m(`drawer.attentionBlocking`):m(`drawer.attentionWaiting`)}),(0,B.jsx)(`h3`,{children:f.item.text}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,B.jsx)(`dd`,{children:f.item.priority??`medium`})]}),ye?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`common.waiting`)}),(0,B.jsx)(`dd`,{children:m(`tasks.waitingAge`,{age:ye})})]}):null]})]}),(0,B.jsx)(Ry,{item:f.item,onSelect:n,successor:Kd(f.item,t)}),!u&&qd(f.item)?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void Ce(f.item,`approve`,m(`common.confirm`)),type:`button`,children:[(0,B.jsx)(em,{size:17}),m(`drawer.decisionReview`)]}),(0,B.jsxs)(`details`,{className:`personal-compact-menu`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(dm,{size:17}),m(`drawer.decisionMore`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`button`,{onClick:()=>void r.onExplainDecision?.(f.item),type:`button`,children:[(0,B.jsx)(Em,{size:16}),m(`drawer.explainDecision`)]}),Jy.map(e=>(0,B.jsx)(`button`,{onClick:()=>void Ce(f.item,e.resolution,m(e.key)),type:`button`,children:m(e.key)},e.resolution))]})]})]}):null]}):null,f.kind===`todo`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-task-inspector-summary`,children:[(0,B.jsxs)(`div`,{className:`personal-task-inspector-status`,children:[(0,B.jsxs)(`span`,{className:f.item.done?`is-done`:f.item.status===`blocked`?`is-blocked`:`is-open`,children:[(0,B.jsx)(`i`,{}),f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)]}),f.item.priority?(0,B.jsx)(`span`,{children:f.item.priority}):null,(0,B.jsx)(`span`,{children:f.item.taskClass===`advancement_task`?m(`drawer.taskAdvancement`):f.item.taskClass??m(`drawer.taskOrdinary`)})]}),(0,B.jsx)(`h3`,{children:f.item.text})]}),(0,B.jsxs)(`section`,{"aria-label":m(`drawer.taskInfo`),className:`personal-task-inspector-fields`,children:[(0,B.jsx)(`h4`,{children:m(`drawer.taskInfo`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`common.owner`)}),(0,B.jsx)(`dd`,{children:f.item.ownerLabel??f.item.claimedBy??m(`drawer.notAssigned`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`common.status`)}),(0,B.jsx)(`dd`,{children:f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,B.jsx)(`dd`,{children:f.item.priority??m(`drawer.notSet`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.dependencies`)}),(0,B.jsx)(`dd`,{children:f.item.dependencies?.join(` · `)||m(`common.none`)})]}),f.item.status===`deferred`||f.item.resumeWhen?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.resumeWhen`)}),(0,B.jsx)(`dd`,{children:f.item.resumeWhen||m(`drawer.notSet`)})]}):null,f.item.resumeWhen?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.resumeState`)}),(0,B.jsx)(`dd`,{children:f.item.resumeReady?m(`drawer.resumeReady`):m(`drawer.resumePending`)})]}):null,f.item.resumeReceiptId?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.resumeReceipt`)}),(0,B.jsx)(`dd`,{children:f.item.resumeReceiptId})]}):null,(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.nextTransition`)}),(0,B.jsx)(`dd`,{children:f.item.nextTransition??(f.item.done?m(`drawer.taskNextCompleted`):f.item.resumeReady?m(`drawer.taskNextResumeReady`):f.item.status===`deferred`?m(`drawer.taskNextDeferred`):m(`drawer.taskNextOpen`))})]})]})]}),!u&&!f.item.done?(0,B.jsxs)(`div`,{className:`personal-task-inspector-actions`,"aria-label":m(`drawer.taskActions`),children:[(0,B.jsxs)(`details`,{className:`personal-task-management`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(dm,{size:16}),m(`drawer.taskManage`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:m(`drawer.reassign`)}),(0,B.jsxs)(`label`,{className:`personal-inline-agent-select`,children:[m(`drawer.reassign`),(0,B.jsx)(`select`,{"aria-label":m(`drawer.reassign`),onChange:e=>ae(e.target.value),value:I,children:e.filter(e=>e.available).map(e=>(0,B.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:f.item.goalId,kind:`todo`,todo_id:f.item.todoId},idempotencyKey:`workspace-todo-${f.item.todoId}-reassign-${I}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:I,goal_id:f.item.goalId,operation:`reassign`,todo_id:f.item.todoId},summary:m(`drawer.reassignSummary`,{task:f.item.text})}),type:`button`,children:m(`timeline.review`)})]}),(0,B.jsx)(`strong`,{children:m(`drawer.taskDeferUntil`)}),(0,B.jsxs)(`label`,{className:`personal-inline-agent-select personal-inline-resume-when`,children:[m(`drawer.taskDeferUntil`),(0,B.jsx)(`input`,{"aria-label":m(`drawer.taskDeferCondition`),"aria-invalid":!!L.trim()&&!be,onChange:e=>oe(e.target.value),placeholder:m(`drawer.taskDeferPlaceholder`),value:L}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:!be,onClick:()=>void Se(f.item,`defer`,m(`drawer.taskDefer`),be??void 0),type:`button`,children:m(`drawer.taskDeferReview`)}),(0,B.jsx)(`small`,{children:L.trim()&&!be?m(`drawer.taskDeferInvalid`):m(`drawer.taskDeferSupported`)})]}),(0,B.jsx)(`div`,{className:`personal-task-management-secondary`,children:qy.map(e=>(0,B.jsx)(`button`,{onClick:()=>void Se(f.item,e.operation,m(e.key)),type:`button`,children:m(e.key)},e.operation))})]})]}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void Se(f.item,`complete`,m(`drawer.taskComplete`)),type:`button`,children:[(0,B.jsx)(em,{size:17}),m(`drawer.taskComplete`)]})]}):null,f.item.done?(0,B.jsxs)(`div`,{className:`personal-task-completed-note`,children:[(0,B.jsx)(em,{size:16}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:m(`drawer.taskCompletedTitle`)}),(0,B.jsx)(`small`,{children:m(`drawer.taskCompletedNote`)})]})]}):null]}):null,f.kind===`goal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsx)(`small`,{children:Yi(f.item.state,p)}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.agentSentence}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.tokens`)}),(0,B.jsxs)(`dd`,{children:[by(f.item.usage?.tokens24h,m(`drawer.usageNotMeasured`),_y),` / `,by(f.item.usage?.tokens7d,m(`drawer.usageNotMeasured`),_y)]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.cost`)}),(0,B.jsxs)(`dd`,{children:[by(f.item.usage?.costUsd24h,m(`drawer.usageNotMeasured`),vy),` / `,by(f.item.usage?.costUsd7d,m(`drawer.usageNotMeasured`),vy)]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.duration`)}),(0,B.jsxs)(`dd`,{children:[by(f.item.usage?.durationMs24h,m(`drawer.usageNotMeasured`),yy),` / `,by(f.item.usage?.durationMs7d,m(`drawer.usageNotMeasured`),yy)]})]})]})]}),(0,B.jsx)(Ly,{goal:f.item}),(()=>{let e=i.find(e=>e.goalId===f.item.goalId),t=s.find(e=>e.goal_id===f.item.goalId);return(0,B.jsxs)(B.Fragment,{children:[f.item.repository?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-repository`,children:[(0,B.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,B.jsx)(`small`,{children:m(`drawer.repository`)}),(0,B.jsx)(`em`,{children:m(`common.readOnly`)})]}),(0,B.jsxs)(`h3`,{children:[(0,B.jsx)(_m,{size:16}),f.item.repository.label]}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.branch`)}),(0,B.jsx)(`dd`,{children:f.item.repository.branch||`detached`})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Role`}),(0,B.jsx)(`dd`,{children:m(`drawer.repositoryRole`)})]})]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>{let e=navigator.clipboard?.writeText(f.item.repository?.identity??``);if(!e){b(`error`);return}e.then(()=>b(`copied`)).catch(()=>b(`error`))},type:`button`,children:[(0,B.jsx)(cm,{size:15}),m(y===`copied`?`drawer.copyRepositoryDone`:`drawer.copyRepository`)]}),y===`error`?(0,B.jsx)(`p`,{className:`personal-copy-feedback is-error`,role:`status`,children:m(`drawer.copyRepositoryError`)}):y===`copied`?(0,B.jsx)(`p`,{className:`personal-copy-feedback`,role:`status`,children:m(`drawer.copyRepositorySuccess`)}):null]}):null,u?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,B.jsx)(`small`,{children:m(`drawer.larkConnection`)}),(0,B.jsx)(`h3`,{children:m(`drawer.remoteDetailsUnavailable`)}),(0,B.jsx)(`p`,{children:m(`drawer.remoteDetailsDescription`)})]}):(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,B.jsx)(`small`,{children:m(`drawer.larkConnection`)}),t?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`h3`,{children:[t.app_label,(0,B.jsx)(`span`,{className:`personal-connection-status`,children:m(`drawer.connected`)})]}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.group`)}),(0,B.jsx)(`dd`,{children:t.chat_name})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.topic`)}),(0,B.jsxs)(`dd`,{children:[`# `,t.topic_name]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.trigger`)}),(0,B.jsx)(`dd`,{children:t.incoming_mode===`mentions`?m(`lark.someoneMentions`):m(`lark.allMessages`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.replyMode`)}),(0,B.jsx)(`dd`,{children:m(`lark.topicReply`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.autoNotify`)}),(0,B.jsx)(`dd`,{children:e?.humanGateAutoNotifyEnabled?m(`common.on`):m(`common.off`)})]}),e?.lastNotifiedAt?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.lastNotification`)}),(0,B.jsx)(`dd`,{children:e.lastNotifiedAt})]}):null]})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h3`,{children:m(`drawer.larkNotConfigured`)}),(0,B.jsx)(`p`,{children:m(`drawer.larkNotConfiguredDescription`)})]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onOpenNotificationSettings?.(f.item.goalId),type:`button`,children:[(0,B.jsx)(Xp,{size:16}),m(t?`drawer.larkConfigure`:`drawer.larkConnect`)]})]})]})})(),(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-session`,children:[(0,B.jsx)(`small`,{children:m(`drawer.runDetails`)}),_e?.sessionId?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h3`,{children:Xi(_e.sessionStatus??_e.status,m)}),(0,B.jsx)(`p`,{children:_e.title}),r.onOpenRunSession?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onOpenRunSession?.(_e),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.runLatest`)]}):null]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h3`,{children:m(`drawer.noRun`)}),(0,B.jsx)(`p`,{children:m(`drawer.noRunDescription`)})]})]}),u?null:(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`heartbeat`,f.item.goalId),type:`button`,children:[(0,B.jsx)(Fm,{size:16}),m(`drawer.setupHeartbeat`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`monitor`,f.item.goalId),type:`button`,children:[(0,B.jsx)($p,{size:16}),m(`drawer.scheduleAdd`)]})]}),f.item.subagentExecution?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-subagents`,children:[(0,B.jsxs)(`div`,{className:`personal-subagent-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:m(`drawer.subagentLabel`)}),(0,B.jsxs)(`h3`,{children:[(0,B.jsx)(Zp,{size:16}),m(`drawer.subagentTitle`)]})]}),(0,B.jsxs)(`button`,{"aria-checked":we.enabled,"aria-label":m(M&&A===`ready`?`drawer.subagentPending`:we.enabled?`drawer.subagentDisable`:`drawer.subagentEnable`),className:`personal-subagent-switch`,"data-pending":M&&A===`ready`?`true`:void 0,disabled:u||Te||!!M||!r.onPreviewGoalSubagentConfiguration,onClick:()=>void ke(!we.enabled),role:`switch`,type:`button`,children:[(0,B.jsx)(`span`,{}),m(M&&A===`ready`?`drawer.subagentPending`:we.enabled?`common.on`:`common.off`)]})]}),(0,B.jsx)(`p`,{children:m(`drawer.subagentDescription`)}),M&&A===`ready`?(0,B.jsxs)(`div`,{className:`personal-subagent-preview`,children:[(0,B.jsx)(`strong`,{children:m(M.enabled?`drawer.subagentConfirmEnable`:`drawer.subagentConfirmDisable`)}),(0,B.jsx)(`p`,{children:M.enabled?m(`drawer.subagentPreviewSummary`,{count:M.maxChildren,domains:M.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)}):m(`drawer.subagentDisableSummary`)}),M.modelConfig===void 0?null:(0,B.jsxs)(`p`,{children:[m(`drawer.subagentModel`),`: `,M.modelConfig?.model||m(`drawer.subagentModelDefault`),` · `,M.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`button`,{className:`personal-primary-action`,onClick:()=>void Ae(),type:`button`,children:m(`common.confirm`)}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:R,type:`button`,children:m(`common.cancel`)})]})]}):null,T?(0,B.jsxs)(`p`,{className:`personal-subagent-feedback is-${A}`,role:`status`,children:[A===`previewing`||A===`applying`?(0,B.jsx)(Lm,{className:`personal-spin`,size:13}):null,T]}):null,(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentModel`)}),(0,B.jsx)(`dd`,{children:we.modelConfig?.model||m(`drawer.subagentModelDefault`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentEffort`)}),(0,B.jsx)(`dd`,{children:we.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentCurrentBoundary`)}),(0,B.jsx)(`dd`,{children:we.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentChildLimit`)}),(0,B.jsx)(`dd`,{children:we.maxChildren||0})]})]}),u?(0,B.jsx)(`p`,{className:`personal-subagent-read-only`,children:m(`drawer.subagentRemoteReadOnly`)}):(0,B.jsxs)(`div`,{className:`personal-subagent-fields`,children:[(0,B.jsxs)(`fieldset`,{className:`personal-subagent-domain-picker`,disabled:Te,children:[(0,B.jsx)(`legend`,{children:m(`drawer.subagentDomains`)}),Ee.length>0?(0,B.jsx)(`div`,{className:`personal-subagent-domain-options`,children:Ee.map(e=>{let t=C.includes(e.value);return(0,B.jsxs)(`label`,{className:`personal-subagent-domain-option${t?` is-selected`:``}`,children:[(0,B.jsx)(`input`,{"aria-label":e.value,checked:t,onChange:t=>Oe(e.value,t.target.checked),type:`checkbox`}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.value}),(0,B.jsx)(`small`,{children:m(`drawer.subagentDomainTodoCount`,{count:e.matchingTodoCount})})]})]},e.value)})}):(0,B.jsx)(`p`,{className:`personal-subagent-domain-empty`,children:m(`drawer.subagentDomainsEmpty`)}),(0,B.jsx)(`small`,{children:m(`drawer.subagentDomainsHint`)})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:m(`drawer.subagentModel`)}),(0,B.jsx)(`input`,{"aria-label":m(`drawer.subagentModel`),disabled:Te,value:ee,placeholder:`gpt-5.6-luna`,onChange:e=>{te(e.target.value),N(null),j(`idle`),E(null)}})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:m(`drawer.subagentEffort`)}),(0,B.jsxs)(`select`,{"aria-label":m(`drawer.subagentEffort`),disabled:Te,value:ne,onChange:e=>{k(e.target.value),N(null),j(`idle`),E(null)},children:[(0,B.jsx)(`option`,{value:``,children:m(`drawer.subagentModelDefault`)}),[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`].map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))]})]}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:Te,type:`button`,onClick:()=>{te(`gpt-5.6-luna`),k(`max`),N(null),j(`idle`),E(null)},children:m(`drawer.subagentLunaPreset`)}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:Te,type:`button`,onClick:()=>{te(``),k(``),N(null),j(`idle`),E(null)},children:m(`drawer.subagentClearModel`)}),(0,B.jsx)(`p`,{children:m(`drawer.subagentModelHint`)}),(0,B.jsxs)(`label`,{className:`personal-subagent-limit-field`,children:[(0,B.jsx)(`span`,{children:m(`drawer.subagentMaxChildren`)}),(0,B.jsx)(`select`,{"aria-label":m(`drawer.subagentMaxChildren`),disabled:Te,onChange:e=>{O(Number(e.target.value)),N(null),j(`idle`),E(null)},value:D,children:Yy.map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))})]}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:Te,onClick:()=>void ke(we.enabled,!0),type:`button`,children:m(`drawer.subagentPreviewBoundary`)})]})]}):null]}):null,f.kind===`run`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{"aria-label":m(`drawer.runView`),className:`personal-run-drawer-tabs`,role:`tablist`,children:[(0,B.jsx)(`button`,{"aria-selected":x===`record`,onClick:()=>S(`record`),role:`tab`,type:`button`,children:m(`drawer.executionRecordAndResult`)}),(0,B.jsx)(`button`,{"aria-selected":x===`details`,onClick:()=>S(`details`),role:`tab`,type:`button`,children:m(`drawer.detailsAndActions`)})]}),x===`record`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card personal-session-summary`,children:[(0,B.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Xi(f.item.sessionStatus??f.item.status,m)]}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.latestActivity}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,B.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]})]})]}),(0,B.jsxs)(`section`,{"aria-label":m(`drawer.executionRecord`),className:`personal-session-message-record`,children:[(0,B.jsx)(`h3`,{children:m(`drawer.executionRecord`)}),f.item.sessionMessages?.length?(0,B.jsx)(`ol`,{children:f.item.sessionMessages.map(e=>(0,B.jsxs)(`li`,{className:`is-${e.role}`,children:[(0,B.jsx)(`i`,{}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:e.role===`user`?m(`drawer.runRoleUser`):e.role===`assistant`?m(`drawer.runRoleAssistant`):m(`drawer.runRoleSystem`)}),e.createdAt?(0,B.jsx)(`time`,{children:new Date(e.createdAt).toLocaleTimeString(p,{hour:`2-digit`,minute:`2-digit`,hour12:!1})}):null]}),(0,B.jsx)(`p`,{children:e.text})]})]},e.messageId))}):(0,B.jsx)(`p`,{className:`personal-session-empty`,children:ve?m(`drawer.runRecordProjected`,{completed:f.item.completedSteps,outputs:f.item.outputs?.length?m(`drawer.runRecordProjectedOutputs`,{count:f.item.outputs.length}):``,total:f.item.totalSteps}):m(`drawer.runRecordEmpty`)}),f.item.status===`running`?(0,B.jsxs)(`div`,{className:`personal-session-active-step`,children:[(0,B.jsx)(`i`,{}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:m(`drawer.analysis`)}),(0,B.jsx)(`small`,{children:m(`drawer.agentWorking`)})]})]}):null]}),f.item.outputs?.length?(0,B.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-run-outputs-title`,children:[(0,B.jsx)(`h3`,{id:`personal-run-outputs-title`,children:m(`drawer.outputs`)}),(0,B.jsx)(`ol`,{children:f.item.outputs.map(e=>(0,B.jsx)(`li`,{children:(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsx)(`small`,{children:e.createdAt??e.kind??m(`files.emptySummary`)})]})},e.outputId))})]}):null]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Xi(f.item.status,m)]}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.latestActivity}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,B.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.sessionStatus`)}),(0,B.jsx)(`dd`,{children:Xi(f.item.sessionStatus??f.item.status,m)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.sessionRecoverable`)}),(0,B.jsx)(`dd`,{children:f.item.resumable===!1?m(`drawer.resumeNo`):m(`drawer.resumeYes`)})]})]})]}),f.item.sessionStatus===`resume_failed`&&!u?(0,B.jsxs)(`section`,{className:`personal-recovery-panel`,"aria-label":m(`drawer.recoveryFailed`),children:[(0,B.jsx)(`strong`,{children:m(`drawer.recoveryFailed`)}),(0,B.jsx)(`p`,{children:m(`drawer.recoveryDescription`)}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,B.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.recoveryNewSession`)]})]}):null,u?null:(0,B.jsxs)(`section`,{className:`personal-correction-panel`,children:[(0,B.jsx)(`header`,{children:(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:16}),m(`drawer.correctionLabel`,{agent:f.item.agentLabel})]})}),(0,B.jsx)(`p`,{children:m(`drawer.correctionDescription`)}),(0,B.jsxs)(`div`,{className:`personal-correction-composer`,children:[(0,B.jsx)(`textarea`,{"aria-label":m(`drawer.correctionTextarea`,{agent:f.item.agentLabel,goal:f.item.goalTitle,run:f.item.title}),onChange:e=>g(e.target.value),placeholder:m(`drawer.correctionPlaceholder`),rows:3,value:h}),(0,B.jsx)(`button`,{"aria-label":m(`drawer.correctionSend`),disabled:!h.trim(),onClick:()=>void xe(),type:`button`,children:(0,B.jsx)(Bm,{size:16})})]})]}),u?null:(0,B.jsxs)(`details`,{className:`personal-compact-menu personal-run-more`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(dm,{size:17}),m(`drawer.moreRunActions`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`button`,{disabled:!f.item.canInterrupt,onClick:()=>void r.onInterruptRun?.(f.item),type:`button`,children:[(0,B.jsx)(Mm,{size:16}),m(`drawer.runInterrupt`)]}),(0,B.jsxs)(`button`,{disabled:f.item.resumable===!1,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,B.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,B.jsxs)(`button`,{onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.runNewSession`)]}),(0,B.jsxs)(`button`,{onClick:()=>void r.onCloseRunSession?.(f.item),type:`button`,children:[(0,B.jsx)(qm,{size:16}),m(`drawer.runCloseSession`)]})]})]})]})]}):null,f.kind===`output`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsx)(`small`,{children:f.item.kind??`output`}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.summary??m(`drawer.outputRecorded`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.outputTodo`)}),(0,B.jsx)(`dd`,{children:f.item.todoId??m(`drawer.notLinked`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.outputRun`)}),(0,B.jsx)(`dd`,{children:f.item.runId??m(`drawer.notLinked`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Agent`}),(0,B.jsx)(`dd`,{children:f.item.agentLabel??f.item.agentId??`LoopX`})]})]})]}),f.item.report?(0,B.jsxs)(`section`,{className:`personal-report-detail`,"data-testid":`personal-periodic-report-detail`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsxs)(`strong`,{children:[`+`,f.item.report.addedCount]}),m(`files.reportAdded`)]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:f.item.report.changedCount}),m(`files.reportChanged`)]})]}),(0,B.jsxs)(`p`,{children:[f.item.report.periodStartAt,` → `,f.item.report.periodEndAt]}),(0,B.jsx)(`ol`,{children:f.item.report.items.map(e=>(0,B.jsxs)(`li`,{"data-change-kind":e.changeKind,children:[(0,B.jsxs)(`small`,{children:[e.changeKind,` · `,e.status]}),(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsx)(`p`,{children:e.summary})]},e.sourceRef))}),(0,B.jsxs)(`footer`,{children:[(0,B.jsxs)(`span`,{children:[m(`files.reportPublication`),`: `,f.item.report.publicationId]}),(0,B.jsxs)(`span`,{children:[m(`files.reportGeneration`),`: `,f.item.report.generationId]})]})]}):null,f.item.safePreview?(0,B.jsx)(`pre`,{"aria-label":m(`drawer.outputSafePreview`),className:`personal-safe-preview`,children:f.item.safePreview}):(0,B.jsx)(`p`,{className:`personal-preview-unavailable`,children:m(`drawer.previewUnavailable`)}),(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:!r.onOpenOutput,onClick:()=>{r.onOpenOutput?.(f.item),c()},type:`button`,children:[(0,B.jsx)(fm,{size:16}),m(`files.openConversation`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!r.onExportOutput,onClick:()=>void r.onExportOutput?.(f.item),type:`button`,children:[(0,B.jsx)(um,{size:16}),m(`files.exportSummary`)]})]})]}):null,f.kind===`proposal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-proposal-card`,children:[(0,B.jsxs)(`small`,{children:[f.item.actionKind,` · `,f.item.status]}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.impact}),f.item.reviewPlan?(0,B.jsx)(`p`,{className:`personal-proposal-explainer`,"data-action-review":f.item.reviewPlan.interaction,children:m(`actionReview.${f.item.reviewPlan.reason}`)}):null,f.item.status===`ready`?(0,B.jsx)(`p`,{className:`personal-proposal-explainer`,children:m(`drawer.proposalExplainer`)}):null,(0,B.jsx)(`dl`,{children:f.item.fields.map(e=>(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:e.label}),(0,B.jsx)(`dd`,{children:e.value})]},e.key))})]}),f.item.status===`applied`?(0,B.jsxs)(`p`,{className:`personal-proposal-state is-applied`,children:[(0,B.jsx)(em,{size:16}),m(`drawer.proposalApplied`)]}):null,f.item.status===`applied`&&f.item.goalId?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>{let e=f.item.goalId;c(),r.onOpenGoal?.(e)},type:`button`,children:[(0,B.jsx)(fm,{size:16}),f.item.actionKind===`goal.create`?m(`drawer.proposalEnterGoal`):m(`drawer.proposalViewGoal`)]}):null,f.item.status===`stale`?(0,B.jsx)(`p`,{className:`personal-proposal-state is-stale`,children:m(`drawer.proposalStale`)}):null,f.item.status===`error`?(0,B.jsxs)(`div`,{className:`personal-proposal-state is-error`,children:[(0,B.jsx)(`span`,{children:f.item.reviewPlan?.reason===`readback_unverified`?m(`actionReview.readback_unverified`):m(`drawer.proposalApplyFailed`)}),f.item.errorMessage?(0,B.jsx)(`small`,{children:f.item.errorMessage}):null,(0,B.jsx)(`small`,{children:m(`drawer.proposalApplyFailedHint`)})]}):null,f.item.status===`rejected`?(0,B.jsx)(`p`,{className:`personal-proposal-state is-error`,children:m(`drawer.proposalRejected`)}):null,f.item.status===`deferred`?(0,B.jsx)(`p`,{className:`personal-proposal-state is-gated`,children:m(`drawer.proposalDeferred`)}):null,f.item.status===`gated`?(0,B.jsxs)(`div`,{className:`personal-proposal-state is-gated`,children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:m(`drawer.gateRequiresHost`)}),m(`drawer.gateRequiresHostDescription`)]}),f.item.gate?.nextAction?(0,B.jsx)(`small`,{children:f.item.gate.nextAction}):null]}):null,f.item.status===`gated`&&f.item.actionKind===`gate.resolve`?(()=>{let e=e=>f.item.fields.find(t=>t.key===e)?.value,t=e(`goal_id`),n=e(`todo_id`);return!t||!n?null:(0,B.jsxs)(`section`,{className:`personal-detail-card personal-gate-cli-hint`,children:[(0,B.jsx)(`small`,{children:m(`drawer.gateApproveHint`)}),(0,B.jsxs)(`code`,{children:[`loopx todo complete --goal-id `,t,` --todo-id `,n,` --decision-outcome approve`]}),(0,B.jsx)(`small`,{children:m(`drawer.gateRejectHint`)})]})})():null,!u&&f.item.workspaceCandidates?.length?(0,B.jsx)(`div`,{className:`personal-workspace-candidates`,"aria-label":m(`drawer.workspaceCandidates`),children:f.item.workspaceCandidates.map(e=>(0,B.jsxs)(`button`,{onClick:()=>void r.onSelectWorkspaceCandidate?.(f.item,e.workspaceRef),type:`button`,children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsx)(`small`,{children:e.workspaceRef})]},e.workspaceRef))}):null,!u&&f.item.status===`error`?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,B.jsx)(Lm,{size:17}),m(`drawer.proposalRegenerate`)]}):!u&&f.item.status!==`gated`?(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:![`ready`,`deferred`].includes(f.item.status)||f.item.reviewPlan?.canApply===!1,onClick:()=>void r.onApplyProposal?.(f.item),type:`button`,children:[(0,B.jsx)(em,{size:17}),f.item.status===`applying`?m(`drawer.applying`):f.item.primaryLabel??m(`drawer.apply`)]}):null,!u&&f.item.actionKind!==`operation.execute`&&([`stale`,`gated`,`rejected`].includes(f.item.status)||f.item.status===`ready`&&f.item.reviewPlan?.canApply===!1)?(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,B.jsx)(Lm,{size:16}),m(`drawer.proposalRecheck`)]}):null,!u&&f.item.actionKind!==`operation.execute`&&[`ready`,`gated`].includes(f.item.status)?(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`defer`),type:`button`,children:m(`drawer.proposalDefer`)}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`reject`),type:`button`,children:m(`drawer.decisionReject`)})]}):null,[`applied`,`applying`].includes(f.item.status)?null:(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:c,type:`button`,children:m(`drawer.proposalClose`)})]}):null,f.kind===`schedule`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsxs)(`small`,{children:[f.item.scheduleKind===`heartbeat`?`Goal Heartbeat`:`continuous_monitor`,` · `,f.item.status??`active`]}),(0,B.jsx)(`h3`,{children:f.item.label}),(0,B.jsx)(`p`,{children:f.item.target??f.item.schedule??m(`drawer.scheduleDefaultTarget`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleTimezone`)}),(0,B.jsx)(`dd`,{children:f.item.timezone??m(`drawer.scheduleLocalTimezone`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleNext`)}),(0,B.jsx)(`dd`,{children:f.item.nextRunAt??m(`drawer.schedulePending`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleLast`)}),(0,B.jsx)(`dd`,{children:f.item.previousRunAt??m(`drawer.scheduleNeverRun`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleNotification`)}),(0,B.jsx)(`dd`,{children:f.item.notificationRule??m(`drawer.scheduleDefaultNotification`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleStopCondition`)}),(0,B.jsx)(`dd`,{children:f.item.stopCondition??m(`drawer.scheduleDefaultStop`)})]})]})]}),!u&&f.item.scheduleKind===`monitor`?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`run_now`),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.scheduleRunNow`)]}):null,u?null:(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,f.item.status===`paused`?`resume`:`pause`),type:`button`,children:[f.item.status===`paused`?(0,B.jsx)(Nm,{size:16}):(0,B.jsx)(Mm,{size:16}),f.item.status===`paused`?m(`drawer.scheduleResume`):m(`drawer.schedulePause`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`edit`),type:`button`,children:[(0,B.jsx)($p,{size:16}),m(`drawer.scheduleEdit`)]})]}),u?null:(0,B.jsxs)(`button`,{className:`personal-danger-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`stop`),type:`button`,children:[(0,B.jsx)(qm,{size:16}),m(`drawer.scheduleStop`,{kind:f.item.scheduleKind===`heartbeat`?` Heartbeat`:m(`drawer.titleSchedule`)})]}),(0,B.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-execution-history-title`,children:[(0,B.jsx)(`h3`,{id:`personal-execution-history-title`,children:m(`drawer.executionHistory`)}),f.item.executionHistory?.length?(0,B.jsx)(`ol`,{children:f.item.executionHistory.map((e,t)=>(0,B.jsxs)(`li`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsx)(`small`,{children:e.timestamp})]}),(0,B.jsx)(`em`,{className:`is-${e.status}`,children:e.status})]},`${e.timestamp}:${e.runId??t}`))}):(0,B.jsx)(`p`,{children:m(`drawer.noExecutionHistory`)})]})]}):null,f.kind===`run`||f.kind===`proposal`||f.kind===`schedule`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`button`,{"aria-expanded":_,className:`personal-diagnostics-trigger`,onClick:()=>v(e=>!e),type:`button`,children:[(0,B.jsx)(`span`,{children:m(`drawer.advancedDiagnostics`)}),(0,B.jsx)(tm,{className:_?`is-open`:``,size:16})]}),_?(0,B.jsxs)(`div`,{className:`personal-diagnostics`,children:[(0,B.jsxs)(`code`,{children:[`goal_id: `,he]}),(0,B.jsxs)(`code`,{children:[`kind: `,f.kind]}),f.kind===`run`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`code`,{children:[`session_id: `,f.item.sessionId??m(`drawer.notLinked`)]}),(0,B.jsxs)(`code`,{children:[`turn_id: `,f.item.turnId??m(`common.none`)]}),(0,B.jsxs)(`code`,{children:[`adapter: `,f.item.agentId]}),(0,B.jsxs)(`code`,{children:[`status: `,f.item.sessionStatus??f.item.status]})]}):f.kind===`proposal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`code`,{children:[`action: `,f.item.actionKind]}),(0,B.jsxs)(`code`,{children:[`status: `,f.item.status]})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`code`,{children:[`schedule_id: `,f.item.scheduleId]}),(0,B.jsxs)(`code`,{children:[`status: `,f.item.status??`active`]})]})]}):null]}):null]})]})}var eb=[`checking`,`connecting`,`downloading`,`installing_app`,`installing_runtime`],tb={desktop_status_unavailable:[`无法读取 App 更新状态。请重启 App 后再试;若仍失败,请重新安装最新 App。`,`Cannot read the App update status. Restart the App; if this persists, reinstall the latest App.`],update_feed_unavailable:[`此通道的更新源尚未就绪或暂时不可用。可稍后重新检查,当前版本仍可继续使用。`,`This channel's update feed is not ready or temporarily unavailable. Check again later; you can keep using this version.`],update_feed_invalid:[`更新源格式异常。请稍后重新检查。`,`The update feed is invalid. Check again later.`],update_platform_unavailable:[`此通道尚无适用于本机的更新包。`,`This channel has no update package for this platform.`],update_check_timeout:[`检查更新超时。请稍后重试。`,`The update check timed out. Try again later.`],update_network_failed:[`无法连接更新服务器。请检查网络后重试。`,`Cannot reach the update server. Check your connection and retry.`],update_download_or_signature_failed:[`更新包下载或签名校验失败,尚未安装。请重新检查更新。`,`Download or signature verification failed; the update was not installed. Check for updates again.`]};function nb(e,t=`update_failed`){return{phase:`error`,details:{code:typeof e==`string`&&Object.hasOwn(tb,e)?e:t}}}function rb(){let{locale:e}=Ji(),t=e===`zh-CN`,[n,r]=(0,z.useState)(!1),i=(0,z.useRef)(null),[a,o]=(0,z.useState)(`stable`),[s,c]=(0,z.useState)({phase:`idle`}),[l,u]=(0,z.useState)(``),[d,f]=(0,z.useState)(!1),p=(0,z.useRef)(!1),m=window.__TAURI__?.core.invoke,h=eb.includes(s.phase);(0,z.useEffect)(()=>{let e=i.current;if(!e)return;let t=()=>r(e.matches(`:popover-open`));return e.addEventListener(`toggle`,t),()=>e.removeEventListener(`toggle`,t)},[]),(0,z.useEffect)(()=>{if(!m)return;let e=!0;return m(`desktop_update_status`).then(t=>{if(!e)return;u(t.app_version),f(t.rollback_available===!0),t.state?.phase&&c(t.state);let n=t.state?.details?.channel??(t.app_version.includes(`-main.`)?`main`:`stable`);o(n),t.state?.phase||m(`desktop_update`,{action:`check`,channel:n}).then(t=>{e&&c(t)}).catch(t=>{e&&c(nb(t))})}).catch(()=>{e&&c(nb(null,`desktop_status_unavailable`))}),()=>{e=!1}},[m]),(0,z.useEffect)(()=>{if(!m||!h)return;let e=window.setInterval(()=>{m(`desktop_update_status`).then(e=>{e.state?.phase&&c(e.state)}).catch(()=>{})},1e3);return()=>window.clearInterval(e)},[m,h]);async function g(e){if(!(!m||p.current)){p.current=!0,c({phase:e===`check`?`checking`:e===`repair`?`installing_runtime`:`downloading`});try{if(!l){let e=await m(`desktop_update_status`);u(e.app_version),f(e.rollback_available===!0)}c(await m(`desktop_update`,{action:e,channel:a}))}catch(e){c(nb(e,l?`update_failed`:`desktop_status_unavailable`))}finally{p.current=!1}}}let _={service_error:t?`运行时已安装,但服务尚未连接。可重试更新、修复或恢复上版。`:`Runtime installed, but services are unavailable. Retry updates, repair, or restore the previous version.`,idle:t?`App 会检查可用更新,不会自动安装。`:`Updates are checked automatically, never installed without confirmation.`,runtime_required:t?`请完成匹配组件安装,或检查 App 更新。`:`Install matching components or check for an App update.`,connecting:t?`正在连接更新后的服务…`:`Connecting to updated services…`,checking:t?`正在检查更新…`:`Checking for updates…`,available:t?`新版本已就绪,一次更新 App 与匹配的运行时。`:`Update the App and its matching runtime together.`,up_to_date:t?`当前通道暂无更新。`:`No newer update on this channel.`,downloading:t?`正在下载并校验签名…`:`Downloading and verifying signature…`,installing_app:t?`正在安装 App,请保持窗口打开。`:`Installing the App. Keep this window open.`,installing_runtime:t?`正在安装匹配的运行时,请稍候…`:`Installing the matching runtime…`,restart_required:t?`重启后将自动完成运行时安装与服务连接。`:`Restart to finish runtime installation and reconnect services.`,ready:t?`更新完成,服务已就绪。`:`Update completed; services are ready.`,error:tb[s.details?.code??``]?.[+!t]??(t?`更新未完成。请重试;启动失败可尝试修复当前版本。`:`Update incomplete. Retry; repair this version if startup fails.`)},v=h?t?`正在更新…`:`Updating…`:s.phase===`available`?t?`有可用更新`:`Update available`:s.phase===`restart_required`?t?`重启完成更新`:`Restart to finish`:s.phase===`error`?t?`更新需重试`:`Retry update`:t?`更新 LoopX`:`Update LoopX`;return(0,B.jsxs)(`div`,{className:`personal-desktop-update`,children:[(0,B.jsxs)(`button`,{className:`personal-update-trigger`,type:`button`,"aria-expanded":n,"aria-controls":`desktop-update-panel`,onClick:e=>{i.current?.style.setProperty(`bottom`,`${window.innerHeight-e.currentTarget.getBoundingClientRect().top+8}px`),i.current?.togglePopover()},children:[(0,B.jsx)(um,{size:16,"aria-hidden":`true`}),(0,B.jsx)(`span`,{children:v}),(0,B.jsx)(rm,{size:14,"aria-hidden":`true`})]}),(0,B.jsxs)(`section`,{ref:i,popover:`auto`,id:`desktop-update-panel`,className:`personal-update-panel`,"aria-label":t?`LoopX 更新`:`LoopX updates`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:t?`LoopX 更新`:`LoopX updates`}),(0,B.jsx)(`button`,{type:`button`,"aria-label":t?`关闭更新面板`:`Close updates`,onClick:()=>i.current?.hidePopover(),children:(0,B.jsx)($m,{size:16,"aria-hidden":`true`})})]}),(0,B.jsxs)(`small`,{children:[l,` · `,a===`main`?t?`main 预览版`:`main preview`:t?`稳定版`:`Stable`]}),s.details?.version?(0,B.jsxs)(`p`,{children:[t?`目标版本:`:`Target: `,s.details.version]}):null,(0,B.jsxs)(`p`,{role:`status`,"aria-live":`polite`,children:[h?(0,B.jsx)(Im,{className:`is-spinning`,size:14,"aria-hidden":`true`}):null,_[s.phase]]}),s.phase===`downloading`&&s.details?.total?(0,B.jsx)(`progress`,{"aria-label":t?`下载进度`:`Download progress`,max:s.details.total,value:s.details.received??0}):null,m?(0,B.jsx)(`div`,{className:`personal-update-actions`,children:s.phase===`restart_required`?(0,B.jsx)(`button`,{type:`button`,onClick:()=>void g(`restart`),children:t?`重启完成更新`:`Restart to finish`}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`button`,{type:`button`,disabled:h,onClick:()=>void g(`check`),children:t?`检查更新`:`Check for updates`}),s.phase===`available`?(0,B.jsx)(`button`,{type:`button`,onClick:()=>void g(`apply`),children:t?`更新并准备重启`:`Install update`}):null]})}):(0,B.jsx)(`p`,{children:t?`请在 LoopX App 中更新;浏览器自身无需安装包。`:`Update from the LoopX App; the browser needs no installer.`}),(0,B.jsxs)(`details`,{children:[(0,B.jsx)(`summary`,{children:t?`高级选项`:`Advanced options`}),(0,B.jsxs)(`label`,{children:[t?`更新通道`:`Update channel`,(0,B.jsxs)(`select`,{disabled:h||s.phase===`restart_required`,value:a,onChange:e=>{o(e.target.value),c({phase:`idle`})},children:[(0,B.jsx)(`option`,{value:`stable`,children:t?`稳定版(推荐)`:`Stable (recommended)`}),(0,B.jsx)(`option`,{value:`main`,children:t?`main 预览版`:`main preview`})]})]}),(0,B.jsx)(`p`,{children:t?`App 与匹配的 CLI 一起更新,服务可能短暂断开。不删除 Goal 数据。`:`Updates the App and matching CLI. Services may briefly disconnect. Goal data is not deleted.`}),m?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{children:t?`启动失败时,可重装当前 App 随附的运行时。`:`If startup fails, reinstall this App's bundled runtime.`}),(0,B.jsx)(`button`,{disabled:h||s.phase===`restart_required`,type:`button`,onClick:()=>void g(`repair`),children:t?`修复当前版本`:`Repair this version`})]}):null,m&&d?(0,B.jsxs)(`details`,{children:[(0,B.jsx)(`summary`,{children:t?`恢复上个版本`:`Restore previous version`}),(0,B.jsx)(`p`,{children:t?`将恢复已保留的 App 和它的运行时,需要重启。`:`Restore the retained App and its runtime, then restart.`}),(0,B.jsx)(`button`,{disabled:h,type:`button`,onClick:()=>void g(`rollback`),children:t?`确认恢复上版`:`Restore previous version`})]}):null]})]})]})}var ib=e=>`loopx-sidebar-goal-order-v1:${encodeURIComponent(e)}`;function ab(e){try{let t=JSON.parse(e??`null`);return Array.isArray(t)&&t.every(e=>typeof e==`string`)?[...new Set(t)]:[]}catch{return[]}}function ob(e,t){let n=new Map(t.map((e,t)=>[e,t]));return[...e].sort((e,t)=>(n.get(e.goalId)??1/0)-(n.get(t.goalId)??1/0))}function sb(e,t,n,r,i){if(n===r||!t.includes(n)||!t.includes(r))return e;let a=[...new Set([...e,...t])].filter(e=>e!==n);return a.splice(a.indexOf(r)+Number(i),0,n),a}function cb(e,t){let n=ib(t),[r,i]=(0,z.useState)(()=>{try{return ab(localStorage.getItem(n))}catch{return[]}}),[a,o]=(0,z.useState)(!1),[s,c]=(0,z.useState)(null),[l,u]=(0,z.useState)(null),d=(0,z.useRef)(null),f=(0,z.useRef)(!1),p=ob(e,r),m=p.map(e=>e.goalId);function h(t,a,s){let l=sb(r,m,t,a,s);if(l===r)return;i(l);let u=ob(e,l),d=u.findIndex(e=>e.goalId===t),f=u[d];f&&c({title:f.title,position:d+1});try{localStorage.setItem(n,JSON.stringify(l)),o(!1)}catch{o(!0)}}function g(){d.current=null,u(null)}return{sorted:p,target:l,saveFailed:a,lastMoved:s,move:h,moveBy(e,t){let n=p[m.indexOf(e)+t];n&&h(e,n.goalId,t===1)},pointerProps:e=>({onPointerDown(t){f.current=!1,t.pointerType===`mouse`&&t.button===0&&(d.current={id:e,x:t.clientX,y:t.clientY,dragging:!1},t.currentTarget.setPointerCapture(t.pointerId))},onPointerMove(e){let t=d.current;if(!t||!t.dragging&&Math.hypot(e.clientX-t.x,e.clientY-t.y)<6)return;t.dragging=!0,f.current=!0;let n=document.elementFromPoint(e.clientX,e.clientY)?.closest(`[data-reorder-goal]`),r=e.currentTarget.closest(`.personal-goal-list`),i=n?.dataset.reorderGoal;if(!n||!i||!r?.contains(n)||i===t.id){u(null);return}let a=n.getBoundingClientRect();u({id:i,after:e.clientY>a.top+a.height/2})},onPointerUp(){d.current?.dragging&&l&&h(d.current.id,l.id,l.after),g()},onPointerCancel:g,onLostPointerCapture:g,onKeyDown(e){e.key===`Escape`&&g()},onClickCapture(e){f.current&&=(e.preventDefault(),e.stopPropagation(),!1)}})}}var lb=`/ssh-hosts`,ub=/^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;function db(e){return typeof e==`string`&&ub.test(e.trim())}function fb(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`SSH Host 列表响应无效。`);let t=e;if(t.ok!==!0||t.schema_version!==`ssh_host_catalog_v0`||!Array.isArray(t.hosts))throw Error(`SSH Host 列表协议不兼容,请更新本机 LoopX 服务。`);let n=new Set;return{hosts:t.hosts.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=String(e.alias??``).trim();return!db(t)||n.has(t)?[]:(n.add(t),[{alias:t}])}),schemaVersion:`ssh_host_catalog_v0`}}async function pb(e=fetch,t=lb){let n=await e(t,{cache:`no-store`});if(!n.ok)throw Error(`无法读取本机 SSH Host(HTTP ${n.status})。`);return fb(await n.json())}function mb(e,t){let n=e.trim();if(!db(n))return{error:`请选择有效的 SSH Host。`};let r=Number(t);return!Number.isInteger(r)||r<1024||r>65535?{error:`本地端口必须是 1024–65535 之间的整数。`}:{command:`ssh -N -L ${r}:127.0.0.1:8766 ${n}`,hostAlias:n,label:n,statusUrl:`http://127.0.0.1:${r}/status.json`}}var hb=`/api/ssh-source/ensure`,gb=`/api/ssh-source/goal-lifecycle`;async function _b(e,t){let n=await fetch(hb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({host_alias:e,local_port:Number(t)})}),r=await n.json().catch(()=>null);if(!n.ok)throw Error(r?.error??`无法建立 SSH 隧道来源。`);if(!r?.ok)throw Error(`无法建立 SSH 隧道来源。`);return r}async function vb(e,t,n,r,i=fetch){let a=await i(gb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({goal_id:t,host_alias:e,operation:n,reason:r})}),o=await a.json().catch(()=>null);if(!a.ok)throw Error(o?.error??`无法更新远端 Goal 生命周期。`);if(!o?.ok||o.schema_version!==`loopx_remote_goal_lifecycle_v1`||o.goal_id!==t||o.host_alias!==e||o.operation!==n||o.activation_state!==(n===`stop`?`stopped`:`active`)||o.projection_verified!==!0)throw Error(`远端 Goal 生命周期回读未验证。`);return o}function yb({activeSource:e,connectionState:t,errorMessage:n,onAdd:r,onConfiguredHostsLoaded:i,onRemove:a,onSelect:o,sources:s}){let{t:c}=Ji(),[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(null),[p,m]=(0,z.useState)(`configured`),[h,g]=(0,z.useState)([]),[_,v]=(0,z.useState)(null),[y,b]=(0,z.useState)(!1),[x,S]=(0,z.useState)(!1),[C,w]=(0,z.useState)(``),[T,E]=(0,z.useState)(``),[D,O]=(0,z.useState)(`8876`),[ee,te]=(0,z.useState)(``),ne=`configured:`,k=[...s.map(e=>({label:e.label,value:e.id})),...h.filter(e=>!s.some(t=>t.label===e.alias)).map(e=>({group:c(`source.configuredGroup`,{count:h.length}),label:e.alias,value:`${ne}${e.alias}`}))],A=(0,z.useMemo)(()=>h.some(e=>e.alias===C)?mb(C,D):{error:c(`source.selectHost`)},[h,C,D,c]);(0,z.useEffect)(()=>{j()},[]);async function j(){b(!0),v(null);try{let e=await pb();g(e.hosts),i?.(e.hosts.map(e=>e.alias)),w(t=>t||e.hosts[0]?.alias||``),e.hosts.length||v(c(`source.hostEmpty`))}catch(e){v(e instanceof Error?e.message:c(`source.hostLoadError`))}finally{b(!1)}}function M(){u(!0),m(`configured`),f(null),j()}function N(){u(!1),m(`configured`),v(null),S(!1),w(``),f(null),E(``),O(`8876`),te(``)}function P(){let e=r({label:T,statusUrl:ee});if(e.error){f(e.error);return}N()}function F(){if(`error`in A){f(A.error??c(`source.invalid`));return}let e=r({ensureTunnel:!0,hostAlias:A.hostAlias,label:A.label,statusUrl:A.statusUrl});if(e.error){f(e.error);return}N()}function re(e){let t=new Set;for(let e of s)try{t.add(new URL(e.statusUrl).port)}catch{}let n=`8877`;for(let e=8877;e<9077;e+=1)if(!t.has(String(e))){n=String(e);break}let i=mb(e,n);if(`error`in i){f(i.error??c(`source.invalid`));return}let a=r({ensureTunnel:!0,hostAlias:i.hostAlias,label:i.label,statusUrl:i.statusUrl});a.error?f(a.error):f(null),O(n)}async function ie(){if(`error`in A){f(A.error??c(`source.invalid`));return}try{await navigator.clipboard.writeText(A.command),S(!0),f(null)}catch{f(c(`source.copyError`))}}return(0,B.jsxs)(`section`,{"aria-label":c(`source.controlPlane`),className:`personal-status-source`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`span`,{children:`Control plane`}),(0,B.jsx)(`button`,{"aria-label":c(`source.addSsh`),onClick:M,title:c(`source.add`),type:`button`,children:(0,B.jsx)(Pm,{size:14})})]}),(0,B.jsx)(Cy,{ariaLabel:c(`source.select`),className:`personal-status-source-select`,icon:(0,B.jsx)(Hm,{size:15}),onChange:e=>{if(e.startsWith(ne)){re(e.slice(11));return}o(e)},options:k,value:e.id}),(0,B.jsxs)(`div`,{className:`personal-status-source-meta`,children:[(0,B.jsxs)(`span`,{className:`is-${t}`,children:[(0,B.jsx)(`i`,{}),c(t===`loading`?`source.connecting`:t===`error`?`source.notAvailable`:`source.connected`)]}),(0,B.jsx)(`small`,{children:e.readOnly?c(`source.readOnly`):c(`source.localInteractive`)}),e.kind===`ssh_tunnel`?(0,B.jsx)(`button`,{"aria-label":c(`source.remove`,{source:e.label}),onClick:()=>a(e.id),title:c(`source.removeCurrent`),type:`button`,children:(0,B.jsx)(Xm,{size:12})}):null]}),n?(0,B.jsx)(`p`,{className:`personal-status-source-error`,role:`alert`,children:n}):null,l?(0,B.jsxs)(`div`,{className:`personal-status-source-form`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:c(`source.addSsh`)}),(0,B.jsx)(`button`,{"aria-label":c(`source.closeForm`),onClick:N,type:`button`,children:(0,B.jsx)($m,{size:13})})]}),(0,B.jsxs)(`div`,{"aria-label":c(`source.addMethod`),className:`personal-status-source-modes`,role:`tablist`,children:[(0,B.jsx)(`button`,{"aria-selected":p===`configured`,onClick:()=>{m(`configured`),f(null)},role:`tab`,type:`button`,children:c(`source.configured`)}),(0,B.jsx)(`button`,{"aria-selected":p===`manual`,onClick:()=>{m(`manual`),f(null)},role:`tab`,type:`button`,children:c(`source.manual`)})]}),p===`configured`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.configuredCount`,{count:h.length})}),(0,B.jsxs)(`span`,{className:`personal-status-source-field-row`,children:[(0,B.jsx)(`input`,{"aria-label":c(`source.host`),disabled:y||!h.length,list:`loopx-configured-ssh-hosts`,onChange:e=>{w(e.target.value),S(!1)},placeholder:c(y?`source.loadingHosts`:`source.hostPlaceholder`),value:C}),(0,B.jsx)(`datalist`,{id:`loopx-configured-ssh-hosts`,children:h.map(e=>(0,B.jsx)(`option`,{value:e.alias},e.alias))}),(0,B.jsx)(`button`,{"aria-label":c(`source.refreshHosts`),disabled:y,onClick:()=>void j(),title:c(`source.refreshHosts`),type:`button`,children:(0,B.jsx)(Rm,{size:13})})]})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.localPort`)}),(0,B.jsx)(`input`,{"aria-label":c(`source.localPort`),inputMode:`numeric`,onChange:e=>{O(e.target.value),S(!1)},value:D})]}),(0,B.jsxs)(`div`,{className:`personal-status-source-command`,children:[(0,B.jsx)(`code`,{children:`error`in A?c(`source.tunnelCommandPending`):A.command}),(0,B.jsxs)(`button`,{"aria-label":c(`source.copyCommand`),disabled:`error`in A,onClick:()=>void ie(),type:`button`,children:[(0,B.jsx)(cm,{size:12}),c(x?`source.copied`:`source.copy`)]})]}),_?(0,B.jsx)(`p`,{className:`is-error`,children:_}):null,(0,B.jsx)(`p`,{children:c(`source.description`)}),(0,B.jsx)(`button`,{className:`personal-status-source-add`,disabled:`error`in A,onClick:F,type:`button`,children:c(`source.addConfigured`)})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.name`)}),(0,B.jsx)(`input`,{autoFocus:!0,maxLength:48,onChange:e=>E(e.target.value),placeholder:c(`source.namePlaceholder`),value:T})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.statusUrl`)}),(0,B.jsx)(`input`,{onChange:e=>te(e.target.value),placeholder:`http://127.0.0.1:8876/status.json`,value:ee})]}),(0,B.jsx)(`p`,{children:(0,B.jsx)(`code`,{children:`ssh -N -L 8876:127.0.0.1:8766 `})}),(0,B.jsx)(`p`,{children:c(`source.manualDescription`)}),(0,B.jsx)(`button`,{className:`personal-status-source-add`,onClick:P,type:`button`,children:c(`source.addConfigured`)})]}),d?(0,B.jsx)(`p`,{className:`is-error`,role:`alert`,children:d}):null]}):null]})}var bb={需修复:`is-danger`,等你:`is-warning`,等待条件:`is-info`,推进中:`is-success`,安静运行:`is-quiet`,已完成:`is-quiet`,已停止:`is-stopped`};function xb({attentionCount:e,goals:t,goalArchiveLoadState:n={error:null,phase:`ready`},lifecycleBusyGoalIds:r,goalLifecycleOperations:i,onRequestGoalCreate:a,onOpenSettings:o,onRetryGoalArchive:s,onRequestGoalLifecycle:c,onSelectGoal:l,selectedGoalId:u,statusSourceControl:d}){let{locale:f,t:p}=Ji(),[m,h]=(0,z.useState)(!1),g=cb(t.filter(e=>e.activationState!==`stopped`),d?.activeSource.statusUrl??`/status.json`),_=g.sorted,v=t.filter(e=>e.activationState===`stopped`),y=e=>!!c&&(!i||i.includes(e)),b=(e,t)=>(0,B.jsxs)(`div`,{className:`personal-goal-row${g.target?.id===e.goalId?g.target.after?` is-drop-after`:` is-drop-before`:``}`,"data-reorder-goal":t?void 0:e.goalId,"data-load-error":e.loadError,children:[(0,B.jsxs)(`button`,{...t?{}:g.pointerProps(e.goalId),title:t?void 0:p(`sidebar.dragGoal`),"aria-current":u===e.goalId?`page`:void 0,className:`personal-goal-link`,onClick:()=>l(e.goalId),type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-goal-state-dot ${e.loadState?``:bb[e.state]}`}),(0,B.jsxs)(`span`,{className:`personal-goal-link-copy`,children:[(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsxs)(`small`,{children:[e.loadState&&(!t||u===e.goalId)?p(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Yi(e.state,f),e.needsYou&&!t?` · ${p(`home.lane.needsYou`)}`:``]})]}),(0,B.jsx)(nm,{size:15})]}),!t&&m?(0,B.jsxs)(`div`,{className:`personal-goal-move-actions`,children:[(0,B.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveUp`,{goal:e.title}),disabled:_[0]?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,-1),children:(0,B.jsx)(Jp,{"aria-hidden":`true`,size:13})}),(0,B.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveDown`,{goal:e.title}),disabled:_.at(-1)?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,1),children:(0,B.jsx)(Wp,{"aria-hidden":`true`,size:13})})]}):null,c&&y(t?`resume`:`stop`)?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`button`,{"aria-label":`${p(t?`sidebar.resume`:`sidebar.stop`)} ${e.title}`,"aria-busy":r?.has(e.goalId)||void 0,className:`personal-goal-lifecycle${r?.has(e.goalId)?` is-pending`:``}`,disabled:r?.has(e.goalId),onClick:()=>c(e,t?`resume`:`stop`),title:p(t?`sidebar.resumeGoal`:`sidebar.stopGoal`),type:`button`,children:r?.has(e.goalId)?(0,B.jsx)(Cm,{size:13}):t?(0,B.jsx)(Lm,{size:13}):(0,B.jsx)(Mm,{size:13})}),t&&y(`delete`)?(0,B.jsx)(`button`,{"aria-label":`${p(`sidebar.delete`)} ${e.title}`,className:`personal-goal-lifecycle personal-goal-delete`,onClick:()=>c(e,`delete`),title:p(`sidebar.deleteGoal`),type:`button`,children:(0,B.jsx)(Xm,{size:13})}):null]}):null]},e.goalId);return(0,B.jsxs)(`div`,{className:`personal-goal-directory`,children:[(0,B.jsxs)(`div`,{className:`personal-sidebar-brand`,children:[(0,B.jsx)(`span`,{className:`personal-brand-mark`,children:(0,B.jsx)(Zp,{size:18})}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:`LoopX`})})]}),d?(0,B.jsx)(yb,{...d}):null,(0,B.jsxs)(`nav`,{"aria-label":p(`home.workspace`),className:`personal-sidebar-nav`,children:[(0,B.jsxs)(`button`,{"aria-current":u===null?`page`:void 0,className:`personal-manager-link`,onClick:()=>l(null),type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-manager-icon`,children:(0,B.jsx)(Zp,{size:17})}),(0,B.jsx)(`span`,{children:p(`sidebar.manager`)}),e>0?(0,B.jsx)(`span`,{className:`personal-sidebar-count`,children:e}):null,(0,B.jsx)(nm,{size:15})]}),(0,B.jsxs)(`div`,{className:`personal-sidebar-section-title`,children:[(0,B.jsx)(`span`,{children:`Goals`}),(0,B.jsxs)(`span`,{className:`personal-sidebar-title-actions`,children:[(0,B.jsx)(`small`,{children:_.length}),(0,B.jsx)(`button`,{"aria-label":p(`sidebar.sortGoals`),title:p(`sidebar.sortGoals`),"aria-pressed":m,onClick:()=>h(!m),type:`button`,children:(0,B.jsx)(qp,{"aria-hidden":`true`,size:15})}),a?(0,B.jsx)(`button`,{"aria-label":p(`sidebar.createGoal`),onClick:a,type:`button`,children:(0,B.jsx)(Pm,{size:15})}):null]})]}),g.saveFailed?(0,B.jsx)(`p`,{role:`status`,children:p(`sidebar.orderNotSaved`)}):null,(0,B.jsx)(`span`,{className:`personal-sr-only`,role:`status`,children:g.lastMoved?p(`sidebar.goalMoved`,{goal:g.lastMoved.title,position:g.lastMoved.position}):``}),(0,B.jsx)(`div`,{className:`personal-goal-list`,children:_.map(e=>b(e,!1))}),v.length||n.phase===`loading`||n.phase===`error`?(0,B.jsxs)(`details`,{className:`personal-stopped-goals`,open:n.phase===`error`||void 0,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(tm,{size:13}),(0,B.jsx)(`span`,{children:p(`sidebar.stopped`)}),n.phase===`loading`?(0,B.jsx)(Cm,{"aria-label":p(`sidebar.stoppedLoading`),className:`is-spinning`,size:13}):(0,B.jsx)(`small`,{children:v.length})]}),(0,B.jsxs)(`div`,{className:`personal-goal-list is-stopped`,children:[n.phase===`error`?(0,B.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`alert`,children:[(0,B.jsx)(`span`,{children:p(`sidebar.stoppedLoadFailed`)}),s?(0,B.jsx)(`button`,{onClick:s,type:`button`,children:p(`sidebar.retryStopped`)}):null]}):null,v.map(e=>b(e,!0))]})]}):null]}),(0,B.jsxs)(`div`,{className:`personal-sidebar-footer`,children:[(0,B.jsx)(rb,{}),o?(0,B.jsxs)(`button`,{"aria-label":p(`settings.open`),className:`personal-sidebar-utility`,onClick:o,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-sidebar-utility-icon`,children:(0,B.jsx)(Um,{size:17})}),(0,B.jsx)(`span`,{className:`personal-sidebar-utility-copy`,children:(0,B.jsx)(`strong`,{children:p(`settings.open`)})}),(0,B.jsx)(nm,{"aria-hidden":`true`,size:15})]}):null]})]})}var Sb=J({ok:X(!0),total:G().int().nonnegative(),next_cursor:W().nullable(),items:q(J({todo_id:W(),text:W(),claimed_by:W().nullable(),evidence:W().nullable(),priority:W().nullable(),task_class:W().nullable()})).max(40)});function Cb({goal:e,agentId:t,seed:n,enabled:r,listView:i=!1,onSelect:a}){let{t:o}=Ji(),s=(0,z.useId)(),[c,l]=(0,z.useState)(!1),u=!i||c,d=i?96:148,[f,p]=(0,z.useState)(n),[m,h]=(0,z.useState)(t===`all`?e.doneTodoCount??n.length:n.length),[g,_]=(0,z.useState)(void 0),[v,y]=(0,z.useState)(!1),[b,x]=(0,z.useState)(!1),[S,C]=(0,z.useState)(!1),[w,T]=(0,z.useState)({top:0,height:600}),[E,D]=(0,z.useState)(null),O=(0,z.useRef)(null),ee=(0,z.useRef)(null),[te,ne]=(0,z.useState)(0);(0,z.useEffect)(()=>{let e=O.current;if(!e)return;let t=new ResizeObserver(()=>T({top:e.scrollTop,height:e.clientHeight}));return t.observe(e),()=>{t.disconnect(),ee.current?.abort()}},[]);let k=g===void 0||w.top+w.height>=f.length*d-d*2;(0,z.useEffect)(()=>{if(!r||!u||!k||g===null||b||ee.current)return;let n=new AbortController;ee.current=n,y(!0);let i=new URLSearchParams({goal_id:e.goalId});t!==`all`&&i.set(`agent_id`,t),g&&i.set(`cursor`,g),fetch(`/api/chat/completed-todos?${i}`,{signal:n.signal}).then(async e=>{if(e.status===409&&C(!0),!e.ok)throw Error(`history unavailable`);let t=Sb.parse(await e.json());if(n.signal.aborted)return;let r=t.items.map(e=>({todoId:e.todo_id,text:e.text,claimedBy:e.claimed_by,evidence:e.evidence,priority:e.priority,taskClass:e.task_class,done:!0,status:`done`}));p(e=>g===void 0?r:[...e,...r.filter(t=>!e.some(e=>e.todoId===t.todoId))]),h(t.total),_(t.next_cursor)}).catch(()=>{n.signal.aborted||x(!0)}).finally(()=>{n.signal.aborted||(ee.current=null,y(!1))})},[r,u,k,g,b,te,e.goalId,t,v]),(0,z.useEffect)(()=>{O.current&&(O.current.scrollTop=0),T({top:0,height:O.current?.clientHeight??600}),D(null)},[i]);let A=Math.max(0,Math.floor(w.top/d)-3),j=Math.min(f.length,Math.ceil((w.top+w.height)/d)+3),M=Array.from({length:Math.max(0,j-A)},(e,t)=>A+t);return E!==null&&El(e=>!e),children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,children:c?`▾`:`▸`}),` `,o(`tasks.completed`)]}):(0,B.jsxs)(`strong`,{children:[(0,B.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-done`}),o(`tasks.completed`)]}),(0,B.jsx)(`span`,{children:m})]}),(0,B.jsxs)(`div`,{id:s,hidden:!u,"aria-label":o(`tasks.completed`),className:`personal-task-lane-scroll`,ref:O,role:`region`,tabIndex:0,onScroll:e=>T({top:e.currentTarget.scrollTop,height:e.currentTarget.clientHeight}),children:[(0,B.jsx)(`div`,{className:`personal-completed-window`,style:{height:f.length*d},children:M.map(t=>{let n=f[t];return(0,B.jsx)(`div`,{className:`personal-task-card personal-completed-row`,style:{top:t*d,height:d},children:(0,B.jsxs)(`button`,{type:`button`,onFocus:()=>D(t),onBlur:()=>D(null),onClick:()=>a({kind:`todo`,item:{...n,goalId:e.goalId,goalTitle:e.title,ownerLabel:n.claimedBy??e.agentLabel??e.agentId}}),children:[(0,B.jsx)(`span`,{className:`is-done`,children:`✓`}),(0,B.jsx)(`strong`,{children:n.text}),(0,B.jsx)(`small`,{children:n.claimedBy??e.agentLabel??e.agentId})]})},n.todoId)})}),(0,B.jsx)(`div`,{className:`personal-completed-footer`,role:`status`,children:v?o(`tasks.historyLoading`):b?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`span`,{children:o(S?`tasks.historyExpired`:`tasks.historyError`)}),(0,B.jsx)(`button`,{type:`button`,onClick:()=>{S&&(_(void 0),O.current&&(O.current.scrollTop=0)),C(!1),x(!1),ne(e=>e+1)},children:o(`tasks.historyRetry`)})]}):r?g===null?o(`tasks.historyEnd`):(0,B.jsx)(`button`,{type:`button`,onClick:()=>{O.current&&(O.current.scrollTop=f.length*d)},children:o(`tasks.historyMore`)}):o(`tasks.historyLocalOnly`)})]})]})}function wb({children:e,count:t,label:n,tone:r,listView:i=!1}){let a=(0,z.useId)(),o=(0,z.useRef)(null),s=(0,z.useRef)([]),c=(0,z.useRef)(null),[l,u]=(0,z.useState)({after:!1,before:!1}),d=(0,z.useCallback)(()=>{let e=o.current;if(!e)return;let t={after:Math.max(0,e.scrollHeight-e.clientHeight)-e.scrollTop>1,before:e.scrollTop>1};u(e=>e.after===t.after&&e.before===t.before?e:t)},[]);return(0,z.useEffect)(()=>{let e=o.current;if(!e)return;let t=new ResizeObserver(d);return c.current=t,t.observe(e),e.addEventListener(`scroll`,d,{passive:!0}),d(),()=>{t.disconnect(),c.current=null,s.current=[],e.removeEventListener(`scroll`,d)}},[i,d]),(0,z.useEffect)(()=>{let e=o.current,t=c.current;if(!e||!t)return;for(let e of s.current)t.unobserve(e);let n=Array.from(e.children).filter(e=>e instanceof HTMLElement);for(let e of n)t.observe(e);s.current=n,d()},[e,t,i,d]),i?!t&&r!==`done`?null:(0,B.jsxs)(`details`,{className:`personal-task-group tone-${r}`,open:!0,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(tm,{size:16}),(0,B.jsx)(`strong`,{children:n}),(0,B.jsx)(`span`,{children:t})]}),(0,B.jsx)(`div`,{className:`personal-task-list-rows`,children:e})]}):(0,B.jsxs)(`section`,{className:`personal-object-list personal-task-lane`,children:[(0,B.jsxs)(`header`,{id:a,children:[(0,B.jsxs)(`strong`,{children:[(0,B.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-${r}`}),n]}),(0,B.jsx)(`span`,{children:t})]}),(0,B.jsx)(`div`,{"aria-labelledby":a,className:`personal-task-lane-scroll${l.before?` has-overflow-before`:``}${l.after?` has-overflow-after`:``}`,ref:o,role:`region`,tabIndex:t>0?0:-1,children:e})]})}function Tb({historyEnabled:e=!1,goal:t,items:n,onDraftTaskFromMessage:r,onOpenChat:i,onQuickComplete:a,quickCompletingTodoIds:o,onSelect:s,selectedTodoId:c=null,userTodos:l}){let{t:u}=Ji(),[d,f]=(0,z.useState)(!1),[p,m]=(0,z.useState)({goalId:``,laneId:`all`}),h=(0,z.useRef)(null);(0,z.useEffect)(()=>{if(!c)return;let e=window.requestAnimationFrame(()=>h.current?.scrollIntoView({block:`nearest`,inline:`nearest`}));return()=>window.cancelAnimationFrame(e)},[c]);let g=l.filter(e=>e.goalId===t.goalId).map(e=>({...e,goalTitle:t.title})),_=e=>e.priority===`P0`?0:e.priority===`P1`?1:e.priority===`P2`?2:3,v=(0,z.useMemo)(()=>{let e=new Map((t.agentLanes??[]).map(e=>[e.agentId,e]));for(let n of t.agentTodos)n.claimedBy&&!e.has(n.claimedBy)&&e.set(n.claimedBy,{agentId:n.claimedBy,label:n.claimedBy});return[...e.values()]},[t.agentLanes,t.agentTodos]),y=p.goalId===t.goalId&&v.some(e=>e.agentId===p.laneId)?p.laneId:`all`,b=e=>y===`all`||e===y,x=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&!e.done).filter(e=>b(e.claimedBy)).sort((e,t)=>_(e)-_(t)),S=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&e.done).filter(e=>b(e.claimedBy)),C=n.filter(e=>e.kind===`schedule`&&b(e.schedule.agentId)),w=n.filter(e=>e.kind===`run`&&!!e.run.todoId&&b(e.run.agentId)),T=!g.length&&!x.length&&!S.length&&!C.length,E=n.filter(e=>e.kind===`message`&&(e.message.role===`user`||e.message.role===`assistant`)),D=E.reduce((e,t,n)=>t.message.role===`user`?n:e,-1),O=D>=0?E[D]?.message:null,ee=D>=0?E.slice(D+1).reverse().find(e=>e.message.role===`assistant`)?.message:null,te=D>=0&&E.slice(D+1).some(e=>e.message.role===`assistant`&&e.message.pending);return(0,B.jsxs)(`section`,{"aria-label":u(`header.tasks`),className:`personal-task-board${d?` is-list-view`:``}`,children:[(0,B.jsxs)(`header`,{className:`personal-task-view-toolbar`,children:[(0,B.jsx)(`div`,{children:(0,B.jsx)(`strong`,{children:u(`header.tasks`)})}),(0,B.jsxs)(`div`,{className:`personal-task-view-switch`,role:`group`,"aria-label":u(`tasks.viewLabel`),children:[(0,B.jsx)(`button`,{type:`button`,"aria-pressed":d,onClick:()=>f(!0),children:u(`tasks.listView`)}),(0,B.jsx)(`button`,{type:`button`,"aria-pressed":!d,onClick:()=>f(!1),children:u(`tasks.boardView`)})]})]}),v.length>1?(0,B.jsxs)(`section`,{"aria-label":u(`tasks.agentLaneFilter`),className:`personal-task-lane-filter`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(Zp,{size:15}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:u(`tasks.agentLane`)})})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{className:`sr-only`,children:u(`tasks.agentLaneFilter`)}),(0,B.jsxs)(`select`,{"aria-label":u(`tasks.agentLaneFilter`),onChange:e=>m({goalId:t.goalId,laneId:e.target.value}),value:y,children:[(0,B.jsx)(`option`,{value:`all`,children:u(`tasks.allAgentLanes`,{count:v.length})}),v.map(e=>(0,B.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))]}),(0,B.jsx)(tm,{"aria-hidden":!0,size:14})]})]}):null,O?(0,B.jsxs)(`section`,{"aria-label":u(`tasks.chatRecent`),className:`personal-task-chat-receipt`,children:[(0,B.jsx)(`span`,{className:`personal-task-chat-icon`,children:(0,B.jsx)(Dm,{size:18})}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:u(te?`tasks.chatPending`:ee?`tasks.chatAgentReplied`:`tasks.chatRecent`)}),(0,B.jsx)(`small`,{children:t.agentLabel??t.agentId})]}),(0,B.jsxs)(`p`,{className:`is-user`,children:[(0,B.jsx)(`b`,{children:u(`common.you`)}),O.text]}),ee&&!ee.pending?(0,B.jsxs)(`p`,{className:`is-assistant`,children:[(0,B.jsx)(`b`,{children:u(`common.agent`)}),ee.text]}):null,(0,B.jsx)(`small`,{children:u(te?`tasks.chatPendingDescription`:`tasks.chatUnchangedDescription`)})]}),(0,B.jsxs)(`footer`,{children:[(0,B.jsxs)(`button`,{onClick:i,type:`button`,children:[(0,B.jsx)(Dm,{size:14}),u(`tasks.chatViewReply`)]}),ee&&!te&&r?(0,B.jsxs)(`button`,{onClick:()=>r(ee.text),type:`button`,children:[(0,B.jsx)(Sm,{size:14}),u(`tasks.convertToTask`)]}):null]})]}):null,(0,B.jsxs)(`div`,{className:d?`personal-task-grouped-list`:`personal-task-kanban`,children:[(0,B.jsxs)(wb,{listView:d,count:g.length,label:u(`timeline.waitingConfirmation`),tone:`attention`,children:[g.map(e=>{let t=Zi(e.updatedAt,u);return(0,B.jsxs)(`button`,{onClick:()=>s({item:e,kind:`attention`}),type:`button`,children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,className:`is-attention`,children:`!`}),(0,B.jsx)(`strong`,{children:e.text}),(0,B.jsxs)(`small`,{children:[(0,B.jsx)(`span`,{className:`personal-row-status ${e.blocking?`is-blocking`:`is-pending`}`,children:e.blocking?u(`tasks.blocked`):u(`tasks.pending`)}),t?(0,B.jsx)(`span`,{className:`personal-task-age`,children:u(`tasks.waitingAge`,{age:t})}):null]})]},e.todoId)}),g.length?null:(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyConfirm`)})]}),(0,B.jsxs)(wb,{listView:d,count:x.length,label:u(`tasks.pendingAndRunning`),tone:`progress`,children:[x.map(e=>{let n={...e,goalId:t.goalId,goalTitle:t.title,ownerLabel:e.claimedBy??t.agentLabel??t.agentId},r=w.find(t=>t.run.todoId===e.todoId)?.run;return(0,B.jsxs)(`div`,{className:`personal-task-card${r?` has-session`:``}${c===e.todoId?` is-selected`:``}`,ref:c===e.todoId?e=>{h.current=e}:void 0,children:[(0,B.jsxs)(`button`,{"aria-pressed":c===e.todoId,onClick:()=>s({item:n,kind:`todo`}),type:`button`,children:[(0,B.jsx)(`span`,{children:`○`}),(0,B.jsx)(`strong`,{children:e.text}),(0,B.jsxs)(`small`,{children:[e.priority?(0,B.jsx)(`span`,{className:`personal-priority-badge is-${e.priority.toLowerCase()}`,children:e.priority}):null,e.status===`blocked`?(0,B.jsx)(`span`,{className:`personal-priority-badge is-blocked`,children:u(`tasks.blocked`)}):null,r?(0,B.jsx)(`span`,{className:`personal-task-session-status`,children:r.status===`running`||r.status===`queued`?u(`runs.running`):r.status===`failed`?u(`tasks.sessionError`):u(`common.waiting`)}):null,e.status===`deferred`?(0,B.jsx)(`span`,{className:`personal-task-session-status`,children:u(`drawer.taskStatusDeferred`)}):r?null:(0,B.jsx)(`span`,{className:`personal-task-session-status`,children:u(`tasks.waiting`)}),e.claimedBy??t.agentLabel??t.agentId]})]}),(0,B.jsxs)(`div`,{className:`personal-task-card-actions`,children:[r?(0,B.jsxs)(`button`,{className:`personal-task-session-link`,"aria-label":u(`tasks.openExecution`,{name:e.text}),onClick:()=>s({item:r,kind:`run`}),title:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`),type:`button`,children:[(0,B.jsx)(fm,{size:14}),(0,B.jsx)(`span`,{children:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`)})]}):null,a?(0,B.jsx)(`button`,{"aria-busy":o?.has(e.todoId)||void 0,"aria-label":u(`tasks.markComplete`,{name:e.text}),disabled:o?.has(e.todoId),onClick:()=>void a(n),title:u(`tasks.completed`),type:`button`,children:o?.has(e.todoId)?(0,B.jsx)(Cm,{className:`personal-spin`,size:14}):(0,B.jsx)(em,{size:14})}):null,(0,B.jsx)(`button`,{"aria-label":u(`tasks.moreActions`,{name:e.text}),onClick:()=>s({item:n,kind:`todo`}),title:u(`common.actions`),type:`button`,children:(0,B.jsx)(dm,{size:14})})]})]},e.todoId)}),x.length?null:(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyRunning`)})]}),(0,B.jsxs)(wb,{listView:d,count:C.length,label:u(`tasks.scheduled`),tone:`schedule`,children:[C.map(e=>(0,B.jsxs)(`button`,{onClick:()=>s({item:e.schedule,kind:`schedule`}),type:`button`,children:[(0,B.jsx)(`span`,{children:`◷`}),(0,B.jsx)(`strong`,{children:e.schedule.label}),(0,B.jsx)(`small`,{children:e.schedule.status===`paused`?u(`schedule.paused`):u(`schedule.active`)})]},e.id)),C.length?null:(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptySchedules`)})]}),(0,B.jsx)(Cb,{goal:t,agentId:y,seed:S,enabled:e,listView:d,onSelect:s},`${t.goalId}:${y}:${e}`)]}),T?(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyGoal`)}):null]})}function Eb(e,t){return{live_steering:{label:t(`lark.ingressSteering`),detail:t(`lark.ingressSteeringDescription`)},session_queue:{label:t(`lark.ingressQueue`),detail:t(`lark.ingressQueueDescription`)},async_inbox:{label:t(`lark.ingressAsync`),detail:t(`lark.ingressAsyncDescription`)},direct_session:{label:t(`lark.ingressLegacy`),detail:t(`lark.ingressLegacyDescription`)}}[e]}function Db(e,t){return e.listener_status===`starting`?{label:t(`lark.health.starting`),detail:t(`lark.health.startingDetail`),state:`not_ready`}:e.listener_status===`retrying`&&e.listener_error_code===`lark_event_source_disconnected`?{label:t(`lark.health.sourceDisconnected`),detail:t(`lark.health.sourceDisconnectedDetail`),state:`not_ready`}:e.listener_status===`retrying`?{label:t(`lark.health.retrying`),detail:t(`lark.health.retryingDetail`),state:`not_ready`}:e.listener_status===`stopped`||e.listener_status===null?{label:t(`lark.health.notStarted`),detail:t(`lark.health.notStartedDetail`),state:`not_ready`}:e.last_event_status===`message_context_permission_required`?{label:t(`lark.health.messageContextPermission`),detail:t(`lark.health.messageContextPermissionDetail`),state:`not_ready`}:e.last_event_status===`processing_failed`?{label:t(`lark.health.processingFailed`),detail:t(`lark.health.processingFailedDetail`),state:`not_ready`}:e.health_error_code===`invalid_routing_state`?{label:t(`lark.health.invalidRouting`),detail:t(`lark.health.invalidRoutingDetail`),state:`not_ready`}:e.last_event_status===`queued_for_agent`?{label:t(`lark.health.queued`),detail:t(`lark.health.queuedDetail`,{agent:e.agent_id??t(`lark.targetAgent`)}),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`not_addressed`?{label:t(`lark.health.notAddressed`),detail:t(`lark.health.notAddressedDetail`),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`self_message`?{label:t(`lark.health.listening`),detail:t(`lark.health.ignoredSelf`),state:`ready`}:e.health_error_code===`lark_event_route_mismatch`||[`chat_mismatch`,`topic_mismatch`,`route_ambiguous`].includes(e.last_event_reason??``)?{label:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguous`):t(`lark.health.routeMismatch`),detail:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguousDetail`):t(`lark.health.routeMismatchDetail`),state:`not_ready`}:[`invalid_event`,`binding_unavailable`].includes(e.last_event_reason??``)?{label:t(`lark.health.routeUnavailable`),detail:t(`lark.health.routeUnavailableDetail`),state:`not_ready`}:e.last_event_status===`replied_and_acknowledged`?{label:t(`lark.health.listening`),detail:t(`lark.health.eventProcessed`,{events:e.event_count,replies:e.replied_count}),state:`ready`}:e.health_error_code===`lark_event_delivery_unverified`||e.event_count===0?{label:t(`lark.health.eventUnverified`),detail:t(`lark.health.eventUnverifiedDetail`),state:`unverified`}:{label:e.reply_ready?t(`lark.health.listening`):t(`lark.health.unavailable`),detail:t(`lark.health.lastStatus`,{status:e.last_event_status??t(`lark.health.waiting`)}),state:e.reply_ready?`ready`:`not_ready`}}function Ob(e){return e.history_permission_guidance?.api_document_url??null}function kb(e,t,n){if(e instanceof Th){let t=String(e.payload.error_code??``);return{lark_cli_not_installed:n(`lark.error.cliMissing`),lark_cli_not_executable:n(`lark.error.cliExecutable`),lark_cli_start_failed:n(`lark.error.cliStart`),lark_message_permissions_required:n(`lark.error.messagePermissions`),lark_app_required:n(`lark.error.appRequired`),invalid_lark_app:n(`lark.error.invalidApp`),lark_group_lookup_failed:n(`lark.error.groupLookup`),provider_api_failed:n(`lark.error.provider`)}[t]??e.message}return e instanceof Error?e.message:t}function Ab({embedded:e=!1,focusGoalConnection:t=!1,goals:n,initialGoalId:r,onChanged:i,onClose:a}){let{t:o}=Ji(),[s,c]=(0,z.useState)(`connections`),[l,u]=(0,z.useState)([]),[d,f]=(0,z.useState)([]),[p,m]=(0,z.useState)(!0),[h,g]=(0,z.useState)(null),[_,v]=(0,z.useState)(``),[y,b]=(0,z.useState)(t),[x,S]=(0,z.useState)(``),[C,w]=(0,z.useState)(r??n[0]?.goalId??``),[T,E]=(0,z.useState)(``),[D,O]=(0,z.useState)([]),[ee,te]=(0,z.useState)(``),[ne,k]=(0,z.useState)(!1),[A,j]=(0,z.useState)(null),[M,N]=(0,z.useState)(`addressed_only`),[P,F]=(0,z.useState)(t&&r?`goal`:`manager`),[re,ie]=(0,z.useState)(`async_inbox`),[I,ae]=(0,z.useState)(`topic_reply`),[L,oe]=(0,z.useState)(``),[se,ce]=(0,z.useState)(!1),[le,ue]=(0,z.useState)({}),[de,fe]=(0,z.useState)(!1),[pe,me]=(0,z.useState)(null),[he,ge]=(0,z.useState)(null),[_e,ve]=(0,z.useState)(null),[ye,be]=(0,z.useState)(null),[xe,Se]=(0,z.useState)(!1),[Ce,we]=(0,z.useState)(`loopx-workspace-bot`),[Te,Ee]=(0,z.useState)(`feishu`),[R,De]=(0,z.useState)(null),[Oe,ke]=(0,z.useState)(!1),[Ae,je]=(0,z.useState)(null),Me=(0,z.useRef)(null),Ne=(0,z.useRef)(null),Pe=(0,z.useRef)(!1);async function Fe(){m(!0),g(null);try{let[e,t]=await Promise.all([Rg(),qg()]);u(e),f(t),S(t=>t||e.find(e=>e.reply_ready)?.app_ref||e.find(e=>e.ready)?.app_ref||e[0]?.app_ref||``)}catch(e){g(kb(e,o(`lark.error.configuration`),o))}finally{m(!1)}}(0,z.useEffect)(()=>{Fe()},[]),(0,z.useEffect)(()=>{if(!t||p||Pe.current||!r)return;Pe.current=!0;let e=d.find(e=>e.goal_id===r);e?Je(e):qe(n.find(e=>e.goalId===r))},[d,t,n,r,p]),(0,z.useEffect)(()=>{if(!y||!x||_e){O([]),te(``),k(!1),j(null);return}let e=!1;k(!0),j(null);let t=window.setTimeout(()=>{Gg(x,T).then(t=>{e||(O(t),te(e=>t.some(t=>t.chat_id===e)?e:t[0]?.chat_id??``))}).catch(t=>{e||(O([]),te(``),j(kb(t,o(`lark.error.groupLoad`),o)))}).finally(()=>{e||k(!1)})},180);return()=>{e=!0,window.clearTimeout(t)}},[x,T,y,_e]),(0,z.useEffect)(()=>{if(!xe||!R||[`ready`,`failed`,`cancelled`].includes(R.status))return;let e=!1,t=window.setTimeout(()=>{Vg(R.setup_id).then(async t=>{e||(De(t),t.verification_url&&Ne.current!==t.verification_url&&(Ne.current=t.verification_url,Me.current&&!Me.current.closed&&(Me.current.location.href=t.verification_url)),t.status===`ready`&&(await Fe(),S(t.app_ref),ue({}),Se(!1)),t.status===`failed`&&je(t.error??o(`lark.error.appCreate`)))}).catch(t=>{e||je(kb(t,o(`lark.error.setupPoll`),o))})},650);return()=>{e=!0,window.clearTimeout(t)}},[xe,R]);let V=n.find(e=>e.goalId===C),Ie=V?.agentId?[{agentId:V.agentId,label:V.agentLabel??V.agentId}]:[],Le=V?.agentLanes?.length?V.agentLanes:Ie,Re=Le.some(e=>e.agentId===L),ze=[];se?ze=Le.map(e=>({agentId:e.agentId,appRef:le[e.agentId]??x})):Re&&(ze=[{agentId:L,appRef:x}]);let Be=ze.map(e=>e.agentId),Ve=!!_e||ze.length>0&&ze.every(e=>l.some(t=>t.app_ref===e.appRef&&t.reply_ready)),He=o(`lark.connect`);he?He=o(`lark.saveConnection`):se&&(He=o(`lark.connectAllAgentsAction`,{count:Be.length}));let Ue=l.find(e=>e.app_ref===x),We=D.find(e=>e.chat_id===ee),Ge=(0,z.useMemo)(()=>{let e=_.trim().toLocaleLowerCase();return e?d.filter(t=>[t.app_label,t.chat_name,t.goal_title,t.topic_name].some(t=>t.toLocaleLowerCase().includes(e))):d},[d,_]),Ke=(0,z.useMemo)(()=>d.filter(e=>Db(e,o).state===`unverified`).length,[d,o]);function qe(e){let i=e??n.find(e=>e.goalId===r)??n[0];ge(null),ve(null),F(e||t?`goal`:`manager`),S(l.some(e=>e.app_ref===x)?x:l.find(e=>e.reply_ready)?.app_ref??l[0]?.app_ref??``),te(``),w(i?.goalId??``),oe(i?.agentId??``),ce(!1),ue({}),N(`addressed_only`),ie(`async_inbox`),ae(`topic_reply`),E(``),me(null),b(!0)}function Je(e){ge(e.goal_id),ve(e),F(e.conversation_kind??`goal`),S(e.app_ref),w(e.goal_id);let t=n.find(t=>t.goalId===e.goal_id),r=t?.agentLanes?.length?t.agentLanes:t?.agentId?[{agentId:t.agentId}]:[];oe(e.agent_id??(r.length===1?r[0].agentId:``)),ce(!1),ue({}),N(e.capture_scope),ie(e.ingress_mode===`direct_session`?`async_inbox`:e.ingress_mode),ae(e.reply_mode),E(e.chat_name),me(null),b(!0)}function Ye(){De(null),je(null),Ne.current=null,Se(!0)}async function Xe(){if(!(Oe||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Ce))){ke(!0),je(null),Ne.current=null,Me.current=window.open(window.location.href,`_blank`);try{let e=await Bg({appRef:Ce,brand:Te});De(e)}catch(e){Me.current?.close(),je(kb(e,o(`lark.error.setupStart`),o))}finally{ke(!1)}}}async function Ze(){let e=R;if(Se(!1),Me.current?.close(),e&&![`ready`,`failed`,`cancelled`].includes(e.status))try{await Hg(e.setup_id)}catch{}}async function Qe(){if(!(!x||!C||!_e&&!We||P===`goal`&&Be.length===0||de)){fe(!0),me(null);try{let e={...P===`manager`?{..._e?{connectionId:_e.connection_id}:{appRef:x,chatId:We.chat_id,chatName:We.chat_name}}:_e?{connectionId:_e.connection_id,agentId:L}:{agentBindings:ze,chatId:We.chat_id,chatName:We.chat_name},conversationKind:P,captureScope:P===`manager`?`addressed_only`:M,goalId:C,incomingMode:M===`configured_chat_all`?`all`:`mentions`,ingressMode:P===`manager`?`session_queue`:re,replyMode:I},t=await Jg({...e,execute:!1});if(!t.ok)throw new Th(t.public_summary??t.blocker??o(`lark.error.bindPreview`),{error_code:t.blocker??`provider_api_failed`});let n=await Jg({...e,execute:!0});if(!n.ok)throw new Th(n.public_summary??n.blocker??o(`lark.error.bind`),{error_code:n.blocker??`provider_api_failed`});b(!1),await Fe(),i?.()}catch(e){me(kb(e,o(`lark.error.bind`),o))}finally{fe(!1)}}}async function $e(e,t){if(ye!==t){be(t);return}try{await Yg(e,t),be(null),await Fe(),i?.()}catch(e){g(kb(e,o(`lark.error.disconnect`),o))}}return(0,B.jsxs)(`section`,{className:`personal-lark-settings${e?` is-embedded`:``}`,"aria-label":o(`lark.configuration`),children:[e?null:(0,B.jsxs)(`header`,{className:`personal-lark-header`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:o(`settings.goalConnections`)}),(0,B.jsx)(`h1`,{children:`Lark`})]}),(0,B.jsx)(`button`,{"aria-label":o(`lark.closeSettings`),className:`personal-icon-button`,onClick:a,type:`button`,children:(0,B.jsx)($m,{size:18})})]}),(0,B.jsxs)(`nav`,{className:`personal-lark-tabs`,"aria-label":o(`lark.management`),children:[(0,B.jsxs)(`button`,{"aria-current":s===`apps`?`page`:void 0,onClick:()=>c(`apps`),type:`button`,children:[o(`lark.apps`),` `,(0,B.jsx)(`span`,{children:p?`…`:l.length})]}),(0,B.jsxs)(`button`,{"aria-current":s===`connections`?`page`:void 0,onClick:()=>c(`connections`),type:`button`,children:[o(`lark.connections`),` `,(0,B.jsx)(`span`,{children:p?`…`:d.length})]})]}),h?(0,B.jsx)(`p`,{className:`personal-notification-error`,children:h}):null,p?(0,B.jsxs)(`div`,{className:`personal-lark-loading`,children:[(0,B.jsx)(Cm,{className:`is-spinning`,size:18}),o(`lark.loading`)]}):null,!p&&s===`apps`?(0,B.jsxs)(`div`,{className:`personal-lark-apps`,children:[(0,B.jsxs)(`div`,{className:`personal-lark-app-toolbar`,children:[(0,B.jsx)(`span`,{children:o(`lark.reusableApps`,{count:l.length})}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:Ye,type:`button`,children:[(0,B.jsx)(Pm,{size:16}),o(`lark.newApp`)]})]}),(0,B.jsxs)(`div`,{className:`personal-lark-app-grid`,children:[l.map(e=>(0,B.jsxs)(`article`,{className:`personal-lark-app-card`,children:[(0,B.jsx)(`span`,{className:`personal-lark-app-avatar`,children:(0,B.jsx)(Zp,{size:19})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsxs)(`small`,{children:[e.brand,` · lark-cli profile`]})]}),(0,B.jsx)(`em`,{className:e.reply_ready?`is-ready`:`is-off`,children:e.reply_ready?o(`lark.autoReplyReady`):e.ready?o(`lark.needsMessagePermissions`):o(`lark.needsSetup`)}),(0,B.jsxs)(`p`,{children:[o(`lark.goalConnections`,{count:d.filter(t=>t.app_ref===e.app_ref).length}),e.ready&&!e.reply_ready?` · ${o(`lark.autoReplyUnavailable`)}`:``]})]},e.app_ref)),l.length===0?(0,B.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noProfiles`)}):null]})]}):null,!p&&s===`connections`?(0,B.jsxs)(`div`,{className:`personal-lark-connections`,children:[Ke>0?(0,B.jsxs)(`p`,{className:`personal-lark-route-readiness`,role:`status`,children:[(0,B.jsx)(Dm,{size:15}),o(`lark.routesUnverified`,{count:Ke})]}):null,(0,B.jsxs)(`div`,{className:`personal-lark-toolbar`,children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(zm,{size:16}),(0,B.jsx)(`input`,{"aria-label":o(`lark.searchConnections`),onChange:e=>v(e.target.value),placeholder:o(`lark.searchPlaceholder`),type:`search`,value:_})]}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:l.length===0||n.length===0,onClick:()=>qe(),type:`button`,children:[(0,B.jsx)(Pm,{size:16}),o(`lark.connectApp`)]})]}),(0,B.jsxs)(`div`,{className:`personal-lark-table`,role:`table`,"aria-label":o(`lark.goalTopicConnections`),children:[(0,B.jsxs)(`div`,{className:`personal-lark-table-head`,role:`row`,children:[(0,B.jsx)(`span`,{children:o(`lark.connection`)}),(0,B.jsx)(`span`,{children:o(`common.goal`)}),(0,B.jsx)(`span`,{children:o(`lark.capture`)}),(0,B.jsx)(`span`,{children:o(`lark.processing`)}),(0,B.jsx)(`span`,{children:o(`common.actions`)})]}),Ge.map(e=>{let t=Db(e,o);return(0,B.jsxs)(`div`,{className:`personal-lark-table-row`,role:`row`,children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.chat_name}),(0,B.jsxs)(`small`,{children:[e.app_label,` · `,t.label]}),(0,B.jsx)(`small`,{children:t.detail}),t.state===`unverified`?(0,B.jsxs)(`a`,{href:`https://open.feishu.cn/document/server-docs/im-v1/message/events/receive?lang=zh-CN`,rel:`noreferrer`,target:`_blank`,children:[(0,B.jsx)(fm,{size:12}),o(`lark.openEventSettings`)]}):null,Ob(e)?(0,B.jsxs)(`a`,{href:Ob(e)??void 0,rel:`noreferrer`,target:`_blank`,children:[(0,B.jsx)(fm,{size:12}),o(`lark.historyPermission`)]}):null]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.goal_title}),(0,B.jsxs)(`small`,{children:[`# `,e.topic_name]})]}),(0,B.jsx)(`span`,{children:e.capture_scope===`addressed_only`?o(`lark.mentionsOnly`):o(`lark.allTopicMessages`)}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.conversation_kind===`manager`?o(`lark.managerConversation`):Eb(e.ingress_mode,o).label}),(0,B.jsx)(`small`,{children:e.conversation_kind===`manager`?o(`lark.managerConversationDescription`):e.agent_id??Eb(e.ingress_mode,o).detail})]}),(0,B.jsxs)(`span`,{className:`personal-lark-row-actions`,children:[(0,B.jsx)(`button`,{"aria-label":o(`lark.settingsConfigure`,{goal:e.goal_title}),onClick:()=>Je(e),type:`button`,children:(0,B.jsx)(Um,{size:15})}),(0,B.jsxs)(`button`,{"aria-label":o(`lark.settingsDisconnect`,{goal:e.goal_title}),className:ye===e.connection_id?`is-confirm`:``,onClick:()=>void $e(e.goal_id,e.connection_id),type:`button`,children:[(0,B.jsx)(Qm,{size:15}),ye===e.connection_id?o(`common.confirm`):null]})]})]},e.connection_id)}),Ge.length===0?(0,B.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noConnections`)}):null]})]}):null,y?(0,B.jsx)(`div`,{className:`personal-lark-modal-backdrop`,role:`presentation`,children:(0,B.jsxs)(`section`,{"aria-labelledby":`connect-lark-title`,"aria-modal":`true`,className:`personal-lark-modal`,role:`dialog`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:`Goal Topic connection`}),(0,B.jsx)(`h2`,{id:`connect-lark-title`,children:o(he?`lark.editConnection`:`lark.connectApp`)})]}),(0,B.jsx)(`button`,{"aria-label":o(`lark.closeConnection`),onClick:()=>b(!1),type:`button`,children:(0,B.jsx)($m,{size:18})})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.conversationKind`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.conversationKind`),disabled:!!_e,value:P,onChange:e=>F(e.target.value),children:[(0,B.jsx)(`option`,{value:`manager`,children:o(`lark.managerConversation`)}),(0,B.jsx)(`option`,{value:`goal`,children:o(`lark.workerConversation`)})]})]}),P===`manager`?(0,B.jsx)(`p`,{children:o(`lark.managerConversationDescription`)}):null,_e?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,B.jsx)(`div`,{children:_e.app_label})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,B.jsx)(`div`,{children:_e.chat_name})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,B.jsx)(`div`,{children:_e.goal_title})]}),(0,B.jsx)(`small`,{children:o(`lark.editPreservesIdentity`)})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,B.jsx)(`select`,{"aria-label":o(`lark.appProfile`),disabled:p,onChange:e=>{e.target.value===`__register__`?Ye():(S(e.target.value),ue({}))},value:x,children:p?(0,B.jsx)(`option`,{value:``,children:o(`lark.appLoading`)}):(0,B.jsxs)(B.Fragment,{children:[l.map(e=>(0,B.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref)),(0,B.jsx)(`option`,{value:`__register__`,children:o(`lark.registerAnother`)})]})}),(0,B.jsx)(`small`,{children:o(`lark.defaultAgentAppDescription`)})]}),Ue?.ready&&!Ue.reply_ready?(0,B.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.appPermissions`)}):null,(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,B.jsx)(`input`,{"aria-label":o(`lark.groupSearch`),onChange:e=>E(e.target.value),placeholder:o(`lark.groupSearch`),type:`search`,value:T}),ne?(0,B.jsxs)(`div`,{className:`personal-lark-group-state`,role:`status`,children:[(0,B.jsx)(Cm,{className:`is-spinning`,size:15}),o(`lark.groupLoading`)]}):null,!ne&&A?(0,B.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:A}):null,!ne&&!A&&D.length===0?(0,B.jsx)(`div`,{className:`personal-lark-group-state`,role:`status`,children:o(`lark.groupEmpty`)}):null,!ne&&!A&&D.length>0?(0,B.jsx)(`select`,{"aria-label":o(`lark.groupChat`),onChange:e=>te(e.target.value),value:ee,children:D.map(e=>(0,B.jsx)(`option`,{value:e.chat_id,children:e.chat_name},e.chat_id))}):null]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,B.jsx)(`select`,{"aria-label":o(`lark.bindGoal`),onChange:e=>{let t=e.target.value;w(t),oe(n.find(e=>e.goalId===t)?.agentId??``),ue({})},value:C,children:n.map(e=>(0,B.jsx)(`option`,{value:e.goalId,children:e.title},e.goalId))})]})]}),(0,B.jsxs)(`label`,{className:`personal-lark-check`,children:[(0,B.jsx)(`input`,{checked:!0,readOnly:!0,type:`checkbox`}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:o(`lark.createAutomatically`)}),(0,B.jsx)(`small`,{children:o(`lark.createAutomaticallyDescription`)})]})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.topicPreview`)}),(0,B.jsxs)(`div`,{className:`personal-lark-topic-preview`,children:[(0,B.jsx)(Dm,{size:15}),`# `,V?.title??V?.goalId??`Goal`]})]}),P===`goal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.captureScope`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.captureScope`),disabled:_e?.ingress_mode===`direct_session`,onChange:e=>N(e.target.value),value:M,children:[(0,B.jsx)(`option`,{value:`addressed_only`,children:o(`lark.captureAddressed`)}),(0,B.jsx)(`option`,{value:`configured_chat_all`,children:o(`lark.captureAll`)})]}),(0,B.jsx)(`small`,{children:o(`lark.captureScopeDescription`)})]}),(0,B.jsxs)(`fieldset`,{"aria-label":o(`lark.agentIngress`),className:`personal-lark-ingress`,children:[(0,B.jsx)(`legend`,{children:o(`lark.agentIngress`)}),(0,B.jsx)(`div`,{children:[`live_steering`,`session_queue`,`async_inbox`].map(e=>{let t=Eb(e,o);return(0,B.jsxs)(`label`,{className:re===e?`is-active`:``,children:[(0,B.jsx)(`input`,{"aria-label":t.label,checked:re===e,name:`lark-agent-ingress`,onChange:()=>ie(e),type:`radio`,value:e}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:t.label}),(0,B.jsx)(`small`,{children:t.detail})]})]},e)})})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.targetAgent`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.targetAgent`),disabled:!!_e?.agent_id,onChange:e=>oe(e.target.value),value:L,children:[Re?null:(0,B.jsx)(`option`,{disabled:!0,value:L,children:L?o(`lark.agentUnavailable`,{agent:L}):o(`lark.noAgentConfigured`)}),Le.map(e=>(0,B.jsx)(`option`,{value:e.agentId,children:e.label===e.agentId?e.agentId:`${e.label} · ${e.agentId}`},e.agentId))]}),(0,B.jsx)(`small`,{children:o(`lark.targetAgentDescription`)})]}),!he&&Le.length>1?(0,B.jsxs)(`label`,{"aria-label":o(`lark.connectAllAgents`),className:`personal-lark-check`,children:[(0,B.jsx)(`input`,{checked:se,onChange:e=>ce(e.target.checked),type:`checkbox`}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:o(`lark.connectAllAgents`)}),(0,B.jsx)(`small`,{children:o(`lark.connectAllAgentsDescription`,{count:Le.length})})]})]}):null,!he&&se&&Le.length>1?(0,B.jsxs)(`fieldset`,{"aria-label":o(`lark.agentApps`),className:`personal-lark-agent-apps`,children:[(0,B.jsx)(`legend`,{children:o(`lark.agentApps`)}),(0,B.jsx)(`small`,{children:o(`lark.agentAppsDescription`)}),(0,B.jsx)(`div`,{children:Le.map(e=>(0,B.jsxs)(`label`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsx)(`small`,{children:e.agentId})]}),(0,B.jsx)(`select`,{"aria-label":o(`lark.agentAppSelection`,{agent:e.label}),onChange:t=>ue(n=>({...n,[e.agentId]:t.target.value})),value:le[e.agentId]??x,children:l.map(e=>(0,B.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref))})]},e.agentId))})]}):null,se&&ze.length>0&&!Ve?(0,B.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.agentAppPermissions`)}):null,Be.length===0?(0,B.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:o(`lark.selectRegisteredAgent`)}):null]}):null,(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.replyMode`)}),(0,B.jsx)(`select`,{"aria-label":o(`lark.replyMode`),onChange:e=>ae(e.target.value),value:I,children:(0,B.jsx)(`option`,{value:`topic_reply`,children:o(`lark.topicReply`)})}),(0,B.jsx)(`small`,{children:o(`lark.replyModeDescription`)})]}),(0,B.jsxs)(`p`,{className:`personal-lark-cardinality`,children:[(0,B.jsx)(em,{size:15}),o(`lark.cardinality`)]}),pe?(0,B.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:pe}):null,(0,B.jsxs)(`footer`,{children:[(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>b(!1),type:`button`,children:o(`lark.cancel`)}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:p||!x||!_e&&(!Ue?.reply_ready||!ee)||P===`goal`&&(!Ve||Be.length===0)||!C||de,onClick:()=>void Qe(),type:`button`,children:[de?(0,B.jsx)(Cm,{className:`is-spinning`,size:15}):null,He]})]})]})}):null,xe?(0,B.jsx)(`div`,{className:`personal-lark-modal-backdrop is-setup`,role:`presentation`,children:(0,B.jsxs)(`section`,{"aria-labelledby":`new-lark-app-title`,"aria-modal":`true`,className:`personal-lark-modal personal-lark-setup-modal`,role:`dialog`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:o(`lark.reusableWorkspaceApp`)}),(0,B.jsx)(`h2`,{id:`new-lark-app-title`,children:o(`lark.newApp`)})]}),(0,B.jsx)(`button`,{"aria-label":o(`lark.closeCreate`),onClick:()=>void Ze(),type:`button`,children:(0,B.jsx)($m,{size:18})})]}),R?(0,B.jsxs)(`div`,{className:`personal-lark-setup-progress`,children:[(0,B.jsx)(`span`,{className:`personal-lark-setup-icon is-${R.status}`,children:R.status===`ready`?(0,B.jsx)(em,{size:22}):(0,B.jsx)(Cm,{className:R.status===`failed`?``:`is-spinning`,size:22})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:R.status===`ready`?o(`lark.appCreated`):R.status===`failed`?o(`lark.appCreateFailed`):o(`lark.waitingFeishu`)}),(0,B.jsx)(`p`,{children:R.status===`waiting_for_feishu`?o(`lark.waitingFeishuDescription`):R.status===`starting`?o(`lark.waitingLink`):R.error})]}),R.verification_url?(0,B.jsxs)(`a`,{href:R.verification_url,rel:`noreferrer`,target:`_blank`,children:[(0,B.jsx)(fm,{size:15}),o(`lark.reopenFeishu`)]}):null]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`personal-lark-setup-copy`,children:o(`lark.setupCopy`)}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.profileName`)}),(0,B.jsx)(`input`,{"aria-label":o(`lark.profileName`),autoComplete:`off`,onChange:e=>we(e.target.value),placeholder:`loopx-workspace-bot`,value:Ce})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.region`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.region`),onChange:e=>Ee(e.target.value),value:Te,children:[(0,B.jsx)(`option`,{value:`feishu`,children:`Feishu`}),(0,B.jsx)(`option`,{value:`lark`,children:`Lark`})]})]}),Ce&&!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Ce)?(0,B.jsx)(`p`,{className:`personal-notification-error`,children:o(`lark.profileValidation`)}):null]}),Ae?(0,B.jsx)(`p`,{className:`personal-notification-error`,children:Ae}):null,(0,B.jsxs)(`footer`,{children:[(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void Ze(),type:`button`,children:o(`lark.cancel`)}),R?null:(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:Oe||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Ce),onClick:()=>void Xe(),type:`button`,children:[Oe?(0,B.jsx)(Cm,{className:`is-spinning`,size:15}):(0,B.jsx)(fm,{size:15}),o(`lark.continueFeishu`)]})]})]})}):null]})}function jb(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function Mb(e,t,n){let r=jb(t),i=jb(n);return Object.fromEntries(e.fields.flatMap(({key:e,nullable:t})=>{let n=r[e],a=i[e];return Object.hasOwn(r,e)&&(n!=null||t&&n===null)?[[e,n]]:Object.hasOwn(i,e)&&a!=null?[[e,a]]:[]}))}function Nb(e,t){let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=new Set(e.fields.map(e=>e.key));return Object.keys(n).some(e=>!r.has(e))?null:n}function Pb(e,t,n){let r={...e,[t]:n},i=e.schedule;return t===`timezone`&&i&&typeof i==`object`&&`schema_version`in i&&i.schema_version===`periodic_report_schedule_v0`&&(r.schedule={...i,timezone:n}),r}function Fb({id:e,value:t,timezone:n,onChange:r}){let{locale:i}=Ji(),a=i===`zh-CN`,o=t&&typeof t==`object`&&!Array.isArray(t)?t:null,s=String(o?.rrule??``).split(`;`).map(e=>e.split(`=`)),c=Object.fromEntries(s.filter(e=>e.length===2)),l=[`MO`,`TU`,`WE`,`TH`,`FR`,`SA`,`SU`],u=(e,t)=>e!==void 0&&/^\d+$/.test(e)&&Number(e)<=t,d=!o||o.schema_version===`periodic_report_schedule_v0`&&[`DAILY`,`WEEKLY`].includes(c.FREQ)&&o.timezone===n&&s.every(e=>e.length===2&&[`FREQ`,`BYDAY`,`BYHOUR`,`BYMINUTE`,`INTERVAL`].includes(e[0]))&&new Set(s.map(([e])=>e)).size===s.length&&u(c.BYHOUR,23)&&u(c.BYMINUTE??`0`,59)&&(c.FREQ===`WEEKLY`?l.includes(c.BYDAY):!c.BYDAY)&&(!c.INTERVAL||c.INTERVAL===`1`),f=a?[`星期一`,`星期二`,`星期三`,`星期四`,`星期五`,`星期六`,`星期日`]:[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`];function p(e){let t={FREQ:`WEEKLY`,BYDAY:`MO`,BYHOUR:`9`,BYMINUTE:`0`,...c,...e};r?.({schema_version:`periodic_report_schedule_v0`,schedule_id:o?.schedule_id??`report-schedule`,timezone:n,rrule:[`FREQ=${t.FREQ}`,...t.FREQ===`WEEKLY`?[`BYDAY=${t.BYDAY}`]:[],`BYHOUR=${t.BYHOUR}`,`BYMINUTE=${t.BYMINUTE}`].join(`;`)})}return(0,B.jsxs)(`div`,{className:`personal-report-schedule`,children:[(0,B.jsxs)(`label`,{className:`is-boolean`,htmlFor:e,children:[(0,B.jsx)(`span`,{children:a?`按日历汇报`:`Calendar reports`}),(0,B.jsx)(`input`,{id:e,type:`checkbox`,role:`switch`,checked:!!o,disabled:!r,onChange:e=>e.target.checked?p({}):r?.(null)})]}),o?(0,B.jsxs)(B.Fragment,{children:[d?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{htmlFor:`${e}-frequency`,children:[(0,B.jsx)(`span`,{children:a?`频率`:`Frequency`}),(0,B.jsxs)(`select`,{id:`${e}-frequency`,value:c.FREQ,disabled:!r,onChange:e=>p({FREQ:e.target.value}),children:[(0,B.jsx)(`option`,{value:`DAILY`,children:a?`每天`:`Daily`}),(0,B.jsx)(`option`,{value:`WEEKLY`,children:a?`每周`:`Weekly`})]})]}),c.FREQ===`WEEKLY`&&(0,B.jsxs)(`label`,{htmlFor:`${e}-day`,children:[(0,B.jsx)(`span`,{children:a?`星期`:`Weekday`}),(0,B.jsx)(`select`,{id:`${e}-day`,value:c.BYDAY,disabled:!r,onChange:e=>p({BYDAY:e.target.value}),children:l.map((e,t)=>(0,B.jsx)(`option`,{value:e,children:f[t]},e))})]}),(0,B.jsxs)(`label`,{htmlFor:`${e}-time`,children:[(0,B.jsxs)(`span`,{children:[a?`当地时间`:`Local time`,` (`,n,`)`]}),(0,B.jsx)(`input`,{id:`${e}-time`,type:`time`,required:!0,disabled:!r,value:`${(c.BYHOUR??`9`).padStart(2,`0`)}:${(c.BYMINUTE??`0`).padStart(2,`0`)}`,onChange:e=>{if(!/^\d{2}:\d{2}$/.test(e.target.value))return;let[t,n]=e.target.value.split(`:`);p({BYHOUR:t,BYMINUTE:n})}})]})]}):(0,B.jsx)(`p`,{role:`alert`,children:a?`此计划需在 JSON 模式中编辑;当前内容已保留。`:`Edit this schedule in JSON mode; its current value is preserved.`}),(0,B.jsx)(`p`,{children:a?`由现有唤醒检查到期计划;实际送达以回执为准。`:`Existing wakes check the schedule; delivery is confirmed by its receipt.`})]}):(0,B.jsx)(`p`,{children:a?`未设置日历计划;保持阶段结束时汇报。`:`No calendar schedule; report at validated stage boundaries.`})]})}function Ib({copy:e,field:t,id:n,onChange:r,value:i,timezone:a}){let o=e[t.key]?.label??t.label,s=!r;if(t.input_kind===`periodic_report_schedule`)return(0,B.jsx)(Fb,{id:n,value:i,timezone:a,onChange:r?e=>r(t.key,e):void 0});if(t.input_kind===`boolean`)return(0,B.jsxs)(`label`,{className:`is-boolean`,htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsx)(`input`,{checked:i===!0,id:n,onChange:r?e=>r(t.key,e.target.checked):void 0,readOnly:s,role:`switch`,type:`checkbox`})]});if(t.input_kind===`select`)return(0,B.jsxs)(`label`,{htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsxs)(`select`,{id:n,onChange:r?e=>r(t.key,e.target.value):void 0,value:typeof i==`string`?i:``,children:[(0,B.jsx)(`option`,{value:``}),(t.options??[]).map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))]})]});if(t.input_kind===`string_list`)return(0,B.jsxs)(`label`,{htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsx)(`textarea`,{id:n,onChange:r?e=>r(t.key,e.target.value.split(/\r?\n/u).filter(Boolean)):void 0,readOnly:s,rows:4,value:Array.isArray(i)?i.join(` +`):``})]});let c=t.input_kind===`number`;return(0,B.jsxs)(`label`,{htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsx)(`input`,{id:n,max:t.maximum,min:t.minimum,onChange:r?e=>r(t.key,c?Number(e.target.value):e.target.value):void 0,readOnly:s,required:t.required,type:c?`number`:`text`,value:typeof i==`number`||typeof i==`string`?i:``})]})}function Lb({copy:e={},disabled:t=!1,editor:n,enabledAction:r,omitKeys:i=[],onChange:a,value:o}){let s=(0,z.useId)(),c=new Set(i);return(0,B.jsx)(`fieldset`,{className:`personal-capability-fields`,disabled:t,children:n.fields.filter(e=>!c.has(e.key)).map(t=>{let n=(0,B.jsx)(Ib,{copy:e,field:t,id:`${s}-${t.key.replace(/[^a-z0-9_-]/gi,`-`)}`,onChange:a,value:o[t.key],timezone:String(o.timezone??`UTC`)},t.key);return t.key===`enabled`&&t.input_kind===`boolean`?(0,B.jsxs)(`div`,{className:`personal-capability-enabled-row`,children:[n,r]},t.key):n})})}var Rb={en:{todo_replan_cadence:{displayName:`Goal review cadence`,description:`Configures the Goal review cadence.`},change_quality_qualification:{displayName:`Change quality qualification`,description:`Prepares a provider-neutral review packet, allows at most one policy-authorized safe-fix pass, and can require an exact-diff receipt.`},explore_graph:{displayName:`Explore Graph`,description:`Organizes bounded exploration as a typed evidence graph so branches, findings, and synthesis remain inspectable.`},explore_harness:{displayName:`Explore Harness`,description:`Selects a capability-owned planning and research harness profile for bounded multi-step exploration.`},lark_event_inbox:{displayName:`Lark event inbox`,description:`Receives provider events through a local-private inbox binding before LoopX projects them into governed work.`,readOnlyReason:`This capability requires a local-private inbox binding. Manage it in Lark settings or through the capability CLI.`},lark_kanban_heartbeat_sync:{displayName:`Lark Kanban heartbeat sync`,description:`Synchronizes accepted LoopX work state to the configured Lark Kanban heartbeat surface.`},local_authority_shadow:{displayName:`Local authority shadow`,description:`Observes post-commit Todo and task-lease state through the shared authority contract without taking write authority.`},multi_subagent:{displayName:`Adaptive child capacity`,description:`Sets bounded child-agent capacity and the public-safe responsibility domains in which parallel work may be delegated.`},peer_task_coordination:{displayName:`Registered-peer task coordination`,description:`Routes explicitly scoped peer-owned work to one registered coordinator without granting cross-owner mutation authority.`},periodic_report:{displayName:`Periodic reports`,description:`Turns validated Goal stage progress into a frozen report and automatically delivers it through the configured Goal Channel with exact readback.`},pull_request_review:{displayName:`Pull-request review`,description:`Ranks the public GitHub PR review queue with a machine-level default; it never grants GitHub, Todo, push, or merge authority.`},reward_memory:{displayName:`Reward Memory experiment`,description:`Configures a reviewed local-private provider binding for Goal-scoped Agent recall and evidence-backed outcome learning.`}},"zh-CN":{todo_replan_cadence:{displayName:`Goal 复核周期`,description:`配置 Goal 的复核周期。`},change_quality_qualification:{displayName:`变更质量验证`,description:`生成与 Provider 无关的审阅包,最多允许一次策略授权的安全修复,并可要求精确 diff 回执。`},explore_graph:{displayName:`探索图谱`,description:`把有界探索组织为 typed 证据图,让探索分支、发现与综合结论都可检查、可追溯。`},explore_harness:{displayName:`探索 Harness`,description:`为有界的多步探索选择由能力负责的规划与研究 Harness profile。`},lark_event_inbox:{displayName:`飞书事件收件箱`,description:`通过本机私有收件箱接收 Provider 事件,再由 LoopX 将其投影为受治理的工作。`,readOnlyReason:`此能力依赖本机私有的收件箱绑定,请在飞书设置或 capability CLI 中管理。`},lark_kanban_heartbeat_sync:{displayName:`飞书看板心跳同步`,description:`把 LoopX 已接受的工作状态同步到配置好的飞书看板心跳界面。`},local_authority_shadow:{displayName:`本地 Authority 影子观测`,description:`通过共享 Authority contract 观测提交后的 Todo 与 task lease 状态,但不取得写入权。`},multi_subagent:{displayName:`自适应子 Agent 容量`,description:`限定子 Agent 容量与可公开的职责域,只有落在这些边界内的工作才能并行委派。`},peer_task_coordination:{displayName:`已注册 Peer 任务协调`,description:`把明确限定的 Peer 工作路由给一个已注册协调者,不授予跨 Owner 修改权限。`},periodic_report:{displayName:`周期报告`,description:`把经过验证的 Goal 阶段进展整理为冻结报告,并通过配置的 Goal Channel 自动发送和精确回读。`},pull_request_review:{displayName:`Pull-request Review`,description:`配置公开 GitHub PR 审阅队列的本机默认排序;不会授予 GitHub、Todo、push 或 merge 权限。`},reward_memory:{displayName:`Reward Memory 实验`,description:`为 Goal 内 Agent 的召回与证据化结果学习配置经过审阅的本机私有 Provider 绑定。`}}},zb={en:{completed_todos:{label:`Completed Todos between Goal reviews`,description:`Machine default or explicit Goal override, from 1 to 5.`},allowed_domains:{label:`Allowed responsibility domains`,description:`Enter one bounded, public-safe domain per line.`},coordinator_agent_id:{label:`Coordinator Agent`,description:`Use an already registered Agent id; leave blank to disable coordination.`},enabled:{label:`Enabled`},model:{label:`Child model`,description:`For example gpt-5.6-luna. Blank clears the child model preference.`},reasoning_effort:{label:`Child reasoning effort`,description:`For example max; the host must support this model and effort.`},max_children:{label:`Maximum children`,description:`Hard upper bound for concurrently delegated child work.`},profile:{label:`Planner profile`,description:`Select one registered Explore Harness profile.`},profile_preset:{label:`Report profile`,description:`Capability-owned report profile, such as weekly-progress.`},review_priority:{label:`Review priority`,description:`Choose whether other developers' PRs or the authenticated reviewer's own PRs are ranked first.`},route_ref:{label:`Goal Channel route`,description:`Public route alias only; credentials and provider identifiers stay outside this form.`},safe_fix:{label:`Allow one bounded safe-fix pass`},strict_receipt:{label:`Require an exact-diff receipt`},timezone:{label:`Timezone`,description:`Use an IANA timezone, for example Asia/Shanghai.`},schedule:{label:`Calendar reports`,description:`Optional daily or weekly reports; no schedule preserves stage-only delivery.`},config_path:{label:`Local-private configuration path`,description:`Repo-relative ignored JSON under .loopx/config/. Leave blank to retain the current binding; the path is never returned.`},enabled_agents:{label:`Enabled Goal Agents`,description:`Enter one registered Goal-local Agent id per line. A private binding currently accepts exactly one Agent.`}},"zh-CN":{completed_todos:{label:`两次 Goal 复核间的已完成 Todo 数`,description:`可设置 1–5;机器默认值可被 Goal 显式覆盖。`},allowed_domains:{label:`允许的职责域`,description:`每行填写一个有边界、可公开的职责域。`},coordinator_agent_id:{label:`协调 Agent`,description:`填写一个已经注册的 Agent ID;留空表示关闭协调。`},enabled:{label:`启用`},model:{label:`子 Agent 模型`,description:`例如 gpt-5.6-luna;留空清除模型偏好。`},reasoning_effort:{label:`子 Agent 推理档位`,description:`例如 max;宿主须支持所选模型与档位。`},max_children:{label:`最大子 Agent 数`,description:`可同时委派的子任务硬上限。`},profile:{label:`规划 Profile`,description:`选择一个已注册的 Explore Harness profile。`},profile_preset:{label:`报告 Profile`,description:`由该能力管理的报告 profile,例如 weekly-progress。`},review_priority:{label:`审阅优先级`,description:`选择先排其他开发者的 PR,还是先排当前已认证审阅者自己的 PR。`},route_ref:{label:`Goal Channel 路由`,description:`只填写公开 route alias;凭据与 Provider 标识不会进入此表单。`},safe_fix:{label:`允许一次有界安全修复`},strict_receipt:{label:`要求精确 diff 回执`},timezone:{label:`时区`,description:`使用 IANA 时区,例如 Asia/Shanghai。`},schedule:{label:`日历汇报`,description:`可选每日或每周计划;未设置时保持阶段结束汇报。`},config_path:{label:`本机私有配置路径`,description:`填写 .loopx/config/ 下、相对仓库且被忽略的 JSON;留空保留当前绑定,路径不会被回传。`},enabled_agents:{label:`已启用的 Goal Agent`,description:`每行填写一个已注册的 Goal 内 Agent ID;私有绑定当前只接受一个 Agent。`}}};function Bb(e,t){let n=Rb[t][e.capability_id];return n?{...e,display_name:n.displayName,description:n.description,configuration_editor:{...e.configuration_editor,...n.readOnlyReason?{read_only_reason:n.readOnlyReason}:{}}}:e}function Vb(e){return zb[e]}Object.freeze(Object.keys(Rb.en).sort());function Hb(e,t){return e.available_scopes.includes(t)&&(t!==`machine`||!!e.machine_namespace)&&e.configuration_editor.editable&&e.configuration_editor.writable_scopes.includes(t)}function Ub({values:e,t}){return(0,B.jsxs)(`details`,{className:`personal-capability-raw-values`,children:[(0,B.jsx)(`summary`,{children:t(`capabilities.rawJson`)}),(0,B.jsx)(`div`,{className:`personal-capability-value-grid`,children:e.map(({label:e,value:t})=>(0,B.jsxs)(`section`,{children:[(0,B.jsx)(`strong`,{children:e}),(0,B.jsx)(`pre`,{children:t?JSON.stringify(t,null,2):`—`})]},e))})]})}function Wb({source:e,t}){return e?(0,B.jsxs)(`p`,{className:`personal-capability-effective-source`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:15}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:t(`capabilities.effectiveSource`)}),t(`capabilities.source.${e}`)]})]}):null}function Gb({available:e,description:t,t:n}){return e?null:(0,B.jsxs)(`section`,{className:`personal-capability-editor-status is-read-only`,children:[(0,B.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:n(`capabilities.readOnly`)}),(0,B.jsx)(`p`,{children:t})]})]})}function Kb(e){return e.availability?.includes(`experimental`)?4:e.capability_id===`multi_subagent`?3:e.configuration_editor.writable_scopes.length===0||e.availability===`supported_explicit_opt_in`?2:e.availability===`supported_explicit_override`?0:1}function qb(e,t){return[...e].sort((e,n)=>{let r=Kb(e)-Kb(n);if(r!==0)return r;let i=Bb(e,t),a=Bb(n,t);return i.display_name.localeCompare(a.display_name,t)||e.capability_id.localeCompare(n.capability_id)})}function Jb({capabilities:e,locale:t,onSelect:n,scope:r,selectedCapabilityId:i,t:a}){return(0,B.jsx)(`nav`,{"aria-label":a(r===`goal`?`capabilities.catalog`:`machine.capabilityCatalog`),className:`personal-capability-list`,tabIndex:0,children:qb(e,t).map(e=>{let o=Bb(e,t);return(0,B.jsxs)(`button`,{"aria-current":i===o.capability_id?`page`:void 0,onClick:()=>n(o.capability_id),type:`button`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:o.display_name})}),(0,B.jsx)(`em`,{children:a(o.available_scopes.includes(r)?r===`goal`?`capabilities.goalScope`:`capabilities.machineScope`:r===`machine`?`capabilities.goalScope`:`capabilities.machineScope`)})]},o.capability_id)})})}function Yb({capability:e,locale:t,source:n}){let{t:r}=Ji(),i=Bb(e,t);return(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`span`,{className:`personal-settings-icon`,children:(0,B.jsx)(Gm,{"aria-hidden":!0,size:18})}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`div`,{className:`personal-capability-heading-row`,children:[(0,B.jsx)(`h2`,{children:i.display_name}),(0,B.jsx)(Wb,{source:n,t:r})]}),e.context_contribution&&(0,B.jsxs)(`details`,{className:`personal-capability-help`,"data-testid":`capability-context-phases`,children:[(0,B.jsx)(`summary`,{children:t===`zh-CN`?`主 Agent 协作指导`:`Coordinator workflow guidance`}),(0,B.jsx)(`p`,{children:t===`zh-CN`?`随能力开启。支持以下阶段;此处展示能力范围,不能证明某次运行已读取或采纳。`:`Enabled with this capability. These are supported phases, not proof that a run read or adopted the guidance.`}),(0,B.jsx)(`dl`,{children:e.context_contribution.supported_phases.map(e=>(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:(0,B.jsx)(`code`,{children:e})}),(0,B.jsx)(`dd`,{children:Xb[e][t===`zh-CN`?`zh`:`en`]})]},e))}),(0,B.jsx)(`p`,{children:t===`zh-CN`?`LoopX Turn 在请求与结果中提供上下文;原生工具入口由 LoopX skill 调用同一只读接口。执行与采纳需另看运行证据。`:`LoopX Turn includes context in requests and results. For native tools, the LoopX skill reads the same interface. Execution and adoption require run evidence.`})]}),(0,B.jsxs)(`details`,{className:`personal-capability-help`,children:[(0,B.jsx)(`summary`,{children:t===`zh-CN`?`配置说明`:`Configuration help`}),(0,B.jsx)(`p`,{children:i.description}),(0,B.jsx)(`dl`,{children:e.configuration_editor.fields.map(e=>{let n=Vb(t)[e.key],r=n?.description??e.description;return r?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:n?.label??e.label}),(0,B.jsx)(`dd`,{children:r})]},e.key):null})})]},e.capability_id)]})]})}var Xb={before_plan:{zh:`规划前:识别独立问题并保留主 Agent 的核验与整合职责。`,en:`Before planning: identify independent questions and retain coordinator validation and integration.`},before_delegate:{zh:`委派前:明确子任务边界、模型偏好及预期证据。`,en:`Before delegation: specify task boundaries, model preferences and expected evidence.`},after_delegate_result:{zh:`回收后:核验结果,说明采纳决定并关联计划与成果。`,en:`After results: validate evidence, explain acceptance and link plans and deliverables.`}};function Zb({goalId:e,onApplied:t,selected:n,t:r}){let[i,a]=(0,z.useState)({busy:null,draft:{},partialWrite:null,preview:null}),[o,s]=(0,z.useState)(null),[c,l]=(0,z.useState)(`guided`),[u,d]=(0,z.useState)(``),f=(0,z.useMemo)(()=>n?Nb(n.configuration_editor,u):null,[n,u]),p=c===`guided`||f!==null;(0,z.useEffect)(()=>{l(`guided`),d(``),a({busy:null,draft:Mb(n?.configuration_editor??{fields:[]},n?.current??n?.effective_configuration?.configuration??n?.default,n?.default),partialWrite:null,preview:null}),s(null)},[n]);async function m(t){if(!(!n||i.busy||!p)){a(e=>({...e,busy:`preview`,partialWrite:null})),s(null);try{let r=await Dg(e,n.capability_id,t);a(e=>({...e,preview:r}))}catch(e){s(e instanceof Error?e.message:r(`capabilities.previewFailed`))}finally{a(e=>({...e,busy:null}))}}}async function h(){if(!(!n||!i.preview||i.busy||!p)){a(e=>({...e,busy:`apply`})),s(null);try{let r=Mb(n.configuration_editor,i.draft,n.default),o=await Og(e,n.capability_id,i.preview.action===`delete`?null:r,i.preview.plan_revision);a(e=>({...e,partialWrite:o.status===`partial_write`?o:null,preview:null})),o.status!==`partial_write`&&t()}catch(e){a(e=>({...e,preview:null})),s(e instanceof Error?e.message:r(`capabilities.applyFailed`))}finally{a(e=>({...e,busy:null}))}}}function g(e,t){a(r=>({...r,draft:n?.capability_id===`periodic_report`?Pb(r.draft,e,t):{...r.draft,[e]:t},preview:null})),s(null)}function _(e){if(!n||i.busy)return;d(e);let t=Nb(n.configuration_editor,e);a(e=>({...e,preview:null,draft:t?Mb(n.configuration_editor,t,n.default):e.draft})),s(null)}function v(){i.busy||!p||(c===`guided`&&d(JSON.stringify(i.draft,null,2)),l(c===`guided`?`json`:`guided`),a(e=>({...e,preview:null})))}return{apply:h,changeDraft:g,changeJson:_,changeMode:v,editorMode:c,jsonDraft:u,jsonValid:p,error:o,mutation:i,preview:m}}function Qb({mutationError:e,onApplied:t,partialWrite:n,preview:r}){let{t:i}=Ji();return(0,B.jsxs)(B.Fragment,{children:[e?(0,B.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:e}):null,n?(0,B.jsxs)(`section`,{"aria-live":`polite`,className:`personal-capability-recovery`,children:[(0,B.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:i(`capabilities.partialWrite`)}),(0,B.jsx)(`p`,{children:i(`capabilities.partialWriteDescription`)}),(0,B.jsx)(`small`,{children:n.recommended_action})]}),(0,B.jsxs)(`button`,{onClick:t,type:`button`,children:[(0,B.jsx)(Im,{"aria-hidden":!0,size:15}),i(`capabilities.refreshSource`)]})]}):null,r?(0,B.jsxs)(`section`,{className:`personal-capability-preview`,"aria-label":i(`capabilities.preview`),children:[(0,B.jsx)(`strong`,{children:i(`capabilities.preview`)}),(0,B.jsx)(`span`,{children:i(`machine.action.${r.action}`)}),(0,B.jsx)(`small`,{children:i(`capabilities.previewLocked`)})]}):null]})}function $b({catalog:e,goalId:t,onApplied:n}){let{locale:r,t:i}=Ji(),a=(0,z.useMemo)(()=>qb(e.capabilities,r),[e.capabilities,r]),[o,s]=(0,z.useState)(()=>a[0]?.capability_id??``),c=(0,z.useMemo)(()=>a.find(e=>e.capability_id===o)??a[0],[a,o]),l=(0,z.useMemo)(()=>c?Bb(c,r):void 0,[r,c]),{apply:u,changeDraft:d,changeJson:f,changeMode:p,editorMode:m,jsonDraft:h,jsonValid:g,error:_,mutation:v,preview:y}=Zb({goalId:t,onApplied:n,selected:l,t:i}),{busy:b,draft:x,partialWrite:S,preview:C}=v;if(!c||!l)return(0,B.jsx)(`p`,{className:`personal-capability-empty`,children:i(`capabilities.empty`)});let w=l.available_scopes.includes(`goal`),T=Hb(l,`goal`),E=l.configuration_editor.read_only_reason??i(w?`capabilities.previewOnly`:`capabilities.machineOnly`);async function D(){if(!l||!T||b||!g)return;let e=Mb(l.configuration_editor,x,l.default);await y(e)}async function O(){!T||b||await y(null)}return(0,B.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,B.jsx)(Jb,{capabilities:e.capabilities,locale:r,onSelect:s,scope:`goal`,selectedCapabilityId:l.capability_id,t:i}),(0,B.jsxs)(`article`,{"aria-label":l.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,B.jsx)(Yb,{capability:c,locale:r,source:l.effective_configuration?.source}),(0,B.jsx)(Gb,{available:T,t:i,description:E}),T?(0,B.jsxs)(B.Fragment,{children:[m===`json`||!l.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,B.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,B.jsxs)(`button`,{disabled:!!b||!g,onClick:p,type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),i(m===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,m===`guided`?(0,B.jsx)(`section`,{className:`personal-capability-field-summary`,children:(0,B.jsx)(Lb,{disabled:!!b,copy:Vb(r),editor:l.configuration_editor,onChange:d,value:x,enabledAction:(0,B.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:p,type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),i(`machine.editJson`)]})})}):(0,B.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`goal-configuration-json`,children:[(0,B.jsx)(`span`,{children:i(`capabilities.jsonConfiguration`)}),(0,B.jsx)(`textarea`,{id:`goal-configuration-json`,"aria-describedby":`goal-configuration-json-help`,disabled:!!b,onChange:e=>f(e.target.value),rows:12,spellCheck:!1,value:h}),(0,B.jsx)(`small`,{id:`goal-configuration-json-help`,children:i(`capabilities.jsonHelp`)}),g?null:(0,B.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:i(`capabilities.jsonInvalid`)})]})]}):null,(0,B.jsx)(Qb,{mutationError:_,onApplied:n,partialWrite:S,preview:C}),T?(0,B.jsxs)(`footer`,{className:`personal-capability-actions`,children:[l.current&&l.available_scopes.includes(`machine`)?(0,B.jsx)(`button`,{disabled:!!b||!g,onClick:()=>void O(),type:`button`,children:i(`capabilities.restoreInheritance`)}):null,(0,B.jsx)(`button`,{disabled:!!b||!g,onClick:()=>void D(),type:`button`,children:i(b===`preview`?`common.loading`:`capabilities.previewChanges`)}),(0,B.jsx)(`button`,{className:`is-primary`,disabled:!!b||!C||!g,onClick:()=>void u(),type:`button`,children:i(b===`apply`?`common.loading`:`capabilities.applyPreview`)})]}):null,(0,B.jsx)(Ub,{values:[{label:i(`capabilities.goalValue`),value:l.current},{label:i(l.machine_current?`capabilities.machineValue`:`capabilities.defaultValue`),value:l.machine_current??l.default}],t:i},c.capability_id)]})]})}function ex({goalId:e}){let{t}=Ji(),[n,r]=(0,z.useState)(null),[i,a]=(0,z.useState)(null),[o,s]=(0,z.useState)(!1);function c(){e&&(s(!0),a(null),Eg(e).then(r).catch(e=>a(e instanceof Error?e.message:t(`capabilities.loadFailed`))).finally(()=>s(!1)))}return(0,z.useEffect)(c,[e]),e?o&&!n?(0,B.jsxs)(`p`,{"aria-live":`polite`,className:`personal-capability-empty`,children:[(0,B.jsx)(Cm,{className:`personal-spin`,size:18}),t(`capabilities.loading`)]}):i?(0,B.jsxs)(`section`,{className:`personal-capability-error`,role:`alert`,children:[(0,B.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:t(`capabilities.loadFailed`)}),(0,B.jsx)(`small`,{children:i})]}),(0,B.jsxs)(`button`,{onClick:c,type:`button`,children:[(0,B.jsx)(Im,{"aria-hidden":!0,size:15}),t(`capabilities.retry`)]})]}):n?(0,B.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":n.revision,children:[(0,B.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:17}),t(`capabilities.atomicOverride`)]}),(0,B.jsx)(`p`,{children:t(`capabilities.atomicOverrideDescription`)})]}),(0,B.jsx)($b,{catalog:n.capability_catalog,goalId:e,onApplied:c})]}):null:(0,B.jsx)(`p`,{className:`personal-capability-empty`,children:t(`capabilities.chooseGoal`)})}function tx(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function nx(e,t){let n=t?.machine_namespace;return n?e?.machine_configuration?.namespaces[n]:void 0}function rx(e,t,n){return{...tx(e.default),...tx(t),...n}}function ix(e,t){for(let n of e.configuration_editor.fields){let e=t[n.key];if(n.required&&(e==null||e===``))return!1}return e.capability_id===`periodic_report`&&t.enabled===!0?!!(String(t.profile_preset??``).trim()&&String(t.route_ref??``).trim()&&String(t.timezone??``).trim()):!0}function ax(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:null}catch{return null}}function ox(e){return e?e===`absent`?e:e.replace(/^sha256:/,``).slice(0,12):`—`}function sx(){let{locale:e,t}=Ji(),[n,r]=(0,z.useState)(null),[i,a]=(0,z.useState)(``),[o,s]=(0,z.useState)({}),[c,l]=(0,z.useState)(`{}`),[u,d]=(0,z.useState)(`guided`),[f,p]=(0,z.useState)(null),[m,h]=(0,z.useState)(`upsert`),[g,_]=(0,z.useState)(null),[v,y]=(0,z.useState)(null),[b,x]=(0,z.useState)(`load`),[S,C]=(0,z.useState)(null),[w,T]=(0,z.useState)(null),E=(0,z.useMemo)(()=>qb(n?.capability_catalog.capabilities??[],e),[n,e]),D=E.find(e=>e.capability_id===i)??E.find(e=>Hb(e,`machine`))??E[0],O=D?Bb(D,e):void 0,ee=nx(n,O),te=!!(O?.machine_namespace&&ee),ne=!!(O&&Hb(O,`machine`)),k=(0,z.useMemo)(()=>ax(c),[c]),A=O?u===`json`?k:rx(O,ee,o):null,j=!!(O&&(u===`json`?k:ix(O,A??{})));async function M(){r(await Tg())}(0,z.useEffect)(()=>{let e=!0;return Tg().then(t=>{e&&r(t)}).catch(n=>{e&&C(n instanceof Error?n.message:t(`machine.loadError`))}).finally(()=>{e&&x(null)}),()=>{e=!1}},[t]),(0,z.useEffect)(()=>{if(!O)return;let e=nx(n,O),t=Mb(O.configuration_editor,e??O.default,O.default),r=rx(O,e,t);s(t),l(JSON.stringify(r,null,2)),d(ne?`guided`:`json`),p(null),h(`upsert`),y(null)},[n,i,e]);function N(e,t){s(n=>O?.capability_id===`periodic_report`?Pb(n,e,t):{...n,[e]:t}),p(null),h(`upsert`),C(null),T(null)}function P(e){if(O){if(e===`json`)l(JSON.stringify(rx(O,ee,o),null,2));else if(k)s(Mb(O.configuration_editor,k,O.default));else{C(t(`machine.jsonInvalid`));return}d(e),p(null),h(`upsert`),C(null)}}async function F(){if(!(!ne||!O?.machine_namespace||!A||!j||b)){x(`preview`),C(null),T(null);try{h(`upsert`),p(await kg(O.machine_namespace,A))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function re(){if(!(!ne||!O?.machine_namespace||!te||b)){x(`preview`),C(null),T(null);try{h(`remove`),p(await jg(O.machine_namespace))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function ie(){if(!ne||!O?.machine_namespace||!f||b||m===`upsert`&&!A)return;x(`apply`),C(null);let e=m;try{let n=e===`remove`?await Mg(O.machine_namespace,f.plan_revision):await Ag(O.machine_namespace,A,f.plan_revision);_(n),p(null),h(`upsert`),y(null),await M(),T(n.status===`applied`?t(e===`remove`?`machine.removed`:`machine.applied`):t(`machine.unchanged`))}catch(e){p(null),h(`upsert`),C(e instanceof Error?e.message:t(`machine.applyError`))}finally{x(null)}}async function I(){if(!(!g?.transaction_id||b)){x(`rollback-preview`),C(null);try{y(await Ng(g.transaction_id))}catch(e){C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}async function ae(){if(!(!g?.transaction_id||!v||b)){x(`rollback`),C(null);try{await Pg(g.transaction_id,v.plan_revision),_(null),y(null),p(null),await M(),T(t(`machine.rolledBack`))}catch(e){y(null),C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}return b===`load`?(0,B.jsx)(`div`,{className:`personal-machine-loading`,role:`status`,children:t(`common.loading`)}):O?(0,B.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":n?.revision,children:[(0,B.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:17}),t(`machine.liveDefault`)]}),(0,B.jsx)(`p`,{children:t(`machine.liveDefaultDescription`)})]}),(0,B.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,B.jsx)(Jb,{capabilities:E,locale:e,onSelect:a,scope:`machine`,selectedCapabilityId:O.capability_id,t}),(0,B.jsxs)(`article`,{"aria-label":O.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,B.jsx)(Yb,{capability:D,locale:e,source:O.available_scopes.includes(`machine`)?te?`machine_default`:`capability_default`:void 0}),(0,B.jsx)(Gb,{available:ne,t,description:O.available_scopes.includes(`machine`)?t(`machine.editorUnavailableDescription`):t(`machine.goalOnly`)}),O.capability_id===`periodic_report`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:ee?.schedule?e===`zh-CN`?`日历与阶段汇报`:`Calendar and stage reports`:t(`machine.periodicReportActivation`)}),(0,B.jsx)(`p`,{children:ee?.schedule?ee.enabled===!0?e===`zh-CN`?`已配置日历计划,由现有唤醒检查;是否送达请核对报告回执。`:`A calendar schedule is configured and checked by existing wakes. Verify delivery in the report receipt.`:e===`zh-CN`?`日历计划已保存;启用此能力后才会检查和投递。`:`The schedule is saved; enable this capability to check and deliver reports.`:t(`machine.periodicReportActivationDescription`)})]})]}):null,O.capability_id===`change_quality_qualification`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.changeQualityActivation`)}),(0,B.jsx)(`p`,{children:t(`machine.changeQualityActivationDescription`)})]})]}):null,O.capability_id===`todo_replan_cadence`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.replanCadenceActivation`)}),(0,B.jsx)(`p`,{children:t(`machine.replanCadenceActivationDescription`)})]})]}):null,O.capability_id===`pull_request_review`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:e===`zh-CN`?`只改变队列排序`:`Queue ordering only`}),(0,B.jsx)(`p`,{children:e===`zh-CN`?`默认先审阅其他开发者的 PR;选择 owner-first 才会优先当前已认证审阅者自己的 PR。此配置不会发布 review、写 Todo、push 或 merge。`:`The default reviews other developers' PRs first; choose owner-first only when the authenticated reviewer's own PRs should lead. This setting never posts a review, writes Todos, pushes, or merges.`})]})]}):null,ne?(0,B.jsxs)(B.Fragment,{children:[u===`json`||!O.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,B.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,B.jsxs)(`button`,{onClick:()=>P(u===`guided`?`json`:`guided`),type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),t(u===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,u===`guided`?(0,B.jsxs)(`section`,{className:`personal-capability-field-summary`,children:[(0,B.jsx)(Lb,{copy:Vb(e),disabled:!!b,editor:O.configuration_editor,onChange:N,value:o,enabledAction:(0,B.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:()=>P(`json`),type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),t(`machine.editJson`)]})}),j?null:(0,B.jsx)(`p`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.requiredFields`)})]}):(0,B.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`machine-configuration-json`,children:[(0,B.jsx)(`span`,{children:t(`machine.jsonConfiguration`)}),(0,B.jsx)(`textarea`,{"aria-describedby":`machine-configuration-json-help`,disabled:!!b,id:`machine-configuration-json`,onChange:e=>{l(e.target.value),p(null),C(null)},rows:12,spellCheck:!1,value:c}),(0,B.jsx)(`small`,{id:`machine-configuration-json-help`,children:t(`machine.jsonConfigurationHelp`)}),k?null:(0,B.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.jsonInvalid`)})]})]}):null,S?(0,B.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:S}):null,w?(0,B.jsxs)(`p`,{className:`personal-machine-notice`,role:`status`,"aria-live":`polite`,children:[(0,B.jsx)(em,{"aria-hidden":!0,size:16}),w]}):null,f?(0,B.jsxs)(`section`,{"aria-label":t(`machine.preview`),className:`personal-machine-preview`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.preview`)}),(0,B.jsx)(`span`,{children:t(`machine.action.${f.action}`)})]}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`machine.currentRevision`)}),(0,B.jsx)(`dd`,{title:f.current_revision,children:ox(f.current_revision)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`machine.desiredRevision`)}),(0,B.jsx)(`dd`,{title:f.desired_revision,children:ox(f.desired_revision)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`machine.changedNamespaces`)}),(0,B.jsx)(`dd`,{children:f.changed_namespaces.join(`, `)||t(`common.none`)})]})]}),(0,B.jsx)(`p`,{children:t(`machine.previewLocked`)})]}):null,g?.rollback_available&&g.transaction_id?(0,B.jsxs)(`section`,{className:`personal-machine-rollback`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.rollbackAvailable`)}),(0,B.jsx)(`p`,{children:t(v?`machine.rollbackPreviewDescription`:`machine.rollbackDescription`)})]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!!b||!!(v&&!v.rollback_allowed),onClick:()=>void(v?ae():I()),type:`button`,children:[(0,B.jsx)(Lm,{"aria-hidden":!0,size:15}),t(b===`rollback`||b===`rollback-preview`?`common.loading`:v?`machine.confirmRollback`:`machine.previewRollback`)]})]}):null,ne?(0,B.jsxs)(`footer`,{className:`personal-capability-actions`,children:[te?(0,B.jsxs)(`button`,{className:`is-danger`,disabled:!!b,onClick:()=>void re(),type:`button`,children:[(0,B.jsx)(Xm,{"aria-hidden":!0,size:15}),t(`machine.previewRemoval`)]}):null,(0,B.jsx)(`button`,{disabled:!!b||!j,onClick:()=>void F(),type:`button`,children:t(b===`preview`?`common.loading`:`machine.previewChanges`)}),(0,B.jsx)(`button`,{className:`is-primary`,disabled:!!b||!f,onClick:()=>void ie(),type:`button`,children:t(b===`apply`?`common.loading`:`machine.applyPreview`)})]}):null,O.available_scopes.includes(`machine`)?(0,B.jsx)(Ub,{values:[{label:t(`machine.currentValue`),value:ee},{label:t(`capabilities.defaultValue`),value:O.default}],t},O.capability_id):null]})]})]}):(0,B.jsx)(`p`,{className:`personal-capability-empty`,children:t(`machine.capabilityEmpty`)})}var cx={appearance:Am,capabilities:Gm,language:bm,lark:Um,machine:Vm};function lx({focusGoalConnection:e=!1,goals:t,initialGoalId:n,initialTab:r=`lark`,onChanged:i,onClose:a,onThemeChange:o,theme:s}){let{locale:c,setLocale:l,t:u}=Ji(),[d,f]=(0,z.useState)(r),p=[...n?[{key:`capabilities`,label:u(`capabilities.title`)}]:[],{key:`machine`,label:u(`machine.title`)},{key:`lark`,label:`Lark`},{key:`appearance`,label:u(`settings.appearance`)},{key:`language`,label:u(`settings.language`)}],m=[{label:u(`settings.languageEnglish`),value:`en`},{label:u(`settings.languageSimplifiedChinese`),value:`zh-CN`}],h={appearance:{title:u(`settings.appearance`)},capabilities:{title:u(`capabilities.title`)},language:{title:u(`settings.language`)},lark:{title:`Lark`},machine:{title:u(`machine.title`)}}[d];return(0,B.jsxs)(`section`,{"aria-label":u(`settings.title`),className:`personal-settings-page`,"data-pw-theme":s,children:[(0,B.jsxs)(`aside`,{className:`personal-settings-sidebar`,children:[(0,B.jsxs)(`button`,{className:`personal-settings-back`,onClick:a,type:`button`,children:[(0,B.jsx)(Gp,{size:17}),(0,B.jsx)(`span`,{children:u(`settings.back`)})]}),(0,B.jsxs)(`div`,{className:`personal-settings-title`,children:[(0,B.jsx)(`small`,{children:u(`settings.eyebrow`)}),(0,B.jsx)(`strong`,{children:u(`settings.title`)})]}),(0,B.jsx)(`nav`,{"aria-label":u(`settings.categories`),className:`personal-settings-tabs`,children:p.map(e=>{let t=cx[e.key];return(0,B.jsxs)(`button`,{"aria-current":d===e.key?`page`:void 0,onClick:()=>f(e.key),type:`button`,children:[(0,B.jsx)(t,{size:17}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:e.label})})]},e.key)})})]}),(0,B.jsxs)(`main`,{className:`personal-settings-body`,children:[(0,B.jsx)(`header`,{className:`personal-settings-header`,children:(0,B.jsx)(`div`,{children:(0,B.jsx)(`h1`,{children:h.title})})}),d===`lark`?(0,B.jsx)(Ab,{embedded:!0,focusGoalConnection:e,goals:t,initialGoalId:n,onChanged:i,onClose:a}):null,d===`machine`?(0,B.jsx)(sx,{}):null,d===`capabilities`?(0,B.jsx)(ex,{goalId:n}):null,d===`appearance`?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-appearance-settings`,children:[(0,B.jsx)(`small`,{children:u(`settings.workspaceDisplay`)}),(0,B.jsx)(`h3`,{children:u(`settings.appearance`)}),(0,B.jsxs)(`div`,{className:`personal-settings-choice-group`,role:`radiogroup`,"aria-label":u(`settings.workspaceTheme`),children:[(0,B.jsxs)(`button`,{"aria-checked":s===`loopx`,onClick:()=>o(`loopx`),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-settings-theme-swatch is-loopx`}),(0,B.jsx)(`strong`,{children:u(`settings.themeLoopx`)})]}),(0,B.jsxs)(`button`,{"aria-checked":s===`paper`,onClick:()=>o(`paper`),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-settings-theme-swatch is-paper`}),(0,B.jsx)(`strong`,{children:u(`settings.themeDefault`)})]}),(0,B.jsxs)(`button`,{"aria-checked":s===`brutal`,onClick:()=>o(`brutal`),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-settings-theme-swatch is-brutal`}),(0,B.jsx)(`strong`,{children:u(`settings.themeHighContrast`)})]})]})]}):null,d===`language`?(0,B.jsxs)(`section`,{className:`personal-settings-card`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`span`,{className:`personal-settings-icon`,children:(0,B.jsx)(bm,{size:18})}),(0,B.jsx)(`div`,{children:(0,B.jsx)(`h2`,{children:u(`settings.language`)})})]}),(0,B.jsx)(`div`,{"aria-label":u(`settings.language`),className:`personal-language-options`,role:`radiogroup`,children:m.map(e=>(0,B.jsxs)(`button`,{"aria-checked":c===e.value,className:c===e.value?`is-selected`:``,onClick:()=>l(e.value),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:e.label})}),c===e.value?(0,B.jsx)(em,{"aria-hidden":!0,size:17}):null]},e.value))})]}):null]})]})}var ux=`loopx-pw-theme`,dx=`loopx`;function fx(){try{let e=window.localStorage.getItem(ux);return e===`loopx`||e===`paper`||e===`brutal`?e:dx}catch{return dx}}function px(e){try{window.localStorage.setItem(ux,e)}catch{}}function mx({drawer:e,drawerMode:t=`panel`,drawerOpen:n,main:r,mobileSidebarOpen:i=!1,onCloseMobileSidebar:a,sidebar:o,theme:s=`loopx`}){let{t:c}=Ji(),l=(0,z.useRef)(null),u=(0,z.useRef)(null);return(0,z.useEffect)(()=>{if(!i)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null;let e=l.current?.querySelectorAll(`button:not([disabled]), a[href], select:not([disabled]), textarea:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])`);e?.[0]?.focus();function t(t){if(t.key!==`Tab`||!e?.length)return;let n=e[0],r=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),r.focus()):!t.shiftKey&&document.activeElement===r&&(t.preventDefault(),n.focus())}return document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`keydown`,t),u.current?.focus(),u.current=null}},[i]),(0,B.jsxs)(`section`,{className:`personal-workspace-shell${n?` has-drawer`:``}${n&&t.startsWith(`inspector`)?` has-task-inspector`:``}${t===`inspector-full`?` is-task-inspector-full`:``}${i?` mobile-sidebar-open`:``}`,"data-pw-theme":s,children:[i?(0,B.jsx)(`button`,{"aria-hidden":!0,className:`personal-sidebar-backdrop`,onClick:a,tabIndex:-1,type:`button`}):null,(0,B.jsx)(`aside`,{"aria-label":i?c(`header.goalNavigation`):void 0,"aria-modal":i?!0:void 0,className:`personal-workspace-sidebar`,"data-workspace-sidebar":!0,ref:l,role:i?`dialog`:void 0,children:(0,B.jsxs)(`div`,{className:`personal-workspace-sidebar-inner`,children:[i?(0,B.jsxs)(`button`,{className:`personal-sr-only`,onClick:a,type:`button`,children:[c(`common.close`),` `,c(`header.goalNavigation`)]}):null,o]})}),(0,B.jsx)(`main`,{"aria-hidden":i||void 0,className:`personal-workspace-main`,inert:i||void 0,children:r}),n?(0,B.jsx)(`aside`,{className:`personal-workspace-drawer`,"data-context-drawer":!0,"data-drawer-mode":t,children:e}):null]})}function hx(e){let t=e.match(/(?:下一步|建议|行动项|待办)[::\s]*([^\n]+)/u),n=t?t[1]:e;n=n.replace(/```[\s\S]*?```/g,``).replace(/`([^`]+)`/g,`$1`).replace(/\[([^\]]+)\]\([^)]+\)/g,`$1`).replace(/[#*~_>]/g,``).replace(/^[-*•\d+.\s]+/u,``).replace(/^(好的|没问题|收到|建议如下|任务如下|分析如下|结论[::])[\s,,::]*/u,``);let r=(n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean)[0]||n).replace(/\s+/gu,` `).trim();return Array.from(r).slice(0,120).join(``)}function gx(e){let t=new Map;return e.forEach(e=>{let n=e.fields.find(e=>e.key===`todo_id`)?.value??``,r=[e.actionKind,e.goalId??``,n,e.title].join(`:`);t.set(r,e)}),[...t.values()]}function _x(e,t,n){if(!e)return n(`home.noFirstActivity`);let r=new Date(e);if(Number.isNaN(r.getTime()))return e;let i=new Date,a=new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r);return r.toDateString()===i.toDateString()?n(`home.todayAt`,{time:a}):new Intl.DateTimeFormat(t,{month:`numeric`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r)}function vx({goals:e,onSelectGoal:t,onRetry:n,systemHealth:r}){let{locale:i,t:a}=Ji(),o=e.filter(e=>e.activationState===`active`),s=o.filter(e=>e.loadState===`error`).length,c=[{key:`needs_you`,label:a(`home.lane.needsYou`)},{key:`running`,label:a(`home.lane.running`)},{key:`observing`,label:a(`home.lane.observing`)},{key:`scheduled`,label:a(`home.lane.scheduled`)}],l=Object.fromEntries(c.map(e=>[e.key,[]])),u=[],d=[];e.filter(e=>!e.loadState).forEach(e=>{let t=gy(e);t===`history`?u.push(e):t===`stopped`?d.push(e):l[t].push(e)});let f=e=>(0,B.jsxs)(`button`,{className:`personal-home-goal-card`,"data-goal-state":e.loadState??e.state,"data-load-error":e.loadError,onClick:()=>t(e.goalId),type:`button`,children:[(0,B.jsxs)(`span`,{className:`personal-home-goal-meta`,children:[(0,B.jsx)(`i`,{}),e.agentLaneCount&&e.agentLaneCount>1?a(`header.workAgentCount`,{count:e.agentLaneCount}):e.agentLabel??e.agentId]}),(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsx)(`p`,{children:e.loadError?a(`startup.error.${e.loadError}`):e.needsYou??e.nextSentence}),(0,B.jsxs)(`footer`,{children:[(0,B.jsx)(`span`,{children:e.loadState?a(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Yi(e.state,i)}),(0,B.jsx)(`small`,{title:e.latestActivity,children:e.loadState?``:e.latestActivity?_x(e.latestActivity,i,a):e.agentTodos.length?a(`home.taskCount`,{count:e.agentTodos.length}):a(`home.noActivity`)})]})]},e.goalId);return(0,B.jsxs)(`section`,{"aria-label":a(`home.workspace`),className:`personal-home-board`,children:[r&&(!r.ok||r.issues.length>0||r.freshnessWarning)?(0,B.jsxs)(`div`,{className:`personal-system-health-banner`,role:`alert`,children:[(0,B.jsxs)(`div`,{className:`personal-system-health-header`,children:[(0,B.jsx)(im,{size:15}),(0,B.jsx)(`strong`,{children:a(`home.systemHealth`,{summary:r.summary})}),r.freshnessWarning?(0,B.jsxs)(`small`,{children:[`(`,r.freshnessWarning,`)`]}):null]}),r.issues.length>0?(0,B.jsx)(`ul`,{className:`personal-system-health-issues`,children:r.issues.map((e,t)=>(0,B.jsx)(`li`,{children:e},t))}):null]}):null,o.some(e=>e.loadState)?(0,B.jsxs)(`section`,{className:`personal-home-lane`,"aria-live":`polite`,children:[(0,B.jsx)(`header`,{children:a(`startup.progress`,{loaded:o.filter(e=>!e.loadState).length,total:o.length})}),s?(0,B.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`status`,children:[(0,B.jsx)(`span`,{children:a(`startup.failedCount`,{count:s})}),(0,B.jsx)(`button`,{className:`min-h-11 rounded-md border px-3 py-2 text-sm`,onClick:n,type:`button`,children:a(`startup.retryFailed`)})]}):null,o.filter(e=>e.loadState).map(f)]}):null,(0,B.jsx)(`div`,{className:`personal-home-lanes`,children:c.map(e=>(0,B.jsxs)(`section`,{className:`personal-home-lane is-${e.key}`,"data-testid":`personal-home-lane-${e.key}`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`i`,{}),e.label]}),(0,B.jsx)(`b`,{children:l[e.key].length})]}),(0,B.jsx)(`div`,{className:`personal-home-lane-list`,children:l[e.key].length?l[e.key].map(f):(0,B.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.empty`)})})]},e.key))}),(0,B.jsxs)(`details`,{className:`personal-home-history`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(`span`,{children:a(`home.history`)}),(0,B.jsx)(`b`,{children:u.length}),(0,B.jsx)(`small`,{children:a(`home.completedGoals`)})]}),(0,B.jsx)(`div`,{children:u.length?u.map(f):(0,B.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.noCompletedGoals`)})})]}),d.length?(0,B.jsxs)(`details`,{className:`personal-home-history is-stopped`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(`span`,{children:a(`home.stopped`)}),(0,B.jsx)(`b`,{children:d.length}),(0,B.jsx)(`small`,{children:a(`home.preservedState`)})]}),(0,B.jsx)(`div`,{children:d.map(f)})]}):null]})}function yx({items:e,onSelect:t,reportState:n}){let{locale:r,t:i}=Ji();return(0,B.jsxs)(`section`,{className:`personal-object-list personal-files-list`,"data-testid":`personal-goal-outputs`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:i(`files.title`)}),(0,B.jsx)(`span`,{children:e.length})]}),n?.loading?(0,B.jsxs)(`p`,{className:`personal-object-list-state`,role:`status`,children:[(0,B.jsx)(Im,{className:`is-spinning`,size:14}),i(`files.loadingReports`)]}):null,n?.error?(0,B.jsxs)(`p`,{className:`personal-object-list-state is-error`,role:`alert`,children:[(0,B.jsx)(im,{size:14}),i(`files.reportLoadFailed`),`: `,n.error]}):null,!n?.loading&&!n?.error&&e.length===0?(0,B.jsxs)(`p`,{className:`personal-object-list-state`,children:[(0,B.jsx)(gm,{size:14}),i(`files.empty`)]}):null,e.map(e=>(0,B.jsxs)(`button`,{"data-output-kind":e.output.kind,onClick:()=>t({item:e.output,kind:`output`}),type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-file-icon`,children:(0,B.jsx)(gm,{size:16})}),(0,B.jsx)(`strong`,{children:e.output.title}),e.output.report?(0,B.jsx)(`em`,{children:i(`files.reportDelta`,{added:e.output.report.addedCount,changed:e.output.report.changedCount})}):null,(0,B.jsx)(`p`,{children:e.output.summary??e.output.safePreview??e.output.kind??i(`files.emptySummary`)}),(0,B.jsx)(`small`,{title:e.output.createdAt,children:[e.output.goalTitle,e.output.kind===`report`?i(`files.verifiedReport`):null,e.output.todoId?`${i(`common.task`)} ${e.output.todoId}`:null,_x(e.output.createdAt,r,i)].filter(Boolean).join(` · `)})]},e.id))]})}function bx({agentLabel:e,messages:t,onClose:n,onDraftTask:r,onOpenConversation:i,title:a}){let{t:o}=Ji(),s=t.reduce((e,t,n)=>t.role===`user`?n:e,0),c=t.slice(Math.max(0,s)).slice(-3),l=c.filter(e=>e.role===`assistant`&&!e.pending).at(-1);return(0,z.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),(0,B.jsxs)(`aside`,{"aria-label":o(`conversation.receipt`),className:`personal-manager-conversation-tray`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:16}),(0,B.jsx)(`strong`,{children:a??o(`conversation.title`)}),(0,B.jsx)(`small`,{children:t.at(-1)?.pending?o(`conversation.replying`):o(`common.recently`)})]}),(0,B.jsxs)(`div`,{className:`personal-manager-conversation-actions`,children:[r&&l?(0,B.jsxs)(`button`,{className:`personal-manager-conversation-btn`,onClick:()=>r(l.text),title:o(`conversation.convertHint`),type:`button`,children:[(0,B.jsx)(Sm,{size:13}),(0,B.jsx)(`span`,{children:o(`conversation.toTask`)})]}):null,(0,B.jsx)(`button`,{className:`personal-manager-conversation-link`,onClick:i,type:`button`,children:o(`conversation.full`)}),n?(0,B.jsx)(`button`,{"aria-label":o(`conversation.close`),className:`personal-manager-conversation-close`,onClick:n,title:o(`conversation.close`),type:`button`,children:(0,B.jsx)($m,{size:14})}):null]})]}),(0,B.jsx)(`div`,{"aria-live":`polite`,className:`personal-manager-conversation-messages`,children:c.map(t=>(0,B.jsxs)(`article`,{className:`is-${t.role}`,children:[(0,B.jsx)(`strong`,{children:t.role===`user`?o(`common.you`):t.agentLabel??e??o(`header.manager`)}),(0,B.jsxs)(`div`,{className:`personal-manager-conversation-bubble`,children:[t.role===`user`?(0,B.jsx)(`p`,{children:t.text}):(0,B.jsx)(jy,{text:t.text}),t.pending?(0,B.jsx)(`small`,{children:o(`conversation.agentPending`)}):null]})]},t.id))})]})}function xx({onClose:e,onOpenDetails:t,run:n}){let{t:r}=Ji();return(0,B.jsxs)(`section`,{"aria-label":r(`session.record`),className:`personal-session-record`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:17}),r(`session.record`)]}),(0,B.jsx)(`button`,{"aria-label":r(`session.closeRecord`),onClick:e,type:`button`,children:(0,B.jsx)($m,{size:15})})]}),(0,B.jsx)(`div`,{children:(0,B.jsx)(`strong`,{children:n.title})}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Agent`}),(0,B.jsx)(`dd`,{children:n.agentLabel})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`common.status`)}),(0,B.jsx)(`dd`,{children:Xi(n.sessionStatus??n.status,r)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Session`}),(0,B.jsx)(`dd`,{title:n.sessionId,children:n.sessionId})]})]}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:t,type:`button`,children:r(`session.details`)})]})}function Sx(e,t,n){let r=[];if(t===null)return e.userTodos.slice(0,4).forEach(t=>r.push({attention:{...t,goalTitle:t.goalTitle??hy(e,t.goalId)},id:`attention:${t.todoId}`,kind:`attention`})),e.goals.filter(e=>gy(e)===`running`).slice(0,4).forEach(e=>r.push({id:`run:${e.goalId}`,kind:`run`,run:{agentId:e.agentId,agentLabel:e.agentLabel??e.agentId,completedSteps:e.doneTodoCount??e.agentTodos.filter(e=>e.done).length,goalId:e.goalId,goalTitle:e.title,latestActivity:e.agentSentence,runId:`goal:${e.goalId}`,status:`running`,title:e.nextSentence,totalSteps:Math.max((e.doneTodoCount??0)+e.agentTodos.filter(e=>!e.done).length,1)}})),r;let i=e.goals.find(e=>e.goalId===t);if(!i)return r;if(i.needsYou){let t=e.userTodos.find(e=>e.goalId===i.goalId);r.push({attention:t?{...t,goalTitle:i.title}:{blocking:i.needsYouBlocking??!1,goalId:i.goalId,goalTitle:i.title,text:i.needsYou,todoId:`${i.goalId}:attention`},id:`attention:${i.goalId}`,kind:`attention`})}r.push({id:`run:${i.goalId}`,kind:`run`,run:{agentId:i.agentId,agentLabel:i.agentLabel??i.agentId,completedSteps:i.doneTodoCount??i.agentTodos.filter(e=>e.done).length,goalId:i.goalId,goalTitle:i.title,latestActivity:i.agentSentence,runId:`goal:${i.goalId}`,status:i.state===`推进中`?`running`:i.state===`需修复`?`failed`:`waiting`,title:i.nextSentence,totalSteps:Math.max((i.doneTodoCount??0)+i.agentTodos.filter(e=>!e.done).length,1)}}),i.agentTodos.filter(e=>e.taskClass===`continuous_monitor`).forEach(t=>{let a=e.timeline?.find(e=>e.kind===`run`&&e.run.goalId===i.goalId&&e.run.todoId===t.todoId&&!!e.run.sessionId);r.push({id:`schedule:${i.goalId}:${t.todoId}`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:a?[{label:a.run.latestActivity||a.run.title,runId:a.run.runId,status:a.run.status===`waiting`||a.run.status===`queued`?`running`:a.run.status,timestamp:i.latestActivity||n(`common.recently`)}]:[],goalId:i.goalId,label:t.text,schedule:t.evidence??n(`schedule.summary`),scheduleId:t.todoId,scheduleKind:`monitor`,sessionId:a?.run.sessionId,status:t.done||t.status===`paused`?`paused`:`active`,stopCondition:n(`drawer.scheduleDefaultStop`),target:t.text,timezone:`Asia/Shanghai`}})});let a=e.timeline?.find(e=>e.kind===`proposal`&&e.proposal.actionKind===`heartbeat.bind`&&e.proposal.goalId===i.goalId);if(a){let e=e=>a.proposal.fields.find(t=>t.key===e)?.value;r.push({id:`schedule:${i.goalId}:heartbeat`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:[],goalId:i.goalId,label:`${n(`schedule.heartbeat`)} · ${i.title}`,nextRunAt:n(`drawer.schedulePending`),notificationRule:n(`drawer.scheduleDefaultNotification`),schedule:e(`cadence`)??n(`schedule.summary`),scheduleId:`${i.goalId}:heartbeat`,scheduleKind:`heartbeat`,status:a.proposal.status===`applied`?`active`:`draft`,stopCondition:e(`stop_condition`)??n(`drawer.scheduleDefaultStop`),timezone:e(`timezone`)??`Asia/Shanghai`}})}return r}function Cx(e){return e===`preview_ready`?`ready`:e===`cancelled`?`draft`:e===`failed`?`error`:e}function wx(e,t){let n={agent_id:t(`proposal.field.agentId`),cadence:t(`proposal.field.cadence`),completion_criteria:t(`proposal.field.completionCriteria`),execution_boundary:t(`proposal.field.executionBoundary`),goal_id:t(`proposal.field.goalId`),heartbeat:t(`proposal.field.heartbeat`),initial_todos:t(`proposal.field.initialTodos`),objective:t(`proposal.field.objective`),operation:t(`proposal.field.operation`),permission:t(`proposal.field.permission`),reason:t(`proposal.field.reason`),stop_condition:t(`proposal.field.stopCondition`),target:t(`proposal.field.target`),timezone:t(`proposal.field.timezone`),title:t(`proposal.field.title`),workspace_ref:t(`proposal.field.workspace`)},r=[`title`,`objective`,`completion_criteria`,`execution_boundary`,`permission`,`agent_id`,`workspace_ref`,`initial_todos`,`heartbeat`,`stop_condition`,`goal_id`];return Object.entries(e).sort(([e],[t])=>{let n=r.indexOf(e),i=r.indexOf(t);return(n<0?r.length:n)-(i<0?r.length:i)}).slice(0,10).map(([e,r])=>({key:e,label:n[e]??e.replaceAll(`_`,` `),value:e===`workspace_ref`?r===`current`?t(`proposal.workspace.current`):t(`proposal.workspace.named`,{workspace:String(r??`current`)}):Array.isArray(r)?r.join(` · `):typeof r==`object`&&r?JSON.stringify(r):String(r??`—`)}))}function Tx(e,t){let n=e.normalized_parameters.projection,r=n&&typeof n==`object`?n:{},i=Array.isArray(r.fields)?r.fields.flatMap((e,t)=>{if(!e||typeof e!=`object`)return[];let n=e;return typeof n.label!=`string`||typeof n.value!=`string`?[]:[{key:`projection:${t}`,label:n.label,value:n.value}]}).slice(0,8):[];return[{key:`operation_state`,label:t(`proposal.field.operationState`),value:e.operation?.lifecycle_state??e.status},...e.operation?.lifecycle_state===`outcome_observed`?[{key:`result_delivery`,label:t(`proposal.field.resultDelivery`),value:e.operation.result_delivery?t(`proposal.resultDelivery.verified`):t(`proposal.resultDelivery.pending`)}]:[],...i,...typeof r.warning==`string`?[{key:`warning`,label:t(`proposal.field.confirmationBoundary`),value:r.warning}]:[],...e.operation?.expires_at?[{key:`expires_at`,label:t(`proposal.field.expiresAt`),value:e.operation.expires_at}]:[]].slice(0,10)}function Ex(e){if(e.action_kind!==`goal.lifecycle`)return;let t=e.normalized_parameters.operation;return t===`stop`||t===`resume`||t===`delete`?t:void 0}function Dx(e,t){let n=Ex(e),r=fy(e),i=typeof e.normalized_parameters.title==`string`?e.normalized_parameters.title:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:``,a=typeof e.normalized_parameters.target==`string`?e.normalized_parameters.target:``,o=e.normalized_parameters.projection,s=o&&typeof o==`object`&&typeof o.title==`string`?String(o.title):e.summary,c=e.action_kind===`operation.execute`?s:e.action_kind===`goal.create`?t(`proposal.summary.goalCreate`,{title:i}):e.action_kind===`heartbeat.bind`?t(`proposal.summary.heartbeat`):e.action_kind===`monitor.create`?t(`proposal.summary.monitor`,{target:a}):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.summary.lifecycleStop`,{title:i}):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.summary.lifecycleDelete`,{title:i}):e.action_kind===`goal.lifecycle`?t(`proposal.summary.lifecycleResume`,{title:i}):e.summary;return{actionKind:e.action_kind,reviewPlan:r,fields:e.action_kind===`operation.execute`?Tx(e,t):wx(e.normalized_parameters,t),goalId:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:void 0,impact:e.action_kind===`operation.execute`?t(`proposal.impact.operation`):e.action_kind===`goal.create`?t(`proposal.impact.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.impact.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.impact.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.impact.lifecycleResume`):e.permission_classification===`protected`?t(`proposal.impact.protected`):t(`proposal.impact.default`),previewId:e.proposal_id,lifecycleOperation:n,gate:e.gate?{kind:String(e.gate.kind??`protected_action`),nextAction:typeof e.gate.next_action==`string`?e.gate.next_action:void 0,summary:String(e.gate.summary??t(`proposal.gate.default`))}:void 0,primaryLabel:e.action_kind===`operation.execute`?t(`proposal.primary.operationGroup`):e.action_kind===`goal.create`?t(`proposal.primary.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.primary.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.primary.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.primary.lifecycleResume`):e.action_kind===`todo.create`&&e.normalized_parameters.start_execution===!0?t(`proposal.primary.todoStart`):t(`proposal.primary.apply`),status:e.status===`applied`&&r.interaction!==`completed`?`error`:Cx(e.status),title:c}}function Ox(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,42);if(t)return t;let n=2166136261;for(let t of e)n^=t.codePointAt(0)??0,n=Math.imul(n,16777619);return`goal-${(n>>>0).toString(36)}`}function kx(e,t){let n=e.match(/[「“"]([^」”"]{2,80})[」”"]/u)?.[1];return n?n.trim():e.replace(/^(请|帮我|我想|给我|创建|新建|设置|please|i want to|create|set up)+/iu,``).replace(/(一个|新的)?\s*(goal|目标)/giu,``).replace(/[,。!?].*$/u,``).trim().slice(0,80)||t(`goal.defaultTitle`)}function Ax(e,t){for(let n of e.split(/\r?\n/u)){let e=n.trim();for(let n of t){let t=e.match(RegExp(`^${n.replace(/[.*+?^${}()|[\]\\]/gu,`\\$&`)}\\s*[::]\\s*(.*)$`,`iu`));if(t?.[1]?.trim())return t[1].trim()}}return``}function jx(e,t){let n=Ax(e,[`目标`,`Objective`]),r=Ax(e,[`完成标准`,`Completion criteria`]),i=Ax(e,[`执行边界(可选)`,`执行边界`,`边界`,`Execution boundary (optional)`,`Execution boundary`,`Boundary`]),a=(n||kx(e,t)).split(/[。;;\n]/u)[0].trim().slice(0,80)||t(`goal.defaultTitle`),o=[n||a,r?t(`goal.objectiveCompletion`,{criteria:r}):``,i?t(`goal.objectiveBoundary`,{boundary:i}):``].filter(Boolean).join(` +`),s=/(只读|不调用外部工具|不修改(?:仓库|代码|状态)|read.?only|do not (?:call|use) external tools|do not modify (?:repositories|repository|code|state))/iu.test(i||e);return{completionCriteria:r,executionBoundary:i,initialTodos:r?[t(`goal.initialTodo`,{criteria:r})]:[],objective:o,permission:s?`read_only`:`workspace_write_on_confirmation`,title:a}}function Mx(e){let t=e.match(/(?:每|every)\s*(\d{1,3})\s*(?:分钟|minutes?)/iu)?.[1];if(t)return`${t}m`;let n=e.match(/(?:每|every)\s*(\d{1,2})\s*(?:小时|hours?)/iu)?.[1];return n?`${n}h`:/每小时|every hour|hourly/iu.test(e)?`1h`:(/每天|每日|早上|上午|daily|every day/iu.test(e),`1d`)}function Nx(e,t){return/(每周|星期|周[一二三四五六日天]|weekly|every\s+(?:mon|tues|wednes|thurs|fri|satur|sun)day|\d{1,2}\s*[::]\s*\d{2})/iu.test(e)?t(`schedule.unsupportedCalendar`):null}function Px(e,t){return Ax(e,[`检查内容`,`监控内容`,`目标`,`Check target`,`Monitor target`,`Target`])||e.replace(/^(?:为当前 Goal |for the current Goal )?(?:添加|配置|创建|add|configure|create)?\s*(?:定时检查|监控|scheduled check|monitor)[::]?/iu,``).split(/\r?\n/u)[0].trim()||t(`schedule.defaultTarget`)}function Fx(e){return/(mr|pr).{0,8}(合并|merge)/iu.test(e)?`pr_merged`:/发布完成|上线完成|release (?:is )?complete|deployment (?:is )?complete/iu.test(e)?`release_complete`:`goal_complete`}function Ix(e,t){let n=e.toLowerCase();return t.find(e=>n.includes(e.agentId.toLowerCase())||n.includes(e.label.toLowerCase()))}function Lx(e){let t=Ax(e,[`标题`,`任务标题`,`Todo 标题`]),n=Ax(e,[`内容`,`任务内容`,`Todo 内容`]);if(t)return[t,n].filter(Boolean).join(`:`).slice(0,400);let r=e.match(/[「“"]([^」”"]{2,200})[」”"]/u)?.[1];return r?r.trim():e.replace(/^(请|帮我|给我|为当前 Goal |新增|新建|创建|添加|加上|加一个|记一个)+/u,``).replace(/^(一个\s*)?(普通\s*)?(todo|待办|任务)(?:\s*到\s*Tasks?)?[::\s]*/iu,``).replace(/[。;;,,]\s*(?:不要|不需要|无需|禁止|别|暂不).{0,80}(?:heartbeat|心跳|定时|监控|执行).*$/iu,``).replace(/[,,]\s*(并且|然后|再)?\s*(交给|分配给|让).+$/u,``).replace(/\s*(交给|分配给|让)\s+.+$/u,``).trim().slice(0,400)||`推进当前 Goal 的下一项工作`}var Rx=new Set([`image/png`,`image/jpeg`,`image/webp`,`image/gif`]),zx=5242880,Bx=4;function Vx(e,t){return new Promise((n,r)=>{let i=new FileReader;i.onerror=()=>r(Error(t(`composer.imageReadError`,{name:e.name}))),i.onload=()=>n({dataUrl:String(i.result??``),id:crypto.randomUUID(),mimeType:e.type,name:e.name,size:e.size}),i.readAsDataURL(e)})}function Hx({agents:e=[{agentId:`codex`,available:!0,capability:`代码与项目执行`,label:`Codex`}],callbacks:t={},goalArchiveLoadState:n={error:null,phase:`ready`},model:r,readOnly:i=!1,selectedAgentId:a,selectedGoalId:o,statusSourceControl:s}){let{locale:c,t:l}=Ji(),[u,d]=(0,z.useState)(o??null),[f,p]=(0,z.useState)(a??e.find(e=>e.available)?.agentId??`codex`),[m,h]=(0,z.useState)(null),[g,_]=(0,z.useState)(!1),[v,y]=(0,z.useState)(null),[b,x]=(0,z.useState)({}),[S,C]=(0,z.useState)(`chat`),[w,T]=(0,z.useState)(!1),[E,D]=(0,z.useState)(!1),[O,ee]=(0,z.useState)(!1),[te,ne]=(0,z.useState)(()=>{try{let e=window.sessionStorage.getItem(`loopx-pw-composer-drafts`),t=e?JSON.parse(e):{};return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}),[k,A]=(0,z.useState)(!1),[j,M]=(0,z.useState)([]),[N,P]=(0,z.useState)(null),[F,re]=(0,z.useState)(null),[ie,I]=(0,z.useState)(()=>new Set),[ae,L]=(0,z.useState)(()=>new Set),[oe,se]=(0,z.useState)(`idle`),[ce,le]=(0,z.useState)([]),[ue,de]=(0,z.useState)(!1),[fe,pe]=(0,z.useState)(fx),[me,he]=(0,z.useState)({}),[ge,_e]=(0,z.useState)([]),ve=(0,z.useRef)(!1),ye=(0,z.useRef)(NaN),be=(0,z.useRef)(null),xe=(0,z.useRef)(null),Se=(0,z.useRef)(null),Ce=(0,z.useRef)(new Set),we=(0,z.useRef)(new Set),[Te,Ee]=(0,z.useState)(null),R=o===void 0?u:o,De=a??f,Oe=`${R??`manager`}:${De}`,ke=te[Oe]??``;(0,z.useEffect)(()=>{M([]),P(null)},[Oe]);function Ae(e,t){ne(n=>{let r={...n};t?r[e]=t:delete r[e];try{window.sessionStorage.setItem(`loopx-pw-composer-drafts`,JSON.stringify(r))}catch{}return r})}function je(e){Ae(Oe,e)}function Me(e){let t=te[Oe]?.trimEnd();je(t?`${t}\n${e}`:e),window.requestAnimationFrame(()=>be.current?.focus())}(0,z.useEffect)(()=>{let e=be.current;e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,120)}px`)},[ke]);let Ne=(0,z.useMemo)(()=>r.goals.map(e=>{let t=me[e.goalId];return t?{...e,repository:{branch:t.branch,identity:t.identity,label:t.label,readOnly:!0}}:e}),[me,r.goals]),Pe=(0,z.useMemo)(()=>Ne.filter(e=>gy(e)===`needs_you`).length,[Ne]),Fe=(0,z.useMemo)(()=>Ne.filter(e=>gy(e)===`needs_you`&&(e.needsYouBlocking||e.state===`等你`)).length,[Ne]),V=Ne.find(e=>e.goalId===R)??null,Ie=m?.kind===`settings`,Le=R,Re=(0,z.useMemo)(()=>{let e=Object.values(b).filter(e=>e.actionKind===`heartbeat.bind`&&e.goalId&&e.status===`applied`).map(e=>({id:`schedule:${e.goalId}:heartbeat`,kind:`schedule`,schedule:{agentId:De,executionHistory:[],goalId:e.goalId,label:e.title,nextRunAt:l(`drawer.schedulePending`),notificationRule:l(`drawer.scheduleDefaultNotification`),schedule:e.fields.find(e=>e.key===`cadence`)?.value??l(`schedule.summary`),scheduleId:`${e.goalId}:heartbeat`,scheduleKind:`heartbeat`,status:e.status===`applied`?`active`:`draft`,stopCondition:e.fields.find(e=>e.key===`stop_condition`)?.value??l(`drawer.scheduleDefaultStop`),timezone:e.fields.find(e=>e.key===`timezone`)?.value??`Asia/Shanghai`}})),t=[...Sx(r,Le,l),...r.timeline??[],...e,...gx(Object.values(b)).filter(e=>e.actionKind!==`heartbeat.bind`||e.status!==`applied`).map(e=>({id:`proposal:${e.previewId}`,kind:`proposal`,proposal:e}))];return[...new Map(t.map(e=>[e.id,e])).values()].filter(e=>e.kind!==`proposal`||![`stale`,`error`].includes(e.proposal.status)||ce.includes(e.proposal.previewId)).filter(e=>!R||e.kind===`message`?!0:e.kind===`proposal`?!e.proposal.goalId||e.proposal.goalId===R:e.kind===`attention`?e.attention.goalId===R:e.kind===`run`?e.run.goalId===R:e.kind===`schedule`?e.schedule.goalId===R:e.output.goalId===R)},[Le,r,b,De,R,ce,l]),ze=(0,z.useMemo)(()=>v?Re.filter(e=>e.kind===`message`?!0:e.kind===`run`?e.run.runId===v.runId:e.kind===`output`&&e.output.runId===v.runId):Re,[v,Re]);(0,z.useEffect)(()=>{if(!v)return;let e=Re.find(e=>e.kind===`run`&&e.run.runId===v.runId);!e||e.kind!==`run`||JSON.stringify({completedSteps:v.completedSteps,latestActivity:v.latestActivity,messages:v.sessionMessages,sessionStatus:v.sessionStatus,status:v.status,totalSteps:v.totalSteps})!==JSON.stringify({completedSteps:e.run.completedSteps,latestActivity:e.run.latestActivity,messages:e.run.sessionMessages,sessionStatus:e.run.sessionStatus,status:e.run.status,totalSteps:e.run.totalSteps})&&y(e.run)},[v,Re]);let Be=(0,z.useMemo)(()=>Re.flatMap(e=>e.kind===`message`?[e.message]:[]),[Re]),Ve=(0,z.useMemo)(()=>V?Re.flatMap(e=>e.kind===`message`?[e.message]:[]):[],[Re,V]);(0,z.useEffect)(()=>{V||w||Be.some(e=>e.pending)&&D(!0)},[w,Be,V]),(0,z.useEffect)(()=>{!V||S===`chat`||Ve.some(e=>e.pending)&&ee(!0)},[Ve,V,S]);let He=(0,z.useMemo)(()=>Re.filter(e=>e.kind===`message`||e.kind===`proposal`&&ce.includes(e.proposal.previewId)),[Re,ce]),Ue=He[He.length-1],We=Ue?.kind===`message`?Ue.message.text.length:0;(0,z.useEffect)(()=>{if(!w||!xe.current)return;let e=window.requestAnimationFrame(()=>{xe.current&&(xe.current.scrollTop=xe.current.scrollHeight)});return()=>window.cancelAnimationFrame(e)},[He.length,w,We]);let Ge=(0,z.useMemo)(()=>{if(m?.kind===`settings`)return null;if(m?.kind===`attention`)return{kind:`attention`,item:Gd(m.item,r.attentionHistory??r.userTodos)};if(m?.kind===`goal`){let e=Ne.find(e=>e.goalId===m.item.goalId);return e?{item:e,kind:`goal`}:m}if(m?.kind!==`run`)return m;let e=Re.find(e=>e.kind===`run`&&e.run.runId===m.item.runId);return e?{item:e.run,kind:`run`}:m},[Re,m,Ne,r.attentionHistory,r.userTodos]);(0,z.useEffect)(()=>{if(i){he({}),_e([]);return}let e=!1;return Promise.all([Ig(),qg()]).then(([t,n])=>{e||(he(Object.fromEntries(t.map(e=>[e.goal_id,e.repository]))),_e(n))}).catch(()=>{}),()=>{e=!0}},[i]),(0,z.useEffect)(()=>{if(!ue)return;function e(e){e.key===`Escape`&&de(!1)}return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[ue]),(0,z.useEffect)(()=>{if(R||!Re.length)return;if(!ve.current){ve.current=!0;try{ye.current=Date.parse(window.localStorage.getItem(`loopx-pw-last-visit`)??``),window.localStorage.setItem(`loopx-pw-last-visit`,new Date().toISOString())}catch{ye.current=NaN}}let e=ye.current,t=Re.filter(e=>e.kind===`run`).map(e=>e.run),n=t=>{let n=Date.parse(t??``);return!Number.isNaN(e)&&!Number.isNaN(n)&&n>e},r={attention:Pe,done:t.filter(e=>e.status===`completed`&&n(e.latestActivity)).length,failed:t.filter(e=>(e.status===`failed`||e.status===`interrupted`)&&n(e.latestActivity)).length};Ee(e=>e?.attention===r.attention&&e.done===r.done&&e.failed===r.failed?e:r)},[Re,Pe,R]),(0,z.useEffect)(()=>{if(i){x({});return}let e=!1;return Mh(R?{goalId:R}:{contextKind:`manager`}).then(t=>{if(e)return;let n=Object.fromEntries(t.filter(e=>[`ready`,`gated`,`deferred`,`applying`].includes(e.status)).map(e=>{let t=Dx(e,l);return[t.previewId,t]}));x(e=>({...e,...n}))}).catch(()=>{}),()=>{e=!0}},[i,R,l]);async function Ke(e,n={}){if(i)throw Error(l(`source.readOnlyWriteError`));let r;try{r=t.onPreviewAction?await t.onPreviewAction(e):Dx(await Ah(e),l)}catch(t){if(!(t instanceof Th)||t.payload.error_code!==`action_preview_gate`)throw t;let n=t.payload.gate&&typeof t.payload.gate==`object`?t.payload.gate:{},i=(Array.isArray(n.candidates)?n.candidates:[]).flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.workspace_ref==`string`&&typeof t.label==`string`?[{label:t.label,workspaceRef:t.workspace_ref}]:[]}),a=String(n.kind??`workspace_selection_required`),o=a===`agent_binding_required`||a===`agent_identity_selection_required`;r={actionKind:e.actionKind,fields:i.map(e=>({key:`workspace_ref:${e.workspaceRef}`,label:e.label,value:e.workspaceRef})),gate:{kind:a,nextAction:typeof n.next_action==`string`?n.next_action:void 0,summary:String(n.summary??l(`proposal.workspaceGate.defaultSummary`))},impact:l(o?`proposal.workspaceGate.agentImpact`:`proposal.workspaceGate.selectionImpact`),previewId:`workspace-choice-${Date.now().toString(36)}`,sourceRequest:e,status:`gated`,title:l(o?`proposal.workspaceGate.agentTitle`:`proposal.workspaceGate.selectionTitle`),workspaceCandidates:i}}return le(e=>e.includes(r.previewId)?e:[...e,r.previewId]),x(e=>({...e,[r.previewId]:r})),n.select!==!1&&h({item:r,kind:`proposal`}),r}function qe(){tt(null),Ae(`manager:${De}`,l(`composer.createGoalTemplate`)),window.requestAnimationFrame(()=>be.current?.focus())}async function Je(e,n){de(!1);let r={delete:`Deleted from the owner workspace`,resume:`Resumed from the owner workspace`,stop:`Stopped from the owner workspace`},i={delete:l(`proposal.summary.lifecycleDelete`,{title:e.title}),resume:l(`proposal.summary.lifecycleResume`,{title:e.title}),stop:l(`proposal.summary.lifecycleStop`,{title:e.title})},a=null,o=!1;try{if(n===`stop`){if(Ce.current.has(e.goalId))return;Ce.current.add(e.goalId),I(new Set(Ce.current)),h(null),a={goalId:e.goalId,next:`stopped`,optimisticApplied:!0,previous:e.activationState},re(l(`feedback.applying`,{title:i.stop})),t.onGoalActivationStateChange?.(e.goalId,`stopped`)}if(t.onExecuteGoalLifecycle){if(n===`delete`)throw Error(`The selected status source does not authorize Goal deletion.`);let a=await t.onExecuteGoalLifecycle({goalId:e.goalId,operation:n,reason:r[n]});if(!a.projectionVerified)throw Error(`Goal lifecycle projection did not verify.`);o=!0,t.onGoalActivationStateChange?.(e.goalId,a.activationState),re(l(`feedback.completed`,{title:i[n]})),n===`stop`&&tt(null),await(t.onReconcileStatus??t.onRefresh)?.();return}let s=await Ke({actionKind:`goal.lifecycle`,context:{kind:`goal_directory`,goal_id:e.goalId},idempotencyKey:`workspace-goal-${n}-${e.goalId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,operation:n,reason:r[n]},summary:i[n]},{select:n!==`stop`});if(s.goalId!==e.goalId||s.lifecycleOperation!==n)throw h(null),Error(l(`actionReview.targetChanged`));n===`stop`&&(s.reviewPlan?.interaction===`direct`?(o=!0,await Qe(s,{lifecycleProjection:a??void 0,presentation:`feedback`})):(a&&t.onGoalActivationStateChange?.(a.goalId,a.previous),re(s.gate?l(`feedback.gateRequired`,{summary:s.gate.summary}):l(`feedback.notCompleted`,{status:s.status})),h({item:s,kind:`proposal`})))}catch(e){a&&!o&&t.onGoalActivationStateChange?.(a.goalId,a.previous),re(l(`feedback.executionFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{n===`stop`&&(Ce.current.delete(e.goalId),I(new Set(Ce.current)))}}function Ye(e,t){je(l(t?e===`heartbeat`?`composer.heartbeatTemplate`:`composer.monitorTemplate`:e===`heartbeat`?`composer.heartbeatTemplateWithoutGoal`:`composer.monitorTemplateWithoutGoal`)),h(null),window.requestAnimationFrame(()=>be.current?.focus())}async function Xe(e,n,r=``){let i=await t.onRequestScheduleConfig?.(e,n);if(i){le(e=>e.includes(i.previewId)?e:[...e,i.previewId]),x(e=>({...e,[i.previewId]:i})),h({item:i,kind:`proposal`});return}if(!n){je(l(e===`heartbeat`?`composer.heartbeatGoalQuestion`:`composer.monitorGoalQuestion`));return}let a=Date.now().toString(36);await Ke({actionKind:e===`heartbeat`?`heartbeat.bind`:`monitor.create`,context:{kind:`schedule`,goal_id:n},idempotencyKey:`workspace-${e}-${n}-${a}`,normalizedParameters:e===`heartbeat`?{agent_id:De,cadence:Mx(r),goal_id:n,stop_condition:Fx(r),timezone:`Asia/Shanghai`}:{agent_id:De,cadence:Mx(r),goal_id:n,stop_condition:Fx(r),target:Px(r,l),target_key:`goal-${n}`,timezone:`Asia/Shanghai`},summary:e===`heartbeat`?l(`proposal.summary.heartbeat`):l(`proposal.summary.monitor`,{target:Px(r,l)})})}async function Ze(e){if(!we.current.has(e.todoId)){we.current.add(e.todoId),L(new Set(we.current)),re(l(`feedback.preparingPreview`,{title:e.text}));try{await Ke({actionKind:`todo.update`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-${e.todoId}-complete-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,operation:`complete`,todo_id:e.todoId},summary:l(`tasks.markComplete`,{name:e.text})}),re(null)}catch(e){re(l(`feedback.previewFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{we.current.delete(e.todoId),L(new Set(we.current))}}}async function Qe(e,n={}){if(e.reviewPlan&&!e.reviewPlan.canApply)return;let i=n.presentation!==`feedback`,a=e.actionKind===`goal.lifecycle`&&e.goalId&&(e.lifecycleOperation===`stop`||e.lifecycleOperation===`resume`)?{goalId:e.goalId,next:e.lifecycleOperation===`stop`?`stopped`:`active`,optimisticApplied:!1,previous:r.goals.find(t=>t.goalId===e.goalId)?.activationState??(e.lifecycleOperation===`stop`?`active`:`stopped`)}:null,o=n.lifecycleProjection??a;re(l(`feedback.applying`,{title:e.title}));let s={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:`pending`,reason:`apply_pending`,canApply:!1}:void 0,status:`applying`};x(t=>({...t,[e.previewId]:s})),i&&h({item:s,kind:`proposal`}),o&&!o.optimisticApplied&&t.onGoalActivationStateChange?.(o.goalId,o.next);try{if(t.onApplyProposal){await t.onApplyProposal(e);let n={...e,status:`applied`};if(x(t=>({...t,[e.previewId]:n})),i&&h({item:n,kind:`proposal`}),re(l(`feedback.completed`,{title:e.title})),e.actionKind===`goal.lifecycle`){(e.lifecycleOperation===`stop`||e.lifecycleOperation===`delete`)&&tt(null),e.lifecycleOperation===`delete`&&e.goalId&&t.onGoalDeleted?.(e.goalId);let n=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>n?.()).catch(()=>void 0)}return}let n=await Nh(e.previewId);if(n.proposal.proposal_id!==e.previewId||n.proposal.action_kind!==e.actionKind||e.actionKind===`goal.lifecycle`&&(n.proposal.normalized_parameters.goal_id!==e.goalId||Ex(n.proposal)!==e.lifecycleOperation))throw new Th(l(`actionReview.targetChanged`),{error_code:`action_response_mismatch`});let r=Dx(n.proposal,l);if(x(t=>({...t,[e.previewId]:r})),i&&h({item:r,kind:`proposal`}),r.reviewPlan?.interaction!==`completed`){o&&t.onGoalActivationStateChange?.(o.goalId,o.previous),h({item:r,kind:`proposal`}),re(n.proposal.status===`stale`?l(`feedback.stale`):l(`actionReview.${r.reviewPlan.reason}`));return}if(re(l(`feedback.completed`,{title:r.title})),r.actionKind===`todo.create`&&await t.onRefresh?.(),r.actionKind===`goal.lifecycle`&&(r.lifecycleOperation===`stop`||r.lifecycleOperation===`delete`)&&tt(null),r.actionKind===`goal.lifecycle`&&r.lifecycleOperation===`delete`&&r.goalId&&t.onGoalDeleted?.(r.goalId),r.actionKind===`goal.lifecycle`){let e=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>e?.()).catch(()=>void 0)}}catch(n){if(o&&t.onGoalActivationStateChange?.(o.goalId,o.previous),n instanceof Th&&n.payload.error_code===`protected_action`){let r=n.payload.gate,i=r&&typeof r==`object`?r:{},a={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:`gated`,reason:`authority_gate`,canApply:!1}:void 0,gate:{kind:String(i.kind??`protected_action`),nextAction:typeof i.next_action==`string`?i.next_action:void 0,summary:String(i.summary??n.message)},status:`gated`};x(t=>({...t,[e.previewId]:a})),h({item:a,kind:`proposal`}),re(l(`feedback.gateRequired`,{summary:a.gate.summary})),e.actionKind===`goal.create`&&e.goalId&&(t.onRefresh?.(),tt(e.goalId));return}let r=n instanceof Th&&py(n.payload),i=n instanceof Th&&n.payload.error_code===`action_response_mismatch`,a={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:r?`refresh`:`repair`,reason:i?`readback_unverified`:r?`stale_proposal`:`apply_failed`,canApply:!1}:void 0,errorMessage:n instanceof Error?n.message:String(n),status:r?`stale`:`error`};x(t=>({...t,[e.previewId]:a})),h({item:a,kind:`proposal`}),re(l(`feedback.executionFailed`,{error:a.errorMessage}))}}let $e={...t,onOpenRunSession:async e=>{e.goalId!==R&&tt(e.goalId),C(`chat`),await t.onOpenRunSession?.(e),y(e),h(null)},onOpenGoal:e=>{tt(e);let n=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>n?.()).catch(()=>{re(l(`feedback.goalRefreshFailed`))})},onOpenGoalView:e=>{C(e),e===`chat`&&y(null),h(null)},onOpenOutput:e=>{e.goalId!==R&&tt(e.goalId),C(`files`),t.onOpenOutput?.(e)},onApplyProposal:Qe,onCancelProposal:async e=>{h(null),x(t=>{let n={...t};return delete n[e.previewId],n});try{t.onCancelProposal?.(e),t.onCancelProposal||await Ph(e.previewId)}catch(t){x(t=>({...t,[e.previewId]:e})),re(l(`feedback.cancelFailed`,{error:t instanceof Error?t.message:String(t)}))}},onTransitionProposal:async(e,t)=>{let n=Dx(await Fh(e.previewId,t),l);le(e=>e.includes(n.previewId)?e:[...e,n.previewId]),x(r=>{let i={...r};return t===`regenerate`&&delete i[e.previewId],i[n.previewId]=n,i}),h({item:n,kind:`proposal`})},onSelectWorkspaceCandidate:async(e,t)=>{e.sourceRequest&&(x(t=>{let n={...t};return delete n[e.previewId],n}),await Ke({...e.sourceRequest,idempotencyKey:`${e.sourceRequest.idempotencyKey}-${t}`,normalizedParameters:{...e.sourceRequest.normalizedParameters,workspace_ref:t}}))},onPreviewAction:Ke,onRequestScheduleConfig:(e,t)=>Ye(e,t),onOpenNotificationSettings:e=>h({goalId:e,kind:`settings`,tab:`lark`}),onFetchNotificationTargets:()=>ig(),onSetupGoalChannel:e=>og(e),onToggleGoalAutoNotify:e=>sg(e),onUpdateSchedule:async(e,t)=>{let n=Date.now().toString(36),r=e.scheduleKind===`heartbeat`;await Ke({actionKind:r?`heartbeat.bind`:`monitor.update`,context:{kind:`schedule`,goal_id:e.goalId},idempotencyKey:`workspace-monitor-${e.scheduleId}-${t}-${n}`,normalizedParameters:{agent_id:e.agentId??De,...!r&&t===`run_now`?{endpoint_id:De}:{},...t===`edit`?{cadence:`2h`,...r?{timezone:e.timezone??`Asia/Shanghai`}:{}}:{},goal_id:e.goalId,operation:t,...!r&&t===`run_now`&&e.sessionId?{session_id:e.sessionId}:{},...r?{}:{todo_id:e.scheduleId}},summary:t===`pause`?`暂停自动运行:${e.label}`:t===`resume`?`恢复自动运行:${e.label}`:t===`run_now`?`立即运行:${e.label}`:t===`stop`?`停止自动运行:${e.label}`:`编辑自动运行生命周期:${e.label}`})}},et=i?{onOpenGoal:$e.onOpenGoal,onOpenGoalView:$e.onOpenGoalView,onOpenOutput:$e.onOpenOutput}:$e;function tt(e){d(e),T(!1),D(!1),ee(!1),y(null),h(null),C(`tasks`),de(!1),t.onSelectGoal?.(e)}function nt(e){p(e),t.onSelectAgent?.(e)}function rt(e){pe(e),px(e)}async function it(n){let r=n?[]:j,i=(n??ke).trim()||(r.length?l(`composer.imageAnalysisPrompt`):``);if(!(!i||k)){n||(je(``),M([])),P(null),A(!0);try{if(r.length){R?S!==`chat`&&ee(!0):D(!0);let e=await t.onSendMessage?.(i,De,R,r);e&&await Ke(e);return}let n=Wy(i,{agents:e.map(e=>({agentId:e.agentId,label:e.label})),goalId:R,todos:(V?.agentTodos??[]).map(e=>({text:e.text,todoId:e.todoId}))});if(n.route===`clarify`){je(i);let e=l(`composer.clarifySingleAction`);n.missingFields.includes(`resume_when`)&&(e=l(`composer.clarifyDefer`)),re(e);return}if(n.actionKind===`goal.create`){let e=jx(i,l),t=Ox(e.title);await Ke({actionKind:`goal.create`,context:{kind:`manager`,goal_id:null,natural_language:i},idempotencyKey:`workspace-goal-intent-${t}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:De,completion_criteria:e.completionCriteria,execution_boundary:e.executionBoundary,goal_id:t,heartbeat:{cadence:Mx(i),enabled:n.normalizedParameters.heartbeat_enabled===!0,timezone:`Asia/Shanghai`},initial_todos:e.initialTodos,objective:e.objective,permission:e.permission,stop_condition:Fx(i),title:e.title,workspace_ref:`current`},summary:l(`proposal.summary.goalCreate`,{title:e.title})});return}if(R&&n.actionKind===`heartbeat.bind`){await Xe(`heartbeat`,R,i);return}if(R&&n.actionKind===`monitor.create`){let e=Nx(i,l);if(e){je(i),re(e);return}await Xe(`monitor`,R,i);return}let a=Ix(i,e);if(R&&a&&n.actionKind===`agent.bind`){await Ke({actionKind:`agent.bind`,context:{kind:`goal`,goal_id:R,natural_language:i},idempotencyKey:`workspace-agent-bind-${R}-${a.agentId}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:a.agentId,goal_id:R},summary:`将 ${a.label} 绑定到 ${V?.title??R}`});return}if(R&&n.actionKind===`todo.create`){if(n.normalizedParameters.start_execution===!0){await Ke({actionKind:`todo.create`,context:{kind:`goal`,goal_id:R,natural_language:i},idempotencyKey:`workspace-task-start-${R}-${Date.now().toString(36)}`,normalizedParameters:{endpoint_id:a?.agentId??De,goal_id:R,start_execution:!0,text:i},summary:`交给 Agent 执行:${i.slice(0,120)}`});return}let e=a?.agentId??(/(交给|分配给|让).{0,24}(agent|codex|claude|kiro|kimi)/iu.test(i)?De:null);await Ke({actionKind:`todo.create`,context:{kind:`goal`,goal_id:R,natural_language:i},idempotencyKey:`workspace-todo-create-${R}-${Date.now().toString(36)}`,normalizedParameters:{...e?{endpoint_id:e}:{},goal_id:R,text:Lx(i)},summary:`创建 Todo:${Lx(i)}`});return}let o=V?.agentTodos.find(e=>i.includes(e.todoId)||i.includes(e.text)),s=typeof n.normalizedParameters.operation==`string`?n.normalizedParameters.operation:null;if(R&&o&&n.actionKind===`todo.update`&&s){await Ke({actionKind:`todo.update`,context:{kind:`todo`,goal_id:R,todo_id:o.todoId,natural_language:i},idempotencyKey:`workspace-todo-update-${o.todoId}-${s}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:De,...s===`reassign`&&a?{endpoint_id:a.agentId}:{},...s===`block`?{note:i}:{},...s===`defer`&&typeof n.normalizedParameters.resume_when==`string`?{resume_when:n.normalizedParameters.resume_when}:{},goal_id:R,operation:s,todo_id:o.todoId},summary:`更新 Todo:${o.text}`});return}R?S!==`chat`&&ee(!0):D(!0);let c=await t.onSendMessage?.(i,De,R);c&&await Ke(c)}catch(e){n||(je(i),M(r));let t=e instanceof Error?e.message:l(`feedback.sendGenericError`);re(l(`feedback.sendFailed`,{error:t}))}finally{A(!1)}}}let at=e.find(e=>e.agentId===De)?.label??De,ot=!V&&ke.startsWith(l(`composer.createGoalDraftLead`)),st=Re.filter(e=>e.kind===`run`&&!!e.run.sessionId&&!!e.run.canInterrupt&&(e.run.status===`running`||e.run.status===`queued`)).length;async function ct(e){if(!e?.length)return;let t=Bx-j.length,n=Array.from(e).slice(0,Math.max(0,t)),r=n.find(e=>!Rx.has(e.type)),i=n.find(e=>e.size>zx);if(t<=0){P(l(`composer.imageCountError`,{count:Bx}));return}if(r){P(l(`composer.imageTypeError`));return}if(i){P(l(`composer.imageSizeError`,{size:zx/1024/1024}));return}try{let t=await Promise.all(n.map(e=>Vx(e,l)));M(e=>[...e,...t].slice(0,Bx)),P(e.length>n.length?l(`composer.imageCountError`,{count:Bx}):null)}catch(e){P(e instanceof Error?e.message:l(`composer.imageReadGenericError`))}finally{Se.current&&(Se.current.value=``)}}function lt(e){let t=Array.from(e.clipboardData.items).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).flatMap(e=>{let t=e.getAsFile();return t?[t]:[]});t.length&&(e.preventDefault(),ct(t))}async function ut(){let e=await qg();_e(e)}async function dt(){await Promise.all([ut(),t.onRefresh?.()])}async function ft(){if(!(!t.onRefresh||oe===`loading`)){se(`loading`);try{await t.onRefresh(),se(`done`)}catch{se(`error`)}window.setTimeout(()=>se(`idle`),1800)}}return Ie?(0,B.jsx)(lx,{focusGoalConnection:!!(m?.kind===`settings`&&m.goalId),goals:Ne,initialGoalId:m?.kind===`settings`?m.goalId??R:R,initialTab:m?.kind===`settings`?m.tab??`lark`:`lark`,onChanged:()=>void dt(),onClose:()=>h(null),onThemeChange:rt,theme:fe}):(0,B.jsx)(mx,{drawer:Ge?(0,B.jsx)($y,{agents:e,attentionHistory:r.attentionHistory??r.userTodos,onSelectAttention:e=>h({kind:`attention`,item:e}),callbacks:et,goalNotifications:r.goalNotifications??[],goals:Ne,inspectorExpanded:g,larkConnections:i?[]:ge,onClose:()=>{Ge.kind===`proposal`&&[`applied`,`rejected`].includes(Ge.item.status)&&(Ge.item.actionKind!==`heartbeat.bind`||Ge.item.status!==`applied`)&&x(e=>{let t={...e};return delete t[Ge.item.previewId],t}),_(!1),h(null)},onToggleInspectorSize:()=>_(e=>!e),readOnly:i,runs:Re.flatMap(e=>e.kind===`run`?[e.run]:[]),selection:Ge}):null,drawerMode:Ge?.kind===`todo`?g?`inspector-full`:`inspector`:`panel`,drawerOpen:Ge!==null,mobileSidebarOpen:ue,onCloseMobileSidebar:()=>de(!1),theme:fe,main:(0,B.jsxs)(`div`,{className:`personal-channel`,children:[(0,B.jsx)(wy,{agents:e,managerChatOpen:w,mobileNavigationOpen:ue,onOpenGoalCapabilities:V?()=>h({goalId:V.goalId,kind:`settings`,tab:`capabilities`}):void 0,onOpenGoalDetail:V&&!V.loadState?()=>h({item:V,kind:`goal`}):void 0,onRefresh:t.onRefresh?()=>void ft():void 0,onOpenNavigation:()=>de(!0),onOpenManagerChat:()=>{D(!1),T(!0)},onSelectGoalTab:e=>{C(e),e===`chat`&&(y(null),ee(!1))},onSelectAgent:nt,onReturnManagerHome:()=>{T(!1),D(!1),window.requestAnimationFrame(()=>xe.current?.scrollTo({behavior:`smooth`,top:0}))},selectedAgentId:De,refreshState:oe,readOnlySourceLabel:i?s?.activeSource.label:void 0,selectedGoal:V,selectedGoalTab:S}),(0,B.jsxs)(`div`,{className:`personal-channel-scroll`,ref:xe,children:[!V&&!w&&Te&&Te.done+Te.failed+Te.attention>0?(0,B.jsxs)(`section`,{className:`personal-digest-card`,"aria-label":l(`digest.away`),children:[(0,B.jsx)(`strong`,{children:l(`digest.away`)}),(0,B.jsxs)(`div`,{className:`personal-digest-stats`,children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`b`,{children:Te.done}),l(`digest.completed`)]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`b`,{children:Te.failed}),l(`digest.failed`)]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`b`,{children:Te.attention}),l(`digest.needsYou`)]})]})]}):null,!V&&!w?(0,B.jsxs)(`section`,{className:`personal-manager-greeting`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Zp,{size:20})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:l(`home.greeting`)}),(0,B.jsx)(`p`,{children:r.goals.some(e=>e.activationState===`active`&&e.loadState)?l(`startup.partial`):(0,B.jsxs)(B.Fragment,{children:[l(`home.waitingCount`,{count:Pe}),` `,l(`home.blockingSummary`,{count:Fe})]})})]})]}):null,V?.loadState?(0,B.jsx)(`section`,{className:`personal-manager-greeting`,role:`status`,"data-testid":`goal-status-loading`,children:(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:l(V.loadState===`error`?`startup.goalError`:`startup.goalLoading`)}),(0,B.jsx)(`p`,{children:l(V.loadError?`startup.error.${V.loadError}`:`startup.independent`)}),V.loadState===`error`?(0,B.jsx)(`button`,{className:`min-h-11 rounded-md border px-3 py-2 text-sm`,type:`button`,onClick:()=>void t.onRefresh?.(),children:l(`startup.retry`)}):null]})}):V&&S===`tasks`?(0,B.jsx)(Tb,{historyEnabled:!i,goal:V,items:Re,onDraftTaskFromMessage:i?void 0:e=>{je(`创建一个 Task:${hx(e)}`),re(l(`feedback.taskDraftCreated`)),window.requestAnimationFrame(()=>be.current?.focus())},onOpenChat:()=>C(`chat`),onQuickComplete:i?void 0:Ze,onSelect:h,quickCompletingTodoIds:ae,selectedTodoId:Ge?.kind===`todo`?Ge.item.todoId:null,userTodos:r.userTodos}):V&&S===`files`?(0,B.jsx)(yx,{items:Re.filter(e=>e.kind===`output`),onSelect:h,reportState:r.periodicReports}):!V&&!w?(0,B.jsx)(vx,{goals:Ne,onRetry:()=>void t.onRefresh?.(),onSelectGoal:tt,systemHealth:r.systemHealth}):V?(0,B.jsxs)(B.Fragment,{children:[V&&v?.goalId===V.goalId?(0,B.jsx)(xx,{onClose:()=>y(null),onOpenDetails:()=>h({item:v,kind:`run`}),run:v}):null,(0,B.jsx)(Iy,{items:ze,onSelect:h,selectedGoal:V})]}):(0,B.jsx)(Iy,{items:He,onSelect:h,selectedGoal:null})]}),(0,B.jsx)(`div`,{className:`personal-composer-wrap`,children:i?(0,B.jsxs)(`div`,{className:`personal-read-only-notice`,children:[(0,B.jsx)(`strong`,{children:l(`source.readOnlyNoticeTitle`)}),(0,B.jsx)(`span`,{children:l(`source.readOnlyNoticeDescription`)})]}):(0,B.jsxs)(B.Fragment,{children:[!V&&!w&&E&&Be.length?(0,B.jsx)(bx,{messages:Be,onClose:()=>D(!1),onOpenConversation:()=>{D(!1),T(!0)}}):null,V&&S!==`chat`&&O&&Ve.length?(0,B.jsx)(bx,{agentLabel:at,messages:Ve,onClose:()=>ee(!1),onDraftTask:S===`tasks`?e=>{je(`创建一个 Task:${hx(e)}`),re(l(`feedback.taskDraftCreated`)),window.requestAnimationFrame(()=>be.current?.focus())}:void 0,onOpenConversation:()=>{ee(!1),C(`chat`)},title:`${V.title} · ${at}`}):null,F?(0,B.jsxs)(`div`,{className:`personal-action-feedback`,role:`status`,children:[(0,B.jsx)(`span`,{children:F}),(0,B.jsx)(`button`,{"aria-label":l(`common.closeActionReceipt`),onClick:()=>re(null),type:`button`,children:(0,B.jsx)($m,{size:14})})]}):null,(0,B.jsx)(`p`,{className:`personal-composer-hint`,children:V?st>0?l(`composer.goalRunningHint`,{agent:at,count:st}):l(`composer.goalMessageHint`,{agent:at}):l(`composer.managerMessageHint`)}),V?(0,B.jsxs)(`div`,{className:`personal-quick-prompts`,children:[(0,B.jsxs)(`button`,{"aria-label":l(`composer.nextAction`),className:`is-draft`,onClick:()=>Me(l(`composer.nextActionPrompt`)),title:l(`composer.prepareDraft`),type:`button`,children:[(0,B.jsx)(Em,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.nextAction`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]}),(0,B.jsxs)(`button`,{className:`is-immediate`,disabled:k,onClick:()=>void it(l(`composer.agentProgressPrompt`)),title:l(`composer.immediate`),type:`button`,children:[(0,B.jsx)(Bm,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.agentProgress`)}),(0,B.jsx)(`em`,{className:`personal-prompt-badge`,children:l(`composer.immediate`)})]}),(0,B.jsxs)(`button`,{"aria-label":l(`composer.monitor`),className:`is-draft`,onClick:()=>Ye(`monitor`,R),title:l(`composer.monitorHint`),type:`button`,children:[(0,B.jsx)($p,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.monitor`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]})]}):(0,B.jsxs)(`div`,{className:`personal-quick-prompts`,children:[(0,B.jsxs)(`button`,{"aria-label":l(`composer.globalTasks`),className:`is-draft`,onClick:()=>Me(l(`composer.globalTasksPrompt`)),title:l(`composer.prepareDraft`),type:`button`,children:[(0,B.jsx)(Em,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.globalTasks`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]}),(0,B.jsxs)(`button`,{className:`is-immediate`,disabled:k,onClick:()=>void it(l(`composer.globalProgressPrompt`)),title:l(`composer.immediate`),type:`button`,children:[(0,B.jsx)(Bm,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.globalProgress`)}),(0,B.jsx)(`em`,{className:`personal-prompt-badge`,children:l(`composer.immediate`)})]}),(0,B.jsxs)(`button`,{"aria-label":l(`composer.createGoal`),className:`is-draft`,onClick:qe,title:l(`composer.createGoalHint`),type:`button`,children:[(0,B.jsx)(Pm,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.createGoal`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]})]}),ot?(0,B.jsxs)(`div`,{className:`personal-goal-draft-status`,role:`status`,children:[(0,B.jsx)(`strong`,{children:l(`composer.createGoalDraft`)}),(0,B.jsx)(`span`,{children:l(`composer.createGoalDraftDescription`)})]}):null,j.length?(0,B.jsx)(`div`,{className:`personal-composer-images`,"aria-label":l(`composer.imagesPending`),children:j.map(e=>(0,B.jsxs)(`figure`,{children:[(0,B.jsx)(`img`,{alt:e.name,src:e.dataUrl}),(0,B.jsx)(`button`,{"aria-label":l(`composer.sentImageAlt`,{name:e.name}),onClick:()=>M(t=>t.filter(t=>t.id!==e.id)),type:`button`,children:(0,B.jsx)($m,{size:13})})]},e.id))}):null,N?(0,B.jsx)(`p`,{className:`personal-composer-error`,role:`alert`,children:N}):null,(0,B.jsxs)(`div`,{className:`personal-channel-composer`,onDragOver:e=>{[...e.dataTransfer.items].some(e=>e.kind===`file`&&e.type.startsWith(`image/`))&&e.preventDefault()},onDrop:e=>{let t=[...e.dataTransfer.files].filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),ct(t))},children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:17}),e.find(e=>e.agentId===De)?.label??De]}),(0,B.jsx)(`button`,{"aria-label":l(`composer.addImage`),className:`personal-composer-attach`,disabled:k||j.length>=Bx,onClick:()=>Se.current?.click(),title:l(`composer.attachImageHint`),type:`button`,children:(0,B.jsx)(jm,{size:17})}),(0,B.jsx)(`input`,{accept:`image/png,image/jpeg,image/webp,image/gif`,"aria-label":l(`composer.imagePicker`),className:`personal-composer-file-input`,disabled:k||j.length>=Bx,multiple:!0,onChange:e=>void ct(e.target.files),ref:Se,type:`file`}),(0,B.jsx)(`textarea`,{"aria-label":l(`composer.sendMessage`),onChange:e=>je(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),it())},onPaste:lt,placeholder:V?l(`composer.goalPlaceholder`,{goal:V.title}):l(`composer.managerPlaceholder`),ref:be,rows:1,value:ke}),(0,B.jsx)(`button`,{"aria-label":l(ot?`composer.createGoal`:`composer.send`),disabled:!ke.trim()&&j.length===0||k,onClick:()=>void it(),title:l(ot?`composer.createGoalHint`:`composer.sendMessageHint`),type:`button`,children:(0,B.jsx)(Bm,{size:18})})]})]})})]}),sidebar:(0,B.jsx)(xb,{attentionCount:Pe,goals:Ne,goalArchiveLoadState:n,goalLifecycleOperations:t.onExecuteGoalLifecycle?[`stop`,`resume`]:void 0,lifecycleBusyGoalIds:ie,onRequestGoalCreate:i?void 0:qe,onRequestGoalLifecycle:i&&!t.onExecuteGoalLifecycle?void 0:(e,t)=>void Je(e,t),onRetryGoalArchive:t.onRetryGoalArchive||t.onRefresh?()=>void(t.onRetryGoalArchive??t.onRefresh)?.():void 0,onOpenSettings:i?void 0:()=>h({kind:`settings`}),onSelectGoal:tt,selectedGoalId:R,statusSourceControl:s},s?.activeSource.statusUrl??`/status.json`)})}function Ux(e){return(e??``).replace(/\s+/gu,` `).trim()}function Wx(e,t=120){let n=Array.from(e);return n.length<=t?e:`${n.slice(0,t-1).join(``)}…`}function Gx(e,t,n){let r=Ux(e);return!r||r===`暂无`?n?t(n):``:/refresh-state|latest_run|latest run-derived/iu.test(r)?t(`projection.refreshState`):/first read-only adapter tick|read-only adapter/iu.test(r)?t(`projection.firstReadOnlyAdapterCheck`):/todo update recorded for/iu.test(r)?t(`projection.todoStatusUpdated`):/^(loopx|python3|npm|git|run)\s|\s--[a-z0-9-]+|\b[a-z]+_[a-z_]+\b/iu.test(r)?t(n??`projection.agentPreparingNextStep`):Wx(r)}function Kx(e,t){return t({advancing:`projection.agentAdvancingGoal`,idle:`projection.agentIdle`,needs_you:`projection.agentNeedsDecision`,stopped:`projection.agentStopped`,waiting_external:`projection.agentWaitingExternal`}[e])}function qx({eventCount:e,hasArtifact:t,hasLatestValidation:n},r){return{label:r(n?`projection.latestValidation`:`projection.latestRun`),metadata:e>0?r(`projection.events24h`,{count:e}):r(t?`projection.runEvidenceAvailable`:`projection.publicSafeProjection`)}}var Jx=`/status.json`,Yx=`loopx-status-source-catalog-v1`,Xx={id:`local`,kind:`local`,label:`本机`,readOnly:!1,statusUrl:Jx};function Zx(e,t){let n=ih(e,t).source;if(!n||!n.isLoopback||n.isRelative)return{error:`SSH 隧道来源必须使用显式的 localhost、127.0.0.1 或 ::1 URL。`};let r=new URL(n.url,t);return[`http:`,`https:`].includes(r.protocol)?{url:r.toString()}:{error:`状态来源只支持 HTTP 或 HTTPS。`}}function Qx(e){let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619);return`ssh-${(t>>>0).toString(36)}`}function $x(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;if(n.kind!==`ssh_tunnel`||typeof n.label!=`string`||typeof n.statusUrl!=`string`)return null;let r=n.label.trim(),i=Zx(n.statusUrl,t);if(!r||r.length>48||!(`url`in i))return null;let a=db(n.hostAlias)?n.hostAlias.trim():void 0;return{...a?{hostAlias:a}:{},id:Qx(i.url),kind:`ssh_tunnel`,label:r,readOnly:!0,statusUrl:i.url}}function eS(){return{schemaVersion:1,sources:[Xx]}}function tS(e,t){try{let n=e.getItem(Yx);if(!n)return eS();let r=JSON.parse(n);if(r.schemaVersion!==1||!Array.isArray(r.sources))return eS();let i=new Set([Xx.statusUrl]);return{schemaVersion:1,sources:[Xx,...r.sources.flatMap(e=>{let n=$x(e,t);return!n||i.has(n.statusUrl)?[]:(i.add(n.statusUrl),[n])})]}}catch{return eS()}}function nS(e,t){e.setItem(Yx,JSON.stringify({schemaVersion:1,sources:t.sources.filter(e=>e.kind===`ssh_tunnel`)}))}function rS(e,t){let n=new Set(t.filter(db).map(e=>e.trim())),r=!1,i=e.sources.map(e=>e.kind!==`ssh_tunnel`||e.hostAlias||!n.has(e.label)?e:(r=!0,{...e,hostAlias:e.label}));return r?{...e,sources:i}:e}function iS(e,t,n){let r=t.label.trim();if(!r)return{error:`请填写来源名称。`};if(r.length>48)return{error:`来源名称不能超过 48 个字符。`};let i=Zx(t.statusUrl,n);if(!(`url`in i))return i;if(e.sources.some(e=>e.statusUrl===i.url))return{error:`这个状态 URL 已经在来源目录中。`};if(t.hostAlias!==void 0&&!db(t.hostAlias))return{error:`请选择有效的 SSH Host。`};let a=t.hostAlias?.trim(),o={...a?{hostAlias:a}:{},id:Qx(i.url),kind:`ssh_tunnel`,label:r,readOnly:!0,statusUrl:i.url};return{catalog:{...e,sources:[...e.sources,o]},source:o}}function aS(e,t){return{...e,sources:e.sources.filter(e=>e.kind===`local`||e.id!==t)}}function oS(e,t,n){if(!t.trim()||ih(t,n).source?.isRelative)return Xx;let r=t.trim();try{r=new URL(r,n).toString()}catch{return null}return e.sources.find(e=>e.statusUrl===r)??null}function sS(e,t,n){return oS(e,t,n)||(ih(t,n).source?.isRelative?Xx:{id:`temporary`,kind:`ssh_tunnel`,label:`临时来源`,readOnly:!0,statusUrl:t.trim()})}function cS(e,t,n,r){return sS(e,t??n,r)}var lS={delete:`删除`,deploy:`部署`,merge:`合并`,payment:`付款`,release:`发布`};function uS(e,t,n){let r=t.replace(/\s+/gu,` `).trim().toLowerCase(),i=n.target.replace(/\s+/gu,` `).trim().toLowerCase();return!i||!r.includes(i)?null:{actionKind:`goal.update`,context:{goal_id:e,kind:`goal`,natural_language:t,semantic_proposal:{operation:n.operation,target:n.target}},idempotencyKey:`workspace-semantic-protected-${e}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e,status:`operator_gate_requested`},summary:`请求受保护操作:${lS[n.operation]} · ${n.target}`}}var dS=Jx;async function fS(e){let t=await fetch(e,{cache:`no-store`,signal:AbortSignal.timeout(3e4)});if(!t.ok)throw Error(`HTTP ${t.status} while loading ${e}`);return Ep(await t.json())}function pS(e,t){if(t?.controller_readiness?.decision_advisor_ready||t?.controller_readiness?.write_controller_ready)return`controller_ready`;if(t?.controller_readiness)return`controller_gated`;if(t?.human_reward)return`reward_judged`;if(t?.operator_gate?.decision===`approve`)return`operator_approved`;if(t?.operator_gate)return`operator_gated`;let n=e||t?.classification||``;return n===`connected_without_run`?`connected`:n===`read_only_project_map`||t?.project_map?`mapped`:n===`state_refreshed`?`refreshed`:n&&n!==`no_status`?`adapter_inspected`:`registered`}function mS(e,t){let n=new Map(t.map(e=>[e.goal_id,e])),r=new Set,i=e.map(e=>{r.add(e.id);let t=n.get(e.id),i=e.latest_runs[0],a=t?.lifecycle_phase??e.lifecycle_phase??i?.lifecycle_phase??pS(t?.status??i?.classification??e.status,i),o=t?.lifecycle_flags?.length?t.lifecycle_flags:e.lifecycle_flags?.length?e.lifecycle_flags:i?.lifecycle_flags?.length?i.lifecycle_flags:[a];return{goal:e,queueItem:t,latestRun:i,status:t?.status??i?.classification??e.status??`no_status`,waitingOn:t?.waiting_on??`clear`,severity:t?.severity??`clear`,lifecyclePhase:a,lifecycleFlags:o}});for(let e of t)r.has(e.goal_id)||i.push({goal:{activation_state:e.activation_state,id:e.goal_id,status:e.status,display_name:e.goal_id,latest_runs:[],lifecycle_flags:[e.lifecycle_phase??`registered`],registry_member:!0,legacy_runtime_goal:!1,index_exists:!1,raw_index_records:0,unique_runs:0},queueItem:e,status:e.status,waitingOn:e.waiting_on,severity:e.severity,lifecyclePhase:e.lifecycle_phase??`registered`,lifecycleFlags:e.lifecycle_flags??[`registered`]});return i}function hS(e){return(e??``).replace(/\s+/g,` `).trim()}function gS(e,t=132){let n=hS(e);return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function _S(e){let t=new Map;for(let n of e?.goals??[])t.set(n.goal_id,n);return t}function vS(e,t){return e===void 0||t===void 0?void 0:e+t}function yS(e,t){if(!e)return null;let n=t===`user`?e.queueItem?.project_asset?.user_todos:e.queueItem?.project_asset?.agent_todos;if(n?.items?.length)return{done_count:n.done??n.items.filter(e=>e.done).length,items:n.items,open_count:n.open??n.items.filter(e=>!e.done).length,total_count:n.total??n.items.length};let r=t===`user`?e.queueItem?.user_todos:e.queueItem?.agent_todos;return r?.items?.length?r:null}function bS(e){return e?.items.find(e=>!e.done)}function xS(e,t,n=`todos`){return e?.items?.length?{advancement_done_count:e.advancement_done_count??t?.advancement_done_count,done_count:e.done??e.items.filter(e=>e.done).length,items:e.items,open_count:e.open??e.items.filter(e=>!e.done).length,total_count:e.total??e.items.length}:t??null}function SS(e){return e?.queueItem?.project_asset?.quota?.state??e?.queueItem?.quota?.state??e?.goal.quota?.state??`waiting`}function CS(e,t,n){let r=[];for(let t of e){let e=yS(t,`agent`);for(let n of e?.items??[])r.push({goalId:t.goal.id,role:`agent`,todo:n})}let i=new Map;for(let e of r){let t=e.todo.claimed_by||`codex`,n=i.get(t)??[];n.push(e),i.set(t,n)}let a=new Map((n?.agents??[]).map(e=>[e.agent_id,e]));return Array.from(new Set([...i.keys(),...a.keys()])).map(e=>{let t=i.get(e)??[],n=a.get(e),r=Array.from(new Set([...t.map(e=>e.goalId),n?.current_todo?.goal_id,...n?.goal_ids??[]].filter(Boolean))),o=(t.filter(e=>!e.todo.done)[0]??t[0])?.goalId??n?.current_todo?.goal_id??r[0]??``,s=n?.last_activity_at??null;return{agentId:e,claimedTodos:t,currentTodo:n?.current_todo??null,evidenceRefs:[],goalIds:r,handoffNote:null,lastActivity:s,nextSafeAction:n?.next_action?.trim()||`Inspect status projection before taking work`,primaryGoalId:o,quotaHints:[],staleClaimHint:null,status:{label:`可用`,summary:`正常运行`,variant:`success`},workspaceRef:null}})}function wS(e){return e?.map(e=>({dataUrl:e.data_url,id:e.id,mimeType:e.mime_type,name:e.name,size:e.size}))}var TS=`loopx.personal-agent-selection.v1`;function ES(){if(typeof window>`u`)return{};try{let e=JSON.parse(window.localStorage.getItem(TS)??`{}`);return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(e=>typeof e[0]==`string`&&typeof e[1]==`string`))}catch{return{}}}var DS={需修复:`danger`,等你:`warning`,等待条件:`info`,推进中:`success`,安静运行:`neutral`,已停止:`neutral`,已完成:`neutral`};function OS(e,t){return hS(t)||e.replace(/^loopx[-_]/i,`LoopX `).split(/[-_]+/).filter(Boolean).map((e,t)=>t===0?`${e.slice(0,1).toUpperCase()}${e.slice(1)}`:e).join(` `)}function kS(e){return e.split(/\r?\n/u).filter(e=>!/^\s*GOAL_(STATUS|PROGRESS)\s*:/u.test(e)).map(e=>/^\s*GOAL_EVIDENCE\s*:/u.test(e)?e.replace(/^\s*GOAL_EVIDENCE\s*:/u,`验证依据:`):/^\s*NEXT_ACTION\s*:/u.test(e)?e.replace(/^\s*NEXT_ACTION\s*:/u,`下一步:`):e).join(` +`).trim()}function AS(e,t){return[`agent`,`assistant`].includes(e.trim().toLowerCase())&&t.trim().length>0}var jS=`已发现的项目 Agent`;function MS(e){switch(cy(e)){case`codex`:return`Codex`;case`claude`:return`Claude Code`;case`kiro`:return`Kiro CLI`;case`trae`:return`Trae CLI Agent`;case`coco`:return`Coco Agent`;default:return OS(e)}}function NS(e,t){switch(ly(e,t)){case`codex`:return`代码与项目执行`;case`claude`:return`复杂分析与长任务`;case`openai`:case`anthropic`:return`管家问答 · 无工具`;case`kiro`:return`终端编码 · 原生 /goal 循环`;case`trae`:return`前端与交互实现`;case`coco`:return`通用任务`;default:return jS}}function PS(e,t){let n=e.project_asset;return t===`user`?xS(n?.user_todos,e.user_todos,`project_asset.user_todos`):xS(n?.agent_todos,e.agent_todos,`project_asset.agent_todos`)}function FS(e){return gS(e.title??e.text,112)}function IS(e){let t=e.resume_condition?.resume_receipt;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t.receipt_id;return typeof n==`string`&&n.trim()?n.trim():null}function LS(e,t){return{resumeWhen:e.resume_when??null,resumeReady:e.resume_ready??null,resumeReceiptId:IS(e),claimedBy:e.claimed_by??null,done:e.status!==`deferred`&&e.done,evidence:e.evidence?gS(e.evidence,96):null,index:e.index,priority:e.priority??null,status:e.status??null,taskClass:e.task_class??null,taskDomain:e.task_domain??null,text:FS(e),todoId:e.todo_id?.trim()||`${t.goal.id}:agent:${e.index}`}}function RS(e){let t=e.queueItem?.agent_todos,n=t?.items??e.queueItem?.project_asset?.agent_todos?.items??[],r=new Map(n.map(t=>[t.todo_id?.trim()||`${e.goal.id}:agent:${t.index}`,t]));for(let n of t?.deferred_items??[]){let t=n.todo_id?.trim()||`${e.goal.id}:agent:${n.index}`;r.has(t)||r.set(t,n)}return[...r.values()]}function zS(e){return RS(e).map(t=>LS(t,e))}function BS(e,t,n){let r=new Map;for(let n of e.todo_index?.items??[]){if(n.goal_id!==t.goal.id||n.role!==`agent`)continue;let e=LS(n,t);r.set(e.todoId,e)}for(let e of n)r.has(e.todoId)||r.set(e.todoId,e);let i=new Map;for(let e of r.values()){if(e.done||e.taskClass!==`advancement_task`)continue;let t=e.taskDomain?.trim();t&&i.set(t,(i.get(t)??0)+1)}return[...i].map(([e,t])=>({domain:e,matchingTodoCount:t}))}function VS(e,t){return{claimedBy:e.claimed_by??null,done:e.status===`done`||e.status===`completed`,index:-1,priority:e.priority??null,status:e.status??null,taskClass:e.task_class??null,text:gS(e.title,112),todoId:e.todo_id?.trim()||`${t.goal.id}:agent:${e.claimed_by??`unknown`}:current`}}function HS(e,t,n){let r=new Map(e.map(e=>[e.todoId,e]));for(let e of t){let t=e.currentTodo;if(!t||t.goal_id!==n.goal.id)continue;let i=VS(t,n);r.has(i.todoId)||r.set(i.todoId,i)}return[...r.values()]}function US(e){let t=e.queueItem?.project_asset?.agent_todos,n=e.queueItem?.agent_todos,r=RS(e),i=t?.advancement_done_count??n?.advancement_done_count??t?.done??n?.done_count??null,a=r.filter(e=>e.done&&e.status!==`deferred`).length,o=Math.max(i??0,a),s=new Set(r.map(e=>e.todo_id?.trim()).filter(e=>!!e)),c=(t?.recent_completed_advancement_items??[]).filter(e=>!e.todo_id?.trim()||!s.has(e.todo_id.trim())).map(t=>LS(t,e)),l=r.find(e=>!e.done);return{doneTodoCount:o,nextTodoText:hS(t?.next??``)||(l?hS(l.title??``)||hS(l.text??``):``)||null,recentCompleted:c}}function WS(e,t){let n=hS(e);return n?/\b(state_file|registry_goal|authority_sources|source_registry)\b|\b[a-z_]+\s+\d+\/\d+/i.test(n)?t(`projection.goalVerified`):Gx(n,t,`projection.validationRecorded`):``}function GS(e,t=4){if(e.length<=t)return e;let n=e.findIndex(e=>!e.done);if(n<0)return e.slice(-t);let r=Math.max(0,Math.min(n-2,e.length-t));return e.slice(r,r+t)}function KS(e,t,n){let r=t.queueItem?.project_asset?.latest_validation,i=t.latestRun,a=e.event_ledger_summary?.goals.find(e=>e.goal_id===t.goal.id);if(!r&&!i&&!a)return null;let o=[WS(r?.summary,n),Gx(i?.health_check,n),Gx(i?.recommended_action,n)].find(e=>e!==``&&e!==`暂无`)??n(`projection.runRecorded`),s=qx({eventCount:a?.events_24h??0,hasArtifact:!!(i?.json_exists||i?.markdown_exists),hasLatestValidation:!!r},n);return{generatedAt:r?.generated_at??i?.generated_at??a?.latest_event_at??``,label:s.label,metadata:s.metadata,runId:i?`${t.goal.id}:${i.generated_at}`:null,safePreview:[o,s.metadata].filter(Boolean).join(` +`),summary:o,todoId:t.queueItem?.project_asset?.agent_todos?.items.find(e=>!e.done)?.todo_id??null}}function qS(e){return[e.status,e.goal.status,e.latestRun?.classification,e.lifecyclePhase].filter(Boolean).some(e=>/(^|[_\s-])(done|complete|completed|finished|terminal|closed|success)([_\s-]|$)/i.test(e??``))}function JS(e,t){return e.global_registry?.findings?.find(e=>e.severity===`high`&&(e.goal_id===t.goal.id||e.goal_ids.includes(t.goal.id)))}function YS(e){return[e.status,e.goal.status,e.latestRun?.classification,e.lifecyclePhase].filter(Boolean).some(e=>/(^|[_\s-])(failure|failed|error|broken|unhealthy|blocked[_\s-]?health|health[_\s-]?blocked)([_\s-]|$)/i.test(e??``))}function XS(e,t){let n=t.queueItem?.stale_latest_run_warning;return t.severity===`high`||!!JS(e,t)||!!(n?.requires_refresh_state||n?.severity===`high`)||YS(t)}function ZS(e,t){let n=JS(e,t);return t.queueItem?.stale_latest_run_warning?.recommended_action??t.queueItem?.stale_latest_run_warning?.reason??n?.recommended_action??n?.message??t.queueItem?.recommended_action??t.latestRun?.recommended_action??null}function QS(e){let t=e.latestRun?.operator_gate,n=t?.decision?.trim().toLowerCase()??``,r=new Set([`approve`,`approved`,`reject`,`rejected`,`defer`,`deferred`,`cancel`,`cancelled`]),i=[e.queueItem?.recommended_action,e.latestRun?.recommended_action].filter(Boolean).join(` `),a=/(?:等待|需要)(?:用户|你|owner).{0,24}(?:批准|确认|授权|补充|选择|决定)|(?:批准|确认|授权).{0,16}(?:后|才能|方可)/i.test(i);return!!(t&&!r.has(n))||e.lifecyclePhase===`operator_gated`&&!r.has(n)||a}function $S(e,t){let n=e.latestRun?.operator_gate;return Gx(n?.operator_question??n?.reason_summary??n?.follow_up??e.queueItem?.recommended_action??e.latestRun?.recommended_action,t,`projection.confirmAgentDecision`)}function eC(e,t){if(t.goal.activation_state===`stopped`)return`已停止`;let n=yS(t,`user`),r=yS(t,`agent`),i=!!bS(n),a=!!bS(r);return[`user_or_controller`,`controller`].includes(t.waitingOn)||i||QS(t)?`等你`:XS(e,t)?`需修复`:t.waitingOn===`external_evidence`?`等待条件`:SS(t)===`eligible`||a?`推进中`:qS(t)?`已完成`:`安静运行`}function tC(e,t,n,r){if(n===`已停止`)return Kx(`stopped`,r);if(n===`需修复`)return Gx(ZS(e,t),r,`projection.statusRefreshNeeded`);if(n===`等你`)return Kx(`needs_you`,r);if(n===`推进中`){let e=[(yS(t,`agent`)?.items??[]).filter(e=>!e.done).flatMap(e=>[e.title,e.text]).map(e=>hS(e)).find(e=>e!==``&&e!==`暂无`),t.queueItem?.recommended_action,t.latestRun?.recommended_action].map(e=>hS(e)).find(e=>e!==``&&e!==`暂无`);return e?Gx(e,r,`projection.agentAdvancingGoal`):Kx(`advancing`,r)}return Kx(n===`等待条件`?`waiting_external`:`idle`,r)}function nC(e,t){return t.some(t=>e.includes(t))}function rC(e,t,n){if(t.goals.some(e=>e.activationState===`active`&&e.loadState))return{text:`Goal 状态尚未全部加载,暂不能给出完整统计。可先打开已加载的 Goal,失败项可重试。`,lines:[]};if(nC(n,[`Agent`,`agent`,`推进`,`在做`])){let e=t.goals.filter(e=>![`安静运行`,`已完成`,`已停止`].includes(e.state)),n=(e.length>0?e:t.goals).slice(0,3);return n.length===0?{text:`当前状态里还没有 Goal 可供汇总。`,lines:[]}:{text:e.length>0?`Agent 当前关注这些 Goal:`:`当前 Goal 都比较安静:`,lines:n.map(e=>`${e.title} · ${e.state} · ${e.agentSentence}`)}}if(nC(n,[`现在`,`下一步`,`我该`,`该做什么`,`优先处理`])){let e=t.userTodos[0];if(e)return{text:e.blocking?`先处理「${OS(e.goalId)}」:${e.text}`:`当前最先处理「${OS(e.goalId)}」:${e.text}`,lines:[]};let n=t.goals.find(e=>e.state===`需修复`);if(n)return{text:`没有待办,但这个 Goal 需要先修复。`,lines:[`${n.title} · ${n.agentSentence}`]};let r=t.goals.find(e=>e.state===`推进中`);return r?{text:`目前不需要你介入,Agent 正在推进。`,lines:[`${r.title} · ${r.agentSentence}`]}:{text:`当前系统很安静,没有需要你立即处理的事项。`,lines:[]}}if(nC(n,[`等我`,`阻塞`,`需要我`,`全局待办`]))return t.userTodos.length===0?{text:`目前没有 Goal 在等你,开放用户待办为 0。`,lines:[]}:{text:`有 ${t.userTodos.length} 项开放用户待办,阻塞项优先:`,lines:t.userTodos.slice(0,3).map(e=>`${OS(e.goalId)} · ${e.blocking?`阻塞`:`待处理`} · ${e.text}`)};if(nC(n,[`状态`,`异常`,`修复`,`健康`])){let n=t.systemHealth?!t.systemHealth.ok:!e.ok||!e.contract?.ok||!e.global_registry?.ok||(e.global_registry?.summary?.high??0)>0,r=t.goals.filter(e=>e.state===`需修复`),i=r.slice(0,n?2:3).map(e=>`${e.title} · ${e.agentSentence}`);return n&&i.push(`全局状态、契约或注册表健康检查未通过,请进入管理页检查。`),i.length===0?{text:`当前没有发现 Goal 级或全局健康异常。`,lines:[]}:{text:r.length>0?`当前需要关注这些健康问题:`:`Goal 状态正常,但全局健康需要检查:`,lines:i}}return{text:`当前管家支持三类问题:下一步、等待你的事项、Agent 与健康状态。`,lines:[`问“我现在该做什么?”`,`问“哪些 Goal 在等我?”`,`问“Agent 在做什么?”或当前健康状态`]}}function iC(e,t,n,r=!1){let i=new Map(t.map(e=>[e.goal.id,e])),a=new Set(e.run_history.goals.filter(e=>e.activation_state===`stopped`).map(e=>e.id)),o=_S(e.usage_summary),s=CS(t,e.todo_index,e.agent_management_projection),c=e.attention_queue.items.flatMap((e,t)=>{if(a.has(e.goal_id))return[];let n=[`user_or_controller`,`controller`].includes(e.waiting_on);return(PS(e,`user`)?.items??[]).map((r,i)=>({projectedDone:r.done,details:Ud(r),actionKind:r.action_kind??null,blocking:n,goalId:e.goal_id,sourceOrder:t,taskClass:r.task_class??null,text:FS(r),todoId:r.todo_id?.trim()||`${e.goal_id}:user:${r.index}`,todoOrder:i,updatedAt:r.updated_at??null}))}),l=c.filter(e=>!e.projectedDone),u=new Set(l.map(e=>e.goalId)),d=t.flatMap((t,r)=>a.has(t.goal.id)||u.has(t.goal.id)||!QS(t)?[]:[{details:Ud({task_class:`user_gate`,status:`open`,note:t.latestRun?.operator_gate?.reason_summary}),actionKind:`gate.resolve`,blocking:!0,goalId:t.goal.id,sourceOrder:e.attention_queue.items.length+r,taskClass:`user_gate`,text:$S(t,n),todoId:`${t.goal.id}:operator-gate`,todoOrder:0,updatedAt:t.latestRun?.operator_gate?.recorded_at??t.latestRun?.generated_at??null}]),f=[...l,...d].sort((e,t)=>Number(t.blocking)-Number(e.blocking)||e.sourceOrder-t.sourceOrder||e.todoOrder-t.todoOrder),p=e.run_history.goals.flatMap(t=>{if(t.registry_member===!1)return[];let a=i.get(t.id);if(!a)return[];let c=eC(e,a),l=f.find(e=>e.goalId===t.id),u=l?.text??null,d=US(a),p=t.coordination?.registered_agents??[],m=new Set(p),h=[...s.filter(e=>e.goalIds.includes(t.id)&&!/unassigned|unknown/i.test(e.agentId)&&(m.size===0||m.has(e.agentId))&&(e.currentTodo?.goal_id===t.id||e.claimedTodos.some(e=>e.goalId===t.id)))].sort((e,t)=>(t.lastActivity??``).localeCompare(e.lastActivity??``)),g=new Set(h.map(e=>e.agentId)),_=[...h.map(e=>({agentId:e.agentId,label:e.agentId,lastActivityAt:e.lastActivity,state:e.status.label})),...p.filter(e=>!g.has(e)).map(e=>({agentId:e,label:e,lastActivityAt:null,state:`registered`}))],v=h[0],y=HS(zS(a),h,a),b=[d.nextTodoText,a.queueItem?.recommended_action,a.latestRun?.recommended_action,tC(e,a,c,n)].map(e=>Gx(e,n)).find(e=>e!==``&&e!==`暂无`)??n(`projection.nextUpdatePending`);return[{activationState:t.activation_state,agentId:v?.agentId??p[0]??`codex`,agentLaneCount:_.length,agentLanes:_,agentLabel:v?.agentId,agentSentence:tC(e,a,c,n),agentTodos:[...y,...d.recentCompleted],doneTodoCount:d.doneTodoCount,acceptanceObservation:t.acceptance_observation,goalId:t.id,latestActivity:a.latestRun?.generated_at??``,needsYou:u,needsYouActionKind:l?.actionKind??null,needsYouBlocking:l?.blocking??!1,needsYouTaskClass:l?.taskClass??null,needsYouTodoId:l?.todoId??null,nextSentence:b,runEvidence:KS(e,a,n),state:c,...r?{subagentExecution:{allowedDomains:t.spawn_policy?.allowed_domains??[],domainCandidates:BS(e,a,y),enabled:t.spawn_policy?.mode===`multi_subagent`&&t.spawn_policy.spawn_allowed===!0&&t.spawn_policy.max_children>0,maxChildren:t.spawn_policy?.max_children??0,modelConfig:t.spawn_policy?.model_config}}:{},title:OS(t.id,t.display_name),usage:(()=>{let e=o.get(t.id);return e?{costUsd24h:e.cost_usd_24h,costUsd7d:e.cost_usd_7d,durationMs24h:e.duration_ms_24h,durationMs7d:e.duration_ms_7d,tokens24h:vS(e.input_tokens_24h,e.output_tokens_24h),tokens7d:vS(e.input_tokens_7d,e.output_tokens_7d)}:null})()}]}),m=[];if(e.ok||m.push(`状态载荷未标记为正常 (payload.ok === false)`),e.contract&&!e.contract.ok){let t=e.contract.summary,n=t?`${t.errors} 项错误 / ${t.warnings} 项警告`:e.contract.errors?.[0]||`请检查控制面契约`;m.push(`契约检查未通过: ${n}`)}if(e.global_registry){e.global_registry.ok||m.push(`注册表状态异常: ${e.global_registry.summary.high} 项高危`);for(let t of e.global_registry.findings||[])t.severity===`high`&&m.push(`[${t.kind}] ${t.message}`)}let h=e.decision_freshness_summary?.summary?.stale_count?`${e.decision_freshness_summary.summary.stale_count} 项决策状态已过期`:null,g=m.length===0&&!h,_={ok:g,summary:g?`所有控制面契约与注册表检查均正常`:`发现 ${m.length+ +!!h} 项系统健康关注点`,issues:m,freshnessWarning:h};return{blockingTodoCount:f.filter(e=>e.blocking).length,goalNotifications:(e.goal_channel_notification_projection?.goals??[]).map(e=>({goalId:e.goal_id,configured:e.configured,enabled:e.enabled,humanGateAutoNotifyEnabled:e.human_gate_auto_notify_enabled,lastNotifiedAt:e.last_notified_at??null,receiptCount:e.receipt_count,targetRef:e.target_ref??null})),goals:p,openUserTodoCount:f.length,systemHealth:_,attentionHistory:[...c,...d],userTodos:f,visibleUserTodos:f.slice(0,5),workers:(e.agent_management_projection?.agents??[]).map(e=>({agentId:e.agent_id,currentTodoGoalId:e.current_todo?.goal_id??null,currentTodoText:e.current_todo?.title?gS(e.current_todo.title,96):null,lastActivityAt:e.last_activity_at??null,state:e.state??null}))}}function aC({goalArchiveLoadState:e,isLoading:t,onGoalActivationStateChange:n,onGoalDeleted:r,onSelectGoal:i,onReconcileStatus:a,onRefresh:o,onRetryGoalArchive:s,payload:c,progress:l,rows:u,selectedGoalId:d,statusSourceControl:f,theme:p,toggleTheme:m}){let h=f.activeSource.readOnly,g=f.activeSource.kind===`ssh_tunnel`?f.activeSource.hostAlias:void 0,{t:_}=Ji(),[v,y]=(0,z.useState)([]),[b,x]=(0,z.useState)(!1),S=(0,z.useMemo)(()=>{let e=iC(c,u,_,b);if(!l)return e;let t=Object.values(l.snapshots).map(e=>iC(e,mS(e.run_history.goals,e.attention_queue.items),_,b)),n=new Map(t.flatMap(e=>e.goals).map(e=>[e.goalId,e])),r=e.goals.map(e=>n.get(e.goalId)??{...e,loadError:l.errors[e.goalId],loadState:l.errors[e.goalId]?`error`:`loading`,agentId:``,agentSentence:``,nextSentence:``,subagentExecution:void 0}),i=t.flatMap(e=>e.userTodos),a=r.some(e=>e.activationState===`active`&&e.loadState),o=[...new Set(t.flatMap(e=>e.systemHealth?.issues??[]))];return{...e,goals:r,userTodos:i,attentionHistory:t.flatMap(e=>e.attentionHistory??e.userTodos),visibleUserTodos:i.slice(0,5),openUserTodoCount:i.length,blockingTodoCount:i.filter(e=>e.blocking).length,workers:[...new Map(t.flatMap(e=>e.workers??[]).map(e=>[e.agentId,e])).values()],goalNotifications:t.flatMap(e=>e.goalNotifications??[]),systemHealth:a||t.length===0?void 0:{ok:t.every(e=>e.systemHealth?.ok),issues:o,summary:o.length?`发现 ${o.length} 项系统健康关注点`:`状态检查已完成`,freshnessWarning:t.map(e=>e.systemHealth?.freshnessWarning).filter(Boolean).join(`;`)||null}}},[c,u,l,b,_]),C=S.goals.find(e=>e.goalId===d)??null,w=l?.snapshots[d]??c,[T,E]=(0,z.useState)(null),[D,O]=(0,z.useState)(null),[ee,te]=(0,z.useState)(!1),ne=S.goals.some(e=>e.activationState===`active`&&e.loadState===`loading`)?`loading`:S.goals.map(e=>`${e.goalId}:${e.agentId}`).join(`|`),k=C?.goalId??`manager`;S.goals.some(e=>e.activationState===`active`&&e.loadState)||(S.systemHealth?!S.systemHealth.ok:!c.ok)||S.openUserTodoCount>0&&`${S.openUserTodoCount}${S.blockingTodoCount}`;let A=v.length>0?v.map(e=>({agentId:e.agent_id,adapterKind:e.adapter_kind,available:e.available,capability:NS(e.agent_id,e.adapter_kind),interrupt:e.interrupt,label:e.display_name,location:e.location,resume:e.resume,source:e.source,statusLabel:e.available?`可用`:`需要配置`,streaming:e.streaming,toolCalls:e.tool_calls,trustScope:e.trust_scope})):[{agentId:`codex`,available:!0,capability:NS(`codex`),label:`Codex`,statusLabel:`正在检测`}],j=[...A,{agentId:`status-only`,available:!0,capability:`不调用模型`,adapterKind:`status_projection`,interrupt:!1,label:`仅查状态`,resume:!0,statusLabel:`只读`,streaming:!1,toolCalls:!1,trustScope:`read_only`}],M=A.find(e=>e.label===`Codex`&&e.available)?.agentId??A.find(e=>e.available)?.agentId??`status-only`,[N,P]=(0,z.useState)(ES),F=uh(j,N[k]??M,M),[re,ie]=(0,z.useState)(!1),[I,ae]=(0,z.useState)(!1),[L,oe]=(0,z.useState)(`chat`),[se,ce]=(0,z.useState)(``),[le,ue]=(0,z.useState)({}),[de,fe]=(0,z.useState)({}),[pe,me]=(0,z.useState)(null),[he,ge]=(0,z.useState)({}),[_e,ve]=(0,z.useState)([]),[ye,be]=(0,z.useState)(null),[xe,Se]=(0,z.useState)({}),Ce=(0,z.useRef)(1),we=(0,z.useRef)(1),Te=(0,z.useRef)(new Map),Ee=(0,z.useRef)(new Set),R=(0,z.useRef)(new Map),De=(0,z.useRef)(new Map),Oe=(0,z.useRef)(new Set),ke=(0,z.useRef)(new Set),Ae=(0,z.useRef)(null),je=(0,z.useRef)(null),Me=(0,z.useRef)(null),Ne=(0,z.useRef)(null);(0,z.useRef)(null);let Pe=le[k]??[];de[k];let Fe=C?S.userTodos.filter(e=>e.goalId===C.goalId):S.userTodos,V=C?.agentTodos??[];GS(V,C?.needsYou?3:4);let Ie=V.filter(e=>e.done).length,Le=V.length>0?`${Ie}/${V.length}`:`暂无计划`;C&&({...S},Fe.filter(e=>e.blocking).length,Fe.length),(0,z.useEffect)(()=>{let e=rh(f.activeSource.statusUrl,window.location.href),t=e.source?sh(w,e.source):null;if(!C||!t?.indexUrl||!t.detailUrl){E(null),O(null),te(!1);return}let{detailUrl:n,indexUrl:r}=t,i=!1;return E(null),O(null),te(!0),ch(r,C.goalId).then(async e=>{let t=e.items[0]?.detail_ref;return t?lh(n,t):null}).then(e=>{i||E(e)}).catch(e=>{i||O(Dp(e))}).finally(()=>{i||te(!1)}),()=>{i=!0}},[w,C?.goalId,f.activeSource.statusUrl]);let Re=C?void 0:he[k]?.sessionId;(0,z.useEffect)(()=>{if(h||!Re)return;let e=!1,t,n=async()=>{try{let t=await Bh(Re);if(e)return;let n=t.messages.filter(e=>e.origin===`manager_followup`);ue(e=>{let t=e[k]??[],r=new Set(t.map(e=>e.sourceMessageId)),i=n.filter(e=>!r.has(e.message_id));return i.length?{...e,[k]:[...t,...i.map(e=>({id:Ce.current++,sourceMessageId:e.message_id,role:`assistant`,agentLabel:F.label,sourceLabel:`管家交接回执`,text:kS(e.text),lines:[]}))]}:e})}catch{}finally{e||(t=setTimeout(n,3e3))}};return n(),()=>{e=!0,t&&clearTimeout(t)}},[h,Re,k,F.label]);function ze(e,t){ge(n=>{if(t===null){let t={...n};return delete t[e],t}return{...n,[e]:t}})}(0,z.useEffect)(()=>{if(h){y([]),x(!1);return}let e=!1;return Lh().then(t=>{e||(y(t.adapters??[]),x(t.goal_subagent_configuration===`preview_locked`))}).catch(()=>{e||x(!1)}),()=>{e=!0}},[h]),(0,z.useEffect)(()=>{try{window.localStorage.setItem(TS,JSON.stringify(N))}catch{}},[N]),(0,z.useEffect)(()=>{if(h||!F.available)return;let e=k,t=`${e}:${F.agentId}`,n=C?`goal`:`manager`,r=C?`goal.${C.goalId}`:`manager`,i=!1,a=null,o=null;return(async()=>{try{let s=await Uh({agentId:F.agentId,channelId:r,goalId:C?.goalId});if(i||(ue(t=>(t[e]?.length??0)>0?t:{...t,[e]:s.messages.map(e=>({sourceMessageId:e.message_id,agentLabel:e.role===`user`?void 0:F.label,attachments:wS(e.attachments),id:Ce.current++,lines:[],role:e.role===`user`?`user`:`assistant`,sourceLabel:e.role===`user`?void 0:e.role===`error`?`本地会话记录`:`恢复的 ${F.label} 会话`,text:e.role===`user`?e.text:kS(e.text)}))}),F.agentId===`status-only`))return;let c=s.sessions[0];if(o=c?.session_id??null,c&&!c.resumable){Ee.current.add(t),ze(e,{agentId:F.agentId,resumable:!1,sessionId:c.session_id,status:`resume_failed`});return}let l=n===`manager`?``:C?.goalId??``;if(n===`goal`&&!l)return;let u=await zh(l,F.agentId,`resume_latest`,n);if(i)return;Te.current.set(t,u.session_id);let d=s.snapshots.find(e=>e.session.session_id===u.session_id),f=d?.session.active_turn_id??``;if(ze(e,{agentId:F.agentId,resumable:!0,sessionId:u.session_id,status:f?`running`:`ready`,turnId:f||void 0}),Ee.current.delete(t),!f)return;let p=`${u.session_id}:${f}`;if(ke.current.has(p))return;ke.current.add(p),R.current.set(e,f),ze(e,{agentId:F.agentId,resumable:!0,sessionId:u.session_id,status:`running`,turnId:f}),me(e),a=new AbortController,De.current.set(e,a);let m=``,h=Be(e,{activity:[`正在恢复进行中的 Agent 回合`],agentLabel:F.label,lines:[],pending:!0,sourceLabel:`恢复的 ${F.label} 会话`,text:``});try{let t=await Xh(u.session_id,f,{signal:a.signal,onDelta:t=>{m+=t,Ve(e,h,{text:m})},onActivity:t=>{ue(n=>({...n,[e]:(n[e]??[]).map(e=>e.id===h?{...e,activity:[...new Set([...e.activity??[],t])].slice(-6)}:e)}))}});if(i)return;Ve(e,h,{lines:t.response.gate?[t.response.gate.summary,t.response.gate.next_action].filter(Boolean).slice(0,2):[],pending:!1,text:t.response.message||m.trim()||`${F.label} 已完成分析。`});let n=S.goals.find(e=>e.goalId===d?.session.goal_id)??C??S.goals[0]??null;if(n&&t.response.proposals.length>0){let r=t.response.proposals.map(e=>({goalId:n.goalId,id:we.current++,previewId:null,proposal:e,receiptLabel:null,state:`candidate`,statusMessage:null}));fe(t=>({...t,[e]:[...t[e]??[],...r]}))}}catch(t){if(i)return;Ve(e,h,{activity:[],lines:[],pending:!1,reconnect:t instanceof Th&&t.payload.reconnectable===!0,sourceLabel:`LoopX Chat 本地后端`,text:t instanceof Error?t.message:`无法恢复进行中的 Agent 回合。`})}finally{ke.current.delete(p),R.current.get(e)===f&&R.current.delete(e),ze(e,{agentId:F.agentId,resumable:!0,sessionId:u.session_id,status:`ready`}),De.current.get(e)===a&&De.current.delete(e),i||me(t=>t===e?null:t)}}catch(n){if(i)return;n instanceof Th&&n.payload.error_code===`resume_failed`&&(Ee.current.add(t),o&&ze(e,{agentId:F.agentId,resumable:!1,sessionId:o,status:`resume_failed`}))}})(),()=>{i=!0,a?.abort()}},[k,S.goals[0]?.goalId,h,C?.goalId,F.agentId,F.available,F.label]),(0,z.useEffect)(()=>{if(h||C||S.goals.length===0||ne===`loading`)return;let e=!1;return Promise.all(S.goals.filter(e=>!e.loadState).map(async e=>{let t=await Vh({agentId:e.agentId,channelId:`goal.${e.goalId}`,goalId:e.goalId});return{goalId:e.goalId,session:t.sessions[0]??null}})).then(t=>{e||ge(e=>{let n={...e};for(let e of t)e.session&&(n[e.goalId]={agentId:e.session.agent_id,resumable:e.session.resumable,sessionId:e.session.session_id,status:e.session.active_turn_id?`running`:e.session.status,turnId:e.session.active_turn_id??void 0});return n})}).catch(()=>{}),()=>{e=!0}},[h,ne,C?.goalId]),(0,z.useEffect)(()=>{if(be(null),h){ve([]),Se({});return}if(!C){ve([]),Se({});return}let e=!1,t=0,n=0;ve([]),Se({});let r=async()=>{if(!e){if(document.hidden){t=window.setTimeout(()=>void r(),1e4);return}try{let t=await Vh({goalId:C.goalId});if(!e){let r=t.sessions.filter(e=>e.channel_id?.startsWith(`task.`));ve(r);let i=await Promise.allSettled(r.map(e=>Bh(e.session_id)));if(!e){let e=i.some(e=>e.status===`rejected`);n=e?n+1:0,be(e?`partial`:null),Se(Object.fromEntries(i.flatMap((e,t)=>e.status===`fulfilled`?[[r[t].session_id,e.value]]:[])))}}}catch{n+=1,e||be(`offline`)}e||(t=window.setTimeout(()=>void r(),Math.min(3e4,2e3*2**Math.min(n,4))))}};return r(),()=>{e=!0,window.clearTimeout(t)}},[h,C?.goalId]),(0,z.useEffect)(()=>{if(!re)return;let e=window.requestAnimationFrame(()=>{Ae.current?.querySelector(`[role="menuitem"]:not(:disabled)`)?.focus()});return()=>{window.cancelAnimationFrame(e),je.current?.focus()}},[re]),(0,z.useEffect)(()=>{if(!I)return;let e=window.requestAnimationFrame(()=>Me.current?.focus());return()=>{window.cancelAnimationFrame(e),Ne.current?.focus()}},[I]),(0,z.useEffect)(()=>{if(!re&&!I)return;let e=e=>{e.key===`Escape`&&(ie(!1),ae(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[re,I]);function Be(e,t){let n=Ce.current++;return ue(r=>({...r,[e]:[...r[e]??[],{...t,id:n,role:`assistant`}]})),n}function Ve(e,t,n){ue(r=>({...r,[e]:(r[e]??[]).map(e=>e.id===t?{...e,...n}:e)}))}async function He(e,t){let n=e.trim();if(!n)return;let r=t&&`goalId`in t?t.goalId??`manager`:k,i=r===`manager`?null:S.goals.find(e=>e.goalId===r)??null,a=t?.agentId?uh(j,t.agentId,M):F,o=r===`manager`?S:i?{...S,blockingTodoCount:S.userTodos.filter(e=>e.goalId===i.goalId&&e.blocking).length,goals:[i],openUserTodoCount:S.userTodos.filter(e=>e.goalId===i.goalId).length,userTodos:S.userTodos.filter(e=>e.goalId===i.goalId),visibleUserTodos:S.userTodos.filter(e=>e.goalId===i.goalId)}:S,s=Ce.current++;if(ue(e=>({...e,[r]:[...e[r]??[],{attachments:t?.attachments,id:s,lines:[],role:`user`,text:n}]})),ce(``),me(r),a.agentId===`status-only`||!i&&r!==`manager`){let e=rC(w,o,n),t=a.agentId===`status-only`;Be(r,{agentLabel:t?`仅查状态`:`LoopX 管家`,lines:e.lines.slice(0,3),sourceLabel:t?`LoopX 状态投影 · 仅查状态`:`LoopX 状态投影`,text:e.text}),Rh({answer:[e.text,...e.lines.slice(0,3)].filter(Boolean).join(` +`),contextKind:r===`manager`?`manager`:`goal`,goalId:r===`manager`?void 0:r,question:n}).catch(()=>{}),me(null);return}let c=`${r}:${a.agentId}`,l=null;try{let e=Te.current.get(c);if(!e){let t=Ee.current.has(c)?`new`:`resume_latest`;e=(await zh(r===`manager`?``:i.goalId,a.agentId,t,r===`manager`?`manager`:`goal`)).session_id,Te.current.set(c,e),ze(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`ready`}),Ee.current.delete(c)}let o=``;l=Be(r,{activity:[`正在连接 Agent`],agentLabel:a.label,lines:[],pending:!0,sourceLabel:r===`manager`?`${a.label} 管家 · 跨 Goal`:`${a.label} Agent · ${OS(i.goalId)}`,text:``});let s=(await Jh(e,n,{attachments:t?.attachments,signal:(()=>{let e=new AbortController;return De.current.set(r,e),e.signal})(),onDelta:e=>{o+=e,l!==null&&Ve(r,l,{text:o})},onActivity:e=>{l!==null&&ue(t=>({...t,[r]:(t[r]??[]).map(t=>t.id===l?{...t,activity:[...new Set([...t.activity??[],e])].slice(-6)}:t)}))},onPhase:(t,n)=>{R.current.set(r,n),ze(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`running`,turnId:n})}})).response;if(Ve(r,l,{lines:s.gate?[s.gate.summary,s.gate.next_action].filter(Boolean).slice(0,2):[],pending:!1,text:kS(s.message||o.trim())||`${a.label} 已完成分析。`}),s.proposals.length>0&&!i&&Ve(r,l,{lines:[`请进入要修改的 Goal,预览并确认具体变更。`]}),s.proposals.length>0&&i){let e=s.proposals.map(e=>({goalId:i.goalId,id:we.current++,previewId:null,proposal:e,receiptLabel:null,state:`candidate`,statusMessage:null}));fe(t=>({...t,[r]:[...t[r]??[],...e]}))}if(r!==`manager`&&s.protected_action){let e=uS(r,n,s.protected_action);if(e)return e}}catch(e){if(Oe.current.delete(r)){let e={agentLabel:a.label,lines:[],pending:!1,sourceLabel:`${a.label} 会话`,text:`已中断。你可以在当前会话继续发送消息。`};l===null?Be(r,e):Ve(r,l,e);return}let t=e instanceof Th?e.payload:null;t&&dh(t)&&Te.current.delete(c),t?.error_code===`resume_failed`&&(Te.current.delete(c),Ee.current.add(c),ze(r,{agentId:a.agentId,resumable:!1,sessionId:he[r]?.sessionId??`resume-failed`,status:`resume_failed`}));let n=t?.gate,i=n&&typeof n==`object`?String(n.summary??``):``,o={agentLabel:a.label,lines:i?[i]:[],pending:!1,reconnect:t?.reconnectable===!0,sourceLabel:`LoopX Chat 本地后端`,text:t?.error_code===`resume_failed`?`原 ${a.label} 会话无法恢复。本地历史已经保留,请在运行详情里选择“重试恢复”或“开始新 Session”。`:e instanceof Error?e.message:`${a.label} 会话暂时不可用。`};l===null?Be(r,o):Ve(r,l,o)}finally{R.current.delete(r),De.current.delete(r);let e=Te.current.get(c);e&&ze(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`ready`}),me(e=>e===r?null:e)}}async function Ue(e){let t=e?.goalId??k,n=he[t],r=e?.agentId??n?.agentId??F.agentId,i=`${t}:${r}`,a=e?.sessionId??n?.sessionId??Te.current.get(i),o=e?.turnId??n?.turnId??R.current.get(t);if(!(!a||!o))try{Oe.current.add(t),await qh(a,o),De.current.get(t)?.abort()}catch(e){throw Oe.current.delete(t),e}finally{R.current.delete(t),ze(t,{agentId:r,resumable:!0,sessionId:a,status:`ready`}),De.current.delete(t),me(e=>e===t?null:e)}}async function We(e){let t=e.goalId,n=`${t}:${e.agentId}`,r=e.sessionId??he[t]?.sessionId??Te.current.get(n);if(r)try{let i=await Qh(r);Te.current.set(n,r),Ee.current.delete(n),ze(t,{agentId:e.agentId,resumable:i.session.resumable,sessionId:r,status:i.session.status})}catch{ze(t,{agentId:e.agentId,resumable:!1,sessionId:r,status:`resume_failed`})}}function Ge(e){let t=`${e.goalId}:${e.agentId}`;Te.current.delete(t),Ee.current.add(t),ze(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:`new-session-pending`,status:`ready`})}async function Ke(e){let t=`${e.goalId}:${e.agentId}`,n=e.sessionId??he[e.goalId]?.sessionId??Te.current.get(t);n&&n!==`new-session-pending`&&await Zh(n),Te.current.delete(t),Ee.current.add(t),ze(e.goalId,null)}function qe(e){j.some(t=>t.agentId===e&&t.available)&&(P(t=>({...t,[k]:e})),ie(!1))}function Je(){i(``),oe(`chat`)}function Ye(e){i(e),oe(`chat`)}C&&DS[C.state],C&&(`${F.label}${C.state}`,V.length>0&&`${Le}`,Fe.length>0&&`${Fe.length}`),C?.state===`需修复`||!C&&!c.ok?(C&&MS(C.agentId),C?.nextSentence,C?.agentSentence):C?.state===`等你`?(C.needsYouBlocking,C.needsYouBlocking,C.needsYou??C.nextSentence,C.needsYou):(C&&MS(C.agentId),C?.nextSentence);let Xe=[...!C&&he.manager?.status===`resume_failed`?[{id:`run:manager:resume-failed`,kind:`run`,run:{agentId:he.manager.agentId,agentLabel:MS(he.manager.agentId),canInterrupt:!1,completedSteps:0,goalId:`manager`,goalTitle:`LoopX 管家`,latestActivity:`本地聊天记录已保留,点我查看恢复方式。`,resumable:!1,runId:`manager:resume-failed`,sessionId:he.manager.sessionId,sessionStatus:`resume_failed`,status:`failed`,title:`上次会话需要恢复`,totalSteps:1,outputs:[]}}]:[],...C?_e.map(e=>{let t=e.channel_id?.startsWith(`task.`)?e.channel_id.slice(5):void 0,n=C.agentTodos.find(e=>e.todoId===t),r=!!e.active_turn_id,i=xe[e.session_id],a=i?.messages.some(e=>AS(e.role,e.text))===!0;return{id:`run:task:${e.session_id}`,kind:`run`,run:{agentId:e.agent_id,agentLabel:MS(e.agent_id),canInterrupt:r,completedSteps:n?.done||a?1:0,goalId:C.goalId,goalTitle:C.title,latestActivity:r?`Agent 正在执行,可进入 Session 查看过程或发送纠偏。`:a?`Agent 已返回结果,点击查看结果与完整运行记录。`:`执行 Session 已保留,可继续纠偏或恢复。`,resumable:e.resumable,runId:e.session_id,sessionId:e.session_id,sessionMessages:i?.messages.map(e=>({createdAt:e.created_at,messageId:e.message_id,role:e.role===`user`?`user`:AS(e.role,e.text)?`assistant`:`error`,text:e.role===`user`?e.text:kS(e.text)})),sessionStatus:a?`completed`:e.status,status:n?.done||a?`completed`:r?`running`:e.status===`resume_failed`?`failed`:`waiting`,title:n?.text??`Agent 执行任务`,todoId:t,totalSteps:1,turnId:e.active_turn_id??void 0}}}):[],...C?[{id:`run:${C.goalId}`,kind:`run`,run:{agentId:he[C.goalId]?.agentId??C.agentId,agentLabel:MS(he[C.goalId]?.agentId??C.agentId),canInterrupt:!!he[C.goalId]?.turnId,completedSteps:C.agentTodos.filter(e=>e.done).length,goalId:C.goalId,goalTitle:C.title,latestActivity:C.agentSentence,resumable:he[C.goalId]?.resumable??!0,runId:`goal:${C.goalId}`,sessionId:he[C.goalId]?.sessionId,sessionStatus:he[C.goalId]?.status,status:he[C.goalId]?.turnId?`running`:C.state===`需修复`?`failed`:`waiting`,title:C.nextSentence,totalSteps:C.agentTodos.length||1,turnId:he[C.goalId]?.turnId,outputs:C.runEvidence?[{createdAt:C.runEvidence.generatedAt,kind:`evidence`,outputId:`${C.goalId}:latest-evidence`,title:C.runEvidence.label}]:[]}}]:[],...Pe.map(e=>({id:`message:${e.id}`,kind:`message`,message:{agentLabel:e.agentLabel,attachments:e.attachments,id:String(e.id),pending:e.pending,role:e.role,text:e.text||(e.pending?`Agent 正在处理…`:e.lines.join(` +`))}})),...(C?[C]:S.goals).flatMap(e=>e.runEvidence?[{id:`output:${e.goalId}:${e.runEvidence.generatedAt||`latest`}`,kind:`output`,output:{agentLabel:MS(e.agentId),createdAt:e.runEvidence.generatedAt,goalId:e.goalId,goalTitle:e.title,kind:`evidence`,outputId:`${e.goalId}:latest-evidence`,runId:e.runEvidence.runId??void 0,safePreview:e.runEvidence.safePreview,summary:e.runEvidence.summary,title:e.runEvidence.label,todoId:e.runEvidence.todoId??void 0}}]:[]),...C&&T?[{id:`output:${C.goalId}:report:${T.publication.publication_id}`,kind:`output`,output:{agentId:T.agent_id,agentLabel:MS(T.agent_id),createdAt:T.publication.delivered_at,goalId:C.goalId,goalTitle:C.title,kind:`report`,outputId:T.publication.publication_id,report:{addedCount:T.delta.added_count,changedCount:T.delta.changed_count,deliveredAt:T.publication.delivered_at,generationId:T.generation_id,items:T.delta.items.map(e=>({changeKind:e.change_kind,previousStatus:e.previous_status,sourceRef:e.source_ref,status:e.status,summary:e.summary,title:e.title})),periodEndAt:T.period_window.end_at,periodStartAt:T.period_window.start_at,predecessorPublicationId:T.publication.predecessor_publication_id,publicationId:T.publication.publication_id},safePreview:T.delta.items.map(e=>`${e.change_kind===`added`?`+`:`~`} ${e.title}\n${e.summary}`).join(` + +`),summary:T.summary,title:T.title}}]:[]],Ze=f.connectionState===`connected`,Qe=new Map(S.goals.map(e=>[e.goalId,e.title])),$e=e=>Wd(e,f.activeSource.statusUrl,Ze&&!l?.errors[e.goalId],Qe.get(e.goalId)),et={...my(S),userTodos:S.userTodos.map($e),attentionHistory:(S.attentionHistory??S.userTodos).map($e),periodicReports:{error:D,loading:ee},timeline:Xe};return(0,B.jsxs)(`div`,{className:p===`dark`?`dark`:``,"data-testid":`personal-goal-home`,children:[ye?(0,B.jsx)(`p`,{role:`status`,className:`m-0 bg-amber-50 px-4 py-2 text-sm text-amber-900`,children:_(ye===`partial`?`runs.discoveryPartial`:`runs.discoveryOffline`)}):null,(0,B.jsx)(Hx,{agents:j.map(e=>({adapterKind:e.adapterKind,agentId:e.agentId,available:e.available,capability:e.capability,interrupt:e.interrupt,label:e.label,location:e.location,resume:e.resume,source:e.source,streaming:e.streaming,toolCalls:e.toolCalls,trustScope:e.trustScope,workspaceCompatibility:e.available?`当前 Goal 写入前验证`:`不可用,需先修复 Endpoint`})),callbacks:{onApplyAttention:e=>Ye(e.goalId),onCorrectRun:async(e,t)=>{if(!e.sessionId)throw Error(`这个 Run 还没有可纠偏的执行 Session。`);let n=await Nh((await Ah({actionKind:`run.correct`,context:{kind:`run`,goal_id:e.goalId,todo_id:e.todoId},idempotencyKey:`workspace-run-correct-${e.sessionId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,message:t,session_id:e.sessionId},summary:`纠偏执行任务:${e.title}`})).proposal_id),r=typeof n.turn?.turn_id==`string`?n.turn.turn_id:void 0;if(ze(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:e.sessionId,status:r?`running`:`ready`,turnId:r}),r){R.current.set(e.goalId,r);let t=new AbortController;De.current.set(e.goalId,t);let n=``,i=Be(e.goalId,{activity:[`正在把纠偏送入原执行 Session`],agentLabel:e.agentLabel,lines:[],pending:!0,sourceLabel:`${e.agentLabel} · 执行 Session`,text:``});try{let a=await Xh(e.sessionId,r,{signal:t.signal,onDelta:t=>{n+=t,Ve(e.goalId,i,{text:n})}});Ve(e.goalId,i,{activity:[],pending:!1,text:kS(a.response.message||n.trim())||`${e.agentLabel} 已完成纠偏。`})}catch(t){let n=Oe.current.delete(e.goalId);Ve(e.goalId,i,{activity:[],pending:!1,text:n?`已中断。你可以在当前会话继续发送消息。`:t instanceof Error?t.message:`纠偏回合失败。`})}finally{R.current.delete(e.goalId),De.current.delete(e.goalId),ze(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:e.sessionId,status:`ready`})}}},onCloseRunSession:Ke,onInterruptRun:async e=>Ue(e),onOpenGoal:Ye,onOpenRunSession:async e=>{if(!e.sessionId)return;let t=e.sessionId,n=await Bh(t);Se(e=>({...e,[t]:n})),Ye(e.goalId),ue(t=>({...t,[e.goalId]:n.messages.map(t=>({agentLabel:t.role===`user`?void 0:e.agentLabel,attachments:wS(t.attachments),id:Ce.current++,lines:[],role:t.role===`user`?`user`:`assistant`,sourceLabel:t.role===`user`?void 0:`${e.agentLabel} · 执行 Session`,text:t.role===`user`?t.text:kS(t.text)}))})),ze(e.goalId,{agentId:e.agentId,resumable:n.session.resumable,sessionId:t,status:n.session.active_turn_id?`running`:n.session.status,turnId:n.session.active_turn_id??void 0})},onOpenOutput:e=>Ye(e.goalId),...b?{onPreviewGoalSubagentConfiguration:async e=>{let t=await tg(e);return{changed:t.changed,configuration:{allowedDomains:t.after.orchestration.allowed_domains,enabled:t.feature_summary.multi_subagent===`enabled`,maxChildren:t.after.orchestration.max_children,modelConfig:t.after.orchestration.model_config},previewId:t.preview_id}},onApplyGoalSubagentConfiguration:async({previewId:e,...t})=>{let n=await ng(t,e);return{allowedDomains:n.after.orchestration.allowed_domains,enabled:n.feature_summary.multi_subagent===`enabled`,maxChildren:n.after.orchestration.max_children,modelConfig:n.after.orchestration.model_config}}}:{},...g?{onExecuteGoalLifecycle:async({goalId:e,operation:t,reason:n})=>{let r=await vb(g,e,t,n);return{activationState:r.activation_state,projectionVerified:r.projection_verified}}}:{},onGoalActivationStateChange:n,onGoalDeleted:r,onReconcileStatus:a,onRetryGoalArchive:s,onExportOutput:async e=>{let t=[`# ${e.title}`,``,e.summary??``,``,e.safePreview??`此产出没有可用的公开安全预览。`,``,`Goal: ${e.goalId}`,`Todo: ${e.todoId??`unlinked`}`,`Run: ${e.runId??`unlinked`}`].join(` +`),n=URL.createObjectURL(new Blob([t],{type:`text/markdown;charset=utf-8`})),r=document.createElement(`a`);r.href=n,r.download=`${e.outputId.replace(/[^a-z0-9._-]+/gi,`-`)}.md`,r.click(),URL.revokeObjectURL(n)},onRefresh:o,onRetryResumeRun:We,onSelectAgent:qe,onSelectGoal:e=>e?Ye(e):Je(),onSendMessage:async(e,t,n,r)=>He(e,{agentId:t,goalId:n,attachments:r}),onStartNewRunSession:Ge},goalArchiveLoadState:e,model:et,readOnly:h,selectedAgentId:F.agentId,selectedGoalId:C?.goalId??null,statusSourceControl:f})]})}function oC({error:e,isLoading:t,onRetry:n,requestedUrl:r,theme:i,toggleTheme:a}){let o=!!(e&&/failed to fetch|networkerror|load failed/i.test(e)&&r.includes(`status.json`));return(0,B.jsx)(`div`,{className:i===`dark`?`dark`:``,children:(0,B.jsxs)(`main`,{className:`min-h-screen bg-[#f6f7f9] text-slate-950 dark:bg-[#09090b] dark:text-zinc-50`,children:[(0,B.jsxs)(`header`,{className:`flex min-h-16 flex-wrap items-center justify-between gap-3 border-b border-slate-200 bg-white px-4 py-3 dark:border-zinc-800 dark:bg-zinc-950 sm:px-6`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`h1`,{className:`text-xl font-semibold`,children:`LoopX Workspace`}),(0,B.jsx)(`p`,{className:`mt-1 break-all text-sm text-slate-500 dark:text-zinc-400`,children:`Personal Workspace`})]}),(0,B.jsx)(ry,{"aria-label":`切换主题`,onClick:a,size:`icon`,variant:`secondary`,children:i===`dark`?(0,B.jsx)(Jm,{className:`h-4 w-4`}):(0,B.jsx)(km,{className:`h-4 w-4`})})]}),(0,B.jsxs)(`div`,{className:`grid min-h-[calc(100vh-80px)] sm:grid-cols-[240px_1fr]`,children:[(0,B.jsxs)(`aside`,{className:`hidden border-r border-slate-200 p-6 dark:border-zinc-800 sm:block`,"aria-label":`Workspace`,children:[(0,B.jsx)(`strong`,{children:`LoopX`}),(0,B.jsx)(`p`,{className:`mt-6 text-sm`,children:`Workspace`}),(0,B.jsx)(`p`,{className:`mt-8 text-xs text-slate-500`,children:`Goals`}),[1,2,3].map(e=>(0,B.jsx)(`div`,{className:`mt-4 h-8 rounded bg-slate-100 dark:bg-zinc-900`},e))]}),(0,B.jsx)(`div`,{className:`p-4 sm:p-8`,children:(0,B.jsx)(iy,{"data-testid":`initial-status-state`,children:(0,B.jsx)(ay,{className:`flex min-h-64 items-center justify-center p-6`,children:(0,B.jsxs)(`div`,{className:`max-w-xl text-center`,children:[e?(0,B.jsx)(im,{className:`mx-auto h-6 w-6 text-rose-600 dark:text-rose-300`}):(0,B.jsx)(Im,{className:`mx-auto h-6 w-6 animate-spin text-slate-500 dark:text-zinc-400`}),(0,B.jsx)(`p`,{className:`mt-3 text-sm font-medium`,children:e?`无法加载实时状态`:`正在加载实时状态`}),e?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`mt-2 break-words text-sm leading-6 text-slate-500 dark:text-zinc-400`,children:o?`本地状态服务暂时未连接。升级或启动期间可能短暂断开,请重试;仍失败时重新打开 LoopX App,或运行 loopx doctor。`:e}),o?(0,B.jsx)(`p`,{className:`mt-2 text-xs leading-5 text-slate-400 dark:text-zinc-500`,children:`重新加载不会执行任务,也不会改变 Goal 配置。`}):null,(0,B.jsx)(`div`,{className:`mt-4 flex flex-wrap justify-center gap-2`,children:(0,B.jsxs)(ry,{disabled:t,onClick:n,children:[(0,B.jsx)(Im,{className:`h-4 w-4`}),`重试`]})})]}):(0,B.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-500 dark:text-zinc-400`,role:`status`,children:`正在连接 Workspace,Goal 列表将先出现,详细状态会逐个补齐。 / Connecting to your Workspace. Goals load independently.`})]})})})})]})]})})}function sC(){let e=iw.useSearch(),t=iw.useNavigate(),[n,r]=(0,z.useState)(`light`),[i,a]=(0,z.useState)(null),o=(0,z.useRef)(null),s=(0,z.useRef)(e.goalId);s.current=e.goalId;let[c,l]=(0,z.useState)(Op),[u,d]=(0,z.useState)({kind:`example`,label:`bundled example`}),[f,p]=(0,z.useState)(()=>tS(window.localStorage,window.location.href)),m=(0,z.useRef)(f);m.current=f;let[h,g]=(0,z.useState)(e.statusUrl),[_,v]=(0,z.useState)(null),[y,b]=(0,z.useState)(!1),[x,S]=(0,z.useState)({error:null,phase:`idle`}),[C,w]=(0,z.useState)(e.statusUrl.trim()||null),[T,E]=(0,z.useState)(!1),D=(0,z.useRef)(null),O=(0,z.useRef)(Xg(e.statusUrl.trim()||null)),ee=!T&&u.kind===`example`?e.statusUrl.trim():``,te=C??ee,ne=u.kind===`url`?u.label:dS,k=!!(_&&C),A=cS(f,C,ne,window.location.href),j=u.kind===`example`&&!T,M=c.attention_queue,N=c.run_history,P=(0,z.useMemo)(()=>mS(N.goals,M.items),[N.goals,M.items]);function F(e,t,n=0){S({error:null,phase:`loading`}),fS(ah(e,`stopped`,window.location.href)).then(r=>{if(!e_(O.current,t))return;let i=r.goal_projection?.registry_revision??null,a=t.registryRevision!==null&&t.registryRevision!==void 0&&i!==null&&t.registryRevision!==i;if(l(e=>C_(e,r)),a&&n<1){I(e,{background:!0,resyncAttempt:n+1});return}S(a?{error:`Goal 状态在加载历史时发生变化,请重试。`,phase:`error`}:{error:null,phase:`ready`})}).catch(e=>{e_(O.current,t)&&S({error:Dp(e),phase:`error`})})}function re(){let e=u.kind===`url`?u.label:h||dS,t=Qg(O.current,e,{background:!0});if(i){I(e);return}t&&F(e,t)}async function ie(e,n,r){if(r.background)return l(e=>C_(e,n)),!0;let i={kind:`url`,label:e};return O.current.loadedUrl=e,l(n),d(i),g(e),await t({search:t=>({...t,statusUrl:e})}),$g(O.current,r)?(O.current.requestedUrl=null,w(null),!0):!1}async function I(e,t={}){let n=e.trim(),r=t.background===!0;if(!n){r||v(`状态地址不能为空`);return}let c=Qg(O.current,n,{background:r,selectionRevision:t.selectionRevision});if(!c)return;o.current?.abort();let d=new AbortController;o.current=d,r||(D.current=null,E(!1),w(n),b(!0),v(null),S({error:null,phase:`idle`}));try{let e=await jp(n,window.location.href).catch(()=>null);if(!e_(O.current,c))return;if(e){let o=t.retryOnly&&u.kind===`url`&&u.label===n&&i?.directory.registry_revision===e.registry_revision?i.snapshots:{};a({directory:e,snapshots:o,errors:{}});let f={...e,goals:e.goals.filter(e=>!o[e.id])},p=!1,m=Mp(e);if(r)l(m);else if(!await ie(n,m,c))return;if(S({error:null,phase:`loading`}),await Np(n,window.location.href,f,(e,t,n)=>{n===`revision`&&(p=!0),a(r=>r&&{...r,snapshots:t?{...r.snapshots,[e]:t}:r.snapshots,errors:n?{...r.errors,[e]:n}:r.errors})},()=>e_(O.current,c),()=>s.current,d.signal),p&&(t.resyncAttempt??0)<1&&e_(O.current,c)){await I(n,{resyncAttempt:1});return}e_(O.current,c)&&S({error:null,phase:`ready`});return}let o=await fS(ah(n,`active`,window.location.href));if(!e_(O.current,c)||(a(null),c.registryRevision=o.goal_projection?.registry_revision??null,!await ie(n,o,c)))return;if(o.goal_projection?.scope!==`active`||o.goal_projection.complete){S({error:null,phase:`ready`});return}F(n,c,t.resyncAttempt??0)}catch(e){if(!$g(O.current,c))return;r||v(Dp(e))}finally{!r&&$g(O.current,c)&&b(!1)}}function ae(e,t={}){o.current?.abort();let n=Zg(O.current,e.statusUrl);D.current=null,E(!1),w(e.statusUrl),b(!0),v(null),(async()=>{if(t.ensureTunnel&&e.kind===`ssh_tunnel`){let t=new URL(e.statusUrl,window.location.href).port;if(t)try{await _b(e.label,t)}catch{}}O.current.selectionRevision===n&&await I(e.statusUrl,{selectionRevision:n})})()}function L(e){m.current=e,p(e);try{nS(window.localStorage,e)}catch{}}let oe={activeSource:A,connectionState:y?`loading`:k?`error`:`connected`,errorMessage:k?`未切换到 ${C??`所选来源`}:${_}`:null,onAdd:e=>{let t=iS(f,e,window.location.href);return`error`in t?{error:t.error}:(L(t.catalog),ae(t.source,{ensureTunnel:e.ensureTunnel}),{})},onConfiguredHostsLoaded:e=>{let t=m.current,n=rS(t,e);n!==t&&L(n)},onRemove:e=>{L(aS(f,e)),A.id===e&&ae(Xx)},onSelect:e=>{let t=f.sources.find(t=>t.id===e);t&&ae(t,{ensureTunnel:t.kind===`ssh_tunnel`})},sources:A.id===`temporary`?[...f.sources,A]:f.sources};(0,z.useEffect)(()=>{let t=e.statusUrl.trim();if(t){if(D.current===t||C&&C!==t)return;(u.kind!==`url`||u.label!==t)&&I(t);return}D.current=null,!T&&(C||u.kind===`example`&&I(dS))},[T,C,e.statusUrl,u.kind,u.label]),(0,z.useEffect)(()=>{if(e.statusUrl&&u.kind===`example`)return;let n=new Set(P.map(e=>e.goal.id));if(P.length===0){e.goalId&&t({search:e=>({...e,goalId:``})});return}e.goalId&&!n.has(e.goalId)&&x.phase!==`loading`&&t({search:e=>({...e,goalId:``})})},[x.phase,P,t,e.goalId,e.statusUrl,u.kind]),(0,z.useEffect)(()=>{if(!i||y||!e.goalId||u.kind!==`url`)return;let t=i.directory.goals.find(t=>t.id===e.goalId);t?.activation_state===`stopped`&&!i.snapshots[t.id]&&!i.errors[t.id]&&I(u.label,{retryOnly:!0})},[e.goalId,y,i,u]);function se(e){t({search:t=>({...t,goalId:e})})}return j?(0,B.jsx)(oC,{error:_,isLoading:y,onRetry:()=>void I(te||dS),requestedUrl:te||dS,theme:n,toggleTheme:()=>r(n===`dark`?`light`:`dark`)}):(0,B.jsx)(aC,{goalArchiveLoadState:x,isLoading:y,onGoalActivationStateChange:(e,t)=>{O.current.projectionRevision+=1,l(n=>wp(n,e,t)),a(n=>n&&{...n,snapshots:Object.fromEntries(Object.entries(n.snapshots).map(([n,r])=>[n,wp(r,e,t)]))})},onGoalDeleted:e=>{O.current.projectionRevision+=1,l(t=>Tp(t,e)),a(t=>t&&{...t,snapshots:Object.fromEntries(Object.entries(t.snapshots).filter(([t])=>t!==e))})},onSelectGoal:se,onReconcileStatus:()=>I(u.kind===`url`?u.label:h||dS,{background:!0}),onRetryGoalArchive:re,onRefresh:()=>I(u.kind===`url`?u.label:h||dS,{retryOnly:!!(i&&Object.keys(i.errors).length)}),payload:c,progress:i,rows:P,selectedGoalId:e.goalId,statusSourceControl:oe,theme:n,toggleTheme:()=>r(n===`dark`?`light`:`dark`)})}var cC=O_(`inline-flex items-center gap-1 rounded-md border px-2 py-0.5 text-xs font-medium`,{variants:{variant:{neutral:`border-slate-200 bg-white text-slate-700 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-300`,success:`border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-200`,warning:`border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-200`,info:`border-sky-200 bg-sky-50 text-sky-800 dark:border-sky-900 dark:bg-sky-950 dark:text-sky-200`,danger:`border-rose-200 bg-rose-50 text-rose-800 dark:border-rose-900 dark:bg-rose-950 dark:text-rose-200`}},defaultVariants:{variant:`neutral`}});function lC({className:e,variant:t,...n}){return(0,B.jsx)(`span`,{className:ty(cC({variant:t}),e),...n})}var uC=[{label:`status payload`,source:`apps/presentation/dashboard/src/data/status.ts`,detail:`status_contract, attention_queue, local_dashboard_api, run_history`},{label:`channel projection`,source:`apps/presentation/dashboard/src/data/goal-channel-frontstage.ts`,detail:`decision_frame, todos, gates, leases, artifacts, truth_contract`},{label:`public showcase catalog`,source:`docs/showcases/showcase-catalog.json`,detail:`case metadata, visual hints, evidence boundaries, story beats`},{label:`route smoke`,source:`apps/presentation/dashboard/smoke/frontstage-route-smoke.ts`,detail:`static route contract, source guards, component expectations`}],dC=[{axis:`schema`,current:`goal_channel_projection_v0`,proposed:`new optional projection field`,gate:`parser default plus route smoke assertion`},{axis:`truth`,current:`event ledger and active state remain source of truth`,proposed:`derived UI state only`,gate:`truth_contract must stay read-only`},{axis:`privacy`,current:`compact source refs and warnings`,proposed:`public-safe fixture field`,gate:`loopx check and browser fake-private fixture`},{axis:`interaction`,current:`render, filter, select, inspect`,proposed:`no browser write by default`,gate:`write affordance requires explicit loopback capability`}],fC=[{title:`Fixture sources`,body:`Use examples/status.example.json, browser-smoke fixtures, and docs/showcases/showcase-catalog.json.`},{title:`Required proof`,body:`Every projection addition needs parser coverage, route smoke assertions, and one browser or bundle check when UI output changes.`},{title:`Never include`,body:`Raw task text, trajectories, transcripts, local paths, private registry state, credentials, or internal document links.`}],pC=[`npm --prefix apps/presentation/dashboard run smoke:frontstage-route`,`npm --prefix apps/presentation/dashboard run smoke:frontstage-browser`,`npm --prefix apps/presentation/dashboard run smoke:frontstage-share-bundle`,`npm --prefix apps/presentation/dashboard run build`,`loopx check --scan-path apps/presentation/dashboard --scan-path docs/status-data-contract.md`],mC=[{name:`Projection lane`,badges:[`read-only`,`schema v0`],body:`Summarizes one compact projection lane without mutating the underlying LoopX state.`},{name:`Capability badge`,badges:[`loopback`,`dry-run`],body:`Shows an advertised local capability only after the status feed declares it.`},{name:`Boundary warning`,badges:[`public-safe`,`omitted`],body:`Names omitted private material and points contributors back to compact source references.`}];function hC({children:e,icon:t,title:n}){return(0,B.jsxs)(`section`,{className:`rounded-lg border border-slate-200 bg-white shadow-sm`,children:[(0,B.jsx)(`div`,{className:`flex items-center justify-between gap-3 border-b border-slate-200 px-4 py-3`,children:(0,B.jsxs)(`h2`,{className:`flex items-center gap-2 text-sm font-semibold text-slate-950`,children:[(0,B.jsx)(t,{className:`h-4 w-4 text-slate-500`}),n]})}),e]})}function gC(){return(0,B.jsx)(hC,{icon:Qp,title:`Status Contract Explorer`,children:(0,B.jsx)(`div`,{className:`grid gap-3 p-4 lg:grid-cols-2`,"data-testid":`developer-contract-explorer`,children:uC.map(e=>(0,B.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-3`,children:[(0,B.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,B.jsx)(lC,{variant:`info`,children:e.label}),(0,B.jsx)(lC,{variant:`neutral`,children:`public contract`})]}),(0,B.jsx)(`div`,{className:`mt-2 break-words font-mono text-xs text-slate-700`,children:e.source}),(0,B.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:e.detail})]},e.label))})})}function _C(){return(0,B.jsx)(hC,{icon:vm,title:`Projection Diffing`,children:(0,B.jsx)(`div`,{className:`overflow-x-auto`,"data-testid":`developer-projection-diffing`,children:(0,B.jsxs)(`table`,{className:`min-w-full border-separate border-spacing-0 text-left text-sm`,children:[(0,B.jsx)(`thead`,{children:(0,B.jsxs)(`tr`,{className:`bg-slate-50 text-xs uppercase tracking-normal text-slate-500`,children:[(0,B.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Axis`}),(0,B.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Current`}),(0,B.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Proposed`}),(0,B.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Gate`})]})}),(0,B.jsx)(`tbody`,{children:dC.map(e=>(0,B.jsxs)(`tr`,{className:`align-top`,children:[(0,B.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 font-semibold text-slate-950`,children:e.axis}),(0,B.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 text-slate-600`,children:e.current}),(0,B.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 text-slate-600`,children:e.proposed}),(0,B.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 text-slate-600`,children:e.gate})]},e.axis))})]})})})}function vC(){return(0,B.jsx)(hC,{icon:mm,title:`Fixture Generation`,children:(0,B.jsx)(`div`,{className:`grid gap-3 p-4 md:grid-cols-3`,"data-testid":`developer-fixture-generation`,children:fC.map(e=>(0,B.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-3`,children:[(0,B.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:e.title}),(0,B.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:e.body})]},e.title))})})}function yC(){return(0,B.jsx)(hC,{icon:om,title:`Smoke Checklist`,children:(0,B.jsx)(`div`,{className:`space-y-2 p-4`,"data-testid":`developer-smoke-checklist`,children:pC.map(e=>(0,B.jsxs)(`div`,{className:`flex items-start gap-3 rounded-md border border-slate-200 bg-slate-50 px-3 py-2`,children:[(0,B.jsx)(Yp,{className:`mt-0.5 h-4 w-4 shrink-0 text-emerald-600`}),(0,B.jsx)(`code`,{className:`break-all text-xs font-semibold leading-5 text-slate-700`,children:e})]},e))})})}function bC(){return(0,B.jsx)(hC,{icon:sm,title:`Component Examples`,children:(0,B.jsx)(`div`,{className:`grid gap-3 p-4 lg:grid-cols-3`,"data-testid":`developer-component-examples`,children:mC.map(e=>(0,B.jsxs)(`article`,{className:`rounded-md border border-slate-200 bg-slate-50 p-3`,children:[(0,B.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:e.badges.map(e=>(0,B.jsx)(lC,{variant:e===`read-only`||e===`public-safe`?`success`:`neutral`,children:e},e))}),(0,B.jsx)(`h3`,{className:`mt-3 text-sm font-semibold leading-6 text-slate-950`,children:e.name}),(0,B.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:e.body})]},e.name))})})}function xC(){return(0,B.jsx)(`main`,{className:`min-h-screen bg-[#f7f7f4] px-4 py-4 text-slate-950 sm:px-5`,"data-testid":`frontstage-developer-cockpit`,children:(0,B.jsxs)(`div`,{className:`mx-auto grid max-w-[1500px] gap-4 xl:grid-cols-[260px_minmax(0,1fr)]`,children:[(0,B.jsxs)(`aside`,{className:`rounded-lg border border-slate-200 bg-white p-4 shadow-sm xl:sticky xl:top-4 xl:self-start`,children:[(0,B.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,B.jsx)(`div`,{className:`flex h-9 w-9 items-center justify-center rounded-md border border-slate-200 bg-slate-950 text-white`,children:(0,B.jsx)(Ym,{className:`h-4 w-4`})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`div`,{className:`text-sm font-semibold`,children:`Developer Cockpit`}),(0,B.jsx)(`div`,{className:`text-xs text-slate-500`,children:`Projection extension`})]})]}),(0,B.jsxs)(`div`,{className:`mt-4 grid gap-2`,children:[(0,B.jsxs)(`a`,{className:`flex items-center gap-2 rounded-md border border-slate-200 px-3 py-2 text-sm font-medium`,href:`https://huangruiteng.github.io/loopx/`,children:[(0,B.jsx)(xm,{className:`h-4 w-4`}),`LoopX home`]}),(0,B.jsxs)(`a`,{className:`flex items-center gap-2 rounded-md border border-slate-200 px-3 py-2 text-sm font-medium`,href:`https://huangruiteng.github.io/loopx/docs/showcases/index.en.html`,children:[(0,B.jsx)(fm,{className:`h-4 w-4`}),`Public cases`]}),(0,B.jsxs)(`a`,{className:`flex items-center gap-2 rounded-md bg-slate-950 px-3 py-2 text-sm font-medium text-white`,href:`/chat/developers/projections/`,children:[(0,B.jsx)(sm,{className:`h-4 w-4`}),`Developer cockpit`]})]}),(0,B.jsxs)(`div`,{className:`mt-5 space-y-2 rounded-md border border-emerald-200 bg-emerald-50 p-3 text-xs leading-5 text-emerald-950`,children:[(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,B.jsx)(lC,{variant:`success`,children:`read-only`}),(0,B.jsx)(lC,{variant:`neutral`,children:`public fixtures`})]}),(0,B.jsx)(`p`,{children:`This route uses static public contracts only; live status feeds, registry files, and browser write APIs stay outside the cockpit.`})]})]}),(0,B.jsxs)(`section`,{className:`space-y-4`,children:[(0,B.jsx)(`div`,{className:`rounded-lg border border-slate-200 bg-white px-5 py-5 shadow-sm`,children:(0,B.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-4`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,B.jsx)(lC,{variant:`info`,children:`developers/projections`}),(0,B.jsx)(lC,{variant:`success`,children:`public-safe`}),(0,B.jsx)(lC,{variant:`neutral`,children:`no browser writes`})]}),(0,B.jsx)(`h1`,{className:`mt-3 text-3xl font-semibold tracking-normal text-slate-950`,children:`LoopX Projection Developer Cockpit`}),(0,B.jsx)(`p`,{className:`mt-2 max-w-3xl text-sm leading-6 text-slate-600`,children:`A read-only contributor workbench for adding dashboard/frontstage projections without reverse-engineering the large operator page.`})]}),(0,B.jsxs)(`div`,{className:`grid min-w-[260px] gap-2 text-sm`,children:[(0,B.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-2`,children:[(0,B.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-normal text-slate-500`,children:`Source of truth`}),(0,B.jsx)(`div`,{className:`mt-1 font-semibold text-slate-950`,children:`status contract + compact fixtures`})]}),(0,B.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-2`,children:[(0,B.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-normal text-slate-500`,children:`Boundary`}),(0,B.jsx)(`div`,{className:`mt-1 font-semibold text-slate-950`,children:`read-only extension surface`})]})]})]})}),(0,B.jsxs)(`div`,{className:`grid gap-4 xl:grid-cols-2`,children:[(0,B.jsx)(gC,{}),(0,B.jsx)(_C,{})]}),(0,B.jsxs)(`div`,{className:`grid gap-4 xl:grid-cols-[minmax(0,1fr)_420px]`,children:[(0,B.jsx)(vC,{}),(0,B.jsx)(yC,{})]}),(0,B.jsx)(bC,{}),(0,B.jsx)(hC,{icon:Wm,title:`Extension Boundary`,children:(0,B.jsxs)(`div`,{className:`grid gap-3 p-4 md:grid-cols-3`,"data-testid":`developer-extension-boundary`,children:[(0,B.jsxs)(`div`,{className:`rounded-md border border-emerald-200 bg-emerald-50 px-3 py-3`,children:[(0,B.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:`Allowed`}),(0,B.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:`Versioned parser defaults, public fixtures, read-only route panels, and focused smoke assertions.`})]}),(0,B.jsxs)(`div`,{className:`rounded-md border border-amber-200 bg-amber-50 px-3 py-3`,children:[(0,B.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:`Review`}),(0,B.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:`New dashboard dependencies, status contract fields, loopback capability display, and browser-visible workflows.`})]}),(0,B.jsxs)(`div`,{className:`rounded-md border border-rose-200 bg-rose-50 px-3 py-3`,children:[(0,B.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:`Stop`}),(0,B.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:`Credentials, private registry material, raw logs, transcripts, production actions, or default browser write authority.`})]})]})})]})]})})}var SC=J({value:G().finite(),total:G().finite().positive().optional(),unit:W().optional(),higher_is_better:K()}).passthrough(),CC=gd(W(),G().finite()).default({}),wC=J({outcome_status:W().optional(),failure_class:W(),causal_summary:W(),expectedness:W(),implication:W(),next_probe:W(),confidence:W(),evidence_refs:q(W()).optional()}).passthrough(),TC=J({arm_id:W(),selected_run_id:W().nullable(),score_countable:K(),metrics:gd(W(),SC),effort:CC,insight:wC.nullable().optional()}),EC=J({run_id:W(),case_id:W(),arm_id:W(),arm_role:W(),status:W(),protocol_id:W(),runner_revision:W().optional(),observed_at:W(),metrics:gd(W(),SC),countability:J({integrity_qualified:K(),official_result_present:K(),score_countable:K()}).passthrough(),treatment_fidelity:W(),effort:CC,redacted_insight:wC.nullable().optional(),upload_provenance:J({producer_id:W(),producer_version:W(),observed_at:W(),source_revision:W()}).passthrough()}).passthrough(),DC=J({case_denominator:G().int().nonnegative(),value_sum:G().finite(),value_mean:G().finite().nullable(),value_median:G().finite().nullable(),value_min:G().finite().nullable(),value_max:G().finite().nullable(),case_macro_rate:G().finite().optional(),suite_micro_rate:G().finite().optional(),suite_micro_numerator:G().finite().optional(),suite_micro_denominator:G().finite().positive().optional()}).passthrough(),OC=J({arm_id:W(),arm_role:W(),factor_assignments:gd(W(),W()),protocol_counts:gd(W(),G().int().nonnegative()).default({}),runner_revision_counts:gd(W(),G().int().nonnegative()).default({}),orchestrator_runtime_counts:gd(W(),G().int().nonnegative()).default({}),intended_case_count:G().int().positive(),run_count:G().int().nonnegative(),terminal_run_count:G().int().nonnegative(),selected_score_countable_case_count:G().int().nonnegative(),coverage_rate:G().finite().min(0).max(1),metrics:gd(W(),DC),binary_outcomes:gd(W(),J({success_count:G().int().nonnegative(),case_denominator:G().int().nonnegative(),success_rate:G().finite().min(0).max(1).nullable()})),effort:gd(W(),J({denominator:G().int().nonnegative(),mean:G().finite().nullable(),median:G().finite().nullable()})),failure_class_counts:gd(W(),G().int().nonnegative())}).passthrough(),kC=J({baseline_value:G().finite(),candidate_value:G().finite(),delta:G().finite(),direction:Y([`improved`,`flat`,`regressed`]).optional()}).passthrough(),AC=J({comparison_id:W(),comparison_anchor_run_id:W(),candidate_run_id:W(),candidate_arm_id:W(),primary_metric:W(),matched_pair_countable:X(!0),metric_deltas:gd(W(),kC)}).passthrough(),jC=J({ok:X(!0),schema_version:X(`benchmark_study_dashboard_v0`),benchmark_id:W(),study_id:W(),status:Y([`complete`,`provisional`]),design:J({protocol_id:W(),comparison_protocol_id:W(),baseline_arm_id:W(),case_set:J({case_set_id:W(),case_ids:q(W())}),metric_catalog:q(J({metric_name:W(),role:Y([`primary`,`guardrail`,`supporting`]),unit:W().optional(),higher_is_better:K(),binary:K()})),labels:gd(W(),W())}).passthrough(),campaign:J({intended_case_count:G().int().positive(),intended_arm_count:G().int().positive(),intended_cell_denominator:G().int().positive(),selected_score_countable_cell_count:G().int().nonnegative(),selected_score_countable_coverage_rate:G().finite().min(0).max(1),complete_declared_design_case_count:G().int().nonnegative(),ambiguous_score_countable_cell_count:G().int().nonnegative(),in_flight_run_count:G().int().nonnegative(),matched_pair_countable_count:G().int().nonnegative(),factorial_contrast_count:G().int().nonnegative(),factorial_contrast_countable_count:G().int().nonnegative(),runtime_observation_count:G().int().nonnegative(),runtime_classification_counts:gd(W(),G().int().nonnegative())}),arms:q(OC),contrasts:gd(W(),J({matched_pair_denominator:G().int().nonnegative(),primary_metric_directions:J({improved:G().int().nonnegative(),flat:G().int().nonnegative(),regressed:G().int().nonnegative()}),binary_metric_transitions:gd(W(),J({"0_to_1":G().int().nonnegative(),"1_to_0":G().int().nonnegative(),same:G().int().nonnegative()}))})),cases:q(J({case_id:W(),complete_declared_design:K(),arms:q(TC),eligible_comparisons:q(AC),largest_eligible_primary_contrast:AC.nullable()})),runs:q(EC),authority:J({score_source:W(),matched_comparison_source:W(),factorial_comparison_source:W().nullable(),manifest_changes_scores:X(!1),dashboard_is_execution_authority:X(!1)}),public_boundary:J({raw_task_recorded:X(!1),raw_trajectory_recorded:X(!1),hidden_evaluation_recorded:X(!1),raw_verifier_output_recorded:X(!1),credentials_recorded:X(!1),local_paths_recorded:X(!1)}),write_performed:X(!1),network_access_performed:X(!1)});function MC(e){return jC.parse(e)}function NC(e,t){let n=new URL(t),r=new URL(e||`/benchmark-study.example.json`,n);if(!new Set([`http:`,`https:`]).has(r.protocol))throw Error(`Benchmark dashboard source must use HTTP or HTTPS`);if(r.origin!==n.origin)throw Error(`Benchmark dashboard source must use same-origin local readback`);return r.toString()}var PC=[{id:`campaign`,label:`Campaign`},{id:`arms`,label:`Arms`},{id:`cases`,label:`Cases`},{id:`runs`,label:`Runs`}];function FC(e){return e==null?`—`:`${(e*100).toFixed(e>=.995?0:1)}%`}function IC(e){return e==null?`—`:new Intl.NumberFormat(`en`,{maximumFractionDigits:2,notation:`compact`}).format(e)}function LC(e){if(e==null)return`—`;let t=e/6e4;return t>=120?`${(t/60).toFixed(1)} h`:`${IC(t)} min`}function RC(e){let t=Object.entries(e);return t.length?t.map(([e,t])=>`${e} (${t})`).join(`, `):`—`}function zC(e){if(!e)return`—`;let t=e.total==null?IC(e.value):`${IC(e.value)}/${IC(e.total)}`;return e.unit?`${t} ${e.unit}`:t}function BC(e,t){let n=e.metrics[t];return!n||n.case_denominator===0?`—`:n.suite_micro_rate==null?`${IC(n.value_mean)} mean`:`${FC(n.suite_micro_rate)} · ${IC(n.suite_micro_numerator)}/${IC(n.suite_micro_denominator)}`}function VC(e,t){let n=e.largest_eligible_primary_contrast,r=n?.metric_deltas[t];if(!n||!r)return null;let i=r.delta>0?`+`:``;return{direction:r.direction,text:`${n.candidate_arm_id}: ${i}${IC(r.delta)}`}}function HC({children:e,tone:t=`neutral`}){return(0,B.jsx)(`span`,{className:`benchmark-state benchmark-state-${t}`,children:e})}function UC({packet:e,primaryMetric:t}){return(0,B.jsxs)(`div`,{className:`benchmark-view-stack`,children:[(0,B.jsxs)(`section`,{"aria-labelledby":`arm-summary-title`,children:[(0,B.jsxs)(`div`,{className:`benchmark-section-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`p`,{className:`benchmark-kicker`,children:`ARM SUMMARY`}),(0,B.jsx)(`h2`,{id:`arm-summary-title`,children:`Comparable outcomes, denominator first`})]}),(0,B.jsx)(`p`,{children:`Only one score-countable run per declared case × arm cell is selected.`})]}),(0,B.jsx)(`div`,{className:`benchmark-arm-grid`,children:e.arms.map(e=>{let n=Object.values(e.binary_outcomes)[0];return(0,B.jsxs)(`article`,{className:`benchmark-arm-card`,children:[(0,B.jsxs)(`div`,{className:`benchmark-card-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`span`,{className:`benchmark-mono`,children:e.arm_role}),(0,B.jsx)(`h3`,{children:e.arm_id})]}),(0,B.jsx)(HC,{tone:e.coverage_rate===1?`success`:`warning`,children:e.coverage_rate===1?`Complete`:`Provisional`})]}),(0,B.jsxs)(`dl`,{className:`benchmark-stat-list`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`dt`,{children:[`Primary · `,t]}),(0,B.jsx)(`dd`,{children:BC(e,t)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Score-countable coverage`}),(0,B.jsxs)(`dd`,{children:[e.selected_score_countable_case_count,`/`,e.intended_case_count]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Binary success`}),(0,B.jsx)(`dd`,{children:n?`${n.success_count}/${n.case_denominator}`:`Not declared`})]})]})]},e.arm_id)})})]}),(0,B.jsxs)(`section`,{"aria-labelledby":`contrast-title`,children:[(0,B.jsxs)(`div`,{className:`benchmark-section-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`p`,{className:`benchmark-kicker`,children:`MATCHED CONTRASTS`}),(0,B.jsx)(`h2`,{id:`contrast-title`,children:`Direction counts on eligible pairs`})]}),(0,B.jsx)(`p`,{children:`Raw run volume is never used as a comparison denominator.`})]}),(0,B.jsx)(`div`,{className:`benchmark-table-shell`,children:(0,B.jsxs)(`table`,{children:[(0,B.jsx)(`thead`,{children:(0,B.jsxs)(`tr`,{children:[(0,B.jsx)(`th`,{children:`Candidate arm`}),(0,B.jsx)(`th`,{children:`Matched denominator`}),(0,B.jsx)(`th`,{children:`Improved`}),(0,B.jsx)(`th`,{children:`Flat`}),(0,B.jsx)(`th`,{children:`Regressed`}),(0,B.jsx)(`th`,{children:`Binary transitions`})]})}),(0,B.jsxs)(`tbody`,{children:[Object.entries(e.contrasts).map(([e,t])=>(0,B.jsxs)(`tr`,{children:[(0,B.jsx)(`td`,{children:(0,B.jsx)(`strong`,{children:e})}),(0,B.jsx)(`td`,{children:t.matched_pair_denominator}),(0,B.jsx)(`td`,{className:`benchmark-positive`,children:t.primary_metric_directions.improved}),(0,B.jsx)(`td`,{children:t.primary_metric_directions.flat}),(0,B.jsx)(`td`,{className:`benchmark-negative`,children:t.primary_metric_directions.regressed}),(0,B.jsx)(`td`,{children:Object.entries(t.binary_metric_transitions).map(([e,t])=>`${e}: 0→1 ${t[`0_to_1`]}, 1→0 ${t[`1_to_0`]}, same ${t.same}`).join(` · `)||`—`})]},e)),Object.keys(e.contrasts).length===0&&(0,B.jsx)(`tr`,{children:(0,B.jsx)(`td`,{colSpan:6,children:`No matched comparisons are countable yet.`})})]})]})})]}),(0,B.jsxs)(`section`,{"aria-labelledby":`runtime-health-title`,children:[(0,B.jsxs)(`div`,{className:`benchmark-section-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`p`,{className:`benchmark-kicker`,children:`RUNTIME HEALTH`}),(0,B.jsx)(`h2`,{id:`runtime-health-title`,children:`Qualified observations, without execution authority`})]}),(0,B.jsxs)(`p`,{children:[e.campaign.runtime_observation_count,` public-safe runtime observations.`]})]}),(0,B.jsxs)(`div`,{className:`benchmark-runtime-list`,children:[Object.entries(e.campaign.runtime_classification_counts).map(([e,t])=>(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`span`,{children:e}),(0,B.jsx)(`strong`,{children:t})]},e)),e.campaign.runtime_observation_count===0&&(0,B.jsx)(`p`,{className:`benchmark-muted`,children:`No runtime observations uploaded.`})]})]})]})}function WC({packet:e}){return(0,B.jsx)(`div`,{className:`benchmark-detail-grid`,children:e.arms.map(t=>(0,B.jsxs)(`article`,{className:`benchmark-detail-card`,children:[(0,B.jsxs)(`div`,{className:`benchmark-card-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`span`,{className:`benchmark-mono`,children:t.arm_role}),(0,B.jsx)(`h2`,{children:t.arm_id})]}),(0,B.jsxs)(HC,{tone:t.coverage_rate===1?`success`:`warning`,children:[t.selected_score_countable_case_count,`/`,t.intended_case_count,` countable`]})]}),(0,B.jsx)(`div`,{className:`benchmark-factor-row`,children:Object.entries(t.factor_assignments).map(([e,t])=>(0,B.jsxs)(`span`,{children:[e,`: `,(0,B.jsx)(`strong`,{children:t})]},e))}),(0,B.jsxs)(`dl`,{className:`benchmark-stat-list`,children:[e.design.metric_catalog.map(e=>(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`dt`,{children:[e.role,` · `,e.metric_name]}),(0,B.jsx)(`dd`,{children:BC(t,e.metric_name)})]},e.metric_name)),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Runs terminal / observed`}),(0,B.jsxs)(`dd`,{children:[t.terminal_run_count,`/`,t.run_count]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Median duration`}),(0,B.jsx)(`dd`,{children:LC(t.effort.duration_ms?.median)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Protocols`}),(0,B.jsx)(`dd`,{children:RC(t.protocol_counts)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Runner revisions`}),(0,B.jsx)(`dd`,{children:RC(t.runner_revision_counts)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Orchestrator runtimes`}),(0,B.jsxs)(`dd`,{children:[Object.keys(t.orchestrator_runtime_counts).length||0,` distinct`]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Failure classes`}),(0,B.jsx)(`dd`,{children:RC(t.failure_class_counts)})]})]})]},t.arm_id))})}function GC({packet:e,primaryMetric:t,onOpenRun:n}){return(0,B.jsx)(`div`,{className:`benchmark-table-shell benchmark-wide-table`,children:(0,B.jsxs)(`table`,{children:[(0,B.jsx)(`thead`,{children:(0,B.jsxs)(`tr`,{children:[(0,B.jsx)(`th`,{children:`Case`}),(0,B.jsx)(`th`,{children:`Design status`}),(0,B.jsx)(`th`,{children:`Largest eligible delta`}),e.arms.map(e=>(0,B.jsx)(`th`,{children:e.arm_id},e.arm_id))]})}),(0,B.jsx)(`tbody`,{children:e.cases.map(r=>{let i=VC(r,t);return(0,B.jsxs)(`tr`,{children:[(0,B.jsx)(`td`,{children:(0,B.jsx)(`strong`,{children:r.case_id})}),(0,B.jsx)(`td`,{children:(0,B.jsx)(HC,{tone:r.complete_declared_design?`success`:`warning`,children:r.complete_declared_design?`Complete`:`Provisional`})}),(0,B.jsx)(`td`,{className:i?.direction===`improved`?`benchmark-positive`:i?.direction===`regressed`?`benchmark-negative`:void 0,children:i?.text??`—`}),r.arms.map(r=>(0,B.jsx)(`td`,{children:r.selected_run_id&&r.score_countable?(0,B.jsxs)(`button`,{className:`benchmark-cell-link`,onClick:()=>n(r.selected_run_id),type:`button`,children:[(0,B.jsxs)(`span`,{children:[t,`: `,zC(r.metrics[t])]}),e.design.metric_catalog.filter(e=>e.metric_name!==t).map(e=>(0,B.jsxs)(`small`,{className:`benchmark-cell-metric`,children:[e.metric_name,`: `,zC(r.metrics[e.metric_name])]},e.metric_name)),(0,B.jsxs)(`small`,{children:[`Countable · `,LC(r.effort.duration_ms),` `,(0,B.jsx)(Kp,{"aria-hidden":`true`,size:12})]}),r.insight&&(0,B.jsxs)(`small`,{children:[r.insight.failure_class,` · `,r.insight.confidence]})]}):(0,B.jsx)(`span`,{className:`benchmark-muted`,children:`Not countable`})},r.arm_id))]},r.case_id)})})]})})}function KC({run:e,packet:t}){return(0,B.jsxs)(`aside`,{"aria-label":`Run detail for ${e.run_id}`,className:`benchmark-run-detail`,children:[(0,B.jsxs)(`div`,{className:`benchmark-card-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`span`,{className:`benchmark-mono`,children:`RUN DETAIL`}),(0,B.jsx)(`h2`,{children:e.run_id})]}),(0,B.jsx)(HC,{tone:e.countability.score_countable?`success`:`warning`,children:e.countability.score_countable?`Score-countable`:`Diagnostic only`})]}),(0,B.jsxs)(`dl`,{className:`benchmark-stat-list benchmark-run-facts`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Case / arm`}),(0,B.jsxs)(`dd`,{children:[e.case_id,` · `,e.arm_id]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Lifecycle`}),(0,B.jsxs)(`dd`,{children:[e.status,` · `,e.observed_at]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Protocol`}),(0,B.jsx)(`dd`,{children:e.protocol_id})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Qualification`}),(0,B.jsxs)(`dd`,{children:[`Integrity `,e.countability.integrity_qualified?`qualified`:`not qualified`,` · result `,e.countability.official_result_present?`present`:`missing`]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Treatment fidelity`}),(0,B.jsx)(`dd`,{children:e.treatment_fidelity})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Effort`}),(0,B.jsxs)(`dd`,{children:[LC(e.effort.duration_ms),` · `,IC(e.effort.agent_steps),` steps · `,IC(e.effort.token_count),` tokens`]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Runner revision`}),(0,B.jsx)(`dd`,{children:e.runner_revision??`—`})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Upload provenance`}),(0,B.jsxs)(`dd`,{children:[e.upload_provenance.producer_id,` · `,e.upload_provenance.source_revision]})]})]}),(0,B.jsx)(`div`,{className:`benchmark-run-metrics`,children:t.design.metric_catalog.map(t=>(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`span`,{children:t.metric_name}),(0,B.jsx)(`strong`,{children:zC(e.metrics[t.metric_name])})]},t.metric_name))}),e.redacted_insight&&(0,B.jsxs)(`div`,{className:`benchmark-insight`,children:[(0,B.jsxs)(`span`,{className:`benchmark-mono`,children:[`REDACTED CASE INSIGHT · `,e.redacted_insight.confidence]}),(0,B.jsx)(`p`,{children:e.redacted_insight.causal_summary}),(0,B.jsxs)(`small`,{children:[`Implication: `,e.redacted_insight.implication]}),(0,B.jsx)(`br`,{}),(0,B.jsxs)(`small`,{children:[`Next probe: `,e.redacted_insight.next_probe]}),!!e.redacted_insight.evidence_refs?.length&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`br`,{}),(0,B.jsxs)(`small`,{children:[`Evidence: `,e.redacted_insight.evidence_refs.join(`, `)]})]})]})]})}function qC({packet:e,selectedRunId:t,onSelectRun:n}){let r=e.runs.find(e=>e.run_id===t)??e.runs[0];return(0,B.jsxs)(`div`,{className:`benchmark-runs-layout`,children:[(0,B.jsx)(`div`,{className:`benchmark-table-shell`,children:(0,B.jsxs)(`table`,{children:[(0,B.jsx)(`thead`,{children:(0,B.jsxs)(`tr`,{children:[(0,B.jsx)(`th`,{children:`Run`}),(0,B.jsx)(`th`,{children:`Case`}),(0,B.jsx)(`th`,{children:`Arm`}),(0,B.jsx)(`th`,{children:`Status`}),(0,B.jsx)(`th`,{children:`Countability`})]})}),(0,B.jsx)(`tbody`,{children:e.runs.map(e=>(0,B.jsxs)(`tr`,{"aria-selected":e.run_id===r?.run_id,children:[(0,B.jsx)(`td`,{children:(0,B.jsx)(`button`,{className:`benchmark-run-link`,onClick:()=>n(e.run_id),type:`button`,children:e.run_id})}),(0,B.jsx)(`td`,{children:e.case_id}),(0,B.jsx)(`td`,{children:e.arm_id}),(0,B.jsx)(`td`,{children:e.status}),(0,B.jsx)(`td`,{children:e.countability.score_countable?`Score-countable`:`Diagnostic only`})]},e.run_id))})]})}),r&&(0,B.jsx)(KC,{packet:e,run:r})]})}function JC(){let e=lw.useSearch(),t=lw.useNavigate(),[n,r]=(0,z.useState)(null),[i,a]=(0,z.useState)(null),[o,s]=(0,z.useState)(0),c=(0,z.useMemo)(()=>{let t=e.dashboardUrl||`/chat/benchmark-study.example.json`;try{return{url:NC(t,window.location.href),error:null}}catch(e){return{url:``,error:e instanceof Error?e.message:`Invalid dashboard source`}}},[e.dashboardUrl]);if((0,z.useEffect)(()=>{let e=!0;return r(null),a(null),c.error?(a(c.error),()=>{e=!1}):(fetch(c.url,{cache:`no-store`}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status} while loading the dashboard packet`);return MC(await e.json())}).then(t=>{e&&r(t)}).catch(t=>{e&&a(t instanceof Error?t.message:`Unable to load dashboard packet`)}),()=>{e=!1})},[o,c]),(0,z.useEffect)(()=>{n&&(document.title=`${n.design.labels.title??n.study_id} · LoopX Benchmark`)},[n]),i)return(0,B.jsxs)(`main`,{className:`benchmark-page benchmark-loading`,children:[(0,B.jsx)(im,{"aria-hidden":`true`}),(0,B.jsx)(`h1`,{children:`Dashboard packet unavailable`}),(0,B.jsx)(`p`,{children:i}),(0,B.jsxs)(`button`,{onClick:()=>s(e=>e+1),type:`button`,children:[(0,B.jsx)(Im,{"aria-hidden":`true`,size:16}),` Retry readback`]})]});if(!n)return(0,B.jsxs)(`main`,{"aria-busy":`true`,className:`benchmark-page benchmark-loading`,children:[(0,B.jsx)(Up,{"aria-hidden":`true`}),(0,B.jsx)(`h1`,{children:`Reading benchmark study`}),(0,B.jsx)(`p`,{children:`Validating the public-safe dashboard packet…`})]});let l=n.design.metric_catalog.find(e=>e.role===`primary`)?.metric_name??`primary`,u=(n,r=e.runId)=>t({search:e=>({...e,view:n,runId:r})}),d=new URL(c.url).pathname;return(0,B.jsxs)(`main`,{className:`benchmark-page`,children:[(0,B.jsxs)(`header`,{className:`benchmark-hero`,children:[(0,B.jsxs)(`div`,{className:`benchmark-hero-topline`,children:[(0,B.jsx)(`a`,{className:`benchmark-wordmark`,href:`/chat/`,children:`LoopX`}),(0,B.jsxs)(`div`,{className:`benchmark-readonly`,children:[(0,B.jsx)(Wm,{"aria-hidden":`true`,size:15}),` Derived read-only projection`]})]}),(0,B.jsxs)(`div`,{className:`benchmark-hero-grid`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`p`,{className:`benchmark-kicker`,children:[`BENCHMARK STUDY / `,n.benchmark_id]}),(0,B.jsxs)(`div`,{className:`benchmark-title-row`,children:[(0,B.jsx)(`h1`,{children:n.design.labels.title??n.study_id}),(0,B.jsx)(HC,{tone:n.status===`complete`?`success`:`warning`,children:n.status})]}),(0,B.jsx)(`p`,{className:`benchmark-lead`,children:`One declared study, explicit denominators, and the same countability rules from campaign summary to exact run.`})]}),(0,B.jsxs)(`dl`,{className:`benchmark-identity`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Study`}),(0,B.jsx)(`dd`,{children:n.study_id})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Protocol`}),(0,B.jsx)(`dd`,{children:n.design.protocol_id})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Case set`}),(0,B.jsx)(`dd`,{children:n.design.case_set.case_set_id})]})]})]}),(0,B.jsxs)(`div`,{className:`benchmark-kpi-grid`,children:[(0,B.jsxs)(`article`,{children:[(0,B.jsx)(lm,{"aria-hidden":`true`}),(0,B.jsx)(`span`,{children:`Score-countable cells`}),(0,B.jsxs)(`strong`,{children:[n.campaign.selected_score_countable_cell_count,(0,B.jsxs)(`small`,{children:[` / `,n.campaign.intended_cell_denominator]})]}),(0,B.jsxs)(`p`,{children:[FC(n.campaign.selected_score_countable_coverage_rate),` declared coverage`]})]}),(0,B.jsxs)(`article`,{children:[(0,B.jsx)(am,{"aria-hidden":`true`}),(0,B.jsx)(`span`,{children:`Complete designs`}),(0,B.jsxs)(`strong`,{children:[n.campaign.complete_declared_design_case_count,(0,B.jsxs)(`small`,{children:[` / `,n.campaign.intended_case_count]})]}),(0,B.jsx)(`p`,{children:`Cases with every declared arm`})]}),(0,B.jsxs)(`article`,{children:[(0,B.jsx)(Kp,{"aria-hidden":`true`}),(0,B.jsx)(`span`,{children:`Matched comparisons`}),(0,B.jsx)(`strong`,{children:n.campaign.matched_pair_countable_count}),(0,B.jsx)(`p`,{children:`Eligible pairs only`})]}),(0,B.jsxs)(`article`,{children:[(0,B.jsx)(Up,{"aria-hidden":`true`}),(0,B.jsx)(`span`,{children:`In flight`}),(0,B.jsx)(`strong`,{children:n.campaign.in_flight_run_count}),(0,B.jsx)(`p`,{children:n.status===`provisional`?`Coverage remains provisional`:`Declared coverage complete`})]})]})]}),(0,B.jsxs)(`nav`,{"aria-label":`Benchmark dashboard views`,className:`benchmark-tabs`,children:[PC.map(t=>(0,B.jsx)(`button`,{"aria-current":e.view===t.id?`page`:void 0,onClick:()=>u(t.id),type:`button`,children:t.label},t.id)),(0,B.jsxs)(`button`,{className:`benchmark-refresh`,onClick:()=>s(e=>e+1),type:`button`,children:[(0,B.jsx)(Im,{"aria-hidden":`true`,size:14}),` Refresh local readback`]})]}),(0,B.jsxs)(`div`,{className:`benchmark-content`,children:[e.view===`campaign`&&(0,B.jsx)(UC,{packet:n,primaryMetric:l}),e.view===`arms`&&(0,B.jsx)(WC,{packet:n}),e.view===`cases`&&(0,B.jsx)(GC,{onOpenRun:e=>u(`runs`,e),packet:n,primaryMetric:l}),e.view===`runs`&&(0,B.jsx)(qC,{onSelectRun:e=>u(`runs`,e),packet:n,selectedRunId:e.runId})]}),(0,B.jsxs)(`footer`,{className:`benchmark-footer`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(Wm,{"aria-hidden":`true`,size:16}),(0,B.jsxs)(`span`,{children:[`Scores: `,n.authority.score_source]}),(0,B.jsx)(`span`,{children:`Dashboard cannot launch, grade, or mutate runs.`})]}),(0,B.jsxs)(`code`,{title:d,children:[`local`,d]})]})]})}var YC=J({goalId:W().optional().default(``),statusUrl:W().optional().default(``)}),XC=J({goalId:W().optional().default(``),mode:Y([`showcase`,`developer`,`ops`]).optional().default(`showcase`),statusUrl:W().optional().default(``),todoLane:Y([`all`,`user`,`agent`]).optional().default(`all`),todoQuery:W().optional().default(``)}),ZC=XC.omit({mode:!0}),QC=J({dashboardUrl:W().optional().default(``),view:Y([`campaign`,`arms`,`cases`,`runs`]).optional().default(`campaign`),runId:W().optional().default(``)});function $C(){let e=`https://huangruiteng.github.io/loopx/docs/showcases/index.en.html`;return(0,z.useEffect)(()=>{window.location.replace(e)},[]),(0,B.jsx)(`a`,{href:e,children:`Open LoopX cases / 浏览案例`})}function ew({goalId:e,statusUrl:t}){let n=t?rh(t,window.location.href):null;return n?.error?(0,B.jsx)(`main`,{role:`alert`,children:n.error}):(0,B.jsx)(ii,{replace:!0,to:`/`,search:{goalId:e,statusUrl:t}})}function tw(){let e=aw.useSearch();return e.mode===`ops`?(0,B.jsx)(ew,{...e}):e.mode===`developer`?(0,B.jsx)(ii,{replace:!0,to:`/developers/projections`}):(0,B.jsx)($C,{})}function nw(){return(0,B.jsx)(ew,{...ow.useSearch()})}var rw=Ci({component:()=>(0,B.jsx)(Mi,{}),errorComponent:()=>(0,B.jsxs)(`main`,{role:`alert`,className:`p-8`,children:[(0,B.jsx)(`h1`,{children:`页面暂时无法显示 / Page unavailable`}),(0,B.jsx)(`p`,{children:`请重新加载页面;这不会执行任务。 / Reloading does not execute tasks.`}),(0,B.jsx)(`button`,{type:`button`,onClick:()=>window.location.reload(),children:`重新加载 / Reload`})]})}),iw=xi({getParentRoute:()=>rw,path:`/`,validateSearch:e=>YC.parse(e),component:sC}),aw=xi({getParentRoute:()=>rw,path:`/frontstage`,validateSearch:e=>XC.parse(e),component:tw}),ow=xi({getParentRoute:()=>rw,path:`/deprecated/frontstage/ops`,validateSearch:e=>ZC.parse(e),component:nw}),sw=xi({getParentRoute:()=>rw,path:`/frontstage/developer`,component:()=>(0,B.jsx)(ii,{replace:!0,to:`/developers/projections`})}),cw=xi({getParentRoute:()=>rw,path:`/developers/projections`,component:xC}),lw=xi({getParentRoute:()=>rw,path:`/benchmarks/study`,validateSearch:e=>QC.parse(e),component:JC}),uw=rw.addChildren([iw,aw,ow,sw,cw,lw]);function dw(e){return!e||e===`/`||e===`./`?`/`:(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}var fw=Li({routeTree:uw,basepath:dw(`/chat/`),trailingSlash:`preserve`}),pw=document.getElementById(`root`);if(!pw)throw Error(`Root element not found`);var mw=new Ae({defaultOptions:{queries:{refetchOnWindowFocus:!1,retry:1,staleTime:1e4}}});(0,Vi.createRoot)(pw).render((0,B.jsx)(Pe,{client:mw,children:(0,B.jsx)(qi,{children:(0,B.jsx)(Bi,{router:fw})})})); \ No newline at end of file diff --git a/loopx/web/chat/assets/index-B-l9MJT-.js b/loopx/web/chat/assets/index-B-l9MJT-.js deleted file mode 100644 index 3020a2b7cb..0000000000 --- a/loopx/web/chat/assets/index-B-l9MJT-.js +++ /dev/null @@ -1,138 +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,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},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,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),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var l=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&&ne(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&&ne(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var ee=new MessageChannel,te=ee.port2;ee.port1.onmessage=D,O=function(){te.postMessage(null)}}else O=function(){_(D,0)};function ne(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,ne(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}}}})),u=o(((e,t)=>{t.exports=l()})),d=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 ee(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var te=/\/+/g;function ne(e,t){return typeof e==`object`&&e&&e.key!=null?ee(``+e.key):t.toString(36)}function k(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 A(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,A(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+ne(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(te,`$&/`)+`/`),A(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(te,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{t.exports=d()})),p=o((e=>{var t=f();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=p()})),h=o((e=>{var t=u(),n=f(),r=m();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=I(null),se=I(null),ce=I(null),le=I(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)?Wd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Wd(t),e=Gd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}ae(oe),L(oe,e)}function de(){ae(oe),ae(se),ae(ce)}function R(e){e.memoizedState!==null&&L(le,e);var t=oe.current,n=Gd(t,e.type);t!==n&&(L(se,e),L(oe,n))}function fe(e){se.current===e&&(ae(oe),ae(se)),le.current===e&&(ae(le),tp._currentValue=F)}var pe,me;function he(e){if(pe===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);pe=t&&t[1]||``,me=-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{ge=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?he(n):``}function ve(e,t){switch(e.tag){case 26:case 27:case 5:return he(e.type);case 16:return he(`Lazy`);case 13:return e.child!==t&&t!==null?he(`Suspense Fallback`):he(`Suspense`);case 19:return he(`SuspenseList`);case 0:case 15:return _e(e.type,!1);case 11:return _e(e.type.render,!1);case 1:return _e(e.type,!0);case 31:return he(`Activity`);default:return``}}function ye(e){try{var t=``,n=null;do t+=ve(e,n),n=e,e=e.return;while(e);return t}catch(e){return` -Error generating stack: `+e.message+` -`+e.stack}}var be=Object.prototype.hasOwnProperty,xe=t.unstable_scheduleCallback,Se=t.unstable_cancelCallback,Ce=t.unstable_shouldYield,we=t.unstable_requestPaint,Te=t.unstable_now,z=t.unstable_getCurrentPriorityLevel,Ee=t.unstable_ImmediatePriority,De=t.unstable_UserBlockingPriority,Oe=t.unstable_NormalPriority,ke=t.unstable_LowPriority,Ae=t.unstable_IdlePriority,je=t.log,B=t.unstable_setDisableYieldValue,V=null,Me=null;function Ne(e){if(typeof je==`function`&&B(e),Me&&typeof Me.setStrictMode==`function`)try{Me.setStrictMode(V,e)}catch{}}var Pe=Math.clz32?Math.clz32:Ie,H=Math.log,Fe=Math.LN2;function Ie(e){return e>>>=0,e===0?32:31-(H(e)/Fe|0)|0}var Le=256,Re=262144,ze=4194304;function Be(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 Ve(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=Be(n))):i=Be(o):i=Be(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=Be(n))):i=Be(o)):i=Be(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 He(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Ue(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 We(){var e=ze;return ze<<=1,!(ze&62914560)&&(ze=4194304),e}function Ge(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Ke(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function qe(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),on=!1;if(an)try{var sn={};Object.defineProperty(sn,"passive",{get:function(){on=!0}}),window.addEventListener(`test`,sn,sn),window.removeEventListener(`test`,sn,sn)}catch{on=!1}var cn=null,ln=null,un=null;function dn(){if(un)return un;var e,t=ln,n=t.length,r,i=`value`in cn?cn.value:cn.textContent,a=i.length;for(e=0;e=Un),Kn=` `,qn=!1;function Jn(e,t){switch(e){case`keyup`:return Vn.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Yn(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Xn=!1;function Zn(e,t){switch(e){case`compositionend`:return Yn(t);case`keypress`:return t.which===32?(qn=!0,Kn):null;case`textInput`:return e=t.data,e===Kn&&qn?null:e;default:return null}}function Qn(e,t){if(Xn)return e===`compositionend`||!Hn&&Jn(e,t)?(e=dn(),un=ln=cn=null,Xn=!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=br(n)}}function Sr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Sr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Cr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Mt(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=Mt(e.document)}return t}function wr(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 Tr=an&&`documentMode`in document&&11>=document.documentMode,Er=null,Dr=null,Or=null,kr=!1;function Ar(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;kr||Er==null||Er!==Mt(r)||(r=Er,`selectionStart`in r&&wr(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}),Or&&yr(Or,r)||(Or=r,r=Od(Dr,`onSelect`),0>=o,i-=o,Si=1<<32-Pe(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),ji&&wi(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),ji&&wi(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 ji&&wi(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)}),ji&&wi(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&&Ca(l)===r.type){n(e,r.sibling),c=a(r,o.props),Aa(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===y?(c=li(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=ci(o.type,o.key,o.props,null,e.mode,c),Aa(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}n(e,r);break}t(e,r),r=r.sibling}c=fi(o,e.mode,c),c.return=e,e=c}return s(e);case O:return o=Ca(o),b(e,r,o,c)}if(M(o))return h(e,r,o,c);if(k(o)){if(l=k(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,ka(o),c);if(o.$$typeof===C)return b(e,r,Qi(e,o),c);ja(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=ui(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Oa=0;var i=b(e,t,n,r);return Da=null,i}catch(t){if(t===va||t===ba)throw t;var a=ii(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Na=Ma(!0),Pa=Ma(!1),Fa=!1;function Ia(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function La(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 Ra(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function za(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Bl&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=ti(e),ei(e,null,n),t}return Zr(e,r,t,n),ti(e)}function Ba(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,Ye(e,n)}}function Va(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 Ha=!1;function Ua(){if(Ha){var e=la;if(e!==null)throw e}}function Wa(e,t,n,r){Ha=!1;var i=e.updateQueue;Fa=!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?(Ul&f)===f:(r&f)===f){f!==0&&f===ca&&(Ha=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(m=g.payload,typeof m==`function`){d=m.call(_,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=g.payload,f=typeof m==`function`?m.call(_,d,f):m,f==null)break a;d=h({},d,f);break a;case 2:Fa=!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),Zl|=o,e.lanes=o,e.memoizedState=d}}function Ga(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function Ka(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=N.T,s={};N.T=s,Ns(e,!1,t,n);try{var c=i(),l=N.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Ms(e,t,fa(c,r),yu(e)):Ms(e,t,r,yu(e))}catch(n){Ms(e,t,{then:function(){},status:`rejected`,reason:n},yu())}finally{P.p=a,o!==null&&s.types!==null&&(o.types=s.types),N.T=o}}function Ss(){}function Cs(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=ws(e).queue;xs(e,a,t,F,n===null?Ss:function(){return Ts(e),n(r)})}function ws(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:F,baseState:F,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Po,lastRenderedState:F},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Po,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Ts(e){var t=ws(e);t.next===null&&(t=e.alternate.memoizedState),Ms(e,t.next.queue,{},yu())}function Es(){return U(tp)}function Ds(){return ko().memoizedState}function Os(){return ko().memoizedState}function ks(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=yu();e=Ra(n);var r=za(t,e,n);r!==null&&(xu(r,t,n),Ba(r,t,n)),t={cache:ia()},e.payload=t;return}t=t.return}}function As(e,t,n){var r=yu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Ps(e)?Fs(t,n):(n=Qr(e,t,n,r),n!==null&&(xu(n,e,r),Is(n,t,r)))}function js(e,t,n){Ms(e,t,n,yu())}function Ms(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ps(e))Fs(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,vr(s,o))return Zr(e,t,i,0),Vl===null&&Xr(),!1}catch{}if(n=Qr(e,t,i,r),n!==null)return xu(n,e,r),Is(n,t,r),!0}return!1}function Ns(e,t,n,r){if(r={lane:2,revertLane:pd(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Ps(e)){if(t)throw Error(i(479))}else t=Qr(e,n,r,2),t!==null&&xu(t,e,2)}function Ps(e){var t=e.alternate;return e===co||t!==null&&t===co}function Fs(e,t){po=fo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Is(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ye(e,n)}}var Ls={readContext:U,use:Mo,useCallback:yo,useContext:yo,useEffect:yo,useImperativeHandle:yo,useLayoutEffect:yo,useInsertionEffect:yo,useMemo:yo,useReducer:yo,useRef:yo,useState:yo,useDebugValue:yo,useDeferredValue:yo,useTransition:yo,useSyncExternalStore:yo,useId:yo,useHostTransitionStatus:yo,useFormState:yo,useActionState:yo,useOptimistic:yo,useMemoCache:yo,useCacheRefresh:yo};Ls.useEffectEvent=yo;var Rs={readContext:U,use:Mo,useCallback:function(e,t){return Oo().memoizedState=[e,t===void 0?null:t],e},useContext:U,useEffect:cs,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),os(4194308,4,ms.bind(null,t,e),n)},useLayoutEffect:function(e,t){return os(4194308,4,e,t)},useInsertionEffect:function(e,t){os(4,2,e,t)},useMemo:function(e,t){var n=Oo();t=t===void 0?null:t;var r=e();if(mo){Ne(!0);try{e()}finally{Ne(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=Oo();if(n!==void 0){var i=n(t);if(mo){Ne(!0);try{n(t)}finally{Ne(!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=As.bind(null,co,e),[r.memoizedState,e]},useRef:function(e){var t=Oo();return e={current:e},t.memoizedState=e},useState:function(e){e=Wo(e);var t=e.queue,n=js.bind(null,co,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:gs,useDeferredValue:function(e,t){return ys(Oo(),e,t)},useTransition:function(){var e=Wo(!1);return e=xs.bind(null,co,e.queue,!0,!1),Oo().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=co,a=Oo();if(ji){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Vl===null)throw Error(i(349));Ul&127||zo(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,cs(Vo.bind(null,r,o,e),[e]),r.flags|=2048,is(9,{destroy:void 0},Bo.bind(null,r,o,n,t),null),n},useId:function(){var e=Oo(),t=Vl.identifierPrefix;if(ji){var n=Ci,r=Si;n=(r&~(1<<32-Pe(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=ho++,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[nt]=t,o[rt]=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(Ld(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&&Mc(t)}}return Lc(t),Nc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Mc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=ce.current,Ri(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=ki,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[nt]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Pd(e.nodeValue,n)),e||Fi(t,!0)}else e=Ud(e).createTextNode(r),e[nt]=t,t.stateNode=e}return Lc(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Ri(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[nt]=t}else zi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Lc(t),e=!1}else n=Bi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(io(t),t):(io(t),null);if(t.flags&128)throw Error(i(558))}return Lc(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=Ri(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[nt]=t}else zi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Lc(t),a=!1}else a=Bi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(io(t),t):(io(t),null)}return io(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),Fc(t,t.updateQueue),Lc(t),null);case 4:return de(),e===null&&wd(t.stateNode.containerInfo),Lc(t),null;case 10:return Ki(t.type),Lc(t),null;case 19:if(ae(ao),r=t.memoizedState,r===null)return Lc(t),null;if(a=!!(t.flags&128),o=r.rendering,o===null){if(a)Ic(r,!1);else{if(Xl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=oo(e),o!==null){for(t.flags|=128,Ic(r,!1),e=o.updateQueue,t.updateQueue=e,Fc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)si(n,e),n=n.sibling;return L(ao,ao.current&1|2),ji&&wi(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Te()>su&&(t.flags|=128,a=!0,Ic(r,!1),t.lanes=4194304)}}else{if(!a){if(e=oo(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Fc(t,e),Ic(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!ji)return Lc(t),null}else 2*Te()-r.renderingStartTime>su&&n!==536870912&&(t.flags|=128,a=!0,Ic(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?(Lc(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Te(),e.sibling=null,n=ao.current,L(ao,a?n&1|2:n&1),ji&&wi(t,r.treeForkCount),e);case 22:case 23:return io(t),Za(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Lc(t),t.subtreeFlags&6&&(t.flags|=8192)):Lc(t),n=t.updateQueue,n!==null&&Fc(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&&ae(ma),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Ki(ra),Lc(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function zc(e,t){switch(Di(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ki(ra),de(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return fe(t),null;case 31:if(t.memoizedState!==null){if(io(t),t.alternate===null)throw Error(i(340));zi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(io(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));zi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ae(ao),null;case 4:return de(),null;case 10:return Ki(t.type),null;case 22:case 23:return io(t),Za(),e!==null&&ae(ma),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Ki(ra),null;case 25:return null;default:return null}}function Bc(e,t){switch(Di(t),t.tag){case 3:Ki(ra),de();break;case 26:case 27:case 5:fe(t);break;case 4:de();break;case 31:t.memoizedState!==null&&io(t);break;case 13:io(t);break;case 19:ae(ao);break;case 10:Ki(t.type);break;case 22:case 23:io(t),Za(),e!==null&&ae(ma);break;case 24:Ki(ra)}}function Vc(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){Xu(t,t.return,e)}}function Hc(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){Xu(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Xu(t,t.return,e)}}function Uc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{Ka(t,n)}catch(t){Xu(e,e.return,t)}}}function Wc(e,t,n){n.props=Gs(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Xu(e,t,n)}}function Gc(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){Xu(e,t,n)}}function Kc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){Xu(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){Xu(e,t,n)}else n.current=null}}function qc(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){Xu(e,e.return,t)}}function Jc(e,t,n){try{var r=e.stateNode;Rd(r,e.type,n,t),r[rt]=t}catch(t){Xu(e,e.return,t)}}function Yc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&ef(e.type)||e.tag===4}function Xc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Yc(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&&ef(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 Zc(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=Yt));else if(r!==4&&(r===27&&ef(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Zc(e,t,n),e=e.sibling;e!==null;)Zc(e,t,n),e=e.sibling}function Qc(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&&ef(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(Qc(e,t,n),e=e.sibling;e!==null;)Qc(e,t,n),e=e.sibling}function $c(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Ld(t,r,n),t[nt]=e,t[rt]=n}catch(t){Xu(e,e.return,t)}}var el=!1,tl=!1,nl=!1,rl=typeof WeakSet==`function`?WeakSet:Set,il=null;function al(e,t){if(e=e.containerInfo,Vd=up,e=Cr(e),wr(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(Hd={focusedElem:e,selectionRange:n},up=!1,il=t;il!==null;)if(t=il,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,il=e;else for(;il!==null;){switch(t=il,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`))),Ld(o,r,n),o[nt]=e,ht(o),r=o;break a;case`link`:var s=Wf(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=xr(s,h),v=xr(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,N.T=null,n=hu,hu=null;var o=du,s=pu;if(uu=0,fu=du=null,pu=0,Bl&6)throw Error(i(331));var c=Bl;if(Bl|=4,Fl(o.current),Dl(o,o.current,s,n),Bl=c,sd(0,!1),Me&&typeof Me.onPostCommitFiberRoot==`function`)try{Me.onPostCommitFiberRoot(V,o)}catch{}return!0}finally{P.p=a,N.T=r,Ku(e,t)}}function Yu(e,t,n){t=mi(n,t),t=Zs(e.stateNode,t,2),e=za(e,t,2),e!==null&&(Ke(e,2),J(e))}function Xu(e,t,n){if(e.tag===3)Yu(e,e,n);else for(;t!==null;){if(t.tag===3){Yu(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(lu===null||!lu.has(r))){e=mi(n,e),n=Qs(2),r=za(t,n,2),r!==null&&($s(n,r,t,e),Ke(r,2),J(r));break}}t=t.return}}function K(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new zl;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)||(Jl=!0,i.add(n),e=Zu.bind(null,e,t,n),t.then(e,e))}function Zu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Vl===e&&(Ul&n)===n&&(Xl===4||Xl===3&&(Ul&62914560)===Ul&&300>Te()-au?!(Bl&2)&&Ou(e,0):$l|=n,tu===Ul&&(tu=0)),J(e)}function Qu(e,t){t===0&&(t=We()),e=$r(e,t),e!==null&&(Ke(e,t),J(e))}function $u(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Qu(e,n)}function q(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),Qu(e,n)}function ed(e,t){return xe(e,t)}var td=null,nd=null,rd=!1,id=!1,ad=!1,od=0;function J(e){e!==nd&&e.next===null&&(nd===null?td=nd=e:nd=nd.next=e),id=!0,rd||(rd=!0,fd())}function sd(e,t){if(!ad&&id){ad=!0;do for(var n=!1,r=td;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-Pe(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,dd(r,a))}else a=Ul,a=Ve(r,r===Vl?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||He(r,a)||(n=!0,dd(r,a))}r=r.next}while(n);ad=!1}}function Y(){cd()}function cd(){id=rd=!1;var e=0;od!==0&&Jd()&&(e=od);for(var t=Te(),n=null,r=td;r!==null;){var i=r.next,a=ld(r,t);a===0?(r.next=null,n===null?td=i:n.next=i,i===null&&(nd=n)):(n=r,(e!==0||a&3)&&(id=!0)),r=i}uu!==0&&uu!==5||sd(e,!1),od!==0&&(od=0)}function ld(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&&zd(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function wf(e,t,n){var r=Cf;if(r&&typeof t==`string`&&t){var i=Pt(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),vf.has(i)||(vf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Ld(t,`link`,e),ht(t),r.head.appendChild(t)))}}function Tf(e){bf.D(e),wf(`dns-prefetch`,e,null)}function Ef(e,t){bf.C(e,t),wf(`preconnect`,e,t)}function Df(e,t,n){bf.L(e,t,n);var r=Cf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Pt(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Pt(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Pt(n.imageSizes)+`"]`)):i+=`[href="`+Pt(e)+`"]`;var a=i;switch(t){case`style`:a=Nf(e);break;case`script`:a=Lf(e)}_f.has(a)||(e=h({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),_f.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Pf(a))||t===`script`&&r.querySelector(Rf(a))||(t=r.createElement(`link`),Ld(t,`link`,e),ht(t),r.head.appendChild(t)))}}function Of(e,t){bf.m(e,t);var n=Cf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Pt(r)+`"][href="`+Pt(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Lf(e)}if(!_f.has(a)&&(e=h({rel:`modulepreload`,href:e},t),_f.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(Rf(a)))return}r=n.createElement(`link`),Ld(r,`link`,e),ht(r),n.head.appendChild(r)}}}function kf(e,t,n){bf.S(e,t,n);var r=Cf;if(r&&e){var i=mt(r).hoistableStyles,a=Nf(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Pf(a)))s.loading=5;else{e=h({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=_f.get(a))&&Vf(e,n);var c=o=r.createElement(`link`);ht(c),Ld(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,Bf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Af(e,t){bf.X(e,t);var n=Cf;if(n&&e){var r=mt(n).hoistableScripts,i=Lf(e),a=r.get(i);a||(a=n.querySelector(Rf(i)),a||(e=h({src:e,async:!0},t),(t=_f.get(i))&&Hf(e,t),a=n.createElement(`script`),ht(a),Ld(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function jf(e,t){bf.M(e,t);var n=Cf;if(n&&e){var r=mt(n).hoistableScripts,i=Lf(e),a=r.get(i);a||(a=n.querySelector(Rf(i)),a||(e=h({src:e,async:!0,type:`module`},t),(t=_f.get(i))&&Hf(e,t),a=n.createElement(`script`),ht(a),Ld(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Mf(e,t,n,r){var a=(a=ce.current)?yf(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=Nf(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=Nf(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(Pf(e)))&&!o._p&&(s.instance=o,s.state.loading=5),_f.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},_f.set(e,n),o||If(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=Lf(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 Nf(e){return`href="`+Pt(e)+`"`}function Pf(e){return`link[rel="stylesheet"][`+e+`]`}function Ff(e){return h({},e,{"data-precedence":e.precedence,precedence:null})}function If(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}),Ld(t,`link`,n),ht(t),e.head.appendChild(t))}function Lf(e){return`[src="`+Pt(e)+`"]`}function Rf(e){return`script[async]`+e}function zf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Pt(n.href)+`"]`);if(r)return t.instance=r,ht(r),r;var a=h({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),ht(r),Ld(r,`style`,a),Bf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Nf(n.href);var o=e.querySelector(Pf(a));if(o)return t.state.loading|=4,t.instance=o,ht(o),o;r=Ff(n),(a=_f.get(a))&&Vf(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}),Ld(o,`link`,r),t.state.loading|=4,Bf(o,n.precedence,e),t.instance=o;case`script`:return o=Lf(n.src),(a=e.querySelector(Rf(o)))?(t.instance=a,ht(a),a):(r=n,(a=_f.get(o))&&(r=h({},n),Hf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),ht(a),Ld(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,Bf(r,n.precedence,e));return t.instance}function Bf(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 Kf(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 qf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Jf(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=Nf(r.href),a=t.querySelector(Pf(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Zf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,ht(a);return}a=t.ownerDocument||t,r=Ff(r),(i=_f.get(i))&&Vf(r,i),a=a.createElement(`link`),ht(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Ld(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=Zf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Yf=0;function Xf(e,t){return e.stylesheets&&e.count===0&&$f(e,e.stylesheets),0Yf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Zf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)$f(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Qf=null;function $f(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Qf=new Map,t.forEach(ep,e),Qf=null,Zf.call(e))}function ep(e,t){if(!(t.state.loading&4)){var n=Qf.get(e);if(n)var r=n.get(null);else{n=new Map,Qf.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=h()})),_=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},v=new class extends _{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},y={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},b=new class{#e=y;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function x(e){setTimeout(e,0)}var S=typeof window>`u`||`Deno`in globalThis;function C(){}function w(e,t){return typeof e==`function`?e(t):e}function T(e){return typeof e==`number`&&e>=0&&e!==1/0}function E(e,t){return Math.max(e+(t||0)-Date.now(),0)}function D(e,t){return typeof e==`function`?e(t):e}function O(e,t){return typeof e==`function`?e(t):e}function ee(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==ne(o,t.options))return!1}else if(!A(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function te(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(k(t.options.mutationKey)!==k(a))return!1}else if(!A(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function ne(e,t){return(t?.queryKeyHashFn||k)(e)}function k(e){return JSON.stringify(e,(e,t)=>P(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function A(e,t){return e===t?!0:typeof e==typeof t&&e&&t&&typeof e==`object`&&typeof t==`object`?Object.keys(t).every(n=>A(e[n],t[n])):!1}var j=Object.prototype.hasOwnProperty;function M(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=N(e)&&N(t);if(!r&&!(P(e)&&P(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l{b.setTimeout(t,e)})}function ie(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:M(e,t)}function I(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ae(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var L=Symbol();function oe(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===L?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function se(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var ce=(()=>{let e=()=>S;return{isServer(){return e()},setIsServer(t){e=t}}})();function le(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var ue=x;function de(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=ue,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var R=de(),fe=new class extends _{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function pe(e){return Math.min(1e3*2**e,3e4)}function me(e){return(e??`online`)!==`online`||fe.isOnline()}var he=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function ge(e){let t=!1,n=0,r,i=le(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new he(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>v.isFocused()&&(e.networkMode===`always`||fe.isOnline())&&e.canRun(),u=()=>me(e.networkMode)&&e.canRun(),d=e=>{a()||(r?.(),i.resolve(e))},f=e=>{a()||(r?.(),i.reject(e))},p=()=>new Promise(t=>{r=e=>{(a()||l())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),m=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(d).catch(r=>{if(a())return;let i=e.retry??(ce.isServer()?0:3),o=e.retryDelay??pe,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&nl()?void 0:p()).then(()=>{t?f(r):m()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:u,start:()=>(u()?m():p().then(m),i)}}var _e=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),T(this.gcTime)&&(this.#e=b.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ce.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(b.clearTimeout(this.#e),this.#e=void 0)}};function ve(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{se(e,()=>t.signal,()=>n=!0)},u=oe(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?ae:I;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?be:ye,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:ye(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(ct.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function ye(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function be(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var xe=class extends _e{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=we(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=we(this.options);e.data!==void 0&&(this.setState(Ce(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=ie(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(C).catch(C):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>O(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===L||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>D(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!E(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#a&&(this.#s||this.#c()?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}#c(){return this.state.fetchStatus===`paused`&&this.state.status===`pending`}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=oe(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?ve(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta}),this.#a=ge({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof he&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#a.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof he){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...Se(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Ce(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),R.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Se(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:me(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Ce(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function we(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Te=class extends _e{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||z(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=ge({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});let r=this.state.status===`pending`,i=!this.#r.canStart();try{if(r)t();else{this.#i({type:`pending`,variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:i})}let a=await this.#r.start();return await this.#n.config.onSuccess?.(a,e,this.state.context,this,n),await this.options.onSuccess?.(a,e,this.state.context,n),await this.#n.config.onSettled?.(a,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(a,null,e,this.state.context,n),this.#i({type:`success`,data:a}),a}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),R.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function z(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Ee=class extends _{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){let r=new Te({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=De(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=De(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=De(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=De(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){R.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>te(t,e))}findAll(e={}){return this.getAll().filter(t=>te(e,t))}notify(e){R.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return R.batch(()=>Promise.all(e.map(e=>e.continue().catch(C))))}};function De(e){return e.options.scope?.id}var Oe=class extends _{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??ne(r,t),a=this.get(i);return a||(a=new xe({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){R.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>ee(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>ee(e,t)):t}notify(e){R.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){R.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){R.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},ke=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new Oe,this.#t=e.mutationCache||new Ee,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=v.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=fe.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(D(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=w(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return R.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;R.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return R.batch(()=>(n.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=R.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(C).catch(C)}invalidateQueries(e,t={}){return R.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=R.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(C)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(C)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(D(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(C).catch(C)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(C).catch(C)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return fe.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(k(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{A(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(k(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{A(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=ne(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===L&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},Ae=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})),je=o(((e,t)=>{t.exports=Ae()})),B=c(f(),1),V=je(),Me=B.createContext(void 0),Ne=({client:e,children:t})=>(B.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,V.jsx)(Me.Provider,{value:e,children:t})),Pe=typeof window<`u`?B.useLayoutEffect:B.useEffect;function H(e){let t=B.useRef({value:e,prev:null}),n=t.current.value;return e!==n&&(t.current={value:e,prev:n}),t.current.prev}function Fe(e,t,n={},r={}){B.useEffect(()=>{if(!e.current||r.disabled||typeof IntersectionObserver!=`function`)return;let i=new IntersectionObserver(([e])=>{t(e)},n);return i.observe(e.current),()=>{i.disconnect()}},[t,n,r.disabled,e])}function Ie(e){let t=B.useRef(null);return B.useImperativeHandle(e,()=>t.current,[]),t}function Le(e){return e[e.length-1]}function Re(e){return typeof e==`function`}function ze(e,t){return Re(e)?e(t):e}var Be=Object.prototype.hasOwnProperty,Ve=Object.prototype.propertyIsEnumerable;function He(e){for(let t in e)if(Be.call(e,t))return!0;return!1}var Ue=()=>Object.create(null),We=(e,t)=>Ge(e,t,Ue);function Ge(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=Ye(e)&&Ye(i);if(!a&&!(qe(e)&&qe(i)))return i;let o=a?e:Ke(e);if(!o)return i;let s=a?i:Ke(i);if(!s)return i;let c=o.length,l=s.length,u=a?Array(l):n(),d=0;for(let t=0;ti||!Xe(e[o],t[o],n)))return!1;return i===a}return!1}function Ze(e){let t,n,r=new Promise((e,r)=>{t=e,n=r});return r.status=`pending`,r.resolve=n=>{r.status=`resolved`,r.value=n,t(n),e?.(n)},r.reject=e=>{r.status=`rejected`,n(e)},r}function Qe(e){return!!(e&&typeof e==`object`&&typeof e.then==`function`)}function $e(e){return e.replace(/[\x00-\x1f\x7f]/g,``)}function et(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return $e(t)}var tt=[`http:`,`https:`,`mailto:`,`tel:`];function nt(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function rt(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=et(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=et(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function it(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function at(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n{e.next&&(e.prev?(e.prev.next=e.next,e.next.prev=e.prev,e.next=void 0,r&&(r.next=e,e.prev=r)):(e.next.prev=void 0,n=e.next,e.next=void 0,r&&(e.prev=r,r.next=e)),r=e)};return{get(e){let n=t.get(e);if(n)return i(n),n.value},set(a,o){if(t.size>=e&&n){let e=n;t.delete(e.key),e.next&&(n=e.next,e.next.prev=void 0),e===r&&(r=void 0)}let s=t.get(a);if(s)s.value=o,i(s);else{let e={key:a,value:o,prev:r};r&&(r.next=e),r=e,n||=e,t.set(a,e)}},clear(){t.clear(),n=void 0,r=void 0}}}var ct=4,lt=5;function ut(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=e.indexOf(`}`,t);return n===-1||t+1>=e.length?null:[t,n]}function dt(e,t,n=new Uint16Array(6)){let r=e.indexOf(`/`,t),i=r===-1?e.length:r,a=e.substring(t,i);if(!a||!a.includes(`$`))return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n;if(a===`$`){let r=e.length;return n[0]=2,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n}if(a.charCodeAt(0)===36)return n[0]=1,n[1]=t,n[2]=t+1,n[3]=i,n[4]=i,n[5]=i,n;let o=ut(a);if(o){let[r,s]=o,c=a.charCodeAt(r+1);if(c===45){if(r+2!e.parse&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=gt(1,n.fullPath??n.from,f,p,m);o=e,e.depth=a,e.parent=i,i.dynamic??=[],i.dynamic.push(e)}break}case 3:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),f=c&&!!(t||s),p=t?f?t:t.toLowerCase():void 0,m=s?f?s:s.toLowerCase():void 0,h=!l&&i.optional?.find(e=>!e.parse&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=gt(3,n.fullPath??n.from,f,p,m);o=e,e.parent=i,e.depth=a,i.optional??=[],i.optional.push(e)}break}case 2:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),l=c&&!!(t||s),f=t?l?t:t.toLowerCase():void 0,p=s?l?s:s.toLowerCase():void 0,m=gt(2,n.fullPath??n.from,l,f,p);o=m,m.parent=i,m.depth=a,i.wildcard??=[],i.wildcard.push(m)}}i=o}if(l&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf(`/`)+1)===95){let e=ht(n.fullPath??n.from);e.kind=lt,e.parent=i,a++,e.depth=a,i.pathless??=[],i.pathless.push(e),i=e}let u=(n.path||!n.children)&&!n.isRoot;if(u&&r.endsWith(`/`)){let e=ht(n.fullPath??n.from);e.kind=ct,e.parent=i,a++,e.depth=a,i.index=e,i=e}i.parse=l??null,i.priority=n.options?.params?.priority??0,u&&!i.route&&(i.route=n,i.fullPath=n.fullPath??n.from)}if(n.children)for(let r of n.children)ft(e,t,r,s,i,a,o)}function pt(e,t){if(e.parse&&!t.parse)return-1;if(!e.parse&&t.parse)return 1;if(e.parse&&t.parse&&(e.priority||t.priority))return t.priority-e.priority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function mt(e){if(e.pathless)for(let t of e.pathless)mt(t);if(e.static)for(let t of e.static.values())mt(t);if(e.staticInsensitive)for(let t of e.staticInsensitive.values())mt(t);if(e.dynamic?.length){e.dynamic.sort(pt);for(let t of e.dynamic)mt(t)}if(e.optional?.length){e.optional.sort(pt);for(let t of e.optional)mt(t)}if(e.wildcard?.length){e.wildcard.sort(pt);for(let t of e.wildcard)mt(t)}}function ht(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function gt(e,t,n,r,i){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,priority:0,caseSensitive:n,prefix:r,suffix:i}}function _t(e,t){let n=ht(`/`),r=new Uint16Array(6);for(let t of e)ft(!1,r,t,1,n,0);mt(n),t.masksTree=n,t.flatCache=st(1e3)}function vt(e,t){e||=`/`;let n=t.flatCache.get(e);if(n)return n;let r=Ct(e,t.masksTree);return t.flatCache.set(e,r),r}function yt(e,t,n,r,i){e||=`/`,r||=`/`;let a=t?`case\0${e}`:e,o=i.singleCache.get(a);return o||(o=ht(`/`),ft(t,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(a,o)),Ct(r,o,n)}function bt(e,t,n=!1){let r=n?e:`nofuzz\0${e}`,i=t.matchCache.get(r);if(i!==void 0)return i;e||=`/`;let a;try{a=Ct(e,t.segmentTree,n)}catch(e){if(e instanceof URIError)a=null;else throw e}return a&&(a.branch=Tt(a.route)),t.matchCache.set(r,a),a}function xt(e){return e===`/`?e:e.replace(/\/{1,}$/,``)}function St(e,t=!1,n){let r=ht(e.fullPath),i=new Uint16Array(6),a={},o={},s=0;return ft(t,i,e,1,r,0,e=>{if(n?.(e,s),e.id in a&&ot(),a[e.id]=e,s!==0&&e.path){let t=xt(e.fullPath);(!o[t]||e.fullPath.endsWith(`/`))&&(o[t]=e)}s++}),mt(r),{processedTree:{segmentTree:r,singleCache:st(1e3),matchCache:st(1e3),flatCache:null,masksTree:null},routesById:a,routesByPath:o}}function Ct(e,t,n=!1){let r=e.split(`/`),i=Dt(e,r,t,n);if(!i)return null;let[a]=wt(e,r,i);return{route:i.node.route,rawParams:a}}function wt(e,t,n){let r=Et(n.node),i=null,a=Object.create(null),o=n.extract?.part??0,s=n.extract?.node??0,c=n.extract?.path??0,l=n.extract?.segment??0;for(;s=0;e--){let n=i.wildcard[e],{prefix:r,suffix:a}=n;if(!(r&&(v||!(n.caseSensitive?y:b??=y.toLowerCase()).startsWith(r)))){if(a){if(v)continue;let e=t.slice(u).join(`/`).slice(-a.length);if((n.caseSensitive?e:e.toLowerCase())!==a)continue}s.push({node:n,index:o,skipped:d,depth:f+1,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}}if(i.optional){let e=d|1<=0;n--){let r=i.optional[n];s.push({node:r,index:u,skipped:e,depth:t,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}if(!v)for(let e=i.optional.length-1;e>=0;e--){let n=i.optional[e],{prefix:r,suffix:a}=n;if(r||a){let e=n.caseSensitive?y:b??=y.toLowerCase();if(r&&!e.startsWith(r)||a&&!e.endsWith(a))continue}s.push({node:n,index:u+1,skipped:d,depth:t,statics:p,dynamics:m,optionals:h+Ot(o,u),extract:g,rawParams:_})}}if(!v&&i.dynamic&&y)for(let e=i.dynamic.length-1;e>=0;e--){let t=i.dynamic[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?y:b??=y.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}s.push({node:t,index:u+1,skipped:d,depth:f+1,statics:p,dynamics:m+Ot(o,u),optionals:h,extract:g,rawParams:_})}if(!v&&i.staticInsensitive){let e=i.staticInsensitive.get(b??=y.toLowerCase());e&&s.push({node:e,index:u+1,skipped:d,depth:f+1,statics:p+Ot(o,u),dynamics:m,optionals:h,extract:g,rawParams:_})}if(!v&&i.static){let e=i.static.get(y);e&&s.push({node:e,index:u+1,skipped:d,depth:f+1,statics:p+Ot(o,u),dynamics:m,optionals:h,extract:g,rawParams:_})}if(i.pathless){let e=f+1;for(let t=i.pathless.length-1;t>=0;t--){let n=i.pathless[t];s.push({node:n,index:u,skipped:d,depth:e,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}}}if(l)return l;if(r&&c){let n=c.index;for(let e=0;ee.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===ct)>(e.node.kind===ct)||t.node.kind===ct==(e.node.kind===ct)&&t.depth>e.depth)))}function Mt(e){return Nt(e.filter(e=>e!==void 0).join(`/`))}function Nt(e){return e.replace(/\/{2,}/g,`/`)}function Pt(e){return e===`/`?e:e.replace(/^\/{1,}/,``)}function Ft(e){let t=e.length;return t>1&&e[t-1]===`/`?e.replace(/\/{1,}$/,``):e}function It(e){return Ft(Pt(e))}function Lt(e,t){return e?.endsWith(`/`)&&e!==`/`&&e!==`${t}/`?e.slice(0,-1):e}function Rt(e,t,n){return Lt(e,n)===Lt(t,n)}function zt({base:e,to:t,trailingSlash:n=`never`,cache:r}){let i=t.startsWith(`/`),a=!i&&t===`.`,o;if(r){o=i?t:a?e:e+`\0`+t;let n=r.get(o);if(n)return n}let s;if(a)s=e.split(`/`);else if(i)s=t.split(`/`);else{for(s=e.split(`/`);s.length>1&&Le(s)===``;)s.pop();let n=t.split(`/`);for(let e=0,t=n.length;e1&&(Le(s)===``?n===`never`&&s.pop():n===`always`&&s.push(``));let c=Nt(s.join(`/`))||`/`;return o&&r&&r.set(o,c),c}function Bt(e){let t=new Map(e.map(e=>[encodeURIComponent(e),e])),n=Array.from(t.keys()).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`),r=new RegExp(n,`g`);return e=>e.replace(r,e=>t.get(e)??e)}function Vt(e,t,n){let r=t[e];return typeof r==`string`?e===`_splat`?/^[a-zA-Z0-9\-._~!/]*$/.test(r)?r:r.split(`/`).map(e=>Ut(e,n)).join(`/`):Ut(r,n):r}function Ht({path:e,params:t,decoder:n,...r}){let i=!1,a=Object.create(null);if(!e||e===`/`)return{interpolatedPath:`/`,usedParams:a,isMissingParams:i};if(!e.includes(`$`))return{interpolatedPath:e,usedParams:a,isMissingParams:i};let o=e.length,s=0,c,l=``;for(;s{t[0]===`?`&&(t=t.substring(1));let n=qt(t);for(let t in n){let r=n[t];if(typeof r==`string`)try{n[t]=e(r)}catch{}}return n}}function Zt(e,t){let n=typeof t==`function`;function r(r){if(typeof r==`object`&&r)try{return e(r)}catch{}else if(n&&typeof r==`string`)try{return t(r),e(r)}catch{}return r}return e=>{let t=Gt(e,r);return t?`?${t}`:``}}var Qt=`__root__`;function $t(e){if(e.statusCode=e.statusCode||e.code||307,!e._builtLocation&&!e.reloadDocument&&typeof e.href==`string`)try{new URL(e.href),e.reloadDocument=!0}catch{}let t=new Headers(e.headers);e.href&&t.get(`Location`)===null&&t.set(`Location`,e.href);let n=new Response(null,{status:e.statusCode,headers:t});if(n.options=e,e.throw)throw n;return n}function en(e){return e instanceof Response&&!!e.options}var tn=e=>{if(!e.rendered)return e.rendered=!0,e.onReady?.()},nn=e=>e.stores.matchesId.get().some(t=>e.stores.matchStores.get(t)?.get()._forcePending),rn=(e,t)=>!!(e.preload&&!e.router.stores.matchStores.has(t)),an=(e,t,n=!0)=>{let r={...e.router.options.context??{}},i=n?t:t-1;for(let t=0;t<=i;t++){let n=e.matches[t];if(!n)continue;let i=e.router.getMatch(n.id);i&&Object.assign(r,i.__routeContext,i.__beforeLoadContext)}return r},on=(e,t)=>{if(!e.matches.length)return;let n=t.routeId,r=e.matches.findIndex(t=>t.routeId===e.router.routeTree.id),i=r>=0?r:0,a=n?e.matches.findIndex(e=>e.routeId===n):e.firstBadMatchIndex??e.matches.length-1;a<0&&(a=i);for(let t=a;t>=0;t--){let n=e.matches[t];if(e.router.looseRoutesById[n.routeId].options.notFoundComponent)return t}return n?a:i},sn=(e,t,n)=>{if(!(!en(n)&&!Wt(n)))throw en(n)&&n.redirectHandled&&!n.options.reloadDocument?n:(t&&(t._nonReactive.beforeLoadPromise?.resolve(),t._nonReactive.loaderPromise?.resolve(),t._nonReactive.beforeLoadPromise=void 0,t._nonReactive.loaderPromise=void 0,t._nonReactive.error=n,e.updateMatch(t.id,r=>({...r,status:en(n)?`redirected`:Wt(n)?`notFound`:r.status===`pending`?`success`:r.status,context:an(e,t.index),isFetching:!1,error:n})),Wt(n)&&!n.routeId&&(n.routeId=t.routeId),t._nonReactive.loadPromise?.resolve()),en(n)&&(e.rendered=!0,n.options._fromLocation=e.location,n.redirectHandled=!0,n=e.router.resolveRedirect(n)),n)},cn=(e,t)=>{let n=e.router.getMatch(t);return!!(!n||n._nonReactive.dehydrated)},ln=(e,t,n)=>{let r=an(e,n);e.updateMatch(t,e=>({...e,context:r}))},un=(e,t,n)=>{let{id:r,routeId:i}=e.matches[t],a=e.router.looseRoutesById[i];if(n instanceof Promise)throw n;e.firstBadMatchIndex??=t,sn(e,e.router.getMatch(r),n);try{a.options.onError?.(n)}catch(t){n=t,sn(e,e.router.getMatch(r),n)}e.updateMatch(r,e=>(e._nonReactive.beforeLoadPromise?.resolve(),e._nonReactive.beforeLoadPromise=void 0,e._nonReactive.loadPromise?.resolve(),{...e,error:n,status:`error`,isFetching:!1,updatedAt:Date.now(),abortController:new AbortController})),!e.preload&&!en(n)&&!Wt(n)&&(e.serialError??=n)},dn=(e,t,n,r)=>{if(r._nonReactive.pendingTimeout!==void 0)return;let i=n.options.pendingMs??e.router.options.defaultPendingMs;if(e.onReady&&!rn(e,t)&&(n.options.loader||n.options.beforeLoad||Sn(n))&&typeof i==`number`&&i!==1/0&&(n.options.pendingComponent??e.router.options?.defaultPendingComponent)){let t=setTimeout(()=>{tn(e)},i);r._nonReactive.pendingTimeout=t}},fn=(e,t,n)=>{let r=e.router.getMatch(t);if(!r._nonReactive.beforeLoadPromise&&!r._nonReactive.loaderPromise)return;dn(e,t,n,r);let i=()=>{let n=e.router.getMatch(t);n.preload&&(n.status===`redirected`||n.status===`notFound`)&&sn(e,n,n.error)};return r._nonReactive.beforeLoadPromise?r._nonReactive.beforeLoadPromise.then(i):i()},pn=(e,t,n,r)=>{let i=e.router.getMatch(t),a=i._nonReactive.loadPromise;i._nonReactive.loadPromise=Ze(()=>{a?.resolve(),a=void 0});let{paramsError:o,searchError:s}=i;o&&un(e,n,o),s&&un(e,n,s),dn(e,t,r,i);let c=new AbortController,l=!1,u=()=>{l||(l=!0,e.updateMatch(t,e=>({...e,isFetching:`beforeLoad`,fetchCount:e.fetchCount+1,abortController:c})))},d=()=>{i._nonReactive.beforeLoadPromise?.resolve(),i._nonReactive.beforeLoadPromise=void 0,e.updateMatch(t,e=>({...e,isFetching:!1}))};if(!r.options.beforeLoad){e.router.batch(()=>{u(),d()});return}i._nonReactive.beforeLoadPromise=Ze();let f={...an(e,n,!1),...i.__routeContext},{search:p,params:m,cause:h}=i,g=rn(e,t),_={search:p,abortController:c,params:m,preload:g,context:f,location:e.location,navigate:t=>e.router.navigate({...t,_fromLocation:e.location}),buildLocation:e.router.buildLocation,cause:g?`preload`:h,matches:e.matches,routeId:r.id,...e.router.options.additionalContext},v=r=>{if(r===void 0){e.router.batch(()=>{u(),d()});return}(en(r)||Wt(r))&&(u(),un(e,n,r)),e.router.batch(()=>{u(),e.updateMatch(t,e=>({...e,__beforeLoadContext:r})),d()})},y;try{if(y=r.options.beforeLoad(_),Qe(y))return u(),y.catch(t=>{un(e,n,t)}).then(v)}catch(t){u(),un(e,n,t)}v(y)},mn=(e,t)=>{let{id:n,routeId:r}=e.matches[t],i=e.router.looseRoutesById[r],a=()=>s(),o=()=>pn(e,n,t,i),s=()=>{if(cn(e,n))return;let t=fn(e,n,i);return Qe(t)?t.then(o):o()};return a()},hn=(e,t,n)=>{let r=e.router.getMatch(t);if(!r||!n.options.head&&!n.options.scripts&&!n.options.headers)return;let i={ssr:e.router.options.ssr,matches:e.matches,match:r,params:r.params,loaderData:r.loaderData};return Promise.all([n.options.head?.(i),n.options.scripts?.(i),n.options.headers?.(i)]).then(([e,t,n])=>({meta:e?.meta,links:e?.links,headScripts:e?.scripts,headers:n,scripts:t,styles:e?.styles}))},gn=(e,t,n,r,i)=>{let a=t[r-1],{params:o,loaderDeps:s,abortController:c,cause:l}=e.router.getMatch(n),u=an(e,r),d=rn(e,n);return{params:o,deps:s,preload:!!d,parentMatchPromise:a,abortController:c,context:u,location:e.location,navigate:t=>e.router.navigate({...t,_fromLocation:e.location}),cause:d?`preload`:l,route:i,...e.router.options.additionalContext}},_n=async(e,t,n,r,i)=>{try{let a=e.router.getMatch(n);try{xn(i);let o=i.options.loader,s=typeof o==`function`?o:o?.handler,c=s?.(gn(e,t,n,r,i)),l=!!s&&Qe(c);if((l||i._lazyPromise||i._componentsPromise||i.options.head||i.options.scripts||i.options.headers||a._nonReactive.minPendingPromise)&&e.updateMatch(n,e=>({...e,isFetching:`loader`})),s){let t=l?await c:c;sn(e,e.router.getMatch(n),t),t!==void 0&&e.updateMatch(n,e=>({...e,loaderData:t}))}i._lazyPromise&&await i._lazyPromise;let u=a._nonReactive.minPendingPromise;u&&await u,i._componentsPromise&&await i._componentsPromise,e.updateMatch(n,t=>({...t,error:void 0,context:an(e,r),status:`success`,isFetching:!1,updatedAt:Date.now()}))}catch(t){let o=t;if(o?.name===`AbortError`){if(a.abortController.signal.aborted){a._nonReactive.loaderPromise?.resolve(),a._nonReactive.loaderPromise=void 0;return}e.updateMatch(n,t=>({...t,status:t.status===`pending`?`success`:t.status,isFetching:!1,context:an(e,r)}));return}let s=a._nonReactive.minPendingPromise;s&&await s,Wt(t)&&await i.options.notFoundComponent?.preload?.(),sn(e,e.router.getMatch(n),t);try{i.options.onError?.(t)}catch(t){o=t,sn(e,e.router.getMatch(n),t)}!en(o)&&!Wt(o)&&await xn(i,[`errorComponent`]),e.updateMatch(n,t=>({...t,error:o,context:an(e,r),status:`error`,isFetching:!1}))}}catch(t){let r=e.router.getMatch(n);r&&(r._nonReactive.loaderPromise=void 0),sn(e,r,t)}},vn=async(e,t,n)=>{async function r(r,a,c,l,d){let f=Date.now()-a.updatedAt,p=r?d.options.preloadStaleTime??e.router.options.defaultPreloadStaleTime??3e4:d.options.staleTime??e.router.options.defaultStaleTime??0,m=d.options.shouldReload,h=typeof m==`function`?m(gn(e,t,i,n,d)):m,{status:g,invalid:_}=l,v=f>=p&&(!!e.forceStaleReload||l.cause===`enter`||c!==void 0&&c!==l.id);o=g===`success`&&(_||(h??v)),r&&d.options.preload===!1||(o&&!e.sync&&u?(s=!0,(async()=>{try{await _n(e,t,i,n,d);let r=e.router.getMatch(i);r._nonReactive.loaderPromise?.resolve(),r._nonReactive.loadPromise?.resolve(),r._nonReactive.loaderPromise=void 0,r._nonReactive.loadPromise=void 0}catch(t){en(t)&&await e.router.navigate(t.options)}})()):g!==`success`||o?await _n(e,t,i,n,d):ln(e,i,n))}let{id:i,routeId:a}=e.matches[n],o=!1,s=!1,c=e.router.looseRoutesById[a],l=c.options.loader,u=((typeof l==`function`?void 0:l?.staleReloadMode)??e.router.options.defaultStaleReloadMode)!==`blocking`;if(cn(e,i)){if(!e.router.getMatch(i))return e.matches[n];ln(e,i,n)}else{let t=e.router.getMatch(i),o=e.router.stores.matchesId.get()[n],s=(o&&e.router.stores.matchStores.get(o)||null)?.routeId===a?o:e.router.stores.matches.get().find(e=>e.routeId===a)?.id,l=rn(e,i);if(t._nonReactive.loaderPromise){if(t.status===`success`&&!e.sync&&!t.preload&&u)return t;await t._nonReactive.loaderPromise;let n=e.router.getMatch(i),a=n._nonReactive.error||n.error;a&&sn(e,n,a),n.status===`pending`&&await r(l,t,s,n,c)}else{let n=l&&!e.router.stores.matchStores.has(i),a=e.router.getMatch(i);a._nonReactive.loaderPromise=Ze(),n!==a.preload&&e.updateMatch(i,e=>({...e,preload:n})),await r(l,t,s,a,c)}}let d=e.router.getMatch(i);s||(d._nonReactive.loaderPromise?.resolve(),d._nonReactive.loadPromise?.resolve(),d._nonReactive.loadPromise=void 0),clearTimeout(d._nonReactive.pendingTimeout),d._nonReactive.pendingTimeout=void 0,s||(d._nonReactive.loaderPromise=void 0),d._nonReactive.dehydrated=void 0;let f=s?d.isFetching:!1;return f!==d.isFetching||d.invalid!==!1?(e.updateMatch(i,e=>({...e,isFetching:f,invalid:!1})),e.router.getMatch(i)):d};async function yn(e){let t=e,n=[];nn(t.router)&&tn(t);let r;for(let e=0;e({...e,...a?{status:`success`,globalNotFound:!0,error:void 0}:{status:`notFound`,error:l},isFetching:!1})),u=e,await xn(r,[`notFoundComponent`])}else if(!t.preload){let e=t.matches[0];e.globalNotFound||t.router.getMatch(e.id)?.globalNotFound&&t.updateMatch(e.id,e=>({...e,globalNotFound:!1,error:void 0}))}if(t.serialError&&t.firstBadMatchIndex!==void 0){let e=t.router.looseRoutesById[t.matches[t.firstBadMatchIndex].routeId];await xn(e,[`errorComponent`])}for(let e=0;e<=u;e++){let{id:n,routeId:r}=t.matches[e],i=t.router.looseRoutesById[r];try{let e=hn(t,n,i);if(e){let r=await e;t.updateMatch(n,e=>({...e,...r}))}}catch(e){console.error(`Error executing head for route ${r}:`,e)}}let d=tn(t);if(Qe(d)&&await d,l)throw l;if(t.serialError&&!t.preload&&!t.onReady)throw t.serialError;return t.matches}function bn(e,t){let n=t.map(t=>e.options[t]?.preload?.()).filter(Boolean);if(n.length!==0)return Promise.all(n)}function xn(e,t=Cn){!e._lazyLoaded&&e._lazyPromise===void 0&&(e.lazyFn?e._lazyPromise=e.lazyFn().then(t=>{let{id:n,...r}=t.options;Object.assign(e.options,r),e._lazyLoaded=!0,e._lazyPromise=void 0}):e._lazyLoaded=!0);let n=()=>e._componentsLoaded?void 0:t===Cn?(()=>{if(e._componentsPromise===void 0){let t=bn(e,Cn);t?e._componentsPromise=t.then(()=>{e._componentsLoaded=!0,e._componentsPromise=void 0}):e._componentsLoaded=!0}return e._componentsPromise})():bn(e,t);return e._lazyPromise?e._lazyPromise.then(n):n()}function Sn(e){for(let t of Cn)if(e.options[t]?.preload)return!0;return!1}var Cn=[`component`,`errorComponent`,`pendingComponent`,`notFoundComponent`];function wn(e){return{input:({url:t})=>{for(let n of e)t=En(n,t);return t},output:({url:t})=>{for(let n=e.length-1;n>=0;n--)t=Dn(e[n],t);return t}}}function Tn(e){let t=It(e.basepath),n=`/${t}`,r=e.caseSensitive?n:n.toLowerCase(),i=`${r}/`;return{input:({url:t})=>{let a=e.caseSensitive?t.pathname:t.pathname.toLowerCase();return a===r?t.pathname=`/`:a.startsWith(i)&&(t.pathname=t.pathname.slice(n.length)),t},output:({url:e})=>(e.pathname=Mt([`/`,t,e.pathname]),e)}}function En(e,t){let n=e?.input?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function Dn(e,t){let n=e?.output?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function On(e,t){let{createMutableStore:n,createReadonlyStore:r,batch:i,init:a}=t,o=new Map,s=new Map,c=new Map,l=n(e.status),u=n(e.loadedAt),d=n(e.isLoading),f=n(e.isTransitioning),p=n(e.location),m=n(e.resolvedLocation),h=n(e.statusCode),g=n(e.redirect),_=n([]),v=n([]),y=n([]),b=r(()=>kn(o,_.get())),x=r(()=>kn(s,v.get())),S=r(()=>kn(c,y.get())),C=r(()=>_.get()[0]),w=r(()=>_.get().some(e=>o.get(e)?.get().status===`pending`)),T=r(()=>({locationHref:p.get().href,resolvedLocationHref:m.get()?.href,status:l.get()})),E=r(()=>({status:l.get(),loadedAt:u.get(),isLoading:d.get(),isTransitioning:f.get(),matches:b.get(),location:p.get(),resolvedLocation:m.get(),statusCode:h.get(),redirect:g.get()})),D=st(64);function O(e){let t=D.get(e);return t||(t=r(()=>{let t=_.get();for(let n of t){let t=o.get(n);if(t&&t.routeId===e)return t.get()}}),D.set(e,t)),t}let ee={status:l,loadedAt:u,isLoading:d,isTransitioning:f,location:p,resolvedLocation:m,statusCode:h,redirect:g,matchesId:_,pendingIds:v,cachedIds:y,matches:b,pendingMatches:x,cachedMatches:S,firstId:C,hasPending:w,matchRouteDeps:T,matchStores:o,pendingMatchStores:s,cachedMatchStores:c,__store:E,getRouteMatchStore:O,setMatches:te,setPending:ne,setCached:k};te(e.matches),a?.(ee);function te(e){An(e,o,_,n,i)}function ne(e){An(e,s,v,n,i)}function k(e){An(e,c,y,n,i)}return ee}function kn(e,t){let n=[];for(let r of t){let t=e.get(r);t&&n.push(t.get())}return n}function An(e,t,n,r,i){let a=e.map(e=>e.id),o=new Set(a);i(()=>{for(let e of t.keys())o.has(e)||t.delete(e);for(let n of e){let e=t.get(n.id);if(!e){let e=r(n);e.routeId=n.routeId,t.set(n.id,e);continue}e.routeId=n.routeId,e.get()!==n&&e.set(n)}at(n.get(),a)||n.set(a)})}var jn=`__TSR_index`,Mn=`popstate`,Nn=`beforeunload`;function Pn(e){let t=e.getLocation(),n=new Set,r=r=>{t=e.getLocation(),n.forEach(e=>e({location:t,action:r}))},i=n=>{e.notifyOnIndexChange??!0?r(n):t=e.getLocation()},a=async({task:n,navigateOpts:r,...i})=>{if(r?.ignoreBlocker??!1){n();return}let a=e.getBlockers?.()??[],o=i.type===`PUSH`||i.type===`REPLACE`;if(typeof document<`u`&&a.length&&o)for(let n of a){let r=Rn(i.path,i.state);if(await n.blockerFn({currentLocation:t,nextLocation:r,action:i.type})){e.onBlocked?.();return}}n()};return{get location(){return t},get length(){return e.getLength()},subscribers:n,subscribe:e=>(n.add(e),()=>{n.delete(e)}),push:(n,i,o)=>{let s=t.state[jn];i=Fn(s+1,i),a({task:()=>{e.pushState(n,i),r({type:`PUSH`})},navigateOpts:o,type:`PUSH`,path:n,state:i})},replace:(n,i,o)=>{let s=t.state[jn];i=Fn(s,i),a({task:()=>{e.replaceState(n,i),r({type:`REPLACE`})},navigateOpts:o,type:`REPLACE`,path:n,state:i})},go:(t,n)=>{a({task:()=>{e.go(t),i({type:`GO`,index:t})},navigateOpts:n,type:`GO`})},back:t=>{a({task:()=>{e.back(t?.ignoreBlocker??!1),i({type:`BACK`})},navigateOpts:t,type:`BACK`})},forward:t=>{a({task:()=>{e.forward(t?.ignoreBlocker??!1),i({type:`FORWARD`})},navigateOpts:t,type:`FORWARD`})},canGoBack:()=>t.state[jn]!==0,createHref:t=>e.createHref(t),block:t=>{if(!e.setBlockers)return()=>{};let n=e.getBlockers?.()??[];return e.setBlockers([...n,t]),()=>{let n=e.getBlockers?.()??[];e.setBlockers?.(n.filter(e=>e!==t))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:r}}function Fn(e,t){t||={};let n=zn();return{...t,key:n,__TSR_key:n,[jn]:e}}function In(e){let t=e?.window??(typeof document<`u`?window:void 0),n=t.history.pushState,r=t.history.replaceState,i=[],a=()=>i,o=e=>i=e,s=e?.createHref??(e=>e),c=e?.parseLocation??(()=>Rn(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){let e=zn();t.history.replaceState({[jn]:0,key:e,__TSR_key:e},``)}let l=c(),u,d=!1,f=!1,p=!1,m=!1,h=()=>l,g,_,v=()=>{g&&(C._ignoreSubscribers=!0,(g.isPush?t.history.pushState:t.history.replaceState)(g.state,``,g.href),C._ignoreSubscribers=!1,g=void 0,_=void 0,u=void 0)},y=(e,t,n)=>{let r=s(t);_||(u=l),l=Rn(t,n),g={href:r,state:n,isPush:g?.isPush||e===`push`},_||=Promise.resolve().then(()=>v())},b=e=>{l=c(),C.notify({type:e})},x=async()=>{if(f){f=!1;return}let e=c(),n=e.state[jn]-l.state[jn],r=n===1,i=n===-1,o=!r&&!i||d;d=!1;let s=o?`GO`:i?`BACK`:`FORWARD`,u=o?{type:`GO`,index:n}:{type:i?`BACK`:`FORWARD`};if(p)p=!1;else{let n=a();if(typeof document<`u`&&n.length){for(let r of n)if(await r.blockerFn({currentLocation:l,nextLocation:e,action:s})){f=!0,t.history.go(1),C.notify(u);return}}}l=c(),C.notify(u)},S=e=>{if(m){m=!1;return}let t=!1,n=a();if(typeof document<`u`&&n.length)for(let e of n){let n=e.enableBeforeUnload??!0;if(n===!0){t=!0;break}if(typeof n==`function`&&n()===!0){t=!0;break}}if(t)return e.preventDefault(),e.returnValue=``},C=Pn({getLocation:h,getLength:()=>t.history.length,pushState:(e,t)=>y(`push`,e,t),replaceState:(e,t)=>y(`replace`,e,t),back:e=>(e&&(p=!0),m=!0,t.history.back()),forward:e=>{e&&(p=!0),m=!0,t.history.forward()},go:e=>{d=!0,t.history.go(e)},createHref:e=>s(e),flush:v,destroy:()=>{t.history.pushState=n,t.history.replaceState=r,t.removeEventListener(Nn,S,{capture:!0}),t.removeEventListener(Mn,x)},onBlocked:()=>{u&&l!==u&&(l=u)},getBlockers:a,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(Nn,S,{capture:!0}),t.addEventListener(Mn,x),t.history.pushState=function(...e){let r=n.apply(t.history,e);return C._ignoreSubscribers||b(`PUSH`),r},t.history.replaceState=function(...e){let n=r.apply(t.history,e);return C._ignoreSubscribers||b(`REPLACE`),n},C}function Ln(e){let t=e.replace(/[\x00-\x1f\x7f]/g,``);return t.startsWith(`//`)&&(t=`/`+t.replace(/^\/+/,``)),t}function Rn(e,t){let n=Ln(e),r=n.indexOf(`#`),i=n.indexOf(`?`),a=zn();return{href:n,pathname:n.substring(0,r>0?i>0?Math.min(r,i):r:i>0?i:n.length),hash:r>-1?n.substring(r):``,search:i>-1?n.slice(i,r===-1?void 0:r):``,state:t||{[jn]:0,key:a,__TSR_key:a}}}function zn(){return(Math.random()+1).toString(36).substring(7)}function Bn(e,t){let n=t,r=e;return{fromLocation:n,toLocation:r,pathChanged:n?.pathname!==r.pathname,hrefChanged:n?.href!==r.href,hashChanged:n?.hash!==r.hash}}var Vn=new WeakMap,Hn=class{constructor(e,t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this.resetNextScroll=!0,this.shouldViewTransition=void 0,this.isViewTransitionTypesSupported=void 0,this.subscribers=new Set,this.isScrollRestoring=!1,this.isScrollRestorationSetup=!1,this.routeBranchCache=new WeakMap,this.startTransition=e=>e(),this.update=e=>{let t=this.options,n=this.basepath??t?.basepath??`/`,r=this.basepath===void 0,i=t?.rewrite;if(this.options={...t,...e},this.isServer=this.options.isServer??typeof document>`u`,this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=Bt(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.history=this.options.history?this.options.history:In()),this.origin=this.options.origin,this.origin||=window?.origin&&window.origin!==`null`?window.origin:`http://localhost`,this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let e;this.resolvePathCache=st(1e3),e=this.buildRouteTree(),this.setRoutes(e)}if(!this.stores&&this.latestLocation){let e=this.getStoreConfig(this);this.batch=e.batch,this.stores=On(Gn(this.latestLocation),e),dr(this)}let a=!1,o=this.options.basepath??`/`,s=this.options.rewrite;if(r||n!==o||i!==s){this.basepath=o;let e=[],t=It(o);t&&t!==`/`&&e.push(Tn({basepath:o})),s&&e.push(s),this.rewrite=e.length===0?void 0:e.length===1?e[0]:wn(e),this.history&&this.updateLatestLocation(),a=!0}a&&this.stores&&this.stores.location.set(this.latestLocation),typeof window<`u`&&`CSS`in window&&typeof window.CSS?.supports==`function`&&(this.isViewTransitionTypesSupported=window.CSS.supports(`selector(:active-view-transition-type(a))`))},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{let e=St(this.routeTree,this.options.caseSensitive,(e,t)=>{e.init({originalIndex:t})});return this.options.routeMasks&&_t(this.options.routeMasks,e.processedTree),e},this.subscribe=(e,t)=>{let n={eventType:e,fn:t};return this.subscribers.add(n),()=>{this.subscribers.delete(n)}},this.emit=e=>{this.subscribers.forEach(t=>{t.eventType===e.type&&t.fn(e)})},this.parseLocation=(e,t)=>{let n=({pathname:e,search:n,hash:r,href:i,state:a})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(e)){let i=this.options.parseSearch(n),o=this.options.stringifySearch(i);return{href:e+o+r,publicHref:e+o+r,pathname:rt(e).path,external:!1,searchStr:o,search:We(t?.search,i),hash:rt(r.slice(1)).path,state:Ge(t?.state,a)}}let o=new URL(i,this.origin),s=En(this.rewrite,o),c=this.options.parseSearch(s.search),l=this.options.stringifySearch(c);return s.search=l,{href:s.href.replace(s.origin,``),publicHref:i,pathname:rt(s.pathname).path,external:!!this.rewrite&&s.origin!==this.origin,searchStr:l,search:We(t?.search,c),hash:rt(s.hash.slice(1)).path,state:Ge(t?.state,a)}},r=n(e),{__tempLocation:i,__tempKey:a}=r.state;if(i&&(!a||a===this.tempLocationKey)){let e=n(i);return e.state.key=r.state.key,e.state.__TSR_key=r.state.__TSR_key,delete e.state.__tempLocation,{...e,maskedLocation:r}}return r},this.resolvePathWithBase=(e,t)=>zt({base:e,to:t.includes(`//`)?Nt(t):t,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(e,t,n)=>typeof e==`string`?this.matchRoutesInternal({pathname:e,search:t},n):this.matchRoutesInternal(e,t),this.getMatchedRoutes=e=>qn({pathname:e,routesById:this.routesById,processedTree:this.processedTree}),this.cancelMatch=e=>{let t=this.getMatch(e);t&&(t.abortController.abort(),clearTimeout(t._nonReactive.pendingTimeout),t._nonReactive.pendingTimeout=void 0)},this.cancelMatches=()=>{this.stores.pendingIds.get().forEach(e=>{this.cancelMatch(e)}),this.stores.matchesId.get().forEach(e=>{if(this.stores.pendingMatchStores.has(e))return;let t=this.stores.matchStores.get(e)?.get();t&&(t.status===`pending`||t.isFetching===`loader`)&&this.cancelMatch(e)})},this.buildLocation=e=>{let t=(t={})=>{let n=t._fromLocation||this.pendingBuiltLocation||this.latestLocation,r=this.matchRoutesLightweight(n);t.from;let i=t.unsafeRelative===`path`?n.pathname:t.from??r.fullPath,a=t.to?`${t.to}`:void 0,o=r.search,s=Object.assign(Object.create(null),r.params),c=a?.charCodeAt(0)===47?`/`:this.resolvePathWithBase(i,`.`),l=a?this.resolvePathWithBase(c,a):c,u=t.params===!1||t.params===null?Object.create(null):(t.params??!0)===!0?s:Object.assign(s,ze(t.params,s)),d=this.routesByPath[Ft(l)],f;if(d)f=this.getRouteBranch(d);else if(l.includes(`$`))f=[];else{let e=this.getMatchedRoutes(l);f=e.matchedRoutes,this.options.notFoundRoute&&(!e.foundRoute||e.foundRoute.path!==`/`&&e.routeParams[`**`])&&(f=[...f,this.options.notFoundRoute])}if(f.length&&He(u))for(let e of f){let t=e.options.params?.stringify??e.options.stringifyParams;if(t)try{Object.assign(u,t(u))}catch{}}let p=e.leaveParams?l:rt(Ht({path:l,params:u,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path,m=o;if(e._includeValidateSearch&&this.options.search?.strict){let e={};f.forEach(t=>{if(t.options.validateSearch)try{Object.assign(e,Kn(t.options.validateSearch,{...e,...m}))}catch{}}),m=e}m=Jn({search:m,dest:t,destRoutes:f,_includeValidateSearch:e._includeValidateSearch}),m=We(o,m);let h=this.options.stringifySearch(m),g=t.hash===!0?n.hash:t.hash?ze(t.hash,n.hash):void 0,_=g?`#${g}`:``,v=t.state===!0?n.state:t.state?ze(t.state,n.state):{};v=Ge(n.state,v);let y=`${p}${h}${_}`,b,x,S=!1;if(this.rewrite){let e=new URL(y,this.origin),t=Dn(this.rewrite,e);b=e.href.replace(e.origin,``),t.origin===this.origin?x=t.pathname+t.search+t.hash:(x=t.href,S=!0)}else b=it(y),x=b;return{publicHref:x,href:b,pathname:p,search:m,searchStr:h,state:v,hash:g??``,external:S,unmaskOnReload:t.unmaskOnReload}},n=(n={},r)=>{let i=t(n),a=r?t(r):void 0;if(!a){let n=Object.create(null);if(this.options.routeMasks){let o=vt(i.pathname,this.processedTree);if(o){Object.assign(n,o.rawParams);let{from:i,params:s,...c}=o.route,l=s===!1||s===null?Object.create(null):(s??!0)===!0?n:Object.assign(n,ze(s,n));r={from:e.from,...c,params:l},a=t(r)}}}return a&&(i.maskedLocation=a),i};return e.mask?n(e,{from:e.from,...e.mask}):n(e)},this.commitLocation=async({viewTransition:e,ignoreBlocker:t,...n})=>{let r,i=()=>{let e=[`key`,`__TSR_key`,`__TSR_index`,`__hashScrollIntoViewOptions`];e.forEach(e=>{n.state[e]=this.latestLocation.state[e]});let t=Xe(n.state,this.latestLocation.state);return e.forEach(e=>{delete n.state[e]}),t},a=Ft(this.latestLocation.href)===Ft(n.href),o=this.commitLocationPromise;if(this.commitLocationPromise=Ze(()=>{o?.resolve(),o=void 0}),a&&i())this.load();else{let{maskedLocation:i,hashScrollIntoView:a,...o}=n;i&&(o={...i,state:{...i.state,__tempKey:void 0,__tempLocation:{...o,search:o.searchStr,state:{...o.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(o.unmaskOnReload??this.options.unmaskOnReload??!1)&&(o.state.__tempKey=this.tempLocationKey)),o.state.__hashScrollIntoViewOptions=a??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=e,r=n.replace?`REPLACE`:`PUSH`,this.history[r===`REPLACE`?`replace`:`push`](o.publicHref,o.state,{ignoreBlocker:t})}return this.resetNextScroll=n.resetScroll??!0,this.history.subscribers.size||this.load(r?{action:{type:r}}:void 0),this.commitLocationPromise},this.buildAndCommitLocation=({replace:e,resetScroll:t,hashScrollIntoView:n,viewTransition:r,ignoreBlocker:i,href:a,...o}={})=>{if(a){let t=this.history.location.state.__TSR_index,n=Rn(a,{__TSR_index:e?t:t+1}),r=new URL(n.pathname,this.origin);o.to=En(this.rewrite,r).pathname,o.search=this.options.parseSearch(n.search),o.hash=n.hash.slice(1)}let s=this.buildLocation({...o,_includeValidateSearch:!0});this.pendingBuiltLocation=s;let c=this.commitLocation({...s,viewTransition:r,replace:e,resetScroll:t,hashScrollIntoView:n,ignoreBlocker:i});return Promise.resolve().then(()=>{this.pendingBuiltLocation===s&&(this.pendingBuiltLocation=void 0)}),c},this.navigate=async({to:e,reloadDocument:t,href:n,publicHref:r,...i})=>{let a=!1;if(n)try{new URL(`${n}`),a=!0}catch{}if(a&&!t&&(t=!0),t){if(e!==void 0||!n){let t=this.buildLocation({to:e,...i});n??=t.publicHref,r??=t.publicHref}let t=!a&&r?r:n;if(nt(t,this.protocolAllowlist))return Promise.resolve();if(!i.ignoreBlocker){let e=this.history.getBlockers?.()??[];for(let t of e)if(t?.blockerFn&&await t.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:`PUSH`}))return Promise.resolve()}return i.replace?window.location.replace(t):window.location.href=t,Promise.resolve()}return this.buildAndCommitLocation({...i,href:n,to:e,_isNavigate:!0})},this.beforeLoad=()=>{this.cancelMatches(),this.updateLatestLocation();let e=this.matchRoutes(this.latestLocation),t=this.stores.cachedMatches.get().filter(t=>!e.some(e=>e.id===t.id));this.batch(()=>{this.stores.status.set(`pending`),this.stores.statusCode.set(200),this.stores.isLoading.set(!0),this.stores.location.set(this.latestLocation),this.stores.setPending(e),this.stores.setCached(t)})},this.load=async e=>{let t=e?.action?.type,n,r,i,a=this.stores.resolvedLocation.get()??this.stores.location.get();for(i=new Promise(o=>{this.startTransition(async()=>{try{this.beforeLoad(),t?Vn.set(this.latestLocation,t):Vn.delete(this.latestLocation);let n=this.latestLocation,r=Bn(n,this.stores.resolvedLocation.get());this.stores.redirect.get()||this.emit({type:`onBeforeNavigate`,...r}),this.emit({type:`onBeforeLoad`,...r}),await yn({router:this,sync:e?.sync,forceStaleReload:a.href===n.href,matches:this.stores.pendingMatches.get(),location:n,updateMatch:this.updateMatch,onReady:async()=>{this.startTransition(()=>{this.startViewTransition(async()=>{let e=null,t=null,n=null,r=null;this.batch(()=>{let i=this.stores.pendingMatches.get(),a=i.length,o=this.stores.matches.get();e=a?o.filter(e=>!this.stores.pendingMatchStores.has(e.id)):null;let s=new Set;for(let e of this.stores.pendingMatchStores.values())e.routeId&&s.add(e.routeId);let c=new Set;for(let e of this.stores.matchStores.values())e.routeId&&c.add(e.routeId);t=a?o.filter(e=>!s.has(e.routeId)):null,n=a?i.filter(e=>!c.has(e.routeId)):null,r=a?i.filter(e=>c.has(e.routeId)):o,this.stores.isLoading.set(!1),this.stores.loadedAt.set(Date.now()),a&&(this.stores.setMatches(i),this.stores.setPending([]),this.stores.setCached([...this.stores.cachedMatches.get(),...e.filter(e=>e.status!==`error`&&e.status!==`notFound`&&e.status!==`redirected`)]),this.clearExpiredCache())});for(let[e,i]of[[t,`onLeave`],[n,`onEnter`],[r,`onStay`]])if(e)for(let t of e)this.looseRoutesById[t.routeId].options[i]?.(t)})})}})}catch(e){en(e)?(n=e,this.navigate({...n.options,replace:!0,ignoreBlocker:!0})):Wt(e)&&(r=e);let t=n?n.status:r?404:this.stores.matches.get().some(e=>e.status===`error`)?500:200;this.batch(()=>{this.stores.statusCode.set(t),this.stores.redirect.set(n)})}this.latestLoadPromise===i&&(this.commitLocationPromise?.resolve(),this.latestLoadPromise=void 0,this.commitLocationPromise=void 0),o()})}),this.latestLoadPromise=i,await i;this.latestLoadPromise&&i!==this.latestLoadPromise;)await this.latestLoadPromise;let o;this.hasNotFoundMatch()?o=404:this.stores.matches.get().some(e=>e.status===`error`)&&(o=500),o!==void 0&&this.stores.statusCode.set(o)},this.startViewTransition=e=>{let t=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,t&&typeof document<`u`&&`startViewTransition`in document&&typeof document.startViewTransition==`function`){let n;if(typeof t==`object`&&this.isViewTransitionTypesSupported){let r=this.latestLocation,i=this.stores.resolvedLocation.get(),a=typeof t.types==`function`?t.types(Bn(r,i)):t.types;if(a===!1){e();return}n={update:e,types:a}}else n=e;document.startViewTransition(n)}else e()},this.updateMatch=(e,t)=>{this.startTransition(()=>{let n=this.stores.pendingMatchStores.get(e);if(n){n.set(t);return}let r=this.stores.matchStores.get(e);if(r){r.set(t);return}let i=this.stores.cachedMatchStores.get(e);if(i){let n=t(i.get());n.status===`redirected`?this.stores.cachedMatchStores.delete(e)&&this.stores.cachedIds.set(t=>t.filter(t=>t!==e)):i.set(n)}})},this.getMatch=e=>this.stores.cachedMatchStores.get(e)?.get()??this.stores.pendingMatchStores.get(e)?.get()??this.stores.matchStores.get(e)?.get(),this.invalidate=e=>{let t=t=>e?.filter?.(t)??!0?{...t,invalid:!0,...e?.forcePending||t.status===`error`||t.status===`notFound`?{status:`pending`,error:void 0}:void 0}:t;return this.batch(()=>{this.stores.setMatches(this.stores.matches.get().map(t)),this.stores.setCached(this.stores.cachedMatches.get().map(t)),this.stores.setPending(this.stores.pendingMatches.get().map(t))}),this.shouldViewTransition=!1,this.load({sync:e?.sync})},this.getParsedLocationHref=e=>e.publicHref||`/`,this.resolveRedirect=e=>{let t=e.headers.get(`Location`);if(!e.options.href||e.options._builtLocation){let t=e.options._builtLocation??this.buildLocation(e.options),n=this.getParsedLocationHref(t);e.options.href=n,e.headers.set(`Location`,n)}else if(t)try{let n=new URL(t);if(this.origin&&n.origin===this.origin){let t=n.pathname+n.search+n.hash;e.options.href=t,e.headers.set(`Location`,t)}}catch{}if(e.options.href&&!e.options._builtLocation&&nt(e.options.href,this.protocolAllowlist))throw Error(`Redirect blocked: unsafe protocol`);return e.headers.get(`Location`)||e.headers.set(`Location`,e.options.href),e},this.clearCache=e=>{let t=e?.filter;t===void 0?this.stores.setCached([]):this.stores.setCached(this.stores.cachedMatches.get().filter(e=>!t(e)))},this.clearExpiredCache=()=>{let e=Date.now();this.clearCache({filter:t=>{let n=this.looseRoutesById[t.routeId];if(!n.options.loader)return!0;let r=(t.preload?n.options.preloadGcTime??this.options.defaultPreloadGcTime:n.options.gcTime??this.options.defaultGcTime)??3e5;return t.status===`error`||e-t.updatedAt>=r}})},this.loadRouteChunk=xn,this.preloadRoute=async e=>{let t=e._builtLocation??this.buildLocation(e),n=this.matchRoutes(t,{throwOnError:!0,preload:!0,dest:e}),r=new Set([...this.stores.matchesId.get(),...this.stores.pendingIds.get()]),i=new Set([...r,...this.stores.cachedIds.get()]),a=n.filter(e=>!i.has(e.id));if(a.length){let e=this.stores.cachedMatches.get();this.stores.setCached([...e,...a])}try{return n=await yn({router:this,matches:n,location:t,preload:!0,updateMatch:(e,t)=>{r.has(e)?n=n.map(n=>n.id===e?t(n):n):this.updateMatch(e,t)}}),n}catch(e){if(en(e))return e.options.reloadDocument?void 0:await this.preloadRoute({...e.options,_fromLocation:t});Wt(e)||console.error(e);return}},this.matchRoute=(e,t)=>{let n={...e,to:e.to?this.resolvePathWithBase(e.from||``,e.to):void 0,params:e.params||{},leaveParams:!0},r=this.buildLocation(n);if(t?.pending&&this.stores.status.get()!==`pending`)return!1;let i=(t?.pending===void 0?!this.stores.isLoading.get():t.pending)?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),a=yt(r.pathname,t?.caseSensitive??!1,t?.fuzzy??!1,i.pathname,this.processedTree);return!a||e.params&&!Xe(a.rawParams,e.params,{partial:!0})?!1:t?.includeSearch??!0?Xe(i.search,r.search,{partial:!0})?a.rawParams:!1:a.rawParams},this.hasNotFoundMatch=()=>this.stores.matches.get().some(e=>e.status===`notFound`||e.globalNotFound),this.getStoreConfig=t,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??`fuzzy`,stringifySearch:e.stringifySearch??Yt,parseSearch:e.parseSearch??Jt,protocolAllowlist:e.protocolAllowlist??tt}),typeof document<`u`&&(self.__TSR_ROUTER__=this)}isShell(){return!!this.options.isShell}isPrerendering(){return!!this.options.isPrerendering}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:n}){this.routesById=e,this.routesByPath=t,this.processedTree=n;let r=this.options.notFoundRoute;r&&(r.init({originalIndex:99999999999}),this.routesById[r.id]=r)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=Tt(e),this.routeBranchCache.set(e,t)),t}get looseRoutesById(){return this.routesById}getParentContext(e){return e?.id?e.context??this.options.context??void 0:this.options.context??void 0}matchRoutesInternal(e,t){let n=this.getMatchedRoutes(e.pathname),{foundRoute:r,routeParams:i}=n,{matchedRoutes:a}=n,o=!1;(r?r.path!==`/`&&i[`**`]:Ft(e.pathname))&&(this.options.notFoundRoute?a=[...a,this.options.notFoundRoute]:o=!0);let s=o?Xn(this.options.notFoundMode,a):void 0,c=Array(a.length),l=new Map;for(let e of this.stores.matchStores.values())e.routeId&&l.set(e.routeId,e.get());for(let n=0;nthis.navigate({...t,_fromLocation:e}),buildLocation:this.buildLocation,cause:n.cause,abortController:n.abortController,preload:!!n.preload,matches:c,routeId:r.id};n.__routeContext=r.options.context(t)??void 0}n.context={...a,...n.__routeContext,...n.__beforeLoadContext}}}return c}matchRoutesLightweight(e){let{matchedRoutes:t,routeParams:n}=this.getMatchedRoutes(e.pathname),r=Le(t),i={...e.search};for(let e of t)try{Object.assign(i,Kn(e.options.validateSearch,i))}catch{}let a=Le(this.stores.matchesId.get()),o=a&&this.stores.matchStores.get(a)?.get(),s=o&&o.routeId===r.id&&o.pathname===e.pathname,c;if(s)c=o.params;else{let e=Object.assign(Object.create(null),n);for(let n of t)try{Zn(n,e)}catch{}c=e}return{matchedRoutes:t,fullPath:r.fullPath,search:i,params:c}}},Un=class extends Error{},Wn=class extends Error{};function Gn(e){return{loadedAt:0,isLoading:!1,isTransitioning:!1,status:`idle`,resolvedLocation:void 0,location:e,matches:[],statusCode:200}}function Kn(e,t){if(e==null)return{};if(`~standard`in e){let n=e[`~standard`].validate(t);if(n instanceof Promise)throw new Un(`Async validation not supported`);if(n.issues)throw new Un(JSON.stringify(n.issues,void 0,2),{cause:n});return n.value}return`parse`in e?e.parse(t):typeof e==`function`?e(t):{}}function qn({pathname:e,routesById:t,processedTree:n}){let r=Object.create(null),i=Ft(e),a,o=bt(i,n,!0);return o&&(a=o.route,Object.assign(r,o.rawParams)),{matchedRoutes:o?.branch||[t.__root__],routeParams:r,foundRoute:a}}function Jn({search:e,dest:t,destRoutes:n,_includeValidateSearch:r}){return Yn(n)(e,t,r??!1)}function Yn(e){let t={dest:null,_includeValidateSearch:!1,middlewares:[]};for(let n of e)`search`in n.options?n.options.search?.middlewares&&t.middlewares.push(...n.options.search.middlewares):(n.options.preSearchFilters||n.options.postSearchFilters)&&t.middlewares.push(({search:e,next:t})=>{let r=e;`preSearchFilters`in n.options&&n.options.preSearchFilters&&(r=n.options.preSearchFilters.reduce((e,t)=>t(e),e));let i=t(r);return`postSearchFilters`in n.options&&n.options.postSearchFilters?n.options.postSearchFilters.reduce((e,t)=>t(e),i):i}),n.options.validateSearch&&t.middlewares.push(({search:e,next:r})=>{let i=r(e);if(!t._includeValidateSearch)return i;try{return{...i,...Kn(n.options.validateSearch,i)??void 0}}catch{return i}});t.middlewares.push(({search:e})=>{let n=t.dest;return n.search?n.search===!0?e:ze(n.search,e):{}});let n=(e,t,r)=>{if(e>=r.length)return t;let i=r[e];return i({search:t,next:t=>n(e+1,t,r)})};return function(e,r,i){return t.dest=r,t._includeValidateSearch=i,n(0,e,t.middlewares)}}function Xn(e,t){if(e!==`root`)for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.children)return n.id}return Qt}function Zn(e,t){let n=e.options.params?.parse??e.options.parseParams;if(n){let e=n(t);if(e===!1)throw Error(`Route params.parse returned false for a matched route`);Object.assign(t,e)}}function Qn(){try{return sessionStorage}catch{return}}var $n=`tsr-scroll-restoration-v1_3`,er=Qn();function tr(){try{return JSON.parse(er?.getItem(`tsr-scroll-restoration-v1_3`)||`{}`)}catch{return{}}}function nr(){try{er?.setItem($n,JSON.stringify(rr))}catch{}}var rr=tr(),ir=`data-scroll-restoration-id`,ar=e=>e.state.__TSR_key||e.href;function or(e){let t=e.getAttribute(ir);if(t)return`[${ir}="${t}"]`;let n=``,r=e,i;for(;i=r.parentNode;){let e=1,t=r;for(;t=t.previousElementSibling;)e++;let a=`${r.localName}:nth-child(${e})`;n=n?`${a} > ${n}`:a,r=i}return n}var sr=!1,cr=`window`;function lr(e){try{return typeof e==`function`?e():document.querySelector(e)}catch{}}function ur(e){let t=[];for(let n of e){if(n===cr)continue;let e=lr(n);e&&t.push(e)}return t}function dr(e,t){if((t??e.options.scrollRestoration)&&(e.isScrollRestoring=!0),e.isScrollRestorationSetup)return;e.isScrollRestorationSetup=!0,sr=!1;let n=e.options.getScrollRestorationKey||ar,r=new Map,i=(e,t,n)=>{let i=r.get(e)||{};i.scrollX=t,i.scrollY=n,r.set(e,i)};history.scrollRestoration=`manual`;let a=t=>{if(!(sr||!e.isScrollRestoring)){if(t.target===document)i(cr,scrollX,scrollY);else{let e=t.target;i(e,e.scrollLeft,e.scrollTop)}}},o=t=>{if(!e.isScrollRestoring)return;let n=rr[t]||={};for(let[e,t]of r)e===cr?n[cr]=t:e.isConnected&&(n[or(e)]=t)};document.addEventListener(`scroll`,a,!0),e.subscribe(`onBeforeLoad`,e=>{e.fromLocation&&o(n(e.fromLocation)),r.clear()}),addEventListener(`pagehide`,()=>{o(n(e.stores.resolvedLocation.get()??e.stores.location.get())),nr()}),e.subscribe(`onRendered`,t=>{let i=e.options.scrollRestorationBehavior,a=e.options.scrollToTopSelectors,o=e.resetNextScroll,s;if(r.clear(),o||(e.resetNextScroll=!0),typeof e.options.scrollRestoration==`function`&&!e.options.scrollRestoration({location:e.latestLocation}))return;let c=n(t.toLocation),l=t.fromLocation&&n(t.fromLocation);if(e.isScrollRestoring&&l&&l!==c){let e=rr[l];if(e){let t=rr[c];for(let n in e){if(n===cr){if(o)continue}else{let e=lr(n);if(!e||o&&a&&(s??=ur(a),s.includes(e)))continue}t||=rr[c]={},t[n]??=e[n]}}}sr=!0;try{let n=t.toLocation.hash,r=t.toLocation.state.__hashScrollIntoViewOptions??!0,l=!1;if(o){let o=Vn.get(t.toLocation),u=n&&r&&(o===`PUSH`||o===`REPLACE`),d=e.isScrollRestoring?rr[c]:void 0;if(d)for(let e in d){let{scrollX:t,scrollY:n}=d[e];if(e===cr){if(u)continue;scrollTo({top:n,left:t,behavior:i}),l=!0}else{let r=lr(e);r&&(r.scrollLeft=t,r.scrollTop=n)}}if(!l&&!n){let e={top:0,left:0,behavior:i};if(scrollTo(e),a){s??=ur(a);for(let t of s)t.scrollTo(e)}}}!l&&n&&r&&document.getElementById(n)?.scrollIntoView(r)}finally{sr=!1}})}var fr=`Error preloading route! ☝️`,pr=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=e=>{this.originalIndex=e.originalIndex;let t=this.options,n=!t?.path&&!t?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=Qt:this.parentRoute||ot();let r=n?Qt:t?.path;r&&r!==`/`&&(r=Pt(r));let i=t?.id||r,a=n?Qt:Mt([this.parentRoute.id===`__root__`?``:this.parentRoute.id,i]);r===`__root__`&&(r=`/`),a!==`__root__`&&(a=Mt([`/`,a]));let o=a===`__root__`?`/`:Mt([this.parentRoute.fullPath,r]);this._path=r,this._id=a,this._fullPath=o,this._to=Ft(o)},this.addChildren=e=>this._addFileChildren(e),this._addFileChildren=e=>(Array.isArray(e)&&(this.children=e),typeof e==`object`&&e&&(this.children=Object.values(e)),this),this._addFileTypes=()=>this,this.updateLoader=e=>(Object.assign(this.options,e),this),this.update=e=>(Object.assign(this.options,e),this),this.lazy=e=>(this.lazyFn=e,this),this.redirect=e=>$t({from:this.fullPath,...e}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw Error(`Route cannot have both an 'id' and a 'path' option.`)}},mr=class extends pr{constructor(e){super(e)}};function hr(e){let t=e.errorComponent??_r;return(0,V.jsx)(gr,{getResetKey:e.getResetKey,onCatch:e.onCatch,children:({error:n,reset:r})=>n?B.createElement(t,{error:n,reset:r}):e.children})}var gr=class extends B.Component{constructor(...e){super(...e),this.state={error:null}}static getDerivedStateFromProps(e,t){let n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:null}:{resetKey:n}}static getDerivedStateFromError(e){return{error:e}}reset(){this.setState({error:null})}componentDidCatch(e,t){this.props.onCatch&&this.props.onCatch(e,t)}render(){return this.props.children({error:this.state.error,reset:()=>{this.reset()}})}};function _r({error:e}){let[t,n]=B.useState(!1);return(0,V.jsxs)(`div`,{style:{padding:`.5rem`,maxWidth:`100%`},children:[(0,V.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`.5rem`},children:[(0,V.jsx)(`strong`,{style:{fontSize:`1rem`},children:`Something went wrong!`}),(0,V.jsx)(`button`,{style:{appearance:`none`,fontSize:`.6em`,border:`1px solid currentColor`,padding:`.1rem .2rem`,fontWeight:`bold`,borderRadius:`.25rem`},onClick:()=>n(e=>!e),children:t?`Hide Error`:`Show Error`})]}),(0,V.jsx)(`div`,{style:{height:`.25rem`}}),t?(0,V.jsx)(`div`,{children:(0,V.jsx)(`pre`,{style:{fontSize:`.7em`,border:`1px solid red`,borderRadius:`.25rem`,padding:`.3rem`,color:`red`,overflow:`auto`},children:e.message?(0,V.jsx)(`code`,{children:e.message}):null})}):null]})}function vr({children:e,fallback:t=null}){return yr()?(0,V.jsx)(B.Fragment,{children:e}):(0,V.jsx)(B.Fragment,{children:t})}function yr(){return B.useSyncExternalStore(br,()=>!0,()=>!1)}function br(){return()=>{}}var xr=B.createContext(null);function Sr(e){return B.useContext(xr)}var Cr=B.createContext(void 0),wr=B.createContext(void 0),Tr=(e=>(e[e.None=0]=`None`,e[e.Mutable=1]=`Mutable`,e[e.Watching=2]=`Watching`,e[e.RecursedCheck=4]=`RecursedCheck`,e[e.Recursed=8]=`Recursed`,e[e.Dirty=16]=`Dirty`,e[e.Pending=32]=`Pending`,e))(Tr||{});function Er({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function Dr(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var Or=[],kr=0,{link:Ar,unlink:jr,propagate:Mr,checkDirty:Nr,shallowPropagate:Pr}=Er({update(e){return e._update()},notify(e){Or[Ir++]=e,e.flags&=~Tr.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=Tr.Mutable|Tr.Dirty,Br(e))}}),Fr=0,Ir=0,Lr,Rr=0;function zr(e){try{++Rr,e()}finally{--Rr||Vr()}}function Br(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=jr(n,e)}function Vr(){if(!(Rr>0)){for(;Fr{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=Lr,o=t?.compare??Object.is;if(n)Lr=i,++kr,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=Tr.Mutable|Tr.RecursedCheck);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{Lr=a,n&&(i.flags&=~Tr.RecursedCheck),Br(i)}}};return n?(i.flags=Tr.Mutable|Tr.Dirty,i.get=function(){let e=i.flags;if(e&Tr.Dirty||e&Tr.Pending&&Nr(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&Pr(e)}}else e&Tr.Pending&&(i.flags=e&~Tr.Pending);return Lr!==void 0&&Ar(i,Lr,kr),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(Mr(e),Pr(e),Vr())}},i}function Ur(e){let t=()=>{let t=Lr;Lr=n,++kr,n.depsTail=void 0,n.flags=Tr.Watching|Tr.RecursedCheck;try{return e()}finally{Lr=t,n.flags&=~Tr.RecursedCheck,Br(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:Tr.Watching|Tr.RecursedCheck,notify(){let e=this.flags;e&Tr.Dirty||e&Tr.Pending&&Nr(this.deps,this)?t():this.flags=Tr.Watching},stop(){this.flags=Tr.None,this.depsTail=void 0,Br(this)}};return t(),n}var Wr=o((e=>{var t=f();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 d=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?d:t.useSyncExternalStore})),Gr=o(((e,t)=>{t.exports=Wr()})),Kr=o((e=>{var t=f(),n=Gr();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}})),qr=o(((e,t)=>{t.exports=Kr()}))();function Jr(e,t){return e===t}function Yr(e,t,n=Jr){let r=(0,B.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,B.useCallback)(()=>e?.get(),[e]);return(0,qr.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var Xr={get:()=>void 0,subscribe:()=>({unsubscribe:()=>{}})};function Zr(e){let t=Sr(),n=B.useContext(e.from?wr:Cr),r=e.from??n,i=r?e.from?t.stores.getRouteMatchStore(r):t.stores.matchStores.get(r):void 0,a=B.useRef(void 0);return Yr(i??Xr,n=>{if((e.shouldThrow??!0)&&!n&&ot(),n===void 0)return;let r=e.select?e.select(n):n;if(e.structuralSharing??t.options.defaultStructuralSharing){let e=Ge(a.current,r);return a.current=e,e}return r})}function Qr(e){return Zr({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function $r(e){let{select:t,...n}=e;return Zr({...n,select:e=>t?t(e.loaderDeps):e.loaderDeps})}function ei(e){return Zr({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function ti(e){return Zr({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function ni(e){let t=Sr();return B.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function ri(e){let t=Sr(),n=ni(),r=B.useRef(null);return Pe(()=>{r.current!==e&&(n(e),r.current=e)},[t,e,n]),null}function ii(e){return Zr({...e,select:t=>e.select?e.select(t.context):t.context})}var ai=m();function oi(e,t){let n=Sr(),r=Ie(t),{activeProps:i,inactiveProps:a,activeOptions:o,to:s,preload:c,preloadDelay:l,preloadIntentProximity:u,hashScrollIntoView:d,replace:f,startTransition:p,resetScroll:m,viewTransition:h,children:g,target:_,disabled:v,style:y,className:b,onClick:x,onBlur:S,onFocus:C,onMouseEnter:w,onMouseLeave:T,onTouchStart:E,ignoreBlocker:D,params:O,search:ee,hash:te,state:ne,mask:k,reloadDocument:A,unsafeRelative:j,from:M,_fromLocation:N,...P}=e,F=yr(),re=B.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),ie=Yr(n.stores.location,e=>e,(e,t)=>e.href===t.href),I=B.useMemo(()=>{let e={_fromLocation:ie,...re};return n.buildLocation(e)},[n,ie,re]),ae=I.maskedLocation?I.maskedLocation.publicHref:I.publicHref,L=I.maskedLocation?I.maskedLocation.external:I.external,oe=B.useMemo(()=>hi(ae,L,n.history,v),[v,L,ae,n.history]),se=B.useMemo(()=>{if(oe?.external)return nt(oe.href,n.protocolAllowlist)?void 0:oe.href;if(!gi(s)&&typeof s==`string`&&s.indexOf(`:`)!==-1)try{return new URL(s),nt(s,n.protocolAllowlist)?void 0:s}catch{}},[s,oe,n.protocolAllowlist]),ce=B.useMemo(()=>{if(se)return!1;if(o?.exact){if(!Rt(ie.pathname,I.pathname,n.basepath))return!1}else{let e=Lt(ie.pathname,n.basepath),t=Lt(I.pathname,n.basepath);if(!(e.startsWith(t)&&(e.length===t.length||e[t.length]===`/`)))return!1}return(o?.includeSearch??!0)&&!Xe(ie.search,I.search,{partial:!o?.exact,ignoreUndefined:!o?.explicitUndefined})?!1:!o?.includeHash||F&&ie.hash===I.hash},[o?.exact,o?.explicitUndefined,o?.includeHash,o?.includeSearch,ie,se,F,I.hash,I.pathname,I.search,n.basepath]),le=ce?ze(i,{})??ci:si,ue=ce?si:ze(a,{})??si,de=[b,le.className,ue.className].filter(Boolean).join(` `),R=(y||le.style||ue.style)&&{...y,...le.style,...ue.style},[fe,pe]=B.useState(!1),me=B.useRef(!1),he=e.reloadDocument||se?!1:c??n.options.defaultPreload,ge=l??n.options.defaultPreloadDelay??0,_e=B.useCallback(()=>{n.preloadRoute({...re,_builtLocation:I}).catch(e=>{console.warn(e),console.warn(fr)})},[n,re,I]);Fe(r,B.useCallback(e=>{e?.isIntersecting&&_e()},[_e]),pi,{disabled:!!v||he!==`viewport`}),B.useEffect(()=>{me.current||!v&&he===`render`&&(_e(),me.current=!0)},[v,_e,he]);let ve=e=>{let t=e.currentTarget.getAttribute(`target`),r=_===void 0?t:_;if(!v&&!vi(e)&&!e.defaultPrevented&&(!r||r===`_self`)&&e.button===0){e.preventDefault(),(0,ai.flushSync)(()=>{pe(!0)});let t=n.subscribe(`onResolved`,()=>{t(),pe(!1)});n.navigate({...re,replace:f,resetScroll:m,hashScrollIntoView:d,startTransition:p,viewTransition:h,ignoreBlocker:D})}};if(se)return{...P,ref:r,href:se,...g&&{children:g},..._&&{target:_},...v&&{disabled:v},...y&&{style:y},...b&&{className:b},...x&&{onClick:x},...S&&{onBlur:S},...C&&{onFocus:C},...w&&{onMouseEnter:w},...T&&{onMouseLeave:T},...E&&{onTouchStart:E}};let ye=e=>{if(v||he!==`intent`)return;if(!ge){_e();return}let t=e.currentTarget;if(fi.has(t))return;let n=setTimeout(()=>{fi.delete(t),_e()},ge);fi.set(t,n)},be=e=>{v||he!==`intent`||_e()},xe=e=>{if(v||!he||!ge)return;let t=e.currentTarget,n=fi.get(t);n&&(clearTimeout(n),fi.delete(t))};return{...P,...le,...ue,href:oe?.href,ref:r,onClick:mi([x,ve]),onBlur:mi([S,xe]),onFocus:mi([C,ye]),onMouseEnter:mi([w,ye]),onMouseLeave:mi([T,xe]),onTouchStart:mi([E,be]),disabled:!!v,target:_,...R&&{style:R},...de&&{className:de},...v&&li,...ce&&ui,...F&&fe&&di}}var si={},ci={className:`active`},li={role:`link`,"aria-disabled":!0},ui={"data-status":`active`,"aria-current":`page`},di={"data-transitioning":`transitioning`},fi=new WeakMap,pi={rootMargin:`100px`},mi=e=>t=>{for(let n of e)if(n){if(t.defaultPrevented)return;n(t)}};function hi(e,t,n,r){if(!r)return t?{href:e,external:!0}:{href:n.createHref(e)||`/`,external:!1}}function gi(e){if(typeof e!=`string`)return!1;let t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var _i=B.forwardRef((e,t)=>{let{_asChild:n,...r}=e,{type:i,...a}=oi(r,t),o=typeof r.children==`function`?r.children({isActive:a[`data-status`]===`active`}):r.children;if(!n){let{disabled:e,...t}=a;return B.createElement(`a`,t,o)}return B.createElement(n,a,o)});function vi(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var yi=class extends pr{constructor(e){super(e),this.useMatch=e=>Zr({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>ii({...e,from:this.id}),this.useSearch=e=>ti({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>ei({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>$r({...e,from:this.id}),this.useLoaderData=e=>Qr({...e,from:this.id}),this.useNavigate=()=>ni({from:this.fullPath}),this.Link=B.forwardRef((e,t)=>(0,V.jsx)(_i,{ref:t,from:this.fullPath,...e}))}};function bi(e){return new yi(e)}var xi=class extends mr{constructor(e){super(e),this.useMatch=e=>Zr({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>ii({...e,from:this.id}),this.useSearch=e=>ti({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>ei({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>$r({...e,from:this.id}),this.useLoaderData=e=>Qr({...e,from:this.id}),this.useNavigate=()=>ni({from:this.fullPath}),this.Link=B.forwardRef((e,t)=>(0,V.jsx)(_i,{ref:t,from:this.fullPath,...e}))}};function Si(e){return new xi(e)}function Ci(e){let t=Sr(),n=`not-found-${Yr(t.stores.location,e=>e.pathname)}-${Yr(t.stores.status,e=>e)}`;return(0,V.jsx)(hr,{getResetKey:()=>n,onCatch:(t,n)=>{if(Wt(t))e.onCatch?.(t,n);else throw t},errorComponent:({error:t})=>{if(Wt(t))return e.fallback?.(t);throw t},children:e.children})}function wi(){return(0,V.jsx)(`p`,{children:`Not Found`})}function Ti(e){return(0,V.jsx)(V.Fragment,{children:e.children})}function Ei(e,t,n){return t.options.notFoundComponent?(0,V.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,V.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,V.jsx)(wi,{})}var Di=B.memo(function({matchId:e}){let t=Sr(),n=t.stores.matchStores.get(e);n||ot();let r=Yr(t.stores.loadedAt,e=>e),i=Yr(n,e=>e);return(0,V.jsx)(Oi,{router:t,matchId:e,resetKey:r,matchState:B.useMemo(()=>{let e=i.routeId,n=t.routesById[e].parentRoute?.id;return{routeId:e,ssr:i.ssr,_displayPending:i._displayPending,parentRouteId:n}},[i._displayPending,i.routeId,i.ssr,t.routesById])})});function Oi({router:e,matchId:t,resetKey:n,matchState:r}){let i=e.routesById[r.routeId],a=i.options.pendingComponent??e.options.defaultPendingComponent,o=a?(0,V.jsx)(a,{}):null,s=i.options.errorComponent??e.options.defaultErrorComponent,c=i.options.onCatch??e.options.defaultOnCatch,l=i.isRoot?i.options.notFoundComponent??e.options.notFoundRoute?.options.component:i.options.notFoundComponent,u=r.ssr===!1||r.ssr===`data-only`,d=(!i.isRoot||i.options.wrapInSuspense||u)&&(i.options.wrapInSuspense??a??(i.options.errorComponent?.preload||u))?B.Suspense:Ti,f=s?hr:Ti,p=l?Ci:Ti;return(0,V.jsxs)(i.isRoot?i.options.shellComponent??Ti:Ti,{children:[(0,V.jsx)(Cr.Provider,{value:t,children:(0,V.jsx)(d,{fallback:o,children:(0,V.jsx)(f,{getResetKey:()=>n,errorComponent:s||_r,onCatch:(e,t)=>{if(Wt(e))throw e.routeId??=r.routeId,e;c?.(e,t)},children:(0,V.jsx)(p,{fallback:e=>{if(e.routeId??=r.routeId,!l||e.routeId&&e.routeId!==r.routeId||!e.routeId&&!i.isRoot)throw e;return B.createElement(l,e)},children:u||r._displayPending?(0,V.jsx)(vr,{fallback:o,children:(0,V.jsx)(Ai,{matchId:t})}):(0,V.jsx)(Ai,{matchId:t})})})})}),r.parentRouteId===`__root__`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(ki,{resetKey:n}),(e.options.scrollRestoration,null)]}):null]})}function ki({resetKey:e}){let t=Sr(),n=B.useRef(void 0);return Pe(()=>{let e=t.latestLocation.href;(n.current===void 0||n.current!==e)&&(t.emit({type:`onRendered`,...Bn(t.stores.location.get(),t.stores.resolvedLocation.get())}),n.current=e)},[t.latestLocation.state.__TSR_key,e,t]),null}var Ai=B.memo(function({matchId:e}){let t=Sr(),n=(e,n)=>t.getMatch(e.id)?._nonReactive[n]??e._nonReactive[n],r=t.stores.matchStores.get(e);r||ot();let i=Yr(r,e=>e),a=i.routeId,o=t.routesById[a],s=B.useMemo(()=>{let e=(t.routesById[a].options.remountDeps??t.options.defaultRemountDeps)?.({routeId:a,loaderDeps:i.loaderDeps,params:i._strictParams,search:i._strictSearch});return e?JSON.stringify(e):void 0},[a,i.loaderDeps,i._strictParams,i._strictSearch,t.options.defaultRemountDeps,t.routesById]),c=B.useMemo(()=>{let e=o.options.component??t.options.defaultComponent;return e?(0,V.jsx)(e,{},s):(0,V.jsx)(ji,{})},[s,o.options.component,t.options.defaultComponent]);if(i._displayPending)throw n(i,`displayPendingPromise`);if(i._forcePending)throw n(i,`minPendingPromise`);if(i.status===`pending`){let e=o.options.pendingMinMs??t.options.defaultPendingMinMs;if(e){let n=t.getMatch(i.id);if(n&&!n._nonReactive.minPendingPromise){let t=Ze();n._nonReactive.minPendingPromise=t,setTimeout(()=>{t.resolve(),n._nonReactive.minPendingPromise=void 0},e)}}throw n(i,`loadPromise`)}if(i.status===`notFound`)return Wt(i.error)||ot(),Ei(t,o,i.error);if(i.status===`redirected`)throw en(i.error)||ot(),n(i,`loadPromise`);if(i.status===`error`)throw i.error;return c}),ji=B.memo(function(){let e=Sr(),t=B.useContext(Cr),n,r=!1,i;{let a=t?e.stores.matchStores.get(t):void 0;[n,r]=Yr(a,e=>[e?.routeId,e?.globalNotFound??!1]),i=Yr(e.stores.matchesId,e=>e[e.findIndex(e=>e===t)+1])}let a=n?e.routesById[n]:void 0,o=e.options.defaultPendingComponent?(0,V.jsx)(e.options.defaultPendingComponent,{}):null;if(r)return a||ot(),Ei(e,a,void 0);if(!i)return null;let s=(0,V.jsx)(Di,{matchId:i});return n===`__root__`?(0,V.jsx)(B.Suspense,{fallback:o,children:s}):s});function Mi(){let e=Sr(),t=B.useRef({router:e,mounted:!1}),[n,r]=B.useState(!1),i=Yr(e.stores.isLoading,e=>e),a=Yr(e.stores.hasPending,e=>e),o=H(i),s=i||n||a,c=H(s),l=i||a,u=H(l);return e.startTransition=e=>{r(!0),B.startTransition(()=>{e(),r(!1)})},B.useEffect(()=>{let t=e.history.subscribe(e.load),n=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return Ft(e.latestLocation.publicHref)!==Ft(n.publicHref)&&e.commitLocation({...n,replace:!0}),()=>{t()}},[e,e.history]),Pe(()=>{typeof window<`u`&&e.ssr||t.current.router===e&&t.current.mounted||(t.current={router:e,mounted:!0},(async()=>{try{await e.load()}catch(e){console.error(e)}})())},[e]),Pe(()=>{o&&!i&&e.emit({type:`onLoad`,...Bn(e.stores.location.get(),e.stores.resolvedLocation.get())})},[o,e,i]),Pe(()=>{u&&!l&&e.emit({type:`onBeforeRouteMount`,...Bn(e.stores.location.get(),e.stores.resolvedLocation.get())})},[l,u,e]),Pe(()=>{if(c&&!s){let t=Bn(e.stores.location.get(),e.stores.resolvedLocation.get());e.emit({type:`onResolved`,...t}),zr(()=>{e.stores.status.set(`idle`),e.stores.resolvedLocation.set(e.stores.location.get())})}},[s,c,e]),null}function Ni(){let e=Sr(),t=e.routesById.__root__.options.pendingComponent??e.options.defaultPendingComponent,n=t?(0,V.jsx)(t,{}):null,r=(0,V.jsxs)(typeof document<`u`&&e.ssr?Ti:B.Suspense,{fallback:n,children:[(0,V.jsx)(Mi,{}),(0,V.jsx)(Pi,{})]});return e.options.InnerWrap?(0,V.jsx)(e.options.InnerWrap,{children:r}):r}function Pi(){let e=Sr(),t=Yr(e.stores.firstId,e=>e),n=Yr(e.stores.loadedAt,e=>e),r=t?(0,V.jsx)(Di,{matchId:t}):null;return(0,V.jsx)(Cr.Provider,{value:t,children:e.options.disableGlobalCatchBoundary?r:(0,V.jsx)(hr,{getResetKey:()=>n,errorComponent:_r,onCatch:void 0,children:r})})}var Fi=e=>({createMutableStore:Hr,createReadonlyStore:Hr,batch:zr}),Ii=e=>new Li(e),Li=class extends Hn{constructor(e){super(e,Fi)}};function Ri({router:e,children:t,...n}){He(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});let r=(0,V.jsx)(xr.Provider,{value:e,children:t});return e.options.Wrap?(0,V.jsx)(e.options.Wrap,{children:r}):r}function zi({router:e,...t}){return(0,V.jsx)(Ri,{router:e,...t,children:(0,V.jsx)(Ni,{})})}var Bi=g(),Vi=(0,B.createContext)(null),Hi=`loopx-pw-locale`,Ui={en:{"acceptance.connected":`Connected`,"acceptance.mapped":`Project mapped`,"acceptance.refreshed":`State refreshed`,"acceptance.inspected":`Adapter inspected`,"acceptance.recorded":`Run recorded`,"acceptance.judged":`Feedback recorded`,"acceptance.approved":`Approval recorded`,"acceptance.ready":`Controller readiness recorded`,"acceptance.attentionSource":`Current status`,"acceptance.visionSource":`Agent acceptance criteria`,"acceptance.todoSource":`Task state`,"acceptance.runSource":`Fresh run evidence`,"acceptance.title":`Acceptance observations`,"acceptance.unavailable":`Acceptance observations are unavailable. Goal completion is unknown.`,"acceptance.partial":`Partial observations only. Completed tasks and an empty gap list do not prove Goal acceptance.`,"acceptance.gaps":`Evidence still required`,"acceptance.reasonUnknown":`Reason not provided by the source`,"acceptance.unknown":`Unknown`,"acceptance.required":`Required evidence or condition`,"acceptance.observed":`Observed at`,"acceptance.noGaps":`No gaps in the available observations. Full acceptance has not been assessed.`,"acceptance.guards":`Pending gates`,"acceptance.noGuards":`No pending gates in the available observations.`,"acceptance.scope":`Decision scope`,"acceptance.next":`Next action from current status`,"acceptance.historical_progress":`Recorded progress`,"acceptance.historical":`Historical lifecycle observations do not grant permission or certify acceptance.`,"acceptance.missing":`Sources not available:`,"acceptance.truncated":`Only the first 12 observations are shown.`,"common.actions":`Actions`,"common.agent":`Agent`,"common.allMessages":`All messages`,"common.cancel":`Cancel`,"common.close":`Close`,"common.closeActionReceipt":`Close action receipt`,"common.confirm":`Confirm`,"common.export":`Export`,"common.failed":`Failed`,"common.goal":`Goal`,"common.loading":`Loading…`,"common.none":`None`,"common.off":`Off`,"common.on":`On`,"common.open":`Open`,"common.owner":`Owner`,"common.readOnly":`Read only`,"common.recently":`Just now`,"common.status":`Status`,"common.task":`Task`,"common.you":`You`,"common.waiting":`Waiting`,"composer.addImage":`Add image`,"composer.agentProgress":`Ask Agent for a progress report`,"composer.agentProgressPrompt":`Give me a progress report for this Goal: completed, running, blocked, and next steps.`,"composer.attachImageHint":`Choose, paste, or drag an image`,"composer.clarifyDefer":`Deferring a Todo requires a deterministic resume condition. Add todo_done:, pr_merged:[owner/repo]#, capacity_available:, or resume_at:.`,"composer.clarifySingleAction":`This message contains multiple operations that may change state. Describe one operation at a time so each confirmation preview can be reviewed separately.`,"composer.createGoal":`Create Goal`,"composer.createGoalDraft":`Goal draft`,"composer.createGoalDraftDescription":`Complete the draft and send it. LoopX will show a confirmation preview first.`,"composer.createGoalDraftLead":`Create a long-term Goal:`,"composer.createGoalTemplate":`Create a long-term Goal: -Objective: -Completion criteria: -Execution boundary (optional): -Related repository (optional): -Notification method (optional):`,"composer.createGoalHint":`Insert a Goal template to review before creation`,"composer.draft":`Draft`,"composer.globalProgress":`Summarize all Goal progress`,"composer.globalProgressPrompt":`Summarize the latest progress and blockers for all active Goals.`,"composer.globalTasks":`Ask about global priorities`,"composer.globalTasksPrompt":`Which Goals need me, and what should I handle first?`,"composer.goalMessageHint":`Your message is delivered to {agent} in this Goal session.`,"composer.goalRunningHint":`{agent} is running {count} tasks · your message enters this session as guidance without interrupting it`,"composer.goalPlaceholder":`Ask or guide {goal}…`,"composer.imageAnalysisPrompt":`Analyze these images in the context of the current Goal and tell me the next step.`,"composer.imageCountError":`You can add up to {count} images.`,"composer.imagePicker":`Image file picker`,"composer.imageReadError":`Could not read image {name}.`,"composer.imageReadGenericError":`Could not read the image.`,"composer.imageSizeError":`Each image must be {size} MB or smaller.`,"composer.imageTypeError":`PNG, JPEG, WebP, and GIF images are supported.`,"composer.imagesPending":`Images to send`,"composer.immediate":`Send now`,"composer.managerMessageHint":`Your message goes to the LoopX Manager across Goals for global questions or Goal creation.`,"composer.managerPlaceholder":`Ask the LoopX Manager, or describe a new Goal…`,"composer.monitor":`Configure scheduled check`,"composer.monitorGoalQuestion":`Which Goal should receive the scheduled check?`,"composer.monitorTemplate":`Add a scheduled check for the current Goal: -Check target: -Frequency (supports 30 minutes / 2 hours / daily): Every 2 hours -Stop condition: Goal completes`,"composer.monitorTemplateWithoutGoal":`Configure a scheduled check: -Goal: -Check target: -Frequency: Every 2 hours -Stop condition: Goal completes`,"composer.monitorHint":`Fill in what to check, frequency, and stop condition before creation`,"composer.heartbeatGoalQuestion":`Which Goal should receive the Heartbeat?`,"composer.heartbeatTemplate":`Set a Heartbeat for the current Goal: -Frequency: Daily -Stop condition: Goal completes -Notification: Only notify me when needed`,"composer.heartbeatTemplateWithoutGoal":`Set up a Heartbeat: -Goal: -Frequency: Daily -Stop condition: Goal completes -Notification: Only notify me when needed`,"composer.nextAction":`Ask what’s next`,"composer.nextActionPrompt":`What should I do next?`,"composer.prepareDraft":`Insert a draft and review before sending`,"composer.send":`Send`,"composer.sendMessage":`Send a message to LoopX`,"composer.sendMessageHint":`Send message`,"composer.sentImageAlt":`Remove image {name}`,"conversation.agentPending":`Working…`,"conversation.close":`Close conversation receipt`,"conversation.convertHint":`Turn the Agent’s latest reply into a Task draft`,"conversation.full":`View full conversation`,"conversation.receipt":`Conversation receipt`,"conversation.replying":`Replying`,"conversation.title":`Manager conversation`,"conversation.toTask":`Convert to Task`,"digest.away":`Runs since your previous visit`,"digest.completed":`new completions`,"digest.failed":`new failed/interrupted runs`,"digest.needsYou":`currently need confirmation`,"feedback.applying":`Running: {title}`,"feedback.cancelFailed":`Cancel failed: {error}`,"feedback.completed":`Completed: {title}`,"feedback.executionFailed":`Execution failed: {error}`,"feedback.gateRequired":`Your confirmation is required: {summary}`,"feedback.notCompleted":`Not completed: {status}`,"feedback.goalRefreshFailed":`The Goal opened, but its latest state could not be refreshed. Use Refresh to try again.`,"feedback.preparingPreview":`Preparing confirmation preview: {title}`,"feedback.previewFailed":`Could not prepare the confirmation preview: {error}`,"feedback.sendFailed":`Send failed: {error}`,"feedback.sendGenericError":`Could not send the message. Try again later.`,"feedback.stale":`State changed, so nothing was applied. Generate a new confirmation preview.`,"feedback.taskDraftCreated":`Created a Task draft from the reply. Edit and send it to review the confirmation preview.`,"goal.defaultTitle":`New personal Goal`,"goal.initialTodo":`Work toward the completion criteria: {criteria}`,"goal.objectiveBoundary":`Execution boundary: {boundary}`,"goal.objectiveCompletion":`Completion criteria: {criteria}`,"drawer.advancedDiagnostics":`Advanced diagnostics`,"drawer.agentWorking":`Agent is continuing; the record updates automatically.`,"drawer.analysis":`Analyzing`,"drawer.apply":`Confirm and apply`,"drawer.applying":`Applying…`,"drawer.attentionBlocking":`Blocking an Agent`,"drawer.attentionWaiting":`Waiting for your decision`,"drawer.autoNotify":`Human-gate auto notifications`,"drawer.branch":`Branch`,"drawer.closeDetail":`Close details and return to {context}`,"drawer.connected":`Connected`,"drawer.correctionDescription":`The message keeps the current Goal, Todo, and Agent Session context.`,"drawer.correctionLabel":`Guide {agent}`,"drawer.correctionPlaceholder":`For example: focus on permission risks first and do not commit yet…`,"drawer.correctionSend":`Send guidance`,"drawer.correctionTextarea":`Enter guidance for Goal {goal}, Agent {agent}, Run {run}`,"drawer.copyRepository":`Copy repository identity`,"drawer.copyRepositoryDone":`Repository identity copied`,"drawer.copyRepositoryError":`Copy failed. Check browser clipboard permission.`,"drawer.copyRepositorySuccess":`Copied. You can paste it into another tool.`,"drawer.cost":`Cost 24h / 7d`,"drawer.costShort":`Cost`,"drawer.durationShort":`Duration`,"drawer.period24h":`24h`,"drawer.period7d":`7d`,"drawer.tokens":`Tokens 24h / 7d`,"drawer.tokensShort":`tokens`,"drawer.usageNotMeasured":`Not measured`,"drawer.currentGoal":`Current Goal`,"attentionDetail.title":`Request details`,"attentionDetail.request":`What is requested`,"attentionDetail.decision":`Decision requested`,"attentionDetail.unknownRequest":`Not specified; review the source before deciding`,"attentionDetail.open":`Open in current projection`,"attentionDetail.closed":`Closed`,"attentionDetail.deferred":`Deferred`,"attentionDetail.superseded":`Replaced`,"attentionDetail.unknown":`Status not provided`,"attentionDetail.unavailable":`The source has not confirmed this item; refresh before acting`,"attentionDetail.unknownReason":`The source has not provided a reason.`,"attentionDetail.targetTodo":`Linked Todo to unblock`,"attentionDetail.targetAgent":`Agent named by the request`,"attentionDetail.scope":`Declared decision scope`,"attentionDetail.notProvided":`Not provided`,"attentionDetail.replacement":`Replacement Todo`,"attentionDetail.openReplacement":`Open replacement`,"attentionDetail.boundary":`Reading this detail does not resolve a gate or grant authority. Available decisions require a fresh preview.`,"drawer.decisionDefaultEvidence":`No additional public-safe evidence is attached. The next step will still show a Preview first.`,"drawer.decisionDefaultReason":`This decision affects the next step of the current Todo.`,"drawer.decisionDefer":`Decide later`,"drawer.decisionMore":`More decisions`,"drawer.decisionReject":`Reject`,"drawer.decisionReview":`Review impact and decide`,"drawer.dependencies":`Dependencies`,"drawer.detailsAndActions":`Details & actions`,"drawer.duration":`Duration 24h / 7d`,"drawer.evidence":`Evidence`,"drawer.executionHistory":`Execution history`,"drawer.executionRecord":`Run record`,"drawer.executionRecordAndResult":`Execution & result`,"drawer.explainDecision":`Explain this decision`,"drawer.gateApproveHint":`Run one command in the terminal to complete approval:`,"drawer.gateRejectHint":`Replace approve with reject at the end to decline. This notice disappears after the command runs.`,"drawer.gateRequiresHost":`Host confirmation required`,"drawer.gateRequiresHostDescription":`This page cannot approve this protected permission change. Nothing was written by your click.`,"drawer.goalAutoRun":`Automatic runs for this Goal`,"drawer.goalChanges":`Pending changes for this Goal`,"drawer.goalDetails":`Goal details`,"drawer.group":`Group`,"drawer.inspectorFull":`Switch to full screen`,"drawer.inspectorFullView":`Full-screen view`,"drawer.inspectorHalf":`Switch to half screen`,"drawer.inspectorHalfView":`Half-screen view`,"drawer.lastNotification":`Latest notification`,"drawer.larkConfigure":`Configure Lark connection`,"drawer.larkConnect":`Connect Lark App`,"drawer.larkConnection":`Lark connection`,"drawer.larkNotConfigured":`Not configured`,"drawer.larkNotConfiguredDescription":`After setup, LoopX sends a Feishu notification when this Goal needs your confirmation.`,"drawer.managerChanges":`Pending Manager changes`,"drawer.moreActions":`More actions`,"drawer.moreRunActions":`More run actions`,"drawer.nextTransition":`Next transition`,"drawer.noExecutionHistory":`No execution history yet.`,"drawer.noRun":`Execution Session has not started`,"drawer.noRunDescription":`Run records will appear here after an Agent starts execution.`,"drawer.notAssigned":`Unassigned`,"drawer.notLinked":`Not linked`,"drawer.notSet":`Not set`,"drawer.outputDetails":`Output details`,"drawer.outputRecorded":`This output is recorded on the current Goal.`,"drawer.outputSafePreview":`Public-safe output preview`,"drawer.outputRun":`Run`,"drawer.outputTodo":`Todo`,"drawer.outputs":`Outputs from this run`,"drawer.previewUnavailable":`No public-safe inline preview is available for this output.`,"drawer.priority":`Priority`,"drawer.progress":`Progress`,"drawer.proposalApplied":`Applied. LoopX state will refresh.`,"drawer.proposalApplyFailed":`Apply failed. No changes were written.`,"drawer.proposalApplyFailedHint":`Refresh the Goal state and regenerate. If it still fails, keep this page open and inspect advanced diagnostics.`,"drawer.proposalClose":`Close`,"drawer.proposalDefer":`Later`,"drawer.proposalDeferred":`Deferred. You can apply it later or regenerate it.`,"drawer.proposalEnterGoal":`Open new Goal`,"drawer.proposalExplainer":`After confirmation, LoopX applies this change and shows the write result. Closing or canceling changes nothing.`,"drawer.proposalRecheck":`Recheck against latest state`,"drawer.proposalRegenerate":`Retry with latest state`,"drawer.proposalRejected":`Rejected. This change will not be written.`,"drawer.proposalStale":`Source state changed. Recheck against the latest state.`,"drawer.proposalViewGoal":`View updated Goal`,"drawer.reassign":`Reassign to`,"drawer.reassignSummary":`Reassign: {task}`,"drawer.reason":`Reason`,"drawer.recoveryDescription":`Local history is preserved. Choose a recovery path.`,"drawer.recoveryFailed":`Upstream Session recovery failed`,"drawer.recoveryNewSession":`Start a new Session with context`,"drawer.recoveryRetry":`Retry recovery`,"drawer.repositoryRole":`Execution workspace`,"drawer.repository":`Repository`,"drawer.replyMode":`Reply mode`,"drawer.subagentApplied":`Applied and verified against the shared Goal state.`,"drawer.subagentAppliedRefreshFailed":`Applied and verified. The status view could not refresh; retry the page refresh later.`,"drawer.subagentApplying":`Applying and verifying shared-state readback…`,"drawer.subagentApplyFailed":`Could not apply the sub-agent setting.`,"drawer.subagentChildLimit":`Current limit`,"drawer.subagentConfirmDisable":`Confirm turning off sub-agent execution`,"drawer.subagentConfirmEnable":`Confirm turning on sub-agent execution`,"drawer.subagentCurrentBoundary":`Current task-domain restriction`,"drawer.subagentDescription":`Allows the runtime to create temporary child agents for independent tasks only after Todo, quota, capability, and write-scope gates pass. It does not force parallel work or grant durable authority.`,"drawer.subagentDisable":`Preview turning off sub-agent execution`,"drawer.subagentDisableSummary":`New child-agent execution will be disabled for this Goal. Existing Todo ownership and execution records stay unchanged.`,"drawer.subagentDomainInvalid":`The selected task-domain restriction is invalid.`,"drawer.subagentDomainTodoCount":`{count} matching open Todos`,"drawer.subagentDomains":`Task-domain restriction (optional)`,"drawer.subagentDomainsEmpty":`No open advancement Todo declares task_domain. Leave this empty to keep child execution unrestricted by task domain.`,"drawer.subagentDomainsHint":`Leave every option clear to apply no task-domain filter. Selecting domains admits only matching typed Todos; all other execution gates still apply.`,"drawer.subagentDomainsUnrestricted":`No task-domain restriction`,"drawer.subagentEnable":`Preview turning on sub-agent execution`,"drawer.subagentLabel":`Per-Goal execution boundary`,"drawer.subagentModel":`Child model`,"drawer.subagentEffort":`Child reasoning effort`,"drawer.subagentModelDefault":`Host default`,"drawer.subagentLunaPreset":`Use Luna / max`,"drawer.subagentClearModel":`Clear model preference`,"drawer.subagentModelHint":`Use Preview configuration update to save this preference. It can be saved while execution is off; host support is checked at launch.`,"drawer.subagentModelRequired":`Choose a child model before setting reasoning effort.`,"drawer.subagentMaxChildren":`Maximum child agents`,"drawer.subagentNoChange":`The current Goal already matches this setting; nothing was written.`,"drawer.subagentPending":`Pending confirmation`,"drawer.subagentPreviewBoundary":`Preview configuration update`,"drawer.subagentPreviewFailed":`Could not create the sub-agent setting preview.`,"drawer.subagentPreviewing":`Checking the latest Goal state…`,"drawer.subagentPreviewReady":`Preview locked. Confirm to apply this Goal setting.`,"drawer.subagentPreviewSummary":`Allow up to {count} child agents. Task-domain restriction: {domains}.`,"drawer.subagentRemoteReadOnly":`This source is read only. Open the Goal on its host to change the setting.`,"drawer.subagentTitle":`Adaptive sub-agent execution`,"drawer.remoteDetailsDescription":`SSH sources expose public-safe status only and do not read connection settings from the source host.`,"drawer.remoteDetailsUnavailable":`Remote details are not projected`,"drawer.resumeNo":`No`,"drawer.resumeYes":`Yes`,"drawer.runDetails":`Execution Session`,"drawer.runInterrupt":`Interrupt this run`,"drawer.runLatest":`View latest execution`,"drawer.runNewSession":`Start new Session`,"drawer.runCloseSession":`Close Session`,"drawer.runRecordEmpty":`No run record yet. The Agent has not started this execution. Check waiting conditions or resume the Session under Details & actions.`,"drawer.runRecordProjected":`No step-by-step record is available. LoopX read {completed}/{total} projected steps{outputs}; inspect the Session under Details & actions.`,"drawer.runRecordProjectedOutputs":` and {count} outputs`,"drawer.runRoleAssistant":`Completed`,"drawer.runRoleSystem":`Needs review`,"drawer.runRoleUser":`Task received`,"drawer.runView":`Session views`,"drawer.scheduleAdd":`Add scheduled check`,"drawer.scheduleDefaultNotification":`Notify only when you are needed`,"drawer.scheduleDefaultStop":`Goal completes or owner stops it`,"drawer.scheduleDefaultTarget":`Wake according to this Goal’s LoopX schedule.`,"drawer.scheduleEdit":`Change to every 2 hours`,"drawer.scheduleLast":`Last run`,"drawer.scheduleLocalTimezone":`Local timezone`,"drawer.scheduleNext":`Next run`,"drawer.scheduleNeverRun":`Not run yet`,"drawer.scheduleNotification":`Notification`,"drawer.schedulePause":`Pause`,"drawer.schedulePending":`Waiting for schedule`,"drawer.scheduleResume":`Resume`,"drawer.scheduleRunNow":`Run now`,"drawer.scheduleStop":`Stop {kind}`,"drawer.scheduleStopCondition":`Stop condition`,"drawer.scheduleTimezone":`Timezone`,"drawer.sessionRecoverable":`Resumable`,"drawer.sessionStatus":`Session status`,"drawer.setupHeartbeat":`Set up Heartbeat`,"drawer.taskActions":`Pending Todo actions`,"drawer.taskAdvancement":`Advancement task`,"drawer.taskBlock":`Mark blocked`,"drawer.taskComplete":`Mark complete`,"drawer.taskCompletedNote":`This task is retained as a read-only record.`,"drawer.taskCompletedTitle":`Task completed`,"drawer.taskDefer":`Defer`,"drawer.taskDeferCondition":`Todo defer resume condition`,"drawer.taskDeferInvalid":`Unsupported condition format; use one of the deterministic conditions below.`,"drawer.taskDeferPlaceholder":`For example, resume_at:2026-09-14T09:00:00+08:00`,"drawer.taskDeferReview":`Review defer`,"drawer.taskDeferSupported":`Supports todo_done, pr_merged, capacity_available, and timezone-aware resume_at conditions.`,"drawer.taskDeferUntil":`Defer until`,"drawer.taskDetails":`Todo details`,"drawer.taskInfo":`Task information`,"drawer.taskManage":`Manage task`,"drawer.taskNextCompleted":`Create a follow-up task`,"drawer.taskNextOpen":`Advance or update status`,"drawer.taskOrdinary":`Task`,"drawer.taskStatusBlocked":`Blocked`,"drawer.taskStatusDeferred":`Deferred`,"drawer.resumeWhen":`Resume condition`,"drawer.resumeState":`Resume state`,"drawer.resumePending":`Waiting for condition`,"drawer.resumeReady":`Ready to resume`,"drawer.resumeReceipt":`Resume receipt`,"drawer.taskNextDeferred":`Wait for the resume condition, then reassess`,"drawer.taskNextResumeReady":`Resume condition met; awaiting lifecycle replan`,"drawer.taskStatusCompleted":`Completed`,"drawer.taskStatusOpen":`Ready`,"drawer.taskSuccessor":`Create follow-up Todo`,"drawer.taskSuccessorNote":`Owner marked this blocked while waiting for more context.`,"drawer.taskSuccessorSummary":`Create follow-up Todo: {task}`,"drawer.taskSuccessorText":`Follow-up work for {task}`,"drawer.taskType":`Task type`,"drawer.topic":`Topic`,"drawer.trigger":`Trigger`,"drawer.titleAttention":`Needs you`,"drawer.titleOutput":`Output details`,"drawer.titleProposalApplied":`Execution result`,"drawer.titleProposalConfirm":`Confirm execution`,"drawer.titleSchedule":`Scheduled check`,"drawer.unconfigured":`Not configured`,"drawer.workspaceCandidates":`Available workspaces`,"files.emptySummary":`Public-safe output`,"files.empty":`No files, outputs, or verified reports yet.`,"files.loadingReports":`Loading verified milestone reports…`,"files.reportDelta":`+{added} added · {changed} changed`,"files.reportAdded":`added`,"files.reportChanged":`changed`,"files.reportGeneration":`Generation`,"files.reportLoadFailed":`Could not load verified reports`,"files.reportPublication":`Publication`,"files.title":`Files & Outputs`,"files.verifiedReport":`Verified milestone report`,"header.agentUnavailable":`Unavailable`,"header.chatRuntime":`Chat`,"header.workAgentCount":`{count} work Agents`,"header.chat":`Chat`,"header.files":`Files`,"header.goalCapabilities":`Capability settings`,"header.goalCapabilitiesDescription":`Manage overrides and inherited machine defaults.`,"header.goalDetails":`Goal details`,"header.goalDetailsDescription":`Review status, usage, repository, notifications, and sessions.`,"header.goalSettings":`Goal settings`,"header.goalSettingsDescription":`Open Goal details or capability settings`,"header.goalNavigation":`Goal navigation`,"header.goalView":`Goal view`,"header.live":`Live`,"header.manager":`LoopX Manager`,"header.managerDescription":`Your personal workspace across Goals`,"header.managerOverview":`Overview`,"header.managerView":`Manager view`,"header.openGoalNavigation":`Open Goal navigation`,"header.readOnlySourceDescription":`{source} is displayed read-only through an SSH tunnel`,"header.refresh":`Refresh status`,"header.refreshDone":`Updated just now`,"header.refreshFailed":`Refresh failed`,"header.refreshing":`Refreshing`,"header.selectAgent":`Select Agent`,"header.selectChatRuntime":`Select chat runtime`,"header.tasks":`Tasks`,"header.themeBrutal":`Switch to brutal theme`,"header.themePaper":`Switch to default theme`,"home.blockingSummary":`{count} are blocking an Agent.`,"home.completedGoals":`Completed Goals`,"home.empty":`Nothing here`,"startup.goalLoading":`Loading status…`,"startup.goalError":`Could not load status`,"startup.progress":`{loaded} of {total} active Goals loaded`,"startup.partial":`Goal states are updating. Counts are incomplete.`,"startup.independent":`Other Goals remain available while this Goal loads.`,"startup.error.timeout":`The request timed out. Retry when the local service is ready.`,"startup.error.network":`The connection was interrupted. Retry to reconnect.`,"startup.error.service":`The local service is temporarily unavailable. Retry to continue.`,"startup.error.revision":`The Goal directory changed during loading. Refresh to synchronize.`,"startup.error.scope":`This Goal is no longer available in the selected source. Refresh the directory.`,"startup.error.invalid":`The status response could not be read. Refresh or check for a LoopX update.`,"startup.retry":`Retry`,"startup.retryFailed":`Retry failed Goals`,"startup.failedCount":`{count} Goals could not be loaded. Ready Goals remain available.`,"home.greeting":`Hi, I’m your LoopX Manager`,"home.history":`History`,"home.lane.needsYou":`Needs you`,"home.lane.needsYouDescription":`Waiting for your decision, authorization, or context`,"home.lane.observing":`Observing`,"home.lane.observingDescription":`Monitoring continuously and notifying you when something changes`,"home.lane.running":`Running`,"home.lane.runningDescription":`Agents are making progress and reporting back`,"home.lane.scheduled":`Scheduled`,"home.lane.scheduledDescription":`Queued until its time or prerequisite arrives`,"home.noActivity":`No activity yet`,"home.noFirstActivity":`Waiting for first activity`,"home.noCompletedGoals":`No completed Goals yet`,"home.preservedState":`State is preserved and can be resumed`,"home.stopped":`Stopped`,"home.systemHealth":`System health: {summary}`,"home.taskCount":`{count} Tasks`,"home.todayAt":`Today {time}`,"home.waitingCount":`You have {count} items to handle.`,"home.workspace":`Goal workspace`,"lark.allMessages":`All messages in this topic`,"lark.allTopicMessages":`All topic messages`,"lark.agentIngress":`Agent ingress`,"lark.agentAppPermissions":`Every selected Agent needs a Lark App that is ready for group mentions and replies.`,"lark.agentApps":`Lark App per Agent`,"lark.agentAppsDescription":`The default App is preselected. Assign a different compatible App when an Agent needs its own bot identity.`,"lark.agentAppSelection":`Lark App for {agent}`,"lark.appCreated":`App created`,"lark.appCreateFailed":`Creation failed`,"lark.appLoading":`Loading available Lark Apps…`,"lark.appPermissions":`This App can send connection messages, but lacks the bot permissions required to receive group mentions or reply automatically. Enable im:message.group_at_msg:readonly, im:message.send_as_bot, and the im.message.receive_v1 event, publish a new version, then refresh.`,"lark.appProfile":`Lark App`,"lark.apps":`Lark Apps`,"lark.autoReplyUnavailable":`Auto reply unavailable`,"lark.autoReplyReady":`Auto reply ready`,"lark.bindGoal":`Bind to Goal`,"lark.cancel":`Cancel`,"lark.cardinality":`One Lark App · many Goals · one isolated route per Agent`,"lark.capture":`Capture`,"lark.captureAddressed":`Only messages that mention or reply to the App`,"lark.captureAll":`All messages in this Goal topic`,"lark.captureScope":`Capture scope`,"lark.captureScopeDescription":`Controls which Topic messages enter LoopX without expanding Agent permissions.`,"lark.closeConnection":`Close connection dialog`,"lark.closeCreate":`Close create dialog`,"lark.closeSettings":`Close Lark settings`,"lark.connect":`Connect`,"lark.connectAllAgents":`Connect every registered Agent`,"lark.connectAllAgentsAction":`Connect {count} Agents`,"lark.connectAllAgentsDescription":`Create {count} isolated Agent Topics in one guided action. Send requests inside the matching Topic; each Agent keeps its own route and inbox.`,"lark.connectApp":`Connect Lark App`,"lark.connection":`Connection`,"lark.connections":`Connections`,"lark.configuration":`Lark configuration`,"lark.continueFeishu":`Continue in Feishu`,"lark.createAutomatically":`Create Goal topic automatically`,"lark.createAutomaticallyDescription":`A dedicated, Agent-labelled Topic will be created for every selected Agent.`,"lark.defaultAgentAppDescription":`Used to find the target group and as the default for every selected Agent. Per-Agent choices below override it.`,"lark.description":`Manage reusable Lark Apps and connect group chats to Goals through dedicated topics.`,"lark.editConnection":`Edit Lark Connection`,"lark.goalConnections":`{count} Goal connections`,"lark.goalTopicConnections":`Lark Goal Topic connections`,"lark.groupChat":`Group chat`,"lark.groupEmpty":`This bot has not joined a group that can be connected. Add it to a Feishu group first, then return to refresh or search.`,"lark.groupLoading":`Reading groups joined by this bot…`,"lark.groupSearch":`Search groups joined by this bot`,"lark.historyPermission":`Group-history permission (separate capability)`,"lark.health.eventProcessed":`{events} events processed, {replies} replies sent.`,"lark.health.eventUnverified":`Event subscription needs verification`,"lark.health.eventUnverifiedDetail":`The provider listener is ready, but no event has arrived. Enable im.message.receive_v1 and group mention permissions, publish a new version, then send a new @ mention inside this Agent Topic. Group-level messages fail closed when multiple Agent routes exist.`,"lark.health.ignoredSelf":`The bot’s own message was ignored to prevent duplicate replies.`,"lark.health.invalidRouting":`Invalid routing configuration`,"lark.health.invalidRoutingDetail":`The connection was safely disabled. Select a processing mode again and save.`,"lark.health.lastStatus":`Latest event status: {status}`,"lark.health.listening":`Listening`,"lark.health.messageContextPermission":`Message permission required`,"lark.health.messageContextPermissionDetail":`A message event arrived, but group context could not be read. Publish and authorize group message read access for this App.`,"lark.health.notAddressed":`Latest message did not directly @ the bot`,"lark.health.notAddressedDetail":`Listening is healthy. This connection only responds to direct @ mentions or replies to the bot.`,"lark.health.notStarted":`Listener not started`,"lark.health.notStartedDetail":`Refresh the connection or restart LoopX, then try again.`,"lark.health.processingFailed":`Message processing failed`,"lark.health.processingFailedDetail":`The message event arrived, but Agent processing failed. Review local diagnostics and retry.`,"lark.health.queued":`Queued in the Agent inbox`,"lark.health.queuedDetail":`The message will be processed asynchronously by {agent} without starting a general Chat Session.`,"lark.health.sourceDisconnected":`Event connection disconnected`,"lark.health.sourceDisconnectedDetail":`The event consumer exited unexpectedly. Check that the app profile uses Feishu for Feishu apps or Lark for international Lark, then inspect connection and subscription errors. LoopX is retrying; successful history queries do not prove live delivery.`,"lark.health.retrying":`Retrying listener`,"lark.health.retryingDetail":`Event listening was interrupted and LoopX is retrying automatically.`,"lark.health.routeAmbiguous":`Message matches multiple Goals`,"lark.health.routeAmbiguousDetail":`The same bot and group have multiple full-group capture connections. Use a separate bot for each Agent or keep only one full-group connection.`,"lark.health.routeMismatch":`Message did not match this Goal Topic`,"lark.health.routeMismatchDetail":`The event came from another group or Topic. Reconnect this Goal to the correct group, then send a new @ mention.`,"lark.health.routeUnavailable":`Message cannot be routed to the Goal`,"lark.health.routeUnavailableDetail":`Connection data is incomplete. Reconnect this Goal, then send a new @ mention.`,"lark.health.starting":`Starting`,"lark.health.startingDetail":`LoopX is starting message event listening for this App.`,"lark.health.unavailable":`Auto reply unavailable`,"lark.health.waiting":`Waiting`,"lark.incomingMessages":`Incoming messages`,"lark.ingressAsync":`Async inbox`,"lark.ingressAsyncDescription":`Write to the Agent private inbox for a later explicit drain.`,"lark.editPreservesIdentity":`Saving preserves this App, group and Topic. Old connections upgrade to the Agent inbox by default.`,"lark.conversationKind":`Connection purpose`,"lark.managerConversation":`Manager · live conversation`,"lark.workerConversation":`Worker Agent · background tasks`,"lark.managerConversationDescription":`The built-in manager responds as you chat and delegates long-running work to background Agents. Group and private conversations keep separate histories.`,"lark.ingressLegacy":`Upgrade available`,"lark.ingressLegacyDescription":`Save this connection to upgrade to the Agent inbox. Existing messages remain in the same Topic.`,"lark.ingressQueue":`Queuing`,"lark.ingressQueueDescription":`Enter the same Agent Session's bounded FIFO queue and run after the current Turn.`,"lark.ingressSteering":`Steering`,"lark.ingressSteeringDescription":`Deliver to the active Turn and reject safely when no exact active Turn exists.`,"lark.loading":`Loading Lark configuration…`,"lark.management":`Lark management`,"lark.openEventSettings":`Open Feishu event settings`,"lark.mentions":`Mentions`,"lark.mentionsOnly":`Mentions only`,"lark.needsMessagePermissions":`Needs message permissions`,"lark.needsSetup":`Needs setup`,"lark.newApp":`New Lark App`,"lark.noAgentConfigured":`No Agent configured`,"lark.noConnections":`No matching connections.`,"lark.noProfiles":`No lark-cli App profiles are available yet.`,"lark.profileName":`Profile name`,"lark.profileValidation":`Profile can contain only letters, numbers, periods, underscores, and hyphens.`,"lark.processing":`Processing`,"lark.region":`Region`,"lark.registerAnother":`+ Register another Lark App — Create through Feishu`,"lark.reopenFeishu":`Reopen Feishu`,"lark.settingsConfigure":`Configure {goal}`,"lark.settingsDisconnect":`Disconnect {goal}`,"lark.replyMode":`Reply mode`,"lark.replyModeDescription":`Replies are limited to the source Topic to prevent cross-group or cross-Goal delivery.`,"lark.reusableApps":`{count} reusable Apps`,"lark.reusableWorkspaceApp":`Reusable workspace App`,"lark.routesUnverified":`{count} Lark routes pending verification`,"lark.saveConnection":`Save connection`,"lark.searchConnections":`Search Lark connections`,"lark.searchPlaceholder":`Search Apps, groups, Goals, or topics`,"lark.setupCopy":`LoopX opens the official Feishu creation page through lark-cli. App credentials stay in the system Keychain; LoopX stores only the profile reference.`,"lark.someoneMentions":`Someone mentions the Agent`,"lark.targetAgent":`Target Agent`,"lark.targetAgentDescription":`Choose a registered Agent in this Goal. This connection delivers to one Agent; it does not broadcast or grant permissions. Steering and Queuing require that Agent's exact active Session.`,"lark.agentUnavailable":`{agent} · no longer available`,"lark.selectRegisteredAgent":`Select an available registered Agent before connecting. The previous Agent will not be replaced automatically.`,"lark.topicPreview":`Topic preview`,"lark.topicReply":`Topic reply`,"lark.trigger":`Trigger`,"lark.waitingFeishu":`Waiting for Feishu`,"lark.waitingFeishuDescription":`Complete Feishu authorization in the new window. This page updates automatically when it is ready.`,"lark.waitingLink":`Generating the official Feishu creation link…`,"lark.error.appCreate":`Lark App creation failed`,"lark.error.appRequired":`Select a Lark App profile.`,"lark.error.bind":`Connection failed`,"lark.error.bindPreview":`Connection preview failed`,"lark.error.configuration":`Could not load Lark configuration`,"lark.error.groupLookup":`Could not read groups joined by this bot. Check the bot status and try again.`,"lark.error.groupLoad":`Could not load group chats`,"lark.error.invalidApp":`The Lark App profile is unavailable or has not completed authorization.`,"lark.error.messagePermissions":`This App lacks the bot permissions required for automatic replies. Enable im:message.group_at_msg:readonly and im:message:send_as_bot, publish a new version, then refresh.`,"lark.error.provider":`The Feishu API call failed without a verified receipt. Try again later.`,"lark.error.setupPoll":`Could not read creation status`,"lark.error.setupStart":`Could not start Lark App creation`,"lark.error.cliExecutable":`The configured lark-cli was found but cannot run. Check the installation or launch arguments.`,"lark.error.cliMissing":`lark-cli was not found. Install lark-cli and restart LoopX.`,"lark.error.cliStart":`lark-cli failed to start. Check the installation and restart LoopX.`,"lark.error.disconnect":`Disconnect failed`,"notifications.autoNotify":`Send automatically when your confirmation is required`,"notifications.bind":`Bind notification group`,"notifications.bindConfirm":`Bind “{goal}” to “{target}”. LoopX will verify that the bot is in the group and send a confirmation message.`,"notifications.bindFailed":`Binding failed`,"notifications.bound":`Bound`,"notifications.confirmBind":`Confirm binding`,"notifications.description":`Send Goal changes that need your confirmation to a Feishu group. Bindings and automatic delivery use the existing channel.`,"notifications.disabled":`Disabled`,"notifications.group":`Notification group: {target}`,"notifications.loadFailed":`Could not load notification groups`,"notifications.noTargets":`No notification groups are available. Group delivery uses a private bot identity; configure one from the terminal first:`,"notifications.notBound":`Not bound`,"notifications.recent":`Latest {time}`,"notifications.sentCount":`{count} sent`,"notifications.settings":`Goal notification bindings`,"notifications.setupFailed":`Could not update settings`,"notifications.title":`Feishu group notifications`,"proposal.field.agentId":`Agent`,"proposal.field.cadence":`Frequency`,"proposal.field.completionCriteria":`Completion criteria`,"proposal.field.executionBoundary":`Execution boundary`,"proposal.field.goalId":`Goal ID`,"proposal.field.heartbeat":`Heartbeat`,"proposal.field.initialTodos":`Initial tasks`,"proposal.field.objective":`Objective`,"proposal.field.operation":`Operation`,"proposal.field.permission":`Permission`,"proposal.field.reason":`Reason`,"proposal.field.stopCondition":`Stop condition`,"proposal.field.target":`Check target`,"proposal.field.timezone":`Timezone`,"proposal.field.title":`Title`,"proposal.field.workspace":`Execution workspace`,"actionReview.targetChanged":`The preview target does not match the requested Goal and operation. Generate a new preview.`,"actionReview.ready_stop":`Pausing is reversible. This validated preview can apply directly; completion still requires verified readback.`,"actionReview.resume_review":`Review before restoring automatic scheduling. Quota, gates and Todo constraints still apply.`,"actionReview.delete_review":`Review removal of this stopped Goal from the registries. Project files and history are preserved.`,"actionReview.action_review":`Review the target and impact before applying this proposal.`,"actionReview.protected_action":`This action needs explicit review. Confirmation cannot replace required authority.`,"actionReview.unknown_permission":`The permission classification is not recognized. Recheck the proposal before continuing.`,"actionReview.unknown_action":`This lifecycle operation is not recognized. Recheck the proposal before continuing.`,"actionReview.incomplete_proposal":`The preview is missing validation or an available apply transition. Generate a new preview.`,"actionReview.authority_gate":`A gate prevents execution. Resolve its requirements, then recheck the proposal.`,"actionReview.stale_proposal":`The source state changed. Generate a new preview; the previous decision no longer applies.`,"actionReview.apply_pending":`Execution is in progress. Wait for its result before retrying.`,"actionReview.readback_verified":`The action completed and its resulting state was verified.`,"actionReview.readback_unverified":`The action returned without verified readback. Completion is not confirmed; recheck the state.`,"actionReview.apply_failed":`Execution did not complete. Check the failure and regenerate the preview before retrying.`,"actionReview.inactive_proposal":`This proposal is no longer ready to execute. Recheck it before continuing.`,"proposal.gate.default":`Host confirmation required`,"proposal.impact.default":`After confirmation, the canonical LoopX service will write the state change.`,"proposal.impact.goalCreate":`After confirmation, LoopX will create the Goal and its initial Todo, then let the selected Agent start the first run.`,"proposal.impact.lifecycleDelete":`After confirmation, this stopped Goal is removed from the source and global registries. Project files, history state, and backups are preserved.`,"proposal.impact.lifecycleResume":`After confirmation, the Goal becomes eligible for automatic scheduling and returns to Active Goals. Actual execution still follows quota, Gate, and Todo constraints.`,"proposal.impact.lifecycleStop":`After confirmation, automatic progress stops and the Goal moves to the collapsed Stopped list. History, Todos, and evidence remain available for resuming.`,"proposal.impact.protected":`This action must be completed through the protected LoopX write service.`,"proposal.primary.apply":`Confirm and apply`,"proposal.primary.goalCreate":`Create Goal and start first run`,"proposal.primary.lifecycleDelete":`Delete Goal`,"proposal.primary.lifecycleResume":`Resume Goal`,"proposal.primary.lifecycleStop":`Stop Goal`,"proposal.primary.todoStart":`Create task and start execution`,"proposal.summary.goalCreate":`Create Goal: {title}`,"proposal.summary.heartbeat":`Set a Heartbeat for the current Goal`,"proposal.summary.lifecycleDelete":`Delete Goal: {title}`,"proposal.summary.lifecycleResume":`Resume Goal: {title}`,"proposal.summary.lifecycleStop":`Stop Goal: {title}`,"proposal.summary.monitor":`Create a scheduled check for the current Goal: {target}`,"proposal.workspace.current":`Current local workspace (no Repository bound)`,"proposal.workspace.named":`{workspace} (execution environment only; does not bind a repository)`,"proposal.workspaceGate.agentImpact":`Bind an Agent identity, then recheck the original action. No Goal has been written.`,"proposal.workspaceGate.agentTitle":`Bind an Agent first`,"proposal.workspaceGate.defaultSummary":`Select the Goal workspace.`,"proposal.workspaceGate.selectionImpact":`After selecting a workspace, LoopX will show the confirmation preview again. The selection itself does not write state.`,"proposal.workspaceGate.selectionTitle":`Select Goal workspace`,"projection.agentAdvancingGoal":`Agent is advancing the current Goal`,"projection.agentIdle":`Nothing needs your attention`,"projection.agentNeedsDecision":`Agent is waiting for your decision`,"projection.agentPreparingNextStep":`Agent is preparing the next step`,"projection.agentStopped":`Stopped by you; history, Todos, and evidence are preserved`,"projection.agentWaitingExternal":`Waiting for an external condition`,"projection.confirmAgentDecision":`Confirm the permission or decision the Agent needs next`,"projection.events24h":`{count} events in the last 24 hours`,"projection.firstReadOnlyAdapterCheck":`Run the first read-only adapter check and save progress`,"projection.goalVerified":`Goal state, Todos, and registration information verified`,"projection.latestRun":`Latest run`,"projection.latestValidation":`Latest validation`,"projection.nextUpdatePending":`Waiting for LoopX to update the next step`,"projection.publicSafeProjection":`Public-safe status projection`,"projection.refreshState":`Refresh LoopX status and confirm the current progress is still valid`,"projection.runEvidenceAvailable":`Run evidence is available`,"projection.runRecorded":`The latest LoopX run is recorded`,"projection.statusRefreshNeeded":`LoopX status needs to be refreshed`,"projection.todoStatusUpdated":`Todo status updated; confirming the next step`,"projection.validationRecorded":`The latest validation is recorded`,"runs.completed":`Completed`,"runs.failed":`Needs review`,"runs.interrupted":`Interrupted`,"runs.queued":`Scheduled`,"runs.ready":`Ready`,"runs.resumeFailed":`Recovery failed`,"runs.running":`Running`,"runs.unknown":`Unknown`,"runs.waiting":`Waiting`,"schedule.active":`Running`,"schedule.heartbeat":`Goal Heartbeat`,"schedule.monitor":`Scheduled & continuous task`,"schedule.paused":`Paused`,"schedule.summary":`Continuously checked under LoopX scheduling constraints`,"schedule.defaultTarget":`Check the current Goal for blockers, progress, and new outputs`,"schedule.unsupportedCalendar":`Scheduled checks do not currently support an exact weekday or time. Use a fixed interval such as “Every 30 minutes,” “Every 2 hours,” or “Daily.” The draft was preserved and no confirmation preview was created.`,"source.add":`Add source`,"source.addConfigured":`Add read-only source`,"source.addMethod":`Source setup method`,"source.addSsh":`Add SSH source`,"source.closeForm":`Close source form`,"source.configured":`Configured SSH`,"source.configuredCount":`Local SSH Hosts · {count}`,"source.configuredGroup":`Configured SSH Hosts · {count} (select to add)`,"source.connected":`Connected`,"source.connecting":`Connecting`,"source.controlPlane":`Control plane source`,"source.copy":`Copy`,"source.copyCommand":`Copy SSH tunnel command`,"source.copyError":`Could not copy the command. Copy it manually below.`,"source.copied":`Copied`,"source.description":`All explicit Hosts are loaded, including Include files. Wildcards are not listed. Run the command first; LoopX never reads SSH keys or configuration details.`,"source.host":`Local SSH Host`,"source.hostEmpty":`No explicit SSH Hosts are available in ~/.ssh/config.`,"source.hostLoadError":`Could not read local SSH Hosts.`,"source.hostPlaceholder":`Enter or search for a Host`,"source.invalid":`The SSH source settings are invalid.`,"source.loadingHosts":`Loading…`,"source.localInteractive":`Local interactive`,"source.localPort":`Local port`,"source.manual":`Manual URL`,"source.manualDescription":`Remote sources always remain read-only projections and never inherit local write permissions.`,"source.name":`Name`,"source.namePlaceholder":`Remote development machine`,"source.notAvailable":`Unavailable`,"source.readOnly":`SSH tunnel · read only`,"source.readOnlyNoticeDescription":`You can view Goals, Tasks, evidence, and run status. Writes, guidance, and Agent sessions remain on the source host.`,"source.readOnlyNoticeTitle":`Remote read-only projection`,"source.readOnlyWriteError":`Remote SSH tunnel sources are read-only projections and cannot perform control-plane writes.`,"source.refreshHosts":`Reload SSH Hosts`,"source.remove":`Remove source {source}`,"source.removeCurrent":`Remove current source`,"source.select":`Select control plane source`,"source.selectHost":`Select a configured SSH Host.`,"source.statusUrl":`Local forwarded URL`,"source.tunnelCommandPending":`Select a Host to generate the tunnel command`,"machine.absent":`Not configured`,"machine.action.create":`Create machine policy`,"machine.action.delete":`Remove machine policy`,"machine.action.unchanged":`No write required`,"machine.action.update":`Update machine policy`,"machine.applied":`Machine policy applied and read back successfully.`,"machine.applyError":`Machine policy could not be applied.`,"machine.applyPreview":`Apply reviewed preview`,"machine.changedNamespaces":`Changed namespaces`,"machine.capabilityCatalog":`Machine capability catalog`,"machine.capabilityEmpty":`No machine-configurable capabilities are registered.`,"machine.configured":`Configured`,"machine.confirmRollback":`Confirm rollback`,"machine.currentRevision":`Current revision`,"machine.currentValue":`Current machine value`,"machine.description":`Browse the same capability catalog as Goal settings. Configure supported machine defaults here; Goal-only capabilities are labeled explicitly.`,"capabilities.rawJson":`Advanced: raw JSON`,"machine.goalOnly":`This capability currently supports Goal configuration only. Open a Goal’s capability settings to configure it; no machine-wide default is applied.`,"machine.desiredRevision":`Desired revision`,"machine.editorUnavailable":`No editor is installed for this namespace`,"machine.editorUnavailableDescription":`The namespace remains visible in the registry. Install or upgrade its Dashboard editor before changing it.`,"machine.editorMode":`Editor mode`,"machine.liveDefault":`Live default; Goal override wins`,"machine.liveDefaultDescription":`Goals without an explicit override read the current machine policy at the capability’s next decision point. Changes and removal affect those existing Goals immediately; an explicit Goal override stays pinned.`,"machine.genericNamespaceDescription":`Edit this registered namespace as JSON. LoopX validates it with the capability-owned schema before previewing any write.`,"machine.jsonConfiguration":`Namespace configuration (JSON)`,"machine.jsonConfigurationHelp":`Only this namespace is updated. Other machine configuration is preserved, and Apply remains locked to the reviewed preview revision.`,"machine.jsonEditor":`JSON`,"machine.editJson":`Edit JSON`,"capabilities.jsonConfiguration":`Goal configuration (JSON)`,"capabilities.jsonHelp":`Edit registered fields for this Goal. Changes require a new preview before applying.`,"capabilities.jsonInvalid":`Enter a valid JSON object using only registered editable fields.`,"machine.backToForm":`Back to form`,"machine.jsonInvalid":`Enter one valid JSON object before previewing changes.`,"machine.loadError":`Machine configuration could not be loaded.`,"machine.machinePolicy":`Machine policy`,"machine.namespaceCount":`Registered namespaces`,"machine.namespaces":`Configuration namespaces`,"machine.periodicReport":`Periodic reports`,"machine.periodicReportDescription":`Default report policy for every Goal without an explicit override. Goal scheduling and delivery consume the effective configuration.`,"machine.periodicReportActivation":`Enabled means automatic delivery at validated stage boundaries`,"machine.periodicReportActivationDescription":`This is not a weekly timer. When LoopX validates a Goal stage completion, an Agent prepares and freezes the report, then automatically delivers it through the configured Goal Channel. The enabled subscription is standing delivery authority; failures and route drift stop closed for repair.`,"machine.changeQualityActivation":`Qualification is a quality gate, not new authority`,"machine.changeQualityActivationDescription":`Goals that inherit this policy qualify their exact final diff. safe_fix allows at most one bounded fix pass inside existing write authority; this setting never grants file, permission, or merge authority.`,"machine.replanCadenceActivation":`Review cadence changes timing, not execution authority`,"machine.replanCadenceActivationDescription":`Goals without an explicit override read this threshold before the next review decision. It does not create Turns, spend quota, or grant authority.`,"machine.preview":`Review exact machine change`,"machine.previewChanges":`Preview changes`,"machine.previewError":`A machine-policy preview could not be created.`,"machine.previewLocked":`Apply is locked to this exact revision. If machine state changes, LoopX requires a new preview.`,"machine.previewRollback":`Preview rollback`,"machine.previewRemoval":`Preview removal`,"machine.profilePreset":`Profile preset`,"machine.profilePresetHelp":`A capability-owned preset, such as weekly-progress.`,"machine.registry":`Typed registry`,"machine.requiredFields":`Enable requires a profile preset, Goal Channel route, and valid timezone.`,"machine.revision":`Machine revision`,"machine.revisionLockedReady":`All changes require a preview and apply only while that exact machine revision remains current.`,"machine.rollbackAvailable":`Rollback is available for the last apply`,"machine.rollbackDescription":`Preview the stored prior revision before restoring it.`,"machine.rollbackError":`The rollback could not be completed.`,"machine.rollbackPreviewDescription":`The prior revision is ready to restore. Confirm to apply this rollback.`,"machine.rolledBack":`The prior machine policy was restored and verified.`,"machine.removed":`Machine policy removed and the resulting configuration read back successfully.`,"machine.routeRef":`Goal Channel route`,"machine.routeRefHelp":`Use a public route alias; credentials and provider identifiers never enter this form.`,"machine.timezone":`Timezone`,"machine.timezoneHelp":`Use an IANA timezone, for example Asia/Shanghai.`,"machine.title":`Machine configuration`,"machine.unchanged":`Machine policy already matches this preview; nothing was written.`,"machine.visualEditor":`Guided`,"capabilities.atomicOverride":`Goal override is atomic`,"capabilities.atomicOverrideDescription":`A complete Goal value wins over the machine default. LoopX never mixes individual fields across scopes.`,"capabilities.applyFailed":`Goal capability changes were not applied.`,"capabilities.applyPreview":`Apply preview`,"capabilities.catalog":`Goal capability catalog`,"capabilities.chooseGoal":`Choose a Goal before inspecting its capabilities.`,"capabilities.defaultValue":`Declared default`,"capabilities.description":`Inspect the capabilities available to this Goal and the exact scope of each setting.`,"capabilities.editorPrepared":`Typed editor contract available`,"capabilities.effectiveSource":`Effective source`,"capabilities.empty":`No capability descriptors are available for this Goal.`,"capabilities.fields":`Registered fields`,"capabilities.goalPolicy":`Goal capability policy`,"capabilities.goalScope":`Goal`,"capabilities.goalValue":`Current Goal value`,"capabilities.loadFailed":`Could not load Goal capabilities`,"capabilities.loading":`Loading Goal capabilities…`,"capabilities.machineOnly":`This capability is configured only at machine scope.`,"capabilities.machineValue":`Live machine default`,"capabilities.machineScope":`Machine`,"capabilities.previewOnly":`Inspection is live. Goal writes remain unavailable until the revision-locked preview and apply path is connected.`,"capabilities.preview":`Revision-locked preview`,"capabilities.previewChanges":`Preview changes`,"capabilities.restoreInheritance":`Restore machine-default inheritance`,"capabilities.previewFailed":`Could not preview Goal capability changes.`,"capabilities.previewLocked":`Apply will re-check this exact plan revision and reject stale changes.`,"capabilities.partialWrite":`Goal value saved; shared projection needs reconciliation`,"capabilities.partialWriteDescription":`The source Goal configuration was written and read back. Its shared runtime projection did not synchronize, so do not submit the change again.`,"capabilities.refreshSource":`Refresh source value`,"capabilities.readOnly":`Read-only capability`,"capabilities.revisionLockedReady":`Changes require a preview and are applied only when its exact revision is still current.`,"capabilities.retry":`Retry`,"capabilities.source.capability_default":`Capability default`,"capabilities.source.goal_override":`Goal override`,"capabilities.source.machine_default":`Live machine default`,"capabilities.source.not_configured":`Not configured`,"capabilities.title":`Goal capabilities`,"settings.close":`Close settings`,"settings.appearance":`Appearance`,"settings.appearanceDescription":`Manage workspace display preferences in this browser.`,"settings.appearanceTabDescription":`Theme and display preferences`,"settings.capabilitiesTabDescription":`Capability overrides for this Goal`,"settings.back":`Back to workspace`,"settings.categories":`Settings categories`,"settings.description":`Manage workspace preferences and integrations.`,"settings.eyebrow":`Workspace preferences`,"settings.general":`General`,"settings.goalConnections":`Goal connections`,"settings.language":`Language`,"settings.languageDescription":`Choose the language used by the LoopX desktop workspace.`,"settings.languageEnglishDescription":`Use English for navigation, settings, and workspace controls.`,"settings.languageEnglish":`English`,"settings.languageSimplifiedChineseDescription":`Use Simplified Chinese for navigation, settings, and workspace controls.`,"settings.languageSimplifiedChinese":`Simplified Chinese`,"settings.languageStoredLocally":`This preference is stored only on this device.`,"settings.languageTabDescription":`Interface language for this device`,"settings.larkTabDescription":`Apps, group chats, and Goal Topic connections`,"settings.machineTabDescription":`Typed defaults shared by capabilities on this machine`,"settings.notifications":`Notifications`,"settings.open":`Settings`,"settings.themeDefault":`Paper`,"settings.themeDefaultDescription":`Calm and lightweight for long-running work.`,"settings.themeDescription":`Choose the workspace visual style. This preference is stored in the current browser.`,"settings.themeHighContrast":`High contrast`,"settings.themeHighContrastDescription":`Stronger borders and more prominent state blocks.`,"settings.themeLoopx":`LoopX standard`,"settings.themeLoopxDescription":`Precise monochrome surfaces, Geist type, and quiet hairline structure.`,"settings.title":`Settings`,"settings.workspaceDisplay":`Workspace display`,"settings.workspaceTheme":`Workspace theme`,"session.closeRecord":`Exit run record`,"session.details":`Session details`,"session.record":`Execution Session · Run record`,"session.recordDescription":`The timeline now shows messages and Turn records from this Session.`,"sidebar.createGoal":`Create Goal`,"sidebar.delete":`Delete`,"sidebar.deleteGoal":`Delete Goal`,"sidebar.manager":`LoopX Manager`,"sidebar.notifications":`Settings`,"sidebar.owner":`Personal workspace`,"sidebar.product":`Personal Agent workspace`,"sidebar.resume":`Resume`,"sidebar.resumeGoal":`Resume Goal`,"sidebar.stop":`Stop`,"tasks.historyLoading":`Loading history…`,"tasks.historyError":`History could not be loaded.`,"tasks.historyExpired":`History snapshot expired. Reload to continue.`,"tasks.historyRetry":`Reload`,"tasks.historyEnd":`End of completed history`,"tasks.historyMore":`Load more`,"tasks.historyLocalOnly":`Open this machine’s Dashboard to browse full history.`,"sidebar.sortGoals":`Reorder Goals`,"sidebar.dragGoal":`Drag to reorder, or use Reorder Goals`,"sidebar.moveUp":`Move {goal} up`,"sidebar.moveDown":`Move {goal} down`,"sidebar.goalMoved":`{goal} moved to position {position}`,"sidebar.orderNotSaved":`Order changed for this visit; browser storage is unavailable.`,"sidebar.stopGoal":`Stop Goal`,"sidebar.stopped":`Stopped`,"sidebar.stoppedLoading":`Loading stopped Goals`,"sidebar.stoppedLoadFailed":`Stopped Goals could not be loaded. Active Goals remain available.`,"sidebar.retryStopped":`Retry`,"state.completed":`Completed`,"state.needsRepair":`Needs repair`,"state.needsYou":`Needs you`,"state.quiet":`Quiet`,"state.running":`Running`,"state.stopped":`Stopped`,"state.waiting":`Waiting`,"tasks.blocked":`Blocked`,"tasks.agentLane":`Work Agent`,"tasks.agentLaneDescription":`Filter this Goal's projected work lanes`,"tasks.agentLaneFilter":`Filter by work Agent`,"tasks.allAgentLanes":`All Agents ({count})`,"tasks.chatAgentReplied":`Agent replied`,"tasks.chatPending":`Sent to Agent`,"tasks.chatPendingDescription":`Processing. Tasks update only after a task operation is confirmed.`,"tasks.chatRecent":`Recent conversation`,"tasks.chatUnchangedDescription":`This conversation did not directly change Tasks. Convert the reply to a Task draft and confirm it when execution is needed.`,"tasks.chatViewReply":`View reply`,"tasks.convertToTask":`Convert to Task`,"tasks.completed":`Completed`,"runs.discoveryPartial":`Some execution details are unavailable. Reconnecting; task summaries are not live execution status.`,"runs.discoveryOffline":`Execution service unavailable. Reconnecting; retained task summaries may be stale.`,"files.openConversation":`Go to conversation`,"files.exportSummary":`Export summary`,"tasks.viewDescription":`Decisions first, then work and recent completions`,"tasks.viewLabel":`Task view`,"tasks.listView":`List`,"tasks.boardView":`Board`,"tasks.completedSummary":`{count} tasks completed. Recent details are projected by the control plane when needed.`,"tasks.emptyCompleted":`No completed tasks yet.`,"tasks.emptyConfirm":`No tasks waiting for confirmation.`,"tasks.emptyRunning":`No queued or running tasks.`,"tasks.emptySchedules":`No scheduled tasks.`,"tasks.emptyGoal":`This Goal has no tasks yet. Describe the next step below and LoopX will show a confirmation preview first.`,"tasks.markComplete":`Mark complete: {name}`,"tasks.moreActions":`More actions: {name}`,"tasks.openExecution":`View execution: {name}`,"tasks.pending":`Pending`,"tasks.pendingAndRunning":`Queued / Running`,"tasks.scheduled":`Scheduled & continuous`,"tasks.sessionError":`Session issue`,"tasks.waiting":`Queued`,"tasks.waitingAge":`Waiting {age}`,"tasks.viewExecution":`View execution`,"tasks.viewResult":`View result`,"time.days":`{count} days`,"time.hours":`{count} hours`,"timeline.emptyGoal":`This Goal has no new activity`,"timeline.emptyGoalDescription":`Ask for progress or send new guidance.`,"timeline.emptyWorkspace":`Your workspace is quiet today`,"timeline.emptyWorkspaceDescription":`Describe a Goal to the LoopX Manager, or ask what deserves attention today.`,"timeline.gateHistory":`{count} historical Gates`,"timeline.pending":`Working…`,"timeline.runCompleted":`{run}: completed`,"timeline.review":`Review`,"timeline.reviewAndConfirm":`Review and confirm`,"timeline.waitingConfirmation":`Needs your confirmation`},"zh-CN":{"acceptance.connected":`已连接`,"acceptance.mapped":`已建立项目映射`,"acceptance.refreshed":`已刷新状态`,"acceptance.inspected":`已检查适配器`,"acceptance.recorded":`已记录执行`,"acceptance.judged":`已记录反馈`,"acceptance.approved":`已记录批准`,"acceptance.ready":`已记录控制器就绪`,"acceptance.attentionSource":`当前状态`,"acceptance.visionSource":`Agent 验收条件`,"acceptance.todoSource":`任务状态`,"acceptance.runSource":`最新执行证据`,"acceptance.title":`验收观察`,"acceptance.unavailable":`验收观测不可用,Goal 是否达成仍未知。`,"acceptance.partial":`当前仅有部分观测。任务完成或缺口列表为空,都不能证明 Goal 已通过验收。`,"acceptance.gaps":`仍需补充的证据`,"acceptance.reasonUnknown":`来源未提供原因`,"acceptance.unknown":`未知`,"acceptance.required":`所需证据或条件`,"acceptance.observed":`观测时间`,"acceptance.noGaps":`现有观测中没有缺口,尚未评估完整验收条件。`,"acceptance.guards":`待处理的门禁决策`,"acceptance.noGuards":`现有观测中没有待处理的门禁决策。`,"acceptance.scope":`决策范围`,"acceptance.next":`当前状态给出的下一步`,"acceptance.historical_progress":`已记录的历史进展`,"acceptance.historical":`历史生命周期记录不授予权限,也不代表通过验收。`,"acceptance.missing":`未获取的来源:`,"acceptance.truncated":`仅展示前 12 条观测。`,"common.actions":`操作`,"common.agent":`Agent`,"common.allMessages":`所有消息`,"common.cancel":`取消`,"common.close":`关闭`,"common.closeActionReceipt":`关闭操作回执`,"common.confirm":`确认`,"common.export":`导出`,"common.failed":`失败`,"common.goal":`Goal`,"common.loading":`加载中…`,"common.none":`无`,"common.off":`关闭`,"common.on":`开启`,"common.open":`打开`,"common.owner":`Owner`,"common.readOnly":`只读`,"common.recently":`刚刚`,"common.status":`状态`,"common.task":`Task`,"common.you":`你`,"common.waiting":`等待中`,"composer.addImage":`添加图片`,"composer.agentProgress":`向 Agent 获取进度报告`,"composer.agentProgressPrompt":`请给我一份当前 Goal 的进度报告:已完成、执行中、阻塞和下一步。`,"composer.attachImageHint":`选择、粘贴或拖入图片`,"composer.clarifyDefer":`暂缓 Todo 需要可自动判断的恢复条件。请补充 todo_done:、pr_merged:[owner/repo]#、capacity_available: 或 resume_at:<带时区 RFC3339 时间>。`,"composer.clarifySingleAction":`这句话包含多个可能修改状态的操作。请一次描述一项操作,我会逐项展示确认预览。`,"composer.createGoal":`创建新 Goal`,"composer.createGoalDraft":`Goal 草稿`,"composer.createGoalDraftDescription":`补充内容后发送,LoopX 会先展示待确认操作。`,"composer.createGoalDraftLead":`我想创建一个长期 Goal:`,"composer.createGoalTemplate":`我想创建一个长期 Goal: -目标: -完成标准: -执行边界(可选): -关联仓库(可选): -通知方式(可选):`,"composer.createGoalHint":`填入 Goal 模板草稿,检查后再创建`,"composer.draft":`草稿`,"composer.globalProgress":`汇总所有 Goal 进展`,"composer.globalProgressPrompt":`请帮我汇总所有活跃 Goal 的最新进展与阻塞。`,"composer.globalTasks":`询问全局待办`,"composer.globalTasksPrompt":`有哪些 Goal 正在等我?我现在该优先处理什么?`,"composer.goalMessageHint":`你的消息由 {agent} 在本 Goal 的会话中接收`,"composer.goalRunningHint":`{agent} 正在执行 {count} 个任务 · 你的消息作为纠偏进入本会话,不会打断执行`,"composer.goalPlaceholder":`询问或纠偏 {goal}…`,"composer.imageAnalysisPrompt":`请结合这些图片分析当前 Goal,并告诉我下一步。`,"composer.imageCountError":`最多添加 {count} 张图片。`,"composer.imagePicker":`图片文件选择器`,"composer.imageReadError":`无法读取图片 {name}`,"composer.imageReadGenericError":`图片读取失败。`,"composer.imageSizeError":`单张图片不能超过 {size}MB。`,"composer.imageTypeError":`支持 PNG、JPEG、WebP 和 GIF 图片。`,"composer.imagesPending":`待发送图片`,"composer.immediate":`立即发送`,"composer.managerMessageHint":`你的消息由 LoopX 管家跨 Goal 接收,支持全局询问与创建 Goal`,"composer.managerPlaceholder":`问问 LoopX 管家,或描述一个新 Goal…`,"composer.monitor":`配置定时检查`,"composer.monitorGoalQuestion":`为哪个 Goal 添加定时检查?`,"composer.monitorTemplate":`为当前 Goal 添加定时检查: -检查内容: -频率(支持 30 分钟 / 2 小时 / 每天):每 2 小时 -停止条件:Goal 完成`,"composer.monitorTemplateWithoutGoal":`配置定时检查: -Goal: -检查内容: -频率:每 2 小时 -停止条件:Goal 完成`,"composer.monitorHint":`先填写检查内容、频率和停止条件,不会立即创建`,"composer.heartbeatGoalQuestion":`为哪个 Goal 设置 Heartbeat?`,"composer.heartbeatTemplate":`为当前 Goal 设置 Heartbeat: -频率:每天 -停止条件:Goal 完成 -通知:仅在需要我时`,"composer.heartbeatTemplateWithoutGoal":`设置 Heartbeat: -Goal: -频率:每天 -停止条件:Goal 完成 -通知:仅在需要我时`,"composer.nextAction":`询问下一步`,"composer.nextActionPrompt":`我现在该做什么?`,"composer.prepareDraft":`填入编辑框,确认后再发送`,"composer.send":`发送`,"composer.sendMessage":`向 LoopX 发送消息`,"composer.sendMessageHint":`发送消息`,"composer.sentImageAlt":`移除图片 {name}`,"conversation.agentPending":`正在整理…`,"conversation.close":`关闭对话回执`,"conversation.convertHint":`将 Agent 最新回复转为 Task 草稿`,"conversation.full":`查看完整对话`,"conversation.receipt":`对话回执`,"conversation.replying":`正在回复`,"conversation.title":`管家对话`,"conversation.toTask":`转为 Task`,"digest.away":`自上次访问以来的运行记录`,"digest.completed":`新增完成运行`,"digest.failed":`新增失败或中断`,"digest.needsYou":`当前待确认`,"feedback.applying":`正在执行:{title}`,"feedback.cancelFailed":`取消失败:{error}`,"feedback.completed":`已完成:{title}`,"feedback.executionFailed":`执行失败:{error}`,"feedback.gateRequired":`需要你确认:{summary}`,"feedback.notCompleted":`操作未完成:{status}`,"feedback.goalRefreshFailed":`已打开 Goal,但暂时无法刷新最新状态。请点击刷新重试。`,"feedback.preparingPreview":`正在准备确认预览:{title}`,"feedback.previewFailed":`无法准备确认预览:{error}`,"feedback.sendFailed":`发送失败:{error}`,"feedback.sendGenericError":`消息发送失败,请稍后重试。`,"feedback.stale":`状态已变化,操作未执行,请重新生成确认预览。`,"feedback.taskDraftCreated":`已根据回复生成 Task 草稿。编辑后发送,LoopX 会先展示确认预览。`,"goal.defaultTitle":`新的个人 Goal`,"goal.initialTodo":`按完成标准推进:{criteria}`,"goal.objectiveBoundary":`执行边界:{boundary}`,"goal.objectiveCompletion":`完成标准:{criteria}`,"drawer.advancedDiagnostics":`高级诊断`,"drawer.agentWorking":`Agent 正在继续执行,记录会自动更新。`,"drawer.analysis":`正在分析`,"drawer.apply":`确认并应用`,"drawer.applying":`正在应用…`,"drawer.attentionBlocking":`正在阻塞 Agent`,"drawer.attentionWaiting":`等待你的决定`,"drawer.autoNotify":`Human-gate 自动通知`,"drawer.branch":`分支`,"drawer.closeDetail":`关闭详情:返回{context}`,"drawer.connected":`已连接`,"drawer.correctionDescription":`消息会沿用当前 Goal、Todo 与 Agent Session 上下文。`,"drawer.correctionLabel":`与 {agent} 纠偏`,"drawer.correctionPlaceholder":`例如:先关注权限风险,暂时不要提交…`,"drawer.correctionSend":`发送纠偏`,"drawer.correctionTextarea":`输入纠偏信息:Goal {goal},Agent {agent},Run {run}`,"drawer.copyRepository":`复制仓库标识`,"drawer.copyRepositoryDone":`已复制仓库标识`,"drawer.copyRepositoryError":`复制失败,请检查浏览器剪贴板权限。`,"drawer.copyRepositorySuccess":`已复制,可粘贴到其他工具。`,"drawer.cost":`成本 24h / 7d`,"drawer.costShort":`成本`,"drawer.durationShort":`时长`,"drawer.period24h":`24 小时`,"drawer.period7d":`7 天`,"drawer.tokens":`Token 24 小时 / 7 天`,"drawer.tokensShort":`Token`,"drawer.usageNotMeasured":`未采集`,"drawer.currentGoal":`当前 Goal`,"attentionDetail.title":`事项说明`,"attentionDetail.request":`需要你做什么`,"attentionDetail.decision":`需要作出决定`,"attentionDetail.unknownRequest":`来源未明确,请先查看来源再判断`,"attentionDetail.open":`当前投影中待处理`,"attentionDetail.closed":`已关闭`,"attentionDetail.deferred":`已推迟`,"attentionDetail.superseded":`已被替代`,"attentionDetail.unknown":`来源未提供状态`,"attentionDetail.unavailable":`来源尚未确认当前事项,请刷新后再操作`,"attentionDetail.unknownReason":`来源尚未提供原因。`,"attentionDetail.targetTodo":`关联的待解锁 Todo`,"attentionDetail.targetAgent":`事项指定的 Agent`,"attentionDetail.scope":`声明的决策范围`,"attentionDetail.notProvided":`来源未提供`,"attentionDetail.replacement":`替代 Todo`,"attentionDetail.openReplacement":`打开替代事项`,"attentionDetail.boundary":`阅读详情不会关闭 gate 或授予权限;作出决定前仍需新的操作预览。`,"drawer.decisionDefaultEvidence":`当前状态没有附加公开安全证据;下一步仍会先展示 Preview。`,"drawer.decisionDefaultReason":`该决定会影响当前 Todo 的下一步执行。`,"drawer.decisionDefer":`稍后决定`,"drawer.decisionMore":`更多决定`,"drawer.decisionReject":`拒绝`,"drawer.decisionReview":`查看影响并决定`,"drawer.dependencies":`依赖`,"drawer.detailsAndActions":`详情与操作`,"drawer.duration":`运行时长 24h / 7d`,"drawer.evidence":`证据`,"drawer.executionHistory":`执行历史`,"drawer.executionRecord":`运行记录`,"drawer.executionRecordAndResult":`执行过程与结果`,"drawer.explainDecision":`解释此决定`,"drawer.gateApproveHint":`在终端执行一条命令即可完成审批:`,"drawer.gateRejectHint":`不同意就把末尾的 approve 换成 reject。执行后这条提醒会自动消失。`,"drawer.gateRequiresHost":`需要宿主确认`,"drawer.gateRequiresHostDescription":`页面无权直接批准这类权限变更,你的点击没有写入任何内容。`,"drawer.goalAutoRun":`当前 Goal 的自动运行`,"drawer.goalChanges":`当前 Goal 的待确认变更`,"drawer.goalDetails":`Goal 详情`,"drawer.group":`群聊`,"drawer.inspectorFull":`切换到全屏`,"drawer.inspectorFullView":`全屏查看`,"drawer.inspectorHalf":`切换到半屏`,"drawer.inspectorHalfView":`半屏查看`,"drawer.lastNotification":`最近通知`,"drawer.larkConfigure":`管理 Lark connection`,"drawer.larkConnect":`连接 Lark App`,"drawer.larkConnection":`Lark connection`,"drawer.larkNotConfigured":`未配置`,"drawer.larkNotConfiguredDescription":`配置后,当这个 Goal 出现需要你确认的变更时,会自动发飞书通知。`,"drawer.managerChanges":`管家待确认变更`,"drawer.moreActions":`更多操作`,"drawer.moreRunActions":`更多运行操作`,"drawer.nextTransition":`下一转换`,"drawer.noExecutionHistory":`暂无执行记录。`,"drawer.noRun":`尚未启动执行 Session`,"drawer.noRunDescription":`Agent 开始执行后,运行记录会稳定显示在这里。`,"drawer.notAssigned":`未分配`,"drawer.notLinked":`未关联`,"drawer.notSet":`未设置`,"drawer.outputDetails":`产出详情`,"drawer.outputRecorded":`该产出已记录到当前 Goal。`,"drawer.outputSafePreview":`公开安全产出预览`,"drawer.outputRun":`Run`,"drawer.outputTodo":`Todo`,"drawer.outputs":`本次运行产出`,"drawer.previewUnavailable":`此产出没有可用的公开安全内联预览。`,"drawer.priority":`优先级`,"drawer.progress":`进度`,"drawer.proposalApplied":`已应用,LoopX 状态将刷新。`,"drawer.proposalApplyFailed":`应用失败,没有写入任何变更。`,"drawer.proposalApplyFailedHint":`请刷新 Goal 状态后重新生成;若仍失败,可保留此页并查看高级诊断。`,"drawer.proposalClose":`关闭`,"drawer.proposalDefer":`稍后`,"drawer.proposalDeferred":`已暂缓,可稍后继续应用或重新生成。`,"drawer.proposalEnterGoal":`进入新 Goal`,"drawer.proposalExplainer":`确认后,LoopX 会执行这项变更并显示写入结果。关闭或取消不会修改任何状态。`,"drawer.proposalRecheck":`按最新状态重新检查`,"drawer.proposalRegenerate":`基于最新状态重试`,"drawer.proposalRejected":`已拒绝,这项变更不会写入。`,"drawer.proposalStale":`来源状态已变化,请按最新状态重新检查。`,"drawer.proposalViewGoal":`查看更新后的 Goal`,"drawer.reassign":`改派给`,"drawer.reassignSummary":`重新分配:{task}`,"drawer.reason":`原因`,"drawer.recoveryDescription":`本地历史已经保留,请选择恢复路径。`,"drawer.recoveryFailed":`上游 Session 恢复失败`,"drawer.recoveryNewSession":`携带上下文开始新 Session`,"drawer.recoveryRetry":`重试恢复`,"drawer.repositoryRole":`执行工作区`,"drawer.repository":`仓库`,"drawer.replyMode":`回复方式`,"drawer.subagentApplied":`已写入,并通过共享 Goal 状态读回校验。`,"drawer.subagentAppliedRefreshFailed":`已写入并通过共享 Goal 状态读回;状态投影刷新失败,可稍后手动刷新。`,"drawer.subagentApplying":`正在写入并校验共享状态读回…`,"drawer.subagentApplyFailed":`子代理设置写入失败。`,"drawer.subagentChildLimit":`当前上限`,"drawer.subagentConfirmDisable":`确认关闭子代理执行`,"drawer.subagentConfirmEnable":`确认开启子代理执行`,"drawer.subagentCurrentBoundary":`当前任务领域限制`,"drawer.subagentDescription":`仅在 Todo、配额、能力和写入范围门禁全部通过后,允许运行时为相互独立的任务临时创建子代理;不会强制并行,也不会授予持久权限。`,"drawer.subagentDisable":`预览关闭子代理执行`,"drawer.subagentDisableSummary":`这个 Goal 将不再创建新的子代理;现有 Todo 归属和执行记录不受影响。`,"drawer.subagentDomainInvalid":`所选任务领域限制无效。`,"drawer.subagentDomainTodoCount":`匹配 {count} 个开放 Todo`,"drawer.subagentDomains":`任务领域限制(可选)`,"drawer.subagentDomainsEmpty":`当前没有开放的 advancement Todo 声明 task_domain;保持为空即可不按任务领域限制子代理执行。`,"drawer.subagentDomainsHint":`全部不选表示不按任务领域过滤;选择后只放行匹配且已声明领域的 Todo,其他执行门禁始终生效。`,"drawer.subagentDomainsUnrestricted":`不限制任务领域`,"drawer.subagentEnable":`预览开启子代理执行`,"drawer.subagentLabel":`Per-Goal 执行边界`,"drawer.subagentModel":`子 Agent 模型`,"drawer.subagentEffort":`子 Agent 推理档位`,"drawer.subagentModelDefault":`宿主默认`,"drawer.subagentLunaPreset":`使用 Luna / max`,"drawer.subagentClearModel":`清除模型偏好`,"drawer.subagentModelHint":`填写后通过“预览配置调整”保存,执行关闭时也可保存偏好;启动时须核验宿主支持情况。`,"drawer.subagentModelRequired":`设置推理档位前请先指定子 Agent 模型。`,"drawer.subagentMaxChildren":`最多子代理数`,"drawer.subagentNoChange":`当前 Goal 已是这个设置,没有写入任何内容。`,"drawer.subagentPending":`待确认`,"drawer.subagentPreviewBoundary":`预览配置调整`,"drawer.subagentPreviewFailed":`无法生成子代理设置预览。`,"drawer.subagentPreviewing":`正在核对最新 Goal 状态…`,"drawer.subagentPreviewReady":`预览已锁定,确认后才会写入这个 Goal。`,"drawer.subagentPreviewSummary":`最多允许创建 {count} 个子代理;任务领域限制:{domains}。`,"drawer.subagentRemoteReadOnly":`当前来源只读,请在 Goal 所在主机上修改。`,"drawer.subagentTitle":`自适应子代理执行`,"drawer.remoteDetailsDescription":`SSH 来源只展示公开安全状态,不读取来源主机上的连接配置。`,"drawer.remoteDetailsUnavailable":`远端详情未投影`,"drawer.resumeNo":`否`,"drawer.resumeYes":`是`,"drawer.runDetails":`执行 Session`,"drawer.runInterrupt":`中断本次运行`,"drawer.runLatest":`查看最近执行过程`,"drawer.runNewSession":`开始新 Session`,"drawer.runCloseSession":`关闭 Session`,"drawer.runRecordEmpty":`还没有运行记录。Agent 尚未开始这次执行;请在“详情与操作”查看等待条件或恢复 Session。`,"drawer.runRecordProjected":`当前没有可展示的逐步运行记录。LoopX 已读取到 {completed}/{total} 的投影进度{outputs};请在“详情与操作”检查 Session 状态。`,"drawer.runRecordProjectedOutputs":`和 {count} 项产出`,"drawer.runRoleAssistant":`已完成`,"drawer.runRoleSystem":`需检查`,"drawer.runRoleUser":`收到任务`,"drawer.runView":`Session 视图`,"drawer.scheduleAdd":`添加定时检查`,"drawer.scheduleDefaultNotification":`仅在需要你时通知`,"drawer.scheduleDefaultStop":`Goal 完成或 owner 停止`,"drawer.scheduleDefaultTarget":`由 LoopX 调度器按 Goal 配置唤醒。`,"drawer.scheduleEdit":`改为每 2 小时`,"drawer.scheduleLast":`上次执行`,"drawer.scheduleLocalTimezone":`本地时区`,"drawer.scheduleNext":`下次执行`,"drawer.scheduleNeverRun":`尚未执行`,"drawer.scheduleNotification":`通知`,"drawer.schedulePause":`暂停`,"drawer.schedulePending":`等待调度`,"drawer.scheduleResume":`恢复`,"drawer.scheduleRunNow":`立即运行`,"drawer.scheduleStop":`停止{kind}`,"drawer.scheduleStopCondition":`停止条件`,"drawer.scheduleTimezone":`时区`,"drawer.sessionRecoverable":`可恢复`,"drawer.sessionStatus":`会话状态`,"drawer.setupHeartbeat":`设置 Heartbeat`,"drawer.taskActions":`Todo 待确认操作`,"drawer.taskAdvancement":`推进任务`,"drawer.taskBlock":`标记阻塞`,"drawer.taskComplete":`标记完成`,"drawer.taskCompletedNote":`该任务保留为只读记录。`,"drawer.taskCompletedTitle":`任务已完成`,"drawer.taskDefer":`暂缓`,"drawer.taskDeferCondition":`Todo 暂缓恢复条件`,"drawer.taskDeferInvalid":`条件格式不受支持;请使用下列可判定条件。`,"drawer.taskDeferPlaceholder":`例如 resume_at:2026-09-14T09:00:00+08:00`,"drawer.taskDeferReview":`检查暂缓`,"drawer.taskDeferSupported":`支持 todo_done、pr_merged、capacity_available 与带时区的 resume_at 条件。`,"drawer.taskDeferUntil":`暂缓至`,"drawer.taskDetails":`Todo 详情`,"drawer.taskInfo":`任务信息`,"drawer.taskManage":`管理任务`,"drawer.taskNextCompleted":`可创建后续任务`,"drawer.taskNextOpen":`推进或更新状态`,"drawer.taskOrdinary":`普通任务`,"drawer.taskStatusBlocked":`受阻`,"drawer.taskStatusDeferred":`已延期`,"drawer.resumeWhen":`恢复条件`,"drawer.resumeState":`恢复状态`,"drawer.resumePending":`等待条件满足`,"drawer.resumeReady":`可恢复`,"drawer.resumeReceipt":`恢复回执`,"drawer.taskNextDeferred":`等待恢复条件满足后重新评估`,"drawer.taskNextResumeReady":`恢复条件已满足,等待生命周期重新规划`,"drawer.taskStatusCompleted":`已完成`,"drawer.taskStatusOpen":`待执行`,"drawer.taskSuccessor":`创建后续 Todo`,"drawer.taskSuccessorNote":`Owner 标记为阻塞,等待补充上下文。`,"drawer.taskSuccessorSummary":`创建后续 Todo:{task}`,"drawer.taskSuccessorText":`{task} 的后续工作`,"drawer.taskType":`任务类型`,"drawer.topic":`Topic`,"drawer.trigger":`触发方式`,"drawer.titleAttention":`需要你`,"drawer.titleOutput":`产出详情`,"drawer.titleProposalApplied":`执行结果`,"drawer.titleProposalConfirm":`确认执行`,"drawer.titleSchedule":`定时检查`,"drawer.unconfigured":`未配置`,"drawer.workspaceCandidates":`可选择的工作区`,"files.emptySummary":`公开安全产出`,"files.empty":`还没有文件、产出或已验证的阶段周报。`,"files.loadingReports":`正在加载已验证的阶段周报…`,"files.reportDelta":`+{added} 新增 · {changed} 变化`,"files.reportAdded":`新增`,"files.reportChanged":`变化`,"files.reportGeneration":`生成批次`,"files.reportLoadFailed":`无法加载已验证周报`,"files.reportPublication":`发布批次`,"files.title":`Files & Outputs`,"files.verifiedReport":`已验证阶段周报`,"header.agentUnavailable":`不可用`,"header.chatRuntime":`Chat`,"header.workAgentCount":`{count} 个工作 Agent`,"header.chat":`Chat`,"header.files":`Files`,"header.goalCapabilities":`能力配置`,"header.goalCapabilitiesDescription":`管理 Goal override 与继承的本机默认值。`,"header.goalDetails":`Goal 详情`,"header.goalDetailsDescription":`查看状态、用量、仓库、通知与 Session。`,"header.goalSettings":`Goal 设置`,"header.goalSettingsDescription":`打开 Goal 详情或能力配置`,"header.goalNavigation":`Goal 导航`,"header.goalView":`Goal 视图`,"header.live":`实时`,"header.manager":`LoopX 管家`,"header.managerDescription":`跨 Goal 的个人工作入口`,"header.managerOverview":`总览`,"header.managerView":`管家视图`,"header.openGoalNavigation":`打开 Goal 导航`,"header.readOnlySourceDescription":`{source} 通过 SSH 隧道只读展示`,"header.refresh":`刷新状态`,"header.refreshDone":`刚刚更新`,"header.refreshFailed":`刷新失败`,"header.refreshing":`刷新中`,"header.selectAgent":`选择 Agent`,"header.selectChatRuntime":`选择聊天 Runtime`,"header.tasks":`Tasks`,"header.themeBrutal":`切换到野兽主题`,"header.themePaper":`切换到默认主题`,"home.blockingSummary":`其中 {count} 项正在阻塞 Agent。`,"home.completedGoals":`已完成的 Goal`,"home.empty":`当前没有`,"startup.goalLoading":`正在加载状态…`,"startup.goalError":`状态加载失败`,"startup.progress":`已加载 {loaded} / {total} 个活跃 Goal`,"startup.partial":`Goal 状态正在逐个更新,当前统计尚不完整。`,"startup.independent":`此 Goal 的加载不会阻塞其他 Goal,你可以先查看已加载的内容。`,"startup.error.timeout":`读取超时,可在本地服务就绪后重试。`,"startup.error.network":`连接中断,请重试以重新连接。`,"startup.error.service":`本地服务暂时不可用,请重试继续加载。`,"startup.error.revision":`加载期间 Goal 目录发生变化,请刷新以同步。`,"startup.error.scope":`该 Goal 已不在当前来源中,请刷新目录。`,"startup.error.invalid":`无法解析状态响应,请刷新或检查 LoopX 更新。`,"startup.retry":`重试`,"startup.retryFailed":`重试失败的 Goal`,"startup.failedCount":`{count} 个 Goal 加载失败,已加载的 Goal 可继续使用。`,"home.greeting":`你好,我是 LoopX 管家`,"home.history":`历史`,"home.lane.needsYou":`需要你`,"home.lane.needsYouDescription":`等待你的决定、授权或补充信息`,"home.lane.observing":`观察中`,"home.lane.observingDescription":`持续监控,出现变化时再提醒你`,"home.lane.running":`执行中`,"home.lane.runningDescription":`Agent 正在推进并持续回传进展`,"home.lane.scheduled":`已安排`,"home.lane.scheduledDescription":`已经安排,等待时间或前置条件`,"home.noActivity":`尚无活动`,"home.noFirstActivity":`等待首次活动`,"home.noCompletedGoals":`还没有已完成的 Goal`,"home.preservedState":`保留状态,可随时恢复`,"home.stopped":`已停止`,"home.systemHealth":`系统健康:{summary}`,"home.taskCount":`{count} 个 Task`,"home.todayAt":`今天 {time}`,"home.waitingCount":`你有 {count} 项需要处理。`,"home.workspace":`Goal 工作区`,"lark.allMessages":`此 Topic 中的所有消息`,"lark.allTopicMessages":`所有 Topic 消息`,"lark.agentIngress":`Agent 入站方式`,"lark.agentAppPermissions":`每个选中的 Agent 都需要一个已具备群聊提及和回复能力的 Lark App。`,"lark.agentApps":`每个 Agent 的 Lark App`,"lark.agentAppsDescription":`默认使用上方 App;需要独立机器人身份时,可为 Agent 选择另一个兼容 App。`,"lark.agentAppSelection":`{agent} 的 Lark App`,"lark.appCreated":`App 已创建`,"lark.appCreateFailed":`创建失败`,"lark.appLoading":`正在加载可用的 Lark Apps…`,"lark.appPermissions":`该 App 能发送建联消息,但缺少接收群聊 @ 消息或自动回复所需的机器人权限。请开启 im:message.group_at_msg:readonly、im:message.send_as_bot 和事件 im.message.receive_v1,发布新版后刷新。`,"lark.appProfile":`Lark App`,"lark.apps":`Lark Apps`,"lark.autoReplyUnavailable":`自动回复暂不可用`,"lark.autoReplyReady":`自动回复可用`,"lark.bindGoal":`绑定到 Goal`,"lark.cancel":`取消`,"lark.cardinality":`一个 Lark App · 多个 Goal · 每个 Agent 一条隔离路由`,"lark.capture":`接收范围`,"lark.captureAddressed":`仅接收提及 App 或回复 App 的消息`,"lark.captureAll":`接收此 Goal Topic 中的所有消息`,"lark.captureScope":`接收范围`,"lark.captureScopeDescription":`决定哪些 Topic 消息会进入 LoopX;不会扩大 Agent 权限。`,"lark.closeConnection":`关闭连接弹窗`,"lark.closeCreate":`关闭创建弹窗`,"lark.closeSettings":`关闭 Lark 设置`,"lark.connect":`连接`,"lark.connectAllAgents":`连接全部已注册 Agent`,"lark.connectAllAgentsAction":`一键连接 {count} 个 Agent`,"lark.connectAllAgentsDescription":`一次引导创建 {count} 个隔离的 Agent Topic;请在对应 Topic 内发送请求,每个 Agent 保留独立路由和收件箱。`,"lark.connectApp":`连接 Lark App`,"lark.connection":`连接`,"lark.connections":`连接`,"lark.configuration":`Lark 配置`,"lark.continueFeishu":`在飞书中继续`,"lark.createAutomatically":`自动创建 Goal Topic`,"lark.createAutomaticallyDescription":`将为每个选中的 Agent 创建带 Agent 标识的专属 Topic。`,"lark.defaultAgentAppDescription":`用于查找目标群聊,并作为所有选中 Agent 的默认 App;下方的逐 Agent 选择可覆盖它。`,"lark.description":`管理可复用的 Lark App,并用独立 Topic 将群聊连接到 Goal。`,"lark.editConnection":`编辑 Lark 连接`,"lark.goalConnections":`{count} 个 Goal 连接`,"lark.goalTopicConnections":`Lark Goal Topic 连接`,"lark.groupChat":`群聊`,"lark.groupEmpty":`该机器人尚未加入可连接的群。请先在飞书群设置中添加这个机器人,再回来刷新或搜索。`,"lark.groupLoading":`正在读取该机器人已加入的群…`,"lark.groupSearch":`搜索该机器人已加入的群`,"lark.historyPermission":`历史补读权限(独立能力)`,"lark.health.eventProcessed":`已处理 {events} 条事件,成功回复 {replies} 条。`,"lark.health.eventUnverified":`事件订阅待验证`,"lark.health.eventUnverifiedDetail":`Provider listener 已就绪,但尚未收到消息事件。请启用 im.message.receive_v1、开通群聊 @ 消息权限并发布新版,然后在这个 Agent Topic 内发送新的 @ 消息;存在多条 Agent 路由时,群顶层消息会 fail closed。`,"lark.health.ignoredSelf":`已忽略机器人自身发送的消息,避免重复回复。`,"lark.health.invalidRouting":`路由配置无效`,"lark.health.invalidRoutingDetail":`连接已安全停用,请重新选择处理方式并保存。`,"lark.health.lastStatus":`最近事件状态:{status}`,"lark.health.listening":`监听中`,"lark.health.messageContextPermission":`消息权限不足`,"lark.health.messageContextPermissionDetail":`已收到消息事件,但无法读取群消息上下文。请发布并授权该 App 的群消息读取权限。`,"lark.health.notAddressed":`最近消息未直接 @ 机器人`,"lark.health.notAddressedDetail":`监听正常;当前连接只响应直接 @ 机器人或对机器人的回复。`,"lark.health.notStarted":`监听未启动`,"lark.health.notStartedDetail":`请刷新连接或重新启动 LoopX 后再试。`,"lark.health.processingFailed":`消息处理失败`,"lark.health.processingFailedDetail":`已收到消息事件,但 Agent 处理失败。请查看本地诊断后重试。`,"lark.health.queued":`已进入 Agent 收件箱`,"lark.health.queuedDetail":`消息由 {agent} 异步处理,不会启动通用 Chat Session。`,"lark.health.sourceDisconnected":`实时消息连接断开`,"lark.health.sourceDisconnectedDetail":`消息监听进程意外退出。请核对应用档案的平台:飞书应用选飞书,国际版 Lark 应用选 Lark,再检查连接及订阅错误。LoopX 正在重试;历史消息能读取,不代表能实时收消息。`,"lark.health.retrying":`监听重试中`,"lark.health.retryingDetail":`事件监听暂时中断,LoopX 正在自动重试。`,"lark.health.routeAmbiguous":`消息匹配多个 Goal`,"lark.health.routeAmbiguousDetail":`同一 Bot 和群聊存在多个完整群捕获连接。请让每个 Agent 使用独立 Bot,或只保留一个完整群连接。`,"lark.health.routeMismatch":`消息未匹配当前 Goal Topic`,"lark.health.routeMismatchDetail":`事件来自其他群聊或 Topic。请重新选择群聊并连接该 Goal,然后发送一条新的 @ 消息。`,"lark.health.routeUnavailable":`消息无法路由到 Goal`,"lark.health.routeUnavailableDetail":`当前连接信息不完整。请重新连接该 Goal 后再发送一条新的 @ 消息。`,"lark.health.starting":`正在启动`,"lark.health.startingDetail":`LoopX 正在启动该 App 的消息事件监听。`,"lark.health.unavailable":`自动回复不可用`,"lark.health.waiting":`等待处理`,"lark.incomingMessages":`接收消息`,"lark.ingressAsync":`异步收件箱`,"lark.ingressAsyncDescription":`写入 Agent 私有收件箱,等待后续显式处理。`,"lark.editPreservesIdentity":`保存会保留此 App、群和 Topic;旧连接默认升级为 Agent 异步收件箱。`,"lark.conversationKind":`连接用途`,"lark.managerConversation":`管家 · 同步对话`,"lark.workerConversation":`工作 Agent · 后台任务`,"lark.managerConversationDescription":`内置管家即时回应对话,长任务交给后台 Agent。群聊与私聊分别保存上下文。`,"lark.ingressLegacy":`待升级`,"lark.ingressLegacyDescription":`保存连接即可升级为 Agent 异步收件箱,已有消息保留在原 Topic 中。`,"lark.ingressQueue":`排队`,"lark.ingressQueueDescription":`进入同一 Agent Session 的有界 FIFO 队列,当前 Turn 完成后处理。`,"lark.ingressSteering":`实时引导`,"lark.ingressSteeringDescription":`投到当前活跃 Turn;没有精确活跃 Turn 时安全拒绝。`,"lark.loading":`加载 Lark 配置…`,"lark.management":`Lark 管理`,"lark.openEventSettings":`查看飞书事件配置`,"lark.mentions":`提及机器人`,"lark.mentionsOnly":`仅提及消息`,"lark.needsMessagePermissions":`需要消息权限`,"lark.needsSetup":`需要设置`,"lark.newApp":`新建 Lark App`,"lark.noAgentConfigured":`未配置 Agent`,"lark.noConnections":`暂无匹配的连接。`,"lark.noProfiles":`还没有可用的 lark-cli App profile。`,"lark.profileName":`Profile 名称`,"lark.profileValidation":`Profile 只能包含字母、数字、点、下划线和连字符。`,"lark.processing":`处理方式`,"lark.region":`区域`,"lark.registerAnother":`+ 注册另一个 Lark App — 通过飞书创建`,"lark.reopenFeishu":`重新打开飞书`,"lark.settingsConfigure":`配置 {goal}`,"lark.settingsDisconnect":`解绑 {goal}`,"lark.replyMode":`回复方式`,"lark.replyModeDescription":`当前只支持在来源 Topic 内回复,避免跨群或跨 Goal 投递。`,"lark.reusableApps":`{count} 个可复用 App`,"lark.reusableWorkspaceApp":`可复用工作区 App`,"lark.routesUnverified":`{count} 条 Lark 路由尚未验证`,"lark.saveConnection":`保存连接`,"lark.searchConnections":`搜索 Lark 连接`,"lark.searchPlaceholder":`搜索 App、群、Goal 或 Topic`,"lark.setupCopy":`LoopX 将通过 lark-cli 打开飞书官方创建页面。应用凭证保存在系统 Keychain,LoopX 只保留 profile 引用。`,"lark.someoneMentions":`有人提及 Agent`,"lark.targetAgent":`目标 Agent`,"lark.targetAgentDescription":`选择该 Goal 内已注册的 Agent。此连接只投递给一个 Agent,不广播、不授予新权限。实时引导与排队需要该 Agent 的精确活跃 Session。`,"lark.agentUnavailable":`{agent} · 已不可用`,"lark.selectRegisteredAgent":`请先选择可用的已注册 Agent;不会自动替换原先的接收者。`,"lark.topicPreview":`Topic 预览`,"lark.topicReply":`Topic 回复`,"lark.trigger":`触发方式`,"lark.waitingFeishu":`等待飞书完成创建`,"lark.waitingFeishuDescription":`请在新窗口中完成飞书授权,完成后会自动回到这里。`,"lark.waitingLink":`正在生成飞书官方创建链接…`,"lark.error.appCreate":`Lark App 创建失败`,"lark.error.appRequired":`请选择一个 Lark App profile。`,"lark.error.bind":`绑定失败`,"lark.error.bindPreview":`绑定预览失败`,"lark.error.configuration":`Lark 配置加载失败`,"lark.error.groupLookup":`无法读取该机器人已加入的群。请检查机器人状态后重试。`,"lark.error.groupLoad":`群聊加载失败`,"lark.error.invalidApp":`Lark App profile 不可用或尚未完成授权。`,"lark.error.messagePermissions":`该 App 缺少自动回复所需的机器人权限。请开启 im:message.group_at_msg:readonly 和 im:message:send_as_bot,发布新版后回来刷新重试。`,"lark.error.provider":`飞书 API 调用失败,且没有生成已验证回执。请稍后重试。`,"lark.error.setupPoll":`创建状态查询失败`,"lark.error.setupStart":`无法启动 Lark App 创建流程`,"lark.error.cliExecutable":`已找到配置的 lark-cli,但当前无法执行。请检查安装或启动参数。`,"lark.error.cliMissing":`未发现 lark-cli。请先安装 lark-cli,然后重新启动 LoopX。`,"lark.error.cliStart":`lark-cli 启动失败。请检查安装状态,然后重新启动 LoopX。`,"lark.error.disconnect":`解绑失败`,"notifications.autoNotify":`需要你确认时自动推送到群里`,"notifications.bind":`绑定到通知群`,"notifications.bindConfirm":`将把「{goal}」绑定到通知群「{target}」,绑定时会验证机器人在群内并发送一条确认消息。`,"notifications.bindFailed":`绑定失败`,"notifications.bound":`已绑定`,"notifications.confirmBind":`确认绑定`,"notifications.description":`把 Goal 里需要你确认的变更推送到飞书群。绑定和开关在这里完成,推送逻辑沿用现有通道。`,"notifications.disabled":`已停用`,"notifications.group":`通知群:{target}`,"notifications.loadFailed":`通知群列表加载失败`,"notifications.noTargets":`还没有可用的通知群。通知群涉及机器人私有身份,请先在终端配置一次:`,"notifications.notBound":`未绑定`,"notifications.recent":`最近 {time}`,"notifications.sentCount":`已发送 {count} 条`,"notifications.settings":`Goal 通知绑定`,"notifications.setupFailed":`设置失败`,"notifications.title":`飞书群通知`,"proposal.field.agentId":`Agent`,"proposal.field.cadence":`频率`,"proposal.field.completionCriteria":`完成标准`,"proposal.field.executionBoundary":`执行边界`,"proposal.field.goalId":`Goal ID`,"proposal.field.heartbeat":`Heartbeat`,"proposal.field.initialTodos":`首个任务`,"proposal.field.objective":`目标`,"proposal.field.operation":`操作`,"proposal.field.permission":`权限`,"proposal.field.reason":`原因`,"proposal.field.stopCondition":`停止条件`,"proposal.field.target":`检查内容`,"proposal.field.timezone":`时区`,"proposal.field.title":`标题`,"proposal.field.workspace":`执行工作区`,"actionReview.targetChanged":`预览目标与请求的 Goal 或操作不一致,请重新生成预览。`,"actionReview.ready_stop":`暂停可恢复。此预览已通过检查,可直接执行;完成仍需要读回验证。`,"actionReview.resume_review":`恢复自动调度前需要确认。实际执行仍受额度、Gate 和 Todo 约束。`,"actionReview.delete_review":`请确认从注册表移除这个已停止 Goal。项目文件与历史记录会保留。`,"actionReview.action_review":`执行前请检查此提案的目标与影响。`,"actionReview.protected_action":`此操作需要明确审阅。确认不能替代所需授权。`,"actionReview.unknown_permission":`无法识别权限分类。请重新检查提案后再继续。`,"actionReview.unknown_action":`无法识别此生命周期操作。请重新检查提案后再继续。`,"actionReview.incomplete_proposal":`预览缺少验证信息或可执行转换。请重新生成预览。`,"actionReview.authority_gate":`Gate 阻止执行。请满足其要求后重新检查提案。`,"actionReview.stale_proposal":`来源状态已变化。请重新生成预览,原决定不再适用。`,"actionReview.apply_pending":`正在执行,请等待读回结果后再重试。`,"actionReview.readback_verified":`操作已完成,结果状态已通过读回验证。`,"actionReview.readback_unverified":`操作返回但未通过读回验证。尚不能确认完成,请重新检查状态。`,"actionReview.apply_failed":`执行未完成。请检查失败原因并重新生成预览后再试。`,"actionReview.inactive_proposal":`此提案当前不可执行。请重新检查后再继续。`,"proposal.gate.default":`需要宿主确认`,"proposal.impact.default":`确认后会调用规范 LoopX 服务写入状态。`,"proposal.impact.goalCreate":`确认后会创建 Goal 和首个 Todo,并让选定 Agent 开始首轮推进。`,"proposal.impact.lifecycleDelete":`确认后会从 source registry 和 global registry 移除这个已停止 Goal;项目文件、历史状态文件和备份不会被删除。`,"proposal.impact.lifecycleResume":`确认后会恢复 Goal 的自动调度资格并移回 Active Goals;实际执行仍受 quota、Gate 和 Todo 约束。`,"proposal.impact.lifecycleStop":`确认后会停止自动推进,并将 Goal 移入折叠的「已停止」列表;历史、Todo 和证据都会保留,可随时恢复。`,"proposal.impact.protected":`该操作需要通过受保护的 LoopX 写入服务完成。`,"proposal.primary.apply":`确认并应用`,"proposal.primary.goalCreate":`创建 Goal 并开始首轮`,"proposal.primary.lifecycleDelete":`删除 Goal`,"proposal.primary.lifecycleResume":`恢复 Goal`,"proposal.primary.lifecycleStop":`停止 Goal`,"proposal.primary.todoStart":`创建任务并开始执行`,"proposal.summary.goalCreate":`创建 Goal:{title}`,"proposal.summary.heartbeat":`为当前 Goal 设置 Heartbeat`,"proposal.summary.lifecycleDelete":`删除 Goal:{title}`,"proposal.summary.lifecycleResume":`恢复 Goal:{title}`,"proposal.summary.lifecycleStop":`停止 Goal:{title}`,"proposal.summary.monitor":`为当前 Goal 创建定时检查:{target}`,"proposal.workspace.current":`当前本地工作区(未绑定 Repository)`,"proposal.workspace.named":`{workspace}(仅提供执行环境,不会自动关联仓库)`,"proposal.workspaceGate.agentImpact":`先完成 Agent 身份绑定,再重新检查原操作;当前没有写入 Goal。`,"proposal.workspaceGate.agentTitle":`先绑定 Agent`,"proposal.workspaceGate.defaultSummary":`请选择 Goal 所属工作区。`,"proposal.workspaceGate.selectionImpact":`选择工作区后会重新展示待确认操作,选择本身不会写入状态。`,"proposal.workspaceGate.selectionTitle":`选择 Goal 工作区`,"projection.agentAdvancingGoal":`Agent 正在推进当前 Goal`,"projection.agentIdle":`暂无需要你处理`,"projection.agentNeedsDecision":`Agent 等待你的决定`,"projection.agentPreparingNextStep":`Agent 正在整理下一步`,"projection.agentStopped":`已由你停止;历史、Todo 和证据仍保留`,"projection.agentWaitingExternal":`正在等待外部条件`,"projection.confirmAgentDecision":`请确认 Agent 下一步需要的权限或决策`,"projection.events24h":`24 小时内 {count} 个事件`,"projection.firstReadOnlyAdapterCheck":`执行首次只读适配检查并保存进度`,"projection.goalVerified":`Goal 状态、Todo 与注册信息已验证`,"projection.latestRun":`最近运行`,"projection.latestValidation":`最近验证`,"projection.nextUpdatePending":`等待 LoopX 更新下一步`,"projection.publicSafeProjection":`公开安全状态投影`,"projection.refreshState":`刷新 LoopX 状态,确认当前进度仍然有效`,"projection.runEvidenceAvailable":`存在可查看的运行证据`,"projection.runRecorded":`最近一次 LoopX 运行已经记录`,"projection.statusRefreshNeeded":`LoopX 状态需要刷新`,"projection.todoStatusUpdated":`Todo 状态已经更新,正在确认下一步`,"projection.validationRecorded":`最近验证已经记录`,"runs.completed":`已完成`,"runs.failed":`需检查`,"runs.interrupted":`已中断`,"runs.queued":`已安排`,"runs.ready":`可继续`,"runs.resumeFailed":`恢复失败`,"runs.running":`执行中`,"runs.unknown":`状态未知`,"runs.waiting":`等待条件`,"schedule.active":`执行中`,"schedule.heartbeat":`Goal Heartbeat`,"schedule.monitor":`定时与持续任务`,"schedule.paused":`已暂停`,"schedule.summary":`按 LoopX 调度约束持续检查`,"schedule.defaultTarget":`检查当前 Goal 的阻塞、进度与新产出`,"schedule.unsupportedCalendar":`当前定时检查不支持精确到星期或时刻的日历计划。请改用固定间隔,例如“每 30 分钟”“每 2 小时”或“每天”;草稿已保留,没有生成待确认操作。`,"source.add":`添加来源`,"source.addConfigured":`添加只读来源`,"source.addMethod":`来源添加方式`,"source.addSsh":`添加 SSH 隧道来源`,"source.closeForm":`关闭来源表单`,"source.configured":`已配置 SSH`,"source.configuredCount":`本机 SSH Host · {count} 个`,"source.configuredGroup":`已配置 SSH Host · {count}(点击快速添加)`,"source.connected":`已连接`,"source.connecting":`连接中`,"source.controlPlane":`控制面来源`,"source.copy":`复制`,"source.copyCommand":`复制 SSH 隧道命令`,"source.copyError":`无法复制命令,请手动复制下方命令。`,"source.copied":`已复制`,"source.description":`已读取全部显式 Host(含 Include);通配规则不会作为具体来源。先运行命令,LoopX 不读取密钥或配置细节。`,"source.host":`本机 SSH Host`,"source.hostEmpty":`~/.ssh/config 中没有可直接选择的显式 Host。`,"source.hostLoadError":`无法读取本机 SSH Host。`,"source.hostPlaceholder":`输入或搜索 Host`,"source.invalid":`SSH 来源参数无效。`,"source.loadingHosts":`正在读取…`,"source.localInteractive":`本机交互`,"source.localPort":`本地端口`,"source.manual":`手动 URL`,"source.manualDescription":`远端来源始终按只读投影处理,不继承本机写权限。`,"source.name":`名称`,"source.namePlaceholder":`远程开发机`,"source.notAvailable":`不可用`,"source.readOnly":`SSH 隧道 · 只读`,"source.readOnlyNoticeDescription":`你可以查看 Goal、Task、证据与运行状态;写入、纠偏和 Agent 会话仍留在来源主机。`,"source.readOnlyNoticeTitle":`远端只读投影`,"source.readOnlyWriteError":`远端 SSH 隧道来源是只读投影,不能执行控制面写入。`,"source.refreshHosts":`重新读取 SSH Host`,"source.remove":`移除来源 {source}`,"source.removeCurrent":`移除当前来源`,"source.select":`选择控制面来源`,"source.selectHost":`请选择已配置的 SSH Host。`,"source.statusUrl":`本地转发 URL`,"source.tunnelCommandPending":`选择 Host 后生成隧道命令`,"machine.absent":`尚未配置`,"machine.action.create":`创建机器策略`,"machine.action.delete":`移除机器策略`,"machine.action.unchanged":`无需写入`,"machine.action.update":`更新机器策略`,"machine.applied":`机器策略已应用,并通过回读校验。`,"machine.applyError":`无法应用机器策略。`,"machine.applyPreview":`应用已审阅预览`,"machine.changedNamespaces":`变更的 Namespace`,"machine.capabilityCatalog":`机器能力目录`,"machine.capabilityEmpty":`当前没有注册可在机器作用域配置的能力。`,"machine.configured":`已配置`,"machine.confirmRollback":`确认回滚`,"machine.currentRevision":`当前 Revision`,"machine.currentValue":`当前机器值`,"machine.description":`与 Goal 设置共用能力目录。在这里管理受支持的机器默认值;仅支持 Goal 配置的能力会明确标注。`,"capabilities.rawJson":`高级:原始 JSON`,"machine.goalOnly":`此能力目前仅支持 Goal 级配置。请打开具体 Goal 的能力设置进行配置;这里不会设置机器级默认值。`,"machine.desiredRevision":`目标 Revision`,"machine.editorUnavailable":`当前版本未安装此 Namespace 的编辑器`,"machine.editorUnavailableDescription":`它仍会显示在 Registry 中;安装或升级对应的 Dashboard 编辑器后才能修改。`,"machine.editorMode":`编辑模式`,"machine.liveDefault":`实时默认值;Goal 显式覆盖优先`,"machine.liveDefaultDescription":`没有显式覆盖的 Goal 会在该能力下一次决策时读取当前机器策略。修改或移除策略会立即影响这些已有 Goal;显式 Goal 覆盖保持固定。`,"machine.genericNamespaceDescription":`使用 JSON 编辑这个已注册 Namespace。LoopX 会先按 capability 自己拥有的 schema 校验,再允许预览写入。`,"machine.jsonConfiguration":`Namespace 配置(JSON)`,"machine.jsonConfigurationHelp":`只更新当前 Namespace;其他机器配置会保留,Apply 仍锁定到已审阅的 Preview Revision。`,"machine.jsonEditor":`JSON`,"machine.editJson":`编辑 JSON`,"capabilities.jsonConfiguration":`Goal 配置(JSON)`,"capabilities.jsonHelp":`仅编辑当前 Goal 的已注册字段。修改后需重新预览才能应用。`,"capabilities.jsonInvalid":`请输入合法的 JSON 对象,且仅包含已注册的可编辑字段。`,"machine.backToForm":`返回表单`,"machine.jsonInvalid":`请先填写一个合法的 JSON object,再预览变更。`,"machine.loadError":`无法读取机器配置。`,"machine.machinePolicy":`机器策略`,"machine.namespaceCount":`已注册 Namespace`,"machine.namespaces":`配置 Namespace`,"machine.periodicReport":`周期报告`,"machine.periodicReportDescription":`为所有未显式覆盖的 Goal 提供默认报告策略;Goal 调度与发送消费解析后的有效配置。`,"machine.periodicReportActivation":`开启后将在已验证的阶段节点自动投递`,"machine.periodicReportActivationDescription":`这不是每周定时器。当 LoopX 验证 Goal 已完成一个阶段时,Agent 会生成并冻结报告,随后通过配置的 Goal Channel 自动发送。启用此订阅即授予持续投递权;发送失败或路由漂移会 fail closed 并进入修复。`,"machine.changeQualityActivation":`质量验证是质量门禁,不是新增授权`,"machine.changeQualityActivationDescription":`继承该策略的 Goal 会验证最终精确 diff。safe_fix 只允许在既有写入权限内执行至多一次有界修复;此设置不会授予文件、权限或合并权。`,"machine.replanCadenceActivation":`复核周期只改变时机,不改变执行权限`,"machine.replanCadenceActivationDescription":`没有显式覆盖的 Goal 会在下一次复核决策前读取此阈值;它不会创建 Turn、消耗配额或授予权限。`,"machine.preview":`审阅机器配置变更`,"machine.previewChanges":`预览变更`,"machine.previewError":`无法生成机器策略预览。`,"machine.previewLocked":`应用操作锁定到当前 Revision;若机器状态变化,LoopX 会要求重新预览。`,"machine.previewRollback":`预览回滚`,"machine.previewRemoval":`预览移除`,"machine.profilePreset":`Profile preset`,"machine.profilePresetHelp":`由 capability 管理的 preset,例如 weekly-progress。`,"machine.registry":`Typed Registry`,"machine.requiredFields":`开启后必须填写 profile preset、Goal Channel route 与有效时区。`,"machine.revision":`机器 Revision`,"machine.revisionLockedReady":`所有变更必须先预览;只有对应的机器 Revision 仍然有效时才会应用。`,"machine.rollbackAvailable":`可回滚上一次应用`,"machine.rollbackDescription":`先预览已保存的前一 Revision,再决定是否恢复。`,"machine.rollbackError":`无法完成回滚。`,"machine.rollbackPreviewDescription":`前一 Revision 已准备恢复,请确认执行本次回滚。`,"machine.rolledBack":`已恢复前一版机器策略,并通过校验。`,"machine.removed":`机器策略已移除,并通过回读校验。`,"machine.routeRef":`Goal Channel route`,"machine.routeRefHelp":`只填写公开 route alias;凭据与 provider identifier 不会进入此表单。`,"machine.timezone":`时区`,"machine.timezoneHelp":`填写 IANA 时区,例如 Asia/Shanghai。`,"machine.title":`机器配置`,"machine.unchanged":`机器策略已与预览一致,本次没有写入。`,"machine.visualEditor":`引导式`,"capabilities.atomicOverride":`Goal override 按完整配置生效`,"capabilities.atomicOverrideDescription":`Goal 的完整配置优先于机器默认值;LoopX 不会在两个作用域之间逐字段拼接。`,"capabilities.applyFailed":`Goal 能力变更未写入。`,"capabilities.applyPreview":`应用此预览`,"capabilities.catalog":`Goal 能力目录`,"capabilities.chooseGoal":`请先选择一个 Goal,再查看它的能力配置。`,"capabilities.defaultValue":`声明的默认值`,"capabilities.description":`查看当前 Goal 可用的能力,以及每项配置的准确作用域。`,"capabilities.editorPrepared":`已注册 typed editor contract`,"capabilities.effectiveSource":`当前生效来源`,"capabilities.empty":`当前 Goal 没有可用的能力描述。`,"capabilities.fields":`已注册字段`,"capabilities.goalPolicy":`Goal 能力策略`,"capabilities.goalScope":`Goal`,"capabilities.goalValue":`当前 Goal 值`,"capabilities.loadFailed":`无法加载 Goal 能力`,"capabilities.loading":`正在加载 Goal 能力…`,"capabilities.machineOnly":`此能力只能在机器作用域配置。`,"capabilities.machineValue":`实时机器默认值`,"capabilities.machineScope":`机器`,"capabilities.previewOnly":`当前读取结果来自真实配置;在 revision-locked preview/apply 路径接通前,Dashboard 不会提供 Goal 写入控件。`,"capabilities.preview":`锁定 revision 的变更预览`,"capabilities.previewChanges":`预览变更`,"capabilities.restoreInheritance":`恢复继承机器默认值`,"capabilities.previewFailed":`无法预览 Goal 能力变更。`,"capabilities.previewLocked":`应用时会重新校验这一个 plan revision;过期变更将被拒绝。`,"capabilities.partialWrite":`Goal 值已保存;共享投影仍需修复`,"capabilities.partialWriteDescription":`源 Goal 配置已经写入并回读,但共享 runtime 投影尚未同步;请勿重复提交本次变更。`,"capabilities.refreshSource":`刷新源配置`,"capabilities.readOnly":`只读能力`,"capabilities.revisionLockedReady":`所有变更必须先预览;只有对应的精确 revision 仍然有效时才会写入。`,"capabilities.retry":`重试`,"capabilities.source.capability_default":`能力默认值`,"capabilities.source.goal_override":`Goal override`,"capabilities.source.machine_default":`实时机器默认值`,"capabilities.source.not_configured":`未配置`,"capabilities.title":`Goal 能力`,"settings.close":`关闭设置`,"settings.appearance":`外观`,"settings.appearanceDescription":`管理当前浏览器里的工作区显示偏好。`,"settings.appearanceTabDescription":`主题和显示偏好`,"settings.capabilitiesTabDescription":`当前 Goal 的能力覆盖配置`,"settings.back":`返回工作区`,"settings.categories":`设置分类`,"settings.description":`管理工作区偏好与集成。`,"settings.eyebrow":`工作区偏好`,"settings.general":`通用`,"settings.goalConnections":`Goal 连接`,"settings.language":`语言`,"settings.languageDescription":`选择 LoopX Desktop 工作区使用的界面语言。`,"settings.languageEnglishDescription":`使用英文显示导航、设置和工作区控件。`,"settings.languageEnglish":`English`,"settings.languageSimplifiedChineseDescription":`使用简体中文显示导航、设置和工作区控件。`,"settings.languageSimplifiedChinese":`简体中文`,"settings.languageStoredLocally":`此偏好仅保存在当前设备。`,"settings.languageTabDescription":`当前设备的界面语言`,"settings.larkTabDescription":`App、群聊和 Goal Topic 连接`,"settings.machineTabDescription":`本机各 Capability 共享的 typed defaults`,"settings.notifications":`通知`,"settings.open":`设置`,"settings.themeDefault":`纸张`,"settings.themeDefaultDescription":`安静、轻量,适合长期查看。`,"settings.themeDescription":`选择工作区的视觉风格。设置会保存在当前浏览器本地。`,"settings.themeHighContrast":`高对比`,"settings.themeHighContrastDescription":`更强边框和更醒目的状态块。`,"settings.themeLoopx":`LoopX 标准`,"settings.themeLoopxDescription":`精确的黑白界面、Geist 字体与安静的细线结构。`,"settings.title":`设置`,"settings.workspaceDisplay":`工作区显示`,"settings.workspaceTheme":`工作区主题`,"session.closeRecord":`退出运行记录`,"session.details":`Session 详情`,"session.record":`执行 Session · 运行记录`,"session.recordDescription":`当前时间线已切换到这次 Session 的消息与 Turn 记录。`,"sidebar.createGoal":`创建 Goal`,"sidebar.delete":`删除`,"sidebar.deleteGoal":`删除 Goal`,"sidebar.manager":`LoopX 管家`,"sidebar.notifications":`设置`,"sidebar.owner":`个人工作区`,"sidebar.product":`个人 Agent 工作区`,"sidebar.resume":`恢复`,"sidebar.resumeGoal":`恢复 Goal`,"sidebar.stop":`停止`,"tasks.historyLoading":`正在加载历史…`,"tasks.historyError":`历史加载失败,已显示的内容仍可查看。`,"tasks.historyExpired":`历史快照已过期,重新加载后可继续查看。`,"tasks.historyRetry":`重新加载`,"tasks.historyEnd":`已显示全部完成记录`,"tasks.historyMore":`加载更多`,"tasks.historyLocalOnly":`请打开这台机器的 Dashboard 查看完整历史。`,"sidebar.sortGoals":`调整 Goal 顺序`,"sidebar.dragGoal":`拖拽调整顺序,或使用列表排序按钮`,"sidebar.moveUp":`上移 {goal}`,"sidebar.moveDown":`下移 {goal}`,"sidebar.goalMoved":`{goal} 已移至第 {position} 位`,"sidebar.orderNotSaved":`顺序已在本次页面生效;浏览器存储不可用,无法保存。`,"sidebar.stopGoal":`停止 Goal`,"sidebar.stopped":`已停止`,"sidebar.stoppedLoading":`正在加载已停止 Goal`,"sidebar.stoppedLoadFailed":`已停止 Goal 加载失败,其他 Goal 仍可使用。`,"sidebar.retryStopped":`重试`,"state.completed":`已完成`,"state.needsRepair":`需修复`,"state.needsYou":`等你`,"state.quiet":`安静运行`,"state.running":`推进中`,"state.stopped":`已停止`,"state.waiting":`等待条件`,"tasks.blocked":`受阻`,"tasks.agentLane":`工作 Agent`,"tasks.agentLaneDescription":`筛选这个 Goal 下的工作泳道`,"tasks.agentLaneFilter":`按工作 Agent 筛选`,"tasks.allAgentLanes":`全部 Agent({count})`,"tasks.chatAgentReplied":`Agent 已回复`,"tasks.chatPending":`已发送给 Agent`,"tasks.chatPendingDescription":`正在处理;只有经过确认的任务操作才会更新 Tasks。`,"tasks.chatRecent":`最近对话`,"tasks.chatUnchangedDescription":`本次对话没有直接修改 Tasks。需要执行时,可先转成 Task 草稿并确认。`,"tasks.chatViewReply":`查看回复`,"tasks.convertToTask":`转为 Task`,"tasks.completed":`已完成`,"runs.discoveryPartial":`部分执行详情暂不可用,正在重连;任务摘要不代表实时执行状态。`,"runs.discoveryOffline":`执行服务暂不可用,正在重连;保留的任务摘要可能已过时。`,"files.openConversation":`前往会话`,"files.exportSummary":`导出摘要`,"tasks.viewDescription":`先处理待确认,再查看工作与完成记录`,"tasks.viewLabel":`任务视图`,"tasks.listView":`列表`,"tasks.boardView":`看板`,"tasks.completedSummary":`已完成 {count} 项,近期完成明细由控制面按需投影。`,"tasks.emptyCompleted":`还没有完成的任务。`,"tasks.emptyConfirm":`没有待确认的任务。`,"tasks.emptyRunning":`没有待执行或进行中的任务。`,"tasks.emptySchedules":`没有定时任务。`,"tasks.emptyGoal":`这个 Goal 还没有任务。用下面的输入框描述下一步,LoopX 会先展示待确认操作。`,"tasks.markComplete":`标记完成:{name}`,"tasks.moreActions":`更多操作:{name}`,"tasks.openExecution":`查看执行过程:{name}`,"tasks.pending":`待处理`,"tasks.pendingAndRunning":`待执行 / 进行中`,"tasks.scheduled":`定时与持续`,"tasks.sessionError":`Session 异常`,"tasks.waiting":`待执行`,"tasks.waitingAge":`已等待 {age}`,"tasks.viewExecution":`查看执行过程`,"tasks.viewResult":`查看结果`,"time.days":`{count} 天`,"time.hours":`{count} 小时`,"timeline.emptyGoal":`这个 Goal 还没有新动态`,"timeline.emptyGoalDescription":`你可以直接询问进度或下发新的纠偏信息。`,"timeline.emptyWorkspace":`今天的工作区很安静`,"timeline.emptyWorkspaceDescription":`向 LoopX 管家描述一个 Goal,或询问今天最值得关注的事情。`,"timeline.gateHistory":`{count} 项历史 Gate`,"timeline.pending":`正在整理…`,"timeline.runCompleted":`{run}:已完成`,"timeline.review":`查看处理方式`,"timeline.reviewAndConfirm":`查看并确认`,"timeline.waitingConfirmation":`待你确认`}};function Wi(e,t){return t?Object.entries(t).reduce((e,[t,n])=>e.replaceAll(`{${t}}`,String(n)),e):e}function Gi(){try{return window.localStorage.getItem(`loopx-pw-locale`)===`en`?`en`:`zh-CN`}catch{return`zh-CN`}}function Ki({children:e}){let[t,n]=(0,B.useState)(Gi);function r(e){n(e);try{window.localStorage.setItem(Hi,e)}catch{}}(0,B.useEffect)(()=>{document.documentElement.lang=t},[t]);let i=(0,B.useMemo)(()=>({locale:t,setLocale:r,t:(e,n)=>Wi(Ui[t][e],n)}),[t]);return(0,V.jsx)(Vi.Provider,{value:i,children:e})}function qi(){let e=(0,B.useContext)(Vi);if(!e)throw Error(`useWorkspaceI18n must be used within WorkspaceI18nProvider`);return e}function Ji(e,t){let n={安静运行:`state.quiet`,等你:`state.needsYou`,等待条件:`state.waiting`,推进中:`state.running`,需修复:`state.needsRepair`,已完成:`state.completed`,已停止:`state.stopped`}[e];return n?Ui[t][n]:e}function Yi(e,t){let n={busy:`runs.running`,completed:`runs.completed`,failed:`runs.failed`,queued:`runs.queued`,ready:`runs.ready`,resume_failed:`runs.resumeFailed`,running:`runs.running`,waiting:`runs.waiting`};return e?n[e]?t(n[e]):e:t(`runs.unknown`)}function Xi(e,t){if(!e)return null;let n=new Date(e).getTime();if(Number.isNaN(n))return null;let r=Date.now()-n;if(r<36e5)return null;let i=Math.floor(r/864e5);return i>=1?t(`time.days`,{count:i}):t(`time.hours`,{count:Math.floor(r/36e5)})}var Zi;function U(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;en?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var Qi=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},$i=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Zi=globalThis).__zod_globalConfig??(Zi.__zod_globalConfig={});var ea=globalThis.__zod_globalConfig;function ta(e){return e&&Object.assign(ea,e),ea}function na(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function ra(e,t){return typeof t==`bigint`?t.toString():t}function ia(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function aa(e){return e==null}function oa(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function sa(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r){};function ha(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ga=ia(()=>{if(ea.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function _a(e){if(ha(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return ha(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function va(e){return _a(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var ya=new Set([`string`,`number`,`symbol`]);function ba(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function xa(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function W(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Sa(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var Ca={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function wa(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return xa(e,da(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return ua(this,`shape`,e),e},checks:[]}))}function Ta(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return xa(e,da(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return ua(this,`shape`,r),r},checks:[]}))}function Ea(e,t){if(!_a(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return xa(e,da(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return ua(this,`shape`,n),n}}))}function Da(e,t){if(!_a(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return xa(e,da(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return ua(this,`shape`,n),n}}))}function Oa(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return xa(e,da(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return ua(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function ka(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return xa(t,da(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return ua(this,`shape`,i),i},checks:[]}))}function Aa(e,t,n){return xa(t,da(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return ua(this,`shape`,i),i}}))}function ja(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Pa(e){return typeof e==`string`?e:e?.message}function Fa(e,t,n){let r=e.message?e.message:Pa(e.inst?._zod.def?.error?.(e))??Pa(t?.error?.(e))??Pa(n.customError?.(e))??Pa(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function Ia(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function La(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var Ra=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ra,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},za=U(`$ZodError`,Ra),Ba=U(`$ZodError`,Ra,{Parent:Error});function Va(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ha(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Qi;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Fa(e,a,ta())));throw ma(t,i?.callee),t}return o.value},Wa=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Fa(e,a,ta())));throw ma(t,i?.callee),t}return o.value},Ga=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Qi;return a.issues.length?{success:!1,error:new(e??za)(a.issues.map(e=>Fa(e,i,ta())))}:{success:!0,data:a.value}},Ka=Ga(Ba),qa=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>Fa(e,i,ta())))}:{success:!0,data:a.value}},Ja=qa(Ba),Ya=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ua(e)(t,n,i)},Xa=e=>(t,n,r)=>Ua(e)(t,n,r),Za=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Wa(e)(t,n,i)},Qa=e=>async(t,n,r)=>Wa(e)(t,n,r),$a=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ga(e)(t,n,i)},eo=e=>(t,n,r)=>Ga(e)(t,n,r),to=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return qa(e)(t,n,i)},no=e=>async(t,n,r)=>qa(e)(t,n,r),ro=/^[cC][0-9a-z]{6,}$/,io=/^[0-9a-z]+$/,ao=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,oo=/^[0-9a-vA-V]{20}$/,so=/^[A-Za-z0-9]{27}$/,co=/^[a-zA-Z0-9_-]{21}$/,lo=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,uo=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,fo=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,po=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,mo=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function ho(){return new RegExp(mo,`u`)}var go=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_o=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,vo=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,yo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bo=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,xo=/^[A-Za-z0-9_-]*$/,So=/^https?$/,Co=/^\+[1-9]\d{6,14}$/,wo=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,To=RegExp(`^${wo}$`);function Eo(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Do(e){return RegExp(`^${Eo(e)}$`)}function Oo(e){let t=Eo({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${wo}T(?:${r})$`)}var ko=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Ao=/^-?\d+$/,jo=/^-?\d+(?:\.\d+)?$/,Mo=/^(?:true|false)$/i,No=/^null$/i,Po=/^[^A-Z]*$/,Fo=/^[^a-z]*$/,Io=U(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Lo={number:`number`,bigint:`bigint`,object:`date`},Ro=U(`$ZodCheckLessThan`,(e,t)=>{Io.init(e,t);let n=Lo[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value{(t.inclusive?r.value<=t.value:r.value{Io.init(e,t);let n=Lo[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Bo=U(`$ZodCheckMultipleOf`,(e,t)=>{Io.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):sa(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Vo=U(`$ZodCheckNumberFormat`,(e,t)=>{Io.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Ca[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=Ao)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}sa&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Ho=U(`$ZodCheckMaxLength`,(e,t)=>{var n;Io.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!aa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum{let r=n.value;if(r.length<=t.maximum)return;let i=Ia(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Uo=U(`$ZodCheckMinLength`,(e,t)=>{var n;Io.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!aa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=Ia(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Wo=U(`$ZodCheckLengthEquals`,(e,t)=>{var n;Io.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!aa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=Ia(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Go=U(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Io.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Ko=U(`$ZodCheckRegex`,(e,t)=>{Go.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),qo=U(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Po,Go.init(e,t)}),Jo=U(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Fo,Go.init(e,t)}),Yo=U(`$ZodCheckIncludes`,(e,t)=>{Io.init(e,t);let n=ba(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Xo=U(`$ZodCheckStartsWith`,(e,t)=>{Io.init(e,t);let n=RegExp(`^${ba(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Zo=U(`$ZodCheckEndsWith`,(e,t)=>{Io.init(e,t);let n=RegExp(`.*${ba(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Qo=U(`$ZodCheckOverwrite`,(e,t)=>{Io.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),$o=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(` -`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(` -`))}},es={major:4,minor:4,patch:3},ts=U(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=es;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=ja(e),i;for(let a of t){if(a._zod.def.when){if(Ma(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new Qi;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=ja(e,t))});else{if(e.issues.length===t)continue;r||=ja(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(ja(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new Qi;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new Qi;return o.then(e=>t(e,r,a))}return t(o,r,a)}}la(e,`~standard`,()=>({validate:t=>{try{let n=Ka(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Ja(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),ns=U(`$ZodString`,(e,t)=>{ts.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ko(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),rs=U(`$ZodStringFormat`,(e,t)=>{Go.init(e,t),ns.init(e,t)}),is=U(`$ZodGUID`,(e,t)=>{t.pattern??=uo,rs.init(e,t)}),as=U(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=fo(e)}else t.pattern??=fo();rs.init(e,t)}),os=U(`$ZodEmail`,(e,t)=>{t.pattern??=po,rs.init(e,t)}),ss=U(`$ZodURL`,(e,t)=>{rs.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===So.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),n.value=t.normalize?i.href:r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),cs=U(`$ZodEmoji`,(e,t)=>{t.pattern??=ho(),rs.init(e,t)}),ls=U(`$ZodNanoID`,(e,t)=>{t.pattern??=co,rs.init(e,t)}),us=U(`$ZodCUID`,(e,t)=>{t.pattern??=ro,rs.init(e,t)}),ds=U(`$ZodCUID2`,(e,t)=>{t.pattern??=io,rs.init(e,t)}),fs=U(`$ZodULID`,(e,t)=>{t.pattern??=ao,rs.init(e,t)}),ps=U(`$ZodXID`,(e,t)=>{t.pattern??=oo,rs.init(e,t)}),ms=U(`$ZodKSUID`,(e,t)=>{t.pattern??=so,rs.init(e,t)}),hs=U(`$ZodISODateTime`,(e,t)=>{t.pattern??=Oo(t),rs.init(e,t)}),gs=U(`$ZodISODate`,(e,t)=>{t.pattern??=To,rs.init(e,t)}),_s=U(`$ZodISOTime`,(e,t)=>{t.pattern??=Do(t),rs.init(e,t)}),vs=U(`$ZodISODuration`,(e,t)=>{t.pattern??=lo,rs.init(e,t)}),ys=U(`$ZodIPv4`,(e,t)=>{t.pattern??=go,rs.init(e,t),e._zod.bag.format=`ipv4`}),bs=U(`$ZodIPv6`,(e,t)=>{t.pattern??=_o,rs.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),xs=U(`$ZodCIDRv4`,(e,t)=>{t.pattern??=vo,rs.init(e,t)}),Ss=U(`$ZodCIDRv6`,(e,t)=>{t.pattern??=yo,rs.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function Cs(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var ws=U(`$ZodBase64`,(e,t)=>{t.pattern??=bo,rs.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{Cs(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Ts(e){if(!xo.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Cs(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var Es=U(`$ZodBase64URL`,(e,t)=>{t.pattern??=xo,rs.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Ts(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Ds=U(`$ZodE164`,(e,t)=>{t.pattern??=Co,rs.init(e,t)});function Os(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var ks=U(`$ZodJWT`,(e,t)=>{rs.init(e,t),e._zod.check=n=>{Os(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),As=U(`$ZodNumber`,(e,t)=>{ts.init(e,t),e._zod.pattern=e._zod.bag.pattern??jo,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),js=U(`$ZodNumberFormat`,(e,t)=>{Vo.init(e,t),As.init(e,t)}),Ms=U(`$ZodBoolean`,(e,t)=>{ts.init(e,t),e._zod.pattern=Mo,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Ns=U(`$ZodNull`,(e,t)=>{ts.init(e,t),e._zod.pattern=No,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),Ps=U(`$ZodUnknown`,(e,t)=>{ts.init(e,t),e._zod.parse=e=>e}),Fs=U(`$ZodNever`,(e,t)=>{ts.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Is(e,t,n){e.issues.length&&t.issues.push(...Na(n,e.issues)),t.value[n]=e.value}var Ls=U(`$ZodArray`,(e,t)=>{ts.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;eIs(t,n,e))):Is(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function Rs(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...Na(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function zs(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Sa(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Bs(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Rs(e,n,i,t,u,d))):Rs(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var Vs=U(`$ZodObject`,(e,t)=>{if(ts.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=ia(()=>zs(t));la(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=ha,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>Rs(n,t,e,s,r,i))):Rs(a,t,e,s,r,i)}return i?Bs(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Hs=U(`$ZodObjectJIT`,(e,t)=>{Vs.init(e,t);let n=e._zod.parse,r=ia(()=>zs(t)),i=e=>{let t=new $o([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=fa(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=fa(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(` - if (${n}.issues.length) { - if (${o} in input) { - payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${o}, ...iss.path] : [${o}] - }))); - } - } - - if (${n}.value === undefined) { - if (${o} in input) { - newResult[${o}] = undefined; - } - } else { - newResult[${o}] = ${n}.value; - } - - `):c?t.write(` - if (${n}.issues.length) { - payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${o}, ...iss.path] : [${o}] - }))); - } - - if (${n}.value === undefined) { - if (${o} in input) { - newResult[${o}] = undefined; - } - } else { - newResult[${o}] = ${n}.value; - } - - `):t.write(` - const ${n}_present = ${o} in input; - if (${n}.issues.length) { - payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${o}, ...iss.path] : [${o}] - }))); - } - if (!${n}_present && !${n}.issues.length) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [${o}] - }); - } - - if (${n}_present) { - if (${n}.value === undefined) { - newResult[${o}] = undefined; - } else { - newResult[${o}] = ${n}.value; - } - } - - `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=ha,s=!ea.jitless,c=s&&ga.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?Bs([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function Us(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!ja(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Fa(e,r,ta())))}),t)}var Ws=U(`$ZodUnion`,(e,t)=>{ts.init(e,t),la(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),la(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),la(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),la(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>oa(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Us(t,r,e,i)):Us(o,r,e,i)}}),Gs=U(`$ZodIntersection`,(e,t)=>{ts.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>qs(e,t,n)):qs(e,i,a)}});function Ks(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(_a(e)&&_a(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Ks(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;re.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),ja(e))return e;let o=Ks(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var Js=U(`$ZodTuple`,(e,t)=>{ts.init(e,t);let n=t.items;e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({input:a,inst:e,expected:`tuple`,code:`invalid_type`}),r;r.value=[];let o=[],s=Ys(n,`optin`),c=Ys(n,`optout`);if(!t.rest){if(a.lengthn.length&&r.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:a,inst:e,origin:`array`})}let l=Array(n.length);for(let e=0;e{l[e]=t})):l[e]=t}if(t.rest){let e=n.length-1,s=a.slice(n.length);for(let n of s){e++;let a=t.rest._zod.run({value:n,issues:[]},i);a instanceof Promise?o.push(a.then(t=>Xs(t,r,e))):Xs(a,r,e)}}return o.length?Promise.all(o).then(()=>Zs(l,r,n,a,c)):Zs(l,r,n,a,c)}});function Ys(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!==`optional`)return n+1;return 0}function Xs(e,t,n){e.issues.length&&t.issues.push(...Na(n,e.issues)),t.value[n]=e.value}function Zs(e,t,n,r,i){for(let a=0;a=i){t.value.length=a;break}t.issues.push(...Na(a,n.issues))}t.value[a]=n.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}var Qs=U(`$ZodRecord`,(e,t)=>{ts.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!_a(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>Fa(e,r,ta())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...Na(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...Na(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&jo.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Fa(e,r,ta())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...Na(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...Na(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),$s=U(`$ZodEnum`,(e,t)=>{ts.init(e,t);let n=na(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>ya.has(typeof e)).map(e=>typeof e==`string`?ba(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),ec=U(`$ZodLiteral`,(e,t)=>{if(ts.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?ba(e):e?ba(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),tc=U(`$ZodTransform`,(e,t)=>{ts.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $i(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new Qi;return n.value=i,n.fallback=!0,n}});function nc(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var rc=U(`$ZodOptional`,(e,t)=>{ts.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,la(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),la(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${oa(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>nc(e,r)):nc(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),ic=U(`$ZodExactOptional`,(e,t)=>{rc.init(e,t),la(e._zod,`values`,()=>t.innerType._zod.values),la(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),ac=U(`$ZodNullable`,(e,t)=>{ts.init(e,t),la(e._zod,`optin`,()=>t.innerType._zod.optin),la(e._zod,`optout`,()=>t.innerType._zod.optout),la(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${oa(e.source)}|null)$`):void 0}),la(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),oc=U(`$ZodDefault`,(e,t)=>{ts.init(e,t),e._zod.optin=`optional`,la(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>sc(e,t)):sc(r,t)}});function sc(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var cc=U(`$ZodPrefault`,(e,t)=>{ts.init(e,t),e._zod.optin=`optional`,la(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),lc=U(`$ZodNonOptional`,(e,t)=>{ts.init(e,t),la(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>uc(t,e)):uc(i,e)}});function uc(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var dc=U(`$ZodCatch`,(e,t)=>{ts.init(e,t),e._zod.optin=`optional`,la(e._zod,`optout`,()=>t.innerType._zod.optout),la(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Fa(e,n,ta()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Fa(e,n,ta()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),fc=U(`$ZodPipe`,(e,t)=>{ts.init(e,t),la(e._zod,`values`,()=>t.in._zod.values),la(e._zod,`optin`,()=>t.in._zod.optin),la(e._zod,`optout`,()=>t.out._zod.optout),la(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>pc(e,t.in,n)):pc(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>pc(e,t.out,n)):pc(r,t.out,n)}});function pc(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var mc=U(`$ZodReadonly`,(e,t)=>{ts.init(e,t),la(e._zod,`propValues`,()=>t.innerType._zod.propValues),la(e._zod,`values`,()=>t.innerType._zod.values),la(e._zod,`optin`,()=>t.innerType?._zod?.optin),la(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(hc):hc(r)}});function hc(e){return e.value=Object.freeze(e.value),e}var gc=U(`$ZodCustom`,(e,t)=>{Io.init(e,t),ts.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>_c(t,n,r,e));_c(i,n,r,e)}});function _c(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(La(e))}}var vc,yc=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function bc(){return new yc}(vc=globalThis).__zod_globalRegistry??(vc.__zod_globalRegistry=bc());var xc=globalThis.__zod_globalRegistry;function Sc(e,t){return new e({type:`string`,...W(t)})}function Cc(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...W(t)})}function wc(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...W(t)})}function Tc(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...W(t)})}function Ec(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...W(t)})}function Dc(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...W(t)})}function Oc(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...W(t)})}function kc(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...W(t)})}function Ac(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...W(t)})}function jc(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...W(t)})}function Mc(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...W(t)})}function Nc(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...W(t)})}function Pc(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...W(t)})}function Fc(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...W(t)})}function Ic(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...W(t)})}function Lc(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...W(t)})}function Rc(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...W(t)})}function zc(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...W(t)})}function Bc(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...W(t)})}function Vc(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...W(t)})}function Hc(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...W(t)})}function Uc(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...W(t)})}function Wc(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...W(t)})}function Gc(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...W(t)})}function Kc(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...W(t)})}function qc(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...W(t)})}function Jc(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...W(t)})}function Yc(e,t){return new e({type:`number`,checks:[],...W(t)})}function Xc(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...W(t)})}function Zc(e,t){return new e({type:`boolean`,...W(t)})}function Qc(e,t){return new e({type:`null`,...W(t)})}function $c(e){return new e({type:`unknown`})}function el(e,t){return new e({type:`never`,...W(t)})}function tl(e,t){return new Ro({check:`less_than`,...W(t),value:e,inclusive:!1})}function nl(e,t){return new Ro({check:`less_than`,...W(t),value:e,inclusive:!0})}function rl(e,t){return new zo({check:`greater_than`,...W(t),value:e,inclusive:!1})}function il(e,t){return new zo({check:`greater_than`,...W(t),value:e,inclusive:!0})}function al(e,t){return new Bo({check:`multiple_of`,...W(t),value:e})}function ol(e,t){return new Ho({check:`max_length`,...W(t),maximum:e})}function sl(e,t){return new Uo({check:`min_length`,...W(t),minimum:e})}function cl(e,t){return new Wo({check:`length_equals`,...W(t),length:e})}function ll(e,t){return new Ko({check:`string_format`,format:`regex`,...W(t),pattern:e})}function ul(e){return new qo({check:`string_format`,format:`lowercase`,...W(e)})}function dl(e){return new Jo({check:`string_format`,format:`uppercase`,...W(e)})}function fl(e,t){return new Yo({check:`string_format`,format:`includes`,...W(t),includes:e})}function pl(e,t){return new Xo({check:`string_format`,format:`starts_with`,...W(t),prefix:e})}function ml(e,t){return new Zo({check:`string_format`,format:`ends_with`,...W(t),suffix:e})}function hl(e){return new Qo({check:`overwrite`,tx:e})}function gl(e){return hl(t=>t.normalize(e))}function _l(){return hl(e=>e.trim())}function vl(){return hl(e=>e.toLowerCase())}function yl(){return hl(e=>e.toUpperCase())}function bl(){return hl(e=>pa(e))}function xl(e,t,n){return new e({type:`array`,element:t,...W(n)})}function Sl(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...W(n)})}function Cl(e,t){let n=wl(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(La(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(La(r))}},e(t.value,t)),t);return n}function wl(e,t){let n=new Io({check:`custom`,...W(t)});return n._zod.check=e,n}function Tl(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??xc,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function El(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,El(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&kl(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Dl(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/ - -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function Ol(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:jl(t,`input`,e.processors),output:jl(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function kl(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return kl(r.element,n);if(r.type===`set`)return kl(r.valueType,n);if(r.type===`lazy`)return kl(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return kl(r.innerType,n);if(r.type===`intersection`)return kl(r.left,n)||kl(r.right,n);if(r.type===`record`||r.type===`map`)return kl(r.keyType,n)||kl(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:kl(r.in,n)||kl(r.out,n);if(r.type===`object`){for(let e in r.shape)if(kl(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(kl(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(kl(e,n))return!0;return!!(r.rest&&kl(r.rest,n))}return!1}var Al=(e,t={})=>n=>{let r=Tl({...n,processors:t});return El(e,r),Dl(r,e),Ol(r,e)},jl=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Tl({...i??{},target:a,io:t,processors:n});return El(e,o),Dl(o,e),Ol(o,e)},Ml={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Nl=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Ml[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Pl=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},Fl=(e,t,n,r)=>{n.type=`boolean`},Il=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Ll=(e,t,n,r)=>{n.not={}},Rl=(e,t,n,r)=>{let i=e._zod.def,a=na(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},zl=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Bl=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Vl=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Hl=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=El(a.element,t,{...r,path:[...r.path,`items`]})},Ul=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=El(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=El(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Wl=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>El(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Gl=(e,t,n,r)=>{let i=e._zod.def,a=El(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=El(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},Kl=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>El(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?El(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},ql=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=El(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=El(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=El(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},Jl=(e,t,n,r)=>{let i=e._zod.def,a=El(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Yl=(e,t,n,r)=>{let i=e._zod.def;El(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Xl=(e,t,n,r)=>{let i=e._zod.def;El(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Zl=(e,t,n,r)=>{let i=e._zod.def;El(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Ql=(e,t,n,r)=>{let i=e._zod.def;El(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},$l=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;El(o,t,r);let s=t.seen.get(e);s.ref=o},eu=(e,t,n,r)=>{let i=e._zod.def;El(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},tu=(e,t,n,r)=>{let i=e._zod.def;El(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},nu=U(`ZodISODateTime`,(e,t)=>{hs.init(e,t),Au.init(e,t)});function ru(e){return Gc(nu,e)}var iu=U(`ZodISODate`,(e,t)=>{gs.init(e,t),Au.init(e,t)});function au(e){return Kc(iu,e)}var ou=U(`ZodISOTime`,(e,t)=>{_s.init(e,t),Au.init(e,t)});function su(e){return qc(ou,e)}var cu=U(`ZodISODuration`,(e,t)=>{vs.init(e,t),Au.init(e,t)});function lu(e){return Jc(cu,e)}var uu=(e,t)=>{za.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Ha(e,t)},flatten:{value:t=>Va(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,ra,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,ra,2)}},isEmpty:{get(){return e.issues.length===0}}})},du=U(`ZodError`,uu),fu=U(`ZodError`,uu,{Parent:Error}),pu=Ua(fu),mu=Wa(fu),hu=Ga(fu),gu=qa(fu),_u=Ya(fu),vu=Xa(fu),yu=Za(fu),bu=Qa(fu),xu=$a(fu),Su=eo(fu),Cu=to(fu),wu=no(fu),Tu=new WeakMap;function Eu(e,t,n){let r=Object.getPrototypeOf(e),i=Tu.get(r);if(i||(i=new Set,Tu.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var Du=U(`ZodType`,(e,t)=>(ts.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:jl(e,`input`),output:jl(e,`output`)}}),e.toJSONSchema=Al(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>pu(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>hu(e,t,n),e.parseAsync=async(t,n)=>mu(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>gu(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>_u(e,t,n),e.decode=(t,n)=>vu(e,t,n),e.encodeAsync=async(t,n)=>yu(e,t,n),e.decodeAsync=async(t,n)=>bu(e,t,n),e.safeEncode=(t,n)=>xu(e,t,n),e.safeDecode=(t,n)=>Su(e,t,n),e.safeEncodeAsync=async(t,n)=>Cu(e,t,n),e.safeDecodeAsync=async(t,n)=>wu(e,t,n),Eu(e,`ZodType`,{check(...e){let t=this.def;return this.clone(da(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return xa(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Bd(e,t))},superRefine(e,t){return this.check(Vd(e,t))},overwrite(e){return this.check(hl(e))},optional(){return Sd(this)},exactOptional(){return wd(this)},nullable(){return Ed(this)},nullish(){return Sd(Ed(this))},nonoptional(e){return Md(this,e)},array(){return J(this)},or(e){return ld([this,e])},and(e){return dd(this,e)},transform(e){return Id(this,bd(e))},default(e){return Od(this,e)},prefault(e){return Ad(this,e)},catch(e){return Pd(this,e)},pipe(e){return Id(this,e)},readonly(){return Rd(this)},describe(e){let t=this.clone();return xc.add(t,{description:e}),t},meta(...e){if(e.length===0)return xc.get(this);let t=this.clone();return xc.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return xc.get(e)?.description},configurable:!0}),e)),Ou=U(`_ZodString`,(e,t)=>{ns.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Nl(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Eu(e,`_ZodString`,{regex(...e){return this.check(ll(...e))},includes(...e){return this.check(fl(...e))},startsWith(...e){return this.check(pl(...e))},endsWith(...e){return this.check(ml(...e))},min(...e){return this.check(sl(...e))},max(...e){return this.check(ol(...e))},length(...e){return this.check(cl(...e))},nonempty(...e){return this.check(sl(1,...e))},lowercase(e){return this.check(ul(e))},uppercase(e){return this.check(dl(e))},trim(){return this.check(_l())},normalize(...e){return this.check(gl(...e))},toLowerCase(){return this.check(vl())},toUpperCase(){return this.check(yl())},slugify(){return this.check(bl())}})}),ku=U(`ZodString`,(e,t)=>{ns.init(e,t),Ou.init(e,t),e.email=t=>e.check(Cc(ju,t)),e.url=t=>e.check(kc(Pu,t)),e.jwt=t=>e.check(Wc(Yu,t)),e.emoji=t=>e.check(Ac(Fu,t)),e.guid=t=>e.check(wc(Mu,t)),e.uuid=t=>e.check(Tc(Nu,t)),e.uuidv4=t=>e.check(Ec(Nu,t)),e.uuidv6=t=>e.check(Dc(Nu,t)),e.uuidv7=t=>e.check(Oc(Nu,t)),e.nanoid=t=>e.check(jc(Iu,t)),e.guid=t=>e.check(wc(Mu,t)),e.cuid=t=>e.check(Mc(Lu,t)),e.cuid2=t=>e.check(Nc(Ru,t)),e.ulid=t=>e.check(Pc(zu,t)),e.base64=t=>e.check(Vc(Ku,t)),e.base64url=t=>e.check(Hc(qu,t)),e.xid=t=>e.check(Fc(Bu,t)),e.ksuid=t=>e.check(Ic(Vu,t)),e.ipv4=t=>e.check(Lc(Hu,t)),e.ipv6=t=>e.check(Rc(Uu,t)),e.cidrv4=t=>e.check(zc(Wu,t)),e.cidrv6=t=>e.check(Bc(Gu,t)),e.e164=t=>e.check(Uc(Ju,t)),e.datetime=t=>e.check(ru(t)),e.date=t=>e.check(au(t)),e.time=t=>e.check(su(t)),e.duration=t=>e.check(lu(t))});function G(e){return Sc(ku,e)}var Au=U(`ZodStringFormat`,(e,t)=>{rs.init(e,t),Ou.init(e,t)}),ju=U(`ZodEmail`,(e,t)=>{os.init(e,t),Au.init(e,t)}),Mu=U(`ZodGUID`,(e,t)=>{is.init(e,t),Au.init(e,t)}),Nu=U(`ZodUUID`,(e,t)=>{as.init(e,t),Au.init(e,t)}),Pu=U(`ZodURL`,(e,t)=>{ss.init(e,t),Au.init(e,t)}),Fu=U(`ZodEmoji`,(e,t)=>{cs.init(e,t),Au.init(e,t)}),Iu=U(`ZodNanoID`,(e,t)=>{ls.init(e,t),Au.init(e,t)}),Lu=U(`ZodCUID`,(e,t)=>{us.init(e,t),Au.init(e,t)}),Ru=U(`ZodCUID2`,(e,t)=>{ds.init(e,t),Au.init(e,t)}),zu=U(`ZodULID`,(e,t)=>{fs.init(e,t),Au.init(e,t)}),Bu=U(`ZodXID`,(e,t)=>{ps.init(e,t),Au.init(e,t)}),Vu=U(`ZodKSUID`,(e,t)=>{ms.init(e,t),Au.init(e,t)}),Hu=U(`ZodIPv4`,(e,t)=>{ys.init(e,t),Au.init(e,t)}),Uu=U(`ZodIPv6`,(e,t)=>{bs.init(e,t),Au.init(e,t)}),Wu=U(`ZodCIDRv4`,(e,t)=>{xs.init(e,t),Au.init(e,t)}),Gu=U(`ZodCIDRv6`,(e,t)=>{Ss.init(e,t),Au.init(e,t)}),Ku=U(`ZodBase64`,(e,t)=>{ws.init(e,t),Au.init(e,t)}),qu=U(`ZodBase64URL`,(e,t)=>{Es.init(e,t),Au.init(e,t)}),Ju=U(`ZodE164`,(e,t)=>{Ds.init(e,t),Au.init(e,t)}),Yu=U(`ZodJWT`,(e,t)=>{ks.init(e,t),Au.init(e,t)}),Xu=U(`ZodNumber`,(e,t)=>{As.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pl(e,t,n,r),Eu(e,`ZodNumber`,{gt(e,t){return this.check(rl(e,t))},gte(e,t){return this.check(il(e,t))},min(e,t){return this.check(il(e,t))},lt(e,t){return this.check(tl(e,t))},lte(e,t){return this.check(nl(e,t))},max(e,t){return this.check(nl(e,t))},int(e){return this.check(Qu(e))},safe(e){return this.check(Qu(e))},positive(e){return this.check(rl(0,e))},nonnegative(e){return this.check(il(0,e))},negative(e){return this.check(tl(0,e))},nonpositive(e){return this.check(nl(0,e))},multipleOf(e,t){return this.check(al(e,t))},step(e,t){return this.check(al(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function K(e){return Yc(Xu,e)}var Zu=U(`ZodNumberFormat`,(e,t)=>{js.init(e,t),Xu.init(e,t)});function Qu(e){return Xc(Zu,e)}var $u=U(`ZodBoolean`,(e,t)=>{Ms.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fl(e,t,n,r)});function q(e){return Zc($u,e)}var ed=U(`ZodNull`,(e,t)=>{Ns.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Il(e,t,n,r)});function td(e){return Qc(ed,e)}var nd=U(`ZodUnknown`,(e,t)=>{Ps.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function rd(){return $c(nd)}var id=U(`ZodNever`,(e,t)=>{Fs.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ll(e,t,n,r)});function ad(e){return el(id,e)}var od=U(`ZodArray`,(e,t)=>{Ls.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hl(e,t,n,r),e.element=t.element,Eu(e,`ZodArray`,{min(e,t){return this.check(sl(e,t))},nonempty(e){return this.check(sl(1,e))},max(e,t){return this.check(ol(e,t))},length(e,t){return this.check(cl(e,t))},unwrap(){return this.element}})});function J(e,t){return xl(od,e,t)}var sd=U(`ZodObject`,(e,t)=>{Hs.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ul(e,t,n,r),la(e,`shape`,()=>t.shape),Eu(e,`ZodObject`,{keyof(){return _d(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:rd()})},loose(){return this.clone({...this._zod.def,catchall:rd()})},strict(){return this.clone({...this._zod.def,catchall:ad()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Ea(this,e)},safeExtend(e){return Da(this,e)},merge(e){return Oa(this,e)},pick(e){return wa(this,e)},omit(e){return Ta(this,e)},partial(...e){return ka(xd,this,e[0])},required(...e){return Aa(jd,this,e[0])}})});function Y(e,t){return new sd({type:`object`,shape:e??{},...W(t)})}var cd=U(`ZodUnion`,(e,t)=>{Ws.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wl(e,t,n,r),e.options=t.options});function ld(e,t){return new cd({type:`union`,options:e,...W(t)})}var ud=U(`ZodIntersection`,(e,t)=>{Gs.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gl(e,t,n,r)});function dd(e,t){return new ud({type:`intersection`,left:e,right:t})}var fd=U(`ZodTuple`,(e,t)=>{Js.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kl(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function pd(e,t,n){let r=t instanceof ts;return new fd({type:`tuple`,items:e,rest:r?t:null,...W(r?n:t)})}var md=U(`ZodRecord`,(e,t)=>{Qs.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ql(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function hd(e,t,n){return!t||!t._zod?new md({type:`record`,keyType:G(),valueType:e,...W(t)}):new md({type:`record`,keyType:e,valueType:t,...W(n)})}var gd=U(`ZodEnum`,(e,t)=>{$s.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rl(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new gd({...t,checks:[],...W(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new gd({...t,checks:[],...W(r),entries:i})}});function _d(e,t){return new gd({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...W(t)})}var vd=U(`ZodLiteral`,(e,t)=>{ec.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zl(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function X(e,t){return new vd({type:`literal`,values:Array.isArray(e)?e:[e],...W(t)})}var yd=U(`ZodTransform`,(e,t)=>{tc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vl(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $i(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(La(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(La(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function bd(e){return new yd({type:`transform`,transform:e})}var xd=U(`ZodOptional`,(e,t)=>{rc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>tu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Sd(e){return new xd({type:`optional`,innerType:e})}var Cd=U(`ZodExactOptional`,(e,t)=>{ic.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>tu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wd(e){return new Cd({type:`optional`,innerType:e})}var Td=U(`ZodNullable`,(e,t)=>{ac.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ed(e){return new Td({type:`nullable`,innerType:e})}var Dd=U(`ZodDefault`,(e,t)=>{oc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Od(e,t){return new Dd({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():va(t)}})}var kd=U(`ZodPrefault`,(e,t)=>{cc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ad(e,t){return new kd({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():va(t)}})}var jd=U(`ZodNonOptional`,(e,t)=>{lc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Md(e,t){return new jd({type:`nonoptional`,innerType:e,...W(t)})}var Nd=U(`ZodCatch`,(e,t)=>{dc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ql(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Pd(e,t){return new Nd({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var Fd=U(`ZodPipe`,(e,t)=>{fc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$l(e,t,n,r),e.in=t.in,e.out=t.out});function Id(e,t){return new Fd({type:`pipe`,in:e,out:t})}var Ld=U(`ZodReadonly`,(e,t)=>{mc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>eu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Rd(e){return new Ld({type:`readonly`,innerType:e})}var zd=U(`ZodCustom`,(e,t)=>{gc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bl(e,t,n,r)});function Bd(e,t={}){return Sl(zd,e,t)}function Vd(e,t){return Cl(e,t)}var Hd=e=>typeof e==`string`&&e.trim()?e.trim():null;function Ud(e){let t=e.decision_scope&&typeof e.decision_scope==`object`&&!Array.isArray(e.decision_scope)?e.decision_scope:{},n=Hd(t.kind),r=Hd(t.granularity),i=Hd(t.scope_key),a=Hd(e.superseded_by);return{interaction:e.task_class===`user_gate`?`decision`:`unknown`,lifecycle:a?`superseded`:e.status===`deferred`?`deferred`:e.done===!0||[`done`,`completed`,`closed`,`archived`].includes(String(e.status))?`closed`:e.status===`open`||e.status===`blocked`?`open`:`unknown`,reason:Hd(e.note),evidence:Hd(e.evidence),blocksAgent:Hd(e.blocks_agent),unblocksTodoId:Hd(e.unblocks_todo_id),decisionScope:n&&r&&i?{kind:n,granularity:r,scopeKey:i}:null,supersededBy:a}}function Wd(e,t,n,r){return{...e,sourceId:t,goalTitle:r??e.goalTitle,details:n?e.details:{...e.details??Ud({}),lifecycle:`unavailable`}}}function Gd(e,t){return t.find(t=>t.sourceId===e.sourceId&&t.goalId===e.goalId&&t.todoId===e.todoId)||{...e,details:{...e.details??Ud({}),lifecycle:`unavailable`}}}function Kd(e,t){let n=e.details?.supersededBy;if(!(!n||n===e.todoId||e.details?.lifecycle===`unavailable`))return t.find(t=>t.sourceId===e.sourceId&&t.goalId===e.goalId&&t.todoId===n)}function qd(e){return![`closed`,`deferred`,`superseded`,`unavailable`].includes(e.details?.lifecycle??`unknown`)}var Jd={ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,runtime_root:`$HOME/.codex/loopx`,goal_count:1,run_count:8440,status_contract:{schema_version:2,minimum_dashboard_schema_version:2,producer:`loopx status`,reload_hint:`scripts/macos-dashboard-launchagent.sh restart`},usage_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.471166+00:00`,sample_run_count:20,proxy_note:`run-history proxy; excludes token counts and raw thread logs`,totals:{runs_24h:20,runs_7d:20,quota_spend_slots_24h:11,quota_spend_slots_7d:11,automation_run_count_24h:11,automation_run_count_7d:11,progress_signal_run_count_24h:9,progress_signal_run_count_7d:9},goals:[{goal_id:`loopx-meta`,runs_24h:20,runs_7d:20,quota_spend_slots_24h:11,quota_spend_slots_7d:11,automation_run_count_24h:11,automation_run_count_7d:11,progress_signal_run_count_24h:9,progress_signal_run_count_7d:9,project_share_24h:1}]},event_ledger_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.360662+00:00`,sample_run_count:20,proxy_note:`append-only run-history projection; compact event-class counts only`,event_classes:[`accounting`,`decision`,`evidence`,`state`,`work`],totals:{events_24h:20,events_7d:20,by_class_24h:{accounting:11,decision:0,evidence:0,state:0,work:9},by_class_7d:{accounting:11,decision:0,evidence:0,state:0,work:9}},goals:[{goal_id:`loopx-meta`,events_24h:20,events_7d:20,by_class_24h:{accounting:11,decision:0,evidence:0,state:0,work:9},by_class_7d:{accounting:11,decision:0,evidence:0,state:0,work:9},latest_event_class:`accounting`,latest_event_at:`2026-07-06T14:37:32+08:00`}]},promotion_readiness_summary:{available:!0,source:`run_history_full_scan`,goal_id:`loopx-meta`,generated_at:`2026-07-05T20:02:02+08:00`,classification:`canary_promotion_readiness_smoke_group`,delivery_batch_scale:`multi_surface`,delivery_outcome:`primary_goal_outcome`,recommended_action:`Canary promotion-readiness smoke passed; promotion may proceed after doctor/status reports fresh evidence.`,json_exists:!0,markdown_exists:!0,freshness_window_hours:24,freshness_status:`fresh`,is_fresh:!0,requires_readiness_run:!1,age_seconds:67624,age_hours:18.78,freshness_reference_time:`2026-07-06T06:49:06.408527+00:00`,sample_run_count:0,proxy_note:`canary promotion-readiness projection from append-only run history; exact evidence stays in run artifacts`},promotion_gate:{ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,runtime_root:`$HOME/.codex/loopx`,gate:`promotion_readiness`,gate_state:`ready`,can_promote:!0,should_warn:!1,non_blocking:!0,recommended_action:`promotion readiness is fresh`,readiness:{available:!0,goal_id:`loopx-meta`,generated_at:`2026-07-05T20:02:02+08:00`,classification:`canary_promotion_readiness_smoke_group`,delivery_batch_scale:`multi_surface`,delivery_outcome:`primary_goal_outcome`,recommended_action:`Canary promotion-readiness smoke passed; promotion may proceed after doctor/status reports fresh evidence.`,json_exists:!0,markdown_exists:!0,runtime_root:`$HOME/.codex/loopx`,freshness_window_hours:24,freshness_status:`fresh`,is_fresh:!0,requires_readiness_run:!1,age_seconds:67624,age_hours:18.78,freshness_reference_time:`2026-07-06T06:49:06.471087+00:00`}},decision_freshness_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.471133+00:00`,sample_run_count:20,window_days:7,proxy_note:`checkpointed decision freshness projection; rebase old decisions at the decision point before reuse`,summary:{decision_count:0,stale_count:0,rebase_required_count:0,fresh_count:0},items:[]},todo_index:JSON.parse(`{"schema_version":"todo_index_v0","source":"live_loopx_status_public_slice","total_count":12,"current_projected_count":12,"rollout_event_count":94,"item_limit":12,"items":[{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo update recorded for todo_1596c3a678bb","schema_version":"todo_index_item_v0","todo_id":"todo_1596c3a678bb","role":"agent","status":"open","title":"todo update recorded for todo_1596c3a678bb","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:33:32Z","latest_event_status":"open","event_count":7,"event_kinds":["todo_update"]},{"goal_id":"loopx-meta","index":24,"done":false,"text":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","schema_version":"todo_index_item_v0","todo_id":"todo_15bc0926a494","role":"agent","status":"open","priority":"P0-REVENUE MONITOR","title":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"github_public_reply_metadata_monitor","claimed_by":"codex-value-explorer","evidence":"autonomous replan: bounded current value-explorer monitor lane with explicit expires_at.","note":"Set bounded watch expiry for metadata-only public reply monitor; no catch-up after expiry.","updated_at":"2026-07-05T06:27:15+08:00"},{"goal_id":"loopx-meta","index":17,"done":false,"text":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","schema_version":"todo_index_item_v0","todo_id":"todo_2bf560b48a0c","role":"agent","status":"open","priority":"P0","title":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"legacy_open_pr_rename_blocker","claimed_by":"codex-main-control"},{"goal_id":"loopx-meta","index":23,"done":false,"text":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","schema_version":"todo_index_item_v0","todo_id":"todo_3ed1c4a69164","role":"agent","status":"open","priority":"P0","title":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"skillsbench_local_verifier_reward_collection","claimed_by":"codex-main-control","required_capabilities":["benchmark_runner"]},{"goal_id":"loopx-meta","index":32,"done":false,"text":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","schema_version":"todo_index_item_v0","todo_id":"todo_44907a5f355d","role":"agent","status":"blocked","priority":"P0","title":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_raw_new_rerun","claimed_by":"codex-main-control","evidence":"Public-safe redacted live LoopX text; inspect local status for the full row.","note":"Do not spend a full citation-check loopx rerun yet: #865 fixed scored output paths and #874 added bootstrap preflight attribution, but citation-check itself still preflights as apt+verifier bootstrap risk on ECS.","updated_at":"2026-06-29T00:49:36+08:00"},{"goal_id":"loopx-meta","index":39,"done":false,"text":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","schema_version":"todo_index_item_v0","todo_id":"todo_4762c790e583","role":"agent","status":"blocked","priority":"P0","title":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_remote_rerun","claimed_by":"codex-main-control","evidence":"A prior benchmark adapter change was validated before the legacy surface was archived. Current research uses the RFC-linked benchmark workspace and toolkit boundary smokes.","note":"2026-06-29: fixed host-local ACP idle/no-output root cause in PR #894. ACP protocol tool_call_count=0 is now distinguished from reverse-channel task-facing bridge activity; repeated codex_exec_bridge_idle_timeout withou…","updated_at":"2026-06-29T19:40:32+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_584f55f8f3b4","schema_version":"todo_index_item_v0","todo_id":"todo_584f55f8f3b4","role":"agent","status":"open","title":"todo add recorded for todo_584f55f8f3b4","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:48:49Z","latest_event_status":"open","event_count":3,"event_kinds":["todo_add","todo_update"]},{"goal_id":"loopx-meta","index":40,"done":false,"text":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","schema_version":"todo_index_item_v0","todo_id":"todo_62debf065fec","role":"agent","status":"blocked","priority":"P0 MONITOR","title":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"monitor_skillsbench_batch","claimed_by":"codex-main-control","evidence":"Observed 2026-06-30T02:52+08: active-state target_key=skillsbench-goal-baseline-30case-20260629T1826Z-r10; local ps/tmux/recent artifact search found no r10 batch process or compact artifact; no raw task/log/trajectory …","updated_at":"2026-06-30T02:54:54+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_93bc6439c521","schema_version":"todo_index_item_v0","todo_id":"todo_93bc6439c521","role":"agent","status":"open","title":"todo add recorded for todo_93bc6439c521","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_claim","latest_event_at":"2026-07-06T06:32:52Z","latest_event_status":"open","event_count":2,"event_kinds":["todo_add","todo_claim"]},{"goal_id":"loopx-meta","index":27,"done":false,"text":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","schema_version":"todo_index_item_v0","todo_id":"todo_aad7e9716927","role":"agent","status":"blocked","priority":"P0","title":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"run_goal_start_product_mode_matrix","claimed_by":"codex-main-control","evidence":"driver.status shows DONE raw then RUN loopx-goal-start with no running driver; raw benchmark_run.compact first_blocker=skillsbench_codex_acp_provider_zero_activity; source guard requires --host-local-acp-launch for Loop…","note":"Remote run group skillsbench-raw-new-goal-start-20260627T0420Z produced a material closeout for citation-check raw only; raw compact attribution is skillsbench_codex_acp_provider_zero_activity with official score missin…","updated_at":"2026-06-27T13:05:47+08:00"},{"goal_id":"loopx-meta","index":21,"done":false,"text":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","schema_version":"todo_index_item_v0","todo_id":"todo_aec1873c7f28","role":"agent","status":"open","priority":"P0 MONITOR","title":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","claimed_by":"codex-main-control","note":"2026-06-23 projection fix: this is monitor context for the powerlifting run, not an advancement next action; current executable path is SkillsBench build cache/prewarm repair.","updated_at":"2026-06-23T10:37:43+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_c02cb7d19607","schema_version":"todo_index_item_v0","todo_id":"todo_c02cb7d19607","role":"agent","status":"open","title":"todo add recorded for todo_c02cb7d19607","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_add","latest_event_at":"2026-07-06T03:47:54Z","latest_event_status":"open","event_count":1,"event_kinds":["todo_add"]}]}`),agent_management_projection:{schema_version:`agent_management_projection_v0`,mode:`read_only`,goal_id:`loopx-meta`,generated_at:`2026-07-06T06:49:06Z`,style_hint:null,truth_contract:{todo_is_runtime_work_item:!0,projection_is_writable:!1,introduces_task_runtime:!1,write_api:!1},source_summary:{registered_agent_count:4,projected_agent_count:4,todo_source:`live_loopx_status_public_slice`,public_safe_export:!0},agents:[{agent_id:`codex-main-control`,agent_model:`peer_v1`,profile_role:`release-validation`,state:`blocked`,next_action:`Continue projected todo todo_2bf560b48a0c.`,last_activity_at:`2026-06-29T00:49:36+08:00`,evidence_refs:[`todo:todo_e72afc24f04a:evidence`],goal_ids:[`loopx-meta`],stale_claim_hint:{state:`activity_missing`,claimed_by:`codex-main-control`,reason:`claimed open todo has no projected activity timestamp`,recommended_operator_action:`inspect evidence before considering reassignment`},current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_2bf560b48a0c`,goal_id:`loopx-meta`,role:`agent`,status:`open`,priority:`P0`,title:`Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harn…`,task_class:`blocker`,action_kind:`legacy_open_pr_rename_blocker`,claimed_by:`codex-main-control`}},{agent_id:`codex-product-capability`,agent_model:`peer_v1`,profile_role:`product-validation`,state:`monitoring`,next_action:`Continue projected todo todo_ded745761822.`,last_activity_at:`2026-07-06T06:29:53Z`,evidence_refs:[`todo:todo_ded745761822:evidence`],goal_ids:[`loopx-meta`],current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_ded745761822`,goal_id:`loopx-meta`,role:`agent`,status:`open`,priority:`P0-LOCAL`,title:`Public-safe redacted live LoopX text; inspect local status for the full row.`,task_class:`continuous_monitor`,action_kind:`Public-safe redacted live LoopX text; inspect local status for the full row.`,claimed_by:`codex-product-capability`,updated_at:`2026-07-04T20:22:45+08:00`}},{agent_id:`codex-side-bypass`,agent_model:`peer_v1`,profile_role:`implementation-validation`,state:`waiting`,next_action:`Inspect status projection before taking work.`,last_activity_at:`2026-07-06T06:32:16Z`,evidence_refs:[`rollout_event:todo_complete:todo_22c946938115`],goal_ids:[`loopx-meta`]},{agent_id:`codex-value-explorer`,agent_model:`peer_v1`,profile_role:`value-exploration`,state:`monitoring`,next_action:`Continue projected todo todo_584f55f8f3b4.`,last_activity_at:`2026-07-06T09:39:59+08:00`,evidence_refs:[`rollout_event:todo_update:todo_584f55f8f3b4`],goal_ids:[`loopx-meta`],current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_584f55f8f3b4`,goal_id:`loopx-meta`,role:`agent`,status:`open`,title:`todo add recorded for todo_584f55f8f3b4`}}]},contract:{ok:!0,summary:{errors:0,warnings:1,checks:6},errors:[],warnings:["loopx-meta: duplicate index rows raw=8444 unique=8440 unexpected=3 artifact_identity_collisions=2 artifact_collision_rows=3 reward_overlays=1; inspect with `loopx history --goal-id loopx-meta inspect-index-duplicates`; artifact identity collisions need review…"],checks:[`registry goals checked: 12`,`registry boundary: shared_local_registry push_allowed=False tracked=False ignored=False`,`user-gate scopes checked: 6 open multi-agent gates`,`runtime root resolved: $HOME/.codex/loopx`,`run-history goals=28 runs=10210`,`public boundary scan clean: 1218 files`]},global_registry:{available:!0,ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,current_registry:`$HOME/.codex/loopx/registry.global.json`,current_registry_is_global:!0,global_goal_count:12,current_goal_count:12,source_registry_count:7,summary:{high:0,action:8,info:0,checks:2,findings:8},findings:[{kind:`source_registry_missing`,severity:`action`,message:"`cc-test` source registry is missing",recommended_action:"reconnect `cc-test` from its project or archive it if the project is obsolete",goal_id:`cc-test`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-test` active state file is missing",recommended_action:"repair `cc-test` state_file or reconnect the project",goal_id:`cc-test`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`cc-tmp` source registry is missing",recommended_action:"reconnect `cc-tmp` from its project or archive it if the project is obsolete",goal_id:`cc-tmp`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-tmp` active state file is missing",recommended_action:"repair `cc-tmp` state_file or reconnect the project",goal_id:`cc-tmp`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`cc-tmp-xdrchpuaul` source registry is missing",recommended_action:"reconnect `cc-tmp-xdrchpuaul` from its project or archive it if the project is obsolete",goal_id:`cc-tmp-xdrchpuaul`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-tmp-xdrchpuaul` active state file is missing",recommended_action:"repair `cc-tmp-xdrchpuaul` state_file or reconnect the project",goal_id:`cc-tmp-xdrchpuaul`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`loopx-auto-research-e2e-probe-20260628-2225-goal` source registry is missing",recommended_action:"reconnect `loopx-auto-research-e2e-probe-20260628-2225-goal` from its project or archive it if the project is obsolete",goal_id:`loopx-auto-research-e2e-probe-20260628-2225-goal`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`loopx-auto-research-e2e-probe-20260628-2225-goal` active state file is missing",recommended_action:"repair `loopx-auto-research-e2e-probe-20260628-2225-goal` state_file or reconnect the project",goal_id:`loopx-auto-research-e2e-probe-20260628-2225-goal`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`}],checks:[`global registry goals checked: 12`,`global source registries checked: 7`]},attention_queue:JSON.parse(`{"available":true,"item_count":1,"needs_user_or_controller":0,"needs_controller":0,"needs_codex":1,"watching_external_evidence":0,"items":[{"goal_id":"loopx-meta","status":"skillsbench_codex_cli_goal_tail4_keepalive_relaunched","lifecycle_phase":"adapter_inspected","lifecycle_flags":["adapter_inspected"],"waiting_on":"codex","severity":"action","recommended_action":"Monitor run_group skillsbench-codex-cli-goal-xhigh-tail4-keepalive-20260706T143132CST using public compact/public artifacts only; once benchmark_run.compact.json lands for each case, classify launcher/case/solver/verifi…","source":"latest_run","quota":{"compute":1.0,"window_hours":24,"slot_minutes":1,"allowed_slots":1440,"spent_slots":97,"state":"eligible","reason":"1 compute quota; eligible for the next automatic agent turn"},"agent_todos":{"source_section":"Agent Todo","total_count":12,"open_count":12,"done_count":0,"items":[{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo update recorded for todo_1596c3a678bb","schema_version":"todo_index_item_v0","todo_id":"todo_1596c3a678bb","role":"agent","status":"open","title":"todo update recorded for todo_1596c3a678bb","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:33:32Z","latest_event_status":"open","event_count":7,"event_kinds":["todo_update"]},{"goal_id":"loopx-meta","index":24,"done":false,"text":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","schema_version":"todo_index_item_v0","todo_id":"todo_15bc0926a494","role":"agent","status":"open","priority":"P0-REVENUE MONITOR","title":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"github_public_reply_metadata_monitor","claimed_by":"codex-value-explorer","evidence":"autonomous replan: bounded current value-explorer monitor lane with explicit expires_at.","note":"Set bounded watch expiry for metadata-only public reply monitor; no catch-up after expiry.","updated_at":"2026-07-05T06:27:15+08:00"},{"goal_id":"loopx-meta","index":17,"done":false,"text":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","schema_version":"todo_index_item_v0","todo_id":"todo_2bf560b48a0c","role":"agent","status":"open","priority":"P0","title":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"legacy_open_pr_rename_blocker","claimed_by":"codex-main-control"},{"goal_id":"loopx-meta","index":23,"done":false,"text":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","schema_version":"todo_index_item_v0","todo_id":"todo_3ed1c4a69164","role":"agent","status":"open","priority":"P0","title":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"skillsbench_local_verifier_reward_collection","claimed_by":"codex-main-control","required_capabilities":["benchmark_runner"]},{"goal_id":"loopx-meta","index":32,"done":false,"text":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","schema_version":"todo_index_item_v0","todo_id":"todo_44907a5f355d","role":"agent","status":"blocked","priority":"P0","title":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_raw_new_rerun","claimed_by":"codex-main-control","evidence":"Public-safe redacted live LoopX text; inspect local status for the full row.","note":"Do not spend a full citation-check loopx rerun yet: #865 fixed scored output paths and #874 added bootstrap preflight attribution, but citation-check itself still preflights as apt+verifier bootstrap risk on ECS.","updated_at":"2026-06-29T00:49:36+08:00"},{"goal_id":"loopx-meta","index":39,"done":false,"text":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","schema_version":"todo_index_item_v0","todo_id":"todo_4762c790e583","role":"agent","status":"blocked","priority":"P0","title":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_remote_rerun","claimed_by":"codex-main-control","evidence":"A prior benchmark adapter change was validated before the legacy surface was archived. Current research uses the RFC-linked benchmark workspace and toolkit boundary smokes.","note":"2026-06-29: fixed host-local ACP idle/no-output root cause in PR #894. ACP protocol tool_call_count=0 is now distinguished from reverse-channel task-facing bridge activity; repeated codex_exec_bridge_idle_timeout withou…","updated_at":"2026-06-29T19:40:32+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_584f55f8f3b4","schema_version":"todo_index_item_v0","todo_id":"todo_584f55f8f3b4","role":"agent","status":"open","title":"todo add recorded for todo_584f55f8f3b4","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:48:49Z","latest_event_status":"open","event_count":3,"event_kinds":["todo_add","todo_update"]},{"goal_id":"loopx-meta","index":40,"done":false,"text":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","schema_version":"todo_index_item_v0","todo_id":"todo_62debf065fec","role":"agent","status":"blocked","priority":"P0 MONITOR","title":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"monitor_skillsbench_batch","claimed_by":"codex-main-control","evidence":"Observed 2026-06-30T02:52+08: active-state target_key=skillsbench-goal-baseline-30case-20260629T1826Z-r10; local ps/tmux/recent artifact search found no r10 batch process or compact artifact; no raw task/log/trajectory …","updated_at":"2026-06-30T02:54:54+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_93bc6439c521","schema_version":"todo_index_item_v0","todo_id":"todo_93bc6439c521","role":"agent","status":"open","title":"todo add recorded for todo_93bc6439c521","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_claim","latest_event_at":"2026-07-06T06:32:52Z","latest_event_status":"open","event_count":2,"event_kinds":["todo_add","todo_claim"]},{"goal_id":"loopx-meta","index":27,"done":false,"text":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","schema_version":"todo_index_item_v0","todo_id":"todo_aad7e9716927","role":"agent","status":"blocked","priority":"P0","title":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"run_goal_start_product_mode_matrix","claimed_by":"codex-main-control","evidence":"driver.status shows DONE raw then RUN loopx-goal-start with no running driver; raw benchmark_run.compact first_blocker=skillsbench_codex_acp_provider_zero_activity; source guard requires --host-local-acp-launch for Loop…","note":"Remote run group skillsbench-raw-new-goal-start-20260627T0420Z produced a material closeout for citation-check raw only; raw compact attribution is skillsbench_codex_acp_provider_zero_activity with official score missin…","updated_at":"2026-06-27T13:05:47+08:00"},{"goal_id":"loopx-meta","index":21,"done":false,"text":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","schema_version":"todo_index_item_v0","todo_id":"todo_aec1873c7f28","role":"agent","status":"open","priority":"P0 MONITOR","title":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","claimed_by":"codex-main-control","note":"2026-06-23 projection fix: this is monitor context for the powerlifting run, not an advancement next action; current executable path is SkillsBench build cache/prewarm repair.","updated_at":"2026-06-23T10:37:43+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_c02cb7d19607","schema_version":"todo_index_item_v0","todo_id":"todo_c02cb7d19607","role":"agent","status":"open","title":"todo add recorded for todo_c02cb7d19607","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_add","latest_event_at":"2026-07-06T03:47:54Z","latest_event_status":"open","event_count":1,"event_kinds":["todo_add"]}]}}]}`),run_history:{available:!0,goal_count:1,run_count:5,goals:[{id:`loopx-meta`,domain:`loopx-platform`,status:`active-read-only`,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`],registry_member:!0,legacy_runtime_goal:!1,adapter_kind:`harness_self_improvement`,adapter_status:`connected-read-only`,index_exists:!0,raw_index_records:8444,unique_runs:8440,quota:{compute:1,window_hours:24,slot_minutes:1,allowed_slots:1440,spent_slots:97,state:`waiting`,reason:`no active Codex-ready work is currently selected`},latest_runs:[{generated_at:`2026-07-06T14:37:32+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-value-explorer`,recommended_action:`审阅 PR #1524 的 Agent Management 面板视觉方向:workspace hint 与 stale claim hint 是否符合预期;确认后允许 codex-value-explorer 自合并。`,health_check:`quota safe-bypass operator gate; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:55+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-main-control`,recommended_action:`[P1] Repair SkillsBench post-run debug gate consistency for countable codex-cli-goal official-zero runs: when attempt_accounting is countable and case_closeout_complete=true, do not project first_blocker=loopx_closeout_…`,health_check:`quota should-run eligible; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:54+08:00`,goal_id:`loopx-meta`,classification:`skillsbench_codex_cli_goal_tail4_keepalive_relaunched`,agent_id:`codex-main-control`,progress_scope:`goal`,delivery_batch_scale:`single_surface`,delivery_outcome:`outcome_progress`,recommended_action:`Monitor run_group skillsbench-codex-cli-goal-xhigh-tail4-keepalive-20260706T143132CST using public compact/public artifacts only; once benchmark_run.compact.json lands for each case, classify launcher/case/solver/verifi…`,health_check:`state_file 1/1; registry_goal 1/1; authority_sources 10`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:34+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-side-bypass`,recommended_action:`[P0] Rerun real KNN visible auto-research after the successor-link fix and verify evaluator completion projects a second-round hypothesis/frontier or explicit completion gate without manual intervention; keep evidence p…`,health_check:`quota should-run eligible; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:32:57+08:00`,goal_id:`loopx-meta`,classification:`auto_research_successor_link_fix_merged`,agent_id:`codex-side-bypass`,progress_scope:`agent_lane`,delivery_batch_scale:`implementation`,delivery_outcome:`outcome_progress`,recommended_action:`[P0] Rerun real KNN visible auto-research after the successor-link fix and verify evaluator completion projects a second-round hypothesis/frontier or explicit completion gate without manual intervention; keep evidence p…`,health_check:`state_file 1/1; registry_goal 1/1; authority_sources 0`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]}]}]}},Yd=G().nullable(),Xd=Y({schema_version:X(`goal_acceptance_observation_projection_v0`),goal_id:G(),read_only:X(!0),acceptance_assessed:X(!1),coverage:_d([`partial`,`unavailable`]),missing_sources:J(G()),truncated:q(),historical_progress:J(Y({kind:G(),observed_at:Yd,source:G(),evidence_refs:J(G())})),acceptance_gaps:J(Y({kind:G(),owner:Yd,reason:Yd,evidence_required:Yd,observed_at:Yd,source:G()})),guards:J(Y({kind:G(),todo_id:Yd,blocks_agent:Yd,owner:Yd,reason:Yd,evidence_required:Yd,decision_scope:Yd})),next_action:Yd,next_action_source:Yd}),Zd=ld([G(),K(),q(),td()]),Qd=hd(G(),Zd),$d=Y({todo_id:G().optional(),priority:G().optional(),status:G(),title:G(),claimed_by:G().optional(),task_class:G().optional(),action_kind:G().optional()}),ef=Y({gate_id:G(),kind:G(),status:G(),blocks:J(G()).optional()}),tf=Y({todo_id:G().optional(),owner_agent:G().optional(),status:G().optional(),lease_until:G().optional(),write_scope:J(G()).optional()}),nf=Y({generated_at:G().optional(),classification:G().optional(),summary:G().optional()}),rf=Y({kind:G().optional().default(`warning`),message:ld([G(),J(G())]).optional().default(`compact source warning`)}).passthrough(),af=Y({schema_version:X(`goal_channel_projection_v0`),mode:X(`read_only`),goal_id:G(),display_name:G(),generated_at:G().optional().nullable(),latest_status:G(),waiting_on:G(),next_action:G(),source_refs:hd(G(),Zd),decision_frame:Y({user_action_required:q(),agent_action_required:q(),quiet_noop_allowed:q()}),quota:Qd,user_todos:J($d).default([]),agent_todos:J($d).default([]),open_gates:J(ef).default([]),active_leases:J(tf).default([]),artifacts:J(Qd).default([]),recent_events:J(nf).default([]),source_warnings:J(rf).default([]),truth_contract:Y({event_ledger_is_source_of_truth:q(),projection_is_writable:q(),recompute_rule:G(),write_authority:G()})}),of=Y({compute:K().optional().default(1),window_hours:K().optional().default(24),slot_minutes:K().optional().default(1),allowed_slots:K().optional().nullable(),spent_slots:K().optional().default(0),state:G().optional().nullable(),next_eligible_at:G().optional().nullable(),reason:G().optional().nullable(),blocked_action_scope:G().optional().nullable(),focus_wait:q().optional().nullable(),handoff_outcome_floor_block:q().optional().nullable(),safe_bypass_allowed:q().optional().default(!1),safe_bypass_kind:G().optional().nullable(),safe_bypass_policy:G().optional().nullable(),post_handoff_outcome_gap_streak:K().optional().nullable(),outcome_gap_threshold:K().optional().nullable(),must_advance:J(G()).optional().default([]),avoid:J(G()).optional().default([])}).transform(e=>{let t=Math.max(1,e.slot_minutes),n=Math.round(e.window_hours*60*e.compute/t);return{...e,slot_minutes:t,allowed_slots:e.allowed_slots??n}}),sf=Y({self_repair:Y({enabled:q().optional().default(!1),allow_health_blocker_repair:q().optional().default(!1),allow_waiting_projection_repair:q().optional().default(!1)}).optional().nullable()}).passthrough(),cf=Y({model_config:Y({model:G(),reasoning_effort:G().optional()}).optional(),mode:G().optional().default(`default`),orchestration_mode:G().optional().nullable(),spawn_allowed:q().optional().default(!1),allowed:q().optional().nullable(),max_children:K().optional().default(0),allowed_domains:J(G()).optional().default([])}).passthrough(),lf=Y({label:G().optional().nullable(),path:G(),anchor:G().optional().nullable(),exists:q().optional().default(!1),resolved_path:G().optional().nullable()}),uf=Y({index:K(),done:q(),text:G(),schema_version:G().optional().nullable(),todo_id:G().optional().nullable(),role:G().optional().nullable(),status:G().optional().nullable(),resume_when:G().optional().nullable(),resume_ready:q().optional().nullable(),resume_condition:hd(G(),rd()).optional().nullable(),priority:G().optional().nullable(),title:G().optional().nullable(),archive_state:G().optional().nullable(),source_section:G().optional().nullable(),task_class:G().optional().nullable(),task_domain:G().optional().nullable(),action_kind:G().optional().nullable(),claimed_by:G().optional().nullable(),required_capabilities:J(G()).optional(),note:G().optional().nullable(),evidence:G().optional().nullable(),updated_at:G().optional().nullable(),review_materials:J(lf).optional().default([])}).passthrough(),df=Y({source_section:G().optional().nullable(),total_count:K().optional().default(0),open_count:K().optional().default(0),done_count:K().optional().default(0),advancement_done_count:K().optional(),items:J(uf).optional().default([]),deferred_items:J(uf).optional()}),ff=uf.extend({goal_id:G(),source:G().optional().nullable(),event_count:K().optional().default(0),event_kinds:J(G()).optional().default([]),latest_event_kind:G().optional().nullable(),latest_event_at:G().optional().nullable(),latest_event_status:G().optional().nullable(),agent_id:G().optional().nullable()}).passthrough(),pf=Y({schema_version:G().optional().nullable(),source:G().optional().nullable(),total_count:K().optional().default(0),current_projected_count:K().optional().default(0),rollout_event_count:K().optional().default(0),item_limit:K().optional().nullable(),items:J(ff).optional().default([])}),mf=Y({kind:G().optional().nullable(),label:G().optional().nullable(),path_safe:q().optional().default(!1),branch:G().optional().nullable(),write_scope:J(G()).optional().default([])}).passthrough(),hf=Y({state:G().optional().nullable(),claimed_by:G().optional().nullable(),last_activity_at:G().optional().nullable(),threshold_hours:K().optional().nullable(),reason:G().optional().nullable(),recommended_operator_action:G().optional().nullable()}).passthrough(),gf=Y({schema_version:G().optional().nullable(),todo_id:G().optional().nullable(),goal_id:G().optional().nullable(),role:G().optional().nullable(),status:G().optional().nullable(),priority:G().optional().nullable(),title:G().optional().nullable(),task_class:G().optional().nullable(),action_kind:G().optional().nullable(),claimed_by:G().optional().nullable(),required_write_scopes:J(G()).optional().default([]),workspace_ref:mf.optional().nullable()}).passthrough(),_f=Y({schema_version:G().optional().nullable(),from_agent:G().optional().nullable(),to_agent:G().optional().nullable(),intent:G().optional().nullable(),summary:G().optional().nullable(),blocker:G().optional().nullable(),suggested_next_action:G().optional().nullable(),evidence_refs:J(G()).optional().default([]),updated_at:G().optional().nullable()}).passthrough(),vf=Y({agent_id:G(),role:G().optional().nullable(),state:G().optional().nullable(),current_todo:gf.optional().nullable(),next_action:G().optional().nullable(),last_activity_at:G().optional().nullable(),evidence_refs:J(G()).optional().default([]),handoff_refs:J(G()).optional().default([]),handoff_note:_f.optional().nullable(),workspace_ref:mf.optional().nullable(),stale_claim_hint:hf.optional().nullable(),blocked_on:gf.optional().nullable(),goal_ids:J(G()).optional().default([])}).passthrough(),yf=Y({schema_version:G().optional().nullable(),mode:G().optional().nullable(),goal_id:G().optional().nullable(),generated_at:G().optional().nullable(),style_hint:Y({preferred:G().optional().nullable(),license_boundary:G().optional().nullable()}).optional().nullable(),truth_contract:Y({todo_is_runtime_work_item:q().optional().default(!0),projection_is_writable:q().optional().default(!1),introduces_task_runtime:q().optional().default(!1),write_api:q().optional().default(!1)}).optional().nullable(),source_summary:Y({registered_agent_count:K().optional().default(0),projected_agent_count:K().optional().default(0),todo_source:G().optional().nullable()}).optional().nullable(),agents:J(vf).optional().default([])}).passthrough(),bf=Y({goal_id:G(),configured:q().optional().default(!1),enabled:q().optional().default(!1),human_gate_auto_notify_enabled:q().optional().default(!1),target_ref:G().optional().nullable(),receipt_count:K().optional().default(0),last_notified_at:G().optional().nullable()}).passthrough(),xf=Y({schema_version:G().optional().nullable(),generated_at:G().optional().nullable(),goals:J(bf).optional().default([])}).passthrough(),Sf=Y({source_section:G().optional().nullable(),open:K().optional().default(0),done:K().optional().default(0),total:K().optional().default(0),advancement_done_count:K().optional(),next:G().optional().nullable(),next_index:K().optional().nullable(),items:J(uf).optional().default([]),recent_completed_advancement_items:J(uf).optional().default([])}),Cf=Y({goal_id:G(),status:G().optional().nullable(),waiting_on:G().optional().nullable(),severity:G().optional().nullable(),index:K().optional().nullable(),text:G(),source:G().optional().nullable()}),wf=Y({source:G().optional().nullable(),open_count:K().optional().default(0),items:J(Cf).optional().default([])}),Tf=Y({goal_id:G(),status:G().optional().nullable(),waiting_on:G().optional().nullable(),quota_state:G().optional().nullable(),priority:G().optional().nullable(),todo_index:K().optional().nullable(),text:G(),source:G().optional().nullable()}),Ef=Y({source:G().optional().nullable(),open_count:K().optional().default(0),items:J(Tf).optional().default([])}),Df=Y({generated_at:G().optional().nullable(),classification:G().optional().nullable(),summary:G().optional().nullable()}),Of=Y({kind:G().optional().nullable(),source:G().optional().nullable(),severity:G().optional().nullable(),requires_refresh_state:q().optional().default(!1),reason:G().optional().nullable(),active_state_updated_at:G().optional().nullable(),latest_run_generated_at:G().optional().nullable(),latest_run_state_updated_at:G().optional().nullable(),latest_run_classification:G().optional().nullable(),recommended_action:G().optional().nullable()}),kf=Y({generated_at:G().optional().nullable(),classification:G().optional().nullable(),delivery_batch_scale:G().optional().nullable(),delivery_outcome:G().optional().nullable(),health_check:G().optional().nullable(),json_exists:q().optional().nullable(),markdown_exists:q().optional().nullable()}),Af=Y({project_asset_backed:q().optional(),same_source_should_run:q().optional(),codex_ready:q().optional(),handoff_has_next_action:q().optional(),handoff_has_stop_condition:q().optional(),handoff_sanitized_surface:q().optional()}).catchall(q()),jf=Y({ready:q().optional().default(!1),codex_ready:q().optional().default(!1),source:G().optional().nullable(),quota_state:G().optional().nullable(),checks:Af.optional().default({}),handoff_status:G().optional().nullable(),handoff_ready_at:G().optional().nullable(),handoff_ready_classification:G().optional().nullable(),post_handoff_run_seen:q().optional().default(!1),post_handoff_latest_run:kf.optional().nullable(),post_handoff_recent_runs:J(kf).optional().default([]),post_handoff_small_scale_streak:K().int().nonnegative().optional().default(0),post_handoff_outcome_gap_streak:K().int().nonnegative().optional().default(0),next_probe:G().optional().nullable()}),Mf=Y({schema_version:G().optional().nullable(),kind:G().optional().nullable(),missing_roles:J(G()).optional().default([]),source:G().optional().nullable(),recommended_action:G().optional().nullable()}),Nf=Y({owner:G(),gate:G(),next_action:G(),stop_condition:G(),user_todos:Sf.optional().nullable(),agent_todos:Sf.optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),orchestration:cf.optional().nullable(),latest_validation:Df.optional().nullable(),stale_latest_run_warning:Of.optional().nullable(),todo_projection_gap:Mf.optional().nullable()}),Pf=Y({goal_id:G(),activation_state:_d([`active`,`stopped`]).optional().default(`active`),status:G(),waiting_on:G(),severity:G(),recommended_action:G(),project_asset:Nf.optional().nullable(),handoff_readiness:jf.optional().nullable(),source:G().optional(),operator_question:G().optional().nullable(),agent_command:G().optional().nullable(),lifecycle_phase:G().optional().nullable(),lifecycle_flags:J(G()).optional().default([]),controller_stage:G().optional().nullable(),missing_gates:J(G()).optional().default([]),next_handoff_condition:G().optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),user_todos:df.optional().nullable(),agent_todos:df.optional().nullable(),stale_latest_run_warning:Of.optional().nullable(),dependency_blockers:wf.optional().nullable(),todo_state_file:G().optional().nullable(),goal_channel_projection:af.optional().nullable()}),Ff=Y({recorded_at:G().optional().nullable(),decision:G().optional().nullable(),reward:G().optional().nullable(),reason_summary:G().optional().nullable(),follow_up:G().optional().nullable()}),If=Y({recorded_at:G().optional().nullable(),gate:G().optional().nullable(),decision:G().optional().nullable(),operator_question:G().optional().nullable(),reason_summary:G().optional().nullable(),follow_up:G().optional().nullable(),agent_command:G().optional().nullable()}),Lf=Y({version:G().optional().nullable(),goal_id:G().optional().nullable(),run_id:G().optional().nullable(),gate_id:G().optional().nullable(),created_state_ref:G().optional().nullable(),created_policy_version:G().optional().nullable(),interrupt_payload:Y({question:G().optional().nullable(),choices:J(G()).optional().default([])}).optional().nullable(),allowed_decisions:J(G()).optional().default([]),operator_decision:G().optional().nullable(),latest_state_ref:G().optional().nullable(),freshness_check:G().optional().nullable(),precondition_check:G().optional().nullable(),migration_or_rebase_result:G().optional().nullable(),resulting_action:G().optional().nullable(),validation_after_resume:G().optional().nullable()}),Rf=Y({id:G().optional().nullable(),ok:q().optional().nullable(),review:G().optional().nullable()}),zf=Y({classification:G().optional().nullable(),read_only_observer_ready:q().optional().nullable(),decision_advisor_ready:q().optional().nullable(),write_controller_ready:q().optional().nullable(),missing_gates:J(G()).optional().default([]),review_judgment:G().optional().nullable(),next_handoff_condition:G().optional().nullable(),gates:J(Rf).optional().default([])}),Bf=Y({declared:q().optional().default(!1),required:q().optional().default(!1),path:G().optional().nullable(),path_exists:q().optional().nullable(),read_status:G().optional().nullable(),default_entry_count:K().optional().default(0),default_entries_checked:K().optional().default(0),default_entries_present:K().optional().default(0),topic_authority_count:K().optional().default(0),project_material_count:K().optional().default(0),project_material_repository_count:K().optional().default(0),project_material_owner_review_required_count:K().optional().default(0),project_material_stale_count:K().optional().default(0),project_material_current_authority_count:K().optional().default(0),deprecated_source_count:K().optional().default(0),conflict_risk:G().optional().nullable()}),Vf=Y({adapter_kind:G().optional().nullable(),adapter_status:G().optional().nullable(),authority_source_count:K().optional().nullable(),authority_registry_declared:q().optional().nullable(),authority_registry_path_exists:q().optional().nullable(),authority_registry_default_entry_count:K().optional().nullable(),authority_registry_default_entries_present:K().optional().nullable(),topic_authority_count:K().optional().nullable(),project_material_count:K().optional().nullable(),project_material_repository_count:K().optional().nullable(),project_material_owner_review_required_count:K().optional().nullable(),project_material_stale_count:K().optional().nullable(),project_material_current_authority_count:K().optional().nullable(),authority_registry_conflict_risk:G().optional().nullable(),guard_count:K().optional().nullable(),sections_found:K().optional().nullable(),sections_checked:K().optional().nullable(),files_present:K().optional().nullable(),files_checked:K().optional().nullable()}),Hf=Y({generated_at:G(),goal_id:G(),classification:G().optional().nullable(),lifecycle_phase:G().optional().nullable(),lifecycle_flags:J(G()).optional().default([]),recommended_action:G().optional().nullable(),health_check:G().optional().nullable(),active_task_count:K().optional().nullable(),active_priorities:hd(G(),rd()).optional().nullable(),cache_check:G().optional().nullable(),json_exists:q().optional().default(!1),markdown_exists:q().optional().default(!1),human_reward:Ff.optional().nullable(),operator_gate:If.optional().nullable(),operator_gate_resume_contract:Lf.optional().nullable(),controller_readiness:zf.optional().nullable(),project_map:Vf.optional().nullable()}),Uf=Y({acceptance_observation:Xd.optional().nullable().catch(null),id:G(),activation_state:_d([`active`,`stopped`]).optional().default(`active`),display_name:G().optional().nullable(),domain:G().optional().nullable(),status:G().optional().nullable(),lifecycle_phase:G().optional().nullable(),lifecycle_flags:J(G()).optional().default([]),registry_member:q().optional().default(!1),legacy_runtime_goal:q().optional().default(!1),adapter_kind:G().optional().nullable(),adapter_status:G().optional().nullable(),authority_registry:Bf.optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),spawn_policy:cf.optional().nullable(),orchestration:cf.optional().nullable(),coordination:Y({agent_model:G().optional().nullable(),registered_agents:J(G()).optional().default([])}).optional().nullable(),index_exists:q().optional().default(!1),raw_index_records:K().optional().default(0),unique_runs:K().optional().default(0),latest_runs:J(Hf).optional().default([])}),Wf=Y({available:q(),goal_count:K().optional().default(0),run_count:K().optional().default(0),goals:J(Uf).optional().default([]),recent_runs:J(Hf).optional().default([])}),Gf=Y({kind:G(),severity:G(),message:G(),recommended_action:G(),goal_id:G().optional().nullable(),path:G().optional().nullable(),goal_ids:J(G()).optional().default([])}),Kf=Y({available:q(),ok:q(),registry:G(),current_registry:G().optional().nullable(),current_registry_is_global:q().optional().default(!1),global_goal_count:K().optional().default(0),current_goal_count:K().optional().default(0),source_registry_count:K().optional().default(0),summary:Y({high:K().optional().default(0),action:K().optional().default(0),info:K().optional().default(0),checks:K().optional().default(0),findings:K().optional().default(0)}),findings:J(Gf).optional().default([]),checks:J(G()).optional().default([])}),qf=Y({runs_24h:K().optional().default(0),runs_7d:K().optional().default(0),quota_spend_slots_24h:K().optional().default(0),quota_spend_slots_7d:K().optional().default(0),automation_run_count_24h:K().optional().default(0),automation_run_count_7d:K().optional().default(0),progress_signal_run_count_24h:K().optional().default(0),progress_signal_run_count_7d:K().optional().default(0),input_tokens_24h:K().optional(),input_tokens_7d:K().optional(),output_tokens_24h:K().optional(),output_tokens_7d:K().optional(),cache_tokens_24h:K().optional(),cache_tokens_7d:K().optional(),cost_usd_24h:K().optional(),cost_usd_7d:K().optional(),duration_ms_24h:K().optional(),duration_ms_7d:K().optional()}),Jf=qf.extend({goal_id:G(),project_share_24h:K().optional().default(0)}),Yf=Y({available:q().optional().default(!0),source:G().optional().default(`run_history`),generated_at:G().optional().nullable(),sample_run_count:K().optional().default(0),proxy_note:G().optional().nullable(),totals:qf.optional().default({runs_24h:0,runs_7d:0,quota_spend_slots_24h:0,quota_spend_slots_7d:0,automation_run_count_24h:0,automation_run_count_7d:0,progress_signal_run_count_24h:0,progress_signal_run_count_7d:0}),goals:J(Jf).optional().default([])}).optional().nullable(),Xf=Y({accounting:K().optional().default(0),decision:K().optional().default(0),evidence:K().optional().default(0),state:K().optional().default(0),work:K().optional().default(0)}),Zf={accounting:0,decision:0,evidence:0,state:0,work:0},Qf=Y({events_24h:K().optional().default(0),events_7d:K().optional().default(0),by_class_24h:Xf.optional().default(Zf),by_class_7d:Xf.optional().default(Zf)}),$f=Qf.extend({goal_id:G(),latest_event_class:G().optional().nullable(),latest_event_at:G().optional().nullable()}),ep={events_24h:0,events_7d:0,by_class_24h:Zf,by_class_7d:Zf},tp=Y({available:q().optional().default(!0),source:G().optional().default(`run_history`),generated_at:G().optional().nullable(),sample_run_count:K().optional().default(0),proxy_note:G().optional().nullable(),event_classes:J(G()).optional().default([`accounting`,`decision`,`evidence`,`state`,`work`]),totals:Qf.optional().default(ep),goals:J($f).optional().default([])}).optional().nullable(),np=Y({available:q().optional().default(!1),source:G().optional().default(`run_history`),goal_id:G().optional().nullable(),generated_at:G().optional().nullable(),classification:G().optional().nullable(),delivery_batch_scale:G().optional().nullable(),delivery_outcome:G().optional().nullable(),recommended_action:G().optional().nullable(),json_exists:q().optional().default(!1),markdown_exists:q().optional().default(!1),freshness_window_hours:K().optional().default(24),freshness_status:G().optional().nullable(),is_fresh:q().optional().default(!1),requires_readiness_run:q().optional().default(!0),age_seconds:K().optional().nullable(),age_hours:K().optional().nullable(),freshness_reference_time:G().optional().nullable(),sample_run_count:K().optional().default(0),proxy_note:G().optional().nullable(),reason:G().optional().nullable()}).optional().nullable(),rp=Y({ok:q().optional().default(!0),registry:G().optional().nullable(),runtime_root:G().optional().nullable(),gate:G().optional().default(`promotion_readiness`),gate_state:G().optional().default(`warning`),can_promote:q().optional().default(!1),should_warn:q().optional().default(!0),non_blocking:q().optional().default(!0),recommended_action:G().optional().nullable(),warning_message:G().optional().nullable(),readiness:np.default(null)}).optional().nullable(),ip=Y({decision_count:K().optional().default(0),stale_count:K().optional().default(0),rebase_required_count:K().optional().default(0),fresh_count:K().optional().default(0)}),ap=Y({goal_id:G(),decision_kind:G().optional().nullable(),decision_at:G().optional().nullable(),classification:G().optional().nullable(),age_days:K().optional().nullable(),stale_by_age:q().optional().default(!1),newer_event_count_7d:K().optional().default(0),newer_event_classes_7d:Xf.optional().default(Zf),freshness_state:G().optional().nullable(),requires_decision_point_rebase:q().optional().default(!1),reason:G().optional().nullable()}),op=Y({available:q().optional().default(!0),source:G().optional().default(`run_history`),generated_at:G().optional().nullable(),sample_run_count:K().optional().default(0),window_days:K().optional().default(7),proxy_note:G().optional().nullable(),summary:ip.optional().default({decision_count:0,stale_count:0,rebase_required_count:0,fresh_count:0}),items:J(ap).optional().default([])}).optional().nullable(),sp=Y({schema_version:K().optional().default(0),minimum_dashboard_schema_version:K().optional().default(2),producer:G().optional().nullable(),reload_hint:G().optional().nullable()}).optional().default({schema_version:0,minimum_dashboard_schema_version:2,producer:null,reload_hint:`scripts/macos-dashboard-launchagent.sh restart`}),cp=Y({schema_version:X(`loopx_goal_projection_scope_v0`),scope:_d([`all`,`active`,`stopped`]),complete:q(),projected_goal_count:K().int().nonnegative(),registry_goal_count:K().int().nonnegative(),registry_revision:G().optional().nullable()}),lp=Y({source:G().optional().default(`serve-status`),status_url:G().optional().nullable(),health_url:G().optional().nullable(),review_material_url:G().optional().nullable(),presentation_surfaces_url:G().optional().nullable(),presentation_detail_url:G().optional().nullable(),periodic_report_index_url:G().optional().nullable(),periodic_report_detail_url:G().optional().nullable(),ssh_hosts_url:G().optional().nullable(),reward_dry_run_url:G().optional().nullable(),reward_append_url:G().optional().nullable(),reward_write_enabled:q().optional().default(!1),configure_goal_dry_run_url:G().optional().nullable(),configure_goal_apply_url:G().optional().nullable(),control_plane_write_enabled:q().optional().default(!1)}).optional().nullable(),up=Y({extension_id:G().min(1),surface_id:G().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/),extension_revision:G().min(1),payload_sha256:G().regex(/^[0-9a-f]{64}$/)}).strict(),dp=Y({extension_id:G().min(1),extension_revision:G().min(1),surface_id:G().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/),surface_kind:G().regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/),title:G().min(1),view_schema:G().regex(/^[a-z][a-z0-9_]*_v\d+$/),visibility:_d([`public-safe`,`owner-only`]),goal_id:G().min(1).nullable(),generated_at:G().min(1).nullable(),review_due_at:G().min(1).nullable(),diagnostic:G().min(1).nullable(),empty_state_title:G().min(1),empty_state_detail:G().min(1)}),fp=ld([dp.extend({state:_d([`ready`,`review_due`]),goal_id:G().min(1),generated_at:G().min(1),detail_ref:up}).strict(),dp.extend({state:X(`empty`),detail_ref:ad().optional()}).strict(),dp.extend({state:X(`invalid`),diagnostic:G().min(1),detail_ref:ad().optional()}).strict()]),pp=Y({schema_version:X(`extension_presentation_surfaces_v0`),count:K().int().nonnegative(),ready_count:K().int().nonnegative(),review_due_count:K().int().nonnegative(),empty_count:K().int().nonnegative(),invalid_count:K().int().nonnegative(),items:J(fp)}).strict(),mp={schema_version:`extension_presentation_surfaces_v0`,count:0,ready_count:0,review_due_count:0,empty_count:0,invalid_count:0,items:[]};Y({ok:X(!0),presentation_surfaces:pp}).strict();var hp=Y({goal_id:G().min(1),agent_id:G().min(1),generation_id:G().min(1),content_sha256:G().regex(/^sha256:[0-9a-f]{64}$/)}).strict(),gp=Y({goal_id:G().min(1),agent_id:G().min(1),generation_id:G().min(1),publication_id:G().min(1),delivered_at:G().min(1),predecessor_publication_id:G().min(1).nullable().optional(),detail_ref:hp}).strict(),_p=Y({schema_version:X(`periodic_report_workspace_index_v0`),count:K().int().nonnegative(),items:J(gp)}),vp=_p.extend({returned_count:K().int().nonnegative(),total_count:K().int().nonnegative(),limit:K().int().nonnegative(),offset:K().int().nonnegative(),truncated:q()}).strict(),yp=_p.strict().transform(e=>({...e,returned_count:e.count,total_count:e.count,limit:e.count,offset:0,truncated:!1})),bp=Y({ok:X(!0),periodic_reports:ld([vp,yp])}).strict(),xp=Y({schema_version:X(`periodic_report_workspace_projection_v0`),goal_id:G().min(1),agent_id:G().min(1),generation_id:G().min(1),generated_at:G().min(1),title:G().min(1),summary:G().min(1),content_sha256:G().regex(/^sha256:[0-9a-f]{64}$/),period_window:Y({start_at:G().min(1),end_at:G().min(1)}).strict(),interaction:Y({attention_kind:X(`progress`),interaction:X(`inform`),delivery:X(`surface`),form:X(`milestone_report`),writable:X(!1)}).strict(),delta:Y({added_count:K().int().nonnegative(),changed_count:K().int().nonnegative(),item_count:K().int().positive(),items:J(Y({fact_id:G().min(1),source_ref:G().min(1),title:G().min(1),summary:G().min(1),status:G().min(1),content_kind:G().min(1),change_kind:_d([`added`,`changed`]),previous_status:G().min(1).optional()}).strict())}).strict(),publication:Y({publication_id:G().min(1),delivered_at:G().min(1),predecessor_publication_id:G().min(1).nullable().optional(),cursor_id:G().min(1)}).strict(),truth_contract:Y({published_cursor_is_source_of_truth:X(!0),generation_receipt_is_delivery_receipt:X(!1),projection_is_writable:X(!1),browser_write_api:X(!1)}).strict()}).strict(),Sp=Y({ok:X(!0),projection:xp}).strict(),Cp=Y({ok:q(),registry:G(),runtime_root:G(),goal_count:K(),run_count:K(),status_contract:sp,goal_projection:cp.optional().nullable().default(null),local_dashboard_api:lp,contract:Y({ok:q(),summary:Y({errors:K(),warnings:K(),checks:K()}),errors:J(G()),warnings:J(G()),checks:J(G()).optional().default([])}),global_registry:Kf.optional().default({available:!1,ok:!0,registry:``,current_registry:null,current_registry_is_global:!1,global_goal_count:0,current_goal_count:0,source_registry_count:0,summary:{high:0,action:0,info:0,checks:0,findings:0},findings:[],checks:[]}),attention_queue:Y({available:q(),item_count:K(),needs_user_or_controller:K(),needs_controller:K().optional().default(0),needs_codex:K(),watching_external_evidence:K(),autonomous_backlog_candidates:Ef.optional().nullable(),items:J(Pf)}),run_history:Wf.optional().default({available:!1,goal_count:0,run_count:0,goals:[],recent_runs:[]}),event_ledger_summary:tp.default(null),promotion_readiness_summary:np.default(null),promotion_gate:rp.default(null),decision_freshness_summary:op.default(null),usage_summary:Yf.default(null),todo_index:pf.optional().nullable().default(null),agent_management_projection:yf.optional().nullable().default(null),goal_channel_notification_projection:xf.optional().nullable().default(null),presentation_surfaces:pp.optional().default(mp)});Y({ok:q(),dry_run:q().optional().default(!0),appended:q().optional().default(!1),goal_id:G().optional().nullable(),raw_index_records_before:K().optional().nullable(),preview_id:G().optional().nullable(),selected_run:Y({generated_at:G().optional().nullable(),classification:G().optional().nullable(),recommended_action:G().optional().nullable(),json_exists:q().optional().nullable(),markdown_exists:q().optional().nullable()}).optional().nullable(),human_reward:Ff.optional().nullable(),active_state_summary:G().optional().nullable(),project_agent_visibility:Y({source_of_truth:G().optional().nullable(),history_command:G().optional().nullable(),active_state_role:G().optional().nullable(),review_packet_role:G().optional().nullable()}).optional().nullable(),error:G().optional().nullable()});function wp(e,t,n){let r=e.run_history.goals.map(e=>e.id===t&&e.activation_state!==n?{...e,activation_state:n}:e),i=e.attention_queue.items.map(e=>e.goal_id===t&&e.activation_state!==n?{...e,activation_state:n}:e),a=r.some((t,n)=>t!==e.run_history.goals[n]),o=i.some((t,n)=>t!==e.attention_queue.items[n]);return!a&&!o?e:{...e,attention_queue:o?{...e.attention_queue,items:i}:e.attention_queue,run_history:a?{...e.run_history,goals:r}:e.run_history}}function Tp(e,t){let n=e.run_history.goals.filter(e=>e.id!==t),r=e.attention_queue.items.filter(e=>e.goal_id!==t);return n.length===e.run_history.goals.length&&r.length===e.attention_queue.items.length?e:{...e,attention_queue:{...e.attention_queue,items:r},run_history:{...e.run_history,goals:n}}}function Ep(e){return Cp.parse(e)}function Dp(e){return e instanceof du?e.issues.map(e=>`${e.path.join(`.`)||`root`}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}var Op=Ep(Jd),kp=Y({ok:X(!0),schema_version:X(`loopx_workspace_directory_v1`),registry_revision:G(),goals:J(Y({id:G(),display_name:G(),activation_state:_d([`active`,`stopped`]),registry_member:X(!0)}))});function Ap(e,t,n){let r=new URL(e,n);r.searchParams.delete(`goal_activation`),r.searchParams.delete(`goal_id`),r.searchParams.delete(`view`);for(let[e,n]of Object.entries(t))r.searchParams.set(e,n);return r.toString()}async function jp(e,t){let n=await fetch(Ap(e,{view:`workspace-directory`},t),{cache:`no-store`,signal:AbortSignal.timeout(5e3)});if(!n.ok)return null;let r=kp.safeParse(await n.json());return r.success?r.data:null}function Mp(e){return Ep({ok:!0,registry:``,runtime_root:``,goal_count:e.goals.length,run_count:0,local_dashboard_api:{},contract:{ok:!0,summary:{errors:0,warnings:0,checks:0},errors:[],warnings:[]},attention_queue:{available:!1,item_count:0,needs_user_or_controller:0,needs_codex:0,watching_external_evidence:0,items:[]},run_history:{available:!1,goal_count:e.goals.length,run_count:0,goals:e.goals,recent_runs:[]}})}async function Np(e,t,n,r,i,a,o){let s=[...n.goals],c=new Map;async function l(){for(;s.length&&i()&&!o?.aborted;){let l=s.findIndex(e=>e.id===a()),u=l>=0?l:s.findIndex(e=>e.activation_state===`active`);if(u<0)return;let d=s.splice(u,1)[0],f=(c.get(d.id)??0)+1;c.set(d.id,f);let p=new AbortController,m=!1,h=()=>p.abort();o?.addEventListener(`abort`,h,{once:!0});let g=setTimeout(()=>{m=!0,p.abort()},3e4),_=null;try{let a=await fetch(Ap(e,{goal_id:d.id},t),{cache:`no-store`,signal:p.signal});if(!a.ok)_=a.status===409?`revision`:a.status>=500?`service`:`scope`;else{let e=await a.json();if(e.workspace_registry_revision!==n.registry_revision)_=`revision`;else{let t=Ep(e);!t.run_history.goals.some(e=>e.id===d.id)||t.run_history.goals.some(e=>e.id!==d.id)?_=`scope`:i()&&!o?.aborted&&r(d.id,t,null)}}}catch(e){_=m?`timeout`:e instanceof TypeError?`network`:`invalid`}finally{clearTimeout(g),o?.removeEventListener(`abort`,h)}if(!i()||o?.aborted)return;_&&[`timeout`,`network`,`service`].includes(_)&&f<3?(await new Promise(e=>setTimeout(e,f*1e3)),s.push(d)):_&&r(d.id,null,_)}}await Promise.all([l(),l()])}var Pp=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),Fp=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),Ip=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),Lp=e=>{let t=Ip(e);return t.charAt(0).toUpperCase()+t.slice(1)},Rp={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`},zp=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},Bp=(0,B.createContext)({}),Vp=()=>(0,B.useContext)(Bp),Hp=(0,B.forwardRef)(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>{let{size:l=24,strokeWidth:u=2,absoluteStrokeWidth:d=!1,color:f=`currentColor`,className:p=``}=Vp()??{},m=r??d?Number(n??u)*24/Number(t??l):n??u;return(0,B.createElement)(`svg`,{ref:c,...Rp,width:t??l??Rp.width,height:t??l??Rp.height,stroke:e??f,strokeWidth:m,className:Pp(`lucide`,p,i),...!a&&!zp(s)&&{"aria-hidden":`true`},...s},[...o.map(([e,t])=>(0,B.createElement)(e,t)),...Array.isArray(a)?a:[a]])}),Z=(e,t)=>{let n=(0,B.forwardRef)(({className:n,...r},i)=>(0,B.createElement)(Hp,{ref:i,iconNode:t,className:Pp(`lucide-${Fp(Lp(e))}`,`lucide-${e}`,n),...r}));return n.displayName=Lp(e),n},Up=Z(`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`}]]),Wp=Z(`arrow-down`,[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]),Gp=Z(`arrow-left`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]),Kp=Z(`arrow-right`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]),qp=Z(`arrow-up-down`,[[`path`,{d:`m21 16-4 4-4-4`,key:`f6ql7i`}],[`path`,{d:`M17 20V4`,key:`1ejh1v`}],[`path`,{d:`m3 8 4-4 4 4`,key:`11wl7u`}],[`path`,{d:`M7 4v16`,key:`1glfcx`}]]),Jp=Z(`arrow-up`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),Yp=Z(`badge-check`,[[`path`,{d:`M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z`,key:`3c2336`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),Xp=Z(`bell`,[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}]]),Zp=Z(`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`}]]),Qp=Z(`braces`,[[`path`,{d:`M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1`,key:`ezmyqa`}],[`path`,{d:`M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1`,key:`e1hn23`}]]),$p=Z(`calendar-clock`,[[`path`,{d:`M16 14v2.2l1.6 1`,key:`fo4ql5`}],[`path`,{d:`M16 2v4`,key:`4m81vk`}],[`path`,{d:`M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5`,key:`1osxxc`}],[`path`,{d:`M3 10h5`,key:`r794hk`}],[`path`,{d:`M8 2v4`,key:`1cmpym`}],[`circle`,{cx:`16`,cy:`16`,r:`6`,key:`qoo3c4`}]]),em=Z(`check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),tm=Z(`chevron-down`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),nm=Z(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),rm=Z(`chevron-up`,[[`path`,{d:`m18 15-6-6-6 6`,key:`153udz`}]]),im=Z(`circle-alert`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`12`,x2:`12`,y1:`8`,y2:`12`,key:`1pkeuh`}],[`line`,{x1:`12`,x2:`12.01`,y1:`16`,y2:`16`,key:`4dfq90`}]]),am=Z(`circle-check`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),om=Z(`clipboard-check`,[[`rect`,{width:`8`,height:`4`,x:`8`,y:`2`,rx:`1`,ry:`1`,key:`tgr4d6`}],[`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`,key:`116196`}],[`path`,{d:`m9 14 2 2 4-4`,key:`df797q`}]]),sm=Z(`code-xml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),cm=Z(`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`}]]),lm=Z(`database`,[[`ellipse`,{cx:`12`,cy:`5`,rx:`9`,ry:`3`,key:`msslwz`}],[`path`,{d:`M3 5V19A9 3 0 0 0 21 19V5`,key:`1wlel7`}],[`path`,{d:`M3 12A9 3 0 0 0 21 12`,key:`mv7ke4`}]]),um=Z(`download`,[[`path`,{d:`M12 15V3`,key:`m9g1x1`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`path`,{d:`m7 10 5 5 5-5`,key:`brsn70`}]]),dm=Z(`ellipsis`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]]),fm=Z(`external-link`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),pm=Z(`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`}]]),mm=Z(`file-braces`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1`,key:`1oajmo`}],[`path`,{d:`M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1`,key:`mpwhp6`}]]),hm=Z(`file-check-corner`,[[`path`,{d:`M10.5 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v6`,key:`g5mvt7`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`m14 20 2 2 4-4`,key:`15kota`}]]),gm=Z(`file-text`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),_m=Z(`git-branch`,[[`path`,{d:`M15 6a9 9 0 0 0-9 9V3`,key:`1cii5b`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}]]),vm=Z(`git-compare-arrows`,[[`circle`,{cx:`5`,cy:`6`,r:`3`,key:`1qnov2`}],[`path`,{d:`M12 6h5a2 2 0 0 1 2 2v7`,key:`1yj91y`}],[`path`,{d:`m15 9-3-3 3-3`,key:`1lwv8l`}],[`circle`,{cx:`19`,cy:`18`,r:`3`,key:`1qljk2`}],[`path`,{d:`M12 18H7a2 2 0 0 1-2-2V9`,key:`16sdep`}],[`path`,{d:`m9 15 3 3-3 3`,key:`1m3kbl`}]]),ym=Z(`info`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]),bm=Z(`languages`,[[`path`,{d:`m5 8 6 6`,key:`1wu5hv`}],[`path`,{d:`m4 14 6-6 2-3`,key:`1k1g8d`}],[`path`,{d:`M2 5h12`,key:`or177f`}],[`path`,{d:`M7 2h1`,key:`1t2jsx`}],[`path`,{d:`m22 22-5-10-5 10`,key:`don7ne`}],[`path`,{d:`M14 18h6`,key:`1m8k6r`}]]),xm=Z(`layout-dashboard`,[[`rect`,{width:`7`,height:`9`,x:`3`,y:`3`,rx:`1`,key:`10lvy0`}],[`rect`,{width:`7`,height:`5`,x:`14`,y:`3`,rx:`1`,key:`16une8`}],[`rect`,{width:`7`,height:`9`,x:`14`,y:`12`,rx:`1`,key:`1hutg5`}],[`rect`,{width:`7`,height:`5`,x:`3`,y:`16`,rx:`1`,key:`ldoo1y`}]]),Sm=Z(`list-plus`,[[`path`,{d:`M16 5H3`,key:`m91uny`}],[`path`,{d:`M11 12H3`,key:`51ecnj`}],[`path`,{d:`M16 19H3`,key:`zzsher`}],[`path`,{d:`M18 9v6`,key:`1twb98`}],[`path`,{d:`M21 12h-6`,key:`bt1uis`}]]),Cm=Z(`loader-circle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),wm=Z(`maximize-2`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`m21 3-7 7`,key:`1l2asr`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M9 21H3v-6`,key:`wtvkvv`}]]),Tm=Z(`menu`,[[`path`,{d:`M4 5h16`,key:`1tepv9`}],[`path`,{d:`M4 12h16`,key:`1lakjw`}],[`path`,{d:`M4 19h16`,key:`1djgab`}]]),Em=Z(`message-circle-question-mark`,[[`path`,{d:`M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719`,key:`1sd12s`}],[`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`,key:`1u773s`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),Dm=Z(`message-square-text`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}],[`path`,{d:`M7 11h10`,key:`1twpyw`}],[`path`,{d:`M7 15h6`,key:`d9of3u`}],[`path`,{d:`M7 7h8`,key:`af5zfr`}]]),Om=Z(`minimize-2`,[[`path`,{d:`m14 10 7-7`,key:`oa77jy`}],[`path`,{d:`M20 10h-6V4`,key:`mjg0md`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M4 14h6v6`,key:`rmj7iw`}]]),km=Z(`moon`,[[`path`,{d:`M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401`,key:`kfwtm`}]]),Am=Z(`palette`,[[`path`,{d:`M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z`,key:`e79jfc`}],[`circle`,{cx:`13.5`,cy:`6.5`,r:`.5`,fill:`currentColor`,key:`1okk4w`}],[`circle`,{cx:`17.5`,cy:`10.5`,r:`.5`,fill:`currentColor`,key:`f64h9f`}],[`circle`,{cx:`6.5`,cy:`12.5`,r:`.5`,fill:`currentColor`,key:`qy21gx`}],[`circle`,{cx:`8.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`fotxhn`}]]),jm=Z(`paperclip`,[[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551`,key:`1miecu`}]]),Mm=Z(`pause`,[[`rect`,{x:`14`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`kaeet6`}],[`rect`,{x:`5`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`1wsw3u`}]]),Nm=Z(`play`,[[`path`,{d:`M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z`,key:`10ikf1`}]]),Pm=Z(`plus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]),Fm=Z(`radio`,[[`path`,{d:`M16.247 7.761a6 6 0 0 1 0 8.478`,key:`1fwjs5`}],[`path`,{d:`M19.075 4.933a10 10 0 0 1 0 14.134`,key:`ehdyv1`}],[`path`,{d:`M4.925 19.067a10 10 0 0 1 0-14.134`,key:`1q22gi`}],[`path`,{d:`M7.753 16.239a6 6 0 0 1 0-8.478`,key:`r2q7qm`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}]]),Im=Z(`refresh-cw`,[[`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,key:`v9h5vc`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}],[`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,key:`3uifl3`}],[`path`,{d:`M8 16H3v5`,key:`1cv678`}]]),Lm=Z(`rotate-ccw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),Rm=Z(`rotate-cw`,[[`path`,{d:`M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8`,key:`1p45f6`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}]]),zm=Z(`search`,[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]),Bm=Z(`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`}]]),Vm=Z(`server-cog`,[[`path`,{d:`m10.852 14.772-.383.923`,key:`11vil6`}],[`path`,{d:`M13.148 14.772a3 3 0 1 0-2.296-5.544l-.383-.923`,key:`1v3clb`}],[`path`,{d:`m13.148 9.228.383-.923`,key:`t2zzyc`}],[`path`,{d:`m13.53 15.696-.382-.924a3 3 0 1 1-2.296-5.544`,key:`1bxfiv`}],[`path`,{d:`m14.772 10.852.923-.383`,key:`k9m8cz`}],[`path`,{d:`m14.772 13.148.923.383`,key:`1xvhww`}],[`path`,{d:`M4.5 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-.5`,key:`tn8das`}],[`path`,{d:`M4.5 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-.5`,key:`1g2pve`}],[`path`,{d:`M6 18h.01`,key:`uhywen`}],[`path`,{d:`M6 6h.01`,key:`1utrut`}],[`path`,{d:`m9.228 10.852-.923-.383`,key:`1wtb30`}],[`path`,{d:`m9.228 13.148-.923.383`,key:`1a830x`}]]),Hm=Z(`server`,[[`rect`,{width:`20`,height:`8`,x:`2`,y:`2`,rx:`2`,ry:`2`,key:`ngkwjq`}],[`rect`,{width:`20`,height:`8`,x:`2`,y:`14`,rx:`2`,ry:`2`,key:`iecqi9`}],[`line`,{x1:`6`,x2:`6.01`,y1:`6`,y2:`6`,key:`16zg32`}],[`line`,{x1:`6`,x2:`6.01`,y1:`18`,y2:`18`,key:`nzw8ys`}]]),Um=Z(`settings-2`,[[`path`,{d:`M14 17H5`,key:`gfn3mx`}],[`path`,{d:`M19 7h-9`,key:`6i9tg`}],[`circle`,{cx:`17`,cy:`17`,r:`3`,key:`18b49y`}],[`circle`,{cx:`7`,cy:`7`,r:`3`,key:`dfmy0x`}]]),Wm=Z(`shield-check`,[[`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`}]]),Gm=Z(`sliders-horizontal`,[[`path`,{d:`M10 5H3`,key:`1qgfaw`}],[`path`,{d:`M12 19H3`,key:`yhmn1j`}],[`path`,{d:`M14 3v4`,key:`1sua03`}],[`path`,{d:`M16 17v4`,key:`1q0r14`}],[`path`,{d:`M21 12h-9`,key:`1o4lsq`}],[`path`,{d:`M21 19h-5`,key:`1rlt1p`}],[`path`,{d:`M21 5h-7`,key:`1oszz2`}],[`path`,{d:`M8 10v4`,key:`tgpxqk`}],[`path`,{d:`M8 12H3`,key:`a7s4jb`}]]),Km=Z(`sparkles`,[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]]),qm=Z(`square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),Jm=Z(`sun`,[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]),Ym=Z(`test-tube-diagonal`,[[`path`,{d:`M21 7 6.82 21.18a2.83 2.83 0 0 1-3.99-.01a2.83 2.83 0 0 1 0-4L17 3`,key:`1ub6xw`}],[`path`,{d:`m16 2 6 6`,key:`1gw87d`}],[`path`,{d:`M12 16H4`,key:`1cjfip`}]]),Xm=Z(`trash-2`,[[`path`,{d:`M10 11v6`,key:`nco0om`}],[`path`,{d:`M14 11v6`,key:`outv1u`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`,key:`miytrc`}],[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`,key:`e791ji`}]]),Zm=Z(`triangle-alert`,[[`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`}]]),Qm=Z(`unlink`,[[`path`,{d:`m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71`,key:`yqzxt4`}],[`path`,{d:`m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71`,key:`4qinb0`}],[`line`,{x1:`8`,x2:`8`,y1:`2`,y2:`5`,key:`1041cp`}],[`line`,{x1:`2`,x2:`5`,y1:`8`,y2:`8`,key:`14m1p5`}],[`line`,{x1:`16`,x2:`16`,y1:`19`,y2:`22`,key:`rzdirn`}],[`line`,{x1:`19`,x2:`22`,y1:`16`,y2:`16`,key:`ox905f`}]]),$m=Z(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]);function eh(e){return/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(e)||e.startsWith(`//`)}function th(e){return[`localhost`,`127.0.0.1`,`::1`,`[::1]`].includes(e)}function nh(e,t,n){let r=e.trim();if(!r)return{error:`status URL is empty`};let i;try{i=new URL(r,t)}catch{return{error:`status URL is invalid`}}let a=!eh(r),o=th(i.hostname);return!a&&!o?{error:`${n} must be relative or loopback`}:{source:{isLoopback:o,isRelative:a,url:r}}}function rh(e,t){return nh(e,t,`statusUrl`)}function ih(e,t){let n=nh(e,t,`Ops statusUrl`);return n.error?{error:`${n.error}; use showcase mode for public links.`}:n}function ah(e,t,n){let r=new URL(e,n);return r.searchParams.set(`goal_activation`,t),r.toString()}function oh(e,t){if(!t||!e.isLoopback)return null;try{let n=new URL(e.url,window.location.href),r=new URL(t,n.origin);return th(r.hostname)?r.toString():null}catch{return null}}function sh(e,t){return{detailUrl:oh(t,e.local_dashboard_api?.periodic_report_detail_url),indexUrl:oh(t,e.local_dashboard_api?.periodic_report_index_url)}}async function ch(e,t){let n=new URL(e);n.searchParams.set(`goal_id`,t),n.searchParams.set(`limit`,`100`),n.searchParams.set(`offset`,`0`);let r=await fetch(n,{cache:`no-store`});if(!r.ok)throw Error(`HTTP ${r.status} while loading published reports`);return bp.parse(await r.json()).periodic_reports}async function lh(e,t){let n=new URL(e);Object.entries(t).forEach(([e,t])=>n.searchParams.set(e,t));let r=await fetch(n,{cache:`no-store`});if(!r.ok)throw Error(`HTTP ${r.status} while loading published report detail`);return Sp.parse(await r.json()).projection}function uh(e,t,n){let r=e.find(e=>e.agentId===t&&e.available)??e.find(e=>e.agentId===n&&e.available)??e.find(e=>e.available);if(!r)throw Error(`Chat requires at least one available route`);return r}function dh(e){return!!(e&&typeof e==`object`&&e.session_invalidated===!0)}var fh=``.replace(/\/+$/,``);function ph(e){return!fh||/^https?:\/\//.test(e)?e:new URL(e,`${fh}/`).toString()}var mh=Y({todo_id:G().nullable(),role:G().nullable(),status:G(),priority:G().nullable(),text:G(),action_kind:G().nullable(),task_class:G().nullable(),claimed_by:G().nullable(),evidence:G().nullable()}),hh=Y({goal_id:G(),title:G(),objective:G(),status:G(),waiting_on:G().nullable(),severity:G().nullable(),gate:G(),next_action:G(),top_todo:mh.nullable(),todos:J(mh),evidence:J(G()),quota:Y({state:G().nullable(),spent_slots:K().nullable(),allowed_slots:K().nullable(),reason:G().nullable()})});Y({ok:q(),schema_version:X(`loopx_chat_status_v0`),selected_goal_id:G().nullable(),goal_count:K(),goals:J(hh)});var gh=Y({ok:X(!0),schema_version:_d([`loopx_chat_capabilities_v0`,`loopx_chat_capabilities_v1`]),agent_backend:G(),sandbox:G(),approval_policy:G(),todo_write:G(),goal_subagent_configuration:G().optional(),goal_id:G().nullable(),streaming:q().optional(),resume:q().optional(),interrupt:q().optional(),typed_actions:q().optional(),action_kinds:J(G()).optional(),adapters:J(Y({agent_id:G(),display_name:G(),adapter_kind:G(),available:q(),streaming:q(),resume:q(),interrupt:q(),location:G().optional(),source:G().optional(),tool_calls:q().optional(),trust_scope:G().optional()})).optional(),lark_cli:Y({available:q(),source:G(),version:G().nullable(),error_code:G().nullable()}).optional()}),_h=Y({kind:X(`todo`),text:G(),priority:_d([`P0`,`P1`,`P2`]),rationale:G()}),vh=Y({operation:_d([`merge`,`release`,`deploy`,`delete`,`payment`]),target:G().min(1).max(160),summary:G().max(300)}),yh=Y({schema_version:X(`loopx_chat_agent_response_v0`),message:G(),proposals:J(_h),protected_action:vh.nullable().optional().default(null),gate:Y({kind:G(),summary:G(),next_action:G()}).nullable()}),bh=Y({closed:X(!0),ok:X(!0),session_id:G().min(1)});Y({dry_run:X(!0),ok:X(!0),preview_id:G().min(1),todo:Y({goal_id:G().min(1),text:G(),todo_id:G().optional()})});var xh=Y({schema_version:X(`loopx_chat_todo_receipt_v0`),receipt_id:G().min(1),preview_id:G().min(1),goal_id:G().min(1),todo_id:G().min(1),status:X(`applied`),outcome:_d([`todo_added`,`todo_already_exists`]),already_exists:q(),preview_revision:G().nullable()});Y({applied:X(!0),ok:X(!0),receipt:xh,todo:Y({text:G(),todo_id:G()})});var Sh=Y({model_config:Y({model:G(),reasoning_effort:G().optional()}).optional(),mode:G(),spawn_allowed:q(),max_children:K().int().nonnegative(),allowed_domains:J(G()).optional().default([])}).passthrough(),Ch=Y({ok:X(!0),dry_run:q(),execute:q(),written:q(),changed:q(),goal_id:G().min(1),changed_fields:J(G()),before:Y({orchestration:Sh}).passthrough(),after:Y({orchestration:Sh}).passthrough(),preview_id:G().min(1),feature_summary:Y({multi_subagent:_d([`off`,`enabled`])}).passthrough(),global_sync:Y({required:q(),executed:q(),readback:Y({status:G(),verified:q()}).passthrough()}).passthrough()}),wh=Y({id:G().min(1),outcome:_d([`approved`,`rejected`,`cancelled`]),projectionVerified:q().nullable(),proposal:_h,receipt:xh.nullable()}).superRefine((e,t)=>{e.outcome===`approved`&&!e.receipt&&t.addIssue({code:`custom`,message:`approved decision history requires a Todo receipt`,path:[`receipt`]}),e.outcome!==`approved`&&e.receipt&&t.addIssue({code:`custom`,message:`zero-write decision history must not include a Todo receipt`,path:[`receipt`]})});Y({schema_version:X(`loopx_chat_decision_history_v0`),goal_id:G().min(1),decisions:J(wh).max(24)});var Th=class extends Error{payload;constructor(e,t){super(e),this.payload=t}},Eh=_d([`goal.create`,`goal.update`,`goal.lifecycle`,`todo.create`,`todo.update`,`agent.bind`,`heartbeat.bind`,`monitor.create`,`monitor.update`,`gate.resolve`,`run.correct`]),Dh=Y({schema_version:X(`loopx_chat_action_proposal_v1`),proposal_id:G().min(1),action_kind:Eh,summary:G().min(1),normalized_parameters:hd(G(),rd()),context:hd(G(),rd()),expected_state_fingerprint:G().min(1),permission_classification:G().min(1),validation_evidence:J(G().refine(e=>e.trim().length>0,`Validation evidence must be non-blank text`)),available_transitions:J(_d([`apply`,`cancel`,`regenerate`,`reject`,`defer`])),status:_d([`preview_ready`,`applying`,`gated`,`failed`,`rejected`,`deferred`,`cancelled`,`stale`,`applied`]),receipt:hd(G(),rd()).nullable(),stale:hd(G(),rd()).nullable(),gate:hd(G(),rd()).nullable().optional(),error:hd(G(),rd()).nullable().optional(),checkpoint:hd(G(),rd()).nullable().optional(),regenerated_from:G().nullable().optional(),created_at:G(),updated_at:G()}),Oh=Y({ok:X(!0),proposal:Dh});async function kh(e){let t=await Fh(`/api/actions/preview`,{method:`POST`,body:JSON.stringify({action_kind:e.actionKind,context:e.context,idempotency_key:e.idempotencyKey,normalized_parameters:e.normalizedParameters,summary:e.summary})});return Oh.parse(t).proposal}var Ah=Y({ok:X(!0),schema_version:X(`loopx_chat_action_list_v1`),proposals:J(Dh)});async function jh(e={}){let t=new URLSearchParams;e.contextKind&&t.set(`context_kind`,e.contextKind),e.goalId&&t.set(`goal_id`,e.goalId);let n=t.size>0?`?${t.toString()}`:``;return Ah.parse(await Fh(`/api/actions${n}`)).proposals}async function Mh(e){let t=await Fh(`/api/actions/${encodeURIComponent(e)}/apply`,{method:`POST`,body:`{}`});return Y({ok:X(!0),proposal:Dh,turn:hd(G(),rd()).nullable().optional()}).parse(t)}async function Nh(e){return Oh.parse(await Fh(`/api/actions/${encodeURIComponent(e)}/cancel`,{method:`POST`,body:`{}`})).proposal}async function Ph(e,t){return Oh.parse(await Fh(`/api/actions/${encodeURIComponent(e)}/${t}`,{method:`POST`,body:`{}`})).proposal}async function Fh(e,t){let n;try{n=await fetch(ph(e),{cache:`no-store`,...t,headers:{"Content-Type":`application/json`,...t?.headers}})}catch{throw new Th(`无法连接 LoopX Chat 服务。请确认 Dashboard 与 Chat 服务已启动且来自同一版本。`,{error_code:`chat_api_unavailable`})}let r=await n.text(),i=null;if(r.trim())try{i=JSON.parse(r)}catch{i=null}let a=i&&typeof i==`object`&&!Array.isArray(i)?i:{};if(!n.ok){let e=(a.proposal&&typeof a.proposal==`object`?a.proposal:null)?.status===`stale`?`来源状态已变化,请重新生成预览。`:null,t=n.status>=500?`LoopX Chat 服务暂时不可用(HTTP ${n.status})。请确认 Dashboard 与 Chat 服务已启动且来自同一版本。`:`LoopX Chat 请求失败(HTTP ${n.status})。`;throw new Th(e??String(a.error||t),Object.keys(a).length?a:{error_code:`chat_api_unavailable`,http_status:n.status})}if(i===null)throw new Th(`LoopX Chat 服务返回了无法识别的响应(HTTP ${n.status})。请确认 Dashboard 与 Chat 服务来自同一版本。`,{error_code:`invalid_chat_api_response`,http_status:n.status});return i}async function Ih(){return gh.parse(await Fh(`/api/chat/capabilities`))}async function Lh(e){return Fh(`/api/chat/projection-messages`,{method:`POST`,body:JSON.stringify({answer:e.answer,context_kind:e.contextKind,goal_id:e.goalId,question:e.question})})}async function Rh(e,t=`codex`,n=`resume_latest`,r=`goal`){return Fh(`/api/chat/sessions`,{method:`POST`,body:JSON.stringify({goal_id:e,agent_id:t,mode:n,context_kind:r})})}async function zh(e){return Fh(`/api/chat/sessions/${e}`)}async function Bh(e){let t=new URLSearchParams;return e.agentId&&t.set(`agent_id`,e.agentId),e.channelId&&t.set(`channel_id`,e.channelId),e.goalId&&t.set(`goal_id`,e.goalId),Fh(`/api/chat/sessions?${t.toString()}`)}function Vh(e){let t=new Map;for(let n of e)for(let e of n.messages)t.set(e.message_id,e);return[...t.values()].sort((e,t)=>e.created_at.localeCompare(t.created_at)||e.message_id.localeCompare(t.message_id))}async function Hh(e){let t=await Bh(e),n=await Promise.all(t.sessions.map(e=>zh(e.session_id)));return{messages:Vh(n),sessions:t.sessions,snapshots:n}}async function Uh(e,t,n,r=[]){return Fh(`/api/chat/sessions/${e}/turns`,{method:`POST`,body:JSON.stringify({message:t,client_turn_id:n,...r.length?{attachments:r.map(e=>({data_url:e.dataUrl,id:e.id,mime_type:e.mimeType,name:e.name,size:e.size}))}:{}})})}function Wh(e){let t=e.split(` -`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(` -`);if(!t)return null;try{let e=JSON.parse(t);return!e.kind||!e.payload||typeof e.payload!=`object`?null:{event_id:String(e.event_id??``),sequence:Number(e.sequence??0),kind:String(e.kind),created_at:String(e.created_at??``),payload:e.payload}}catch{return null}}async function Gh(e,t,n){let r=``,i=0,a=!1;for(;!a&&i<4;){let o=typeof window>`u`?`http://127.0.0.1`:window.location.origin,s=new URL(ph(e),o);r&&s.searchParams.set(`after`,r);try{let e=await fetch(s,{cache:`no-store`,headers:{Accept:`text/event-stream`},signal:n});if(!e.ok||!e.body)throw new Th(`SSE HTTP ${e.status}`,{status:e.status});let o=e.body.getReader(),c=new TextDecoder,l=``;for(;;){let{done:e,value:n}=await o.read();l+=c.decode(n,{stream:!e}).replaceAll(`\r -`,` -`);let i=l.indexOf(` - -`);for(;i>=0;){let e=l.slice(0,i);l=l.slice(i+2);let n=Wh(e);n&&(n.event_id&&(r=n.event_id),t(n),a=[`turn.completed`,`turn.interrupted`,`turn.failed`].includes(n.kind)),i=l.indexOf(` - -`)}if(e||a)break}i=a?i:i+1}catch(e){if(n?.aborted||(i+=1,i>=4))throw e;await new Promise(e=>globalThis.setTimeout(e,250*2**(i-1)))}}if(!a)throw new Th(`Agent 事件流连接已断开。`,{reconnect_attempts:i})}async function Kh(e,t){return Fh(`/api/chat/sessions/${e}/turns/${t}/interrupt`,{method:`POST`,body:`{}`})}async function qh(e,t,n={}){let r=await Uh(e,t,n.clientTurnId??crypto.randomUUID(),n.attachments);return n.onPhase?.(`turn.accepted`,r.turn_id),Jh(e,r.turn_id,r.events_url,n)}async function Jh(e,t,n,r={}){let i=null,a={failure:null,interrupted:null};try{await Gh(n,e=>{r.onPhase?.(e.kind,t),(e.kind===`answer.delta`||e.kind===`assistant.delta`)&&r.onDelta?.(String(e.payload.text??``)),e.kind===`agent.phase`&&r.onActivity?.(String(e.payload.label??`Agent 正在处理`)),e.kind===`turn.completed`&&(i=e.payload.response),e.kind===`turn.failed`&&(a.failure=e.payload),e.kind===`turn.interrupted`&&(a.interrupted=e.payload)},r.signal)}catch(i){throw i instanceof Th&&!r.signal?.aborted?new Th(i.message,{...i.payload,events_url:n,reconnectable:!0,session_id:e,turn_id:t}):i}if(a.failure)throw new Th(String(a.failure.message||`Agent 回合失败。`),a.failure);if(a.interrupted)throw new Th(`Agent 回合已中断。`,{...a.interrupted,error_code:`turn_interrupted`,session_id:e,turn_id:t});return{response:yh.parse(i),sessionId:e,turnId:t}}async function Yh(e,t,n={}){return Jh(e,t,`/api/chat/sessions/${e}/turns/${t}/events`,n)}async function Xh(e){let t=bh.parse(await Fh(`/api/chat/sessions/${e}`,{keepalive:!0,method:`DELETE`}));if(t.session_id!==e)throw new Th(`Agent 会话关闭回执与本次请求不一致。`,{session_id:t.session_id});return t}async function Zh(e){return Fh(`/api/chat/sessions/${e}/resume`,{method:`POST`,body:`{}`})}function Qh(e){return{goal_id:e.goalId,enabled:e.enabled,...e.modelConfig===void 0?{}:{model_config:e.modelConfig},...e.enabled?{max_children:e.maxChildren,allowed_domains:e.allowedDomains}:{}}}function $h(e,t){let n=e.after.orchestration,r=[...new Set(t.allowedDomains)],i=e.feature_summary.multi_subagent===`enabled`;if(!(e.goal_id===t.goalId&&i===t.enabled&&(t.modelConfig===void 0||JSON.stringify(n.model_config??null)===JSON.stringify(t.modelConfig))&&(t.enabled?n.max_children===t.maxChildren&&JSON.stringify(n.allowed_domains)===JSON.stringify(r):n.spawn_allowed===!1&&n.max_children===0)))throw new Th(`Goal 子代理配置回执与本次请求不一致,界面已停止更新。`,{after:e.after,goal_id:e.goal_id});return e}async function eg(e){let t=Ch.parse(await Fh(`/api/chat/goal-subagents/dry-run`,{method:`POST`,body:JSON.stringify(Qh(e))}));if(!t.dry_run||t.execute||t.written)throw new Th(`Goal 子代理预览返回了非预览回执,已停止进入确认状态。`,{result:t});return $h(t,e)}async function tg(e,t){let n=Ch.parse(await Fh(`/api/chat/goal-subagents/apply`,{method:`POST`,body:JSON.stringify({...Qh(e),preview_id:t})}));if(n.preview_id!==t||n.dry_run||!n.execute)throw new Th(`Goal 子代理写入回执与本次确认不一致,界面已停止更新。`,{result:n});if(n.changed&&(!n.written||!n.global_sync.executed||!n.global_sync.readback.verified))throw new Th(`Goal 子代理设置未通过共享状态读回验证。`,{result:n});return $h(n,e)}var ng=Y({ok:X(!0),targets:J(Y({enabled:q(),provider:G(),target_name:G()}))});async function rg(){return ng.parse(await Fh(`/api/chat/goal-channel/targets`)).targets}var ig=Y({ok:q(),blocker:G().optional(),public_summary:G().optional(),status:G().optional()});async function ag(e){return ig.parse(await Fh(`/api/chat/goal-channel/setup`,{method:`POST`,body:JSON.stringify({execute:e.execute,goal_id:e.goalId,target:e.target})}))}async function og(e){return ig.parse(await Fh(`/api/chat/goal-channel/configure`,{method:`POST`,body:JSON.stringify({auto_notify_human_gates:e.autoNotify,goal_id:e.goalId})}))}var sg=Y({schema_version:X(`periodic_report_schedule_v0`),schedule_id:G(),rrule:G(),timezone:G()});Y({schema_version:X(`periodic_report_machine_defaults_v0`),enabled:q(),inheritance:X(`live_machine_default`),profile_preset:G().optional(),route_ref:G().optional(),timezone:G(),schedule:sg.nullable().optional()});var cg=Y({schema_version:X(`loopx_machine_configuration_v0`),namespaces:hd(G(),hd(G(),rd()))}),lg=Y({namespace:G(),title:G(),description:G(),schema_versions:J(G()).min(1),configuration_template:hd(G(),rd()),template_status:_d([`ready`,`schema_only`])}),ug=Y({schema_version:X(`machine_configuration_catalog_v0`),namespaces:J(lg)}),dg=Y({key:G(),label:G(),description:G(),input_kind:_d([`boolean`,`number`,`select`,`string_list`,`text`,`periodic_report_schedule`]),nullable:q().optional(),required:q(),minimum:K().int().optional(),maximum:K().int().optional(),options:J(G()).optional()}),fg=Y({schema_version:X(`capability_configuration_editor_v0`),editable:q(),supported_scopes:J(_d([`goal`,`machine`])),writable_scopes:J(_d([`goal`,`machine`])),fields:J(dg),read_only_reason:G().optional()}),pg=Y({schema_version:X(`capability_configuration_catalog_v0`),capabilities:J(Y({capability_id:G(),display_name:G(),description:G(),available_scopes:J(_d([`goal`,`machine`])),machine_namespace:G().optional(),goal_feature_id:G().optional(),effective_value_policy:X(`goal_override_over_live_machine_default`).optional(),availability:G().optional(),default:hd(G(),rd()).optional(),current:hd(G(),rd()).optional(),machine_current:hd(G(),rd()).optional(),effective_configuration:Y({schema_version:X(`capability_configuration_resolution_v0`),capability_id:G(),source:_d([`goal_override`,`machine_default`,`capability_default`,`not_configured`]),configuration:hd(G(),rd()).nullable(),inherited:q(),goal_override_present:q(),machine_default_present:q(),effective_revision:G()}).optional(),documentation:hd(G(),rd()).optional(),context_contribution:Y({supported_phases:J(_d([`before_plan`,`before_delegate`,`after_delegate_result`])),target:X(`coordinator`),activation:X(`with_capability`),receipt_required:X(!0)}).optional(),configuration_editor:fg}))}),mg=Y({ok:X(!0),schema_version:X(`goal_configuration_inspection_v0`),status:X(`configured`),goal_id:G(),revision:G(),available_capabilities:J(G()),capability_catalog:pg}),hg=Y({ok:X(!0),goal_id:G(),capability_id:G(),changed_fields:J(G()),goal_configuration:hd(G(),rd()).nullable(),capability_catalog:pg}),gg=hg.extend({schema_version:X(`goal_configuration_update_plan_v0`),status:X(`preview`),action:_d([`create`,`update`,`delete`,`unchanged`]),current_revision:G(),desired_revision:G(),base_revision:G(),plan_revision:G(),writes_required:K().int().nonnegative()}),_g=ld([hg.extend({schema_version:X(`goal_configuration_transaction_v0`),status:_d([`applied`,`unchanged`]),plan_revision:G(),applied_revision:G(),readback_verified:X(!0)}),Y({ok:X(!1),schema_version:X(`goal_configuration_transaction_v0`),status:X(`partial_write`),goal_id:G(),capability_id:G(),plan_revision:G(),applied_revision:G().nullable(),source_written:X(!0),shared_sync_pending:X(!0),readback_verified:q(),changed_fields:J(G()),goal_configuration:hd(G(),rd()).nullable(),capability_catalog:pg,error:G(),recommended_action:G()})]),vg=Y({ok:X(!0),available_namespaces:J(G()),namespace_catalog:ug.optional().default({schema_version:`machine_configuration_catalog_v0`,namespaces:[]}),capability_catalog:pg,changed_namespaces:J(G()).optional().default([]),machine_configuration:cg.nullable().optional()}),yg=vg.extend({schema_version:X(`machine_configuration_inspection_v0`),status:_d([`configured`,`absent`]),revision:G()}),bg=vg.extend({schema_version:X(`machine_configuration_update_plan_v0`),status:X(`preview`),action:_d([`create`,`update`,`delete`,`unchanged`]),current_revision:G(),desired_revision:G(),plan_revision:G(),writes_required:K().int().nonnegative(),machine_configuration:cg.nullable()}),xg=vg.extend({schema_version:X(`machine_configuration_transaction_v0`),status:_d([`applied`,`unchanged`]),plan_revision:G(),transaction_id:G().nullable(),readback_verified:X(!0),rollback_available:q(),applied_revision:G().optional(),prior_revision:G().optional()}),Sg=vg.extend({schema_version:X(`machine_configuration_rollback_plan_v0`),status:X(`preview`),action:_d([`delete`,`restore`,`unchanged`,`blocked`]),reason:G(),transaction_id:G(),plan_revision:G(),rollback_allowed:q(),writes_required:K().int().nonnegative()}),Cg=vg.extend({schema_version:X(`machine_configuration_rollback_receipt_v0`),status:_d([`rolled_back`,`unchanged`]),transaction_id:G(),plan_revision:G(),rollback_id:G().nullable(),readback_verified:X(!0)});async function wg(){return yg.parse(await Fh(`/api/chat/machine-configuration`))}async function Tg(e){let t=new URLSearchParams({goal_id:e});return mg.parse(await Fh(`/api/chat/goal-configuration?${t.toString()}`))}async function Eg(e,t,n){return gg.parse(await Fh(`/api/chat/goal-configuration/preview`,{method:`POST`,body:JSON.stringify({goal_id:e,capability_id:t,configuration:n})}))}async function Dg(e,t,n,r){return _g.parse(await Fh(`/api/chat/goal-configuration/apply`,{method:`POST`,body:JSON.stringify({goal_id:e,capability_id:t,configuration:n,expected_plan_revision:r})}))}async function Og(e,t){return bg.parse(await Fh(`/api/chat/machine-configuration/preview`,{method:`POST`,body:JSON.stringify({namespace:e,namespace_configuration:t})}))}async function kg(e,t,n){return xg.parse(await Fh(`/api/chat/machine-configuration/apply`,{method:`POST`,body:JSON.stringify({expected_plan_revision:n,namespace:e,namespace_configuration:t})}))}async function Ag(e){return bg.parse(await Fh(`/api/chat/machine-configuration/preview`,{method:`POST`,body:JSON.stringify({namespace:e,operation:`remove`})}))}async function jg(e,t){return xg.parse(await Fh(`/api/chat/machine-configuration/apply`,{method:`POST`,body:JSON.stringify({expected_plan_revision:t,namespace:e,operation:`remove`})}))}async function Mg(e){return Sg.parse(await Fh(`/api/chat/machine-configuration/rollback`,{method:`POST`,body:JSON.stringify({execute:!1,transaction_id:e})}))}async function Ng(e,t){return Cg.parse(await Fh(`/api/chat/machine-configuration/rollback`,{method:`POST`,body:JSON.stringify({execute:!0,expected_plan_revision:t,transaction_id:e})}))}var Pg=Y({ok:X(!0),goals:J(Y({goal_id:G(),repository:Y({branch:G(),identity:G(),label:G(),read_only:X(!0)})}))});async function Fg(){return Pg.parse(await Fh(`/api/chat/goals/contexts`)).goals}var Ig=Y({ok:X(!0),apps:J(Y({active:q(),app_ref:G(),brand:G(),health_error_code:G().nullable().default(null),label:G(),ready:q(),reply_ready:q().default(!1)}))});async function Lg(){return Ig.parse(await Fh(`/api/chat/lark/apps`)).apps}var Rg=Y({ok:X(!0),app_ref:G(),error:G().nullable(),setup_id:G(),status:_d([`starting`,`waiting_for_feishu`,`ready`,`failed`,`cancelled`]),verification_url:G().url().nullable()});async function zg(e){return Rg.parse(await Fh(`/api/chat/lark/app-setups`,{method:`POST`,body:JSON.stringify({app_ref:e.appRef,brand:e.brand})}))}async function Bg(e){return Rg.parse(await Fh(`/api/chat/lark/app-setups/${encodeURIComponent(e)}`))}async function Vg(e){return Rg.parse(await Fh(`/api/chat/lark/app-setups/${encodeURIComponent(e)}`,{method:`DELETE`}))}var Hg=[`invalid_event`,`binding_unavailable`,`chat_mismatch`,`topic_mismatch`,`route_ambiguous`,`self_message`,`invalid_routing_state`,`not_addressed`],Ug=Y({ok:X(!0),chats:J(Y({chat_id:G(),chat_name:G()}))});async function Wg(e,t){let n=new URLSearchParams({app_ref:e});return t&&n.set(`query`,t),Ug.parse(await Fh(`/api/chat/lark/chats?${n.toString()}`)).chats}var Gg=Y({ok:X(!0),connections:J(Y({conversation_kind:_d([`goal`,`manager`]).default(`goal`),agent_id:G().nullable().default(null),connection_id:G(),app_label:G(),app_ref:G(),capture_scope:_d([`addressed_only`,`configured_chat_all`]).default(`addressed_only`),chat_name:G(),enabled:q(),goal_id:G(),goal_title:G(),health_error_code:G().nullable().default(null),history_permission_guidance:Y({action:X(`enable_application_scopes_and_publish`),api_document_url:G().url(),capability:X(`group_history_pagination`),identity:X(`bot`),required_scopes:pd([X(`im:message.group_msg`),X(`im:message.group_msg.include_bot:read`)]),schema_version:X(`lark_bot_group_history_permission_guidance_v0`)}).nullable().default(null),incoming_mode:_d([`mentions`,`all`]),ingress_mode:_d([`live_steering`,`session_queue`,`async_inbox`,`direct_session`]).default(`async_inbox`),event_count:K().int().nonnegative().default(0),last_event_reason:_d(Hg).nullable().default(null).catch(null),last_event_status:G().nullable().default(null),listener_error_code:G().nullable().default(null),listener_status:_d([`starting`,`listening`,`retrying`,`stopped`]).nullable().default(null),replied_count:K().int().nonnegative().default(0),reply_ready:q().default(!1),reply_mode:X(`topic_reply`),session_bound:q().default(!1),target_ref:G(),topic_name:G(),topic_setup_required:q()}))});async function Kg(){return Gg.parse(await Fh(`/api/chat/lark/connections`)).connections}async function qg(e){return ig.parse(await Fh(`/api/chat/lark/connections`,{method:`POST`,body:JSON.stringify({...e.agentBindings?{agent_bindings:e.agentBindings.map(e=>({agent_id:e.agentId,app_ref:e.appRef}))}:{},...e.agentId?{agent_id:e.agentId}:{},...e.appRef?{app_ref:e.appRef}:{},...e.connectionId?{connection_id:e.connectionId}:{},conversation_kind:e.conversationKind??`goal`,capture_scope:e.captureScope,chat_id:e.chatId,chat_name:e.chatName,execute:e.execute,goal_id:e.goalId,incoming_mode:e.incomingMode,ingress_mode:e.ingressMode,reply_mode:e.replyMode})}))}async function Jg(e,t){let n=new URLSearchParams({goal_id:e,connection_id:t});return ig.parse(await Fh(`/api/chat/lark/connections?${n.toString()}`,{method:`DELETE`}))}function Yg(e){return{loadedUrl:null,projectionRevision:0,requestedUrl:e,selectionRevision:0,requestGeneration:0}}function Xg(e,t){return e.selectionRevision+=1,e.requestedUrl=t,e.selectionRevision}function Zg(e,t,n){if(n.background)return e.requestedUrl!==null||e.loadedUrl!==t?null:(e.requestGeneration+=1,{background:!0,projectionRevision:e.projectionRevision,selectionRevision:e.selectionRevision,url:t,generation:e.requestGeneration});let r=n.selectionRevision??e.selectionRevision+1;return n.selectionRevision!==void 0&&e.selectionRevision!==r?null:(e.selectionRevision=r,e.projectionRevision+=1,e.requestedUrl=t,e.requestGeneration+=1,{background:!1,projectionRevision:e.projectionRevision,selectionRevision:r,url:t,generation:e.requestGeneration})}function Qg(e,t){return t.generation===e.requestGeneration&&e.projectionRevision===t.projectionRevision&&e.selectionRevision===t.selectionRevision}function $g(e,t){return Qg(e,t)&&(!t.background||e.requestedUrl===null&&e.loadedUrl===t.url)}function e_(e,t,n){return t.get(e)===n}function t_(e,t,n,r){return e.filter(e=>e_(r(e),n,t))}function n_(e,t,n){let r=new Set,i=[];for(let a of[...e,...t]){let e=n(a);e==null||r.has(e)||(r.add(e),i.push(a))}return i}var r_=[`runs_24h`,`runs_7d`,`quota_spend_slots_24h`,`quota_spend_slots_7d`,`automation_run_count_24h`,`automation_run_count_7d`,`progress_signal_run_count_24h`,`progress_signal_run_count_7d`],i_=[`input_tokens_24h`,`input_tokens_7d`,`output_tokens_24h`,`output_tokens_7d`,`cache_tokens_24h`,`cache_tokens_7d`,`cost_usd_24h`,`cost_usd_7d`,`duration_ms_24h`,`duration_ms_7d`],a_=[`accounting`,`decision`,`evidence`,`state`,`work`],o_={accounting:0,decision:0,evidence:0,state:0,work:0},s_={runs_24h:0,runs_7d:0,quota_spend_slots_24h:0,quota_spend_slots_7d:0,automation_run_count_24h:0,automation_run_count_7d:0,progress_signal_run_count_24h:0,progress_signal_run_count_7d:0};function c_(e,t){let n={...e};for(let r of r_)n[r]=(Number(e[r])||0)+(Number(t[r])||0);for(let r of i_)(e[r]!==void 0||t[r]!==void 0)&&(n[r]=(e[r]??0)+(t[r]??0));return n}function l_(e,t){return!e.length||t<=0?e:e.map(e=>({...e,project_share_24h:Math.round((Number(e.runs_24h)||0)/t*1e3)/1e3}))}function u_(e,t){let n={...e};for(let r of a_)n[r]=(e[r]??0)+(t[r]??0);return n}function d_(e){let t={events_24h:0,events_7d:0,by_class_24h:{...o_},by_class_7d:{...o_}};for(let n of e)t.events_24h+=n.events_24h,t.events_7d+=n.events_7d,t.by_class_24h=u_(t.by_class_24h,n.by_class_24h),t.by_class_7d=u_(t.by_class_7d,n.by_class_7d);return t}function f_(e,t,n){if(!e&&!t)return null;let r=t_(e?.goals??[],`active`,n,e=>e.goal_id),i=t_(t?.goals??[],`stopped`,n,e=>e.goal_id),a=n_(r,i,e=>e.goal_id),o=d_(r),s=d_(i),c={events_24h:o.events_24h+s.events_24h,events_7d:o.events_7d+s.events_7d,by_class_24h:u_(o.by_class_24h,s.by_class_24h),by_class_7d:u_(o.by_class_7d,s.by_class_7d)};return{...e??t,goals:a,sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),totals:c}}function p_(e,t,n){if(!e&&!t)return null;let r=n_([...t_(e?.items??[],`active`,n,e=>e.goal_id),...t_(t?.items??[],`stopped`,n,e=>e.goal_id)],[],e=>`${e.goal_id}:${e.decision_kind??``}:${e.decision_at??``}`),i={decision_count:(e?.summary.decision_count??0)+(t?.summary.decision_count??0),stale_count:r.filter(e=>e.stale_by_age).length,rebase_required_count:(e?.summary.rebase_required_count??0)+(t?.summary.rebase_required_count??0),fresh_count:(e?.summary.fresh_count??0)+(t?.summary.fresh_count??0)};return{...e??t,items:r,sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),summary:i}}function m_(e,t){return n_([...e,...t].sort((e,t)=>t.generated_at.localeCompare(e.generated_at)),[],e=>`${e.goal_id}:${e.generated_at}:${e.classification??``}`)}function h_(e,t,n){let r=n_(t_(e.items,`active`,n,e=>e.goal_id),t_(t.items,`stopped`,n,e=>e.goal_id),e=>e.goal_id);return{...e,item_count:r.length,items:r,needs_controller:r.filter(e=>e.waiting_on===`controller`).length,needs_codex:r.filter(e=>e.waiting_on===`codex`).length,needs_user_or_controller:r.filter(e=>[`user_or_controller`,`controller`].includes(e.waiting_on)).length,watching_external_evidence:r.filter(e=>e.waiting_on===`external_evidence`).length}}function g_(e){let t=e.todo_id?.trim()||``;return t?`${e.goal_id}:${t}`:`${e.goal_id}:synthetic:${e.role??``}:${e.index??``}:${e.text??``}`}function __(e){let t={...s_};for(let n of e){for(let e of r_)t[e]+=Number(n[e])||0;for(let e of i_)n[e]!==void 0&&(t[e]=(t[e]??0)+n[e])}return t}function v_(e,t,n){if(!e&&!t)return null;let r=t_(e?.items??[],`active`,n,e=>e.goal_id),i=t_(t?.items??[],`stopped`,n,e=>e.goal_id),a=n_(r,i,g_);return{...e??t,current_projected_count:r.length+i.length,items:a,rollout_event_count:a.reduce((e,t)=>e+(t.event_count??0),0),total_count:a.length}}function y_(e,t,n){if(!e&&!t)return null;let r=t_(e?.goals??[],`active`,n,e=>e.goal_id),i=t_(t?.goals??[],`stopped`,n,e=>e.goal_id),a=n_(r,i,e=>e.goal_id),o=c_(__(r),__(i));return{...e??t,goals:l_(a,Number(o.runs_24h)||0),sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),totals:o}}function b_(e,t,n){if(!e&&!t)return null;let r=(e?.agents??[]).filter(e=>e.goal_ids.some(e=>e_(e,n,`active`))||(e.current_todo?.goal_id?e_(e.current_todo.goal_id,n,`active`):!1)),i=(t?.agents??[]).filter(e=>e.goal_ids.some(e=>e_(e,n,`stopped`))||(e.current_todo?.goal_id?e_(e.current_todo.goal_id,n,`stopped`):!1)),a=n_(r,i,e=>e.agent_id).map(e=>{let t=i.find(t=>t.agent_id===e.agent_id);return t?{...e,goal_ids:Array.from(new Set([...e.goal_ids??[],...t.goal_ids]))}:e});return{...e??t,agents:a,source_summary:(e??t)?.source_summary?{...(e??t).source_summary,projected_agent_count:a.length,registered_agent_count:new Set(a.map(e=>e.agent_id)).size}:(e??t)?.source_summary}}function x_(e,t,n){if(!e&&!t)return null;let r=n_(t_(e?.goals??[],`active`,n,e=>e.goal_id),t_(t?.goals??[],`stopped`,n,e=>e.goal_id),e=>e.goal_id);return{...e??t,goals:r}}function S_(e,t){let n=t.goal_projection?.scope;if(n!==`active`&&n!==`stopped`)return t;let r=n,i=t.run_history.goals,a=e.run_history.goals,o=n_(r===`active`?i:a.filter(e=>e.activation_state!==`stopped`),r===`stopped`?i:a.filter(e=>e.activation_state===`stopped`),e=>e.id),s=new Map(o.map(e=>[e.id,e.activation_state])),c=r===`active`?t:e,l=r===`stopped`?t:e,u=e.goal_projection?.registry_revision??null,d=t.goal_projection?.registry_revision??null,f=u===null||d===null||u===d;return{...e,agent_management_projection:b_(c.agent_management_projection,l.agent_management_projection,s),attention_queue:h_(c.attention_queue,l.attention_queue,s),decision_freshness_summary:p_(c.decision_freshness_summary,l.decision_freshness_summary,s),event_ledger_summary:f_(c.event_ledger_summary,l.event_ledger_summary,s),goal_channel_notification_projection:x_(c.goal_channel_notification_projection,l.goal_channel_notification_projection,s),goal_projection:{schema_version:`loopx_goal_projection_scope_v0`,...t.goal_projection,complete:f,projected_goal_count:o.length,registry_goal_count:t.goal_projection?.registry_goal_count??0,scope:`all`},run_history:{...e.run_history,goal_count:o.length,goals:o,recent_runs:m_(c.run_history.recent_runs,l.run_history.recent_runs),run_count:c.run_history.run_count+l.run_history.run_count},todo_index:v_(c.todo_index,l.todo_index,s),usage_summary:y_(c.usage_summary,l.usage_summary,s)}}function C_(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`){if(Array.isArray(e)){var i=e.length;for(t=0;ttypeof e==`boolean`?`${e}`:e===0?`0`:e,E_=w_,D_=(e,t)=>n=>{if(t?.variants==null)return E_(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=T_(t)||T_(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return E_(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)},O_=(e,t)=>{let n=Array(e.length+t.length);for(let t=0;t({classGroupId:e,validator:t}),A_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),j_=`-`,M_=[],N_=`arbitrary..`,P_=e=>{let t=L_(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return I_(e);let n=e.split(j_);return F_(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?O_(i,t):t:i||M_}return n[e]||M_}}},F_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=F_(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(j_):e.slice(t).join(j_),s=a.length;for(let e=0;ee.slice(1,-1).indexOf(`:`)===-1?void 0:(()=>{let t=e.slice(1,-1),n=t.indexOf(`:`),r=t.slice(0,n);return r?N_+r:void 0})(),L_=e=>{let{theme:t,classGroups:n}=e;return R_(n,t)},R_=(e,t)=>{let n=A_();for(let r in e){let i=e[r];z_(i,n,r,t)}return n},z_=(e,t,n,r)=>{let i=e.length;for(let a=0;a{if(typeof e==`string`){V_(e,t,n);return}if(typeof e==`function`){H_(e,t,n,r);return}U_(e,t,n,r)},V_=(e,t,n)=>{let r=e===``?t:W_(t,e);r.classGroupId=n},H_=(e,t,n,r)=>{if(G_(e)){z_(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(k_(n,e))},U_=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e{let n=e,r=t.split(j_),i=r.length;for(let e=0;e`isThemeGetter`in e&&e.isThemeGetter===!0,K_=e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null),i=(i,a)=>{n[i]=a,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];if(t!==void 0)return t;if((t=r[e])!==void 0)return i(e,t),t},set(e,t){e in n?n[e]=t:i(e,t)}}},q_=`!`,J_=`:`,Y_=[],X_=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),Z_=e=>{let{prefix:t,experimentalParseClassName:n}=e,r=e=>{let t=[],n=0,r=0,i=0,a,o=e.length;for(let s=0;si?a-i:void 0;return X_(t,l,c,u)};if(t){let e=t+J_,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):X_(Y_,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},Q_=e=>{let t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{let n=[],r=[];for(let i=0;i0&&(r.sort(),n.push(...r),r=[]),n.push(a)):r.push(a)}return r.length>0&&(r.sort(),n.push(...r)),n}},$_=e=>({cache:K_(e.cacheSize),parseClassName:Z_(e),sortModifiers:Q_(e),postfixLookupClassGroupIds:ev(e),...P_(e)}),ev=e=>{let t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let e=0;e{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a,postfixLookupClassGroupIds:o}=t,s=[],c=e.trim().split(tv),l=``;for(let e=c.length-1;e>=0;--e){let t=c[e],{isExternal:u,modifiers:d,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:m}=n(t);if(u){l=t+(l.length>0?` `+l:l);continue}let h=!!m,g;if(h){g=r(p.substring(0,m));let e=g&&o[g]?r(p):void 0;e&&e!==g&&(g=e,h=!1)}else g=r(p);if(!g){if(!h){l=t+(l.length>0?` `+l:l);continue}if(g=r(p),!g){l=t+(l.length>0?` `+l:l);continue}h=!1}let _=d.length===0?``:d.length===1?d[0]:a(d).join(`:`),v=f?_+q_:_,y=v+g;if(s.indexOf(y)>-1)continue;s.push(y);let b=i(g,h);for(let e=0;e0?` `+l:l)}return l},rv=(...e)=>{let t=0,n,r,i=``;for(;t{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r{let n,r,i,a,o=o=>(n=$_(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,a=s,s(o)),s=e=>{let t=r(e);if(t)return t;let a=nv(e,n);return i(e,a),a};return a=o,(...e)=>a(rv(...e))},ov=[],sv=e=>{let t=t=>t[e]||ov;return t.isThemeGetter=!0,t},cv=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,lv=/^\((?:(\w[\w-]*):)?(.+)\)$/i,uv=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,dv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,fv=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,pv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,mv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,hv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,gv=e=>uv.test(e),_v=e=>!!e&&!Number.isNaN(Number(e)),vv=e=>!!e&&Number.isInteger(Number(e)),yv=e=>e.endsWith(`%`)&&_v(e.slice(0,-1)),bv=e=>dv.test(e),xv=()=>!0,Sv=e=>fv.test(e)&&!pv.test(e),Cv=()=>!1,wv=e=>mv.test(e),Tv=e=>hv.test(e),Ev=e=>!Q(e)&&!$(e),Dv=e=>e.startsWith(`@container`)&&(e[10]===`/`&&e[11]!==void 0||e[11]===`s`&&e[16]!==void 0&&e.startsWith(`-size/`,10)||e[11]===`n`&&e[18]!==void 0&&e.startsWith(`-normal/`,10)),Ov=e=>Uv(e,qv,Cv),Q=e=>cv.test(e),kv=e=>Uv(e,Jv,Sv),Av=e=>Uv(e,Yv,_v),jv=e=>Uv(e,Zv,xv),Mv=e=>Uv(e,Xv,Cv),Nv=e=>Uv(e,Gv,Cv),Pv=e=>Uv(e,Kv,Tv),Fv=e=>Uv(e,Qv,wv),$=e=>lv.test(e),Iv=e=>Wv(e,Jv),Lv=e=>Wv(e,Xv),Rv=e=>Wv(e,Gv),zv=e=>Wv(e,qv),Bv=e=>Wv(e,Kv),Vv=e=>Wv(e,Qv,!0),Hv=e=>Wv(e,Zv,!0),Uv=(e,t,n)=>{let r=cv.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Wv=(e,t,n=!1)=>{let r=lv.exec(e);return r?r[1]?t(r[1]):n:!1},Gv=e=>e===`position`||e===`percentage`,Kv=e=>e===`image`||e===`url`,qv=e=>e===`length`||e===`size`||e===`bg-size`,Jv=e=>e===`length`,Yv=e=>e===`number`,Xv=e=>e===`family-name`,Zv=e=>e===`number`||e===`weight`,Qv=e=>e===`shadow`,$v=av(()=>{let e=sv(`color`),t=sv(`font`),n=sv(`text`),r=sv(`font-weight`),i=sv(`tracking`),a=sv(`leading`),o=sv(`breakpoint`),s=sv(`container`),c=sv(`spacing`),l=sv(`radius`),u=sv(`shadow`),d=sv(`inset-shadow`),f=sv(`text-shadow`),p=sv(`drop-shadow`),m=sv(`blur`),h=sv(`perspective`),g=sv(`aspect`),_=sv(`ease`),v=sv(`animate`),y=()=>[`auto`,`avoid`,`all`,`avoid-page`,`page`,`left`,`right`,`column`],b=()=>[`center`,`top`,`bottom`,`left`,`right`,`top-left`,`left-top`,`top-right`,`right-top`,`bottom-right`,`right-bottom`,`bottom-left`,`left-bottom`],x=()=>[...b(),$,Q],S=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],C=()=>[`auto`,`contain`,`none`],w=()=>[$,Q,c],T=()=>[gv,`full`,`auto`,...w()],E=()=>[vv,`none`,`subgrid`,$,Q],D=()=>[`auto`,{span:[`full`,vv,$,Q]},vv,$,Q],O=()=>[vv,`auto`,$,Q],ee=()=>[`auto`,`min`,`max`,`fr`,$,Q],te=()=>[`start`,`end`,`center`,`between`,`around`,`evenly`,`stretch`,`baseline`,`center-safe`,`end-safe`],ne=()=>[`start`,`end`,`center`,`stretch`,`center-safe`,`end-safe`],k=()=>[`auto`,...w()],A=()=>[gv,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...w()],j=()=>[gv,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...w()],M=()=>[gv,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...w()],N=()=>[e,$,Q],P=()=>[...b(),Rv,Nv,{position:[$,Q]}],F=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],re=()=>[`auto`,`cover`,`contain`,zv,Ov,{size:[$,Q]}],ie=()=>[yv,Iv,kv],I=()=>[``,`none`,`full`,l,$,Q],ae=()=>[``,_v,Iv,kv],L=()=>[`solid`,`dashed`,`dotted`,`double`],oe=()=>[`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`],se=()=>[_v,yv,Rv,Nv],ce=()=>[``,`none`,m,$,Q],le=()=>[`none`,_v,$,Q],ue=()=>[`none`,_v,$,Q],de=()=>[_v,$,Q],R=()=>[gv,`full`,...w()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[bv],breakpoint:[bv],color:[xv],container:[bv],"drop-shadow":[bv],ease:[`in`,`out`,`in-out`],font:[Ev],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[bv],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[bv],shadow:[bv],spacing:[`px`,_v],text:[bv],"text-shadow":[bv],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,gv,Q,$,g]}],container:[`container`],"container-type":[{"@container":[``,`normal`,`size`,$,Q]}],"container-named":[Dv],columns:[{columns:[_v,Q,$,s]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":[`auto`,`avoid`,`avoid-page`,`avoid-column`]}],"box-decoration":[{"box-decoration":[`slice`,`clone`]}],box:[{box:[`border`,`content`]}],display:[`block`,`inline-block`,`inline`,`flex`,`inline-flex`,`table`,`inline-table`,`table-caption`,`table-cell`,`table-column`,`table-column-group`,`table-footer-group`,`table-header-group`,`table-row-group`,`table-row`,`flow-root`,`grid`,`inline-grid`,`contents`,`list-item`,`hidden`],sr:[`sr-only`,`not-sr-only`],float:[{float:[`right`,`left`,`none`,`start`,`end`]}],clear:[{clear:[`left`,`right`,`both`,`none`,`start`,`end`]}],isolation:[`isolate`,`isolation-auto`],"object-fit":[{object:[`contain`,`cover`,`fill`,`none`,`scale-down`]}],"object-position":[{object:x()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:[`static`,`fixed`,`absolute`,`relative`,`sticky`],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{"inset-s":T(),start:T()}],end:[{"inset-e":T(),end:T()}],"inset-bs":[{"inset-bs":T()}],"inset-be":[{"inset-be":T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:[`visible`,`invisible`,`collapse`],z:[{z:[vv,`auto`,$,Q]}],basis:[{basis:[gv,`full`,`auto`,s,...w()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[_v,gv,`auto`,`initial`,`none`,Q]}],grow:[{grow:[``,_v,$,Q]}],shrink:[{shrink:[``,_v,$,Q]}],order:[{order:[vv,`first`,`last`,`none`,$,Q]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":[`row`,`col`,`dense`,`row-dense`,`col-dense`]}],"auto-cols":[{"auto-cols":ee()}],"auto-rows":[{"auto-rows":ee()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...te(),`normal`]}],"justify-items":[{"justify-items":[...ne(),`normal`]}],"justify-self":[{"justify-self":[`auto`,...ne()]}],"align-content":[{content:[`normal`,...te()]}],"align-items":[{items:[...ne(),{baseline:[``,`last`]}]}],"align-self":[{self:[`auto`,...ne(),{baseline:[``,`last`]}]}],"place-content":[{"place-content":te()}],"place-items":[{"place-items":[...ne(),`baseline`]}],"place-self":[{"place-self":[`auto`,...ne()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pbs:[{pbs:w()}],pbe:[{pbe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:k()}],mx:[{mx:k()}],my:[{my:k()}],ms:[{ms:k()}],me:[{me:k()}],mbs:[{mbs:k()}],mbe:[{mbe:k()}],mt:[{mt:k()}],mr:[{mr:k()}],mb:[{mb:k()}],ml:[{ml:k()}],"space-x":[{"space-x":w()}],"space-x-reverse":[`space-x-reverse`],"space-y":[{"space-y":w()}],"space-y-reverse":[`space-y-reverse`],size:[{size:A()}],"inline-size":[{inline:[`auto`,...j()]}],"min-inline-size":[{"min-inline":[`auto`,...j()]}],"max-inline-size":[{"max-inline":[`none`,...j()]}],"block-size":[{block:[`auto`,...M()]}],"min-block-size":[{"min-block":[`auto`,...M()]}],"max-block-size":[{"max-block":[`none`,...M()]}],w:[{w:[s,`screen`,...A()]}],"min-w":[{"min-w":[s,`screen`,`none`,...A()]}],"max-w":[{"max-w":[s,`screen`,`none`,`prose`,{screen:[o]},...A()]}],h:[{h:[`screen`,`lh`,...A()]}],"min-h":[{"min-h":[`screen`,`lh`,`none`,...A()]}],"max-h":[{"max-h":[`screen`,`lh`,...A()]}],"font-size":[{text:[`base`,n,Iv,kv]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,Hv,jv]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,yv,Q]}],"font-family":[{font:[Lv,Mv,t]}],"font-features":[{"font-features":[Q]}],"fvn-normal":[`normal-nums`],"fvn-ordinal":[`ordinal`],"fvn-slashed-zero":[`slashed-zero`],"fvn-figure":[`lining-nums`,`oldstyle-nums`],"fvn-spacing":[`proportional-nums`,`tabular-nums`],"fvn-fraction":[`diagonal-fractions`,`stacked-fractions`],tracking:[{tracking:[i,$,Q]}],"line-clamp":[{"line-clamp":[_v,`none`,$,Av]}],leading:[{leading:[a,...w()]}],"list-image":[{"list-image":[`none`,$,Q]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,$,Q]}],"text-alignment":[{text:[`left`,`center`,`right`,`justify`,`start`,`end`]}],"placeholder-color":[{placeholder:N()}],"text-color":[{text:N()}],"text-decoration":[`underline`,`overline`,`line-through`,`no-underline`],"text-decoration-style":[{decoration:[...L(),`wavy`]}],"text-decoration-thickness":[{decoration:[_v,`from-font`,`auto`,$,kv]}],"text-decoration-color":[{decoration:N()}],"underline-offset":[{"underline-offset":[_v,`auto`,$,Q]}],"text-transform":[`uppercase`,`lowercase`,`capitalize`,`normal-case`],"text-overflow":[`truncate`,`text-ellipsis`,`text-clip`],"text-wrap":[{text:[`wrap`,`nowrap`,`balance`,`pretty`]}],indent:[{indent:w()}],"tab-size":[{tab:[vv,$,Q]}],"vertical-align":[{align:[`baseline`,`top`,`middle`,`bottom`,`text-top`,`text-bottom`,`sub`,`super`,$,Q]}],whitespace:[{whitespace:[`normal`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]}],break:[{break:[`normal`,`words`,`all`,`keep`]}],wrap:[{wrap:[`break-word`,`anywhere`,`normal`]}],hyphens:[{hyphens:[`none`,`manual`,`auto`]}],content:[{content:[`none`,$,Q]}],"bg-attachment":[{bg:[`fixed`,`local`,`scroll`]}],"bg-clip":[{"bg-clip":[`border`,`padding`,`content`,`text`]}],"bg-origin":[{"bg-origin":[`border`,`padding`,`content`]}],"bg-position":[{bg:P()}],"bg-repeat":[{bg:F()}],"bg-size":[{bg:re()}],"bg-image":[{bg:[`none`,{linear:[{to:[`t`,`tr`,`r`,`br`,`b`,`bl`,`l`,`tl`]},vv,$,Q],radial:[``,$,Q],conic:[vv,$,Q]},Bv,Pv]}],"bg-color":[{bg:N()}],"gradient-from-pos":[{from:ie()}],"gradient-via-pos":[{via:ie()}],"gradient-to-pos":[{to:ie()}],"gradient-from":[{from:N()}],"gradient-via":[{via:N()}],"gradient-to":[{to:N()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:ae()}],"border-w-x":[{"border-x":ae()}],"border-w-y":[{"border-y":ae()}],"border-w-s":[{"border-s":ae()}],"border-w-e":[{"border-e":ae()}],"border-w-bs":[{"border-bs":ae()}],"border-w-be":[{"border-be":ae()}],"border-w-t":[{"border-t":ae()}],"border-w-r":[{"border-r":ae()}],"border-w-b":[{"border-b":ae()}],"border-w-l":[{"border-l":ae()}],"divide-x":[{"divide-x":ae()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":ae()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...L(),`hidden`,`none`]}],"divide-style":[{divide:[...L(),`hidden`,`none`]}],"border-color":[{border:N()}],"border-color-x":[{"border-x":N()}],"border-color-y":[{"border-y":N()}],"border-color-s":[{"border-s":N()}],"border-color-e":[{"border-e":N()}],"border-color-bs":[{"border-bs":N()}],"border-color-be":[{"border-be":N()}],"border-color-t":[{"border-t":N()}],"border-color-r":[{"border-r":N()}],"border-color-b":[{"border-b":N()}],"border-color-l":[{"border-l":N()}],"divide-color":[{divide:N()}],"outline-style":[{outline:[...L(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[_v,$,Q]}],"outline-w":[{outline:[``,_v,Iv,kv]}],"outline-color":[{outline:N()}],shadow:[{shadow:[``,`none`,u,Vv,Fv]}],"shadow-color":[{shadow:N()}],"inset-shadow":[{"inset-shadow":[`none`,d,Vv,Fv]}],"inset-shadow-color":[{"inset-shadow":N()}],"ring-w":[{ring:ae()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:N()}],"ring-offset-w":[{"ring-offset":[_v,kv]}],"ring-offset-color":[{"ring-offset":N()}],"inset-ring-w":[{"inset-ring":ae()}],"inset-ring-color":[{"inset-ring":N()}],"text-shadow":[{"text-shadow":[`none`,f,Vv,Fv]}],"text-shadow-color":[{"text-shadow":N()}],opacity:[{opacity:[_v,$,Q]}],"mix-blend":[{"mix-blend":[...oe(),`plus-darker`,`plus-lighter`]}],"bg-blend":[{"bg-blend":oe()}],"mask-clip":[{"mask-clip":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]},`mask-no-clip`],"mask-composite":[{mask:[`add`,`subtract`,`intersect`,`exclude`]}],"mask-image-linear-pos":[{"mask-linear":[_v]}],"mask-image-linear-from-pos":[{"mask-linear-from":se()}],"mask-image-linear-to-pos":[{"mask-linear-to":se()}],"mask-image-linear-from-color":[{"mask-linear-from":N()}],"mask-image-linear-to-color":[{"mask-linear-to":N()}],"mask-image-t-from-pos":[{"mask-t-from":se()}],"mask-image-t-to-pos":[{"mask-t-to":se()}],"mask-image-t-from-color":[{"mask-t-from":N()}],"mask-image-t-to-color":[{"mask-t-to":N()}],"mask-image-r-from-pos":[{"mask-r-from":se()}],"mask-image-r-to-pos":[{"mask-r-to":se()}],"mask-image-r-from-color":[{"mask-r-from":N()}],"mask-image-r-to-color":[{"mask-r-to":N()}],"mask-image-b-from-pos":[{"mask-b-from":se()}],"mask-image-b-to-pos":[{"mask-b-to":se()}],"mask-image-b-from-color":[{"mask-b-from":N()}],"mask-image-b-to-color":[{"mask-b-to":N()}],"mask-image-l-from-pos":[{"mask-l-from":se()}],"mask-image-l-to-pos":[{"mask-l-to":se()}],"mask-image-l-from-color":[{"mask-l-from":N()}],"mask-image-l-to-color":[{"mask-l-to":N()}],"mask-image-x-from-pos":[{"mask-x-from":se()}],"mask-image-x-to-pos":[{"mask-x-to":se()}],"mask-image-x-from-color":[{"mask-x-from":N()}],"mask-image-x-to-color":[{"mask-x-to":N()}],"mask-image-y-from-pos":[{"mask-y-from":se()}],"mask-image-y-to-pos":[{"mask-y-to":se()}],"mask-image-y-from-color":[{"mask-y-from":N()}],"mask-image-y-to-color":[{"mask-y-to":N()}],"mask-image-radial":[{"mask-radial":[$,Q]}],"mask-image-radial-from-pos":[{"mask-radial-from":se()}],"mask-image-radial-to-pos":[{"mask-radial-to":se()}],"mask-image-radial-from-color":[{"mask-radial-from":N()}],"mask-image-radial-to-color":[{"mask-radial-to":N()}],"mask-image-radial-shape":[{"mask-radial":[`circle`,`ellipse`]}],"mask-image-radial-size":[{"mask-radial":[{closest:[`side`,`corner`],farthest:[`side`,`corner`]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[_v]}],"mask-image-conic-from-pos":[{"mask-conic-from":se()}],"mask-image-conic-to-pos":[{"mask-conic-to":se()}],"mask-image-conic-from-color":[{"mask-conic-from":N()}],"mask-image-conic-to-color":[{"mask-conic-to":N()}],"mask-mode":[{mask:[`alpha`,`luminance`,`match`]}],"mask-origin":[{"mask-origin":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]}],"mask-position":[{mask:P()}],"mask-repeat":[{mask:F()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":[`alpha`,`luminance`]}],"mask-image":[{mask:[`none`,$,Q]}],filter:[{filter:[``,`none`,$,Q]}],blur:[{blur:ce()}],brightness:[{brightness:[_v,$,Q]}],contrast:[{contrast:[_v,$,Q]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,Vv,Fv]}],"drop-shadow-color":[{"drop-shadow":N()}],grayscale:[{grayscale:[``,_v,$,Q]}],"hue-rotate":[{"hue-rotate":[_v,$,Q]}],invert:[{invert:[``,_v,$,Q]}],saturate:[{saturate:[_v,$,Q]}],sepia:[{sepia:[``,_v,$,Q]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,$,Q]}],"backdrop-blur":[{"backdrop-blur":ce()}],"backdrop-brightness":[{"backdrop-brightness":[_v,$,Q]}],"backdrop-contrast":[{"backdrop-contrast":[_v,$,Q]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,_v,$,Q]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[_v,$,Q]}],"backdrop-invert":[{"backdrop-invert":[``,_v,$,Q]}],"backdrop-opacity":[{"backdrop-opacity":[_v,$,Q]}],"backdrop-saturate":[{"backdrop-saturate":[_v,$,Q]}],"backdrop-sepia":[{"backdrop-sepia":[``,_v,$,Q]}],"border-collapse":[{border:[`collapse`,`separate`]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:[`auto`,`fixed`]}],caption:[{caption:[`top`,`bottom`]}],transition:[{transition:[``,`all`,`colors`,`opacity`,`shadow`,`transform`,`none`,$,Q]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[_v,`initial`,$,Q]}],ease:[{ease:[`linear`,`initial`,_,$,Q]}],delay:[{delay:[_v,$,Q]}],animate:[{animate:[`none`,v,$,Q]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,$,Q]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:le()}],"rotate-x":[{"rotate-x":le()}],"rotate-y":[{"rotate-y":le()}],"rotate-z":[{"rotate-z":le()}],scale:[{scale:ue()}],"scale-x":[{"scale-x":ue()}],"scale-y":[{"scale-y":ue()}],"scale-z":[{"scale-z":ue()}],"scale-3d":[`scale-3d`],skew:[{skew:de()}],"skew-x":[{"skew-x":de()}],"skew-y":[{"skew-y":de()}],transform:[{transform:[$,Q,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:R()}],"translate-x":[{"translate-x":R()}],"translate-y":[{"translate-y":R()}],"translate-z":[{"translate-z":R()}],"translate-none":[`translate-none`],zoom:[{zoom:[vv,$,Q]}],accent:[{accent:N()}],appearance:[{appearance:[`none`,`auto`]}],"caret-color":[{caret:N()}],"color-scheme":[{scheme:[`normal`,`dark`,`light`,`light-dark`,`only-dark`,`only-light`]}],cursor:[{cursor:[`auto`,`default`,`pointer`,`wait`,`text`,`move`,`help`,`not-allowed`,`none`,`context-menu`,`progress`,`cell`,`crosshair`,`vertical-text`,`alias`,`copy`,`no-drop`,`grab`,`grabbing`,`all-scroll`,`col-resize`,`row-resize`,`n-resize`,`e-resize`,`s-resize`,`w-resize`,`ne-resize`,`nw-resize`,`se-resize`,`sw-resize`,`ew-resize`,`ns-resize`,`nesw-resize`,`nwse-resize`,`zoom-in`,`zoom-out`,$,Q]}],"field-sizing":[{"field-sizing":[`fixed`,`content`]}],"pointer-events":[{"pointer-events":[`auto`,`none`]}],resize:[{resize:[`none`,``,`y`,`x`]}],"scroll-behavior":[{scroll:[`auto`,`smooth`]}],"scrollbar-thumb-color":[{"scrollbar-thumb":N()}],"scrollbar-track-color":[{"scrollbar-track":N()}],"scrollbar-gutter":[{"scrollbar-gutter":[`auto`,`stable`,`both`]}],"scrollbar-w":[{scrollbar:[`auto`,`thin`,`none`]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mbs":[{"scroll-mbs":w()}],"scroll-mbe":[{"scroll-mbe":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pbs":[{"scroll-pbs":w()}],"scroll-pbe":[{"scroll-pbe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:[`start`,`end`,`center`,`align-none`]}],"snap-stop":[{snap:[`normal`,`always`]}],"snap-type":[{snap:[`none`,`x`,`y`,`both`]}],"snap-strictness":[{snap:[`mandatory`,`proximity`]}],touch:[{touch:[`auto`,`none`,`manipulation`]}],"touch-x":[{"touch-pan":[`x`,`left`,`right`]}],"touch-y":[{"touch-pan":[`y`,`up`,`down`]}],"touch-pz":[`touch-pinch-zoom`],select:[{select:[`none`,`text`,`all`,`auto`]}],"will-change":[{"will-change":[`auto`,`scroll`,`contents`,`transform`,$,Q]}],fill:[{fill:[`none`,...N()]}],"stroke-w":[{stroke:[_v,Iv,kv,Av]}],stroke:[{stroke:[`none`,...N()]}],"forced-color-adjust":[{"forced-color-adjust":[`auto`,`none`]}]},conflictingClassGroups:{"container-named":[`container-type`],overflow:[`overflow-x`,`overflow-y`],overscroll:[`overscroll-x`,`overscroll-y`],inset:[`inset-x`,`inset-y`,`inset-bs`,`inset-be`,`start`,`end`,`top`,`right`,`bottom`,`left`],"inset-x":[`right`,`left`],"inset-y":[`top`,`bottom`],flex:[`basis`,`grow`,`shrink`],gap:[`gap-x`,`gap-y`],p:[`px`,`py`,`ps`,`pe`,`pbs`,`pbe`,`pt`,`pr`,`pb`,`pl`],px:[`pr`,`pl`],py:[`pt`,`pb`],m:[`mx`,`my`,`ms`,`me`,`mbs`,`mbe`,`mt`,`mr`,`mb`,`ml`],mx:[`mr`,`ml`],my:[`mt`,`mb`],size:[`w`,`h`],"font-size":[`leading`],"fvn-normal":[`fvn-ordinal`,`fvn-slashed-zero`,`fvn-figure`,`fvn-spacing`,`fvn-fraction`],"fvn-ordinal":[`fvn-normal`],"fvn-slashed-zero":[`fvn-normal`],"fvn-figure":[`fvn-normal`],"fvn-spacing":[`fvn-normal`],"fvn-fraction":[`fvn-normal`],"line-clamp":[`display`,`overflow`],rounded:[`rounded-s`,`rounded-e`,`rounded-t`,`rounded-r`,`rounded-b`,`rounded-l`,`rounded-ss`,`rounded-se`,`rounded-ee`,`rounded-es`,`rounded-tl`,`rounded-tr`,`rounded-br`,`rounded-bl`],"rounded-s":[`rounded-ss`,`rounded-es`],"rounded-e":[`rounded-se`,`rounded-ee`],"rounded-t":[`rounded-tl`,`rounded-tr`],"rounded-r":[`rounded-tr`,`rounded-br`],"rounded-b":[`rounded-br`,`rounded-bl`],"rounded-l":[`rounded-tl`,`rounded-bl`],"border-spacing":[`border-spacing-x`,`border-spacing-y`],"border-w":[`border-w-x`,`border-w-y`,`border-w-s`,`border-w-e`,`border-w-bs`,`border-w-be`,`border-w-t`,`border-w-r`,`border-w-b`,`border-w-l`],"border-w-x":[`border-w-r`,`border-w-l`],"border-w-y":[`border-w-t`,`border-w-b`],"border-color":[`border-color-x`,`border-color-y`,`border-color-s`,`border-color-e`,`border-color-bs`,`border-color-be`,`border-color-t`,`border-color-r`,`border-color-b`,`border-color-l`],"border-color-x":[`border-color-r`,`border-color-l`],"border-color-y":[`border-color-t`,`border-color-b`],translate:[`translate-x`,`translate-y`,`translate-none`],"translate-none":[`translate`,`translate-x`,`translate-y`,`translate-z`],"scroll-m":[`scroll-mx`,`scroll-my`,`scroll-ms`,`scroll-me`,`scroll-mbs`,`scroll-mbe`,`scroll-mt`,`scroll-mr`,`scroll-mb`,`scroll-ml`],"scroll-mx":[`scroll-mr`,`scroll-ml`],"scroll-my":[`scroll-mt`,`scroll-mb`],"scroll-p":[`scroll-px`,`scroll-py`,`scroll-ps`,`scroll-pe`,`scroll-pbs`,`scroll-pbe`,`scroll-pt`,`scroll-pr`,`scroll-pb`,`scroll-pl`],"scroll-px":[`scroll-pr`,`scroll-pl`],"scroll-py":[`scroll-pt`,`scroll-pb`],touch:[`touch-x`,`touch-y`,`touch-pz`],"touch-x":[`touch`],"touch-y":[`touch`],"touch-pz":[`touch`]},conflictingClassGroupModifiers:{"font-size":[`leading`]},postfixLookupClassGroups:[`container-type`],orderSensitiveModifiers:[`*`,`**`,`after`,`backdrop`,`before`,`details-content`,`file`,`first-letter`,`first-line`,`marker`,`placeholder`,`selection`]}});function ey(...e){return $v(w_(e))}var ty=D_(`inline-flex h-9 shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-md border px-3 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400 disabled:pointer-events-none disabled:opacity-50 dark:focus-visible:ring-zinc-500`,{variants:{variant:{primary:`border-slate-900 bg-slate-950 text-white hover:bg-slate-800 dark:border-zinc-100 dark:bg-zinc-50 dark:text-zinc-950 dark:hover:bg-zinc-200`,secondary:`border-slate-200 bg-white text-slate-900 hover:bg-slate-50 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-100 dark:hover:bg-zinc-900`,ghost:`border-transparent bg-transparent text-slate-700 hover:bg-slate-100 dark:text-zinc-300 dark:hover:bg-zinc-900`},size:{sm:`h-8 px-2 text-xs`,md:`h-9 px-3 text-sm`,icon:`h-9 w-9 px-0`}},defaultVariants:{variant:`secondary`,size:`md`}});function ny({className:e,variant:t,size:n,...r}){return(0,V.jsx)(`button`,{className:ey(ty({variant:t,size:n}),e),type:`button`,...r})}function ry({className:e,...t}){return(0,V.jsx)(`section`,{className:ey(`rounded-lg border border-slate-200/80 bg-white/95 text-slate-950 shadow-[0_1px_2px_rgba(15,23,42,0.04)] dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50`,e),...t})}function iy({className:e,...t}){return(0,V.jsx)(`div`,{className:ey(`p-4 pt-0`,e),...t})}var ay=[`codex`,`claude`,`kiro`,`trae`,`coco`,`openai`,`anthropic`],oy=new Set([`acp`,`status_projection`]);function sy(e){let t=e.trim().toLowerCase().replace(/_/gu,`-`);for(let e of ay)if(t===e||t.startsWith(`${e}-`))return e;return t}function cy(e,t){let n=t?.trim().toLowerCase()??``;return n.length>0&&!oy.has(n)?sy(n):sy(e)}var ly={stop:`ready_stop`,resume:`resume_review`,delete:`delete_review`},uy=e=>typeof e==`string`&&e.trim().length>0;function dy(e){let t={schemaVersion:`action_review_plan_v0`,proposalId:e.proposal_id,sourceFingerprint:e.expected_state_fingerprint},n=(e,n)=>({...t,interaction:e,reason:n,canApply:!1}),r=e.action_kind===`goal.lifecycle`;if(r&&e.gate!=null||e.status===`gated`)return n(`gated`,`authority_gate`);if(r&&e.stale!=null||e.status===`stale`)return n(`refresh`,`stale_proposal`);if(e.status===`applied`)return e.receipt?.projection_verified===!0?n(`completed`,`readback_verified`):n(`repair`,`readback_unverified`);if(e.status===`applying`)return n(`pending`,`apply_pending`);if(e.status===`failed`||e.error!=null)return n(`repair`,`apply_failed`);if(e.status!==`preview_ready`&&e.status!==`deferred`)return n(`inactive`,`inactive_proposal`);let i=(e,n=!0)=>({...t,interaction:`review`,reason:e,canApply:n});if(e.action_kind!==`goal.lifecycle`)return i(e.permission_classification===`protected`?`protected_action`:`action_review`);if(!(uy(e.proposal_id)&&uy(e.expected_state_fingerprint)&&Dh.shape.validation_evidence.safeParse(e.validation_evidence).success&&e.validation_evidence.length>0&&e.available_transitions.includes(`apply`)))return n(`refresh`,`incomplete_proposal`);let{operation:a,goal_id:o}=e.normalized_parameters;if(!uy(o)||e.context.goal_id!=null&&e.context.goal_id!==o)return n(`refresh`,`incomplete_proposal`);if(a!==`stop`&&a!==`resume`&&a!==`delete`)return i(`unknown_action`,!1);if(e.permission_classification===`protected`)return i(`protected_action`);if(e.permission_classification!==`durable_write`)return i(`unknown_permission`,!1);let s=ly[a];return s===`ready_stop`&&e.status===`preview_ready`?{...t,interaction:`direct`,reason:s,canApply:!0}:i(s===`ready_stop`?`action_review`:s)}function fy(e){if(e.error_code===`action_stale`||e.error_code===`action_conflict`)return!0;let t=e.proposal;return typeof t==`object`&&!!t&&`status`in t&&t.status===`stale`}function py(e){return{blockingTodoCount:e.blockingTodoCount,goalNotifications:e.goalNotifications,goals:e.goals,openUserTodoCount:e.openUserTodoCount,systemHealth:e.systemHealth,attentionHistory:e.attentionHistory,userTodos:e.userTodos,workers:e.workers}}function my(e,t){return e.goals.find(e=>e.goalId===t)?.title??t}function hy(e){return e.activationState===`stopped`||e.state===`已停止`?`stopped`:e.state===`已完成`?`history`:e.needsYou||e.state===`等你`?`needs_you`:e.state===`推进中`||e.state===`需修复`?`running`:e.state===`安静运行`?`observing`:`scheduled`}function gy(e){let t=e;return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function _y(e){return`$${e.toFixed(2)}`}function vy(e){let t=e;return t>=36e5?`${(t/36e5).toFixed(1)}h`:t>=6e4?`${(t/6e4).toFixed(1)}m`:t>=1e3?`${Math.round(t/1e3)}s`:`${t}ms`}function yy(e,t,n){return e==null?t:n(e)}function by(e){return!!(e&&[e.tokens24h,e.tokens7d,e.costUsd24h,e.costUsd7d,e.durationMs24h,e.durationMs7d].some(e=>e!=null))}function xy(e,t){if(!by(e))return null;let n=(e,n,r,i)=>{let a=[n==null?null:`${gy(n)} ${t.tokens}`,r==null?null:`${t.cost}: ${_y(r)}`,i==null?null:`${t.duration}: ${vy(i)}`].filter(e=>e!==null);return a.length?`${e} ${a.join(` · `)}`:null};return n(t.period7d,e.tokens7d,e.costUsd7d,e.durationMs7d)??n(t.period24h,e.tokens24h,e.costUsd24h,e.durationMs24h)}function Sy({ariaLabel:e,className:t,icon:n,onChange:r,options:i,prefixLabel:a,value:o}){let s=(0,B.useId)(),c=(0,B.useRef)(null),l=(0,B.useRef)(null),u=(0,B.useRef)(new Map),[d,f]=(0,B.useState)(!1),[p,m]=(0,B.useState)(o),h=i.find(e=>e.value===o)??i[0],g=i.filter(e=>!e.disabled);(0,B.useEffect)(()=>{if(!d)return;let e=e=>{c.current?.contains(e.target)||f(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[d]),(0,B.useEffect)(()=>{d&&u.current.get(p)?.focus()},[p,d]);function _(e){m(e)}function v(e=`selected`){let t=e===`last`?g.at(-1):g[0],n=e===`selected`&&h&&!h.disabled?h:t;n&&(f(!0),_(n.value))}function y({restoreFocus:e=!1}={}){f(!1),e&&l.current?.focus()}function b(e){e.disabled||(r(e.value),y({restoreFocus:!0}))}function x(e){if(!g.length)return;let t=g.findIndex(e=>e.value===p),n=t<0?0:(t+e+g.length)%g.length;_(g[n].value)}function S(e){e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),v(`selected`)):e.key===`ArrowUp`&&(e.preventDefault(),v(`last`))}function C(e,t){if(e.key===`ArrowDown`)e.preventDefault(),x(1);else if(e.key===`ArrowUp`)e.preventDefault(),x(-1);else if(e.key===`Home`)e.preventDefault(),g[0]&&_(g[0].value);else if(e.key===`End`){e.preventDefault();let t=g.at(-1);t&&_(t.value)}else e.key===`Enter`||e.key===` `?(e.preventDefault(),b(t)):e.key===`Escape`?(e.preventDefault(),y({restoreFocus:!0})):e.key===`Tab`&&y()}let w;return(0,V.jsxs)(`div`,{className:`personal-select${t?` ${t}`:``}`,ref:c,children:[(0,V.jsxs)(`button`,{"aria-controls":s,"aria-expanded":d,"aria-haspopup":`listbox`,"aria-label":e,className:`personal-select-trigger`,"data-value":o,onClick:()=>d?y():v(),onKeyDown:S,ref:l,role:`combobox`,type:`button`,children:[n?(0,V.jsx)(`span`,{className:`personal-select-icon`,children:n}):null,(0,V.jsxs)(`span`,{className:`personal-select-value`,children:[a?(0,V.jsx)(`small`,{children:a}):null,(0,V.jsx)(`span`,{children:h?.label??o})]}),(0,V.jsx)(tm,{"aria-hidden":!0,className:d?`is-open`:void 0,size:14})]}),d?(0,V.jsx)(`div`,{"aria-label":e,className:`personal-select-listbox`,id:s,role:`listbox`,children:i.map(e=>{let t=e.group&&e.group!==w;return w=e.group,(0,V.jsxs)(`div`,{className:`personal-select-option-wrap`,children:[t?(0,V.jsx)(`div`,{className:`personal-select-group-label`,children:e.group}):null,(0,V.jsxs)(`button`,{"aria-disabled":e.disabled||void 0,"aria-selected":e.value===o,className:`personal-select-option`,disabled:e.disabled,id:`${s}-${e.value.replace(/[^a-z0-9_-]/gi,`-`)}`,onClick:()=>b(e),onFocus:()=>m(e.value),onKeyDown:t=>C(t,e),ref:t=>{t?u.current.set(e.value,t):u.current.delete(e.value)},role:`option`,tabIndex:e.value===p?0:-1,type:`button`,children:[(0,V.jsx)(`span`,{children:e.label}),e.value===o?(0,V.jsx)(em,{"aria-hidden":!0,size:15}):null]})]},e.value)})}):null]})}function Cy({agents:e,managerChatOpen:t,mobileNavigationOpen:n,onOpenGoalCapabilities:r,onOpenGoalDetail:i,onOpenManagerChat:a,onRefresh:o,onOpenNavigation:s,onSelectGoalTab:c,onSelectAgent:l,onReturnManagerHome:u,refreshState:d,readOnlySourceLabel:f,selectedAgentId:p,selectedGoal:m,selectedGoalTab:h}){let{locale:g,t:_}=qi(),[v,y]=(0,B.useState)(!1),b=(0,B.useRef)(null),x=(0,B.useRef)(null);(0,B.useEffect)(()=>{if(!v)return;function e(e){x.current?.contains(e.target)||y(!1)}function t(e){e.key===`Escape`&&(y(!1),b.current?.focus())}return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[v]),(0,B.useEffect)(()=>y(!1),[m?.goalId]);function S(e){y(!1),e?.()}let C=m?xy(m.usage,{cost:_(`drawer.costShort`),duration:_(`drawer.durationShort`),period24h:_(`drawer.period24h`),period7d:_(`drawer.period7d`),tokens:_(`drawer.tokensShort`)}):null;return(0,V.jsxs)(`header`,{className:`personal-channel-header`,children:[(0,V.jsx)(`button`,{"aria-expanded":n??!1,"aria-label":_(`header.openGoalNavigation`),className:`personal-icon-button personal-mobile-menu`,onClick:s,type:`button`,children:(0,V.jsx)(Tm,{size:18})}),(0,V.jsxs)(`div`,{className:`personal-channel-title`,children:[(0,V.jsx)(`h1`,{children:m?.title??_(`header.manager`)}),m?(0,V.jsx)(`p`,{children:m.loadState?_(m.loadState===`error`?`startup.goalError`:`startup.goalLoading`):`${m.agentLaneCount&&m.agentLaneCount>1?_(`header.workAgentCount`,{count:m.agentLaneCount}):m.agentLabel??m.agentId} · ${m.loadState?_(m.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Ji(m.state,g)}${C?` · ${C}`:``} · ${m.nextSentence}`}):null]}),m?(0,V.jsxs)(`nav`,{"aria-label":_(`header.goalView`),className:`personal-goal-tabs`,children:[(0,V.jsx)(`button`,{"aria-current":h===`chat`?`page`:void 0,onClick:()=>c(`chat`),type:`button`,children:_(`header.chat`)}),(0,V.jsx)(`button`,{"aria-current":h===`tasks`?`page`:void 0,onClick:()=>c(`tasks`),type:`button`,children:_(`header.tasks`)}),(0,V.jsx)(`button`,{"aria-current":h===`files`?`page`:void 0,onClick:()=>c(`files`),type:`button`,children:_(`header.files`)})]}):(0,V.jsxs)(`nav`,{"aria-label":_(`header.managerView`),className:`personal-goal-tabs`,children:[(0,V.jsx)(`button`,{"aria-current":t?void 0:`page`,onClick:u,type:`button`,children:_(`header.managerOverview`)}),(0,V.jsx)(`button`,{"aria-current":t?`page`:void 0,onClick:a,type:`button`,children:_(`header.chat`)})]}),(0,V.jsxs)(`div`,{className:`personal-channel-actions`,children:[m&&i&&r?(0,V.jsxs)(`div`,{className:`personal-goal-tools`,ref:x,children:[(0,V.jsxs)(`button`,{"aria-expanded":v,"aria-haspopup":`menu`,"aria-label":_(`header.goalSettingsDescription`),className:`personal-goal-tools-trigger`,onClick:()=>y(e=>!e),ref:b,title:_(`header.goalSettingsDescription`),type:`button`,children:[(0,V.jsx)(Gm,{"aria-hidden":!0,size:16}),(0,V.jsx)(`span`,{children:_(`header.goalSettings`)}),(0,V.jsx)(tm,{"aria-hidden":!0,size:13})]}),v?(0,V.jsxs)(`fieldset`,{"aria-label":_(`header.goalSettings`),className:`personal-goal-tools-menu`,children:[(0,V.jsxs)(`button`,{onClick:()=>S(i),type:`button`,children:[(0,V.jsx)(ym,{"aria-hidden":!0,size:17}),(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:_(`header.goalDetails`)})})]}),(0,V.jsxs)(`button`,{onClick:()=>S(r),type:`button`,children:[(0,V.jsx)(Gm,{"aria-hidden":!0,size:17}),(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:_(`header.goalCapabilities`)})})]})]}):null]}):null,f?(0,V.jsxs)(`span`,{className:`personal-read-only-source`,title:_(`header.readOnlySourceDescription`,{source:f}),children:[(0,V.jsx)(pm,{size:15}),f,(0,V.jsx)(`small`,{children:_(`common.readOnly`)})]}):(0,V.jsx)(Sy,{ariaLabel:_(`header.selectChatRuntime`),className:`personal-agent-select`,icon:(0,V.jsx)(Zp,{size:16}),onChange:l,options:e.map(e=>({disabled:!e.available,label:`${e.label}${e.available?``:` · ${_(`header.agentUnavailable`)}`}`,value:e.agentId})),prefixLabel:_(`header.chatRuntime`),value:p}),(0,V.jsxs)(`span`,{className:`personal-live-indicator`,children:[(0,V.jsx)(`i`,{}),_(`header.live`)]}),o?(0,V.jsxs)(`span`,{className:`personal-refresh-control is-${d??`idle`}`,children:[d===`loading`?(0,V.jsx)(`small`,{children:_(`header.refreshing`)}):d===`done`?(0,V.jsx)(`small`,{children:_(`header.refreshDone`)}):d===`error`?(0,V.jsx)(`small`,{children:_(`header.refreshFailed`)}):null,(0,V.jsx)(`button`,{"aria-label":_(d===`loading`?`header.refreshing`:`header.refresh`),className:`personal-icon-button`,disabled:d===`loading`,onClick:o,type:`button`,children:(0,V.jsx)(Im,{className:d===`loading`?`is-spinning`:void 0,size:17})})]}):null]})]})}function wy({attention:e,onSelect:t}){let{t:n}=qi(),r=Xi(e.updatedAt,n);return(0,V.jsxs)(`button`,{className:`personal-timeline-row personal-attention-row`,"data-testid":`personal-browse-row`,onClick:t,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-row-icon is-attention`,children:(0,V.jsx)(im,{size:18})}),(0,V.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,V.jsxs)(`small`,{children:[e.goalTitle??e.goalId,` · `,n(`home.lane.needsYou`),r?` · ${n(`tasks.waitingAge`,{age:r})}`:``]}),(0,V.jsx)(`strong`,{children:e.text})]}),(0,V.jsx)(`span`,{className:`personal-priority-dot is-${e.priority??(e.blocking?`high`:`medium`)}`}),(0,V.jsx)(`span`,{className:`personal-row-status ${e.blocking?`is-blocking`:`is-pending`}`,children:e.blocking?n(`tasks.blocked`):n(`tasks.pending`)}),(0,V.jsx)(nm,{size:17})]})}var Ty=/(`[^`\n]+`)|(\*\*[^*\n]+(\*[^*\n]*)?\*\*)|(\[[^\]\n]{1,120}\]\(https?:\/\/[^)\s]+\))/g;function Ey(e,t){let n=[],r=0,i=0;for(let a of e.matchAll(Ty)){let o=a.index??0;o>r&&n.push(e.slice(r,o));let s=a[0],c=`${t}-i${i++}`;if(s.startsWith("`"))n.push((0,V.jsx)(`code`,{className:`personal-md-code`,children:s.slice(1,-1)},c));else if(s.startsWith(`**`))n.push((0,V.jsx)(`strong`,{children:s.slice(2,-2)},c));else{let e=s.indexOf(`](`),t=s.slice(1,e),r=s.slice(e+2,-1);n.push((0,V.jsx)(`a`,{className:`personal-md-link`,href:r,rel:`noreferrer`,target:`_blank`,children:t},c))}r=o+s.length}return r{r.length>0&&(n.push({type:`paragraph`,lines:r}),r=[])},a=0;for(;a{let n=`b${t}`;if(e.type===`code`)return(0,V.jsx)(`pre`,{className:`personal-md-pre`,children:(0,V.jsx)(`code`,{children:e.text})},n);if(e.type===`heading`)return(0,V.jsx)(`p`,{className:`personal-md-heading is-h${e.level}`,children:Ey(e.text,n)},n);if(e.type===`list`){let t=e.items.map((e,t)=>(0,V.jsx)(`li`,{children:Ey(e,`${n}-${t}`)},`${n}-${t}`));return e.ordered?(0,V.jsx)(`ol`,{className:`personal-md-list`,children:t},n):(0,V.jsx)(`ul`,{className:`personal-md-list`,children:t},n)}return(0,V.jsx)(`p`,{children:e.lines.map((e,t)=>(0,V.jsxs)(B.Fragment,{children:[t>0?(0,V.jsx)(`br`,{}):null,Ey(e,`${n}-${t}`)]},`${n}-${t}`))},n)})})}function jy({onSelect:e,output:t}){let{t:n}=qi(),r=t.kind===`report`?gm:hm;return(0,V.jsxs)(`button`,{className:`personal-timeline-row personal-output-row`,"data-output-kind":t.kind,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-row-icon is-output`,children:(0,V.jsx)(r,{size:18})}),(0,V.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,V.jsxs)(`small`,{children:[t.goalTitle??t.goalId,` · `,t.agentLabel??`LoopX`]}),(0,V.jsx)(`strong`,{children:t.title}),t.summary?(0,V.jsx)(`span`,{children:t.summary}):null,t.report?(0,V.jsxs)(`small`,{children:[n(`files.reportDelta`,{added:t.report.addedCount,changed:t.report.changedCount}),` · `,n(`files.verifiedReport`)]}):null]}),t.createdAt?(0,V.jsx)(`time`,{children:t.createdAt}):null,(0,V.jsx)(nm,{size:17})]})}var My={completed:`runs.completed`,failed:`runs.failed`,interrupted:`runs.interrupted`,queued:`runs.queued`,running:`runs.running`,waiting:`runs.waiting`};function Ny({onSelect:e,run:t}){let{t:n}=qi(),r=t.totalSteps>0?Math.min(100,t.completedSteps/t.totalSteps*100):0;return(0,V.jsxs)(`button`,{"aria-label":`${n(`tasks.viewExecution`)}:${t.title}`,className:`personal-timeline-row personal-run-row`,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-row-icon is-run`,children:(0,V.jsx)(Zp,{size:18})}),(0,V.jsxs)(`span`,{className:`personal-run-identity`,children:[(0,V.jsx)(`small`,{children:t.goalTitle}),(0,V.jsx)(`strong`,{children:t.agentLabel})]}),(0,V.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,V.jsx)(`strong`,{children:t.title}),(0,V.jsx)(`small`,{children:t.latestActivity})]}),(0,V.jsxs)(`span`,{className:`personal-run-progress`,"aria-label":`${t.completedSteps}/${t.totalSteps}`,children:[(0,V.jsxs)(`small`,{children:[t.completedSteps,`/`,t.totalSteps]}),(0,V.jsx)(`i`,{children:(0,V.jsx)(`b`,{style:{width:`${r}%`}})})]}),(0,V.jsxs)(`span`,{className:`personal-row-status is-${t.status}`,children:[t.status===`running`?(0,V.jsx)(Cm,{className:`personal-spin`,size:14}):null,n(My[t.status])]}),t.sessionId?(0,V.jsx)(`span`,{className:`personal-run-open-label`,children:n(`tasks.viewExecution`)}):null,(0,V.jsx)(nm,{size:17})]})}function Py({onSelect:e,schedule:t}){let{t:n}=qi(),r=t.scheduleKind===`heartbeat`;return(0,V.jsxs)(`button`,{"aria-label":`${r?`Heartbeat`:n(`tasks.scheduled`)}:${t.label};${t.status??`active`}`,className:`personal-schedule-row`,onClick:e,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-schedule-icon`,children:r?(0,V.jsx)(Fm,{size:17}):(0,V.jsx)($p,{size:17})}),(0,V.jsxs)(`span`,{className:`personal-schedule-copy`,children:[(0,V.jsx)(`small`,{children:n(r?`schedule.heartbeat`:`schedule.monitor`)}),(0,V.jsx)(`strong`,{children:t.label}),(0,V.jsx)(`p`,{children:t.schedule??n(`schedule.summary`)})]}),(0,V.jsx)(`span`,{className:`personal-schedule-status is-${t.status??`active`}`,children:t.status===`paused`?n(`schedule.paused`):n(`schedule.active`)}),(0,V.jsx)(nm,{size:16})]})}function Fy({items:e,onSelect:t,selectedGoal:n}){let{t:r}=qi();if(e.length===0)return(0,V.jsxs)(`div`,{className:`personal-timeline-empty`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(Km,{size:20})}),(0,V.jsx)(`strong`,{children:r(n?`timeline.emptyGoal`:`timeline.emptyWorkspace`)}),(0,V.jsx)(`p`,{children:r(n?`timeline.emptyGoalDescription`:`timeline.emptyWorkspaceDescription`)})]});let i=[...e].reverse().find(e=>e.kind===`message`&&e.message.role!==`user`||e.kind===`proposal`&&[`applied`,`stale`,`error`,`gated`].includes(e.proposal.status)||e.kind===`run`&&e.run.status===`completed`),a=i?.kind===`message`?`${i.message.agentLabel??r(`header.manager`)}:${i.message.pending?r(`timeline.pending`):i.message.text}`:i?.kind===`proposal`?`${i.proposal.title}:${i.proposal.status}`:i?.kind===`run`?r(`timeline.runCompleted`,{run:i.run.title}):``,o=e.filter(e=>e.kind===`proposal`&&e.proposal.status===`gated`),s=e.filter(e=>e.kind!==`proposal`),c=e.filter(e=>e.kind===`proposal`&&e.proposal.status!==`gated`);function l(e){return e.kind===`attention`?(0,V.jsx)(wy,{attention:e.attention,onSelect:()=>t({item:e.attention,kind:`attention`})},e.id):e.kind===`run`?(0,V.jsx)(Ny,{onSelect:()=>t({item:e.run,kind:`run`}),run:e.run},e.id):e.kind===`output`?(0,V.jsx)(jy,{onSelect:()=>t({item:e.output,kind:`output`}),output:e.output},e.id):e.kind===`schedule`?(0,V.jsx)(Py,{onSelect:()=>t({item:e.schedule,kind:`schedule`}),schedule:e.schedule},e.id):e.kind===`proposal`?(0,V.jsxs)(`button`,{className:`personal-proposal-row is-${e.proposal.status}`,onClick:()=>t({item:e.proposal,kind:`proposal`}),type:`button`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(Km,{size:17})}),(0,V.jsxs)(`span`,{children:[(0,V.jsxs)(`small`,{children:[e.proposal.actionKind,` · `,e.proposal.status]}),(0,V.jsx)(`strong`,{children:e.proposal.title}),(0,V.jsx)(`p`,{children:e.proposal.impact})]}),(0,V.jsx)(`b`,{children:e.proposal.status===`gated`?r(`timeline.review`):e.proposal.primaryLabel??r(`timeline.reviewAndConfirm`)})]},e.id):(0,V.jsxs)(`article`,{className:`personal-message is-${e.message.role}`,children:[e.message.role===`user`?null:(0,V.jsx)(`span`,{className:`personal-message-avatar`,children:(0,V.jsx)(Zp,{size:17})}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:e.message.role===`user`?r(`common.you`):e.message.agentLabel??r(`header.manager`)}),e.message.time?(0,V.jsx)(`time`,{children:e.message.time}):null]}),e.message.attachments?.length?(0,V.jsx)(`div`,{className:`personal-message-images`,children:e.message.attachments.map(e=>(0,V.jsx)(`img`,{alt:e.name,src:e.dataUrl},e.id))}):null,e.message.role===`user`?(0,V.jsx)(`p`,{children:e.message.text}):(0,V.jsx)(Ay,{text:e.message.text}),e.message.pending?(0,V.jsx)(`span`,{className:`personal-message-pending`,children:r(`timeline.pending`)}):null]})]},e.id)}return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{"aria-atomic":`true`,"aria-live":`polite`,className:`personal-live-region`,role:`status`,children:a}),(0,V.jsxs)(`div`,{className:`personal-channel-timeline`,children:[s.map(l),o.length?(0,V.jsxs)(`details`,{className:`personal-gated-summary`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(Km,{size:16})}),(0,V.jsx)(`strong`,{children:r(`timeline.waitingConfirmation`)}),(0,V.jsx)(`small`,{children:r(`timeline.gateHistory`,{count:o.length})})]}),(0,V.jsx)(`div`,{children:o.map(l)})]}):null,c.map(l)]})]})}function Iy({goal:e}){let{t}=qi(),n={connected:t(`acceptance.connected`),mapped:t(`acceptance.mapped`),refreshed:t(`acceptance.refreshed`),adapter_inspected:t(`acceptance.inspected`),run_recorded:t(`acceptance.recorded`),reward_judged:t(`acceptance.judged`),operator_approved:t(`acceptance.approved`),controller_ready:t(`acceptance.ready`),attention_queue:t(`acceptance.attentionSource`),agent_vision:t(`acceptance.visionSource`),todo_projection:t(`acceptance.todoSource`),current_run:t(`acceptance.runSource`)},r=e=>n[e]??t(`acceptance.unknown`),i=e.acceptanceObservation,a=e.loadState||!i||i.goal_id!==e.goalId||i.coverage===`unavailable`;return(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-acceptance`,"aria-label":t(`acceptance.title`),children:[(0,V.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,V.jsx)(`h3`,{children:t(`acceptance.title`)}),(0,V.jsx)(`em`,{children:t(`common.readOnly`)})]}),(0,V.jsx)(`p`,{role:`status`,children:t(a?`acceptance.unavailable`:`acceptance.partial`)}),!a&&i?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h4`,{children:t(`acceptance.gaps`)}),i.acceptance_gaps.length?i.acceptance_gaps.map((e,n)=>(0,V.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,V.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.owner`)}),(0,V.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,V.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.observed`)}),(0,V.jsx)(`dd`,{children:e.observed_at??t(`acceptance.unknown`)})]})]})]},`${e.kind}:${e.owner}:${n}`)):(0,V.jsx)(`p`,{children:t(`acceptance.noGaps`)}),(0,V.jsx)(`h4`,{children:t(`acceptance.guards`)}),i.guards.length?i.guards.map((e,n)=>(0,V.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,V.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.owner`)}),(0,V.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),e.blocks_agent?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.agent`)}),(0,V.jsx)(`dd`,{children:e.blocks_agent})]}):null,e.todo_id?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.task`)}),(0,V.jsx)(`dd`,{children:e.todo_id})]}):null,(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,V.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.scope`)}),(0,V.jsx)(`dd`,{children:e.decision_scope??t(`acceptance.unknown`)})]})]})]},`${e.todo_id}:${n}`)):(0,V.jsx)(`p`,{children:t(`acceptance.noGuards`)}),(0,V.jsx)(`h4`,{children:t(`acceptance.next`)}),(0,V.jsx)(`p`,{children:i.next_action??t(`acceptance.unknown`)}),(0,V.jsxs)(`details`,{children:[(0,V.jsxs)(`summary`,{children:[t(`acceptance.historical_progress`),` · `,i.historical_progress.length]}),(0,V.jsx)(`p`,{children:t(`acceptance.historical`)}),i.historical_progress.map(e=>(0,V.jsxs)(`p`,{children:[(0,V.jsx)(`strong`,{children:r(e.kind)}),` · `,e.observed_at??t(`acceptance.unknown`),` `,e.evidence_refs.join(`, `)]},e.kind))]}),i.missing_sources.length?(0,V.jsxs)(`p`,{children:[t(`acceptance.missing`),` `,i.missing_sources.map(r).join(`, `)]}):null,i.truncated?(0,V.jsx)(`p`,{children:t(`acceptance.truncated`)}):null]}):null]})}function Ly({item:e,successor:t,onSelect:n}){let{t:r}=qi(),i=e.details;return(0,V.jsxs)(`section`,{className:`personal-detail-card`,"aria-label":r(`attentionDetail.title`),children:[(0,V.jsx)(`h3`,{children:r(`attentionDetail.title`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.request`)}),(0,V.jsx)(`dd`,{children:r(i?.interaction===`decision`?`attentionDetail.decision`:`attentionDetail.unknownRequest`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`common.status`)}),(0,V.jsx)(`dd`,{children:r(`attentionDetail.${i?.lifecycle??`unknown`}`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`drawer.reason`)}),(0,V.jsx)(`dd`,{children:i?.reason??e.explanation??r(`attentionDetail.unknownReason`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Todo`}),(0,V.jsx)(`dd`,{children:e.todoId})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.targetTodo`)}),(0,V.jsx)(`dd`,{children:i?.unblocksTodoId??r(`attentionDetail.notProvided`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.targetAgent`)}),(0,V.jsx)(`dd`,{children:i?.blocksAgent??r(`attentionDetail.notProvided`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.scope`)}),(0,V.jsx)(`dd`,{children:i?.decisionScope?`${i.decisionScope.kind} · ${i.decisionScope.granularity} · ${i.decisionScope.scopeKey}`:r(`attentionDetail.notProvided`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`drawer.evidence`)}),(0,V.jsx)(`dd`,{children:i?.evidence??e.evidence??r(`drawer.decisionDefaultEvidence`)})]})]}),i?.supersededBy?(0,V.jsxs)(`p`,{children:[r(`attentionDetail.replacement`),`: `,i.supersededBy]}):null,t&&n?(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>n(t),type:`button`,children:r(`attentionDetail.openReplacement`)}):null,(0,V.jsx)(`p`,{children:r(`attentionDetail.boundary`)})]})}function Ry(e){return e.replace(/\s+/gu,` `).trim()}function zy(e,t){let n=RegExp(`(?:不要|不需要|无需|禁止|别|暂不|do not\\b|don't\\b|without\\b).{0,10}(?:${t.source})`,`iu`),r=RegExp(`(?:${t.source}).{0,10}(?:不要|不需要|无需|禁止|关闭)`,`iu`),i=RegExp(`disable\\b.{0,10}(?:${t.source})|(?:turn|switch|set)\\b.{0,10}(?:${t.source}).{0,10}\\boff\\b|(?:${t.source})\\s+(?:is\\s+)?disabled\\b`,`iu`);return n.test(e)||r.test(e)||i.test(e)}function By(e){return/(我现在该做什么|下一步|哪些\s*Goal\s*在等我|需要我|谁在等我|Agent\s*在做什么|当前进度|总结(?:今天)?进展)/iu.test(e)}function Vy(e){let t=/(怎么|如何|为什么|给.*建议|分析一下|解释|只读)/u.test(e),n=/(解决一下|修复一下|处理一下|执行一下|改一下|跑(?:一下)?测试|rebase|push|提交|推送)/iu.test(e);return!t&&n&&/(帮我|请|给我|直接|现在|开始|bytedcli|codebase|git|rebase|push|提交|推送)/iu.test(e)}function Hy(e){return Ry(e).toLowerCase().match(/(?:^|[\s,,;;:((:]|到|至)(?todo_done:todo_[a-z0-9_-]{3,64}|pr_merged:(?:(?:[a-z0-9_.-]{1,80})\/(?:[a-z0-9_.-]{1,100}))?#[1-9][0-9]{0,8}|capacity_available:[a-z][a-z0-9_:-]{0,63})(?=$|[\s,,。;;))])/iu)?.groups?.condition??null}function Uy(e,t){let n=Ry(e),r=[],i=t.agents.find(e=>{let t=n.toLowerCase();return t.includes(e.agentId.toLowerCase())||t.includes(e.label.toLowerCase())}),a=t.todos.find(e=>n.includes(e.todoId)||n.includes(e.text)),o=/(刚刚|已经|已)(?:经)?\s*(新增|创建|添加)(?:的)?\s*(todo|待办|任务)/iu.test(n),s=!!t.goalId&&!zy(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n);if(!t.goalId&&!zy(n,/goal|目标/iu)&&/(创建|新建|设置|create|start|set up).{0,24}(goal|目标)/iu.test(n)&&r.push({actionKind:`goal.create`,confidence:.97,normalizedParameters:{heartbeat_enabled:!zy(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n)}}),t.goalId&&s&&r.push({actionKind:`heartbeat.bind`,confidence:.96,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&!s&&!zy(n,/定时|监控|监测|持续观察|scheduled check|monitor/iu)&&/(定时|监控|监测|每.{0,8}(分钟|小时|天)|持续观察|scheduled check|monitor|every.{0,12}(minute|hour|day)|daily)/iu.test(n)&&r.push({actionKind:`monitor.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&i&&!zy(n,/绑定|负责|接管|管理/iu)&&/((让|交给).{0,20}(管理|负责|接管).{0,8}(goal|目标)|(绑定).{0,12}(goal|目标)|(goal|目标).{0,12}(交给|绑定|负责|接管))/iu.test(n)&&r.push({actionKind:`agent.bind`,confidence:.96,normalizedParameters:{agent_id:i.agentId,goal_id:t.goalId}}),t.goalId&&!o&&!zy(n,RegExp(`todo|待办|任务`,`iu`))&&/(创建|新建|新增|添加|加一个|记一个).{0,16}(todo|待办|任务)|(todo|待办|任务).{0,12}(创建|新建|新增|添加)|(?:create|add)(?:\s+(?:a|an|new))?\s+(?:todo|task)|(?:todo|task).{0,12}(?:create|add)/iu.test(n)&&r.push({actionKind:`todo.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&Vy(n)&&r.push({actionKind:`todo.create`,confidence:.9,normalizedParameters:{goal_id:t.goalId,start_execution:!0}}),t.goalId&&a){let e=!zy(n,/完成|做完|关闭/u)&&/完成|做完|关闭/u.test(n)?`complete`:!zy(n,/阻塞|卡住/u)&&/阻塞|卡住/u.test(n)?`block`:!zy(n,/暂缓|稍后|推迟/u)&&/暂缓|稍后|推迟/u.test(n)?`defer`:i&&!zy(n,/交给|分配给|改派/u)&&/交给|分配给|改派/u.test(n)?`reassign`:null;if(e){let i=e===`defer`?Hy(n):null;if(e===`defer`&&!i)return{actionKind:`todo.update`,confidence:.97,missingFields:[`resume_when`],normalizedParameters:{goal_id:t.goalId,operation:e,todo_id:a.todoId},route:`clarify`};r.push({actionKind:`todo.update`,confidence:.97,normalizedParameters:{goal_id:t.goalId,operation:e,...i?{resume_when:i}:{},todo_id:a.todoId}})}}let c=[...new Map(r.map(e=>[e.actionKind,e])).values()];return c.length>1?{actionKind:null,confidence:.4,missingFields:[`single_intent`],normalizedParameters:{},route:`clarify`}:c.length===1?{...c[0],missingFields:[],route:`typed_action`}:!t.goalId&&By(n)?{actionKind:null,confidence:.98,missingFields:[],normalizedParameters:{},route:`projection`}:{actionKind:null,confidence:.75,missingFields:[],normalizedParameters:{},route:`agent_chat`}}function Wy(e,t,n){if(!e)return{};if(!t.trim())return{modelConfig:null};let r={model:t.trim()};return n&&(r.reasoning_effort=n),{modelConfig:r}}var Gy=[`a[href]`,`button:not([disabled])`,`textarea:not([disabled])`,`select:not([disabled])`,`input:not([disabled])`,`[tabindex]:not([tabindex='-1'])`].join(`,`),Ky=[{key:`drawer.taskBlock`,operation:`block`},{key:`drawer.taskSuccessor`,operation:`successor_create`}],qy=[{key:`drawer.decisionReject`,resolution:`reject`},{key:`drawer.decisionDefer`,resolution:`defer`}],Jy=Array.from({length:32},(e,t)=>t+1),Yy=/^[a-z][a-z0-9_.-]{0,63}$/u;function Xy(e){let t=String(e??``).trim().toLowerCase();return Yy.test(t)?t:null}function Zy(e,t){return e.enabled===t.enabled&&e.maxChildren===t.maxChildren&&JSON.stringify(e.modelConfig??null)===JSON.stringify(t.modelConfig??null)&&[...e.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)===[...t.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)}function Qy({agents:e,attentionHistory:t=[],onSelectAttention:n,callbacks:r,goalNotifications:i=[],goals:a=[],inspectorExpanded:o=!1,larkConnections:s=[],onClose:c,onToggleInspectorSize:l,readOnly:u=!1,runs:d=[],selection:f}){let{locale:p,t:m}=qi(),[h,g]=(0,B.useState)(``),[_,v]=(0,B.useState)(!1),[y,b]=(0,B.useState)(`idle`),[x,S]=(0,B.useState)(`record`),[C,w]=(0,B.useState)([]),[T,E]=(0,B.useState)(null),[D,O]=(0,B.useState)(2),[ee,te]=(0,B.useState)(``),[ne,k]=(0,B.useState)(``),[A,j]=(0,B.useState)(`idle`),[M,N]=(0,B.useState)(null),[P,F]=(0,B.useState)(null),re=(0,B.useRef)(null),ie=(0,B.useRef)(null),[I,ae]=(0,B.useState)(e.find(e=>e.available)?.agentId??`codex`),[L,oe]=(0,B.useState)(``),se=(0,B.useRef)(null),ce=(0,B.useRef)(null),le=(0,B.useRef)(null),ue=(0,B.useRef)(null),de=f.kind===`run`?`run:${f.item.runId}`:f.kind===`proposal`?`proposal:${f.item.previewId}`:f.kind===`todo`?`todo:${f.item.todoId}`:f.kind===`attention`?`attention:${f.item.todoId}`:f.kind===`output`?`output:${f.item.outputId}`:f.kind===`schedule`?`schedule:${f.item.scheduleId}`:`goal:${f.item.goalId}`;(0,B.useEffect)(()=>{b(`idle`),v(!1),S(`record`),oe(``);let e=f.kind===`goal`?f.item.subagentExecution:void 0;w(e?.allowedDomains??[]),te(e?.modelConfig?.model??``),k(e?.modelConfig?.reasoning_effort??``),O(e?.maxChildren?Math.min(e.maxChildren,32):2),E(null),j(`idle`),N(null),F(null),re.current=e??null,ie.current=null},[de]);let R=f.kind===`goal`?f.item.subagentExecution:void 0;(0,B.useEffect)(()=>{let e=re.current,t=R?!e||!Zy(e,R):e!==null;if(re.current=R??null,!P){t&&R&&(w(R.allowedDomains),te(R.modelConfig?.model??``),k(R.modelConfig?.reasoning_effort??``),O(R.maxChildren||2),E(null),j(`idle`),N(null));return}let n=ie.current;(!R||Zy(P,R)||n&&!Zy(n,R))&&(R&&(w(R.allowedDomains),te(R.modelConfig?.model??``),k(R.modelConfig?.reasoning_effort??``),O(R.maxChildren||2)),ie.current=null,F(null))},[R,P]),(0,B.useEffect)(()=>{let e=document.activeElement;e instanceof HTMLElement&&!ce.current?.contains(e)&&(le.current=e);let t=window.requestAnimationFrame(()=>ue.current?.focus());return()=>window.cancelAnimationFrame(t)},[de]);let fe=(0,B.useCallback)(()=>{let e=le.current;c(),window.requestAnimationFrame(()=>e?.focus())},[c]);(0,B.useEffect)(()=>{function e(e){if(e.key===`Escape`){e.preventDefault(),fe();return}if(e.key===`Tab`&&f.kind!==`todo`){let t=Array.from(ce.current?.querySelectorAll(Gy)??[]).filter(e=>!e.hasAttribute(`disabled`)&&e.getAttribute(`aria-hidden`)!==`true`);if(t.length===0)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n.focus())}}return document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`keydown`,e)}},[fe,f.kind]);let pe=f.kind===`attention`?m(`drawer.titleAttention`):f.kind===`todo`?m(`drawer.taskDetails`):f.kind===`run`?m(`drawer.runDetails`):f.kind===`output`?m(`drawer.titleOutput`):f.kind===`proposal`?m(f.item.status===`applied`?`drawer.titleProposalApplied`:`drawer.titleProposalConfirm`):f.kind===`schedule`?f.item.scheduleKind===`heartbeat`?`Heartbeat`:m(`drawer.titleSchedule`):m(`drawer.goalDetails`),me=f.kind===`proposal`?f.item.goalId??`manager`:f.item.goalId,he=f.kind===`attention`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`todo`||f.kind===`run`?f.item.goalTitle:f.kind===`output`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`goal`?f.item.title:f.kind===`schedule`?m(`drawer.goalAutoRun`):f.item.goalId?m(`drawer.goalChanges`):m(`drawer.managerChanges`),ge=f.kind===`goal`?d.find(e=>e.goalId===f.item.goalId&&!!e.sessionId)??d.find(e=>e.goalId===f.item.goalId):null,_e=f.kind===`run`&&(f.item.completedSteps>0||!!f.item.latestActivity||!!f.item.outputs?.length),ve=f.kind===`attention`?Xi(f.item.updatedAt,m):null,ye=Hy(L);async function be(){f.kind!==`run`||!h.trim()||(await r.onCorrectRun?.(f.item,h.trim()),g(``))}async function xe(e,t,n,i){if(t===`successor_create`){await r.onPreviewAction?.({actionKind:`todo.create`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-successor-${e.todoId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,text:m(`drawer.taskSuccessorText`,{task:e.text})},summary:m(`drawer.taskSuccessorSummary`,{task:e.text})});return}await r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:e.claimedBy??I,goal_id:e.goalId,operation:t,...t===`block`?{note:m(`drawer.taskSuccessorNote`)}:{},...t===`defer`&&i?{resume_when:i}:{},todo_id:e.todoId},summary:`${n}:${e.text}`})}async function Se(e,t,n){u||!qd(e)||await r.onPreviewAction?.({actionKind:`gate.resolve`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-decision-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,decision:t,todo_id:e.todoId},summary:`${n}:${e.text}`})}let Ce=f.kind===`goal`?P??f.item.subagentExecution??{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0}:{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0},we=A===`previewing`||A===`applying`,Te=(()=>{if(f.kind!==`goal`)return[];let e=new Map;for(let t of Ce.allowedDomains){let n=Xy(t);n&&e.set(n,{matchingTodoCount:0,value:n})}if(Ce.domainCandidates)for(let t of Ce.domainCandidates){let n=Xy(t.domain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+t.matchingTodoCount,value:n})}else for(let t of f.item.agentTodos){if(t.done||t.taskClass!==`advancement_task`)continue;let n=Xy(t.taskDomain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+1,value:n})}return[...e.values()]})();function z(){w(Ce.allowedDomains),te(Ce.modelConfig?.model??``),k(Ce.modelConfig?.reasoning_effort??``),O(Ce.maxChildren||2),E(null),j(`idle`),N(null)}function Ee(){let e=[...new Set(C.map(e=>Xy(e)))];return e.every(e=>!!e)?e:null}function De(e,t){w(n=>t?[...n,e].filter((e,t,n)=>n.indexOf(e)===t):n.filter(t=>t!==e)),N(null),j(`idle`),E(null)}async function Oe(e,t=e){if(f.kind!==`goal`||!r.onPreviewGoalSubagentConfiguration)return;let n=e?Ee():[];if(t&&!ee.trim()&&ne){j(`error`),E(m(`drawer.subagentModelRequired`));return}if(e&&!n){j(`error`),E(m(`drawer.subagentDomainInvalid`)),N(null);return}let i={allowedDomains:n??[],enabled:e,goalId:f.item.goalId,maxChildren:e?D:0,...Wy(t,ee,ne)};j(`previewing`),E(m(`drawer.subagentPreviewing`)),N(null);try{let e=await r.onPreviewGoalSubagentConfiguration(i);if(!e.changed){ie.current=R??null,F({...e.configuration,domainCandidates:Ce.domainCandidates}),w(e.configuration.allowedDomains),te(e.configuration.modelConfig?.model??``),k(e.configuration.modelConfig?.reasoning_effort??``),O(e.configuration.maxChildren||2),j(`success`),E(m(`drawer.subagentNoChange`));return}N({...i,changed:e.changed,previewId:e.previewId}),j(`ready`),E(m(`drawer.subagentPreviewReady`))}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentPreviewFailed`))}}async function ke(){if(!(!M||!r.onApplyGoalSubagentConfiguration)){j(`applying`),E(m(`drawer.subagentApplying`));try{let e=await r.onApplyGoalSubagentConfiguration({allowedDomains:M.allowedDomains,enabled:M.enabled,goalId:M.goalId,maxChildren:M.maxChildren,modelConfig:M.modelConfig,previewId:M.previewId});ie.current=R??null,F({...e,domainCandidates:Ce.domainCandidates}),w(e.allowedDomains),te(e.modelConfig?.model??``),k(e.modelConfig?.reasoning_effort??``),O(e.maxChildren||2),j(`success`),E(m(`drawer.subagentApplied`)),N(null);try{await r.onRefresh?.()}catch{j(`warning`),E(m(`drawer.subagentAppliedRefreshFailed`))}}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentApplyFailed`))}}}return(0,V.jsxs)(`div`,{"aria-labelledby":`personal-drawer-title`,"aria-modal":f.kind===`todo`?void 0:`true`,className:`personal-context-drawer`,"data-context-kind":f.kind,ref:ce,role:`dialog`,children:[(0,V.jsxs)(`header`,{className:`personal-drawer-header${f.kind===`todo`?` is-task-inspector`:``}`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`h2`,{id:`personal-drawer-title`,ref:ue,tabIndex:-1,children:pe}),(0,V.jsx)(`p`,{children:he})]}),(0,V.jsxs)(`div`,{className:`personal-drawer-header-actions`,children:[f.kind===`todo`&&l?(0,V.jsx)(`button`,{"aria-label":m(o?`drawer.inspectorHalf`:`drawer.inspectorFull`),className:`personal-icon-button personal-inspector-size`,onClick:l,title:m(o?`drawer.inspectorHalfView`:`drawer.inspectorFullView`),type:`button`,children:o?(0,V.jsx)(Om,{size:17}):(0,V.jsx)(wm,{size:17})}):null,(0,V.jsxs)(`button`,{"aria-label":m(`drawer.closeDetail`,{context:he}),className:`personal-icon-button personal-drawer-close`,onClick:fe,ref:se,type:`button`,children:[(0,V.jsx)(Gp,{className:`personal-mobile-back`,size:18}),(0,V.jsx)($m,{className:`personal-desktop-close`,size:18})]})]})]}),(0,V.jsxs)(`div`,{className:`personal-drawer-body`,children:[f.kind===`attention`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card is-attention`,children:[(0,V.jsx)(`small`,{children:f.item.blocking?m(`drawer.attentionBlocking`):m(`drawer.attentionWaiting`)}),(0,V.jsx)(`h3`,{children:f.item.text}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,V.jsx)(`dd`,{children:f.item.priority??`medium`})]}),ve?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`common.waiting`)}),(0,V.jsx)(`dd`,{children:m(`tasks.waitingAge`,{age:ve})})]}):null]})]}),(0,V.jsx)(Ly,{item:f.item,onSelect:n,successor:Kd(f.item,t)}),!u&&qd(f.item)?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void Se(f.item,`approve`,m(`common.confirm`)),type:`button`,children:[(0,V.jsx)(em,{size:17}),m(`drawer.decisionReview`)]}),(0,V.jsxs)(`details`,{className:`personal-compact-menu`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(dm,{size:17}),m(`drawer.decisionMore`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`button`,{onClick:()=>void r.onExplainDecision?.(f.item),type:`button`,children:[(0,V.jsx)(Em,{size:16}),m(`drawer.explainDecision`)]}),qy.map(e=>(0,V.jsx)(`button`,{onClick:()=>void Se(f.item,e.resolution,m(e.key)),type:`button`,children:m(e.key)},e.resolution))]})]})]}):null]}):null,f.kind===`todo`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-task-inspector-summary`,children:[(0,V.jsxs)(`div`,{className:`personal-task-inspector-status`,children:[(0,V.jsxs)(`span`,{className:f.item.done?`is-done`:f.item.status===`blocked`?`is-blocked`:`is-open`,children:[(0,V.jsx)(`i`,{}),f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)]}),f.item.priority?(0,V.jsx)(`span`,{children:f.item.priority}):null,(0,V.jsx)(`span`,{children:f.item.taskClass===`advancement_task`?m(`drawer.taskAdvancement`):f.item.taskClass??m(`drawer.taskOrdinary`)})]}),(0,V.jsx)(`h3`,{children:f.item.text})]}),(0,V.jsxs)(`section`,{"aria-label":m(`drawer.taskInfo`),className:`personal-task-inspector-fields`,children:[(0,V.jsx)(`h4`,{children:m(`drawer.taskInfo`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`common.owner`)}),(0,V.jsx)(`dd`,{children:f.item.ownerLabel??f.item.claimedBy??m(`drawer.notAssigned`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`common.status`)}),(0,V.jsx)(`dd`,{children:f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,V.jsx)(`dd`,{children:f.item.priority??m(`drawer.notSet`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.dependencies`)}),(0,V.jsx)(`dd`,{children:f.item.dependencies?.join(` · `)||m(`common.none`)})]}),f.item.status===`deferred`?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.resumeWhen`)}),(0,V.jsx)(`dd`,{children:f.item.resumeWhen||m(`drawer.notSet`)})]}):null,(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.nextTransition`)}),(0,V.jsx)(`dd`,{children:f.item.nextTransition??(f.item.done?m(`drawer.taskNextCompleted`):f.item.status===`deferred`?m(`drawer.taskNextDeferred`):m(`drawer.taskNextOpen`))})]})]})]}),!u&&!f.item.done?(0,V.jsxs)(`div`,{className:`personal-task-inspector-actions`,"aria-label":m(`drawer.taskActions`),children:[(0,V.jsxs)(`details`,{className:`personal-task-management`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(dm,{size:16}),m(`drawer.taskManage`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.reassign`)}),(0,V.jsxs)(`label`,{className:`personal-inline-agent-select`,children:[m(`drawer.reassign`),(0,V.jsx)(`select`,{"aria-label":m(`drawer.reassign`),onChange:e=>ae(e.target.value),value:I,children:e.filter(e=>e.available).map(e=>(0,V.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:f.item.goalId,kind:`todo`,todo_id:f.item.todoId},idempotencyKey:`workspace-todo-${f.item.todoId}-reassign-${I}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:I,goal_id:f.item.goalId,operation:`reassign`,todo_id:f.item.todoId},summary:m(`drawer.reassignSummary`,{task:f.item.text})}),type:`button`,children:m(`timeline.review`)})]}),(0,V.jsx)(`strong`,{children:m(`drawer.taskDeferUntil`)}),(0,V.jsxs)(`label`,{className:`personal-inline-agent-select personal-inline-resume-when`,children:[m(`drawer.taskDeferUntil`),(0,V.jsx)(`input`,{"aria-label":m(`drawer.taskDeferCondition`),"aria-invalid":!!L.trim()&&!ye,onChange:e=>oe(e.target.value),placeholder:m(`drawer.taskDeferPlaceholder`),value:L}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:!ye,onClick:()=>void xe(f.item,`defer`,m(`drawer.taskDefer`),ye??void 0),type:`button`,children:m(`drawer.taskDeferReview`)}),(0,V.jsx)(`small`,{children:L.trim()&&!ye?m(`drawer.taskDeferInvalid`):m(`drawer.taskDeferSupported`)})]}),(0,V.jsx)(`div`,{className:`personal-task-management-secondary`,children:Ky.map(e=>(0,V.jsx)(`button`,{onClick:()=>void xe(f.item,e.operation,m(e.key)),type:`button`,children:m(e.key)},e.operation))})]})]}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void xe(f.item,`complete`,m(`drawer.taskComplete`)),type:`button`,children:[(0,V.jsx)(em,{size:17}),m(`drawer.taskComplete`)]})]}):null,f.item.done?(0,V.jsxs)(`div`,{className:`personal-task-completed-note`,children:[(0,V.jsx)(em,{size:16}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.taskCompletedTitle`)}),(0,V.jsx)(`small`,{children:m(`drawer.taskCompletedNote`)})]})]}):null]}):null,f.kind===`goal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsx)(`small`,{children:Ji(f.item.state,p)}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.agentSentence}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.tokens`)}),(0,V.jsxs)(`dd`,{children:[yy(f.item.usage?.tokens24h,m(`drawer.usageNotMeasured`),gy),` / `,yy(f.item.usage?.tokens7d,m(`drawer.usageNotMeasured`),gy)]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.cost`)}),(0,V.jsxs)(`dd`,{children:[yy(f.item.usage?.costUsd24h,m(`drawer.usageNotMeasured`),_y),` / `,yy(f.item.usage?.costUsd7d,m(`drawer.usageNotMeasured`),_y)]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.duration`)}),(0,V.jsxs)(`dd`,{children:[yy(f.item.usage?.durationMs24h,m(`drawer.usageNotMeasured`),vy),` / `,yy(f.item.usage?.durationMs7d,m(`drawer.usageNotMeasured`),vy)]})]})]})]}),(0,V.jsx)(Iy,{goal:f.item}),(()=>{let e=i.find(e=>e.goalId===f.item.goalId),t=s.find(e=>e.goal_id===f.item.goalId);return(0,V.jsxs)(V.Fragment,{children:[f.item.repository?(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-repository`,children:[(0,V.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,V.jsx)(`small`,{children:m(`drawer.repository`)}),(0,V.jsx)(`em`,{children:m(`common.readOnly`)})]}),(0,V.jsxs)(`h3`,{children:[(0,V.jsx)(_m,{size:16}),f.item.repository.label]}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.branch`)}),(0,V.jsx)(`dd`,{children:f.item.repository.branch||`detached`})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Role`}),(0,V.jsx)(`dd`,{children:m(`drawer.repositoryRole`)})]})]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>{let e=navigator.clipboard?.writeText(f.item.repository?.identity??``);if(!e){b(`error`);return}e.then(()=>b(`copied`)).catch(()=>b(`error`))},type:`button`,children:[(0,V.jsx)(cm,{size:15}),m(y===`copied`?`drawer.copyRepositoryDone`:`drawer.copyRepository`)]}),y===`error`?(0,V.jsx)(`p`,{className:`personal-copy-feedback is-error`,role:`status`,children:m(`drawer.copyRepositoryError`)}):y===`copied`?(0,V.jsx)(`p`,{className:`personal-copy-feedback`,role:`status`,children:m(`drawer.copyRepositorySuccess`)}):null]}):null,u?(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,V.jsx)(`small`,{children:m(`drawer.larkConnection`)}),(0,V.jsx)(`h3`,{children:m(`drawer.remoteDetailsUnavailable`)}),(0,V.jsx)(`p`,{children:m(`drawer.remoteDetailsDescription`)})]}):(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,V.jsx)(`small`,{children:m(`drawer.larkConnection`)}),t?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`h3`,{children:[t.app_label,(0,V.jsx)(`span`,{className:`personal-connection-status`,children:m(`drawer.connected`)})]}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.group`)}),(0,V.jsx)(`dd`,{children:t.chat_name})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.topic`)}),(0,V.jsxs)(`dd`,{children:[`# `,t.topic_name]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.trigger`)}),(0,V.jsx)(`dd`,{children:t.incoming_mode===`mentions`?m(`lark.someoneMentions`):m(`lark.allMessages`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.replyMode`)}),(0,V.jsx)(`dd`,{children:m(`lark.topicReply`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.autoNotify`)}),(0,V.jsx)(`dd`,{children:e?.humanGateAutoNotifyEnabled?m(`common.on`):m(`common.off`)})]}),e?.lastNotifiedAt?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.lastNotification`)}),(0,V.jsx)(`dd`,{children:e.lastNotifiedAt})]}):null]})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h3`,{children:m(`drawer.larkNotConfigured`)}),(0,V.jsx)(`p`,{children:m(`drawer.larkNotConfiguredDescription`)})]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onOpenNotificationSettings?.(f.item.goalId),type:`button`,children:[(0,V.jsx)(Xp,{size:16}),m(t?`drawer.larkConfigure`:`drawer.larkConnect`)]})]})]})})(),(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-session`,children:[(0,V.jsx)(`small`,{children:m(`drawer.runDetails`)}),ge?.sessionId?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h3`,{children:Yi(ge.sessionStatus??ge.status,m)}),(0,V.jsx)(`p`,{children:ge.title}),r.onOpenRunSession?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onOpenRunSession?.(ge),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.runLatest`)]}):null]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h3`,{children:m(`drawer.noRun`)}),(0,V.jsx)(`p`,{children:m(`drawer.noRunDescription`)})]})]}),u?null:(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`heartbeat`,f.item.goalId),type:`button`,children:[(0,V.jsx)(Fm,{size:16}),m(`drawer.setupHeartbeat`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`monitor`,f.item.goalId),type:`button`,children:[(0,V.jsx)($p,{size:16}),m(`drawer.scheduleAdd`)]})]}),f.item.subagentExecution?(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-subagents`,children:[(0,V.jsxs)(`div`,{className:`personal-subagent-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:m(`drawer.subagentLabel`)}),(0,V.jsxs)(`h3`,{children:[(0,V.jsx)(Zp,{size:16}),m(`drawer.subagentTitle`)]})]}),(0,V.jsxs)(`button`,{"aria-checked":Ce.enabled,"aria-label":m(M&&A===`ready`?`drawer.subagentPending`:Ce.enabled?`drawer.subagentDisable`:`drawer.subagentEnable`),className:`personal-subagent-switch`,"data-pending":M&&A===`ready`?`true`:void 0,disabled:u||we||!!M||!r.onPreviewGoalSubagentConfiguration,onClick:()=>void Oe(!Ce.enabled),role:`switch`,type:`button`,children:[(0,V.jsx)(`span`,{}),m(M&&A===`ready`?`drawer.subagentPending`:Ce.enabled?`common.on`:`common.off`)]})]}),(0,V.jsx)(`p`,{children:m(`drawer.subagentDescription`)}),M&&A===`ready`?(0,V.jsxs)(`div`,{className:`personal-subagent-preview`,children:[(0,V.jsx)(`strong`,{children:m(M.enabled?`drawer.subagentConfirmEnable`:`drawer.subagentConfirmDisable`)}),(0,V.jsx)(`p`,{children:M.enabled?m(`drawer.subagentPreviewSummary`,{count:M.maxChildren,domains:M.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)}):m(`drawer.subagentDisableSummary`)}),M.modelConfig===void 0?null:(0,V.jsxs)(`p`,{children:[m(`drawer.subagentModel`),`: `,M.modelConfig?.model||m(`drawer.subagentModelDefault`),` · `,M.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`button`,{className:`personal-primary-action`,onClick:()=>void ke(),type:`button`,children:m(`common.confirm`)}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:z,type:`button`,children:m(`common.cancel`)})]})]}):null,T?(0,V.jsxs)(`p`,{className:`personal-subagent-feedback is-${A}`,role:`status`,children:[A===`previewing`||A===`applying`?(0,V.jsx)(Lm,{className:`personal-spin`,size:13}):null,T]}):null,(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentModel`)}),(0,V.jsx)(`dd`,{children:Ce.modelConfig?.model||m(`drawer.subagentModelDefault`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentEffort`)}),(0,V.jsx)(`dd`,{children:Ce.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentCurrentBoundary`)}),(0,V.jsx)(`dd`,{children:Ce.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentChildLimit`)}),(0,V.jsx)(`dd`,{children:Ce.maxChildren||0})]})]}),u?(0,V.jsx)(`p`,{className:`personal-subagent-read-only`,children:m(`drawer.subagentRemoteReadOnly`)}):(0,V.jsxs)(`div`,{className:`personal-subagent-fields`,children:[(0,V.jsxs)(`fieldset`,{className:`personal-subagent-domain-picker`,disabled:we,children:[(0,V.jsx)(`legend`,{children:m(`drawer.subagentDomains`)}),Te.length>0?(0,V.jsx)(`div`,{className:`personal-subagent-domain-options`,children:Te.map(e=>{let t=C.includes(e.value);return(0,V.jsxs)(`label`,{className:`personal-subagent-domain-option${t?` is-selected`:``}`,children:[(0,V.jsx)(`input`,{"aria-label":e.value,checked:t,onChange:t=>De(e.value,t.target.checked),type:`checkbox`}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.value}),(0,V.jsx)(`small`,{children:m(`drawer.subagentDomainTodoCount`,{count:e.matchingTodoCount})})]})]},e.value)})}):(0,V.jsx)(`p`,{className:`personal-subagent-domain-empty`,children:m(`drawer.subagentDomainsEmpty`)}),(0,V.jsx)(`small`,{children:m(`drawer.subagentDomainsHint`)})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:m(`drawer.subagentModel`)}),(0,V.jsx)(`input`,{"aria-label":m(`drawer.subagentModel`),disabled:we,value:ee,placeholder:`gpt-5.6-luna`,onChange:e=>{te(e.target.value),N(null),j(`idle`),E(null)}})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:m(`drawer.subagentEffort`)}),(0,V.jsxs)(`select`,{"aria-label":m(`drawer.subagentEffort`),disabled:we,value:ne,onChange:e=>{k(e.target.value),N(null),j(`idle`),E(null)},children:[(0,V.jsx)(`option`,{value:``,children:m(`drawer.subagentModelDefault`)}),[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`].map(e=>(0,V.jsx)(`option`,{value:e,children:e},e))]})]}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:we,type:`button`,onClick:()=>{te(`gpt-5.6-luna`),k(`max`),N(null),j(`idle`),E(null)},children:m(`drawer.subagentLunaPreset`)}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:we,type:`button`,onClick:()=>{te(``),k(``),N(null),j(`idle`),E(null)},children:m(`drawer.subagentClearModel`)}),(0,V.jsx)(`p`,{children:m(`drawer.subagentModelHint`)}),(0,V.jsxs)(`label`,{className:`personal-subagent-limit-field`,children:[(0,V.jsx)(`span`,{children:m(`drawer.subagentMaxChildren`)}),(0,V.jsx)(`select`,{"aria-label":m(`drawer.subagentMaxChildren`),disabled:we,onChange:e=>{O(Number(e.target.value)),N(null),j(`idle`),E(null)},value:D,children:Jy.map(e=>(0,V.jsx)(`option`,{value:e,children:e},e))})]}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:we,onClick:()=>void Oe(Ce.enabled,!0),type:`button`,children:m(`drawer.subagentPreviewBoundary`)})]})]}):null]}):null,f.kind===`run`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`div`,{"aria-label":m(`drawer.runView`),className:`personal-run-drawer-tabs`,role:`tablist`,children:[(0,V.jsx)(`button`,{"aria-selected":x===`record`,onClick:()=>S(`record`),role:`tab`,type:`button`,children:m(`drawer.executionRecordAndResult`)}),(0,V.jsx)(`button`,{"aria-selected":x===`details`,onClick:()=>S(`details`),role:`tab`,type:`button`,children:m(`drawer.detailsAndActions`)})]}),x===`record`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card personal-session-summary`,children:[(0,V.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Yi(f.item.sessionStatus??f.item.status,m)]}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.latestActivity}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,V.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]})]})]}),(0,V.jsxs)(`section`,{"aria-label":m(`drawer.executionRecord`),className:`personal-session-message-record`,children:[(0,V.jsx)(`h3`,{children:m(`drawer.executionRecord`)}),f.item.sessionMessages?.length?(0,V.jsx)(`ol`,{children:f.item.sessionMessages.map(e=>(0,V.jsxs)(`li`,{className:`is-${e.role}`,children:[(0,V.jsx)(`i`,{}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:e.role===`user`?m(`drawer.runRoleUser`):e.role===`assistant`?m(`drawer.runRoleAssistant`):m(`drawer.runRoleSystem`)}),e.createdAt?(0,V.jsx)(`time`,{children:new Date(e.createdAt).toLocaleTimeString(p,{hour:`2-digit`,minute:`2-digit`,hour12:!1})}):null]}),(0,V.jsx)(`p`,{children:e.text})]})]},e.messageId))}):(0,V.jsx)(`p`,{className:`personal-session-empty`,children:_e?m(`drawer.runRecordProjected`,{completed:f.item.completedSteps,outputs:f.item.outputs?.length?m(`drawer.runRecordProjectedOutputs`,{count:f.item.outputs.length}):``,total:f.item.totalSteps}):m(`drawer.runRecordEmpty`)}),f.item.status===`running`?(0,V.jsxs)(`div`,{className:`personal-session-active-step`,children:[(0,V.jsx)(`i`,{}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.analysis`)}),(0,V.jsx)(`small`,{children:m(`drawer.agentWorking`)})]})]}):null]}),f.item.outputs?.length?(0,V.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-run-outputs-title`,children:[(0,V.jsx)(`h3`,{id:`personal-run-outputs-title`,children:m(`drawer.outputs`)}),(0,V.jsx)(`ol`,{children:f.item.outputs.map(e=>(0,V.jsx)(`li`,{children:(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.title}),(0,V.jsx)(`small`,{children:e.createdAt??e.kind??m(`files.emptySummary`)})]})},e.outputId))})]}):null]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Yi(f.item.status,m)]}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.latestActivity}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,V.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.sessionStatus`)}),(0,V.jsx)(`dd`,{children:Yi(f.item.sessionStatus??f.item.status,m)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.sessionRecoverable`)}),(0,V.jsx)(`dd`,{children:f.item.resumable===!1?m(`drawer.resumeNo`):m(`drawer.resumeYes`)})]})]})]}),f.item.sessionStatus===`resume_failed`&&!u?(0,V.jsxs)(`section`,{className:`personal-recovery-panel`,"aria-label":m(`drawer.recoveryFailed`),children:[(0,V.jsx)(`strong`,{children:m(`drawer.recoveryFailed`)}),(0,V.jsx)(`p`,{children:m(`drawer.recoveryDescription`)}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,V.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.recoveryNewSession`)]})]}):null,u?null:(0,V.jsxs)(`section`,{className:`personal-correction-panel`,children:[(0,V.jsx)(`header`,{children:(0,V.jsxs)(`span`,{children:[(0,V.jsx)(Zp,{size:16}),m(`drawer.correctionLabel`,{agent:f.item.agentLabel})]})}),(0,V.jsx)(`p`,{children:m(`drawer.correctionDescription`)}),(0,V.jsxs)(`div`,{className:`personal-correction-composer`,children:[(0,V.jsx)(`textarea`,{"aria-label":m(`drawer.correctionTextarea`,{agent:f.item.agentLabel,goal:f.item.goalTitle,run:f.item.title}),onChange:e=>g(e.target.value),placeholder:m(`drawer.correctionPlaceholder`),rows:3,value:h}),(0,V.jsx)(`button`,{"aria-label":m(`drawer.correctionSend`),disabled:!h.trim(),onClick:()=>void be(),type:`button`,children:(0,V.jsx)(Bm,{size:16})})]})]}),u?null:(0,V.jsxs)(`details`,{className:`personal-compact-menu personal-run-more`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(dm,{size:17}),m(`drawer.moreRunActions`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`button`,{disabled:!f.item.canInterrupt,onClick:()=>void r.onInterruptRun?.(f.item),type:`button`,children:[(0,V.jsx)(Mm,{size:16}),m(`drawer.runInterrupt`)]}),(0,V.jsxs)(`button`,{disabled:f.item.resumable===!1,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,V.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,V.jsxs)(`button`,{onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.runNewSession`)]}),(0,V.jsxs)(`button`,{onClick:()=>void r.onCloseRunSession?.(f.item),type:`button`,children:[(0,V.jsx)(qm,{size:16}),m(`drawer.runCloseSession`)]})]})]})]})]}):null,f.kind===`output`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsx)(`small`,{children:f.item.kind??`output`}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.summary??m(`drawer.outputRecorded`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.outputTodo`)}),(0,V.jsx)(`dd`,{children:f.item.todoId??m(`drawer.notLinked`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.outputRun`)}),(0,V.jsx)(`dd`,{children:f.item.runId??m(`drawer.notLinked`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Agent`}),(0,V.jsx)(`dd`,{children:f.item.agentLabel??f.item.agentId??`LoopX`})]})]})]}),f.item.report?(0,V.jsxs)(`section`,{className:`personal-report-detail`,"data-testid":`personal-periodic-report-detail`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsxs)(`strong`,{children:[`+`,f.item.report.addedCount]}),m(`files.reportAdded`)]}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:f.item.report.changedCount}),m(`files.reportChanged`)]})]}),(0,V.jsxs)(`p`,{children:[f.item.report.periodStartAt,` → `,f.item.report.periodEndAt]}),(0,V.jsx)(`ol`,{children:f.item.report.items.map(e=>(0,V.jsxs)(`li`,{"data-change-kind":e.changeKind,children:[(0,V.jsxs)(`small`,{children:[e.changeKind,` · `,e.status]}),(0,V.jsx)(`strong`,{children:e.title}),(0,V.jsx)(`p`,{children:e.summary})]},e.sourceRef))}),(0,V.jsxs)(`footer`,{children:[(0,V.jsxs)(`span`,{children:[m(`files.reportPublication`),`: `,f.item.report.publicationId]}),(0,V.jsxs)(`span`,{children:[m(`files.reportGeneration`),`: `,f.item.report.generationId]})]})]}):null,f.item.safePreview?(0,V.jsx)(`pre`,{"aria-label":m(`drawer.outputSafePreview`),className:`personal-safe-preview`,children:f.item.safePreview}):(0,V.jsx)(`p`,{className:`personal-preview-unavailable`,children:m(`drawer.previewUnavailable`)}),(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:!r.onOpenOutput,onClick:()=>{r.onOpenOutput?.(f.item),c()},type:`button`,children:[(0,V.jsx)(fm,{size:16}),m(`files.openConversation`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!r.onExportOutput,onClick:()=>void r.onExportOutput?.(f.item),type:`button`,children:[(0,V.jsx)(um,{size:16}),m(`files.exportSummary`)]})]})]}):null,f.kind===`proposal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-proposal-card`,children:[(0,V.jsxs)(`small`,{children:[f.item.actionKind,` · `,f.item.status]}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.impact}),f.item.reviewPlan?(0,V.jsx)(`p`,{className:`personal-proposal-explainer`,"data-action-review":f.item.reviewPlan.interaction,children:m(`actionReview.${f.item.reviewPlan.reason}`)}):null,f.item.status===`ready`?(0,V.jsx)(`p`,{className:`personal-proposal-explainer`,children:m(`drawer.proposalExplainer`)}):null,(0,V.jsx)(`dl`,{children:f.item.fields.map(e=>(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:e.label}),(0,V.jsx)(`dd`,{children:e.value})]},e.key))})]}),f.item.status===`applied`?(0,V.jsxs)(`p`,{className:`personal-proposal-state is-applied`,children:[(0,V.jsx)(em,{size:16}),m(`drawer.proposalApplied`)]}):null,f.item.status===`applied`&&f.item.goalId?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>{let e=f.item.goalId;c(),r.onOpenGoal?.(e)},type:`button`,children:[(0,V.jsx)(fm,{size:16}),f.item.actionKind===`goal.create`?m(`drawer.proposalEnterGoal`):m(`drawer.proposalViewGoal`)]}):null,f.item.status===`stale`?(0,V.jsx)(`p`,{className:`personal-proposal-state is-stale`,children:m(`drawer.proposalStale`)}):null,f.item.status===`error`?(0,V.jsxs)(`div`,{className:`personal-proposal-state is-error`,children:[(0,V.jsx)(`span`,{children:f.item.reviewPlan?.reason===`readback_unverified`?m(`actionReview.readback_unverified`):m(`drawer.proposalApplyFailed`)}),f.item.errorMessage?(0,V.jsx)(`small`,{children:f.item.errorMessage}):null,(0,V.jsx)(`small`,{children:m(`drawer.proposalApplyFailedHint`)})]}):null,f.item.status===`rejected`?(0,V.jsx)(`p`,{className:`personal-proposal-state is-error`,children:m(`drawer.proposalRejected`)}):null,f.item.status===`deferred`?(0,V.jsx)(`p`,{className:`personal-proposal-state is-gated`,children:m(`drawer.proposalDeferred`)}):null,f.item.status===`gated`?(0,V.jsxs)(`div`,{className:`personal-proposal-state is-gated`,children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.gateRequiresHost`)}),m(`drawer.gateRequiresHostDescription`)]}),f.item.gate?.nextAction?(0,V.jsx)(`small`,{children:f.item.gate.nextAction}):null]}):null,f.item.status===`gated`&&f.item.actionKind===`gate.resolve`?(()=>{let e=e=>f.item.fields.find(t=>t.key===e)?.value,t=e(`goal_id`),n=e(`todo_id`);return!t||!n?null:(0,V.jsxs)(`section`,{className:`personal-detail-card personal-gate-cli-hint`,children:[(0,V.jsx)(`small`,{children:m(`drawer.gateApproveHint`)}),(0,V.jsxs)(`code`,{children:[`loopx todo complete --goal-id `,t,` --todo-id `,n,` --decision-outcome approve`]}),(0,V.jsx)(`small`,{children:m(`drawer.gateRejectHint`)})]})})():null,!u&&f.item.workspaceCandidates?.length?(0,V.jsx)(`div`,{className:`personal-workspace-candidates`,"aria-label":m(`drawer.workspaceCandidates`),children:f.item.workspaceCandidates.map(e=>(0,V.jsxs)(`button`,{onClick:()=>void r.onSelectWorkspaceCandidate?.(f.item,e.workspaceRef),type:`button`,children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsx)(`small`,{children:e.workspaceRef})]},e.workspaceRef))}):null,!u&&f.item.status===`error`?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,V.jsx)(Lm,{size:17}),m(`drawer.proposalRegenerate`)]}):!u&&f.item.status!==`gated`?(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:![`ready`,`deferred`].includes(f.item.status)||f.item.reviewPlan?.canApply===!1,onClick:()=>void r.onApplyProposal?.(f.item),type:`button`,children:[(0,V.jsx)(em,{size:17}),f.item.status===`applying`?m(`drawer.applying`):f.item.primaryLabel??m(`drawer.apply`)]}):null,!u&&([`stale`,`gated`,`rejected`].includes(f.item.status)||f.item.status===`ready`&&f.item.reviewPlan?.canApply===!1)?(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,V.jsx)(Lm,{size:16}),m(`drawer.proposalRecheck`)]}):null,!u&&[`ready`,`gated`].includes(f.item.status)?(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`defer`),type:`button`,children:m(`drawer.proposalDefer`)}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`reject`),type:`button`,children:m(`drawer.decisionReject`)})]}):null,[`applied`,`applying`].includes(f.item.status)?null:(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:c,type:`button`,children:m(`drawer.proposalClose`)})]}):null,f.kind===`schedule`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsxs)(`small`,{children:[f.item.scheduleKind===`heartbeat`?`Goal Heartbeat`:`continuous_monitor`,` · `,f.item.status??`active`]}),(0,V.jsx)(`h3`,{children:f.item.label}),(0,V.jsx)(`p`,{children:f.item.target??f.item.schedule??m(`drawer.scheduleDefaultTarget`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleTimezone`)}),(0,V.jsx)(`dd`,{children:f.item.timezone??m(`drawer.scheduleLocalTimezone`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleNext`)}),(0,V.jsx)(`dd`,{children:f.item.nextRunAt??m(`drawer.schedulePending`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleLast`)}),(0,V.jsx)(`dd`,{children:f.item.previousRunAt??m(`drawer.scheduleNeverRun`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleNotification`)}),(0,V.jsx)(`dd`,{children:f.item.notificationRule??m(`drawer.scheduleDefaultNotification`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleStopCondition`)}),(0,V.jsx)(`dd`,{children:f.item.stopCondition??m(`drawer.scheduleDefaultStop`)})]})]})]}),!u&&f.item.scheduleKind===`monitor`?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`run_now`),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.scheduleRunNow`)]}):null,u?null:(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,f.item.status===`paused`?`resume`:`pause`),type:`button`,children:[f.item.status===`paused`?(0,V.jsx)(Nm,{size:16}):(0,V.jsx)(Mm,{size:16}),f.item.status===`paused`?m(`drawer.scheduleResume`):m(`drawer.schedulePause`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`edit`),type:`button`,children:[(0,V.jsx)($p,{size:16}),m(`drawer.scheduleEdit`)]})]}),u?null:(0,V.jsxs)(`button`,{className:`personal-danger-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`stop`),type:`button`,children:[(0,V.jsx)(qm,{size:16}),m(`drawer.scheduleStop`,{kind:f.item.scheduleKind===`heartbeat`?` Heartbeat`:m(`drawer.titleSchedule`)})]}),(0,V.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-execution-history-title`,children:[(0,V.jsx)(`h3`,{id:`personal-execution-history-title`,children:m(`drawer.executionHistory`)}),f.item.executionHistory?.length?(0,V.jsx)(`ol`,{children:f.item.executionHistory.map((e,t)=>(0,V.jsxs)(`li`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsx)(`small`,{children:e.timestamp})]}),(0,V.jsx)(`em`,{className:`is-${e.status}`,children:e.status})]},`${e.timestamp}:${e.runId??t}`))}):(0,V.jsx)(`p`,{children:m(`drawer.noExecutionHistory`)})]})]}):null,f.kind===`run`||f.kind===`proposal`||f.kind===`schedule`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`button`,{"aria-expanded":_,className:`personal-diagnostics-trigger`,onClick:()=>v(e=>!e),type:`button`,children:[(0,V.jsx)(`span`,{children:m(`drawer.advancedDiagnostics`)}),(0,V.jsx)(tm,{className:_?`is-open`:``,size:16})]}),_?(0,V.jsxs)(`div`,{className:`personal-diagnostics`,children:[(0,V.jsxs)(`code`,{children:[`goal_id: `,me]}),(0,V.jsxs)(`code`,{children:[`kind: `,f.kind]}),f.kind===`run`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`code`,{children:[`session_id: `,f.item.sessionId??m(`drawer.notLinked`)]}),(0,V.jsxs)(`code`,{children:[`turn_id: `,f.item.turnId??m(`common.none`)]}),(0,V.jsxs)(`code`,{children:[`adapter: `,f.item.agentId]}),(0,V.jsxs)(`code`,{children:[`status: `,f.item.sessionStatus??f.item.status]})]}):f.kind===`proposal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`code`,{children:[`action: `,f.item.actionKind]}),(0,V.jsxs)(`code`,{children:[`status: `,f.item.status]})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`code`,{children:[`schedule_id: `,f.item.scheduleId]}),(0,V.jsxs)(`code`,{children:[`status: `,f.item.status??`active`]})]})]}):null]}):null]})]})}var $y=[`checking`,`connecting`,`downloading`,`installing_app`,`installing_runtime`],eb={desktop_status_unavailable:[`无法读取 App 更新状态。请重启 App 后再试;若仍失败,请重新安装最新 App。`,`Cannot read the App update status. Restart the App; if this persists, reinstall the latest App.`],update_feed_unavailable:[`此通道的更新源尚未就绪或暂时不可用。可稍后重新检查,当前版本仍可继续使用。`,`This channel's update feed is not ready or temporarily unavailable. Check again later; you can keep using this version.`],update_feed_invalid:[`更新源格式异常。请稍后重新检查。`,`The update feed is invalid. Check again later.`],update_platform_unavailable:[`此通道尚无适用于本机的更新包。`,`This channel has no update package for this platform.`],update_check_timeout:[`检查更新超时。请稍后重试。`,`The update check timed out. Try again later.`],update_network_failed:[`无法连接更新服务器。请检查网络后重试。`,`Cannot reach the update server. Check your connection and retry.`],update_download_or_signature_failed:[`更新包下载或签名校验失败,尚未安装。请重新检查更新。`,`Download or signature verification failed; the update was not installed. Check for updates again.`]};function tb(e,t=`update_failed`){return{phase:`error`,details:{code:typeof e==`string`&&Object.hasOwn(eb,e)?e:t}}}function nb(){let{locale:e}=qi(),t=e===`zh-CN`,[n,r]=(0,B.useState)(!1),i=(0,B.useRef)(null),[a,o]=(0,B.useState)(`stable`),[s,c]=(0,B.useState)({phase:`idle`}),[l,u]=(0,B.useState)(``),[d,f]=(0,B.useState)(!1),p=(0,B.useRef)(!1),m=window.__TAURI__?.core.invoke,h=$y.includes(s.phase);(0,B.useEffect)(()=>{let e=i.current;if(!e)return;let t=()=>r(e.matches(`:popover-open`));return e.addEventListener(`toggle`,t),()=>e.removeEventListener(`toggle`,t)},[]),(0,B.useEffect)(()=>{if(!m)return;let e=!0;return m(`desktop_update_status`).then(t=>{if(!e)return;u(t.app_version),f(t.rollback_available===!0),t.state?.phase&&c(t.state);let n=t.state?.details?.channel??(t.app_version.includes(`-main.`)?`main`:`stable`);o(n),t.state?.phase||m(`desktop_update`,{action:`check`,channel:n}).then(t=>{e&&c(t)}).catch(t=>{e&&c(tb(t))})}).catch(()=>{e&&c(tb(null,`desktop_status_unavailable`))}),()=>{e=!1}},[m]),(0,B.useEffect)(()=>{if(!m||!h)return;let e=window.setInterval(()=>{m(`desktop_update_status`).then(e=>{e.state?.phase&&c(e.state)}).catch(()=>{})},1e3);return()=>window.clearInterval(e)},[m,h]);async function g(e){if(!(!m||p.current)){p.current=!0,c({phase:e===`check`?`checking`:e===`repair`?`installing_runtime`:`downloading`});try{if(!l){let e=await m(`desktop_update_status`);u(e.app_version),f(e.rollback_available===!0)}c(await m(`desktop_update`,{action:e,channel:a}))}catch(e){c(tb(e,l?`update_failed`:`desktop_status_unavailable`))}finally{p.current=!1}}}let _={service_error:t?`运行时已安装,但服务尚未连接。可重试更新、修复或恢复上版。`:`Runtime installed, but services are unavailable. Retry updates, repair, or restore the previous version.`,idle:t?`App 会检查可用更新,不会自动安装。`:`Updates are checked automatically, never installed without confirmation.`,runtime_required:t?`请完成匹配组件安装,或检查 App 更新。`:`Install matching components or check for an App update.`,connecting:t?`正在连接更新后的服务…`:`Connecting to updated services…`,checking:t?`正在检查更新…`:`Checking for updates…`,available:t?`新版本已就绪,一次更新 App 与匹配的运行时。`:`Update the App and its matching runtime together.`,up_to_date:t?`当前通道暂无更新。`:`No newer update on this channel.`,downloading:t?`正在下载并校验签名…`:`Downloading and verifying signature…`,installing_app:t?`正在安装 App,请保持窗口打开。`:`Installing the App. Keep this window open.`,installing_runtime:t?`正在安装匹配的运行时,请稍候…`:`Installing the matching runtime…`,restart_required:t?`重启后将自动完成运行时安装与服务连接。`:`Restart to finish runtime installation and reconnect services.`,ready:t?`更新完成,服务已就绪。`:`Update completed; services are ready.`,error:eb[s.details?.code??``]?.[+!t]??(t?`更新未完成。请重试;启动失败可尝试修复当前版本。`:`Update incomplete. Retry; repair this version if startup fails.`)},v=h?t?`正在更新…`:`Updating…`:s.phase===`available`?t?`有可用更新`:`Update available`:s.phase===`restart_required`?t?`重启完成更新`:`Restart to finish`:s.phase===`error`?t?`更新需重试`:`Retry update`:t?`更新 LoopX`:`Update LoopX`;return(0,V.jsxs)(`div`,{className:`personal-desktop-update`,children:[(0,V.jsxs)(`button`,{className:`personal-update-trigger`,type:`button`,"aria-expanded":n,"aria-controls":`desktop-update-panel`,onClick:e=>{i.current?.style.setProperty(`bottom`,`${window.innerHeight-e.currentTarget.getBoundingClientRect().top+8}px`),i.current?.togglePopover()},children:[(0,V.jsx)(um,{size:16,"aria-hidden":`true`}),(0,V.jsx)(`span`,{children:v}),(0,V.jsx)(rm,{size:14,"aria-hidden":`true`})]}),(0,V.jsxs)(`section`,{ref:i,popover:`auto`,id:`desktop-update-panel`,className:`personal-update-panel`,"aria-label":t?`LoopX 更新`:`LoopX updates`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:t?`LoopX 更新`:`LoopX updates`}),(0,V.jsx)(`button`,{type:`button`,"aria-label":t?`关闭更新面板`:`Close updates`,onClick:()=>i.current?.hidePopover(),children:(0,V.jsx)($m,{size:16,"aria-hidden":`true`})})]}),(0,V.jsxs)(`small`,{children:[l,` · `,a===`main`?t?`main 预览版`:`main preview`:t?`稳定版`:`Stable`]}),s.details?.version?(0,V.jsxs)(`p`,{children:[t?`目标版本:`:`Target: `,s.details.version]}):null,(0,V.jsxs)(`p`,{role:`status`,"aria-live":`polite`,children:[h?(0,V.jsx)(Im,{className:`is-spinning`,size:14,"aria-hidden":`true`}):null,_[s.phase]]}),s.phase===`downloading`&&s.details?.total?(0,V.jsx)(`progress`,{"aria-label":t?`下载进度`:`Download progress`,max:s.details.total,value:s.details.received??0}):null,m?(0,V.jsx)(`div`,{className:`personal-update-actions`,children:s.phase===`restart_required`?(0,V.jsx)(`button`,{type:`button`,onClick:()=>void g(`restart`),children:t?`重启完成更新`:`Restart to finish`}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{type:`button`,disabled:h,onClick:()=>void g(`check`),children:t?`检查更新`:`Check for updates`}),s.phase===`available`?(0,V.jsx)(`button`,{type:`button`,onClick:()=>void g(`apply`),children:t?`更新并准备重启`:`Install update`}):null]})}):(0,V.jsx)(`p`,{children:t?`请在 LoopX App 中更新;浏览器自身无需安装包。`:`Update from the LoopX App; the browser needs no installer.`}),(0,V.jsxs)(`details`,{children:[(0,V.jsx)(`summary`,{children:t?`高级选项`:`Advanced options`}),(0,V.jsxs)(`label`,{children:[t?`更新通道`:`Update channel`,(0,V.jsxs)(`select`,{disabled:h||s.phase===`restart_required`,value:a,onChange:e=>{o(e.target.value),c({phase:`idle`})},children:[(0,V.jsx)(`option`,{value:`stable`,children:t?`稳定版(推荐)`:`Stable (recommended)`}),(0,V.jsx)(`option`,{value:`main`,children:t?`main 预览版`:`main preview`})]})]}),(0,V.jsx)(`p`,{children:t?`App 与匹配的 CLI 一起更新,服务可能短暂断开。不删除 Goal 数据。`:`Updates the App and matching CLI. Services may briefly disconnect. Goal data is not deleted.`}),m?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{children:t?`启动失败时,可重装当前 App 随附的运行时。`:`If startup fails, reinstall this App's bundled runtime.`}),(0,V.jsx)(`button`,{disabled:h||s.phase===`restart_required`,type:`button`,onClick:()=>void g(`repair`),children:t?`修复当前版本`:`Repair this version`})]}):null,m&&d?(0,V.jsxs)(`details`,{children:[(0,V.jsx)(`summary`,{children:t?`恢复上个版本`:`Restore previous version`}),(0,V.jsx)(`p`,{children:t?`将恢复已保留的 App 和它的运行时,需要重启。`:`Restore the retained App and its runtime, then restart.`}),(0,V.jsx)(`button`,{disabled:h,type:`button`,onClick:()=>void g(`rollback`),children:t?`确认恢复上版`:`Restore previous version`})]}):null]})]})]})}var rb=e=>`loopx-sidebar-goal-order-v1:${encodeURIComponent(e)}`;function ib(e){try{let t=JSON.parse(e??`null`);return Array.isArray(t)&&t.every(e=>typeof e==`string`)?[...new Set(t)]:[]}catch{return[]}}function ab(e,t){let n=new Map(t.map((e,t)=>[e,t]));return[...e].sort((e,t)=>(n.get(e.goalId)??1/0)-(n.get(t.goalId)??1/0))}function ob(e,t,n,r,i){if(n===r||!t.includes(n)||!t.includes(r))return e;let a=[...new Set([...e,...t])].filter(e=>e!==n);return a.splice(a.indexOf(r)+Number(i),0,n),a}function sb(e,t){let n=rb(t),[r,i]=(0,B.useState)(()=>{try{return ib(localStorage.getItem(n))}catch{return[]}}),[a,o]=(0,B.useState)(!1),[s,c]=(0,B.useState)(null),[l,u]=(0,B.useState)(null),d=(0,B.useRef)(null),f=(0,B.useRef)(!1),p=ab(e,r),m=p.map(e=>e.goalId);function h(t,a,s){let l=ob(r,m,t,a,s);if(l===r)return;i(l);let u=ab(e,l),d=u.findIndex(e=>e.goalId===t),f=u[d];f&&c({title:f.title,position:d+1});try{localStorage.setItem(n,JSON.stringify(l)),o(!1)}catch{o(!0)}}function g(){d.current=null,u(null)}return{sorted:p,target:l,saveFailed:a,lastMoved:s,move:h,moveBy(e,t){let n=p[m.indexOf(e)+t];n&&h(e,n.goalId,t===1)},pointerProps:e=>({onPointerDown(t){f.current=!1,t.pointerType===`mouse`&&t.button===0&&(d.current={id:e,x:t.clientX,y:t.clientY,dragging:!1},t.currentTarget.setPointerCapture(t.pointerId))},onPointerMove(e){let t=d.current;if(!t||!t.dragging&&Math.hypot(e.clientX-t.x,e.clientY-t.y)<6)return;t.dragging=!0,f.current=!0;let n=document.elementFromPoint(e.clientX,e.clientY)?.closest(`[data-reorder-goal]`),r=e.currentTarget.closest(`.personal-goal-list`),i=n?.dataset.reorderGoal;if(!n||!i||!r?.contains(n)||i===t.id){u(null);return}let a=n.getBoundingClientRect();u({id:i,after:e.clientY>a.top+a.height/2})},onPointerUp(){d.current?.dragging&&l&&h(d.current.id,l.id,l.after),g()},onPointerCancel:g,onLostPointerCapture:g,onKeyDown(e){e.key===`Escape`&&g()},onClickCapture(e){f.current&&=(e.preventDefault(),e.stopPropagation(),!1)}})}}var cb=`/ssh-hosts`,lb=/^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;function ub(e){return typeof e==`string`&&lb.test(e.trim())}function db(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`SSH Host 列表响应无效。`);let t=e;if(t.ok!==!0||t.schema_version!==`ssh_host_catalog_v0`||!Array.isArray(t.hosts))throw Error(`SSH Host 列表协议不兼容,请更新本机 LoopX 服务。`);let n=new Set;return{hosts:t.hosts.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=String(e.alias??``).trim();return!ub(t)||n.has(t)?[]:(n.add(t),[{alias:t}])}),schemaVersion:`ssh_host_catalog_v0`}}async function fb(e=fetch,t=cb){let n=await e(t,{cache:`no-store`});if(!n.ok)throw Error(`无法读取本机 SSH Host(HTTP ${n.status})。`);return db(await n.json())}function pb(e,t){let n=e.trim();if(!ub(n))return{error:`请选择有效的 SSH Host。`};let r=Number(t);return!Number.isInteger(r)||r<1024||r>65535?{error:`本地端口必须是 1024–65535 之间的整数。`}:{command:`ssh -N -L ${r}:127.0.0.1:8766 ${n}`,hostAlias:n,label:n,statusUrl:`http://127.0.0.1:${r}/status.json`}}var mb=`/api/ssh-source/ensure`,hb=`/api/ssh-source/goal-lifecycle`;async function gb(e,t){let n=await fetch(mb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({host_alias:e,local_port:Number(t)})}),r=await n.json().catch(()=>null);if(!n.ok)throw Error(r?.error??`无法建立 SSH 隧道来源。`);if(!r?.ok)throw Error(`无法建立 SSH 隧道来源。`);return r}async function _b(e,t,n,r,i=fetch){let a=await i(hb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({goal_id:t,host_alias:e,operation:n,reason:r})}),o=await a.json().catch(()=>null);if(!a.ok)throw Error(o?.error??`无法更新远端 Goal 生命周期。`);if(!o?.ok||o.schema_version!==`loopx_remote_goal_lifecycle_v1`||o.goal_id!==t||o.host_alias!==e||o.operation!==n||o.activation_state!==(n===`stop`?`stopped`:`active`)||o.projection_verified!==!0)throw Error(`远端 Goal 生命周期回读未验证。`);return o}function vb({activeSource:e,connectionState:t,errorMessage:n,onAdd:r,onConfiguredHostsLoaded:i,onRemove:a,onSelect:o,sources:s}){let{t:c}=qi(),[l,u]=(0,B.useState)(!1),[d,f]=(0,B.useState)(null),[p,m]=(0,B.useState)(`configured`),[h,g]=(0,B.useState)([]),[_,v]=(0,B.useState)(null),[y,b]=(0,B.useState)(!1),[x,S]=(0,B.useState)(!1),[C,w]=(0,B.useState)(``),[T,E]=(0,B.useState)(``),[D,O]=(0,B.useState)(`8876`),[ee,te]=(0,B.useState)(``),ne=`configured:`,k=[...s.map(e=>({label:e.label,value:e.id})),...h.filter(e=>!s.some(t=>t.label===e.alias)).map(e=>({group:c(`source.configuredGroup`,{count:h.length}),label:e.alias,value:`${ne}${e.alias}`}))],A=(0,B.useMemo)(()=>h.some(e=>e.alias===C)?pb(C,D):{error:c(`source.selectHost`)},[h,C,D,c]);(0,B.useEffect)(()=>{j()},[]);async function j(){b(!0),v(null);try{let e=await fb();g(e.hosts),i?.(e.hosts.map(e=>e.alias)),w(t=>t||e.hosts[0]?.alias||``),e.hosts.length||v(c(`source.hostEmpty`))}catch(e){v(e instanceof Error?e.message:c(`source.hostLoadError`))}finally{b(!1)}}function M(){u(!0),m(`configured`),f(null),j()}function N(){u(!1),m(`configured`),v(null),S(!1),w(``),f(null),E(``),O(`8876`),te(``)}function P(){let e=r({label:T,statusUrl:ee});if(e.error){f(e.error);return}N()}function F(){if(`error`in A){f(A.error??c(`source.invalid`));return}let e=r({ensureTunnel:!0,hostAlias:A.hostAlias,label:A.label,statusUrl:A.statusUrl});if(e.error){f(e.error);return}N()}function re(e){let t=new Set;for(let e of s)try{t.add(new URL(e.statusUrl).port)}catch{}let n=`8877`;for(let e=8877;e<9077;e+=1)if(!t.has(String(e))){n=String(e);break}let i=pb(e,n);if(`error`in i){f(i.error??c(`source.invalid`));return}let a=r({ensureTunnel:!0,hostAlias:i.hostAlias,label:i.label,statusUrl:i.statusUrl});a.error?f(a.error):f(null),O(n)}async function ie(){if(`error`in A){f(A.error??c(`source.invalid`));return}try{await navigator.clipboard.writeText(A.command),S(!0),f(null)}catch{f(c(`source.copyError`))}}return(0,V.jsxs)(`section`,{"aria-label":c(`source.controlPlane`),className:`personal-status-source`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`span`,{children:`Control plane`}),(0,V.jsx)(`button`,{"aria-label":c(`source.addSsh`),onClick:M,title:c(`source.add`),type:`button`,children:(0,V.jsx)(Pm,{size:14})})]}),(0,V.jsx)(Sy,{ariaLabel:c(`source.select`),className:`personal-status-source-select`,icon:(0,V.jsx)(Hm,{size:15}),onChange:e=>{if(e.startsWith(ne)){re(e.slice(11));return}o(e)},options:k,value:e.id}),(0,V.jsxs)(`div`,{className:`personal-status-source-meta`,children:[(0,V.jsxs)(`span`,{className:`is-${t}`,children:[(0,V.jsx)(`i`,{}),c(t===`loading`?`source.connecting`:t===`error`?`source.notAvailable`:`source.connected`)]}),(0,V.jsx)(`small`,{children:e.readOnly?c(`source.readOnly`):c(`source.localInteractive`)}),e.kind===`ssh_tunnel`?(0,V.jsx)(`button`,{"aria-label":c(`source.remove`,{source:e.label}),onClick:()=>a(e.id),title:c(`source.removeCurrent`),type:`button`,children:(0,V.jsx)(Xm,{size:12})}):null]}),n?(0,V.jsx)(`p`,{className:`personal-status-source-error`,role:`alert`,children:n}):null,l?(0,V.jsxs)(`div`,{className:`personal-status-source-form`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:c(`source.addSsh`)}),(0,V.jsx)(`button`,{"aria-label":c(`source.closeForm`),onClick:N,type:`button`,children:(0,V.jsx)($m,{size:13})})]}),(0,V.jsxs)(`div`,{"aria-label":c(`source.addMethod`),className:`personal-status-source-modes`,role:`tablist`,children:[(0,V.jsx)(`button`,{"aria-selected":p===`configured`,onClick:()=>{m(`configured`),f(null)},role:`tab`,type:`button`,children:c(`source.configured`)}),(0,V.jsx)(`button`,{"aria-selected":p===`manual`,onClick:()=>{m(`manual`),f(null)},role:`tab`,type:`button`,children:c(`source.manual`)})]}),p===`configured`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.configuredCount`,{count:h.length})}),(0,V.jsxs)(`span`,{className:`personal-status-source-field-row`,children:[(0,V.jsx)(`input`,{"aria-label":c(`source.host`),disabled:y||!h.length,list:`loopx-configured-ssh-hosts`,onChange:e=>{w(e.target.value),S(!1)},placeholder:c(y?`source.loadingHosts`:`source.hostPlaceholder`),value:C}),(0,V.jsx)(`datalist`,{id:`loopx-configured-ssh-hosts`,children:h.map(e=>(0,V.jsx)(`option`,{value:e.alias},e.alias))}),(0,V.jsx)(`button`,{"aria-label":c(`source.refreshHosts`),disabled:y,onClick:()=>void j(),title:c(`source.refreshHosts`),type:`button`,children:(0,V.jsx)(Rm,{size:13})})]})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.localPort`)}),(0,V.jsx)(`input`,{"aria-label":c(`source.localPort`),inputMode:`numeric`,onChange:e=>{O(e.target.value),S(!1)},value:D})]}),(0,V.jsxs)(`div`,{className:`personal-status-source-command`,children:[(0,V.jsx)(`code`,{children:`error`in A?c(`source.tunnelCommandPending`):A.command}),(0,V.jsxs)(`button`,{"aria-label":c(`source.copyCommand`),disabled:`error`in A,onClick:()=>void ie(),type:`button`,children:[(0,V.jsx)(cm,{size:12}),c(x?`source.copied`:`source.copy`)]})]}),_?(0,V.jsx)(`p`,{className:`is-error`,children:_}):null,(0,V.jsx)(`p`,{children:c(`source.description`)}),(0,V.jsx)(`button`,{className:`personal-status-source-add`,disabled:`error`in A,onClick:F,type:`button`,children:c(`source.addConfigured`)})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.name`)}),(0,V.jsx)(`input`,{autoFocus:!0,maxLength:48,onChange:e=>E(e.target.value),placeholder:c(`source.namePlaceholder`),value:T})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.statusUrl`)}),(0,V.jsx)(`input`,{onChange:e=>te(e.target.value),placeholder:`http://127.0.0.1:8876/status.json`,value:ee})]}),(0,V.jsx)(`p`,{children:(0,V.jsx)(`code`,{children:`ssh -N -L 8876:127.0.0.1:8766 `})}),(0,V.jsx)(`p`,{children:c(`source.manualDescription`)}),(0,V.jsx)(`button`,{className:`personal-status-source-add`,onClick:P,type:`button`,children:c(`source.addConfigured`)})]}),d?(0,V.jsx)(`p`,{className:`is-error`,role:`alert`,children:d}):null]}):null]})}var yb={需修复:`is-danger`,等你:`is-warning`,等待条件:`is-info`,推进中:`is-success`,安静运行:`is-quiet`,已完成:`is-quiet`,已停止:`is-stopped`};function bb({attentionCount:e,goals:t,goalArchiveLoadState:n={error:null,phase:`ready`},lifecycleBusyGoalIds:r,goalLifecycleOperations:i,onRequestGoalCreate:a,onOpenSettings:o,onRetryGoalArchive:s,onRequestGoalLifecycle:c,onSelectGoal:l,selectedGoalId:u,statusSourceControl:d}){let{locale:f,t:p}=qi(),[m,h]=(0,B.useState)(!1),g=sb(t.filter(e=>e.activationState!==`stopped`),d?.activeSource.statusUrl??`/status.json`),_=g.sorted,v=t.filter(e=>e.activationState===`stopped`),y=e=>!!c&&(!i||i.includes(e)),b=(e,t)=>(0,V.jsxs)(`div`,{className:`personal-goal-row${g.target?.id===e.goalId?g.target.after?` is-drop-after`:` is-drop-before`:``}`,"data-reorder-goal":t?void 0:e.goalId,"data-load-error":e.loadError,children:[(0,V.jsxs)(`button`,{...t?{}:g.pointerProps(e.goalId),title:t?void 0:p(`sidebar.dragGoal`),"aria-current":u===e.goalId?`page`:void 0,className:`personal-goal-link`,onClick:()=>l(e.goalId),type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-goal-state-dot ${e.loadState?``:yb[e.state]}`}),(0,V.jsxs)(`span`,{className:`personal-goal-link-copy`,children:[(0,V.jsx)(`strong`,{children:e.title}),(0,V.jsxs)(`small`,{children:[e.loadState&&(!t||u===e.goalId)?p(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Ji(e.state,f),e.needsYou&&!t?` · ${p(`home.lane.needsYou`)}`:``]})]}),(0,V.jsx)(nm,{size:15})]}),!t&&m?(0,V.jsxs)(`div`,{className:`personal-goal-move-actions`,children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveUp`,{goal:e.title}),disabled:_[0]?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,-1),children:(0,V.jsx)(Jp,{"aria-hidden":`true`,size:13})}),(0,V.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveDown`,{goal:e.title}),disabled:_.at(-1)?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,1),children:(0,V.jsx)(Wp,{"aria-hidden":`true`,size:13})})]}):null,c&&y(t?`resume`:`stop`)?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{"aria-label":`${p(t?`sidebar.resume`:`sidebar.stop`)} ${e.title}`,"aria-busy":r?.has(e.goalId)||void 0,className:`personal-goal-lifecycle${r?.has(e.goalId)?` is-pending`:``}`,disabled:r?.has(e.goalId),onClick:()=>c(e,t?`resume`:`stop`),title:p(t?`sidebar.resumeGoal`:`sidebar.stopGoal`),type:`button`,children:r?.has(e.goalId)?(0,V.jsx)(Cm,{size:13}):t?(0,V.jsx)(Lm,{size:13}):(0,V.jsx)(Mm,{size:13})}),t&&y(`delete`)?(0,V.jsx)(`button`,{"aria-label":`${p(`sidebar.delete`)} ${e.title}`,className:`personal-goal-lifecycle personal-goal-delete`,onClick:()=>c(e,`delete`),title:p(`sidebar.deleteGoal`),type:`button`,children:(0,V.jsx)(Xm,{size:13})}):null]}):null]},e.goalId);return(0,V.jsxs)(`div`,{className:`personal-goal-directory`,children:[(0,V.jsxs)(`div`,{className:`personal-sidebar-brand`,children:[(0,V.jsx)(`span`,{className:`personal-brand-mark`,children:(0,V.jsx)(Zp,{size:18})}),(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:`LoopX`})})]}),d?(0,V.jsx)(vb,{...d}):null,(0,V.jsxs)(`nav`,{"aria-label":p(`home.workspace`),className:`personal-sidebar-nav`,children:[(0,V.jsxs)(`button`,{"aria-current":u===null?`page`:void 0,className:`personal-manager-link`,onClick:()=>l(null),type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-manager-icon`,children:(0,V.jsx)(Zp,{size:17})}),(0,V.jsx)(`span`,{children:p(`sidebar.manager`)}),e>0?(0,V.jsx)(`span`,{className:`personal-sidebar-count`,children:e}):null,(0,V.jsx)(nm,{size:15})]}),(0,V.jsxs)(`div`,{className:`personal-sidebar-section-title`,children:[(0,V.jsx)(`span`,{children:`Goals`}),(0,V.jsxs)(`span`,{className:`personal-sidebar-title-actions`,children:[(0,V.jsx)(`small`,{children:_.length}),(0,V.jsx)(`button`,{"aria-label":p(`sidebar.sortGoals`),title:p(`sidebar.sortGoals`),"aria-pressed":m,onClick:()=>h(!m),type:`button`,children:(0,V.jsx)(qp,{"aria-hidden":`true`,size:15})}),a?(0,V.jsx)(`button`,{"aria-label":p(`sidebar.createGoal`),onClick:a,type:`button`,children:(0,V.jsx)(Pm,{size:15})}):null]})]}),g.saveFailed?(0,V.jsx)(`p`,{role:`status`,children:p(`sidebar.orderNotSaved`)}):null,(0,V.jsx)(`span`,{className:`personal-sr-only`,role:`status`,children:g.lastMoved?p(`sidebar.goalMoved`,{goal:g.lastMoved.title,position:g.lastMoved.position}):``}),(0,V.jsx)(`div`,{className:`personal-goal-list`,children:_.map(e=>b(e,!1))}),v.length||n.phase===`loading`||n.phase===`error`?(0,V.jsxs)(`details`,{className:`personal-stopped-goals`,open:n.phase===`error`||void 0,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(tm,{size:13}),(0,V.jsx)(`span`,{children:p(`sidebar.stopped`)}),n.phase===`loading`?(0,V.jsx)(Cm,{"aria-label":p(`sidebar.stoppedLoading`),className:`is-spinning`,size:13}):(0,V.jsx)(`small`,{children:v.length})]}),(0,V.jsxs)(`div`,{className:`personal-goal-list is-stopped`,children:[n.phase===`error`?(0,V.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`alert`,children:[(0,V.jsx)(`span`,{children:p(`sidebar.stoppedLoadFailed`)}),s?(0,V.jsx)(`button`,{onClick:s,type:`button`,children:p(`sidebar.retryStopped`)}):null]}):null,v.map(e=>b(e,!0))]})]}):null]}),(0,V.jsxs)(`div`,{className:`personal-sidebar-footer`,children:[(0,V.jsx)(nb,{}),o?(0,V.jsxs)(`button`,{"aria-label":p(`settings.open`),className:`personal-sidebar-utility`,onClick:o,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-sidebar-utility-icon`,children:(0,V.jsx)(Um,{size:17})}),(0,V.jsx)(`span`,{className:`personal-sidebar-utility-copy`,children:(0,V.jsx)(`strong`,{children:p(`settings.open`)})}),(0,V.jsx)(nm,{"aria-hidden":`true`,size:15})]}):null]})]})}var xb=Y({ok:X(!0),total:K().int().nonnegative(),next_cursor:G().nullable(),items:J(Y({todo_id:G(),text:G(),claimed_by:G().nullable(),evidence:G().nullable(),priority:G().nullable(),task_class:G().nullable()})).max(40)});function Sb({goal:e,agentId:t,seed:n,enabled:r,listView:i=!1,onSelect:a}){let{t:o}=qi(),s=(0,B.useId)(),[c,l]=(0,B.useState)(!1),u=!i||c,d=i?96:148,[f,p]=(0,B.useState)(n),[m,h]=(0,B.useState)(t===`all`?e.doneTodoCount??n.length:n.length),[g,_]=(0,B.useState)(void 0),[v,y]=(0,B.useState)(!1),[b,x]=(0,B.useState)(!1),[S,C]=(0,B.useState)(!1),[w,T]=(0,B.useState)({top:0,height:600}),[E,D]=(0,B.useState)(null),O=(0,B.useRef)(null),ee=(0,B.useRef)(null),[te,ne]=(0,B.useState)(0);(0,B.useEffect)(()=>{let e=O.current;if(!e)return;let t=new ResizeObserver(()=>T({top:e.scrollTop,height:e.clientHeight}));return t.observe(e),()=>{t.disconnect(),ee.current?.abort()}},[]);let k=g===void 0||w.top+w.height>=f.length*d-d*2;(0,B.useEffect)(()=>{if(!r||!u||!k||g===null||b||ee.current)return;let n=new AbortController;ee.current=n,y(!0);let i=new URLSearchParams({goal_id:e.goalId});t!==`all`&&i.set(`agent_id`,t),g&&i.set(`cursor`,g),fetch(`/api/chat/completed-todos?${i}`,{signal:n.signal}).then(async e=>{if(e.status===409&&C(!0),!e.ok)throw Error(`history unavailable`);let t=xb.parse(await e.json());if(n.signal.aborted)return;let r=t.items.map(e=>({todoId:e.todo_id,text:e.text,claimedBy:e.claimed_by,evidence:e.evidence,priority:e.priority,taskClass:e.task_class,done:!0,status:`done`}));p(e=>g===void 0?r:[...e,...r.filter(t=>!e.some(e=>e.todoId===t.todoId))]),h(t.total),_(t.next_cursor)}).catch(()=>{n.signal.aborted||x(!0)}).finally(()=>{n.signal.aborted||(ee.current=null,y(!1))})},[r,u,k,g,b,te,e.goalId,t,v]),(0,B.useEffect)(()=>{O.current&&(O.current.scrollTop=0),T({top:0,height:O.current?.clientHeight??600}),D(null)},[i]);let A=Math.max(0,Math.floor(w.top/d)-3),j=Math.min(f.length,Math.ceil((w.top+w.height)/d)+3),M=Array.from({length:Math.max(0,j-A)},(e,t)=>A+t);return E!==null&&El(e=>!e),children:[(0,V.jsx)(`span`,{"aria-hidden":`true`,children:c?`▾`:`▸`}),` `,o(`tasks.completed`)]}):(0,V.jsxs)(`strong`,{children:[(0,V.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-done`}),o(`tasks.completed`)]}),(0,V.jsx)(`span`,{children:m})]}),(0,V.jsxs)(`div`,{id:s,hidden:!u,"aria-label":o(`tasks.completed`),className:`personal-task-lane-scroll`,ref:O,role:`region`,tabIndex:0,onScroll:e=>T({top:e.currentTarget.scrollTop,height:e.currentTarget.clientHeight}),children:[(0,V.jsx)(`div`,{className:`personal-completed-window`,style:{height:f.length*d},children:M.map(t=>{let n=f[t];return(0,V.jsx)(`div`,{className:`personal-task-card personal-completed-row`,style:{top:t*d,height:d},children:(0,V.jsxs)(`button`,{type:`button`,onFocus:()=>D(t),onBlur:()=>D(null),onClick:()=>a({kind:`todo`,item:{...n,goalId:e.goalId,goalTitle:e.title,ownerLabel:n.claimedBy??e.agentLabel??e.agentId}}),children:[(0,V.jsx)(`span`,{className:`is-done`,children:`✓`}),(0,V.jsx)(`strong`,{children:n.text}),(0,V.jsx)(`small`,{children:n.claimedBy??e.agentLabel??e.agentId})]})},n.todoId)})}),(0,V.jsx)(`div`,{className:`personal-completed-footer`,role:`status`,children:v?o(`tasks.historyLoading`):b?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`span`,{children:o(S?`tasks.historyExpired`:`tasks.historyError`)}),(0,V.jsx)(`button`,{type:`button`,onClick:()=>{S&&(_(void 0),O.current&&(O.current.scrollTop=0)),C(!1),x(!1),ne(e=>e+1)},children:o(`tasks.historyRetry`)})]}):r?g===null?o(`tasks.historyEnd`):(0,V.jsx)(`button`,{type:`button`,onClick:()=>{O.current&&(O.current.scrollTop=f.length*d)},children:o(`tasks.historyMore`)}):o(`tasks.historyLocalOnly`)})]})]})}function Cb({children:e,count:t,label:n,tone:r,listView:i=!1}){let a=(0,B.useId)(),o=(0,B.useRef)(null),s=(0,B.useRef)([]),c=(0,B.useRef)(null),[l,u]=(0,B.useState)({after:!1,before:!1}),d=(0,B.useCallback)(()=>{let e=o.current;if(!e)return;let t={after:Math.max(0,e.scrollHeight-e.clientHeight)-e.scrollTop>1,before:e.scrollTop>1};u(e=>e.after===t.after&&e.before===t.before?e:t)},[]);return(0,B.useEffect)(()=>{let e=o.current;if(!e)return;let t=new ResizeObserver(d);return c.current=t,t.observe(e),e.addEventListener(`scroll`,d,{passive:!0}),d(),()=>{t.disconnect(),c.current=null,s.current=[],e.removeEventListener(`scroll`,d)}},[i,d]),(0,B.useEffect)(()=>{let e=o.current,t=c.current;if(!e||!t)return;for(let e of s.current)t.unobserve(e);let n=Array.from(e.children).filter(e=>e instanceof HTMLElement);for(let e of n)t.observe(e);s.current=n,d()},[e,t,i,d]),i?!t&&r!==`done`?null:(0,V.jsxs)(`details`,{className:`personal-task-group tone-${r}`,open:!0,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(tm,{size:16}),(0,V.jsx)(`strong`,{children:n}),(0,V.jsx)(`span`,{children:t})]}),(0,V.jsx)(`div`,{className:`personal-task-list-rows`,children:e})]}):(0,V.jsxs)(`section`,{className:`personal-object-list personal-task-lane`,children:[(0,V.jsxs)(`header`,{id:a,children:[(0,V.jsxs)(`strong`,{children:[(0,V.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-${r}`}),n]}),(0,V.jsx)(`span`,{children:t})]}),(0,V.jsx)(`div`,{"aria-labelledby":a,className:`personal-task-lane-scroll${l.before?` has-overflow-before`:``}${l.after?` has-overflow-after`:``}`,ref:o,role:`region`,tabIndex:t>0?0:-1,children:e})]})}function wb({historyEnabled:e=!1,goal:t,items:n,onDraftTaskFromMessage:r,onOpenChat:i,onQuickComplete:a,quickCompletingTodoIds:o,onSelect:s,selectedTodoId:c=null,userTodos:l}){let{t:u}=qi(),[d,f]=(0,B.useState)(!1),[p,m]=(0,B.useState)({goalId:``,laneId:`all`}),h=(0,B.useRef)(null);(0,B.useEffect)(()=>{if(!c)return;let e=window.requestAnimationFrame(()=>h.current?.scrollIntoView({block:`nearest`,inline:`nearest`}));return()=>window.cancelAnimationFrame(e)},[c]);let g=l.filter(e=>e.goalId===t.goalId).map(e=>({...e,goalTitle:t.title})),_=e=>e.priority===`P0`?0:e.priority===`P1`?1:e.priority===`P2`?2:3,v=(0,B.useMemo)(()=>{let e=new Map((t.agentLanes??[]).map(e=>[e.agentId,e]));for(let n of t.agentTodos)n.claimedBy&&!e.has(n.claimedBy)&&e.set(n.claimedBy,{agentId:n.claimedBy,label:n.claimedBy});return[...e.values()]},[t.agentLanes,t.agentTodos]),y=p.goalId===t.goalId&&v.some(e=>e.agentId===p.laneId)?p.laneId:`all`,b=e=>y===`all`||e===y,x=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&!e.done).filter(e=>b(e.claimedBy)).sort((e,t)=>_(e)-_(t)),S=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&e.done).filter(e=>b(e.claimedBy)),C=n.filter(e=>e.kind===`schedule`&&b(e.schedule.agentId)),w=n.filter(e=>e.kind===`run`&&!!e.run.todoId&&b(e.run.agentId)),T=!g.length&&!x.length&&!S.length&&!C.length,E=n.filter(e=>e.kind===`message`&&(e.message.role===`user`||e.message.role===`assistant`)),D=E.reduce((e,t,n)=>t.message.role===`user`?n:e,-1),O=D>=0?E[D]?.message:null,ee=D>=0?E.slice(D+1).reverse().find(e=>e.message.role===`assistant`)?.message:null,te=D>=0&&E.slice(D+1).some(e=>e.message.role===`assistant`&&e.message.pending);return(0,V.jsxs)(`section`,{"aria-label":u(`header.tasks`),className:`personal-task-board${d?` is-list-view`:``}`,children:[(0,V.jsxs)(`header`,{className:`personal-task-view-toolbar`,children:[(0,V.jsx)(`div`,{children:(0,V.jsx)(`strong`,{children:u(`header.tasks`)})}),(0,V.jsxs)(`div`,{className:`personal-task-view-switch`,role:`group`,"aria-label":u(`tasks.viewLabel`),children:[(0,V.jsx)(`button`,{type:`button`,"aria-pressed":d,onClick:()=>f(!0),children:u(`tasks.listView`)}),(0,V.jsx)(`button`,{type:`button`,"aria-pressed":!d,onClick:()=>f(!1),children:u(`tasks.boardView`)})]})]}),v.length>1?(0,V.jsxs)(`section`,{"aria-label":u(`tasks.agentLaneFilter`),className:`personal-task-lane-filter`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(Zp,{size:15}),(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:u(`tasks.agentLane`)})})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{className:`sr-only`,children:u(`tasks.agentLaneFilter`)}),(0,V.jsxs)(`select`,{"aria-label":u(`tasks.agentLaneFilter`),onChange:e=>m({goalId:t.goalId,laneId:e.target.value}),value:y,children:[(0,V.jsx)(`option`,{value:`all`,children:u(`tasks.allAgentLanes`,{count:v.length})}),v.map(e=>(0,V.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))]}),(0,V.jsx)(tm,{"aria-hidden":!0,size:14})]})]}):null,O?(0,V.jsxs)(`section`,{"aria-label":u(`tasks.chatRecent`),className:`personal-task-chat-receipt`,children:[(0,V.jsx)(`span`,{className:`personal-task-chat-icon`,children:(0,V.jsx)(Dm,{size:18})}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:u(te?`tasks.chatPending`:ee?`tasks.chatAgentReplied`:`tasks.chatRecent`)}),(0,V.jsx)(`small`,{children:t.agentLabel??t.agentId})]}),(0,V.jsxs)(`p`,{className:`is-user`,children:[(0,V.jsx)(`b`,{children:u(`common.you`)}),O.text]}),ee&&!ee.pending?(0,V.jsxs)(`p`,{className:`is-assistant`,children:[(0,V.jsx)(`b`,{children:u(`common.agent`)}),ee.text]}):null,(0,V.jsx)(`small`,{children:u(te?`tasks.chatPendingDescription`:`tasks.chatUnchangedDescription`)})]}),(0,V.jsxs)(`footer`,{children:[(0,V.jsxs)(`button`,{onClick:i,type:`button`,children:[(0,V.jsx)(Dm,{size:14}),u(`tasks.chatViewReply`)]}),ee&&!te&&r?(0,V.jsxs)(`button`,{onClick:()=>r(ee.text),type:`button`,children:[(0,V.jsx)(Sm,{size:14}),u(`tasks.convertToTask`)]}):null]})]}):null,(0,V.jsxs)(`div`,{className:d?`personal-task-grouped-list`:`personal-task-kanban`,children:[(0,V.jsxs)(Cb,{listView:d,count:g.length,label:u(`timeline.waitingConfirmation`),tone:`attention`,children:[g.map(e=>{let t=Xi(e.updatedAt,u);return(0,V.jsxs)(`button`,{onClick:()=>s({item:e,kind:`attention`}),type:`button`,children:[(0,V.jsx)(`span`,{"aria-hidden":`true`,className:`is-attention`,children:`!`}),(0,V.jsx)(`strong`,{children:e.text}),(0,V.jsxs)(`small`,{children:[(0,V.jsx)(`span`,{className:`personal-row-status ${e.blocking?`is-blocking`:`is-pending`}`,children:e.blocking?u(`tasks.blocked`):u(`tasks.pending`)}),t?(0,V.jsx)(`span`,{className:`personal-task-age`,children:u(`tasks.waitingAge`,{age:t})}):null]})]},e.todoId)}),g.length?null:(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyConfirm`)})]}),(0,V.jsxs)(Cb,{listView:d,count:x.length,label:u(`tasks.pendingAndRunning`),tone:`progress`,children:[x.map(e=>{let n={...e,goalId:t.goalId,goalTitle:t.title,ownerLabel:e.claimedBy??t.agentLabel??t.agentId},r=w.find(t=>t.run.todoId===e.todoId)?.run;return(0,V.jsxs)(`div`,{className:`personal-task-card${r?` has-session`:``}${c===e.todoId?` is-selected`:``}`,ref:c===e.todoId?e=>{h.current=e}:void 0,children:[(0,V.jsxs)(`button`,{"aria-pressed":c===e.todoId,onClick:()=>s({item:n,kind:`todo`}),type:`button`,children:[(0,V.jsx)(`span`,{children:`○`}),(0,V.jsx)(`strong`,{children:e.text}),(0,V.jsxs)(`small`,{children:[e.priority?(0,V.jsx)(`span`,{className:`personal-priority-badge is-${e.priority.toLowerCase()}`,children:e.priority}):null,e.status===`blocked`?(0,V.jsx)(`span`,{className:`personal-priority-badge is-blocked`,children:u(`tasks.blocked`)}):null,r?(0,V.jsx)(`span`,{className:`personal-task-session-status`,children:r.status===`running`||r.status===`queued`?u(`runs.running`):r.status===`failed`?u(`tasks.sessionError`):u(`common.waiting`)}):null,e.status===`deferred`?(0,V.jsx)(`span`,{className:`personal-task-session-status`,children:u(`drawer.taskStatusDeferred`)}):r?null:(0,V.jsx)(`span`,{className:`personal-task-session-status`,children:u(`tasks.waiting`)}),e.claimedBy??t.agentLabel??t.agentId]})]}),(0,V.jsxs)(`div`,{className:`personal-task-card-actions`,children:[r?(0,V.jsxs)(`button`,{className:`personal-task-session-link`,"aria-label":u(`tasks.openExecution`,{name:e.text}),onClick:()=>s({item:r,kind:`run`}),title:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`),type:`button`,children:[(0,V.jsx)(fm,{size:14}),(0,V.jsx)(`span`,{children:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`)})]}):null,a?(0,V.jsx)(`button`,{"aria-busy":o?.has(e.todoId)||void 0,"aria-label":u(`tasks.markComplete`,{name:e.text}),disabled:o?.has(e.todoId),onClick:()=>void a(n),title:u(`tasks.completed`),type:`button`,children:o?.has(e.todoId)?(0,V.jsx)(Cm,{className:`personal-spin`,size:14}):(0,V.jsx)(em,{size:14})}):null,(0,V.jsx)(`button`,{"aria-label":u(`tasks.moreActions`,{name:e.text}),onClick:()=>s({item:n,kind:`todo`}),title:u(`common.actions`),type:`button`,children:(0,V.jsx)(dm,{size:14})})]})]},e.todoId)}),x.length?null:(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyRunning`)})]}),(0,V.jsxs)(Cb,{listView:d,count:C.length,label:u(`tasks.scheduled`),tone:`schedule`,children:[C.map(e=>(0,V.jsxs)(`button`,{onClick:()=>s({item:e.schedule,kind:`schedule`}),type:`button`,children:[(0,V.jsx)(`span`,{children:`◷`}),(0,V.jsx)(`strong`,{children:e.schedule.label}),(0,V.jsx)(`small`,{children:e.schedule.status===`paused`?u(`schedule.paused`):u(`schedule.active`)})]},e.id)),C.length?null:(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptySchedules`)})]}),(0,V.jsx)(Sb,{goal:t,agentId:y,seed:S,enabled:e,listView:d,onSelect:s},`${t.goalId}:${y}:${e}`)]}),T?(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyGoal`)}):null]})}function Tb(e,t){return{live_steering:{label:t(`lark.ingressSteering`),detail:t(`lark.ingressSteeringDescription`)},session_queue:{label:t(`lark.ingressQueue`),detail:t(`lark.ingressQueueDescription`)},async_inbox:{label:t(`lark.ingressAsync`),detail:t(`lark.ingressAsyncDescription`)},direct_session:{label:t(`lark.ingressLegacy`),detail:t(`lark.ingressLegacyDescription`)}}[e]}function Eb(e,t){return e.listener_status===`starting`?{label:t(`lark.health.starting`),detail:t(`lark.health.startingDetail`),state:`not_ready`}:e.listener_status===`retrying`&&e.listener_error_code===`lark_event_source_disconnected`?{label:t(`lark.health.sourceDisconnected`),detail:t(`lark.health.sourceDisconnectedDetail`),state:`not_ready`}:e.listener_status===`retrying`?{label:t(`lark.health.retrying`),detail:t(`lark.health.retryingDetail`),state:`not_ready`}:e.listener_status===`stopped`||e.listener_status===null?{label:t(`lark.health.notStarted`),detail:t(`lark.health.notStartedDetail`),state:`not_ready`}:e.last_event_status===`message_context_permission_required`?{label:t(`lark.health.messageContextPermission`),detail:t(`lark.health.messageContextPermissionDetail`),state:`not_ready`}:e.last_event_status===`processing_failed`?{label:t(`lark.health.processingFailed`),detail:t(`lark.health.processingFailedDetail`),state:`not_ready`}:e.health_error_code===`invalid_routing_state`?{label:t(`lark.health.invalidRouting`),detail:t(`lark.health.invalidRoutingDetail`),state:`not_ready`}:e.last_event_status===`queued_for_agent`?{label:t(`lark.health.queued`),detail:t(`lark.health.queuedDetail`,{agent:e.agent_id??t(`lark.targetAgent`)}),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`not_addressed`?{label:t(`lark.health.notAddressed`),detail:t(`lark.health.notAddressedDetail`),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`self_message`?{label:t(`lark.health.listening`),detail:t(`lark.health.ignoredSelf`),state:`ready`}:e.health_error_code===`lark_event_route_mismatch`||[`chat_mismatch`,`topic_mismatch`,`route_ambiguous`].includes(e.last_event_reason??``)?{label:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguous`):t(`lark.health.routeMismatch`),detail:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguousDetail`):t(`lark.health.routeMismatchDetail`),state:`not_ready`}:[`invalid_event`,`binding_unavailable`].includes(e.last_event_reason??``)?{label:t(`lark.health.routeUnavailable`),detail:t(`lark.health.routeUnavailableDetail`),state:`not_ready`}:e.last_event_status===`replied_and_acknowledged`?{label:t(`lark.health.listening`),detail:t(`lark.health.eventProcessed`,{events:e.event_count,replies:e.replied_count}),state:`ready`}:e.health_error_code===`lark_event_delivery_unverified`||e.event_count===0?{label:t(`lark.health.eventUnverified`),detail:t(`lark.health.eventUnverifiedDetail`),state:`unverified`}:{label:e.reply_ready?t(`lark.health.listening`):t(`lark.health.unavailable`),detail:t(`lark.health.lastStatus`,{status:e.last_event_status??t(`lark.health.waiting`)}),state:e.reply_ready?`ready`:`not_ready`}}function Db(e){return e.history_permission_guidance?.api_document_url??null}function Ob(e,t,n){if(e instanceof Th){let t=String(e.payload.error_code??``);return{lark_cli_not_installed:n(`lark.error.cliMissing`),lark_cli_not_executable:n(`lark.error.cliExecutable`),lark_cli_start_failed:n(`lark.error.cliStart`),lark_message_permissions_required:n(`lark.error.messagePermissions`),lark_app_required:n(`lark.error.appRequired`),invalid_lark_app:n(`lark.error.invalidApp`),lark_group_lookup_failed:n(`lark.error.groupLookup`),provider_api_failed:n(`lark.error.provider`)}[t]??e.message}return e instanceof Error?e.message:t}function kb({embedded:e=!1,focusGoalConnection:t=!1,goals:n,initialGoalId:r,onChanged:i,onClose:a}){let{t:o}=qi(),[s,c]=(0,B.useState)(`connections`),[l,u]=(0,B.useState)([]),[d,f]=(0,B.useState)([]),[p,m]=(0,B.useState)(!0),[h,g]=(0,B.useState)(null),[_,v]=(0,B.useState)(``),[y,b]=(0,B.useState)(t),[x,S]=(0,B.useState)(``),[C,w]=(0,B.useState)(r??n[0]?.goalId??``),[T,E]=(0,B.useState)(``),[D,O]=(0,B.useState)([]),[ee,te]=(0,B.useState)(``),[ne,k]=(0,B.useState)(!1),[A,j]=(0,B.useState)(null),[M,N]=(0,B.useState)(`addressed_only`),[P,F]=(0,B.useState)(t&&r?`goal`:`manager`),[re,ie]=(0,B.useState)(`async_inbox`),[I,ae]=(0,B.useState)(`topic_reply`),[L,oe]=(0,B.useState)(``),[se,ce]=(0,B.useState)(!1),[le,ue]=(0,B.useState)({}),[de,R]=(0,B.useState)(!1),[fe,pe]=(0,B.useState)(null),[me,he]=(0,B.useState)(null),[ge,_e]=(0,B.useState)(null),[ve,ye]=(0,B.useState)(null),[be,xe]=(0,B.useState)(!1),[Se,Ce]=(0,B.useState)(`loopx-workspace-bot`),[we,Te]=(0,B.useState)(`feishu`),[z,Ee]=(0,B.useState)(null),[De,Oe]=(0,B.useState)(!1),[ke,Ae]=(0,B.useState)(null),je=(0,B.useRef)(null),Me=(0,B.useRef)(null),Ne=(0,B.useRef)(!1);async function Pe(){m(!0),g(null);try{let[e,t]=await Promise.all([Lg(),Kg()]);u(e),f(t),S(t=>t||e.find(e=>e.reply_ready)?.app_ref||e.find(e=>e.ready)?.app_ref||e[0]?.app_ref||``)}catch(e){g(Ob(e,o(`lark.error.configuration`),o))}finally{m(!1)}}(0,B.useEffect)(()=>{Pe()},[]),(0,B.useEffect)(()=>{if(!t||p||Ne.current||!r)return;Ne.current=!0;let e=d.find(e=>e.goal_id===r);e?qe(e):Ke(n.find(e=>e.goalId===r))},[d,t,n,r,p]),(0,B.useEffect)(()=>{if(!y||!x||ge){O([]),te(``),k(!1),j(null);return}let e=!1;k(!0),j(null);let t=window.setTimeout(()=>{Wg(x,T).then(t=>{e||(O(t),te(e=>t.some(t=>t.chat_id===e)?e:t[0]?.chat_id??``))}).catch(t=>{e||(O([]),te(``),j(Ob(t,o(`lark.error.groupLoad`),o)))}).finally(()=>{e||k(!1)})},180);return()=>{e=!0,window.clearTimeout(t)}},[x,T,y,ge]),(0,B.useEffect)(()=>{if(!be||!z||[`ready`,`failed`,`cancelled`].includes(z.status))return;let e=!1,t=window.setTimeout(()=>{Bg(z.setup_id).then(async t=>{e||(Ee(t),t.verification_url&&Me.current!==t.verification_url&&(Me.current=t.verification_url,je.current&&!je.current.closed&&(je.current.location.href=t.verification_url)),t.status===`ready`&&(await Pe(),S(t.app_ref),ue({}),xe(!1)),t.status===`failed`&&Ae(t.error??o(`lark.error.appCreate`)))}).catch(t=>{e||Ae(Ob(t,o(`lark.error.setupPoll`),o))})},650);return()=>{e=!0,window.clearTimeout(t)}},[be,z]);let H=n.find(e=>e.goalId===C),Fe=H?.agentId?[{agentId:H.agentId,label:H.agentLabel??H.agentId}]:[],Ie=H?.agentLanes?.length?H.agentLanes:Fe,Le=Ie.some(e=>e.agentId===L),Re=[];se?Re=Ie.map(e=>({agentId:e.agentId,appRef:le[e.agentId]??x})):Le&&(Re=[{agentId:L,appRef:x}]);let ze=Re.map(e=>e.agentId),Be=!!ge||Re.length>0&&Re.every(e=>l.some(t=>t.app_ref===e.appRef&&t.reply_ready)),Ve=o(`lark.connect`);me?Ve=o(`lark.saveConnection`):se&&(Ve=o(`lark.connectAllAgentsAction`,{count:ze.length}));let He=l.find(e=>e.app_ref===x),Ue=D.find(e=>e.chat_id===ee),We=(0,B.useMemo)(()=>{let e=_.trim().toLocaleLowerCase();return e?d.filter(t=>[t.app_label,t.chat_name,t.goal_title,t.topic_name].some(t=>t.toLocaleLowerCase().includes(e))):d},[d,_]),Ge=(0,B.useMemo)(()=>d.filter(e=>Eb(e,o).state===`unverified`).length,[d,o]);function Ke(e){let i=e??n.find(e=>e.goalId===r)??n[0];he(null),_e(null),F(e||t?`goal`:`manager`),S(l.some(e=>e.app_ref===x)?x:l.find(e=>e.reply_ready)?.app_ref??l[0]?.app_ref??``),te(``),w(i?.goalId??``),oe(i?.agentId??``),ce(!1),ue({}),N(`addressed_only`),ie(`async_inbox`),ae(`topic_reply`),E(``),pe(null),b(!0)}function qe(e){he(e.goal_id),_e(e),F(e.conversation_kind??`goal`),S(e.app_ref),w(e.goal_id);let t=n.find(t=>t.goalId===e.goal_id),r=t?.agentLanes?.length?t.agentLanes:t?.agentId?[{agentId:t.agentId}]:[];oe(e.agent_id??(r.length===1?r[0].agentId:``)),ce(!1),ue({}),N(e.capture_scope),ie(e.ingress_mode===`direct_session`?`async_inbox`:e.ingress_mode),ae(e.reply_mode),E(e.chat_name),pe(null),b(!0)}function Je(){Ee(null),Ae(null),Me.current=null,xe(!0)}async function Ye(){if(!(De||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Se))){Oe(!0),Ae(null),Me.current=null,je.current=window.open(window.location.href,`_blank`);try{let e=await zg({appRef:Se,brand:we});Ee(e)}catch(e){je.current?.close(),Ae(Ob(e,o(`lark.error.setupStart`),o))}finally{Oe(!1)}}}async function Xe(){let e=z;if(xe(!1),je.current?.close(),e&&![`ready`,`failed`,`cancelled`].includes(e.status))try{await Vg(e.setup_id)}catch{}}async function Ze(){if(!(!x||!C||!ge&&!Ue||P===`goal`&&ze.length===0||de)){R(!0),pe(null);try{let e={...P===`manager`?{...ge?{connectionId:ge.connection_id}:{appRef:x,chatId:Ue.chat_id,chatName:Ue.chat_name}}:ge?{connectionId:ge.connection_id,agentId:L}:{agentBindings:Re,chatId:Ue.chat_id,chatName:Ue.chat_name},conversationKind:P,captureScope:P===`manager`?`addressed_only`:M,goalId:C,incomingMode:M===`configured_chat_all`?`all`:`mentions`,ingressMode:P===`manager`?`session_queue`:re,replyMode:I},t=await qg({...e,execute:!1});if(!t.ok)throw new Th(t.public_summary??t.blocker??o(`lark.error.bindPreview`),{error_code:t.blocker??`provider_api_failed`});let n=await qg({...e,execute:!0});if(!n.ok)throw new Th(n.public_summary??n.blocker??o(`lark.error.bind`),{error_code:n.blocker??`provider_api_failed`});b(!1),await Pe(),i?.()}catch(e){pe(Ob(e,o(`lark.error.bind`),o))}finally{R(!1)}}}async function Qe(e,t){if(ve!==t){ye(t);return}try{await Jg(e,t),ye(null),await Pe(),i?.()}catch(e){g(Ob(e,o(`lark.error.disconnect`),o))}}return(0,V.jsxs)(`section`,{className:`personal-lark-settings${e?` is-embedded`:``}`,"aria-label":o(`lark.configuration`),children:[e?null:(0,V.jsxs)(`header`,{className:`personal-lark-header`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:o(`settings.goalConnections`)}),(0,V.jsx)(`h1`,{children:`Lark`})]}),(0,V.jsx)(`button`,{"aria-label":o(`lark.closeSettings`),className:`personal-icon-button`,onClick:a,type:`button`,children:(0,V.jsx)($m,{size:18})})]}),(0,V.jsxs)(`nav`,{className:`personal-lark-tabs`,"aria-label":o(`lark.management`),children:[(0,V.jsxs)(`button`,{"aria-current":s===`apps`?`page`:void 0,onClick:()=>c(`apps`),type:`button`,children:[o(`lark.apps`),` `,(0,V.jsx)(`span`,{children:p?`…`:l.length})]}),(0,V.jsxs)(`button`,{"aria-current":s===`connections`?`page`:void 0,onClick:()=>c(`connections`),type:`button`,children:[o(`lark.connections`),` `,(0,V.jsx)(`span`,{children:p?`…`:d.length})]})]}),h?(0,V.jsx)(`p`,{className:`personal-notification-error`,children:h}):null,p?(0,V.jsxs)(`div`,{className:`personal-lark-loading`,children:[(0,V.jsx)(Cm,{className:`is-spinning`,size:18}),o(`lark.loading`)]}):null,!p&&s===`apps`?(0,V.jsxs)(`div`,{className:`personal-lark-apps`,children:[(0,V.jsxs)(`div`,{className:`personal-lark-app-toolbar`,children:[(0,V.jsx)(`span`,{children:o(`lark.reusableApps`,{count:l.length})}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:Je,type:`button`,children:[(0,V.jsx)(Pm,{size:16}),o(`lark.newApp`)]})]}),(0,V.jsxs)(`div`,{className:`personal-lark-app-grid`,children:[l.map(e=>(0,V.jsxs)(`article`,{className:`personal-lark-app-card`,children:[(0,V.jsx)(`span`,{className:`personal-lark-app-avatar`,children:(0,V.jsx)(Zp,{size:19})}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsxs)(`small`,{children:[e.brand,` · lark-cli profile`]})]}),(0,V.jsx)(`em`,{className:e.reply_ready?`is-ready`:`is-off`,children:e.reply_ready?o(`lark.autoReplyReady`):e.ready?o(`lark.needsMessagePermissions`):o(`lark.needsSetup`)}),(0,V.jsxs)(`p`,{children:[o(`lark.goalConnections`,{count:d.filter(t=>t.app_ref===e.app_ref).length}),e.ready&&!e.reply_ready?` · ${o(`lark.autoReplyUnavailable`)}`:``]})]},e.app_ref)),l.length===0?(0,V.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noProfiles`)}):null]})]}):null,!p&&s===`connections`?(0,V.jsxs)(`div`,{className:`personal-lark-connections`,children:[Ge>0?(0,V.jsxs)(`p`,{className:`personal-lark-route-readiness`,role:`status`,children:[(0,V.jsx)(Dm,{size:15}),o(`lark.routesUnverified`,{count:Ge})]}):null,(0,V.jsxs)(`div`,{className:`personal-lark-toolbar`,children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(zm,{size:16}),(0,V.jsx)(`input`,{"aria-label":o(`lark.searchConnections`),onChange:e=>v(e.target.value),placeholder:o(`lark.searchPlaceholder`),type:`search`,value:_})]}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:l.length===0||n.length===0,onClick:()=>Ke(),type:`button`,children:[(0,V.jsx)(Pm,{size:16}),o(`lark.connectApp`)]})]}),(0,V.jsxs)(`div`,{className:`personal-lark-table`,role:`table`,"aria-label":o(`lark.goalTopicConnections`),children:[(0,V.jsxs)(`div`,{className:`personal-lark-table-head`,role:`row`,children:[(0,V.jsx)(`span`,{children:o(`lark.connection`)}),(0,V.jsx)(`span`,{children:o(`common.goal`)}),(0,V.jsx)(`span`,{children:o(`lark.capture`)}),(0,V.jsx)(`span`,{children:o(`lark.processing`)}),(0,V.jsx)(`span`,{children:o(`common.actions`)})]}),We.map(e=>{let t=Eb(e,o);return(0,V.jsxs)(`div`,{className:`personal-lark-table-row`,role:`row`,children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.chat_name}),(0,V.jsxs)(`small`,{children:[e.app_label,` · `,t.label]}),(0,V.jsx)(`small`,{children:t.detail}),t.state===`unverified`?(0,V.jsxs)(`a`,{href:`https://open.feishu.cn/document/server-docs/im-v1/message/events/receive?lang=zh-CN`,rel:`noreferrer`,target:`_blank`,children:[(0,V.jsx)(fm,{size:12}),o(`lark.openEventSettings`)]}):null,Db(e)?(0,V.jsxs)(`a`,{href:Db(e)??void 0,rel:`noreferrer`,target:`_blank`,children:[(0,V.jsx)(fm,{size:12}),o(`lark.historyPermission`)]}):null]}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.goal_title}),(0,V.jsxs)(`small`,{children:[`# `,e.topic_name]})]}),(0,V.jsx)(`span`,{children:e.capture_scope===`addressed_only`?o(`lark.mentionsOnly`):o(`lark.allTopicMessages`)}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.conversation_kind===`manager`?o(`lark.managerConversation`):Tb(e.ingress_mode,o).label}),(0,V.jsx)(`small`,{children:e.conversation_kind===`manager`?o(`lark.managerConversationDescription`):e.agent_id??Tb(e.ingress_mode,o).detail})]}),(0,V.jsxs)(`span`,{className:`personal-lark-row-actions`,children:[(0,V.jsx)(`button`,{"aria-label":o(`lark.settingsConfigure`,{goal:e.goal_title}),onClick:()=>qe(e),type:`button`,children:(0,V.jsx)(Um,{size:15})}),(0,V.jsxs)(`button`,{"aria-label":o(`lark.settingsDisconnect`,{goal:e.goal_title}),className:ve===e.connection_id?`is-confirm`:``,onClick:()=>void Qe(e.goal_id,e.connection_id),type:`button`,children:[(0,V.jsx)(Qm,{size:15}),ve===e.connection_id?o(`common.confirm`):null]})]})]},e.connection_id)}),We.length===0?(0,V.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noConnections`)}):null]})]}):null,y?(0,V.jsx)(`div`,{className:`personal-lark-modal-backdrop`,role:`presentation`,children:(0,V.jsxs)(`section`,{"aria-labelledby":`connect-lark-title`,"aria-modal":`true`,className:`personal-lark-modal`,role:`dialog`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:`Goal Topic connection`}),(0,V.jsx)(`h2`,{id:`connect-lark-title`,children:o(me?`lark.editConnection`:`lark.connectApp`)})]}),(0,V.jsx)(`button`,{"aria-label":o(`lark.closeConnection`),onClick:()=>b(!1),type:`button`,children:(0,V.jsx)($m,{size:18})})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.conversationKind`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.conversationKind`),disabled:!!ge,value:P,onChange:e=>F(e.target.value),children:[(0,V.jsx)(`option`,{value:`manager`,children:o(`lark.managerConversation`)}),(0,V.jsx)(`option`,{value:`goal`,children:o(`lark.workerConversation`)})]})]}),P===`manager`?(0,V.jsx)(`p`,{children:o(`lark.managerConversationDescription`)}):null,ge?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,V.jsx)(`div`,{children:ge.app_label})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,V.jsx)(`div`,{children:ge.chat_name})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,V.jsx)(`div`,{children:ge.goal_title})]}),(0,V.jsx)(`small`,{children:o(`lark.editPreservesIdentity`)})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,V.jsx)(`select`,{"aria-label":o(`lark.appProfile`),disabled:p,onChange:e=>{e.target.value===`__register__`?Je():(S(e.target.value),ue({}))},value:x,children:p?(0,V.jsx)(`option`,{value:``,children:o(`lark.appLoading`)}):(0,V.jsxs)(V.Fragment,{children:[l.map(e=>(0,V.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref)),(0,V.jsx)(`option`,{value:`__register__`,children:o(`lark.registerAnother`)})]})}),(0,V.jsx)(`small`,{children:o(`lark.defaultAgentAppDescription`)})]}),He?.ready&&!He.reply_ready?(0,V.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.appPermissions`)}):null,(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,V.jsx)(`input`,{"aria-label":o(`lark.groupSearch`),onChange:e=>E(e.target.value),placeholder:o(`lark.groupSearch`),type:`search`,value:T}),ne?(0,V.jsxs)(`div`,{className:`personal-lark-group-state`,role:`status`,children:[(0,V.jsx)(Cm,{className:`is-spinning`,size:15}),o(`lark.groupLoading`)]}):null,!ne&&A?(0,V.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:A}):null,!ne&&!A&&D.length===0?(0,V.jsx)(`div`,{className:`personal-lark-group-state`,role:`status`,children:o(`lark.groupEmpty`)}):null,!ne&&!A&&D.length>0?(0,V.jsx)(`select`,{"aria-label":o(`lark.groupChat`),onChange:e=>te(e.target.value),value:ee,children:D.map(e=>(0,V.jsx)(`option`,{value:e.chat_id,children:e.chat_name},e.chat_id))}):null]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,V.jsx)(`select`,{"aria-label":o(`lark.bindGoal`),onChange:e=>{let t=e.target.value;w(t),oe(n.find(e=>e.goalId===t)?.agentId??``),ue({})},value:C,children:n.map(e=>(0,V.jsx)(`option`,{value:e.goalId,children:e.title},e.goalId))})]})]}),(0,V.jsxs)(`label`,{className:`personal-lark-check`,children:[(0,V.jsx)(`input`,{checked:!0,readOnly:!0,type:`checkbox`}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:o(`lark.createAutomatically`)}),(0,V.jsx)(`small`,{children:o(`lark.createAutomaticallyDescription`)})]})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.topicPreview`)}),(0,V.jsxs)(`div`,{className:`personal-lark-topic-preview`,children:[(0,V.jsx)(Dm,{size:15}),`# `,H?.title??H?.goalId??`Goal`]})]}),P===`goal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.captureScope`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.captureScope`),disabled:ge?.ingress_mode===`direct_session`,onChange:e=>N(e.target.value),value:M,children:[(0,V.jsx)(`option`,{value:`addressed_only`,children:o(`lark.captureAddressed`)}),(0,V.jsx)(`option`,{value:`configured_chat_all`,children:o(`lark.captureAll`)})]}),(0,V.jsx)(`small`,{children:o(`lark.captureScopeDescription`)})]}),(0,V.jsxs)(`fieldset`,{"aria-label":o(`lark.agentIngress`),className:`personal-lark-ingress`,children:[(0,V.jsx)(`legend`,{children:o(`lark.agentIngress`)}),(0,V.jsx)(`div`,{children:[`live_steering`,`session_queue`,`async_inbox`].map(e=>{let t=Tb(e,o);return(0,V.jsxs)(`label`,{className:re===e?`is-active`:``,children:[(0,V.jsx)(`input`,{"aria-label":t.label,checked:re===e,name:`lark-agent-ingress`,onChange:()=>ie(e),type:`radio`,value:e}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:t.label}),(0,V.jsx)(`small`,{children:t.detail})]})]},e)})})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.targetAgent`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.targetAgent`),disabled:!!ge?.agent_id,onChange:e=>oe(e.target.value),value:L,children:[Le?null:(0,V.jsx)(`option`,{disabled:!0,value:L,children:L?o(`lark.agentUnavailable`,{agent:L}):o(`lark.noAgentConfigured`)}),Ie.map(e=>(0,V.jsx)(`option`,{value:e.agentId,children:e.label===e.agentId?e.agentId:`${e.label} · ${e.agentId}`},e.agentId))]}),(0,V.jsx)(`small`,{children:o(`lark.targetAgentDescription`)})]}),!me&&Ie.length>1?(0,V.jsxs)(`label`,{"aria-label":o(`lark.connectAllAgents`),className:`personal-lark-check`,children:[(0,V.jsx)(`input`,{checked:se,onChange:e=>ce(e.target.checked),type:`checkbox`}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:o(`lark.connectAllAgents`)}),(0,V.jsx)(`small`,{children:o(`lark.connectAllAgentsDescription`,{count:Ie.length})})]})]}):null,!me&&se&&Ie.length>1?(0,V.jsxs)(`fieldset`,{"aria-label":o(`lark.agentApps`),className:`personal-lark-agent-apps`,children:[(0,V.jsx)(`legend`,{children:o(`lark.agentApps`)}),(0,V.jsx)(`small`,{children:o(`lark.agentAppsDescription`)}),(0,V.jsx)(`div`,{children:Ie.map(e=>(0,V.jsxs)(`label`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsx)(`small`,{children:e.agentId})]}),(0,V.jsx)(`select`,{"aria-label":o(`lark.agentAppSelection`,{agent:e.label}),onChange:t=>ue(n=>({...n,[e.agentId]:t.target.value})),value:le[e.agentId]??x,children:l.map(e=>(0,V.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref))})]},e.agentId))})]}):null,se&&Re.length>0&&!Be?(0,V.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.agentAppPermissions`)}):null,ze.length===0?(0,V.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:o(`lark.selectRegisteredAgent`)}):null]}):null,(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.replyMode`)}),(0,V.jsx)(`select`,{"aria-label":o(`lark.replyMode`),onChange:e=>ae(e.target.value),value:I,children:(0,V.jsx)(`option`,{value:`topic_reply`,children:o(`lark.topicReply`)})}),(0,V.jsx)(`small`,{children:o(`lark.replyModeDescription`)})]}),(0,V.jsxs)(`p`,{className:`personal-lark-cardinality`,children:[(0,V.jsx)(em,{size:15}),o(`lark.cardinality`)]}),fe?(0,V.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:fe}):null,(0,V.jsxs)(`footer`,{children:[(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>b(!1),type:`button`,children:o(`lark.cancel`)}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:p||!x||!ge&&(!He?.reply_ready||!ee)||P===`goal`&&(!Be||ze.length===0)||!C||de,onClick:()=>void Ze(),type:`button`,children:[de?(0,V.jsx)(Cm,{className:`is-spinning`,size:15}):null,Ve]})]})]})}):null,be?(0,V.jsx)(`div`,{className:`personal-lark-modal-backdrop is-setup`,role:`presentation`,children:(0,V.jsxs)(`section`,{"aria-labelledby":`new-lark-app-title`,"aria-modal":`true`,className:`personal-lark-modal personal-lark-setup-modal`,role:`dialog`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:o(`lark.reusableWorkspaceApp`)}),(0,V.jsx)(`h2`,{id:`new-lark-app-title`,children:o(`lark.newApp`)})]}),(0,V.jsx)(`button`,{"aria-label":o(`lark.closeCreate`),onClick:()=>void Xe(),type:`button`,children:(0,V.jsx)($m,{size:18})})]}),z?(0,V.jsxs)(`div`,{className:`personal-lark-setup-progress`,children:[(0,V.jsx)(`span`,{className:`personal-lark-setup-icon is-${z.status}`,children:z.status===`ready`?(0,V.jsx)(em,{size:22}):(0,V.jsx)(Cm,{className:z.status===`failed`?``:`is-spinning`,size:22})}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:z.status===`ready`?o(`lark.appCreated`):z.status===`failed`?o(`lark.appCreateFailed`):o(`lark.waitingFeishu`)}),(0,V.jsx)(`p`,{children:z.status===`waiting_for_feishu`?o(`lark.waitingFeishuDescription`):z.status===`starting`?o(`lark.waitingLink`):z.error})]}),z.verification_url?(0,V.jsxs)(`a`,{href:z.verification_url,rel:`noreferrer`,target:`_blank`,children:[(0,V.jsx)(fm,{size:15}),o(`lark.reopenFeishu`)]}):null]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{className:`personal-lark-setup-copy`,children:o(`lark.setupCopy`)}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.profileName`)}),(0,V.jsx)(`input`,{"aria-label":o(`lark.profileName`),autoComplete:`off`,onChange:e=>Ce(e.target.value),placeholder:`loopx-workspace-bot`,value:Se})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.region`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.region`),onChange:e=>Te(e.target.value),value:we,children:[(0,V.jsx)(`option`,{value:`feishu`,children:`Feishu`}),(0,V.jsx)(`option`,{value:`lark`,children:`Lark`})]})]}),Se&&!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Se)?(0,V.jsx)(`p`,{className:`personal-notification-error`,children:o(`lark.profileValidation`)}):null]}),ke?(0,V.jsx)(`p`,{className:`personal-notification-error`,children:ke}):null,(0,V.jsxs)(`footer`,{children:[(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void Xe(),type:`button`,children:o(`lark.cancel`)}),z?null:(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:De||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Se),onClick:()=>void Ye(),type:`button`,children:[De?(0,V.jsx)(Cm,{className:`is-spinning`,size:15}):(0,V.jsx)(fm,{size:15}),o(`lark.continueFeishu`)]})]})]})}):null]})}function Ab(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function jb(e,t,n){let r=Ab(t),i=Ab(n);return Object.fromEntries(e.fields.flatMap(({key:e,nullable:t})=>{let n=r[e],a=i[e];return Object.hasOwn(r,e)&&(n!=null||t&&n===null)?[[e,n]]:Object.hasOwn(i,e)&&a!=null?[[e,a]]:[]}))}function Mb(e,t){let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=new Set(e.fields.map(e=>e.key));return Object.keys(n).some(e=>!r.has(e))?null:n}function Nb(e,t,n){let r={...e,[t]:n},i=e.schedule;return t===`timezone`&&i&&typeof i==`object`&&`schema_version`in i&&i.schema_version===`periodic_report_schedule_v0`&&(r.schedule={...i,timezone:n}),r}function Pb({id:e,value:t,timezone:n,onChange:r}){let{locale:i}=qi(),a=i===`zh-CN`,o=t&&typeof t==`object`&&!Array.isArray(t)?t:null,s=String(o?.rrule??``).split(`;`).map(e=>e.split(`=`)),c=Object.fromEntries(s.filter(e=>e.length===2)),l=[`MO`,`TU`,`WE`,`TH`,`FR`,`SA`,`SU`],u=(e,t)=>e!==void 0&&/^\d+$/.test(e)&&Number(e)<=t,d=!o||o.schema_version===`periodic_report_schedule_v0`&&[`DAILY`,`WEEKLY`].includes(c.FREQ)&&o.timezone===n&&s.every(e=>e.length===2&&[`FREQ`,`BYDAY`,`BYHOUR`,`BYMINUTE`,`INTERVAL`].includes(e[0]))&&new Set(s.map(([e])=>e)).size===s.length&&u(c.BYHOUR,23)&&u(c.BYMINUTE??`0`,59)&&(c.FREQ===`WEEKLY`?l.includes(c.BYDAY):!c.BYDAY)&&(!c.INTERVAL||c.INTERVAL===`1`),f=a?[`星期一`,`星期二`,`星期三`,`星期四`,`星期五`,`星期六`,`星期日`]:[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`];function p(e){let t={FREQ:`WEEKLY`,BYDAY:`MO`,BYHOUR:`9`,BYMINUTE:`0`,...c,...e};r?.({schema_version:`periodic_report_schedule_v0`,schedule_id:o?.schedule_id??`report-schedule`,timezone:n,rrule:[`FREQ=${t.FREQ}`,...t.FREQ===`WEEKLY`?[`BYDAY=${t.BYDAY}`]:[],`BYHOUR=${t.BYHOUR}`,`BYMINUTE=${t.BYMINUTE}`].join(`;`)})}return(0,V.jsxs)(`div`,{className:`personal-report-schedule`,children:[(0,V.jsxs)(`label`,{className:`is-boolean`,htmlFor:e,children:[(0,V.jsx)(`span`,{children:a?`按日历汇报`:`Calendar reports`}),(0,V.jsx)(`input`,{id:e,type:`checkbox`,role:`switch`,checked:!!o,disabled:!r,onChange:e=>e.target.checked?p({}):r?.(null)})]}),o?(0,V.jsxs)(V.Fragment,{children:[d?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{htmlFor:`${e}-frequency`,children:[(0,V.jsx)(`span`,{children:a?`频率`:`Frequency`}),(0,V.jsxs)(`select`,{id:`${e}-frequency`,value:c.FREQ,disabled:!r,onChange:e=>p({FREQ:e.target.value}),children:[(0,V.jsx)(`option`,{value:`DAILY`,children:a?`每天`:`Daily`}),(0,V.jsx)(`option`,{value:`WEEKLY`,children:a?`每周`:`Weekly`})]})]}),c.FREQ===`WEEKLY`&&(0,V.jsxs)(`label`,{htmlFor:`${e}-day`,children:[(0,V.jsx)(`span`,{children:a?`星期`:`Weekday`}),(0,V.jsx)(`select`,{id:`${e}-day`,value:c.BYDAY,disabled:!r,onChange:e=>p({BYDAY:e.target.value}),children:l.map((e,t)=>(0,V.jsx)(`option`,{value:e,children:f[t]},e))})]}),(0,V.jsxs)(`label`,{htmlFor:`${e}-time`,children:[(0,V.jsxs)(`span`,{children:[a?`当地时间`:`Local time`,` (`,n,`)`]}),(0,V.jsx)(`input`,{id:`${e}-time`,type:`time`,required:!0,disabled:!r,value:`${(c.BYHOUR??`9`).padStart(2,`0`)}:${(c.BYMINUTE??`0`).padStart(2,`0`)}`,onChange:e=>{if(!/^\d{2}:\d{2}$/.test(e.target.value))return;let[t,n]=e.target.value.split(`:`);p({BYHOUR:t,BYMINUTE:n})}})]})]}):(0,V.jsx)(`p`,{role:`alert`,children:a?`此计划需在 JSON 模式中编辑;当前内容已保留。`:`Edit this schedule in JSON mode; its current value is preserved.`}),(0,V.jsx)(`p`,{children:a?`由现有唤醒检查到期计划;实际送达以回执为准。`:`Existing wakes check the schedule; delivery is confirmed by its receipt.`})]}):(0,V.jsx)(`p`,{children:a?`未设置日历计划;保持阶段结束时汇报。`:`No calendar schedule; report at validated stage boundaries.`})]})}function Fb({copy:e,field:t,id:n,onChange:r,value:i,timezone:a}){let o=e[t.key]?.label??t.label,s=!r;if(t.input_kind===`periodic_report_schedule`)return(0,V.jsx)(Pb,{id:n,value:i,timezone:a,onChange:r?e=>r(t.key,e):void 0});if(t.input_kind===`boolean`)return(0,V.jsxs)(`label`,{className:`is-boolean`,htmlFor:n,children:[(0,V.jsx)(`span`,{children:o}),(0,V.jsx)(`input`,{checked:i===!0,id:n,onChange:r?e=>r(t.key,e.target.checked):void 0,readOnly:s,role:`switch`,type:`checkbox`})]});if(t.input_kind===`select`)return(0,V.jsxs)(`label`,{htmlFor:n,children:[(0,V.jsx)(`span`,{children:o}),(0,V.jsxs)(`select`,{id:n,onChange:r?e=>r(t.key,e.target.value):void 0,value:typeof i==`string`?i:``,children:[(0,V.jsx)(`option`,{value:``}),(t.options??[]).map(e=>(0,V.jsx)(`option`,{value:e,children:e},e))]})]});if(t.input_kind===`string_list`)return(0,V.jsxs)(`label`,{htmlFor:n,children:[(0,V.jsx)(`span`,{children:o}),(0,V.jsx)(`textarea`,{id:n,onChange:r?e=>r(t.key,e.target.value.split(/\r?\n/u).filter(Boolean)):void 0,readOnly:s,rows:4,value:Array.isArray(i)?i.join(` -`):``})]});let c=t.input_kind===`number`;return(0,V.jsxs)(`label`,{htmlFor:n,children:[(0,V.jsx)(`span`,{children:o}),(0,V.jsx)(`input`,{id:n,max:t.maximum,min:t.minimum,onChange:r?e=>r(t.key,c?Number(e.target.value):e.target.value):void 0,readOnly:s,required:t.required,type:c?`number`:`text`,value:typeof i==`number`||typeof i==`string`?i:``})]})}function Ib({copy:e={},disabled:t=!1,editor:n,enabledAction:r,omitKeys:i=[],onChange:a,value:o}){let s=(0,B.useId)(),c=new Set(i);return(0,V.jsx)(`fieldset`,{className:`personal-capability-fields`,disabled:t,children:n.fields.filter(e=>!c.has(e.key)).map(t=>{let n=(0,V.jsx)(Fb,{copy:e,field:t,id:`${s}-${t.key.replace(/[^a-z0-9_-]/gi,`-`)}`,onChange:a,value:o[t.key],timezone:String(o.timezone??`UTC`)},t.key);return t.key===`enabled`&&t.input_kind===`boolean`?(0,V.jsxs)(`div`,{className:`personal-capability-enabled-row`,children:[n,r]},t.key):n})})}var Lb={en:{todo_replan_cadence:{displayName:`Goal review cadence`,description:`Configures the Goal review cadence.`},change_quality_qualification:{displayName:`Change quality qualification`,description:`Prepares a provider-neutral review packet, allows at most one policy-authorized safe-fix pass, and can require an exact-diff receipt.`},explore_graph:{displayName:`Explore Graph`,description:`Organizes bounded exploration as a typed evidence graph so branches, findings, and synthesis remain inspectable.`},explore_harness:{displayName:`Explore Harness`,description:`Selects a capability-owned planning and research harness profile for bounded multi-step exploration.`},lark_event_inbox:{displayName:`Lark event inbox`,description:`Receives provider events through a local-private inbox binding before LoopX projects them into governed work.`,readOnlyReason:`This capability requires a local-private inbox binding. Manage it in Lark settings or through the capability CLI.`},lark_kanban_heartbeat_sync:{displayName:`Lark Kanban heartbeat sync`,description:`Synchronizes accepted LoopX work state to the configured Lark Kanban heartbeat surface.`},local_authority_shadow:{displayName:`Local authority shadow`,description:`Observes post-commit Todo and task-lease state through the shared authority contract without taking write authority.`},multi_subagent:{displayName:`Adaptive child capacity`,description:`Sets bounded child-agent capacity and the public-safe responsibility domains in which parallel work may be delegated.`},peer_task_coordination:{displayName:`Registered-peer task coordination`,description:`Routes explicitly scoped peer-owned work to one registered coordinator without granting cross-owner mutation authority.`},periodic_report:{displayName:`Periodic reports`,description:`Turns validated Goal stage progress into a frozen report and automatically delivers it through the configured Goal Channel with exact readback.`},pull_request_review:{displayName:`Pull-request review`,description:`Ranks the public GitHub PR review queue with a machine-level default; it never grants GitHub, Todo, push, or merge authority.`},reward_memory:{displayName:`Reward Memory experiment`,description:`Configures a reviewed local-private provider binding for Goal-scoped Agent recall and evidence-backed outcome learning.`}},"zh-CN":{todo_replan_cadence:{displayName:`Goal 复核周期`,description:`配置 Goal 的复核周期。`},change_quality_qualification:{displayName:`变更质量验证`,description:`生成与 Provider 无关的审阅包,最多允许一次策略授权的安全修复,并可要求精确 diff 回执。`},explore_graph:{displayName:`探索图谱`,description:`把有界探索组织为 typed 证据图,让探索分支、发现与综合结论都可检查、可追溯。`},explore_harness:{displayName:`探索 Harness`,description:`为有界的多步探索选择由能力负责的规划与研究 Harness profile。`},lark_event_inbox:{displayName:`飞书事件收件箱`,description:`通过本机私有收件箱接收 Provider 事件,再由 LoopX 将其投影为受治理的工作。`,readOnlyReason:`此能力依赖本机私有的收件箱绑定,请在飞书设置或 capability CLI 中管理。`},lark_kanban_heartbeat_sync:{displayName:`飞书看板心跳同步`,description:`把 LoopX 已接受的工作状态同步到配置好的飞书看板心跳界面。`},local_authority_shadow:{displayName:`本地 Authority 影子观测`,description:`通过共享 Authority contract 观测提交后的 Todo 与 task lease 状态,但不取得写入权。`},multi_subagent:{displayName:`自适应子 Agent 容量`,description:`限定子 Agent 容量与可公开的职责域,只有落在这些边界内的工作才能并行委派。`},peer_task_coordination:{displayName:`已注册 Peer 任务协调`,description:`把明确限定的 Peer 工作路由给一个已注册协调者,不授予跨 Owner 修改权限。`},periodic_report:{displayName:`周期报告`,description:`把经过验证的 Goal 阶段进展整理为冻结报告,并通过配置的 Goal Channel 自动发送和精确回读。`},pull_request_review:{displayName:`Pull-request Review`,description:`配置公开 GitHub PR 审阅队列的本机默认排序;不会授予 GitHub、Todo、push 或 merge 权限。`},reward_memory:{displayName:`Reward Memory 实验`,description:`为 Goal 内 Agent 的召回与证据化结果学习配置经过审阅的本机私有 Provider 绑定。`}}},Rb={en:{completed_todos:{label:`Completed Todos between Goal reviews`,description:`Machine default or explicit Goal override, from 1 to 5.`},allowed_domains:{label:`Allowed responsibility domains`,description:`Enter one bounded, public-safe domain per line.`},coordinator_agent_id:{label:`Coordinator Agent`,description:`Use an already registered Agent id; leave blank to disable coordination.`},enabled:{label:`Enabled`},model:{label:`Child model`,description:`For example gpt-5.6-luna. Blank clears the child model preference.`},reasoning_effort:{label:`Child reasoning effort`,description:`For example max; the host must support this model and effort.`},max_children:{label:`Maximum children`,description:`Hard upper bound for concurrently delegated child work.`},profile:{label:`Planner profile`,description:`Select one registered Explore Harness profile.`},profile_preset:{label:`Report profile`,description:`Capability-owned report profile, such as weekly-progress.`},review_priority:{label:`Review priority`,description:`Choose whether other developers' PRs or the authenticated reviewer's own PRs are ranked first.`},route_ref:{label:`Goal Channel route`,description:`Public route alias only; credentials and provider identifiers stay outside this form.`},safe_fix:{label:`Allow one bounded safe-fix pass`},strict_receipt:{label:`Require an exact-diff receipt`},timezone:{label:`Timezone`,description:`Use an IANA timezone, for example Asia/Shanghai.`},schedule:{label:`Calendar reports`,description:`Optional daily or weekly reports; no schedule preserves stage-only delivery.`},config_path:{label:`Local-private configuration path`,description:`Repo-relative ignored JSON under .loopx/config/. Leave blank to retain the current binding; the path is never returned.`},enabled_agents:{label:`Enabled Goal Agents`,description:`Enter one registered Goal-local Agent id per line. A private binding currently accepts exactly one Agent.`}},"zh-CN":{completed_todos:{label:`两次 Goal 复核间的已完成 Todo 数`,description:`可设置 1–5;机器默认值可被 Goal 显式覆盖。`},allowed_domains:{label:`允许的职责域`,description:`每行填写一个有边界、可公开的职责域。`},coordinator_agent_id:{label:`协调 Agent`,description:`填写一个已经注册的 Agent ID;留空表示关闭协调。`},enabled:{label:`启用`},model:{label:`子 Agent 模型`,description:`例如 gpt-5.6-luna;留空清除模型偏好。`},reasoning_effort:{label:`子 Agent 推理档位`,description:`例如 max;宿主须支持所选模型与档位。`},max_children:{label:`最大子 Agent 数`,description:`可同时委派的子任务硬上限。`},profile:{label:`规划 Profile`,description:`选择一个已注册的 Explore Harness profile。`},profile_preset:{label:`报告 Profile`,description:`由该能力管理的报告 profile,例如 weekly-progress。`},review_priority:{label:`审阅优先级`,description:`选择先排其他开发者的 PR,还是先排当前已认证审阅者自己的 PR。`},route_ref:{label:`Goal Channel 路由`,description:`只填写公开 route alias;凭据与 Provider 标识不会进入此表单。`},safe_fix:{label:`允许一次有界安全修复`},strict_receipt:{label:`要求精确 diff 回执`},timezone:{label:`时区`,description:`使用 IANA 时区,例如 Asia/Shanghai。`},schedule:{label:`日历汇报`,description:`可选每日或每周计划;未设置时保持阶段结束汇报。`},config_path:{label:`本机私有配置路径`,description:`填写 .loopx/config/ 下、相对仓库且被忽略的 JSON;留空保留当前绑定,路径不会被回传。`},enabled_agents:{label:`已启用的 Goal Agent`,description:`每行填写一个已注册的 Goal 内 Agent ID;私有绑定当前只接受一个 Agent。`}}};function zb(e,t){let n=Lb[t][e.capability_id];return n?{...e,display_name:n.displayName,description:n.description,configuration_editor:{...e.configuration_editor,...n.readOnlyReason?{read_only_reason:n.readOnlyReason}:{}}}:e}function Bb(e){return Rb[e]}Object.freeze(Object.keys(Lb.en).sort());function Vb(e,t){return e.available_scopes.includes(t)&&(t!==`machine`||!!e.machine_namespace)&&e.configuration_editor.editable&&e.configuration_editor.writable_scopes.includes(t)}function Hb({values:e,t}){return(0,V.jsxs)(`details`,{className:`personal-capability-raw-values`,children:[(0,V.jsx)(`summary`,{children:t(`capabilities.rawJson`)}),(0,V.jsx)(`div`,{className:`personal-capability-value-grid`,children:e.map(({label:e,value:t})=>(0,V.jsxs)(`section`,{children:[(0,V.jsx)(`strong`,{children:e}),(0,V.jsx)(`pre`,{children:t?JSON.stringify(t,null,2):`—`})]},e))})]})}function Ub({source:e,t}){return e?(0,V.jsxs)(`p`,{className:`personal-capability-effective-source`,children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:15}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:t(`capabilities.effectiveSource`)}),t(`capabilities.source.${e}`)]})]}):null}function Wb({available:e,description:t,t:n}){return e?null:(0,V.jsxs)(`section`,{className:`personal-capability-editor-status is-read-only`,children:[(0,V.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:n(`capabilities.readOnly`)}),(0,V.jsx)(`p`,{children:t})]})]})}function Gb(e){return e.availability?.includes(`experimental`)?4:e.capability_id===`multi_subagent`?3:e.configuration_editor.writable_scopes.length===0||e.availability===`supported_explicit_opt_in`?2:e.availability===`supported_explicit_override`?0:1}function Kb(e,t){return[...e].sort((e,n)=>{let r=Gb(e)-Gb(n);if(r!==0)return r;let i=zb(e,t),a=zb(n,t);return i.display_name.localeCompare(a.display_name,t)||e.capability_id.localeCompare(n.capability_id)})}function qb({capabilities:e,locale:t,onSelect:n,scope:r,selectedCapabilityId:i,t:a}){return(0,V.jsx)(`nav`,{"aria-label":a(r===`goal`?`capabilities.catalog`:`machine.capabilityCatalog`),className:`personal-capability-list`,tabIndex:0,children:Kb(e,t).map(e=>{let o=zb(e,t);return(0,V.jsxs)(`button`,{"aria-current":i===o.capability_id?`page`:void 0,onClick:()=>n(o.capability_id),type:`button`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:o.display_name})}),(0,V.jsx)(`em`,{children:a(o.available_scopes.includes(r)?r===`goal`?`capabilities.goalScope`:`capabilities.machineScope`:r===`machine`?`capabilities.goalScope`:`capabilities.machineScope`)})]},o.capability_id)})})}function Jb({capability:e,locale:t,source:n}){let{t:r}=qi(),i=zb(e,t);return(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`span`,{className:`personal-settings-icon`,children:(0,V.jsx)(Gm,{"aria-hidden":!0,size:18})}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{className:`personal-capability-heading-row`,children:[(0,V.jsx)(`h2`,{children:i.display_name}),(0,V.jsx)(Ub,{source:n,t:r})]}),e.context_contribution&&(0,V.jsxs)(`details`,{className:`personal-capability-help`,"data-testid":`capability-context-phases`,children:[(0,V.jsx)(`summary`,{children:t===`zh-CN`?`主 Agent 协作指导`:`Coordinator workflow guidance`}),(0,V.jsx)(`p`,{children:t===`zh-CN`?`随能力开启。支持以下阶段;此处展示能力范围,不能证明某次运行已读取或采纳。`:`Enabled with this capability. These are supported phases, not proof that a run read or adopted the guidance.`}),(0,V.jsx)(`dl`,{children:e.context_contribution.supported_phases.map(e=>(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:(0,V.jsx)(`code`,{children:e})}),(0,V.jsx)(`dd`,{children:Yb[e][t===`zh-CN`?`zh`:`en`]})]},e))}),(0,V.jsx)(`p`,{children:t===`zh-CN`?`LoopX Turn 在请求与结果中提供上下文;原生工具入口由 LoopX skill 调用同一只读接口。执行与采纳需另看运行证据。`:`LoopX Turn includes context in requests and results. For native tools, the LoopX skill reads the same interface. Execution and adoption require run evidence.`})]}),(0,V.jsxs)(`details`,{className:`personal-capability-help`,children:[(0,V.jsx)(`summary`,{children:t===`zh-CN`?`配置说明`:`Configuration help`}),(0,V.jsx)(`p`,{children:i.description}),(0,V.jsx)(`dl`,{children:e.configuration_editor.fields.map(e=>{let n=Bb(t)[e.key],r=n?.description??e.description;return r?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:n?.label??e.label}),(0,V.jsx)(`dd`,{children:r})]},e.key):null})})]},e.capability_id)]})]})}var Yb={before_plan:{zh:`规划前:识别独立问题并保留主 Agent 的核验与整合职责。`,en:`Before planning: identify independent questions and retain coordinator validation and integration.`},before_delegate:{zh:`委派前:明确子任务边界、模型偏好及预期证据。`,en:`Before delegation: specify task boundaries, model preferences and expected evidence.`},after_delegate_result:{zh:`回收后:核验结果,说明采纳决定并关联计划与成果。`,en:`After results: validate evidence, explain acceptance and link plans and deliverables.`}};function Xb({goalId:e,onApplied:t,selected:n,t:r}){let[i,a]=(0,B.useState)({busy:null,draft:{},partialWrite:null,preview:null}),[o,s]=(0,B.useState)(null),[c,l]=(0,B.useState)(`guided`),[u,d]=(0,B.useState)(``),f=(0,B.useMemo)(()=>n?Mb(n.configuration_editor,u):null,[n,u]),p=c===`guided`||f!==null;(0,B.useEffect)(()=>{l(`guided`),d(``),a({busy:null,draft:jb(n?.configuration_editor??{fields:[]},n?.current??n?.effective_configuration?.configuration??n?.default,n?.default),partialWrite:null,preview:null}),s(null)},[n]);async function m(t){if(!(!n||i.busy||!p)){a(e=>({...e,busy:`preview`,partialWrite:null})),s(null);try{let r=await Eg(e,n.capability_id,t);a(e=>({...e,preview:r}))}catch(e){s(e instanceof Error?e.message:r(`capabilities.previewFailed`))}finally{a(e=>({...e,busy:null}))}}}async function h(){if(!(!n||!i.preview||i.busy||!p)){a(e=>({...e,busy:`apply`})),s(null);try{let r=jb(n.configuration_editor,i.draft,n.default),o=await Dg(e,n.capability_id,i.preview.action===`delete`?null:r,i.preview.plan_revision);a(e=>({...e,partialWrite:o.status===`partial_write`?o:null,preview:null})),o.status!==`partial_write`&&t()}catch(e){a(e=>({...e,preview:null})),s(e instanceof Error?e.message:r(`capabilities.applyFailed`))}finally{a(e=>({...e,busy:null}))}}}function g(e,t){a(r=>({...r,draft:n?.capability_id===`periodic_report`?Nb(r.draft,e,t):{...r.draft,[e]:t},preview:null})),s(null)}function _(e){if(!n||i.busy)return;d(e);let t=Mb(n.configuration_editor,e);a(e=>({...e,preview:null,draft:t?jb(n.configuration_editor,t,n.default):e.draft})),s(null)}function v(){i.busy||!p||(c===`guided`&&d(JSON.stringify(i.draft,null,2)),l(c===`guided`?`json`:`guided`),a(e=>({...e,preview:null})))}return{apply:h,changeDraft:g,changeJson:_,changeMode:v,editorMode:c,jsonDraft:u,jsonValid:p,error:o,mutation:i,preview:m}}function Zb({mutationError:e,onApplied:t,partialWrite:n,preview:r}){let{t:i}=qi();return(0,V.jsxs)(V.Fragment,{children:[e?(0,V.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:e}):null,n?(0,V.jsxs)(`section`,{"aria-live":`polite`,className:`personal-capability-recovery`,children:[(0,V.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:i(`capabilities.partialWrite`)}),(0,V.jsx)(`p`,{children:i(`capabilities.partialWriteDescription`)}),(0,V.jsx)(`small`,{children:n.recommended_action})]}),(0,V.jsxs)(`button`,{onClick:t,type:`button`,children:[(0,V.jsx)(Im,{"aria-hidden":!0,size:15}),i(`capabilities.refreshSource`)]})]}):null,r?(0,V.jsxs)(`section`,{className:`personal-capability-preview`,"aria-label":i(`capabilities.preview`),children:[(0,V.jsx)(`strong`,{children:i(`capabilities.preview`)}),(0,V.jsx)(`span`,{children:i(`machine.action.${r.action}`)}),(0,V.jsx)(`small`,{children:i(`capabilities.previewLocked`)})]}):null]})}function Qb({catalog:e,goalId:t,onApplied:n}){let{locale:r,t:i}=qi(),a=(0,B.useMemo)(()=>Kb(e.capabilities,r),[e.capabilities,r]),[o,s]=(0,B.useState)(()=>a[0]?.capability_id??``),c=(0,B.useMemo)(()=>a.find(e=>e.capability_id===o)??a[0],[a,o]),l=(0,B.useMemo)(()=>c?zb(c,r):void 0,[r,c]),{apply:u,changeDraft:d,changeJson:f,changeMode:p,editorMode:m,jsonDraft:h,jsonValid:g,error:_,mutation:v,preview:y}=Xb({goalId:t,onApplied:n,selected:l,t:i}),{busy:b,draft:x,partialWrite:S,preview:C}=v;if(!c||!l)return(0,V.jsx)(`p`,{className:`personal-capability-empty`,children:i(`capabilities.empty`)});let w=l.available_scopes.includes(`goal`),T=Vb(l,`goal`),E=l.configuration_editor.read_only_reason??i(w?`capabilities.previewOnly`:`capabilities.machineOnly`);async function D(){if(!l||!T||b||!g)return;let e=jb(l.configuration_editor,x,l.default);await y(e)}async function O(){!T||b||await y(null)}return(0,V.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,V.jsx)(qb,{capabilities:e.capabilities,locale:r,onSelect:s,scope:`goal`,selectedCapabilityId:l.capability_id,t:i}),(0,V.jsxs)(`article`,{"aria-label":l.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,V.jsx)(Jb,{capability:c,locale:r,source:l.effective_configuration?.source}),(0,V.jsx)(Wb,{available:T,t:i,description:E}),T?(0,V.jsxs)(V.Fragment,{children:[m===`json`||!l.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,V.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,V.jsxs)(`button`,{disabled:!!b||!g,onClick:p,type:`button`,children:[(0,V.jsx)(sm,{"aria-hidden":!0,size:14}),i(m===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,m===`guided`?(0,V.jsx)(`section`,{className:`personal-capability-field-summary`,children:(0,V.jsx)(Ib,{disabled:!!b,copy:Bb(r),editor:l.configuration_editor,onChange:d,value:x,enabledAction:(0,V.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:p,type:`button`,children:[(0,V.jsx)(sm,{"aria-hidden":!0,size:14}),i(`machine.editJson`)]})})}):(0,V.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`goal-configuration-json`,children:[(0,V.jsx)(`span`,{children:i(`capabilities.jsonConfiguration`)}),(0,V.jsx)(`textarea`,{id:`goal-configuration-json`,"aria-describedby":`goal-configuration-json-help`,disabled:!!b,onChange:e=>f(e.target.value),rows:12,spellCheck:!1,value:h}),(0,V.jsx)(`small`,{id:`goal-configuration-json-help`,children:i(`capabilities.jsonHelp`)}),g?null:(0,V.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:i(`capabilities.jsonInvalid`)})]})]}):null,(0,V.jsx)(Zb,{mutationError:_,onApplied:n,partialWrite:S,preview:C}),T?(0,V.jsxs)(`footer`,{className:`personal-capability-actions`,children:[l.current&&l.available_scopes.includes(`machine`)?(0,V.jsx)(`button`,{disabled:!!b||!g,onClick:()=>void O(),type:`button`,children:i(`capabilities.restoreInheritance`)}):null,(0,V.jsx)(`button`,{disabled:!!b||!g,onClick:()=>void D(),type:`button`,children:i(b===`preview`?`common.loading`:`capabilities.previewChanges`)}),(0,V.jsx)(`button`,{className:`is-primary`,disabled:!!b||!C||!g,onClick:()=>void u(),type:`button`,children:i(b===`apply`?`common.loading`:`capabilities.applyPreview`)})]}):null,(0,V.jsx)(Hb,{values:[{label:i(`capabilities.goalValue`),value:l.current},{label:i(l.machine_current?`capabilities.machineValue`:`capabilities.defaultValue`),value:l.machine_current??l.default}],t:i},c.capability_id)]})]})}function $b({goalId:e}){let{t}=qi(),[n,r]=(0,B.useState)(null),[i,a]=(0,B.useState)(null),[o,s]=(0,B.useState)(!1);function c(){e&&(s(!0),a(null),Tg(e).then(r).catch(e=>a(e instanceof Error?e.message:t(`capabilities.loadFailed`))).finally(()=>s(!1)))}return(0,B.useEffect)(c,[e]),e?o&&!n?(0,V.jsxs)(`p`,{"aria-live":`polite`,className:`personal-capability-empty`,children:[(0,V.jsx)(Cm,{className:`personal-spin`,size:18}),t(`capabilities.loading`)]}):i?(0,V.jsxs)(`section`,{className:`personal-capability-error`,role:`alert`,children:[(0,V.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:t(`capabilities.loadFailed`)}),(0,V.jsx)(`small`,{children:i})]}),(0,V.jsxs)(`button`,{onClick:c,type:`button`,children:[(0,V.jsx)(Im,{"aria-hidden":!0,size:15}),t(`capabilities.retry`)]})]}):n?(0,V.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":n.revision,children:[(0,V.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:17}),t(`capabilities.atomicOverride`)]}),(0,V.jsx)(`p`,{children:t(`capabilities.atomicOverrideDescription`)})]}),(0,V.jsx)(Qb,{catalog:n.capability_catalog,goalId:e,onApplied:c})]}):null:(0,V.jsx)(`p`,{className:`personal-capability-empty`,children:t(`capabilities.chooseGoal`)})}function ex(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function tx(e,t){let n=t?.machine_namespace;return n?e?.machine_configuration?.namespaces[n]:void 0}function nx(e,t,n){return{...ex(e.default),...ex(t),...n}}function rx(e,t){for(let n of e.configuration_editor.fields){let e=t[n.key];if(n.required&&(e==null||e===``))return!1}return e.capability_id===`periodic_report`&&t.enabled===!0?!!(String(t.profile_preset??``).trim()&&String(t.route_ref??``).trim()&&String(t.timezone??``).trim()):!0}function ix(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:null}catch{return null}}function ax(e){return e?e===`absent`?e:e.replace(/^sha256:/,``).slice(0,12):`—`}function ox(){let{locale:e,t}=qi(),[n,r]=(0,B.useState)(null),[i,a]=(0,B.useState)(``),[o,s]=(0,B.useState)({}),[c,l]=(0,B.useState)(`{}`),[u,d]=(0,B.useState)(`guided`),[f,p]=(0,B.useState)(null),[m,h]=(0,B.useState)(`upsert`),[g,_]=(0,B.useState)(null),[v,y]=(0,B.useState)(null),[b,x]=(0,B.useState)(`load`),[S,C]=(0,B.useState)(null),[w,T]=(0,B.useState)(null),E=(0,B.useMemo)(()=>Kb(n?.capability_catalog.capabilities??[],e),[n,e]),D=E.find(e=>e.capability_id===i)??E.find(e=>Vb(e,`machine`))??E[0],O=D?zb(D,e):void 0,ee=tx(n,O),te=!!(O?.machine_namespace&&ee),ne=!!(O&&Vb(O,`machine`)),k=(0,B.useMemo)(()=>ix(c),[c]),A=O?u===`json`?k:nx(O,ee,o):null,j=!!(O&&(u===`json`?k:rx(O,A??{})));async function M(){r(await wg())}(0,B.useEffect)(()=>{let e=!0;return wg().then(t=>{e&&r(t)}).catch(n=>{e&&C(n instanceof Error?n.message:t(`machine.loadError`))}).finally(()=>{e&&x(null)}),()=>{e=!1}},[t]),(0,B.useEffect)(()=>{if(!O)return;let e=tx(n,O),t=jb(O.configuration_editor,e??O.default,O.default),r=nx(O,e,t);s(t),l(JSON.stringify(r,null,2)),d(ne?`guided`:`json`),p(null),h(`upsert`),y(null)},[n,i,e]);function N(e,t){s(n=>O?.capability_id===`periodic_report`?Nb(n,e,t):{...n,[e]:t}),p(null),h(`upsert`),C(null),T(null)}function P(e){if(O){if(e===`json`)l(JSON.stringify(nx(O,ee,o),null,2));else if(k)s(jb(O.configuration_editor,k,O.default));else{C(t(`machine.jsonInvalid`));return}d(e),p(null),h(`upsert`),C(null)}}async function F(){if(!(!ne||!O?.machine_namespace||!A||!j||b)){x(`preview`),C(null),T(null);try{h(`upsert`),p(await Og(O.machine_namespace,A))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function re(){if(!(!ne||!O?.machine_namespace||!te||b)){x(`preview`),C(null),T(null);try{h(`remove`),p(await Ag(O.machine_namespace))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function ie(){if(!ne||!O?.machine_namespace||!f||b||m===`upsert`&&!A)return;x(`apply`),C(null);let e=m;try{let n=e===`remove`?await jg(O.machine_namespace,f.plan_revision):await kg(O.machine_namespace,A,f.plan_revision);_(n),p(null),h(`upsert`),y(null),await M(),T(n.status===`applied`?t(e===`remove`?`machine.removed`:`machine.applied`):t(`machine.unchanged`))}catch(e){p(null),h(`upsert`),C(e instanceof Error?e.message:t(`machine.applyError`))}finally{x(null)}}async function I(){if(!(!g?.transaction_id||b)){x(`rollback-preview`),C(null);try{y(await Mg(g.transaction_id))}catch(e){C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}async function ae(){if(!(!g?.transaction_id||!v||b)){x(`rollback`),C(null);try{await Ng(g.transaction_id,v.plan_revision),_(null),y(null),p(null),await M(),T(t(`machine.rolledBack`))}catch(e){y(null),C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}return b===`load`?(0,V.jsx)(`div`,{className:`personal-machine-loading`,role:`status`,children:t(`common.loading`)}):O?(0,V.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":n?.revision,children:[(0,V.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:17}),t(`machine.liveDefault`)]}),(0,V.jsx)(`p`,{children:t(`machine.liveDefaultDescription`)})]}),(0,V.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,V.jsx)(qb,{capabilities:E,locale:e,onSelect:a,scope:`machine`,selectedCapabilityId:O.capability_id,t}),(0,V.jsxs)(`article`,{"aria-label":O.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,V.jsx)(Jb,{capability:D,locale:e,source:O.available_scopes.includes(`machine`)?te?`machine_default`:`capability_default`:void 0}),(0,V.jsx)(Wb,{available:ne,t,description:O.available_scopes.includes(`machine`)?t(`machine.editorUnavailableDescription`):t(`machine.goalOnly`)}),O.capability_id===`periodic_report`?(0,V.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:ee?.schedule?e===`zh-CN`?`日历与阶段汇报`:`Calendar and stage reports`:t(`machine.periodicReportActivation`)}),(0,V.jsx)(`p`,{children:ee?.schedule?ee.enabled===!0?e===`zh-CN`?`已配置日历计划,由现有唤醒检查;是否送达请核对报告回执。`:`A calendar schedule is configured and checked by existing wakes. Verify delivery in the report receipt.`:e===`zh-CN`?`日历计划已保存;启用此能力后才会检查和投递。`:`The schedule is saved; enable this capability to check and deliver reports.`:t(`machine.periodicReportActivationDescription`)})]})]}):null,O.capability_id===`change_quality_qualification`?(0,V.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:t(`machine.changeQualityActivation`)}),(0,V.jsx)(`p`,{children:t(`machine.changeQualityActivationDescription`)})]})]}):null,O.capability_id===`todo_replan_cadence`?(0,V.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:t(`machine.replanCadenceActivation`)}),(0,V.jsx)(`p`,{children:t(`machine.replanCadenceActivationDescription`)})]})]}):null,O.capability_id===`pull_request_review`?(0,V.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:e===`zh-CN`?`只改变队列排序`:`Queue ordering only`}),(0,V.jsx)(`p`,{children:e===`zh-CN`?`默认先审阅其他开发者的 PR;选择 owner-first 才会优先当前已认证审阅者自己的 PR。此配置不会发布 review、写 Todo、push 或 merge。`:`The default reviews other developers' PRs first; choose owner-first only when the authenticated reviewer's own PRs should lead. This setting never posts a review, writes Todos, pushes, or merges.`})]})]}):null,ne?(0,V.jsxs)(V.Fragment,{children:[u===`json`||!O.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,V.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,V.jsxs)(`button`,{onClick:()=>P(u===`guided`?`json`:`guided`),type:`button`,children:[(0,V.jsx)(sm,{"aria-hidden":!0,size:14}),t(u===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,u===`guided`?(0,V.jsxs)(`section`,{className:`personal-capability-field-summary`,children:[(0,V.jsx)(Ib,{copy:Bb(e),disabled:!!b,editor:O.configuration_editor,onChange:N,value:o,enabledAction:(0,V.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:()=>P(`json`),type:`button`,children:[(0,V.jsx)(sm,{"aria-hidden":!0,size:14}),t(`machine.editJson`)]})}),j?null:(0,V.jsx)(`p`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.requiredFields`)})]}):(0,V.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`machine-configuration-json`,children:[(0,V.jsx)(`span`,{children:t(`machine.jsonConfiguration`)}),(0,V.jsx)(`textarea`,{"aria-describedby":`machine-configuration-json-help`,disabled:!!b,id:`machine-configuration-json`,onChange:e=>{l(e.target.value),p(null),C(null)},rows:12,spellCheck:!1,value:c}),(0,V.jsx)(`small`,{id:`machine-configuration-json-help`,children:t(`machine.jsonConfigurationHelp`)}),k?null:(0,V.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.jsonInvalid`)})]})]}):null,S?(0,V.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:S}):null,w?(0,V.jsxs)(`p`,{className:`personal-machine-notice`,role:`status`,"aria-live":`polite`,children:[(0,V.jsx)(em,{"aria-hidden":!0,size:16}),w]}):null,f?(0,V.jsxs)(`section`,{"aria-label":t(`machine.preview`),className:`personal-machine-preview`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:t(`machine.preview`)}),(0,V.jsx)(`span`,{children:t(`machine.action.${f.action}`)})]}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`machine.currentRevision`)}),(0,V.jsx)(`dd`,{title:f.current_revision,children:ax(f.current_revision)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`machine.desiredRevision`)}),(0,V.jsx)(`dd`,{title:f.desired_revision,children:ax(f.desired_revision)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`machine.changedNamespaces`)}),(0,V.jsx)(`dd`,{children:f.changed_namespaces.join(`, `)||t(`common.none`)})]})]}),(0,V.jsx)(`p`,{children:t(`machine.previewLocked`)})]}):null,g?.rollback_available&&g.transaction_id?(0,V.jsxs)(`section`,{className:`personal-machine-rollback`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:t(`machine.rollbackAvailable`)}),(0,V.jsx)(`p`,{children:t(v?`machine.rollbackPreviewDescription`:`machine.rollbackDescription`)})]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!!b||!!(v&&!v.rollback_allowed),onClick:()=>void(v?ae():I()),type:`button`,children:[(0,V.jsx)(Lm,{"aria-hidden":!0,size:15}),t(b===`rollback`||b===`rollback-preview`?`common.loading`:v?`machine.confirmRollback`:`machine.previewRollback`)]})]}):null,ne?(0,V.jsxs)(`footer`,{className:`personal-capability-actions`,children:[te?(0,V.jsxs)(`button`,{className:`is-danger`,disabled:!!b,onClick:()=>void re(),type:`button`,children:[(0,V.jsx)(Xm,{"aria-hidden":!0,size:15}),t(`machine.previewRemoval`)]}):null,(0,V.jsx)(`button`,{disabled:!!b||!j,onClick:()=>void F(),type:`button`,children:t(b===`preview`?`common.loading`:`machine.previewChanges`)}),(0,V.jsx)(`button`,{className:`is-primary`,disabled:!!b||!f,onClick:()=>void ie(),type:`button`,children:t(b===`apply`?`common.loading`:`machine.applyPreview`)})]}):null,O.available_scopes.includes(`machine`)?(0,V.jsx)(Hb,{values:[{label:t(`machine.currentValue`),value:ee},{label:t(`capabilities.defaultValue`),value:O.default}],t},O.capability_id):null]})]})]}):(0,V.jsx)(`p`,{className:`personal-capability-empty`,children:t(`machine.capabilityEmpty`)})}var sx={appearance:Am,capabilities:Gm,language:bm,lark:Um,machine:Vm};function cx({focusGoalConnection:e=!1,goals:t,initialGoalId:n,initialTab:r=`lark`,onChanged:i,onClose:a,onThemeChange:o,theme:s}){let{locale:c,setLocale:l,t:u}=qi(),[d,f]=(0,B.useState)(r),p=[...n?[{key:`capabilities`,label:u(`capabilities.title`)}]:[],{key:`machine`,label:u(`machine.title`)},{key:`lark`,label:`Lark`},{key:`appearance`,label:u(`settings.appearance`)},{key:`language`,label:u(`settings.language`)}],m=[{label:u(`settings.languageEnglish`),value:`en`},{label:u(`settings.languageSimplifiedChinese`),value:`zh-CN`}],h={appearance:{title:u(`settings.appearance`)},capabilities:{title:u(`capabilities.title`)},language:{title:u(`settings.language`)},lark:{title:`Lark`},machine:{title:u(`machine.title`)}}[d];return(0,V.jsxs)(`section`,{"aria-label":u(`settings.title`),className:`personal-settings-page`,"data-pw-theme":s,children:[(0,V.jsxs)(`aside`,{className:`personal-settings-sidebar`,children:[(0,V.jsxs)(`button`,{className:`personal-settings-back`,onClick:a,type:`button`,children:[(0,V.jsx)(Gp,{size:17}),(0,V.jsx)(`span`,{children:u(`settings.back`)})]}),(0,V.jsxs)(`div`,{className:`personal-settings-title`,children:[(0,V.jsx)(`small`,{children:u(`settings.eyebrow`)}),(0,V.jsx)(`strong`,{children:u(`settings.title`)})]}),(0,V.jsx)(`nav`,{"aria-label":u(`settings.categories`),className:`personal-settings-tabs`,children:p.map(e=>{let t=sx[e.key];return(0,V.jsxs)(`button`,{"aria-current":d===e.key?`page`:void 0,onClick:()=>f(e.key),type:`button`,children:[(0,V.jsx)(t,{size:17}),(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:e.label})})]},e.key)})})]}),(0,V.jsxs)(`main`,{className:`personal-settings-body`,children:[(0,V.jsx)(`header`,{className:`personal-settings-header`,children:(0,V.jsx)(`div`,{children:(0,V.jsx)(`h1`,{children:h.title})})}),d===`lark`?(0,V.jsx)(kb,{embedded:!0,focusGoalConnection:e,goals:t,initialGoalId:n,onChanged:i,onClose:a}):null,d===`machine`?(0,V.jsx)(ox,{}):null,d===`capabilities`?(0,V.jsx)($b,{goalId:n}):null,d===`appearance`?(0,V.jsxs)(`section`,{className:`personal-detail-card personal-appearance-settings`,children:[(0,V.jsx)(`small`,{children:u(`settings.workspaceDisplay`)}),(0,V.jsx)(`h3`,{children:u(`settings.appearance`)}),(0,V.jsxs)(`div`,{className:`personal-settings-choice-group`,role:`radiogroup`,"aria-label":u(`settings.workspaceTheme`),children:[(0,V.jsxs)(`button`,{"aria-checked":s===`loopx`,onClick:()=>o(`loopx`),role:`radio`,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-settings-theme-swatch is-loopx`}),(0,V.jsx)(`strong`,{children:u(`settings.themeLoopx`)})]}),(0,V.jsxs)(`button`,{"aria-checked":s===`paper`,onClick:()=>o(`paper`),role:`radio`,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-settings-theme-swatch is-paper`}),(0,V.jsx)(`strong`,{children:u(`settings.themeDefault`)})]}),(0,V.jsxs)(`button`,{"aria-checked":s===`brutal`,onClick:()=>o(`brutal`),role:`radio`,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-settings-theme-swatch is-brutal`}),(0,V.jsx)(`strong`,{children:u(`settings.themeHighContrast`)})]})]})]}):null,d===`language`?(0,V.jsxs)(`section`,{className:`personal-settings-card`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`span`,{className:`personal-settings-icon`,children:(0,V.jsx)(bm,{size:18})}),(0,V.jsx)(`div`,{children:(0,V.jsx)(`h2`,{children:u(`settings.language`)})})]}),(0,V.jsx)(`div`,{"aria-label":u(`settings.language`),className:`personal-language-options`,role:`radiogroup`,children:m.map(e=>(0,V.jsxs)(`button`,{"aria-checked":c===e.value,className:c===e.value?`is-selected`:``,onClick:()=>l(e.value),role:`radio`,type:`button`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:e.label})}),c===e.value?(0,V.jsx)(em,{"aria-hidden":!0,size:17}):null]},e.value))})]}):null]})]})}var lx=`loopx-pw-theme`,ux=`loopx`;function dx(){try{let e=window.localStorage.getItem(lx);return e===`loopx`||e===`paper`||e===`brutal`?e:ux}catch{return ux}}function fx(e){try{window.localStorage.setItem(lx,e)}catch{}}function px({drawer:e,drawerMode:t=`panel`,drawerOpen:n,main:r,mobileSidebarOpen:i=!1,onCloseMobileSidebar:a,sidebar:o,theme:s=`loopx`}){let{t:c}=qi(),l=(0,B.useRef)(null),u=(0,B.useRef)(null);return(0,B.useEffect)(()=>{if(!i)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null;let e=l.current?.querySelectorAll(`button:not([disabled]), a[href], select:not([disabled]), textarea:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])`);e?.[0]?.focus();function t(t){if(t.key!==`Tab`||!e?.length)return;let n=e[0],r=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),r.focus()):!t.shiftKey&&document.activeElement===r&&(t.preventDefault(),n.focus())}return document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`keydown`,t),u.current?.focus(),u.current=null}},[i]),(0,V.jsxs)(`section`,{className:`personal-workspace-shell${n?` has-drawer`:``}${n&&t.startsWith(`inspector`)?` has-task-inspector`:``}${t===`inspector-full`?` is-task-inspector-full`:``}${i?` mobile-sidebar-open`:``}`,"data-pw-theme":s,children:[i?(0,V.jsx)(`button`,{"aria-hidden":!0,className:`personal-sidebar-backdrop`,onClick:a,tabIndex:-1,type:`button`}):null,(0,V.jsx)(`aside`,{"aria-label":i?c(`header.goalNavigation`):void 0,"aria-modal":i?!0:void 0,className:`personal-workspace-sidebar`,"data-workspace-sidebar":!0,ref:l,role:i?`dialog`:void 0,children:(0,V.jsxs)(`div`,{className:`personal-workspace-sidebar-inner`,children:[i?(0,V.jsxs)(`button`,{className:`personal-sr-only`,onClick:a,type:`button`,children:[c(`common.close`),` `,c(`header.goalNavigation`)]}):null,o]})}),(0,V.jsx)(`main`,{"aria-hidden":i||void 0,className:`personal-workspace-main`,inert:i||void 0,children:r}),n?(0,V.jsx)(`aside`,{className:`personal-workspace-drawer`,"data-context-drawer":!0,"data-drawer-mode":t,children:e}):null]})}function mx(e){let t=e.match(/(?:下一步|建议|行动项|待办)[::\s]*([^\n]+)/u),n=t?t[1]:e;n=n.replace(/```[\s\S]*?```/g,``).replace(/`([^`]+)`/g,`$1`).replace(/\[([^\]]+)\]\([^)]+\)/g,`$1`).replace(/[#*~_>]/g,``).replace(/^[-*•\d+.\s]+/u,``).replace(/^(好的|没问题|收到|建议如下|任务如下|分析如下|结论[::])[\s,,::]*/u,``);let r=(n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean)[0]||n).replace(/\s+/gu,` `).trim();return Array.from(r).slice(0,120).join(``)}function hx(e){let t=new Map;return e.forEach(e=>{let n=e.fields.find(e=>e.key===`todo_id`)?.value??``,r=[e.actionKind,e.goalId??``,n,e.title].join(`:`);t.set(r,e)}),[...t.values()]}function gx(e,t,n){if(!e)return n(`home.noFirstActivity`);let r=new Date(e);if(Number.isNaN(r.getTime()))return e;let i=new Date,a=new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r);return r.toDateString()===i.toDateString()?n(`home.todayAt`,{time:a}):new Intl.DateTimeFormat(t,{month:`numeric`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r)}function _x({goals:e,onSelectGoal:t,onRetry:n,systemHealth:r}){let{locale:i,t:a}=qi(),o=e.filter(e=>e.activationState===`active`),s=o.filter(e=>e.loadState===`error`).length,c=[{key:`needs_you`,label:a(`home.lane.needsYou`)},{key:`running`,label:a(`home.lane.running`)},{key:`observing`,label:a(`home.lane.observing`)},{key:`scheduled`,label:a(`home.lane.scheduled`)}],l=Object.fromEntries(c.map(e=>[e.key,[]])),u=[],d=[];e.filter(e=>!e.loadState).forEach(e=>{let t=hy(e);t===`history`?u.push(e):t===`stopped`?d.push(e):l[t].push(e)});let f=e=>(0,V.jsxs)(`button`,{className:`personal-home-goal-card`,"data-goal-state":e.loadState??e.state,"data-load-error":e.loadError,onClick:()=>t(e.goalId),type:`button`,children:[(0,V.jsxs)(`span`,{className:`personal-home-goal-meta`,children:[(0,V.jsx)(`i`,{}),e.agentLaneCount&&e.agentLaneCount>1?a(`header.workAgentCount`,{count:e.agentLaneCount}):e.agentLabel??e.agentId]}),(0,V.jsx)(`strong`,{children:e.title}),(0,V.jsx)(`p`,{children:e.loadError?a(`startup.error.${e.loadError}`):e.needsYou??e.nextSentence}),(0,V.jsxs)(`footer`,{children:[(0,V.jsx)(`span`,{children:e.loadState?a(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Ji(e.state,i)}),(0,V.jsx)(`small`,{title:e.latestActivity,children:e.loadState?``:e.latestActivity?gx(e.latestActivity,i,a):e.agentTodos.length?a(`home.taskCount`,{count:e.agentTodos.length}):a(`home.noActivity`)})]})]},e.goalId);return(0,V.jsxs)(`section`,{"aria-label":a(`home.workspace`),className:`personal-home-board`,children:[r&&(!r.ok||r.issues.length>0||r.freshnessWarning)?(0,V.jsxs)(`div`,{className:`personal-system-health-banner`,role:`alert`,children:[(0,V.jsxs)(`div`,{className:`personal-system-health-header`,children:[(0,V.jsx)(im,{size:15}),(0,V.jsx)(`strong`,{children:a(`home.systemHealth`,{summary:r.summary})}),r.freshnessWarning?(0,V.jsxs)(`small`,{children:[`(`,r.freshnessWarning,`)`]}):null]}),r.issues.length>0?(0,V.jsx)(`ul`,{className:`personal-system-health-issues`,children:r.issues.map((e,t)=>(0,V.jsx)(`li`,{children:e},t))}):null]}):null,o.some(e=>e.loadState)?(0,V.jsxs)(`section`,{className:`personal-home-lane`,"aria-live":`polite`,children:[(0,V.jsx)(`header`,{children:a(`startup.progress`,{loaded:o.filter(e=>!e.loadState).length,total:o.length})}),s?(0,V.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`status`,children:[(0,V.jsx)(`span`,{children:a(`startup.failedCount`,{count:s})}),(0,V.jsx)(`button`,{className:`min-h-11 rounded-md border px-3 py-2 text-sm`,onClick:n,type:`button`,children:a(`startup.retryFailed`)})]}):null,o.filter(e=>e.loadState).map(f)]}):null,(0,V.jsx)(`div`,{className:`personal-home-lanes`,children:c.map(e=>(0,V.jsxs)(`section`,{className:`personal-home-lane is-${e.key}`,"data-testid":`personal-home-lane-${e.key}`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`i`,{}),e.label]}),(0,V.jsx)(`b`,{children:l[e.key].length})]}),(0,V.jsx)(`div`,{className:`personal-home-lane-list`,children:l[e.key].length?l[e.key].map(f):(0,V.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.empty`)})})]},e.key))}),(0,V.jsxs)(`details`,{className:`personal-home-history`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(`span`,{children:a(`home.history`)}),(0,V.jsx)(`b`,{children:u.length}),(0,V.jsx)(`small`,{children:a(`home.completedGoals`)})]}),(0,V.jsx)(`div`,{children:u.length?u.map(f):(0,V.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.noCompletedGoals`)})})]}),d.length?(0,V.jsxs)(`details`,{className:`personal-home-history is-stopped`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(`span`,{children:a(`home.stopped`)}),(0,V.jsx)(`b`,{children:d.length}),(0,V.jsx)(`small`,{children:a(`home.preservedState`)})]}),(0,V.jsx)(`div`,{children:d.map(f)})]}):null]})}function vx({items:e,onSelect:t,reportState:n}){let{locale:r,t:i}=qi();return(0,V.jsxs)(`section`,{className:`personal-object-list personal-files-list`,"data-testid":`personal-goal-outputs`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:i(`files.title`)}),(0,V.jsx)(`span`,{children:e.length})]}),n?.loading?(0,V.jsxs)(`p`,{className:`personal-object-list-state`,role:`status`,children:[(0,V.jsx)(Im,{className:`is-spinning`,size:14}),i(`files.loadingReports`)]}):null,n?.error?(0,V.jsxs)(`p`,{className:`personal-object-list-state is-error`,role:`alert`,children:[(0,V.jsx)(im,{size:14}),i(`files.reportLoadFailed`),`: `,n.error]}):null,!n?.loading&&!n?.error&&e.length===0?(0,V.jsxs)(`p`,{className:`personal-object-list-state`,children:[(0,V.jsx)(gm,{size:14}),i(`files.empty`)]}):null,e.map(e=>(0,V.jsxs)(`button`,{"data-output-kind":e.output.kind,onClick:()=>t({item:e.output,kind:`output`}),type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-file-icon`,children:(0,V.jsx)(gm,{size:16})}),(0,V.jsx)(`strong`,{children:e.output.title}),e.output.report?(0,V.jsx)(`em`,{children:i(`files.reportDelta`,{added:e.output.report.addedCount,changed:e.output.report.changedCount})}):null,(0,V.jsx)(`p`,{children:e.output.summary??e.output.safePreview??e.output.kind??i(`files.emptySummary`)}),(0,V.jsx)(`small`,{title:e.output.createdAt,children:[e.output.goalTitle,e.output.kind===`report`?i(`files.verifiedReport`):null,e.output.todoId?`${i(`common.task`)} ${e.output.todoId}`:null,gx(e.output.createdAt,r,i)].filter(Boolean).join(` · `)})]},e.id))]})}function yx({agentLabel:e,messages:t,onClose:n,onDraftTask:r,onOpenConversation:i,title:a}){let{t:o}=qi(),s=t.reduce((e,t,n)=>t.role===`user`?n:e,0),c=t.slice(Math.max(0,s)).slice(-3),l=c.filter(e=>e.role===`assistant`&&!e.pending).at(-1);return(0,B.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),(0,V.jsxs)(`aside`,{"aria-label":o(`conversation.receipt`),className:`personal-manager-conversation-tray`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(Zp,{size:16}),(0,V.jsx)(`strong`,{children:a??o(`conversation.title`)}),(0,V.jsx)(`small`,{children:t.at(-1)?.pending?o(`conversation.replying`):o(`common.recently`)})]}),(0,V.jsxs)(`div`,{className:`personal-manager-conversation-actions`,children:[r&&l?(0,V.jsxs)(`button`,{className:`personal-manager-conversation-btn`,onClick:()=>r(l.text),title:o(`conversation.convertHint`),type:`button`,children:[(0,V.jsx)(Sm,{size:13}),(0,V.jsx)(`span`,{children:o(`conversation.toTask`)})]}):null,(0,V.jsx)(`button`,{className:`personal-manager-conversation-link`,onClick:i,type:`button`,children:o(`conversation.full`)}),n?(0,V.jsx)(`button`,{"aria-label":o(`conversation.close`),className:`personal-manager-conversation-close`,onClick:n,title:o(`conversation.close`),type:`button`,children:(0,V.jsx)($m,{size:14})}):null]})]}),(0,V.jsx)(`div`,{"aria-live":`polite`,className:`personal-manager-conversation-messages`,children:c.map(t=>(0,V.jsxs)(`article`,{className:`is-${t.role}`,children:[(0,V.jsx)(`strong`,{children:t.role===`user`?o(`common.you`):t.agentLabel??e??o(`header.manager`)}),(0,V.jsxs)(`div`,{className:`personal-manager-conversation-bubble`,children:[t.role===`user`?(0,V.jsx)(`p`,{children:t.text}):(0,V.jsx)(Ay,{text:t.text}),t.pending?(0,V.jsx)(`small`,{children:o(`conversation.agentPending`)}):null]})]},t.id))})]})}function bx({onClose:e,onOpenDetails:t,run:n}){let{t:r}=qi();return(0,V.jsxs)(`section`,{"aria-label":r(`session.record`),className:`personal-session-record`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(Zp,{size:17}),r(`session.record`)]}),(0,V.jsx)(`button`,{"aria-label":r(`session.closeRecord`),onClick:e,type:`button`,children:(0,V.jsx)($m,{size:15})})]}),(0,V.jsx)(`div`,{children:(0,V.jsx)(`strong`,{children:n.title})}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Agent`}),(0,V.jsx)(`dd`,{children:n.agentLabel})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`common.status`)}),(0,V.jsx)(`dd`,{children:Yi(n.sessionStatus??n.status,r)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Session`}),(0,V.jsx)(`dd`,{title:n.sessionId,children:n.sessionId})]})]}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:t,type:`button`,children:r(`session.details`)})]})}function xx(e,t,n){let r=[];if(t===null)return e.userTodos.slice(0,4).forEach(t=>r.push({attention:{...t,goalTitle:t.goalTitle??my(e,t.goalId)},id:`attention:${t.todoId}`,kind:`attention`})),e.goals.filter(e=>hy(e)===`running`).slice(0,4).forEach(e=>r.push({id:`run:${e.goalId}`,kind:`run`,run:{agentId:e.agentId,agentLabel:e.agentLabel??e.agentId,completedSteps:e.doneTodoCount??e.agentTodos.filter(e=>e.done).length,goalId:e.goalId,goalTitle:e.title,latestActivity:e.agentSentence,runId:`goal:${e.goalId}`,status:`running`,title:e.nextSentence,totalSteps:Math.max((e.doneTodoCount??0)+e.agentTodos.filter(e=>!e.done).length,1)}})),r;let i=e.goals.find(e=>e.goalId===t);if(!i)return r;if(i.needsYou){let t=e.userTodos.find(e=>e.goalId===i.goalId);r.push({attention:t?{...t,goalTitle:i.title}:{blocking:i.needsYouBlocking??!1,goalId:i.goalId,goalTitle:i.title,text:i.needsYou,todoId:`${i.goalId}:attention`},id:`attention:${i.goalId}`,kind:`attention`})}r.push({id:`run:${i.goalId}`,kind:`run`,run:{agentId:i.agentId,agentLabel:i.agentLabel??i.agentId,completedSteps:i.doneTodoCount??i.agentTodos.filter(e=>e.done).length,goalId:i.goalId,goalTitle:i.title,latestActivity:i.agentSentence,runId:`goal:${i.goalId}`,status:i.state===`推进中`?`running`:i.state===`需修复`?`failed`:`waiting`,title:i.nextSentence,totalSteps:Math.max((i.doneTodoCount??0)+i.agentTodos.filter(e=>!e.done).length,1)}}),i.agentTodos.filter(e=>e.taskClass===`continuous_monitor`).forEach(t=>{let a=e.timeline?.find(e=>e.kind===`run`&&e.run.goalId===i.goalId&&e.run.todoId===t.todoId&&!!e.run.sessionId);r.push({id:`schedule:${i.goalId}:${t.todoId}`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:a?[{label:a.run.latestActivity||a.run.title,runId:a.run.runId,status:a.run.status===`waiting`||a.run.status===`queued`?`running`:a.run.status,timestamp:i.latestActivity||n(`common.recently`)}]:[],goalId:i.goalId,label:t.text,schedule:t.evidence??n(`schedule.summary`),scheduleId:t.todoId,scheduleKind:`monitor`,sessionId:a?.run.sessionId,status:t.done||t.status===`paused`?`paused`:`active`,stopCondition:n(`drawer.scheduleDefaultStop`),target:t.text,timezone:`Asia/Shanghai`}})});let a=e.timeline?.find(e=>e.kind===`proposal`&&e.proposal.actionKind===`heartbeat.bind`&&e.proposal.goalId===i.goalId);if(a){let e=e=>a.proposal.fields.find(t=>t.key===e)?.value;r.push({id:`schedule:${i.goalId}:heartbeat`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:[],goalId:i.goalId,label:`${n(`schedule.heartbeat`)} · ${i.title}`,nextRunAt:n(`drawer.schedulePending`),notificationRule:n(`drawer.scheduleDefaultNotification`),schedule:e(`cadence`)??n(`schedule.summary`),scheduleId:`${i.goalId}:heartbeat`,scheduleKind:`heartbeat`,status:a.proposal.status===`applied`?`active`:`draft`,stopCondition:e(`stop_condition`)??n(`drawer.scheduleDefaultStop`),timezone:e(`timezone`)??`Asia/Shanghai`}})}return r}function Sx(e){return e===`preview_ready`?`ready`:e===`cancelled`?`draft`:e===`failed`?`error`:e}function Cx(e,t){let n={agent_id:t(`proposal.field.agentId`),cadence:t(`proposal.field.cadence`),completion_criteria:t(`proposal.field.completionCriteria`),execution_boundary:t(`proposal.field.executionBoundary`),goal_id:t(`proposal.field.goalId`),heartbeat:t(`proposal.field.heartbeat`),initial_todos:t(`proposal.field.initialTodos`),objective:t(`proposal.field.objective`),operation:t(`proposal.field.operation`),permission:t(`proposal.field.permission`),reason:t(`proposal.field.reason`),stop_condition:t(`proposal.field.stopCondition`),target:t(`proposal.field.target`),timezone:t(`proposal.field.timezone`),title:t(`proposal.field.title`),workspace_ref:t(`proposal.field.workspace`)},r=[`title`,`objective`,`completion_criteria`,`execution_boundary`,`permission`,`agent_id`,`workspace_ref`,`initial_todos`,`heartbeat`,`stop_condition`,`goal_id`];return Object.entries(e).sort(([e],[t])=>{let n=r.indexOf(e),i=r.indexOf(t);return(n<0?r.length:n)-(i<0?r.length:i)}).slice(0,10).map(([e,r])=>({key:e,label:n[e]??e.replaceAll(`_`,` `),value:e===`workspace_ref`?r===`current`?t(`proposal.workspace.current`):t(`proposal.workspace.named`,{workspace:String(r??`current`)}):Array.isArray(r)?r.join(` · `):typeof r==`object`&&r?JSON.stringify(r):String(r??`—`)}))}function wx(e){if(e.action_kind!==`goal.lifecycle`)return;let t=e.normalized_parameters.operation;return t===`stop`||t===`resume`||t===`delete`?t:void 0}function Tx(e,t){let n=wx(e),r=dy(e),i=typeof e.normalized_parameters.title==`string`?e.normalized_parameters.title:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:``,a=typeof e.normalized_parameters.target==`string`?e.normalized_parameters.target:``,o=e.action_kind===`goal.create`?t(`proposal.summary.goalCreate`,{title:i}):e.action_kind===`heartbeat.bind`?t(`proposal.summary.heartbeat`):e.action_kind===`monitor.create`?t(`proposal.summary.monitor`,{target:a}):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.summary.lifecycleStop`,{title:i}):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.summary.lifecycleDelete`,{title:i}):e.action_kind===`goal.lifecycle`?t(`proposal.summary.lifecycleResume`,{title:i}):e.summary;return{actionKind:e.action_kind,reviewPlan:r,fields:Cx(e.normalized_parameters,t),goalId:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:void 0,impact:e.action_kind===`goal.create`?t(`proposal.impact.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.impact.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.impact.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.impact.lifecycleResume`):e.permission_classification===`protected`?t(`proposal.impact.protected`):t(`proposal.impact.default`),previewId:e.proposal_id,lifecycleOperation:n,gate:e.gate?{kind:String(e.gate.kind??`protected_action`),nextAction:typeof e.gate.next_action==`string`?e.gate.next_action:void 0,summary:String(e.gate.summary??t(`proposal.gate.default`))}:void 0,primaryLabel:e.action_kind===`goal.create`?t(`proposal.primary.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.primary.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.primary.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.primary.lifecycleResume`):e.action_kind===`todo.create`&&e.normalized_parameters.start_execution===!0?t(`proposal.primary.todoStart`):t(`proposal.primary.apply`),status:e.status===`applied`&&r.interaction!==`completed`?`error`:Sx(e.status),title:o}}function Ex(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,42);if(t)return t;let n=2166136261;for(let t of e)n^=t.codePointAt(0)??0,n=Math.imul(n,16777619);return`goal-${(n>>>0).toString(36)}`}function Dx(e,t){let n=e.match(/[「“"]([^」”"]{2,80})[」”"]/u)?.[1];return n?n.trim():e.replace(/^(请|帮我|我想|给我|创建|新建|设置|please|i want to|create|set up)+/iu,``).replace(/(一个|新的)?\s*(goal|目标)/giu,``).replace(/[,。!?].*$/u,``).trim().slice(0,80)||t(`goal.defaultTitle`)}function Ox(e,t){for(let n of e.split(/\r?\n/u)){let e=n.trim();for(let n of t){let t=e.match(RegExp(`^${n.replace(/[.*+?^${}()|[\]\\]/gu,`\\$&`)}\\s*[::]\\s*(.*)$`,`iu`));if(t?.[1]?.trim())return t[1].trim()}}return``}function kx(e,t){let n=Ox(e,[`目标`,`Objective`]),r=Ox(e,[`完成标准`,`Completion criteria`]),i=Ox(e,[`执行边界(可选)`,`执行边界`,`边界`,`Execution boundary (optional)`,`Execution boundary`,`Boundary`]),a=(n||Dx(e,t)).split(/[。;;\n]/u)[0].trim().slice(0,80)||t(`goal.defaultTitle`),o=[n||a,r?t(`goal.objectiveCompletion`,{criteria:r}):``,i?t(`goal.objectiveBoundary`,{boundary:i}):``].filter(Boolean).join(` -======== -`)});continue}let o=e.match(/^\s{0,3}#{1,4}\s+(.*)$/);if(o){i();let t=e.trimStart().match(/^#+/)?.[0].length??1;n.push({type:`heading`,level:t,text:o[1].trim()}),a+=1;continue}if(Dy.test(e)||Oy.test(e)){i();let r=Oy.test(e),o=r?Oy:Dy,s=[];for(;a{let n=`b${t}`;if(e.type===`code`)return(0,V.jsx)(`pre`,{className:`personal-md-pre`,children:(0,V.jsx)(`code`,{children:e.text})},n);if(e.type===`heading`)return(0,V.jsx)(`p`,{className:`personal-md-heading is-h${e.level}`,children:Ey(e.text,n)},n);if(e.type===`list`){let t=e.items.map((e,t)=>(0,V.jsx)(`li`,{children:Ey(e,`${n}-${t}`)},`${n}-${t}`));return e.ordered?(0,V.jsx)(`ol`,{className:`personal-md-list`,children:t},n):(0,V.jsx)(`ul`,{className:`personal-md-list`,children:t},n)}return(0,V.jsx)(`p`,{children:e.lines.map((e,t)=>(0,V.jsxs)(B.Fragment,{children:[t>0?(0,V.jsx)(`br`,{}):null,Ey(e,`${n}-${t}`)]},`${n}-${t}`))},n)})})}function jy({onSelect:e,output:t}){let{t:n}=qi(),r=t.kind===`report`?gm:hm;return(0,V.jsxs)(`button`,{className:`personal-timeline-row personal-output-row`,"data-output-kind":t.kind,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-row-icon is-output`,children:(0,V.jsx)(r,{size:18})}),(0,V.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,V.jsxs)(`small`,{children:[t.goalTitle??t.goalId,` · `,t.agentLabel??`LoopX`]}),(0,V.jsx)(`strong`,{children:t.title}),t.summary?(0,V.jsx)(`span`,{children:t.summary}):null,t.report?(0,V.jsxs)(`small`,{children:[n(`files.reportDelta`,{added:t.report.addedCount,changed:t.report.changedCount}),` · `,n(`files.verifiedReport`)]}):null]}),t.createdAt?(0,V.jsx)(`time`,{children:t.createdAt}):null,(0,V.jsx)(nm,{size:17})]})}var My={completed:`runs.completed`,failed:`runs.failed`,interrupted:`runs.interrupted`,queued:`runs.queued`,running:`runs.running`,waiting:`runs.waiting`};function Ny({onSelect:e,run:t}){let{t:n}=qi(),r=t.totalSteps>0?Math.min(100,t.completedSteps/t.totalSteps*100):0;return(0,V.jsxs)(`button`,{"aria-label":`${n(`tasks.viewExecution`)}:${t.title}`,className:`personal-timeline-row personal-run-row`,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-row-icon is-run`,children:(0,V.jsx)(Zp,{size:18})}),(0,V.jsxs)(`span`,{className:`personal-run-identity`,children:[(0,V.jsx)(`small`,{children:t.goalTitle}),(0,V.jsx)(`strong`,{children:t.agentLabel})]}),(0,V.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,V.jsx)(`strong`,{children:t.title}),(0,V.jsx)(`small`,{children:t.latestActivity})]}),(0,V.jsxs)(`span`,{className:`personal-run-progress`,"aria-label":`${t.completedSteps}/${t.totalSteps}`,children:[(0,V.jsxs)(`small`,{children:[t.completedSteps,`/`,t.totalSteps]}),(0,V.jsx)(`i`,{children:(0,V.jsx)(`b`,{style:{width:`${r}%`}})})]}),(0,V.jsxs)(`span`,{className:`personal-row-status is-${t.status}`,children:[t.status===`running`?(0,V.jsx)(Cm,{className:`personal-spin`,size:14}):null,n(My[t.status])]}),t.sessionId?(0,V.jsx)(`span`,{className:`personal-run-open-label`,children:n(`tasks.viewExecution`)}):null,(0,V.jsx)(nm,{size:17})]})}function Py({onSelect:e,schedule:t}){let{t:n}=qi(),r=t.scheduleKind===`heartbeat`;return(0,V.jsxs)(`button`,{"aria-label":`${r?`Heartbeat`:n(`tasks.scheduled`)}:${t.label};${t.status??`active`}`,className:`personal-schedule-row`,onClick:e,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-schedule-icon`,children:r?(0,V.jsx)(Fm,{size:17}):(0,V.jsx)($p,{size:17})}),(0,V.jsxs)(`span`,{className:`personal-schedule-copy`,children:[(0,V.jsx)(`small`,{children:n(r?`schedule.heartbeat`:`schedule.monitor`)}),(0,V.jsx)(`strong`,{children:t.label}),(0,V.jsx)(`p`,{children:t.schedule??n(`schedule.summary`)})]}),(0,V.jsx)(`span`,{className:`personal-schedule-status is-${t.status??`active`}`,children:t.status===`paused`?n(`schedule.paused`):n(`schedule.active`)}),(0,V.jsx)(nm,{size:16})]})}function Fy({items:e,onSelect:t,selectedGoal:n}){let{t:r}=qi();if(e.length===0)return(0,V.jsxs)(`div`,{className:`personal-timeline-empty`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(Km,{size:20})}),(0,V.jsx)(`strong`,{children:r(n?`timeline.emptyGoal`:`timeline.emptyWorkspace`)}),(0,V.jsx)(`p`,{children:r(n?`timeline.emptyGoalDescription`:`timeline.emptyWorkspaceDescription`)})]});let i=[...e].reverse().find(e=>e.kind===`message`&&e.message.role!==`user`||e.kind===`proposal`&&[`applied`,`stale`,`error`,`gated`].includes(e.proposal.status)||e.kind===`run`&&e.run.status===`completed`),a=i?.kind===`message`?`${i.message.agentLabel??r(`header.manager`)}:${i.message.pending?r(`timeline.pending`):i.message.text}`:i?.kind===`proposal`?`${i.proposal.title}:${i.proposal.status}`:i?.kind===`run`?r(`timeline.runCompleted`,{run:i.run.title}):``,o=e.filter(e=>e.kind===`proposal`&&e.proposal.status===`gated`),s=e.filter(e=>e.kind!==`proposal`),c=e.filter(e=>e.kind===`proposal`&&e.proposal.status!==`gated`);function l(e){return e.kind===`attention`?(0,V.jsx)(wy,{attention:e.attention,onSelect:()=>t({item:e.attention,kind:`attention`})},e.id):e.kind===`run`?(0,V.jsx)(Ny,{onSelect:()=>t({item:e.run,kind:`run`}),run:e.run},e.id):e.kind===`output`?(0,V.jsx)(jy,{onSelect:()=>t({item:e.output,kind:`output`}),output:e.output},e.id):e.kind===`schedule`?(0,V.jsx)(Py,{onSelect:()=>t({item:e.schedule,kind:`schedule`}),schedule:e.schedule},e.id):e.kind===`proposal`?(0,V.jsxs)(`button`,{className:`personal-proposal-row is-${e.proposal.status}`,onClick:()=>t({item:e.proposal,kind:`proposal`}),type:`button`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(Km,{size:17})}),(0,V.jsxs)(`span`,{children:[(0,V.jsxs)(`small`,{children:[e.proposal.actionKind,` · `,e.proposal.status]}),(0,V.jsx)(`strong`,{children:e.proposal.title}),(0,V.jsx)(`p`,{children:e.proposal.impact})]}),(0,V.jsx)(`b`,{children:e.proposal.status===`gated`?r(`timeline.review`):e.proposal.primaryLabel??r(`timeline.reviewAndConfirm`)})]},e.id):(0,V.jsxs)(`article`,{className:`personal-message is-${e.message.role}`,children:[e.message.role===`user`?null:(0,V.jsx)(`span`,{className:`personal-message-avatar`,children:(0,V.jsx)(Zp,{size:17})}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:e.message.role===`user`?r(`common.you`):e.message.agentLabel??r(`header.manager`)}),e.message.time?(0,V.jsx)(`time`,{children:e.message.time}):null]}),e.message.attachments?.length?(0,V.jsx)(`div`,{className:`personal-message-images`,children:e.message.attachments.map(e=>(0,V.jsx)(`img`,{alt:e.name,src:e.dataUrl},e.id))}):null,e.message.role===`user`?(0,V.jsx)(`p`,{children:e.message.text}):(0,V.jsx)(Ay,{text:e.message.text}),e.message.pending?(0,V.jsx)(`span`,{className:`personal-message-pending`,children:r(`timeline.pending`)}):null]})]},e.id)}return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{"aria-atomic":`true`,"aria-live":`polite`,className:`personal-live-region`,role:`status`,children:a}),(0,V.jsxs)(`div`,{className:`personal-channel-timeline`,children:[s.map(l),o.length?(0,V.jsxs)(`details`,{className:`personal-gated-summary`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(Km,{size:16})}),(0,V.jsx)(`strong`,{children:r(`timeline.waitingConfirmation`)}),(0,V.jsx)(`small`,{children:r(`timeline.gateHistory`,{count:o.length})})]}),(0,V.jsx)(`div`,{children:o.map(l)})]}):null,c.map(l)]})]})}function Iy({goal:e}){let{t}=qi(),n={connected:t(`acceptance.connected`),mapped:t(`acceptance.mapped`),refreshed:t(`acceptance.refreshed`),adapter_inspected:t(`acceptance.inspected`),run_recorded:t(`acceptance.recorded`),reward_judged:t(`acceptance.judged`),operator_approved:t(`acceptance.approved`),controller_ready:t(`acceptance.ready`),attention_queue:t(`acceptance.attentionSource`),agent_vision:t(`acceptance.visionSource`),todo_projection:t(`acceptance.todoSource`),current_run:t(`acceptance.runSource`)},r=e=>n[e]??t(`acceptance.unknown`),i=e.acceptanceObservation,a=e.loadState||!i||i.goal_id!==e.goalId||i.coverage===`unavailable`;return(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-acceptance`,"aria-label":t(`acceptance.title`),children:[(0,V.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,V.jsx)(`h3`,{children:t(`acceptance.title`)}),(0,V.jsx)(`em`,{children:t(`common.readOnly`)})]}),(0,V.jsx)(`p`,{role:`status`,children:t(a?`acceptance.unavailable`:`acceptance.partial`)}),!a&&i?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h4`,{children:t(`acceptance.gaps`)}),i.acceptance_gaps.length?i.acceptance_gaps.map((e,n)=>(0,V.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,V.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.owner`)}),(0,V.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,V.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.observed`)}),(0,V.jsx)(`dd`,{children:e.observed_at??t(`acceptance.unknown`)})]})]})]},`${e.kind}:${e.owner}:${n}`)):(0,V.jsx)(`p`,{children:t(`acceptance.noGaps`)}),(0,V.jsx)(`h4`,{children:t(`acceptance.guards`)}),i.guards.length?i.guards.map((e,n)=>(0,V.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,V.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.owner`)}),(0,V.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),e.blocks_agent?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.agent`)}),(0,V.jsx)(`dd`,{children:e.blocks_agent})]}):null,e.todo_id?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.task`)}),(0,V.jsx)(`dd`,{children:e.todo_id})]}):null,(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,V.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.scope`)}),(0,V.jsx)(`dd`,{children:e.decision_scope??t(`acceptance.unknown`)})]})]})]},`${e.todo_id}:${n}`)):(0,V.jsx)(`p`,{children:t(`acceptance.noGuards`)}),(0,V.jsx)(`h4`,{children:t(`acceptance.next`)}),(0,V.jsx)(`p`,{children:i.next_action??t(`acceptance.unknown`)}),(0,V.jsxs)(`details`,{children:[(0,V.jsxs)(`summary`,{children:[t(`acceptance.historical_progress`),` · `,i.historical_progress.length]}),(0,V.jsx)(`p`,{children:t(`acceptance.historical`)}),i.historical_progress.map(e=>(0,V.jsxs)(`p`,{children:[(0,V.jsx)(`strong`,{children:r(e.kind)}),` · `,e.observed_at??t(`acceptance.unknown`),` `,e.evidence_refs.join(`, `)]},e.kind))]}),i.missing_sources.length?(0,V.jsxs)(`p`,{children:[t(`acceptance.missing`),` `,i.missing_sources.map(r).join(`, `)]}):null,i.truncated?(0,V.jsx)(`p`,{children:t(`acceptance.truncated`)}):null]}):null]})}function Ly({item:e,successor:t,onSelect:n}){let{t:r}=qi(),i=e.details;return(0,V.jsxs)(`section`,{className:`personal-detail-card`,"aria-label":r(`attentionDetail.title`),children:[(0,V.jsx)(`h3`,{children:r(`attentionDetail.title`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.request`)}),(0,V.jsx)(`dd`,{children:r(i?.interaction===`decision`?`attentionDetail.decision`:`attentionDetail.unknownRequest`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`common.status`)}),(0,V.jsx)(`dd`,{children:r(`attentionDetail.${i?.lifecycle??`unknown`}`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`drawer.reason`)}),(0,V.jsx)(`dd`,{children:i?.reason??e.explanation??r(`attentionDetail.unknownReason`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Todo`}),(0,V.jsx)(`dd`,{children:e.todoId})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.targetTodo`)}),(0,V.jsx)(`dd`,{children:i?.unblocksTodoId??r(`attentionDetail.notProvided`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.targetAgent`)}),(0,V.jsx)(`dd`,{children:i?.blocksAgent??r(`attentionDetail.notProvided`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.scope`)}),(0,V.jsx)(`dd`,{children:i?.decisionScope?`${i.decisionScope.kind} · ${i.decisionScope.granularity} · ${i.decisionScope.scopeKey}`:r(`attentionDetail.notProvided`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`drawer.evidence`)}),(0,V.jsx)(`dd`,{children:i?.evidence??e.evidence??r(`drawer.decisionDefaultEvidence`)})]})]}),i?.supersededBy?(0,V.jsxs)(`p`,{children:[r(`attentionDetail.replacement`),`: `,i.supersededBy]}):null,t&&n?(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>n(t),type:`button`,children:r(`attentionDetail.openReplacement`)}):null,(0,V.jsx)(`p`,{children:r(`attentionDetail.boundary`)})]})}function Ry(e){return e.replace(/\s+/gu,` `).trim()}function zy(e,t){let n=RegExp(`(?:不要|不需要|无需|禁止|别|暂不|do not\\b|don't\\b|without\\b).{0,10}(?:${t.source})`,`iu`),r=RegExp(`(?:${t.source}).{0,10}(?:不要|不需要|无需|禁止|关闭)`,`iu`),i=RegExp(`disable\\b.{0,10}(?:${t.source})|(?:turn|switch|set)\\b.{0,10}(?:${t.source}).{0,10}\\boff\\b|(?:${t.source})\\s+(?:is\\s+)?disabled\\b`,`iu`);return n.test(e)||r.test(e)||i.test(e)}function By(e){return/(我现在该做什么|下一步|哪些\s*Goal\s*在等我|需要我|谁在等我|Agent\s*在做什么|当前进度|总结(?:今天)?进展)/iu.test(e)}function Vy(e){let t=/(怎么|如何|为什么|给.*建议|分析一下|解释|只读)/u.test(e),n=/(解决一下|修复一下|处理一下|执行一下|改一下|跑(?:一下)?测试|rebase|push|提交|推送)/iu.test(e);return!t&&n&&/(帮我|请|给我|直接|现在|开始|bytedcli|codebase|git|rebase|push|提交|推送)/iu.test(e)}function Hy(e){return Ry(e).toLowerCase().match(/(?:^|[\s,,;;:((:]|到|至)(?todo_done:todo_[a-z0-9_-]{3,64}|pr_merged:(?:(?:[a-z0-9_.-]{1,80})\/(?:[a-z0-9_.-]{1,100}))?#[1-9][0-9]{0,8}|capacity_available:[a-z][a-z0-9_:-]{0,63}|resume_at:[1-9][0-9]{3}-[0-9]{2}-[0-9]{2}t[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,3})?(?:z|[+-][0-9]{2}:[0-9]{2}))(?=$|[\s,,。;;))])/iu)?.groups?.condition??null}function Uy(e,t){let n=Ry(e),r=[],i=t.agents.find(e=>{let t=n.toLowerCase();return t.includes(e.agentId.toLowerCase())||t.includes(e.label.toLowerCase())}),a=t.todos.find(e=>n.includes(e.todoId)||n.includes(e.text)),o=/(刚刚|已经|已)(?:经)?\s*(新增|创建|添加)(?:的)?\s*(todo|待办|任务)/iu.test(n),s=!!t.goalId&&!zy(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n);if(!t.goalId&&!zy(n,/goal|目标/iu)&&/(创建|新建|设置|create|start|set up).{0,24}(goal|目标)/iu.test(n)&&r.push({actionKind:`goal.create`,confidence:.97,normalizedParameters:{heartbeat_enabled:!zy(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n)}}),t.goalId&&s&&r.push({actionKind:`heartbeat.bind`,confidence:.96,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&!s&&!zy(n,/定时|监控|监测|持续观察|scheduled check|monitor/iu)&&/(定时|监控|监测|每.{0,8}(分钟|小时|天)|持续观察|scheduled check|monitor|every.{0,12}(minute|hour|day)|daily)/iu.test(n)&&r.push({actionKind:`monitor.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&i&&!zy(n,/绑定|负责|接管|管理/iu)&&/((让|交给).{0,20}(管理|负责|接管).{0,8}(goal|目标)|(绑定).{0,12}(goal|目标)|(goal|目标).{0,12}(交给|绑定|负责|接管))/iu.test(n)&&r.push({actionKind:`agent.bind`,confidence:.96,normalizedParameters:{agent_id:i.agentId,goal_id:t.goalId}}),t.goalId&&!o&&!zy(n,RegExp(`todo|待办|任务`,`iu`))&&/(创建|新建|新增|添加|加一个|记一个).{0,16}(todo|待办|任务)|(todo|待办|任务).{0,12}(创建|新建|新增|添加)|(?:create|add)(?:\s+(?:a|an|new))?\s+(?:todo|task)|(?:todo|task).{0,12}(?:create|add)/iu.test(n)&&r.push({actionKind:`todo.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&Vy(n)&&r.push({actionKind:`todo.create`,confidence:.9,normalizedParameters:{goal_id:t.goalId,start_execution:!0}}),t.goalId&&a){let e=!zy(n,/完成|做完|关闭/u)&&/完成|做完|关闭/u.test(n)?`complete`:!zy(n,/阻塞|卡住/u)&&/阻塞|卡住/u.test(n)?`block`:!zy(n,/暂缓|稍后|推迟/u)&&/暂缓|稍后|推迟/u.test(n)?`defer`:i&&!zy(n,/交给|分配给|改派/u)&&/交给|分配给|改派/u.test(n)?`reassign`:null;if(e){let i=e===`defer`?Hy(n):null;if(e===`defer`&&!i)return{actionKind:`todo.update`,confidence:.97,missingFields:[`resume_when`],normalizedParameters:{goal_id:t.goalId,operation:e,todo_id:a.todoId},route:`clarify`};r.push({actionKind:`todo.update`,confidence:.97,normalizedParameters:{goal_id:t.goalId,operation:e,...i?{resume_when:i}:{},todo_id:a.todoId}})}}let c=[...new Map(r.map(e=>[e.actionKind,e])).values()];return c.length>1?{actionKind:null,confidence:.4,missingFields:[`single_intent`],normalizedParameters:{},route:`clarify`}:c.length===1?{...c[0],missingFields:[],route:`typed_action`}:!t.goalId&&By(n)?{actionKind:null,confidence:.98,missingFields:[],normalizedParameters:{},route:`projection`}:{actionKind:null,confidence:.75,missingFields:[],normalizedParameters:{},route:`agent_chat`}}function Wy(e,t,n){if(!e)return{};if(!t.trim())return{modelConfig:null};let r={model:t.trim()};return n&&(r.reasoning_effort=n),{modelConfig:r}}var Gy=[`a[href]`,`button:not([disabled])`,`textarea:not([disabled])`,`select:not([disabled])`,`input:not([disabled])`,`[tabindex]:not([tabindex='-1'])`].join(`,`),Ky=[{key:`drawer.taskBlock`,operation:`block`},{key:`drawer.taskSuccessor`,operation:`successor_create`}],qy=[{key:`drawer.decisionReject`,resolution:`reject`},{key:`drawer.decisionDefer`,resolution:`defer`}],Jy=Array.from({length:32},(e,t)=>t+1),Yy=/^[a-z][a-z0-9_.-]{0,63}$/u;function Xy(e){let t=String(e??``).trim().toLowerCase();return Yy.test(t)?t:null}function Zy(e,t){return e.enabled===t.enabled&&e.maxChildren===t.maxChildren&&JSON.stringify(e.modelConfig??null)===JSON.stringify(t.modelConfig??null)&&[...e.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)===[...t.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)}function Qy({agents:e,attentionHistory:t=[],onSelectAttention:n,callbacks:r,goalNotifications:i=[],goals:a=[],inspectorExpanded:o=!1,larkConnections:s=[],onClose:c,onToggleInspectorSize:l,readOnly:u=!1,runs:d=[],selection:f}){let{locale:p,t:m}=qi(),[h,g]=(0,B.useState)(``),[_,v]=(0,B.useState)(!1),[y,b]=(0,B.useState)(`idle`),[x,S]=(0,B.useState)(`record`),[C,w]=(0,B.useState)([]),[T,E]=(0,B.useState)(null),[D,O]=(0,B.useState)(2),[ee,te]=(0,B.useState)(``),[ne,k]=(0,B.useState)(``),[A,j]=(0,B.useState)(`idle`),[M,N]=(0,B.useState)(null),[P,F]=(0,B.useState)(null),re=(0,B.useRef)(null),ie=(0,B.useRef)(null),[I,ae]=(0,B.useState)(e.find(e=>e.available)?.agentId??`codex`),[L,oe]=(0,B.useState)(``),se=(0,B.useRef)(null),ce=(0,B.useRef)(null),le=(0,B.useRef)(null),ue=(0,B.useRef)(null),de=f.kind===`run`?`run:${f.item.runId}`:f.kind===`proposal`?`proposal:${f.item.previewId}`:f.kind===`todo`?`todo:${f.item.todoId}`:f.kind===`attention`?`attention:${f.item.todoId}`:f.kind===`output`?`output:${f.item.outputId}`:f.kind===`schedule`?`schedule:${f.item.scheduleId}`:`goal:${f.item.goalId}`;(0,B.useEffect)(()=>{b(`idle`),v(!1),S(`record`),oe(``);let e=f.kind===`goal`?f.item.subagentExecution:void 0;w(e?.allowedDomains??[]),te(e?.modelConfig?.model??``),k(e?.modelConfig?.reasoning_effort??``),O(e?.maxChildren?Math.min(e.maxChildren,32):2),E(null),j(`idle`),N(null),F(null),re.current=e??null,ie.current=null},[de]);let R=f.kind===`goal`?f.item.subagentExecution:void 0;(0,B.useEffect)(()=>{let e=re.current,t=R?!e||!Zy(e,R):e!==null;if(re.current=R??null,!P){t&&R&&(w(R.allowedDomains),te(R.modelConfig?.model??``),k(R.modelConfig?.reasoning_effort??``),O(R.maxChildren||2),E(null),j(`idle`),N(null));return}let n=ie.current;(!R||Zy(P,R)||n&&!Zy(n,R))&&(R&&(w(R.allowedDomains),te(R.modelConfig?.model??``),k(R.modelConfig?.reasoning_effort??``),O(R.maxChildren||2)),ie.current=null,F(null))},[R,P]),(0,B.useEffect)(()=>{let e=document.activeElement;e instanceof HTMLElement&&!ce.current?.contains(e)&&(le.current=e);let t=window.requestAnimationFrame(()=>ue.current?.focus());return()=>window.cancelAnimationFrame(t)},[de]);let fe=(0,B.useCallback)(()=>{let e=le.current;c(),window.requestAnimationFrame(()=>e?.focus())},[c]);(0,B.useEffect)(()=>{function e(e){if(e.key===`Escape`){e.preventDefault(),fe();return}if(e.key===`Tab`&&f.kind!==`todo`){let t=Array.from(ce.current?.querySelectorAll(Gy)??[]).filter(e=>!e.hasAttribute(`disabled`)&&e.getAttribute(`aria-hidden`)!==`true`);if(t.length===0)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n.focus())}}return document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`keydown`,e)}},[fe,f.kind]);let pe=f.kind===`attention`?m(`drawer.titleAttention`):f.kind===`todo`?m(`drawer.taskDetails`):f.kind===`run`?m(`drawer.runDetails`):f.kind===`output`?m(`drawer.titleOutput`):f.kind===`proposal`?m(f.item.status===`applied`?`drawer.titleProposalApplied`:`drawer.titleProposalConfirm`):f.kind===`schedule`?f.item.scheduleKind===`heartbeat`?`Heartbeat`:m(`drawer.titleSchedule`):m(`drawer.goalDetails`),me=f.kind===`proposal`?f.item.goalId??`manager`:f.item.goalId,he=f.kind===`attention`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`todo`||f.kind===`run`?f.item.goalTitle:f.kind===`output`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`goal`?f.item.title:f.kind===`schedule`?m(`drawer.goalAutoRun`):f.item.goalId?m(`drawer.goalChanges`):m(`drawer.managerChanges`),ge=f.kind===`goal`?d.find(e=>e.goalId===f.item.goalId&&!!e.sessionId)??d.find(e=>e.goalId===f.item.goalId):null,_e=f.kind===`run`&&(f.item.completedSteps>0||!!f.item.latestActivity||!!f.item.outputs?.length),ve=f.kind===`attention`?Xi(f.item.updatedAt,m):null,ye=Hy(L);async function be(){f.kind!==`run`||!h.trim()||(await r.onCorrectRun?.(f.item,h.trim()),g(``))}async function xe(e,t,n,i){if(t===`successor_create`){await r.onPreviewAction?.({actionKind:`todo.create`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-successor-${e.todoId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,text:m(`drawer.taskSuccessorText`,{task:e.text})},summary:m(`drawer.taskSuccessorSummary`,{task:e.text})});return}await r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:e.claimedBy??I,goal_id:e.goalId,operation:t,...t===`block`?{note:m(`drawer.taskSuccessorNote`)}:{},...t===`defer`&&i?{resume_when:i}:{},todo_id:e.todoId},summary:`${n}:${e.text}`})}async function Se(e,t,n){u||!qd(e)||await r.onPreviewAction?.({actionKind:`gate.resolve`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-decision-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,decision:t,todo_id:e.todoId},summary:`${n}:${e.text}`})}let Ce=f.kind===`goal`?P??f.item.subagentExecution??{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0}:{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0},we=A===`previewing`||A===`applying`,Te=(()=>{if(f.kind!==`goal`)return[];let e=new Map;for(let t of Ce.allowedDomains){let n=Xy(t);n&&e.set(n,{matchingTodoCount:0,value:n})}if(Ce.domainCandidates)for(let t of Ce.domainCandidates){let n=Xy(t.domain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+t.matchingTodoCount,value:n})}else for(let t of f.item.agentTodos){if(t.done||t.taskClass!==`advancement_task`)continue;let n=Xy(t.taskDomain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+1,value:n})}return[...e.values()]})();function z(){w(Ce.allowedDomains),te(Ce.modelConfig?.model??``),k(Ce.modelConfig?.reasoning_effort??``),O(Ce.maxChildren||2),E(null),j(`idle`),N(null)}function Ee(){let e=[...new Set(C.map(e=>Xy(e)))];return e.every(e=>!!e)?e:null}function De(e,t){w(n=>t?[...n,e].filter((e,t,n)=>n.indexOf(e)===t):n.filter(t=>t!==e)),N(null),j(`idle`),E(null)}async function Oe(e,t=e){if(f.kind!==`goal`||!r.onPreviewGoalSubagentConfiguration)return;let n=e?Ee():[];if(t&&!ee.trim()&&ne){j(`error`),E(m(`drawer.subagentModelRequired`));return}if(e&&!n){j(`error`),E(m(`drawer.subagentDomainInvalid`)),N(null);return}let i={allowedDomains:n??[],enabled:e,goalId:f.item.goalId,maxChildren:e?D:0,...Wy(t,ee,ne)};j(`previewing`),E(m(`drawer.subagentPreviewing`)),N(null);try{let e=await r.onPreviewGoalSubagentConfiguration(i);if(!e.changed){ie.current=R??null,F({...e.configuration,domainCandidates:Ce.domainCandidates}),w(e.configuration.allowedDomains),te(e.configuration.modelConfig?.model??``),k(e.configuration.modelConfig?.reasoning_effort??``),O(e.configuration.maxChildren||2),j(`success`),E(m(`drawer.subagentNoChange`));return}N({...i,changed:e.changed,previewId:e.previewId}),j(`ready`),E(m(`drawer.subagentPreviewReady`))}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentPreviewFailed`))}}async function ke(){if(!(!M||!r.onApplyGoalSubagentConfiguration)){j(`applying`),E(m(`drawer.subagentApplying`));try{let e=await r.onApplyGoalSubagentConfiguration({allowedDomains:M.allowedDomains,enabled:M.enabled,goalId:M.goalId,maxChildren:M.maxChildren,modelConfig:M.modelConfig,previewId:M.previewId});ie.current=R??null,F({...e,domainCandidates:Ce.domainCandidates}),w(e.allowedDomains),te(e.modelConfig?.model??``),k(e.modelConfig?.reasoning_effort??``),O(e.maxChildren||2),j(`success`),E(m(`drawer.subagentApplied`)),N(null);try{await r.onRefresh?.()}catch{j(`warning`),E(m(`drawer.subagentAppliedRefreshFailed`))}}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentApplyFailed`))}}}return(0,V.jsxs)(`div`,{"aria-labelledby":`personal-drawer-title`,"aria-modal":f.kind===`todo`?void 0:`true`,className:`personal-context-drawer`,"data-context-kind":f.kind,ref:ce,role:`dialog`,children:[(0,V.jsxs)(`header`,{className:`personal-drawer-header${f.kind===`todo`?` is-task-inspector`:``}`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`h2`,{id:`personal-drawer-title`,ref:ue,tabIndex:-1,children:pe}),(0,V.jsx)(`p`,{children:he})]}),(0,V.jsxs)(`div`,{className:`personal-drawer-header-actions`,children:[f.kind===`todo`&&l?(0,V.jsx)(`button`,{"aria-label":m(o?`drawer.inspectorHalf`:`drawer.inspectorFull`),className:`personal-icon-button personal-inspector-size`,onClick:l,title:m(o?`drawer.inspectorHalfView`:`drawer.inspectorFullView`),type:`button`,children:o?(0,V.jsx)(Om,{size:17}):(0,V.jsx)(wm,{size:17})}):null,(0,V.jsxs)(`button`,{"aria-label":m(`drawer.closeDetail`,{context:he}),className:`personal-icon-button personal-drawer-close`,onClick:fe,ref:se,type:`button`,children:[(0,V.jsx)(Gp,{className:`personal-mobile-back`,size:18}),(0,V.jsx)($m,{className:`personal-desktop-close`,size:18})]})]})]}),(0,V.jsxs)(`div`,{className:`personal-drawer-body`,children:[f.kind===`attention`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card is-attention`,children:[(0,V.jsx)(`small`,{children:f.item.blocking?m(`drawer.attentionBlocking`):m(`drawer.attentionWaiting`)}),(0,V.jsx)(`h3`,{children:f.item.text}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,V.jsx)(`dd`,{children:f.item.priority??`medium`})]}),ve?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`common.waiting`)}),(0,V.jsx)(`dd`,{children:m(`tasks.waitingAge`,{age:ve})})]}):null]})]}),(0,V.jsx)(Ly,{item:f.item,onSelect:n,successor:Kd(f.item,t)}),!u&&qd(f.item)?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void Se(f.item,`approve`,m(`common.confirm`)),type:`button`,children:[(0,V.jsx)(em,{size:17}),m(`drawer.decisionReview`)]}),(0,V.jsxs)(`details`,{className:`personal-compact-menu`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(dm,{size:17}),m(`drawer.decisionMore`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`button`,{onClick:()=>void r.onExplainDecision?.(f.item),type:`button`,children:[(0,V.jsx)(Em,{size:16}),m(`drawer.explainDecision`)]}),qy.map(e=>(0,V.jsx)(`button`,{onClick:()=>void Se(f.item,e.resolution,m(e.key)),type:`button`,children:m(e.key)},e.resolution))]})]})]}):null]}):null,f.kind===`todo`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-task-inspector-summary`,children:[(0,V.jsxs)(`div`,{className:`personal-task-inspector-status`,children:[(0,V.jsxs)(`span`,{className:f.item.done?`is-done`:f.item.status===`blocked`?`is-blocked`:`is-open`,children:[(0,V.jsx)(`i`,{}),f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)]}),f.item.priority?(0,V.jsx)(`span`,{children:f.item.priority}):null,(0,V.jsx)(`span`,{children:f.item.taskClass===`advancement_task`?m(`drawer.taskAdvancement`):f.item.taskClass??m(`drawer.taskOrdinary`)})]}),(0,V.jsx)(`h3`,{children:f.item.text})]}),(0,V.jsxs)(`section`,{"aria-label":m(`drawer.taskInfo`),className:`personal-task-inspector-fields`,children:[(0,V.jsx)(`h4`,{children:m(`drawer.taskInfo`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`common.owner`)}),(0,V.jsx)(`dd`,{children:f.item.ownerLabel??f.item.claimedBy??m(`drawer.notAssigned`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`common.status`)}),(0,V.jsx)(`dd`,{children:f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,V.jsx)(`dd`,{children:f.item.priority??m(`drawer.notSet`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.dependencies`)}),(0,V.jsx)(`dd`,{children:f.item.dependencies?.join(` · `)||m(`common.none`)})]}),f.item.resumeWhen?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.resumeWhen`)}),(0,V.jsx)(`dd`,{children:f.item.resumeWhen})]}):null,f.item.resumeWhen?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.resumeState`)}),(0,V.jsx)(`dd`,{children:f.item.resumeReady?m(`drawer.resumeReady`):m(`drawer.resumePending`)})]}):null,f.item.resumeReceiptId?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.resumeReceipt`)}),(0,V.jsx)(`dd`,{children:f.item.resumeReceiptId})]}):null,(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.nextTransition`)}),(0,V.jsx)(`dd`,{children:f.item.nextTransition??(f.item.done?m(`drawer.taskNextCompleted`):f.item.status===`deferred`?m(`drawer.taskNextDeferred`):m(`drawer.taskNextOpen`))})]})]})]}),!u&&!f.item.done?(0,V.jsxs)(`div`,{className:`personal-task-inspector-actions`,"aria-label":m(`drawer.taskActions`),children:[(0,V.jsxs)(`details`,{className:`personal-task-management`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(dm,{size:16}),m(`drawer.taskManage`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.reassign`)}),(0,V.jsxs)(`label`,{className:`personal-inline-agent-select`,children:[m(`drawer.reassign`),(0,V.jsx)(`select`,{"aria-label":m(`drawer.reassign`),onChange:e=>ae(e.target.value),value:I,children:e.filter(e=>e.available).map(e=>(0,V.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:f.item.goalId,kind:`todo`,todo_id:f.item.todoId},idempotencyKey:`workspace-todo-${f.item.todoId}-reassign-${I}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:I,goal_id:f.item.goalId,operation:`reassign`,todo_id:f.item.todoId},summary:m(`drawer.reassignSummary`,{task:f.item.text})}),type:`button`,children:m(`timeline.review`)})]}),(0,V.jsx)(`strong`,{children:m(`drawer.taskDeferUntil`)}),(0,V.jsxs)(`label`,{className:`personal-inline-agent-select personal-inline-resume-when`,children:[m(`drawer.taskDeferUntil`),(0,V.jsx)(`input`,{"aria-label":m(`drawer.taskDeferCondition`),"aria-invalid":!!L.trim()&&!ye,onChange:e=>oe(e.target.value),placeholder:m(`drawer.taskDeferPlaceholder`),value:L}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:!ye,onClick:()=>void xe(f.item,`defer`,m(`drawer.taskDefer`),ye??void 0),type:`button`,children:m(`drawer.taskDeferReview`)}),(0,V.jsx)(`small`,{children:L.trim()&&!ye?m(`drawer.taskDeferInvalid`):m(`drawer.taskDeferSupported`)})]}),(0,V.jsx)(`div`,{className:`personal-task-management-secondary`,children:Ky.map(e=>(0,V.jsx)(`button`,{onClick:()=>void xe(f.item,e.operation,m(e.key)),type:`button`,children:m(e.key)},e.operation))})]})]}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void xe(f.item,`complete`,m(`drawer.taskComplete`)),type:`button`,children:[(0,V.jsx)(em,{size:17}),m(`drawer.taskComplete`)]})]}):null,f.item.done?(0,V.jsxs)(`div`,{className:`personal-task-completed-note`,children:[(0,V.jsx)(em,{size:16}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.taskCompletedTitle`)}),(0,V.jsx)(`small`,{children:m(`drawer.taskCompletedNote`)})]})]}):null]}):null,f.kind===`goal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsx)(`small`,{children:Ji(f.item.state,p)}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.agentSentence}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.tokens`)}),(0,V.jsxs)(`dd`,{children:[yy(f.item.usage?.tokens24h,m(`drawer.usageNotMeasured`),gy),` / `,yy(f.item.usage?.tokens7d,m(`drawer.usageNotMeasured`),gy)]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.cost`)}),(0,V.jsxs)(`dd`,{children:[yy(f.item.usage?.costUsd24h,m(`drawer.usageNotMeasured`),_y),` / `,yy(f.item.usage?.costUsd7d,m(`drawer.usageNotMeasured`),_y)]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.duration`)}),(0,V.jsxs)(`dd`,{children:[yy(f.item.usage?.durationMs24h,m(`drawer.usageNotMeasured`),vy),` / `,yy(f.item.usage?.durationMs7d,m(`drawer.usageNotMeasured`),vy)]})]})]})]}),(0,V.jsx)(Iy,{goal:f.item}),(()=>{let e=i.find(e=>e.goalId===f.item.goalId),t=s.find(e=>e.goal_id===f.item.goalId);return(0,V.jsxs)(V.Fragment,{children:[f.item.repository?(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-repository`,children:[(0,V.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,V.jsx)(`small`,{children:m(`drawer.repository`)}),(0,V.jsx)(`em`,{children:m(`common.readOnly`)})]}),(0,V.jsxs)(`h3`,{children:[(0,V.jsx)(_m,{size:16}),f.item.repository.label]}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.branch`)}),(0,V.jsx)(`dd`,{children:f.item.repository.branch||`detached`})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Role`}),(0,V.jsx)(`dd`,{children:m(`drawer.repositoryRole`)})]})]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>{let e=navigator.clipboard?.writeText(f.item.repository?.identity??``);if(!e){b(`error`);return}e.then(()=>b(`copied`)).catch(()=>b(`error`))},type:`button`,children:[(0,V.jsx)(cm,{size:15}),m(y===`copied`?`drawer.copyRepositoryDone`:`drawer.copyRepository`)]}),y===`error`?(0,V.jsx)(`p`,{className:`personal-copy-feedback is-error`,role:`status`,children:m(`drawer.copyRepositoryError`)}):y===`copied`?(0,V.jsx)(`p`,{className:`personal-copy-feedback`,role:`status`,children:m(`drawer.copyRepositorySuccess`)}):null]}):null,u?(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,V.jsx)(`small`,{children:m(`drawer.larkConnection`)}),(0,V.jsx)(`h3`,{children:m(`drawer.remoteDetailsUnavailable`)}),(0,V.jsx)(`p`,{children:m(`drawer.remoteDetailsDescription`)})]}):(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,V.jsx)(`small`,{children:m(`drawer.larkConnection`)}),t?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`h3`,{children:[t.app_label,(0,V.jsx)(`span`,{className:`personal-connection-status`,children:m(`drawer.connected`)})]}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.group`)}),(0,V.jsx)(`dd`,{children:t.chat_name})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.topic`)}),(0,V.jsxs)(`dd`,{children:[`# `,t.topic_name]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.trigger`)}),(0,V.jsx)(`dd`,{children:t.incoming_mode===`mentions`?m(`lark.someoneMentions`):m(`lark.allMessages`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.replyMode`)}),(0,V.jsx)(`dd`,{children:m(`lark.topicReply`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.autoNotify`)}),(0,V.jsx)(`dd`,{children:e?.humanGateAutoNotifyEnabled?m(`common.on`):m(`common.off`)})]}),e?.lastNotifiedAt?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.lastNotification`)}),(0,V.jsx)(`dd`,{children:e.lastNotifiedAt})]}):null]})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h3`,{children:m(`drawer.larkNotConfigured`)}),(0,V.jsx)(`p`,{children:m(`drawer.larkNotConfiguredDescription`)})]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onOpenNotificationSettings?.(f.item.goalId),type:`button`,children:[(0,V.jsx)(Xp,{size:16}),m(t?`drawer.larkConfigure`:`drawer.larkConnect`)]})]})]})})(),(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-session`,children:[(0,V.jsx)(`small`,{children:m(`drawer.runDetails`)}),ge?.sessionId?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h3`,{children:Yi(ge.sessionStatus??ge.status,m)}),(0,V.jsx)(`p`,{children:ge.title}),r.onOpenRunSession?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onOpenRunSession?.(ge),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.runLatest`)]}):null]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h3`,{children:m(`drawer.noRun`)}),(0,V.jsx)(`p`,{children:m(`drawer.noRunDescription`)})]})]}),u?null:(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`heartbeat`,f.item.goalId),type:`button`,children:[(0,V.jsx)(Fm,{size:16}),m(`drawer.setupHeartbeat`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`monitor`,f.item.goalId),type:`button`,children:[(0,V.jsx)($p,{size:16}),m(`drawer.scheduleAdd`)]})]}),f.item.subagentExecution?(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-subagents`,children:[(0,V.jsxs)(`div`,{className:`personal-subagent-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:m(`drawer.subagentLabel`)}),(0,V.jsxs)(`h3`,{children:[(0,V.jsx)(Zp,{size:16}),m(`drawer.subagentTitle`)]})]}),(0,V.jsxs)(`button`,{"aria-checked":Ce.enabled,"aria-label":m(M&&A===`ready`?`drawer.subagentPending`:Ce.enabled?`drawer.subagentDisable`:`drawer.subagentEnable`),className:`personal-subagent-switch`,"data-pending":M&&A===`ready`?`true`:void 0,disabled:u||we||!!M||!r.onPreviewGoalSubagentConfiguration,onClick:()=>void Oe(!Ce.enabled),role:`switch`,type:`button`,children:[(0,V.jsx)(`span`,{}),m(M&&A===`ready`?`drawer.subagentPending`:Ce.enabled?`common.on`:`common.off`)]})]}),(0,V.jsx)(`p`,{children:m(`drawer.subagentDescription`)}),M&&A===`ready`?(0,V.jsxs)(`div`,{className:`personal-subagent-preview`,children:[(0,V.jsx)(`strong`,{children:m(M.enabled?`drawer.subagentConfirmEnable`:`drawer.subagentConfirmDisable`)}),(0,V.jsx)(`p`,{children:M.enabled?m(`drawer.subagentPreviewSummary`,{count:M.maxChildren,domains:M.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)}):m(`drawer.subagentDisableSummary`)}),M.modelConfig===void 0?null:(0,V.jsxs)(`p`,{children:[m(`drawer.subagentModel`),`: `,M.modelConfig?.model||m(`drawer.subagentModelDefault`),` · `,M.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`button`,{className:`personal-primary-action`,onClick:()=>void ke(),type:`button`,children:m(`common.confirm`)}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:z,type:`button`,children:m(`common.cancel`)})]})]}):null,T?(0,V.jsxs)(`p`,{className:`personal-subagent-feedback is-${A}`,role:`status`,children:[A===`previewing`||A===`applying`?(0,V.jsx)(Lm,{className:`personal-spin`,size:13}):null,T]}):null,(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentModel`)}),(0,V.jsx)(`dd`,{children:Ce.modelConfig?.model||m(`drawer.subagentModelDefault`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentEffort`)}),(0,V.jsx)(`dd`,{children:Ce.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentCurrentBoundary`)}),(0,V.jsx)(`dd`,{children:Ce.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentChildLimit`)}),(0,V.jsx)(`dd`,{children:Ce.maxChildren||0})]})]}),u?(0,V.jsx)(`p`,{className:`personal-subagent-read-only`,children:m(`drawer.subagentRemoteReadOnly`)}):(0,V.jsxs)(`div`,{className:`personal-subagent-fields`,children:[(0,V.jsxs)(`fieldset`,{className:`personal-subagent-domain-picker`,disabled:we,children:[(0,V.jsx)(`legend`,{children:m(`drawer.subagentDomains`)}),Te.length>0?(0,V.jsx)(`div`,{className:`personal-subagent-domain-options`,children:Te.map(e=>{let t=C.includes(e.value);return(0,V.jsxs)(`label`,{className:`personal-subagent-domain-option${t?` is-selected`:``}`,children:[(0,V.jsx)(`input`,{"aria-label":e.value,checked:t,onChange:t=>De(e.value,t.target.checked),type:`checkbox`}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.value}),(0,V.jsx)(`small`,{children:m(`drawer.subagentDomainTodoCount`,{count:e.matchingTodoCount})})]})]},e.value)})}):(0,V.jsx)(`p`,{className:`personal-subagent-domain-empty`,children:m(`drawer.subagentDomainsEmpty`)}),(0,V.jsx)(`small`,{children:m(`drawer.subagentDomainsHint`)})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:m(`drawer.subagentModel`)}),(0,V.jsx)(`input`,{"aria-label":m(`drawer.subagentModel`),disabled:we,value:ee,placeholder:`gpt-5.6-luna`,onChange:e=>{te(e.target.value),N(null),j(`idle`),E(null)}})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:m(`drawer.subagentEffort`)}),(0,V.jsxs)(`select`,{"aria-label":m(`drawer.subagentEffort`),disabled:we,value:ne,onChange:e=>{k(e.target.value),N(null),j(`idle`),E(null)},children:[(0,V.jsx)(`option`,{value:``,children:m(`drawer.subagentModelDefault`)}),[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`].map(e=>(0,V.jsx)(`option`,{value:e,children:e},e))]})]}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:we,type:`button`,onClick:()=>{te(`gpt-5.6-luna`),k(`max`),N(null),j(`idle`),E(null)},children:m(`drawer.subagentLunaPreset`)}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:we,type:`button`,onClick:()=>{te(``),k(``),N(null),j(`idle`),E(null)},children:m(`drawer.subagentClearModel`)}),(0,V.jsx)(`p`,{children:m(`drawer.subagentModelHint`)}),(0,V.jsxs)(`label`,{className:`personal-subagent-limit-field`,children:[(0,V.jsx)(`span`,{children:m(`drawer.subagentMaxChildren`)}),(0,V.jsx)(`select`,{"aria-label":m(`drawer.subagentMaxChildren`),disabled:we,onChange:e=>{O(Number(e.target.value)),N(null),j(`idle`),E(null)},value:D,children:Jy.map(e=>(0,V.jsx)(`option`,{value:e,children:e},e))})]}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:we,onClick:()=>void Oe(Ce.enabled,!0),type:`button`,children:m(`drawer.subagentPreviewBoundary`)})]})]}):null]}):null,f.kind===`run`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`div`,{"aria-label":m(`drawer.runView`),className:`personal-run-drawer-tabs`,role:`tablist`,children:[(0,V.jsx)(`button`,{"aria-selected":x===`record`,onClick:()=>S(`record`),role:`tab`,type:`button`,children:m(`drawer.executionRecordAndResult`)}),(0,V.jsx)(`button`,{"aria-selected":x===`details`,onClick:()=>S(`details`),role:`tab`,type:`button`,children:m(`drawer.detailsAndActions`)})]}),x===`record`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card personal-session-summary`,children:[(0,V.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Yi(f.item.sessionStatus??f.item.status,m)]}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.latestActivity}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,V.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]})]})]}),(0,V.jsxs)(`section`,{"aria-label":m(`drawer.executionRecord`),className:`personal-session-message-record`,children:[(0,V.jsx)(`h3`,{children:m(`drawer.executionRecord`)}),f.item.sessionMessages?.length?(0,V.jsx)(`ol`,{children:f.item.sessionMessages.map(e=>(0,V.jsxs)(`li`,{className:`is-${e.role}`,children:[(0,V.jsx)(`i`,{}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:e.role===`user`?m(`drawer.runRoleUser`):e.role===`assistant`?m(`drawer.runRoleAssistant`):m(`drawer.runRoleSystem`)}),e.createdAt?(0,V.jsx)(`time`,{children:new Date(e.createdAt).toLocaleTimeString(p,{hour:`2-digit`,minute:`2-digit`,hour12:!1})}):null]}),(0,V.jsx)(`p`,{children:e.text})]})]},e.messageId))}):(0,V.jsx)(`p`,{className:`personal-session-empty`,children:_e?m(`drawer.runRecordProjected`,{completed:f.item.completedSteps,outputs:f.item.outputs?.length?m(`drawer.runRecordProjectedOutputs`,{count:f.item.outputs.length}):``,total:f.item.totalSteps}):m(`drawer.runRecordEmpty`)}),f.item.status===`running`?(0,V.jsxs)(`div`,{className:`personal-session-active-step`,children:[(0,V.jsx)(`i`,{}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.analysis`)}),(0,V.jsx)(`small`,{children:m(`drawer.agentWorking`)})]})]}):null]}),f.item.outputs?.length?(0,V.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-run-outputs-title`,children:[(0,V.jsx)(`h3`,{id:`personal-run-outputs-title`,children:m(`drawer.outputs`)}),(0,V.jsx)(`ol`,{children:f.item.outputs.map(e=>(0,V.jsx)(`li`,{children:(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.title}),(0,V.jsx)(`small`,{children:e.createdAt??e.kind??m(`files.emptySummary`)})]})},e.outputId))})]}):null]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Yi(f.item.status,m)]}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.latestActivity}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,V.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.sessionStatus`)}),(0,V.jsx)(`dd`,{children:Yi(f.item.sessionStatus??f.item.status,m)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.sessionRecoverable`)}),(0,V.jsx)(`dd`,{children:f.item.resumable===!1?m(`drawer.resumeNo`):m(`drawer.resumeYes`)})]})]})]}),f.item.sessionStatus===`resume_failed`&&!u?(0,V.jsxs)(`section`,{className:`personal-recovery-panel`,"aria-label":m(`drawer.recoveryFailed`),children:[(0,V.jsx)(`strong`,{children:m(`drawer.recoveryFailed`)}),(0,V.jsx)(`p`,{children:m(`drawer.recoveryDescription`)}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,V.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.recoveryNewSession`)]})]}):null,u?null:(0,V.jsxs)(`section`,{className:`personal-correction-panel`,children:[(0,V.jsx)(`header`,{children:(0,V.jsxs)(`span`,{children:[(0,V.jsx)(Zp,{size:16}),m(`drawer.correctionLabel`,{agent:f.item.agentLabel})]})}),(0,V.jsx)(`p`,{children:m(`drawer.correctionDescription`)}),(0,V.jsxs)(`div`,{className:`personal-correction-composer`,children:[(0,V.jsx)(`textarea`,{"aria-label":m(`drawer.correctionTextarea`,{agent:f.item.agentLabel,goal:f.item.goalTitle,run:f.item.title}),onChange:e=>g(e.target.value),placeholder:m(`drawer.correctionPlaceholder`),rows:3,value:h}),(0,V.jsx)(`button`,{"aria-label":m(`drawer.correctionSend`),disabled:!h.trim(),onClick:()=>void be(),type:`button`,children:(0,V.jsx)(Bm,{size:16})})]})]}),u?null:(0,V.jsxs)(`details`,{className:`personal-compact-menu personal-run-more`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(dm,{size:17}),m(`drawer.moreRunActions`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`button`,{disabled:!f.item.canInterrupt,onClick:()=>void r.onInterruptRun?.(f.item),type:`button`,children:[(0,V.jsx)(Mm,{size:16}),m(`drawer.runInterrupt`)]}),(0,V.jsxs)(`button`,{disabled:f.item.resumable===!1,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,V.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,V.jsxs)(`button`,{onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.runNewSession`)]}),(0,V.jsxs)(`button`,{onClick:()=>void r.onCloseRunSession?.(f.item),type:`button`,children:[(0,V.jsx)(qm,{size:16}),m(`drawer.runCloseSession`)]})]})]})]})]}):null,f.kind===`output`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsx)(`small`,{children:f.item.kind??`output`}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.summary??m(`drawer.outputRecorded`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.outputTodo`)}),(0,V.jsx)(`dd`,{children:f.item.todoId??m(`drawer.notLinked`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.outputRun`)}),(0,V.jsx)(`dd`,{children:f.item.runId??m(`drawer.notLinked`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Agent`}),(0,V.jsx)(`dd`,{children:f.item.agentLabel??f.item.agentId??`LoopX`})]})]})]}),f.item.report?(0,V.jsxs)(`section`,{className:`personal-report-detail`,"data-testid":`personal-periodic-report-detail`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsxs)(`strong`,{children:[`+`,f.item.report.addedCount]}),m(`files.reportAdded`)]}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:f.item.report.changedCount}),m(`files.reportChanged`)]})]}),(0,V.jsxs)(`p`,{children:[f.item.report.periodStartAt,` → `,f.item.report.periodEndAt]}),(0,V.jsx)(`ol`,{children:f.item.report.items.map(e=>(0,V.jsxs)(`li`,{"data-change-kind":e.changeKind,children:[(0,V.jsxs)(`small`,{children:[e.changeKind,` · `,e.status]}),(0,V.jsx)(`strong`,{children:e.title}),(0,V.jsx)(`p`,{children:e.summary})]},e.sourceRef))}),(0,V.jsxs)(`footer`,{children:[(0,V.jsxs)(`span`,{children:[m(`files.reportPublication`),`: `,f.item.report.publicationId]}),(0,V.jsxs)(`span`,{children:[m(`files.reportGeneration`),`: `,f.item.report.generationId]})]})]}):null,f.item.safePreview?(0,V.jsx)(`pre`,{"aria-label":m(`drawer.outputSafePreview`),className:`personal-safe-preview`,children:f.item.safePreview}):(0,V.jsx)(`p`,{className:`personal-preview-unavailable`,children:m(`drawer.previewUnavailable`)}),(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:!r.onOpenOutput,onClick:()=>{r.onOpenOutput?.(f.item),c()},type:`button`,children:[(0,V.jsx)(fm,{size:16}),m(`files.openConversation`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!r.onExportOutput,onClick:()=>void r.onExportOutput?.(f.item),type:`button`,children:[(0,V.jsx)(um,{size:16}),m(`files.exportSummary`)]})]})]}):null,f.kind===`proposal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-proposal-card`,children:[(0,V.jsxs)(`small`,{children:[f.item.actionKind,` · `,f.item.status]}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.impact}),f.item.reviewPlan?(0,V.jsx)(`p`,{className:`personal-proposal-explainer`,"data-action-review":f.item.reviewPlan.interaction,children:m(`actionReview.${f.item.reviewPlan.reason}`)}):null,f.item.status===`ready`?(0,V.jsx)(`p`,{className:`personal-proposal-explainer`,children:m(`drawer.proposalExplainer`)}):null,(0,V.jsx)(`dl`,{children:f.item.fields.map(e=>(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:e.label}),(0,V.jsx)(`dd`,{children:e.value})]},e.key))})]}),f.item.status===`applied`?(0,V.jsxs)(`p`,{className:`personal-proposal-state is-applied`,children:[(0,V.jsx)(em,{size:16}),m(`drawer.proposalApplied`)]}):null,f.item.status===`applied`&&f.item.goalId?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>{let e=f.item.goalId;c(),r.onOpenGoal?.(e)},type:`button`,children:[(0,V.jsx)(fm,{size:16}),f.item.actionKind===`goal.create`?m(`drawer.proposalEnterGoal`):m(`drawer.proposalViewGoal`)]}):null,f.item.status===`stale`?(0,V.jsx)(`p`,{className:`personal-proposal-state is-stale`,children:m(`drawer.proposalStale`)}):null,f.item.status===`error`?(0,V.jsxs)(`div`,{className:`personal-proposal-state is-error`,children:[(0,V.jsx)(`span`,{children:f.item.reviewPlan?.reason===`readback_unverified`?m(`actionReview.readback_unverified`):m(`drawer.proposalApplyFailed`)}),f.item.errorMessage?(0,V.jsx)(`small`,{children:f.item.errorMessage}):null,(0,V.jsx)(`small`,{children:m(`drawer.proposalApplyFailedHint`)})]}):null,f.item.status===`rejected`?(0,V.jsx)(`p`,{className:`personal-proposal-state is-error`,children:m(`drawer.proposalRejected`)}):null,f.item.status===`deferred`?(0,V.jsx)(`p`,{className:`personal-proposal-state is-gated`,children:m(`drawer.proposalDeferred`)}):null,f.item.status===`gated`?(0,V.jsxs)(`div`,{className:`personal-proposal-state is-gated`,children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.gateRequiresHost`)}),m(`drawer.gateRequiresHostDescription`)]}),f.item.gate?.nextAction?(0,V.jsx)(`small`,{children:f.item.gate.nextAction}):null]}):null,f.item.status===`gated`&&f.item.actionKind===`gate.resolve`?(()=>{let e=e=>f.item.fields.find(t=>t.key===e)?.value,t=e(`goal_id`),n=e(`todo_id`);return!t||!n?null:(0,V.jsxs)(`section`,{className:`personal-detail-card personal-gate-cli-hint`,children:[(0,V.jsx)(`small`,{children:m(`drawer.gateApproveHint`)}),(0,V.jsxs)(`code`,{children:[`loopx todo complete --goal-id `,t,` --todo-id `,n,` --decision-outcome approve`]}),(0,V.jsx)(`small`,{children:m(`drawer.gateRejectHint`)})]})})():null,!u&&f.item.workspaceCandidates?.length?(0,V.jsx)(`div`,{className:`personal-workspace-candidates`,"aria-label":m(`drawer.workspaceCandidates`),children:f.item.workspaceCandidates.map(e=>(0,V.jsxs)(`button`,{onClick:()=>void r.onSelectWorkspaceCandidate?.(f.item,e.workspaceRef),type:`button`,children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsx)(`small`,{children:e.workspaceRef})]},e.workspaceRef))}):null,!u&&f.item.status===`error`?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,V.jsx)(Lm,{size:17}),m(`drawer.proposalRegenerate`)]}):!u&&f.item.status!==`gated`?(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:![`ready`,`deferred`].includes(f.item.status)||f.item.reviewPlan?.canApply===!1,onClick:()=>void r.onApplyProposal?.(f.item),type:`button`,children:[(0,V.jsx)(em,{size:17}),f.item.status===`applying`?m(`drawer.applying`):f.item.primaryLabel??m(`drawer.apply`)]}):null,!u&&([`stale`,`gated`,`rejected`].includes(f.item.status)||f.item.status===`ready`&&f.item.reviewPlan?.canApply===!1)?(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,V.jsx)(Lm,{size:16}),m(`drawer.proposalRecheck`)]}):null,!u&&[`ready`,`gated`].includes(f.item.status)?(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`defer`),type:`button`,children:m(`drawer.proposalDefer`)}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`reject`),type:`button`,children:m(`drawer.decisionReject`)})]}):null,[`applied`,`applying`].includes(f.item.status)?null:(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:c,type:`button`,children:m(`drawer.proposalClose`)})]}):null,f.kind===`schedule`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsxs)(`small`,{children:[f.item.scheduleKind===`heartbeat`?`Goal Heartbeat`:`continuous_monitor`,` · `,f.item.status??`active`]}),(0,V.jsx)(`h3`,{children:f.item.label}),(0,V.jsx)(`p`,{children:f.item.target??f.item.schedule??m(`drawer.scheduleDefaultTarget`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleTimezone`)}),(0,V.jsx)(`dd`,{children:f.item.timezone??m(`drawer.scheduleLocalTimezone`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleNext`)}),(0,V.jsx)(`dd`,{children:f.item.nextRunAt??m(`drawer.schedulePending`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleLast`)}),(0,V.jsx)(`dd`,{children:f.item.previousRunAt??m(`drawer.scheduleNeverRun`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleNotification`)}),(0,V.jsx)(`dd`,{children:f.item.notificationRule??m(`drawer.scheduleDefaultNotification`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleStopCondition`)}),(0,V.jsx)(`dd`,{children:f.item.stopCondition??m(`drawer.scheduleDefaultStop`)})]})]})]}),!u&&f.item.scheduleKind===`monitor`?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`run_now`),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.scheduleRunNow`)]}):null,u?null:(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,f.item.status===`paused`?`resume`:`pause`),type:`button`,children:[f.item.status===`paused`?(0,V.jsx)(Nm,{size:16}):(0,V.jsx)(Mm,{size:16}),f.item.status===`paused`?m(`drawer.scheduleResume`):m(`drawer.schedulePause`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`edit`),type:`button`,children:[(0,V.jsx)($p,{size:16}),m(`drawer.scheduleEdit`)]})]}),u?null:(0,V.jsxs)(`button`,{className:`personal-danger-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`stop`),type:`button`,children:[(0,V.jsx)(qm,{size:16}),m(`drawer.scheduleStop`,{kind:f.item.scheduleKind===`heartbeat`?` Heartbeat`:m(`drawer.titleSchedule`)})]}),(0,V.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-execution-history-title`,children:[(0,V.jsx)(`h3`,{id:`personal-execution-history-title`,children:m(`drawer.executionHistory`)}),f.item.executionHistory?.length?(0,V.jsx)(`ol`,{children:f.item.executionHistory.map((e,t)=>(0,V.jsxs)(`li`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsx)(`small`,{children:e.timestamp})]}),(0,V.jsx)(`em`,{className:`is-${e.status}`,children:e.status})]},`${e.timestamp}:${e.runId??t}`))}):(0,V.jsx)(`p`,{children:m(`drawer.noExecutionHistory`)})]})]}):null,f.kind===`run`||f.kind===`proposal`||f.kind===`schedule`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`button`,{"aria-expanded":_,className:`personal-diagnostics-trigger`,onClick:()=>v(e=>!e),type:`button`,children:[(0,V.jsx)(`span`,{children:m(`drawer.advancedDiagnostics`)}),(0,V.jsx)(tm,{className:_?`is-open`:``,size:16})]}),_?(0,V.jsxs)(`div`,{className:`personal-diagnostics`,children:[(0,V.jsxs)(`code`,{children:[`goal_id: `,me]}),(0,V.jsxs)(`code`,{children:[`kind: `,f.kind]}),f.kind===`run`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`code`,{children:[`session_id: `,f.item.sessionId??m(`drawer.notLinked`)]}),(0,V.jsxs)(`code`,{children:[`turn_id: `,f.item.turnId??m(`common.none`)]}),(0,V.jsxs)(`code`,{children:[`adapter: `,f.item.agentId]}),(0,V.jsxs)(`code`,{children:[`status: `,f.item.sessionStatus??f.item.status]})]}):f.kind===`proposal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`code`,{children:[`action: `,f.item.actionKind]}),(0,V.jsxs)(`code`,{children:[`status: `,f.item.status]})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`code`,{children:[`schedule_id: `,f.item.scheduleId]}),(0,V.jsxs)(`code`,{children:[`status: `,f.item.status??`active`]})]})]}):null]}):null]})]})}var $y=[`checking`,`connecting`,`downloading`,`installing_app`,`installing_runtime`],eb={desktop_status_unavailable:[`无法读取 App 更新状态。请重启 App 后再试;若仍失败,请重新安装最新 App。`,`Cannot read the App update status. Restart the App; if this persists, reinstall the latest App.`],update_feed_unavailable:[`此通道的更新源尚未就绪或暂时不可用。可稍后重新检查,当前版本仍可继续使用。`,`This channel's update feed is not ready or temporarily unavailable. Check again later; you can keep using this version.`],update_feed_invalid:[`更新源格式异常。请稍后重新检查。`,`The update feed is invalid. Check again later.`],update_platform_unavailable:[`此通道尚无适用于本机的更新包。`,`This channel has no update package for this platform.`],update_check_timeout:[`检查更新超时。请稍后重试。`,`The update check timed out. Try again later.`],update_network_failed:[`无法连接更新服务器。请检查网络后重试。`,`Cannot reach the update server. Check your connection and retry.`],update_download_or_signature_failed:[`更新包下载或签名校验失败,尚未安装。请重新检查更新。`,`Download or signature verification failed; the update was not installed. Check for updates again.`]};function tb(e,t=`update_failed`){return{phase:`error`,details:{code:typeof e==`string`&&Object.hasOwn(eb,e)?e:t}}}function nb(){let{locale:e}=qi(),t=e===`zh-CN`,[n,r]=(0,B.useState)(!1),i=(0,B.useRef)(null),[a,o]=(0,B.useState)(`stable`),[s,c]=(0,B.useState)({phase:`idle`}),[l,u]=(0,B.useState)(``),[d,f]=(0,B.useState)(!1),p=(0,B.useRef)(!1),m=window.__TAURI__?.core.invoke,h=$y.includes(s.phase);(0,B.useEffect)(()=>{let e=i.current;if(!e)return;let t=()=>r(e.matches(`:popover-open`));return e.addEventListener(`toggle`,t),()=>e.removeEventListener(`toggle`,t)},[]),(0,B.useEffect)(()=>{if(!m)return;let e=!0;return m(`desktop_update_status`).then(t=>{if(!e)return;u(t.app_version),f(t.rollback_available===!0),t.state?.phase&&c(t.state);let n=t.state?.details?.channel??(t.app_version.includes(`-main.`)?`main`:`stable`);o(n),t.state?.phase||m(`desktop_update`,{action:`check`,channel:n}).then(t=>{e&&c(t)}).catch(t=>{e&&c(tb(t))})}).catch(()=>{e&&c(tb(null,`desktop_status_unavailable`))}),()=>{e=!1}},[m]),(0,B.useEffect)(()=>{if(!m||!h)return;let e=window.setInterval(()=>{m(`desktop_update_status`).then(e=>{e.state?.phase&&c(e.state)}).catch(()=>{})},1e3);return()=>window.clearInterval(e)},[m,h]);async function g(e){if(!(!m||p.current)){p.current=!0,c({phase:e===`check`?`checking`:e===`repair`?`installing_runtime`:`downloading`});try{if(!l){let e=await m(`desktop_update_status`);u(e.app_version),f(e.rollback_available===!0)}c(await m(`desktop_update`,{action:e,channel:a}))}catch(e){c(tb(e,l?`update_failed`:`desktop_status_unavailable`))}finally{p.current=!1}}}let _={service_error:t?`运行时已安装,但服务尚未连接。可重试更新、修复或恢复上版。`:`Runtime installed, but services are unavailable. Retry updates, repair, or restore the previous version.`,idle:t?`App 会检查可用更新,不会自动安装。`:`Updates are checked automatically, never installed without confirmation.`,runtime_required:t?`请完成匹配组件安装,或检查 App 更新。`:`Install matching components or check for an App update.`,connecting:t?`正在连接更新后的服务…`:`Connecting to updated services…`,checking:t?`正在检查更新…`:`Checking for updates…`,available:t?`新版本已就绪,一次更新 App 与匹配的运行时。`:`Update the App and its matching runtime together.`,up_to_date:t?`当前通道暂无更新。`:`No newer update on this channel.`,downloading:t?`正在下载并校验签名…`:`Downloading and verifying signature…`,installing_app:t?`正在安装 App,请保持窗口打开。`:`Installing the App. Keep this window open.`,installing_runtime:t?`正在安装匹配的运行时,请稍候…`:`Installing the matching runtime…`,restart_required:t?`重启后将自动完成运行时安装与服务连接。`:`Restart to finish runtime installation and reconnect services.`,ready:t?`更新完成,服务已就绪。`:`Update completed; services are ready.`,error:eb[s.details?.code??``]?.[+!t]??(t?`更新未完成。请重试;启动失败可尝试修复当前版本。`:`Update incomplete. Retry; repair this version if startup fails.`)},v=h?t?`正在更新…`:`Updating…`:s.phase===`available`?t?`有可用更新`:`Update available`:s.phase===`restart_required`?t?`重启完成更新`:`Restart to finish`:s.phase===`error`?t?`更新需重试`:`Retry update`:t?`更新 LoopX`:`Update LoopX`;return(0,V.jsxs)(`div`,{className:`personal-desktop-update`,children:[(0,V.jsxs)(`button`,{className:`personal-update-trigger`,type:`button`,"aria-expanded":n,"aria-controls":`desktop-update-panel`,onClick:e=>{i.current?.style.setProperty(`bottom`,`${window.innerHeight-e.currentTarget.getBoundingClientRect().top+8}px`),i.current?.togglePopover()},children:[(0,V.jsx)(um,{size:16,"aria-hidden":`true`}),(0,V.jsx)(`span`,{children:v}),(0,V.jsx)(rm,{size:14,"aria-hidden":`true`})]}),(0,V.jsxs)(`section`,{ref:i,popover:`auto`,id:`desktop-update-panel`,className:`personal-update-panel`,"aria-label":t?`LoopX 更新`:`LoopX updates`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:t?`LoopX 更新`:`LoopX updates`}),(0,V.jsx)(`button`,{type:`button`,"aria-label":t?`关闭更新面板`:`Close updates`,onClick:()=>i.current?.hidePopover(),children:(0,V.jsx)($m,{size:16,"aria-hidden":`true`})})]}),(0,V.jsxs)(`small`,{children:[l,` · `,a===`main`?t?`main 预览版`:`main preview`:t?`稳定版`:`Stable`]}),s.details?.version?(0,V.jsxs)(`p`,{children:[t?`目标版本:`:`Target: `,s.details.version]}):null,(0,V.jsxs)(`p`,{role:`status`,"aria-live":`polite`,children:[h?(0,V.jsx)(Im,{className:`is-spinning`,size:14,"aria-hidden":`true`}):null,_[s.phase]]}),s.phase===`downloading`&&s.details?.total?(0,V.jsx)(`progress`,{"aria-label":t?`下载进度`:`Download progress`,max:s.details.total,value:s.details.received??0}):null,m?(0,V.jsx)(`div`,{className:`personal-update-actions`,children:s.phase===`restart_required`?(0,V.jsx)(`button`,{type:`button`,onClick:()=>void g(`restart`),children:t?`重启完成更新`:`Restart to finish`}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{type:`button`,disabled:h,onClick:()=>void g(`check`),children:t?`检查更新`:`Check for updates`}),s.phase===`available`?(0,V.jsx)(`button`,{type:`button`,onClick:()=>void g(`apply`),children:t?`更新并准备重启`:`Install update`}):null]})}):(0,V.jsx)(`p`,{children:t?`请在 LoopX App 中更新;浏览器自身无需安装包。`:`Update from the LoopX App; the browser needs no installer.`}),(0,V.jsxs)(`details`,{children:[(0,V.jsx)(`summary`,{children:t?`高级选项`:`Advanced options`}),(0,V.jsxs)(`label`,{children:[t?`更新通道`:`Update channel`,(0,V.jsxs)(`select`,{disabled:h||s.phase===`restart_required`,value:a,onChange:e=>{o(e.target.value),c({phase:`idle`})},children:[(0,V.jsx)(`option`,{value:`stable`,children:t?`稳定版(推荐)`:`Stable (recommended)`}),(0,V.jsx)(`option`,{value:`main`,children:t?`main 预览版`:`main preview`})]})]}),(0,V.jsx)(`p`,{children:t?`App 与匹配的 CLI 一起更新,服务可能短暂断开。不删除 Goal 数据。`:`Updates the App and matching CLI. Services may briefly disconnect. Goal data is not deleted.`}),m?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{children:t?`启动失败时,可重装当前 App 随附的运行时。`:`If startup fails, reinstall this App's bundled runtime.`}),(0,V.jsx)(`button`,{disabled:h||s.phase===`restart_required`,type:`button`,onClick:()=>void g(`repair`),children:t?`修复当前版本`:`Repair this version`})]}):null,m&&d?(0,V.jsxs)(`details`,{children:[(0,V.jsx)(`summary`,{children:t?`恢复上个版本`:`Restore previous version`}),(0,V.jsx)(`p`,{children:t?`将恢复已保留的 App 和它的运行时,需要重启。`:`Restore the retained App and its runtime, then restart.`}),(0,V.jsx)(`button`,{disabled:h,type:`button`,onClick:()=>void g(`rollback`),children:t?`确认恢复上版`:`Restore previous version`})]}):null]})]})]})}var rb=e=>`loopx-sidebar-goal-order-v1:${encodeURIComponent(e)}`;function ib(e){try{let t=JSON.parse(e??`null`);return Array.isArray(t)&&t.every(e=>typeof e==`string`)?[...new Set(t)]:[]}catch{return[]}}function ab(e,t){let n=new Map(t.map((e,t)=>[e,t]));return[...e].sort((e,t)=>(n.get(e.goalId)??1/0)-(n.get(t.goalId)??1/0))}function ob(e,t,n,r,i){if(n===r||!t.includes(n)||!t.includes(r))return e;let a=[...new Set([...e,...t])].filter(e=>e!==n);return a.splice(a.indexOf(r)+Number(i),0,n),a}function sb(e,t){let n=rb(t),[r,i]=(0,B.useState)(()=>{try{return ib(localStorage.getItem(n))}catch{return[]}}),[a,o]=(0,B.useState)(!1),[s,c]=(0,B.useState)(null),[l,u]=(0,B.useState)(null),d=(0,B.useRef)(null),f=(0,B.useRef)(!1),p=ab(e,r),m=p.map(e=>e.goalId);function h(t,a,s){let l=ob(r,m,t,a,s);if(l===r)return;i(l);let u=ab(e,l),d=u.findIndex(e=>e.goalId===t),f=u[d];f&&c({title:f.title,position:d+1});try{localStorage.setItem(n,JSON.stringify(l)),o(!1)}catch{o(!0)}}function g(){d.current=null,u(null)}return{sorted:p,target:l,saveFailed:a,lastMoved:s,move:h,moveBy(e,t){let n=p[m.indexOf(e)+t];n&&h(e,n.goalId,t===1)},pointerProps:e=>({onPointerDown(t){f.current=!1,t.pointerType===`mouse`&&t.button===0&&(d.current={id:e,x:t.clientX,y:t.clientY,dragging:!1},t.currentTarget.setPointerCapture(t.pointerId))},onPointerMove(e){let t=d.current;if(!t||!t.dragging&&Math.hypot(e.clientX-t.x,e.clientY-t.y)<6)return;t.dragging=!0,f.current=!0;let n=document.elementFromPoint(e.clientX,e.clientY)?.closest(`[data-reorder-goal]`),r=e.currentTarget.closest(`.personal-goal-list`),i=n?.dataset.reorderGoal;if(!n||!i||!r?.contains(n)||i===t.id){u(null);return}let a=n.getBoundingClientRect();u({id:i,after:e.clientY>a.top+a.height/2})},onPointerUp(){d.current?.dragging&&l&&h(d.current.id,l.id,l.after),g()},onPointerCancel:g,onLostPointerCapture:g,onKeyDown(e){e.key===`Escape`&&g()},onClickCapture(e){f.current&&=(e.preventDefault(),e.stopPropagation(),!1)}})}}var cb=`/ssh-hosts`,lb=/^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;function ub(e){return typeof e==`string`&&lb.test(e.trim())}function db(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`SSH Host 列表响应无效。`);let t=e;if(t.ok!==!0||t.schema_version!==`ssh_host_catalog_v0`||!Array.isArray(t.hosts))throw Error(`SSH Host 列表协议不兼容,请更新本机 LoopX 服务。`);let n=new Set;return{hosts:t.hosts.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=String(e.alias??``).trim();return!ub(t)||n.has(t)?[]:(n.add(t),[{alias:t}])}),schemaVersion:`ssh_host_catalog_v0`}}async function fb(e=fetch,t=cb){let n=await e(t,{cache:`no-store`});if(!n.ok)throw Error(`无法读取本机 SSH Host(HTTP ${n.status})。`);return db(await n.json())}function pb(e,t){let n=e.trim();if(!ub(n))return{error:`请选择有效的 SSH Host。`};let r=Number(t);return!Number.isInteger(r)||r<1024||r>65535?{error:`本地端口必须是 1024–65535 之间的整数。`}:{command:`ssh -N -L ${r}:127.0.0.1:8766 ${n}`,hostAlias:n,label:n,statusUrl:`http://127.0.0.1:${r}/status.json`}}var mb=`/api/ssh-source/ensure`,hb=`/api/ssh-source/goal-lifecycle`;async function gb(e,t){let n=await fetch(mb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({host_alias:e,local_port:Number(t)})}),r=await n.json().catch(()=>null);if(!n.ok)throw Error(r?.error??`无法建立 SSH 隧道来源。`);if(!r?.ok)throw Error(`无法建立 SSH 隧道来源。`);return r}async function _b(e,t,n,r,i=fetch){let a=await i(hb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({goal_id:t,host_alias:e,operation:n,reason:r})}),o=await a.json().catch(()=>null);if(!a.ok)throw Error(o?.error??`无法更新远端 Goal 生命周期。`);if(!o?.ok||o.schema_version!==`loopx_remote_goal_lifecycle_v1`||o.goal_id!==t||o.host_alias!==e||o.operation!==n||o.activation_state!==(n===`stop`?`stopped`:`active`)||o.projection_verified!==!0)throw Error(`远端 Goal 生命周期回读未验证。`);return o}function vb({activeSource:e,connectionState:t,errorMessage:n,onAdd:r,onConfiguredHostsLoaded:i,onRemove:a,onSelect:o,sources:s}){let{t:c}=qi(),[l,u]=(0,B.useState)(!1),[d,f]=(0,B.useState)(null),[p,m]=(0,B.useState)(`configured`),[h,g]=(0,B.useState)([]),[_,v]=(0,B.useState)(null),[y,b]=(0,B.useState)(!1),[x,S]=(0,B.useState)(!1),[C,w]=(0,B.useState)(``),[T,E]=(0,B.useState)(``),[D,O]=(0,B.useState)(`8876`),[ee,te]=(0,B.useState)(``),ne=`configured:`,k=[...s.map(e=>({label:e.label,value:e.id})),...h.filter(e=>!s.some(t=>t.label===e.alias)).map(e=>({group:c(`source.configuredGroup`,{count:h.length}),label:e.alias,value:`${ne}${e.alias}`}))],A=(0,B.useMemo)(()=>h.some(e=>e.alias===C)?pb(C,D):{error:c(`source.selectHost`)},[h,C,D,c]);(0,B.useEffect)(()=>{j()},[]);async function j(){b(!0),v(null);try{let e=await fb();g(e.hosts),i?.(e.hosts.map(e=>e.alias)),w(t=>t||e.hosts[0]?.alias||``),e.hosts.length||v(c(`source.hostEmpty`))}catch(e){v(e instanceof Error?e.message:c(`source.hostLoadError`))}finally{b(!1)}}function M(){u(!0),m(`configured`),f(null),j()}function N(){u(!1),m(`configured`),v(null),S(!1),w(``),f(null),E(``),O(`8876`),te(``)}function P(){let e=r({label:T,statusUrl:ee});if(e.error){f(e.error);return}N()}function F(){if(`error`in A){f(A.error??c(`source.invalid`));return}let e=r({ensureTunnel:!0,hostAlias:A.hostAlias,label:A.label,statusUrl:A.statusUrl});if(e.error){f(e.error);return}N()}function re(e){let t=new Set;for(let e of s)try{t.add(new URL(e.statusUrl).port)}catch{}let n=`8877`;for(let e=8877;e<9077;e+=1)if(!t.has(String(e))){n=String(e);break}let i=pb(e,n);if(`error`in i){f(i.error??c(`source.invalid`));return}let a=r({ensureTunnel:!0,hostAlias:i.hostAlias,label:i.label,statusUrl:i.statusUrl});a.error?f(a.error):f(null),O(n)}async function ie(){if(`error`in A){f(A.error??c(`source.invalid`));return}try{await navigator.clipboard.writeText(A.command),S(!0),f(null)}catch{f(c(`source.copyError`))}}return(0,V.jsxs)(`section`,{"aria-label":c(`source.controlPlane`),className:`personal-status-source`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`span`,{children:`Control plane`}),(0,V.jsx)(`button`,{"aria-label":c(`source.addSsh`),onClick:M,title:c(`source.add`),type:`button`,children:(0,V.jsx)(Pm,{size:14})})]}),(0,V.jsx)(Sy,{ariaLabel:c(`source.select`),className:`personal-status-source-select`,icon:(0,V.jsx)(Hm,{size:15}),onChange:e=>{if(e.startsWith(ne)){re(e.slice(11));return}o(e)},options:k,value:e.id}),(0,V.jsxs)(`div`,{className:`personal-status-source-meta`,children:[(0,V.jsxs)(`span`,{className:`is-${t}`,children:[(0,V.jsx)(`i`,{}),c(t===`loading`?`source.connecting`:t===`error`?`source.notAvailable`:`source.connected`)]}),(0,V.jsx)(`small`,{children:e.readOnly?c(`source.readOnly`):c(`source.localInteractive`)}),e.kind===`ssh_tunnel`?(0,V.jsx)(`button`,{"aria-label":c(`source.remove`,{source:e.label}),onClick:()=>a(e.id),title:c(`source.removeCurrent`),type:`button`,children:(0,V.jsx)(Xm,{size:12})}):null]}),n?(0,V.jsx)(`p`,{className:`personal-status-source-error`,role:`alert`,children:n}):null,l?(0,V.jsxs)(`div`,{className:`personal-status-source-form`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:c(`source.addSsh`)}),(0,V.jsx)(`button`,{"aria-label":c(`source.closeForm`),onClick:N,type:`button`,children:(0,V.jsx)($m,{size:13})})]}),(0,V.jsxs)(`div`,{"aria-label":c(`source.addMethod`),className:`personal-status-source-modes`,role:`tablist`,children:[(0,V.jsx)(`button`,{"aria-selected":p===`configured`,onClick:()=>{m(`configured`),f(null)},role:`tab`,type:`button`,children:c(`source.configured`)}),(0,V.jsx)(`button`,{"aria-selected":p===`manual`,onClick:()=>{m(`manual`),f(null)},role:`tab`,type:`button`,children:c(`source.manual`)})]}),p===`configured`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.configuredCount`,{count:h.length})}),(0,V.jsxs)(`span`,{className:`personal-status-source-field-row`,children:[(0,V.jsx)(`input`,{"aria-label":c(`source.host`),disabled:y||!h.length,list:`loopx-configured-ssh-hosts`,onChange:e=>{w(e.target.value),S(!1)},placeholder:c(y?`source.loadingHosts`:`source.hostPlaceholder`),value:C}),(0,V.jsx)(`datalist`,{id:`loopx-configured-ssh-hosts`,children:h.map(e=>(0,V.jsx)(`option`,{value:e.alias},e.alias))}),(0,V.jsx)(`button`,{"aria-label":c(`source.refreshHosts`),disabled:y,onClick:()=>void j(),title:c(`source.refreshHosts`),type:`button`,children:(0,V.jsx)(Rm,{size:13})})]})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.localPort`)}),(0,V.jsx)(`input`,{"aria-label":c(`source.localPort`),inputMode:`numeric`,onChange:e=>{O(e.target.value),S(!1)},value:D})]}),(0,V.jsxs)(`div`,{className:`personal-status-source-command`,children:[(0,V.jsx)(`code`,{children:`error`in A?c(`source.tunnelCommandPending`):A.command}),(0,V.jsxs)(`button`,{"aria-label":c(`source.copyCommand`),disabled:`error`in A,onClick:()=>void ie(),type:`button`,children:[(0,V.jsx)(cm,{size:12}),c(x?`source.copied`:`source.copy`)]})]}),_?(0,V.jsx)(`p`,{className:`is-error`,children:_}):null,(0,V.jsx)(`p`,{children:c(`source.description`)}),(0,V.jsx)(`button`,{className:`personal-status-source-add`,disabled:`error`in A,onClick:F,type:`button`,children:c(`source.addConfigured`)})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.name`)}),(0,V.jsx)(`input`,{autoFocus:!0,maxLength:48,onChange:e=>E(e.target.value),placeholder:c(`source.namePlaceholder`),value:T})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.statusUrl`)}),(0,V.jsx)(`input`,{onChange:e=>te(e.target.value),placeholder:`http://127.0.0.1:8876/status.json`,value:ee})]}),(0,V.jsx)(`p`,{children:(0,V.jsx)(`code`,{children:`ssh -N -L 8876:127.0.0.1:8766 `})}),(0,V.jsx)(`p`,{children:c(`source.manualDescription`)}),(0,V.jsx)(`button`,{className:`personal-status-source-add`,onClick:P,type:`button`,children:c(`source.addConfigured`)})]}),d?(0,V.jsx)(`p`,{className:`is-error`,role:`alert`,children:d}):null]}):null]})}var yb={需修复:`is-danger`,等你:`is-warning`,等待条件:`is-info`,推进中:`is-success`,安静运行:`is-quiet`,已完成:`is-quiet`,已停止:`is-stopped`};function bb({attentionCount:e,goals:t,goalArchiveLoadState:n={error:null,phase:`ready`},lifecycleBusyGoalIds:r,goalLifecycleOperations:i,onRequestGoalCreate:a,onOpenSettings:o,onRetryGoalArchive:s,onRequestGoalLifecycle:c,onSelectGoal:l,selectedGoalId:u,statusSourceControl:d}){let{locale:f,t:p}=qi(),[m,h]=(0,B.useState)(!1),g=sb(t.filter(e=>e.activationState!==`stopped`),d?.activeSource.statusUrl??`/status.json`),_=g.sorted,v=t.filter(e=>e.activationState===`stopped`),y=e=>!!c&&(!i||i.includes(e)),b=(e,t)=>(0,V.jsxs)(`div`,{className:`personal-goal-row${g.target?.id===e.goalId?g.target.after?` is-drop-after`:` is-drop-before`:``}`,"data-reorder-goal":t?void 0:e.goalId,"data-load-error":e.loadError,children:[(0,V.jsxs)(`button`,{...t?{}:g.pointerProps(e.goalId),title:t?void 0:p(`sidebar.dragGoal`),"aria-current":u===e.goalId?`page`:void 0,className:`personal-goal-link`,onClick:()=>l(e.goalId),type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-goal-state-dot ${e.loadState?``:yb[e.state]}`}),(0,V.jsxs)(`span`,{className:`personal-goal-link-copy`,children:[(0,V.jsx)(`strong`,{children:e.title}),(0,V.jsxs)(`small`,{children:[e.loadState&&(!t||u===e.goalId)?p(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Ji(e.state,f),e.needsYou&&!t?` · ${p(`home.lane.needsYou`)}`:``]})]}),(0,V.jsx)(nm,{size:15})]}),!t&&m?(0,V.jsxs)(`div`,{className:`personal-goal-move-actions`,children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveUp`,{goal:e.title}),disabled:_[0]?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,-1),children:(0,V.jsx)(Jp,{"aria-hidden":`true`,size:13})}),(0,V.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveDown`,{goal:e.title}),disabled:_.at(-1)?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,1),children:(0,V.jsx)(Wp,{"aria-hidden":`true`,size:13})})]}):null,c&&y(t?`resume`:`stop`)?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{"aria-label":`${p(t?`sidebar.resume`:`sidebar.stop`)} ${e.title}`,"aria-busy":r?.has(e.goalId)||void 0,className:`personal-goal-lifecycle${r?.has(e.goalId)?` is-pending`:``}`,disabled:r?.has(e.goalId),onClick:()=>c(e,t?`resume`:`stop`),title:p(t?`sidebar.resumeGoal`:`sidebar.stopGoal`),type:`button`,children:r?.has(e.goalId)?(0,V.jsx)(Cm,{size:13}):t?(0,V.jsx)(Lm,{size:13}):(0,V.jsx)(Mm,{size:13})}),t&&y(`delete`)?(0,V.jsx)(`button`,{"aria-label":`${p(`sidebar.delete`)} ${e.title}`,className:`personal-goal-lifecycle personal-goal-delete`,onClick:()=>c(e,`delete`),title:p(`sidebar.deleteGoal`),type:`button`,children:(0,V.jsx)(Xm,{size:13})}):null]}):null]},e.goalId);return(0,V.jsxs)(`div`,{className:`personal-goal-directory`,children:[(0,V.jsxs)(`div`,{className:`personal-sidebar-brand`,children:[(0,V.jsx)(`span`,{className:`personal-brand-mark`,children:(0,V.jsx)(Zp,{size:18})}),(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:`LoopX`})})]}),d?(0,V.jsx)(vb,{...d}):null,(0,V.jsxs)(`nav`,{"aria-label":p(`home.workspace`),className:`personal-sidebar-nav`,children:[(0,V.jsxs)(`button`,{"aria-current":u===null?`page`:void 0,className:`personal-manager-link`,onClick:()=>l(null),type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-manager-icon`,children:(0,V.jsx)(Zp,{size:17})}),(0,V.jsx)(`span`,{children:p(`sidebar.manager`)}),e>0?(0,V.jsx)(`span`,{className:`personal-sidebar-count`,children:e}):null,(0,V.jsx)(nm,{size:15})]}),(0,V.jsxs)(`div`,{className:`personal-sidebar-section-title`,children:[(0,V.jsx)(`span`,{children:`Goals`}),(0,V.jsxs)(`span`,{className:`personal-sidebar-title-actions`,children:[(0,V.jsx)(`small`,{children:_.length}),(0,V.jsx)(`button`,{"aria-label":p(`sidebar.sortGoals`),title:p(`sidebar.sortGoals`),"aria-pressed":m,onClick:()=>h(!m),type:`button`,children:(0,V.jsx)(qp,{"aria-hidden":`true`,size:15})}),a?(0,V.jsx)(`button`,{"aria-label":p(`sidebar.createGoal`),onClick:a,type:`button`,children:(0,V.jsx)(Pm,{size:15})}):null]})]}),g.saveFailed?(0,V.jsx)(`p`,{role:`status`,children:p(`sidebar.orderNotSaved`)}):null,(0,V.jsx)(`span`,{className:`personal-sr-only`,role:`status`,children:g.lastMoved?p(`sidebar.goalMoved`,{goal:g.lastMoved.title,position:g.lastMoved.position}):``}),(0,V.jsx)(`div`,{className:`personal-goal-list`,children:_.map(e=>b(e,!1))}),v.length||n.phase===`loading`||n.phase===`error`?(0,V.jsxs)(`details`,{className:`personal-stopped-goals`,open:n.phase===`error`||void 0,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(tm,{size:13}),(0,V.jsx)(`span`,{children:p(`sidebar.stopped`)}),n.phase===`loading`?(0,V.jsx)(Cm,{"aria-label":p(`sidebar.stoppedLoading`),className:`is-spinning`,size:13}):(0,V.jsx)(`small`,{children:v.length})]}),(0,V.jsxs)(`div`,{className:`personal-goal-list is-stopped`,children:[n.phase===`error`?(0,V.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`alert`,children:[(0,V.jsx)(`span`,{children:p(`sidebar.stoppedLoadFailed`)}),s?(0,V.jsx)(`button`,{onClick:s,type:`button`,children:p(`sidebar.retryStopped`)}):null]}):null,v.map(e=>b(e,!0))]})]}):null]}),(0,V.jsxs)(`div`,{className:`personal-sidebar-footer`,children:[(0,V.jsx)(nb,{}),o?(0,V.jsxs)(`button`,{"aria-label":p(`settings.open`),className:`personal-sidebar-utility`,onClick:o,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-sidebar-utility-icon`,children:(0,V.jsx)(Um,{size:17})}),(0,V.jsx)(`span`,{className:`personal-sidebar-utility-copy`,children:(0,V.jsx)(`strong`,{children:p(`settings.open`)})}),(0,V.jsx)(nm,{"aria-hidden":`true`,size:15})]}):null]})]})}var xb=Y({ok:X(!0),total:K().int().nonnegative(),next_cursor:G().nullable(),items:J(Y({todo_id:G(),text:G(),claimed_by:G().nullable(),evidence:G().nullable(),priority:G().nullable(),task_class:G().nullable()})).max(40)});function Sb({goal:e,agentId:t,seed:n,enabled:r,listView:i=!1,onSelect:a}){let{t:o}=qi(),s=(0,B.useId)(),[c,l]=(0,B.useState)(!1),u=!i||c,d=i?96:148,[f,p]=(0,B.useState)(n),[m,h]=(0,B.useState)(t===`all`?e.doneTodoCount??n.length:n.length),[g,_]=(0,B.useState)(void 0),[v,y]=(0,B.useState)(!1),[b,x]=(0,B.useState)(!1),[S,C]=(0,B.useState)(!1),[w,T]=(0,B.useState)({top:0,height:600}),[E,D]=(0,B.useState)(null),O=(0,B.useRef)(null),ee=(0,B.useRef)(null),[te,ne]=(0,B.useState)(0);(0,B.useEffect)(()=>{let e=O.current;if(!e)return;let t=new ResizeObserver(()=>T({top:e.scrollTop,height:e.clientHeight}));return t.observe(e),()=>{t.disconnect(),ee.current?.abort()}},[]);let k=g===void 0||w.top+w.height>=f.length*d-d*2;(0,B.useEffect)(()=>{if(!r||!u||!k||g===null||b||ee.current)return;let n=new AbortController;ee.current=n,y(!0);let i=new URLSearchParams({goal_id:e.goalId});t!==`all`&&i.set(`agent_id`,t),g&&i.set(`cursor`,g),fetch(`/api/chat/completed-todos?${i}`,{signal:n.signal}).then(async e=>{if(e.status===409&&C(!0),!e.ok)throw Error(`history unavailable`);let t=xb.parse(await e.json());if(n.signal.aborted)return;let r=t.items.map(e=>({todoId:e.todo_id,text:e.text,claimedBy:e.claimed_by,evidence:e.evidence,priority:e.priority,taskClass:e.task_class,done:!0,status:`done`}));p(e=>g===void 0?r:[...e,...r.filter(t=>!e.some(e=>e.todoId===t.todoId))]),h(t.total),_(t.next_cursor)}).catch(()=>{n.signal.aborted||x(!0)}).finally(()=>{n.signal.aborted||(ee.current=null,y(!1))})},[r,u,k,g,b,te,e.goalId,t,v]),(0,B.useEffect)(()=>{O.current&&(O.current.scrollTop=0),T({top:0,height:O.current?.clientHeight??600}),D(null)},[i]);let A=Math.max(0,Math.floor(w.top/d)-3),j=Math.min(f.length,Math.ceil((w.top+w.height)/d)+3),M=Array.from({length:Math.max(0,j-A)},(e,t)=>A+t);return E!==null&&El(e=>!e),children:[(0,V.jsx)(`span`,{"aria-hidden":`true`,children:c?`▾`:`▸`}),` `,o(`tasks.completed`)]}):(0,V.jsxs)(`strong`,{children:[(0,V.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-done`}),o(`tasks.completed`)]}),(0,V.jsx)(`span`,{children:m})]}),(0,V.jsxs)(`div`,{id:s,hidden:!u,"aria-label":o(`tasks.completed`),className:`personal-task-lane-scroll`,ref:O,role:`region`,tabIndex:0,onScroll:e=>T({top:e.currentTarget.scrollTop,height:e.currentTarget.clientHeight}),children:[(0,V.jsx)(`div`,{className:`personal-completed-window`,style:{height:f.length*d},children:M.map(t=>{let n=f[t];return(0,V.jsx)(`div`,{className:`personal-task-card personal-completed-row`,style:{top:t*d,height:d},children:(0,V.jsxs)(`button`,{type:`button`,onFocus:()=>D(t),onBlur:()=>D(null),onClick:()=>a({kind:`todo`,item:{...n,goalId:e.goalId,goalTitle:e.title,ownerLabel:n.claimedBy??e.agentLabel??e.agentId}}),children:[(0,V.jsx)(`span`,{className:`is-done`,children:`✓`}),(0,V.jsx)(`strong`,{children:n.text}),(0,V.jsx)(`small`,{children:n.claimedBy??e.agentLabel??e.agentId})]})},n.todoId)})}),(0,V.jsx)(`div`,{className:`personal-completed-footer`,role:`status`,children:v?o(`tasks.historyLoading`):b?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`span`,{children:o(S?`tasks.historyExpired`:`tasks.historyError`)}),(0,V.jsx)(`button`,{type:`button`,onClick:()=>{S&&(_(void 0),O.current&&(O.current.scrollTop=0)),C(!1),x(!1),ne(e=>e+1)},children:o(`tasks.historyRetry`)})]}):r?g===null?o(`tasks.historyEnd`):(0,V.jsx)(`button`,{type:`button`,onClick:()=>{O.current&&(O.current.scrollTop=f.length*d)},children:o(`tasks.historyMore`)}):o(`tasks.historyLocalOnly`)})]})]})}function Cb({children:e,count:t,label:n,tone:r,listView:i=!1}){let a=(0,B.useId)(),o=(0,B.useRef)(null),s=(0,B.useRef)([]),c=(0,B.useRef)(null),[l,u]=(0,B.useState)({after:!1,before:!1}),d=(0,B.useCallback)(()=>{let e=o.current;if(!e)return;let t={after:Math.max(0,e.scrollHeight-e.clientHeight)-e.scrollTop>1,before:e.scrollTop>1};u(e=>e.after===t.after&&e.before===t.before?e:t)},[]);return(0,B.useEffect)(()=>{let e=o.current;if(!e)return;let t=new ResizeObserver(d);return c.current=t,t.observe(e),e.addEventListener(`scroll`,d,{passive:!0}),d(),()=>{t.disconnect(),c.current=null,s.current=[],e.removeEventListener(`scroll`,d)}},[i,d]),(0,B.useEffect)(()=>{let e=o.current,t=c.current;if(!e||!t)return;for(let e of s.current)t.unobserve(e);let n=Array.from(e.children).filter(e=>e instanceof HTMLElement);for(let e of n)t.observe(e);s.current=n,d()},[e,t,i,d]),i?!t&&r!==`done`?null:(0,V.jsxs)(`details`,{className:`personal-task-group tone-${r}`,open:!0,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(tm,{size:16}),(0,V.jsx)(`strong`,{children:n}),(0,V.jsx)(`span`,{children:t})]}),(0,V.jsx)(`div`,{className:`personal-task-list-rows`,children:e})]}):(0,V.jsxs)(`section`,{className:`personal-object-list personal-task-lane`,children:[(0,V.jsxs)(`header`,{id:a,children:[(0,V.jsxs)(`strong`,{children:[(0,V.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-${r}`}),n]}),(0,V.jsx)(`span`,{children:t})]}),(0,V.jsx)(`div`,{"aria-labelledby":a,className:`personal-task-lane-scroll${l.before?` has-overflow-before`:``}${l.after?` has-overflow-after`:``}`,ref:o,role:`region`,tabIndex:t>0?0:-1,children:e})]})}function wb({historyEnabled:e=!1,goal:t,items:n,onDraftTaskFromMessage:r,onOpenChat:i,onQuickComplete:a,quickCompletingTodoIds:o,onSelect:s,selectedTodoId:c=null,userTodos:l}){let{t:u}=qi(),[d,f]=(0,B.useState)(!1),[p,m]=(0,B.useState)({goalId:``,laneId:`all`}),h=(0,B.useRef)(null);(0,B.useEffect)(()=>{if(!c)return;let e=window.requestAnimationFrame(()=>h.current?.scrollIntoView({block:`nearest`,inline:`nearest`}));return()=>window.cancelAnimationFrame(e)},[c]);let g=l.filter(e=>e.goalId===t.goalId).map(e=>({...e,goalTitle:t.title})),_=e=>e.priority===`P0`?0:e.priority===`P1`?1:e.priority===`P2`?2:3,v=(0,B.useMemo)(()=>{let e=new Map((t.agentLanes??[]).map(e=>[e.agentId,e]));for(let n of t.agentTodos)n.claimedBy&&!e.has(n.claimedBy)&&e.set(n.claimedBy,{agentId:n.claimedBy,label:n.claimedBy});return[...e.values()]},[t.agentLanes,t.agentTodos]),y=p.goalId===t.goalId&&v.some(e=>e.agentId===p.laneId)?p.laneId:`all`,b=e=>y===`all`||e===y,x=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&!e.done).filter(e=>b(e.claimedBy)).sort((e,t)=>_(e)-_(t)),S=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&e.done).filter(e=>b(e.claimedBy)),C=n.filter(e=>e.kind===`schedule`&&b(e.schedule.agentId)),w=n.filter(e=>e.kind===`run`&&!!e.run.todoId&&b(e.run.agentId)),T=!g.length&&!x.length&&!S.length&&!C.length,E=n.filter(e=>e.kind===`message`&&(e.message.role===`user`||e.message.role===`assistant`)),D=E.reduce((e,t,n)=>t.message.role===`user`?n:e,-1),O=D>=0?E[D]?.message:null,ee=D>=0?E.slice(D+1).reverse().find(e=>e.message.role===`assistant`)?.message:null,te=D>=0&&E.slice(D+1).some(e=>e.message.role===`assistant`&&e.message.pending);return(0,V.jsxs)(`section`,{"aria-label":u(`header.tasks`),className:`personal-task-board${d?` is-list-view`:``}`,children:[(0,V.jsxs)(`header`,{className:`personal-task-view-toolbar`,children:[(0,V.jsx)(`div`,{children:(0,V.jsx)(`strong`,{children:u(`header.tasks`)})}),(0,V.jsxs)(`div`,{className:`personal-task-view-switch`,role:`group`,"aria-label":u(`tasks.viewLabel`),children:[(0,V.jsx)(`button`,{type:`button`,"aria-pressed":d,onClick:()=>f(!0),children:u(`tasks.listView`)}),(0,V.jsx)(`button`,{type:`button`,"aria-pressed":!d,onClick:()=>f(!1),children:u(`tasks.boardView`)})]})]}),v.length>1?(0,V.jsxs)(`section`,{"aria-label":u(`tasks.agentLaneFilter`),className:`personal-task-lane-filter`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(Zp,{size:15}),(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:u(`tasks.agentLane`)})})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{className:`sr-only`,children:u(`tasks.agentLaneFilter`)}),(0,V.jsxs)(`select`,{"aria-label":u(`tasks.agentLaneFilter`),onChange:e=>m({goalId:t.goalId,laneId:e.target.value}),value:y,children:[(0,V.jsx)(`option`,{value:`all`,children:u(`tasks.allAgentLanes`,{count:v.length})}),v.map(e=>(0,V.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))]}),(0,V.jsx)(tm,{"aria-hidden":!0,size:14})]})]}):null,O?(0,V.jsxs)(`section`,{"aria-label":u(`tasks.chatRecent`),className:`personal-task-chat-receipt`,children:[(0,V.jsx)(`span`,{className:`personal-task-chat-icon`,children:(0,V.jsx)(Dm,{size:18})}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:u(te?`tasks.chatPending`:ee?`tasks.chatAgentReplied`:`tasks.chatRecent`)}),(0,V.jsx)(`small`,{children:t.agentLabel??t.agentId})]}),(0,V.jsxs)(`p`,{className:`is-user`,children:[(0,V.jsx)(`b`,{children:u(`common.you`)}),O.text]}),ee&&!ee.pending?(0,V.jsxs)(`p`,{className:`is-assistant`,children:[(0,V.jsx)(`b`,{children:u(`common.agent`)}),ee.text]}):null,(0,V.jsx)(`small`,{children:u(te?`tasks.chatPendingDescription`:`tasks.chatUnchangedDescription`)})]}),(0,V.jsxs)(`footer`,{children:[(0,V.jsxs)(`button`,{onClick:i,type:`button`,children:[(0,V.jsx)(Dm,{size:14}),u(`tasks.chatViewReply`)]}),ee&&!te&&r?(0,V.jsxs)(`button`,{onClick:()=>r(ee.text),type:`button`,children:[(0,V.jsx)(Sm,{size:14}),u(`tasks.convertToTask`)]}):null]})]}):null,(0,V.jsxs)(`div`,{className:d?`personal-task-grouped-list`:`personal-task-kanban`,children:[(0,V.jsxs)(Cb,{listView:d,count:g.length,label:u(`timeline.waitingConfirmation`),tone:`attention`,children:[g.map(e=>{let t=Xi(e.updatedAt,u);return(0,V.jsxs)(`button`,{onClick:()=>s({item:e,kind:`attention`}),type:`button`,children:[(0,V.jsx)(`span`,{"aria-hidden":`true`,className:`is-attention`,children:`!`}),(0,V.jsx)(`strong`,{children:e.text}),(0,V.jsxs)(`small`,{children:[(0,V.jsx)(`span`,{className:`personal-row-status ${e.blocking?`is-blocking`:`is-pending`}`,children:e.blocking?u(`tasks.blocked`):u(`tasks.pending`)}),t?(0,V.jsx)(`span`,{className:`personal-task-age`,children:u(`tasks.waitingAge`,{age:t})}):null]})]},e.todoId)}),g.length?null:(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyConfirm`)})]}),(0,V.jsxs)(Cb,{listView:d,count:x.length,label:u(`tasks.pendingAndRunning`),tone:`progress`,children:[x.map(e=>{let n={...e,goalId:t.goalId,goalTitle:t.title,ownerLabel:e.claimedBy??t.agentLabel??t.agentId},r=w.find(t=>t.run.todoId===e.todoId)?.run;return(0,V.jsxs)(`div`,{className:`personal-task-card${r?` has-session`:``}${c===e.todoId?` is-selected`:``}`,ref:c===e.todoId?e=>{h.current=e}:void 0,children:[(0,V.jsxs)(`button`,{"aria-pressed":c===e.todoId,onClick:()=>s({item:n,kind:`todo`}),type:`button`,children:[(0,V.jsx)(`span`,{children:`○`}),(0,V.jsx)(`strong`,{children:e.text}),(0,V.jsxs)(`small`,{children:[e.priority?(0,V.jsx)(`span`,{className:`personal-priority-badge is-${e.priority.toLowerCase()}`,children:e.priority}):null,e.status===`blocked`?(0,V.jsx)(`span`,{className:`personal-priority-badge is-blocked`,children:u(`tasks.blocked`)}):null,r?(0,V.jsx)(`span`,{className:`personal-task-session-status`,children:r.status===`running`||r.status===`queued`?u(`runs.running`):r.status===`failed`?u(`tasks.sessionError`):u(`common.waiting`)}):null,e.status===`deferred`?(0,V.jsx)(`span`,{className:`personal-task-session-status`,children:u(`drawer.taskStatusDeferred`)}):r?null:(0,V.jsx)(`span`,{className:`personal-task-session-status`,children:u(`tasks.waiting`)}),e.claimedBy??t.agentLabel??t.agentId]})]}),(0,V.jsxs)(`div`,{className:`personal-task-card-actions`,children:[r?(0,V.jsxs)(`button`,{className:`personal-task-session-link`,"aria-label":u(`tasks.openExecution`,{name:e.text}),onClick:()=>s({item:r,kind:`run`}),title:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`),type:`button`,children:[(0,V.jsx)(fm,{size:14}),(0,V.jsx)(`span`,{children:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`)})]}):null,a?(0,V.jsx)(`button`,{"aria-busy":o?.has(e.todoId)||void 0,"aria-label":u(`tasks.markComplete`,{name:e.text}),disabled:o?.has(e.todoId),onClick:()=>void a(n),title:u(`tasks.completed`),type:`button`,children:o?.has(e.todoId)?(0,V.jsx)(Cm,{className:`personal-spin`,size:14}):(0,V.jsx)(em,{size:14})}):null,(0,V.jsx)(`button`,{"aria-label":u(`tasks.moreActions`,{name:e.text}),onClick:()=>s({item:n,kind:`todo`}),title:u(`common.actions`),type:`button`,children:(0,V.jsx)(dm,{size:14})})]})]},e.todoId)}),x.length?null:(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyRunning`)})]}),(0,V.jsxs)(Cb,{listView:d,count:C.length,label:u(`tasks.scheduled`),tone:`schedule`,children:[C.map(e=>(0,V.jsxs)(`button`,{onClick:()=>s({item:e.schedule,kind:`schedule`}),type:`button`,children:[(0,V.jsx)(`span`,{children:`◷`}),(0,V.jsx)(`strong`,{children:e.schedule.label}),(0,V.jsx)(`small`,{children:e.schedule.status===`paused`?u(`schedule.paused`):u(`schedule.active`)})]},e.id)),C.length?null:(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptySchedules`)})]}),(0,V.jsx)(Sb,{goal:t,agentId:y,seed:S,enabled:e,listView:d,onSelect:s},`${t.goalId}:${y}:${e}`)]}),T?(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyGoal`)}):null]})}function Tb(e,t){return{live_steering:{label:t(`lark.ingressSteering`),detail:t(`lark.ingressSteeringDescription`)},session_queue:{label:t(`lark.ingressQueue`),detail:t(`lark.ingressQueueDescription`)},async_inbox:{label:t(`lark.ingressAsync`),detail:t(`lark.ingressAsyncDescription`)},direct_session:{label:t(`lark.ingressLegacy`),detail:t(`lark.ingressLegacyDescription`)}}[e]}function Eb(e,t){return e.listener_status===`starting`?{label:t(`lark.health.starting`),detail:t(`lark.health.startingDetail`),state:`not_ready`}:e.listener_status===`retrying`&&e.listener_error_code===`lark_event_source_disconnected`?{label:t(`lark.health.sourceDisconnected`),detail:t(`lark.health.sourceDisconnectedDetail`),state:`not_ready`}:e.listener_status===`retrying`?{label:t(`lark.health.retrying`),detail:t(`lark.health.retryingDetail`),state:`not_ready`}:e.listener_status===`stopped`||e.listener_status===null?{label:t(`lark.health.notStarted`),detail:t(`lark.health.notStartedDetail`),state:`not_ready`}:e.last_event_status===`message_context_permission_required`?{label:t(`lark.health.messageContextPermission`),detail:t(`lark.health.messageContextPermissionDetail`),state:`not_ready`}:e.last_event_status===`processing_failed`?{label:t(`lark.health.processingFailed`),detail:t(`lark.health.processingFailedDetail`),state:`not_ready`}:e.health_error_code===`invalid_routing_state`?{label:t(`lark.health.invalidRouting`),detail:t(`lark.health.invalidRoutingDetail`),state:`not_ready`}:e.last_event_status===`queued_for_agent`?{label:t(`lark.health.queued`),detail:t(`lark.health.queuedDetail`,{agent:e.agent_id??t(`lark.targetAgent`)}),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`not_addressed`?{label:t(`lark.health.notAddressed`),detail:t(`lark.health.notAddressedDetail`),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`self_message`?{label:t(`lark.health.listening`),detail:t(`lark.health.ignoredSelf`),state:`ready`}:e.health_error_code===`lark_event_route_mismatch`||[`chat_mismatch`,`topic_mismatch`,`route_ambiguous`].includes(e.last_event_reason??``)?{label:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguous`):t(`lark.health.routeMismatch`),detail:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguousDetail`):t(`lark.health.routeMismatchDetail`),state:`not_ready`}:[`invalid_event`,`binding_unavailable`].includes(e.last_event_reason??``)?{label:t(`lark.health.routeUnavailable`),detail:t(`lark.health.routeUnavailableDetail`),state:`not_ready`}:e.last_event_status===`replied_and_acknowledged`?{label:t(`lark.health.listening`),detail:t(`lark.health.eventProcessed`,{events:e.event_count,replies:e.replied_count}),state:`ready`}:e.health_error_code===`lark_event_delivery_unverified`||e.event_count===0?{label:t(`lark.health.eventUnverified`),detail:t(`lark.health.eventUnverifiedDetail`),state:`unverified`}:{label:e.reply_ready?t(`lark.health.listening`):t(`lark.health.unavailable`),detail:t(`lark.health.lastStatus`,{status:e.last_event_status??t(`lark.health.waiting`)}),state:e.reply_ready?`ready`:`not_ready`}}function Db(e){return e.history_permission_guidance?.api_document_url??null}function Ob(e,t,n){if(e instanceof Th){let t=String(e.payload.error_code??``);return{lark_cli_not_installed:n(`lark.error.cliMissing`),lark_cli_not_executable:n(`lark.error.cliExecutable`),lark_cli_start_failed:n(`lark.error.cliStart`),lark_message_permissions_required:n(`lark.error.messagePermissions`),lark_app_required:n(`lark.error.appRequired`),invalid_lark_app:n(`lark.error.invalidApp`),lark_group_lookup_failed:n(`lark.error.groupLookup`),provider_api_failed:n(`lark.error.provider`)}[t]??e.message}return e instanceof Error?e.message:t}function kb({embedded:e=!1,focusGoalConnection:t=!1,goals:n,initialGoalId:r,onChanged:i,onClose:a}){let{t:o}=qi(),[s,c]=(0,B.useState)(`connections`),[l,u]=(0,B.useState)([]),[d,f]=(0,B.useState)([]),[p,m]=(0,B.useState)(!0),[h,g]=(0,B.useState)(null),[_,v]=(0,B.useState)(``),[y,b]=(0,B.useState)(t),[x,S]=(0,B.useState)(``),[C,w]=(0,B.useState)(r??n[0]?.goalId??``),[T,E]=(0,B.useState)(``),[D,O]=(0,B.useState)([]),[ee,te]=(0,B.useState)(``),[ne,k]=(0,B.useState)(!1),[A,j]=(0,B.useState)(null),[M,N]=(0,B.useState)(`addressed_only`),[P,F]=(0,B.useState)(t&&r?`goal`:`manager`),[re,ie]=(0,B.useState)(`async_inbox`),[I,ae]=(0,B.useState)(`topic_reply`),[L,oe]=(0,B.useState)(``),[se,ce]=(0,B.useState)(!1),[le,ue]=(0,B.useState)({}),[de,R]=(0,B.useState)(!1),[fe,pe]=(0,B.useState)(null),[me,he]=(0,B.useState)(null),[ge,_e]=(0,B.useState)(null),[ve,ye]=(0,B.useState)(null),[be,xe]=(0,B.useState)(!1),[Se,Ce]=(0,B.useState)(`loopx-workspace-bot`),[we,Te]=(0,B.useState)(`feishu`),[z,Ee]=(0,B.useState)(null),[De,Oe]=(0,B.useState)(!1),[ke,Ae]=(0,B.useState)(null),je=(0,B.useRef)(null),Me=(0,B.useRef)(null),Ne=(0,B.useRef)(!1);async function Pe(){m(!0),g(null);try{let[e,t]=await Promise.all([Lg(),Kg()]);u(e),f(t),S(t=>t||e.find(e=>e.reply_ready)?.app_ref||e.find(e=>e.ready)?.app_ref||e[0]?.app_ref||``)}catch(e){g(Ob(e,o(`lark.error.configuration`),o))}finally{m(!1)}}(0,B.useEffect)(()=>{Pe()},[]),(0,B.useEffect)(()=>{if(!t||p||Ne.current||!r)return;Ne.current=!0;let e=d.find(e=>e.goal_id===r);e?qe(e):Ke(n.find(e=>e.goalId===r))},[d,t,n,r,p]),(0,B.useEffect)(()=>{if(!y||!x||ge){O([]),te(``),k(!1),j(null);return}let e=!1;k(!0),j(null);let t=window.setTimeout(()=>{Wg(x,T).then(t=>{e||(O(t),te(e=>t.some(t=>t.chat_id===e)?e:t[0]?.chat_id??``))}).catch(t=>{e||(O([]),te(``),j(Ob(t,o(`lark.error.groupLoad`),o)))}).finally(()=>{e||k(!1)})},180);return()=>{e=!0,window.clearTimeout(t)}},[x,T,y,ge]),(0,B.useEffect)(()=>{if(!be||!z||[`ready`,`failed`,`cancelled`].includes(z.status))return;let e=!1,t=window.setTimeout(()=>{Bg(z.setup_id).then(async t=>{e||(Ee(t),t.verification_url&&Me.current!==t.verification_url&&(Me.current=t.verification_url,je.current&&!je.current.closed&&(je.current.location.href=t.verification_url)),t.status===`ready`&&(await Pe(),S(t.app_ref),ue({}),xe(!1)),t.status===`failed`&&Ae(t.error??o(`lark.error.appCreate`)))}).catch(t=>{e||Ae(Ob(t,o(`lark.error.setupPoll`),o))})},650);return()=>{e=!0,window.clearTimeout(t)}},[be,z]);let H=n.find(e=>e.goalId===C),Fe=H?.agentId?[{agentId:H.agentId,label:H.agentLabel??H.agentId}]:[],Ie=H?.agentLanes?.length?H.agentLanes:Fe,Le=Ie.some(e=>e.agentId===L),Re=[];se?Re=Ie.map(e=>({agentId:e.agentId,appRef:le[e.agentId]??x})):Le&&(Re=[{agentId:L,appRef:x}]);let ze=Re.map(e=>e.agentId),Be=!!ge||Re.length>0&&Re.every(e=>l.some(t=>t.app_ref===e.appRef&&t.reply_ready)),Ve=o(`lark.connect`);me?Ve=o(`lark.saveConnection`):se&&(Ve=o(`lark.connectAllAgentsAction`,{count:ze.length}));let He=l.find(e=>e.app_ref===x),Ue=D.find(e=>e.chat_id===ee),We=(0,B.useMemo)(()=>{let e=_.trim().toLocaleLowerCase();return e?d.filter(t=>[t.app_label,t.chat_name,t.goal_title,t.topic_name].some(t=>t.toLocaleLowerCase().includes(e))):d},[d,_]),Ge=(0,B.useMemo)(()=>d.filter(e=>Eb(e,o).state===`unverified`).length,[d,o]);function Ke(e){let i=e??n.find(e=>e.goalId===r)??n[0];he(null),_e(null),F(e||t?`goal`:`manager`),S(l.some(e=>e.app_ref===x)?x:l.find(e=>e.reply_ready)?.app_ref??l[0]?.app_ref??``),te(``),w(i?.goalId??``),oe(i?.agentId??``),ce(!1),ue({}),N(`addressed_only`),ie(`async_inbox`),ae(`topic_reply`),E(``),pe(null),b(!0)}function qe(e){he(e.goal_id),_e(e),F(e.conversation_kind??`goal`),S(e.app_ref),w(e.goal_id);let t=n.find(t=>t.goalId===e.goal_id),r=t?.agentLanes?.length?t.agentLanes:t?.agentId?[{agentId:t.agentId}]:[];oe(e.agent_id??(r.length===1?r[0].agentId:``)),ce(!1),ue({}),N(e.capture_scope),ie(e.ingress_mode===`direct_session`?`async_inbox`:e.ingress_mode),ae(e.reply_mode),E(e.chat_name),pe(null),b(!0)}function Je(){Ee(null),Ae(null),Me.current=null,xe(!0)}async function Ye(){if(!(De||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Se))){Oe(!0),Ae(null),Me.current=null,je.current=window.open(window.location.href,`_blank`);try{let e=await zg({appRef:Se,brand:we});Ee(e)}catch(e){je.current?.close(),Ae(Ob(e,o(`lark.error.setupStart`),o))}finally{Oe(!1)}}}async function Xe(){let e=z;if(xe(!1),je.current?.close(),e&&![`ready`,`failed`,`cancelled`].includes(e.status))try{await Vg(e.setup_id)}catch{}}async function Ze(){if(!(!x||!C||!ge&&!Ue||P===`goal`&&ze.length===0||de)){R(!0),pe(null);try{let e={...P===`manager`?{...ge?{connectionId:ge.connection_id}:{appRef:x,chatId:Ue.chat_id,chatName:Ue.chat_name}}:ge?{connectionId:ge.connection_id,agentId:L}:{agentBindings:Re,chatId:Ue.chat_id,chatName:Ue.chat_name},conversationKind:P,captureScope:P===`manager`?`addressed_only`:M,goalId:C,incomingMode:M===`configured_chat_all`?`all`:`mentions`,ingressMode:P===`manager`?`session_queue`:re,replyMode:I},t=await qg({...e,execute:!1});if(!t.ok)throw new Th(t.public_summary??t.blocker??o(`lark.error.bindPreview`),{error_code:t.blocker??`provider_api_failed`});let n=await qg({...e,execute:!0});if(!n.ok)throw new Th(n.public_summary??n.blocker??o(`lark.error.bind`),{error_code:n.blocker??`provider_api_failed`});b(!1),await Pe(),i?.()}catch(e){pe(Ob(e,o(`lark.error.bind`),o))}finally{R(!1)}}}async function Qe(e,t){if(ve!==t){ye(t);return}try{await Jg(e,t),ye(null),await Pe(),i?.()}catch(e){g(Ob(e,o(`lark.error.disconnect`),o))}}return(0,V.jsxs)(`section`,{className:`personal-lark-settings${e?` is-embedded`:``}`,"aria-label":o(`lark.configuration`),children:[e?null:(0,V.jsxs)(`header`,{className:`personal-lark-header`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:o(`settings.goalConnections`)}),(0,V.jsx)(`h1`,{children:`Lark`})]}),(0,V.jsx)(`button`,{"aria-label":o(`lark.closeSettings`),className:`personal-icon-button`,onClick:a,type:`button`,children:(0,V.jsx)($m,{size:18})})]}),(0,V.jsxs)(`nav`,{className:`personal-lark-tabs`,"aria-label":o(`lark.management`),children:[(0,V.jsxs)(`button`,{"aria-current":s===`apps`?`page`:void 0,onClick:()=>c(`apps`),type:`button`,children:[o(`lark.apps`),` `,(0,V.jsx)(`span`,{children:p?`…`:l.length})]}),(0,V.jsxs)(`button`,{"aria-current":s===`connections`?`page`:void 0,onClick:()=>c(`connections`),type:`button`,children:[o(`lark.connections`),` `,(0,V.jsx)(`span`,{children:p?`…`:d.length})]})]}),h?(0,V.jsx)(`p`,{className:`personal-notification-error`,children:h}):null,p?(0,V.jsxs)(`div`,{className:`personal-lark-loading`,children:[(0,V.jsx)(Cm,{className:`is-spinning`,size:18}),o(`lark.loading`)]}):null,!p&&s===`apps`?(0,V.jsxs)(`div`,{className:`personal-lark-apps`,children:[(0,V.jsxs)(`div`,{className:`personal-lark-app-toolbar`,children:[(0,V.jsx)(`span`,{children:o(`lark.reusableApps`,{count:l.length})}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:Je,type:`button`,children:[(0,V.jsx)(Pm,{size:16}),o(`lark.newApp`)]})]}),(0,V.jsxs)(`div`,{className:`personal-lark-app-grid`,children:[l.map(e=>(0,V.jsxs)(`article`,{className:`personal-lark-app-card`,children:[(0,V.jsx)(`span`,{className:`personal-lark-app-avatar`,children:(0,V.jsx)(Zp,{size:19})}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsxs)(`small`,{children:[e.brand,` · lark-cli profile`]})]}),(0,V.jsx)(`em`,{className:e.reply_ready?`is-ready`:`is-off`,children:e.reply_ready?o(`lark.autoReplyReady`):e.ready?o(`lark.needsMessagePermissions`):o(`lark.needsSetup`)}),(0,V.jsxs)(`p`,{children:[o(`lark.goalConnections`,{count:d.filter(t=>t.app_ref===e.app_ref).length}),e.ready&&!e.reply_ready?` · ${o(`lark.autoReplyUnavailable`)}`:``]})]},e.app_ref)),l.length===0?(0,V.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noProfiles`)}):null]})]}):null,!p&&s===`connections`?(0,V.jsxs)(`div`,{className:`personal-lark-connections`,children:[Ge>0?(0,V.jsxs)(`p`,{className:`personal-lark-route-readiness`,role:`status`,children:[(0,V.jsx)(Dm,{size:15}),o(`lark.routesUnverified`,{count:Ge})]}):null,(0,V.jsxs)(`div`,{className:`personal-lark-toolbar`,children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(zm,{size:16}),(0,V.jsx)(`input`,{"aria-label":o(`lark.searchConnections`),onChange:e=>v(e.target.value),placeholder:o(`lark.searchPlaceholder`),type:`search`,value:_})]}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:l.length===0||n.length===0,onClick:()=>Ke(),type:`button`,children:[(0,V.jsx)(Pm,{size:16}),o(`lark.connectApp`)]})]}),(0,V.jsxs)(`div`,{className:`personal-lark-table`,role:`table`,"aria-label":o(`lark.goalTopicConnections`),children:[(0,V.jsxs)(`div`,{className:`personal-lark-table-head`,role:`row`,children:[(0,V.jsx)(`span`,{children:o(`lark.connection`)}),(0,V.jsx)(`span`,{children:o(`common.goal`)}),(0,V.jsx)(`span`,{children:o(`lark.capture`)}),(0,V.jsx)(`span`,{children:o(`lark.processing`)}),(0,V.jsx)(`span`,{children:o(`common.actions`)})]}),We.map(e=>{let t=Eb(e,o);return(0,V.jsxs)(`div`,{className:`personal-lark-table-row`,role:`row`,children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.chat_name}),(0,V.jsxs)(`small`,{children:[e.app_label,` · `,t.label]}),(0,V.jsx)(`small`,{children:t.detail}),t.state===`unverified`?(0,V.jsxs)(`a`,{href:`https://open.feishu.cn/document/server-docs/im-v1/message/events/receive?lang=zh-CN`,rel:`noreferrer`,target:`_blank`,children:[(0,V.jsx)(fm,{size:12}),o(`lark.openEventSettings`)]}):null,Db(e)?(0,V.jsxs)(`a`,{href:Db(e)??void 0,rel:`noreferrer`,target:`_blank`,children:[(0,V.jsx)(fm,{size:12}),o(`lark.historyPermission`)]}):null]}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.goal_title}),(0,V.jsxs)(`small`,{children:[`# `,e.topic_name]})]}),(0,V.jsx)(`span`,{children:e.capture_scope===`addressed_only`?o(`lark.mentionsOnly`):o(`lark.allTopicMessages`)}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.conversation_kind===`manager`?o(`lark.managerConversation`):Tb(e.ingress_mode,o).label}),(0,V.jsx)(`small`,{children:e.conversation_kind===`manager`?o(`lark.managerConversationDescription`):e.agent_id??Tb(e.ingress_mode,o).detail})]}),(0,V.jsxs)(`span`,{className:`personal-lark-row-actions`,children:[(0,V.jsx)(`button`,{"aria-label":o(`lark.settingsConfigure`,{goal:e.goal_title}),onClick:()=>qe(e),type:`button`,children:(0,V.jsx)(Um,{size:15})}),(0,V.jsxs)(`button`,{"aria-label":o(`lark.settingsDisconnect`,{goal:e.goal_title}),className:ve===e.connection_id?`is-confirm`:``,onClick:()=>void Qe(e.goal_id,e.connection_id),type:`button`,children:[(0,V.jsx)(Qm,{size:15}),ve===e.connection_id?o(`common.confirm`):null]})]})]},e.connection_id)}),We.length===0?(0,V.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noConnections`)}):null]})]}):null,y?(0,V.jsx)(`div`,{className:`personal-lark-modal-backdrop`,role:`presentation`,children:(0,V.jsxs)(`section`,{"aria-labelledby":`connect-lark-title`,"aria-modal":`true`,className:`personal-lark-modal`,role:`dialog`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:`Goal Topic connection`}),(0,V.jsx)(`h2`,{id:`connect-lark-title`,children:o(me?`lark.editConnection`:`lark.connectApp`)})]}),(0,V.jsx)(`button`,{"aria-label":o(`lark.closeConnection`),onClick:()=>b(!1),type:`button`,children:(0,V.jsx)($m,{size:18})})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.conversationKind`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.conversationKind`),disabled:!!ge,value:P,onChange:e=>F(e.target.value),children:[(0,V.jsx)(`option`,{value:`manager`,children:o(`lark.managerConversation`)}),(0,V.jsx)(`option`,{value:`goal`,children:o(`lark.workerConversation`)})]})]}),P===`manager`?(0,V.jsx)(`p`,{children:o(`lark.managerConversationDescription`)}):null,ge?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,V.jsx)(`div`,{children:ge.app_label})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,V.jsx)(`div`,{children:ge.chat_name})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,V.jsx)(`div`,{children:ge.goal_title})]}),(0,V.jsx)(`small`,{children:o(`lark.editPreservesIdentity`)})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,V.jsx)(`select`,{"aria-label":o(`lark.appProfile`),disabled:p,onChange:e=>{e.target.value===`__register__`?Je():(S(e.target.value),ue({}))},value:x,children:p?(0,V.jsx)(`option`,{value:``,children:o(`lark.appLoading`)}):(0,V.jsxs)(V.Fragment,{children:[l.map(e=>(0,V.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref)),(0,V.jsx)(`option`,{value:`__register__`,children:o(`lark.registerAnother`)})]})}),(0,V.jsx)(`small`,{children:o(`lark.defaultAgentAppDescription`)})]}),He?.ready&&!He.reply_ready?(0,V.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.appPermissions`)}):null,(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,V.jsx)(`input`,{"aria-label":o(`lark.groupSearch`),onChange:e=>E(e.target.value),placeholder:o(`lark.groupSearch`),type:`search`,value:T}),ne?(0,V.jsxs)(`div`,{className:`personal-lark-group-state`,role:`status`,children:[(0,V.jsx)(Cm,{className:`is-spinning`,size:15}),o(`lark.groupLoading`)]}):null,!ne&&A?(0,V.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:A}):null,!ne&&!A&&D.length===0?(0,V.jsx)(`div`,{className:`personal-lark-group-state`,role:`status`,children:o(`lark.groupEmpty`)}):null,!ne&&!A&&D.length>0?(0,V.jsx)(`select`,{"aria-label":o(`lark.groupChat`),onChange:e=>te(e.target.value),value:ee,children:D.map(e=>(0,V.jsx)(`option`,{value:e.chat_id,children:e.chat_name},e.chat_id))}):null]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,V.jsx)(`select`,{"aria-label":o(`lark.bindGoal`),onChange:e=>{let t=e.target.value;w(t),oe(n.find(e=>e.goalId===t)?.agentId??``),ue({})},value:C,children:n.map(e=>(0,V.jsx)(`option`,{value:e.goalId,children:e.title},e.goalId))})]})]}),(0,V.jsxs)(`label`,{className:`personal-lark-check`,children:[(0,V.jsx)(`input`,{checked:!0,readOnly:!0,type:`checkbox`}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:o(`lark.createAutomatically`)}),(0,V.jsx)(`small`,{children:o(`lark.createAutomaticallyDescription`)})]})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.topicPreview`)}),(0,V.jsxs)(`div`,{className:`personal-lark-topic-preview`,children:[(0,V.jsx)(Dm,{size:15}),`# `,H?.title??H?.goalId??`Goal`]})]}),P===`goal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.captureScope`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.captureScope`),disabled:ge?.ingress_mode===`direct_session`,onChange:e=>N(e.target.value),value:M,children:[(0,V.jsx)(`option`,{value:`addressed_only`,children:o(`lark.captureAddressed`)}),(0,V.jsx)(`option`,{value:`configured_chat_all`,children:o(`lark.captureAll`)})]}),(0,V.jsx)(`small`,{children:o(`lark.captureScopeDescription`)})]}),(0,V.jsxs)(`fieldset`,{"aria-label":o(`lark.agentIngress`),className:`personal-lark-ingress`,children:[(0,V.jsx)(`legend`,{children:o(`lark.agentIngress`)}),(0,V.jsx)(`div`,{children:[`live_steering`,`session_queue`,`async_inbox`].map(e=>{let t=Tb(e,o);return(0,V.jsxs)(`label`,{className:re===e?`is-active`:``,children:[(0,V.jsx)(`input`,{"aria-label":t.label,checked:re===e,name:`lark-agent-ingress`,onChange:()=>ie(e),type:`radio`,value:e}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:t.label}),(0,V.jsx)(`small`,{children:t.detail})]})]},e)})})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.targetAgent`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.targetAgent`),disabled:!!ge?.agent_id,onChange:e=>oe(e.target.value),value:L,children:[Le?null:(0,V.jsx)(`option`,{disabled:!0,value:L,children:L?o(`lark.agentUnavailable`,{agent:L}):o(`lark.noAgentConfigured`)}),Ie.map(e=>(0,V.jsx)(`option`,{value:e.agentId,children:e.label===e.agentId?e.agentId:`${e.label} · ${e.agentId}`},e.agentId))]}),(0,V.jsx)(`small`,{children:o(`lark.targetAgentDescription`)})]}),!me&&Ie.length>1?(0,V.jsxs)(`label`,{"aria-label":o(`lark.connectAllAgents`),className:`personal-lark-check`,children:[(0,V.jsx)(`input`,{checked:se,onChange:e=>ce(e.target.checked),type:`checkbox`}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:o(`lark.connectAllAgents`)}),(0,V.jsx)(`small`,{children:o(`lark.connectAllAgentsDescription`,{count:Ie.length})})]})]}):null,!me&&se&&Ie.length>1?(0,V.jsxs)(`fieldset`,{"aria-label":o(`lark.agentApps`),className:`personal-lark-agent-apps`,children:[(0,V.jsx)(`legend`,{children:o(`lark.agentApps`)}),(0,V.jsx)(`small`,{children:o(`lark.agentAppsDescription`)}),(0,V.jsx)(`div`,{children:Ie.map(e=>(0,V.jsxs)(`label`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsx)(`small`,{children:e.agentId})]}),(0,V.jsx)(`select`,{"aria-label":o(`lark.agentAppSelection`,{agent:e.label}),onChange:t=>ue(n=>({...n,[e.agentId]:t.target.value})),value:le[e.agentId]??x,children:l.map(e=>(0,V.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref))})]},e.agentId))})]}):null,se&&Re.length>0&&!Be?(0,V.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.agentAppPermissions`)}):null,ze.length===0?(0,V.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:o(`lark.selectRegisteredAgent`)}):null]}):null,(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.replyMode`)}),(0,V.jsx)(`select`,{"aria-label":o(`lark.replyMode`),onChange:e=>ae(e.target.value),value:I,children:(0,V.jsx)(`option`,{value:`topic_reply`,children:o(`lark.topicReply`)})}),(0,V.jsx)(`small`,{children:o(`lark.replyModeDescription`)})]}),(0,V.jsxs)(`p`,{className:`personal-lark-cardinality`,children:[(0,V.jsx)(em,{size:15}),o(`lark.cardinality`)]}),fe?(0,V.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:fe}):null,(0,V.jsxs)(`footer`,{children:[(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>b(!1),type:`button`,children:o(`lark.cancel`)}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:p||!x||!ge&&(!He?.reply_ready||!ee)||P===`goal`&&(!Be||ze.length===0)||!C||de,onClick:()=>void Ze(),type:`button`,children:[de?(0,V.jsx)(Cm,{className:`is-spinning`,size:15}):null,Ve]})]})]})}):null,be?(0,V.jsx)(`div`,{className:`personal-lark-modal-backdrop is-setup`,role:`presentation`,children:(0,V.jsxs)(`section`,{"aria-labelledby":`new-lark-app-title`,"aria-modal":`true`,className:`personal-lark-modal personal-lark-setup-modal`,role:`dialog`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:o(`lark.reusableWorkspaceApp`)}),(0,V.jsx)(`h2`,{id:`new-lark-app-title`,children:o(`lark.newApp`)})]}),(0,V.jsx)(`button`,{"aria-label":o(`lark.closeCreate`),onClick:()=>void Xe(),type:`button`,children:(0,V.jsx)($m,{size:18})})]}),z?(0,V.jsxs)(`div`,{className:`personal-lark-setup-progress`,children:[(0,V.jsx)(`span`,{className:`personal-lark-setup-icon is-${z.status}`,children:z.status===`ready`?(0,V.jsx)(em,{size:22}):(0,V.jsx)(Cm,{className:z.status===`failed`?``:`is-spinning`,size:22})}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:z.status===`ready`?o(`lark.appCreated`):z.status===`failed`?o(`lark.appCreateFailed`):o(`lark.waitingFeishu`)}),(0,V.jsx)(`p`,{children:z.status===`waiting_for_feishu`?o(`lark.waitingFeishuDescription`):z.status===`starting`?o(`lark.waitingLink`):z.error})]}),z.verification_url?(0,V.jsxs)(`a`,{href:z.verification_url,rel:`noreferrer`,target:`_blank`,children:[(0,V.jsx)(fm,{size:15}),o(`lark.reopenFeishu`)]}):null]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{className:`personal-lark-setup-copy`,children:o(`lark.setupCopy`)}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.profileName`)}),(0,V.jsx)(`input`,{"aria-label":o(`lark.profileName`),autoComplete:`off`,onChange:e=>Ce(e.target.value),placeholder:`loopx-workspace-bot`,value:Se})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.region`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.region`),onChange:e=>Te(e.target.value),value:we,children:[(0,V.jsx)(`option`,{value:`feishu`,children:`Feishu`}),(0,V.jsx)(`option`,{value:`lark`,children:`Lark`})]})]}),Se&&!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Se)?(0,V.jsx)(`p`,{className:`personal-notification-error`,children:o(`lark.profileValidation`)}):null]}),ke?(0,V.jsx)(`p`,{className:`personal-notification-error`,children:ke}):null,(0,V.jsxs)(`footer`,{children:[(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void Xe(),type:`button`,children:o(`lark.cancel`)}),z?null:(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:De||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Se),onClick:()=>void Ye(),type:`button`,children:[De?(0,V.jsx)(Cm,{className:`is-spinning`,size:15}):(0,V.jsx)(fm,{size:15}),o(`lark.continueFeishu`)]})]})]})}):null]})}function Ab(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function jb(e,t,n){let r=Ab(t),i=Ab(n);return Object.fromEntries(e.fields.flatMap(({key:e,nullable:t})=>{let n=r[e],a=i[e];return Object.hasOwn(r,e)&&(n!=null||t&&n===null)?[[e,n]]:Object.hasOwn(i,e)&&a!=null?[[e,a]]:[]}))}function Mb(e,t){let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=new Set(e.fields.map(e=>e.key));return Object.keys(n).some(e=>!r.has(e))?null:n}function Nb(e,t,n){let r={...e,[t]:n},i=e.schedule;return t===`timezone`&&i&&typeof i==`object`&&`schema_version`in i&&i.schema_version===`periodic_report_schedule_v0`&&(r.schedule={...i,timezone:n}),r}function Pb({id:e,value:t,timezone:n,onChange:r}){let{locale:i}=qi(),a=i===`zh-CN`,o=t&&typeof t==`object`&&!Array.isArray(t)?t:null,s=String(o?.rrule??``).split(`;`).map(e=>e.split(`=`)),c=Object.fromEntries(s.filter(e=>e.length===2)),l=[`MO`,`TU`,`WE`,`TH`,`FR`,`SA`,`SU`],u=(e,t)=>e!==void 0&&/^\d+$/.test(e)&&Number(e)<=t,d=!o||o.schema_version===`periodic_report_schedule_v0`&&[`DAILY`,`WEEKLY`].includes(c.FREQ)&&o.timezone===n&&s.every(e=>e.length===2&&[`FREQ`,`BYDAY`,`BYHOUR`,`BYMINUTE`,`INTERVAL`].includes(e[0]))&&new Set(s.map(([e])=>e)).size===s.length&&u(c.BYHOUR,23)&&u(c.BYMINUTE??`0`,59)&&(c.FREQ===`WEEKLY`?l.includes(c.BYDAY):!c.BYDAY)&&(!c.INTERVAL||c.INTERVAL===`1`),f=a?[`星期一`,`星期二`,`星期三`,`星期四`,`星期五`,`星期六`,`星期日`]:[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`];function p(e){let t={FREQ:`WEEKLY`,BYDAY:`MO`,BYHOUR:`9`,BYMINUTE:`0`,...c,...e};r?.({schema_version:`periodic_report_schedule_v0`,schedule_id:o?.schedule_id??`report-schedule`,timezone:n,rrule:[`FREQ=${t.FREQ}`,...t.FREQ===`WEEKLY`?[`BYDAY=${t.BYDAY}`]:[],`BYHOUR=${t.BYHOUR}`,`BYMINUTE=${t.BYMINUTE}`].join(`;`)})}return(0,V.jsxs)(`div`,{className:`personal-report-schedule`,children:[(0,V.jsxs)(`label`,{className:`is-boolean`,htmlFor:e,children:[(0,V.jsx)(`span`,{children:a?`按日历汇报`:`Calendar reports`}),(0,V.jsx)(`input`,{id:e,type:`checkbox`,role:`switch`,checked:!!o,disabled:!r,onChange:e=>e.target.checked?p({}):r?.(null)})]}),o?(0,V.jsxs)(V.Fragment,{children:[d?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{htmlFor:`${e}-frequency`,children:[(0,V.jsx)(`span`,{children:a?`频率`:`Frequency`}),(0,V.jsxs)(`select`,{id:`${e}-frequency`,value:c.FREQ,disabled:!r,onChange:e=>p({FREQ:e.target.value}),children:[(0,V.jsx)(`option`,{value:`DAILY`,children:a?`每天`:`Daily`}),(0,V.jsx)(`option`,{value:`WEEKLY`,children:a?`每周`:`Weekly`})]})]}),c.FREQ===`WEEKLY`&&(0,V.jsxs)(`label`,{htmlFor:`${e}-day`,children:[(0,V.jsx)(`span`,{children:a?`星期`:`Weekday`}),(0,V.jsx)(`select`,{id:`${e}-day`,value:c.BYDAY,disabled:!r,onChange:e=>p({BYDAY:e.target.value}),children:l.map((e,t)=>(0,V.jsx)(`option`,{value:e,children:f[t]},e))})]}),(0,V.jsxs)(`label`,{htmlFor:`${e}-time`,children:[(0,V.jsxs)(`span`,{children:[a?`当地时间`:`Local time`,` (`,n,`)`]}),(0,V.jsx)(`input`,{id:`${e}-time`,type:`time`,required:!0,disabled:!r,value:`${(c.BYHOUR??`9`).padStart(2,`0`)}:${(c.BYMINUTE??`0`).padStart(2,`0`)}`,onChange:e=>{if(!/^\d{2}:\d{2}$/.test(e.target.value))return;let[t,n]=e.target.value.split(`:`);p({BYHOUR:t,BYMINUTE:n})}})]})]}):(0,V.jsx)(`p`,{role:`alert`,children:a?`此计划需在 JSON 模式中编辑;当前内容已保留。`:`Edit this schedule in JSON mode; its current value is preserved.`}),(0,V.jsx)(`p`,{children:a?`由现有唤醒检查到期计划;实际送达以回执为准。`:`Existing wakes check the schedule; delivery is confirmed by its receipt.`})]}):(0,V.jsx)(`p`,{children:a?`未设置日历计划;保持阶段结束时汇报。`:`No calendar schedule; report at validated stage boundaries.`})]})}function Fb({copy:e,field:t,id:n,onChange:r,value:i,timezone:a}){let o=e[t.key]?.label??t.label,s=!r;if(t.input_kind===`periodic_report_schedule`)return(0,V.jsx)(Pb,{id:n,value:i,timezone:a,onChange:r?e=>r(t.key,e):void 0});if(t.input_kind===`boolean`)return(0,V.jsxs)(`label`,{className:`is-boolean`,htmlFor:n,children:[(0,V.jsx)(`span`,{children:o}),(0,V.jsx)(`input`,{checked:i===!0,id:n,onChange:r?e=>r(t.key,e.target.checked):void 0,readOnly:s,role:`switch`,type:`checkbox`})]});if(t.input_kind===`select`)return(0,V.jsxs)(`label`,{htmlFor:n,children:[(0,V.jsx)(`span`,{children:o}),(0,V.jsxs)(`select`,{id:n,onChange:r?e=>r(t.key,e.target.value):void 0,value:typeof i==`string`?i:``,children:[(0,V.jsx)(`option`,{value:``}),(t.options??[]).map(e=>(0,V.jsx)(`option`,{value:e,children:e},e))]})]});if(t.input_kind===`string_list`)return(0,V.jsxs)(`label`,{htmlFor:n,children:[(0,V.jsx)(`span`,{children:o}),(0,V.jsx)(`textarea`,{id:n,onChange:r?e=>r(t.key,e.target.value.split(/\r?\n/u).filter(Boolean)):void 0,readOnly:s,rows:4,value:Array.isArray(i)?i.join(` -======== -`)});continue}let o=e.match(/^\s{0,3}#{1,4}\s+(.*)$/);if(o){i();let t=e.trimStart().match(/^#+/)?.[0].length??1;n.push({type:`heading`,level:t,text:o[1].trim()}),a+=1;continue}if(Dy.test(e)||Oy.test(e)){i();let r=Oy.test(e),o=r?Oy:Dy,s=[];for(;a{let n=`b${t}`;if(e.type===`code`)return(0,V.jsx)(`pre`,{className:`personal-md-pre`,children:(0,V.jsx)(`code`,{children:e.text})},n);if(e.type===`heading`)return(0,V.jsx)(`p`,{className:`personal-md-heading is-h${e.level}`,children:Ey(e.text,n)},n);if(e.type===`list`){let t=e.items.map((e,t)=>(0,V.jsx)(`li`,{children:Ey(e,`${n}-${t}`)},`${n}-${t}`));return e.ordered?(0,V.jsx)(`ol`,{className:`personal-md-list`,children:t},n):(0,V.jsx)(`ul`,{className:`personal-md-list`,children:t},n)}return(0,V.jsx)(`p`,{children:e.lines.map((e,t)=>(0,V.jsxs)(B.Fragment,{children:[t>0?(0,V.jsx)(`br`,{}):null,Ey(e,`${n}-${t}`)]},`${n}-${t}`))},n)})})}function jy({onSelect:e,output:t}){let{t:n}=qi(),r=t.kind===`report`?gm:hm;return(0,V.jsxs)(`button`,{className:`personal-timeline-row personal-output-row`,"data-output-kind":t.kind,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-row-icon is-output`,children:(0,V.jsx)(r,{size:18})}),(0,V.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,V.jsxs)(`small`,{children:[t.goalTitle??t.goalId,` · `,t.agentLabel??`LoopX`]}),(0,V.jsx)(`strong`,{children:t.title}),t.summary?(0,V.jsx)(`span`,{children:t.summary}):null,t.report?(0,V.jsxs)(`small`,{children:[n(`files.reportDelta`,{added:t.report.addedCount,changed:t.report.changedCount}),` · `,n(`files.verifiedReport`)]}):null]}),t.createdAt?(0,V.jsx)(`time`,{children:t.createdAt}):null,(0,V.jsx)(nm,{size:17})]})}var My={completed:`runs.completed`,failed:`runs.failed`,interrupted:`runs.interrupted`,queued:`runs.queued`,running:`runs.running`,waiting:`runs.waiting`};function Ny({onSelect:e,run:t}){let{t:n}=qi(),r=t.totalSteps>0?Math.min(100,t.completedSteps/t.totalSteps*100):0;return(0,V.jsxs)(`button`,{"aria-label":`${n(`tasks.viewExecution`)}:${t.title}`,className:`personal-timeline-row personal-run-row`,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-row-icon is-run`,children:(0,V.jsx)(Zp,{size:18})}),(0,V.jsxs)(`span`,{className:`personal-run-identity`,children:[(0,V.jsx)(`small`,{children:t.goalTitle}),(0,V.jsx)(`strong`,{children:t.agentLabel})]}),(0,V.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,V.jsx)(`strong`,{children:t.title}),(0,V.jsx)(`small`,{children:t.latestActivity})]}),(0,V.jsxs)(`span`,{className:`personal-run-progress`,"aria-label":`${t.completedSteps}/${t.totalSteps}`,children:[(0,V.jsxs)(`small`,{children:[t.completedSteps,`/`,t.totalSteps]}),(0,V.jsx)(`i`,{children:(0,V.jsx)(`b`,{style:{width:`${r}%`}})})]}),(0,V.jsxs)(`span`,{className:`personal-row-status is-${t.status}`,children:[t.status===`running`?(0,V.jsx)(Cm,{className:`personal-spin`,size:14}):null,n(My[t.status])]}),t.sessionId?(0,V.jsx)(`span`,{className:`personal-run-open-label`,children:n(`tasks.viewExecution`)}):null,(0,V.jsx)(nm,{size:17})]})}function Py({onSelect:e,schedule:t}){let{t:n}=qi(),r=t.scheduleKind===`heartbeat`;return(0,V.jsxs)(`button`,{"aria-label":`${r?`Heartbeat`:n(`tasks.scheduled`)}:${t.label};${t.status??`active`}`,className:`personal-schedule-row`,onClick:e,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-schedule-icon`,children:r?(0,V.jsx)(Fm,{size:17}):(0,V.jsx)($p,{size:17})}),(0,V.jsxs)(`span`,{className:`personal-schedule-copy`,children:[(0,V.jsx)(`small`,{children:n(r?`schedule.heartbeat`:`schedule.monitor`)}),(0,V.jsx)(`strong`,{children:t.label}),(0,V.jsx)(`p`,{children:t.schedule??n(`schedule.summary`)})]}),(0,V.jsx)(`span`,{className:`personal-schedule-status is-${t.status??`active`}`,children:t.status===`paused`?n(`schedule.paused`):n(`schedule.active`)}),(0,V.jsx)(nm,{size:16})]})}function Fy({items:e,onSelect:t,selectedGoal:n}){let{t:r}=qi();if(e.length===0)return(0,V.jsxs)(`div`,{className:`personal-timeline-empty`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(Km,{size:20})}),(0,V.jsx)(`strong`,{children:r(n?`timeline.emptyGoal`:`timeline.emptyWorkspace`)}),(0,V.jsx)(`p`,{children:r(n?`timeline.emptyGoalDescription`:`timeline.emptyWorkspaceDescription`)})]});let i=[...e].reverse().find(e=>e.kind===`message`&&e.message.role!==`user`||e.kind===`proposal`&&[`applied`,`stale`,`error`,`gated`].includes(e.proposal.status)||e.kind===`run`&&e.run.status===`completed`),a=i?.kind===`message`?`${i.message.agentLabel??r(`header.manager`)}:${i.message.pending?r(`timeline.pending`):i.message.text}`:i?.kind===`proposal`?`${i.proposal.title}:${i.proposal.status}`:i?.kind===`run`?r(`timeline.runCompleted`,{run:i.run.title}):``,o=e.filter(e=>e.kind===`proposal`&&e.proposal.status===`gated`),s=e.filter(e=>e.kind!==`proposal`),c=e.filter(e=>e.kind===`proposal`&&e.proposal.status!==`gated`);function l(e){return e.kind===`attention`?(0,V.jsx)(wy,{attention:e.attention,onSelect:()=>t({item:e.attention,kind:`attention`})},e.id):e.kind===`run`?(0,V.jsx)(Ny,{onSelect:()=>t({item:e.run,kind:`run`}),run:e.run},e.id):e.kind===`output`?(0,V.jsx)(jy,{onSelect:()=>t({item:e.output,kind:`output`}),output:e.output},e.id):e.kind===`schedule`?(0,V.jsx)(Py,{onSelect:()=>t({item:e.schedule,kind:`schedule`}),schedule:e.schedule},e.id):e.kind===`proposal`?(0,V.jsxs)(`button`,{className:`personal-proposal-row is-${e.proposal.status}`,onClick:()=>t({item:e.proposal,kind:`proposal`}),type:`button`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(Km,{size:17})}),(0,V.jsxs)(`span`,{children:[(0,V.jsxs)(`small`,{children:[e.proposal.actionKind,` · `,e.proposal.status]}),(0,V.jsx)(`strong`,{children:e.proposal.title}),(0,V.jsx)(`p`,{children:e.proposal.impact})]}),(0,V.jsx)(`b`,{children:e.proposal.status===`gated`?r(`timeline.review`):e.proposal.primaryLabel??r(`timeline.reviewAndConfirm`)})]},e.id):(0,V.jsxs)(`article`,{className:`personal-message is-${e.message.role}`,children:[e.message.role===`user`?null:(0,V.jsx)(`span`,{className:`personal-message-avatar`,children:(0,V.jsx)(Zp,{size:17})}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:e.message.role===`user`?r(`common.you`):e.message.agentLabel??r(`header.manager`)}),e.message.time?(0,V.jsx)(`time`,{children:e.message.time}):null]}),e.message.attachments?.length?(0,V.jsx)(`div`,{className:`personal-message-images`,children:e.message.attachments.map(e=>(0,V.jsx)(`img`,{alt:e.name,src:e.dataUrl},e.id))}):null,e.message.role===`user`?(0,V.jsx)(`p`,{children:e.message.text}):(0,V.jsx)(Ay,{text:e.message.text}),e.message.pending?(0,V.jsx)(`span`,{className:`personal-message-pending`,children:r(`timeline.pending`)}):null]})]},e.id)}return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{"aria-atomic":`true`,"aria-live":`polite`,className:`personal-live-region`,role:`status`,children:a}),(0,V.jsxs)(`div`,{className:`personal-channel-timeline`,children:[s.map(l),o.length?(0,V.jsxs)(`details`,{className:`personal-gated-summary`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(Km,{size:16})}),(0,V.jsx)(`strong`,{children:r(`timeline.waitingConfirmation`)}),(0,V.jsx)(`small`,{children:r(`timeline.gateHistory`,{count:o.length})})]}),(0,V.jsx)(`div`,{children:o.map(l)})]}):null,c.map(l)]})]})}function Iy({goal:e}){let{t}=qi(),n={connected:t(`acceptance.connected`),mapped:t(`acceptance.mapped`),refreshed:t(`acceptance.refreshed`),adapter_inspected:t(`acceptance.inspected`),run_recorded:t(`acceptance.recorded`),reward_judged:t(`acceptance.judged`),operator_approved:t(`acceptance.approved`),controller_ready:t(`acceptance.ready`),attention_queue:t(`acceptance.attentionSource`),agent_vision:t(`acceptance.visionSource`),todo_projection:t(`acceptance.todoSource`),current_run:t(`acceptance.runSource`)},r=e=>n[e]??t(`acceptance.unknown`),i=e.acceptanceObservation,a=e.loadState||!i||i.goal_id!==e.goalId||i.coverage===`unavailable`;return(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-acceptance`,"aria-label":t(`acceptance.title`),children:[(0,V.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,V.jsx)(`h3`,{children:t(`acceptance.title`)}),(0,V.jsx)(`em`,{children:t(`common.readOnly`)})]}),(0,V.jsx)(`p`,{role:`status`,children:t(a?`acceptance.unavailable`:`acceptance.partial`)}),!a&&i?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h4`,{children:t(`acceptance.gaps`)}),i.acceptance_gaps.length?i.acceptance_gaps.map((e,n)=>(0,V.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,V.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.owner`)}),(0,V.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,V.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.observed`)}),(0,V.jsx)(`dd`,{children:e.observed_at??t(`acceptance.unknown`)})]})]})]},`${e.kind}:${e.owner}:${n}`)):(0,V.jsx)(`p`,{children:t(`acceptance.noGaps`)}),(0,V.jsx)(`h4`,{children:t(`acceptance.guards`)}),i.guards.length?i.guards.map((e,n)=>(0,V.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,V.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.owner`)}),(0,V.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),e.blocks_agent?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.agent`)}),(0,V.jsx)(`dd`,{children:e.blocks_agent})]}):null,e.todo_id?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.task`)}),(0,V.jsx)(`dd`,{children:e.todo_id})]}):null,(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,V.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.scope`)}),(0,V.jsx)(`dd`,{children:e.decision_scope??t(`acceptance.unknown`)})]})]})]},`${e.todo_id}:${n}`)):(0,V.jsx)(`p`,{children:t(`acceptance.noGuards`)}),(0,V.jsx)(`h4`,{children:t(`acceptance.next`)}),(0,V.jsx)(`p`,{children:i.next_action??t(`acceptance.unknown`)}),(0,V.jsxs)(`details`,{children:[(0,V.jsxs)(`summary`,{children:[t(`acceptance.historical_progress`),` · `,i.historical_progress.length]}),(0,V.jsx)(`p`,{children:t(`acceptance.historical`)}),i.historical_progress.map(e=>(0,V.jsxs)(`p`,{children:[(0,V.jsx)(`strong`,{children:r(e.kind)}),` · `,e.observed_at??t(`acceptance.unknown`),` `,e.evidence_refs.join(`, `)]},e.kind))]}),i.missing_sources.length?(0,V.jsxs)(`p`,{children:[t(`acceptance.missing`),` `,i.missing_sources.map(r).join(`, `)]}):null,i.truncated?(0,V.jsx)(`p`,{children:t(`acceptance.truncated`)}):null]}):null]})}function Ly({item:e,successor:t,onSelect:n}){let{t:r}=qi(),i=e.details;return(0,V.jsxs)(`section`,{className:`personal-detail-card`,"aria-label":r(`attentionDetail.title`),children:[(0,V.jsx)(`h3`,{children:r(`attentionDetail.title`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.request`)}),(0,V.jsx)(`dd`,{children:r(i?.interaction===`decision`?`attentionDetail.decision`:`attentionDetail.unknownRequest`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`common.status`)}),(0,V.jsx)(`dd`,{children:r(`attentionDetail.${i?.lifecycle??`unknown`}`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`drawer.reason`)}),(0,V.jsx)(`dd`,{children:i?.reason??e.explanation??r(`attentionDetail.unknownReason`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Todo`}),(0,V.jsx)(`dd`,{children:e.todoId})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.targetTodo`)}),(0,V.jsx)(`dd`,{children:i?.unblocksTodoId??r(`attentionDetail.notProvided`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.targetAgent`)}),(0,V.jsx)(`dd`,{children:i?.blocksAgent??r(`attentionDetail.notProvided`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.scope`)}),(0,V.jsx)(`dd`,{children:i?.decisionScope?`${i.decisionScope.kind} · ${i.decisionScope.granularity} · ${i.decisionScope.scopeKey}`:r(`attentionDetail.notProvided`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`drawer.evidence`)}),(0,V.jsx)(`dd`,{children:i?.evidence??e.evidence??r(`drawer.decisionDefaultEvidence`)})]})]}),i?.supersededBy?(0,V.jsxs)(`p`,{children:[r(`attentionDetail.replacement`),`: `,i.supersededBy]}):null,t&&n?(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>n(t),type:`button`,children:r(`attentionDetail.openReplacement`)}):null,(0,V.jsx)(`p`,{children:r(`attentionDetail.boundary`)})]})}function Ry(e){return e.replace(/\s+/gu,` `).trim()}function zy(e,t){let n=RegExp(`(?:不要|不需要|无需|禁止|别|暂不|do not\\b|don't\\b|without\\b).{0,10}(?:${t.source})`,`iu`),r=RegExp(`(?:${t.source}).{0,10}(?:不要|不需要|无需|禁止|关闭)`,`iu`),i=RegExp(`disable\\b.{0,10}(?:${t.source})|(?:turn|switch|set)\\b.{0,10}(?:${t.source}).{0,10}\\boff\\b|(?:${t.source})\\s+(?:is\\s+)?disabled\\b`,`iu`);return n.test(e)||r.test(e)||i.test(e)}function By(e){return/(我现在该做什么|下一步|哪些\s*Goal\s*在等我|需要我|谁在等我|Agent\s*在做什么|当前进度|总结(?:今天)?进展)/iu.test(e)}function Vy(e){let t=/(怎么|如何|为什么|给.*建议|分析一下|解释|只读)/u.test(e),n=/(解决一下|修复一下|处理一下|执行一下|改一下|跑(?:一下)?测试|rebase|push|提交|推送)/iu.test(e);return!t&&n&&/(帮我|请|给我|直接|现在|开始|bytedcli|codebase|git|rebase|push|提交|推送)/iu.test(e)}function Hy(e){return Ry(e).toLowerCase().match(/(?:^|[\s,,;;:((:]|到|至)(?todo_done:todo_[a-z0-9_-]{3,64}|pr_merged:(?:(?:[a-z0-9_.-]{1,80})\/(?:[a-z0-9_.-]{1,100}))?#[1-9][0-9]{0,8}|capacity_available:[a-z][a-z0-9_:-]{0,63}|resume_at:[1-9][0-9]{3}-[0-9]{2}-[0-9]{2}t[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,3})?(?:z|[+-][0-9]{2}:[0-9]{2}))(?=$|[\s,,。;;))])/iu)?.groups?.condition??null}function Uy(e,t){let n=Ry(e),r=[],i=t.agents.find(e=>{let t=n.toLowerCase();return t.includes(e.agentId.toLowerCase())||t.includes(e.label.toLowerCase())}),a=t.todos.find(e=>n.includes(e.todoId)||n.includes(e.text)),o=/(刚刚|已经|已)(?:经)?\s*(新增|创建|添加)(?:的)?\s*(todo|待办|任务)/iu.test(n),s=!!t.goalId&&!zy(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n);if(!t.goalId&&!zy(n,/goal|目标/iu)&&/(创建|新建|设置|create|start|set up).{0,24}(goal|目标)/iu.test(n)&&r.push({actionKind:`goal.create`,confidence:.97,normalizedParameters:{heartbeat_enabled:!zy(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n)}}),t.goalId&&s&&r.push({actionKind:`heartbeat.bind`,confidence:.96,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&!s&&!zy(n,/定时|监控|监测|持续观察|scheduled check|monitor/iu)&&/(定时|监控|监测|每.{0,8}(分钟|小时|天)|持续观察|scheduled check|monitor|every.{0,12}(minute|hour|day)|daily)/iu.test(n)&&r.push({actionKind:`monitor.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&i&&!zy(n,/绑定|负责|接管|管理/iu)&&/((让|交给).{0,20}(管理|负责|接管).{0,8}(goal|目标)|(绑定).{0,12}(goal|目标)|(goal|目标).{0,12}(交给|绑定|负责|接管))/iu.test(n)&&r.push({actionKind:`agent.bind`,confidence:.96,normalizedParameters:{agent_id:i.agentId,goal_id:t.goalId}}),t.goalId&&!o&&!zy(n,RegExp(`todo|待办|任务`,`iu`))&&/(创建|新建|新增|添加|加一个|记一个).{0,16}(todo|待办|任务)|(todo|待办|任务).{0,12}(创建|新建|新增|添加)|(?:create|add)(?:\s+(?:a|an|new))?\s+(?:todo|task)|(?:todo|task).{0,12}(?:create|add)/iu.test(n)&&r.push({actionKind:`todo.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&Vy(n)&&r.push({actionKind:`todo.create`,confidence:.9,normalizedParameters:{goal_id:t.goalId,start_execution:!0}}),t.goalId&&a){let e=!zy(n,/完成|做完|关闭/u)&&/完成|做完|关闭/u.test(n)?`complete`:!zy(n,/阻塞|卡住/u)&&/阻塞|卡住/u.test(n)?`block`:!zy(n,/暂缓|稍后|推迟/u)&&/暂缓|稍后|推迟/u.test(n)?`defer`:i&&!zy(n,/交给|分配给|改派/u)&&/交给|分配给|改派/u.test(n)?`reassign`:null;if(e){let i=e===`defer`?Hy(n):null;if(e===`defer`&&!i)return{actionKind:`todo.update`,confidence:.97,missingFields:[`resume_when`],normalizedParameters:{goal_id:t.goalId,operation:e,todo_id:a.todoId},route:`clarify`};r.push({actionKind:`todo.update`,confidence:.97,normalizedParameters:{goal_id:t.goalId,operation:e,...i?{resume_when:i}:{},todo_id:a.todoId}})}}let c=[...new Map(r.map(e=>[e.actionKind,e])).values()];return c.length>1?{actionKind:null,confidence:.4,missingFields:[`single_intent`],normalizedParameters:{},route:`clarify`}:c.length===1?{...c[0],missingFields:[],route:`typed_action`}:!t.goalId&&By(n)?{actionKind:null,confidence:.98,missingFields:[],normalizedParameters:{},route:`projection`}:{actionKind:null,confidence:.75,missingFields:[],normalizedParameters:{},route:`agent_chat`}}function Wy(e,t,n){if(!e)return{};if(!t.trim())return{modelConfig:null};let r={model:t.trim()};return n&&(r.reasoning_effort=n),{modelConfig:r}}var Gy=[`a[href]`,`button:not([disabled])`,`textarea:not([disabled])`,`select:not([disabled])`,`input:not([disabled])`,`[tabindex]:not([tabindex='-1'])`].join(`,`),Ky=[{key:`drawer.taskBlock`,operation:`block`},{key:`drawer.taskSuccessor`,operation:`successor_create`}],qy=[{key:`drawer.decisionReject`,resolution:`reject`},{key:`drawer.decisionDefer`,resolution:`defer`}],Jy=Array.from({length:32},(e,t)=>t+1),Yy=/^[a-z][a-z0-9_.-]{0,63}$/u;function Xy(e){let t=String(e??``).trim().toLowerCase();return Yy.test(t)?t:null}function Zy(e,t){return e.enabled===t.enabled&&e.maxChildren===t.maxChildren&&JSON.stringify(e.modelConfig??null)===JSON.stringify(t.modelConfig??null)&&[...e.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)===[...t.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)}function Qy({agents:e,attentionHistory:t=[],onSelectAttention:n,callbacks:r,goalNotifications:i=[],goals:a=[],inspectorExpanded:o=!1,larkConnections:s=[],onClose:c,onToggleInspectorSize:l,readOnly:u=!1,runs:d=[],selection:f}){let{locale:p,t:m}=qi(),[h,g]=(0,B.useState)(``),[_,v]=(0,B.useState)(!1),[y,b]=(0,B.useState)(`idle`),[x,S]=(0,B.useState)(`record`),[C,w]=(0,B.useState)([]),[T,E]=(0,B.useState)(null),[D,O]=(0,B.useState)(2),[ee,te]=(0,B.useState)(``),[ne,k]=(0,B.useState)(``),[A,j]=(0,B.useState)(`idle`),[M,N]=(0,B.useState)(null),[P,F]=(0,B.useState)(null),re=(0,B.useRef)(null),ie=(0,B.useRef)(null),[I,ae]=(0,B.useState)(e.find(e=>e.available)?.agentId??`codex`),[L,oe]=(0,B.useState)(``),se=(0,B.useRef)(null),ce=(0,B.useRef)(null),le=(0,B.useRef)(null),ue=(0,B.useRef)(null),de=f.kind===`run`?`run:${f.item.runId}`:f.kind===`proposal`?`proposal:${f.item.previewId}`:f.kind===`todo`?`todo:${f.item.todoId}`:f.kind===`attention`?`attention:${f.item.todoId}`:f.kind===`output`?`output:${f.item.outputId}`:f.kind===`schedule`?`schedule:${f.item.scheduleId}`:`goal:${f.item.goalId}`;(0,B.useEffect)(()=>{b(`idle`),v(!1),S(`record`),oe(``);let e=f.kind===`goal`?f.item.subagentExecution:void 0;w(e?.allowedDomains??[]),te(e?.modelConfig?.model??``),k(e?.modelConfig?.reasoning_effort??``),O(e?.maxChildren?Math.min(e.maxChildren,32):2),E(null),j(`idle`),N(null),F(null),re.current=e??null,ie.current=null},[de]);let R=f.kind===`goal`?f.item.subagentExecution:void 0;(0,B.useEffect)(()=>{let e=re.current,t=R?!e||!Zy(e,R):e!==null;if(re.current=R??null,!P){t&&R&&(w(R.allowedDomains),te(R.modelConfig?.model??``),k(R.modelConfig?.reasoning_effort??``),O(R.maxChildren||2),E(null),j(`idle`),N(null));return}let n=ie.current;(!R||Zy(P,R)||n&&!Zy(n,R))&&(R&&(w(R.allowedDomains),te(R.modelConfig?.model??``),k(R.modelConfig?.reasoning_effort??``),O(R.maxChildren||2)),ie.current=null,F(null))},[R,P]),(0,B.useEffect)(()=>{let e=document.activeElement;e instanceof HTMLElement&&!ce.current?.contains(e)&&(le.current=e);let t=window.requestAnimationFrame(()=>ue.current?.focus());return()=>window.cancelAnimationFrame(t)},[de]);let fe=(0,B.useCallback)(()=>{let e=le.current;c(),window.requestAnimationFrame(()=>e?.focus())},[c]);(0,B.useEffect)(()=>{function e(e){if(e.key===`Escape`){e.preventDefault(),fe();return}if(e.key===`Tab`&&f.kind!==`todo`){let t=Array.from(ce.current?.querySelectorAll(Gy)??[]).filter(e=>!e.hasAttribute(`disabled`)&&e.getAttribute(`aria-hidden`)!==`true`);if(t.length===0)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n.focus())}}return document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`keydown`,e)}},[fe,f.kind]);let pe=f.kind===`attention`?m(`drawer.titleAttention`):f.kind===`todo`?m(`drawer.taskDetails`):f.kind===`run`?m(`drawer.runDetails`):f.kind===`output`?m(`drawer.titleOutput`):f.kind===`proposal`?m(f.item.status===`applied`?`drawer.titleProposalApplied`:`drawer.titleProposalConfirm`):f.kind===`schedule`?f.item.scheduleKind===`heartbeat`?`Heartbeat`:m(`drawer.titleSchedule`):m(`drawer.goalDetails`),me=f.kind===`proposal`?f.item.goalId??`manager`:f.item.goalId,he=f.kind===`attention`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`todo`||f.kind===`run`?f.item.goalTitle:f.kind===`output`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`goal`?f.item.title:f.kind===`schedule`?m(`drawer.goalAutoRun`):f.item.goalId?m(`drawer.goalChanges`):m(`drawer.managerChanges`),ge=f.kind===`goal`?d.find(e=>e.goalId===f.item.goalId&&!!e.sessionId)??d.find(e=>e.goalId===f.item.goalId):null,_e=f.kind===`run`&&(f.item.completedSteps>0||!!f.item.latestActivity||!!f.item.outputs?.length),ve=f.kind===`attention`?Xi(f.item.updatedAt,m):null,ye=Hy(L);async function be(){f.kind!==`run`||!h.trim()||(await r.onCorrectRun?.(f.item,h.trim()),g(``))}async function xe(e,t,n,i){if(t===`successor_create`){await r.onPreviewAction?.({actionKind:`todo.create`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-successor-${e.todoId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,text:m(`drawer.taskSuccessorText`,{task:e.text})},summary:m(`drawer.taskSuccessorSummary`,{task:e.text})});return}await r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:e.claimedBy??I,goal_id:e.goalId,operation:t,...t===`block`?{note:m(`drawer.taskSuccessorNote`)}:{},...t===`defer`&&i?{resume_when:i}:{},todo_id:e.todoId},summary:`${n}:${e.text}`})}async function Se(e,t,n){u||!qd(e)||await r.onPreviewAction?.({actionKind:`gate.resolve`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-decision-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,decision:t,todo_id:e.todoId},summary:`${n}:${e.text}`})}let Ce=f.kind===`goal`?P??f.item.subagentExecution??{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0}:{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0},we=A===`previewing`||A===`applying`,Te=(()=>{if(f.kind!==`goal`)return[];let e=new Map;for(let t of Ce.allowedDomains){let n=Xy(t);n&&e.set(n,{matchingTodoCount:0,value:n})}if(Ce.domainCandidates)for(let t of Ce.domainCandidates){let n=Xy(t.domain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+t.matchingTodoCount,value:n})}else for(let t of f.item.agentTodos){if(t.done||t.taskClass!==`advancement_task`)continue;let n=Xy(t.taskDomain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+1,value:n})}return[...e.values()]})();function z(){w(Ce.allowedDomains),te(Ce.modelConfig?.model??``),k(Ce.modelConfig?.reasoning_effort??``),O(Ce.maxChildren||2),E(null),j(`idle`),N(null)}function Ee(){let e=[...new Set(C.map(e=>Xy(e)))];return e.every(e=>!!e)?e:null}function De(e,t){w(n=>t?[...n,e].filter((e,t,n)=>n.indexOf(e)===t):n.filter(t=>t!==e)),N(null),j(`idle`),E(null)}async function Oe(e,t=e){if(f.kind!==`goal`||!r.onPreviewGoalSubagentConfiguration)return;let n=e?Ee():[];if(t&&!ee.trim()&&ne){j(`error`),E(m(`drawer.subagentModelRequired`));return}if(e&&!n){j(`error`),E(m(`drawer.subagentDomainInvalid`)),N(null);return}let i={allowedDomains:n??[],enabled:e,goalId:f.item.goalId,maxChildren:e?D:0,...Wy(t,ee,ne)};j(`previewing`),E(m(`drawer.subagentPreviewing`)),N(null);try{let e=await r.onPreviewGoalSubagentConfiguration(i);if(!e.changed){ie.current=R??null,F({...e.configuration,domainCandidates:Ce.domainCandidates}),w(e.configuration.allowedDomains),te(e.configuration.modelConfig?.model??``),k(e.configuration.modelConfig?.reasoning_effort??``),O(e.configuration.maxChildren||2),j(`success`),E(m(`drawer.subagentNoChange`));return}N({...i,changed:e.changed,previewId:e.previewId}),j(`ready`),E(m(`drawer.subagentPreviewReady`))}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentPreviewFailed`))}}async function ke(){if(!(!M||!r.onApplyGoalSubagentConfiguration)){j(`applying`),E(m(`drawer.subagentApplying`));try{let e=await r.onApplyGoalSubagentConfiguration({allowedDomains:M.allowedDomains,enabled:M.enabled,goalId:M.goalId,maxChildren:M.maxChildren,modelConfig:M.modelConfig,previewId:M.previewId});ie.current=R??null,F({...e,domainCandidates:Ce.domainCandidates}),w(e.allowedDomains),te(e.modelConfig?.model??``),k(e.modelConfig?.reasoning_effort??``),O(e.maxChildren||2),j(`success`),E(m(`drawer.subagentApplied`)),N(null);try{await r.onRefresh?.()}catch{j(`warning`),E(m(`drawer.subagentAppliedRefreshFailed`))}}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentApplyFailed`))}}}return(0,V.jsxs)(`div`,{"aria-labelledby":`personal-drawer-title`,"aria-modal":f.kind===`todo`?void 0:`true`,className:`personal-context-drawer`,"data-context-kind":f.kind,ref:ce,role:`dialog`,children:[(0,V.jsxs)(`header`,{className:`personal-drawer-header${f.kind===`todo`?` is-task-inspector`:``}`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`h2`,{id:`personal-drawer-title`,ref:ue,tabIndex:-1,children:pe}),(0,V.jsx)(`p`,{children:he})]}),(0,V.jsxs)(`div`,{className:`personal-drawer-header-actions`,children:[f.kind===`todo`&&l?(0,V.jsx)(`button`,{"aria-label":m(o?`drawer.inspectorHalf`:`drawer.inspectorFull`),className:`personal-icon-button personal-inspector-size`,onClick:l,title:m(o?`drawer.inspectorHalfView`:`drawer.inspectorFullView`),type:`button`,children:o?(0,V.jsx)(Om,{size:17}):(0,V.jsx)(wm,{size:17})}):null,(0,V.jsxs)(`button`,{"aria-label":m(`drawer.closeDetail`,{context:he}),className:`personal-icon-button personal-drawer-close`,onClick:fe,ref:se,type:`button`,children:[(0,V.jsx)(Gp,{className:`personal-mobile-back`,size:18}),(0,V.jsx)($m,{className:`personal-desktop-close`,size:18})]})]})]}),(0,V.jsxs)(`div`,{className:`personal-drawer-body`,children:[f.kind===`attention`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card is-attention`,children:[(0,V.jsx)(`small`,{children:f.item.blocking?m(`drawer.attentionBlocking`):m(`drawer.attentionWaiting`)}),(0,V.jsx)(`h3`,{children:f.item.text}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,V.jsx)(`dd`,{children:f.item.priority??`medium`})]}),ve?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`common.waiting`)}),(0,V.jsx)(`dd`,{children:m(`tasks.waitingAge`,{age:ve})})]}):null]})]}),(0,V.jsx)(Ly,{item:f.item,onSelect:n,successor:Kd(f.item,t)}),!u&&qd(f.item)?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void Se(f.item,`approve`,m(`common.confirm`)),type:`button`,children:[(0,V.jsx)(em,{size:17}),m(`drawer.decisionReview`)]}),(0,V.jsxs)(`details`,{className:`personal-compact-menu`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(dm,{size:17}),m(`drawer.decisionMore`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`button`,{onClick:()=>void r.onExplainDecision?.(f.item),type:`button`,children:[(0,V.jsx)(Em,{size:16}),m(`drawer.explainDecision`)]}),qy.map(e=>(0,V.jsx)(`button`,{onClick:()=>void Se(f.item,e.resolution,m(e.key)),type:`button`,children:m(e.key)},e.resolution))]})]})]}):null]}):null,f.kind===`todo`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-task-inspector-summary`,children:[(0,V.jsxs)(`div`,{className:`personal-task-inspector-status`,children:[(0,V.jsxs)(`span`,{className:f.item.done?`is-done`:f.item.status===`blocked`?`is-blocked`:`is-open`,children:[(0,V.jsx)(`i`,{}),f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)]}),f.item.priority?(0,V.jsx)(`span`,{children:f.item.priority}):null,(0,V.jsx)(`span`,{children:f.item.taskClass===`advancement_task`?m(`drawer.taskAdvancement`):f.item.taskClass??m(`drawer.taskOrdinary`)})]}),(0,V.jsx)(`h3`,{children:f.item.text})]}),(0,V.jsxs)(`section`,{"aria-label":m(`drawer.taskInfo`),className:`personal-task-inspector-fields`,children:[(0,V.jsx)(`h4`,{children:m(`drawer.taskInfo`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`common.owner`)}),(0,V.jsx)(`dd`,{children:f.item.ownerLabel??f.item.claimedBy??m(`drawer.notAssigned`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`common.status`)}),(0,V.jsx)(`dd`,{children:f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,V.jsx)(`dd`,{children:f.item.priority??m(`drawer.notSet`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.dependencies`)}),(0,V.jsx)(`dd`,{children:f.item.dependencies?.join(` · `)||m(`common.none`)})]}),f.item.status===`deferred`?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.resumeWhen`)}),(0,V.jsx)(`dd`,{children:f.item.resumeWhen||m(`drawer.notSet`)})]}):null,f.item.resumeWhen?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.resumeState`)}),(0,V.jsx)(`dd`,{children:f.item.resumeReady?m(`drawer.resumeReady`):m(`drawer.resumePending`)})]}):null,f.item.resumeReceiptId?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.resumeReceipt`)}),(0,V.jsx)(`dd`,{children:f.item.resumeReceiptId})]}):null,(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.nextTransition`)}),(0,V.jsx)(`dd`,{children:f.item.nextTransition??(f.item.done?m(`drawer.taskNextCompleted`):f.item.resumeReady?m(`drawer.taskNextResumeReady`):f.item.status===`deferred`?m(`drawer.taskNextDeferred`):m(`drawer.taskNextOpen`))})]})]})]}),!u&&!f.item.done?(0,V.jsxs)(`div`,{className:`personal-task-inspector-actions`,"aria-label":m(`drawer.taskActions`),children:[(0,V.jsxs)(`details`,{className:`personal-task-management`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(dm,{size:16}),m(`drawer.taskManage`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.reassign`)}),(0,V.jsxs)(`label`,{className:`personal-inline-agent-select`,children:[m(`drawer.reassign`),(0,V.jsx)(`select`,{"aria-label":m(`drawer.reassign`),onChange:e=>ae(e.target.value),value:I,children:e.filter(e=>e.available).map(e=>(0,V.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:f.item.goalId,kind:`todo`,todo_id:f.item.todoId},idempotencyKey:`workspace-todo-${f.item.todoId}-reassign-${I}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:I,goal_id:f.item.goalId,operation:`reassign`,todo_id:f.item.todoId},summary:m(`drawer.reassignSummary`,{task:f.item.text})}),type:`button`,children:m(`timeline.review`)})]}),(0,V.jsx)(`strong`,{children:m(`drawer.taskDeferUntil`)}),(0,V.jsxs)(`label`,{className:`personal-inline-agent-select personal-inline-resume-when`,children:[m(`drawer.taskDeferUntil`),(0,V.jsx)(`input`,{"aria-label":m(`drawer.taskDeferCondition`),"aria-invalid":!!L.trim()&&!ye,onChange:e=>oe(e.target.value),placeholder:m(`drawer.taskDeferPlaceholder`),value:L}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:!ye,onClick:()=>void xe(f.item,`defer`,m(`drawer.taskDefer`),ye??void 0),type:`button`,children:m(`drawer.taskDeferReview`)}),(0,V.jsx)(`small`,{children:L.trim()&&!ye?m(`drawer.taskDeferInvalid`):m(`drawer.taskDeferSupported`)})]}),(0,V.jsx)(`div`,{className:`personal-task-management-secondary`,children:Ky.map(e=>(0,V.jsx)(`button`,{onClick:()=>void xe(f.item,e.operation,m(e.key)),type:`button`,children:m(e.key)},e.operation))})]})]}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void xe(f.item,`complete`,m(`drawer.taskComplete`)),type:`button`,children:[(0,V.jsx)(em,{size:17}),m(`drawer.taskComplete`)]})]}):null,f.item.done?(0,V.jsxs)(`div`,{className:`personal-task-completed-note`,children:[(0,V.jsx)(em,{size:16}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.taskCompletedTitle`)}),(0,V.jsx)(`small`,{children:m(`drawer.taskCompletedNote`)})]})]}):null]}):null,f.kind===`goal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsx)(`small`,{children:Ji(f.item.state,p)}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.agentSentence}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.tokens`)}),(0,V.jsxs)(`dd`,{children:[yy(f.item.usage?.tokens24h,m(`drawer.usageNotMeasured`),gy),` / `,yy(f.item.usage?.tokens7d,m(`drawer.usageNotMeasured`),gy)]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.cost`)}),(0,V.jsxs)(`dd`,{children:[yy(f.item.usage?.costUsd24h,m(`drawer.usageNotMeasured`),_y),` / `,yy(f.item.usage?.costUsd7d,m(`drawer.usageNotMeasured`),_y)]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.duration`)}),(0,V.jsxs)(`dd`,{children:[yy(f.item.usage?.durationMs24h,m(`drawer.usageNotMeasured`),vy),` / `,yy(f.item.usage?.durationMs7d,m(`drawer.usageNotMeasured`),vy)]})]})]})]}),(0,V.jsx)(Iy,{goal:f.item}),(()=>{let e=i.find(e=>e.goalId===f.item.goalId),t=s.find(e=>e.goal_id===f.item.goalId);return(0,V.jsxs)(V.Fragment,{children:[f.item.repository?(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-repository`,children:[(0,V.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,V.jsx)(`small`,{children:m(`drawer.repository`)}),(0,V.jsx)(`em`,{children:m(`common.readOnly`)})]}),(0,V.jsxs)(`h3`,{children:[(0,V.jsx)(_m,{size:16}),f.item.repository.label]}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.branch`)}),(0,V.jsx)(`dd`,{children:f.item.repository.branch||`detached`})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Role`}),(0,V.jsx)(`dd`,{children:m(`drawer.repositoryRole`)})]})]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>{let e=navigator.clipboard?.writeText(f.item.repository?.identity??``);if(!e){b(`error`);return}e.then(()=>b(`copied`)).catch(()=>b(`error`))},type:`button`,children:[(0,V.jsx)(cm,{size:15}),m(y===`copied`?`drawer.copyRepositoryDone`:`drawer.copyRepository`)]}),y===`error`?(0,V.jsx)(`p`,{className:`personal-copy-feedback is-error`,role:`status`,children:m(`drawer.copyRepositoryError`)}):y===`copied`?(0,V.jsx)(`p`,{className:`personal-copy-feedback`,role:`status`,children:m(`drawer.copyRepositorySuccess`)}):null]}):null,u?(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,V.jsx)(`small`,{children:m(`drawer.larkConnection`)}),(0,V.jsx)(`h3`,{children:m(`drawer.remoteDetailsUnavailable`)}),(0,V.jsx)(`p`,{children:m(`drawer.remoteDetailsDescription`)})]}):(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,V.jsx)(`small`,{children:m(`drawer.larkConnection`)}),t?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`h3`,{children:[t.app_label,(0,V.jsx)(`span`,{className:`personal-connection-status`,children:m(`drawer.connected`)})]}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.group`)}),(0,V.jsx)(`dd`,{children:t.chat_name})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.topic`)}),(0,V.jsxs)(`dd`,{children:[`# `,t.topic_name]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.trigger`)}),(0,V.jsx)(`dd`,{children:t.incoming_mode===`mentions`?m(`lark.someoneMentions`):m(`lark.allMessages`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.replyMode`)}),(0,V.jsx)(`dd`,{children:m(`lark.topicReply`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.autoNotify`)}),(0,V.jsx)(`dd`,{children:e?.humanGateAutoNotifyEnabled?m(`common.on`):m(`common.off`)})]}),e?.lastNotifiedAt?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.lastNotification`)}),(0,V.jsx)(`dd`,{children:e.lastNotifiedAt})]}):null]})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h3`,{children:m(`drawer.larkNotConfigured`)}),(0,V.jsx)(`p`,{children:m(`drawer.larkNotConfiguredDescription`)})]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onOpenNotificationSettings?.(f.item.goalId),type:`button`,children:[(0,V.jsx)(Xp,{size:16}),m(t?`drawer.larkConfigure`:`drawer.larkConnect`)]})]})]})})(),(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-session`,children:[(0,V.jsx)(`small`,{children:m(`drawer.runDetails`)}),ge?.sessionId?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h3`,{children:Yi(ge.sessionStatus??ge.status,m)}),(0,V.jsx)(`p`,{children:ge.title}),r.onOpenRunSession?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onOpenRunSession?.(ge),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.runLatest`)]}):null]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h3`,{children:m(`drawer.noRun`)}),(0,V.jsx)(`p`,{children:m(`drawer.noRunDescription`)})]})]}),u?null:(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`heartbeat`,f.item.goalId),type:`button`,children:[(0,V.jsx)(Fm,{size:16}),m(`drawer.setupHeartbeat`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`monitor`,f.item.goalId),type:`button`,children:[(0,V.jsx)($p,{size:16}),m(`drawer.scheduleAdd`)]})]}),f.item.subagentExecution?(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-subagents`,children:[(0,V.jsxs)(`div`,{className:`personal-subagent-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:m(`drawer.subagentLabel`)}),(0,V.jsxs)(`h3`,{children:[(0,V.jsx)(Zp,{size:16}),m(`drawer.subagentTitle`)]})]}),(0,V.jsxs)(`button`,{"aria-checked":Ce.enabled,"aria-label":m(M&&A===`ready`?`drawer.subagentPending`:Ce.enabled?`drawer.subagentDisable`:`drawer.subagentEnable`),className:`personal-subagent-switch`,"data-pending":M&&A===`ready`?`true`:void 0,disabled:u||we||!!M||!r.onPreviewGoalSubagentConfiguration,onClick:()=>void Oe(!Ce.enabled),role:`switch`,type:`button`,children:[(0,V.jsx)(`span`,{}),m(M&&A===`ready`?`drawer.subagentPending`:Ce.enabled?`common.on`:`common.off`)]})]}),(0,V.jsx)(`p`,{children:m(`drawer.subagentDescription`)}),M&&A===`ready`?(0,V.jsxs)(`div`,{className:`personal-subagent-preview`,children:[(0,V.jsx)(`strong`,{children:m(M.enabled?`drawer.subagentConfirmEnable`:`drawer.subagentConfirmDisable`)}),(0,V.jsx)(`p`,{children:M.enabled?m(`drawer.subagentPreviewSummary`,{count:M.maxChildren,domains:M.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)}):m(`drawer.subagentDisableSummary`)}),M.modelConfig===void 0?null:(0,V.jsxs)(`p`,{children:[m(`drawer.subagentModel`),`: `,M.modelConfig?.model||m(`drawer.subagentModelDefault`),` · `,M.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`button`,{className:`personal-primary-action`,onClick:()=>void ke(),type:`button`,children:m(`common.confirm`)}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:z,type:`button`,children:m(`common.cancel`)})]})]}):null,T?(0,V.jsxs)(`p`,{className:`personal-subagent-feedback is-${A}`,role:`status`,children:[A===`previewing`||A===`applying`?(0,V.jsx)(Lm,{className:`personal-spin`,size:13}):null,T]}):null,(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentModel`)}),(0,V.jsx)(`dd`,{children:Ce.modelConfig?.model||m(`drawer.subagentModelDefault`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentEffort`)}),(0,V.jsx)(`dd`,{children:Ce.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentCurrentBoundary`)}),(0,V.jsx)(`dd`,{children:Ce.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentChildLimit`)}),(0,V.jsx)(`dd`,{children:Ce.maxChildren||0})]})]}),u?(0,V.jsx)(`p`,{className:`personal-subagent-read-only`,children:m(`drawer.subagentRemoteReadOnly`)}):(0,V.jsxs)(`div`,{className:`personal-subagent-fields`,children:[(0,V.jsxs)(`fieldset`,{className:`personal-subagent-domain-picker`,disabled:we,children:[(0,V.jsx)(`legend`,{children:m(`drawer.subagentDomains`)}),Te.length>0?(0,V.jsx)(`div`,{className:`personal-subagent-domain-options`,children:Te.map(e=>{let t=C.includes(e.value);return(0,V.jsxs)(`label`,{className:`personal-subagent-domain-option${t?` is-selected`:``}`,children:[(0,V.jsx)(`input`,{"aria-label":e.value,checked:t,onChange:t=>De(e.value,t.target.checked),type:`checkbox`}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.value}),(0,V.jsx)(`small`,{children:m(`drawer.subagentDomainTodoCount`,{count:e.matchingTodoCount})})]})]},e.value)})}):(0,V.jsx)(`p`,{className:`personal-subagent-domain-empty`,children:m(`drawer.subagentDomainsEmpty`)}),(0,V.jsx)(`small`,{children:m(`drawer.subagentDomainsHint`)})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:m(`drawer.subagentModel`)}),(0,V.jsx)(`input`,{"aria-label":m(`drawer.subagentModel`),disabled:we,value:ee,placeholder:`gpt-5.6-luna`,onChange:e=>{te(e.target.value),N(null),j(`idle`),E(null)}})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:m(`drawer.subagentEffort`)}),(0,V.jsxs)(`select`,{"aria-label":m(`drawer.subagentEffort`),disabled:we,value:ne,onChange:e=>{k(e.target.value),N(null),j(`idle`),E(null)},children:[(0,V.jsx)(`option`,{value:``,children:m(`drawer.subagentModelDefault`)}),[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`].map(e=>(0,V.jsx)(`option`,{value:e,children:e},e))]})]}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:we,type:`button`,onClick:()=>{te(`gpt-5.6-luna`),k(`max`),N(null),j(`idle`),E(null)},children:m(`drawer.subagentLunaPreset`)}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:we,type:`button`,onClick:()=>{te(``),k(``),N(null),j(`idle`),E(null)},children:m(`drawer.subagentClearModel`)}),(0,V.jsx)(`p`,{children:m(`drawer.subagentModelHint`)}),(0,V.jsxs)(`label`,{className:`personal-subagent-limit-field`,children:[(0,V.jsx)(`span`,{children:m(`drawer.subagentMaxChildren`)}),(0,V.jsx)(`select`,{"aria-label":m(`drawer.subagentMaxChildren`),disabled:we,onChange:e=>{O(Number(e.target.value)),N(null),j(`idle`),E(null)},value:D,children:Jy.map(e=>(0,V.jsx)(`option`,{value:e,children:e},e))})]}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:we,onClick:()=>void Oe(Ce.enabled,!0),type:`button`,children:m(`drawer.subagentPreviewBoundary`)})]})]}):null]}):null,f.kind===`run`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`div`,{"aria-label":m(`drawer.runView`),className:`personal-run-drawer-tabs`,role:`tablist`,children:[(0,V.jsx)(`button`,{"aria-selected":x===`record`,onClick:()=>S(`record`),role:`tab`,type:`button`,children:m(`drawer.executionRecordAndResult`)}),(0,V.jsx)(`button`,{"aria-selected":x===`details`,onClick:()=>S(`details`),role:`tab`,type:`button`,children:m(`drawer.detailsAndActions`)})]}),x===`record`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card personal-session-summary`,children:[(0,V.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Yi(f.item.sessionStatus??f.item.status,m)]}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.latestActivity}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,V.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]})]})]}),(0,V.jsxs)(`section`,{"aria-label":m(`drawer.executionRecord`),className:`personal-session-message-record`,children:[(0,V.jsx)(`h3`,{children:m(`drawer.executionRecord`)}),f.item.sessionMessages?.length?(0,V.jsx)(`ol`,{children:f.item.sessionMessages.map(e=>(0,V.jsxs)(`li`,{className:`is-${e.role}`,children:[(0,V.jsx)(`i`,{}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:e.role===`user`?m(`drawer.runRoleUser`):e.role===`assistant`?m(`drawer.runRoleAssistant`):m(`drawer.runRoleSystem`)}),e.createdAt?(0,V.jsx)(`time`,{children:new Date(e.createdAt).toLocaleTimeString(p,{hour:`2-digit`,minute:`2-digit`,hour12:!1})}):null]}),(0,V.jsx)(`p`,{children:e.text})]})]},e.messageId))}):(0,V.jsx)(`p`,{className:`personal-session-empty`,children:_e?m(`drawer.runRecordProjected`,{completed:f.item.completedSteps,outputs:f.item.outputs?.length?m(`drawer.runRecordProjectedOutputs`,{count:f.item.outputs.length}):``,total:f.item.totalSteps}):m(`drawer.runRecordEmpty`)}),f.item.status===`running`?(0,V.jsxs)(`div`,{className:`personal-session-active-step`,children:[(0,V.jsx)(`i`,{}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.analysis`)}),(0,V.jsx)(`small`,{children:m(`drawer.agentWorking`)})]})]}):null]}),f.item.outputs?.length?(0,V.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-run-outputs-title`,children:[(0,V.jsx)(`h3`,{id:`personal-run-outputs-title`,children:m(`drawer.outputs`)}),(0,V.jsx)(`ol`,{children:f.item.outputs.map(e=>(0,V.jsx)(`li`,{children:(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.title}),(0,V.jsx)(`small`,{children:e.createdAt??e.kind??m(`files.emptySummary`)})]})},e.outputId))})]}):null]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Yi(f.item.status,m)]}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.latestActivity}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,V.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.sessionStatus`)}),(0,V.jsx)(`dd`,{children:Yi(f.item.sessionStatus??f.item.status,m)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.sessionRecoverable`)}),(0,V.jsx)(`dd`,{children:f.item.resumable===!1?m(`drawer.resumeNo`):m(`drawer.resumeYes`)})]})]})]}),f.item.sessionStatus===`resume_failed`&&!u?(0,V.jsxs)(`section`,{className:`personal-recovery-panel`,"aria-label":m(`drawer.recoveryFailed`),children:[(0,V.jsx)(`strong`,{children:m(`drawer.recoveryFailed`)}),(0,V.jsx)(`p`,{children:m(`drawer.recoveryDescription`)}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,V.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.recoveryNewSession`)]})]}):null,u?null:(0,V.jsxs)(`section`,{className:`personal-correction-panel`,children:[(0,V.jsx)(`header`,{children:(0,V.jsxs)(`span`,{children:[(0,V.jsx)(Zp,{size:16}),m(`drawer.correctionLabel`,{agent:f.item.agentLabel})]})}),(0,V.jsx)(`p`,{children:m(`drawer.correctionDescription`)}),(0,V.jsxs)(`div`,{className:`personal-correction-composer`,children:[(0,V.jsx)(`textarea`,{"aria-label":m(`drawer.correctionTextarea`,{agent:f.item.agentLabel,goal:f.item.goalTitle,run:f.item.title}),onChange:e=>g(e.target.value),placeholder:m(`drawer.correctionPlaceholder`),rows:3,value:h}),(0,V.jsx)(`button`,{"aria-label":m(`drawer.correctionSend`),disabled:!h.trim(),onClick:()=>void be(),type:`button`,children:(0,V.jsx)(Bm,{size:16})})]})]}),u?null:(0,V.jsxs)(`details`,{className:`personal-compact-menu personal-run-more`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(dm,{size:17}),m(`drawer.moreRunActions`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`button`,{disabled:!f.item.canInterrupt,onClick:()=>void r.onInterruptRun?.(f.item),type:`button`,children:[(0,V.jsx)(Mm,{size:16}),m(`drawer.runInterrupt`)]}),(0,V.jsxs)(`button`,{disabled:f.item.resumable===!1,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,V.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,V.jsxs)(`button`,{onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.runNewSession`)]}),(0,V.jsxs)(`button`,{onClick:()=>void r.onCloseRunSession?.(f.item),type:`button`,children:[(0,V.jsx)(qm,{size:16}),m(`drawer.runCloseSession`)]})]})]})]})]}):null,f.kind===`output`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsx)(`small`,{children:f.item.kind??`output`}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.summary??m(`drawer.outputRecorded`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.outputTodo`)}),(0,V.jsx)(`dd`,{children:f.item.todoId??m(`drawer.notLinked`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.outputRun`)}),(0,V.jsx)(`dd`,{children:f.item.runId??m(`drawer.notLinked`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Agent`}),(0,V.jsx)(`dd`,{children:f.item.agentLabel??f.item.agentId??`LoopX`})]})]})]}),f.item.report?(0,V.jsxs)(`section`,{className:`personal-report-detail`,"data-testid":`personal-periodic-report-detail`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsxs)(`strong`,{children:[`+`,f.item.report.addedCount]}),m(`files.reportAdded`)]}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:f.item.report.changedCount}),m(`files.reportChanged`)]})]}),(0,V.jsxs)(`p`,{children:[f.item.report.periodStartAt,` → `,f.item.report.periodEndAt]}),(0,V.jsx)(`ol`,{children:f.item.report.items.map(e=>(0,V.jsxs)(`li`,{"data-change-kind":e.changeKind,children:[(0,V.jsxs)(`small`,{children:[e.changeKind,` · `,e.status]}),(0,V.jsx)(`strong`,{children:e.title}),(0,V.jsx)(`p`,{children:e.summary})]},e.sourceRef))}),(0,V.jsxs)(`footer`,{children:[(0,V.jsxs)(`span`,{children:[m(`files.reportPublication`),`: `,f.item.report.publicationId]}),(0,V.jsxs)(`span`,{children:[m(`files.reportGeneration`),`: `,f.item.report.generationId]})]})]}):null,f.item.safePreview?(0,V.jsx)(`pre`,{"aria-label":m(`drawer.outputSafePreview`),className:`personal-safe-preview`,children:f.item.safePreview}):(0,V.jsx)(`p`,{className:`personal-preview-unavailable`,children:m(`drawer.previewUnavailable`)}),(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:!r.onOpenOutput,onClick:()=>{r.onOpenOutput?.(f.item),c()},type:`button`,children:[(0,V.jsx)(fm,{size:16}),m(`files.openConversation`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!r.onExportOutput,onClick:()=>void r.onExportOutput?.(f.item),type:`button`,children:[(0,V.jsx)(um,{size:16}),m(`files.exportSummary`)]})]})]}):null,f.kind===`proposal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-proposal-card`,children:[(0,V.jsxs)(`small`,{children:[f.item.actionKind,` · `,f.item.status]}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.impact}),f.item.reviewPlan?(0,V.jsx)(`p`,{className:`personal-proposal-explainer`,"data-action-review":f.item.reviewPlan.interaction,children:m(`actionReview.${f.item.reviewPlan.reason}`)}):null,f.item.status===`ready`?(0,V.jsx)(`p`,{className:`personal-proposal-explainer`,children:m(`drawer.proposalExplainer`)}):null,(0,V.jsx)(`dl`,{children:f.item.fields.map(e=>(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:e.label}),(0,V.jsx)(`dd`,{children:e.value})]},e.key))})]}),f.item.status===`applied`?(0,V.jsxs)(`p`,{className:`personal-proposal-state is-applied`,children:[(0,V.jsx)(em,{size:16}),m(`drawer.proposalApplied`)]}):null,f.item.status===`applied`&&f.item.goalId?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>{let e=f.item.goalId;c(),r.onOpenGoal?.(e)},type:`button`,children:[(0,V.jsx)(fm,{size:16}),f.item.actionKind===`goal.create`?m(`drawer.proposalEnterGoal`):m(`drawer.proposalViewGoal`)]}):null,f.item.status===`stale`?(0,V.jsx)(`p`,{className:`personal-proposal-state is-stale`,children:m(`drawer.proposalStale`)}):null,f.item.status===`error`?(0,V.jsxs)(`div`,{className:`personal-proposal-state is-error`,children:[(0,V.jsx)(`span`,{children:f.item.reviewPlan?.reason===`readback_unverified`?m(`actionReview.readback_unverified`):m(`drawer.proposalApplyFailed`)}),f.item.errorMessage?(0,V.jsx)(`small`,{children:f.item.errorMessage}):null,(0,V.jsx)(`small`,{children:m(`drawer.proposalApplyFailedHint`)})]}):null,f.item.status===`rejected`?(0,V.jsx)(`p`,{className:`personal-proposal-state is-error`,children:m(`drawer.proposalRejected`)}):null,f.item.status===`deferred`?(0,V.jsx)(`p`,{className:`personal-proposal-state is-gated`,children:m(`drawer.proposalDeferred`)}):null,f.item.status===`gated`?(0,V.jsxs)(`div`,{className:`personal-proposal-state is-gated`,children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.gateRequiresHost`)}),m(`drawer.gateRequiresHostDescription`)]}),f.item.gate?.nextAction?(0,V.jsx)(`small`,{children:f.item.gate.nextAction}):null]}):null,f.item.status===`gated`&&f.item.actionKind===`gate.resolve`?(()=>{let e=e=>f.item.fields.find(t=>t.key===e)?.value,t=e(`goal_id`),n=e(`todo_id`);return!t||!n?null:(0,V.jsxs)(`section`,{className:`personal-detail-card personal-gate-cli-hint`,children:[(0,V.jsx)(`small`,{children:m(`drawer.gateApproveHint`)}),(0,V.jsxs)(`code`,{children:[`loopx todo complete --goal-id `,t,` --todo-id `,n,` --decision-outcome approve`]}),(0,V.jsx)(`small`,{children:m(`drawer.gateRejectHint`)})]})})():null,!u&&f.item.workspaceCandidates?.length?(0,V.jsx)(`div`,{className:`personal-workspace-candidates`,"aria-label":m(`drawer.workspaceCandidates`),children:f.item.workspaceCandidates.map(e=>(0,V.jsxs)(`button`,{onClick:()=>void r.onSelectWorkspaceCandidate?.(f.item,e.workspaceRef),type:`button`,children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsx)(`small`,{children:e.workspaceRef})]},e.workspaceRef))}):null,!u&&f.item.status===`error`?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,V.jsx)(Lm,{size:17}),m(`drawer.proposalRegenerate`)]}):!u&&f.item.status!==`gated`?(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:![`ready`,`deferred`].includes(f.item.status)||f.item.reviewPlan?.canApply===!1,onClick:()=>void r.onApplyProposal?.(f.item),type:`button`,children:[(0,V.jsx)(em,{size:17}),f.item.status===`applying`?m(`drawer.applying`):f.item.primaryLabel??m(`drawer.apply`)]}):null,!u&&([`stale`,`gated`,`rejected`].includes(f.item.status)||f.item.status===`ready`&&f.item.reviewPlan?.canApply===!1)?(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,V.jsx)(Lm,{size:16}),m(`drawer.proposalRecheck`)]}):null,!u&&[`ready`,`gated`].includes(f.item.status)?(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`defer`),type:`button`,children:m(`drawer.proposalDefer`)}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`reject`),type:`button`,children:m(`drawer.decisionReject`)})]}):null,[`applied`,`applying`].includes(f.item.status)?null:(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:c,type:`button`,children:m(`drawer.proposalClose`)})]}):null,f.kind===`schedule`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsxs)(`small`,{children:[f.item.scheduleKind===`heartbeat`?`Goal Heartbeat`:`continuous_monitor`,` · `,f.item.status??`active`]}),(0,V.jsx)(`h3`,{children:f.item.label}),(0,V.jsx)(`p`,{children:f.item.target??f.item.schedule??m(`drawer.scheduleDefaultTarget`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleTimezone`)}),(0,V.jsx)(`dd`,{children:f.item.timezone??m(`drawer.scheduleLocalTimezone`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleNext`)}),(0,V.jsx)(`dd`,{children:f.item.nextRunAt??m(`drawer.schedulePending`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleLast`)}),(0,V.jsx)(`dd`,{children:f.item.previousRunAt??m(`drawer.scheduleNeverRun`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleNotification`)}),(0,V.jsx)(`dd`,{children:f.item.notificationRule??m(`drawer.scheduleDefaultNotification`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleStopCondition`)}),(0,V.jsx)(`dd`,{children:f.item.stopCondition??m(`drawer.scheduleDefaultStop`)})]})]})]}),!u&&f.item.scheduleKind===`monitor`?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`run_now`),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.scheduleRunNow`)]}):null,u?null:(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,f.item.status===`paused`?`resume`:`pause`),type:`button`,children:[f.item.status===`paused`?(0,V.jsx)(Nm,{size:16}):(0,V.jsx)(Mm,{size:16}),f.item.status===`paused`?m(`drawer.scheduleResume`):m(`drawer.schedulePause`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`edit`),type:`button`,children:[(0,V.jsx)($p,{size:16}),m(`drawer.scheduleEdit`)]})]}),u?null:(0,V.jsxs)(`button`,{className:`personal-danger-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`stop`),type:`button`,children:[(0,V.jsx)(qm,{size:16}),m(`drawer.scheduleStop`,{kind:f.item.scheduleKind===`heartbeat`?` Heartbeat`:m(`drawer.titleSchedule`)})]}),(0,V.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-execution-history-title`,children:[(0,V.jsx)(`h3`,{id:`personal-execution-history-title`,children:m(`drawer.executionHistory`)}),f.item.executionHistory?.length?(0,V.jsx)(`ol`,{children:f.item.executionHistory.map((e,t)=>(0,V.jsxs)(`li`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsx)(`small`,{children:e.timestamp})]}),(0,V.jsx)(`em`,{className:`is-${e.status}`,children:e.status})]},`${e.timestamp}:${e.runId??t}`))}):(0,V.jsx)(`p`,{children:m(`drawer.noExecutionHistory`)})]})]}):null,f.kind===`run`||f.kind===`proposal`||f.kind===`schedule`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`button`,{"aria-expanded":_,className:`personal-diagnostics-trigger`,onClick:()=>v(e=>!e),type:`button`,children:[(0,V.jsx)(`span`,{children:m(`drawer.advancedDiagnostics`)}),(0,V.jsx)(tm,{className:_?`is-open`:``,size:16})]}),_?(0,V.jsxs)(`div`,{className:`personal-diagnostics`,children:[(0,V.jsxs)(`code`,{children:[`goal_id: `,me]}),(0,V.jsxs)(`code`,{children:[`kind: `,f.kind]}),f.kind===`run`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`code`,{children:[`session_id: `,f.item.sessionId??m(`drawer.notLinked`)]}),(0,V.jsxs)(`code`,{children:[`turn_id: `,f.item.turnId??m(`common.none`)]}),(0,V.jsxs)(`code`,{children:[`adapter: `,f.item.agentId]}),(0,V.jsxs)(`code`,{children:[`status: `,f.item.sessionStatus??f.item.status]})]}):f.kind===`proposal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`code`,{children:[`action: `,f.item.actionKind]}),(0,V.jsxs)(`code`,{children:[`status: `,f.item.status]})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`code`,{children:[`schedule_id: `,f.item.scheduleId]}),(0,V.jsxs)(`code`,{children:[`status: `,f.item.status??`active`]})]})]}):null]}):null]})]})}var $y=[`checking`,`connecting`,`downloading`,`installing_app`,`installing_runtime`],eb={desktop_status_unavailable:[`无法读取 App 更新状态。请重启 App 后再试;若仍失败,请重新安装最新 App。`,`Cannot read the App update status. Restart the App; if this persists, reinstall the latest App.`],update_feed_unavailable:[`此通道的更新源尚未就绪或暂时不可用。可稍后重新检查,当前版本仍可继续使用。`,`This channel's update feed is not ready or temporarily unavailable. Check again later; you can keep using this version.`],update_feed_invalid:[`更新源格式异常。请稍后重新检查。`,`The update feed is invalid. Check again later.`],update_platform_unavailable:[`此通道尚无适用于本机的更新包。`,`This channel has no update package for this platform.`],update_check_timeout:[`检查更新超时。请稍后重试。`,`The update check timed out. Try again later.`],update_network_failed:[`无法连接更新服务器。请检查网络后重试。`,`Cannot reach the update server. Check your connection and retry.`],update_download_or_signature_failed:[`更新包下载或签名校验失败,尚未安装。请重新检查更新。`,`Download or signature verification failed; the update was not installed. Check for updates again.`]};function tb(e,t=`update_failed`){return{phase:`error`,details:{code:typeof e==`string`&&Object.hasOwn(eb,e)?e:t}}}function nb(){let{locale:e}=qi(),t=e===`zh-CN`,[n,r]=(0,B.useState)(!1),i=(0,B.useRef)(null),[a,o]=(0,B.useState)(`stable`),[s,c]=(0,B.useState)({phase:`idle`}),[l,u]=(0,B.useState)(``),[d,f]=(0,B.useState)(!1),p=(0,B.useRef)(!1),m=window.__TAURI__?.core.invoke,h=$y.includes(s.phase);(0,B.useEffect)(()=>{let e=i.current;if(!e)return;let t=()=>r(e.matches(`:popover-open`));return e.addEventListener(`toggle`,t),()=>e.removeEventListener(`toggle`,t)},[]),(0,B.useEffect)(()=>{if(!m)return;let e=!0;return m(`desktop_update_status`).then(t=>{if(!e)return;u(t.app_version),f(t.rollback_available===!0),t.state?.phase&&c(t.state);let n=t.state?.details?.channel??(t.app_version.includes(`-main.`)?`main`:`stable`);o(n),t.state?.phase||m(`desktop_update`,{action:`check`,channel:n}).then(t=>{e&&c(t)}).catch(t=>{e&&c(tb(t))})}).catch(()=>{e&&c(tb(null,`desktop_status_unavailable`))}),()=>{e=!1}},[m]),(0,B.useEffect)(()=>{if(!m||!h)return;let e=window.setInterval(()=>{m(`desktop_update_status`).then(e=>{e.state?.phase&&c(e.state)}).catch(()=>{})},1e3);return()=>window.clearInterval(e)},[m,h]);async function g(e){if(!(!m||p.current)){p.current=!0,c({phase:e===`check`?`checking`:e===`repair`?`installing_runtime`:`downloading`});try{if(!l){let e=await m(`desktop_update_status`);u(e.app_version),f(e.rollback_available===!0)}c(await m(`desktop_update`,{action:e,channel:a}))}catch(e){c(tb(e,l?`update_failed`:`desktop_status_unavailable`))}finally{p.current=!1}}}let _={service_error:t?`运行时已安装,但服务尚未连接。可重试更新、修复或恢复上版。`:`Runtime installed, but services are unavailable. Retry updates, repair, or restore the previous version.`,idle:t?`App 会检查可用更新,不会自动安装。`:`Updates are checked automatically, never installed without confirmation.`,runtime_required:t?`请完成匹配组件安装,或检查 App 更新。`:`Install matching components or check for an App update.`,connecting:t?`正在连接更新后的服务…`:`Connecting to updated services…`,checking:t?`正在检查更新…`:`Checking for updates…`,available:t?`新版本已就绪,一次更新 App 与匹配的运行时。`:`Update the App and its matching runtime together.`,up_to_date:t?`当前通道暂无更新。`:`No newer update on this channel.`,downloading:t?`正在下载并校验签名…`:`Downloading and verifying signature…`,installing_app:t?`正在安装 App,请保持窗口打开。`:`Installing the App. Keep this window open.`,installing_runtime:t?`正在安装匹配的运行时,请稍候…`:`Installing the matching runtime…`,restart_required:t?`重启后将自动完成运行时安装与服务连接。`:`Restart to finish runtime installation and reconnect services.`,ready:t?`更新完成,服务已就绪。`:`Update completed; services are ready.`,error:eb[s.details?.code??``]?.[+!t]??(t?`更新未完成。请重试;启动失败可尝试修复当前版本。`:`Update incomplete. Retry; repair this version if startup fails.`)},v=h?t?`正在更新…`:`Updating…`:s.phase===`available`?t?`有可用更新`:`Update available`:s.phase===`restart_required`?t?`重启完成更新`:`Restart to finish`:s.phase===`error`?t?`更新需重试`:`Retry update`:t?`更新 LoopX`:`Update LoopX`;return(0,V.jsxs)(`div`,{className:`personal-desktop-update`,children:[(0,V.jsxs)(`button`,{className:`personal-update-trigger`,type:`button`,"aria-expanded":n,"aria-controls":`desktop-update-panel`,onClick:e=>{i.current?.style.setProperty(`bottom`,`${window.innerHeight-e.currentTarget.getBoundingClientRect().top+8}px`),i.current?.togglePopover()},children:[(0,V.jsx)(um,{size:16,"aria-hidden":`true`}),(0,V.jsx)(`span`,{children:v}),(0,V.jsx)(rm,{size:14,"aria-hidden":`true`})]}),(0,V.jsxs)(`section`,{ref:i,popover:`auto`,id:`desktop-update-panel`,className:`personal-update-panel`,"aria-label":t?`LoopX 更新`:`LoopX updates`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:t?`LoopX 更新`:`LoopX updates`}),(0,V.jsx)(`button`,{type:`button`,"aria-label":t?`关闭更新面板`:`Close updates`,onClick:()=>i.current?.hidePopover(),children:(0,V.jsx)($m,{size:16,"aria-hidden":`true`})})]}),(0,V.jsxs)(`small`,{children:[l,` · `,a===`main`?t?`main 预览版`:`main preview`:t?`稳定版`:`Stable`]}),s.details?.version?(0,V.jsxs)(`p`,{children:[t?`目标版本:`:`Target: `,s.details.version]}):null,(0,V.jsxs)(`p`,{role:`status`,"aria-live":`polite`,children:[h?(0,V.jsx)(Im,{className:`is-spinning`,size:14,"aria-hidden":`true`}):null,_[s.phase]]}),s.phase===`downloading`&&s.details?.total?(0,V.jsx)(`progress`,{"aria-label":t?`下载进度`:`Download progress`,max:s.details.total,value:s.details.received??0}):null,m?(0,V.jsx)(`div`,{className:`personal-update-actions`,children:s.phase===`restart_required`?(0,V.jsx)(`button`,{type:`button`,onClick:()=>void g(`restart`),children:t?`重启完成更新`:`Restart to finish`}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{type:`button`,disabled:h,onClick:()=>void g(`check`),children:t?`检查更新`:`Check for updates`}),s.phase===`available`?(0,V.jsx)(`button`,{type:`button`,onClick:()=>void g(`apply`),children:t?`更新并准备重启`:`Install update`}):null]})}):(0,V.jsx)(`p`,{children:t?`请在 LoopX App 中更新;浏览器自身无需安装包。`:`Update from the LoopX App; the browser needs no installer.`}),(0,V.jsxs)(`details`,{children:[(0,V.jsx)(`summary`,{children:t?`高级选项`:`Advanced options`}),(0,V.jsxs)(`label`,{children:[t?`更新通道`:`Update channel`,(0,V.jsxs)(`select`,{disabled:h||s.phase===`restart_required`,value:a,onChange:e=>{o(e.target.value),c({phase:`idle`})},children:[(0,V.jsx)(`option`,{value:`stable`,children:t?`稳定版(推荐)`:`Stable (recommended)`}),(0,V.jsx)(`option`,{value:`main`,children:t?`main 预览版`:`main preview`})]})]}),(0,V.jsx)(`p`,{children:t?`App 与匹配的 CLI 一起更新,服务可能短暂断开。不删除 Goal 数据。`:`Updates the App and matching CLI. Services may briefly disconnect. Goal data is not deleted.`}),m?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{children:t?`启动失败时,可重装当前 App 随附的运行时。`:`If startup fails, reinstall this App's bundled runtime.`}),(0,V.jsx)(`button`,{disabled:h||s.phase===`restart_required`,type:`button`,onClick:()=>void g(`repair`),children:t?`修复当前版本`:`Repair this version`})]}):null,m&&d?(0,V.jsxs)(`details`,{children:[(0,V.jsx)(`summary`,{children:t?`恢复上个版本`:`Restore previous version`}),(0,V.jsx)(`p`,{children:t?`将恢复已保留的 App 和它的运行时,需要重启。`:`Restore the retained App and its runtime, then restart.`}),(0,V.jsx)(`button`,{disabled:h,type:`button`,onClick:()=>void g(`rollback`),children:t?`确认恢复上版`:`Restore previous version`})]}):null]})]})]})}var rb=e=>`loopx-sidebar-goal-order-v1:${encodeURIComponent(e)}`;function ib(e){try{let t=JSON.parse(e??`null`);return Array.isArray(t)&&t.every(e=>typeof e==`string`)?[...new Set(t)]:[]}catch{return[]}}function ab(e,t){let n=new Map(t.map((e,t)=>[e,t]));return[...e].sort((e,t)=>(n.get(e.goalId)??1/0)-(n.get(t.goalId)??1/0))}function ob(e,t,n,r,i){if(n===r||!t.includes(n)||!t.includes(r))return e;let a=[...new Set([...e,...t])].filter(e=>e!==n);return a.splice(a.indexOf(r)+Number(i),0,n),a}function sb(e,t){let n=rb(t),[r,i]=(0,B.useState)(()=>{try{return ib(localStorage.getItem(n))}catch{return[]}}),[a,o]=(0,B.useState)(!1),[s,c]=(0,B.useState)(null),[l,u]=(0,B.useState)(null),d=(0,B.useRef)(null),f=(0,B.useRef)(!1),p=ab(e,r),m=p.map(e=>e.goalId);function h(t,a,s){let l=ob(r,m,t,a,s);if(l===r)return;i(l);let u=ab(e,l),d=u.findIndex(e=>e.goalId===t),f=u[d];f&&c({title:f.title,position:d+1});try{localStorage.setItem(n,JSON.stringify(l)),o(!1)}catch{o(!0)}}function g(){d.current=null,u(null)}return{sorted:p,target:l,saveFailed:a,lastMoved:s,move:h,moveBy(e,t){let n=p[m.indexOf(e)+t];n&&h(e,n.goalId,t===1)},pointerProps:e=>({onPointerDown(t){f.current=!1,t.pointerType===`mouse`&&t.button===0&&(d.current={id:e,x:t.clientX,y:t.clientY,dragging:!1},t.currentTarget.setPointerCapture(t.pointerId))},onPointerMove(e){let t=d.current;if(!t||!t.dragging&&Math.hypot(e.clientX-t.x,e.clientY-t.y)<6)return;t.dragging=!0,f.current=!0;let n=document.elementFromPoint(e.clientX,e.clientY)?.closest(`[data-reorder-goal]`),r=e.currentTarget.closest(`.personal-goal-list`),i=n?.dataset.reorderGoal;if(!n||!i||!r?.contains(n)||i===t.id){u(null);return}let a=n.getBoundingClientRect();u({id:i,after:e.clientY>a.top+a.height/2})},onPointerUp(){d.current?.dragging&&l&&h(d.current.id,l.id,l.after),g()},onPointerCancel:g,onLostPointerCapture:g,onKeyDown(e){e.key===`Escape`&&g()},onClickCapture(e){f.current&&=(e.preventDefault(),e.stopPropagation(),!1)}})}}var cb=`/ssh-hosts`,lb=/^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;function ub(e){return typeof e==`string`&&lb.test(e.trim())}function db(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`SSH Host 列表响应无效。`);let t=e;if(t.ok!==!0||t.schema_version!==`ssh_host_catalog_v0`||!Array.isArray(t.hosts))throw Error(`SSH Host 列表协议不兼容,请更新本机 LoopX 服务。`);let n=new Set;return{hosts:t.hosts.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=String(e.alias??``).trim();return!ub(t)||n.has(t)?[]:(n.add(t),[{alias:t}])}),schemaVersion:`ssh_host_catalog_v0`}}async function fb(e=fetch,t=cb){let n=await e(t,{cache:`no-store`});if(!n.ok)throw Error(`无法读取本机 SSH Host(HTTP ${n.status})。`);return db(await n.json())}function pb(e,t){let n=e.trim();if(!ub(n))return{error:`请选择有效的 SSH Host。`};let r=Number(t);return!Number.isInteger(r)||r<1024||r>65535?{error:`本地端口必须是 1024–65535 之间的整数。`}:{command:`ssh -N -L ${r}:127.0.0.1:8766 ${n}`,hostAlias:n,label:n,statusUrl:`http://127.0.0.1:${r}/status.json`}}var mb=`/api/ssh-source/ensure`,hb=`/api/ssh-source/goal-lifecycle`;async function gb(e,t){let n=await fetch(mb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({host_alias:e,local_port:Number(t)})}),r=await n.json().catch(()=>null);if(!n.ok)throw Error(r?.error??`无法建立 SSH 隧道来源。`);if(!r?.ok)throw Error(`无法建立 SSH 隧道来源。`);return r}async function _b(e,t,n,r,i=fetch){let a=await i(hb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({goal_id:t,host_alias:e,operation:n,reason:r})}),o=await a.json().catch(()=>null);if(!a.ok)throw Error(o?.error??`无法更新远端 Goal 生命周期。`);if(!o?.ok||o.schema_version!==`loopx_remote_goal_lifecycle_v1`||o.goal_id!==t||o.host_alias!==e||o.operation!==n||o.activation_state!==(n===`stop`?`stopped`:`active`)||o.projection_verified!==!0)throw Error(`远端 Goal 生命周期回读未验证。`);return o}function vb({activeSource:e,connectionState:t,errorMessage:n,onAdd:r,onConfiguredHostsLoaded:i,onRemove:a,onSelect:o,sources:s}){let{t:c}=qi(),[l,u]=(0,B.useState)(!1),[d,f]=(0,B.useState)(null),[p,m]=(0,B.useState)(`configured`),[h,g]=(0,B.useState)([]),[_,v]=(0,B.useState)(null),[y,b]=(0,B.useState)(!1),[x,S]=(0,B.useState)(!1),[C,w]=(0,B.useState)(``),[T,E]=(0,B.useState)(``),[D,O]=(0,B.useState)(`8876`),[ee,te]=(0,B.useState)(``),ne=`configured:`,k=[...s.map(e=>({label:e.label,value:e.id})),...h.filter(e=>!s.some(t=>t.label===e.alias)).map(e=>({group:c(`source.configuredGroup`,{count:h.length}),label:e.alias,value:`${ne}${e.alias}`}))],A=(0,B.useMemo)(()=>h.some(e=>e.alias===C)?pb(C,D):{error:c(`source.selectHost`)},[h,C,D,c]);(0,B.useEffect)(()=>{j()},[]);async function j(){b(!0),v(null);try{let e=await fb();g(e.hosts),i?.(e.hosts.map(e=>e.alias)),w(t=>t||e.hosts[0]?.alias||``),e.hosts.length||v(c(`source.hostEmpty`))}catch(e){v(e instanceof Error?e.message:c(`source.hostLoadError`))}finally{b(!1)}}function M(){u(!0),m(`configured`),f(null),j()}function N(){u(!1),m(`configured`),v(null),S(!1),w(``),f(null),E(``),O(`8876`),te(``)}function P(){let e=r({label:T,statusUrl:ee});if(e.error){f(e.error);return}N()}function F(){if(`error`in A){f(A.error??c(`source.invalid`));return}let e=r({ensureTunnel:!0,hostAlias:A.hostAlias,label:A.label,statusUrl:A.statusUrl});if(e.error){f(e.error);return}N()}function re(e){let t=new Set;for(let e of s)try{t.add(new URL(e.statusUrl).port)}catch{}let n=`8877`;for(let e=8877;e<9077;e+=1)if(!t.has(String(e))){n=String(e);break}let i=pb(e,n);if(`error`in i){f(i.error??c(`source.invalid`));return}let a=r({ensureTunnel:!0,hostAlias:i.hostAlias,label:i.label,statusUrl:i.statusUrl});a.error?f(a.error):f(null),O(n)}async function ie(){if(`error`in A){f(A.error??c(`source.invalid`));return}try{await navigator.clipboard.writeText(A.command),S(!0),f(null)}catch{f(c(`source.copyError`))}}return(0,V.jsxs)(`section`,{"aria-label":c(`source.controlPlane`),className:`personal-status-source`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`span`,{children:`Control plane`}),(0,V.jsx)(`button`,{"aria-label":c(`source.addSsh`),onClick:M,title:c(`source.add`),type:`button`,children:(0,V.jsx)(Pm,{size:14})})]}),(0,V.jsx)(Sy,{ariaLabel:c(`source.select`),className:`personal-status-source-select`,icon:(0,V.jsx)(Hm,{size:15}),onChange:e=>{if(e.startsWith(ne)){re(e.slice(11));return}o(e)},options:k,value:e.id}),(0,V.jsxs)(`div`,{className:`personal-status-source-meta`,children:[(0,V.jsxs)(`span`,{className:`is-${t}`,children:[(0,V.jsx)(`i`,{}),c(t===`loading`?`source.connecting`:t===`error`?`source.notAvailable`:`source.connected`)]}),(0,V.jsx)(`small`,{children:e.readOnly?c(`source.readOnly`):c(`source.localInteractive`)}),e.kind===`ssh_tunnel`?(0,V.jsx)(`button`,{"aria-label":c(`source.remove`,{source:e.label}),onClick:()=>a(e.id),title:c(`source.removeCurrent`),type:`button`,children:(0,V.jsx)(Xm,{size:12})}):null]}),n?(0,V.jsx)(`p`,{className:`personal-status-source-error`,role:`alert`,children:n}):null,l?(0,V.jsxs)(`div`,{className:`personal-status-source-form`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:c(`source.addSsh`)}),(0,V.jsx)(`button`,{"aria-label":c(`source.closeForm`),onClick:N,type:`button`,children:(0,V.jsx)($m,{size:13})})]}),(0,V.jsxs)(`div`,{"aria-label":c(`source.addMethod`),className:`personal-status-source-modes`,role:`tablist`,children:[(0,V.jsx)(`button`,{"aria-selected":p===`configured`,onClick:()=>{m(`configured`),f(null)},role:`tab`,type:`button`,children:c(`source.configured`)}),(0,V.jsx)(`button`,{"aria-selected":p===`manual`,onClick:()=>{m(`manual`),f(null)},role:`tab`,type:`button`,children:c(`source.manual`)})]}),p===`configured`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.configuredCount`,{count:h.length})}),(0,V.jsxs)(`span`,{className:`personal-status-source-field-row`,children:[(0,V.jsx)(`input`,{"aria-label":c(`source.host`),disabled:y||!h.length,list:`loopx-configured-ssh-hosts`,onChange:e=>{w(e.target.value),S(!1)},placeholder:c(y?`source.loadingHosts`:`source.hostPlaceholder`),value:C}),(0,V.jsx)(`datalist`,{id:`loopx-configured-ssh-hosts`,children:h.map(e=>(0,V.jsx)(`option`,{value:e.alias},e.alias))}),(0,V.jsx)(`button`,{"aria-label":c(`source.refreshHosts`),disabled:y,onClick:()=>void j(),title:c(`source.refreshHosts`),type:`button`,children:(0,V.jsx)(Rm,{size:13})})]})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.localPort`)}),(0,V.jsx)(`input`,{"aria-label":c(`source.localPort`),inputMode:`numeric`,onChange:e=>{O(e.target.value),S(!1)},value:D})]}),(0,V.jsxs)(`div`,{className:`personal-status-source-command`,children:[(0,V.jsx)(`code`,{children:`error`in A?c(`source.tunnelCommandPending`):A.command}),(0,V.jsxs)(`button`,{"aria-label":c(`source.copyCommand`),disabled:`error`in A,onClick:()=>void ie(),type:`button`,children:[(0,V.jsx)(cm,{size:12}),c(x?`source.copied`:`source.copy`)]})]}),_?(0,V.jsx)(`p`,{className:`is-error`,children:_}):null,(0,V.jsx)(`p`,{children:c(`source.description`)}),(0,V.jsx)(`button`,{className:`personal-status-source-add`,disabled:`error`in A,onClick:F,type:`button`,children:c(`source.addConfigured`)})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.name`)}),(0,V.jsx)(`input`,{autoFocus:!0,maxLength:48,onChange:e=>E(e.target.value),placeholder:c(`source.namePlaceholder`),value:T})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.statusUrl`)}),(0,V.jsx)(`input`,{onChange:e=>te(e.target.value),placeholder:`http://127.0.0.1:8876/status.json`,value:ee})]}),(0,V.jsx)(`p`,{children:(0,V.jsx)(`code`,{children:`ssh -N -L 8876:127.0.0.1:8766 `})}),(0,V.jsx)(`p`,{children:c(`source.manualDescription`)}),(0,V.jsx)(`button`,{className:`personal-status-source-add`,onClick:P,type:`button`,children:c(`source.addConfigured`)})]}),d?(0,V.jsx)(`p`,{className:`is-error`,role:`alert`,children:d}):null]}):null]})}var yb={需修复:`is-danger`,等你:`is-warning`,等待条件:`is-info`,推进中:`is-success`,安静运行:`is-quiet`,已完成:`is-quiet`,已停止:`is-stopped`};function bb({attentionCount:e,goals:t,goalArchiveLoadState:n={error:null,phase:`ready`},lifecycleBusyGoalIds:r,goalLifecycleOperations:i,onRequestGoalCreate:a,onOpenSettings:o,onRetryGoalArchive:s,onRequestGoalLifecycle:c,onSelectGoal:l,selectedGoalId:u,statusSourceControl:d}){let{locale:f,t:p}=qi(),[m,h]=(0,B.useState)(!1),g=sb(t.filter(e=>e.activationState!==`stopped`),d?.activeSource.statusUrl??`/status.json`),_=g.sorted,v=t.filter(e=>e.activationState===`stopped`),y=e=>!!c&&(!i||i.includes(e)),b=(e,t)=>(0,V.jsxs)(`div`,{className:`personal-goal-row${g.target?.id===e.goalId?g.target.after?` is-drop-after`:` is-drop-before`:``}`,"data-reorder-goal":t?void 0:e.goalId,"data-load-error":e.loadError,children:[(0,V.jsxs)(`button`,{...t?{}:g.pointerProps(e.goalId),title:t?void 0:p(`sidebar.dragGoal`),"aria-current":u===e.goalId?`page`:void 0,className:`personal-goal-link`,onClick:()=>l(e.goalId),type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-goal-state-dot ${e.loadState?``:yb[e.state]}`}),(0,V.jsxs)(`span`,{className:`personal-goal-link-copy`,children:[(0,V.jsx)(`strong`,{children:e.title}),(0,V.jsxs)(`small`,{children:[e.loadState&&(!t||u===e.goalId)?p(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Ji(e.state,f),e.needsYou&&!t?` · ${p(`home.lane.needsYou`)}`:``]})]}),(0,V.jsx)(nm,{size:15})]}),!t&&m?(0,V.jsxs)(`div`,{className:`personal-goal-move-actions`,children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveUp`,{goal:e.title}),disabled:_[0]?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,-1),children:(0,V.jsx)(Jp,{"aria-hidden":`true`,size:13})}),(0,V.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveDown`,{goal:e.title}),disabled:_.at(-1)?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,1),children:(0,V.jsx)(Wp,{"aria-hidden":`true`,size:13})})]}):null,c&&y(t?`resume`:`stop`)?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{"aria-label":`${p(t?`sidebar.resume`:`sidebar.stop`)} ${e.title}`,"aria-busy":r?.has(e.goalId)||void 0,className:`personal-goal-lifecycle${r?.has(e.goalId)?` is-pending`:``}`,disabled:r?.has(e.goalId),onClick:()=>c(e,t?`resume`:`stop`),title:p(t?`sidebar.resumeGoal`:`sidebar.stopGoal`),type:`button`,children:r?.has(e.goalId)?(0,V.jsx)(Cm,{size:13}):t?(0,V.jsx)(Lm,{size:13}):(0,V.jsx)(Mm,{size:13})}),t&&y(`delete`)?(0,V.jsx)(`button`,{"aria-label":`${p(`sidebar.delete`)} ${e.title}`,className:`personal-goal-lifecycle personal-goal-delete`,onClick:()=>c(e,`delete`),title:p(`sidebar.deleteGoal`),type:`button`,children:(0,V.jsx)(Xm,{size:13})}):null]}):null]},e.goalId);return(0,V.jsxs)(`div`,{className:`personal-goal-directory`,children:[(0,V.jsxs)(`div`,{className:`personal-sidebar-brand`,children:[(0,V.jsx)(`span`,{className:`personal-brand-mark`,children:(0,V.jsx)(Zp,{size:18})}),(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:`LoopX`})})]}),d?(0,V.jsx)(vb,{...d}):null,(0,V.jsxs)(`nav`,{"aria-label":p(`home.workspace`),className:`personal-sidebar-nav`,children:[(0,V.jsxs)(`button`,{"aria-current":u===null?`page`:void 0,className:`personal-manager-link`,onClick:()=>l(null),type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-manager-icon`,children:(0,V.jsx)(Zp,{size:17})}),(0,V.jsx)(`span`,{children:p(`sidebar.manager`)}),e>0?(0,V.jsx)(`span`,{className:`personal-sidebar-count`,children:e}):null,(0,V.jsx)(nm,{size:15})]}),(0,V.jsxs)(`div`,{className:`personal-sidebar-section-title`,children:[(0,V.jsx)(`span`,{children:`Goals`}),(0,V.jsxs)(`span`,{className:`personal-sidebar-title-actions`,children:[(0,V.jsx)(`small`,{children:_.length}),(0,V.jsx)(`button`,{"aria-label":p(`sidebar.sortGoals`),title:p(`sidebar.sortGoals`),"aria-pressed":m,onClick:()=>h(!m),type:`button`,children:(0,V.jsx)(qp,{"aria-hidden":`true`,size:15})}),a?(0,V.jsx)(`button`,{"aria-label":p(`sidebar.createGoal`),onClick:a,type:`button`,children:(0,V.jsx)(Pm,{size:15})}):null]})]}),g.saveFailed?(0,V.jsx)(`p`,{role:`status`,children:p(`sidebar.orderNotSaved`)}):null,(0,V.jsx)(`span`,{className:`personal-sr-only`,role:`status`,children:g.lastMoved?p(`sidebar.goalMoved`,{goal:g.lastMoved.title,position:g.lastMoved.position}):``}),(0,V.jsx)(`div`,{className:`personal-goal-list`,children:_.map(e=>b(e,!1))}),v.length||n.phase===`loading`||n.phase===`error`?(0,V.jsxs)(`details`,{className:`personal-stopped-goals`,open:n.phase===`error`||void 0,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(tm,{size:13}),(0,V.jsx)(`span`,{children:p(`sidebar.stopped`)}),n.phase===`loading`?(0,V.jsx)(Cm,{"aria-label":p(`sidebar.stoppedLoading`),className:`is-spinning`,size:13}):(0,V.jsx)(`small`,{children:v.length})]}),(0,V.jsxs)(`div`,{className:`personal-goal-list is-stopped`,children:[n.phase===`error`?(0,V.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`alert`,children:[(0,V.jsx)(`span`,{children:p(`sidebar.stoppedLoadFailed`)}),s?(0,V.jsx)(`button`,{onClick:s,type:`button`,children:p(`sidebar.retryStopped`)}):null]}):null,v.map(e=>b(e,!0))]})]}):null]}),(0,V.jsxs)(`div`,{className:`personal-sidebar-footer`,children:[(0,V.jsx)(nb,{}),o?(0,V.jsxs)(`button`,{"aria-label":p(`settings.open`),className:`personal-sidebar-utility`,onClick:o,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-sidebar-utility-icon`,children:(0,V.jsx)(Um,{size:17})}),(0,V.jsx)(`span`,{className:`personal-sidebar-utility-copy`,children:(0,V.jsx)(`strong`,{children:p(`settings.open`)})}),(0,V.jsx)(nm,{"aria-hidden":`true`,size:15})]}):null]})]})}var xb=Y({ok:X(!0),total:K().int().nonnegative(),next_cursor:G().nullable(),items:J(Y({todo_id:G(),text:G(),claimed_by:G().nullable(),evidence:G().nullable(),priority:G().nullable(),task_class:G().nullable()})).max(40)});function Sb({goal:e,agentId:t,seed:n,enabled:r,listView:i=!1,onSelect:a}){let{t:o}=qi(),s=(0,B.useId)(),[c,l]=(0,B.useState)(!1),u=!i||c,d=i?96:148,[f,p]=(0,B.useState)(n),[m,h]=(0,B.useState)(t===`all`?e.doneTodoCount??n.length:n.length),[g,_]=(0,B.useState)(void 0),[v,y]=(0,B.useState)(!1),[b,x]=(0,B.useState)(!1),[S,C]=(0,B.useState)(!1),[w,T]=(0,B.useState)({top:0,height:600}),[E,D]=(0,B.useState)(null),O=(0,B.useRef)(null),ee=(0,B.useRef)(null),[te,ne]=(0,B.useState)(0);(0,B.useEffect)(()=>{let e=O.current;if(!e)return;let t=new ResizeObserver(()=>T({top:e.scrollTop,height:e.clientHeight}));return t.observe(e),()=>{t.disconnect(),ee.current?.abort()}},[]);let k=g===void 0||w.top+w.height>=f.length*d-d*2;(0,B.useEffect)(()=>{if(!r||!u||!k||g===null||b||ee.current)return;let n=new AbortController;ee.current=n,y(!0);let i=new URLSearchParams({goal_id:e.goalId});t!==`all`&&i.set(`agent_id`,t),g&&i.set(`cursor`,g),fetch(`/api/chat/completed-todos?${i}`,{signal:n.signal}).then(async e=>{if(e.status===409&&C(!0),!e.ok)throw Error(`history unavailable`);let t=xb.parse(await e.json());if(n.signal.aborted)return;let r=t.items.map(e=>({todoId:e.todo_id,text:e.text,claimedBy:e.claimed_by,evidence:e.evidence,priority:e.priority,taskClass:e.task_class,done:!0,status:`done`}));p(e=>g===void 0?r:[...e,...r.filter(t=>!e.some(e=>e.todoId===t.todoId))]),h(t.total),_(t.next_cursor)}).catch(()=>{n.signal.aborted||x(!0)}).finally(()=>{n.signal.aborted||(ee.current=null,y(!1))})},[r,u,k,g,b,te,e.goalId,t,v]),(0,B.useEffect)(()=>{O.current&&(O.current.scrollTop=0),T({top:0,height:O.current?.clientHeight??600}),D(null)},[i]);let A=Math.max(0,Math.floor(w.top/d)-3),j=Math.min(f.length,Math.ceil((w.top+w.height)/d)+3),M=Array.from({length:Math.max(0,j-A)},(e,t)=>A+t);return E!==null&&El(e=>!e),children:[(0,V.jsx)(`span`,{"aria-hidden":`true`,children:c?`▾`:`▸`}),` `,o(`tasks.completed`)]}):(0,V.jsxs)(`strong`,{children:[(0,V.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-done`}),o(`tasks.completed`)]}),(0,V.jsx)(`span`,{children:m})]}),(0,V.jsxs)(`div`,{id:s,hidden:!u,"aria-label":o(`tasks.completed`),className:`personal-task-lane-scroll`,ref:O,role:`region`,tabIndex:0,onScroll:e=>T({top:e.currentTarget.scrollTop,height:e.currentTarget.clientHeight}),children:[(0,V.jsx)(`div`,{className:`personal-completed-window`,style:{height:f.length*d},children:M.map(t=>{let n=f[t];return(0,V.jsx)(`div`,{className:`personal-task-card personal-completed-row`,style:{top:t*d,height:d},children:(0,V.jsxs)(`button`,{type:`button`,onFocus:()=>D(t),onBlur:()=>D(null),onClick:()=>a({kind:`todo`,item:{...n,goalId:e.goalId,goalTitle:e.title,ownerLabel:n.claimedBy??e.agentLabel??e.agentId}}),children:[(0,V.jsx)(`span`,{className:`is-done`,children:`✓`}),(0,V.jsx)(`strong`,{children:n.text}),(0,V.jsx)(`small`,{children:n.claimedBy??e.agentLabel??e.agentId})]})},n.todoId)})}),(0,V.jsx)(`div`,{className:`personal-completed-footer`,role:`status`,children:v?o(`tasks.historyLoading`):b?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`span`,{children:o(S?`tasks.historyExpired`:`tasks.historyError`)}),(0,V.jsx)(`button`,{type:`button`,onClick:()=>{S&&(_(void 0),O.current&&(O.current.scrollTop=0)),C(!1),x(!1),ne(e=>e+1)},children:o(`tasks.historyRetry`)})]}):r?g===null?o(`tasks.historyEnd`):(0,V.jsx)(`button`,{type:`button`,onClick:()=>{O.current&&(O.current.scrollTop=f.length*d)},children:o(`tasks.historyMore`)}):o(`tasks.historyLocalOnly`)})]})]})}function Cb({children:e,count:t,label:n,tone:r,listView:i=!1}){let a=(0,B.useId)(),o=(0,B.useRef)(null),s=(0,B.useRef)([]),c=(0,B.useRef)(null),[l,u]=(0,B.useState)({after:!1,before:!1}),d=(0,B.useCallback)(()=>{let e=o.current;if(!e)return;let t={after:Math.max(0,e.scrollHeight-e.clientHeight)-e.scrollTop>1,before:e.scrollTop>1};u(e=>e.after===t.after&&e.before===t.before?e:t)},[]);return(0,B.useEffect)(()=>{let e=o.current;if(!e)return;let t=new ResizeObserver(d);return c.current=t,t.observe(e),e.addEventListener(`scroll`,d,{passive:!0}),d(),()=>{t.disconnect(),c.current=null,s.current=[],e.removeEventListener(`scroll`,d)}},[i,d]),(0,B.useEffect)(()=>{let e=o.current,t=c.current;if(!e||!t)return;for(let e of s.current)t.unobserve(e);let n=Array.from(e.children).filter(e=>e instanceof HTMLElement);for(let e of n)t.observe(e);s.current=n,d()},[e,t,i,d]),i?!t&&r!==`done`?null:(0,V.jsxs)(`details`,{className:`personal-task-group tone-${r}`,open:!0,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(tm,{size:16}),(0,V.jsx)(`strong`,{children:n}),(0,V.jsx)(`span`,{children:t})]}),(0,V.jsx)(`div`,{className:`personal-task-list-rows`,children:e})]}):(0,V.jsxs)(`section`,{className:`personal-object-list personal-task-lane`,children:[(0,V.jsxs)(`header`,{id:a,children:[(0,V.jsxs)(`strong`,{children:[(0,V.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-${r}`}),n]}),(0,V.jsx)(`span`,{children:t})]}),(0,V.jsx)(`div`,{"aria-labelledby":a,className:`personal-task-lane-scroll${l.before?` has-overflow-before`:``}${l.after?` has-overflow-after`:``}`,ref:o,role:`region`,tabIndex:t>0?0:-1,children:e})]})}function wb({historyEnabled:e=!1,goal:t,items:n,onDraftTaskFromMessage:r,onOpenChat:i,onQuickComplete:a,quickCompletingTodoIds:o,onSelect:s,selectedTodoId:c=null,userTodos:l}){let{t:u}=qi(),[d,f]=(0,B.useState)(!1),[p,m]=(0,B.useState)({goalId:``,laneId:`all`}),h=(0,B.useRef)(null);(0,B.useEffect)(()=>{if(!c)return;let e=window.requestAnimationFrame(()=>h.current?.scrollIntoView({block:`nearest`,inline:`nearest`}));return()=>window.cancelAnimationFrame(e)},[c]);let g=l.filter(e=>e.goalId===t.goalId).map(e=>({...e,goalTitle:t.title})),_=e=>e.priority===`P0`?0:e.priority===`P1`?1:e.priority===`P2`?2:3,v=(0,B.useMemo)(()=>{let e=new Map((t.agentLanes??[]).map(e=>[e.agentId,e]));for(let n of t.agentTodos)n.claimedBy&&!e.has(n.claimedBy)&&e.set(n.claimedBy,{agentId:n.claimedBy,label:n.claimedBy});return[...e.values()]},[t.agentLanes,t.agentTodos]),y=p.goalId===t.goalId&&v.some(e=>e.agentId===p.laneId)?p.laneId:`all`,b=e=>y===`all`||e===y,x=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&!e.done).filter(e=>b(e.claimedBy)).sort((e,t)=>_(e)-_(t)),S=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&e.done).filter(e=>b(e.claimedBy)),C=n.filter(e=>e.kind===`schedule`&&b(e.schedule.agentId)),w=n.filter(e=>e.kind===`run`&&!!e.run.todoId&&b(e.run.agentId)),T=!g.length&&!x.length&&!S.length&&!C.length,E=n.filter(e=>e.kind===`message`&&(e.message.role===`user`||e.message.role===`assistant`)),D=E.reduce((e,t,n)=>t.message.role===`user`?n:e,-1),O=D>=0?E[D]?.message:null,ee=D>=0?E.slice(D+1).reverse().find(e=>e.message.role===`assistant`)?.message:null,te=D>=0&&E.slice(D+1).some(e=>e.message.role===`assistant`&&e.message.pending);return(0,V.jsxs)(`section`,{"aria-label":u(`header.tasks`),className:`personal-task-board${d?` is-list-view`:``}`,children:[(0,V.jsxs)(`header`,{className:`personal-task-view-toolbar`,children:[(0,V.jsx)(`div`,{children:(0,V.jsx)(`strong`,{children:u(`header.tasks`)})}),(0,V.jsxs)(`div`,{className:`personal-task-view-switch`,role:`group`,"aria-label":u(`tasks.viewLabel`),children:[(0,V.jsx)(`button`,{type:`button`,"aria-pressed":d,onClick:()=>f(!0),children:u(`tasks.listView`)}),(0,V.jsx)(`button`,{type:`button`,"aria-pressed":!d,onClick:()=>f(!1),children:u(`tasks.boardView`)})]})]}),v.length>1?(0,V.jsxs)(`section`,{"aria-label":u(`tasks.agentLaneFilter`),className:`personal-task-lane-filter`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(Zp,{size:15}),(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:u(`tasks.agentLane`)})})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{className:`sr-only`,children:u(`tasks.agentLaneFilter`)}),(0,V.jsxs)(`select`,{"aria-label":u(`tasks.agentLaneFilter`),onChange:e=>m({goalId:t.goalId,laneId:e.target.value}),value:y,children:[(0,V.jsx)(`option`,{value:`all`,children:u(`tasks.allAgentLanes`,{count:v.length})}),v.map(e=>(0,V.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))]}),(0,V.jsx)(tm,{"aria-hidden":!0,size:14})]})]}):null,O?(0,V.jsxs)(`section`,{"aria-label":u(`tasks.chatRecent`),className:`personal-task-chat-receipt`,children:[(0,V.jsx)(`span`,{className:`personal-task-chat-icon`,children:(0,V.jsx)(Dm,{size:18})}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:u(te?`tasks.chatPending`:ee?`tasks.chatAgentReplied`:`tasks.chatRecent`)}),(0,V.jsx)(`small`,{children:t.agentLabel??t.agentId})]}),(0,V.jsxs)(`p`,{className:`is-user`,children:[(0,V.jsx)(`b`,{children:u(`common.you`)}),O.text]}),ee&&!ee.pending?(0,V.jsxs)(`p`,{className:`is-assistant`,children:[(0,V.jsx)(`b`,{children:u(`common.agent`)}),ee.text]}):null,(0,V.jsx)(`small`,{children:u(te?`tasks.chatPendingDescription`:`tasks.chatUnchangedDescription`)})]}),(0,V.jsxs)(`footer`,{children:[(0,V.jsxs)(`button`,{onClick:i,type:`button`,children:[(0,V.jsx)(Dm,{size:14}),u(`tasks.chatViewReply`)]}),ee&&!te&&r?(0,V.jsxs)(`button`,{onClick:()=>r(ee.text),type:`button`,children:[(0,V.jsx)(Sm,{size:14}),u(`tasks.convertToTask`)]}):null]})]}):null,(0,V.jsxs)(`div`,{className:d?`personal-task-grouped-list`:`personal-task-kanban`,children:[(0,V.jsxs)(Cb,{listView:d,count:g.length,label:u(`timeline.waitingConfirmation`),tone:`attention`,children:[g.map(e=>{let t=Xi(e.updatedAt,u);return(0,V.jsxs)(`button`,{onClick:()=>s({item:e,kind:`attention`}),type:`button`,children:[(0,V.jsx)(`span`,{"aria-hidden":`true`,className:`is-attention`,children:`!`}),(0,V.jsx)(`strong`,{children:e.text}),(0,V.jsxs)(`small`,{children:[(0,V.jsx)(`span`,{className:`personal-row-status ${e.blocking?`is-blocking`:`is-pending`}`,children:e.blocking?u(`tasks.blocked`):u(`tasks.pending`)}),t?(0,V.jsx)(`span`,{className:`personal-task-age`,children:u(`tasks.waitingAge`,{age:t})}):null]})]},e.todoId)}),g.length?null:(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyConfirm`)})]}),(0,V.jsxs)(Cb,{listView:d,count:x.length,label:u(`tasks.pendingAndRunning`),tone:`progress`,children:[x.map(e=>{let n={...e,goalId:t.goalId,goalTitle:t.title,ownerLabel:e.claimedBy??t.agentLabel??t.agentId},r=w.find(t=>t.run.todoId===e.todoId)?.run;return(0,V.jsxs)(`div`,{className:`personal-task-card${r?` has-session`:``}${c===e.todoId?` is-selected`:``}`,ref:c===e.todoId?e=>{h.current=e}:void 0,children:[(0,V.jsxs)(`button`,{"aria-pressed":c===e.todoId,onClick:()=>s({item:n,kind:`todo`}),type:`button`,children:[(0,V.jsx)(`span`,{children:`○`}),(0,V.jsx)(`strong`,{children:e.text}),(0,V.jsxs)(`small`,{children:[e.priority?(0,V.jsx)(`span`,{className:`personal-priority-badge is-${e.priority.toLowerCase()}`,children:e.priority}):null,e.status===`blocked`?(0,V.jsx)(`span`,{className:`personal-priority-badge is-blocked`,children:u(`tasks.blocked`)}):null,r?(0,V.jsx)(`span`,{className:`personal-task-session-status`,children:r.status===`running`||r.status===`queued`?u(`runs.running`):r.status===`failed`?u(`tasks.sessionError`):u(`common.waiting`)}):null,e.status===`deferred`?(0,V.jsx)(`span`,{className:`personal-task-session-status`,children:u(`drawer.taskStatusDeferred`)}):r?null:(0,V.jsx)(`span`,{className:`personal-task-session-status`,children:u(`tasks.waiting`)}),e.claimedBy??t.agentLabel??t.agentId]})]}),(0,V.jsxs)(`div`,{className:`personal-task-card-actions`,children:[r?(0,V.jsxs)(`button`,{className:`personal-task-session-link`,"aria-label":u(`tasks.openExecution`,{name:e.text}),onClick:()=>s({item:r,kind:`run`}),title:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`),type:`button`,children:[(0,V.jsx)(fm,{size:14}),(0,V.jsx)(`span`,{children:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`)})]}):null,a?(0,V.jsx)(`button`,{"aria-busy":o?.has(e.todoId)||void 0,"aria-label":u(`tasks.markComplete`,{name:e.text}),disabled:o?.has(e.todoId),onClick:()=>void a(n),title:u(`tasks.completed`),type:`button`,children:o?.has(e.todoId)?(0,V.jsx)(Cm,{className:`personal-spin`,size:14}):(0,V.jsx)(em,{size:14})}):null,(0,V.jsx)(`button`,{"aria-label":u(`tasks.moreActions`,{name:e.text}),onClick:()=>s({item:n,kind:`todo`}),title:u(`common.actions`),type:`button`,children:(0,V.jsx)(dm,{size:14})})]})]},e.todoId)}),x.length?null:(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyRunning`)})]}),(0,V.jsxs)(Cb,{listView:d,count:C.length,label:u(`tasks.scheduled`),tone:`schedule`,children:[C.map(e=>(0,V.jsxs)(`button`,{onClick:()=>s({item:e.schedule,kind:`schedule`}),type:`button`,children:[(0,V.jsx)(`span`,{children:`◷`}),(0,V.jsx)(`strong`,{children:e.schedule.label}),(0,V.jsx)(`small`,{children:e.schedule.status===`paused`?u(`schedule.paused`):u(`schedule.active`)})]},e.id)),C.length?null:(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptySchedules`)})]}),(0,V.jsx)(Sb,{goal:t,agentId:y,seed:S,enabled:e,listView:d,onSelect:s},`${t.goalId}:${y}:${e}`)]}),T?(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyGoal`)}):null]})}function Tb(e,t){return{live_steering:{label:t(`lark.ingressSteering`),detail:t(`lark.ingressSteeringDescription`)},session_queue:{label:t(`lark.ingressQueue`),detail:t(`lark.ingressQueueDescription`)},async_inbox:{label:t(`lark.ingressAsync`),detail:t(`lark.ingressAsyncDescription`)},direct_session:{label:t(`lark.ingressLegacy`),detail:t(`lark.ingressLegacyDescription`)}}[e]}function Eb(e,t){return e.listener_status===`starting`?{label:t(`lark.health.starting`),detail:t(`lark.health.startingDetail`),state:`not_ready`}:e.listener_status===`retrying`&&e.listener_error_code===`lark_event_source_disconnected`?{label:t(`lark.health.sourceDisconnected`),detail:t(`lark.health.sourceDisconnectedDetail`),state:`not_ready`}:e.listener_status===`retrying`?{label:t(`lark.health.retrying`),detail:t(`lark.health.retryingDetail`),state:`not_ready`}:e.listener_status===`stopped`||e.listener_status===null?{label:t(`lark.health.notStarted`),detail:t(`lark.health.notStartedDetail`),state:`not_ready`}:e.last_event_status===`message_context_permission_required`?{label:t(`lark.health.messageContextPermission`),detail:t(`lark.health.messageContextPermissionDetail`),state:`not_ready`}:e.last_event_status===`processing_failed`?{label:t(`lark.health.processingFailed`),detail:t(`lark.health.processingFailedDetail`),state:`not_ready`}:e.health_error_code===`invalid_routing_state`?{label:t(`lark.health.invalidRouting`),detail:t(`lark.health.invalidRoutingDetail`),state:`not_ready`}:e.last_event_status===`queued_for_agent`?{label:t(`lark.health.queued`),detail:t(`lark.health.queuedDetail`,{agent:e.agent_id??t(`lark.targetAgent`)}),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`not_addressed`?{label:t(`lark.health.notAddressed`),detail:t(`lark.health.notAddressedDetail`),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`self_message`?{label:t(`lark.health.listening`),detail:t(`lark.health.ignoredSelf`),state:`ready`}:e.health_error_code===`lark_event_route_mismatch`||[`chat_mismatch`,`topic_mismatch`,`route_ambiguous`].includes(e.last_event_reason??``)?{label:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguous`):t(`lark.health.routeMismatch`),detail:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguousDetail`):t(`lark.health.routeMismatchDetail`),state:`not_ready`}:[`invalid_event`,`binding_unavailable`].includes(e.last_event_reason??``)?{label:t(`lark.health.routeUnavailable`),detail:t(`lark.health.routeUnavailableDetail`),state:`not_ready`}:e.last_event_status===`replied_and_acknowledged`?{label:t(`lark.health.listening`),detail:t(`lark.health.eventProcessed`,{events:e.event_count,replies:e.replied_count}),state:`ready`}:e.health_error_code===`lark_event_delivery_unverified`||e.event_count===0?{label:t(`lark.health.eventUnverified`),detail:t(`lark.health.eventUnverifiedDetail`),state:`unverified`}:{label:e.reply_ready?t(`lark.health.listening`):t(`lark.health.unavailable`),detail:t(`lark.health.lastStatus`,{status:e.last_event_status??t(`lark.health.waiting`)}),state:e.reply_ready?`ready`:`not_ready`}}function Db(e){return e.history_permission_guidance?.api_document_url??null}function Ob(e,t,n){if(e instanceof Th){let t=String(e.payload.error_code??``);return{lark_cli_not_installed:n(`lark.error.cliMissing`),lark_cli_not_executable:n(`lark.error.cliExecutable`),lark_cli_start_failed:n(`lark.error.cliStart`),lark_message_permissions_required:n(`lark.error.messagePermissions`),lark_app_required:n(`lark.error.appRequired`),invalid_lark_app:n(`lark.error.invalidApp`),lark_group_lookup_failed:n(`lark.error.groupLookup`),provider_api_failed:n(`lark.error.provider`)}[t]??e.message}return e instanceof Error?e.message:t}function kb({embedded:e=!1,focusGoalConnection:t=!1,goals:n,initialGoalId:r,onChanged:i,onClose:a}){let{t:o}=qi(),[s,c]=(0,B.useState)(`connections`),[l,u]=(0,B.useState)([]),[d,f]=(0,B.useState)([]),[p,m]=(0,B.useState)(!0),[h,g]=(0,B.useState)(null),[_,v]=(0,B.useState)(``),[y,b]=(0,B.useState)(t),[x,S]=(0,B.useState)(``),[C,w]=(0,B.useState)(r??n[0]?.goalId??``),[T,E]=(0,B.useState)(``),[D,O]=(0,B.useState)([]),[ee,te]=(0,B.useState)(``),[ne,k]=(0,B.useState)(!1),[A,j]=(0,B.useState)(null),[M,N]=(0,B.useState)(`addressed_only`),[P,F]=(0,B.useState)(t&&r?`goal`:`manager`),[re,ie]=(0,B.useState)(`async_inbox`),[I,ae]=(0,B.useState)(`topic_reply`),[L,oe]=(0,B.useState)(``),[se,ce]=(0,B.useState)(!1),[le,ue]=(0,B.useState)({}),[de,R]=(0,B.useState)(!1),[fe,pe]=(0,B.useState)(null),[me,he]=(0,B.useState)(null),[ge,_e]=(0,B.useState)(null),[ve,ye]=(0,B.useState)(null),[be,xe]=(0,B.useState)(!1),[Se,Ce]=(0,B.useState)(`loopx-workspace-bot`),[we,Te]=(0,B.useState)(`feishu`),[z,Ee]=(0,B.useState)(null),[De,Oe]=(0,B.useState)(!1),[ke,Ae]=(0,B.useState)(null),je=(0,B.useRef)(null),Me=(0,B.useRef)(null),Ne=(0,B.useRef)(!1);async function Pe(){m(!0),g(null);try{let[e,t]=await Promise.all([Lg(),Kg()]);u(e),f(t),S(t=>t||e.find(e=>e.reply_ready)?.app_ref||e.find(e=>e.ready)?.app_ref||e[0]?.app_ref||``)}catch(e){g(Ob(e,o(`lark.error.configuration`),o))}finally{m(!1)}}(0,B.useEffect)(()=>{Pe()},[]),(0,B.useEffect)(()=>{if(!t||p||Ne.current||!r)return;Ne.current=!0;let e=d.find(e=>e.goal_id===r);e?qe(e):Ke(n.find(e=>e.goalId===r))},[d,t,n,r,p]),(0,B.useEffect)(()=>{if(!y||!x||ge){O([]),te(``),k(!1),j(null);return}let e=!1;k(!0),j(null);let t=window.setTimeout(()=>{Wg(x,T).then(t=>{e||(O(t),te(e=>t.some(t=>t.chat_id===e)?e:t[0]?.chat_id??``))}).catch(t=>{e||(O([]),te(``),j(Ob(t,o(`lark.error.groupLoad`),o)))}).finally(()=>{e||k(!1)})},180);return()=>{e=!0,window.clearTimeout(t)}},[x,T,y,ge]),(0,B.useEffect)(()=>{if(!be||!z||[`ready`,`failed`,`cancelled`].includes(z.status))return;let e=!1,t=window.setTimeout(()=>{Bg(z.setup_id).then(async t=>{e||(Ee(t),t.verification_url&&Me.current!==t.verification_url&&(Me.current=t.verification_url,je.current&&!je.current.closed&&(je.current.location.href=t.verification_url)),t.status===`ready`&&(await Pe(),S(t.app_ref),ue({}),xe(!1)),t.status===`failed`&&Ae(t.error??o(`lark.error.appCreate`)))}).catch(t=>{e||Ae(Ob(t,o(`lark.error.setupPoll`),o))})},650);return()=>{e=!0,window.clearTimeout(t)}},[be,z]);let H=n.find(e=>e.goalId===C),Fe=H?.agentId?[{agentId:H.agentId,label:H.agentLabel??H.agentId}]:[],Ie=H?.agentLanes?.length?H.agentLanes:Fe,Le=Ie.some(e=>e.agentId===L),Re=[];se?Re=Ie.map(e=>({agentId:e.agentId,appRef:le[e.agentId]??x})):Le&&(Re=[{agentId:L,appRef:x}]);let ze=Re.map(e=>e.agentId),Be=!!ge||Re.length>0&&Re.every(e=>l.some(t=>t.app_ref===e.appRef&&t.reply_ready)),Ve=o(`lark.connect`);me?Ve=o(`lark.saveConnection`):se&&(Ve=o(`lark.connectAllAgentsAction`,{count:ze.length}));let He=l.find(e=>e.app_ref===x),Ue=D.find(e=>e.chat_id===ee),We=(0,B.useMemo)(()=>{let e=_.trim().toLocaleLowerCase();return e?d.filter(t=>[t.app_label,t.chat_name,t.goal_title,t.topic_name].some(t=>t.toLocaleLowerCase().includes(e))):d},[d,_]),Ge=(0,B.useMemo)(()=>d.filter(e=>Eb(e,o).state===`unverified`).length,[d,o]);function Ke(e){let i=e??n.find(e=>e.goalId===r)??n[0];he(null),_e(null),F(e||t?`goal`:`manager`),S(l.some(e=>e.app_ref===x)?x:l.find(e=>e.reply_ready)?.app_ref??l[0]?.app_ref??``),te(``),w(i?.goalId??``),oe(i?.agentId??``),ce(!1),ue({}),N(`addressed_only`),ie(`async_inbox`),ae(`topic_reply`),E(``),pe(null),b(!0)}function qe(e){he(e.goal_id),_e(e),F(e.conversation_kind??`goal`),S(e.app_ref),w(e.goal_id);let t=n.find(t=>t.goalId===e.goal_id),r=t?.agentLanes?.length?t.agentLanes:t?.agentId?[{agentId:t.agentId}]:[];oe(e.agent_id??(r.length===1?r[0].agentId:``)),ce(!1),ue({}),N(e.capture_scope),ie(e.ingress_mode===`direct_session`?`async_inbox`:e.ingress_mode),ae(e.reply_mode),E(e.chat_name),pe(null),b(!0)}function Je(){Ee(null),Ae(null),Me.current=null,xe(!0)}async function Ye(){if(!(De||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Se))){Oe(!0),Ae(null),Me.current=null,je.current=window.open(window.location.href,`_blank`);try{let e=await zg({appRef:Se,brand:we});Ee(e)}catch(e){je.current?.close(),Ae(Ob(e,o(`lark.error.setupStart`),o))}finally{Oe(!1)}}}async function Xe(){let e=z;if(xe(!1),je.current?.close(),e&&![`ready`,`failed`,`cancelled`].includes(e.status))try{await Vg(e.setup_id)}catch{}}async function Ze(){if(!(!x||!C||!ge&&!Ue||P===`goal`&&ze.length===0||de)){R(!0),pe(null);try{let e={...P===`manager`?{...ge?{connectionId:ge.connection_id}:{appRef:x,chatId:Ue.chat_id,chatName:Ue.chat_name}}:ge?{connectionId:ge.connection_id,agentId:L}:{agentBindings:Re,chatId:Ue.chat_id,chatName:Ue.chat_name},conversationKind:P,captureScope:P===`manager`?`addressed_only`:M,goalId:C,incomingMode:M===`configured_chat_all`?`all`:`mentions`,ingressMode:P===`manager`?`session_queue`:re,replyMode:I},t=await qg({...e,execute:!1});if(!t.ok)throw new Th(t.public_summary??t.blocker??o(`lark.error.bindPreview`),{error_code:t.blocker??`provider_api_failed`});let n=await qg({...e,execute:!0});if(!n.ok)throw new Th(n.public_summary??n.blocker??o(`lark.error.bind`),{error_code:n.blocker??`provider_api_failed`});b(!1),await Pe(),i?.()}catch(e){pe(Ob(e,o(`lark.error.bind`),o))}finally{R(!1)}}}async function Qe(e,t){if(ve!==t){ye(t);return}try{await Jg(e,t),ye(null),await Pe(),i?.()}catch(e){g(Ob(e,o(`lark.error.disconnect`),o))}}return(0,V.jsxs)(`section`,{className:`personal-lark-settings${e?` is-embedded`:``}`,"aria-label":o(`lark.configuration`),children:[e?null:(0,V.jsxs)(`header`,{className:`personal-lark-header`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:o(`settings.goalConnections`)}),(0,V.jsx)(`h1`,{children:`Lark`})]}),(0,V.jsx)(`button`,{"aria-label":o(`lark.closeSettings`),className:`personal-icon-button`,onClick:a,type:`button`,children:(0,V.jsx)($m,{size:18})})]}),(0,V.jsxs)(`nav`,{className:`personal-lark-tabs`,"aria-label":o(`lark.management`),children:[(0,V.jsxs)(`button`,{"aria-current":s===`apps`?`page`:void 0,onClick:()=>c(`apps`),type:`button`,children:[o(`lark.apps`),` `,(0,V.jsx)(`span`,{children:p?`…`:l.length})]}),(0,V.jsxs)(`button`,{"aria-current":s===`connections`?`page`:void 0,onClick:()=>c(`connections`),type:`button`,children:[o(`lark.connections`),` `,(0,V.jsx)(`span`,{children:p?`…`:d.length})]})]}),h?(0,V.jsx)(`p`,{className:`personal-notification-error`,children:h}):null,p?(0,V.jsxs)(`div`,{className:`personal-lark-loading`,children:[(0,V.jsx)(Cm,{className:`is-spinning`,size:18}),o(`lark.loading`)]}):null,!p&&s===`apps`?(0,V.jsxs)(`div`,{className:`personal-lark-apps`,children:[(0,V.jsxs)(`div`,{className:`personal-lark-app-toolbar`,children:[(0,V.jsx)(`span`,{children:o(`lark.reusableApps`,{count:l.length})}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:Je,type:`button`,children:[(0,V.jsx)(Pm,{size:16}),o(`lark.newApp`)]})]}),(0,V.jsxs)(`div`,{className:`personal-lark-app-grid`,children:[l.map(e=>(0,V.jsxs)(`article`,{className:`personal-lark-app-card`,children:[(0,V.jsx)(`span`,{className:`personal-lark-app-avatar`,children:(0,V.jsx)(Zp,{size:19})}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsxs)(`small`,{children:[e.brand,` · lark-cli profile`]})]}),(0,V.jsx)(`em`,{className:e.reply_ready?`is-ready`:`is-off`,children:e.reply_ready?o(`lark.autoReplyReady`):e.ready?o(`lark.needsMessagePermissions`):o(`lark.needsSetup`)}),(0,V.jsxs)(`p`,{children:[o(`lark.goalConnections`,{count:d.filter(t=>t.app_ref===e.app_ref).length}),e.ready&&!e.reply_ready?` · ${o(`lark.autoReplyUnavailable`)}`:``]})]},e.app_ref)),l.length===0?(0,V.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noProfiles`)}):null]})]}):null,!p&&s===`connections`?(0,V.jsxs)(`div`,{className:`personal-lark-connections`,children:[Ge>0?(0,V.jsxs)(`p`,{className:`personal-lark-route-readiness`,role:`status`,children:[(0,V.jsx)(Dm,{size:15}),o(`lark.routesUnverified`,{count:Ge})]}):null,(0,V.jsxs)(`div`,{className:`personal-lark-toolbar`,children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(zm,{size:16}),(0,V.jsx)(`input`,{"aria-label":o(`lark.searchConnections`),onChange:e=>v(e.target.value),placeholder:o(`lark.searchPlaceholder`),type:`search`,value:_})]}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:l.length===0||n.length===0,onClick:()=>Ke(),type:`button`,children:[(0,V.jsx)(Pm,{size:16}),o(`lark.connectApp`)]})]}),(0,V.jsxs)(`div`,{className:`personal-lark-table`,role:`table`,"aria-label":o(`lark.goalTopicConnections`),children:[(0,V.jsxs)(`div`,{className:`personal-lark-table-head`,role:`row`,children:[(0,V.jsx)(`span`,{children:o(`lark.connection`)}),(0,V.jsx)(`span`,{children:o(`common.goal`)}),(0,V.jsx)(`span`,{children:o(`lark.capture`)}),(0,V.jsx)(`span`,{children:o(`lark.processing`)}),(0,V.jsx)(`span`,{children:o(`common.actions`)})]}),We.map(e=>{let t=Eb(e,o);return(0,V.jsxs)(`div`,{className:`personal-lark-table-row`,role:`row`,children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.chat_name}),(0,V.jsxs)(`small`,{children:[e.app_label,` · `,t.label]}),(0,V.jsx)(`small`,{children:t.detail}),t.state===`unverified`?(0,V.jsxs)(`a`,{href:`https://open.feishu.cn/document/server-docs/im-v1/message/events/receive?lang=zh-CN`,rel:`noreferrer`,target:`_blank`,children:[(0,V.jsx)(fm,{size:12}),o(`lark.openEventSettings`)]}):null,Db(e)?(0,V.jsxs)(`a`,{href:Db(e)??void 0,rel:`noreferrer`,target:`_blank`,children:[(0,V.jsx)(fm,{size:12}),o(`lark.historyPermission`)]}):null]}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.goal_title}),(0,V.jsxs)(`small`,{children:[`# `,e.topic_name]})]}),(0,V.jsx)(`span`,{children:e.capture_scope===`addressed_only`?o(`lark.mentionsOnly`):o(`lark.allTopicMessages`)}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.conversation_kind===`manager`?o(`lark.managerConversation`):Tb(e.ingress_mode,o).label}),(0,V.jsx)(`small`,{children:e.conversation_kind===`manager`?o(`lark.managerConversationDescription`):e.agent_id??Tb(e.ingress_mode,o).detail})]}),(0,V.jsxs)(`span`,{className:`personal-lark-row-actions`,children:[(0,V.jsx)(`button`,{"aria-label":o(`lark.settingsConfigure`,{goal:e.goal_title}),onClick:()=>qe(e),type:`button`,children:(0,V.jsx)(Um,{size:15})}),(0,V.jsxs)(`button`,{"aria-label":o(`lark.settingsDisconnect`,{goal:e.goal_title}),className:ve===e.connection_id?`is-confirm`:``,onClick:()=>void Qe(e.goal_id,e.connection_id),type:`button`,children:[(0,V.jsx)(Qm,{size:15}),ve===e.connection_id?o(`common.confirm`):null]})]})]},e.connection_id)}),We.length===0?(0,V.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noConnections`)}):null]})]}):null,y?(0,V.jsx)(`div`,{className:`personal-lark-modal-backdrop`,role:`presentation`,children:(0,V.jsxs)(`section`,{"aria-labelledby":`connect-lark-title`,"aria-modal":`true`,className:`personal-lark-modal`,role:`dialog`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:`Goal Topic connection`}),(0,V.jsx)(`h2`,{id:`connect-lark-title`,children:o(me?`lark.editConnection`:`lark.connectApp`)})]}),(0,V.jsx)(`button`,{"aria-label":o(`lark.closeConnection`),onClick:()=>b(!1),type:`button`,children:(0,V.jsx)($m,{size:18})})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.conversationKind`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.conversationKind`),disabled:!!ge,value:P,onChange:e=>F(e.target.value),children:[(0,V.jsx)(`option`,{value:`manager`,children:o(`lark.managerConversation`)}),(0,V.jsx)(`option`,{value:`goal`,children:o(`lark.workerConversation`)})]})]}),P===`manager`?(0,V.jsx)(`p`,{children:o(`lark.managerConversationDescription`)}):null,ge?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,V.jsx)(`div`,{children:ge.app_label})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,V.jsx)(`div`,{children:ge.chat_name})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,V.jsx)(`div`,{children:ge.goal_title})]}),(0,V.jsx)(`small`,{children:o(`lark.editPreservesIdentity`)})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,V.jsx)(`select`,{"aria-label":o(`lark.appProfile`),disabled:p,onChange:e=>{e.target.value===`__register__`?Je():(S(e.target.value),ue({}))},value:x,children:p?(0,V.jsx)(`option`,{value:``,children:o(`lark.appLoading`)}):(0,V.jsxs)(V.Fragment,{children:[l.map(e=>(0,V.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref)),(0,V.jsx)(`option`,{value:`__register__`,children:o(`lark.registerAnother`)})]})}),(0,V.jsx)(`small`,{children:o(`lark.defaultAgentAppDescription`)})]}),He?.ready&&!He.reply_ready?(0,V.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.appPermissions`)}):null,(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,V.jsx)(`input`,{"aria-label":o(`lark.groupSearch`),onChange:e=>E(e.target.value),placeholder:o(`lark.groupSearch`),type:`search`,value:T}),ne?(0,V.jsxs)(`div`,{className:`personal-lark-group-state`,role:`status`,children:[(0,V.jsx)(Cm,{className:`is-spinning`,size:15}),o(`lark.groupLoading`)]}):null,!ne&&A?(0,V.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:A}):null,!ne&&!A&&D.length===0?(0,V.jsx)(`div`,{className:`personal-lark-group-state`,role:`status`,children:o(`lark.groupEmpty`)}):null,!ne&&!A&&D.length>0?(0,V.jsx)(`select`,{"aria-label":o(`lark.groupChat`),onChange:e=>te(e.target.value),value:ee,children:D.map(e=>(0,V.jsx)(`option`,{value:e.chat_id,children:e.chat_name},e.chat_id))}):null]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,V.jsx)(`select`,{"aria-label":o(`lark.bindGoal`),onChange:e=>{let t=e.target.value;w(t),oe(n.find(e=>e.goalId===t)?.agentId??``),ue({})},value:C,children:n.map(e=>(0,V.jsx)(`option`,{value:e.goalId,children:e.title},e.goalId))})]})]}),(0,V.jsxs)(`label`,{className:`personal-lark-check`,children:[(0,V.jsx)(`input`,{checked:!0,readOnly:!0,type:`checkbox`}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:o(`lark.createAutomatically`)}),(0,V.jsx)(`small`,{children:o(`lark.createAutomaticallyDescription`)})]})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.topicPreview`)}),(0,V.jsxs)(`div`,{className:`personal-lark-topic-preview`,children:[(0,V.jsx)(Dm,{size:15}),`# `,H?.title??H?.goalId??`Goal`]})]}),P===`goal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.captureScope`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.captureScope`),disabled:ge?.ingress_mode===`direct_session`,onChange:e=>N(e.target.value),value:M,children:[(0,V.jsx)(`option`,{value:`addressed_only`,children:o(`lark.captureAddressed`)}),(0,V.jsx)(`option`,{value:`configured_chat_all`,children:o(`lark.captureAll`)})]}),(0,V.jsx)(`small`,{children:o(`lark.captureScopeDescription`)})]}),(0,V.jsxs)(`fieldset`,{"aria-label":o(`lark.agentIngress`),className:`personal-lark-ingress`,children:[(0,V.jsx)(`legend`,{children:o(`lark.agentIngress`)}),(0,V.jsx)(`div`,{children:[`live_steering`,`session_queue`,`async_inbox`].map(e=>{let t=Tb(e,o);return(0,V.jsxs)(`label`,{className:re===e?`is-active`:``,children:[(0,V.jsx)(`input`,{"aria-label":t.label,checked:re===e,name:`lark-agent-ingress`,onChange:()=>ie(e),type:`radio`,value:e}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:t.label}),(0,V.jsx)(`small`,{children:t.detail})]})]},e)})})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.targetAgent`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.targetAgent`),disabled:!!ge?.agent_id,onChange:e=>oe(e.target.value),value:L,children:[Le?null:(0,V.jsx)(`option`,{disabled:!0,value:L,children:L?o(`lark.agentUnavailable`,{agent:L}):o(`lark.noAgentConfigured`)}),Ie.map(e=>(0,V.jsx)(`option`,{value:e.agentId,children:e.label===e.agentId?e.agentId:`${e.label} · ${e.agentId}`},e.agentId))]}),(0,V.jsx)(`small`,{children:o(`lark.targetAgentDescription`)})]}),!me&&Ie.length>1?(0,V.jsxs)(`label`,{"aria-label":o(`lark.connectAllAgents`),className:`personal-lark-check`,children:[(0,V.jsx)(`input`,{checked:se,onChange:e=>ce(e.target.checked),type:`checkbox`}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:o(`lark.connectAllAgents`)}),(0,V.jsx)(`small`,{children:o(`lark.connectAllAgentsDescription`,{count:Ie.length})})]})]}):null,!me&&se&&Ie.length>1?(0,V.jsxs)(`fieldset`,{"aria-label":o(`lark.agentApps`),className:`personal-lark-agent-apps`,children:[(0,V.jsx)(`legend`,{children:o(`lark.agentApps`)}),(0,V.jsx)(`small`,{children:o(`lark.agentAppsDescription`)}),(0,V.jsx)(`div`,{children:Ie.map(e=>(0,V.jsxs)(`label`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsx)(`small`,{children:e.agentId})]}),(0,V.jsx)(`select`,{"aria-label":o(`lark.agentAppSelection`,{agent:e.label}),onChange:t=>ue(n=>({...n,[e.agentId]:t.target.value})),value:le[e.agentId]??x,children:l.map(e=>(0,V.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref))})]},e.agentId))})]}):null,se&&Re.length>0&&!Be?(0,V.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.agentAppPermissions`)}):null,ze.length===0?(0,V.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:o(`lark.selectRegisteredAgent`)}):null]}):null,(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.replyMode`)}),(0,V.jsx)(`select`,{"aria-label":o(`lark.replyMode`),onChange:e=>ae(e.target.value),value:I,children:(0,V.jsx)(`option`,{value:`topic_reply`,children:o(`lark.topicReply`)})}),(0,V.jsx)(`small`,{children:o(`lark.replyModeDescription`)})]}),(0,V.jsxs)(`p`,{className:`personal-lark-cardinality`,children:[(0,V.jsx)(em,{size:15}),o(`lark.cardinality`)]}),fe?(0,V.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:fe}):null,(0,V.jsxs)(`footer`,{children:[(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>b(!1),type:`button`,children:o(`lark.cancel`)}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:p||!x||!ge&&(!He?.reply_ready||!ee)||P===`goal`&&(!Be||ze.length===0)||!C||de,onClick:()=>void Ze(),type:`button`,children:[de?(0,V.jsx)(Cm,{className:`is-spinning`,size:15}):null,Ve]})]})]})}):null,be?(0,V.jsx)(`div`,{className:`personal-lark-modal-backdrop is-setup`,role:`presentation`,children:(0,V.jsxs)(`section`,{"aria-labelledby":`new-lark-app-title`,"aria-modal":`true`,className:`personal-lark-modal personal-lark-setup-modal`,role:`dialog`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:o(`lark.reusableWorkspaceApp`)}),(0,V.jsx)(`h2`,{id:`new-lark-app-title`,children:o(`lark.newApp`)})]}),(0,V.jsx)(`button`,{"aria-label":o(`lark.closeCreate`),onClick:()=>void Xe(),type:`button`,children:(0,V.jsx)($m,{size:18})})]}),z?(0,V.jsxs)(`div`,{className:`personal-lark-setup-progress`,children:[(0,V.jsx)(`span`,{className:`personal-lark-setup-icon is-${z.status}`,children:z.status===`ready`?(0,V.jsx)(em,{size:22}):(0,V.jsx)(Cm,{className:z.status===`failed`?``:`is-spinning`,size:22})}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:z.status===`ready`?o(`lark.appCreated`):z.status===`failed`?o(`lark.appCreateFailed`):o(`lark.waitingFeishu`)}),(0,V.jsx)(`p`,{children:z.status===`waiting_for_feishu`?o(`lark.waitingFeishuDescription`):z.status===`starting`?o(`lark.waitingLink`):z.error})]}),z.verification_url?(0,V.jsxs)(`a`,{href:z.verification_url,rel:`noreferrer`,target:`_blank`,children:[(0,V.jsx)(fm,{size:15}),o(`lark.reopenFeishu`)]}):null]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{className:`personal-lark-setup-copy`,children:o(`lark.setupCopy`)}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.profileName`)}),(0,V.jsx)(`input`,{"aria-label":o(`lark.profileName`),autoComplete:`off`,onChange:e=>Ce(e.target.value),placeholder:`loopx-workspace-bot`,value:Se})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.region`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.region`),onChange:e=>Te(e.target.value),value:we,children:[(0,V.jsx)(`option`,{value:`feishu`,children:`Feishu`}),(0,V.jsx)(`option`,{value:`lark`,children:`Lark`})]})]}),Se&&!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Se)?(0,V.jsx)(`p`,{className:`personal-notification-error`,children:o(`lark.profileValidation`)}):null]}),ke?(0,V.jsx)(`p`,{className:`personal-notification-error`,children:ke}):null,(0,V.jsxs)(`footer`,{children:[(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void Xe(),type:`button`,children:o(`lark.cancel`)}),z?null:(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:De||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Se),onClick:()=>void Ye(),type:`button`,children:[De?(0,V.jsx)(Cm,{className:`is-spinning`,size:15}):(0,V.jsx)(fm,{size:15}),o(`lark.continueFeishu`)]})]})]})}):null]})}function Ab(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function jb(e,t,n){let r=Ab(t),i=Ab(n);return Object.fromEntries(e.fields.flatMap(({key:e,nullable:t})=>{let n=r[e],a=i[e];return Object.hasOwn(r,e)&&(n!=null||t&&n===null)?[[e,n]]:Object.hasOwn(i,e)&&a!=null?[[e,a]]:[]}))}function Mb(e,t){let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=new Set(e.fields.map(e=>e.key));return Object.keys(n).some(e=>!r.has(e))?null:n}function Nb(e,t,n){let r={...e,[t]:n},i=e.schedule;return t===`timezone`&&i&&typeof i==`object`&&`schema_version`in i&&i.schema_version===`periodic_report_schedule_v0`&&(r.schedule={...i,timezone:n}),r}function Pb({id:e,value:t,timezone:n,onChange:r}){let{locale:i}=qi(),a=i===`zh-CN`,o=t&&typeof t==`object`&&!Array.isArray(t)?t:null,s=String(o?.rrule??``).split(`;`).map(e=>e.split(`=`)),c=Object.fromEntries(s.filter(e=>e.length===2)),l=[`MO`,`TU`,`WE`,`TH`,`FR`,`SA`,`SU`],u=(e,t)=>e!==void 0&&/^\d+$/.test(e)&&Number(e)<=t,d=!o||o.schema_version===`periodic_report_schedule_v0`&&[`DAILY`,`WEEKLY`].includes(c.FREQ)&&o.timezone===n&&s.every(e=>e.length===2&&[`FREQ`,`BYDAY`,`BYHOUR`,`BYMINUTE`,`INTERVAL`].includes(e[0]))&&new Set(s.map(([e])=>e)).size===s.length&&u(c.BYHOUR,23)&&u(c.BYMINUTE??`0`,59)&&(c.FREQ===`WEEKLY`?l.includes(c.BYDAY):!c.BYDAY)&&(!c.INTERVAL||c.INTERVAL===`1`),f=a?[`星期一`,`星期二`,`星期三`,`星期四`,`星期五`,`星期六`,`星期日`]:[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`];function p(e){let t={FREQ:`WEEKLY`,BYDAY:`MO`,BYHOUR:`9`,BYMINUTE:`0`,...c,...e};r?.({schema_version:`periodic_report_schedule_v0`,schedule_id:o?.schedule_id??`report-schedule`,timezone:n,rrule:[`FREQ=${t.FREQ}`,...t.FREQ===`WEEKLY`?[`BYDAY=${t.BYDAY}`]:[],`BYHOUR=${t.BYHOUR}`,`BYMINUTE=${t.BYMINUTE}`].join(`;`)})}return(0,V.jsxs)(`div`,{className:`personal-report-schedule`,children:[(0,V.jsxs)(`label`,{className:`is-boolean`,htmlFor:e,children:[(0,V.jsx)(`span`,{children:a?`按日历汇报`:`Calendar reports`}),(0,V.jsx)(`input`,{id:e,type:`checkbox`,role:`switch`,checked:!!o,disabled:!r,onChange:e=>e.target.checked?p({}):r?.(null)})]}),o?(0,V.jsxs)(V.Fragment,{children:[d?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{htmlFor:`${e}-frequency`,children:[(0,V.jsx)(`span`,{children:a?`频率`:`Frequency`}),(0,V.jsxs)(`select`,{id:`${e}-frequency`,value:c.FREQ,disabled:!r,onChange:e=>p({FREQ:e.target.value}),children:[(0,V.jsx)(`option`,{value:`DAILY`,children:a?`每天`:`Daily`}),(0,V.jsx)(`option`,{value:`WEEKLY`,children:a?`每周`:`Weekly`})]})]}),c.FREQ===`WEEKLY`&&(0,V.jsxs)(`label`,{htmlFor:`${e}-day`,children:[(0,V.jsx)(`span`,{children:a?`星期`:`Weekday`}),(0,V.jsx)(`select`,{id:`${e}-day`,value:c.BYDAY,disabled:!r,onChange:e=>p({BYDAY:e.target.value}),children:l.map((e,t)=>(0,V.jsx)(`option`,{value:e,children:f[t]},e))})]}),(0,V.jsxs)(`label`,{htmlFor:`${e}-time`,children:[(0,V.jsxs)(`span`,{children:[a?`当地时间`:`Local time`,` (`,n,`)`]}),(0,V.jsx)(`input`,{id:`${e}-time`,type:`time`,required:!0,disabled:!r,value:`${(c.BYHOUR??`9`).padStart(2,`0`)}:${(c.BYMINUTE??`0`).padStart(2,`0`)}`,onChange:e=>{if(!/^\d{2}:\d{2}$/.test(e.target.value))return;let[t,n]=e.target.value.split(`:`);p({BYHOUR:t,BYMINUTE:n})}})]})]}):(0,V.jsx)(`p`,{role:`alert`,children:a?`此计划需在 JSON 模式中编辑;当前内容已保留。`:`Edit this schedule in JSON mode; its current value is preserved.`}),(0,V.jsx)(`p`,{children:a?`由现有唤醒检查到期计划;实际送达以回执为准。`:`Existing wakes check the schedule; delivery is confirmed by its receipt.`})]}):(0,V.jsx)(`p`,{children:a?`未设置日历计划;保持阶段结束时汇报。`:`No calendar schedule; report at validated stage boundaries.`})]})}function Fb({copy:e,field:t,id:n,onChange:r,value:i,timezone:a}){let o=e[t.key]?.label??t.label,s=!r;if(t.input_kind===`periodic_report_schedule`)return(0,V.jsx)(Pb,{id:n,value:i,timezone:a,onChange:r?e=>r(t.key,e):void 0});if(t.input_kind===`boolean`)return(0,V.jsxs)(`label`,{className:`is-boolean`,htmlFor:n,children:[(0,V.jsx)(`span`,{children:o}),(0,V.jsx)(`input`,{checked:i===!0,id:n,onChange:r?e=>r(t.key,e.target.checked):void 0,readOnly:s,role:`switch`,type:`checkbox`})]});if(t.input_kind===`select`)return(0,V.jsxs)(`label`,{htmlFor:n,children:[(0,V.jsx)(`span`,{children:o}),(0,V.jsxs)(`select`,{id:n,onChange:r?e=>r(t.key,e.target.value):void 0,value:typeof i==`string`?i:``,children:[(0,V.jsx)(`option`,{value:``}),(t.options??[]).map(e=>(0,V.jsx)(`option`,{value:e,children:e},e))]})]});if(t.input_kind===`string_list`)return(0,V.jsxs)(`label`,{htmlFor:n,children:[(0,V.jsx)(`span`,{children:o}),(0,V.jsx)(`textarea`,{id:n,onChange:r?e=>r(t.key,e.target.value.split(/\r?\n/u).filter(Boolean)):void 0,readOnly:s,rows:4,value:Array.isArray(i)?i.join(` ->>>>>>>> b985710a0 (test(dashboard): keep typed resume smoke deterministic):loopx/web/chat/assets/index-BkVzp3yz.js -`):``})]});let c=t.input_kind===`number`;return(0,V.jsxs)(`label`,{htmlFor:n,children:[(0,V.jsx)(`span`,{children:o}),(0,V.jsx)(`input`,{id:n,max:t.maximum,min:t.minimum,onChange:r?e=>r(t.key,c?Number(e.target.value):e.target.value):void 0,readOnly:s,required:t.required,type:c?`number`:`text`,value:typeof i==`number`||typeof i==`string`?i:``})]})}function Ib({copy:e={},disabled:t=!1,editor:n,enabledAction:r,omitKeys:i=[],onChange:a,value:o}){let s=(0,B.useId)(),c=new Set(i);return(0,V.jsx)(`fieldset`,{className:`personal-capability-fields`,disabled:t,children:n.fields.filter(e=>!c.has(e.key)).map(t=>{let n=(0,V.jsx)(Fb,{copy:e,field:t,id:`${s}-${t.key.replace(/[^a-z0-9_-]/gi,`-`)}`,onChange:a,value:o[t.key],timezone:String(o.timezone??`UTC`)},t.key);return t.key===`enabled`&&t.input_kind===`boolean`?(0,V.jsxs)(`div`,{className:`personal-capability-enabled-row`,children:[n,r]},t.key):n})})}var Lb={en:{todo_replan_cadence:{displayName:`Goal review cadence`,description:`Configures the Goal review cadence.`},change_quality_qualification:{displayName:`Change quality qualification`,description:`Prepares a provider-neutral review packet, allows at most one policy-authorized safe-fix pass, and can require an exact-diff receipt.`},explore_graph:{displayName:`Explore Graph`,description:`Organizes bounded exploration as a typed evidence graph so branches, findings, and synthesis remain inspectable.`},explore_harness:{displayName:`Explore Harness`,description:`Selects a capability-owned planning and research harness profile for bounded multi-step exploration.`},lark_event_inbox:{displayName:`Lark event inbox`,description:`Receives provider events through a local-private inbox binding before LoopX projects them into governed work.`,readOnlyReason:`This capability requires a local-private inbox binding. Manage it in Lark settings or through the capability CLI.`},lark_kanban_heartbeat_sync:{displayName:`Lark Kanban heartbeat sync`,description:`Synchronizes accepted LoopX work state to the configured Lark Kanban heartbeat surface.`},local_authority_shadow:{displayName:`Local authority shadow`,description:`Observes post-commit Todo and task-lease state through the shared authority contract without taking write authority.`},multi_subagent:{displayName:`Adaptive child capacity`,description:`Sets bounded child-agent capacity and the public-safe responsibility domains in which parallel work may be delegated.`},peer_task_coordination:{displayName:`Registered-peer task coordination`,description:`Routes explicitly scoped peer-owned work to one registered coordinator without granting cross-owner mutation authority.`},periodic_report:{displayName:`Periodic reports`,description:`Turns validated Goal stage progress into a frozen report and automatically delivers it through the configured Goal Channel with exact readback.`},reward_memory:{displayName:`Reward Memory experiment`,description:`Configures a reviewed local-private provider binding for Goal-scoped Agent recall and evidence-backed outcome learning.`}},"zh-CN":{todo_replan_cadence:{displayName:`Goal 复核周期`,description:`配置 Goal 的复核周期。`},change_quality_qualification:{displayName:`变更质量验证`,description:`生成与 Provider 无关的审阅包,最多允许一次策略授权的安全修复,并可要求精确 diff 回执。`},explore_graph:{displayName:`探索图谱`,description:`把有界探索组织为 typed 证据图,让探索分支、发现与综合结论都可检查、可追溯。`},explore_harness:{displayName:`探索 Harness`,description:`为有界的多步探索选择由能力负责的规划与研究 Harness profile。`},lark_event_inbox:{displayName:`飞书事件收件箱`,description:`通过本机私有收件箱接收 Provider 事件,再由 LoopX 将其投影为受治理的工作。`,readOnlyReason:`此能力依赖本机私有的收件箱绑定,请在飞书设置或 capability CLI 中管理。`},lark_kanban_heartbeat_sync:{displayName:`飞书看板心跳同步`,description:`把 LoopX 已接受的工作状态同步到配置好的飞书看板心跳界面。`},local_authority_shadow:{displayName:`本地 Authority 影子观测`,description:`通过共享 Authority contract 观测提交后的 Todo 与 task lease 状态,但不取得写入权。`},multi_subagent:{displayName:`自适应子 Agent 容量`,description:`限定子 Agent 容量与可公开的职责域,只有落在这些边界内的工作才能并行委派。`},peer_task_coordination:{displayName:`已注册 Peer 任务协调`,description:`把明确限定的 Peer 工作路由给一个已注册协调者,不授予跨 Owner 修改权限。`},periodic_report:{displayName:`周期报告`,description:`把经过验证的 Goal 阶段进展整理为冻结报告,并通过配置的 Goal Channel 自动发送和精确回读。`},reward_memory:{displayName:`Reward Memory 实验`,description:`为 Goal 内 Agent 的召回与证据化结果学习配置经过审阅的本机私有 Provider 绑定。`}}},Rb={en:{completed_todos:{label:`Completed Todos between Goal reviews`,description:`Machine default or explicit Goal override, from 1 to 5.`},allowed_domains:{label:`Allowed responsibility domains`,description:`Enter one bounded, public-safe domain per line.`},coordinator_agent_id:{label:`Coordinator Agent`,description:`Use an already registered Agent id; leave blank to disable coordination.`},enabled:{label:`Enabled`},model:{label:`Child model`,description:`For example gpt-5.6-luna. Blank clears the child model preference.`},reasoning_effort:{label:`Child reasoning effort`,description:`For example max; the host must support this model and effort.`},max_children:{label:`Maximum children`,description:`Hard upper bound for concurrently delegated child work.`},profile:{label:`Planner profile`,description:`Select one registered Explore Harness profile.`},profile_preset:{label:`Report profile`,description:`Capability-owned report profile, such as weekly-progress.`},route_ref:{label:`Goal Channel route`,description:`Public route alias only; credentials and provider identifiers stay outside this form.`},safe_fix:{label:`Allow one bounded safe-fix pass`},strict_receipt:{label:`Require an exact-diff receipt`},timezone:{label:`Timezone`,description:`Use an IANA timezone, for example Asia/Shanghai.`},schedule:{label:`Calendar reports`,description:`Optional daily or weekly reports; no schedule preserves stage-only delivery.`},config_path:{label:`Local-private configuration path`,description:`Repo-relative ignored JSON under .loopx/config/. Leave blank to retain the current binding; the path is never returned.`},enabled_agents:{label:`Enabled Goal Agents`,description:`Enter one registered Goal-local Agent id per line. A private binding currently accepts exactly one Agent.`}},"zh-CN":{completed_todos:{label:`两次 Goal 复核间的已完成 Todo 数`,description:`可设置 1–5;机器默认值可被 Goal 显式覆盖。`},allowed_domains:{label:`允许的职责域`,description:`每行填写一个有边界、可公开的职责域。`},coordinator_agent_id:{label:`协调 Agent`,description:`填写一个已经注册的 Agent ID;留空表示关闭协调。`},enabled:{label:`启用`},model:{label:`子 Agent 模型`,description:`例如 gpt-5.6-luna;留空清除模型偏好。`},reasoning_effort:{label:`子 Agent 推理档位`,description:`例如 max;宿主须支持所选模型与档位。`},max_children:{label:`最大子 Agent 数`,description:`可同时委派的子任务硬上限。`},profile:{label:`规划 Profile`,description:`选择一个已注册的 Explore Harness profile。`},profile_preset:{label:`报告 Profile`,description:`由该能力管理的报告 profile,例如 weekly-progress。`},route_ref:{label:`Goal Channel 路由`,description:`只填写公开 route alias;凭据与 Provider 标识不会进入此表单。`},safe_fix:{label:`允许一次有界安全修复`},strict_receipt:{label:`要求精确 diff 回执`},timezone:{label:`时区`,description:`使用 IANA 时区,例如 Asia/Shanghai。`},schedule:{label:`日历汇报`,description:`可选每日或每周计划;未设置时保持阶段结束汇报。`},config_path:{label:`本机私有配置路径`,description:`填写 .loopx/config/ 下、相对仓库且被忽略的 JSON;留空保留当前绑定,路径不会被回传。`},enabled_agents:{label:`已启用的 Goal Agent`,description:`每行填写一个已注册的 Goal 内 Agent ID;私有绑定当前只接受一个 Agent。`}}};function zb(e,t){let n=Lb[t][e.capability_id];return n?{...e,display_name:n.displayName,description:n.description,configuration_editor:{...e.configuration_editor,...n.readOnlyReason?{read_only_reason:n.readOnlyReason}:{}}}:e}function Bb(e){return Rb[e]}Object.freeze(Object.keys(Lb.en).sort());function Vb(e,t){return e.available_scopes.includes(t)&&(t!==`machine`||!!e.machine_namespace)&&e.configuration_editor.editable&&e.configuration_editor.writable_scopes.includes(t)}function Hb({values:e,t}){return(0,V.jsxs)(`details`,{className:`personal-capability-raw-values`,children:[(0,V.jsx)(`summary`,{children:t(`capabilities.rawJson`)}),(0,V.jsx)(`div`,{className:`personal-capability-value-grid`,children:e.map(({label:e,value:t})=>(0,V.jsxs)(`section`,{children:[(0,V.jsx)(`strong`,{children:e}),(0,V.jsx)(`pre`,{children:t?JSON.stringify(t,null,2):`—`})]},e))})]})}function Ub({source:e,t}){return e?(0,V.jsxs)(`p`,{className:`personal-capability-effective-source`,children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:15}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:t(`capabilities.effectiveSource`)}),t(`capabilities.source.${e}`)]})]}):null}function Wb({available:e,description:t,t:n}){return e?null:(0,V.jsxs)(`section`,{className:`personal-capability-editor-status is-read-only`,children:[(0,V.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:n(`capabilities.readOnly`)}),(0,V.jsx)(`p`,{children:t})]})]})}function Gb(e){return e.availability?.includes(`experimental`)?4:e.capability_id===`multi_subagent`?3:e.configuration_editor.writable_scopes.length===0||e.availability===`supported_explicit_opt_in`?2:e.availability===`supported_explicit_override`?0:1}function Kb(e,t){return[...e].sort((e,n)=>{let r=Gb(e)-Gb(n);if(r!==0)return r;let i=zb(e,t),a=zb(n,t);return i.display_name.localeCompare(a.display_name,t)||e.capability_id.localeCompare(n.capability_id)})}function qb({capabilities:e,locale:t,onSelect:n,scope:r,selectedCapabilityId:i,t:a}){return(0,V.jsx)(`nav`,{"aria-label":a(r===`goal`?`capabilities.catalog`:`machine.capabilityCatalog`),className:`personal-capability-list`,tabIndex:0,children:Kb(e,t).map(e=>{let o=zb(e,t);return(0,V.jsxs)(`button`,{"aria-current":i===o.capability_id?`page`:void 0,onClick:()=>n(o.capability_id),type:`button`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:o.display_name})}),(0,V.jsx)(`em`,{children:a(o.available_scopes.includes(r)?r===`goal`?`capabilities.goalScope`:`capabilities.machineScope`:r===`machine`?`capabilities.goalScope`:`capabilities.machineScope`)})]},o.capability_id)})})}function Jb({capability:e,locale:t,source:n}){let{t:r}=qi(),i=zb(e,t);return(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`span`,{className:`personal-settings-icon`,children:(0,V.jsx)(Gm,{"aria-hidden":!0,size:18})}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{className:`personal-capability-heading-row`,children:[(0,V.jsx)(`h2`,{children:i.display_name}),(0,V.jsx)(Ub,{source:n,t:r})]}),e.context_contribution&&(0,V.jsxs)(`details`,{className:`personal-capability-help`,"data-testid":`capability-context-phases`,children:[(0,V.jsx)(`summary`,{children:t===`zh-CN`?`主 Agent 协作指导`:`Coordinator workflow guidance`}),(0,V.jsx)(`p`,{children:t===`zh-CN`?`随能力开启。支持以下阶段;此处展示能力范围,不能证明某次运行已读取或采纳。`:`Enabled with this capability. These are supported phases, not proof that a run read or adopted the guidance.`}),(0,V.jsx)(`dl`,{children:e.context_contribution.supported_phases.map(e=>(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:(0,V.jsx)(`code`,{children:e})}),(0,V.jsx)(`dd`,{children:Yb[e][t===`zh-CN`?`zh`:`en`]})]},e))}),(0,V.jsx)(`p`,{children:t===`zh-CN`?`LoopX Turn 在请求与结果中提供上下文;原生工具入口由 LoopX skill 调用同一只读接口。执行与采纳需另看运行证据。`:`LoopX Turn includes context in requests and results. For native tools, the LoopX skill reads the same interface. Execution and adoption require run evidence.`})]}),(0,V.jsxs)(`details`,{className:`personal-capability-help`,children:[(0,V.jsx)(`summary`,{children:t===`zh-CN`?`配置说明`:`Configuration help`}),(0,V.jsx)(`p`,{children:i.description}),(0,V.jsx)(`dl`,{children:e.configuration_editor.fields.map(e=>{let n=Bb(t)[e.key],r=n?.description??e.description;return r?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:n?.label??e.label}),(0,V.jsx)(`dd`,{children:r})]},e.key):null})})]},e.capability_id)]})]})}var Yb={before_plan:{zh:`规划前:识别独立问题并保留主 Agent 的核验与整合职责。`,en:`Before planning: identify independent questions and retain coordinator validation and integration.`},before_delegate:{zh:`委派前:明确子任务边界、模型偏好及预期证据。`,en:`Before delegation: specify task boundaries, model preferences and expected evidence.`},after_delegate_result:{zh:`回收后:核验结果,说明采纳决定并关联计划与成果。`,en:`After results: validate evidence, explain acceptance and link plans and deliverables.`}};function Xb({goalId:e,onApplied:t,selected:n,t:r}){let[i,a]=(0,B.useState)({busy:null,draft:{},partialWrite:null,preview:null}),[o,s]=(0,B.useState)(null),[c,l]=(0,B.useState)(`guided`),[u,d]=(0,B.useState)(``),f=(0,B.useMemo)(()=>n?Mb(n.configuration_editor,u):null,[n,u]),p=c===`guided`||f!==null;(0,B.useEffect)(()=>{l(`guided`),d(``),a({busy:null,draft:jb(n?.configuration_editor??{fields:[]},n?.current??n?.effective_configuration?.configuration??n?.default,n?.default),partialWrite:null,preview:null}),s(null)},[n]);async function m(t){if(!(!n||i.busy||!p)){a(e=>({...e,busy:`preview`,partialWrite:null})),s(null);try{let r=await Eg(e,n.capability_id,t);a(e=>({...e,preview:r}))}catch(e){s(e instanceof Error?e.message:r(`capabilities.previewFailed`))}finally{a(e=>({...e,busy:null}))}}}async function h(){if(!(!n||!i.preview||i.busy||!p)){a(e=>({...e,busy:`apply`})),s(null);try{let r=jb(n.configuration_editor,i.draft,n.default),o=await Dg(e,n.capability_id,i.preview.action===`delete`?null:r,i.preview.plan_revision);a(e=>({...e,partialWrite:o.status===`partial_write`?o:null,preview:null})),o.status!==`partial_write`&&t()}catch(e){a(e=>({...e,preview:null})),s(e instanceof Error?e.message:r(`capabilities.applyFailed`))}finally{a(e=>({...e,busy:null}))}}}function g(e,t){a(r=>({...r,draft:n?.capability_id===`periodic_report`?Nb(r.draft,e,t):{...r.draft,[e]:t},preview:null})),s(null)}function _(e){if(!n||i.busy)return;d(e);let t=Mb(n.configuration_editor,e);a(e=>({...e,preview:null,draft:t?jb(n.configuration_editor,t,n.default):e.draft})),s(null)}function v(){i.busy||!p||(c===`guided`&&d(JSON.stringify(i.draft,null,2)),l(c===`guided`?`json`:`guided`),a(e=>({...e,preview:null})))}return{apply:h,changeDraft:g,changeJson:_,changeMode:v,editorMode:c,jsonDraft:u,jsonValid:p,error:o,mutation:i,preview:m}}function Zb({mutationError:e,onApplied:t,partialWrite:n,preview:r}){let{t:i}=qi();return(0,V.jsxs)(V.Fragment,{children:[e?(0,V.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:e}):null,n?(0,V.jsxs)(`section`,{"aria-live":`polite`,className:`personal-capability-recovery`,children:[(0,V.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:i(`capabilities.partialWrite`)}),(0,V.jsx)(`p`,{children:i(`capabilities.partialWriteDescription`)}),(0,V.jsx)(`small`,{children:n.recommended_action})]}),(0,V.jsxs)(`button`,{onClick:t,type:`button`,children:[(0,V.jsx)(Im,{"aria-hidden":!0,size:15}),i(`capabilities.refreshSource`)]})]}):null,r?(0,V.jsxs)(`section`,{className:`personal-capability-preview`,"aria-label":i(`capabilities.preview`),children:[(0,V.jsx)(`strong`,{children:i(`capabilities.preview`)}),(0,V.jsx)(`span`,{children:i(`machine.action.${r.action}`)}),(0,V.jsx)(`small`,{children:i(`capabilities.previewLocked`)})]}):null]})}function Qb({catalog:e,goalId:t,onApplied:n}){let{locale:r,t:i}=qi(),a=(0,B.useMemo)(()=>Kb(e.capabilities,r),[e.capabilities,r]),[o,s]=(0,B.useState)(()=>a[0]?.capability_id??``),c=(0,B.useMemo)(()=>a.find(e=>e.capability_id===o)??a[0],[a,o]),l=(0,B.useMemo)(()=>c?zb(c,r):void 0,[r,c]),{apply:u,changeDraft:d,changeJson:f,changeMode:p,editorMode:m,jsonDraft:h,jsonValid:g,error:_,mutation:v,preview:y}=Xb({goalId:t,onApplied:n,selected:l,t:i}),{busy:b,draft:x,partialWrite:S,preview:C}=v;if(!c||!l)return(0,V.jsx)(`p`,{className:`personal-capability-empty`,children:i(`capabilities.empty`)});let w=l.available_scopes.includes(`goal`),T=Vb(l,`goal`),E=l.configuration_editor.read_only_reason??i(w?`capabilities.previewOnly`:`capabilities.machineOnly`);async function D(){if(!l||!T||b||!g)return;let e=jb(l.configuration_editor,x,l.default);await y(e)}async function O(){!T||b||await y(null)}return(0,V.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,V.jsx)(qb,{capabilities:e.capabilities,locale:r,onSelect:s,scope:`goal`,selectedCapabilityId:l.capability_id,t:i}),(0,V.jsxs)(`article`,{"aria-label":l.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,V.jsx)(Jb,{capability:c,locale:r,source:l.effective_configuration?.source}),(0,V.jsx)(Wb,{available:T,t:i,description:E}),T?(0,V.jsxs)(V.Fragment,{children:[m===`json`||!l.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,V.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,V.jsxs)(`button`,{disabled:!!b||!g,onClick:p,type:`button`,children:[(0,V.jsx)(sm,{"aria-hidden":!0,size:14}),i(m===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,m===`guided`?(0,V.jsx)(`section`,{className:`personal-capability-field-summary`,children:(0,V.jsx)(Ib,{disabled:!!b,copy:Bb(r),editor:l.configuration_editor,onChange:d,value:x,enabledAction:(0,V.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:p,type:`button`,children:[(0,V.jsx)(sm,{"aria-hidden":!0,size:14}),i(`machine.editJson`)]})})}):(0,V.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`goal-configuration-json`,children:[(0,V.jsx)(`span`,{children:i(`capabilities.jsonConfiguration`)}),(0,V.jsx)(`textarea`,{id:`goal-configuration-json`,"aria-describedby":`goal-configuration-json-help`,disabled:!!b,onChange:e=>f(e.target.value),rows:12,spellCheck:!1,value:h}),(0,V.jsx)(`small`,{id:`goal-configuration-json-help`,children:i(`capabilities.jsonHelp`)}),g?null:(0,V.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:i(`capabilities.jsonInvalid`)})]})]}):null,(0,V.jsx)(Zb,{mutationError:_,onApplied:n,partialWrite:S,preview:C}),T?(0,V.jsxs)(`footer`,{className:`personal-capability-actions`,children:[l.current&&l.available_scopes.includes(`machine`)?(0,V.jsx)(`button`,{disabled:!!b||!g,onClick:()=>void O(),type:`button`,children:i(`capabilities.restoreInheritance`)}):null,(0,V.jsx)(`button`,{disabled:!!b||!g,onClick:()=>void D(),type:`button`,children:i(b===`preview`?`common.loading`:`capabilities.previewChanges`)}),(0,V.jsx)(`button`,{className:`is-primary`,disabled:!!b||!C||!g,onClick:()=>void u(),type:`button`,children:i(b===`apply`?`common.loading`:`capabilities.applyPreview`)})]}):null,(0,V.jsx)(Hb,{values:[{label:i(`capabilities.goalValue`),value:l.current},{label:i(l.machine_current?`capabilities.machineValue`:`capabilities.defaultValue`),value:l.machine_current??l.default}],t:i},c.capability_id)]})]})}function $b({goalId:e}){let{t}=qi(),[n,r]=(0,B.useState)(null),[i,a]=(0,B.useState)(null),[o,s]=(0,B.useState)(!1);function c(){e&&(s(!0),a(null),Tg(e).then(r).catch(e=>a(e instanceof Error?e.message:t(`capabilities.loadFailed`))).finally(()=>s(!1)))}return(0,B.useEffect)(c,[e]),e?o&&!n?(0,V.jsxs)(`p`,{"aria-live":`polite`,className:`personal-capability-empty`,children:[(0,V.jsx)(Cm,{className:`personal-spin`,size:18}),t(`capabilities.loading`)]}):i?(0,V.jsxs)(`section`,{className:`personal-capability-error`,role:`alert`,children:[(0,V.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:t(`capabilities.loadFailed`)}),(0,V.jsx)(`small`,{children:i})]}),(0,V.jsxs)(`button`,{onClick:c,type:`button`,children:[(0,V.jsx)(Im,{"aria-hidden":!0,size:15}),t(`capabilities.retry`)]})]}):n?(0,V.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":n.revision,children:[(0,V.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:17}),t(`capabilities.atomicOverride`)]}),(0,V.jsx)(`p`,{children:t(`capabilities.atomicOverrideDescription`)})]}),(0,V.jsx)(Qb,{catalog:n.capability_catalog,goalId:e,onApplied:c})]}):null:(0,V.jsx)(`p`,{className:`personal-capability-empty`,children:t(`capabilities.chooseGoal`)})}function ex(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function tx(e,t){let n=t?.machine_namespace;return n?e?.machine_configuration?.namespaces[n]:void 0}function nx(e,t,n){return{...ex(e.default),...ex(t),...n}}function rx(e,t){for(let n of e.configuration_editor.fields){let e=t[n.key];if(n.required&&(e==null||e===``))return!1}return e.capability_id===`periodic_report`&&t.enabled===!0?!!(String(t.profile_preset??``).trim()&&String(t.route_ref??``).trim()&&String(t.timezone??``).trim()):!0}function ix(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:null}catch{return null}}function ax(e){return e?e===`absent`?e:e.replace(/^sha256:/,``).slice(0,12):`—`}function ox(){let{locale:e,t}=qi(),[n,r]=(0,B.useState)(null),[i,a]=(0,B.useState)(``),[o,s]=(0,B.useState)({}),[c,l]=(0,B.useState)(`{}`),[u,d]=(0,B.useState)(`guided`),[f,p]=(0,B.useState)(null),[m,h]=(0,B.useState)(`upsert`),[g,_]=(0,B.useState)(null),[v,y]=(0,B.useState)(null),[b,x]=(0,B.useState)(`load`),[S,C]=(0,B.useState)(null),[w,T]=(0,B.useState)(null),E=(0,B.useMemo)(()=>Kb(n?.capability_catalog.capabilities??[],e),[n,e]),D=E.find(e=>e.capability_id===i)??E.find(e=>Vb(e,`machine`))??E[0],O=D?zb(D,e):void 0,ee=tx(n,O),te=!!(O?.machine_namespace&&ee),ne=!!(O&&Vb(O,`machine`)),k=(0,B.useMemo)(()=>ix(c),[c]),A=O?u===`json`?k:nx(O,ee,o):null,j=!!(O&&(u===`json`?k:rx(O,A??{})));async function M(){r(await wg())}(0,B.useEffect)(()=>{let e=!0;return wg().then(t=>{e&&r(t)}).catch(n=>{e&&C(n instanceof Error?n.message:t(`machine.loadError`))}).finally(()=>{e&&x(null)}),()=>{e=!1}},[t]),(0,B.useEffect)(()=>{if(!O)return;let e=tx(n,O),t=jb(O.configuration_editor,e??O.default,O.default),r=nx(O,e,t);s(t),l(JSON.stringify(r,null,2)),d(ne?`guided`:`json`),p(null),h(`upsert`),y(null)},[n,i,e]);function N(e,t){s(n=>O?.capability_id===`periodic_report`?Nb(n,e,t):{...n,[e]:t}),p(null),h(`upsert`),C(null),T(null)}function P(e){if(O){if(e===`json`)l(JSON.stringify(nx(O,ee,o),null,2));else if(k)s(jb(O.configuration_editor,k,O.default));else{C(t(`machine.jsonInvalid`));return}d(e),p(null),h(`upsert`),C(null)}}async function F(){if(!(!ne||!O?.machine_namespace||!A||!j||b)){x(`preview`),C(null),T(null);try{h(`upsert`),p(await Og(O.machine_namespace,A))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function re(){if(!(!ne||!O?.machine_namespace||!te||b)){x(`preview`),C(null),T(null);try{h(`remove`),p(await Ag(O.machine_namespace))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function ie(){if(!ne||!O?.machine_namespace||!f||b||m===`upsert`&&!A)return;x(`apply`),C(null);let e=m;try{let n=e===`remove`?await jg(O.machine_namespace,f.plan_revision):await kg(O.machine_namespace,A,f.plan_revision);_(n),p(null),h(`upsert`),y(null),await M(),T(n.status===`applied`?t(e===`remove`?`machine.removed`:`machine.applied`):t(`machine.unchanged`))}catch(e){p(null),h(`upsert`),C(e instanceof Error?e.message:t(`machine.applyError`))}finally{x(null)}}async function I(){if(!(!g?.transaction_id||b)){x(`rollback-preview`),C(null);try{y(await Mg(g.transaction_id))}catch(e){C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}async function ae(){if(!(!g?.transaction_id||!v||b)){x(`rollback`),C(null);try{await Ng(g.transaction_id,v.plan_revision),_(null),y(null),p(null),await M(),T(t(`machine.rolledBack`))}catch(e){y(null),C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}return b===`load`?(0,V.jsx)(`div`,{className:`personal-machine-loading`,role:`status`,children:t(`common.loading`)}):O?(0,V.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":n?.revision,children:[(0,V.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:17}),t(`machine.liveDefault`)]}),(0,V.jsx)(`p`,{children:t(`machine.liveDefaultDescription`)})]}),(0,V.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,V.jsx)(qb,{capabilities:E,locale:e,onSelect:a,scope:`machine`,selectedCapabilityId:O.capability_id,t}),(0,V.jsxs)(`article`,{"aria-label":O.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,V.jsx)(Jb,{capability:D,locale:e,source:O.available_scopes.includes(`machine`)?te?`machine_default`:`capability_default`:void 0}),(0,V.jsx)(Wb,{available:ne,t,description:O.available_scopes.includes(`machine`)?t(`machine.editorUnavailableDescription`):t(`machine.goalOnly`)}),O.capability_id===`periodic_report`?(0,V.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:ee?.schedule?e===`zh-CN`?`日历与阶段汇报`:`Calendar and stage reports`:t(`machine.periodicReportActivation`)}),(0,V.jsx)(`p`,{children:ee?.schedule?ee.enabled===!0?e===`zh-CN`?`已配置日历计划,由现有唤醒检查;是否送达请核对报告回执。`:`A calendar schedule is configured and checked by existing wakes. Verify delivery in the report receipt.`:e===`zh-CN`?`日历计划已保存;启用此能力后才会检查和投递。`:`The schedule is saved; enable this capability to check and deliver reports.`:t(`machine.periodicReportActivationDescription`)})]})]}):null,O.capability_id===`change_quality_qualification`?(0,V.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:t(`machine.changeQualityActivation`)}),(0,V.jsx)(`p`,{children:t(`machine.changeQualityActivationDescription`)})]})]}):null,O.capability_id===`todo_replan_cadence`?(0,V.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:t(`machine.replanCadenceActivation`)}),(0,V.jsx)(`p`,{children:t(`machine.replanCadenceActivationDescription`)})]})]}):null,ne?(0,V.jsxs)(V.Fragment,{children:[u===`json`||!O.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,V.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,V.jsxs)(`button`,{onClick:()=>P(u===`guided`?`json`:`guided`),type:`button`,children:[(0,V.jsx)(sm,{"aria-hidden":!0,size:14}),t(u===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,u===`guided`?(0,V.jsxs)(`section`,{className:`personal-capability-field-summary`,children:[(0,V.jsx)(Ib,{copy:Bb(e),disabled:!!b,editor:O.configuration_editor,onChange:N,value:o,enabledAction:(0,V.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:()=>P(`json`),type:`button`,children:[(0,V.jsx)(sm,{"aria-hidden":!0,size:14}),t(`machine.editJson`)]})}),j?null:(0,V.jsx)(`p`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.requiredFields`)})]}):(0,V.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`machine-configuration-json`,children:[(0,V.jsx)(`span`,{children:t(`machine.jsonConfiguration`)}),(0,V.jsx)(`textarea`,{"aria-describedby":`machine-configuration-json-help`,disabled:!!b,id:`machine-configuration-json`,onChange:e=>{l(e.target.value),p(null),C(null)},rows:12,spellCheck:!1,value:c}),(0,V.jsx)(`small`,{id:`machine-configuration-json-help`,children:t(`machine.jsonConfigurationHelp`)}),k?null:(0,V.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.jsonInvalid`)})]})]}):null,S?(0,V.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:S}):null,w?(0,V.jsxs)(`p`,{className:`personal-machine-notice`,role:`status`,"aria-live":`polite`,children:[(0,V.jsx)(em,{"aria-hidden":!0,size:16}),w]}):null,f?(0,V.jsxs)(`section`,{"aria-label":t(`machine.preview`),className:`personal-machine-preview`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:t(`machine.preview`)}),(0,V.jsx)(`span`,{children:t(`machine.action.${f.action}`)})]}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`machine.currentRevision`)}),(0,V.jsx)(`dd`,{title:f.current_revision,children:ax(f.current_revision)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`machine.desiredRevision`)}),(0,V.jsx)(`dd`,{title:f.desired_revision,children:ax(f.desired_revision)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`machine.changedNamespaces`)}),(0,V.jsx)(`dd`,{children:f.changed_namespaces.join(`, `)||t(`common.none`)})]})]}),(0,V.jsx)(`p`,{children:t(`machine.previewLocked`)})]}):null,g?.rollback_available&&g.transaction_id?(0,V.jsxs)(`section`,{className:`personal-machine-rollback`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:t(`machine.rollbackAvailable`)}),(0,V.jsx)(`p`,{children:t(v?`machine.rollbackPreviewDescription`:`machine.rollbackDescription`)})]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!!b||!!(v&&!v.rollback_allowed),onClick:()=>void(v?ae():I()),type:`button`,children:[(0,V.jsx)(Lm,{"aria-hidden":!0,size:15}),t(b===`rollback`||b===`rollback-preview`?`common.loading`:v?`machine.confirmRollback`:`machine.previewRollback`)]})]}):null,ne?(0,V.jsxs)(`footer`,{className:`personal-capability-actions`,children:[te?(0,V.jsxs)(`button`,{className:`is-danger`,disabled:!!b,onClick:()=>void re(),type:`button`,children:[(0,V.jsx)(Xm,{"aria-hidden":!0,size:15}),t(`machine.previewRemoval`)]}):null,(0,V.jsx)(`button`,{disabled:!!b||!j,onClick:()=>void F(),type:`button`,children:t(b===`preview`?`common.loading`:`machine.previewChanges`)}),(0,V.jsx)(`button`,{className:`is-primary`,disabled:!!b||!f,onClick:()=>void ie(),type:`button`,children:t(b===`apply`?`common.loading`:`machine.applyPreview`)})]}):null,O.available_scopes.includes(`machine`)?(0,V.jsx)(Hb,{values:[{label:t(`machine.currentValue`),value:ee},{label:t(`capabilities.defaultValue`),value:O.default}],t},O.capability_id):null]})]})]}):(0,V.jsx)(`p`,{className:`personal-capability-empty`,children:t(`machine.capabilityEmpty`)})}var sx={appearance:Am,capabilities:Gm,language:bm,lark:Um,machine:Vm};function cx({focusGoalConnection:e=!1,goals:t,initialGoalId:n,initialTab:r=`lark`,onChanged:i,onClose:a,onThemeChange:o,theme:s}){let{locale:c,setLocale:l,t:u}=qi(),[d,f]=(0,B.useState)(r),p=[...n?[{key:`capabilities`,label:u(`capabilities.title`)}]:[],{key:`machine`,label:u(`machine.title`)},{key:`lark`,label:`Lark`},{key:`appearance`,label:u(`settings.appearance`)},{key:`language`,label:u(`settings.language`)}],m=[{label:u(`settings.languageEnglish`),value:`en`},{label:u(`settings.languageSimplifiedChinese`),value:`zh-CN`}],h={appearance:{title:u(`settings.appearance`)},capabilities:{title:u(`capabilities.title`)},language:{title:u(`settings.language`)},lark:{title:`Lark`},machine:{title:u(`machine.title`)}}[d];return(0,V.jsxs)(`section`,{"aria-label":u(`settings.title`),className:`personal-settings-page`,"data-pw-theme":s,children:[(0,V.jsxs)(`aside`,{className:`personal-settings-sidebar`,children:[(0,V.jsxs)(`button`,{className:`personal-settings-back`,onClick:a,type:`button`,children:[(0,V.jsx)(Gp,{size:17}),(0,V.jsx)(`span`,{children:u(`settings.back`)})]}),(0,V.jsxs)(`div`,{className:`personal-settings-title`,children:[(0,V.jsx)(`small`,{children:u(`settings.eyebrow`)}),(0,V.jsx)(`strong`,{children:u(`settings.title`)})]}),(0,V.jsx)(`nav`,{"aria-label":u(`settings.categories`),className:`personal-settings-tabs`,children:p.map(e=>{let t=sx[e.key];return(0,V.jsxs)(`button`,{"aria-current":d===e.key?`page`:void 0,onClick:()=>f(e.key),type:`button`,children:[(0,V.jsx)(t,{size:17}),(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:e.label})})]},e.key)})})]}),(0,V.jsxs)(`main`,{className:`personal-settings-body`,children:[(0,V.jsx)(`header`,{className:`personal-settings-header`,children:(0,V.jsx)(`div`,{children:(0,V.jsx)(`h1`,{children:h.title})})}),d===`lark`?(0,V.jsx)(kb,{embedded:!0,focusGoalConnection:e,goals:t,initialGoalId:n,onChanged:i,onClose:a}):null,d===`machine`?(0,V.jsx)(ox,{}):null,d===`capabilities`?(0,V.jsx)($b,{goalId:n}):null,d===`appearance`?(0,V.jsxs)(`section`,{className:`personal-detail-card personal-appearance-settings`,children:[(0,V.jsx)(`small`,{children:u(`settings.workspaceDisplay`)}),(0,V.jsx)(`h3`,{children:u(`settings.appearance`)}),(0,V.jsxs)(`div`,{className:`personal-settings-choice-group`,role:`radiogroup`,"aria-label":u(`settings.workspaceTheme`),children:[(0,V.jsxs)(`button`,{"aria-checked":s===`loopx`,onClick:()=>o(`loopx`),role:`radio`,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-settings-theme-swatch is-loopx`}),(0,V.jsx)(`strong`,{children:u(`settings.themeLoopx`)})]}),(0,V.jsxs)(`button`,{"aria-checked":s===`paper`,onClick:()=>o(`paper`),role:`radio`,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-settings-theme-swatch is-paper`}),(0,V.jsx)(`strong`,{children:u(`settings.themeDefault`)})]}),(0,V.jsxs)(`button`,{"aria-checked":s===`brutal`,onClick:()=>o(`brutal`),role:`radio`,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-settings-theme-swatch is-brutal`}),(0,V.jsx)(`strong`,{children:u(`settings.themeHighContrast`)})]})]})]}):null,d===`language`?(0,V.jsxs)(`section`,{className:`personal-settings-card`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`span`,{className:`personal-settings-icon`,children:(0,V.jsx)(bm,{size:18})}),(0,V.jsx)(`div`,{children:(0,V.jsx)(`h2`,{children:u(`settings.language`)})})]}),(0,V.jsx)(`div`,{"aria-label":u(`settings.language`),className:`personal-language-options`,role:`radiogroup`,children:m.map(e=>(0,V.jsxs)(`button`,{"aria-checked":c===e.value,className:c===e.value?`is-selected`:``,onClick:()=>l(e.value),role:`radio`,type:`button`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:e.label})}),c===e.value?(0,V.jsx)(em,{"aria-hidden":!0,size:17}):null]},e.value))})]}):null]})]})}var lx=`loopx-pw-theme`,ux=`loopx`;function dx(){try{let e=window.localStorage.getItem(lx);return e===`loopx`||e===`paper`||e===`brutal`?e:ux}catch{return ux}}function fx(e){try{window.localStorage.setItem(lx,e)}catch{}}function px({drawer:e,drawerMode:t=`panel`,drawerOpen:n,main:r,mobileSidebarOpen:i=!1,onCloseMobileSidebar:a,sidebar:o,theme:s=`loopx`}){let{t:c}=qi(),l=(0,B.useRef)(null),u=(0,B.useRef)(null);return(0,B.useEffect)(()=>{if(!i)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null;let e=l.current?.querySelectorAll(`button:not([disabled]), a[href], select:not([disabled]), textarea:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])`);e?.[0]?.focus();function t(t){if(t.key!==`Tab`||!e?.length)return;let n=e[0],r=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),r.focus()):!t.shiftKey&&document.activeElement===r&&(t.preventDefault(),n.focus())}return document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`keydown`,t),u.current?.focus(),u.current=null}},[i]),(0,V.jsxs)(`section`,{className:`personal-workspace-shell${n?` has-drawer`:``}${n&&t.startsWith(`inspector`)?` has-task-inspector`:``}${t===`inspector-full`?` is-task-inspector-full`:``}${i?` mobile-sidebar-open`:``}`,"data-pw-theme":s,children:[i?(0,V.jsx)(`button`,{"aria-hidden":!0,className:`personal-sidebar-backdrop`,onClick:a,tabIndex:-1,type:`button`}):null,(0,V.jsx)(`aside`,{"aria-label":i?c(`header.goalNavigation`):void 0,"aria-modal":i?!0:void 0,className:`personal-workspace-sidebar`,"data-workspace-sidebar":!0,ref:l,role:i?`dialog`:void 0,children:(0,V.jsxs)(`div`,{className:`personal-workspace-sidebar-inner`,children:[i?(0,V.jsxs)(`button`,{className:`personal-sr-only`,onClick:a,type:`button`,children:[c(`common.close`),` `,c(`header.goalNavigation`)]}):null,o]})}),(0,V.jsx)(`main`,{"aria-hidden":i||void 0,className:`personal-workspace-main`,inert:i||void 0,children:r}),n?(0,V.jsx)(`aside`,{className:`personal-workspace-drawer`,"data-context-drawer":!0,"data-drawer-mode":t,children:e}):null]})}function mx(e){let t=e.match(/(?:下一步|建议|行动项|待办)[::\s]*([^\n]+)/u),n=t?t[1]:e;n=n.replace(/```[\s\S]*?```/g,``).replace(/`([^`]+)`/g,`$1`).replace(/\[([^\]]+)\]\([^)]+\)/g,`$1`).replace(/[#*~_>]/g,``).replace(/^[-*•\d+.\s]+/u,``).replace(/^(好的|没问题|收到|建议如下|任务如下|分析如下|结论[::])[\s,,::]*/u,``);let r=(n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean)[0]||n).replace(/\s+/gu,` `).trim();return Array.from(r).slice(0,120).join(``)}function hx(e){let t=new Map;return e.forEach(e=>{let n=e.fields.find(e=>e.key===`todo_id`)?.value??``,r=[e.actionKind,e.goalId??``,n,e.title].join(`:`);t.set(r,e)}),[...t.values()]}function gx(e,t,n){if(!e)return n(`home.noFirstActivity`);let r=new Date(e);if(Number.isNaN(r.getTime()))return e;let i=new Date,a=new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r);return r.toDateString()===i.toDateString()?n(`home.todayAt`,{time:a}):new Intl.DateTimeFormat(t,{month:`numeric`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r)}function _x({goals:e,onSelectGoal:t,onRetry:n,systemHealth:r}){let{locale:i,t:a}=qi(),o=e.filter(e=>e.activationState===`active`),s=o.filter(e=>e.loadState===`error`).length,c=[{key:`needs_you`,label:a(`home.lane.needsYou`)},{key:`running`,label:a(`home.lane.running`)},{key:`observing`,label:a(`home.lane.observing`)},{key:`scheduled`,label:a(`home.lane.scheduled`)}],l=Object.fromEntries(c.map(e=>[e.key,[]])),u=[],d=[];e.filter(e=>!e.loadState).forEach(e=>{let t=hy(e);t===`history`?u.push(e):t===`stopped`?d.push(e):l[t].push(e)});let f=e=>(0,V.jsxs)(`button`,{className:`personal-home-goal-card`,"data-goal-state":e.loadState??e.state,"data-load-error":e.loadError,onClick:()=>t(e.goalId),type:`button`,children:[(0,V.jsxs)(`span`,{className:`personal-home-goal-meta`,children:[(0,V.jsx)(`i`,{}),e.agentLaneCount&&e.agentLaneCount>1?a(`header.workAgentCount`,{count:e.agentLaneCount}):e.agentLabel??e.agentId]}),(0,V.jsx)(`strong`,{children:e.title}),(0,V.jsx)(`p`,{children:e.loadError?a(`startup.error.${e.loadError}`):e.needsYou??e.nextSentence}),(0,V.jsxs)(`footer`,{children:[(0,V.jsx)(`span`,{children:e.loadState?a(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Ji(e.state,i)}),(0,V.jsx)(`small`,{title:e.latestActivity,children:e.loadState?``:e.latestActivity?gx(e.latestActivity,i,a):e.agentTodos.length?a(`home.taskCount`,{count:e.agentTodos.length}):a(`home.noActivity`)})]})]},e.goalId);return(0,V.jsxs)(`section`,{"aria-label":a(`home.workspace`),className:`personal-home-board`,children:[r&&(!r.ok||r.issues.length>0||r.freshnessWarning)?(0,V.jsxs)(`div`,{className:`personal-system-health-banner`,role:`alert`,children:[(0,V.jsxs)(`div`,{className:`personal-system-health-header`,children:[(0,V.jsx)(im,{size:15}),(0,V.jsx)(`strong`,{children:a(`home.systemHealth`,{summary:r.summary})}),r.freshnessWarning?(0,V.jsxs)(`small`,{children:[`(`,r.freshnessWarning,`)`]}):null]}),r.issues.length>0?(0,V.jsx)(`ul`,{className:`personal-system-health-issues`,children:r.issues.map((e,t)=>(0,V.jsx)(`li`,{children:e},t))}):null]}):null,o.some(e=>e.loadState)?(0,V.jsxs)(`section`,{className:`personal-home-lane`,"aria-live":`polite`,children:[(0,V.jsx)(`header`,{children:a(`startup.progress`,{loaded:o.filter(e=>!e.loadState).length,total:o.length})}),s?(0,V.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`status`,children:[(0,V.jsx)(`span`,{children:a(`startup.failedCount`,{count:s})}),(0,V.jsx)(`button`,{className:`min-h-11 rounded-md border px-3 py-2 text-sm`,onClick:n,type:`button`,children:a(`startup.retryFailed`)})]}):null,o.filter(e=>e.loadState).map(f)]}):null,(0,V.jsx)(`div`,{className:`personal-home-lanes`,children:c.map(e=>(0,V.jsxs)(`section`,{className:`personal-home-lane is-${e.key}`,"data-testid":`personal-home-lane-${e.key}`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`i`,{}),e.label]}),(0,V.jsx)(`b`,{children:l[e.key].length})]}),(0,V.jsx)(`div`,{className:`personal-home-lane-list`,children:l[e.key].length?l[e.key].map(f):(0,V.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.empty`)})})]},e.key))}),(0,V.jsxs)(`details`,{className:`personal-home-history`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(`span`,{children:a(`home.history`)}),(0,V.jsx)(`b`,{children:u.length}),(0,V.jsx)(`small`,{children:a(`home.completedGoals`)})]}),(0,V.jsx)(`div`,{children:u.length?u.map(f):(0,V.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.noCompletedGoals`)})})]}),d.length?(0,V.jsxs)(`details`,{className:`personal-home-history is-stopped`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(`span`,{children:a(`home.stopped`)}),(0,V.jsx)(`b`,{children:d.length}),(0,V.jsx)(`small`,{children:a(`home.preservedState`)})]}),(0,V.jsx)(`div`,{children:d.map(f)})]}):null]})}function vx({items:e,onSelect:t,reportState:n}){let{locale:r,t:i}=qi();return(0,V.jsxs)(`section`,{className:`personal-object-list personal-files-list`,"data-testid":`personal-goal-outputs`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:i(`files.title`)}),(0,V.jsx)(`span`,{children:e.length})]}),n?.loading?(0,V.jsxs)(`p`,{className:`personal-object-list-state`,role:`status`,children:[(0,V.jsx)(Im,{className:`is-spinning`,size:14}),i(`files.loadingReports`)]}):null,n?.error?(0,V.jsxs)(`p`,{className:`personal-object-list-state is-error`,role:`alert`,children:[(0,V.jsx)(im,{size:14}),i(`files.reportLoadFailed`),`: `,n.error]}):null,!n?.loading&&!n?.error&&e.length===0?(0,V.jsxs)(`p`,{className:`personal-object-list-state`,children:[(0,V.jsx)(gm,{size:14}),i(`files.empty`)]}):null,e.map(e=>(0,V.jsxs)(`button`,{"data-output-kind":e.output.kind,onClick:()=>t({item:e.output,kind:`output`}),type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-file-icon`,children:(0,V.jsx)(gm,{size:16})}),(0,V.jsx)(`strong`,{children:e.output.title}),e.output.report?(0,V.jsx)(`em`,{children:i(`files.reportDelta`,{added:e.output.report.addedCount,changed:e.output.report.changedCount})}):null,(0,V.jsx)(`p`,{children:e.output.summary??e.output.safePreview??e.output.kind??i(`files.emptySummary`)}),(0,V.jsx)(`small`,{title:e.output.createdAt,children:[e.output.goalTitle,e.output.kind===`report`?i(`files.verifiedReport`):null,e.output.todoId?`${i(`common.task`)} ${e.output.todoId}`:null,gx(e.output.createdAt,r,i)].filter(Boolean).join(` · `)})]},e.id))]})}function yx({agentLabel:e,messages:t,onClose:n,onDraftTask:r,onOpenConversation:i,title:a}){let{t:o}=qi(),s=t.reduce((e,t,n)=>t.role===`user`?n:e,0),c=t.slice(Math.max(0,s)).slice(-3),l=c.filter(e=>e.role===`assistant`&&!e.pending).at(-1);return(0,B.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),(0,V.jsxs)(`aside`,{"aria-label":o(`conversation.receipt`),className:`personal-manager-conversation-tray`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(Zp,{size:16}),(0,V.jsx)(`strong`,{children:a??o(`conversation.title`)}),(0,V.jsx)(`small`,{children:t.at(-1)?.pending?o(`conversation.replying`):o(`common.recently`)})]}),(0,V.jsxs)(`div`,{className:`personal-manager-conversation-actions`,children:[r&&l?(0,V.jsxs)(`button`,{className:`personal-manager-conversation-btn`,onClick:()=>r(l.text),title:o(`conversation.convertHint`),type:`button`,children:[(0,V.jsx)(Sm,{size:13}),(0,V.jsx)(`span`,{children:o(`conversation.toTask`)})]}):null,(0,V.jsx)(`button`,{className:`personal-manager-conversation-link`,onClick:i,type:`button`,children:o(`conversation.full`)}),n?(0,V.jsx)(`button`,{"aria-label":o(`conversation.close`),className:`personal-manager-conversation-close`,onClick:n,title:o(`conversation.close`),type:`button`,children:(0,V.jsx)($m,{size:14})}):null]})]}),(0,V.jsx)(`div`,{"aria-live":`polite`,className:`personal-manager-conversation-messages`,children:c.map(t=>(0,V.jsxs)(`article`,{className:`is-${t.role}`,children:[(0,V.jsx)(`strong`,{children:t.role===`user`?o(`common.you`):t.agentLabel??e??o(`header.manager`)}),(0,V.jsxs)(`div`,{className:`personal-manager-conversation-bubble`,children:[t.role===`user`?(0,V.jsx)(`p`,{children:t.text}):(0,V.jsx)(Ay,{text:t.text}),t.pending?(0,V.jsx)(`small`,{children:o(`conversation.agentPending`)}):null]})]},t.id))})]})}function bx({onClose:e,onOpenDetails:t,run:n}){let{t:r}=qi();return(0,V.jsxs)(`section`,{"aria-label":r(`session.record`),className:`personal-session-record`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(Zp,{size:17}),r(`session.record`)]}),(0,V.jsx)(`button`,{"aria-label":r(`session.closeRecord`),onClick:e,type:`button`,children:(0,V.jsx)($m,{size:15})})]}),(0,V.jsx)(`div`,{children:(0,V.jsx)(`strong`,{children:n.title})}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Agent`}),(0,V.jsx)(`dd`,{children:n.agentLabel})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`common.status`)}),(0,V.jsx)(`dd`,{children:Yi(n.sessionStatus??n.status,r)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Session`}),(0,V.jsx)(`dd`,{title:n.sessionId,children:n.sessionId})]})]}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:t,type:`button`,children:r(`session.details`)})]})}function xx(e,t,n){let r=[];if(t===null)return e.userTodos.slice(0,4).forEach(t=>r.push({attention:{...t,goalTitle:t.goalTitle??my(e,t.goalId)},id:`attention:${t.todoId}`,kind:`attention`})),e.goals.filter(e=>hy(e)===`running`).slice(0,4).forEach(e=>r.push({id:`run:${e.goalId}`,kind:`run`,run:{agentId:e.agentId,agentLabel:e.agentLabel??e.agentId,completedSteps:e.doneTodoCount??e.agentTodos.filter(e=>e.done).length,goalId:e.goalId,goalTitle:e.title,latestActivity:e.agentSentence,runId:`goal:${e.goalId}`,status:`running`,title:e.nextSentence,totalSteps:Math.max((e.doneTodoCount??0)+e.agentTodos.filter(e=>!e.done).length,1)}})),r;let i=e.goals.find(e=>e.goalId===t);if(!i)return r;if(i.needsYou){let t=e.userTodos.find(e=>e.goalId===i.goalId);r.push({attention:t?{...t,goalTitle:i.title}:{blocking:i.needsYouBlocking??!1,goalId:i.goalId,goalTitle:i.title,text:i.needsYou,todoId:`${i.goalId}:attention`},id:`attention:${i.goalId}`,kind:`attention`})}r.push({id:`run:${i.goalId}`,kind:`run`,run:{agentId:i.agentId,agentLabel:i.agentLabel??i.agentId,completedSteps:i.doneTodoCount??i.agentTodos.filter(e=>e.done).length,goalId:i.goalId,goalTitle:i.title,latestActivity:i.agentSentence,runId:`goal:${i.goalId}`,status:i.state===`推进中`?`running`:i.state===`需修复`?`failed`:`waiting`,title:i.nextSentence,totalSteps:Math.max((i.doneTodoCount??0)+i.agentTodos.filter(e=>!e.done).length,1)}}),i.agentTodos.filter(e=>e.taskClass===`continuous_monitor`).forEach(t=>{let a=e.timeline?.find(e=>e.kind===`run`&&e.run.goalId===i.goalId&&e.run.todoId===t.todoId&&!!e.run.sessionId);r.push({id:`schedule:${i.goalId}:${t.todoId}`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:a?[{label:a.run.latestActivity||a.run.title,runId:a.run.runId,status:a.run.status===`waiting`||a.run.status===`queued`?`running`:a.run.status,timestamp:i.latestActivity||n(`common.recently`)}]:[],goalId:i.goalId,label:t.text,schedule:t.evidence??n(`schedule.summary`),scheduleId:t.todoId,scheduleKind:`monitor`,sessionId:a?.run.sessionId,status:t.done||t.status===`paused`?`paused`:`active`,stopCondition:n(`drawer.scheduleDefaultStop`),target:t.text,timezone:`Asia/Shanghai`}})});let a=e.timeline?.find(e=>e.kind===`proposal`&&e.proposal.actionKind===`heartbeat.bind`&&e.proposal.goalId===i.goalId);if(a){let e=e=>a.proposal.fields.find(t=>t.key===e)?.value;r.push({id:`schedule:${i.goalId}:heartbeat`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:[],goalId:i.goalId,label:`${n(`schedule.heartbeat`)} · ${i.title}`,nextRunAt:n(`drawer.schedulePending`),notificationRule:n(`drawer.scheduleDefaultNotification`),schedule:e(`cadence`)??n(`schedule.summary`),scheduleId:`${i.goalId}:heartbeat`,scheduleKind:`heartbeat`,status:a.proposal.status===`applied`?`active`:`draft`,stopCondition:e(`stop_condition`)??n(`drawer.scheduleDefaultStop`),timezone:e(`timezone`)??`Asia/Shanghai`}})}return r}function Sx(e){return e===`preview_ready`?`ready`:e===`cancelled`?`draft`:e===`failed`?`error`:e}function Cx(e,t){let n={agent_id:t(`proposal.field.agentId`),cadence:t(`proposal.field.cadence`),completion_criteria:t(`proposal.field.completionCriteria`),execution_boundary:t(`proposal.field.executionBoundary`),goal_id:t(`proposal.field.goalId`),heartbeat:t(`proposal.field.heartbeat`),initial_todos:t(`proposal.field.initialTodos`),objective:t(`proposal.field.objective`),operation:t(`proposal.field.operation`),permission:t(`proposal.field.permission`),reason:t(`proposal.field.reason`),stop_condition:t(`proposal.field.stopCondition`),target:t(`proposal.field.target`),timezone:t(`proposal.field.timezone`),title:t(`proposal.field.title`),workspace_ref:t(`proposal.field.workspace`)},r=[`title`,`objective`,`completion_criteria`,`execution_boundary`,`permission`,`agent_id`,`workspace_ref`,`initial_todos`,`heartbeat`,`stop_condition`,`goal_id`];return Object.entries(e).sort(([e],[t])=>{let n=r.indexOf(e),i=r.indexOf(t);return(n<0?r.length:n)-(i<0?r.length:i)}).slice(0,10).map(([e,r])=>({key:e,label:n[e]??e.replaceAll(`_`,` `),value:e===`workspace_ref`?r===`current`?t(`proposal.workspace.current`):t(`proposal.workspace.named`,{workspace:String(r??`current`)}):Array.isArray(r)?r.join(` · `):typeof r==`object`&&r?JSON.stringify(r):String(r??`—`)}))}function wx(e){if(e.action_kind!==`goal.lifecycle`)return;let t=e.normalized_parameters.operation;return t===`stop`||t===`resume`||t===`delete`?t:void 0}function Tx(e,t){let n=wx(e),r=dy(e),i=typeof e.normalized_parameters.title==`string`?e.normalized_parameters.title:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:``,a=typeof e.normalized_parameters.target==`string`?e.normalized_parameters.target:``,o=e.action_kind===`goal.create`?t(`proposal.summary.goalCreate`,{title:i}):e.action_kind===`heartbeat.bind`?t(`proposal.summary.heartbeat`):e.action_kind===`monitor.create`?t(`proposal.summary.monitor`,{target:a}):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.summary.lifecycleStop`,{title:i}):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.summary.lifecycleDelete`,{title:i}):e.action_kind===`goal.lifecycle`?t(`proposal.summary.lifecycleResume`,{title:i}):e.summary;return{actionKind:e.action_kind,reviewPlan:r,fields:Cx(e.normalized_parameters,t),goalId:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:void 0,impact:e.action_kind===`goal.create`?t(`proposal.impact.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.impact.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.impact.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.impact.lifecycleResume`):e.permission_classification===`protected`?t(`proposal.impact.protected`):t(`proposal.impact.default`),previewId:e.proposal_id,lifecycleOperation:n,gate:e.gate?{kind:String(e.gate.kind??`protected_action`),nextAction:typeof e.gate.next_action==`string`?e.gate.next_action:void 0,summary:String(e.gate.summary??t(`proposal.gate.default`))}:void 0,primaryLabel:e.action_kind===`goal.create`?t(`proposal.primary.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.primary.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.primary.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.primary.lifecycleResume`):e.action_kind===`todo.create`&&e.normalized_parameters.start_execution===!0?t(`proposal.primary.todoStart`):t(`proposal.primary.apply`),status:e.status===`applied`&&r.interaction!==`completed`?`error`:Sx(e.status),title:o}}function Ex(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,42);if(t)return t;let n=2166136261;for(let t of e)n^=t.codePointAt(0)??0,n=Math.imul(n,16777619);return`goal-${(n>>>0).toString(36)}`}function Dx(e,t){let n=e.match(/[「“"]([^」”"]{2,80})[」”"]/u)?.[1];return n?n.trim():e.replace(/^(请|帮我|我想|给我|创建|新建|设置|please|i want to|create|set up)+/iu,``).replace(/(一个|新的)?\s*(goal|目标)/giu,``).replace(/[,。!?].*$/u,``).trim().slice(0,80)||t(`goal.defaultTitle`)}function Ox(e,t){for(let n of e.split(/\r?\n/u)){let e=n.trim();for(let n of t){let t=e.match(RegExp(`^${n.replace(/[.*+?^${}()|[\]\\]/gu,`\\$&`)}\\s*[::]\\s*(.*)$`,`iu`));if(t?.[1]?.trim())return t[1].trim()}}return``}function kx(e,t){let n=Ox(e,[`目标`,`Objective`]),r=Ox(e,[`完成标准`,`Completion criteria`]),i=Ox(e,[`执行边界(可选)`,`执行边界`,`边界`,`Execution boundary (optional)`,`Execution boundary`,`Boundary`]),a=(n||Dx(e,t)).split(/[。;;\n]/u)[0].trim().slice(0,80)||t(`goal.defaultTitle`),o=[n||a,r?t(`goal.objectiveCompletion`,{criteria:r}):``,i?t(`goal.objectiveBoundary`,{boundary:i}):``].filter(Boolean).join(` ->>>>>>>> bb5bffbb3 (feat(todo): add typed date resume trigger):loopx/web/chat/assets/index-BcZEL7DL.js -`),s=/(只读|不调用外部工具|不修改(?:仓库|代码|状态)|read.?only|do not (?:call|use) external tools|do not modify (?:repositories|repository|code|state))/iu.test(i||e);return{completionCriteria:r,executionBoundary:i,initialTodos:r?[t(`goal.initialTodo`,{criteria:r})]:[],objective:o,permission:s?`read_only`:`workspace_write_on_confirmation`,title:a}}function Ax(e){let t=e.match(/(?:每|every)\s*(\d{1,3})\s*(?:分钟|minutes?)/iu)?.[1];if(t)return`${t}m`;let n=e.match(/(?:每|every)\s*(\d{1,2})\s*(?:小时|hours?)/iu)?.[1];return n?`${n}h`:/每小时|every hour|hourly/iu.test(e)?`1h`:(/每天|每日|早上|上午|daily|every day/iu.test(e),`1d`)}function jx(e,t){return/(每周|星期|周[一二三四五六日天]|weekly|every\s+(?:mon|tues|wednes|thurs|fri|satur|sun)day|\d{1,2}\s*[::]\s*\d{2})/iu.test(e)?t(`schedule.unsupportedCalendar`):null}function Mx(e,t){return Ox(e,[`检查内容`,`监控内容`,`目标`,`Check target`,`Monitor target`,`Target`])||e.replace(/^(?:为当前 Goal |for the current Goal )?(?:添加|配置|创建|add|configure|create)?\s*(?:定时检查|监控|scheduled check|monitor)[::]?/iu,``).split(/\r?\n/u)[0].trim()||t(`schedule.defaultTarget`)}function Nx(e){return/(mr|pr).{0,8}(合并|merge)/iu.test(e)?`pr_merged`:/发布完成|上线完成|release (?:is )?complete|deployment (?:is )?complete/iu.test(e)?`release_complete`:`goal_complete`}function Px(e,t){let n=e.toLowerCase();return t.find(e=>n.includes(e.agentId.toLowerCase())||n.includes(e.label.toLowerCase()))}function Fx(e){let t=Ox(e,[`标题`,`任务标题`,`Todo 标题`]),n=Ox(e,[`内容`,`任务内容`,`Todo 内容`]);if(t)return[t,n].filter(Boolean).join(`:`).slice(0,400);let r=e.match(/[「“"]([^」”"]{2,200})[」”"]/u)?.[1];return r?r.trim():e.replace(/^(请|帮我|给我|为当前 Goal |新增|新建|创建|添加|加上|加一个|记一个)+/u,``).replace(/^(一个\s*)?(普通\s*)?(todo|待办|任务)(?:\s*到\s*Tasks?)?[::\s]*/iu,``).replace(/[。;;,,]\s*(?:不要|不需要|无需|禁止|别|暂不).{0,80}(?:heartbeat|心跳|定时|监控|执行).*$/iu,``).replace(/[,,]\s*(并且|然后|再)?\s*(交给|分配给|让).+$/u,``).replace(/\s*(交给|分配给|让)\s+.+$/u,``).trim().slice(0,400)||`推进当前 Goal 的下一项工作`}var Ix=new Set([`image/png`,`image/jpeg`,`image/webp`,`image/gif`]),Lx=5242880,Rx=4;function zx(e,t){return new Promise((n,r)=>{let i=new FileReader;i.onerror=()=>r(Error(t(`composer.imageReadError`,{name:e.name}))),i.onload=()=>n({dataUrl:String(i.result??``),id:crypto.randomUUID(),mimeType:e.type,name:e.name,size:e.size}),i.readAsDataURL(e)})}function Bx({agents:e=[{agentId:`codex`,available:!0,capability:`代码与项目执行`,label:`Codex`}],callbacks:t={},goalArchiveLoadState:n={error:null,phase:`ready`},model:r,readOnly:i=!1,selectedAgentId:a,selectedGoalId:o,statusSourceControl:s}){let{locale:c,t:l}=qi(),[u,d]=(0,B.useState)(o??null),[f,p]=(0,B.useState)(a??e.find(e=>e.available)?.agentId??`codex`),[m,h]=(0,B.useState)(null),[g,_]=(0,B.useState)(!1),[v,y]=(0,B.useState)(null),[b,x]=(0,B.useState)({}),[S,C]=(0,B.useState)(`chat`),[w,T]=(0,B.useState)(!1),[E,D]=(0,B.useState)(!1),[O,ee]=(0,B.useState)(!1),[te,ne]=(0,B.useState)(()=>{try{let e=window.sessionStorage.getItem(`loopx-pw-composer-drafts`),t=e?JSON.parse(e):{};return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}),[k,A]=(0,B.useState)(!1),[j,M]=(0,B.useState)([]),[N,P]=(0,B.useState)(null),[F,re]=(0,B.useState)(null),[ie,I]=(0,B.useState)(()=>new Set),[ae,L]=(0,B.useState)(()=>new Set),[oe,se]=(0,B.useState)(`idle`),[ce,le]=(0,B.useState)([]),[ue,de]=(0,B.useState)(!1),[R,fe]=(0,B.useState)(dx),[pe,me]=(0,B.useState)({}),[he,ge]=(0,B.useState)([]),_e=(0,B.useRef)(!1),ve=(0,B.useRef)(NaN),ye=(0,B.useRef)(null),be=(0,B.useRef)(null),xe=(0,B.useRef)(null),Se=(0,B.useRef)(new Set),Ce=(0,B.useRef)(new Set),[we,Te]=(0,B.useState)(null),z=o===void 0?u:o,Ee=a??f,De=`${z??`manager`}:${Ee}`,Oe=te[De]??``;(0,B.useEffect)(()=>{M([]),P(null)},[De]);function ke(e,t){ne(n=>{let r={...n};t?r[e]=t:delete r[e];try{window.sessionStorage.setItem(`loopx-pw-composer-drafts`,JSON.stringify(r))}catch{}return r})}function Ae(e){ke(De,e)}function je(e){let t=te[De]?.trimEnd();Ae(t?`${t}\n${e}`:e),window.requestAnimationFrame(()=>ye.current?.focus())}(0,B.useEffect)(()=>{let e=ye.current;e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,120)}px`)},[Oe]);let Me=(0,B.useMemo)(()=>r.goals.map(e=>{let t=pe[e.goalId];return t?{...e,repository:{branch:t.branch,identity:t.identity,label:t.label,readOnly:!0}}:e}),[pe,r.goals]),Ne=(0,B.useMemo)(()=>Me.filter(e=>hy(e)===`needs_you`).length,[Me]),Pe=(0,B.useMemo)(()=>Me.filter(e=>hy(e)===`needs_you`&&(e.needsYouBlocking||e.state===`等你`)).length,[Me]),H=Me.find(e=>e.goalId===z)??null,Fe=m?.kind===`settings`,Ie=z,Le=(0,B.useMemo)(()=>{let e=Object.values(b).filter(e=>e.actionKind===`heartbeat.bind`&&e.goalId&&e.status===`applied`).map(e=>({id:`schedule:${e.goalId}:heartbeat`,kind:`schedule`,schedule:{agentId:Ee,executionHistory:[],goalId:e.goalId,label:e.title,nextRunAt:l(`drawer.schedulePending`),notificationRule:l(`drawer.scheduleDefaultNotification`),schedule:e.fields.find(e=>e.key===`cadence`)?.value??l(`schedule.summary`),scheduleId:`${e.goalId}:heartbeat`,scheduleKind:`heartbeat`,status:e.status===`applied`?`active`:`draft`,stopCondition:e.fields.find(e=>e.key===`stop_condition`)?.value??l(`drawer.scheduleDefaultStop`),timezone:e.fields.find(e=>e.key===`timezone`)?.value??`Asia/Shanghai`}})),t=[...xx(r,Ie,l),...r.timeline??[],...e,...hx(Object.values(b)).filter(e=>e.actionKind!==`heartbeat.bind`||e.status!==`applied`).map(e=>({id:`proposal:${e.previewId}`,kind:`proposal`,proposal:e}))];return[...new Map(t.map(e=>[e.id,e])).values()].filter(e=>e.kind!==`proposal`||![`stale`,`error`].includes(e.proposal.status)||ce.includes(e.proposal.previewId)).filter(e=>!z||e.kind===`message`?!0:e.kind===`proposal`?!e.proposal.goalId||e.proposal.goalId===z:e.kind===`attention`?e.attention.goalId===z:e.kind===`run`?e.run.goalId===z:e.kind===`schedule`?e.schedule.goalId===z:e.output.goalId===z)},[Ie,r,b,Ee,z,ce,l]),Re=(0,B.useMemo)(()=>v?Le.filter(e=>e.kind===`message`?!0:e.kind===`run`?e.run.runId===v.runId:e.kind===`output`&&e.output.runId===v.runId):Le,[v,Le]);(0,B.useEffect)(()=>{if(!v)return;let e=Le.find(e=>e.kind===`run`&&e.run.runId===v.runId);!e||e.kind!==`run`||JSON.stringify({completedSteps:v.completedSteps,latestActivity:v.latestActivity,messages:v.sessionMessages,sessionStatus:v.sessionStatus,status:v.status,totalSteps:v.totalSteps})!==JSON.stringify({completedSteps:e.run.completedSteps,latestActivity:e.run.latestActivity,messages:e.run.sessionMessages,sessionStatus:e.run.sessionStatus,status:e.run.status,totalSteps:e.run.totalSteps})&&y(e.run)},[v,Le]);let ze=(0,B.useMemo)(()=>Le.flatMap(e=>e.kind===`message`?[e.message]:[]),[Le]),Be=(0,B.useMemo)(()=>H?Le.flatMap(e=>e.kind===`message`?[e.message]:[]):[],[Le,H]);(0,B.useEffect)(()=>{H||w||ze.some(e=>e.pending)&&D(!0)},[w,ze,H]),(0,B.useEffect)(()=>{!H||S===`chat`||Be.some(e=>e.pending)&&ee(!0)},[Be,H,S]);let Ve=(0,B.useMemo)(()=>Le.filter(e=>e.kind===`message`||e.kind===`proposal`&&ce.includes(e.proposal.previewId)),[Le,ce]),He=Ve[Ve.length-1],Ue=He?.kind===`message`?He.message.text.length:0;(0,B.useEffect)(()=>{if(!w||!be.current)return;let e=window.requestAnimationFrame(()=>{be.current&&(be.current.scrollTop=be.current.scrollHeight)});return()=>window.cancelAnimationFrame(e)},[Ve.length,w,Ue]);let We=(0,B.useMemo)(()=>{if(m?.kind===`settings`)return null;if(m?.kind===`attention`)return{kind:`attention`,item:Gd(m.item,r.attentionHistory??r.userTodos)};if(m?.kind===`goal`){let e=Me.find(e=>e.goalId===m.item.goalId);return e?{item:e,kind:`goal`}:m}if(m?.kind!==`run`)return m;let e=Le.find(e=>e.kind===`run`&&e.run.runId===m.item.runId);return e?{item:e.run,kind:`run`}:m},[Le,m,Me,r.attentionHistory,r.userTodos]);(0,B.useEffect)(()=>{if(i){me({}),ge([]);return}let e=!1;return Promise.all([Fg(),Kg()]).then(([t,n])=>{e||(me(Object.fromEntries(t.map(e=>[e.goal_id,e.repository]))),ge(n))}).catch(()=>{}),()=>{e=!0}},[i]),(0,B.useEffect)(()=>{if(!ue)return;function e(e){e.key===`Escape`&&de(!1)}return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[ue]),(0,B.useEffect)(()=>{if(z||!Le.length)return;if(!_e.current){_e.current=!0;try{ve.current=Date.parse(window.localStorage.getItem(`loopx-pw-last-visit`)??``),window.localStorage.setItem(`loopx-pw-last-visit`,new Date().toISOString())}catch{ve.current=NaN}}let e=ve.current,t=Le.filter(e=>e.kind===`run`).map(e=>e.run),n=t=>{let n=Date.parse(t??``);return!Number.isNaN(e)&&!Number.isNaN(n)&&n>e},r={attention:Ne,done:t.filter(e=>e.status===`completed`&&n(e.latestActivity)).length,failed:t.filter(e=>(e.status===`failed`||e.status===`interrupted`)&&n(e.latestActivity)).length};Te(e=>e?.attention===r.attention&&e.done===r.done&&e.failed===r.failed?e:r)},[Le,Ne,z]),(0,B.useEffect)(()=>{if(i){x({});return}let e=!1;return jh(z?{goalId:z}:{contextKind:`manager`}).then(t=>{if(e)return;let n=Object.fromEntries(t.filter(e=>[`ready`,`gated`,`deferred`,`applying`].includes(e.status)).map(e=>{let t=Tx(e,l);return[t.previewId,t]}));x(e=>({...e,...n}))}).catch(()=>{}),()=>{e=!0}},[i,z,l]);async function Ge(e,n={}){if(i)throw Error(l(`source.readOnlyWriteError`));let r;try{r=t.onPreviewAction?await t.onPreviewAction(e):Tx(await kh(e),l)}catch(t){if(!(t instanceof Th)||t.payload.error_code!==`action_preview_gate`)throw t;let n=t.payload.gate&&typeof t.payload.gate==`object`?t.payload.gate:{},i=(Array.isArray(n.candidates)?n.candidates:[]).flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.workspace_ref==`string`&&typeof t.label==`string`?[{label:t.label,workspaceRef:t.workspace_ref}]:[]}),a=String(n.kind??`workspace_selection_required`),o=a===`agent_binding_required`||a===`agent_identity_selection_required`;r={actionKind:e.actionKind,fields:i.map(e=>({key:`workspace_ref:${e.workspaceRef}`,label:e.label,value:e.workspaceRef})),gate:{kind:a,nextAction:typeof n.next_action==`string`?n.next_action:void 0,summary:String(n.summary??l(`proposal.workspaceGate.defaultSummary`))},impact:l(o?`proposal.workspaceGate.agentImpact`:`proposal.workspaceGate.selectionImpact`),previewId:`workspace-choice-${Date.now().toString(36)}`,sourceRequest:e,status:`gated`,title:l(o?`proposal.workspaceGate.agentTitle`:`proposal.workspaceGate.selectionTitle`),workspaceCandidates:i}}return le(e=>e.includes(r.previewId)?e:[...e,r.previewId]),x(e=>({...e,[r.previewId]:r})),n.select!==!1&&h({item:r,kind:`proposal`}),r}function Ke(){et(null),ke(`manager:${Ee}`,l(`composer.createGoalTemplate`)),window.requestAnimationFrame(()=>ye.current?.focus())}async function qe(e,n){de(!1);let r={delete:`Deleted from the owner workspace`,resume:`Resumed from the owner workspace`,stop:`Stopped from the owner workspace`},i={delete:l(`proposal.summary.lifecycleDelete`,{title:e.title}),resume:l(`proposal.summary.lifecycleResume`,{title:e.title}),stop:l(`proposal.summary.lifecycleStop`,{title:e.title})},a=null,o=!1;try{if(n===`stop`){if(Se.current.has(e.goalId))return;Se.current.add(e.goalId),I(new Set(Se.current)),h(null),a={goalId:e.goalId,next:`stopped`,optimisticApplied:!0,previous:e.activationState},re(l(`feedback.applying`,{title:i.stop})),t.onGoalActivationStateChange?.(e.goalId,`stopped`)}if(t.onExecuteGoalLifecycle){if(n===`delete`)throw Error(`The selected status source does not authorize Goal deletion.`);let a=await t.onExecuteGoalLifecycle({goalId:e.goalId,operation:n,reason:r[n]});if(!a.projectionVerified)throw Error(`Goal lifecycle projection did not verify.`);o=!0,t.onGoalActivationStateChange?.(e.goalId,a.activationState),re(l(`feedback.completed`,{title:i[n]})),n===`stop`&&et(null),await(t.onReconcileStatus??t.onRefresh)?.();return}let s=await Ge({actionKind:`goal.lifecycle`,context:{kind:`goal_directory`,goal_id:e.goalId},idempotencyKey:`workspace-goal-${n}-${e.goalId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,operation:n,reason:r[n]},summary:i[n]},{select:n!==`stop`});if(s.goalId!==e.goalId||s.lifecycleOperation!==n)throw h(null),Error(l(`actionReview.targetChanged`));n===`stop`&&(s.reviewPlan?.interaction===`direct`?(o=!0,await Ze(s,{lifecycleProjection:a??void 0,presentation:`feedback`})):(a&&t.onGoalActivationStateChange?.(a.goalId,a.previous),re(s.gate?l(`feedback.gateRequired`,{summary:s.gate.summary}):l(`feedback.notCompleted`,{status:s.status})),h({item:s,kind:`proposal`})))}catch(e){a&&!o&&t.onGoalActivationStateChange?.(a.goalId,a.previous),re(l(`feedback.executionFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{n===`stop`&&(Se.current.delete(e.goalId),I(new Set(Se.current)))}}function Je(e,t){Ae(l(t?e===`heartbeat`?`composer.heartbeatTemplate`:`composer.monitorTemplate`:e===`heartbeat`?`composer.heartbeatTemplateWithoutGoal`:`composer.monitorTemplateWithoutGoal`)),h(null),window.requestAnimationFrame(()=>ye.current?.focus())}async function Ye(e,n,r=``){let i=await t.onRequestScheduleConfig?.(e,n);if(i){le(e=>e.includes(i.previewId)?e:[...e,i.previewId]),x(e=>({...e,[i.previewId]:i})),h({item:i,kind:`proposal`});return}if(!n){Ae(l(e===`heartbeat`?`composer.heartbeatGoalQuestion`:`composer.monitorGoalQuestion`));return}let a=Date.now().toString(36);await Ge({actionKind:e===`heartbeat`?`heartbeat.bind`:`monitor.create`,context:{kind:`schedule`,goal_id:n},idempotencyKey:`workspace-${e}-${n}-${a}`,normalizedParameters:e===`heartbeat`?{agent_id:Ee,cadence:Ax(r),goal_id:n,stop_condition:Nx(r),timezone:`Asia/Shanghai`}:{agent_id:Ee,cadence:Ax(r),goal_id:n,stop_condition:Nx(r),target:Mx(r,l),target_key:`goal-${n}`,timezone:`Asia/Shanghai`},summary:e===`heartbeat`?l(`proposal.summary.heartbeat`):l(`proposal.summary.monitor`,{target:Mx(r,l)})})}async function Xe(e){if(!Ce.current.has(e.todoId)){Ce.current.add(e.todoId),L(new Set(Ce.current)),re(l(`feedback.preparingPreview`,{title:e.text}));try{await Ge({actionKind:`todo.update`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-${e.todoId}-complete-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,operation:`complete`,todo_id:e.todoId},summary:l(`tasks.markComplete`,{name:e.text})}),re(null)}catch(e){re(l(`feedback.previewFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{Ce.current.delete(e.todoId),L(new Set(Ce.current))}}}async function Ze(e,n={}){if(e.reviewPlan&&!e.reviewPlan.canApply)return;let i=n.presentation!==`feedback`,a=e.actionKind===`goal.lifecycle`&&e.goalId&&(e.lifecycleOperation===`stop`||e.lifecycleOperation===`resume`)?{goalId:e.goalId,next:e.lifecycleOperation===`stop`?`stopped`:`active`,optimisticApplied:!1,previous:r.goals.find(t=>t.goalId===e.goalId)?.activationState??(e.lifecycleOperation===`stop`?`active`:`stopped`)}:null,o=n.lifecycleProjection??a;re(l(`feedback.applying`,{title:e.title}));let s={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:`pending`,reason:`apply_pending`,canApply:!1}:void 0,status:`applying`};x(t=>({...t,[e.previewId]:s})),i&&h({item:s,kind:`proposal`}),o&&!o.optimisticApplied&&t.onGoalActivationStateChange?.(o.goalId,o.next);try{if(t.onApplyProposal){await t.onApplyProposal(e);let n={...e,status:`applied`};if(x(t=>({...t,[e.previewId]:n})),i&&h({item:n,kind:`proposal`}),re(l(`feedback.completed`,{title:e.title})),e.actionKind===`goal.lifecycle`){(e.lifecycleOperation===`stop`||e.lifecycleOperation===`delete`)&&et(null),e.lifecycleOperation===`delete`&&e.goalId&&t.onGoalDeleted?.(e.goalId);let n=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>n?.()).catch(()=>void 0)}return}let n=await Mh(e.previewId);if(n.proposal.proposal_id!==e.previewId||n.proposal.action_kind!==e.actionKind||e.actionKind===`goal.lifecycle`&&(n.proposal.normalized_parameters.goal_id!==e.goalId||wx(n.proposal)!==e.lifecycleOperation))throw new Th(l(`actionReview.targetChanged`),{error_code:`action_response_mismatch`});let r=Tx(n.proposal,l);if(x(t=>({...t,[e.previewId]:r})),i&&h({item:r,kind:`proposal`}),r.reviewPlan?.interaction!==`completed`){o&&t.onGoalActivationStateChange?.(o.goalId,o.previous),h({item:r,kind:`proposal`}),re(n.proposal.status===`stale`?l(`feedback.stale`):l(`actionReview.${r.reviewPlan.reason}`));return}if(re(l(`feedback.completed`,{title:r.title})),r.actionKind===`todo.create`&&await t.onRefresh?.(),r.actionKind===`goal.lifecycle`&&(r.lifecycleOperation===`stop`||r.lifecycleOperation===`delete`)&&et(null),r.actionKind===`goal.lifecycle`&&r.lifecycleOperation===`delete`&&r.goalId&&t.onGoalDeleted?.(r.goalId),r.actionKind===`goal.lifecycle`){let e=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>e?.()).catch(()=>void 0)}}catch(n){if(o&&t.onGoalActivationStateChange?.(o.goalId,o.previous),n instanceof Th&&n.payload.error_code===`protected_action`){let r=n.payload.gate,i=r&&typeof r==`object`?r:{},a={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:`gated`,reason:`authority_gate`,canApply:!1}:void 0,gate:{kind:String(i.kind??`protected_action`),nextAction:typeof i.next_action==`string`?i.next_action:void 0,summary:String(i.summary??n.message)},status:`gated`};x(t=>({...t,[e.previewId]:a})),h({item:a,kind:`proposal`}),re(l(`feedback.gateRequired`,{summary:a.gate.summary})),e.actionKind===`goal.create`&&e.goalId&&(t.onRefresh?.(),et(e.goalId));return}let r=n instanceof Th&&fy(n.payload),i=n instanceof Th&&n.payload.error_code===`action_response_mismatch`,a={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:r?`refresh`:`repair`,reason:i?`readback_unverified`:r?`stale_proposal`:`apply_failed`,canApply:!1}:void 0,errorMessage:n instanceof Error?n.message:String(n),status:r?`stale`:`error`};x(t=>({...t,[e.previewId]:a})),h({item:a,kind:`proposal`}),re(l(`feedback.executionFailed`,{error:a.errorMessage}))}}let Qe={...t,onOpenRunSession:async e=>{e.goalId!==z&&et(e.goalId),C(`chat`),await t.onOpenRunSession?.(e),y(e),h(null)},onOpenGoal:e=>{et(e);let n=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>n?.()).catch(()=>{re(l(`feedback.goalRefreshFailed`))})},onOpenGoalView:e=>{C(e),e===`chat`&&y(null),h(null)},onOpenOutput:e=>{e.goalId!==z&&et(e.goalId),C(`files`),t.onOpenOutput?.(e)},onApplyProposal:Ze,onCancelProposal:async e=>{h(null),x(t=>{let n={...t};return delete n[e.previewId],n});try{t.onCancelProposal?.(e),t.onCancelProposal||await Nh(e.previewId)}catch(t){x(t=>({...t,[e.previewId]:e})),re(l(`feedback.cancelFailed`,{error:t instanceof Error?t.message:String(t)}))}},onTransitionProposal:async(e,t)=>{let n=Tx(await Ph(e.previewId,t),l);le(e=>e.includes(n.previewId)?e:[...e,n.previewId]),x(r=>{let i={...r};return t===`regenerate`&&delete i[e.previewId],i[n.previewId]=n,i}),h({item:n,kind:`proposal`})},onSelectWorkspaceCandidate:async(e,t)=>{e.sourceRequest&&(x(t=>{let n={...t};return delete n[e.previewId],n}),await Ge({...e.sourceRequest,idempotencyKey:`${e.sourceRequest.idempotencyKey}-${t}`,normalizedParameters:{...e.sourceRequest.normalizedParameters,workspace_ref:t}}))},onPreviewAction:Ge,onRequestScheduleConfig:(e,t)=>Je(e,t),onOpenNotificationSettings:e=>h({goalId:e,kind:`settings`,tab:`lark`}),onFetchNotificationTargets:()=>rg(),onSetupGoalChannel:e=>ag(e),onToggleGoalAutoNotify:e=>og(e),onUpdateSchedule:async(e,t)=>{let n=Date.now().toString(36),r=e.scheduleKind===`heartbeat`;await Ge({actionKind:r?`heartbeat.bind`:`monitor.update`,context:{kind:`schedule`,goal_id:e.goalId},idempotencyKey:`workspace-monitor-${e.scheduleId}-${t}-${n}`,normalizedParameters:{agent_id:e.agentId??Ee,...!r&&t===`run_now`?{endpoint_id:Ee}:{},...t===`edit`?{cadence:`2h`,...r?{timezone:e.timezone??`Asia/Shanghai`}:{}}:{},goal_id:e.goalId,operation:t,...!r&&t===`run_now`&&e.sessionId?{session_id:e.sessionId}:{},...r?{}:{todo_id:e.scheduleId}},summary:t===`pause`?`暂停自动运行:${e.label}`:t===`resume`?`恢复自动运行:${e.label}`:t===`run_now`?`立即运行:${e.label}`:t===`stop`?`停止自动运行:${e.label}`:`编辑自动运行生命周期:${e.label}`})}},$e=i?{onOpenGoal:Qe.onOpenGoal,onOpenGoalView:Qe.onOpenGoalView,onOpenOutput:Qe.onOpenOutput}:Qe;function et(e){d(e),T(!1),D(!1),ee(!1),y(null),h(null),C(`tasks`),de(!1),t.onSelectGoal?.(e)}function tt(e){p(e),t.onSelectAgent?.(e)}function nt(e){fe(e),fx(e)}async function rt(n){let r=n?[]:j,i=(n??Oe).trim()||(r.length?l(`composer.imageAnalysisPrompt`):``);if(!(!i||k)){n||(Ae(``),M([])),P(null),A(!0);try{if(r.length){z?S!==`chat`&&ee(!0):D(!0);let e=await t.onSendMessage?.(i,Ee,z,r);e&&await Ge(e);return}let n=Uy(i,{agents:e.map(e=>({agentId:e.agentId,label:e.label})),goalId:z,todos:(H?.agentTodos??[]).map(e=>({text:e.text,todoId:e.todoId}))});if(n.route===`clarify`){Ae(i);let e=l(`composer.clarifySingleAction`);n.missingFields.includes(`resume_when`)&&(e=l(`composer.clarifyDefer`)),re(e);return}if(n.actionKind===`goal.create`){let e=kx(i,l),t=Ex(e.title);await Ge({actionKind:`goal.create`,context:{kind:`manager`,goal_id:null,natural_language:i},idempotencyKey:`workspace-goal-intent-${t}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:Ee,completion_criteria:e.completionCriteria,execution_boundary:e.executionBoundary,goal_id:t,heartbeat:{cadence:Ax(i),enabled:n.normalizedParameters.heartbeat_enabled===!0,timezone:`Asia/Shanghai`},initial_todos:e.initialTodos,objective:e.objective,permission:e.permission,stop_condition:Nx(i),title:e.title,workspace_ref:`current`},summary:l(`proposal.summary.goalCreate`,{title:e.title})});return}if(z&&n.actionKind===`heartbeat.bind`){await Ye(`heartbeat`,z,i);return}if(z&&n.actionKind===`monitor.create`){let e=jx(i,l);if(e){Ae(i),re(e);return}await Ye(`monitor`,z,i);return}let a=Px(i,e);if(z&&a&&n.actionKind===`agent.bind`){await Ge({actionKind:`agent.bind`,context:{kind:`goal`,goal_id:z,natural_language:i},idempotencyKey:`workspace-agent-bind-${z}-${a.agentId}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:a.agentId,goal_id:z},summary:`将 ${a.label} 绑定到 ${H?.title??z}`});return}if(z&&n.actionKind===`todo.create`){if(n.normalizedParameters.start_execution===!0){await Ge({actionKind:`todo.create`,context:{kind:`goal`,goal_id:z,natural_language:i},idempotencyKey:`workspace-task-start-${z}-${Date.now().toString(36)}`,normalizedParameters:{endpoint_id:a?.agentId??Ee,goal_id:z,start_execution:!0,text:i},summary:`交给 Agent 执行:${i.slice(0,120)}`});return}let e=a?.agentId??(/(交给|分配给|让).{0,24}(agent|codex|claude|kiro|kimi)/iu.test(i)?Ee:null);await Ge({actionKind:`todo.create`,context:{kind:`goal`,goal_id:z,natural_language:i},idempotencyKey:`workspace-todo-create-${z}-${Date.now().toString(36)}`,normalizedParameters:{...e?{endpoint_id:e}:{},goal_id:z,text:Fx(i)},summary:`创建 Todo:${Fx(i)}`});return}let o=H?.agentTodos.find(e=>i.includes(e.todoId)||i.includes(e.text)),s=typeof n.normalizedParameters.operation==`string`?n.normalizedParameters.operation:null;if(z&&o&&n.actionKind===`todo.update`&&s){await Ge({actionKind:`todo.update`,context:{kind:`todo`,goal_id:z,todo_id:o.todoId,natural_language:i},idempotencyKey:`workspace-todo-update-${o.todoId}-${s}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:Ee,...s===`reassign`&&a?{endpoint_id:a.agentId}:{},...s===`block`?{note:i}:{},...s===`defer`&&typeof n.normalizedParameters.resume_when==`string`?{resume_when:n.normalizedParameters.resume_when}:{},goal_id:z,operation:s,todo_id:o.todoId},summary:`更新 Todo:${o.text}`});return}z?S!==`chat`&&ee(!0):D(!0);let c=await t.onSendMessage?.(i,Ee,z);c&&await Ge(c)}catch(e){n||(Ae(i),M(r));let t=e instanceof Error?e.message:l(`feedback.sendGenericError`);re(l(`feedback.sendFailed`,{error:t}))}finally{A(!1)}}}let it=e.find(e=>e.agentId===Ee)?.label??Ee,at=!H&&Oe.startsWith(l(`composer.createGoalDraftLead`)),ot=Le.filter(e=>e.kind===`run`&&!!e.run.sessionId&&!!e.run.canInterrupt&&(e.run.status===`running`||e.run.status===`queued`)).length;async function st(e){if(!e?.length)return;let t=Rx-j.length,n=Array.from(e).slice(0,Math.max(0,t)),r=n.find(e=>!Ix.has(e.type)),i=n.find(e=>e.size>Lx);if(t<=0){P(l(`composer.imageCountError`,{count:Rx}));return}if(r){P(l(`composer.imageTypeError`));return}if(i){P(l(`composer.imageSizeError`,{size:Lx/1024/1024}));return}try{let t=await Promise.all(n.map(e=>zx(e,l)));M(e=>[...e,...t].slice(0,Rx)),P(e.length>n.length?l(`composer.imageCountError`,{count:Rx}):null)}catch(e){P(e instanceof Error?e.message:l(`composer.imageReadGenericError`))}finally{xe.current&&(xe.current.value=``)}}function ct(e){let t=Array.from(e.clipboardData.items).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).flatMap(e=>{let t=e.getAsFile();return t?[t]:[]});t.length&&(e.preventDefault(),st(t))}async function lt(){let e=await Kg();ge(e)}async function ut(){await Promise.all([lt(),t.onRefresh?.()])}async function dt(){if(!(!t.onRefresh||oe===`loading`)){se(`loading`);try{await t.onRefresh(),se(`done`)}catch{se(`error`)}window.setTimeout(()=>se(`idle`),1800)}}return Fe?(0,V.jsx)(cx,{focusGoalConnection:!!(m?.kind===`settings`&&m.goalId),goals:Me,initialGoalId:m?.kind===`settings`?m.goalId??z:z,initialTab:m?.kind===`settings`?m.tab??`lark`:`lark`,onChanged:()=>void ut(),onClose:()=>h(null),onThemeChange:nt,theme:R}):(0,V.jsx)(px,{drawer:We?(0,V.jsx)(Qy,{agents:e,attentionHistory:r.attentionHistory??r.userTodos,onSelectAttention:e=>h({kind:`attention`,item:e}),callbacks:$e,goalNotifications:r.goalNotifications??[],goals:Me,inspectorExpanded:g,larkConnections:i?[]:he,onClose:()=>{We.kind===`proposal`&&[`applied`,`rejected`].includes(We.item.status)&&(We.item.actionKind!==`heartbeat.bind`||We.item.status!==`applied`)&&x(e=>{let t={...e};return delete t[We.item.previewId],t}),_(!1),h(null)},onToggleInspectorSize:()=>_(e=>!e),readOnly:i,runs:Le.flatMap(e=>e.kind===`run`?[e.run]:[]),selection:We}):null,drawerMode:We?.kind===`todo`?g?`inspector-full`:`inspector`:`panel`,drawerOpen:We!==null,mobileSidebarOpen:ue,onCloseMobileSidebar:()=>de(!1),theme:R,main:(0,V.jsxs)(`div`,{className:`personal-channel`,children:[(0,V.jsx)(Cy,{agents:e,managerChatOpen:w,mobileNavigationOpen:ue,onOpenGoalCapabilities:H?()=>h({goalId:H.goalId,kind:`settings`,tab:`capabilities`}):void 0,onOpenGoalDetail:H&&!H.loadState?()=>h({item:H,kind:`goal`}):void 0,onRefresh:t.onRefresh?()=>void dt():void 0,onOpenNavigation:()=>de(!0),onOpenManagerChat:()=>{D(!1),T(!0)},onSelectGoalTab:e=>{C(e),e===`chat`&&(y(null),ee(!1))},onSelectAgent:tt,onReturnManagerHome:()=>{T(!1),D(!1),window.requestAnimationFrame(()=>be.current?.scrollTo({behavior:`smooth`,top:0}))},selectedAgentId:Ee,refreshState:oe,readOnlySourceLabel:i?s?.activeSource.label:void 0,selectedGoal:H,selectedGoalTab:S}),(0,V.jsxs)(`div`,{className:`personal-channel-scroll`,ref:be,children:[!H&&!w&&we&&we.done+we.failed+we.attention>0?(0,V.jsxs)(`section`,{className:`personal-digest-card`,"aria-label":l(`digest.away`),children:[(0,V.jsx)(`strong`,{children:l(`digest.away`)}),(0,V.jsxs)(`div`,{className:`personal-digest-stats`,children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`b`,{children:we.done}),l(`digest.completed`)]}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`b`,{children:we.failed}),l(`digest.failed`)]}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`b`,{children:we.attention}),l(`digest.needsYou`)]})]})]}):null,!H&&!w?(0,V.jsxs)(`section`,{className:`personal-manager-greeting`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(Zp,{size:20})}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:l(`home.greeting`)}),(0,V.jsx)(`p`,{children:r.goals.some(e=>e.activationState===`active`&&e.loadState)?l(`startup.partial`):(0,V.jsxs)(V.Fragment,{children:[l(`home.waitingCount`,{count:Ne}),` `,l(`home.blockingSummary`,{count:Pe})]})})]})]}):null,H?.loadState?(0,V.jsx)(`section`,{className:`personal-manager-greeting`,role:`status`,"data-testid":`goal-status-loading`,children:(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:l(H.loadState===`error`?`startup.goalError`:`startup.goalLoading`)}),(0,V.jsx)(`p`,{children:l(H.loadError?`startup.error.${H.loadError}`:`startup.independent`)}),H.loadState===`error`?(0,V.jsx)(`button`,{className:`min-h-11 rounded-md border px-3 py-2 text-sm`,type:`button`,onClick:()=>void t.onRefresh?.(),children:l(`startup.retry`)}):null]})}):H&&S===`tasks`?(0,V.jsx)(wb,{historyEnabled:!i,goal:H,items:Le,onDraftTaskFromMessage:i?void 0:e=>{Ae(`创建一个 Task:${mx(e)}`),re(l(`feedback.taskDraftCreated`)),window.requestAnimationFrame(()=>ye.current?.focus())},onOpenChat:()=>C(`chat`),onQuickComplete:i?void 0:Xe,onSelect:h,quickCompletingTodoIds:ae,selectedTodoId:We?.kind===`todo`?We.item.todoId:null,userTodos:r.userTodos}):H&&S===`files`?(0,V.jsx)(vx,{items:Le.filter(e=>e.kind===`output`),onSelect:h,reportState:r.periodicReports}):!H&&!w?(0,V.jsx)(_x,{goals:Me,onRetry:()=>void t.onRefresh?.(),onSelectGoal:et,systemHealth:r.systemHealth}):H?(0,V.jsxs)(V.Fragment,{children:[H&&v?.goalId===H.goalId?(0,V.jsx)(bx,{onClose:()=>y(null),onOpenDetails:()=>h({item:v,kind:`run`}),run:v}):null,(0,V.jsx)(Fy,{items:Re,onSelect:h,selectedGoal:H})]}):(0,V.jsx)(Fy,{items:Ve,onSelect:h,selectedGoal:null})]}),(0,V.jsx)(`div`,{className:`personal-composer-wrap`,children:i?(0,V.jsxs)(`div`,{className:`personal-read-only-notice`,children:[(0,V.jsx)(`strong`,{children:l(`source.readOnlyNoticeTitle`)}),(0,V.jsx)(`span`,{children:l(`source.readOnlyNoticeDescription`)})]}):(0,V.jsxs)(V.Fragment,{children:[!H&&!w&&E&&ze.length?(0,V.jsx)(yx,{messages:ze,onClose:()=>D(!1),onOpenConversation:()=>{D(!1),T(!0)}}):null,H&&S!==`chat`&&O&&Be.length?(0,V.jsx)(yx,{agentLabel:it,messages:Be,onClose:()=>ee(!1),onDraftTask:S===`tasks`?e=>{Ae(`创建一个 Task:${mx(e)}`),re(l(`feedback.taskDraftCreated`)),window.requestAnimationFrame(()=>ye.current?.focus())}:void 0,onOpenConversation:()=>{ee(!1),C(`chat`)},title:`${H.title} · ${it}`}):null,F?(0,V.jsxs)(`div`,{className:`personal-action-feedback`,role:`status`,children:[(0,V.jsx)(`span`,{children:F}),(0,V.jsx)(`button`,{"aria-label":l(`common.closeActionReceipt`),onClick:()=>re(null),type:`button`,children:(0,V.jsx)($m,{size:14})})]}):null,(0,V.jsx)(`p`,{className:`personal-composer-hint`,children:H?ot>0?l(`composer.goalRunningHint`,{agent:it,count:ot}):l(`composer.goalMessageHint`,{agent:it}):l(`composer.managerMessageHint`)}),H?(0,V.jsxs)(`div`,{className:`personal-quick-prompts`,children:[(0,V.jsxs)(`button`,{"aria-label":l(`composer.nextAction`),className:`is-draft`,onClick:()=>je(l(`composer.nextActionPrompt`)),title:l(`composer.prepareDraft`),type:`button`,children:[(0,V.jsx)(Em,{size:13}),(0,V.jsx)(`span`,{children:l(`composer.nextAction`)}),(0,V.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]}),(0,V.jsxs)(`button`,{className:`is-immediate`,disabled:k,onClick:()=>void rt(l(`composer.agentProgressPrompt`)),title:l(`composer.immediate`),type:`button`,children:[(0,V.jsx)(Bm,{size:13}),(0,V.jsx)(`span`,{children:l(`composer.agentProgress`)}),(0,V.jsx)(`em`,{className:`personal-prompt-badge`,children:l(`composer.immediate`)})]}),(0,V.jsxs)(`button`,{"aria-label":l(`composer.monitor`),className:`is-draft`,onClick:()=>Je(`monitor`,z),title:l(`composer.monitorHint`),type:`button`,children:[(0,V.jsx)($p,{size:13}),(0,V.jsx)(`span`,{children:l(`composer.monitor`)}),(0,V.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]})]}):(0,V.jsxs)(`div`,{className:`personal-quick-prompts`,children:[(0,V.jsxs)(`button`,{"aria-label":l(`composer.globalTasks`),className:`is-draft`,onClick:()=>je(l(`composer.globalTasksPrompt`)),title:l(`composer.prepareDraft`),type:`button`,children:[(0,V.jsx)(Em,{size:13}),(0,V.jsx)(`span`,{children:l(`composer.globalTasks`)}),(0,V.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]}),(0,V.jsxs)(`button`,{className:`is-immediate`,disabled:k,onClick:()=>void rt(l(`composer.globalProgressPrompt`)),title:l(`composer.immediate`),type:`button`,children:[(0,V.jsx)(Bm,{size:13}),(0,V.jsx)(`span`,{children:l(`composer.globalProgress`)}),(0,V.jsx)(`em`,{className:`personal-prompt-badge`,children:l(`composer.immediate`)})]}),(0,V.jsxs)(`button`,{"aria-label":l(`composer.createGoal`),className:`is-draft`,onClick:Ke,title:l(`composer.createGoalHint`),type:`button`,children:[(0,V.jsx)(Pm,{size:13}),(0,V.jsx)(`span`,{children:l(`composer.createGoal`)}),(0,V.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]})]}),at?(0,V.jsxs)(`div`,{className:`personal-goal-draft-status`,role:`status`,children:[(0,V.jsx)(`strong`,{children:l(`composer.createGoalDraft`)}),(0,V.jsx)(`span`,{children:l(`composer.createGoalDraftDescription`)})]}):null,j.length?(0,V.jsx)(`div`,{className:`personal-composer-images`,"aria-label":l(`composer.imagesPending`),children:j.map(e=>(0,V.jsxs)(`figure`,{children:[(0,V.jsx)(`img`,{alt:e.name,src:e.dataUrl}),(0,V.jsx)(`button`,{"aria-label":l(`composer.sentImageAlt`,{name:e.name}),onClick:()=>M(t=>t.filter(t=>t.id!==e.id)),type:`button`,children:(0,V.jsx)($m,{size:13})})]},e.id))}):null,N?(0,V.jsx)(`p`,{className:`personal-composer-error`,role:`alert`,children:N}):null,(0,V.jsxs)(`div`,{className:`personal-channel-composer`,onDragOver:e=>{[...e.dataTransfer.items].some(e=>e.kind===`file`&&e.type.startsWith(`image/`))&&e.preventDefault()},onDrop:e=>{let t=[...e.dataTransfer.files].filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),st(t))},children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(Zp,{size:17}),e.find(e=>e.agentId===Ee)?.label??Ee]}),(0,V.jsx)(`button`,{"aria-label":l(`composer.addImage`),className:`personal-composer-attach`,disabled:k||j.length>=Rx,onClick:()=>xe.current?.click(),title:l(`composer.attachImageHint`),type:`button`,children:(0,V.jsx)(jm,{size:17})}),(0,V.jsx)(`input`,{accept:`image/png,image/jpeg,image/webp,image/gif`,"aria-label":l(`composer.imagePicker`),className:`personal-composer-file-input`,disabled:k||j.length>=Rx,multiple:!0,onChange:e=>void st(e.target.files),ref:xe,type:`file`}),(0,V.jsx)(`textarea`,{"aria-label":l(`composer.sendMessage`),onChange:e=>Ae(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),rt())},onPaste:ct,placeholder:H?l(`composer.goalPlaceholder`,{goal:H.title}):l(`composer.managerPlaceholder`),ref:ye,rows:1,value:Oe}),(0,V.jsx)(`button`,{"aria-label":l(at?`composer.createGoal`:`composer.send`),disabled:!Oe.trim()&&j.length===0||k,onClick:()=>void rt(),title:l(at?`composer.createGoalHint`:`composer.sendMessageHint`),type:`button`,children:(0,V.jsx)(Bm,{size:18})})]})]})})]}),sidebar:(0,V.jsx)(bb,{attentionCount:Ne,goals:Me,goalArchiveLoadState:n,goalLifecycleOperations:t.onExecuteGoalLifecycle?[`stop`,`resume`]:void 0,lifecycleBusyGoalIds:ie,onRequestGoalCreate:i?void 0:Ke,onRequestGoalLifecycle:i&&!t.onExecuteGoalLifecycle?void 0:(e,t)=>void qe(e,t),onRetryGoalArchive:t.onRetryGoalArchive||t.onRefresh?()=>void(t.onRetryGoalArchive??t.onRefresh)?.():void 0,onOpenSettings:i?void 0:()=>h({kind:`settings`}),onSelectGoal:et,selectedGoalId:z,statusSourceControl:s},s?.activeSource.statusUrl??`/status.json`)})}function Vx(e){return(e??``).replace(/\s+/gu,` `).trim()}function Hx(e,t=120){let n=Array.from(e);return n.length<=t?e:`${n.slice(0,t-1).join(``)}…`}function Ux(e,t,n){let r=Vx(e);return!r||r===`暂无`?n?t(n):``:/refresh-state|latest_run|latest run-derived/iu.test(r)?t(`projection.refreshState`):/first read-only adapter tick|read-only adapter/iu.test(r)?t(`projection.firstReadOnlyAdapterCheck`):/todo update recorded for/iu.test(r)?t(`projection.todoStatusUpdated`):/^(loopx|python3|npm|git|run)\s|\s--[a-z0-9-]+|\b[a-z]+_[a-z_]+\b/iu.test(r)?t(n??`projection.agentPreparingNextStep`):Hx(r)}function Wx(e,t){return t({advancing:`projection.agentAdvancingGoal`,idle:`projection.agentIdle`,needs_you:`projection.agentNeedsDecision`,stopped:`projection.agentStopped`,waiting_external:`projection.agentWaitingExternal`}[e])}function Gx({eventCount:e,hasArtifact:t,hasLatestValidation:n},r){return{label:r(n?`projection.latestValidation`:`projection.latestRun`),metadata:e>0?r(`projection.events24h`,{count:e}):r(t?`projection.runEvidenceAvailable`:`projection.publicSafeProjection`)}}var Kx=`/status.json`,qx=`loopx-status-source-catalog-v1`,Jx={id:`local`,kind:`local`,label:`本机`,readOnly:!1,statusUrl:Kx};function Yx(e,t){let n=ih(e,t).source;if(!n||!n.isLoopback||n.isRelative)return{error:`SSH 隧道来源必须使用显式的 localhost、127.0.0.1 或 ::1 URL。`};let r=new URL(n.url,t);return[`http:`,`https:`].includes(r.protocol)?{url:r.toString()}:{error:`状态来源只支持 HTTP 或 HTTPS。`}}function Xx(e){let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619);return`ssh-${(t>>>0).toString(36)}`}function Zx(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;if(n.kind!==`ssh_tunnel`||typeof n.label!=`string`||typeof n.statusUrl!=`string`)return null;let r=n.label.trim(),i=Yx(n.statusUrl,t);if(!r||r.length>48||!(`url`in i))return null;let a=ub(n.hostAlias)?n.hostAlias.trim():void 0;return{...a?{hostAlias:a}:{},id:Xx(i.url),kind:`ssh_tunnel`,label:r,readOnly:!0,statusUrl:i.url}}function Qx(){return{schemaVersion:1,sources:[Jx]}}function $x(e,t){try{let n=e.getItem(qx);if(!n)return Qx();let r=JSON.parse(n);if(r.schemaVersion!==1||!Array.isArray(r.sources))return Qx();let i=new Set([Jx.statusUrl]);return{schemaVersion:1,sources:[Jx,...r.sources.flatMap(e=>{let n=Zx(e,t);return!n||i.has(n.statusUrl)?[]:(i.add(n.statusUrl),[n])})]}}catch{return Qx()}}function eS(e,t){e.setItem(qx,JSON.stringify({schemaVersion:1,sources:t.sources.filter(e=>e.kind===`ssh_tunnel`)}))}function tS(e,t){let n=new Set(t.filter(ub).map(e=>e.trim())),r=!1,i=e.sources.map(e=>e.kind!==`ssh_tunnel`||e.hostAlias||!n.has(e.label)?e:(r=!0,{...e,hostAlias:e.label}));return r?{...e,sources:i}:e}function nS(e,t,n){let r=t.label.trim();if(!r)return{error:`请填写来源名称。`};if(r.length>48)return{error:`来源名称不能超过 48 个字符。`};let i=Yx(t.statusUrl,n);if(!(`url`in i))return i;if(e.sources.some(e=>e.statusUrl===i.url))return{error:`这个状态 URL 已经在来源目录中。`};if(t.hostAlias!==void 0&&!ub(t.hostAlias))return{error:`请选择有效的 SSH Host。`};let a=t.hostAlias?.trim(),o={...a?{hostAlias:a}:{},id:Xx(i.url),kind:`ssh_tunnel`,label:r,readOnly:!0,statusUrl:i.url};return{catalog:{...e,sources:[...e.sources,o]},source:o}}function rS(e,t){return{...e,sources:e.sources.filter(e=>e.kind===`local`||e.id!==t)}}function iS(e,t,n){if(!t.trim()||ih(t,n).source?.isRelative)return Jx;let r=t.trim();try{r=new URL(r,n).toString()}catch{return null}return e.sources.find(e=>e.statusUrl===r)??null}function aS(e,t,n){return iS(e,t,n)||(ih(t,n).source?.isRelative?Jx:{id:`temporary`,kind:`ssh_tunnel`,label:`临时来源`,readOnly:!0,statusUrl:t.trim()})}function oS(e,t,n,r){return aS(e,t??n,r)}var sS={delete:`删除`,deploy:`部署`,merge:`合并`,payment:`付款`,release:`发布`};function cS(e,t,n){let r=t.replace(/\s+/gu,` `).trim().toLowerCase(),i=n.target.replace(/\s+/gu,` `).trim().toLowerCase();return!i||!r.includes(i)?null:{actionKind:`goal.update`,context:{goal_id:e,kind:`goal`,natural_language:t,semantic_proposal:{operation:n.operation,target:n.target}},idempotencyKey:`workspace-semantic-protected-${e}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e,status:`operator_gate_requested`},summary:`请求受保护操作:${sS[n.operation]} · ${n.target}`}}var lS=Kx;async function uS(e){let t=await fetch(e,{cache:`no-store`,signal:AbortSignal.timeout(3e4)});if(!t.ok)throw Error(`HTTP ${t.status} while loading ${e}`);return Ep(await t.json())}function dS(e,t){if(t?.controller_readiness?.decision_advisor_ready||t?.controller_readiness?.write_controller_ready)return`controller_ready`;if(t?.controller_readiness)return`controller_gated`;if(t?.human_reward)return`reward_judged`;if(t?.operator_gate?.decision===`approve`)return`operator_approved`;if(t?.operator_gate)return`operator_gated`;let n=e||t?.classification||``;return n===`connected_without_run`?`connected`:n===`read_only_project_map`||t?.project_map?`mapped`:n===`state_refreshed`?`refreshed`:n&&n!==`no_status`?`adapter_inspected`:`registered`}function fS(e,t){let n=new Map(t.map(e=>[e.goal_id,e])),r=new Set,i=e.map(e=>{r.add(e.id);let t=n.get(e.id),i=e.latest_runs[0],a=t?.lifecycle_phase??e.lifecycle_phase??i?.lifecycle_phase??dS(t?.status??i?.classification??e.status,i),o=t?.lifecycle_flags?.length?t.lifecycle_flags:e.lifecycle_flags?.length?e.lifecycle_flags:i?.lifecycle_flags?.length?i.lifecycle_flags:[a];return{goal:e,queueItem:t,latestRun:i,status:t?.status??i?.classification??e.status??`no_status`,waitingOn:t?.waiting_on??`clear`,severity:t?.severity??`clear`,lifecyclePhase:a,lifecycleFlags:o}});for(let e of t)r.has(e.goal_id)||i.push({goal:{activation_state:e.activation_state,id:e.goal_id,status:e.status,display_name:e.goal_id,latest_runs:[],lifecycle_flags:[e.lifecycle_phase??`registered`],registry_member:!0,legacy_runtime_goal:!1,index_exists:!1,raw_index_records:0,unique_runs:0},queueItem:e,status:e.status,waitingOn:e.waiting_on,severity:e.severity,lifecyclePhase:e.lifecycle_phase??`registered`,lifecycleFlags:e.lifecycle_flags??[`registered`]});return i}function pS(e){return(e??``).replace(/\s+/g,` `).trim()}function mS(e,t=132){let n=pS(e);return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function hS(e){let t=new Map;for(let n of e?.goals??[])t.set(n.goal_id,n);return t}function gS(e,t){return e===void 0||t===void 0?void 0:e+t}function _S(e,t){if(!e)return null;let n=t===`user`?e.queueItem?.project_asset?.user_todos:e.queueItem?.project_asset?.agent_todos;if(n?.items?.length)return{done_count:n.done??n.items.filter(e=>e.done).length,items:n.items,open_count:n.open??n.items.filter(e=>!e.done).length,total_count:n.total??n.items.length};let r=t===`user`?e.queueItem?.user_todos:e.queueItem?.agent_todos;return r?.items?.length?r:null}function vS(e){return e?.items.find(e=>!e.done)}function yS(e,t,n=`todos`){return e?.items?.length?{advancement_done_count:e.advancement_done_count??t?.advancement_done_count,done_count:e.done??e.items.filter(e=>e.done).length,items:e.items,open_count:e.open??e.items.filter(e=>!e.done).length,total_count:e.total??e.items.length}:t??null}function bS(e){return e?.queueItem?.project_asset?.quota?.state??e?.queueItem?.quota?.state??e?.goal.quota?.state??`waiting`}function xS(e,t,n){let r=[];for(let t of e){let e=_S(t,`agent`);for(let n of e?.items??[])r.push({goalId:t.goal.id,role:`agent`,todo:n})}let i=new Map;for(let e of r){let t=e.todo.claimed_by||`codex`,n=i.get(t)??[];n.push(e),i.set(t,n)}let a=new Map((n?.agents??[]).map(e=>[e.agent_id,e]));return Array.from(new Set([...i.keys(),...a.keys()])).map(e=>{let t=i.get(e)??[],n=a.get(e),r=Array.from(new Set([...t.map(e=>e.goalId),n?.current_todo?.goal_id,...n?.goal_ids??[]].filter(Boolean))),o=(t.filter(e=>!e.todo.done)[0]??t[0])?.goalId??n?.current_todo?.goal_id??r[0]??``,s=n?.last_activity_at??null;return{agentId:e,claimedTodos:t,currentTodo:n?.current_todo??null,evidenceRefs:[],goalIds:r,handoffNote:null,lastActivity:s,nextSafeAction:n?.next_action?.trim()||`Inspect status projection before taking work`,primaryGoalId:o,quotaHints:[],staleClaimHint:null,status:{label:`可用`,summary:`正常运行`,variant:`success`},workspaceRef:null}})}function SS(e){return e?.map(e=>({dataUrl:e.data_url,id:e.id,mimeType:e.mime_type,name:e.name,size:e.size}))}var CS=`loopx.personal-agent-selection.v1`;function wS(){if(typeof window>`u`)return{};try{let e=JSON.parse(window.localStorage.getItem(CS)??`{}`);return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(e=>typeof e[0]==`string`&&typeof e[1]==`string`))}catch{return{}}}var TS={需修复:`danger`,等你:`warning`,等待条件:`info`,推进中:`success`,安静运行:`neutral`,已停止:`neutral`,已完成:`neutral`};function ES(e,t){return pS(t)||e.replace(/^loopx[-_]/i,`LoopX `).split(/[-_]+/).filter(Boolean).map((e,t)=>t===0?`${e.slice(0,1).toUpperCase()}${e.slice(1)}`:e).join(` `)}function DS(e){return e.split(/\r?\n/u).filter(e=>!/^\s*GOAL_(STATUS|PROGRESS)\s*:/u.test(e)).map(e=>/^\s*GOAL_EVIDENCE\s*:/u.test(e)?e.replace(/^\s*GOAL_EVIDENCE\s*:/u,`验证依据:`):/^\s*NEXT_ACTION\s*:/u.test(e)?e.replace(/^\s*NEXT_ACTION\s*:/u,`下一步:`):e).join(` -`).trim()}function OS(e,t){return[`agent`,`assistant`].includes(e.trim().toLowerCase())&&t.trim().length>0}var kS=`已发现的项目 Agent`;function AS(e){switch(sy(e)){case`codex`:return`Codex`;case`claude`:return`Claude Code`;case`kiro`:return`Kiro CLI`;case`trae`:return`Trae CLI Agent`;case`coco`:return`Coco Agent`;default:return ES(e)}}function jS(e,t){switch(cy(e,t)){case`codex`:return`代码与项目执行`;case`claude`:return`复杂分析与长任务`;case`openai`:case`anthropic`:return`管家问答 · 无工具`;case`kiro`:return`终端编码 · 原生 /goal 循环`;case`trae`:return`前端与交互实现`;case`coco`:return`通用任务`;default:return kS}}function MS(e,t){let n=e.project_asset;return t===`user`?yS(n?.user_todos,e.user_todos,`project_asset.user_todos`):yS(n?.agent_todos,e.agent_todos,`project_asset.agent_todos`)}function NS(e){return mS(e.title??e.text,112)}function PS(e){let t=e.resume_condition?.resume_receipt;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t.receipt_id;return typeof n==`string`&&n.trim()?n.trim():null}function FS(e,t){return{resumeWhen:e.resume_when??null,resumeReady:e.resume_ready??null,resumeReceiptId:PS(e),claimedBy:e.claimed_by??null,done:e.status!==`deferred`&&e.done,evidence:e.evidence?mS(e.evidence,96):null,index:e.index,priority:e.priority??null,status:e.status??null,taskClass:e.task_class??null,taskDomain:e.task_domain??null,text:NS(e),todoId:e.todo_id?.trim()||`${t.goal.id}:agent:${e.index}`}}function IS(e){let t=e.queueItem?.agent_todos,n=t?.items??e.queueItem?.project_asset?.agent_todos?.items??[],r=new Map(n.map(t=>[t.todo_id?.trim()||`${e.goal.id}:agent:${t.index}`,t]));for(let n of t?.deferred_items??[]){let t=n.todo_id?.trim()||`${e.goal.id}:agent:${n.index}`;r.has(t)||r.set(t,n)}return[...r.values()]}function LS(e){return IS(e).map(t=>FS(t,e))}function RS(e,t,n){let r=new Map;for(let n of e.todo_index?.items??[]){if(n.goal_id!==t.goal.id||n.role!==`agent`)continue;let e=FS(n,t);r.set(e.todoId,e)}for(let e of n)r.has(e.todoId)||r.set(e.todoId,e);let i=new Map;for(let e of r.values()){if(e.done||e.taskClass!==`advancement_task`)continue;let t=e.taskDomain?.trim();t&&i.set(t,(i.get(t)??0)+1)}return[...i].map(([e,t])=>({domain:e,matchingTodoCount:t}))}function zS(e,t){return{claimedBy:e.claimed_by??null,done:e.status===`done`||e.status===`completed`,index:-1,priority:e.priority??null,status:e.status??null,taskClass:e.task_class??null,text:mS(e.title,112),todoId:e.todo_id?.trim()||`${t.goal.id}:agent:${e.claimed_by??`unknown`}:current`}}function BS(e,t,n){let r=new Map(e.map(e=>[e.todoId,e]));for(let e of t){let t=e.currentTodo;if(!t||t.goal_id!==n.goal.id)continue;let i=zS(t,n);r.has(i.todoId)||r.set(i.todoId,i)}return[...r.values()]}function VS(e){let t=e.queueItem?.project_asset?.agent_todos,n=e.queueItem?.agent_todos,r=IS(e),i=t?.advancement_done_count??n?.advancement_done_count??t?.done??n?.done_count??null,a=r.filter(e=>e.done&&e.status!==`deferred`).length,o=Math.max(i??0,a),s=new Set(r.map(e=>e.todo_id?.trim()).filter(e=>!!e)),c=(t?.recent_completed_advancement_items??[]).filter(e=>!e.todo_id?.trim()||!s.has(e.todo_id.trim())).map(t=>FS(t,e)),l=r.find(e=>!e.done);return{doneTodoCount:o,nextTodoText:pS(t?.next??``)||(l?pS(l.title??``)||pS(l.text??``):``)||null,recentCompleted:c}}function HS(e,t){let n=pS(e);return n?/\b(state_file|registry_goal|authority_sources|source_registry)\b|\b[a-z_]+\s+\d+\/\d+/i.test(n)?t(`projection.goalVerified`):Ux(n,t,`projection.validationRecorded`):``}function US(e,t=4){if(e.length<=t)return e;let n=e.findIndex(e=>!e.done);if(n<0)return e.slice(-t);let r=Math.max(0,Math.min(n-2,e.length-t));return e.slice(r,r+t)}function WS(e,t,n){let r=t.queueItem?.project_asset?.latest_validation,i=t.latestRun,a=e.event_ledger_summary?.goals.find(e=>e.goal_id===t.goal.id);if(!r&&!i&&!a)return null;let o=[HS(r?.summary,n),Ux(i?.health_check,n),Ux(i?.recommended_action,n)].find(e=>e!==``&&e!==`暂无`)??n(`projection.runRecorded`),s=Gx({eventCount:a?.events_24h??0,hasArtifact:!!(i?.json_exists||i?.markdown_exists),hasLatestValidation:!!r},n);return{generatedAt:r?.generated_at??i?.generated_at??a?.latest_event_at??``,label:s.label,metadata:s.metadata,runId:i?`${t.goal.id}:${i.generated_at}`:null,safePreview:[o,s.metadata].filter(Boolean).join(` -`),summary:o,todoId:t.queueItem?.project_asset?.agent_todos?.items.find(e=>!e.done)?.todo_id??null}}function GS(e){return[e.status,e.goal.status,e.latestRun?.classification,e.lifecyclePhase].filter(Boolean).some(e=>/(^|[_\s-])(done|complete|completed|finished|terminal|closed|success)([_\s-]|$)/i.test(e??``))}function KS(e,t){return e.global_registry?.findings?.find(e=>e.severity===`high`&&(e.goal_id===t.goal.id||e.goal_ids.includes(t.goal.id)))}function qS(e){return[e.status,e.goal.status,e.latestRun?.classification,e.lifecyclePhase].filter(Boolean).some(e=>/(^|[_\s-])(failure|failed|error|broken|unhealthy|blocked[_\s-]?health|health[_\s-]?blocked)([_\s-]|$)/i.test(e??``))}function JS(e,t){let n=t.queueItem?.stale_latest_run_warning;return t.severity===`high`||!!KS(e,t)||!!(n?.requires_refresh_state||n?.severity===`high`)||qS(t)}function YS(e,t){let n=KS(e,t);return t.queueItem?.stale_latest_run_warning?.recommended_action??t.queueItem?.stale_latest_run_warning?.reason??n?.recommended_action??n?.message??t.queueItem?.recommended_action??t.latestRun?.recommended_action??null}function XS(e){let t=e.latestRun?.operator_gate,n=t?.decision?.trim().toLowerCase()??``,r=new Set([`approve`,`approved`,`reject`,`rejected`,`defer`,`deferred`,`cancel`,`cancelled`]),i=[e.queueItem?.recommended_action,e.latestRun?.recommended_action].filter(Boolean).join(` `),a=/(?:等待|需要)(?:用户|你|owner).{0,24}(?:批准|确认|授权|补充|选择|决定)|(?:批准|确认|授权).{0,16}(?:后|才能|方可)/i.test(i);return!!(t&&!r.has(n))||e.lifecyclePhase===`operator_gated`&&!r.has(n)||a}function ZS(e,t){let n=e.latestRun?.operator_gate;return Ux(n?.operator_question??n?.reason_summary??n?.follow_up??e.queueItem?.recommended_action??e.latestRun?.recommended_action,t,`projection.confirmAgentDecision`)}function QS(e,t){if(t.goal.activation_state===`stopped`)return`已停止`;let n=_S(t,`user`),r=_S(t,`agent`),i=!!vS(n),a=!!vS(r);return[`user_or_controller`,`controller`].includes(t.waitingOn)||i||XS(t)?`等你`:JS(e,t)?`需修复`:t.waitingOn===`external_evidence`?`等待条件`:bS(t)===`eligible`||a?`推进中`:GS(t)?`已完成`:`安静运行`}function $S(e,t,n,r){if(n===`已停止`)return Wx(`stopped`,r);if(n===`需修复`)return Ux(YS(e,t),r,`projection.statusRefreshNeeded`);if(n===`等你`)return Wx(`needs_you`,r);if(n===`推进中`){let e=[(_S(t,`agent`)?.items??[]).filter(e=>!e.done).flatMap(e=>[e.title,e.text]).map(e=>pS(e)).find(e=>e!==``&&e!==`暂无`),t.queueItem?.recommended_action,t.latestRun?.recommended_action].map(e=>pS(e)).find(e=>e!==``&&e!==`暂无`);return e?Ux(e,r,`projection.agentAdvancingGoal`):Wx(`advancing`,r)}return Wx(n===`等待条件`?`waiting_external`:`idle`,r)}function eC(e,t){return t.some(t=>e.includes(t))}function tC(e,t,n){if(t.goals.some(e=>e.activationState===`active`&&e.loadState))return{text:`Goal 状态尚未全部加载,暂不能给出完整统计。可先打开已加载的 Goal,失败项可重试。`,lines:[]};if(eC(n,[`Agent`,`agent`,`推进`,`在做`])){let e=t.goals.filter(e=>![`安静运行`,`已完成`,`已停止`].includes(e.state)),n=(e.length>0?e:t.goals).slice(0,3);return n.length===0?{text:`当前状态里还没有 Goal 可供汇总。`,lines:[]}:{text:e.length>0?`Agent 当前关注这些 Goal:`:`当前 Goal 都比较安静:`,lines:n.map(e=>`${e.title} · ${e.state} · ${e.agentSentence}`)}}if(eC(n,[`现在`,`下一步`,`我该`,`该做什么`,`优先处理`])){let e=t.userTodos[0];if(e)return{text:e.blocking?`先处理「${ES(e.goalId)}」:${e.text}`:`当前最先处理「${ES(e.goalId)}」:${e.text}`,lines:[]};let n=t.goals.find(e=>e.state===`需修复`);if(n)return{text:`没有待办,但这个 Goal 需要先修复。`,lines:[`${n.title} · ${n.agentSentence}`]};let r=t.goals.find(e=>e.state===`推进中`);return r?{text:`目前不需要你介入,Agent 正在推进。`,lines:[`${r.title} · ${r.agentSentence}`]}:{text:`当前系统很安静,没有需要你立即处理的事项。`,lines:[]}}if(eC(n,[`等我`,`阻塞`,`需要我`,`全局待办`]))return t.userTodos.length===0?{text:`目前没有 Goal 在等你,开放用户待办为 0。`,lines:[]}:{text:`有 ${t.userTodos.length} 项开放用户待办,阻塞项优先:`,lines:t.userTodos.slice(0,3).map(e=>`${ES(e.goalId)} · ${e.blocking?`阻塞`:`待处理`} · ${e.text}`)};if(eC(n,[`状态`,`异常`,`修复`,`健康`])){let n=t.systemHealth?!t.systemHealth.ok:!e.ok||!e.contract?.ok||!e.global_registry?.ok||(e.global_registry?.summary?.high??0)>0,r=t.goals.filter(e=>e.state===`需修复`),i=r.slice(0,n?2:3).map(e=>`${e.title} · ${e.agentSentence}`);return n&&i.push(`全局状态、契约或注册表健康检查未通过,请进入管理页检查。`),i.length===0?{text:`当前没有发现 Goal 级或全局健康异常。`,lines:[]}:{text:r.length>0?`当前需要关注这些健康问题:`:`Goal 状态正常,但全局健康需要检查:`,lines:i}}return{text:`当前管家支持三类问题:下一步、等待你的事项、Agent 与健康状态。`,lines:[`问“我现在该做什么?”`,`问“哪些 Goal 在等我?”`,`问“Agent 在做什么?”或当前健康状态`]}}function nC(e,t,n,r=!1){let i=new Map(t.map(e=>[e.goal.id,e])),a=new Set(e.run_history.goals.filter(e=>e.activation_state===`stopped`).map(e=>e.id)),o=hS(e.usage_summary),s=xS(t,e.todo_index,e.agent_management_projection),c=e.attention_queue.items.flatMap((e,t)=>{if(a.has(e.goal_id))return[];let n=[`user_or_controller`,`controller`].includes(e.waiting_on);return(MS(e,`user`)?.items??[]).map((r,i)=>({projectedDone:r.done,details:Ud(r),actionKind:r.action_kind??null,blocking:n,goalId:e.goal_id,sourceOrder:t,taskClass:r.task_class??null,text:NS(r),todoId:r.todo_id?.trim()||`${e.goal_id}:user:${r.index}`,todoOrder:i,updatedAt:r.updated_at??null}))}),l=c.filter(e=>!e.projectedDone),u=new Set(l.map(e=>e.goalId)),d=t.flatMap((t,r)=>a.has(t.goal.id)||u.has(t.goal.id)||!XS(t)?[]:[{details:Ud({task_class:`user_gate`,status:`open`,note:t.latestRun?.operator_gate?.reason_summary}),actionKind:`gate.resolve`,blocking:!0,goalId:t.goal.id,sourceOrder:e.attention_queue.items.length+r,taskClass:`user_gate`,text:ZS(t,n),todoId:`${t.goal.id}:operator-gate`,todoOrder:0,updatedAt:t.latestRun?.operator_gate?.recorded_at??t.latestRun?.generated_at??null}]),f=[...l,...d].sort((e,t)=>Number(t.blocking)-Number(e.blocking)||e.sourceOrder-t.sourceOrder||e.todoOrder-t.todoOrder),p=e.run_history.goals.flatMap(t=>{if(t.registry_member===!1)return[];let a=i.get(t.id);if(!a)return[];let c=QS(e,a),l=f.find(e=>e.goalId===t.id),u=l?.text??null,d=VS(a),p=t.coordination?.registered_agents??[],m=new Set(p),h=[...s.filter(e=>e.goalIds.includes(t.id)&&!/unassigned|unknown/i.test(e.agentId)&&(m.size===0||m.has(e.agentId))&&(e.currentTodo?.goal_id===t.id||e.claimedTodos.some(e=>e.goalId===t.id)))].sort((e,t)=>(t.lastActivity??``).localeCompare(e.lastActivity??``)),g=new Set(h.map(e=>e.agentId)),_=[...h.map(e=>({agentId:e.agentId,label:e.agentId,lastActivityAt:e.lastActivity,state:e.status.label})),...p.filter(e=>!g.has(e)).map(e=>({agentId:e,label:e,lastActivityAt:null,state:`registered`}))],v=h[0],y=BS(LS(a),h,a),b=[d.nextTodoText,a.queueItem?.recommended_action,a.latestRun?.recommended_action,$S(e,a,c,n)].map(e=>Ux(e,n)).find(e=>e!==``&&e!==`暂无`)??n(`projection.nextUpdatePending`);return[{activationState:t.activation_state,agentId:v?.agentId??p[0]??`codex`,agentLaneCount:_.length,agentLanes:_,agentLabel:v?.agentId,agentSentence:$S(e,a,c,n),agentTodos:[...y,...d.recentCompleted],doneTodoCount:d.doneTodoCount,acceptanceObservation:t.acceptance_observation,goalId:t.id,latestActivity:a.latestRun?.generated_at??``,needsYou:u,needsYouActionKind:l?.actionKind??null,needsYouBlocking:l?.blocking??!1,needsYouTaskClass:l?.taskClass??null,needsYouTodoId:l?.todoId??null,nextSentence:b,runEvidence:WS(e,a,n),state:c,...r?{subagentExecution:{allowedDomains:t.spawn_policy?.allowed_domains??[],domainCandidates:RS(e,a,y),enabled:t.spawn_policy?.mode===`multi_subagent`&&t.spawn_policy.spawn_allowed===!0&&t.spawn_policy.max_children>0,maxChildren:t.spawn_policy?.max_children??0,modelConfig:t.spawn_policy?.model_config}}:{},title:ES(t.id,t.display_name),usage:(()=>{let e=o.get(t.id);return e?{costUsd24h:e.cost_usd_24h,costUsd7d:e.cost_usd_7d,durationMs24h:e.duration_ms_24h,durationMs7d:e.duration_ms_7d,tokens24h:gS(e.input_tokens_24h,e.output_tokens_24h),tokens7d:gS(e.input_tokens_7d,e.output_tokens_7d)}:null})()}]}),m=[];if(e.ok||m.push(`状态载荷未标记为正常 (payload.ok === false)`),e.contract&&!e.contract.ok){let t=e.contract.summary,n=t?`${t.errors} 项错误 / ${t.warnings} 项警告`:e.contract.errors?.[0]||`请检查控制面契约`;m.push(`契约检查未通过: ${n}`)}if(e.global_registry){e.global_registry.ok||m.push(`注册表状态异常: ${e.global_registry.summary.high} 项高危`);for(let t of e.global_registry.findings||[])t.severity===`high`&&m.push(`[${t.kind}] ${t.message}`)}let h=e.decision_freshness_summary?.summary?.stale_count?`${e.decision_freshness_summary.summary.stale_count} 项决策状态已过期`:null,g=m.length===0&&!h,_={ok:g,summary:g?`所有控制面契约与注册表检查均正常`:`发现 ${m.length+ +!!h} 项系统健康关注点`,issues:m,freshnessWarning:h};return{blockingTodoCount:f.filter(e=>e.blocking).length,goalNotifications:(e.goal_channel_notification_projection?.goals??[]).map(e=>({goalId:e.goal_id,configured:e.configured,enabled:e.enabled,humanGateAutoNotifyEnabled:e.human_gate_auto_notify_enabled,lastNotifiedAt:e.last_notified_at??null,receiptCount:e.receipt_count,targetRef:e.target_ref??null})),goals:p,openUserTodoCount:f.length,systemHealth:_,attentionHistory:[...c,...d],userTodos:f,visibleUserTodos:f.slice(0,5),workers:(e.agent_management_projection?.agents??[]).map(e=>({agentId:e.agent_id,currentTodoGoalId:e.current_todo?.goal_id??null,currentTodoText:e.current_todo?.title?mS(e.current_todo.title,96):null,lastActivityAt:e.last_activity_at??null,state:e.state??null}))}}function rC({goalArchiveLoadState:e,isLoading:t,onGoalActivationStateChange:n,onGoalDeleted:r,onSelectGoal:i,onReconcileStatus:a,onRefresh:o,onRetryGoalArchive:s,payload:c,progress:l,rows:u,selectedGoalId:d,statusSourceControl:f,theme:p,toggleTheme:m}){let h=f.activeSource.readOnly,g=f.activeSource.kind===`ssh_tunnel`?f.activeSource.hostAlias:void 0,{t:_}=qi(),[v,y]=(0,B.useState)([]),[b,x]=(0,B.useState)(!1),S=(0,B.useMemo)(()=>{let e=nC(c,u,_,b);if(!l)return e;let t=Object.values(l.snapshots).map(e=>nC(e,fS(e.run_history.goals,e.attention_queue.items),_,b)),n=new Map(t.flatMap(e=>e.goals).map(e=>[e.goalId,e])),r=e.goals.map(e=>n.get(e.goalId)??{...e,loadError:l.errors[e.goalId],loadState:l.errors[e.goalId]?`error`:`loading`,agentId:``,agentSentence:``,nextSentence:``,subagentExecution:void 0}),i=t.flatMap(e=>e.userTodos),a=r.some(e=>e.activationState===`active`&&e.loadState),o=[...new Set(t.flatMap(e=>e.systemHealth?.issues??[]))];return{...e,goals:r,userTodos:i,attentionHistory:t.flatMap(e=>e.attentionHistory??e.userTodos),visibleUserTodos:i.slice(0,5),openUserTodoCount:i.length,blockingTodoCount:i.filter(e=>e.blocking).length,workers:[...new Map(t.flatMap(e=>e.workers??[]).map(e=>[e.agentId,e])).values()],goalNotifications:t.flatMap(e=>e.goalNotifications??[]),systemHealth:a||t.length===0?void 0:{ok:t.every(e=>e.systemHealth?.ok),issues:o,summary:o.length?`发现 ${o.length} 项系统健康关注点`:`状态检查已完成`,freshnessWarning:t.map(e=>e.systemHealth?.freshnessWarning).filter(Boolean).join(`;`)||null}}},[c,u,l,b,_]),C=S.goals.find(e=>e.goalId===d)??null,w=l?.snapshots[d]??c,[T,E]=(0,B.useState)(null),[D,O]=(0,B.useState)(null),[ee,te]=(0,B.useState)(!1),ne=S.goals.some(e=>e.activationState===`active`&&e.loadState===`loading`)?`loading`:S.goals.map(e=>`${e.goalId}:${e.agentId}`).join(`|`),k=C?.goalId??`manager`;S.goals.some(e=>e.activationState===`active`&&e.loadState)||(S.systemHealth?!S.systemHealth.ok:!c.ok)||S.openUserTodoCount>0&&`${S.openUserTodoCount}${S.blockingTodoCount}`;let A=v.length>0?v.map(e=>({agentId:e.agent_id,adapterKind:e.adapter_kind,available:e.available,capability:jS(e.agent_id,e.adapter_kind),interrupt:e.interrupt,label:e.display_name,location:e.location,resume:e.resume,source:e.source,statusLabel:e.available?`可用`:`需要配置`,streaming:e.streaming,toolCalls:e.tool_calls,trustScope:e.trust_scope})):[{agentId:`codex`,available:!0,capability:jS(`codex`),label:`Codex`,statusLabel:`正在检测`}],j=[...A,{agentId:`status-only`,available:!0,capability:`不调用模型`,adapterKind:`status_projection`,interrupt:!1,label:`仅查状态`,resume:!0,statusLabel:`只读`,streaming:!1,toolCalls:!1,trustScope:`read_only`}],M=A.find(e=>e.label===`Codex`&&e.available)?.agentId??A.find(e=>e.available)?.agentId??`status-only`,[N,P]=(0,B.useState)(wS),F=uh(j,N[k]??M,M),[re,ie]=(0,B.useState)(!1),[I,ae]=(0,B.useState)(!1),[L,oe]=(0,B.useState)(`chat`),[se,ce]=(0,B.useState)(``),[le,ue]=(0,B.useState)({}),[de,R]=(0,B.useState)({}),[fe,pe]=(0,B.useState)(null),[me,he]=(0,B.useState)({}),[ge,_e]=(0,B.useState)([]),[ve,ye]=(0,B.useState)(null),[be,xe]=(0,B.useState)({}),Se=(0,B.useRef)(1),Ce=(0,B.useRef)(1),we=(0,B.useRef)(new Map),Te=(0,B.useRef)(new Set),z=(0,B.useRef)(new Map),Ee=(0,B.useRef)(new Map),De=(0,B.useRef)(new Set),Oe=(0,B.useRef)(new Set),ke=(0,B.useRef)(null),Ae=(0,B.useRef)(null),je=(0,B.useRef)(null),Me=(0,B.useRef)(null);(0,B.useRef)(null);let Ne=le[k]??[];de[k];let Pe=C?S.userTodos.filter(e=>e.goalId===C.goalId):S.userTodos,H=C?.agentTodos??[];US(H,C?.needsYou?3:4);let Fe=H.filter(e=>e.done).length,Ie=H.length>0?`${Fe}/${H.length}`:`暂无计划`;C&&({...S},Pe.filter(e=>e.blocking).length,Pe.length),(0,B.useEffect)(()=>{let e=rh(f.activeSource.statusUrl,window.location.href),t=e.source?sh(w,e.source):null;if(!C||!t?.indexUrl||!t.detailUrl){E(null),O(null),te(!1);return}let{detailUrl:n,indexUrl:r}=t,i=!1;return E(null),O(null),te(!0),ch(r,C.goalId).then(async e=>{let t=e.items[0]?.detail_ref;return t?lh(n,t):null}).then(e=>{i||E(e)}).catch(e=>{i||O(Dp(e))}).finally(()=>{i||te(!1)}),()=>{i=!0}},[w,C?.goalId,f.activeSource.statusUrl]);let Le=C?void 0:me[k]?.sessionId;(0,B.useEffect)(()=>{if(h||!Le)return;let e=!1,t,n=async()=>{try{let t=await zh(Le);if(e)return;let n=t.messages.filter(e=>e.origin===`manager_followup`);ue(e=>{let t=e[k]??[],r=new Set(t.map(e=>e.sourceMessageId)),i=n.filter(e=>!r.has(e.message_id));return i.length?{...e,[k]:[...t,...i.map(e=>({id:Se.current++,sourceMessageId:e.message_id,role:`assistant`,agentLabel:F.label,sourceLabel:`管家交接回执`,text:DS(e.text),lines:[]}))]}:e})}catch{}finally{e||(t=setTimeout(n,3e3))}};return n(),()=>{e=!0,t&&clearTimeout(t)}},[h,Le,k,F.label]);function Re(e,t){he(n=>{if(t===null){let t={...n};return delete t[e],t}return{...n,[e]:t}})}(0,B.useEffect)(()=>{if(h){y([]),x(!1);return}let e=!1;return Ih().then(t=>{e||(y(t.adapters??[]),x(t.goal_subagent_configuration===`preview_locked`))}).catch(()=>{e||x(!1)}),()=>{e=!0}},[h]),(0,B.useEffect)(()=>{try{window.localStorage.setItem(CS,JSON.stringify(N))}catch{}},[N]),(0,B.useEffect)(()=>{if(h||!F.available)return;let e=k,t=`${e}:${F.agentId}`,n=C?`goal`:`manager`,r=C?`goal.${C.goalId}`:`manager`,i=!1,a=null,o=null;return(async()=>{try{let s=await Hh({agentId:F.agentId,channelId:r,goalId:C?.goalId});if(i||(ue(t=>(t[e]?.length??0)>0?t:{...t,[e]:s.messages.map(e=>({sourceMessageId:e.message_id,agentLabel:e.role===`user`?void 0:F.label,attachments:SS(e.attachments),id:Se.current++,lines:[],role:e.role===`user`?`user`:`assistant`,sourceLabel:e.role===`user`?void 0:e.role===`error`?`本地会话记录`:`恢复的 ${F.label} 会话`,text:e.role===`user`?e.text:DS(e.text)}))}),F.agentId===`status-only`))return;let c=s.sessions[0];if(o=c?.session_id??null,c&&!c.resumable){Te.current.add(t),Re(e,{agentId:F.agentId,resumable:!1,sessionId:c.session_id,status:`resume_failed`});return}let l=n===`manager`?``:C?.goalId??``;if(n===`goal`&&!l)return;let u=await Rh(l,F.agentId,`resume_latest`,n);if(i)return;we.current.set(t,u.session_id);let d=s.snapshots.find(e=>e.session.session_id===u.session_id),f=d?.session.active_turn_id??``;if(Re(e,{agentId:F.agentId,resumable:!0,sessionId:u.session_id,status:f?`running`:`ready`,turnId:f||void 0}),Te.current.delete(t),!f)return;let p=`${u.session_id}:${f}`;if(Oe.current.has(p))return;Oe.current.add(p),z.current.set(e,f),Re(e,{agentId:F.agentId,resumable:!0,sessionId:u.session_id,status:`running`,turnId:f}),pe(e),a=new AbortController,Ee.current.set(e,a);let m=``,h=ze(e,{activity:[`正在恢复进行中的 Agent 回合`],agentLabel:F.label,lines:[],pending:!0,sourceLabel:`恢复的 ${F.label} 会话`,text:``});try{let t=await Yh(u.session_id,f,{signal:a.signal,onDelta:t=>{m+=t,Be(e,h,{text:m})},onActivity:t=>{ue(n=>({...n,[e]:(n[e]??[]).map(e=>e.id===h?{...e,activity:[...new Set([...e.activity??[],t])].slice(-6)}:e)}))}});if(i)return;Be(e,h,{lines:t.response.gate?[t.response.gate.summary,t.response.gate.next_action].filter(Boolean).slice(0,2):[],pending:!1,text:t.response.message||m.trim()||`${F.label} 已完成分析。`});let n=S.goals.find(e=>e.goalId===d?.session.goal_id)??C??S.goals[0]??null;if(n&&t.response.proposals.length>0){let r=t.response.proposals.map(e=>({goalId:n.goalId,id:Ce.current++,previewId:null,proposal:e,receiptLabel:null,state:`candidate`,statusMessage:null}));R(t=>({...t,[e]:[...t[e]??[],...r]}))}}catch(t){if(i)return;Be(e,h,{activity:[],lines:[],pending:!1,reconnect:t instanceof Th&&t.payload.reconnectable===!0,sourceLabel:`LoopX Chat 本地后端`,text:t instanceof Error?t.message:`无法恢复进行中的 Agent 回合。`})}finally{Oe.current.delete(p),z.current.get(e)===f&&z.current.delete(e),Re(e,{agentId:F.agentId,resumable:!0,sessionId:u.session_id,status:`ready`}),Ee.current.get(e)===a&&Ee.current.delete(e),i||pe(t=>t===e?null:t)}}catch(n){if(i)return;n instanceof Th&&n.payload.error_code===`resume_failed`&&(Te.current.add(t),o&&Re(e,{agentId:F.agentId,resumable:!1,sessionId:o,status:`resume_failed`}))}})(),()=>{i=!0,a?.abort()}},[k,S.goals[0]?.goalId,h,C?.goalId,F.agentId,F.available,F.label]),(0,B.useEffect)(()=>{if(h||C||S.goals.length===0||ne===`loading`)return;let e=!1;return Promise.all(S.goals.filter(e=>!e.loadState).map(async e=>{let t=await Bh({agentId:e.agentId,channelId:`goal.${e.goalId}`,goalId:e.goalId});return{goalId:e.goalId,session:t.sessions[0]??null}})).then(t=>{e||he(e=>{let n={...e};for(let e of t)e.session&&(n[e.goalId]={agentId:e.session.agent_id,resumable:e.session.resumable,sessionId:e.session.session_id,status:e.session.active_turn_id?`running`:e.session.status,turnId:e.session.active_turn_id??void 0});return n})}).catch(()=>{}),()=>{e=!0}},[h,ne,C?.goalId]),(0,B.useEffect)(()=>{if(ye(null),h){_e([]),xe({});return}if(!C){_e([]),xe({});return}let e=!1,t=0,n=0;_e([]),xe({});let r=async()=>{if(!e){if(document.hidden){t=window.setTimeout(()=>void r(),1e4);return}try{let t=await Bh({goalId:C.goalId});if(!e){let r=t.sessions.filter(e=>e.channel_id?.startsWith(`task.`));_e(r);let i=await Promise.allSettled(r.map(e=>zh(e.session_id)));if(!e){let e=i.some(e=>e.status===`rejected`);n=e?n+1:0,ye(e?`partial`:null),xe(Object.fromEntries(i.flatMap((e,t)=>e.status===`fulfilled`?[[r[t].session_id,e.value]]:[])))}}}catch{n+=1,e||ye(`offline`)}e||(t=window.setTimeout(()=>void r(),Math.min(3e4,2e3*2**Math.min(n,4))))}};return r(),()=>{e=!0,window.clearTimeout(t)}},[h,C?.goalId]),(0,B.useEffect)(()=>{if(!re)return;let e=window.requestAnimationFrame(()=>{ke.current?.querySelector(`[role="menuitem"]:not(:disabled)`)?.focus()});return()=>{window.cancelAnimationFrame(e),Ae.current?.focus()}},[re]),(0,B.useEffect)(()=>{if(!I)return;let e=window.requestAnimationFrame(()=>je.current?.focus());return()=>{window.cancelAnimationFrame(e),Me.current?.focus()}},[I]),(0,B.useEffect)(()=>{if(!re&&!I)return;let e=e=>{e.key===`Escape`&&(ie(!1),ae(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[re,I]);function ze(e,t){let n=Se.current++;return ue(r=>({...r,[e]:[...r[e]??[],{...t,id:n,role:`assistant`}]})),n}function Be(e,t,n){ue(r=>({...r,[e]:(r[e]??[]).map(e=>e.id===t?{...e,...n}:e)}))}async function Ve(e,t){let n=e.trim();if(!n)return;let r=t&&`goalId`in t?t.goalId??`manager`:k,i=r===`manager`?null:S.goals.find(e=>e.goalId===r)??null,a=t?.agentId?uh(j,t.agentId,M):F,o=r===`manager`?S:i?{...S,blockingTodoCount:S.userTodos.filter(e=>e.goalId===i.goalId&&e.blocking).length,goals:[i],openUserTodoCount:S.userTodos.filter(e=>e.goalId===i.goalId).length,userTodos:S.userTodos.filter(e=>e.goalId===i.goalId),visibleUserTodos:S.userTodos.filter(e=>e.goalId===i.goalId)}:S,s=Se.current++;if(ue(e=>({...e,[r]:[...e[r]??[],{attachments:t?.attachments,id:s,lines:[],role:`user`,text:n}]})),ce(``),pe(r),a.agentId===`status-only`||!i&&r!==`manager`){let e=tC(w,o,n),t=a.agentId===`status-only`;ze(r,{agentLabel:t?`仅查状态`:`LoopX 管家`,lines:e.lines.slice(0,3),sourceLabel:t?`LoopX 状态投影 · 仅查状态`:`LoopX 状态投影`,text:e.text}),Lh({answer:[e.text,...e.lines.slice(0,3)].filter(Boolean).join(` -`),contextKind:r===`manager`?`manager`:`goal`,goalId:r===`manager`?void 0:r,question:n}).catch(()=>{}),pe(null);return}let c=`${r}:${a.agentId}`,l=null;try{let e=we.current.get(c);if(!e){let t=Te.current.has(c)?`new`:`resume_latest`;e=(await Rh(r===`manager`?``:i.goalId,a.agentId,t,r===`manager`?`manager`:`goal`)).session_id,we.current.set(c,e),Re(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`ready`}),Te.current.delete(c)}let o=``;l=ze(r,{activity:[`正在连接 Agent`],agentLabel:a.label,lines:[],pending:!0,sourceLabel:r===`manager`?`${a.label} 管家 · 跨 Goal`:`${a.label} Agent · ${ES(i.goalId)}`,text:``});let s=(await qh(e,n,{attachments:t?.attachments,signal:(()=>{let e=new AbortController;return Ee.current.set(r,e),e.signal})(),onDelta:e=>{o+=e,l!==null&&Be(r,l,{text:o})},onActivity:e=>{l!==null&&ue(t=>({...t,[r]:(t[r]??[]).map(t=>t.id===l?{...t,activity:[...new Set([...t.activity??[],e])].slice(-6)}:t)}))},onPhase:(t,n)=>{z.current.set(r,n),Re(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`running`,turnId:n})}})).response;if(Be(r,l,{lines:s.gate?[s.gate.summary,s.gate.next_action].filter(Boolean).slice(0,2):[],pending:!1,text:DS(s.message||o.trim())||`${a.label} 已完成分析。`}),s.proposals.length>0&&!i&&Be(r,l,{lines:[`请进入要修改的 Goal,预览并确认具体变更。`]}),s.proposals.length>0&&i){let e=s.proposals.map(e=>({goalId:i.goalId,id:Ce.current++,previewId:null,proposal:e,receiptLabel:null,state:`candidate`,statusMessage:null}));R(t=>({...t,[r]:[...t[r]??[],...e]}))}if(r!==`manager`&&s.protected_action){let e=cS(r,n,s.protected_action);if(e)return e}}catch(e){if(De.current.delete(r)){let e={agentLabel:a.label,lines:[],pending:!1,sourceLabel:`${a.label} 会话`,text:`已中断。你可以在当前会话继续发送消息。`};l===null?ze(r,e):Be(r,l,e);return}let t=e instanceof Th?e.payload:null;t&&dh(t)&&we.current.delete(c),t?.error_code===`resume_failed`&&(we.current.delete(c),Te.current.add(c),Re(r,{agentId:a.agentId,resumable:!1,sessionId:me[r]?.sessionId??`resume-failed`,status:`resume_failed`}));let n=t?.gate,i=n&&typeof n==`object`?String(n.summary??``):``,o={agentLabel:a.label,lines:i?[i]:[],pending:!1,reconnect:t?.reconnectable===!0,sourceLabel:`LoopX Chat 本地后端`,text:t?.error_code===`resume_failed`?`原 ${a.label} 会话无法恢复。本地历史已经保留,请在运行详情里选择“重试恢复”或“开始新 Session”。`:e instanceof Error?e.message:`${a.label} 会话暂时不可用。`};l===null?ze(r,o):Be(r,l,o)}finally{z.current.delete(r),Ee.current.delete(r);let e=we.current.get(c);e&&Re(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`ready`}),pe(e=>e===r?null:e)}}async function He(e){let t=e?.goalId??k,n=me[t],r=e?.agentId??n?.agentId??F.agentId,i=`${t}:${r}`,a=e?.sessionId??n?.sessionId??we.current.get(i),o=e?.turnId??n?.turnId??z.current.get(t);if(!(!a||!o))try{De.current.add(t),await Kh(a,o),Ee.current.get(t)?.abort()}catch(e){throw De.current.delete(t),e}finally{z.current.delete(t),Re(t,{agentId:r,resumable:!0,sessionId:a,status:`ready`}),Ee.current.delete(t),pe(e=>e===t?null:e)}}async function Ue(e){let t=e.goalId,n=`${t}:${e.agentId}`,r=e.sessionId??me[t]?.sessionId??we.current.get(n);if(r)try{let i=await Zh(r);we.current.set(n,r),Te.current.delete(n),Re(t,{agentId:e.agentId,resumable:i.session.resumable,sessionId:r,status:i.session.status})}catch{Re(t,{agentId:e.agentId,resumable:!1,sessionId:r,status:`resume_failed`})}}function We(e){let t=`${e.goalId}:${e.agentId}`;we.current.delete(t),Te.current.add(t),Re(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:`new-session-pending`,status:`ready`})}async function Ge(e){let t=`${e.goalId}:${e.agentId}`,n=e.sessionId??me[e.goalId]?.sessionId??we.current.get(t);n&&n!==`new-session-pending`&&await Xh(n),we.current.delete(t),Te.current.add(t),Re(e.goalId,null)}function Ke(e){j.some(t=>t.agentId===e&&t.available)&&(P(t=>({...t,[k]:e})),ie(!1))}function qe(){i(``),oe(`chat`)}function Je(e){i(e),oe(`chat`)}C&&TS[C.state],C&&(`${F.label}${C.state}`,H.length>0&&`${Ie}`,Pe.length>0&&`${Pe.length}`),C?.state===`需修复`||!C&&!c.ok?(C&&AS(C.agentId),C?.nextSentence,C?.agentSentence):C?.state===`等你`?(C.needsYouBlocking,C.needsYouBlocking,C.needsYou??C.nextSentence,C.needsYou):(C&&AS(C.agentId),C?.nextSentence);let Ye=[...!C&&me.manager?.status===`resume_failed`?[{id:`run:manager:resume-failed`,kind:`run`,run:{agentId:me.manager.agentId,agentLabel:AS(me.manager.agentId),canInterrupt:!1,completedSteps:0,goalId:`manager`,goalTitle:`LoopX 管家`,latestActivity:`本地聊天记录已保留,点我查看恢复方式。`,resumable:!1,runId:`manager:resume-failed`,sessionId:me.manager.sessionId,sessionStatus:`resume_failed`,status:`failed`,title:`上次会话需要恢复`,totalSteps:1,outputs:[]}}]:[],...C?ge.map(e=>{let t=e.channel_id?.startsWith(`task.`)?e.channel_id.slice(5):void 0,n=C.agentTodos.find(e=>e.todoId===t),r=!!e.active_turn_id,i=be[e.session_id],a=i?.messages.some(e=>OS(e.role,e.text))===!0;return{id:`run:task:${e.session_id}`,kind:`run`,run:{agentId:e.agent_id,agentLabel:AS(e.agent_id),canInterrupt:r,completedSteps:n?.done||a?1:0,goalId:C.goalId,goalTitle:C.title,latestActivity:r?`Agent 正在执行,可进入 Session 查看过程或发送纠偏。`:a?`Agent 已返回结果,点击查看结果与完整运行记录。`:`执行 Session 已保留,可继续纠偏或恢复。`,resumable:e.resumable,runId:e.session_id,sessionId:e.session_id,sessionMessages:i?.messages.map(e=>({createdAt:e.created_at,messageId:e.message_id,role:e.role===`user`?`user`:OS(e.role,e.text)?`assistant`:`error`,text:e.role===`user`?e.text:DS(e.text)})),sessionStatus:a?`completed`:e.status,status:n?.done||a?`completed`:r?`running`:e.status===`resume_failed`?`failed`:`waiting`,title:n?.text??`Agent 执行任务`,todoId:t,totalSteps:1,turnId:e.active_turn_id??void 0}}}):[],...C?[{id:`run:${C.goalId}`,kind:`run`,run:{agentId:me[C.goalId]?.agentId??C.agentId,agentLabel:AS(me[C.goalId]?.agentId??C.agentId),canInterrupt:!!me[C.goalId]?.turnId,completedSteps:C.agentTodos.filter(e=>e.done).length,goalId:C.goalId,goalTitle:C.title,latestActivity:C.agentSentence,resumable:me[C.goalId]?.resumable??!0,runId:`goal:${C.goalId}`,sessionId:me[C.goalId]?.sessionId,sessionStatus:me[C.goalId]?.status,status:me[C.goalId]?.turnId?`running`:C.state===`需修复`?`failed`:`waiting`,title:C.nextSentence,totalSteps:C.agentTodos.length||1,turnId:me[C.goalId]?.turnId,outputs:C.runEvidence?[{createdAt:C.runEvidence.generatedAt,kind:`evidence`,outputId:`${C.goalId}:latest-evidence`,title:C.runEvidence.label}]:[]}}]:[],...Ne.map(e=>({id:`message:${e.id}`,kind:`message`,message:{agentLabel:e.agentLabel,attachments:e.attachments,id:String(e.id),pending:e.pending,role:e.role,text:e.text||(e.pending?`Agent 正在处理…`:e.lines.join(` -`))}})),...(C?[C]:S.goals).flatMap(e=>e.runEvidence?[{id:`output:${e.goalId}:${e.runEvidence.generatedAt||`latest`}`,kind:`output`,output:{agentLabel:AS(e.agentId),createdAt:e.runEvidence.generatedAt,goalId:e.goalId,goalTitle:e.title,kind:`evidence`,outputId:`${e.goalId}:latest-evidence`,runId:e.runEvidence.runId??void 0,safePreview:e.runEvidence.safePreview,summary:e.runEvidence.summary,title:e.runEvidence.label,todoId:e.runEvidence.todoId??void 0}}]:[]),...C&&T?[{id:`output:${C.goalId}:report:${T.publication.publication_id}`,kind:`output`,output:{agentId:T.agent_id,agentLabel:AS(T.agent_id),createdAt:T.publication.delivered_at,goalId:C.goalId,goalTitle:C.title,kind:`report`,outputId:T.publication.publication_id,report:{addedCount:T.delta.added_count,changedCount:T.delta.changed_count,deliveredAt:T.publication.delivered_at,generationId:T.generation_id,items:T.delta.items.map(e=>({changeKind:e.change_kind,previousStatus:e.previous_status,sourceRef:e.source_ref,status:e.status,summary:e.summary,title:e.title})),periodEndAt:T.period_window.end_at,periodStartAt:T.period_window.start_at,predecessorPublicationId:T.publication.predecessor_publication_id,publicationId:T.publication.publication_id},safePreview:T.delta.items.map(e=>`${e.change_kind===`added`?`+`:`~`} ${e.title}\n${e.summary}`).join(` - -`),summary:T.summary,title:T.title}}]:[]],Xe=f.connectionState===`connected`,Ze=new Map(S.goals.map(e=>[e.goalId,e.title])),Qe=e=>Wd(e,f.activeSource.statusUrl,Xe&&!l?.errors[e.goalId],Ze.get(e.goalId)),$e={...py(S),userTodos:S.userTodos.map(Qe),attentionHistory:(S.attentionHistory??S.userTodos).map(Qe),periodicReports:{error:D,loading:ee},timeline:Ye};return(0,V.jsxs)(`div`,{className:p===`dark`?`dark`:``,"data-testid":`personal-goal-home`,children:[ve?(0,V.jsx)(`p`,{role:`status`,className:`m-0 bg-amber-50 px-4 py-2 text-sm text-amber-900`,children:_(ve===`partial`?`runs.discoveryPartial`:`runs.discoveryOffline`)}):null,(0,V.jsx)(Bx,{agents:j.map(e=>({adapterKind:e.adapterKind,agentId:e.agentId,available:e.available,capability:e.capability,interrupt:e.interrupt,label:e.label,location:e.location,resume:e.resume,source:e.source,streaming:e.streaming,toolCalls:e.toolCalls,trustScope:e.trustScope,workspaceCompatibility:e.available?`当前 Goal 写入前验证`:`不可用,需先修复 Endpoint`})),callbacks:{onApplyAttention:e=>Je(e.goalId),onCorrectRun:async(e,t)=>{if(!e.sessionId)throw Error(`这个 Run 还没有可纠偏的执行 Session。`);let n=await Mh((await kh({actionKind:`run.correct`,context:{kind:`run`,goal_id:e.goalId,todo_id:e.todoId},idempotencyKey:`workspace-run-correct-${e.sessionId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,message:t,session_id:e.sessionId},summary:`纠偏执行任务:${e.title}`})).proposal_id),r=typeof n.turn?.turn_id==`string`?n.turn.turn_id:void 0;if(Re(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:e.sessionId,status:r?`running`:`ready`,turnId:r}),r){z.current.set(e.goalId,r);let t=new AbortController;Ee.current.set(e.goalId,t);let n=``,i=ze(e.goalId,{activity:[`正在把纠偏送入原执行 Session`],agentLabel:e.agentLabel,lines:[],pending:!0,sourceLabel:`${e.agentLabel} · 执行 Session`,text:``});try{let a=await Yh(e.sessionId,r,{signal:t.signal,onDelta:t=>{n+=t,Be(e.goalId,i,{text:n})}});Be(e.goalId,i,{activity:[],pending:!1,text:DS(a.response.message||n.trim())||`${e.agentLabel} 已完成纠偏。`})}catch(t){let n=De.current.delete(e.goalId);Be(e.goalId,i,{activity:[],pending:!1,text:n?`已中断。你可以在当前会话继续发送消息。`:t instanceof Error?t.message:`纠偏回合失败。`})}finally{z.current.delete(e.goalId),Ee.current.delete(e.goalId),Re(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:e.sessionId,status:`ready`})}}},onCloseRunSession:Ge,onInterruptRun:async e=>He(e),onOpenGoal:Je,onOpenRunSession:async e=>{if(!e.sessionId)return;let t=e.sessionId,n=await zh(t);xe(e=>({...e,[t]:n})),Je(e.goalId),ue(t=>({...t,[e.goalId]:n.messages.map(t=>({agentLabel:t.role===`user`?void 0:e.agentLabel,attachments:SS(t.attachments),id:Se.current++,lines:[],role:t.role===`user`?`user`:`assistant`,sourceLabel:t.role===`user`?void 0:`${e.agentLabel} · 执行 Session`,text:t.role===`user`?t.text:DS(t.text)}))})),Re(e.goalId,{agentId:e.agentId,resumable:n.session.resumable,sessionId:t,status:n.session.active_turn_id?`running`:n.session.status,turnId:n.session.active_turn_id??void 0})},onOpenOutput:e=>Je(e.goalId),...b?{onPreviewGoalSubagentConfiguration:async e=>{let t=await eg(e);return{changed:t.changed,configuration:{allowedDomains:t.after.orchestration.allowed_domains,enabled:t.feature_summary.multi_subagent===`enabled`,maxChildren:t.after.orchestration.max_children,modelConfig:t.after.orchestration.model_config},previewId:t.preview_id}},onApplyGoalSubagentConfiguration:async({previewId:e,...t})=>{let n=await tg(t,e);return{allowedDomains:n.after.orchestration.allowed_domains,enabled:n.feature_summary.multi_subagent===`enabled`,maxChildren:n.after.orchestration.max_children,modelConfig:n.after.orchestration.model_config}}}:{},...g?{onExecuteGoalLifecycle:async({goalId:e,operation:t,reason:n})=>{let r=await _b(g,e,t,n);return{activationState:r.activation_state,projectionVerified:r.projection_verified}}}:{},onGoalActivationStateChange:n,onGoalDeleted:r,onReconcileStatus:a,onRetryGoalArchive:s,onExportOutput:async e=>{let t=[`# ${e.title}`,``,e.summary??``,``,e.safePreview??`此产出没有可用的公开安全预览。`,``,`Goal: ${e.goalId}`,`Todo: ${e.todoId??`unlinked`}`,`Run: ${e.runId??`unlinked`}`].join(` -`),n=URL.createObjectURL(new Blob([t],{type:`text/markdown;charset=utf-8`})),r=document.createElement(`a`);r.href=n,r.download=`${e.outputId.replace(/[^a-z0-9._-]+/gi,`-`)}.md`,r.click(),URL.revokeObjectURL(n)},onRefresh:o,onRetryResumeRun:Ue,onSelectAgent:Ke,onSelectGoal:e=>e?Je(e):qe(),onSendMessage:async(e,t,n,r)=>Ve(e,{agentId:t,goalId:n,attachments:r}),onStartNewRunSession:We},goalArchiveLoadState:e,model:$e,readOnly:h,selectedAgentId:F.agentId,selectedGoalId:C?.goalId??null,statusSourceControl:f})]})}function iC({error:e,isLoading:t,onRetry:n,requestedUrl:r,theme:i,toggleTheme:a}){let o=!!(e&&/failed to fetch|networkerror|load failed/i.test(e)&&r.includes(`status.json`));return(0,V.jsx)(`div`,{className:i===`dark`?`dark`:``,children:(0,V.jsxs)(`main`,{className:`min-h-screen bg-[#f6f7f9] text-slate-950 dark:bg-[#09090b] dark:text-zinc-50`,children:[(0,V.jsxs)(`header`,{className:`flex min-h-16 flex-wrap items-center justify-between gap-3 border-b border-slate-200 bg-white px-4 py-3 dark:border-zinc-800 dark:bg-zinc-950 sm:px-6`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`h1`,{className:`text-xl font-semibold`,children:`LoopX Workspace`}),(0,V.jsx)(`p`,{className:`mt-1 break-all text-sm text-slate-500 dark:text-zinc-400`,children:`Personal Workspace`})]}),(0,V.jsx)(ny,{"aria-label":`切换主题`,onClick:a,size:`icon`,variant:`secondary`,children:i===`dark`?(0,V.jsx)(Jm,{className:`h-4 w-4`}):(0,V.jsx)(km,{className:`h-4 w-4`})})]}),(0,V.jsxs)(`div`,{className:`grid min-h-[calc(100vh-80px)] sm:grid-cols-[240px_1fr]`,children:[(0,V.jsxs)(`aside`,{className:`hidden border-r border-slate-200 p-6 dark:border-zinc-800 sm:block`,"aria-label":`Workspace`,children:[(0,V.jsx)(`strong`,{children:`LoopX`}),(0,V.jsx)(`p`,{className:`mt-6 text-sm`,children:`Workspace`}),(0,V.jsx)(`p`,{className:`mt-8 text-xs text-slate-500`,children:`Goals`}),[1,2,3].map(e=>(0,V.jsx)(`div`,{className:`mt-4 h-8 rounded bg-slate-100 dark:bg-zinc-900`},e))]}),(0,V.jsx)(`div`,{className:`p-4 sm:p-8`,children:(0,V.jsx)(ry,{"data-testid":`initial-status-state`,children:(0,V.jsx)(iy,{className:`flex min-h-64 items-center justify-center p-6`,children:(0,V.jsxs)(`div`,{className:`max-w-xl text-center`,children:[e?(0,V.jsx)(im,{className:`mx-auto h-6 w-6 text-rose-600 dark:text-rose-300`}):(0,V.jsx)(Im,{className:`mx-auto h-6 w-6 animate-spin text-slate-500 dark:text-zinc-400`}),(0,V.jsx)(`p`,{className:`mt-3 text-sm font-medium`,children:e?`无法加载实时状态`:`正在加载实时状态`}),e?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{className:`mt-2 break-words text-sm leading-6 text-slate-500 dark:text-zinc-400`,children:o?`本地状态服务暂时未连接。升级或启动期间可能短暂断开,请重试;仍失败时重新打开 LoopX App,或运行 loopx doctor。`:e}),o?(0,V.jsx)(`p`,{className:`mt-2 text-xs leading-5 text-slate-400 dark:text-zinc-500`,children:`重新加载不会执行任务,也不会改变 Goal 配置。`}):null,(0,V.jsx)(`div`,{className:`mt-4 flex flex-wrap justify-center gap-2`,children:(0,V.jsxs)(ny,{disabled:t,onClick:n,children:[(0,V.jsx)(Im,{className:`h-4 w-4`}),`重试`]})})]}):(0,V.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-500 dark:text-zinc-400`,role:`status`,children:`正在连接 Workspace,Goal 列表将先出现,详细状态会逐个补齐。 / Connecting to your Workspace. Goals load independently.`})]})})})})]})]})})}function aC(){let e=nw.useSearch(),t=nw.useNavigate(),[n,r]=(0,B.useState)(`light`),[i,a]=(0,B.useState)(null),o=(0,B.useRef)(null),s=(0,B.useRef)(e.goalId);s.current=e.goalId;let[c,l]=(0,B.useState)(Op),[u,d]=(0,B.useState)({kind:`example`,label:`bundled example`}),[f,p]=(0,B.useState)(()=>$x(window.localStorage,window.location.href)),m=(0,B.useRef)(f);m.current=f;let[h,g]=(0,B.useState)(e.statusUrl),[_,v]=(0,B.useState)(null),[y,b]=(0,B.useState)(!1),[x,S]=(0,B.useState)({error:null,phase:`idle`}),[C,w]=(0,B.useState)(e.statusUrl.trim()||null),[T,E]=(0,B.useState)(!1),D=(0,B.useRef)(null),O=(0,B.useRef)(Yg(e.statusUrl.trim()||null)),ee=!T&&u.kind===`example`?e.statusUrl.trim():``,te=C??ee,ne=u.kind===`url`?u.label:lS,k=!!(_&&C),A=oS(f,C,ne,window.location.href),j=u.kind===`example`&&!T,M=c.attention_queue,N=c.run_history,P=(0,B.useMemo)(()=>fS(N.goals,M.items),[N.goals,M.items]);function F(e,t,n=0){S({error:null,phase:`loading`}),uS(ah(e,`stopped`,window.location.href)).then(r=>{if(!$g(O.current,t))return;let i=r.goal_projection?.registry_revision??null,a=t.registryRevision!==null&&t.registryRevision!==void 0&&i!==null&&t.registryRevision!==i;if(l(e=>S_(e,r)),a&&n<1){I(e,{background:!0,resyncAttempt:n+1});return}S(a?{error:`Goal 状态在加载历史时发生变化,请重试。`,phase:`error`}:{error:null,phase:`ready`})}).catch(e=>{$g(O.current,t)&&S({error:Dp(e),phase:`error`})})}function re(){let e=u.kind===`url`?u.label:h||lS,t=Zg(O.current,e,{background:!0});if(i){I(e);return}t&&F(e,t)}async function ie(e,n,r){if(r.background)return l(e=>S_(e,n)),!0;let i={kind:`url`,label:e};return O.current.loadedUrl=e,l(n),d(i),g(e),await t({search:t=>({...t,statusUrl:e})}),Qg(O.current,r)?(O.current.requestedUrl=null,w(null),!0):!1}async function I(e,t={}){let n=e.trim(),r=t.background===!0;if(!n){r||v(`状态地址不能为空`);return}let c=Zg(O.current,n,{background:r,selectionRevision:t.selectionRevision});if(!c)return;o.current?.abort();let d=new AbortController;o.current=d,r||(D.current=null,E(!1),w(n),b(!0),v(null),S({error:null,phase:`idle`}));try{let e=await jp(n,window.location.href).catch(()=>null);if(!$g(O.current,c))return;if(e){let o=t.retryOnly&&u.kind===`url`&&u.label===n&&i?.directory.registry_revision===e.registry_revision?i.snapshots:{};a({directory:e,snapshots:o,errors:{}});let f={...e,goals:e.goals.filter(e=>!o[e.id])},p=!1,m=Mp(e);if(r)l(m);else if(!await ie(n,m,c))return;if(S({error:null,phase:`loading`}),await Np(n,window.location.href,f,(e,t,n)=>{n===`revision`&&(p=!0),a(r=>r&&{...r,snapshots:t?{...r.snapshots,[e]:t}:r.snapshots,errors:n?{...r.errors,[e]:n}:r.errors})},()=>$g(O.current,c),()=>s.current,d.signal),p&&(t.resyncAttempt??0)<1&&$g(O.current,c)){await I(n,{resyncAttempt:1});return}$g(O.current,c)&&S({error:null,phase:`ready`});return}let o=await uS(ah(n,`active`,window.location.href));if(!$g(O.current,c)||(a(null),c.registryRevision=o.goal_projection?.registry_revision??null,!await ie(n,o,c)))return;if(o.goal_projection?.scope!==`active`||o.goal_projection.complete){S({error:null,phase:`ready`});return}F(n,c,t.resyncAttempt??0)}catch(e){if(!Qg(O.current,c))return;r||v(Dp(e))}finally{!r&&Qg(O.current,c)&&b(!1)}}function ae(e,t={}){o.current?.abort();let n=Xg(O.current,e.statusUrl);D.current=null,E(!1),w(e.statusUrl),b(!0),v(null),(async()=>{if(t.ensureTunnel&&e.kind===`ssh_tunnel`){let t=new URL(e.statusUrl,window.location.href).port;if(t)try{await gb(e.label,t)}catch{}}O.current.selectionRevision===n&&await I(e.statusUrl,{selectionRevision:n})})()}function L(e){m.current=e,p(e);try{eS(window.localStorage,e)}catch{}}let oe={activeSource:A,connectionState:y?`loading`:k?`error`:`connected`,errorMessage:k?`未切换到 ${C??`所选来源`}:${_}`:null,onAdd:e=>{let t=nS(f,e,window.location.href);return`error`in t?{error:t.error}:(L(t.catalog),ae(t.source,{ensureTunnel:e.ensureTunnel}),{})},onConfiguredHostsLoaded:e=>{let t=m.current,n=tS(t,e);n!==t&&L(n)},onRemove:e=>{L(rS(f,e)),A.id===e&&ae(Jx)},onSelect:e=>{let t=f.sources.find(t=>t.id===e);t&&ae(t,{ensureTunnel:t.kind===`ssh_tunnel`})},sources:A.id===`temporary`?[...f.sources,A]:f.sources};(0,B.useEffect)(()=>{let t=e.statusUrl.trim();if(t){if(D.current===t||C&&C!==t)return;(u.kind!==`url`||u.label!==t)&&I(t);return}D.current=null,!T&&(C||u.kind===`example`&&I(lS))},[T,C,e.statusUrl,u.kind,u.label]),(0,B.useEffect)(()=>{if(e.statusUrl&&u.kind===`example`)return;let n=new Set(P.map(e=>e.goal.id));if(P.length===0){e.goalId&&t({search:e=>({...e,goalId:``})});return}e.goalId&&!n.has(e.goalId)&&x.phase!==`loading`&&t({search:e=>({...e,goalId:``})})},[x.phase,P,t,e.goalId,e.statusUrl,u.kind]),(0,B.useEffect)(()=>{if(!i||y||!e.goalId||u.kind!==`url`)return;let t=i.directory.goals.find(t=>t.id===e.goalId);t?.activation_state===`stopped`&&!i.snapshots[t.id]&&!i.errors[t.id]&&I(u.label,{retryOnly:!0})},[e.goalId,y,i,u]);function se(e){t({search:t=>({...t,goalId:e})})}return j?(0,V.jsx)(iC,{error:_,isLoading:y,onRetry:()=>void I(te||lS),requestedUrl:te||lS,theme:n,toggleTheme:()=>r(n===`dark`?`light`:`dark`)}):(0,V.jsx)(rC,{goalArchiveLoadState:x,isLoading:y,onGoalActivationStateChange:(e,t)=>{O.current.projectionRevision+=1,l(n=>wp(n,e,t)),a(n=>n&&{...n,snapshots:Object.fromEntries(Object.entries(n.snapshots).map(([n,r])=>[n,wp(r,e,t)]))})},onGoalDeleted:e=>{O.current.projectionRevision+=1,l(t=>Tp(t,e)),a(t=>t&&{...t,snapshots:Object.fromEntries(Object.entries(t.snapshots).filter(([t])=>t!==e))})},onSelectGoal:se,onReconcileStatus:()=>I(u.kind===`url`?u.label:h||lS,{background:!0}),onRetryGoalArchive:re,onRefresh:()=>I(u.kind===`url`?u.label:h||lS,{retryOnly:!!(i&&Object.keys(i.errors).length)}),payload:c,progress:i,rows:P,selectedGoalId:e.goalId,statusSourceControl:oe,theme:n,toggleTheme:()=>r(n===`dark`?`light`:`dark`)})}var oC=D_(`inline-flex items-center gap-1 rounded-md border px-2 py-0.5 text-xs font-medium`,{variants:{variant:{neutral:`border-slate-200 bg-white text-slate-700 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-300`,success:`border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-200`,warning:`border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-200`,info:`border-sky-200 bg-sky-50 text-sky-800 dark:border-sky-900 dark:bg-sky-950 dark:text-sky-200`,danger:`border-rose-200 bg-rose-50 text-rose-800 dark:border-rose-900 dark:bg-rose-950 dark:text-rose-200`}},defaultVariants:{variant:`neutral`}});function sC({className:e,variant:t,...n}){return(0,V.jsx)(`span`,{className:ey(oC({variant:t}),e),...n})}var cC=[{label:`status payload`,source:`apps/presentation/dashboard/src/data/status.ts`,detail:`status_contract, attention_queue, local_dashboard_api, run_history`},{label:`channel projection`,source:`apps/presentation/dashboard/src/data/goal-channel-frontstage.ts`,detail:`decision_frame, todos, gates, leases, artifacts, truth_contract`},{label:`public showcase catalog`,source:`docs/showcases/showcase-catalog.json`,detail:`case metadata, visual hints, evidence boundaries, story beats`},{label:`route smoke`,source:`apps/presentation/dashboard/smoke/frontstage-route-smoke.ts`,detail:`static route contract, source guards, component expectations`}],lC=[{axis:`schema`,current:`goal_channel_projection_v0`,proposed:`new optional projection field`,gate:`parser default plus route smoke assertion`},{axis:`truth`,current:`event ledger and active state remain source of truth`,proposed:`derived UI state only`,gate:`truth_contract must stay read-only`},{axis:`privacy`,current:`compact source refs and warnings`,proposed:`public-safe fixture field`,gate:`loopx check and browser fake-private fixture`},{axis:`interaction`,current:`render, filter, select, inspect`,proposed:`no browser write by default`,gate:`write affordance requires explicit loopback capability`}],uC=[{title:`Fixture sources`,body:`Use examples/status.example.json, browser-smoke fixtures, and docs/showcases/showcase-catalog.json.`},{title:`Required proof`,body:`Every projection addition needs parser coverage, route smoke assertions, and one browser or bundle check when UI output changes.`},{title:`Never include`,body:`Raw task text, trajectories, transcripts, local paths, private registry state, credentials, or internal document links.`}],dC=[`npm --prefix apps/presentation/dashboard run smoke:frontstage-route`,`npm --prefix apps/presentation/dashboard run smoke:frontstage-browser`,`npm --prefix apps/presentation/dashboard run smoke:frontstage-share-bundle`,`npm --prefix apps/presentation/dashboard run build`,`loopx check --scan-path apps/presentation/dashboard --scan-path docs/status-data-contract.md`],fC=[{name:`Projection lane`,badges:[`read-only`,`schema v0`],body:`Summarizes one compact projection lane without mutating the underlying LoopX state.`},{name:`Capability badge`,badges:[`loopback`,`dry-run`],body:`Shows an advertised local capability only after the status feed declares it.`},{name:`Boundary warning`,badges:[`public-safe`,`omitted`],body:`Names omitted private material and points contributors back to compact source references.`}];function pC({children:e,icon:t,title:n}){return(0,V.jsxs)(`section`,{className:`rounded-lg border border-slate-200 bg-white shadow-sm`,children:[(0,V.jsx)(`div`,{className:`flex items-center justify-between gap-3 border-b border-slate-200 px-4 py-3`,children:(0,V.jsxs)(`h2`,{className:`flex items-center gap-2 text-sm font-semibold text-slate-950`,children:[(0,V.jsx)(t,{className:`h-4 w-4 text-slate-500`}),n]})}),e]})}function mC(){return(0,V.jsx)(pC,{icon:Qp,title:`Status Contract Explorer`,children:(0,V.jsx)(`div`,{className:`grid gap-3 p-4 lg:grid-cols-2`,"data-testid":`developer-contract-explorer`,children:cC.map(e=>(0,V.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-3`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,V.jsx)(sC,{variant:`info`,children:e.label}),(0,V.jsx)(sC,{variant:`neutral`,children:`public contract`})]}),(0,V.jsx)(`div`,{className:`mt-2 break-words font-mono text-xs text-slate-700`,children:e.source}),(0,V.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:e.detail})]},e.label))})})}function hC(){return(0,V.jsx)(pC,{icon:vm,title:`Projection Diffing`,children:(0,V.jsx)(`div`,{className:`overflow-x-auto`,"data-testid":`developer-projection-diffing`,children:(0,V.jsxs)(`table`,{className:`min-w-full border-separate border-spacing-0 text-left text-sm`,children:[(0,V.jsx)(`thead`,{children:(0,V.jsxs)(`tr`,{className:`bg-slate-50 text-xs uppercase tracking-normal text-slate-500`,children:[(0,V.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Axis`}),(0,V.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Current`}),(0,V.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Proposed`}),(0,V.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Gate`})]})}),(0,V.jsx)(`tbody`,{children:lC.map(e=>(0,V.jsxs)(`tr`,{className:`align-top`,children:[(0,V.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 font-semibold text-slate-950`,children:e.axis}),(0,V.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 text-slate-600`,children:e.current}),(0,V.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 text-slate-600`,children:e.proposed}),(0,V.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 text-slate-600`,children:e.gate})]},e.axis))})]})})})}function gC(){return(0,V.jsx)(pC,{icon:mm,title:`Fixture Generation`,children:(0,V.jsx)(`div`,{className:`grid gap-3 p-4 md:grid-cols-3`,"data-testid":`developer-fixture-generation`,children:uC.map(e=>(0,V.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-3`,children:[(0,V.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:e.title}),(0,V.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:e.body})]},e.title))})})}function _C(){return(0,V.jsx)(pC,{icon:om,title:`Smoke Checklist`,children:(0,V.jsx)(`div`,{className:`space-y-2 p-4`,"data-testid":`developer-smoke-checklist`,children:dC.map(e=>(0,V.jsxs)(`div`,{className:`flex items-start gap-3 rounded-md border border-slate-200 bg-slate-50 px-3 py-2`,children:[(0,V.jsx)(Yp,{className:`mt-0.5 h-4 w-4 shrink-0 text-emerald-600`}),(0,V.jsx)(`code`,{className:`break-all text-xs font-semibold leading-5 text-slate-700`,children:e})]},e))})})}function vC(){return(0,V.jsx)(pC,{icon:sm,title:`Component Examples`,children:(0,V.jsx)(`div`,{className:`grid gap-3 p-4 lg:grid-cols-3`,"data-testid":`developer-component-examples`,children:fC.map(e=>(0,V.jsxs)(`article`,{className:`rounded-md border border-slate-200 bg-slate-50 p-3`,children:[(0,V.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:e.badges.map(e=>(0,V.jsx)(sC,{variant:e===`read-only`||e===`public-safe`?`success`:`neutral`,children:e},e))}),(0,V.jsx)(`h3`,{className:`mt-3 text-sm font-semibold leading-6 text-slate-950`,children:e.name}),(0,V.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:e.body})]},e.name))})})}function yC(){return(0,V.jsx)(`main`,{className:`min-h-screen bg-[#f7f7f4] px-4 py-4 text-slate-950 sm:px-5`,"data-testid":`frontstage-developer-cockpit`,children:(0,V.jsxs)(`div`,{className:`mx-auto grid max-w-[1500px] gap-4 xl:grid-cols-[260px_minmax(0,1fr)]`,children:[(0,V.jsxs)(`aside`,{className:`rounded-lg border border-slate-200 bg-white p-4 shadow-sm xl:sticky xl:top-4 xl:self-start`,children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsx)(`div`,{className:`flex h-9 w-9 items-center justify-center rounded-md border border-slate-200 bg-slate-950 text-white`,children:(0,V.jsx)(Ym,{className:`h-4 w-4`})}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`div`,{className:`text-sm font-semibold`,children:`Developer Cockpit`}),(0,V.jsx)(`div`,{className:`text-xs text-slate-500`,children:`Projection extension`})]})]}),(0,V.jsxs)(`div`,{className:`mt-4 grid gap-2`,children:[(0,V.jsxs)(`a`,{className:`flex items-center gap-2 rounded-md border border-slate-200 px-3 py-2 text-sm font-medium`,href:`https://huangruiteng.github.io/loopx/`,children:[(0,V.jsx)(xm,{className:`h-4 w-4`}),`LoopX home`]}),(0,V.jsxs)(`a`,{className:`flex items-center gap-2 rounded-md border border-slate-200 px-3 py-2 text-sm font-medium`,href:`https://huangruiteng.github.io/loopx/docs/showcases/index.en.html`,children:[(0,V.jsx)(fm,{className:`h-4 w-4`}),`Public cases`]}),(0,V.jsxs)(`a`,{className:`flex items-center gap-2 rounded-md bg-slate-950 px-3 py-2 text-sm font-medium text-white`,href:`/chat/developers/projections/`,children:[(0,V.jsx)(sm,{className:`h-4 w-4`}),`Developer cockpit`]})]}),(0,V.jsxs)(`div`,{className:`mt-5 space-y-2 rounded-md border border-emerald-200 bg-emerald-50 p-3 text-xs leading-5 text-emerald-950`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,V.jsx)(sC,{variant:`success`,children:`read-only`}),(0,V.jsx)(sC,{variant:`neutral`,children:`public fixtures`})]}),(0,V.jsx)(`p`,{children:`This route uses static public contracts only; live status feeds, registry files, and browser write APIs stay outside the cockpit.`})]})]}),(0,V.jsxs)(`section`,{className:`space-y-4`,children:[(0,V.jsx)(`div`,{className:`rounded-lg border border-slate-200 bg-white px-5 py-5 shadow-sm`,children:(0,V.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-4`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,V.jsx)(sC,{variant:`info`,children:`developers/projections`}),(0,V.jsx)(sC,{variant:`success`,children:`public-safe`}),(0,V.jsx)(sC,{variant:`neutral`,children:`no browser writes`})]}),(0,V.jsx)(`h1`,{className:`mt-3 text-3xl font-semibold tracking-normal text-slate-950`,children:`LoopX Projection Developer Cockpit`}),(0,V.jsx)(`p`,{className:`mt-2 max-w-3xl text-sm leading-6 text-slate-600`,children:`A read-only contributor workbench for adding dashboard/frontstage projections without reverse-engineering the large operator page.`})]}),(0,V.jsxs)(`div`,{className:`grid min-w-[260px] gap-2 text-sm`,children:[(0,V.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-2`,children:[(0,V.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-normal text-slate-500`,children:`Source of truth`}),(0,V.jsx)(`div`,{className:`mt-1 font-semibold text-slate-950`,children:`status contract + compact fixtures`})]}),(0,V.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-2`,children:[(0,V.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-normal text-slate-500`,children:`Boundary`}),(0,V.jsx)(`div`,{className:`mt-1 font-semibold text-slate-950`,children:`read-only extension surface`})]})]})]})}),(0,V.jsxs)(`div`,{className:`grid gap-4 xl:grid-cols-2`,children:[(0,V.jsx)(mC,{}),(0,V.jsx)(hC,{})]}),(0,V.jsxs)(`div`,{className:`grid gap-4 xl:grid-cols-[minmax(0,1fr)_420px]`,children:[(0,V.jsx)(gC,{}),(0,V.jsx)(_C,{})]}),(0,V.jsx)(vC,{}),(0,V.jsx)(pC,{icon:Wm,title:`Extension Boundary`,children:(0,V.jsxs)(`div`,{className:`grid gap-3 p-4 md:grid-cols-3`,"data-testid":`developer-extension-boundary`,children:[(0,V.jsxs)(`div`,{className:`rounded-md border border-emerald-200 bg-emerald-50 px-3 py-3`,children:[(0,V.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:`Allowed`}),(0,V.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:`Versioned parser defaults, public fixtures, read-only route panels, and focused smoke assertions.`})]}),(0,V.jsxs)(`div`,{className:`rounded-md border border-amber-200 bg-amber-50 px-3 py-3`,children:[(0,V.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:`Review`}),(0,V.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:`New dashboard dependencies, status contract fields, loopback capability display, and browser-visible workflows.`})]}),(0,V.jsxs)(`div`,{className:`rounded-md border border-rose-200 bg-rose-50 px-3 py-3`,children:[(0,V.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:`Stop`}),(0,V.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:`Credentials, private registry material, raw logs, transcripts, production actions, or default browser write authority.`})]})]})})]})]})})}var bC=Y({value:K().finite(),total:K().finite().positive().optional(),unit:G().optional(),higher_is_better:q()}).passthrough(),xC=hd(G(),K().finite()).default({}),SC=Y({outcome_status:G().optional(),failure_class:G(),causal_summary:G(),expectedness:G(),implication:G(),next_probe:G(),confidence:G(),evidence_refs:J(G()).optional()}).passthrough(),CC=Y({arm_id:G(),selected_run_id:G().nullable(),score_countable:q(),metrics:hd(G(),bC),effort:xC,insight:SC.nullable().optional()}),wC=Y({run_id:G(),case_id:G(),arm_id:G(),arm_role:G(),status:G(),protocol_id:G(),runner_revision:G().optional(),observed_at:G(),metrics:hd(G(),bC),countability:Y({integrity_qualified:q(),official_result_present:q(),score_countable:q()}).passthrough(),treatment_fidelity:G(),effort:xC,redacted_insight:SC.nullable().optional(),upload_provenance:Y({producer_id:G(),producer_version:G(),observed_at:G(),source_revision:G()}).passthrough()}).passthrough(),TC=Y({case_denominator:K().int().nonnegative(),value_sum:K().finite(),value_mean:K().finite().nullable(),value_median:K().finite().nullable(),value_min:K().finite().nullable(),value_max:K().finite().nullable(),case_macro_rate:K().finite().optional(),suite_micro_rate:K().finite().optional(),suite_micro_numerator:K().finite().optional(),suite_micro_denominator:K().finite().positive().optional()}).passthrough(),EC=Y({arm_id:G(),arm_role:G(),factor_assignments:hd(G(),G()),protocol_counts:hd(G(),K().int().nonnegative()).default({}),runner_revision_counts:hd(G(),K().int().nonnegative()).default({}),orchestrator_runtime_counts:hd(G(),K().int().nonnegative()).default({}),intended_case_count:K().int().positive(),run_count:K().int().nonnegative(),terminal_run_count:K().int().nonnegative(),selected_score_countable_case_count:K().int().nonnegative(),coverage_rate:K().finite().min(0).max(1),metrics:hd(G(),TC),binary_outcomes:hd(G(),Y({success_count:K().int().nonnegative(),case_denominator:K().int().nonnegative(),success_rate:K().finite().min(0).max(1).nullable()})),effort:hd(G(),Y({denominator:K().int().nonnegative(),mean:K().finite().nullable(),median:K().finite().nullable()})),failure_class_counts:hd(G(),K().int().nonnegative())}).passthrough(),DC=Y({baseline_value:K().finite(),candidate_value:K().finite(),delta:K().finite(),direction:_d([`improved`,`flat`,`regressed`]).optional()}).passthrough(),OC=Y({comparison_id:G(),comparison_anchor_run_id:G(),candidate_run_id:G(),candidate_arm_id:G(),primary_metric:G(),matched_pair_countable:X(!0),metric_deltas:hd(G(),DC)}).passthrough(),kC=Y({ok:X(!0),schema_version:X(`benchmark_study_dashboard_v0`),benchmark_id:G(),study_id:G(),status:_d([`complete`,`provisional`]),design:Y({protocol_id:G(),comparison_protocol_id:G(),baseline_arm_id:G(),case_set:Y({case_set_id:G(),case_ids:J(G())}),metric_catalog:J(Y({metric_name:G(),role:_d([`primary`,`guardrail`,`supporting`]),unit:G().optional(),higher_is_better:q(),binary:q()})),labels:hd(G(),G())}).passthrough(),campaign:Y({intended_case_count:K().int().positive(),intended_arm_count:K().int().positive(),intended_cell_denominator:K().int().positive(),selected_score_countable_cell_count:K().int().nonnegative(),selected_score_countable_coverage_rate:K().finite().min(0).max(1),complete_declared_design_case_count:K().int().nonnegative(),ambiguous_score_countable_cell_count:K().int().nonnegative(),in_flight_run_count:K().int().nonnegative(),matched_pair_countable_count:K().int().nonnegative(),factorial_contrast_count:K().int().nonnegative(),factorial_contrast_countable_count:K().int().nonnegative(),runtime_observation_count:K().int().nonnegative(),runtime_classification_counts:hd(G(),K().int().nonnegative())}),arms:J(EC),contrasts:hd(G(),Y({matched_pair_denominator:K().int().nonnegative(),primary_metric_directions:Y({improved:K().int().nonnegative(),flat:K().int().nonnegative(),regressed:K().int().nonnegative()}),binary_metric_transitions:hd(G(),Y({"0_to_1":K().int().nonnegative(),"1_to_0":K().int().nonnegative(),same:K().int().nonnegative()}))})),cases:J(Y({case_id:G(),complete_declared_design:q(),arms:J(CC),eligible_comparisons:J(OC),largest_eligible_primary_contrast:OC.nullable()})),runs:J(wC),authority:Y({score_source:G(),matched_comparison_source:G(),factorial_comparison_source:G().nullable(),manifest_changes_scores:X(!1),dashboard_is_execution_authority:X(!1)}),public_boundary:Y({raw_task_recorded:X(!1),raw_trajectory_recorded:X(!1),hidden_evaluation_recorded:X(!1),raw_verifier_output_recorded:X(!1),credentials_recorded:X(!1),local_paths_recorded:X(!1)}),write_performed:X(!1),network_access_performed:X(!1)});function AC(e){return kC.parse(e)}function jC(e,t){let n=new URL(t),r=new URL(e||`/benchmark-study.example.json`,n);if(!new Set([`http:`,`https:`]).has(r.protocol))throw Error(`Benchmark dashboard source must use HTTP or HTTPS`);if(r.origin!==n.origin)throw Error(`Benchmark dashboard source must use same-origin local readback`);return r.toString()}var MC=[{id:`campaign`,label:`Campaign`},{id:`arms`,label:`Arms`},{id:`cases`,label:`Cases`},{id:`runs`,label:`Runs`}];function NC(e){return e==null?`—`:`${(e*100).toFixed(e>=.995?0:1)}%`}function PC(e){return e==null?`—`:new Intl.NumberFormat(`en`,{maximumFractionDigits:2,notation:`compact`}).format(e)}function FC(e){if(e==null)return`—`;let t=e/6e4;return t>=120?`${(t/60).toFixed(1)} h`:`${PC(t)} min`}function IC(e){let t=Object.entries(e);return t.length?t.map(([e,t])=>`${e} (${t})`).join(`, `):`—`}function LC(e){if(!e)return`—`;let t=e.total==null?PC(e.value):`${PC(e.value)}/${PC(e.total)}`;return e.unit?`${t} ${e.unit}`:t}function RC(e,t){let n=e.metrics[t];return!n||n.case_denominator===0?`—`:n.suite_micro_rate==null?`${PC(n.value_mean)} mean`:`${NC(n.suite_micro_rate)} · ${PC(n.suite_micro_numerator)}/${PC(n.suite_micro_denominator)}`}function zC(e,t){let n=e.largest_eligible_primary_contrast,r=n?.metric_deltas[t];if(!n||!r)return null;let i=r.delta>0?`+`:``;return{direction:r.direction,text:`${n.candidate_arm_id}: ${i}${PC(r.delta)}`}}function BC({children:e,tone:t=`neutral`}){return(0,V.jsx)(`span`,{className:`benchmark-state benchmark-state-${t}`,children:e})}function VC({packet:e,primaryMetric:t}){return(0,V.jsxs)(`div`,{className:`benchmark-view-stack`,children:[(0,V.jsxs)(`section`,{"aria-labelledby":`arm-summary-title`,children:[(0,V.jsxs)(`div`,{className:`benchmark-section-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`p`,{className:`benchmark-kicker`,children:`ARM SUMMARY`}),(0,V.jsx)(`h2`,{id:`arm-summary-title`,children:`Comparable outcomes, denominator first`})]}),(0,V.jsx)(`p`,{children:`Only one score-countable run per declared case × arm cell is selected.`})]}),(0,V.jsx)(`div`,{className:`benchmark-arm-grid`,children:e.arms.map(e=>{let n=Object.values(e.binary_outcomes)[0];return(0,V.jsxs)(`article`,{className:`benchmark-arm-card`,children:[(0,V.jsxs)(`div`,{className:`benchmark-card-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`span`,{className:`benchmark-mono`,children:e.arm_role}),(0,V.jsx)(`h3`,{children:e.arm_id})]}),(0,V.jsx)(BC,{tone:e.coverage_rate===1?`success`:`warning`,children:e.coverage_rate===1?`Complete`:`Provisional`})]}),(0,V.jsxs)(`dl`,{className:`benchmark-stat-list`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`dt`,{children:[`Primary · `,t]}),(0,V.jsx)(`dd`,{children:RC(e,t)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Score-countable coverage`}),(0,V.jsxs)(`dd`,{children:[e.selected_score_countable_case_count,`/`,e.intended_case_count]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Binary success`}),(0,V.jsx)(`dd`,{children:n?`${n.success_count}/${n.case_denominator}`:`Not declared`})]})]})]},e.arm_id)})})]}),(0,V.jsxs)(`section`,{"aria-labelledby":`contrast-title`,children:[(0,V.jsxs)(`div`,{className:`benchmark-section-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`p`,{className:`benchmark-kicker`,children:`MATCHED CONTRASTS`}),(0,V.jsx)(`h2`,{id:`contrast-title`,children:`Direction counts on eligible pairs`})]}),(0,V.jsx)(`p`,{children:`Raw run volume is never used as a comparison denominator.`})]}),(0,V.jsx)(`div`,{className:`benchmark-table-shell`,children:(0,V.jsxs)(`table`,{children:[(0,V.jsx)(`thead`,{children:(0,V.jsxs)(`tr`,{children:[(0,V.jsx)(`th`,{children:`Candidate arm`}),(0,V.jsx)(`th`,{children:`Matched denominator`}),(0,V.jsx)(`th`,{children:`Improved`}),(0,V.jsx)(`th`,{children:`Flat`}),(0,V.jsx)(`th`,{children:`Regressed`}),(0,V.jsx)(`th`,{children:`Binary transitions`})]})}),(0,V.jsxs)(`tbody`,{children:[Object.entries(e.contrasts).map(([e,t])=>(0,V.jsxs)(`tr`,{children:[(0,V.jsx)(`td`,{children:(0,V.jsx)(`strong`,{children:e})}),(0,V.jsx)(`td`,{children:t.matched_pair_denominator}),(0,V.jsx)(`td`,{className:`benchmark-positive`,children:t.primary_metric_directions.improved}),(0,V.jsx)(`td`,{children:t.primary_metric_directions.flat}),(0,V.jsx)(`td`,{className:`benchmark-negative`,children:t.primary_metric_directions.regressed}),(0,V.jsx)(`td`,{children:Object.entries(t.binary_metric_transitions).map(([e,t])=>`${e}: 0→1 ${t[`0_to_1`]}, 1→0 ${t[`1_to_0`]}, same ${t.same}`).join(` · `)||`—`})]},e)),Object.keys(e.contrasts).length===0&&(0,V.jsx)(`tr`,{children:(0,V.jsx)(`td`,{colSpan:6,children:`No matched comparisons are countable yet.`})})]})]})})]}),(0,V.jsxs)(`section`,{"aria-labelledby":`runtime-health-title`,children:[(0,V.jsxs)(`div`,{className:`benchmark-section-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`p`,{className:`benchmark-kicker`,children:`RUNTIME HEALTH`}),(0,V.jsx)(`h2`,{id:`runtime-health-title`,children:`Qualified observations, without execution authority`})]}),(0,V.jsxs)(`p`,{children:[e.campaign.runtime_observation_count,` public-safe runtime observations.`]})]}),(0,V.jsxs)(`div`,{className:`benchmark-runtime-list`,children:[Object.entries(e.campaign.runtime_classification_counts).map(([e,t])=>(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`span`,{children:e}),(0,V.jsx)(`strong`,{children:t})]},e)),e.campaign.runtime_observation_count===0&&(0,V.jsx)(`p`,{className:`benchmark-muted`,children:`No runtime observations uploaded.`})]})]})]})}function HC({packet:e}){return(0,V.jsx)(`div`,{className:`benchmark-detail-grid`,children:e.arms.map(t=>(0,V.jsxs)(`article`,{className:`benchmark-detail-card`,children:[(0,V.jsxs)(`div`,{className:`benchmark-card-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`span`,{className:`benchmark-mono`,children:t.arm_role}),(0,V.jsx)(`h2`,{children:t.arm_id})]}),(0,V.jsxs)(BC,{tone:t.coverage_rate===1?`success`:`warning`,children:[t.selected_score_countable_case_count,`/`,t.intended_case_count,` countable`]})]}),(0,V.jsx)(`div`,{className:`benchmark-factor-row`,children:Object.entries(t.factor_assignments).map(([e,t])=>(0,V.jsxs)(`span`,{children:[e,`: `,(0,V.jsx)(`strong`,{children:t})]},e))}),(0,V.jsxs)(`dl`,{className:`benchmark-stat-list`,children:[e.design.metric_catalog.map(e=>(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`dt`,{children:[e.role,` · `,e.metric_name]}),(0,V.jsx)(`dd`,{children:RC(t,e.metric_name)})]},e.metric_name)),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Runs terminal / observed`}),(0,V.jsxs)(`dd`,{children:[t.terminal_run_count,`/`,t.run_count]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Median duration`}),(0,V.jsx)(`dd`,{children:FC(t.effort.duration_ms?.median)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Protocols`}),(0,V.jsx)(`dd`,{children:IC(t.protocol_counts)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Runner revisions`}),(0,V.jsx)(`dd`,{children:IC(t.runner_revision_counts)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Orchestrator runtimes`}),(0,V.jsxs)(`dd`,{children:[Object.keys(t.orchestrator_runtime_counts).length||0,` distinct`]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Failure classes`}),(0,V.jsx)(`dd`,{children:IC(t.failure_class_counts)})]})]})]},t.arm_id))})}function UC({packet:e,primaryMetric:t,onOpenRun:n}){return(0,V.jsx)(`div`,{className:`benchmark-table-shell benchmark-wide-table`,children:(0,V.jsxs)(`table`,{children:[(0,V.jsx)(`thead`,{children:(0,V.jsxs)(`tr`,{children:[(0,V.jsx)(`th`,{children:`Case`}),(0,V.jsx)(`th`,{children:`Design status`}),(0,V.jsx)(`th`,{children:`Largest eligible delta`}),e.arms.map(e=>(0,V.jsx)(`th`,{children:e.arm_id},e.arm_id))]})}),(0,V.jsx)(`tbody`,{children:e.cases.map(r=>{let i=zC(r,t);return(0,V.jsxs)(`tr`,{children:[(0,V.jsx)(`td`,{children:(0,V.jsx)(`strong`,{children:r.case_id})}),(0,V.jsx)(`td`,{children:(0,V.jsx)(BC,{tone:r.complete_declared_design?`success`:`warning`,children:r.complete_declared_design?`Complete`:`Provisional`})}),(0,V.jsx)(`td`,{className:i?.direction===`improved`?`benchmark-positive`:i?.direction===`regressed`?`benchmark-negative`:void 0,children:i?.text??`—`}),r.arms.map(r=>(0,V.jsx)(`td`,{children:r.selected_run_id&&r.score_countable?(0,V.jsxs)(`button`,{className:`benchmark-cell-link`,onClick:()=>n(r.selected_run_id),type:`button`,children:[(0,V.jsxs)(`span`,{children:[t,`: `,LC(r.metrics[t])]}),e.design.metric_catalog.filter(e=>e.metric_name!==t).map(e=>(0,V.jsxs)(`small`,{className:`benchmark-cell-metric`,children:[e.metric_name,`: `,LC(r.metrics[e.metric_name])]},e.metric_name)),(0,V.jsxs)(`small`,{children:[`Countable · `,FC(r.effort.duration_ms),` `,(0,V.jsx)(Kp,{"aria-hidden":`true`,size:12})]}),r.insight&&(0,V.jsxs)(`small`,{children:[r.insight.failure_class,` · `,r.insight.confidence]})]}):(0,V.jsx)(`span`,{className:`benchmark-muted`,children:`Not countable`})},r.arm_id))]},r.case_id)})})]})})}function WC({run:e,packet:t}){return(0,V.jsxs)(`aside`,{"aria-label":`Run detail for ${e.run_id}`,className:`benchmark-run-detail`,children:[(0,V.jsxs)(`div`,{className:`benchmark-card-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`span`,{className:`benchmark-mono`,children:`RUN DETAIL`}),(0,V.jsx)(`h2`,{children:e.run_id})]}),(0,V.jsx)(BC,{tone:e.countability.score_countable?`success`:`warning`,children:e.countability.score_countable?`Score-countable`:`Diagnostic only`})]}),(0,V.jsxs)(`dl`,{className:`benchmark-stat-list benchmark-run-facts`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Case / arm`}),(0,V.jsxs)(`dd`,{children:[e.case_id,` · `,e.arm_id]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Lifecycle`}),(0,V.jsxs)(`dd`,{children:[e.status,` · `,e.observed_at]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Protocol`}),(0,V.jsx)(`dd`,{children:e.protocol_id})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Qualification`}),(0,V.jsxs)(`dd`,{children:[`Integrity `,e.countability.integrity_qualified?`qualified`:`not qualified`,` · result `,e.countability.official_result_present?`present`:`missing`]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Treatment fidelity`}),(0,V.jsx)(`dd`,{children:e.treatment_fidelity})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Effort`}),(0,V.jsxs)(`dd`,{children:[FC(e.effort.duration_ms),` · `,PC(e.effort.agent_steps),` steps · `,PC(e.effort.token_count),` tokens`]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Runner revision`}),(0,V.jsx)(`dd`,{children:e.runner_revision??`—`})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Upload provenance`}),(0,V.jsxs)(`dd`,{children:[e.upload_provenance.producer_id,` · `,e.upload_provenance.source_revision]})]})]}),(0,V.jsx)(`div`,{className:`benchmark-run-metrics`,children:t.design.metric_catalog.map(t=>(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`span`,{children:t.metric_name}),(0,V.jsx)(`strong`,{children:LC(e.metrics[t.metric_name])})]},t.metric_name))}),e.redacted_insight&&(0,V.jsxs)(`div`,{className:`benchmark-insight`,children:[(0,V.jsxs)(`span`,{className:`benchmark-mono`,children:[`REDACTED CASE INSIGHT · `,e.redacted_insight.confidence]}),(0,V.jsx)(`p`,{children:e.redacted_insight.causal_summary}),(0,V.jsxs)(`small`,{children:[`Implication: `,e.redacted_insight.implication]}),(0,V.jsx)(`br`,{}),(0,V.jsxs)(`small`,{children:[`Next probe: `,e.redacted_insight.next_probe]}),!!e.redacted_insight.evidence_refs?.length&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`br`,{}),(0,V.jsxs)(`small`,{children:[`Evidence: `,e.redacted_insight.evidence_refs.join(`, `)]})]})]})]})}function GC({packet:e,selectedRunId:t,onSelectRun:n}){let r=e.runs.find(e=>e.run_id===t)??e.runs[0];return(0,V.jsxs)(`div`,{className:`benchmark-runs-layout`,children:[(0,V.jsx)(`div`,{className:`benchmark-table-shell`,children:(0,V.jsxs)(`table`,{children:[(0,V.jsx)(`thead`,{children:(0,V.jsxs)(`tr`,{children:[(0,V.jsx)(`th`,{children:`Run`}),(0,V.jsx)(`th`,{children:`Case`}),(0,V.jsx)(`th`,{children:`Arm`}),(0,V.jsx)(`th`,{children:`Status`}),(0,V.jsx)(`th`,{children:`Countability`})]})}),(0,V.jsx)(`tbody`,{children:e.runs.map(e=>(0,V.jsxs)(`tr`,{"aria-selected":e.run_id===r?.run_id,children:[(0,V.jsx)(`td`,{children:(0,V.jsx)(`button`,{className:`benchmark-run-link`,onClick:()=>n(e.run_id),type:`button`,children:e.run_id})}),(0,V.jsx)(`td`,{children:e.case_id}),(0,V.jsx)(`td`,{children:e.arm_id}),(0,V.jsx)(`td`,{children:e.status}),(0,V.jsx)(`td`,{children:e.countability.score_countable?`Score-countable`:`Diagnostic only`})]},e.run_id))})]})}),r&&(0,V.jsx)(WC,{packet:e,run:r})]})}function KC(){let e=sw.useSearch(),t=sw.useNavigate(),[n,r]=(0,B.useState)(null),[i,a]=(0,B.useState)(null),[o,s]=(0,B.useState)(0),c=(0,B.useMemo)(()=>{let t=e.dashboardUrl||`/chat/benchmark-study.example.json`;try{return{url:jC(t,window.location.href),error:null}}catch(e){return{url:``,error:e instanceof Error?e.message:`Invalid dashboard source`}}},[e.dashboardUrl]);if((0,B.useEffect)(()=>{let e=!0;return r(null),a(null),c.error?(a(c.error),()=>{e=!1}):(fetch(c.url,{cache:`no-store`}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status} while loading the dashboard packet`);return AC(await e.json())}).then(t=>{e&&r(t)}).catch(t=>{e&&a(t instanceof Error?t.message:`Unable to load dashboard packet`)}),()=>{e=!1})},[o,c]),(0,B.useEffect)(()=>{n&&(document.title=`${n.design.labels.title??n.study_id} · LoopX Benchmark`)},[n]),i)return(0,V.jsxs)(`main`,{className:`benchmark-page benchmark-loading`,children:[(0,V.jsx)(im,{"aria-hidden":`true`}),(0,V.jsx)(`h1`,{children:`Dashboard packet unavailable`}),(0,V.jsx)(`p`,{children:i}),(0,V.jsxs)(`button`,{onClick:()=>s(e=>e+1),type:`button`,children:[(0,V.jsx)(Im,{"aria-hidden":`true`,size:16}),` Retry readback`]})]});if(!n)return(0,V.jsxs)(`main`,{"aria-busy":`true`,className:`benchmark-page benchmark-loading`,children:[(0,V.jsx)(Up,{"aria-hidden":`true`}),(0,V.jsx)(`h1`,{children:`Reading benchmark study`}),(0,V.jsx)(`p`,{children:`Validating the public-safe dashboard packet…`})]});let l=n.design.metric_catalog.find(e=>e.role===`primary`)?.metric_name??`primary`,u=(n,r=e.runId)=>t({search:e=>({...e,view:n,runId:r})}),d=new URL(c.url).pathname;return(0,V.jsxs)(`main`,{className:`benchmark-page`,children:[(0,V.jsxs)(`header`,{className:`benchmark-hero`,children:[(0,V.jsxs)(`div`,{className:`benchmark-hero-topline`,children:[(0,V.jsx)(`a`,{className:`benchmark-wordmark`,href:`/chat/`,children:`LoopX`}),(0,V.jsxs)(`div`,{className:`benchmark-readonly`,children:[(0,V.jsx)(Wm,{"aria-hidden":`true`,size:15}),` Derived read-only projection`]})]}),(0,V.jsxs)(`div`,{className:`benchmark-hero-grid`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`p`,{className:`benchmark-kicker`,children:[`BENCHMARK STUDY / `,n.benchmark_id]}),(0,V.jsxs)(`div`,{className:`benchmark-title-row`,children:[(0,V.jsx)(`h1`,{children:n.design.labels.title??n.study_id}),(0,V.jsx)(BC,{tone:n.status===`complete`?`success`:`warning`,children:n.status})]}),(0,V.jsx)(`p`,{className:`benchmark-lead`,children:`One declared study, explicit denominators, and the same countability rules from campaign summary to exact run.`})]}),(0,V.jsxs)(`dl`,{className:`benchmark-identity`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Study`}),(0,V.jsx)(`dd`,{children:n.study_id})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Protocol`}),(0,V.jsx)(`dd`,{children:n.design.protocol_id})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Case set`}),(0,V.jsx)(`dd`,{children:n.design.case_set.case_set_id})]})]})]}),(0,V.jsxs)(`div`,{className:`benchmark-kpi-grid`,children:[(0,V.jsxs)(`article`,{children:[(0,V.jsx)(lm,{"aria-hidden":`true`}),(0,V.jsx)(`span`,{children:`Score-countable cells`}),(0,V.jsxs)(`strong`,{children:[n.campaign.selected_score_countable_cell_count,(0,V.jsxs)(`small`,{children:[` / `,n.campaign.intended_cell_denominator]})]}),(0,V.jsxs)(`p`,{children:[NC(n.campaign.selected_score_countable_coverage_rate),` declared coverage`]})]}),(0,V.jsxs)(`article`,{children:[(0,V.jsx)(am,{"aria-hidden":`true`}),(0,V.jsx)(`span`,{children:`Complete designs`}),(0,V.jsxs)(`strong`,{children:[n.campaign.complete_declared_design_case_count,(0,V.jsxs)(`small`,{children:[` / `,n.campaign.intended_case_count]})]}),(0,V.jsx)(`p`,{children:`Cases with every declared arm`})]}),(0,V.jsxs)(`article`,{children:[(0,V.jsx)(Kp,{"aria-hidden":`true`}),(0,V.jsx)(`span`,{children:`Matched comparisons`}),(0,V.jsx)(`strong`,{children:n.campaign.matched_pair_countable_count}),(0,V.jsx)(`p`,{children:`Eligible pairs only`})]}),(0,V.jsxs)(`article`,{children:[(0,V.jsx)(Up,{"aria-hidden":`true`}),(0,V.jsx)(`span`,{children:`In flight`}),(0,V.jsx)(`strong`,{children:n.campaign.in_flight_run_count}),(0,V.jsx)(`p`,{children:n.status===`provisional`?`Coverage remains provisional`:`Declared coverage complete`})]})]})]}),(0,V.jsxs)(`nav`,{"aria-label":`Benchmark dashboard views`,className:`benchmark-tabs`,children:[MC.map(t=>(0,V.jsx)(`button`,{"aria-current":e.view===t.id?`page`:void 0,onClick:()=>u(t.id),type:`button`,children:t.label},t.id)),(0,V.jsxs)(`button`,{className:`benchmark-refresh`,onClick:()=>s(e=>e+1),type:`button`,children:[(0,V.jsx)(Im,{"aria-hidden":`true`,size:14}),` Refresh local readback`]})]}),(0,V.jsxs)(`div`,{className:`benchmark-content`,children:[e.view===`campaign`&&(0,V.jsx)(VC,{packet:n,primaryMetric:l}),e.view===`arms`&&(0,V.jsx)(HC,{packet:n}),e.view===`cases`&&(0,V.jsx)(UC,{onOpenRun:e=>u(`runs`,e),packet:n,primaryMetric:l}),e.view===`runs`&&(0,V.jsx)(GC,{onSelectRun:e=>u(`runs`,e),packet:n,selectedRunId:e.runId})]}),(0,V.jsxs)(`footer`,{className:`benchmark-footer`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(Wm,{"aria-hidden":`true`,size:16}),(0,V.jsxs)(`span`,{children:[`Scores: `,n.authority.score_source]}),(0,V.jsx)(`span`,{children:`Dashboard cannot launch, grade, or mutate runs.`})]}),(0,V.jsxs)(`code`,{title:d,children:[`local`,d]})]})]})}var qC=Y({goalId:G().optional().default(``),statusUrl:G().optional().default(``)}),JC=Y({goalId:G().optional().default(``),mode:_d([`showcase`,`developer`,`ops`]).optional().default(`showcase`),statusUrl:G().optional().default(``),todoLane:_d([`all`,`user`,`agent`]).optional().default(`all`),todoQuery:G().optional().default(``)}),YC=JC.omit({mode:!0}),XC=Y({dashboardUrl:G().optional().default(``),view:_d([`campaign`,`arms`,`cases`,`runs`]).optional().default(`campaign`),runId:G().optional().default(``)});function ZC(){let e=`https://huangruiteng.github.io/loopx/docs/showcases/index.en.html`;return(0,B.useEffect)(()=>{window.location.replace(e)},[]),(0,V.jsx)(`a`,{href:e,children:`Open LoopX cases / 浏览案例`})}function QC({goalId:e,statusUrl:t}){let n=t?rh(t,window.location.href):null;return n?.error?(0,V.jsx)(`main`,{role:`alert`,children:n.error}):(0,V.jsx)(ri,{replace:!0,to:`/`,search:{goalId:e,statusUrl:t}})}function $C(){let e=rw.useSearch();return e.mode===`ops`?(0,V.jsx)(QC,{...e}):e.mode===`developer`?(0,V.jsx)(ri,{replace:!0,to:`/developers/projections`}):(0,V.jsx)(ZC,{})}function ew(){return(0,V.jsx)(QC,{...iw.useSearch()})}var tw=Si({component:()=>(0,V.jsx)(ji,{}),errorComponent:()=>(0,V.jsxs)(`main`,{role:`alert`,className:`p-8`,children:[(0,V.jsx)(`h1`,{children:`页面暂时无法显示 / Page unavailable`}),(0,V.jsx)(`p`,{children:`请重新加载页面;这不会执行任务。 / Reloading does not execute tasks.`}),(0,V.jsx)(`button`,{type:`button`,onClick:()=>window.location.reload(),children:`重新加载 / Reload`})]})}),nw=bi({getParentRoute:()=>tw,path:`/`,validateSearch:e=>qC.parse(e),component:aC}),rw=bi({getParentRoute:()=>tw,path:`/frontstage`,validateSearch:e=>JC.parse(e),component:$C}),iw=bi({getParentRoute:()=>tw,path:`/deprecated/frontstage/ops`,validateSearch:e=>YC.parse(e),component:ew}),aw=bi({getParentRoute:()=>tw,path:`/frontstage/developer`,component:()=>(0,V.jsx)(ri,{replace:!0,to:`/developers/projections`})}),ow=bi({getParentRoute:()=>tw,path:`/developers/projections`,component:yC}),sw=bi({getParentRoute:()=>tw,path:`/benchmarks/study`,validateSearch:e=>XC.parse(e),component:KC}),cw=tw.addChildren([nw,rw,iw,aw,ow,sw]);function lw(e){return!e||e===`/`||e===`./`?`/`:(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}var uw=Ii({routeTree:cw,basepath:lw(`/chat/`),trailingSlash:`preserve`}),dw=document.getElementById(`root`);if(!dw)throw Error(`Root element not found`);var fw=new ke({defaultOptions:{queries:{refetchOnWindowFocus:!1,retry:1,staleTime:1e4}}});(0,Bi.createRoot)(dw).render((0,V.jsx)(Ne,{client:fw,children:(0,V.jsx)(Ki,{children:(0,V.jsx)(zi,{router:uw})})})); \ No newline at end of file diff --git a/loopx/web/chat/assets/index-DGnmPxJU.js b/loopx/web/chat/assets/index-DGnmPxJU.js deleted file mode 100644 index c9d52f6f2e..0000000000 --- a/loopx/web/chat/assets/index-DGnmPxJU.js +++ /dev/null @@ -1,129 +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,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},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,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),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var l=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&&ne(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&&ne(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var ee=new MessageChannel,te=ee.port2;ee.port1.onmessage=D,O=function(){te.postMessage(null)}}else O=function(){_(D,0)};function ne(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,ne(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}}}})),u=o(((e,t)=>{t.exports=l()})),d=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 ee(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var te=/\/+/g;function ne(e,t){return typeof e==`object`&&e&&e.key!=null?ee(``+e.key):t.toString(36)}function k(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 A(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,A(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+ne(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(te,`$&/`)+`/`),A(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(te,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{t.exports=d()})),p=o((e=>{var t=f();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=p()})),h=o((e=>{var t=u(),n=f(),r=m();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=I(null),se=I(null),ce=I(null),le=I(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)?Wd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Wd(t),e=Gd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}ae(oe),L(oe,e)}function de(){ae(oe),ae(se),ae(ce)}function R(e){e.memoizedState!==null&&L(le,e);var t=oe.current,n=Gd(t,e.type);t!==n&&(L(se,e),L(oe,n))}function fe(e){se.current===e&&(ae(oe),ae(se)),le.current===e&&(ae(le),tp._currentValue=F)}var pe,me;function he(e){if(pe===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);pe=t&&t[1]||``,me=-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{ge=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?he(n):``}function ve(e,t){switch(e.tag){case 26:case 27:case 5:return he(e.type);case 16:return he(`Lazy`);case 13:return e.child!==t&&t!==null?he(`Suspense Fallback`):he(`Suspense`);case 19:return he(`SuspenseList`);case 0:case 15:return _e(e.type,!1);case 11:return _e(e.type.render,!1);case 1:return _e(e.type,!0);case 31:return he(`Activity`);default:return``}}function ye(e){try{var t=``,n=null;do t+=ve(e,n),n=e,e=e.return;while(e);return t}catch(e){return` -Error generating stack: `+e.message+` -`+e.stack}}var be=Object.prototype.hasOwnProperty,xe=t.unstable_scheduleCallback,Se=t.unstable_cancelCallback,Ce=t.unstable_shouldYield,we=t.unstable_requestPaint,Te=t.unstable_now,z=t.unstable_getCurrentPriorityLevel,Ee=t.unstable_ImmediatePriority,De=t.unstable_UserBlockingPriority,Oe=t.unstable_NormalPriority,ke=t.unstable_LowPriority,Ae=t.unstable_IdlePriority,je=t.log,B=t.unstable_setDisableYieldValue,V=null,Me=null;function Ne(e){if(typeof je==`function`&&B(e),Me&&typeof Me.setStrictMode==`function`)try{Me.setStrictMode(V,e)}catch{}}var Pe=Math.clz32?Math.clz32:Ie,H=Math.log,Fe=Math.LN2;function Ie(e){return e>>>=0,e===0?32:31-(H(e)/Fe|0)|0}var Le=256,Re=262144,ze=4194304;function Be(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 Ve(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=Be(n))):i=Be(o):i=Be(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=Be(n))):i=Be(o)):i=Be(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 He(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Ue(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 We(){var e=ze;return ze<<=1,!(ze&62914560)&&(ze=4194304),e}function Ge(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Ke(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function qe(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),on=!1;if(an)try{var sn={};Object.defineProperty(sn,"passive",{get:function(){on=!0}}),window.addEventListener(`test`,sn,sn),window.removeEventListener(`test`,sn,sn)}catch{on=!1}var cn=null,ln=null,un=null;function dn(){if(un)return un;var e,t=ln,n=t.length,r,i=`value`in cn?cn.value:cn.textContent,a=i.length;for(e=0;e=Un),Kn=` `,qn=!1;function Jn(e,t){switch(e){case`keyup`:return Vn.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Yn(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Xn=!1;function Zn(e,t){switch(e){case`compositionend`:return Yn(t);case`keypress`:return t.which===32?(qn=!0,Kn):null;case`textInput`:return e=t.data,e===Kn&&qn?null:e;default:return null}}function Qn(e,t){if(Xn)return e===`compositionend`||!Hn&&Jn(e,t)?(e=dn(),un=ln=cn=null,Xn=!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=br(n)}}function Sr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Sr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Cr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Mt(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=Mt(e.document)}return t}function wr(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 Tr=an&&`documentMode`in document&&11>=document.documentMode,Er=null,Dr=null,Or=null,kr=!1;function Ar(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;kr||Er==null||Er!==Mt(r)||(r=Er,`selectionStart`in r&&wr(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}),Or&&yr(Or,r)||(Or=r,r=Od(Dr,`onSelect`),0>=o,i-=o,Si=1<<32-Pe(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),ji&&wi(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),ji&&wi(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 ji&&wi(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)}),ji&&wi(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&&Ca(l)===r.type){n(e,r.sibling),c=a(r,o.props),Aa(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===y?(c=li(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=ci(o.type,o.key,o.props,null,e.mode,c),Aa(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}n(e,r);break}t(e,r),r=r.sibling}c=fi(o,e.mode,c),c.return=e,e=c}return s(e);case O:return o=Ca(o),b(e,r,o,c)}if(M(o))return h(e,r,o,c);if(k(o)){if(l=k(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,ka(o),c);if(o.$$typeof===C)return b(e,r,Qi(e,o),c);ja(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=ui(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Oa=0;var i=b(e,t,n,r);return Da=null,i}catch(t){if(t===va||t===ba)throw t;var a=ii(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Na=Ma(!0),Pa=Ma(!1),Fa=!1;function Ia(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function La(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 Ra(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function za(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Bl&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=ti(e),ei(e,null,n),t}return Zr(e,r,t,n),ti(e)}function Ba(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,Ye(e,n)}}function Va(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 Ha=!1;function Ua(){if(Ha){var e=la;if(e!==null)throw e}}function Wa(e,t,n,r){Ha=!1;var i=e.updateQueue;Fa=!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?(Ul&f)===f:(r&f)===f){f!==0&&f===ca&&(Ha=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(m=g.payload,typeof m==`function`){d=m.call(_,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=g.payload,f=typeof m==`function`?m.call(_,d,f):m,f==null)break a;d=h({},d,f);break a;case 2:Fa=!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),Zl|=o,e.lanes=o,e.memoizedState=d}}function Ga(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function Ka(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=N.T,s={};N.T=s,Ns(e,!1,t,n);try{var c=i(),l=N.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Ms(e,t,fa(c,r),yu(e)):Ms(e,t,r,yu(e))}catch(n){Ms(e,t,{then:function(){},status:`rejected`,reason:n},yu())}finally{P.p=a,o!==null&&s.types!==null&&(o.types=s.types),N.T=o}}function Ss(){}function Cs(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=ws(e).queue;xs(e,a,t,F,n===null?Ss:function(){return Ts(e),n(r)})}function ws(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:F,baseState:F,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Po,lastRenderedState:F},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Po,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Ts(e){var t=ws(e);t.next===null&&(t=e.alternate.memoizedState),Ms(e,t.next.queue,{},yu())}function Es(){return U(tp)}function Ds(){return ko().memoizedState}function Os(){return ko().memoizedState}function ks(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=yu();e=Ra(n);var r=za(t,e,n);r!==null&&(xu(r,t,n),Ba(r,t,n)),t={cache:ia()},e.payload=t;return}t=t.return}}function As(e,t,n){var r=yu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Ps(e)?Fs(t,n):(n=Qr(e,t,n,r),n!==null&&(xu(n,e,r),Is(n,t,r)))}function js(e,t,n){Ms(e,t,n,yu())}function Ms(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ps(e))Fs(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,vr(s,o))return Zr(e,t,i,0),Vl===null&&Xr(),!1}catch{}if(n=Qr(e,t,i,r),n!==null)return xu(n,e,r),Is(n,t,r),!0}return!1}function Ns(e,t,n,r){if(r={lane:2,revertLane:pd(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Ps(e)){if(t)throw Error(i(479))}else t=Qr(e,n,r,2),t!==null&&xu(t,e,2)}function Ps(e){var t=e.alternate;return e===co||t!==null&&t===co}function Fs(e,t){po=fo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Is(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ye(e,n)}}var Ls={readContext:U,use:Mo,useCallback:yo,useContext:yo,useEffect:yo,useImperativeHandle:yo,useLayoutEffect:yo,useInsertionEffect:yo,useMemo:yo,useReducer:yo,useRef:yo,useState:yo,useDebugValue:yo,useDeferredValue:yo,useTransition:yo,useSyncExternalStore:yo,useId:yo,useHostTransitionStatus:yo,useFormState:yo,useActionState:yo,useOptimistic:yo,useMemoCache:yo,useCacheRefresh:yo};Ls.useEffectEvent=yo;var Rs={readContext:U,use:Mo,useCallback:function(e,t){return Oo().memoizedState=[e,t===void 0?null:t],e},useContext:U,useEffect:cs,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),os(4194308,4,ms.bind(null,t,e),n)},useLayoutEffect:function(e,t){return os(4194308,4,e,t)},useInsertionEffect:function(e,t){os(4,2,e,t)},useMemo:function(e,t){var n=Oo();t=t===void 0?null:t;var r=e();if(mo){Ne(!0);try{e()}finally{Ne(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=Oo();if(n!==void 0){var i=n(t);if(mo){Ne(!0);try{n(t)}finally{Ne(!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=As.bind(null,co,e),[r.memoizedState,e]},useRef:function(e){var t=Oo();return e={current:e},t.memoizedState=e},useState:function(e){e=Wo(e);var t=e.queue,n=js.bind(null,co,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:gs,useDeferredValue:function(e,t){return ys(Oo(),e,t)},useTransition:function(){var e=Wo(!1);return e=xs.bind(null,co,e.queue,!0,!1),Oo().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=co,a=Oo();if(ji){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Vl===null)throw Error(i(349));Ul&127||zo(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,cs(Vo.bind(null,r,o,e),[e]),r.flags|=2048,is(9,{destroy:void 0},Bo.bind(null,r,o,n,t),null),n},useId:function(){var e=Oo(),t=Vl.identifierPrefix;if(ji){var n=Ci,r=Si;n=(r&~(1<<32-Pe(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=ho++,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[nt]=t,o[rt]=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(Ld(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&&Mc(t)}}return Lc(t),Nc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Mc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=ce.current,Ri(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=ki,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[nt]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Pd(e.nodeValue,n)),e||Fi(t,!0)}else e=Ud(e).createTextNode(r),e[nt]=t,t.stateNode=e}return Lc(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Ri(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[nt]=t}else zi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Lc(t),e=!1}else n=Bi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(io(t),t):(io(t),null);if(t.flags&128)throw Error(i(558))}return Lc(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=Ri(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[nt]=t}else zi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Lc(t),a=!1}else a=Bi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(io(t),t):(io(t),null)}return io(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),Fc(t,t.updateQueue),Lc(t),null);case 4:return de(),e===null&&wd(t.stateNode.containerInfo),Lc(t),null;case 10:return Ki(t.type),Lc(t),null;case 19:if(ae(ao),r=t.memoizedState,r===null)return Lc(t),null;if(a=!!(t.flags&128),o=r.rendering,o===null){if(a)Ic(r,!1);else{if(Xl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=oo(e),o!==null){for(t.flags|=128,Ic(r,!1),e=o.updateQueue,t.updateQueue=e,Fc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)si(n,e),n=n.sibling;return L(ao,ao.current&1|2),ji&&wi(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Te()>su&&(t.flags|=128,a=!0,Ic(r,!1),t.lanes=4194304)}}else{if(!a){if(e=oo(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Fc(t,e),Ic(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!ji)return Lc(t),null}else 2*Te()-r.renderingStartTime>su&&n!==536870912&&(t.flags|=128,a=!0,Ic(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?(Lc(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Te(),e.sibling=null,n=ao.current,L(ao,a?n&1|2:n&1),ji&&wi(t,r.treeForkCount),e);case 22:case 23:return io(t),Za(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Lc(t),t.subtreeFlags&6&&(t.flags|=8192)):Lc(t),n=t.updateQueue,n!==null&&Fc(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&&ae(ma),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Ki(ra),Lc(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function zc(e,t){switch(Di(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ki(ra),de(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return fe(t),null;case 31:if(t.memoizedState!==null){if(io(t),t.alternate===null)throw Error(i(340));zi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(io(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));zi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ae(ao),null;case 4:return de(),null;case 10:return Ki(t.type),null;case 22:case 23:return io(t),Za(),e!==null&&ae(ma),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Ki(ra),null;case 25:return null;default:return null}}function Bc(e,t){switch(Di(t),t.tag){case 3:Ki(ra),de();break;case 26:case 27:case 5:fe(t);break;case 4:de();break;case 31:t.memoizedState!==null&&io(t);break;case 13:io(t);break;case 19:ae(ao);break;case 10:Ki(t.type);break;case 22:case 23:io(t),Za(),e!==null&&ae(ma);break;case 24:Ki(ra)}}function Vc(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){Xu(t,t.return,e)}}function Hc(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){Xu(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Xu(t,t.return,e)}}function Uc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{Ka(t,n)}catch(t){Xu(e,e.return,t)}}}function Wc(e,t,n){n.props=Gs(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Xu(e,t,n)}}function Gc(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){Xu(e,t,n)}}function Kc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){Xu(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){Xu(e,t,n)}else n.current=null}}function qc(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){Xu(e,e.return,t)}}function Jc(e,t,n){try{var r=e.stateNode;Rd(r,e.type,n,t),r[rt]=t}catch(t){Xu(e,e.return,t)}}function Yc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&ef(e.type)||e.tag===4}function Xc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Yc(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&&ef(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 Zc(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=Yt));else if(r!==4&&(r===27&&ef(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Zc(e,t,n),e=e.sibling;e!==null;)Zc(e,t,n),e=e.sibling}function Qc(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&&ef(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(Qc(e,t,n),e=e.sibling;e!==null;)Qc(e,t,n),e=e.sibling}function $c(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Ld(t,r,n),t[nt]=e,t[rt]=n}catch(t){Xu(e,e.return,t)}}var el=!1,tl=!1,nl=!1,rl=typeof WeakSet==`function`?WeakSet:Set,il=null;function al(e,t){if(e=e.containerInfo,Vd=up,e=Cr(e),wr(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(Hd={focusedElem:e,selectionRange:n},up=!1,il=t;il!==null;)if(t=il,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,il=e;else for(;il!==null;){switch(t=il,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`))),Ld(o,r,n),o[nt]=e,ht(o),r=o;break a;case`link`:var s=Wf(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=xr(s,h),v=xr(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,N.T=null,n=hu,hu=null;var o=du,s=pu;if(uu=0,fu=du=null,pu=0,Bl&6)throw Error(i(331));var c=Bl;if(Bl|=4,Fl(o.current),Dl(o,o.current,s,n),Bl=c,sd(0,!1),Me&&typeof Me.onPostCommitFiberRoot==`function`)try{Me.onPostCommitFiberRoot(V,o)}catch{}return!0}finally{P.p=a,N.T=r,Ku(e,t)}}function Yu(e,t,n){t=mi(n,t),t=Zs(e.stateNode,t,2),e=za(e,t,2),e!==null&&(Ke(e,2),J(e))}function Xu(e,t,n){if(e.tag===3)Yu(e,e,n);else for(;t!==null;){if(t.tag===3){Yu(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(lu===null||!lu.has(r))){e=mi(n,e),n=Qs(2),r=za(t,n,2),r!==null&&($s(n,r,t,e),Ke(r,2),J(r));break}}t=t.return}}function K(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new zl;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)||(Jl=!0,i.add(n),e=Zu.bind(null,e,t,n),t.then(e,e))}function Zu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Vl===e&&(Ul&n)===n&&(Xl===4||Xl===3&&(Ul&62914560)===Ul&&300>Te()-au?!(Bl&2)&&Ou(e,0):$l|=n,tu===Ul&&(tu=0)),J(e)}function Qu(e,t){t===0&&(t=We()),e=$r(e,t),e!==null&&(Ke(e,t),J(e))}function $u(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Qu(e,n)}function q(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),Qu(e,n)}function ed(e,t){return xe(e,t)}var td=null,nd=null,rd=!1,id=!1,ad=!1,od=0;function J(e){e!==nd&&e.next===null&&(nd===null?td=nd=e:nd=nd.next=e),id=!0,rd||(rd=!0,fd())}function sd(e,t){if(!ad&&id){ad=!0;do for(var n=!1,r=td;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-Pe(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,dd(r,a))}else a=Ul,a=Ve(r,r===Vl?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||He(r,a)||(n=!0,dd(r,a))}r=r.next}while(n);ad=!1}}function Y(){cd()}function cd(){id=rd=!1;var e=0;od!==0&&Jd()&&(e=od);for(var t=Te(),n=null,r=td;r!==null;){var i=r.next,a=ld(r,t);a===0?(r.next=null,n===null?td=i:n.next=i,i===null&&(nd=n)):(n=r,(e!==0||a&3)&&(id=!0)),r=i}uu!==0&&uu!==5||sd(e,!1),od!==0&&(od=0)}function ld(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&&zd(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function wf(e,t,n){var r=Cf;if(r&&typeof t==`string`&&t){var i=Pt(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),vf.has(i)||(vf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Ld(t,`link`,e),ht(t),r.head.appendChild(t)))}}function Tf(e){bf.D(e),wf(`dns-prefetch`,e,null)}function Ef(e,t){bf.C(e,t),wf(`preconnect`,e,t)}function Df(e,t,n){bf.L(e,t,n);var r=Cf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Pt(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Pt(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Pt(n.imageSizes)+`"]`)):i+=`[href="`+Pt(e)+`"]`;var a=i;switch(t){case`style`:a=Nf(e);break;case`script`:a=Lf(e)}_f.has(a)||(e=h({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),_f.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Pf(a))||t===`script`&&r.querySelector(Rf(a))||(t=r.createElement(`link`),Ld(t,`link`,e),ht(t),r.head.appendChild(t)))}}function Of(e,t){bf.m(e,t);var n=Cf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Pt(r)+`"][href="`+Pt(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Lf(e)}if(!_f.has(a)&&(e=h({rel:`modulepreload`,href:e},t),_f.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(Rf(a)))return}r=n.createElement(`link`),Ld(r,`link`,e),ht(r),n.head.appendChild(r)}}}function kf(e,t,n){bf.S(e,t,n);var r=Cf;if(r&&e){var i=mt(r).hoistableStyles,a=Nf(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Pf(a)))s.loading=5;else{e=h({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=_f.get(a))&&Vf(e,n);var c=o=r.createElement(`link`);ht(c),Ld(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,Bf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Af(e,t){bf.X(e,t);var n=Cf;if(n&&e){var r=mt(n).hoistableScripts,i=Lf(e),a=r.get(i);a||(a=n.querySelector(Rf(i)),a||(e=h({src:e,async:!0},t),(t=_f.get(i))&&Hf(e,t),a=n.createElement(`script`),ht(a),Ld(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function jf(e,t){bf.M(e,t);var n=Cf;if(n&&e){var r=mt(n).hoistableScripts,i=Lf(e),a=r.get(i);a||(a=n.querySelector(Rf(i)),a||(e=h({src:e,async:!0,type:`module`},t),(t=_f.get(i))&&Hf(e,t),a=n.createElement(`script`),ht(a),Ld(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Mf(e,t,n,r){var a=(a=ce.current)?yf(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=Nf(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=Nf(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(Pf(e)))&&!o._p&&(s.instance=o,s.state.loading=5),_f.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},_f.set(e,n),o||If(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=Lf(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 Nf(e){return`href="`+Pt(e)+`"`}function Pf(e){return`link[rel="stylesheet"][`+e+`]`}function Ff(e){return h({},e,{"data-precedence":e.precedence,precedence:null})}function If(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}),Ld(t,`link`,n),ht(t),e.head.appendChild(t))}function Lf(e){return`[src="`+Pt(e)+`"]`}function Rf(e){return`script[async]`+e}function zf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Pt(n.href)+`"]`);if(r)return t.instance=r,ht(r),r;var a=h({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),ht(r),Ld(r,`style`,a),Bf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Nf(n.href);var o=e.querySelector(Pf(a));if(o)return t.state.loading|=4,t.instance=o,ht(o),o;r=Ff(n),(a=_f.get(a))&&Vf(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}),Ld(o,`link`,r),t.state.loading|=4,Bf(o,n.precedence,e),t.instance=o;case`script`:return o=Lf(n.src),(a=e.querySelector(Rf(o)))?(t.instance=a,ht(a),a):(r=n,(a=_f.get(o))&&(r=h({},n),Hf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),ht(a),Ld(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,Bf(r,n.precedence,e));return t.instance}function Bf(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 Kf(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 qf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Jf(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=Nf(r.href),a=t.querySelector(Pf(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Zf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,ht(a);return}a=t.ownerDocument||t,r=Ff(r),(i=_f.get(i))&&Vf(r,i),a=a.createElement(`link`),ht(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Ld(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=Zf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Yf=0;function Xf(e,t){return e.stylesheets&&e.count===0&&$f(e,e.stylesheets),0Yf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Zf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)$f(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Qf=null;function $f(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Qf=new Map,t.forEach(ep,e),Qf=null,Zf.call(e))}function ep(e,t){if(!(t.state.loading&4)){var n=Qf.get(e);if(n)var r=n.get(null);else{n=new Map,Qf.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=h()})),_=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},v=new class extends _{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},y={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},b=new class{#e=y;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function x(e){setTimeout(e,0)}var S=typeof window>`u`||`Deno`in globalThis;function C(){}function w(e,t){return typeof e==`function`?e(t):e}function T(e){return typeof e==`number`&&e>=0&&e!==1/0}function E(e,t){return Math.max(e+(t||0)-Date.now(),0)}function D(e,t){return typeof e==`function`?e(t):e}function O(e,t){return typeof e==`function`?e(t):e}function ee(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==ne(o,t.options))return!1}else if(!A(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function te(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(k(t.options.mutationKey)!==k(a))return!1}else if(!A(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function ne(e,t){return(t?.queryKeyHashFn||k)(e)}function k(e){return JSON.stringify(e,(e,t)=>P(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function A(e,t){return e===t?!0:typeof e==typeof t&&e&&t&&typeof e==`object`&&typeof t==`object`?Object.keys(t).every(n=>A(e[n],t[n])):!1}var j=Object.prototype.hasOwnProperty;function M(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=N(e)&&N(t);if(!r&&!(P(e)&&P(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l{b.setTimeout(t,e)})}function ie(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:M(e,t)}function I(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ae(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var L=Symbol();function oe(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===L?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function se(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var ce=(()=>{let e=()=>S;return{isServer(){return e()},setIsServer(t){e=t}}})();function le(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var ue=x;function de(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=ue,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var R=de(),fe=new class extends _{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function pe(e){return Math.min(1e3*2**e,3e4)}function me(e){return(e??`online`)!==`online`||fe.isOnline()}var he=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function ge(e){let t=!1,n=0,r,i=le(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new he(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>v.isFocused()&&(e.networkMode===`always`||fe.isOnline())&&e.canRun(),u=()=>me(e.networkMode)&&e.canRun(),d=e=>{a()||(r?.(),i.resolve(e))},f=e=>{a()||(r?.(),i.reject(e))},p=()=>new Promise(t=>{r=e=>{(a()||l())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),m=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(d).catch(r=>{if(a())return;let i=e.retry??(ce.isServer()?0:3),o=e.retryDelay??pe,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&nl()?void 0:p()).then(()=>{t?f(r):m()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:u,start:()=>(u()?m():p().then(m),i)}}var _e=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),T(this.gcTime)&&(this.#e=b.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ce.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(b.clearTimeout(this.#e),this.#e=void 0)}};function ve(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{se(e,()=>t.signal,()=>n=!0)},u=oe(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?ae:I;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?be:ye,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:ye(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(ct.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function ye(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function be(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var xe=class extends _e{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=we(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=we(this.options);e.data!==void 0&&(this.setState(Ce(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=ie(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(C).catch(C):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>O(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===L||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>D(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!E(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#a&&(this.#s||this.#c()?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}#c(){return this.state.fetchStatus===`paused`&&this.state.status===`pending`}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=oe(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?ve(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta}),this.#a=ge({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof he&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#a.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof he){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...Se(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Ce(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),R.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Se(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:me(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Ce(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function we(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Te=class extends _e{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||z(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=ge({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});let r=this.state.status===`pending`,i=!this.#r.canStart();try{if(r)t();else{this.#i({type:`pending`,variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:i})}let a=await this.#r.start();return await this.#n.config.onSuccess?.(a,e,this.state.context,this,n),await this.options.onSuccess?.(a,e,this.state.context,n),await this.#n.config.onSettled?.(a,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(a,null,e,this.state.context,n),this.#i({type:`success`,data:a}),a}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),R.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function z(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Ee=class extends _{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){let r=new Te({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=De(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=De(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=De(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=De(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){R.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>te(t,e))}findAll(e={}){return this.getAll().filter(t=>te(e,t))}notify(e){R.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return R.batch(()=>Promise.all(e.map(e=>e.continue().catch(C))))}};function De(e){return e.options.scope?.id}var Oe=class extends _{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??ne(r,t),a=this.get(i);return a||(a=new xe({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){R.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>ee(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>ee(e,t)):t}notify(e){R.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){R.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){R.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},ke=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new Oe,this.#t=e.mutationCache||new Ee,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=v.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=fe.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(D(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=w(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return R.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;R.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return R.batch(()=>(n.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=R.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(C).catch(C)}invalidateQueries(e,t={}){return R.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=R.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(C)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(C)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(D(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(C).catch(C)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(C).catch(C)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return fe.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(k(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{A(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(k(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{A(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=ne(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===L&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},Ae=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})),je=o(((e,t)=>{t.exports=Ae()})),B=c(f(),1),V=je(),Me=B.createContext(void 0),Ne=({client:e,children:t})=>(B.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,V.jsx)(Me.Provider,{value:e,children:t})),Pe=typeof window<`u`?B.useLayoutEffect:B.useEffect;function H(e){let t=B.useRef({value:e,prev:null}),n=t.current.value;return e!==n&&(t.current={value:e,prev:n}),t.current.prev}function Fe(e,t,n={},r={}){B.useEffect(()=>{if(!e.current||r.disabled||typeof IntersectionObserver!=`function`)return;let i=new IntersectionObserver(([e])=>{t(e)},n);return i.observe(e.current),()=>{i.disconnect()}},[t,n,r.disabled,e])}function Ie(e){let t=B.useRef(null);return B.useImperativeHandle(e,()=>t.current,[]),t}function Le(e){return e[e.length-1]}function Re(e){return typeof e==`function`}function ze(e,t){return Re(e)?e(t):e}var Be=Object.prototype.hasOwnProperty,Ve=Object.prototype.propertyIsEnumerable;function He(e){for(let t in e)if(Be.call(e,t))return!0;return!1}var Ue=()=>Object.create(null),We=(e,t)=>Ge(e,t,Ue);function Ge(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=Ye(e)&&Ye(i);if(!a&&!(qe(e)&&qe(i)))return i;let o=a?e:Ke(e);if(!o)return i;let s=a?i:Ke(i);if(!s)return i;let c=o.length,l=s.length,u=a?Array(l):n(),d=0;for(let t=0;ti||!Xe(e[o],t[o],n)))return!1;return i===a}return!1}function Ze(e){let t,n,r=new Promise((e,r)=>{t=e,n=r});return r.status=`pending`,r.resolve=n=>{r.status=`resolved`,r.value=n,t(n),e?.(n)},r.reject=e=>{r.status=`rejected`,n(e)},r}function Qe(e){return!!(e&&typeof e==`object`&&typeof e.then==`function`)}function $e(e){return e.replace(/[\x00-\x1f\x7f]/g,``)}function et(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return $e(t)}var tt=[`http:`,`https:`,`mailto:`,`tel:`];function nt(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function rt(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=et(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=et(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function it(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function at(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n{e.next&&(e.prev?(e.prev.next=e.next,e.next.prev=e.prev,e.next=void 0,r&&(r.next=e,e.prev=r)):(e.next.prev=void 0,n=e.next,e.next=void 0,r&&(e.prev=r,r.next=e)),r=e)};return{get(e){let n=t.get(e);if(n)return i(n),n.value},set(a,o){if(t.size>=e&&n){let e=n;t.delete(e.key),e.next&&(n=e.next,e.next.prev=void 0),e===r&&(r=void 0)}let s=t.get(a);if(s)s.value=o,i(s);else{let e={key:a,value:o,prev:r};r&&(r.next=e),r=e,n||=e,t.set(a,e)}},clear(){t.clear(),n=void 0,r=void 0}}}var ct=4,lt=5;function ut(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=e.indexOf(`}`,t);return n===-1||t+1>=e.length?null:[t,n]}function dt(e,t,n=new Uint16Array(6)){let r=e.indexOf(`/`,t),i=r===-1?e.length:r,a=e.substring(t,i);if(!a||!a.includes(`$`))return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n;if(a===`$`){let r=e.length;return n[0]=2,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n}if(a.charCodeAt(0)===36)return n[0]=1,n[1]=t,n[2]=t+1,n[3]=i,n[4]=i,n[5]=i,n;let o=ut(a);if(o){let[r,s]=o,c=a.charCodeAt(r+1);if(c===45){if(r+2!e.parse&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=gt(1,n.fullPath??n.from,f,p,m);o=e,e.depth=a,e.parent=i,i.dynamic??=[],i.dynamic.push(e)}break}case 3:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),f=c&&!!(t||s),p=t?f?t:t.toLowerCase():void 0,m=s?f?s:s.toLowerCase():void 0,h=!l&&i.optional?.find(e=>!e.parse&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=gt(3,n.fullPath??n.from,f,p,m);o=e,e.parent=i,e.depth=a,i.optional??=[],i.optional.push(e)}break}case 2:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),l=c&&!!(t||s),f=t?l?t:t.toLowerCase():void 0,p=s?l?s:s.toLowerCase():void 0,m=gt(2,n.fullPath??n.from,l,f,p);o=m,m.parent=i,m.depth=a,i.wildcard??=[],i.wildcard.push(m)}}i=o}if(l&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf(`/`)+1)===95){let e=ht(n.fullPath??n.from);e.kind=lt,e.parent=i,a++,e.depth=a,i.pathless??=[],i.pathless.push(e),i=e}let u=(n.path||!n.children)&&!n.isRoot;if(u&&r.endsWith(`/`)){let e=ht(n.fullPath??n.from);e.kind=ct,e.parent=i,a++,e.depth=a,i.index=e,i=e}i.parse=l??null,i.priority=n.options?.params?.priority??0,u&&!i.route&&(i.route=n,i.fullPath=n.fullPath??n.from)}if(n.children)for(let r of n.children)ft(e,t,r,s,i,a,o)}function pt(e,t){if(e.parse&&!t.parse)return-1;if(!e.parse&&t.parse)return 1;if(e.parse&&t.parse&&(e.priority||t.priority))return t.priority-e.priority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function mt(e){if(e.pathless)for(let t of e.pathless)mt(t);if(e.static)for(let t of e.static.values())mt(t);if(e.staticInsensitive)for(let t of e.staticInsensitive.values())mt(t);if(e.dynamic?.length){e.dynamic.sort(pt);for(let t of e.dynamic)mt(t)}if(e.optional?.length){e.optional.sort(pt);for(let t of e.optional)mt(t)}if(e.wildcard?.length){e.wildcard.sort(pt);for(let t of e.wildcard)mt(t)}}function ht(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function gt(e,t,n,r,i){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,priority:0,caseSensitive:n,prefix:r,suffix:i}}function _t(e,t){let n=ht(`/`),r=new Uint16Array(6);for(let t of e)ft(!1,r,t,1,n,0);mt(n),t.masksTree=n,t.flatCache=st(1e3)}function vt(e,t){e||=`/`;let n=t.flatCache.get(e);if(n)return n;let r=Ct(e,t.masksTree);return t.flatCache.set(e,r),r}function yt(e,t,n,r,i){e||=`/`,r||=`/`;let a=t?`case\0${e}`:e,o=i.singleCache.get(a);return o||(o=ht(`/`),ft(t,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(a,o)),Ct(r,o,n)}function bt(e,t,n=!1){let r=n?e:`nofuzz\0${e}`,i=t.matchCache.get(r);if(i!==void 0)return i;e||=`/`;let a;try{a=Ct(e,t.segmentTree,n)}catch(e){if(e instanceof URIError)a=null;else throw e}return a&&(a.branch=Tt(a.route)),t.matchCache.set(r,a),a}function xt(e){return e===`/`?e:e.replace(/\/{1,}$/,``)}function St(e,t=!1,n){let r=ht(e.fullPath),i=new Uint16Array(6),a={},o={},s=0;return ft(t,i,e,1,r,0,e=>{if(n?.(e,s),e.id in a&&ot(),a[e.id]=e,s!==0&&e.path){let t=xt(e.fullPath);(!o[t]||e.fullPath.endsWith(`/`))&&(o[t]=e)}s++}),mt(r),{processedTree:{segmentTree:r,singleCache:st(1e3),matchCache:st(1e3),flatCache:null,masksTree:null},routesById:a,routesByPath:o}}function Ct(e,t,n=!1){let r=e.split(`/`),i=Dt(e,r,t,n);if(!i)return null;let[a]=wt(e,r,i);return{route:i.node.route,rawParams:a}}function wt(e,t,n){let r=Et(n.node),i=null,a=Object.create(null),o=n.extract?.part??0,s=n.extract?.node??0,c=n.extract?.path??0,l=n.extract?.segment??0;for(;s=0;e--){let n=i.wildcard[e],{prefix:r,suffix:a}=n;if(!(r&&(v||!(n.caseSensitive?y:b??=y.toLowerCase()).startsWith(r)))){if(a){if(v)continue;let e=t.slice(u).join(`/`).slice(-a.length);if((n.caseSensitive?e:e.toLowerCase())!==a)continue}s.push({node:n,index:o,skipped:d,depth:f+1,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}}if(i.optional){let e=d|1<=0;n--){let r=i.optional[n];s.push({node:r,index:u,skipped:e,depth:t,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}if(!v)for(let e=i.optional.length-1;e>=0;e--){let n=i.optional[e],{prefix:r,suffix:a}=n;if(r||a){let e=n.caseSensitive?y:b??=y.toLowerCase();if(r&&!e.startsWith(r)||a&&!e.endsWith(a))continue}s.push({node:n,index:u+1,skipped:d,depth:t,statics:p,dynamics:m,optionals:h+Ot(o,u),extract:g,rawParams:_})}}if(!v&&i.dynamic&&y)for(let e=i.dynamic.length-1;e>=0;e--){let t=i.dynamic[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?y:b??=y.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}s.push({node:t,index:u+1,skipped:d,depth:f+1,statics:p,dynamics:m+Ot(o,u),optionals:h,extract:g,rawParams:_})}if(!v&&i.staticInsensitive){let e=i.staticInsensitive.get(b??=y.toLowerCase());e&&s.push({node:e,index:u+1,skipped:d,depth:f+1,statics:p+Ot(o,u),dynamics:m,optionals:h,extract:g,rawParams:_})}if(!v&&i.static){let e=i.static.get(y);e&&s.push({node:e,index:u+1,skipped:d,depth:f+1,statics:p+Ot(o,u),dynamics:m,optionals:h,extract:g,rawParams:_})}if(i.pathless){let e=f+1;for(let t=i.pathless.length-1;t>=0;t--){let n=i.pathless[t];s.push({node:n,index:u,skipped:d,depth:e,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}}}if(l)return l;if(r&&c){let n=c.index;for(let e=0;ee.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===ct)>(e.node.kind===ct)||t.node.kind===ct==(e.node.kind===ct)&&t.depth>e.depth)))}function Mt(e){return Nt(e.filter(e=>e!==void 0).join(`/`))}function Nt(e){return e.replace(/\/{2,}/g,`/`)}function Pt(e){return e===`/`?e:e.replace(/^\/{1,}/,``)}function Ft(e){let t=e.length;return t>1&&e[t-1]===`/`?e.replace(/\/{1,}$/,``):e}function It(e){return Ft(Pt(e))}function Lt(e,t){return e?.endsWith(`/`)&&e!==`/`&&e!==`${t}/`?e.slice(0,-1):e}function Rt(e,t,n){return Lt(e,n)===Lt(t,n)}function zt({base:e,to:t,trailingSlash:n=`never`,cache:r}){let i=t.startsWith(`/`),a=!i&&t===`.`,o;if(r){o=i?t:a?e:e+`\0`+t;let n=r.get(o);if(n)return n}let s;if(a)s=e.split(`/`);else if(i)s=t.split(`/`);else{for(s=e.split(`/`);s.length>1&&Le(s)===``;)s.pop();let n=t.split(`/`);for(let e=0,t=n.length;e1&&(Le(s)===``?n===`never`&&s.pop():n===`always`&&s.push(``));let c=Nt(s.join(`/`))||`/`;return o&&r&&r.set(o,c),c}function Bt(e){let t=new Map(e.map(e=>[encodeURIComponent(e),e])),n=Array.from(t.keys()).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`),r=new RegExp(n,`g`);return e=>e.replace(r,e=>t.get(e)??e)}function Vt(e,t,n){let r=t[e];return typeof r==`string`?e===`_splat`?/^[a-zA-Z0-9\-._~!/]*$/.test(r)?r:r.split(`/`).map(e=>Ut(e,n)).join(`/`):Ut(r,n):r}function Ht({path:e,params:t,decoder:n,...r}){let i=!1,a=Object.create(null);if(!e||e===`/`)return{interpolatedPath:`/`,usedParams:a,isMissingParams:i};if(!e.includes(`$`))return{interpolatedPath:e,usedParams:a,isMissingParams:i};let o=e.length,s=0,c,l=``;for(;s{t[0]===`?`&&(t=t.substring(1));let n=qt(t);for(let t in n){let r=n[t];if(typeof r==`string`)try{n[t]=e(r)}catch{}}return n}}function Zt(e,t){let n=typeof t==`function`;function r(r){if(typeof r==`object`&&r)try{return e(r)}catch{}else if(n&&typeof r==`string`)try{return t(r),e(r)}catch{}return r}return e=>{let t=Gt(e,r);return t?`?${t}`:``}}var Qt=`__root__`;function $t(e){if(e.statusCode=e.statusCode||e.code||307,!e._builtLocation&&!e.reloadDocument&&typeof e.href==`string`)try{new URL(e.href),e.reloadDocument=!0}catch{}let t=new Headers(e.headers);e.href&&t.get(`Location`)===null&&t.set(`Location`,e.href);let n=new Response(null,{status:e.statusCode,headers:t});if(n.options=e,e.throw)throw n;return n}function en(e){return e instanceof Response&&!!e.options}var tn=e=>{if(!e.rendered)return e.rendered=!0,e.onReady?.()},nn=e=>e.stores.matchesId.get().some(t=>e.stores.matchStores.get(t)?.get()._forcePending),rn=(e,t)=>!!(e.preload&&!e.router.stores.matchStores.has(t)),an=(e,t,n=!0)=>{let r={...e.router.options.context??{}},i=n?t:t-1;for(let t=0;t<=i;t++){let n=e.matches[t];if(!n)continue;let i=e.router.getMatch(n.id);i&&Object.assign(r,i.__routeContext,i.__beforeLoadContext)}return r},on=(e,t)=>{if(!e.matches.length)return;let n=t.routeId,r=e.matches.findIndex(t=>t.routeId===e.router.routeTree.id),i=r>=0?r:0,a=n?e.matches.findIndex(e=>e.routeId===n):e.firstBadMatchIndex??e.matches.length-1;a<0&&(a=i);for(let t=a;t>=0;t--){let n=e.matches[t];if(e.router.looseRoutesById[n.routeId].options.notFoundComponent)return t}return n?a:i},sn=(e,t,n)=>{if(!(!en(n)&&!Wt(n)))throw en(n)&&n.redirectHandled&&!n.options.reloadDocument?n:(t&&(t._nonReactive.beforeLoadPromise?.resolve(),t._nonReactive.loaderPromise?.resolve(),t._nonReactive.beforeLoadPromise=void 0,t._nonReactive.loaderPromise=void 0,t._nonReactive.error=n,e.updateMatch(t.id,r=>({...r,status:en(n)?`redirected`:Wt(n)?`notFound`:r.status===`pending`?`success`:r.status,context:an(e,t.index),isFetching:!1,error:n})),Wt(n)&&!n.routeId&&(n.routeId=t.routeId),t._nonReactive.loadPromise?.resolve()),en(n)&&(e.rendered=!0,n.options._fromLocation=e.location,n.redirectHandled=!0,n=e.router.resolveRedirect(n)),n)},cn=(e,t)=>{let n=e.router.getMatch(t);return!!(!n||n._nonReactive.dehydrated)},ln=(e,t,n)=>{let r=an(e,n);e.updateMatch(t,e=>({...e,context:r}))},un=(e,t,n)=>{let{id:r,routeId:i}=e.matches[t],a=e.router.looseRoutesById[i];if(n instanceof Promise)throw n;e.firstBadMatchIndex??=t,sn(e,e.router.getMatch(r),n);try{a.options.onError?.(n)}catch(t){n=t,sn(e,e.router.getMatch(r),n)}e.updateMatch(r,e=>(e._nonReactive.beforeLoadPromise?.resolve(),e._nonReactive.beforeLoadPromise=void 0,e._nonReactive.loadPromise?.resolve(),{...e,error:n,status:`error`,isFetching:!1,updatedAt:Date.now(),abortController:new AbortController})),!e.preload&&!en(n)&&!Wt(n)&&(e.serialError??=n)},dn=(e,t,n,r)=>{if(r._nonReactive.pendingTimeout!==void 0)return;let i=n.options.pendingMs??e.router.options.defaultPendingMs;if(e.onReady&&!rn(e,t)&&(n.options.loader||n.options.beforeLoad||Sn(n))&&typeof i==`number`&&i!==1/0&&(n.options.pendingComponent??e.router.options?.defaultPendingComponent)){let t=setTimeout(()=>{tn(e)},i);r._nonReactive.pendingTimeout=t}},fn=(e,t,n)=>{let r=e.router.getMatch(t);if(!r._nonReactive.beforeLoadPromise&&!r._nonReactive.loaderPromise)return;dn(e,t,n,r);let i=()=>{let n=e.router.getMatch(t);n.preload&&(n.status===`redirected`||n.status===`notFound`)&&sn(e,n,n.error)};return r._nonReactive.beforeLoadPromise?r._nonReactive.beforeLoadPromise.then(i):i()},pn=(e,t,n,r)=>{let i=e.router.getMatch(t),a=i._nonReactive.loadPromise;i._nonReactive.loadPromise=Ze(()=>{a?.resolve(),a=void 0});let{paramsError:o,searchError:s}=i;o&&un(e,n,o),s&&un(e,n,s),dn(e,t,r,i);let c=new AbortController,l=!1,u=()=>{l||(l=!0,e.updateMatch(t,e=>({...e,isFetching:`beforeLoad`,fetchCount:e.fetchCount+1,abortController:c})))},d=()=>{i._nonReactive.beforeLoadPromise?.resolve(),i._nonReactive.beforeLoadPromise=void 0,e.updateMatch(t,e=>({...e,isFetching:!1}))};if(!r.options.beforeLoad){e.router.batch(()=>{u(),d()});return}i._nonReactive.beforeLoadPromise=Ze();let f={...an(e,n,!1),...i.__routeContext},{search:p,params:m,cause:h}=i,g=rn(e,t),_={search:p,abortController:c,params:m,preload:g,context:f,location:e.location,navigate:t=>e.router.navigate({...t,_fromLocation:e.location}),buildLocation:e.router.buildLocation,cause:g?`preload`:h,matches:e.matches,routeId:r.id,...e.router.options.additionalContext},v=r=>{if(r===void 0){e.router.batch(()=>{u(),d()});return}(en(r)||Wt(r))&&(u(),un(e,n,r)),e.router.batch(()=>{u(),e.updateMatch(t,e=>({...e,__beforeLoadContext:r})),d()})},y;try{if(y=r.options.beforeLoad(_),Qe(y))return u(),y.catch(t=>{un(e,n,t)}).then(v)}catch(t){u(),un(e,n,t)}v(y)},mn=(e,t)=>{let{id:n,routeId:r}=e.matches[t],i=e.router.looseRoutesById[r],a=()=>s(),o=()=>pn(e,n,t,i),s=()=>{if(cn(e,n))return;let t=fn(e,n,i);return Qe(t)?t.then(o):o()};return a()},hn=(e,t,n)=>{let r=e.router.getMatch(t);if(!r||!n.options.head&&!n.options.scripts&&!n.options.headers)return;let i={ssr:e.router.options.ssr,matches:e.matches,match:r,params:r.params,loaderData:r.loaderData};return Promise.all([n.options.head?.(i),n.options.scripts?.(i),n.options.headers?.(i)]).then(([e,t,n])=>({meta:e?.meta,links:e?.links,headScripts:e?.scripts,headers:n,scripts:t,styles:e?.styles}))},gn=(e,t,n,r,i)=>{let a=t[r-1],{params:o,loaderDeps:s,abortController:c,cause:l}=e.router.getMatch(n),u=an(e,r),d=rn(e,n);return{params:o,deps:s,preload:!!d,parentMatchPromise:a,abortController:c,context:u,location:e.location,navigate:t=>e.router.navigate({...t,_fromLocation:e.location}),cause:d?`preload`:l,route:i,...e.router.options.additionalContext}},_n=async(e,t,n,r,i)=>{try{let a=e.router.getMatch(n);try{xn(i);let o=i.options.loader,s=typeof o==`function`?o:o?.handler,c=s?.(gn(e,t,n,r,i)),l=!!s&&Qe(c);if((l||i._lazyPromise||i._componentsPromise||i.options.head||i.options.scripts||i.options.headers||a._nonReactive.minPendingPromise)&&e.updateMatch(n,e=>({...e,isFetching:`loader`})),s){let t=l?await c:c;sn(e,e.router.getMatch(n),t),t!==void 0&&e.updateMatch(n,e=>({...e,loaderData:t}))}i._lazyPromise&&await i._lazyPromise;let u=a._nonReactive.minPendingPromise;u&&await u,i._componentsPromise&&await i._componentsPromise,e.updateMatch(n,t=>({...t,error:void 0,context:an(e,r),status:`success`,isFetching:!1,updatedAt:Date.now()}))}catch(t){let o=t;if(o?.name===`AbortError`){if(a.abortController.signal.aborted){a._nonReactive.loaderPromise?.resolve(),a._nonReactive.loaderPromise=void 0;return}e.updateMatch(n,t=>({...t,status:t.status===`pending`?`success`:t.status,isFetching:!1,context:an(e,r)}));return}let s=a._nonReactive.minPendingPromise;s&&await s,Wt(t)&&await i.options.notFoundComponent?.preload?.(),sn(e,e.router.getMatch(n),t);try{i.options.onError?.(t)}catch(t){o=t,sn(e,e.router.getMatch(n),t)}!en(o)&&!Wt(o)&&await xn(i,[`errorComponent`]),e.updateMatch(n,t=>({...t,error:o,context:an(e,r),status:`error`,isFetching:!1}))}}catch(t){let r=e.router.getMatch(n);r&&(r._nonReactive.loaderPromise=void 0),sn(e,r,t)}},vn=async(e,t,n)=>{async function r(r,a,c,l,d){let f=Date.now()-a.updatedAt,p=r?d.options.preloadStaleTime??e.router.options.defaultPreloadStaleTime??3e4:d.options.staleTime??e.router.options.defaultStaleTime??0,m=d.options.shouldReload,h=typeof m==`function`?m(gn(e,t,i,n,d)):m,{status:g,invalid:_}=l,v=f>=p&&(!!e.forceStaleReload||l.cause===`enter`||c!==void 0&&c!==l.id);o=g===`success`&&(_||(h??v)),r&&d.options.preload===!1||(o&&!e.sync&&u?(s=!0,(async()=>{try{await _n(e,t,i,n,d);let r=e.router.getMatch(i);r._nonReactive.loaderPromise?.resolve(),r._nonReactive.loadPromise?.resolve(),r._nonReactive.loaderPromise=void 0,r._nonReactive.loadPromise=void 0}catch(t){en(t)&&await e.router.navigate(t.options)}})()):g!==`success`||o?await _n(e,t,i,n,d):ln(e,i,n))}let{id:i,routeId:a}=e.matches[n],o=!1,s=!1,c=e.router.looseRoutesById[a],l=c.options.loader,u=((typeof l==`function`?void 0:l?.staleReloadMode)??e.router.options.defaultStaleReloadMode)!==`blocking`;if(cn(e,i)){if(!e.router.getMatch(i))return e.matches[n];ln(e,i,n)}else{let t=e.router.getMatch(i),o=e.router.stores.matchesId.get()[n],s=(o&&e.router.stores.matchStores.get(o)||null)?.routeId===a?o:e.router.stores.matches.get().find(e=>e.routeId===a)?.id,l=rn(e,i);if(t._nonReactive.loaderPromise){if(t.status===`success`&&!e.sync&&!t.preload&&u)return t;await t._nonReactive.loaderPromise;let n=e.router.getMatch(i),a=n._nonReactive.error||n.error;a&&sn(e,n,a),n.status===`pending`&&await r(l,t,s,n,c)}else{let n=l&&!e.router.stores.matchStores.has(i),a=e.router.getMatch(i);a._nonReactive.loaderPromise=Ze(),n!==a.preload&&e.updateMatch(i,e=>({...e,preload:n})),await r(l,t,s,a,c)}}let d=e.router.getMatch(i);s||(d._nonReactive.loaderPromise?.resolve(),d._nonReactive.loadPromise?.resolve(),d._nonReactive.loadPromise=void 0),clearTimeout(d._nonReactive.pendingTimeout),d._nonReactive.pendingTimeout=void 0,s||(d._nonReactive.loaderPromise=void 0),d._nonReactive.dehydrated=void 0;let f=s?d.isFetching:!1;return f!==d.isFetching||d.invalid!==!1?(e.updateMatch(i,e=>({...e,isFetching:f,invalid:!1})),e.router.getMatch(i)):d};async function yn(e){let t=e,n=[];nn(t.router)&&tn(t);let r;for(let e=0;e({...e,...a?{status:`success`,globalNotFound:!0,error:void 0}:{status:`notFound`,error:l},isFetching:!1})),u=e,await xn(r,[`notFoundComponent`])}else if(!t.preload){let e=t.matches[0];e.globalNotFound||t.router.getMatch(e.id)?.globalNotFound&&t.updateMatch(e.id,e=>({...e,globalNotFound:!1,error:void 0}))}if(t.serialError&&t.firstBadMatchIndex!==void 0){let e=t.router.looseRoutesById[t.matches[t.firstBadMatchIndex].routeId];await xn(e,[`errorComponent`])}for(let e=0;e<=u;e++){let{id:n,routeId:r}=t.matches[e],i=t.router.looseRoutesById[r];try{let e=hn(t,n,i);if(e){let r=await e;t.updateMatch(n,e=>({...e,...r}))}}catch(e){console.error(`Error executing head for route ${r}:`,e)}}let d=tn(t);if(Qe(d)&&await d,l)throw l;if(t.serialError&&!t.preload&&!t.onReady)throw t.serialError;return t.matches}function bn(e,t){let n=t.map(t=>e.options[t]?.preload?.()).filter(Boolean);if(n.length!==0)return Promise.all(n)}function xn(e,t=Cn){!e._lazyLoaded&&e._lazyPromise===void 0&&(e.lazyFn?e._lazyPromise=e.lazyFn().then(t=>{let{id:n,...r}=t.options;Object.assign(e.options,r),e._lazyLoaded=!0,e._lazyPromise=void 0}):e._lazyLoaded=!0);let n=()=>e._componentsLoaded?void 0:t===Cn?(()=>{if(e._componentsPromise===void 0){let t=bn(e,Cn);t?e._componentsPromise=t.then(()=>{e._componentsLoaded=!0,e._componentsPromise=void 0}):e._componentsLoaded=!0}return e._componentsPromise})():bn(e,t);return e._lazyPromise?e._lazyPromise.then(n):n()}function Sn(e){for(let t of Cn)if(e.options[t]?.preload)return!0;return!1}var Cn=[`component`,`errorComponent`,`pendingComponent`,`notFoundComponent`];function wn(e){return{input:({url:t})=>{for(let n of e)t=En(n,t);return t},output:({url:t})=>{for(let n=e.length-1;n>=0;n--)t=Dn(e[n],t);return t}}}function Tn(e){let t=It(e.basepath),n=`/${t}`,r=e.caseSensitive?n:n.toLowerCase(),i=`${r}/`;return{input:({url:t})=>{let a=e.caseSensitive?t.pathname:t.pathname.toLowerCase();return a===r?t.pathname=`/`:a.startsWith(i)&&(t.pathname=t.pathname.slice(n.length)),t},output:({url:e})=>(e.pathname=Mt([`/`,t,e.pathname]),e)}}function En(e,t){let n=e?.input?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function Dn(e,t){let n=e?.output?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function On(e,t){let{createMutableStore:n,createReadonlyStore:r,batch:i,init:a}=t,o=new Map,s=new Map,c=new Map,l=n(e.status),u=n(e.loadedAt),d=n(e.isLoading),f=n(e.isTransitioning),p=n(e.location),m=n(e.resolvedLocation),h=n(e.statusCode),g=n(e.redirect),_=n([]),v=n([]),y=n([]),b=r(()=>kn(o,_.get())),x=r(()=>kn(s,v.get())),S=r(()=>kn(c,y.get())),C=r(()=>_.get()[0]),w=r(()=>_.get().some(e=>o.get(e)?.get().status===`pending`)),T=r(()=>({locationHref:p.get().href,resolvedLocationHref:m.get()?.href,status:l.get()})),E=r(()=>({status:l.get(),loadedAt:u.get(),isLoading:d.get(),isTransitioning:f.get(),matches:b.get(),location:p.get(),resolvedLocation:m.get(),statusCode:h.get(),redirect:g.get()})),D=st(64);function O(e){let t=D.get(e);return t||(t=r(()=>{let t=_.get();for(let n of t){let t=o.get(n);if(t&&t.routeId===e)return t.get()}}),D.set(e,t)),t}let ee={status:l,loadedAt:u,isLoading:d,isTransitioning:f,location:p,resolvedLocation:m,statusCode:h,redirect:g,matchesId:_,pendingIds:v,cachedIds:y,matches:b,pendingMatches:x,cachedMatches:S,firstId:C,hasPending:w,matchRouteDeps:T,matchStores:o,pendingMatchStores:s,cachedMatchStores:c,__store:E,getRouteMatchStore:O,setMatches:te,setPending:ne,setCached:k};te(e.matches),a?.(ee);function te(e){An(e,o,_,n,i)}function ne(e){An(e,s,v,n,i)}function k(e){An(e,c,y,n,i)}return ee}function kn(e,t){let n=[];for(let r of t){let t=e.get(r);t&&n.push(t.get())}return n}function An(e,t,n,r,i){let a=e.map(e=>e.id),o=new Set(a);i(()=>{for(let e of t.keys())o.has(e)||t.delete(e);for(let n of e){let e=t.get(n.id);if(!e){let e=r(n);e.routeId=n.routeId,t.set(n.id,e);continue}e.routeId=n.routeId,e.get()!==n&&e.set(n)}at(n.get(),a)||n.set(a)})}var jn=`__TSR_index`,Mn=`popstate`,Nn=`beforeunload`;function Pn(e){let t=e.getLocation(),n=new Set,r=r=>{t=e.getLocation(),n.forEach(e=>e({location:t,action:r}))},i=n=>{e.notifyOnIndexChange??!0?r(n):t=e.getLocation()},a=async({task:n,navigateOpts:r,...i})=>{if(r?.ignoreBlocker??!1){n();return}let a=e.getBlockers?.()??[],o=i.type===`PUSH`||i.type===`REPLACE`;if(typeof document<`u`&&a.length&&o)for(let n of a){let r=Rn(i.path,i.state);if(await n.blockerFn({currentLocation:t,nextLocation:r,action:i.type})){e.onBlocked?.();return}}n()};return{get location(){return t},get length(){return e.getLength()},subscribers:n,subscribe:e=>(n.add(e),()=>{n.delete(e)}),push:(n,i,o)=>{let s=t.state[jn];i=Fn(s+1,i),a({task:()=>{e.pushState(n,i),r({type:`PUSH`})},navigateOpts:o,type:`PUSH`,path:n,state:i})},replace:(n,i,o)=>{let s=t.state[jn];i=Fn(s,i),a({task:()=>{e.replaceState(n,i),r({type:`REPLACE`})},navigateOpts:o,type:`REPLACE`,path:n,state:i})},go:(t,n)=>{a({task:()=>{e.go(t),i({type:`GO`,index:t})},navigateOpts:n,type:`GO`})},back:t=>{a({task:()=>{e.back(t?.ignoreBlocker??!1),i({type:`BACK`})},navigateOpts:t,type:`BACK`})},forward:t=>{a({task:()=>{e.forward(t?.ignoreBlocker??!1),i({type:`FORWARD`})},navigateOpts:t,type:`FORWARD`})},canGoBack:()=>t.state[jn]!==0,createHref:t=>e.createHref(t),block:t=>{if(!e.setBlockers)return()=>{};let n=e.getBlockers?.()??[];return e.setBlockers([...n,t]),()=>{let n=e.getBlockers?.()??[];e.setBlockers?.(n.filter(e=>e!==t))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:r}}function Fn(e,t){t||={};let n=zn();return{...t,key:n,__TSR_key:n,[jn]:e}}function In(e){let t=e?.window??(typeof document<`u`?window:void 0),n=t.history.pushState,r=t.history.replaceState,i=[],a=()=>i,o=e=>i=e,s=e?.createHref??(e=>e),c=e?.parseLocation??(()=>Rn(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){let e=zn();t.history.replaceState({[jn]:0,key:e,__TSR_key:e},``)}let l=c(),u,d=!1,f=!1,p=!1,m=!1,h=()=>l,g,_,v=()=>{g&&(C._ignoreSubscribers=!0,(g.isPush?t.history.pushState:t.history.replaceState)(g.state,``,g.href),C._ignoreSubscribers=!1,g=void 0,_=void 0,u=void 0)},y=(e,t,n)=>{let r=s(t);_||(u=l),l=Rn(t,n),g={href:r,state:n,isPush:g?.isPush||e===`push`},_||=Promise.resolve().then(()=>v())},b=e=>{l=c(),C.notify({type:e})},x=async()=>{if(f){f=!1;return}let e=c(),n=e.state[jn]-l.state[jn],r=n===1,i=n===-1,o=!r&&!i||d;d=!1;let s=o?`GO`:i?`BACK`:`FORWARD`,u=o?{type:`GO`,index:n}:{type:i?`BACK`:`FORWARD`};if(p)p=!1;else{let n=a();if(typeof document<`u`&&n.length){for(let r of n)if(await r.blockerFn({currentLocation:l,nextLocation:e,action:s})){f=!0,t.history.go(1),C.notify(u);return}}}l=c(),C.notify(u)},S=e=>{if(m){m=!1;return}let t=!1,n=a();if(typeof document<`u`&&n.length)for(let e of n){let n=e.enableBeforeUnload??!0;if(n===!0){t=!0;break}if(typeof n==`function`&&n()===!0){t=!0;break}}if(t)return e.preventDefault(),e.returnValue=``},C=Pn({getLocation:h,getLength:()=>t.history.length,pushState:(e,t)=>y(`push`,e,t),replaceState:(e,t)=>y(`replace`,e,t),back:e=>(e&&(p=!0),m=!0,t.history.back()),forward:e=>{e&&(p=!0),m=!0,t.history.forward()},go:e=>{d=!0,t.history.go(e)},createHref:e=>s(e),flush:v,destroy:()=>{t.history.pushState=n,t.history.replaceState=r,t.removeEventListener(Nn,S,{capture:!0}),t.removeEventListener(Mn,x)},onBlocked:()=>{u&&l!==u&&(l=u)},getBlockers:a,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(Nn,S,{capture:!0}),t.addEventListener(Mn,x),t.history.pushState=function(...e){let r=n.apply(t.history,e);return C._ignoreSubscribers||b(`PUSH`),r},t.history.replaceState=function(...e){let n=r.apply(t.history,e);return C._ignoreSubscribers||b(`REPLACE`),n},C}function Ln(e){let t=e.replace(/[\x00-\x1f\x7f]/g,``);return t.startsWith(`//`)&&(t=`/`+t.replace(/^\/+/,``)),t}function Rn(e,t){let n=Ln(e),r=n.indexOf(`#`),i=n.indexOf(`?`),a=zn();return{href:n,pathname:n.substring(0,r>0?i>0?Math.min(r,i):r:i>0?i:n.length),hash:r>-1?n.substring(r):``,search:i>-1?n.slice(i,r===-1?void 0:r):``,state:t||{[jn]:0,key:a,__TSR_key:a}}}function zn(){return(Math.random()+1).toString(36).substring(7)}function Bn(e,t){let n=t,r=e;return{fromLocation:n,toLocation:r,pathChanged:n?.pathname!==r.pathname,hrefChanged:n?.href!==r.href,hashChanged:n?.hash!==r.hash}}var Vn=new WeakMap,Hn=class{constructor(e,t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this.resetNextScroll=!0,this.shouldViewTransition=void 0,this.isViewTransitionTypesSupported=void 0,this.subscribers=new Set,this.isScrollRestoring=!1,this.isScrollRestorationSetup=!1,this.routeBranchCache=new WeakMap,this.startTransition=e=>e(),this.update=e=>{let t=this.options,n=this.basepath??t?.basepath??`/`,r=this.basepath===void 0,i=t?.rewrite;if(this.options={...t,...e},this.isServer=this.options.isServer??typeof document>`u`,this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=Bt(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.history=this.options.history?this.options.history:In()),this.origin=this.options.origin,this.origin||=window?.origin&&window.origin!==`null`?window.origin:`http://localhost`,this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let e;this.resolvePathCache=st(1e3),e=this.buildRouteTree(),this.setRoutes(e)}if(!this.stores&&this.latestLocation){let e=this.getStoreConfig(this);this.batch=e.batch,this.stores=On(Gn(this.latestLocation),e),dr(this)}let a=!1,o=this.options.basepath??`/`,s=this.options.rewrite;if(r||n!==o||i!==s){this.basepath=o;let e=[],t=It(o);t&&t!==`/`&&e.push(Tn({basepath:o})),s&&e.push(s),this.rewrite=e.length===0?void 0:e.length===1?e[0]:wn(e),this.history&&this.updateLatestLocation(),a=!0}a&&this.stores&&this.stores.location.set(this.latestLocation),typeof window<`u`&&`CSS`in window&&typeof window.CSS?.supports==`function`&&(this.isViewTransitionTypesSupported=window.CSS.supports(`selector(:active-view-transition-type(a))`))},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{let e=St(this.routeTree,this.options.caseSensitive,(e,t)=>{e.init({originalIndex:t})});return this.options.routeMasks&&_t(this.options.routeMasks,e.processedTree),e},this.subscribe=(e,t)=>{let n={eventType:e,fn:t};return this.subscribers.add(n),()=>{this.subscribers.delete(n)}},this.emit=e=>{this.subscribers.forEach(t=>{t.eventType===e.type&&t.fn(e)})},this.parseLocation=(e,t)=>{let n=({pathname:e,search:n,hash:r,href:i,state:a})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(e)){let i=this.options.parseSearch(n),o=this.options.stringifySearch(i);return{href:e+o+r,publicHref:e+o+r,pathname:rt(e).path,external:!1,searchStr:o,search:We(t?.search,i),hash:rt(r.slice(1)).path,state:Ge(t?.state,a)}}let o=new URL(i,this.origin),s=En(this.rewrite,o),c=this.options.parseSearch(s.search),l=this.options.stringifySearch(c);return s.search=l,{href:s.href.replace(s.origin,``),publicHref:i,pathname:rt(s.pathname).path,external:!!this.rewrite&&s.origin!==this.origin,searchStr:l,search:We(t?.search,c),hash:rt(s.hash.slice(1)).path,state:Ge(t?.state,a)}},r=n(e),{__tempLocation:i,__tempKey:a}=r.state;if(i&&(!a||a===this.tempLocationKey)){let e=n(i);return e.state.key=r.state.key,e.state.__TSR_key=r.state.__TSR_key,delete e.state.__tempLocation,{...e,maskedLocation:r}}return r},this.resolvePathWithBase=(e,t)=>zt({base:e,to:t.includes(`//`)?Nt(t):t,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(e,t,n)=>typeof e==`string`?this.matchRoutesInternal({pathname:e,search:t},n):this.matchRoutesInternal(e,t),this.getMatchedRoutes=e=>qn({pathname:e,routesById:this.routesById,processedTree:this.processedTree}),this.cancelMatch=e=>{let t=this.getMatch(e);t&&(t.abortController.abort(),clearTimeout(t._nonReactive.pendingTimeout),t._nonReactive.pendingTimeout=void 0)},this.cancelMatches=()=>{this.stores.pendingIds.get().forEach(e=>{this.cancelMatch(e)}),this.stores.matchesId.get().forEach(e=>{if(this.stores.pendingMatchStores.has(e))return;let t=this.stores.matchStores.get(e)?.get();t&&(t.status===`pending`||t.isFetching===`loader`)&&this.cancelMatch(e)})},this.buildLocation=e=>{let t=(t={})=>{let n=t._fromLocation||this.pendingBuiltLocation||this.latestLocation,r=this.matchRoutesLightweight(n);t.from;let i=t.unsafeRelative===`path`?n.pathname:t.from??r.fullPath,a=t.to?`${t.to}`:void 0,o=r.search,s=Object.assign(Object.create(null),r.params),c=a?.charCodeAt(0)===47?`/`:this.resolvePathWithBase(i,`.`),l=a?this.resolvePathWithBase(c,a):c,u=t.params===!1||t.params===null?Object.create(null):(t.params??!0)===!0?s:Object.assign(s,ze(t.params,s)),d=this.routesByPath[Ft(l)],f;if(d)f=this.getRouteBranch(d);else if(l.includes(`$`))f=[];else{let e=this.getMatchedRoutes(l);f=e.matchedRoutes,this.options.notFoundRoute&&(!e.foundRoute||e.foundRoute.path!==`/`&&e.routeParams[`**`])&&(f=[...f,this.options.notFoundRoute])}if(f.length&&He(u))for(let e of f){let t=e.options.params?.stringify??e.options.stringifyParams;if(t)try{Object.assign(u,t(u))}catch{}}let p=e.leaveParams?l:rt(Ht({path:l,params:u,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path,m=o;if(e._includeValidateSearch&&this.options.search?.strict){let e={};f.forEach(t=>{if(t.options.validateSearch)try{Object.assign(e,Kn(t.options.validateSearch,{...e,...m}))}catch{}}),m=e}m=Jn({search:m,dest:t,destRoutes:f,_includeValidateSearch:e._includeValidateSearch}),m=We(o,m);let h=this.options.stringifySearch(m),g=t.hash===!0?n.hash:t.hash?ze(t.hash,n.hash):void 0,_=g?`#${g}`:``,v=t.state===!0?n.state:t.state?ze(t.state,n.state):{};v=Ge(n.state,v);let y=`${p}${h}${_}`,b,x,S=!1;if(this.rewrite){let e=new URL(y,this.origin),t=Dn(this.rewrite,e);b=e.href.replace(e.origin,``),t.origin===this.origin?x=t.pathname+t.search+t.hash:(x=t.href,S=!0)}else b=it(y),x=b;return{publicHref:x,href:b,pathname:p,search:m,searchStr:h,state:v,hash:g??``,external:S,unmaskOnReload:t.unmaskOnReload}},n=(n={},r)=>{let i=t(n),a=r?t(r):void 0;if(!a){let n=Object.create(null);if(this.options.routeMasks){let o=vt(i.pathname,this.processedTree);if(o){Object.assign(n,o.rawParams);let{from:i,params:s,...c}=o.route,l=s===!1||s===null?Object.create(null):(s??!0)===!0?n:Object.assign(n,ze(s,n));r={from:e.from,...c,params:l},a=t(r)}}}return a&&(i.maskedLocation=a),i};return e.mask?n(e,{from:e.from,...e.mask}):n(e)},this.commitLocation=async({viewTransition:e,ignoreBlocker:t,...n})=>{let r,i=()=>{let e=[`key`,`__TSR_key`,`__TSR_index`,`__hashScrollIntoViewOptions`];e.forEach(e=>{n.state[e]=this.latestLocation.state[e]});let t=Xe(n.state,this.latestLocation.state);return e.forEach(e=>{delete n.state[e]}),t},a=Ft(this.latestLocation.href)===Ft(n.href),o=this.commitLocationPromise;if(this.commitLocationPromise=Ze(()=>{o?.resolve(),o=void 0}),a&&i())this.load();else{let{maskedLocation:i,hashScrollIntoView:a,...o}=n;i&&(o={...i,state:{...i.state,__tempKey:void 0,__tempLocation:{...o,search:o.searchStr,state:{...o.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(o.unmaskOnReload??this.options.unmaskOnReload??!1)&&(o.state.__tempKey=this.tempLocationKey)),o.state.__hashScrollIntoViewOptions=a??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=e,r=n.replace?`REPLACE`:`PUSH`,this.history[r===`REPLACE`?`replace`:`push`](o.publicHref,o.state,{ignoreBlocker:t})}return this.resetNextScroll=n.resetScroll??!0,this.history.subscribers.size||this.load(r?{action:{type:r}}:void 0),this.commitLocationPromise},this.buildAndCommitLocation=({replace:e,resetScroll:t,hashScrollIntoView:n,viewTransition:r,ignoreBlocker:i,href:a,...o}={})=>{if(a){let t=this.history.location.state.__TSR_index,n=Rn(a,{__TSR_index:e?t:t+1}),r=new URL(n.pathname,this.origin);o.to=En(this.rewrite,r).pathname,o.search=this.options.parseSearch(n.search),o.hash=n.hash.slice(1)}let s=this.buildLocation({...o,_includeValidateSearch:!0});this.pendingBuiltLocation=s;let c=this.commitLocation({...s,viewTransition:r,replace:e,resetScroll:t,hashScrollIntoView:n,ignoreBlocker:i});return Promise.resolve().then(()=>{this.pendingBuiltLocation===s&&(this.pendingBuiltLocation=void 0)}),c},this.navigate=async({to:e,reloadDocument:t,href:n,publicHref:r,...i})=>{let a=!1;if(n)try{new URL(`${n}`),a=!0}catch{}if(a&&!t&&(t=!0),t){if(e!==void 0||!n){let t=this.buildLocation({to:e,...i});n??=t.publicHref,r??=t.publicHref}let t=!a&&r?r:n;if(nt(t,this.protocolAllowlist))return Promise.resolve();if(!i.ignoreBlocker){let e=this.history.getBlockers?.()??[];for(let t of e)if(t?.blockerFn&&await t.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:`PUSH`}))return Promise.resolve()}return i.replace?window.location.replace(t):window.location.href=t,Promise.resolve()}return this.buildAndCommitLocation({...i,href:n,to:e,_isNavigate:!0})},this.beforeLoad=()=>{this.cancelMatches(),this.updateLatestLocation();let e=this.matchRoutes(this.latestLocation),t=this.stores.cachedMatches.get().filter(t=>!e.some(e=>e.id===t.id));this.batch(()=>{this.stores.status.set(`pending`),this.stores.statusCode.set(200),this.stores.isLoading.set(!0),this.stores.location.set(this.latestLocation),this.stores.setPending(e),this.stores.setCached(t)})},this.load=async e=>{let t=e?.action?.type,n,r,i,a=this.stores.resolvedLocation.get()??this.stores.location.get();for(i=new Promise(o=>{this.startTransition(async()=>{try{this.beforeLoad(),t?Vn.set(this.latestLocation,t):Vn.delete(this.latestLocation);let n=this.latestLocation,r=Bn(n,this.stores.resolvedLocation.get());this.stores.redirect.get()||this.emit({type:`onBeforeNavigate`,...r}),this.emit({type:`onBeforeLoad`,...r}),await yn({router:this,sync:e?.sync,forceStaleReload:a.href===n.href,matches:this.stores.pendingMatches.get(),location:n,updateMatch:this.updateMatch,onReady:async()=>{this.startTransition(()=>{this.startViewTransition(async()=>{let e=null,t=null,n=null,r=null;this.batch(()=>{let i=this.stores.pendingMatches.get(),a=i.length,o=this.stores.matches.get();e=a?o.filter(e=>!this.stores.pendingMatchStores.has(e.id)):null;let s=new Set;for(let e of this.stores.pendingMatchStores.values())e.routeId&&s.add(e.routeId);let c=new Set;for(let e of this.stores.matchStores.values())e.routeId&&c.add(e.routeId);t=a?o.filter(e=>!s.has(e.routeId)):null,n=a?i.filter(e=>!c.has(e.routeId)):null,r=a?i.filter(e=>c.has(e.routeId)):o,this.stores.isLoading.set(!1),this.stores.loadedAt.set(Date.now()),a&&(this.stores.setMatches(i),this.stores.setPending([]),this.stores.setCached([...this.stores.cachedMatches.get(),...e.filter(e=>e.status!==`error`&&e.status!==`notFound`&&e.status!==`redirected`)]),this.clearExpiredCache())});for(let[e,i]of[[t,`onLeave`],[n,`onEnter`],[r,`onStay`]])if(e)for(let t of e)this.looseRoutesById[t.routeId].options[i]?.(t)})})}})}catch(e){en(e)?(n=e,this.navigate({...n.options,replace:!0,ignoreBlocker:!0})):Wt(e)&&(r=e);let t=n?n.status:r?404:this.stores.matches.get().some(e=>e.status===`error`)?500:200;this.batch(()=>{this.stores.statusCode.set(t),this.stores.redirect.set(n)})}this.latestLoadPromise===i&&(this.commitLocationPromise?.resolve(),this.latestLoadPromise=void 0,this.commitLocationPromise=void 0),o()})}),this.latestLoadPromise=i,await i;this.latestLoadPromise&&i!==this.latestLoadPromise;)await this.latestLoadPromise;let o;this.hasNotFoundMatch()?o=404:this.stores.matches.get().some(e=>e.status===`error`)&&(o=500),o!==void 0&&this.stores.statusCode.set(o)},this.startViewTransition=e=>{let t=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,t&&typeof document<`u`&&`startViewTransition`in document&&typeof document.startViewTransition==`function`){let n;if(typeof t==`object`&&this.isViewTransitionTypesSupported){let r=this.latestLocation,i=this.stores.resolvedLocation.get(),a=typeof t.types==`function`?t.types(Bn(r,i)):t.types;if(a===!1){e();return}n={update:e,types:a}}else n=e;document.startViewTransition(n)}else e()},this.updateMatch=(e,t)=>{this.startTransition(()=>{let n=this.stores.pendingMatchStores.get(e);if(n){n.set(t);return}let r=this.stores.matchStores.get(e);if(r){r.set(t);return}let i=this.stores.cachedMatchStores.get(e);if(i){let n=t(i.get());n.status===`redirected`?this.stores.cachedMatchStores.delete(e)&&this.stores.cachedIds.set(t=>t.filter(t=>t!==e)):i.set(n)}})},this.getMatch=e=>this.stores.cachedMatchStores.get(e)?.get()??this.stores.pendingMatchStores.get(e)?.get()??this.stores.matchStores.get(e)?.get(),this.invalidate=e=>{let t=t=>e?.filter?.(t)??!0?{...t,invalid:!0,...e?.forcePending||t.status===`error`||t.status===`notFound`?{status:`pending`,error:void 0}:void 0}:t;return this.batch(()=>{this.stores.setMatches(this.stores.matches.get().map(t)),this.stores.setCached(this.stores.cachedMatches.get().map(t)),this.stores.setPending(this.stores.pendingMatches.get().map(t))}),this.shouldViewTransition=!1,this.load({sync:e?.sync})},this.getParsedLocationHref=e=>e.publicHref||`/`,this.resolveRedirect=e=>{let t=e.headers.get(`Location`);if(!e.options.href||e.options._builtLocation){let t=e.options._builtLocation??this.buildLocation(e.options),n=this.getParsedLocationHref(t);e.options.href=n,e.headers.set(`Location`,n)}else if(t)try{let n=new URL(t);if(this.origin&&n.origin===this.origin){let t=n.pathname+n.search+n.hash;e.options.href=t,e.headers.set(`Location`,t)}}catch{}if(e.options.href&&!e.options._builtLocation&&nt(e.options.href,this.protocolAllowlist))throw Error(`Redirect blocked: unsafe protocol`);return e.headers.get(`Location`)||e.headers.set(`Location`,e.options.href),e},this.clearCache=e=>{let t=e?.filter;t===void 0?this.stores.setCached([]):this.stores.setCached(this.stores.cachedMatches.get().filter(e=>!t(e)))},this.clearExpiredCache=()=>{let e=Date.now();this.clearCache({filter:t=>{let n=this.looseRoutesById[t.routeId];if(!n.options.loader)return!0;let r=(t.preload?n.options.preloadGcTime??this.options.defaultPreloadGcTime:n.options.gcTime??this.options.defaultGcTime)??3e5;return t.status===`error`||e-t.updatedAt>=r}})},this.loadRouteChunk=xn,this.preloadRoute=async e=>{let t=e._builtLocation??this.buildLocation(e),n=this.matchRoutes(t,{throwOnError:!0,preload:!0,dest:e}),r=new Set([...this.stores.matchesId.get(),...this.stores.pendingIds.get()]),i=new Set([...r,...this.stores.cachedIds.get()]),a=n.filter(e=>!i.has(e.id));if(a.length){let e=this.stores.cachedMatches.get();this.stores.setCached([...e,...a])}try{return n=await yn({router:this,matches:n,location:t,preload:!0,updateMatch:(e,t)=>{r.has(e)?n=n.map(n=>n.id===e?t(n):n):this.updateMatch(e,t)}}),n}catch(e){if(en(e))return e.options.reloadDocument?void 0:await this.preloadRoute({...e.options,_fromLocation:t});Wt(e)||console.error(e);return}},this.matchRoute=(e,t)=>{let n={...e,to:e.to?this.resolvePathWithBase(e.from||``,e.to):void 0,params:e.params||{},leaveParams:!0},r=this.buildLocation(n);if(t?.pending&&this.stores.status.get()!==`pending`)return!1;let i=(t?.pending===void 0?!this.stores.isLoading.get():t.pending)?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),a=yt(r.pathname,t?.caseSensitive??!1,t?.fuzzy??!1,i.pathname,this.processedTree);return!a||e.params&&!Xe(a.rawParams,e.params,{partial:!0})?!1:t?.includeSearch??!0?Xe(i.search,r.search,{partial:!0})?a.rawParams:!1:a.rawParams},this.hasNotFoundMatch=()=>this.stores.matches.get().some(e=>e.status===`notFound`||e.globalNotFound),this.getStoreConfig=t,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??`fuzzy`,stringifySearch:e.stringifySearch??Yt,parseSearch:e.parseSearch??Jt,protocolAllowlist:e.protocolAllowlist??tt}),typeof document<`u`&&(self.__TSR_ROUTER__=this)}isShell(){return!!this.options.isShell}isPrerendering(){return!!this.options.isPrerendering}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:n}){this.routesById=e,this.routesByPath=t,this.processedTree=n;let r=this.options.notFoundRoute;r&&(r.init({originalIndex:99999999999}),this.routesById[r.id]=r)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=Tt(e),this.routeBranchCache.set(e,t)),t}get looseRoutesById(){return this.routesById}getParentContext(e){return e?.id?e.context??this.options.context??void 0:this.options.context??void 0}matchRoutesInternal(e,t){let n=this.getMatchedRoutes(e.pathname),{foundRoute:r,routeParams:i}=n,{matchedRoutes:a}=n,o=!1;(r?r.path!==`/`&&i[`**`]:Ft(e.pathname))&&(this.options.notFoundRoute?a=[...a,this.options.notFoundRoute]:o=!0);let s=o?Xn(this.options.notFoundMode,a):void 0,c=Array(a.length),l=new Map;for(let e of this.stores.matchStores.values())e.routeId&&l.set(e.routeId,e.get());for(let n=0;nthis.navigate({...t,_fromLocation:e}),buildLocation:this.buildLocation,cause:n.cause,abortController:n.abortController,preload:!!n.preload,matches:c,routeId:r.id};n.__routeContext=r.options.context(t)??void 0}n.context={...a,...n.__routeContext,...n.__beforeLoadContext}}}return c}matchRoutesLightweight(e){let{matchedRoutes:t,routeParams:n}=this.getMatchedRoutes(e.pathname),r=Le(t),i={...e.search};for(let e of t)try{Object.assign(i,Kn(e.options.validateSearch,i))}catch{}let a=Le(this.stores.matchesId.get()),o=a&&this.stores.matchStores.get(a)?.get(),s=o&&o.routeId===r.id&&o.pathname===e.pathname,c;if(s)c=o.params;else{let e=Object.assign(Object.create(null),n);for(let n of t)try{Zn(n,e)}catch{}c=e}return{matchedRoutes:t,fullPath:r.fullPath,search:i,params:c}}},Un=class extends Error{},Wn=class extends Error{};function Gn(e){return{loadedAt:0,isLoading:!1,isTransitioning:!1,status:`idle`,resolvedLocation:void 0,location:e,matches:[],statusCode:200}}function Kn(e,t){if(e==null)return{};if(`~standard`in e){let n=e[`~standard`].validate(t);if(n instanceof Promise)throw new Un(`Async validation not supported`);if(n.issues)throw new Un(JSON.stringify(n.issues,void 0,2),{cause:n});return n.value}return`parse`in e?e.parse(t):typeof e==`function`?e(t):{}}function qn({pathname:e,routesById:t,processedTree:n}){let r=Object.create(null),i=Ft(e),a,o=bt(i,n,!0);return o&&(a=o.route,Object.assign(r,o.rawParams)),{matchedRoutes:o?.branch||[t.__root__],routeParams:r,foundRoute:a}}function Jn({search:e,dest:t,destRoutes:n,_includeValidateSearch:r}){return Yn(n)(e,t,r??!1)}function Yn(e){let t={dest:null,_includeValidateSearch:!1,middlewares:[]};for(let n of e)`search`in n.options?n.options.search?.middlewares&&t.middlewares.push(...n.options.search.middlewares):(n.options.preSearchFilters||n.options.postSearchFilters)&&t.middlewares.push(({search:e,next:t})=>{let r=e;`preSearchFilters`in n.options&&n.options.preSearchFilters&&(r=n.options.preSearchFilters.reduce((e,t)=>t(e),e));let i=t(r);return`postSearchFilters`in n.options&&n.options.postSearchFilters?n.options.postSearchFilters.reduce((e,t)=>t(e),i):i}),n.options.validateSearch&&t.middlewares.push(({search:e,next:r})=>{let i=r(e);if(!t._includeValidateSearch)return i;try{return{...i,...Kn(n.options.validateSearch,i)??void 0}}catch{return i}});t.middlewares.push(({search:e})=>{let n=t.dest;return n.search?n.search===!0?e:ze(n.search,e):{}});let n=(e,t,r)=>{if(e>=r.length)return t;let i=r[e];return i({search:t,next:t=>n(e+1,t,r)})};return function(e,r,i){return t.dest=r,t._includeValidateSearch=i,n(0,e,t.middlewares)}}function Xn(e,t){if(e!==`root`)for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.children)return n.id}return Qt}function Zn(e,t){let n=e.options.params?.parse??e.options.parseParams;if(n){let e=n(t);if(e===!1)throw Error(`Route params.parse returned false for a matched route`);Object.assign(t,e)}}function Qn(){try{return sessionStorage}catch{return}}var $n=`tsr-scroll-restoration-v1_3`,er=Qn();function tr(){try{return JSON.parse(er?.getItem(`tsr-scroll-restoration-v1_3`)||`{}`)}catch{return{}}}function nr(){try{er?.setItem($n,JSON.stringify(rr))}catch{}}var rr=tr(),ir=`data-scroll-restoration-id`,ar=e=>e.state.__TSR_key||e.href;function or(e){let t=e.getAttribute(ir);if(t)return`[${ir}="${t}"]`;let n=``,r=e,i;for(;i=r.parentNode;){let e=1,t=r;for(;t=t.previousElementSibling;)e++;let a=`${r.localName}:nth-child(${e})`;n=n?`${a} > ${n}`:a,r=i}return n}var sr=!1,cr=`window`;function lr(e){try{return typeof e==`function`?e():document.querySelector(e)}catch{}}function ur(e){let t=[];for(let n of e){if(n===cr)continue;let e=lr(n);e&&t.push(e)}return t}function dr(e,t){if((t??e.options.scrollRestoration)&&(e.isScrollRestoring=!0),e.isScrollRestorationSetup)return;e.isScrollRestorationSetup=!0,sr=!1;let n=e.options.getScrollRestorationKey||ar,r=new Map,i=(e,t,n)=>{let i=r.get(e)||{};i.scrollX=t,i.scrollY=n,r.set(e,i)};history.scrollRestoration=`manual`;let a=t=>{if(!(sr||!e.isScrollRestoring)){if(t.target===document)i(cr,scrollX,scrollY);else{let e=t.target;i(e,e.scrollLeft,e.scrollTop)}}},o=t=>{if(!e.isScrollRestoring)return;let n=rr[t]||={};for(let[e,t]of r)e===cr?n[cr]=t:e.isConnected&&(n[or(e)]=t)};document.addEventListener(`scroll`,a,!0),e.subscribe(`onBeforeLoad`,e=>{e.fromLocation&&o(n(e.fromLocation)),r.clear()}),addEventListener(`pagehide`,()=>{o(n(e.stores.resolvedLocation.get()??e.stores.location.get())),nr()}),e.subscribe(`onRendered`,t=>{let i=e.options.scrollRestorationBehavior,a=e.options.scrollToTopSelectors,o=e.resetNextScroll,s;if(r.clear(),o||(e.resetNextScroll=!0),typeof e.options.scrollRestoration==`function`&&!e.options.scrollRestoration({location:e.latestLocation}))return;let c=n(t.toLocation),l=t.fromLocation&&n(t.fromLocation);if(e.isScrollRestoring&&l&&l!==c){let e=rr[l];if(e){let t=rr[c];for(let n in e){if(n===cr){if(o)continue}else{let e=lr(n);if(!e||o&&a&&(s??=ur(a),s.includes(e)))continue}t||=rr[c]={},t[n]??=e[n]}}}sr=!0;try{let n=t.toLocation.hash,r=t.toLocation.state.__hashScrollIntoViewOptions??!0,l=!1;if(o){let o=Vn.get(t.toLocation),u=n&&r&&(o===`PUSH`||o===`REPLACE`),d=e.isScrollRestoring?rr[c]:void 0;if(d)for(let e in d){let{scrollX:t,scrollY:n}=d[e];if(e===cr){if(u)continue;scrollTo({top:n,left:t,behavior:i}),l=!0}else{let r=lr(e);r&&(r.scrollLeft=t,r.scrollTop=n)}}if(!l&&!n){let e={top:0,left:0,behavior:i};if(scrollTo(e),a){s??=ur(a);for(let t of s)t.scrollTo(e)}}}!l&&n&&r&&document.getElementById(n)?.scrollIntoView(r)}finally{sr=!1}})}var fr=`Error preloading route! ☝️`,pr=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=e=>{this.originalIndex=e.originalIndex;let t=this.options,n=!t?.path&&!t?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=Qt:this.parentRoute||ot();let r=n?Qt:t?.path;r&&r!==`/`&&(r=Pt(r));let i=t?.id||r,a=n?Qt:Mt([this.parentRoute.id===`__root__`?``:this.parentRoute.id,i]);r===`__root__`&&(r=`/`),a!==`__root__`&&(a=Mt([`/`,a]));let o=a===`__root__`?`/`:Mt([this.parentRoute.fullPath,r]);this._path=r,this._id=a,this._fullPath=o,this._to=Ft(o)},this.addChildren=e=>this._addFileChildren(e),this._addFileChildren=e=>(Array.isArray(e)&&(this.children=e),typeof e==`object`&&e&&(this.children=Object.values(e)),this),this._addFileTypes=()=>this,this.updateLoader=e=>(Object.assign(this.options,e),this),this.update=e=>(Object.assign(this.options,e),this),this.lazy=e=>(this.lazyFn=e,this),this.redirect=e=>$t({from:this.fullPath,...e}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw Error(`Route cannot have both an 'id' and a 'path' option.`)}},mr=class extends pr{constructor(e){super(e)}};function hr(e){let t=e.errorComponent??_r;return(0,V.jsx)(gr,{getResetKey:e.getResetKey,onCatch:e.onCatch,children:({error:n,reset:r})=>n?B.createElement(t,{error:n,reset:r}):e.children})}var gr=class extends B.Component{constructor(...e){super(...e),this.state={error:null}}static getDerivedStateFromProps(e,t){let n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:null}:{resetKey:n}}static getDerivedStateFromError(e){return{error:e}}reset(){this.setState({error:null})}componentDidCatch(e,t){this.props.onCatch&&this.props.onCatch(e,t)}render(){return this.props.children({error:this.state.error,reset:()=>{this.reset()}})}};function _r({error:e}){let[t,n]=B.useState(!1);return(0,V.jsxs)(`div`,{style:{padding:`.5rem`,maxWidth:`100%`},children:[(0,V.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`.5rem`},children:[(0,V.jsx)(`strong`,{style:{fontSize:`1rem`},children:`Something went wrong!`}),(0,V.jsx)(`button`,{style:{appearance:`none`,fontSize:`.6em`,border:`1px solid currentColor`,padding:`.1rem .2rem`,fontWeight:`bold`,borderRadius:`.25rem`},onClick:()=>n(e=>!e),children:t?`Hide Error`:`Show Error`})]}),(0,V.jsx)(`div`,{style:{height:`.25rem`}}),t?(0,V.jsx)(`div`,{children:(0,V.jsx)(`pre`,{style:{fontSize:`.7em`,border:`1px solid red`,borderRadius:`.25rem`,padding:`.3rem`,color:`red`,overflow:`auto`},children:e.message?(0,V.jsx)(`code`,{children:e.message}):null})}):null]})}function vr({children:e,fallback:t=null}){return yr()?(0,V.jsx)(B.Fragment,{children:e}):(0,V.jsx)(B.Fragment,{children:t})}function yr(){return B.useSyncExternalStore(br,()=>!0,()=>!1)}function br(){return()=>{}}var xr=B.createContext(null);function Sr(e){return B.useContext(xr)}var Cr=B.createContext(void 0),wr=B.createContext(void 0),Tr=(e=>(e[e.None=0]=`None`,e[e.Mutable=1]=`Mutable`,e[e.Watching=2]=`Watching`,e[e.RecursedCheck=4]=`RecursedCheck`,e[e.Recursed=8]=`Recursed`,e[e.Dirty=16]=`Dirty`,e[e.Pending=32]=`Pending`,e))(Tr||{});function Er({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function Dr(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var Or=[],kr=0,{link:Ar,unlink:jr,propagate:Mr,checkDirty:Nr,shallowPropagate:Pr}=Er({update(e){return e._update()},notify(e){Or[Ir++]=e,e.flags&=~Tr.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=Tr.Mutable|Tr.Dirty,Br(e))}}),Fr=0,Ir=0,Lr,Rr=0;function zr(e){try{++Rr,e()}finally{--Rr||Vr()}}function Br(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=jr(n,e)}function Vr(){if(!(Rr>0)){for(;Fr{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=Lr,o=t?.compare??Object.is;if(n)Lr=i,++kr,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=Tr.Mutable|Tr.RecursedCheck);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{Lr=a,n&&(i.flags&=~Tr.RecursedCheck),Br(i)}}};return n?(i.flags=Tr.Mutable|Tr.Dirty,i.get=function(){let e=i.flags;if(e&Tr.Dirty||e&Tr.Pending&&Nr(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&Pr(e)}}else e&Tr.Pending&&(i.flags=e&~Tr.Pending);return Lr!==void 0&&Ar(i,Lr,kr),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(Mr(e),Pr(e),Vr())}},i}function Ur(e){let t=()=>{let t=Lr;Lr=n,++kr,n.depsTail=void 0,n.flags=Tr.Watching|Tr.RecursedCheck;try{return e()}finally{Lr=t,n.flags&=~Tr.RecursedCheck,Br(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:Tr.Watching|Tr.RecursedCheck,notify(){let e=this.flags;e&Tr.Dirty||e&Tr.Pending&&Nr(this.deps,this)?t():this.flags=Tr.Watching},stop(){this.flags=Tr.None,this.depsTail=void 0,Br(this)}};return t(),n}var Wr=o((e=>{var t=f();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 d=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?d:t.useSyncExternalStore})),Gr=o(((e,t)=>{t.exports=Wr()})),Kr=o((e=>{var t=f(),n=Gr();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}})),qr=o(((e,t)=>{t.exports=Kr()}))();function Jr(e,t){return e===t}function Yr(e,t,n=Jr){let r=(0,B.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,B.useCallback)(()=>e?.get(),[e]);return(0,qr.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var Xr={get:()=>void 0,subscribe:()=>({unsubscribe:()=>{}})};function Zr(e){let t=Sr(),n=B.useContext(e.from?wr:Cr),r=e.from??n,i=r?e.from?t.stores.getRouteMatchStore(r):t.stores.matchStores.get(r):void 0,a=B.useRef(void 0);return Yr(i??Xr,n=>{if((e.shouldThrow??!0)&&!n&&ot(),n===void 0)return;let r=e.select?e.select(n):n;if(e.structuralSharing??t.options.defaultStructuralSharing){let e=Ge(a.current,r);return a.current=e,e}return r})}function Qr(e){return Zr({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function $r(e){let{select:t,...n}=e;return Zr({...n,select:e=>t?t(e.loaderDeps):e.loaderDeps})}function ei(e){return Zr({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function ti(e){return Zr({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function ni(e){let t=Sr();return B.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function ri(e){let t=Sr(),n=ni(),r=B.useRef(null);return Pe(()=>{r.current!==e&&(n(e),r.current=e)},[t,e,n]),null}function ii(e){return Zr({...e,select:t=>e.select?e.select(t.context):t.context})}var ai=m();function oi(e,t){let n=Sr(),r=Ie(t),{activeProps:i,inactiveProps:a,activeOptions:o,to:s,preload:c,preloadDelay:l,preloadIntentProximity:u,hashScrollIntoView:d,replace:f,startTransition:p,resetScroll:m,viewTransition:h,children:g,target:_,disabled:v,style:y,className:b,onClick:x,onBlur:S,onFocus:C,onMouseEnter:w,onMouseLeave:T,onTouchStart:E,ignoreBlocker:D,params:O,search:ee,hash:te,state:ne,mask:k,reloadDocument:A,unsafeRelative:j,from:M,_fromLocation:N,...P}=e,F=yr(),re=B.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),ie=Yr(n.stores.location,e=>e,(e,t)=>e.href===t.href),I=B.useMemo(()=>{let e={_fromLocation:ie,...re};return n.buildLocation(e)},[n,ie,re]),ae=I.maskedLocation?I.maskedLocation.publicHref:I.publicHref,L=I.maskedLocation?I.maskedLocation.external:I.external,oe=B.useMemo(()=>hi(ae,L,n.history,v),[v,L,ae,n.history]),se=B.useMemo(()=>{if(oe?.external)return nt(oe.href,n.protocolAllowlist)?void 0:oe.href;if(!gi(s)&&typeof s==`string`&&s.indexOf(`:`)!==-1)try{return new URL(s),nt(s,n.protocolAllowlist)?void 0:s}catch{}},[s,oe,n.protocolAllowlist]),ce=B.useMemo(()=>{if(se)return!1;if(o?.exact){if(!Rt(ie.pathname,I.pathname,n.basepath))return!1}else{let e=Lt(ie.pathname,n.basepath),t=Lt(I.pathname,n.basepath);if(!(e.startsWith(t)&&(e.length===t.length||e[t.length]===`/`)))return!1}return(o?.includeSearch??!0)&&!Xe(ie.search,I.search,{partial:!o?.exact,ignoreUndefined:!o?.explicitUndefined})?!1:!o?.includeHash||F&&ie.hash===I.hash},[o?.exact,o?.explicitUndefined,o?.includeHash,o?.includeSearch,ie,se,F,I.hash,I.pathname,I.search,n.basepath]),le=ce?ze(i,{})??ci:si,ue=ce?si:ze(a,{})??si,de=[b,le.className,ue.className].filter(Boolean).join(` `),R=(y||le.style||ue.style)&&{...y,...le.style,...ue.style},[fe,pe]=B.useState(!1),me=B.useRef(!1),he=e.reloadDocument||se?!1:c??n.options.defaultPreload,ge=l??n.options.defaultPreloadDelay??0,_e=B.useCallback(()=>{n.preloadRoute({...re,_builtLocation:I}).catch(e=>{console.warn(e),console.warn(fr)})},[n,re,I]);Fe(r,B.useCallback(e=>{e?.isIntersecting&&_e()},[_e]),pi,{disabled:!!v||he!==`viewport`}),B.useEffect(()=>{me.current||!v&&he===`render`&&(_e(),me.current=!0)},[v,_e,he]);let ve=e=>{let t=e.currentTarget.getAttribute(`target`),r=_===void 0?t:_;if(!v&&!vi(e)&&!e.defaultPrevented&&(!r||r===`_self`)&&e.button===0){e.preventDefault(),(0,ai.flushSync)(()=>{pe(!0)});let t=n.subscribe(`onResolved`,()=>{t(),pe(!1)});n.navigate({...re,replace:f,resetScroll:m,hashScrollIntoView:d,startTransition:p,viewTransition:h,ignoreBlocker:D})}};if(se)return{...P,ref:r,href:se,...g&&{children:g},..._&&{target:_},...v&&{disabled:v},...y&&{style:y},...b&&{className:b},...x&&{onClick:x},...S&&{onBlur:S},...C&&{onFocus:C},...w&&{onMouseEnter:w},...T&&{onMouseLeave:T},...E&&{onTouchStart:E}};let ye=e=>{if(v||he!==`intent`)return;if(!ge){_e();return}let t=e.currentTarget;if(fi.has(t))return;let n=setTimeout(()=>{fi.delete(t),_e()},ge);fi.set(t,n)},be=e=>{v||he!==`intent`||_e()},xe=e=>{if(v||!he||!ge)return;let t=e.currentTarget,n=fi.get(t);n&&(clearTimeout(n),fi.delete(t))};return{...P,...le,...ue,href:oe?.href,ref:r,onClick:mi([x,ve]),onBlur:mi([S,xe]),onFocus:mi([C,ye]),onMouseEnter:mi([w,ye]),onMouseLeave:mi([T,xe]),onTouchStart:mi([E,be]),disabled:!!v,target:_,...R&&{style:R},...de&&{className:de},...v&&li,...ce&&ui,...F&&fe&&di}}var si={},ci={className:`active`},li={role:`link`,"aria-disabled":!0},ui={"data-status":`active`,"aria-current":`page`},di={"data-transitioning":`transitioning`},fi=new WeakMap,pi={rootMargin:`100px`},mi=e=>t=>{for(let n of e)if(n){if(t.defaultPrevented)return;n(t)}};function hi(e,t,n,r){if(!r)return t?{href:e,external:!0}:{href:n.createHref(e)||`/`,external:!1}}function gi(e){if(typeof e!=`string`)return!1;let t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var _i=B.forwardRef((e,t)=>{let{_asChild:n,...r}=e,{type:i,...a}=oi(r,t),o=typeof r.children==`function`?r.children({isActive:a[`data-status`]===`active`}):r.children;if(!n){let{disabled:e,...t}=a;return B.createElement(`a`,t,o)}return B.createElement(n,a,o)});function vi(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var yi=class extends pr{constructor(e){super(e),this.useMatch=e=>Zr({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>ii({...e,from:this.id}),this.useSearch=e=>ti({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>ei({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>$r({...e,from:this.id}),this.useLoaderData=e=>Qr({...e,from:this.id}),this.useNavigate=()=>ni({from:this.fullPath}),this.Link=B.forwardRef((e,t)=>(0,V.jsx)(_i,{ref:t,from:this.fullPath,...e}))}};function bi(e){return new yi(e)}var xi=class extends mr{constructor(e){super(e),this.useMatch=e=>Zr({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>ii({...e,from:this.id}),this.useSearch=e=>ti({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>ei({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>$r({...e,from:this.id}),this.useLoaderData=e=>Qr({...e,from:this.id}),this.useNavigate=()=>ni({from:this.fullPath}),this.Link=B.forwardRef((e,t)=>(0,V.jsx)(_i,{ref:t,from:this.fullPath,...e}))}};function Si(e){return new xi(e)}function Ci(e){let t=Sr(),n=`not-found-${Yr(t.stores.location,e=>e.pathname)}-${Yr(t.stores.status,e=>e)}`;return(0,V.jsx)(hr,{getResetKey:()=>n,onCatch:(t,n)=>{if(Wt(t))e.onCatch?.(t,n);else throw t},errorComponent:({error:t})=>{if(Wt(t))return e.fallback?.(t);throw t},children:e.children})}function wi(){return(0,V.jsx)(`p`,{children:`Not Found`})}function Ti(e){return(0,V.jsx)(V.Fragment,{children:e.children})}function Ei(e,t,n){return t.options.notFoundComponent?(0,V.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,V.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,V.jsx)(wi,{})}var Di=B.memo(function({matchId:e}){let t=Sr(),n=t.stores.matchStores.get(e);n||ot();let r=Yr(t.stores.loadedAt,e=>e),i=Yr(n,e=>e);return(0,V.jsx)(Oi,{router:t,matchId:e,resetKey:r,matchState:B.useMemo(()=>{let e=i.routeId,n=t.routesById[e].parentRoute?.id;return{routeId:e,ssr:i.ssr,_displayPending:i._displayPending,parentRouteId:n}},[i._displayPending,i.routeId,i.ssr,t.routesById])})});function Oi({router:e,matchId:t,resetKey:n,matchState:r}){let i=e.routesById[r.routeId],a=i.options.pendingComponent??e.options.defaultPendingComponent,o=a?(0,V.jsx)(a,{}):null,s=i.options.errorComponent??e.options.defaultErrorComponent,c=i.options.onCatch??e.options.defaultOnCatch,l=i.isRoot?i.options.notFoundComponent??e.options.notFoundRoute?.options.component:i.options.notFoundComponent,u=r.ssr===!1||r.ssr===`data-only`,d=(!i.isRoot||i.options.wrapInSuspense||u)&&(i.options.wrapInSuspense??a??(i.options.errorComponent?.preload||u))?B.Suspense:Ti,f=s?hr:Ti,p=l?Ci:Ti;return(0,V.jsxs)(i.isRoot?i.options.shellComponent??Ti:Ti,{children:[(0,V.jsx)(Cr.Provider,{value:t,children:(0,V.jsx)(d,{fallback:o,children:(0,V.jsx)(f,{getResetKey:()=>n,errorComponent:s||_r,onCatch:(e,t)=>{if(Wt(e))throw e.routeId??=r.routeId,e;c?.(e,t)},children:(0,V.jsx)(p,{fallback:e=>{if(e.routeId??=r.routeId,!l||e.routeId&&e.routeId!==r.routeId||!e.routeId&&!i.isRoot)throw e;return B.createElement(l,e)},children:u||r._displayPending?(0,V.jsx)(vr,{fallback:o,children:(0,V.jsx)(Ai,{matchId:t})}):(0,V.jsx)(Ai,{matchId:t})})})})}),r.parentRouteId===`__root__`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(ki,{resetKey:n}),(e.options.scrollRestoration,null)]}):null]})}function ki({resetKey:e}){let t=Sr(),n=B.useRef(void 0);return Pe(()=>{let e=t.latestLocation.href;(n.current===void 0||n.current!==e)&&(t.emit({type:`onRendered`,...Bn(t.stores.location.get(),t.stores.resolvedLocation.get())}),n.current=e)},[t.latestLocation.state.__TSR_key,e,t]),null}var Ai=B.memo(function({matchId:e}){let t=Sr(),n=(e,n)=>t.getMatch(e.id)?._nonReactive[n]??e._nonReactive[n],r=t.stores.matchStores.get(e);r||ot();let i=Yr(r,e=>e),a=i.routeId,o=t.routesById[a],s=B.useMemo(()=>{let e=(t.routesById[a].options.remountDeps??t.options.defaultRemountDeps)?.({routeId:a,loaderDeps:i.loaderDeps,params:i._strictParams,search:i._strictSearch});return e?JSON.stringify(e):void 0},[a,i.loaderDeps,i._strictParams,i._strictSearch,t.options.defaultRemountDeps,t.routesById]),c=B.useMemo(()=>{let e=o.options.component??t.options.defaultComponent;return e?(0,V.jsx)(e,{},s):(0,V.jsx)(ji,{})},[s,o.options.component,t.options.defaultComponent]);if(i._displayPending)throw n(i,`displayPendingPromise`);if(i._forcePending)throw n(i,`minPendingPromise`);if(i.status===`pending`){let e=o.options.pendingMinMs??t.options.defaultPendingMinMs;if(e){let n=t.getMatch(i.id);if(n&&!n._nonReactive.minPendingPromise){let t=Ze();n._nonReactive.minPendingPromise=t,setTimeout(()=>{t.resolve(),n._nonReactive.minPendingPromise=void 0},e)}}throw n(i,`loadPromise`)}if(i.status===`notFound`)return Wt(i.error)||ot(),Ei(t,o,i.error);if(i.status===`redirected`)throw en(i.error)||ot(),n(i,`loadPromise`);if(i.status===`error`)throw i.error;return c}),ji=B.memo(function(){let e=Sr(),t=B.useContext(Cr),n,r=!1,i;{let a=t?e.stores.matchStores.get(t):void 0;[n,r]=Yr(a,e=>[e?.routeId,e?.globalNotFound??!1]),i=Yr(e.stores.matchesId,e=>e[e.findIndex(e=>e===t)+1])}let a=n?e.routesById[n]:void 0,o=e.options.defaultPendingComponent?(0,V.jsx)(e.options.defaultPendingComponent,{}):null;if(r)return a||ot(),Ei(e,a,void 0);if(!i)return null;let s=(0,V.jsx)(Di,{matchId:i});return n===`__root__`?(0,V.jsx)(B.Suspense,{fallback:o,children:s}):s});function Mi(){let e=Sr(),t=B.useRef({router:e,mounted:!1}),[n,r]=B.useState(!1),i=Yr(e.stores.isLoading,e=>e),a=Yr(e.stores.hasPending,e=>e),o=H(i),s=i||n||a,c=H(s),l=i||a,u=H(l);return e.startTransition=e=>{r(!0),B.startTransition(()=>{e(),r(!1)})},B.useEffect(()=>{let t=e.history.subscribe(e.load),n=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return Ft(e.latestLocation.publicHref)!==Ft(n.publicHref)&&e.commitLocation({...n,replace:!0}),()=>{t()}},[e,e.history]),Pe(()=>{typeof window<`u`&&e.ssr||t.current.router===e&&t.current.mounted||(t.current={router:e,mounted:!0},(async()=>{try{await e.load()}catch(e){console.error(e)}})())},[e]),Pe(()=>{o&&!i&&e.emit({type:`onLoad`,...Bn(e.stores.location.get(),e.stores.resolvedLocation.get())})},[o,e,i]),Pe(()=>{u&&!l&&e.emit({type:`onBeforeRouteMount`,...Bn(e.stores.location.get(),e.stores.resolvedLocation.get())})},[l,u,e]),Pe(()=>{if(c&&!s){let t=Bn(e.stores.location.get(),e.stores.resolvedLocation.get());e.emit({type:`onResolved`,...t}),zr(()=>{e.stores.status.set(`idle`),e.stores.resolvedLocation.set(e.stores.location.get())})}},[s,c,e]),null}function Ni(){let e=Sr(),t=e.routesById.__root__.options.pendingComponent??e.options.defaultPendingComponent,n=t?(0,V.jsx)(t,{}):null,r=(0,V.jsxs)(typeof document<`u`&&e.ssr?Ti:B.Suspense,{fallback:n,children:[(0,V.jsx)(Mi,{}),(0,V.jsx)(Pi,{})]});return e.options.InnerWrap?(0,V.jsx)(e.options.InnerWrap,{children:r}):r}function Pi(){let e=Sr(),t=Yr(e.stores.firstId,e=>e),n=Yr(e.stores.loadedAt,e=>e),r=t?(0,V.jsx)(Di,{matchId:t}):null;return(0,V.jsx)(Cr.Provider,{value:t,children:e.options.disableGlobalCatchBoundary?r:(0,V.jsx)(hr,{getResetKey:()=>n,errorComponent:_r,onCatch:void 0,children:r})})}var Fi=e=>({createMutableStore:Hr,createReadonlyStore:Hr,batch:zr}),Ii=e=>new Li(e),Li=class extends Hn{constructor(e){super(e,Fi)}};function Ri({router:e,children:t,...n}){He(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});let r=(0,V.jsx)(xr.Provider,{value:e,children:t});return e.options.Wrap?(0,V.jsx)(e.options.Wrap,{children:r}):r}function zi({router:e,...t}){return(0,V.jsx)(Ri,{router:e,...t,children:(0,V.jsx)(Ni,{})})}var Bi=g(),Vi=(0,B.createContext)(null),Hi=`loopx-pw-locale`,Ui={en:{"acceptance.connected":`Connected`,"acceptance.mapped":`Project mapped`,"acceptance.refreshed":`State refreshed`,"acceptance.inspected":`Adapter inspected`,"acceptance.recorded":`Run recorded`,"acceptance.judged":`Feedback recorded`,"acceptance.approved":`Approval recorded`,"acceptance.ready":`Controller readiness recorded`,"acceptance.attentionSource":`Current status`,"acceptance.visionSource":`Agent acceptance criteria`,"acceptance.todoSource":`Task state`,"acceptance.runSource":`Fresh run evidence`,"acceptance.title":`Acceptance observations`,"acceptance.unavailable":`Acceptance observations are unavailable. Goal completion is unknown.`,"acceptance.partial":`Partial observations only. Completed tasks and an empty gap list do not prove Goal acceptance.`,"acceptance.gaps":`Evidence still required`,"acceptance.reasonUnknown":`Reason not provided by the source`,"acceptance.unknown":`Unknown`,"acceptance.required":`Required evidence or condition`,"acceptance.observed":`Observed at`,"acceptance.noGaps":`No gaps in the available observations. Full acceptance has not been assessed.`,"acceptance.guards":`Pending gates`,"acceptance.noGuards":`No pending gates in the available observations.`,"acceptance.scope":`Decision scope`,"acceptance.next":`Next action from current status`,"acceptance.historical_progress":`Recorded progress`,"acceptance.historical":`Historical lifecycle observations do not grant permission or certify acceptance.`,"acceptance.missing":`Sources not available:`,"acceptance.truncated":`Only the first 12 observations are shown.`,"common.actions":`Actions`,"common.agent":`Agent`,"common.allMessages":`All messages`,"common.cancel":`Cancel`,"common.close":`Close`,"common.closeActionReceipt":`Close action receipt`,"common.confirm":`Confirm`,"common.export":`Export`,"common.failed":`Failed`,"common.goal":`Goal`,"common.loading":`Loading…`,"common.none":`None`,"common.off":`Off`,"common.on":`On`,"common.open":`Open`,"common.owner":`Owner`,"common.readOnly":`Read only`,"common.recently":`Just now`,"common.status":`Status`,"common.task":`Task`,"common.you":`You`,"common.waiting":`Waiting`,"composer.addImage":`Add image`,"composer.agentProgress":`Ask Agent for a progress report`,"composer.agentProgressPrompt":`Give me a progress report for this Goal: completed, running, blocked, and next steps.`,"composer.attachImageHint":`Choose, paste, or drag an image`,"composer.clarifyDefer":`Deferring a Todo requires a deterministic resume condition. Add todo_done:, pr_merged:[owner/repo]#, capacity_available:, or resume_at:.`,"composer.clarifySingleAction":`This message contains multiple operations that may change state. Describe one operation at a time so each confirmation preview can be reviewed separately.`,"composer.createGoal":`Create Goal`,"composer.createGoalDraft":`Goal draft`,"composer.createGoalDraftDescription":`Complete the draft and send it. LoopX will show a confirmation preview first.`,"composer.createGoalDraftLead":`Create a long-term Goal:`,"composer.createGoalTemplate":`Create a long-term Goal: -Objective: -Completion criteria: -Execution boundary (optional): -Related repository (optional): -Notification method (optional):`,"composer.createGoalHint":`Insert a Goal template to review before creation`,"composer.draft":`Draft`,"composer.globalProgress":`Summarize all Goal progress`,"composer.globalProgressPrompt":`Summarize the latest progress and blockers for all active Goals.`,"composer.globalTasks":`Ask about global priorities`,"composer.globalTasksPrompt":`Which Goals need me, and what should I handle first?`,"composer.goalMessageHint":`Your message is delivered to {agent} in this Goal session.`,"composer.goalRunningHint":`{agent} is running {count} tasks · your message enters this session as guidance without interrupting it`,"composer.goalPlaceholder":`Ask or guide {goal}…`,"composer.imageAnalysisPrompt":`Analyze these images in the context of the current Goal and tell me the next step.`,"composer.imageCountError":`You can add up to {count} images.`,"composer.imagePicker":`Image file picker`,"composer.imageReadError":`Could not read image {name}.`,"composer.imageReadGenericError":`Could not read the image.`,"composer.imageSizeError":`Each image must be {size} MB or smaller.`,"composer.imageTypeError":`PNG, JPEG, WebP, and GIF images are supported.`,"composer.imagesPending":`Images to send`,"composer.immediate":`Send now`,"composer.managerMessageHint":`Your message goes to the LoopX Manager across Goals for global questions or Goal creation.`,"composer.managerPlaceholder":`Ask the LoopX Manager, or describe a new Goal…`,"composer.monitor":`Configure scheduled check`,"composer.monitorGoalQuestion":`Which Goal should receive the scheduled check?`,"composer.monitorTemplate":`Add a scheduled check for the current Goal: -Check target: -Frequency (supports 30 minutes / 2 hours / daily): Every 2 hours -Stop condition: Goal completes`,"composer.monitorTemplateWithoutGoal":`Configure a scheduled check: -Goal: -Check target: -Frequency: Every 2 hours -Stop condition: Goal completes`,"composer.monitorHint":`Fill in what to check, frequency, and stop condition before creation`,"composer.heartbeatGoalQuestion":`Which Goal should receive the Heartbeat?`,"composer.heartbeatTemplate":`Set a Heartbeat for the current Goal: -Frequency: Daily -Stop condition: Goal completes -Notification: Only notify me when needed`,"composer.heartbeatTemplateWithoutGoal":`Set up a Heartbeat: -Goal: -Frequency: Daily -Stop condition: Goal completes -Notification: Only notify me when needed`,"composer.nextAction":`Ask what’s next`,"composer.nextActionPrompt":`What should I do next?`,"composer.prepareDraft":`Insert a draft and review before sending`,"composer.send":`Send`,"composer.sendMessage":`Send a message to LoopX`,"composer.sendMessageHint":`Send message`,"composer.sentImageAlt":`Remove image {name}`,"conversation.agentPending":`Working…`,"conversation.close":`Close conversation receipt`,"conversation.convertHint":`Turn the Agent’s latest reply into a Task draft`,"conversation.full":`View full conversation`,"conversation.receipt":`Conversation receipt`,"conversation.replying":`Replying`,"conversation.title":`Manager conversation`,"conversation.toTask":`Convert to Task`,"digest.away":`Runs since your previous visit`,"digest.completed":`new completions`,"digest.failed":`new failed/interrupted runs`,"digest.needsYou":`currently need confirmation`,"feedback.applying":`Running: {title}`,"feedback.cancelFailed":`Cancel failed: {error}`,"feedback.completed":`Completed: {title}`,"feedback.executionFailed":`Execution failed: {error}`,"feedback.gateRequired":`Your confirmation is required: {summary}`,"feedback.notCompleted":`Not completed: {status}`,"feedback.goalRefreshFailed":`The Goal opened, but its latest state could not be refreshed. Use Refresh to try again.`,"feedback.preparingPreview":`Preparing confirmation preview: {title}`,"feedback.previewFailed":`Could not prepare the confirmation preview: {error}`,"feedback.sendFailed":`Send failed: {error}`,"feedback.sendGenericError":`Could not send the message. Try again later.`,"feedback.stale":`State changed, so nothing was applied. Generate a new confirmation preview.`,"feedback.taskDraftCreated":`Created a Task draft from the reply. Edit and send it to review the confirmation preview.`,"goal.defaultTitle":`New personal Goal`,"goal.initialTodo":`Work toward the completion criteria: {criteria}`,"goal.objectiveBoundary":`Execution boundary: {boundary}`,"goal.objectiveCompletion":`Completion criteria: {criteria}`,"drawer.advancedDiagnostics":`Advanced diagnostics`,"drawer.agentWorking":`Agent is continuing; the record updates automatically.`,"drawer.analysis":`Analyzing`,"drawer.apply":`Confirm and apply`,"drawer.applying":`Applying…`,"drawer.attentionBlocking":`Blocking an Agent`,"drawer.attentionWaiting":`Waiting for your decision`,"drawer.autoNotify":`Human-gate auto notifications`,"drawer.branch":`Branch`,"drawer.closeDetail":`Close details and return to {context}`,"drawer.connected":`Connected`,"drawer.correctionDescription":`The message keeps the current Goal, Todo, and Agent Session context.`,"drawer.correctionLabel":`Guide {agent}`,"drawer.correctionPlaceholder":`For example: focus on permission risks first and do not commit yet…`,"drawer.correctionSend":`Send guidance`,"drawer.correctionTextarea":`Enter guidance for Goal {goal}, Agent {agent}, Run {run}`,"drawer.copyRepository":`Copy repository identity`,"drawer.copyRepositoryDone":`Repository identity copied`,"drawer.copyRepositoryError":`Copy failed. Check browser clipboard permission.`,"drawer.copyRepositorySuccess":`Copied. You can paste it into another tool.`,"drawer.cost":`Cost 24h / 7d`,"drawer.costShort":`Cost`,"drawer.durationShort":`Duration`,"drawer.period24h":`24h`,"drawer.period7d":`7d`,"drawer.tokens":`Tokens 24h / 7d`,"drawer.tokensShort":`tokens`,"drawer.usageNotMeasured":`Not measured`,"drawer.currentGoal":`Current Goal`,"attentionDetail.title":`Request details`,"attentionDetail.request":`What is requested`,"attentionDetail.decision":`Decision requested`,"attentionDetail.unknownRequest":`Not specified; review the source before deciding`,"attentionDetail.open":`Open in current projection`,"attentionDetail.closed":`Closed`,"attentionDetail.deferred":`Deferred`,"attentionDetail.superseded":`Replaced`,"attentionDetail.unknown":`Status not provided`,"attentionDetail.unavailable":`The source has not confirmed this item; refresh before acting`,"attentionDetail.unknownReason":`The source has not provided a reason.`,"attentionDetail.targetTodo":`Linked Todo to unblock`,"attentionDetail.targetAgent":`Agent named by the request`,"attentionDetail.scope":`Declared decision scope`,"attentionDetail.notProvided":`Not provided`,"attentionDetail.replacement":`Replacement Todo`,"attentionDetail.openReplacement":`Open replacement`,"attentionDetail.boundary":`Reading this detail does not resolve a gate or grant authority. Available decisions require a fresh preview.`,"drawer.decisionDefaultEvidence":`No additional public-safe evidence is attached. The next step will still show a Preview first.`,"drawer.decisionDefaultReason":`This decision affects the next step of the current Todo.`,"drawer.decisionDefer":`Decide later`,"drawer.decisionMore":`More decisions`,"drawer.decisionReject":`Reject`,"drawer.decisionReview":`Review impact and decide`,"drawer.dependencies":`Dependencies`,"drawer.detailsAndActions":`Details & actions`,"drawer.duration":`Duration 24h / 7d`,"drawer.evidence":`Evidence`,"drawer.executionHistory":`Execution history`,"drawer.executionRecord":`Run record`,"drawer.executionRecordAndResult":`Execution & result`,"drawer.explainDecision":`Explain this decision`,"drawer.gateApproveHint":`Run one command in the terminal to complete approval:`,"drawer.gateRejectHint":`Replace approve with reject at the end to decline. This notice disappears after the command runs.`,"drawer.gateRequiresHost":`Host confirmation required`,"drawer.gateRequiresHostDescription":`This page cannot approve this protected permission change. Nothing was written by your click.`,"drawer.goalAutoRun":`Automatic runs for this Goal`,"drawer.goalChanges":`Pending changes for this Goal`,"drawer.goalDetails":`Goal details`,"drawer.group":`Group`,"drawer.inspectorFull":`Switch to full screen`,"drawer.inspectorFullView":`Full-screen view`,"drawer.inspectorHalf":`Switch to half screen`,"drawer.inspectorHalfView":`Half-screen view`,"drawer.lastNotification":`Latest notification`,"drawer.larkConfigure":`Configure Lark connection`,"drawer.larkConnect":`Connect Lark App`,"drawer.larkConnection":`Lark connection`,"drawer.larkNotConfigured":`Not configured`,"drawer.larkNotConfiguredDescription":`After setup, LoopX sends a Feishu notification when this Goal needs your confirmation.`,"drawer.managerChanges":`Pending Manager changes`,"drawer.moreActions":`More actions`,"drawer.moreRunActions":`More run actions`,"drawer.nextTransition":`Next transition`,"drawer.noExecutionHistory":`No execution history yet.`,"drawer.noRun":`Execution Session has not started`,"drawer.noRunDescription":`Run records will appear here after an Agent starts execution.`,"drawer.notAssigned":`Unassigned`,"drawer.notLinked":`Not linked`,"drawer.notSet":`Not set`,"drawer.outputDetails":`Output details`,"drawer.outputRecorded":`This output is recorded on the current Goal.`,"drawer.outputSafePreview":`Public-safe output preview`,"drawer.outputRun":`Run`,"drawer.outputTodo":`Todo`,"drawer.outputs":`Outputs from this run`,"drawer.previewUnavailable":`No public-safe inline preview is available for this output.`,"drawer.priority":`Priority`,"drawer.progress":`Progress`,"drawer.proposalApplied":`Applied. LoopX state will refresh.`,"drawer.proposalApplyFailed":`Apply failed. No changes were written.`,"drawer.proposalApplyFailedHint":`Refresh the Goal state and regenerate. If it still fails, keep this page open and inspect advanced diagnostics.`,"drawer.proposalClose":`Close`,"drawer.proposalDefer":`Later`,"drawer.proposalDeferred":`Deferred. You can apply it later or regenerate it.`,"drawer.proposalEnterGoal":`Open new Goal`,"drawer.proposalExplainer":`After confirmation, LoopX applies this change and shows the write result. Closing or canceling changes nothing.`,"drawer.proposalRecheck":`Recheck against latest state`,"drawer.proposalRegenerate":`Retry with latest state`,"drawer.proposalRejected":`Rejected. This change will not be written.`,"drawer.proposalStale":`Source state changed. Recheck against the latest state.`,"drawer.proposalViewGoal":`View updated Goal`,"drawer.reassign":`Reassign to`,"drawer.reassignSummary":`Reassign: {task}`,"drawer.reason":`Reason`,"drawer.recoveryDescription":`Local history is preserved. Choose a recovery path.`,"drawer.recoveryFailed":`Upstream Session recovery failed`,"drawer.recoveryNewSession":`Start a new Session with context`,"drawer.recoveryRetry":`Retry recovery`,"drawer.repositoryRole":`Execution workspace`,"drawer.repository":`Repository`,"drawer.replyMode":`Reply mode`,"drawer.subagentApplied":`Applied and verified against the shared Goal state.`,"drawer.subagentAppliedRefreshFailed":`Applied and verified. The status view could not refresh; retry the page refresh later.`,"drawer.subagentApplying":`Applying and verifying shared-state readback…`,"drawer.subagentApplyFailed":`Could not apply the sub-agent setting.`,"drawer.subagentChildLimit":`Current limit`,"drawer.subagentConfirmDisable":`Confirm turning off sub-agent execution`,"drawer.subagentConfirmEnable":`Confirm turning on sub-agent execution`,"drawer.subagentCurrentBoundary":`Current task-domain restriction`,"drawer.subagentDescription":`Allows the runtime to create temporary child agents for independent tasks only after Todo, quota, capability, and write-scope gates pass. It does not force parallel work or grant durable authority.`,"drawer.subagentDisable":`Preview turning off sub-agent execution`,"drawer.subagentDisableSummary":`New child-agent execution will be disabled for this Goal. Existing Todo ownership and execution records stay unchanged.`,"drawer.subagentDomainInvalid":`The selected task-domain restriction is invalid.`,"drawer.subagentDomainTodoCount":`{count} matching open Todos`,"drawer.subagentDomains":`Task-domain restriction (optional)`,"drawer.subagentDomainsEmpty":`No open advancement Todo declares task_domain. Leave this empty to keep child execution unrestricted by task domain.`,"drawer.subagentDomainsHint":`Leave every option clear to apply no task-domain filter. Selecting domains admits only matching typed Todos; all other execution gates still apply.`,"drawer.subagentDomainsUnrestricted":`No task-domain restriction`,"drawer.subagentEnable":`Preview turning on sub-agent execution`,"drawer.subagentLabel":`Per-Goal execution boundary`,"drawer.subagentModel":`Child model`,"drawer.subagentEffort":`Child reasoning effort`,"drawer.subagentModelDefault":`Host default`,"drawer.subagentLunaPreset":`Use Luna / max`,"drawer.subagentClearModel":`Clear model preference`,"drawer.subagentModelHint":`Use Preview configuration update to save this preference. It can be saved while execution is off; host support is checked at launch.`,"drawer.subagentModelRequired":`Choose a child model before setting reasoning effort.`,"drawer.subagentMaxChildren":`Maximum child agents`,"drawer.subagentNoChange":`The current Goal already matches this setting; nothing was written.`,"drawer.subagentPending":`Pending confirmation`,"drawer.subagentPreviewBoundary":`Preview configuration update`,"drawer.subagentPreviewFailed":`Could not create the sub-agent setting preview.`,"drawer.subagentPreviewing":`Checking the latest Goal state…`,"drawer.subagentPreviewReady":`Preview locked. Confirm to apply this Goal setting.`,"drawer.subagentPreviewSummary":`Allow up to {count} child agents. Task-domain restriction: {domains}.`,"drawer.subagentRemoteReadOnly":`This source is read only. Open the Goal on its host to change the setting.`,"drawer.subagentTitle":`Adaptive sub-agent execution`,"drawer.remoteDetailsDescription":`SSH sources expose public-safe status only and do not read connection settings from the source host.`,"drawer.remoteDetailsUnavailable":`Remote details are not projected`,"drawer.resumeNo":`No`,"drawer.resumeYes":`Yes`,"drawer.runDetails":`Execution Session`,"drawer.runInterrupt":`Interrupt this run`,"drawer.runLatest":`View latest execution`,"drawer.runNewSession":`Start new Session`,"drawer.runCloseSession":`Close Session`,"drawer.runRecordEmpty":`No run record yet. The Agent has not started this execution. Check waiting conditions or resume the Session under Details & actions.`,"drawer.runRecordProjected":`No step-by-step record is available. LoopX read {completed}/{total} projected steps{outputs}; inspect the Session under Details & actions.`,"drawer.runRecordProjectedOutputs":` and {count} outputs`,"drawer.runRoleAssistant":`Completed`,"drawer.runRoleSystem":`Needs review`,"drawer.runRoleUser":`Task received`,"drawer.runView":`Session views`,"drawer.scheduleAdd":`Add scheduled check`,"drawer.scheduleDefaultNotification":`Notify only when you are needed`,"drawer.scheduleDefaultStop":`Goal completes or owner stops it`,"drawer.scheduleDefaultTarget":`Wake according to this Goal’s LoopX schedule.`,"drawer.scheduleEdit":`Change to every 2 hours`,"drawer.scheduleLast":`Last run`,"drawer.scheduleLocalTimezone":`Local timezone`,"drawer.scheduleNext":`Next run`,"drawer.scheduleNeverRun":`Not run yet`,"drawer.scheduleNotification":`Notification`,"drawer.schedulePause":`Pause`,"drawer.schedulePending":`Waiting for schedule`,"drawer.scheduleResume":`Resume`,"drawer.scheduleRunNow":`Run now`,"drawer.scheduleStop":`Stop {kind}`,"drawer.scheduleStopCondition":`Stop condition`,"drawer.scheduleTimezone":`Timezone`,"drawer.sessionRecoverable":`Resumable`,"drawer.sessionStatus":`Session status`,"drawer.setupHeartbeat":`Set up Heartbeat`,"drawer.taskActions":`Pending Todo actions`,"drawer.taskAdvancement":`Advancement task`,"drawer.taskBlock":`Mark blocked`,"drawer.taskComplete":`Mark complete`,"drawer.taskCompletedNote":`This task is retained as a read-only record.`,"drawer.taskCompletedTitle":`Task completed`,"drawer.taskDefer":`Defer`,"drawer.taskDeferCondition":`Todo defer resume condition`,"drawer.taskDeferInvalid":`Unsupported condition format; use one of the deterministic conditions below.`,"drawer.taskDeferPlaceholder":`For example, resume_at:2026-09-14T09:00:00+08:00`,"drawer.taskDeferReview":`Review defer`,"drawer.taskDeferSupported":`Supports todo_done, pr_merged, capacity_available, and timezone-aware resume_at conditions.`,"drawer.taskDeferUntil":`Defer until`,"drawer.taskDetails":`Todo details`,"drawer.taskInfo":`Task information`,"drawer.taskManage":`Manage task`,"drawer.taskNextCompleted":`Create a follow-up task`,"drawer.taskNextOpen":`Advance or update status`,"drawer.taskOrdinary":`Task`,"drawer.taskStatusBlocked":`Blocked`,"drawer.taskStatusDeferred":`Deferred`,"drawer.resumeWhen":`Resume condition`,"drawer.resumeState":`Resume state`,"drawer.resumePending":`Waiting for condition`,"drawer.resumeReady":`Ready to resume`,"drawer.resumeReceipt":`Resume receipt`,"drawer.taskNextDeferred":`Wait for the resume condition, then reassess`,"drawer.taskNextResumeReady":`Resume condition met; awaiting lifecycle replan`,"drawer.taskStatusCompleted":`Completed`,"drawer.taskStatusOpen":`Ready`,"drawer.taskSuccessor":`Create follow-up Todo`,"drawer.taskSuccessorNote":`Owner marked this blocked while waiting for more context.`,"drawer.taskSuccessorSummary":`Create follow-up Todo: {task}`,"drawer.taskSuccessorText":`Follow-up work for {task}`,"drawer.taskType":`Task type`,"drawer.topic":`Topic`,"drawer.trigger":`Trigger`,"drawer.titleAttention":`Needs you`,"drawer.titleOutput":`Output details`,"drawer.titleProposalApplied":`Execution result`,"drawer.titleProposalConfirm":`Confirm execution`,"drawer.titleSchedule":`Scheduled check`,"drawer.unconfigured":`Not configured`,"drawer.workspaceCandidates":`Available workspaces`,"files.emptySummary":`Public-safe output`,"files.empty":`No files, outputs, or verified reports yet.`,"files.loadingReports":`Loading verified milestone reports…`,"files.reportDelta":`+{added} added · {changed} changed`,"files.reportAdded":`added`,"files.reportChanged":`changed`,"files.reportGeneration":`Generation`,"files.reportLoadFailed":`Could not load verified reports`,"files.reportPublication":`Publication`,"files.title":`Files & Outputs`,"files.verifiedReport":`Verified milestone report`,"header.agentUnavailable":`Unavailable`,"header.chatRuntime":`Chat`,"header.workAgentCount":`{count} work Agents`,"header.chat":`Chat`,"header.files":`Files`,"header.goalCapabilities":`Capability settings`,"header.goalCapabilitiesDescription":`Manage overrides and inherited machine defaults.`,"header.goalDetails":`Goal details`,"header.goalDetailsDescription":`Review status, usage, repository, notifications, and sessions.`,"header.goalSettings":`Goal settings`,"header.goalSettingsDescription":`Open Goal details or capability settings`,"header.goalNavigation":`Goal navigation`,"header.goalView":`Goal view`,"header.live":`Live`,"header.manager":`LoopX Manager`,"header.managerDescription":`Your personal workspace across Goals`,"header.managerOverview":`Overview`,"header.managerView":`Manager view`,"header.openGoalNavigation":`Open Goal navigation`,"header.readOnlySourceDescription":`{source} is displayed read-only through an SSH tunnel`,"header.refresh":`Refresh status`,"header.refreshDone":`Updated just now`,"header.refreshFailed":`Refresh failed`,"header.refreshing":`Refreshing`,"header.selectAgent":`Select Agent`,"header.selectChatRuntime":`Select chat runtime`,"header.tasks":`Tasks`,"header.themeBrutal":`Switch to brutal theme`,"header.themePaper":`Switch to default theme`,"home.blockingSummary":`{count} are blocking an Agent.`,"home.completedGoals":`Completed Goals`,"home.empty":`Nothing here`,"startup.goalLoading":`Loading status…`,"startup.goalError":`Could not load status`,"startup.progress":`{loaded} of {total} active Goals loaded`,"startup.partial":`Goal states are updating. Counts are incomplete.`,"startup.independent":`Other Goals remain available while this Goal loads.`,"startup.error.timeout":`The request timed out. Retry when the local service is ready.`,"startup.error.network":`The connection was interrupted. Retry to reconnect.`,"startup.error.service":`The local service is temporarily unavailable. Retry to continue.`,"startup.error.revision":`The Goal directory changed during loading. Refresh to synchronize.`,"startup.error.scope":`This Goal is no longer available in the selected source. Refresh the directory.`,"startup.error.invalid":`The status response could not be read. Refresh or check for a LoopX update.`,"startup.retry":`Retry`,"startup.retryFailed":`Retry failed Goals`,"startup.failedCount":`{count} Goals could not be loaded. Ready Goals remain available.`,"home.greeting":`Hi, I’m your LoopX Manager`,"home.history":`History`,"home.lane.needsYou":`Needs you`,"home.lane.needsYouDescription":`Waiting for your decision, authorization, or context`,"home.lane.observing":`Observing`,"home.lane.observingDescription":`Monitoring continuously and notifying you when something changes`,"home.lane.running":`Running`,"home.lane.runningDescription":`Agents are making progress and reporting back`,"home.lane.scheduled":`Scheduled`,"home.lane.scheduledDescription":`Queued until its time or prerequisite arrives`,"home.noActivity":`No activity yet`,"home.noFirstActivity":`Waiting for first activity`,"home.noCompletedGoals":`No completed Goals yet`,"home.preservedState":`State is preserved and can be resumed`,"home.stopped":`Stopped`,"home.systemHealth":`System health: {summary}`,"home.taskCount":`{count} Tasks`,"home.todayAt":`Today {time}`,"home.waitingCount":`You have {count} items to handle.`,"home.workspace":`Goal workspace`,"lark.allMessages":`All messages in this topic`,"lark.allTopicMessages":`All topic messages`,"lark.agentIngress":`Agent ingress`,"lark.agentAppPermissions":`Every selected Agent needs a Lark App that is ready for group mentions and replies.`,"lark.agentApps":`Lark App per Agent`,"lark.agentAppsDescription":`The default App is preselected. Assign a different compatible App when an Agent needs its own bot identity.`,"lark.agentAppSelection":`Lark App for {agent}`,"lark.appCreated":`App created`,"lark.appCreateFailed":`Creation failed`,"lark.appLoading":`Loading available Lark Apps…`,"lark.appPermissions":`This App can send connection messages, but lacks the bot permissions required to receive group mentions or reply automatically. Enable im:message.group_at_msg:readonly, im:message.send_as_bot, and the im.message.receive_v1 event, publish a new version, then refresh.`,"lark.appProfile":`Lark App`,"lark.apps":`Lark Apps`,"lark.autoReplyUnavailable":`Auto reply unavailable`,"lark.autoReplyReady":`Auto reply ready`,"lark.bindGoal":`Bind to Goal`,"lark.cancel":`Cancel`,"lark.cardinality":`One Lark App · many Goals · one isolated route per Agent`,"lark.capture":`Capture`,"lark.captureAddressed":`Only messages that mention or reply to the App`,"lark.captureAll":`All messages in this Goal topic`,"lark.captureScope":`Capture scope`,"lark.captureScopeDescription":`Controls which Topic messages enter LoopX without expanding Agent permissions.`,"lark.closeConnection":`Close connection dialog`,"lark.closeCreate":`Close create dialog`,"lark.closeSettings":`Close Lark settings`,"lark.connect":`Connect`,"lark.connectAllAgents":`Connect every registered Agent`,"lark.connectAllAgentsAction":`Connect {count} Agents`,"lark.connectAllAgentsDescription":`Create {count} isolated Agent Topics in one guided action. Send requests inside the matching Topic; each Agent keeps its own route and inbox.`,"lark.connectApp":`Connect Lark App`,"lark.connection":`Connection`,"lark.connections":`Connections`,"lark.configuration":`Lark configuration`,"lark.continueFeishu":`Continue in Feishu`,"lark.createAutomatically":`Create Goal topic automatically`,"lark.createAutomaticallyDescription":`A dedicated, Agent-labelled Topic will be created for every selected Agent.`,"lark.defaultAgentAppDescription":`Used to find the target group and as the default for every selected Agent. Per-Agent choices below override it.`,"lark.description":`Manage reusable Lark Apps and connect group chats to Goals through dedicated topics.`,"lark.editConnection":`Edit Lark Connection`,"lark.goalConnections":`{count} Goal connections`,"lark.goalTopicConnections":`Lark Goal Topic connections`,"lark.groupChat":`Group chat`,"lark.groupEmpty":`This bot has not joined a group that can be connected. Add it to a Feishu group first, then return to refresh or search.`,"lark.groupLoading":`Reading groups joined by this bot…`,"lark.groupSearch":`Search groups joined by this bot`,"lark.historyPermission":`Group-history permission (separate capability)`,"lark.health.eventProcessed":`{events} events processed, {replies} replies sent.`,"lark.health.eventUnverified":`Event subscription needs verification`,"lark.health.eventUnverifiedDetail":`The provider listener is ready, but no event has arrived. Enable im.message.receive_v1 and group mention permissions, publish a new version, then send a new @ mention inside this Agent Topic. Group-level messages fail closed when multiple Agent routes exist.`,"lark.health.ignoredSelf":`The bot’s own message was ignored to prevent duplicate replies.`,"lark.health.invalidRouting":`Invalid routing configuration`,"lark.health.invalidRoutingDetail":`The connection was safely disabled. Select a processing mode again and save.`,"lark.health.lastStatus":`Latest event status: {status}`,"lark.health.listening":`Listening`,"lark.health.messageContextPermission":`Message permission required`,"lark.health.messageContextPermissionDetail":`A message event arrived, but group context could not be read. Publish and authorize group message read access for this App.`,"lark.health.notAddressed":`Latest message did not directly @ the bot`,"lark.health.notAddressedDetail":`Listening is healthy. This connection only responds to direct @ mentions or replies to the bot.`,"lark.health.notStarted":`Listener not started`,"lark.health.notStartedDetail":`Refresh the connection or restart LoopX, then try again.`,"lark.health.processingFailed":`Message processing failed`,"lark.health.processingFailedDetail":`The message event arrived, but Agent processing failed. Review local diagnostics and retry.`,"lark.health.queued":`Queued in the Agent inbox`,"lark.health.queuedDetail":`The message will be processed asynchronously by {agent} without starting a general Chat Session.`,"lark.health.sourceDisconnected":`Event connection disconnected`,"lark.health.sourceDisconnectedDetail":`The event consumer exited unexpectedly. Check that the app profile uses Feishu for Feishu apps or Lark for international Lark, then inspect connection and subscription errors. LoopX is retrying; successful history queries do not prove live delivery.`,"lark.health.retrying":`Retrying listener`,"lark.health.retryingDetail":`Event listening was interrupted and LoopX is retrying automatically.`,"lark.health.routeAmbiguous":`Message matches multiple Goals`,"lark.health.routeAmbiguousDetail":`The same bot and group have multiple full-group capture connections. Use a separate bot for each Agent or keep only one full-group connection.`,"lark.health.routeMismatch":`Message did not match this Goal Topic`,"lark.health.routeMismatchDetail":`The event came from another group or Topic. Reconnect this Goal to the correct group, then send a new @ mention.`,"lark.health.routeUnavailable":`Message cannot be routed to the Goal`,"lark.health.routeUnavailableDetail":`Connection data is incomplete. Reconnect this Goal, then send a new @ mention.`,"lark.health.starting":`Starting`,"lark.health.startingDetail":`LoopX is starting message event listening for this App.`,"lark.health.unavailable":`Auto reply unavailable`,"lark.health.waiting":`Waiting`,"lark.incomingMessages":`Incoming messages`,"lark.ingressAsync":`Async inbox`,"lark.ingressAsyncDescription":`Write to the Agent private inbox for a later explicit drain.`,"lark.editPreservesIdentity":`Saving preserves this App, group and Topic. Old connections upgrade to the Agent inbox by default.`,"lark.conversationKind":`Connection purpose`,"lark.managerConversation":`Manager · live conversation`,"lark.workerConversation":`Worker Agent · background tasks`,"lark.managerConversationDescription":`The built-in manager responds as you chat and delegates long-running work to background Agents. Group and private conversations keep separate histories.`,"lark.ingressLegacy":`Upgrade available`,"lark.ingressLegacyDescription":`Save this connection to upgrade to the Agent inbox. Existing messages remain in the same Topic.`,"lark.ingressQueue":`Queuing`,"lark.ingressQueueDescription":`Enter the same Agent Session's bounded FIFO queue and run after the current Turn.`,"lark.ingressSteering":`Steering`,"lark.ingressSteeringDescription":`Deliver to the active Turn and reject safely when no exact active Turn exists.`,"lark.loading":`Loading Lark configuration…`,"lark.management":`Lark management`,"lark.openEventSettings":`Open Feishu event settings`,"lark.mentions":`Mentions`,"lark.mentionsOnly":`Mentions only`,"lark.needsMessagePermissions":`Needs message permissions`,"lark.needsSetup":`Needs setup`,"lark.newApp":`New Lark App`,"lark.noAgentConfigured":`No Agent configured`,"lark.noConnections":`No matching connections.`,"lark.noProfiles":`No lark-cli App profiles are available yet.`,"lark.profileName":`Profile name`,"lark.profileValidation":`Profile can contain only letters, numbers, periods, underscores, and hyphens.`,"lark.processing":`Processing`,"lark.region":`Region`,"lark.registerAnother":`+ Register another Lark App — Create through Feishu`,"lark.reopenFeishu":`Reopen Feishu`,"lark.settingsConfigure":`Configure {goal}`,"lark.settingsDisconnect":`Disconnect {goal}`,"lark.replyMode":`Reply mode`,"lark.replyModeDescription":`Replies are limited to the source Topic to prevent cross-group or cross-Goal delivery.`,"lark.reusableApps":`{count} reusable Apps`,"lark.reusableWorkspaceApp":`Reusable workspace App`,"lark.routesUnverified":`{count} Lark routes pending verification`,"lark.saveConnection":`Save connection`,"lark.searchConnections":`Search Lark connections`,"lark.searchPlaceholder":`Search Apps, groups, Goals, or topics`,"lark.setupCopy":`LoopX opens the official Feishu creation page through lark-cli. App credentials stay in the system Keychain; LoopX stores only the profile reference.`,"lark.someoneMentions":`Someone mentions the Agent`,"lark.targetAgent":`Target Agent`,"lark.targetAgentDescription":`Choose a registered Agent in this Goal. This connection delivers to one Agent; it does not broadcast or grant permissions. Steering and Queuing require that Agent's exact active Session.`,"lark.agentUnavailable":`{agent} · no longer available`,"lark.selectRegisteredAgent":`Select an available registered Agent before connecting. The previous Agent will not be replaced automatically.`,"lark.topicPreview":`Topic preview`,"lark.topicReply":`Topic reply`,"lark.trigger":`Trigger`,"lark.waitingFeishu":`Waiting for Feishu`,"lark.waitingFeishuDescription":`Complete Feishu authorization in the new window. This page updates automatically when it is ready.`,"lark.waitingLink":`Generating the official Feishu creation link…`,"lark.error.appCreate":`Lark App creation failed`,"lark.error.appRequired":`Select a Lark App profile.`,"lark.error.bind":`Connection failed`,"lark.error.bindPreview":`Connection preview failed`,"lark.error.configuration":`Could not load Lark configuration`,"lark.error.groupLookup":`Could not read groups joined by this bot. Check the bot status and try again.`,"lark.error.groupLoad":`Could not load group chats`,"lark.error.invalidApp":`The Lark App profile is unavailable or has not completed authorization.`,"lark.error.messagePermissions":`This App lacks the bot permissions required for automatic replies. Enable im:message.group_at_msg:readonly and im:message:send_as_bot, publish a new version, then refresh.`,"lark.error.provider":`The Feishu API call failed without a verified receipt. Try again later.`,"lark.error.setupPoll":`Could not read creation status`,"lark.error.setupStart":`Could not start Lark App creation`,"lark.error.cliExecutable":`The configured lark-cli was found but cannot run. Check the installation or launch arguments.`,"lark.error.cliMissing":`lark-cli was not found. Install lark-cli and restart LoopX.`,"lark.error.cliStart":`lark-cli failed to start. Check the installation and restart LoopX.`,"lark.error.disconnect":`Disconnect failed`,"notifications.autoNotify":`Send automatically when your confirmation is required`,"notifications.bind":`Bind notification group`,"notifications.bindConfirm":`Bind “{goal}” to “{target}”. LoopX will verify that the bot is in the group and send a confirmation message.`,"notifications.bindFailed":`Binding failed`,"notifications.bound":`Bound`,"notifications.confirmBind":`Confirm binding`,"notifications.description":`Send Goal changes that need your confirmation to a Feishu group. Bindings and automatic delivery use the existing channel.`,"notifications.disabled":`Disabled`,"notifications.group":`Notification group: {target}`,"notifications.loadFailed":`Could not load notification groups`,"notifications.noTargets":`No notification groups are available. Group delivery uses a private bot identity; configure one from the terminal first:`,"notifications.notBound":`Not bound`,"notifications.recent":`Latest {time}`,"notifications.sentCount":`{count} sent`,"notifications.settings":`Goal notification bindings`,"notifications.setupFailed":`Could not update settings`,"notifications.title":`Feishu group notifications`,"proposal.field.agentId":`Agent`,"proposal.field.cadence":`Frequency`,"proposal.field.completionCriteria":`Completion criteria`,"proposal.field.executionBoundary":`Execution boundary`,"proposal.field.goalId":`Goal ID`,"proposal.field.heartbeat":`Heartbeat`,"proposal.field.initialTodos":`Initial tasks`,"proposal.field.objective":`Objective`,"proposal.field.operation":`Operation`,"proposal.field.permission":`Permission`,"proposal.field.reason":`Reason`,"proposal.field.stopCondition":`Stop condition`,"proposal.field.target":`Check target`,"proposal.field.timezone":`Timezone`,"proposal.field.title":`Title`,"proposal.field.workspace":`Execution workspace`,"actionReview.targetChanged":`The preview target does not match the requested Goal and operation. Generate a new preview.`,"actionReview.ready_stop":`Pausing is reversible. This validated preview can apply directly; completion still requires verified readback.`,"actionReview.resume_review":`Review before restoring automatic scheduling. Quota, gates and Todo constraints still apply.`,"actionReview.delete_review":`Review removal of this stopped Goal from the registries. Project files and history are preserved.`,"actionReview.action_review":`Review the target and impact before applying this proposal.`,"actionReview.protected_action":`This action needs explicit review. Confirmation cannot replace required authority.`,"actionReview.unknown_permission":`The permission classification is not recognized. Recheck the proposal before continuing.`,"actionReview.unknown_action":`This lifecycle operation is not recognized. Recheck the proposal before continuing.`,"actionReview.incomplete_proposal":`The preview is missing validation or an available apply transition. Generate a new preview.`,"actionReview.authority_gate":`A gate prevents execution. Resolve its requirements, then recheck the proposal.`,"actionReview.stale_proposal":`The source state changed. Generate a new preview; the previous decision no longer applies.`,"actionReview.apply_pending":`Execution is in progress. Wait for its result before retrying.`,"actionReview.readback_verified":`The action completed and its resulting state was verified.`,"actionReview.readback_unverified":`The action returned without verified readback. Completion is not confirmed; recheck the state.`,"actionReview.apply_failed":`Execution did not complete. Check the failure and regenerate the preview before retrying.`,"actionReview.inactive_proposal":`This proposal is no longer ready to execute. Recheck it before continuing.`,"proposal.gate.default":`Host confirmation required`,"proposal.impact.default":`After confirmation, the canonical LoopX service will write the state change.`,"proposal.impact.goalCreate":`After confirmation, LoopX will create the Goal and its initial Todo, then let the selected Agent start the first run.`,"proposal.impact.lifecycleDelete":`After confirmation, this stopped Goal is removed from the source and global registries. Project files, history state, and backups are preserved.`,"proposal.impact.lifecycleResume":`After confirmation, the Goal becomes eligible for automatic scheduling and returns to Active Goals. Actual execution still follows quota, Gate, and Todo constraints.`,"proposal.impact.lifecycleStop":`After confirmation, automatic progress stops and the Goal moves to the collapsed Stopped list. History, Todos, and evidence remain available for resuming.`,"proposal.impact.protected":`This action must be completed through the protected LoopX write service.`,"proposal.primary.apply":`Confirm and apply`,"proposal.primary.goalCreate":`Create Goal and start first run`,"proposal.primary.lifecycleDelete":`Delete Goal`,"proposal.primary.lifecycleResume":`Resume Goal`,"proposal.primary.lifecycleStop":`Stop Goal`,"proposal.primary.todoStart":`Create task and start execution`,"proposal.summary.goalCreate":`Create Goal: {title}`,"proposal.summary.heartbeat":`Set a Heartbeat for the current Goal`,"proposal.summary.lifecycleDelete":`Delete Goal: {title}`,"proposal.summary.lifecycleResume":`Resume Goal: {title}`,"proposal.summary.lifecycleStop":`Stop Goal: {title}`,"proposal.summary.monitor":`Create a scheduled check for the current Goal: {target}`,"proposal.workspace.current":`Current local workspace (no Repository bound)`,"proposal.workspace.named":`{workspace} (execution environment only; does not bind a repository)`,"proposal.workspaceGate.agentImpact":`Bind an Agent identity, then recheck the original action. No Goal has been written.`,"proposal.workspaceGate.agentTitle":`Bind an Agent first`,"proposal.workspaceGate.defaultSummary":`Select the Goal workspace.`,"proposal.workspaceGate.selectionImpact":`After selecting a workspace, LoopX will show the confirmation preview again. The selection itself does not write state.`,"proposal.workspaceGate.selectionTitle":`Select Goal workspace`,"projection.agentAdvancingGoal":`Agent is advancing the current Goal`,"projection.agentIdle":`Nothing needs your attention`,"projection.agentNeedsDecision":`Agent is waiting for your decision`,"projection.agentPreparingNextStep":`Agent is preparing the next step`,"projection.agentStopped":`Stopped by you; history, Todos, and evidence are preserved`,"projection.agentWaitingExternal":`Waiting for an external condition`,"projection.confirmAgentDecision":`Confirm the permission or decision the Agent needs next`,"projection.events24h":`{count} events in the last 24 hours`,"projection.firstReadOnlyAdapterCheck":`Run the first read-only adapter check and save progress`,"projection.goalVerified":`Goal state, Todos, and registration information verified`,"projection.latestRun":`Latest run`,"projection.latestValidation":`Latest validation`,"projection.nextUpdatePending":`Waiting for LoopX to update the next step`,"projection.publicSafeProjection":`Public-safe status projection`,"projection.refreshState":`Refresh LoopX status and confirm the current progress is still valid`,"projection.runEvidenceAvailable":`Run evidence is available`,"projection.runRecorded":`The latest LoopX run is recorded`,"projection.statusRefreshNeeded":`LoopX status needs to be refreshed`,"projection.todoStatusUpdated":`Todo status updated; confirming the next step`,"projection.validationRecorded":`The latest validation is recorded`,"runs.completed":`Completed`,"runs.failed":`Needs review`,"runs.interrupted":`Interrupted`,"runs.queued":`Scheduled`,"runs.ready":`Ready`,"runs.resumeFailed":`Recovery failed`,"runs.running":`Running`,"runs.unknown":`Unknown`,"runs.waiting":`Waiting`,"schedule.active":`Running`,"schedule.heartbeat":`Goal Heartbeat`,"schedule.monitor":`Scheduled & continuous task`,"schedule.paused":`Paused`,"schedule.summary":`Continuously checked under LoopX scheduling constraints`,"schedule.defaultTarget":`Check the current Goal for blockers, progress, and new outputs`,"schedule.unsupportedCalendar":`Scheduled checks do not currently support an exact weekday or time. Use a fixed interval such as “Every 30 minutes,” “Every 2 hours,” or “Daily.” The draft was preserved and no confirmation preview was created.`,"source.add":`Add source`,"source.addConfigured":`Add read-only source`,"source.addMethod":`Source setup method`,"source.addSsh":`Add SSH source`,"source.closeForm":`Close source form`,"source.configured":`Configured SSH`,"source.configuredCount":`Local SSH Hosts · {count}`,"source.configuredGroup":`Configured SSH Hosts · {count} (select to add)`,"source.connected":`Connected`,"source.connecting":`Connecting`,"source.controlPlane":`Control plane source`,"source.copy":`Copy`,"source.copyCommand":`Copy SSH tunnel command`,"source.copyError":`Could not copy the command. Copy it manually below.`,"source.copied":`Copied`,"source.description":`All explicit Hosts are loaded, including Include files. Wildcards are not listed. Run the command first; LoopX never reads SSH keys or configuration details.`,"source.host":`Local SSH Host`,"source.hostEmpty":`No explicit SSH Hosts are available in ~/.ssh/config.`,"source.hostLoadError":`Could not read local SSH Hosts.`,"source.hostPlaceholder":`Enter or search for a Host`,"source.invalid":`The SSH source settings are invalid.`,"source.loadingHosts":`Loading…`,"source.localInteractive":`Local interactive`,"source.localPort":`Local port`,"source.manual":`Manual URL`,"source.manualDescription":`Remote sources always remain read-only projections and never inherit local write permissions.`,"source.name":`Name`,"source.namePlaceholder":`Remote development machine`,"source.notAvailable":`Unavailable`,"source.readOnly":`SSH tunnel · read only`,"source.readOnlyNoticeDescription":`You can view Goals, Tasks, evidence, and run status. Writes, guidance, and Agent sessions remain on the source host.`,"source.readOnlyNoticeTitle":`Remote read-only projection`,"source.readOnlyWriteError":`Remote SSH tunnel sources are read-only projections and cannot perform control-plane writes.`,"source.refreshHosts":`Reload SSH Hosts`,"source.remove":`Remove source {source}`,"source.removeCurrent":`Remove current source`,"source.select":`Select control plane source`,"source.selectHost":`Select a configured SSH Host.`,"source.statusUrl":`Local forwarded URL`,"source.tunnelCommandPending":`Select a Host to generate the tunnel command`,"machine.absent":`Not configured`,"machine.action.create":`Create machine policy`,"machine.action.delete":`Remove machine policy`,"machine.action.unchanged":`No write required`,"machine.action.update":`Update machine policy`,"machine.applied":`Machine policy applied and read back successfully.`,"machine.applyError":`Machine policy could not be applied.`,"machine.applyPreview":`Apply reviewed preview`,"machine.changedNamespaces":`Changed namespaces`,"machine.capabilityCatalog":`Machine capability catalog`,"machine.capabilityEmpty":`No machine-configurable capabilities are registered.`,"machine.configured":`Configured`,"machine.confirmRollback":`Confirm rollback`,"machine.currentRevision":`Current revision`,"machine.currentValue":`Current machine value`,"machine.description":`Browse the same capability catalog as Goal settings. Configure supported machine defaults here; Goal-only capabilities are labeled explicitly.`,"capabilities.rawJson":`Advanced: raw JSON`,"machine.goalOnly":`This capability currently supports Goal configuration only. Open a Goal’s capability settings to configure it; no machine-wide default is applied.`,"machine.desiredRevision":`Desired revision`,"machine.editorUnavailable":`No editor is installed for this namespace`,"machine.editorUnavailableDescription":`The namespace remains visible in the registry. Install or upgrade its Dashboard editor before changing it.`,"machine.editorMode":`Editor mode`,"machine.liveDefault":`Live default; Goal override wins`,"machine.liveDefaultDescription":`Goals without an explicit override read the current machine policy at the capability’s next decision point. Changes and removal affect those existing Goals immediately; an explicit Goal override stays pinned.`,"machine.genericNamespaceDescription":`Edit this registered namespace as JSON. LoopX validates it with the capability-owned schema before previewing any write.`,"machine.jsonConfiguration":`Namespace configuration (JSON)`,"machine.jsonConfigurationHelp":`Only this namespace is updated. Other machine configuration is preserved, and Apply remains locked to the reviewed preview revision.`,"machine.jsonEditor":`JSON`,"machine.editJson":`Edit JSON`,"capabilities.jsonConfiguration":`Goal configuration (JSON)`,"capabilities.jsonHelp":`Edit registered fields for this Goal. Changes require a new preview before applying.`,"capabilities.jsonInvalid":`Enter a valid JSON object using only registered editable fields.`,"machine.backToForm":`Back to form`,"machine.jsonInvalid":`Enter one valid JSON object before previewing changes.`,"machine.loadError":`Machine configuration could not be loaded.`,"machine.machinePolicy":`Machine policy`,"machine.namespaceCount":`Registered namespaces`,"machine.namespaces":`Configuration namespaces`,"machine.periodicReport":`Periodic reports`,"machine.periodicReportDescription":`Default report policy for every Goal without an explicit override. Goal scheduling and delivery consume the effective configuration.`,"machine.periodicReportActivation":`Enabled means automatic delivery at validated stage boundaries`,"machine.periodicReportActivationDescription":`This is not a weekly timer. When LoopX validates a Goal stage completion, an Agent prepares and freezes the report, then automatically delivers it through the configured Goal Channel. The enabled subscription is standing delivery authority; failures and route drift stop closed for repair.`,"machine.changeQualityActivation":`Qualification is a quality gate, not new authority`,"machine.changeQualityActivationDescription":`Goals that inherit this policy qualify their exact final diff. safe_fix allows at most one bounded fix pass inside existing write authority; this setting never grants file, permission, or merge authority.`,"machine.replanCadenceActivation":`Review cadence changes timing, not execution authority`,"machine.replanCadenceActivationDescription":`Goals without an explicit override read this threshold before the next review decision. It does not create Turns, spend quota, or grant authority.`,"machine.preview":`Review exact machine change`,"machine.previewChanges":`Preview changes`,"machine.previewError":`A machine-policy preview could not be created.`,"machine.previewLocked":`Apply is locked to this exact revision. If machine state changes, LoopX requires a new preview.`,"machine.previewRollback":`Preview rollback`,"machine.previewRemoval":`Preview removal`,"machine.profilePreset":`Profile preset`,"machine.profilePresetHelp":`A capability-owned preset, such as weekly-progress.`,"machine.registry":`Typed registry`,"machine.requiredFields":`Enable requires a profile preset, Goal Channel route, and valid timezone.`,"machine.revision":`Machine revision`,"machine.revisionLockedReady":`All changes require a preview and apply only while that exact machine revision remains current.`,"machine.rollbackAvailable":`Rollback is available for the last apply`,"machine.rollbackDescription":`Preview the stored prior revision before restoring it.`,"machine.rollbackError":`The rollback could not be completed.`,"machine.rollbackPreviewDescription":`The prior revision is ready to restore. Confirm to apply this rollback.`,"machine.rolledBack":`The prior machine policy was restored and verified.`,"machine.removed":`Machine policy removed and the resulting configuration read back successfully.`,"machine.routeRef":`Goal Channel route`,"machine.routeRefHelp":`Use a public route alias; credentials and provider identifiers never enter this form.`,"machine.timezone":`Timezone`,"machine.timezoneHelp":`Use an IANA timezone, for example Asia/Shanghai.`,"machine.title":`Machine configuration`,"machine.unchanged":`Machine policy already matches this preview; nothing was written.`,"machine.visualEditor":`Guided`,"capabilities.atomicOverride":`Goal override is atomic`,"capabilities.atomicOverrideDescription":`A complete Goal value wins over the machine default. LoopX never mixes individual fields across scopes.`,"capabilities.applyFailed":`Goal capability changes were not applied.`,"capabilities.applyPreview":`Apply preview`,"capabilities.catalog":`Goal capability catalog`,"capabilities.chooseGoal":`Choose a Goal before inspecting its capabilities.`,"capabilities.defaultValue":`Declared default`,"capabilities.description":`Inspect the capabilities available to this Goal and the exact scope of each setting.`,"capabilities.editorPrepared":`Typed editor contract available`,"capabilities.effectiveSource":`Effective source`,"capabilities.empty":`No capability descriptors are available for this Goal.`,"capabilities.fields":`Registered fields`,"capabilities.goalPolicy":`Goal capability policy`,"capabilities.goalScope":`Goal`,"capabilities.goalValue":`Current Goal value`,"capabilities.loadFailed":`Could not load Goal capabilities`,"capabilities.loading":`Loading Goal capabilities…`,"capabilities.machineOnly":`This capability is configured only at machine scope.`,"capabilities.machineValue":`Live machine default`,"capabilities.machineScope":`Machine`,"capabilities.previewOnly":`Inspection is live. Goal writes remain unavailable until the revision-locked preview and apply path is connected.`,"capabilities.preview":`Revision-locked preview`,"capabilities.previewChanges":`Preview changes`,"capabilities.restoreInheritance":`Restore machine-default inheritance`,"capabilities.previewFailed":`Could not preview Goal capability changes.`,"capabilities.previewLocked":`Apply will re-check this exact plan revision and reject stale changes.`,"capabilities.partialWrite":`Goal value saved; shared projection needs reconciliation`,"capabilities.partialWriteDescription":`The source Goal configuration was written and read back. Its shared runtime projection did not synchronize, so do not submit the change again.`,"capabilities.refreshSource":`Refresh source value`,"capabilities.readOnly":`Read-only capability`,"capabilities.revisionLockedReady":`Changes require a preview and are applied only when its exact revision is still current.`,"capabilities.retry":`Retry`,"capabilities.source.capability_default":`Capability default`,"capabilities.source.goal_override":`Goal override`,"capabilities.source.machine_default":`Live machine default`,"capabilities.source.not_configured":`Not configured`,"capabilities.title":`Goal capabilities`,"settings.close":`Close settings`,"settings.appearance":`Appearance`,"settings.appearanceDescription":`Manage workspace display preferences in this browser.`,"settings.appearanceTabDescription":`Theme and display preferences`,"settings.capabilitiesTabDescription":`Capability overrides for this Goal`,"settings.back":`Back to workspace`,"settings.categories":`Settings categories`,"settings.description":`Manage workspace preferences and integrations.`,"settings.eyebrow":`Workspace preferences`,"settings.general":`General`,"settings.goalConnections":`Goal connections`,"settings.language":`Language`,"settings.languageDescription":`Choose the language used by the LoopX desktop workspace.`,"settings.languageEnglishDescription":`Use English for navigation, settings, and workspace controls.`,"settings.languageEnglish":`English`,"settings.languageSimplifiedChineseDescription":`Use Simplified Chinese for navigation, settings, and workspace controls.`,"settings.languageSimplifiedChinese":`Simplified Chinese`,"settings.languageStoredLocally":`This preference is stored only on this device.`,"settings.languageTabDescription":`Interface language for this device`,"settings.larkTabDescription":`Apps, group chats, and Goal Topic connections`,"settings.machineTabDescription":`Typed defaults shared by capabilities on this machine`,"settings.notifications":`Notifications`,"settings.open":`Settings`,"settings.themeDefault":`Paper`,"settings.themeDefaultDescription":`Calm and lightweight for long-running work.`,"settings.themeDescription":`Choose the workspace visual style. This preference is stored in the current browser.`,"settings.themeHighContrast":`High contrast`,"settings.themeHighContrastDescription":`Stronger borders and more prominent state blocks.`,"settings.themeLoopx":`LoopX standard`,"settings.themeLoopxDescription":`Precise monochrome surfaces, Geist type, and quiet hairline structure.`,"settings.title":`Settings`,"settings.workspaceDisplay":`Workspace display`,"settings.workspaceTheme":`Workspace theme`,"session.closeRecord":`Exit run record`,"session.details":`Session details`,"session.record":`Execution Session · Run record`,"session.recordDescription":`The timeline now shows messages and Turn records from this Session.`,"sidebar.createGoal":`Create Goal`,"sidebar.delete":`Delete`,"sidebar.deleteGoal":`Delete Goal`,"sidebar.manager":`LoopX Manager`,"sidebar.notifications":`Settings`,"sidebar.owner":`Personal workspace`,"sidebar.product":`Personal Agent workspace`,"sidebar.resume":`Resume`,"sidebar.resumeGoal":`Resume Goal`,"sidebar.stop":`Stop`,"tasks.historyLoading":`Loading history…`,"tasks.historyError":`History could not be loaded.`,"tasks.historyExpired":`History snapshot expired. Reload to continue.`,"tasks.historyRetry":`Reload`,"tasks.historyEnd":`End of completed history`,"tasks.historyMore":`Load more`,"tasks.historyLocalOnly":`Open this machine’s Dashboard to browse full history.`,"sidebar.sortGoals":`Reorder Goals`,"sidebar.dragGoal":`Drag to reorder, or use Reorder Goals`,"sidebar.moveUp":`Move {goal} up`,"sidebar.moveDown":`Move {goal} down`,"sidebar.goalMoved":`{goal} moved to position {position}`,"sidebar.orderNotSaved":`Order changed for this visit; browser storage is unavailable.`,"sidebar.stopGoal":`Stop Goal`,"sidebar.stopped":`Stopped`,"sidebar.stoppedLoading":`Loading stopped Goals`,"sidebar.stoppedLoadFailed":`Stopped Goals could not be loaded. Active Goals remain available.`,"sidebar.retryStopped":`Retry`,"state.completed":`Completed`,"state.needsRepair":`Needs repair`,"state.needsYou":`Needs you`,"state.quiet":`Quiet`,"state.running":`Running`,"state.stopped":`Stopped`,"state.waiting":`Waiting`,"tasks.blocked":`Blocked`,"tasks.agentLane":`Work Agent`,"tasks.agentLaneDescription":`Filter this Goal's projected work lanes`,"tasks.agentLaneFilter":`Filter by work Agent`,"tasks.allAgentLanes":`All Agents ({count})`,"tasks.chatAgentReplied":`Agent replied`,"tasks.chatPending":`Sent to Agent`,"tasks.chatPendingDescription":`Processing. Tasks update only after a task operation is confirmed.`,"tasks.chatRecent":`Recent conversation`,"tasks.chatUnchangedDescription":`This conversation did not directly change Tasks. Convert the reply to a Task draft and confirm it when execution is needed.`,"tasks.chatViewReply":`View reply`,"tasks.convertToTask":`Convert to Task`,"tasks.completed":`Completed`,"runs.discoveryPartial":`Some execution details are unavailable. Reconnecting; task summaries are not live execution status.`,"runs.discoveryOffline":`Execution service unavailable. Reconnecting; retained task summaries may be stale.`,"files.openConversation":`Go to conversation`,"files.exportSummary":`Export summary`,"tasks.viewDescription":`Decisions first, then work and recent completions`,"tasks.viewLabel":`Task view`,"tasks.listView":`List`,"tasks.boardView":`Board`,"tasks.completedSummary":`{count} tasks completed. Recent details are projected by the control plane when needed.`,"tasks.emptyCompleted":`No completed tasks yet.`,"tasks.emptyConfirm":`No tasks waiting for confirmation.`,"tasks.emptyRunning":`No queued or running tasks.`,"tasks.emptySchedules":`No scheduled tasks.`,"tasks.emptyGoal":`This Goal has no tasks yet. Describe the next step below and LoopX will show a confirmation preview first.`,"tasks.markComplete":`Mark complete: {name}`,"tasks.moreActions":`More actions: {name}`,"tasks.openExecution":`View execution: {name}`,"tasks.pending":`Pending`,"tasks.pendingAndRunning":`Queued / Running`,"tasks.scheduled":`Scheduled & continuous`,"tasks.sessionError":`Session issue`,"tasks.waiting":`Queued`,"tasks.waitingAge":`Waiting {age}`,"tasks.viewExecution":`View execution`,"tasks.viewResult":`View result`,"time.days":`{count} days`,"time.hours":`{count} hours`,"timeline.emptyGoal":`This Goal has no new activity`,"timeline.emptyGoalDescription":`Ask for progress or send new guidance.`,"timeline.emptyWorkspace":`Your workspace is quiet today`,"timeline.emptyWorkspaceDescription":`Describe a Goal to the LoopX Manager, or ask what deserves attention today.`,"timeline.gateHistory":`{count} historical Gates`,"timeline.pending":`Working…`,"timeline.runCompleted":`{run}: completed`,"timeline.review":`Review`,"timeline.reviewAndConfirm":`Review and confirm`,"timeline.waitingConfirmation":`Needs your confirmation`},"zh-CN":{"acceptance.connected":`已连接`,"acceptance.mapped":`已建立项目映射`,"acceptance.refreshed":`已刷新状态`,"acceptance.inspected":`已检查适配器`,"acceptance.recorded":`已记录执行`,"acceptance.judged":`已记录反馈`,"acceptance.approved":`已记录批准`,"acceptance.ready":`已记录控制器就绪`,"acceptance.attentionSource":`当前状态`,"acceptance.visionSource":`Agent 验收条件`,"acceptance.todoSource":`任务状态`,"acceptance.runSource":`最新执行证据`,"acceptance.title":`验收观察`,"acceptance.unavailable":`验收观测不可用,Goal 是否达成仍未知。`,"acceptance.partial":`当前仅有部分观测。任务完成或缺口列表为空,都不能证明 Goal 已通过验收。`,"acceptance.gaps":`仍需补充的证据`,"acceptance.reasonUnknown":`来源未提供原因`,"acceptance.unknown":`未知`,"acceptance.required":`所需证据或条件`,"acceptance.observed":`观测时间`,"acceptance.noGaps":`现有观测中没有缺口,尚未评估完整验收条件。`,"acceptance.guards":`待处理的门禁决策`,"acceptance.noGuards":`现有观测中没有待处理的门禁决策。`,"acceptance.scope":`决策范围`,"acceptance.next":`当前状态给出的下一步`,"acceptance.historical_progress":`已记录的历史进展`,"acceptance.historical":`历史生命周期记录不授予权限,也不代表通过验收。`,"acceptance.missing":`未获取的来源:`,"acceptance.truncated":`仅展示前 12 条观测。`,"common.actions":`操作`,"common.agent":`Agent`,"common.allMessages":`所有消息`,"common.cancel":`取消`,"common.close":`关闭`,"common.closeActionReceipt":`关闭操作回执`,"common.confirm":`确认`,"common.export":`导出`,"common.failed":`失败`,"common.goal":`Goal`,"common.loading":`加载中…`,"common.none":`无`,"common.off":`关闭`,"common.on":`开启`,"common.open":`打开`,"common.owner":`Owner`,"common.readOnly":`只读`,"common.recently":`刚刚`,"common.status":`状态`,"common.task":`Task`,"common.you":`你`,"common.waiting":`等待中`,"composer.addImage":`添加图片`,"composer.agentProgress":`向 Agent 获取进度报告`,"composer.agentProgressPrompt":`请给我一份当前 Goal 的进度报告:已完成、执行中、阻塞和下一步。`,"composer.attachImageHint":`选择、粘贴或拖入图片`,"composer.clarifyDefer":`暂缓 Todo 需要可自动判断的恢复条件。请补充 todo_done:、pr_merged:[owner/repo]#、capacity_available: 或 resume_at:<带时区 RFC3339 时间>。`,"composer.clarifySingleAction":`这句话包含多个可能修改状态的操作。请一次描述一项操作,我会逐项展示确认预览。`,"composer.createGoal":`创建新 Goal`,"composer.createGoalDraft":`Goal 草稿`,"composer.createGoalDraftDescription":`补充内容后发送,LoopX 会先展示待确认操作。`,"composer.createGoalDraftLead":`我想创建一个长期 Goal:`,"composer.createGoalTemplate":`我想创建一个长期 Goal: -目标: -完成标准: -执行边界(可选): -关联仓库(可选): -通知方式(可选):`,"composer.createGoalHint":`填入 Goal 模板草稿,检查后再创建`,"composer.draft":`草稿`,"composer.globalProgress":`汇总所有 Goal 进展`,"composer.globalProgressPrompt":`请帮我汇总所有活跃 Goal 的最新进展与阻塞。`,"composer.globalTasks":`询问全局待办`,"composer.globalTasksPrompt":`有哪些 Goal 正在等我?我现在该优先处理什么?`,"composer.goalMessageHint":`你的消息由 {agent} 在本 Goal 的会话中接收`,"composer.goalRunningHint":`{agent} 正在执行 {count} 个任务 · 你的消息作为纠偏进入本会话,不会打断执行`,"composer.goalPlaceholder":`询问或纠偏 {goal}…`,"composer.imageAnalysisPrompt":`请结合这些图片分析当前 Goal,并告诉我下一步。`,"composer.imageCountError":`最多添加 {count} 张图片。`,"composer.imagePicker":`图片文件选择器`,"composer.imageReadError":`无法读取图片 {name}`,"composer.imageReadGenericError":`图片读取失败。`,"composer.imageSizeError":`单张图片不能超过 {size}MB。`,"composer.imageTypeError":`支持 PNG、JPEG、WebP 和 GIF 图片。`,"composer.imagesPending":`待发送图片`,"composer.immediate":`立即发送`,"composer.managerMessageHint":`你的消息由 LoopX 管家跨 Goal 接收,支持全局询问与创建 Goal`,"composer.managerPlaceholder":`问问 LoopX 管家,或描述一个新 Goal…`,"composer.monitor":`配置定时检查`,"composer.monitorGoalQuestion":`为哪个 Goal 添加定时检查?`,"composer.monitorTemplate":`为当前 Goal 添加定时检查: -检查内容: -频率(支持 30 分钟 / 2 小时 / 每天):每 2 小时 -停止条件:Goal 完成`,"composer.monitorTemplateWithoutGoal":`配置定时检查: -Goal: -检查内容: -频率:每 2 小时 -停止条件:Goal 完成`,"composer.monitorHint":`先填写检查内容、频率和停止条件,不会立即创建`,"composer.heartbeatGoalQuestion":`为哪个 Goal 设置 Heartbeat?`,"composer.heartbeatTemplate":`为当前 Goal 设置 Heartbeat: -频率:每天 -停止条件:Goal 完成 -通知:仅在需要我时`,"composer.heartbeatTemplateWithoutGoal":`设置 Heartbeat: -Goal: -频率:每天 -停止条件:Goal 完成 -通知:仅在需要我时`,"composer.nextAction":`询问下一步`,"composer.nextActionPrompt":`我现在该做什么?`,"composer.prepareDraft":`填入编辑框,确认后再发送`,"composer.send":`发送`,"composer.sendMessage":`向 LoopX 发送消息`,"composer.sendMessageHint":`发送消息`,"composer.sentImageAlt":`移除图片 {name}`,"conversation.agentPending":`正在整理…`,"conversation.close":`关闭对话回执`,"conversation.convertHint":`将 Agent 最新回复转为 Task 草稿`,"conversation.full":`查看完整对话`,"conversation.receipt":`对话回执`,"conversation.replying":`正在回复`,"conversation.title":`管家对话`,"conversation.toTask":`转为 Task`,"digest.away":`自上次访问以来的运行记录`,"digest.completed":`新增完成运行`,"digest.failed":`新增失败或中断`,"digest.needsYou":`当前待确认`,"feedback.applying":`正在执行:{title}`,"feedback.cancelFailed":`取消失败:{error}`,"feedback.completed":`已完成:{title}`,"feedback.executionFailed":`执行失败:{error}`,"feedback.gateRequired":`需要你确认:{summary}`,"feedback.notCompleted":`操作未完成:{status}`,"feedback.goalRefreshFailed":`已打开 Goal,但暂时无法刷新最新状态。请点击刷新重试。`,"feedback.preparingPreview":`正在准备确认预览:{title}`,"feedback.previewFailed":`无法准备确认预览:{error}`,"feedback.sendFailed":`发送失败:{error}`,"feedback.sendGenericError":`消息发送失败,请稍后重试。`,"feedback.stale":`状态已变化,操作未执行,请重新生成确认预览。`,"feedback.taskDraftCreated":`已根据回复生成 Task 草稿。编辑后发送,LoopX 会先展示确认预览。`,"goal.defaultTitle":`新的个人 Goal`,"goal.initialTodo":`按完成标准推进:{criteria}`,"goal.objectiveBoundary":`执行边界:{boundary}`,"goal.objectiveCompletion":`完成标准:{criteria}`,"drawer.advancedDiagnostics":`高级诊断`,"drawer.agentWorking":`Agent 正在继续执行,记录会自动更新。`,"drawer.analysis":`正在分析`,"drawer.apply":`确认并应用`,"drawer.applying":`正在应用…`,"drawer.attentionBlocking":`正在阻塞 Agent`,"drawer.attentionWaiting":`等待你的决定`,"drawer.autoNotify":`Human-gate 自动通知`,"drawer.branch":`分支`,"drawer.closeDetail":`关闭详情:返回{context}`,"drawer.connected":`已连接`,"drawer.correctionDescription":`消息会沿用当前 Goal、Todo 与 Agent Session 上下文。`,"drawer.correctionLabel":`与 {agent} 纠偏`,"drawer.correctionPlaceholder":`例如:先关注权限风险,暂时不要提交…`,"drawer.correctionSend":`发送纠偏`,"drawer.correctionTextarea":`输入纠偏信息:Goal {goal},Agent {agent},Run {run}`,"drawer.copyRepository":`复制仓库标识`,"drawer.copyRepositoryDone":`已复制仓库标识`,"drawer.copyRepositoryError":`复制失败,请检查浏览器剪贴板权限。`,"drawer.copyRepositorySuccess":`已复制,可粘贴到其他工具。`,"drawer.cost":`成本 24h / 7d`,"drawer.costShort":`成本`,"drawer.durationShort":`时长`,"drawer.period24h":`24 小时`,"drawer.period7d":`7 天`,"drawer.tokens":`Token 24 小时 / 7 天`,"drawer.tokensShort":`Token`,"drawer.usageNotMeasured":`未采集`,"drawer.currentGoal":`当前 Goal`,"attentionDetail.title":`事项说明`,"attentionDetail.request":`需要你做什么`,"attentionDetail.decision":`需要作出决定`,"attentionDetail.unknownRequest":`来源未明确,请先查看来源再判断`,"attentionDetail.open":`当前投影中待处理`,"attentionDetail.closed":`已关闭`,"attentionDetail.deferred":`已推迟`,"attentionDetail.superseded":`已被替代`,"attentionDetail.unknown":`来源未提供状态`,"attentionDetail.unavailable":`来源尚未确认当前事项,请刷新后再操作`,"attentionDetail.unknownReason":`来源尚未提供原因。`,"attentionDetail.targetTodo":`关联的待解锁 Todo`,"attentionDetail.targetAgent":`事项指定的 Agent`,"attentionDetail.scope":`声明的决策范围`,"attentionDetail.notProvided":`来源未提供`,"attentionDetail.replacement":`替代 Todo`,"attentionDetail.openReplacement":`打开替代事项`,"attentionDetail.boundary":`阅读详情不会关闭 gate 或授予权限;作出决定前仍需新的操作预览。`,"drawer.decisionDefaultEvidence":`当前状态没有附加公开安全证据;下一步仍会先展示 Preview。`,"drawer.decisionDefaultReason":`该决定会影响当前 Todo 的下一步执行。`,"drawer.decisionDefer":`稍后决定`,"drawer.decisionMore":`更多决定`,"drawer.decisionReject":`拒绝`,"drawer.decisionReview":`查看影响并决定`,"drawer.dependencies":`依赖`,"drawer.detailsAndActions":`详情与操作`,"drawer.duration":`运行时长 24h / 7d`,"drawer.evidence":`证据`,"drawer.executionHistory":`执行历史`,"drawer.executionRecord":`运行记录`,"drawer.executionRecordAndResult":`执行过程与结果`,"drawer.explainDecision":`解释此决定`,"drawer.gateApproveHint":`在终端执行一条命令即可完成审批:`,"drawer.gateRejectHint":`不同意就把末尾的 approve 换成 reject。执行后这条提醒会自动消失。`,"drawer.gateRequiresHost":`需要宿主确认`,"drawer.gateRequiresHostDescription":`页面无权直接批准这类权限变更,你的点击没有写入任何内容。`,"drawer.goalAutoRun":`当前 Goal 的自动运行`,"drawer.goalChanges":`当前 Goal 的待确认变更`,"drawer.goalDetails":`Goal 详情`,"drawer.group":`群聊`,"drawer.inspectorFull":`切换到全屏`,"drawer.inspectorFullView":`全屏查看`,"drawer.inspectorHalf":`切换到半屏`,"drawer.inspectorHalfView":`半屏查看`,"drawer.lastNotification":`最近通知`,"drawer.larkConfigure":`管理 Lark connection`,"drawer.larkConnect":`连接 Lark App`,"drawer.larkConnection":`Lark connection`,"drawer.larkNotConfigured":`未配置`,"drawer.larkNotConfiguredDescription":`配置后,当这个 Goal 出现需要你确认的变更时,会自动发飞书通知。`,"drawer.managerChanges":`管家待确认变更`,"drawer.moreActions":`更多操作`,"drawer.moreRunActions":`更多运行操作`,"drawer.nextTransition":`下一转换`,"drawer.noExecutionHistory":`暂无执行记录。`,"drawer.noRun":`尚未启动执行 Session`,"drawer.noRunDescription":`Agent 开始执行后,运行记录会稳定显示在这里。`,"drawer.notAssigned":`未分配`,"drawer.notLinked":`未关联`,"drawer.notSet":`未设置`,"drawer.outputDetails":`产出详情`,"drawer.outputRecorded":`该产出已记录到当前 Goal。`,"drawer.outputSafePreview":`公开安全产出预览`,"drawer.outputRun":`Run`,"drawer.outputTodo":`Todo`,"drawer.outputs":`本次运行产出`,"drawer.previewUnavailable":`此产出没有可用的公开安全内联预览。`,"drawer.priority":`优先级`,"drawer.progress":`进度`,"drawer.proposalApplied":`已应用,LoopX 状态将刷新。`,"drawer.proposalApplyFailed":`应用失败,没有写入任何变更。`,"drawer.proposalApplyFailedHint":`请刷新 Goal 状态后重新生成;若仍失败,可保留此页并查看高级诊断。`,"drawer.proposalClose":`关闭`,"drawer.proposalDefer":`稍后`,"drawer.proposalDeferred":`已暂缓,可稍后继续应用或重新生成。`,"drawer.proposalEnterGoal":`进入新 Goal`,"drawer.proposalExplainer":`确认后,LoopX 会执行这项变更并显示写入结果。关闭或取消不会修改任何状态。`,"drawer.proposalRecheck":`按最新状态重新检查`,"drawer.proposalRegenerate":`基于最新状态重试`,"drawer.proposalRejected":`已拒绝,这项变更不会写入。`,"drawer.proposalStale":`来源状态已变化,请按最新状态重新检查。`,"drawer.proposalViewGoal":`查看更新后的 Goal`,"drawer.reassign":`改派给`,"drawer.reassignSummary":`重新分配:{task}`,"drawer.reason":`原因`,"drawer.recoveryDescription":`本地历史已经保留,请选择恢复路径。`,"drawer.recoveryFailed":`上游 Session 恢复失败`,"drawer.recoveryNewSession":`携带上下文开始新 Session`,"drawer.recoveryRetry":`重试恢复`,"drawer.repositoryRole":`执行工作区`,"drawer.repository":`仓库`,"drawer.replyMode":`回复方式`,"drawer.subagentApplied":`已写入,并通过共享 Goal 状态读回校验。`,"drawer.subagentAppliedRefreshFailed":`已写入并通过共享 Goal 状态读回;状态投影刷新失败,可稍后手动刷新。`,"drawer.subagentApplying":`正在写入并校验共享状态读回…`,"drawer.subagentApplyFailed":`子代理设置写入失败。`,"drawer.subagentChildLimit":`当前上限`,"drawer.subagentConfirmDisable":`确认关闭子代理执行`,"drawer.subagentConfirmEnable":`确认开启子代理执行`,"drawer.subagentCurrentBoundary":`当前任务领域限制`,"drawer.subagentDescription":`仅在 Todo、配额、能力和写入范围门禁全部通过后,允许运行时为相互独立的任务临时创建子代理;不会强制并行,也不会授予持久权限。`,"drawer.subagentDisable":`预览关闭子代理执行`,"drawer.subagentDisableSummary":`这个 Goal 将不再创建新的子代理;现有 Todo 归属和执行记录不受影响。`,"drawer.subagentDomainInvalid":`所选任务领域限制无效。`,"drawer.subagentDomainTodoCount":`匹配 {count} 个开放 Todo`,"drawer.subagentDomains":`任务领域限制(可选)`,"drawer.subagentDomainsEmpty":`当前没有开放的 advancement Todo 声明 task_domain;保持为空即可不按任务领域限制子代理执行。`,"drawer.subagentDomainsHint":`全部不选表示不按任务领域过滤;选择后只放行匹配且已声明领域的 Todo,其他执行门禁始终生效。`,"drawer.subagentDomainsUnrestricted":`不限制任务领域`,"drawer.subagentEnable":`预览开启子代理执行`,"drawer.subagentLabel":`Per-Goal 执行边界`,"drawer.subagentModel":`子 Agent 模型`,"drawer.subagentEffort":`子 Agent 推理档位`,"drawer.subagentModelDefault":`宿主默认`,"drawer.subagentLunaPreset":`使用 Luna / max`,"drawer.subagentClearModel":`清除模型偏好`,"drawer.subagentModelHint":`填写后通过“预览配置调整”保存,执行关闭时也可保存偏好;启动时须核验宿主支持情况。`,"drawer.subagentModelRequired":`设置推理档位前请先指定子 Agent 模型。`,"drawer.subagentMaxChildren":`最多子代理数`,"drawer.subagentNoChange":`当前 Goal 已是这个设置,没有写入任何内容。`,"drawer.subagentPending":`待确认`,"drawer.subagentPreviewBoundary":`预览配置调整`,"drawer.subagentPreviewFailed":`无法生成子代理设置预览。`,"drawer.subagentPreviewing":`正在核对最新 Goal 状态…`,"drawer.subagentPreviewReady":`预览已锁定,确认后才会写入这个 Goal。`,"drawer.subagentPreviewSummary":`最多允许创建 {count} 个子代理;任务领域限制:{domains}。`,"drawer.subagentRemoteReadOnly":`当前来源只读,请在 Goal 所在主机上修改。`,"drawer.subagentTitle":`自适应子代理执行`,"drawer.remoteDetailsDescription":`SSH 来源只展示公开安全状态,不读取来源主机上的连接配置。`,"drawer.remoteDetailsUnavailable":`远端详情未投影`,"drawer.resumeNo":`否`,"drawer.resumeYes":`是`,"drawer.runDetails":`执行 Session`,"drawer.runInterrupt":`中断本次运行`,"drawer.runLatest":`查看最近执行过程`,"drawer.runNewSession":`开始新 Session`,"drawer.runCloseSession":`关闭 Session`,"drawer.runRecordEmpty":`还没有运行记录。Agent 尚未开始这次执行;请在“详情与操作”查看等待条件或恢复 Session。`,"drawer.runRecordProjected":`当前没有可展示的逐步运行记录。LoopX 已读取到 {completed}/{total} 的投影进度{outputs};请在“详情与操作”检查 Session 状态。`,"drawer.runRecordProjectedOutputs":`和 {count} 项产出`,"drawer.runRoleAssistant":`已完成`,"drawer.runRoleSystem":`需检查`,"drawer.runRoleUser":`收到任务`,"drawer.runView":`Session 视图`,"drawer.scheduleAdd":`添加定时检查`,"drawer.scheduleDefaultNotification":`仅在需要你时通知`,"drawer.scheduleDefaultStop":`Goal 完成或 owner 停止`,"drawer.scheduleDefaultTarget":`由 LoopX 调度器按 Goal 配置唤醒。`,"drawer.scheduleEdit":`改为每 2 小时`,"drawer.scheduleLast":`上次执行`,"drawer.scheduleLocalTimezone":`本地时区`,"drawer.scheduleNext":`下次执行`,"drawer.scheduleNeverRun":`尚未执行`,"drawer.scheduleNotification":`通知`,"drawer.schedulePause":`暂停`,"drawer.schedulePending":`等待调度`,"drawer.scheduleResume":`恢复`,"drawer.scheduleRunNow":`立即运行`,"drawer.scheduleStop":`停止{kind}`,"drawer.scheduleStopCondition":`停止条件`,"drawer.scheduleTimezone":`时区`,"drawer.sessionRecoverable":`可恢复`,"drawer.sessionStatus":`会话状态`,"drawer.setupHeartbeat":`设置 Heartbeat`,"drawer.taskActions":`Todo 待确认操作`,"drawer.taskAdvancement":`推进任务`,"drawer.taskBlock":`标记阻塞`,"drawer.taskComplete":`标记完成`,"drawer.taskCompletedNote":`该任务保留为只读记录。`,"drawer.taskCompletedTitle":`任务已完成`,"drawer.taskDefer":`暂缓`,"drawer.taskDeferCondition":`Todo 暂缓恢复条件`,"drawer.taskDeferInvalid":`条件格式不受支持;请使用下列可判定条件。`,"drawer.taskDeferPlaceholder":`例如 resume_at:2026-09-14T09:00:00+08:00`,"drawer.taskDeferReview":`检查暂缓`,"drawer.taskDeferSupported":`支持 todo_done、pr_merged、capacity_available 与带时区的 resume_at 条件。`,"drawer.taskDeferUntil":`暂缓至`,"drawer.taskDetails":`Todo 详情`,"drawer.taskInfo":`任务信息`,"drawer.taskManage":`管理任务`,"drawer.taskNextCompleted":`可创建后续任务`,"drawer.taskNextOpen":`推进或更新状态`,"drawer.taskOrdinary":`普通任务`,"drawer.taskStatusBlocked":`受阻`,"drawer.taskStatusDeferred":`已延期`,"drawer.resumeWhen":`恢复条件`,"drawer.resumeState":`恢复状态`,"drawer.resumePending":`等待条件满足`,"drawer.resumeReady":`可恢复`,"drawer.resumeReceipt":`恢复回执`,"drawer.taskNextDeferred":`等待恢复条件满足后重新评估`,"drawer.taskNextResumeReady":`恢复条件已满足,等待生命周期重新规划`,"drawer.taskStatusCompleted":`已完成`,"drawer.taskStatusOpen":`待执行`,"drawer.taskSuccessor":`创建后续 Todo`,"drawer.taskSuccessorNote":`Owner 标记为阻塞,等待补充上下文。`,"drawer.taskSuccessorSummary":`创建后续 Todo:{task}`,"drawer.taskSuccessorText":`{task} 的后续工作`,"drawer.taskType":`任务类型`,"drawer.topic":`Topic`,"drawer.trigger":`触发方式`,"drawer.titleAttention":`需要你`,"drawer.titleOutput":`产出详情`,"drawer.titleProposalApplied":`执行结果`,"drawer.titleProposalConfirm":`确认执行`,"drawer.titleSchedule":`定时检查`,"drawer.unconfigured":`未配置`,"drawer.workspaceCandidates":`可选择的工作区`,"files.emptySummary":`公开安全产出`,"files.empty":`还没有文件、产出或已验证的阶段周报。`,"files.loadingReports":`正在加载已验证的阶段周报…`,"files.reportDelta":`+{added} 新增 · {changed} 变化`,"files.reportAdded":`新增`,"files.reportChanged":`变化`,"files.reportGeneration":`生成批次`,"files.reportLoadFailed":`无法加载已验证周报`,"files.reportPublication":`发布批次`,"files.title":`Files & Outputs`,"files.verifiedReport":`已验证阶段周报`,"header.agentUnavailable":`不可用`,"header.chatRuntime":`Chat`,"header.workAgentCount":`{count} 个工作 Agent`,"header.chat":`Chat`,"header.files":`Files`,"header.goalCapabilities":`能力配置`,"header.goalCapabilitiesDescription":`管理 Goal override 与继承的本机默认值。`,"header.goalDetails":`Goal 详情`,"header.goalDetailsDescription":`查看状态、用量、仓库、通知与 Session。`,"header.goalSettings":`Goal 设置`,"header.goalSettingsDescription":`打开 Goal 详情或能力配置`,"header.goalNavigation":`Goal 导航`,"header.goalView":`Goal 视图`,"header.live":`实时`,"header.manager":`LoopX 管家`,"header.managerDescription":`跨 Goal 的个人工作入口`,"header.managerOverview":`总览`,"header.managerView":`管家视图`,"header.openGoalNavigation":`打开 Goal 导航`,"header.readOnlySourceDescription":`{source} 通过 SSH 隧道只读展示`,"header.refresh":`刷新状态`,"header.refreshDone":`刚刚更新`,"header.refreshFailed":`刷新失败`,"header.refreshing":`刷新中`,"header.selectAgent":`选择 Agent`,"header.selectChatRuntime":`选择聊天 Runtime`,"header.tasks":`Tasks`,"header.themeBrutal":`切换到野兽主题`,"header.themePaper":`切换到默认主题`,"home.blockingSummary":`其中 {count} 项正在阻塞 Agent。`,"home.completedGoals":`已完成的 Goal`,"home.empty":`当前没有`,"startup.goalLoading":`正在加载状态…`,"startup.goalError":`状态加载失败`,"startup.progress":`已加载 {loaded} / {total} 个活跃 Goal`,"startup.partial":`Goal 状态正在逐个更新,当前统计尚不完整。`,"startup.independent":`此 Goal 的加载不会阻塞其他 Goal,你可以先查看已加载的内容。`,"startup.error.timeout":`读取超时,可在本地服务就绪后重试。`,"startup.error.network":`连接中断,请重试以重新连接。`,"startup.error.service":`本地服务暂时不可用,请重试继续加载。`,"startup.error.revision":`加载期间 Goal 目录发生变化,请刷新以同步。`,"startup.error.scope":`该 Goal 已不在当前来源中,请刷新目录。`,"startup.error.invalid":`无法解析状态响应,请刷新或检查 LoopX 更新。`,"startup.retry":`重试`,"startup.retryFailed":`重试失败的 Goal`,"startup.failedCount":`{count} 个 Goal 加载失败,已加载的 Goal 可继续使用。`,"home.greeting":`你好,我是 LoopX 管家`,"home.history":`历史`,"home.lane.needsYou":`需要你`,"home.lane.needsYouDescription":`等待你的决定、授权或补充信息`,"home.lane.observing":`观察中`,"home.lane.observingDescription":`持续监控,出现变化时再提醒你`,"home.lane.running":`执行中`,"home.lane.runningDescription":`Agent 正在推进并持续回传进展`,"home.lane.scheduled":`已安排`,"home.lane.scheduledDescription":`已经安排,等待时间或前置条件`,"home.noActivity":`尚无活动`,"home.noFirstActivity":`等待首次活动`,"home.noCompletedGoals":`还没有已完成的 Goal`,"home.preservedState":`保留状态,可随时恢复`,"home.stopped":`已停止`,"home.systemHealth":`系统健康:{summary}`,"home.taskCount":`{count} 个 Task`,"home.todayAt":`今天 {time}`,"home.waitingCount":`你有 {count} 项需要处理。`,"home.workspace":`Goal 工作区`,"lark.allMessages":`此 Topic 中的所有消息`,"lark.allTopicMessages":`所有 Topic 消息`,"lark.agentIngress":`Agent 入站方式`,"lark.agentAppPermissions":`每个选中的 Agent 都需要一个已具备群聊提及和回复能力的 Lark App。`,"lark.agentApps":`每个 Agent 的 Lark App`,"lark.agentAppsDescription":`默认使用上方 App;需要独立机器人身份时,可为 Agent 选择另一个兼容 App。`,"lark.agentAppSelection":`{agent} 的 Lark App`,"lark.appCreated":`App 已创建`,"lark.appCreateFailed":`创建失败`,"lark.appLoading":`正在加载可用的 Lark Apps…`,"lark.appPermissions":`该 App 能发送建联消息,但缺少接收群聊 @ 消息或自动回复所需的机器人权限。请开启 im:message.group_at_msg:readonly、im:message.send_as_bot 和事件 im.message.receive_v1,发布新版后刷新。`,"lark.appProfile":`Lark App`,"lark.apps":`Lark Apps`,"lark.autoReplyUnavailable":`自动回复暂不可用`,"lark.autoReplyReady":`自动回复可用`,"lark.bindGoal":`绑定到 Goal`,"lark.cancel":`取消`,"lark.cardinality":`一个 Lark App · 多个 Goal · 每个 Agent 一条隔离路由`,"lark.capture":`接收范围`,"lark.captureAddressed":`仅接收提及 App 或回复 App 的消息`,"lark.captureAll":`接收此 Goal Topic 中的所有消息`,"lark.captureScope":`接收范围`,"lark.captureScopeDescription":`决定哪些 Topic 消息会进入 LoopX;不会扩大 Agent 权限。`,"lark.closeConnection":`关闭连接弹窗`,"lark.closeCreate":`关闭创建弹窗`,"lark.closeSettings":`关闭 Lark 设置`,"lark.connect":`连接`,"lark.connectAllAgents":`连接全部已注册 Agent`,"lark.connectAllAgentsAction":`一键连接 {count} 个 Agent`,"lark.connectAllAgentsDescription":`一次引导创建 {count} 个隔离的 Agent Topic;请在对应 Topic 内发送请求,每个 Agent 保留独立路由和收件箱。`,"lark.connectApp":`连接 Lark App`,"lark.connection":`连接`,"lark.connections":`连接`,"lark.configuration":`Lark 配置`,"lark.continueFeishu":`在飞书中继续`,"lark.createAutomatically":`自动创建 Goal Topic`,"lark.createAutomaticallyDescription":`将为每个选中的 Agent 创建带 Agent 标识的专属 Topic。`,"lark.defaultAgentAppDescription":`用于查找目标群聊,并作为所有选中 Agent 的默认 App;下方的逐 Agent 选择可覆盖它。`,"lark.description":`管理可复用的 Lark App,并用独立 Topic 将群聊连接到 Goal。`,"lark.editConnection":`编辑 Lark 连接`,"lark.goalConnections":`{count} 个 Goal 连接`,"lark.goalTopicConnections":`Lark Goal Topic 连接`,"lark.groupChat":`群聊`,"lark.groupEmpty":`该机器人尚未加入可连接的群。请先在飞书群设置中添加这个机器人,再回来刷新或搜索。`,"lark.groupLoading":`正在读取该机器人已加入的群…`,"lark.groupSearch":`搜索该机器人已加入的群`,"lark.historyPermission":`历史补读权限(独立能力)`,"lark.health.eventProcessed":`已处理 {events} 条事件,成功回复 {replies} 条。`,"lark.health.eventUnverified":`事件订阅待验证`,"lark.health.eventUnverifiedDetail":`Provider listener 已就绪,但尚未收到消息事件。请启用 im.message.receive_v1、开通群聊 @ 消息权限并发布新版,然后在这个 Agent Topic 内发送新的 @ 消息;存在多条 Agent 路由时,群顶层消息会 fail closed。`,"lark.health.ignoredSelf":`已忽略机器人自身发送的消息,避免重复回复。`,"lark.health.invalidRouting":`路由配置无效`,"lark.health.invalidRoutingDetail":`连接已安全停用,请重新选择处理方式并保存。`,"lark.health.lastStatus":`最近事件状态:{status}`,"lark.health.listening":`监听中`,"lark.health.messageContextPermission":`消息权限不足`,"lark.health.messageContextPermissionDetail":`已收到消息事件,但无法读取群消息上下文。请发布并授权该 App 的群消息读取权限。`,"lark.health.notAddressed":`最近消息未直接 @ 机器人`,"lark.health.notAddressedDetail":`监听正常;当前连接只响应直接 @ 机器人或对机器人的回复。`,"lark.health.notStarted":`监听未启动`,"lark.health.notStartedDetail":`请刷新连接或重新启动 LoopX 后再试。`,"lark.health.processingFailed":`消息处理失败`,"lark.health.processingFailedDetail":`已收到消息事件,但 Agent 处理失败。请查看本地诊断后重试。`,"lark.health.queued":`已进入 Agent 收件箱`,"lark.health.queuedDetail":`消息由 {agent} 异步处理,不会启动通用 Chat Session。`,"lark.health.sourceDisconnected":`实时消息连接断开`,"lark.health.sourceDisconnectedDetail":`消息监听进程意外退出。请核对应用档案的平台:飞书应用选飞书,国际版 Lark 应用选 Lark,再检查连接及订阅错误。LoopX 正在重试;历史消息能读取,不代表能实时收消息。`,"lark.health.retrying":`监听重试中`,"lark.health.retryingDetail":`事件监听暂时中断,LoopX 正在自动重试。`,"lark.health.routeAmbiguous":`消息匹配多个 Goal`,"lark.health.routeAmbiguousDetail":`同一 Bot 和群聊存在多个完整群捕获连接。请让每个 Agent 使用独立 Bot,或只保留一个完整群连接。`,"lark.health.routeMismatch":`消息未匹配当前 Goal Topic`,"lark.health.routeMismatchDetail":`事件来自其他群聊或 Topic。请重新选择群聊并连接该 Goal,然后发送一条新的 @ 消息。`,"lark.health.routeUnavailable":`消息无法路由到 Goal`,"lark.health.routeUnavailableDetail":`当前连接信息不完整。请重新连接该 Goal 后再发送一条新的 @ 消息。`,"lark.health.starting":`正在启动`,"lark.health.startingDetail":`LoopX 正在启动该 App 的消息事件监听。`,"lark.health.unavailable":`自动回复不可用`,"lark.health.waiting":`等待处理`,"lark.incomingMessages":`接收消息`,"lark.ingressAsync":`异步收件箱`,"lark.ingressAsyncDescription":`写入 Agent 私有收件箱,等待后续显式处理。`,"lark.editPreservesIdentity":`保存会保留此 App、群和 Topic;旧连接默认升级为 Agent 异步收件箱。`,"lark.conversationKind":`连接用途`,"lark.managerConversation":`管家 · 同步对话`,"lark.workerConversation":`工作 Agent · 后台任务`,"lark.managerConversationDescription":`内置管家即时回应对话,长任务交给后台 Agent。群聊与私聊分别保存上下文。`,"lark.ingressLegacy":`待升级`,"lark.ingressLegacyDescription":`保存连接即可升级为 Agent 异步收件箱,已有消息保留在原 Topic 中。`,"lark.ingressQueue":`排队`,"lark.ingressQueueDescription":`进入同一 Agent Session 的有界 FIFO 队列,当前 Turn 完成后处理。`,"lark.ingressSteering":`实时引导`,"lark.ingressSteeringDescription":`投到当前活跃 Turn;没有精确活跃 Turn 时安全拒绝。`,"lark.loading":`加载 Lark 配置…`,"lark.management":`Lark 管理`,"lark.openEventSettings":`查看飞书事件配置`,"lark.mentions":`提及机器人`,"lark.mentionsOnly":`仅提及消息`,"lark.needsMessagePermissions":`需要消息权限`,"lark.needsSetup":`需要设置`,"lark.newApp":`新建 Lark App`,"lark.noAgentConfigured":`未配置 Agent`,"lark.noConnections":`暂无匹配的连接。`,"lark.noProfiles":`还没有可用的 lark-cli App profile。`,"lark.profileName":`Profile 名称`,"lark.profileValidation":`Profile 只能包含字母、数字、点、下划线和连字符。`,"lark.processing":`处理方式`,"lark.region":`区域`,"lark.registerAnother":`+ 注册另一个 Lark App — 通过飞书创建`,"lark.reopenFeishu":`重新打开飞书`,"lark.settingsConfigure":`配置 {goal}`,"lark.settingsDisconnect":`解绑 {goal}`,"lark.replyMode":`回复方式`,"lark.replyModeDescription":`当前只支持在来源 Topic 内回复,避免跨群或跨 Goal 投递。`,"lark.reusableApps":`{count} 个可复用 App`,"lark.reusableWorkspaceApp":`可复用工作区 App`,"lark.routesUnverified":`{count} 条 Lark 路由尚未验证`,"lark.saveConnection":`保存连接`,"lark.searchConnections":`搜索 Lark 连接`,"lark.searchPlaceholder":`搜索 App、群、Goal 或 Topic`,"lark.setupCopy":`LoopX 将通过 lark-cli 打开飞书官方创建页面。应用凭证保存在系统 Keychain,LoopX 只保留 profile 引用。`,"lark.someoneMentions":`有人提及 Agent`,"lark.targetAgent":`目标 Agent`,"lark.targetAgentDescription":`选择该 Goal 内已注册的 Agent。此连接只投递给一个 Agent,不广播、不授予新权限。实时引导与排队需要该 Agent 的精确活跃 Session。`,"lark.agentUnavailable":`{agent} · 已不可用`,"lark.selectRegisteredAgent":`请先选择可用的已注册 Agent;不会自动替换原先的接收者。`,"lark.topicPreview":`Topic 预览`,"lark.topicReply":`Topic 回复`,"lark.trigger":`触发方式`,"lark.waitingFeishu":`等待飞书完成创建`,"lark.waitingFeishuDescription":`请在新窗口中完成飞书授权,完成后会自动回到这里。`,"lark.waitingLink":`正在生成飞书官方创建链接…`,"lark.error.appCreate":`Lark App 创建失败`,"lark.error.appRequired":`请选择一个 Lark App profile。`,"lark.error.bind":`绑定失败`,"lark.error.bindPreview":`绑定预览失败`,"lark.error.configuration":`Lark 配置加载失败`,"lark.error.groupLookup":`无法读取该机器人已加入的群。请检查机器人状态后重试。`,"lark.error.groupLoad":`群聊加载失败`,"lark.error.invalidApp":`Lark App profile 不可用或尚未完成授权。`,"lark.error.messagePermissions":`该 App 缺少自动回复所需的机器人权限。请开启 im:message.group_at_msg:readonly 和 im:message:send_as_bot,发布新版后回来刷新重试。`,"lark.error.provider":`飞书 API 调用失败,且没有生成已验证回执。请稍后重试。`,"lark.error.setupPoll":`创建状态查询失败`,"lark.error.setupStart":`无法启动 Lark App 创建流程`,"lark.error.cliExecutable":`已找到配置的 lark-cli,但当前无法执行。请检查安装或启动参数。`,"lark.error.cliMissing":`未发现 lark-cli。请先安装 lark-cli,然后重新启动 LoopX。`,"lark.error.cliStart":`lark-cli 启动失败。请检查安装状态,然后重新启动 LoopX。`,"lark.error.disconnect":`解绑失败`,"notifications.autoNotify":`需要你确认时自动推送到群里`,"notifications.bind":`绑定到通知群`,"notifications.bindConfirm":`将把「{goal}」绑定到通知群「{target}」,绑定时会验证机器人在群内并发送一条确认消息。`,"notifications.bindFailed":`绑定失败`,"notifications.bound":`已绑定`,"notifications.confirmBind":`确认绑定`,"notifications.description":`把 Goal 里需要你确认的变更推送到飞书群。绑定和开关在这里完成,推送逻辑沿用现有通道。`,"notifications.disabled":`已停用`,"notifications.group":`通知群:{target}`,"notifications.loadFailed":`通知群列表加载失败`,"notifications.noTargets":`还没有可用的通知群。通知群涉及机器人私有身份,请先在终端配置一次:`,"notifications.notBound":`未绑定`,"notifications.recent":`最近 {time}`,"notifications.sentCount":`已发送 {count} 条`,"notifications.settings":`Goal 通知绑定`,"notifications.setupFailed":`设置失败`,"notifications.title":`飞书群通知`,"proposal.field.agentId":`Agent`,"proposal.field.cadence":`频率`,"proposal.field.completionCriteria":`完成标准`,"proposal.field.executionBoundary":`执行边界`,"proposal.field.goalId":`Goal ID`,"proposal.field.heartbeat":`Heartbeat`,"proposal.field.initialTodos":`首个任务`,"proposal.field.objective":`目标`,"proposal.field.operation":`操作`,"proposal.field.permission":`权限`,"proposal.field.reason":`原因`,"proposal.field.stopCondition":`停止条件`,"proposal.field.target":`检查内容`,"proposal.field.timezone":`时区`,"proposal.field.title":`标题`,"proposal.field.workspace":`执行工作区`,"actionReview.targetChanged":`预览目标与请求的 Goal 或操作不一致,请重新生成预览。`,"actionReview.ready_stop":`暂停可恢复。此预览已通过检查,可直接执行;完成仍需要读回验证。`,"actionReview.resume_review":`恢复自动调度前需要确认。实际执行仍受额度、Gate 和 Todo 约束。`,"actionReview.delete_review":`请确认从注册表移除这个已停止 Goal。项目文件与历史记录会保留。`,"actionReview.action_review":`执行前请检查此提案的目标与影响。`,"actionReview.protected_action":`此操作需要明确审阅。确认不能替代所需授权。`,"actionReview.unknown_permission":`无法识别权限分类。请重新检查提案后再继续。`,"actionReview.unknown_action":`无法识别此生命周期操作。请重新检查提案后再继续。`,"actionReview.incomplete_proposal":`预览缺少验证信息或可执行转换。请重新生成预览。`,"actionReview.authority_gate":`Gate 阻止执行。请满足其要求后重新检查提案。`,"actionReview.stale_proposal":`来源状态已变化。请重新生成预览,原决定不再适用。`,"actionReview.apply_pending":`正在执行,请等待读回结果后再重试。`,"actionReview.readback_verified":`操作已完成,结果状态已通过读回验证。`,"actionReview.readback_unverified":`操作返回但未通过读回验证。尚不能确认完成,请重新检查状态。`,"actionReview.apply_failed":`执行未完成。请检查失败原因并重新生成预览后再试。`,"actionReview.inactive_proposal":`此提案当前不可执行。请重新检查后再继续。`,"proposal.gate.default":`需要宿主确认`,"proposal.impact.default":`确认后会调用规范 LoopX 服务写入状态。`,"proposal.impact.goalCreate":`确认后会创建 Goal 和首个 Todo,并让选定 Agent 开始首轮推进。`,"proposal.impact.lifecycleDelete":`确认后会从 source registry 和 global registry 移除这个已停止 Goal;项目文件、历史状态文件和备份不会被删除。`,"proposal.impact.lifecycleResume":`确认后会恢复 Goal 的自动调度资格并移回 Active Goals;实际执行仍受 quota、Gate 和 Todo 约束。`,"proposal.impact.lifecycleStop":`确认后会停止自动推进,并将 Goal 移入折叠的「已停止」列表;历史、Todo 和证据都会保留,可随时恢复。`,"proposal.impact.protected":`该操作需要通过受保护的 LoopX 写入服务完成。`,"proposal.primary.apply":`确认并应用`,"proposal.primary.goalCreate":`创建 Goal 并开始首轮`,"proposal.primary.lifecycleDelete":`删除 Goal`,"proposal.primary.lifecycleResume":`恢复 Goal`,"proposal.primary.lifecycleStop":`停止 Goal`,"proposal.primary.todoStart":`创建任务并开始执行`,"proposal.summary.goalCreate":`创建 Goal:{title}`,"proposal.summary.heartbeat":`为当前 Goal 设置 Heartbeat`,"proposal.summary.lifecycleDelete":`删除 Goal:{title}`,"proposal.summary.lifecycleResume":`恢复 Goal:{title}`,"proposal.summary.lifecycleStop":`停止 Goal:{title}`,"proposal.summary.monitor":`为当前 Goal 创建定时检查:{target}`,"proposal.workspace.current":`当前本地工作区(未绑定 Repository)`,"proposal.workspace.named":`{workspace}(仅提供执行环境,不会自动关联仓库)`,"proposal.workspaceGate.agentImpact":`先完成 Agent 身份绑定,再重新检查原操作;当前没有写入 Goal。`,"proposal.workspaceGate.agentTitle":`先绑定 Agent`,"proposal.workspaceGate.defaultSummary":`请选择 Goal 所属工作区。`,"proposal.workspaceGate.selectionImpact":`选择工作区后会重新展示待确认操作,选择本身不会写入状态。`,"proposal.workspaceGate.selectionTitle":`选择 Goal 工作区`,"projection.agentAdvancingGoal":`Agent 正在推进当前 Goal`,"projection.agentIdle":`暂无需要你处理`,"projection.agentNeedsDecision":`Agent 等待你的决定`,"projection.agentPreparingNextStep":`Agent 正在整理下一步`,"projection.agentStopped":`已由你停止;历史、Todo 和证据仍保留`,"projection.agentWaitingExternal":`正在等待外部条件`,"projection.confirmAgentDecision":`请确认 Agent 下一步需要的权限或决策`,"projection.events24h":`24 小时内 {count} 个事件`,"projection.firstReadOnlyAdapterCheck":`执行首次只读适配检查并保存进度`,"projection.goalVerified":`Goal 状态、Todo 与注册信息已验证`,"projection.latestRun":`最近运行`,"projection.latestValidation":`最近验证`,"projection.nextUpdatePending":`等待 LoopX 更新下一步`,"projection.publicSafeProjection":`公开安全状态投影`,"projection.refreshState":`刷新 LoopX 状态,确认当前进度仍然有效`,"projection.runEvidenceAvailable":`存在可查看的运行证据`,"projection.runRecorded":`最近一次 LoopX 运行已经记录`,"projection.statusRefreshNeeded":`LoopX 状态需要刷新`,"projection.todoStatusUpdated":`Todo 状态已经更新,正在确认下一步`,"projection.validationRecorded":`最近验证已经记录`,"runs.completed":`已完成`,"runs.failed":`需检查`,"runs.interrupted":`已中断`,"runs.queued":`已安排`,"runs.ready":`可继续`,"runs.resumeFailed":`恢复失败`,"runs.running":`执行中`,"runs.unknown":`状态未知`,"runs.waiting":`等待条件`,"schedule.active":`执行中`,"schedule.heartbeat":`Goal Heartbeat`,"schedule.monitor":`定时与持续任务`,"schedule.paused":`已暂停`,"schedule.summary":`按 LoopX 调度约束持续检查`,"schedule.defaultTarget":`检查当前 Goal 的阻塞、进度与新产出`,"schedule.unsupportedCalendar":`当前定时检查不支持精确到星期或时刻的日历计划。请改用固定间隔,例如“每 30 分钟”“每 2 小时”或“每天”;草稿已保留,没有生成待确认操作。`,"source.add":`添加来源`,"source.addConfigured":`添加只读来源`,"source.addMethod":`来源添加方式`,"source.addSsh":`添加 SSH 隧道来源`,"source.closeForm":`关闭来源表单`,"source.configured":`已配置 SSH`,"source.configuredCount":`本机 SSH Host · {count} 个`,"source.configuredGroup":`已配置 SSH Host · {count}(点击快速添加)`,"source.connected":`已连接`,"source.connecting":`连接中`,"source.controlPlane":`控制面来源`,"source.copy":`复制`,"source.copyCommand":`复制 SSH 隧道命令`,"source.copyError":`无法复制命令,请手动复制下方命令。`,"source.copied":`已复制`,"source.description":`已读取全部显式 Host(含 Include);通配规则不会作为具体来源。先运行命令,LoopX 不读取密钥或配置细节。`,"source.host":`本机 SSH Host`,"source.hostEmpty":`~/.ssh/config 中没有可直接选择的显式 Host。`,"source.hostLoadError":`无法读取本机 SSH Host。`,"source.hostPlaceholder":`输入或搜索 Host`,"source.invalid":`SSH 来源参数无效。`,"source.loadingHosts":`正在读取…`,"source.localInteractive":`本机交互`,"source.localPort":`本地端口`,"source.manual":`手动 URL`,"source.manualDescription":`远端来源始终按只读投影处理,不继承本机写权限。`,"source.name":`名称`,"source.namePlaceholder":`远程开发机`,"source.notAvailable":`不可用`,"source.readOnly":`SSH 隧道 · 只读`,"source.readOnlyNoticeDescription":`你可以查看 Goal、Task、证据与运行状态;写入、纠偏和 Agent 会话仍留在来源主机。`,"source.readOnlyNoticeTitle":`远端只读投影`,"source.readOnlyWriteError":`远端 SSH 隧道来源是只读投影,不能执行控制面写入。`,"source.refreshHosts":`重新读取 SSH Host`,"source.remove":`移除来源 {source}`,"source.removeCurrent":`移除当前来源`,"source.select":`选择控制面来源`,"source.selectHost":`请选择已配置的 SSH Host。`,"source.statusUrl":`本地转发 URL`,"source.tunnelCommandPending":`选择 Host 后生成隧道命令`,"machine.absent":`尚未配置`,"machine.action.create":`创建机器策略`,"machine.action.delete":`移除机器策略`,"machine.action.unchanged":`无需写入`,"machine.action.update":`更新机器策略`,"machine.applied":`机器策略已应用,并通过回读校验。`,"machine.applyError":`无法应用机器策略。`,"machine.applyPreview":`应用已审阅预览`,"machine.changedNamespaces":`变更的 Namespace`,"machine.capabilityCatalog":`机器能力目录`,"machine.capabilityEmpty":`当前没有注册可在机器作用域配置的能力。`,"machine.configured":`已配置`,"machine.confirmRollback":`确认回滚`,"machine.currentRevision":`当前 Revision`,"machine.currentValue":`当前机器值`,"machine.description":`与 Goal 设置共用能力目录。在这里管理受支持的机器默认值;仅支持 Goal 配置的能力会明确标注。`,"capabilities.rawJson":`高级:原始 JSON`,"machine.goalOnly":`此能力目前仅支持 Goal 级配置。请打开具体 Goal 的能力设置进行配置;这里不会设置机器级默认值。`,"machine.desiredRevision":`目标 Revision`,"machine.editorUnavailable":`当前版本未安装此 Namespace 的编辑器`,"machine.editorUnavailableDescription":`它仍会显示在 Registry 中;安装或升级对应的 Dashboard 编辑器后才能修改。`,"machine.editorMode":`编辑模式`,"machine.liveDefault":`实时默认值;Goal 显式覆盖优先`,"machine.liveDefaultDescription":`没有显式覆盖的 Goal 会在该能力下一次决策时读取当前机器策略。修改或移除策略会立即影响这些已有 Goal;显式 Goal 覆盖保持固定。`,"machine.genericNamespaceDescription":`使用 JSON 编辑这个已注册 Namespace。LoopX 会先按 capability 自己拥有的 schema 校验,再允许预览写入。`,"machine.jsonConfiguration":`Namespace 配置(JSON)`,"machine.jsonConfigurationHelp":`只更新当前 Namespace;其他机器配置会保留,Apply 仍锁定到已审阅的 Preview Revision。`,"machine.jsonEditor":`JSON`,"machine.editJson":`编辑 JSON`,"capabilities.jsonConfiguration":`Goal 配置(JSON)`,"capabilities.jsonHelp":`仅编辑当前 Goal 的已注册字段。修改后需重新预览才能应用。`,"capabilities.jsonInvalid":`请输入合法的 JSON 对象,且仅包含已注册的可编辑字段。`,"machine.backToForm":`返回表单`,"machine.jsonInvalid":`请先填写一个合法的 JSON object,再预览变更。`,"machine.loadError":`无法读取机器配置。`,"machine.machinePolicy":`机器策略`,"machine.namespaceCount":`已注册 Namespace`,"machine.namespaces":`配置 Namespace`,"machine.periodicReport":`周期报告`,"machine.periodicReportDescription":`为所有未显式覆盖的 Goal 提供默认报告策略;Goal 调度与发送消费解析后的有效配置。`,"machine.periodicReportActivation":`开启后将在已验证的阶段节点自动投递`,"machine.periodicReportActivationDescription":`这不是每周定时器。当 LoopX 验证 Goal 已完成一个阶段时,Agent 会生成并冻结报告,随后通过配置的 Goal Channel 自动发送。启用此订阅即授予持续投递权;发送失败或路由漂移会 fail closed 并进入修复。`,"machine.changeQualityActivation":`质量验证是质量门禁,不是新增授权`,"machine.changeQualityActivationDescription":`继承该策略的 Goal 会验证最终精确 diff。safe_fix 只允许在既有写入权限内执行至多一次有界修复;此设置不会授予文件、权限或合并权。`,"machine.replanCadenceActivation":`复核周期只改变时机,不改变执行权限`,"machine.replanCadenceActivationDescription":`没有显式覆盖的 Goal 会在下一次复核决策前读取此阈值;它不会创建 Turn、消耗配额或授予权限。`,"machine.preview":`审阅机器配置变更`,"machine.previewChanges":`预览变更`,"machine.previewError":`无法生成机器策略预览。`,"machine.previewLocked":`应用操作锁定到当前 Revision;若机器状态变化,LoopX 会要求重新预览。`,"machine.previewRollback":`预览回滚`,"machine.previewRemoval":`预览移除`,"machine.profilePreset":`Profile preset`,"machine.profilePresetHelp":`由 capability 管理的 preset,例如 weekly-progress。`,"machine.registry":`Typed Registry`,"machine.requiredFields":`开启后必须填写 profile preset、Goal Channel route 与有效时区。`,"machine.revision":`机器 Revision`,"machine.revisionLockedReady":`所有变更必须先预览;只有对应的机器 Revision 仍然有效时才会应用。`,"machine.rollbackAvailable":`可回滚上一次应用`,"machine.rollbackDescription":`先预览已保存的前一 Revision,再决定是否恢复。`,"machine.rollbackError":`无法完成回滚。`,"machine.rollbackPreviewDescription":`前一 Revision 已准备恢复,请确认执行本次回滚。`,"machine.rolledBack":`已恢复前一版机器策略,并通过校验。`,"machine.removed":`机器策略已移除,并通过回读校验。`,"machine.routeRef":`Goal Channel route`,"machine.routeRefHelp":`只填写公开 route alias;凭据与 provider identifier 不会进入此表单。`,"machine.timezone":`时区`,"machine.timezoneHelp":`填写 IANA 时区,例如 Asia/Shanghai。`,"machine.title":`机器配置`,"machine.unchanged":`机器策略已与预览一致,本次没有写入。`,"machine.visualEditor":`引导式`,"capabilities.atomicOverride":`Goal override 按完整配置生效`,"capabilities.atomicOverrideDescription":`Goal 的完整配置优先于机器默认值;LoopX 不会在两个作用域之间逐字段拼接。`,"capabilities.applyFailed":`Goal 能力变更未写入。`,"capabilities.applyPreview":`应用此预览`,"capabilities.catalog":`Goal 能力目录`,"capabilities.chooseGoal":`请先选择一个 Goal,再查看它的能力配置。`,"capabilities.defaultValue":`声明的默认值`,"capabilities.description":`查看当前 Goal 可用的能力,以及每项配置的准确作用域。`,"capabilities.editorPrepared":`已注册 typed editor contract`,"capabilities.effectiveSource":`当前生效来源`,"capabilities.empty":`当前 Goal 没有可用的能力描述。`,"capabilities.fields":`已注册字段`,"capabilities.goalPolicy":`Goal 能力策略`,"capabilities.goalScope":`Goal`,"capabilities.goalValue":`当前 Goal 值`,"capabilities.loadFailed":`无法加载 Goal 能力`,"capabilities.loading":`正在加载 Goal 能力…`,"capabilities.machineOnly":`此能力只能在机器作用域配置。`,"capabilities.machineValue":`实时机器默认值`,"capabilities.machineScope":`机器`,"capabilities.previewOnly":`当前读取结果来自真实配置;在 revision-locked preview/apply 路径接通前,Dashboard 不会提供 Goal 写入控件。`,"capabilities.preview":`锁定 revision 的变更预览`,"capabilities.previewChanges":`预览变更`,"capabilities.restoreInheritance":`恢复继承机器默认值`,"capabilities.previewFailed":`无法预览 Goal 能力变更。`,"capabilities.previewLocked":`应用时会重新校验这一个 plan revision;过期变更将被拒绝。`,"capabilities.partialWrite":`Goal 值已保存;共享投影仍需修复`,"capabilities.partialWriteDescription":`源 Goal 配置已经写入并回读,但共享 runtime 投影尚未同步;请勿重复提交本次变更。`,"capabilities.refreshSource":`刷新源配置`,"capabilities.readOnly":`只读能力`,"capabilities.revisionLockedReady":`所有变更必须先预览;只有对应的精确 revision 仍然有效时才会写入。`,"capabilities.retry":`重试`,"capabilities.source.capability_default":`能力默认值`,"capabilities.source.goal_override":`Goal override`,"capabilities.source.machine_default":`实时机器默认值`,"capabilities.source.not_configured":`未配置`,"capabilities.title":`Goal 能力`,"settings.close":`关闭设置`,"settings.appearance":`外观`,"settings.appearanceDescription":`管理当前浏览器里的工作区显示偏好。`,"settings.appearanceTabDescription":`主题和显示偏好`,"settings.capabilitiesTabDescription":`当前 Goal 的能力覆盖配置`,"settings.back":`返回工作区`,"settings.categories":`设置分类`,"settings.description":`管理工作区偏好与集成。`,"settings.eyebrow":`工作区偏好`,"settings.general":`通用`,"settings.goalConnections":`Goal 连接`,"settings.language":`语言`,"settings.languageDescription":`选择 LoopX Desktop 工作区使用的界面语言。`,"settings.languageEnglishDescription":`使用英文显示导航、设置和工作区控件。`,"settings.languageEnglish":`English`,"settings.languageSimplifiedChineseDescription":`使用简体中文显示导航、设置和工作区控件。`,"settings.languageSimplifiedChinese":`简体中文`,"settings.languageStoredLocally":`此偏好仅保存在当前设备。`,"settings.languageTabDescription":`当前设备的界面语言`,"settings.larkTabDescription":`App、群聊和 Goal Topic 连接`,"settings.machineTabDescription":`本机各 Capability 共享的 typed defaults`,"settings.notifications":`通知`,"settings.open":`设置`,"settings.themeDefault":`纸张`,"settings.themeDefaultDescription":`安静、轻量,适合长期查看。`,"settings.themeDescription":`选择工作区的视觉风格。设置会保存在当前浏览器本地。`,"settings.themeHighContrast":`高对比`,"settings.themeHighContrastDescription":`更强边框和更醒目的状态块。`,"settings.themeLoopx":`LoopX 标准`,"settings.themeLoopxDescription":`精确的黑白界面、Geist 字体与安静的细线结构。`,"settings.title":`设置`,"settings.workspaceDisplay":`工作区显示`,"settings.workspaceTheme":`工作区主题`,"session.closeRecord":`退出运行记录`,"session.details":`Session 详情`,"session.record":`执行 Session · 运行记录`,"session.recordDescription":`当前时间线已切换到这次 Session 的消息与 Turn 记录。`,"sidebar.createGoal":`创建 Goal`,"sidebar.delete":`删除`,"sidebar.deleteGoal":`删除 Goal`,"sidebar.manager":`LoopX 管家`,"sidebar.notifications":`设置`,"sidebar.owner":`个人工作区`,"sidebar.product":`个人 Agent 工作区`,"sidebar.resume":`恢复`,"sidebar.resumeGoal":`恢复 Goal`,"sidebar.stop":`停止`,"tasks.historyLoading":`正在加载历史…`,"tasks.historyError":`历史加载失败,已显示的内容仍可查看。`,"tasks.historyExpired":`历史快照已过期,重新加载后可继续查看。`,"tasks.historyRetry":`重新加载`,"tasks.historyEnd":`已显示全部完成记录`,"tasks.historyMore":`加载更多`,"tasks.historyLocalOnly":`请打开这台机器的 Dashboard 查看完整历史。`,"sidebar.sortGoals":`调整 Goal 顺序`,"sidebar.dragGoal":`拖拽调整顺序,或使用列表排序按钮`,"sidebar.moveUp":`上移 {goal}`,"sidebar.moveDown":`下移 {goal}`,"sidebar.goalMoved":`{goal} 已移至第 {position} 位`,"sidebar.orderNotSaved":`顺序已在本次页面生效;浏览器存储不可用,无法保存。`,"sidebar.stopGoal":`停止 Goal`,"sidebar.stopped":`已停止`,"sidebar.stoppedLoading":`正在加载已停止 Goal`,"sidebar.stoppedLoadFailed":`已停止 Goal 加载失败,其他 Goal 仍可使用。`,"sidebar.retryStopped":`重试`,"state.completed":`已完成`,"state.needsRepair":`需修复`,"state.needsYou":`等你`,"state.quiet":`安静运行`,"state.running":`推进中`,"state.stopped":`已停止`,"state.waiting":`等待条件`,"tasks.blocked":`受阻`,"tasks.agentLane":`工作 Agent`,"tasks.agentLaneDescription":`筛选这个 Goal 下的工作泳道`,"tasks.agentLaneFilter":`按工作 Agent 筛选`,"tasks.allAgentLanes":`全部 Agent({count})`,"tasks.chatAgentReplied":`Agent 已回复`,"tasks.chatPending":`已发送给 Agent`,"tasks.chatPendingDescription":`正在处理;只有经过确认的任务操作才会更新 Tasks。`,"tasks.chatRecent":`最近对话`,"tasks.chatUnchangedDescription":`本次对话没有直接修改 Tasks。需要执行时,可先转成 Task 草稿并确认。`,"tasks.chatViewReply":`查看回复`,"tasks.convertToTask":`转为 Task`,"tasks.completed":`已完成`,"runs.discoveryPartial":`部分执行详情暂不可用,正在重连;任务摘要不代表实时执行状态。`,"runs.discoveryOffline":`执行服务暂不可用,正在重连;保留的任务摘要可能已过时。`,"files.openConversation":`前往会话`,"files.exportSummary":`导出摘要`,"tasks.viewDescription":`先处理待确认,再查看工作与完成记录`,"tasks.viewLabel":`任务视图`,"tasks.listView":`列表`,"tasks.boardView":`看板`,"tasks.completedSummary":`已完成 {count} 项,近期完成明细由控制面按需投影。`,"tasks.emptyCompleted":`还没有完成的任务。`,"tasks.emptyConfirm":`没有待确认的任务。`,"tasks.emptyRunning":`没有待执行或进行中的任务。`,"tasks.emptySchedules":`没有定时任务。`,"tasks.emptyGoal":`这个 Goal 还没有任务。用下面的输入框描述下一步,LoopX 会先展示待确认操作。`,"tasks.markComplete":`标记完成:{name}`,"tasks.moreActions":`更多操作:{name}`,"tasks.openExecution":`查看执行过程:{name}`,"tasks.pending":`待处理`,"tasks.pendingAndRunning":`待执行 / 进行中`,"tasks.scheduled":`定时与持续`,"tasks.sessionError":`Session 异常`,"tasks.waiting":`待执行`,"tasks.waitingAge":`已等待 {age}`,"tasks.viewExecution":`查看执行过程`,"tasks.viewResult":`查看结果`,"time.days":`{count} 天`,"time.hours":`{count} 小时`,"timeline.emptyGoal":`这个 Goal 还没有新动态`,"timeline.emptyGoalDescription":`你可以直接询问进度或下发新的纠偏信息。`,"timeline.emptyWorkspace":`今天的工作区很安静`,"timeline.emptyWorkspaceDescription":`向 LoopX 管家描述一个 Goal,或询问今天最值得关注的事情。`,"timeline.gateHistory":`{count} 项历史 Gate`,"timeline.pending":`正在整理…`,"timeline.runCompleted":`{run}:已完成`,"timeline.review":`查看处理方式`,"timeline.reviewAndConfirm":`查看并确认`,"timeline.waitingConfirmation":`待你确认`}};function Wi(e,t){return t?Object.entries(t).reduce((e,[t,n])=>e.replaceAll(`{${t}}`,String(n)),e):e}function Gi(){try{return window.localStorage.getItem(`loopx-pw-locale`)===`en`?`en`:`zh-CN`}catch{return`zh-CN`}}function Ki({children:e}){let[t,n]=(0,B.useState)(Gi);function r(e){n(e);try{window.localStorage.setItem(Hi,e)}catch{}}(0,B.useEffect)(()=>{document.documentElement.lang=t},[t]);let i=(0,B.useMemo)(()=>({locale:t,setLocale:r,t:(e,n)=>Wi(Ui[t][e],n)}),[t]);return(0,V.jsx)(Vi.Provider,{value:i,children:e})}function qi(){let e=(0,B.useContext)(Vi);if(!e)throw Error(`useWorkspaceI18n must be used within WorkspaceI18nProvider`);return e}function Ji(e,t){let n={安静运行:`state.quiet`,等你:`state.needsYou`,等待条件:`state.waiting`,推进中:`state.running`,需修复:`state.needsRepair`,已完成:`state.completed`,已停止:`state.stopped`}[e];return n?Ui[t][n]:e}function Yi(e,t){let n={busy:`runs.running`,completed:`runs.completed`,failed:`runs.failed`,queued:`runs.queued`,ready:`runs.ready`,resume_failed:`runs.resumeFailed`,running:`runs.running`,waiting:`runs.waiting`};return e?n[e]?t(n[e]):e:t(`runs.unknown`)}function Xi(e,t){if(!e)return null;let n=new Date(e).getTime();if(Number.isNaN(n))return null;let r=Date.now()-n;if(r<36e5)return null;let i=Math.floor(r/864e5);return i>=1?t(`time.days`,{count:i}):t(`time.hours`,{count:Math.floor(r/36e5)})}var Zi;function U(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;en?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var Qi=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},$i=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Zi=globalThis).__zod_globalConfig??(Zi.__zod_globalConfig={});var ea=globalThis.__zod_globalConfig;function ta(e){return e&&Object.assign(ea,e),ea}function na(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function ra(e,t){return typeof t==`bigint`?t.toString():t}function ia(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function aa(e){return e==null}function oa(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function sa(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r){};function ha(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ga=ia(()=>{if(ea.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function _a(e){if(ha(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return ha(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function va(e){return _a(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var ya=new Set([`string`,`number`,`symbol`]);function ba(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function xa(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function W(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Sa(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var Ca={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function wa(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return xa(e,da(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return ua(this,`shape`,e),e},checks:[]}))}function Ta(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return xa(e,da(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return ua(this,`shape`,r),r},checks:[]}))}function Ea(e,t){if(!_a(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return xa(e,da(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return ua(this,`shape`,n),n}}))}function Da(e,t){if(!_a(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return xa(e,da(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return ua(this,`shape`,n),n}}))}function Oa(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return xa(e,da(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return ua(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function ka(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return xa(t,da(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return ua(this,`shape`,i),i},checks:[]}))}function Aa(e,t,n){return xa(t,da(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return ua(this,`shape`,i),i}}))}function ja(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Pa(e){return typeof e==`string`?e:e?.message}function Fa(e,t,n){let r=e.message?e.message:Pa(e.inst?._zod.def?.error?.(e))??Pa(t?.error?.(e))??Pa(n.customError?.(e))??Pa(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function Ia(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function La(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var Ra=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ra,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},za=U(`$ZodError`,Ra),Ba=U(`$ZodError`,Ra,{Parent:Error});function Va(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ha(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Qi;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Fa(e,a,ta())));throw ma(t,i?.callee),t}return o.value},Wa=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Fa(e,a,ta())));throw ma(t,i?.callee),t}return o.value},Ga=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Qi;return a.issues.length?{success:!1,error:new(e??za)(a.issues.map(e=>Fa(e,i,ta())))}:{success:!0,data:a.value}},Ka=Ga(Ba),qa=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>Fa(e,i,ta())))}:{success:!0,data:a.value}},Ja=qa(Ba),Ya=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ua(e)(t,n,i)},Xa=e=>(t,n,r)=>Ua(e)(t,n,r),Za=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Wa(e)(t,n,i)},Qa=e=>async(t,n,r)=>Wa(e)(t,n,r),$a=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ga(e)(t,n,i)},eo=e=>(t,n,r)=>Ga(e)(t,n,r),to=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return qa(e)(t,n,i)},no=e=>async(t,n,r)=>qa(e)(t,n,r),ro=/^[cC][0-9a-z]{6,}$/,io=/^[0-9a-z]+$/,ao=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,oo=/^[0-9a-vA-V]{20}$/,so=/^[A-Za-z0-9]{27}$/,co=/^[a-zA-Z0-9_-]{21}$/,lo=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,uo=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,fo=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,po=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,mo=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function ho(){return new RegExp(mo,`u`)}var go=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_o=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,vo=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,yo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bo=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,xo=/^[A-Za-z0-9_-]*$/,So=/^https?$/,Co=/^\+[1-9]\d{6,14}$/,wo=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,To=RegExp(`^${wo}$`);function Eo(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Do(e){return RegExp(`^${Eo(e)}$`)}function Oo(e){let t=Eo({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${wo}T(?:${r})$`)}var ko=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Ao=/^-?\d+$/,jo=/^-?\d+(?:\.\d+)?$/,Mo=/^(?:true|false)$/i,No=/^null$/i,Po=/^[^A-Z]*$/,Fo=/^[^a-z]*$/,Io=U(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Lo={number:`number`,bigint:`bigint`,object:`date`},Ro=U(`$ZodCheckLessThan`,(e,t)=>{Io.init(e,t);let n=Lo[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value{(t.inclusive?r.value<=t.value:r.value{Io.init(e,t);let n=Lo[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Bo=U(`$ZodCheckMultipleOf`,(e,t)=>{Io.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):sa(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Vo=U(`$ZodCheckNumberFormat`,(e,t)=>{Io.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Ca[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=Ao)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}sa&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Ho=U(`$ZodCheckMaxLength`,(e,t)=>{var n;Io.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!aa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum{let r=n.value;if(r.length<=t.maximum)return;let i=Ia(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Uo=U(`$ZodCheckMinLength`,(e,t)=>{var n;Io.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!aa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=Ia(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Wo=U(`$ZodCheckLengthEquals`,(e,t)=>{var n;Io.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!aa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=Ia(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Go=U(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Io.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Ko=U(`$ZodCheckRegex`,(e,t)=>{Go.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),qo=U(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Po,Go.init(e,t)}),Jo=U(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Fo,Go.init(e,t)}),Yo=U(`$ZodCheckIncludes`,(e,t)=>{Io.init(e,t);let n=ba(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Xo=U(`$ZodCheckStartsWith`,(e,t)=>{Io.init(e,t);let n=RegExp(`^${ba(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Zo=U(`$ZodCheckEndsWith`,(e,t)=>{Io.init(e,t);let n=RegExp(`.*${ba(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Qo=U(`$ZodCheckOverwrite`,(e,t)=>{Io.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),$o=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(` -`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(` -`))}},es={major:4,minor:4,patch:3},ts=U(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=es;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=ja(e),i;for(let a of t){if(a._zod.def.when){if(Ma(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new Qi;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=ja(e,t))});else{if(e.issues.length===t)continue;r||=ja(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(ja(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new Qi;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new Qi;return o.then(e=>t(e,r,a))}return t(o,r,a)}}la(e,`~standard`,()=>({validate:t=>{try{let n=Ka(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Ja(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),ns=U(`$ZodString`,(e,t)=>{ts.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ko(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),rs=U(`$ZodStringFormat`,(e,t)=>{Go.init(e,t),ns.init(e,t)}),is=U(`$ZodGUID`,(e,t)=>{t.pattern??=uo,rs.init(e,t)}),as=U(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=fo(e)}else t.pattern??=fo();rs.init(e,t)}),os=U(`$ZodEmail`,(e,t)=>{t.pattern??=po,rs.init(e,t)}),ss=U(`$ZodURL`,(e,t)=>{rs.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===So.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),n.value=t.normalize?i.href:r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),cs=U(`$ZodEmoji`,(e,t)=>{t.pattern??=ho(),rs.init(e,t)}),ls=U(`$ZodNanoID`,(e,t)=>{t.pattern??=co,rs.init(e,t)}),us=U(`$ZodCUID`,(e,t)=>{t.pattern??=ro,rs.init(e,t)}),ds=U(`$ZodCUID2`,(e,t)=>{t.pattern??=io,rs.init(e,t)}),fs=U(`$ZodULID`,(e,t)=>{t.pattern??=ao,rs.init(e,t)}),ps=U(`$ZodXID`,(e,t)=>{t.pattern??=oo,rs.init(e,t)}),ms=U(`$ZodKSUID`,(e,t)=>{t.pattern??=so,rs.init(e,t)}),hs=U(`$ZodISODateTime`,(e,t)=>{t.pattern??=Oo(t),rs.init(e,t)}),gs=U(`$ZodISODate`,(e,t)=>{t.pattern??=To,rs.init(e,t)}),_s=U(`$ZodISOTime`,(e,t)=>{t.pattern??=Do(t),rs.init(e,t)}),vs=U(`$ZodISODuration`,(e,t)=>{t.pattern??=lo,rs.init(e,t)}),ys=U(`$ZodIPv4`,(e,t)=>{t.pattern??=go,rs.init(e,t),e._zod.bag.format=`ipv4`}),bs=U(`$ZodIPv6`,(e,t)=>{t.pattern??=_o,rs.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),xs=U(`$ZodCIDRv4`,(e,t)=>{t.pattern??=vo,rs.init(e,t)}),Ss=U(`$ZodCIDRv6`,(e,t)=>{t.pattern??=yo,rs.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function Cs(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var ws=U(`$ZodBase64`,(e,t)=>{t.pattern??=bo,rs.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{Cs(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Ts(e){if(!xo.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Cs(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var Es=U(`$ZodBase64URL`,(e,t)=>{t.pattern??=xo,rs.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Ts(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Ds=U(`$ZodE164`,(e,t)=>{t.pattern??=Co,rs.init(e,t)});function Os(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var ks=U(`$ZodJWT`,(e,t)=>{rs.init(e,t),e._zod.check=n=>{Os(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),As=U(`$ZodNumber`,(e,t)=>{ts.init(e,t),e._zod.pattern=e._zod.bag.pattern??jo,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),js=U(`$ZodNumberFormat`,(e,t)=>{Vo.init(e,t),As.init(e,t)}),Ms=U(`$ZodBoolean`,(e,t)=>{ts.init(e,t),e._zod.pattern=Mo,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Ns=U(`$ZodNull`,(e,t)=>{ts.init(e,t),e._zod.pattern=No,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),Ps=U(`$ZodUnknown`,(e,t)=>{ts.init(e,t),e._zod.parse=e=>e}),Fs=U(`$ZodNever`,(e,t)=>{ts.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Is(e,t,n){e.issues.length&&t.issues.push(...Na(n,e.issues)),t.value[n]=e.value}var Ls=U(`$ZodArray`,(e,t)=>{ts.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;eIs(t,n,e))):Is(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function Rs(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...Na(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function zs(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Sa(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Bs(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Rs(e,n,i,t,u,d))):Rs(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var Vs=U(`$ZodObject`,(e,t)=>{if(ts.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=ia(()=>zs(t));la(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=ha,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>Rs(n,t,e,s,r,i))):Rs(a,t,e,s,r,i)}return i?Bs(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Hs=U(`$ZodObjectJIT`,(e,t)=>{Vs.init(e,t);let n=e._zod.parse,r=ia(()=>zs(t)),i=e=>{let t=new $o([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=fa(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=fa(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(` - if (${n}.issues.length) { - if (${o} in input) { - payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${o}, ...iss.path] : [${o}] - }))); - } - } - - if (${n}.value === undefined) { - if (${o} in input) { - newResult[${o}] = undefined; - } - } else { - newResult[${o}] = ${n}.value; - } - - `):c?t.write(` - if (${n}.issues.length) { - payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${o}, ...iss.path] : [${o}] - }))); - } - - if (${n}.value === undefined) { - if (${o} in input) { - newResult[${o}] = undefined; - } - } else { - newResult[${o}] = ${n}.value; - } - - `):t.write(` - const ${n}_present = ${o} in input; - if (${n}.issues.length) { - payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${o}, ...iss.path] : [${o}] - }))); - } - if (!${n}_present && !${n}.issues.length) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [${o}] - }); - } - - if (${n}_present) { - if (${n}.value === undefined) { - newResult[${o}] = undefined; - } else { - newResult[${o}] = ${n}.value; - } - } - - `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=ha,s=!ea.jitless,c=s&&ga.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?Bs([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function Us(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!ja(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Fa(e,r,ta())))}),t)}var Ws=U(`$ZodUnion`,(e,t)=>{ts.init(e,t),la(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),la(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),la(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),la(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>oa(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Us(t,r,e,i)):Us(o,r,e,i)}}),Gs=U(`$ZodIntersection`,(e,t)=>{ts.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>qs(e,t,n)):qs(e,i,a)}});function Ks(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(_a(e)&&_a(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Ks(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;re.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),ja(e))return e;let o=Ks(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var Js=U(`$ZodTuple`,(e,t)=>{ts.init(e,t);let n=t.items;e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({input:a,inst:e,expected:`tuple`,code:`invalid_type`}),r;r.value=[];let o=[],s=Ys(n,`optin`),c=Ys(n,`optout`);if(!t.rest){if(a.lengthn.length&&r.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:a,inst:e,origin:`array`})}let l=Array(n.length);for(let e=0;e{l[e]=t})):l[e]=t}if(t.rest){let e=n.length-1,s=a.slice(n.length);for(let n of s){e++;let a=t.rest._zod.run({value:n,issues:[]},i);a instanceof Promise?o.push(a.then(t=>Xs(t,r,e))):Xs(a,r,e)}}return o.length?Promise.all(o).then(()=>Zs(l,r,n,a,c)):Zs(l,r,n,a,c)}});function Ys(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!==`optional`)return n+1;return 0}function Xs(e,t,n){e.issues.length&&t.issues.push(...Na(n,e.issues)),t.value[n]=e.value}function Zs(e,t,n,r,i){for(let a=0;a=i){t.value.length=a;break}t.issues.push(...Na(a,n.issues))}t.value[a]=n.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}var Qs=U(`$ZodRecord`,(e,t)=>{ts.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!_a(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>Fa(e,r,ta())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...Na(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...Na(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&jo.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Fa(e,r,ta())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...Na(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...Na(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),$s=U(`$ZodEnum`,(e,t)=>{ts.init(e,t);let n=na(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>ya.has(typeof e)).map(e=>typeof e==`string`?ba(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),ec=U(`$ZodLiteral`,(e,t)=>{if(ts.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?ba(e):e?ba(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),tc=U(`$ZodTransform`,(e,t)=>{ts.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $i(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new Qi;return n.value=i,n.fallback=!0,n}});function nc(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var rc=U(`$ZodOptional`,(e,t)=>{ts.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,la(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),la(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${oa(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>nc(e,r)):nc(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),ic=U(`$ZodExactOptional`,(e,t)=>{rc.init(e,t),la(e._zod,`values`,()=>t.innerType._zod.values),la(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),ac=U(`$ZodNullable`,(e,t)=>{ts.init(e,t),la(e._zod,`optin`,()=>t.innerType._zod.optin),la(e._zod,`optout`,()=>t.innerType._zod.optout),la(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${oa(e.source)}|null)$`):void 0}),la(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),oc=U(`$ZodDefault`,(e,t)=>{ts.init(e,t),e._zod.optin=`optional`,la(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>sc(e,t)):sc(r,t)}});function sc(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var cc=U(`$ZodPrefault`,(e,t)=>{ts.init(e,t),e._zod.optin=`optional`,la(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),lc=U(`$ZodNonOptional`,(e,t)=>{ts.init(e,t),la(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>uc(t,e)):uc(i,e)}});function uc(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var dc=U(`$ZodCatch`,(e,t)=>{ts.init(e,t),e._zod.optin=`optional`,la(e._zod,`optout`,()=>t.innerType._zod.optout),la(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Fa(e,n,ta()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Fa(e,n,ta()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),fc=U(`$ZodPipe`,(e,t)=>{ts.init(e,t),la(e._zod,`values`,()=>t.in._zod.values),la(e._zod,`optin`,()=>t.in._zod.optin),la(e._zod,`optout`,()=>t.out._zod.optout),la(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>pc(e,t.in,n)):pc(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>pc(e,t.out,n)):pc(r,t.out,n)}});function pc(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var mc=U(`$ZodReadonly`,(e,t)=>{ts.init(e,t),la(e._zod,`propValues`,()=>t.innerType._zod.propValues),la(e._zod,`values`,()=>t.innerType._zod.values),la(e._zod,`optin`,()=>t.innerType?._zod?.optin),la(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(hc):hc(r)}});function hc(e){return e.value=Object.freeze(e.value),e}var gc=U(`$ZodCustom`,(e,t)=>{Io.init(e,t),ts.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>_c(t,n,r,e));_c(i,n,r,e)}});function _c(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(La(e))}}var vc,yc=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function bc(){return new yc}(vc=globalThis).__zod_globalRegistry??(vc.__zod_globalRegistry=bc());var xc=globalThis.__zod_globalRegistry;function Sc(e,t){return new e({type:`string`,...W(t)})}function Cc(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...W(t)})}function wc(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...W(t)})}function Tc(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...W(t)})}function Ec(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...W(t)})}function Dc(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...W(t)})}function Oc(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...W(t)})}function kc(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...W(t)})}function Ac(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...W(t)})}function jc(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...W(t)})}function Mc(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...W(t)})}function Nc(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...W(t)})}function Pc(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...W(t)})}function Fc(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...W(t)})}function Ic(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...W(t)})}function Lc(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...W(t)})}function Rc(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...W(t)})}function zc(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...W(t)})}function Bc(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...W(t)})}function Vc(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...W(t)})}function Hc(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...W(t)})}function Uc(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...W(t)})}function Wc(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...W(t)})}function Gc(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...W(t)})}function Kc(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...W(t)})}function qc(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...W(t)})}function Jc(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...W(t)})}function Yc(e,t){return new e({type:`number`,checks:[],...W(t)})}function Xc(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...W(t)})}function Zc(e,t){return new e({type:`boolean`,...W(t)})}function Qc(e,t){return new e({type:`null`,...W(t)})}function $c(e){return new e({type:`unknown`})}function el(e,t){return new e({type:`never`,...W(t)})}function tl(e,t){return new Ro({check:`less_than`,...W(t),value:e,inclusive:!1})}function nl(e,t){return new Ro({check:`less_than`,...W(t),value:e,inclusive:!0})}function rl(e,t){return new zo({check:`greater_than`,...W(t),value:e,inclusive:!1})}function il(e,t){return new zo({check:`greater_than`,...W(t),value:e,inclusive:!0})}function al(e,t){return new Bo({check:`multiple_of`,...W(t),value:e})}function ol(e,t){return new Ho({check:`max_length`,...W(t),maximum:e})}function sl(e,t){return new Uo({check:`min_length`,...W(t),minimum:e})}function cl(e,t){return new Wo({check:`length_equals`,...W(t),length:e})}function ll(e,t){return new Ko({check:`string_format`,format:`regex`,...W(t),pattern:e})}function ul(e){return new qo({check:`string_format`,format:`lowercase`,...W(e)})}function dl(e){return new Jo({check:`string_format`,format:`uppercase`,...W(e)})}function fl(e,t){return new Yo({check:`string_format`,format:`includes`,...W(t),includes:e})}function pl(e,t){return new Xo({check:`string_format`,format:`starts_with`,...W(t),prefix:e})}function ml(e,t){return new Zo({check:`string_format`,format:`ends_with`,...W(t),suffix:e})}function hl(e){return new Qo({check:`overwrite`,tx:e})}function gl(e){return hl(t=>t.normalize(e))}function _l(){return hl(e=>e.trim())}function vl(){return hl(e=>e.toLowerCase())}function yl(){return hl(e=>e.toUpperCase())}function bl(){return hl(e=>pa(e))}function xl(e,t,n){return new e({type:`array`,element:t,...W(n)})}function Sl(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...W(n)})}function Cl(e,t){let n=wl(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(La(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(La(r))}},e(t.value,t)),t);return n}function wl(e,t){let n=new Io({check:`custom`,...W(t)});return n._zod.check=e,n}function Tl(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??xc,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function El(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,El(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&kl(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Dl(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/ - -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function Ol(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:jl(t,`input`,e.processors),output:jl(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function kl(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return kl(r.element,n);if(r.type===`set`)return kl(r.valueType,n);if(r.type===`lazy`)return kl(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return kl(r.innerType,n);if(r.type===`intersection`)return kl(r.left,n)||kl(r.right,n);if(r.type===`record`||r.type===`map`)return kl(r.keyType,n)||kl(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:kl(r.in,n)||kl(r.out,n);if(r.type===`object`){for(let e in r.shape)if(kl(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(kl(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(kl(e,n))return!0;return!!(r.rest&&kl(r.rest,n))}return!1}var Al=(e,t={})=>n=>{let r=Tl({...n,processors:t});return El(e,r),Dl(r,e),Ol(r,e)},jl=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Tl({...i??{},target:a,io:t,processors:n});return El(e,o),Dl(o,e),Ol(o,e)},Ml={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Nl=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Ml[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Pl=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},Fl=(e,t,n,r)=>{n.type=`boolean`},Il=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Ll=(e,t,n,r)=>{n.not={}},Rl=(e,t,n,r)=>{let i=e._zod.def,a=na(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},zl=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Bl=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Vl=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Hl=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=El(a.element,t,{...r,path:[...r.path,`items`]})},Ul=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=El(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=El(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Wl=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>El(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Gl=(e,t,n,r)=>{let i=e._zod.def,a=El(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=El(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},Kl=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>El(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?El(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},ql=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=El(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=El(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=El(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},Jl=(e,t,n,r)=>{let i=e._zod.def,a=El(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Yl=(e,t,n,r)=>{let i=e._zod.def;El(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Xl=(e,t,n,r)=>{let i=e._zod.def;El(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Zl=(e,t,n,r)=>{let i=e._zod.def;El(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Ql=(e,t,n,r)=>{let i=e._zod.def;El(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},$l=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;El(o,t,r);let s=t.seen.get(e);s.ref=o},eu=(e,t,n,r)=>{let i=e._zod.def;El(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},tu=(e,t,n,r)=>{let i=e._zod.def;El(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},nu=U(`ZodISODateTime`,(e,t)=>{hs.init(e,t),Au.init(e,t)});function ru(e){return Gc(nu,e)}var iu=U(`ZodISODate`,(e,t)=>{gs.init(e,t),Au.init(e,t)});function au(e){return Kc(iu,e)}var ou=U(`ZodISOTime`,(e,t)=>{_s.init(e,t),Au.init(e,t)});function su(e){return qc(ou,e)}var cu=U(`ZodISODuration`,(e,t)=>{vs.init(e,t),Au.init(e,t)});function lu(e){return Jc(cu,e)}var uu=(e,t)=>{za.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Ha(e,t)},flatten:{value:t=>Va(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,ra,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,ra,2)}},isEmpty:{get(){return e.issues.length===0}}})},du=U(`ZodError`,uu),fu=U(`ZodError`,uu,{Parent:Error}),pu=Ua(fu),mu=Wa(fu),hu=Ga(fu),gu=qa(fu),_u=Ya(fu),vu=Xa(fu),yu=Za(fu),bu=Qa(fu),xu=$a(fu),Su=eo(fu),Cu=to(fu),wu=no(fu),Tu=new WeakMap;function Eu(e,t,n){let r=Object.getPrototypeOf(e),i=Tu.get(r);if(i||(i=new Set,Tu.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var Du=U(`ZodType`,(e,t)=>(ts.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:jl(e,`input`),output:jl(e,`output`)}}),e.toJSONSchema=Al(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>pu(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>hu(e,t,n),e.parseAsync=async(t,n)=>mu(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>gu(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>_u(e,t,n),e.decode=(t,n)=>vu(e,t,n),e.encodeAsync=async(t,n)=>yu(e,t,n),e.decodeAsync=async(t,n)=>bu(e,t,n),e.safeEncode=(t,n)=>xu(e,t,n),e.safeDecode=(t,n)=>Su(e,t,n),e.safeEncodeAsync=async(t,n)=>Cu(e,t,n),e.safeDecodeAsync=async(t,n)=>wu(e,t,n),Eu(e,`ZodType`,{check(...e){let t=this.def;return this.clone(da(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return xa(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Bd(e,t))},superRefine(e,t){return this.check(Vd(e,t))},overwrite(e){return this.check(hl(e))},optional(){return Sd(this)},exactOptional(){return wd(this)},nullable(){return Ed(this)},nullish(){return Sd(Ed(this))},nonoptional(e){return Md(this,e)},array(){return J(this)},or(e){return ld([this,e])},and(e){return dd(this,e)},transform(e){return Id(this,bd(e))},default(e){return Od(this,e)},prefault(e){return Ad(this,e)},catch(e){return Pd(this,e)},pipe(e){return Id(this,e)},readonly(){return Rd(this)},describe(e){let t=this.clone();return xc.add(t,{description:e}),t},meta(...e){if(e.length===0)return xc.get(this);let t=this.clone();return xc.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return xc.get(e)?.description},configurable:!0}),e)),Ou=U(`_ZodString`,(e,t)=>{ns.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Nl(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Eu(e,`_ZodString`,{regex(...e){return this.check(ll(...e))},includes(...e){return this.check(fl(...e))},startsWith(...e){return this.check(pl(...e))},endsWith(...e){return this.check(ml(...e))},min(...e){return this.check(sl(...e))},max(...e){return this.check(ol(...e))},length(...e){return this.check(cl(...e))},nonempty(...e){return this.check(sl(1,...e))},lowercase(e){return this.check(ul(e))},uppercase(e){return this.check(dl(e))},trim(){return this.check(_l())},normalize(...e){return this.check(gl(...e))},toLowerCase(){return this.check(vl())},toUpperCase(){return this.check(yl())},slugify(){return this.check(bl())}})}),ku=U(`ZodString`,(e,t)=>{ns.init(e,t),Ou.init(e,t),e.email=t=>e.check(Cc(ju,t)),e.url=t=>e.check(kc(Pu,t)),e.jwt=t=>e.check(Wc(Yu,t)),e.emoji=t=>e.check(Ac(Fu,t)),e.guid=t=>e.check(wc(Mu,t)),e.uuid=t=>e.check(Tc(Nu,t)),e.uuidv4=t=>e.check(Ec(Nu,t)),e.uuidv6=t=>e.check(Dc(Nu,t)),e.uuidv7=t=>e.check(Oc(Nu,t)),e.nanoid=t=>e.check(jc(Iu,t)),e.guid=t=>e.check(wc(Mu,t)),e.cuid=t=>e.check(Mc(Lu,t)),e.cuid2=t=>e.check(Nc(Ru,t)),e.ulid=t=>e.check(Pc(zu,t)),e.base64=t=>e.check(Vc(Ku,t)),e.base64url=t=>e.check(Hc(qu,t)),e.xid=t=>e.check(Fc(Bu,t)),e.ksuid=t=>e.check(Ic(Vu,t)),e.ipv4=t=>e.check(Lc(Hu,t)),e.ipv6=t=>e.check(Rc(Uu,t)),e.cidrv4=t=>e.check(zc(Wu,t)),e.cidrv6=t=>e.check(Bc(Gu,t)),e.e164=t=>e.check(Uc(Ju,t)),e.datetime=t=>e.check(ru(t)),e.date=t=>e.check(au(t)),e.time=t=>e.check(su(t)),e.duration=t=>e.check(lu(t))});function G(e){return Sc(ku,e)}var Au=U(`ZodStringFormat`,(e,t)=>{rs.init(e,t),Ou.init(e,t)}),ju=U(`ZodEmail`,(e,t)=>{os.init(e,t),Au.init(e,t)}),Mu=U(`ZodGUID`,(e,t)=>{is.init(e,t),Au.init(e,t)}),Nu=U(`ZodUUID`,(e,t)=>{as.init(e,t),Au.init(e,t)}),Pu=U(`ZodURL`,(e,t)=>{ss.init(e,t),Au.init(e,t)}),Fu=U(`ZodEmoji`,(e,t)=>{cs.init(e,t),Au.init(e,t)}),Iu=U(`ZodNanoID`,(e,t)=>{ls.init(e,t),Au.init(e,t)}),Lu=U(`ZodCUID`,(e,t)=>{us.init(e,t),Au.init(e,t)}),Ru=U(`ZodCUID2`,(e,t)=>{ds.init(e,t),Au.init(e,t)}),zu=U(`ZodULID`,(e,t)=>{fs.init(e,t),Au.init(e,t)}),Bu=U(`ZodXID`,(e,t)=>{ps.init(e,t),Au.init(e,t)}),Vu=U(`ZodKSUID`,(e,t)=>{ms.init(e,t),Au.init(e,t)}),Hu=U(`ZodIPv4`,(e,t)=>{ys.init(e,t),Au.init(e,t)}),Uu=U(`ZodIPv6`,(e,t)=>{bs.init(e,t),Au.init(e,t)}),Wu=U(`ZodCIDRv4`,(e,t)=>{xs.init(e,t),Au.init(e,t)}),Gu=U(`ZodCIDRv6`,(e,t)=>{Ss.init(e,t),Au.init(e,t)}),Ku=U(`ZodBase64`,(e,t)=>{ws.init(e,t),Au.init(e,t)}),qu=U(`ZodBase64URL`,(e,t)=>{Es.init(e,t),Au.init(e,t)}),Ju=U(`ZodE164`,(e,t)=>{Ds.init(e,t),Au.init(e,t)}),Yu=U(`ZodJWT`,(e,t)=>{ks.init(e,t),Au.init(e,t)}),Xu=U(`ZodNumber`,(e,t)=>{As.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pl(e,t,n,r),Eu(e,`ZodNumber`,{gt(e,t){return this.check(rl(e,t))},gte(e,t){return this.check(il(e,t))},min(e,t){return this.check(il(e,t))},lt(e,t){return this.check(tl(e,t))},lte(e,t){return this.check(nl(e,t))},max(e,t){return this.check(nl(e,t))},int(e){return this.check(Qu(e))},safe(e){return this.check(Qu(e))},positive(e){return this.check(rl(0,e))},nonnegative(e){return this.check(il(0,e))},negative(e){return this.check(tl(0,e))},nonpositive(e){return this.check(nl(0,e))},multipleOf(e,t){return this.check(al(e,t))},step(e,t){return this.check(al(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function K(e){return Yc(Xu,e)}var Zu=U(`ZodNumberFormat`,(e,t)=>{js.init(e,t),Xu.init(e,t)});function Qu(e){return Xc(Zu,e)}var $u=U(`ZodBoolean`,(e,t)=>{Ms.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fl(e,t,n,r)});function q(e){return Zc($u,e)}var ed=U(`ZodNull`,(e,t)=>{Ns.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Il(e,t,n,r)});function td(e){return Qc(ed,e)}var nd=U(`ZodUnknown`,(e,t)=>{Ps.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function rd(){return $c(nd)}var id=U(`ZodNever`,(e,t)=>{Fs.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ll(e,t,n,r)});function ad(e){return el(id,e)}var od=U(`ZodArray`,(e,t)=>{Ls.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hl(e,t,n,r),e.element=t.element,Eu(e,`ZodArray`,{min(e,t){return this.check(sl(e,t))},nonempty(e){return this.check(sl(1,e))},max(e,t){return this.check(ol(e,t))},length(e,t){return this.check(cl(e,t))},unwrap(){return this.element}})});function J(e,t){return xl(od,e,t)}var sd=U(`ZodObject`,(e,t)=>{Hs.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ul(e,t,n,r),la(e,`shape`,()=>t.shape),Eu(e,`ZodObject`,{keyof(){return _d(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:rd()})},loose(){return this.clone({...this._zod.def,catchall:rd()})},strict(){return this.clone({...this._zod.def,catchall:ad()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Ea(this,e)},safeExtend(e){return Da(this,e)},merge(e){return Oa(this,e)},pick(e){return wa(this,e)},omit(e){return Ta(this,e)},partial(...e){return ka(xd,this,e[0])},required(...e){return Aa(jd,this,e[0])}})});function Y(e,t){return new sd({type:`object`,shape:e??{},...W(t)})}var cd=U(`ZodUnion`,(e,t)=>{Ws.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wl(e,t,n,r),e.options=t.options});function ld(e,t){return new cd({type:`union`,options:e,...W(t)})}var ud=U(`ZodIntersection`,(e,t)=>{Gs.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gl(e,t,n,r)});function dd(e,t){return new ud({type:`intersection`,left:e,right:t})}var fd=U(`ZodTuple`,(e,t)=>{Js.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kl(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function pd(e,t,n){let r=t instanceof ts;return new fd({type:`tuple`,items:e,rest:r?t:null,...W(r?n:t)})}var md=U(`ZodRecord`,(e,t)=>{Qs.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ql(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function hd(e,t,n){return!t||!t._zod?new md({type:`record`,keyType:G(),valueType:e,...W(t)}):new md({type:`record`,keyType:e,valueType:t,...W(n)})}var gd=U(`ZodEnum`,(e,t)=>{$s.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rl(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new gd({...t,checks:[],...W(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new gd({...t,checks:[],...W(r),entries:i})}});function _d(e,t){return new gd({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...W(t)})}var vd=U(`ZodLiteral`,(e,t)=>{ec.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zl(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function X(e,t){return new vd({type:`literal`,values:Array.isArray(e)?e:[e],...W(t)})}var yd=U(`ZodTransform`,(e,t)=>{tc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vl(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $i(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(La(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(La(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function bd(e){return new yd({type:`transform`,transform:e})}var xd=U(`ZodOptional`,(e,t)=>{rc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>tu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Sd(e){return new xd({type:`optional`,innerType:e})}var Cd=U(`ZodExactOptional`,(e,t)=>{ic.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>tu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wd(e){return new Cd({type:`optional`,innerType:e})}var Td=U(`ZodNullable`,(e,t)=>{ac.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ed(e){return new Td({type:`nullable`,innerType:e})}var Dd=U(`ZodDefault`,(e,t)=>{oc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Od(e,t){return new Dd({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():va(t)}})}var kd=U(`ZodPrefault`,(e,t)=>{cc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ad(e,t){return new kd({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():va(t)}})}var jd=U(`ZodNonOptional`,(e,t)=>{lc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Md(e,t){return new jd({type:`nonoptional`,innerType:e,...W(t)})}var Nd=U(`ZodCatch`,(e,t)=>{dc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ql(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Pd(e,t){return new Nd({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var Fd=U(`ZodPipe`,(e,t)=>{fc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$l(e,t,n,r),e.in=t.in,e.out=t.out});function Id(e,t){return new Fd({type:`pipe`,in:e,out:t})}var Ld=U(`ZodReadonly`,(e,t)=>{mc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>eu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Rd(e){return new Ld({type:`readonly`,innerType:e})}var zd=U(`ZodCustom`,(e,t)=>{gc.init(e,t),Du.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bl(e,t,n,r)});function Bd(e,t={}){return Sl(zd,e,t)}function Vd(e,t){return Cl(e,t)}var Hd=e=>typeof e==`string`&&e.trim()?e.trim():null;function Ud(e){let t=e.decision_scope&&typeof e.decision_scope==`object`&&!Array.isArray(e.decision_scope)?e.decision_scope:{},n=Hd(t.kind),r=Hd(t.granularity),i=Hd(t.scope_key),a=Hd(e.superseded_by);return{interaction:e.task_class===`user_gate`?`decision`:`unknown`,lifecycle:a?`superseded`:e.status===`deferred`?`deferred`:e.done===!0||[`done`,`completed`,`closed`,`archived`].includes(String(e.status))?`closed`:e.status===`open`||e.status===`blocked`?`open`:`unknown`,reason:Hd(e.note),evidence:Hd(e.evidence),blocksAgent:Hd(e.blocks_agent),unblocksTodoId:Hd(e.unblocks_todo_id),decisionScope:n&&r&&i?{kind:n,granularity:r,scopeKey:i}:null,supersededBy:a}}function Wd(e,t,n,r){return{...e,sourceId:t,goalTitle:r??e.goalTitle,details:n?e.details:{...e.details??Ud({}),lifecycle:`unavailable`}}}function Gd(e,t){return t.find(t=>t.sourceId===e.sourceId&&t.goalId===e.goalId&&t.todoId===e.todoId)||{...e,details:{...e.details??Ud({}),lifecycle:`unavailable`}}}function Kd(e,t){let n=e.details?.supersededBy;if(!(!n||n===e.todoId||e.details?.lifecycle===`unavailable`))return t.find(t=>t.sourceId===e.sourceId&&t.goalId===e.goalId&&t.todoId===n)}function qd(e){return![`closed`,`deferred`,`superseded`,`unavailable`].includes(e.details?.lifecycle??`unknown`)}var Jd={ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,runtime_root:`$HOME/.codex/loopx`,goal_count:1,run_count:8440,status_contract:{schema_version:2,minimum_dashboard_schema_version:2,producer:`loopx status`,reload_hint:`scripts/macos-dashboard-launchagent.sh restart`},usage_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.471166+00:00`,sample_run_count:20,proxy_note:`run-history proxy; excludes token counts and raw thread logs`,totals:{runs_24h:20,runs_7d:20,quota_spend_slots_24h:11,quota_spend_slots_7d:11,automation_run_count_24h:11,automation_run_count_7d:11,progress_signal_run_count_24h:9,progress_signal_run_count_7d:9},goals:[{goal_id:`loopx-meta`,runs_24h:20,runs_7d:20,quota_spend_slots_24h:11,quota_spend_slots_7d:11,automation_run_count_24h:11,automation_run_count_7d:11,progress_signal_run_count_24h:9,progress_signal_run_count_7d:9,project_share_24h:1}]},event_ledger_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.360662+00:00`,sample_run_count:20,proxy_note:`append-only run-history projection; compact event-class counts only`,event_classes:[`accounting`,`decision`,`evidence`,`state`,`work`],totals:{events_24h:20,events_7d:20,by_class_24h:{accounting:11,decision:0,evidence:0,state:0,work:9},by_class_7d:{accounting:11,decision:0,evidence:0,state:0,work:9}},goals:[{goal_id:`loopx-meta`,events_24h:20,events_7d:20,by_class_24h:{accounting:11,decision:0,evidence:0,state:0,work:9},by_class_7d:{accounting:11,decision:0,evidence:0,state:0,work:9},latest_event_class:`accounting`,latest_event_at:`2026-07-06T14:37:32+08:00`}]},promotion_readiness_summary:{available:!0,source:`run_history_full_scan`,goal_id:`loopx-meta`,generated_at:`2026-07-05T20:02:02+08:00`,classification:`canary_promotion_readiness_smoke_group`,delivery_batch_scale:`multi_surface`,delivery_outcome:`primary_goal_outcome`,recommended_action:`Canary promotion-readiness smoke passed; promotion may proceed after doctor/status reports fresh evidence.`,json_exists:!0,markdown_exists:!0,freshness_window_hours:24,freshness_status:`fresh`,is_fresh:!0,requires_readiness_run:!1,age_seconds:67624,age_hours:18.78,freshness_reference_time:`2026-07-06T06:49:06.408527+00:00`,sample_run_count:0,proxy_note:`canary promotion-readiness projection from append-only run history; exact evidence stays in run artifacts`},promotion_gate:{ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,runtime_root:`$HOME/.codex/loopx`,gate:`promotion_readiness`,gate_state:`ready`,can_promote:!0,should_warn:!1,non_blocking:!0,recommended_action:`promotion readiness is fresh`,readiness:{available:!0,goal_id:`loopx-meta`,generated_at:`2026-07-05T20:02:02+08:00`,classification:`canary_promotion_readiness_smoke_group`,delivery_batch_scale:`multi_surface`,delivery_outcome:`primary_goal_outcome`,recommended_action:`Canary promotion-readiness smoke passed; promotion may proceed after doctor/status reports fresh evidence.`,json_exists:!0,markdown_exists:!0,runtime_root:`$HOME/.codex/loopx`,freshness_window_hours:24,freshness_status:`fresh`,is_fresh:!0,requires_readiness_run:!1,age_seconds:67624,age_hours:18.78,freshness_reference_time:`2026-07-06T06:49:06.471087+00:00`}},decision_freshness_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.471133+00:00`,sample_run_count:20,window_days:7,proxy_note:`checkpointed decision freshness projection; rebase old decisions at the decision point before reuse`,summary:{decision_count:0,stale_count:0,rebase_required_count:0,fresh_count:0},items:[]},todo_index:JSON.parse(`{"schema_version":"todo_index_v0","source":"live_loopx_status_public_slice","total_count":12,"current_projected_count":12,"rollout_event_count":94,"item_limit":12,"items":[{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo update recorded for todo_1596c3a678bb","schema_version":"todo_index_item_v0","todo_id":"todo_1596c3a678bb","role":"agent","status":"open","title":"todo update recorded for todo_1596c3a678bb","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:33:32Z","latest_event_status":"open","event_count":7,"event_kinds":["todo_update"]},{"goal_id":"loopx-meta","index":24,"done":false,"text":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","schema_version":"todo_index_item_v0","todo_id":"todo_15bc0926a494","role":"agent","status":"open","priority":"P0-REVENUE MONITOR","title":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"github_public_reply_metadata_monitor","claimed_by":"codex-value-explorer","evidence":"autonomous replan: bounded current value-explorer monitor lane with explicit expires_at.","note":"Set bounded watch expiry for metadata-only public reply monitor; no catch-up after expiry.","updated_at":"2026-07-05T06:27:15+08:00"},{"goal_id":"loopx-meta","index":17,"done":false,"text":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","schema_version":"todo_index_item_v0","todo_id":"todo_2bf560b48a0c","role":"agent","status":"open","priority":"P0","title":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"legacy_open_pr_rename_blocker","claimed_by":"codex-main-control"},{"goal_id":"loopx-meta","index":23,"done":false,"text":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","schema_version":"todo_index_item_v0","todo_id":"todo_3ed1c4a69164","role":"agent","status":"open","priority":"P0","title":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"skillsbench_local_verifier_reward_collection","claimed_by":"codex-main-control","required_capabilities":["benchmark_runner"]},{"goal_id":"loopx-meta","index":32,"done":false,"text":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","schema_version":"todo_index_item_v0","todo_id":"todo_44907a5f355d","role":"agent","status":"blocked","priority":"P0","title":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_raw_new_rerun","claimed_by":"codex-main-control","evidence":"Public-safe redacted live LoopX text; inspect local status for the full row.","note":"Do not spend a full citation-check loopx rerun yet: #865 fixed scored output paths and #874 added bootstrap preflight attribution, but citation-check itself still preflights as apt+verifier bootstrap risk on ECS.","updated_at":"2026-06-29T00:49:36+08:00"},{"goal_id":"loopx-meta","index":39,"done":false,"text":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","schema_version":"todo_index_item_v0","todo_id":"todo_4762c790e583","role":"agent","status":"blocked","priority":"P0","title":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_remote_rerun","claimed_by":"codex-main-control","evidence":"A prior benchmark adapter change was validated before the legacy surface was archived. Current research uses the RFC-linked benchmark workspace and toolkit boundary smokes.","note":"2026-06-29: fixed host-local ACP idle/no-output root cause in PR #894. ACP protocol tool_call_count=0 is now distinguished from reverse-channel task-facing bridge activity; repeated codex_exec_bridge_idle_timeout withou…","updated_at":"2026-06-29T19:40:32+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_584f55f8f3b4","schema_version":"todo_index_item_v0","todo_id":"todo_584f55f8f3b4","role":"agent","status":"open","title":"todo add recorded for todo_584f55f8f3b4","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:48:49Z","latest_event_status":"open","event_count":3,"event_kinds":["todo_add","todo_update"]},{"goal_id":"loopx-meta","index":40,"done":false,"text":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","schema_version":"todo_index_item_v0","todo_id":"todo_62debf065fec","role":"agent","status":"blocked","priority":"P0 MONITOR","title":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"monitor_skillsbench_batch","claimed_by":"codex-main-control","evidence":"Observed 2026-06-30T02:52+08: active-state target_key=skillsbench-goal-baseline-30case-20260629T1826Z-r10; local ps/tmux/recent artifact search found no r10 batch process or compact artifact; no raw task/log/trajectory …","updated_at":"2026-06-30T02:54:54+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_93bc6439c521","schema_version":"todo_index_item_v0","todo_id":"todo_93bc6439c521","role":"agent","status":"open","title":"todo add recorded for todo_93bc6439c521","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_claim","latest_event_at":"2026-07-06T06:32:52Z","latest_event_status":"open","event_count":2,"event_kinds":["todo_add","todo_claim"]},{"goal_id":"loopx-meta","index":27,"done":false,"text":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","schema_version":"todo_index_item_v0","todo_id":"todo_aad7e9716927","role":"agent","status":"blocked","priority":"P0","title":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"run_goal_start_product_mode_matrix","claimed_by":"codex-main-control","evidence":"driver.status shows DONE raw then RUN loopx-goal-start with no running driver; raw benchmark_run.compact first_blocker=skillsbench_codex_acp_provider_zero_activity; source guard requires --host-local-acp-launch for Loop…","note":"Remote run group skillsbench-raw-new-goal-start-20260627T0420Z produced a material closeout for citation-check raw only; raw compact attribution is skillsbench_codex_acp_provider_zero_activity with official score missin…","updated_at":"2026-06-27T13:05:47+08:00"},{"goal_id":"loopx-meta","index":21,"done":false,"text":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","schema_version":"todo_index_item_v0","todo_id":"todo_aec1873c7f28","role":"agent","status":"open","priority":"P0 MONITOR","title":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","claimed_by":"codex-main-control","note":"2026-06-23 projection fix: this is monitor context for the powerlifting run, not an advancement next action; current executable path is SkillsBench build cache/prewarm repair.","updated_at":"2026-06-23T10:37:43+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_c02cb7d19607","schema_version":"todo_index_item_v0","todo_id":"todo_c02cb7d19607","role":"agent","status":"open","title":"todo add recorded for todo_c02cb7d19607","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_add","latest_event_at":"2026-07-06T03:47:54Z","latest_event_status":"open","event_count":1,"event_kinds":["todo_add"]}]}`),agent_management_projection:{schema_version:`agent_management_projection_v0`,mode:`read_only`,goal_id:`loopx-meta`,generated_at:`2026-07-06T06:49:06Z`,style_hint:null,truth_contract:{todo_is_runtime_work_item:!0,projection_is_writable:!1,introduces_task_runtime:!1,write_api:!1},source_summary:{registered_agent_count:4,projected_agent_count:4,todo_source:`live_loopx_status_public_slice`,public_safe_export:!0},agents:[{agent_id:`codex-main-control`,agent_model:`peer_v1`,profile_role:`release-validation`,state:`blocked`,next_action:`Continue projected todo todo_2bf560b48a0c.`,last_activity_at:`2026-06-29T00:49:36+08:00`,evidence_refs:[`todo:todo_e72afc24f04a:evidence`],goal_ids:[`loopx-meta`],stale_claim_hint:{state:`activity_missing`,claimed_by:`codex-main-control`,reason:`claimed open todo has no projected activity timestamp`,recommended_operator_action:`inspect evidence before considering reassignment`},current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_2bf560b48a0c`,goal_id:`loopx-meta`,role:`agent`,status:`open`,priority:`P0`,title:`Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harn…`,task_class:`blocker`,action_kind:`legacy_open_pr_rename_blocker`,claimed_by:`codex-main-control`}},{agent_id:`codex-product-capability`,agent_model:`peer_v1`,profile_role:`product-validation`,state:`monitoring`,next_action:`Continue projected todo todo_ded745761822.`,last_activity_at:`2026-07-06T06:29:53Z`,evidence_refs:[`todo:todo_ded745761822:evidence`],goal_ids:[`loopx-meta`],current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_ded745761822`,goal_id:`loopx-meta`,role:`agent`,status:`open`,priority:`P0-LOCAL`,title:`Public-safe redacted live LoopX text; inspect local status for the full row.`,task_class:`continuous_monitor`,action_kind:`Public-safe redacted live LoopX text; inspect local status for the full row.`,claimed_by:`codex-product-capability`,updated_at:`2026-07-04T20:22:45+08:00`}},{agent_id:`codex-side-bypass`,agent_model:`peer_v1`,profile_role:`implementation-validation`,state:`waiting`,next_action:`Inspect status projection before taking work.`,last_activity_at:`2026-07-06T06:32:16Z`,evidence_refs:[`rollout_event:todo_complete:todo_22c946938115`],goal_ids:[`loopx-meta`]},{agent_id:`codex-value-explorer`,agent_model:`peer_v1`,profile_role:`value-exploration`,state:`monitoring`,next_action:`Continue projected todo todo_584f55f8f3b4.`,last_activity_at:`2026-07-06T09:39:59+08:00`,evidence_refs:[`rollout_event:todo_update:todo_584f55f8f3b4`],goal_ids:[`loopx-meta`],current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_584f55f8f3b4`,goal_id:`loopx-meta`,role:`agent`,status:`open`,title:`todo add recorded for todo_584f55f8f3b4`}}]},contract:{ok:!0,summary:{errors:0,warnings:1,checks:6},errors:[],warnings:["loopx-meta: duplicate index rows raw=8444 unique=8440 unexpected=3 artifact_identity_collisions=2 artifact_collision_rows=3 reward_overlays=1; inspect with `loopx history --goal-id loopx-meta inspect-index-duplicates`; artifact identity collisions need review…"],checks:[`registry goals checked: 12`,`registry boundary: shared_local_registry push_allowed=False tracked=False ignored=False`,`user-gate scopes checked: 6 open multi-agent gates`,`runtime root resolved: $HOME/.codex/loopx`,`run-history goals=28 runs=10210`,`public boundary scan clean: 1218 files`]},global_registry:{available:!0,ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,current_registry:`$HOME/.codex/loopx/registry.global.json`,current_registry_is_global:!0,global_goal_count:12,current_goal_count:12,source_registry_count:7,summary:{high:0,action:8,info:0,checks:2,findings:8},findings:[{kind:`source_registry_missing`,severity:`action`,message:"`cc-test` source registry is missing",recommended_action:"reconnect `cc-test` from its project or archive it if the project is obsolete",goal_id:`cc-test`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-test` active state file is missing",recommended_action:"repair `cc-test` state_file or reconnect the project",goal_id:`cc-test`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`cc-tmp` source registry is missing",recommended_action:"reconnect `cc-tmp` from its project or archive it if the project is obsolete",goal_id:`cc-tmp`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-tmp` active state file is missing",recommended_action:"repair `cc-tmp` state_file or reconnect the project",goal_id:`cc-tmp`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`cc-tmp-xdrchpuaul` source registry is missing",recommended_action:"reconnect `cc-tmp-xdrchpuaul` from its project or archive it if the project is obsolete",goal_id:`cc-tmp-xdrchpuaul`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-tmp-xdrchpuaul` active state file is missing",recommended_action:"repair `cc-tmp-xdrchpuaul` state_file or reconnect the project",goal_id:`cc-tmp-xdrchpuaul`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`loopx-auto-research-e2e-probe-20260628-2225-goal` source registry is missing",recommended_action:"reconnect `loopx-auto-research-e2e-probe-20260628-2225-goal` from its project or archive it if the project is obsolete",goal_id:`loopx-auto-research-e2e-probe-20260628-2225-goal`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`loopx-auto-research-e2e-probe-20260628-2225-goal` active state file is missing",recommended_action:"repair `loopx-auto-research-e2e-probe-20260628-2225-goal` state_file or reconnect the project",goal_id:`loopx-auto-research-e2e-probe-20260628-2225-goal`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`}],checks:[`global registry goals checked: 12`,`global source registries checked: 7`]},attention_queue:JSON.parse(`{"available":true,"item_count":1,"needs_user_or_controller":0,"needs_controller":0,"needs_codex":1,"watching_external_evidence":0,"items":[{"goal_id":"loopx-meta","status":"skillsbench_codex_cli_goal_tail4_keepalive_relaunched","lifecycle_phase":"adapter_inspected","lifecycle_flags":["adapter_inspected"],"waiting_on":"codex","severity":"action","recommended_action":"Monitor run_group skillsbench-codex-cli-goal-xhigh-tail4-keepalive-20260706T143132CST using public compact/public artifacts only; once benchmark_run.compact.json lands for each case, classify launcher/case/solver/verifi…","source":"latest_run","quota":{"compute":1.0,"window_hours":24,"slot_minutes":1,"allowed_slots":1440,"spent_slots":97,"state":"eligible","reason":"1 compute quota; eligible for the next automatic agent turn"},"agent_todos":{"source_section":"Agent Todo","total_count":12,"open_count":12,"done_count":0,"items":[{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo update recorded for todo_1596c3a678bb","schema_version":"todo_index_item_v0","todo_id":"todo_1596c3a678bb","role":"agent","status":"open","title":"todo update recorded for todo_1596c3a678bb","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:33:32Z","latest_event_status":"open","event_count":7,"event_kinds":["todo_update"]},{"goal_id":"loopx-meta","index":24,"done":false,"text":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","schema_version":"todo_index_item_v0","todo_id":"todo_15bc0926a494","role":"agent","status":"open","priority":"P0-REVENUE MONITOR","title":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"github_public_reply_metadata_monitor","claimed_by":"codex-value-explorer","evidence":"autonomous replan: bounded current value-explorer monitor lane with explicit expires_at.","note":"Set bounded watch expiry for metadata-only public reply monitor; no catch-up after expiry.","updated_at":"2026-07-05T06:27:15+08:00"},{"goal_id":"loopx-meta","index":17,"done":false,"text":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","schema_version":"todo_index_item_v0","todo_id":"todo_2bf560b48a0c","role":"agent","status":"open","priority":"P0","title":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"legacy_open_pr_rename_blocker","claimed_by":"codex-main-control"},{"goal_id":"loopx-meta","index":23,"done":false,"text":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","schema_version":"todo_index_item_v0","todo_id":"todo_3ed1c4a69164","role":"agent","status":"open","priority":"P0","title":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"skillsbench_local_verifier_reward_collection","claimed_by":"codex-main-control","required_capabilities":["benchmark_runner"]},{"goal_id":"loopx-meta","index":32,"done":false,"text":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","schema_version":"todo_index_item_v0","todo_id":"todo_44907a5f355d","role":"agent","status":"blocked","priority":"P0","title":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_raw_new_rerun","claimed_by":"codex-main-control","evidence":"Public-safe redacted live LoopX text; inspect local status for the full row.","note":"Do not spend a full citation-check loopx rerun yet: #865 fixed scored output paths and #874 added bootstrap preflight attribution, but citation-check itself still preflights as apt+verifier bootstrap risk on ECS.","updated_at":"2026-06-29T00:49:36+08:00"},{"goal_id":"loopx-meta","index":39,"done":false,"text":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","schema_version":"todo_index_item_v0","todo_id":"todo_4762c790e583","role":"agent","status":"blocked","priority":"P0","title":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_remote_rerun","claimed_by":"codex-main-control","evidence":"A prior benchmark adapter change was validated before the legacy surface was archived. Current research uses the RFC-linked benchmark workspace and toolkit boundary smokes.","note":"2026-06-29: fixed host-local ACP idle/no-output root cause in PR #894. ACP protocol tool_call_count=0 is now distinguished from reverse-channel task-facing bridge activity; repeated codex_exec_bridge_idle_timeout withou…","updated_at":"2026-06-29T19:40:32+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_584f55f8f3b4","schema_version":"todo_index_item_v0","todo_id":"todo_584f55f8f3b4","role":"agent","status":"open","title":"todo add recorded for todo_584f55f8f3b4","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:48:49Z","latest_event_status":"open","event_count":3,"event_kinds":["todo_add","todo_update"]},{"goal_id":"loopx-meta","index":40,"done":false,"text":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","schema_version":"todo_index_item_v0","todo_id":"todo_62debf065fec","role":"agent","status":"blocked","priority":"P0 MONITOR","title":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"monitor_skillsbench_batch","claimed_by":"codex-main-control","evidence":"Observed 2026-06-30T02:52+08: active-state target_key=skillsbench-goal-baseline-30case-20260629T1826Z-r10; local ps/tmux/recent artifact search found no r10 batch process or compact artifact; no raw task/log/trajectory …","updated_at":"2026-06-30T02:54:54+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_93bc6439c521","schema_version":"todo_index_item_v0","todo_id":"todo_93bc6439c521","role":"agent","status":"open","title":"todo add recorded for todo_93bc6439c521","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_claim","latest_event_at":"2026-07-06T06:32:52Z","latest_event_status":"open","event_count":2,"event_kinds":["todo_add","todo_claim"]},{"goal_id":"loopx-meta","index":27,"done":false,"text":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","schema_version":"todo_index_item_v0","todo_id":"todo_aad7e9716927","role":"agent","status":"blocked","priority":"P0","title":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"run_goal_start_product_mode_matrix","claimed_by":"codex-main-control","evidence":"driver.status shows DONE raw then RUN loopx-goal-start with no running driver; raw benchmark_run.compact first_blocker=skillsbench_codex_acp_provider_zero_activity; source guard requires --host-local-acp-launch for Loop…","note":"Remote run group skillsbench-raw-new-goal-start-20260627T0420Z produced a material closeout for citation-check raw only; raw compact attribution is skillsbench_codex_acp_provider_zero_activity with official score missin…","updated_at":"2026-06-27T13:05:47+08:00"},{"goal_id":"loopx-meta","index":21,"done":false,"text":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","schema_version":"todo_index_item_v0","todo_id":"todo_aec1873c7f28","role":"agent","status":"open","priority":"P0 MONITOR","title":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","claimed_by":"codex-main-control","note":"2026-06-23 projection fix: this is monitor context for the powerlifting run, not an advancement next action; current executable path is SkillsBench build cache/prewarm repair.","updated_at":"2026-06-23T10:37:43+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_c02cb7d19607","schema_version":"todo_index_item_v0","todo_id":"todo_c02cb7d19607","role":"agent","status":"open","title":"todo add recorded for todo_c02cb7d19607","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_add","latest_event_at":"2026-07-06T03:47:54Z","latest_event_status":"open","event_count":1,"event_kinds":["todo_add"]}]}}]}`),run_history:{available:!0,goal_count:1,run_count:5,goals:[{id:`loopx-meta`,domain:`loopx-platform`,status:`active-read-only`,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`],registry_member:!0,legacy_runtime_goal:!1,adapter_kind:`harness_self_improvement`,adapter_status:`connected-read-only`,index_exists:!0,raw_index_records:8444,unique_runs:8440,quota:{compute:1,window_hours:24,slot_minutes:1,allowed_slots:1440,spent_slots:97,state:`waiting`,reason:`no active Codex-ready work is currently selected`},latest_runs:[{generated_at:`2026-07-06T14:37:32+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-value-explorer`,recommended_action:`审阅 PR #1524 的 Agent Management 面板视觉方向:workspace hint 与 stale claim hint 是否符合预期;确认后允许 codex-value-explorer 自合并。`,health_check:`quota safe-bypass operator gate; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:55+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-main-control`,recommended_action:`[P1] Repair SkillsBench post-run debug gate consistency for countable codex-cli-goal official-zero runs: when attempt_accounting is countable and case_closeout_complete=true, do not project first_blocker=loopx_closeout_…`,health_check:`quota should-run eligible; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:54+08:00`,goal_id:`loopx-meta`,classification:`skillsbench_codex_cli_goal_tail4_keepalive_relaunched`,agent_id:`codex-main-control`,progress_scope:`goal`,delivery_batch_scale:`single_surface`,delivery_outcome:`outcome_progress`,recommended_action:`Monitor run_group skillsbench-codex-cli-goal-xhigh-tail4-keepalive-20260706T143132CST using public compact/public artifacts only; once benchmark_run.compact.json lands for each case, classify launcher/case/solver/verifi…`,health_check:`state_file 1/1; registry_goal 1/1; authority_sources 10`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:34+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-side-bypass`,recommended_action:`[P0] Rerun real KNN visible auto-research after the successor-link fix and verify evaluator completion projects a second-round hypothesis/frontier or explicit completion gate without manual intervention; keep evidence p…`,health_check:`quota should-run eligible; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:32:57+08:00`,goal_id:`loopx-meta`,classification:`auto_research_successor_link_fix_merged`,agent_id:`codex-side-bypass`,progress_scope:`agent_lane`,delivery_batch_scale:`implementation`,delivery_outcome:`outcome_progress`,recommended_action:`[P0] Rerun real KNN visible auto-research after the successor-link fix and verify evaluator completion projects a second-round hypothesis/frontier or explicit completion gate without manual intervention; keep evidence p…`,health_check:`state_file 1/1; registry_goal 1/1; authority_sources 0`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]}]}]}},Yd=G().nullable(),Xd=Y({schema_version:X(`goal_acceptance_observation_projection_v0`),goal_id:G(),read_only:X(!0),acceptance_assessed:X(!1),coverage:_d([`partial`,`unavailable`]),missing_sources:J(G()),truncated:q(),historical_progress:J(Y({kind:G(),observed_at:Yd,source:G(),evidence_refs:J(G())})),acceptance_gaps:J(Y({kind:G(),owner:Yd,reason:Yd,evidence_required:Yd,observed_at:Yd,source:G()})),guards:J(Y({kind:G(),todo_id:Yd,blocks_agent:Yd,owner:Yd,reason:Yd,evidence_required:Yd,decision_scope:Yd})),next_action:Yd,next_action_source:Yd}),Zd=ld([G(),K(),q(),td()]),Qd=hd(G(),Zd),$d=Y({todo_id:G().optional(),priority:G().optional(),status:G(),title:G(),claimed_by:G().optional(),task_class:G().optional(),action_kind:G().optional()}),ef=Y({gate_id:G(),kind:G(),status:G(),blocks:J(G()).optional()}),tf=Y({todo_id:G().optional(),owner_agent:G().optional(),status:G().optional(),lease_until:G().optional(),write_scope:J(G()).optional()}),nf=Y({generated_at:G().optional(),classification:G().optional(),summary:G().optional()}),rf=Y({kind:G().optional().default(`warning`),message:ld([G(),J(G())]).optional().default(`compact source warning`)}).passthrough(),af=Y({schema_version:X(`goal_channel_projection_v0`),mode:X(`read_only`),goal_id:G(),display_name:G(),generated_at:G().optional().nullable(),latest_status:G(),waiting_on:G(),next_action:G(),source_refs:hd(G(),Zd),decision_frame:Y({user_action_required:q(),agent_action_required:q(),quiet_noop_allowed:q()}),quota:Qd,user_todos:J($d).default([]),agent_todos:J($d).default([]),open_gates:J(ef).default([]),active_leases:J(tf).default([]),artifacts:J(Qd).default([]),recent_events:J(nf).default([]),source_warnings:J(rf).default([]),truth_contract:Y({event_ledger_is_source_of_truth:q(),projection_is_writable:q(),recompute_rule:G(),write_authority:G()})}),of=Y({compute:K().optional().default(1),window_hours:K().optional().default(24),slot_minutes:K().optional().default(1),allowed_slots:K().optional().nullable(),spent_slots:K().optional().default(0),state:G().optional().nullable(),next_eligible_at:G().optional().nullable(),reason:G().optional().nullable(),blocked_action_scope:G().optional().nullable(),focus_wait:q().optional().nullable(),handoff_outcome_floor_block:q().optional().nullable(),safe_bypass_allowed:q().optional().default(!1),safe_bypass_kind:G().optional().nullable(),safe_bypass_policy:G().optional().nullable(),post_handoff_outcome_gap_streak:K().optional().nullable(),outcome_gap_threshold:K().optional().nullable(),must_advance:J(G()).optional().default([]),avoid:J(G()).optional().default([])}).transform(e=>{let t=Math.max(1,e.slot_minutes),n=Math.round(e.window_hours*60*e.compute/t);return{...e,slot_minutes:t,allowed_slots:e.allowed_slots??n}}),sf=Y({self_repair:Y({enabled:q().optional().default(!1),allow_health_blocker_repair:q().optional().default(!1),allow_waiting_projection_repair:q().optional().default(!1)}).optional().nullable()}).passthrough(),cf=Y({model_config:Y({model:G(),reasoning_effort:G().optional()}).optional(),mode:G().optional().default(`default`),orchestration_mode:G().optional().nullable(),spawn_allowed:q().optional().default(!1),allowed:q().optional().nullable(),max_children:K().optional().default(0),allowed_domains:J(G()).optional().default([])}).passthrough(),lf=Y({label:G().optional().nullable(),path:G(),anchor:G().optional().nullable(),exists:q().optional().default(!1),resolved_path:G().optional().nullable()}),uf=Y({index:K(),done:q(),text:G(),schema_version:G().optional().nullable(),todo_id:G().optional().nullable(),role:G().optional().nullable(),status:G().optional().nullable(),resume_when:G().optional().nullable(),resume_ready:q().optional().nullable(),resume_condition:hd(G(),rd()).optional().nullable(),priority:G().optional().nullable(),title:G().optional().nullable(),archive_state:G().optional().nullable(),source_section:G().optional().nullable(),task_class:G().optional().nullable(),task_domain:G().optional().nullable(),action_kind:G().optional().nullable(),claimed_by:G().optional().nullable(),required_capabilities:J(G()).optional(),note:G().optional().nullable(),evidence:G().optional().nullable(),updated_at:G().optional().nullable(),review_materials:J(lf).optional().default([])}).passthrough(),df=Y({source_section:G().optional().nullable(),total_count:K().optional().default(0),open_count:K().optional().default(0),done_count:K().optional().default(0),advancement_done_count:K().optional(),items:J(uf).optional().default([]),deferred_items:J(uf).optional()}),ff=uf.extend({goal_id:G(),source:G().optional().nullable(),event_count:K().optional().default(0),event_kinds:J(G()).optional().default([]),latest_event_kind:G().optional().nullable(),latest_event_at:G().optional().nullable(),latest_event_status:G().optional().nullable(),agent_id:G().optional().nullable()}).passthrough(),pf=Y({schema_version:G().optional().nullable(),source:G().optional().nullable(),total_count:K().optional().default(0),current_projected_count:K().optional().default(0),rollout_event_count:K().optional().default(0),item_limit:K().optional().nullable(),items:J(ff).optional().default([])}),mf=Y({kind:G().optional().nullable(),label:G().optional().nullable(),path_safe:q().optional().default(!1),branch:G().optional().nullable(),write_scope:J(G()).optional().default([])}).passthrough(),hf=Y({state:G().optional().nullable(),claimed_by:G().optional().nullable(),last_activity_at:G().optional().nullable(),threshold_hours:K().optional().nullable(),reason:G().optional().nullable(),recommended_operator_action:G().optional().nullable()}).passthrough(),gf=Y({schema_version:G().optional().nullable(),todo_id:G().optional().nullable(),goal_id:G().optional().nullable(),role:G().optional().nullable(),status:G().optional().nullable(),priority:G().optional().nullable(),title:G().optional().nullable(),task_class:G().optional().nullable(),action_kind:G().optional().nullable(),claimed_by:G().optional().nullable(),required_write_scopes:J(G()).optional().default([]),workspace_ref:mf.optional().nullable()}).passthrough(),_f=Y({schema_version:G().optional().nullable(),from_agent:G().optional().nullable(),to_agent:G().optional().nullable(),intent:G().optional().nullable(),summary:G().optional().nullable(),blocker:G().optional().nullable(),suggested_next_action:G().optional().nullable(),evidence_refs:J(G()).optional().default([]),updated_at:G().optional().nullable()}).passthrough(),vf=Y({agent_id:G(),role:G().optional().nullable(),state:G().optional().nullable(),current_todo:gf.optional().nullable(),next_action:G().optional().nullable(),last_activity_at:G().optional().nullable(),evidence_refs:J(G()).optional().default([]),handoff_refs:J(G()).optional().default([]),handoff_note:_f.optional().nullable(),workspace_ref:mf.optional().nullable(),stale_claim_hint:hf.optional().nullable(),blocked_on:gf.optional().nullable(),goal_ids:J(G()).optional().default([])}).passthrough(),yf=Y({schema_version:G().optional().nullable(),mode:G().optional().nullable(),goal_id:G().optional().nullable(),generated_at:G().optional().nullable(),style_hint:Y({preferred:G().optional().nullable(),license_boundary:G().optional().nullable()}).optional().nullable(),truth_contract:Y({todo_is_runtime_work_item:q().optional().default(!0),projection_is_writable:q().optional().default(!1),introduces_task_runtime:q().optional().default(!1),write_api:q().optional().default(!1)}).optional().nullable(),source_summary:Y({registered_agent_count:K().optional().default(0),projected_agent_count:K().optional().default(0),todo_source:G().optional().nullable()}).optional().nullable(),agents:J(vf).optional().default([])}).passthrough(),bf=Y({goal_id:G(),configured:q().optional().default(!1),enabled:q().optional().default(!1),human_gate_auto_notify_enabled:q().optional().default(!1),target_ref:G().optional().nullable(),receipt_count:K().optional().default(0),last_notified_at:G().optional().nullable()}).passthrough(),xf=Y({schema_version:G().optional().nullable(),generated_at:G().optional().nullable(),goals:J(bf).optional().default([])}).passthrough(),Sf=Y({source_section:G().optional().nullable(),open:K().optional().default(0),done:K().optional().default(0),total:K().optional().default(0),advancement_done_count:K().optional(),next:G().optional().nullable(),next_index:K().optional().nullable(),items:J(uf).optional().default([]),recent_completed_advancement_items:J(uf).optional().default([])}),Cf=Y({goal_id:G(),status:G().optional().nullable(),waiting_on:G().optional().nullable(),severity:G().optional().nullable(),index:K().optional().nullable(),text:G(),source:G().optional().nullable()}),wf=Y({source:G().optional().nullable(),open_count:K().optional().default(0),items:J(Cf).optional().default([])}),Tf=Y({goal_id:G(),status:G().optional().nullable(),waiting_on:G().optional().nullable(),quota_state:G().optional().nullable(),priority:G().optional().nullable(),todo_index:K().optional().nullable(),text:G(),source:G().optional().nullable()}),Ef=Y({source:G().optional().nullable(),open_count:K().optional().default(0),items:J(Tf).optional().default([])}),Df=Y({generated_at:G().optional().nullable(),classification:G().optional().nullable(),summary:G().optional().nullable()}),Of=Y({kind:G().optional().nullable(),source:G().optional().nullable(),severity:G().optional().nullable(),requires_refresh_state:q().optional().default(!1),reason:G().optional().nullable(),active_state_updated_at:G().optional().nullable(),latest_run_generated_at:G().optional().nullable(),latest_run_state_updated_at:G().optional().nullable(),latest_run_classification:G().optional().nullable(),recommended_action:G().optional().nullable()}),kf=Y({generated_at:G().optional().nullable(),classification:G().optional().nullable(),delivery_batch_scale:G().optional().nullable(),delivery_outcome:G().optional().nullable(),health_check:G().optional().nullable(),json_exists:q().optional().nullable(),markdown_exists:q().optional().nullable()}),Af=Y({project_asset_backed:q().optional(),same_source_should_run:q().optional(),codex_ready:q().optional(),handoff_has_next_action:q().optional(),handoff_has_stop_condition:q().optional(),handoff_sanitized_surface:q().optional()}).catchall(q()),jf=Y({ready:q().optional().default(!1),codex_ready:q().optional().default(!1),source:G().optional().nullable(),quota_state:G().optional().nullable(),checks:Af.optional().default({}),handoff_status:G().optional().nullable(),handoff_ready_at:G().optional().nullable(),handoff_ready_classification:G().optional().nullable(),post_handoff_run_seen:q().optional().default(!1),post_handoff_latest_run:kf.optional().nullable(),post_handoff_recent_runs:J(kf).optional().default([]),post_handoff_small_scale_streak:K().int().nonnegative().optional().default(0),post_handoff_outcome_gap_streak:K().int().nonnegative().optional().default(0),next_probe:G().optional().nullable()}),Mf=Y({schema_version:G().optional().nullable(),kind:G().optional().nullable(),missing_roles:J(G()).optional().default([]),source:G().optional().nullable(),recommended_action:G().optional().nullable()}),Nf=Y({owner:G(),gate:G(),next_action:G(),stop_condition:G(),user_todos:Sf.optional().nullable(),agent_todos:Sf.optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),orchestration:cf.optional().nullable(),latest_validation:Df.optional().nullable(),stale_latest_run_warning:Of.optional().nullable(),todo_projection_gap:Mf.optional().nullable()}),Pf=Y({goal_id:G(),activation_state:_d([`active`,`stopped`]).optional().default(`active`),status:G(),waiting_on:G(),severity:G(),recommended_action:G(),project_asset:Nf.optional().nullable(),handoff_readiness:jf.optional().nullable(),source:G().optional(),operator_question:G().optional().nullable(),agent_command:G().optional().nullable(),lifecycle_phase:G().optional().nullable(),lifecycle_flags:J(G()).optional().default([]),controller_stage:G().optional().nullable(),missing_gates:J(G()).optional().default([]),next_handoff_condition:G().optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),user_todos:df.optional().nullable(),agent_todos:df.optional().nullable(),stale_latest_run_warning:Of.optional().nullable(),dependency_blockers:wf.optional().nullable(),todo_state_file:G().optional().nullable(),goal_channel_projection:af.optional().nullable()}),Ff=Y({recorded_at:G().optional().nullable(),decision:G().optional().nullable(),reward:G().optional().nullable(),reason_summary:G().optional().nullable(),follow_up:G().optional().nullable()}),If=Y({recorded_at:G().optional().nullable(),gate:G().optional().nullable(),decision:G().optional().nullable(),operator_question:G().optional().nullable(),reason_summary:G().optional().nullable(),follow_up:G().optional().nullable(),agent_command:G().optional().nullable()}),Lf=Y({version:G().optional().nullable(),goal_id:G().optional().nullable(),run_id:G().optional().nullable(),gate_id:G().optional().nullable(),created_state_ref:G().optional().nullable(),created_policy_version:G().optional().nullable(),interrupt_payload:Y({question:G().optional().nullable(),choices:J(G()).optional().default([])}).optional().nullable(),allowed_decisions:J(G()).optional().default([]),operator_decision:G().optional().nullable(),latest_state_ref:G().optional().nullable(),freshness_check:G().optional().nullable(),precondition_check:G().optional().nullable(),migration_or_rebase_result:G().optional().nullable(),resulting_action:G().optional().nullable(),validation_after_resume:G().optional().nullable()}),Rf=Y({id:G().optional().nullable(),ok:q().optional().nullable(),review:G().optional().nullable()}),zf=Y({classification:G().optional().nullable(),read_only_observer_ready:q().optional().nullable(),decision_advisor_ready:q().optional().nullable(),write_controller_ready:q().optional().nullable(),missing_gates:J(G()).optional().default([]),review_judgment:G().optional().nullable(),next_handoff_condition:G().optional().nullable(),gates:J(Rf).optional().default([])}),Bf=Y({declared:q().optional().default(!1),required:q().optional().default(!1),path:G().optional().nullable(),path_exists:q().optional().nullable(),read_status:G().optional().nullable(),default_entry_count:K().optional().default(0),default_entries_checked:K().optional().default(0),default_entries_present:K().optional().default(0),topic_authority_count:K().optional().default(0),project_material_count:K().optional().default(0),project_material_repository_count:K().optional().default(0),project_material_owner_review_required_count:K().optional().default(0),project_material_stale_count:K().optional().default(0),project_material_current_authority_count:K().optional().default(0),deprecated_source_count:K().optional().default(0),conflict_risk:G().optional().nullable()}),Vf=Y({adapter_kind:G().optional().nullable(),adapter_status:G().optional().nullable(),authority_source_count:K().optional().nullable(),authority_registry_declared:q().optional().nullable(),authority_registry_path_exists:q().optional().nullable(),authority_registry_default_entry_count:K().optional().nullable(),authority_registry_default_entries_present:K().optional().nullable(),topic_authority_count:K().optional().nullable(),project_material_count:K().optional().nullable(),project_material_repository_count:K().optional().nullable(),project_material_owner_review_required_count:K().optional().nullable(),project_material_stale_count:K().optional().nullable(),project_material_current_authority_count:K().optional().nullable(),authority_registry_conflict_risk:G().optional().nullable(),guard_count:K().optional().nullable(),sections_found:K().optional().nullable(),sections_checked:K().optional().nullable(),files_present:K().optional().nullable(),files_checked:K().optional().nullable()}),Hf=Y({generated_at:G(),goal_id:G(),classification:G().optional().nullable(),lifecycle_phase:G().optional().nullable(),lifecycle_flags:J(G()).optional().default([]),recommended_action:G().optional().nullable(),health_check:G().optional().nullable(),active_task_count:K().optional().nullable(),active_priorities:hd(G(),rd()).optional().nullable(),cache_check:G().optional().nullable(),json_exists:q().optional().default(!1),markdown_exists:q().optional().default(!1),human_reward:Ff.optional().nullable(),operator_gate:If.optional().nullable(),operator_gate_resume_contract:Lf.optional().nullable(),controller_readiness:zf.optional().nullable(),project_map:Vf.optional().nullable()}),Uf=Y({acceptance_observation:Xd.optional().nullable().catch(null),id:G(),activation_state:_d([`active`,`stopped`]).optional().default(`active`),display_name:G().optional().nullable(),domain:G().optional().nullable(),status:G().optional().nullable(),lifecycle_phase:G().optional().nullable(),lifecycle_flags:J(G()).optional().default([]),registry_member:q().optional().default(!1),legacy_runtime_goal:q().optional().default(!1),adapter_kind:G().optional().nullable(),adapter_status:G().optional().nullable(),authority_registry:Bf.optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),spawn_policy:cf.optional().nullable(),orchestration:cf.optional().nullable(),coordination:Y({agent_model:G().optional().nullable(),registered_agents:J(G()).optional().default([])}).optional().nullable(),index_exists:q().optional().default(!1),raw_index_records:K().optional().default(0),unique_runs:K().optional().default(0),latest_runs:J(Hf).optional().default([])}),Wf=Y({available:q(),goal_count:K().optional().default(0),run_count:K().optional().default(0),goals:J(Uf).optional().default([]),recent_runs:J(Hf).optional().default([])}),Gf=Y({kind:G(),severity:G(),message:G(),recommended_action:G(),goal_id:G().optional().nullable(),path:G().optional().nullable(),goal_ids:J(G()).optional().default([])}),Kf=Y({available:q(),ok:q(),registry:G(),current_registry:G().optional().nullable(),current_registry_is_global:q().optional().default(!1),global_goal_count:K().optional().default(0),current_goal_count:K().optional().default(0),source_registry_count:K().optional().default(0),summary:Y({high:K().optional().default(0),action:K().optional().default(0),info:K().optional().default(0),checks:K().optional().default(0),findings:K().optional().default(0)}),findings:J(Gf).optional().default([]),checks:J(G()).optional().default([])}),qf=Y({runs_24h:K().optional().default(0),runs_7d:K().optional().default(0),quota_spend_slots_24h:K().optional().default(0),quota_spend_slots_7d:K().optional().default(0),automation_run_count_24h:K().optional().default(0),automation_run_count_7d:K().optional().default(0),progress_signal_run_count_24h:K().optional().default(0),progress_signal_run_count_7d:K().optional().default(0),input_tokens_24h:K().optional(),input_tokens_7d:K().optional(),output_tokens_24h:K().optional(),output_tokens_7d:K().optional(),cache_tokens_24h:K().optional(),cache_tokens_7d:K().optional(),cost_usd_24h:K().optional(),cost_usd_7d:K().optional(),duration_ms_24h:K().optional(),duration_ms_7d:K().optional()}),Jf=qf.extend({goal_id:G(),project_share_24h:K().optional().default(0)}),Yf=Y({available:q().optional().default(!0),source:G().optional().default(`run_history`),generated_at:G().optional().nullable(),sample_run_count:K().optional().default(0),proxy_note:G().optional().nullable(),totals:qf.optional().default({runs_24h:0,runs_7d:0,quota_spend_slots_24h:0,quota_spend_slots_7d:0,automation_run_count_24h:0,automation_run_count_7d:0,progress_signal_run_count_24h:0,progress_signal_run_count_7d:0}),goals:J(Jf).optional().default([])}).optional().nullable(),Xf=Y({accounting:K().optional().default(0),decision:K().optional().default(0),evidence:K().optional().default(0),state:K().optional().default(0),work:K().optional().default(0)}),Zf={accounting:0,decision:0,evidence:0,state:0,work:0},Qf=Y({events_24h:K().optional().default(0),events_7d:K().optional().default(0),by_class_24h:Xf.optional().default(Zf),by_class_7d:Xf.optional().default(Zf)}),$f=Qf.extend({goal_id:G(),latest_event_class:G().optional().nullable(),latest_event_at:G().optional().nullable()}),ep={events_24h:0,events_7d:0,by_class_24h:Zf,by_class_7d:Zf},tp=Y({available:q().optional().default(!0),source:G().optional().default(`run_history`),generated_at:G().optional().nullable(),sample_run_count:K().optional().default(0),proxy_note:G().optional().nullable(),event_classes:J(G()).optional().default([`accounting`,`decision`,`evidence`,`state`,`work`]),totals:Qf.optional().default(ep),goals:J($f).optional().default([])}).optional().nullable(),np=Y({available:q().optional().default(!1),source:G().optional().default(`run_history`),goal_id:G().optional().nullable(),generated_at:G().optional().nullable(),classification:G().optional().nullable(),delivery_batch_scale:G().optional().nullable(),delivery_outcome:G().optional().nullable(),recommended_action:G().optional().nullable(),json_exists:q().optional().default(!1),markdown_exists:q().optional().default(!1),freshness_window_hours:K().optional().default(24),freshness_status:G().optional().nullable(),is_fresh:q().optional().default(!1),requires_readiness_run:q().optional().default(!0),age_seconds:K().optional().nullable(),age_hours:K().optional().nullable(),freshness_reference_time:G().optional().nullable(),sample_run_count:K().optional().default(0),proxy_note:G().optional().nullable(),reason:G().optional().nullable()}).optional().nullable(),rp=Y({ok:q().optional().default(!0),registry:G().optional().nullable(),runtime_root:G().optional().nullable(),gate:G().optional().default(`promotion_readiness`),gate_state:G().optional().default(`warning`),can_promote:q().optional().default(!1),should_warn:q().optional().default(!0),non_blocking:q().optional().default(!0),recommended_action:G().optional().nullable(),warning_message:G().optional().nullable(),readiness:np.default(null)}).optional().nullable(),ip=Y({decision_count:K().optional().default(0),stale_count:K().optional().default(0),rebase_required_count:K().optional().default(0),fresh_count:K().optional().default(0)}),ap=Y({goal_id:G(),decision_kind:G().optional().nullable(),decision_at:G().optional().nullable(),classification:G().optional().nullable(),age_days:K().optional().nullable(),stale_by_age:q().optional().default(!1),newer_event_count_7d:K().optional().default(0),newer_event_classes_7d:Xf.optional().default(Zf),freshness_state:G().optional().nullable(),requires_decision_point_rebase:q().optional().default(!1),reason:G().optional().nullable()}),op=Y({available:q().optional().default(!0),source:G().optional().default(`run_history`),generated_at:G().optional().nullable(),sample_run_count:K().optional().default(0),window_days:K().optional().default(7),proxy_note:G().optional().nullable(),summary:ip.optional().default({decision_count:0,stale_count:0,rebase_required_count:0,fresh_count:0}),items:J(ap).optional().default([])}).optional().nullable(),sp=Y({schema_version:K().optional().default(0),minimum_dashboard_schema_version:K().optional().default(2),producer:G().optional().nullable(),reload_hint:G().optional().nullable()}).optional().default({schema_version:0,minimum_dashboard_schema_version:2,producer:null,reload_hint:`scripts/macos-dashboard-launchagent.sh restart`}),cp=Y({schema_version:X(`loopx_goal_projection_scope_v0`),scope:_d([`all`,`active`,`stopped`]),complete:q(),projected_goal_count:K().int().nonnegative(),registry_goal_count:K().int().nonnegative(),registry_revision:G().optional().nullable()}),lp=Y({source:G().optional().default(`serve-status`),status_url:G().optional().nullable(),health_url:G().optional().nullable(),review_material_url:G().optional().nullable(),presentation_surfaces_url:G().optional().nullable(),presentation_detail_url:G().optional().nullable(),periodic_report_index_url:G().optional().nullable(),periodic_report_detail_url:G().optional().nullable(),ssh_hosts_url:G().optional().nullable(),reward_dry_run_url:G().optional().nullable(),reward_append_url:G().optional().nullable(),reward_write_enabled:q().optional().default(!1),configure_goal_dry_run_url:G().optional().nullable(),configure_goal_apply_url:G().optional().nullable(),control_plane_write_enabled:q().optional().default(!1)}).optional().nullable(),up=Y({extension_id:G().min(1),surface_id:G().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/),extension_revision:G().min(1),payload_sha256:G().regex(/^[0-9a-f]{64}$/)}).strict(),dp=Y({extension_id:G().min(1),extension_revision:G().min(1),surface_id:G().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/),surface_kind:G().regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/),title:G().min(1),view_schema:G().regex(/^[a-z][a-z0-9_]*_v\d+$/),visibility:_d([`public-safe`,`owner-only`]),goal_id:G().min(1).nullable(),generated_at:G().min(1).nullable(),review_due_at:G().min(1).nullable(),diagnostic:G().min(1).nullable(),empty_state_title:G().min(1),empty_state_detail:G().min(1)}),fp=ld([dp.extend({state:_d([`ready`,`review_due`]),goal_id:G().min(1),generated_at:G().min(1),detail_ref:up}).strict(),dp.extend({state:X(`empty`),detail_ref:ad().optional()}).strict(),dp.extend({state:X(`invalid`),diagnostic:G().min(1),detail_ref:ad().optional()}).strict()]),pp=Y({schema_version:X(`extension_presentation_surfaces_v0`),count:K().int().nonnegative(),ready_count:K().int().nonnegative(),review_due_count:K().int().nonnegative(),empty_count:K().int().nonnegative(),invalid_count:K().int().nonnegative(),items:J(fp)}).strict(),mp={schema_version:`extension_presentation_surfaces_v0`,count:0,ready_count:0,review_due_count:0,empty_count:0,invalid_count:0,items:[]};Y({ok:X(!0),presentation_surfaces:pp}).strict();var hp=Y({goal_id:G().min(1),agent_id:G().min(1),generation_id:G().min(1),content_sha256:G().regex(/^sha256:[0-9a-f]{64}$/)}).strict(),gp=Y({goal_id:G().min(1),agent_id:G().min(1),generation_id:G().min(1),publication_id:G().min(1),delivered_at:G().min(1),predecessor_publication_id:G().min(1).nullable().optional(),detail_ref:hp}).strict(),_p=Y({schema_version:X(`periodic_report_workspace_index_v0`),count:K().int().nonnegative(),items:J(gp)}),vp=_p.extend({returned_count:K().int().nonnegative(),total_count:K().int().nonnegative(),limit:K().int().nonnegative(),offset:K().int().nonnegative(),truncated:q()}).strict(),yp=_p.strict().transform(e=>({...e,returned_count:e.count,total_count:e.count,limit:e.count,offset:0,truncated:!1})),bp=Y({ok:X(!0),periodic_reports:ld([vp,yp])}).strict(),xp=Y({schema_version:X(`periodic_report_workspace_projection_v0`),goal_id:G().min(1),agent_id:G().min(1),generation_id:G().min(1),generated_at:G().min(1),title:G().min(1),summary:G().min(1),content_sha256:G().regex(/^sha256:[0-9a-f]{64}$/),period_window:Y({start_at:G().min(1),end_at:G().min(1)}).strict(),interaction:Y({attention_kind:X(`progress`),interaction:X(`inform`),delivery:X(`surface`),form:X(`milestone_report`),writable:X(!1)}).strict(),delta:Y({added_count:K().int().nonnegative(),changed_count:K().int().nonnegative(),item_count:K().int().positive(),items:J(Y({fact_id:G().min(1),source_ref:G().min(1),title:G().min(1),summary:G().min(1),status:G().min(1),content_kind:G().min(1),change_kind:_d([`added`,`changed`]),previous_status:G().min(1).optional()}).strict())}).strict(),publication:Y({publication_id:G().min(1),delivered_at:G().min(1),predecessor_publication_id:G().min(1).nullable().optional(),cursor_id:G().min(1)}).strict(),truth_contract:Y({published_cursor_is_source_of_truth:X(!0),generation_receipt_is_delivery_receipt:X(!1),projection_is_writable:X(!1),browser_write_api:X(!1)}).strict()}).strict(),Sp=Y({ok:X(!0),projection:xp}).strict(),Cp=Y({ok:q(),registry:G(),runtime_root:G(),goal_count:K(),run_count:K(),status_contract:sp,goal_projection:cp.optional().nullable().default(null),local_dashboard_api:lp,contract:Y({ok:q(),summary:Y({errors:K(),warnings:K(),checks:K()}),errors:J(G()),warnings:J(G()),checks:J(G()).optional().default([])}),global_registry:Kf.optional().default({available:!1,ok:!0,registry:``,current_registry:null,current_registry_is_global:!1,global_goal_count:0,current_goal_count:0,source_registry_count:0,summary:{high:0,action:0,info:0,checks:0,findings:0},findings:[],checks:[]}),attention_queue:Y({available:q(),item_count:K(),needs_user_or_controller:K(),needs_controller:K().optional().default(0),needs_codex:K(),watching_external_evidence:K(),autonomous_backlog_candidates:Ef.optional().nullable(),items:J(Pf)}),run_history:Wf.optional().default({available:!1,goal_count:0,run_count:0,goals:[],recent_runs:[]}),event_ledger_summary:tp.default(null),promotion_readiness_summary:np.default(null),promotion_gate:rp.default(null),decision_freshness_summary:op.default(null),usage_summary:Yf.default(null),todo_index:pf.optional().nullable().default(null),agent_management_projection:yf.optional().nullable().default(null),goal_channel_notification_projection:xf.optional().nullable().default(null),presentation_surfaces:pp.optional().default(mp)});Y({ok:q(),dry_run:q().optional().default(!0),appended:q().optional().default(!1),goal_id:G().optional().nullable(),raw_index_records_before:K().optional().nullable(),preview_id:G().optional().nullable(),selected_run:Y({generated_at:G().optional().nullable(),classification:G().optional().nullable(),recommended_action:G().optional().nullable(),json_exists:q().optional().nullable(),markdown_exists:q().optional().nullable()}).optional().nullable(),human_reward:Ff.optional().nullable(),active_state_summary:G().optional().nullable(),project_agent_visibility:Y({source_of_truth:G().optional().nullable(),history_command:G().optional().nullable(),active_state_role:G().optional().nullable(),review_packet_role:G().optional().nullable()}).optional().nullable(),error:G().optional().nullable()});function wp(e,t,n){let r=e.run_history.goals.map(e=>e.id===t&&e.activation_state!==n?{...e,activation_state:n}:e),i=e.attention_queue.items.map(e=>e.goal_id===t&&e.activation_state!==n?{...e,activation_state:n}:e),a=r.some((t,n)=>t!==e.run_history.goals[n]),o=i.some((t,n)=>t!==e.attention_queue.items[n]);return!a&&!o?e:{...e,attention_queue:o?{...e.attention_queue,items:i}:e.attention_queue,run_history:a?{...e.run_history,goals:r}:e.run_history}}function Tp(e,t){let n=e.run_history.goals.filter(e=>e.id!==t),r=e.attention_queue.items.filter(e=>e.goal_id!==t);return n.length===e.run_history.goals.length&&r.length===e.attention_queue.items.length?e:{...e,attention_queue:{...e.attention_queue,items:r},run_history:{...e.run_history,goals:n}}}function Ep(e){return Cp.parse(e)}function Dp(e){return e instanceof du?e.issues.map(e=>`${e.path.join(`.`)||`root`}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}var Op=Ep(Jd),kp=Y({ok:X(!0),schema_version:X(`loopx_workspace_directory_v1`),registry_revision:G(),goals:J(Y({id:G(),display_name:G(),activation_state:_d([`active`,`stopped`]),registry_member:X(!0)}))});function Ap(e,t,n){let r=new URL(e,n);r.searchParams.delete(`goal_activation`),r.searchParams.delete(`goal_id`),r.searchParams.delete(`view`);for(let[e,n]of Object.entries(t))r.searchParams.set(e,n);return r.toString()}async function jp(e,t){let n=await fetch(Ap(e,{view:`workspace-directory`},t),{cache:`no-store`,signal:AbortSignal.timeout(5e3)});if(!n.ok)return null;let r=kp.safeParse(await n.json());return r.success?r.data:null}function Mp(e){return Ep({ok:!0,registry:``,runtime_root:``,goal_count:e.goals.length,run_count:0,local_dashboard_api:{},contract:{ok:!0,summary:{errors:0,warnings:0,checks:0},errors:[],warnings:[]},attention_queue:{available:!1,item_count:0,needs_user_or_controller:0,needs_codex:0,watching_external_evidence:0,items:[]},run_history:{available:!1,goal_count:e.goals.length,run_count:0,goals:e.goals,recent_runs:[]}})}async function Np(e,t,n,r,i,a,o){let s=[...n.goals],c=new Map;async function l(){for(;s.length&&i()&&!o?.aborted;){let l=s.findIndex(e=>e.id===a()),u=l>=0?l:s.findIndex(e=>e.activation_state===`active`);if(u<0)return;let d=s.splice(u,1)[0],f=(c.get(d.id)??0)+1;c.set(d.id,f);let p=new AbortController,m=!1,h=()=>p.abort();o?.addEventListener(`abort`,h,{once:!0});let g=setTimeout(()=>{m=!0,p.abort()},3e4),_=null;try{let a=await fetch(Ap(e,{goal_id:d.id},t),{cache:`no-store`,signal:p.signal});if(!a.ok)_=a.status===409?`revision`:a.status>=500?`service`:`scope`;else{let e=await a.json();if(e.workspace_registry_revision!==n.registry_revision)_=`revision`;else{let t=Ep(e);!t.run_history.goals.some(e=>e.id===d.id)||t.run_history.goals.some(e=>e.id!==d.id)?_=`scope`:i()&&!o?.aborted&&r(d.id,t,null)}}}catch(e){_=m?`timeout`:e instanceof TypeError?`network`:`invalid`}finally{clearTimeout(g),o?.removeEventListener(`abort`,h)}if(!i()||o?.aborted)return;_&&[`timeout`,`network`,`service`].includes(_)&&f<3?(await new Promise(e=>setTimeout(e,f*1e3)),s.push(d)):_&&r(d.id,null,_)}}await Promise.all([l(),l()])}var Pp=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),Fp=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),Ip=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),Lp=e=>{let t=Ip(e);return t.charAt(0).toUpperCase()+t.slice(1)},Rp={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`},zp=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},Bp=(0,B.createContext)({}),Vp=()=>(0,B.useContext)(Bp),Hp=(0,B.forwardRef)(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>{let{size:l=24,strokeWidth:u=2,absoluteStrokeWidth:d=!1,color:f=`currentColor`,className:p=``}=Vp()??{},m=r??d?Number(n??u)*24/Number(t??l):n??u;return(0,B.createElement)(`svg`,{ref:c,...Rp,width:t??l??Rp.width,height:t??l??Rp.height,stroke:e??f,strokeWidth:m,className:Pp(`lucide`,p,i),...!a&&!zp(s)&&{"aria-hidden":`true`},...s},[...o.map(([e,t])=>(0,B.createElement)(e,t)),...Array.isArray(a)?a:[a]])}),Z=(e,t)=>{let n=(0,B.forwardRef)(({className:n,...r},i)=>(0,B.createElement)(Hp,{ref:i,iconNode:t,className:Pp(`lucide-${Fp(Lp(e))}`,`lucide-${e}`,n),...r}));return n.displayName=Lp(e),n},Up=Z(`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`}]]),Wp=Z(`arrow-down`,[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]),Gp=Z(`arrow-left`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]),Kp=Z(`arrow-right`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]),qp=Z(`arrow-up-down`,[[`path`,{d:`m21 16-4 4-4-4`,key:`f6ql7i`}],[`path`,{d:`M17 20V4`,key:`1ejh1v`}],[`path`,{d:`m3 8 4-4 4 4`,key:`11wl7u`}],[`path`,{d:`M7 4v16`,key:`1glfcx`}]]),Jp=Z(`arrow-up`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),Yp=Z(`badge-check`,[[`path`,{d:`M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z`,key:`3c2336`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),Xp=Z(`bell`,[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}]]),Zp=Z(`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`}]]),Qp=Z(`braces`,[[`path`,{d:`M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1`,key:`ezmyqa`}],[`path`,{d:`M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1`,key:`e1hn23`}]]),$p=Z(`calendar-clock`,[[`path`,{d:`M16 14v2.2l1.6 1`,key:`fo4ql5`}],[`path`,{d:`M16 2v4`,key:`4m81vk`}],[`path`,{d:`M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5`,key:`1osxxc`}],[`path`,{d:`M3 10h5`,key:`r794hk`}],[`path`,{d:`M8 2v4`,key:`1cmpym`}],[`circle`,{cx:`16`,cy:`16`,r:`6`,key:`qoo3c4`}]]),em=Z(`check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),tm=Z(`chevron-down`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),nm=Z(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),rm=Z(`chevron-up`,[[`path`,{d:`m18 15-6-6-6 6`,key:`153udz`}]]),im=Z(`circle-alert`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`12`,x2:`12`,y1:`8`,y2:`12`,key:`1pkeuh`}],[`line`,{x1:`12`,x2:`12.01`,y1:`16`,y2:`16`,key:`4dfq90`}]]),am=Z(`circle-check`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),om=Z(`clipboard-check`,[[`rect`,{width:`8`,height:`4`,x:`8`,y:`2`,rx:`1`,ry:`1`,key:`tgr4d6`}],[`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`,key:`116196`}],[`path`,{d:`m9 14 2 2 4-4`,key:`df797q`}]]),sm=Z(`code-xml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),cm=Z(`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`}]]),lm=Z(`database`,[[`ellipse`,{cx:`12`,cy:`5`,rx:`9`,ry:`3`,key:`msslwz`}],[`path`,{d:`M3 5V19A9 3 0 0 0 21 19V5`,key:`1wlel7`}],[`path`,{d:`M3 12A9 3 0 0 0 21 12`,key:`mv7ke4`}]]),um=Z(`download`,[[`path`,{d:`M12 15V3`,key:`m9g1x1`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`path`,{d:`m7 10 5 5 5-5`,key:`brsn70`}]]),dm=Z(`ellipsis`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]]),fm=Z(`external-link`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),pm=Z(`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`}]]),mm=Z(`file-braces`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1`,key:`1oajmo`}],[`path`,{d:`M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1`,key:`mpwhp6`}]]),hm=Z(`file-check-corner`,[[`path`,{d:`M10.5 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v6`,key:`g5mvt7`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`m14 20 2 2 4-4`,key:`15kota`}]]),gm=Z(`file-text`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),_m=Z(`git-branch`,[[`path`,{d:`M15 6a9 9 0 0 0-9 9V3`,key:`1cii5b`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}]]),vm=Z(`git-compare-arrows`,[[`circle`,{cx:`5`,cy:`6`,r:`3`,key:`1qnov2`}],[`path`,{d:`M12 6h5a2 2 0 0 1 2 2v7`,key:`1yj91y`}],[`path`,{d:`m15 9-3-3 3-3`,key:`1lwv8l`}],[`circle`,{cx:`19`,cy:`18`,r:`3`,key:`1qljk2`}],[`path`,{d:`M12 18H7a2 2 0 0 1-2-2V9`,key:`16sdep`}],[`path`,{d:`m9 15 3 3-3 3`,key:`1m3kbl`}]]),ym=Z(`info`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]),bm=Z(`languages`,[[`path`,{d:`m5 8 6 6`,key:`1wu5hv`}],[`path`,{d:`m4 14 6-6 2-3`,key:`1k1g8d`}],[`path`,{d:`M2 5h12`,key:`or177f`}],[`path`,{d:`M7 2h1`,key:`1t2jsx`}],[`path`,{d:`m22 22-5-10-5 10`,key:`don7ne`}],[`path`,{d:`M14 18h6`,key:`1m8k6r`}]]),xm=Z(`layout-dashboard`,[[`rect`,{width:`7`,height:`9`,x:`3`,y:`3`,rx:`1`,key:`10lvy0`}],[`rect`,{width:`7`,height:`5`,x:`14`,y:`3`,rx:`1`,key:`16une8`}],[`rect`,{width:`7`,height:`9`,x:`14`,y:`12`,rx:`1`,key:`1hutg5`}],[`rect`,{width:`7`,height:`5`,x:`3`,y:`16`,rx:`1`,key:`ldoo1y`}]]),Sm=Z(`list-plus`,[[`path`,{d:`M16 5H3`,key:`m91uny`}],[`path`,{d:`M11 12H3`,key:`51ecnj`}],[`path`,{d:`M16 19H3`,key:`zzsher`}],[`path`,{d:`M18 9v6`,key:`1twb98`}],[`path`,{d:`M21 12h-6`,key:`bt1uis`}]]),Cm=Z(`loader-circle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),wm=Z(`maximize-2`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`m21 3-7 7`,key:`1l2asr`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M9 21H3v-6`,key:`wtvkvv`}]]),Tm=Z(`menu`,[[`path`,{d:`M4 5h16`,key:`1tepv9`}],[`path`,{d:`M4 12h16`,key:`1lakjw`}],[`path`,{d:`M4 19h16`,key:`1djgab`}]]),Em=Z(`message-circle-question-mark`,[[`path`,{d:`M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719`,key:`1sd12s`}],[`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`,key:`1u773s`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),Dm=Z(`message-square-text`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}],[`path`,{d:`M7 11h10`,key:`1twpyw`}],[`path`,{d:`M7 15h6`,key:`d9of3u`}],[`path`,{d:`M7 7h8`,key:`af5zfr`}]]),Om=Z(`minimize-2`,[[`path`,{d:`m14 10 7-7`,key:`oa77jy`}],[`path`,{d:`M20 10h-6V4`,key:`mjg0md`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M4 14h6v6`,key:`rmj7iw`}]]),km=Z(`moon`,[[`path`,{d:`M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401`,key:`kfwtm`}]]),Am=Z(`palette`,[[`path`,{d:`M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z`,key:`e79jfc`}],[`circle`,{cx:`13.5`,cy:`6.5`,r:`.5`,fill:`currentColor`,key:`1okk4w`}],[`circle`,{cx:`17.5`,cy:`10.5`,r:`.5`,fill:`currentColor`,key:`f64h9f`}],[`circle`,{cx:`6.5`,cy:`12.5`,r:`.5`,fill:`currentColor`,key:`qy21gx`}],[`circle`,{cx:`8.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`fotxhn`}]]),jm=Z(`paperclip`,[[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551`,key:`1miecu`}]]),Mm=Z(`pause`,[[`rect`,{x:`14`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`kaeet6`}],[`rect`,{x:`5`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`1wsw3u`}]]),Nm=Z(`play`,[[`path`,{d:`M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z`,key:`10ikf1`}]]),Pm=Z(`plus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]),Fm=Z(`radio`,[[`path`,{d:`M16.247 7.761a6 6 0 0 1 0 8.478`,key:`1fwjs5`}],[`path`,{d:`M19.075 4.933a10 10 0 0 1 0 14.134`,key:`ehdyv1`}],[`path`,{d:`M4.925 19.067a10 10 0 0 1 0-14.134`,key:`1q22gi`}],[`path`,{d:`M7.753 16.239a6 6 0 0 1 0-8.478`,key:`r2q7qm`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}]]),Im=Z(`refresh-cw`,[[`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,key:`v9h5vc`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}],[`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,key:`3uifl3`}],[`path`,{d:`M8 16H3v5`,key:`1cv678`}]]),Lm=Z(`rotate-ccw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),Rm=Z(`rotate-cw`,[[`path`,{d:`M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8`,key:`1p45f6`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}]]),zm=Z(`search`,[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]),Bm=Z(`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`}]]),Vm=Z(`server-cog`,[[`path`,{d:`m10.852 14.772-.383.923`,key:`11vil6`}],[`path`,{d:`M13.148 14.772a3 3 0 1 0-2.296-5.544l-.383-.923`,key:`1v3clb`}],[`path`,{d:`m13.148 9.228.383-.923`,key:`t2zzyc`}],[`path`,{d:`m13.53 15.696-.382-.924a3 3 0 1 1-2.296-5.544`,key:`1bxfiv`}],[`path`,{d:`m14.772 10.852.923-.383`,key:`k9m8cz`}],[`path`,{d:`m14.772 13.148.923.383`,key:`1xvhww`}],[`path`,{d:`M4.5 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-.5`,key:`tn8das`}],[`path`,{d:`M4.5 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-.5`,key:`1g2pve`}],[`path`,{d:`M6 18h.01`,key:`uhywen`}],[`path`,{d:`M6 6h.01`,key:`1utrut`}],[`path`,{d:`m9.228 10.852-.923-.383`,key:`1wtb30`}],[`path`,{d:`m9.228 13.148-.923.383`,key:`1a830x`}]]),Hm=Z(`server`,[[`rect`,{width:`20`,height:`8`,x:`2`,y:`2`,rx:`2`,ry:`2`,key:`ngkwjq`}],[`rect`,{width:`20`,height:`8`,x:`2`,y:`14`,rx:`2`,ry:`2`,key:`iecqi9`}],[`line`,{x1:`6`,x2:`6.01`,y1:`6`,y2:`6`,key:`16zg32`}],[`line`,{x1:`6`,x2:`6.01`,y1:`18`,y2:`18`,key:`nzw8ys`}]]),Um=Z(`settings-2`,[[`path`,{d:`M14 17H5`,key:`gfn3mx`}],[`path`,{d:`M19 7h-9`,key:`6i9tg`}],[`circle`,{cx:`17`,cy:`17`,r:`3`,key:`18b49y`}],[`circle`,{cx:`7`,cy:`7`,r:`3`,key:`dfmy0x`}]]),Wm=Z(`shield-check`,[[`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`}]]),Gm=Z(`sliders-horizontal`,[[`path`,{d:`M10 5H3`,key:`1qgfaw`}],[`path`,{d:`M12 19H3`,key:`yhmn1j`}],[`path`,{d:`M14 3v4`,key:`1sua03`}],[`path`,{d:`M16 17v4`,key:`1q0r14`}],[`path`,{d:`M21 12h-9`,key:`1o4lsq`}],[`path`,{d:`M21 19h-5`,key:`1rlt1p`}],[`path`,{d:`M21 5h-7`,key:`1oszz2`}],[`path`,{d:`M8 10v4`,key:`tgpxqk`}],[`path`,{d:`M8 12H3`,key:`a7s4jb`}]]),Km=Z(`sparkles`,[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]]),qm=Z(`square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),Jm=Z(`sun`,[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]),Ym=Z(`test-tube-diagonal`,[[`path`,{d:`M21 7 6.82 21.18a2.83 2.83 0 0 1-3.99-.01a2.83 2.83 0 0 1 0-4L17 3`,key:`1ub6xw`}],[`path`,{d:`m16 2 6 6`,key:`1gw87d`}],[`path`,{d:`M12 16H4`,key:`1cjfip`}]]),Xm=Z(`trash-2`,[[`path`,{d:`M10 11v6`,key:`nco0om`}],[`path`,{d:`M14 11v6`,key:`outv1u`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`,key:`miytrc`}],[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`,key:`e791ji`}]]),Zm=Z(`triangle-alert`,[[`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`}]]),Qm=Z(`unlink`,[[`path`,{d:`m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71`,key:`yqzxt4`}],[`path`,{d:`m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71`,key:`4qinb0`}],[`line`,{x1:`8`,x2:`8`,y1:`2`,y2:`5`,key:`1041cp`}],[`line`,{x1:`2`,x2:`5`,y1:`8`,y2:`8`,key:`14m1p5`}],[`line`,{x1:`16`,x2:`16`,y1:`19`,y2:`22`,key:`rzdirn`}],[`line`,{x1:`19`,x2:`22`,y1:`16`,y2:`16`,key:`ox905f`}]]),$m=Z(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]);function eh(e){return/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(e)||e.startsWith(`//`)}function th(e){return[`localhost`,`127.0.0.1`,`::1`,`[::1]`].includes(e)}function nh(e,t,n){let r=e.trim();if(!r)return{error:`status URL is empty`};let i;try{i=new URL(r,t)}catch{return{error:`status URL is invalid`}}let a=!eh(r),o=th(i.hostname);return!a&&!o?{error:`${n} must be relative or loopback`}:{source:{isLoopback:o,isRelative:a,url:r}}}function rh(e,t){return nh(e,t,`statusUrl`)}function ih(e,t){let n=nh(e,t,`Ops statusUrl`);return n.error?{error:`${n.error}; use showcase mode for public links.`}:n}function ah(e,t,n){let r=new URL(e,n);return r.searchParams.set(`goal_activation`,t),r.toString()}function oh(e,t){if(!t||!e.isLoopback)return null;try{let n=new URL(e.url,window.location.href),r=new URL(t,n.origin);return th(r.hostname)?r.toString():null}catch{return null}}function sh(e,t){return{detailUrl:oh(t,e.local_dashboard_api?.periodic_report_detail_url),indexUrl:oh(t,e.local_dashboard_api?.periodic_report_index_url)}}async function ch(e,t){let n=new URL(e);n.searchParams.set(`goal_id`,t),n.searchParams.set(`limit`,`100`),n.searchParams.set(`offset`,`0`);let r=await fetch(n,{cache:`no-store`});if(!r.ok)throw Error(`HTTP ${r.status} while loading published reports`);return bp.parse(await r.json()).periodic_reports}async function lh(e,t){let n=new URL(e);Object.entries(t).forEach(([e,t])=>n.searchParams.set(e,t));let r=await fetch(n,{cache:`no-store`});if(!r.ok)throw Error(`HTTP ${r.status} while loading published report detail`);return Sp.parse(await r.json()).projection}function uh(e,t,n){let r=e.find(e=>e.agentId===t&&e.available)??e.find(e=>e.agentId===n&&e.available)??e.find(e=>e.available);if(!r)throw Error(`Chat requires at least one available route`);return r}function dh(e){return!!(e&&typeof e==`object`&&e.session_invalidated===!0)}var fh=``.replace(/\/+$/,``);function ph(e){return!fh||/^https?:\/\//.test(e)?e:new URL(e,`${fh}/`).toString()}var mh=Y({todo_id:G().nullable(),role:G().nullable(),status:G(),priority:G().nullable(),text:G(),action_kind:G().nullable(),task_class:G().nullable(),claimed_by:G().nullable(),evidence:G().nullable()}),hh=Y({goal_id:G(),title:G(),objective:G(),status:G(),waiting_on:G().nullable(),severity:G().nullable(),gate:G(),next_action:G(),top_todo:mh.nullable(),todos:J(mh),evidence:J(G()),quota:Y({state:G().nullable(),spent_slots:K().nullable(),allowed_slots:K().nullable(),reason:G().nullable()})});Y({ok:q(),schema_version:X(`loopx_chat_status_v0`),selected_goal_id:G().nullable(),goal_count:K(),goals:J(hh)});var gh=Y({ok:X(!0),schema_version:_d([`loopx_chat_capabilities_v0`,`loopx_chat_capabilities_v1`]),agent_backend:G(),sandbox:G(),approval_policy:G(),todo_write:G(),goal_subagent_configuration:G().optional(),goal_id:G().nullable(),streaming:q().optional(),resume:q().optional(),interrupt:q().optional(),typed_actions:q().optional(),action_kinds:J(G()).optional(),adapters:J(Y({agent_id:G(),display_name:G(),adapter_kind:G(),available:q(),streaming:q(),resume:q(),interrupt:q(),location:G().optional(),source:G().optional(),tool_calls:q().optional(),trust_scope:G().optional()})).optional(),lark_cli:Y({available:q(),source:G(),version:G().nullable(),error_code:G().nullable()}).optional()}),_h=Y({kind:X(`todo`),text:G(),priority:_d([`P0`,`P1`,`P2`]),rationale:G()}),vh=Y({operation:_d([`merge`,`release`,`deploy`,`delete`,`payment`]),target:G().min(1).max(160),summary:G().max(300)}),yh=Y({schema_version:X(`loopx_chat_agent_response_v0`),message:G(),proposals:J(_h),protected_action:vh.nullable().optional().default(null),gate:Y({kind:G(),summary:G(),next_action:G()}).nullable()}),bh=Y({closed:X(!0),ok:X(!0),session_id:G().min(1)});Y({dry_run:X(!0),ok:X(!0),preview_id:G().min(1),todo:Y({goal_id:G().min(1),text:G(),todo_id:G().optional()})});var xh=Y({schema_version:X(`loopx_chat_todo_receipt_v0`),receipt_id:G().min(1),preview_id:G().min(1),goal_id:G().min(1),todo_id:G().min(1),status:X(`applied`),outcome:_d([`todo_added`,`todo_already_exists`]),already_exists:q(),preview_revision:G().nullable()});Y({applied:X(!0),ok:X(!0),receipt:xh,todo:Y({text:G(),todo_id:G()})});var Sh=Y({model_config:Y({model:G(),reasoning_effort:G().optional()}).optional(),mode:G(),spawn_allowed:q(),max_children:K().int().nonnegative(),allowed_domains:J(G()).optional().default([])}).passthrough(),Ch=Y({ok:X(!0),dry_run:q(),execute:q(),written:q(),changed:q(),goal_id:G().min(1),changed_fields:J(G()),before:Y({orchestration:Sh}).passthrough(),after:Y({orchestration:Sh}).passthrough(),preview_id:G().min(1),feature_summary:Y({multi_subagent:_d([`off`,`enabled`])}).passthrough(),global_sync:Y({required:q(),executed:q(),readback:Y({status:G(),verified:q()}).passthrough()}).passthrough()}),wh=Y({id:G().min(1),outcome:_d([`approved`,`rejected`,`cancelled`]),projectionVerified:q().nullable(),proposal:_h,receipt:xh.nullable()}).superRefine((e,t)=>{e.outcome===`approved`&&!e.receipt&&t.addIssue({code:`custom`,message:`approved decision history requires a Todo receipt`,path:[`receipt`]}),e.outcome!==`approved`&&e.receipt&&t.addIssue({code:`custom`,message:`zero-write decision history must not include a Todo receipt`,path:[`receipt`]})});Y({schema_version:X(`loopx_chat_decision_history_v0`),goal_id:G().min(1),decisions:J(wh).max(24)});var Th=class extends Error{payload;constructor(e,t){super(e),this.payload=t}},Eh=_d([`goal.create`,`goal.update`,`goal.lifecycle`,`todo.create`,`todo.update`,`agent.bind`,`heartbeat.bind`,`monitor.create`,`monitor.update`,`gate.resolve`,`run.correct`]),Dh=Y({schema_version:X(`loopx_chat_action_proposal_v1`),proposal_id:G().min(1),action_kind:Eh,summary:G().min(1),normalized_parameters:hd(G(),rd()),context:hd(G(),rd()),expected_state_fingerprint:G().min(1),permission_classification:G().min(1),validation_evidence:J(G().refine(e=>e.trim().length>0,`Validation evidence must be non-blank text`)),available_transitions:J(_d([`apply`,`cancel`,`regenerate`,`reject`,`defer`])),status:_d([`preview_ready`,`applying`,`gated`,`failed`,`rejected`,`deferred`,`cancelled`,`stale`,`applied`]),receipt:hd(G(),rd()).nullable(),stale:hd(G(),rd()).nullable(),gate:hd(G(),rd()).nullable().optional(),error:hd(G(),rd()).nullable().optional(),checkpoint:hd(G(),rd()).nullable().optional(),regenerated_from:G().nullable().optional(),created_at:G(),updated_at:G()}),Oh=Y({ok:X(!0),proposal:Dh});async function kh(e){let t=await Fh(`/api/actions/preview`,{method:`POST`,body:JSON.stringify({action_kind:e.actionKind,context:e.context,idempotency_key:e.idempotencyKey,normalized_parameters:e.normalizedParameters,summary:e.summary})});return Oh.parse(t).proposal}var Ah=Y({ok:X(!0),schema_version:X(`loopx_chat_action_list_v1`),proposals:J(Dh)});async function jh(e={}){let t=new URLSearchParams;e.contextKind&&t.set(`context_kind`,e.contextKind),e.goalId&&t.set(`goal_id`,e.goalId);let n=t.size>0?`?${t.toString()}`:``;return Ah.parse(await Fh(`/api/actions${n}`)).proposals}async function Mh(e){let t=await Fh(`/api/actions/${encodeURIComponent(e)}/apply`,{method:`POST`,body:`{}`});return Y({ok:X(!0),proposal:Dh,turn:hd(G(),rd()).nullable().optional()}).parse(t)}async function Nh(e){return Oh.parse(await Fh(`/api/actions/${encodeURIComponent(e)}/cancel`,{method:`POST`,body:`{}`})).proposal}async function Ph(e,t){return Oh.parse(await Fh(`/api/actions/${encodeURIComponent(e)}/${t}`,{method:`POST`,body:`{}`})).proposal}async function Fh(e,t){let n;try{n=await fetch(ph(e),{cache:`no-store`,...t,headers:{"Content-Type":`application/json`,...t?.headers}})}catch{throw new Th(`无法连接 LoopX Chat 服务。请确认 Dashboard 与 Chat 服务已启动且来自同一版本。`,{error_code:`chat_api_unavailable`})}let r=await n.text(),i=null;if(r.trim())try{i=JSON.parse(r)}catch{i=null}let a=i&&typeof i==`object`&&!Array.isArray(i)?i:{};if(!n.ok){let e=(a.proposal&&typeof a.proposal==`object`?a.proposal:null)?.status===`stale`?`来源状态已变化,请重新生成预览。`:null,t=n.status>=500?`LoopX Chat 服务暂时不可用(HTTP ${n.status})。请确认 Dashboard 与 Chat 服务已启动且来自同一版本。`:`LoopX Chat 请求失败(HTTP ${n.status})。`;throw new Th(e??String(a.error||t),Object.keys(a).length?a:{error_code:`chat_api_unavailable`,http_status:n.status})}if(i===null)throw new Th(`LoopX Chat 服务返回了无法识别的响应(HTTP ${n.status})。请确认 Dashboard 与 Chat 服务来自同一版本。`,{error_code:`invalid_chat_api_response`,http_status:n.status});return i}async function Ih(){return gh.parse(await Fh(`/api/chat/capabilities`))}async function Lh(e){return Fh(`/api/chat/projection-messages`,{method:`POST`,body:JSON.stringify({answer:e.answer,context_kind:e.contextKind,goal_id:e.goalId,question:e.question})})}async function Rh(e,t=`codex`,n=`resume_latest`,r=`goal`){return Fh(`/api/chat/sessions`,{method:`POST`,body:JSON.stringify({goal_id:e,agent_id:t,mode:n,context_kind:r})})}async function zh(e){return Fh(`/api/chat/sessions/${e}`)}async function Bh(e){let t=new URLSearchParams;return e.agentId&&t.set(`agent_id`,e.agentId),e.channelId&&t.set(`channel_id`,e.channelId),e.goalId&&t.set(`goal_id`,e.goalId),Fh(`/api/chat/sessions?${t.toString()}`)}function Vh(e){let t=new Map;for(let n of e)for(let e of n.messages)t.set(e.message_id,e);return[...t.values()].sort((e,t)=>e.created_at.localeCompare(t.created_at)||e.message_id.localeCompare(t.message_id))}async function Hh(e){let t=await Bh(e),n=await Promise.all(t.sessions.map(e=>zh(e.session_id)));return{messages:Vh(n),sessions:t.sessions,snapshots:n}}async function Uh(e,t,n,r=[]){return Fh(`/api/chat/sessions/${e}/turns`,{method:`POST`,body:JSON.stringify({message:t,client_turn_id:n,...r.length?{attachments:r.map(e=>({data_url:e.dataUrl,id:e.id,mime_type:e.mimeType,name:e.name,size:e.size}))}:{}})})}function Wh(e){let t=e.split(` -`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(` -`);if(!t)return null;try{let e=JSON.parse(t);return!e.kind||!e.payload||typeof e.payload!=`object`?null:{event_id:String(e.event_id??``),sequence:Number(e.sequence??0),kind:String(e.kind),created_at:String(e.created_at??``),payload:e.payload}}catch{return null}}async function Gh(e,t,n){let r=``,i=0,a=!1;for(;!a&&i<4;){let o=typeof window>`u`?`http://127.0.0.1`:window.location.origin,s=new URL(ph(e),o);r&&s.searchParams.set(`after`,r);try{let e=await fetch(s,{cache:`no-store`,headers:{Accept:`text/event-stream`},signal:n});if(!e.ok||!e.body)throw new Th(`SSE HTTP ${e.status}`,{status:e.status});let o=e.body.getReader(),c=new TextDecoder,l=``;for(;;){let{done:e,value:n}=await o.read();l+=c.decode(n,{stream:!e}).replaceAll(`\r -`,` -`);let i=l.indexOf(` - -`);for(;i>=0;){let e=l.slice(0,i);l=l.slice(i+2);let n=Wh(e);n&&(n.event_id&&(r=n.event_id),t(n),a=[`turn.completed`,`turn.interrupted`,`turn.failed`].includes(n.kind)),i=l.indexOf(` - -`)}if(e||a)break}i=a?i:i+1}catch(e){if(n?.aborted||(i+=1,i>=4))throw e;await new Promise(e=>globalThis.setTimeout(e,250*2**(i-1)))}}if(!a)throw new Th(`Agent 事件流连接已断开。`,{reconnect_attempts:i})}async function Kh(e,t){return Fh(`/api/chat/sessions/${e}/turns/${t}/interrupt`,{method:`POST`,body:`{}`})}async function qh(e,t,n={}){let r=await Uh(e,t,n.clientTurnId??crypto.randomUUID(),n.attachments);return n.onPhase?.(`turn.accepted`,r.turn_id),Jh(e,r.turn_id,r.events_url,n)}async function Jh(e,t,n,r={}){let i=null,a={failure:null,interrupted:null};try{await Gh(n,e=>{r.onPhase?.(e.kind,t),(e.kind===`answer.delta`||e.kind===`assistant.delta`)&&r.onDelta?.(String(e.payload.text??``)),e.kind===`agent.phase`&&r.onActivity?.(String(e.payload.label??`Agent 正在处理`)),e.kind===`turn.completed`&&(i=e.payload.response),e.kind===`turn.failed`&&(a.failure=e.payload),e.kind===`turn.interrupted`&&(a.interrupted=e.payload)},r.signal)}catch(i){throw i instanceof Th&&!r.signal?.aborted?new Th(i.message,{...i.payload,events_url:n,reconnectable:!0,session_id:e,turn_id:t}):i}if(a.failure)throw new Th(String(a.failure.message||`Agent 回合失败。`),a.failure);if(a.interrupted)throw new Th(`Agent 回合已中断。`,{...a.interrupted,error_code:`turn_interrupted`,session_id:e,turn_id:t});return{response:yh.parse(i),sessionId:e,turnId:t}}async function Yh(e,t,n={}){return Jh(e,t,`/api/chat/sessions/${e}/turns/${t}/events`,n)}async function Xh(e){let t=bh.parse(await Fh(`/api/chat/sessions/${e}`,{keepalive:!0,method:`DELETE`}));if(t.session_id!==e)throw new Th(`Agent 会话关闭回执与本次请求不一致。`,{session_id:t.session_id});return t}async function Zh(e){return Fh(`/api/chat/sessions/${e}/resume`,{method:`POST`,body:`{}`})}function Qh(e){return{goal_id:e.goalId,enabled:e.enabled,...e.modelConfig===void 0?{}:{model_config:e.modelConfig},...e.enabled?{max_children:e.maxChildren,allowed_domains:e.allowedDomains}:{}}}function $h(e,t){let n=e.after.orchestration,r=[...new Set(t.allowedDomains)],i=e.feature_summary.multi_subagent===`enabled`;if(!(e.goal_id===t.goalId&&i===t.enabled&&(t.modelConfig===void 0||JSON.stringify(n.model_config??null)===JSON.stringify(t.modelConfig))&&(t.enabled?n.max_children===t.maxChildren&&JSON.stringify(n.allowed_domains)===JSON.stringify(r):n.spawn_allowed===!1&&n.max_children===0)))throw new Th(`Goal 子代理配置回执与本次请求不一致,界面已停止更新。`,{after:e.after,goal_id:e.goal_id});return e}async function eg(e){let t=Ch.parse(await Fh(`/api/chat/goal-subagents/dry-run`,{method:`POST`,body:JSON.stringify(Qh(e))}));if(!t.dry_run||t.execute||t.written)throw new Th(`Goal 子代理预览返回了非预览回执,已停止进入确认状态。`,{result:t});return $h(t,e)}async function tg(e,t){let n=Ch.parse(await Fh(`/api/chat/goal-subagents/apply`,{method:`POST`,body:JSON.stringify({...Qh(e),preview_id:t})}));if(n.preview_id!==t||n.dry_run||!n.execute)throw new Th(`Goal 子代理写入回执与本次确认不一致,界面已停止更新。`,{result:n});if(n.changed&&(!n.written||!n.global_sync.executed||!n.global_sync.readback.verified))throw new Th(`Goal 子代理设置未通过共享状态读回验证。`,{result:n});return $h(n,e)}var ng=Y({ok:X(!0),targets:J(Y({enabled:q(),provider:G(),target_name:G()}))});async function rg(){return ng.parse(await Fh(`/api/chat/goal-channel/targets`)).targets}var ig=Y({ok:q(),blocker:G().optional(),public_summary:G().optional(),status:G().optional()});async function ag(e){return ig.parse(await Fh(`/api/chat/goal-channel/setup`,{method:`POST`,body:JSON.stringify({execute:e.execute,goal_id:e.goalId,target:e.target})}))}async function og(e){return ig.parse(await Fh(`/api/chat/goal-channel/configure`,{method:`POST`,body:JSON.stringify({auto_notify_human_gates:e.autoNotify,goal_id:e.goalId})}))}var sg=Y({schema_version:X(`periodic_report_schedule_v0`),schedule_id:G(),rrule:G(),timezone:G()});Y({schema_version:X(`periodic_report_machine_defaults_v0`),enabled:q(),inheritance:X(`live_machine_default`),profile_preset:G().optional(),route_ref:G().optional(),timezone:G(),schedule:sg.nullable().optional()});var cg=Y({schema_version:X(`loopx_machine_configuration_v0`),namespaces:hd(G(),hd(G(),rd()))}),lg=Y({namespace:G(),title:G(),description:G(),schema_versions:J(G()).min(1),configuration_template:hd(G(),rd()),template_status:_d([`ready`,`schema_only`])}),ug=Y({schema_version:X(`machine_configuration_catalog_v0`),namespaces:J(lg)}),dg=Y({key:G(),label:G(),description:G(),input_kind:_d([`boolean`,`number`,`select`,`string_list`,`text`,`periodic_report_schedule`]),nullable:q().optional(),required:q(),minimum:K().int().optional(),maximum:K().int().optional(),options:J(G()).optional()}),fg=Y({schema_version:X(`capability_configuration_editor_v0`),editable:q(),supported_scopes:J(_d([`goal`,`machine`])),writable_scopes:J(_d([`goal`,`machine`])),fields:J(dg),read_only_reason:G().optional()}),pg=Y({schema_version:X(`capability_configuration_catalog_v0`),capabilities:J(Y({capability_id:G(),display_name:G(),description:G(),available_scopes:J(_d([`goal`,`machine`])),machine_namespace:G().optional(),goal_feature_id:G().optional(),effective_value_policy:X(`goal_override_over_live_machine_default`).optional(),availability:G().optional(),default:hd(G(),rd()).optional(),current:hd(G(),rd()).optional(),machine_current:hd(G(),rd()).optional(),effective_configuration:Y({schema_version:X(`capability_configuration_resolution_v0`),capability_id:G(),source:_d([`goal_override`,`machine_default`,`capability_default`,`not_configured`]),configuration:hd(G(),rd()).nullable(),inherited:q(),goal_override_present:q(),machine_default_present:q(),effective_revision:G()}).optional(),documentation:hd(G(),rd()).optional(),context_contribution:Y({supported_phases:J(_d([`before_plan`,`before_delegate`,`after_delegate_result`])),target:X(`coordinator`),activation:X(`with_capability`),receipt_required:X(!0)}).optional(),configuration_editor:fg}))}),mg=Y({ok:X(!0),schema_version:X(`goal_configuration_inspection_v0`),status:X(`configured`),goal_id:G(),revision:G(),available_capabilities:J(G()),capability_catalog:pg}),hg=Y({ok:X(!0),goal_id:G(),capability_id:G(),changed_fields:J(G()),goal_configuration:hd(G(),rd()).nullable(),capability_catalog:pg}),gg=hg.extend({schema_version:X(`goal_configuration_update_plan_v0`),status:X(`preview`),action:_d([`create`,`update`,`delete`,`unchanged`]),current_revision:G(),desired_revision:G(),base_revision:G(),plan_revision:G(),writes_required:K().int().nonnegative()}),_g=ld([hg.extend({schema_version:X(`goal_configuration_transaction_v0`),status:_d([`applied`,`unchanged`]),plan_revision:G(),applied_revision:G(),readback_verified:X(!0)}),Y({ok:X(!1),schema_version:X(`goal_configuration_transaction_v0`),status:X(`partial_write`),goal_id:G(),capability_id:G(),plan_revision:G(),applied_revision:G().nullable(),source_written:X(!0),shared_sync_pending:X(!0),readback_verified:q(),changed_fields:J(G()),goal_configuration:hd(G(),rd()).nullable(),capability_catalog:pg,error:G(),recommended_action:G()})]),vg=Y({ok:X(!0),available_namespaces:J(G()),namespace_catalog:ug.optional().default({schema_version:`machine_configuration_catalog_v0`,namespaces:[]}),capability_catalog:pg,changed_namespaces:J(G()).optional().default([]),machine_configuration:cg.nullable().optional()}),yg=vg.extend({schema_version:X(`machine_configuration_inspection_v0`),status:_d([`configured`,`absent`]),revision:G()}),bg=vg.extend({schema_version:X(`machine_configuration_update_plan_v0`),status:X(`preview`),action:_d([`create`,`update`,`delete`,`unchanged`]),current_revision:G(),desired_revision:G(),plan_revision:G(),writes_required:K().int().nonnegative(),machine_configuration:cg.nullable()}),xg=vg.extend({schema_version:X(`machine_configuration_transaction_v0`),status:_d([`applied`,`unchanged`]),plan_revision:G(),transaction_id:G().nullable(),readback_verified:X(!0),rollback_available:q(),applied_revision:G().optional(),prior_revision:G().optional()}),Sg=vg.extend({schema_version:X(`machine_configuration_rollback_plan_v0`),status:X(`preview`),action:_d([`delete`,`restore`,`unchanged`,`blocked`]),reason:G(),transaction_id:G(),plan_revision:G(),rollback_allowed:q(),writes_required:K().int().nonnegative()}),Cg=vg.extend({schema_version:X(`machine_configuration_rollback_receipt_v0`),status:_d([`rolled_back`,`unchanged`]),transaction_id:G(),plan_revision:G(),rollback_id:G().nullable(),readback_verified:X(!0)});async function wg(){return yg.parse(await Fh(`/api/chat/machine-configuration`))}async function Tg(e){let t=new URLSearchParams({goal_id:e});return mg.parse(await Fh(`/api/chat/goal-configuration?${t.toString()}`))}async function Eg(e,t,n){return gg.parse(await Fh(`/api/chat/goal-configuration/preview`,{method:`POST`,body:JSON.stringify({goal_id:e,capability_id:t,configuration:n})}))}async function Dg(e,t,n,r){return _g.parse(await Fh(`/api/chat/goal-configuration/apply`,{method:`POST`,body:JSON.stringify({goal_id:e,capability_id:t,configuration:n,expected_plan_revision:r})}))}async function Og(e,t){return bg.parse(await Fh(`/api/chat/machine-configuration/preview`,{method:`POST`,body:JSON.stringify({namespace:e,namespace_configuration:t})}))}async function kg(e,t,n){return xg.parse(await Fh(`/api/chat/machine-configuration/apply`,{method:`POST`,body:JSON.stringify({expected_plan_revision:n,namespace:e,namespace_configuration:t})}))}async function Ag(e){return bg.parse(await Fh(`/api/chat/machine-configuration/preview`,{method:`POST`,body:JSON.stringify({namespace:e,operation:`remove`})}))}async function jg(e,t){return xg.parse(await Fh(`/api/chat/machine-configuration/apply`,{method:`POST`,body:JSON.stringify({expected_plan_revision:t,namespace:e,operation:`remove`})}))}async function Mg(e){return Sg.parse(await Fh(`/api/chat/machine-configuration/rollback`,{method:`POST`,body:JSON.stringify({execute:!1,transaction_id:e})}))}async function Ng(e,t){return Cg.parse(await Fh(`/api/chat/machine-configuration/rollback`,{method:`POST`,body:JSON.stringify({execute:!0,expected_plan_revision:t,transaction_id:e})}))}var Pg=Y({ok:X(!0),goals:J(Y({goal_id:G(),repository:Y({branch:G(),identity:G(),label:G(),read_only:X(!0)})}))});async function Fg(){return Pg.parse(await Fh(`/api/chat/goals/contexts`)).goals}var Ig=Y({ok:X(!0),apps:J(Y({active:q(),app_ref:G(),brand:G(),health_error_code:G().nullable().default(null),label:G(),ready:q(),reply_ready:q().default(!1)}))});async function Lg(){return Ig.parse(await Fh(`/api/chat/lark/apps`)).apps}var Rg=Y({ok:X(!0),app_ref:G(),error:G().nullable(),setup_id:G(),status:_d([`starting`,`waiting_for_feishu`,`ready`,`failed`,`cancelled`]),verification_url:G().url().nullable()});async function zg(e){return Rg.parse(await Fh(`/api/chat/lark/app-setups`,{method:`POST`,body:JSON.stringify({app_ref:e.appRef,brand:e.brand})}))}async function Bg(e){return Rg.parse(await Fh(`/api/chat/lark/app-setups/${encodeURIComponent(e)}`))}async function Vg(e){return Rg.parse(await Fh(`/api/chat/lark/app-setups/${encodeURIComponent(e)}`,{method:`DELETE`}))}var Hg=[`invalid_event`,`binding_unavailable`,`chat_mismatch`,`topic_mismatch`,`route_ambiguous`,`self_message`,`invalid_routing_state`,`not_addressed`],Ug=Y({ok:X(!0),chats:J(Y({chat_id:G(),chat_name:G()}))});async function Wg(e,t){let n=new URLSearchParams({app_ref:e});return t&&n.set(`query`,t),Ug.parse(await Fh(`/api/chat/lark/chats?${n.toString()}`)).chats}var Gg=Y({ok:X(!0),connections:J(Y({conversation_kind:_d([`goal`,`manager`]).default(`goal`),agent_id:G().nullable().default(null),connection_id:G(),app_label:G(),app_ref:G(),capture_scope:_d([`addressed_only`,`configured_chat_all`]).default(`addressed_only`),chat_name:G(),enabled:q(),goal_id:G(),goal_title:G(),health_error_code:G().nullable().default(null),history_permission_guidance:Y({action:X(`enable_application_scopes_and_publish`),api_document_url:G().url(),capability:X(`group_history_pagination`),identity:X(`bot`),required_scopes:pd([X(`im:message.group_msg`),X(`im:message.group_msg.include_bot:read`)]),schema_version:X(`lark_bot_group_history_permission_guidance_v0`)}).nullable().default(null),incoming_mode:_d([`mentions`,`all`]),ingress_mode:_d([`live_steering`,`session_queue`,`async_inbox`,`direct_session`]).default(`async_inbox`),event_count:K().int().nonnegative().default(0),last_event_reason:_d(Hg).nullable().default(null).catch(null),last_event_status:G().nullable().default(null),listener_error_code:G().nullable().default(null),listener_status:_d([`starting`,`listening`,`retrying`,`stopped`]).nullable().default(null),replied_count:K().int().nonnegative().default(0),reply_ready:q().default(!1),reply_mode:X(`topic_reply`),session_bound:q().default(!1),target_ref:G(),topic_name:G(),topic_setup_required:q()}))});async function Kg(){return Gg.parse(await Fh(`/api/chat/lark/connections`)).connections}async function qg(e){return ig.parse(await Fh(`/api/chat/lark/connections`,{method:`POST`,body:JSON.stringify({...e.agentBindings?{agent_bindings:e.agentBindings.map(e=>({agent_id:e.agentId,app_ref:e.appRef}))}:{},...e.agentId?{agent_id:e.agentId}:{},...e.appRef?{app_ref:e.appRef}:{},...e.connectionId?{connection_id:e.connectionId}:{},conversation_kind:e.conversationKind??`goal`,capture_scope:e.captureScope,chat_id:e.chatId,chat_name:e.chatName,execute:e.execute,goal_id:e.goalId,incoming_mode:e.incomingMode,ingress_mode:e.ingressMode,reply_mode:e.replyMode})}))}async function Jg(e,t){let n=new URLSearchParams({goal_id:e,connection_id:t});return ig.parse(await Fh(`/api/chat/lark/connections?${n.toString()}`,{method:`DELETE`}))}function Yg(e){return{loadedUrl:null,projectionRevision:0,requestedUrl:e,selectionRevision:0,requestGeneration:0}}function Xg(e,t){return e.selectionRevision+=1,e.requestedUrl=t,e.selectionRevision}function Zg(e,t,n){if(n.background)return e.requestedUrl!==null||e.loadedUrl!==t?null:(e.requestGeneration+=1,{background:!0,projectionRevision:e.projectionRevision,selectionRevision:e.selectionRevision,url:t,generation:e.requestGeneration});let r=n.selectionRevision??e.selectionRevision+1;return n.selectionRevision!==void 0&&e.selectionRevision!==r?null:(e.selectionRevision=r,e.projectionRevision+=1,e.requestedUrl=t,e.requestGeneration+=1,{background:!1,projectionRevision:e.projectionRevision,selectionRevision:r,url:t,generation:e.requestGeneration})}function Qg(e,t){return t.generation===e.requestGeneration&&e.projectionRevision===t.projectionRevision&&e.selectionRevision===t.selectionRevision}function $g(e,t){return Qg(e,t)&&(!t.background||e.requestedUrl===null&&e.loadedUrl===t.url)}function e_(e,t,n){return t.get(e)===n}function t_(e,t,n,r){return e.filter(e=>e_(r(e),n,t))}function n_(e,t,n){let r=new Set,i=[];for(let a of[...e,...t]){let e=n(a);e==null||r.has(e)||(r.add(e),i.push(a))}return i}var r_=[`runs_24h`,`runs_7d`,`quota_spend_slots_24h`,`quota_spend_slots_7d`,`automation_run_count_24h`,`automation_run_count_7d`,`progress_signal_run_count_24h`,`progress_signal_run_count_7d`],i_=[`input_tokens_24h`,`input_tokens_7d`,`output_tokens_24h`,`output_tokens_7d`,`cache_tokens_24h`,`cache_tokens_7d`,`cost_usd_24h`,`cost_usd_7d`,`duration_ms_24h`,`duration_ms_7d`],a_=[`accounting`,`decision`,`evidence`,`state`,`work`],o_={accounting:0,decision:0,evidence:0,state:0,work:0},s_={runs_24h:0,runs_7d:0,quota_spend_slots_24h:0,quota_spend_slots_7d:0,automation_run_count_24h:0,automation_run_count_7d:0,progress_signal_run_count_24h:0,progress_signal_run_count_7d:0};function c_(e,t){let n={...e};for(let r of r_)n[r]=(Number(e[r])||0)+(Number(t[r])||0);for(let r of i_)(e[r]!==void 0||t[r]!==void 0)&&(n[r]=(e[r]??0)+(t[r]??0));return n}function l_(e,t){return!e.length||t<=0?e:e.map(e=>({...e,project_share_24h:Math.round((Number(e.runs_24h)||0)/t*1e3)/1e3}))}function u_(e,t){let n={...e};for(let r of a_)n[r]=(e[r]??0)+(t[r]??0);return n}function d_(e){let t={events_24h:0,events_7d:0,by_class_24h:{...o_},by_class_7d:{...o_}};for(let n of e)t.events_24h+=n.events_24h,t.events_7d+=n.events_7d,t.by_class_24h=u_(t.by_class_24h,n.by_class_24h),t.by_class_7d=u_(t.by_class_7d,n.by_class_7d);return t}function f_(e,t,n){if(!e&&!t)return null;let r=t_(e?.goals??[],`active`,n,e=>e.goal_id),i=t_(t?.goals??[],`stopped`,n,e=>e.goal_id),a=n_(r,i,e=>e.goal_id),o=d_(r),s=d_(i),c={events_24h:o.events_24h+s.events_24h,events_7d:o.events_7d+s.events_7d,by_class_24h:u_(o.by_class_24h,s.by_class_24h),by_class_7d:u_(o.by_class_7d,s.by_class_7d)};return{...e??t,goals:a,sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),totals:c}}function p_(e,t,n){if(!e&&!t)return null;let r=n_([...t_(e?.items??[],`active`,n,e=>e.goal_id),...t_(t?.items??[],`stopped`,n,e=>e.goal_id)],[],e=>`${e.goal_id}:${e.decision_kind??``}:${e.decision_at??``}`),i={decision_count:(e?.summary.decision_count??0)+(t?.summary.decision_count??0),stale_count:r.filter(e=>e.stale_by_age).length,rebase_required_count:(e?.summary.rebase_required_count??0)+(t?.summary.rebase_required_count??0),fresh_count:(e?.summary.fresh_count??0)+(t?.summary.fresh_count??0)};return{...e??t,items:r,sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),summary:i}}function m_(e,t){return n_([...e,...t].sort((e,t)=>t.generated_at.localeCompare(e.generated_at)),[],e=>`${e.goal_id}:${e.generated_at}:${e.classification??``}`)}function h_(e,t,n){let r=n_(t_(e.items,`active`,n,e=>e.goal_id),t_(t.items,`stopped`,n,e=>e.goal_id),e=>e.goal_id);return{...e,item_count:r.length,items:r,needs_controller:r.filter(e=>e.waiting_on===`controller`).length,needs_codex:r.filter(e=>e.waiting_on===`codex`).length,needs_user_or_controller:r.filter(e=>[`user_or_controller`,`controller`].includes(e.waiting_on)).length,watching_external_evidence:r.filter(e=>e.waiting_on===`external_evidence`).length}}function g_(e){let t=e.todo_id?.trim()||``;return t?`${e.goal_id}:${t}`:`${e.goal_id}:synthetic:${e.role??``}:${e.index??``}:${e.text??``}`}function __(e){let t={...s_};for(let n of e){for(let e of r_)t[e]+=Number(n[e])||0;for(let e of i_)n[e]!==void 0&&(t[e]=(t[e]??0)+n[e])}return t}function v_(e,t,n){if(!e&&!t)return null;let r=t_(e?.items??[],`active`,n,e=>e.goal_id),i=t_(t?.items??[],`stopped`,n,e=>e.goal_id),a=n_(r,i,g_);return{...e??t,current_projected_count:r.length+i.length,items:a,rollout_event_count:a.reduce((e,t)=>e+(t.event_count??0),0),total_count:a.length}}function y_(e,t,n){if(!e&&!t)return null;let r=t_(e?.goals??[],`active`,n,e=>e.goal_id),i=t_(t?.goals??[],`stopped`,n,e=>e.goal_id),a=n_(r,i,e=>e.goal_id),o=c_(__(r),__(i));return{...e??t,goals:l_(a,Number(o.runs_24h)||0),sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),totals:o}}function b_(e,t,n){if(!e&&!t)return null;let r=(e?.agents??[]).filter(e=>e.goal_ids.some(e=>e_(e,n,`active`))||(e.current_todo?.goal_id?e_(e.current_todo.goal_id,n,`active`):!1)),i=(t?.agents??[]).filter(e=>e.goal_ids.some(e=>e_(e,n,`stopped`))||(e.current_todo?.goal_id?e_(e.current_todo.goal_id,n,`stopped`):!1)),a=n_(r,i,e=>e.agent_id).map(e=>{let t=i.find(t=>t.agent_id===e.agent_id);return t?{...e,goal_ids:Array.from(new Set([...e.goal_ids??[],...t.goal_ids]))}:e});return{...e??t,agents:a,source_summary:(e??t)?.source_summary?{...(e??t).source_summary,projected_agent_count:a.length,registered_agent_count:new Set(a.map(e=>e.agent_id)).size}:(e??t)?.source_summary}}function x_(e,t,n){if(!e&&!t)return null;let r=n_(t_(e?.goals??[],`active`,n,e=>e.goal_id),t_(t?.goals??[],`stopped`,n,e=>e.goal_id),e=>e.goal_id);return{...e??t,goals:r}}function S_(e,t){let n=t.goal_projection?.scope;if(n!==`active`&&n!==`stopped`)return t;let r=n,i=t.run_history.goals,a=e.run_history.goals,o=n_(r===`active`?i:a.filter(e=>e.activation_state!==`stopped`),r===`stopped`?i:a.filter(e=>e.activation_state===`stopped`),e=>e.id),s=new Map(o.map(e=>[e.id,e.activation_state])),c=r===`active`?t:e,l=r===`stopped`?t:e,u=e.goal_projection?.registry_revision??null,d=t.goal_projection?.registry_revision??null,f=u===null||d===null||u===d;return{...e,agent_management_projection:b_(c.agent_management_projection,l.agent_management_projection,s),attention_queue:h_(c.attention_queue,l.attention_queue,s),decision_freshness_summary:p_(c.decision_freshness_summary,l.decision_freshness_summary,s),event_ledger_summary:f_(c.event_ledger_summary,l.event_ledger_summary,s),goal_channel_notification_projection:x_(c.goal_channel_notification_projection,l.goal_channel_notification_projection,s),goal_projection:{schema_version:`loopx_goal_projection_scope_v0`,...t.goal_projection,complete:f,projected_goal_count:o.length,registry_goal_count:t.goal_projection?.registry_goal_count??0,scope:`all`},run_history:{...e.run_history,goal_count:o.length,goals:o,recent_runs:m_(c.run_history.recent_runs,l.run_history.recent_runs),run_count:c.run_history.run_count+l.run_history.run_count},todo_index:v_(c.todo_index,l.todo_index,s),usage_summary:y_(c.usage_summary,l.usage_summary,s)}}function C_(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`){if(Array.isArray(e)){var i=e.length;for(t=0;ttypeof e==`boolean`?`${e}`:e===0?`0`:e,E_=w_,D_=(e,t)=>n=>{if(t?.variants==null)return E_(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=T_(t)||T_(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return E_(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)},O_=(e,t)=>{let n=Array(e.length+t.length);for(let t=0;t({classGroupId:e,validator:t}),A_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),j_=`-`,M_=[],N_=`arbitrary..`,P_=e=>{let t=L_(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return I_(e);let n=e.split(j_);return F_(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?O_(i,t):t:i||M_}return n[e]||M_}}},F_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=F_(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(j_):e.slice(t).join(j_),s=a.length;for(let e=0;ee.slice(1,-1).indexOf(`:`)===-1?void 0:(()=>{let t=e.slice(1,-1),n=t.indexOf(`:`),r=t.slice(0,n);return r?N_+r:void 0})(),L_=e=>{let{theme:t,classGroups:n}=e;return R_(n,t)},R_=(e,t)=>{let n=A_();for(let r in e){let i=e[r];z_(i,n,r,t)}return n},z_=(e,t,n,r)=>{let i=e.length;for(let a=0;a{if(typeof e==`string`){V_(e,t,n);return}if(typeof e==`function`){H_(e,t,n,r);return}U_(e,t,n,r)},V_=(e,t,n)=>{let r=e===``?t:W_(t,e);r.classGroupId=n},H_=(e,t,n,r)=>{if(G_(e)){z_(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(k_(n,e))},U_=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e{let n=e,r=t.split(j_),i=r.length;for(let e=0;e`isThemeGetter`in e&&e.isThemeGetter===!0,K_=e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null),i=(i,a)=>{n[i]=a,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];if(t!==void 0)return t;if((t=r[e])!==void 0)return i(e,t),t},set(e,t){e in n?n[e]=t:i(e,t)}}},q_=`!`,J_=`:`,Y_=[],X_=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),Z_=e=>{let{prefix:t,experimentalParseClassName:n}=e,r=e=>{let t=[],n=0,r=0,i=0,a,o=e.length;for(let s=0;si?a-i:void 0;return X_(t,l,c,u)};if(t){let e=t+J_,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):X_(Y_,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},Q_=e=>{let t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{let n=[],r=[];for(let i=0;i0&&(r.sort(),n.push(...r),r=[]),n.push(a)):r.push(a)}return r.length>0&&(r.sort(),n.push(...r)),n}},$_=e=>({cache:K_(e.cacheSize),parseClassName:Z_(e),sortModifiers:Q_(e),postfixLookupClassGroupIds:ev(e),...P_(e)}),ev=e=>{let t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let e=0;e{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a,postfixLookupClassGroupIds:o}=t,s=[],c=e.trim().split(tv),l=``;for(let e=c.length-1;e>=0;--e){let t=c[e],{isExternal:u,modifiers:d,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:m}=n(t);if(u){l=t+(l.length>0?` `+l:l);continue}let h=!!m,g;if(h){g=r(p.substring(0,m));let e=g&&o[g]?r(p):void 0;e&&e!==g&&(g=e,h=!1)}else g=r(p);if(!g){if(!h){l=t+(l.length>0?` `+l:l);continue}if(g=r(p),!g){l=t+(l.length>0?` `+l:l);continue}h=!1}let _=d.length===0?``:d.length===1?d[0]:a(d).join(`:`),v=f?_+q_:_,y=v+g;if(s.indexOf(y)>-1)continue;s.push(y);let b=i(g,h);for(let e=0;e0?` `+l:l)}return l},rv=(...e)=>{let t=0,n,r,i=``;for(;t{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r{let n,r,i,a,o=o=>(n=$_(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,a=s,s(o)),s=e=>{let t=r(e);if(t)return t;let a=nv(e,n);return i(e,a),a};return a=o,(...e)=>a(rv(...e))},ov=[],sv=e=>{let t=t=>t[e]||ov;return t.isThemeGetter=!0,t},cv=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,lv=/^\((?:(\w[\w-]*):)?(.+)\)$/i,uv=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,dv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,fv=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,pv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,mv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,hv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,gv=e=>uv.test(e),_v=e=>!!e&&!Number.isNaN(Number(e)),vv=e=>!!e&&Number.isInteger(Number(e)),yv=e=>e.endsWith(`%`)&&_v(e.slice(0,-1)),bv=e=>dv.test(e),xv=()=>!0,Sv=e=>fv.test(e)&&!pv.test(e),Cv=()=>!1,wv=e=>mv.test(e),Tv=e=>hv.test(e),Ev=e=>!Q(e)&&!$(e),Dv=e=>e.startsWith(`@container`)&&(e[10]===`/`&&e[11]!==void 0||e[11]===`s`&&e[16]!==void 0&&e.startsWith(`-size/`,10)||e[11]===`n`&&e[18]!==void 0&&e.startsWith(`-normal/`,10)),Ov=e=>Uv(e,qv,Cv),Q=e=>cv.test(e),kv=e=>Uv(e,Jv,Sv),Av=e=>Uv(e,Yv,_v),jv=e=>Uv(e,Zv,xv),Mv=e=>Uv(e,Xv,Cv),Nv=e=>Uv(e,Gv,Cv),Pv=e=>Uv(e,Kv,Tv),Fv=e=>Uv(e,Qv,wv),$=e=>lv.test(e),Iv=e=>Wv(e,Jv),Lv=e=>Wv(e,Xv),Rv=e=>Wv(e,Gv),zv=e=>Wv(e,qv),Bv=e=>Wv(e,Kv),Vv=e=>Wv(e,Qv,!0),Hv=e=>Wv(e,Zv,!0),Uv=(e,t,n)=>{let r=cv.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Wv=(e,t,n=!1)=>{let r=lv.exec(e);return r?r[1]?t(r[1]):n:!1},Gv=e=>e===`position`||e===`percentage`,Kv=e=>e===`image`||e===`url`,qv=e=>e===`length`||e===`size`||e===`bg-size`,Jv=e=>e===`length`,Yv=e=>e===`number`,Xv=e=>e===`family-name`,Zv=e=>e===`number`||e===`weight`,Qv=e=>e===`shadow`,$v=av(()=>{let e=sv(`color`),t=sv(`font`),n=sv(`text`),r=sv(`font-weight`),i=sv(`tracking`),a=sv(`leading`),o=sv(`breakpoint`),s=sv(`container`),c=sv(`spacing`),l=sv(`radius`),u=sv(`shadow`),d=sv(`inset-shadow`),f=sv(`text-shadow`),p=sv(`drop-shadow`),m=sv(`blur`),h=sv(`perspective`),g=sv(`aspect`),_=sv(`ease`),v=sv(`animate`),y=()=>[`auto`,`avoid`,`all`,`avoid-page`,`page`,`left`,`right`,`column`],b=()=>[`center`,`top`,`bottom`,`left`,`right`,`top-left`,`left-top`,`top-right`,`right-top`,`bottom-right`,`right-bottom`,`bottom-left`,`left-bottom`],x=()=>[...b(),$,Q],S=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],C=()=>[`auto`,`contain`,`none`],w=()=>[$,Q,c],T=()=>[gv,`full`,`auto`,...w()],E=()=>[vv,`none`,`subgrid`,$,Q],D=()=>[`auto`,{span:[`full`,vv,$,Q]},vv,$,Q],O=()=>[vv,`auto`,$,Q],ee=()=>[`auto`,`min`,`max`,`fr`,$,Q],te=()=>[`start`,`end`,`center`,`between`,`around`,`evenly`,`stretch`,`baseline`,`center-safe`,`end-safe`],ne=()=>[`start`,`end`,`center`,`stretch`,`center-safe`,`end-safe`],k=()=>[`auto`,...w()],A=()=>[gv,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...w()],j=()=>[gv,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...w()],M=()=>[gv,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...w()],N=()=>[e,$,Q],P=()=>[...b(),Rv,Nv,{position:[$,Q]}],F=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],re=()=>[`auto`,`cover`,`contain`,zv,Ov,{size:[$,Q]}],ie=()=>[yv,Iv,kv],I=()=>[``,`none`,`full`,l,$,Q],ae=()=>[``,_v,Iv,kv],L=()=>[`solid`,`dashed`,`dotted`,`double`],oe=()=>[`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`],se=()=>[_v,yv,Rv,Nv],ce=()=>[``,`none`,m,$,Q],le=()=>[`none`,_v,$,Q],ue=()=>[`none`,_v,$,Q],de=()=>[_v,$,Q],R=()=>[gv,`full`,...w()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[bv],breakpoint:[bv],color:[xv],container:[bv],"drop-shadow":[bv],ease:[`in`,`out`,`in-out`],font:[Ev],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[bv],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[bv],shadow:[bv],spacing:[`px`,_v],text:[bv],"text-shadow":[bv],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,gv,Q,$,g]}],container:[`container`],"container-type":[{"@container":[``,`normal`,`size`,$,Q]}],"container-named":[Dv],columns:[{columns:[_v,Q,$,s]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":[`auto`,`avoid`,`avoid-page`,`avoid-column`]}],"box-decoration":[{"box-decoration":[`slice`,`clone`]}],box:[{box:[`border`,`content`]}],display:[`block`,`inline-block`,`inline`,`flex`,`inline-flex`,`table`,`inline-table`,`table-caption`,`table-cell`,`table-column`,`table-column-group`,`table-footer-group`,`table-header-group`,`table-row-group`,`table-row`,`flow-root`,`grid`,`inline-grid`,`contents`,`list-item`,`hidden`],sr:[`sr-only`,`not-sr-only`],float:[{float:[`right`,`left`,`none`,`start`,`end`]}],clear:[{clear:[`left`,`right`,`both`,`none`,`start`,`end`]}],isolation:[`isolate`,`isolation-auto`],"object-fit":[{object:[`contain`,`cover`,`fill`,`none`,`scale-down`]}],"object-position":[{object:x()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:[`static`,`fixed`,`absolute`,`relative`,`sticky`],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{"inset-s":T(),start:T()}],end:[{"inset-e":T(),end:T()}],"inset-bs":[{"inset-bs":T()}],"inset-be":[{"inset-be":T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:[`visible`,`invisible`,`collapse`],z:[{z:[vv,`auto`,$,Q]}],basis:[{basis:[gv,`full`,`auto`,s,...w()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[_v,gv,`auto`,`initial`,`none`,Q]}],grow:[{grow:[``,_v,$,Q]}],shrink:[{shrink:[``,_v,$,Q]}],order:[{order:[vv,`first`,`last`,`none`,$,Q]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":[`row`,`col`,`dense`,`row-dense`,`col-dense`]}],"auto-cols":[{"auto-cols":ee()}],"auto-rows":[{"auto-rows":ee()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...te(),`normal`]}],"justify-items":[{"justify-items":[...ne(),`normal`]}],"justify-self":[{"justify-self":[`auto`,...ne()]}],"align-content":[{content:[`normal`,...te()]}],"align-items":[{items:[...ne(),{baseline:[``,`last`]}]}],"align-self":[{self:[`auto`,...ne(),{baseline:[``,`last`]}]}],"place-content":[{"place-content":te()}],"place-items":[{"place-items":[...ne(),`baseline`]}],"place-self":[{"place-self":[`auto`,...ne()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pbs:[{pbs:w()}],pbe:[{pbe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:k()}],mx:[{mx:k()}],my:[{my:k()}],ms:[{ms:k()}],me:[{me:k()}],mbs:[{mbs:k()}],mbe:[{mbe:k()}],mt:[{mt:k()}],mr:[{mr:k()}],mb:[{mb:k()}],ml:[{ml:k()}],"space-x":[{"space-x":w()}],"space-x-reverse":[`space-x-reverse`],"space-y":[{"space-y":w()}],"space-y-reverse":[`space-y-reverse`],size:[{size:A()}],"inline-size":[{inline:[`auto`,...j()]}],"min-inline-size":[{"min-inline":[`auto`,...j()]}],"max-inline-size":[{"max-inline":[`none`,...j()]}],"block-size":[{block:[`auto`,...M()]}],"min-block-size":[{"min-block":[`auto`,...M()]}],"max-block-size":[{"max-block":[`none`,...M()]}],w:[{w:[s,`screen`,...A()]}],"min-w":[{"min-w":[s,`screen`,`none`,...A()]}],"max-w":[{"max-w":[s,`screen`,`none`,`prose`,{screen:[o]},...A()]}],h:[{h:[`screen`,`lh`,...A()]}],"min-h":[{"min-h":[`screen`,`lh`,`none`,...A()]}],"max-h":[{"max-h":[`screen`,`lh`,...A()]}],"font-size":[{text:[`base`,n,Iv,kv]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,Hv,jv]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,yv,Q]}],"font-family":[{font:[Lv,Mv,t]}],"font-features":[{"font-features":[Q]}],"fvn-normal":[`normal-nums`],"fvn-ordinal":[`ordinal`],"fvn-slashed-zero":[`slashed-zero`],"fvn-figure":[`lining-nums`,`oldstyle-nums`],"fvn-spacing":[`proportional-nums`,`tabular-nums`],"fvn-fraction":[`diagonal-fractions`,`stacked-fractions`],tracking:[{tracking:[i,$,Q]}],"line-clamp":[{"line-clamp":[_v,`none`,$,Av]}],leading:[{leading:[a,...w()]}],"list-image":[{"list-image":[`none`,$,Q]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,$,Q]}],"text-alignment":[{text:[`left`,`center`,`right`,`justify`,`start`,`end`]}],"placeholder-color":[{placeholder:N()}],"text-color":[{text:N()}],"text-decoration":[`underline`,`overline`,`line-through`,`no-underline`],"text-decoration-style":[{decoration:[...L(),`wavy`]}],"text-decoration-thickness":[{decoration:[_v,`from-font`,`auto`,$,kv]}],"text-decoration-color":[{decoration:N()}],"underline-offset":[{"underline-offset":[_v,`auto`,$,Q]}],"text-transform":[`uppercase`,`lowercase`,`capitalize`,`normal-case`],"text-overflow":[`truncate`,`text-ellipsis`,`text-clip`],"text-wrap":[{text:[`wrap`,`nowrap`,`balance`,`pretty`]}],indent:[{indent:w()}],"tab-size":[{tab:[vv,$,Q]}],"vertical-align":[{align:[`baseline`,`top`,`middle`,`bottom`,`text-top`,`text-bottom`,`sub`,`super`,$,Q]}],whitespace:[{whitespace:[`normal`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]}],break:[{break:[`normal`,`words`,`all`,`keep`]}],wrap:[{wrap:[`break-word`,`anywhere`,`normal`]}],hyphens:[{hyphens:[`none`,`manual`,`auto`]}],content:[{content:[`none`,$,Q]}],"bg-attachment":[{bg:[`fixed`,`local`,`scroll`]}],"bg-clip":[{"bg-clip":[`border`,`padding`,`content`,`text`]}],"bg-origin":[{"bg-origin":[`border`,`padding`,`content`]}],"bg-position":[{bg:P()}],"bg-repeat":[{bg:F()}],"bg-size":[{bg:re()}],"bg-image":[{bg:[`none`,{linear:[{to:[`t`,`tr`,`r`,`br`,`b`,`bl`,`l`,`tl`]},vv,$,Q],radial:[``,$,Q],conic:[vv,$,Q]},Bv,Pv]}],"bg-color":[{bg:N()}],"gradient-from-pos":[{from:ie()}],"gradient-via-pos":[{via:ie()}],"gradient-to-pos":[{to:ie()}],"gradient-from":[{from:N()}],"gradient-via":[{via:N()}],"gradient-to":[{to:N()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:ae()}],"border-w-x":[{"border-x":ae()}],"border-w-y":[{"border-y":ae()}],"border-w-s":[{"border-s":ae()}],"border-w-e":[{"border-e":ae()}],"border-w-bs":[{"border-bs":ae()}],"border-w-be":[{"border-be":ae()}],"border-w-t":[{"border-t":ae()}],"border-w-r":[{"border-r":ae()}],"border-w-b":[{"border-b":ae()}],"border-w-l":[{"border-l":ae()}],"divide-x":[{"divide-x":ae()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":ae()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...L(),`hidden`,`none`]}],"divide-style":[{divide:[...L(),`hidden`,`none`]}],"border-color":[{border:N()}],"border-color-x":[{"border-x":N()}],"border-color-y":[{"border-y":N()}],"border-color-s":[{"border-s":N()}],"border-color-e":[{"border-e":N()}],"border-color-bs":[{"border-bs":N()}],"border-color-be":[{"border-be":N()}],"border-color-t":[{"border-t":N()}],"border-color-r":[{"border-r":N()}],"border-color-b":[{"border-b":N()}],"border-color-l":[{"border-l":N()}],"divide-color":[{divide:N()}],"outline-style":[{outline:[...L(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[_v,$,Q]}],"outline-w":[{outline:[``,_v,Iv,kv]}],"outline-color":[{outline:N()}],shadow:[{shadow:[``,`none`,u,Vv,Fv]}],"shadow-color":[{shadow:N()}],"inset-shadow":[{"inset-shadow":[`none`,d,Vv,Fv]}],"inset-shadow-color":[{"inset-shadow":N()}],"ring-w":[{ring:ae()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:N()}],"ring-offset-w":[{"ring-offset":[_v,kv]}],"ring-offset-color":[{"ring-offset":N()}],"inset-ring-w":[{"inset-ring":ae()}],"inset-ring-color":[{"inset-ring":N()}],"text-shadow":[{"text-shadow":[`none`,f,Vv,Fv]}],"text-shadow-color":[{"text-shadow":N()}],opacity:[{opacity:[_v,$,Q]}],"mix-blend":[{"mix-blend":[...oe(),`plus-darker`,`plus-lighter`]}],"bg-blend":[{"bg-blend":oe()}],"mask-clip":[{"mask-clip":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]},`mask-no-clip`],"mask-composite":[{mask:[`add`,`subtract`,`intersect`,`exclude`]}],"mask-image-linear-pos":[{"mask-linear":[_v]}],"mask-image-linear-from-pos":[{"mask-linear-from":se()}],"mask-image-linear-to-pos":[{"mask-linear-to":se()}],"mask-image-linear-from-color":[{"mask-linear-from":N()}],"mask-image-linear-to-color":[{"mask-linear-to":N()}],"mask-image-t-from-pos":[{"mask-t-from":se()}],"mask-image-t-to-pos":[{"mask-t-to":se()}],"mask-image-t-from-color":[{"mask-t-from":N()}],"mask-image-t-to-color":[{"mask-t-to":N()}],"mask-image-r-from-pos":[{"mask-r-from":se()}],"mask-image-r-to-pos":[{"mask-r-to":se()}],"mask-image-r-from-color":[{"mask-r-from":N()}],"mask-image-r-to-color":[{"mask-r-to":N()}],"mask-image-b-from-pos":[{"mask-b-from":se()}],"mask-image-b-to-pos":[{"mask-b-to":se()}],"mask-image-b-from-color":[{"mask-b-from":N()}],"mask-image-b-to-color":[{"mask-b-to":N()}],"mask-image-l-from-pos":[{"mask-l-from":se()}],"mask-image-l-to-pos":[{"mask-l-to":se()}],"mask-image-l-from-color":[{"mask-l-from":N()}],"mask-image-l-to-color":[{"mask-l-to":N()}],"mask-image-x-from-pos":[{"mask-x-from":se()}],"mask-image-x-to-pos":[{"mask-x-to":se()}],"mask-image-x-from-color":[{"mask-x-from":N()}],"mask-image-x-to-color":[{"mask-x-to":N()}],"mask-image-y-from-pos":[{"mask-y-from":se()}],"mask-image-y-to-pos":[{"mask-y-to":se()}],"mask-image-y-from-color":[{"mask-y-from":N()}],"mask-image-y-to-color":[{"mask-y-to":N()}],"mask-image-radial":[{"mask-radial":[$,Q]}],"mask-image-radial-from-pos":[{"mask-radial-from":se()}],"mask-image-radial-to-pos":[{"mask-radial-to":se()}],"mask-image-radial-from-color":[{"mask-radial-from":N()}],"mask-image-radial-to-color":[{"mask-radial-to":N()}],"mask-image-radial-shape":[{"mask-radial":[`circle`,`ellipse`]}],"mask-image-radial-size":[{"mask-radial":[{closest:[`side`,`corner`],farthest:[`side`,`corner`]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[_v]}],"mask-image-conic-from-pos":[{"mask-conic-from":se()}],"mask-image-conic-to-pos":[{"mask-conic-to":se()}],"mask-image-conic-from-color":[{"mask-conic-from":N()}],"mask-image-conic-to-color":[{"mask-conic-to":N()}],"mask-mode":[{mask:[`alpha`,`luminance`,`match`]}],"mask-origin":[{"mask-origin":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]}],"mask-position":[{mask:P()}],"mask-repeat":[{mask:F()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":[`alpha`,`luminance`]}],"mask-image":[{mask:[`none`,$,Q]}],filter:[{filter:[``,`none`,$,Q]}],blur:[{blur:ce()}],brightness:[{brightness:[_v,$,Q]}],contrast:[{contrast:[_v,$,Q]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,Vv,Fv]}],"drop-shadow-color":[{"drop-shadow":N()}],grayscale:[{grayscale:[``,_v,$,Q]}],"hue-rotate":[{"hue-rotate":[_v,$,Q]}],invert:[{invert:[``,_v,$,Q]}],saturate:[{saturate:[_v,$,Q]}],sepia:[{sepia:[``,_v,$,Q]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,$,Q]}],"backdrop-blur":[{"backdrop-blur":ce()}],"backdrop-brightness":[{"backdrop-brightness":[_v,$,Q]}],"backdrop-contrast":[{"backdrop-contrast":[_v,$,Q]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,_v,$,Q]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[_v,$,Q]}],"backdrop-invert":[{"backdrop-invert":[``,_v,$,Q]}],"backdrop-opacity":[{"backdrop-opacity":[_v,$,Q]}],"backdrop-saturate":[{"backdrop-saturate":[_v,$,Q]}],"backdrop-sepia":[{"backdrop-sepia":[``,_v,$,Q]}],"border-collapse":[{border:[`collapse`,`separate`]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:[`auto`,`fixed`]}],caption:[{caption:[`top`,`bottom`]}],transition:[{transition:[``,`all`,`colors`,`opacity`,`shadow`,`transform`,`none`,$,Q]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[_v,`initial`,$,Q]}],ease:[{ease:[`linear`,`initial`,_,$,Q]}],delay:[{delay:[_v,$,Q]}],animate:[{animate:[`none`,v,$,Q]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,$,Q]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:le()}],"rotate-x":[{"rotate-x":le()}],"rotate-y":[{"rotate-y":le()}],"rotate-z":[{"rotate-z":le()}],scale:[{scale:ue()}],"scale-x":[{"scale-x":ue()}],"scale-y":[{"scale-y":ue()}],"scale-z":[{"scale-z":ue()}],"scale-3d":[`scale-3d`],skew:[{skew:de()}],"skew-x":[{"skew-x":de()}],"skew-y":[{"skew-y":de()}],transform:[{transform:[$,Q,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:R()}],"translate-x":[{"translate-x":R()}],"translate-y":[{"translate-y":R()}],"translate-z":[{"translate-z":R()}],"translate-none":[`translate-none`],zoom:[{zoom:[vv,$,Q]}],accent:[{accent:N()}],appearance:[{appearance:[`none`,`auto`]}],"caret-color":[{caret:N()}],"color-scheme":[{scheme:[`normal`,`dark`,`light`,`light-dark`,`only-dark`,`only-light`]}],cursor:[{cursor:[`auto`,`default`,`pointer`,`wait`,`text`,`move`,`help`,`not-allowed`,`none`,`context-menu`,`progress`,`cell`,`crosshair`,`vertical-text`,`alias`,`copy`,`no-drop`,`grab`,`grabbing`,`all-scroll`,`col-resize`,`row-resize`,`n-resize`,`e-resize`,`s-resize`,`w-resize`,`ne-resize`,`nw-resize`,`se-resize`,`sw-resize`,`ew-resize`,`ns-resize`,`nesw-resize`,`nwse-resize`,`zoom-in`,`zoom-out`,$,Q]}],"field-sizing":[{"field-sizing":[`fixed`,`content`]}],"pointer-events":[{"pointer-events":[`auto`,`none`]}],resize:[{resize:[`none`,``,`y`,`x`]}],"scroll-behavior":[{scroll:[`auto`,`smooth`]}],"scrollbar-thumb-color":[{"scrollbar-thumb":N()}],"scrollbar-track-color":[{"scrollbar-track":N()}],"scrollbar-gutter":[{"scrollbar-gutter":[`auto`,`stable`,`both`]}],"scrollbar-w":[{scrollbar:[`auto`,`thin`,`none`]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mbs":[{"scroll-mbs":w()}],"scroll-mbe":[{"scroll-mbe":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pbs":[{"scroll-pbs":w()}],"scroll-pbe":[{"scroll-pbe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:[`start`,`end`,`center`,`align-none`]}],"snap-stop":[{snap:[`normal`,`always`]}],"snap-type":[{snap:[`none`,`x`,`y`,`both`]}],"snap-strictness":[{snap:[`mandatory`,`proximity`]}],touch:[{touch:[`auto`,`none`,`manipulation`]}],"touch-x":[{"touch-pan":[`x`,`left`,`right`]}],"touch-y":[{"touch-pan":[`y`,`up`,`down`]}],"touch-pz":[`touch-pinch-zoom`],select:[{select:[`none`,`text`,`all`,`auto`]}],"will-change":[{"will-change":[`auto`,`scroll`,`contents`,`transform`,$,Q]}],fill:[{fill:[`none`,...N()]}],"stroke-w":[{stroke:[_v,Iv,kv,Av]}],stroke:[{stroke:[`none`,...N()]}],"forced-color-adjust":[{"forced-color-adjust":[`auto`,`none`]}]},conflictingClassGroups:{"container-named":[`container-type`],overflow:[`overflow-x`,`overflow-y`],overscroll:[`overscroll-x`,`overscroll-y`],inset:[`inset-x`,`inset-y`,`inset-bs`,`inset-be`,`start`,`end`,`top`,`right`,`bottom`,`left`],"inset-x":[`right`,`left`],"inset-y":[`top`,`bottom`],flex:[`basis`,`grow`,`shrink`],gap:[`gap-x`,`gap-y`],p:[`px`,`py`,`ps`,`pe`,`pbs`,`pbe`,`pt`,`pr`,`pb`,`pl`],px:[`pr`,`pl`],py:[`pt`,`pb`],m:[`mx`,`my`,`ms`,`me`,`mbs`,`mbe`,`mt`,`mr`,`mb`,`ml`],mx:[`mr`,`ml`],my:[`mt`,`mb`],size:[`w`,`h`],"font-size":[`leading`],"fvn-normal":[`fvn-ordinal`,`fvn-slashed-zero`,`fvn-figure`,`fvn-spacing`,`fvn-fraction`],"fvn-ordinal":[`fvn-normal`],"fvn-slashed-zero":[`fvn-normal`],"fvn-figure":[`fvn-normal`],"fvn-spacing":[`fvn-normal`],"fvn-fraction":[`fvn-normal`],"line-clamp":[`display`,`overflow`],rounded:[`rounded-s`,`rounded-e`,`rounded-t`,`rounded-r`,`rounded-b`,`rounded-l`,`rounded-ss`,`rounded-se`,`rounded-ee`,`rounded-es`,`rounded-tl`,`rounded-tr`,`rounded-br`,`rounded-bl`],"rounded-s":[`rounded-ss`,`rounded-es`],"rounded-e":[`rounded-se`,`rounded-ee`],"rounded-t":[`rounded-tl`,`rounded-tr`],"rounded-r":[`rounded-tr`,`rounded-br`],"rounded-b":[`rounded-br`,`rounded-bl`],"rounded-l":[`rounded-tl`,`rounded-bl`],"border-spacing":[`border-spacing-x`,`border-spacing-y`],"border-w":[`border-w-x`,`border-w-y`,`border-w-s`,`border-w-e`,`border-w-bs`,`border-w-be`,`border-w-t`,`border-w-r`,`border-w-b`,`border-w-l`],"border-w-x":[`border-w-r`,`border-w-l`],"border-w-y":[`border-w-t`,`border-w-b`],"border-color":[`border-color-x`,`border-color-y`,`border-color-s`,`border-color-e`,`border-color-bs`,`border-color-be`,`border-color-t`,`border-color-r`,`border-color-b`,`border-color-l`],"border-color-x":[`border-color-r`,`border-color-l`],"border-color-y":[`border-color-t`,`border-color-b`],translate:[`translate-x`,`translate-y`,`translate-none`],"translate-none":[`translate`,`translate-x`,`translate-y`,`translate-z`],"scroll-m":[`scroll-mx`,`scroll-my`,`scroll-ms`,`scroll-me`,`scroll-mbs`,`scroll-mbe`,`scroll-mt`,`scroll-mr`,`scroll-mb`,`scroll-ml`],"scroll-mx":[`scroll-mr`,`scroll-ml`],"scroll-my":[`scroll-mt`,`scroll-mb`],"scroll-p":[`scroll-px`,`scroll-py`,`scroll-ps`,`scroll-pe`,`scroll-pbs`,`scroll-pbe`,`scroll-pt`,`scroll-pr`,`scroll-pb`,`scroll-pl`],"scroll-px":[`scroll-pr`,`scroll-pl`],"scroll-py":[`scroll-pt`,`scroll-pb`],touch:[`touch-x`,`touch-y`,`touch-pz`],"touch-x":[`touch`],"touch-y":[`touch`],"touch-pz":[`touch`]},conflictingClassGroupModifiers:{"font-size":[`leading`]},postfixLookupClassGroups:[`container-type`],orderSensitiveModifiers:[`*`,`**`,`after`,`backdrop`,`before`,`details-content`,`file`,`first-letter`,`first-line`,`marker`,`placeholder`,`selection`]}});function ey(...e){return $v(w_(e))}var ty=D_(`inline-flex h-9 shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-md border px-3 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400 disabled:pointer-events-none disabled:opacity-50 dark:focus-visible:ring-zinc-500`,{variants:{variant:{primary:`border-slate-900 bg-slate-950 text-white hover:bg-slate-800 dark:border-zinc-100 dark:bg-zinc-50 dark:text-zinc-950 dark:hover:bg-zinc-200`,secondary:`border-slate-200 bg-white text-slate-900 hover:bg-slate-50 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-100 dark:hover:bg-zinc-900`,ghost:`border-transparent bg-transparent text-slate-700 hover:bg-slate-100 dark:text-zinc-300 dark:hover:bg-zinc-900`},size:{sm:`h-8 px-2 text-xs`,md:`h-9 px-3 text-sm`,icon:`h-9 w-9 px-0`}},defaultVariants:{variant:`secondary`,size:`md`}});function ny({className:e,variant:t,size:n,...r}){return(0,V.jsx)(`button`,{className:ey(ty({variant:t,size:n}),e),type:`button`,...r})}function ry({className:e,...t}){return(0,V.jsx)(`section`,{className:ey(`rounded-lg border border-slate-200/80 bg-white/95 text-slate-950 shadow-[0_1px_2px_rgba(15,23,42,0.04)] dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50`,e),...t})}function iy({className:e,...t}){return(0,V.jsx)(`div`,{className:ey(`p-4 pt-0`,e),...t})}var ay=[`codex`,`claude`,`kiro`,`trae`,`coco`,`openai`,`anthropic`],oy=new Set([`acp`,`status_projection`]);function sy(e){let t=e.trim().toLowerCase().replace(/_/gu,`-`);for(let e of ay)if(t===e||t.startsWith(`${e}-`))return e;return t}function cy(e,t){let n=t?.trim().toLowerCase()??``;return n.length>0&&!oy.has(n)?sy(n):sy(e)}var ly={stop:`ready_stop`,resume:`resume_review`,delete:`delete_review`},uy=e=>typeof e==`string`&&e.trim().length>0;function dy(e){let t={schemaVersion:`action_review_plan_v0`,proposalId:e.proposal_id,sourceFingerprint:e.expected_state_fingerprint},n=(e,n)=>({...t,interaction:e,reason:n,canApply:!1}),r=e.action_kind===`goal.lifecycle`;if(r&&e.gate!=null||e.status===`gated`)return n(`gated`,`authority_gate`);if(r&&e.stale!=null||e.status===`stale`)return n(`refresh`,`stale_proposal`);if(e.status===`applied`)return e.receipt?.projection_verified===!0?n(`completed`,`readback_verified`):n(`repair`,`readback_unverified`);if(e.status===`applying`)return n(`pending`,`apply_pending`);if(e.status===`failed`||e.error!=null)return n(`repair`,`apply_failed`);if(e.status!==`preview_ready`&&e.status!==`deferred`)return n(`inactive`,`inactive_proposal`);let i=(e,n=!0)=>({...t,interaction:`review`,reason:e,canApply:n});if(e.action_kind!==`goal.lifecycle`)return i(e.permission_classification===`protected`?`protected_action`:`action_review`);if(!(uy(e.proposal_id)&&uy(e.expected_state_fingerprint)&&Dh.shape.validation_evidence.safeParse(e.validation_evidence).success&&e.validation_evidence.length>0&&e.available_transitions.includes(`apply`)))return n(`refresh`,`incomplete_proposal`);let{operation:a,goal_id:o}=e.normalized_parameters;if(!uy(o)||e.context.goal_id!=null&&e.context.goal_id!==o)return n(`refresh`,`incomplete_proposal`);if(a!==`stop`&&a!==`resume`&&a!==`delete`)return i(`unknown_action`,!1);if(e.permission_classification===`protected`)return i(`protected_action`);if(e.permission_classification!==`durable_write`)return i(`unknown_permission`,!1);let s=ly[a];return s===`ready_stop`&&e.status===`preview_ready`?{...t,interaction:`direct`,reason:s,canApply:!0}:i(s===`ready_stop`?`action_review`:s)}function fy(e){if(e.error_code===`action_stale`||e.error_code===`action_conflict`)return!0;let t=e.proposal;return typeof t==`object`&&!!t&&`status`in t&&t.status===`stale`}function py(e){return{blockingTodoCount:e.blockingTodoCount,goalNotifications:e.goalNotifications,goals:e.goals,openUserTodoCount:e.openUserTodoCount,systemHealth:e.systemHealth,attentionHistory:e.attentionHistory,userTodos:e.userTodos,workers:e.workers}}function my(e,t){return e.goals.find(e=>e.goalId===t)?.title??t}function hy(e){return e.activationState===`stopped`||e.state===`已停止`?`stopped`:e.state===`已完成`?`history`:e.needsYou||e.state===`等你`?`needs_you`:e.state===`推进中`||e.state===`需修复`?`running`:e.state===`安静运行`?`observing`:`scheduled`}function gy(e){let t=e;return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function _y(e){return`$${e.toFixed(2)}`}function vy(e){let t=e;return t>=36e5?`${(t/36e5).toFixed(1)}h`:t>=6e4?`${(t/6e4).toFixed(1)}m`:t>=1e3?`${Math.round(t/1e3)}s`:`${t}ms`}function yy(e,t,n){return e==null?t:n(e)}function by(e){return!!(e&&[e.tokens24h,e.tokens7d,e.costUsd24h,e.costUsd7d,e.durationMs24h,e.durationMs7d].some(e=>e!=null))}function xy(e,t){if(!by(e))return null;let n=(e,n,r,i)=>{let a=[n==null?null:`${gy(n)} ${t.tokens}`,r==null?null:`${t.cost}: ${_y(r)}`,i==null?null:`${t.duration}: ${vy(i)}`].filter(e=>e!==null);return a.length?`${e} ${a.join(` · `)}`:null};return n(t.period7d,e.tokens7d,e.costUsd7d,e.durationMs7d)??n(t.period24h,e.tokens24h,e.costUsd24h,e.durationMs24h)}function Sy({ariaLabel:e,className:t,icon:n,onChange:r,options:i,prefixLabel:a,value:o}){let s=(0,B.useId)(),c=(0,B.useRef)(null),l=(0,B.useRef)(null),u=(0,B.useRef)(new Map),[d,f]=(0,B.useState)(!1),[p,m]=(0,B.useState)(o),h=i.find(e=>e.value===o)??i[0],g=i.filter(e=>!e.disabled);(0,B.useEffect)(()=>{if(!d)return;let e=e=>{c.current?.contains(e.target)||f(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[d]),(0,B.useEffect)(()=>{d&&u.current.get(p)?.focus()},[p,d]);function _(e){m(e)}function v(e=`selected`){let t=e===`last`?g.at(-1):g[0],n=e===`selected`&&h&&!h.disabled?h:t;n&&(f(!0),_(n.value))}function y({restoreFocus:e=!1}={}){f(!1),e&&l.current?.focus()}function b(e){e.disabled||(r(e.value),y({restoreFocus:!0}))}function x(e){if(!g.length)return;let t=g.findIndex(e=>e.value===p),n=t<0?0:(t+e+g.length)%g.length;_(g[n].value)}function S(e){e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),v(`selected`)):e.key===`ArrowUp`&&(e.preventDefault(),v(`last`))}function C(e,t){if(e.key===`ArrowDown`)e.preventDefault(),x(1);else if(e.key===`ArrowUp`)e.preventDefault(),x(-1);else if(e.key===`Home`)e.preventDefault(),g[0]&&_(g[0].value);else if(e.key===`End`){e.preventDefault();let t=g.at(-1);t&&_(t.value)}else e.key===`Enter`||e.key===` `?(e.preventDefault(),b(t)):e.key===`Escape`?(e.preventDefault(),y({restoreFocus:!0})):e.key===`Tab`&&y()}let w;return(0,V.jsxs)(`div`,{className:`personal-select${t?` ${t}`:``}`,ref:c,children:[(0,V.jsxs)(`button`,{"aria-controls":s,"aria-expanded":d,"aria-haspopup":`listbox`,"aria-label":e,className:`personal-select-trigger`,"data-value":o,onClick:()=>d?y():v(),onKeyDown:S,ref:l,role:`combobox`,type:`button`,children:[n?(0,V.jsx)(`span`,{className:`personal-select-icon`,children:n}):null,(0,V.jsxs)(`span`,{className:`personal-select-value`,children:[a?(0,V.jsx)(`small`,{children:a}):null,(0,V.jsx)(`span`,{children:h?.label??o})]}),(0,V.jsx)(tm,{"aria-hidden":!0,className:d?`is-open`:void 0,size:14})]}),d?(0,V.jsx)(`div`,{"aria-label":e,className:`personal-select-listbox`,id:s,role:`listbox`,children:i.map(e=>{let t=e.group&&e.group!==w;return w=e.group,(0,V.jsxs)(`div`,{className:`personal-select-option-wrap`,children:[t?(0,V.jsx)(`div`,{className:`personal-select-group-label`,children:e.group}):null,(0,V.jsxs)(`button`,{"aria-disabled":e.disabled||void 0,"aria-selected":e.value===o,className:`personal-select-option`,disabled:e.disabled,id:`${s}-${e.value.replace(/[^a-z0-9_-]/gi,`-`)}`,onClick:()=>b(e),onFocus:()=>m(e.value),onKeyDown:t=>C(t,e),ref:t=>{t?u.current.set(e.value,t):u.current.delete(e.value)},role:`option`,tabIndex:e.value===p?0:-1,type:`button`,children:[(0,V.jsx)(`span`,{children:e.label}),e.value===o?(0,V.jsx)(em,{"aria-hidden":!0,size:15}):null]})]},e.value)})}):null]})}function Cy({agents:e,managerChatOpen:t,mobileNavigationOpen:n,onOpenGoalCapabilities:r,onOpenGoalDetail:i,onOpenManagerChat:a,onRefresh:o,onOpenNavigation:s,onSelectGoalTab:c,onSelectAgent:l,onReturnManagerHome:u,refreshState:d,readOnlySourceLabel:f,selectedAgentId:p,selectedGoal:m,selectedGoalTab:h}){let{locale:g,t:_}=qi(),[v,y]=(0,B.useState)(!1),b=(0,B.useRef)(null),x=(0,B.useRef)(null);(0,B.useEffect)(()=>{if(!v)return;function e(e){x.current?.contains(e.target)||y(!1)}function t(e){e.key===`Escape`&&(y(!1),b.current?.focus())}return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[v]),(0,B.useEffect)(()=>y(!1),[m?.goalId]);function S(e){y(!1),e?.()}let C=m?xy(m.usage,{cost:_(`drawer.costShort`),duration:_(`drawer.durationShort`),period24h:_(`drawer.period24h`),period7d:_(`drawer.period7d`),tokens:_(`drawer.tokensShort`)}):null;return(0,V.jsxs)(`header`,{className:`personal-channel-header`,children:[(0,V.jsx)(`button`,{"aria-expanded":n??!1,"aria-label":_(`header.openGoalNavigation`),className:`personal-icon-button personal-mobile-menu`,onClick:s,type:`button`,children:(0,V.jsx)(Tm,{size:18})}),(0,V.jsxs)(`div`,{className:`personal-channel-title`,children:[(0,V.jsx)(`h1`,{children:m?.title??_(`header.manager`)}),m?(0,V.jsx)(`p`,{children:m.loadState?_(m.loadState===`error`?`startup.goalError`:`startup.goalLoading`):`${m.agentLaneCount&&m.agentLaneCount>1?_(`header.workAgentCount`,{count:m.agentLaneCount}):m.agentLabel??m.agentId} · ${m.loadState?_(m.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Ji(m.state,g)}${C?` · ${C}`:``} · ${m.nextSentence}`}):null]}),m?(0,V.jsxs)(`nav`,{"aria-label":_(`header.goalView`),className:`personal-goal-tabs`,children:[(0,V.jsx)(`button`,{"aria-current":h===`chat`?`page`:void 0,onClick:()=>c(`chat`),type:`button`,children:_(`header.chat`)}),(0,V.jsx)(`button`,{"aria-current":h===`tasks`?`page`:void 0,onClick:()=>c(`tasks`),type:`button`,children:_(`header.tasks`)}),(0,V.jsx)(`button`,{"aria-current":h===`files`?`page`:void 0,onClick:()=>c(`files`),type:`button`,children:_(`header.files`)})]}):(0,V.jsxs)(`nav`,{"aria-label":_(`header.managerView`),className:`personal-goal-tabs`,children:[(0,V.jsx)(`button`,{"aria-current":t?void 0:`page`,onClick:u,type:`button`,children:_(`header.managerOverview`)}),(0,V.jsx)(`button`,{"aria-current":t?`page`:void 0,onClick:a,type:`button`,children:_(`header.chat`)})]}),(0,V.jsxs)(`div`,{className:`personal-channel-actions`,children:[m&&i&&r?(0,V.jsxs)(`div`,{className:`personal-goal-tools`,ref:x,children:[(0,V.jsxs)(`button`,{"aria-expanded":v,"aria-haspopup":`menu`,"aria-label":_(`header.goalSettingsDescription`),className:`personal-goal-tools-trigger`,onClick:()=>y(e=>!e),ref:b,title:_(`header.goalSettingsDescription`),type:`button`,children:[(0,V.jsx)(Gm,{"aria-hidden":!0,size:16}),(0,V.jsx)(`span`,{children:_(`header.goalSettings`)}),(0,V.jsx)(tm,{"aria-hidden":!0,size:13})]}),v?(0,V.jsxs)(`fieldset`,{"aria-label":_(`header.goalSettings`),className:`personal-goal-tools-menu`,children:[(0,V.jsxs)(`button`,{onClick:()=>S(i),type:`button`,children:[(0,V.jsx)(ym,{"aria-hidden":!0,size:17}),(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:_(`header.goalDetails`)})})]}),(0,V.jsxs)(`button`,{onClick:()=>S(r),type:`button`,children:[(0,V.jsx)(Gm,{"aria-hidden":!0,size:17}),(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:_(`header.goalCapabilities`)})})]})]}):null]}):null,f?(0,V.jsxs)(`span`,{className:`personal-read-only-source`,title:_(`header.readOnlySourceDescription`,{source:f}),children:[(0,V.jsx)(pm,{size:15}),f,(0,V.jsx)(`small`,{children:_(`common.readOnly`)})]}):(0,V.jsx)(Sy,{ariaLabel:_(`header.selectChatRuntime`),className:`personal-agent-select`,icon:(0,V.jsx)(Zp,{size:16}),onChange:l,options:e.map(e=>({disabled:!e.available,label:`${e.label}${e.available?``:` · ${_(`header.agentUnavailable`)}`}`,value:e.agentId})),prefixLabel:_(`header.chatRuntime`),value:p}),(0,V.jsxs)(`span`,{className:`personal-live-indicator`,children:[(0,V.jsx)(`i`,{}),_(`header.live`)]}),o?(0,V.jsxs)(`span`,{className:`personal-refresh-control is-${d??`idle`}`,children:[d===`loading`?(0,V.jsx)(`small`,{children:_(`header.refreshing`)}):d===`done`?(0,V.jsx)(`small`,{children:_(`header.refreshDone`)}):d===`error`?(0,V.jsx)(`small`,{children:_(`header.refreshFailed`)}):null,(0,V.jsx)(`button`,{"aria-label":_(d===`loading`?`header.refreshing`:`header.refresh`),className:`personal-icon-button`,disabled:d===`loading`,onClick:o,type:`button`,children:(0,V.jsx)(Im,{className:d===`loading`?`is-spinning`:void 0,size:17})})]}):null]})]})}function wy({attention:e,onSelect:t}){let{t:n}=qi(),r=Xi(e.updatedAt,n);return(0,V.jsxs)(`button`,{className:`personal-timeline-row personal-attention-row`,"data-testid":`personal-browse-row`,onClick:t,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-row-icon is-attention`,children:(0,V.jsx)(im,{size:18})}),(0,V.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,V.jsxs)(`small`,{children:[e.goalTitle??e.goalId,` · `,n(`home.lane.needsYou`),r?` · ${n(`tasks.waitingAge`,{age:r})}`:``]}),(0,V.jsx)(`strong`,{children:e.text})]}),(0,V.jsx)(`span`,{className:`personal-priority-dot is-${e.priority??(e.blocking?`high`:`medium`)}`}),(0,V.jsx)(`span`,{className:`personal-row-status ${e.blocking?`is-blocking`:`is-pending`}`,children:e.blocking?n(`tasks.blocked`):n(`tasks.pending`)}),(0,V.jsx)(nm,{size:17})]})}var Ty=/(`[^`\n]+`)|(\*\*[^*\n]+(\*[^*\n]*)?\*\*)|(\[[^\]\n]{1,120}\]\(https?:\/\/[^)\s]+\))/g;function Ey(e,t){let n=[],r=0,i=0;for(let a of e.matchAll(Ty)){let o=a.index??0;o>r&&n.push(e.slice(r,o));let s=a[0],c=`${t}-i${i++}`;if(s.startsWith("`"))n.push((0,V.jsx)(`code`,{className:`personal-md-code`,children:s.slice(1,-1)},c));else if(s.startsWith(`**`))n.push((0,V.jsx)(`strong`,{children:s.slice(2,-2)},c));else{let e=s.indexOf(`](`),t=s.slice(1,e),r=s.slice(e+2,-1);n.push((0,V.jsx)(`a`,{className:`personal-md-link`,href:r,rel:`noreferrer`,target:`_blank`,children:t},c))}r=o+s.length}return r{r.length>0&&(n.push({type:`paragraph`,lines:r}),r=[])},a=0;for(;a{let n=`b${t}`;if(e.type===`code`)return(0,V.jsx)(`pre`,{className:`personal-md-pre`,children:(0,V.jsx)(`code`,{children:e.text})},n);if(e.type===`heading`)return(0,V.jsx)(`p`,{className:`personal-md-heading is-h${e.level}`,children:Ey(e.text,n)},n);if(e.type===`list`){let t=e.items.map((e,t)=>(0,V.jsx)(`li`,{children:Ey(e,`${n}-${t}`)},`${n}-${t}`));return e.ordered?(0,V.jsx)(`ol`,{className:`personal-md-list`,children:t},n):(0,V.jsx)(`ul`,{className:`personal-md-list`,children:t},n)}return(0,V.jsx)(`p`,{children:e.lines.map((e,t)=>(0,V.jsxs)(B.Fragment,{children:[t>0?(0,V.jsx)(`br`,{}):null,Ey(e,`${n}-${t}`)]},`${n}-${t}`))},n)})})}function jy({onSelect:e,output:t}){let{t:n}=qi(),r=t.kind===`report`?gm:hm;return(0,V.jsxs)(`button`,{className:`personal-timeline-row personal-output-row`,"data-output-kind":t.kind,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-row-icon is-output`,children:(0,V.jsx)(r,{size:18})}),(0,V.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,V.jsxs)(`small`,{children:[t.goalTitle??t.goalId,` · `,t.agentLabel??`LoopX`]}),(0,V.jsx)(`strong`,{children:t.title}),t.summary?(0,V.jsx)(`span`,{children:t.summary}):null,t.report?(0,V.jsxs)(`small`,{children:[n(`files.reportDelta`,{added:t.report.addedCount,changed:t.report.changedCount}),` · `,n(`files.verifiedReport`)]}):null]}),t.createdAt?(0,V.jsx)(`time`,{children:t.createdAt}):null,(0,V.jsx)(nm,{size:17})]})}var My={completed:`runs.completed`,failed:`runs.failed`,interrupted:`runs.interrupted`,queued:`runs.queued`,running:`runs.running`,waiting:`runs.waiting`};function Ny({onSelect:e,run:t}){let{t:n}=qi(),r=t.totalSteps>0?Math.min(100,t.completedSteps/t.totalSteps*100):0;return(0,V.jsxs)(`button`,{"aria-label":`${n(`tasks.viewExecution`)}:${t.title}`,className:`personal-timeline-row personal-run-row`,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-row-icon is-run`,children:(0,V.jsx)(Zp,{size:18})}),(0,V.jsxs)(`span`,{className:`personal-run-identity`,children:[(0,V.jsx)(`small`,{children:t.goalTitle}),(0,V.jsx)(`strong`,{children:t.agentLabel})]}),(0,V.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,V.jsx)(`strong`,{children:t.title}),(0,V.jsx)(`small`,{children:t.latestActivity})]}),(0,V.jsxs)(`span`,{className:`personal-run-progress`,"aria-label":`${t.completedSteps}/${t.totalSteps}`,children:[(0,V.jsxs)(`small`,{children:[t.completedSteps,`/`,t.totalSteps]}),(0,V.jsx)(`i`,{children:(0,V.jsx)(`b`,{style:{width:`${r}%`}})})]}),(0,V.jsxs)(`span`,{className:`personal-row-status is-${t.status}`,children:[t.status===`running`?(0,V.jsx)(Cm,{className:`personal-spin`,size:14}):null,n(My[t.status])]}),t.sessionId?(0,V.jsx)(`span`,{className:`personal-run-open-label`,children:n(`tasks.viewExecution`)}):null,(0,V.jsx)(nm,{size:17})]})}function Py({onSelect:e,schedule:t}){let{t:n}=qi(),r=t.scheduleKind===`heartbeat`;return(0,V.jsxs)(`button`,{"aria-label":`${r?`Heartbeat`:n(`tasks.scheduled`)}:${t.label};${t.status??`active`}`,className:`personal-schedule-row`,onClick:e,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-schedule-icon`,children:r?(0,V.jsx)(Fm,{size:17}):(0,V.jsx)($p,{size:17})}),(0,V.jsxs)(`span`,{className:`personal-schedule-copy`,children:[(0,V.jsx)(`small`,{children:n(r?`schedule.heartbeat`:`schedule.monitor`)}),(0,V.jsx)(`strong`,{children:t.label}),(0,V.jsx)(`p`,{children:t.schedule??n(`schedule.summary`)})]}),(0,V.jsx)(`span`,{className:`personal-schedule-status is-${t.status??`active`}`,children:t.status===`paused`?n(`schedule.paused`):n(`schedule.active`)}),(0,V.jsx)(nm,{size:16})]})}function Fy({items:e,onSelect:t,selectedGoal:n}){let{t:r}=qi();if(e.length===0)return(0,V.jsxs)(`div`,{className:`personal-timeline-empty`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(Km,{size:20})}),(0,V.jsx)(`strong`,{children:r(n?`timeline.emptyGoal`:`timeline.emptyWorkspace`)}),(0,V.jsx)(`p`,{children:r(n?`timeline.emptyGoalDescription`:`timeline.emptyWorkspaceDescription`)})]});let i=[...e].reverse().find(e=>e.kind===`message`&&e.message.role!==`user`||e.kind===`proposal`&&[`applied`,`stale`,`error`,`gated`].includes(e.proposal.status)||e.kind===`run`&&e.run.status===`completed`),a=i?.kind===`message`?`${i.message.agentLabel??r(`header.manager`)}:${i.message.pending?r(`timeline.pending`):i.message.text}`:i?.kind===`proposal`?`${i.proposal.title}:${i.proposal.status}`:i?.kind===`run`?r(`timeline.runCompleted`,{run:i.run.title}):``,o=e.filter(e=>e.kind===`proposal`&&e.proposal.status===`gated`),s=e.filter(e=>e.kind!==`proposal`),c=e.filter(e=>e.kind===`proposal`&&e.proposal.status!==`gated`);function l(e){return e.kind===`attention`?(0,V.jsx)(wy,{attention:e.attention,onSelect:()=>t({item:e.attention,kind:`attention`})},e.id):e.kind===`run`?(0,V.jsx)(Ny,{onSelect:()=>t({item:e.run,kind:`run`}),run:e.run},e.id):e.kind===`output`?(0,V.jsx)(jy,{onSelect:()=>t({item:e.output,kind:`output`}),output:e.output},e.id):e.kind===`schedule`?(0,V.jsx)(Py,{onSelect:()=>t({item:e.schedule,kind:`schedule`}),schedule:e.schedule},e.id):e.kind===`proposal`?(0,V.jsxs)(`button`,{className:`personal-proposal-row is-${e.proposal.status}`,onClick:()=>t({item:e.proposal,kind:`proposal`}),type:`button`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(Km,{size:17})}),(0,V.jsxs)(`span`,{children:[(0,V.jsxs)(`small`,{children:[e.proposal.actionKind,` · `,e.proposal.status]}),(0,V.jsx)(`strong`,{children:e.proposal.title}),(0,V.jsx)(`p`,{children:e.proposal.impact})]}),(0,V.jsx)(`b`,{children:e.proposal.status===`gated`?r(`timeline.review`):e.proposal.primaryLabel??r(`timeline.reviewAndConfirm`)})]},e.id):(0,V.jsxs)(`article`,{className:`personal-message is-${e.message.role}`,children:[e.message.role===`user`?null:(0,V.jsx)(`span`,{className:`personal-message-avatar`,children:(0,V.jsx)(Zp,{size:17})}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:e.message.role===`user`?r(`common.you`):e.message.agentLabel??r(`header.manager`)}),e.message.time?(0,V.jsx)(`time`,{children:e.message.time}):null]}),e.message.attachments?.length?(0,V.jsx)(`div`,{className:`personal-message-images`,children:e.message.attachments.map(e=>(0,V.jsx)(`img`,{alt:e.name,src:e.dataUrl},e.id))}):null,e.message.role===`user`?(0,V.jsx)(`p`,{children:e.message.text}):(0,V.jsx)(Ay,{text:e.message.text}),e.message.pending?(0,V.jsx)(`span`,{className:`personal-message-pending`,children:r(`timeline.pending`)}):null]})]},e.id)}return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{"aria-atomic":`true`,"aria-live":`polite`,className:`personal-live-region`,role:`status`,children:a}),(0,V.jsxs)(`div`,{className:`personal-channel-timeline`,children:[s.map(l),o.length?(0,V.jsxs)(`details`,{className:`personal-gated-summary`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(Km,{size:16})}),(0,V.jsx)(`strong`,{children:r(`timeline.waitingConfirmation`)}),(0,V.jsx)(`small`,{children:r(`timeline.gateHistory`,{count:o.length})})]}),(0,V.jsx)(`div`,{children:o.map(l)})]}):null,c.map(l)]})]})}function Iy({goal:e}){let{t}=qi(),n={connected:t(`acceptance.connected`),mapped:t(`acceptance.mapped`),refreshed:t(`acceptance.refreshed`),adapter_inspected:t(`acceptance.inspected`),run_recorded:t(`acceptance.recorded`),reward_judged:t(`acceptance.judged`),operator_approved:t(`acceptance.approved`),controller_ready:t(`acceptance.ready`),attention_queue:t(`acceptance.attentionSource`),agent_vision:t(`acceptance.visionSource`),todo_projection:t(`acceptance.todoSource`),current_run:t(`acceptance.runSource`)},r=e=>n[e]??t(`acceptance.unknown`),i=e.acceptanceObservation,a=e.loadState||!i||i.goal_id!==e.goalId||i.coverage===`unavailable`;return(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-acceptance`,"aria-label":t(`acceptance.title`),children:[(0,V.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,V.jsx)(`h3`,{children:t(`acceptance.title`)}),(0,V.jsx)(`em`,{children:t(`common.readOnly`)})]}),(0,V.jsx)(`p`,{role:`status`,children:t(a?`acceptance.unavailable`:`acceptance.partial`)}),!a&&i?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h4`,{children:t(`acceptance.gaps`)}),i.acceptance_gaps.length?i.acceptance_gaps.map((e,n)=>(0,V.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,V.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.owner`)}),(0,V.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,V.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.observed`)}),(0,V.jsx)(`dd`,{children:e.observed_at??t(`acceptance.unknown`)})]})]})]},`${e.kind}:${e.owner}:${n}`)):(0,V.jsx)(`p`,{children:t(`acceptance.noGaps`)}),(0,V.jsx)(`h4`,{children:t(`acceptance.guards`)}),i.guards.length?i.guards.map((e,n)=>(0,V.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,V.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.owner`)}),(0,V.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),e.blocks_agent?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.agent`)}),(0,V.jsx)(`dd`,{children:e.blocks_agent})]}):null,e.todo_id?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`common.task`)}),(0,V.jsx)(`dd`,{children:e.todo_id})]}):null,(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,V.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`acceptance.scope`)}),(0,V.jsx)(`dd`,{children:e.decision_scope??t(`acceptance.unknown`)})]})]})]},`${e.todo_id}:${n}`)):(0,V.jsx)(`p`,{children:t(`acceptance.noGuards`)}),(0,V.jsx)(`h4`,{children:t(`acceptance.next`)}),(0,V.jsx)(`p`,{children:i.next_action??t(`acceptance.unknown`)}),(0,V.jsxs)(`details`,{children:[(0,V.jsxs)(`summary`,{children:[t(`acceptance.historical_progress`),` · `,i.historical_progress.length]}),(0,V.jsx)(`p`,{children:t(`acceptance.historical`)}),i.historical_progress.map(e=>(0,V.jsxs)(`p`,{children:[(0,V.jsx)(`strong`,{children:r(e.kind)}),` · `,e.observed_at??t(`acceptance.unknown`),` `,e.evidence_refs.join(`, `)]},e.kind))]}),i.missing_sources.length?(0,V.jsxs)(`p`,{children:[t(`acceptance.missing`),` `,i.missing_sources.map(r).join(`, `)]}):null,i.truncated?(0,V.jsx)(`p`,{children:t(`acceptance.truncated`)}):null]}):null]})}function Ly({item:e,successor:t,onSelect:n}){let{t:r}=qi(),i=e.details;return(0,V.jsxs)(`section`,{className:`personal-detail-card`,"aria-label":r(`attentionDetail.title`),children:[(0,V.jsx)(`h3`,{children:r(`attentionDetail.title`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.request`)}),(0,V.jsx)(`dd`,{children:r(i?.interaction===`decision`?`attentionDetail.decision`:`attentionDetail.unknownRequest`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`common.status`)}),(0,V.jsx)(`dd`,{children:r(`attentionDetail.${i?.lifecycle??`unknown`}`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`drawer.reason`)}),(0,V.jsx)(`dd`,{children:i?.reason??e.explanation??r(`attentionDetail.unknownReason`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Todo`}),(0,V.jsx)(`dd`,{children:e.todoId})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.targetTodo`)}),(0,V.jsx)(`dd`,{children:i?.unblocksTodoId??r(`attentionDetail.notProvided`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.targetAgent`)}),(0,V.jsx)(`dd`,{children:i?.blocksAgent??r(`attentionDetail.notProvided`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`attentionDetail.scope`)}),(0,V.jsx)(`dd`,{children:i?.decisionScope?`${i.decisionScope.kind} · ${i.decisionScope.granularity} · ${i.decisionScope.scopeKey}`:r(`attentionDetail.notProvided`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`drawer.evidence`)}),(0,V.jsx)(`dd`,{children:i?.evidence??e.evidence??r(`drawer.decisionDefaultEvidence`)})]})]}),i?.supersededBy?(0,V.jsxs)(`p`,{children:[r(`attentionDetail.replacement`),`: `,i.supersededBy]}):null,t&&n?(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>n(t),type:`button`,children:r(`attentionDetail.openReplacement`)}):null,(0,V.jsx)(`p`,{children:r(`attentionDetail.boundary`)})]})}function Ry(e){return e.replace(/\s+/gu,` `).trim()}function zy(e,t){let n=RegExp(`(?:不要|不需要|无需|禁止|别|暂不|do not\\b|don't\\b|without\\b).{0,10}(?:${t.source})`,`iu`),r=RegExp(`(?:${t.source}).{0,10}(?:不要|不需要|无需|禁止|关闭)`,`iu`),i=RegExp(`disable\\b.{0,10}(?:${t.source})|(?:turn|switch|set)\\b.{0,10}(?:${t.source}).{0,10}\\boff\\b|(?:${t.source})\\s+(?:is\\s+)?disabled\\b`,`iu`);return n.test(e)||r.test(e)||i.test(e)}function By(e){return/(我现在该做什么|下一步|哪些\s*Goal\s*在等我|需要我|谁在等我|Agent\s*在做什么|当前进度|总结(?:今天)?进展)/iu.test(e)}function Vy(e){let t=/(怎么|如何|为什么|给.*建议|分析一下|解释|只读)/u.test(e),n=/(解决一下|修复一下|处理一下|执行一下|改一下|跑(?:一下)?测试|rebase|push|提交|推送)/iu.test(e);return!t&&n&&/(帮我|请|给我|直接|现在|开始|bytedcli|codebase|git|rebase|push|提交|推送)/iu.test(e)}function Hy(e){return Ry(e).toLowerCase().match(/(?:^|[\s,,;;:((:]|到|至)(?todo_done:todo_[a-z0-9_-]{3,64}|pr_merged:(?:(?:[a-z0-9_.-]{1,80})\/(?:[a-z0-9_.-]{1,100}))?#[1-9][0-9]{0,8}|capacity_available:[a-z][a-z0-9_:-]{0,63}|resume_at:[1-9][0-9]{3}-[0-9]{2}-[0-9]{2}t[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,3})?(?:z|[+-][0-9]{2}:[0-9]{2}))(?=$|[\s,,。;;))])/iu)?.groups?.condition??null}function Uy(e,t){let n=Ry(e),r=[],i=t.agents.find(e=>{let t=n.toLowerCase();return t.includes(e.agentId.toLowerCase())||t.includes(e.label.toLowerCase())}),a=t.todos.find(e=>n.includes(e.todoId)||n.includes(e.text)),o=/(刚刚|已经|已)(?:经)?\s*(新增|创建|添加)(?:的)?\s*(todo|待办|任务)/iu.test(n),s=!!t.goalId&&!zy(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n);if(!t.goalId&&!zy(n,/goal|目标/iu)&&/(创建|新建|设置|create|start|set up).{0,24}(goal|目标)/iu.test(n)&&r.push({actionKind:`goal.create`,confidence:.97,normalizedParameters:{heartbeat_enabled:!zy(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n)}}),t.goalId&&s&&r.push({actionKind:`heartbeat.bind`,confidence:.96,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&!s&&!zy(n,/定时|监控|监测|持续观察|scheduled check|monitor/iu)&&/(定时|监控|监测|每.{0,8}(分钟|小时|天)|持续观察|scheduled check|monitor|every.{0,12}(minute|hour|day)|daily)/iu.test(n)&&r.push({actionKind:`monitor.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&i&&!zy(n,/绑定|负责|接管|管理/iu)&&/((让|交给).{0,20}(管理|负责|接管).{0,8}(goal|目标)|(绑定).{0,12}(goal|目标)|(goal|目标).{0,12}(交给|绑定|负责|接管))/iu.test(n)&&r.push({actionKind:`agent.bind`,confidence:.96,normalizedParameters:{agent_id:i.agentId,goal_id:t.goalId}}),t.goalId&&!o&&!zy(n,RegExp(`todo|待办|任务`,`iu`))&&/(创建|新建|新增|添加|加一个|记一个).{0,16}(todo|待办|任务)|(todo|待办|任务).{0,12}(创建|新建|新增|添加)|(?:create|add)(?:\s+(?:a|an|new))?\s+(?:todo|task)|(?:todo|task).{0,12}(?:create|add)/iu.test(n)&&r.push({actionKind:`todo.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&Vy(n)&&r.push({actionKind:`todo.create`,confidence:.9,normalizedParameters:{goal_id:t.goalId,start_execution:!0}}),t.goalId&&a){let e=!zy(n,/完成|做完|关闭/u)&&/完成|做完|关闭/u.test(n)?`complete`:!zy(n,/阻塞|卡住/u)&&/阻塞|卡住/u.test(n)?`block`:!zy(n,/暂缓|稍后|推迟/u)&&/暂缓|稍后|推迟/u.test(n)?`defer`:i&&!zy(n,/交给|分配给|改派/u)&&/交给|分配给|改派/u.test(n)?`reassign`:null;if(e){let i=e===`defer`?Hy(n):null;if(e===`defer`&&!i)return{actionKind:`todo.update`,confidence:.97,missingFields:[`resume_when`],normalizedParameters:{goal_id:t.goalId,operation:e,todo_id:a.todoId},route:`clarify`};r.push({actionKind:`todo.update`,confidence:.97,normalizedParameters:{goal_id:t.goalId,operation:e,...i?{resume_when:i}:{},todo_id:a.todoId}})}}let c=[...new Map(r.map(e=>[e.actionKind,e])).values()];return c.length>1?{actionKind:null,confidence:.4,missingFields:[`single_intent`],normalizedParameters:{},route:`clarify`}:c.length===1?{...c[0],missingFields:[],route:`typed_action`}:!t.goalId&&By(n)?{actionKind:null,confidence:.98,missingFields:[],normalizedParameters:{},route:`projection`}:{actionKind:null,confidence:.75,missingFields:[],normalizedParameters:{},route:`agent_chat`}}function Wy(e,t,n){if(!e)return{};if(!t.trim())return{modelConfig:null};let r={model:t.trim()};return n&&(r.reasoning_effort=n),{modelConfig:r}}var Gy=[`a[href]`,`button:not([disabled])`,`textarea:not([disabled])`,`select:not([disabled])`,`input:not([disabled])`,`[tabindex]:not([tabindex='-1'])`].join(`,`),Ky=[{key:`drawer.taskBlock`,operation:`block`},{key:`drawer.taskSuccessor`,operation:`successor_create`}],qy=[{key:`drawer.decisionReject`,resolution:`reject`},{key:`drawer.decisionDefer`,resolution:`defer`}],Jy=Array.from({length:32},(e,t)=>t+1),Yy=/^[a-z][a-z0-9_.-]{0,63}$/u;function Xy(e){let t=String(e??``).trim().toLowerCase();return Yy.test(t)?t:null}function Zy(e,t){return e.enabled===t.enabled&&e.maxChildren===t.maxChildren&&JSON.stringify(e.modelConfig??null)===JSON.stringify(t.modelConfig??null)&&[...e.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)===[...t.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)}function Qy({agents:e,attentionHistory:t=[],onSelectAttention:n,callbacks:r,goalNotifications:i=[],goals:a=[],inspectorExpanded:o=!1,larkConnections:s=[],onClose:c,onToggleInspectorSize:l,readOnly:u=!1,runs:d=[],selection:f}){let{locale:p,t:m}=qi(),[h,g]=(0,B.useState)(``),[_,v]=(0,B.useState)(!1),[y,b]=(0,B.useState)(`idle`),[x,S]=(0,B.useState)(`record`),[C,w]=(0,B.useState)([]),[T,E]=(0,B.useState)(null),[D,O]=(0,B.useState)(2),[ee,te]=(0,B.useState)(``),[ne,k]=(0,B.useState)(``),[A,j]=(0,B.useState)(`idle`),[M,N]=(0,B.useState)(null),[P,F]=(0,B.useState)(null),re=(0,B.useRef)(null),ie=(0,B.useRef)(null),[I,ae]=(0,B.useState)(e.find(e=>e.available)?.agentId??`codex`),[L,oe]=(0,B.useState)(``),se=(0,B.useRef)(null),ce=(0,B.useRef)(null),le=(0,B.useRef)(null),ue=(0,B.useRef)(null),de=f.kind===`run`?`run:${f.item.runId}`:f.kind===`proposal`?`proposal:${f.item.previewId}`:f.kind===`todo`?`todo:${f.item.todoId}`:f.kind===`attention`?`attention:${f.item.todoId}`:f.kind===`output`?`output:${f.item.outputId}`:f.kind===`schedule`?`schedule:${f.item.scheduleId}`:`goal:${f.item.goalId}`;(0,B.useEffect)(()=>{b(`idle`),v(!1),S(`record`),oe(``);let e=f.kind===`goal`?f.item.subagentExecution:void 0;w(e?.allowedDomains??[]),te(e?.modelConfig?.model??``),k(e?.modelConfig?.reasoning_effort??``),O(e?.maxChildren?Math.min(e.maxChildren,32):2),E(null),j(`idle`),N(null),F(null),re.current=e??null,ie.current=null},[de]);let R=f.kind===`goal`?f.item.subagentExecution:void 0;(0,B.useEffect)(()=>{let e=re.current,t=R?!e||!Zy(e,R):e!==null;if(re.current=R??null,!P){t&&R&&(w(R.allowedDomains),te(R.modelConfig?.model??``),k(R.modelConfig?.reasoning_effort??``),O(R.maxChildren||2),E(null),j(`idle`),N(null));return}let n=ie.current;(!R||Zy(P,R)||n&&!Zy(n,R))&&(R&&(w(R.allowedDomains),te(R.modelConfig?.model??``),k(R.modelConfig?.reasoning_effort??``),O(R.maxChildren||2)),ie.current=null,F(null))},[R,P]),(0,B.useEffect)(()=>{let e=document.activeElement;e instanceof HTMLElement&&!ce.current?.contains(e)&&(le.current=e);let t=window.requestAnimationFrame(()=>ue.current?.focus());return()=>window.cancelAnimationFrame(t)},[de]);let fe=(0,B.useCallback)(()=>{let e=le.current;c(),window.requestAnimationFrame(()=>e?.focus())},[c]);(0,B.useEffect)(()=>{function e(e){if(e.key===`Escape`){e.preventDefault(),fe();return}if(e.key===`Tab`&&f.kind!==`todo`){let t=Array.from(ce.current?.querySelectorAll(Gy)??[]).filter(e=>!e.hasAttribute(`disabled`)&&e.getAttribute(`aria-hidden`)!==`true`);if(t.length===0)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n.focus())}}return document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`keydown`,e)}},[fe,f.kind]);let pe=f.kind===`attention`?m(`drawer.titleAttention`):f.kind===`todo`?m(`drawer.taskDetails`):f.kind===`run`?m(`drawer.runDetails`):f.kind===`output`?m(`drawer.titleOutput`):f.kind===`proposal`?m(f.item.status===`applied`?`drawer.titleProposalApplied`:`drawer.titleProposalConfirm`):f.kind===`schedule`?f.item.scheduleKind===`heartbeat`?`Heartbeat`:m(`drawer.titleSchedule`):m(`drawer.goalDetails`),me=f.kind===`proposal`?f.item.goalId??`manager`:f.item.goalId,he=f.kind===`attention`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`todo`||f.kind===`run`?f.item.goalTitle:f.kind===`output`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`goal`?f.item.title:f.kind===`schedule`?m(`drawer.goalAutoRun`):f.item.goalId?m(`drawer.goalChanges`):m(`drawer.managerChanges`),ge=f.kind===`goal`?d.find(e=>e.goalId===f.item.goalId&&!!e.sessionId)??d.find(e=>e.goalId===f.item.goalId):null,_e=f.kind===`run`&&(f.item.completedSteps>0||!!f.item.latestActivity||!!f.item.outputs?.length),ve=f.kind===`attention`?Xi(f.item.updatedAt,m):null,ye=Hy(L);async function be(){f.kind!==`run`||!h.trim()||(await r.onCorrectRun?.(f.item,h.trim()),g(``))}async function xe(e,t,n,i){if(t===`successor_create`){await r.onPreviewAction?.({actionKind:`todo.create`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-successor-${e.todoId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,text:m(`drawer.taskSuccessorText`,{task:e.text})},summary:m(`drawer.taskSuccessorSummary`,{task:e.text})});return}await r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:e.claimedBy??I,goal_id:e.goalId,operation:t,...t===`block`?{note:m(`drawer.taskSuccessorNote`)}:{},...t===`defer`&&i?{resume_when:i}:{},todo_id:e.todoId},summary:`${n}:${e.text}`})}async function Se(e,t,n){u||!qd(e)||await r.onPreviewAction?.({actionKind:`gate.resolve`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-decision-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,decision:t,todo_id:e.todoId},summary:`${n}:${e.text}`})}let Ce=f.kind===`goal`?P??f.item.subagentExecution??{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0}:{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0},we=A===`previewing`||A===`applying`,Te=(()=>{if(f.kind!==`goal`)return[];let e=new Map;for(let t of Ce.allowedDomains){let n=Xy(t);n&&e.set(n,{matchingTodoCount:0,value:n})}if(Ce.domainCandidates)for(let t of Ce.domainCandidates){let n=Xy(t.domain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+t.matchingTodoCount,value:n})}else for(let t of f.item.agentTodos){if(t.done||t.taskClass!==`advancement_task`)continue;let n=Xy(t.taskDomain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+1,value:n})}return[...e.values()]})();function z(){w(Ce.allowedDomains),te(Ce.modelConfig?.model??``),k(Ce.modelConfig?.reasoning_effort??``),O(Ce.maxChildren||2),E(null),j(`idle`),N(null)}function Ee(){let e=[...new Set(C.map(e=>Xy(e)))];return e.every(e=>!!e)?e:null}function De(e,t){w(n=>t?[...n,e].filter((e,t,n)=>n.indexOf(e)===t):n.filter(t=>t!==e)),N(null),j(`idle`),E(null)}async function Oe(e,t=e){if(f.kind!==`goal`||!r.onPreviewGoalSubagentConfiguration)return;let n=e?Ee():[];if(t&&!ee.trim()&&ne){j(`error`),E(m(`drawer.subagentModelRequired`));return}if(e&&!n){j(`error`),E(m(`drawer.subagentDomainInvalid`)),N(null);return}let i={allowedDomains:n??[],enabled:e,goalId:f.item.goalId,maxChildren:e?D:0,...Wy(t,ee,ne)};j(`previewing`),E(m(`drawer.subagentPreviewing`)),N(null);try{let e=await r.onPreviewGoalSubagentConfiguration(i);if(!e.changed){ie.current=R??null,F({...e.configuration,domainCandidates:Ce.domainCandidates}),w(e.configuration.allowedDomains),te(e.configuration.modelConfig?.model??``),k(e.configuration.modelConfig?.reasoning_effort??``),O(e.configuration.maxChildren||2),j(`success`),E(m(`drawer.subagentNoChange`));return}N({...i,changed:e.changed,previewId:e.previewId}),j(`ready`),E(m(`drawer.subagentPreviewReady`))}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentPreviewFailed`))}}async function ke(){if(!(!M||!r.onApplyGoalSubagentConfiguration)){j(`applying`),E(m(`drawer.subagentApplying`));try{let e=await r.onApplyGoalSubagentConfiguration({allowedDomains:M.allowedDomains,enabled:M.enabled,goalId:M.goalId,maxChildren:M.maxChildren,modelConfig:M.modelConfig,previewId:M.previewId});ie.current=R??null,F({...e,domainCandidates:Ce.domainCandidates}),w(e.allowedDomains),te(e.modelConfig?.model??``),k(e.modelConfig?.reasoning_effort??``),O(e.maxChildren||2),j(`success`),E(m(`drawer.subagentApplied`)),N(null);try{await r.onRefresh?.()}catch{j(`warning`),E(m(`drawer.subagentAppliedRefreshFailed`))}}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentApplyFailed`))}}}return(0,V.jsxs)(`div`,{"aria-labelledby":`personal-drawer-title`,"aria-modal":f.kind===`todo`?void 0:`true`,className:`personal-context-drawer`,"data-context-kind":f.kind,ref:ce,role:`dialog`,children:[(0,V.jsxs)(`header`,{className:`personal-drawer-header${f.kind===`todo`?` is-task-inspector`:``}`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`h2`,{id:`personal-drawer-title`,ref:ue,tabIndex:-1,children:pe}),(0,V.jsx)(`p`,{children:he})]}),(0,V.jsxs)(`div`,{className:`personal-drawer-header-actions`,children:[f.kind===`todo`&&l?(0,V.jsx)(`button`,{"aria-label":m(o?`drawer.inspectorHalf`:`drawer.inspectorFull`),className:`personal-icon-button personal-inspector-size`,onClick:l,title:m(o?`drawer.inspectorHalfView`:`drawer.inspectorFullView`),type:`button`,children:o?(0,V.jsx)(Om,{size:17}):(0,V.jsx)(wm,{size:17})}):null,(0,V.jsxs)(`button`,{"aria-label":m(`drawer.closeDetail`,{context:he}),className:`personal-icon-button personal-drawer-close`,onClick:fe,ref:se,type:`button`,children:[(0,V.jsx)(Gp,{className:`personal-mobile-back`,size:18}),(0,V.jsx)($m,{className:`personal-desktop-close`,size:18})]})]})]}),(0,V.jsxs)(`div`,{className:`personal-drawer-body`,children:[f.kind===`attention`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card is-attention`,children:[(0,V.jsx)(`small`,{children:f.item.blocking?m(`drawer.attentionBlocking`):m(`drawer.attentionWaiting`)}),(0,V.jsx)(`h3`,{children:f.item.text}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,V.jsx)(`dd`,{children:f.item.priority??`medium`})]}),ve?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`common.waiting`)}),(0,V.jsx)(`dd`,{children:m(`tasks.waitingAge`,{age:ve})})]}):null]})]}),(0,V.jsx)(Ly,{item:f.item,onSelect:n,successor:Kd(f.item,t)}),!u&&qd(f.item)?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void Se(f.item,`approve`,m(`common.confirm`)),type:`button`,children:[(0,V.jsx)(em,{size:17}),m(`drawer.decisionReview`)]}),(0,V.jsxs)(`details`,{className:`personal-compact-menu`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(dm,{size:17}),m(`drawer.decisionMore`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`button`,{onClick:()=>void r.onExplainDecision?.(f.item),type:`button`,children:[(0,V.jsx)(Em,{size:16}),m(`drawer.explainDecision`)]}),qy.map(e=>(0,V.jsx)(`button`,{onClick:()=>void Se(f.item,e.resolution,m(e.key)),type:`button`,children:m(e.key)},e.resolution))]})]})]}):null]}):null,f.kind===`todo`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-task-inspector-summary`,children:[(0,V.jsxs)(`div`,{className:`personal-task-inspector-status`,children:[(0,V.jsxs)(`span`,{className:f.item.done?`is-done`:f.item.status===`blocked`?`is-blocked`:`is-open`,children:[(0,V.jsx)(`i`,{}),f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)]}),f.item.priority?(0,V.jsx)(`span`,{children:f.item.priority}):null,(0,V.jsx)(`span`,{children:f.item.taskClass===`advancement_task`?m(`drawer.taskAdvancement`):f.item.taskClass??m(`drawer.taskOrdinary`)})]}),(0,V.jsx)(`h3`,{children:f.item.text})]}),(0,V.jsxs)(`section`,{"aria-label":m(`drawer.taskInfo`),className:`personal-task-inspector-fields`,children:[(0,V.jsx)(`h4`,{children:m(`drawer.taskInfo`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`common.owner`)}),(0,V.jsx)(`dd`,{children:f.item.ownerLabel??f.item.claimedBy??m(`drawer.notAssigned`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`common.status`)}),(0,V.jsx)(`dd`,{children:f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,V.jsx)(`dd`,{children:f.item.priority??m(`drawer.notSet`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.dependencies`)}),(0,V.jsx)(`dd`,{children:f.item.dependencies?.join(` · `)||m(`common.none`)})]}),f.item.status===`deferred`||f.item.resumeWhen?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.resumeWhen`)}),(0,V.jsx)(`dd`,{children:f.item.resumeWhen||m(`drawer.notSet`)})]}):null,f.item.resumeWhen?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.resumeState`)}),(0,V.jsx)(`dd`,{children:f.item.resumeReady?m(`drawer.resumeReady`):m(`drawer.resumePending`)})]}):null,f.item.resumeReceiptId?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.resumeReceipt`)}),(0,V.jsx)(`dd`,{children:f.item.resumeReceiptId})]}):null,(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.nextTransition`)}),(0,V.jsx)(`dd`,{children:f.item.nextTransition??(f.item.done?m(`drawer.taskNextCompleted`):f.item.resumeReady?m(`drawer.taskNextResumeReady`):f.item.status===`deferred`?m(`drawer.taskNextDeferred`):m(`drawer.taskNextOpen`))})]})]})]}),!u&&!f.item.done?(0,V.jsxs)(`div`,{className:`personal-task-inspector-actions`,"aria-label":m(`drawer.taskActions`),children:[(0,V.jsxs)(`details`,{className:`personal-task-management`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(dm,{size:16}),m(`drawer.taskManage`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.reassign`)}),(0,V.jsxs)(`label`,{className:`personal-inline-agent-select`,children:[m(`drawer.reassign`),(0,V.jsx)(`select`,{"aria-label":m(`drawer.reassign`),onChange:e=>ae(e.target.value),value:I,children:e.filter(e=>e.available).map(e=>(0,V.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:f.item.goalId,kind:`todo`,todo_id:f.item.todoId},idempotencyKey:`workspace-todo-${f.item.todoId}-reassign-${I}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:I,goal_id:f.item.goalId,operation:`reassign`,todo_id:f.item.todoId},summary:m(`drawer.reassignSummary`,{task:f.item.text})}),type:`button`,children:m(`timeline.review`)})]}),(0,V.jsx)(`strong`,{children:m(`drawer.taskDeferUntil`)}),(0,V.jsxs)(`label`,{className:`personal-inline-agent-select personal-inline-resume-when`,children:[m(`drawer.taskDeferUntil`),(0,V.jsx)(`input`,{"aria-label":m(`drawer.taskDeferCondition`),"aria-invalid":!!L.trim()&&!ye,onChange:e=>oe(e.target.value),placeholder:m(`drawer.taskDeferPlaceholder`),value:L}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:!ye,onClick:()=>void xe(f.item,`defer`,m(`drawer.taskDefer`),ye??void 0),type:`button`,children:m(`drawer.taskDeferReview`)}),(0,V.jsx)(`small`,{children:L.trim()&&!ye?m(`drawer.taskDeferInvalid`):m(`drawer.taskDeferSupported`)})]}),(0,V.jsx)(`div`,{className:`personal-task-management-secondary`,children:Ky.map(e=>(0,V.jsx)(`button`,{onClick:()=>void xe(f.item,e.operation,m(e.key)),type:`button`,children:m(e.key)},e.operation))})]})]}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void xe(f.item,`complete`,m(`drawer.taskComplete`)),type:`button`,children:[(0,V.jsx)(em,{size:17}),m(`drawer.taskComplete`)]})]}):null,f.item.done?(0,V.jsxs)(`div`,{className:`personal-task-completed-note`,children:[(0,V.jsx)(em,{size:16}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.taskCompletedTitle`)}),(0,V.jsx)(`small`,{children:m(`drawer.taskCompletedNote`)})]})]}):null]}):null,f.kind===`goal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsx)(`small`,{children:Ji(f.item.state,p)}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.agentSentence}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.tokens`)}),(0,V.jsxs)(`dd`,{children:[yy(f.item.usage?.tokens24h,m(`drawer.usageNotMeasured`),gy),` / `,yy(f.item.usage?.tokens7d,m(`drawer.usageNotMeasured`),gy)]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.cost`)}),(0,V.jsxs)(`dd`,{children:[yy(f.item.usage?.costUsd24h,m(`drawer.usageNotMeasured`),_y),` / `,yy(f.item.usage?.costUsd7d,m(`drawer.usageNotMeasured`),_y)]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.duration`)}),(0,V.jsxs)(`dd`,{children:[yy(f.item.usage?.durationMs24h,m(`drawer.usageNotMeasured`),vy),` / `,yy(f.item.usage?.durationMs7d,m(`drawer.usageNotMeasured`),vy)]})]})]})]}),(0,V.jsx)(Iy,{goal:f.item}),(()=>{let e=i.find(e=>e.goalId===f.item.goalId),t=s.find(e=>e.goal_id===f.item.goalId);return(0,V.jsxs)(V.Fragment,{children:[f.item.repository?(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-repository`,children:[(0,V.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,V.jsx)(`small`,{children:m(`drawer.repository`)}),(0,V.jsx)(`em`,{children:m(`common.readOnly`)})]}),(0,V.jsxs)(`h3`,{children:[(0,V.jsx)(_m,{size:16}),f.item.repository.label]}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.branch`)}),(0,V.jsx)(`dd`,{children:f.item.repository.branch||`detached`})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Role`}),(0,V.jsx)(`dd`,{children:m(`drawer.repositoryRole`)})]})]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>{let e=navigator.clipboard?.writeText(f.item.repository?.identity??``);if(!e){b(`error`);return}e.then(()=>b(`copied`)).catch(()=>b(`error`))},type:`button`,children:[(0,V.jsx)(cm,{size:15}),m(y===`copied`?`drawer.copyRepositoryDone`:`drawer.copyRepository`)]}),y===`error`?(0,V.jsx)(`p`,{className:`personal-copy-feedback is-error`,role:`status`,children:m(`drawer.copyRepositoryError`)}):y===`copied`?(0,V.jsx)(`p`,{className:`personal-copy-feedback`,role:`status`,children:m(`drawer.copyRepositorySuccess`)}):null]}):null,u?(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,V.jsx)(`small`,{children:m(`drawer.larkConnection`)}),(0,V.jsx)(`h3`,{children:m(`drawer.remoteDetailsUnavailable`)}),(0,V.jsx)(`p`,{children:m(`drawer.remoteDetailsDescription`)})]}):(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,V.jsx)(`small`,{children:m(`drawer.larkConnection`)}),t?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`h3`,{children:[t.app_label,(0,V.jsx)(`span`,{className:`personal-connection-status`,children:m(`drawer.connected`)})]}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.group`)}),(0,V.jsx)(`dd`,{children:t.chat_name})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.topic`)}),(0,V.jsxs)(`dd`,{children:[`# `,t.topic_name]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.trigger`)}),(0,V.jsx)(`dd`,{children:t.incoming_mode===`mentions`?m(`lark.someoneMentions`):m(`lark.allMessages`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.replyMode`)}),(0,V.jsx)(`dd`,{children:m(`lark.topicReply`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.autoNotify`)}),(0,V.jsx)(`dd`,{children:e?.humanGateAutoNotifyEnabled?m(`common.on`):m(`common.off`)})]}),e?.lastNotifiedAt?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.lastNotification`)}),(0,V.jsx)(`dd`,{children:e.lastNotifiedAt})]}):null]})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h3`,{children:m(`drawer.larkNotConfigured`)}),(0,V.jsx)(`p`,{children:m(`drawer.larkNotConfiguredDescription`)})]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onOpenNotificationSettings?.(f.item.goalId),type:`button`,children:[(0,V.jsx)(Xp,{size:16}),m(t?`drawer.larkConfigure`:`drawer.larkConnect`)]})]})]})})(),(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-session`,children:[(0,V.jsx)(`small`,{children:m(`drawer.runDetails`)}),ge?.sessionId?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h3`,{children:Yi(ge.sessionStatus??ge.status,m)}),(0,V.jsx)(`p`,{children:ge.title}),r.onOpenRunSession?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onOpenRunSession?.(ge),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.runLatest`)]}):null]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`h3`,{children:m(`drawer.noRun`)}),(0,V.jsx)(`p`,{children:m(`drawer.noRunDescription`)})]})]}),u?null:(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`heartbeat`,f.item.goalId),type:`button`,children:[(0,V.jsx)(Fm,{size:16}),m(`drawer.setupHeartbeat`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`monitor`,f.item.goalId),type:`button`,children:[(0,V.jsx)($p,{size:16}),m(`drawer.scheduleAdd`)]})]}),f.item.subagentExecution?(0,V.jsxs)(`section`,{className:`personal-detail-card personal-goal-subagents`,children:[(0,V.jsxs)(`div`,{className:`personal-subagent-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:m(`drawer.subagentLabel`)}),(0,V.jsxs)(`h3`,{children:[(0,V.jsx)(Zp,{size:16}),m(`drawer.subagentTitle`)]})]}),(0,V.jsxs)(`button`,{"aria-checked":Ce.enabled,"aria-label":m(M&&A===`ready`?`drawer.subagentPending`:Ce.enabled?`drawer.subagentDisable`:`drawer.subagentEnable`),className:`personal-subagent-switch`,"data-pending":M&&A===`ready`?`true`:void 0,disabled:u||we||!!M||!r.onPreviewGoalSubagentConfiguration,onClick:()=>void Oe(!Ce.enabled),role:`switch`,type:`button`,children:[(0,V.jsx)(`span`,{}),m(M&&A===`ready`?`drawer.subagentPending`:Ce.enabled?`common.on`:`common.off`)]})]}),(0,V.jsx)(`p`,{children:m(`drawer.subagentDescription`)}),M&&A===`ready`?(0,V.jsxs)(`div`,{className:`personal-subagent-preview`,children:[(0,V.jsx)(`strong`,{children:m(M.enabled?`drawer.subagentConfirmEnable`:`drawer.subagentConfirmDisable`)}),(0,V.jsx)(`p`,{children:M.enabled?m(`drawer.subagentPreviewSummary`,{count:M.maxChildren,domains:M.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)}):m(`drawer.subagentDisableSummary`)}),M.modelConfig===void 0?null:(0,V.jsxs)(`p`,{children:[m(`drawer.subagentModel`),`: `,M.modelConfig?.model||m(`drawer.subagentModelDefault`),` · `,M.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`button`,{className:`personal-primary-action`,onClick:()=>void ke(),type:`button`,children:m(`common.confirm`)}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:z,type:`button`,children:m(`common.cancel`)})]})]}):null,T?(0,V.jsxs)(`p`,{className:`personal-subagent-feedback is-${A}`,role:`status`,children:[A===`previewing`||A===`applying`?(0,V.jsx)(Lm,{className:`personal-spin`,size:13}):null,T]}):null,(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentModel`)}),(0,V.jsx)(`dd`,{children:Ce.modelConfig?.model||m(`drawer.subagentModelDefault`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentEffort`)}),(0,V.jsx)(`dd`,{children:Ce.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentCurrentBoundary`)}),(0,V.jsx)(`dd`,{children:Ce.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.subagentChildLimit`)}),(0,V.jsx)(`dd`,{children:Ce.maxChildren||0})]})]}),u?(0,V.jsx)(`p`,{className:`personal-subagent-read-only`,children:m(`drawer.subagentRemoteReadOnly`)}):(0,V.jsxs)(`div`,{className:`personal-subagent-fields`,children:[(0,V.jsxs)(`fieldset`,{className:`personal-subagent-domain-picker`,disabled:we,children:[(0,V.jsx)(`legend`,{children:m(`drawer.subagentDomains`)}),Te.length>0?(0,V.jsx)(`div`,{className:`personal-subagent-domain-options`,children:Te.map(e=>{let t=C.includes(e.value);return(0,V.jsxs)(`label`,{className:`personal-subagent-domain-option${t?` is-selected`:``}`,children:[(0,V.jsx)(`input`,{"aria-label":e.value,checked:t,onChange:t=>De(e.value,t.target.checked),type:`checkbox`}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.value}),(0,V.jsx)(`small`,{children:m(`drawer.subagentDomainTodoCount`,{count:e.matchingTodoCount})})]})]},e.value)})}):(0,V.jsx)(`p`,{className:`personal-subagent-domain-empty`,children:m(`drawer.subagentDomainsEmpty`)}),(0,V.jsx)(`small`,{children:m(`drawer.subagentDomainsHint`)})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:m(`drawer.subagentModel`)}),(0,V.jsx)(`input`,{"aria-label":m(`drawer.subagentModel`),disabled:we,value:ee,placeholder:`gpt-5.6-luna`,onChange:e=>{te(e.target.value),N(null),j(`idle`),E(null)}})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:m(`drawer.subagentEffort`)}),(0,V.jsxs)(`select`,{"aria-label":m(`drawer.subagentEffort`),disabled:we,value:ne,onChange:e=>{k(e.target.value),N(null),j(`idle`),E(null)},children:[(0,V.jsx)(`option`,{value:``,children:m(`drawer.subagentModelDefault`)}),[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`].map(e=>(0,V.jsx)(`option`,{value:e,children:e},e))]})]}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:we,type:`button`,onClick:()=>{te(`gpt-5.6-luna`),k(`max`),N(null),j(`idle`),E(null)},children:m(`drawer.subagentLunaPreset`)}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:we,type:`button`,onClick:()=>{te(``),k(``),N(null),j(`idle`),E(null)},children:m(`drawer.subagentClearModel`)}),(0,V.jsx)(`p`,{children:m(`drawer.subagentModelHint`)}),(0,V.jsxs)(`label`,{className:`personal-subagent-limit-field`,children:[(0,V.jsx)(`span`,{children:m(`drawer.subagentMaxChildren`)}),(0,V.jsx)(`select`,{"aria-label":m(`drawer.subagentMaxChildren`),disabled:we,onChange:e=>{O(Number(e.target.value)),N(null),j(`idle`),E(null)},value:D,children:Jy.map(e=>(0,V.jsx)(`option`,{value:e,children:e},e))})]}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,disabled:we,onClick:()=>void Oe(Ce.enabled,!0),type:`button`,children:m(`drawer.subagentPreviewBoundary`)})]})]}):null]}):null,f.kind===`run`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`div`,{"aria-label":m(`drawer.runView`),className:`personal-run-drawer-tabs`,role:`tablist`,children:[(0,V.jsx)(`button`,{"aria-selected":x===`record`,onClick:()=>S(`record`),role:`tab`,type:`button`,children:m(`drawer.executionRecordAndResult`)}),(0,V.jsx)(`button`,{"aria-selected":x===`details`,onClick:()=>S(`details`),role:`tab`,type:`button`,children:m(`drawer.detailsAndActions`)})]}),x===`record`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card personal-session-summary`,children:[(0,V.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Yi(f.item.sessionStatus??f.item.status,m)]}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.latestActivity}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,V.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]})]})]}),(0,V.jsxs)(`section`,{"aria-label":m(`drawer.executionRecord`),className:`personal-session-message-record`,children:[(0,V.jsx)(`h3`,{children:m(`drawer.executionRecord`)}),f.item.sessionMessages?.length?(0,V.jsx)(`ol`,{children:f.item.sessionMessages.map(e=>(0,V.jsxs)(`li`,{className:`is-${e.role}`,children:[(0,V.jsx)(`i`,{}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:e.role===`user`?m(`drawer.runRoleUser`):e.role===`assistant`?m(`drawer.runRoleAssistant`):m(`drawer.runRoleSystem`)}),e.createdAt?(0,V.jsx)(`time`,{children:new Date(e.createdAt).toLocaleTimeString(p,{hour:`2-digit`,minute:`2-digit`,hour12:!1})}):null]}),(0,V.jsx)(`p`,{children:e.text})]})]},e.messageId))}):(0,V.jsx)(`p`,{className:`personal-session-empty`,children:_e?m(`drawer.runRecordProjected`,{completed:f.item.completedSteps,outputs:f.item.outputs?.length?m(`drawer.runRecordProjectedOutputs`,{count:f.item.outputs.length}):``,total:f.item.totalSteps}):m(`drawer.runRecordEmpty`)}),f.item.status===`running`?(0,V.jsxs)(`div`,{className:`personal-session-active-step`,children:[(0,V.jsx)(`i`,{}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.analysis`)}),(0,V.jsx)(`small`,{children:m(`drawer.agentWorking`)})]})]}):null]}),f.item.outputs?.length?(0,V.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-run-outputs-title`,children:[(0,V.jsx)(`h3`,{id:`personal-run-outputs-title`,children:m(`drawer.outputs`)}),(0,V.jsx)(`ol`,{children:f.item.outputs.map(e=>(0,V.jsx)(`li`,{children:(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.title}),(0,V.jsx)(`small`,{children:e.createdAt??e.kind??m(`files.emptySummary`)})]})},e.outputId))})]}):null]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Yi(f.item.status,m)]}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.latestActivity}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,V.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.sessionStatus`)}),(0,V.jsx)(`dd`,{children:Yi(f.item.sessionStatus??f.item.status,m)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.sessionRecoverable`)}),(0,V.jsx)(`dd`,{children:f.item.resumable===!1?m(`drawer.resumeNo`):m(`drawer.resumeYes`)})]})]})]}),f.item.sessionStatus===`resume_failed`&&!u?(0,V.jsxs)(`section`,{className:`personal-recovery-panel`,"aria-label":m(`drawer.recoveryFailed`),children:[(0,V.jsx)(`strong`,{children:m(`drawer.recoveryFailed`)}),(0,V.jsx)(`p`,{children:m(`drawer.recoveryDescription`)}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,V.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.recoveryNewSession`)]})]}):null,u?null:(0,V.jsxs)(`section`,{className:`personal-correction-panel`,children:[(0,V.jsx)(`header`,{children:(0,V.jsxs)(`span`,{children:[(0,V.jsx)(Zp,{size:16}),m(`drawer.correctionLabel`,{agent:f.item.agentLabel})]})}),(0,V.jsx)(`p`,{children:m(`drawer.correctionDescription`)}),(0,V.jsxs)(`div`,{className:`personal-correction-composer`,children:[(0,V.jsx)(`textarea`,{"aria-label":m(`drawer.correctionTextarea`,{agent:f.item.agentLabel,goal:f.item.goalTitle,run:f.item.title}),onChange:e=>g(e.target.value),placeholder:m(`drawer.correctionPlaceholder`),rows:3,value:h}),(0,V.jsx)(`button`,{"aria-label":m(`drawer.correctionSend`),disabled:!h.trim(),onClick:()=>void be(),type:`button`,children:(0,V.jsx)(Bm,{size:16})})]})]}),u?null:(0,V.jsxs)(`details`,{className:`personal-compact-menu personal-run-more`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(dm,{size:17}),m(`drawer.moreRunActions`)]}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`button`,{disabled:!f.item.canInterrupt,onClick:()=>void r.onInterruptRun?.(f.item),type:`button`,children:[(0,V.jsx)(Mm,{size:16}),m(`drawer.runInterrupt`)]}),(0,V.jsxs)(`button`,{disabled:f.item.resumable===!1,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,V.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,V.jsxs)(`button`,{onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.runNewSession`)]}),(0,V.jsxs)(`button`,{onClick:()=>void r.onCloseRunSession?.(f.item),type:`button`,children:[(0,V.jsx)(qm,{size:16}),m(`drawer.runCloseSession`)]})]})]})]})]}):null,f.kind===`output`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsx)(`small`,{children:f.item.kind??`output`}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.summary??m(`drawer.outputRecorded`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Goal`}),(0,V.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.outputTodo`)}),(0,V.jsx)(`dd`,{children:f.item.todoId??m(`drawer.notLinked`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.outputRun`)}),(0,V.jsx)(`dd`,{children:f.item.runId??m(`drawer.notLinked`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Agent`}),(0,V.jsx)(`dd`,{children:f.item.agentLabel??f.item.agentId??`LoopX`})]})]})]}),f.item.report?(0,V.jsxs)(`section`,{className:`personal-report-detail`,"data-testid":`personal-periodic-report-detail`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsxs)(`strong`,{children:[`+`,f.item.report.addedCount]}),m(`files.reportAdded`)]}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:f.item.report.changedCount}),m(`files.reportChanged`)]})]}),(0,V.jsxs)(`p`,{children:[f.item.report.periodStartAt,` → `,f.item.report.periodEndAt]}),(0,V.jsx)(`ol`,{children:f.item.report.items.map(e=>(0,V.jsxs)(`li`,{"data-change-kind":e.changeKind,children:[(0,V.jsxs)(`small`,{children:[e.changeKind,` · `,e.status]}),(0,V.jsx)(`strong`,{children:e.title}),(0,V.jsx)(`p`,{children:e.summary})]},e.sourceRef))}),(0,V.jsxs)(`footer`,{children:[(0,V.jsxs)(`span`,{children:[m(`files.reportPublication`),`: `,f.item.report.publicationId]}),(0,V.jsxs)(`span`,{children:[m(`files.reportGeneration`),`: `,f.item.report.generationId]})]})]}):null,f.item.safePreview?(0,V.jsx)(`pre`,{"aria-label":m(`drawer.outputSafePreview`),className:`personal-safe-preview`,children:f.item.safePreview}):(0,V.jsx)(`p`,{className:`personal-preview-unavailable`,children:m(`drawer.previewUnavailable`)}),(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:!r.onOpenOutput,onClick:()=>{r.onOpenOutput?.(f.item),c()},type:`button`,children:[(0,V.jsx)(fm,{size:16}),m(`files.openConversation`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!r.onExportOutput,onClick:()=>void r.onExportOutput?.(f.item),type:`button`,children:[(0,V.jsx)(um,{size:16}),m(`files.exportSummary`)]})]})]}):null,f.kind===`proposal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-proposal-card`,children:[(0,V.jsxs)(`small`,{children:[f.item.actionKind,` · `,f.item.status]}),(0,V.jsx)(`h3`,{children:f.item.title}),(0,V.jsx)(`p`,{children:f.item.impact}),f.item.reviewPlan?(0,V.jsx)(`p`,{className:`personal-proposal-explainer`,"data-action-review":f.item.reviewPlan.interaction,children:m(`actionReview.${f.item.reviewPlan.reason}`)}):null,f.item.status===`ready`?(0,V.jsx)(`p`,{className:`personal-proposal-explainer`,children:m(`drawer.proposalExplainer`)}):null,(0,V.jsx)(`dl`,{children:f.item.fields.map(e=>(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:e.label}),(0,V.jsx)(`dd`,{children:e.value})]},e.key))})]}),f.item.status===`applied`?(0,V.jsxs)(`p`,{className:`personal-proposal-state is-applied`,children:[(0,V.jsx)(em,{size:16}),m(`drawer.proposalApplied`)]}):null,f.item.status===`applied`&&f.item.goalId?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>{let e=f.item.goalId;c(),r.onOpenGoal?.(e)},type:`button`,children:[(0,V.jsx)(fm,{size:16}),f.item.actionKind===`goal.create`?m(`drawer.proposalEnterGoal`):m(`drawer.proposalViewGoal`)]}):null,f.item.status===`stale`?(0,V.jsx)(`p`,{className:`personal-proposal-state is-stale`,children:m(`drawer.proposalStale`)}):null,f.item.status===`error`?(0,V.jsxs)(`div`,{className:`personal-proposal-state is-error`,children:[(0,V.jsx)(`span`,{children:f.item.reviewPlan?.reason===`readback_unverified`?m(`actionReview.readback_unverified`):m(`drawer.proposalApplyFailed`)}),f.item.errorMessage?(0,V.jsx)(`small`,{children:f.item.errorMessage}):null,(0,V.jsx)(`small`,{children:m(`drawer.proposalApplyFailedHint`)})]}):null,f.item.status===`rejected`?(0,V.jsx)(`p`,{className:`personal-proposal-state is-error`,children:m(`drawer.proposalRejected`)}):null,f.item.status===`deferred`?(0,V.jsx)(`p`,{className:`personal-proposal-state is-gated`,children:m(`drawer.proposalDeferred`)}):null,f.item.status===`gated`?(0,V.jsxs)(`div`,{className:`personal-proposal-state is-gated`,children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:m(`drawer.gateRequiresHost`)}),m(`drawer.gateRequiresHostDescription`)]}),f.item.gate?.nextAction?(0,V.jsx)(`small`,{children:f.item.gate.nextAction}):null]}):null,f.item.status===`gated`&&f.item.actionKind===`gate.resolve`?(()=>{let e=e=>f.item.fields.find(t=>t.key===e)?.value,t=e(`goal_id`),n=e(`todo_id`);return!t||!n?null:(0,V.jsxs)(`section`,{className:`personal-detail-card personal-gate-cli-hint`,children:[(0,V.jsx)(`small`,{children:m(`drawer.gateApproveHint`)}),(0,V.jsxs)(`code`,{children:[`loopx todo complete --goal-id `,t,` --todo-id `,n,` --decision-outcome approve`]}),(0,V.jsx)(`small`,{children:m(`drawer.gateRejectHint`)})]})})():null,!u&&f.item.workspaceCandidates?.length?(0,V.jsx)(`div`,{className:`personal-workspace-candidates`,"aria-label":m(`drawer.workspaceCandidates`),children:f.item.workspaceCandidates.map(e=>(0,V.jsxs)(`button`,{onClick:()=>void r.onSelectWorkspaceCandidate?.(f.item,e.workspaceRef),type:`button`,children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsx)(`small`,{children:e.workspaceRef})]},e.workspaceRef))}):null,!u&&f.item.status===`error`?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,V.jsx)(Lm,{size:17}),m(`drawer.proposalRegenerate`)]}):!u&&f.item.status!==`gated`?(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:![`ready`,`deferred`].includes(f.item.status)||f.item.reviewPlan?.canApply===!1,onClick:()=>void r.onApplyProposal?.(f.item),type:`button`,children:[(0,V.jsx)(em,{size:17}),f.item.status===`applying`?m(`drawer.applying`):f.item.primaryLabel??m(`drawer.apply`)]}):null,!u&&([`stale`,`gated`,`rejected`].includes(f.item.status)||f.item.status===`ready`&&f.item.reviewPlan?.canApply===!1)?(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,V.jsx)(Lm,{size:16}),m(`drawer.proposalRecheck`)]}):null,!u&&[`ready`,`gated`].includes(f.item.status)?(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`defer`),type:`button`,children:m(`drawer.proposalDefer`)}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`reject`),type:`button`,children:m(`drawer.decisionReject`)})]}):null,[`applied`,`applying`].includes(f.item.status)?null:(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:c,type:`button`,children:m(`drawer.proposalClose`)})]}):null,f.kind===`schedule`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,V.jsxs)(`small`,{children:[f.item.scheduleKind===`heartbeat`?`Goal Heartbeat`:`continuous_monitor`,` · `,f.item.status??`active`]}),(0,V.jsx)(`h3`,{children:f.item.label}),(0,V.jsx)(`p`,{children:f.item.target??f.item.schedule??m(`drawer.scheduleDefaultTarget`)}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleTimezone`)}),(0,V.jsx)(`dd`,{children:f.item.timezone??m(`drawer.scheduleLocalTimezone`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleNext`)}),(0,V.jsx)(`dd`,{children:f.item.nextRunAt??m(`drawer.schedulePending`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleLast`)}),(0,V.jsx)(`dd`,{children:f.item.previousRunAt??m(`drawer.scheduleNeverRun`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleNotification`)}),(0,V.jsx)(`dd`,{children:f.item.notificationRule??m(`drawer.scheduleDefaultNotification`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:m(`drawer.scheduleStopCondition`)}),(0,V.jsx)(`dd`,{children:f.item.stopCondition??m(`drawer.scheduleDefaultStop`)})]})]})]}),!u&&f.item.scheduleKind===`monitor`?(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`run_now`),type:`button`,children:[(0,V.jsx)(Nm,{size:16}),m(`drawer.scheduleRunNow`)]}):null,u?null:(0,V.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,f.item.status===`paused`?`resume`:`pause`),type:`button`,children:[f.item.status===`paused`?(0,V.jsx)(Nm,{size:16}):(0,V.jsx)(Mm,{size:16}),f.item.status===`paused`?m(`drawer.scheduleResume`):m(`drawer.schedulePause`)]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`edit`),type:`button`,children:[(0,V.jsx)($p,{size:16}),m(`drawer.scheduleEdit`)]})]}),u?null:(0,V.jsxs)(`button`,{className:`personal-danger-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`stop`),type:`button`,children:[(0,V.jsx)(qm,{size:16}),m(`drawer.scheduleStop`,{kind:f.item.scheduleKind===`heartbeat`?` Heartbeat`:m(`drawer.titleSchedule`)})]}),(0,V.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-execution-history-title`,children:[(0,V.jsx)(`h3`,{id:`personal-execution-history-title`,children:m(`drawer.executionHistory`)}),f.item.executionHistory?.length?(0,V.jsx)(`ol`,{children:f.item.executionHistory.map((e,t)=>(0,V.jsxs)(`li`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsx)(`small`,{children:e.timestamp})]}),(0,V.jsx)(`em`,{className:`is-${e.status}`,children:e.status})]},`${e.timestamp}:${e.runId??t}`))}):(0,V.jsx)(`p`,{children:m(`drawer.noExecutionHistory`)})]})]}):null,f.kind===`run`||f.kind===`proposal`||f.kind===`schedule`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`button`,{"aria-expanded":_,className:`personal-diagnostics-trigger`,onClick:()=>v(e=>!e),type:`button`,children:[(0,V.jsx)(`span`,{children:m(`drawer.advancedDiagnostics`)}),(0,V.jsx)(tm,{className:_?`is-open`:``,size:16})]}),_?(0,V.jsxs)(`div`,{className:`personal-diagnostics`,children:[(0,V.jsxs)(`code`,{children:[`goal_id: `,me]}),(0,V.jsxs)(`code`,{children:[`kind: `,f.kind]}),f.kind===`run`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`code`,{children:[`session_id: `,f.item.sessionId??m(`drawer.notLinked`)]}),(0,V.jsxs)(`code`,{children:[`turn_id: `,f.item.turnId??m(`common.none`)]}),(0,V.jsxs)(`code`,{children:[`adapter: `,f.item.agentId]}),(0,V.jsxs)(`code`,{children:[`status: `,f.item.sessionStatus??f.item.status]})]}):f.kind===`proposal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`code`,{children:[`action: `,f.item.actionKind]}),(0,V.jsxs)(`code`,{children:[`status: `,f.item.status]})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`code`,{children:[`schedule_id: `,f.item.scheduleId]}),(0,V.jsxs)(`code`,{children:[`status: `,f.item.status??`active`]})]})]}):null]}):null]})]})}var $y=[`checking`,`connecting`,`downloading`,`installing_app`,`installing_runtime`],eb={desktop_status_unavailable:[`无法读取 App 更新状态。请重启 App 后再试;若仍失败,请重新安装最新 App。`,`Cannot read the App update status. Restart the App; if this persists, reinstall the latest App.`],update_feed_unavailable:[`此通道的更新源尚未就绪或暂时不可用。可稍后重新检查,当前版本仍可继续使用。`,`This channel's update feed is not ready or temporarily unavailable. Check again later; you can keep using this version.`],update_feed_invalid:[`更新源格式异常。请稍后重新检查。`,`The update feed is invalid. Check again later.`],update_platform_unavailable:[`此通道尚无适用于本机的更新包。`,`This channel has no update package for this platform.`],update_check_timeout:[`检查更新超时。请稍后重试。`,`The update check timed out. Try again later.`],update_network_failed:[`无法连接更新服务器。请检查网络后重试。`,`Cannot reach the update server. Check your connection and retry.`],update_download_or_signature_failed:[`更新包下载或签名校验失败,尚未安装。请重新检查更新。`,`Download or signature verification failed; the update was not installed. Check for updates again.`]};function tb(e,t=`update_failed`){return{phase:`error`,details:{code:typeof e==`string`&&Object.hasOwn(eb,e)?e:t}}}function nb(){let{locale:e}=qi(),t=e===`zh-CN`,[n,r]=(0,B.useState)(!1),i=(0,B.useRef)(null),[a,o]=(0,B.useState)(`stable`),[s,c]=(0,B.useState)({phase:`idle`}),[l,u]=(0,B.useState)(``),[d,f]=(0,B.useState)(!1),p=(0,B.useRef)(!1),m=window.__TAURI__?.core.invoke,h=$y.includes(s.phase);(0,B.useEffect)(()=>{let e=i.current;if(!e)return;let t=()=>r(e.matches(`:popover-open`));return e.addEventListener(`toggle`,t),()=>e.removeEventListener(`toggle`,t)},[]),(0,B.useEffect)(()=>{if(!m)return;let e=!0;return m(`desktop_update_status`).then(t=>{if(!e)return;u(t.app_version),f(t.rollback_available===!0),t.state?.phase&&c(t.state);let n=t.state?.details?.channel??(t.app_version.includes(`-main.`)?`main`:`stable`);o(n),t.state?.phase||m(`desktop_update`,{action:`check`,channel:n}).then(t=>{e&&c(t)}).catch(t=>{e&&c(tb(t))})}).catch(()=>{e&&c(tb(null,`desktop_status_unavailable`))}),()=>{e=!1}},[m]),(0,B.useEffect)(()=>{if(!m||!h)return;let e=window.setInterval(()=>{m(`desktop_update_status`).then(e=>{e.state?.phase&&c(e.state)}).catch(()=>{})},1e3);return()=>window.clearInterval(e)},[m,h]);async function g(e){if(!(!m||p.current)){p.current=!0,c({phase:e===`check`?`checking`:e===`repair`?`installing_runtime`:`downloading`});try{if(!l){let e=await m(`desktop_update_status`);u(e.app_version),f(e.rollback_available===!0)}c(await m(`desktop_update`,{action:e,channel:a}))}catch(e){c(tb(e,l?`update_failed`:`desktop_status_unavailable`))}finally{p.current=!1}}}let _={service_error:t?`运行时已安装,但服务尚未连接。可重试更新、修复或恢复上版。`:`Runtime installed, but services are unavailable. Retry updates, repair, or restore the previous version.`,idle:t?`App 会检查可用更新,不会自动安装。`:`Updates are checked automatically, never installed without confirmation.`,runtime_required:t?`请完成匹配组件安装,或检查 App 更新。`:`Install matching components or check for an App update.`,connecting:t?`正在连接更新后的服务…`:`Connecting to updated services…`,checking:t?`正在检查更新…`:`Checking for updates…`,available:t?`新版本已就绪,一次更新 App 与匹配的运行时。`:`Update the App and its matching runtime together.`,up_to_date:t?`当前通道暂无更新。`:`No newer update on this channel.`,downloading:t?`正在下载并校验签名…`:`Downloading and verifying signature…`,installing_app:t?`正在安装 App,请保持窗口打开。`:`Installing the App. Keep this window open.`,installing_runtime:t?`正在安装匹配的运行时,请稍候…`:`Installing the matching runtime…`,restart_required:t?`重启后将自动完成运行时安装与服务连接。`:`Restart to finish runtime installation and reconnect services.`,ready:t?`更新完成,服务已就绪。`:`Update completed; services are ready.`,error:eb[s.details?.code??``]?.[+!t]??(t?`更新未完成。请重试;启动失败可尝试修复当前版本。`:`Update incomplete. Retry; repair this version if startup fails.`)},v=h?t?`正在更新…`:`Updating…`:s.phase===`available`?t?`有可用更新`:`Update available`:s.phase===`restart_required`?t?`重启完成更新`:`Restart to finish`:s.phase===`error`?t?`更新需重试`:`Retry update`:t?`更新 LoopX`:`Update LoopX`;return(0,V.jsxs)(`div`,{className:`personal-desktop-update`,children:[(0,V.jsxs)(`button`,{className:`personal-update-trigger`,type:`button`,"aria-expanded":n,"aria-controls":`desktop-update-panel`,onClick:e=>{i.current?.style.setProperty(`bottom`,`${window.innerHeight-e.currentTarget.getBoundingClientRect().top+8}px`),i.current?.togglePopover()},children:[(0,V.jsx)(um,{size:16,"aria-hidden":`true`}),(0,V.jsx)(`span`,{children:v}),(0,V.jsx)(rm,{size:14,"aria-hidden":`true`})]}),(0,V.jsxs)(`section`,{ref:i,popover:`auto`,id:`desktop-update-panel`,className:`personal-update-panel`,"aria-label":t?`LoopX 更新`:`LoopX updates`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:t?`LoopX 更新`:`LoopX updates`}),(0,V.jsx)(`button`,{type:`button`,"aria-label":t?`关闭更新面板`:`Close updates`,onClick:()=>i.current?.hidePopover(),children:(0,V.jsx)($m,{size:16,"aria-hidden":`true`})})]}),(0,V.jsxs)(`small`,{children:[l,` · `,a===`main`?t?`main 预览版`:`main preview`:t?`稳定版`:`Stable`]}),s.details?.version?(0,V.jsxs)(`p`,{children:[t?`目标版本:`:`Target: `,s.details.version]}):null,(0,V.jsxs)(`p`,{role:`status`,"aria-live":`polite`,children:[h?(0,V.jsx)(Im,{className:`is-spinning`,size:14,"aria-hidden":`true`}):null,_[s.phase]]}),s.phase===`downloading`&&s.details?.total?(0,V.jsx)(`progress`,{"aria-label":t?`下载进度`:`Download progress`,max:s.details.total,value:s.details.received??0}):null,m?(0,V.jsx)(`div`,{className:`personal-update-actions`,children:s.phase===`restart_required`?(0,V.jsx)(`button`,{type:`button`,onClick:()=>void g(`restart`),children:t?`重启完成更新`:`Restart to finish`}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{type:`button`,disabled:h,onClick:()=>void g(`check`),children:t?`检查更新`:`Check for updates`}),s.phase===`available`?(0,V.jsx)(`button`,{type:`button`,onClick:()=>void g(`apply`),children:t?`更新并准备重启`:`Install update`}):null]})}):(0,V.jsx)(`p`,{children:t?`请在 LoopX App 中更新;浏览器自身无需安装包。`:`Update from the LoopX App; the browser needs no installer.`}),(0,V.jsxs)(`details`,{children:[(0,V.jsx)(`summary`,{children:t?`高级选项`:`Advanced options`}),(0,V.jsxs)(`label`,{children:[t?`更新通道`:`Update channel`,(0,V.jsxs)(`select`,{disabled:h||s.phase===`restart_required`,value:a,onChange:e=>{o(e.target.value),c({phase:`idle`})},children:[(0,V.jsx)(`option`,{value:`stable`,children:t?`稳定版(推荐)`:`Stable (recommended)`}),(0,V.jsx)(`option`,{value:`main`,children:t?`main 预览版`:`main preview`})]})]}),(0,V.jsx)(`p`,{children:t?`App 与匹配的 CLI 一起更新,服务可能短暂断开。不删除 Goal 数据。`:`Updates the App and matching CLI. Services may briefly disconnect. Goal data is not deleted.`}),m?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{children:t?`启动失败时,可重装当前 App 随附的运行时。`:`If startup fails, reinstall this App's bundled runtime.`}),(0,V.jsx)(`button`,{disabled:h||s.phase===`restart_required`,type:`button`,onClick:()=>void g(`repair`),children:t?`修复当前版本`:`Repair this version`})]}):null,m&&d?(0,V.jsxs)(`details`,{children:[(0,V.jsx)(`summary`,{children:t?`恢复上个版本`:`Restore previous version`}),(0,V.jsx)(`p`,{children:t?`将恢复已保留的 App 和它的运行时,需要重启。`:`Restore the retained App and its runtime, then restart.`}),(0,V.jsx)(`button`,{disabled:h,type:`button`,onClick:()=>void g(`rollback`),children:t?`确认恢复上版`:`Restore previous version`})]}):null]})]})]})}var rb=e=>`loopx-sidebar-goal-order-v1:${encodeURIComponent(e)}`;function ib(e){try{let t=JSON.parse(e??`null`);return Array.isArray(t)&&t.every(e=>typeof e==`string`)?[...new Set(t)]:[]}catch{return[]}}function ab(e,t){let n=new Map(t.map((e,t)=>[e,t]));return[...e].sort((e,t)=>(n.get(e.goalId)??1/0)-(n.get(t.goalId)??1/0))}function ob(e,t,n,r,i){if(n===r||!t.includes(n)||!t.includes(r))return e;let a=[...new Set([...e,...t])].filter(e=>e!==n);return a.splice(a.indexOf(r)+Number(i),0,n),a}function sb(e,t){let n=rb(t),[r,i]=(0,B.useState)(()=>{try{return ib(localStorage.getItem(n))}catch{return[]}}),[a,o]=(0,B.useState)(!1),[s,c]=(0,B.useState)(null),[l,u]=(0,B.useState)(null),d=(0,B.useRef)(null),f=(0,B.useRef)(!1),p=ab(e,r),m=p.map(e=>e.goalId);function h(t,a,s){let l=ob(r,m,t,a,s);if(l===r)return;i(l);let u=ab(e,l),d=u.findIndex(e=>e.goalId===t),f=u[d];f&&c({title:f.title,position:d+1});try{localStorage.setItem(n,JSON.stringify(l)),o(!1)}catch{o(!0)}}function g(){d.current=null,u(null)}return{sorted:p,target:l,saveFailed:a,lastMoved:s,move:h,moveBy(e,t){let n=p[m.indexOf(e)+t];n&&h(e,n.goalId,t===1)},pointerProps:e=>({onPointerDown(t){f.current=!1,t.pointerType===`mouse`&&t.button===0&&(d.current={id:e,x:t.clientX,y:t.clientY,dragging:!1},t.currentTarget.setPointerCapture(t.pointerId))},onPointerMove(e){let t=d.current;if(!t||!t.dragging&&Math.hypot(e.clientX-t.x,e.clientY-t.y)<6)return;t.dragging=!0,f.current=!0;let n=document.elementFromPoint(e.clientX,e.clientY)?.closest(`[data-reorder-goal]`),r=e.currentTarget.closest(`.personal-goal-list`),i=n?.dataset.reorderGoal;if(!n||!i||!r?.contains(n)||i===t.id){u(null);return}let a=n.getBoundingClientRect();u({id:i,after:e.clientY>a.top+a.height/2})},onPointerUp(){d.current?.dragging&&l&&h(d.current.id,l.id,l.after),g()},onPointerCancel:g,onLostPointerCapture:g,onKeyDown(e){e.key===`Escape`&&g()},onClickCapture(e){f.current&&=(e.preventDefault(),e.stopPropagation(),!1)}})}}var cb=`/ssh-hosts`,lb=/^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;function ub(e){return typeof e==`string`&&lb.test(e.trim())}function db(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`SSH Host 列表响应无效。`);let t=e;if(t.ok!==!0||t.schema_version!==`ssh_host_catalog_v0`||!Array.isArray(t.hosts))throw Error(`SSH Host 列表协议不兼容,请更新本机 LoopX 服务。`);let n=new Set;return{hosts:t.hosts.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=String(e.alias??``).trim();return!ub(t)||n.has(t)?[]:(n.add(t),[{alias:t}])}),schemaVersion:`ssh_host_catalog_v0`}}async function fb(e=fetch,t=cb){let n=await e(t,{cache:`no-store`});if(!n.ok)throw Error(`无法读取本机 SSH Host(HTTP ${n.status})。`);return db(await n.json())}function pb(e,t){let n=e.trim();if(!ub(n))return{error:`请选择有效的 SSH Host。`};let r=Number(t);return!Number.isInteger(r)||r<1024||r>65535?{error:`本地端口必须是 1024–65535 之间的整数。`}:{command:`ssh -N -L ${r}:127.0.0.1:8766 ${n}`,hostAlias:n,label:n,statusUrl:`http://127.0.0.1:${r}/status.json`}}var mb=`/api/ssh-source/ensure`,hb=`/api/ssh-source/goal-lifecycle`;async function gb(e,t){let n=await fetch(mb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({host_alias:e,local_port:Number(t)})}),r=await n.json().catch(()=>null);if(!n.ok)throw Error(r?.error??`无法建立 SSH 隧道来源。`);if(!r?.ok)throw Error(`无法建立 SSH 隧道来源。`);return r}async function _b(e,t,n,r,i=fetch){let a=await i(hb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({goal_id:t,host_alias:e,operation:n,reason:r})}),o=await a.json().catch(()=>null);if(!a.ok)throw Error(o?.error??`无法更新远端 Goal 生命周期。`);if(!o?.ok||o.schema_version!==`loopx_remote_goal_lifecycle_v1`||o.goal_id!==t||o.host_alias!==e||o.operation!==n||o.activation_state!==(n===`stop`?`stopped`:`active`)||o.projection_verified!==!0)throw Error(`远端 Goal 生命周期回读未验证。`);return o}function vb({activeSource:e,connectionState:t,errorMessage:n,onAdd:r,onConfiguredHostsLoaded:i,onRemove:a,onSelect:o,sources:s}){let{t:c}=qi(),[l,u]=(0,B.useState)(!1),[d,f]=(0,B.useState)(null),[p,m]=(0,B.useState)(`configured`),[h,g]=(0,B.useState)([]),[_,v]=(0,B.useState)(null),[y,b]=(0,B.useState)(!1),[x,S]=(0,B.useState)(!1),[C,w]=(0,B.useState)(``),[T,E]=(0,B.useState)(``),[D,O]=(0,B.useState)(`8876`),[ee,te]=(0,B.useState)(``),ne=`configured:`,k=[...s.map(e=>({label:e.label,value:e.id})),...h.filter(e=>!s.some(t=>t.label===e.alias)).map(e=>({group:c(`source.configuredGroup`,{count:h.length}),label:e.alias,value:`${ne}${e.alias}`}))],A=(0,B.useMemo)(()=>h.some(e=>e.alias===C)?pb(C,D):{error:c(`source.selectHost`)},[h,C,D,c]);(0,B.useEffect)(()=>{j()},[]);async function j(){b(!0),v(null);try{let e=await fb();g(e.hosts),i?.(e.hosts.map(e=>e.alias)),w(t=>t||e.hosts[0]?.alias||``),e.hosts.length||v(c(`source.hostEmpty`))}catch(e){v(e instanceof Error?e.message:c(`source.hostLoadError`))}finally{b(!1)}}function M(){u(!0),m(`configured`),f(null),j()}function N(){u(!1),m(`configured`),v(null),S(!1),w(``),f(null),E(``),O(`8876`),te(``)}function P(){let e=r({label:T,statusUrl:ee});if(e.error){f(e.error);return}N()}function F(){if(`error`in A){f(A.error??c(`source.invalid`));return}let e=r({ensureTunnel:!0,hostAlias:A.hostAlias,label:A.label,statusUrl:A.statusUrl});if(e.error){f(e.error);return}N()}function re(e){let t=new Set;for(let e of s)try{t.add(new URL(e.statusUrl).port)}catch{}let n=`8877`;for(let e=8877;e<9077;e+=1)if(!t.has(String(e))){n=String(e);break}let i=pb(e,n);if(`error`in i){f(i.error??c(`source.invalid`));return}let a=r({ensureTunnel:!0,hostAlias:i.hostAlias,label:i.label,statusUrl:i.statusUrl});a.error?f(a.error):f(null),O(n)}async function ie(){if(`error`in A){f(A.error??c(`source.invalid`));return}try{await navigator.clipboard.writeText(A.command),S(!0),f(null)}catch{f(c(`source.copyError`))}}return(0,V.jsxs)(`section`,{"aria-label":c(`source.controlPlane`),className:`personal-status-source`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`span`,{children:`Control plane`}),(0,V.jsx)(`button`,{"aria-label":c(`source.addSsh`),onClick:M,title:c(`source.add`),type:`button`,children:(0,V.jsx)(Pm,{size:14})})]}),(0,V.jsx)(Sy,{ariaLabel:c(`source.select`),className:`personal-status-source-select`,icon:(0,V.jsx)(Hm,{size:15}),onChange:e=>{if(e.startsWith(ne)){re(e.slice(11));return}o(e)},options:k,value:e.id}),(0,V.jsxs)(`div`,{className:`personal-status-source-meta`,children:[(0,V.jsxs)(`span`,{className:`is-${t}`,children:[(0,V.jsx)(`i`,{}),c(t===`loading`?`source.connecting`:t===`error`?`source.notAvailable`:`source.connected`)]}),(0,V.jsx)(`small`,{children:e.readOnly?c(`source.readOnly`):c(`source.localInteractive`)}),e.kind===`ssh_tunnel`?(0,V.jsx)(`button`,{"aria-label":c(`source.remove`,{source:e.label}),onClick:()=>a(e.id),title:c(`source.removeCurrent`),type:`button`,children:(0,V.jsx)(Xm,{size:12})}):null]}),n?(0,V.jsx)(`p`,{className:`personal-status-source-error`,role:`alert`,children:n}):null,l?(0,V.jsxs)(`div`,{className:`personal-status-source-form`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:c(`source.addSsh`)}),(0,V.jsx)(`button`,{"aria-label":c(`source.closeForm`),onClick:N,type:`button`,children:(0,V.jsx)($m,{size:13})})]}),(0,V.jsxs)(`div`,{"aria-label":c(`source.addMethod`),className:`personal-status-source-modes`,role:`tablist`,children:[(0,V.jsx)(`button`,{"aria-selected":p===`configured`,onClick:()=>{m(`configured`),f(null)},role:`tab`,type:`button`,children:c(`source.configured`)}),(0,V.jsx)(`button`,{"aria-selected":p===`manual`,onClick:()=>{m(`manual`),f(null)},role:`tab`,type:`button`,children:c(`source.manual`)})]}),p===`configured`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.configuredCount`,{count:h.length})}),(0,V.jsxs)(`span`,{className:`personal-status-source-field-row`,children:[(0,V.jsx)(`input`,{"aria-label":c(`source.host`),disabled:y||!h.length,list:`loopx-configured-ssh-hosts`,onChange:e=>{w(e.target.value),S(!1)},placeholder:c(y?`source.loadingHosts`:`source.hostPlaceholder`),value:C}),(0,V.jsx)(`datalist`,{id:`loopx-configured-ssh-hosts`,children:h.map(e=>(0,V.jsx)(`option`,{value:e.alias},e.alias))}),(0,V.jsx)(`button`,{"aria-label":c(`source.refreshHosts`),disabled:y,onClick:()=>void j(),title:c(`source.refreshHosts`),type:`button`,children:(0,V.jsx)(Rm,{size:13})})]})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.localPort`)}),(0,V.jsx)(`input`,{"aria-label":c(`source.localPort`),inputMode:`numeric`,onChange:e=>{O(e.target.value),S(!1)},value:D})]}),(0,V.jsxs)(`div`,{className:`personal-status-source-command`,children:[(0,V.jsx)(`code`,{children:`error`in A?c(`source.tunnelCommandPending`):A.command}),(0,V.jsxs)(`button`,{"aria-label":c(`source.copyCommand`),disabled:`error`in A,onClick:()=>void ie(),type:`button`,children:[(0,V.jsx)(cm,{size:12}),c(x?`source.copied`:`source.copy`)]})]}),_?(0,V.jsx)(`p`,{className:`is-error`,children:_}):null,(0,V.jsx)(`p`,{children:c(`source.description`)}),(0,V.jsx)(`button`,{className:`personal-status-source-add`,disabled:`error`in A,onClick:F,type:`button`,children:c(`source.addConfigured`)})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.name`)}),(0,V.jsx)(`input`,{autoFocus:!0,maxLength:48,onChange:e=>E(e.target.value),placeholder:c(`source.namePlaceholder`),value:T})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:c(`source.statusUrl`)}),(0,V.jsx)(`input`,{onChange:e=>te(e.target.value),placeholder:`http://127.0.0.1:8876/status.json`,value:ee})]}),(0,V.jsx)(`p`,{children:(0,V.jsx)(`code`,{children:`ssh -N -L 8876:127.0.0.1:8766 `})}),(0,V.jsx)(`p`,{children:c(`source.manualDescription`)}),(0,V.jsx)(`button`,{className:`personal-status-source-add`,onClick:P,type:`button`,children:c(`source.addConfigured`)})]}),d?(0,V.jsx)(`p`,{className:`is-error`,role:`alert`,children:d}):null]}):null]})}var yb={需修复:`is-danger`,等你:`is-warning`,等待条件:`is-info`,推进中:`is-success`,安静运行:`is-quiet`,已完成:`is-quiet`,已停止:`is-stopped`};function bb({attentionCount:e,goals:t,goalArchiveLoadState:n={error:null,phase:`ready`},lifecycleBusyGoalIds:r,goalLifecycleOperations:i,onRequestGoalCreate:a,onOpenSettings:o,onRetryGoalArchive:s,onRequestGoalLifecycle:c,onSelectGoal:l,selectedGoalId:u,statusSourceControl:d}){let{locale:f,t:p}=qi(),[m,h]=(0,B.useState)(!1),g=sb(t.filter(e=>e.activationState!==`stopped`),d?.activeSource.statusUrl??`/status.json`),_=g.sorted,v=t.filter(e=>e.activationState===`stopped`),y=e=>!!c&&(!i||i.includes(e)),b=(e,t)=>(0,V.jsxs)(`div`,{className:`personal-goal-row${g.target?.id===e.goalId?g.target.after?` is-drop-after`:` is-drop-before`:``}`,"data-reorder-goal":t?void 0:e.goalId,"data-load-error":e.loadError,children:[(0,V.jsxs)(`button`,{...t?{}:g.pointerProps(e.goalId),title:t?void 0:p(`sidebar.dragGoal`),"aria-current":u===e.goalId?`page`:void 0,className:`personal-goal-link`,onClick:()=>l(e.goalId),type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-goal-state-dot ${e.loadState?``:yb[e.state]}`}),(0,V.jsxs)(`span`,{className:`personal-goal-link-copy`,children:[(0,V.jsx)(`strong`,{children:e.title}),(0,V.jsxs)(`small`,{children:[e.loadState&&(!t||u===e.goalId)?p(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Ji(e.state,f),e.needsYou&&!t?` · ${p(`home.lane.needsYou`)}`:``]})]}),(0,V.jsx)(nm,{size:15})]}),!t&&m?(0,V.jsxs)(`div`,{className:`personal-goal-move-actions`,children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveUp`,{goal:e.title}),disabled:_[0]?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,-1),children:(0,V.jsx)(Jp,{"aria-hidden":`true`,size:13})}),(0,V.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveDown`,{goal:e.title}),disabled:_.at(-1)?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,1),children:(0,V.jsx)(Wp,{"aria-hidden":`true`,size:13})})]}):null,c&&y(t?`resume`:`stop`)?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{"aria-label":`${p(t?`sidebar.resume`:`sidebar.stop`)} ${e.title}`,"aria-busy":r?.has(e.goalId)||void 0,className:`personal-goal-lifecycle${r?.has(e.goalId)?` is-pending`:``}`,disabled:r?.has(e.goalId),onClick:()=>c(e,t?`resume`:`stop`),title:p(t?`sidebar.resumeGoal`:`sidebar.stopGoal`),type:`button`,children:r?.has(e.goalId)?(0,V.jsx)(Cm,{size:13}):t?(0,V.jsx)(Lm,{size:13}):(0,V.jsx)(Mm,{size:13})}),t&&y(`delete`)?(0,V.jsx)(`button`,{"aria-label":`${p(`sidebar.delete`)} ${e.title}`,className:`personal-goal-lifecycle personal-goal-delete`,onClick:()=>c(e,`delete`),title:p(`sidebar.deleteGoal`),type:`button`,children:(0,V.jsx)(Xm,{size:13})}):null]}):null]},e.goalId);return(0,V.jsxs)(`div`,{className:`personal-goal-directory`,children:[(0,V.jsxs)(`div`,{className:`personal-sidebar-brand`,children:[(0,V.jsx)(`span`,{className:`personal-brand-mark`,children:(0,V.jsx)(Zp,{size:18})}),(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:`LoopX`})})]}),d?(0,V.jsx)(vb,{...d}):null,(0,V.jsxs)(`nav`,{"aria-label":p(`home.workspace`),className:`personal-sidebar-nav`,children:[(0,V.jsxs)(`button`,{"aria-current":u===null?`page`:void 0,className:`personal-manager-link`,onClick:()=>l(null),type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-manager-icon`,children:(0,V.jsx)(Zp,{size:17})}),(0,V.jsx)(`span`,{children:p(`sidebar.manager`)}),e>0?(0,V.jsx)(`span`,{className:`personal-sidebar-count`,children:e}):null,(0,V.jsx)(nm,{size:15})]}),(0,V.jsxs)(`div`,{className:`personal-sidebar-section-title`,children:[(0,V.jsx)(`span`,{children:`Goals`}),(0,V.jsxs)(`span`,{className:`personal-sidebar-title-actions`,children:[(0,V.jsx)(`small`,{children:_.length}),(0,V.jsx)(`button`,{"aria-label":p(`sidebar.sortGoals`),title:p(`sidebar.sortGoals`),"aria-pressed":m,onClick:()=>h(!m),type:`button`,children:(0,V.jsx)(qp,{"aria-hidden":`true`,size:15})}),a?(0,V.jsx)(`button`,{"aria-label":p(`sidebar.createGoal`),onClick:a,type:`button`,children:(0,V.jsx)(Pm,{size:15})}):null]})]}),g.saveFailed?(0,V.jsx)(`p`,{role:`status`,children:p(`sidebar.orderNotSaved`)}):null,(0,V.jsx)(`span`,{className:`personal-sr-only`,role:`status`,children:g.lastMoved?p(`sidebar.goalMoved`,{goal:g.lastMoved.title,position:g.lastMoved.position}):``}),(0,V.jsx)(`div`,{className:`personal-goal-list`,children:_.map(e=>b(e,!1))}),v.length||n.phase===`loading`||n.phase===`error`?(0,V.jsxs)(`details`,{className:`personal-stopped-goals`,open:n.phase===`error`||void 0,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(tm,{size:13}),(0,V.jsx)(`span`,{children:p(`sidebar.stopped`)}),n.phase===`loading`?(0,V.jsx)(Cm,{"aria-label":p(`sidebar.stoppedLoading`),className:`is-spinning`,size:13}):(0,V.jsx)(`small`,{children:v.length})]}),(0,V.jsxs)(`div`,{className:`personal-goal-list is-stopped`,children:[n.phase===`error`?(0,V.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`alert`,children:[(0,V.jsx)(`span`,{children:p(`sidebar.stoppedLoadFailed`)}),s?(0,V.jsx)(`button`,{onClick:s,type:`button`,children:p(`sidebar.retryStopped`)}):null]}):null,v.map(e=>b(e,!0))]})]}):null]}),(0,V.jsxs)(`div`,{className:`personal-sidebar-footer`,children:[(0,V.jsx)(nb,{}),o?(0,V.jsxs)(`button`,{"aria-label":p(`settings.open`),className:`personal-sidebar-utility`,onClick:o,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-sidebar-utility-icon`,children:(0,V.jsx)(Um,{size:17})}),(0,V.jsx)(`span`,{className:`personal-sidebar-utility-copy`,children:(0,V.jsx)(`strong`,{children:p(`settings.open`)})}),(0,V.jsx)(nm,{"aria-hidden":`true`,size:15})]}):null]})]})}var xb=Y({ok:X(!0),total:K().int().nonnegative(),next_cursor:G().nullable(),items:J(Y({todo_id:G(),text:G(),claimed_by:G().nullable(),evidence:G().nullable(),priority:G().nullable(),task_class:G().nullable()})).max(40)});function Sb({goal:e,agentId:t,seed:n,enabled:r,listView:i=!1,onSelect:a}){let{t:o}=qi(),s=(0,B.useId)(),[c,l]=(0,B.useState)(!1),u=!i||c,d=i?96:148,[f,p]=(0,B.useState)(n),[m,h]=(0,B.useState)(t===`all`?e.doneTodoCount??n.length:n.length),[g,_]=(0,B.useState)(void 0),[v,y]=(0,B.useState)(!1),[b,x]=(0,B.useState)(!1),[S,C]=(0,B.useState)(!1),[w,T]=(0,B.useState)({top:0,height:600}),[E,D]=(0,B.useState)(null),O=(0,B.useRef)(null),ee=(0,B.useRef)(null),[te,ne]=(0,B.useState)(0);(0,B.useEffect)(()=>{let e=O.current;if(!e)return;let t=new ResizeObserver(()=>T({top:e.scrollTop,height:e.clientHeight}));return t.observe(e),()=>{t.disconnect(),ee.current?.abort()}},[]);let k=g===void 0||w.top+w.height>=f.length*d-d*2;(0,B.useEffect)(()=>{if(!r||!u||!k||g===null||b||ee.current)return;let n=new AbortController;ee.current=n,y(!0);let i=new URLSearchParams({goal_id:e.goalId});t!==`all`&&i.set(`agent_id`,t),g&&i.set(`cursor`,g),fetch(`/api/chat/completed-todos?${i}`,{signal:n.signal}).then(async e=>{if(e.status===409&&C(!0),!e.ok)throw Error(`history unavailable`);let t=xb.parse(await e.json());if(n.signal.aborted)return;let r=t.items.map(e=>({todoId:e.todo_id,text:e.text,claimedBy:e.claimed_by,evidence:e.evidence,priority:e.priority,taskClass:e.task_class,done:!0,status:`done`}));p(e=>g===void 0?r:[...e,...r.filter(t=>!e.some(e=>e.todoId===t.todoId))]),h(t.total),_(t.next_cursor)}).catch(()=>{n.signal.aborted||x(!0)}).finally(()=>{n.signal.aborted||(ee.current=null,y(!1))})},[r,u,k,g,b,te,e.goalId,t,v]),(0,B.useEffect)(()=>{O.current&&(O.current.scrollTop=0),T({top:0,height:O.current?.clientHeight??600}),D(null)},[i]);let A=Math.max(0,Math.floor(w.top/d)-3),j=Math.min(f.length,Math.ceil((w.top+w.height)/d)+3),M=Array.from({length:Math.max(0,j-A)},(e,t)=>A+t);return E!==null&&El(e=>!e),children:[(0,V.jsx)(`span`,{"aria-hidden":`true`,children:c?`▾`:`▸`}),` `,o(`tasks.completed`)]}):(0,V.jsxs)(`strong`,{children:[(0,V.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-done`}),o(`tasks.completed`)]}),(0,V.jsx)(`span`,{children:m})]}),(0,V.jsxs)(`div`,{id:s,hidden:!u,"aria-label":o(`tasks.completed`),className:`personal-task-lane-scroll`,ref:O,role:`region`,tabIndex:0,onScroll:e=>T({top:e.currentTarget.scrollTop,height:e.currentTarget.clientHeight}),children:[(0,V.jsx)(`div`,{className:`personal-completed-window`,style:{height:f.length*d},children:M.map(t=>{let n=f[t];return(0,V.jsx)(`div`,{className:`personal-task-card personal-completed-row`,style:{top:t*d,height:d},children:(0,V.jsxs)(`button`,{type:`button`,onFocus:()=>D(t),onBlur:()=>D(null),onClick:()=>a({kind:`todo`,item:{...n,goalId:e.goalId,goalTitle:e.title,ownerLabel:n.claimedBy??e.agentLabel??e.agentId}}),children:[(0,V.jsx)(`span`,{className:`is-done`,children:`✓`}),(0,V.jsx)(`strong`,{children:n.text}),(0,V.jsx)(`small`,{children:n.claimedBy??e.agentLabel??e.agentId})]})},n.todoId)})}),(0,V.jsx)(`div`,{className:`personal-completed-footer`,role:`status`,children:v?o(`tasks.historyLoading`):b?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`span`,{children:o(S?`tasks.historyExpired`:`tasks.historyError`)}),(0,V.jsx)(`button`,{type:`button`,onClick:()=>{S&&(_(void 0),O.current&&(O.current.scrollTop=0)),C(!1),x(!1),ne(e=>e+1)},children:o(`tasks.historyRetry`)})]}):r?g===null?o(`tasks.historyEnd`):(0,V.jsx)(`button`,{type:`button`,onClick:()=>{O.current&&(O.current.scrollTop=f.length*d)},children:o(`tasks.historyMore`)}):o(`tasks.historyLocalOnly`)})]})]})}function Cb({children:e,count:t,label:n,tone:r,listView:i=!1}){let a=(0,B.useId)(),o=(0,B.useRef)(null),s=(0,B.useRef)([]),c=(0,B.useRef)(null),[l,u]=(0,B.useState)({after:!1,before:!1}),d=(0,B.useCallback)(()=>{let e=o.current;if(!e)return;let t={after:Math.max(0,e.scrollHeight-e.clientHeight)-e.scrollTop>1,before:e.scrollTop>1};u(e=>e.after===t.after&&e.before===t.before?e:t)},[]);return(0,B.useEffect)(()=>{let e=o.current;if(!e)return;let t=new ResizeObserver(d);return c.current=t,t.observe(e),e.addEventListener(`scroll`,d,{passive:!0}),d(),()=>{t.disconnect(),c.current=null,s.current=[],e.removeEventListener(`scroll`,d)}},[i,d]),(0,B.useEffect)(()=>{let e=o.current,t=c.current;if(!e||!t)return;for(let e of s.current)t.unobserve(e);let n=Array.from(e.children).filter(e=>e instanceof HTMLElement);for(let e of n)t.observe(e);s.current=n,d()},[e,t,i,d]),i?!t&&r!==`done`?null:(0,V.jsxs)(`details`,{className:`personal-task-group tone-${r}`,open:!0,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(tm,{size:16}),(0,V.jsx)(`strong`,{children:n}),(0,V.jsx)(`span`,{children:t})]}),(0,V.jsx)(`div`,{className:`personal-task-list-rows`,children:e})]}):(0,V.jsxs)(`section`,{className:`personal-object-list personal-task-lane`,children:[(0,V.jsxs)(`header`,{id:a,children:[(0,V.jsxs)(`strong`,{children:[(0,V.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-${r}`}),n]}),(0,V.jsx)(`span`,{children:t})]}),(0,V.jsx)(`div`,{"aria-labelledby":a,className:`personal-task-lane-scroll${l.before?` has-overflow-before`:``}${l.after?` has-overflow-after`:``}`,ref:o,role:`region`,tabIndex:t>0?0:-1,children:e})]})}function wb({historyEnabled:e=!1,goal:t,items:n,onDraftTaskFromMessage:r,onOpenChat:i,onQuickComplete:a,quickCompletingTodoIds:o,onSelect:s,selectedTodoId:c=null,userTodos:l}){let{t:u}=qi(),[d,f]=(0,B.useState)(!1),[p,m]=(0,B.useState)({goalId:``,laneId:`all`}),h=(0,B.useRef)(null);(0,B.useEffect)(()=>{if(!c)return;let e=window.requestAnimationFrame(()=>h.current?.scrollIntoView({block:`nearest`,inline:`nearest`}));return()=>window.cancelAnimationFrame(e)},[c]);let g=l.filter(e=>e.goalId===t.goalId).map(e=>({...e,goalTitle:t.title})),_=e=>e.priority===`P0`?0:e.priority===`P1`?1:e.priority===`P2`?2:3,v=(0,B.useMemo)(()=>{let e=new Map((t.agentLanes??[]).map(e=>[e.agentId,e]));for(let n of t.agentTodos)n.claimedBy&&!e.has(n.claimedBy)&&e.set(n.claimedBy,{agentId:n.claimedBy,label:n.claimedBy});return[...e.values()]},[t.agentLanes,t.agentTodos]),y=p.goalId===t.goalId&&v.some(e=>e.agentId===p.laneId)?p.laneId:`all`,b=e=>y===`all`||e===y,x=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&!e.done).filter(e=>b(e.claimedBy)).sort((e,t)=>_(e)-_(t)),S=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&e.done).filter(e=>b(e.claimedBy)),C=n.filter(e=>e.kind===`schedule`&&b(e.schedule.agentId)),w=n.filter(e=>e.kind===`run`&&!!e.run.todoId&&b(e.run.agentId)),T=!g.length&&!x.length&&!S.length&&!C.length,E=n.filter(e=>e.kind===`message`&&(e.message.role===`user`||e.message.role===`assistant`)),D=E.reduce((e,t,n)=>t.message.role===`user`?n:e,-1),O=D>=0?E[D]?.message:null,ee=D>=0?E.slice(D+1).reverse().find(e=>e.message.role===`assistant`)?.message:null,te=D>=0&&E.slice(D+1).some(e=>e.message.role===`assistant`&&e.message.pending);return(0,V.jsxs)(`section`,{"aria-label":u(`header.tasks`),className:`personal-task-board${d?` is-list-view`:``}`,children:[(0,V.jsxs)(`header`,{className:`personal-task-view-toolbar`,children:[(0,V.jsx)(`div`,{children:(0,V.jsx)(`strong`,{children:u(`header.tasks`)})}),(0,V.jsxs)(`div`,{className:`personal-task-view-switch`,role:`group`,"aria-label":u(`tasks.viewLabel`),children:[(0,V.jsx)(`button`,{type:`button`,"aria-pressed":d,onClick:()=>f(!0),children:u(`tasks.listView`)}),(0,V.jsx)(`button`,{type:`button`,"aria-pressed":!d,onClick:()=>f(!1),children:u(`tasks.boardView`)})]})]}),v.length>1?(0,V.jsxs)(`section`,{"aria-label":u(`tasks.agentLaneFilter`),className:`personal-task-lane-filter`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(Zp,{size:15}),(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:u(`tasks.agentLane`)})})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{className:`sr-only`,children:u(`tasks.agentLaneFilter`)}),(0,V.jsxs)(`select`,{"aria-label":u(`tasks.agentLaneFilter`),onChange:e=>m({goalId:t.goalId,laneId:e.target.value}),value:y,children:[(0,V.jsx)(`option`,{value:`all`,children:u(`tasks.allAgentLanes`,{count:v.length})}),v.map(e=>(0,V.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))]}),(0,V.jsx)(tm,{"aria-hidden":!0,size:14})]})]}):null,O?(0,V.jsxs)(`section`,{"aria-label":u(`tasks.chatRecent`),className:`personal-task-chat-receipt`,children:[(0,V.jsx)(`span`,{className:`personal-task-chat-icon`,children:(0,V.jsx)(Dm,{size:18})}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:u(te?`tasks.chatPending`:ee?`tasks.chatAgentReplied`:`tasks.chatRecent`)}),(0,V.jsx)(`small`,{children:t.agentLabel??t.agentId})]}),(0,V.jsxs)(`p`,{className:`is-user`,children:[(0,V.jsx)(`b`,{children:u(`common.you`)}),O.text]}),ee&&!ee.pending?(0,V.jsxs)(`p`,{className:`is-assistant`,children:[(0,V.jsx)(`b`,{children:u(`common.agent`)}),ee.text]}):null,(0,V.jsx)(`small`,{children:u(te?`tasks.chatPendingDescription`:`tasks.chatUnchangedDescription`)})]}),(0,V.jsxs)(`footer`,{children:[(0,V.jsxs)(`button`,{onClick:i,type:`button`,children:[(0,V.jsx)(Dm,{size:14}),u(`tasks.chatViewReply`)]}),ee&&!te&&r?(0,V.jsxs)(`button`,{onClick:()=>r(ee.text),type:`button`,children:[(0,V.jsx)(Sm,{size:14}),u(`tasks.convertToTask`)]}):null]})]}):null,(0,V.jsxs)(`div`,{className:d?`personal-task-grouped-list`:`personal-task-kanban`,children:[(0,V.jsxs)(Cb,{listView:d,count:g.length,label:u(`timeline.waitingConfirmation`),tone:`attention`,children:[g.map(e=>{let t=Xi(e.updatedAt,u);return(0,V.jsxs)(`button`,{onClick:()=>s({item:e,kind:`attention`}),type:`button`,children:[(0,V.jsx)(`span`,{"aria-hidden":`true`,className:`is-attention`,children:`!`}),(0,V.jsx)(`strong`,{children:e.text}),(0,V.jsxs)(`small`,{children:[(0,V.jsx)(`span`,{className:`personal-row-status ${e.blocking?`is-blocking`:`is-pending`}`,children:e.blocking?u(`tasks.blocked`):u(`tasks.pending`)}),t?(0,V.jsx)(`span`,{className:`personal-task-age`,children:u(`tasks.waitingAge`,{age:t})}):null]})]},e.todoId)}),g.length?null:(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyConfirm`)})]}),(0,V.jsxs)(Cb,{listView:d,count:x.length,label:u(`tasks.pendingAndRunning`),tone:`progress`,children:[x.map(e=>{let n={...e,goalId:t.goalId,goalTitle:t.title,ownerLabel:e.claimedBy??t.agentLabel??t.agentId},r=w.find(t=>t.run.todoId===e.todoId)?.run;return(0,V.jsxs)(`div`,{className:`personal-task-card${r?` has-session`:``}${c===e.todoId?` is-selected`:``}`,ref:c===e.todoId?e=>{h.current=e}:void 0,children:[(0,V.jsxs)(`button`,{"aria-pressed":c===e.todoId,onClick:()=>s({item:n,kind:`todo`}),type:`button`,children:[(0,V.jsx)(`span`,{children:`○`}),(0,V.jsx)(`strong`,{children:e.text}),(0,V.jsxs)(`small`,{children:[e.priority?(0,V.jsx)(`span`,{className:`personal-priority-badge is-${e.priority.toLowerCase()}`,children:e.priority}):null,e.status===`blocked`?(0,V.jsx)(`span`,{className:`personal-priority-badge is-blocked`,children:u(`tasks.blocked`)}):null,r?(0,V.jsx)(`span`,{className:`personal-task-session-status`,children:r.status===`running`||r.status===`queued`?u(`runs.running`):r.status===`failed`?u(`tasks.sessionError`):u(`common.waiting`)}):null,e.status===`deferred`?(0,V.jsx)(`span`,{className:`personal-task-session-status`,children:u(`drawer.taskStatusDeferred`)}):r?null:(0,V.jsx)(`span`,{className:`personal-task-session-status`,children:u(`tasks.waiting`)}),e.claimedBy??t.agentLabel??t.agentId]})]}),(0,V.jsxs)(`div`,{className:`personal-task-card-actions`,children:[r?(0,V.jsxs)(`button`,{className:`personal-task-session-link`,"aria-label":u(`tasks.openExecution`,{name:e.text}),onClick:()=>s({item:r,kind:`run`}),title:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`),type:`button`,children:[(0,V.jsx)(fm,{size:14}),(0,V.jsx)(`span`,{children:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`)})]}):null,a?(0,V.jsx)(`button`,{"aria-busy":o?.has(e.todoId)||void 0,"aria-label":u(`tasks.markComplete`,{name:e.text}),disabled:o?.has(e.todoId),onClick:()=>void a(n),title:u(`tasks.completed`),type:`button`,children:o?.has(e.todoId)?(0,V.jsx)(Cm,{className:`personal-spin`,size:14}):(0,V.jsx)(em,{size:14})}):null,(0,V.jsx)(`button`,{"aria-label":u(`tasks.moreActions`,{name:e.text}),onClick:()=>s({item:n,kind:`todo`}),title:u(`common.actions`),type:`button`,children:(0,V.jsx)(dm,{size:14})})]})]},e.todoId)}),x.length?null:(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyRunning`)})]}),(0,V.jsxs)(Cb,{listView:d,count:C.length,label:u(`tasks.scheduled`),tone:`schedule`,children:[C.map(e=>(0,V.jsxs)(`button`,{onClick:()=>s({item:e.schedule,kind:`schedule`}),type:`button`,children:[(0,V.jsx)(`span`,{children:`◷`}),(0,V.jsx)(`strong`,{children:e.schedule.label}),(0,V.jsx)(`small`,{children:e.schedule.status===`paused`?u(`schedule.paused`):u(`schedule.active`)})]},e.id)),C.length?null:(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptySchedules`)})]}),(0,V.jsx)(Sb,{goal:t,agentId:y,seed:S,enabled:e,listView:d,onSelect:s},`${t.goalId}:${y}:${e}`)]}),T?(0,V.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyGoal`)}):null]})}function Tb(e,t){return{live_steering:{label:t(`lark.ingressSteering`),detail:t(`lark.ingressSteeringDescription`)},session_queue:{label:t(`lark.ingressQueue`),detail:t(`lark.ingressQueueDescription`)},async_inbox:{label:t(`lark.ingressAsync`),detail:t(`lark.ingressAsyncDescription`)},direct_session:{label:t(`lark.ingressLegacy`),detail:t(`lark.ingressLegacyDescription`)}}[e]}function Eb(e,t){return e.listener_status===`starting`?{label:t(`lark.health.starting`),detail:t(`lark.health.startingDetail`),state:`not_ready`}:e.listener_status===`retrying`&&e.listener_error_code===`lark_event_source_disconnected`?{label:t(`lark.health.sourceDisconnected`),detail:t(`lark.health.sourceDisconnectedDetail`),state:`not_ready`}:e.listener_status===`retrying`?{label:t(`lark.health.retrying`),detail:t(`lark.health.retryingDetail`),state:`not_ready`}:e.listener_status===`stopped`||e.listener_status===null?{label:t(`lark.health.notStarted`),detail:t(`lark.health.notStartedDetail`),state:`not_ready`}:e.last_event_status===`message_context_permission_required`?{label:t(`lark.health.messageContextPermission`),detail:t(`lark.health.messageContextPermissionDetail`),state:`not_ready`}:e.last_event_status===`processing_failed`?{label:t(`lark.health.processingFailed`),detail:t(`lark.health.processingFailedDetail`),state:`not_ready`}:e.health_error_code===`invalid_routing_state`?{label:t(`lark.health.invalidRouting`),detail:t(`lark.health.invalidRoutingDetail`),state:`not_ready`}:e.last_event_status===`queued_for_agent`?{label:t(`lark.health.queued`),detail:t(`lark.health.queuedDetail`,{agent:e.agent_id??t(`lark.targetAgent`)}),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`not_addressed`?{label:t(`lark.health.notAddressed`),detail:t(`lark.health.notAddressedDetail`),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`self_message`?{label:t(`lark.health.listening`),detail:t(`lark.health.ignoredSelf`),state:`ready`}:e.health_error_code===`lark_event_route_mismatch`||[`chat_mismatch`,`topic_mismatch`,`route_ambiguous`].includes(e.last_event_reason??``)?{label:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguous`):t(`lark.health.routeMismatch`),detail:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguousDetail`):t(`lark.health.routeMismatchDetail`),state:`not_ready`}:[`invalid_event`,`binding_unavailable`].includes(e.last_event_reason??``)?{label:t(`lark.health.routeUnavailable`),detail:t(`lark.health.routeUnavailableDetail`),state:`not_ready`}:e.last_event_status===`replied_and_acknowledged`?{label:t(`lark.health.listening`),detail:t(`lark.health.eventProcessed`,{events:e.event_count,replies:e.replied_count}),state:`ready`}:e.health_error_code===`lark_event_delivery_unverified`||e.event_count===0?{label:t(`lark.health.eventUnverified`),detail:t(`lark.health.eventUnverifiedDetail`),state:`unverified`}:{label:e.reply_ready?t(`lark.health.listening`):t(`lark.health.unavailable`),detail:t(`lark.health.lastStatus`,{status:e.last_event_status??t(`lark.health.waiting`)}),state:e.reply_ready?`ready`:`not_ready`}}function Db(e){return e.history_permission_guidance?.api_document_url??null}function Ob(e,t,n){if(e instanceof Th){let t=String(e.payload.error_code??``);return{lark_cli_not_installed:n(`lark.error.cliMissing`),lark_cli_not_executable:n(`lark.error.cliExecutable`),lark_cli_start_failed:n(`lark.error.cliStart`),lark_message_permissions_required:n(`lark.error.messagePermissions`),lark_app_required:n(`lark.error.appRequired`),invalid_lark_app:n(`lark.error.invalidApp`),lark_group_lookup_failed:n(`lark.error.groupLookup`),provider_api_failed:n(`lark.error.provider`)}[t]??e.message}return e instanceof Error?e.message:t}function kb({embedded:e=!1,focusGoalConnection:t=!1,goals:n,initialGoalId:r,onChanged:i,onClose:a}){let{t:o}=qi(),[s,c]=(0,B.useState)(`connections`),[l,u]=(0,B.useState)([]),[d,f]=(0,B.useState)([]),[p,m]=(0,B.useState)(!0),[h,g]=(0,B.useState)(null),[_,v]=(0,B.useState)(``),[y,b]=(0,B.useState)(t),[x,S]=(0,B.useState)(``),[C,w]=(0,B.useState)(r??n[0]?.goalId??``),[T,E]=(0,B.useState)(``),[D,O]=(0,B.useState)([]),[ee,te]=(0,B.useState)(``),[ne,k]=(0,B.useState)(!1),[A,j]=(0,B.useState)(null),[M,N]=(0,B.useState)(`addressed_only`),[P,F]=(0,B.useState)(t&&r?`goal`:`manager`),[re,ie]=(0,B.useState)(`async_inbox`),[I,ae]=(0,B.useState)(`topic_reply`),[L,oe]=(0,B.useState)(``),[se,ce]=(0,B.useState)(!1),[le,ue]=(0,B.useState)({}),[de,R]=(0,B.useState)(!1),[fe,pe]=(0,B.useState)(null),[me,he]=(0,B.useState)(null),[ge,_e]=(0,B.useState)(null),[ve,ye]=(0,B.useState)(null),[be,xe]=(0,B.useState)(!1),[Se,Ce]=(0,B.useState)(`loopx-workspace-bot`),[we,Te]=(0,B.useState)(`feishu`),[z,Ee]=(0,B.useState)(null),[De,Oe]=(0,B.useState)(!1),[ke,Ae]=(0,B.useState)(null),je=(0,B.useRef)(null),Me=(0,B.useRef)(null),Ne=(0,B.useRef)(!1);async function Pe(){m(!0),g(null);try{let[e,t]=await Promise.all([Lg(),Kg()]);u(e),f(t),S(t=>t||e.find(e=>e.reply_ready)?.app_ref||e.find(e=>e.ready)?.app_ref||e[0]?.app_ref||``)}catch(e){g(Ob(e,o(`lark.error.configuration`),o))}finally{m(!1)}}(0,B.useEffect)(()=>{Pe()},[]),(0,B.useEffect)(()=>{if(!t||p||Ne.current||!r)return;Ne.current=!0;let e=d.find(e=>e.goal_id===r);e?qe(e):Ke(n.find(e=>e.goalId===r))},[d,t,n,r,p]),(0,B.useEffect)(()=>{if(!y||!x||ge){O([]),te(``),k(!1),j(null);return}let e=!1;k(!0),j(null);let t=window.setTimeout(()=>{Wg(x,T).then(t=>{e||(O(t),te(e=>t.some(t=>t.chat_id===e)?e:t[0]?.chat_id??``))}).catch(t=>{e||(O([]),te(``),j(Ob(t,o(`lark.error.groupLoad`),o)))}).finally(()=>{e||k(!1)})},180);return()=>{e=!0,window.clearTimeout(t)}},[x,T,y,ge]),(0,B.useEffect)(()=>{if(!be||!z||[`ready`,`failed`,`cancelled`].includes(z.status))return;let e=!1,t=window.setTimeout(()=>{Bg(z.setup_id).then(async t=>{e||(Ee(t),t.verification_url&&Me.current!==t.verification_url&&(Me.current=t.verification_url,je.current&&!je.current.closed&&(je.current.location.href=t.verification_url)),t.status===`ready`&&(await Pe(),S(t.app_ref),ue({}),xe(!1)),t.status===`failed`&&Ae(t.error??o(`lark.error.appCreate`)))}).catch(t=>{e||Ae(Ob(t,o(`lark.error.setupPoll`),o))})},650);return()=>{e=!0,window.clearTimeout(t)}},[be,z]);let H=n.find(e=>e.goalId===C),Fe=H?.agentId?[{agentId:H.agentId,label:H.agentLabel??H.agentId}]:[],Ie=H?.agentLanes?.length?H.agentLanes:Fe,Le=Ie.some(e=>e.agentId===L),Re=[];se?Re=Ie.map(e=>({agentId:e.agentId,appRef:le[e.agentId]??x})):Le&&(Re=[{agentId:L,appRef:x}]);let ze=Re.map(e=>e.agentId),Be=!!ge||Re.length>0&&Re.every(e=>l.some(t=>t.app_ref===e.appRef&&t.reply_ready)),Ve=o(`lark.connect`);me?Ve=o(`lark.saveConnection`):se&&(Ve=o(`lark.connectAllAgentsAction`,{count:ze.length}));let He=l.find(e=>e.app_ref===x),Ue=D.find(e=>e.chat_id===ee),We=(0,B.useMemo)(()=>{let e=_.trim().toLocaleLowerCase();return e?d.filter(t=>[t.app_label,t.chat_name,t.goal_title,t.topic_name].some(t=>t.toLocaleLowerCase().includes(e))):d},[d,_]),Ge=(0,B.useMemo)(()=>d.filter(e=>Eb(e,o).state===`unverified`).length,[d,o]);function Ke(e){let i=e??n.find(e=>e.goalId===r)??n[0];he(null),_e(null),F(e||t?`goal`:`manager`),S(l.some(e=>e.app_ref===x)?x:l.find(e=>e.reply_ready)?.app_ref??l[0]?.app_ref??``),te(``),w(i?.goalId??``),oe(i?.agentId??``),ce(!1),ue({}),N(`addressed_only`),ie(`async_inbox`),ae(`topic_reply`),E(``),pe(null),b(!0)}function qe(e){he(e.goal_id),_e(e),F(e.conversation_kind??`goal`),S(e.app_ref),w(e.goal_id);let t=n.find(t=>t.goalId===e.goal_id),r=t?.agentLanes?.length?t.agentLanes:t?.agentId?[{agentId:t.agentId}]:[];oe(e.agent_id??(r.length===1?r[0].agentId:``)),ce(!1),ue({}),N(e.capture_scope),ie(e.ingress_mode===`direct_session`?`async_inbox`:e.ingress_mode),ae(e.reply_mode),E(e.chat_name),pe(null),b(!0)}function Je(){Ee(null),Ae(null),Me.current=null,xe(!0)}async function Ye(){if(!(De||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Se))){Oe(!0),Ae(null),Me.current=null,je.current=window.open(window.location.href,`_blank`);try{let e=await zg({appRef:Se,brand:we});Ee(e)}catch(e){je.current?.close(),Ae(Ob(e,o(`lark.error.setupStart`),o))}finally{Oe(!1)}}}async function Xe(){let e=z;if(xe(!1),je.current?.close(),e&&![`ready`,`failed`,`cancelled`].includes(e.status))try{await Vg(e.setup_id)}catch{}}async function Ze(){if(!(!x||!C||!ge&&!Ue||P===`goal`&&ze.length===0||de)){R(!0),pe(null);try{let e={...P===`manager`?{...ge?{connectionId:ge.connection_id}:{appRef:x,chatId:Ue.chat_id,chatName:Ue.chat_name}}:ge?{connectionId:ge.connection_id,agentId:L}:{agentBindings:Re,chatId:Ue.chat_id,chatName:Ue.chat_name},conversationKind:P,captureScope:P===`manager`?`addressed_only`:M,goalId:C,incomingMode:M===`configured_chat_all`?`all`:`mentions`,ingressMode:P===`manager`?`session_queue`:re,replyMode:I},t=await qg({...e,execute:!1});if(!t.ok)throw new Th(t.public_summary??t.blocker??o(`lark.error.bindPreview`),{error_code:t.blocker??`provider_api_failed`});let n=await qg({...e,execute:!0});if(!n.ok)throw new Th(n.public_summary??n.blocker??o(`lark.error.bind`),{error_code:n.blocker??`provider_api_failed`});b(!1),await Pe(),i?.()}catch(e){pe(Ob(e,o(`lark.error.bind`),o))}finally{R(!1)}}}async function Qe(e,t){if(ve!==t){ye(t);return}try{await Jg(e,t),ye(null),await Pe(),i?.()}catch(e){g(Ob(e,o(`lark.error.disconnect`),o))}}return(0,V.jsxs)(`section`,{className:`personal-lark-settings${e?` is-embedded`:``}`,"aria-label":o(`lark.configuration`),children:[e?null:(0,V.jsxs)(`header`,{className:`personal-lark-header`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:o(`settings.goalConnections`)}),(0,V.jsx)(`h1`,{children:`Lark`})]}),(0,V.jsx)(`button`,{"aria-label":o(`lark.closeSettings`),className:`personal-icon-button`,onClick:a,type:`button`,children:(0,V.jsx)($m,{size:18})})]}),(0,V.jsxs)(`nav`,{className:`personal-lark-tabs`,"aria-label":o(`lark.management`),children:[(0,V.jsxs)(`button`,{"aria-current":s===`apps`?`page`:void 0,onClick:()=>c(`apps`),type:`button`,children:[o(`lark.apps`),` `,(0,V.jsx)(`span`,{children:p?`…`:l.length})]}),(0,V.jsxs)(`button`,{"aria-current":s===`connections`?`page`:void 0,onClick:()=>c(`connections`),type:`button`,children:[o(`lark.connections`),` `,(0,V.jsx)(`span`,{children:p?`…`:d.length})]})]}),h?(0,V.jsx)(`p`,{className:`personal-notification-error`,children:h}):null,p?(0,V.jsxs)(`div`,{className:`personal-lark-loading`,children:[(0,V.jsx)(Cm,{className:`is-spinning`,size:18}),o(`lark.loading`)]}):null,!p&&s===`apps`?(0,V.jsxs)(`div`,{className:`personal-lark-apps`,children:[(0,V.jsxs)(`div`,{className:`personal-lark-app-toolbar`,children:[(0,V.jsx)(`span`,{children:o(`lark.reusableApps`,{count:l.length})}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,onClick:Je,type:`button`,children:[(0,V.jsx)(Pm,{size:16}),o(`lark.newApp`)]})]}),(0,V.jsxs)(`div`,{className:`personal-lark-app-grid`,children:[l.map(e=>(0,V.jsxs)(`article`,{className:`personal-lark-app-card`,children:[(0,V.jsx)(`span`,{className:`personal-lark-app-avatar`,children:(0,V.jsx)(Zp,{size:19})}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsxs)(`small`,{children:[e.brand,` · lark-cli profile`]})]}),(0,V.jsx)(`em`,{className:e.reply_ready?`is-ready`:`is-off`,children:e.reply_ready?o(`lark.autoReplyReady`):e.ready?o(`lark.needsMessagePermissions`):o(`lark.needsSetup`)}),(0,V.jsxs)(`p`,{children:[o(`lark.goalConnections`,{count:d.filter(t=>t.app_ref===e.app_ref).length}),e.ready&&!e.reply_ready?` · ${o(`lark.autoReplyUnavailable`)}`:``]})]},e.app_ref)),l.length===0?(0,V.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noProfiles`)}):null]})]}):null,!p&&s===`connections`?(0,V.jsxs)(`div`,{className:`personal-lark-connections`,children:[Ge>0?(0,V.jsxs)(`p`,{className:`personal-lark-route-readiness`,role:`status`,children:[(0,V.jsx)(Dm,{size:15}),o(`lark.routesUnverified`,{count:Ge})]}):null,(0,V.jsxs)(`div`,{className:`personal-lark-toolbar`,children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(zm,{size:16}),(0,V.jsx)(`input`,{"aria-label":o(`lark.searchConnections`),onChange:e=>v(e.target.value),placeholder:o(`lark.searchPlaceholder`),type:`search`,value:_})]}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:l.length===0||n.length===0,onClick:()=>Ke(),type:`button`,children:[(0,V.jsx)(Pm,{size:16}),o(`lark.connectApp`)]})]}),(0,V.jsxs)(`div`,{className:`personal-lark-table`,role:`table`,"aria-label":o(`lark.goalTopicConnections`),children:[(0,V.jsxs)(`div`,{className:`personal-lark-table-head`,role:`row`,children:[(0,V.jsx)(`span`,{children:o(`lark.connection`)}),(0,V.jsx)(`span`,{children:o(`common.goal`)}),(0,V.jsx)(`span`,{children:o(`lark.capture`)}),(0,V.jsx)(`span`,{children:o(`lark.processing`)}),(0,V.jsx)(`span`,{children:o(`common.actions`)})]}),We.map(e=>{let t=Eb(e,o);return(0,V.jsxs)(`div`,{className:`personal-lark-table-row`,role:`row`,children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.chat_name}),(0,V.jsxs)(`small`,{children:[e.app_label,` · `,t.label]}),(0,V.jsx)(`small`,{children:t.detail}),t.state===`unverified`?(0,V.jsxs)(`a`,{href:`https://open.feishu.cn/document/server-docs/im-v1/message/events/receive?lang=zh-CN`,rel:`noreferrer`,target:`_blank`,children:[(0,V.jsx)(fm,{size:12}),o(`lark.openEventSettings`)]}):null,Db(e)?(0,V.jsxs)(`a`,{href:Db(e)??void 0,rel:`noreferrer`,target:`_blank`,children:[(0,V.jsx)(fm,{size:12}),o(`lark.historyPermission`)]}):null]}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.goal_title}),(0,V.jsxs)(`small`,{children:[`# `,e.topic_name]})]}),(0,V.jsx)(`span`,{children:e.capture_scope===`addressed_only`?o(`lark.mentionsOnly`):o(`lark.allTopicMessages`)}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.conversation_kind===`manager`?o(`lark.managerConversation`):Tb(e.ingress_mode,o).label}),(0,V.jsx)(`small`,{children:e.conversation_kind===`manager`?o(`lark.managerConversationDescription`):e.agent_id??Tb(e.ingress_mode,o).detail})]}),(0,V.jsxs)(`span`,{className:`personal-lark-row-actions`,children:[(0,V.jsx)(`button`,{"aria-label":o(`lark.settingsConfigure`,{goal:e.goal_title}),onClick:()=>qe(e),type:`button`,children:(0,V.jsx)(Um,{size:15})}),(0,V.jsxs)(`button`,{"aria-label":o(`lark.settingsDisconnect`,{goal:e.goal_title}),className:ve===e.connection_id?`is-confirm`:``,onClick:()=>void Qe(e.goal_id,e.connection_id),type:`button`,children:[(0,V.jsx)(Qm,{size:15}),ve===e.connection_id?o(`common.confirm`):null]})]})]},e.connection_id)}),We.length===0?(0,V.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noConnections`)}):null]})]}):null,y?(0,V.jsx)(`div`,{className:`personal-lark-modal-backdrop`,role:`presentation`,children:(0,V.jsxs)(`section`,{"aria-labelledby":`connect-lark-title`,"aria-modal":`true`,className:`personal-lark-modal`,role:`dialog`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:`Goal Topic connection`}),(0,V.jsx)(`h2`,{id:`connect-lark-title`,children:o(me?`lark.editConnection`:`lark.connectApp`)})]}),(0,V.jsx)(`button`,{"aria-label":o(`lark.closeConnection`),onClick:()=>b(!1),type:`button`,children:(0,V.jsx)($m,{size:18})})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.conversationKind`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.conversationKind`),disabled:!!ge,value:P,onChange:e=>F(e.target.value),children:[(0,V.jsx)(`option`,{value:`manager`,children:o(`lark.managerConversation`)}),(0,V.jsx)(`option`,{value:`goal`,children:o(`lark.workerConversation`)})]})]}),P===`manager`?(0,V.jsx)(`p`,{children:o(`lark.managerConversationDescription`)}):null,ge?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,V.jsx)(`div`,{children:ge.app_label})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,V.jsx)(`div`,{children:ge.chat_name})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,V.jsx)(`div`,{children:ge.goal_title})]}),(0,V.jsx)(`small`,{children:o(`lark.editPreservesIdentity`)})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,V.jsx)(`select`,{"aria-label":o(`lark.appProfile`),disabled:p,onChange:e=>{e.target.value===`__register__`?Je():(S(e.target.value),ue({}))},value:x,children:p?(0,V.jsx)(`option`,{value:``,children:o(`lark.appLoading`)}):(0,V.jsxs)(V.Fragment,{children:[l.map(e=>(0,V.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref)),(0,V.jsx)(`option`,{value:`__register__`,children:o(`lark.registerAnother`)})]})}),(0,V.jsx)(`small`,{children:o(`lark.defaultAgentAppDescription`)})]}),He?.ready&&!He.reply_ready?(0,V.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.appPermissions`)}):null,(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,V.jsx)(`input`,{"aria-label":o(`lark.groupSearch`),onChange:e=>E(e.target.value),placeholder:o(`lark.groupSearch`),type:`search`,value:T}),ne?(0,V.jsxs)(`div`,{className:`personal-lark-group-state`,role:`status`,children:[(0,V.jsx)(Cm,{className:`is-spinning`,size:15}),o(`lark.groupLoading`)]}):null,!ne&&A?(0,V.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:A}):null,!ne&&!A&&D.length===0?(0,V.jsx)(`div`,{className:`personal-lark-group-state`,role:`status`,children:o(`lark.groupEmpty`)}):null,!ne&&!A&&D.length>0?(0,V.jsx)(`select`,{"aria-label":o(`lark.groupChat`),onChange:e=>te(e.target.value),value:ee,children:D.map(e=>(0,V.jsx)(`option`,{value:e.chat_id,children:e.chat_name},e.chat_id))}):null]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,V.jsx)(`select`,{"aria-label":o(`lark.bindGoal`),onChange:e=>{let t=e.target.value;w(t),oe(n.find(e=>e.goalId===t)?.agentId??``),ue({})},value:C,children:n.map(e=>(0,V.jsx)(`option`,{value:e.goalId,children:e.title},e.goalId))})]})]}),(0,V.jsxs)(`label`,{className:`personal-lark-check`,children:[(0,V.jsx)(`input`,{checked:!0,readOnly:!0,type:`checkbox`}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:o(`lark.createAutomatically`)}),(0,V.jsx)(`small`,{children:o(`lark.createAutomaticallyDescription`)})]})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.topicPreview`)}),(0,V.jsxs)(`div`,{className:`personal-lark-topic-preview`,children:[(0,V.jsx)(Dm,{size:15}),`# `,H?.title??H?.goalId??`Goal`]})]}),P===`goal`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.captureScope`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.captureScope`),disabled:ge?.ingress_mode===`direct_session`,onChange:e=>N(e.target.value),value:M,children:[(0,V.jsx)(`option`,{value:`addressed_only`,children:o(`lark.captureAddressed`)}),(0,V.jsx)(`option`,{value:`configured_chat_all`,children:o(`lark.captureAll`)})]}),(0,V.jsx)(`small`,{children:o(`lark.captureScopeDescription`)})]}),(0,V.jsxs)(`fieldset`,{"aria-label":o(`lark.agentIngress`),className:`personal-lark-ingress`,children:[(0,V.jsx)(`legend`,{children:o(`lark.agentIngress`)}),(0,V.jsx)(`div`,{children:[`live_steering`,`session_queue`,`async_inbox`].map(e=>{let t=Tb(e,o);return(0,V.jsxs)(`label`,{className:re===e?`is-active`:``,children:[(0,V.jsx)(`input`,{"aria-label":t.label,checked:re===e,name:`lark-agent-ingress`,onChange:()=>ie(e),type:`radio`,value:e}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:t.label}),(0,V.jsx)(`small`,{children:t.detail})]})]},e)})})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.targetAgent`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.targetAgent`),disabled:!!ge?.agent_id,onChange:e=>oe(e.target.value),value:L,children:[Le?null:(0,V.jsx)(`option`,{disabled:!0,value:L,children:L?o(`lark.agentUnavailable`,{agent:L}):o(`lark.noAgentConfigured`)}),Ie.map(e=>(0,V.jsx)(`option`,{value:e.agentId,children:e.label===e.agentId?e.agentId:`${e.label} · ${e.agentId}`},e.agentId))]}),(0,V.jsx)(`small`,{children:o(`lark.targetAgentDescription`)})]}),!me&&Ie.length>1?(0,V.jsxs)(`label`,{"aria-label":o(`lark.connectAllAgents`),className:`personal-lark-check`,children:[(0,V.jsx)(`input`,{checked:se,onChange:e=>ce(e.target.checked),type:`checkbox`}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:o(`lark.connectAllAgents`)}),(0,V.jsx)(`small`,{children:o(`lark.connectAllAgentsDescription`,{count:Ie.length})})]})]}):null,!me&&se&&Ie.length>1?(0,V.jsxs)(`fieldset`,{"aria-label":o(`lark.agentApps`),className:`personal-lark-agent-apps`,children:[(0,V.jsx)(`legend`,{children:o(`lark.agentApps`)}),(0,V.jsx)(`small`,{children:o(`lark.agentAppsDescription`)}),(0,V.jsx)(`div`,{children:Ie.map(e=>(0,V.jsxs)(`label`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:e.label}),(0,V.jsx)(`small`,{children:e.agentId})]}),(0,V.jsx)(`select`,{"aria-label":o(`lark.agentAppSelection`,{agent:e.label}),onChange:t=>ue(n=>({...n,[e.agentId]:t.target.value})),value:le[e.agentId]??x,children:l.map(e=>(0,V.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref))})]},e.agentId))})]}):null,se&&Re.length>0&&!Be?(0,V.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.agentAppPermissions`)}):null,ze.length===0?(0,V.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:o(`lark.selectRegisteredAgent`)}):null]}):null,(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.replyMode`)}),(0,V.jsx)(`select`,{"aria-label":o(`lark.replyMode`),onChange:e=>ae(e.target.value),value:I,children:(0,V.jsx)(`option`,{value:`topic_reply`,children:o(`lark.topicReply`)})}),(0,V.jsx)(`small`,{children:o(`lark.replyModeDescription`)})]}),(0,V.jsxs)(`p`,{className:`personal-lark-cardinality`,children:[(0,V.jsx)(em,{size:15}),o(`lark.cardinality`)]}),fe?(0,V.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:fe}):null,(0,V.jsxs)(`footer`,{children:[(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>b(!1),type:`button`,children:o(`lark.cancel`)}),(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:p||!x||!ge&&(!He?.reply_ready||!ee)||P===`goal`&&(!Be||ze.length===0)||!C||de,onClick:()=>void Ze(),type:`button`,children:[de?(0,V.jsx)(Cm,{className:`is-spinning`,size:15}):null,Ve]})]})]})}):null,be?(0,V.jsx)(`div`,{className:`personal-lark-modal-backdrop is-setup`,role:`presentation`,children:(0,V.jsxs)(`section`,{"aria-labelledby":`new-lark-app-title`,"aria-modal":`true`,className:`personal-lark-modal personal-lark-setup-modal`,role:`dialog`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`small`,{children:o(`lark.reusableWorkspaceApp`)}),(0,V.jsx)(`h2`,{id:`new-lark-app-title`,children:o(`lark.newApp`)})]}),(0,V.jsx)(`button`,{"aria-label":o(`lark.closeCreate`),onClick:()=>void Xe(),type:`button`,children:(0,V.jsx)($m,{size:18})})]}),z?(0,V.jsxs)(`div`,{className:`personal-lark-setup-progress`,children:[(0,V.jsx)(`span`,{className:`personal-lark-setup-icon is-${z.status}`,children:z.status===`ready`?(0,V.jsx)(em,{size:22}):(0,V.jsx)(Cm,{className:z.status===`failed`?``:`is-spinning`,size:22})}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:z.status===`ready`?o(`lark.appCreated`):z.status===`failed`?o(`lark.appCreateFailed`):o(`lark.waitingFeishu`)}),(0,V.jsx)(`p`,{children:z.status===`waiting_for_feishu`?o(`lark.waitingFeishuDescription`):z.status===`starting`?o(`lark.waitingLink`):z.error})]}),z.verification_url?(0,V.jsxs)(`a`,{href:z.verification_url,rel:`noreferrer`,target:`_blank`,children:[(0,V.jsx)(fm,{size:15}),o(`lark.reopenFeishu`)]}):null]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{className:`personal-lark-setup-copy`,children:o(`lark.setupCopy`)}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.profileName`)}),(0,V.jsx)(`input`,{"aria-label":o(`lark.profileName`),autoComplete:`off`,onChange:e=>Ce(e.target.value),placeholder:`loopx-workspace-bot`,value:Se})]}),(0,V.jsxs)(`label`,{children:[(0,V.jsx)(`span`,{children:o(`lark.region`)}),(0,V.jsxs)(`select`,{"aria-label":o(`lark.region`),onChange:e=>Te(e.target.value),value:we,children:[(0,V.jsx)(`option`,{value:`feishu`,children:`Feishu`}),(0,V.jsx)(`option`,{value:`lark`,children:`Lark`})]})]}),Se&&!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Se)?(0,V.jsx)(`p`,{className:`personal-notification-error`,children:o(`lark.profileValidation`)}):null]}),ke?(0,V.jsx)(`p`,{className:`personal-notification-error`,children:ke}):null,(0,V.jsxs)(`footer`,{children:[(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void Xe(),type:`button`,children:o(`lark.cancel`)}),z?null:(0,V.jsxs)(`button`,{className:`personal-primary-action`,disabled:De||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Se),onClick:()=>void Ye(),type:`button`,children:[De?(0,V.jsx)(Cm,{className:`is-spinning`,size:15}):(0,V.jsx)(fm,{size:15}),o(`lark.continueFeishu`)]})]})]})}):null]})}function Ab(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function jb(e,t,n){let r=Ab(t),i=Ab(n);return Object.fromEntries(e.fields.flatMap(({key:e,nullable:t})=>{let n=r[e],a=i[e];return Object.hasOwn(r,e)&&(n!=null||t&&n===null)?[[e,n]]:Object.hasOwn(i,e)&&a!=null?[[e,a]]:[]}))}function Mb(e,t){let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=new Set(e.fields.map(e=>e.key));return Object.keys(n).some(e=>!r.has(e))?null:n}function Nb(e,t,n){let r={...e,[t]:n},i=e.schedule;return t===`timezone`&&i&&typeof i==`object`&&`schema_version`in i&&i.schema_version===`periodic_report_schedule_v0`&&(r.schedule={...i,timezone:n}),r}function Pb({id:e,value:t,timezone:n,onChange:r}){let{locale:i}=qi(),a=i===`zh-CN`,o=t&&typeof t==`object`&&!Array.isArray(t)?t:null,s=String(o?.rrule??``).split(`;`).map(e=>e.split(`=`)),c=Object.fromEntries(s.filter(e=>e.length===2)),l=[`MO`,`TU`,`WE`,`TH`,`FR`,`SA`,`SU`],u=(e,t)=>e!==void 0&&/^\d+$/.test(e)&&Number(e)<=t,d=!o||o.schema_version===`periodic_report_schedule_v0`&&[`DAILY`,`WEEKLY`].includes(c.FREQ)&&o.timezone===n&&s.every(e=>e.length===2&&[`FREQ`,`BYDAY`,`BYHOUR`,`BYMINUTE`,`INTERVAL`].includes(e[0]))&&new Set(s.map(([e])=>e)).size===s.length&&u(c.BYHOUR,23)&&u(c.BYMINUTE??`0`,59)&&(c.FREQ===`WEEKLY`?l.includes(c.BYDAY):!c.BYDAY)&&(!c.INTERVAL||c.INTERVAL===`1`),f=a?[`星期一`,`星期二`,`星期三`,`星期四`,`星期五`,`星期六`,`星期日`]:[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`];function p(e){let t={FREQ:`WEEKLY`,BYDAY:`MO`,BYHOUR:`9`,BYMINUTE:`0`,...c,...e};r?.({schema_version:`periodic_report_schedule_v0`,schedule_id:o?.schedule_id??`report-schedule`,timezone:n,rrule:[`FREQ=${t.FREQ}`,...t.FREQ===`WEEKLY`?[`BYDAY=${t.BYDAY}`]:[],`BYHOUR=${t.BYHOUR}`,`BYMINUTE=${t.BYMINUTE}`].join(`;`)})}return(0,V.jsxs)(`div`,{className:`personal-report-schedule`,children:[(0,V.jsxs)(`label`,{className:`is-boolean`,htmlFor:e,children:[(0,V.jsx)(`span`,{children:a?`按日历汇报`:`Calendar reports`}),(0,V.jsx)(`input`,{id:e,type:`checkbox`,role:`switch`,checked:!!o,disabled:!r,onChange:e=>e.target.checked?p({}):r?.(null)})]}),o?(0,V.jsxs)(V.Fragment,{children:[d?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{htmlFor:`${e}-frequency`,children:[(0,V.jsx)(`span`,{children:a?`频率`:`Frequency`}),(0,V.jsxs)(`select`,{id:`${e}-frequency`,value:c.FREQ,disabled:!r,onChange:e=>p({FREQ:e.target.value}),children:[(0,V.jsx)(`option`,{value:`DAILY`,children:a?`每天`:`Daily`}),(0,V.jsx)(`option`,{value:`WEEKLY`,children:a?`每周`:`Weekly`})]})]}),c.FREQ===`WEEKLY`&&(0,V.jsxs)(`label`,{htmlFor:`${e}-day`,children:[(0,V.jsx)(`span`,{children:a?`星期`:`Weekday`}),(0,V.jsx)(`select`,{id:`${e}-day`,value:c.BYDAY,disabled:!r,onChange:e=>p({BYDAY:e.target.value}),children:l.map((e,t)=>(0,V.jsx)(`option`,{value:e,children:f[t]},e))})]}),(0,V.jsxs)(`label`,{htmlFor:`${e}-time`,children:[(0,V.jsxs)(`span`,{children:[a?`当地时间`:`Local time`,` (`,n,`)`]}),(0,V.jsx)(`input`,{id:`${e}-time`,type:`time`,required:!0,disabled:!r,value:`${(c.BYHOUR??`9`).padStart(2,`0`)}:${(c.BYMINUTE??`0`).padStart(2,`0`)}`,onChange:e=>{if(!/^\d{2}:\d{2}$/.test(e.target.value))return;let[t,n]=e.target.value.split(`:`);p({BYHOUR:t,BYMINUTE:n})}})]})]}):(0,V.jsx)(`p`,{role:`alert`,children:a?`此计划需在 JSON 模式中编辑;当前内容已保留。`:`Edit this schedule in JSON mode; its current value is preserved.`}),(0,V.jsx)(`p`,{children:a?`由现有唤醒检查到期计划;实际送达以回执为准。`:`Existing wakes check the schedule; delivery is confirmed by its receipt.`})]}):(0,V.jsx)(`p`,{children:a?`未设置日历计划;保持阶段结束时汇报。`:`No calendar schedule; report at validated stage boundaries.`})]})}function Fb({copy:e,field:t,id:n,onChange:r,value:i,timezone:a}){let o=e[t.key]?.label??t.label,s=!r;if(t.input_kind===`periodic_report_schedule`)return(0,V.jsx)(Pb,{id:n,value:i,timezone:a,onChange:r?e=>r(t.key,e):void 0});if(t.input_kind===`boolean`)return(0,V.jsxs)(`label`,{className:`is-boolean`,htmlFor:n,children:[(0,V.jsx)(`span`,{children:o}),(0,V.jsx)(`input`,{checked:i===!0,id:n,onChange:r?e=>r(t.key,e.target.checked):void 0,readOnly:s,role:`switch`,type:`checkbox`})]});if(t.input_kind===`select`)return(0,V.jsxs)(`label`,{htmlFor:n,children:[(0,V.jsx)(`span`,{children:o}),(0,V.jsxs)(`select`,{id:n,onChange:r?e=>r(t.key,e.target.value):void 0,value:typeof i==`string`?i:``,children:[(0,V.jsx)(`option`,{value:``}),(t.options??[]).map(e=>(0,V.jsx)(`option`,{value:e,children:e},e))]})]});if(t.input_kind===`string_list`)return(0,V.jsxs)(`label`,{htmlFor:n,children:[(0,V.jsx)(`span`,{children:o}),(0,V.jsx)(`textarea`,{id:n,onChange:r?e=>r(t.key,e.target.value.split(/\r?\n/u).filter(Boolean)):void 0,readOnly:s,rows:4,value:Array.isArray(i)?i.join(` -`):``})]});let c=t.input_kind===`number`;return(0,V.jsxs)(`label`,{htmlFor:n,children:[(0,V.jsx)(`span`,{children:o}),(0,V.jsx)(`input`,{id:n,max:t.maximum,min:t.minimum,onChange:r?e=>r(t.key,c?Number(e.target.value):e.target.value):void 0,readOnly:s,required:t.required,type:c?`number`:`text`,value:typeof i==`number`||typeof i==`string`?i:``})]})}function Ib({copy:e={},disabled:t=!1,editor:n,enabledAction:r,omitKeys:i=[],onChange:a,value:o}){let s=(0,B.useId)(),c=new Set(i);return(0,V.jsx)(`fieldset`,{className:`personal-capability-fields`,disabled:t,children:n.fields.filter(e=>!c.has(e.key)).map(t=>{let n=(0,V.jsx)(Fb,{copy:e,field:t,id:`${s}-${t.key.replace(/[^a-z0-9_-]/gi,`-`)}`,onChange:a,value:o[t.key],timezone:String(o.timezone??`UTC`)},t.key);return t.key===`enabled`&&t.input_kind===`boolean`?(0,V.jsxs)(`div`,{className:`personal-capability-enabled-row`,children:[n,r]},t.key):n})})}var Lb={en:{todo_replan_cadence:{displayName:`Goal review cadence`,description:`Configures the Goal review cadence.`},change_quality_qualification:{displayName:`Change quality qualification`,description:`Prepares a provider-neutral review packet, allows at most one policy-authorized safe-fix pass, and can require an exact-diff receipt.`},explore_graph:{displayName:`Explore Graph`,description:`Organizes bounded exploration as a typed evidence graph so branches, findings, and synthesis remain inspectable.`},explore_harness:{displayName:`Explore Harness`,description:`Selects a capability-owned planning and research harness profile for bounded multi-step exploration.`},lark_event_inbox:{displayName:`Lark event inbox`,description:`Receives provider events through a local-private inbox binding before LoopX projects them into governed work.`,readOnlyReason:`This capability requires a local-private inbox binding. Manage it in Lark settings or through the capability CLI.`},lark_kanban_heartbeat_sync:{displayName:`Lark Kanban heartbeat sync`,description:`Synchronizes accepted LoopX work state to the configured Lark Kanban heartbeat surface.`},local_authority_shadow:{displayName:`Local authority shadow`,description:`Observes post-commit Todo and task-lease state through the shared authority contract without taking write authority.`},multi_subagent:{displayName:`Adaptive child capacity`,description:`Sets bounded child-agent capacity and the public-safe responsibility domains in which parallel work may be delegated.`},peer_task_coordination:{displayName:`Registered-peer task coordination`,description:`Routes explicitly scoped peer-owned work to one registered coordinator without granting cross-owner mutation authority.`},periodic_report:{displayName:`Periodic reports`,description:`Turns validated Goal stage progress into a frozen report and automatically delivers it through the configured Goal Channel with exact readback.`},pull_request_review:{displayName:`Pull-request review`,description:`Ranks the public GitHub PR review queue with a machine-level default; it never grants GitHub, Todo, push, or merge authority.`},reward_memory:{displayName:`Reward Memory experiment`,description:`Configures a reviewed local-private provider binding for Goal-scoped Agent recall and evidence-backed outcome learning.`}},"zh-CN":{todo_replan_cadence:{displayName:`Goal 复核周期`,description:`配置 Goal 的复核周期。`},change_quality_qualification:{displayName:`变更质量验证`,description:`生成与 Provider 无关的审阅包,最多允许一次策略授权的安全修复,并可要求精确 diff 回执。`},explore_graph:{displayName:`探索图谱`,description:`把有界探索组织为 typed 证据图,让探索分支、发现与综合结论都可检查、可追溯。`},explore_harness:{displayName:`探索 Harness`,description:`为有界的多步探索选择由能力负责的规划与研究 Harness profile。`},lark_event_inbox:{displayName:`飞书事件收件箱`,description:`通过本机私有收件箱接收 Provider 事件,再由 LoopX 将其投影为受治理的工作。`,readOnlyReason:`此能力依赖本机私有的收件箱绑定,请在飞书设置或 capability CLI 中管理。`},lark_kanban_heartbeat_sync:{displayName:`飞书看板心跳同步`,description:`把 LoopX 已接受的工作状态同步到配置好的飞书看板心跳界面。`},local_authority_shadow:{displayName:`本地 Authority 影子观测`,description:`通过共享 Authority contract 观测提交后的 Todo 与 task lease 状态,但不取得写入权。`},multi_subagent:{displayName:`自适应子 Agent 容量`,description:`限定子 Agent 容量与可公开的职责域,只有落在这些边界内的工作才能并行委派。`},peer_task_coordination:{displayName:`已注册 Peer 任务协调`,description:`把明确限定的 Peer 工作路由给一个已注册协调者,不授予跨 Owner 修改权限。`},periodic_report:{displayName:`周期报告`,description:`把经过验证的 Goal 阶段进展整理为冻结报告,并通过配置的 Goal Channel 自动发送和精确回读。`},pull_request_review:{displayName:`Pull-request Review`,description:`配置公开 GitHub PR 审阅队列的本机默认排序;不会授予 GitHub、Todo、push 或 merge 权限。`},reward_memory:{displayName:`Reward Memory 实验`,description:`为 Goal 内 Agent 的召回与证据化结果学习配置经过审阅的本机私有 Provider 绑定。`}}},Rb={en:{completed_todos:{label:`Completed Todos between Goal reviews`,description:`Machine default or explicit Goal override, from 1 to 5.`},allowed_domains:{label:`Allowed responsibility domains`,description:`Enter one bounded, public-safe domain per line.`},coordinator_agent_id:{label:`Coordinator Agent`,description:`Use an already registered Agent id; leave blank to disable coordination.`},enabled:{label:`Enabled`},model:{label:`Child model`,description:`For example gpt-5.6-luna. Blank clears the child model preference.`},reasoning_effort:{label:`Child reasoning effort`,description:`For example max; the host must support this model and effort.`},max_children:{label:`Maximum children`,description:`Hard upper bound for concurrently delegated child work.`},profile:{label:`Planner profile`,description:`Select one registered Explore Harness profile.`},profile_preset:{label:`Report profile`,description:`Capability-owned report profile, such as weekly-progress.`},review_priority:{label:`Review priority`,description:`Choose whether other developers' PRs or the authenticated reviewer's own PRs are ranked first.`},route_ref:{label:`Goal Channel route`,description:`Public route alias only; credentials and provider identifiers stay outside this form.`},safe_fix:{label:`Allow one bounded safe-fix pass`},strict_receipt:{label:`Require an exact-diff receipt`},timezone:{label:`Timezone`,description:`Use an IANA timezone, for example Asia/Shanghai.`},schedule:{label:`Calendar reports`,description:`Optional daily or weekly reports; no schedule preserves stage-only delivery.`},config_path:{label:`Local-private configuration path`,description:`Repo-relative ignored JSON under .loopx/config/. Leave blank to retain the current binding; the path is never returned.`},enabled_agents:{label:`Enabled Goal Agents`,description:`Enter one registered Goal-local Agent id per line. A private binding currently accepts exactly one Agent.`}},"zh-CN":{completed_todos:{label:`两次 Goal 复核间的已完成 Todo 数`,description:`可设置 1–5;机器默认值可被 Goal 显式覆盖。`},allowed_domains:{label:`允许的职责域`,description:`每行填写一个有边界、可公开的职责域。`},coordinator_agent_id:{label:`协调 Agent`,description:`填写一个已经注册的 Agent ID;留空表示关闭协调。`},enabled:{label:`启用`},model:{label:`子 Agent 模型`,description:`例如 gpt-5.6-luna;留空清除模型偏好。`},reasoning_effort:{label:`子 Agent 推理档位`,description:`例如 max;宿主须支持所选模型与档位。`},max_children:{label:`最大子 Agent 数`,description:`可同时委派的子任务硬上限。`},profile:{label:`规划 Profile`,description:`选择一个已注册的 Explore Harness profile。`},profile_preset:{label:`报告 Profile`,description:`由该能力管理的报告 profile,例如 weekly-progress。`},review_priority:{label:`审阅优先级`,description:`选择先排其他开发者的 PR,还是先排当前已认证审阅者自己的 PR。`},route_ref:{label:`Goal Channel 路由`,description:`只填写公开 route alias;凭据与 Provider 标识不会进入此表单。`},safe_fix:{label:`允许一次有界安全修复`},strict_receipt:{label:`要求精确 diff 回执`},timezone:{label:`时区`,description:`使用 IANA 时区,例如 Asia/Shanghai。`},schedule:{label:`日历汇报`,description:`可选每日或每周计划;未设置时保持阶段结束汇报。`},config_path:{label:`本机私有配置路径`,description:`填写 .loopx/config/ 下、相对仓库且被忽略的 JSON;留空保留当前绑定,路径不会被回传。`},enabled_agents:{label:`已启用的 Goal Agent`,description:`每行填写一个已注册的 Goal 内 Agent ID;私有绑定当前只接受一个 Agent。`}}};function zb(e,t){let n=Lb[t][e.capability_id];return n?{...e,display_name:n.displayName,description:n.description,configuration_editor:{...e.configuration_editor,...n.readOnlyReason?{read_only_reason:n.readOnlyReason}:{}}}:e}function Bb(e){return Rb[e]}Object.freeze(Object.keys(Lb.en).sort());function Vb(e,t){return e.available_scopes.includes(t)&&(t!==`machine`||!!e.machine_namespace)&&e.configuration_editor.editable&&e.configuration_editor.writable_scopes.includes(t)}function Hb({values:e,t}){return(0,V.jsxs)(`details`,{className:`personal-capability-raw-values`,children:[(0,V.jsx)(`summary`,{children:t(`capabilities.rawJson`)}),(0,V.jsx)(`div`,{className:`personal-capability-value-grid`,children:e.map(({label:e,value:t})=>(0,V.jsxs)(`section`,{children:[(0,V.jsx)(`strong`,{children:e}),(0,V.jsx)(`pre`,{children:t?JSON.stringify(t,null,2):`—`})]},e))})]})}function Ub({source:e,t}){return e?(0,V.jsxs)(`p`,{className:`personal-capability-effective-source`,children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:15}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:t(`capabilities.effectiveSource`)}),t(`capabilities.source.${e}`)]})]}):null}function Wb({available:e,description:t,t:n}){return e?null:(0,V.jsxs)(`section`,{className:`personal-capability-editor-status is-read-only`,children:[(0,V.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:n(`capabilities.readOnly`)}),(0,V.jsx)(`p`,{children:t})]})]})}function Gb(e){return e.availability?.includes(`experimental`)?4:e.capability_id===`multi_subagent`?3:e.configuration_editor.writable_scopes.length===0||e.availability===`supported_explicit_opt_in`?2:e.availability===`supported_explicit_override`?0:1}function Kb(e,t){return[...e].sort((e,n)=>{let r=Gb(e)-Gb(n);if(r!==0)return r;let i=zb(e,t),a=zb(n,t);return i.display_name.localeCompare(a.display_name,t)||e.capability_id.localeCompare(n.capability_id)})}function qb({capabilities:e,locale:t,onSelect:n,scope:r,selectedCapabilityId:i,t:a}){return(0,V.jsx)(`nav`,{"aria-label":a(r===`goal`?`capabilities.catalog`:`machine.capabilityCatalog`),className:`personal-capability-list`,tabIndex:0,children:Kb(e,t).map(e=>{let o=zb(e,t);return(0,V.jsxs)(`button`,{"aria-current":i===o.capability_id?`page`:void 0,onClick:()=>n(o.capability_id),type:`button`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:o.display_name})}),(0,V.jsx)(`em`,{children:a(o.available_scopes.includes(r)?r===`goal`?`capabilities.goalScope`:`capabilities.machineScope`:r===`machine`?`capabilities.goalScope`:`capabilities.machineScope`)})]},o.capability_id)})})}function Jb({capability:e,locale:t,source:n}){let{t:r}=qi(),i=zb(e,t);return(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`span`,{className:`personal-settings-icon`,children:(0,V.jsx)(Gm,{"aria-hidden":!0,size:18})}),(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{className:`personal-capability-heading-row`,children:[(0,V.jsx)(`h2`,{children:i.display_name}),(0,V.jsx)(Ub,{source:n,t:r})]}),e.context_contribution&&(0,V.jsxs)(`details`,{className:`personal-capability-help`,"data-testid":`capability-context-phases`,children:[(0,V.jsx)(`summary`,{children:t===`zh-CN`?`主 Agent 协作指导`:`Coordinator workflow guidance`}),(0,V.jsx)(`p`,{children:t===`zh-CN`?`随能力开启。支持以下阶段;此处展示能力范围,不能证明某次运行已读取或采纳。`:`Enabled with this capability. These are supported phases, not proof that a run read or adopted the guidance.`}),(0,V.jsx)(`dl`,{children:e.context_contribution.supported_phases.map(e=>(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:(0,V.jsx)(`code`,{children:e})}),(0,V.jsx)(`dd`,{children:Yb[e][t===`zh-CN`?`zh`:`en`]})]},e))}),(0,V.jsx)(`p`,{children:t===`zh-CN`?`LoopX Turn 在请求与结果中提供上下文;原生工具入口由 LoopX skill 调用同一只读接口。执行与采纳需另看运行证据。`:`LoopX Turn includes context in requests and results. For native tools, the LoopX skill reads the same interface. Execution and adoption require run evidence.`})]}),(0,V.jsxs)(`details`,{className:`personal-capability-help`,children:[(0,V.jsx)(`summary`,{children:t===`zh-CN`?`配置说明`:`Configuration help`}),(0,V.jsx)(`p`,{children:i.description}),(0,V.jsx)(`dl`,{children:e.configuration_editor.fields.map(e=>{let n=Bb(t)[e.key],r=n?.description??e.description;return r?(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:n?.label??e.label}),(0,V.jsx)(`dd`,{children:r})]},e.key):null})})]},e.capability_id)]})]})}var Yb={before_plan:{zh:`规划前:识别独立问题并保留主 Agent 的核验与整合职责。`,en:`Before planning: identify independent questions and retain coordinator validation and integration.`},before_delegate:{zh:`委派前:明确子任务边界、模型偏好及预期证据。`,en:`Before delegation: specify task boundaries, model preferences and expected evidence.`},after_delegate_result:{zh:`回收后:核验结果,说明采纳决定并关联计划与成果。`,en:`After results: validate evidence, explain acceptance and link plans and deliverables.`}};function Xb({goalId:e,onApplied:t,selected:n,t:r}){let[i,a]=(0,B.useState)({busy:null,draft:{},partialWrite:null,preview:null}),[o,s]=(0,B.useState)(null),[c,l]=(0,B.useState)(`guided`),[u,d]=(0,B.useState)(``),f=(0,B.useMemo)(()=>n?Mb(n.configuration_editor,u):null,[n,u]),p=c===`guided`||f!==null;(0,B.useEffect)(()=>{l(`guided`),d(``),a({busy:null,draft:jb(n?.configuration_editor??{fields:[]},n?.current??n?.effective_configuration?.configuration??n?.default,n?.default),partialWrite:null,preview:null}),s(null)},[n]);async function m(t){if(!(!n||i.busy||!p)){a(e=>({...e,busy:`preview`,partialWrite:null})),s(null);try{let r=await Eg(e,n.capability_id,t);a(e=>({...e,preview:r}))}catch(e){s(e instanceof Error?e.message:r(`capabilities.previewFailed`))}finally{a(e=>({...e,busy:null}))}}}async function h(){if(!(!n||!i.preview||i.busy||!p)){a(e=>({...e,busy:`apply`})),s(null);try{let r=jb(n.configuration_editor,i.draft,n.default),o=await Dg(e,n.capability_id,i.preview.action===`delete`?null:r,i.preview.plan_revision);a(e=>({...e,partialWrite:o.status===`partial_write`?o:null,preview:null})),o.status!==`partial_write`&&t()}catch(e){a(e=>({...e,preview:null})),s(e instanceof Error?e.message:r(`capabilities.applyFailed`))}finally{a(e=>({...e,busy:null}))}}}function g(e,t){a(r=>({...r,draft:n?.capability_id===`periodic_report`?Nb(r.draft,e,t):{...r.draft,[e]:t},preview:null})),s(null)}function _(e){if(!n||i.busy)return;d(e);let t=Mb(n.configuration_editor,e);a(e=>({...e,preview:null,draft:t?jb(n.configuration_editor,t,n.default):e.draft})),s(null)}function v(){i.busy||!p||(c===`guided`&&d(JSON.stringify(i.draft,null,2)),l(c===`guided`?`json`:`guided`),a(e=>({...e,preview:null})))}return{apply:h,changeDraft:g,changeJson:_,changeMode:v,editorMode:c,jsonDraft:u,jsonValid:p,error:o,mutation:i,preview:m}}function Zb({mutationError:e,onApplied:t,partialWrite:n,preview:r}){let{t:i}=qi();return(0,V.jsxs)(V.Fragment,{children:[e?(0,V.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:e}):null,n?(0,V.jsxs)(`section`,{"aria-live":`polite`,className:`personal-capability-recovery`,children:[(0,V.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:i(`capabilities.partialWrite`)}),(0,V.jsx)(`p`,{children:i(`capabilities.partialWriteDescription`)}),(0,V.jsx)(`small`,{children:n.recommended_action})]}),(0,V.jsxs)(`button`,{onClick:t,type:`button`,children:[(0,V.jsx)(Im,{"aria-hidden":!0,size:15}),i(`capabilities.refreshSource`)]})]}):null,r?(0,V.jsxs)(`section`,{className:`personal-capability-preview`,"aria-label":i(`capabilities.preview`),children:[(0,V.jsx)(`strong`,{children:i(`capabilities.preview`)}),(0,V.jsx)(`span`,{children:i(`machine.action.${r.action}`)}),(0,V.jsx)(`small`,{children:i(`capabilities.previewLocked`)})]}):null]})}function Qb({catalog:e,goalId:t,onApplied:n}){let{locale:r,t:i}=qi(),a=(0,B.useMemo)(()=>Kb(e.capabilities,r),[e.capabilities,r]),[o,s]=(0,B.useState)(()=>a[0]?.capability_id??``),c=(0,B.useMemo)(()=>a.find(e=>e.capability_id===o)??a[0],[a,o]),l=(0,B.useMemo)(()=>c?zb(c,r):void 0,[r,c]),{apply:u,changeDraft:d,changeJson:f,changeMode:p,editorMode:m,jsonDraft:h,jsonValid:g,error:_,mutation:v,preview:y}=Xb({goalId:t,onApplied:n,selected:l,t:i}),{busy:b,draft:x,partialWrite:S,preview:C}=v;if(!c||!l)return(0,V.jsx)(`p`,{className:`personal-capability-empty`,children:i(`capabilities.empty`)});let w=l.available_scopes.includes(`goal`),T=Vb(l,`goal`),E=l.configuration_editor.read_only_reason??i(w?`capabilities.previewOnly`:`capabilities.machineOnly`);async function D(){if(!l||!T||b||!g)return;let e=jb(l.configuration_editor,x,l.default);await y(e)}async function O(){!T||b||await y(null)}return(0,V.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,V.jsx)(qb,{capabilities:e.capabilities,locale:r,onSelect:s,scope:`goal`,selectedCapabilityId:l.capability_id,t:i}),(0,V.jsxs)(`article`,{"aria-label":l.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,V.jsx)(Jb,{capability:c,locale:r,source:l.effective_configuration?.source}),(0,V.jsx)(Wb,{available:T,t:i,description:E}),T?(0,V.jsxs)(V.Fragment,{children:[m===`json`||!l.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,V.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,V.jsxs)(`button`,{disabled:!!b||!g,onClick:p,type:`button`,children:[(0,V.jsx)(sm,{"aria-hidden":!0,size:14}),i(m===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,m===`guided`?(0,V.jsx)(`section`,{className:`personal-capability-field-summary`,children:(0,V.jsx)(Ib,{disabled:!!b,copy:Bb(r),editor:l.configuration_editor,onChange:d,value:x,enabledAction:(0,V.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:p,type:`button`,children:[(0,V.jsx)(sm,{"aria-hidden":!0,size:14}),i(`machine.editJson`)]})})}):(0,V.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`goal-configuration-json`,children:[(0,V.jsx)(`span`,{children:i(`capabilities.jsonConfiguration`)}),(0,V.jsx)(`textarea`,{id:`goal-configuration-json`,"aria-describedby":`goal-configuration-json-help`,disabled:!!b,onChange:e=>f(e.target.value),rows:12,spellCheck:!1,value:h}),(0,V.jsx)(`small`,{id:`goal-configuration-json-help`,children:i(`capabilities.jsonHelp`)}),g?null:(0,V.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:i(`capabilities.jsonInvalid`)})]})]}):null,(0,V.jsx)(Zb,{mutationError:_,onApplied:n,partialWrite:S,preview:C}),T?(0,V.jsxs)(`footer`,{className:`personal-capability-actions`,children:[l.current&&l.available_scopes.includes(`machine`)?(0,V.jsx)(`button`,{disabled:!!b||!g,onClick:()=>void O(),type:`button`,children:i(`capabilities.restoreInheritance`)}):null,(0,V.jsx)(`button`,{disabled:!!b||!g,onClick:()=>void D(),type:`button`,children:i(b===`preview`?`common.loading`:`capabilities.previewChanges`)}),(0,V.jsx)(`button`,{className:`is-primary`,disabled:!!b||!C||!g,onClick:()=>void u(),type:`button`,children:i(b===`apply`?`common.loading`:`capabilities.applyPreview`)})]}):null,(0,V.jsx)(Hb,{values:[{label:i(`capabilities.goalValue`),value:l.current},{label:i(l.machine_current?`capabilities.machineValue`:`capabilities.defaultValue`),value:l.machine_current??l.default}],t:i},c.capability_id)]})]})}function $b({goalId:e}){let{t}=qi(),[n,r]=(0,B.useState)(null),[i,a]=(0,B.useState)(null),[o,s]=(0,B.useState)(!1);function c(){e&&(s(!0),a(null),Tg(e).then(r).catch(e=>a(e instanceof Error?e.message:t(`capabilities.loadFailed`))).finally(()=>s(!1)))}return(0,B.useEffect)(c,[e]),e?o&&!n?(0,V.jsxs)(`p`,{"aria-live":`polite`,className:`personal-capability-empty`,children:[(0,V.jsx)(Cm,{className:`personal-spin`,size:18}),t(`capabilities.loading`)]}):i?(0,V.jsxs)(`section`,{className:`personal-capability-error`,role:`alert`,children:[(0,V.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:t(`capabilities.loadFailed`)}),(0,V.jsx)(`small`,{children:i})]}),(0,V.jsxs)(`button`,{onClick:c,type:`button`,children:[(0,V.jsx)(Im,{"aria-hidden":!0,size:15}),t(`capabilities.retry`)]})]}):n?(0,V.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":n.revision,children:[(0,V.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:17}),t(`capabilities.atomicOverride`)]}),(0,V.jsx)(`p`,{children:t(`capabilities.atomicOverrideDescription`)})]}),(0,V.jsx)(Qb,{catalog:n.capability_catalog,goalId:e,onApplied:c})]}):null:(0,V.jsx)(`p`,{className:`personal-capability-empty`,children:t(`capabilities.chooseGoal`)})}function ex(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function tx(e,t){let n=t?.machine_namespace;return n?e?.machine_configuration?.namespaces[n]:void 0}function nx(e,t,n){return{...ex(e.default),...ex(t),...n}}function rx(e,t){for(let n of e.configuration_editor.fields){let e=t[n.key];if(n.required&&(e==null||e===``))return!1}return e.capability_id===`periodic_report`&&t.enabled===!0?!!(String(t.profile_preset??``).trim()&&String(t.route_ref??``).trim()&&String(t.timezone??``).trim()):!0}function ix(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:null}catch{return null}}function ax(e){return e?e===`absent`?e:e.replace(/^sha256:/,``).slice(0,12):`—`}function ox(){let{locale:e,t}=qi(),[n,r]=(0,B.useState)(null),[i,a]=(0,B.useState)(``),[o,s]=(0,B.useState)({}),[c,l]=(0,B.useState)(`{}`),[u,d]=(0,B.useState)(`guided`),[f,p]=(0,B.useState)(null),[m,h]=(0,B.useState)(`upsert`),[g,_]=(0,B.useState)(null),[v,y]=(0,B.useState)(null),[b,x]=(0,B.useState)(`load`),[S,C]=(0,B.useState)(null),[w,T]=(0,B.useState)(null),E=(0,B.useMemo)(()=>Kb(n?.capability_catalog.capabilities??[],e),[n,e]),D=E.find(e=>e.capability_id===i)??E.find(e=>Vb(e,`machine`))??E[0],O=D?zb(D,e):void 0,ee=tx(n,O),te=!!(O?.machine_namespace&&ee),ne=!!(O&&Vb(O,`machine`)),k=(0,B.useMemo)(()=>ix(c),[c]),A=O?u===`json`?k:nx(O,ee,o):null,j=!!(O&&(u===`json`?k:rx(O,A??{})));async function M(){r(await wg())}(0,B.useEffect)(()=>{let e=!0;return wg().then(t=>{e&&r(t)}).catch(n=>{e&&C(n instanceof Error?n.message:t(`machine.loadError`))}).finally(()=>{e&&x(null)}),()=>{e=!1}},[t]),(0,B.useEffect)(()=>{if(!O)return;let e=tx(n,O),t=jb(O.configuration_editor,e??O.default,O.default),r=nx(O,e,t);s(t),l(JSON.stringify(r,null,2)),d(ne?`guided`:`json`),p(null),h(`upsert`),y(null)},[n,i,e]);function N(e,t){s(n=>O?.capability_id===`periodic_report`?Nb(n,e,t):{...n,[e]:t}),p(null),h(`upsert`),C(null),T(null)}function P(e){if(O){if(e===`json`)l(JSON.stringify(nx(O,ee,o),null,2));else if(k)s(jb(O.configuration_editor,k,O.default));else{C(t(`machine.jsonInvalid`));return}d(e),p(null),h(`upsert`),C(null)}}async function F(){if(!(!ne||!O?.machine_namespace||!A||!j||b)){x(`preview`),C(null),T(null);try{h(`upsert`),p(await Og(O.machine_namespace,A))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function re(){if(!(!ne||!O?.machine_namespace||!te||b)){x(`preview`),C(null),T(null);try{h(`remove`),p(await Ag(O.machine_namespace))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function ie(){if(!ne||!O?.machine_namespace||!f||b||m===`upsert`&&!A)return;x(`apply`),C(null);let e=m;try{let n=e===`remove`?await jg(O.machine_namespace,f.plan_revision):await kg(O.machine_namespace,A,f.plan_revision);_(n),p(null),h(`upsert`),y(null),await M(),T(n.status===`applied`?t(e===`remove`?`machine.removed`:`machine.applied`):t(`machine.unchanged`))}catch(e){p(null),h(`upsert`),C(e instanceof Error?e.message:t(`machine.applyError`))}finally{x(null)}}async function I(){if(!(!g?.transaction_id||b)){x(`rollback-preview`),C(null);try{y(await Mg(g.transaction_id))}catch(e){C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}async function ae(){if(!(!g?.transaction_id||!v||b)){x(`rollback`),C(null);try{await Ng(g.transaction_id,v.plan_revision),_(null),y(null),p(null),await M(),T(t(`machine.rolledBack`))}catch(e){y(null),C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}return b===`load`?(0,V.jsx)(`div`,{className:`personal-machine-loading`,role:`status`,children:t(`common.loading`)}):O?(0,V.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":n?.revision,children:[(0,V.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:17}),t(`machine.liveDefault`)]}),(0,V.jsx)(`p`,{children:t(`machine.liveDefaultDescription`)})]}),(0,V.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,V.jsx)(qb,{capabilities:E,locale:e,onSelect:a,scope:`machine`,selectedCapabilityId:O.capability_id,t}),(0,V.jsxs)(`article`,{"aria-label":O.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,V.jsx)(Jb,{capability:D,locale:e,source:O.available_scopes.includes(`machine`)?te?`machine_default`:`capability_default`:void 0}),(0,V.jsx)(Wb,{available:ne,t,description:O.available_scopes.includes(`machine`)?t(`machine.editorUnavailableDescription`):t(`machine.goalOnly`)}),O.capability_id===`periodic_report`?(0,V.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:ee?.schedule?e===`zh-CN`?`日历与阶段汇报`:`Calendar and stage reports`:t(`machine.periodicReportActivation`)}),(0,V.jsx)(`p`,{children:ee?.schedule?ee.enabled===!0?e===`zh-CN`?`已配置日历计划,由现有唤醒检查;是否送达请核对报告回执。`:`A calendar schedule is configured and checked by existing wakes. Verify delivery in the report receipt.`:e===`zh-CN`?`日历计划已保存;启用此能力后才会检查和投递。`:`The schedule is saved; enable this capability to check and deliver reports.`:t(`machine.periodicReportActivationDescription`)})]})]}):null,O.capability_id===`change_quality_qualification`?(0,V.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:t(`machine.changeQualityActivation`)}),(0,V.jsx)(`p`,{children:t(`machine.changeQualityActivationDescription`)})]})]}):null,O.capability_id===`todo_replan_cadence`?(0,V.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:t(`machine.replanCadenceActivation`)}),(0,V.jsx)(`p`,{children:t(`machine.replanCadenceActivationDescription`)})]})]}):null,O.capability_id===`pull_request_review`?(0,V.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,V.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:e===`zh-CN`?`只改变队列排序`:`Queue ordering only`}),(0,V.jsx)(`p`,{children:e===`zh-CN`?`默认先审阅其他开发者的 PR;选择 owner-first 才会优先当前已认证审阅者自己的 PR。此配置不会发布 review、写 Todo、push 或 merge。`:`The default reviews other developers' PRs first; choose owner-first only when the authenticated reviewer's own PRs should lead. This setting never posts a review, writes Todos, pushes, or merges.`})]})]}):null,ne?(0,V.jsxs)(V.Fragment,{children:[u===`json`||!O.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,V.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,V.jsxs)(`button`,{onClick:()=>P(u===`guided`?`json`:`guided`),type:`button`,children:[(0,V.jsx)(sm,{"aria-hidden":!0,size:14}),t(u===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,u===`guided`?(0,V.jsxs)(`section`,{className:`personal-capability-field-summary`,children:[(0,V.jsx)(Ib,{copy:Bb(e),disabled:!!b,editor:O.configuration_editor,onChange:N,value:o,enabledAction:(0,V.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:()=>P(`json`),type:`button`,children:[(0,V.jsx)(sm,{"aria-hidden":!0,size:14}),t(`machine.editJson`)]})}),j?null:(0,V.jsx)(`p`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.requiredFields`)})]}):(0,V.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`machine-configuration-json`,children:[(0,V.jsx)(`span`,{children:t(`machine.jsonConfiguration`)}),(0,V.jsx)(`textarea`,{"aria-describedby":`machine-configuration-json-help`,disabled:!!b,id:`machine-configuration-json`,onChange:e=>{l(e.target.value),p(null),C(null)},rows:12,spellCheck:!1,value:c}),(0,V.jsx)(`small`,{id:`machine-configuration-json-help`,children:t(`machine.jsonConfigurationHelp`)}),k?null:(0,V.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.jsonInvalid`)})]})]}):null,S?(0,V.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:S}):null,w?(0,V.jsxs)(`p`,{className:`personal-machine-notice`,role:`status`,"aria-live":`polite`,children:[(0,V.jsx)(em,{"aria-hidden":!0,size:16}),w]}):null,f?(0,V.jsxs)(`section`,{"aria-label":t(`machine.preview`),className:`personal-machine-preview`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:t(`machine.preview`)}),(0,V.jsx)(`span`,{children:t(`machine.action.${f.action}`)})]}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`machine.currentRevision`)}),(0,V.jsx)(`dd`,{title:f.current_revision,children:ax(f.current_revision)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`machine.desiredRevision`)}),(0,V.jsx)(`dd`,{title:f.desired_revision,children:ax(f.desired_revision)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:t(`machine.changedNamespaces`)}),(0,V.jsx)(`dd`,{children:f.changed_namespaces.join(`, `)||t(`common.none`)})]})]}),(0,V.jsx)(`p`,{children:t(`machine.previewLocked`)})]}):null,g?.rollback_available&&g.transaction_id?(0,V.jsxs)(`section`,{className:`personal-machine-rollback`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:t(`machine.rollbackAvailable`)}),(0,V.jsx)(`p`,{children:t(v?`machine.rollbackPreviewDescription`:`machine.rollbackDescription`)})]}),(0,V.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!!b||!!(v&&!v.rollback_allowed),onClick:()=>void(v?ae():I()),type:`button`,children:[(0,V.jsx)(Lm,{"aria-hidden":!0,size:15}),t(b===`rollback`||b===`rollback-preview`?`common.loading`:v?`machine.confirmRollback`:`machine.previewRollback`)]})]}):null,ne?(0,V.jsxs)(`footer`,{className:`personal-capability-actions`,children:[te?(0,V.jsxs)(`button`,{className:`is-danger`,disabled:!!b,onClick:()=>void re(),type:`button`,children:[(0,V.jsx)(Xm,{"aria-hidden":!0,size:15}),t(`machine.previewRemoval`)]}):null,(0,V.jsx)(`button`,{disabled:!!b||!j,onClick:()=>void F(),type:`button`,children:t(b===`preview`?`common.loading`:`machine.previewChanges`)}),(0,V.jsx)(`button`,{className:`is-primary`,disabled:!!b||!f,onClick:()=>void ie(),type:`button`,children:t(b===`apply`?`common.loading`:`machine.applyPreview`)})]}):null,O.available_scopes.includes(`machine`)?(0,V.jsx)(Hb,{values:[{label:t(`machine.currentValue`),value:ee},{label:t(`capabilities.defaultValue`),value:O.default}],t},O.capability_id):null]})]})]}):(0,V.jsx)(`p`,{className:`personal-capability-empty`,children:t(`machine.capabilityEmpty`)})}var sx={appearance:Am,capabilities:Gm,language:bm,lark:Um,machine:Vm};function cx({focusGoalConnection:e=!1,goals:t,initialGoalId:n,initialTab:r=`lark`,onChanged:i,onClose:a,onThemeChange:o,theme:s}){let{locale:c,setLocale:l,t:u}=qi(),[d,f]=(0,B.useState)(r),p=[...n?[{key:`capabilities`,label:u(`capabilities.title`)}]:[],{key:`machine`,label:u(`machine.title`)},{key:`lark`,label:`Lark`},{key:`appearance`,label:u(`settings.appearance`)},{key:`language`,label:u(`settings.language`)}],m=[{label:u(`settings.languageEnglish`),value:`en`},{label:u(`settings.languageSimplifiedChinese`),value:`zh-CN`}],h={appearance:{title:u(`settings.appearance`)},capabilities:{title:u(`capabilities.title`)},language:{title:u(`settings.language`)},lark:{title:`Lark`},machine:{title:u(`machine.title`)}}[d];return(0,V.jsxs)(`section`,{"aria-label":u(`settings.title`),className:`personal-settings-page`,"data-pw-theme":s,children:[(0,V.jsxs)(`aside`,{className:`personal-settings-sidebar`,children:[(0,V.jsxs)(`button`,{className:`personal-settings-back`,onClick:a,type:`button`,children:[(0,V.jsx)(Gp,{size:17}),(0,V.jsx)(`span`,{children:u(`settings.back`)})]}),(0,V.jsxs)(`div`,{className:`personal-settings-title`,children:[(0,V.jsx)(`small`,{children:u(`settings.eyebrow`)}),(0,V.jsx)(`strong`,{children:u(`settings.title`)})]}),(0,V.jsx)(`nav`,{"aria-label":u(`settings.categories`),className:`personal-settings-tabs`,children:p.map(e=>{let t=sx[e.key];return(0,V.jsxs)(`button`,{"aria-current":d===e.key?`page`:void 0,onClick:()=>f(e.key),type:`button`,children:[(0,V.jsx)(t,{size:17}),(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:e.label})})]},e.key)})})]}),(0,V.jsxs)(`main`,{className:`personal-settings-body`,children:[(0,V.jsx)(`header`,{className:`personal-settings-header`,children:(0,V.jsx)(`div`,{children:(0,V.jsx)(`h1`,{children:h.title})})}),d===`lark`?(0,V.jsx)(kb,{embedded:!0,focusGoalConnection:e,goals:t,initialGoalId:n,onChanged:i,onClose:a}):null,d===`machine`?(0,V.jsx)(ox,{}):null,d===`capabilities`?(0,V.jsx)($b,{goalId:n}):null,d===`appearance`?(0,V.jsxs)(`section`,{className:`personal-detail-card personal-appearance-settings`,children:[(0,V.jsx)(`small`,{children:u(`settings.workspaceDisplay`)}),(0,V.jsx)(`h3`,{children:u(`settings.appearance`)}),(0,V.jsxs)(`div`,{className:`personal-settings-choice-group`,role:`radiogroup`,"aria-label":u(`settings.workspaceTheme`),children:[(0,V.jsxs)(`button`,{"aria-checked":s===`loopx`,onClick:()=>o(`loopx`),role:`radio`,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-settings-theme-swatch is-loopx`}),(0,V.jsx)(`strong`,{children:u(`settings.themeLoopx`)})]}),(0,V.jsxs)(`button`,{"aria-checked":s===`paper`,onClick:()=>o(`paper`),role:`radio`,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-settings-theme-swatch is-paper`}),(0,V.jsx)(`strong`,{children:u(`settings.themeDefault`)})]}),(0,V.jsxs)(`button`,{"aria-checked":s===`brutal`,onClick:()=>o(`brutal`),role:`radio`,type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-settings-theme-swatch is-brutal`}),(0,V.jsx)(`strong`,{children:u(`settings.themeHighContrast`)})]})]})]}):null,d===`language`?(0,V.jsxs)(`section`,{className:`personal-settings-card`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`span`,{className:`personal-settings-icon`,children:(0,V.jsx)(bm,{size:18})}),(0,V.jsx)(`div`,{children:(0,V.jsx)(`h2`,{children:u(`settings.language`)})})]}),(0,V.jsx)(`div`,{"aria-label":u(`settings.language`),className:`personal-language-options`,role:`radiogroup`,children:m.map(e=>(0,V.jsxs)(`button`,{"aria-checked":c===e.value,className:c===e.value?`is-selected`:``,onClick:()=>l(e.value),role:`radio`,type:`button`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(`strong`,{children:e.label})}),c===e.value?(0,V.jsx)(em,{"aria-hidden":!0,size:17}):null]},e.value))})]}):null]})]})}var lx=`loopx-pw-theme`,ux=`loopx`;function dx(){try{let e=window.localStorage.getItem(lx);return e===`loopx`||e===`paper`||e===`brutal`?e:ux}catch{return ux}}function fx(e){try{window.localStorage.setItem(lx,e)}catch{}}function px({drawer:e,drawerMode:t=`panel`,drawerOpen:n,main:r,mobileSidebarOpen:i=!1,onCloseMobileSidebar:a,sidebar:o,theme:s=`loopx`}){let{t:c}=qi(),l=(0,B.useRef)(null),u=(0,B.useRef)(null);return(0,B.useEffect)(()=>{if(!i)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null;let e=l.current?.querySelectorAll(`button:not([disabled]), a[href], select:not([disabled]), textarea:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])`);e?.[0]?.focus();function t(t){if(t.key!==`Tab`||!e?.length)return;let n=e[0],r=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),r.focus()):!t.shiftKey&&document.activeElement===r&&(t.preventDefault(),n.focus())}return document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`keydown`,t),u.current?.focus(),u.current=null}},[i]),(0,V.jsxs)(`section`,{className:`personal-workspace-shell${n?` has-drawer`:``}${n&&t.startsWith(`inspector`)?` has-task-inspector`:``}${t===`inspector-full`?` is-task-inspector-full`:``}${i?` mobile-sidebar-open`:``}`,"data-pw-theme":s,children:[i?(0,V.jsx)(`button`,{"aria-hidden":!0,className:`personal-sidebar-backdrop`,onClick:a,tabIndex:-1,type:`button`}):null,(0,V.jsx)(`aside`,{"aria-label":i?c(`header.goalNavigation`):void 0,"aria-modal":i?!0:void 0,className:`personal-workspace-sidebar`,"data-workspace-sidebar":!0,ref:l,role:i?`dialog`:void 0,children:(0,V.jsxs)(`div`,{className:`personal-workspace-sidebar-inner`,children:[i?(0,V.jsxs)(`button`,{className:`personal-sr-only`,onClick:a,type:`button`,children:[c(`common.close`),` `,c(`header.goalNavigation`)]}):null,o]})}),(0,V.jsx)(`main`,{"aria-hidden":i||void 0,className:`personal-workspace-main`,inert:i||void 0,children:r}),n?(0,V.jsx)(`aside`,{className:`personal-workspace-drawer`,"data-context-drawer":!0,"data-drawer-mode":t,children:e}):null]})}function mx(e){let t=e.match(/(?:下一步|建议|行动项|待办)[::\s]*([^\n]+)/u),n=t?t[1]:e;n=n.replace(/```[\s\S]*?```/g,``).replace(/`([^`]+)`/g,`$1`).replace(/\[([^\]]+)\]\([^)]+\)/g,`$1`).replace(/[#*~_>]/g,``).replace(/^[-*•\d+.\s]+/u,``).replace(/^(好的|没问题|收到|建议如下|任务如下|分析如下|结论[::])[\s,,::]*/u,``);let r=(n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean)[0]||n).replace(/\s+/gu,` `).trim();return Array.from(r).slice(0,120).join(``)}function hx(e){let t=new Map;return e.forEach(e=>{let n=e.fields.find(e=>e.key===`todo_id`)?.value??``,r=[e.actionKind,e.goalId??``,n,e.title].join(`:`);t.set(r,e)}),[...t.values()]}function gx(e,t,n){if(!e)return n(`home.noFirstActivity`);let r=new Date(e);if(Number.isNaN(r.getTime()))return e;let i=new Date,a=new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r);return r.toDateString()===i.toDateString()?n(`home.todayAt`,{time:a}):new Intl.DateTimeFormat(t,{month:`numeric`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r)}function _x({goals:e,onSelectGoal:t,onRetry:n,systemHealth:r}){let{locale:i,t:a}=qi(),o=e.filter(e=>e.activationState===`active`),s=o.filter(e=>e.loadState===`error`).length,c=[{key:`needs_you`,label:a(`home.lane.needsYou`)},{key:`running`,label:a(`home.lane.running`)},{key:`observing`,label:a(`home.lane.observing`)},{key:`scheduled`,label:a(`home.lane.scheduled`)}],l=Object.fromEntries(c.map(e=>[e.key,[]])),u=[],d=[];e.filter(e=>!e.loadState).forEach(e=>{let t=hy(e);t===`history`?u.push(e):t===`stopped`?d.push(e):l[t].push(e)});let f=e=>(0,V.jsxs)(`button`,{className:`personal-home-goal-card`,"data-goal-state":e.loadState??e.state,"data-load-error":e.loadError,onClick:()=>t(e.goalId),type:`button`,children:[(0,V.jsxs)(`span`,{className:`personal-home-goal-meta`,children:[(0,V.jsx)(`i`,{}),e.agentLaneCount&&e.agentLaneCount>1?a(`header.workAgentCount`,{count:e.agentLaneCount}):e.agentLabel??e.agentId]}),(0,V.jsx)(`strong`,{children:e.title}),(0,V.jsx)(`p`,{children:e.loadError?a(`startup.error.${e.loadError}`):e.needsYou??e.nextSentence}),(0,V.jsxs)(`footer`,{children:[(0,V.jsx)(`span`,{children:e.loadState?a(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Ji(e.state,i)}),(0,V.jsx)(`small`,{title:e.latestActivity,children:e.loadState?``:e.latestActivity?gx(e.latestActivity,i,a):e.agentTodos.length?a(`home.taskCount`,{count:e.agentTodos.length}):a(`home.noActivity`)})]})]},e.goalId);return(0,V.jsxs)(`section`,{"aria-label":a(`home.workspace`),className:`personal-home-board`,children:[r&&(!r.ok||r.issues.length>0||r.freshnessWarning)?(0,V.jsxs)(`div`,{className:`personal-system-health-banner`,role:`alert`,children:[(0,V.jsxs)(`div`,{className:`personal-system-health-header`,children:[(0,V.jsx)(im,{size:15}),(0,V.jsx)(`strong`,{children:a(`home.systemHealth`,{summary:r.summary})}),r.freshnessWarning?(0,V.jsxs)(`small`,{children:[`(`,r.freshnessWarning,`)`]}):null]}),r.issues.length>0?(0,V.jsx)(`ul`,{className:`personal-system-health-issues`,children:r.issues.map((e,t)=>(0,V.jsx)(`li`,{children:e},t))}):null]}):null,o.some(e=>e.loadState)?(0,V.jsxs)(`section`,{className:`personal-home-lane`,"aria-live":`polite`,children:[(0,V.jsx)(`header`,{children:a(`startup.progress`,{loaded:o.filter(e=>!e.loadState).length,total:o.length})}),s?(0,V.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`status`,children:[(0,V.jsx)(`span`,{children:a(`startup.failedCount`,{count:s})}),(0,V.jsx)(`button`,{className:`min-h-11 rounded-md border px-3 py-2 text-sm`,onClick:n,type:`button`,children:a(`startup.retryFailed`)})]}):null,o.filter(e=>e.loadState).map(f)]}):null,(0,V.jsx)(`div`,{className:`personal-home-lanes`,children:c.map(e=>(0,V.jsxs)(`section`,{className:`personal-home-lane is-${e.key}`,"data-testid":`personal-home-lane-${e.key}`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`i`,{}),e.label]}),(0,V.jsx)(`b`,{children:l[e.key].length})]}),(0,V.jsx)(`div`,{className:`personal-home-lane-list`,children:l[e.key].length?l[e.key].map(f):(0,V.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.empty`)})})]},e.key))}),(0,V.jsxs)(`details`,{className:`personal-home-history`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(`span`,{children:a(`home.history`)}),(0,V.jsx)(`b`,{children:u.length}),(0,V.jsx)(`small`,{children:a(`home.completedGoals`)})]}),(0,V.jsx)(`div`,{children:u.length?u.map(f):(0,V.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.noCompletedGoals`)})})]}),d.length?(0,V.jsxs)(`details`,{className:`personal-home-history is-stopped`,children:[(0,V.jsxs)(`summary`,{children:[(0,V.jsx)(`span`,{children:a(`home.stopped`)}),(0,V.jsx)(`b`,{children:d.length}),(0,V.jsx)(`small`,{children:a(`home.preservedState`)})]}),(0,V.jsx)(`div`,{children:d.map(f)})]}):null]})}function vx({items:e,onSelect:t,reportState:n}){let{locale:r,t:i}=qi();return(0,V.jsxs)(`section`,{className:`personal-object-list personal-files-list`,"data-testid":`personal-goal-outputs`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsx)(`strong`,{children:i(`files.title`)}),(0,V.jsx)(`span`,{children:e.length})]}),n?.loading?(0,V.jsxs)(`p`,{className:`personal-object-list-state`,role:`status`,children:[(0,V.jsx)(Im,{className:`is-spinning`,size:14}),i(`files.loadingReports`)]}):null,n?.error?(0,V.jsxs)(`p`,{className:`personal-object-list-state is-error`,role:`alert`,children:[(0,V.jsx)(im,{size:14}),i(`files.reportLoadFailed`),`: `,n.error]}):null,!n?.loading&&!n?.error&&e.length===0?(0,V.jsxs)(`p`,{className:`personal-object-list-state`,children:[(0,V.jsx)(gm,{size:14}),i(`files.empty`)]}):null,e.map(e=>(0,V.jsxs)(`button`,{"data-output-kind":e.output.kind,onClick:()=>t({item:e.output,kind:`output`}),type:`button`,children:[(0,V.jsx)(`span`,{className:`personal-file-icon`,children:(0,V.jsx)(gm,{size:16})}),(0,V.jsx)(`strong`,{children:e.output.title}),e.output.report?(0,V.jsx)(`em`,{children:i(`files.reportDelta`,{added:e.output.report.addedCount,changed:e.output.report.changedCount})}):null,(0,V.jsx)(`p`,{children:e.output.summary??e.output.safePreview??e.output.kind??i(`files.emptySummary`)}),(0,V.jsx)(`small`,{title:e.output.createdAt,children:[e.output.goalTitle,e.output.kind===`report`?i(`files.verifiedReport`):null,e.output.todoId?`${i(`common.task`)} ${e.output.todoId}`:null,gx(e.output.createdAt,r,i)].filter(Boolean).join(` · `)})]},e.id))]})}function yx({agentLabel:e,messages:t,onClose:n,onDraftTask:r,onOpenConversation:i,title:a}){let{t:o}=qi(),s=t.reduce((e,t,n)=>t.role===`user`?n:e,0),c=t.slice(Math.max(0,s)).slice(-3),l=c.filter(e=>e.role===`assistant`&&!e.pending).at(-1);return(0,B.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),(0,V.jsxs)(`aside`,{"aria-label":o(`conversation.receipt`),className:`personal-manager-conversation-tray`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(Zp,{size:16}),(0,V.jsx)(`strong`,{children:a??o(`conversation.title`)}),(0,V.jsx)(`small`,{children:t.at(-1)?.pending?o(`conversation.replying`):o(`common.recently`)})]}),(0,V.jsxs)(`div`,{className:`personal-manager-conversation-actions`,children:[r&&l?(0,V.jsxs)(`button`,{className:`personal-manager-conversation-btn`,onClick:()=>r(l.text),title:o(`conversation.convertHint`),type:`button`,children:[(0,V.jsx)(Sm,{size:13}),(0,V.jsx)(`span`,{children:o(`conversation.toTask`)})]}):null,(0,V.jsx)(`button`,{className:`personal-manager-conversation-link`,onClick:i,type:`button`,children:o(`conversation.full`)}),n?(0,V.jsx)(`button`,{"aria-label":o(`conversation.close`),className:`personal-manager-conversation-close`,onClick:n,title:o(`conversation.close`),type:`button`,children:(0,V.jsx)($m,{size:14})}):null]})]}),(0,V.jsx)(`div`,{"aria-live":`polite`,className:`personal-manager-conversation-messages`,children:c.map(t=>(0,V.jsxs)(`article`,{className:`is-${t.role}`,children:[(0,V.jsx)(`strong`,{children:t.role===`user`?o(`common.you`):t.agentLabel??e??o(`header.manager`)}),(0,V.jsxs)(`div`,{className:`personal-manager-conversation-bubble`,children:[t.role===`user`?(0,V.jsx)(`p`,{children:t.text}):(0,V.jsx)(Ay,{text:t.text}),t.pending?(0,V.jsx)(`small`,{children:o(`conversation.agentPending`)}):null]})]},t.id))})]})}function bx({onClose:e,onOpenDetails:t,run:n}){let{t:r}=qi();return(0,V.jsxs)(`section`,{"aria-label":r(`session.record`),className:`personal-session-record`,children:[(0,V.jsxs)(`header`,{children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(Zp,{size:17}),r(`session.record`)]}),(0,V.jsx)(`button`,{"aria-label":r(`session.closeRecord`),onClick:e,type:`button`,children:(0,V.jsx)($m,{size:15})})]}),(0,V.jsx)(`div`,{children:(0,V.jsx)(`strong`,{children:n.title})}),(0,V.jsxs)(`dl`,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Agent`}),(0,V.jsx)(`dd`,{children:n.agentLabel})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:r(`common.status`)}),(0,V.jsx)(`dd`,{children:Yi(n.sessionStatus??n.status,r)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Session`}),(0,V.jsx)(`dd`,{title:n.sessionId,children:n.sessionId})]})]}),(0,V.jsx)(`button`,{className:`personal-secondary-action`,onClick:t,type:`button`,children:r(`session.details`)})]})}function xx(e,t,n){let r=[];if(t===null)return e.userTodos.slice(0,4).forEach(t=>r.push({attention:{...t,goalTitle:t.goalTitle??my(e,t.goalId)},id:`attention:${t.todoId}`,kind:`attention`})),e.goals.filter(e=>hy(e)===`running`).slice(0,4).forEach(e=>r.push({id:`run:${e.goalId}`,kind:`run`,run:{agentId:e.agentId,agentLabel:e.agentLabel??e.agentId,completedSteps:e.doneTodoCount??e.agentTodos.filter(e=>e.done).length,goalId:e.goalId,goalTitle:e.title,latestActivity:e.agentSentence,runId:`goal:${e.goalId}`,status:`running`,title:e.nextSentence,totalSteps:Math.max((e.doneTodoCount??0)+e.agentTodos.filter(e=>!e.done).length,1)}})),r;let i=e.goals.find(e=>e.goalId===t);if(!i)return r;if(i.needsYou){let t=e.userTodos.find(e=>e.goalId===i.goalId);r.push({attention:t?{...t,goalTitle:i.title}:{blocking:i.needsYouBlocking??!1,goalId:i.goalId,goalTitle:i.title,text:i.needsYou,todoId:`${i.goalId}:attention`},id:`attention:${i.goalId}`,kind:`attention`})}r.push({id:`run:${i.goalId}`,kind:`run`,run:{agentId:i.agentId,agentLabel:i.agentLabel??i.agentId,completedSteps:i.doneTodoCount??i.agentTodos.filter(e=>e.done).length,goalId:i.goalId,goalTitle:i.title,latestActivity:i.agentSentence,runId:`goal:${i.goalId}`,status:i.state===`推进中`?`running`:i.state===`需修复`?`failed`:`waiting`,title:i.nextSentence,totalSteps:Math.max((i.doneTodoCount??0)+i.agentTodos.filter(e=>!e.done).length,1)}}),i.agentTodos.filter(e=>e.taskClass===`continuous_monitor`).forEach(t=>{let a=e.timeline?.find(e=>e.kind===`run`&&e.run.goalId===i.goalId&&e.run.todoId===t.todoId&&!!e.run.sessionId);r.push({id:`schedule:${i.goalId}:${t.todoId}`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:a?[{label:a.run.latestActivity||a.run.title,runId:a.run.runId,status:a.run.status===`waiting`||a.run.status===`queued`?`running`:a.run.status,timestamp:i.latestActivity||n(`common.recently`)}]:[],goalId:i.goalId,label:t.text,schedule:t.evidence??n(`schedule.summary`),scheduleId:t.todoId,scheduleKind:`monitor`,sessionId:a?.run.sessionId,status:t.done||t.status===`paused`?`paused`:`active`,stopCondition:n(`drawer.scheduleDefaultStop`),target:t.text,timezone:`Asia/Shanghai`}})});let a=e.timeline?.find(e=>e.kind===`proposal`&&e.proposal.actionKind===`heartbeat.bind`&&e.proposal.goalId===i.goalId);if(a){let e=e=>a.proposal.fields.find(t=>t.key===e)?.value;r.push({id:`schedule:${i.goalId}:heartbeat`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:[],goalId:i.goalId,label:`${n(`schedule.heartbeat`)} · ${i.title}`,nextRunAt:n(`drawer.schedulePending`),notificationRule:n(`drawer.scheduleDefaultNotification`),schedule:e(`cadence`)??n(`schedule.summary`),scheduleId:`${i.goalId}:heartbeat`,scheduleKind:`heartbeat`,status:a.proposal.status===`applied`?`active`:`draft`,stopCondition:e(`stop_condition`)??n(`drawer.scheduleDefaultStop`),timezone:e(`timezone`)??`Asia/Shanghai`}})}return r}function Sx(e){return e===`preview_ready`?`ready`:e===`cancelled`?`draft`:e===`failed`?`error`:e}function Cx(e,t){let n={agent_id:t(`proposal.field.agentId`),cadence:t(`proposal.field.cadence`),completion_criteria:t(`proposal.field.completionCriteria`),execution_boundary:t(`proposal.field.executionBoundary`),goal_id:t(`proposal.field.goalId`),heartbeat:t(`proposal.field.heartbeat`),initial_todos:t(`proposal.field.initialTodos`),objective:t(`proposal.field.objective`),operation:t(`proposal.field.operation`),permission:t(`proposal.field.permission`),reason:t(`proposal.field.reason`),stop_condition:t(`proposal.field.stopCondition`),target:t(`proposal.field.target`),timezone:t(`proposal.field.timezone`),title:t(`proposal.field.title`),workspace_ref:t(`proposal.field.workspace`)},r=[`title`,`objective`,`completion_criteria`,`execution_boundary`,`permission`,`agent_id`,`workspace_ref`,`initial_todos`,`heartbeat`,`stop_condition`,`goal_id`];return Object.entries(e).sort(([e],[t])=>{let n=r.indexOf(e),i=r.indexOf(t);return(n<0?r.length:n)-(i<0?r.length:i)}).slice(0,10).map(([e,r])=>({key:e,label:n[e]??e.replaceAll(`_`,` `),value:e===`workspace_ref`?r===`current`?t(`proposal.workspace.current`):t(`proposal.workspace.named`,{workspace:String(r??`current`)}):Array.isArray(r)?r.join(` · `):typeof r==`object`&&r?JSON.stringify(r):String(r??`—`)}))}function wx(e){if(e.action_kind!==`goal.lifecycle`)return;let t=e.normalized_parameters.operation;return t===`stop`||t===`resume`||t===`delete`?t:void 0}function Tx(e,t){let n=wx(e),r=dy(e),i=typeof e.normalized_parameters.title==`string`?e.normalized_parameters.title:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:``,a=typeof e.normalized_parameters.target==`string`?e.normalized_parameters.target:``,o=e.action_kind===`goal.create`?t(`proposal.summary.goalCreate`,{title:i}):e.action_kind===`heartbeat.bind`?t(`proposal.summary.heartbeat`):e.action_kind===`monitor.create`?t(`proposal.summary.monitor`,{target:a}):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.summary.lifecycleStop`,{title:i}):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.summary.lifecycleDelete`,{title:i}):e.action_kind===`goal.lifecycle`?t(`proposal.summary.lifecycleResume`,{title:i}):e.summary;return{actionKind:e.action_kind,reviewPlan:r,fields:Cx(e.normalized_parameters,t),goalId:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:void 0,impact:e.action_kind===`goal.create`?t(`proposal.impact.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.impact.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.impact.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.impact.lifecycleResume`):e.permission_classification===`protected`?t(`proposal.impact.protected`):t(`proposal.impact.default`),previewId:e.proposal_id,lifecycleOperation:n,gate:e.gate?{kind:String(e.gate.kind??`protected_action`),nextAction:typeof e.gate.next_action==`string`?e.gate.next_action:void 0,summary:String(e.gate.summary??t(`proposal.gate.default`))}:void 0,primaryLabel:e.action_kind===`goal.create`?t(`proposal.primary.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.primary.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.primary.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.primary.lifecycleResume`):e.action_kind===`todo.create`&&e.normalized_parameters.start_execution===!0?t(`proposal.primary.todoStart`):t(`proposal.primary.apply`),status:e.status===`applied`&&r.interaction!==`completed`?`error`:Sx(e.status),title:o}}function Ex(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,42);if(t)return t;let n=2166136261;for(let t of e)n^=t.codePointAt(0)??0,n=Math.imul(n,16777619);return`goal-${(n>>>0).toString(36)}`}function Dx(e,t){let n=e.match(/[「“"]([^」”"]{2,80})[」”"]/u)?.[1];return n?n.trim():e.replace(/^(请|帮我|我想|给我|创建|新建|设置|please|i want to|create|set up)+/iu,``).replace(/(一个|新的)?\s*(goal|目标)/giu,``).replace(/[,。!?].*$/u,``).trim().slice(0,80)||t(`goal.defaultTitle`)}function Ox(e,t){for(let n of e.split(/\r?\n/u)){let e=n.trim();for(let n of t){let t=e.match(RegExp(`^${n.replace(/[.*+?^${}()|[\]\\]/gu,`\\$&`)}\\s*[::]\\s*(.*)$`,`iu`));if(t?.[1]?.trim())return t[1].trim()}}return``}function kx(e,t){let n=Ox(e,[`目标`,`Objective`]),r=Ox(e,[`完成标准`,`Completion criteria`]),i=Ox(e,[`执行边界(可选)`,`执行边界`,`边界`,`Execution boundary (optional)`,`Execution boundary`,`Boundary`]),a=(n||Dx(e,t)).split(/[。;;\n]/u)[0].trim().slice(0,80)||t(`goal.defaultTitle`),o=[n||a,r?t(`goal.objectiveCompletion`,{criteria:r}):``,i?t(`goal.objectiveBoundary`,{boundary:i}):``].filter(Boolean).join(` -`),s=/(只读|不调用外部工具|不修改(?:仓库|代码|状态)|read.?only|do not (?:call|use) external tools|do not modify (?:repositories|repository|code|state))/iu.test(i||e);return{completionCriteria:r,executionBoundary:i,initialTodos:r?[t(`goal.initialTodo`,{criteria:r})]:[],objective:o,permission:s?`read_only`:`workspace_write_on_confirmation`,title:a}}function Ax(e){let t=e.match(/(?:每|every)\s*(\d{1,3})\s*(?:分钟|minutes?)/iu)?.[1];if(t)return`${t}m`;let n=e.match(/(?:每|every)\s*(\d{1,2})\s*(?:小时|hours?)/iu)?.[1];return n?`${n}h`:/每小时|every hour|hourly/iu.test(e)?`1h`:(/每天|每日|早上|上午|daily|every day/iu.test(e),`1d`)}function jx(e,t){return/(每周|星期|周[一二三四五六日天]|weekly|every\s+(?:mon|tues|wednes|thurs|fri|satur|sun)day|\d{1,2}\s*[::]\s*\d{2})/iu.test(e)?t(`schedule.unsupportedCalendar`):null}function Mx(e,t){return Ox(e,[`检查内容`,`监控内容`,`目标`,`Check target`,`Monitor target`,`Target`])||e.replace(/^(?:为当前 Goal |for the current Goal )?(?:添加|配置|创建|add|configure|create)?\s*(?:定时检查|监控|scheduled check|monitor)[::]?/iu,``).split(/\r?\n/u)[0].trim()||t(`schedule.defaultTarget`)}function Nx(e){return/(mr|pr).{0,8}(合并|merge)/iu.test(e)?`pr_merged`:/发布完成|上线完成|release (?:is )?complete|deployment (?:is )?complete/iu.test(e)?`release_complete`:`goal_complete`}function Px(e,t){let n=e.toLowerCase();return t.find(e=>n.includes(e.agentId.toLowerCase())||n.includes(e.label.toLowerCase()))}function Fx(e){let t=Ox(e,[`标题`,`任务标题`,`Todo 标题`]),n=Ox(e,[`内容`,`任务内容`,`Todo 内容`]);if(t)return[t,n].filter(Boolean).join(`:`).slice(0,400);let r=e.match(/[「“"]([^」”"]{2,200})[」”"]/u)?.[1];return r?r.trim():e.replace(/^(请|帮我|给我|为当前 Goal |新增|新建|创建|添加|加上|加一个|记一个)+/u,``).replace(/^(一个\s*)?(普通\s*)?(todo|待办|任务)(?:\s*到\s*Tasks?)?[::\s]*/iu,``).replace(/[。;;,,]\s*(?:不要|不需要|无需|禁止|别|暂不).{0,80}(?:heartbeat|心跳|定时|监控|执行).*$/iu,``).replace(/[,,]\s*(并且|然后|再)?\s*(交给|分配给|让).+$/u,``).replace(/\s*(交给|分配给|让)\s+.+$/u,``).trim().slice(0,400)||`推进当前 Goal 的下一项工作`}var Ix=new Set([`image/png`,`image/jpeg`,`image/webp`,`image/gif`]),Lx=5242880,Rx=4;function zx(e,t){return new Promise((n,r)=>{let i=new FileReader;i.onerror=()=>r(Error(t(`composer.imageReadError`,{name:e.name}))),i.onload=()=>n({dataUrl:String(i.result??``),id:crypto.randomUUID(),mimeType:e.type,name:e.name,size:e.size}),i.readAsDataURL(e)})}function Bx({agents:e=[{agentId:`codex`,available:!0,capability:`代码与项目执行`,label:`Codex`}],callbacks:t={},goalArchiveLoadState:n={error:null,phase:`ready`},model:r,readOnly:i=!1,selectedAgentId:a,selectedGoalId:o,statusSourceControl:s}){let{locale:c,t:l}=qi(),[u,d]=(0,B.useState)(o??null),[f,p]=(0,B.useState)(a??e.find(e=>e.available)?.agentId??`codex`),[m,h]=(0,B.useState)(null),[g,_]=(0,B.useState)(!1),[v,y]=(0,B.useState)(null),[b,x]=(0,B.useState)({}),[S,C]=(0,B.useState)(`chat`),[w,T]=(0,B.useState)(!1),[E,D]=(0,B.useState)(!1),[O,ee]=(0,B.useState)(!1),[te,ne]=(0,B.useState)(()=>{try{let e=window.sessionStorage.getItem(`loopx-pw-composer-drafts`),t=e?JSON.parse(e):{};return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}),[k,A]=(0,B.useState)(!1),[j,M]=(0,B.useState)([]),[N,P]=(0,B.useState)(null),[F,re]=(0,B.useState)(null),[ie,I]=(0,B.useState)(()=>new Set),[ae,L]=(0,B.useState)(()=>new Set),[oe,se]=(0,B.useState)(`idle`),[ce,le]=(0,B.useState)([]),[ue,de]=(0,B.useState)(!1),[R,fe]=(0,B.useState)(dx),[pe,me]=(0,B.useState)({}),[he,ge]=(0,B.useState)([]),_e=(0,B.useRef)(!1),ve=(0,B.useRef)(NaN),ye=(0,B.useRef)(null),be=(0,B.useRef)(null),xe=(0,B.useRef)(null),Se=(0,B.useRef)(new Set),Ce=(0,B.useRef)(new Set),[we,Te]=(0,B.useState)(null),z=o===void 0?u:o,Ee=a??f,De=`${z??`manager`}:${Ee}`,Oe=te[De]??``;(0,B.useEffect)(()=>{M([]),P(null)},[De]);function ke(e,t){ne(n=>{let r={...n};t?r[e]=t:delete r[e];try{window.sessionStorage.setItem(`loopx-pw-composer-drafts`,JSON.stringify(r))}catch{}return r})}function Ae(e){ke(De,e)}function je(e){let t=te[De]?.trimEnd();Ae(t?`${t}\n${e}`:e),window.requestAnimationFrame(()=>ye.current?.focus())}(0,B.useEffect)(()=>{let e=ye.current;e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,120)}px`)},[Oe]);let Me=(0,B.useMemo)(()=>r.goals.map(e=>{let t=pe[e.goalId];return t?{...e,repository:{branch:t.branch,identity:t.identity,label:t.label,readOnly:!0}}:e}),[pe,r.goals]),Ne=(0,B.useMemo)(()=>Me.filter(e=>hy(e)===`needs_you`).length,[Me]),Pe=(0,B.useMemo)(()=>Me.filter(e=>hy(e)===`needs_you`&&(e.needsYouBlocking||e.state===`等你`)).length,[Me]),H=Me.find(e=>e.goalId===z)??null,Fe=m?.kind===`settings`,Ie=z,Le=(0,B.useMemo)(()=>{let e=Object.values(b).filter(e=>e.actionKind===`heartbeat.bind`&&e.goalId&&e.status===`applied`).map(e=>({id:`schedule:${e.goalId}:heartbeat`,kind:`schedule`,schedule:{agentId:Ee,executionHistory:[],goalId:e.goalId,label:e.title,nextRunAt:l(`drawer.schedulePending`),notificationRule:l(`drawer.scheduleDefaultNotification`),schedule:e.fields.find(e=>e.key===`cadence`)?.value??l(`schedule.summary`),scheduleId:`${e.goalId}:heartbeat`,scheduleKind:`heartbeat`,status:e.status===`applied`?`active`:`draft`,stopCondition:e.fields.find(e=>e.key===`stop_condition`)?.value??l(`drawer.scheduleDefaultStop`),timezone:e.fields.find(e=>e.key===`timezone`)?.value??`Asia/Shanghai`}})),t=[...xx(r,Ie,l),...r.timeline??[],...e,...hx(Object.values(b)).filter(e=>e.actionKind!==`heartbeat.bind`||e.status!==`applied`).map(e=>({id:`proposal:${e.previewId}`,kind:`proposal`,proposal:e}))];return[...new Map(t.map(e=>[e.id,e])).values()].filter(e=>e.kind!==`proposal`||![`stale`,`error`].includes(e.proposal.status)||ce.includes(e.proposal.previewId)).filter(e=>!z||e.kind===`message`?!0:e.kind===`proposal`?!e.proposal.goalId||e.proposal.goalId===z:e.kind===`attention`?e.attention.goalId===z:e.kind===`run`?e.run.goalId===z:e.kind===`schedule`?e.schedule.goalId===z:e.output.goalId===z)},[Ie,r,b,Ee,z,ce,l]),Re=(0,B.useMemo)(()=>v?Le.filter(e=>e.kind===`message`?!0:e.kind===`run`?e.run.runId===v.runId:e.kind===`output`&&e.output.runId===v.runId):Le,[v,Le]);(0,B.useEffect)(()=>{if(!v)return;let e=Le.find(e=>e.kind===`run`&&e.run.runId===v.runId);!e||e.kind!==`run`||JSON.stringify({completedSteps:v.completedSteps,latestActivity:v.latestActivity,messages:v.sessionMessages,sessionStatus:v.sessionStatus,status:v.status,totalSteps:v.totalSteps})!==JSON.stringify({completedSteps:e.run.completedSteps,latestActivity:e.run.latestActivity,messages:e.run.sessionMessages,sessionStatus:e.run.sessionStatus,status:e.run.status,totalSteps:e.run.totalSteps})&&y(e.run)},[v,Le]);let ze=(0,B.useMemo)(()=>Le.flatMap(e=>e.kind===`message`?[e.message]:[]),[Le]),Be=(0,B.useMemo)(()=>H?Le.flatMap(e=>e.kind===`message`?[e.message]:[]):[],[Le,H]);(0,B.useEffect)(()=>{H||w||ze.some(e=>e.pending)&&D(!0)},[w,ze,H]),(0,B.useEffect)(()=>{!H||S===`chat`||Be.some(e=>e.pending)&&ee(!0)},[Be,H,S]);let Ve=(0,B.useMemo)(()=>Le.filter(e=>e.kind===`message`||e.kind===`proposal`&&ce.includes(e.proposal.previewId)),[Le,ce]),He=Ve[Ve.length-1],Ue=He?.kind===`message`?He.message.text.length:0;(0,B.useEffect)(()=>{if(!w||!be.current)return;let e=window.requestAnimationFrame(()=>{be.current&&(be.current.scrollTop=be.current.scrollHeight)});return()=>window.cancelAnimationFrame(e)},[Ve.length,w,Ue]);let We=(0,B.useMemo)(()=>{if(m?.kind===`settings`)return null;if(m?.kind===`attention`)return{kind:`attention`,item:Gd(m.item,r.attentionHistory??r.userTodos)};if(m?.kind===`goal`){let e=Me.find(e=>e.goalId===m.item.goalId);return e?{item:e,kind:`goal`}:m}if(m?.kind!==`run`)return m;let e=Le.find(e=>e.kind===`run`&&e.run.runId===m.item.runId);return e?{item:e.run,kind:`run`}:m},[Le,m,Me,r.attentionHistory,r.userTodos]);(0,B.useEffect)(()=>{if(i){me({}),ge([]);return}let e=!1;return Promise.all([Fg(),Kg()]).then(([t,n])=>{e||(me(Object.fromEntries(t.map(e=>[e.goal_id,e.repository]))),ge(n))}).catch(()=>{}),()=>{e=!0}},[i]),(0,B.useEffect)(()=>{if(!ue)return;function e(e){e.key===`Escape`&&de(!1)}return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[ue]),(0,B.useEffect)(()=>{if(z||!Le.length)return;if(!_e.current){_e.current=!0;try{ve.current=Date.parse(window.localStorage.getItem(`loopx-pw-last-visit`)??``),window.localStorage.setItem(`loopx-pw-last-visit`,new Date().toISOString())}catch{ve.current=NaN}}let e=ve.current,t=Le.filter(e=>e.kind===`run`).map(e=>e.run),n=t=>{let n=Date.parse(t??``);return!Number.isNaN(e)&&!Number.isNaN(n)&&n>e},r={attention:Ne,done:t.filter(e=>e.status===`completed`&&n(e.latestActivity)).length,failed:t.filter(e=>(e.status===`failed`||e.status===`interrupted`)&&n(e.latestActivity)).length};Te(e=>e?.attention===r.attention&&e.done===r.done&&e.failed===r.failed?e:r)},[Le,Ne,z]),(0,B.useEffect)(()=>{if(i){x({});return}let e=!1;return jh(z?{goalId:z}:{contextKind:`manager`}).then(t=>{if(e)return;let n=Object.fromEntries(t.filter(e=>[`ready`,`gated`,`deferred`,`applying`].includes(e.status)).map(e=>{let t=Tx(e,l);return[t.previewId,t]}));x(e=>({...e,...n}))}).catch(()=>{}),()=>{e=!0}},[i,z,l]);async function Ge(e,n={}){if(i)throw Error(l(`source.readOnlyWriteError`));let r;try{r=t.onPreviewAction?await t.onPreviewAction(e):Tx(await kh(e),l)}catch(t){if(!(t instanceof Th)||t.payload.error_code!==`action_preview_gate`)throw t;let n=t.payload.gate&&typeof t.payload.gate==`object`?t.payload.gate:{},i=(Array.isArray(n.candidates)?n.candidates:[]).flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.workspace_ref==`string`&&typeof t.label==`string`?[{label:t.label,workspaceRef:t.workspace_ref}]:[]}),a=String(n.kind??`workspace_selection_required`),o=a===`agent_binding_required`||a===`agent_identity_selection_required`;r={actionKind:e.actionKind,fields:i.map(e=>({key:`workspace_ref:${e.workspaceRef}`,label:e.label,value:e.workspaceRef})),gate:{kind:a,nextAction:typeof n.next_action==`string`?n.next_action:void 0,summary:String(n.summary??l(`proposal.workspaceGate.defaultSummary`))},impact:l(o?`proposal.workspaceGate.agentImpact`:`proposal.workspaceGate.selectionImpact`),previewId:`workspace-choice-${Date.now().toString(36)}`,sourceRequest:e,status:`gated`,title:l(o?`proposal.workspaceGate.agentTitle`:`proposal.workspaceGate.selectionTitle`),workspaceCandidates:i}}return le(e=>e.includes(r.previewId)?e:[...e,r.previewId]),x(e=>({...e,[r.previewId]:r})),n.select!==!1&&h({item:r,kind:`proposal`}),r}function Ke(){et(null),ke(`manager:${Ee}`,l(`composer.createGoalTemplate`)),window.requestAnimationFrame(()=>ye.current?.focus())}async function qe(e,n){de(!1);let r={delete:`Deleted from the owner workspace`,resume:`Resumed from the owner workspace`,stop:`Stopped from the owner workspace`},i={delete:l(`proposal.summary.lifecycleDelete`,{title:e.title}),resume:l(`proposal.summary.lifecycleResume`,{title:e.title}),stop:l(`proposal.summary.lifecycleStop`,{title:e.title})},a=null,o=!1;try{if(n===`stop`){if(Se.current.has(e.goalId))return;Se.current.add(e.goalId),I(new Set(Se.current)),h(null),a={goalId:e.goalId,next:`stopped`,optimisticApplied:!0,previous:e.activationState},re(l(`feedback.applying`,{title:i.stop})),t.onGoalActivationStateChange?.(e.goalId,`stopped`)}if(t.onExecuteGoalLifecycle){if(n===`delete`)throw Error(`The selected status source does not authorize Goal deletion.`);let a=await t.onExecuteGoalLifecycle({goalId:e.goalId,operation:n,reason:r[n]});if(!a.projectionVerified)throw Error(`Goal lifecycle projection did not verify.`);o=!0,t.onGoalActivationStateChange?.(e.goalId,a.activationState),re(l(`feedback.completed`,{title:i[n]})),n===`stop`&&et(null),await(t.onReconcileStatus??t.onRefresh)?.();return}let s=await Ge({actionKind:`goal.lifecycle`,context:{kind:`goal_directory`,goal_id:e.goalId},idempotencyKey:`workspace-goal-${n}-${e.goalId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,operation:n,reason:r[n]},summary:i[n]},{select:n!==`stop`});if(s.goalId!==e.goalId||s.lifecycleOperation!==n)throw h(null),Error(l(`actionReview.targetChanged`));n===`stop`&&(s.reviewPlan?.interaction===`direct`?(o=!0,await Ze(s,{lifecycleProjection:a??void 0,presentation:`feedback`})):(a&&t.onGoalActivationStateChange?.(a.goalId,a.previous),re(s.gate?l(`feedback.gateRequired`,{summary:s.gate.summary}):l(`feedback.notCompleted`,{status:s.status})),h({item:s,kind:`proposal`})))}catch(e){a&&!o&&t.onGoalActivationStateChange?.(a.goalId,a.previous),re(l(`feedback.executionFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{n===`stop`&&(Se.current.delete(e.goalId),I(new Set(Se.current)))}}function Je(e,t){Ae(l(t?e===`heartbeat`?`composer.heartbeatTemplate`:`composer.monitorTemplate`:e===`heartbeat`?`composer.heartbeatTemplateWithoutGoal`:`composer.monitorTemplateWithoutGoal`)),h(null),window.requestAnimationFrame(()=>ye.current?.focus())}async function Ye(e,n,r=``){let i=await t.onRequestScheduleConfig?.(e,n);if(i){le(e=>e.includes(i.previewId)?e:[...e,i.previewId]),x(e=>({...e,[i.previewId]:i})),h({item:i,kind:`proposal`});return}if(!n){Ae(l(e===`heartbeat`?`composer.heartbeatGoalQuestion`:`composer.monitorGoalQuestion`));return}let a=Date.now().toString(36);await Ge({actionKind:e===`heartbeat`?`heartbeat.bind`:`monitor.create`,context:{kind:`schedule`,goal_id:n},idempotencyKey:`workspace-${e}-${n}-${a}`,normalizedParameters:e===`heartbeat`?{agent_id:Ee,cadence:Ax(r),goal_id:n,stop_condition:Nx(r),timezone:`Asia/Shanghai`}:{agent_id:Ee,cadence:Ax(r),goal_id:n,stop_condition:Nx(r),target:Mx(r,l),target_key:`goal-${n}`,timezone:`Asia/Shanghai`},summary:e===`heartbeat`?l(`proposal.summary.heartbeat`):l(`proposal.summary.monitor`,{target:Mx(r,l)})})}async function Xe(e){if(!Ce.current.has(e.todoId)){Ce.current.add(e.todoId),L(new Set(Ce.current)),re(l(`feedback.preparingPreview`,{title:e.text}));try{await Ge({actionKind:`todo.update`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-${e.todoId}-complete-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,operation:`complete`,todo_id:e.todoId},summary:l(`tasks.markComplete`,{name:e.text})}),re(null)}catch(e){re(l(`feedback.previewFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{Ce.current.delete(e.todoId),L(new Set(Ce.current))}}}async function Ze(e,n={}){if(e.reviewPlan&&!e.reviewPlan.canApply)return;let i=n.presentation!==`feedback`,a=e.actionKind===`goal.lifecycle`&&e.goalId&&(e.lifecycleOperation===`stop`||e.lifecycleOperation===`resume`)?{goalId:e.goalId,next:e.lifecycleOperation===`stop`?`stopped`:`active`,optimisticApplied:!1,previous:r.goals.find(t=>t.goalId===e.goalId)?.activationState??(e.lifecycleOperation===`stop`?`active`:`stopped`)}:null,o=n.lifecycleProjection??a;re(l(`feedback.applying`,{title:e.title}));let s={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:`pending`,reason:`apply_pending`,canApply:!1}:void 0,status:`applying`};x(t=>({...t,[e.previewId]:s})),i&&h({item:s,kind:`proposal`}),o&&!o.optimisticApplied&&t.onGoalActivationStateChange?.(o.goalId,o.next);try{if(t.onApplyProposal){await t.onApplyProposal(e);let n={...e,status:`applied`};if(x(t=>({...t,[e.previewId]:n})),i&&h({item:n,kind:`proposal`}),re(l(`feedback.completed`,{title:e.title})),e.actionKind===`goal.lifecycle`){(e.lifecycleOperation===`stop`||e.lifecycleOperation===`delete`)&&et(null),e.lifecycleOperation===`delete`&&e.goalId&&t.onGoalDeleted?.(e.goalId);let n=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>n?.()).catch(()=>void 0)}return}let n=await Mh(e.previewId);if(n.proposal.proposal_id!==e.previewId||n.proposal.action_kind!==e.actionKind||e.actionKind===`goal.lifecycle`&&(n.proposal.normalized_parameters.goal_id!==e.goalId||wx(n.proposal)!==e.lifecycleOperation))throw new Th(l(`actionReview.targetChanged`),{error_code:`action_response_mismatch`});let r=Tx(n.proposal,l);if(x(t=>({...t,[e.previewId]:r})),i&&h({item:r,kind:`proposal`}),r.reviewPlan?.interaction!==`completed`){o&&t.onGoalActivationStateChange?.(o.goalId,o.previous),h({item:r,kind:`proposal`}),re(n.proposal.status===`stale`?l(`feedback.stale`):l(`actionReview.${r.reviewPlan.reason}`));return}if(re(l(`feedback.completed`,{title:r.title})),r.actionKind===`todo.create`&&await t.onRefresh?.(),r.actionKind===`goal.lifecycle`&&(r.lifecycleOperation===`stop`||r.lifecycleOperation===`delete`)&&et(null),r.actionKind===`goal.lifecycle`&&r.lifecycleOperation===`delete`&&r.goalId&&t.onGoalDeleted?.(r.goalId),r.actionKind===`goal.lifecycle`){let e=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>e?.()).catch(()=>void 0)}}catch(n){if(o&&t.onGoalActivationStateChange?.(o.goalId,o.previous),n instanceof Th&&n.payload.error_code===`protected_action`){let r=n.payload.gate,i=r&&typeof r==`object`?r:{},a={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:`gated`,reason:`authority_gate`,canApply:!1}:void 0,gate:{kind:String(i.kind??`protected_action`),nextAction:typeof i.next_action==`string`?i.next_action:void 0,summary:String(i.summary??n.message)},status:`gated`};x(t=>({...t,[e.previewId]:a})),h({item:a,kind:`proposal`}),re(l(`feedback.gateRequired`,{summary:a.gate.summary})),e.actionKind===`goal.create`&&e.goalId&&(t.onRefresh?.(),et(e.goalId));return}let r=n instanceof Th&&fy(n.payload),i=n instanceof Th&&n.payload.error_code===`action_response_mismatch`,a={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:r?`refresh`:`repair`,reason:i?`readback_unverified`:r?`stale_proposal`:`apply_failed`,canApply:!1}:void 0,errorMessage:n instanceof Error?n.message:String(n),status:r?`stale`:`error`};x(t=>({...t,[e.previewId]:a})),h({item:a,kind:`proposal`}),re(l(`feedback.executionFailed`,{error:a.errorMessage}))}}let Qe={...t,onOpenRunSession:async e=>{e.goalId!==z&&et(e.goalId),C(`chat`),await t.onOpenRunSession?.(e),y(e),h(null)},onOpenGoal:e=>{et(e);let n=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>n?.()).catch(()=>{re(l(`feedback.goalRefreshFailed`))})},onOpenGoalView:e=>{C(e),e===`chat`&&y(null),h(null)},onOpenOutput:e=>{e.goalId!==z&&et(e.goalId),C(`files`),t.onOpenOutput?.(e)},onApplyProposal:Ze,onCancelProposal:async e=>{h(null),x(t=>{let n={...t};return delete n[e.previewId],n});try{t.onCancelProposal?.(e),t.onCancelProposal||await Nh(e.previewId)}catch(t){x(t=>({...t,[e.previewId]:e})),re(l(`feedback.cancelFailed`,{error:t instanceof Error?t.message:String(t)}))}},onTransitionProposal:async(e,t)=>{let n=Tx(await Ph(e.previewId,t),l);le(e=>e.includes(n.previewId)?e:[...e,n.previewId]),x(r=>{let i={...r};return t===`regenerate`&&delete i[e.previewId],i[n.previewId]=n,i}),h({item:n,kind:`proposal`})},onSelectWorkspaceCandidate:async(e,t)=>{e.sourceRequest&&(x(t=>{let n={...t};return delete n[e.previewId],n}),await Ge({...e.sourceRequest,idempotencyKey:`${e.sourceRequest.idempotencyKey}-${t}`,normalizedParameters:{...e.sourceRequest.normalizedParameters,workspace_ref:t}}))},onPreviewAction:Ge,onRequestScheduleConfig:(e,t)=>Je(e,t),onOpenNotificationSettings:e=>h({goalId:e,kind:`settings`,tab:`lark`}),onFetchNotificationTargets:()=>rg(),onSetupGoalChannel:e=>ag(e),onToggleGoalAutoNotify:e=>og(e),onUpdateSchedule:async(e,t)=>{let n=Date.now().toString(36),r=e.scheduleKind===`heartbeat`;await Ge({actionKind:r?`heartbeat.bind`:`monitor.update`,context:{kind:`schedule`,goal_id:e.goalId},idempotencyKey:`workspace-monitor-${e.scheduleId}-${t}-${n}`,normalizedParameters:{agent_id:e.agentId??Ee,...!r&&t===`run_now`?{endpoint_id:Ee}:{},...t===`edit`?{cadence:`2h`,...r?{timezone:e.timezone??`Asia/Shanghai`}:{}}:{},goal_id:e.goalId,operation:t,...!r&&t===`run_now`&&e.sessionId?{session_id:e.sessionId}:{},...r?{}:{todo_id:e.scheduleId}},summary:t===`pause`?`暂停自动运行:${e.label}`:t===`resume`?`恢复自动运行:${e.label}`:t===`run_now`?`立即运行:${e.label}`:t===`stop`?`停止自动运行:${e.label}`:`编辑自动运行生命周期:${e.label}`})}},$e=i?{onOpenGoal:Qe.onOpenGoal,onOpenGoalView:Qe.onOpenGoalView,onOpenOutput:Qe.onOpenOutput}:Qe;function et(e){d(e),T(!1),D(!1),ee(!1),y(null),h(null),C(`tasks`),de(!1),t.onSelectGoal?.(e)}function tt(e){p(e),t.onSelectAgent?.(e)}function nt(e){fe(e),fx(e)}async function rt(n){let r=n?[]:j,i=(n??Oe).trim()||(r.length?l(`composer.imageAnalysisPrompt`):``);if(!(!i||k)){n||(Ae(``),M([])),P(null),A(!0);try{if(r.length){z?S!==`chat`&&ee(!0):D(!0);let e=await t.onSendMessage?.(i,Ee,z,r);e&&await Ge(e);return}let n=Uy(i,{agents:e.map(e=>({agentId:e.agentId,label:e.label})),goalId:z,todos:(H?.agentTodos??[]).map(e=>({text:e.text,todoId:e.todoId}))});if(n.route===`clarify`){Ae(i);let e=l(`composer.clarifySingleAction`);n.missingFields.includes(`resume_when`)&&(e=l(`composer.clarifyDefer`)),re(e);return}if(n.actionKind===`goal.create`){let e=kx(i,l),t=Ex(e.title);await Ge({actionKind:`goal.create`,context:{kind:`manager`,goal_id:null,natural_language:i},idempotencyKey:`workspace-goal-intent-${t}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:Ee,completion_criteria:e.completionCriteria,execution_boundary:e.executionBoundary,goal_id:t,heartbeat:{cadence:Ax(i),enabled:n.normalizedParameters.heartbeat_enabled===!0,timezone:`Asia/Shanghai`},initial_todos:e.initialTodos,objective:e.objective,permission:e.permission,stop_condition:Nx(i),title:e.title,workspace_ref:`current`},summary:l(`proposal.summary.goalCreate`,{title:e.title})});return}if(z&&n.actionKind===`heartbeat.bind`){await Ye(`heartbeat`,z,i);return}if(z&&n.actionKind===`monitor.create`){let e=jx(i,l);if(e){Ae(i),re(e);return}await Ye(`monitor`,z,i);return}let a=Px(i,e);if(z&&a&&n.actionKind===`agent.bind`){await Ge({actionKind:`agent.bind`,context:{kind:`goal`,goal_id:z,natural_language:i},idempotencyKey:`workspace-agent-bind-${z}-${a.agentId}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:a.agentId,goal_id:z},summary:`将 ${a.label} 绑定到 ${H?.title??z}`});return}if(z&&n.actionKind===`todo.create`){if(n.normalizedParameters.start_execution===!0){await Ge({actionKind:`todo.create`,context:{kind:`goal`,goal_id:z,natural_language:i},idempotencyKey:`workspace-task-start-${z}-${Date.now().toString(36)}`,normalizedParameters:{endpoint_id:a?.agentId??Ee,goal_id:z,start_execution:!0,text:i},summary:`交给 Agent 执行:${i.slice(0,120)}`});return}let e=a?.agentId??(/(交给|分配给|让).{0,24}(agent|codex|claude|kiro|kimi)/iu.test(i)?Ee:null);await Ge({actionKind:`todo.create`,context:{kind:`goal`,goal_id:z,natural_language:i},idempotencyKey:`workspace-todo-create-${z}-${Date.now().toString(36)}`,normalizedParameters:{...e?{endpoint_id:e}:{},goal_id:z,text:Fx(i)},summary:`创建 Todo:${Fx(i)}`});return}let o=H?.agentTodos.find(e=>i.includes(e.todoId)||i.includes(e.text)),s=typeof n.normalizedParameters.operation==`string`?n.normalizedParameters.operation:null;if(z&&o&&n.actionKind===`todo.update`&&s){await Ge({actionKind:`todo.update`,context:{kind:`todo`,goal_id:z,todo_id:o.todoId,natural_language:i},idempotencyKey:`workspace-todo-update-${o.todoId}-${s}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:Ee,...s===`reassign`&&a?{endpoint_id:a.agentId}:{},...s===`block`?{note:i}:{},...s===`defer`&&typeof n.normalizedParameters.resume_when==`string`?{resume_when:n.normalizedParameters.resume_when}:{},goal_id:z,operation:s,todo_id:o.todoId},summary:`更新 Todo:${o.text}`});return}z?S!==`chat`&&ee(!0):D(!0);let c=await t.onSendMessage?.(i,Ee,z);c&&await Ge(c)}catch(e){n||(Ae(i),M(r));let t=e instanceof Error?e.message:l(`feedback.sendGenericError`);re(l(`feedback.sendFailed`,{error:t}))}finally{A(!1)}}}let it=e.find(e=>e.agentId===Ee)?.label??Ee,at=!H&&Oe.startsWith(l(`composer.createGoalDraftLead`)),ot=Le.filter(e=>e.kind===`run`&&!!e.run.sessionId&&!!e.run.canInterrupt&&(e.run.status===`running`||e.run.status===`queued`)).length;async function st(e){if(!e?.length)return;let t=Rx-j.length,n=Array.from(e).slice(0,Math.max(0,t)),r=n.find(e=>!Ix.has(e.type)),i=n.find(e=>e.size>Lx);if(t<=0){P(l(`composer.imageCountError`,{count:Rx}));return}if(r){P(l(`composer.imageTypeError`));return}if(i){P(l(`composer.imageSizeError`,{size:Lx/1024/1024}));return}try{let t=await Promise.all(n.map(e=>zx(e,l)));M(e=>[...e,...t].slice(0,Rx)),P(e.length>n.length?l(`composer.imageCountError`,{count:Rx}):null)}catch(e){P(e instanceof Error?e.message:l(`composer.imageReadGenericError`))}finally{xe.current&&(xe.current.value=``)}}function ct(e){let t=Array.from(e.clipboardData.items).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).flatMap(e=>{let t=e.getAsFile();return t?[t]:[]});t.length&&(e.preventDefault(),st(t))}async function lt(){let e=await Kg();ge(e)}async function ut(){await Promise.all([lt(),t.onRefresh?.()])}async function dt(){if(!(!t.onRefresh||oe===`loading`)){se(`loading`);try{await t.onRefresh(),se(`done`)}catch{se(`error`)}window.setTimeout(()=>se(`idle`),1800)}}return Fe?(0,V.jsx)(cx,{focusGoalConnection:!!(m?.kind===`settings`&&m.goalId),goals:Me,initialGoalId:m?.kind===`settings`?m.goalId??z:z,initialTab:m?.kind===`settings`?m.tab??`lark`:`lark`,onChanged:()=>void ut(),onClose:()=>h(null),onThemeChange:nt,theme:R}):(0,V.jsx)(px,{drawer:We?(0,V.jsx)(Qy,{agents:e,attentionHistory:r.attentionHistory??r.userTodos,onSelectAttention:e=>h({kind:`attention`,item:e}),callbacks:$e,goalNotifications:r.goalNotifications??[],goals:Me,inspectorExpanded:g,larkConnections:i?[]:he,onClose:()=>{We.kind===`proposal`&&[`applied`,`rejected`].includes(We.item.status)&&(We.item.actionKind!==`heartbeat.bind`||We.item.status!==`applied`)&&x(e=>{let t={...e};return delete t[We.item.previewId],t}),_(!1),h(null)},onToggleInspectorSize:()=>_(e=>!e),readOnly:i,runs:Le.flatMap(e=>e.kind===`run`?[e.run]:[]),selection:We}):null,drawerMode:We?.kind===`todo`?g?`inspector-full`:`inspector`:`panel`,drawerOpen:We!==null,mobileSidebarOpen:ue,onCloseMobileSidebar:()=>de(!1),theme:R,main:(0,V.jsxs)(`div`,{className:`personal-channel`,children:[(0,V.jsx)(Cy,{agents:e,managerChatOpen:w,mobileNavigationOpen:ue,onOpenGoalCapabilities:H?()=>h({goalId:H.goalId,kind:`settings`,tab:`capabilities`}):void 0,onOpenGoalDetail:H&&!H.loadState?()=>h({item:H,kind:`goal`}):void 0,onRefresh:t.onRefresh?()=>void dt():void 0,onOpenNavigation:()=>de(!0),onOpenManagerChat:()=>{D(!1),T(!0)},onSelectGoalTab:e=>{C(e),e===`chat`&&(y(null),ee(!1))},onSelectAgent:tt,onReturnManagerHome:()=>{T(!1),D(!1),window.requestAnimationFrame(()=>be.current?.scrollTo({behavior:`smooth`,top:0}))},selectedAgentId:Ee,refreshState:oe,readOnlySourceLabel:i?s?.activeSource.label:void 0,selectedGoal:H,selectedGoalTab:S}),(0,V.jsxs)(`div`,{className:`personal-channel-scroll`,ref:be,children:[!H&&!w&&we&&we.done+we.failed+we.attention>0?(0,V.jsxs)(`section`,{className:`personal-digest-card`,"aria-label":l(`digest.away`),children:[(0,V.jsx)(`strong`,{children:l(`digest.away`)}),(0,V.jsxs)(`div`,{className:`personal-digest-stats`,children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`b`,{children:we.done}),l(`digest.completed`)]}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`b`,{children:we.failed}),l(`digest.failed`)]}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`b`,{children:we.attention}),l(`digest.needsYou`)]})]})]}):null,!H&&!w?(0,V.jsxs)(`section`,{className:`personal-manager-greeting`,children:[(0,V.jsx)(`span`,{children:(0,V.jsx)(Zp,{size:20})}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:l(`home.greeting`)}),(0,V.jsx)(`p`,{children:r.goals.some(e=>e.activationState===`active`&&e.loadState)?l(`startup.partial`):(0,V.jsxs)(V.Fragment,{children:[l(`home.waitingCount`,{count:Ne}),` `,l(`home.blockingSummary`,{count:Pe})]})})]})]}):null,H?.loadState?(0,V.jsx)(`section`,{className:`personal-manager-greeting`,role:`status`,"data-testid":`goal-status-loading`,children:(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`strong`,{children:l(H.loadState===`error`?`startup.goalError`:`startup.goalLoading`)}),(0,V.jsx)(`p`,{children:l(H.loadError?`startup.error.${H.loadError}`:`startup.independent`)}),H.loadState===`error`?(0,V.jsx)(`button`,{className:`min-h-11 rounded-md border px-3 py-2 text-sm`,type:`button`,onClick:()=>void t.onRefresh?.(),children:l(`startup.retry`)}):null]})}):H&&S===`tasks`?(0,V.jsx)(wb,{historyEnabled:!i,goal:H,items:Le,onDraftTaskFromMessage:i?void 0:e=>{Ae(`创建一个 Task:${mx(e)}`),re(l(`feedback.taskDraftCreated`)),window.requestAnimationFrame(()=>ye.current?.focus())},onOpenChat:()=>C(`chat`),onQuickComplete:i?void 0:Xe,onSelect:h,quickCompletingTodoIds:ae,selectedTodoId:We?.kind===`todo`?We.item.todoId:null,userTodos:r.userTodos}):H&&S===`files`?(0,V.jsx)(vx,{items:Le.filter(e=>e.kind===`output`),onSelect:h,reportState:r.periodicReports}):!H&&!w?(0,V.jsx)(_x,{goals:Me,onRetry:()=>void t.onRefresh?.(),onSelectGoal:et,systemHealth:r.systemHealth}):H?(0,V.jsxs)(V.Fragment,{children:[H&&v?.goalId===H.goalId?(0,V.jsx)(bx,{onClose:()=>y(null),onOpenDetails:()=>h({item:v,kind:`run`}),run:v}):null,(0,V.jsx)(Fy,{items:Re,onSelect:h,selectedGoal:H})]}):(0,V.jsx)(Fy,{items:Ve,onSelect:h,selectedGoal:null})]}),(0,V.jsx)(`div`,{className:`personal-composer-wrap`,children:i?(0,V.jsxs)(`div`,{className:`personal-read-only-notice`,children:[(0,V.jsx)(`strong`,{children:l(`source.readOnlyNoticeTitle`)}),(0,V.jsx)(`span`,{children:l(`source.readOnlyNoticeDescription`)})]}):(0,V.jsxs)(V.Fragment,{children:[!H&&!w&&E&&ze.length?(0,V.jsx)(yx,{messages:ze,onClose:()=>D(!1),onOpenConversation:()=>{D(!1),T(!0)}}):null,H&&S!==`chat`&&O&&Be.length?(0,V.jsx)(yx,{agentLabel:it,messages:Be,onClose:()=>ee(!1),onDraftTask:S===`tasks`?e=>{Ae(`创建一个 Task:${mx(e)}`),re(l(`feedback.taskDraftCreated`)),window.requestAnimationFrame(()=>ye.current?.focus())}:void 0,onOpenConversation:()=>{ee(!1),C(`chat`)},title:`${H.title} · ${it}`}):null,F?(0,V.jsxs)(`div`,{className:`personal-action-feedback`,role:`status`,children:[(0,V.jsx)(`span`,{children:F}),(0,V.jsx)(`button`,{"aria-label":l(`common.closeActionReceipt`),onClick:()=>re(null),type:`button`,children:(0,V.jsx)($m,{size:14})})]}):null,(0,V.jsx)(`p`,{className:`personal-composer-hint`,children:H?ot>0?l(`composer.goalRunningHint`,{agent:it,count:ot}):l(`composer.goalMessageHint`,{agent:it}):l(`composer.managerMessageHint`)}),H?(0,V.jsxs)(`div`,{className:`personal-quick-prompts`,children:[(0,V.jsxs)(`button`,{"aria-label":l(`composer.nextAction`),className:`is-draft`,onClick:()=>je(l(`composer.nextActionPrompt`)),title:l(`composer.prepareDraft`),type:`button`,children:[(0,V.jsx)(Em,{size:13}),(0,V.jsx)(`span`,{children:l(`composer.nextAction`)}),(0,V.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]}),(0,V.jsxs)(`button`,{className:`is-immediate`,disabled:k,onClick:()=>void rt(l(`composer.agentProgressPrompt`)),title:l(`composer.immediate`),type:`button`,children:[(0,V.jsx)(Bm,{size:13}),(0,V.jsx)(`span`,{children:l(`composer.agentProgress`)}),(0,V.jsx)(`em`,{className:`personal-prompt-badge`,children:l(`composer.immediate`)})]}),(0,V.jsxs)(`button`,{"aria-label":l(`composer.monitor`),className:`is-draft`,onClick:()=>Je(`monitor`,z),title:l(`composer.monitorHint`),type:`button`,children:[(0,V.jsx)($p,{size:13}),(0,V.jsx)(`span`,{children:l(`composer.monitor`)}),(0,V.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]})]}):(0,V.jsxs)(`div`,{className:`personal-quick-prompts`,children:[(0,V.jsxs)(`button`,{"aria-label":l(`composer.globalTasks`),className:`is-draft`,onClick:()=>je(l(`composer.globalTasksPrompt`)),title:l(`composer.prepareDraft`),type:`button`,children:[(0,V.jsx)(Em,{size:13}),(0,V.jsx)(`span`,{children:l(`composer.globalTasks`)}),(0,V.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]}),(0,V.jsxs)(`button`,{className:`is-immediate`,disabled:k,onClick:()=>void rt(l(`composer.globalProgressPrompt`)),title:l(`composer.immediate`),type:`button`,children:[(0,V.jsx)(Bm,{size:13}),(0,V.jsx)(`span`,{children:l(`composer.globalProgress`)}),(0,V.jsx)(`em`,{className:`personal-prompt-badge`,children:l(`composer.immediate`)})]}),(0,V.jsxs)(`button`,{"aria-label":l(`composer.createGoal`),className:`is-draft`,onClick:Ke,title:l(`composer.createGoalHint`),type:`button`,children:[(0,V.jsx)(Pm,{size:13}),(0,V.jsx)(`span`,{children:l(`composer.createGoal`)}),(0,V.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]})]}),at?(0,V.jsxs)(`div`,{className:`personal-goal-draft-status`,role:`status`,children:[(0,V.jsx)(`strong`,{children:l(`composer.createGoalDraft`)}),(0,V.jsx)(`span`,{children:l(`composer.createGoalDraftDescription`)})]}):null,j.length?(0,V.jsx)(`div`,{className:`personal-composer-images`,"aria-label":l(`composer.imagesPending`),children:j.map(e=>(0,V.jsxs)(`figure`,{children:[(0,V.jsx)(`img`,{alt:e.name,src:e.dataUrl}),(0,V.jsx)(`button`,{"aria-label":l(`composer.sentImageAlt`,{name:e.name}),onClick:()=>M(t=>t.filter(t=>t.id!==e.id)),type:`button`,children:(0,V.jsx)($m,{size:13})})]},e.id))}):null,N?(0,V.jsx)(`p`,{className:`personal-composer-error`,role:`alert`,children:N}):null,(0,V.jsxs)(`div`,{className:`personal-channel-composer`,onDragOver:e=>{[...e.dataTransfer.items].some(e=>e.kind===`file`&&e.type.startsWith(`image/`))&&e.preventDefault()},onDrop:e=>{let t=[...e.dataTransfer.files].filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),st(t))},children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(Zp,{size:17}),e.find(e=>e.agentId===Ee)?.label??Ee]}),(0,V.jsx)(`button`,{"aria-label":l(`composer.addImage`),className:`personal-composer-attach`,disabled:k||j.length>=Rx,onClick:()=>xe.current?.click(),title:l(`composer.attachImageHint`),type:`button`,children:(0,V.jsx)(jm,{size:17})}),(0,V.jsx)(`input`,{accept:`image/png,image/jpeg,image/webp,image/gif`,"aria-label":l(`composer.imagePicker`),className:`personal-composer-file-input`,disabled:k||j.length>=Rx,multiple:!0,onChange:e=>void st(e.target.files),ref:xe,type:`file`}),(0,V.jsx)(`textarea`,{"aria-label":l(`composer.sendMessage`),onChange:e=>Ae(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),rt())},onPaste:ct,placeholder:H?l(`composer.goalPlaceholder`,{goal:H.title}):l(`composer.managerPlaceholder`),ref:ye,rows:1,value:Oe}),(0,V.jsx)(`button`,{"aria-label":l(at?`composer.createGoal`:`composer.send`),disabled:!Oe.trim()&&j.length===0||k,onClick:()=>void rt(),title:l(at?`composer.createGoalHint`:`composer.sendMessageHint`),type:`button`,children:(0,V.jsx)(Bm,{size:18})})]})]})})]}),sidebar:(0,V.jsx)(bb,{attentionCount:Ne,goals:Me,goalArchiveLoadState:n,goalLifecycleOperations:t.onExecuteGoalLifecycle?[`stop`,`resume`]:void 0,lifecycleBusyGoalIds:ie,onRequestGoalCreate:i?void 0:Ke,onRequestGoalLifecycle:i&&!t.onExecuteGoalLifecycle?void 0:(e,t)=>void qe(e,t),onRetryGoalArchive:t.onRetryGoalArchive||t.onRefresh?()=>void(t.onRetryGoalArchive??t.onRefresh)?.():void 0,onOpenSettings:i?void 0:()=>h({kind:`settings`}),onSelectGoal:et,selectedGoalId:z,statusSourceControl:s},s?.activeSource.statusUrl??`/status.json`)})}function Vx(e){return(e??``).replace(/\s+/gu,` `).trim()}function Hx(e,t=120){let n=Array.from(e);return n.length<=t?e:`${n.slice(0,t-1).join(``)}…`}function Ux(e,t,n){let r=Vx(e);return!r||r===`暂无`?n?t(n):``:/refresh-state|latest_run|latest run-derived/iu.test(r)?t(`projection.refreshState`):/first read-only adapter tick|read-only adapter/iu.test(r)?t(`projection.firstReadOnlyAdapterCheck`):/todo update recorded for/iu.test(r)?t(`projection.todoStatusUpdated`):/^(loopx|python3|npm|git|run)\s|\s--[a-z0-9-]+|\b[a-z]+_[a-z_]+\b/iu.test(r)?t(n??`projection.agentPreparingNextStep`):Hx(r)}function Wx(e,t){return t({advancing:`projection.agentAdvancingGoal`,idle:`projection.agentIdle`,needs_you:`projection.agentNeedsDecision`,stopped:`projection.agentStopped`,waiting_external:`projection.agentWaitingExternal`}[e])}function Gx({eventCount:e,hasArtifact:t,hasLatestValidation:n},r){return{label:r(n?`projection.latestValidation`:`projection.latestRun`),metadata:e>0?r(`projection.events24h`,{count:e}):r(t?`projection.runEvidenceAvailable`:`projection.publicSafeProjection`)}}var Kx=`/status.json`,qx=`loopx-status-source-catalog-v1`,Jx={id:`local`,kind:`local`,label:`本机`,readOnly:!1,statusUrl:Kx};function Yx(e,t){let n=ih(e,t).source;if(!n||!n.isLoopback||n.isRelative)return{error:`SSH 隧道来源必须使用显式的 localhost、127.0.0.1 或 ::1 URL。`};let r=new URL(n.url,t);return[`http:`,`https:`].includes(r.protocol)?{url:r.toString()}:{error:`状态来源只支持 HTTP 或 HTTPS。`}}function Xx(e){let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619);return`ssh-${(t>>>0).toString(36)}`}function Zx(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;if(n.kind!==`ssh_tunnel`||typeof n.label!=`string`||typeof n.statusUrl!=`string`)return null;let r=n.label.trim(),i=Yx(n.statusUrl,t);if(!r||r.length>48||!(`url`in i))return null;let a=ub(n.hostAlias)?n.hostAlias.trim():void 0;return{...a?{hostAlias:a}:{},id:Xx(i.url),kind:`ssh_tunnel`,label:r,readOnly:!0,statusUrl:i.url}}function Qx(){return{schemaVersion:1,sources:[Jx]}}function $x(e,t){try{let n=e.getItem(qx);if(!n)return Qx();let r=JSON.parse(n);if(r.schemaVersion!==1||!Array.isArray(r.sources))return Qx();let i=new Set([Jx.statusUrl]);return{schemaVersion:1,sources:[Jx,...r.sources.flatMap(e=>{let n=Zx(e,t);return!n||i.has(n.statusUrl)?[]:(i.add(n.statusUrl),[n])})]}}catch{return Qx()}}function eS(e,t){e.setItem(qx,JSON.stringify({schemaVersion:1,sources:t.sources.filter(e=>e.kind===`ssh_tunnel`)}))}function tS(e,t){let n=new Set(t.filter(ub).map(e=>e.trim())),r=!1,i=e.sources.map(e=>e.kind!==`ssh_tunnel`||e.hostAlias||!n.has(e.label)?e:(r=!0,{...e,hostAlias:e.label}));return r?{...e,sources:i}:e}function nS(e,t,n){let r=t.label.trim();if(!r)return{error:`请填写来源名称。`};if(r.length>48)return{error:`来源名称不能超过 48 个字符。`};let i=Yx(t.statusUrl,n);if(!(`url`in i))return i;if(e.sources.some(e=>e.statusUrl===i.url))return{error:`这个状态 URL 已经在来源目录中。`};if(t.hostAlias!==void 0&&!ub(t.hostAlias))return{error:`请选择有效的 SSH Host。`};let a=t.hostAlias?.trim(),o={...a?{hostAlias:a}:{},id:Xx(i.url),kind:`ssh_tunnel`,label:r,readOnly:!0,statusUrl:i.url};return{catalog:{...e,sources:[...e.sources,o]},source:o}}function rS(e,t){return{...e,sources:e.sources.filter(e=>e.kind===`local`||e.id!==t)}}function iS(e,t,n){if(!t.trim()||ih(t,n).source?.isRelative)return Jx;let r=t.trim();try{r=new URL(r,n).toString()}catch{return null}return e.sources.find(e=>e.statusUrl===r)??null}function aS(e,t,n){return iS(e,t,n)||(ih(t,n).source?.isRelative?Jx:{id:`temporary`,kind:`ssh_tunnel`,label:`临时来源`,readOnly:!0,statusUrl:t.trim()})}function oS(e,t,n,r){return aS(e,t??n,r)}var sS={delete:`删除`,deploy:`部署`,merge:`合并`,payment:`付款`,release:`发布`};function cS(e,t,n){let r=t.replace(/\s+/gu,` `).trim().toLowerCase(),i=n.target.replace(/\s+/gu,` `).trim().toLowerCase();return!i||!r.includes(i)?null:{actionKind:`goal.update`,context:{goal_id:e,kind:`goal`,natural_language:t,semantic_proposal:{operation:n.operation,target:n.target}},idempotencyKey:`workspace-semantic-protected-${e}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e,status:`operator_gate_requested`},summary:`请求受保护操作:${sS[n.operation]} · ${n.target}`}}var lS=Kx;async function uS(e){let t=await fetch(e,{cache:`no-store`,signal:AbortSignal.timeout(3e4)});if(!t.ok)throw Error(`HTTP ${t.status} while loading ${e}`);return Ep(await t.json())}function dS(e,t){if(t?.controller_readiness?.decision_advisor_ready||t?.controller_readiness?.write_controller_ready)return`controller_ready`;if(t?.controller_readiness)return`controller_gated`;if(t?.human_reward)return`reward_judged`;if(t?.operator_gate?.decision===`approve`)return`operator_approved`;if(t?.operator_gate)return`operator_gated`;let n=e||t?.classification||``;return n===`connected_without_run`?`connected`:n===`read_only_project_map`||t?.project_map?`mapped`:n===`state_refreshed`?`refreshed`:n&&n!==`no_status`?`adapter_inspected`:`registered`}function fS(e,t){let n=new Map(t.map(e=>[e.goal_id,e])),r=new Set,i=e.map(e=>{r.add(e.id);let t=n.get(e.id),i=e.latest_runs[0],a=t?.lifecycle_phase??e.lifecycle_phase??i?.lifecycle_phase??dS(t?.status??i?.classification??e.status,i),o=t?.lifecycle_flags?.length?t.lifecycle_flags:e.lifecycle_flags?.length?e.lifecycle_flags:i?.lifecycle_flags?.length?i.lifecycle_flags:[a];return{goal:e,queueItem:t,latestRun:i,status:t?.status??i?.classification??e.status??`no_status`,waitingOn:t?.waiting_on??`clear`,severity:t?.severity??`clear`,lifecyclePhase:a,lifecycleFlags:o}});for(let e of t)r.has(e.goal_id)||i.push({goal:{activation_state:e.activation_state,id:e.goal_id,status:e.status,display_name:e.goal_id,latest_runs:[],lifecycle_flags:[e.lifecycle_phase??`registered`],registry_member:!0,legacy_runtime_goal:!1,index_exists:!1,raw_index_records:0,unique_runs:0},queueItem:e,status:e.status,waitingOn:e.waiting_on,severity:e.severity,lifecyclePhase:e.lifecycle_phase??`registered`,lifecycleFlags:e.lifecycle_flags??[`registered`]});return i}function pS(e){return(e??``).replace(/\s+/g,` `).trim()}function mS(e,t=132){let n=pS(e);return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function hS(e){let t=new Map;for(let n of e?.goals??[])t.set(n.goal_id,n);return t}function gS(e,t){return e===void 0||t===void 0?void 0:e+t}function _S(e,t){if(!e)return null;let n=t===`user`?e.queueItem?.project_asset?.user_todos:e.queueItem?.project_asset?.agent_todos;if(n?.items?.length)return{done_count:n.done??n.items.filter(e=>e.done).length,items:n.items,open_count:n.open??n.items.filter(e=>!e.done).length,total_count:n.total??n.items.length};let r=t===`user`?e.queueItem?.user_todos:e.queueItem?.agent_todos;return r?.items?.length?r:null}function vS(e){return e?.items.find(e=>!e.done)}function yS(e,t,n=`todos`){return e?.items?.length?{advancement_done_count:e.advancement_done_count??t?.advancement_done_count,done_count:e.done??e.items.filter(e=>e.done).length,items:e.items,open_count:e.open??e.items.filter(e=>!e.done).length,total_count:e.total??e.items.length}:t??null}function bS(e){return e?.queueItem?.project_asset?.quota?.state??e?.queueItem?.quota?.state??e?.goal.quota?.state??`waiting`}function xS(e,t,n){let r=[];for(let t of e){let e=_S(t,`agent`);for(let n of e?.items??[])r.push({goalId:t.goal.id,role:`agent`,todo:n})}let i=new Map;for(let e of r){let t=e.todo.claimed_by||`codex`,n=i.get(t)??[];n.push(e),i.set(t,n)}let a=new Map((n?.agents??[]).map(e=>[e.agent_id,e]));return Array.from(new Set([...i.keys(),...a.keys()])).map(e=>{let t=i.get(e)??[],n=a.get(e),r=Array.from(new Set([...t.map(e=>e.goalId),n?.current_todo?.goal_id,...n?.goal_ids??[]].filter(Boolean))),o=(t.filter(e=>!e.todo.done)[0]??t[0])?.goalId??n?.current_todo?.goal_id??r[0]??``,s=n?.last_activity_at??null;return{agentId:e,claimedTodos:t,currentTodo:n?.current_todo??null,evidenceRefs:[],goalIds:r,handoffNote:null,lastActivity:s,nextSafeAction:n?.next_action?.trim()||`Inspect status projection before taking work`,primaryGoalId:o,quotaHints:[],staleClaimHint:null,status:{label:`可用`,summary:`正常运行`,variant:`success`},workspaceRef:null}})}function SS(e){return e?.map(e=>({dataUrl:e.data_url,id:e.id,mimeType:e.mime_type,name:e.name,size:e.size}))}var CS=`loopx.personal-agent-selection.v1`;function wS(){if(typeof window>`u`)return{};try{let e=JSON.parse(window.localStorage.getItem(CS)??`{}`);return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(e=>typeof e[0]==`string`&&typeof e[1]==`string`))}catch{return{}}}var TS={需修复:`danger`,等你:`warning`,等待条件:`info`,推进中:`success`,安静运行:`neutral`,已停止:`neutral`,已完成:`neutral`};function ES(e,t){return pS(t)||e.replace(/^loopx[-_]/i,`LoopX `).split(/[-_]+/).filter(Boolean).map((e,t)=>t===0?`${e.slice(0,1).toUpperCase()}${e.slice(1)}`:e).join(` `)}function DS(e){return e.split(/\r?\n/u).filter(e=>!/^\s*GOAL_(STATUS|PROGRESS)\s*:/u.test(e)).map(e=>/^\s*GOAL_EVIDENCE\s*:/u.test(e)?e.replace(/^\s*GOAL_EVIDENCE\s*:/u,`验证依据:`):/^\s*NEXT_ACTION\s*:/u.test(e)?e.replace(/^\s*NEXT_ACTION\s*:/u,`下一步:`):e).join(` -`).trim()}function OS(e,t){return[`agent`,`assistant`].includes(e.trim().toLowerCase())&&t.trim().length>0}var kS=`已发现的项目 Agent`;function AS(e){switch(sy(e)){case`codex`:return`Codex`;case`claude`:return`Claude Code`;case`kiro`:return`Kiro CLI`;case`trae`:return`Trae CLI Agent`;case`coco`:return`Coco Agent`;default:return ES(e)}}function jS(e,t){switch(cy(e,t)){case`codex`:return`代码与项目执行`;case`claude`:return`复杂分析与长任务`;case`openai`:case`anthropic`:return`管家问答 · 无工具`;case`kiro`:return`终端编码 · 原生 /goal 循环`;case`trae`:return`前端与交互实现`;case`coco`:return`通用任务`;default:return kS}}function MS(e,t){let n=e.project_asset;return t===`user`?yS(n?.user_todos,e.user_todos,`project_asset.user_todos`):yS(n?.agent_todos,e.agent_todos,`project_asset.agent_todos`)}function NS(e){return mS(e.title??e.text,112)}function PS(e){let t=e.resume_condition?.resume_receipt;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t.receipt_id;return typeof n==`string`&&n.trim()?n.trim():null}function FS(e,t){return{resumeWhen:e.resume_when??null,resumeReady:e.resume_ready??null,resumeReceiptId:PS(e),claimedBy:e.claimed_by??null,done:e.status!==`deferred`&&e.done,evidence:e.evidence?mS(e.evidence,96):null,index:e.index,priority:e.priority??null,status:e.status??null,taskClass:e.task_class??null,taskDomain:e.task_domain??null,text:NS(e),todoId:e.todo_id?.trim()||`${t.goal.id}:agent:${e.index}`}}function IS(e){let t=e.queueItem?.agent_todos,n=t?.items??e.queueItem?.project_asset?.agent_todos?.items??[],r=new Map(n.map(t=>[t.todo_id?.trim()||`${e.goal.id}:agent:${t.index}`,t]));for(let n of t?.deferred_items??[]){let t=n.todo_id?.trim()||`${e.goal.id}:agent:${n.index}`;r.has(t)||r.set(t,n)}return[...r.values()]}function LS(e){return IS(e).map(t=>FS(t,e))}function RS(e,t,n){let r=new Map;for(let n of e.todo_index?.items??[]){if(n.goal_id!==t.goal.id||n.role!==`agent`)continue;let e=FS(n,t);r.set(e.todoId,e)}for(let e of n)r.has(e.todoId)||r.set(e.todoId,e);let i=new Map;for(let e of r.values()){if(e.done||e.taskClass!==`advancement_task`)continue;let t=e.taskDomain?.trim();t&&i.set(t,(i.get(t)??0)+1)}return[...i].map(([e,t])=>({domain:e,matchingTodoCount:t}))}function zS(e,t){return{claimedBy:e.claimed_by??null,done:e.status===`done`||e.status===`completed`,index:-1,priority:e.priority??null,status:e.status??null,taskClass:e.task_class??null,text:mS(e.title,112),todoId:e.todo_id?.trim()||`${t.goal.id}:agent:${e.claimed_by??`unknown`}:current`}}function BS(e,t,n){let r=new Map(e.map(e=>[e.todoId,e]));for(let e of t){let t=e.currentTodo;if(!t||t.goal_id!==n.goal.id)continue;let i=zS(t,n);r.has(i.todoId)||r.set(i.todoId,i)}return[...r.values()]}function VS(e){let t=e.queueItem?.project_asset?.agent_todos,n=e.queueItem?.agent_todos,r=IS(e),i=t?.advancement_done_count??n?.advancement_done_count??t?.done??n?.done_count??null,a=r.filter(e=>e.done&&e.status!==`deferred`).length,o=Math.max(i??0,a),s=new Set(r.map(e=>e.todo_id?.trim()).filter(e=>!!e)),c=(t?.recent_completed_advancement_items??[]).filter(e=>!e.todo_id?.trim()||!s.has(e.todo_id.trim())).map(t=>FS(t,e)),l=r.find(e=>!e.done);return{doneTodoCount:o,nextTodoText:pS(t?.next??``)||(l?pS(l.title??``)||pS(l.text??``):``)||null,recentCompleted:c}}function HS(e,t){let n=pS(e);return n?/\b(state_file|registry_goal|authority_sources|source_registry)\b|\b[a-z_]+\s+\d+\/\d+/i.test(n)?t(`projection.goalVerified`):Ux(n,t,`projection.validationRecorded`):``}function US(e,t=4){if(e.length<=t)return e;let n=e.findIndex(e=>!e.done);if(n<0)return e.slice(-t);let r=Math.max(0,Math.min(n-2,e.length-t));return e.slice(r,r+t)}function WS(e,t,n){let r=t.queueItem?.project_asset?.latest_validation,i=t.latestRun,a=e.event_ledger_summary?.goals.find(e=>e.goal_id===t.goal.id);if(!r&&!i&&!a)return null;let o=[HS(r?.summary,n),Ux(i?.health_check,n),Ux(i?.recommended_action,n)].find(e=>e!==``&&e!==`暂无`)??n(`projection.runRecorded`),s=Gx({eventCount:a?.events_24h??0,hasArtifact:!!(i?.json_exists||i?.markdown_exists),hasLatestValidation:!!r},n);return{generatedAt:r?.generated_at??i?.generated_at??a?.latest_event_at??``,label:s.label,metadata:s.metadata,runId:i?`${t.goal.id}:${i.generated_at}`:null,safePreview:[o,s.metadata].filter(Boolean).join(` -`),summary:o,todoId:t.queueItem?.project_asset?.agent_todos?.items.find(e=>!e.done)?.todo_id??null}}function GS(e){return[e.status,e.goal.status,e.latestRun?.classification,e.lifecyclePhase].filter(Boolean).some(e=>/(^|[_\s-])(done|complete|completed|finished|terminal|closed|success)([_\s-]|$)/i.test(e??``))}function KS(e,t){return e.global_registry?.findings?.find(e=>e.severity===`high`&&(e.goal_id===t.goal.id||e.goal_ids.includes(t.goal.id)))}function qS(e){return[e.status,e.goal.status,e.latestRun?.classification,e.lifecyclePhase].filter(Boolean).some(e=>/(^|[_\s-])(failure|failed|error|broken|unhealthy|blocked[_\s-]?health|health[_\s-]?blocked)([_\s-]|$)/i.test(e??``))}function JS(e,t){let n=t.queueItem?.stale_latest_run_warning;return t.severity===`high`||!!KS(e,t)||!!(n?.requires_refresh_state||n?.severity===`high`)||qS(t)}function YS(e,t){let n=KS(e,t);return t.queueItem?.stale_latest_run_warning?.recommended_action??t.queueItem?.stale_latest_run_warning?.reason??n?.recommended_action??n?.message??t.queueItem?.recommended_action??t.latestRun?.recommended_action??null}function XS(e){let t=e.latestRun?.operator_gate,n=t?.decision?.trim().toLowerCase()??``,r=new Set([`approve`,`approved`,`reject`,`rejected`,`defer`,`deferred`,`cancel`,`cancelled`]),i=[e.queueItem?.recommended_action,e.latestRun?.recommended_action].filter(Boolean).join(` `),a=/(?:等待|需要)(?:用户|你|owner).{0,24}(?:批准|确认|授权|补充|选择|决定)|(?:批准|确认|授权).{0,16}(?:后|才能|方可)/i.test(i);return!!(t&&!r.has(n))||e.lifecyclePhase===`operator_gated`&&!r.has(n)||a}function ZS(e,t){let n=e.latestRun?.operator_gate;return Ux(n?.operator_question??n?.reason_summary??n?.follow_up??e.queueItem?.recommended_action??e.latestRun?.recommended_action,t,`projection.confirmAgentDecision`)}function QS(e,t){if(t.goal.activation_state===`stopped`)return`已停止`;let n=_S(t,`user`),r=_S(t,`agent`),i=!!vS(n),a=!!vS(r);return[`user_or_controller`,`controller`].includes(t.waitingOn)||i||XS(t)?`等你`:JS(e,t)?`需修复`:t.waitingOn===`external_evidence`?`等待条件`:bS(t)===`eligible`||a?`推进中`:GS(t)?`已完成`:`安静运行`}function $S(e,t,n,r){if(n===`已停止`)return Wx(`stopped`,r);if(n===`需修复`)return Ux(YS(e,t),r,`projection.statusRefreshNeeded`);if(n===`等你`)return Wx(`needs_you`,r);if(n===`推进中`){let e=[(_S(t,`agent`)?.items??[]).filter(e=>!e.done).flatMap(e=>[e.title,e.text]).map(e=>pS(e)).find(e=>e!==``&&e!==`暂无`),t.queueItem?.recommended_action,t.latestRun?.recommended_action].map(e=>pS(e)).find(e=>e!==``&&e!==`暂无`);return e?Ux(e,r,`projection.agentAdvancingGoal`):Wx(`advancing`,r)}return Wx(n===`等待条件`?`waiting_external`:`idle`,r)}function eC(e,t){return t.some(t=>e.includes(t))}function tC(e,t,n){if(t.goals.some(e=>e.activationState===`active`&&e.loadState))return{text:`Goal 状态尚未全部加载,暂不能给出完整统计。可先打开已加载的 Goal,失败项可重试。`,lines:[]};if(eC(n,[`Agent`,`agent`,`推进`,`在做`])){let e=t.goals.filter(e=>![`安静运行`,`已完成`,`已停止`].includes(e.state)),n=(e.length>0?e:t.goals).slice(0,3);return n.length===0?{text:`当前状态里还没有 Goal 可供汇总。`,lines:[]}:{text:e.length>0?`Agent 当前关注这些 Goal:`:`当前 Goal 都比较安静:`,lines:n.map(e=>`${e.title} · ${e.state} · ${e.agentSentence}`)}}if(eC(n,[`现在`,`下一步`,`我该`,`该做什么`,`优先处理`])){let e=t.userTodos[0];if(e)return{text:e.blocking?`先处理「${ES(e.goalId)}」:${e.text}`:`当前最先处理「${ES(e.goalId)}」:${e.text}`,lines:[]};let n=t.goals.find(e=>e.state===`需修复`);if(n)return{text:`没有待办,但这个 Goal 需要先修复。`,lines:[`${n.title} · ${n.agentSentence}`]};let r=t.goals.find(e=>e.state===`推进中`);return r?{text:`目前不需要你介入,Agent 正在推进。`,lines:[`${r.title} · ${r.agentSentence}`]}:{text:`当前系统很安静,没有需要你立即处理的事项。`,lines:[]}}if(eC(n,[`等我`,`阻塞`,`需要我`,`全局待办`]))return t.userTodos.length===0?{text:`目前没有 Goal 在等你,开放用户待办为 0。`,lines:[]}:{text:`有 ${t.userTodos.length} 项开放用户待办,阻塞项优先:`,lines:t.userTodos.slice(0,3).map(e=>`${ES(e.goalId)} · ${e.blocking?`阻塞`:`待处理`} · ${e.text}`)};if(eC(n,[`状态`,`异常`,`修复`,`健康`])){let n=t.systemHealth?!t.systemHealth.ok:!e.ok||!e.contract?.ok||!e.global_registry?.ok||(e.global_registry?.summary?.high??0)>0,r=t.goals.filter(e=>e.state===`需修复`),i=r.slice(0,n?2:3).map(e=>`${e.title} · ${e.agentSentence}`);return n&&i.push(`全局状态、契约或注册表健康检查未通过,请进入管理页检查。`),i.length===0?{text:`当前没有发现 Goal 级或全局健康异常。`,lines:[]}:{text:r.length>0?`当前需要关注这些健康问题:`:`Goal 状态正常,但全局健康需要检查:`,lines:i}}return{text:`当前管家支持三类问题:下一步、等待你的事项、Agent 与健康状态。`,lines:[`问“我现在该做什么?”`,`问“哪些 Goal 在等我?”`,`问“Agent 在做什么?”或当前健康状态`]}}function nC(e,t,n,r=!1){let i=new Map(t.map(e=>[e.goal.id,e])),a=new Set(e.run_history.goals.filter(e=>e.activation_state===`stopped`).map(e=>e.id)),o=hS(e.usage_summary),s=xS(t,e.todo_index,e.agent_management_projection),c=e.attention_queue.items.flatMap((e,t)=>{if(a.has(e.goal_id))return[];let n=[`user_or_controller`,`controller`].includes(e.waiting_on);return(MS(e,`user`)?.items??[]).map((r,i)=>({projectedDone:r.done,details:Ud(r),actionKind:r.action_kind??null,blocking:n,goalId:e.goal_id,sourceOrder:t,taskClass:r.task_class??null,text:NS(r),todoId:r.todo_id?.trim()||`${e.goal_id}:user:${r.index}`,todoOrder:i,updatedAt:r.updated_at??null}))}),l=c.filter(e=>!e.projectedDone),u=new Set(l.map(e=>e.goalId)),d=t.flatMap((t,r)=>a.has(t.goal.id)||u.has(t.goal.id)||!XS(t)?[]:[{details:Ud({task_class:`user_gate`,status:`open`,note:t.latestRun?.operator_gate?.reason_summary}),actionKind:`gate.resolve`,blocking:!0,goalId:t.goal.id,sourceOrder:e.attention_queue.items.length+r,taskClass:`user_gate`,text:ZS(t,n),todoId:`${t.goal.id}:operator-gate`,todoOrder:0,updatedAt:t.latestRun?.operator_gate?.recorded_at??t.latestRun?.generated_at??null}]),f=[...l,...d].sort((e,t)=>Number(t.blocking)-Number(e.blocking)||e.sourceOrder-t.sourceOrder||e.todoOrder-t.todoOrder),p=e.run_history.goals.flatMap(t=>{if(t.registry_member===!1)return[];let a=i.get(t.id);if(!a)return[];let c=QS(e,a),l=f.find(e=>e.goalId===t.id),u=l?.text??null,d=VS(a),p=t.coordination?.registered_agents??[],m=new Set(p),h=[...s.filter(e=>e.goalIds.includes(t.id)&&!/unassigned|unknown/i.test(e.agentId)&&(m.size===0||m.has(e.agentId))&&(e.currentTodo?.goal_id===t.id||e.claimedTodos.some(e=>e.goalId===t.id)))].sort((e,t)=>(t.lastActivity??``).localeCompare(e.lastActivity??``)),g=new Set(h.map(e=>e.agentId)),_=[...h.map(e=>({agentId:e.agentId,label:e.agentId,lastActivityAt:e.lastActivity,state:e.status.label})),...p.filter(e=>!g.has(e)).map(e=>({agentId:e,label:e,lastActivityAt:null,state:`registered`}))],v=h[0],y=BS(LS(a),h,a),b=[d.nextTodoText,a.queueItem?.recommended_action,a.latestRun?.recommended_action,$S(e,a,c,n)].map(e=>Ux(e,n)).find(e=>e!==``&&e!==`暂无`)??n(`projection.nextUpdatePending`);return[{activationState:t.activation_state,agentId:v?.agentId??p[0]??`codex`,agentLaneCount:_.length,agentLanes:_,agentLabel:v?.agentId,agentSentence:$S(e,a,c,n),agentTodos:[...y,...d.recentCompleted],doneTodoCount:d.doneTodoCount,acceptanceObservation:t.acceptance_observation,goalId:t.id,latestActivity:a.latestRun?.generated_at??``,needsYou:u,needsYouActionKind:l?.actionKind??null,needsYouBlocking:l?.blocking??!1,needsYouTaskClass:l?.taskClass??null,needsYouTodoId:l?.todoId??null,nextSentence:b,runEvidence:WS(e,a,n),state:c,...r?{subagentExecution:{allowedDomains:t.spawn_policy?.allowed_domains??[],domainCandidates:RS(e,a,y),enabled:t.spawn_policy?.mode===`multi_subagent`&&t.spawn_policy.spawn_allowed===!0&&t.spawn_policy.max_children>0,maxChildren:t.spawn_policy?.max_children??0,modelConfig:t.spawn_policy?.model_config}}:{},title:ES(t.id,t.display_name),usage:(()=>{let e=o.get(t.id);return e?{costUsd24h:e.cost_usd_24h,costUsd7d:e.cost_usd_7d,durationMs24h:e.duration_ms_24h,durationMs7d:e.duration_ms_7d,tokens24h:gS(e.input_tokens_24h,e.output_tokens_24h),tokens7d:gS(e.input_tokens_7d,e.output_tokens_7d)}:null})()}]}),m=[];if(e.ok||m.push(`状态载荷未标记为正常 (payload.ok === false)`),e.contract&&!e.contract.ok){let t=e.contract.summary,n=t?`${t.errors} 项错误 / ${t.warnings} 项警告`:e.contract.errors?.[0]||`请检查控制面契约`;m.push(`契约检查未通过: ${n}`)}if(e.global_registry){e.global_registry.ok||m.push(`注册表状态异常: ${e.global_registry.summary.high} 项高危`);for(let t of e.global_registry.findings||[])t.severity===`high`&&m.push(`[${t.kind}] ${t.message}`)}let h=e.decision_freshness_summary?.summary?.stale_count?`${e.decision_freshness_summary.summary.stale_count} 项决策状态已过期`:null,g=m.length===0&&!h,_={ok:g,summary:g?`所有控制面契约与注册表检查均正常`:`发现 ${m.length+ +!!h} 项系统健康关注点`,issues:m,freshnessWarning:h};return{blockingTodoCount:f.filter(e=>e.blocking).length,goalNotifications:(e.goal_channel_notification_projection?.goals??[]).map(e=>({goalId:e.goal_id,configured:e.configured,enabled:e.enabled,humanGateAutoNotifyEnabled:e.human_gate_auto_notify_enabled,lastNotifiedAt:e.last_notified_at??null,receiptCount:e.receipt_count,targetRef:e.target_ref??null})),goals:p,openUserTodoCount:f.length,systemHealth:_,attentionHistory:[...c,...d],userTodos:f,visibleUserTodos:f.slice(0,5),workers:(e.agent_management_projection?.agents??[]).map(e=>({agentId:e.agent_id,currentTodoGoalId:e.current_todo?.goal_id??null,currentTodoText:e.current_todo?.title?mS(e.current_todo.title,96):null,lastActivityAt:e.last_activity_at??null,state:e.state??null}))}}function rC({goalArchiveLoadState:e,isLoading:t,onGoalActivationStateChange:n,onGoalDeleted:r,onSelectGoal:i,onReconcileStatus:a,onRefresh:o,onRetryGoalArchive:s,payload:c,progress:l,rows:u,selectedGoalId:d,statusSourceControl:f,theme:p,toggleTheme:m}){let h=f.activeSource.readOnly,g=f.activeSource.kind===`ssh_tunnel`?f.activeSource.hostAlias:void 0,{t:_}=qi(),[v,y]=(0,B.useState)([]),[b,x]=(0,B.useState)(!1),S=(0,B.useMemo)(()=>{let e=nC(c,u,_,b);if(!l)return e;let t=Object.values(l.snapshots).map(e=>nC(e,fS(e.run_history.goals,e.attention_queue.items),_,b)),n=new Map(t.flatMap(e=>e.goals).map(e=>[e.goalId,e])),r=e.goals.map(e=>n.get(e.goalId)??{...e,loadError:l.errors[e.goalId],loadState:l.errors[e.goalId]?`error`:`loading`,agentId:``,agentSentence:``,nextSentence:``,subagentExecution:void 0}),i=t.flatMap(e=>e.userTodos),a=r.some(e=>e.activationState===`active`&&e.loadState),o=[...new Set(t.flatMap(e=>e.systemHealth?.issues??[]))];return{...e,goals:r,userTodos:i,attentionHistory:t.flatMap(e=>e.attentionHistory??e.userTodos),visibleUserTodos:i.slice(0,5),openUserTodoCount:i.length,blockingTodoCount:i.filter(e=>e.blocking).length,workers:[...new Map(t.flatMap(e=>e.workers??[]).map(e=>[e.agentId,e])).values()],goalNotifications:t.flatMap(e=>e.goalNotifications??[]),systemHealth:a||t.length===0?void 0:{ok:t.every(e=>e.systemHealth?.ok),issues:o,summary:o.length?`发现 ${o.length} 项系统健康关注点`:`状态检查已完成`,freshnessWarning:t.map(e=>e.systemHealth?.freshnessWarning).filter(Boolean).join(`;`)||null}}},[c,u,l,b,_]),C=S.goals.find(e=>e.goalId===d)??null,w=l?.snapshots[d]??c,[T,E]=(0,B.useState)(null),[D,O]=(0,B.useState)(null),[ee,te]=(0,B.useState)(!1),ne=S.goals.some(e=>e.activationState===`active`&&e.loadState===`loading`)?`loading`:S.goals.map(e=>`${e.goalId}:${e.agentId}`).join(`|`),k=C?.goalId??`manager`;S.goals.some(e=>e.activationState===`active`&&e.loadState)||(S.systemHealth?!S.systemHealth.ok:!c.ok)||S.openUserTodoCount>0&&`${S.openUserTodoCount}${S.blockingTodoCount}`;let A=v.length>0?v.map(e=>({agentId:e.agent_id,adapterKind:e.adapter_kind,available:e.available,capability:jS(e.agent_id,e.adapter_kind),interrupt:e.interrupt,label:e.display_name,location:e.location,resume:e.resume,source:e.source,statusLabel:e.available?`可用`:`需要配置`,streaming:e.streaming,toolCalls:e.tool_calls,trustScope:e.trust_scope})):[{agentId:`codex`,available:!0,capability:jS(`codex`),label:`Codex`,statusLabel:`正在检测`}],j=[...A,{agentId:`status-only`,available:!0,capability:`不调用模型`,adapterKind:`status_projection`,interrupt:!1,label:`仅查状态`,resume:!0,statusLabel:`只读`,streaming:!1,toolCalls:!1,trustScope:`read_only`}],M=A.find(e=>e.label===`Codex`&&e.available)?.agentId??A.find(e=>e.available)?.agentId??`status-only`,[N,P]=(0,B.useState)(wS),F=uh(j,N[k]??M,M),[re,ie]=(0,B.useState)(!1),[I,ae]=(0,B.useState)(!1),[L,oe]=(0,B.useState)(`chat`),[se,ce]=(0,B.useState)(``),[le,ue]=(0,B.useState)({}),[de,R]=(0,B.useState)({}),[fe,pe]=(0,B.useState)(null),[me,he]=(0,B.useState)({}),[ge,_e]=(0,B.useState)([]),[ve,ye]=(0,B.useState)(null),[be,xe]=(0,B.useState)({}),Se=(0,B.useRef)(1),Ce=(0,B.useRef)(1),we=(0,B.useRef)(new Map),Te=(0,B.useRef)(new Set),z=(0,B.useRef)(new Map),Ee=(0,B.useRef)(new Map),De=(0,B.useRef)(new Set),Oe=(0,B.useRef)(new Set),ke=(0,B.useRef)(null),Ae=(0,B.useRef)(null),je=(0,B.useRef)(null),Me=(0,B.useRef)(null);(0,B.useRef)(null);let Ne=le[k]??[];de[k];let Pe=C?S.userTodos.filter(e=>e.goalId===C.goalId):S.userTodos,H=C?.agentTodos??[];US(H,C?.needsYou?3:4);let Fe=H.filter(e=>e.done).length,Ie=H.length>0?`${Fe}/${H.length}`:`暂无计划`;C&&({...S},Pe.filter(e=>e.blocking).length,Pe.length),(0,B.useEffect)(()=>{let e=rh(f.activeSource.statusUrl,window.location.href),t=e.source?sh(w,e.source):null;if(!C||!t?.indexUrl||!t.detailUrl){E(null),O(null),te(!1);return}let{detailUrl:n,indexUrl:r}=t,i=!1;return E(null),O(null),te(!0),ch(r,C.goalId).then(async e=>{let t=e.items[0]?.detail_ref;return t?lh(n,t):null}).then(e=>{i||E(e)}).catch(e=>{i||O(Dp(e))}).finally(()=>{i||te(!1)}),()=>{i=!0}},[w,C?.goalId,f.activeSource.statusUrl]);let Le=C?void 0:me[k]?.sessionId;(0,B.useEffect)(()=>{if(h||!Le)return;let e=!1,t,n=async()=>{try{let t=await zh(Le);if(e)return;let n=t.messages.filter(e=>e.origin===`manager_followup`);ue(e=>{let t=e[k]??[],r=new Set(t.map(e=>e.sourceMessageId)),i=n.filter(e=>!r.has(e.message_id));return i.length?{...e,[k]:[...t,...i.map(e=>({id:Se.current++,sourceMessageId:e.message_id,role:`assistant`,agentLabel:F.label,sourceLabel:`管家交接回执`,text:DS(e.text),lines:[]}))]}:e})}catch{}finally{e||(t=setTimeout(n,3e3))}};return n(),()=>{e=!0,t&&clearTimeout(t)}},[h,Le,k,F.label]);function Re(e,t){he(n=>{if(t===null){let t={...n};return delete t[e],t}return{...n,[e]:t}})}(0,B.useEffect)(()=>{if(h){y([]),x(!1);return}let e=!1;return Ih().then(t=>{e||(y(t.adapters??[]),x(t.goal_subagent_configuration===`preview_locked`))}).catch(()=>{e||x(!1)}),()=>{e=!0}},[h]),(0,B.useEffect)(()=>{try{window.localStorage.setItem(CS,JSON.stringify(N))}catch{}},[N]),(0,B.useEffect)(()=>{if(h||!F.available)return;let e=k,t=`${e}:${F.agentId}`,n=C?`goal`:`manager`,r=C?`goal.${C.goalId}`:`manager`,i=!1,a=null,o=null;return(async()=>{try{let s=await Hh({agentId:F.agentId,channelId:r,goalId:C?.goalId});if(i||(ue(t=>(t[e]?.length??0)>0?t:{...t,[e]:s.messages.map(e=>({sourceMessageId:e.message_id,agentLabel:e.role===`user`?void 0:F.label,attachments:SS(e.attachments),id:Se.current++,lines:[],role:e.role===`user`?`user`:`assistant`,sourceLabel:e.role===`user`?void 0:e.role===`error`?`本地会话记录`:`恢复的 ${F.label} 会话`,text:e.role===`user`?e.text:DS(e.text)}))}),F.agentId===`status-only`))return;let c=s.sessions[0];if(o=c?.session_id??null,c&&!c.resumable){Te.current.add(t),Re(e,{agentId:F.agentId,resumable:!1,sessionId:c.session_id,status:`resume_failed`});return}let l=n===`manager`?``:C?.goalId??``;if(n===`goal`&&!l)return;let u=await Rh(l,F.agentId,`resume_latest`,n);if(i)return;we.current.set(t,u.session_id);let d=s.snapshots.find(e=>e.session.session_id===u.session_id),f=d?.session.active_turn_id??``;if(Re(e,{agentId:F.agentId,resumable:!0,sessionId:u.session_id,status:f?`running`:`ready`,turnId:f||void 0}),Te.current.delete(t),!f)return;let p=`${u.session_id}:${f}`;if(Oe.current.has(p))return;Oe.current.add(p),z.current.set(e,f),Re(e,{agentId:F.agentId,resumable:!0,sessionId:u.session_id,status:`running`,turnId:f}),pe(e),a=new AbortController,Ee.current.set(e,a);let m=``,h=ze(e,{activity:[`正在恢复进行中的 Agent 回合`],agentLabel:F.label,lines:[],pending:!0,sourceLabel:`恢复的 ${F.label} 会话`,text:``});try{let t=await Yh(u.session_id,f,{signal:a.signal,onDelta:t=>{m+=t,Be(e,h,{text:m})},onActivity:t=>{ue(n=>({...n,[e]:(n[e]??[]).map(e=>e.id===h?{...e,activity:[...new Set([...e.activity??[],t])].slice(-6)}:e)}))}});if(i)return;Be(e,h,{lines:t.response.gate?[t.response.gate.summary,t.response.gate.next_action].filter(Boolean).slice(0,2):[],pending:!1,text:t.response.message||m.trim()||`${F.label} 已完成分析。`});let n=S.goals.find(e=>e.goalId===d?.session.goal_id)??C??S.goals[0]??null;if(n&&t.response.proposals.length>0){let r=t.response.proposals.map(e=>({goalId:n.goalId,id:Ce.current++,previewId:null,proposal:e,receiptLabel:null,state:`candidate`,statusMessage:null}));R(t=>({...t,[e]:[...t[e]??[],...r]}))}}catch(t){if(i)return;Be(e,h,{activity:[],lines:[],pending:!1,reconnect:t instanceof Th&&t.payload.reconnectable===!0,sourceLabel:`LoopX Chat 本地后端`,text:t instanceof Error?t.message:`无法恢复进行中的 Agent 回合。`})}finally{Oe.current.delete(p),z.current.get(e)===f&&z.current.delete(e),Re(e,{agentId:F.agentId,resumable:!0,sessionId:u.session_id,status:`ready`}),Ee.current.get(e)===a&&Ee.current.delete(e),i||pe(t=>t===e?null:t)}}catch(n){if(i)return;n instanceof Th&&n.payload.error_code===`resume_failed`&&(Te.current.add(t),o&&Re(e,{agentId:F.agentId,resumable:!1,sessionId:o,status:`resume_failed`}))}})(),()=>{i=!0,a?.abort()}},[k,S.goals[0]?.goalId,h,C?.goalId,F.agentId,F.available,F.label]),(0,B.useEffect)(()=>{if(h||C||S.goals.length===0||ne===`loading`)return;let e=!1;return Promise.all(S.goals.filter(e=>!e.loadState).map(async e=>{let t=await Bh({agentId:e.agentId,channelId:`goal.${e.goalId}`,goalId:e.goalId});return{goalId:e.goalId,session:t.sessions[0]??null}})).then(t=>{e||he(e=>{let n={...e};for(let e of t)e.session&&(n[e.goalId]={agentId:e.session.agent_id,resumable:e.session.resumable,sessionId:e.session.session_id,status:e.session.active_turn_id?`running`:e.session.status,turnId:e.session.active_turn_id??void 0});return n})}).catch(()=>{}),()=>{e=!0}},[h,ne,C?.goalId]),(0,B.useEffect)(()=>{if(ye(null),h){_e([]),xe({});return}if(!C){_e([]),xe({});return}let e=!1,t=0,n=0;_e([]),xe({});let r=async()=>{if(!e){if(document.hidden){t=window.setTimeout(()=>void r(),1e4);return}try{let t=await Bh({goalId:C.goalId});if(!e){let r=t.sessions.filter(e=>e.channel_id?.startsWith(`task.`));_e(r);let i=await Promise.allSettled(r.map(e=>zh(e.session_id)));if(!e){let e=i.some(e=>e.status===`rejected`);n=e?n+1:0,ye(e?`partial`:null),xe(Object.fromEntries(i.flatMap((e,t)=>e.status===`fulfilled`?[[r[t].session_id,e.value]]:[])))}}}catch{n+=1,e||ye(`offline`)}e||(t=window.setTimeout(()=>void r(),Math.min(3e4,2e3*2**Math.min(n,4))))}};return r(),()=>{e=!0,window.clearTimeout(t)}},[h,C?.goalId]),(0,B.useEffect)(()=>{if(!re)return;let e=window.requestAnimationFrame(()=>{ke.current?.querySelector(`[role="menuitem"]:not(:disabled)`)?.focus()});return()=>{window.cancelAnimationFrame(e),Ae.current?.focus()}},[re]),(0,B.useEffect)(()=>{if(!I)return;let e=window.requestAnimationFrame(()=>je.current?.focus());return()=>{window.cancelAnimationFrame(e),Me.current?.focus()}},[I]),(0,B.useEffect)(()=>{if(!re&&!I)return;let e=e=>{e.key===`Escape`&&(ie(!1),ae(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[re,I]);function ze(e,t){let n=Se.current++;return ue(r=>({...r,[e]:[...r[e]??[],{...t,id:n,role:`assistant`}]})),n}function Be(e,t,n){ue(r=>({...r,[e]:(r[e]??[]).map(e=>e.id===t?{...e,...n}:e)}))}async function Ve(e,t){let n=e.trim();if(!n)return;let r=t&&`goalId`in t?t.goalId??`manager`:k,i=r===`manager`?null:S.goals.find(e=>e.goalId===r)??null,a=t?.agentId?uh(j,t.agentId,M):F,o=r===`manager`?S:i?{...S,blockingTodoCount:S.userTodos.filter(e=>e.goalId===i.goalId&&e.blocking).length,goals:[i],openUserTodoCount:S.userTodos.filter(e=>e.goalId===i.goalId).length,userTodos:S.userTodos.filter(e=>e.goalId===i.goalId),visibleUserTodos:S.userTodos.filter(e=>e.goalId===i.goalId)}:S,s=Se.current++;if(ue(e=>({...e,[r]:[...e[r]??[],{attachments:t?.attachments,id:s,lines:[],role:`user`,text:n}]})),ce(``),pe(r),a.agentId===`status-only`||!i&&r!==`manager`){let e=tC(w,o,n),t=a.agentId===`status-only`;ze(r,{agentLabel:t?`仅查状态`:`LoopX 管家`,lines:e.lines.slice(0,3),sourceLabel:t?`LoopX 状态投影 · 仅查状态`:`LoopX 状态投影`,text:e.text}),Lh({answer:[e.text,...e.lines.slice(0,3)].filter(Boolean).join(` -`),contextKind:r===`manager`?`manager`:`goal`,goalId:r===`manager`?void 0:r,question:n}).catch(()=>{}),pe(null);return}let c=`${r}:${a.agentId}`,l=null;try{let e=we.current.get(c);if(!e){let t=Te.current.has(c)?`new`:`resume_latest`;e=(await Rh(r===`manager`?``:i.goalId,a.agentId,t,r===`manager`?`manager`:`goal`)).session_id,we.current.set(c,e),Re(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`ready`}),Te.current.delete(c)}let o=``;l=ze(r,{activity:[`正在连接 Agent`],agentLabel:a.label,lines:[],pending:!0,sourceLabel:r===`manager`?`${a.label} 管家 · 跨 Goal`:`${a.label} Agent · ${ES(i.goalId)}`,text:``});let s=(await qh(e,n,{attachments:t?.attachments,signal:(()=>{let e=new AbortController;return Ee.current.set(r,e),e.signal})(),onDelta:e=>{o+=e,l!==null&&Be(r,l,{text:o})},onActivity:e=>{l!==null&&ue(t=>({...t,[r]:(t[r]??[]).map(t=>t.id===l?{...t,activity:[...new Set([...t.activity??[],e])].slice(-6)}:t)}))},onPhase:(t,n)=>{z.current.set(r,n),Re(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`running`,turnId:n})}})).response;if(Be(r,l,{lines:s.gate?[s.gate.summary,s.gate.next_action].filter(Boolean).slice(0,2):[],pending:!1,text:DS(s.message||o.trim())||`${a.label} 已完成分析。`}),s.proposals.length>0&&!i&&Be(r,l,{lines:[`请进入要修改的 Goal,预览并确认具体变更。`]}),s.proposals.length>0&&i){let e=s.proposals.map(e=>({goalId:i.goalId,id:Ce.current++,previewId:null,proposal:e,receiptLabel:null,state:`candidate`,statusMessage:null}));R(t=>({...t,[r]:[...t[r]??[],...e]}))}if(r!==`manager`&&s.protected_action){let e=cS(r,n,s.protected_action);if(e)return e}}catch(e){if(De.current.delete(r)){let e={agentLabel:a.label,lines:[],pending:!1,sourceLabel:`${a.label} 会话`,text:`已中断。你可以在当前会话继续发送消息。`};l===null?ze(r,e):Be(r,l,e);return}let t=e instanceof Th?e.payload:null;t&&dh(t)&&we.current.delete(c),t?.error_code===`resume_failed`&&(we.current.delete(c),Te.current.add(c),Re(r,{agentId:a.agentId,resumable:!1,sessionId:me[r]?.sessionId??`resume-failed`,status:`resume_failed`}));let n=t?.gate,i=n&&typeof n==`object`?String(n.summary??``):``,o={agentLabel:a.label,lines:i?[i]:[],pending:!1,reconnect:t?.reconnectable===!0,sourceLabel:`LoopX Chat 本地后端`,text:t?.error_code===`resume_failed`?`原 ${a.label} 会话无法恢复。本地历史已经保留,请在运行详情里选择“重试恢复”或“开始新 Session”。`:e instanceof Error?e.message:`${a.label} 会话暂时不可用。`};l===null?ze(r,o):Be(r,l,o)}finally{z.current.delete(r),Ee.current.delete(r);let e=we.current.get(c);e&&Re(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`ready`}),pe(e=>e===r?null:e)}}async function He(e){let t=e?.goalId??k,n=me[t],r=e?.agentId??n?.agentId??F.agentId,i=`${t}:${r}`,a=e?.sessionId??n?.sessionId??we.current.get(i),o=e?.turnId??n?.turnId??z.current.get(t);if(!(!a||!o))try{De.current.add(t),await Kh(a,o),Ee.current.get(t)?.abort()}catch(e){throw De.current.delete(t),e}finally{z.current.delete(t),Re(t,{agentId:r,resumable:!0,sessionId:a,status:`ready`}),Ee.current.delete(t),pe(e=>e===t?null:e)}}async function Ue(e){let t=e.goalId,n=`${t}:${e.agentId}`,r=e.sessionId??me[t]?.sessionId??we.current.get(n);if(r)try{let i=await Zh(r);we.current.set(n,r),Te.current.delete(n),Re(t,{agentId:e.agentId,resumable:i.session.resumable,sessionId:r,status:i.session.status})}catch{Re(t,{agentId:e.agentId,resumable:!1,sessionId:r,status:`resume_failed`})}}function We(e){let t=`${e.goalId}:${e.agentId}`;we.current.delete(t),Te.current.add(t),Re(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:`new-session-pending`,status:`ready`})}async function Ge(e){let t=`${e.goalId}:${e.agentId}`,n=e.sessionId??me[e.goalId]?.sessionId??we.current.get(t);n&&n!==`new-session-pending`&&await Xh(n),we.current.delete(t),Te.current.add(t),Re(e.goalId,null)}function Ke(e){j.some(t=>t.agentId===e&&t.available)&&(P(t=>({...t,[k]:e})),ie(!1))}function qe(){i(``),oe(`chat`)}function Je(e){i(e),oe(`chat`)}C&&TS[C.state],C&&(`${F.label}${C.state}`,H.length>0&&`${Ie}`,Pe.length>0&&`${Pe.length}`),C?.state===`需修复`||!C&&!c.ok?(C&&AS(C.agentId),C?.nextSentence,C?.agentSentence):C?.state===`等你`?(C.needsYouBlocking,C.needsYouBlocking,C.needsYou??C.nextSentence,C.needsYou):(C&&AS(C.agentId),C?.nextSentence);let Ye=[...!C&&me.manager?.status===`resume_failed`?[{id:`run:manager:resume-failed`,kind:`run`,run:{agentId:me.manager.agentId,agentLabel:AS(me.manager.agentId),canInterrupt:!1,completedSteps:0,goalId:`manager`,goalTitle:`LoopX 管家`,latestActivity:`本地聊天记录已保留,点我查看恢复方式。`,resumable:!1,runId:`manager:resume-failed`,sessionId:me.manager.sessionId,sessionStatus:`resume_failed`,status:`failed`,title:`上次会话需要恢复`,totalSteps:1,outputs:[]}}]:[],...C?ge.map(e=>{let t=e.channel_id?.startsWith(`task.`)?e.channel_id.slice(5):void 0,n=C.agentTodos.find(e=>e.todoId===t),r=!!e.active_turn_id,i=be[e.session_id],a=i?.messages.some(e=>OS(e.role,e.text))===!0;return{id:`run:task:${e.session_id}`,kind:`run`,run:{agentId:e.agent_id,agentLabel:AS(e.agent_id),canInterrupt:r,completedSteps:n?.done||a?1:0,goalId:C.goalId,goalTitle:C.title,latestActivity:r?`Agent 正在执行,可进入 Session 查看过程或发送纠偏。`:a?`Agent 已返回结果,点击查看结果与完整运行记录。`:`执行 Session 已保留,可继续纠偏或恢复。`,resumable:e.resumable,runId:e.session_id,sessionId:e.session_id,sessionMessages:i?.messages.map(e=>({createdAt:e.created_at,messageId:e.message_id,role:e.role===`user`?`user`:OS(e.role,e.text)?`assistant`:`error`,text:e.role===`user`?e.text:DS(e.text)})),sessionStatus:a?`completed`:e.status,status:n?.done||a?`completed`:r?`running`:e.status===`resume_failed`?`failed`:`waiting`,title:n?.text??`Agent 执行任务`,todoId:t,totalSteps:1,turnId:e.active_turn_id??void 0}}}):[],...C?[{id:`run:${C.goalId}`,kind:`run`,run:{agentId:me[C.goalId]?.agentId??C.agentId,agentLabel:AS(me[C.goalId]?.agentId??C.agentId),canInterrupt:!!me[C.goalId]?.turnId,completedSteps:C.agentTodos.filter(e=>e.done).length,goalId:C.goalId,goalTitle:C.title,latestActivity:C.agentSentence,resumable:me[C.goalId]?.resumable??!0,runId:`goal:${C.goalId}`,sessionId:me[C.goalId]?.sessionId,sessionStatus:me[C.goalId]?.status,status:me[C.goalId]?.turnId?`running`:C.state===`需修复`?`failed`:`waiting`,title:C.nextSentence,totalSteps:C.agentTodos.length||1,turnId:me[C.goalId]?.turnId,outputs:C.runEvidence?[{createdAt:C.runEvidence.generatedAt,kind:`evidence`,outputId:`${C.goalId}:latest-evidence`,title:C.runEvidence.label}]:[]}}]:[],...Ne.map(e=>({id:`message:${e.id}`,kind:`message`,message:{agentLabel:e.agentLabel,attachments:e.attachments,id:String(e.id),pending:e.pending,role:e.role,text:e.text||(e.pending?`Agent 正在处理…`:e.lines.join(` -`))}})),...(C?[C]:S.goals).flatMap(e=>e.runEvidence?[{id:`output:${e.goalId}:${e.runEvidence.generatedAt||`latest`}`,kind:`output`,output:{agentLabel:AS(e.agentId),createdAt:e.runEvidence.generatedAt,goalId:e.goalId,goalTitle:e.title,kind:`evidence`,outputId:`${e.goalId}:latest-evidence`,runId:e.runEvidence.runId??void 0,safePreview:e.runEvidence.safePreview,summary:e.runEvidence.summary,title:e.runEvidence.label,todoId:e.runEvidence.todoId??void 0}}]:[]),...C&&T?[{id:`output:${C.goalId}:report:${T.publication.publication_id}`,kind:`output`,output:{agentId:T.agent_id,agentLabel:AS(T.agent_id),createdAt:T.publication.delivered_at,goalId:C.goalId,goalTitle:C.title,kind:`report`,outputId:T.publication.publication_id,report:{addedCount:T.delta.added_count,changedCount:T.delta.changed_count,deliveredAt:T.publication.delivered_at,generationId:T.generation_id,items:T.delta.items.map(e=>({changeKind:e.change_kind,previousStatus:e.previous_status,sourceRef:e.source_ref,status:e.status,summary:e.summary,title:e.title})),periodEndAt:T.period_window.end_at,periodStartAt:T.period_window.start_at,predecessorPublicationId:T.publication.predecessor_publication_id,publicationId:T.publication.publication_id},safePreview:T.delta.items.map(e=>`${e.change_kind===`added`?`+`:`~`} ${e.title}\n${e.summary}`).join(` - -`),summary:T.summary,title:T.title}}]:[]],Xe=f.connectionState===`connected`,Ze=new Map(S.goals.map(e=>[e.goalId,e.title])),Qe=e=>Wd(e,f.activeSource.statusUrl,Xe&&!l?.errors[e.goalId],Ze.get(e.goalId)),$e={...py(S),userTodos:S.userTodos.map(Qe),attentionHistory:(S.attentionHistory??S.userTodos).map(Qe),periodicReports:{error:D,loading:ee},timeline:Ye};return(0,V.jsxs)(`div`,{className:p===`dark`?`dark`:``,"data-testid":`personal-goal-home`,children:[ve?(0,V.jsx)(`p`,{role:`status`,className:`m-0 bg-amber-50 px-4 py-2 text-sm text-amber-900`,children:_(ve===`partial`?`runs.discoveryPartial`:`runs.discoveryOffline`)}):null,(0,V.jsx)(Bx,{agents:j.map(e=>({adapterKind:e.adapterKind,agentId:e.agentId,available:e.available,capability:e.capability,interrupt:e.interrupt,label:e.label,location:e.location,resume:e.resume,source:e.source,streaming:e.streaming,toolCalls:e.toolCalls,trustScope:e.trustScope,workspaceCompatibility:e.available?`当前 Goal 写入前验证`:`不可用,需先修复 Endpoint`})),callbacks:{onApplyAttention:e=>Je(e.goalId),onCorrectRun:async(e,t)=>{if(!e.sessionId)throw Error(`这个 Run 还没有可纠偏的执行 Session。`);let n=await Mh((await kh({actionKind:`run.correct`,context:{kind:`run`,goal_id:e.goalId,todo_id:e.todoId},idempotencyKey:`workspace-run-correct-${e.sessionId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,message:t,session_id:e.sessionId},summary:`纠偏执行任务:${e.title}`})).proposal_id),r=typeof n.turn?.turn_id==`string`?n.turn.turn_id:void 0;if(Re(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:e.sessionId,status:r?`running`:`ready`,turnId:r}),r){z.current.set(e.goalId,r);let t=new AbortController;Ee.current.set(e.goalId,t);let n=``,i=ze(e.goalId,{activity:[`正在把纠偏送入原执行 Session`],agentLabel:e.agentLabel,lines:[],pending:!0,sourceLabel:`${e.agentLabel} · 执行 Session`,text:``});try{let a=await Yh(e.sessionId,r,{signal:t.signal,onDelta:t=>{n+=t,Be(e.goalId,i,{text:n})}});Be(e.goalId,i,{activity:[],pending:!1,text:DS(a.response.message||n.trim())||`${e.agentLabel} 已完成纠偏。`})}catch(t){let n=De.current.delete(e.goalId);Be(e.goalId,i,{activity:[],pending:!1,text:n?`已中断。你可以在当前会话继续发送消息。`:t instanceof Error?t.message:`纠偏回合失败。`})}finally{z.current.delete(e.goalId),Ee.current.delete(e.goalId),Re(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:e.sessionId,status:`ready`})}}},onCloseRunSession:Ge,onInterruptRun:async e=>He(e),onOpenGoal:Je,onOpenRunSession:async e=>{if(!e.sessionId)return;let t=e.sessionId,n=await zh(t);xe(e=>({...e,[t]:n})),Je(e.goalId),ue(t=>({...t,[e.goalId]:n.messages.map(t=>({agentLabel:t.role===`user`?void 0:e.agentLabel,attachments:SS(t.attachments),id:Se.current++,lines:[],role:t.role===`user`?`user`:`assistant`,sourceLabel:t.role===`user`?void 0:`${e.agentLabel} · 执行 Session`,text:t.role===`user`?t.text:DS(t.text)}))})),Re(e.goalId,{agentId:e.agentId,resumable:n.session.resumable,sessionId:t,status:n.session.active_turn_id?`running`:n.session.status,turnId:n.session.active_turn_id??void 0})},onOpenOutput:e=>Je(e.goalId),...b?{onPreviewGoalSubagentConfiguration:async e=>{let t=await eg(e);return{changed:t.changed,configuration:{allowedDomains:t.after.orchestration.allowed_domains,enabled:t.feature_summary.multi_subagent===`enabled`,maxChildren:t.after.orchestration.max_children,modelConfig:t.after.orchestration.model_config},previewId:t.preview_id}},onApplyGoalSubagentConfiguration:async({previewId:e,...t})=>{let n=await tg(t,e);return{allowedDomains:n.after.orchestration.allowed_domains,enabled:n.feature_summary.multi_subagent===`enabled`,maxChildren:n.after.orchestration.max_children,modelConfig:n.after.orchestration.model_config}}}:{},...g?{onExecuteGoalLifecycle:async({goalId:e,operation:t,reason:n})=>{let r=await _b(g,e,t,n);return{activationState:r.activation_state,projectionVerified:r.projection_verified}}}:{},onGoalActivationStateChange:n,onGoalDeleted:r,onReconcileStatus:a,onRetryGoalArchive:s,onExportOutput:async e=>{let t=[`# ${e.title}`,``,e.summary??``,``,e.safePreview??`此产出没有可用的公开安全预览。`,``,`Goal: ${e.goalId}`,`Todo: ${e.todoId??`unlinked`}`,`Run: ${e.runId??`unlinked`}`].join(` -`),n=URL.createObjectURL(new Blob([t],{type:`text/markdown;charset=utf-8`})),r=document.createElement(`a`);r.href=n,r.download=`${e.outputId.replace(/[^a-z0-9._-]+/gi,`-`)}.md`,r.click(),URL.revokeObjectURL(n)},onRefresh:o,onRetryResumeRun:Ue,onSelectAgent:Ke,onSelectGoal:e=>e?Je(e):qe(),onSendMessage:async(e,t,n,r)=>Ve(e,{agentId:t,goalId:n,attachments:r}),onStartNewRunSession:We},goalArchiveLoadState:e,model:$e,readOnly:h,selectedAgentId:F.agentId,selectedGoalId:C?.goalId??null,statusSourceControl:f})]})}function iC({error:e,isLoading:t,onRetry:n,requestedUrl:r,theme:i,toggleTheme:a}){let o=!!(e&&/failed to fetch|networkerror|load failed/i.test(e)&&r.includes(`status.json`));return(0,V.jsx)(`div`,{className:i===`dark`?`dark`:``,children:(0,V.jsxs)(`main`,{className:`min-h-screen bg-[#f6f7f9] text-slate-950 dark:bg-[#09090b] dark:text-zinc-50`,children:[(0,V.jsxs)(`header`,{className:`flex min-h-16 flex-wrap items-center justify-between gap-3 border-b border-slate-200 bg-white px-4 py-3 dark:border-zinc-800 dark:bg-zinc-950 sm:px-6`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`h1`,{className:`text-xl font-semibold`,children:`LoopX Workspace`}),(0,V.jsx)(`p`,{className:`mt-1 break-all text-sm text-slate-500 dark:text-zinc-400`,children:`Personal Workspace`})]}),(0,V.jsx)(ny,{"aria-label":`切换主题`,onClick:a,size:`icon`,variant:`secondary`,children:i===`dark`?(0,V.jsx)(Jm,{className:`h-4 w-4`}):(0,V.jsx)(km,{className:`h-4 w-4`})})]}),(0,V.jsxs)(`div`,{className:`grid min-h-[calc(100vh-80px)] sm:grid-cols-[240px_1fr]`,children:[(0,V.jsxs)(`aside`,{className:`hidden border-r border-slate-200 p-6 dark:border-zinc-800 sm:block`,"aria-label":`Workspace`,children:[(0,V.jsx)(`strong`,{children:`LoopX`}),(0,V.jsx)(`p`,{className:`mt-6 text-sm`,children:`Workspace`}),(0,V.jsx)(`p`,{className:`mt-8 text-xs text-slate-500`,children:`Goals`}),[1,2,3].map(e=>(0,V.jsx)(`div`,{className:`mt-4 h-8 rounded bg-slate-100 dark:bg-zinc-900`},e))]}),(0,V.jsx)(`div`,{className:`p-4 sm:p-8`,children:(0,V.jsx)(ry,{"data-testid":`initial-status-state`,children:(0,V.jsx)(iy,{className:`flex min-h-64 items-center justify-center p-6`,children:(0,V.jsxs)(`div`,{className:`max-w-xl text-center`,children:[e?(0,V.jsx)(im,{className:`mx-auto h-6 w-6 text-rose-600 dark:text-rose-300`}):(0,V.jsx)(Im,{className:`mx-auto h-6 w-6 animate-spin text-slate-500 dark:text-zinc-400`}),(0,V.jsx)(`p`,{className:`mt-3 text-sm font-medium`,children:e?`无法加载实时状态`:`正在加载实时状态`}),e?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{className:`mt-2 break-words text-sm leading-6 text-slate-500 dark:text-zinc-400`,children:o?`本地状态服务暂时未连接。升级或启动期间可能短暂断开,请重试;仍失败时重新打开 LoopX App,或运行 loopx doctor。`:e}),o?(0,V.jsx)(`p`,{className:`mt-2 text-xs leading-5 text-slate-400 dark:text-zinc-500`,children:`重新加载不会执行任务,也不会改变 Goal 配置。`}):null,(0,V.jsx)(`div`,{className:`mt-4 flex flex-wrap justify-center gap-2`,children:(0,V.jsxs)(ny,{disabled:t,onClick:n,children:[(0,V.jsx)(Im,{className:`h-4 w-4`}),`重试`]})})]}):(0,V.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-500 dark:text-zinc-400`,role:`status`,children:`正在连接 Workspace,Goal 列表将先出现,详细状态会逐个补齐。 / Connecting to your Workspace. Goals load independently.`})]})})})})]})]})})}function aC(){let e=nw.useSearch(),t=nw.useNavigate(),[n,r]=(0,B.useState)(`light`),[i,a]=(0,B.useState)(null),o=(0,B.useRef)(null),s=(0,B.useRef)(e.goalId);s.current=e.goalId;let[c,l]=(0,B.useState)(Op),[u,d]=(0,B.useState)({kind:`example`,label:`bundled example`}),[f,p]=(0,B.useState)(()=>$x(window.localStorage,window.location.href)),m=(0,B.useRef)(f);m.current=f;let[h,g]=(0,B.useState)(e.statusUrl),[_,v]=(0,B.useState)(null),[y,b]=(0,B.useState)(!1),[x,S]=(0,B.useState)({error:null,phase:`idle`}),[C,w]=(0,B.useState)(e.statusUrl.trim()||null),[T,E]=(0,B.useState)(!1),D=(0,B.useRef)(null),O=(0,B.useRef)(Yg(e.statusUrl.trim()||null)),ee=!T&&u.kind===`example`?e.statusUrl.trim():``,te=C??ee,ne=u.kind===`url`?u.label:lS,k=!!(_&&C),A=oS(f,C,ne,window.location.href),j=u.kind===`example`&&!T,M=c.attention_queue,N=c.run_history,P=(0,B.useMemo)(()=>fS(N.goals,M.items),[N.goals,M.items]);function F(e,t,n=0){S({error:null,phase:`loading`}),uS(ah(e,`stopped`,window.location.href)).then(r=>{if(!$g(O.current,t))return;let i=r.goal_projection?.registry_revision??null,a=t.registryRevision!==null&&t.registryRevision!==void 0&&i!==null&&t.registryRevision!==i;if(l(e=>S_(e,r)),a&&n<1){I(e,{background:!0,resyncAttempt:n+1});return}S(a?{error:`Goal 状态在加载历史时发生变化,请重试。`,phase:`error`}:{error:null,phase:`ready`})}).catch(e=>{$g(O.current,t)&&S({error:Dp(e),phase:`error`})})}function re(){let e=u.kind===`url`?u.label:h||lS,t=Zg(O.current,e,{background:!0});if(i){I(e);return}t&&F(e,t)}async function ie(e,n,r){if(r.background)return l(e=>S_(e,n)),!0;let i={kind:`url`,label:e};return O.current.loadedUrl=e,l(n),d(i),g(e),await t({search:t=>({...t,statusUrl:e})}),Qg(O.current,r)?(O.current.requestedUrl=null,w(null),!0):!1}async function I(e,t={}){let n=e.trim(),r=t.background===!0;if(!n){r||v(`状态地址不能为空`);return}let c=Zg(O.current,n,{background:r,selectionRevision:t.selectionRevision});if(!c)return;o.current?.abort();let d=new AbortController;o.current=d,r||(D.current=null,E(!1),w(n),b(!0),v(null),S({error:null,phase:`idle`}));try{let e=await jp(n,window.location.href).catch(()=>null);if(!$g(O.current,c))return;if(e){let o=t.retryOnly&&u.kind===`url`&&u.label===n&&i?.directory.registry_revision===e.registry_revision?i.snapshots:{};a({directory:e,snapshots:o,errors:{}});let f={...e,goals:e.goals.filter(e=>!o[e.id])},p=!1,m=Mp(e);if(r)l(m);else if(!await ie(n,m,c))return;if(S({error:null,phase:`loading`}),await Np(n,window.location.href,f,(e,t,n)=>{n===`revision`&&(p=!0),a(r=>r&&{...r,snapshots:t?{...r.snapshots,[e]:t}:r.snapshots,errors:n?{...r.errors,[e]:n}:r.errors})},()=>$g(O.current,c),()=>s.current,d.signal),p&&(t.resyncAttempt??0)<1&&$g(O.current,c)){await I(n,{resyncAttempt:1});return}$g(O.current,c)&&S({error:null,phase:`ready`});return}let o=await uS(ah(n,`active`,window.location.href));if(!$g(O.current,c)||(a(null),c.registryRevision=o.goal_projection?.registry_revision??null,!await ie(n,o,c)))return;if(o.goal_projection?.scope!==`active`||o.goal_projection.complete){S({error:null,phase:`ready`});return}F(n,c,t.resyncAttempt??0)}catch(e){if(!Qg(O.current,c))return;r||v(Dp(e))}finally{!r&&Qg(O.current,c)&&b(!1)}}function ae(e,t={}){o.current?.abort();let n=Xg(O.current,e.statusUrl);D.current=null,E(!1),w(e.statusUrl),b(!0),v(null),(async()=>{if(t.ensureTunnel&&e.kind===`ssh_tunnel`){let t=new URL(e.statusUrl,window.location.href).port;if(t)try{await gb(e.label,t)}catch{}}O.current.selectionRevision===n&&await I(e.statusUrl,{selectionRevision:n})})()}function L(e){m.current=e,p(e);try{eS(window.localStorage,e)}catch{}}let oe={activeSource:A,connectionState:y?`loading`:k?`error`:`connected`,errorMessage:k?`未切换到 ${C??`所选来源`}:${_}`:null,onAdd:e=>{let t=nS(f,e,window.location.href);return`error`in t?{error:t.error}:(L(t.catalog),ae(t.source,{ensureTunnel:e.ensureTunnel}),{})},onConfiguredHostsLoaded:e=>{let t=m.current,n=tS(t,e);n!==t&&L(n)},onRemove:e=>{L(rS(f,e)),A.id===e&&ae(Jx)},onSelect:e=>{let t=f.sources.find(t=>t.id===e);t&&ae(t,{ensureTunnel:t.kind===`ssh_tunnel`})},sources:A.id===`temporary`?[...f.sources,A]:f.sources};(0,B.useEffect)(()=>{let t=e.statusUrl.trim();if(t){if(D.current===t||C&&C!==t)return;(u.kind!==`url`||u.label!==t)&&I(t);return}D.current=null,!T&&(C||u.kind===`example`&&I(lS))},[T,C,e.statusUrl,u.kind,u.label]),(0,B.useEffect)(()=>{if(e.statusUrl&&u.kind===`example`)return;let n=new Set(P.map(e=>e.goal.id));if(P.length===0){e.goalId&&t({search:e=>({...e,goalId:``})});return}e.goalId&&!n.has(e.goalId)&&x.phase!==`loading`&&t({search:e=>({...e,goalId:``})})},[x.phase,P,t,e.goalId,e.statusUrl,u.kind]),(0,B.useEffect)(()=>{if(!i||y||!e.goalId||u.kind!==`url`)return;let t=i.directory.goals.find(t=>t.id===e.goalId);t?.activation_state===`stopped`&&!i.snapshots[t.id]&&!i.errors[t.id]&&I(u.label,{retryOnly:!0})},[e.goalId,y,i,u]);function se(e){t({search:t=>({...t,goalId:e})})}return j?(0,V.jsx)(iC,{error:_,isLoading:y,onRetry:()=>void I(te||lS),requestedUrl:te||lS,theme:n,toggleTheme:()=>r(n===`dark`?`light`:`dark`)}):(0,V.jsx)(rC,{goalArchiveLoadState:x,isLoading:y,onGoalActivationStateChange:(e,t)=>{O.current.projectionRevision+=1,l(n=>wp(n,e,t)),a(n=>n&&{...n,snapshots:Object.fromEntries(Object.entries(n.snapshots).map(([n,r])=>[n,wp(r,e,t)]))})},onGoalDeleted:e=>{O.current.projectionRevision+=1,l(t=>Tp(t,e)),a(t=>t&&{...t,snapshots:Object.fromEntries(Object.entries(t.snapshots).filter(([t])=>t!==e))})},onSelectGoal:se,onReconcileStatus:()=>I(u.kind===`url`?u.label:h||lS,{background:!0}),onRetryGoalArchive:re,onRefresh:()=>I(u.kind===`url`?u.label:h||lS,{retryOnly:!!(i&&Object.keys(i.errors).length)}),payload:c,progress:i,rows:P,selectedGoalId:e.goalId,statusSourceControl:oe,theme:n,toggleTheme:()=>r(n===`dark`?`light`:`dark`)})}var oC=D_(`inline-flex items-center gap-1 rounded-md border px-2 py-0.5 text-xs font-medium`,{variants:{variant:{neutral:`border-slate-200 bg-white text-slate-700 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-300`,success:`border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-200`,warning:`border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-200`,info:`border-sky-200 bg-sky-50 text-sky-800 dark:border-sky-900 dark:bg-sky-950 dark:text-sky-200`,danger:`border-rose-200 bg-rose-50 text-rose-800 dark:border-rose-900 dark:bg-rose-950 dark:text-rose-200`}},defaultVariants:{variant:`neutral`}});function sC({className:e,variant:t,...n}){return(0,V.jsx)(`span`,{className:ey(oC({variant:t}),e),...n})}var cC=[{label:`status payload`,source:`apps/presentation/dashboard/src/data/status.ts`,detail:`status_contract, attention_queue, local_dashboard_api, run_history`},{label:`channel projection`,source:`apps/presentation/dashboard/src/data/goal-channel-frontstage.ts`,detail:`decision_frame, todos, gates, leases, artifacts, truth_contract`},{label:`public showcase catalog`,source:`docs/showcases/showcase-catalog.json`,detail:`case metadata, visual hints, evidence boundaries, story beats`},{label:`route smoke`,source:`apps/presentation/dashboard/smoke/frontstage-route-smoke.ts`,detail:`static route contract, source guards, component expectations`}],lC=[{axis:`schema`,current:`goal_channel_projection_v0`,proposed:`new optional projection field`,gate:`parser default plus route smoke assertion`},{axis:`truth`,current:`event ledger and active state remain source of truth`,proposed:`derived UI state only`,gate:`truth_contract must stay read-only`},{axis:`privacy`,current:`compact source refs and warnings`,proposed:`public-safe fixture field`,gate:`loopx check and browser fake-private fixture`},{axis:`interaction`,current:`render, filter, select, inspect`,proposed:`no browser write by default`,gate:`write affordance requires explicit loopback capability`}],uC=[{title:`Fixture sources`,body:`Use examples/status.example.json, browser-smoke fixtures, and docs/showcases/showcase-catalog.json.`},{title:`Required proof`,body:`Every projection addition needs parser coverage, route smoke assertions, and one browser or bundle check when UI output changes.`},{title:`Never include`,body:`Raw task text, trajectories, transcripts, local paths, private registry state, credentials, or internal document links.`}],dC=[`npm --prefix apps/presentation/dashboard run smoke:frontstage-route`,`npm --prefix apps/presentation/dashboard run smoke:frontstage-browser`,`npm --prefix apps/presentation/dashboard run smoke:frontstage-share-bundle`,`npm --prefix apps/presentation/dashboard run build`,`loopx check --scan-path apps/presentation/dashboard --scan-path docs/status-data-contract.md`],fC=[{name:`Projection lane`,badges:[`read-only`,`schema v0`],body:`Summarizes one compact projection lane without mutating the underlying LoopX state.`},{name:`Capability badge`,badges:[`loopback`,`dry-run`],body:`Shows an advertised local capability only after the status feed declares it.`},{name:`Boundary warning`,badges:[`public-safe`,`omitted`],body:`Names omitted private material and points contributors back to compact source references.`}];function pC({children:e,icon:t,title:n}){return(0,V.jsxs)(`section`,{className:`rounded-lg border border-slate-200 bg-white shadow-sm`,children:[(0,V.jsx)(`div`,{className:`flex items-center justify-between gap-3 border-b border-slate-200 px-4 py-3`,children:(0,V.jsxs)(`h2`,{className:`flex items-center gap-2 text-sm font-semibold text-slate-950`,children:[(0,V.jsx)(t,{className:`h-4 w-4 text-slate-500`}),n]})}),e]})}function mC(){return(0,V.jsx)(pC,{icon:Qp,title:`Status Contract Explorer`,children:(0,V.jsx)(`div`,{className:`grid gap-3 p-4 lg:grid-cols-2`,"data-testid":`developer-contract-explorer`,children:cC.map(e=>(0,V.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-3`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,V.jsx)(sC,{variant:`info`,children:e.label}),(0,V.jsx)(sC,{variant:`neutral`,children:`public contract`})]}),(0,V.jsx)(`div`,{className:`mt-2 break-words font-mono text-xs text-slate-700`,children:e.source}),(0,V.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:e.detail})]},e.label))})})}function hC(){return(0,V.jsx)(pC,{icon:vm,title:`Projection Diffing`,children:(0,V.jsx)(`div`,{className:`overflow-x-auto`,"data-testid":`developer-projection-diffing`,children:(0,V.jsxs)(`table`,{className:`min-w-full border-separate border-spacing-0 text-left text-sm`,children:[(0,V.jsx)(`thead`,{children:(0,V.jsxs)(`tr`,{className:`bg-slate-50 text-xs uppercase tracking-normal text-slate-500`,children:[(0,V.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Axis`}),(0,V.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Current`}),(0,V.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Proposed`}),(0,V.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Gate`})]})}),(0,V.jsx)(`tbody`,{children:lC.map(e=>(0,V.jsxs)(`tr`,{className:`align-top`,children:[(0,V.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 font-semibold text-slate-950`,children:e.axis}),(0,V.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 text-slate-600`,children:e.current}),(0,V.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 text-slate-600`,children:e.proposed}),(0,V.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 text-slate-600`,children:e.gate})]},e.axis))})]})})})}function gC(){return(0,V.jsx)(pC,{icon:mm,title:`Fixture Generation`,children:(0,V.jsx)(`div`,{className:`grid gap-3 p-4 md:grid-cols-3`,"data-testid":`developer-fixture-generation`,children:uC.map(e=>(0,V.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-3`,children:[(0,V.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:e.title}),(0,V.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:e.body})]},e.title))})})}function _C(){return(0,V.jsx)(pC,{icon:om,title:`Smoke Checklist`,children:(0,V.jsx)(`div`,{className:`space-y-2 p-4`,"data-testid":`developer-smoke-checklist`,children:dC.map(e=>(0,V.jsxs)(`div`,{className:`flex items-start gap-3 rounded-md border border-slate-200 bg-slate-50 px-3 py-2`,children:[(0,V.jsx)(Yp,{className:`mt-0.5 h-4 w-4 shrink-0 text-emerald-600`}),(0,V.jsx)(`code`,{className:`break-all text-xs font-semibold leading-5 text-slate-700`,children:e})]},e))})})}function vC(){return(0,V.jsx)(pC,{icon:sm,title:`Component Examples`,children:(0,V.jsx)(`div`,{className:`grid gap-3 p-4 lg:grid-cols-3`,"data-testid":`developer-component-examples`,children:fC.map(e=>(0,V.jsxs)(`article`,{className:`rounded-md border border-slate-200 bg-slate-50 p-3`,children:[(0,V.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:e.badges.map(e=>(0,V.jsx)(sC,{variant:e===`read-only`||e===`public-safe`?`success`:`neutral`,children:e},e))}),(0,V.jsx)(`h3`,{className:`mt-3 text-sm font-semibold leading-6 text-slate-950`,children:e.name}),(0,V.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:e.body})]},e.name))})})}function yC(){return(0,V.jsx)(`main`,{className:`min-h-screen bg-[#f7f7f4] px-4 py-4 text-slate-950 sm:px-5`,"data-testid":`frontstage-developer-cockpit`,children:(0,V.jsxs)(`div`,{className:`mx-auto grid max-w-[1500px] gap-4 xl:grid-cols-[260px_minmax(0,1fr)]`,children:[(0,V.jsxs)(`aside`,{className:`rounded-lg border border-slate-200 bg-white p-4 shadow-sm xl:sticky xl:top-4 xl:self-start`,children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsx)(`div`,{className:`flex h-9 w-9 items-center justify-center rounded-md border border-slate-200 bg-slate-950 text-white`,children:(0,V.jsx)(Ym,{className:`h-4 w-4`})}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`div`,{className:`text-sm font-semibold`,children:`Developer Cockpit`}),(0,V.jsx)(`div`,{className:`text-xs text-slate-500`,children:`Projection extension`})]})]}),(0,V.jsxs)(`div`,{className:`mt-4 grid gap-2`,children:[(0,V.jsxs)(`a`,{className:`flex items-center gap-2 rounded-md border border-slate-200 px-3 py-2 text-sm font-medium`,href:`https://huangruiteng.github.io/loopx/`,children:[(0,V.jsx)(xm,{className:`h-4 w-4`}),`LoopX home`]}),(0,V.jsxs)(`a`,{className:`flex items-center gap-2 rounded-md border border-slate-200 px-3 py-2 text-sm font-medium`,href:`https://huangruiteng.github.io/loopx/docs/showcases/index.en.html`,children:[(0,V.jsx)(fm,{className:`h-4 w-4`}),`Public cases`]}),(0,V.jsxs)(`a`,{className:`flex items-center gap-2 rounded-md bg-slate-950 px-3 py-2 text-sm font-medium text-white`,href:`/chat/developers/projections/`,children:[(0,V.jsx)(sm,{className:`h-4 w-4`}),`Developer cockpit`]})]}),(0,V.jsxs)(`div`,{className:`mt-5 space-y-2 rounded-md border border-emerald-200 bg-emerald-50 p-3 text-xs leading-5 text-emerald-950`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,V.jsx)(sC,{variant:`success`,children:`read-only`}),(0,V.jsx)(sC,{variant:`neutral`,children:`public fixtures`})]}),(0,V.jsx)(`p`,{children:`This route uses static public contracts only; live status feeds, registry files, and browser write APIs stay outside the cockpit.`})]})]}),(0,V.jsxs)(`section`,{className:`space-y-4`,children:[(0,V.jsx)(`div`,{className:`rounded-lg border border-slate-200 bg-white px-5 py-5 shadow-sm`,children:(0,V.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-4`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,V.jsx)(sC,{variant:`info`,children:`developers/projections`}),(0,V.jsx)(sC,{variant:`success`,children:`public-safe`}),(0,V.jsx)(sC,{variant:`neutral`,children:`no browser writes`})]}),(0,V.jsx)(`h1`,{className:`mt-3 text-3xl font-semibold tracking-normal text-slate-950`,children:`LoopX Projection Developer Cockpit`}),(0,V.jsx)(`p`,{className:`mt-2 max-w-3xl text-sm leading-6 text-slate-600`,children:`A read-only contributor workbench for adding dashboard/frontstage projections without reverse-engineering the large operator page.`})]}),(0,V.jsxs)(`div`,{className:`grid min-w-[260px] gap-2 text-sm`,children:[(0,V.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-2`,children:[(0,V.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-normal text-slate-500`,children:`Source of truth`}),(0,V.jsx)(`div`,{className:`mt-1 font-semibold text-slate-950`,children:`status contract + compact fixtures`})]}),(0,V.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-2`,children:[(0,V.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-normal text-slate-500`,children:`Boundary`}),(0,V.jsx)(`div`,{className:`mt-1 font-semibold text-slate-950`,children:`read-only extension surface`})]})]})]})}),(0,V.jsxs)(`div`,{className:`grid gap-4 xl:grid-cols-2`,children:[(0,V.jsx)(mC,{}),(0,V.jsx)(hC,{})]}),(0,V.jsxs)(`div`,{className:`grid gap-4 xl:grid-cols-[minmax(0,1fr)_420px]`,children:[(0,V.jsx)(gC,{}),(0,V.jsx)(_C,{})]}),(0,V.jsx)(vC,{}),(0,V.jsx)(pC,{icon:Wm,title:`Extension Boundary`,children:(0,V.jsxs)(`div`,{className:`grid gap-3 p-4 md:grid-cols-3`,"data-testid":`developer-extension-boundary`,children:[(0,V.jsxs)(`div`,{className:`rounded-md border border-emerald-200 bg-emerald-50 px-3 py-3`,children:[(0,V.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:`Allowed`}),(0,V.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:`Versioned parser defaults, public fixtures, read-only route panels, and focused smoke assertions.`})]}),(0,V.jsxs)(`div`,{className:`rounded-md border border-amber-200 bg-amber-50 px-3 py-3`,children:[(0,V.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:`Review`}),(0,V.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:`New dashboard dependencies, status contract fields, loopback capability display, and browser-visible workflows.`})]}),(0,V.jsxs)(`div`,{className:`rounded-md border border-rose-200 bg-rose-50 px-3 py-3`,children:[(0,V.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:`Stop`}),(0,V.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:`Credentials, private registry material, raw logs, transcripts, production actions, or default browser write authority.`})]})]})})]})]})})}var bC=Y({value:K().finite(),total:K().finite().positive().optional(),unit:G().optional(),higher_is_better:q()}).passthrough(),xC=hd(G(),K().finite()).default({}),SC=Y({outcome_status:G().optional(),failure_class:G(),causal_summary:G(),expectedness:G(),implication:G(),next_probe:G(),confidence:G(),evidence_refs:J(G()).optional()}).passthrough(),CC=Y({arm_id:G(),selected_run_id:G().nullable(),score_countable:q(),metrics:hd(G(),bC),effort:xC,insight:SC.nullable().optional()}),wC=Y({run_id:G(),case_id:G(),arm_id:G(),arm_role:G(),status:G(),protocol_id:G(),runner_revision:G().optional(),observed_at:G(),metrics:hd(G(),bC),countability:Y({integrity_qualified:q(),official_result_present:q(),score_countable:q()}).passthrough(),treatment_fidelity:G(),effort:xC,redacted_insight:SC.nullable().optional(),upload_provenance:Y({producer_id:G(),producer_version:G(),observed_at:G(),source_revision:G()}).passthrough()}).passthrough(),TC=Y({case_denominator:K().int().nonnegative(),value_sum:K().finite(),value_mean:K().finite().nullable(),value_median:K().finite().nullable(),value_min:K().finite().nullable(),value_max:K().finite().nullable(),case_macro_rate:K().finite().optional(),suite_micro_rate:K().finite().optional(),suite_micro_numerator:K().finite().optional(),suite_micro_denominator:K().finite().positive().optional()}).passthrough(),EC=Y({arm_id:G(),arm_role:G(),factor_assignments:hd(G(),G()),protocol_counts:hd(G(),K().int().nonnegative()).default({}),runner_revision_counts:hd(G(),K().int().nonnegative()).default({}),orchestrator_runtime_counts:hd(G(),K().int().nonnegative()).default({}),intended_case_count:K().int().positive(),run_count:K().int().nonnegative(),terminal_run_count:K().int().nonnegative(),selected_score_countable_case_count:K().int().nonnegative(),coverage_rate:K().finite().min(0).max(1),metrics:hd(G(),TC),binary_outcomes:hd(G(),Y({success_count:K().int().nonnegative(),case_denominator:K().int().nonnegative(),success_rate:K().finite().min(0).max(1).nullable()})),effort:hd(G(),Y({denominator:K().int().nonnegative(),mean:K().finite().nullable(),median:K().finite().nullable()})),failure_class_counts:hd(G(),K().int().nonnegative())}).passthrough(),DC=Y({baseline_value:K().finite(),candidate_value:K().finite(),delta:K().finite(),direction:_d([`improved`,`flat`,`regressed`]).optional()}).passthrough(),OC=Y({comparison_id:G(),comparison_anchor_run_id:G(),candidate_run_id:G(),candidate_arm_id:G(),primary_metric:G(),matched_pair_countable:X(!0),metric_deltas:hd(G(),DC)}).passthrough(),kC=Y({ok:X(!0),schema_version:X(`benchmark_study_dashboard_v0`),benchmark_id:G(),study_id:G(),status:_d([`complete`,`provisional`]),design:Y({protocol_id:G(),comparison_protocol_id:G(),baseline_arm_id:G(),case_set:Y({case_set_id:G(),case_ids:J(G())}),metric_catalog:J(Y({metric_name:G(),role:_d([`primary`,`guardrail`,`supporting`]),unit:G().optional(),higher_is_better:q(),binary:q()})),labels:hd(G(),G())}).passthrough(),campaign:Y({intended_case_count:K().int().positive(),intended_arm_count:K().int().positive(),intended_cell_denominator:K().int().positive(),selected_score_countable_cell_count:K().int().nonnegative(),selected_score_countable_coverage_rate:K().finite().min(0).max(1),complete_declared_design_case_count:K().int().nonnegative(),ambiguous_score_countable_cell_count:K().int().nonnegative(),in_flight_run_count:K().int().nonnegative(),matched_pair_countable_count:K().int().nonnegative(),factorial_contrast_count:K().int().nonnegative(),factorial_contrast_countable_count:K().int().nonnegative(),runtime_observation_count:K().int().nonnegative(),runtime_classification_counts:hd(G(),K().int().nonnegative())}),arms:J(EC),contrasts:hd(G(),Y({matched_pair_denominator:K().int().nonnegative(),primary_metric_directions:Y({improved:K().int().nonnegative(),flat:K().int().nonnegative(),regressed:K().int().nonnegative()}),binary_metric_transitions:hd(G(),Y({"0_to_1":K().int().nonnegative(),"1_to_0":K().int().nonnegative(),same:K().int().nonnegative()}))})),cases:J(Y({case_id:G(),complete_declared_design:q(),arms:J(CC),eligible_comparisons:J(OC),largest_eligible_primary_contrast:OC.nullable()})),runs:J(wC),authority:Y({score_source:G(),matched_comparison_source:G(),factorial_comparison_source:G().nullable(),manifest_changes_scores:X(!1),dashboard_is_execution_authority:X(!1)}),public_boundary:Y({raw_task_recorded:X(!1),raw_trajectory_recorded:X(!1),hidden_evaluation_recorded:X(!1),raw_verifier_output_recorded:X(!1),credentials_recorded:X(!1),local_paths_recorded:X(!1)}),write_performed:X(!1),network_access_performed:X(!1)});function AC(e){return kC.parse(e)}function jC(e,t){let n=new URL(t),r=new URL(e||`/benchmark-study.example.json`,n);if(!new Set([`http:`,`https:`]).has(r.protocol))throw Error(`Benchmark dashboard source must use HTTP or HTTPS`);if(r.origin!==n.origin)throw Error(`Benchmark dashboard source must use same-origin local readback`);return r.toString()}var MC=[{id:`campaign`,label:`Campaign`},{id:`arms`,label:`Arms`},{id:`cases`,label:`Cases`},{id:`runs`,label:`Runs`}];function NC(e){return e==null?`—`:`${(e*100).toFixed(e>=.995?0:1)}%`}function PC(e){return e==null?`—`:new Intl.NumberFormat(`en`,{maximumFractionDigits:2,notation:`compact`}).format(e)}function FC(e){if(e==null)return`—`;let t=e/6e4;return t>=120?`${(t/60).toFixed(1)} h`:`${PC(t)} min`}function IC(e){let t=Object.entries(e);return t.length?t.map(([e,t])=>`${e} (${t})`).join(`, `):`—`}function LC(e){if(!e)return`—`;let t=e.total==null?PC(e.value):`${PC(e.value)}/${PC(e.total)}`;return e.unit?`${t} ${e.unit}`:t}function RC(e,t){let n=e.metrics[t];return!n||n.case_denominator===0?`—`:n.suite_micro_rate==null?`${PC(n.value_mean)} mean`:`${NC(n.suite_micro_rate)} · ${PC(n.suite_micro_numerator)}/${PC(n.suite_micro_denominator)}`}function zC(e,t){let n=e.largest_eligible_primary_contrast,r=n?.metric_deltas[t];if(!n||!r)return null;let i=r.delta>0?`+`:``;return{direction:r.direction,text:`${n.candidate_arm_id}: ${i}${PC(r.delta)}`}}function BC({children:e,tone:t=`neutral`}){return(0,V.jsx)(`span`,{className:`benchmark-state benchmark-state-${t}`,children:e})}function VC({packet:e,primaryMetric:t}){return(0,V.jsxs)(`div`,{className:`benchmark-view-stack`,children:[(0,V.jsxs)(`section`,{"aria-labelledby":`arm-summary-title`,children:[(0,V.jsxs)(`div`,{className:`benchmark-section-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`p`,{className:`benchmark-kicker`,children:`ARM SUMMARY`}),(0,V.jsx)(`h2`,{id:`arm-summary-title`,children:`Comparable outcomes, denominator first`})]}),(0,V.jsx)(`p`,{children:`Only one score-countable run per declared case × arm cell is selected.`})]}),(0,V.jsx)(`div`,{className:`benchmark-arm-grid`,children:e.arms.map(e=>{let n=Object.values(e.binary_outcomes)[0];return(0,V.jsxs)(`article`,{className:`benchmark-arm-card`,children:[(0,V.jsxs)(`div`,{className:`benchmark-card-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`span`,{className:`benchmark-mono`,children:e.arm_role}),(0,V.jsx)(`h3`,{children:e.arm_id})]}),(0,V.jsx)(BC,{tone:e.coverage_rate===1?`success`:`warning`,children:e.coverage_rate===1?`Complete`:`Provisional`})]}),(0,V.jsxs)(`dl`,{className:`benchmark-stat-list`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`dt`,{children:[`Primary · `,t]}),(0,V.jsx)(`dd`,{children:RC(e,t)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Score-countable coverage`}),(0,V.jsxs)(`dd`,{children:[e.selected_score_countable_case_count,`/`,e.intended_case_count]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Binary success`}),(0,V.jsx)(`dd`,{children:n?`${n.success_count}/${n.case_denominator}`:`Not declared`})]})]})]},e.arm_id)})})]}),(0,V.jsxs)(`section`,{"aria-labelledby":`contrast-title`,children:[(0,V.jsxs)(`div`,{className:`benchmark-section-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`p`,{className:`benchmark-kicker`,children:`MATCHED CONTRASTS`}),(0,V.jsx)(`h2`,{id:`contrast-title`,children:`Direction counts on eligible pairs`})]}),(0,V.jsx)(`p`,{children:`Raw run volume is never used as a comparison denominator.`})]}),(0,V.jsx)(`div`,{className:`benchmark-table-shell`,children:(0,V.jsxs)(`table`,{children:[(0,V.jsx)(`thead`,{children:(0,V.jsxs)(`tr`,{children:[(0,V.jsx)(`th`,{children:`Candidate arm`}),(0,V.jsx)(`th`,{children:`Matched denominator`}),(0,V.jsx)(`th`,{children:`Improved`}),(0,V.jsx)(`th`,{children:`Flat`}),(0,V.jsx)(`th`,{children:`Regressed`}),(0,V.jsx)(`th`,{children:`Binary transitions`})]})}),(0,V.jsxs)(`tbody`,{children:[Object.entries(e.contrasts).map(([e,t])=>(0,V.jsxs)(`tr`,{children:[(0,V.jsx)(`td`,{children:(0,V.jsx)(`strong`,{children:e})}),(0,V.jsx)(`td`,{children:t.matched_pair_denominator}),(0,V.jsx)(`td`,{className:`benchmark-positive`,children:t.primary_metric_directions.improved}),(0,V.jsx)(`td`,{children:t.primary_metric_directions.flat}),(0,V.jsx)(`td`,{className:`benchmark-negative`,children:t.primary_metric_directions.regressed}),(0,V.jsx)(`td`,{children:Object.entries(t.binary_metric_transitions).map(([e,t])=>`${e}: 0→1 ${t[`0_to_1`]}, 1→0 ${t[`1_to_0`]}, same ${t.same}`).join(` · `)||`—`})]},e)),Object.keys(e.contrasts).length===0&&(0,V.jsx)(`tr`,{children:(0,V.jsx)(`td`,{colSpan:6,children:`No matched comparisons are countable yet.`})})]})]})})]}),(0,V.jsxs)(`section`,{"aria-labelledby":`runtime-health-title`,children:[(0,V.jsxs)(`div`,{className:`benchmark-section-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`p`,{className:`benchmark-kicker`,children:`RUNTIME HEALTH`}),(0,V.jsx)(`h2`,{id:`runtime-health-title`,children:`Qualified observations, without execution authority`})]}),(0,V.jsxs)(`p`,{children:[e.campaign.runtime_observation_count,` public-safe runtime observations.`]})]}),(0,V.jsxs)(`div`,{className:`benchmark-runtime-list`,children:[Object.entries(e.campaign.runtime_classification_counts).map(([e,t])=>(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`span`,{children:e}),(0,V.jsx)(`strong`,{children:t})]},e)),e.campaign.runtime_observation_count===0&&(0,V.jsx)(`p`,{className:`benchmark-muted`,children:`No runtime observations uploaded.`})]})]})]})}function HC({packet:e}){return(0,V.jsx)(`div`,{className:`benchmark-detail-grid`,children:e.arms.map(t=>(0,V.jsxs)(`article`,{className:`benchmark-detail-card`,children:[(0,V.jsxs)(`div`,{className:`benchmark-card-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`span`,{className:`benchmark-mono`,children:t.arm_role}),(0,V.jsx)(`h2`,{children:t.arm_id})]}),(0,V.jsxs)(BC,{tone:t.coverage_rate===1?`success`:`warning`,children:[t.selected_score_countable_case_count,`/`,t.intended_case_count,` countable`]})]}),(0,V.jsx)(`div`,{className:`benchmark-factor-row`,children:Object.entries(t.factor_assignments).map(([e,t])=>(0,V.jsxs)(`span`,{children:[e,`: `,(0,V.jsx)(`strong`,{children:t})]},e))}),(0,V.jsxs)(`dl`,{className:`benchmark-stat-list`,children:[e.design.metric_catalog.map(e=>(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`dt`,{children:[e.role,` · `,e.metric_name]}),(0,V.jsx)(`dd`,{children:RC(t,e.metric_name)})]},e.metric_name)),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Runs terminal / observed`}),(0,V.jsxs)(`dd`,{children:[t.terminal_run_count,`/`,t.run_count]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Median duration`}),(0,V.jsx)(`dd`,{children:FC(t.effort.duration_ms?.median)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Protocols`}),(0,V.jsx)(`dd`,{children:IC(t.protocol_counts)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Runner revisions`}),(0,V.jsx)(`dd`,{children:IC(t.runner_revision_counts)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Orchestrator runtimes`}),(0,V.jsxs)(`dd`,{children:[Object.keys(t.orchestrator_runtime_counts).length||0,` distinct`]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Failure classes`}),(0,V.jsx)(`dd`,{children:IC(t.failure_class_counts)})]})]})]},t.arm_id))})}function UC({packet:e,primaryMetric:t,onOpenRun:n}){return(0,V.jsx)(`div`,{className:`benchmark-table-shell benchmark-wide-table`,children:(0,V.jsxs)(`table`,{children:[(0,V.jsx)(`thead`,{children:(0,V.jsxs)(`tr`,{children:[(0,V.jsx)(`th`,{children:`Case`}),(0,V.jsx)(`th`,{children:`Design status`}),(0,V.jsx)(`th`,{children:`Largest eligible delta`}),e.arms.map(e=>(0,V.jsx)(`th`,{children:e.arm_id},e.arm_id))]})}),(0,V.jsx)(`tbody`,{children:e.cases.map(r=>{let i=zC(r,t);return(0,V.jsxs)(`tr`,{children:[(0,V.jsx)(`td`,{children:(0,V.jsx)(`strong`,{children:r.case_id})}),(0,V.jsx)(`td`,{children:(0,V.jsx)(BC,{tone:r.complete_declared_design?`success`:`warning`,children:r.complete_declared_design?`Complete`:`Provisional`})}),(0,V.jsx)(`td`,{className:i?.direction===`improved`?`benchmark-positive`:i?.direction===`regressed`?`benchmark-negative`:void 0,children:i?.text??`—`}),r.arms.map(r=>(0,V.jsx)(`td`,{children:r.selected_run_id&&r.score_countable?(0,V.jsxs)(`button`,{className:`benchmark-cell-link`,onClick:()=>n(r.selected_run_id),type:`button`,children:[(0,V.jsxs)(`span`,{children:[t,`: `,LC(r.metrics[t])]}),e.design.metric_catalog.filter(e=>e.metric_name!==t).map(e=>(0,V.jsxs)(`small`,{className:`benchmark-cell-metric`,children:[e.metric_name,`: `,LC(r.metrics[e.metric_name])]},e.metric_name)),(0,V.jsxs)(`small`,{children:[`Countable · `,FC(r.effort.duration_ms),` `,(0,V.jsx)(Kp,{"aria-hidden":`true`,size:12})]}),r.insight&&(0,V.jsxs)(`small`,{children:[r.insight.failure_class,` · `,r.insight.confidence]})]}):(0,V.jsx)(`span`,{className:`benchmark-muted`,children:`Not countable`})},r.arm_id))]},r.case_id)})})]})})}function WC({run:e,packet:t}){return(0,V.jsxs)(`aside`,{"aria-label":`Run detail for ${e.run_id}`,className:`benchmark-run-detail`,children:[(0,V.jsxs)(`div`,{className:`benchmark-card-heading`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`span`,{className:`benchmark-mono`,children:`RUN DETAIL`}),(0,V.jsx)(`h2`,{children:e.run_id})]}),(0,V.jsx)(BC,{tone:e.countability.score_countable?`success`:`warning`,children:e.countability.score_countable?`Score-countable`:`Diagnostic only`})]}),(0,V.jsxs)(`dl`,{className:`benchmark-stat-list benchmark-run-facts`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Case / arm`}),(0,V.jsxs)(`dd`,{children:[e.case_id,` · `,e.arm_id]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Lifecycle`}),(0,V.jsxs)(`dd`,{children:[e.status,` · `,e.observed_at]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Protocol`}),(0,V.jsx)(`dd`,{children:e.protocol_id})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Qualification`}),(0,V.jsxs)(`dd`,{children:[`Integrity `,e.countability.integrity_qualified?`qualified`:`not qualified`,` · result `,e.countability.official_result_present?`present`:`missing`]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Treatment fidelity`}),(0,V.jsx)(`dd`,{children:e.treatment_fidelity})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Effort`}),(0,V.jsxs)(`dd`,{children:[FC(e.effort.duration_ms),` · `,PC(e.effort.agent_steps),` steps · `,PC(e.effort.token_count),` tokens`]})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Runner revision`}),(0,V.jsx)(`dd`,{children:e.runner_revision??`—`})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Upload provenance`}),(0,V.jsxs)(`dd`,{children:[e.upload_provenance.producer_id,` · `,e.upload_provenance.source_revision]})]})]}),(0,V.jsx)(`div`,{className:`benchmark-run-metrics`,children:t.design.metric_catalog.map(t=>(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`span`,{children:t.metric_name}),(0,V.jsx)(`strong`,{children:LC(e.metrics[t.metric_name])})]},t.metric_name))}),e.redacted_insight&&(0,V.jsxs)(`div`,{className:`benchmark-insight`,children:[(0,V.jsxs)(`span`,{className:`benchmark-mono`,children:[`REDACTED CASE INSIGHT · `,e.redacted_insight.confidence]}),(0,V.jsx)(`p`,{children:e.redacted_insight.causal_summary}),(0,V.jsxs)(`small`,{children:[`Implication: `,e.redacted_insight.implication]}),(0,V.jsx)(`br`,{}),(0,V.jsxs)(`small`,{children:[`Next probe: `,e.redacted_insight.next_probe]}),!!e.redacted_insight.evidence_refs?.length&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`br`,{}),(0,V.jsxs)(`small`,{children:[`Evidence: `,e.redacted_insight.evidence_refs.join(`, `)]})]})]})]})}function GC({packet:e,selectedRunId:t,onSelectRun:n}){let r=e.runs.find(e=>e.run_id===t)??e.runs[0];return(0,V.jsxs)(`div`,{className:`benchmark-runs-layout`,children:[(0,V.jsx)(`div`,{className:`benchmark-table-shell`,children:(0,V.jsxs)(`table`,{children:[(0,V.jsx)(`thead`,{children:(0,V.jsxs)(`tr`,{children:[(0,V.jsx)(`th`,{children:`Run`}),(0,V.jsx)(`th`,{children:`Case`}),(0,V.jsx)(`th`,{children:`Arm`}),(0,V.jsx)(`th`,{children:`Status`}),(0,V.jsx)(`th`,{children:`Countability`})]})}),(0,V.jsx)(`tbody`,{children:e.runs.map(e=>(0,V.jsxs)(`tr`,{"aria-selected":e.run_id===r?.run_id,children:[(0,V.jsx)(`td`,{children:(0,V.jsx)(`button`,{className:`benchmark-run-link`,onClick:()=>n(e.run_id),type:`button`,children:e.run_id})}),(0,V.jsx)(`td`,{children:e.case_id}),(0,V.jsx)(`td`,{children:e.arm_id}),(0,V.jsx)(`td`,{children:e.status}),(0,V.jsx)(`td`,{children:e.countability.score_countable?`Score-countable`:`Diagnostic only`})]},e.run_id))})]})}),r&&(0,V.jsx)(WC,{packet:e,run:r})]})}function KC(){let e=sw.useSearch(),t=sw.useNavigate(),[n,r]=(0,B.useState)(null),[i,a]=(0,B.useState)(null),[o,s]=(0,B.useState)(0),c=(0,B.useMemo)(()=>{let t=e.dashboardUrl||`/chat/benchmark-study.example.json`;try{return{url:jC(t,window.location.href),error:null}}catch(e){return{url:``,error:e instanceof Error?e.message:`Invalid dashboard source`}}},[e.dashboardUrl]);if((0,B.useEffect)(()=>{let e=!0;return r(null),a(null),c.error?(a(c.error),()=>{e=!1}):(fetch(c.url,{cache:`no-store`}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status} while loading the dashboard packet`);return AC(await e.json())}).then(t=>{e&&r(t)}).catch(t=>{e&&a(t instanceof Error?t.message:`Unable to load dashboard packet`)}),()=>{e=!1})},[o,c]),(0,B.useEffect)(()=>{n&&(document.title=`${n.design.labels.title??n.study_id} · LoopX Benchmark`)},[n]),i)return(0,V.jsxs)(`main`,{className:`benchmark-page benchmark-loading`,children:[(0,V.jsx)(im,{"aria-hidden":`true`}),(0,V.jsx)(`h1`,{children:`Dashboard packet unavailable`}),(0,V.jsx)(`p`,{children:i}),(0,V.jsxs)(`button`,{onClick:()=>s(e=>e+1),type:`button`,children:[(0,V.jsx)(Im,{"aria-hidden":`true`,size:16}),` Retry readback`]})]});if(!n)return(0,V.jsxs)(`main`,{"aria-busy":`true`,className:`benchmark-page benchmark-loading`,children:[(0,V.jsx)(Up,{"aria-hidden":`true`}),(0,V.jsx)(`h1`,{children:`Reading benchmark study`}),(0,V.jsx)(`p`,{children:`Validating the public-safe dashboard packet…`})]});let l=n.design.metric_catalog.find(e=>e.role===`primary`)?.metric_name??`primary`,u=(n,r=e.runId)=>t({search:e=>({...e,view:n,runId:r})}),d=new URL(c.url).pathname;return(0,V.jsxs)(`main`,{className:`benchmark-page`,children:[(0,V.jsxs)(`header`,{className:`benchmark-hero`,children:[(0,V.jsxs)(`div`,{className:`benchmark-hero-topline`,children:[(0,V.jsx)(`a`,{className:`benchmark-wordmark`,href:`/chat/`,children:`LoopX`}),(0,V.jsxs)(`div`,{className:`benchmark-readonly`,children:[(0,V.jsx)(Wm,{"aria-hidden":`true`,size:15}),` Derived read-only projection`]})]}),(0,V.jsxs)(`div`,{className:`benchmark-hero-grid`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`p`,{className:`benchmark-kicker`,children:[`BENCHMARK STUDY / `,n.benchmark_id]}),(0,V.jsxs)(`div`,{className:`benchmark-title-row`,children:[(0,V.jsx)(`h1`,{children:n.design.labels.title??n.study_id}),(0,V.jsx)(BC,{tone:n.status===`complete`?`success`:`warning`,children:n.status})]}),(0,V.jsx)(`p`,{className:`benchmark-lead`,children:`One declared study, explicit denominators, and the same countability rules from campaign summary to exact run.`})]}),(0,V.jsxs)(`dl`,{className:`benchmark-identity`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Study`}),(0,V.jsx)(`dd`,{children:n.study_id})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Protocol`}),(0,V.jsx)(`dd`,{children:n.design.protocol_id})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{children:`Case set`}),(0,V.jsx)(`dd`,{children:n.design.case_set.case_set_id})]})]})]}),(0,V.jsxs)(`div`,{className:`benchmark-kpi-grid`,children:[(0,V.jsxs)(`article`,{children:[(0,V.jsx)(lm,{"aria-hidden":`true`}),(0,V.jsx)(`span`,{children:`Score-countable cells`}),(0,V.jsxs)(`strong`,{children:[n.campaign.selected_score_countable_cell_count,(0,V.jsxs)(`small`,{children:[` / `,n.campaign.intended_cell_denominator]})]}),(0,V.jsxs)(`p`,{children:[NC(n.campaign.selected_score_countable_coverage_rate),` declared coverage`]})]}),(0,V.jsxs)(`article`,{children:[(0,V.jsx)(am,{"aria-hidden":`true`}),(0,V.jsx)(`span`,{children:`Complete designs`}),(0,V.jsxs)(`strong`,{children:[n.campaign.complete_declared_design_case_count,(0,V.jsxs)(`small`,{children:[` / `,n.campaign.intended_case_count]})]}),(0,V.jsx)(`p`,{children:`Cases with every declared arm`})]}),(0,V.jsxs)(`article`,{children:[(0,V.jsx)(Kp,{"aria-hidden":`true`}),(0,V.jsx)(`span`,{children:`Matched comparisons`}),(0,V.jsx)(`strong`,{children:n.campaign.matched_pair_countable_count}),(0,V.jsx)(`p`,{children:`Eligible pairs only`})]}),(0,V.jsxs)(`article`,{children:[(0,V.jsx)(Up,{"aria-hidden":`true`}),(0,V.jsx)(`span`,{children:`In flight`}),(0,V.jsx)(`strong`,{children:n.campaign.in_flight_run_count}),(0,V.jsx)(`p`,{children:n.status===`provisional`?`Coverage remains provisional`:`Declared coverage complete`})]})]})]}),(0,V.jsxs)(`nav`,{"aria-label":`Benchmark dashboard views`,className:`benchmark-tabs`,children:[MC.map(t=>(0,V.jsx)(`button`,{"aria-current":e.view===t.id?`page`:void 0,onClick:()=>u(t.id),type:`button`,children:t.label},t.id)),(0,V.jsxs)(`button`,{className:`benchmark-refresh`,onClick:()=>s(e=>e+1),type:`button`,children:[(0,V.jsx)(Im,{"aria-hidden":`true`,size:14}),` Refresh local readback`]})]}),(0,V.jsxs)(`div`,{className:`benchmark-content`,children:[e.view===`campaign`&&(0,V.jsx)(VC,{packet:n,primaryMetric:l}),e.view===`arms`&&(0,V.jsx)(HC,{packet:n}),e.view===`cases`&&(0,V.jsx)(UC,{onOpenRun:e=>u(`runs`,e),packet:n,primaryMetric:l}),e.view===`runs`&&(0,V.jsx)(GC,{onSelectRun:e=>u(`runs`,e),packet:n,selectedRunId:e.runId})]}),(0,V.jsxs)(`footer`,{className:`benchmark-footer`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(Wm,{"aria-hidden":`true`,size:16}),(0,V.jsxs)(`span`,{children:[`Scores: `,n.authority.score_source]}),(0,V.jsx)(`span`,{children:`Dashboard cannot launch, grade, or mutate runs.`})]}),(0,V.jsxs)(`code`,{title:d,children:[`local`,d]})]})]})}var qC=Y({goalId:G().optional().default(``),statusUrl:G().optional().default(``)}),JC=Y({goalId:G().optional().default(``),mode:_d([`showcase`,`developer`,`ops`]).optional().default(`showcase`),statusUrl:G().optional().default(``),todoLane:_d([`all`,`user`,`agent`]).optional().default(`all`),todoQuery:G().optional().default(``)}),YC=JC.omit({mode:!0}),XC=Y({dashboardUrl:G().optional().default(``),view:_d([`campaign`,`arms`,`cases`,`runs`]).optional().default(`campaign`),runId:G().optional().default(``)});function ZC(){let e=`https://huangruiteng.github.io/loopx/docs/showcases/index.en.html`;return(0,B.useEffect)(()=>{window.location.replace(e)},[]),(0,V.jsx)(`a`,{href:e,children:`Open LoopX cases / 浏览案例`})}function QC({goalId:e,statusUrl:t}){let n=t?rh(t,window.location.href):null;return n?.error?(0,V.jsx)(`main`,{role:`alert`,children:n.error}):(0,V.jsx)(ri,{replace:!0,to:`/`,search:{goalId:e,statusUrl:t}})}function $C(){let e=rw.useSearch();return e.mode===`ops`?(0,V.jsx)(QC,{...e}):e.mode===`developer`?(0,V.jsx)(ri,{replace:!0,to:`/developers/projections`}):(0,V.jsx)(ZC,{})}function ew(){return(0,V.jsx)(QC,{...iw.useSearch()})}var tw=Si({component:()=>(0,V.jsx)(ji,{}),errorComponent:()=>(0,V.jsxs)(`main`,{role:`alert`,className:`p-8`,children:[(0,V.jsx)(`h1`,{children:`页面暂时无法显示 / Page unavailable`}),(0,V.jsx)(`p`,{children:`请重新加载页面;这不会执行任务。 / Reloading does not execute tasks.`}),(0,V.jsx)(`button`,{type:`button`,onClick:()=>window.location.reload(),children:`重新加载 / Reload`})]})}),nw=bi({getParentRoute:()=>tw,path:`/`,validateSearch:e=>qC.parse(e),component:aC}),rw=bi({getParentRoute:()=>tw,path:`/frontstage`,validateSearch:e=>JC.parse(e),component:$C}),iw=bi({getParentRoute:()=>tw,path:`/deprecated/frontstage/ops`,validateSearch:e=>YC.parse(e),component:ew}),aw=bi({getParentRoute:()=>tw,path:`/frontstage/developer`,component:()=>(0,V.jsx)(ri,{replace:!0,to:`/developers/projections`})}),ow=bi({getParentRoute:()=>tw,path:`/developers/projections`,component:yC}),sw=bi({getParentRoute:()=>tw,path:`/benchmarks/study`,validateSearch:e=>XC.parse(e),component:KC}),cw=tw.addChildren([nw,rw,iw,aw,ow,sw]);function lw(e){return!e||e===`/`||e===`./`?`/`:(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}var uw=Ii({routeTree:cw,basepath:lw(`/chat/`),trailingSlash:`preserve`}),dw=document.getElementById(`root`);if(!dw)throw Error(`Root element not found`);var fw=new ke({defaultOptions:{queries:{refetchOnWindowFocus:!1,retry:1,staleTime:1e4}}});(0,Bi.createRoot)(dw).render((0,V.jsx)(Ne,{client:fw,children:(0,V.jsx)(Ki,{children:(0,V.jsx)(zi,{router:uw})})})); \ No newline at end of file diff --git a/loopx/web/chat/assets/index-uHL7gp0q.js b/loopx/web/chat/assets/index-uHL7gp0q.js new file mode 100644 index 0000000000..aaa77a41f1 --- /dev/null +++ b/loopx/web/chat/assets/index-uHL7gp0q.js @@ -0,0 +1,129 @@ +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,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},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,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),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var l=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&&ne(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&&ne(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var ee=new MessageChannel,te=ee.port2;ee.port1.onmessage=D,O=function(){te.postMessage(null)}}else O=function(){_(D,0)};function ne(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,ne(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}}}})),u=o(((e,t)=>{t.exports=l()})),d=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 ee(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var te=/\/+/g;function ne(e,t){return typeof e==`object`&&e&&e.key!=null?ee(``+e.key):t.toString(36)}function k(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 A(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,A(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+ne(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(te,`$&/`)+`/`),A(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(te,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{t.exports=d()})),p=o((e=>{var t=f();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=p()})),h=o((e=>{var t=u(),n=f(),r=m();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=I(null),se=I(null),ce=I(null),le=I(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)?Wd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Wd(t),e=Gd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}ae(oe),L(oe,e)}function de(){ae(oe),ae(se),ae(ce)}function fe(e){e.memoizedState!==null&&L(le,e);var t=oe.current,n=Gd(t,e.type);t!==n&&(L(se,e),L(oe,n))}function pe(e){se.current===e&&(ae(oe),ae(se)),le.current===e&&(ae(le),tp._currentValue=F)}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,R=t.unstable_getCurrentPriorityLevel,De=t.unstable_ImmediatePriority,Oe=t.unstable_UserBlockingPriority,ke=t.unstable_NormalPriority,Ae=t.unstable_LowPriority,je=t.unstable_IdlePriority,Me=t.log,z=t.unstable_setDisableYieldValue,B=null,Ne=null;function Pe(e){if(typeof Me==`function`&&z(e),Ne&&typeof Ne.setStrictMode==`function`)try{Ne.setStrictMode(B,e)}catch{}}var Fe=Math.clz32?Math.clz32:Le,V=Math.log,Ie=Math.LN2;function Le(e){return e>>>=0,e===0?32:31-(V(e)/Ie|0)|0}var Re=256,ze=262144,Be=4194304;function Ve(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 He(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=Ve(n))):i=Ve(o):i=Ve(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=Ve(n))):i=Ve(o)):i=Ve(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 Ue(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function We(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 Ge(){var e=Be;return Be<<=1,!(Be&62914560)&&(Be=4194304),e}function Ke(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function qe(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Je(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),sn=!1;if(on)try{var cn={};Object.defineProperty(cn,"passive",{get:function(){sn=!0}}),window.addEventListener(`test`,cn,cn),window.removeEventListener(`test`,cn,cn)}catch{sn=!1}var ln=null,un=null,dn=null;function fn(){if(dn)return dn;var e,t=un,n=t.length,r,i=`value`in ln?ln.value:ln.textContent,a=i.length;for(e=0;e=Wn),qn=` `,Jn=!1;function Yn(e,t){switch(e){case`keyup`:return Hn.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Xn(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Zn=!1;function Qn(e,t){switch(e){case`compositionend`:return Xn(t);case`keypress`:return t.which===32?(Jn=!0,qn):null;case`textInput`:return e=t.data,e===qn&&Jn?null:e;default:return null}}function $n(e,t){if(Zn)return e===`compositionend`||!Un&&Yn(e,t)?(e=fn(),dn=un=ln=null,Zn=!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=xr(n)}}function Cr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Cr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function wr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Nt(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=Nt(e.document)}return t}function Tr(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 Er=on&&`documentMode`in document&&11>=document.documentMode,Dr=null,Or=null,kr=null,Ar=!1;function jr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ar||Dr==null||Dr!==Nt(r)||(r=Dr,`selectionStart`in r&&Tr(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}),kr&&br(kr,r)||(kr=r,r=Od(Or,`onSelect`),0>=o,i-=o,Ci=1<<32-Fe(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),Mi&&Ti(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),Mi&&Ti(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 Mi&&Ti(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)}),Mi&&Ti(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&&wa(l)===r.type){n(e,r.sibling),c=a(r,o.props),ja(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===y?(c=ui(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=li(o.type,o.key,o.props,null,e.mode,c),ja(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}n(e,r);break}t(e,r),r=r.sibling}c=pi(o,e.mode,c),c.return=e,e=c}return s(e);case O:return o=wa(o),b(e,r,o,c)}if(M(o))return h(e,r,o,c);if(k(o)){if(l=k(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,Aa(o),c);if(o.$$typeof===C)return b(e,r,$i(e,o),c);Ma(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=di(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{ka=0;var i=b(e,t,n,r);return Oa=null,i}catch(t){if(t===ya||t===xa)throw t;var a=ai(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Pa=Na(!0),Fa=Na(!1),Ia=!1;function La(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ra(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 za(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Ba(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Vl&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=ni(e),ti(e,null,n),t}return Qr(e,r,t,n),ni(e)}function Va(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,Xe(e,n)}}function Ha(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 Ua=!1;function Wa(){if(Ua){var e=ua;if(e!==null)throw e}}function Ga(e,t,n,r){Ua=!1;var i=e.updateQueue;Ia=!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?(Wl&f)===f:(r&f)===f){f!==0&&f===la&&(Ua=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(m=g.payload,typeof m==`function`){d=m.call(_,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=g.payload,f=typeof m==`function`?m.call(_,d,f):m,f==null)break a;d=h({},d,f);break a;case 2:Ia=!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 Ka(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function qa(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=N.T,s={};N.T=s,Ps(e,!1,t,n);try{var c=i(),l=N.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Ns(e,t,pa(c,r),bu(e)):Ns(e,t,r,bu(e))}catch(n){Ns(e,t,{then:function(){},status:`rejected`,reason:n},bu())}finally{P.p=a,o!==null&&s.types!==null&&(o.types=s.types),N.T=o}}function Cs(){}function ws(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=Ts(e).queue;Ss(e,a,t,F,n===null?Cs:function(){return Es(e),n(r)})}function Ts(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:F,baseState:F,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fo,lastRenderedState:F},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fo,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Es(e){var t=Ts(e);t.next===null&&(t=e.alternate.memoizedState),Ns(e,t.next.queue,{},bu())}function Ds(){return H(tp)}function Os(){return Ao().memoizedState}function ks(){return Ao().memoizedState}function As(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=bu();e=za(n);var r=Ba(t,e,n);r!==null&&(Su(r,t,n),Va(r,t,n)),t={cache:aa()},e.payload=t;return}t=t.return}}function js(e,t,n){var r=bu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Fs(e)?Is(t,n):(n=$r(e,t,n,r),n!==null&&(Su(n,e,r),Ls(n,t,r)))}function Ms(e,t,n){Ns(e,t,n,bu())}function Ns(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Fs(e))Is(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,yr(s,o))return Qr(e,t,i,0),Hl===null&&Zr(),!1}catch{}if(n=$r(e,t,i,r),n!==null)return Su(n,e,r),Ls(n,t,r),!0}return!1}function Ps(e,t,n,r){if(r={lane:2,revertLane:md(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Fs(e)){if(t)throw Error(i(479))}else t=$r(e,n,r,2),t!==null&&Su(t,e,2)}function Fs(e){var t=e.alternate;return e===lo||t!==null&&t===lo}function Is(e,t){mo=po=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Ls(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Xe(e,n)}}var Rs={readContext:H,use:No,useCallback:bo,useContext:bo,useEffect:bo,useImperativeHandle:bo,useLayoutEffect:bo,useInsertionEffect:bo,useMemo:bo,useReducer:bo,useRef:bo,useState:bo,useDebugValue:bo,useDeferredValue:bo,useTransition:bo,useSyncExternalStore:bo,useId:bo,useHostTransitionStatus:bo,useFormState:bo,useActionState:bo,useOptimistic:bo,useMemoCache:bo,useCacheRefresh:bo};Rs.useEffectEvent=bo;var zs={readContext:H,use:No,useCallback:function(e,t){return ko().memoizedState=[e,t===void 0?null:t],e},useContext:H,useEffect:ls,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),ss(4194308,4,hs.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ss(4194308,4,e,t)},useInsertionEffect:function(e,t){ss(4,2,e,t)},useMemo:function(e,t){var n=ko();t=t===void 0?null:t;var r=e();if(ho){Pe(!0);try{e()}finally{Pe(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=ko();if(n!==void 0){var i=n(t);if(ho){Pe(!0);try{n(t)}finally{Pe(!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=js.bind(null,lo,e),[r.memoizedState,e]},useRef:function(e){var t=ko();return e={current:e},t.memoizedState=e},useState:function(e){e=Go(e);var t=e.queue,n=Ms.bind(null,lo,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:_s,useDeferredValue:function(e,t){return bs(ko(),e,t)},useTransition:function(){var e=Go(!1);return e=Ss.bind(null,lo,e.queue,!0,!1),ko().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=lo,a=ko();if(Mi){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Hl===null)throw Error(i(349));Wl&127||Bo(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,ls(Ho.bind(null,r,o,e),[e]),r.flags|=2048,as(9,{destroy:void 0},Vo.bind(null,r,o,n,t),null),n},useId:function(){var e=ko(),t=Hl.identifierPrefix;if(Mi){var n=wi,r=Ci;n=(r&~(1<<32-Fe(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=go++,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(Ld(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&&Nc(t)}}return Rc(t),Pc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Nc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=ce.current,zi(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=Ai,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[rt]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Pd(e.nodeValue,n)),e||Ii(t,!0)}else e=Ud(e).createTextNode(r),e[rt]=t,t.stateNode=e}return Rc(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=zi(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 Bi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Rc(t),e=!1}else n=Vi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(ao(t),t):(ao(t),null);if(t.flags&128)throw Error(i(558))}return Rc(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=zi(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 Bi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Rc(t),a=!1}else a=Vi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(ao(t),t):(ao(t),null)}return ao(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),Ic(t,t.updateQueue),Rc(t),null);case 4:return de(),e===null&&wd(t.stateNode.containerInfo),Rc(t),null;case 10:return qi(t.type),Rc(t),null;case 19:if(ae(oo),r=t.memoizedState,r===null)return Rc(t),null;if(a=!!(t.flags&128),o=r.rendering,o===null){if(a)Lc(r,!1);else{if(Zl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=so(e),o!==null){for(t.flags|=128,Lc(r,!1),e=o.updateQueue,t.updateQueue=e,Ic(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)ci(n,e),n=n.sibling;return L(oo,oo.current&1|2),Mi&&Ti(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ee()>cu&&(t.flags|=128,a=!0,Lc(r,!1),t.lanes=4194304)}}else{if(!a){if(e=so(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Ic(t,e),Lc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!Mi)return Rc(t),null}else 2*Ee()-r.renderingStartTime>cu&&n!==536870912&&(t.flags|=128,a=!0,Lc(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?(Rc(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ee(),e.sibling=null,n=oo.current,L(oo,a?n&1|2:n&1),Mi&&Ti(t,r.treeForkCount),e);case 22:case 23:return ao(t),Qa(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Rc(t),t.subtreeFlags&6&&(t.flags|=8192)):Rc(t),n=t.updateQueue,n!==null&&Ic(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&&ae(ha),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),qi(ia),Rc(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function Bc(e,t){switch(Oi(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return qi(ia),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(ao(t),t.alternate===null)throw Error(i(340));Bi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(ao(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));Bi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ae(oo),null;case 4:return de(),null;case 10:return qi(t.type),null;case 22:case 23:return ao(t),Qa(),e!==null&&ae(ha),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return qi(ia),null;case 25:return null;default:return null}}function Vc(e,t){switch(Oi(t),t.tag){case 3:qi(ia),de();break;case 26:case 27:case 5:pe(t);break;case 4:de();break;case 31:t.memoizedState!==null&&ao(t);break;case 13:ao(t);break;case 19:ae(oo);break;case 10:qi(t.type);break;case 22:case 23:ao(t),Qa(),e!==null&&ae(ha);break;case 24:qi(ia)}}function Hc(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){Zu(t,t.return,e)}}function Uc(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){Zu(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Zu(t,t.return,e)}}function Wc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{qa(t,n)}catch(t){Zu(e,e.return,t)}}}function Gc(e,t,n){n.props=Ks(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Zu(e,t,n)}}function Kc(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){Zu(e,t,n)}}function qc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){Zu(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){Zu(e,t,n)}else n.current=null}}function Jc(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){Zu(e,e.return,t)}}function Yc(e,t,n){try{var r=e.stateNode;Rd(r,e.type,n,t),r[it]=t}catch(t){Zu(e,e.return,t)}}function Xc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&ef(e.type)||e.tag===4}function Zc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Xc(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&&ef(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 Qc(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=Xt));else if(r!==4&&(r===27&&ef(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Qc(e,t,n),e=e.sibling;e!==null;)Qc(e,t,n),e=e.sibling}function $c(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&&ef(e.type)&&(n=e.stateNode),e=e.child,e!==null))for($c(e,t,n),e=e.sibling;e!==null;)$c(e,t,n),e=e.sibling}function el(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Ld(t,r,n),t[rt]=e,t[it]=n}catch(t){Zu(e,e.return,t)}}var tl=!1,nl=!1,rl=!1,il=typeof WeakSet==`function`?WeakSet:Set,al=null;function ol(e,t){if(e=e.containerInfo,Vd=up,e=wr(e),Tr(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(Hd={focusedElem:e,selectionRange:n},up=!1,al=t;al!==null;)if(t=al,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,al=e;else for(;al!==null;){switch(t=al,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`))),Ld(o,r,n),o[rt]=e,gt(o),r=o;break a;case`link`:var s=Wf(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=Sr(s,h),v=Sr(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,N.T=null,n=gu,gu=null;var o=fu,s=mu;if(du=0,pu=fu=null,mu=0,Vl&6)throw Error(i(331));var c=Vl;if(Vl|=4,Il(o.current),Ol(o,o.current,s,n),Vl=c,cd(0,!1),Ne&&typeof Ne.onPostCommitFiberRoot==`function`)try{Ne.onPostCommitFiberRoot(B,o)}catch{}return!0}finally{P.p=a,N.T=r,qu(e,t)}}function Xu(e,t,n){t=hi(n,t),t=Qs(e.stateNode,t,2),e=Ba(e,t,2),e!==null&&(qe(e,2),q(e))}function Zu(e,t,n){if(e.tag===3)Xu(e,e,n);else for(;t!==null;){if(t.tag===3){Xu(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(uu===null||!uu.has(r))){e=hi(n,e),n=$s(2),r=Ba(t,n,2),r!==null&&(ec(n,r,t,e),qe(r,2),q(r));break}}t=t.return}}function G(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Bl;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)||(Yl=!0,i.add(n),e=Qu.bind(null,e,t,n),t.then(e,e))}function Qu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Hl===e&&(Wl&n)===n&&(Zl===4||Zl===3&&(Wl&62914560)===Wl&&300>Ee()-ou?!(Vl&2)&&ku(e,0):eu|=n,nu===Wl&&(nu=0)),q(e)}function $u(e,t){t===0&&(t=Ge()),e=ei(e,t),e!==null&&(qe(e,t),q(e))}function ed(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),$u(e,n)}function K(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),$u(e,n)}function td(e,t){return Se(e,t)}var nd=null,rd=null,id=!1,ad=!1,od=!1,sd=0;function q(e){e!==rd&&e.next===null&&(rd===null?nd=rd=e:rd=rd.next=e),ad=!0,id||(id=!0,pd())}function cd(e,t){if(!od&&ad){od=!0;do for(var n=!1,r=nd;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-Fe(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=Wl,a=He(r,r===Hl?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||Ue(r,a)||(n=!0,fd(r,a))}r=r.next}while(n);od=!1}}function J(){ld()}function ld(){ad=id=!1;var e=0;sd!==0&&Jd()&&(e=sd);for(var t=Ee(),n=null,r=nd;r!==null;){var i=r.next,a=ud(r,t);a===0?(r.next=null,n===null?nd=i:n.next=i,i===null&&(rd=n)):(n=r,(e!==0||a&3)&&(ad=!0)),r=i}du!==0&&du!==5||cd(e,!1),sd!==0&&(sd=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&&zd(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function wf(e,t,n){var r=Cf;if(r&&typeof t==`string`&&t){var i=Ft(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),vf.has(i)||(vf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Ld(t,`link`,e),gt(t),r.head.appendChild(t)))}}function Tf(e){bf.D(e),wf(`dns-prefetch`,e,null)}function Ef(e,t){bf.C(e,t),wf(`preconnect`,e,t)}function Df(e,t,n){bf.L(e,t,n);var r=Cf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Ft(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Ft(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Ft(n.imageSizes)+`"]`)):i+=`[href="`+Ft(e)+`"]`;var a=i;switch(t){case`style`:a=Nf(e);break;case`script`:a=Lf(e)}_f.has(a)||(e=h({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),_f.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Pf(a))||t===`script`&&r.querySelector(Rf(a))||(t=r.createElement(`link`),Ld(t,`link`,e),gt(t),r.head.appendChild(t)))}}function Of(e,t){bf.m(e,t);var n=Cf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Ft(r)+`"][href="`+Ft(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Lf(e)}if(!_f.has(a)&&(e=h({rel:`modulepreload`,href:e},t),_f.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(Rf(a)))return}r=n.createElement(`link`),Ld(r,`link`,e),gt(r),n.head.appendChild(r)}}}function kf(e,t,n){bf.S(e,t,n);var r=Cf;if(r&&e){var i=ht(r).hoistableStyles,a=Nf(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Pf(a)))s.loading=5;else{e=h({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=_f.get(a))&&Vf(e,n);var c=o=r.createElement(`link`);gt(c),Ld(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,Bf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Af(e,t){bf.X(e,t);var n=Cf;if(n&&e){var r=ht(n).hoistableScripts,i=Lf(e),a=r.get(i);a||(a=n.querySelector(Rf(i)),a||(e=h({src:e,async:!0},t),(t=_f.get(i))&&Hf(e,t),a=n.createElement(`script`),gt(a),Ld(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function jf(e,t){bf.M(e,t);var n=Cf;if(n&&e){var r=ht(n).hoistableScripts,i=Lf(e),a=r.get(i);a||(a=n.querySelector(Rf(i)),a||(e=h({src:e,async:!0,type:`module`},t),(t=_f.get(i))&&Hf(e,t),a=n.createElement(`script`),gt(a),Ld(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Mf(e,t,n,r){var a=(a=ce.current)?yf(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=Nf(n.href),n=ht(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=Nf(n.href);var o=ht(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(Pf(e)))&&!o._p&&(s.instance=o,s.state.loading=5),_f.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},_f.set(e,n),o||If(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=Lf(n),n=ht(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 Nf(e){return`href="`+Ft(e)+`"`}function Pf(e){return`link[rel="stylesheet"][`+e+`]`}function Ff(e){return h({},e,{"data-precedence":e.precedence,precedence:null})}function If(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}),Ld(t,`link`,n),gt(t),e.head.appendChild(t))}function Lf(e){return`[src="`+Ft(e)+`"]`}function Rf(e){return`script[async]`+e}function zf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Ft(n.href)+`"]`);if(r)return t.instance=r,gt(r),r;var a=h({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),gt(r),Ld(r,`style`,a),Bf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Nf(n.href);var o=e.querySelector(Pf(a));if(o)return t.state.loading|=4,t.instance=o,gt(o),o;r=Ff(n),(a=_f.get(a))&&Vf(r,a),o=(e.ownerDocument||e).createElement(`link`),gt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Ld(o,`link`,r),t.state.loading|=4,Bf(o,n.precedence,e),t.instance=o;case`script`:return o=Lf(n.src),(a=e.querySelector(Rf(o)))?(t.instance=a,gt(a),a):(r=n,(a=_f.get(o))&&(r=h({},n),Hf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),gt(a),Ld(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,Bf(r,n.precedence,e));return t.instance}function Bf(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 Kf(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 qf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Jf(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=Nf(r.href),a=t.querySelector(Pf(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Zf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,gt(a);return}a=t.ownerDocument||t,r=Ff(r),(i=_f.get(i))&&Vf(r,i),a=a.createElement(`link`),gt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Ld(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=Zf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Yf=0;function Xf(e,t){return e.stylesheets&&e.count===0&&$f(e,e.stylesheets),0Yf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Zf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)$f(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Qf=null;function $f(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Qf=new Map,t.forEach(ep,e),Qf=null,Zf.call(e))}function ep(e,t){if(!(t.state.loading&4)){var n=Qf.get(e);if(n)var r=n.get(null);else{n=new Map,Qf.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=h()})),_=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},v=new class extends _{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},y={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},b=new class{#e=y;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function x(e){setTimeout(e,0)}var S=typeof window>`u`||`Deno`in globalThis;function C(){}function w(e,t){return typeof e==`function`?e(t):e}function T(e){return typeof e==`number`&&e>=0&&e!==1/0}function E(e,t){return Math.max(e+(t||0)-Date.now(),0)}function D(e,t){return typeof e==`function`?e(t):e}function O(e,t){return typeof e==`function`?e(t):e}function ee(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==ne(o,t.options))return!1}else if(!A(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function te(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(k(t.options.mutationKey)!==k(a))return!1}else if(!A(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function ne(e,t){return(t?.queryKeyHashFn||k)(e)}function k(e){return JSON.stringify(e,(e,t)=>P(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function A(e,t){return e===t?!0:typeof e==typeof t&&e&&t&&typeof e==`object`&&typeof t==`object`?Object.keys(t).every(n=>A(e[n],t[n])):!1}var j=Object.prototype.hasOwnProperty;function M(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=N(e)&&N(t);if(!r&&!(P(e)&&P(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l{b.setTimeout(t,e)})}function ie(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:M(e,t)}function I(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ae(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var L=Symbol();function oe(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===L?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function se(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var ce=(()=>{let e=()=>S;return{isServer(){return e()},setIsServer(t){e=t}}})();function le(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var ue=x;function de(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=ue,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var fe=de(),pe=new class extends _{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function me(e){return Math.min(1e3*2**e,3e4)}function he(e){return(e??`online`)!==`online`||pe.isOnline()}var ge=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function _e(e){let t=!1,n=0,r,i=le(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new ge(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>v.isFocused()&&(e.networkMode===`always`||pe.isOnline())&&e.canRun(),u=()=>he(e.networkMode)&&e.canRun(),d=e=>{a()||(r?.(),i.resolve(e))},f=e=>{a()||(r?.(),i.reject(e))},p=()=>new Promise(t=>{r=e=>{(a()||l())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),m=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(d).catch(r=>{if(a())return;let i=e.retry??(ce.isServer()?0:3),o=e.retryDelay??me,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&nl()?void 0:p()).then(()=>{t?f(r):m()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:u,start:()=>(u()?m():p().then(m),i)}}var ve=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),T(this.gcTime)&&(this.#e=b.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ce.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(b.clearTimeout(this.#e),this.#e=void 0)}};function ye(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{se(e,()=>t.signal,()=>n=!0)},u=oe(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?ae:I;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?xe:be,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:be(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(ct.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function be(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function xe(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var Se=class extends ve{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Te(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Te(this.options);e.data!==void 0&&(this.setState(we(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=ie(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(C).catch(C):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>O(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===L||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>D(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!E(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#a&&(this.#s||this.#c()?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}#c(){return this.state.fetchStatus===`paused`&&this.state.status===`pending`}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=oe(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?ye(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta}),this.#a=_e({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof ge&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#a.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof ge){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...Ce(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...we(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),fe.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Ce(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:he(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function we(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Te(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Ee=class extends ve{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||R(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=_e({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});let r=this.state.status===`pending`,i=!this.#r.canStart();try{if(r)t();else{this.#i({type:`pending`,variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:i})}let a=await this.#r.start();return await this.#n.config.onSuccess?.(a,e,this.state.context,this,n),await this.options.onSuccess?.(a,e,this.state.context,n),await this.#n.config.onSettled?.(a,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(a,null,e,this.state.context,n),this.#i({type:`success`,data:a}),a}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),fe.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function R(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var De=class extends _{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){let r=new Ee({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=Oe(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=Oe(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=Oe(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=Oe(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){fe.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>te(t,e))}findAll(e={}){return this.getAll().filter(t=>te(e,t))}notify(e){fe.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return fe.batch(()=>Promise.all(e.map(e=>e.continue().catch(C))))}};function Oe(e){return e.options.scope?.id}var ke=class extends _{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??ne(r,t),a=this.get(i);return a||(a=new Se({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){fe.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>ee(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>ee(e,t)):t}notify(e){fe.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){fe.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){fe.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Ae=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new ke,this.#t=e.mutationCache||new De,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=v.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=pe.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(D(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=w(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return fe.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;fe.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return fe.batch(()=>(n.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=fe.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(C).catch(C)}invalidateQueries(e,t={}){return fe.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=fe.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(C)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(C)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(D(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(C).catch(C)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(C).catch(C)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return pe.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(k(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{A(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(k(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{A(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=ne(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===L&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},je=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})),Me=o(((e,t)=>{t.exports=je()})),z=c(f(),1),B=Me(),Ne=z.createContext(void 0),Pe=({client:e,children:t})=>(z.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,B.jsx)(Ne.Provider,{value:e,children:t})),Fe=typeof window<`u`?z.useLayoutEffect:z.useEffect;function V(e){let t=z.useRef({value:e,prev:null}),n=t.current.value;return e!==n&&(t.current={value:e,prev:n}),t.current.prev}function Ie(e,t,n={},r={}){z.useEffect(()=>{if(!e.current||r.disabled||typeof IntersectionObserver!=`function`)return;let i=new IntersectionObserver(([e])=>{t(e)},n);return i.observe(e.current),()=>{i.disconnect()}},[t,n,r.disabled,e])}function Le(e){let t=z.useRef(null);return z.useImperativeHandle(e,()=>t.current,[]),t}function Re(e){return e[e.length-1]}function ze(e){return typeof e==`function`}function Be(e,t){return ze(e)?e(t):e}var Ve=Object.prototype.hasOwnProperty,He=Object.prototype.propertyIsEnumerable;function Ue(e){for(let t in e)if(Ve.call(e,t))return!0;return!1}var We=()=>Object.create(null),Ge=(e,t)=>Ke(e,t,We);function Ke(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=Xe(e)&&Xe(i);if(!a&&!(Je(e)&&Je(i)))return i;let o=a?e:qe(e);if(!o)return i;let s=a?i:qe(i);if(!s)return i;let c=o.length,l=s.length,u=a?Array(l):n(),d=0;for(let t=0;ti||!Ze(e[o],t[o],n)))return!1;return i===a}return!1}function Qe(e){let t,n,r=new Promise((e,r)=>{t=e,n=r});return r.status=`pending`,r.resolve=n=>{r.status=`resolved`,r.value=n,t(n),e?.(n)},r.reject=e=>{r.status=`rejected`,n(e)},r}function $e(e){return!!(e&&typeof e==`object`&&typeof e.then==`function`)}function et(e){return e.replace(/[\x00-\x1f\x7f]/g,``)}function tt(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return et(t)}var nt=[`http:`,`https:`,`mailto:`,`tel:`];function rt(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function it(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=tt(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=tt(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function at(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function ot(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n{e.next&&(e.prev?(e.prev.next=e.next,e.next.prev=e.prev,e.next=void 0,r&&(r.next=e,e.prev=r)):(e.next.prev=void 0,n=e.next,e.next=void 0,r&&(e.prev=r,r.next=e)),r=e)};return{get(e){let n=t.get(e);if(n)return i(n),n.value},set(a,o){if(t.size>=e&&n){let e=n;t.delete(e.key),e.next&&(n=e.next,e.next.prev=void 0),e===r&&(r=void 0)}let s=t.get(a);if(s)s.value=o,i(s);else{let e={key:a,value:o,prev:r};r&&(r.next=e),r=e,n||=e,t.set(a,e)}},clear(){t.clear(),n=void 0,r=void 0}}}var lt=4,ut=5;function dt(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=e.indexOf(`}`,t);return n===-1||t+1>=e.length?null:[t,n]}function ft(e,t,n=new Uint16Array(6)){let r=e.indexOf(`/`,t),i=r===-1?e.length:r,a=e.substring(t,i);if(!a||!a.includes(`$`))return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n;if(a===`$`){let r=e.length;return n[0]=2,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n}if(a.charCodeAt(0)===36)return n[0]=1,n[1]=t,n[2]=t+1,n[3]=i,n[4]=i,n[5]=i,n;let o=dt(a);if(o){let[r,s]=o,c=a.charCodeAt(r+1);if(c===45){if(r+2!e.parse&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=_t(1,n.fullPath??n.from,f,p,m);o=e,e.depth=a,e.parent=i,i.dynamic??=[],i.dynamic.push(e)}break}case 3:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),f=c&&!!(t||s),p=t?f?t:t.toLowerCase():void 0,m=s?f?s:s.toLowerCase():void 0,h=!l&&i.optional?.find(e=>!e.parse&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=_t(3,n.fullPath??n.from,f,p,m);o=e,e.parent=i,e.depth=a,i.optional??=[],i.optional.push(e)}break}case 2:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),l=c&&!!(t||s),f=t?l?t:t.toLowerCase():void 0,p=s?l?s:s.toLowerCase():void 0,m=_t(2,n.fullPath??n.from,l,f,p);o=m,m.parent=i,m.depth=a,i.wildcard??=[],i.wildcard.push(m)}}i=o}if(l&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf(`/`)+1)===95){let e=gt(n.fullPath??n.from);e.kind=ut,e.parent=i,a++,e.depth=a,i.pathless??=[],i.pathless.push(e),i=e}let u=(n.path||!n.children)&&!n.isRoot;if(u&&r.endsWith(`/`)){let e=gt(n.fullPath??n.from);e.kind=lt,e.parent=i,a++,e.depth=a,i.index=e,i=e}i.parse=l??null,i.priority=n.options?.params?.priority??0,u&&!i.route&&(i.route=n,i.fullPath=n.fullPath??n.from)}if(n.children)for(let r of n.children)pt(e,t,r,s,i,a,o)}function mt(e,t){if(e.parse&&!t.parse)return-1;if(!e.parse&&t.parse)return 1;if(e.parse&&t.parse&&(e.priority||t.priority))return t.priority-e.priority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function ht(e){if(e.pathless)for(let t of e.pathless)ht(t);if(e.static)for(let t of e.static.values())ht(t);if(e.staticInsensitive)for(let t of e.staticInsensitive.values())ht(t);if(e.dynamic?.length){e.dynamic.sort(mt);for(let t of e.dynamic)ht(t)}if(e.optional?.length){e.optional.sort(mt);for(let t of e.optional)ht(t)}if(e.wildcard?.length){e.wildcard.sort(mt);for(let t of e.wildcard)ht(t)}}function gt(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function _t(e,t,n,r,i){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,priority:0,caseSensitive:n,prefix:r,suffix:i}}function vt(e,t){let n=gt(`/`),r=new Uint16Array(6);for(let t of e)pt(!1,r,t,1,n,0);ht(n),t.masksTree=n,t.flatCache=ct(1e3)}function yt(e,t){e||=`/`;let n=t.flatCache.get(e);if(n)return n;let r=wt(e,t.masksTree);return t.flatCache.set(e,r),r}function bt(e,t,n,r,i){e||=`/`,r||=`/`;let a=t?`case\0${e}`:e,o=i.singleCache.get(a);return o||(o=gt(`/`),pt(t,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(a,o)),wt(r,o,n)}function xt(e,t,n=!1){let r=n?e:`nofuzz\0${e}`,i=t.matchCache.get(r);if(i!==void 0)return i;e||=`/`;let a;try{a=wt(e,t.segmentTree,n)}catch(e){if(e instanceof URIError)a=null;else throw e}return a&&(a.branch=Et(a.route)),t.matchCache.set(r,a),a}function St(e){return e===`/`?e:e.replace(/\/{1,}$/,``)}function Ct(e,t=!1,n){let r=gt(e.fullPath),i=new Uint16Array(6),a={},o={},s=0;return pt(t,i,e,1,r,0,e=>{if(n?.(e,s),e.id in a&&st(),a[e.id]=e,s!==0&&e.path){let t=St(e.fullPath);(!o[t]||e.fullPath.endsWith(`/`))&&(o[t]=e)}s++}),ht(r),{processedTree:{segmentTree:r,singleCache:ct(1e3),matchCache:ct(1e3),flatCache:null,masksTree:null},routesById:a,routesByPath:o}}function wt(e,t,n=!1){let r=e.split(`/`),i=Ot(e,r,t,n);if(!i)return null;let[a]=Tt(e,r,i);return{route:i.node.route,rawParams:a}}function Tt(e,t,n){let r=Dt(n.node),i=null,a=Object.create(null),o=n.extract?.part??0,s=n.extract?.node??0,c=n.extract?.path??0,l=n.extract?.segment??0;for(;s=0;e--){let n=i.wildcard[e],{prefix:r,suffix:a}=n;if(!(r&&(v||!(n.caseSensitive?y:b??=y.toLowerCase()).startsWith(r)))){if(a){if(v)continue;let e=t.slice(u).join(`/`).slice(-a.length);if((n.caseSensitive?e:e.toLowerCase())!==a)continue}s.push({node:n,index:o,skipped:d,depth:f+1,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}}if(i.optional){let e=d|1<=0;n--){let r=i.optional[n];s.push({node:r,index:u,skipped:e,depth:t,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}if(!v)for(let e=i.optional.length-1;e>=0;e--){let n=i.optional[e],{prefix:r,suffix:a}=n;if(r||a){let e=n.caseSensitive?y:b??=y.toLowerCase();if(r&&!e.startsWith(r)||a&&!e.endsWith(a))continue}s.push({node:n,index:u+1,skipped:d,depth:t,statics:p,dynamics:m,optionals:h+kt(o,u),extract:g,rawParams:_})}}if(!v&&i.dynamic&&y)for(let e=i.dynamic.length-1;e>=0;e--){let t=i.dynamic[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?y:b??=y.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}s.push({node:t,index:u+1,skipped:d,depth:f+1,statics:p,dynamics:m+kt(o,u),optionals:h,extract:g,rawParams:_})}if(!v&&i.staticInsensitive){let e=i.staticInsensitive.get(b??=y.toLowerCase());e&&s.push({node:e,index:u+1,skipped:d,depth:f+1,statics:p+kt(o,u),dynamics:m,optionals:h,extract:g,rawParams:_})}if(!v&&i.static){let e=i.static.get(y);e&&s.push({node:e,index:u+1,skipped:d,depth:f+1,statics:p+kt(o,u),dynamics:m,optionals:h,extract:g,rawParams:_})}if(i.pathless){let e=f+1;for(let t=i.pathless.length-1;t>=0;t--){let n=i.pathless[t];s.push({node:n,index:u,skipped:d,depth:e,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}}}if(l)return l;if(r&&c){let n=c.index;for(let e=0;ee.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===lt)>(e.node.kind===lt)||t.node.kind===lt==(e.node.kind===lt)&&t.depth>e.depth)))}function Nt(e){return Pt(e.filter(e=>e!==void 0).join(`/`))}function Pt(e){return e.replace(/\/{2,}/g,`/`)}function Ft(e){return e===`/`?e:e.replace(/^\/{1,}/,``)}function It(e){let t=e.length;return t>1&&e[t-1]===`/`?e.replace(/\/{1,}$/,``):e}function Lt(e){return It(Ft(e))}function Rt(e,t){return e?.endsWith(`/`)&&e!==`/`&&e!==`${t}/`?e.slice(0,-1):e}function zt(e,t,n){return Rt(e,n)===Rt(t,n)}function Bt({base:e,to:t,trailingSlash:n=`never`,cache:r}){let i=t.startsWith(`/`),a=!i&&t===`.`,o;if(r){o=i?t:a?e:e+`\0`+t;let n=r.get(o);if(n)return n}let s;if(a)s=e.split(`/`);else if(i)s=t.split(`/`);else{for(s=e.split(`/`);s.length>1&&Re(s)===``;)s.pop();let n=t.split(`/`);for(let e=0,t=n.length;e1&&(Re(s)===``?n===`never`&&s.pop():n===`always`&&s.push(``));let c=Pt(s.join(`/`))||`/`;return o&&r&&r.set(o,c),c}function Vt(e){let t=new Map(e.map(e=>[encodeURIComponent(e),e])),n=Array.from(t.keys()).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`),r=new RegExp(n,`g`);return e=>e.replace(r,e=>t.get(e)??e)}function Ht(e,t,n){let r=t[e];return typeof r==`string`?e===`_splat`?/^[a-zA-Z0-9\-._~!/]*$/.test(r)?r:r.split(`/`).map(e=>Wt(e,n)).join(`/`):Wt(r,n):r}function Ut({path:e,params:t,decoder:n,...r}){let i=!1,a=Object.create(null);if(!e||e===`/`)return{interpolatedPath:`/`,usedParams:a,isMissingParams:i};if(!e.includes(`$`))return{interpolatedPath:e,usedParams:a,isMissingParams:i};let o=e.length,s=0,c,l=``;for(;s{t[0]===`?`&&(t=t.substring(1));let n=Jt(t);for(let t in n){let r=n[t];if(typeof r==`string`)try{n[t]=e(r)}catch{}}return n}}function Qt(e,t){let n=typeof t==`function`;function r(r){if(typeof r==`object`&&r)try{return e(r)}catch{}else if(n&&typeof r==`string`)try{return t(r),e(r)}catch{}return r}return e=>{let t=Kt(e,r);return t?`?${t}`:``}}var $t=`__root__`;function en(e){if(e.statusCode=e.statusCode||e.code||307,!e._builtLocation&&!e.reloadDocument&&typeof e.href==`string`)try{new URL(e.href),e.reloadDocument=!0}catch{}let t=new Headers(e.headers);e.href&&t.get(`Location`)===null&&t.set(`Location`,e.href);let n=new Response(null,{status:e.statusCode,headers:t});if(n.options=e,e.throw)throw n;return n}function tn(e){return e instanceof Response&&!!e.options}var nn=e=>{if(!e.rendered)return e.rendered=!0,e.onReady?.()},rn=e=>e.stores.matchesId.get().some(t=>e.stores.matchStores.get(t)?.get()._forcePending),an=(e,t)=>!!(e.preload&&!e.router.stores.matchStores.has(t)),on=(e,t,n=!0)=>{let r={...e.router.options.context??{}},i=n?t:t-1;for(let t=0;t<=i;t++){let n=e.matches[t];if(!n)continue;let i=e.router.getMatch(n.id);i&&Object.assign(r,i.__routeContext,i.__beforeLoadContext)}return r},sn=(e,t)=>{if(!e.matches.length)return;let n=t.routeId,r=e.matches.findIndex(t=>t.routeId===e.router.routeTree.id),i=r>=0?r:0,a=n?e.matches.findIndex(e=>e.routeId===n):e.firstBadMatchIndex??e.matches.length-1;a<0&&(a=i);for(let t=a;t>=0;t--){let n=e.matches[t];if(e.router.looseRoutesById[n.routeId].options.notFoundComponent)return t}return n?a:i},cn=(e,t,n)=>{if(!(!tn(n)&&!Gt(n)))throw tn(n)&&n.redirectHandled&&!n.options.reloadDocument?n:(t&&(t._nonReactive.beforeLoadPromise?.resolve(),t._nonReactive.loaderPromise?.resolve(),t._nonReactive.beforeLoadPromise=void 0,t._nonReactive.loaderPromise=void 0,t._nonReactive.error=n,e.updateMatch(t.id,r=>({...r,status:tn(n)?`redirected`:Gt(n)?`notFound`:r.status===`pending`?`success`:r.status,context:on(e,t.index),isFetching:!1,error:n})),Gt(n)&&!n.routeId&&(n.routeId=t.routeId),t._nonReactive.loadPromise?.resolve()),tn(n)&&(e.rendered=!0,n.options._fromLocation=e.location,n.redirectHandled=!0,n=e.router.resolveRedirect(n)),n)},ln=(e,t)=>{let n=e.router.getMatch(t);return!!(!n||n._nonReactive.dehydrated)},un=(e,t,n)=>{let r=on(e,n);e.updateMatch(t,e=>({...e,context:r}))},dn=(e,t,n)=>{let{id:r,routeId:i}=e.matches[t],a=e.router.looseRoutesById[i];if(n instanceof Promise)throw n;e.firstBadMatchIndex??=t,cn(e,e.router.getMatch(r),n);try{a.options.onError?.(n)}catch(t){n=t,cn(e,e.router.getMatch(r),n)}e.updateMatch(r,e=>(e._nonReactive.beforeLoadPromise?.resolve(),e._nonReactive.beforeLoadPromise=void 0,e._nonReactive.loadPromise?.resolve(),{...e,error:n,status:`error`,isFetching:!1,updatedAt:Date.now(),abortController:new AbortController})),!e.preload&&!tn(n)&&!Gt(n)&&(e.serialError??=n)},fn=(e,t,n,r)=>{if(r._nonReactive.pendingTimeout!==void 0)return;let i=n.options.pendingMs??e.router.options.defaultPendingMs;if(e.onReady&&!an(e,t)&&(n.options.loader||n.options.beforeLoad||Cn(n))&&typeof i==`number`&&i!==1/0&&(n.options.pendingComponent??e.router.options?.defaultPendingComponent)){let t=setTimeout(()=>{nn(e)},i);r._nonReactive.pendingTimeout=t}},pn=(e,t,n)=>{let r=e.router.getMatch(t);if(!r._nonReactive.beforeLoadPromise&&!r._nonReactive.loaderPromise)return;fn(e,t,n,r);let i=()=>{let n=e.router.getMatch(t);n.preload&&(n.status===`redirected`||n.status===`notFound`)&&cn(e,n,n.error)};return r._nonReactive.beforeLoadPromise?r._nonReactive.beforeLoadPromise.then(i):i()},mn=(e,t,n,r)=>{let i=e.router.getMatch(t),a=i._nonReactive.loadPromise;i._nonReactive.loadPromise=Qe(()=>{a?.resolve(),a=void 0});let{paramsError:o,searchError:s}=i;o&&dn(e,n,o),s&&dn(e,n,s),fn(e,t,r,i);let c=new AbortController,l=!1,u=()=>{l||(l=!0,e.updateMatch(t,e=>({...e,isFetching:`beforeLoad`,fetchCount:e.fetchCount+1,abortController:c})))},d=()=>{i._nonReactive.beforeLoadPromise?.resolve(),i._nonReactive.beforeLoadPromise=void 0,e.updateMatch(t,e=>({...e,isFetching:!1}))};if(!r.options.beforeLoad){e.router.batch(()=>{u(),d()});return}i._nonReactive.beforeLoadPromise=Qe();let f={...on(e,n,!1),...i.__routeContext},{search:p,params:m,cause:h}=i,g=an(e,t),_={search:p,abortController:c,params:m,preload:g,context:f,location:e.location,navigate:t=>e.router.navigate({...t,_fromLocation:e.location}),buildLocation:e.router.buildLocation,cause:g?`preload`:h,matches:e.matches,routeId:r.id,...e.router.options.additionalContext},v=r=>{if(r===void 0){e.router.batch(()=>{u(),d()});return}(tn(r)||Gt(r))&&(u(),dn(e,n,r)),e.router.batch(()=>{u(),e.updateMatch(t,e=>({...e,__beforeLoadContext:r})),d()})},y;try{if(y=r.options.beforeLoad(_),$e(y))return u(),y.catch(t=>{dn(e,n,t)}).then(v)}catch(t){u(),dn(e,n,t)}v(y)},hn=(e,t)=>{let{id:n,routeId:r}=e.matches[t],i=e.router.looseRoutesById[r],a=()=>s(),o=()=>mn(e,n,t,i),s=()=>{if(ln(e,n))return;let t=pn(e,n,i);return $e(t)?t.then(o):o()};return a()},gn=(e,t,n)=>{let r=e.router.getMatch(t);if(!r||!n.options.head&&!n.options.scripts&&!n.options.headers)return;let i={ssr:e.router.options.ssr,matches:e.matches,match:r,params:r.params,loaderData:r.loaderData};return Promise.all([n.options.head?.(i),n.options.scripts?.(i),n.options.headers?.(i)]).then(([e,t,n])=>({meta:e?.meta,links:e?.links,headScripts:e?.scripts,headers:n,scripts:t,styles:e?.styles}))},_n=(e,t,n,r,i)=>{let a=t[r-1],{params:o,loaderDeps:s,abortController:c,cause:l}=e.router.getMatch(n),u=on(e,r),d=an(e,n);return{params:o,deps:s,preload:!!d,parentMatchPromise:a,abortController:c,context:u,location:e.location,navigate:t=>e.router.navigate({...t,_fromLocation:e.location}),cause:d?`preload`:l,route:i,...e.router.options.additionalContext}},vn=async(e,t,n,r,i)=>{try{let a=e.router.getMatch(n);try{Sn(i);let o=i.options.loader,s=typeof o==`function`?o:o?.handler,c=s?.(_n(e,t,n,r,i)),l=!!s&&$e(c);if((l||i._lazyPromise||i._componentsPromise||i.options.head||i.options.scripts||i.options.headers||a._nonReactive.minPendingPromise)&&e.updateMatch(n,e=>({...e,isFetching:`loader`})),s){let t=l?await c:c;cn(e,e.router.getMatch(n),t),t!==void 0&&e.updateMatch(n,e=>({...e,loaderData:t}))}i._lazyPromise&&await i._lazyPromise;let u=a._nonReactive.minPendingPromise;u&&await u,i._componentsPromise&&await i._componentsPromise,e.updateMatch(n,t=>({...t,error:void 0,context:on(e,r),status:`success`,isFetching:!1,updatedAt:Date.now()}))}catch(t){let o=t;if(o?.name===`AbortError`){if(a.abortController.signal.aborted){a._nonReactive.loaderPromise?.resolve(),a._nonReactive.loaderPromise=void 0;return}e.updateMatch(n,t=>({...t,status:t.status===`pending`?`success`:t.status,isFetching:!1,context:on(e,r)}));return}let s=a._nonReactive.minPendingPromise;s&&await s,Gt(t)&&await i.options.notFoundComponent?.preload?.(),cn(e,e.router.getMatch(n),t);try{i.options.onError?.(t)}catch(t){o=t,cn(e,e.router.getMatch(n),t)}!tn(o)&&!Gt(o)&&await Sn(i,[`errorComponent`]),e.updateMatch(n,t=>({...t,error:o,context:on(e,r),status:`error`,isFetching:!1}))}}catch(t){let r=e.router.getMatch(n);r&&(r._nonReactive.loaderPromise=void 0),cn(e,r,t)}},yn=async(e,t,n)=>{async function r(r,a,c,l,d){let f=Date.now()-a.updatedAt,p=r?d.options.preloadStaleTime??e.router.options.defaultPreloadStaleTime??3e4:d.options.staleTime??e.router.options.defaultStaleTime??0,m=d.options.shouldReload,h=typeof m==`function`?m(_n(e,t,i,n,d)):m,{status:g,invalid:_}=l,v=f>=p&&(!!e.forceStaleReload||l.cause===`enter`||c!==void 0&&c!==l.id);o=g===`success`&&(_||(h??v)),r&&d.options.preload===!1||(o&&!e.sync&&u?(s=!0,(async()=>{try{await vn(e,t,i,n,d);let r=e.router.getMatch(i);r._nonReactive.loaderPromise?.resolve(),r._nonReactive.loadPromise?.resolve(),r._nonReactive.loaderPromise=void 0,r._nonReactive.loadPromise=void 0}catch(t){tn(t)&&await e.router.navigate(t.options)}})()):g!==`success`||o?await vn(e,t,i,n,d):un(e,i,n))}let{id:i,routeId:a}=e.matches[n],o=!1,s=!1,c=e.router.looseRoutesById[a],l=c.options.loader,u=((typeof l==`function`?void 0:l?.staleReloadMode)??e.router.options.defaultStaleReloadMode)!==`blocking`;if(ln(e,i)){if(!e.router.getMatch(i))return e.matches[n];un(e,i,n)}else{let t=e.router.getMatch(i),o=e.router.stores.matchesId.get()[n],s=(o&&e.router.stores.matchStores.get(o)||null)?.routeId===a?o:e.router.stores.matches.get().find(e=>e.routeId===a)?.id,l=an(e,i);if(t._nonReactive.loaderPromise){if(t.status===`success`&&!e.sync&&!t.preload&&u)return t;await t._nonReactive.loaderPromise;let n=e.router.getMatch(i),a=n._nonReactive.error||n.error;a&&cn(e,n,a),n.status===`pending`&&await r(l,t,s,n,c)}else{let n=l&&!e.router.stores.matchStores.has(i),a=e.router.getMatch(i);a._nonReactive.loaderPromise=Qe(),n!==a.preload&&e.updateMatch(i,e=>({...e,preload:n})),await r(l,t,s,a,c)}}let d=e.router.getMatch(i);s||(d._nonReactive.loaderPromise?.resolve(),d._nonReactive.loadPromise?.resolve(),d._nonReactive.loadPromise=void 0),clearTimeout(d._nonReactive.pendingTimeout),d._nonReactive.pendingTimeout=void 0,s||(d._nonReactive.loaderPromise=void 0),d._nonReactive.dehydrated=void 0;let f=s?d.isFetching:!1;return f!==d.isFetching||d.invalid!==!1?(e.updateMatch(i,e=>({...e,isFetching:f,invalid:!1})),e.router.getMatch(i)):d};async function bn(e){let t=e,n=[];rn(t.router)&&nn(t);let r;for(let e=0;e({...e,...a?{status:`success`,globalNotFound:!0,error:void 0}:{status:`notFound`,error:l},isFetching:!1})),u=e,await Sn(r,[`notFoundComponent`])}else if(!t.preload){let e=t.matches[0];e.globalNotFound||t.router.getMatch(e.id)?.globalNotFound&&t.updateMatch(e.id,e=>({...e,globalNotFound:!1,error:void 0}))}if(t.serialError&&t.firstBadMatchIndex!==void 0){let e=t.router.looseRoutesById[t.matches[t.firstBadMatchIndex].routeId];await Sn(e,[`errorComponent`])}for(let e=0;e<=u;e++){let{id:n,routeId:r}=t.matches[e],i=t.router.looseRoutesById[r];try{let e=gn(t,n,i);if(e){let r=await e;t.updateMatch(n,e=>({...e,...r}))}}catch(e){console.error(`Error executing head for route ${r}:`,e)}}let d=nn(t);if($e(d)&&await d,l)throw l;if(t.serialError&&!t.preload&&!t.onReady)throw t.serialError;return t.matches}function xn(e,t){let n=t.map(t=>e.options[t]?.preload?.()).filter(Boolean);if(n.length!==0)return Promise.all(n)}function Sn(e,t=wn){!e._lazyLoaded&&e._lazyPromise===void 0&&(e.lazyFn?e._lazyPromise=e.lazyFn().then(t=>{let{id:n,...r}=t.options;Object.assign(e.options,r),e._lazyLoaded=!0,e._lazyPromise=void 0}):e._lazyLoaded=!0);let n=()=>e._componentsLoaded?void 0:t===wn?(()=>{if(e._componentsPromise===void 0){let t=xn(e,wn);t?e._componentsPromise=t.then(()=>{e._componentsLoaded=!0,e._componentsPromise=void 0}):e._componentsLoaded=!0}return e._componentsPromise})():xn(e,t);return e._lazyPromise?e._lazyPromise.then(n):n()}function Cn(e){for(let t of wn)if(e.options[t]?.preload)return!0;return!1}var wn=[`component`,`errorComponent`,`pendingComponent`,`notFoundComponent`];function Tn(e){return{input:({url:t})=>{for(let n of e)t=Dn(n,t);return t},output:({url:t})=>{for(let n=e.length-1;n>=0;n--)t=On(e[n],t);return t}}}function En(e){let t=Lt(e.basepath),n=`/${t}`,r=e.caseSensitive?n:n.toLowerCase(),i=`${r}/`;return{input:({url:t})=>{let a=e.caseSensitive?t.pathname:t.pathname.toLowerCase();return a===r?t.pathname=`/`:a.startsWith(i)&&(t.pathname=t.pathname.slice(n.length)),t},output:({url:e})=>(e.pathname=Nt([`/`,t,e.pathname]),e)}}function Dn(e,t){let n=e?.input?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function On(e,t){let n=e?.output?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function kn(e,t){let{createMutableStore:n,createReadonlyStore:r,batch:i,init:a}=t,o=new Map,s=new Map,c=new Map,l=n(e.status),u=n(e.loadedAt),d=n(e.isLoading),f=n(e.isTransitioning),p=n(e.location),m=n(e.resolvedLocation),h=n(e.statusCode),g=n(e.redirect),_=n([]),v=n([]),y=n([]),b=r(()=>An(o,_.get())),x=r(()=>An(s,v.get())),S=r(()=>An(c,y.get())),C=r(()=>_.get()[0]),w=r(()=>_.get().some(e=>o.get(e)?.get().status===`pending`)),T=r(()=>({locationHref:p.get().href,resolvedLocationHref:m.get()?.href,status:l.get()})),E=r(()=>({status:l.get(),loadedAt:u.get(),isLoading:d.get(),isTransitioning:f.get(),matches:b.get(),location:p.get(),resolvedLocation:m.get(),statusCode:h.get(),redirect:g.get()})),D=ct(64);function O(e){let t=D.get(e);return t||(t=r(()=>{let t=_.get();for(let n of t){let t=o.get(n);if(t&&t.routeId===e)return t.get()}}),D.set(e,t)),t}let ee={status:l,loadedAt:u,isLoading:d,isTransitioning:f,location:p,resolvedLocation:m,statusCode:h,redirect:g,matchesId:_,pendingIds:v,cachedIds:y,matches:b,pendingMatches:x,cachedMatches:S,firstId:C,hasPending:w,matchRouteDeps:T,matchStores:o,pendingMatchStores:s,cachedMatchStores:c,__store:E,getRouteMatchStore:O,setMatches:te,setPending:ne,setCached:k};te(e.matches),a?.(ee);function te(e){jn(e,o,_,n,i)}function ne(e){jn(e,s,v,n,i)}function k(e){jn(e,c,y,n,i)}return ee}function An(e,t){let n=[];for(let r of t){let t=e.get(r);t&&n.push(t.get())}return n}function jn(e,t,n,r,i){let a=e.map(e=>e.id),o=new Set(a);i(()=>{for(let e of t.keys())o.has(e)||t.delete(e);for(let n of e){let e=t.get(n.id);if(!e){let e=r(n);e.routeId=n.routeId,t.set(n.id,e);continue}e.routeId=n.routeId,e.get()!==n&&e.set(n)}ot(n.get(),a)||n.set(a)})}var Mn=`__TSR_index`,Nn=`popstate`,Pn=`beforeunload`;function Fn(e){let t=e.getLocation(),n=new Set,r=r=>{t=e.getLocation(),n.forEach(e=>e({location:t,action:r}))},i=n=>{e.notifyOnIndexChange??!0?r(n):t=e.getLocation()},a=async({task:n,navigateOpts:r,...i})=>{if(r?.ignoreBlocker??!1){n();return}let a=e.getBlockers?.()??[],o=i.type===`PUSH`||i.type===`REPLACE`;if(typeof document<`u`&&a.length&&o)for(let n of a){let r=zn(i.path,i.state);if(await n.blockerFn({currentLocation:t,nextLocation:r,action:i.type})){e.onBlocked?.();return}}n()};return{get location(){return t},get length(){return e.getLength()},subscribers:n,subscribe:e=>(n.add(e),()=>{n.delete(e)}),push:(n,i,o)=>{let s=t.state[Mn];i=In(s+1,i),a({task:()=>{e.pushState(n,i),r({type:`PUSH`})},navigateOpts:o,type:`PUSH`,path:n,state:i})},replace:(n,i,o)=>{let s=t.state[Mn];i=In(s,i),a({task:()=>{e.replaceState(n,i),r({type:`REPLACE`})},navigateOpts:o,type:`REPLACE`,path:n,state:i})},go:(t,n)=>{a({task:()=>{e.go(t),i({type:`GO`,index:t})},navigateOpts:n,type:`GO`})},back:t=>{a({task:()=>{e.back(t?.ignoreBlocker??!1),i({type:`BACK`})},navigateOpts:t,type:`BACK`})},forward:t=>{a({task:()=>{e.forward(t?.ignoreBlocker??!1),i({type:`FORWARD`})},navigateOpts:t,type:`FORWARD`})},canGoBack:()=>t.state[Mn]!==0,createHref:t=>e.createHref(t),block:t=>{if(!e.setBlockers)return()=>{};let n=e.getBlockers?.()??[];return e.setBlockers([...n,t]),()=>{let n=e.getBlockers?.()??[];e.setBlockers?.(n.filter(e=>e!==t))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:r}}function In(e,t){t||={};let n=Bn();return{...t,key:n,__TSR_key:n,[Mn]:e}}function Ln(e){let t=e?.window??(typeof document<`u`?window:void 0),n=t.history.pushState,r=t.history.replaceState,i=[],a=()=>i,o=e=>i=e,s=e?.createHref??(e=>e),c=e?.parseLocation??(()=>zn(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){let e=Bn();t.history.replaceState({[Mn]:0,key:e,__TSR_key:e},``)}let l=c(),u,d=!1,f=!1,p=!1,m=!1,h=()=>l,g,_,v=()=>{g&&(C._ignoreSubscribers=!0,(g.isPush?t.history.pushState:t.history.replaceState)(g.state,``,g.href),C._ignoreSubscribers=!1,g=void 0,_=void 0,u=void 0)},y=(e,t,n)=>{let r=s(t);_||(u=l),l=zn(t,n),g={href:r,state:n,isPush:g?.isPush||e===`push`},_||=Promise.resolve().then(()=>v())},b=e=>{l=c(),C.notify({type:e})},x=async()=>{if(f){f=!1;return}let e=c(),n=e.state[Mn]-l.state[Mn],r=n===1,i=n===-1,o=!r&&!i||d;d=!1;let s=o?`GO`:i?`BACK`:`FORWARD`,u=o?{type:`GO`,index:n}:{type:i?`BACK`:`FORWARD`};if(p)p=!1;else{let n=a();if(typeof document<`u`&&n.length){for(let r of n)if(await r.blockerFn({currentLocation:l,nextLocation:e,action:s})){f=!0,t.history.go(1),C.notify(u);return}}}l=c(),C.notify(u)},S=e=>{if(m){m=!1;return}let t=!1,n=a();if(typeof document<`u`&&n.length)for(let e of n){let n=e.enableBeforeUnload??!0;if(n===!0){t=!0;break}if(typeof n==`function`&&n()===!0){t=!0;break}}if(t)return e.preventDefault(),e.returnValue=``},C=Fn({getLocation:h,getLength:()=>t.history.length,pushState:(e,t)=>y(`push`,e,t),replaceState:(e,t)=>y(`replace`,e,t),back:e=>(e&&(p=!0),m=!0,t.history.back()),forward:e=>{e&&(p=!0),m=!0,t.history.forward()},go:e=>{d=!0,t.history.go(e)},createHref:e=>s(e),flush:v,destroy:()=>{t.history.pushState=n,t.history.replaceState=r,t.removeEventListener(Pn,S,{capture:!0}),t.removeEventListener(Nn,x)},onBlocked:()=>{u&&l!==u&&(l=u)},getBlockers:a,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(Pn,S,{capture:!0}),t.addEventListener(Nn,x),t.history.pushState=function(...e){let r=n.apply(t.history,e);return C._ignoreSubscribers||b(`PUSH`),r},t.history.replaceState=function(...e){let n=r.apply(t.history,e);return C._ignoreSubscribers||b(`REPLACE`),n},C}function Rn(e){let t=e.replace(/[\x00-\x1f\x7f]/g,``);return t.startsWith(`//`)&&(t=`/`+t.replace(/^\/+/,``)),t}function zn(e,t){let n=Rn(e),r=n.indexOf(`#`),i=n.indexOf(`?`),a=Bn();return{href:n,pathname:n.substring(0,r>0?i>0?Math.min(r,i):r:i>0?i:n.length),hash:r>-1?n.substring(r):``,search:i>-1?n.slice(i,r===-1?void 0:r):``,state:t||{[Mn]:0,key:a,__TSR_key:a}}}function Bn(){return(Math.random()+1).toString(36).substring(7)}function Vn(e,t){let n=t,r=e;return{fromLocation:n,toLocation:r,pathChanged:n?.pathname!==r.pathname,hrefChanged:n?.href!==r.href,hashChanged:n?.hash!==r.hash}}var Hn=new WeakMap,Un=class{constructor(e,t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this.resetNextScroll=!0,this.shouldViewTransition=void 0,this.isViewTransitionTypesSupported=void 0,this.subscribers=new Set,this.isScrollRestoring=!1,this.isScrollRestorationSetup=!1,this.routeBranchCache=new WeakMap,this.startTransition=e=>e(),this.update=e=>{let t=this.options,n=this.basepath??t?.basepath??`/`,r=this.basepath===void 0,i=t?.rewrite;if(this.options={...t,...e},this.isServer=this.options.isServer??typeof document>`u`,this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=Vt(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.history=this.options.history?this.options.history:Ln()),this.origin=this.options.origin,this.origin||=window?.origin&&window.origin!==`null`?window.origin:`http://localhost`,this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let e;this.resolvePathCache=ct(1e3),e=this.buildRouteTree(),this.setRoutes(e)}if(!this.stores&&this.latestLocation){let e=this.getStoreConfig(this);this.batch=e.batch,this.stores=kn(Kn(this.latestLocation),e),fr(this)}let a=!1,o=this.options.basepath??`/`,s=this.options.rewrite;if(r||n!==o||i!==s){this.basepath=o;let e=[],t=Lt(o);t&&t!==`/`&&e.push(En({basepath:o})),s&&e.push(s),this.rewrite=e.length===0?void 0:e.length===1?e[0]:Tn(e),this.history&&this.updateLatestLocation(),a=!0}a&&this.stores&&this.stores.location.set(this.latestLocation),typeof window<`u`&&`CSS`in window&&typeof window.CSS?.supports==`function`&&(this.isViewTransitionTypesSupported=window.CSS.supports(`selector(:active-view-transition-type(a))`))},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{let e=Ct(this.routeTree,this.options.caseSensitive,(e,t)=>{e.init({originalIndex:t})});return this.options.routeMasks&&vt(this.options.routeMasks,e.processedTree),e},this.subscribe=(e,t)=>{let n={eventType:e,fn:t};return this.subscribers.add(n),()=>{this.subscribers.delete(n)}},this.emit=e=>{this.subscribers.forEach(t=>{t.eventType===e.type&&t.fn(e)})},this.parseLocation=(e,t)=>{let n=({pathname:e,search:n,hash:r,href:i,state:a})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(e)){let i=this.options.parseSearch(n),o=this.options.stringifySearch(i);return{href:e+o+r,publicHref:e+o+r,pathname:it(e).path,external:!1,searchStr:o,search:Ge(t?.search,i),hash:it(r.slice(1)).path,state:Ke(t?.state,a)}}let o=new URL(i,this.origin),s=Dn(this.rewrite,o),c=this.options.parseSearch(s.search),l=this.options.stringifySearch(c);return s.search=l,{href:s.href.replace(s.origin,``),publicHref:i,pathname:it(s.pathname).path,external:!!this.rewrite&&s.origin!==this.origin,searchStr:l,search:Ge(t?.search,c),hash:it(s.hash.slice(1)).path,state:Ke(t?.state,a)}},r=n(e),{__tempLocation:i,__tempKey:a}=r.state;if(i&&(!a||a===this.tempLocationKey)){let e=n(i);return e.state.key=r.state.key,e.state.__TSR_key=r.state.__TSR_key,delete e.state.__tempLocation,{...e,maskedLocation:r}}return r},this.resolvePathWithBase=(e,t)=>Bt({base:e,to:t.includes(`//`)?Pt(t):t,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(e,t,n)=>typeof e==`string`?this.matchRoutesInternal({pathname:e,search:t},n):this.matchRoutesInternal(e,t),this.getMatchedRoutes=e=>Jn({pathname:e,routesById:this.routesById,processedTree:this.processedTree}),this.cancelMatch=e=>{let t=this.getMatch(e);t&&(t.abortController.abort(),clearTimeout(t._nonReactive.pendingTimeout),t._nonReactive.pendingTimeout=void 0)},this.cancelMatches=()=>{this.stores.pendingIds.get().forEach(e=>{this.cancelMatch(e)}),this.stores.matchesId.get().forEach(e=>{if(this.stores.pendingMatchStores.has(e))return;let t=this.stores.matchStores.get(e)?.get();t&&(t.status===`pending`||t.isFetching===`loader`)&&this.cancelMatch(e)})},this.buildLocation=e=>{let t=(t={})=>{let n=t._fromLocation||this.pendingBuiltLocation||this.latestLocation,r=this.matchRoutesLightweight(n);t.from;let i=t.unsafeRelative===`path`?n.pathname:t.from??r.fullPath,a=t.to?`${t.to}`:void 0,o=r.search,s=Object.assign(Object.create(null),r.params),c=a?.charCodeAt(0)===47?`/`:this.resolvePathWithBase(i,`.`),l=a?this.resolvePathWithBase(c,a):c,u=t.params===!1||t.params===null?Object.create(null):(t.params??!0)===!0?s:Object.assign(s,Be(t.params,s)),d=this.routesByPath[It(l)],f;if(d)f=this.getRouteBranch(d);else if(l.includes(`$`))f=[];else{let e=this.getMatchedRoutes(l);f=e.matchedRoutes,this.options.notFoundRoute&&(!e.foundRoute||e.foundRoute.path!==`/`&&e.routeParams[`**`])&&(f=[...f,this.options.notFoundRoute])}if(f.length&&Ue(u))for(let e of f){let t=e.options.params?.stringify??e.options.stringifyParams;if(t)try{Object.assign(u,t(u))}catch{}}let p=e.leaveParams?l:it(Ut({path:l,params:u,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path,m=o;if(e._includeValidateSearch&&this.options.search?.strict){let e={};f.forEach(t=>{if(t.options.validateSearch)try{Object.assign(e,qn(t.options.validateSearch,{...e,...m}))}catch{}}),m=e}m=Yn({search:m,dest:t,destRoutes:f,_includeValidateSearch:e._includeValidateSearch}),m=Ge(o,m);let h=this.options.stringifySearch(m),g=t.hash===!0?n.hash:t.hash?Be(t.hash,n.hash):void 0,_=g?`#${g}`:``,v=t.state===!0?n.state:t.state?Be(t.state,n.state):{};v=Ke(n.state,v);let y=`${p}${h}${_}`,b,x,S=!1;if(this.rewrite){let e=new URL(y,this.origin),t=On(this.rewrite,e);b=e.href.replace(e.origin,``),t.origin===this.origin?x=t.pathname+t.search+t.hash:(x=t.href,S=!0)}else b=at(y),x=b;return{publicHref:x,href:b,pathname:p,search:m,searchStr:h,state:v,hash:g??``,external:S,unmaskOnReload:t.unmaskOnReload}},n=(n={},r)=>{let i=t(n),a=r?t(r):void 0;if(!a){let n=Object.create(null);if(this.options.routeMasks){let o=yt(i.pathname,this.processedTree);if(o){Object.assign(n,o.rawParams);let{from:i,params:s,...c}=o.route,l=s===!1||s===null?Object.create(null):(s??!0)===!0?n:Object.assign(n,Be(s,n));r={from:e.from,...c,params:l},a=t(r)}}}return a&&(i.maskedLocation=a),i};return e.mask?n(e,{from:e.from,...e.mask}):n(e)},this.commitLocation=async({viewTransition:e,ignoreBlocker:t,...n})=>{let r,i=()=>{let e=[`key`,`__TSR_key`,`__TSR_index`,`__hashScrollIntoViewOptions`];e.forEach(e=>{n.state[e]=this.latestLocation.state[e]});let t=Ze(n.state,this.latestLocation.state);return e.forEach(e=>{delete n.state[e]}),t},a=It(this.latestLocation.href)===It(n.href),o=this.commitLocationPromise;if(this.commitLocationPromise=Qe(()=>{o?.resolve(),o=void 0}),a&&i())this.load();else{let{maskedLocation:i,hashScrollIntoView:a,...o}=n;i&&(o={...i,state:{...i.state,__tempKey:void 0,__tempLocation:{...o,search:o.searchStr,state:{...o.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(o.unmaskOnReload??this.options.unmaskOnReload??!1)&&(o.state.__tempKey=this.tempLocationKey)),o.state.__hashScrollIntoViewOptions=a??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=e,r=n.replace?`REPLACE`:`PUSH`,this.history[r===`REPLACE`?`replace`:`push`](o.publicHref,o.state,{ignoreBlocker:t})}return this.resetNextScroll=n.resetScroll??!0,this.history.subscribers.size||this.load(r?{action:{type:r}}:void 0),this.commitLocationPromise},this.buildAndCommitLocation=({replace:e,resetScroll:t,hashScrollIntoView:n,viewTransition:r,ignoreBlocker:i,href:a,...o}={})=>{if(a){let t=this.history.location.state.__TSR_index,n=zn(a,{__TSR_index:e?t:t+1}),r=new URL(n.pathname,this.origin);o.to=Dn(this.rewrite,r).pathname,o.search=this.options.parseSearch(n.search),o.hash=n.hash.slice(1)}let s=this.buildLocation({...o,_includeValidateSearch:!0});this.pendingBuiltLocation=s;let c=this.commitLocation({...s,viewTransition:r,replace:e,resetScroll:t,hashScrollIntoView:n,ignoreBlocker:i});return Promise.resolve().then(()=>{this.pendingBuiltLocation===s&&(this.pendingBuiltLocation=void 0)}),c},this.navigate=async({to:e,reloadDocument:t,href:n,publicHref:r,...i})=>{let a=!1;if(n)try{new URL(`${n}`),a=!0}catch{}if(a&&!t&&(t=!0),t){if(e!==void 0||!n){let t=this.buildLocation({to:e,...i});n??=t.publicHref,r??=t.publicHref}let t=!a&&r?r:n;if(rt(t,this.protocolAllowlist))return Promise.resolve();if(!i.ignoreBlocker){let e=this.history.getBlockers?.()??[];for(let t of e)if(t?.blockerFn&&await t.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:`PUSH`}))return Promise.resolve()}return i.replace?window.location.replace(t):window.location.href=t,Promise.resolve()}return this.buildAndCommitLocation({...i,href:n,to:e,_isNavigate:!0})},this.beforeLoad=()=>{this.cancelMatches(),this.updateLatestLocation();let e=this.matchRoutes(this.latestLocation),t=this.stores.cachedMatches.get().filter(t=>!e.some(e=>e.id===t.id));this.batch(()=>{this.stores.status.set(`pending`),this.stores.statusCode.set(200),this.stores.isLoading.set(!0),this.stores.location.set(this.latestLocation),this.stores.setPending(e),this.stores.setCached(t)})},this.load=async e=>{let t=e?.action?.type,n,r,i,a=this.stores.resolvedLocation.get()??this.stores.location.get();for(i=new Promise(o=>{this.startTransition(async()=>{try{this.beforeLoad(),t?Hn.set(this.latestLocation,t):Hn.delete(this.latestLocation);let n=this.latestLocation,r=Vn(n,this.stores.resolvedLocation.get());this.stores.redirect.get()||this.emit({type:`onBeforeNavigate`,...r}),this.emit({type:`onBeforeLoad`,...r}),await bn({router:this,sync:e?.sync,forceStaleReload:a.href===n.href,matches:this.stores.pendingMatches.get(),location:n,updateMatch:this.updateMatch,onReady:async()=>{this.startTransition(()=>{this.startViewTransition(async()=>{let e=null,t=null,n=null,r=null;this.batch(()=>{let i=this.stores.pendingMatches.get(),a=i.length,o=this.stores.matches.get();e=a?o.filter(e=>!this.stores.pendingMatchStores.has(e.id)):null;let s=new Set;for(let e of this.stores.pendingMatchStores.values())e.routeId&&s.add(e.routeId);let c=new Set;for(let e of this.stores.matchStores.values())e.routeId&&c.add(e.routeId);t=a?o.filter(e=>!s.has(e.routeId)):null,n=a?i.filter(e=>!c.has(e.routeId)):null,r=a?i.filter(e=>c.has(e.routeId)):o,this.stores.isLoading.set(!1),this.stores.loadedAt.set(Date.now()),a&&(this.stores.setMatches(i),this.stores.setPending([]),this.stores.setCached([...this.stores.cachedMatches.get(),...e.filter(e=>e.status!==`error`&&e.status!==`notFound`&&e.status!==`redirected`)]),this.clearExpiredCache())});for(let[e,i]of[[t,`onLeave`],[n,`onEnter`],[r,`onStay`]])if(e)for(let t of e)this.looseRoutesById[t.routeId].options[i]?.(t)})})}})}catch(e){tn(e)?(n=e,this.navigate({...n.options,replace:!0,ignoreBlocker:!0})):Gt(e)&&(r=e);let t=n?n.status:r?404:this.stores.matches.get().some(e=>e.status===`error`)?500:200;this.batch(()=>{this.stores.statusCode.set(t),this.stores.redirect.set(n)})}this.latestLoadPromise===i&&(this.commitLocationPromise?.resolve(),this.latestLoadPromise=void 0,this.commitLocationPromise=void 0),o()})}),this.latestLoadPromise=i,await i;this.latestLoadPromise&&i!==this.latestLoadPromise;)await this.latestLoadPromise;let o;this.hasNotFoundMatch()?o=404:this.stores.matches.get().some(e=>e.status===`error`)&&(o=500),o!==void 0&&this.stores.statusCode.set(o)},this.startViewTransition=e=>{let t=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,t&&typeof document<`u`&&`startViewTransition`in document&&typeof document.startViewTransition==`function`){let n;if(typeof t==`object`&&this.isViewTransitionTypesSupported){let r=this.latestLocation,i=this.stores.resolvedLocation.get(),a=typeof t.types==`function`?t.types(Vn(r,i)):t.types;if(a===!1){e();return}n={update:e,types:a}}else n=e;document.startViewTransition(n)}else e()},this.updateMatch=(e,t)=>{this.startTransition(()=>{let n=this.stores.pendingMatchStores.get(e);if(n){n.set(t);return}let r=this.stores.matchStores.get(e);if(r){r.set(t);return}let i=this.stores.cachedMatchStores.get(e);if(i){let n=t(i.get());n.status===`redirected`?this.stores.cachedMatchStores.delete(e)&&this.stores.cachedIds.set(t=>t.filter(t=>t!==e)):i.set(n)}})},this.getMatch=e=>this.stores.cachedMatchStores.get(e)?.get()??this.stores.pendingMatchStores.get(e)?.get()??this.stores.matchStores.get(e)?.get(),this.invalidate=e=>{let t=t=>e?.filter?.(t)??!0?{...t,invalid:!0,...e?.forcePending||t.status===`error`||t.status===`notFound`?{status:`pending`,error:void 0}:void 0}:t;return this.batch(()=>{this.stores.setMatches(this.stores.matches.get().map(t)),this.stores.setCached(this.stores.cachedMatches.get().map(t)),this.stores.setPending(this.stores.pendingMatches.get().map(t))}),this.shouldViewTransition=!1,this.load({sync:e?.sync})},this.getParsedLocationHref=e=>e.publicHref||`/`,this.resolveRedirect=e=>{let t=e.headers.get(`Location`);if(!e.options.href||e.options._builtLocation){let t=e.options._builtLocation??this.buildLocation(e.options),n=this.getParsedLocationHref(t);e.options.href=n,e.headers.set(`Location`,n)}else if(t)try{let n=new URL(t);if(this.origin&&n.origin===this.origin){let t=n.pathname+n.search+n.hash;e.options.href=t,e.headers.set(`Location`,t)}}catch{}if(e.options.href&&!e.options._builtLocation&&rt(e.options.href,this.protocolAllowlist))throw Error(`Redirect blocked: unsafe protocol`);return e.headers.get(`Location`)||e.headers.set(`Location`,e.options.href),e},this.clearCache=e=>{let t=e?.filter;t===void 0?this.stores.setCached([]):this.stores.setCached(this.stores.cachedMatches.get().filter(e=>!t(e)))},this.clearExpiredCache=()=>{let e=Date.now();this.clearCache({filter:t=>{let n=this.looseRoutesById[t.routeId];if(!n.options.loader)return!0;let r=(t.preload?n.options.preloadGcTime??this.options.defaultPreloadGcTime:n.options.gcTime??this.options.defaultGcTime)??3e5;return t.status===`error`||e-t.updatedAt>=r}})},this.loadRouteChunk=Sn,this.preloadRoute=async e=>{let t=e._builtLocation??this.buildLocation(e),n=this.matchRoutes(t,{throwOnError:!0,preload:!0,dest:e}),r=new Set([...this.stores.matchesId.get(),...this.stores.pendingIds.get()]),i=new Set([...r,...this.stores.cachedIds.get()]),a=n.filter(e=>!i.has(e.id));if(a.length){let e=this.stores.cachedMatches.get();this.stores.setCached([...e,...a])}try{return n=await bn({router:this,matches:n,location:t,preload:!0,updateMatch:(e,t)=>{r.has(e)?n=n.map(n=>n.id===e?t(n):n):this.updateMatch(e,t)}}),n}catch(e){if(tn(e))return e.options.reloadDocument?void 0:await this.preloadRoute({...e.options,_fromLocation:t});Gt(e)||console.error(e);return}},this.matchRoute=(e,t)=>{let n={...e,to:e.to?this.resolvePathWithBase(e.from||``,e.to):void 0,params:e.params||{},leaveParams:!0},r=this.buildLocation(n);if(t?.pending&&this.stores.status.get()!==`pending`)return!1;let i=(t?.pending===void 0?!this.stores.isLoading.get():t.pending)?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),a=bt(r.pathname,t?.caseSensitive??!1,t?.fuzzy??!1,i.pathname,this.processedTree);return!a||e.params&&!Ze(a.rawParams,e.params,{partial:!0})?!1:t?.includeSearch??!0?Ze(i.search,r.search,{partial:!0})?a.rawParams:!1:a.rawParams},this.hasNotFoundMatch=()=>this.stores.matches.get().some(e=>e.status===`notFound`||e.globalNotFound),this.getStoreConfig=t,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??`fuzzy`,stringifySearch:e.stringifySearch??Xt,parseSearch:e.parseSearch??Yt,protocolAllowlist:e.protocolAllowlist??nt}),typeof document<`u`&&(self.__TSR_ROUTER__=this)}isShell(){return!!this.options.isShell}isPrerendering(){return!!this.options.isPrerendering}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:n}){this.routesById=e,this.routesByPath=t,this.processedTree=n;let r=this.options.notFoundRoute;r&&(r.init({originalIndex:99999999999}),this.routesById[r.id]=r)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=Et(e),this.routeBranchCache.set(e,t)),t}get looseRoutesById(){return this.routesById}getParentContext(e){return e?.id?e.context??this.options.context??void 0:this.options.context??void 0}matchRoutesInternal(e,t){let n=this.getMatchedRoutes(e.pathname),{foundRoute:r,routeParams:i}=n,{matchedRoutes:a}=n,o=!1;(r?r.path!==`/`&&i[`**`]:It(e.pathname))&&(this.options.notFoundRoute?a=[...a,this.options.notFoundRoute]:o=!0);let s=o?Zn(this.options.notFoundMode,a):void 0,c=Array(a.length),l=new Map;for(let e of this.stores.matchStores.values())e.routeId&&l.set(e.routeId,e.get());for(let n=0;nthis.navigate({...t,_fromLocation:e}),buildLocation:this.buildLocation,cause:n.cause,abortController:n.abortController,preload:!!n.preload,matches:c,routeId:r.id};n.__routeContext=r.options.context(t)??void 0}n.context={...a,...n.__routeContext,...n.__beforeLoadContext}}}return c}matchRoutesLightweight(e){let{matchedRoutes:t,routeParams:n}=this.getMatchedRoutes(e.pathname),r=Re(t),i={...e.search};for(let e of t)try{Object.assign(i,qn(e.options.validateSearch,i))}catch{}let a=Re(this.stores.matchesId.get()),o=a&&this.stores.matchStores.get(a)?.get(),s=o&&o.routeId===r.id&&o.pathname===e.pathname,c;if(s)c=o.params;else{let e=Object.assign(Object.create(null),n);for(let n of t)try{Qn(n,e)}catch{}c=e}return{matchedRoutes:t,fullPath:r.fullPath,search:i,params:c}}},Wn=class extends Error{},Gn=class extends Error{};function Kn(e){return{loadedAt:0,isLoading:!1,isTransitioning:!1,status:`idle`,resolvedLocation:void 0,location:e,matches:[],statusCode:200}}function qn(e,t){if(e==null)return{};if(`~standard`in e){let n=e[`~standard`].validate(t);if(n instanceof Promise)throw new Wn(`Async validation not supported`);if(n.issues)throw new Wn(JSON.stringify(n.issues,void 0,2),{cause:n});return n.value}return`parse`in e?e.parse(t):typeof e==`function`?e(t):{}}function Jn({pathname:e,routesById:t,processedTree:n}){let r=Object.create(null),i=It(e),a,o=xt(i,n,!0);return o&&(a=o.route,Object.assign(r,o.rawParams)),{matchedRoutes:o?.branch||[t.__root__],routeParams:r,foundRoute:a}}function Yn({search:e,dest:t,destRoutes:n,_includeValidateSearch:r}){return Xn(n)(e,t,r??!1)}function Xn(e){let t={dest:null,_includeValidateSearch:!1,middlewares:[]};for(let n of e)`search`in n.options?n.options.search?.middlewares&&t.middlewares.push(...n.options.search.middlewares):(n.options.preSearchFilters||n.options.postSearchFilters)&&t.middlewares.push(({search:e,next:t})=>{let r=e;`preSearchFilters`in n.options&&n.options.preSearchFilters&&(r=n.options.preSearchFilters.reduce((e,t)=>t(e),e));let i=t(r);return`postSearchFilters`in n.options&&n.options.postSearchFilters?n.options.postSearchFilters.reduce((e,t)=>t(e),i):i}),n.options.validateSearch&&t.middlewares.push(({search:e,next:r})=>{let i=r(e);if(!t._includeValidateSearch)return i;try{return{...i,...qn(n.options.validateSearch,i)??void 0}}catch{return i}});t.middlewares.push(({search:e})=>{let n=t.dest;return n.search?n.search===!0?e:Be(n.search,e):{}});let n=(e,t,r)=>{if(e>=r.length)return t;let i=r[e];return i({search:t,next:t=>n(e+1,t,r)})};return function(e,r,i){return t.dest=r,t._includeValidateSearch=i,n(0,e,t.middlewares)}}function Zn(e,t){if(e!==`root`)for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.children)return n.id}return $t}function Qn(e,t){let n=e.options.params?.parse??e.options.parseParams;if(n){let e=n(t);if(e===!1)throw Error(`Route params.parse returned false for a matched route`);Object.assign(t,e)}}function $n(){try{return sessionStorage}catch{return}}var er=`tsr-scroll-restoration-v1_3`,tr=$n();function nr(){try{return JSON.parse(tr?.getItem(`tsr-scroll-restoration-v1_3`)||`{}`)}catch{return{}}}function rr(){try{tr?.setItem(er,JSON.stringify(ir))}catch{}}var ir=nr(),ar=`data-scroll-restoration-id`,or=e=>e.state.__TSR_key||e.href;function sr(e){let t=e.getAttribute(ar);if(t)return`[${ar}="${t}"]`;let n=``,r=e,i;for(;i=r.parentNode;){let e=1,t=r;for(;t=t.previousElementSibling;)e++;let a=`${r.localName}:nth-child(${e})`;n=n?`${a} > ${n}`:a,r=i}return n}var cr=!1,lr=`window`;function ur(e){try{return typeof e==`function`?e():document.querySelector(e)}catch{}}function dr(e){let t=[];for(let n of e){if(n===lr)continue;let e=ur(n);e&&t.push(e)}return t}function fr(e,t){if((t??e.options.scrollRestoration)&&(e.isScrollRestoring=!0),e.isScrollRestorationSetup)return;e.isScrollRestorationSetup=!0,cr=!1;let n=e.options.getScrollRestorationKey||or,r=new Map,i=(e,t,n)=>{let i=r.get(e)||{};i.scrollX=t,i.scrollY=n,r.set(e,i)};history.scrollRestoration=`manual`;let a=t=>{if(!(cr||!e.isScrollRestoring)){if(t.target===document)i(lr,scrollX,scrollY);else{let e=t.target;i(e,e.scrollLeft,e.scrollTop)}}},o=t=>{if(!e.isScrollRestoring)return;let n=ir[t]||={};for(let[e,t]of r)e===lr?n[lr]=t:e.isConnected&&(n[sr(e)]=t)};document.addEventListener(`scroll`,a,!0),e.subscribe(`onBeforeLoad`,e=>{e.fromLocation&&o(n(e.fromLocation)),r.clear()}),addEventListener(`pagehide`,()=>{o(n(e.stores.resolvedLocation.get()??e.stores.location.get())),rr()}),e.subscribe(`onRendered`,t=>{let i=e.options.scrollRestorationBehavior,a=e.options.scrollToTopSelectors,o=e.resetNextScroll,s;if(r.clear(),o||(e.resetNextScroll=!0),typeof e.options.scrollRestoration==`function`&&!e.options.scrollRestoration({location:e.latestLocation}))return;let c=n(t.toLocation),l=t.fromLocation&&n(t.fromLocation);if(e.isScrollRestoring&&l&&l!==c){let e=ir[l];if(e){let t=ir[c];for(let n in e){if(n===lr){if(o)continue}else{let e=ur(n);if(!e||o&&a&&(s??=dr(a),s.includes(e)))continue}t||=ir[c]={},t[n]??=e[n]}}}cr=!0;try{let n=t.toLocation.hash,r=t.toLocation.state.__hashScrollIntoViewOptions??!0,l=!1;if(o){let o=Hn.get(t.toLocation),u=n&&r&&(o===`PUSH`||o===`REPLACE`),d=e.isScrollRestoring?ir[c]:void 0;if(d)for(let e in d){let{scrollX:t,scrollY:n}=d[e];if(e===lr){if(u)continue;scrollTo({top:n,left:t,behavior:i}),l=!0}else{let r=ur(e);r&&(r.scrollLeft=t,r.scrollTop=n)}}if(!l&&!n){let e={top:0,left:0,behavior:i};if(scrollTo(e),a){s??=dr(a);for(let t of s)t.scrollTo(e)}}}!l&&n&&r&&document.getElementById(n)?.scrollIntoView(r)}finally{cr=!1}})}var pr=`Error preloading route! ☝️`,mr=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=e=>{this.originalIndex=e.originalIndex;let t=this.options,n=!t?.path&&!t?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=$t:this.parentRoute||st();let r=n?$t:t?.path;r&&r!==`/`&&(r=Ft(r));let i=t?.id||r,a=n?$t:Nt([this.parentRoute.id===`__root__`?``:this.parentRoute.id,i]);r===`__root__`&&(r=`/`),a!==`__root__`&&(a=Nt([`/`,a]));let o=a===`__root__`?`/`:Nt([this.parentRoute.fullPath,r]);this._path=r,this._id=a,this._fullPath=o,this._to=It(o)},this.addChildren=e=>this._addFileChildren(e),this._addFileChildren=e=>(Array.isArray(e)&&(this.children=e),typeof e==`object`&&e&&(this.children=Object.values(e)),this),this._addFileTypes=()=>this,this.updateLoader=e=>(Object.assign(this.options,e),this),this.update=e=>(Object.assign(this.options,e),this),this.lazy=e=>(this.lazyFn=e,this),this.redirect=e=>en({from:this.fullPath,...e}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw Error(`Route cannot have both an 'id' and a 'path' option.`)}},hr=class extends mr{constructor(e){super(e)}};function gr(e){let t=e.errorComponent??vr;return(0,B.jsx)(_r,{getResetKey:e.getResetKey,onCatch:e.onCatch,children:({error:n,reset:r})=>n?z.createElement(t,{error:n,reset:r}):e.children})}var _r=class extends z.Component{constructor(...e){super(...e),this.state={error:null}}static getDerivedStateFromProps(e,t){let n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:null}:{resetKey:n}}static getDerivedStateFromError(e){return{error:e}}reset(){this.setState({error:null})}componentDidCatch(e,t){this.props.onCatch&&this.props.onCatch(e,t)}render(){return this.props.children({error:this.state.error,reset:()=>{this.reset()}})}};function vr({error:e}){let[t,n]=z.useState(!1);return(0,B.jsxs)(`div`,{style:{padding:`.5rem`,maxWidth:`100%`},children:[(0,B.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`.5rem`},children:[(0,B.jsx)(`strong`,{style:{fontSize:`1rem`},children:`Something went wrong!`}),(0,B.jsx)(`button`,{style:{appearance:`none`,fontSize:`.6em`,border:`1px solid currentColor`,padding:`.1rem .2rem`,fontWeight:`bold`,borderRadius:`.25rem`},onClick:()=>n(e=>!e),children:t?`Hide Error`:`Show Error`})]}),(0,B.jsx)(`div`,{style:{height:`.25rem`}}),t?(0,B.jsx)(`div`,{children:(0,B.jsx)(`pre`,{style:{fontSize:`.7em`,border:`1px solid red`,borderRadius:`.25rem`,padding:`.3rem`,color:`red`,overflow:`auto`},children:e.message?(0,B.jsx)(`code`,{children:e.message}):null})}):null]})}function yr({children:e,fallback:t=null}){return br()?(0,B.jsx)(z.Fragment,{children:e}):(0,B.jsx)(z.Fragment,{children:t})}function br(){return z.useSyncExternalStore(xr,()=>!0,()=>!1)}function xr(){return()=>{}}var Sr=z.createContext(null);function Cr(e){return z.useContext(Sr)}var wr=z.createContext(void 0),Tr=z.createContext(void 0),Er=(e=>(e[e.None=0]=`None`,e[e.Mutable=1]=`Mutable`,e[e.Watching=2]=`Watching`,e[e.RecursedCheck=4]=`RecursedCheck`,e[e.Recursed=8]=`Recursed`,e[e.Dirty=16]=`Dirty`,e[e.Pending=32]=`Pending`,e))(Er||{});function Dr({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function Or(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var kr=[],Ar=0,{link:jr,unlink:Mr,propagate:Nr,checkDirty:Pr,shallowPropagate:Fr}=Dr({update(e){return e._update()},notify(e){kr[Lr++]=e,e.flags&=~Er.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=Er.Mutable|Er.Dirty,Vr(e))}}),Ir=0,Lr=0,Rr,zr=0;function Br(e){try{++zr,e()}finally{--zr||Hr()}}function Vr(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=Mr(n,e)}function Hr(){if(!(zr>0)){for(;Ir{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=Rr,o=t?.compare??Object.is;if(n)Rr=i,++Ar,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=Er.Mutable|Er.RecursedCheck);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{Rr=a,n&&(i.flags&=~Er.RecursedCheck),Vr(i)}}};return n?(i.flags=Er.Mutable|Er.Dirty,i.get=function(){let e=i.flags;if(e&Er.Dirty||e&Er.Pending&&Pr(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&Fr(e)}}else e&Er.Pending&&(i.flags=e&~Er.Pending);return Rr!==void 0&&jr(i,Rr,Ar),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(Nr(e),Fr(e),Hr())}},i}function Wr(e){let t=()=>{let t=Rr;Rr=n,++Ar,n.depsTail=void 0,n.flags=Er.Watching|Er.RecursedCheck;try{return e()}finally{Rr=t,n.flags&=~Er.RecursedCheck,Vr(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:Er.Watching|Er.RecursedCheck,notify(){let e=this.flags;e&Er.Dirty||e&Er.Pending&&Pr(this.deps,this)?t():this.flags=Er.Watching},stop(){this.flags=Er.None,this.depsTail=void 0,Vr(this)}};return t(),n}var Gr=o((e=>{var t=f();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 d=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?d:t.useSyncExternalStore})),Kr=o(((e,t)=>{t.exports=Gr()})),qr=o((e=>{var t=f(),n=Kr();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}})),Jr=o(((e,t)=>{t.exports=qr()}))();function Yr(e,t){return e===t}function Xr(e,t,n=Yr){let r=(0,z.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,z.useCallback)(()=>e?.get(),[e]);return(0,Jr.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var Zr={get:()=>void 0,subscribe:()=>({unsubscribe:()=>{}})};function Qr(e){let t=Cr(),n=z.useContext(e.from?Tr:wr),r=e.from??n,i=r?e.from?t.stores.getRouteMatchStore(r):t.stores.matchStores.get(r):void 0,a=z.useRef(void 0);return Xr(i??Zr,n=>{if((e.shouldThrow??!0)&&!n&&st(),n===void 0)return;let r=e.select?e.select(n):n;if(e.structuralSharing??t.options.defaultStructuralSharing){let e=Ke(a.current,r);return a.current=e,e}return r})}function $r(e){return Qr({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function ei(e){let{select:t,...n}=e;return Qr({...n,select:e=>t?t(e.loaderDeps):e.loaderDeps})}function ti(e){return Qr({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function ni(e){return Qr({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function ri(e){let t=Cr();return z.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function ii(e){let t=Cr(),n=ri(),r=z.useRef(null);return Fe(()=>{r.current!==e&&(n(e),r.current=e)},[t,e,n]),null}function ai(e){return Qr({...e,select:t=>e.select?e.select(t.context):t.context})}var oi=m();function si(e,t){let n=Cr(),r=Le(t),{activeProps:i,inactiveProps:a,activeOptions:o,to:s,preload:c,preloadDelay:l,preloadIntentProximity:u,hashScrollIntoView:d,replace:f,startTransition:p,resetScroll:m,viewTransition:h,children:g,target:_,disabled:v,style:y,className:b,onClick:x,onBlur:S,onFocus:C,onMouseEnter:w,onMouseLeave:T,onTouchStart:E,ignoreBlocker:D,params:O,search:ee,hash:te,state:ne,mask:k,reloadDocument:A,unsafeRelative:j,from:M,_fromLocation:N,...P}=e,F=br(),re=z.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),ie=Xr(n.stores.location,e=>e,(e,t)=>e.href===t.href),I=z.useMemo(()=>{let e={_fromLocation:ie,...re};return n.buildLocation(e)},[n,ie,re]),ae=I.maskedLocation?I.maskedLocation.publicHref:I.publicHref,L=I.maskedLocation?I.maskedLocation.external:I.external,oe=z.useMemo(()=>gi(ae,L,n.history,v),[v,L,ae,n.history]),se=z.useMemo(()=>{if(oe?.external)return rt(oe.href,n.protocolAllowlist)?void 0:oe.href;if(!_i(s)&&typeof s==`string`&&s.indexOf(`:`)!==-1)try{return new URL(s),rt(s,n.protocolAllowlist)?void 0:s}catch{}},[s,oe,n.protocolAllowlist]),ce=z.useMemo(()=>{if(se)return!1;if(o?.exact){if(!zt(ie.pathname,I.pathname,n.basepath))return!1}else{let e=Rt(ie.pathname,n.basepath),t=Rt(I.pathname,n.basepath);if(!(e.startsWith(t)&&(e.length===t.length||e[t.length]===`/`)))return!1}return(o?.includeSearch??!0)&&!Ze(ie.search,I.search,{partial:!o?.exact,ignoreUndefined:!o?.explicitUndefined})?!1:!o?.includeHash||F&&ie.hash===I.hash},[o?.exact,o?.explicitUndefined,o?.includeHash,o?.includeSearch,ie,se,F,I.hash,I.pathname,I.search,n.basepath]),le=ce?Be(i,{})??li:ci,ue=ce?ci:Be(a,{})??ci,de=[b,le.className,ue.className].filter(Boolean).join(` `),fe=(y||le.style||ue.style)&&{...y,...le.style,...ue.style},[pe,me]=z.useState(!1),he=z.useRef(!1),ge=e.reloadDocument||se?!1:c??n.options.defaultPreload,_e=l??n.options.defaultPreloadDelay??0,ve=z.useCallback(()=>{n.preloadRoute({...re,_builtLocation:I}).catch(e=>{console.warn(e),console.warn(pr)})},[n,re,I]);Ie(r,z.useCallback(e=>{e?.isIntersecting&&ve()},[ve]),mi,{disabled:!!v||ge!==`viewport`}),z.useEffect(()=>{he.current||!v&&ge===`render`&&(ve(),he.current=!0)},[v,ve,ge]);let ye=e=>{let t=e.currentTarget.getAttribute(`target`),r=_===void 0?t:_;if(!v&&!yi(e)&&!e.defaultPrevented&&(!r||r===`_self`)&&e.button===0){e.preventDefault(),(0,oi.flushSync)(()=>{me(!0)});let t=n.subscribe(`onResolved`,()=>{t(),me(!1)});n.navigate({...re,replace:f,resetScroll:m,hashScrollIntoView:d,startTransition:p,viewTransition:h,ignoreBlocker:D})}};if(se)return{...P,ref:r,href:se,...g&&{children:g},..._&&{target:_},...v&&{disabled:v},...y&&{style:y},...b&&{className:b},...x&&{onClick:x},...S&&{onBlur:S},...C&&{onFocus:C},...w&&{onMouseEnter:w},...T&&{onMouseLeave:T},...E&&{onTouchStart:E}};let be=e=>{if(v||ge!==`intent`)return;if(!_e){ve();return}let t=e.currentTarget;if(pi.has(t))return;let n=setTimeout(()=>{pi.delete(t),ve()},_e);pi.set(t,n)},xe=e=>{v||ge!==`intent`||ve()},Se=e=>{if(v||!ge||!_e)return;let t=e.currentTarget,n=pi.get(t);n&&(clearTimeout(n),pi.delete(t))};return{...P,...le,...ue,href:oe?.href,ref:r,onClick:hi([x,ye]),onBlur:hi([S,Se]),onFocus:hi([C,be]),onMouseEnter:hi([w,be]),onMouseLeave:hi([T,Se]),onTouchStart:hi([E,xe]),disabled:!!v,target:_,...fe&&{style:fe},...de&&{className:de},...v&&ui,...ce&&di,...F&&pe&&fi}}var ci={},li={className:`active`},ui={role:`link`,"aria-disabled":!0},di={"data-status":`active`,"aria-current":`page`},fi={"data-transitioning":`transitioning`},pi=new WeakMap,mi={rootMargin:`100px`},hi=e=>t=>{for(let n of e)if(n){if(t.defaultPrevented)return;n(t)}};function gi(e,t,n,r){if(!r)return t?{href:e,external:!0}:{href:n.createHref(e)||`/`,external:!1}}function _i(e){if(typeof e!=`string`)return!1;let t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var vi=z.forwardRef((e,t)=>{let{_asChild:n,...r}=e,{type:i,...a}=si(r,t),o=typeof r.children==`function`?r.children({isActive:a[`data-status`]===`active`}):r.children;if(!n){let{disabled:e,...t}=a;return z.createElement(`a`,t,o)}return z.createElement(n,a,o)});function yi(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var bi=class extends mr{constructor(e){super(e),this.useMatch=e=>Qr({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>ai({...e,from:this.id}),this.useSearch=e=>ni({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>ti({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>ei({...e,from:this.id}),this.useLoaderData=e=>$r({...e,from:this.id}),this.useNavigate=()=>ri({from:this.fullPath}),this.Link=z.forwardRef((e,t)=>(0,B.jsx)(vi,{ref:t,from:this.fullPath,...e}))}};function xi(e){return new bi(e)}var Si=class extends hr{constructor(e){super(e),this.useMatch=e=>Qr({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>ai({...e,from:this.id}),this.useSearch=e=>ni({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>ti({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>ei({...e,from:this.id}),this.useLoaderData=e=>$r({...e,from:this.id}),this.useNavigate=()=>ri({from:this.fullPath}),this.Link=z.forwardRef((e,t)=>(0,B.jsx)(vi,{ref:t,from:this.fullPath,...e}))}};function Ci(e){return new Si(e)}function wi(e){let t=Cr(),n=`not-found-${Xr(t.stores.location,e=>e.pathname)}-${Xr(t.stores.status,e=>e)}`;return(0,B.jsx)(gr,{getResetKey:()=>n,onCatch:(t,n)=>{if(Gt(t))e.onCatch?.(t,n);else throw t},errorComponent:({error:t})=>{if(Gt(t))return e.fallback?.(t);throw t},children:e.children})}function Ti(){return(0,B.jsx)(`p`,{children:`Not Found`})}function Ei(e){return(0,B.jsx)(B.Fragment,{children:e.children})}function Di(e,t,n){return t.options.notFoundComponent?(0,B.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,B.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,B.jsx)(Ti,{})}var Oi=z.memo(function({matchId:e}){let t=Cr(),n=t.stores.matchStores.get(e);n||st();let r=Xr(t.stores.loadedAt,e=>e),i=Xr(n,e=>e);return(0,B.jsx)(ki,{router:t,matchId:e,resetKey:r,matchState:z.useMemo(()=>{let e=i.routeId,n=t.routesById[e].parentRoute?.id;return{routeId:e,ssr:i.ssr,_displayPending:i._displayPending,parentRouteId:n}},[i._displayPending,i.routeId,i.ssr,t.routesById])})});function ki({router:e,matchId:t,resetKey:n,matchState:r}){let i=e.routesById[r.routeId],a=i.options.pendingComponent??e.options.defaultPendingComponent,o=a?(0,B.jsx)(a,{}):null,s=i.options.errorComponent??e.options.defaultErrorComponent,c=i.options.onCatch??e.options.defaultOnCatch,l=i.isRoot?i.options.notFoundComponent??e.options.notFoundRoute?.options.component:i.options.notFoundComponent,u=r.ssr===!1||r.ssr===`data-only`,d=(!i.isRoot||i.options.wrapInSuspense||u)&&(i.options.wrapInSuspense??a??(i.options.errorComponent?.preload||u))?z.Suspense:Ei,f=s?gr:Ei,p=l?wi:Ei;return(0,B.jsxs)(i.isRoot?i.options.shellComponent??Ei:Ei,{children:[(0,B.jsx)(wr.Provider,{value:t,children:(0,B.jsx)(d,{fallback:o,children:(0,B.jsx)(f,{getResetKey:()=>n,errorComponent:s||vr,onCatch:(e,t)=>{if(Gt(e))throw e.routeId??=r.routeId,e;c?.(e,t)},children:(0,B.jsx)(p,{fallback:e=>{if(e.routeId??=r.routeId,!l||e.routeId&&e.routeId!==r.routeId||!e.routeId&&!i.isRoot)throw e;return z.createElement(l,e)},children:u||r._displayPending?(0,B.jsx)(yr,{fallback:o,children:(0,B.jsx)(ji,{matchId:t})}):(0,B.jsx)(ji,{matchId:t})})})})}),r.parentRouteId===`__root__`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(Ai,{resetKey:n}),(e.options.scrollRestoration,null)]}):null]})}function Ai({resetKey:e}){let t=Cr(),n=z.useRef(void 0);return Fe(()=>{let e=t.latestLocation.href;(n.current===void 0||n.current!==e)&&(t.emit({type:`onRendered`,...Vn(t.stores.location.get(),t.stores.resolvedLocation.get())}),n.current=e)},[t.latestLocation.state.__TSR_key,e,t]),null}var ji=z.memo(function({matchId:e}){let t=Cr(),n=(e,n)=>t.getMatch(e.id)?._nonReactive[n]??e._nonReactive[n],r=t.stores.matchStores.get(e);r||st();let i=Xr(r,e=>e),a=i.routeId,o=t.routesById[a],s=z.useMemo(()=>{let e=(t.routesById[a].options.remountDeps??t.options.defaultRemountDeps)?.({routeId:a,loaderDeps:i.loaderDeps,params:i._strictParams,search:i._strictSearch});return e?JSON.stringify(e):void 0},[a,i.loaderDeps,i._strictParams,i._strictSearch,t.options.defaultRemountDeps,t.routesById]),c=z.useMemo(()=>{let e=o.options.component??t.options.defaultComponent;return e?(0,B.jsx)(e,{},s):(0,B.jsx)(Mi,{})},[s,o.options.component,t.options.defaultComponent]);if(i._displayPending)throw n(i,`displayPendingPromise`);if(i._forcePending)throw n(i,`minPendingPromise`);if(i.status===`pending`){let e=o.options.pendingMinMs??t.options.defaultPendingMinMs;if(e){let n=t.getMatch(i.id);if(n&&!n._nonReactive.minPendingPromise){let t=Qe();n._nonReactive.minPendingPromise=t,setTimeout(()=>{t.resolve(),n._nonReactive.minPendingPromise=void 0},e)}}throw n(i,`loadPromise`)}if(i.status===`notFound`)return Gt(i.error)||st(),Di(t,o,i.error);if(i.status===`redirected`)throw tn(i.error)||st(),n(i,`loadPromise`);if(i.status===`error`)throw i.error;return c}),Mi=z.memo(function(){let e=Cr(),t=z.useContext(wr),n,r=!1,i;{let a=t?e.stores.matchStores.get(t):void 0;[n,r]=Xr(a,e=>[e?.routeId,e?.globalNotFound??!1]),i=Xr(e.stores.matchesId,e=>e[e.findIndex(e=>e===t)+1])}let a=n?e.routesById[n]:void 0,o=e.options.defaultPendingComponent?(0,B.jsx)(e.options.defaultPendingComponent,{}):null;if(r)return a||st(),Di(e,a,void 0);if(!i)return null;let s=(0,B.jsx)(Oi,{matchId:i});return n===`__root__`?(0,B.jsx)(z.Suspense,{fallback:o,children:s}):s});function Ni(){let e=Cr(),t=z.useRef({router:e,mounted:!1}),[n,r]=z.useState(!1),i=Xr(e.stores.isLoading,e=>e),a=Xr(e.stores.hasPending,e=>e),o=V(i),s=i||n||a,c=V(s),l=i||a,u=V(l);return e.startTransition=e=>{r(!0),z.startTransition(()=>{e(),r(!1)})},z.useEffect(()=>{let t=e.history.subscribe(e.load),n=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return It(e.latestLocation.publicHref)!==It(n.publicHref)&&e.commitLocation({...n,replace:!0}),()=>{t()}},[e,e.history]),Fe(()=>{typeof window<`u`&&e.ssr||t.current.router===e&&t.current.mounted||(t.current={router:e,mounted:!0},(async()=>{try{await e.load()}catch(e){console.error(e)}})())},[e]),Fe(()=>{o&&!i&&e.emit({type:`onLoad`,...Vn(e.stores.location.get(),e.stores.resolvedLocation.get())})},[o,e,i]),Fe(()=>{u&&!l&&e.emit({type:`onBeforeRouteMount`,...Vn(e.stores.location.get(),e.stores.resolvedLocation.get())})},[l,u,e]),Fe(()=>{if(c&&!s){let t=Vn(e.stores.location.get(),e.stores.resolvedLocation.get());e.emit({type:`onResolved`,...t}),Br(()=>{e.stores.status.set(`idle`),e.stores.resolvedLocation.set(e.stores.location.get())})}},[s,c,e]),null}function Pi(){let e=Cr(),t=e.routesById.__root__.options.pendingComponent??e.options.defaultPendingComponent,n=t?(0,B.jsx)(t,{}):null,r=(0,B.jsxs)(typeof document<`u`&&e.ssr?Ei:z.Suspense,{fallback:n,children:[(0,B.jsx)(Ni,{}),(0,B.jsx)(Fi,{})]});return e.options.InnerWrap?(0,B.jsx)(e.options.InnerWrap,{children:r}):r}function Fi(){let e=Cr(),t=Xr(e.stores.firstId,e=>e),n=Xr(e.stores.loadedAt,e=>e),r=t?(0,B.jsx)(Oi,{matchId:t}):null;return(0,B.jsx)(wr.Provider,{value:t,children:e.options.disableGlobalCatchBoundary?r:(0,B.jsx)(gr,{getResetKey:()=>n,errorComponent:vr,onCatch:void 0,children:r})})}var Ii=e=>({createMutableStore:Ur,createReadonlyStore:Ur,batch:Br}),Li=e=>new Ri(e),Ri=class extends Un{constructor(e){super(e,Ii)}};function zi({router:e,children:t,...n}){Ue(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});let r=(0,B.jsx)(Sr.Provider,{value:e,children:t});return e.options.Wrap?(0,B.jsx)(e.options.Wrap,{children:r}):r}function Bi({router:e,...t}){return(0,B.jsx)(zi,{router:e,...t,children:(0,B.jsx)(Pi,{})})}var Vi=g(),Hi=(0,z.createContext)(null),Ui=`loopx-pw-locale`,Wi={en:{"acceptance.connected":`Connected`,"acceptance.mapped":`Project mapped`,"acceptance.refreshed":`State refreshed`,"acceptance.inspected":`Adapter inspected`,"acceptance.recorded":`Run recorded`,"acceptance.judged":`Feedback recorded`,"acceptance.approved":`Approval recorded`,"acceptance.ready":`Controller readiness recorded`,"acceptance.attentionSource":`Current status`,"acceptance.visionSource":`Agent acceptance criteria`,"acceptance.todoSource":`Task state`,"acceptance.runSource":`Fresh run evidence`,"acceptance.title":`Acceptance observations`,"acceptance.unavailable":`Acceptance observations are unavailable. Goal completion is unknown.`,"acceptance.partial":`Partial observations only. Completed tasks and an empty gap list do not prove Goal acceptance.`,"acceptance.gaps":`Evidence still required`,"acceptance.reasonUnknown":`Reason not provided by the source`,"acceptance.unknown":`Unknown`,"acceptance.required":`Required evidence or condition`,"acceptance.observed":`Observed at`,"acceptance.noGaps":`No gaps in the available observations. Full acceptance has not been assessed.`,"acceptance.guards":`Pending gates`,"acceptance.noGuards":`No pending gates in the available observations.`,"acceptance.scope":`Decision scope`,"acceptance.next":`Next action from current status`,"acceptance.historical_progress":`Recorded progress`,"acceptance.historical":`Historical lifecycle observations do not grant permission or certify acceptance.`,"acceptance.missing":`Sources not available:`,"acceptance.truncated":`Only the first 12 observations are shown.`,"common.actions":`Actions`,"common.agent":`Agent`,"common.allMessages":`All messages`,"common.cancel":`Cancel`,"common.close":`Close`,"common.closeActionReceipt":`Close action receipt`,"common.confirm":`Confirm`,"common.export":`Export`,"common.failed":`Failed`,"common.goal":`Goal`,"common.loading":`Loading…`,"common.none":`None`,"common.off":`Off`,"common.on":`On`,"common.open":`Open`,"common.owner":`Owner`,"common.readOnly":`Read only`,"common.recently":`Just now`,"common.status":`Status`,"common.task":`Task`,"common.you":`You`,"common.waiting":`Waiting`,"composer.addImage":`Add image`,"composer.agentProgress":`Ask Agent for a progress report`,"composer.agentProgressPrompt":`Give me a progress report for this Goal: completed, running, blocked, and next steps.`,"composer.attachImageHint":`Choose, paste, or drag an image`,"composer.clarifyDefer":`Deferring a Todo requires a deterministic resume condition. Add todo_done:, pr_merged:[owner/repo]#, capacity_available:, or resume_at:.`,"composer.clarifySingleAction":`This message contains multiple operations that may change state. Describe one operation at a time so each confirmation preview can be reviewed separately.`,"composer.createGoal":`Create Goal`,"composer.createGoalDraft":`Goal draft`,"composer.createGoalDraftDescription":`Complete the draft and send it. LoopX will show a confirmation preview first.`,"composer.createGoalDraftLead":`Create a long-term Goal:`,"composer.createGoalTemplate":`Create a long-term Goal: +Objective: +Completion criteria: +Execution boundary (optional): +Related repository (optional): +Notification method (optional):`,"composer.createGoalHint":`Insert a Goal template to review before creation`,"composer.draft":`Draft`,"composer.globalProgress":`Summarize all Goal progress`,"composer.globalProgressPrompt":`Summarize the latest progress and blockers for all active Goals.`,"composer.globalTasks":`Ask about global priorities`,"composer.globalTasksPrompt":`Which Goals need me, and what should I handle first?`,"composer.goalMessageHint":`Your message is delivered to {agent} in this Goal session.`,"composer.goalRunningHint":`{agent} is running {count} tasks · your message enters this session as guidance without interrupting it`,"composer.goalPlaceholder":`Ask or guide {goal}…`,"composer.imageAnalysisPrompt":`Analyze these images in the context of the current Goal and tell me the next step.`,"composer.imageCountError":`You can add up to {count} images.`,"composer.imagePicker":`Image file picker`,"composer.imageReadError":`Could not read image {name}.`,"composer.imageReadGenericError":`Could not read the image.`,"composer.imageSizeError":`Each image must be {size} MB or smaller.`,"composer.imageTypeError":`PNG, JPEG, WebP, and GIF images are supported.`,"composer.imagesPending":`Images to send`,"composer.immediate":`Send now`,"composer.managerMessageHint":`Your message goes to the LoopX Manager across Goals for global questions or Goal creation.`,"composer.managerPlaceholder":`Ask the LoopX Manager, or describe a new Goal…`,"composer.monitor":`Configure scheduled check`,"composer.monitorGoalQuestion":`Which Goal should receive the scheduled check?`,"composer.monitorTemplate":`Add a scheduled check for the current Goal: +Check target: +Frequency (supports 30 minutes / 2 hours / daily): Every 2 hours +Stop condition: Goal completes`,"composer.monitorTemplateWithoutGoal":`Configure a scheduled check: +Goal: +Check target: +Frequency: Every 2 hours +Stop condition: Goal completes`,"composer.monitorHint":`Fill in what to check, frequency, and stop condition before creation`,"composer.heartbeatGoalQuestion":`Which Goal should receive the Heartbeat?`,"composer.heartbeatTemplate":`Set a Heartbeat for the current Goal: +Frequency: Daily +Stop condition: Goal completes +Notification: Only notify me when needed`,"composer.heartbeatTemplateWithoutGoal":`Set up a Heartbeat: +Goal: +Frequency: Daily +Stop condition: Goal completes +Notification: Only notify me when needed`,"composer.nextAction":`Ask what’s next`,"composer.nextActionPrompt":`What should I do next?`,"composer.prepareDraft":`Insert a draft and review before sending`,"composer.send":`Send`,"composer.sendMessage":`Send a message to LoopX`,"composer.sendMessageHint":`Send message`,"composer.sentImageAlt":`Remove image {name}`,"conversation.agentPending":`Working…`,"conversation.close":`Close conversation receipt`,"conversation.convertHint":`Turn the Agent’s latest reply into a Task draft`,"conversation.full":`View full conversation`,"conversation.receipt":`Conversation receipt`,"conversation.replying":`Replying`,"conversation.title":`Manager conversation`,"conversation.toTask":`Convert to Task`,"digest.away":`Runs since your previous visit`,"digest.completed":`new completions`,"digest.failed":`new failed/interrupted runs`,"digest.needsYou":`currently need confirmation`,"feedback.applying":`Running: {title}`,"feedback.cancelFailed":`Cancel failed: {error}`,"feedback.completed":`Completed: {title}`,"feedback.executionFailed":`Execution failed: {error}`,"feedback.gateRequired":`Your confirmation is required: {summary}`,"feedback.notCompleted":`Not completed: {status}`,"feedback.goalRefreshFailed":`The Goal opened, but its latest state could not be refreshed. Use Refresh to try again.`,"feedback.preparingPreview":`Preparing confirmation preview: {title}`,"feedback.previewFailed":`Could not prepare the confirmation preview: {error}`,"feedback.sendFailed":`Send failed: {error}`,"feedback.sendGenericError":`Could not send the message. Try again later.`,"feedback.stale":`State changed, so nothing was applied. Generate a new confirmation preview.`,"feedback.taskDraftCreated":`Created a Task draft from the reply. Edit and send it to review the confirmation preview.`,"goal.defaultTitle":`New personal Goal`,"goal.initialTodo":`Work toward the completion criteria: {criteria}`,"goal.objectiveBoundary":`Execution boundary: {boundary}`,"goal.objectiveCompletion":`Completion criteria: {criteria}`,"drawer.advancedDiagnostics":`Advanced diagnostics`,"drawer.agentWorking":`Agent is continuing; the record updates automatically.`,"drawer.analysis":`Analyzing`,"drawer.apply":`Confirm and apply`,"drawer.applying":`Applying…`,"drawer.attentionBlocking":`Blocking an Agent`,"drawer.attentionWaiting":`Waiting for your decision`,"drawer.autoNotify":`Human-gate auto notifications`,"drawer.branch":`Branch`,"drawer.closeDetail":`Close details and return to {context}`,"drawer.connected":`Connected`,"drawer.correctionDescription":`The message keeps the current Goal, Todo, and Agent Session context.`,"drawer.correctionLabel":`Guide {agent}`,"drawer.correctionPlaceholder":`For example: focus on permission risks first and do not commit yet…`,"drawer.correctionSend":`Send guidance`,"drawer.correctionTextarea":`Enter guidance for Goal {goal}, Agent {agent}, Run {run}`,"drawer.copyRepository":`Copy repository identity`,"drawer.copyRepositoryDone":`Repository identity copied`,"drawer.copyRepositoryError":`Copy failed. Check browser clipboard permission.`,"drawer.copyRepositorySuccess":`Copied. You can paste it into another tool.`,"drawer.cost":`Cost 24h / 7d`,"drawer.costShort":`Cost`,"drawer.durationShort":`Duration`,"drawer.period24h":`24h`,"drawer.period7d":`7d`,"drawer.tokens":`Tokens 24h / 7d`,"drawer.tokensShort":`tokens`,"drawer.usageNotMeasured":`Not measured`,"drawer.currentGoal":`Current Goal`,"attentionDetail.title":`Request details`,"attentionDetail.request":`What is requested`,"attentionDetail.decision":`Decision requested`,"attentionDetail.unknownRequest":`Not specified; review the source before deciding`,"attentionDetail.open":`Open in current projection`,"attentionDetail.closed":`Closed`,"attentionDetail.deferred":`Deferred`,"attentionDetail.superseded":`Replaced`,"attentionDetail.unknown":`Status not provided`,"attentionDetail.unavailable":`The source has not confirmed this item; refresh before acting`,"attentionDetail.unknownReason":`The source has not provided a reason.`,"attentionDetail.targetTodo":`Linked Todo to unblock`,"attentionDetail.targetAgent":`Agent named by the request`,"attentionDetail.scope":`Declared decision scope`,"attentionDetail.notProvided":`Not provided`,"attentionDetail.replacement":`Replacement Todo`,"attentionDetail.openReplacement":`Open replacement`,"attentionDetail.boundary":`Reading this detail does not resolve a gate or grant authority. Available decisions require a fresh preview.`,"drawer.decisionDefaultEvidence":`No additional public-safe evidence is attached. The next step will still show a Preview first.`,"drawer.decisionDefaultReason":`This decision affects the next step of the current Todo.`,"drawer.decisionDefer":`Decide later`,"drawer.decisionMore":`More decisions`,"drawer.decisionReject":`Reject`,"drawer.decisionReview":`Review impact and decide`,"drawer.dependencies":`Dependencies`,"drawer.detailsAndActions":`Details & actions`,"drawer.duration":`Duration 24h / 7d`,"drawer.evidence":`Evidence`,"drawer.executionHistory":`Execution history`,"drawer.executionRecord":`Run record`,"drawer.executionRecordAndResult":`Execution & result`,"drawer.explainDecision":`Explain this decision`,"drawer.gateApproveHint":`Run one command in the terminal to complete approval:`,"drawer.gateRejectHint":`Replace approve with reject at the end to decline. This notice disappears after the command runs.`,"drawer.gateRequiresHost":`Host confirmation required`,"drawer.gateRequiresHostDescription":`This page cannot approve this protected permission change. Nothing was written by your click.`,"drawer.goalAutoRun":`Automatic runs for this Goal`,"drawer.goalChanges":`Pending changes for this Goal`,"drawer.goalDetails":`Goal details`,"drawer.group":`Group`,"drawer.inspectorFull":`Switch to full screen`,"drawer.inspectorFullView":`Full-screen view`,"drawer.inspectorHalf":`Switch to half screen`,"drawer.inspectorHalfView":`Half-screen view`,"drawer.lastNotification":`Latest notification`,"drawer.larkConfigure":`Configure Lark connection`,"drawer.larkConnect":`Connect Lark App`,"drawer.larkConnection":`Lark connection`,"drawer.larkNotConfigured":`Not configured`,"drawer.larkNotConfiguredDescription":`After setup, LoopX sends a Feishu notification when this Goal needs your confirmation.`,"drawer.managerChanges":`Pending Manager changes`,"drawer.moreActions":`More actions`,"drawer.moreRunActions":`More run actions`,"drawer.nextTransition":`Next transition`,"drawer.noExecutionHistory":`No execution history yet.`,"drawer.noRun":`Execution Session has not started`,"drawer.noRunDescription":`Run records will appear here after an Agent starts execution.`,"drawer.notAssigned":`Unassigned`,"drawer.notLinked":`Not linked`,"drawer.notSet":`Not set`,"drawer.outputDetails":`Output details`,"drawer.outputRecorded":`This output is recorded on the current Goal.`,"drawer.outputSafePreview":`Public-safe output preview`,"drawer.outputRun":`Run`,"drawer.outputTodo":`Todo`,"drawer.outputs":`Outputs from this run`,"drawer.previewUnavailable":`No public-safe inline preview is available for this output.`,"drawer.priority":`Priority`,"drawer.progress":`Progress`,"drawer.proposalApplied":`Applied. LoopX state will refresh.`,"drawer.proposalApplyFailed":`Apply failed. No changes were written.`,"drawer.proposalApplyFailedHint":`Refresh the Goal state and regenerate. If it still fails, keep this page open and inspect advanced diagnostics.`,"drawer.proposalClose":`Close`,"drawer.proposalDefer":`Later`,"drawer.proposalDeferred":`Deferred. You can apply it later or regenerate it.`,"drawer.proposalEnterGoal":`Open new Goal`,"drawer.proposalExplainer":`After confirmation, LoopX applies this change and shows the write result. Closing or canceling changes nothing.`,"drawer.proposalRecheck":`Recheck against latest state`,"drawer.proposalRegenerate":`Retry with latest state`,"drawer.proposalRejected":`Rejected. This change will not be written.`,"drawer.proposalStale":`Source state changed. Recheck against the latest state.`,"drawer.proposalViewGoal":`View updated Goal`,"drawer.reassign":`Reassign to`,"drawer.reassignSummary":`Reassign: {task}`,"drawer.reason":`Reason`,"drawer.recoveryDescription":`Local history is preserved. Choose a recovery path.`,"drawer.recoveryFailed":`Upstream Session recovery failed`,"drawer.recoveryNewSession":`Start a new Session with context`,"drawer.recoveryRetry":`Retry recovery`,"drawer.repositoryRole":`Execution workspace`,"drawer.repository":`Repository`,"drawer.replyMode":`Reply mode`,"drawer.subagentApplied":`Applied and verified against the shared Goal state.`,"drawer.subagentAppliedRefreshFailed":`Applied and verified. The status view could not refresh; retry the page refresh later.`,"drawer.subagentApplying":`Applying and verifying shared-state readback…`,"drawer.subagentApplyFailed":`Could not apply the sub-agent setting.`,"drawer.subagentChildLimit":`Current limit`,"drawer.subagentConfirmDisable":`Confirm turning off sub-agent execution`,"drawer.subagentConfirmEnable":`Confirm turning on sub-agent execution`,"drawer.subagentCurrentBoundary":`Current task-domain restriction`,"drawer.subagentDescription":`Allows the runtime to create temporary child agents for independent tasks only after Todo, quota, capability, and write-scope gates pass. It does not force parallel work or grant durable authority.`,"drawer.subagentDisable":`Preview turning off sub-agent execution`,"drawer.subagentDisableSummary":`New child-agent execution will be disabled for this Goal. Existing Todo ownership and execution records stay unchanged.`,"drawer.subagentDomainInvalid":`The selected task-domain restriction is invalid.`,"drawer.subagentDomainTodoCount":`{count} matching open Todos`,"drawer.subagentDomains":`Task-domain restriction (optional)`,"drawer.subagentDomainsEmpty":`No open advancement Todo declares task_domain. Leave this empty to keep child execution unrestricted by task domain.`,"drawer.subagentDomainsHint":`Leave every option clear to apply no task-domain filter. Selecting domains admits only matching typed Todos; all other execution gates still apply.`,"drawer.subagentDomainsUnrestricted":`No task-domain restriction`,"drawer.subagentEnable":`Preview turning on sub-agent execution`,"drawer.subagentLabel":`Per-Goal execution boundary`,"drawer.subagentModel":`Child model`,"drawer.subagentEffort":`Child reasoning effort`,"drawer.subagentModelDefault":`Host default`,"drawer.subagentLunaPreset":`Use Luna / max`,"drawer.subagentClearModel":`Clear model preference`,"drawer.subagentModelHint":`Use Preview configuration update to save this preference. It can be saved while execution is off; host support is checked at launch.`,"drawer.subagentModelRequired":`Choose a child model before setting reasoning effort.`,"drawer.subagentMaxChildren":`Maximum child agents`,"drawer.subagentNoChange":`The current Goal already matches this setting; nothing was written.`,"drawer.subagentPending":`Pending confirmation`,"drawer.subagentPreviewBoundary":`Preview configuration update`,"drawer.subagentPreviewFailed":`Could not create the sub-agent setting preview.`,"drawer.subagentPreviewing":`Checking the latest Goal state…`,"drawer.subagentPreviewReady":`Preview locked. Confirm to apply this Goal setting.`,"drawer.subagentPreviewSummary":`Allow up to {count} child agents. Task-domain restriction: {domains}.`,"drawer.subagentRemoteReadOnly":`This source is read only. Open the Goal on its host to change the setting.`,"drawer.subagentTitle":`Adaptive sub-agent execution`,"drawer.remoteDetailsDescription":`SSH sources expose public-safe status only and do not read connection settings from the source host.`,"drawer.remoteDetailsUnavailable":`Remote details are not projected`,"drawer.resumeNo":`No`,"drawer.resumeYes":`Yes`,"drawer.runDetails":`Execution Session`,"drawer.runInterrupt":`Interrupt this run`,"drawer.runLatest":`View latest execution`,"drawer.runNewSession":`Start new Session`,"drawer.runCloseSession":`Close Session`,"drawer.runRecordEmpty":`No run record yet. The Agent has not started this execution. Check waiting conditions or resume the Session under Details & actions.`,"drawer.runRecordProjected":`No step-by-step record is available. LoopX read {completed}/{total} projected steps{outputs}; inspect the Session under Details & actions.`,"drawer.runRecordProjectedOutputs":` and {count} outputs`,"drawer.runRoleAssistant":`Completed`,"drawer.runRoleSystem":`Needs review`,"drawer.runRoleUser":`Task received`,"drawer.runView":`Session views`,"drawer.scheduleAdd":`Add scheduled check`,"drawer.scheduleDefaultNotification":`Notify only when you are needed`,"drawer.scheduleDefaultStop":`Goal completes or owner stops it`,"drawer.scheduleDefaultTarget":`Wake according to this Goal’s LoopX schedule.`,"drawer.scheduleEdit":`Change to every 2 hours`,"drawer.scheduleLast":`Last run`,"drawer.scheduleLocalTimezone":`Local timezone`,"drawer.scheduleNext":`Next run`,"drawer.scheduleNeverRun":`Not run yet`,"drawer.scheduleNotification":`Notification`,"drawer.schedulePause":`Pause`,"drawer.schedulePending":`Waiting for schedule`,"drawer.scheduleResume":`Resume`,"drawer.scheduleRunNow":`Run now`,"drawer.scheduleStop":`Stop {kind}`,"drawer.scheduleStopCondition":`Stop condition`,"drawer.scheduleTimezone":`Timezone`,"drawer.sessionRecoverable":`Resumable`,"drawer.sessionStatus":`Session status`,"drawer.setupHeartbeat":`Set up Heartbeat`,"drawer.taskActions":`Pending Todo actions`,"drawer.taskAdvancement":`Advancement task`,"drawer.taskBlock":`Mark blocked`,"drawer.taskComplete":`Mark complete`,"drawer.taskCompletedNote":`This task is retained as a read-only record.`,"drawer.taskCompletedTitle":`Task completed`,"drawer.taskDefer":`Defer`,"drawer.taskDeferCondition":`Todo defer resume condition`,"drawer.taskDeferInvalid":`Unsupported condition format; use one of the deterministic conditions below.`,"drawer.taskDeferPlaceholder":`For example, resume_at:2026-09-14T09:00:00+08:00`,"drawer.taskDeferReview":`Review defer`,"drawer.taskDeferSupported":`Supports todo_done, pr_merged, capacity_available, and timezone-aware resume_at conditions.`,"drawer.taskDeferUntil":`Defer until`,"drawer.taskDetails":`Todo details`,"drawer.taskInfo":`Task information`,"drawer.taskManage":`Manage task`,"drawer.taskNextCompleted":`Create a follow-up task`,"drawer.taskNextOpen":`Advance or update status`,"drawer.taskOrdinary":`Task`,"drawer.taskStatusBlocked":`Blocked`,"drawer.taskStatusDeferred":`Deferred`,"drawer.resumeWhen":`Resume condition`,"drawer.resumeState":`Resume state`,"drawer.resumePending":`Waiting for condition`,"drawer.resumeReady":`Ready to resume`,"drawer.resumeReceipt":`Resume receipt`,"drawer.taskNextDeferred":`Wait for the resume condition, then reassess`,"drawer.taskNextResumeReady":`Resume condition met; awaiting lifecycle replan`,"drawer.taskStatusCompleted":`Completed`,"drawer.taskStatusOpen":`Ready`,"drawer.taskSuccessor":`Create follow-up Todo`,"drawer.taskSuccessorNote":`Owner marked this blocked while waiting for more context.`,"drawer.taskSuccessorSummary":`Create follow-up Todo: {task}`,"drawer.taskSuccessorText":`Follow-up work for {task}`,"drawer.taskType":`Task type`,"drawer.topic":`Topic`,"drawer.trigger":`Trigger`,"drawer.titleAttention":`Needs you`,"drawer.titleOutput":`Output details`,"drawer.titleProposalApplied":`Execution result`,"drawer.titleProposalConfirm":`Confirm execution`,"drawer.titleSchedule":`Scheduled check`,"drawer.unconfigured":`Not configured`,"drawer.workspaceCandidates":`Available workspaces`,"files.emptySummary":`Public-safe output`,"files.empty":`No files, outputs, or verified reports yet.`,"files.loadingReports":`Loading verified milestone reports…`,"files.reportDelta":`+{added} added · {changed} changed`,"files.reportAdded":`added`,"files.reportChanged":`changed`,"files.reportGeneration":`Generation`,"files.reportLoadFailed":`Could not load verified reports`,"files.reportPublication":`Publication`,"files.title":`Files & Outputs`,"files.verifiedReport":`Verified milestone report`,"header.agentUnavailable":`Unavailable`,"header.chatRuntime":`Chat`,"header.workAgentCount":`{count} work Agents`,"header.chat":`Chat`,"header.files":`Files`,"header.goalCapabilities":`Capability settings`,"header.goalCapabilitiesDescription":`Manage overrides and inherited machine defaults.`,"header.goalDetails":`Goal details`,"header.goalDetailsDescription":`Review status, usage, repository, notifications, and sessions.`,"header.goalSettings":`Goal settings`,"header.goalSettingsDescription":`Open Goal details or capability settings`,"header.goalNavigation":`Goal navigation`,"header.goalView":`Goal view`,"header.live":`Live`,"header.manager":`LoopX Manager`,"header.managerDescription":`Your personal workspace across Goals`,"header.managerOverview":`Overview`,"header.managerView":`Manager view`,"header.openGoalNavigation":`Open Goal navigation`,"header.readOnlySourceDescription":`{source} is displayed read-only through an SSH tunnel`,"header.refresh":`Refresh status`,"header.refreshDone":`Updated just now`,"header.refreshFailed":`Refresh failed`,"header.refreshing":`Refreshing`,"header.selectAgent":`Select Agent`,"header.selectChatRuntime":`Select chat runtime`,"header.tasks":`Tasks`,"header.themeBrutal":`Switch to brutal theme`,"header.themePaper":`Switch to default theme`,"home.blockingSummary":`{count} are blocking an Agent.`,"home.completedGoals":`Completed Goals`,"home.empty":`Nothing here`,"startup.goalLoading":`Loading status…`,"startup.goalError":`Could not load status`,"startup.progress":`{loaded} of {total} active Goals loaded`,"startup.partial":`Goal states are updating. Counts are incomplete.`,"startup.independent":`Other Goals remain available while this Goal loads.`,"startup.error.timeout":`The request timed out. Retry when the local service is ready.`,"startup.error.network":`The connection was interrupted. Retry to reconnect.`,"startup.error.service":`The local service is temporarily unavailable. Retry to continue.`,"startup.error.revision":`The Goal directory changed during loading. Refresh to synchronize.`,"startup.error.scope":`This Goal is no longer available in the selected source. Refresh the directory.`,"startup.error.invalid":`The status response could not be read. Refresh or check for a LoopX update.`,"startup.retry":`Retry`,"startup.retryFailed":`Retry failed Goals`,"startup.failedCount":`{count} Goals could not be loaded. Ready Goals remain available.`,"home.greeting":`Hi, I’m your LoopX Manager`,"home.history":`History`,"home.lane.needsYou":`Needs you`,"home.lane.needsYouDescription":`Waiting for your decision, authorization, or context`,"home.lane.observing":`Observing`,"home.lane.observingDescription":`Monitoring continuously and notifying you when something changes`,"home.lane.running":`Running`,"home.lane.runningDescription":`Agents are making progress and reporting back`,"home.lane.scheduled":`Scheduled`,"home.lane.scheduledDescription":`Queued until its time or prerequisite arrives`,"home.noActivity":`No activity yet`,"home.noFirstActivity":`Waiting for first activity`,"home.noCompletedGoals":`No completed Goals yet`,"home.preservedState":`State is preserved and can be resumed`,"home.stopped":`Stopped`,"home.systemHealth":`System health: {summary}`,"home.taskCount":`{count} Tasks`,"home.todayAt":`Today {time}`,"home.waitingCount":`You have {count} items to handle.`,"home.workspace":`Goal workspace`,"lark.allMessages":`All messages in this topic`,"lark.allTopicMessages":`All topic messages`,"lark.agentIngress":`Agent ingress`,"lark.agentAppPermissions":`Every selected Agent needs a Lark App that is ready for group mentions and replies.`,"lark.agentApps":`Lark App per Agent`,"lark.agentAppsDescription":`The default App is preselected. Assign a different compatible App when an Agent needs its own bot identity.`,"lark.agentAppSelection":`Lark App for {agent}`,"lark.appCreated":`App created`,"lark.appCreateFailed":`Creation failed`,"lark.appLoading":`Loading available Lark Apps…`,"lark.appPermissions":`This App can send connection messages, but lacks the bot permissions required to receive group mentions or reply automatically. Enable im:message.group_at_msg:readonly, im:message.send_as_bot, and the im.message.receive_v1 event, publish a new version, then refresh.`,"lark.appProfile":`Lark App`,"lark.apps":`Lark Apps`,"lark.autoReplyUnavailable":`Auto reply unavailable`,"lark.autoReplyReady":`Auto reply ready`,"lark.bindGoal":`Bind to Goal`,"lark.cancel":`Cancel`,"lark.cardinality":`One Lark App · many Goals · one isolated route per Agent`,"lark.capture":`Capture`,"lark.captureAddressed":`Only messages that mention or reply to the App`,"lark.captureAll":`All messages in this Goal topic`,"lark.captureScope":`Capture scope`,"lark.captureScopeDescription":`Controls which Topic messages enter LoopX without expanding Agent permissions.`,"lark.closeConnection":`Close connection dialog`,"lark.closeCreate":`Close create dialog`,"lark.closeSettings":`Close Lark settings`,"lark.connect":`Connect`,"lark.connectAllAgents":`Connect every registered Agent`,"lark.connectAllAgentsAction":`Connect {count} Agents`,"lark.connectAllAgentsDescription":`Create {count} isolated Agent Topics in one guided action. Send requests inside the matching Topic; each Agent keeps its own route and inbox.`,"lark.connectApp":`Connect Lark App`,"lark.connection":`Connection`,"lark.connections":`Connections`,"lark.configuration":`Lark configuration`,"lark.continueFeishu":`Continue in Feishu`,"lark.createAutomatically":`Create Goal topic automatically`,"lark.createAutomaticallyDescription":`A dedicated, Agent-labelled Topic will be created for every selected Agent.`,"lark.defaultAgentAppDescription":`Used to find the target group and as the default for every selected Agent. Per-Agent choices below override it.`,"lark.description":`Manage reusable Lark Apps and connect group chats to Goals through dedicated topics.`,"lark.editConnection":`Edit Lark Connection`,"lark.goalConnections":`{count} Goal connections`,"lark.goalTopicConnections":`Lark Goal Topic connections`,"lark.groupChat":`Group chat`,"lark.groupEmpty":`This bot has not joined a group that can be connected. Add it to a Feishu group first, then return to refresh or search.`,"lark.groupLoading":`Reading groups joined by this bot…`,"lark.groupSearch":`Search groups joined by this bot`,"lark.historyPermission":`Group-history permission (separate capability)`,"lark.health.eventProcessed":`{events} events processed, {replies} replies sent.`,"lark.health.eventUnverified":`Event subscription needs verification`,"lark.health.eventUnverifiedDetail":`The provider listener is ready, but no event has arrived. Enable im.message.receive_v1 and group mention permissions, publish a new version, then send a new @ mention inside this Agent Topic. Group-level messages fail closed when multiple Agent routes exist.`,"lark.health.ignoredSelf":`The bot’s own message was ignored to prevent duplicate replies.`,"lark.health.invalidRouting":`Invalid routing configuration`,"lark.health.invalidRoutingDetail":`The connection was safely disabled. Select a processing mode again and save.`,"lark.health.lastStatus":`Latest event status: {status}`,"lark.health.listening":`Listening`,"lark.health.messageContextPermission":`Message permission required`,"lark.health.messageContextPermissionDetail":`A message event arrived, but group context could not be read. Publish and authorize group message read access for this App.`,"lark.health.notAddressed":`Latest message did not directly @ the bot`,"lark.health.notAddressedDetail":`Listening is healthy. This connection only responds to direct @ mentions or replies to the bot.`,"lark.health.notStarted":`Listener not started`,"lark.health.notStartedDetail":`Refresh the connection or restart LoopX, then try again.`,"lark.health.processingFailed":`Message processing failed`,"lark.health.processingFailedDetail":`The message event arrived, but Agent processing failed. Review local diagnostics and retry.`,"lark.health.queued":`Queued in the Agent inbox`,"lark.health.queuedDetail":`The message will be processed asynchronously by {agent} without starting a general Chat Session.`,"lark.health.sourceDisconnected":`Event connection disconnected`,"lark.health.sourceDisconnectedDetail":`The event consumer exited unexpectedly. Check that the app profile uses Feishu for Feishu apps or Lark for international Lark, then inspect connection and subscription errors. LoopX is retrying; successful history queries do not prove live delivery.`,"lark.health.retrying":`Retrying listener`,"lark.health.retryingDetail":`Event listening was interrupted and LoopX is retrying automatically.`,"lark.health.routeAmbiguous":`Message matches multiple Goals`,"lark.health.routeAmbiguousDetail":`The same bot and group have multiple full-group capture connections. Use a separate bot for each Agent or keep only one full-group connection.`,"lark.health.routeMismatch":`Message did not match this Goal Topic`,"lark.health.routeMismatchDetail":`The event came from another group or Topic. Reconnect this Goal to the correct group, then send a new @ mention.`,"lark.health.routeUnavailable":`Message cannot be routed to the Goal`,"lark.health.routeUnavailableDetail":`Connection data is incomplete. Reconnect this Goal, then send a new @ mention.`,"lark.health.starting":`Starting`,"lark.health.startingDetail":`LoopX is starting message event listening for this App.`,"lark.health.unavailable":`Auto reply unavailable`,"lark.health.waiting":`Waiting`,"lark.incomingMessages":`Incoming messages`,"lark.ingressAsync":`Async inbox`,"lark.ingressAsyncDescription":`Write to the Agent private inbox for a later explicit drain.`,"lark.editPreservesIdentity":`Saving preserves this App, group and Topic. Old connections upgrade to the Agent inbox by default.`,"lark.conversationKind":`Connection purpose`,"lark.managerConversation":`Manager · live conversation`,"lark.workerConversation":`Worker Agent · background tasks`,"lark.managerConversationDescription":`The built-in manager responds as you chat and delegates long-running work to background Agents. Group and private conversations keep separate histories.`,"lark.ingressLegacy":`Upgrade available`,"lark.ingressLegacyDescription":`Save this connection to upgrade to the Agent inbox. Existing messages remain in the same Topic.`,"lark.ingressQueue":`Queuing`,"lark.ingressQueueDescription":`Enter the same Agent Session's bounded FIFO queue and run after the current Turn.`,"lark.ingressSteering":`Steering`,"lark.ingressSteeringDescription":`Deliver to the active Turn and reject safely when no exact active Turn exists.`,"lark.loading":`Loading Lark configuration…`,"lark.management":`Lark management`,"lark.openEventSettings":`Open Feishu event settings`,"lark.mentions":`Mentions`,"lark.mentionsOnly":`Mentions only`,"lark.needsMessagePermissions":`Needs message permissions`,"lark.needsSetup":`Needs setup`,"lark.newApp":`New Lark App`,"lark.noAgentConfigured":`No Agent configured`,"lark.noConnections":`No matching connections.`,"lark.noProfiles":`No lark-cli App profiles are available yet.`,"lark.profileName":`Profile name`,"lark.profileValidation":`Profile can contain only letters, numbers, periods, underscores, and hyphens.`,"lark.processing":`Processing`,"lark.region":`Region`,"lark.registerAnother":`+ Register another Lark App — Create through Feishu`,"lark.reopenFeishu":`Reopen Feishu`,"lark.settingsConfigure":`Configure {goal}`,"lark.settingsDisconnect":`Disconnect {goal}`,"lark.replyMode":`Reply mode`,"lark.replyModeDescription":`Replies are limited to the source Topic to prevent cross-group or cross-Goal delivery.`,"lark.reusableApps":`{count} reusable Apps`,"lark.reusableWorkspaceApp":`Reusable workspace App`,"lark.routesUnverified":`{count} Lark routes pending verification`,"lark.saveConnection":`Save connection`,"lark.searchConnections":`Search Lark connections`,"lark.searchPlaceholder":`Search Apps, groups, Goals, or topics`,"lark.setupCopy":`LoopX opens the official Feishu creation page through lark-cli. App credentials stay in the system Keychain; LoopX stores only the profile reference.`,"lark.someoneMentions":`Someone mentions the Agent`,"lark.targetAgent":`Target Agent`,"lark.targetAgentDescription":`Choose a registered Agent in this Goal. This connection delivers to one Agent; it does not broadcast or grant permissions. Steering and Queuing require that Agent's exact active Session.`,"lark.agentUnavailable":`{agent} · no longer available`,"lark.selectRegisteredAgent":`Select an available registered Agent before connecting. The previous Agent will not be replaced automatically.`,"lark.topicPreview":`Topic preview`,"lark.topicReply":`Topic reply`,"lark.trigger":`Trigger`,"lark.waitingFeishu":`Waiting for Feishu`,"lark.waitingFeishuDescription":`Complete Feishu authorization in the new window. This page updates automatically when it is ready.`,"lark.waitingLink":`Generating the official Feishu creation link…`,"lark.error.appCreate":`Lark App creation failed`,"lark.error.appRequired":`Select a Lark App profile.`,"lark.error.bind":`Connection failed`,"lark.error.bindPreview":`Connection preview failed`,"lark.error.configuration":`Could not load Lark configuration`,"lark.error.groupLookup":`Could not read groups joined by this bot. Check the bot status and try again.`,"lark.error.groupLoad":`Could not load group chats`,"lark.error.invalidApp":`The Lark App profile is unavailable or has not completed authorization.`,"lark.error.messagePermissions":`This App lacks the bot permissions required for automatic replies. Enable im:message.group_at_msg:readonly and im:message:send_as_bot, publish a new version, then refresh.`,"lark.error.provider":`The Feishu API call failed without a verified receipt. Try again later.`,"lark.error.setupPoll":`Could not read creation status`,"lark.error.setupStart":`Could not start Lark App creation`,"lark.error.cliExecutable":`The configured lark-cli was found but cannot run. Check the installation or launch arguments.`,"lark.error.cliMissing":`lark-cli was not found. Install lark-cli and restart LoopX.`,"lark.error.cliStart":`lark-cli failed to start. Check the installation and restart LoopX.`,"lark.error.disconnect":`Disconnect failed`,"notifications.autoNotify":`Send automatically when your confirmation is required`,"notifications.bind":`Bind notification group`,"notifications.bindConfirm":`Bind “{goal}” to “{target}”. LoopX will verify that the bot is in the group and send a confirmation message.`,"notifications.bindFailed":`Binding failed`,"notifications.bound":`Bound`,"notifications.confirmBind":`Confirm binding`,"notifications.description":`Send Goal changes that need your confirmation to a Feishu group. Bindings and automatic delivery use the existing channel.`,"notifications.disabled":`Disabled`,"notifications.group":`Notification group: {target}`,"notifications.loadFailed":`Could not load notification groups`,"notifications.noTargets":`No notification groups are available. Group delivery uses a private bot identity; configure one from the terminal first:`,"notifications.notBound":`Not bound`,"notifications.recent":`Latest {time}`,"notifications.sentCount":`{count} sent`,"notifications.settings":`Goal notification bindings`,"notifications.setupFailed":`Could not update settings`,"notifications.title":`Feishu group notifications`,"proposal.field.agentId":`Agent`,"proposal.field.cadence":`Frequency`,"proposal.field.completionCriteria":`Completion criteria`,"proposal.field.executionBoundary":`Execution boundary`,"proposal.field.goalId":`Goal ID`,"proposal.field.heartbeat":`Heartbeat`,"proposal.field.initialTodos":`Initial tasks`,"proposal.field.objective":`Objective`,"proposal.field.operation":`Operation`,"proposal.field.operationState":`Operation state`,"proposal.field.confirmationBoundary":`Confirmation boundary`,"proposal.field.expiresAt":`Expires at`,"proposal.field.permission":`Permission`,"proposal.field.reason":`Reason`,"proposal.field.stopCondition":`Stop condition`,"proposal.field.target":`Check target`,"proposal.field.timezone":`Timezone`,"proposal.field.title":`Title`,"proposal.field.workspace":`Execution workspace`,"actionReview.targetChanged":`The preview target does not match the requested Goal and operation. Generate a new preview.`,"actionReview.ready_stop":`Pausing is reversible. This validated preview can apply directly; completion still requires verified readback.`,"actionReview.resume_review":`Review before restoring automatic scheduling. Quota, gates and Todo constraints still apply.`,"actionReview.delete_review":`Review removal of this stopped Goal from the registries. Project files and history are preserved.`,"actionReview.action_review":`Review the target and impact before applying this proposal.`,"actionReview.protected_action":`This action needs explicit review. Confirmation cannot replace required authority.`,"actionReview.unknown_permission":`The permission classification is not recognized. Recheck the proposal before continuing.`,"actionReview.unknown_action":`This lifecycle operation is not recognized. Recheck the proposal before continuing.`,"actionReview.incomplete_proposal":`The preview is missing validation or an available apply transition. Generate a new preview.`,"actionReview.authority_gate":`A gate prevents execution. Resolve its requirements, then recheck the proposal.`,"actionReview.stale_proposal":`The source state changed. Generate a new preview; the previous decision no longer applies.`,"actionReview.apply_pending":`Execution is in progress. Wait for its result before retrying.`,"actionReview.readback_verified":`The action completed and its resulting state was verified.`,"actionReview.readback_unverified":`The action returned without verified readback. Completion is not confirmed; recheck the state.`,"actionReview.apply_failed":`Execution did not complete. Check the failure and regenerate the preview before retrying.`,"actionReview.inactive_proposal":`This proposal is no longer ready to execute. Recheck it before continuing.`,"proposal.gate.default":`Host confirmation required`,"proposal.impact.default":`After confirmation, the canonical LoopX service will write the state change.`,"proposal.impact.goalCreate":`After confirmation, LoopX will create the Goal and its initial Todo, then let the selected Agent start the first run.`,"proposal.impact.lifecycleDelete":`After confirmation, this stopped Goal is removed from the source and global registries. Project files, history state, and backups are preserved.`,"proposal.impact.lifecycleResume":`After confirmation, the Goal becomes eligible for automatic scheduling and returns to Active Goals. Actual execution still follows quota, Gate, and Todo constraints.`,"proposal.impact.lifecycleStop":`After confirmation, automatic progress stops and the Goal moves to the collapsed Stopped list. History, Todos, and evidence remain available for resuming.`,"proposal.impact.protected":`This action must be completed through the protected LoopX write service.`,"proposal.impact.operation":`The exact terms are read-only here. Confirm or reject the same immutable request in the bound Feishu group; confirmation consumes one canonical claim.`,"proposal.primary.apply":`Confirm and apply`,"proposal.primary.goalCreate":`Create Goal and start first run`,"proposal.primary.lifecycleDelete":`Delete Goal`,"proposal.primary.lifecycleResume":`Resume Goal`,"proposal.primary.lifecycleStop":`Stop Goal`,"proposal.primary.todoStart":`Create task and start execution`,"proposal.primary.operationGroup":`Confirm in Feishu group`,"proposal.summary.goalCreate":`Create Goal: {title}`,"proposal.summary.heartbeat":`Set a Heartbeat for the current Goal`,"proposal.summary.lifecycleDelete":`Delete Goal: {title}`,"proposal.summary.lifecycleResume":`Resume Goal: {title}`,"proposal.summary.lifecycleStop":`Stop Goal: {title}`,"proposal.summary.monitor":`Create a scheduled check for the current Goal: {target}`,"proposal.workspace.current":`Current local workspace (no Repository bound)`,"proposal.workspace.named":`{workspace} (execution environment only; does not bind a repository)`,"proposal.workspaceGate.agentImpact":`Bind an Agent identity, then recheck the original action. No Goal has been written.`,"proposal.workspaceGate.agentTitle":`Bind an Agent first`,"proposal.workspaceGate.defaultSummary":`Select the Goal workspace.`,"proposal.workspaceGate.selectionImpact":`After selecting a workspace, LoopX will show the confirmation preview again. The selection itself does not write state.`,"proposal.workspaceGate.selectionTitle":`Select Goal workspace`,"projection.agentAdvancingGoal":`Agent is advancing the current Goal`,"projection.agentIdle":`Nothing needs your attention`,"projection.agentNeedsDecision":`Agent is waiting for your decision`,"projection.agentPreparingNextStep":`Agent is preparing the next step`,"projection.agentStopped":`Stopped by you; history, Todos, and evidence are preserved`,"projection.agentWaitingExternal":`Waiting for an external condition`,"projection.confirmAgentDecision":`Confirm the permission or decision the Agent needs next`,"projection.events24h":`{count} events in the last 24 hours`,"projection.firstReadOnlyAdapterCheck":`Run the first read-only adapter check and save progress`,"projection.goalVerified":`Goal state, Todos, and registration information verified`,"projection.latestRun":`Latest run`,"projection.latestValidation":`Latest validation`,"projection.nextUpdatePending":`Waiting for LoopX to update the next step`,"projection.publicSafeProjection":`Public-safe status projection`,"projection.refreshState":`Refresh LoopX status and confirm the current progress is still valid`,"projection.runEvidenceAvailable":`Run evidence is available`,"projection.runRecorded":`The latest LoopX run is recorded`,"projection.statusRefreshNeeded":`LoopX status needs to be refreshed`,"projection.todoStatusUpdated":`Todo status updated; confirming the next step`,"projection.validationRecorded":`The latest validation is recorded`,"runs.completed":`Completed`,"runs.failed":`Needs review`,"runs.interrupted":`Interrupted`,"runs.queued":`Scheduled`,"runs.ready":`Ready`,"runs.resumeFailed":`Recovery failed`,"runs.running":`Running`,"runs.unknown":`Unknown`,"runs.waiting":`Waiting`,"schedule.active":`Running`,"schedule.heartbeat":`Goal Heartbeat`,"schedule.monitor":`Scheduled & continuous task`,"schedule.paused":`Paused`,"schedule.summary":`Continuously checked under LoopX scheduling constraints`,"schedule.defaultTarget":`Check the current Goal for blockers, progress, and new outputs`,"schedule.unsupportedCalendar":`Scheduled checks do not currently support an exact weekday or time. Use a fixed interval such as “Every 30 minutes,” “Every 2 hours,” or “Daily.” The draft was preserved and no confirmation preview was created.`,"source.add":`Add source`,"source.addConfigured":`Add read-only source`,"source.addMethod":`Source setup method`,"source.addSsh":`Add SSH source`,"source.closeForm":`Close source form`,"source.configured":`Configured SSH`,"source.configuredCount":`Local SSH Hosts · {count}`,"source.configuredGroup":`Configured SSH Hosts · {count} (select to add)`,"source.connected":`Connected`,"source.connecting":`Connecting`,"source.controlPlane":`Control plane source`,"source.copy":`Copy`,"source.copyCommand":`Copy SSH tunnel command`,"source.copyError":`Could not copy the command. Copy it manually below.`,"source.copied":`Copied`,"source.description":`All explicit Hosts are loaded, including Include files. Wildcards are not listed. Run the command first; LoopX never reads SSH keys or configuration details.`,"source.host":`Local SSH Host`,"source.hostEmpty":`No explicit SSH Hosts are available in ~/.ssh/config.`,"source.hostLoadError":`Could not read local SSH Hosts.`,"source.hostPlaceholder":`Enter or search for a Host`,"source.invalid":`The SSH source settings are invalid.`,"source.loadingHosts":`Loading…`,"source.localInteractive":`Local interactive`,"source.localPort":`Local port`,"source.manual":`Manual URL`,"source.manualDescription":`Remote sources always remain read-only projections and never inherit local write permissions.`,"source.name":`Name`,"source.namePlaceholder":`Remote development machine`,"source.notAvailable":`Unavailable`,"source.readOnly":`SSH tunnel · read only`,"source.readOnlyNoticeDescription":`You can view Goals, Tasks, evidence, and run status. Writes, guidance, and Agent sessions remain on the source host.`,"source.readOnlyNoticeTitle":`Remote read-only projection`,"source.readOnlyWriteError":`Remote SSH tunnel sources are read-only projections and cannot perform control-plane writes.`,"source.refreshHosts":`Reload SSH Hosts`,"source.remove":`Remove source {source}`,"source.removeCurrent":`Remove current source`,"source.select":`Select control plane source`,"source.selectHost":`Select a configured SSH Host.`,"source.statusUrl":`Local forwarded URL`,"source.tunnelCommandPending":`Select a Host to generate the tunnel command`,"machine.absent":`Not configured`,"machine.action.create":`Create machine policy`,"machine.action.delete":`Remove machine policy`,"machine.action.unchanged":`No write required`,"machine.action.update":`Update machine policy`,"machine.applied":`Machine policy applied and read back successfully.`,"machine.applyError":`Machine policy could not be applied.`,"machine.applyPreview":`Apply reviewed preview`,"machine.changedNamespaces":`Changed namespaces`,"machine.capabilityCatalog":`Machine capability catalog`,"machine.capabilityEmpty":`No machine-configurable capabilities are registered.`,"machine.configured":`Configured`,"machine.confirmRollback":`Confirm rollback`,"machine.currentRevision":`Current revision`,"machine.currentValue":`Current machine value`,"machine.description":`Browse the same capability catalog as Goal settings. Configure supported machine defaults here; Goal-only capabilities are labeled explicitly.`,"capabilities.rawJson":`Advanced: raw JSON`,"machine.goalOnly":`This capability currently supports Goal configuration only. Open a Goal’s capability settings to configure it; no machine-wide default is applied.`,"machine.desiredRevision":`Desired revision`,"machine.editorUnavailable":`No editor is installed for this namespace`,"machine.editorUnavailableDescription":`The namespace remains visible in the registry. Install or upgrade its Dashboard editor before changing it.`,"machine.editorMode":`Editor mode`,"machine.liveDefault":`Live default; Goal override wins`,"machine.liveDefaultDescription":`Goals without an explicit override read the current machine policy at the capability’s next decision point. Changes and removal affect those existing Goals immediately; an explicit Goal override stays pinned.`,"machine.genericNamespaceDescription":`Edit this registered namespace as JSON. LoopX validates it with the capability-owned schema before previewing any write.`,"machine.jsonConfiguration":`Namespace configuration (JSON)`,"machine.jsonConfigurationHelp":`Only this namespace is updated. Other machine configuration is preserved, and Apply remains locked to the reviewed preview revision.`,"machine.jsonEditor":`JSON`,"machine.editJson":`Edit JSON`,"capabilities.jsonConfiguration":`Goal configuration (JSON)`,"capabilities.jsonHelp":`Edit registered fields for this Goal. Changes require a new preview before applying.`,"capabilities.jsonInvalid":`Enter a valid JSON object using only registered editable fields.`,"machine.backToForm":`Back to form`,"machine.jsonInvalid":`Enter one valid JSON object before previewing changes.`,"machine.loadError":`Machine configuration could not be loaded.`,"machine.machinePolicy":`Machine policy`,"machine.namespaceCount":`Registered namespaces`,"machine.namespaces":`Configuration namespaces`,"machine.periodicReport":`Periodic reports`,"machine.periodicReportDescription":`Default report policy for every Goal without an explicit override. Goal scheduling and delivery consume the effective configuration.`,"machine.periodicReportActivation":`Enabled means automatic delivery at validated stage boundaries`,"machine.periodicReportActivationDescription":`This is not a weekly timer. When LoopX validates a Goal stage completion, an Agent prepares and freezes the report, then automatically delivers it through the configured Goal Channel. The enabled subscription is standing delivery authority; failures and route drift stop closed for repair.`,"machine.changeQualityActivation":`Qualification is a quality gate, not new authority`,"machine.changeQualityActivationDescription":`Goals that inherit this policy qualify their exact final diff. safe_fix allows at most one bounded fix pass inside existing write authority; this setting never grants file, permission, or merge authority.`,"machine.replanCadenceActivation":`Review cadence changes timing, not execution authority`,"machine.replanCadenceActivationDescription":`Goals without an explicit override read this threshold before the next review decision. It does not create Turns, spend quota, or grant authority.`,"machine.preview":`Review exact machine change`,"machine.previewChanges":`Preview changes`,"machine.previewError":`A machine-policy preview could not be created.`,"machine.previewLocked":`Apply is locked to this exact revision. If machine state changes, LoopX requires a new preview.`,"machine.previewRollback":`Preview rollback`,"machine.previewRemoval":`Preview removal`,"machine.profilePreset":`Profile preset`,"machine.profilePresetHelp":`A capability-owned preset, such as weekly-progress.`,"machine.registry":`Typed registry`,"machine.requiredFields":`Enable requires a profile preset, Goal Channel route, and valid timezone.`,"machine.revision":`Machine revision`,"machine.revisionLockedReady":`All changes require a preview and apply only while that exact machine revision remains current.`,"machine.rollbackAvailable":`Rollback is available for the last apply`,"machine.rollbackDescription":`Preview the stored prior revision before restoring it.`,"machine.rollbackError":`The rollback could not be completed.`,"machine.rollbackPreviewDescription":`The prior revision is ready to restore. Confirm to apply this rollback.`,"machine.rolledBack":`The prior machine policy was restored and verified.`,"machine.removed":`Machine policy removed and the resulting configuration read back successfully.`,"machine.routeRef":`Goal Channel route`,"machine.routeRefHelp":`Use a public route alias; credentials and provider identifiers never enter this form.`,"machine.timezone":`Timezone`,"machine.timezoneHelp":`Use an IANA timezone, for example Asia/Shanghai.`,"machine.title":`Machine configuration`,"machine.unchanged":`Machine policy already matches this preview; nothing was written.`,"machine.visualEditor":`Guided`,"capabilities.atomicOverride":`Goal override is atomic`,"capabilities.atomicOverrideDescription":`A complete Goal value wins over the machine default. LoopX never mixes individual fields across scopes.`,"capabilities.applyFailed":`Goal capability changes were not applied.`,"capabilities.applyPreview":`Apply preview`,"capabilities.catalog":`Goal capability catalog`,"capabilities.chooseGoal":`Choose a Goal before inspecting its capabilities.`,"capabilities.defaultValue":`Declared default`,"capabilities.description":`Inspect the capabilities available to this Goal and the exact scope of each setting.`,"capabilities.editorPrepared":`Typed editor contract available`,"capabilities.effectiveSource":`Effective source`,"capabilities.empty":`No capability descriptors are available for this Goal.`,"capabilities.fields":`Registered fields`,"capabilities.goalPolicy":`Goal capability policy`,"capabilities.goalScope":`Goal`,"capabilities.goalValue":`Current Goal value`,"capabilities.loadFailed":`Could not load Goal capabilities`,"capabilities.loading":`Loading Goal capabilities…`,"capabilities.machineOnly":`This capability is configured only at machine scope.`,"capabilities.machineValue":`Live machine default`,"capabilities.machineScope":`Machine`,"capabilities.previewOnly":`Inspection is live. Goal writes remain unavailable until the revision-locked preview and apply path is connected.`,"capabilities.preview":`Revision-locked preview`,"capabilities.previewChanges":`Preview changes`,"capabilities.restoreInheritance":`Restore machine-default inheritance`,"capabilities.previewFailed":`Could not preview Goal capability changes.`,"capabilities.previewLocked":`Apply will re-check this exact plan revision and reject stale changes.`,"capabilities.partialWrite":`Goal value saved; shared projection needs reconciliation`,"capabilities.partialWriteDescription":`The source Goal configuration was written and read back. Its shared runtime projection did not synchronize, so do not submit the change again.`,"capabilities.refreshSource":`Refresh source value`,"capabilities.readOnly":`Read-only capability`,"capabilities.revisionLockedReady":`Changes require a preview and are applied only when its exact revision is still current.`,"capabilities.retry":`Retry`,"capabilities.source.capability_default":`Capability default`,"capabilities.source.goal_override":`Goal override`,"capabilities.source.machine_default":`Live machine default`,"capabilities.source.not_configured":`Not configured`,"capabilities.title":`Goal capabilities`,"settings.close":`Close settings`,"settings.appearance":`Appearance`,"settings.appearanceDescription":`Manage workspace display preferences in this browser.`,"settings.appearanceTabDescription":`Theme and display preferences`,"settings.capabilitiesTabDescription":`Capability overrides for this Goal`,"settings.back":`Back to workspace`,"settings.categories":`Settings categories`,"settings.description":`Manage workspace preferences and integrations.`,"settings.eyebrow":`Workspace preferences`,"settings.general":`General`,"settings.goalConnections":`Goal connections`,"settings.language":`Language`,"settings.languageDescription":`Choose the language used by the LoopX desktop workspace.`,"settings.languageEnglishDescription":`Use English for navigation, settings, and workspace controls.`,"settings.languageEnglish":`English`,"settings.languageSimplifiedChineseDescription":`Use Simplified Chinese for navigation, settings, and workspace controls.`,"settings.languageSimplifiedChinese":`Simplified Chinese`,"settings.languageStoredLocally":`This preference is stored only on this device.`,"settings.languageTabDescription":`Interface language for this device`,"settings.larkTabDescription":`Apps, group chats, and Goal Topic connections`,"settings.machineTabDescription":`Typed defaults shared by capabilities on this machine`,"settings.notifications":`Notifications`,"settings.open":`Settings`,"settings.themeDefault":`Paper`,"settings.themeDefaultDescription":`Calm and lightweight for long-running work.`,"settings.themeDescription":`Choose the workspace visual style. This preference is stored in the current browser.`,"settings.themeHighContrast":`High contrast`,"settings.themeHighContrastDescription":`Stronger borders and more prominent state blocks.`,"settings.themeLoopx":`LoopX standard`,"settings.themeLoopxDescription":`Precise monochrome surfaces, Geist type, and quiet hairline structure.`,"settings.title":`Settings`,"settings.workspaceDisplay":`Workspace display`,"settings.workspaceTheme":`Workspace theme`,"session.closeRecord":`Exit run record`,"session.details":`Session details`,"session.record":`Execution Session · Run record`,"session.recordDescription":`The timeline now shows messages and Turn records from this Session.`,"sidebar.createGoal":`Create Goal`,"sidebar.delete":`Delete`,"sidebar.deleteGoal":`Delete Goal`,"sidebar.manager":`LoopX Manager`,"sidebar.notifications":`Settings`,"sidebar.owner":`Personal workspace`,"sidebar.product":`Personal Agent workspace`,"sidebar.resume":`Resume`,"sidebar.resumeGoal":`Resume Goal`,"sidebar.stop":`Stop`,"tasks.historyLoading":`Loading history…`,"tasks.historyError":`History could not be loaded.`,"tasks.historyExpired":`History snapshot expired. Reload to continue.`,"tasks.historyRetry":`Reload`,"tasks.historyEnd":`End of completed history`,"tasks.historyMore":`Load more`,"tasks.historyLocalOnly":`Open this machine’s Dashboard to browse full history.`,"sidebar.sortGoals":`Reorder Goals`,"sidebar.dragGoal":`Drag to reorder, or use Reorder Goals`,"sidebar.moveUp":`Move {goal} up`,"sidebar.moveDown":`Move {goal} down`,"sidebar.goalMoved":`{goal} moved to position {position}`,"sidebar.orderNotSaved":`Order changed for this visit; browser storage is unavailable.`,"sidebar.stopGoal":`Stop Goal`,"sidebar.stopped":`Stopped`,"sidebar.stoppedLoading":`Loading stopped Goals`,"sidebar.stoppedLoadFailed":`Stopped Goals could not be loaded. Active Goals remain available.`,"sidebar.retryStopped":`Retry`,"state.completed":`Completed`,"state.needsRepair":`Needs repair`,"state.needsYou":`Needs you`,"state.quiet":`Quiet`,"state.running":`Running`,"state.stopped":`Stopped`,"state.waiting":`Waiting`,"tasks.blocked":`Blocked`,"tasks.agentLane":`Work Agent`,"tasks.agentLaneDescription":`Filter this Goal's projected work lanes`,"tasks.agentLaneFilter":`Filter by work Agent`,"tasks.allAgentLanes":`All Agents ({count})`,"tasks.chatAgentReplied":`Agent replied`,"tasks.chatPending":`Sent to Agent`,"tasks.chatPendingDescription":`Processing. Tasks update only after a task operation is confirmed.`,"tasks.chatRecent":`Recent conversation`,"tasks.chatUnchangedDescription":`This conversation did not directly change Tasks. Convert the reply to a Task draft and confirm it when execution is needed.`,"tasks.chatViewReply":`View reply`,"tasks.convertToTask":`Convert to Task`,"tasks.completed":`Completed`,"runs.discoveryPartial":`Some execution details are unavailable. Reconnecting; task summaries are not live execution status.`,"runs.discoveryOffline":`Execution service unavailable. Reconnecting; retained task summaries may be stale.`,"files.openConversation":`Go to conversation`,"files.exportSummary":`Export summary`,"tasks.viewDescription":`Decisions first, then work and recent completions`,"tasks.viewLabel":`Task view`,"tasks.listView":`List`,"tasks.boardView":`Board`,"tasks.completedSummary":`{count} tasks completed. Recent details are projected by the control plane when needed.`,"tasks.emptyCompleted":`No completed tasks yet.`,"tasks.emptyConfirm":`No tasks waiting for confirmation.`,"tasks.emptyRunning":`No queued or running tasks.`,"tasks.emptySchedules":`No scheduled tasks.`,"tasks.emptyGoal":`This Goal has no tasks yet. Describe the next step below and LoopX will show a confirmation preview first.`,"tasks.markComplete":`Mark complete: {name}`,"tasks.moreActions":`More actions: {name}`,"tasks.openExecution":`View execution: {name}`,"tasks.pending":`Pending`,"tasks.pendingAndRunning":`Queued / Running`,"tasks.scheduled":`Scheduled & continuous`,"tasks.sessionError":`Session issue`,"tasks.waiting":`Queued`,"tasks.waitingAge":`Waiting {age}`,"tasks.viewExecution":`View execution`,"tasks.viewResult":`View result`,"time.days":`{count} days`,"time.hours":`{count} hours`,"timeline.emptyGoal":`This Goal has no new activity`,"timeline.emptyGoalDescription":`Ask for progress or send new guidance.`,"timeline.emptyWorkspace":`Your workspace is quiet today`,"timeline.emptyWorkspaceDescription":`Describe a Goal to the LoopX Manager, or ask what deserves attention today.`,"timeline.gateHistory":`{count} historical Gates`,"timeline.pending":`Working…`,"timeline.runCompleted":`{run}: completed`,"timeline.review":`Review`,"timeline.reviewAndConfirm":`Review and confirm`,"timeline.waitingConfirmation":`Needs your confirmation`},"zh-CN":{"acceptance.connected":`已连接`,"acceptance.mapped":`已建立项目映射`,"acceptance.refreshed":`已刷新状态`,"acceptance.inspected":`已检查适配器`,"acceptance.recorded":`已记录执行`,"acceptance.judged":`已记录反馈`,"acceptance.approved":`已记录批准`,"acceptance.ready":`已记录控制器就绪`,"acceptance.attentionSource":`当前状态`,"acceptance.visionSource":`Agent 验收条件`,"acceptance.todoSource":`任务状态`,"acceptance.runSource":`最新执行证据`,"acceptance.title":`验收观察`,"acceptance.unavailable":`验收观测不可用,Goal 是否达成仍未知。`,"acceptance.partial":`当前仅有部分观测。任务完成或缺口列表为空,都不能证明 Goal 已通过验收。`,"acceptance.gaps":`仍需补充的证据`,"acceptance.reasonUnknown":`来源未提供原因`,"acceptance.unknown":`未知`,"acceptance.required":`所需证据或条件`,"acceptance.observed":`观测时间`,"acceptance.noGaps":`现有观测中没有缺口,尚未评估完整验收条件。`,"acceptance.guards":`待处理的门禁决策`,"acceptance.noGuards":`现有观测中没有待处理的门禁决策。`,"acceptance.scope":`决策范围`,"acceptance.next":`当前状态给出的下一步`,"acceptance.historical_progress":`已记录的历史进展`,"acceptance.historical":`历史生命周期记录不授予权限,也不代表通过验收。`,"acceptance.missing":`未获取的来源:`,"acceptance.truncated":`仅展示前 12 条观测。`,"common.actions":`操作`,"common.agent":`Agent`,"common.allMessages":`所有消息`,"common.cancel":`取消`,"common.close":`关闭`,"common.closeActionReceipt":`关闭操作回执`,"common.confirm":`确认`,"common.export":`导出`,"common.failed":`失败`,"common.goal":`Goal`,"common.loading":`加载中…`,"common.none":`无`,"common.off":`关闭`,"common.on":`开启`,"common.open":`打开`,"common.owner":`Owner`,"common.readOnly":`只读`,"common.recently":`刚刚`,"common.status":`状态`,"common.task":`Task`,"common.you":`你`,"common.waiting":`等待中`,"composer.addImage":`添加图片`,"composer.agentProgress":`向 Agent 获取进度报告`,"composer.agentProgressPrompt":`请给我一份当前 Goal 的进度报告:已完成、执行中、阻塞和下一步。`,"composer.attachImageHint":`选择、粘贴或拖入图片`,"composer.clarifyDefer":`暂缓 Todo 需要可自动判断的恢复条件。请补充 todo_done:、pr_merged:[owner/repo]#、capacity_available: 或 resume_at:<带时区 RFC3339 时间>。`,"composer.clarifySingleAction":`这句话包含多个可能修改状态的操作。请一次描述一项操作,我会逐项展示确认预览。`,"composer.createGoal":`创建新 Goal`,"composer.createGoalDraft":`Goal 草稿`,"composer.createGoalDraftDescription":`补充内容后发送,LoopX 会先展示待确认操作。`,"composer.createGoalDraftLead":`我想创建一个长期 Goal:`,"composer.createGoalTemplate":`我想创建一个长期 Goal: +目标: +完成标准: +执行边界(可选): +关联仓库(可选): +通知方式(可选):`,"composer.createGoalHint":`填入 Goal 模板草稿,检查后再创建`,"composer.draft":`草稿`,"composer.globalProgress":`汇总所有 Goal 进展`,"composer.globalProgressPrompt":`请帮我汇总所有活跃 Goal 的最新进展与阻塞。`,"composer.globalTasks":`询问全局待办`,"composer.globalTasksPrompt":`有哪些 Goal 正在等我?我现在该优先处理什么?`,"composer.goalMessageHint":`你的消息由 {agent} 在本 Goal 的会话中接收`,"composer.goalRunningHint":`{agent} 正在执行 {count} 个任务 · 你的消息作为纠偏进入本会话,不会打断执行`,"composer.goalPlaceholder":`询问或纠偏 {goal}…`,"composer.imageAnalysisPrompt":`请结合这些图片分析当前 Goal,并告诉我下一步。`,"composer.imageCountError":`最多添加 {count} 张图片。`,"composer.imagePicker":`图片文件选择器`,"composer.imageReadError":`无法读取图片 {name}`,"composer.imageReadGenericError":`图片读取失败。`,"composer.imageSizeError":`单张图片不能超过 {size}MB。`,"composer.imageTypeError":`支持 PNG、JPEG、WebP 和 GIF 图片。`,"composer.imagesPending":`待发送图片`,"composer.immediate":`立即发送`,"composer.managerMessageHint":`你的消息由 LoopX 管家跨 Goal 接收,支持全局询问与创建 Goal`,"composer.managerPlaceholder":`问问 LoopX 管家,或描述一个新 Goal…`,"composer.monitor":`配置定时检查`,"composer.monitorGoalQuestion":`为哪个 Goal 添加定时检查?`,"composer.monitorTemplate":`为当前 Goal 添加定时检查: +检查内容: +频率(支持 30 分钟 / 2 小时 / 每天):每 2 小时 +停止条件:Goal 完成`,"composer.monitorTemplateWithoutGoal":`配置定时检查: +Goal: +检查内容: +频率:每 2 小时 +停止条件:Goal 完成`,"composer.monitorHint":`先填写检查内容、频率和停止条件,不会立即创建`,"composer.heartbeatGoalQuestion":`为哪个 Goal 设置 Heartbeat?`,"composer.heartbeatTemplate":`为当前 Goal 设置 Heartbeat: +频率:每天 +停止条件:Goal 完成 +通知:仅在需要我时`,"composer.heartbeatTemplateWithoutGoal":`设置 Heartbeat: +Goal: +频率:每天 +停止条件:Goal 完成 +通知:仅在需要我时`,"composer.nextAction":`询问下一步`,"composer.nextActionPrompt":`我现在该做什么?`,"composer.prepareDraft":`填入编辑框,确认后再发送`,"composer.send":`发送`,"composer.sendMessage":`向 LoopX 发送消息`,"composer.sendMessageHint":`发送消息`,"composer.sentImageAlt":`移除图片 {name}`,"conversation.agentPending":`正在整理…`,"conversation.close":`关闭对话回执`,"conversation.convertHint":`将 Agent 最新回复转为 Task 草稿`,"conversation.full":`查看完整对话`,"conversation.receipt":`对话回执`,"conversation.replying":`正在回复`,"conversation.title":`管家对话`,"conversation.toTask":`转为 Task`,"digest.away":`自上次访问以来的运行记录`,"digest.completed":`新增完成运行`,"digest.failed":`新增失败或中断`,"digest.needsYou":`当前待确认`,"feedback.applying":`正在执行:{title}`,"feedback.cancelFailed":`取消失败:{error}`,"feedback.completed":`已完成:{title}`,"feedback.executionFailed":`执行失败:{error}`,"feedback.gateRequired":`需要你确认:{summary}`,"feedback.notCompleted":`操作未完成:{status}`,"feedback.goalRefreshFailed":`已打开 Goal,但暂时无法刷新最新状态。请点击刷新重试。`,"feedback.preparingPreview":`正在准备确认预览:{title}`,"feedback.previewFailed":`无法准备确认预览:{error}`,"feedback.sendFailed":`发送失败:{error}`,"feedback.sendGenericError":`消息发送失败,请稍后重试。`,"feedback.stale":`状态已变化,操作未执行,请重新生成确认预览。`,"feedback.taskDraftCreated":`已根据回复生成 Task 草稿。编辑后发送,LoopX 会先展示确认预览。`,"goal.defaultTitle":`新的个人 Goal`,"goal.initialTodo":`按完成标准推进:{criteria}`,"goal.objectiveBoundary":`执行边界:{boundary}`,"goal.objectiveCompletion":`完成标准:{criteria}`,"drawer.advancedDiagnostics":`高级诊断`,"drawer.agentWorking":`Agent 正在继续执行,记录会自动更新。`,"drawer.analysis":`正在分析`,"drawer.apply":`确认并应用`,"drawer.applying":`正在应用…`,"drawer.attentionBlocking":`正在阻塞 Agent`,"drawer.attentionWaiting":`等待你的决定`,"drawer.autoNotify":`Human-gate 自动通知`,"drawer.branch":`分支`,"drawer.closeDetail":`关闭详情:返回{context}`,"drawer.connected":`已连接`,"drawer.correctionDescription":`消息会沿用当前 Goal、Todo 与 Agent Session 上下文。`,"drawer.correctionLabel":`与 {agent} 纠偏`,"drawer.correctionPlaceholder":`例如:先关注权限风险,暂时不要提交…`,"drawer.correctionSend":`发送纠偏`,"drawer.correctionTextarea":`输入纠偏信息:Goal {goal},Agent {agent},Run {run}`,"drawer.copyRepository":`复制仓库标识`,"drawer.copyRepositoryDone":`已复制仓库标识`,"drawer.copyRepositoryError":`复制失败,请检查浏览器剪贴板权限。`,"drawer.copyRepositorySuccess":`已复制,可粘贴到其他工具。`,"drawer.cost":`成本 24h / 7d`,"drawer.costShort":`成本`,"drawer.durationShort":`时长`,"drawer.period24h":`24 小时`,"drawer.period7d":`7 天`,"drawer.tokens":`Token 24 小时 / 7 天`,"drawer.tokensShort":`Token`,"drawer.usageNotMeasured":`未采集`,"drawer.currentGoal":`当前 Goal`,"attentionDetail.title":`事项说明`,"attentionDetail.request":`需要你做什么`,"attentionDetail.decision":`需要作出决定`,"attentionDetail.unknownRequest":`来源未明确,请先查看来源再判断`,"attentionDetail.open":`当前投影中待处理`,"attentionDetail.closed":`已关闭`,"attentionDetail.deferred":`已推迟`,"attentionDetail.superseded":`已被替代`,"attentionDetail.unknown":`来源未提供状态`,"attentionDetail.unavailable":`来源尚未确认当前事项,请刷新后再操作`,"attentionDetail.unknownReason":`来源尚未提供原因。`,"attentionDetail.targetTodo":`关联的待解锁 Todo`,"attentionDetail.targetAgent":`事项指定的 Agent`,"attentionDetail.scope":`声明的决策范围`,"attentionDetail.notProvided":`来源未提供`,"attentionDetail.replacement":`替代 Todo`,"attentionDetail.openReplacement":`打开替代事项`,"attentionDetail.boundary":`阅读详情不会关闭 gate 或授予权限;作出决定前仍需新的操作预览。`,"drawer.decisionDefaultEvidence":`当前状态没有附加公开安全证据;下一步仍会先展示 Preview。`,"drawer.decisionDefaultReason":`该决定会影响当前 Todo 的下一步执行。`,"drawer.decisionDefer":`稍后决定`,"drawer.decisionMore":`更多决定`,"drawer.decisionReject":`拒绝`,"drawer.decisionReview":`查看影响并决定`,"drawer.dependencies":`依赖`,"drawer.detailsAndActions":`详情与操作`,"drawer.duration":`运行时长 24h / 7d`,"drawer.evidence":`证据`,"drawer.executionHistory":`执行历史`,"drawer.executionRecord":`运行记录`,"drawer.executionRecordAndResult":`执行过程与结果`,"drawer.explainDecision":`解释此决定`,"drawer.gateApproveHint":`在终端执行一条命令即可完成审批:`,"drawer.gateRejectHint":`不同意就把末尾的 approve 换成 reject。执行后这条提醒会自动消失。`,"drawer.gateRequiresHost":`需要宿主确认`,"drawer.gateRequiresHostDescription":`页面无权直接批准这类权限变更,你的点击没有写入任何内容。`,"drawer.goalAutoRun":`当前 Goal 的自动运行`,"drawer.goalChanges":`当前 Goal 的待确认变更`,"drawer.goalDetails":`Goal 详情`,"drawer.group":`群聊`,"drawer.inspectorFull":`切换到全屏`,"drawer.inspectorFullView":`全屏查看`,"drawer.inspectorHalf":`切换到半屏`,"drawer.inspectorHalfView":`半屏查看`,"drawer.lastNotification":`最近通知`,"drawer.larkConfigure":`管理 Lark connection`,"drawer.larkConnect":`连接 Lark App`,"drawer.larkConnection":`Lark connection`,"drawer.larkNotConfigured":`未配置`,"drawer.larkNotConfiguredDescription":`配置后,当这个 Goal 出现需要你确认的变更时,会自动发飞书通知。`,"drawer.managerChanges":`管家待确认变更`,"drawer.moreActions":`更多操作`,"drawer.moreRunActions":`更多运行操作`,"drawer.nextTransition":`下一转换`,"drawer.noExecutionHistory":`暂无执行记录。`,"drawer.noRun":`尚未启动执行 Session`,"drawer.noRunDescription":`Agent 开始执行后,运行记录会稳定显示在这里。`,"drawer.notAssigned":`未分配`,"drawer.notLinked":`未关联`,"drawer.notSet":`未设置`,"drawer.outputDetails":`产出详情`,"drawer.outputRecorded":`该产出已记录到当前 Goal。`,"drawer.outputSafePreview":`公开安全产出预览`,"drawer.outputRun":`Run`,"drawer.outputTodo":`Todo`,"drawer.outputs":`本次运行产出`,"drawer.previewUnavailable":`此产出没有可用的公开安全内联预览。`,"drawer.priority":`优先级`,"drawer.progress":`进度`,"drawer.proposalApplied":`已应用,LoopX 状态将刷新。`,"drawer.proposalApplyFailed":`应用失败,没有写入任何变更。`,"drawer.proposalApplyFailedHint":`请刷新 Goal 状态后重新生成;若仍失败,可保留此页并查看高级诊断。`,"drawer.proposalClose":`关闭`,"drawer.proposalDefer":`稍后`,"drawer.proposalDeferred":`已暂缓,可稍后继续应用或重新生成。`,"drawer.proposalEnterGoal":`进入新 Goal`,"drawer.proposalExplainer":`确认后,LoopX 会执行这项变更并显示写入结果。关闭或取消不会修改任何状态。`,"drawer.proposalRecheck":`按最新状态重新检查`,"drawer.proposalRegenerate":`基于最新状态重试`,"drawer.proposalRejected":`已拒绝,这项变更不会写入。`,"drawer.proposalStale":`来源状态已变化,请按最新状态重新检查。`,"drawer.proposalViewGoal":`查看更新后的 Goal`,"drawer.reassign":`改派给`,"drawer.reassignSummary":`重新分配:{task}`,"drawer.reason":`原因`,"drawer.recoveryDescription":`本地历史已经保留,请选择恢复路径。`,"drawer.recoveryFailed":`上游 Session 恢复失败`,"drawer.recoveryNewSession":`携带上下文开始新 Session`,"drawer.recoveryRetry":`重试恢复`,"drawer.repositoryRole":`执行工作区`,"drawer.repository":`仓库`,"drawer.replyMode":`回复方式`,"drawer.subagentApplied":`已写入,并通过共享 Goal 状态读回校验。`,"drawer.subagentAppliedRefreshFailed":`已写入并通过共享 Goal 状态读回;状态投影刷新失败,可稍后手动刷新。`,"drawer.subagentApplying":`正在写入并校验共享状态读回…`,"drawer.subagentApplyFailed":`子代理设置写入失败。`,"drawer.subagentChildLimit":`当前上限`,"drawer.subagentConfirmDisable":`确认关闭子代理执行`,"drawer.subagentConfirmEnable":`确认开启子代理执行`,"drawer.subagentCurrentBoundary":`当前任务领域限制`,"drawer.subagentDescription":`仅在 Todo、配额、能力和写入范围门禁全部通过后,允许运行时为相互独立的任务临时创建子代理;不会强制并行,也不会授予持久权限。`,"drawer.subagentDisable":`预览关闭子代理执行`,"drawer.subagentDisableSummary":`这个 Goal 将不再创建新的子代理;现有 Todo 归属和执行记录不受影响。`,"drawer.subagentDomainInvalid":`所选任务领域限制无效。`,"drawer.subagentDomainTodoCount":`匹配 {count} 个开放 Todo`,"drawer.subagentDomains":`任务领域限制(可选)`,"drawer.subagentDomainsEmpty":`当前没有开放的 advancement Todo 声明 task_domain;保持为空即可不按任务领域限制子代理执行。`,"drawer.subagentDomainsHint":`全部不选表示不按任务领域过滤;选择后只放行匹配且已声明领域的 Todo,其他执行门禁始终生效。`,"drawer.subagentDomainsUnrestricted":`不限制任务领域`,"drawer.subagentEnable":`预览开启子代理执行`,"drawer.subagentLabel":`Per-Goal 执行边界`,"drawer.subagentModel":`子 Agent 模型`,"drawer.subagentEffort":`子 Agent 推理档位`,"drawer.subagentModelDefault":`宿主默认`,"drawer.subagentLunaPreset":`使用 Luna / max`,"drawer.subagentClearModel":`清除模型偏好`,"drawer.subagentModelHint":`填写后通过“预览配置调整”保存,执行关闭时也可保存偏好;启动时须核验宿主支持情况。`,"drawer.subagentModelRequired":`设置推理档位前请先指定子 Agent 模型。`,"drawer.subagentMaxChildren":`最多子代理数`,"drawer.subagentNoChange":`当前 Goal 已是这个设置,没有写入任何内容。`,"drawer.subagentPending":`待确认`,"drawer.subagentPreviewBoundary":`预览配置调整`,"drawer.subagentPreviewFailed":`无法生成子代理设置预览。`,"drawer.subagentPreviewing":`正在核对最新 Goal 状态…`,"drawer.subagentPreviewReady":`预览已锁定,确认后才会写入这个 Goal。`,"drawer.subagentPreviewSummary":`最多允许创建 {count} 个子代理;任务领域限制:{domains}。`,"drawer.subagentRemoteReadOnly":`当前来源只读,请在 Goal 所在主机上修改。`,"drawer.subagentTitle":`自适应子代理执行`,"drawer.remoteDetailsDescription":`SSH 来源只展示公开安全状态,不读取来源主机上的连接配置。`,"drawer.remoteDetailsUnavailable":`远端详情未投影`,"drawer.resumeNo":`否`,"drawer.resumeYes":`是`,"drawer.runDetails":`执行 Session`,"drawer.runInterrupt":`中断本次运行`,"drawer.runLatest":`查看最近执行过程`,"drawer.runNewSession":`开始新 Session`,"drawer.runCloseSession":`关闭 Session`,"drawer.runRecordEmpty":`还没有运行记录。Agent 尚未开始这次执行;请在“详情与操作”查看等待条件或恢复 Session。`,"drawer.runRecordProjected":`当前没有可展示的逐步运行记录。LoopX 已读取到 {completed}/{total} 的投影进度{outputs};请在“详情与操作”检查 Session 状态。`,"drawer.runRecordProjectedOutputs":`和 {count} 项产出`,"drawer.runRoleAssistant":`已完成`,"drawer.runRoleSystem":`需检查`,"drawer.runRoleUser":`收到任务`,"drawer.runView":`Session 视图`,"drawer.scheduleAdd":`添加定时检查`,"drawer.scheduleDefaultNotification":`仅在需要你时通知`,"drawer.scheduleDefaultStop":`Goal 完成或 owner 停止`,"drawer.scheduleDefaultTarget":`由 LoopX 调度器按 Goal 配置唤醒。`,"drawer.scheduleEdit":`改为每 2 小时`,"drawer.scheduleLast":`上次执行`,"drawer.scheduleLocalTimezone":`本地时区`,"drawer.scheduleNext":`下次执行`,"drawer.scheduleNeverRun":`尚未执行`,"drawer.scheduleNotification":`通知`,"drawer.schedulePause":`暂停`,"drawer.schedulePending":`等待调度`,"drawer.scheduleResume":`恢复`,"drawer.scheduleRunNow":`立即运行`,"drawer.scheduleStop":`停止{kind}`,"drawer.scheduleStopCondition":`停止条件`,"drawer.scheduleTimezone":`时区`,"drawer.sessionRecoverable":`可恢复`,"drawer.sessionStatus":`会话状态`,"drawer.setupHeartbeat":`设置 Heartbeat`,"drawer.taskActions":`Todo 待确认操作`,"drawer.taskAdvancement":`推进任务`,"drawer.taskBlock":`标记阻塞`,"drawer.taskComplete":`标记完成`,"drawer.taskCompletedNote":`该任务保留为只读记录。`,"drawer.taskCompletedTitle":`任务已完成`,"drawer.taskDefer":`暂缓`,"drawer.taskDeferCondition":`Todo 暂缓恢复条件`,"drawer.taskDeferInvalid":`条件格式不受支持;请使用下列可判定条件。`,"drawer.taskDeferPlaceholder":`例如 resume_at:2026-09-14T09:00:00+08:00`,"drawer.taskDeferReview":`检查暂缓`,"drawer.taskDeferSupported":`支持 todo_done、pr_merged、capacity_available 与带时区的 resume_at 条件。`,"drawer.taskDeferUntil":`暂缓至`,"drawer.taskDetails":`Todo 详情`,"drawer.taskInfo":`任务信息`,"drawer.taskManage":`管理任务`,"drawer.taskNextCompleted":`可创建后续任务`,"drawer.taskNextOpen":`推进或更新状态`,"drawer.taskOrdinary":`普通任务`,"drawer.taskStatusBlocked":`受阻`,"drawer.taskStatusDeferred":`已延期`,"drawer.resumeWhen":`恢复条件`,"drawer.resumeState":`恢复状态`,"drawer.resumePending":`等待条件满足`,"drawer.resumeReady":`可恢复`,"drawer.resumeReceipt":`恢复回执`,"drawer.taskNextDeferred":`等待恢复条件满足后重新评估`,"drawer.taskNextResumeReady":`恢复条件已满足,等待生命周期重新规划`,"drawer.taskStatusCompleted":`已完成`,"drawer.taskStatusOpen":`待执行`,"drawer.taskSuccessor":`创建后续 Todo`,"drawer.taskSuccessorNote":`Owner 标记为阻塞,等待补充上下文。`,"drawer.taskSuccessorSummary":`创建后续 Todo:{task}`,"drawer.taskSuccessorText":`{task} 的后续工作`,"drawer.taskType":`任务类型`,"drawer.topic":`Topic`,"drawer.trigger":`触发方式`,"drawer.titleAttention":`需要你`,"drawer.titleOutput":`产出详情`,"drawer.titleProposalApplied":`执行结果`,"drawer.titleProposalConfirm":`确认执行`,"drawer.titleSchedule":`定时检查`,"drawer.unconfigured":`未配置`,"drawer.workspaceCandidates":`可选择的工作区`,"files.emptySummary":`公开安全产出`,"files.empty":`还没有文件、产出或已验证的阶段周报。`,"files.loadingReports":`正在加载已验证的阶段周报…`,"files.reportDelta":`+{added} 新增 · {changed} 变化`,"files.reportAdded":`新增`,"files.reportChanged":`变化`,"files.reportGeneration":`生成批次`,"files.reportLoadFailed":`无法加载已验证周报`,"files.reportPublication":`发布批次`,"files.title":`Files & Outputs`,"files.verifiedReport":`已验证阶段周报`,"header.agentUnavailable":`不可用`,"header.chatRuntime":`Chat`,"header.workAgentCount":`{count} 个工作 Agent`,"header.chat":`Chat`,"header.files":`Files`,"header.goalCapabilities":`能力配置`,"header.goalCapabilitiesDescription":`管理 Goal override 与继承的本机默认值。`,"header.goalDetails":`Goal 详情`,"header.goalDetailsDescription":`查看状态、用量、仓库、通知与 Session。`,"header.goalSettings":`Goal 设置`,"header.goalSettingsDescription":`打开 Goal 详情或能力配置`,"header.goalNavigation":`Goal 导航`,"header.goalView":`Goal 视图`,"header.live":`实时`,"header.manager":`LoopX 管家`,"header.managerDescription":`跨 Goal 的个人工作入口`,"header.managerOverview":`总览`,"header.managerView":`管家视图`,"header.openGoalNavigation":`打开 Goal 导航`,"header.readOnlySourceDescription":`{source} 通过 SSH 隧道只读展示`,"header.refresh":`刷新状态`,"header.refreshDone":`刚刚更新`,"header.refreshFailed":`刷新失败`,"header.refreshing":`刷新中`,"header.selectAgent":`选择 Agent`,"header.selectChatRuntime":`选择聊天 Runtime`,"header.tasks":`Tasks`,"header.themeBrutal":`切换到野兽主题`,"header.themePaper":`切换到默认主题`,"home.blockingSummary":`其中 {count} 项正在阻塞 Agent。`,"home.completedGoals":`已完成的 Goal`,"home.empty":`当前没有`,"startup.goalLoading":`正在加载状态…`,"startup.goalError":`状态加载失败`,"startup.progress":`已加载 {loaded} / {total} 个活跃 Goal`,"startup.partial":`Goal 状态正在逐个更新,当前统计尚不完整。`,"startup.independent":`此 Goal 的加载不会阻塞其他 Goal,你可以先查看已加载的内容。`,"startup.error.timeout":`读取超时,可在本地服务就绪后重试。`,"startup.error.network":`连接中断,请重试以重新连接。`,"startup.error.service":`本地服务暂时不可用,请重试继续加载。`,"startup.error.revision":`加载期间 Goal 目录发生变化,请刷新以同步。`,"startup.error.scope":`该 Goal 已不在当前来源中,请刷新目录。`,"startup.error.invalid":`无法解析状态响应,请刷新或检查 LoopX 更新。`,"startup.retry":`重试`,"startup.retryFailed":`重试失败的 Goal`,"startup.failedCount":`{count} 个 Goal 加载失败,已加载的 Goal 可继续使用。`,"home.greeting":`你好,我是 LoopX 管家`,"home.history":`历史`,"home.lane.needsYou":`需要你`,"home.lane.needsYouDescription":`等待你的决定、授权或补充信息`,"home.lane.observing":`观察中`,"home.lane.observingDescription":`持续监控,出现变化时再提醒你`,"home.lane.running":`执行中`,"home.lane.runningDescription":`Agent 正在推进并持续回传进展`,"home.lane.scheduled":`已安排`,"home.lane.scheduledDescription":`已经安排,等待时间或前置条件`,"home.noActivity":`尚无活动`,"home.noFirstActivity":`等待首次活动`,"home.noCompletedGoals":`还没有已完成的 Goal`,"home.preservedState":`保留状态,可随时恢复`,"home.stopped":`已停止`,"home.systemHealth":`系统健康:{summary}`,"home.taskCount":`{count} 个 Task`,"home.todayAt":`今天 {time}`,"home.waitingCount":`你有 {count} 项需要处理。`,"home.workspace":`Goal 工作区`,"lark.allMessages":`此 Topic 中的所有消息`,"lark.allTopicMessages":`所有 Topic 消息`,"lark.agentIngress":`Agent 入站方式`,"lark.agentAppPermissions":`每个选中的 Agent 都需要一个已具备群聊提及和回复能力的 Lark App。`,"lark.agentApps":`每个 Agent 的 Lark App`,"lark.agentAppsDescription":`默认使用上方 App;需要独立机器人身份时,可为 Agent 选择另一个兼容 App。`,"lark.agentAppSelection":`{agent} 的 Lark App`,"lark.appCreated":`App 已创建`,"lark.appCreateFailed":`创建失败`,"lark.appLoading":`正在加载可用的 Lark Apps…`,"lark.appPermissions":`该 App 能发送建联消息,但缺少接收群聊 @ 消息或自动回复所需的机器人权限。请开启 im:message.group_at_msg:readonly、im:message.send_as_bot 和事件 im.message.receive_v1,发布新版后刷新。`,"lark.appProfile":`Lark App`,"lark.apps":`Lark Apps`,"lark.autoReplyUnavailable":`自动回复暂不可用`,"lark.autoReplyReady":`自动回复可用`,"lark.bindGoal":`绑定到 Goal`,"lark.cancel":`取消`,"lark.cardinality":`一个 Lark App · 多个 Goal · 每个 Agent 一条隔离路由`,"lark.capture":`接收范围`,"lark.captureAddressed":`仅接收提及 App 或回复 App 的消息`,"lark.captureAll":`接收此 Goal Topic 中的所有消息`,"lark.captureScope":`接收范围`,"lark.captureScopeDescription":`决定哪些 Topic 消息会进入 LoopX;不会扩大 Agent 权限。`,"lark.closeConnection":`关闭连接弹窗`,"lark.closeCreate":`关闭创建弹窗`,"lark.closeSettings":`关闭 Lark 设置`,"lark.connect":`连接`,"lark.connectAllAgents":`连接全部已注册 Agent`,"lark.connectAllAgentsAction":`一键连接 {count} 个 Agent`,"lark.connectAllAgentsDescription":`一次引导创建 {count} 个隔离的 Agent Topic;请在对应 Topic 内发送请求,每个 Agent 保留独立路由和收件箱。`,"lark.connectApp":`连接 Lark App`,"lark.connection":`连接`,"lark.connections":`连接`,"lark.configuration":`Lark 配置`,"lark.continueFeishu":`在飞书中继续`,"lark.createAutomatically":`自动创建 Goal Topic`,"lark.createAutomaticallyDescription":`将为每个选中的 Agent 创建带 Agent 标识的专属 Topic。`,"lark.defaultAgentAppDescription":`用于查找目标群聊,并作为所有选中 Agent 的默认 App;下方的逐 Agent 选择可覆盖它。`,"lark.description":`管理可复用的 Lark App,并用独立 Topic 将群聊连接到 Goal。`,"lark.editConnection":`编辑 Lark 连接`,"lark.goalConnections":`{count} 个 Goal 连接`,"lark.goalTopicConnections":`Lark Goal Topic 连接`,"lark.groupChat":`群聊`,"lark.groupEmpty":`该机器人尚未加入可连接的群。请先在飞书群设置中添加这个机器人,再回来刷新或搜索。`,"lark.groupLoading":`正在读取该机器人已加入的群…`,"lark.groupSearch":`搜索该机器人已加入的群`,"lark.historyPermission":`历史补读权限(独立能力)`,"lark.health.eventProcessed":`已处理 {events} 条事件,成功回复 {replies} 条。`,"lark.health.eventUnverified":`事件订阅待验证`,"lark.health.eventUnverifiedDetail":`Provider listener 已就绪,但尚未收到消息事件。请启用 im.message.receive_v1、开通群聊 @ 消息权限并发布新版,然后在这个 Agent Topic 内发送新的 @ 消息;存在多条 Agent 路由时,群顶层消息会 fail closed。`,"lark.health.ignoredSelf":`已忽略机器人自身发送的消息,避免重复回复。`,"lark.health.invalidRouting":`路由配置无效`,"lark.health.invalidRoutingDetail":`连接已安全停用,请重新选择处理方式并保存。`,"lark.health.lastStatus":`最近事件状态:{status}`,"lark.health.listening":`监听中`,"lark.health.messageContextPermission":`消息权限不足`,"lark.health.messageContextPermissionDetail":`已收到消息事件,但无法读取群消息上下文。请发布并授权该 App 的群消息读取权限。`,"lark.health.notAddressed":`最近消息未直接 @ 机器人`,"lark.health.notAddressedDetail":`监听正常;当前连接只响应直接 @ 机器人或对机器人的回复。`,"lark.health.notStarted":`监听未启动`,"lark.health.notStartedDetail":`请刷新连接或重新启动 LoopX 后再试。`,"lark.health.processingFailed":`消息处理失败`,"lark.health.processingFailedDetail":`已收到消息事件,但 Agent 处理失败。请查看本地诊断后重试。`,"lark.health.queued":`已进入 Agent 收件箱`,"lark.health.queuedDetail":`消息由 {agent} 异步处理,不会启动通用 Chat Session。`,"lark.health.sourceDisconnected":`实时消息连接断开`,"lark.health.sourceDisconnectedDetail":`消息监听进程意外退出。请核对应用档案的平台:飞书应用选飞书,国际版 Lark 应用选 Lark,再检查连接及订阅错误。LoopX 正在重试;历史消息能读取,不代表能实时收消息。`,"lark.health.retrying":`监听重试中`,"lark.health.retryingDetail":`事件监听暂时中断,LoopX 正在自动重试。`,"lark.health.routeAmbiguous":`消息匹配多个 Goal`,"lark.health.routeAmbiguousDetail":`同一 Bot 和群聊存在多个完整群捕获连接。请让每个 Agent 使用独立 Bot,或只保留一个完整群连接。`,"lark.health.routeMismatch":`消息未匹配当前 Goal Topic`,"lark.health.routeMismatchDetail":`事件来自其他群聊或 Topic。请重新选择群聊并连接该 Goal,然后发送一条新的 @ 消息。`,"lark.health.routeUnavailable":`消息无法路由到 Goal`,"lark.health.routeUnavailableDetail":`当前连接信息不完整。请重新连接该 Goal 后再发送一条新的 @ 消息。`,"lark.health.starting":`正在启动`,"lark.health.startingDetail":`LoopX 正在启动该 App 的消息事件监听。`,"lark.health.unavailable":`自动回复不可用`,"lark.health.waiting":`等待处理`,"lark.incomingMessages":`接收消息`,"lark.ingressAsync":`异步收件箱`,"lark.ingressAsyncDescription":`写入 Agent 私有收件箱,等待后续显式处理。`,"lark.editPreservesIdentity":`保存会保留此 App、群和 Topic;旧连接默认升级为 Agent 异步收件箱。`,"lark.conversationKind":`连接用途`,"lark.managerConversation":`管家 · 同步对话`,"lark.workerConversation":`工作 Agent · 后台任务`,"lark.managerConversationDescription":`内置管家即时回应对话,长任务交给后台 Agent。群聊与私聊分别保存上下文。`,"lark.ingressLegacy":`待升级`,"lark.ingressLegacyDescription":`保存连接即可升级为 Agent 异步收件箱,已有消息保留在原 Topic 中。`,"lark.ingressQueue":`排队`,"lark.ingressQueueDescription":`进入同一 Agent Session 的有界 FIFO 队列,当前 Turn 完成后处理。`,"lark.ingressSteering":`实时引导`,"lark.ingressSteeringDescription":`投到当前活跃 Turn;没有精确活跃 Turn 时安全拒绝。`,"lark.loading":`加载 Lark 配置…`,"lark.management":`Lark 管理`,"lark.openEventSettings":`查看飞书事件配置`,"lark.mentions":`提及机器人`,"lark.mentionsOnly":`仅提及消息`,"lark.needsMessagePermissions":`需要消息权限`,"lark.needsSetup":`需要设置`,"lark.newApp":`新建 Lark App`,"lark.noAgentConfigured":`未配置 Agent`,"lark.noConnections":`暂无匹配的连接。`,"lark.noProfiles":`还没有可用的 lark-cli App profile。`,"lark.profileName":`Profile 名称`,"lark.profileValidation":`Profile 只能包含字母、数字、点、下划线和连字符。`,"lark.processing":`处理方式`,"lark.region":`区域`,"lark.registerAnother":`+ 注册另一个 Lark App — 通过飞书创建`,"lark.reopenFeishu":`重新打开飞书`,"lark.settingsConfigure":`配置 {goal}`,"lark.settingsDisconnect":`解绑 {goal}`,"lark.replyMode":`回复方式`,"lark.replyModeDescription":`当前只支持在来源 Topic 内回复,避免跨群或跨 Goal 投递。`,"lark.reusableApps":`{count} 个可复用 App`,"lark.reusableWorkspaceApp":`可复用工作区 App`,"lark.routesUnverified":`{count} 条 Lark 路由尚未验证`,"lark.saveConnection":`保存连接`,"lark.searchConnections":`搜索 Lark 连接`,"lark.searchPlaceholder":`搜索 App、群、Goal 或 Topic`,"lark.setupCopy":`LoopX 将通过 lark-cli 打开飞书官方创建页面。应用凭证保存在系统 Keychain,LoopX 只保留 profile 引用。`,"lark.someoneMentions":`有人提及 Agent`,"lark.targetAgent":`目标 Agent`,"lark.targetAgentDescription":`选择该 Goal 内已注册的 Agent。此连接只投递给一个 Agent,不广播、不授予新权限。实时引导与排队需要该 Agent 的精确活跃 Session。`,"lark.agentUnavailable":`{agent} · 已不可用`,"lark.selectRegisteredAgent":`请先选择可用的已注册 Agent;不会自动替换原先的接收者。`,"lark.topicPreview":`Topic 预览`,"lark.topicReply":`Topic 回复`,"lark.trigger":`触发方式`,"lark.waitingFeishu":`等待飞书完成创建`,"lark.waitingFeishuDescription":`请在新窗口中完成飞书授权,完成后会自动回到这里。`,"lark.waitingLink":`正在生成飞书官方创建链接…`,"lark.error.appCreate":`Lark App 创建失败`,"lark.error.appRequired":`请选择一个 Lark App profile。`,"lark.error.bind":`绑定失败`,"lark.error.bindPreview":`绑定预览失败`,"lark.error.configuration":`Lark 配置加载失败`,"lark.error.groupLookup":`无法读取该机器人已加入的群。请检查机器人状态后重试。`,"lark.error.groupLoad":`群聊加载失败`,"lark.error.invalidApp":`Lark App profile 不可用或尚未完成授权。`,"lark.error.messagePermissions":`该 App 缺少自动回复所需的机器人权限。请开启 im:message.group_at_msg:readonly 和 im:message:send_as_bot,发布新版后回来刷新重试。`,"lark.error.provider":`飞书 API 调用失败,且没有生成已验证回执。请稍后重试。`,"lark.error.setupPoll":`创建状态查询失败`,"lark.error.setupStart":`无法启动 Lark App 创建流程`,"lark.error.cliExecutable":`已找到配置的 lark-cli,但当前无法执行。请检查安装或启动参数。`,"lark.error.cliMissing":`未发现 lark-cli。请先安装 lark-cli,然后重新启动 LoopX。`,"lark.error.cliStart":`lark-cli 启动失败。请检查安装状态,然后重新启动 LoopX。`,"lark.error.disconnect":`解绑失败`,"notifications.autoNotify":`需要你确认时自动推送到群里`,"notifications.bind":`绑定到通知群`,"notifications.bindConfirm":`将把「{goal}」绑定到通知群「{target}」,绑定时会验证机器人在群内并发送一条确认消息。`,"notifications.bindFailed":`绑定失败`,"notifications.bound":`已绑定`,"notifications.confirmBind":`确认绑定`,"notifications.description":`把 Goal 里需要你确认的变更推送到飞书群。绑定和开关在这里完成,推送逻辑沿用现有通道。`,"notifications.disabled":`已停用`,"notifications.group":`通知群:{target}`,"notifications.loadFailed":`通知群列表加载失败`,"notifications.noTargets":`还没有可用的通知群。通知群涉及机器人私有身份,请先在终端配置一次:`,"notifications.notBound":`未绑定`,"notifications.recent":`最近 {time}`,"notifications.sentCount":`已发送 {count} 条`,"notifications.settings":`Goal 通知绑定`,"notifications.setupFailed":`设置失败`,"notifications.title":`飞书群通知`,"proposal.field.agentId":`Agent`,"proposal.field.cadence":`频率`,"proposal.field.completionCriteria":`完成标准`,"proposal.field.executionBoundary":`执行边界`,"proposal.field.goalId":`Goal ID`,"proposal.field.heartbeat":`Heartbeat`,"proposal.field.initialTodos":`首个任务`,"proposal.field.objective":`目标`,"proposal.field.operation":`操作`,"proposal.field.operationState":`操作状态`,"proposal.field.confirmationBoundary":`确认边界`,"proposal.field.expiresAt":`过期时间`,"proposal.field.permission":`权限`,"proposal.field.reason":`原因`,"proposal.field.stopCondition":`停止条件`,"proposal.field.target":`检查内容`,"proposal.field.timezone":`时区`,"proposal.field.title":`标题`,"proposal.field.workspace":`执行工作区`,"actionReview.targetChanged":`预览目标与请求的 Goal 或操作不一致,请重新生成预览。`,"actionReview.ready_stop":`暂停可恢复。此预览已通过检查,可直接执行;完成仍需要读回验证。`,"actionReview.resume_review":`恢复自动调度前需要确认。实际执行仍受额度、Gate 和 Todo 约束。`,"actionReview.delete_review":`请确认从注册表移除这个已停止 Goal。项目文件与历史记录会保留。`,"actionReview.action_review":`执行前请检查此提案的目标与影响。`,"actionReview.protected_action":`此操作需要明确审阅。确认不能替代所需授权。`,"actionReview.unknown_permission":`无法识别权限分类。请重新检查提案后再继续。`,"actionReview.unknown_action":`无法识别此生命周期操作。请重新检查提案后再继续。`,"actionReview.incomplete_proposal":`预览缺少验证信息或可执行转换。请重新生成预览。`,"actionReview.authority_gate":`Gate 阻止执行。请满足其要求后重新检查提案。`,"actionReview.stale_proposal":`来源状态已变化。请重新生成预览,原决定不再适用。`,"actionReview.apply_pending":`正在执行,请等待读回结果后再重试。`,"actionReview.readback_verified":`操作已完成,结果状态已通过读回验证。`,"actionReview.readback_unverified":`操作返回但未通过读回验证。尚不能确认完成,请重新检查状态。`,"actionReview.apply_failed":`执行未完成。请检查失败原因并重新生成预览后再试。`,"actionReview.inactive_proposal":`此提案当前不可执行。请重新检查后再继续。`,"proposal.gate.default":`需要宿主确认`,"proposal.impact.default":`确认后会调用规范 LoopX 服务写入状态。`,"proposal.impact.goalCreate":`确认后会创建 Goal 和首个 Todo,并让选定 Agent 开始首轮推进。`,"proposal.impact.lifecycleDelete":`确认后会从 source registry 和 global registry 移除这个已停止 Goal;项目文件、历史状态文件和备份不会被删除。`,"proposal.impact.lifecycleResume":`确认后会恢复 Goal 的自动调度资格并移回 Active Goals;实际执行仍受 quota、Gate 和 Todo 约束。`,"proposal.impact.lifecycleStop":`确认后会停止自动推进,并将 Goal 移入折叠的「已停止」列表;历史、Todo 和证据都会保留,可随时恢复。`,"proposal.impact.protected":`该操作需要通过受保护的 LoopX 写入服务完成。`,"proposal.impact.operation":`这里仅展示同一份不可变条款。请在已绑定的飞书群确认或拒绝;确认只会消费一个规范 claim。`,"proposal.primary.apply":`确认并应用`,"proposal.primary.goalCreate":`创建 Goal 并开始首轮`,"proposal.primary.lifecycleDelete":`删除 Goal`,"proposal.primary.lifecycleResume":`恢复 Goal`,"proposal.primary.lifecycleStop":`停止 Goal`,"proposal.primary.todoStart":`创建任务并开始执行`,"proposal.primary.operationGroup":`前往飞书群确认`,"proposal.summary.goalCreate":`创建 Goal:{title}`,"proposal.summary.heartbeat":`为当前 Goal 设置 Heartbeat`,"proposal.summary.lifecycleDelete":`删除 Goal:{title}`,"proposal.summary.lifecycleResume":`恢复 Goal:{title}`,"proposal.summary.lifecycleStop":`停止 Goal:{title}`,"proposal.summary.monitor":`为当前 Goal 创建定时检查:{target}`,"proposal.workspace.current":`当前本地工作区(未绑定 Repository)`,"proposal.workspace.named":`{workspace}(仅提供执行环境,不会自动关联仓库)`,"proposal.workspaceGate.agentImpact":`先完成 Agent 身份绑定,再重新检查原操作;当前没有写入 Goal。`,"proposal.workspaceGate.agentTitle":`先绑定 Agent`,"proposal.workspaceGate.defaultSummary":`请选择 Goal 所属工作区。`,"proposal.workspaceGate.selectionImpact":`选择工作区后会重新展示待确认操作,选择本身不会写入状态。`,"proposal.workspaceGate.selectionTitle":`选择 Goal 工作区`,"projection.agentAdvancingGoal":`Agent 正在推进当前 Goal`,"projection.agentIdle":`暂无需要你处理`,"projection.agentNeedsDecision":`Agent 等待你的决定`,"projection.agentPreparingNextStep":`Agent 正在整理下一步`,"projection.agentStopped":`已由你停止;历史、Todo 和证据仍保留`,"projection.agentWaitingExternal":`正在等待外部条件`,"projection.confirmAgentDecision":`请确认 Agent 下一步需要的权限或决策`,"projection.events24h":`24 小时内 {count} 个事件`,"projection.firstReadOnlyAdapterCheck":`执行首次只读适配检查并保存进度`,"projection.goalVerified":`Goal 状态、Todo 与注册信息已验证`,"projection.latestRun":`最近运行`,"projection.latestValidation":`最近验证`,"projection.nextUpdatePending":`等待 LoopX 更新下一步`,"projection.publicSafeProjection":`公开安全状态投影`,"projection.refreshState":`刷新 LoopX 状态,确认当前进度仍然有效`,"projection.runEvidenceAvailable":`存在可查看的运行证据`,"projection.runRecorded":`最近一次 LoopX 运行已经记录`,"projection.statusRefreshNeeded":`LoopX 状态需要刷新`,"projection.todoStatusUpdated":`Todo 状态已经更新,正在确认下一步`,"projection.validationRecorded":`最近验证已经记录`,"runs.completed":`已完成`,"runs.failed":`需检查`,"runs.interrupted":`已中断`,"runs.queued":`已安排`,"runs.ready":`可继续`,"runs.resumeFailed":`恢复失败`,"runs.running":`执行中`,"runs.unknown":`状态未知`,"runs.waiting":`等待条件`,"schedule.active":`执行中`,"schedule.heartbeat":`Goal Heartbeat`,"schedule.monitor":`定时与持续任务`,"schedule.paused":`已暂停`,"schedule.summary":`按 LoopX 调度约束持续检查`,"schedule.defaultTarget":`检查当前 Goal 的阻塞、进度与新产出`,"schedule.unsupportedCalendar":`当前定时检查不支持精确到星期或时刻的日历计划。请改用固定间隔,例如“每 30 分钟”“每 2 小时”或“每天”;草稿已保留,没有生成待确认操作。`,"source.add":`添加来源`,"source.addConfigured":`添加只读来源`,"source.addMethod":`来源添加方式`,"source.addSsh":`添加 SSH 隧道来源`,"source.closeForm":`关闭来源表单`,"source.configured":`已配置 SSH`,"source.configuredCount":`本机 SSH Host · {count} 个`,"source.configuredGroup":`已配置 SSH Host · {count}(点击快速添加)`,"source.connected":`已连接`,"source.connecting":`连接中`,"source.controlPlane":`控制面来源`,"source.copy":`复制`,"source.copyCommand":`复制 SSH 隧道命令`,"source.copyError":`无法复制命令,请手动复制下方命令。`,"source.copied":`已复制`,"source.description":`已读取全部显式 Host(含 Include);通配规则不会作为具体来源。先运行命令,LoopX 不读取密钥或配置细节。`,"source.host":`本机 SSH Host`,"source.hostEmpty":`~/.ssh/config 中没有可直接选择的显式 Host。`,"source.hostLoadError":`无法读取本机 SSH Host。`,"source.hostPlaceholder":`输入或搜索 Host`,"source.invalid":`SSH 来源参数无效。`,"source.loadingHosts":`正在读取…`,"source.localInteractive":`本机交互`,"source.localPort":`本地端口`,"source.manual":`手动 URL`,"source.manualDescription":`远端来源始终按只读投影处理,不继承本机写权限。`,"source.name":`名称`,"source.namePlaceholder":`远程开发机`,"source.notAvailable":`不可用`,"source.readOnly":`SSH 隧道 · 只读`,"source.readOnlyNoticeDescription":`你可以查看 Goal、Task、证据与运行状态;写入、纠偏和 Agent 会话仍留在来源主机。`,"source.readOnlyNoticeTitle":`远端只读投影`,"source.readOnlyWriteError":`远端 SSH 隧道来源是只读投影,不能执行控制面写入。`,"source.refreshHosts":`重新读取 SSH Host`,"source.remove":`移除来源 {source}`,"source.removeCurrent":`移除当前来源`,"source.select":`选择控制面来源`,"source.selectHost":`请选择已配置的 SSH Host。`,"source.statusUrl":`本地转发 URL`,"source.tunnelCommandPending":`选择 Host 后生成隧道命令`,"machine.absent":`尚未配置`,"machine.action.create":`创建机器策略`,"machine.action.delete":`移除机器策略`,"machine.action.unchanged":`无需写入`,"machine.action.update":`更新机器策略`,"machine.applied":`机器策略已应用,并通过回读校验。`,"machine.applyError":`无法应用机器策略。`,"machine.applyPreview":`应用已审阅预览`,"machine.changedNamespaces":`变更的 Namespace`,"machine.capabilityCatalog":`机器能力目录`,"machine.capabilityEmpty":`当前没有注册可在机器作用域配置的能力。`,"machine.configured":`已配置`,"machine.confirmRollback":`确认回滚`,"machine.currentRevision":`当前 Revision`,"machine.currentValue":`当前机器值`,"machine.description":`与 Goal 设置共用能力目录。在这里管理受支持的机器默认值;仅支持 Goal 配置的能力会明确标注。`,"capabilities.rawJson":`高级:原始 JSON`,"machine.goalOnly":`此能力目前仅支持 Goal 级配置。请打开具体 Goal 的能力设置进行配置;这里不会设置机器级默认值。`,"machine.desiredRevision":`目标 Revision`,"machine.editorUnavailable":`当前版本未安装此 Namespace 的编辑器`,"machine.editorUnavailableDescription":`它仍会显示在 Registry 中;安装或升级对应的 Dashboard 编辑器后才能修改。`,"machine.editorMode":`编辑模式`,"machine.liveDefault":`实时默认值;Goal 显式覆盖优先`,"machine.liveDefaultDescription":`没有显式覆盖的 Goal 会在该能力下一次决策时读取当前机器策略。修改或移除策略会立即影响这些已有 Goal;显式 Goal 覆盖保持固定。`,"machine.genericNamespaceDescription":`使用 JSON 编辑这个已注册 Namespace。LoopX 会先按 capability 自己拥有的 schema 校验,再允许预览写入。`,"machine.jsonConfiguration":`Namespace 配置(JSON)`,"machine.jsonConfigurationHelp":`只更新当前 Namespace;其他机器配置会保留,Apply 仍锁定到已审阅的 Preview Revision。`,"machine.jsonEditor":`JSON`,"machine.editJson":`编辑 JSON`,"capabilities.jsonConfiguration":`Goal 配置(JSON)`,"capabilities.jsonHelp":`仅编辑当前 Goal 的已注册字段。修改后需重新预览才能应用。`,"capabilities.jsonInvalid":`请输入合法的 JSON 对象,且仅包含已注册的可编辑字段。`,"machine.backToForm":`返回表单`,"machine.jsonInvalid":`请先填写一个合法的 JSON object,再预览变更。`,"machine.loadError":`无法读取机器配置。`,"machine.machinePolicy":`机器策略`,"machine.namespaceCount":`已注册 Namespace`,"machine.namespaces":`配置 Namespace`,"machine.periodicReport":`周期报告`,"machine.periodicReportDescription":`为所有未显式覆盖的 Goal 提供默认报告策略;Goal 调度与发送消费解析后的有效配置。`,"machine.periodicReportActivation":`开启后将在已验证的阶段节点自动投递`,"machine.periodicReportActivationDescription":`这不是每周定时器。当 LoopX 验证 Goal 已完成一个阶段时,Agent 会生成并冻结报告,随后通过配置的 Goal Channel 自动发送。启用此订阅即授予持续投递权;发送失败或路由漂移会 fail closed 并进入修复。`,"machine.changeQualityActivation":`质量验证是质量门禁,不是新增授权`,"machine.changeQualityActivationDescription":`继承该策略的 Goal 会验证最终精确 diff。safe_fix 只允许在既有写入权限内执行至多一次有界修复;此设置不会授予文件、权限或合并权。`,"machine.replanCadenceActivation":`复核周期只改变时机,不改变执行权限`,"machine.replanCadenceActivationDescription":`没有显式覆盖的 Goal 会在下一次复核决策前读取此阈值;它不会创建 Turn、消耗配额或授予权限。`,"machine.preview":`审阅机器配置变更`,"machine.previewChanges":`预览变更`,"machine.previewError":`无法生成机器策略预览。`,"machine.previewLocked":`应用操作锁定到当前 Revision;若机器状态变化,LoopX 会要求重新预览。`,"machine.previewRollback":`预览回滚`,"machine.previewRemoval":`预览移除`,"machine.profilePreset":`Profile preset`,"machine.profilePresetHelp":`由 capability 管理的 preset,例如 weekly-progress。`,"machine.registry":`Typed Registry`,"machine.requiredFields":`开启后必须填写 profile preset、Goal Channel route 与有效时区。`,"machine.revision":`机器 Revision`,"machine.revisionLockedReady":`所有变更必须先预览;只有对应的机器 Revision 仍然有效时才会应用。`,"machine.rollbackAvailable":`可回滚上一次应用`,"machine.rollbackDescription":`先预览已保存的前一 Revision,再决定是否恢复。`,"machine.rollbackError":`无法完成回滚。`,"machine.rollbackPreviewDescription":`前一 Revision 已准备恢复,请确认执行本次回滚。`,"machine.rolledBack":`已恢复前一版机器策略,并通过校验。`,"machine.removed":`机器策略已移除,并通过回读校验。`,"machine.routeRef":`Goal Channel route`,"machine.routeRefHelp":`只填写公开 route alias;凭据与 provider identifier 不会进入此表单。`,"machine.timezone":`时区`,"machine.timezoneHelp":`填写 IANA 时区,例如 Asia/Shanghai。`,"machine.title":`机器配置`,"machine.unchanged":`机器策略已与预览一致,本次没有写入。`,"machine.visualEditor":`引导式`,"capabilities.atomicOverride":`Goal override 按完整配置生效`,"capabilities.atomicOverrideDescription":`Goal 的完整配置优先于机器默认值;LoopX 不会在两个作用域之间逐字段拼接。`,"capabilities.applyFailed":`Goal 能力变更未写入。`,"capabilities.applyPreview":`应用此预览`,"capabilities.catalog":`Goal 能力目录`,"capabilities.chooseGoal":`请先选择一个 Goal,再查看它的能力配置。`,"capabilities.defaultValue":`声明的默认值`,"capabilities.description":`查看当前 Goal 可用的能力,以及每项配置的准确作用域。`,"capabilities.editorPrepared":`已注册 typed editor contract`,"capabilities.effectiveSource":`当前生效来源`,"capabilities.empty":`当前 Goal 没有可用的能力描述。`,"capabilities.fields":`已注册字段`,"capabilities.goalPolicy":`Goal 能力策略`,"capabilities.goalScope":`Goal`,"capabilities.goalValue":`当前 Goal 值`,"capabilities.loadFailed":`无法加载 Goal 能力`,"capabilities.loading":`正在加载 Goal 能力…`,"capabilities.machineOnly":`此能力只能在机器作用域配置。`,"capabilities.machineValue":`实时机器默认值`,"capabilities.machineScope":`机器`,"capabilities.previewOnly":`当前读取结果来自真实配置;在 revision-locked preview/apply 路径接通前,Dashboard 不会提供 Goal 写入控件。`,"capabilities.preview":`锁定 revision 的变更预览`,"capabilities.previewChanges":`预览变更`,"capabilities.restoreInheritance":`恢复继承机器默认值`,"capabilities.previewFailed":`无法预览 Goal 能力变更。`,"capabilities.previewLocked":`应用时会重新校验这一个 plan revision;过期变更将被拒绝。`,"capabilities.partialWrite":`Goal 值已保存;共享投影仍需修复`,"capabilities.partialWriteDescription":`源 Goal 配置已经写入并回读,但共享 runtime 投影尚未同步;请勿重复提交本次变更。`,"capabilities.refreshSource":`刷新源配置`,"capabilities.readOnly":`只读能力`,"capabilities.revisionLockedReady":`所有变更必须先预览;只有对应的精确 revision 仍然有效时才会写入。`,"capabilities.retry":`重试`,"capabilities.source.capability_default":`能力默认值`,"capabilities.source.goal_override":`Goal override`,"capabilities.source.machine_default":`实时机器默认值`,"capabilities.source.not_configured":`未配置`,"capabilities.title":`Goal 能力`,"settings.close":`关闭设置`,"settings.appearance":`外观`,"settings.appearanceDescription":`管理当前浏览器里的工作区显示偏好。`,"settings.appearanceTabDescription":`主题和显示偏好`,"settings.capabilitiesTabDescription":`当前 Goal 的能力覆盖配置`,"settings.back":`返回工作区`,"settings.categories":`设置分类`,"settings.description":`管理工作区偏好与集成。`,"settings.eyebrow":`工作区偏好`,"settings.general":`通用`,"settings.goalConnections":`Goal 连接`,"settings.language":`语言`,"settings.languageDescription":`选择 LoopX Desktop 工作区使用的界面语言。`,"settings.languageEnglishDescription":`使用英文显示导航、设置和工作区控件。`,"settings.languageEnglish":`English`,"settings.languageSimplifiedChineseDescription":`使用简体中文显示导航、设置和工作区控件。`,"settings.languageSimplifiedChinese":`简体中文`,"settings.languageStoredLocally":`此偏好仅保存在当前设备。`,"settings.languageTabDescription":`当前设备的界面语言`,"settings.larkTabDescription":`App、群聊和 Goal Topic 连接`,"settings.machineTabDescription":`本机各 Capability 共享的 typed defaults`,"settings.notifications":`通知`,"settings.open":`设置`,"settings.themeDefault":`纸张`,"settings.themeDefaultDescription":`安静、轻量,适合长期查看。`,"settings.themeDescription":`选择工作区的视觉风格。设置会保存在当前浏览器本地。`,"settings.themeHighContrast":`高对比`,"settings.themeHighContrastDescription":`更强边框和更醒目的状态块。`,"settings.themeLoopx":`LoopX 标准`,"settings.themeLoopxDescription":`精确的黑白界面、Geist 字体与安静的细线结构。`,"settings.title":`设置`,"settings.workspaceDisplay":`工作区显示`,"settings.workspaceTheme":`工作区主题`,"session.closeRecord":`退出运行记录`,"session.details":`Session 详情`,"session.record":`执行 Session · 运行记录`,"session.recordDescription":`当前时间线已切换到这次 Session 的消息与 Turn 记录。`,"sidebar.createGoal":`创建 Goal`,"sidebar.delete":`删除`,"sidebar.deleteGoal":`删除 Goal`,"sidebar.manager":`LoopX 管家`,"sidebar.notifications":`设置`,"sidebar.owner":`个人工作区`,"sidebar.product":`个人 Agent 工作区`,"sidebar.resume":`恢复`,"sidebar.resumeGoal":`恢复 Goal`,"sidebar.stop":`停止`,"tasks.historyLoading":`正在加载历史…`,"tasks.historyError":`历史加载失败,已显示的内容仍可查看。`,"tasks.historyExpired":`历史快照已过期,重新加载后可继续查看。`,"tasks.historyRetry":`重新加载`,"tasks.historyEnd":`已显示全部完成记录`,"tasks.historyMore":`加载更多`,"tasks.historyLocalOnly":`请打开这台机器的 Dashboard 查看完整历史。`,"sidebar.sortGoals":`调整 Goal 顺序`,"sidebar.dragGoal":`拖拽调整顺序,或使用列表排序按钮`,"sidebar.moveUp":`上移 {goal}`,"sidebar.moveDown":`下移 {goal}`,"sidebar.goalMoved":`{goal} 已移至第 {position} 位`,"sidebar.orderNotSaved":`顺序已在本次页面生效;浏览器存储不可用,无法保存。`,"sidebar.stopGoal":`停止 Goal`,"sidebar.stopped":`已停止`,"sidebar.stoppedLoading":`正在加载已停止 Goal`,"sidebar.stoppedLoadFailed":`已停止 Goal 加载失败,其他 Goal 仍可使用。`,"sidebar.retryStopped":`重试`,"state.completed":`已完成`,"state.needsRepair":`需修复`,"state.needsYou":`等你`,"state.quiet":`安静运行`,"state.running":`推进中`,"state.stopped":`已停止`,"state.waiting":`等待条件`,"tasks.blocked":`受阻`,"tasks.agentLane":`工作 Agent`,"tasks.agentLaneDescription":`筛选这个 Goal 下的工作泳道`,"tasks.agentLaneFilter":`按工作 Agent 筛选`,"tasks.allAgentLanes":`全部 Agent({count})`,"tasks.chatAgentReplied":`Agent 已回复`,"tasks.chatPending":`已发送给 Agent`,"tasks.chatPendingDescription":`正在处理;只有经过确认的任务操作才会更新 Tasks。`,"tasks.chatRecent":`最近对话`,"tasks.chatUnchangedDescription":`本次对话没有直接修改 Tasks。需要执行时,可先转成 Task 草稿并确认。`,"tasks.chatViewReply":`查看回复`,"tasks.convertToTask":`转为 Task`,"tasks.completed":`已完成`,"runs.discoveryPartial":`部分执行详情暂不可用,正在重连;任务摘要不代表实时执行状态。`,"runs.discoveryOffline":`执行服务暂不可用,正在重连;保留的任务摘要可能已过时。`,"files.openConversation":`前往会话`,"files.exportSummary":`导出摘要`,"tasks.viewDescription":`先处理待确认,再查看工作与完成记录`,"tasks.viewLabel":`任务视图`,"tasks.listView":`列表`,"tasks.boardView":`看板`,"tasks.completedSummary":`已完成 {count} 项,近期完成明细由控制面按需投影。`,"tasks.emptyCompleted":`还没有完成的任务。`,"tasks.emptyConfirm":`没有待确认的任务。`,"tasks.emptyRunning":`没有待执行或进行中的任务。`,"tasks.emptySchedules":`没有定时任务。`,"tasks.emptyGoal":`这个 Goal 还没有任务。用下面的输入框描述下一步,LoopX 会先展示待确认操作。`,"tasks.markComplete":`标记完成:{name}`,"tasks.moreActions":`更多操作:{name}`,"tasks.openExecution":`查看执行过程:{name}`,"tasks.pending":`待处理`,"tasks.pendingAndRunning":`待执行 / 进行中`,"tasks.scheduled":`定时与持续`,"tasks.sessionError":`Session 异常`,"tasks.waiting":`待执行`,"tasks.waitingAge":`已等待 {age}`,"tasks.viewExecution":`查看执行过程`,"tasks.viewResult":`查看结果`,"time.days":`{count} 天`,"time.hours":`{count} 小时`,"timeline.emptyGoal":`这个 Goal 还没有新动态`,"timeline.emptyGoalDescription":`你可以直接询问进度或下发新的纠偏信息。`,"timeline.emptyWorkspace":`今天的工作区很安静`,"timeline.emptyWorkspaceDescription":`向 LoopX 管家描述一个 Goal,或询问今天最值得关注的事情。`,"timeline.gateHistory":`{count} 项历史 Gate`,"timeline.pending":`正在整理…`,"timeline.runCompleted":`{run}:已完成`,"timeline.review":`查看处理方式`,"timeline.reviewAndConfirm":`查看并确认`,"timeline.waitingConfirmation":`待你确认`}};function Gi(e,t){return t?Object.entries(t).reduce((e,[t,n])=>e.replaceAll(`{${t}}`,String(n)),e):e}function Ki(){try{return window.localStorage.getItem(`loopx-pw-locale`)===`en`?`en`:`zh-CN`}catch{return`zh-CN`}}function qi({children:e}){let[t,n]=(0,z.useState)(Ki);function r(e){n(e);try{window.localStorage.setItem(Ui,e)}catch{}}(0,z.useEffect)(()=>{document.documentElement.lang=t},[t]);let i=(0,z.useMemo)(()=>({locale:t,setLocale:r,t:(e,n)=>Gi(Wi[t][e],n)}),[t]);return(0,B.jsx)(Hi.Provider,{value:i,children:e})}function Ji(){let e=(0,z.useContext)(Hi);if(!e)throw Error(`useWorkspaceI18n must be used within WorkspaceI18nProvider`);return e}function Yi(e,t){let n={安静运行:`state.quiet`,等你:`state.needsYou`,等待条件:`state.waiting`,推进中:`state.running`,需修复:`state.needsRepair`,已完成:`state.completed`,已停止:`state.stopped`}[e];return n?Wi[t][n]:e}function Xi(e,t){let n={busy:`runs.running`,completed:`runs.completed`,failed:`runs.failed`,queued:`runs.queued`,ready:`runs.ready`,resume_failed:`runs.resumeFailed`,running:`runs.running`,waiting:`runs.waiting`};return e?n[e]?t(n[e]):e:t(`runs.unknown`)}function Zi(e,t){if(!e)return null;let n=new Date(e).getTime();if(Number.isNaN(n))return null;let r=Date.now()-n;if(r<36e5)return null;let i=Math.floor(r/864e5);return i>=1?t(`time.days`,{count:i}):t(`time.hours`,{count:Math.floor(r/36e5)})}var Qi;function H(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;en?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var $i=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},ea=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Qi=globalThis).__zod_globalConfig??(Qi.__zod_globalConfig={});var ta=globalThis.__zod_globalConfig;function na(e){return e&&Object.assign(ta,e),ta}function ra(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function ia(e,t){return typeof t==`bigint`?t.toString():t}function aa(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function oa(e){return e==null}function sa(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function ca(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r){};function ga(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var _a=aa(()=>{if(ta.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function va(e){if(ga(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return ga(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function ya(e){return va(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var ba=new Set([`string`,`number`,`symbol`]);function xa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Sa(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function U(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Ca(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var wa={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ta(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Sa(e,fa(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return da(this,`shape`,e),e},checks:[]}))}function Ea(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Sa(e,fa(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return da(this,`shape`,r),r},checks:[]}))}function Da(e,t){if(!va(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Sa(e,fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return da(this,`shape`,n),n}}))}function Oa(e,t){if(!va(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Sa(e,fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return da(this,`shape`,n),n}}))}function ka(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Sa(e,fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return da(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function Aa(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return Sa(t,fa(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return da(this,`shape`,i),i},checks:[]}))}function ja(e,t,n){return Sa(t,fa(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return da(this,`shape`,i),i}}))}function Ma(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Fa(e){return typeof e==`string`?e:e?.message}function Ia(e,t,n){let r=e.message?e.message:Fa(e.inst?._zod.def?.error?.(e))??Fa(t?.error?.(e))??Fa(n.customError?.(e))??Fa(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function La(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Ra(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var za=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ia,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ba=H(`$ZodError`,za),Va=H(`$ZodError`,za,{Parent:Error});function Ha(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ua(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new $i;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Ia(e,a,na())));throw ha(t,i?.callee),t}return o.value},Ga=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Ia(e,a,na())));throw ha(t,i?.callee),t}return o.value},Ka=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new $i;return a.issues.length?{success:!1,error:new(e??Ba)(a.issues.map(e=>Ia(e,i,na())))}:{success:!0,data:a.value}},qa=Ka(Va),Ja=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>Ia(e,i,na())))}:{success:!0,data:a.value}},Ya=Ja(Va),Xa=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Wa(e)(t,n,i)},Za=e=>(t,n,r)=>Wa(e)(t,n,r),Qa=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ga(e)(t,n,i)},$a=e=>async(t,n,r)=>Ga(e)(t,n,r),eo=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ka(e)(t,n,i)},to=e=>(t,n,r)=>Ka(e)(t,n,r),no=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ja(e)(t,n,i)},ro=e=>async(t,n,r)=>Ja(e)(t,n,r),io=/^[cC][0-9a-z]{6,}$/,ao=/^[0-9a-z]+$/,oo=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,so=/^[0-9a-vA-V]{20}$/,co=/^[A-Za-z0-9]{27}$/,lo=/^[a-zA-Z0-9_-]{21}$/,uo=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,fo=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,po=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,mo=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ho=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function go(){return new RegExp(ho,`u`)}var _o=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,vo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,yo=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,bo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xo=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,So=/^[A-Za-z0-9_-]*$/,Co=/^https?$/,wo=/^\+[1-9]\d{6,14}$/,To=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,Eo=RegExp(`^${To}$`);function Do(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Oo(e){return RegExp(`^${Do(e)}$`)}function ko(e){let t=Do({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${To}T(?:${r})$`)}var Ao=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},jo=/^-?\d+$/,Mo=/^-?\d+(?:\.\d+)?$/,No=/^(?:true|false)$/i,Po=/^null$/i,Fo=/^[^A-Z]*$/,Io=/^[^a-z]*$/,Lo=H(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ro={number:`number`,bigint:`bigint`,object:`date`},zo=H(`$ZodCheckLessThan`,(e,t)=>{Lo.init(e,t);let n=Ro[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value{(t.inclusive?r.value<=t.value:r.value{Lo.init(e,t);let n=Ro[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Vo=H(`$ZodCheckMultipleOf`,(e,t)=>{Lo.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):ca(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Ho=H(`$ZodCheckNumberFormat`,(e,t)=>{Lo.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=wa[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=jo)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}sa&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Uo=H(`$ZodCheckMaxLength`,(e,t)=>{var n;Lo.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!oa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum{let r=n.value;if(r.length<=t.maximum)return;let i=La(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Wo=H(`$ZodCheckMinLength`,(e,t)=>{var n;Lo.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!oa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=La(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Go=H(`$ZodCheckLengthEquals`,(e,t)=>{var n;Lo.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!oa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=La(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ko=H(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Lo.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),qo=H(`$ZodCheckRegex`,(e,t)=>{Ko.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Jo=H(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Fo,Ko.init(e,t)}),Yo=H(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Io,Ko.init(e,t)}),Xo=H(`$ZodCheckIncludes`,(e,t)=>{Lo.init(e,t);let n=xa(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Zo=H(`$ZodCheckStartsWith`,(e,t)=>{Lo.init(e,t);let n=RegExp(`^${xa(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Qo=H(`$ZodCheckEndsWith`,(e,t)=>{Lo.init(e,t);let n=RegExp(`.*${xa(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),$o=H(`$ZodCheckOverwrite`,(e,t)=>{Lo.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),es=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(` +`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(` +`))}},ts={major:4,minor:4,patch:3},ns=H(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ts;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=Ma(e),i;for(let a of t){if(a._zod.def.when){if(Na(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new $i;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=Ma(e,t))});else{if(e.issues.length===t)continue;r||=Ma(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(Ma(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new $i;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new $i;return o.then(e=>t(e,r,a))}return t(o,r,a)}}ua(e,`~standard`,()=>({validate:t=>{try{let n=qa(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Ya(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),rs=H(`$ZodString`,(e,t)=>{ns.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ao(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),is=H(`$ZodStringFormat`,(e,t)=>{Ko.init(e,t),rs.init(e,t)}),as=H(`$ZodGUID`,(e,t)=>{t.pattern??=fo,is.init(e,t)}),os=H(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=po(e)}else t.pattern??=po();is.init(e,t)}),ss=H(`$ZodEmail`,(e,t)=>{t.pattern??=mo,is.init(e,t)}),cs=H(`$ZodURL`,(e,t)=>{is.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===Co.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),n.value=t.normalize?i.href:r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),ls=H(`$ZodEmoji`,(e,t)=>{t.pattern??=go(),is.init(e,t)}),us=H(`$ZodNanoID`,(e,t)=>{t.pattern??=lo,is.init(e,t)}),ds=H(`$ZodCUID`,(e,t)=>{t.pattern??=io,is.init(e,t)}),fs=H(`$ZodCUID2`,(e,t)=>{t.pattern??=ao,is.init(e,t)}),ps=H(`$ZodULID`,(e,t)=>{t.pattern??=oo,is.init(e,t)}),ms=H(`$ZodXID`,(e,t)=>{t.pattern??=so,is.init(e,t)}),hs=H(`$ZodKSUID`,(e,t)=>{t.pattern??=co,is.init(e,t)}),gs=H(`$ZodISODateTime`,(e,t)=>{t.pattern??=ko(t),is.init(e,t)}),_s=H(`$ZodISODate`,(e,t)=>{t.pattern??=Eo,is.init(e,t)}),vs=H(`$ZodISOTime`,(e,t)=>{t.pattern??=Oo(t),is.init(e,t)}),ys=H(`$ZodISODuration`,(e,t)=>{t.pattern??=uo,is.init(e,t)}),bs=H(`$ZodIPv4`,(e,t)=>{t.pattern??=_o,is.init(e,t),e._zod.bag.format=`ipv4`}),xs=H(`$ZodIPv6`,(e,t)=>{t.pattern??=vo,is.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),Ss=H(`$ZodCIDRv4`,(e,t)=>{t.pattern??=yo,is.init(e,t)}),Cs=H(`$ZodCIDRv6`,(e,t)=>{t.pattern??=bo,is.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function ws(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Ts=H(`$ZodBase64`,(e,t)=>{t.pattern??=xo,is.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{ws(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Es(e){if(!So.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return ws(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var Ds=H(`$ZodBase64URL`,(e,t)=>{t.pattern??=So,is.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Es(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Os=H(`$ZodE164`,(e,t)=>{t.pattern??=wo,is.init(e,t)});function ks(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var As=H(`$ZodJWT`,(e,t)=>{is.init(e,t),e._zod.check=n=>{ks(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),js=H(`$ZodNumber`,(e,t)=>{ns.init(e,t),e._zod.pattern=e._zod.bag.pattern??Mo,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Ms=H(`$ZodNumberFormat`,(e,t)=>{Ho.init(e,t),js.init(e,t)}),Ns=H(`$ZodBoolean`,(e,t)=>{ns.init(e,t),e._zod.pattern=No,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Ps=H(`$ZodNull`,(e,t)=>{ns.init(e,t),e._zod.pattern=Po,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),Fs=H(`$ZodUnknown`,(e,t)=>{ns.init(e,t),e._zod.parse=e=>e}),Is=H(`$ZodNever`,(e,t)=>{ns.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Ls(e,t,n){e.issues.length&&t.issues.push(...Pa(n,e.issues)),t.value[n]=e.value}var Rs=H(`$ZodArray`,(e,t)=>{ns.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;eLs(t,n,e))):Ls(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function zs(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...Pa(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function Bs(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Ca(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Vs(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>zs(e,n,i,t,u,d))):zs(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var Hs=H(`$ZodObject`,(e,t)=>{if(ns.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=aa(()=>Bs(t));ua(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=ga,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>zs(n,t,e,s,r,i))):zs(a,t,e,s,r,i)}return i?Vs(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Us=H(`$ZodObjectJIT`,(e,t)=>{Hs.init(e,t);let n=e._zod.parse,r=aa(()=>Bs(t)),i=e=>{let t=new es([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=pa(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=pa(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(` + if (${n}.issues.length) { + if (${o} in input) { + payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${o}, ...iss.path] : [${o}] + }))); + } + } + + if (${n}.value === undefined) { + if (${o} in input) { + newResult[${o}] = undefined; + } + } else { + newResult[${o}] = ${n}.value; + } + + `):c?t.write(` + if (${n}.issues.length) { + payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${o}, ...iss.path] : [${o}] + }))); + } + + if (${n}.value === undefined) { + if (${o} in input) { + newResult[${o}] = undefined; + } + } else { + newResult[${o}] = ${n}.value; + } + + `):t.write(` + const ${n}_present = ${o} in input; + if (${n}.issues.length) { + payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${o}, ...iss.path] : [${o}] + }))); + } + if (!${n}_present && !${n}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${o}] + }); + } + + if (${n}_present) { + if (${n}.value === undefined) { + newResult[${o}] = undefined; + } else { + newResult[${o}] = ${n}.value; + } + } + + `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=ga,s=!ta.jitless,c=s&&_a.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?Vs([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function Ws(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Ma(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Ia(e,r,na())))}),t)}var Gs=H(`$ZodUnion`,(e,t)=>{ns.init(e,t),ua(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),ua(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),ua(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),ua(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>sa(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Ws(t,r,e,i)):Ws(o,r,e,i)}}),Ks=H(`$ZodIntersection`,(e,t)=>{ns.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Js(e,t,n)):Js(e,i,a)}});function qs(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(va(e)&&va(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=qs(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;re.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),Ma(e))return e;let o=qs(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var Ys=H(`$ZodTuple`,(e,t)=>{ns.init(e,t);let n=t.items;e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({input:a,inst:e,expected:`tuple`,code:`invalid_type`}),r;r.value=[];let o=[],s=Xs(n,`optin`),c=Xs(n,`optout`);if(!t.rest){if(a.lengthn.length&&r.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:a,inst:e,origin:`array`})}let l=Array(n.length);for(let e=0;e{l[e]=t})):l[e]=t}if(t.rest){let e=n.length-1,s=a.slice(n.length);for(let n of s){e++;let a=t.rest._zod.run({value:n,issues:[]},i);a instanceof Promise?o.push(a.then(t=>Zs(t,r,e))):Zs(a,r,e)}}return o.length?Promise.all(o).then(()=>Qs(l,r,n,a,c)):Qs(l,r,n,a,c)}});function Xs(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!==`optional`)return n+1;return 0}function Zs(e,t,n){e.issues.length&&t.issues.push(...Pa(n,e.issues)),t.value[n]=e.value}function Qs(e,t,n,r,i){for(let a=0;a=i){t.value.length=a;break}t.issues.push(...Pa(a,n.issues))}t.value[a]=n.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}var $s=H(`$ZodRecord`,(e,t)=>{ns.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!va(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>Ia(e,r,na())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...Pa(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...Pa(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&Mo.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Ia(e,r,na())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...Pa(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...Pa(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),ec=H(`$ZodEnum`,(e,t)=>{ns.init(e,t);let n=ra(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>ba.has(typeof e)).map(e=>typeof e==`string`?xa(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),tc=H(`$ZodLiteral`,(e,t)=>{if(ns.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?xa(e):e?xa(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),nc=H(`$ZodTransform`,(e,t)=>{ns.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new ea(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new $i;return n.value=i,n.fallback=!0,n}});function rc(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var ic=H(`$ZodOptional`,(e,t)=>{ns.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,ua(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ua(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${sa(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>rc(e,r)):rc(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),ac=H(`$ZodExactOptional`,(e,t)=>{ic.init(e,t),ua(e._zod,`values`,()=>t.innerType._zod.values),ua(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),oc=H(`$ZodNullable`,(e,t)=>{ns.init(e,t),ua(e._zod,`optin`,()=>t.innerType._zod.optin),ua(e._zod,`optout`,()=>t.innerType._zod.optout),ua(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${sa(e.source)}|null)$`):void 0}),ua(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),sc=H(`$ZodDefault`,(e,t)=>{ns.init(e,t),e._zod.optin=`optional`,ua(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>cc(e,t)):cc(r,t)}});function cc(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var lc=H(`$ZodPrefault`,(e,t)=>{ns.init(e,t),e._zod.optin=`optional`,ua(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),uc=H(`$ZodNonOptional`,(e,t)=>{ns.init(e,t),ua(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>dc(t,e)):dc(i,e)}});function dc(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var fc=H(`$ZodCatch`,(e,t)=>{ns.init(e,t),e._zod.optin=`optional`,ua(e._zod,`optout`,()=>t.innerType._zod.optout),ua(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Ia(e,n,na()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Ia(e,n,na()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),pc=H(`$ZodPipe`,(e,t)=>{ns.init(e,t),ua(e._zod,`values`,()=>t.in._zod.values),ua(e._zod,`optin`,()=>t.in._zod.optin),ua(e._zod,`optout`,()=>t.out._zod.optout),ua(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>mc(e,t.in,n)):mc(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>mc(e,t.out,n)):mc(r,t.out,n)}});function mc(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var hc=H(`$ZodReadonly`,(e,t)=>{ns.init(e,t),ua(e._zod,`propValues`,()=>t.innerType._zod.propValues),ua(e._zod,`values`,()=>t.innerType._zod.values),ua(e._zod,`optin`,()=>t.innerType?._zod?.optin),ua(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(gc):gc(r)}});function gc(e){return e.value=Object.freeze(e.value),e}var _c=H(`$ZodCustom`,(e,t)=>{Lo.init(e,t),ns.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>vc(t,n,r,e));vc(i,n,r,e)}});function vc(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Ra(e))}}var yc,bc=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function xc(){return new bc}(yc=globalThis).__zod_globalRegistry??(yc.__zod_globalRegistry=xc());var Sc=globalThis.__zod_globalRegistry;function Cc(e,t){return new e({type:`string`,...U(t)})}function wc(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...U(t)})}function Tc(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...U(t)})}function Ec(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...U(t)})}function Dc(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...U(t)})}function Oc(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...U(t)})}function kc(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...U(t)})}function Ac(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...U(t)})}function jc(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...U(t)})}function Mc(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...U(t)})}function Nc(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...U(t)})}function Pc(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...U(t)})}function Fc(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...U(t)})}function Ic(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...U(t)})}function Lc(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...U(t)})}function Rc(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...U(t)})}function zc(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...U(t)})}function Bc(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...U(t)})}function Vc(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...U(t)})}function Hc(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...U(t)})}function Uc(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...U(t)})}function Wc(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...U(t)})}function Gc(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...U(t)})}function Kc(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...U(t)})}function qc(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...U(t)})}function Jc(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...U(t)})}function Yc(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...U(t)})}function Xc(e,t){return new e({type:`number`,checks:[],...U(t)})}function Zc(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...U(t)})}function Qc(e,t){return new e({type:`boolean`,...U(t)})}function $c(e,t){return new e({type:`null`,...U(t)})}function el(e){return new e({type:`unknown`})}function tl(e,t){return new e({type:`never`,...U(t)})}function nl(e,t){return new zo({check:`less_than`,...U(t),value:e,inclusive:!1})}function rl(e,t){return new zo({check:`less_than`,...U(t),value:e,inclusive:!0})}function il(e,t){return new Bo({check:`greater_than`,...U(t),value:e,inclusive:!1})}function al(e,t){return new Bo({check:`greater_than`,...U(t),value:e,inclusive:!0})}function ol(e,t){return new Vo({check:`multiple_of`,...U(t),value:e})}function sl(e,t){return new Uo({check:`max_length`,...U(t),maximum:e})}function cl(e,t){return new Wo({check:`min_length`,...U(t),minimum:e})}function ll(e,t){return new Go({check:`length_equals`,...U(t),length:e})}function ul(e,t){return new qo({check:`string_format`,format:`regex`,...U(t),pattern:e})}function dl(e){return new Jo({check:`string_format`,format:`lowercase`,...U(e)})}function fl(e){return new Yo({check:`string_format`,format:`uppercase`,...U(e)})}function pl(e,t){return new Xo({check:`string_format`,format:`includes`,...U(t),includes:e})}function ml(e,t){return new Zo({check:`string_format`,format:`starts_with`,...U(t),prefix:e})}function hl(e,t){return new Qo({check:`string_format`,format:`ends_with`,...U(t),suffix:e})}function gl(e){return new $o({check:`overwrite`,tx:e})}function _l(e){return gl(t=>t.normalize(e))}function vl(){return gl(e=>e.trim())}function yl(){return gl(e=>e.toLowerCase())}function bl(){return gl(e=>e.toUpperCase())}function xl(){return gl(e=>ma(e))}function Sl(e,t,n){return new e({type:`array`,element:t,...U(n)})}function Cl(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...U(n)})}function wl(e,t){let n=Tl(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Ra(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Ra(r))}},e(t.value,t)),t);return n}function Tl(e,t){let n=new Lo({check:`custom`,...U(t)});return n._zod.check=e,n}function El(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Sc,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function Dl(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,Dl(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&Al(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Ol(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function kl(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Ml(t,`input`,e.processors),output:Ml(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function Al(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return Al(r.element,n);if(r.type===`set`)return Al(r.valueType,n);if(r.type===`lazy`)return Al(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return Al(r.innerType,n);if(r.type===`intersection`)return Al(r.left,n)||Al(r.right,n);if(r.type===`record`||r.type===`map`)return Al(r.keyType,n)||Al(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:Al(r.in,n)||Al(r.out,n);if(r.type===`object`){for(let e in r.shape)if(Al(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(Al(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(Al(e,n))return!0;return!!(r.rest&&Al(r.rest,n))}return!1}var jl=(e,t={})=>n=>{let r=El({...n,processors:t});return Dl(e,r),Ol(r,e),kl(r,e)},Ml=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=El({...i??{},target:a,io:t,processors:n});return Dl(e,o),Ol(o,e),kl(o,e)},Nl={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Pl=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Nl[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Fl=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},Il=(e,t,n,r)=>{n.type=`boolean`},Ll=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Rl=(e,t,n,r)=>{n.not={}},zl=(e,t,n,r)=>{let i=e._zod.def,a=ra(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Bl=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Vl=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Hl=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Ul=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=Dl(a.element,t,{...r,path:[...r.path,`items`]})},Wl=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=Dl(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Dl(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Gl=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>Dl(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Kl=(e,t,n,r)=>{let i=e._zod.def,a=Dl(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=Dl(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},ql=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>Dl(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?Dl(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},Jl=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=Dl(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=Dl(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=Dl(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},Yl=(e,t,n,r)=>{let i=e._zod.def,a=Dl(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Xl=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Zl=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Ql=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},$l=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},eu=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;Dl(o,t,r);let s=t.seen.get(e);s.ref=o},tu=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},nu=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ru=H(`ZodISODateTime`,(e,t)=>{gs.init(e,t),ju.init(e,t)});function iu(e){return Kc(ru,e)}var au=H(`ZodISODate`,(e,t)=>{_s.init(e,t),ju.init(e,t)});function ou(e){return qc(au,e)}var su=H(`ZodISOTime`,(e,t)=>{vs.init(e,t),ju.init(e,t)});function cu(e){return Jc(su,e)}var lu=H(`ZodISODuration`,(e,t)=>{ys.init(e,t),ju.init(e,t)});function uu(e){return Yc(lu,e)}var du=(e,t)=>{Ba.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Ua(e,t)},flatten:{value:t=>Ha(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,ia,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,ia,2)}},isEmpty:{get(){return e.issues.length===0}}})},fu=H(`ZodError`,du),pu=H(`ZodError`,du,{Parent:Error}),mu=Wa(pu),hu=Ga(pu),gu=Ka(pu),_u=Ja(pu),vu=Xa(pu),yu=Za(pu),bu=Qa(pu),xu=$a(pu),Su=eo(pu),Cu=to(pu),wu=no(pu),Tu=ro(pu),Eu=new WeakMap;function Du(e,t,n){let r=Object.getPrototypeOf(e),i=Eu.get(r);if(i||(i=new Set,Eu.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var Ou=H(`ZodType`,(e,t)=>(ns.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Ml(e,`input`),output:Ml(e,`output`)}}),e.toJSONSchema=jl(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>mu(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>gu(e,t,n),e.parseAsync=async(t,n)=>hu(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>_u(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>vu(e,t,n),e.decode=(t,n)=>yu(e,t,n),e.encodeAsync=async(t,n)=>bu(e,t,n),e.decodeAsync=async(t,n)=>xu(e,t,n),e.safeEncode=(t,n)=>Su(e,t,n),e.safeDecode=(t,n)=>Cu(e,t,n),e.safeEncodeAsync=async(t,n)=>wu(e,t,n),e.safeDecodeAsync=async(t,n)=>Tu(e,t,n),Du(e,`ZodType`,{check(...e){let t=this.def;return this.clone(fa(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Sa(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Bd(e,t))},superRefine(e,t){return this.check(Vd(e,t))},overwrite(e){return this.check(gl(e))},optional(){return Sd(this)},exactOptional(){return wd(this)},nullable(){return Ed(this)},nullish(){return Sd(Ed(this))},nonoptional(e){return Md(this,e)},array(){return q(this)},or(e){return ud([this,e])},and(e){return fd(this,e)},transform(e){return Id(this,bd(e))},default(e){return Od(this,e)},prefault(e){return Ad(this,e)},catch(e){return Pd(this,e)},pipe(e){return Id(this,e)},readonly(){return Rd(this)},describe(e){let t=this.clone();return Sc.add(t,{description:e}),t},meta(...e){if(e.length===0)return Sc.get(this);let t=this.clone();return Sc.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return Sc.get(e)?.description},configurable:!0}),e)),ku=H(`_ZodString`,(e,t)=>{rs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pl(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Du(e,`_ZodString`,{regex(...e){return this.check(ul(...e))},includes(...e){return this.check(pl(...e))},startsWith(...e){return this.check(ml(...e))},endsWith(...e){return this.check(hl(...e))},min(...e){return this.check(cl(...e))},max(...e){return this.check(sl(...e))},length(...e){return this.check(ll(...e))},nonempty(...e){return this.check(cl(1,...e))},lowercase(e){return this.check(dl(e))},uppercase(e){return this.check(fl(e))},trim(){return this.check(vl())},normalize(...e){return this.check(_l(...e))},toLowerCase(){return this.check(yl())},toUpperCase(){return this.check(bl())},slugify(){return this.check(xl())}})}),Au=H(`ZodString`,(e,t)=>{rs.init(e,t),ku.init(e,t),e.email=t=>e.check(wc(Mu,t)),e.url=t=>e.check(Ac(Fu,t)),e.jwt=t=>e.check(Gc(Xu,t)),e.emoji=t=>e.check(jc(Iu,t)),e.guid=t=>e.check(Tc(Nu,t)),e.uuid=t=>e.check(Ec(Pu,t)),e.uuidv4=t=>e.check(Dc(Pu,t)),e.uuidv6=t=>e.check(Oc(Pu,t)),e.uuidv7=t=>e.check(kc(Pu,t)),e.nanoid=t=>e.check(Mc(Lu,t)),e.guid=t=>e.check(Tc(Nu,t)),e.cuid=t=>e.check(Nc(Ru,t)),e.cuid2=t=>e.check(Pc(zu,t)),e.ulid=t=>e.check(Fc(Bu,t)),e.base64=t=>e.check(Hc(qu,t)),e.base64url=t=>e.check(Uc(Ju,t)),e.xid=t=>e.check(Ic(Vu,t)),e.ksuid=t=>e.check(Lc(Hu,t)),e.ipv4=t=>e.check(Rc(Uu,t)),e.ipv6=t=>e.check(zc(Wu,t)),e.cidrv4=t=>e.check(Bc(Gu,t)),e.cidrv6=t=>e.check(Vc(Ku,t)),e.e164=t=>e.check(Wc(Yu,t)),e.datetime=t=>e.check(iu(t)),e.date=t=>e.check(ou(t)),e.time=t=>e.check(cu(t)),e.duration=t=>e.check(uu(t))});function W(e){return Cc(Au,e)}var ju=H(`ZodStringFormat`,(e,t)=>{is.init(e,t),ku.init(e,t)}),Mu=H(`ZodEmail`,(e,t)=>{ss.init(e,t),ju.init(e,t)}),Nu=H(`ZodGUID`,(e,t)=>{as.init(e,t),ju.init(e,t)}),Pu=H(`ZodUUID`,(e,t)=>{os.init(e,t),ju.init(e,t)}),Fu=H(`ZodURL`,(e,t)=>{cs.init(e,t),ju.init(e,t)}),Iu=H(`ZodEmoji`,(e,t)=>{ls.init(e,t),ju.init(e,t)}),Lu=H(`ZodNanoID`,(e,t)=>{us.init(e,t),ju.init(e,t)}),Ru=H(`ZodCUID`,(e,t)=>{ds.init(e,t),ju.init(e,t)}),zu=H(`ZodCUID2`,(e,t)=>{fs.init(e,t),ju.init(e,t)}),Bu=H(`ZodULID`,(e,t)=>{ps.init(e,t),ju.init(e,t)}),Vu=H(`ZodXID`,(e,t)=>{ms.init(e,t),ju.init(e,t)}),Hu=H(`ZodKSUID`,(e,t)=>{hs.init(e,t),ju.init(e,t)}),Uu=H(`ZodIPv4`,(e,t)=>{bs.init(e,t),ju.init(e,t)}),Wu=H(`ZodIPv6`,(e,t)=>{xs.init(e,t),ju.init(e,t)}),Gu=H(`ZodCIDRv4`,(e,t)=>{Ss.init(e,t),ju.init(e,t)}),Ku=H(`ZodCIDRv6`,(e,t)=>{Cs.init(e,t),ju.init(e,t)}),qu=H(`ZodBase64`,(e,t)=>{Ts.init(e,t),ju.init(e,t)}),Ju=H(`ZodBase64URL`,(e,t)=>{Ds.init(e,t),ju.init(e,t)}),Yu=H(`ZodE164`,(e,t)=>{Os.init(e,t),ju.init(e,t)}),Xu=H(`ZodJWT`,(e,t)=>{As.init(e,t),ju.init(e,t)}),Zu=H(`ZodNumber`,(e,t)=>{js.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fl(e,t,n,r),Du(e,`ZodNumber`,{gt(e,t){return this.check(il(e,t))},gte(e,t){return this.check(al(e,t))},min(e,t){return this.check(al(e,t))},lt(e,t){return this.check(nl(e,t))},lte(e,t){return this.check(rl(e,t))},max(e,t){return this.check(rl(e,t))},int(e){return this.check($u(e))},safe(e){return this.check($u(e))},positive(e){return this.check(il(0,e))},nonnegative(e){return this.check(al(0,e))},negative(e){return this.check(nl(0,e))},nonpositive(e){return this.check(rl(0,e))},multipleOf(e,t){return this.check(ol(e,t))},step(e,t){return this.check(ol(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function G(e){return Xc(Zu,e)}var Qu=H(`ZodNumberFormat`,(e,t)=>{Ms.init(e,t),Zu.init(e,t)});function $u(e){return Zc(Qu,e)}var ed=H(`ZodBoolean`,(e,t)=>{Ns.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Il(e,t,n,r)});function K(e){return Qc(ed,e)}var td=H(`ZodNull`,(e,t)=>{Ps.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ll(e,t,n,r)});function nd(e){return $c(td,e)}var rd=H(`ZodUnknown`,(e,t)=>{Fs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function id(){return el(rd)}var ad=H(`ZodNever`,(e,t)=>{Is.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rl(e,t,n,r)});function od(e){return tl(ad,e)}var sd=H(`ZodArray`,(e,t)=>{Rs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ul(e,t,n,r),e.element=t.element,Du(e,`ZodArray`,{min(e,t){return this.check(cl(e,t))},nonempty(e){return this.check(cl(1,e))},max(e,t){return this.check(sl(e,t))},length(e,t){return this.check(ll(e,t))},unwrap(){return this.element}})});function q(e,t){return Sl(sd,e,t)}var cd=H(`ZodObject`,(e,t)=>{Us.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wl(e,t,n,r),ua(e,`shape`,()=>t.shape),Du(e,`ZodObject`,{keyof(){return Y(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:id()})},loose(){return this.clone({...this._zod.def,catchall:id()})},strict(){return this.clone({...this._zod.def,catchall:od()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Da(this,e)},safeExtend(e){return Oa(this,e)},merge(e){return ka(this,e)},pick(e){return Ta(this,e)},omit(e){return Ea(this,e)},partial(...e){return Aa(xd,this,e[0])},required(...e){return ja(jd,this,e[0])}})});function J(e,t){return new cd({type:`object`,shape:e??{},...U(t)})}var ld=H(`ZodUnion`,(e,t)=>{Gs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gl(e,t,n,r),e.options=t.options});function ud(e,t){return new ld({type:`union`,options:e,...U(t)})}var dd=H(`ZodIntersection`,(e,t)=>{Ks.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kl(e,t,n,r)});function fd(e,t){return new dd({type:`intersection`,left:e,right:t})}var pd=H(`ZodTuple`,(e,t)=>{Ys.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ql(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function md(e,t,n){let r=t instanceof ns;return new pd({type:`tuple`,items:e,rest:r?t:null,...U(r?n:t)})}var hd=H(`ZodRecord`,(e,t)=>{$s.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jl(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function gd(e,t,n){return!t||!t._zod?new hd({type:`record`,keyType:W(),valueType:e,...U(t)}):new hd({type:`record`,keyType:e,valueType:t,...U(n)})}var _d=H(`ZodEnum`,(e,t)=>{ec.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zl(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new _d({...t,checks:[],...U(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new _d({...t,checks:[],...U(r),entries:i})}});function Y(e,t){return new _d({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...U(t)})}var vd=H(`ZodLiteral`,(e,t)=>{tc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bl(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function X(e,t){return new vd({type:`literal`,values:Array.isArray(e)?e:[e],...U(t)})}var yd=H(`ZodTransform`,(e,t)=>{nc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hl(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new ea(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Ra(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Ra(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function bd(e){return new yd({type:`transform`,transform:e})}var xd=H(`ZodOptional`,(e,t)=>{ic.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Sd(e){return new xd({type:`optional`,innerType:e})}var Cd=H(`ZodExactOptional`,(e,t)=>{ac.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wd(e){return new Cd({type:`optional`,innerType:e})}var Td=H(`ZodNullable`,(e,t)=>{oc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ed(e){return new Td({type:`nullable`,innerType:e})}var Dd=H(`ZodDefault`,(e,t)=>{sc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Od(e,t){return new Dd({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ya(t)}})}var kd=H(`ZodPrefault`,(e,t)=>{lc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ql(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ad(e,t){return new kd({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ya(t)}})}var jd=H(`ZodNonOptional`,(e,t)=>{uc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Md(e,t){return new jd({type:`nonoptional`,innerType:e,...U(t)})}var Nd=H(`ZodCatch`,(e,t)=>{fc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$l(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Pd(e,t){return new Nd({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var Fd=H(`ZodPipe`,(e,t)=>{pc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>eu(e,t,n,r),e.in=t.in,e.out=t.out});function Id(e,t){return new Fd({type:`pipe`,in:e,out:t})}var Ld=H(`ZodReadonly`,(e,t)=>{hc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>tu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Rd(e){return new Ld({type:`readonly`,innerType:e})}var zd=H(`ZodCustom`,(e,t)=>{_c.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vl(e,t,n,r)});function Bd(e,t={}){return Cl(zd,e,t)}function Vd(e,t){return wl(e,t)}var Hd=e=>typeof e==`string`&&e.trim()?e.trim():null;function Ud(e){let t=e.decision_scope&&typeof e.decision_scope==`object`&&!Array.isArray(e.decision_scope)?e.decision_scope:{},n=Hd(t.kind),r=Hd(t.granularity),i=Hd(t.scope_key),a=Hd(e.superseded_by);return{interaction:e.task_class===`user_gate`?`decision`:`unknown`,lifecycle:a?`superseded`:e.status===`deferred`?`deferred`:e.done===!0||[`done`,`completed`,`closed`,`archived`].includes(String(e.status))?`closed`:e.status===`open`||e.status===`blocked`?`open`:`unknown`,reason:Hd(e.note),evidence:Hd(e.evidence),blocksAgent:Hd(e.blocks_agent),unblocksTodoId:Hd(e.unblocks_todo_id),decisionScope:n&&r&&i?{kind:n,granularity:r,scopeKey:i}:null,supersededBy:a}}function Wd(e,t,n,r){return{...e,sourceId:t,goalTitle:r??e.goalTitle,details:n?e.details:{...e.details??Ud({}),lifecycle:`unavailable`}}}function Gd(e,t){return t.find(t=>t.sourceId===e.sourceId&&t.goalId===e.goalId&&t.todoId===e.todoId)||{...e,details:{...e.details??Ud({}),lifecycle:`unavailable`}}}function Kd(e,t){let n=e.details?.supersededBy;if(!(!n||n===e.todoId||e.details?.lifecycle===`unavailable`))return t.find(t=>t.sourceId===e.sourceId&&t.goalId===e.goalId&&t.todoId===n)}function qd(e){return![`closed`,`deferred`,`superseded`,`unavailable`].includes(e.details?.lifecycle??`unknown`)}var Jd={ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,runtime_root:`$HOME/.codex/loopx`,goal_count:1,run_count:8440,status_contract:{schema_version:2,minimum_dashboard_schema_version:2,producer:`loopx status`,reload_hint:`scripts/macos-dashboard-launchagent.sh restart`},usage_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.471166+00:00`,sample_run_count:20,proxy_note:`run-history proxy; excludes token counts and raw thread logs`,totals:{runs_24h:20,runs_7d:20,quota_spend_slots_24h:11,quota_spend_slots_7d:11,automation_run_count_24h:11,automation_run_count_7d:11,progress_signal_run_count_24h:9,progress_signal_run_count_7d:9},goals:[{goal_id:`loopx-meta`,runs_24h:20,runs_7d:20,quota_spend_slots_24h:11,quota_spend_slots_7d:11,automation_run_count_24h:11,automation_run_count_7d:11,progress_signal_run_count_24h:9,progress_signal_run_count_7d:9,project_share_24h:1}]},event_ledger_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.360662+00:00`,sample_run_count:20,proxy_note:`append-only run-history projection; compact event-class counts only`,event_classes:[`accounting`,`decision`,`evidence`,`state`,`work`],totals:{events_24h:20,events_7d:20,by_class_24h:{accounting:11,decision:0,evidence:0,state:0,work:9},by_class_7d:{accounting:11,decision:0,evidence:0,state:0,work:9}},goals:[{goal_id:`loopx-meta`,events_24h:20,events_7d:20,by_class_24h:{accounting:11,decision:0,evidence:0,state:0,work:9},by_class_7d:{accounting:11,decision:0,evidence:0,state:0,work:9},latest_event_class:`accounting`,latest_event_at:`2026-07-06T14:37:32+08:00`}]},promotion_readiness_summary:{available:!0,source:`run_history_full_scan`,goal_id:`loopx-meta`,generated_at:`2026-07-05T20:02:02+08:00`,classification:`canary_promotion_readiness_smoke_group`,delivery_batch_scale:`multi_surface`,delivery_outcome:`primary_goal_outcome`,recommended_action:`Canary promotion-readiness smoke passed; promotion may proceed after doctor/status reports fresh evidence.`,json_exists:!0,markdown_exists:!0,freshness_window_hours:24,freshness_status:`fresh`,is_fresh:!0,requires_readiness_run:!1,age_seconds:67624,age_hours:18.78,freshness_reference_time:`2026-07-06T06:49:06.408527+00:00`,sample_run_count:0,proxy_note:`canary promotion-readiness projection from append-only run history; exact evidence stays in run artifacts`},promotion_gate:{ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,runtime_root:`$HOME/.codex/loopx`,gate:`promotion_readiness`,gate_state:`ready`,can_promote:!0,should_warn:!1,non_blocking:!0,recommended_action:`promotion readiness is fresh`,readiness:{available:!0,goal_id:`loopx-meta`,generated_at:`2026-07-05T20:02:02+08:00`,classification:`canary_promotion_readiness_smoke_group`,delivery_batch_scale:`multi_surface`,delivery_outcome:`primary_goal_outcome`,recommended_action:`Canary promotion-readiness smoke passed; promotion may proceed after doctor/status reports fresh evidence.`,json_exists:!0,markdown_exists:!0,runtime_root:`$HOME/.codex/loopx`,freshness_window_hours:24,freshness_status:`fresh`,is_fresh:!0,requires_readiness_run:!1,age_seconds:67624,age_hours:18.78,freshness_reference_time:`2026-07-06T06:49:06.471087+00:00`}},decision_freshness_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.471133+00:00`,sample_run_count:20,window_days:7,proxy_note:`checkpointed decision freshness projection; rebase old decisions at the decision point before reuse`,summary:{decision_count:0,stale_count:0,rebase_required_count:0,fresh_count:0},items:[]},todo_index:JSON.parse(`{"schema_version":"todo_index_v0","source":"live_loopx_status_public_slice","total_count":12,"current_projected_count":12,"rollout_event_count":94,"item_limit":12,"items":[{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo update recorded for todo_1596c3a678bb","schema_version":"todo_index_item_v0","todo_id":"todo_1596c3a678bb","role":"agent","status":"open","title":"todo update recorded for todo_1596c3a678bb","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:33:32Z","latest_event_status":"open","event_count":7,"event_kinds":["todo_update"]},{"goal_id":"loopx-meta","index":24,"done":false,"text":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","schema_version":"todo_index_item_v0","todo_id":"todo_15bc0926a494","role":"agent","status":"open","priority":"P0-REVENUE MONITOR","title":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"github_public_reply_metadata_monitor","claimed_by":"codex-value-explorer","evidence":"autonomous replan: bounded current value-explorer monitor lane with explicit expires_at.","note":"Set bounded watch expiry for metadata-only public reply monitor; no catch-up after expiry.","updated_at":"2026-07-05T06:27:15+08:00"},{"goal_id":"loopx-meta","index":17,"done":false,"text":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","schema_version":"todo_index_item_v0","todo_id":"todo_2bf560b48a0c","role":"agent","status":"open","priority":"P0","title":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"legacy_open_pr_rename_blocker","claimed_by":"codex-main-control"},{"goal_id":"loopx-meta","index":23,"done":false,"text":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","schema_version":"todo_index_item_v0","todo_id":"todo_3ed1c4a69164","role":"agent","status":"open","priority":"P0","title":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"skillsbench_local_verifier_reward_collection","claimed_by":"codex-main-control","required_capabilities":["benchmark_runner"]},{"goal_id":"loopx-meta","index":32,"done":false,"text":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","schema_version":"todo_index_item_v0","todo_id":"todo_44907a5f355d","role":"agent","status":"blocked","priority":"P0","title":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_raw_new_rerun","claimed_by":"codex-main-control","evidence":"Public-safe redacted live LoopX text; inspect local status for the full row.","note":"Do not spend a full citation-check loopx rerun yet: #865 fixed scored output paths and #874 added bootstrap preflight attribution, but citation-check itself still preflights as apt+verifier bootstrap risk on ECS.","updated_at":"2026-06-29T00:49:36+08:00"},{"goal_id":"loopx-meta","index":39,"done":false,"text":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","schema_version":"todo_index_item_v0","todo_id":"todo_4762c790e583","role":"agent","status":"blocked","priority":"P0","title":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_remote_rerun","claimed_by":"codex-main-control","evidence":"A prior benchmark adapter change was validated before the legacy surface was archived. Current research uses the RFC-linked benchmark workspace and toolkit boundary smokes.","note":"2026-06-29: fixed host-local ACP idle/no-output root cause in PR #894. ACP protocol tool_call_count=0 is now distinguished from reverse-channel task-facing bridge activity; repeated codex_exec_bridge_idle_timeout withou…","updated_at":"2026-06-29T19:40:32+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_584f55f8f3b4","schema_version":"todo_index_item_v0","todo_id":"todo_584f55f8f3b4","role":"agent","status":"open","title":"todo add recorded for todo_584f55f8f3b4","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:48:49Z","latest_event_status":"open","event_count":3,"event_kinds":["todo_add","todo_update"]},{"goal_id":"loopx-meta","index":40,"done":false,"text":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","schema_version":"todo_index_item_v0","todo_id":"todo_62debf065fec","role":"agent","status":"blocked","priority":"P0 MONITOR","title":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"monitor_skillsbench_batch","claimed_by":"codex-main-control","evidence":"Observed 2026-06-30T02:52+08: active-state target_key=skillsbench-goal-baseline-30case-20260629T1826Z-r10; local ps/tmux/recent artifact search found no r10 batch process or compact artifact; no raw task/log/trajectory …","updated_at":"2026-06-30T02:54:54+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_93bc6439c521","schema_version":"todo_index_item_v0","todo_id":"todo_93bc6439c521","role":"agent","status":"open","title":"todo add recorded for todo_93bc6439c521","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_claim","latest_event_at":"2026-07-06T06:32:52Z","latest_event_status":"open","event_count":2,"event_kinds":["todo_add","todo_claim"]},{"goal_id":"loopx-meta","index":27,"done":false,"text":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","schema_version":"todo_index_item_v0","todo_id":"todo_aad7e9716927","role":"agent","status":"blocked","priority":"P0","title":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"run_goal_start_product_mode_matrix","claimed_by":"codex-main-control","evidence":"driver.status shows DONE raw then RUN loopx-goal-start with no running driver; raw benchmark_run.compact first_blocker=skillsbench_codex_acp_provider_zero_activity; source guard requires --host-local-acp-launch for Loop…","note":"Remote run group skillsbench-raw-new-goal-start-20260627T0420Z produced a material closeout for citation-check raw only; raw compact attribution is skillsbench_codex_acp_provider_zero_activity with official score missin…","updated_at":"2026-06-27T13:05:47+08:00"},{"goal_id":"loopx-meta","index":21,"done":false,"text":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","schema_version":"todo_index_item_v0","todo_id":"todo_aec1873c7f28","role":"agent","status":"open","priority":"P0 MONITOR","title":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","claimed_by":"codex-main-control","note":"2026-06-23 projection fix: this is monitor context for the powerlifting run, not an advancement next action; current executable path is SkillsBench build cache/prewarm repair.","updated_at":"2026-06-23T10:37:43+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_c02cb7d19607","schema_version":"todo_index_item_v0","todo_id":"todo_c02cb7d19607","role":"agent","status":"open","title":"todo add recorded for todo_c02cb7d19607","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_add","latest_event_at":"2026-07-06T03:47:54Z","latest_event_status":"open","event_count":1,"event_kinds":["todo_add"]}]}`),agent_management_projection:{schema_version:`agent_management_projection_v0`,mode:`read_only`,goal_id:`loopx-meta`,generated_at:`2026-07-06T06:49:06Z`,style_hint:null,truth_contract:{todo_is_runtime_work_item:!0,projection_is_writable:!1,introduces_task_runtime:!1,write_api:!1},source_summary:{registered_agent_count:4,projected_agent_count:4,todo_source:`live_loopx_status_public_slice`,public_safe_export:!0},agents:[{agent_id:`codex-main-control`,agent_model:`peer_v1`,profile_role:`release-validation`,state:`blocked`,next_action:`Continue projected todo todo_2bf560b48a0c.`,last_activity_at:`2026-06-29T00:49:36+08:00`,evidence_refs:[`todo:todo_e72afc24f04a:evidence`],goal_ids:[`loopx-meta`],stale_claim_hint:{state:`activity_missing`,claimed_by:`codex-main-control`,reason:`claimed open todo has no projected activity timestamp`,recommended_operator_action:`inspect evidence before considering reassignment`},current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_2bf560b48a0c`,goal_id:`loopx-meta`,role:`agent`,status:`open`,priority:`P0`,title:`Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harn…`,task_class:`blocker`,action_kind:`legacy_open_pr_rename_blocker`,claimed_by:`codex-main-control`}},{agent_id:`codex-product-capability`,agent_model:`peer_v1`,profile_role:`product-validation`,state:`monitoring`,next_action:`Continue projected todo todo_ded745761822.`,last_activity_at:`2026-07-06T06:29:53Z`,evidence_refs:[`todo:todo_ded745761822:evidence`],goal_ids:[`loopx-meta`],current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_ded745761822`,goal_id:`loopx-meta`,role:`agent`,status:`open`,priority:`P0-LOCAL`,title:`Public-safe redacted live LoopX text; inspect local status for the full row.`,task_class:`continuous_monitor`,action_kind:`Public-safe redacted live LoopX text; inspect local status for the full row.`,claimed_by:`codex-product-capability`,updated_at:`2026-07-04T20:22:45+08:00`}},{agent_id:`codex-side-bypass`,agent_model:`peer_v1`,profile_role:`implementation-validation`,state:`waiting`,next_action:`Inspect status projection before taking work.`,last_activity_at:`2026-07-06T06:32:16Z`,evidence_refs:[`rollout_event:todo_complete:todo_22c946938115`],goal_ids:[`loopx-meta`]},{agent_id:`codex-value-explorer`,agent_model:`peer_v1`,profile_role:`value-exploration`,state:`monitoring`,next_action:`Continue projected todo todo_584f55f8f3b4.`,last_activity_at:`2026-07-06T09:39:59+08:00`,evidence_refs:[`rollout_event:todo_update:todo_584f55f8f3b4`],goal_ids:[`loopx-meta`],current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_584f55f8f3b4`,goal_id:`loopx-meta`,role:`agent`,status:`open`,title:`todo add recorded for todo_584f55f8f3b4`}}]},contract:{ok:!0,summary:{errors:0,warnings:1,checks:6},errors:[],warnings:["loopx-meta: duplicate index rows raw=8444 unique=8440 unexpected=3 artifact_identity_collisions=2 artifact_collision_rows=3 reward_overlays=1; inspect with `loopx history --goal-id loopx-meta inspect-index-duplicates`; artifact identity collisions need review…"],checks:[`registry goals checked: 12`,`registry boundary: shared_local_registry push_allowed=False tracked=False ignored=False`,`user-gate scopes checked: 6 open multi-agent gates`,`runtime root resolved: $HOME/.codex/loopx`,`run-history goals=28 runs=10210`,`public boundary scan clean: 1218 files`]},global_registry:{available:!0,ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,current_registry:`$HOME/.codex/loopx/registry.global.json`,current_registry_is_global:!0,global_goal_count:12,current_goal_count:12,source_registry_count:7,summary:{high:0,action:8,info:0,checks:2,findings:8},findings:[{kind:`source_registry_missing`,severity:`action`,message:"`cc-test` source registry is missing",recommended_action:"reconnect `cc-test` from its project or archive it if the project is obsolete",goal_id:`cc-test`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-test` active state file is missing",recommended_action:"repair `cc-test` state_file or reconnect the project",goal_id:`cc-test`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`cc-tmp` source registry is missing",recommended_action:"reconnect `cc-tmp` from its project or archive it if the project is obsolete",goal_id:`cc-tmp`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-tmp` active state file is missing",recommended_action:"repair `cc-tmp` state_file or reconnect the project",goal_id:`cc-tmp`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`cc-tmp-xdrchpuaul` source registry is missing",recommended_action:"reconnect `cc-tmp-xdrchpuaul` from its project or archive it if the project is obsolete",goal_id:`cc-tmp-xdrchpuaul`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-tmp-xdrchpuaul` active state file is missing",recommended_action:"repair `cc-tmp-xdrchpuaul` state_file or reconnect the project",goal_id:`cc-tmp-xdrchpuaul`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`loopx-auto-research-e2e-probe-20260628-2225-goal` source registry is missing",recommended_action:"reconnect `loopx-auto-research-e2e-probe-20260628-2225-goal` from its project or archive it if the project is obsolete",goal_id:`loopx-auto-research-e2e-probe-20260628-2225-goal`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`loopx-auto-research-e2e-probe-20260628-2225-goal` active state file is missing",recommended_action:"repair `loopx-auto-research-e2e-probe-20260628-2225-goal` state_file or reconnect the project",goal_id:`loopx-auto-research-e2e-probe-20260628-2225-goal`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`}],checks:[`global registry goals checked: 12`,`global source registries checked: 7`]},attention_queue:JSON.parse(`{"available":true,"item_count":1,"needs_user_or_controller":0,"needs_controller":0,"needs_codex":1,"watching_external_evidence":0,"items":[{"goal_id":"loopx-meta","status":"skillsbench_codex_cli_goal_tail4_keepalive_relaunched","lifecycle_phase":"adapter_inspected","lifecycle_flags":["adapter_inspected"],"waiting_on":"codex","severity":"action","recommended_action":"Monitor run_group skillsbench-codex-cli-goal-xhigh-tail4-keepalive-20260706T143132CST using public compact/public artifacts only; once benchmark_run.compact.json lands for each case, classify launcher/case/solver/verifi…","source":"latest_run","quota":{"compute":1.0,"window_hours":24,"slot_minutes":1,"allowed_slots":1440,"spent_slots":97,"state":"eligible","reason":"1 compute quota; eligible for the next automatic agent turn"},"agent_todos":{"source_section":"Agent Todo","total_count":12,"open_count":12,"done_count":0,"items":[{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo update recorded for todo_1596c3a678bb","schema_version":"todo_index_item_v0","todo_id":"todo_1596c3a678bb","role":"agent","status":"open","title":"todo update recorded for todo_1596c3a678bb","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:33:32Z","latest_event_status":"open","event_count":7,"event_kinds":["todo_update"]},{"goal_id":"loopx-meta","index":24,"done":false,"text":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","schema_version":"todo_index_item_v0","todo_id":"todo_15bc0926a494","role":"agent","status":"open","priority":"P0-REVENUE MONITOR","title":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"github_public_reply_metadata_monitor","claimed_by":"codex-value-explorer","evidence":"autonomous replan: bounded current value-explorer monitor lane with explicit expires_at.","note":"Set bounded watch expiry for metadata-only public reply monitor; no catch-up after expiry.","updated_at":"2026-07-05T06:27:15+08:00"},{"goal_id":"loopx-meta","index":17,"done":false,"text":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","schema_version":"todo_index_item_v0","todo_id":"todo_2bf560b48a0c","role":"agent","status":"open","priority":"P0","title":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"legacy_open_pr_rename_blocker","claimed_by":"codex-main-control"},{"goal_id":"loopx-meta","index":23,"done":false,"text":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","schema_version":"todo_index_item_v0","todo_id":"todo_3ed1c4a69164","role":"agent","status":"open","priority":"P0","title":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"skillsbench_local_verifier_reward_collection","claimed_by":"codex-main-control","required_capabilities":["benchmark_runner"]},{"goal_id":"loopx-meta","index":32,"done":false,"text":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","schema_version":"todo_index_item_v0","todo_id":"todo_44907a5f355d","role":"agent","status":"blocked","priority":"P0","title":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_raw_new_rerun","claimed_by":"codex-main-control","evidence":"Public-safe redacted live LoopX text; inspect local status for the full row.","note":"Do not spend a full citation-check loopx rerun yet: #865 fixed scored output paths and #874 added bootstrap preflight attribution, but citation-check itself still preflights as apt+verifier bootstrap risk on ECS.","updated_at":"2026-06-29T00:49:36+08:00"},{"goal_id":"loopx-meta","index":39,"done":false,"text":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","schema_version":"todo_index_item_v0","todo_id":"todo_4762c790e583","role":"agent","status":"blocked","priority":"P0","title":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_remote_rerun","claimed_by":"codex-main-control","evidence":"A prior benchmark adapter change was validated before the legacy surface was archived. Current research uses the RFC-linked benchmark workspace and toolkit boundary smokes.","note":"2026-06-29: fixed host-local ACP idle/no-output root cause in PR #894. ACP protocol tool_call_count=0 is now distinguished from reverse-channel task-facing bridge activity; repeated codex_exec_bridge_idle_timeout withou…","updated_at":"2026-06-29T19:40:32+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_584f55f8f3b4","schema_version":"todo_index_item_v0","todo_id":"todo_584f55f8f3b4","role":"agent","status":"open","title":"todo add recorded for todo_584f55f8f3b4","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:48:49Z","latest_event_status":"open","event_count":3,"event_kinds":["todo_add","todo_update"]},{"goal_id":"loopx-meta","index":40,"done":false,"text":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","schema_version":"todo_index_item_v0","todo_id":"todo_62debf065fec","role":"agent","status":"blocked","priority":"P0 MONITOR","title":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"monitor_skillsbench_batch","claimed_by":"codex-main-control","evidence":"Observed 2026-06-30T02:52+08: active-state target_key=skillsbench-goal-baseline-30case-20260629T1826Z-r10; local ps/tmux/recent artifact search found no r10 batch process or compact artifact; no raw task/log/trajectory …","updated_at":"2026-06-30T02:54:54+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_93bc6439c521","schema_version":"todo_index_item_v0","todo_id":"todo_93bc6439c521","role":"agent","status":"open","title":"todo add recorded for todo_93bc6439c521","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_claim","latest_event_at":"2026-07-06T06:32:52Z","latest_event_status":"open","event_count":2,"event_kinds":["todo_add","todo_claim"]},{"goal_id":"loopx-meta","index":27,"done":false,"text":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","schema_version":"todo_index_item_v0","todo_id":"todo_aad7e9716927","role":"agent","status":"blocked","priority":"P0","title":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"run_goal_start_product_mode_matrix","claimed_by":"codex-main-control","evidence":"driver.status shows DONE raw then RUN loopx-goal-start with no running driver; raw benchmark_run.compact first_blocker=skillsbench_codex_acp_provider_zero_activity; source guard requires --host-local-acp-launch for Loop…","note":"Remote run group skillsbench-raw-new-goal-start-20260627T0420Z produced a material closeout for citation-check raw only; raw compact attribution is skillsbench_codex_acp_provider_zero_activity with official score missin…","updated_at":"2026-06-27T13:05:47+08:00"},{"goal_id":"loopx-meta","index":21,"done":false,"text":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","schema_version":"todo_index_item_v0","todo_id":"todo_aec1873c7f28","role":"agent","status":"open","priority":"P0 MONITOR","title":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","claimed_by":"codex-main-control","note":"2026-06-23 projection fix: this is monitor context for the powerlifting run, not an advancement next action; current executable path is SkillsBench build cache/prewarm repair.","updated_at":"2026-06-23T10:37:43+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_c02cb7d19607","schema_version":"todo_index_item_v0","todo_id":"todo_c02cb7d19607","role":"agent","status":"open","title":"todo add recorded for todo_c02cb7d19607","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_add","latest_event_at":"2026-07-06T03:47:54Z","latest_event_status":"open","event_count":1,"event_kinds":["todo_add"]}]}}]}`),run_history:{available:!0,goal_count:1,run_count:5,goals:[{id:`loopx-meta`,domain:`loopx-platform`,status:`active-read-only`,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`],registry_member:!0,legacy_runtime_goal:!1,adapter_kind:`harness_self_improvement`,adapter_status:`connected-read-only`,index_exists:!0,raw_index_records:8444,unique_runs:8440,quota:{compute:1,window_hours:24,slot_minutes:1,allowed_slots:1440,spent_slots:97,state:`waiting`,reason:`no active Codex-ready work is currently selected`},latest_runs:[{generated_at:`2026-07-06T14:37:32+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-value-explorer`,recommended_action:`审阅 PR #1524 的 Agent Management 面板视觉方向:workspace hint 与 stale claim hint 是否符合预期;确认后允许 codex-value-explorer 自合并。`,health_check:`quota safe-bypass operator gate; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:55+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-main-control`,recommended_action:`[P1] Repair SkillsBench post-run debug gate consistency for countable codex-cli-goal official-zero runs: when attempt_accounting is countable and case_closeout_complete=true, do not project first_blocker=loopx_closeout_…`,health_check:`quota should-run eligible; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:54+08:00`,goal_id:`loopx-meta`,classification:`skillsbench_codex_cli_goal_tail4_keepalive_relaunched`,agent_id:`codex-main-control`,progress_scope:`goal`,delivery_batch_scale:`single_surface`,delivery_outcome:`outcome_progress`,recommended_action:`Monitor run_group skillsbench-codex-cli-goal-xhigh-tail4-keepalive-20260706T143132CST using public compact/public artifacts only; once benchmark_run.compact.json lands for each case, classify launcher/case/solver/verifi…`,health_check:`state_file 1/1; registry_goal 1/1; authority_sources 10`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:34+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-side-bypass`,recommended_action:`[P0] Rerun real KNN visible auto-research after the successor-link fix and verify evaluator completion projects a second-round hypothesis/frontier or explicit completion gate without manual intervention; keep evidence p…`,health_check:`quota should-run eligible; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:32:57+08:00`,goal_id:`loopx-meta`,classification:`auto_research_successor_link_fix_merged`,agent_id:`codex-side-bypass`,progress_scope:`agent_lane`,delivery_batch_scale:`implementation`,delivery_outcome:`outcome_progress`,recommended_action:`[P0] Rerun real KNN visible auto-research after the successor-link fix and verify evaluator completion projects a second-round hypothesis/frontier or explicit completion gate without manual intervention; keep evidence p…`,health_check:`state_file 1/1; registry_goal 1/1; authority_sources 0`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]}]}]}},Yd=W().nullable(),Xd=J({schema_version:X(`goal_acceptance_observation_projection_v0`),goal_id:W(),read_only:X(!0),acceptance_assessed:X(!1),coverage:Y([`partial`,`unavailable`]),missing_sources:q(W()),truncated:K(),historical_progress:q(J({kind:W(),observed_at:Yd,source:W(),evidence_refs:q(W())})),acceptance_gaps:q(J({kind:W(),owner:Yd,reason:Yd,evidence_required:Yd,observed_at:Yd,source:W()})),guards:q(J({kind:W(),todo_id:Yd,blocks_agent:Yd,owner:Yd,reason:Yd,evidence_required:Yd,decision_scope:Yd})),next_action:Yd,next_action_source:Yd}),Zd=ud([W(),G(),K(),nd()]),Qd=gd(W(),Zd),$d=J({todo_id:W().optional(),priority:W().optional(),status:W(),title:W(),claimed_by:W().optional(),task_class:W().optional(),action_kind:W().optional()}),ef=J({gate_id:W(),kind:W(),status:W(),blocks:q(W()).optional()}),tf=J({todo_id:W().optional(),owner_agent:W().optional(),status:W().optional(),lease_until:W().optional(),write_scope:q(W()).optional()}),nf=J({generated_at:W().optional(),classification:W().optional(),summary:W().optional()}),rf=J({kind:W().optional().default(`warning`),message:ud([W(),q(W())]).optional().default(`compact source warning`)}).passthrough(),af=J({schema_version:X(`goal_channel_projection_v0`),mode:X(`read_only`),goal_id:W(),display_name:W(),generated_at:W().optional().nullable(),latest_status:W(),waiting_on:W(),next_action:W(),source_refs:gd(W(),Zd),decision_frame:J({user_action_required:K(),agent_action_required:K(),quiet_noop_allowed:K()}),quota:Qd,user_todos:q($d).default([]),agent_todos:q($d).default([]),open_gates:q(ef).default([]),active_leases:q(tf).default([]),artifacts:q(Qd).default([]),recent_events:q(nf).default([]),source_warnings:q(rf).default([]),truth_contract:J({event_ledger_is_source_of_truth:K(),projection_is_writable:K(),recompute_rule:W(),write_authority:W()})}),of=J({compute:G().optional().default(1),window_hours:G().optional().default(24),slot_minutes:G().optional().default(1),allowed_slots:G().optional().nullable(),spent_slots:G().optional().default(0),state:W().optional().nullable(),next_eligible_at:W().optional().nullable(),reason:W().optional().nullable(),blocked_action_scope:W().optional().nullable(),focus_wait:K().optional().nullable(),handoff_outcome_floor_block:K().optional().nullable(),safe_bypass_allowed:K().optional().default(!1),safe_bypass_kind:W().optional().nullable(),safe_bypass_policy:W().optional().nullable(),post_handoff_outcome_gap_streak:G().optional().nullable(),outcome_gap_threshold:G().optional().nullable(),must_advance:q(W()).optional().default([]),avoid:q(W()).optional().default([])}).transform(e=>{let t=Math.max(1,e.slot_minutes),n=Math.round(e.window_hours*60*e.compute/t);return{...e,slot_minutes:t,allowed_slots:e.allowed_slots??n}}),sf=J({self_repair:J({enabled:K().optional().default(!1),allow_health_blocker_repair:K().optional().default(!1),allow_waiting_projection_repair:K().optional().default(!1)}).optional().nullable()}).passthrough(),cf=J({model_config:J({model:W(),reasoning_effort:W().optional()}).optional(),mode:W().optional().default(`default`),orchestration_mode:W().optional().nullable(),spawn_allowed:K().optional().default(!1),allowed:K().optional().nullable(),max_children:G().optional().default(0),allowed_domains:q(W()).optional().default([])}).passthrough(),lf=J({label:W().optional().nullable(),path:W(),anchor:W().optional().nullable(),exists:K().optional().default(!1),resolved_path:W().optional().nullable()}),uf=J({index:G(),done:K(),text:W(),schema_version:W().optional().nullable(),todo_id:W().optional().nullable(),role:W().optional().nullable(),status:W().optional().nullable(),resume_when:W().optional().nullable(),resume_ready:K().optional().nullable(),resume_condition:gd(W(),id()).optional().nullable(),priority:W().optional().nullable(),title:W().optional().nullable(),archive_state:W().optional().nullable(),source_section:W().optional().nullable(),task_class:W().optional().nullable(),task_domain:W().optional().nullable(),action_kind:W().optional().nullable(),claimed_by:W().optional().nullable(),required_capabilities:q(W()).optional(),note:W().optional().nullable(),evidence:W().optional().nullable(),updated_at:W().optional().nullable(),review_materials:q(lf).optional().default([])}).passthrough(),df=J({source_section:W().optional().nullable(),total_count:G().optional().default(0),open_count:G().optional().default(0),done_count:G().optional().default(0),advancement_done_count:G().optional(),items:q(uf).optional().default([]),deferred_items:q(uf).optional()}),ff=uf.extend({goal_id:W(),source:W().optional().nullable(),event_count:G().optional().default(0),event_kinds:q(W()).optional().default([]),latest_event_kind:W().optional().nullable(),latest_event_at:W().optional().nullable(),latest_event_status:W().optional().nullable(),agent_id:W().optional().nullable()}).passthrough(),pf=J({schema_version:W().optional().nullable(),source:W().optional().nullable(),total_count:G().optional().default(0),current_projected_count:G().optional().default(0),rollout_event_count:G().optional().default(0),item_limit:G().optional().nullable(),items:q(ff).optional().default([])}),mf=J({kind:W().optional().nullable(),label:W().optional().nullable(),path_safe:K().optional().default(!1),branch:W().optional().nullable(),write_scope:q(W()).optional().default([])}).passthrough(),hf=J({state:W().optional().nullable(),claimed_by:W().optional().nullable(),last_activity_at:W().optional().nullable(),threshold_hours:G().optional().nullable(),reason:W().optional().nullable(),recommended_operator_action:W().optional().nullable()}).passthrough(),gf=J({schema_version:W().optional().nullable(),todo_id:W().optional().nullable(),goal_id:W().optional().nullable(),role:W().optional().nullable(),status:W().optional().nullable(),priority:W().optional().nullable(),title:W().optional().nullable(),task_class:W().optional().nullable(),action_kind:W().optional().nullable(),claimed_by:W().optional().nullable(),required_write_scopes:q(W()).optional().default([]),workspace_ref:mf.optional().nullable()}).passthrough(),_f=J({schema_version:W().optional().nullable(),from_agent:W().optional().nullable(),to_agent:W().optional().nullable(),intent:W().optional().nullable(),summary:W().optional().nullable(),blocker:W().optional().nullable(),suggested_next_action:W().optional().nullable(),evidence_refs:q(W()).optional().default([]),updated_at:W().optional().nullable()}).passthrough(),vf=J({agent_id:W(),role:W().optional().nullable(),state:W().optional().nullable(),current_todo:gf.optional().nullable(),next_action:W().optional().nullable(),last_activity_at:W().optional().nullable(),evidence_refs:q(W()).optional().default([]),handoff_refs:q(W()).optional().default([]),handoff_note:_f.optional().nullable(),workspace_ref:mf.optional().nullable(),stale_claim_hint:hf.optional().nullable(),blocked_on:gf.optional().nullable(),goal_ids:q(W()).optional().default([])}).passthrough(),yf=J({schema_version:W().optional().nullable(),mode:W().optional().nullable(),goal_id:W().optional().nullable(),generated_at:W().optional().nullable(),style_hint:J({preferred:W().optional().nullable(),license_boundary:W().optional().nullable()}).optional().nullable(),truth_contract:J({todo_is_runtime_work_item:K().optional().default(!0),projection_is_writable:K().optional().default(!1),introduces_task_runtime:K().optional().default(!1),write_api:K().optional().default(!1)}).optional().nullable(),source_summary:J({registered_agent_count:G().optional().default(0),projected_agent_count:G().optional().default(0),todo_source:W().optional().nullable()}).optional().nullable(),agents:q(vf).optional().default([])}).passthrough(),bf=J({goal_id:W(),configured:K().optional().default(!1),enabled:K().optional().default(!1),human_gate_auto_notify_enabled:K().optional().default(!1),target_ref:W().optional().nullable(),receipt_count:G().optional().default(0),last_notified_at:W().optional().nullable()}).passthrough(),xf=J({schema_version:W().optional().nullable(),generated_at:W().optional().nullable(),goals:q(bf).optional().default([])}).passthrough(),Sf=J({source_section:W().optional().nullable(),open:G().optional().default(0),done:G().optional().default(0),total:G().optional().default(0),advancement_done_count:G().optional(),next:W().optional().nullable(),next_index:G().optional().nullable(),items:q(uf).optional().default([]),recent_completed_advancement_items:q(uf).optional().default([])}),Cf=J({goal_id:W(),status:W().optional().nullable(),waiting_on:W().optional().nullable(),severity:W().optional().nullable(),index:G().optional().nullable(),text:W(),source:W().optional().nullable()}),wf=J({source:W().optional().nullable(),open_count:G().optional().default(0),items:q(Cf).optional().default([])}),Tf=J({goal_id:W(),status:W().optional().nullable(),waiting_on:W().optional().nullable(),quota_state:W().optional().nullable(),priority:W().optional().nullable(),todo_index:G().optional().nullable(),text:W(),source:W().optional().nullable()}),Ef=J({source:W().optional().nullable(),open_count:G().optional().default(0),items:q(Tf).optional().default([])}),Df=J({generated_at:W().optional().nullable(),classification:W().optional().nullable(),summary:W().optional().nullable()}),Of=J({kind:W().optional().nullable(),source:W().optional().nullable(),severity:W().optional().nullable(),requires_refresh_state:K().optional().default(!1),reason:W().optional().nullable(),active_state_updated_at:W().optional().nullable(),latest_run_generated_at:W().optional().nullable(),latest_run_state_updated_at:W().optional().nullable(),latest_run_classification:W().optional().nullable(),recommended_action:W().optional().nullable()}),kf=J({generated_at:W().optional().nullable(),classification:W().optional().nullable(),delivery_batch_scale:W().optional().nullable(),delivery_outcome:W().optional().nullable(),health_check:W().optional().nullable(),json_exists:K().optional().nullable(),markdown_exists:K().optional().nullable()}),Af=J({project_asset_backed:K().optional(),same_source_should_run:K().optional(),codex_ready:K().optional(),handoff_has_next_action:K().optional(),handoff_has_stop_condition:K().optional(),handoff_sanitized_surface:K().optional()}).catchall(K()),jf=J({ready:K().optional().default(!1),codex_ready:K().optional().default(!1),source:W().optional().nullable(),quota_state:W().optional().nullable(),checks:Af.optional().default({}),handoff_status:W().optional().nullable(),handoff_ready_at:W().optional().nullable(),handoff_ready_classification:W().optional().nullable(),post_handoff_run_seen:K().optional().default(!1),post_handoff_latest_run:kf.optional().nullable(),post_handoff_recent_runs:q(kf).optional().default([]),post_handoff_small_scale_streak:G().int().nonnegative().optional().default(0),post_handoff_outcome_gap_streak:G().int().nonnegative().optional().default(0),next_probe:W().optional().nullable()}),Mf=J({schema_version:W().optional().nullable(),kind:W().optional().nullable(),missing_roles:q(W()).optional().default([]),source:W().optional().nullable(),recommended_action:W().optional().nullable()}),Nf=J({owner:W(),gate:W(),next_action:W(),stop_condition:W(),user_todos:Sf.optional().nullable(),agent_todos:Sf.optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),orchestration:cf.optional().nullable(),latest_validation:Df.optional().nullable(),stale_latest_run_warning:Of.optional().nullable(),todo_projection_gap:Mf.optional().nullable()}),Pf=J({goal_id:W(),activation_state:Y([`active`,`stopped`]).optional().default(`active`),status:W(),waiting_on:W(),severity:W(),recommended_action:W(),project_asset:Nf.optional().nullable(),handoff_readiness:jf.optional().nullable(),source:W().optional(),operator_question:W().optional().nullable(),agent_command:W().optional().nullable(),lifecycle_phase:W().optional().nullable(),lifecycle_flags:q(W()).optional().default([]),controller_stage:W().optional().nullable(),missing_gates:q(W()).optional().default([]),next_handoff_condition:W().optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),user_todos:df.optional().nullable(),agent_todos:df.optional().nullable(),stale_latest_run_warning:Of.optional().nullable(),dependency_blockers:wf.optional().nullable(),todo_state_file:W().optional().nullable(),goal_channel_projection:af.optional().nullable()}),Ff=J({recorded_at:W().optional().nullable(),decision:W().optional().nullable(),reward:W().optional().nullable(),reason_summary:W().optional().nullable(),follow_up:W().optional().nullable()}),If=J({recorded_at:W().optional().nullable(),gate:W().optional().nullable(),decision:W().optional().nullable(),operator_question:W().optional().nullable(),reason_summary:W().optional().nullable(),follow_up:W().optional().nullable(),agent_command:W().optional().nullable()}),Lf=J({version:W().optional().nullable(),goal_id:W().optional().nullable(),run_id:W().optional().nullable(),gate_id:W().optional().nullable(),created_state_ref:W().optional().nullable(),created_policy_version:W().optional().nullable(),interrupt_payload:J({question:W().optional().nullable(),choices:q(W()).optional().default([])}).optional().nullable(),allowed_decisions:q(W()).optional().default([]),operator_decision:W().optional().nullable(),latest_state_ref:W().optional().nullable(),freshness_check:W().optional().nullable(),precondition_check:W().optional().nullable(),migration_or_rebase_result:W().optional().nullable(),resulting_action:W().optional().nullable(),validation_after_resume:W().optional().nullable()}),Rf=J({id:W().optional().nullable(),ok:K().optional().nullable(),review:W().optional().nullable()}),zf=J({classification:W().optional().nullable(),read_only_observer_ready:K().optional().nullable(),decision_advisor_ready:K().optional().nullable(),write_controller_ready:K().optional().nullable(),missing_gates:q(W()).optional().default([]),review_judgment:W().optional().nullable(),next_handoff_condition:W().optional().nullable(),gates:q(Rf).optional().default([])}),Bf=J({declared:K().optional().default(!1),required:K().optional().default(!1),path:W().optional().nullable(),path_exists:K().optional().nullable(),read_status:W().optional().nullable(),default_entry_count:G().optional().default(0),default_entries_checked:G().optional().default(0),default_entries_present:G().optional().default(0),topic_authority_count:G().optional().default(0),project_material_count:G().optional().default(0),project_material_repository_count:G().optional().default(0),project_material_owner_review_required_count:G().optional().default(0),project_material_stale_count:G().optional().default(0),project_material_current_authority_count:G().optional().default(0),deprecated_source_count:G().optional().default(0),conflict_risk:W().optional().nullable()}),Vf=J({adapter_kind:W().optional().nullable(),adapter_status:W().optional().nullable(),authority_source_count:G().optional().nullable(),authority_registry_declared:K().optional().nullable(),authority_registry_path_exists:K().optional().nullable(),authority_registry_default_entry_count:G().optional().nullable(),authority_registry_default_entries_present:G().optional().nullable(),topic_authority_count:G().optional().nullable(),project_material_count:G().optional().nullable(),project_material_repository_count:G().optional().nullable(),project_material_owner_review_required_count:G().optional().nullable(),project_material_stale_count:G().optional().nullable(),project_material_current_authority_count:G().optional().nullable(),authority_registry_conflict_risk:W().optional().nullable(),guard_count:G().optional().nullable(),sections_found:G().optional().nullable(),sections_checked:G().optional().nullable(),files_present:G().optional().nullable(),files_checked:G().optional().nullable()}),Hf=J({generated_at:W(),goal_id:W(),classification:W().optional().nullable(),lifecycle_phase:W().optional().nullable(),lifecycle_flags:q(W()).optional().default([]),recommended_action:W().optional().nullable(),health_check:W().optional().nullable(),active_task_count:G().optional().nullable(),active_priorities:gd(W(),id()).optional().nullable(),cache_check:W().optional().nullable(),json_exists:K().optional().default(!1),markdown_exists:K().optional().default(!1),human_reward:Ff.optional().nullable(),operator_gate:If.optional().nullable(),operator_gate_resume_contract:Lf.optional().nullable(),controller_readiness:zf.optional().nullable(),project_map:Vf.optional().nullable()}),Uf=J({acceptance_observation:Xd.optional().nullable().catch(null),id:W(),activation_state:Y([`active`,`stopped`]).optional().default(`active`),display_name:W().optional().nullable(),domain:W().optional().nullable(),status:W().optional().nullable(),lifecycle_phase:W().optional().nullable(),lifecycle_flags:q(W()).optional().default([]),registry_member:K().optional().default(!1),legacy_runtime_goal:K().optional().default(!1),adapter_kind:W().optional().nullable(),adapter_status:W().optional().nullable(),authority_registry:Bf.optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),spawn_policy:cf.optional().nullable(),orchestration:cf.optional().nullable(),coordination:J({agent_model:W().optional().nullable(),registered_agents:q(W()).optional().default([])}).optional().nullable(),index_exists:K().optional().default(!1),raw_index_records:G().optional().default(0),unique_runs:G().optional().default(0),latest_runs:q(Hf).optional().default([])}),Wf=J({available:K(),goal_count:G().optional().default(0),run_count:G().optional().default(0),goals:q(Uf).optional().default([]),recent_runs:q(Hf).optional().default([])}),Gf=J({kind:W(),severity:W(),message:W(),recommended_action:W(),goal_id:W().optional().nullable(),path:W().optional().nullable(),goal_ids:q(W()).optional().default([])}),Kf=J({available:K(),ok:K(),registry:W(),current_registry:W().optional().nullable(),current_registry_is_global:K().optional().default(!1),global_goal_count:G().optional().default(0),current_goal_count:G().optional().default(0),source_registry_count:G().optional().default(0),summary:J({high:G().optional().default(0),action:G().optional().default(0),info:G().optional().default(0),checks:G().optional().default(0),findings:G().optional().default(0)}),findings:q(Gf).optional().default([]),checks:q(W()).optional().default([])}),qf=J({runs_24h:G().optional().default(0),runs_7d:G().optional().default(0),quota_spend_slots_24h:G().optional().default(0),quota_spend_slots_7d:G().optional().default(0),automation_run_count_24h:G().optional().default(0),automation_run_count_7d:G().optional().default(0),progress_signal_run_count_24h:G().optional().default(0),progress_signal_run_count_7d:G().optional().default(0),input_tokens_24h:G().optional(),input_tokens_7d:G().optional(),output_tokens_24h:G().optional(),output_tokens_7d:G().optional(),cache_tokens_24h:G().optional(),cache_tokens_7d:G().optional(),cost_usd_24h:G().optional(),cost_usd_7d:G().optional(),duration_ms_24h:G().optional(),duration_ms_7d:G().optional()}),Jf=qf.extend({goal_id:W(),project_share_24h:G().optional().default(0)}),Yf=J({available:K().optional().default(!0),source:W().optional().default(`run_history`),generated_at:W().optional().nullable(),sample_run_count:G().optional().default(0),proxy_note:W().optional().nullable(),totals:qf.optional().default({runs_24h:0,runs_7d:0,quota_spend_slots_24h:0,quota_spend_slots_7d:0,automation_run_count_24h:0,automation_run_count_7d:0,progress_signal_run_count_24h:0,progress_signal_run_count_7d:0}),goals:q(Jf).optional().default([])}).optional().nullable(),Xf=J({accounting:G().optional().default(0),decision:G().optional().default(0),evidence:G().optional().default(0),state:G().optional().default(0),work:G().optional().default(0)}),Zf={accounting:0,decision:0,evidence:0,state:0,work:0},Qf=J({events_24h:G().optional().default(0),events_7d:G().optional().default(0),by_class_24h:Xf.optional().default(Zf),by_class_7d:Xf.optional().default(Zf)}),$f=Qf.extend({goal_id:W(),latest_event_class:W().optional().nullable(),latest_event_at:W().optional().nullable()}),ep={events_24h:0,events_7d:0,by_class_24h:Zf,by_class_7d:Zf},tp=J({available:K().optional().default(!0),source:W().optional().default(`run_history`),generated_at:W().optional().nullable(),sample_run_count:G().optional().default(0),proxy_note:W().optional().nullable(),event_classes:q(W()).optional().default([`accounting`,`decision`,`evidence`,`state`,`work`]),totals:Qf.optional().default(ep),goals:q($f).optional().default([])}).optional().nullable(),np=J({available:K().optional().default(!1),source:W().optional().default(`run_history`),goal_id:W().optional().nullable(),generated_at:W().optional().nullable(),classification:W().optional().nullable(),delivery_batch_scale:W().optional().nullable(),delivery_outcome:W().optional().nullable(),recommended_action:W().optional().nullable(),json_exists:K().optional().default(!1),markdown_exists:K().optional().default(!1),freshness_window_hours:G().optional().default(24),freshness_status:W().optional().nullable(),is_fresh:K().optional().default(!1),requires_readiness_run:K().optional().default(!0),age_seconds:G().optional().nullable(),age_hours:G().optional().nullable(),freshness_reference_time:W().optional().nullable(),sample_run_count:G().optional().default(0),proxy_note:W().optional().nullable(),reason:W().optional().nullable()}).optional().nullable(),rp=J({ok:K().optional().default(!0),registry:W().optional().nullable(),runtime_root:W().optional().nullable(),gate:W().optional().default(`promotion_readiness`),gate_state:W().optional().default(`warning`),can_promote:K().optional().default(!1),should_warn:K().optional().default(!0),non_blocking:K().optional().default(!0),recommended_action:W().optional().nullable(),warning_message:W().optional().nullable(),readiness:np.default(null)}).optional().nullable(),ip=J({decision_count:G().optional().default(0),stale_count:G().optional().default(0),rebase_required_count:G().optional().default(0),fresh_count:G().optional().default(0)}),ap=J({goal_id:W(),decision_kind:W().optional().nullable(),decision_at:W().optional().nullable(),classification:W().optional().nullable(),age_days:G().optional().nullable(),stale_by_age:K().optional().default(!1),newer_event_count_7d:G().optional().default(0),newer_event_classes_7d:Xf.optional().default(Zf),freshness_state:W().optional().nullable(),requires_decision_point_rebase:K().optional().default(!1),reason:W().optional().nullable()}),op=J({available:K().optional().default(!0),source:W().optional().default(`run_history`),generated_at:W().optional().nullable(),sample_run_count:G().optional().default(0),window_days:G().optional().default(7),proxy_note:W().optional().nullable(),summary:ip.optional().default({decision_count:0,stale_count:0,rebase_required_count:0,fresh_count:0}),items:q(ap).optional().default([])}).optional().nullable(),sp=J({schema_version:G().optional().default(0),minimum_dashboard_schema_version:G().optional().default(2),producer:W().optional().nullable(),reload_hint:W().optional().nullable()}).optional().default({schema_version:0,minimum_dashboard_schema_version:2,producer:null,reload_hint:`scripts/macos-dashboard-launchagent.sh restart`}),cp=J({schema_version:X(`loopx_goal_projection_scope_v0`),scope:Y([`all`,`active`,`stopped`]),complete:K(),projected_goal_count:G().int().nonnegative(),registry_goal_count:G().int().nonnegative(),registry_revision:W().optional().nullable()}),lp=J({source:W().optional().default(`serve-status`),status_url:W().optional().nullable(),health_url:W().optional().nullable(),review_material_url:W().optional().nullable(),presentation_surfaces_url:W().optional().nullable(),presentation_detail_url:W().optional().nullable(),periodic_report_index_url:W().optional().nullable(),periodic_report_detail_url:W().optional().nullable(),ssh_hosts_url:W().optional().nullable(),reward_dry_run_url:W().optional().nullable(),reward_append_url:W().optional().nullable(),reward_write_enabled:K().optional().default(!1),configure_goal_dry_run_url:W().optional().nullable(),configure_goal_apply_url:W().optional().nullable(),control_plane_write_enabled:K().optional().default(!1)}).optional().nullable(),up=J({extension_id:W().min(1),surface_id:W().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/),extension_revision:W().min(1),payload_sha256:W().regex(/^[0-9a-f]{64}$/)}).strict(),dp=J({extension_id:W().min(1),extension_revision:W().min(1),surface_id:W().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/),surface_kind:W().regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/),title:W().min(1),view_schema:W().regex(/^[a-z][a-z0-9_]*_v\d+$/),visibility:Y([`public-safe`,`owner-only`]),goal_id:W().min(1).nullable(),generated_at:W().min(1).nullable(),review_due_at:W().min(1).nullable(),diagnostic:W().min(1).nullable(),empty_state_title:W().min(1),empty_state_detail:W().min(1)}),fp=ud([dp.extend({state:Y([`ready`,`review_due`]),goal_id:W().min(1),generated_at:W().min(1),detail_ref:up}).strict(),dp.extend({state:X(`empty`),detail_ref:od().optional()}).strict(),dp.extend({state:X(`invalid`),diagnostic:W().min(1),detail_ref:od().optional()}).strict()]),pp=J({schema_version:X(`extension_presentation_surfaces_v0`),count:G().int().nonnegative(),ready_count:G().int().nonnegative(),review_due_count:G().int().nonnegative(),empty_count:G().int().nonnegative(),invalid_count:G().int().nonnegative(),items:q(fp)}).strict(),mp={schema_version:`extension_presentation_surfaces_v0`,count:0,ready_count:0,review_due_count:0,empty_count:0,invalid_count:0,items:[]};J({ok:X(!0),presentation_surfaces:pp}).strict();var hp=J({goal_id:W().min(1),agent_id:W().min(1),generation_id:W().min(1),content_sha256:W().regex(/^sha256:[0-9a-f]{64}$/)}).strict(),gp=J({goal_id:W().min(1),agent_id:W().min(1),generation_id:W().min(1),publication_id:W().min(1),delivered_at:W().min(1),predecessor_publication_id:W().min(1).nullable().optional(),detail_ref:hp}).strict(),_p=J({schema_version:X(`periodic_report_workspace_index_v0`),count:G().int().nonnegative(),items:q(gp)}),vp=_p.extend({returned_count:G().int().nonnegative(),total_count:G().int().nonnegative(),limit:G().int().nonnegative(),offset:G().int().nonnegative(),truncated:K()}).strict(),yp=_p.strict().transform(e=>({...e,returned_count:e.count,total_count:e.count,limit:e.count,offset:0,truncated:!1})),bp=J({ok:X(!0),periodic_reports:ud([vp,yp])}).strict(),xp=J({schema_version:X(`periodic_report_workspace_projection_v0`),goal_id:W().min(1),agent_id:W().min(1),generation_id:W().min(1),generated_at:W().min(1),title:W().min(1),summary:W().min(1),content_sha256:W().regex(/^sha256:[0-9a-f]{64}$/),period_window:J({start_at:W().min(1),end_at:W().min(1)}).strict(),interaction:J({attention_kind:X(`progress`),interaction:X(`inform`),delivery:X(`surface`),form:X(`milestone_report`),writable:X(!1)}).strict(),delta:J({added_count:G().int().nonnegative(),changed_count:G().int().nonnegative(),item_count:G().int().positive(),items:q(J({fact_id:W().min(1),source_ref:W().min(1),title:W().min(1),summary:W().min(1),status:W().min(1),content_kind:W().min(1),change_kind:Y([`added`,`changed`]),previous_status:W().min(1).optional()}).strict())}).strict(),publication:J({publication_id:W().min(1),delivered_at:W().min(1),predecessor_publication_id:W().min(1).nullable().optional(),cursor_id:W().min(1)}).strict(),truth_contract:J({published_cursor_is_source_of_truth:X(!0),generation_receipt_is_delivery_receipt:X(!1),projection_is_writable:X(!1),browser_write_api:X(!1)}).strict()}).strict(),Sp=J({ok:X(!0),projection:xp}).strict(),Cp=J({ok:K(),registry:W(),runtime_root:W(),goal_count:G(),run_count:G(),status_contract:sp,goal_projection:cp.optional().nullable().default(null),local_dashboard_api:lp,contract:J({ok:K(),summary:J({errors:G(),warnings:G(),checks:G()}),errors:q(W()),warnings:q(W()),checks:q(W()).optional().default([])}),global_registry:Kf.optional().default({available:!1,ok:!0,registry:``,current_registry:null,current_registry_is_global:!1,global_goal_count:0,current_goal_count:0,source_registry_count:0,summary:{high:0,action:0,info:0,checks:0,findings:0},findings:[],checks:[]}),attention_queue:J({available:K(),item_count:G(),needs_user_or_controller:G(),needs_controller:G().optional().default(0),needs_codex:G(),watching_external_evidence:G(),autonomous_backlog_candidates:Ef.optional().nullable(),items:q(Pf)}),run_history:Wf.optional().default({available:!1,goal_count:0,run_count:0,goals:[],recent_runs:[]}),event_ledger_summary:tp.default(null),promotion_readiness_summary:np.default(null),promotion_gate:rp.default(null),decision_freshness_summary:op.default(null),usage_summary:Yf.default(null),todo_index:pf.optional().nullable().default(null),agent_management_projection:yf.optional().nullable().default(null),goal_channel_notification_projection:xf.optional().nullable().default(null),presentation_surfaces:pp.optional().default(mp)});J({ok:K(),dry_run:K().optional().default(!0),appended:K().optional().default(!1),goal_id:W().optional().nullable(),raw_index_records_before:G().optional().nullable(),preview_id:W().optional().nullable(),selected_run:J({generated_at:W().optional().nullable(),classification:W().optional().nullable(),recommended_action:W().optional().nullable(),json_exists:K().optional().nullable(),markdown_exists:K().optional().nullable()}).optional().nullable(),human_reward:Ff.optional().nullable(),active_state_summary:W().optional().nullable(),project_agent_visibility:J({source_of_truth:W().optional().nullable(),history_command:W().optional().nullable(),active_state_role:W().optional().nullable(),review_packet_role:W().optional().nullable()}).optional().nullable(),error:W().optional().nullable()});function wp(e,t,n){let r=e.run_history.goals.map(e=>e.id===t&&e.activation_state!==n?{...e,activation_state:n}:e),i=e.attention_queue.items.map(e=>e.goal_id===t&&e.activation_state!==n?{...e,activation_state:n}:e),a=r.some((t,n)=>t!==e.run_history.goals[n]),o=i.some((t,n)=>t!==e.attention_queue.items[n]);return!a&&!o?e:{...e,attention_queue:o?{...e.attention_queue,items:i}:e.attention_queue,run_history:a?{...e.run_history,goals:r}:e.run_history}}function Tp(e,t){let n=e.run_history.goals.filter(e=>e.id!==t),r=e.attention_queue.items.filter(e=>e.goal_id!==t);return n.length===e.run_history.goals.length&&r.length===e.attention_queue.items.length?e:{...e,attention_queue:{...e.attention_queue,items:r},run_history:{...e.run_history,goals:n}}}function Ep(e){return Cp.parse(e)}function Dp(e){return e instanceof fu?e.issues.map(e=>`${e.path.join(`.`)||`root`}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}var Op=Ep(Jd),kp=J({ok:X(!0),schema_version:X(`loopx_workspace_directory_v1`),registry_revision:W(),goals:q(J({id:W(),display_name:W(),activation_state:Y([`active`,`stopped`]),registry_member:X(!0)}))});function Ap(e,t,n){let r=new URL(e,n);r.searchParams.delete(`goal_activation`),r.searchParams.delete(`goal_id`),r.searchParams.delete(`view`);for(let[e,n]of Object.entries(t))r.searchParams.set(e,n);return r.toString()}async function jp(e,t){let n=await fetch(Ap(e,{view:`workspace-directory`},t),{cache:`no-store`,signal:AbortSignal.timeout(5e3)});if(!n.ok)return null;let r=kp.safeParse(await n.json());return r.success?r.data:null}function Mp(e){return Ep({ok:!0,registry:``,runtime_root:``,goal_count:e.goals.length,run_count:0,local_dashboard_api:{},contract:{ok:!0,summary:{errors:0,warnings:0,checks:0},errors:[],warnings:[]},attention_queue:{available:!1,item_count:0,needs_user_or_controller:0,needs_codex:0,watching_external_evidence:0,items:[]},run_history:{available:!1,goal_count:e.goals.length,run_count:0,goals:e.goals,recent_runs:[]}})}async function Np(e,t,n,r,i,a,o){let s=[...n.goals],c=new Map;async function l(){for(;s.length&&i()&&!o?.aborted;){let l=s.findIndex(e=>e.id===a()),u=l>=0?l:s.findIndex(e=>e.activation_state===`active`);if(u<0)return;let d=s.splice(u,1)[0],f=(c.get(d.id)??0)+1;c.set(d.id,f);let p=new AbortController,m=!1,h=()=>p.abort();o?.addEventListener(`abort`,h,{once:!0});let g=setTimeout(()=>{m=!0,p.abort()},3e4),_=null;try{let a=await fetch(Ap(e,{goal_id:d.id},t),{cache:`no-store`,signal:p.signal});if(!a.ok)_=a.status===409?`revision`:a.status>=500?`service`:`scope`;else{let e=await a.json();if(e.workspace_registry_revision!==n.registry_revision)_=`revision`;else{let t=Ep(e);!t.run_history.goals.some(e=>e.id===d.id)||t.run_history.goals.some(e=>e.id!==d.id)?_=`scope`:i()&&!o?.aborted&&r(d.id,t,null)}}}catch(e){_=m?`timeout`:e instanceof TypeError?`network`:`invalid`}finally{clearTimeout(g),o?.removeEventListener(`abort`,h)}if(!i()||o?.aborted)return;_&&[`timeout`,`network`,`service`].includes(_)&&f<3?(await new Promise(e=>setTimeout(e,f*1e3)),s.push(d)):_&&r(d.id,null,_)}}await Promise.all([l(),l()])}var Pp=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),Fp=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),Ip=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),Lp=e=>{let t=Ip(e);return t.charAt(0).toUpperCase()+t.slice(1)},Rp={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`},zp=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},Bp=(0,z.createContext)({}),Vp=()=>(0,z.useContext)(Bp),Hp=(0,z.forwardRef)(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>{let{size:l=24,strokeWidth:u=2,absoluteStrokeWidth:d=!1,color:f=`currentColor`,className:p=``}=Vp()??{},m=r??d?Number(n??u)*24/Number(t??l):n??u;return(0,z.createElement)(`svg`,{ref:c,...Rp,width:t??l??Rp.width,height:t??l??Rp.height,stroke:e??f,strokeWidth:m,className:Pp(`lucide`,p,i),...!a&&!zp(s)&&{"aria-hidden":`true`},...s},[...o.map(([e,t])=>(0,z.createElement)(e,t)),...Array.isArray(a)?a:[a]])}),Z=(e,t)=>{let n=(0,z.forwardRef)(({className:n,...r},i)=>(0,z.createElement)(Hp,{ref:i,iconNode:t,className:Pp(`lucide-${Fp(Lp(e))}`,`lucide-${e}`,n),...r}));return n.displayName=Lp(e),n},Up=Z(`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`}]]),Wp=Z(`arrow-down`,[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]),Gp=Z(`arrow-left`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]),Kp=Z(`arrow-right`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]),qp=Z(`arrow-up-down`,[[`path`,{d:`m21 16-4 4-4-4`,key:`f6ql7i`}],[`path`,{d:`M17 20V4`,key:`1ejh1v`}],[`path`,{d:`m3 8 4-4 4 4`,key:`11wl7u`}],[`path`,{d:`M7 4v16`,key:`1glfcx`}]]),Jp=Z(`arrow-up`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),Yp=Z(`badge-check`,[[`path`,{d:`M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z`,key:`3c2336`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),Xp=Z(`bell`,[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}]]),Zp=Z(`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`}]]),Qp=Z(`braces`,[[`path`,{d:`M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1`,key:`ezmyqa`}],[`path`,{d:`M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1`,key:`e1hn23`}]]),$p=Z(`calendar-clock`,[[`path`,{d:`M16 14v2.2l1.6 1`,key:`fo4ql5`}],[`path`,{d:`M16 2v4`,key:`4m81vk`}],[`path`,{d:`M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5`,key:`1osxxc`}],[`path`,{d:`M3 10h5`,key:`r794hk`}],[`path`,{d:`M8 2v4`,key:`1cmpym`}],[`circle`,{cx:`16`,cy:`16`,r:`6`,key:`qoo3c4`}]]),em=Z(`check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),tm=Z(`chevron-down`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),nm=Z(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),rm=Z(`chevron-up`,[[`path`,{d:`m18 15-6-6-6 6`,key:`153udz`}]]),im=Z(`circle-alert`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`12`,x2:`12`,y1:`8`,y2:`12`,key:`1pkeuh`}],[`line`,{x1:`12`,x2:`12.01`,y1:`16`,y2:`16`,key:`4dfq90`}]]),am=Z(`circle-check`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),om=Z(`clipboard-check`,[[`rect`,{width:`8`,height:`4`,x:`8`,y:`2`,rx:`1`,ry:`1`,key:`tgr4d6`}],[`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`,key:`116196`}],[`path`,{d:`m9 14 2 2 4-4`,key:`df797q`}]]),sm=Z(`code-xml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),cm=Z(`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`}]]),lm=Z(`database`,[[`ellipse`,{cx:`12`,cy:`5`,rx:`9`,ry:`3`,key:`msslwz`}],[`path`,{d:`M3 5V19A9 3 0 0 0 21 19V5`,key:`1wlel7`}],[`path`,{d:`M3 12A9 3 0 0 0 21 12`,key:`mv7ke4`}]]),um=Z(`download`,[[`path`,{d:`M12 15V3`,key:`m9g1x1`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`path`,{d:`m7 10 5 5 5-5`,key:`brsn70`}]]),dm=Z(`ellipsis`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]]),fm=Z(`external-link`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),pm=Z(`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`}]]),mm=Z(`file-braces`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1`,key:`1oajmo`}],[`path`,{d:`M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1`,key:`mpwhp6`}]]),hm=Z(`file-check-corner`,[[`path`,{d:`M10.5 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v6`,key:`g5mvt7`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`m14 20 2 2 4-4`,key:`15kota`}]]),gm=Z(`file-text`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),_m=Z(`git-branch`,[[`path`,{d:`M15 6a9 9 0 0 0-9 9V3`,key:`1cii5b`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}]]),vm=Z(`git-compare-arrows`,[[`circle`,{cx:`5`,cy:`6`,r:`3`,key:`1qnov2`}],[`path`,{d:`M12 6h5a2 2 0 0 1 2 2v7`,key:`1yj91y`}],[`path`,{d:`m15 9-3-3 3-3`,key:`1lwv8l`}],[`circle`,{cx:`19`,cy:`18`,r:`3`,key:`1qljk2`}],[`path`,{d:`M12 18H7a2 2 0 0 1-2-2V9`,key:`16sdep`}],[`path`,{d:`m9 15 3 3-3 3`,key:`1m3kbl`}]]),ym=Z(`info`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]),bm=Z(`languages`,[[`path`,{d:`m5 8 6 6`,key:`1wu5hv`}],[`path`,{d:`m4 14 6-6 2-3`,key:`1k1g8d`}],[`path`,{d:`M2 5h12`,key:`or177f`}],[`path`,{d:`M7 2h1`,key:`1t2jsx`}],[`path`,{d:`m22 22-5-10-5 10`,key:`don7ne`}],[`path`,{d:`M14 18h6`,key:`1m8k6r`}]]),xm=Z(`layout-dashboard`,[[`rect`,{width:`7`,height:`9`,x:`3`,y:`3`,rx:`1`,key:`10lvy0`}],[`rect`,{width:`7`,height:`5`,x:`14`,y:`3`,rx:`1`,key:`16une8`}],[`rect`,{width:`7`,height:`9`,x:`14`,y:`12`,rx:`1`,key:`1hutg5`}],[`rect`,{width:`7`,height:`5`,x:`3`,y:`16`,rx:`1`,key:`ldoo1y`}]]),Sm=Z(`list-plus`,[[`path`,{d:`M16 5H3`,key:`m91uny`}],[`path`,{d:`M11 12H3`,key:`51ecnj`}],[`path`,{d:`M16 19H3`,key:`zzsher`}],[`path`,{d:`M18 9v6`,key:`1twb98`}],[`path`,{d:`M21 12h-6`,key:`bt1uis`}]]),Cm=Z(`loader-circle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),wm=Z(`maximize-2`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`m21 3-7 7`,key:`1l2asr`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M9 21H3v-6`,key:`wtvkvv`}]]),Tm=Z(`menu`,[[`path`,{d:`M4 5h16`,key:`1tepv9`}],[`path`,{d:`M4 12h16`,key:`1lakjw`}],[`path`,{d:`M4 19h16`,key:`1djgab`}]]),Em=Z(`message-circle-question-mark`,[[`path`,{d:`M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719`,key:`1sd12s`}],[`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`,key:`1u773s`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),Dm=Z(`message-square-text`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}],[`path`,{d:`M7 11h10`,key:`1twpyw`}],[`path`,{d:`M7 15h6`,key:`d9of3u`}],[`path`,{d:`M7 7h8`,key:`af5zfr`}]]),Om=Z(`minimize-2`,[[`path`,{d:`m14 10 7-7`,key:`oa77jy`}],[`path`,{d:`M20 10h-6V4`,key:`mjg0md`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M4 14h6v6`,key:`rmj7iw`}]]),km=Z(`moon`,[[`path`,{d:`M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401`,key:`kfwtm`}]]),Am=Z(`palette`,[[`path`,{d:`M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z`,key:`e79jfc`}],[`circle`,{cx:`13.5`,cy:`6.5`,r:`.5`,fill:`currentColor`,key:`1okk4w`}],[`circle`,{cx:`17.5`,cy:`10.5`,r:`.5`,fill:`currentColor`,key:`f64h9f`}],[`circle`,{cx:`6.5`,cy:`12.5`,r:`.5`,fill:`currentColor`,key:`qy21gx`}],[`circle`,{cx:`8.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`fotxhn`}]]),jm=Z(`paperclip`,[[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551`,key:`1miecu`}]]),Mm=Z(`pause`,[[`rect`,{x:`14`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`kaeet6`}],[`rect`,{x:`5`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`1wsw3u`}]]),Nm=Z(`play`,[[`path`,{d:`M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z`,key:`10ikf1`}]]),Pm=Z(`plus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]),Fm=Z(`radio`,[[`path`,{d:`M16.247 7.761a6 6 0 0 1 0 8.478`,key:`1fwjs5`}],[`path`,{d:`M19.075 4.933a10 10 0 0 1 0 14.134`,key:`ehdyv1`}],[`path`,{d:`M4.925 19.067a10 10 0 0 1 0-14.134`,key:`1q22gi`}],[`path`,{d:`M7.753 16.239a6 6 0 0 1 0-8.478`,key:`r2q7qm`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}]]),Im=Z(`refresh-cw`,[[`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,key:`v9h5vc`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}],[`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,key:`3uifl3`}],[`path`,{d:`M8 16H3v5`,key:`1cv678`}]]),Lm=Z(`rotate-ccw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),Rm=Z(`rotate-cw`,[[`path`,{d:`M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8`,key:`1p45f6`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}]]),zm=Z(`search`,[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]),Bm=Z(`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`}]]),Vm=Z(`server-cog`,[[`path`,{d:`m10.852 14.772-.383.923`,key:`11vil6`}],[`path`,{d:`M13.148 14.772a3 3 0 1 0-2.296-5.544l-.383-.923`,key:`1v3clb`}],[`path`,{d:`m13.148 9.228.383-.923`,key:`t2zzyc`}],[`path`,{d:`m13.53 15.696-.382-.924a3 3 0 1 1-2.296-5.544`,key:`1bxfiv`}],[`path`,{d:`m14.772 10.852.923-.383`,key:`k9m8cz`}],[`path`,{d:`m14.772 13.148.923.383`,key:`1xvhww`}],[`path`,{d:`M4.5 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-.5`,key:`tn8das`}],[`path`,{d:`M4.5 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-.5`,key:`1g2pve`}],[`path`,{d:`M6 18h.01`,key:`uhywen`}],[`path`,{d:`M6 6h.01`,key:`1utrut`}],[`path`,{d:`m9.228 10.852-.923-.383`,key:`1wtb30`}],[`path`,{d:`m9.228 13.148-.923.383`,key:`1a830x`}]]),Hm=Z(`server`,[[`rect`,{width:`20`,height:`8`,x:`2`,y:`2`,rx:`2`,ry:`2`,key:`ngkwjq`}],[`rect`,{width:`20`,height:`8`,x:`2`,y:`14`,rx:`2`,ry:`2`,key:`iecqi9`}],[`line`,{x1:`6`,x2:`6.01`,y1:`6`,y2:`6`,key:`16zg32`}],[`line`,{x1:`6`,x2:`6.01`,y1:`18`,y2:`18`,key:`nzw8ys`}]]),Um=Z(`settings-2`,[[`path`,{d:`M14 17H5`,key:`gfn3mx`}],[`path`,{d:`M19 7h-9`,key:`6i9tg`}],[`circle`,{cx:`17`,cy:`17`,r:`3`,key:`18b49y`}],[`circle`,{cx:`7`,cy:`7`,r:`3`,key:`dfmy0x`}]]),Wm=Z(`shield-check`,[[`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`}]]),Gm=Z(`sliders-horizontal`,[[`path`,{d:`M10 5H3`,key:`1qgfaw`}],[`path`,{d:`M12 19H3`,key:`yhmn1j`}],[`path`,{d:`M14 3v4`,key:`1sua03`}],[`path`,{d:`M16 17v4`,key:`1q0r14`}],[`path`,{d:`M21 12h-9`,key:`1o4lsq`}],[`path`,{d:`M21 19h-5`,key:`1rlt1p`}],[`path`,{d:`M21 5h-7`,key:`1oszz2`}],[`path`,{d:`M8 10v4`,key:`tgpxqk`}],[`path`,{d:`M8 12H3`,key:`a7s4jb`}]]),Km=Z(`sparkles`,[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]]),qm=Z(`square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),Jm=Z(`sun`,[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]),Ym=Z(`test-tube-diagonal`,[[`path`,{d:`M21 7 6.82 21.18a2.83 2.83 0 0 1-3.99-.01a2.83 2.83 0 0 1 0-4L17 3`,key:`1ub6xw`}],[`path`,{d:`m16 2 6 6`,key:`1gw87d`}],[`path`,{d:`M12 16H4`,key:`1cjfip`}]]),Xm=Z(`trash-2`,[[`path`,{d:`M10 11v6`,key:`nco0om`}],[`path`,{d:`M14 11v6`,key:`outv1u`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`,key:`miytrc`}],[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`,key:`e791ji`}]]),Zm=Z(`triangle-alert`,[[`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`}]]),Qm=Z(`unlink`,[[`path`,{d:`m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71`,key:`yqzxt4`}],[`path`,{d:`m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71`,key:`4qinb0`}],[`line`,{x1:`8`,x2:`8`,y1:`2`,y2:`5`,key:`1041cp`}],[`line`,{x1:`2`,x2:`5`,y1:`8`,y2:`8`,key:`14m1p5`}],[`line`,{x1:`16`,x2:`16`,y1:`19`,y2:`22`,key:`rzdirn`}],[`line`,{x1:`19`,x2:`22`,y1:`16`,y2:`16`,key:`ox905f`}]]),$m=Z(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]);function eh(e){return/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(e)||e.startsWith(`//`)}function th(e){return[`localhost`,`127.0.0.1`,`::1`,`[::1]`].includes(e)}function nh(e,t,n){let r=e.trim();if(!r)return{error:`status URL is empty`};let i;try{i=new URL(r,t)}catch{return{error:`status URL is invalid`}}let a=!eh(r),o=th(i.hostname);return!a&&!o?{error:`${n} must be relative or loopback`}:{source:{isLoopback:o,isRelative:a,url:r}}}function rh(e,t){return nh(e,t,`statusUrl`)}function ih(e,t){let n=nh(e,t,`Ops statusUrl`);return n.error?{error:`${n.error}; use showcase mode for public links.`}:n}function ah(e,t,n){let r=new URL(e,n);return r.searchParams.set(`goal_activation`,t),r.toString()}function oh(e,t){if(!t||!e.isLoopback)return null;try{let n=new URL(e.url,window.location.href),r=new URL(t,n.origin);return th(r.hostname)?r.toString():null}catch{return null}}function sh(e,t){return{detailUrl:oh(t,e.local_dashboard_api?.periodic_report_detail_url),indexUrl:oh(t,e.local_dashboard_api?.periodic_report_index_url)}}async function ch(e,t){let n=new URL(e);n.searchParams.set(`goal_id`,t),n.searchParams.set(`limit`,`100`),n.searchParams.set(`offset`,`0`);let r=await fetch(n,{cache:`no-store`});if(!r.ok)throw Error(`HTTP ${r.status} while loading published reports`);return bp.parse(await r.json()).periodic_reports}async function lh(e,t){let n=new URL(e);Object.entries(t).forEach(([e,t])=>n.searchParams.set(e,t));let r=await fetch(n,{cache:`no-store`});if(!r.ok)throw Error(`HTTP ${r.status} while loading published report detail`);return Sp.parse(await r.json()).projection}function uh(e,t,n){let r=e.find(e=>e.agentId===t&&e.available)??e.find(e=>e.agentId===n&&e.available)??e.find(e=>e.available);if(!r)throw Error(`Chat requires at least one available route`);return r}function dh(e){return!!(e&&typeof e==`object`&&e.session_invalidated===!0)}var fh=``.replace(/\/+$/,``);function ph(e){return!fh||/^https?:\/\//.test(e)?e:new URL(e,`${fh}/`).toString()}var mh=J({todo_id:W().nullable(),role:W().nullable(),status:W(),priority:W().nullable(),text:W(),action_kind:W().nullable(),task_class:W().nullable(),claimed_by:W().nullable(),evidence:W().nullable()}),hh=J({goal_id:W(),title:W(),objective:W(),status:W(),waiting_on:W().nullable(),severity:W().nullable(),gate:W(),next_action:W(),top_todo:mh.nullable(),todos:q(mh),evidence:q(W()),quota:J({state:W().nullable(),spent_slots:G().nullable(),allowed_slots:G().nullable(),reason:W().nullable()})});J({ok:K(),schema_version:X(`loopx_chat_status_v0`),selected_goal_id:W().nullable(),goal_count:G(),goals:q(hh)});var gh=J({ok:X(!0),schema_version:Y([`loopx_chat_capabilities_v0`,`loopx_chat_capabilities_v1`]),agent_backend:W(),sandbox:W(),approval_policy:W(),todo_write:W(),goal_subagent_configuration:W().optional(),goal_id:W().nullable(),streaming:K().optional(),resume:K().optional(),interrupt:K().optional(),typed_actions:K().optional(),action_kinds:q(W()).optional(),adapters:q(J({agent_id:W(),display_name:W(),adapter_kind:W(),available:K(),streaming:K(),resume:K(),interrupt:K(),location:W().optional(),source:W().optional(),tool_calls:K().optional(),trust_scope:W().optional()})).optional(),lark_cli:J({available:K(),source:W(),version:W().nullable(),error_code:W().nullable()}).optional()}),_h=J({kind:X(`todo`),text:W(),priority:Y([`P0`,`P1`,`P2`]),rationale:W()}),vh=J({operation:Y([`merge`,`release`,`deploy`,`delete`,`payment`]),target:W().min(1).max(160),summary:W().max(300)}),yh=J({schema_version:X(`loopx_chat_agent_response_v0`),message:W(),proposals:q(_h),protected_action:vh.nullable().optional().default(null),gate:J({kind:W(),summary:W(),next_action:W()}).nullable()}),bh=J({closed:X(!0),ok:X(!0),session_id:W().min(1)});J({dry_run:X(!0),ok:X(!0),preview_id:W().min(1),todo:J({goal_id:W().min(1),text:W(),todo_id:W().optional()})});var xh=J({schema_version:X(`loopx_chat_todo_receipt_v0`),receipt_id:W().min(1),preview_id:W().min(1),goal_id:W().min(1),todo_id:W().min(1),status:X(`applied`),outcome:Y([`todo_added`,`todo_already_exists`]),already_exists:K(),preview_revision:W().nullable()});J({applied:X(!0),ok:X(!0),receipt:xh,todo:J({text:W(),todo_id:W()})});var Sh=J({model_config:J({model:W(),reasoning_effort:W().optional()}).optional(),mode:W(),spawn_allowed:K(),max_children:G().int().nonnegative(),allowed_domains:q(W()).optional().default([])}).passthrough(),Ch=J({ok:X(!0),dry_run:K(),execute:K(),written:K(),changed:K(),goal_id:W().min(1),changed_fields:q(W()),before:J({orchestration:Sh}).passthrough(),after:J({orchestration:Sh}).passthrough(),preview_id:W().min(1),feature_summary:J({multi_subagent:Y([`off`,`enabled`])}).passthrough(),global_sync:J({required:K(),executed:K(),readback:J({status:W(),verified:K()}).passthrough()}).passthrough()}),wh=J({id:W().min(1),outcome:Y([`approved`,`rejected`,`cancelled`]),projectionVerified:K().nullable(),proposal:_h,receipt:xh.nullable()}).superRefine((e,t)=>{e.outcome===`approved`&&!e.receipt&&t.addIssue({code:`custom`,message:`approved decision history requires a Todo receipt`,path:[`receipt`]}),e.outcome!==`approved`&&e.receipt&&t.addIssue({code:`custom`,message:`zero-write decision history must not include a Todo receipt`,path:[`receipt`]})});J({schema_version:X(`loopx_chat_decision_history_v0`),goal_id:W().min(1),decisions:q(wh).max(24)});var Th=class extends Error{payload;constructor(e,t){super(e),this.payload=t}},Eh=Y([`goal.create`,`goal.update`,`goal.lifecycle`,`todo.create`,`todo.update`,`agent.bind`,`heartbeat.bind`,`monitor.create`,`monitor.update`,`gate.resolve`,`run.correct`,`operation.execute`]),Dh=J({schema_version:X(`loopx_operation_envelope_v0`),lifecycle_state:Y([`prepared`,`awaiting_confirmation`,`claimed`,`outcome_observed`]),operation_id:W().min(1),confirmation_digest:W().min(1),payload_digest:W().min(1),projection_digest:W().min(1),expires_at:W().min(1),delivery:gd(W(),id()).nullable(),confirmation:gd(W(),id()).nullable(),claim:gd(W(),id()).nullable(),outcome:gd(W(),id()).nullable()}).passthrough(),Oh=J({schema_version:X(`loopx_chat_action_proposal_v1`),proposal_id:W().min(1),action_kind:Eh,summary:W().min(1),normalized_parameters:gd(W(),id()),context:gd(W(),id()),expected_state_fingerprint:W().min(1),permission_classification:W().min(1),validation_evidence:q(W().refine(e=>e.trim().length>0,`Validation evidence must be non-blank text`)),available_transitions:q(Y([`apply`,`cancel`,`regenerate`,`reject`,`defer`])),status:Y([`preview_ready`,`applying`,`gated`,`failed`,`rejected`,`deferred`,`cancelled`,`stale`,`applied`]),receipt:gd(W(),id()).nullable(),stale:gd(W(),id()).nullable(),gate:gd(W(),id()).nullable().optional(),error:gd(W(),id()).nullable().optional(),checkpoint:gd(W(),id()).nullable().optional(),regenerated_from:W().nullable().optional(),operation:Dh.nullable().optional(),created_at:W(),updated_at:W()}),kh=J({ok:X(!0),proposal:Oh});async function Ah(e){let t=await Ih(`/api/actions/preview`,{method:`POST`,body:JSON.stringify({action_kind:e.actionKind,context:e.context,idempotency_key:e.idempotencyKey,normalized_parameters:e.normalizedParameters,summary:e.summary})});return kh.parse(t).proposal}var jh=J({ok:X(!0),schema_version:X(`loopx_chat_action_list_v1`),proposals:q(Oh)});async function Mh(e={}){let t=new URLSearchParams;e.contextKind&&t.set(`context_kind`,e.contextKind),e.goalId&&t.set(`goal_id`,e.goalId);let n=t.size>0?`?${t.toString()}`:``;return jh.parse(await Ih(`/api/actions${n}`)).proposals}async function Nh(e){let t=await Ih(`/api/actions/${encodeURIComponent(e)}/apply`,{method:`POST`,body:`{}`});return J({ok:X(!0),proposal:Oh,turn:gd(W(),id()).nullable().optional()}).parse(t)}async function Ph(e){return kh.parse(await Ih(`/api/actions/${encodeURIComponent(e)}/cancel`,{method:`POST`,body:`{}`})).proposal}async function Fh(e,t){return kh.parse(await Ih(`/api/actions/${encodeURIComponent(e)}/${t}`,{method:`POST`,body:`{}`})).proposal}async function Ih(e,t){let n;try{n=await fetch(ph(e),{cache:`no-store`,...t,headers:{"Content-Type":`application/json`,...t?.headers}})}catch{throw new Th(`无法连接 LoopX Chat 服务。请确认 Dashboard 与 Chat 服务已启动且来自同一版本。`,{error_code:`chat_api_unavailable`})}let r=await n.text(),i=null;if(r.trim())try{i=JSON.parse(r)}catch{i=null}let a=i&&typeof i==`object`&&!Array.isArray(i)?i:{};if(!n.ok){let e=(a.proposal&&typeof a.proposal==`object`?a.proposal:null)?.status===`stale`?`来源状态已变化,请重新生成预览。`:null,t=n.status>=500?`LoopX Chat 服务暂时不可用(HTTP ${n.status})。请确认 Dashboard 与 Chat 服务已启动且来自同一版本。`:`LoopX Chat 请求失败(HTTP ${n.status})。`;throw new Th(e??String(a.error||t),Object.keys(a).length?a:{error_code:`chat_api_unavailable`,http_status:n.status})}if(i===null)throw new Th(`LoopX Chat 服务返回了无法识别的响应(HTTP ${n.status})。请确认 Dashboard 与 Chat 服务来自同一版本。`,{error_code:`invalid_chat_api_response`,http_status:n.status});return i}async function Lh(){return gh.parse(await Ih(`/api/chat/capabilities`))}async function Rh(e){return Ih(`/api/chat/projection-messages`,{method:`POST`,body:JSON.stringify({answer:e.answer,context_kind:e.contextKind,goal_id:e.goalId,question:e.question})})}async function zh(e,t=`codex`,n=`resume_latest`,r=`goal`){return Ih(`/api/chat/sessions`,{method:`POST`,body:JSON.stringify({goal_id:e,agent_id:t,mode:n,context_kind:r})})}async function Bh(e){return Ih(`/api/chat/sessions/${e}`)}async function Vh(e){let t=new URLSearchParams;return e.agentId&&t.set(`agent_id`,e.agentId),e.channelId&&t.set(`channel_id`,e.channelId),e.goalId&&t.set(`goal_id`,e.goalId),Ih(`/api/chat/sessions?${t.toString()}`)}function Hh(e){let t=new Map;for(let n of e)for(let e of n.messages)t.set(e.message_id,e);return[...t.values()].sort((e,t)=>e.created_at.localeCompare(t.created_at)||e.message_id.localeCompare(t.message_id))}async function Uh(e){let t=await Vh(e),n=await Promise.all(t.sessions.map(e=>Bh(e.session_id)));return{messages:Hh(n),sessions:t.sessions,snapshots:n}}async function Wh(e,t,n,r=[]){return Ih(`/api/chat/sessions/${e}/turns`,{method:`POST`,body:JSON.stringify({message:t,client_turn_id:n,...r.length?{attachments:r.map(e=>({data_url:e.dataUrl,id:e.id,mime_type:e.mimeType,name:e.name,size:e.size}))}:{}})})}function Gh(e){let t=e.split(` +`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(` +`);if(!t)return null;try{let e=JSON.parse(t);return!e.kind||!e.payload||typeof e.payload!=`object`?null:{event_id:String(e.event_id??``),sequence:Number(e.sequence??0),kind:String(e.kind),created_at:String(e.created_at??``),payload:e.payload}}catch{return null}}async function Kh(e,t,n){let r=``,i=0,a=!1;for(;!a&&i<4;){let o=typeof window>`u`?`http://127.0.0.1`:window.location.origin,s=new URL(ph(e),o);r&&s.searchParams.set(`after`,r);try{let e=await fetch(s,{cache:`no-store`,headers:{Accept:`text/event-stream`},signal:n});if(!e.ok||!e.body)throw new Th(`SSE HTTP ${e.status}`,{status:e.status});let o=e.body.getReader(),c=new TextDecoder,l=``;for(;;){let{done:e,value:n}=await o.read();l+=c.decode(n,{stream:!e}).replaceAll(`\r +`,` +`);let i=l.indexOf(` + +`);for(;i>=0;){let e=l.slice(0,i);l=l.slice(i+2);let n=Gh(e);n&&(n.event_id&&(r=n.event_id),t(n),a=[`turn.completed`,`turn.interrupted`,`turn.failed`].includes(n.kind)),i=l.indexOf(` + +`)}if(e||a)break}i=a?i:i+1}catch(e){if(n?.aborted||(i+=1,i>=4))throw e;await new Promise(e=>globalThis.setTimeout(e,250*2**(i-1)))}}if(!a)throw new Th(`Agent 事件流连接已断开。`,{reconnect_attempts:i})}async function qh(e,t){return Ih(`/api/chat/sessions/${e}/turns/${t}/interrupt`,{method:`POST`,body:`{}`})}async function Jh(e,t,n={}){let r=await Wh(e,t,n.clientTurnId??crypto.randomUUID(),n.attachments);return n.onPhase?.(`turn.accepted`,r.turn_id),Yh(e,r.turn_id,r.events_url,n)}async function Yh(e,t,n,r={}){let i=null,a={failure:null,interrupted:null};try{await Kh(n,e=>{r.onPhase?.(e.kind,t),(e.kind===`answer.delta`||e.kind===`assistant.delta`)&&r.onDelta?.(String(e.payload.text??``)),e.kind===`agent.phase`&&r.onActivity?.(String(e.payload.label??`Agent 正在处理`)),e.kind===`turn.completed`&&(i=e.payload.response),e.kind===`turn.failed`&&(a.failure=e.payload),e.kind===`turn.interrupted`&&(a.interrupted=e.payload)},r.signal)}catch(i){throw i instanceof Th&&!r.signal?.aborted?new Th(i.message,{...i.payload,events_url:n,reconnectable:!0,session_id:e,turn_id:t}):i}if(a.failure)throw new Th(String(a.failure.message||`Agent 回合失败。`),a.failure);if(a.interrupted)throw new Th(`Agent 回合已中断。`,{...a.interrupted,error_code:`turn_interrupted`,session_id:e,turn_id:t});return{response:yh.parse(i),sessionId:e,turnId:t}}async function Xh(e,t,n={}){return Yh(e,t,`/api/chat/sessions/${e}/turns/${t}/events`,n)}async function Zh(e){let t=bh.parse(await Ih(`/api/chat/sessions/${e}`,{keepalive:!0,method:`DELETE`}));if(t.session_id!==e)throw new Th(`Agent 会话关闭回执与本次请求不一致。`,{session_id:t.session_id});return t}async function Qh(e){return Ih(`/api/chat/sessions/${e}/resume`,{method:`POST`,body:`{}`})}function $h(e){return{goal_id:e.goalId,enabled:e.enabled,...e.modelConfig===void 0?{}:{model_config:e.modelConfig},...e.enabled?{max_children:e.maxChildren,allowed_domains:e.allowedDomains}:{}}}function eg(e,t){let n=e.after.orchestration,r=[...new Set(t.allowedDomains)],i=e.feature_summary.multi_subagent===`enabled`;if(!(e.goal_id===t.goalId&&i===t.enabled&&(t.modelConfig===void 0||JSON.stringify(n.model_config??null)===JSON.stringify(t.modelConfig))&&(t.enabled?n.max_children===t.maxChildren&&JSON.stringify(n.allowed_domains)===JSON.stringify(r):n.spawn_allowed===!1&&n.max_children===0)))throw new Th(`Goal 子代理配置回执与本次请求不一致,界面已停止更新。`,{after:e.after,goal_id:e.goal_id});return e}async function tg(e){let t=Ch.parse(await Ih(`/api/chat/goal-subagents/dry-run`,{method:`POST`,body:JSON.stringify($h(e))}));if(!t.dry_run||t.execute||t.written)throw new Th(`Goal 子代理预览返回了非预览回执,已停止进入确认状态。`,{result:t});return eg(t,e)}async function ng(e,t){let n=Ch.parse(await Ih(`/api/chat/goal-subagents/apply`,{method:`POST`,body:JSON.stringify({...$h(e),preview_id:t})}));if(n.preview_id!==t||n.dry_run||!n.execute)throw new Th(`Goal 子代理写入回执与本次确认不一致,界面已停止更新。`,{result:n});if(n.changed&&(!n.written||!n.global_sync.executed||!n.global_sync.readback.verified))throw new Th(`Goal 子代理设置未通过共享状态读回验证。`,{result:n});return eg(n,e)}var rg=J({ok:X(!0),targets:q(J({enabled:K(),provider:W(),target_name:W()}))});async function ig(){return rg.parse(await Ih(`/api/chat/goal-channel/targets`)).targets}var ag=J({ok:K(),blocker:W().optional(),public_summary:W().optional(),status:W().optional()});async function og(e){return ag.parse(await Ih(`/api/chat/goal-channel/setup`,{method:`POST`,body:JSON.stringify({execute:e.execute,goal_id:e.goalId,target:e.target})}))}async function sg(e){return ag.parse(await Ih(`/api/chat/goal-channel/configure`,{method:`POST`,body:JSON.stringify({auto_notify_human_gates:e.autoNotify,goal_id:e.goalId})}))}var cg=J({schema_version:X(`periodic_report_schedule_v0`),schedule_id:W(),rrule:W(),timezone:W()});J({schema_version:X(`periodic_report_machine_defaults_v0`),enabled:K(),inheritance:X(`live_machine_default`),profile_preset:W().optional(),route_ref:W().optional(),timezone:W(),schedule:cg.nullable().optional()});var lg=J({schema_version:X(`loopx_machine_configuration_v0`),namespaces:gd(W(),gd(W(),id()))}),ug=J({namespace:W(),title:W(),description:W(),schema_versions:q(W()).min(1),configuration_template:gd(W(),id()),template_status:Y([`ready`,`schema_only`])}),dg=J({schema_version:X(`machine_configuration_catalog_v0`),namespaces:q(ug)}),fg=J({key:W(),label:W(),description:W(),input_kind:Y([`boolean`,`number`,`select`,`string_list`,`text`,`periodic_report_schedule`]),nullable:K().optional(),required:K(),minimum:G().int().optional(),maximum:G().int().optional(),options:q(W()).optional()}),pg=J({schema_version:X(`capability_configuration_editor_v0`),editable:K(),supported_scopes:q(Y([`goal`,`machine`])),writable_scopes:q(Y([`goal`,`machine`])),fields:q(fg),read_only_reason:W().optional()}),mg=J({schema_version:X(`capability_configuration_catalog_v0`),capabilities:q(J({capability_id:W(),display_name:W(),description:W(),available_scopes:q(Y([`goal`,`machine`])),machine_namespace:W().optional(),goal_feature_id:W().optional(),effective_value_policy:X(`goal_override_over_live_machine_default`).optional(),availability:W().optional(),default:gd(W(),id()).optional(),current:gd(W(),id()).optional(),machine_current:gd(W(),id()).optional(),effective_configuration:J({schema_version:X(`capability_configuration_resolution_v0`),capability_id:W(),source:Y([`goal_override`,`machine_default`,`capability_default`,`not_configured`]),configuration:gd(W(),id()).nullable(),inherited:K(),goal_override_present:K(),machine_default_present:K(),effective_revision:W()}).optional(),documentation:gd(W(),id()).optional(),context_contribution:J({supported_phases:q(Y([`before_plan`,`before_delegate`,`after_delegate_result`])),target:X(`coordinator`),activation:X(`with_capability`),receipt_required:X(!0)}).optional(),configuration_editor:pg}))}),hg=J({ok:X(!0),schema_version:X(`goal_configuration_inspection_v0`),status:X(`configured`),goal_id:W(),revision:W(),available_capabilities:q(W()),capability_catalog:mg}),gg=J({ok:X(!0),goal_id:W(),capability_id:W(),changed_fields:q(W()),goal_configuration:gd(W(),id()).nullable(),capability_catalog:mg}),_g=gg.extend({schema_version:X(`goal_configuration_update_plan_v0`),status:X(`preview`),action:Y([`create`,`update`,`delete`,`unchanged`]),current_revision:W(),desired_revision:W(),base_revision:W(),plan_revision:W(),writes_required:G().int().nonnegative()}),vg=ud([gg.extend({schema_version:X(`goal_configuration_transaction_v0`),status:Y([`applied`,`unchanged`]),plan_revision:W(),applied_revision:W(),readback_verified:X(!0)}),J({ok:X(!1),schema_version:X(`goal_configuration_transaction_v0`),status:X(`partial_write`),goal_id:W(),capability_id:W(),plan_revision:W(),applied_revision:W().nullable(),source_written:X(!0),shared_sync_pending:X(!0),readback_verified:K(),changed_fields:q(W()),goal_configuration:gd(W(),id()).nullable(),capability_catalog:mg,error:W(),recommended_action:W()})]),yg=J({ok:X(!0),available_namespaces:q(W()),namespace_catalog:dg.optional().default({schema_version:`machine_configuration_catalog_v0`,namespaces:[]}),capability_catalog:mg,changed_namespaces:q(W()).optional().default([]),machine_configuration:lg.nullable().optional()}),bg=yg.extend({schema_version:X(`machine_configuration_inspection_v0`),status:Y([`configured`,`absent`]),revision:W()}),xg=yg.extend({schema_version:X(`machine_configuration_update_plan_v0`),status:X(`preview`),action:Y([`create`,`update`,`delete`,`unchanged`]),current_revision:W(),desired_revision:W(),plan_revision:W(),writes_required:G().int().nonnegative(),machine_configuration:lg.nullable()}),Sg=yg.extend({schema_version:X(`machine_configuration_transaction_v0`),status:Y([`applied`,`unchanged`]),plan_revision:W(),transaction_id:W().nullable(),readback_verified:X(!0),rollback_available:K(),applied_revision:W().optional(),prior_revision:W().optional()}),Cg=yg.extend({schema_version:X(`machine_configuration_rollback_plan_v0`),status:X(`preview`),action:Y([`delete`,`restore`,`unchanged`,`blocked`]),reason:W(),transaction_id:W(),plan_revision:W(),rollback_allowed:K(),writes_required:G().int().nonnegative()}),wg=yg.extend({schema_version:X(`machine_configuration_rollback_receipt_v0`),status:Y([`rolled_back`,`unchanged`]),transaction_id:W(),plan_revision:W(),rollback_id:W().nullable(),readback_verified:X(!0)});async function Tg(){return bg.parse(await Ih(`/api/chat/machine-configuration`))}async function Eg(e){let t=new URLSearchParams({goal_id:e});return hg.parse(await Ih(`/api/chat/goal-configuration?${t.toString()}`))}async function Dg(e,t,n){return _g.parse(await Ih(`/api/chat/goal-configuration/preview`,{method:`POST`,body:JSON.stringify({goal_id:e,capability_id:t,configuration:n})}))}async function Og(e,t,n,r){return vg.parse(await Ih(`/api/chat/goal-configuration/apply`,{method:`POST`,body:JSON.stringify({goal_id:e,capability_id:t,configuration:n,expected_plan_revision:r})}))}async function kg(e,t){return xg.parse(await Ih(`/api/chat/machine-configuration/preview`,{method:`POST`,body:JSON.stringify({namespace:e,namespace_configuration:t})}))}async function Ag(e,t,n){return Sg.parse(await Ih(`/api/chat/machine-configuration/apply`,{method:`POST`,body:JSON.stringify({expected_plan_revision:n,namespace:e,namespace_configuration:t})}))}async function jg(e){return xg.parse(await Ih(`/api/chat/machine-configuration/preview`,{method:`POST`,body:JSON.stringify({namespace:e,operation:`remove`})}))}async function Mg(e,t){return Sg.parse(await Ih(`/api/chat/machine-configuration/apply`,{method:`POST`,body:JSON.stringify({expected_plan_revision:t,namespace:e,operation:`remove`})}))}async function Ng(e){return Cg.parse(await Ih(`/api/chat/machine-configuration/rollback`,{method:`POST`,body:JSON.stringify({execute:!1,transaction_id:e})}))}async function Pg(e,t){return wg.parse(await Ih(`/api/chat/machine-configuration/rollback`,{method:`POST`,body:JSON.stringify({execute:!0,expected_plan_revision:t,transaction_id:e})}))}var Fg=J({ok:X(!0),goals:q(J({goal_id:W(),repository:J({branch:W(),identity:W(),label:W(),read_only:X(!0)})}))});async function Ig(){return Fg.parse(await Ih(`/api/chat/goals/contexts`)).goals}var Lg=J({ok:X(!0),apps:q(J({active:K(),app_ref:W(),brand:W(),health_error_code:W().nullable().default(null),label:W(),ready:K(),reply_ready:K().default(!1)}))});async function Rg(){return Lg.parse(await Ih(`/api/chat/lark/apps`)).apps}var zg=J({ok:X(!0),app_ref:W(),error:W().nullable(),setup_id:W(),status:Y([`starting`,`waiting_for_feishu`,`ready`,`failed`,`cancelled`]),verification_url:W().url().nullable()});async function Bg(e){return zg.parse(await Ih(`/api/chat/lark/app-setups`,{method:`POST`,body:JSON.stringify({app_ref:e.appRef,brand:e.brand})}))}async function Vg(e){return zg.parse(await Ih(`/api/chat/lark/app-setups/${encodeURIComponent(e)}`))}async function Hg(e){return zg.parse(await Ih(`/api/chat/lark/app-setups/${encodeURIComponent(e)}`,{method:`DELETE`}))}var Ug=[`invalid_event`,`binding_unavailable`,`chat_mismatch`,`topic_mismatch`,`route_ambiguous`,`self_message`,`invalid_routing_state`,`not_addressed`],Wg=J({ok:X(!0),chats:q(J({chat_id:W(),chat_name:W()}))});async function Gg(e,t){let n=new URLSearchParams({app_ref:e});return t&&n.set(`query`,t),Wg.parse(await Ih(`/api/chat/lark/chats?${n.toString()}`)).chats}var Kg=J({ok:X(!0),connections:q(J({conversation_kind:Y([`goal`,`manager`]).default(`goal`),agent_id:W().nullable().default(null),connection_id:W(),app_label:W(),app_ref:W(),capture_scope:Y([`addressed_only`,`configured_chat_all`]).default(`addressed_only`),chat_name:W(),enabled:K(),goal_id:W(),goal_title:W(),health_error_code:W().nullable().default(null),history_permission_guidance:J({action:X(`enable_application_scopes_and_publish`),api_document_url:W().url(),capability:X(`group_history_pagination`),identity:X(`bot`),required_scopes:md([X(`im:message.group_msg`),X(`im:message.group_msg.include_bot:read`)]),schema_version:X(`lark_bot_group_history_permission_guidance_v0`)}).nullable().default(null),incoming_mode:Y([`mentions`,`all`]),ingress_mode:Y([`live_steering`,`session_queue`,`async_inbox`,`direct_session`]).default(`async_inbox`),event_count:G().int().nonnegative().default(0),last_event_reason:Y(Ug).nullable().default(null).catch(null),last_event_status:W().nullable().default(null),listener_error_code:W().nullable().default(null),listener_status:Y([`starting`,`listening`,`retrying`,`stopped`]).nullable().default(null),replied_count:G().int().nonnegative().default(0),reply_ready:K().default(!1),reply_mode:X(`topic_reply`),session_bound:K().default(!1),target_ref:W(),topic_name:W(),topic_setup_required:K()}))});async function qg(){return Kg.parse(await Ih(`/api/chat/lark/connections`)).connections}async function Jg(e){return ag.parse(await Ih(`/api/chat/lark/connections`,{method:`POST`,body:JSON.stringify({...e.agentBindings?{agent_bindings:e.agentBindings.map(e=>({agent_id:e.agentId,app_ref:e.appRef}))}:{},...e.agentId?{agent_id:e.agentId}:{},...e.appRef?{app_ref:e.appRef}:{},...e.connectionId?{connection_id:e.connectionId}:{},conversation_kind:e.conversationKind??`goal`,capture_scope:e.captureScope,chat_id:e.chatId,chat_name:e.chatName,execute:e.execute,goal_id:e.goalId,incoming_mode:e.incomingMode,ingress_mode:e.ingressMode,reply_mode:e.replyMode})}))}async function Yg(e,t){let n=new URLSearchParams({goal_id:e,connection_id:t});return ag.parse(await Ih(`/api/chat/lark/connections?${n.toString()}`,{method:`DELETE`}))}function Xg(e){return{loadedUrl:null,projectionRevision:0,requestedUrl:e,selectionRevision:0,requestGeneration:0}}function Zg(e,t){return e.selectionRevision+=1,e.requestedUrl=t,e.selectionRevision}function Qg(e,t,n){if(n.background)return e.requestedUrl!==null||e.loadedUrl!==t?null:(e.requestGeneration+=1,{background:!0,projectionRevision:e.projectionRevision,selectionRevision:e.selectionRevision,url:t,generation:e.requestGeneration});let r=n.selectionRevision??e.selectionRevision+1;return n.selectionRevision!==void 0&&e.selectionRevision!==r?null:(e.selectionRevision=r,e.projectionRevision+=1,e.requestedUrl=t,e.requestGeneration+=1,{background:!1,projectionRevision:e.projectionRevision,selectionRevision:r,url:t,generation:e.requestGeneration})}function $g(e,t){return t.generation===e.requestGeneration&&e.projectionRevision===t.projectionRevision&&e.selectionRevision===t.selectionRevision}function e_(e,t){return $g(e,t)&&(!t.background||e.requestedUrl===null&&e.loadedUrl===t.url)}function t_(e,t,n){return t.get(e)===n}function n_(e,t,n,r){return e.filter(e=>t_(r(e),n,t))}function r_(e,t,n){let r=new Set,i=[];for(let a of[...e,...t]){let e=n(a);e==null||r.has(e)||(r.add(e),i.push(a))}return i}var i_=[`runs_24h`,`runs_7d`,`quota_spend_slots_24h`,`quota_spend_slots_7d`,`automation_run_count_24h`,`automation_run_count_7d`,`progress_signal_run_count_24h`,`progress_signal_run_count_7d`],a_=[`input_tokens_24h`,`input_tokens_7d`,`output_tokens_24h`,`output_tokens_7d`,`cache_tokens_24h`,`cache_tokens_7d`,`cost_usd_24h`,`cost_usd_7d`,`duration_ms_24h`,`duration_ms_7d`],o_=[`accounting`,`decision`,`evidence`,`state`,`work`],s_={accounting:0,decision:0,evidence:0,state:0,work:0},c_={runs_24h:0,runs_7d:0,quota_spend_slots_24h:0,quota_spend_slots_7d:0,automation_run_count_24h:0,automation_run_count_7d:0,progress_signal_run_count_24h:0,progress_signal_run_count_7d:0};function l_(e,t){let n={...e};for(let r of i_)n[r]=(Number(e[r])||0)+(Number(t[r])||0);for(let r of a_)(e[r]!==void 0||t[r]!==void 0)&&(n[r]=(e[r]??0)+(t[r]??0));return n}function u_(e,t){return!e.length||t<=0?e:e.map(e=>({...e,project_share_24h:Math.round((Number(e.runs_24h)||0)/t*1e3)/1e3}))}function d_(e,t){let n={...e};for(let r of o_)n[r]=(e[r]??0)+(t[r]??0);return n}function f_(e){let t={events_24h:0,events_7d:0,by_class_24h:{...s_},by_class_7d:{...s_}};for(let n of e)t.events_24h+=n.events_24h,t.events_7d+=n.events_7d,t.by_class_24h=d_(t.by_class_24h,n.by_class_24h),t.by_class_7d=d_(t.by_class_7d,n.by_class_7d);return t}function p_(e,t,n){if(!e&&!t)return null;let r=n_(e?.goals??[],`active`,n,e=>e.goal_id),i=n_(t?.goals??[],`stopped`,n,e=>e.goal_id),a=r_(r,i,e=>e.goal_id),o=f_(r),s=f_(i),c={events_24h:o.events_24h+s.events_24h,events_7d:o.events_7d+s.events_7d,by_class_24h:d_(o.by_class_24h,s.by_class_24h),by_class_7d:d_(o.by_class_7d,s.by_class_7d)};return{...e??t,goals:a,sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),totals:c}}function m_(e,t,n){if(!e&&!t)return null;let r=r_([...n_(e?.items??[],`active`,n,e=>e.goal_id),...n_(t?.items??[],`stopped`,n,e=>e.goal_id)],[],e=>`${e.goal_id}:${e.decision_kind??``}:${e.decision_at??``}`),i={decision_count:(e?.summary.decision_count??0)+(t?.summary.decision_count??0),stale_count:r.filter(e=>e.stale_by_age).length,rebase_required_count:(e?.summary.rebase_required_count??0)+(t?.summary.rebase_required_count??0),fresh_count:(e?.summary.fresh_count??0)+(t?.summary.fresh_count??0)};return{...e??t,items:r,sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),summary:i}}function h_(e,t){return r_([...e,...t].sort((e,t)=>t.generated_at.localeCompare(e.generated_at)),[],e=>`${e.goal_id}:${e.generated_at}:${e.classification??``}`)}function g_(e,t,n){let r=r_(n_(e.items,`active`,n,e=>e.goal_id),n_(t.items,`stopped`,n,e=>e.goal_id),e=>e.goal_id);return{...e,item_count:r.length,items:r,needs_controller:r.filter(e=>e.waiting_on===`controller`).length,needs_codex:r.filter(e=>e.waiting_on===`codex`).length,needs_user_or_controller:r.filter(e=>[`user_or_controller`,`controller`].includes(e.waiting_on)).length,watching_external_evidence:r.filter(e=>e.waiting_on===`external_evidence`).length}}function __(e){let t=e.todo_id?.trim()||``;return t?`${e.goal_id}:${t}`:`${e.goal_id}:synthetic:${e.role??``}:${e.index??``}:${e.text??``}`}function v_(e){let t={...c_};for(let n of e){for(let e of i_)t[e]+=Number(n[e])||0;for(let e of a_)n[e]!==void 0&&(t[e]=(t[e]??0)+n[e])}return t}function y_(e,t,n){if(!e&&!t)return null;let r=n_(e?.items??[],`active`,n,e=>e.goal_id),i=n_(t?.items??[],`stopped`,n,e=>e.goal_id),a=r_(r,i,__);return{...e??t,current_projected_count:r.length+i.length,items:a,rollout_event_count:a.reduce((e,t)=>e+(t.event_count??0),0),total_count:a.length}}function b_(e,t,n){if(!e&&!t)return null;let r=n_(e?.goals??[],`active`,n,e=>e.goal_id),i=n_(t?.goals??[],`stopped`,n,e=>e.goal_id),a=r_(r,i,e=>e.goal_id),o=l_(v_(r),v_(i));return{...e??t,goals:u_(a,Number(o.runs_24h)||0),sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),totals:o}}function x_(e,t,n){if(!e&&!t)return null;let r=(e?.agents??[]).filter(e=>e.goal_ids.some(e=>t_(e,n,`active`))||(e.current_todo?.goal_id?t_(e.current_todo.goal_id,n,`active`):!1)),i=(t?.agents??[]).filter(e=>e.goal_ids.some(e=>t_(e,n,`stopped`))||(e.current_todo?.goal_id?t_(e.current_todo.goal_id,n,`stopped`):!1)),a=r_(r,i,e=>e.agent_id).map(e=>{let t=i.find(t=>t.agent_id===e.agent_id);return t?{...e,goal_ids:Array.from(new Set([...e.goal_ids??[],...t.goal_ids]))}:e});return{...e??t,agents:a,source_summary:(e??t)?.source_summary?{...(e??t).source_summary,projected_agent_count:a.length,registered_agent_count:new Set(a.map(e=>e.agent_id)).size}:(e??t)?.source_summary}}function S_(e,t,n){if(!e&&!t)return null;let r=r_(n_(e?.goals??[],`active`,n,e=>e.goal_id),n_(t?.goals??[],`stopped`,n,e=>e.goal_id),e=>e.goal_id);return{...e??t,goals:r}}function C_(e,t){let n=t.goal_projection?.scope;if(n!==`active`&&n!==`stopped`)return t;let r=n,i=t.run_history.goals,a=e.run_history.goals,o=r_(r===`active`?i:a.filter(e=>e.activation_state!==`stopped`),r===`stopped`?i:a.filter(e=>e.activation_state===`stopped`),e=>e.id),s=new Map(o.map(e=>[e.id,e.activation_state])),c=r===`active`?t:e,l=r===`stopped`?t:e,u=e.goal_projection?.registry_revision??null,d=t.goal_projection?.registry_revision??null,f=u===null||d===null||u===d;return{...e,agent_management_projection:x_(c.agent_management_projection,l.agent_management_projection,s),attention_queue:g_(c.attention_queue,l.attention_queue,s),decision_freshness_summary:m_(c.decision_freshness_summary,l.decision_freshness_summary,s),event_ledger_summary:p_(c.event_ledger_summary,l.event_ledger_summary,s),goal_channel_notification_projection:S_(c.goal_channel_notification_projection,l.goal_channel_notification_projection,s),goal_projection:{schema_version:`loopx_goal_projection_scope_v0`,...t.goal_projection,complete:f,projected_goal_count:o.length,registry_goal_count:t.goal_projection?.registry_goal_count??0,scope:`all`},run_history:{...e.run_history,goal_count:o.length,goals:o,recent_runs:h_(c.run_history.recent_runs,l.run_history.recent_runs),run_count:c.run_history.run_count+l.run_history.run_count},todo_index:y_(c.todo_index,l.todo_index,s),usage_summary:b_(c.usage_summary,l.usage_summary,s)}}function w_(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`){if(Array.isArray(e)){var i=e.length;for(t=0;ttypeof e==`boolean`?`${e}`:e===0?`0`:e,D_=T_,O_=(e,t)=>n=>{if(t?.variants==null)return D_(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=E_(t)||E_(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return D_(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)},k_=(e,t)=>{let n=Array(e.length+t.length);for(let t=0;t({classGroupId:e,validator:t}),j_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),M_=`-`,N_=[],P_=`arbitrary..`,F_=e=>{let t=R_(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return L_(e);let n=e.split(M_);return I_(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?k_(i,t):t:i||N_}return n[e]||N_}}},I_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=I_(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(M_):e.slice(t).join(M_),s=a.length;for(let e=0;ee.slice(1,-1).indexOf(`:`)===-1?void 0:(()=>{let t=e.slice(1,-1),n=t.indexOf(`:`),r=t.slice(0,n);return r?P_+r:void 0})(),R_=e=>{let{theme:t,classGroups:n}=e;return z_(n,t)},z_=(e,t)=>{let n=j_();for(let r in e){let i=e[r];B_(i,n,r,t)}return n},B_=(e,t,n,r)=>{let i=e.length;for(let a=0;a{if(typeof e==`string`){H_(e,t,n);return}if(typeof e==`function`){U_(e,t,n,r);return}W_(e,t,n,r)},H_=(e,t,n)=>{let r=e===``?t:G_(t,e);r.classGroupId=n},U_=(e,t,n,r)=>{if(K_(e)){B_(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(A_(n,e))},W_=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e{let n=e,r=t.split(M_),i=r.length;for(let e=0;e`isThemeGetter`in e&&e.isThemeGetter===!0,q_=e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null),i=(i,a)=>{n[i]=a,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];if(t!==void 0)return t;if((t=r[e])!==void 0)return i(e,t),t},set(e,t){e in n?n[e]=t:i(e,t)}}},J_=`!`,Y_=`:`,X_=[],Z_=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),Q_=e=>{let{prefix:t,experimentalParseClassName:n}=e,r=e=>{let t=[],n=0,r=0,i=0,a,o=e.length;for(let s=0;si?a-i:void 0;return Z_(t,l,c,u)};if(t){let e=t+Y_,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):Z_(X_,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},$_=e=>{let t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{let n=[],r=[];for(let i=0;i0&&(r.sort(),n.push(...r),r=[]),n.push(a)):r.push(a)}return r.length>0&&(r.sort(),n.push(...r)),n}},ev=e=>({cache:q_(e.cacheSize),parseClassName:Q_(e),sortModifiers:$_(e),postfixLookupClassGroupIds:tv(e),...F_(e)}),tv=e=>{let t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let e=0;e{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a,postfixLookupClassGroupIds:o}=t,s=[],c=e.trim().split(nv),l=``;for(let e=c.length-1;e>=0;--e){let t=c[e],{isExternal:u,modifiers:d,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:m}=n(t);if(u){l=t+(l.length>0?` `+l:l);continue}let h=!!m,g;if(h){g=r(p.substring(0,m));let e=g&&o[g]?r(p):void 0;e&&e!==g&&(g=e,h=!1)}else g=r(p);if(!g){if(!h){l=t+(l.length>0?` `+l:l);continue}if(g=r(p),!g){l=t+(l.length>0?` `+l:l);continue}h=!1}let _=d.length===0?``:d.length===1?d[0]:a(d).join(`:`),v=f?_+J_:_,y=v+g;if(s.indexOf(y)>-1)continue;s.push(y);let b=i(g,h);for(let e=0;e0?` `+l:l)}return l},iv=(...e)=>{let t=0,n,r,i=``;for(;t{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r{let n,r,i,a,o=o=>(n=ev(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,a=s,s(o)),s=e=>{let t=r(e);if(t)return t;let a=rv(e,n);return i(e,a),a};return a=o,(...e)=>a(iv(...e))},sv=[],cv=e=>{let t=t=>t[e]||sv;return t.isThemeGetter=!0,t},lv=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,uv=/^\((?:(\w[\w-]*):)?(.+)\)$/i,dv=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,fv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,pv=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,mv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,hv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,gv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,_v=e=>dv.test(e),vv=e=>!!e&&!Number.isNaN(Number(e)),yv=e=>!!e&&Number.isInteger(Number(e)),bv=e=>e.endsWith(`%`)&&vv(e.slice(0,-1)),xv=e=>fv.test(e),Sv=()=>!0,Cv=e=>pv.test(e)&&!mv.test(e),wv=()=>!1,Tv=e=>hv.test(e),Ev=e=>gv.test(e),Dv=e=>!Q(e)&&!$(e),Ov=e=>e.startsWith(`@container`)&&(e[10]===`/`&&e[11]!==void 0||e[11]===`s`&&e[16]!==void 0&&e.startsWith(`-size/`,10)||e[11]===`n`&&e[18]!==void 0&&e.startsWith(`-normal/`,10)),kv=e=>Wv(e,Jv,wv),Q=e=>lv.test(e),Av=e=>Wv(e,Yv,Cv),jv=e=>Wv(e,Xv,vv),Mv=e=>Wv(e,Qv,Sv),Nv=e=>Wv(e,Zv,wv),Pv=e=>Wv(e,Kv,wv),Fv=e=>Wv(e,qv,Ev),Iv=e=>Wv(e,$v,Tv),$=e=>uv.test(e),Lv=e=>Gv(e,Yv),Rv=e=>Gv(e,Zv),zv=e=>Gv(e,Kv),Bv=e=>Gv(e,Jv),Vv=e=>Gv(e,qv),Hv=e=>Gv(e,$v,!0),Uv=e=>Gv(e,Qv,!0),Wv=(e,t,n)=>{let r=lv.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Gv=(e,t,n=!1)=>{let r=uv.exec(e);return r?r[1]?t(r[1]):n:!1},Kv=e=>e===`position`||e===`percentage`,qv=e=>e===`image`||e===`url`,Jv=e=>e===`length`||e===`size`||e===`bg-size`,Yv=e=>e===`length`,Xv=e=>e===`number`,Zv=e=>e===`family-name`,Qv=e=>e===`number`||e===`weight`,$v=e=>e===`shadow`,ey=ov(()=>{let e=cv(`color`),t=cv(`font`),n=cv(`text`),r=cv(`font-weight`),i=cv(`tracking`),a=cv(`leading`),o=cv(`breakpoint`),s=cv(`container`),c=cv(`spacing`),l=cv(`radius`),u=cv(`shadow`),d=cv(`inset-shadow`),f=cv(`text-shadow`),p=cv(`drop-shadow`),m=cv(`blur`),h=cv(`perspective`),g=cv(`aspect`),_=cv(`ease`),v=cv(`animate`),y=()=>[`auto`,`avoid`,`all`,`avoid-page`,`page`,`left`,`right`,`column`],b=()=>[`center`,`top`,`bottom`,`left`,`right`,`top-left`,`left-top`,`top-right`,`right-top`,`bottom-right`,`right-bottom`,`bottom-left`,`left-bottom`],x=()=>[...b(),$,Q],S=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],C=()=>[`auto`,`contain`,`none`],w=()=>[$,Q,c],T=()=>[_v,`full`,`auto`,...w()],E=()=>[yv,`none`,`subgrid`,$,Q],D=()=>[`auto`,{span:[`full`,yv,$,Q]},yv,$,Q],O=()=>[yv,`auto`,$,Q],ee=()=>[`auto`,`min`,`max`,`fr`,$,Q],te=()=>[`start`,`end`,`center`,`between`,`around`,`evenly`,`stretch`,`baseline`,`center-safe`,`end-safe`],ne=()=>[`start`,`end`,`center`,`stretch`,`center-safe`,`end-safe`],k=()=>[`auto`,...w()],A=()=>[_v,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...w()],j=()=>[_v,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...w()],M=()=>[_v,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...w()],N=()=>[e,$,Q],P=()=>[...b(),zv,Pv,{position:[$,Q]}],F=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],re=()=>[`auto`,`cover`,`contain`,Bv,kv,{size:[$,Q]}],ie=()=>[bv,Lv,Av],I=()=>[``,`none`,`full`,l,$,Q],ae=()=>[``,vv,Lv,Av],L=()=>[`solid`,`dashed`,`dotted`,`double`],oe=()=>[`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`],se=()=>[vv,bv,zv,Pv],ce=()=>[``,`none`,m,$,Q],le=()=>[`none`,vv,$,Q],ue=()=>[`none`,vv,$,Q],de=()=>[vv,$,Q],fe=()=>[_v,`full`,...w()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[xv],breakpoint:[xv],color:[Sv],container:[xv],"drop-shadow":[xv],ease:[`in`,`out`,`in-out`],font:[Dv],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[xv],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[xv],shadow:[xv],spacing:[`px`,vv],text:[xv],"text-shadow":[xv],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,_v,Q,$,g]}],container:[`container`],"container-type":[{"@container":[``,`normal`,`size`,$,Q]}],"container-named":[Ov],columns:[{columns:[vv,Q,$,s]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":[`auto`,`avoid`,`avoid-page`,`avoid-column`]}],"box-decoration":[{"box-decoration":[`slice`,`clone`]}],box:[{box:[`border`,`content`]}],display:[`block`,`inline-block`,`inline`,`flex`,`inline-flex`,`table`,`inline-table`,`table-caption`,`table-cell`,`table-column`,`table-column-group`,`table-footer-group`,`table-header-group`,`table-row-group`,`table-row`,`flow-root`,`grid`,`inline-grid`,`contents`,`list-item`,`hidden`],sr:[`sr-only`,`not-sr-only`],float:[{float:[`right`,`left`,`none`,`start`,`end`]}],clear:[{clear:[`left`,`right`,`both`,`none`,`start`,`end`]}],isolation:[`isolate`,`isolation-auto`],"object-fit":[{object:[`contain`,`cover`,`fill`,`none`,`scale-down`]}],"object-position":[{object:x()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:[`static`,`fixed`,`absolute`,`relative`,`sticky`],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{"inset-s":T(),start:T()}],end:[{"inset-e":T(),end:T()}],"inset-bs":[{"inset-bs":T()}],"inset-be":[{"inset-be":T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:[`visible`,`invisible`,`collapse`],z:[{z:[yv,`auto`,$,Q]}],basis:[{basis:[_v,`full`,`auto`,s,...w()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[vv,_v,`auto`,`initial`,`none`,Q]}],grow:[{grow:[``,vv,$,Q]}],shrink:[{shrink:[``,vv,$,Q]}],order:[{order:[yv,`first`,`last`,`none`,$,Q]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":[`row`,`col`,`dense`,`row-dense`,`col-dense`]}],"auto-cols":[{"auto-cols":ee()}],"auto-rows":[{"auto-rows":ee()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...te(),`normal`]}],"justify-items":[{"justify-items":[...ne(),`normal`]}],"justify-self":[{"justify-self":[`auto`,...ne()]}],"align-content":[{content:[`normal`,...te()]}],"align-items":[{items:[...ne(),{baseline:[``,`last`]}]}],"align-self":[{self:[`auto`,...ne(),{baseline:[``,`last`]}]}],"place-content":[{"place-content":te()}],"place-items":[{"place-items":[...ne(),`baseline`]}],"place-self":[{"place-self":[`auto`,...ne()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pbs:[{pbs:w()}],pbe:[{pbe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:k()}],mx:[{mx:k()}],my:[{my:k()}],ms:[{ms:k()}],me:[{me:k()}],mbs:[{mbs:k()}],mbe:[{mbe:k()}],mt:[{mt:k()}],mr:[{mr:k()}],mb:[{mb:k()}],ml:[{ml:k()}],"space-x":[{"space-x":w()}],"space-x-reverse":[`space-x-reverse`],"space-y":[{"space-y":w()}],"space-y-reverse":[`space-y-reverse`],size:[{size:A()}],"inline-size":[{inline:[`auto`,...j()]}],"min-inline-size":[{"min-inline":[`auto`,...j()]}],"max-inline-size":[{"max-inline":[`none`,...j()]}],"block-size":[{block:[`auto`,...M()]}],"min-block-size":[{"min-block":[`auto`,...M()]}],"max-block-size":[{"max-block":[`none`,...M()]}],w:[{w:[s,`screen`,...A()]}],"min-w":[{"min-w":[s,`screen`,`none`,...A()]}],"max-w":[{"max-w":[s,`screen`,`none`,`prose`,{screen:[o]},...A()]}],h:[{h:[`screen`,`lh`,...A()]}],"min-h":[{"min-h":[`screen`,`lh`,`none`,...A()]}],"max-h":[{"max-h":[`screen`,`lh`,...A()]}],"font-size":[{text:[`base`,n,Lv,Av]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,Uv,Mv]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,bv,Q]}],"font-family":[{font:[Rv,Nv,t]}],"font-features":[{"font-features":[Q]}],"fvn-normal":[`normal-nums`],"fvn-ordinal":[`ordinal`],"fvn-slashed-zero":[`slashed-zero`],"fvn-figure":[`lining-nums`,`oldstyle-nums`],"fvn-spacing":[`proportional-nums`,`tabular-nums`],"fvn-fraction":[`diagonal-fractions`,`stacked-fractions`],tracking:[{tracking:[i,$,Q]}],"line-clamp":[{"line-clamp":[vv,`none`,$,jv]}],leading:[{leading:[a,...w()]}],"list-image":[{"list-image":[`none`,$,Q]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,$,Q]}],"text-alignment":[{text:[`left`,`center`,`right`,`justify`,`start`,`end`]}],"placeholder-color":[{placeholder:N()}],"text-color":[{text:N()}],"text-decoration":[`underline`,`overline`,`line-through`,`no-underline`],"text-decoration-style":[{decoration:[...L(),`wavy`]}],"text-decoration-thickness":[{decoration:[vv,`from-font`,`auto`,$,Av]}],"text-decoration-color":[{decoration:N()}],"underline-offset":[{"underline-offset":[vv,`auto`,$,Q]}],"text-transform":[`uppercase`,`lowercase`,`capitalize`,`normal-case`],"text-overflow":[`truncate`,`text-ellipsis`,`text-clip`],"text-wrap":[{text:[`wrap`,`nowrap`,`balance`,`pretty`]}],indent:[{indent:w()}],"tab-size":[{tab:[yv,$,Q]}],"vertical-align":[{align:[`baseline`,`top`,`middle`,`bottom`,`text-top`,`text-bottom`,`sub`,`super`,$,Q]}],whitespace:[{whitespace:[`normal`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]}],break:[{break:[`normal`,`words`,`all`,`keep`]}],wrap:[{wrap:[`break-word`,`anywhere`,`normal`]}],hyphens:[{hyphens:[`none`,`manual`,`auto`]}],content:[{content:[`none`,$,Q]}],"bg-attachment":[{bg:[`fixed`,`local`,`scroll`]}],"bg-clip":[{"bg-clip":[`border`,`padding`,`content`,`text`]}],"bg-origin":[{"bg-origin":[`border`,`padding`,`content`]}],"bg-position":[{bg:P()}],"bg-repeat":[{bg:F()}],"bg-size":[{bg:re()}],"bg-image":[{bg:[`none`,{linear:[{to:[`t`,`tr`,`r`,`br`,`b`,`bl`,`l`,`tl`]},yv,$,Q],radial:[``,$,Q],conic:[yv,$,Q]},Vv,Fv]}],"bg-color":[{bg:N()}],"gradient-from-pos":[{from:ie()}],"gradient-via-pos":[{via:ie()}],"gradient-to-pos":[{to:ie()}],"gradient-from":[{from:N()}],"gradient-via":[{via:N()}],"gradient-to":[{to:N()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:ae()}],"border-w-x":[{"border-x":ae()}],"border-w-y":[{"border-y":ae()}],"border-w-s":[{"border-s":ae()}],"border-w-e":[{"border-e":ae()}],"border-w-bs":[{"border-bs":ae()}],"border-w-be":[{"border-be":ae()}],"border-w-t":[{"border-t":ae()}],"border-w-r":[{"border-r":ae()}],"border-w-b":[{"border-b":ae()}],"border-w-l":[{"border-l":ae()}],"divide-x":[{"divide-x":ae()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":ae()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...L(),`hidden`,`none`]}],"divide-style":[{divide:[...L(),`hidden`,`none`]}],"border-color":[{border:N()}],"border-color-x":[{"border-x":N()}],"border-color-y":[{"border-y":N()}],"border-color-s":[{"border-s":N()}],"border-color-e":[{"border-e":N()}],"border-color-bs":[{"border-bs":N()}],"border-color-be":[{"border-be":N()}],"border-color-t":[{"border-t":N()}],"border-color-r":[{"border-r":N()}],"border-color-b":[{"border-b":N()}],"border-color-l":[{"border-l":N()}],"divide-color":[{divide:N()}],"outline-style":[{outline:[...L(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[vv,$,Q]}],"outline-w":[{outline:[``,vv,Lv,Av]}],"outline-color":[{outline:N()}],shadow:[{shadow:[``,`none`,u,Hv,Iv]}],"shadow-color":[{shadow:N()}],"inset-shadow":[{"inset-shadow":[`none`,d,Hv,Iv]}],"inset-shadow-color":[{"inset-shadow":N()}],"ring-w":[{ring:ae()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:N()}],"ring-offset-w":[{"ring-offset":[vv,Av]}],"ring-offset-color":[{"ring-offset":N()}],"inset-ring-w":[{"inset-ring":ae()}],"inset-ring-color":[{"inset-ring":N()}],"text-shadow":[{"text-shadow":[`none`,f,Hv,Iv]}],"text-shadow-color":[{"text-shadow":N()}],opacity:[{opacity:[vv,$,Q]}],"mix-blend":[{"mix-blend":[...oe(),`plus-darker`,`plus-lighter`]}],"bg-blend":[{"bg-blend":oe()}],"mask-clip":[{"mask-clip":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]},`mask-no-clip`],"mask-composite":[{mask:[`add`,`subtract`,`intersect`,`exclude`]}],"mask-image-linear-pos":[{"mask-linear":[vv]}],"mask-image-linear-from-pos":[{"mask-linear-from":se()}],"mask-image-linear-to-pos":[{"mask-linear-to":se()}],"mask-image-linear-from-color":[{"mask-linear-from":N()}],"mask-image-linear-to-color":[{"mask-linear-to":N()}],"mask-image-t-from-pos":[{"mask-t-from":se()}],"mask-image-t-to-pos":[{"mask-t-to":se()}],"mask-image-t-from-color":[{"mask-t-from":N()}],"mask-image-t-to-color":[{"mask-t-to":N()}],"mask-image-r-from-pos":[{"mask-r-from":se()}],"mask-image-r-to-pos":[{"mask-r-to":se()}],"mask-image-r-from-color":[{"mask-r-from":N()}],"mask-image-r-to-color":[{"mask-r-to":N()}],"mask-image-b-from-pos":[{"mask-b-from":se()}],"mask-image-b-to-pos":[{"mask-b-to":se()}],"mask-image-b-from-color":[{"mask-b-from":N()}],"mask-image-b-to-color":[{"mask-b-to":N()}],"mask-image-l-from-pos":[{"mask-l-from":se()}],"mask-image-l-to-pos":[{"mask-l-to":se()}],"mask-image-l-from-color":[{"mask-l-from":N()}],"mask-image-l-to-color":[{"mask-l-to":N()}],"mask-image-x-from-pos":[{"mask-x-from":se()}],"mask-image-x-to-pos":[{"mask-x-to":se()}],"mask-image-x-from-color":[{"mask-x-from":N()}],"mask-image-x-to-color":[{"mask-x-to":N()}],"mask-image-y-from-pos":[{"mask-y-from":se()}],"mask-image-y-to-pos":[{"mask-y-to":se()}],"mask-image-y-from-color":[{"mask-y-from":N()}],"mask-image-y-to-color":[{"mask-y-to":N()}],"mask-image-radial":[{"mask-radial":[$,Q]}],"mask-image-radial-from-pos":[{"mask-radial-from":se()}],"mask-image-radial-to-pos":[{"mask-radial-to":se()}],"mask-image-radial-from-color":[{"mask-radial-from":N()}],"mask-image-radial-to-color":[{"mask-radial-to":N()}],"mask-image-radial-shape":[{"mask-radial":[`circle`,`ellipse`]}],"mask-image-radial-size":[{"mask-radial":[{closest:[`side`,`corner`],farthest:[`side`,`corner`]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[vv]}],"mask-image-conic-from-pos":[{"mask-conic-from":se()}],"mask-image-conic-to-pos":[{"mask-conic-to":se()}],"mask-image-conic-from-color":[{"mask-conic-from":N()}],"mask-image-conic-to-color":[{"mask-conic-to":N()}],"mask-mode":[{mask:[`alpha`,`luminance`,`match`]}],"mask-origin":[{"mask-origin":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]}],"mask-position":[{mask:P()}],"mask-repeat":[{mask:F()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":[`alpha`,`luminance`]}],"mask-image":[{mask:[`none`,$,Q]}],filter:[{filter:[``,`none`,$,Q]}],blur:[{blur:ce()}],brightness:[{brightness:[vv,$,Q]}],contrast:[{contrast:[vv,$,Q]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,Hv,Iv]}],"drop-shadow-color":[{"drop-shadow":N()}],grayscale:[{grayscale:[``,vv,$,Q]}],"hue-rotate":[{"hue-rotate":[vv,$,Q]}],invert:[{invert:[``,vv,$,Q]}],saturate:[{saturate:[vv,$,Q]}],sepia:[{sepia:[``,vv,$,Q]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,$,Q]}],"backdrop-blur":[{"backdrop-blur":ce()}],"backdrop-brightness":[{"backdrop-brightness":[vv,$,Q]}],"backdrop-contrast":[{"backdrop-contrast":[vv,$,Q]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,vv,$,Q]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[vv,$,Q]}],"backdrop-invert":[{"backdrop-invert":[``,vv,$,Q]}],"backdrop-opacity":[{"backdrop-opacity":[vv,$,Q]}],"backdrop-saturate":[{"backdrop-saturate":[vv,$,Q]}],"backdrop-sepia":[{"backdrop-sepia":[``,vv,$,Q]}],"border-collapse":[{border:[`collapse`,`separate`]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:[`auto`,`fixed`]}],caption:[{caption:[`top`,`bottom`]}],transition:[{transition:[``,`all`,`colors`,`opacity`,`shadow`,`transform`,`none`,$,Q]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[vv,`initial`,$,Q]}],ease:[{ease:[`linear`,`initial`,_,$,Q]}],delay:[{delay:[vv,$,Q]}],animate:[{animate:[`none`,v,$,Q]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,$,Q]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:le()}],"rotate-x":[{"rotate-x":le()}],"rotate-y":[{"rotate-y":le()}],"rotate-z":[{"rotate-z":le()}],scale:[{scale:ue()}],"scale-x":[{"scale-x":ue()}],"scale-y":[{"scale-y":ue()}],"scale-z":[{"scale-z":ue()}],"scale-3d":[`scale-3d`],skew:[{skew:de()}],"skew-x":[{"skew-x":de()}],"skew-y":[{"skew-y":de()}],transform:[{transform:[$,Q,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:fe()}],"translate-x":[{"translate-x":fe()}],"translate-y":[{"translate-y":fe()}],"translate-z":[{"translate-z":fe()}],"translate-none":[`translate-none`],zoom:[{zoom:[yv,$,Q]}],accent:[{accent:N()}],appearance:[{appearance:[`none`,`auto`]}],"caret-color":[{caret:N()}],"color-scheme":[{scheme:[`normal`,`dark`,`light`,`light-dark`,`only-dark`,`only-light`]}],cursor:[{cursor:[`auto`,`default`,`pointer`,`wait`,`text`,`move`,`help`,`not-allowed`,`none`,`context-menu`,`progress`,`cell`,`crosshair`,`vertical-text`,`alias`,`copy`,`no-drop`,`grab`,`grabbing`,`all-scroll`,`col-resize`,`row-resize`,`n-resize`,`e-resize`,`s-resize`,`w-resize`,`ne-resize`,`nw-resize`,`se-resize`,`sw-resize`,`ew-resize`,`ns-resize`,`nesw-resize`,`nwse-resize`,`zoom-in`,`zoom-out`,$,Q]}],"field-sizing":[{"field-sizing":[`fixed`,`content`]}],"pointer-events":[{"pointer-events":[`auto`,`none`]}],resize:[{resize:[`none`,``,`y`,`x`]}],"scroll-behavior":[{scroll:[`auto`,`smooth`]}],"scrollbar-thumb-color":[{"scrollbar-thumb":N()}],"scrollbar-track-color":[{"scrollbar-track":N()}],"scrollbar-gutter":[{"scrollbar-gutter":[`auto`,`stable`,`both`]}],"scrollbar-w":[{scrollbar:[`auto`,`thin`,`none`]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mbs":[{"scroll-mbs":w()}],"scroll-mbe":[{"scroll-mbe":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pbs":[{"scroll-pbs":w()}],"scroll-pbe":[{"scroll-pbe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:[`start`,`end`,`center`,`align-none`]}],"snap-stop":[{snap:[`normal`,`always`]}],"snap-type":[{snap:[`none`,`x`,`y`,`both`]}],"snap-strictness":[{snap:[`mandatory`,`proximity`]}],touch:[{touch:[`auto`,`none`,`manipulation`]}],"touch-x":[{"touch-pan":[`x`,`left`,`right`]}],"touch-y":[{"touch-pan":[`y`,`up`,`down`]}],"touch-pz":[`touch-pinch-zoom`],select:[{select:[`none`,`text`,`all`,`auto`]}],"will-change":[{"will-change":[`auto`,`scroll`,`contents`,`transform`,$,Q]}],fill:[{fill:[`none`,...N()]}],"stroke-w":[{stroke:[vv,Lv,Av,jv]}],stroke:[{stroke:[`none`,...N()]}],"forced-color-adjust":[{"forced-color-adjust":[`auto`,`none`]}]},conflictingClassGroups:{"container-named":[`container-type`],overflow:[`overflow-x`,`overflow-y`],overscroll:[`overscroll-x`,`overscroll-y`],inset:[`inset-x`,`inset-y`,`inset-bs`,`inset-be`,`start`,`end`,`top`,`right`,`bottom`,`left`],"inset-x":[`right`,`left`],"inset-y":[`top`,`bottom`],flex:[`basis`,`grow`,`shrink`],gap:[`gap-x`,`gap-y`],p:[`px`,`py`,`ps`,`pe`,`pbs`,`pbe`,`pt`,`pr`,`pb`,`pl`],px:[`pr`,`pl`],py:[`pt`,`pb`],m:[`mx`,`my`,`ms`,`me`,`mbs`,`mbe`,`mt`,`mr`,`mb`,`ml`],mx:[`mr`,`ml`],my:[`mt`,`mb`],size:[`w`,`h`],"font-size":[`leading`],"fvn-normal":[`fvn-ordinal`,`fvn-slashed-zero`,`fvn-figure`,`fvn-spacing`,`fvn-fraction`],"fvn-ordinal":[`fvn-normal`],"fvn-slashed-zero":[`fvn-normal`],"fvn-figure":[`fvn-normal`],"fvn-spacing":[`fvn-normal`],"fvn-fraction":[`fvn-normal`],"line-clamp":[`display`,`overflow`],rounded:[`rounded-s`,`rounded-e`,`rounded-t`,`rounded-r`,`rounded-b`,`rounded-l`,`rounded-ss`,`rounded-se`,`rounded-ee`,`rounded-es`,`rounded-tl`,`rounded-tr`,`rounded-br`,`rounded-bl`],"rounded-s":[`rounded-ss`,`rounded-es`],"rounded-e":[`rounded-se`,`rounded-ee`],"rounded-t":[`rounded-tl`,`rounded-tr`],"rounded-r":[`rounded-tr`,`rounded-br`],"rounded-b":[`rounded-br`,`rounded-bl`],"rounded-l":[`rounded-tl`,`rounded-bl`],"border-spacing":[`border-spacing-x`,`border-spacing-y`],"border-w":[`border-w-x`,`border-w-y`,`border-w-s`,`border-w-e`,`border-w-bs`,`border-w-be`,`border-w-t`,`border-w-r`,`border-w-b`,`border-w-l`],"border-w-x":[`border-w-r`,`border-w-l`],"border-w-y":[`border-w-t`,`border-w-b`],"border-color":[`border-color-x`,`border-color-y`,`border-color-s`,`border-color-e`,`border-color-bs`,`border-color-be`,`border-color-t`,`border-color-r`,`border-color-b`,`border-color-l`],"border-color-x":[`border-color-r`,`border-color-l`],"border-color-y":[`border-color-t`,`border-color-b`],translate:[`translate-x`,`translate-y`,`translate-none`],"translate-none":[`translate`,`translate-x`,`translate-y`,`translate-z`],"scroll-m":[`scroll-mx`,`scroll-my`,`scroll-ms`,`scroll-me`,`scroll-mbs`,`scroll-mbe`,`scroll-mt`,`scroll-mr`,`scroll-mb`,`scroll-ml`],"scroll-mx":[`scroll-mr`,`scroll-ml`],"scroll-my":[`scroll-mt`,`scroll-mb`],"scroll-p":[`scroll-px`,`scroll-py`,`scroll-ps`,`scroll-pe`,`scroll-pbs`,`scroll-pbe`,`scroll-pt`,`scroll-pr`,`scroll-pb`,`scroll-pl`],"scroll-px":[`scroll-pr`,`scroll-pl`],"scroll-py":[`scroll-pt`,`scroll-pb`],touch:[`touch-x`,`touch-y`,`touch-pz`],"touch-x":[`touch`],"touch-y":[`touch`],"touch-pz":[`touch`]},conflictingClassGroupModifiers:{"font-size":[`leading`]},postfixLookupClassGroups:[`container-type`],orderSensitiveModifiers:[`*`,`**`,`after`,`backdrop`,`before`,`details-content`,`file`,`first-letter`,`first-line`,`marker`,`placeholder`,`selection`]}});function ty(...e){return ey(T_(e))}var ny=O_(`inline-flex h-9 shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-md border px-3 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400 disabled:pointer-events-none disabled:opacity-50 dark:focus-visible:ring-zinc-500`,{variants:{variant:{primary:`border-slate-900 bg-slate-950 text-white hover:bg-slate-800 dark:border-zinc-100 dark:bg-zinc-50 dark:text-zinc-950 dark:hover:bg-zinc-200`,secondary:`border-slate-200 bg-white text-slate-900 hover:bg-slate-50 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-100 dark:hover:bg-zinc-900`,ghost:`border-transparent bg-transparent text-slate-700 hover:bg-slate-100 dark:text-zinc-300 dark:hover:bg-zinc-900`},size:{sm:`h-8 px-2 text-xs`,md:`h-9 px-3 text-sm`,icon:`h-9 w-9 px-0`}},defaultVariants:{variant:`secondary`,size:`md`}});function ry({className:e,variant:t,size:n,...r}){return(0,B.jsx)(`button`,{className:ty(ny({variant:t,size:n}),e),type:`button`,...r})}function iy({className:e,...t}){return(0,B.jsx)(`section`,{className:ty(`rounded-lg border border-slate-200/80 bg-white/95 text-slate-950 shadow-[0_1px_2px_rgba(15,23,42,0.04)] dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50`,e),...t})}function ay({className:e,...t}){return(0,B.jsx)(`div`,{className:ty(`p-4 pt-0`,e),...t})}var oy=[`codex`,`claude`,`kiro`,`trae`,`coco`,`openai`,`anthropic`],sy=new Set([`acp`,`status_projection`]);function cy(e){let t=e.trim().toLowerCase().replace(/_/gu,`-`);for(let e of oy)if(t===e||t.startsWith(`${e}-`))return e;return t}function ly(e,t){let n=t?.trim().toLowerCase()??``;return n.length>0&&!sy.has(n)?cy(n):cy(e)}var uy={stop:`ready_stop`,resume:`resume_review`,delete:`delete_review`},dy=e=>typeof e==`string`&&e.trim().length>0;function fy(e){let t={schemaVersion:`action_review_plan_v0`,proposalId:e.proposal_id,sourceFingerprint:e.expected_state_fingerprint},n=(e,n)=>({...t,interaction:e,reason:n,canApply:!1}),r=e.action_kind===`goal.lifecycle`;if(r&&e.gate!=null||e.status===`gated`)return n(`gated`,`authority_gate`);if(r&&e.stale!=null||e.status===`stale`)return n(`refresh`,`stale_proposal`);if(e.status===`applied`)return e.receipt?.projection_verified===!0?n(`completed`,`readback_verified`):n(`repair`,`readback_unverified`);if(e.status===`applying`)return n(`pending`,`apply_pending`);if(e.status===`failed`||e.error!=null)return n(`repair`,`apply_failed`);if(e.status!==`preview_ready`&&e.status!==`deferred`)return n(`inactive`,`inactive_proposal`);let i=(e,n=!0)=>({...t,interaction:`review`,reason:e,canApply:n});if(e.action_kind!==`goal.lifecycle`)return i(e.permission_classification===`protected`?`protected_action`:`action_review`);if(!(dy(e.proposal_id)&&dy(e.expected_state_fingerprint)&&Oh.shape.validation_evidence.safeParse(e.validation_evidence).success&&e.validation_evidence.length>0&&e.available_transitions.includes(`apply`)))return n(`refresh`,`incomplete_proposal`);let{operation:a,goal_id:o}=e.normalized_parameters;if(!dy(o)||e.context.goal_id!=null&&e.context.goal_id!==o)return n(`refresh`,`incomplete_proposal`);if(a!==`stop`&&a!==`resume`&&a!==`delete`)return i(`unknown_action`,!1);if(e.permission_classification===`protected`)return i(`protected_action`);if(e.permission_classification!==`durable_write`)return i(`unknown_permission`,!1);let s=uy[a];return s===`ready_stop`&&e.status===`preview_ready`?{...t,interaction:`direct`,reason:s,canApply:!0}:i(s===`ready_stop`?`action_review`:s)}function py(e){if(e.error_code===`action_stale`||e.error_code===`action_conflict`)return!0;let t=e.proposal;return typeof t==`object`&&!!t&&`status`in t&&t.status===`stale`}function my(e){return{blockingTodoCount:e.blockingTodoCount,goalNotifications:e.goalNotifications,goals:e.goals,openUserTodoCount:e.openUserTodoCount,systemHealth:e.systemHealth,attentionHistory:e.attentionHistory,userTodos:e.userTodos,workers:e.workers}}function hy(e,t){return e.goals.find(e=>e.goalId===t)?.title??t}function gy(e){return e.activationState===`stopped`||e.state===`已停止`?`stopped`:e.state===`已完成`?`history`:e.needsYou||e.state===`等你`?`needs_you`:e.state===`推进中`||e.state===`需修复`?`running`:e.state===`安静运行`?`observing`:`scheduled`}function _y(e){let t=e;return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function vy(e){return`$${e.toFixed(2)}`}function yy(e){let t=e;return t>=36e5?`${(t/36e5).toFixed(1)}h`:t>=6e4?`${(t/6e4).toFixed(1)}m`:t>=1e3?`${Math.round(t/1e3)}s`:`${t}ms`}function by(e,t,n){return e==null?t:n(e)}function xy(e){return!!(e&&[e.tokens24h,e.tokens7d,e.costUsd24h,e.costUsd7d,e.durationMs24h,e.durationMs7d].some(e=>e!=null))}function Sy(e,t){if(!xy(e))return null;let n=(e,n,r,i)=>{let a=[n==null?null:`${_y(n)} ${t.tokens}`,r==null?null:`${t.cost}: ${vy(r)}`,i==null?null:`${t.duration}: ${yy(i)}`].filter(e=>e!==null);return a.length?`${e} ${a.join(` · `)}`:null};return n(t.period7d,e.tokens7d,e.costUsd7d,e.durationMs7d)??n(t.period24h,e.tokens24h,e.costUsd24h,e.durationMs24h)}function Cy({ariaLabel:e,className:t,icon:n,onChange:r,options:i,prefixLabel:a,value:o}){let s=(0,z.useId)(),c=(0,z.useRef)(null),l=(0,z.useRef)(null),u=(0,z.useRef)(new Map),[d,f]=(0,z.useState)(!1),[p,m]=(0,z.useState)(o),h=i.find(e=>e.value===o)??i[0],g=i.filter(e=>!e.disabled);(0,z.useEffect)(()=>{if(!d)return;let e=e=>{c.current?.contains(e.target)||f(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[d]),(0,z.useEffect)(()=>{d&&u.current.get(p)?.focus()},[p,d]);function _(e){m(e)}function v(e=`selected`){let t=e===`last`?g.at(-1):g[0],n=e===`selected`&&h&&!h.disabled?h:t;n&&(f(!0),_(n.value))}function y({restoreFocus:e=!1}={}){f(!1),e&&l.current?.focus()}function b(e){e.disabled||(r(e.value),y({restoreFocus:!0}))}function x(e){if(!g.length)return;let t=g.findIndex(e=>e.value===p),n=t<0?0:(t+e+g.length)%g.length;_(g[n].value)}function S(e){e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),v(`selected`)):e.key===`ArrowUp`&&(e.preventDefault(),v(`last`))}function C(e,t){if(e.key===`ArrowDown`)e.preventDefault(),x(1);else if(e.key===`ArrowUp`)e.preventDefault(),x(-1);else if(e.key===`Home`)e.preventDefault(),g[0]&&_(g[0].value);else if(e.key===`End`){e.preventDefault();let t=g.at(-1);t&&_(t.value)}else e.key===`Enter`||e.key===` `?(e.preventDefault(),b(t)):e.key===`Escape`?(e.preventDefault(),y({restoreFocus:!0})):e.key===`Tab`&&y()}let w;return(0,B.jsxs)(`div`,{className:`personal-select${t?` ${t}`:``}`,ref:c,children:[(0,B.jsxs)(`button`,{"aria-controls":s,"aria-expanded":d,"aria-haspopup":`listbox`,"aria-label":e,className:`personal-select-trigger`,"data-value":o,onClick:()=>d?y():v(),onKeyDown:S,ref:l,role:`combobox`,type:`button`,children:[n?(0,B.jsx)(`span`,{className:`personal-select-icon`,children:n}):null,(0,B.jsxs)(`span`,{className:`personal-select-value`,children:[a?(0,B.jsx)(`small`,{children:a}):null,(0,B.jsx)(`span`,{children:h?.label??o})]}),(0,B.jsx)(tm,{"aria-hidden":!0,className:d?`is-open`:void 0,size:14})]}),d?(0,B.jsx)(`div`,{"aria-label":e,className:`personal-select-listbox`,id:s,role:`listbox`,children:i.map(e=>{let t=e.group&&e.group!==w;return w=e.group,(0,B.jsxs)(`div`,{className:`personal-select-option-wrap`,children:[t?(0,B.jsx)(`div`,{className:`personal-select-group-label`,children:e.group}):null,(0,B.jsxs)(`button`,{"aria-disabled":e.disabled||void 0,"aria-selected":e.value===o,className:`personal-select-option`,disabled:e.disabled,id:`${s}-${e.value.replace(/[^a-z0-9_-]/gi,`-`)}`,onClick:()=>b(e),onFocus:()=>m(e.value),onKeyDown:t=>C(t,e),ref:t=>{t?u.current.set(e.value,t):u.current.delete(e.value)},role:`option`,tabIndex:e.value===p?0:-1,type:`button`,children:[(0,B.jsx)(`span`,{children:e.label}),e.value===o?(0,B.jsx)(em,{"aria-hidden":!0,size:15}):null]})]},e.value)})}):null]})}function wy({agents:e,managerChatOpen:t,mobileNavigationOpen:n,onOpenGoalCapabilities:r,onOpenGoalDetail:i,onOpenManagerChat:a,onRefresh:o,onOpenNavigation:s,onSelectGoalTab:c,onSelectAgent:l,onReturnManagerHome:u,refreshState:d,readOnlySourceLabel:f,selectedAgentId:p,selectedGoal:m,selectedGoalTab:h}){let{locale:g,t:_}=Ji(),[v,y]=(0,z.useState)(!1),b=(0,z.useRef)(null),x=(0,z.useRef)(null);(0,z.useEffect)(()=>{if(!v)return;function e(e){x.current?.contains(e.target)||y(!1)}function t(e){e.key===`Escape`&&(y(!1),b.current?.focus())}return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[v]),(0,z.useEffect)(()=>y(!1),[m?.goalId]);function S(e){y(!1),e?.()}let C=m?Sy(m.usage,{cost:_(`drawer.costShort`),duration:_(`drawer.durationShort`),period24h:_(`drawer.period24h`),period7d:_(`drawer.period7d`),tokens:_(`drawer.tokensShort`)}):null;return(0,B.jsxs)(`header`,{className:`personal-channel-header`,children:[(0,B.jsx)(`button`,{"aria-expanded":n??!1,"aria-label":_(`header.openGoalNavigation`),className:`personal-icon-button personal-mobile-menu`,onClick:s,type:`button`,children:(0,B.jsx)(Tm,{size:18})}),(0,B.jsxs)(`div`,{className:`personal-channel-title`,children:[(0,B.jsx)(`h1`,{children:m?.title??_(`header.manager`)}),m?(0,B.jsx)(`p`,{children:m.loadState?_(m.loadState===`error`?`startup.goalError`:`startup.goalLoading`):`${m.agentLaneCount&&m.agentLaneCount>1?_(`header.workAgentCount`,{count:m.agentLaneCount}):m.agentLabel??m.agentId} · ${m.loadState?_(m.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Yi(m.state,g)}${C?` · ${C}`:``} · ${m.nextSentence}`}):null]}),m?(0,B.jsxs)(`nav`,{"aria-label":_(`header.goalView`),className:`personal-goal-tabs`,children:[(0,B.jsx)(`button`,{"aria-current":h===`chat`?`page`:void 0,onClick:()=>c(`chat`),type:`button`,children:_(`header.chat`)}),(0,B.jsx)(`button`,{"aria-current":h===`tasks`?`page`:void 0,onClick:()=>c(`tasks`),type:`button`,children:_(`header.tasks`)}),(0,B.jsx)(`button`,{"aria-current":h===`files`?`page`:void 0,onClick:()=>c(`files`),type:`button`,children:_(`header.files`)})]}):(0,B.jsxs)(`nav`,{"aria-label":_(`header.managerView`),className:`personal-goal-tabs`,children:[(0,B.jsx)(`button`,{"aria-current":t?void 0:`page`,onClick:u,type:`button`,children:_(`header.managerOverview`)}),(0,B.jsx)(`button`,{"aria-current":t?`page`:void 0,onClick:a,type:`button`,children:_(`header.chat`)})]}),(0,B.jsxs)(`div`,{className:`personal-channel-actions`,children:[m&&i&&r?(0,B.jsxs)(`div`,{className:`personal-goal-tools`,ref:x,children:[(0,B.jsxs)(`button`,{"aria-expanded":v,"aria-haspopup":`menu`,"aria-label":_(`header.goalSettingsDescription`),className:`personal-goal-tools-trigger`,onClick:()=>y(e=>!e),ref:b,title:_(`header.goalSettingsDescription`),type:`button`,children:[(0,B.jsx)(Gm,{"aria-hidden":!0,size:16}),(0,B.jsx)(`span`,{children:_(`header.goalSettings`)}),(0,B.jsx)(tm,{"aria-hidden":!0,size:13})]}),v?(0,B.jsxs)(`fieldset`,{"aria-label":_(`header.goalSettings`),className:`personal-goal-tools-menu`,children:[(0,B.jsxs)(`button`,{onClick:()=>S(i),type:`button`,children:[(0,B.jsx)(ym,{"aria-hidden":!0,size:17}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:_(`header.goalDetails`)})})]}),(0,B.jsxs)(`button`,{onClick:()=>S(r),type:`button`,children:[(0,B.jsx)(Gm,{"aria-hidden":!0,size:17}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:_(`header.goalCapabilities`)})})]})]}):null]}):null,f?(0,B.jsxs)(`span`,{className:`personal-read-only-source`,title:_(`header.readOnlySourceDescription`,{source:f}),children:[(0,B.jsx)(pm,{size:15}),f,(0,B.jsx)(`small`,{children:_(`common.readOnly`)})]}):(0,B.jsx)(Cy,{ariaLabel:_(`header.selectChatRuntime`),className:`personal-agent-select`,icon:(0,B.jsx)(Zp,{size:16}),onChange:l,options:e.map(e=>({disabled:!e.available,label:`${e.label}${e.available?``:` · ${_(`header.agentUnavailable`)}`}`,value:e.agentId})),prefixLabel:_(`header.chatRuntime`),value:p}),(0,B.jsxs)(`span`,{className:`personal-live-indicator`,children:[(0,B.jsx)(`i`,{}),_(`header.live`)]}),o?(0,B.jsxs)(`span`,{className:`personal-refresh-control is-${d??`idle`}`,children:[d===`loading`?(0,B.jsx)(`small`,{children:_(`header.refreshing`)}):d===`done`?(0,B.jsx)(`small`,{children:_(`header.refreshDone`)}):d===`error`?(0,B.jsx)(`small`,{children:_(`header.refreshFailed`)}):null,(0,B.jsx)(`button`,{"aria-label":_(d===`loading`?`header.refreshing`:`header.refresh`),className:`personal-icon-button`,disabled:d===`loading`,onClick:o,type:`button`,children:(0,B.jsx)(Im,{className:d===`loading`?`is-spinning`:void 0,size:17})})]}):null]})]})}function Ty({attention:e,onSelect:t}){let{t:n}=Ji(),r=Zi(e.updatedAt,n);return(0,B.jsxs)(`button`,{className:`personal-timeline-row personal-attention-row`,"data-testid":`personal-browse-row`,onClick:t,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-row-icon is-attention`,children:(0,B.jsx)(im,{size:18})}),(0,B.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,B.jsxs)(`small`,{children:[e.goalTitle??e.goalId,` · `,n(`home.lane.needsYou`),r?` · ${n(`tasks.waitingAge`,{age:r})}`:``]}),(0,B.jsx)(`strong`,{children:e.text})]}),(0,B.jsx)(`span`,{className:`personal-priority-dot is-${e.priority??(e.blocking?`high`:`medium`)}`}),(0,B.jsx)(`span`,{className:`personal-row-status ${e.blocking?`is-blocking`:`is-pending`}`,children:e.blocking?n(`tasks.blocked`):n(`tasks.pending`)}),(0,B.jsx)(nm,{size:17})]})}var Ey=/(`[^`\n]+`)|(\*\*[^*\n]+(\*[^*\n]*)?\*\*)|(\[[^\]\n]{1,120}\]\(https?:\/\/[^)\s]+\))/g;function Dy(e,t){let n=[],r=0,i=0;for(let a of e.matchAll(Ey)){let o=a.index??0;o>r&&n.push(e.slice(r,o));let s=a[0],c=`${t}-i${i++}`;if(s.startsWith("`"))n.push((0,B.jsx)(`code`,{className:`personal-md-code`,children:s.slice(1,-1)},c));else if(s.startsWith(`**`))n.push((0,B.jsx)(`strong`,{children:s.slice(2,-2)},c));else{let e=s.indexOf(`](`),t=s.slice(1,e),r=s.slice(e+2,-1);n.push((0,B.jsx)(`a`,{className:`personal-md-link`,href:r,rel:`noreferrer`,target:`_blank`,children:t},c))}r=o+s.length}return r{r.length>0&&(n.push({type:`paragraph`,lines:r}),r=[])},a=0;for(;a{let n=`b${t}`;if(e.type===`code`)return(0,B.jsx)(`pre`,{className:`personal-md-pre`,children:(0,B.jsx)(`code`,{children:e.text})},n);if(e.type===`heading`)return(0,B.jsx)(`p`,{className:`personal-md-heading is-h${e.level}`,children:Dy(e.text,n)},n);if(e.type===`list`){let t=e.items.map((e,t)=>(0,B.jsx)(`li`,{children:Dy(e,`${n}-${t}`)},`${n}-${t}`));return e.ordered?(0,B.jsx)(`ol`,{className:`personal-md-list`,children:t},n):(0,B.jsx)(`ul`,{className:`personal-md-list`,children:t},n)}return(0,B.jsx)(`p`,{children:e.lines.map((e,t)=>(0,B.jsxs)(z.Fragment,{children:[t>0?(0,B.jsx)(`br`,{}):null,Dy(e,`${n}-${t}`)]},`${n}-${t}`))},n)})})}function My({onSelect:e,output:t}){let{t:n}=Ji(),r=t.kind===`report`?gm:hm;return(0,B.jsxs)(`button`,{className:`personal-timeline-row personal-output-row`,"data-output-kind":t.kind,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-row-icon is-output`,children:(0,B.jsx)(r,{size:18})}),(0,B.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,B.jsxs)(`small`,{children:[t.goalTitle??t.goalId,` · `,t.agentLabel??`LoopX`]}),(0,B.jsx)(`strong`,{children:t.title}),t.summary?(0,B.jsx)(`span`,{children:t.summary}):null,t.report?(0,B.jsxs)(`small`,{children:[n(`files.reportDelta`,{added:t.report.addedCount,changed:t.report.changedCount}),` · `,n(`files.verifiedReport`)]}):null]}),t.createdAt?(0,B.jsx)(`time`,{children:t.createdAt}):null,(0,B.jsx)(nm,{size:17})]})}var Ny={completed:`runs.completed`,failed:`runs.failed`,interrupted:`runs.interrupted`,queued:`runs.queued`,running:`runs.running`,waiting:`runs.waiting`};function Py({onSelect:e,run:t}){let{t:n}=Ji(),r=t.totalSteps>0?Math.min(100,t.completedSteps/t.totalSteps*100):0;return(0,B.jsxs)(`button`,{"aria-label":`${n(`tasks.viewExecution`)}:${t.title}`,className:`personal-timeline-row personal-run-row`,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-row-icon is-run`,children:(0,B.jsx)(Zp,{size:18})}),(0,B.jsxs)(`span`,{className:`personal-run-identity`,children:[(0,B.jsx)(`small`,{children:t.goalTitle}),(0,B.jsx)(`strong`,{children:t.agentLabel})]}),(0,B.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,B.jsx)(`strong`,{children:t.title}),(0,B.jsx)(`small`,{children:t.latestActivity})]}),(0,B.jsxs)(`span`,{className:`personal-run-progress`,"aria-label":`${t.completedSteps}/${t.totalSteps}`,children:[(0,B.jsxs)(`small`,{children:[t.completedSteps,`/`,t.totalSteps]}),(0,B.jsx)(`i`,{children:(0,B.jsx)(`b`,{style:{width:`${r}%`}})})]}),(0,B.jsxs)(`span`,{className:`personal-row-status is-${t.status}`,children:[t.status===`running`?(0,B.jsx)(Cm,{className:`personal-spin`,size:14}):null,n(Ny[t.status])]}),t.sessionId?(0,B.jsx)(`span`,{className:`personal-run-open-label`,children:n(`tasks.viewExecution`)}):null,(0,B.jsx)(nm,{size:17})]})}function Fy({onSelect:e,schedule:t}){let{t:n}=Ji(),r=t.scheduleKind===`heartbeat`;return(0,B.jsxs)(`button`,{"aria-label":`${r?`Heartbeat`:n(`tasks.scheduled`)}:${t.label};${t.status??`active`}`,className:`personal-schedule-row`,onClick:e,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-schedule-icon`,children:r?(0,B.jsx)(Fm,{size:17}):(0,B.jsx)($p,{size:17})}),(0,B.jsxs)(`span`,{className:`personal-schedule-copy`,children:[(0,B.jsx)(`small`,{children:n(r?`schedule.heartbeat`:`schedule.monitor`)}),(0,B.jsx)(`strong`,{children:t.label}),(0,B.jsx)(`p`,{children:t.schedule??n(`schedule.summary`)})]}),(0,B.jsx)(`span`,{className:`personal-schedule-status is-${t.status??`active`}`,children:t.status===`paused`?n(`schedule.paused`):n(`schedule.active`)}),(0,B.jsx)(nm,{size:16})]})}function Iy({items:e,onSelect:t,selectedGoal:n}){let{t:r}=Ji();if(e.length===0)return(0,B.jsxs)(`div`,{className:`personal-timeline-empty`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Km,{size:20})}),(0,B.jsx)(`strong`,{children:r(n?`timeline.emptyGoal`:`timeline.emptyWorkspace`)}),(0,B.jsx)(`p`,{children:r(n?`timeline.emptyGoalDescription`:`timeline.emptyWorkspaceDescription`)})]});let i=[...e].reverse().find(e=>e.kind===`message`&&e.message.role!==`user`||e.kind===`proposal`&&[`applied`,`stale`,`error`,`gated`].includes(e.proposal.status)||e.kind===`run`&&e.run.status===`completed`),a=i?.kind===`message`?`${i.message.agentLabel??r(`header.manager`)}:${i.message.pending?r(`timeline.pending`):i.message.text}`:i?.kind===`proposal`?`${i.proposal.title}:${i.proposal.status}`:i?.kind===`run`?r(`timeline.runCompleted`,{run:i.run.title}):``,o=e.filter(e=>e.kind===`proposal`&&e.proposal.status===`gated`),s=e.filter(e=>e.kind!==`proposal`),c=e.filter(e=>e.kind===`proposal`&&e.proposal.status!==`gated`);function l(e){return e.kind===`attention`?(0,B.jsx)(Ty,{attention:e.attention,onSelect:()=>t({item:e.attention,kind:`attention`})},e.id):e.kind===`run`?(0,B.jsx)(Py,{onSelect:()=>t({item:e.run,kind:`run`}),run:e.run},e.id):e.kind===`output`?(0,B.jsx)(My,{onSelect:()=>t({item:e.output,kind:`output`}),output:e.output},e.id):e.kind===`schedule`?(0,B.jsx)(Fy,{onSelect:()=>t({item:e.schedule,kind:`schedule`}),schedule:e.schedule},e.id):e.kind===`proposal`?(0,B.jsxs)(`button`,{className:`personal-proposal-row is-${e.proposal.status}`,onClick:()=>t({item:e.proposal,kind:`proposal`}),type:`button`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Km,{size:17})}),(0,B.jsxs)(`span`,{children:[(0,B.jsxs)(`small`,{children:[e.proposal.actionKind,` · `,e.proposal.status]}),(0,B.jsx)(`strong`,{children:e.proposal.title}),(0,B.jsx)(`p`,{children:e.proposal.impact})]}),(0,B.jsx)(`b`,{children:e.proposal.status===`gated`?r(`timeline.review`):e.proposal.primaryLabel??r(`timeline.reviewAndConfirm`)})]},e.id):(0,B.jsxs)(`article`,{className:`personal-message is-${e.message.role}`,children:[e.message.role===`user`?null:(0,B.jsx)(`span`,{className:`personal-message-avatar`,children:(0,B.jsx)(Zp,{size:17})}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:e.message.role===`user`?r(`common.you`):e.message.agentLabel??r(`header.manager`)}),e.message.time?(0,B.jsx)(`time`,{children:e.message.time}):null]}),e.message.attachments?.length?(0,B.jsx)(`div`,{className:`personal-message-images`,children:e.message.attachments.map(e=>(0,B.jsx)(`img`,{alt:e.name,src:e.dataUrl},e.id))}):null,e.message.role===`user`?(0,B.jsx)(`p`,{children:e.message.text}):(0,B.jsx)(jy,{text:e.message.text}),e.message.pending?(0,B.jsx)(`span`,{className:`personal-message-pending`,children:r(`timeline.pending`)}):null]})]},e.id)}return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{"aria-atomic":`true`,"aria-live":`polite`,className:`personal-live-region`,role:`status`,children:a}),(0,B.jsxs)(`div`,{className:`personal-channel-timeline`,children:[s.map(l),o.length?(0,B.jsxs)(`details`,{className:`personal-gated-summary`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Km,{size:16})}),(0,B.jsx)(`strong`,{children:r(`timeline.waitingConfirmation`)}),(0,B.jsx)(`small`,{children:r(`timeline.gateHistory`,{count:o.length})})]}),(0,B.jsx)(`div`,{children:o.map(l)})]}):null,c.map(l)]})]})}function Ly({goal:e}){let{t}=Ji(),n={connected:t(`acceptance.connected`),mapped:t(`acceptance.mapped`),refreshed:t(`acceptance.refreshed`),adapter_inspected:t(`acceptance.inspected`),run_recorded:t(`acceptance.recorded`),reward_judged:t(`acceptance.judged`),operator_approved:t(`acceptance.approved`),controller_ready:t(`acceptance.ready`),attention_queue:t(`acceptance.attentionSource`),agent_vision:t(`acceptance.visionSource`),todo_projection:t(`acceptance.todoSource`),current_run:t(`acceptance.runSource`)},r=e=>n[e]??t(`acceptance.unknown`),i=e.acceptanceObservation,a=e.loadState||!i||i.goal_id!==e.goalId||i.coverage===`unavailable`;return(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-acceptance`,"aria-label":t(`acceptance.title`),children:[(0,B.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,B.jsx)(`h3`,{children:t(`acceptance.title`)}),(0,B.jsx)(`em`,{children:t(`common.readOnly`)})]}),(0,B.jsx)(`p`,{role:`status`,children:t(a?`acceptance.unavailable`:`acceptance.partial`)}),!a&&i?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h4`,{children:t(`acceptance.gaps`)}),i.acceptance_gaps.length?i.acceptance_gaps.map((e,n)=>(0,B.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,B.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.owner`)}),(0,B.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,B.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.observed`)}),(0,B.jsx)(`dd`,{children:e.observed_at??t(`acceptance.unknown`)})]})]})]},`${e.kind}:${e.owner}:${n}`)):(0,B.jsx)(`p`,{children:t(`acceptance.noGaps`)}),(0,B.jsx)(`h4`,{children:t(`acceptance.guards`)}),i.guards.length?i.guards.map((e,n)=>(0,B.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,B.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.owner`)}),(0,B.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),e.blocks_agent?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.agent`)}),(0,B.jsx)(`dd`,{children:e.blocks_agent})]}):null,e.todo_id?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.task`)}),(0,B.jsx)(`dd`,{children:e.todo_id})]}):null,(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,B.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.scope`)}),(0,B.jsx)(`dd`,{children:e.decision_scope??t(`acceptance.unknown`)})]})]})]},`${e.todo_id}:${n}`)):(0,B.jsx)(`p`,{children:t(`acceptance.noGuards`)}),(0,B.jsx)(`h4`,{children:t(`acceptance.next`)}),(0,B.jsx)(`p`,{children:i.next_action??t(`acceptance.unknown`)}),(0,B.jsxs)(`details`,{children:[(0,B.jsxs)(`summary`,{children:[t(`acceptance.historical_progress`),` · `,i.historical_progress.length]}),(0,B.jsx)(`p`,{children:t(`acceptance.historical`)}),i.historical_progress.map(e=>(0,B.jsxs)(`p`,{children:[(0,B.jsx)(`strong`,{children:r(e.kind)}),` · `,e.observed_at??t(`acceptance.unknown`),` `,e.evidence_refs.join(`, `)]},e.kind))]}),i.missing_sources.length?(0,B.jsxs)(`p`,{children:[t(`acceptance.missing`),` `,i.missing_sources.map(r).join(`, `)]}):null,i.truncated?(0,B.jsx)(`p`,{children:t(`acceptance.truncated`)}):null]}):null]})}function Ry({item:e,successor:t,onSelect:n}){let{t:r}=Ji(),i=e.details;return(0,B.jsxs)(`section`,{className:`personal-detail-card`,"aria-label":r(`attentionDetail.title`),children:[(0,B.jsx)(`h3`,{children:r(`attentionDetail.title`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.request`)}),(0,B.jsx)(`dd`,{children:r(i?.interaction===`decision`?`attentionDetail.decision`:`attentionDetail.unknownRequest`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`common.status`)}),(0,B.jsx)(`dd`,{children:r(`attentionDetail.${i?.lifecycle??`unknown`}`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`drawer.reason`)}),(0,B.jsx)(`dd`,{children:i?.reason??e.explanation??r(`attentionDetail.unknownReason`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Todo`}),(0,B.jsx)(`dd`,{children:e.todoId})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.targetTodo`)}),(0,B.jsx)(`dd`,{children:i?.unblocksTodoId??r(`attentionDetail.notProvided`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.targetAgent`)}),(0,B.jsx)(`dd`,{children:i?.blocksAgent??r(`attentionDetail.notProvided`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.scope`)}),(0,B.jsx)(`dd`,{children:i?.decisionScope?`${i.decisionScope.kind} · ${i.decisionScope.granularity} · ${i.decisionScope.scopeKey}`:r(`attentionDetail.notProvided`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`drawer.evidence`)}),(0,B.jsx)(`dd`,{children:i?.evidence??e.evidence??r(`drawer.decisionDefaultEvidence`)})]})]}),i?.supersededBy?(0,B.jsxs)(`p`,{children:[r(`attentionDetail.replacement`),`: `,i.supersededBy]}):null,t&&n?(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>n(t),type:`button`,children:r(`attentionDetail.openReplacement`)}):null,(0,B.jsx)(`p`,{children:r(`attentionDetail.boundary`)})]})}function zy(e){return e.replace(/\s+/gu,` `).trim()}function By(e,t){let n=RegExp(`(?:不要|不需要|无需|禁止|别|暂不|do not\\b|don't\\b|without\\b).{0,10}(?:${t.source})`,`iu`),r=RegExp(`(?:${t.source}).{0,10}(?:不要|不需要|无需|禁止|关闭)`,`iu`),i=RegExp(`disable\\b.{0,10}(?:${t.source})|(?:turn|switch|set)\\b.{0,10}(?:${t.source}).{0,10}\\boff\\b|(?:${t.source})\\s+(?:is\\s+)?disabled\\b`,`iu`);return n.test(e)||r.test(e)||i.test(e)}function Vy(e){return/(我现在该做什么|下一步|哪些\s*Goal\s*在等我|需要我|谁在等我|Agent\s*在做什么|当前进度|总结(?:今天)?进展)/iu.test(e)}function Hy(e){let t=/(怎么|如何|为什么|给.*建议|分析一下|解释|只读)/u.test(e),n=/(解决一下|修复一下|处理一下|执行一下|改一下|跑(?:一下)?测试|rebase|push|提交|推送)/iu.test(e);return!t&&n&&/(帮我|请|给我|直接|现在|开始|bytedcli|codebase|git|rebase|push|提交|推送)/iu.test(e)}function Uy(e){return zy(e).toLowerCase().match(/(?:^|[\s,,;;:((:]|到|至)(?todo_done:todo_[a-z0-9_-]{3,64}|pr_merged:(?:(?:[a-z0-9_.-]{1,80})\/(?:[a-z0-9_.-]{1,100}))?#[1-9][0-9]{0,8}|capacity_available:[a-z][a-z0-9_:-]{0,63}|resume_at:[1-9][0-9]{3}-[0-9]{2}-[0-9]{2}t[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,3})?(?:z|[+-][0-9]{2}:[0-9]{2}))(?=$|[\s,,。;;))])/iu)?.groups?.condition??null}function Wy(e,t){let n=zy(e),r=[],i=t.agents.find(e=>{let t=n.toLowerCase();return t.includes(e.agentId.toLowerCase())||t.includes(e.label.toLowerCase())}),a=t.todos.find(e=>n.includes(e.todoId)||n.includes(e.text)),o=/(刚刚|已经|已)(?:经)?\s*(新增|创建|添加)(?:的)?\s*(todo|待办|任务)/iu.test(n),s=!!t.goalId&&!By(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n);if(!t.goalId&&!By(n,/goal|目标/iu)&&/(创建|新建|设置|create|start|set up).{0,24}(goal|目标)/iu.test(n)&&r.push({actionKind:`goal.create`,confidence:.97,normalizedParameters:{heartbeat_enabled:!By(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n)}}),t.goalId&&s&&r.push({actionKind:`heartbeat.bind`,confidence:.96,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&!s&&!By(n,/定时|监控|监测|持续观察|scheduled check|monitor/iu)&&/(定时|监控|监测|每.{0,8}(分钟|小时|天)|持续观察|scheduled check|monitor|every.{0,12}(minute|hour|day)|daily)/iu.test(n)&&r.push({actionKind:`monitor.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&i&&!By(n,/绑定|负责|接管|管理/iu)&&/((让|交给).{0,20}(管理|负责|接管).{0,8}(goal|目标)|(绑定).{0,12}(goal|目标)|(goal|目标).{0,12}(交给|绑定|负责|接管))/iu.test(n)&&r.push({actionKind:`agent.bind`,confidence:.96,normalizedParameters:{agent_id:i.agentId,goal_id:t.goalId}}),t.goalId&&!o&&!By(n,RegExp(`todo|待办|任务`,`iu`))&&/(创建|新建|新增|添加|加一个|记一个).{0,16}(todo|待办|任务)|(todo|待办|任务).{0,12}(创建|新建|新增|添加)|(?:create|add)(?:\s+(?:a|an|new))?\s+(?:todo|task)|(?:todo|task).{0,12}(?:create|add)/iu.test(n)&&r.push({actionKind:`todo.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&Hy(n)&&r.push({actionKind:`todo.create`,confidence:.9,normalizedParameters:{goal_id:t.goalId,start_execution:!0}}),t.goalId&&a){let e=!By(n,/完成|做完|关闭/u)&&/完成|做完|关闭/u.test(n)?`complete`:!By(n,/阻塞|卡住/u)&&/阻塞|卡住/u.test(n)?`block`:!By(n,/暂缓|稍后|推迟/u)&&/暂缓|稍后|推迟/u.test(n)?`defer`:i&&!By(n,/交给|分配给|改派/u)&&/交给|分配给|改派/u.test(n)?`reassign`:null;if(e){let i=e===`defer`?Uy(n):null;if(e===`defer`&&!i)return{actionKind:`todo.update`,confidence:.97,missingFields:[`resume_when`],normalizedParameters:{goal_id:t.goalId,operation:e,todo_id:a.todoId},route:`clarify`};r.push({actionKind:`todo.update`,confidence:.97,normalizedParameters:{goal_id:t.goalId,operation:e,...i?{resume_when:i}:{},todo_id:a.todoId}})}}let c=[...new Map(r.map(e=>[e.actionKind,e])).values()];return c.length>1?{actionKind:null,confidence:.4,missingFields:[`single_intent`],normalizedParameters:{},route:`clarify`}:c.length===1?{...c[0],missingFields:[],route:`typed_action`}:!t.goalId&&Vy(n)?{actionKind:null,confidence:.98,missingFields:[],normalizedParameters:{},route:`projection`}:{actionKind:null,confidence:.75,missingFields:[],normalizedParameters:{},route:`agent_chat`}}function Gy(e,t,n){if(!e)return{};if(!t.trim())return{modelConfig:null};let r={model:t.trim()};return n&&(r.reasoning_effort=n),{modelConfig:r}}var Ky=[`a[href]`,`button:not([disabled])`,`textarea:not([disabled])`,`select:not([disabled])`,`input:not([disabled])`,`[tabindex]:not([tabindex='-1'])`].join(`,`),qy=[{key:`drawer.taskBlock`,operation:`block`},{key:`drawer.taskSuccessor`,operation:`successor_create`}],Jy=[{key:`drawer.decisionReject`,resolution:`reject`},{key:`drawer.decisionDefer`,resolution:`defer`}],Yy=Array.from({length:32},(e,t)=>t+1),Xy=/^[a-z][a-z0-9_.-]{0,63}$/u;function Zy(e){let t=String(e??``).trim().toLowerCase();return Xy.test(t)?t:null}function Qy(e,t){return e.enabled===t.enabled&&e.maxChildren===t.maxChildren&&JSON.stringify(e.modelConfig??null)===JSON.stringify(t.modelConfig??null)&&[...e.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)===[...t.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)}function $y({agents:e,attentionHistory:t=[],onSelectAttention:n,callbacks:r,goalNotifications:i=[],goals:a=[],inspectorExpanded:o=!1,larkConnections:s=[],onClose:c,onToggleInspectorSize:l,readOnly:u=!1,runs:d=[],selection:f}){let{locale:p,t:m}=Ji(),[h,g]=(0,z.useState)(``),[_,v]=(0,z.useState)(!1),[y,b]=(0,z.useState)(`idle`),[x,S]=(0,z.useState)(`record`),[C,w]=(0,z.useState)([]),[T,E]=(0,z.useState)(null),[D,O]=(0,z.useState)(2),[ee,te]=(0,z.useState)(``),[ne,k]=(0,z.useState)(``),[A,j]=(0,z.useState)(`idle`),[M,N]=(0,z.useState)(null),[P,F]=(0,z.useState)(null),re=(0,z.useRef)(null),ie=(0,z.useRef)(null),[I,ae]=(0,z.useState)(e.find(e=>e.available)?.agentId??`codex`),[L,oe]=(0,z.useState)(``),se=(0,z.useRef)(null),ce=(0,z.useRef)(null),le=(0,z.useRef)(null),ue=(0,z.useRef)(null),de=f.kind===`run`?`run:${f.item.runId}`:f.kind===`proposal`?`proposal:${f.item.previewId}`:f.kind===`todo`?`todo:${f.item.todoId}`:f.kind===`attention`?`attention:${f.item.todoId}`:f.kind===`output`?`output:${f.item.outputId}`:f.kind===`schedule`?`schedule:${f.item.scheduleId}`:`goal:${f.item.goalId}`;(0,z.useEffect)(()=>{b(`idle`),v(!1),S(`record`),oe(``);let e=f.kind===`goal`?f.item.subagentExecution:void 0;w(e?.allowedDomains??[]),te(e?.modelConfig?.model??``),k(e?.modelConfig?.reasoning_effort??``),O(e?.maxChildren?Math.min(e.maxChildren,32):2),E(null),j(`idle`),N(null),F(null),re.current=e??null,ie.current=null},[de]);let fe=f.kind===`goal`?f.item.subagentExecution:void 0;(0,z.useEffect)(()=>{let e=re.current,t=fe?!e||!Qy(e,fe):e!==null;if(re.current=fe??null,!P){t&&fe&&(w(fe.allowedDomains),te(fe.modelConfig?.model??``),k(fe.modelConfig?.reasoning_effort??``),O(fe.maxChildren||2),E(null),j(`idle`),N(null));return}let n=ie.current;(!fe||Qy(P,fe)||n&&!Qy(n,fe))&&(fe&&(w(fe.allowedDomains),te(fe.modelConfig?.model??``),k(fe.modelConfig?.reasoning_effort??``),O(fe.maxChildren||2)),ie.current=null,F(null))},[fe,P]),(0,z.useEffect)(()=>{let e=document.activeElement;e instanceof HTMLElement&&!ce.current?.contains(e)&&(le.current=e);let t=window.requestAnimationFrame(()=>ue.current?.focus());return()=>window.cancelAnimationFrame(t)},[de]);let pe=(0,z.useCallback)(()=>{let e=le.current;c(),window.requestAnimationFrame(()=>e?.focus())},[c]);(0,z.useEffect)(()=>{function e(e){if(e.key===`Escape`){e.preventDefault(),pe();return}if(e.key===`Tab`&&f.kind!==`todo`){let t=Array.from(ce.current?.querySelectorAll(Ky)??[]).filter(e=>!e.hasAttribute(`disabled`)&&e.getAttribute(`aria-hidden`)!==`true`);if(t.length===0)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n.focus())}}return document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`keydown`,e)}},[pe,f.kind]);let me=f.kind===`attention`?m(`drawer.titleAttention`):f.kind===`todo`?m(`drawer.taskDetails`):f.kind===`run`?m(`drawer.runDetails`):f.kind===`output`?m(`drawer.titleOutput`):f.kind===`proposal`?m(f.item.status===`applied`?`drawer.titleProposalApplied`:`drawer.titleProposalConfirm`):f.kind===`schedule`?f.item.scheduleKind===`heartbeat`?`Heartbeat`:m(`drawer.titleSchedule`):m(`drawer.goalDetails`),he=f.kind===`proposal`?f.item.goalId??`manager`:f.item.goalId,ge=f.kind===`attention`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`todo`||f.kind===`run`?f.item.goalTitle:f.kind===`output`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`goal`?f.item.title:f.kind===`schedule`?m(`drawer.goalAutoRun`):f.item.goalId?m(`drawer.goalChanges`):m(`drawer.managerChanges`),_e=f.kind===`goal`?d.find(e=>e.goalId===f.item.goalId&&!!e.sessionId)??d.find(e=>e.goalId===f.item.goalId):null,ve=f.kind===`run`&&(f.item.completedSteps>0||!!f.item.latestActivity||!!f.item.outputs?.length),ye=f.kind===`attention`?Zi(f.item.updatedAt,m):null,be=Uy(L);async function xe(){f.kind!==`run`||!h.trim()||(await r.onCorrectRun?.(f.item,h.trim()),g(``))}async function Se(e,t,n,i){if(t===`successor_create`){await r.onPreviewAction?.({actionKind:`todo.create`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-successor-${e.todoId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,text:m(`drawer.taskSuccessorText`,{task:e.text})},summary:m(`drawer.taskSuccessorSummary`,{task:e.text})});return}await r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:e.claimedBy??I,goal_id:e.goalId,operation:t,...t===`block`?{note:m(`drawer.taskSuccessorNote`)}:{},...t===`defer`&&i?{resume_when:i}:{},todo_id:e.todoId},summary:`${n}:${e.text}`})}async function Ce(e,t,n){u||!qd(e)||await r.onPreviewAction?.({actionKind:`gate.resolve`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-decision-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,decision:t,todo_id:e.todoId},summary:`${n}:${e.text}`})}let we=f.kind===`goal`?P??f.item.subagentExecution??{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0}:{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0},Te=A===`previewing`||A===`applying`,Ee=(()=>{if(f.kind!==`goal`)return[];let e=new Map;for(let t of we.allowedDomains){let n=Zy(t);n&&e.set(n,{matchingTodoCount:0,value:n})}if(we.domainCandidates)for(let t of we.domainCandidates){let n=Zy(t.domain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+t.matchingTodoCount,value:n})}else for(let t of f.item.agentTodos){if(t.done||t.taskClass!==`advancement_task`)continue;let n=Zy(t.taskDomain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+1,value:n})}return[...e.values()]})();function R(){w(we.allowedDomains),te(we.modelConfig?.model??``),k(we.modelConfig?.reasoning_effort??``),O(we.maxChildren||2),E(null),j(`idle`),N(null)}function De(){let e=[...new Set(C.map(e=>Zy(e)))];return e.every(e=>!!e)?e:null}function Oe(e,t){w(n=>t?[...n,e].filter((e,t,n)=>n.indexOf(e)===t):n.filter(t=>t!==e)),N(null),j(`idle`),E(null)}async function ke(e,t=e){if(f.kind!==`goal`||!r.onPreviewGoalSubagentConfiguration)return;let n=e?De():[];if(t&&!ee.trim()&&ne){j(`error`),E(m(`drawer.subagentModelRequired`));return}if(e&&!n){j(`error`),E(m(`drawer.subagentDomainInvalid`)),N(null);return}let i={allowedDomains:n??[],enabled:e,goalId:f.item.goalId,maxChildren:e?D:0,...Gy(t,ee,ne)};j(`previewing`),E(m(`drawer.subagentPreviewing`)),N(null);try{let e=await r.onPreviewGoalSubagentConfiguration(i);if(!e.changed){ie.current=fe??null,F({...e.configuration,domainCandidates:we.domainCandidates}),w(e.configuration.allowedDomains),te(e.configuration.modelConfig?.model??``),k(e.configuration.modelConfig?.reasoning_effort??``),O(e.configuration.maxChildren||2),j(`success`),E(m(`drawer.subagentNoChange`));return}N({...i,changed:e.changed,previewId:e.previewId}),j(`ready`),E(m(`drawer.subagentPreviewReady`))}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentPreviewFailed`))}}async function Ae(){if(!(!M||!r.onApplyGoalSubagentConfiguration)){j(`applying`),E(m(`drawer.subagentApplying`));try{let e=await r.onApplyGoalSubagentConfiguration({allowedDomains:M.allowedDomains,enabled:M.enabled,goalId:M.goalId,maxChildren:M.maxChildren,modelConfig:M.modelConfig,previewId:M.previewId});ie.current=fe??null,F({...e,domainCandidates:we.domainCandidates}),w(e.allowedDomains),te(e.modelConfig?.model??``),k(e.modelConfig?.reasoning_effort??``),O(e.maxChildren||2),j(`success`),E(m(`drawer.subagentApplied`)),N(null);try{await r.onRefresh?.()}catch{j(`warning`),E(m(`drawer.subagentAppliedRefreshFailed`))}}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentApplyFailed`))}}}return(0,B.jsxs)(`div`,{"aria-labelledby":`personal-drawer-title`,"aria-modal":f.kind===`todo`?void 0:`true`,className:`personal-context-drawer`,"data-context-kind":f.kind,ref:ce,role:`dialog`,children:[(0,B.jsxs)(`header`,{className:`personal-drawer-header${f.kind===`todo`?` is-task-inspector`:``}`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`h2`,{id:`personal-drawer-title`,ref:ue,tabIndex:-1,children:me}),(0,B.jsx)(`p`,{children:ge})]}),(0,B.jsxs)(`div`,{className:`personal-drawer-header-actions`,children:[f.kind===`todo`&&l?(0,B.jsx)(`button`,{"aria-label":m(o?`drawer.inspectorHalf`:`drawer.inspectorFull`),className:`personal-icon-button personal-inspector-size`,onClick:l,title:m(o?`drawer.inspectorHalfView`:`drawer.inspectorFullView`),type:`button`,children:o?(0,B.jsx)(Om,{size:17}):(0,B.jsx)(wm,{size:17})}):null,(0,B.jsxs)(`button`,{"aria-label":m(`drawer.closeDetail`,{context:ge}),className:`personal-icon-button personal-drawer-close`,onClick:pe,ref:se,type:`button`,children:[(0,B.jsx)(Gp,{className:`personal-mobile-back`,size:18}),(0,B.jsx)($m,{className:`personal-desktop-close`,size:18})]})]})]}),(0,B.jsxs)(`div`,{className:`personal-drawer-body`,children:[f.kind===`attention`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card is-attention`,children:[(0,B.jsx)(`small`,{children:f.item.blocking?m(`drawer.attentionBlocking`):m(`drawer.attentionWaiting`)}),(0,B.jsx)(`h3`,{children:f.item.text}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,B.jsx)(`dd`,{children:f.item.priority??`medium`})]}),ye?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`common.waiting`)}),(0,B.jsx)(`dd`,{children:m(`tasks.waitingAge`,{age:ye})})]}):null]})]}),(0,B.jsx)(Ry,{item:f.item,onSelect:n,successor:Kd(f.item,t)}),!u&&qd(f.item)?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void Ce(f.item,`approve`,m(`common.confirm`)),type:`button`,children:[(0,B.jsx)(em,{size:17}),m(`drawer.decisionReview`)]}),(0,B.jsxs)(`details`,{className:`personal-compact-menu`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(dm,{size:17}),m(`drawer.decisionMore`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`button`,{onClick:()=>void r.onExplainDecision?.(f.item),type:`button`,children:[(0,B.jsx)(Em,{size:16}),m(`drawer.explainDecision`)]}),Jy.map(e=>(0,B.jsx)(`button`,{onClick:()=>void Ce(f.item,e.resolution,m(e.key)),type:`button`,children:m(e.key)},e.resolution))]})]})]}):null]}):null,f.kind===`todo`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-task-inspector-summary`,children:[(0,B.jsxs)(`div`,{className:`personal-task-inspector-status`,children:[(0,B.jsxs)(`span`,{className:f.item.done?`is-done`:f.item.status===`blocked`?`is-blocked`:`is-open`,children:[(0,B.jsx)(`i`,{}),f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)]}),f.item.priority?(0,B.jsx)(`span`,{children:f.item.priority}):null,(0,B.jsx)(`span`,{children:f.item.taskClass===`advancement_task`?m(`drawer.taskAdvancement`):f.item.taskClass??m(`drawer.taskOrdinary`)})]}),(0,B.jsx)(`h3`,{children:f.item.text})]}),(0,B.jsxs)(`section`,{"aria-label":m(`drawer.taskInfo`),className:`personal-task-inspector-fields`,children:[(0,B.jsx)(`h4`,{children:m(`drawer.taskInfo`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`common.owner`)}),(0,B.jsx)(`dd`,{children:f.item.ownerLabel??f.item.claimedBy??m(`drawer.notAssigned`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`common.status`)}),(0,B.jsx)(`dd`,{children:f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,B.jsx)(`dd`,{children:f.item.priority??m(`drawer.notSet`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.dependencies`)}),(0,B.jsx)(`dd`,{children:f.item.dependencies?.join(` · `)||m(`common.none`)})]}),f.item.status===`deferred`||f.item.resumeWhen?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.resumeWhen`)}),(0,B.jsx)(`dd`,{children:f.item.resumeWhen||m(`drawer.notSet`)})]}):null,f.item.resumeWhen?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.resumeState`)}),(0,B.jsx)(`dd`,{children:f.item.resumeReady?m(`drawer.resumeReady`):m(`drawer.resumePending`)})]}):null,f.item.resumeReceiptId?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.resumeReceipt`)}),(0,B.jsx)(`dd`,{children:f.item.resumeReceiptId})]}):null,(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.nextTransition`)}),(0,B.jsx)(`dd`,{children:f.item.nextTransition??(f.item.done?m(`drawer.taskNextCompleted`):f.item.resumeReady?m(`drawer.taskNextResumeReady`):f.item.status===`deferred`?m(`drawer.taskNextDeferred`):m(`drawer.taskNextOpen`))})]})]})]}),!u&&!f.item.done?(0,B.jsxs)(`div`,{className:`personal-task-inspector-actions`,"aria-label":m(`drawer.taskActions`),children:[(0,B.jsxs)(`details`,{className:`personal-task-management`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(dm,{size:16}),m(`drawer.taskManage`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:m(`drawer.reassign`)}),(0,B.jsxs)(`label`,{className:`personal-inline-agent-select`,children:[m(`drawer.reassign`),(0,B.jsx)(`select`,{"aria-label":m(`drawer.reassign`),onChange:e=>ae(e.target.value),value:I,children:e.filter(e=>e.available).map(e=>(0,B.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:f.item.goalId,kind:`todo`,todo_id:f.item.todoId},idempotencyKey:`workspace-todo-${f.item.todoId}-reassign-${I}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:I,goal_id:f.item.goalId,operation:`reassign`,todo_id:f.item.todoId},summary:m(`drawer.reassignSummary`,{task:f.item.text})}),type:`button`,children:m(`timeline.review`)})]}),(0,B.jsx)(`strong`,{children:m(`drawer.taskDeferUntil`)}),(0,B.jsxs)(`label`,{className:`personal-inline-agent-select personal-inline-resume-when`,children:[m(`drawer.taskDeferUntil`),(0,B.jsx)(`input`,{"aria-label":m(`drawer.taskDeferCondition`),"aria-invalid":!!L.trim()&&!be,onChange:e=>oe(e.target.value),placeholder:m(`drawer.taskDeferPlaceholder`),value:L}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:!be,onClick:()=>void Se(f.item,`defer`,m(`drawer.taskDefer`),be??void 0),type:`button`,children:m(`drawer.taskDeferReview`)}),(0,B.jsx)(`small`,{children:L.trim()&&!be?m(`drawer.taskDeferInvalid`):m(`drawer.taskDeferSupported`)})]}),(0,B.jsx)(`div`,{className:`personal-task-management-secondary`,children:qy.map(e=>(0,B.jsx)(`button`,{onClick:()=>void Se(f.item,e.operation,m(e.key)),type:`button`,children:m(e.key)},e.operation))})]})]}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void Se(f.item,`complete`,m(`drawer.taskComplete`)),type:`button`,children:[(0,B.jsx)(em,{size:17}),m(`drawer.taskComplete`)]})]}):null,f.item.done?(0,B.jsxs)(`div`,{className:`personal-task-completed-note`,children:[(0,B.jsx)(em,{size:16}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:m(`drawer.taskCompletedTitle`)}),(0,B.jsx)(`small`,{children:m(`drawer.taskCompletedNote`)})]})]}):null]}):null,f.kind===`goal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsx)(`small`,{children:Yi(f.item.state,p)}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.agentSentence}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.tokens`)}),(0,B.jsxs)(`dd`,{children:[by(f.item.usage?.tokens24h,m(`drawer.usageNotMeasured`),_y),` / `,by(f.item.usage?.tokens7d,m(`drawer.usageNotMeasured`),_y)]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.cost`)}),(0,B.jsxs)(`dd`,{children:[by(f.item.usage?.costUsd24h,m(`drawer.usageNotMeasured`),vy),` / `,by(f.item.usage?.costUsd7d,m(`drawer.usageNotMeasured`),vy)]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.duration`)}),(0,B.jsxs)(`dd`,{children:[by(f.item.usage?.durationMs24h,m(`drawer.usageNotMeasured`),yy),` / `,by(f.item.usage?.durationMs7d,m(`drawer.usageNotMeasured`),yy)]})]})]})]}),(0,B.jsx)(Ly,{goal:f.item}),(()=>{let e=i.find(e=>e.goalId===f.item.goalId),t=s.find(e=>e.goal_id===f.item.goalId);return(0,B.jsxs)(B.Fragment,{children:[f.item.repository?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-repository`,children:[(0,B.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,B.jsx)(`small`,{children:m(`drawer.repository`)}),(0,B.jsx)(`em`,{children:m(`common.readOnly`)})]}),(0,B.jsxs)(`h3`,{children:[(0,B.jsx)(_m,{size:16}),f.item.repository.label]}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.branch`)}),(0,B.jsx)(`dd`,{children:f.item.repository.branch||`detached`})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Role`}),(0,B.jsx)(`dd`,{children:m(`drawer.repositoryRole`)})]})]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>{let e=navigator.clipboard?.writeText(f.item.repository?.identity??``);if(!e){b(`error`);return}e.then(()=>b(`copied`)).catch(()=>b(`error`))},type:`button`,children:[(0,B.jsx)(cm,{size:15}),m(y===`copied`?`drawer.copyRepositoryDone`:`drawer.copyRepository`)]}),y===`error`?(0,B.jsx)(`p`,{className:`personal-copy-feedback is-error`,role:`status`,children:m(`drawer.copyRepositoryError`)}):y===`copied`?(0,B.jsx)(`p`,{className:`personal-copy-feedback`,role:`status`,children:m(`drawer.copyRepositorySuccess`)}):null]}):null,u?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,B.jsx)(`small`,{children:m(`drawer.larkConnection`)}),(0,B.jsx)(`h3`,{children:m(`drawer.remoteDetailsUnavailable`)}),(0,B.jsx)(`p`,{children:m(`drawer.remoteDetailsDescription`)})]}):(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,B.jsx)(`small`,{children:m(`drawer.larkConnection`)}),t?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`h3`,{children:[t.app_label,(0,B.jsx)(`span`,{className:`personal-connection-status`,children:m(`drawer.connected`)})]}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.group`)}),(0,B.jsx)(`dd`,{children:t.chat_name})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.topic`)}),(0,B.jsxs)(`dd`,{children:[`# `,t.topic_name]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.trigger`)}),(0,B.jsx)(`dd`,{children:t.incoming_mode===`mentions`?m(`lark.someoneMentions`):m(`lark.allMessages`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.replyMode`)}),(0,B.jsx)(`dd`,{children:m(`lark.topicReply`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.autoNotify`)}),(0,B.jsx)(`dd`,{children:e?.humanGateAutoNotifyEnabled?m(`common.on`):m(`common.off`)})]}),e?.lastNotifiedAt?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.lastNotification`)}),(0,B.jsx)(`dd`,{children:e.lastNotifiedAt})]}):null]})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h3`,{children:m(`drawer.larkNotConfigured`)}),(0,B.jsx)(`p`,{children:m(`drawer.larkNotConfiguredDescription`)})]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onOpenNotificationSettings?.(f.item.goalId),type:`button`,children:[(0,B.jsx)(Xp,{size:16}),m(t?`drawer.larkConfigure`:`drawer.larkConnect`)]})]})]})})(),(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-session`,children:[(0,B.jsx)(`small`,{children:m(`drawer.runDetails`)}),_e?.sessionId?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h3`,{children:Xi(_e.sessionStatus??_e.status,m)}),(0,B.jsx)(`p`,{children:_e.title}),r.onOpenRunSession?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onOpenRunSession?.(_e),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.runLatest`)]}):null]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h3`,{children:m(`drawer.noRun`)}),(0,B.jsx)(`p`,{children:m(`drawer.noRunDescription`)})]})]}),u?null:(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`heartbeat`,f.item.goalId),type:`button`,children:[(0,B.jsx)(Fm,{size:16}),m(`drawer.setupHeartbeat`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`monitor`,f.item.goalId),type:`button`,children:[(0,B.jsx)($p,{size:16}),m(`drawer.scheduleAdd`)]})]}),f.item.subagentExecution?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-subagents`,children:[(0,B.jsxs)(`div`,{className:`personal-subagent-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:m(`drawer.subagentLabel`)}),(0,B.jsxs)(`h3`,{children:[(0,B.jsx)(Zp,{size:16}),m(`drawer.subagentTitle`)]})]}),(0,B.jsxs)(`button`,{"aria-checked":we.enabled,"aria-label":m(M&&A===`ready`?`drawer.subagentPending`:we.enabled?`drawer.subagentDisable`:`drawer.subagentEnable`),className:`personal-subagent-switch`,"data-pending":M&&A===`ready`?`true`:void 0,disabled:u||Te||!!M||!r.onPreviewGoalSubagentConfiguration,onClick:()=>void ke(!we.enabled),role:`switch`,type:`button`,children:[(0,B.jsx)(`span`,{}),m(M&&A===`ready`?`drawer.subagentPending`:we.enabled?`common.on`:`common.off`)]})]}),(0,B.jsx)(`p`,{children:m(`drawer.subagentDescription`)}),M&&A===`ready`?(0,B.jsxs)(`div`,{className:`personal-subagent-preview`,children:[(0,B.jsx)(`strong`,{children:m(M.enabled?`drawer.subagentConfirmEnable`:`drawer.subagentConfirmDisable`)}),(0,B.jsx)(`p`,{children:M.enabled?m(`drawer.subagentPreviewSummary`,{count:M.maxChildren,domains:M.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)}):m(`drawer.subagentDisableSummary`)}),M.modelConfig===void 0?null:(0,B.jsxs)(`p`,{children:[m(`drawer.subagentModel`),`: `,M.modelConfig?.model||m(`drawer.subagentModelDefault`),` · `,M.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`button`,{className:`personal-primary-action`,onClick:()=>void Ae(),type:`button`,children:m(`common.confirm`)}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:R,type:`button`,children:m(`common.cancel`)})]})]}):null,T?(0,B.jsxs)(`p`,{className:`personal-subagent-feedback is-${A}`,role:`status`,children:[A===`previewing`||A===`applying`?(0,B.jsx)(Lm,{className:`personal-spin`,size:13}):null,T]}):null,(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentModel`)}),(0,B.jsx)(`dd`,{children:we.modelConfig?.model||m(`drawer.subagentModelDefault`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentEffort`)}),(0,B.jsx)(`dd`,{children:we.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentCurrentBoundary`)}),(0,B.jsx)(`dd`,{children:we.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentChildLimit`)}),(0,B.jsx)(`dd`,{children:we.maxChildren||0})]})]}),u?(0,B.jsx)(`p`,{className:`personal-subagent-read-only`,children:m(`drawer.subagentRemoteReadOnly`)}):(0,B.jsxs)(`div`,{className:`personal-subagent-fields`,children:[(0,B.jsxs)(`fieldset`,{className:`personal-subagent-domain-picker`,disabled:Te,children:[(0,B.jsx)(`legend`,{children:m(`drawer.subagentDomains`)}),Ee.length>0?(0,B.jsx)(`div`,{className:`personal-subagent-domain-options`,children:Ee.map(e=>{let t=C.includes(e.value);return(0,B.jsxs)(`label`,{className:`personal-subagent-domain-option${t?` is-selected`:``}`,children:[(0,B.jsx)(`input`,{"aria-label":e.value,checked:t,onChange:t=>Oe(e.value,t.target.checked),type:`checkbox`}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.value}),(0,B.jsx)(`small`,{children:m(`drawer.subagentDomainTodoCount`,{count:e.matchingTodoCount})})]})]},e.value)})}):(0,B.jsx)(`p`,{className:`personal-subagent-domain-empty`,children:m(`drawer.subagentDomainsEmpty`)}),(0,B.jsx)(`small`,{children:m(`drawer.subagentDomainsHint`)})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:m(`drawer.subagentModel`)}),(0,B.jsx)(`input`,{"aria-label":m(`drawer.subagentModel`),disabled:Te,value:ee,placeholder:`gpt-5.6-luna`,onChange:e=>{te(e.target.value),N(null),j(`idle`),E(null)}})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:m(`drawer.subagentEffort`)}),(0,B.jsxs)(`select`,{"aria-label":m(`drawer.subagentEffort`),disabled:Te,value:ne,onChange:e=>{k(e.target.value),N(null),j(`idle`),E(null)},children:[(0,B.jsx)(`option`,{value:``,children:m(`drawer.subagentModelDefault`)}),[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`].map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))]})]}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:Te,type:`button`,onClick:()=>{te(`gpt-5.6-luna`),k(`max`),N(null),j(`idle`),E(null)},children:m(`drawer.subagentLunaPreset`)}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:Te,type:`button`,onClick:()=>{te(``),k(``),N(null),j(`idle`),E(null)},children:m(`drawer.subagentClearModel`)}),(0,B.jsx)(`p`,{children:m(`drawer.subagentModelHint`)}),(0,B.jsxs)(`label`,{className:`personal-subagent-limit-field`,children:[(0,B.jsx)(`span`,{children:m(`drawer.subagentMaxChildren`)}),(0,B.jsx)(`select`,{"aria-label":m(`drawer.subagentMaxChildren`),disabled:Te,onChange:e=>{O(Number(e.target.value)),N(null),j(`idle`),E(null)},value:D,children:Yy.map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))})]}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:Te,onClick:()=>void ke(we.enabled,!0),type:`button`,children:m(`drawer.subagentPreviewBoundary`)})]})]}):null]}):null,f.kind===`run`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{"aria-label":m(`drawer.runView`),className:`personal-run-drawer-tabs`,role:`tablist`,children:[(0,B.jsx)(`button`,{"aria-selected":x===`record`,onClick:()=>S(`record`),role:`tab`,type:`button`,children:m(`drawer.executionRecordAndResult`)}),(0,B.jsx)(`button`,{"aria-selected":x===`details`,onClick:()=>S(`details`),role:`tab`,type:`button`,children:m(`drawer.detailsAndActions`)})]}),x===`record`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card personal-session-summary`,children:[(0,B.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Xi(f.item.sessionStatus??f.item.status,m)]}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.latestActivity}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,B.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]})]})]}),(0,B.jsxs)(`section`,{"aria-label":m(`drawer.executionRecord`),className:`personal-session-message-record`,children:[(0,B.jsx)(`h3`,{children:m(`drawer.executionRecord`)}),f.item.sessionMessages?.length?(0,B.jsx)(`ol`,{children:f.item.sessionMessages.map(e=>(0,B.jsxs)(`li`,{className:`is-${e.role}`,children:[(0,B.jsx)(`i`,{}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:e.role===`user`?m(`drawer.runRoleUser`):e.role===`assistant`?m(`drawer.runRoleAssistant`):m(`drawer.runRoleSystem`)}),e.createdAt?(0,B.jsx)(`time`,{children:new Date(e.createdAt).toLocaleTimeString(p,{hour:`2-digit`,minute:`2-digit`,hour12:!1})}):null]}),(0,B.jsx)(`p`,{children:e.text})]})]},e.messageId))}):(0,B.jsx)(`p`,{className:`personal-session-empty`,children:ve?m(`drawer.runRecordProjected`,{completed:f.item.completedSteps,outputs:f.item.outputs?.length?m(`drawer.runRecordProjectedOutputs`,{count:f.item.outputs.length}):``,total:f.item.totalSteps}):m(`drawer.runRecordEmpty`)}),f.item.status===`running`?(0,B.jsxs)(`div`,{className:`personal-session-active-step`,children:[(0,B.jsx)(`i`,{}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:m(`drawer.analysis`)}),(0,B.jsx)(`small`,{children:m(`drawer.agentWorking`)})]})]}):null]}),f.item.outputs?.length?(0,B.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-run-outputs-title`,children:[(0,B.jsx)(`h3`,{id:`personal-run-outputs-title`,children:m(`drawer.outputs`)}),(0,B.jsx)(`ol`,{children:f.item.outputs.map(e=>(0,B.jsx)(`li`,{children:(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsx)(`small`,{children:e.createdAt??e.kind??m(`files.emptySummary`)})]})},e.outputId))})]}):null]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Xi(f.item.status,m)]}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.latestActivity}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,B.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.sessionStatus`)}),(0,B.jsx)(`dd`,{children:Xi(f.item.sessionStatus??f.item.status,m)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.sessionRecoverable`)}),(0,B.jsx)(`dd`,{children:f.item.resumable===!1?m(`drawer.resumeNo`):m(`drawer.resumeYes`)})]})]})]}),f.item.sessionStatus===`resume_failed`&&!u?(0,B.jsxs)(`section`,{className:`personal-recovery-panel`,"aria-label":m(`drawer.recoveryFailed`),children:[(0,B.jsx)(`strong`,{children:m(`drawer.recoveryFailed`)}),(0,B.jsx)(`p`,{children:m(`drawer.recoveryDescription`)}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,B.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.recoveryNewSession`)]})]}):null,u?null:(0,B.jsxs)(`section`,{className:`personal-correction-panel`,children:[(0,B.jsx)(`header`,{children:(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:16}),m(`drawer.correctionLabel`,{agent:f.item.agentLabel})]})}),(0,B.jsx)(`p`,{children:m(`drawer.correctionDescription`)}),(0,B.jsxs)(`div`,{className:`personal-correction-composer`,children:[(0,B.jsx)(`textarea`,{"aria-label":m(`drawer.correctionTextarea`,{agent:f.item.agentLabel,goal:f.item.goalTitle,run:f.item.title}),onChange:e=>g(e.target.value),placeholder:m(`drawer.correctionPlaceholder`),rows:3,value:h}),(0,B.jsx)(`button`,{"aria-label":m(`drawer.correctionSend`),disabled:!h.trim(),onClick:()=>void xe(),type:`button`,children:(0,B.jsx)(Bm,{size:16})})]})]}),u?null:(0,B.jsxs)(`details`,{className:`personal-compact-menu personal-run-more`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(dm,{size:17}),m(`drawer.moreRunActions`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`button`,{disabled:!f.item.canInterrupt,onClick:()=>void r.onInterruptRun?.(f.item),type:`button`,children:[(0,B.jsx)(Mm,{size:16}),m(`drawer.runInterrupt`)]}),(0,B.jsxs)(`button`,{disabled:f.item.resumable===!1,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,B.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,B.jsxs)(`button`,{onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.runNewSession`)]}),(0,B.jsxs)(`button`,{onClick:()=>void r.onCloseRunSession?.(f.item),type:`button`,children:[(0,B.jsx)(qm,{size:16}),m(`drawer.runCloseSession`)]})]})]})]})]}):null,f.kind===`output`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsx)(`small`,{children:f.item.kind??`output`}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.summary??m(`drawer.outputRecorded`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.outputTodo`)}),(0,B.jsx)(`dd`,{children:f.item.todoId??m(`drawer.notLinked`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.outputRun`)}),(0,B.jsx)(`dd`,{children:f.item.runId??m(`drawer.notLinked`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Agent`}),(0,B.jsx)(`dd`,{children:f.item.agentLabel??f.item.agentId??`LoopX`})]})]})]}),f.item.report?(0,B.jsxs)(`section`,{className:`personal-report-detail`,"data-testid":`personal-periodic-report-detail`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsxs)(`strong`,{children:[`+`,f.item.report.addedCount]}),m(`files.reportAdded`)]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:f.item.report.changedCount}),m(`files.reportChanged`)]})]}),(0,B.jsxs)(`p`,{children:[f.item.report.periodStartAt,` → `,f.item.report.periodEndAt]}),(0,B.jsx)(`ol`,{children:f.item.report.items.map(e=>(0,B.jsxs)(`li`,{"data-change-kind":e.changeKind,children:[(0,B.jsxs)(`small`,{children:[e.changeKind,` · `,e.status]}),(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsx)(`p`,{children:e.summary})]},e.sourceRef))}),(0,B.jsxs)(`footer`,{children:[(0,B.jsxs)(`span`,{children:[m(`files.reportPublication`),`: `,f.item.report.publicationId]}),(0,B.jsxs)(`span`,{children:[m(`files.reportGeneration`),`: `,f.item.report.generationId]})]})]}):null,f.item.safePreview?(0,B.jsx)(`pre`,{"aria-label":m(`drawer.outputSafePreview`),className:`personal-safe-preview`,children:f.item.safePreview}):(0,B.jsx)(`p`,{className:`personal-preview-unavailable`,children:m(`drawer.previewUnavailable`)}),(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:!r.onOpenOutput,onClick:()=>{r.onOpenOutput?.(f.item),c()},type:`button`,children:[(0,B.jsx)(fm,{size:16}),m(`files.openConversation`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!r.onExportOutput,onClick:()=>void r.onExportOutput?.(f.item),type:`button`,children:[(0,B.jsx)(um,{size:16}),m(`files.exportSummary`)]})]})]}):null,f.kind===`proposal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-proposal-card`,children:[(0,B.jsxs)(`small`,{children:[f.item.actionKind,` · `,f.item.status]}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.impact}),f.item.reviewPlan?(0,B.jsx)(`p`,{className:`personal-proposal-explainer`,"data-action-review":f.item.reviewPlan.interaction,children:m(`actionReview.${f.item.reviewPlan.reason}`)}):null,f.item.status===`ready`?(0,B.jsx)(`p`,{className:`personal-proposal-explainer`,children:m(`drawer.proposalExplainer`)}):null,(0,B.jsx)(`dl`,{children:f.item.fields.map(e=>(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:e.label}),(0,B.jsx)(`dd`,{children:e.value})]},e.key))})]}),f.item.status===`applied`?(0,B.jsxs)(`p`,{className:`personal-proposal-state is-applied`,children:[(0,B.jsx)(em,{size:16}),m(`drawer.proposalApplied`)]}):null,f.item.status===`applied`&&f.item.goalId?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>{let e=f.item.goalId;c(),r.onOpenGoal?.(e)},type:`button`,children:[(0,B.jsx)(fm,{size:16}),f.item.actionKind===`goal.create`?m(`drawer.proposalEnterGoal`):m(`drawer.proposalViewGoal`)]}):null,f.item.status===`stale`?(0,B.jsx)(`p`,{className:`personal-proposal-state is-stale`,children:m(`drawer.proposalStale`)}):null,f.item.status===`error`?(0,B.jsxs)(`div`,{className:`personal-proposal-state is-error`,children:[(0,B.jsx)(`span`,{children:f.item.reviewPlan?.reason===`readback_unverified`?m(`actionReview.readback_unverified`):m(`drawer.proposalApplyFailed`)}),f.item.errorMessage?(0,B.jsx)(`small`,{children:f.item.errorMessage}):null,(0,B.jsx)(`small`,{children:m(`drawer.proposalApplyFailedHint`)})]}):null,f.item.status===`rejected`?(0,B.jsx)(`p`,{className:`personal-proposal-state is-error`,children:m(`drawer.proposalRejected`)}):null,f.item.status===`deferred`?(0,B.jsx)(`p`,{className:`personal-proposal-state is-gated`,children:m(`drawer.proposalDeferred`)}):null,f.item.status===`gated`?(0,B.jsxs)(`div`,{className:`personal-proposal-state is-gated`,children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:m(`drawer.gateRequiresHost`)}),m(`drawer.gateRequiresHostDescription`)]}),f.item.gate?.nextAction?(0,B.jsx)(`small`,{children:f.item.gate.nextAction}):null]}):null,f.item.status===`gated`&&f.item.actionKind===`gate.resolve`?(()=>{let e=e=>f.item.fields.find(t=>t.key===e)?.value,t=e(`goal_id`),n=e(`todo_id`);return!t||!n?null:(0,B.jsxs)(`section`,{className:`personal-detail-card personal-gate-cli-hint`,children:[(0,B.jsx)(`small`,{children:m(`drawer.gateApproveHint`)}),(0,B.jsxs)(`code`,{children:[`loopx todo complete --goal-id `,t,` --todo-id `,n,` --decision-outcome approve`]}),(0,B.jsx)(`small`,{children:m(`drawer.gateRejectHint`)})]})})():null,!u&&f.item.workspaceCandidates?.length?(0,B.jsx)(`div`,{className:`personal-workspace-candidates`,"aria-label":m(`drawer.workspaceCandidates`),children:f.item.workspaceCandidates.map(e=>(0,B.jsxs)(`button`,{onClick:()=>void r.onSelectWorkspaceCandidate?.(f.item,e.workspaceRef),type:`button`,children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsx)(`small`,{children:e.workspaceRef})]},e.workspaceRef))}):null,!u&&f.item.status===`error`?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,B.jsx)(Lm,{size:17}),m(`drawer.proposalRegenerate`)]}):!u&&f.item.status!==`gated`?(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:![`ready`,`deferred`].includes(f.item.status)||f.item.reviewPlan?.canApply===!1,onClick:()=>void r.onApplyProposal?.(f.item),type:`button`,children:[(0,B.jsx)(em,{size:17}),f.item.status===`applying`?m(`drawer.applying`):f.item.primaryLabel??m(`drawer.apply`)]}):null,!u&&([`stale`,`gated`,`rejected`].includes(f.item.status)||f.item.status===`ready`&&f.item.reviewPlan?.canApply===!1)?(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,B.jsx)(Lm,{size:16}),m(`drawer.proposalRecheck`)]}):null,!u&&[`ready`,`gated`].includes(f.item.status)?(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`defer`),type:`button`,children:m(`drawer.proposalDefer`)}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`reject`),type:`button`,children:m(`drawer.decisionReject`)})]}):null,[`applied`,`applying`].includes(f.item.status)?null:(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:c,type:`button`,children:m(`drawer.proposalClose`)})]}):null,f.kind===`schedule`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsxs)(`small`,{children:[f.item.scheduleKind===`heartbeat`?`Goal Heartbeat`:`continuous_monitor`,` · `,f.item.status??`active`]}),(0,B.jsx)(`h3`,{children:f.item.label}),(0,B.jsx)(`p`,{children:f.item.target??f.item.schedule??m(`drawer.scheduleDefaultTarget`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleTimezone`)}),(0,B.jsx)(`dd`,{children:f.item.timezone??m(`drawer.scheduleLocalTimezone`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleNext`)}),(0,B.jsx)(`dd`,{children:f.item.nextRunAt??m(`drawer.schedulePending`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleLast`)}),(0,B.jsx)(`dd`,{children:f.item.previousRunAt??m(`drawer.scheduleNeverRun`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleNotification`)}),(0,B.jsx)(`dd`,{children:f.item.notificationRule??m(`drawer.scheduleDefaultNotification`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleStopCondition`)}),(0,B.jsx)(`dd`,{children:f.item.stopCondition??m(`drawer.scheduleDefaultStop`)})]})]})]}),!u&&f.item.scheduleKind===`monitor`?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`run_now`),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.scheduleRunNow`)]}):null,u?null:(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,f.item.status===`paused`?`resume`:`pause`),type:`button`,children:[f.item.status===`paused`?(0,B.jsx)(Nm,{size:16}):(0,B.jsx)(Mm,{size:16}),f.item.status===`paused`?m(`drawer.scheduleResume`):m(`drawer.schedulePause`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`edit`),type:`button`,children:[(0,B.jsx)($p,{size:16}),m(`drawer.scheduleEdit`)]})]}),u?null:(0,B.jsxs)(`button`,{className:`personal-danger-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`stop`),type:`button`,children:[(0,B.jsx)(qm,{size:16}),m(`drawer.scheduleStop`,{kind:f.item.scheduleKind===`heartbeat`?` Heartbeat`:m(`drawer.titleSchedule`)})]}),(0,B.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-execution-history-title`,children:[(0,B.jsx)(`h3`,{id:`personal-execution-history-title`,children:m(`drawer.executionHistory`)}),f.item.executionHistory?.length?(0,B.jsx)(`ol`,{children:f.item.executionHistory.map((e,t)=>(0,B.jsxs)(`li`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsx)(`small`,{children:e.timestamp})]}),(0,B.jsx)(`em`,{className:`is-${e.status}`,children:e.status})]},`${e.timestamp}:${e.runId??t}`))}):(0,B.jsx)(`p`,{children:m(`drawer.noExecutionHistory`)})]})]}):null,f.kind===`run`||f.kind===`proposal`||f.kind===`schedule`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`button`,{"aria-expanded":_,className:`personal-diagnostics-trigger`,onClick:()=>v(e=>!e),type:`button`,children:[(0,B.jsx)(`span`,{children:m(`drawer.advancedDiagnostics`)}),(0,B.jsx)(tm,{className:_?`is-open`:``,size:16})]}),_?(0,B.jsxs)(`div`,{className:`personal-diagnostics`,children:[(0,B.jsxs)(`code`,{children:[`goal_id: `,he]}),(0,B.jsxs)(`code`,{children:[`kind: `,f.kind]}),f.kind===`run`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`code`,{children:[`session_id: `,f.item.sessionId??m(`drawer.notLinked`)]}),(0,B.jsxs)(`code`,{children:[`turn_id: `,f.item.turnId??m(`common.none`)]}),(0,B.jsxs)(`code`,{children:[`adapter: `,f.item.agentId]}),(0,B.jsxs)(`code`,{children:[`status: `,f.item.sessionStatus??f.item.status]})]}):f.kind===`proposal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`code`,{children:[`action: `,f.item.actionKind]}),(0,B.jsxs)(`code`,{children:[`status: `,f.item.status]})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`code`,{children:[`schedule_id: `,f.item.scheduleId]}),(0,B.jsxs)(`code`,{children:[`status: `,f.item.status??`active`]})]})]}):null]}):null]})]})}var eb=[`checking`,`connecting`,`downloading`,`installing_app`,`installing_runtime`],tb={desktop_status_unavailable:[`无法读取 App 更新状态。请重启 App 后再试;若仍失败,请重新安装最新 App。`,`Cannot read the App update status. Restart the App; if this persists, reinstall the latest App.`],update_feed_unavailable:[`此通道的更新源尚未就绪或暂时不可用。可稍后重新检查,当前版本仍可继续使用。`,`This channel's update feed is not ready or temporarily unavailable. Check again later; you can keep using this version.`],update_feed_invalid:[`更新源格式异常。请稍后重新检查。`,`The update feed is invalid. Check again later.`],update_platform_unavailable:[`此通道尚无适用于本机的更新包。`,`This channel has no update package for this platform.`],update_check_timeout:[`检查更新超时。请稍后重试。`,`The update check timed out. Try again later.`],update_network_failed:[`无法连接更新服务器。请检查网络后重试。`,`Cannot reach the update server. Check your connection and retry.`],update_download_or_signature_failed:[`更新包下载或签名校验失败,尚未安装。请重新检查更新。`,`Download or signature verification failed; the update was not installed. Check for updates again.`]};function nb(e,t=`update_failed`){return{phase:`error`,details:{code:typeof e==`string`&&Object.hasOwn(tb,e)?e:t}}}function rb(){let{locale:e}=Ji(),t=e===`zh-CN`,[n,r]=(0,z.useState)(!1),i=(0,z.useRef)(null),[a,o]=(0,z.useState)(`stable`),[s,c]=(0,z.useState)({phase:`idle`}),[l,u]=(0,z.useState)(``),[d,f]=(0,z.useState)(!1),p=(0,z.useRef)(!1),m=window.__TAURI__?.core.invoke,h=eb.includes(s.phase);(0,z.useEffect)(()=>{let e=i.current;if(!e)return;let t=()=>r(e.matches(`:popover-open`));return e.addEventListener(`toggle`,t),()=>e.removeEventListener(`toggle`,t)},[]),(0,z.useEffect)(()=>{if(!m)return;let e=!0;return m(`desktop_update_status`).then(t=>{if(!e)return;u(t.app_version),f(t.rollback_available===!0),t.state?.phase&&c(t.state);let n=t.state?.details?.channel??(t.app_version.includes(`-main.`)?`main`:`stable`);o(n),t.state?.phase||m(`desktop_update`,{action:`check`,channel:n}).then(t=>{e&&c(t)}).catch(t=>{e&&c(nb(t))})}).catch(()=>{e&&c(nb(null,`desktop_status_unavailable`))}),()=>{e=!1}},[m]),(0,z.useEffect)(()=>{if(!m||!h)return;let e=window.setInterval(()=>{m(`desktop_update_status`).then(e=>{e.state?.phase&&c(e.state)}).catch(()=>{})},1e3);return()=>window.clearInterval(e)},[m,h]);async function g(e){if(!(!m||p.current)){p.current=!0,c({phase:e===`check`?`checking`:e===`repair`?`installing_runtime`:`downloading`});try{if(!l){let e=await m(`desktop_update_status`);u(e.app_version),f(e.rollback_available===!0)}c(await m(`desktop_update`,{action:e,channel:a}))}catch(e){c(nb(e,l?`update_failed`:`desktop_status_unavailable`))}finally{p.current=!1}}}let _={service_error:t?`运行时已安装,但服务尚未连接。可重试更新、修复或恢复上版。`:`Runtime installed, but services are unavailable. Retry updates, repair, or restore the previous version.`,idle:t?`App 会检查可用更新,不会自动安装。`:`Updates are checked automatically, never installed without confirmation.`,runtime_required:t?`请完成匹配组件安装,或检查 App 更新。`:`Install matching components or check for an App update.`,connecting:t?`正在连接更新后的服务…`:`Connecting to updated services…`,checking:t?`正在检查更新…`:`Checking for updates…`,available:t?`新版本已就绪,一次更新 App 与匹配的运行时。`:`Update the App and its matching runtime together.`,up_to_date:t?`当前通道暂无更新。`:`No newer update on this channel.`,downloading:t?`正在下载并校验签名…`:`Downloading and verifying signature…`,installing_app:t?`正在安装 App,请保持窗口打开。`:`Installing the App. Keep this window open.`,installing_runtime:t?`正在安装匹配的运行时,请稍候…`:`Installing the matching runtime…`,restart_required:t?`重启后将自动完成运行时安装与服务连接。`:`Restart to finish runtime installation and reconnect services.`,ready:t?`更新完成,服务已就绪。`:`Update completed; services are ready.`,error:tb[s.details?.code??``]?.[+!t]??(t?`更新未完成。请重试;启动失败可尝试修复当前版本。`:`Update incomplete. Retry; repair this version if startup fails.`)},v=h?t?`正在更新…`:`Updating…`:s.phase===`available`?t?`有可用更新`:`Update available`:s.phase===`restart_required`?t?`重启完成更新`:`Restart to finish`:s.phase===`error`?t?`更新需重试`:`Retry update`:t?`更新 LoopX`:`Update LoopX`;return(0,B.jsxs)(`div`,{className:`personal-desktop-update`,children:[(0,B.jsxs)(`button`,{className:`personal-update-trigger`,type:`button`,"aria-expanded":n,"aria-controls":`desktop-update-panel`,onClick:e=>{i.current?.style.setProperty(`bottom`,`${window.innerHeight-e.currentTarget.getBoundingClientRect().top+8}px`),i.current?.togglePopover()},children:[(0,B.jsx)(um,{size:16,"aria-hidden":`true`}),(0,B.jsx)(`span`,{children:v}),(0,B.jsx)(rm,{size:14,"aria-hidden":`true`})]}),(0,B.jsxs)(`section`,{ref:i,popover:`auto`,id:`desktop-update-panel`,className:`personal-update-panel`,"aria-label":t?`LoopX 更新`:`LoopX updates`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:t?`LoopX 更新`:`LoopX updates`}),(0,B.jsx)(`button`,{type:`button`,"aria-label":t?`关闭更新面板`:`Close updates`,onClick:()=>i.current?.hidePopover(),children:(0,B.jsx)($m,{size:16,"aria-hidden":`true`})})]}),(0,B.jsxs)(`small`,{children:[l,` · `,a===`main`?t?`main 预览版`:`main preview`:t?`稳定版`:`Stable`]}),s.details?.version?(0,B.jsxs)(`p`,{children:[t?`目标版本:`:`Target: `,s.details.version]}):null,(0,B.jsxs)(`p`,{role:`status`,"aria-live":`polite`,children:[h?(0,B.jsx)(Im,{className:`is-spinning`,size:14,"aria-hidden":`true`}):null,_[s.phase]]}),s.phase===`downloading`&&s.details?.total?(0,B.jsx)(`progress`,{"aria-label":t?`下载进度`:`Download progress`,max:s.details.total,value:s.details.received??0}):null,m?(0,B.jsx)(`div`,{className:`personal-update-actions`,children:s.phase===`restart_required`?(0,B.jsx)(`button`,{type:`button`,onClick:()=>void g(`restart`),children:t?`重启完成更新`:`Restart to finish`}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`button`,{type:`button`,disabled:h,onClick:()=>void g(`check`),children:t?`检查更新`:`Check for updates`}),s.phase===`available`?(0,B.jsx)(`button`,{type:`button`,onClick:()=>void g(`apply`),children:t?`更新并准备重启`:`Install update`}):null]})}):(0,B.jsx)(`p`,{children:t?`请在 LoopX App 中更新;浏览器自身无需安装包。`:`Update from the LoopX App; the browser needs no installer.`}),(0,B.jsxs)(`details`,{children:[(0,B.jsx)(`summary`,{children:t?`高级选项`:`Advanced options`}),(0,B.jsxs)(`label`,{children:[t?`更新通道`:`Update channel`,(0,B.jsxs)(`select`,{disabled:h||s.phase===`restart_required`,value:a,onChange:e=>{o(e.target.value),c({phase:`idle`})},children:[(0,B.jsx)(`option`,{value:`stable`,children:t?`稳定版(推荐)`:`Stable (recommended)`}),(0,B.jsx)(`option`,{value:`main`,children:t?`main 预览版`:`main preview`})]})]}),(0,B.jsx)(`p`,{children:t?`App 与匹配的 CLI 一起更新,服务可能短暂断开。不删除 Goal 数据。`:`Updates the App and matching CLI. Services may briefly disconnect. Goal data is not deleted.`}),m?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{children:t?`启动失败时,可重装当前 App 随附的运行时。`:`If startup fails, reinstall this App's bundled runtime.`}),(0,B.jsx)(`button`,{disabled:h||s.phase===`restart_required`,type:`button`,onClick:()=>void g(`repair`),children:t?`修复当前版本`:`Repair this version`})]}):null,m&&d?(0,B.jsxs)(`details`,{children:[(0,B.jsx)(`summary`,{children:t?`恢复上个版本`:`Restore previous version`}),(0,B.jsx)(`p`,{children:t?`将恢复已保留的 App 和它的运行时,需要重启。`:`Restore the retained App and its runtime, then restart.`}),(0,B.jsx)(`button`,{disabled:h,type:`button`,onClick:()=>void g(`rollback`),children:t?`确认恢复上版`:`Restore previous version`})]}):null]})]})]})}var ib=e=>`loopx-sidebar-goal-order-v1:${encodeURIComponent(e)}`;function ab(e){try{let t=JSON.parse(e??`null`);return Array.isArray(t)&&t.every(e=>typeof e==`string`)?[...new Set(t)]:[]}catch{return[]}}function ob(e,t){let n=new Map(t.map((e,t)=>[e,t]));return[...e].sort((e,t)=>(n.get(e.goalId)??1/0)-(n.get(t.goalId)??1/0))}function sb(e,t,n,r,i){if(n===r||!t.includes(n)||!t.includes(r))return e;let a=[...new Set([...e,...t])].filter(e=>e!==n);return a.splice(a.indexOf(r)+Number(i),0,n),a}function cb(e,t){let n=ib(t),[r,i]=(0,z.useState)(()=>{try{return ab(localStorage.getItem(n))}catch{return[]}}),[a,o]=(0,z.useState)(!1),[s,c]=(0,z.useState)(null),[l,u]=(0,z.useState)(null),d=(0,z.useRef)(null),f=(0,z.useRef)(!1),p=ob(e,r),m=p.map(e=>e.goalId);function h(t,a,s){let l=sb(r,m,t,a,s);if(l===r)return;i(l);let u=ob(e,l),d=u.findIndex(e=>e.goalId===t),f=u[d];f&&c({title:f.title,position:d+1});try{localStorage.setItem(n,JSON.stringify(l)),o(!1)}catch{o(!0)}}function g(){d.current=null,u(null)}return{sorted:p,target:l,saveFailed:a,lastMoved:s,move:h,moveBy(e,t){let n=p[m.indexOf(e)+t];n&&h(e,n.goalId,t===1)},pointerProps:e=>({onPointerDown(t){f.current=!1,t.pointerType===`mouse`&&t.button===0&&(d.current={id:e,x:t.clientX,y:t.clientY,dragging:!1},t.currentTarget.setPointerCapture(t.pointerId))},onPointerMove(e){let t=d.current;if(!t||!t.dragging&&Math.hypot(e.clientX-t.x,e.clientY-t.y)<6)return;t.dragging=!0,f.current=!0;let n=document.elementFromPoint(e.clientX,e.clientY)?.closest(`[data-reorder-goal]`),r=e.currentTarget.closest(`.personal-goal-list`),i=n?.dataset.reorderGoal;if(!n||!i||!r?.contains(n)||i===t.id){u(null);return}let a=n.getBoundingClientRect();u({id:i,after:e.clientY>a.top+a.height/2})},onPointerUp(){d.current?.dragging&&l&&h(d.current.id,l.id,l.after),g()},onPointerCancel:g,onLostPointerCapture:g,onKeyDown(e){e.key===`Escape`&&g()},onClickCapture(e){f.current&&=(e.preventDefault(),e.stopPropagation(),!1)}})}}var lb=`/ssh-hosts`,ub=/^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;function db(e){return typeof e==`string`&&ub.test(e.trim())}function fb(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`SSH Host 列表响应无效。`);let t=e;if(t.ok!==!0||t.schema_version!==`ssh_host_catalog_v0`||!Array.isArray(t.hosts))throw Error(`SSH Host 列表协议不兼容,请更新本机 LoopX 服务。`);let n=new Set;return{hosts:t.hosts.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=String(e.alias??``).trim();return!db(t)||n.has(t)?[]:(n.add(t),[{alias:t}])}),schemaVersion:`ssh_host_catalog_v0`}}async function pb(e=fetch,t=lb){let n=await e(t,{cache:`no-store`});if(!n.ok)throw Error(`无法读取本机 SSH Host(HTTP ${n.status})。`);return fb(await n.json())}function mb(e,t){let n=e.trim();if(!db(n))return{error:`请选择有效的 SSH Host。`};let r=Number(t);return!Number.isInteger(r)||r<1024||r>65535?{error:`本地端口必须是 1024–65535 之间的整数。`}:{command:`ssh -N -L ${r}:127.0.0.1:8766 ${n}`,hostAlias:n,label:n,statusUrl:`http://127.0.0.1:${r}/status.json`}}var hb=`/api/ssh-source/ensure`,gb=`/api/ssh-source/goal-lifecycle`;async function _b(e,t){let n=await fetch(hb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({host_alias:e,local_port:Number(t)})}),r=await n.json().catch(()=>null);if(!n.ok)throw Error(r?.error??`无法建立 SSH 隧道来源。`);if(!r?.ok)throw Error(`无法建立 SSH 隧道来源。`);return r}async function vb(e,t,n,r,i=fetch){let a=await i(gb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({goal_id:t,host_alias:e,operation:n,reason:r})}),o=await a.json().catch(()=>null);if(!a.ok)throw Error(o?.error??`无法更新远端 Goal 生命周期。`);if(!o?.ok||o.schema_version!==`loopx_remote_goal_lifecycle_v1`||o.goal_id!==t||o.host_alias!==e||o.operation!==n||o.activation_state!==(n===`stop`?`stopped`:`active`)||o.projection_verified!==!0)throw Error(`远端 Goal 生命周期回读未验证。`);return o}function yb({activeSource:e,connectionState:t,errorMessage:n,onAdd:r,onConfiguredHostsLoaded:i,onRemove:a,onSelect:o,sources:s}){let{t:c}=Ji(),[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(null),[p,m]=(0,z.useState)(`configured`),[h,g]=(0,z.useState)([]),[_,v]=(0,z.useState)(null),[y,b]=(0,z.useState)(!1),[x,S]=(0,z.useState)(!1),[C,w]=(0,z.useState)(``),[T,E]=(0,z.useState)(``),[D,O]=(0,z.useState)(`8876`),[ee,te]=(0,z.useState)(``),ne=`configured:`,k=[...s.map(e=>({label:e.label,value:e.id})),...h.filter(e=>!s.some(t=>t.label===e.alias)).map(e=>({group:c(`source.configuredGroup`,{count:h.length}),label:e.alias,value:`${ne}${e.alias}`}))],A=(0,z.useMemo)(()=>h.some(e=>e.alias===C)?mb(C,D):{error:c(`source.selectHost`)},[h,C,D,c]);(0,z.useEffect)(()=>{j()},[]);async function j(){b(!0),v(null);try{let e=await pb();g(e.hosts),i?.(e.hosts.map(e=>e.alias)),w(t=>t||e.hosts[0]?.alias||``),e.hosts.length||v(c(`source.hostEmpty`))}catch(e){v(e instanceof Error?e.message:c(`source.hostLoadError`))}finally{b(!1)}}function M(){u(!0),m(`configured`),f(null),j()}function N(){u(!1),m(`configured`),v(null),S(!1),w(``),f(null),E(``),O(`8876`),te(``)}function P(){let e=r({label:T,statusUrl:ee});if(e.error){f(e.error);return}N()}function F(){if(`error`in A){f(A.error??c(`source.invalid`));return}let e=r({ensureTunnel:!0,hostAlias:A.hostAlias,label:A.label,statusUrl:A.statusUrl});if(e.error){f(e.error);return}N()}function re(e){let t=new Set;for(let e of s)try{t.add(new URL(e.statusUrl).port)}catch{}let n=`8877`;for(let e=8877;e<9077;e+=1)if(!t.has(String(e))){n=String(e);break}let i=mb(e,n);if(`error`in i){f(i.error??c(`source.invalid`));return}let a=r({ensureTunnel:!0,hostAlias:i.hostAlias,label:i.label,statusUrl:i.statusUrl});a.error?f(a.error):f(null),O(n)}async function ie(){if(`error`in A){f(A.error??c(`source.invalid`));return}try{await navigator.clipboard.writeText(A.command),S(!0),f(null)}catch{f(c(`source.copyError`))}}return(0,B.jsxs)(`section`,{"aria-label":c(`source.controlPlane`),className:`personal-status-source`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`span`,{children:`Control plane`}),(0,B.jsx)(`button`,{"aria-label":c(`source.addSsh`),onClick:M,title:c(`source.add`),type:`button`,children:(0,B.jsx)(Pm,{size:14})})]}),(0,B.jsx)(Cy,{ariaLabel:c(`source.select`),className:`personal-status-source-select`,icon:(0,B.jsx)(Hm,{size:15}),onChange:e=>{if(e.startsWith(ne)){re(e.slice(11));return}o(e)},options:k,value:e.id}),(0,B.jsxs)(`div`,{className:`personal-status-source-meta`,children:[(0,B.jsxs)(`span`,{className:`is-${t}`,children:[(0,B.jsx)(`i`,{}),c(t===`loading`?`source.connecting`:t===`error`?`source.notAvailable`:`source.connected`)]}),(0,B.jsx)(`small`,{children:e.readOnly?c(`source.readOnly`):c(`source.localInteractive`)}),e.kind===`ssh_tunnel`?(0,B.jsx)(`button`,{"aria-label":c(`source.remove`,{source:e.label}),onClick:()=>a(e.id),title:c(`source.removeCurrent`),type:`button`,children:(0,B.jsx)(Xm,{size:12})}):null]}),n?(0,B.jsx)(`p`,{className:`personal-status-source-error`,role:`alert`,children:n}):null,l?(0,B.jsxs)(`div`,{className:`personal-status-source-form`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:c(`source.addSsh`)}),(0,B.jsx)(`button`,{"aria-label":c(`source.closeForm`),onClick:N,type:`button`,children:(0,B.jsx)($m,{size:13})})]}),(0,B.jsxs)(`div`,{"aria-label":c(`source.addMethod`),className:`personal-status-source-modes`,role:`tablist`,children:[(0,B.jsx)(`button`,{"aria-selected":p===`configured`,onClick:()=>{m(`configured`),f(null)},role:`tab`,type:`button`,children:c(`source.configured`)}),(0,B.jsx)(`button`,{"aria-selected":p===`manual`,onClick:()=>{m(`manual`),f(null)},role:`tab`,type:`button`,children:c(`source.manual`)})]}),p===`configured`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.configuredCount`,{count:h.length})}),(0,B.jsxs)(`span`,{className:`personal-status-source-field-row`,children:[(0,B.jsx)(`input`,{"aria-label":c(`source.host`),disabled:y||!h.length,list:`loopx-configured-ssh-hosts`,onChange:e=>{w(e.target.value),S(!1)},placeholder:c(y?`source.loadingHosts`:`source.hostPlaceholder`),value:C}),(0,B.jsx)(`datalist`,{id:`loopx-configured-ssh-hosts`,children:h.map(e=>(0,B.jsx)(`option`,{value:e.alias},e.alias))}),(0,B.jsx)(`button`,{"aria-label":c(`source.refreshHosts`),disabled:y,onClick:()=>void j(),title:c(`source.refreshHosts`),type:`button`,children:(0,B.jsx)(Rm,{size:13})})]})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.localPort`)}),(0,B.jsx)(`input`,{"aria-label":c(`source.localPort`),inputMode:`numeric`,onChange:e=>{O(e.target.value),S(!1)},value:D})]}),(0,B.jsxs)(`div`,{className:`personal-status-source-command`,children:[(0,B.jsx)(`code`,{children:`error`in A?c(`source.tunnelCommandPending`):A.command}),(0,B.jsxs)(`button`,{"aria-label":c(`source.copyCommand`),disabled:`error`in A,onClick:()=>void ie(),type:`button`,children:[(0,B.jsx)(cm,{size:12}),c(x?`source.copied`:`source.copy`)]})]}),_?(0,B.jsx)(`p`,{className:`is-error`,children:_}):null,(0,B.jsx)(`p`,{children:c(`source.description`)}),(0,B.jsx)(`button`,{className:`personal-status-source-add`,disabled:`error`in A,onClick:F,type:`button`,children:c(`source.addConfigured`)})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.name`)}),(0,B.jsx)(`input`,{autoFocus:!0,maxLength:48,onChange:e=>E(e.target.value),placeholder:c(`source.namePlaceholder`),value:T})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.statusUrl`)}),(0,B.jsx)(`input`,{onChange:e=>te(e.target.value),placeholder:`http://127.0.0.1:8876/status.json`,value:ee})]}),(0,B.jsx)(`p`,{children:(0,B.jsx)(`code`,{children:`ssh -N -L 8876:127.0.0.1:8766 `})}),(0,B.jsx)(`p`,{children:c(`source.manualDescription`)}),(0,B.jsx)(`button`,{className:`personal-status-source-add`,onClick:P,type:`button`,children:c(`source.addConfigured`)})]}),d?(0,B.jsx)(`p`,{className:`is-error`,role:`alert`,children:d}):null]}):null]})}var bb={需修复:`is-danger`,等你:`is-warning`,等待条件:`is-info`,推进中:`is-success`,安静运行:`is-quiet`,已完成:`is-quiet`,已停止:`is-stopped`};function xb({attentionCount:e,goals:t,goalArchiveLoadState:n={error:null,phase:`ready`},lifecycleBusyGoalIds:r,goalLifecycleOperations:i,onRequestGoalCreate:a,onOpenSettings:o,onRetryGoalArchive:s,onRequestGoalLifecycle:c,onSelectGoal:l,selectedGoalId:u,statusSourceControl:d}){let{locale:f,t:p}=Ji(),[m,h]=(0,z.useState)(!1),g=cb(t.filter(e=>e.activationState!==`stopped`),d?.activeSource.statusUrl??`/status.json`),_=g.sorted,v=t.filter(e=>e.activationState===`stopped`),y=e=>!!c&&(!i||i.includes(e)),b=(e,t)=>(0,B.jsxs)(`div`,{className:`personal-goal-row${g.target?.id===e.goalId?g.target.after?` is-drop-after`:` is-drop-before`:``}`,"data-reorder-goal":t?void 0:e.goalId,"data-load-error":e.loadError,children:[(0,B.jsxs)(`button`,{...t?{}:g.pointerProps(e.goalId),title:t?void 0:p(`sidebar.dragGoal`),"aria-current":u===e.goalId?`page`:void 0,className:`personal-goal-link`,onClick:()=>l(e.goalId),type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-goal-state-dot ${e.loadState?``:bb[e.state]}`}),(0,B.jsxs)(`span`,{className:`personal-goal-link-copy`,children:[(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsxs)(`small`,{children:[e.loadState&&(!t||u===e.goalId)?p(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Yi(e.state,f),e.needsYou&&!t?` · ${p(`home.lane.needsYou`)}`:``]})]}),(0,B.jsx)(nm,{size:15})]}),!t&&m?(0,B.jsxs)(`div`,{className:`personal-goal-move-actions`,children:[(0,B.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveUp`,{goal:e.title}),disabled:_[0]?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,-1),children:(0,B.jsx)(Jp,{"aria-hidden":`true`,size:13})}),(0,B.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveDown`,{goal:e.title}),disabled:_.at(-1)?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,1),children:(0,B.jsx)(Wp,{"aria-hidden":`true`,size:13})})]}):null,c&&y(t?`resume`:`stop`)?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`button`,{"aria-label":`${p(t?`sidebar.resume`:`sidebar.stop`)} ${e.title}`,"aria-busy":r?.has(e.goalId)||void 0,className:`personal-goal-lifecycle${r?.has(e.goalId)?` is-pending`:``}`,disabled:r?.has(e.goalId),onClick:()=>c(e,t?`resume`:`stop`),title:p(t?`sidebar.resumeGoal`:`sidebar.stopGoal`),type:`button`,children:r?.has(e.goalId)?(0,B.jsx)(Cm,{size:13}):t?(0,B.jsx)(Lm,{size:13}):(0,B.jsx)(Mm,{size:13})}),t&&y(`delete`)?(0,B.jsx)(`button`,{"aria-label":`${p(`sidebar.delete`)} ${e.title}`,className:`personal-goal-lifecycle personal-goal-delete`,onClick:()=>c(e,`delete`),title:p(`sidebar.deleteGoal`),type:`button`,children:(0,B.jsx)(Xm,{size:13})}):null]}):null]},e.goalId);return(0,B.jsxs)(`div`,{className:`personal-goal-directory`,children:[(0,B.jsxs)(`div`,{className:`personal-sidebar-brand`,children:[(0,B.jsx)(`span`,{className:`personal-brand-mark`,children:(0,B.jsx)(Zp,{size:18})}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:`LoopX`})})]}),d?(0,B.jsx)(yb,{...d}):null,(0,B.jsxs)(`nav`,{"aria-label":p(`home.workspace`),className:`personal-sidebar-nav`,children:[(0,B.jsxs)(`button`,{"aria-current":u===null?`page`:void 0,className:`personal-manager-link`,onClick:()=>l(null),type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-manager-icon`,children:(0,B.jsx)(Zp,{size:17})}),(0,B.jsx)(`span`,{children:p(`sidebar.manager`)}),e>0?(0,B.jsx)(`span`,{className:`personal-sidebar-count`,children:e}):null,(0,B.jsx)(nm,{size:15})]}),(0,B.jsxs)(`div`,{className:`personal-sidebar-section-title`,children:[(0,B.jsx)(`span`,{children:`Goals`}),(0,B.jsxs)(`span`,{className:`personal-sidebar-title-actions`,children:[(0,B.jsx)(`small`,{children:_.length}),(0,B.jsx)(`button`,{"aria-label":p(`sidebar.sortGoals`),title:p(`sidebar.sortGoals`),"aria-pressed":m,onClick:()=>h(!m),type:`button`,children:(0,B.jsx)(qp,{"aria-hidden":`true`,size:15})}),a?(0,B.jsx)(`button`,{"aria-label":p(`sidebar.createGoal`),onClick:a,type:`button`,children:(0,B.jsx)(Pm,{size:15})}):null]})]}),g.saveFailed?(0,B.jsx)(`p`,{role:`status`,children:p(`sidebar.orderNotSaved`)}):null,(0,B.jsx)(`span`,{className:`personal-sr-only`,role:`status`,children:g.lastMoved?p(`sidebar.goalMoved`,{goal:g.lastMoved.title,position:g.lastMoved.position}):``}),(0,B.jsx)(`div`,{className:`personal-goal-list`,children:_.map(e=>b(e,!1))}),v.length||n.phase===`loading`||n.phase===`error`?(0,B.jsxs)(`details`,{className:`personal-stopped-goals`,open:n.phase===`error`||void 0,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(tm,{size:13}),(0,B.jsx)(`span`,{children:p(`sidebar.stopped`)}),n.phase===`loading`?(0,B.jsx)(Cm,{"aria-label":p(`sidebar.stoppedLoading`),className:`is-spinning`,size:13}):(0,B.jsx)(`small`,{children:v.length})]}),(0,B.jsxs)(`div`,{className:`personal-goal-list is-stopped`,children:[n.phase===`error`?(0,B.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`alert`,children:[(0,B.jsx)(`span`,{children:p(`sidebar.stoppedLoadFailed`)}),s?(0,B.jsx)(`button`,{onClick:s,type:`button`,children:p(`sidebar.retryStopped`)}):null]}):null,v.map(e=>b(e,!0))]})]}):null]}),(0,B.jsxs)(`div`,{className:`personal-sidebar-footer`,children:[(0,B.jsx)(rb,{}),o?(0,B.jsxs)(`button`,{"aria-label":p(`settings.open`),className:`personal-sidebar-utility`,onClick:o,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-sidebar-utility-icon`,children:(0,B.jsx)(Um,{size:17})}),(0,B.jsx)(`span`,{className:`personal-sidebar-utility-copy`,children:(0,B.jsx)(`strong`,{children:p(`settings.open`)})}),(0,B.jsx)(nm,{"aria-hidden":`true`,size:15})]}):null]})]})}var Sb=J({ok:X(!0),total:G().int().nonnegative(),next_cursor:W().nullable(),items:q(J({todo_id:W(),text:W(),claimed_by:W().nullable(),evidence:W().nullable(),priority:W().nullable(),task_class:W().nullable()})).max(40)});function Cb({goal:e,agentId:t,seed:n,enabled:r,listView:i=!1,onSelect:a}){let{t:o}=Ji(),s=(0,z.useId)(),[c,l]=(0,z.useState)(!1),u=!i||c,d=i?96:148,[f,p]=(0,z.useState)(n),[m,h]=(0,z.useState)(t===`all`?e.doneTodoCount??n.length:n.length),[g,_]=(0,z.useState)(void 0),[v,y]=(0,z.useState)(!1),[b,x]=(0,z.useState)(!1),[S,C]=(0,z.useState)(!1),[w,T]=(0,z.useState)({top:0,height:600}),[E,D]=(0,z.useState)(null),O=(0,z.useRef)(null),ee=(0,z.useRef)(null),[te,ne]=(0,z.useState)(0);(0,z.useEffect)(()=>{let e=O.current;if(!e)return;let t=new ResizeObserver(()=>T({top:e.scrollTop,height:e.clientHeight}));return t.observe(e),()=>{t.disconnect(),ee.current?.abort()}},[]);let k=g===void 0||w.top+w.height>=f.length*d-d*2;(0,z.useEffect)(()=>{if(!r||!u||!k||g===null||b||ee.current)return;let n=new AbortController;ee.current=n,y(!0);let i=new URLSearchParams({goal_id:e.goalId});t!==`all`&&i.set(`agent_id`,t),g&&i.set(`cursor`,g),fetch(`/api/chat/completed-todos?${i}`,{signal:n.signal}).then(async e=>{if(e.status===409&&C(!0),!e.ok)throw Error(`history unavailable`);let t=Sb.parse(await e.json());if(n.signal.aborted)return;let r=t.items.map(e=>({todoId:e.todo_id,text:e.text,claimedBy:e.claimed_by,evidence:e.evidence,priority:e.priority,taskClass:e.task_class,done:!0,status:`done`}));p(e=>g===void 0?r:[...e,...r.filter(t=>!e.some(e=>e.todoId===t.todoId))]),h(t.total),_(t.next_cursor)}).catch(()=>{n.signal.aborted||x(!0)}).finally(()=>{n.signal.aborted||(ee.current=null,y(!1))})},[r,u,k,g,b,te,e.goalId,t,v]),(0,z.useEffect)(()=>{O.current&&(O.current.scrollTop=0),T({top:0,height:O.current?.clientHeight??600}),D(null)},[i]);let A=Math.max(0,Math.floor(w.top/d)-3),j=Math.min(f.length,Math.ceil((w.top+w.height)/d)+3),M=Array.from({length:Math.max(0,j-A)},(e,t)=>A+t);return E!==null&&El(e=>!e),children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,children:c?`▾`:`▸`}),` `,o(`tasks.completed`)]}):(0,B.jsxs)(`strong`,{children:[(0,B.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-done`}),o(`tasks.completed`)]}),(0,B.jsx)(`span`,{children:m})]}),(0,B.jsxs)(`div`,{id:s,hidden:!u,"aria-label":o(`tasks.completed`),className:`personal-task-lane-scroll`,ref:O,role:`region`,tabIndex:0,onScroll:e=>T({top:e.currentTarget.scrollTop,height:e.currentTarget.clientHeight}),children:[(0,B.jsx)(`div`,{className:`personal-completed-window`,style:{height:f.length*d},children:M.map(t=>{let n=f[t];return(0,B.jsx)(`div`,{className:`personal-task-card personal-completed-row`,style:{top:t*d,height:d},children:(0,B.jsxs)(`button`,{type:`button`,onFocus:()=>D(t),onBlur:()=>D(null),onClick:()=>a({kind:`todo`,item:{...n,goalId:e.goalId,goalTitle:e.title,ownerLabel:n.claimedBy??e.agentLabel??e.agentId}}),children:[(0,B.jsx)(`span`,{className:`is-done`,children:`✓`}),(0,B.jsx)(`strong`,{children:n.text}),(0,B.jsx)(`small`,{children:n.claimedBy??e.agentLabel??e.agentId})]})},n.todoId)})}),(0,B.jsx)(`div`,{className:`personal-completed-footer`,role:`status`,children:v?o(`tasks.historyLoading`):b?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`span`,{children:o(S?`tasks.historyExpired`:`tasks.historyError`)}),(0,B.jsx)(`button`,{type:`button`,onClick:()=>{S&&(_(void 0),O.current&&(O.current.scrollTop=0)),C(!1),x(!1),ne(e=>e+1)},children:o(`tasks.historyRetry`)})]}):r?g===null?o(`tasks.historyEnd`):(0,B.jsx)(`button`,{type:`button`,onClick:()=>{O.current&&(O.current.scrollTop=f.length*d)},children:o(`tasks.historyMore`)}):o(`tasks.historyLocalOnly`)})]})]})}function wb({children:e,count:t,label:n,tone:r,listView:i=!1}){let a=(0,z.useId)(),o=(0,z.useRef)(null),s=(0,z.useRef)([]),c=(0,z.useRef)(null),[l,u]=(0,z.useState)({after:!1,before:!1}),d=(0,z.useCallback)(()=>{let e=o.current;if(!e)return;let t={after:Math.max(0,e.scrollHeight-e.clientHeight)-e.scrollTop>1,before:e.scrollTop>1};u(e=>e.after===t.after&&e.before===t.before?e:t)},[]);return(0,z.useEffect)(()=>{let e=o.current;if(!e)return;let t=new ResizeObserver(d);return c.current=t,t.observe(e),e.addEventListener(`scroll`,d,{passive:!0}),d(),()=>{t.disconnect(),c.current=null,s.current=[],e.removeEventListener(`scroll`,d)}},[i,d]),(0,z.useEffect)(()=>{let e=o.current,t=c.current;if(!e||!t)return;for(let e of s.current)t.unobserve(e);let n=Array.from(e.children).filter(e=>e instanceof HTMLElement);for(let e of n)t.observe(e);s.current=n,d()},[e,t,i,d]),i?!t&&r!==`done`?null:(0,B.jsxs)(`details`,{className:`personal-task-group tone-${r}`,open:!0,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(tm,{size:16}),(0,B.jsx)(`strong`,{children:n}),(0,B.jsx)(`span`,{children:t})]}),(0,B.jsx)(`div`,{className:`personal-task-list-rows`,children:e})]}):(0,B.jsxs)(`section`,{className:`personal-object-list personal-task-lane`,children:[(0,B.jsxs)(`header`,{id:a,children:[(0,B.jsxs)(`strong`,{children:[(0,B.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-${r}`}),n]}),(0,B.jsx)(`span`,{children:t})]}),(0,B.jsx)(`div`,{"aria-labelledby":a,className:`personal-task-lane-scroll${l.before?` has-overflow-before`:``}${l.after?` has-overflow-after`:``}`,ref:o,role:`region`,tabIndex:t>0?0:-1,children:e})]})}function Tb({historyEnabled:e=!1,goal:t,items:n,onDraftTaskFromMessage:r,onOpenChat:i,onQuickComplete:a,quickCompletingTodoIds:o,onSelect:s,selectedTodoId:c=null,userTodos:l}){let{t:u}=Ji(),[d,f]=(0,z.useState)(!1),[p,m]=(0,z.useState)({goalId:``,laneId:`all`}),h=(0,z.useRef)(null);(0,z.useEffect)(()=>{if(!c)return;let e=window.requestAnimationFrame(()=>h.current?.scrollIntoView({block:`nearest`,inline:`nearest`}));return()=>window.cancelAnimationFrame(e)},[c]);let g=l.filter(e=>e.goalId===t.goalId).map(e=>({...e,goalTitle:t.title})),_=e=>e.priority===`P0`?0:e.priority===`P1`?1:e.priority===`P2`?2:3,v=(0,z.useMemo)(()=>{let e=new Map((t.agentLanes??[]).map(e=>[e.agentId,e]));for(let n of t.agentTodos)n.claimedBy&&!e.has(n.claimedBy)&&e.set(n.claimedBy,{agentId:n.claimedBy,label:n.claimedBy});return[...e.values()]},[t.agentLanes,t.agentTodos]),y=p.goalId===t.goalId&&v.some(e=>e.agentId===p.laneId)?p.laneId:`all`,b=e=>y===`all`||e===y,x=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&!e.done).filter(e=>b(e.claimedBy)).sort((e,t)=>_(e)-_(t)),S=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&e.done).filter(e=>b(e.claimedBy)),C=n.filter(e=>e.kind===`schedule`&&b(e.schedule.agentId)),w=n.filter(e=>e.kind===`run`&&!!e.run.todoId&&b(e.run.agentId)),T=!g.length&&!x.length&&!S.length&&!C.length,E=n.filter(e=>e.kind===`message`&&(e.message.role===`user`||e.message.role===`assistant`)),D=E.reduce((e,t,n)=>t.message.role===`user`?n:e,-1),O=D>=0?E[D]?.message:null,ee=D>=0?E.slice(D+1).reverse().find(e=>e.message.role===`assistant`)?.message:null,te=D>=0&&E.slice(D+1).some(e=>e.message.role===`assistant`&&e.message.pending);return(0,B.jsxs)(`section`,{"aria-label":u(`header.tasks`),className:`personal-task-board${d?` is-list-view`:``}`,children:[(0,B.jsxs)(`header`,{className:`personal-task-view-toolbar`,children:[(0,B.jsx)(`div`,{children:(0,B.jsx)(`strong`,{children:u(`header.tasks`)})}),(0,B.jsxs)(`div`,{className:`personal-task-view-switch`,role:`group`,"aria-label":u(`tasks.viewLabel`),children:[(0,B.jsx)(`button`,{type:`button`,"aria-pressed":d,onClick:()=>f(!0),children:u(`tasks.listView`)}),(0,B.jsx)(`button`,{type:`button`,"aria-pressed":!d,onClick:()=>f(!1),children:u(`tasks.boardView`)})]})]}),v.length>1?(0,B.jsxs)(`section`,{"aria-label":u(`tasks.agentLaneFilter`),className:`personal-task-lane-filter`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(Zp,{size:15}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:u(`tasks.agentLane`)})})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{className:`sr-only`,children:u(`tasks.agentLaneFilter`)}),(0,B.jsxs)(`select`,{"aria-label":u(`tasks.agentLaneFilter`),onChange:e=>m({goalId:t.goalId,laneId:e.target.value}),value:y,children:[(0,B.jsx)(`option`,{value:`all`,children:u(`tasks.allAgentLanes`,{count:v.length})}),v.map(e=>(0,B.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))]}),(0,B.jsx)(tm,{"aria-hidden":!0,size:14})]})]}):null,O?(0,B.jsxs)(`section`,{"aria-label":u(`tasks.chatRecent`),className:`personal-task-chat-receipt`,children:[(0,B.jsx)(`span`,{className:`personal-task-chat-icon`,children:(0,B.jsx)(Dm,{size:18})}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:u(te?`tasks.chatPending`:ee?`tasks.chatAgentReplied`:`tasks.chatRecent`)}),(0,B.jsx)(`small`,{children:t.agentLabel??t.agentId})]}),(0,B.jsxs)(`p`,{className:`is-user`,children:[(0,B.jsx)(`b`,{children:u(`common.you`)}),O.text]}),ee&&!ee.pending?(0,B.jsxs)(`p`,{className:`is-assistant`,children:[(0,B.jsx)(`b`,{children:u(`common.agent`)}),ee.text]}):null,(0,B.jsx)(`small`,{children:u(te?`tasks.chatPendingDescription`:`tasks.chatUnchangedDescription`)})]}),(0,B.jsxs)(`footer`,{children:[(0,B.jsxs)(`button`,{onClick:i,type:`button`,children:[(0,B.jsx)(Dm,{size:14}),u(`tasks.chatViewReply`)]}),ee&&!te&&r?(0,B.jsxs)(`button`,{onClick:()=>r(ee.text),type:`button`,children:[(0,B.jsx)(Sm,{size:14}),u(`tasks.convertToTask`)]}):null]})]}):null,(0,B.jsxs)(`div`,{className:d?`personal-task-grouped-list`:`personal-task-kanban`,children:[(0,B.jsxs)(wb,{listView:d,count:g.length,label:u(`timeline.waitingConfirmation`),tone:`attention`,children:[g.map(e=>{let t=Zi(e.updatedAt,u);return(0,B.jsxs)(`button`,{onClick:()=>s({item:e,kind:`attention`}),type:`button`,children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,className:`is-attention`,children:`!`}),(0,B.jsx)(`strong`,{children:e.text}),(0,B.jsxs)(`small`,{children:[(0,B.jsx)(`span`,{className:`personal-row-status ${e.blocking?`is-blocking`:`is-pending`}`,children:e.blocking?u(`tasks.blocked`):u(`tasks.pending`)}),t?(0,B.jsx)(`span`,{className:`personal-task-age`,children:u(`tasks.waitingAge`,{age:t})}):null]})]},e.todoId)}),g.length?null:(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyConfirm`)})]}),(0,B.jsxs)(wb,{listView:d,count:x.length,label:u(`tasks.pendingAndRunning`),tone:`progress`,children:[x.map(e=>{let n={...e,goalId:t.goalId,goalTitle:t.title,ownerLabel:e.claimedBy??t.agentLabel??t.agentId},r=w.find(t=>t.run.todoId===e.todoId)?.run;return(0,B.jsxs)(`div`,{className:`personal-task-card${r?` has-session`:``}${c===e.todoId?` is-selected`:``}`,ref:c===e.todoId?e=>{h.current=e}:void 0,children:[(0,B.jsxs)(`button`,{"aria-pressed":c===e.todoId,onClick:()=>s({item:n,kind:`todo`}),type:`button`,children:[(0,B.jsx)(`span`,{children:`○`}),(0,B.jsx)(`strong`,{children:e.text}),(0,B.jsxs)(`small`,{children:[e.priority?(0,B.jsx)(`span`,{className:`personal-priority-badge is-${e.priority.toLowerCase()}`,children:e.priority}):null,e.status===`blocked`?(0,B.jsx)(`span`,{className:`personal-priority-badge is-blocked`,children:u(`tasks.blocked`)}):null,r?(0,B.jsx)(`span`,{className:`personal-task-session-status`,children:r.status===`running`||r.status===`queued`?u(`runs.running`):r.status===`failed`?u(`tasks.sessionError`):u(`common.waiting`)}):null,e.status===`deferred`?(0,B.jsx)(`span`,{className:`personal-task-session-status`,children:u(`drawer.taskStatusDeferred`)}):r?null:(0,B.jsx)(`span`,{className:`personal-task-session-status`,children:u(`tasks.waiting`)}),e.claimedBy??t.agentLabel??t.agentId]})]}),(0,B.jsxs)(`div`,{className:`personal-task-card-actions`,children:[r?(0,B.jsxs)(`button`,{className:`personal-task-session-link`,"aria-label":u(`tasks.openExecution`,{name:e.text}),onClick:()=>s({item:r,kind:`run`}),title:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`),type:`button`,children:[(0,B.jsx)(fm,{size:14}),(0,B.jsx)(`span`,{children:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`)})]}):null,a?(0,B.jsx)(`button`,{"aria-busy":o?.has(e.todoId)||void 0,"aria-label":u(`tasks.markComplete`,{name:e.text}),disabled:o?.has(e.todoId),onClick:()=>void a(n),title:u(`tasks.completed`),type:`button`,children:o?.has(e.todoId)?(0,B.jsx)(Cm,{className:`personal-spin`,size:14}):(0,B.jsx)(em,{size:14})}):null,(0,B.jsx)(`button`,{"aria-label":u(`tasks.moreActions`,{name:e.text}),onClick:()=>s({item:n,kind:`todo`}),title:u(`common.actions`),type:`button`,children:(0,B.jsx)(dm,{size:14})})]})]},e.todoId)}),x.length?null:(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyRunning`)})]}),(0,B.jsxs)(wb,{listView:d,count:C.length,label:u(`tasks.scheduled`),tone:`schedule`,children:[C.map(e=>(0,B.jsxs)(`button`,{onClick:()=>s({item:e.schedule,kind:`schedule`}),type:`button`,children:[(0,B.jsx)(`span`,{children:`◷`}),(0,B.jsx)(`strong`,{children:e.schedule.label}),(0,B.jsx)(`small`,{children:e.schedule.status===`paused`?u(`schedule.paused`):u(`schedule.active`)})]},e.id)),C.length?null:(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptySchedules`)})]}),(0,B.jsx)(Cb,{goal:t,agentId:y,seed:S,enabled:e,listView:d,onSelect:s},`${t.goalId}:${y}:${e}`)]}),T?(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyGoal`)}):null]})}function Eb(e,t){return{live_steering:{label:t(`lark.ingressSteering`),detail:t(`lark.ingressSteeringDescription`)},session_queue:{label:t(`lark.ingressQueue`),detail:t(`lark.ingressQueueDescription`)},async_inbox:{label:t(`lark.ingressAsync`),detail:t(`lark.ingressAsyncDescription`)},direct_session:{label:t(`lark.ingressLegacy`),detail:t(`lark.ingressLegacyDescription`)}}[e]}function Db(e,t){return e.listener_status===`starting`?{label:t(`lark.health.starting`),detail:t(`lark.health.startingDetail`),state:`not_ready`}:e.listener_status===`retrying`&&e.listener_error_code===`lark_event_source_disconnected`?{label:t(`lark.health.sourceDisconnected`),detail:t(`lark.health.sourceDisconnectedDetail`),state:`not_ready`}:e.listener_status===`retrying`?{label:t(`lark.health.retrying`),detail:t(`lark.health.retryingDetail`),state:`not_ready`}:e.listener_status===`stopped`||e.listener_status===null?{label:t(`lark.health.notStarted`),detail:t(`lark.health.notStartedDetail`),state:`not_ready`}:e.last_event_status===`message_context_permission_required`?{label:t(`lark.health.messageContextPermission`),detail:t(`lark.health.messageContextPermissionDetail`),state:`not_ready`}:e.last_event_status===`processing_failed`?{label:t(`lark.health.processingFailed`),detail:t(`lark.health.processingFailedDetail`),state:`not_ready`}:e.health_error_code===`invalid_routing_state`?{label:t(`lark.health.invalidRouting`),detail:t(`lark.health.invalidRoutingDetail`),state:`not_ready`}:e.last_event_status===`queued_for_agent`?{label:t(`lark.health.queued`),detail:t(`lark.health.queuedDetail`,{agent:e.agent_id??t(`lark.targetAgent`)}),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`not_addressed`?{label:t(`lark.health.notAddressed`),detail:t(`lark.health.notAddressedDetail`),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`self_message`?{label:t(`lark.health.listening`),detail:t(`lark.health.ignoredSelf`),state:`ready`}:e.health_error_code===`lark_event_route_mismatch`||[`chat_mismatch`,`topic_mismatch`,`route_ambiguous`].includes(e.last_event_reason??``)?{label:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguous`):t(`lark.health.routeMismatch`),detail:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguousDetail`):t(`lark.health.routeMismatchDetail`),state:`not_ready`}:[`invalid_event`,`binding_unavailable`].includes(e.last_event_reason??``)?{label:t(`lark.health.routeUnavailable`),detail:t(`lark.health.routeUnavailableDetail`),state:`not_ready`}:e.last_event_status===`replied_and_acknowledged`?{label:t(`lark.health.listening`),detail:t(`lark.health.eventProcessed`,{events:e.event_count,replies:e.replied_count}),state:`ready`}:e.health_error_code===`lark_event_delivery_unverified`||e.event_count===0?{label:t(`lark.health.eventUnverified`),detail:t(`lark.health.eventUnverifiedDetail`),state:`unverified`}:{label:e.reply_ready?t(`lark.health.listening`):t(`lark.health.unavailable`),detail:t(`lark.health.lastStatus`,{status:e.last_event_status??t(`lark.health.waiting`)}),state:e.reply_ready?`ready`:`not_ready`}}function Ob(e){return e.history_permission_guidance?.api_document_url??null}function kb(e,t,n){if(e instanceof Th){let t=String(e.payload.error_code??``);return{lark_cli_not_installed:n(`lark.error.cliMissing`),lark_cli_not_executable:n(`lark.error.cliExecutable`),lark_cli_start_failed:n(`lark.error.cliStart`),lark_message_permissions_required:n(`lark.error.messagePermissions`),lark_app_required:n(`lark.error.appRequired`),invalid_lark_app:n(`lark.error.invalidApp`),lark_group_lookup_failed:n(`lark.error.groupLookup`),provider_api_failed:n(`lark.error.provider`)}[t]??e.message}return e instanceof Error?e.message:t}function Ab({embedded:e=!1,focusGoalConnection:t=!1,goals:n,initialGoalId:r,onChanged:i,onClose:a}){let{t:o}=Ji(),[s,c]=(0,z.useState)(`connections`),[l,u]=(0,z.useState)([]),[d,f]=(0,z.useState)([]),[p,m]=(0,z.useState)(!0),[h,g]=(0,z.useState)(null),[_,v]=(0,z.useState)(``),[y,b]=(0,z.useState)(t),[x,S]=(0,z.useState)(``),[C,w]=(0,z.useState)(r??n[0]?.goalId??``),[T,E]=(0,z.useState)(``),[D,O]=(0,z.useState)([]),[ee,te]=(0,z.useState)(``),[ne,k]=(0,z.useState)(!1),[A,j]=(0,z.useState)(null),[M,N]=(0,z.useState)(`addressed_only`),[P,F]=(0,z.useState)(t&&r?`goal`:`manager`),[re,ie]=(0,z.useState)(`async_inbox`),[I,ae]=(0,z.useState)(`topic_reply`),[L,oe]=(0,z.useState)(``),[se,ce]=(0,z.useState)(!1),[le,ue]=(0,z.useState)({}),[de,fe]=(0,z.useState)(!1),[pe,me]=(0,z.useState)(null),[he,ge]=(0,z.useState)(null),[_e,ve]=(0,z.useState)(null),[ye,be]=(0,z.useState)(null),[xe,Se]=(0,z.useState)(!1),[Ce,we]=(0,z.useState)(`loopx-workspace-bot`),[Te,Ee]=(0,z.useState)(`feishu`),[R,De]=(0,z.useState)(null),[Oe,ke]=(0,z.useState)(!1),[Ae,je]=(0,z.useState)(null),Me=(0,z.useRef)(null),Ne=(0,z.useRef)(null),Pe=(0,z.useRef)(!1);async function Fe(){m(!0),g(null);try{let[e,t]=await Promise.all([Rg(),qg()]);u(e),f(t),S(t=>t||e.find(e=>e.reply_ready)?.app_ref||e.find(e=>e.ready)?.app_ref||e[0]?.app_ref||``)}catch(e){g(kb(e,o(`lark.error.configuration`),o))}finally{m(!1)}}(0,z.useEffect)(()=>{Fe()},[]),(0,z.useEffect)(()=>{if(!t||p||Pe.current||!r)return;Pe.current=!0;let e=d.find(e=>e.goal_id===r);e?Je(e):qe(n.find(e=>e.goalId===r))},[d,t,n,r,p]),(0,z.useEffect)(()=>{if(!y||!x||_e){O([]),te(``),k(!1),j(null);return}let e=!1;k(!0),j(null);let t=window.setTimeout(()=>{Gg(x,T).then(t=>{e||(O(t),te(e=>t.some(t=>t.chat_id===e)?e:t[0]?.chat_id??``))}).catch(t=>{e||(O([]),te(``),j(kb(t,o(`lark.error.groupLoad`),o)))}).finally(()=>{e||k(!1)})},180);return()=>{e=!0,window.clearTimeout(t)}},[x,T,y,_e]),(0,z.useEffect)(()=>{if(!xe||!R||[`ready`,`failed`,`cancelled`].includes(R.status))return;let e=!1,t=window.setTimeout(()=>{Vg(R.setup_id).then(async t=>{e||(De(t),t.verification_url&&Ne.current!==t.verification_url&&(Ne.current=t.verification_url,Me.current&&!Me.current.closed&&(Me.current.location.href=t.verification_url)),t.status===`ready`&&(await Fe(),S(t.app_ref),ue({}),Se(!1)),t.status===`failed`&&je(t.error??o(`lark.error.appCreate`)))}).catch(t=>{e||je(kb(t,o(`lark.error.setupPoll`),o))})},650);return()=>{e=!0,window.clearTimeout(t)}},[xe,R]);let V=n.find(e=>e.goalId===C),Ie=V?.agentId?[{agentId:V.agentId,label:V.agentLabel??V.agentId}]:[],Le=V?.agentLanes?.length?V.agentLanes:Ie,Re=Le.some(e=>e.agentId===L),ze=[];se?ze=Le.map(e=>({agentId:e.agentId,appRef:le[e.agentId]??x})):Re&&(ze=[{agentId:L,appRef:x}]);let Be=ze.map(e=>e.agentId),Ve=!!_e||ze.length>0&&ze.every(e=>l.some(t=>t.app_ref===e.appRef&&t.reply_ready)),He=o(`lark.connect`);he?He=o(`lark.saveConnection`):se&&(He=o(`lark.connectAllAgentsAction`,{count:Be.length}));let Ue=l.find(e=>e.app_ref===x),We=D.find(e=>e.chat_id===ee),Ge=(0,z.useMemo)(()=>{let e=_.trim().toLocaleLowerCase();return e?d.filter(t=>[t.app_label,t.chat_name,t.goal_title,t.topic_name].some(t=>t.toLocaleLowerCase().includes(e))):d},[d,_]),Ke=(0,z.useMemo)(()=>d.filter(e=>Db(e,o).state===`unverified`).length,[d,o]);function qe(e){let i=e??n.find(e=>e.goalId===r)??n[0];ge(null),ve(null),F(e||t?`goal`:`manager`),S(l.some(e=>e.app_ref===x)?x:l.find(e=>e.reply_ready)?.app_ref??l[0]?.app_ref??``),te(``),w(i?.goalId??``),oe(i?.agentId??``),ce(!1),ue({}),N(`addressed_only`),ie(`async_inbox`),ae(`topic_reply`),E(``),me(null),b(!0)}function Je(e){ge(e.goal_id),ve(e),F(e.conversation_kind??`goal`),S(e.app_ref),w(e.goal_id);let t=n.find(t=>t.goalId===e.goal_id),r=t?.agentLanes?.length?t.agentLanes:t?.agentId?[{agentId:t.agentId}]:[];oe(e.agent_id??(r.length===1?r[0].agentId:``)),ce(!1),ue({}),N(e.capture_scope),ie(e.ingress_mode===`direct_session`?`async_inbox`:e.ingress_mode),ae(e.reply_mode),E(e.chat_name),me(null),b(!0)}function Ye(){De(null),je(null),Ne.current=null,Se(!0)}async function Xe(){if(!(Oe||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Ce))){ke(!0),je(null),Ne.current=null,Me.current=window.open(window.location.href,`_blank`);try{let e=await Bg({appRef:Ce,brand:Te});De(e)}catch(e){Me.current?.close(),je(kb(e,o(`lark.error.setupStart`),o))}finally{ke(!1)}}}async function Ze(){let e=R;if(Se(!1),Me.current?.close(),e&&![`ready`,`failed`,`cancelled`].includes(e.status))try{await Hg(e.setup_id)}catch{}}async function Qe(){if(!(!x||!C||!_e&&!We||P===`goal`&&Be.length===0||de)){fe(!0),me(null);try{let e={...P===`manager`?{..._e?{connectionId:_e.connection_id}:{appRef:x,chatId:We.chat_id,chatName:We.chat_name}}:_e?{connectionId:_e.connection_id,agentId:L}:{agentBindings:ze,chatId:We.chat_id,chatName:We.chat_name},conversationKind:P,captureScope:P===`manager`?`addressed_only`:M,goalId:C,incomingMode:M===`configured_chat_all`?`all`:`mentions`,ingressMode:P===`manager`?`session_queue`:re,replyMode:I},t=await Jg({...e,execute:!1});if(!t.ok)throw new Th(t.public_summary??t.blocker??o(`lark.error.bindPreview`),{error_code:t.blocker??`provider_api_failed`});let n=await Jg({...e,execute:!0});if(!n.ok)throw new Th(n.public_summary??n.blocker??o(`lark.error.bind`),{error_code:n.blocker??`provider_api_failed`});b(!1),await Fe(),i?.()}catch(e){me(kb(e,o(`lark.error.bind`),o))}finally{fe(!1)}}}async function $e(e,t){if(ye!==t){be(t);return}try{await Yg(e,t),be(null),await Fe(),i?.()}catch(e){g(kb(e,o(`lark.error.disconnect`),o))}}return(0,B.jsxs)(`section`,{className:`personal-lark-settings${e?` is-embedded`:``}`,"aria-label":o(`lark.configuration`),children:[e?null:(0,B.jsxs)(`header`,{className:`personal-lark-header`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:o(`settings.goalConnections`)}),(0,B.jsx)(`h1`,{children:`Lark`})]}),(0,B.jsx)(`button`,{"aria-label":o(`lark.closeSettings`),className:`personal-icon-button`,onClick:a,type:`button`,children:(0,B.jsx)($m,{size:18})})]}),(0,B.jsxs)(`nav`,{className:`personal-lark-tabs`,"aria-label":o(`lark.management`),children:[(0,B.jsxs)(`button`,{"aria-current":s===`apps`?`page`:void 0,onClick:()=>c(`apps`),type:`button`,children:[o(`lark.apps`),` `,(0,B.jsx)(`span`,{children:p?`…`:l.length})]}),(0,B.jsxs)(`button`,{"aria-current":s===`connections`?`page`:void 0,onClick:()=>c(`connections`),type:`button`,children:[o(`lark.connections`),` `,(0,B.jsx)(`span`,{children:p?`…`:d.length})]})]}),h?(0,B.jsx)(`p`,{className:`personal-notification-error`,children:h}):null,p?(0,B.jsxs)(`div`,{className:`personal-lark-loading`,children:[(0,B.jsx)(Cm,{className:`is-spinning`,size:18}),o(`lark.loading`)]}):null,!p&&s===`apps`?(0,B.jsxs)(`div`,{className:`personal-lark-apps`,children:[(0,B.jsxs)(`div`,{className:`personal-lark-app-toolbar`,children:[(0,B.jsx)(`span`,{children:o(`lark.reusableApps`,{count:l.length})}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:Ye,type:`button`,children:[(0,B.jsx)(Pm,{size:16}),o(`lark.newApp`)]})]}),(0,B.jsxs)(`div`,{className:`personal-lark-app-grid`,children:[l.map(e=>(0,B.jsxs)(`article`,{className:`personal-lark-app-card`,children:[(0,B.jsx)(`span`,{className:`personal-lark-app-avatar`,children:(0,B.jsx)(Zp,{size:19})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsxs)(`small`,{children:[e.brand,` · lark-cli profile`]})]}),(0,B.jsx)(`em`,{className:e.reply_ready?`is-ready`:`is-off`,children:e.reply_ready?o(`lark.autoReplyReady`):e.ready?o(`lark.needsMessagePermissions`):o(`lark.needsSetup`)}),(0,B.jsxs)(`p`,{children:[o(`lark.goalConnections`,{count:d.filter(t=>t.app_ref===e.app_ref).length}),e.ready&&!e.reply_ready?` · ${o(`lark.autoReplyUnavailable`)}`:``]})]},e.app_ref)),l.length===0?(0,B.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noProfiles`)}):null]})]}):null,!p&&s===`connections`?(0,B.jsxs)(`div`,{className:`personal-lark-connections`,children:[Ke>0?(0,B.jsxs)(`p`,{className:`personal-lark-route-readiness`,role:`status`,children:[(0,B.jsx)(Dm,{size:15}),o(`lark.routesUnverified`,{count:Ke})]}):null,(0,B.jsxs)(`div`,{className:`personal-lark-toolbar`,children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(zm,{size:16}),(0,B.jsx)(`input`,{"aria-label":o(`lark.searchConnections`),onChange:e=>v(e.target.value),placeholder:o(`lark.searchPlaceholder`),type:`search`,value:_})]}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:l.length===0||n.length===0,onClick:()=>qe(),type:`button`,children:[(0,B.jsx)(Pm,{size:16}),o(`lark.connectApp`)]})]}),(0,B.jsxs)(`div`,{className:`personal-lark-table`,role:`table`,"aria-label":o(`lark.goalTopicConnections`),children:[(0,B.jsxs)(`div`,{className:`personal-lark-table-head`,role:`row`,children:[(0,B.jsx)(`span`,{children:o(`lark.connection`)}),(0,B.jsx)(`span`,{children:o(`common.goal`)}),(0,B.jsx)(`span`,{children:o(`lark.capture`)}),(0,B.jsx)(`span`,{children:o(`lark.processing`)}),(0,B.jsx)(`span`,{children:o(`common.actions`)})]}),Ge.map(e=>{let t=Db(e,o);return(0,B.jsxs)(`div`,{className:`personal-lark-table-row`,role:`row`,children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.chat_name}),(0,B.jsxs)(`small`,{children:[e.app_label,` · `,t.label]}),(0,B.jsx)(`small`,{children:t.detail}),t.state===`unverified`?(0,B.jsxs)(`a`,{href:`https://open.feishu.cn/document/server-docs/im-v1/message/events/receive?lang=zh-CN`,rel:`noreferrer`,target:`_blank`,children:[(0,B.jsx)(fm,{size:12}),o(`lark.openEventSettings`)]}):null,Ob(e)?(0,B.jsxs)(`a`,{href:Ob(e)??void 0,rel:`noreferrer`,target:`_blank`,children:[(0,B.jsx)(fm,{size:12}),o(`lark.historyPermission`)]}):null]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.goal_title}),(0,B.jsxs)(`small`,{children:[`# `,e.topic_name]})]}),(0,B.jsx)(`span`,{children:e.capture_scope===`addressed_only`?o(`lark.mentionsOnly`):o(`lark.allTopicMessages`)}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.conversation_kind===`manager`?o(`lark.managerConversation`):Eb(e.ingress_mode,o).label}),(0,B.jsx)(`small`,{children:e.conversation_kind===`manager`?o(`lark.managerConversationDescription`):e.agent_id??Eb(e.ingress_mode,o).detail})]}),(0,B.jsxs)(`span`,{className:`personal-lark-row-actions`,children:[(0,B.jsx)(`button`,{"aria-label":o(`lark.settingsConfigure`,{goal:e.goal_title}),onClick:()=>Je(e),type:`button`,children:(0,B.jsx)(Um,{size:15})}),(0,B.jsxs)(`button`,{"aria-label":o(`lark.settingsDisconnect`,{goal:e.goal_title}),className:ye===e.connection_id?`is-confirm`:``,onClick:()=>void $e(e.goal_id,e.connection_id),type:`button`,children:[(0,B.jsx)(Qm,{size:15}),ye===e.connection_id?o(`common.confirm`):null]})]})]},e.connection_id)}),Ge.length===0?(0,B.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noConnections`)}):null]})]}):null,y?(0,B.jsx)(`div`,{className:`personal-lark-modal-backdrop`,role:`presentation`,children:(0,B.jsxs)(`section`,{"aria-labelledby":`connect-lark-title`,"aria-modal":`true`,className:`personal-lark-modal`,role:`dialog`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:`Goal Topic connection`}),(0,B.jsx)(`h2`,{id:`connect-lark-title`,children:o(he?`lark.editConnection`:`lark.connectApp`)})]}),(0,B.jsx)(`button`,{"aria-label":o(`lark.closeConnection`),onClick:()=>b(!1),type:`button`,children:(0,B.jsx)($m,{size:18})})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.conversationKind`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.conversationKind`),disabled:!!_e,value:P,onChange:e=>F(e.target.value),children:[(0,B.jsx)(`option`,{value:`manager`,children:o(`lark.managerConversation`)}),(0,B.jsx)(`option`,{value:`goal`,children:o(`lark.workerConversation`)})]})]}),P===`manager`?(0,B.jsx)(`p`,{children:o(`lark.managerConversationDescription`)}):null,_e?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,B.jsx)(`div`,{children:_e.app_label})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,B.jsx)(`div`,{children:_e.chat_name})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,B.jsx)(`div`,{children:_e.goal_title})]}),(0,B.jsx)(`small`,{children:o(`lark.editPreservesIdentity`)})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,B.jsx)(`select`,{"aria-label":o(`lark.appProfile`),disabled:p,onChange:e=>{e.target.value===`__register__`?Ye():(S(e.target.value),ue({}))},value:x,children:p?(0,B.jsx)(`option`,{value:``,children:o(`lark.appLoading`)}):(0,B.jsxs)(B.Fragment,{children:[l.map(e=>(0,B.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref)),(0,B.jsx)(`option`,{value:`__register__`,children:o(`lark.registerAnother`)})]})}),(0,B.jsx)(`small`,{children:o(`lark.defaultAgentAppDescription`)})]}),Ue?.ready&&!Ue.reply_ready?(0,B.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.appPermissions`)}):null,(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,B.jsx)(`input`,{"aria-label":o(`lark.groupSearch`),onChange:e=>E(e.target.value),placeholder:o(`lark.groupSearch`),type:`search`,value:T}),ne?(0,B.jsxs)(`div`,{className:`personal-lark-group-state`,role:`status`,children:[(0,B.jsx)(Cm,{className:`is-spinning`,size:15}),o(`lark.groupLoading`)]}):null,!ne&&A?(0,B.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:A}):null,!ne&&!A&&D.length===0?(0,B.jsx)(`div`,{className:`personal-lark-group-state`,role:`status`,children:o(`lark.groupEmpty`)}):null,!ne&&!A&&D.length>0?(0,B.jsx)(`select`,{"aria-label":o(`lark.groupChat`),onChange:e=>te(e.target.value),value:ee,children:D.map(e=>(0,B.jsx)(`option`,{value:e.chat_id,children:e.chat_name},e.chat_id))}):null]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,B.jsx)(`select`,{"aria-label":o(`lark.bindGoal`),onChange:e=>{let t=e.target.value;w(t),oe(n.find(e=>e.goalId===t)?.agentId??``),ue({})},value:C,children:n.map(e=>(0,B.jsx)(`option`,{value:e.goalId,children:e.title},e.goalId))})]})]}),(0,B.jsxs)(`label`,{className:`personal-lark-check`,children:[(0,B.jsx)(`input`,{checked:!0,readOnly:!0,type:`checkbox`}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:o(`lark.createAutomatically`)}),(0,B.jsx)(`small`,{children:o(`lark.createAutomaticallyDescription`)})]})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.topicPreview`)}),(0,B.jsxs)(`div`,{className:`personal-lark-topic-preview`,children:[(0,B.jsx)(Dm,{size:15}),`# `,V?.title??V?.goalId??`Goal`]})]}),P===`goal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.captureScope`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.captureScope`),disabled:_e?.ingress_mode===`direct_session`,onChange:e=>N(e.target.value),value:M,children:[(0,B.jsx)(`option`,{value:`addressed_only`,children:o(`lark.captureAddressed`)}),(0,B.jsx)(`option`,{value:`configured_chat_all`,children:o(`lark.captureAll`)})]}),(0,B.jsx)(`small`,{children:o(`lark.captureScopeDescription`)})]}),(0,B.jsxs)(`fieldset`,{"aria-label":o(`lark.agentIngress`),className:`personal-lark-ingress`,children:[(0,B.jsx)(`legend`,{children:o(`lark.agentIngress`)}),(0,B.jsx)(`div`,{children:[`live_steering`,`session_queue`,`async_inbox`].map(e=>{let t=Eb(e,o);return(0,B.jsxs)(`label`,{className:re===e?`is-active`:``,children:[(0,B.jsx)(`input`,{"aria-label":t.label,checked:re===e,name:`lark-agent-ingress`,onChange:()=>ie(e),type:`radio`,value:e}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:t.label}),(0,B.jsx)(`small`,{children:t.detail})]})]},e)})})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.targetAgent`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.targetAgent`),disabled:!!_e?.agent_id,onChange:e=>oe(e.target.value),value:L,children:[Re?null:(0,B.jsx)(`option`,{disabled:!0,value:L,children:L?o(`lark.agentUnavailable`,{agent:L}):o(`lark.noAgentConfigured`)}),Le.map(e=>(0,B.jsx)(`option`,{value:e.agentId,children:e.label===e.agentId?e.agentId:`${e.label} · ${e.agentId}`},e.agentId))]}),(0,B.jsx)(`small`,{children:o(`lark.targetAgentDescription`)})]}),!he&&Le.length>1?(0,B.jsxs)(`label`,{"aria-label":o(`lark.connectAllAgents`),className:`personal-lark-check`,children:[(0,B.jsx)(`input`,{checked:se,onChange:e=>ce(e.target.checked),type:`checkbox`}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:o(`lark.connectAllAgents`)}),(0,B.jsx)(`small`,{children:o(`lark.connectAllAgentsDescription`,{count:Le.length})})]})]}):null,!he&&se&&Le.length>1?(0,B.jsxs)(`fieldset`,{"aria-label":o(`lark.agentApps`),className:`personal-lark-agent-apps`,children:[(0,B.jsx)(`legend`,{children:o(`lark.agentApps`)}),(0,B.jsx)(`small`,{children:o(`lark.agentAppsDescription`)}),(0,B.jsx)(`div`,{children:Le.map(e=>(0,B.jsxs)(`label`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsx)(`small`,{children:e.agentId})]}),(0,B.jsx)(`select`,{"aria-label":o(`lark.agentAppSelection`,{agent:e.label}),onChange:t=>ue(n=>({...n,[e.agentId]:t.target.value})),value:le[e.agentId]??x,children:l.map(e=>(0,B.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref))})]},e.agentId))})]}):null,se&&ze.length>0&&!Ve?(0,B.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.agentAppPermissions`)}):null,Be.length===0?(0,B.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:o(`lark.selectRegisteredAgent`)}):null]}):null,(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.replyMode`)}),(0,B.jsx)(`select`,{"aria-label":o(`lark.replyMode`),onChange:e=>ae(e.target.value),value:I,children:(0,B.jsx)(`option`,{value:`topic_reply`,children:o(`lark.topicReply`)})}),(0,B.jsx)(`small`,{children:o(`lark.replyModeDescription`)})]}),(0,B.jsxs)(`p`,{className:`personal-lark-cardinality`,children:[(0,B.jsx)(em,{size:15}),o(`lark.cardinality`)]}),pe?(0,B.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:pe}):null,(0,B.jsxs)(`footer`,{children:[(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>b(!1),type:`button`,children:o(`lark.cancel`)}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:p||!x||!_e&&(!Ue?.reply_ready||!ee)||P===`goal`&&(!Ve||Be.length===0)||!C||de,onClick:()=>void Qe(),type:`button`,children:[de?(0,B.jsx)(Cm,{className:`is-spinning`,size:15}):null,He]})]})]})}):null,xe?(0,B.jsx)(`div`,{className:`personal-lark-modal-backdrop is-setup`,role:`presentation`,children:(0,B.jsxs)(`section`,{"aria-labelledby":`new-lark-app-title`,"aria-modal":`true`,className:`personal-lark-modal personal-lark-setup-modal`,role:`dialog`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:o(`lark.reusableWorkspaceApp`)}),(0,B.jsx)(`h2`,{id:`new-lark-app-title`,children:o(`lark.newApp`)})]}),(0,B.jsx)(`button`,{"aria-label":o(`lark.closeCreate`),onClick:()=>void Ze(),type:`button`,children:(0,B.jsx)($m,{size:18})})]}),R?(0,B.jsxs)(`div`,{className:`personal-lark-setup-progress`,children:[(0,B.jsx)(`span`,{className:`personal-lark-setup-icon is-${R.status}`,children:R.status===`ready`?(0,B.jsx)(em,{size:22}):(0,B.jsx)(Cm,{className:R.status===`failed`?``:`is-spinning`,size:22})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:R.status===`ready`?o(`lark.appCreated`):R.status===`failed`?o(`lark.appCreateFailed`):o(`lark.waitingFeishu`)}),(0,B.jsx)(`p`,{children:R.status===`waiting_for_feishu`?o(`lark.waitingFeishuDescription`):R.status===`starting`?o(`lark.waitingLink`):R.error})]}),R.verification_url?(0,B.jsxs)(`a`,{href:R.verification_url,rel:`noreferrer`,target:`_blank`,children:[(0,B.jsx)(fm,{size:15}),o(`lark.reopenFeishu`)]}):null]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`personal-lark-setup-copy`,children:o(`lark.setupCopy`)}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.profileName`)}),(0,B.jsx)(`input`,{"aria-label":o(`lark.profileName`),autoComplete:`off`,onChange:e=>we(e.target.value),placeholder:`loopx-workspace-bot`,value:Ce})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.region`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.region`),onChange:e=>Ee(e.target.value),value:Te,children:[(0,B.jsx)(`option`,{value:`feishu`,children:`Feishu`}),(0,B.jsx)(`option`,{value:`lark`,children:`Lark`})]})]}),Ce&&!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Ce)?(0,B.jsx)(`p`,{className:`personal-notification-error`,children:o(`lark.profileValidation`)}):null]}),Ae?(0,B.jsx)(`p`,{className:`personal-notification-error`,children:Ae}):null,(0,B.jsxs)(`footer`,{children:[(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void Ze(),type:`button`,children:o(`lark.cancel`)}),R?null:(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:Oe||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Ce),onClick:()=>void Xe(),type:`button`,children:[Oe?(0,B.jsx)(Cm,{className:`is-spinning`,size:15}):(0,B.jsx)(fm,{size:15}),o(`lark.continueFeishu`)]})]})]})}):null]})}function jb(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function Mb(e,t,n){let r=jb(t),i=jb(n);return Object.fromEntries(e.fields.flatMap(({key:e,nullable:t})=>{let n=r[e],a=i[e];return Object.hasOwn(r,e)&&(n!=null||t&&n===null)?[[e,n]]:Object.hasOwn(i,e)&&a!=null?[[e,a]]:[]}))}function Nb(e,t){let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=new Set(e.fields.map(e=>e.key));return Object.keys(n).some(e=>!r.has(e))?null:n}function Pb(e,t,n){let r={...e,[t]:n},i=e.schedule;return t===`timezone`&&i&&typeof i==`object`&&`schema_version`in i&&i.schema_version===`periodic_report_schedule_v0`&&(r.schedule={...i,timezone:n}),r}function Fb({id:e,value:t,timezone:n,onChange:r}){let{locale:i}=Ji(),a=i===`zh-CN`,o=t&&typeof t==`object`&&!Array.isArray(t)?t:null,s=String(o?.rrule??``).split(`;`).map(e=>e.split(`=`)),c=Object.fromEntries(s.filter(e=>e.length===2)),l=[`MO`,`TU`,`WE`,`TH`,`FR`,`SA`,`SU`],u=(e,t)=>e!==void 0&&/^\d+$/.test(e)&&Number(e)<=t,d=!o||o.schema_version===`periodic_report_schedule_v0`&&[`DAILY`,`WEEKLY`].includes(c.FREQ)&&o.timezone===n&&s.every(e=>e.length===2&&[`FREQ`,`BYDAY`,`BYHOUR`,`BYMINUTE`,`INTERVAL`].includes(e[0]))&&new Set(s.map(([e])=>e)).size===s.length&&u(c.BYHOUR,23)&&u(c.BYMINUTE??`0`,59)&&(c.FREQ===`WEEKLY`?l.includes(c.BYDAY):!c.BYDAY)&&(!c.INTERVAL||c.INTERVAL===`1`),f=a?[`星期一`,`星期二`,`星期三`,`星期四`,`星期五`,`星期六`,`星期日`]:[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`];function p(e){let t={FREQ:`WEEKLY`,BYDAY:`MO`,BYHOUR:`9`,BYMINUTE:`0`,...c,...e};r?.({schema_version:`periodic_report_schedule_v0`,schedule_id:o?.schedule_id??`report-schedule`,timezone:n,rrule:[`FREQ=${t.FREQ}`,...t.FREQ===`WEEKLY`?[`BYDAY=${t.BYDAY}`]:[],`BYHOUR=${t.BYHOUR}`,`BYMINUTE=${t.BYMINUTE}`].join(`;`)})}return(0,B.jsxs)(`div`,{className:`personal-report-schedule`,children:[(0,B.jsxs)(`label`,{className:`is-boolean`,htmlFor:e,children:[(0,B.jsx)(`span`,{children:a?`按日历汇报`:`Calendar reports`}),(0,B.jsx)(`input`,{id:e,type:`checkbox`,role:`switch`,checked:!!o,disabled:!r,onChange:e=>e.target.checked?p({}):r?.(null)})]}),o?(0,B.jsxs)(B.Fragment,{children:[d?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{htmlFor:`${e}-frequency`,children:[(0,B.jsx)(`span`,{children:a?`频率`:`Frequency`}),(0,B.jsxs)(`select`,{id:`${e}-frequency`,value:c.FREQ,disabled:!r,onChange:e=>p({FREQ:e.target.value}),children:[(0,B.jsx)(`option`,{value:`DAILY`,children:a?`每天`:`Daily`}),(0,B.jsx)(`option`,{value:`WEEKLY`,children:a?`每周`:`Weekly`})]})]}),c.FREQ===`WEEKLY`&&(0,B.jsxs)(`label`,{htmlFor:`${e}-day`,children:[(0,B.jsx)(`span`,{children:a?`星期`:`Weekday`}),(0,B.jsx)(`select`,{id:`${e}-day`,value:c.BYDAY,disabled:!r,onChange:e=>p({BYDAY:e.target.value}),children:l.map((e,t)=>(0,B.jsx)(`option`,{value:e,children:f[t]},e))})]}),(0,B.jsxs)(`label`,{htmlFor:`${e}-time`,children:[(0,B.jsxs)(`span`,{children:[a?`当地时间`:`Local time`,` (`,n,`)`]}),(0,B.jsx)(`input`,{id:`${e}-time`,type:`time`,required:!0,disabled:!r,value:`${(c.BYHOUR??`9`).padStart(2,`0`)}:${(c.BYMINUTE??`0`).padStart(2,`0`)}`,onChange:e=>{if(!/^\d{2}:\d{2}$/.test(e.target.value))return;let[t,n]=e.target.value.split(`:`);p({BYHOUR:t,BYMINUTE:n})}})]})]}):(0,B.jsx)(`p`,{role:`alert`,children:a?`此计划需在 JSON 模式中编辑;当前内容已保留。`:`Edit this schedule in JSON mode; its current value is preserved.`}),(0,B.jsx)(`p`,{children:a?`由现有唤醒检查到期计划;实际送达以回执为准。`:`Existing wakes check the schedule; delivery is confirmed by its receipt.`})]}):(0,B.jsx)(`p`,{children:a?`未设置日历计划;保持阶段结束时汇报。`:`No calendar schedule; report at validated stage boundaries.`})]})}function Ib({copy:e,field:t,id:n,onChange:r,value:i,timezone:a}){let o=e[t.key]?.label??t.label,s=!r;if(t.input_kind===`periodic_report_schedule`)return(0,B.jsx)(Fb,{id:n,value:i,timezone:a,onChange:r?e=>r(t.key,e):void 0});if(t.input_kind===`boolean`)return(0,B.jsxs)(`label`,{className:`is-boolean`,htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsx)(`input`,{checked:i===!0,id:n,onChange:r?e=>r(t.key,e.target.checked):void 0,readOnly:s,role:`switch`,type:`checkbox`})]});if(t.input_kind===`select`)return(0,B.jsxs)(`label`,{htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsxs)(`select`,{id:n,onChange:r?e=>r(t.key,e.target.value):void 0,value:typeof i==`string`?i:``,children:[(0,B.jsx)(`option`,{value:``}),(t.options??[]).map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))]})]});if(t.input_kind===`string_list`)return(0,B.jsxs)(`label`,{htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsx)(`textarea`,{id:n,onChange:r?e=>r(t.key,e.target.value.split(/\r?\n/u).filter(Boolean)):void 0,readOnly:s,rows:4,value:Array.isArray(i)?i.join(` +`):``})]});let c=t.input_kind===`number`;return(0,B.jsxs)(`label`,{htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsx)(`input`,{id:n,max:t.maximum,min:t.minimum,onChange:r?e=>r(t.key,c?Number(e.target.value):e.target.value):void 0,readOnly:s,required:t.required,type:c?`number`:`text`,value:typeof i==`number`||typeof i==`string`?i:``})]})}function Lb({copy:e={},disabled:t=!1,editor:n,enabledAction:r,omitKeys:i=[],onChange:a,value:o}){let s=(0,z.useId)(),c=new Set(i);return(0,B.jsx)(`fieldset`,{className:`personal-capability-fields`,disabled:t,children:n.fields.filter(e=>!c.has(e.key)).map(t=>{let n=(0,B.jsx)(Ib,{copy:e,field:t,id:`${s}-${t.key.replace(/[^a-z0-9_-]/gi,`-`)}`,onChange:a,value:o[t.key],timezone:String(o.timezone??`UTC`)},t.key);return t.key===`enabled`&&t.input_kind===`boolean`?(0,B.jsxs)(`div`,{className:`personal-capability-enabled-row`,children:[n,r]},t.key):n})})}var Rb={en:{todo_replan_cadence:{displayName:`Goal review cadence`,description:`Configures the Goal review cadence.`},change_quality_qualification:{displayName:`Change quality qualification`,description:`Prepares a provider-neutral review packet, allows at most one policy-authorized safe-fix pass, and can require an exact-diff receipt.`},explore_graph:{displayName:`Explore Graph`,description:`Organizes bounded exploration as a typed evidence graph so branches, findings, and synthesis remain inspectable.`},explore_harness:{displayName:`Explore Harness`,description:`Selects a capability-owned planning and research harness profile for bounded multi-step exploration.`},lark_event_inbox:{displayName:`Lark event inbox`,description:`Receives provider events through a local-private inbox binding before LoopX projects them into governed work.`,readOnlyReason:`This capability requires a local-private inbox binding. Manage it in Lark settings or through the capability CLI.`},lark_kanban_heartbeat_sync:{displayName:`Lark Kanban heartbeat sync`,description:`Synchronizes accepted LoopX work state to the configured Lark Kanban heartbeat surface.`},local_authority_shadow:{displayName:`Local authority shadow`,description:`Observes post-commit Todo and task-lease state through the shared authority contract without taking write authority.`},multi_subagent:{displayName:`Adaptive child capacity`,description:`Sets bounded child-agent capacity and the public-safe responsibility domains in which parallel work may be delegated.`},peer_task_coordination:{displayName:`Registered-peer task coordination`,description:`Routes explicitly scoped peer-owned work to one registered coordinator without granting cross-owner mutation authority.`},periodic_report:{displayName:`Periodic reports`,description:`Turns validated Goal stage progress into a frozen report and automatically delivers it through the configured Goal Channel with exact readback.`},pull_request_review:{displayName:`Pull-request review`,description:`Ranks the public GitHub PR review queue with a machine-level default; it never grants GitHub, Todo, push, or merge authority.`},reward_memory:{displayName:`Reward Memory experiment`,description:`Configures a reviewed local-private provider binding for Goal-scoped Agent recall and evidence-backed outcome learning.`}},"zh-CN":{todo_replan_cadence:{displayName:`Goal 复核周期`,description:`配置 Goal 的复核周期。`},change_quality_qualification:{displayName:`变更质量验证`,description:`生成与 Provider 无关的审阅包,最多允许一次策略授权的安全修复,并可要求精确 diff 回执。`},explore_graph:{displayName:`探索图谱`,description:`把有界探索组织为 typed 证据图,让探索分支、发现与综合结论都可检查、可追溯。`},explore_harness:{displayName:`探索 Harness`,description:`为有界的多步探索选择由能力负责的规划与研究 Harness profile。`},lark_event_inbox:{displayName:`飞书事件收件箱`,description:`通过本机私有收件箱接收 Provider 事件,再由 LoopX 将其投影为受治理的工作。`,readOnlyReason:`此能力依赖本机私有的收件箱绑定,请在飞书设置或 capability CLI 中管理。`},lark_kanban_heartbeat_sync:{displayName:`飞书看板心跳同步`,description:`把 LoopX 已接受的工作状态同步到配置好的飞书看板心跳界面。`},local_authority_shadow:{displayName:`本地 Authority 影子观测`,description:`通过共享 Authority contract 观测提交后的 Todo 与 task lease 状态,但不取得写入权。`},multi_subagent:{displayName:`自适应子 Agent 容量`,description:`限定子 Agent 容量与可公开的职责域,只有落在这些边界内的工作才能并行委派。`},peer_task_coordination:{displayName:`已注册 Peer 任务协调`,description:`把明确限定的 Peer 工作路由给一个已注册协调者,不授予跨 Owner 修改权限。`},periodic_report:{displayName:`周期报告`,description:`把经过验证的 Goal 阶段进展整理为冻结报告,并通过配置的 Goal Channel 自动发送和精确回读。`},pull_request_review:{displayName:`Pull-request Review`,description:`配置公开 GitHub PR 审阅队列的本机默认排序;不会授予 GitHub、Todo、push 或 merge 权限。`},reward_memory:{displayName:`Reward Memory 实验`,description:`为 Goal 内 Agent 的召回与证据化结果学习配置经过审阅的本机私有 Provider 绑定。`}}},zb={en:{completed_todos:{label:`Completed Todos between Goal reviews`,description:`Machine default or explicit Goal override, from 1 to 5.`},allowed_domains:{label:`Allowed responsibility domains`,description:`Enter one bounded, public-safe domain per line.`},coordinator_agent_id:{label:`Coordinator Agent`,description:`Use an already registered Agent id; leave blank to disable coordination.`},enabled:{label:`Enabled`},model:{label:`Child model`,description:`For example gpt-5.6-luna. Blank clears the child model preference.`},reasoning_effort:{label:`Child reasoning effort`,description:`For example max; the host must support this model and effort.`},max_children:{label:`Maximum children`,description:`Hard upper bound for concurrently delegated child work.`},profile:{label:`Planner profile`,description:`Select one registered Explore Harness profile.`},profile_preset:{label:`Report profile`,description:`Capability-owned report profile, such as weekly-progress.`},review_priority:{label:`Review priority`,description:`Choose whether other developers' PRs or the authenticated reviewer's own PRs are ranked first.`},route_ref:{label:`Goal Channel route`,description:`Public route alias only; credentials and provider identifiers stay outside this form.`},safe_fix:{label:`Allow one bounded safe-fix pass`},strict_receipt:{label:`Require an exact-diff receipt`},timezone:{label:`Timezone`,description:`Use an IANA timezone, for example Asia/Shanghai.`},schedule:{label:`Calendar reports`,description:`Optional daily or weekly reports; no schedule preserves stage-only delivery.`},config_path:{label:`Local-private configuration path`,description:`Repo-relative ignored JSON under .loopx/config/. Leave blank to retain the current binding; the path is never returned.`},enabled_agents:{label:`Enabled Goal Agents`,description:`Enter one registered Goal-local Agent id per line. A private binding currently accepts exactly one Agent.`}},"zh-CN":{completed_todos:{label:`两次 Goal 复核间的已完成 Todo 数`,description:`可设置 1–5;机器默认值可被 Goal 显式覆盖。`},allowed_domains:{label:`允许的职责域`,description:`每行填写一个有边界、可公开的职责域。`},coordinator_agent_id:{label:`协调 Agent`,description:`填写一个已经注册的 Agent ID;留空表示关闭协调。`},enabled:{label:`启用`},model:{label:`子 Agent 模型`,description:`例如 gpt-5.6-luna;留空清除模型偏好。`},reasoning_effort:{label:`子 Agent 推理档位`,description:`例如 max;宿主须支持所选模型与档位。`},max_children:{label:`最大子 Agent 数`,description:`可同时委派的子任务硬上限。`},profile:{label:`规划 Profile`,description:`选择一个已注册的 Explore Harness profile。`},profile_preset:{label:`报告 Profile`,description:`由该能力管理的报告 profile,例如 weekly-progress。`},review_priority:{label:`审阅优先级`,description:`选择先排其他开发者的 PR,还是先排当前已认证审阅者自己的 PR。`},route_ref:{label:`Goal Channel 路由`,description:`只填写公开 route alias;凭据与 Provider 标识不会进入此表单。`},safe_fix:{label:`允许一次有界安全修复`},strict_receipt:{label:`要求精确 diff 回执`},timezone:{label:`时区`,description:`使用 IANA 时区,例如 Asia/Shanghai。`},schedule:{label:`日历汇报`,description:`可选每日或每周计划;未设置时保持阶段结束汇报。`},config_path:{label:`本机私有配置路径`,description:`填写 .loopx/config/ 下、相对仓库且被忽略的 JSON;留空保留当前绑定,路径不会被回传。`},enabled_agents:{label:`已启用的 Goal Agent`,description:`每行填写一个已注册的 Goal 内 Agent ID;私有绑定当前只接受一个 Agent。`}}};function Bb(e,t){let n=Rb[t][e.capability_id];return n?{...e,display_name:n.displayName,description:n.description,configuration_editor:{...e.configuration_editor,...n.readOnlyReason?{read_only_reason:n.readOnlyReason}:{}}}:e}function Vb(e){return zb[e]}Object.freeze(Object.keys(Rb.en).sort());function Hb(e,t){return e.available_scopes.includes(t)&&(t!==`machine`||!!e.machine_namespace)&&e.configuration_editor.editable&&e.configuration_editor.writable_scopes.includes(t)}function Ub({values:e,t}){return(0,B.jsxs)(`details`,{className:`personal-capability-raw-values`,children:[(0,B.jsx)(`summary`,{children:t(`capabilities.rawJson`)}),(0,B.jsx)(`div`,{className:`personal-capability-value-grid`,children:e.map(({label:e,value:t})=>(0,B.jsxs)(`section`,{children:[(0,B.jsx)(`strong`,{children:e}),(0,B.jsx)(`pre`,{children:t?JSON.stringify(t,null,2):`—`})]},e))})]})}function Wb({source:e,t}){return e?(0,B.jsxs)(`p`,{className:`personal-capability-effective-source`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:15}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:t(`capabilities.effectiveSource`)}),t(`capabilities.source.${e}`)]})]}):null}function Gb({available:e,description:t,t:n}){return e?null:(0,B.jsxs)(`section`,{className:`personal-capability-editor-status is-read-only`,children:[(0,B.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:n(`capabilities.readOnly`)}),(0,B.jsx)(`p`,{children:t})]})]})}function Kb(e){return e.availability?.includes(`experimental`)?4:e.capability_id===`multi_subagent`?3:e.configuration_editor.writable_scopes.length===0||e.availability===`supported_explicit_opt_in`?2:e.availability===`supported_explicit_override`?0:1}function qb(e,t){return[...e].sort((e,n)=>{let r=Kb(e)-Kb(n);if(r!==0)return r;let i=Bb(e,t),a=Bb(n,t);return i.display_name.localeCompare(a.display_name,t)||e.capability_id.localeCompare(n.capability_id)})}function Jb({capabilities:e,locale:t,onSelect:n,scope:r,selectedCapabilityId:i,t:a}){return(0,B.jsx)(`nav`,{"aria-label":a(r===`goal`?`capabilities.catalog`:`machine.capabilityCatalog`),className:`personal-capability-list`,tabIndex:0,children:qb(e,t).map(e=>{let o=Bb(e,t);return(0,B.jsxs)(`button`,{"aria-current":i===o.capability_id?`page`:void 0,onClick:()=>n(o.capability_id),type:`button`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:o.display_name})}),(0,B.jsx)(`em`,{children:a(o.available_scopes.includes(r)?r===`goal`?`capabilities.goalScope`:`capabilities.machineScope`:r===`machine`?`capabilities.goalScope`:`capabilities.machineScope`)})]},o.capability_id)})})}function Yb({capability:e,locale:t,source:n}){let{t:r}=Ji(),i=Bb(e,t);return(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`span`,{className:`personal-settings-icon`,children:(0,B.jsx)(Gm,{"aria-hidden":!0,size:18})}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`div`,{className:`personal-capability-heading-row`,children:[(0,B.jsx)(`h2`,{children:i.display_name}),(0,B.jsx)(Wb,{source:n,t:r})]}),e.context_contribution&&(0,B.jsxs)(`details`,{className:`personal-capability-help`,"data-testid":`capability-context-phases`,children:[(0,B.jsx)(`summary`,{children:t===`zh-CN`?`主 Agent 协作指导`:`Coordinator workflow guidance`}),(0,B.jsx)(`p`,{children:t===`zh-CN`?`随能力开启。支持以下阶段;此处展示能力范围,不能证明某次运行已读取或采纳。`:`Enabled with this capability. These are supported phases, not proof that a run read or adopted the guidance.`}),(0,B.jsx)(`dl`,{children:e.context_contribution.supported_phases.map(e=>(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:(0,B.jsx)(`code`,{children:e})}),(0,B.jsx)(`dd`,{children:Xb[e][t===`zh-CN`?`zh`:`en`]})]},e))}),(0,B.jsx)(`p`,{children:t===`zh-CN`?`LoopX Turn 在请求与结果中提供上下文;原生工具入口由 LoopX skill 调用同一只读接口。执行与采纳需另看运行证据。`:`LoopX Turn includes context in requests and results. For native tools, the LoopX skill reads the same interface. Execution and adoption require run evidence.`})]}),(0,B.jsxs)(`details`,{className:`personal-capability-help`,children:[(0,B.jsx)(`summary`,{children:t===`zh-CN`?`配置说明`:`Configuration help`}),(0,B.jsx)(`p`,{children:i.description}),(0,B.jsx)(`dl`,{children:e.configuration_editor.fields.map(e=>{let n=Vb(t)[e.key],r=n?.description??e.description;return r?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:n?.label??e.label}),(0,B.jsx)(`dd`,{children:r})]},e.key):null})})]},e.capability_id)]})]})}var Xb={before_plan:{zh:`规划前:识别独立问题并保留主 Agent 的核验与整合职责。`,en:`Before planning: identify independent questions and retain coordinator validation and integration.`},before_delegate:{zh:`委派前:明确子任务边界、模型偏好及预期证据。`,en:`Before delegation: specify task boundaries, model preferences and expected evidence.`},after_delegate_result:{zh:`回收后:核验结果,说明采纳决定并关联计划与成果。`,en:`After results: validate evidence, explain acceptance and link plans and deliverables.`}};function Zb({goalId:e,onApplied:t,selected:n,t:r}){let[i,a]=(0,z.useState)({busy:null,draft:{},partialWrite:null,preview:null}),[o,s]=(0,z.useState)(null),[c,l]=(0,z.useState)(`guided`),[u,d]=(0,z.useState)(``),f=(0,z.useMemo)(()=>n?Nb(n.configuration_editor,u):null,[n,u]),p=c===`guided`||f!==null;(0,z.useEffect)(()=>{l(`guided`),d(``),a({busy:null,draft:Mb(n?.configuration_editor??{fields:[]},n?.current??n?.effective_configuration?.configuration??n?.default,n?.default),partialWrite:null,preview:null}),s(null)},[n]);async function m(t){if(!(!n||i.busy||!p)){a(e=>({...e,busy:`preview`,partialWrite:null})),s(null);try{let r=await Dg(e,n.capability_id,t);a(e=>({...e,preview:r}))}catch(e){s(e instanceof Error?e.message:r(`capabilities.previewFailed`))}finally{a(e=>({...e,busy:null}))}}}async function h(){if(!(!n||!i.preview||i.busy||!p)){a(e=>({...e,busy:`apply`})),s(null);try{let r=Mb(n.configuration_editor,i.draft,n.default),o=await Og(e,n.capability_id,i.preview.action===`delete`?null:r,i.preview.plan_revision);a(e=>({...e,partialWrite:o.status===`partial_write`?o:null,preview:null})),o.status!==`partial_write`&&t()}catch(e){a(e=>({...e,preview:null})),s(e instanceof Error?e.message:r(`capabilities.applyFailed`))}finally{a(e=>({...e,busy:null}))}}}function g(e,t){a(r=>({...r,draft:n?.capability_id===`periodic_report`?Pb(r.draft,e,t):{...r.draft,[e]:t},preview:null})),s(null)}function _(e){if(!n||i.busy)return;d(e);let t=Nb(n.configuration_editor,e);a(e=>({...e,preview:null,draft:t?Mb(n.configuration_editor,t,n.default):e.draft})),s(null)}function v(){i.busy||!p||(c===`guided`&&d(JSON.stringify(i.draft,null,2)),l(c===`guided`?`json`:`guided`),a(e=>({...e,preview:null})))}return{apply:h,changeDraft:g,changeJson:_,changeMode:v,editorMode:c,jsonDraft:u,jsonValid:p,error:o,mutation:i,preview:m}}function Qb({mutationError:e,onApplied:t,partialWrite:n,preview:r}){let{t:i}=Ji();return(0,B.jsxs)(B.Fragment,{children:[e?(0,B.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:e}):null,n?(0,B.jsxs)(`section`,{"aria-live":`polite`,className:`personal-capability-recovery`,children:[(0,B.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:i(`capabilities.partialWrite`)}),(0,B.jsx)(`p`,{children:i(`capabilities.partialWriteDescription`)}),(0,B.jsx)(`small`,{children:n.recommended_action})]}),(0,B.jsxs)(`button`,{onClick:t,type:`button`,children:[(0,B.jsx)(Im,{"aria-hidden":!0,size:15}),i(`capabilities.refreshSource`)]})]}):null,r?(0,B.jsxs)(`section`,{className:`personal-capability-preview`,"aria-label":i(`capabilities.preview`),children:[(0,B.jsx)(`strong`,{children:i(`capabilities.preview`)}),(0,B.jsx)(`span`,{children:i(`machine.action.${r.action}`)}),(0,B.jsx)(`small`,{children:i(`capabilities.previewLocked`)})]}):null]})}function $b({catalog:e,goalId:t,onApplied:n}){let{locale:r,t:i}=Ji(),a=(0,z.useMemo)(()=>qb(e.capabilities,r),[e.capabilities,r]),[o,s]=(0,z.useState)(()=>a[0]?.capability_id??``),c=(0,z.useMemo)(()=>a.find(e=>e.capability_id===o)??a[0],[a,o]),l=(0,z.useMemo)(()=>c?Bb(c,r):void 0,[r,c]),{apply:u,changeDraft:d,changeJson:f,changeMode:p,editorMode:m,jsonDraft:h,jsonValid:g,error:_,mutation:v,preview:y}=Zb({goalId:t,onApplied:n,selected:l,t:i}),{busy:b,draft:x,partialWrite:S,preview:C}=v;if(!c||!l)return(0,B.jsx)(`p`,{className:`personal-capability-empty`,children:i(`capabilities.empty`)});let w=l.available_scopes.includes(`goal`),T=Hb(l,`goal`),E=l.configuration_editor.read_only_reason??i(w?`capabilities.previewOnly`:`capabilities.machineOnly`);async function D(){if(!l||!T||b||!g)return;let e=Mb(l.configuration_editor,x,l.default);await y(e)}async function O(){!T||b||await y(null)}return(0,B.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,B.jsx)(Jb,{capabilities:e.capabilities,locale:r,onSelect:s,scope:`goal`,selectedCapabilityId:l.capability_id,t:i}),(0,B.jsxs)(`article`,{"aria-label":l.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,B.jsx)(Yb,{capability:c,locale:r,source:l.effective_configuration?.source}),(0,B.jsx)(Gb,{available:T,t:i,description:E}),T?(0,B.jsxs)(B.Fragment,{children:[m===`json`||!l.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,B.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,B.jsxs)(`button`,{disabled:!!b||!g,onClick:p,type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),i(m===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,m===`guided`?(0,B.jsx)(`section`,{className:`personal-capability-field-summary`,children:(0,B.jsx)(Lb,{disabled:!!b,copy:Vb(r),editor:l.configuration_editor,onChange:d,value:x,enabledAction:(0,B.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:p,type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),i(`machine.editJson`)]})})}):(0,B.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`goal-configuration-json`,children:[(0,B.jsx)(`span`,{children:i(`capabilities.jsonConfiguration`)}),(0,B.jsx)(`textarea`,{id:`goal-configuration-json`,"aria-describedby":`goal-configuration-json-help`,disabled:!!b,onChange:e=>f(e.target.value),rows:12,spellCheck:!1,value:h}),(0,B.jsx)(`small`,{id:`goal-configuration-json-help`,children:i(`capabilities.jsonHelp`)}),g?null:(0,B.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:i(`capabilities.jsonInvalid`)})]})]}):null,(0,B.jsx)(Qb,{mutationError:_,onApplied:n,partialWrite:S,preview:C}),T?(0,B.jsxs)(`footer`,{className:`personal-capability-actions`,children:[l.current&&l.available_scopes.includes(`machine`)?(0,B.jsx)(`button`,{disabled:!!b||!g,onClick:()=>void O(),type:`button`,children:i(`capabilities.restoreInheritance`)}):null,(0,B.jsx)(`button`,{disabled:!!b||!g,onClick:()=>void D(),type:`button`,children:i(b===`preview`?`common.loading`:`capabilities.previewChanges`)}),(0,B.jsx)(`button`,{className:`is-primary`,disabled:!!b||!C||!g,onClick:()=>void u(),type:`button`,children:i(b===`apply`?`common.loading`:`capabilities.applyPreview`)})]}):null,(0,B.jsx)(Ub,{values:[{label:i(`capabilities.goalValue`),value:l.current},{label:i(l.machine_current?`capabilities.machineValue`:`capabilities.defaultValue`),value:l.machine_current??l.default}],t:i},c.capability_id)]})]})}function ex({goalId:e}){let{t}=Ji(),[n,r]=(0,z.useState)(null),[i,a]=(0,z.useState)(null),[o,s]=(0,z.useState)(!1);function c(){e&&(s(!0),a(null),Eg(e).then(r).catch(e=>a(e instanceof Error?e.message:t(`capabilities.loadFailed`))).finally(()=>s(!1)))}return(0,z.useEffect)(c,[e]),e?o&&!n?(0,B.jsxs)(`p`,{"aria-live":`polite`,className:`personal-capability-empty`,children:[(0,B.jsx)(Cm,{className:`personal-spin`,size:18}),t(`capabilities.loading`)]}):i?(0,B.jsxs)(`section`,{className:`personal-capability-error`,role:`alert`,children:[(0,B.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:t(`capabilities.loadFailed`)}),(0,B.jsx)(`small`,{children:i})]}),(0,B.jsxs)(`button`,{onClick:c,type:`button`,children:[(0,B.jsx)(Im,{"aria-hidden":!0,size:15}),t(`capabilities.retry`)]})]}):n?(0,B.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":n.revision,children:[(0,B.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:17}),t(`capabilities.atomicOverride`)]}),(0,B.jsx)(`p`,{children:t(`capabilities.atomicOverrideDescription`)})]}),(0,B.jsx)($b,{catalog:n.capability_catalog,goalId:e,onApplied:c})]}):null:(0,B.jsx)(`p`,{className:`personal-capability-empty`,children:t(`capabilities.chooseGoal`)})}function tx(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function nx(e,t){let n=t?.machine_namespace;return n?e?.machine_configuration?.namespaces[n]:void 0}function rx(e,t,n){return{...tx(e.default),...tx(t),...n}}function ix(e,t){for(let n of e.configuration_editor.fields){let e=t[n.key];if(n.required&&(e==null||e===``))return!1}return e.capability_id===`periodic_report`&&t.enabled===!0?!!(String(t.profile_preset??``).trim()&&String(t.route_ref??``).trim()&&String(t.timezone??``).trim()):!0}function ax(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:null}catch{return null}}function ox(e){return e?e===`absent`?e:e.replace(/^sha256:/,``).slice(0,12):`—`}function sx(){let{locale:e,t}=Ji(),[n,r]=(0,z.useState)(null),[i,a]=(0,z.useState)(``),[o,s]=(0,z.useState)({}),[c,l]=(0,z.useState)(`{}`),[u,d]=(0,z.useState)(`guided`),[f,p]=(0,z.useState)(null),[m,h]=(0,z.useState)(`upsert`),[g,_]=(0,z.useState)(null),[v,y]=(0,z.useState)(null),[b,x]=(0,z.useState)(`load`),[S,C]=(0,z.useState)(null),[w,T]=(0,z.useState)(null),E=(0,z.useMemo)(()=>qb(n?.capability_catalog.capabilities??[],e),[n,e]),D=E.find(e=>e.capability_id===i)??E.find(e=>Hb(e,`machine`))??E[0],O=D?Bb(D,e):void 0,ee=nx(n,O),te=!!(O?.machine_namespace&&ee),ne=!!(O&&Hb(O,`machine`)),k=(0,z.useMemo)(()=>ax(c),[c]),A=O?u===`json`?k:rx(O,ee,o):null,j=!!(O&&(u===`json`?k:ix(O,A??{})));async function M(){r(await Tg())}(0,z.useEffect)(()=>{let e=!0;return Tg().then(t=>{e&&r(t)}).catch(n=>{e&&C(n instanceof Error?n.message:t(`machine.loadError`))}).finally(()=>{e&&x(null)}),()=>{e=!1}},[t]),(0,z.useEffect)(()=>{if(!O)return;let e=nx(n,O),t=Mb(O.configuration_editor,e??O.default,O.default),r=rx(O,e,t);s(t),l(JSON.stringify(r,null,2)),d(ne?`guided`:`json`),p(null),h(`upsert`),y(null)},[n,i,e]);function N(e,t){s(n=>O?.capability_id===`periodic_report`?Pb(n,e,t):{...n,[e]:t}),p(null),h(`upsert`),C(null),T(null)}function P(e){if(O){if(e===`json`)l(JSON.stringify(rx(O,ee,o),null,2));else if(k)s(Mb(O.configuration_editor,k,O.default));else{C(t(`machine.jsonInvalid`));return}d(e),p(null),h(`upsert`),C(null)}}async function F(){if(!(!ne||!O?.machine_namespace||!A||!j||b)){x(`preview`),C(null),T(null);try{h(`upsert`),p(await kg(O.machine_namespace,A))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function re(){if(!(!ne||!O?.machine_namespace||!te||b)){x(`preview`),C(null),T(null);try{h(`remove`),p(await jg(O.machine_namespace))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function ie(){if(!ne||!O?.machine_namespace||!f||b||m===`upsert`&&!A)return;x(`apply`),C(null);let e=m;try{let n=e===`remove`?await Mg(O.machine_namespace,f.plan_revision):await Ag(O.machine_namespace,A,f.plan_revision);_(n),p(null),h(`upsert`),y(null),await M(),T(n.status===`applied`?t(e===`remove`?`machine.removed`:`machine.applied`):t(`machine.unchanged`))}catch(e){p(null),h(`upsert`),C(e instanceof Error?e.message:t(`machine.applyError`))}finally{x(null)}}async function I(){if(!(!g?.transaction_id||b)){x(`rollback-preview`),C(null);try{y(await Ng(g.transaction_id))}catch(e){C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}async function ae(){if(!(!g?.transaction_id||!v||b)){x(`rollback`),C(null);try{await Pg(g.transaction_id,v.plan_revision),_(null),y(null),p(null),await M(),T(t(`machine.rolledBack`))}catch(e){y(null),C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}return b===`load`?(0,B.jsx)(`div`,{className:`personal-machine-loading`,role:`status`,children:t(`common.loading`)}):O?(0,B.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":n?.revision,children:[(0,B.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:17}),t(`machine.liveDefault`)]}),(0,B.jsx)(`p`,{children:t(`machine.liveDefaultDescription`)})]}),(0,B.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,B.jsx)(Jb,{capabilities:E,locale:e,onSelect:a,scope:`machine`,selectedCapabilityId:O.capability_id,t}),(0,B.jsxs)(`article`,{"aria-label":O.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,B.jsx)(Yb,{capability:D,locale:e,source:O.available_scopes.includes(`machine`)?te?`machine_default`:`capability_default`:void 0}),(0,B.jsx)(Gb,{available:ne,t,description:O.available_scopes.includes(`machine`)?t(`machine.editorUnavailableDescription`):t(`machine.goalOnly`)}),O.capability_id===`periodic_report`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:ee?.schedule?e===`zh-CN`?`日历与阶段汇报`:`Calendar and stage reports`:t(`machine.periodicReportActivation`)}),(0,B.jsx)(`p`,{children:ee?.schedule?ee.enabled===!0?e===`zh-CN`?`已配置日历计划,由现有唤醒检查;是否送达请核对报告回执。`:`A calendar schedule is configured and checked by existing wakes. Verify delivery in the report receipt.`:e===`zh-CN`?`日历计划已保存;启用此能力后才会检查和投递。`:`The schedule is saved; enable this capability to check and deliver reports.`:t(`machine.periodicReportActivationDescription`)})]})]}):null,O.capability_id===`change_quality_qualification`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.changeQualityActivation`)}),(0,B.jsx)(`p`,{children:t(`machine.changeQualityActivationDescription`)})]})]}):null,O.capability_id===`todo_replan_cadence`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.replanCadenceActivation`)}),(0,B.jsx)(`p`,{children:t(`machine.replanCadenceActivationDescription`)})]})]}):null,O.capability_id===`pull_request_review`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:e===`zh-CN`?`只改变队列排序`:`Queue ordering only`}),(0,B.jsx)(`p`,{children:e===`zh-CN`?`默认先审阅其他开发者的 PR;选择 owner-first 才会优先当前已认证审阅者自己的 PR。此配置不会发布 review、写 Todo、push 或 merge。`:`The default reviews other developers' PRs first; choose owner-first only when the authenticated reviewer's own PRs should lead. This setting never posts a review, writes Todos, pushes, or merges.`})]})]}):null,ne?(0,B.jsxs)(B.Fragment,{children:[u===`json`||!O.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,B.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,B.jsxs)(`button`,{onClick:()=>P(u===`guided`?`json`:`guided`),type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),t(u===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,u===`guided`?(0,B.jsxs)(`section`,{className:`personal-capability-field-summary`,children:[(0,B.jsx)(Lb,{copy:Vb(e),disabled:!!b,editor:O.configuration_editor,onChange:N,value:o,enabledAction:(0,B.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:()=>P(`json`),type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),t(`machine.editJson`)]})}),j?null:(0,B.jsx)(`p`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.requiredFields`)})]}):(0,B.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`machine-configuration-json`,children:[(0,B.jsx)(`span`,{children:t(`machine.jsonConfiguration`)}),(0,B.jsx)(`textarea`,{"aria-describedby":`machine-configuration-json-help`,disabled:!!b,id:`machine-configuration-json`,onChange:e=>{l(e.target.value),p(null),C(null)},rows:12,spellCheck:!1,value:c}),(0,B.jsx)(`small`,{id:`machine-configuration-json-help`,children:t(`machine.jsonConfigurationHelp`)}),k?null:(0,B.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.jsonInvalid`)})]})]}):null,S?(0,B.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:S}):null,w?(0,B.jsxs)(`p`,{className:`personal-machine-notice`,role:`status`,"aria-live":`polite`,children:[(0,B.jsx)(em,{"aria-hidden":!0,size:16}),w]}):null,f?(0,B.jsxs)(`section`,{"aria-label":t(`machine.preview`),className:`personal-machine-preview`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.preview`)}),(0,B.jsx)(`span`,{children:t(`machine.action.${f.action}`)})]}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`machine.currentRevision`)}),(0,B.jsx)(`dd`,{title:f.current_revision,children:ox(f.current_revision)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`machine.desiredRevision`)}),(0,B.jsx)(`dd`,{title:f.desired_revision,children:ox(f.desired_revision)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`machine.changedNamespaces`)}),(0,B.jsx)(`dd`,{children:f.changed_namespaces.join(`, `)||t(`common.none`)})]})]}),(0,B.jsx)(`p`,{children:t(`machine.previewLocked`)})]}):null,g?.rollback_available&&g.transaction_id?(0,B.jsxs)(`section`,{className:`personal-machine-rollback`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.rollbackAvailable`)}),(0,B.jsx)(`p`,{children:t(v?`machine.rollbackPreviewDescription`:`machine.rollbackDescription`)})]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!!b||!!(v&&!v.rollback_allowed),onClick:()=>void(v?ae():I()),type:`button`,children:[(0,B.jsx)(Lm,{"aria-hidden":!0,size:15}),t(b===`rollback`||b===`rollback-preview`?`common.loading`:v?`machine.confirmRollback`:`machine.previewRollback`)]})]}):null,ne?(0,B.jsxs)(`footer`,{className:`personal-capability-actions`,children:[te?(0,B.jsxs)(`button`,{className:`is-danger`,disabled:!!b,onClick:()=>void re(),type:`button`,children:[(0,B.jsx)(Xm,{"aria-hidden":!0,size:15}),t(`machine.previewRemoval`)]}):null,(0,B.jsx)(`button`,{disabled:!!b||!j,onClick:()=>void F(),type:`button`,children:t(b===`preview`?`common.loading`:`machine.previewChanges`)}),(0,B.jsx)(`button`,{className:`is-primary`,disabled:!!b||!f,onClick:()=>void ie(),type:`button`,children:t(b===`apply`?`common.loading`:`machine.applyPreview`)})]}):null,O.available_scopes.includes(`machine`)?(0,B.jsx)(Ub,{values:[{label:t(`machine.currentValue`),value:ee},{label:t(`capabilities.defaultValue`),value:O.default}],t},O.capability_id):null]})]})]}):(0,B.jsx)(`p`,{className:`personal-capability-empty`,children:t(`machine.capabilityEmpty`)})}var cx={appearance:Am,capabilities:Gm,language:bm,lark:Um,machine:Vm};function lx({focusGoalConnection:e=!1,goals:t,initialGoalId:n,initialTab:r=`lark`,onChanged:i,onClose:a,onThemeChange:o,theme:s}){let{locale:c,setLocale:l,t:u}=Ji(),[d,f]=(0,z.useState)(r),p=[...n?[{key:`capabilities`,label:u(`capabilities.title`)}]:[],{key:`machine`,label:u(`machine.title`)},{key:`lark`,label:`Lark`},{key:`appearance`,label:u(`settings.appearance`)},{key:`language`,label:u(`settings.language`)}],m=[{label:u(`settings.languageEnglish`),value:`en`},{label:u(`settings.languageSimplifiedChinese`),value:`zh-CN`}],h={appearance:{title:u(`settings.appearance`)},capabilities:{title:u(`capabilities.title`)},language:{title:u(`settings.language`)},lark:{title:`Lark`},machine:{title:u(`machine.title`)}}[d];return(0,B.jsxs)(`section`,{"aria-label":u(`settings.title`),className:`personal-settings-page`,"data-pw-theme":s,children:[(0,B.jsxs)(`aside`,{className:`personal-settings-sidebar`,children:[(0,B.jsxs)(`button`,{className:`personal-settings-back`,onClick:a,type:`button`,children:[(0,B.jsx)(Gp,{size:17}),(0,B.jsx)(`span`,{children:u(`settings.back`)})]}),(0,B.jsxs)(`div`,{className:`personal-settings-title`,children:[(0,B.jsx)(`small`,{children:u(`settings.eyebrow`)}),(0,B.jsx)(`strong`,{children:u(`settings.title`)})]}),(0,B.jsx)(`nav`,{"aria-label":u(`settings.categories`),className:`personal-settings-tabs`,children:p.map(e=>{let t=cx[e.key];return(0,B.jsxs)(`button`,{"aria-current":d===e.key?`page`:void 0,onClick:()=>f(e.key),type:`button`,children:[(0,B.jsx)(t,{size:17}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:e.label})})]},e.key)})})]}),(0,B.jsxs)(`main`,{className:`personal-settings-body`,children:[(0,B.jsx)(`header`,{className:`personal-settings-header`,children:(0,B.jsx)(`div`,{children:(0,B.jsx)(`h1`,{children:h.title})})}),d===`lark`?(0,B.jsx)(Ab,{embedded:!0,focusGoalConnection:e,goals:t,initialGoalId:n,onChanged:i,onClose:a}):null,d===`machine`?(0,B.jsx)(sx,{}):null,d===`capabilities`?(0,B.jsx)(ex,{goalId:n}):null,d===`appearance`?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-appearance-settings`,children:[(0,B.jsx)(`small`,{children:u(`settings.workspaceDisplay`)}),(0,B.jsx)(`h3`,{children:u(`settings.appearance`)}),(0,B.jsxs)(`div`,{className:`personal-settings-choice-group`,role:`radiogroup`,"aria-label":u(`settings.workspaceTheme`),children:[(0,B.jsxs)(`button`,{"aria-checked":s===`loopx`,onClick:()=>o(`loopx`),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-settings-theme-swatch is-loopx`}),(0,B.jsx)(`strong`,{children:u(`settings.themeLoopx`)})]}),(0,B.jsxs)(`button`,{"aria-checked":s===`paper`,onClick:()=>o(`paper`),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-settings-theme-swatch is-paper`}),(0,B.jsx)(`strong`,{children:u(`settings.themeDefault`)})]}),(0,B.jsxs)(`button`,{"aria-checked":s===`brutal`,onClick:()=>o(`brutal`),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-settings-theme-swatch is-brutal`}),(0,B.jsx)(`strong`,{children:u(`settings.themeHighContrast`)})]})]})]}):null,d===`language`?(0,B.jsxs)(`section`,{className:`personal-settings-card`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`span`,{className:`personal-settings-icon`,children:(0,B.jsx)(bm,{size:18})}),(0,B.jsx)(`div`,{children:(0,B.jsx)(`h2`,{children:u(`settings.language`)})})]}),(0,B.jsx)(`div`,{"aria-label":u(`settings.language`),className:`personal-language-options`,role:`radiogroup`,children:m.map(e=>(0,B.jsxs)(`button`,{"aria-checked":c===e.value,className:c===e.value?`is-selected`:``,onClick:()=>l(e.value),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:e.label})}),c===e.value?(0,B.jsx)(em,{"aria-hidden":!0,size:17}):null]},e.value))})]}):null]})]})}var ux=`loopx-pw-theme`,dx=`loopx`;function fx(){try{let e=window.localStorage.getItem(ux);return e===`loopx`||e===`paper`||e===`brutal`?e:dx}catch{return dx}}function px(e){try{window.localStorage.setItem(ux,e)}catch{}}function mx({drawer:e,drawerMode:t=`panel`,drawerOpen:n,main:r,mobileSidebarOpen:i=!1,onCloseMobileSidebar:a,sidebar:o,theme:s=`loopx`}){let{t:c}=Ji(),l=(0,z.useRef)(null),u=(0,z.useRef)(null);return(0,z.useEffect)(()=>{if(!i)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null;let e=l.current?.querySelectorAll(`button:not([disabled]), a[href], select:not([disabled]), textarea:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])`);e?.[0]?.focus();function t(t){if(t.key!==`Tab`||!e?.length)return;let n=e[0],r=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),r.focus()):!t.shiftKey&&document.activeElement===r&&(t.preventDefault(),n.focus())}return document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`keydown`,t),u.current?.focus(),u.current=null}},[i]),(0,B.jsxs)(`section`,{className:`personal-workspace-shell${n?` has-drawer`:``}${n&&t.startsWith(`inspector`)?` has-task-inspector`:``}${t===`inspector-full`?` is-task-inspector-full`:``}${i?` mobile-sidebar-open`:``}`,"data-pw-theme":s,children:[i?(0,B.jsx)(`button`,{"aria-hidden":!0,className:`personal-sidebar-backdrop`,onClick:a,tabIndex:-1,type:`button`}):null,(0,B.jsx)(`aside`,{"aria-label":i?c(`header.goalNavigation`):void 0,"aria-modal":i?!0:void 0,className:`personal-workspace-sidebar`,"data-workspace-sidebar":!0,ref:l,role:i?`dialog`:void 0,children:(0,B.jsxs)(`div`,{className:`personal-workspace-sidebar-inner`,children:[i?(0,B.jsxs)(`button`,{className:`personal-sr-only`,onClick:a,type:`button`,children:[c(`common.close`),` `,c(`header.goalNavigation`)]}):null,o]})}),(0,B.jsx)(`main`,{"aria-hidden":i||void 0,className:`personal-workspace-main`,inert:i||void 0,children:r}),n?(0,B.jsx)(`aside`,{className:`personal-workspace-drawer`,"data-context-drawer":!0,"data-drawer-mode":t,children:e}):null]})}function hx(e){let t=e.match(/(?:下一步|建议|行动项|待办)[::\s]*([^\n]+)/u),n=t?t[1]:e;n=n.replace(/```[\s\S]*?```/g,``).replace(/`([^`]+)`/g,`$1`).replace(/\[([^\]]+)\]\([^)]+\)/g,`$1`).replace(/[#*~_>]/g,``).replace(/^[-*•\d+.\s]+/u,``).replace(/^(好的|没问题|收到|建议如下|任务如下|分析如下|结论[::])[\s,,::]*/u,``);let r=(n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean)[0]||n).replace(/\s+/gu,` `).trim();return Array.from(r).slice(0,120).join(``)}function gx(e){let t=new Map;return e.forEach(e=>{let n=e.fields.find(e=>e.key===`todo_id`)?.value??``,r=[e.actionKind,e.goalId??``,n,e.title].join(`:`);t.set(r,e)}),[...t.values()]}function _x(e,t,n){if(!e)return n(`home.noFirstActivity`);let r=new Date(e);if(Number.isNaN(r.getTime()))return e;let i=new Date,a=new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r);return r.toDateString()===i.toDateString()?n(`home.todayAt`,{time:a}):new Intl.DateTimeFormat(t,{month:`numeric`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r)}function vx({goals:e,onSelectGoal:t,onRetry:n,systemHealth:r}){let{locale:i,t:a}=Ji(),o=e.filter(e=>e.activationState===`active`),s=o.filter(e=>e.loadState===`error`).length,c=[{key:`needs_you`,label:a(`home.lane.needsYou`)},{key:`running`,label:a(`home.lane.running`)},{key:`observing`,label:a(`home.lane.observing`)},{key:`scheduled`,label:a(`home.lane.scheduled`)}],l=Object.fromEntries(c.map(e=>[e.key,[]])),u=[],d=[];e.filter(e=>!e.loadState).forEach(e=>{let t=gy(e);t===`history`?u.push(e):t===`stopped`?d.push(e):l[t].push(e)});let f=e=>(0,B.jsxs)(`button`,{className:`personal-home-goal-card`,"data-goal-state":e.loadState??e.state,"data-load-error":e.loadError,onClick:()=>t(e.goalId),type:`button`,children:[(0,B.jsxs)(`span`,{className:`personal-home-goal-meta`,children:[(0,B.jsx)(`i`,{}),e.agentLaneCount&&e.agentLaneCount>1?a(`header.workAgentCount`,{count:e.agentLaneCount}):e.agentLabel??e.agentId]}),(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsx)(`p`,{children:e.loadError?a(`startup.error.${e.loadError}`):e.needsYou??e.nextSentence}),(0,B.jsxs)(`footer`,{children:[(0,B.jsx)(`span`,{children:e.loadState?a(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Yi(e.state,i)}),(0,B.jsx)(`small`,{title:e.latestActivity,children:e.loadState?``:e.latestActivity?_x(e.latestActivity,i,a):e.agentTodos.length?a(`home.taskCount`,{count:e.agentTodos.length}):a(`home.noActivity`)})]})]},e.goalId);return(0,B.jsxs)(`section`,{"aria-label":a(`home.workspace`),className:`personal-home-board`,children:[r&&(!r.ok||r.issues.length>0||r.freshnessWarning)?(0,B.jsxs)(`div`,{className:`personal-system-health-banner`,role:`alert`,children:[(0,B.jsxs)(`div`,{className:`personal-system-health-header`,children:[(0,B.jsx)(im,{size:15}),(0,B.jsx)(`strong`,{children:a(`home.systemHealth`,{summary:r.summary})}),r.freshnessWarning?(0,B.jsxs)(`small`,{children:[`(`,r.freshnessWarning,`)`]}):null]}),r.issues.length>0?(0,B.jsx)(`ul`,{className:`personal-system-health-issues`,children:r.issues.map((e,t)=>(0,B.jsx)(`li`,{children:e},t))}):null]}):null,o.some(e=>e.loadState)?(0,B.jsxs)(`section`,{className:`personal-home-lane`,"aria-live":`polite`,children:[(0,B.jsx)(`header`,{children:a(`startup.progress`,{loaded:o.filter(e=>!e.loadState).length,total:o.length})}),s?(0,B.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`status`,children:[(0,B.jsx)(`span`,{children:a(`startup.failedCount`,{count:s})}),(0,B.jsx)(`button`,{className:`min-h-11 rounded-md border px-3 py-2 text-sm`,onClick:n,type:`button`,children:a(`startup.retryFailed`)})]}):null,o.filter(e=>e.loadState).map(f)]}):null,(0,B.jsx)(`div`,{className:`personal-home-lanes`,children:c.map(e=>(0,B.jsxs)(`section`,{className:`personal-home-lane is-${e.key}`,"data-testid":`personal-home-lane-${e.key}`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`i`,{}),e.label]}),(0,B.jsx)(`b`,{children:l[e.key].length})]}),(0,B.jsx)(`div`,{className:`personal-home-lane-list`,children:l[e.key].length?l[e.key].map(f):(0,B.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.empty`)})})]},e.key))}),(0,B.jsxs)(`details`,{className:`personal-home-history`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(`span`,{children:a(`home.history`)}),(0,B.jsx)(`b`,{children:u.length}),(0,B.jsx)(`small`,{children:a(`home.completedGoals`)})]}),(0,B.jsx)(`div`,{children:u.length?u.map(f):(0,B.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.noCompletedGoals`)})})]}),d.length?(0,B.jsxs)(`details`,{className:`personal-home-history is-stopped`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(`span`,{children:a(`home.stopped`)}),(0,B.jsx)(`b`,{children:d.length}),(0,B.jsx)(`small`,{children:a(`home.preservedState`)})]}),(0,B.jsx)(`div`,{children:d.map(f)})]}):null]})}function yx({items:e,onSelect:t,reportState:n}){let{locale:r,t:i}=Ji();return(0,B.jsxs)(`section`,{className:`personal-object-list personal-files-list`,"data-testid":`personal-goal-outputs`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:i(`files.title`)}),(0,B.jsx)(`span`,{children:e.length})]}),n?.loading?(0,B.jsxs)(`p`,{className:`personal-object-list-state`,role:`status`,children:[(0,B.jsx)(Im,{className:`is-spinning`,size:14}),i(`files.loadingReports`)]}):null,n?.error?(0,B.jsxs)(`p`,{className:`personal-object-list-state is-error`,role:`alert`,children:[(0,B.jsx)(im,{size:14}),i(`files.reportLoadFailed`),`: `,n.error]}):null,!n?.loading&&!n?.error&&e.length===0?(0,B.jsxs)(`p`,{className:`personal-object-list-state`,children:[(0,B.jsx)(gm,{size:14}),i(`files.empty`)]}):null,e.map(e=>(0,B.jsxs)(`button`,{"data-output-kind":e.output.kind,onClick:()=>t({item:e.output,kind:`output`}),type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-file-icon`,children:(0,B.jsx)(gm,{size:16})}),(0,B.jsx)(`strong`,{children:e.output.title}),e.output.report?(0,B.jsx)(`em`,{children:i(`files.reportDelta`,{added:e.output.report.addedCount,changed:e.output.report.changedCount})}):null,(0,B.jsx)(`p`,{children:e.output.summary??e.output.safePreview??e.output.kind??i(`files.emptySummary`)}),(0,B.jsx)(`small`,{title:e.output.createdAt,children:[e.output.goalTitle,e.output.kind===`report`?i(`files.verifiedReport`):null,e.output.todoId?`${i(`common.task`)} ${e.output.todoId}`:null,_x(e.output.createdAt,r,i)].filter(Boolean).join(` · `)})]},e.id))]})}function bx({agentLabel:e,messages:t,onClose:n,onDraftTask:r,onOpenConversation:i,title:a}){let{t:o}=Ji(),s=t.reduce((e,t,n)=>t.role===`user`?n:e,0),c=t.slice(Math.max(0,s)).slice(-3),l=c.filter(e=>e.role===`assistant`&&!e.pending).at(-1);return(0,z.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),(0,B.jsxs)(`aside`,{"aria-label":o(`conversation.receipt`),className:`personal-manager-conversation-tray`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:16}),(0,B.jsx)(`strong`,{children:a??o(`conversation.title`)}),(0,B.jsx)(`small`,{children:t.at(-1)?.pending?o(`conversation.replying`):o(`common.recently`)})]}),(0,B.jsxs)(`div`,{className:`personal-manager-conversation-actions`,children:[r&&l?(0,B.jsxs)(`button`,{className:`personal-manager-conversation-btn`,onClick:()=>r(l.text),title:o(`conversation.convertHint`),type:`button`,children:[(0,B.jsx)(Sm,{size:13}),(0,B.jsx)(`span`,{children:o(`conversation.toTask`)})]}):null,(0,B.jsx)(`button`,{className:`personal-manager-conversation-link`,onClick:i,type:`button`,children:o(`conversation.full`)}),n?(0,B.jsx)(`button`,{"aria-label":o(`conversation.close`),className:`personal-manager-conversation-close`,onClick:n,title:o(`conversation.close`),type:`button`,children:(0,B.jsx)($m,{size:14})}):null]})]}),(0,B.jsx)(`div`,{"aria-live":`polite`,className:`personal-manager-conversation-messages`,children:c.map(t=>(0,B.jsxs)(`article`,{className:`is-${t.role}`,children:[(0,B.jsx)(`strong`,{children:t.role===`user`?o(`common.you`):t.agentLabel??e??o(`header.manager`)}),(0,B.jsxs)(`div`,{className:`personal-manager-conversation-bubble`,children:[t.role===`user`?(0,B.jsx)(`p`,{children:t.text}):(0,B.jsx)(jy,{text:t.text}),t.pending?(0,B.jsx)(`small`,{children:o(`conversation.agentPending`)}):null]})]},t.id))})]})}function xx({onClose:e,onOpenDetails:t,run:n}){let{t:r}=Ji();return(0,B.jsxs)(`section`,{"aria-label":r(`session.record`),className:`personal-session-record`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:17}),r(`session.record`)]}),(0,B.jsx)(`button`,{"aria-label":r(`session.closeRecord`),onClick:e,type:`button`,children:(0,B.jsx)($m,{size:15})})]}),(0,B.jsx)(`div`,{children:(0,B.jsx)(`strong`,{children:n.title})}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Agent`}),(0,B.jsx)(`dd`,{children:n.agentLabel})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`common.status`)}),(0,B.jsx)(`dd`,{children:Xi(n.sessionStatus??n.status,r)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Session`}),(0,B.jsx)(`dd`,{title:n.sessionId,children:n.sessionId})]})]}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:t,type:`button`,children:r(`session.details`)})]})}function Sx(e,t,n){let r=[];if(t===null)return e.userTodos.slice(0,4).forEach(t=>r.push({attention:{...t,goalTitle:t.goalTitle??hy(e,t.goalId)},id:`attention:${t.todoId}`,kind:`attention`})),e.goals.filter(e=>gy(e)===`running`).slice(0,4).forEach(e=>r.push({id:`run:${e.goalId}`,kind:`run`,run:{agentId:e.agentId,agentLabel:e.agentLabel??e.agentId,completedSteps:e.doneTodoCount??e.agentTodos.filter(e=>e.done).length,goalId:e.goalId,goalTitle:e.title,latestActivity:e.agentSentence,runId:`goal:${e.goalId}`,status:`running`,title:e.nextSentence,totalSteps:Math.max((e.doneTodoCount??0)+e.agentTodos.filter(e=>!e.done).length,1)}})),r;let i=e.goals.find(e=>e.goalId===t);if(!i)return r;if(i.needsYou){let t=e.userTodos.find(e=>e.goalId===i.goalId);r.push({attention:t?{...t,goalTitle:i.title}:{blocking:i.needsYouBlocking??!1,goalId:i.goalId,goalTitle:i.title,text:i.needsYou,todoId:`${i.goalId}:attention`},id:`attention:${i.goalId}`,kind:`attention`})}r.push({id:`run:${i.goalId}`,kind:`run`,run:{agentId:i.agentId,agentLabel:i.agentLabel??i.agentId,completedSteps:i.doneTodoCount??i.agentTodos.filter(e=>e.done).length,goalId:i.goalId,goalTitle:i.title,latestActivity:i.agentSentence,runId:`goal:${i.goalId}`,status:i.state===`推进中`?`running`:i.state===`需修复`?`failed`:`waiting`,title:i.nextSentence,totalSteps:Math.max((i.doneTodoCount??0)+i.agentTodos.filter(e=>!e.done).length,1)}}),i.agentTodos.filter(e=>e.taskClass===`continuous_monitor`).forEach(t=>{let a=e.timeline?.find(e=>e.kind===`run`&&e.run.goalId===i.goalId&&e.run.todoId===t.todoId&&!!e.run.sessionId);r.push({id:`schedule:${i.goalId}:${t.todoId}`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:a?[{label:a.run.latestActivity||a.run.title,runId:a.run.runId,status:a.run.status===`waiting`||a.run.status===`queued`?`running`:a.run.status,timestamp:i.latestActivity||n(`common.recently`)}]:[],goalId:i.goalId,label:t.text,schedule:t.evidence??n(`schedule.summary`),scheduleId:t.todoId,scheduleKind:`monitor`,sessionId:a?.run.sessionId,status:t.done||t.status===`paused`?`paused`:`active`,stopCondition:n(`drawer.scheduleDefaultStop`),target:t.text,timezone:`Asia/Shanghai`}})});let a=e.timeline?.find(e=>e.kind===`proposal`&&e.proposal.actionKind===`heartbeat.bind`&&e.proposal.goalId===i.goalId);if(a){let e=e=>a.proposal.fields.find(t=>t.key===e)?.value;r.push({id:`schedule:${i.goalId}:heartbeat`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:[],goalId:i.goalId,label:`${n(`schedule.heartbeat`)} · ${i.title}`,nextRunAt:n(`drawer.schedulePending`),notificationRule:n(`drawer.scheduleDefaultNotification`),schedule:e(`cadence`)??n(`schedule.summary`),scheduleId:`${i.goalId}:heartbeat`,scheduleKind:`heartbeat`,status:a.proposal.status===`applied`?`active`:`draft`,stopCondition:e(`stop_condition`)??n(`drawer.scheduleDefaultStop`),timezone:e(`timezone`)??`Asia/Shanghai`}})}return r}function Cx(e){return e===`preview_ready`?`ready`:e===`cancelled`?`draft`:e===`failed`?`error`:e}function wx(e,t){let n={agent_id:t(`proposal.field.agentId`),cadence:t(`proposal.field.cadence`),completion_criteria:t(`proposal.field.completionCriteria`),execution_boundary:t(`proposal.field.executionBoundary`),goal_id:t(`proposal.field.goalId`),heartbeat:t(`proposal.field.heartbeat`),initial_todos:t(`proposal.field.initialTodos`),objective:t(`proposal.field.objective`),operation:t(`proposal.field.operation`),permission:t(`proposal.field.permission`),reason:t(`proposal.field.reason`),stop_condition:t(`proposal.field.stopCondition`),target:t(`proposal.field.target`),timezone:t(`proposal.field.timezone`),title:t(`proposal.field.title`),workspace_ref:t(`proposal.field.workspace`)},r=[`title`,`objective`,`completion_criteria`,`execution_boundary`,`permission`,`agent_id`,`workspace_ref`,`initial_todos`,`heartbeat`,`stop_condition`,`goal_id`];return Object.entries(e).sort(([e],[t])=>{let n=r.indexOf(e),i=r.indexOf(t);return(n<0?r.length:n)-(i<0?r.length:i)}).slice(0,10).map(([e,r])=>({key:e,label:n[e]??e.replaceAll(`_`,` `),value:e===`workspace_ref`?r===`current`?t(`proposal.workspace.current`):t(`proposal.workspace.named`,{workspace:String(r??`current`)}):Array.isArray(r)?r.join(` · `):typeof r==`object`&&r?JSON.stringify(r):String(r??`—`)}))}function Tx(e,t){let n=e.normalized_parameters.projection,r=n&&typeof n==`object`?n:{},i=Array.isArray(r.fields)?r.fields.flatMap((e,t)=>{if(!e||typeof e!=`object`)return[];let n=e;return typeof n.label!=`string`||typeof n.value!=`string`?[]:[{key:`projection:${t}`,label:n.label,value:n.value}]}).slice(0,8):[];return[{key:`operation_state`,label:t(`proposal.field.operationState`),value:e.operation?.lifecycle_state??e.status},...i,...typeof r.warning==`string`?[{key:`warning`,label:t(`proposal.field.confirmationBoundary`),value:r.warning}]:[],...e.operation?.expires_at?[{key:`expires_at`,label:t(`proposal.field.expiresAt`),value:e.operation.expires_at}]:[]].slice(0,10)}function Ex(e){if(e.action_kind!==`goal.lifecycle`)return;let t=e.normalized_parameters.operation;return t===`stop`||t===`resume`||t===`delete`?t:void 0}function Dx(e,t){let n=Ex(e),r=fy(e),i=typeof e.normalized_parameters.title==`string`?e.normalized_parameters.title:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:``,a=typeof e.normalized_parameters.target==`string`?e.normalized_parameters.target:``,o=e.normalized_parameters.projection,s=o&&typeof o==`object`&&typeof o.title==`string`?String(o.title):e.summary,c=e.action_kind===`operation.execute`?s:e.action_kind===`goal.create`?t(`proposal.summary.goalCreate`,{title:i}):e.action_kind===`heartbeat.bind`?t(`proposal.summary.heartbeat`):e.action_kind===`monitor.create`?t(`proposal.summary.monitor`,{target:a}):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.summary.lifecycleStop`,{title:i}):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.summary.lifecycleDelete`,{title:i}):e.action_kind===`goal.lifecycle`?t(`proposal.summary.lifecycleResume`,{title:i}):e.summary;return{actionKind:e.action_kind,reviewPlan:r,fields:e.action_kind===`operation.execute`?Tx(e,t):wx(e.normalized_parameters,t),goalId:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:void 0,impact:e.action_kind===`operation.execute`?t(`proposal.impact.operation`):e.action_kind===`goal.create`?t(`proposal.impact.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.impact.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.impact.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.impact.lifecycleResume`):e.permission_classification===`protected`?t(`proposal.impact.protected`):t(`proposal.impact.default`),previewId:e.proposal_id,lifecycleOperation:n,gate:e.gate?{kind:String(e.gate.kind??`protected_action`),nextAction:typeof e.gate.next_action==`string`?e.gate.next_action:void 0,summary:String(e.gate.summary??t(`proposal.gate.default`))}:void 0,primaryLabel:e.action_kind===`operation.execute`?t(`proposal.primary.operationGroup`):e.action_kind===`goal.create`?t(`proposal.primary.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.primary.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.primary.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.primary.lifecycleResume`):e.action_kind===`todo.create`&&e.normalized_parameters.start_execution===!0?t(`proposal.primary.todoStart`):t(`proposal.primary.apply`),status:e.status===`applied`&&r.interaction!==`completed`?`error`:Cx(e.status),title:c}}function Ox(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,42);if(t)return t;let n=2166136261;for(let t of e)n^=t.codePointAt(0)??0,n=Math.imul(n,16777619);return`goal-${(n>>>0).toString(36)}`}function kx(e,t){let n=e.match(/[「“"]([^」”"]{2,80})[」”"]/u)?.[1];return n?n.trim():e.replace(/^(请|帮我|我想|给我|创建|新建|设置|please|i want to|create|set up)+/iu,``).replace(/(一个|新的)?\s*(goal|目标)/giu,``).replace(/[,。!?].*$/u,``).trim().slice(0,80)||t(`goal.defaultTitle`)}function Ax(e,t){for(let n of e.split(/\r?\n/u)){let e=n.trim();for(let n of t){let t=e.match(RegExp(`^${n.replace(/[.*+?^${}()|[\]\\]/gu,`\\$&`)}\\s*[::]\\s*(.*)$`,`iu`));if(t?.[1]?.trim())return t[1].trim()}}return``}function jx(e,t){let n=Ax(e,[`目标`,`Objective`]),r=Ax(e,[`完成标准`,`Completion criteria`]),i=Ax(e,[`执行边界(可选)`,`执行边界`,`边界`,`Execution boundary (optional)`,`Execution boundary`,`Boundary`]),a=(n||kx(e,t)).split(/[。;;\n]/u)[0].trim().slice(0,80)||t(`goal.defaultTitle`),o=[n||a,r?t(`goal.objectiveCompletion`,{criteria:r}):``,i?t(`goal.objectiveBoundary`,{boundary:i}):``].filter(Boolean).join(` +`),s=/(只读|不调用外部工具|不修改(?:仓库|代码|状态)|read.?only|do not (?:call|use) external tools|do not modify (?:repositories|repository|code|state))/iu.test(i||e);return{completionCriteria:r,executionBoundary:i,initialTodos:r?[t(`goal.initialTodo`,{criteria:r})]:[],objective:o,permission:s?`read_only`:`workspace_write_on_confirmation`,title:a}}function Mx(e){let t=e.match(/(?:每|every)\s*(\d{1,3})\s*(?:分钟|minutes?)/iu)?.[1];if(t)return`${t}m`;let n=e.match(/(?:每|every)\s*(\d{1,2})\s*(?:小时|hours?)/iu)?.[1];return n?`${n}h`:/每小时|every hour|hourly/iu.test(e)?`1h`:(/每天|每日|早上|上午|daily|every day/iu.test(e),`1d`)}function Nx(e,t){return/(每周|星期|周[一二三四五六日天]|weekly|every\s+(?:mon|tues|wednes|thurs|fri|satur|sun)day|\d{1,2}\s*[::]\s*\d{2})/iu.test(e)?t(`schedule.unsupportedCalendar`):null}function Px(e,t){return Ax(e,[`检查内容`,`监控内容`,`目标`,`Check target`,`Monitor target`,`Target`])||e.replace(/^(?:为当前 Goal |for the current Goal )?(?:添加|配置|创建|add|configure|create)?\s*(?:定时检查|监控|scheduled check|monitor)[::]?/iu,``).split(/\r?\n/u)[0].trim()||t(`schedule.defaultTarget`)}function Fx(e){return/(mr|pr).{0,8}(合并|merge)/iu.test(e)?`pr_merged`:/发布完成|上线完成|release (?:is )?complete|deployment (?:is )?complete/iu.test(e)?`release_complete`:`goal_complete`}function Ix(e,t){let n=e.toLowerCase();return t.find(e=>n.includes(e.agentId.toLowerCase())||n.includes(e.label.toLowerCase()))}function Lx(e){let t=Ax(e,[`标题`,`任务标题`,`Todo 标题`]),n=Ax(e,[`内容`,`任务内容`,`Todo 内容`]);if(t)return[t,n].filter(Boolean).join(`:`).slice(0,400);let r=e.match(/[「“"]([^」”"]{2,200})[」”"]/u)?.[1];return r?r.trim():e.replace(/^(请|帮我|给我|为当前 Goal |新增|新建|创建|添加|加上|加一个|记一个)+/u,``).replace(/^(一个\s*)?(普通\s*)?(todo|待办|任务)(?:\s*到\s*Tasks?)?[::\s]*/iu,``).replace(/[。;;,,]\s*(?:不要|不需要|无需|禁止|别|暂不).{0,80}(?:heartbeat|心跳|定时|监控|执行).*$/iu,``).replace(/[,,]\s*(并且|然后|再)?\s*(交给|分配给|让).+$/u,``).replace(/\s*(交给|分配给|让)\s+.+$/u,``).trim().slice(0,400)||`推进当前 Goal 的下一项工作`}var Rx=new Set([`image/png`,`image/jpeg`,`image/webp`,`image/gif`]),zx=5242880,Bx=4;function Vx(e,t){return new Promise((n,r)=>{let i=new FileReader;i.onerror=()=>r(Error(t(`composer.imageReadError`,{name:e.name}))),i.onload=()=>n({dataUrl:String(i.result??``),id:crypto.randomUUID(),mimeType:e.type,name:e.name,size:e.size}),i.readAsDataURL(e)})}function Hx({agents:e=[{agentId:`codex`,available:!0,capability:`代码与项目执行`,label:`Codex`}],callbacks:t={},goalArchiveLoadState:n={error:null,phase:`ready`},model:r,readOnly:i=!1,selectedAgentId:a,selectedGoalId:o,statusSourceControl:s}){let{locale:c,t:l}=Ji(),[u,d]=(0,z.useState)(o??null),[f,p]=(0,z.useState)(a??e.find(e=>e.available)?.agentId??`codex`),[m,h]=(0,z.useState)(null),[g,_]=(0,z.useState)(!1),[v,y]=(0,z.useState)(null),[b,x]=(0,z.useState)({}),[S,C]=(0,z.useState)(`chat`),[w,T]=(0,z.useState)(!1),[E,D]=(0,z.useState)(!1),[O,ee]=(0,z.useState)(!1),[te,ne]=(0,z.useState)(()=>{try{let e=window.sessionStorage.getItem(`loopx-pw-composer-drafts`),t=e?JSON.parse(e):{};return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}),[k,A]=(0,z.useState)(!1),[j,M]=(0,z.useState)([]),[N,P]=(0,z.useState)(null),[F,re]=(0,z.useState)(null),[ie,I]=(0,z.useState)(()=>new Set),[ae,L]=(0,z.useState)(()=>new Set),[oe,se]=(0,z.useState)(`idle`),[ce,le]=(0,z.useState)([]),[ue,de]=(0,z.useState)(!1),[fe,pe]=(0,z.useState)(fx),[me,he]=(0,z.useState)({}),[ge,_e]=(0,z.useState)([]),ve=(0,z.useRef)(!1),ye=(0,z.useRef)(NaN),be=(0,z.useRef)(null),xe=(0,z.useRef)(null),Se=(0,z.useRef)(null),Ce=(0,z.useRef)(new Set),we=(0,z.useRef)(new Set),[Te,Ee]=(0,z.useState)(null),R=o===void 0?u:o,De=a??f,Oe=`${R??`manager`}:${De}`,ke=te[Oe]??``;(0,z.useEffect)(()=>{M([]),P(null)},[Oe]);function Ae(e,t){ne(n=>{let r={...n};t?r[e]=t:delete r[e];try{window.sessionStorage.setItem(`loopx-pw-composer-drafts`,JSON.stringify(r))}catch{}return r})}function je(e){Ae(Oe,e)}function Me(e){let t=te[Oe]?.trimEnd();je(t?`${t}\n${e}`:e),window.requestAnimationFrame(()=>be.current?.focus())}(0,z.useEffect)(()=>{let e=be.current;e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,120)}px`)},[ke]);let Ne=(0,z.useMemo)(()=>r.goals.map(e=>{let t=me[e.goalId];return t?{...e,repository:{branch:t.branch,identity:t.identity,label:t.label,readOnly:!0}}:e}),[me,r.goals]),Pe=(0,z.useMemo)(()=>Ne.filter(e=>gy(e)===`needs_you`).length,[Ne]),Fe=(0,z.useMemo)(()=>Ne.filter(e=>gy(e)===`needs_you`&&(e.needsYouBlocking||e.state===`等你`)).length,[Ne]),V=Ne.find(e=>e.goalId===R)??null,Ie=m?.kind===`settings`,Le=R,Re=(0,z.useMemo)(()=>{let e=Object.values(b).filter(e=>e.actionKind===`heartbeat.bind`&&e.goalId&&e.status===`applied`).map(e=>({id:`schedule:${e.goalId}:heartbeat`,kind:`schedule`,schedule:{agentId:De,executionHistory:[],goalId:e.goalId,label:e.title,nextRunAt:l(`drawer.schedulePending`),notificationRule:l(`drawer.scheduleDefaultNotification`),schedule:e.fields.find(e=>e.key===`cadence`)?.value??l(`schedule.summary`),scheduleId:`${e.goalId}:heartbeat`,scheduleKind:`heartbeat`,status:e.status===`applied`?`active`:`draft`,stopCondition:e.fields.find(e=>e.key===`stop_condition`)?.value??l(`drawer.scheduleDefaultStop`),timezone:e.fields.find(e=>e.key===`timezone`)?.value??`Asia/Shanghai`}})),t=[...Sx(r,Le,l),...r.timeline??[],...e,...gx(Object.values(b)).filter(e=>e.actionKind!==`heartbeat.bind`||e.status!==`applied`).map(e=>({id:`proposal:${e.previewId}`,kind:`proposal`,proposal:e}))];return[...new Map(t.map(e=>[e.id,e])).values()].filter(e=>e.kind!==`proposal`||![`stale`,`error`].includes(e.proposal.status)||ce.includes(e.proposal.previewId)).filter(e=>!R||e.kind===`message`?!0:e.kind===`proposal`?!e.proposal.goalId||e.proposal.goalId===R:e.kind===`attention`?e.attention.goalId===R:e.kind===`run`?e.run.goalId===R:e.kind===`schedule`?e.schedule.goalId===R:e.output.goalId===R)},[Le,r,b,De,R,ce,l]),ze=(0,z.useMemo)(()=>v?Re.filter(e=>e.kind===`message`?!0:e.kind===`run`?e.run.runId===v.runId:e.kind===`output`&&e.output.runId===v.runId):Re,[v,Re]);(0,z.useEffect)(()=>{if(!v)return;let e=Re.find(e=>e.kind===`run`&&e.run.runId===v.runId);!e||e.kind!==`run`||JSON.stringify({completedSteps:v.completedSteps,latestActivity:v.latestActivity,messages:v.sessionMessages,sessionStatus:v.sessionStatus,status:v.status,totalSteps:v.totalSteps})!==JSON.stringify({completedSteps:e.run.completedSteps,latestActivity:e.run.latestActivity,messages:e.run.sessionMessages,sessionStatus:e.run.sessionStatus,status:e.run.status,totalSteps:e.run.totalSteps})&&y(e.run)},[v,Re]);let Be=(0,z.useMemo)(()=>Re.flatMap(e=>e.kind===`message`?[e.message]:[]),[Re]),Ve=(0,z.useMemo)(()=>V?Re.flatMap(e=>e.kind===`message`?[e.message]:[]):[],[Re,V]);(0,z.useEffect)(()=>{V||w||Be.some(e=>e.pending)&&D(!0)},[w,Be,V]),(0,z.useEffect)(()=>{!V||S===`chat`||Ve.some(e=>e.pending)&&ee(!0)},[Ve,V,S]);let He=(0,z.useMemo)(()=>Re.filter(e=>e.kind===`message`||e.kind===`proposal`&&ce.includes(e.proposal.previewId)),[Re,ce]),Ue=He[He.length-1],We=Ue?.kind===`message`?Ue.message.text.length:0;(0,z.useEffect)(()=>{if(!w||!xe.current)return;let e=window.requestAnimationFrame(()=>{xe.current&&(xe.current.scrollTop=xe.current.scrollHeight)});return()=>window.cancelAnimationFrame(e)},[He.length,w,We]);let Ge=(0,z.useMemo)(()=>{if(m?.kind===`settings`)return null;if(m?.kind===`attention`)return{kind:`attention`,item:Gd(m.item,r.attentionHistory??r.userTodos)};if(m?.kind===`goal`){let e=Ne.find(e=>e.goalId===m.item.goalId);return e?{item:e,kind:`goal`}:m}if(m?.kind!==`run`)return m;let e=Re.find(e=>e.kind===`run`&&e.run.runId===m.item.runId);return e?{item:e.run,kind:`run`}:m},[Re,m,Ne,r.attentionHistory,r.userTodos]);(0,z.useEffect)(()=>{if(i){he({}),_e([]);return}let e=!1;return Promise.all([Ig(),qg()]).then(([t,n])=>{e||(he(Object.fromEntries(t.map(e=>[e.goal_id,e.repository]))),_e(n))}).catch(()=>{}),()=>{e=!0}},[i]),(0,z.useEffect)(()=>{if(!ue)return;function e(e){e.key===`Escape`&&de(!1)}return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[ue]),(0,z.useEffect)(()=>{if(R||!Re.length)return;if(!ve.current){ve.current=!0;try{ye.current=Date.parse(window.localStorage.getItem(`loopx-pw-last-visit`)??``),window.localStorage.setItem(`loopx-pw-last-visit`,new Date().toISOString())}catch{ye.current=NaN}}let e=ye.current,t=Re.filter(e=>e.kind===`run`).map(e=>e.run),n=t=>{let n=Date.parse(t??``);return!Number.isNaN(e)&&!Number.isNaN(n)&&n>e},r={attention:Pe,done:t.filter(e=>e.status===`completed`&&n(e.latestActivity)).length,failed:t.filter(e=>(e.status===`failed`||e.status===`interrupted`)&&n(e.latestActivity)).length};Ee(e=>e?.attention===r.attention&&e.done===r.done&&e.failed===r.failed?e:r)},[Re,Pe,R]),(0,z.useEffect)(()=>{if(i){x({});return}let e=!1;return Mh(R?{goalId:R}:{contextKind:`manager`}).then(t=>{if(e)return;let n=Object.fromEntries(t.filter(e=>[`ready`,`gated`,`deferred`,`applying`].includes(e.status)).map(e=>{let t=Dx(e,l);return[t.previewId,t]}));x(e=>({...e,...n}))}).catch(()=>{}),()=>{e=!0}},[i,R,l]);async function Ke(e,n={}){if(i)throw Error(l(`source.readOnlyWriteError`));let r;try{r=t.onPreviewAction?await t.onPreviewAction(e):Dx(await Ah(e),l)}catch(t){if(!(t instanceof Th)||t.payload.error_code!==`action_preview_gate`)throw t;let n=t.payload.gate&&typeof t.payload.gate==`object`?t.payload.gate:{},i=(Array.isArray(n.candidates)?n.candidates:[]).flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.workspace_ref==`string`&&typeof t.label==`string`?[{label:t.label,workspaceRef:t.workspace_ref}]:[]}),a=String(n.kind??`workspace_selection_required`),o=a===`agent_binding_required`||a===`agent_identity_selection_required`;r={actionKind:e.actionKind,fields:i.map(e=>({key:`workspace_ref:${e.workspaceRef}`,label:e.label,value:e.workspaceRef})),gate:{kind:a,nextAction:typeof n.next_action==`string`?n.next_action:void 0,summary:String(n.summary??l(`proposal.workspaceGate.defaultSummary`))},impact:l(o?`proposal.workspaceGate.agentImpact`:`proposal.workspaceGate.selectionImpact`),previewId:`workspace-choice-${Date.now().toString(36)}`,sourceRequest:e,status:`gated`,title:l(o?`proposal.workspaceGate.agentTitle`:`proposal.workspaceGate.selectionTitle`),workspaceCandidates:i}}return le(e=>e.includes(r.previewId)?e:[...e,r.previewId]),x(e=>({...e,[r.previewId]:r})),n.select!==!1&&h({item:r,kind:`proposal`}),r}function qe(){tt(null),Ae(`manager:${De}`,l(`composer.createGoalTemplate`)),window.requestAnimationFrame(()=>be.current?.focus())}async function Je(e,n){de(!1);let r={delete:`Deleted from the owner workspace`,resume:`Resumed from the owner workspace`,stop:`Stopped from the owner workspace`},i={delete:l(`proposal.summary.lifecycleDelete`,{title:e.title}),resume:l(`proposal.summary.lifecycleResume`,{title:e.title}),stop:l(`proposal.summary.lifecycleStop`,{title:e.title})},a=null,o=!1;try{if(n===`stop`){if(Ce.current.has(e.goalId))return;Ce.current.add(e.goalId),I(new Set(Ce.current)),h(null),a={goalId:e.goalId,next:`stopped`,optimisticApplied:!0,previous:e.activationState},re(l(`feedback.applying`,{title:i.stop})),t.onGoalActivationStateChange?.(e.goalId,`stopped`)}if(t.onExecuteGoalLifecycle){if(n===`delete`)throw Error(`The selected status source does not authorize Goal deletion.`);let a=await t.onExecuteGoalLifecycle({goalId:e.goalId,operation:n,reason:r[n]});if(!a.projectionVerified)throw Error(`Goal lifecycle projection did not verify.`);o=!0,t.onGoalActivationStateChange?.(e.goalId,a.activationState),re(l(`feedback.completed`,{title:i[n]})),n===`stop`&&tt(null),await(t.onReconcileStatus??t.onRefresh)?.();return}let s=await Ke({actionKind:`goal.lifecycle`,context:{kind:`goal_directory`,goal_id:e.goalId},idempotencyKey:`workspace-goal-${n}-${e.goalId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,operation:n,reason:r[n]},summary:i[n]},{select:n!==`stop`});if(s.goalId!==e.goalId||s.lifecycleOperation!==n)throw h(null),Error(l(`actionReview.targetChanged`));n===`stop`&&(s.reviewPlan?.interaction===`direct`?(o=!0,await Qe(s,{lifecycleProjection:a??void 0,presentation:`feedback`})):(a&&t.onGoalActivationStateChange?.(a.goalId,a.previous),re(s.gate?l(`feedback.gateRequired`,{summary:s.gate.summary}):l(`feedback.notCompleted`,{status:s.status})),h({item:s,kind:`proposal`})))}catch(e){a&&!o&&t.onGoalActivationStateChange?.(a.goalId,a.previous),re(l(`feedback.executionFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{n===`stop`&&(Ce.current.delete(e.goalId),I(new Set(Ce.current)))}}function Ye(e,t){je(l(t?e===`heartbeat`?`composer.heartbeatTemplate`:`composer.monitorTemplate`:e===`heartbeat`?`composer.heartbeatTemplateWithoutGoal`:`composer.monitorTemplateWithoutGoal`)),h(null),window.requestAnimationFrame(()=>be.current?.focus())}async function Xe(e,n,r=``){let i=await t.onRequestScheduleConfig?.(e,n);if(i){le(e=>e.includes(i.previewId)?e:[...e,i.previewId]),x(e=>({...e,[i.previewId]:i})),h({item:i,kind:`proposal`});return}if(!n){je(l(e===`heartbeat`?`composer.heartbeatGoalQuestion`:`composer.monitorGoalQuestion`));return}let a=Date.now().toString(36);await Ke({actionKind:e===`heartbeat`?`heartbeat.bind`:`monitor.create`,context:{kind:`schedule`,goal_id:n},idempotencyKey:`workspace-${e}-${n}-${a}`,normalizedParameters:e===`heartbeat`?{agent_id:De,cadence:Mx(r),goal_id:n,stop_condition:Fx(r),timezone:`Asia/Shanghai`}:{agent_id:De,cadence:Mx(r),goal_id:n,stop_condition:Fx(r),target:Px(r,l),target_key:`goal-${n}`,timezone:`Asia/Shanghai`},summary:e===`heartbeat`?l(`proposal.summary.heartbeat`):l(`proposal.summary.monitor`,{target:Px(r,l)})})}async function Ze(e){if(!we.current.has(e.todoId)){we.current.add(e.todoId),L(new Set(we.current)),re(l(`feedback.preparingPreview`,{title:e.text}));try{await Ke({actionKind:`todo.update`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-${e.todoId}-complete-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,operation:`complete`,todo_id:e.todoId},summary:l(`tasks.markComplete`,{name:e.text})}),re(null)}catch(e){re(l(`feedback.previewFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{we.current.delete(e.todoId),L(new Set(we.current))}}}async function Qe(e,n={}){if(e.reviewPlan&&!e.reviewPlan.canApply)return;let i=n.presentation!==`feedback`,a=e.actionKind===`goal.lifecycle`&&e.goalId&&(e.lifecycleOperation===`stop`||e.lifecycleOperation===`resume`)?{goalId:e.goalId,next:e.lifecycleOperation===`stop`?`stopped`:`active`,optimisticApplied:!1,previous:r.goals.find(t=>t.goalId===e.goalId)?.activationState??(e.lifecycleOperation===`stop`?`active`:`stopped`)}:null,o=n.lifecycleProjection??a;re(l(`feedback.applying`,{title:e.title}));let s={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:`pending`,reason:`apply_pending`,canApply:!1}:void 0,status:`applying`};x(t=>({...t,[e.previewId]:s})),i&&h({item:s,kind:`proposal`}),o&&!o.optimisticApplied&&t.onGoalActivationStateChange?.(o.goalId,o.next);try{if(t.onApplyProposal){await t.onApplyProposal(e);let n={...e,status:`applied`};if(x(t=>({...t,[e.previewId]:n})),i&&h({item:n,kind:`proposal`}),re(l(`feedback.completed`,{title:e.title})),e.actionKind===`goal.lifecycle`){(e.lifecycleOperation===`stop`||e.lifecycleOperation===`delete`)&&tt(null),e.lifecycleOperation===`delete`&&e.goalId&&t.onGoalDeleted?.(e.goalId);let n=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>n?.()).catch(()=>void 0)}return}let n=await Nh(e.previewId);if(n.proposal.proposal_id!==e.previewId||n.proposal.action_kind!==e.actionKind||e.actionKind===`goal.lifecycle`&&(n.proposal.normalized_parameters.goal_id!==e.goalId||Ex(n.proposal)!==e.lifecycleOperation))throw new Th(l(`actionReview.targetChanged`),{error_code:`action_response_mismatch`});let r=Dx(n.proposal,l);if(x(t=>({...t,[e.previewId]:r})),i&&h({item:r,kind:`proposal`}),r.reviewPlan?.interaction!==`completed`){o&&t.onGoalActivationStateChange?.(o.goalId,o.previous),h({item:r,kind:`proposal`}),re(n.proposal.status===`stale`?l(`feedback.stale`):l(`actionReview.${r.reviewPlan.reason}`));return}if(re(l(`feedback.completed`,{title:r.title})),r.actionKind===`todo.create`&&await t.onRefresh?.(),r.actionKind===`goal.lifecycle`&&(r.lifecycleOperation===`stop`||r.lifecycleOperation===`delete`)&&tt(null),r.actionKind===`goal.lifecycle`&&r.lifecycleOperation===`delete`&&r.goalId&&t.onGoalDeleted?.(r.goalId),r.actionKind===`goal.lifecycle`){let e=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>e?.()).catch(()=>void 0)}}catch(n){if(o&&t.onGoalActivationStateChange?.(o.goalId,o.previous),n instanceof Th&&n.payload.error_code===`protected_action`){let r=n.payload.gate,i=r&&typeof r==`object`?r:{},a={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:`gated`,reason:`authority_gate`,canApply:!1}:void 0,gate:{kind:String(i.kind??`protected_action`),nextAction:typeof i.next_action==`string`?i.next_action:void 0,summary:String(i.summary??n.message)},status:`gated`};x(t=>({...t,[e.previewId]:a})),h({item:a,kind:`proposal`}),re(l(`feedback.gateRequired`,{summary:a.gate.summary})),e.actionKind===`goal.create`&&e.goalId&&(t.onRefresh?.(),tt(e.goalId));return}let r=n instanceof Th&&py(n.payload),i=n instanceof Th&&n.payload.error_code===`action_response_mismatch`,a={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:r?`refresh`:`repair`,reason:i?`readback_unverified`:r?`stale_proposal`:`apply_failed`,canApply:!1}:void 0,errorMessage:n instanceof Error?n.message:String(n),status:r?`stale`:`error`};x(t=>({...t,[e.previewId]:a})),h({item:a,kind:`proposal`}),re(l(`feedback.executionFailed`,{error:a.errorMessage}))}}let $e={...t,onOpenRunSession:async e=>{e.goalId!==R&&tt(e.goalId),C(`chat`),await t.onOpenRunSession?.(e),y(e),h(null)},onOpenGoal:e=>{tt(e);let n=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>n?.()).catch(()=>{re(l(`feedback.goalRefreshFailed`))})},onOpenGoalView:e=>{C(e),e===`chat`&&y(null),h(null)},onOpenOutput:e=>{e.goalId!==R&&tt(e.goalId),C(`files`),t.onOpenOutput?.(e)},onApplyProposal:Qe,onCancelProposal:async e=>{h(null),x(t=>{let n={...t};return delete n[e.previewId],n});try{t.onCancelProposal?.(e),t.onCancelProposal||await Ph(e.previewId)}catch(t){x(t=>({...t,[e.previewId]:e})),re(l(`feedback.cancelFailed`,{error:t instanceof Error?t.message:String(t)}))}},onTransitionProposal:async(e,t)=>{let n=Dx(await Fh(e.previewId,t),l);le(e=>e.includes(n.previewId)?e:[...e,n.previewId]),x(r=>{let i={...r};return t===`regenerate`&&delete i[e.previewId],i[n.previewId]=n,i}),h({item:n,kind:`proposal`})},onSelectWorkspaceCandidate:async(e,t)=>{e.sourceRequest&&(x(t=>{let n={...t};return delete n[e.previewId],n}),await Ke({...e.sourceRequest,idempotencyKey:`${e.sourceRequest.idempotencyKey}-${t}`,normalizedParameters:{...e.sourceRequest.normalizedParameters,workspace_ref:t}}))},onPreviewAction:Ke,onRequestScheduleConfig:(e,t)=>Ye(e,t),onOpenNotificationSettings:e=>h({goalId:e,kind:`settings`,tab:`lark`}),onFetchNotificationTargets:()=>ig(),onSetupGoalChannel:e=>og(e),onToggleGoalAutoNotify:e=>sg(e),onUpdateSchedule:async(e,t)=>{let n=Date.now().toString(36),r=e.scheduleKind===`heartbeat`;await Ke({actionKind:r?`heartbeat.bind`:`monitor.update`,context:{kind:`schedule`,goal_id:e.goalId},idempotencyKey:`workspace-monitor-${e.scheduleId}-${t}-${n}`,normalizedParameters:{agent_id:e.agentId??De,...!r&&t===`run_now`?{endpoint_id:De}:{},...t===`edit`?{cadence:`2h`,...r?{timezone:e.timezone??`Asia/Shanghai`}:{}}:{},goal_id:e.goalId,operation:t,...!r&&t===`run_now`&&e.sessionId?{session_id:e.sessionId}:{},...r?{}:{todo_id:e.scheduleId}},summary:t===`pause`?`暂停自动运行:${e.label}`:t===`resume`?`恢复自动运行:${e.label}`:t===`run_now`?`立即运行:${e.label}`:t===`stop`?`停止自动运行:${e.label}`:`编辑自动运行生命周期:${e.label}`})}},et=i?{onOpenGoal:$e.onOpenGoal,onOpenGoalView:$e.onOpenGoalView,onOpenOutput:$e.onOpenOutput}:$e;function tt(e){d(e),T(!1),D(!1),ee(!1),y(null),h(null),C(`tasks`),de(!1),t.onSelectGoal?.(e)}function nt(e){p(e),t.onSelectAgent?.(e)}function rt(e){pe(e),px(e)}async function it(n){let r=n?[]:j,i=(n??ke).trim()||(r.length?l(`composer.imageAnalysisPrompt`):``);if(!(!i||k)){n||(je(``),M([])),P(null),A(!0);try{if(r.length){R?S!==`chat`&&ee(!0):D(!0);let e=await t.onSendMessage?.(i,De,R,r);e&&await Ke(e);return}let n=Wy(i,{agents:e.map(e=>({agentId:e.agentId,label:e.label})),goalId:R,todos:(V?.agentTodos??[]).map(e=>({text:e.text,todoId:e.todoId}))});if(n.route===`clarify`){je(i);let e=l(`composer.clarifySingleAction`);n.missingFields.includes(`resume_when`)&&(e=l(`composer.clarifyDefer`)),re(e);return}if(n.actionKind===`goal.create`){let e=jx(i,l),t=Ox(e.title);await Ke({actionKind:`goal.create`,context:{kind:`manager`,goal_id:null,natural_language:i},idempotencyKey:`workspace-goal-intent-${t}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:De,completion_criteria:e.completionCriteria,execution_boundary:e.executionBoundary,goal_id:t,heartbeat:{cadence:Mx(i),enabled:n.normalizedParameters.heartbeat_enabled===!0,timezone:`Asia/Shanghai`},initial_todos:e.initialTodos,objective:e.objective,permission:e.permission,stop_condition:Fx(i),title:e.title,workspace_ref:`current`},summary:l(`proposal.summary.goalCreate`,{title:e.title})});return}if(R&&n.actionKind===`heartbeat.bind`){await Xe(`heartbeat`,R,i);return}if(R&&n.actionKind===`monitor.create`){let e=Nx(i,l);if(e){je(i),re(e);return}await Xe(`monitor`,R,i);return}let a=Ix(i,e);if(R&&a&&n.actionKind===`agent.bind`){await Ke({actionKind:`agent.bind`,context:{kind:`goal`,goal_id:R,natural_language:i},idempotencyKey:`workspace-agent-bind-${R}-${a.agentId}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:a.agentId,goal_id:R},summary:`将 ${a.label} 绑定到 ${V?.title??R}`});return}if(R&&n.actionKind===`todo.create`){if(n.normalizedParameters.start_execution===!0){await Ke({actionKind:`todo.create`,context:{kind:`goal`,goal_id:R,natural_language:i},idempotencyKey:`workspace-task-start-${R}-${Date.now().toString(36)}`,normalizedParameters:{endpoint_id:a?.agentId??De,goal_id:R,start_execution:!0,text:i},summary:`交给 Agent 执行:${i.slice(0,120)}`});return}let e=a?.agentId??(/(交给|分配给|让).{0,24}(agent|codex|claude|kiro|kimi)/iu.test(i)?De:null);await Ke({actionKind:`todo.create`,context:{kind:`goal`,goal_id:R,natural_language:i},idempotencyKey:`workspace-todo-create-${R}-${Date.now().toString(36)}`,normalizedParameters:{...e?{endpoint_id:e}:{},goal_id:R,text:Lx(i)},summary:`创建 Todo:${Lx(i)}`});return}let o=V?.agentTodos.find(e=>i.includes(e.todoId)||i.includes(e.text)),s=typeof n.normalizedParameters.operation==`string`?n.normalizedParameters.operation:null;if(R&&o&&n.actionKind===`todo.update`&&s){await Ke({actionKind:`todo.update`,context:{kind:`todo`,goal_id:R,todo_id:o.todoId,natural_language:i},idempotencyKey:`workspace-todo-update-${o.todoId}-${s}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:De,...s===`reassign`&&a?{endpoint_id:a.agentId}:{},...s===`block`?{note:i}:{},...s===`defer`&&typeof n.normalizedParameters.resume_when==`string`?{resume_when:n.normalizedParameters.resume_when}:{},goal_id:R,operation:s,todo_id:o.todoId},summary:`更新 Todo:${o.text}`});return}R?S!==`chat`&&ee(!0):D(!0);let c=await t.onSendMessage?.(i,De,R);c&&await Ke(c)}catch(e){n||(je(i),M(r));let t=e instanceof Error?e.message:l(`feedback.sendGenericError`);re(l(`feedback.sendFailed`,{error:t}))}finally{A(!1)}}}let at=e.find(e=>e.agentId===De)?.label??De,ot=!V&&ke.startsWith(l(`composer.createGoalDraftLead`)),st=Re.filter(e=>e.kind===`run`&&!!e.run.sessionId&&!!e.run.canInterrupt&&(e.run.status===`running`||e.run.status===`queued`)).length;async function ct(e){if(!e?.length)return;let t=Bx-j.length,n=Array.from(e).slice(0,Math.max(0,t)),r=n.find(e=>!Rx.has(e.type)),i=n.find(e=>e.size>zx);if(t<=0){P(l(`composer.imageCountError`,{count:Bx}));return}if(r){P(l(`composer.imageTypeError`));return}if(i){P(l(`composer.imageSizeError`,{size:zx/1024/1024}));return}try{let t=await Promise.all(n.map(e=>Vx(e,l)));M(e=>[...e,...t].slice(0,Bx)),P(e.length>n.length?l(`composer.imageCountError`,{count:Bx}):null)}catch(e){P(e instanceof Error?e.message:l(`composer.imageReadGenericError`))}finally{Se.current&&(Se.current.value=``)}}function lt(e){let t=Array.from(e.clipboardData.items).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).flatMap(e=>{let t=e.getAsFile();return t?[t]:[]});t.length&&(e.preventDefault(),ct(t))}async function ut(){let e=await qg();_e(e)}async function dt(){await Promise.all([ut(),t.onRefresh?.()])}async function ft(){if(!(!t.onRefresh||oe===`loading`)){se(`loading`);try{await t.onRefresh(),se(`done`)}catch{se(`error`)}window.setTimeout(()=>se(`idle`),1800)}}return Ie?(0,B.jsx)(lx,{focusGoalConnection:!!(m?.kind===`settings`&&m.goalId),goals:Ne,initialGoalId:m?.kind===`settings`?m.goalId??R:R,initialTab:m?.kind===`settings`?m.tab??`lark`:`lark`,onChanged:()=>void dt(),onClose:()=>h(null),onThemeChange:rt,theme:fe}):(0,B.jsx)(mx,{drawer:Ge?(0,B.jsx)($y,{agents:e,attentionHistory:r.attentionHistory??r.userTodos,onSelectAttention:e=>h({kind:`attention`,item:e}),callbacks:et,goalNotifications:r.goalNotifications??[],goals:Ne,inspectorExpanded:g,larkConnections:i?[]:ge,onClose:()=>{Ge.kind===`proposal`&&[`applied`,`rejected`].includes(Ge.item.status)&&(Ge.item.actionKind!==`heartbeat.bind`||Ge.item.status!==`applied`)&&x(e=>{let t={...e};return delete t[Ge.item.previewId],t}),_(!1),h(null)},onToggleInspectorSize:()=>_(e=>!e),readOnly:i,runs:Re.flatMap(e=>e.kind===`run`?[e.run]:[]),selection:Ge}):null,drawerMode:Ge?.kind===`todo`?g?`inspector-full`:`inspector`:`panel`,drawerOpen:Ge!==null,mobileSidebarOpen:ue,onCloseMobileSidebar:()=>de(!1),theme:fe,main:(0,B.jsxs)(`div`,{className:`personal-channel`,children:[(0,B.jsx)(wy,{agents:e,managerChatOpen:w,mobileNavigationOpen:ue,onOpenGoalCapabilities:V?()=>h({goalId:V.goalId,kind:`settings`,tab:`capabilities`}):void 0,onOpenGoalDetail:V&&!V.loadState?()=>h({item:V,kind:`goal`}):void 0,onRefresh:t.onRefresh?()=>void ft():void 0,onOpenNavigation:()=>de(!0),onOpenManagerChat:()=>{D(!1),T(!0)},onSelectGoalTab:e=>{C(e),e===`chat`&&(y(null),ee(!1))},onSelectAgent:nt,onReturnManagerHome:()=>{T(!1),D(!1),window.requestAnimationFrame(()=>xe.current?.scrollTo({behavior:`smooth`,top:0}))},selectedAgentId:De,refreshState:oe,readOnlySourceLabel:i?s?.activeSource.label:void 0,selectedGoal:V,selectedGoalTab:S}),(0,B.jsxs)(`div`,{className:`personal-channel-scroll`,ref:xe,children:[!V&&!w&&Te&&Te.done+Te.failed+Te.attention>0?(0,B.jsxs)(`section`,{className:`personal-digest-card`,"aria-label":l(`digest.away`),children:[(0,B.jsx)(`strong`,{children:l(`digest.away`)}),(0,B.jsxs)(`div`,{className:`personal-digest-stats`,children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`b`,{children:Te.done}),l(`digest.completed`)]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`b`,{children:Te.failed}),l(`digest.failed`)]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`b`,{children:Te.attention}),l(`digest.needsYou`)]})]})]}):null,!V&&!w?(0,B.jsxs)(`section`,{className:`personal-manager-greeting`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Zp,{size:20})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:l(`home.greeting`)}),(0,B.jsx)(`p`,{children:r.goals.some(e=>e.activationState===`active`&&e.loadState)?l(`startup.partial`):(0,B.jsxs)(B.Fragment,{children:[l(`home.waitingCount`,{count:Pe}),` `,l(`home.blockingSummary`,{count:Fe})]})})]})]}):null,V?.loadState?(0,B.jsx)(`section`,{className:`personal-manager-greeting`,role:`status`,"data-testid":`goal-status-loading`,children:(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:l(V.loadState===`error`?`startup.goalError`:`startup.goalLoading`)}),(0,B.jsx)(`p`,{children:l(V.loadError?`startup.error.${V.loadError}`:`startup.independent`)}),V.loadState===`error`?(0,B.jsx)(`button`,{className:`min-h-11 rounded-md border px-3 py-2 text-sm`,type:`button`,onClick:()=>void t.onRefresh?.(),children:l(`startup.retry`)}):null]})}):V&&S===`tasks`?(0,B.jsx)(Tb,{historyEnabled:!i,goal:V,items:Re,onDraftTaskFromMessage:i?void 0:e=>{je(`创建一个 Task:${hx(e)}`),re(l(`feedback.taskDraftCreated`)),window.requestAnimationFrame(()=>be.current?.focus())},onOpenChat:()=>C(`chat`),onQuickComplete:i?void 0:Ze,onSelect:h,quickCompletingTodoIds:ae,selectedTodoId:Ge?.kind===`todo`?Ge.item.todoId:null,userTodos:r.userTodos}):V&&S===`files`?(0,B.jsx)(yx,{items:Re.filter(e=>e.kind===`output`),onSelect:h,reportState:r.periodicReports}):!V&&!w?(0,B.jsx)(vx,{goals:Ne,onRetry:()=>void t.onRefresh?.(),onSelectGoal:tt,systemHealth:r.systemHealth}):V?(0,B.jsxs)(B.Fragment,{children:[V&&v?.goalId===V.goalId?(0,B.jsx)(xx,{onClose:()=>y(null),onOpenDetails:()=>h({item:v,kind:`run`}),run:v}):null,(0,B.jsx)(Iy,{items:ze,onSelect:h,selectedGoal:V})]}):(0,B.jsx)(Iy,{items:He,onSelect:h,selectedGoal:null})]}),(0,B.jsx)(`div`,{className:`personal-composer-wrap`,children:i?(0,B.jsxs)(`div`,{className:`personal-read-only-notice`,children:[(0,B.jsx)(`strong`,{children:l(`source.readOnlyNoticeTitle`)}),(0,B.jsx)(`span`,{children:l(`source.readOnlyNoticeDescription`)})]}):(0,B.jsxs)(B.Fragment,{children:[!V&&!w&&E&&Be.length?(0,B.jsx)(bx,{messages:Be,onClose:()=>D(!1),onOpenConversation:()=>{D(!1),T(!0)}}):null,V&&S!==`chat`&&O&&Ve.length?(0,B.jsx)(bx,{agentLabel:at,messages:Ve,onClose:()=>ee(!1),onDraftTask:S===`tasks`?e=>{je(`创建一个 Task:${hx(e)}`),re(l(`feedback.taskDraftCreated`)),window.requestAnimationFrame(()=>be.current?.focus())}:void 0,onOpenConversation:()=>{ee(!1),C(`chat`)},title:`${V.title} · ${at}`}):null,F?(0,B.jsxs)(`div`,{className:`personal-action-feedback`,role:`status`,children:[(0,B.jsx)(`span`,{children:F}),(0,B.jsx)(`button`,{"aria-label":l(`common.closeActionReceipt`),onClick:()=>re(null),type:`button`,children:(0,B.jsx)($m,{size:14})})]}):null,(0,B.jsx)(`p`,{className:`personal-composer-hint`,children:V?st>0?l(`composer.goalRunningHint`,{agent:at,count:st}):l(`composer.goalMessageHint`,{agent:at}):l(`composer.managerMessageHint`)}),V?(0,B.jsxs)(`div`,{className:`personal-quick-prompts`,children:[(0,B.jsxs)(`button`,{"aria-label":l(`composer.nextAction`),className:`is-draft`,onClick:()=>Me(l(`composer.nextActionPrompt`)),title:l(`composer.prepareDraft`),type:`button`,children:[(0,B.jsx)(Em,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.nextAction`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]}),(0,B.jsxs)(`button`,{className:`is-immediate`,disabled:k,onClick:()=>void it(l(`composer.agentProgressPrompt`)),title:l(`composer.immediate`),type:`button`,children:[(0,B.jsx)(Bm,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.agentProgress`)}),(0,B.jsx)(`em`,{className:`personal-prompt-badge`,children:l(`composer.immediate`)})]}),(0,B.jsxs)(`button`,{"aria-label":l(`composer.monitor`),className:`is-draft`,onClick:()=>Ye(`monitor`,R),title:l(`composer.monitorHint`),type:`button`,children:[(0,B.jsx)($p,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.monitor`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]})]}):(0,B.jsxs)(`div`,{className:`personal-quick-prompts`,children:[(0,B.jsxs)(`button`,{"aria-label":l(`composer.globalTasks`),className:`is-draft`,onClick:()=>Me(l(`composer.globalTasksPrompt`)),title:l(`composer.prepareDraft`),type:`button`,children:[(0,B.jsx)(Em,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.globalTasks`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]}),(0,B.jsxs)(`button`,{className:`is-immediate`,disabled:k,onClick:()=>void it(l(`composer.globalProgressPrompt`)),title:l(`composer.immediate`),type:`button`,children:[(0,B.jsx)(Bm,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.globalProgress`)}),(0,B.jsx)(`em`,{className:`personal-prompt-badge`,children:l(`composer.immediate`)})]}),(0,B.jsxs)(`button`,{"aria-label":l(`composer.createGoal`),className:`is-draft`,onClick:qe,title:l(`composer.createGoalHint`),type:`button`,children:[(0,B.jsx)(Pm,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.createGoal`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]})]}),ot?(0,B.jsxs)(`div`,{className:`personal-goal-draft-status`,role:`status`,children:[(0,B.jsx)(`strong`,{children:l(`composer.createGoalDraft`)}),(0,B.jsx)(`span`,{children:l(`composer.createGoalDraftDescription`)})]}):null,j.length?(0,B.jsx)(`div`,{className:`personal-composer-images`,"aria-label":l(`composer.imagesPending`),children:j.map(e=>(0,B.jsxs)(`figure`,{children:[(0,B.jsx)(`img`,{alt:e.name,src:e.dataUrl}),(0,B.jsx)(`button`,{"aria-label":l(`composer.sentImageAlt`,{name:e.name}),onClick:()=>M(t=>t.filter(t=>t.id!==e.id)),type:`button`,children:(0,B.jsx)($m,{size:13})})]},e.id))}):null,N?(0,B.jsx)(`p`,{className:`personal-composer-error`,role:`alert`,children:N}):null,(0,B.jsxs)(`div`,{className:`personal-channel-composer`,onDragOver:e=>{[...e.dataTransfer.items].some(e=>e.kind===`file`&&e.type.startsWith(`image/`))&&e.preventDefault()},onDrop:e=>{let t=[...e.dataTransfer.files].filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),ct(t))},children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:17}),e.find(e=>e.agentId===De)?.label??De]}),(0,B.jsx)(`button`,{"aria-label":l(`composer.addImage`),className:`personal-composer-attach`,disabled:k||j.length>=Bx,onClick:()=>Se.current?.click(),title:l(`composer.attachImageHint`),type:`button`,children:(0,B.jsx)(jm,{size:17})}),(0,B.jsx)(`input`,{accept:`image/png,image/jpeg,image/webp,image/gif`,"aria-label":l(`composer.imagePicker`),className:`personal-composer-file-input`,disabled:k||j.length>=Bx,multiple:!0,onChange:e=>void ct(e.target.files),ref:Se,type:`file`}),(0,B.jsx)(`textarea`,{"aria-label":l(`composer.sendMessage`),onChange:e=>je(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),it())},onPaste:lt,placeholder:V?l(`composer.goalPlaceholder`,{goal:V.title}):l(`composer.managerPlaceholder`),ref:be,rows:1,value:ke}),(0,B.jsx)(`button`,{"aria-label":l(ot?`composer.createGoal`:`composer.send`),disabled:!ke.trim()&&j.length===0||k,onClick:()=>void it(),title:l(ot?`composer.createGoalHint`:`composer.sendMessageHint`),type:`button`,children:(0,B.jsx)(Bm,{size:18})})]})]})})]}),sidebar:(0,B.jsx)(xb,{attentionCount:Pe,goals:Ne,goalArchiveLoadState:n,goalLifecycleOperations:t.onExecuteGoalLifecycle?[`stop`,`resume`]:void 0,lifecycleBusyGoalIds:ie,onRequestGoalCreate:i?void 0:qe,onRequestGoalLifecycle:i&&!t.onExecuteGoalLifecycle?void 0:(e,t)=>void Je(e,t),onRetryGoalArchive:t.onRetryGoalArchive||t.onRefresh?()=>void(t.onRetryGoalArchive??t.onRefresh)?.():void 0,onOpenSettings:i?void 0:()=>h({kind:`settings`}),onSelectGoal:tt,selectedGoalId:R,statusSourceControl:s},s?.activeSource.statusUrl??`/status.json`)})}function Ux(e){return(e??``).replace(/\s+/gu,` `).trim()}function Wx(e,t=120){let n=Array.from(e);return n.length<=t?e:`${n.slice(0,t-1).join(``)}…`}function Gx(e,t,n){let r=Ux(e);return!r||r===`暂无`?n?t(n):``:/refresh-state|latest_run|latest run-derived/iu.test(r)?t(`projection.refreshState`):/first read-only adapter tick|read-only adapter/iu.test(r)?t(`projection.firstReadOnlyAdapterCheck`):/todo update recorded for/iu.test(r)?t(`projection.todoStatusUpdated`):/^(loopx|python3|npm|git|run)\s|\s--[a-z0-9-]+|\b[a-z]+_[a-z_]+\b/iu.test(r)?t(n??`projection.agentPreparingNextStep`):Wx(r)}function Kx(e,t){return t({advancing:`projection.agentAdvancingGoal`,idle:`projection.agentIdle`,needs_you:`projection.agentNeedsDecision`,stopped:`projection.agentStopped`,waiting_external:`projection.agentWaitingExternal`}[e])}function qx({eventCount:e,hasArtifact:t,hasLatestValidation:n},r){return{label:r(n?`projection.latestValidation`:`projection.latestRun`),metadata:e>0?r(`projection.events24h`,{count:e}):r(t?`projection.runEvidenceAvailable`:`projection.publicSafeProjection`)}}var Jx=`/status.json`,Yx=`loopx-status-source-catalog-v1`,Xx={id:`local`,kind:`local`,label:`本机`,readOnly:!1,statusUrl:Jx};function Zx(e,t){let n=ih(e,t).source;if(!n||!n.isLoopback||n.isRelative)return{error:`SSH 隧道来源必须使用显式的 localhost、127.0.0.1 或 ::1 URL。`};let r=new URL(n.url,t);return[`http:`,`https:`].includes(r.protocol)?{url:r.toString()}:{error:`状态来源只支持 HTTP 或 HTTPS。`}}function Qx(e){let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619);return`ssh-${(t>>>0).toString(36)}`}function $x(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;if(n.kind!==`ssh_tunnel`||typeof n.label!=`string`||typeof n.statusUrl!=`string`)return null;let r=n.label.trim(),i=Zx(n.statusUrl,t);if(!r||r.length>48||!(`url`in i))return null;let a=db(n.hostAlias)?n.hostAlias.trim():void 0;return{...a?{hostAlias:a}:{},id:Qx(i.url),kind:`ssh_tunnel`,label:r,readOnly:!0,statusUrl:i.url}}function eS(){return{schemaVersion:1,sources:[Xx]}}function tS(e,t){try{let n=e.getItem(Yx);if(!n)return eS();let r=JSON.parse(n);if(r.schemaVersion!==1||!Array.isArray(r.sources))return eS();let i=new Set([Xx.statusUrl]);return{schemaVersion:1,sources:[Xx,...r.sources.flatMap(e=>{let n=$x(e,t);return!n||i.has(n.statusUrl)?[]:(i.add(n.statusUrl),[n])})]}}catch{return eS()}}function nS(e,t){e.setItem(Yx,JSON.stringify({schemaVersion:1,sources:t.sources.filter(e=>e.kind===`ssh_tunnel`)}))}function rS(e,t){let n=new Set(t.filter(db).map(e=>e.trim())),r=!1,i=e.sources.map(e=>e.kind!==`ssh_tunnel`||e.hostAlias||!n.has(e.label)?e:(r=!0,{...e,hostAlias:e.label}));return r?{...e,sources:i}:e}function iS(e,t,n){let r=t.label.trim();if(!r)return{error:`请填写来源名称。`};if(r.length>48)return{error:`来源名称不能超过 48 个字符。`};let i=Zx(t.statusUrl,n);if(!(`url`in i))return i;if(e.sources.some(e=>e.statusUrl===i.url))return{error:`这个状态 URL 已经在来源目录中。`};if(t.hostAlias!==void 0&&!db(t.hostAlias))return{error:`请选择有效的 SSH Host。`};let a=t.hostAlias?.trim(),o={...a?{hostAlias:a}:{},id:Qx(i.url),kind:`ssh_tunnel`,label:r,readOnly:!0,statusUrl:i.url};return{catalog:{...e,sources:[...e.sources,o]},source:o}}function aS(e,t){return{...e,sources:e.sources.filter(e=>e.kind===`local`||e.id!==t)}}function oS(e,t,n){if(!t.trim()||ih(t,n).source?.isRelative)return Xx;let r=t.trim();try{r=new URL(r,n).toString()}catch{return null}return e.sources.find(e=>e.statusUrl===r)??null}function sS(e,t,n){return oS(e,t,n)||(ih(t,n).source?.isRelative?Xx:{id:`temporary`,kind:`ssh_tunnel`,label:`临时来源`,readOnly:!0,statusUrl:t.trim()})}function cS(e,t,n,r){return sS(e,t??n,r)}var lS={delete:`删除`,deploy:`部署`,merge:`合并`,payment:`付款`,release:`发布`};function uS(e,t,n){let r=t.replace(/\s+/gu,` `).trim().toLowerCase(),i=n.target.replace(/\s+/gu,` `).trim().toLowerCase();return!i||!r.includes(i)?null:{actionKind:`goal.update`,context:{goal_id:e,kind:`goal`,natural_language:t,semantic_proposal:{operation:n.operation,target:n.target}},idempotencyKey:`workspace-semantic-protected-${e}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e,status:`operator_gate_requested`},summary:`请求受保护操作:${lS[n.operation]} · ${n.target}`}}var dS=Jx;async function fS(e){let t=await fetch(e,{cache:`no-store`,signal:AbortSignal.timeout(3e4)});if(!t.ok)throw Error(`HTTP ${t.status} while loading ${e}`);return Ep(await t.json())}function pS(e,t){if(t?.controller_readiness?.decision_advisor_ready||t?.controller_readiness?.write_controller_ready)return`controller_ready`;if(t?.controller_readiness)return`controller_gated`;if(t?.human_reward)return`reward_judged`;if(t?.operator_gate?.decision===`approve`)return`operator_approved`;if(t?.operator_gate)return`operator_gated`;let n=e||t?.classification||``;return n===`connected_without_run`?`connected`:n===`read_only_project_map`||t?.project_map?`mapped`:n===`state_refreshed`?`refreshed`:n&&n!==`no_status`?`adapter_inspected`:`registered`}function mS(e,t){let n=new Map(t.map(e=>[e.goal_id,e])),r=new Set,i=e.map(e=>{r.add(e.id);let t=n.get(e.id),i=e.latest_runs[0],a=t?.lifecycle_phase??e.lifecycle_phase??i?.lifecycle_phase??pS(t?.status??i?.classification??e.status,i),o=t?.lifecycle_flags?.length?t.lifecycle_flags:e.lifecycle_flags?.length?e.lifecycle_flags:i?.lifecycle_flags?.length?i.lifecycle_flags:[a];return{goal:e,queueItem:t,latestRun:i,status:t?.status??i?.classification??e.status??`no_status`,waitingOn:t?.waiting_on??`clear`,severity:t?.severity??`clear`,lifecyclePhase:a,lifecycleFlags:o}});for(let e of t)r.has(e.goal_id)||i.push({goal:{activation_state:e.activation_state,id:e.goal_id,status:e.status,display_name:e.goal_id,latest_runs:[],lifecycle_flags:[e.lifecycle_phase??`registered`],registry_member:!0,legacy_runtime_goal:!1,index_exists:!1,raw_index_records:0,unique_runs:0},queueItem:e,status:e.status,waitingOn:e.waiting_on,severity:e.severity,lifecyclePhase:e.lifecycle_phase??`registered`,lifecycleFlags:e.lifecycle_flags??[`registered`]});return i}function hS(e){return(e??``).replace(/\s+/g,` `).trim()}function gS(e,t=132){let n=hS(e);return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function _S(e){let t=new Map;for(let n of e?.goals??[])t.set(n.goal_id,n);return t}function vS(e,t){return e===void 0||t===void 0?void 0:e+t}function yS(e,t){if(!e)return null;let n=t===`user`?e.queueItem?.project_asset?.user_todos:e.queueItem?.project_asset?.agent_todos;if(n?.items?.length)return{done_count:n.done??n.items.filter(e=>e.done).length,items:n.items,open_count:n.open??n.items.filter(e=>!e.done).length,total_count:n.total??n.items.length};let r=t===`user`?e.queueItem?.user_todos:e.queueItem?.agent_todos;return r?.items?.length?r:null}function bS(e){return e?.items.find(e=>!e.done)}function xS(e,t,n=`todos`){return e?.items?.length?{advancement_done_count:e.advancement_done_count??t?.advancement_done_count,done_count:e.done??e.items.filter(e=>e.done).length,items:e.items,open_count:e.open??e.items.filter(e=>!e.done).length,total_count:e.total??e.items.length}:t??null}function SS(e){return e?.queueItem?.project_asset?.quota?.state??e?.queueItem?.quota?.state??e?.goal.quota?.state??`waiting`}function CS(e,t,n){let r=[];for(let t of e){let e=yS(t,`agent`);for(let n of e?.items??[])r.push({goalId:t.goal.id,role:`agent`,todo:n})}let i=new Map;for(let e of r){let t=e.todo.claimed_by||`codex`,n=i.get(t)??[];n.push(e),i.set(t,n)}let a=new Map((n?.agents??[]).map(e=>[e.agent_id,e]));return Array.from(new Set([...i.keys(),...a.keys()])).map(e=>{let t=i.get(e)??[],n=a.get(e),r=Array.from(new Set([...t.map(e=>e.goalId),n?.current_todo?.goal_id,...n?.goal_ids??[]].filter(Boolean))),o=(t.filter(e=>!e.todo.done)[0]??t[0])?.goalId??n?.current_todo?.goal_id??r[0]??``,s=n?.last_activity_at??null;return{agentId:e,claimedTodos:t,currentTodo:n?.current_todo??null,evidenceRefs:[],goalIds:r,handoffNote:null,lastActivity:s,nextSafeAction:n?.next_action?.trim()||`Inspect status projection before taking work`,primaryGoalId:o,quotaHints:[],staleClaimHint:null,status:{label:`可用`,summary:`正常运行`,variant:`success`},workspaceRef:null}})}function wS(e){return e?.map(e=>({dataUrl:e.data_url,id:e.id,mimeType:e.mime_type,name:e.name,size:e.size}))}var TS=`loopx.personal-agent-selection.v1`;function ES(){if(typeof window>`u`)return{};try{let e=JSON.parse(window.localStorage.getItem(TS)??`{}`);return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(e=>typeof e[0]==`string`&&typeof e[1]==`string`))}catch{return{}}}var DS={需修复:`danger`,等你:`warning`,等待条件:`info`,推进中:`success`,安静运行:`neutral`,已停止:`neutral`,已完成:`neutral`};function OS(e,t){return hS(t)||e.replace(/^loopx[-_]/i,`LoopX `).split(/[-_]+/).filter(Boolean).map((e,t)=>t===0?`${e.slice(0,1).toUpperCase()}${e.slice(1)}`:e).join(` `)}function kS(e){return e.split(/\r?\n/u).filter(e=>!/^\s*GOAL_(STATUS|PROGRESS)\s*:/u.test(e)).map(e=>/^\s*GOAL_EVIDENCE\s*:/u.test(e)?e.replace(/^\s*GOAL_EVIDENCE\s*:/u,`验证依据:`):/^\s*NEXT_ACTION\s*:/u.test(e)?e.replace(/^\s*NEXT_ACTION\s*:/u,`下一步:`):e).join(` +`).trim()}function AS(e,t){return[`agent`,`assistant`].includes(e.trim().toLowerCase())&&t.trim().length>0}var jS=`已发现的项目 Agent`;function MS(e){switch(cy(e)){case`codex`:return`Codex`;case`claude`:return`Claude Code`;case`kiro`:return`Kiro CLI`;case`trae`:return`Trae CLI Agent`;case`coco`:return`Coco Agent`;default:return OS(e)}}function NS(e,t){switch(ly(e,t)){case`codex`:return`代码与项目执行`;case`claude`:return`复杂分析与长任务`;case`openai`:case`anthropic`:return`管家问答 · 无工具`;case`kiro`:return`终端编码 · 原生 /goal 循环`;case`trae`:return`前端与交互实现`;case`coco`:return`通用任务`;default:return jS}}function PS(e,t){let n=e.project_asset;return t===`user`?xS(n?.user_todos,e.user_todos,`project_asset.user_todos`):xS(n?.agent_todos,e.agent_todos,`project_asset.agent_todos`)}function FS(e){return gS(e.title??e.text,112)}function IS(e){let t=e.resume_condition?.resume_receipt;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t.receipt_id;return typeof n==`string`&&n.trim()?n.trim():null}function LS(e,t){return{resumeWhen:e.resume_when??null,resumeReady:e.resume_ready??null,resumeReceiptId:IS(e),claimedBy:e.claimed_by??null,done:e.status!==`deferred`&&e.done,evidence:e.evidence?gS(e.evidence,96):null,index:e.index,priority:e.priority??null,status:e.status??null,taskClass:e.task_class??null,taskDomain:e.task_domain??null,text:FS(e),todoId:e.todo_id?.trim()||`${t.goal.id}:agent:${e.index}`}}function RS(e){let t=e.queueItem?.agent_todos,n=t?.items??e.queueItem?.project_asset?.agent_todos?.items??[],r=new Map(n.map(t=>[t.todo_id?.trim()||`${e.goal.id}:agent:${t.index}`,t]));for(let n of t?.deferred_items??[]){let t=n.todo_id?.trim()||`${e.goal.id}:agent:${n.index}`;r.has(t)||r.set(t,n)}return[...r.values()]}function zS(e){return RS(e).map(t=>LS(t,e))}function BS(e,t,n){let r=new Map;for(let n of e.todo_index?.items??[]){if(n.goal_id!==t.goal.id||n.role!==`agent`)continue;let e=LS(n,t);r.set(e.todoId,e)}for(let e of n)r.has(e.todoId)||r.set(e.todoId,e);let i=new Map;for(let e of r.values()){if(e.done||e.taskClass!==`advancement_task`)continue;let t=e.taskDomain?.trim();t&&i.set(t,(i.get(t)??0)+1)}return[...i].map(([e,t])=>({domain:e,matchingTodoCount:t}))}function VS(e,t){return{claimedBy:e.claimed_by??null,done:e.status===`done`||e.status===`completed`,index:-1,priority:e.priority??null,status:e.status??null,taskClass:e.task_class??null,text:gS(e.title,112),todoId:e.todo_id?.trim()||`${t.goal.id}:agent:${e.claimed_by??`unknown`}:current`}}function HS(e,t,n){let r=new Map(e.map(e=>[e.todoId,e]));for(let e of t){let t=e.currentTodo;if(!t||t.goal_id!==n.goal.id)continue;let i=VS(t,n);r.has(i.todoId)||r.set(i.todoId,i)}return[...r.values()]}function US(e){let t=e.queueItem?.project_asset?.agent_todos,n=e.queueItem?.agent_todos,r=RS(e),i=t?.advancement_done_count??n?.advancement_done_count??t?.done??n?.done_count??null,a=r.filter(e=>e.done&&e.status!==`deferred`).length,o=Math.max(i??0,a),s=new Set(r.map(e=>e.todo_id?.trim()).filter(e=>!!e)),c=(t?.recent_completed_advancement_items??[]).filter(e=>!e.todo_id?.trim()||!s.has(e.todo_id.trim())).map(t=>LS(t,e)),l=r.find(e=>!e.done);return{doneTodoCount:o,nextTodoText:hS(t?.next??``)||(l?hS(l.title??``)||hS(l.text??``):``)||null,recentCompleted:c}}function WS(e,t){let n=hS(e);return n?/\b(state_file|registry_goal|authority_sources|source_registry)\b|\b[a-z_]+\s+\d+\/\d+/i.test(n)?t(`projection.goalVerified`):Gx(n,t,`projection.validationRecorded`):``}function GS(e,t=4){if(e.length<=t)return e;let n=e.findIndex(e=>!e.done);if(n<0)return e.slice(-t);let r=Math.max(0,Math.min(n-2,e.length-t));return e.slice(r,r+t)}function KS(e,t,n){let r=t.queueItem?.project_asset?.latest_validation,i=t.latestRun,a=e.event_ledger_summary?.goals.find(e=>e.goal_id===t.goal.id);if(!r&&!i&&!a)return null;let o=[WS(r?.summary,n),Gx(i?.health_check,n),Gx(i?.recommended_action,n)].find(e=>e!==``&&e!==`暂无`)??n(`projection.runRecorded`),s=qx({eventCount:a?.events_24h??0,hasArtifact:!!(i?.json_exists||i?.markdown_exists),hasLatestValidation:!!r},n);return{generatedAt:r?.generated_at??i?.generated_at??a?.latest_event_at??``,label:s.label,metadata:s.metadata,runId:i?`${t.goal.id}:${i.generated_at}`:null,safePreview:[o,s.metadata].filter(Boolean).join(` +`),summary:o,todoId:t.queueItem?.project_asset?.agent_todos?.items.find(e=>!e.done)?.todo_id??null}}function qS(e){return[e.status,e.goal.status,e.latestRun?.classification,e.lifecyclePhase].filter(Boolean).some(e=>/(^|[_\s-])(done|complete|completed|finished|terminal|closed|success)([_\s-]|$)/i.test(e??``))}function JS(e,t){return e.global_registry?.findings?.find(e=>e.severity===`high`&&(e.goal_id===t.goal.id||e.goal_ids.includes(t.goal.id)))}function YS(e){return[e.status,e.goal.status,e.latestRun?.classification,e.lifecyclePhase].filter(Boolean).some(e=>/(^|[_\s-])(failure|failed|error|broken|unhealthy|blocked[_\s-]?health|health[_\s-]?blocked)([_\s-]|$)/i.test(e??``))}function XS(e,t){let n=t.queueItem?.stale_latest_run_warning;return t.severity===`high`||!!JS(e,t)||!!(n?.requires_refresh_state||n?.severity===`high`)||YS(t)}function ZS(e,t){let n=JS(e,t);return t.queueItem?.stale_latest_run_warning?.recommended_action??t.queueItem?.stale_latest_run_warning?.reason??n?.recommended_action??n?.message??t.queueItem?.recommended_action??t.latestRun?.recommended_action??null}function QS(e){let t=e.latestRun?.operator_gate,n=t?.decision?.trim().toLowerCase()??``,r=new Set([`approve`,`approved`,`reject`,`rejected`,`defer`,`deferred`,`cancel`,`cancelled`]),i=[e.queueItem?.recommended_action,e.latestRun?.recommended_action].filter(Boolean).join(` `),a=/(?:等待|需要)(?:用户|你|owner).{0,24}(?:批准|确认|授权|补充|选择|决定)|(?:批准|确认|授权).{0,16}(?:后|才能|方可)/i.test(i);return!!(t&&!r.has(n))||e.lifecyclePhase===`operator_gated`&&!r.has(n)||a}function $S(e,t){let n=e.latestRun?.operator_gate;return Gx(n?.operator_question??n?.reason_summary??n?.follow_up??e.queueItem?.recommended_action??e.latestRun?.recommended_action,t,`projection.confirmAgentDecision`)}function eC(e,t){if(t.goal.activation_state===`stopped`)return`已停止`;let n=yS(t,`user`),r=yS(t,`agent`),i=!!bS(n),a=!!bS(r);return[`user_or_controller`,`controller`].includes(t.waitingOn)||i||QS(t)?`等你`:XS(e,t)?`需修复`:t.waitingOn===`external_evidence`?`等待条件`:SS(t)===`eligible`||a?`推进中`:qS(t)?`已完成`:`安静运行`}function tC(e,t,n,r){if(n===`已停止`)return Kx(`stopped`,r);if(n===`需修复`)return Gx(ZS(e,t),r,`projection.statusRefreshNeeded`);if(n===`等你`)return Kx(`needs_you`,r);if(n===`推进中`){let e=[(yS(t,`agent`)?.items??[]).filter(e=>!e.done).flatMap(e=>[e.title,e.text]).map(e=>hS(e)).find(e=>e!==``&&e!==`暂无`),t.queueItem?.recommended_action,t.latestRun?.recommended_action].map(e=>hS(e)).find(e=>e!==``&&e!==`暂无`);return e?Gx(e,r,`projection.agentAdvancingGoal`):Kx(`advancing`,r)}return Kx(n===`等待条件`?`waiting_external`:`idle`,r)}function nC(e,t){return t.some(t=>e.includes(t))}function rC(e,t,n){if(t.goals.some(e=>e.activationState===`active`&&e.loadState))return{text:`Goal 状态尚未全部加载,暂不能给出完整统计。可先打开已加载的 Goal,失败项可重试。`,lines:[]};if(nC(n,[`Agent`,`agent`,`推进`,`在做`])){let e=t.goals.filter(e=>![`安静运行`,`已完成`,`已停止`].includes(e.state)),n=(e.length>0?e:t.goals).slice(0,3);return n.length===0?{text:`当前状态里还没有 Goal 可供汇总。`,lines:[]}:{text:e.length>0?`Agent 当前关注这些 Goal:`:`当前 Goal 都比较安静:`,lines:n.map(e=>`${e.title} · ${e.state} · ${e.agentSentence}`)}}if(nC(n,[`现在`,`下一步`,`我该`,`该做什么`,`优先处理`])){let e=t.userTodos[0];if(e)return{text:e.blocking?`先处理「${OS(e.goalId)}」:${e.text}`:`当前最先处理「${OS(e.goalId)}」:${e.text}`,lines:[]};let n=t.goals.find(e=>e.state===`需修复`);if(n)return{text:`没有待办,但这个 Goal 需要先修复。`,lines:[`${n.title} · ${n.agentSentence}`]};let r=t.goals.find(e=>e.state===`推进中`);return r?{text:`目前不需要你介入,Agent 正在推进。`,lines:[`${r.title} · ${r.agentSentence}`]}:{text:`当前系统很安静,没有需要你立即处理的事项。`,lines:[]}}if(nC(n,[`等我`,`阻塞`,`需要我`,`全局待办`]))return t.userTodos.length===0?{text:`目前没有 Goal 在等你,开放用户待办为 0。`,lines:[]}:{text:`有 ${t.userTodos.length} 项开放用户待办,阻塞项优先:`,lines:t.userTodos.slice(0,3).map(e=>`${OS(e.goalId)} · ${e.blocking?`阻塞`:`待处理`} · ${e.text}`)};if(nC(n,[`状态`,`异常`,`修复`,`健康`])){let n=t.systemHealth?!t.systemHealth.ok:!e.ok||!e.contract?.ok||!e.global_registry?.ok||(e.global_registry?.summary?.high??0)>0,r=t.goals.filter(e=>e.state===`需修复`),i=r.slice(0,n?2:3).map(e=>`${e.title} · ${e.agentSentence}`);return n&&i.push(`全局状态、契约或注册表健康检查未通过,请进入管理页检查。`),i.length===0?{text:`当前没有发现 Goal 级或全局健康异常。`,lines:[]}:{text:r.length>0?`当前需要关注这些健康问题:`:`Goal 状态正常,但全局健康需要检查:`,lines:i}}return{text:`当前管家支持三类问题:下一步、等待你的事项、Agent 与健康状态。`,lines:[`问“我现在该做什么?”`,`问“哪些 Goal 在等我?”`,`问“Agent 在做什么?”或当前健康状态`]}}function iC(e,t,n,r=!1){let i=new Map(t.map(e=>[e.goal.id,e])),a=new Set(e.run_history.goals.filter(e=>e.activation_state===`stopped`).map(e=>e.id)),o=_S(e.usage_summary),s=CS(t,e.todo_index,e.agent_management_projection),c=e.attention_queue.items.flatMap((e,t)=>{if(a.has(e.goal_id))return[];let n=[`user_or_controller`,`controller`].includes(e.waiting_on);return(PS(e,`user`)?.items??[]).map((r,i)=>({projectedDone:r.done,details:Ud(r),actionKind:r.action_kind??null,blocking:n,goalId:e.goal_id,sourceOrder:t,taskClass:r.task_class??null,text:FS(r),todoId:r.todo_id?.trim()||`${e.goal_id}:user:${r.index}`,todoOrder:i,updatedAt:r.updated_at??null}))}),l=c.filter(e=>!e.projectedDone),u=new Set(l.map(e=>e.goalId)),d=t.flatMap((t,r)=>a.has(t.goal.id)||u.has(t.goal.id)||!QS(t)?[]:[{details:Ud({task_class:`user_gate`,status:`open`,note:t.latestRun?.operator_gate?.reason_summary}),actionKind:`gate.resolve`,blocking:!0,goalId:t.goal.id,sourceOrder:e.attention_queue.items.length+r,taskClass:`user_gate`,text:$S(t,n),todoId:`${t.goal.id}:operator-gate`,todoOrder:0,updatedAt:t.latestRun?.operator_gate?.recorded_at??t.latestRun?.generated_at??null}]),f=[...l,...d].sort((e,t)=>Number(t.blocking)-Number(e.blocking)||e.sourceOrder-t.sourceOrder||e.todoOrder-t.todoOrder),p=e.run_history.goals.flatMap(t=>{if(t.registry_member===!1)return[];let a=i.get(t.id);if(!a)return[];let c=eC(e,a),l=f.find(e=>e.goalId===t.id),u=l?.text??null,d=US(a),p=t.coordination?.registered_agents??[],m=new Set(p),h=[...s.filter(e=>e.goalIds.includes(t.id)&&!/unassigned|unknown/i.test(e.agentId)&&(m.size===0||m.has(e.agentId))&&(e.currentTodo?.goal_id===t.id||e.claimedTodos.some(e=>e.goalId===t.id)))].sort((e,t)=>(t.lastActivity??``).localeCompare(e.lastActivity??``)),g=new Set(h.map(e=>e.agentId)),_=[...h.map(e=>({agentId:e.agentId,label:e.agentId,lastActivityAt:e.lastActivity,state:e.status.label})),...p.filter(e=>!g.has(e)).map(e=>({agentId:e,label:e,lastActivityAt:null,state:`registered`}))],v=h[0],y=HS(zS(a),h,a),b=[d.nextTodoText,a.queueItem?.recommended_action,a.latestRun?.recommended_action,tC(e,a,c,n)].map(e=>Gx(e,n)).find(e=>e!==``&&e!==`暂无`)??n(`projection.nextUpdatePending`);return[{activationState:t.activation_state,agentId:v?.agentId??p[0]??`codex`,agentLaneCount:_.length,agentLanes:_,agentLabel:v?.agentId,agentSentence:tC(e,a,c,n),agentTodos:[...y,...d.recentCompleted],doneTodoCount:d.doneTodoCount,acceptanceObservation:t.acceptance_observation,goalId:t.id,latestActivity:a.latestRun?.generated_at??``,needsYou:u,needsYouActionKind:l?.actionKind??null,needsYouBlocking:l?.blocking??!1,needsYouTaskClass:l?.taskClass??null,needsYouTodoId:l?.todoId??null,nextSentence:b,runEvidence:KS(e,a,n),state:c,...r?{subagentExecution:{allowedDomains:t.spawn_policy?.allowed_domains??[],domainCandidates:BS(e,a,y),enabled:t.spawn_policy?.mode===`multi_subagent`&&t.spawn_policy.spawn_allowed===!0&&t.spawn_policy.max_children>0,maxChildren:t.spawn_policy?.max_children??0,modelConfig:t.spawn_policy?.model_config}}:{},title:OS(t.id,t.display_name),usage:(()=>{let e=o.get(t.id);return e?{costUsd24h:e.cost_usd_24h,costUsd7d:e.cost_usd_7d,durationMs24h:e.duration_ms_24h,durationMs7d:e.duration_ms_7d,tokens24h:vS(e.input_tokens_24h,e.output_tokens_24h),tokens7d:vS(e.input_tokens_7d,e.output_tokens_7d)}:null})()}]}),m=[];if(e.ok||m.push(`状态载荷未标记为正常 (payload.ok === false)`),e.contract&&!e.contract.ok){let t=e.contract.summary,n=t?`${t.errors} 项错误 / ${t.warnings} 项警告`:e.contract.errors?.[0]||`请检查控制面契约`;m.push(`契约检查未通过: ${n}`)}if(e.global_registry){e.global_registry.ok||m.push(`注册表状态异常: ${e.global_registry.summary.high} 项高危`);for(let t of e.global_registry.findings||[])t.severity===`high`&&m.push(`[${t.kind}] ${t.message}`)}let h=e.decision_freshness_summary?.summary?.stale_count?`${e.decision_freshness_summary.summary.stale_count} 项决策状态已过期`:null,g=m.length===0&&!h,_={ok:g,summary:g?`所有控制面契约与注册表检查均正常`:`发现 ${m.length+ +!!h} 项系统健康关注点`,issues:m,freshnessWarning:h};return{blockingTodoCount:f.filter(e=>e.blocking).length,goalNotifications:(e.goal_channel_notification_projection?.goals??[]).map(e=>({goalId:e.goal_id,configured:e.configured,enabled:e.enabled,humanGateAutoNotifyEnabled:e.human_gate_auto_notify_enabled,lastNotifiedAt:e.last_notified_at??null,receiptCount:e.receipt_count,targetRef:e.target_ref??null})),goals:p,openUserTodoCount:f.length,systemHealth:_,attentionHistory:[...c,...d],userTodos:f,visibleUserTodos:f.slice(0,5),workers:(e.agent_management_projection?.agents??[]).map(e=>({agentId:e.agent_id,currentTodoGoalId:e.current_todo?.goal_id??null,currentTodoText:e.current_todo?.title?gS(e.current_todo.title,96):null,lastActivityAt:e.last_activity_at??null,state:e.state??null}))}}function aC({goalArchiveLoadState:e,isLoading:t,onGoalActivationStateChange:n,onGoalDeleted:r,onSelectGoal:i,onReconcileStatus:a,onRefresh:o,onRetryGoalArchive:s,payload:c,progress:l,rows:u,selectedGoalId:d,statusSourceControl:f,theme:p,toggleTheme:m}){let h=f.activeSource.readOnly,g=f.activeSource.kind===`ssh_tunnel`?f.activeSource.hostAlias:void 0,{t:_}=Ji(),[v,y]=(0,z.useState)([]),[b,x]=(0,z.useState)(!1),S=(0,z.useMemo)(()=>{let e=iC(c,u,_,b);if(!l)return e;let t=Object.values(l.snapshots).map(e=>iC(e,mS(e.run_history.goals,e.attention_queue.items),_,b)),n=new Map(t.flatMap(e=>e.goals).map(e=>[e.goalId,e])),r=e.goals.map(e=>n.get(e.goalId)??{...e,loadError:l.errors[e.goalId],loadState:l.errors[e.goalId]?`error`:`loading`,agentId:``,agentSentence:``,nextSentence:``,subagentExecution:void 0}),i=t.flatMap(e=>e.userTodos),a=r.some(e=>e.activationState===`active`&&e.loadState),o=[...new Set(t.flatMap(e=>e.systemHealth?.issues??[]))];return{...e,goals:r,userTodos:i,attentionHistory:t.flatMap(e=>e.attentionHistory??e.userTodos),visibleUserTodos:i.slice(0,5),openUserTodoCount:i.length,blockingTodoCount:i.filter(e=>e.blocking).length,workers:[...new Map(t.flatMap(e=>e.workers??[]).map(e=>[e.agentId,e])).values()],goalNotifications:t.flatMap(e=>e.goalNotifications??[]),systemHealth:a||t.length===0?void 0:{ok:t.every(e=>e.systemHealth?.ok),issues:o,summary:o.length?`发现 ${o.length} 项系统健康关注点`:`状态检查已完成`,freshnessWarning:t.map(e=>e.systemHealth?.freshnessWarning).filter(Boolean).join(`;`)||null}}},[c,u,l,b,_]),C=S.goals.find(e=>e.goalId===d)??null,w=l?.snapshots[d]??c,[T,E]=(0,z.useState)(null),[D,O]=(0,z.useState)(null),[ee,te]=(0,z.useState)(!1),ne=S.goals.some(e=>e.activationState===`active`&&e.loadState===`loading`)?`loading`:S.goals.map(e=>`${e.goalId}:${e.agentId}`).join(`|`),k=C?.goalId??`manager`;S.goals.some(e=>e.activationState===`active`&&e.loadState)||(S.systemHealth?!S.systemHealth.ok:!c.ok)||S.openUserTodoCount>0&&`${S.openUserTodoCount}${S.blockingTodoCount}`;let A=v.length>0?v.map(e=>({agentId:e.agent_id,adapterKind:e.adapter_kind,available:e.available,capability:NS(e.agent_id,e.adapter_kind),interrupt:e.interrupt,label:e.display_name,location:e.location,resume:e.resume,source:e.source,statusLabel:e.available?`可用`:`需要配置`,streaming:e.streaming,toolCalls:e.tool_calls,trustScope:e.trust_scope})):[{agentId:`codex`,available:!0,capability:NS(`codex`),label:`Codex`,statusLabel:`正在检测`}],j=[...A,{agentId:`status-only`,available:!0,capability:`不调用模型`,adapterKind:`status_projection`,interrupt:!1,label:`仅查状态`,resume:!0,statusLabel:`只读`,streaming:!1,toolCalls:!1,trustScope:`read_only`}],M=A.find(e=>e.label===`Codex`&&e.available)?.agentId??A.find(e=>e.available)?.agentId??`status-only`,[N,P]=(0,z.useState)(ES),F=uh(j,N[k]??M,M),[re,ie]=(0,z.useState)(!1),[I,ae]=(0,z.useState)(!1),[L,oe]=(0,z.useState)(`chat`),[se,ce]=(0,z.useState)(``),[le,ue]=(0,z.useState)({}),[de,fe]=(0,z.useState)({}),[pe,me]=(0,z.useState)(null),[he,ge]=(0,z.useState)({}),[_e,ve]=(0,z.useState)([]),[ye,be]=(0,z.useState)(null),[xe,Se]=(0,z.useState)({}),Ce=(0,z.useRef)(1),we=(0,z.useRef)(1),Te=(0,z.useRef)(new Map),Ee=(0,z.useRef)(new Set),R=(0,z.useRef)(new Map),De=(0,z.useRef)(new Map),Oe=(0,z.useRef)(new Set),ke=(0,z.useRef)(new Set),Ae=(0,z.useRef)(null),je=(0,z.useRef)(null),Me=(0,z.useRef)(null),Ne=(0,z.useRef)(null);(0,z.useRef)(null);let Pe=le[k]??[];de[k];let Fe=C?S.userTodos.filter(e=>e.goalId===C.goalId):S.userTodos,V=C?.agentTodos??[];GS(V,C?.needsYou?3:4);let Ie=V.filter(e=>e.done).length,Le=V.length>0?`${Ie}/${V.length}`:`暂无计划`;C&&({...S},Fe.filter(e=>e.blocking).length,Fe.length),(0,z.useEffect)(()=>{let e=rh(f.activeSource.statusUrl,window.location.href),t=e.source?sh(w,e.source):null;if(!C||!t?.indexUrl||!t.detailUrl){E(null),O(null),te(!1);return}let{detailUrl:n,indexUrl:r}=t,i=!1;return E(null),O(null),te(!0),ch(r,C.goalId).then(async e=>{let t=e.items[0]?.detail_ref;return t?lh(n,t):null}).then(e=>{i||E(e)}).catch(e=>{i||O(Dp(e))}).finally(()=>{i||te(!1)}),()=>{i=!0}},[w,C?.goalId,f.activeSource.statusUrl]);let Re=C?void 0:he[k]?.sessionId;(0,z.useEffect)(()=>{if(h||!Re)return;let e=!1,t,n=async()=>{try{let t=await Bh(Re);if(e)return;let n=t.messages.filter(e=>e.origin===`manager_followup`);ue(e=>{let t=e[k]??[],r=new Set(t.map(e=>e.sourceMessageId)),i=n.filter(e=>!r.has(e.message_id));return i.length?{...e,[k]:[...t,...i.map(e=>({id:Ce.current++,sourceMessageId:e.message_id,role:`assistant`,agentLabel:F.label,sourceLabel:`管家交接回执`,text:kS(e.text),lines:[]}))]}:e})}catch{}finally{e||(t=setTimeout(n,3e3))}};return n(),()=>{e=!0,t&&clearTimeout(t)}},[h,Re,k,F.label]);function ze(e,t){ge(n=>{if(t===null){let t={...n};return delete t[e],t}return{...n,[e]:t}})}(0,z.useEffect)(()=>{if(h){y([]),x(!1);return}let e=!1;return Lh().then(t=>{e||(y(t.adapters??[]),x(t.goal_subagent_configuration===`preview_locked`))}).catch(()=>{e||x(!1)}),()=>{e=!0}},[h]),(0,z.useEffect)(()=>{try{window.localStorage.setItem(TS,JSON.stringify(N))}catch{}},[N]),(0,z.useEffect)(()=>{if(h||!F.available)return;let e=k,t=`${e}:${F.agentId}`,n=C?`goal`:`manager`,r=C?`goal.${C.goalId}`:`manager`,i=!1,a=null,o=null;return(async()=>{try{let s=await Uh({agentId:F.agentId,channelId:r,goalId:C?.goalId});if(i||(ue(t=>(t[e]?.length??0)>0?t:{...t,[e]:s.messages.map(e=>({sourceMessageId:e.message_id,agentLabel:e.role===`user`?void 0:F.label,attachments:wS(e.attachments),id:Ce.current++,lines:[],role:e.role===`user`?`user`:`assistant`,sourceLabel:e.role===`user`?void 0:e.role===`error`?`本地会话记录`:`恢复的 ${F.label} 会话`,text:e.role===`user`?e.text:kS(e.text)}))}),F.agentId===`status-only`))return;let c=s.sessions[0];if(o=c?.session_id??null,c&&!c.resumable){Ee.current.add(t),ze(e,{agentId:F.agentId,resumable:!1,sessionId:c.session_id,status:`resume_failed`});return}let l=n===`manager`?``:C?.goalId??``;if(n===`goal`&&!l)return;let u=await zh(l,F.agentId,`resume_latest`,n);if(i)return;Te.current.set(t,u.session_id);let d=s.snapshots.find(e=>e.session.session_id===u.session_id),f=d?.session.active_turn_id??``;if(ze(e,{agentId:F.agentId,resumable:!0,sessionId:u.session_id,status:f?`running`:`ready`,turnId:f||void 0}),Ee.current.delete(t),!f)return;let p=`${u.session_id}:${f}`;if(ke.current.has(p))return;ke.current.add(p),R.current.set(e,f),ze(e,{agentId:F.agentId,resumable:!0,sessionId:u.session_id,status:`running`,turnId:f}),me(e),a=new AbortController,De.current.set(e,a);let m=``,h=Be(e,{activity:[`正在恢复进行中的 Agent 回合`],agentLabel:F.label,lines:[],pending:!0,sourceLabel:`恢复的 ${F.label} 会话`,text:``});try{let t=await Xh(u.session_id,f,{signal:a.signal,onDelta:t=>{m+=t,Ve(e,h,{text:m})},onActivity:t=>{ue(n=>({...n,[e]:(n[e]??[]).map(e=>e.id===h?{...e,activity:[...new Set([...e.activity??[],t])].slice(-6)}:e)}))}});if(i)return;Ve(e,h,{lines:t.response.gate?[t.response.gate.summary,t.response.gate.next_action].filter(Boolean).slice(0,2):[],pending:!1,text:t.response.message||m.trim()||`${F.label} 已完成分析。`});let n=S.goals.find(e=>e.goalId===d?.session.goal_id)??C??S.goals[0]??null;if(n&&t.response.proposals.length>0){let r=t.response.proposals.map(e=>({goalId:n.goalId,id:we.current++,previewId:null,proposal:e,receiptLabel:null,state:`candidate`,statusMessage:null}));fe(t=>({...t,[e]:[...t[e]??[],...r]}))}}catch(t){if(i)return;Ve(e,h,{activity:[],lines:[],pending:!1,reconnect:t instanceof Th&&t.payload.reconnectable===!0,sourceLabel:`LoopX Chat 本地后端`,text:t instanceof Error?t.message:`无法恢复进行中的 Agent 回合。`})}finally{ke.current.delete(p),R.current.get(e)===f&&R.current.delete(e),ze(e,{agentId:F.agentId,resumable:!0,sessionId:u.session_id,status:`ready`}),De.current.get(e)===a&&De.current.delete(e),i||me(t=>t===e?null:t)}}catch(n){if(i)return;n instanceof Th&&n.payload.error_code===`resume_failed`&&(Ee.current.add(t),o&&ze(e,{agentId:F.agentId,resumable:!1,sessionId:o,status:`resume_failed`}))}})(),()=>{i=!0,a?.abort()}},[k,S.goals[0]?.goalId,h,C?.goalId,F.agentId,F.available,F.label]),(0,z.useEffect)(()=>{if(h||C||S.goals.length===0||ne===`loading`)return;let e=!1;return Promise.all(S.goals.filter(e=>!e.loadState).map(async e=>{let t=await Vh({agentId:e.agentId,channelId:`goal.${e.goalId}`,goalId:e.goalId});return{goalId:e.goalId,session:t.sessions[0]??null}})).then(t=>{e||ge(e=>{let n={...e};for(let e of t)e.session&&(n[e.goalId]={agentId:e.session.agent_id,resumable:e.session.resumable,sessionId:e.session.session_id,status:e.session.active_turn_id?`running`:e.session.status,turnId:e.session.active_turn_id??void 0});return n})}).catch(()=>{}),()=>{e=!0}},[h,ne,C?.goalId]),(0,z.useEffect)(()=>{if(be(null),h){ve([]),Se({});return}if(!C){ve([]),Se({});return}let e=!1,t=0,n=0;ve([]),Se({});let r=async()=>{if(!e){if(document.hidden){t=window.setTimeout(()=>void r(),1e4);return}try{let t=await Vh({goalId:C.goalId});if(!e){let r=t.sessions.filter(e=>e.channel_id?.startsWith(`task.`));ve(r);let i=await Promise.allSettled(r.map(e=>Bh(e.session_id)));if(!e){let e=i.some(e=>e.status===`rejected`);n=e?n+1:0,be(e?`partial`:null),Se(Object.fromEntries(i.flatMap((e,t)=>e.status===`fulfilled`?[[r[t].session_id,e.value]]:[])))}}}catch{n+=1,e||be(`offline`)}e||(t=window.setTimeout(()=>void r(),Math.min(3e4,2e3*2**Math.min(n,4))))}};return r(),()=>{e=!0,window.clearTimeout(t)}},[h,C?.goalId]),(0,z.useEffect)(()=>{if(!re)return;let e=window.requestAnimationFrame(()=>{Ae.current?.querySelector(`[role="menuitem"]:not(:disabled)`)?.focus()});return()=>{window.cancelAnimationFrame(e),je.current?.focus()}},[re]),(0,z.useEffect)(()=>{if(!I)return;let e=window.requestAnimationFrame(()=>Me.current?.focus());return()=>{window.cancelAnimationFrame(e),Ne.current?.focus()}},[I]),(0,z.useEffect)(()=>{if(!re&&!I)return;let e=e=>{e.key===`Escape`&&(ie(!1),ae(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[re,I]);function Be(e,t){let n=Ce.current++;return ue(r=>({...r,[e]:[...r[e]??[],{...t,id:n,role:`assistant`}]})),n}function Ve(e,t,n){ue(r=>({...r,[e]:(r[e]??[]).map(e=>e.id===t?{...e,...n}:e)}))}async function He(e,t){let n=e.trim();if(!n)return;let r=t&&`goalId`in t?t.goalId??`manager`:k,i=r===`manager`?null:S.goals.find(e=>e.goalId===r)??null,a=t?.agentId?uh(j,t.agentId,M):F,o=r===`manager`?S:i?{...S,blockingTodoCount:S.userTodos.filter(e=>e.goalId===i.goalId&&e.blocking).length,goals:[i],openUserTodoCount:S.userTodos.filter(e=>e.goalId===i.goalId).length,userTodos:S.userTodos.filter(e=>e.goalId===i.goalId),visibleUserTodos:S.userTodos.filter(e=>e.goalId===i.goalId)}:S,s=Ce.current++;if(ue(e=>({...e,[r]:[...e[r]??[],{attachments:t?.attachments,id:s,lines:[],role:`user`,text:n}]})),ce(``),me(r),a.agentId===`status-only`||!i&&r!==`manager`){let e=rC(w,o,n),t=a.agentId===`status-only`;Be(r,{agentLabel:t?`仅查状态`:`LoopX 管家`,lines:e.lines.slice(0,3),sourceLabel:t?`LoopX 状态投影 · 仅查状态`:`LoopX 状态投影`,text:e.text}),Rh({answer:[e.text,...e.lines.slice(0,3)].filter(Boolean).join(` +`),contextKind:r===`manager`?`manager`:`goal`,goalId:r===`manager`?void 0:r,question:n}).catch(()=>{}),me(null);return}let c=`${r}:${a.agentId}`,l=null;try{let e=Te.current.get(c);if(!e){let t=Ee.current.has(c)?`new`:`resume_latest`;e=(await zh(r===`manager`?``:i.goalId,a.agentId,t,r===`manager`?`manager`:`goal`)).session_id,Te.current.set(c,e),ze(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`ready`}),Ee.current.delete(c)}let o=``;l=Be(r,{activity:[`正在连接 Agent`],agentLabel:a.label,lines:[],pending:!0,sourceLabel:r===`manager`?`${a.label} 管家 · 跨 Goal`:`${a.label} Agent · ${OS(i.goalId)}`,text:``});let s=(await Jh(e,n,{attachments:t?.attachments,signal:(()=>{let e=new AbortController;return De.current.set(r,e),e.signal})(),onDelta:e=>{o+=e,l!==null&&Ve(r,l,{text:o})},onActivity:e=>{l!==null&&ue(t=>({...t,[r]:(t[r]??[]).map(t=>t.id===l?{...t,activity:[...new Set([...t.activity??[],e])].slice(-6)}:t)}))},onPhase:(t,n)=>{R.current.set(r,n),ze(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`running`,turnId:n})}})).response;if(Ve(r,l,{lines:s.gate?[s.gate.summary,s.gate.next_action].filter(Boolean).slice(0,2):[],pending:!1,text:kS(s.message||o.trim())||`${a.label} 已完成分析。`}),s.proposals.length>0&&!i&&Ve(r,l,{lines:[`请进入要修改的 Goal,预览并确认具体变更。`]}),s.proposals.length>0&&i){let e=s.proposals.map(e=>({goalId:i.goalId,id:we.current++,previewId:null,proposal:e,receiptLabel:null,state:`candidate`,statusMessage:null}));fe(t=>({...t,[r]:[...t[r]??[],...e]}))}if(r!==`manager`&&s.protected_action){let e=uS(r,n,s.protected_action);if(e)return e}}catch(e){if(Oe.current.delete(r)){let e={agentLabel:a.label,lines:[],pending:!1,sourceLabel:`${a.label} 会话`,text:`已中断。你可以在当前会话继续发送消息。`};l===null?Be(r,e):Ve(r,l,e);return}let t=e instanceof Th?e.payload:null;t&&dh(t)&&Te.current.delete(c),t?.error_code===`resume_failed`&&(Te.current.delete(c),Ee.current.add(c),ze(r,{agentId:a.agentId,resumable:!1,sessionId:he[r]?.sessionId??`resume-failed`,status:`resume_failed`}));let n=t?.gate,i=n&&typeof n==`object`?String(n.summary??``):``,o={agentLabel:a.label,lines:i?[i]:[],pending:!1,reconnect:t?.reconnectable===!0,sourceLabel:`LoopX Chat 本地后端`,text:t?.error_code===`resume_failed`?`原 ${a.label} 会话无法恢复。本地历史已经保留,请在运行详情里选择“重试恢复”或“开始新 Session”。`:e instanceof Error?e.message:`${a.label} 会话暂时不可用。`};l===null?Be(r,o):Ve(r,l,o)}finally{R.current.delete(r),De.current.delete(r);let e=Te.current.get(c);e&&ze(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`ready`}),me(e=>e===r?null:e)}}async function Ue(e){let t=e?.goalId??k,n=he[t],r=e?.agentId??n?.agentId??F.agentId,i=`${t}:${r}`,a=e?.sessionId??n?.sessionId??Te.current.get(i),o=e?.turnId??n?.turnId??R.current.get(t);if(!(!a||!o))try{Oe.current.add(t),await qh(a,o),De.current.get(t)?.abort()}catch(e){throw Oe.current.delete(t),e}finally{R.current.delete(t),ze(t,{agentId:r,resumable:!0,sessionId:a,status:`ready`}),De.current.delete(t),me(e=>e===t?null:e)}}async function We(e){let t=e.goalId,n=`${t}:${e.agentId}`,r=e.sessionId??he[t]?.sessionId??Te.current.get(n);if(r)try{let i=await Qh(r);Te.current.set(n,r),Ee.current.delete(n),ze(t,{agentId:e.agentId,resumable:i.session.resumable,sessionId:r,status:i.session.status})}catch{ze(t,{agentId:e.agentId,resumable:!1,sessionId:r,status:`resume_failed`})}}function Ge(e){let t=`${e.goalId}:${e.agentId}`;Te.current.delete(t),Ee.current.add(t),ze(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:`new-session-pending`,status:`ready`})}async function Ke(e){let t=`${e.goalId}:${e.agentId}`,n=e.sessionId??he[e.goalId]?.sessionId??Te.current.get(t);n&&n!==`new-session-pending`&&await Zh(n),Te.current.delete(t),Ee.current.add(t),ze(e.goalId,null)}function qe(e){j.some(t=>t.agentId===e&&t.available)&&(P(t=>({...t,[k]:e})),ie(!1))}function Je(){i(``),oe(`chat`)}function Ye(e){i(e),oe(`chat`)}C&&DS[C.state],C&&(`${F.label}${C.state}`,V.length>0&&`${Le}`,Fe.length>0&&`${Fe.length}`),C?.state===`需修复`||!C&&!c.ok?(C&&MS(C.agentId),C?.nextSentence,C?.agentSentence):C?.state===`等你`?(C.needsYouBlocking,C.needsYouBlocking,C.needsYou??C.nextSentence,C.needsYou):(C&&MS(C.agentId),C?.nextSentence);let Xe=[...!C&&he.manager?.status===`resume_failed`?[{id:`run:manager:resume-failed`,kind:`run`,run:{agentId:he.manager.agentId,agentLabel:MS(he.manager.agentId),canInterrupt:!1,completedSteps:0,goalId:`manager`,goalTitle:`LoopX 管家`,latestActivity:`本地聊天记录已保留,点我查看恢复方式。`,resumable:!1,runId:`manager:resume-failed`,sessionId:he.manager.sessionId,sessionStatus:`resume_failed`,status:`failed`,title:`上次会话需要恢复`,totalSteps:1,outputs:[]}}]:[],...C?_e.map(e=>{let t=e.channel_id?.startsWith(`task.`)?e.channel_id.slice(5):void 0,n=C.agentTodos.find(e=>e.todoId===t),r=!!e.active_turn_id,i=xe[e.session_id],a=i?.messages.some(e=>AS(e.role,e.text))===!0;return{id:`run:task:${e.session_id}`,kind:`run`,run:{agentId:e.agent_id,agentLabel:MS(e.agent_id),canInterrupt:r,completedSteps:n?.done||a?1:0,goalId:C.goalId,goalTitle:C.title,latestActivity:r?`Agent 正在执行,可进入 Session 查看过程或发送纠偏。`:a?`Agent 已返回结果,点击查看结果与完整运行记录。`:`执行 Session 已保留,可继续纠偏或恢复。`,resumable:e.resumable,runId:e.session_id,sessionId:e.session_id,sessionMessages:i?.messages.map(e=>({createdAt:e.created_at,messageId:e.message_id,role:e.role===`user`?`user`:AS(e.role,e.text)?`assistant`:`error`,text:e.role===`user`?e.text:kS(e.text)})),sessionStatus:a?`completed`:e.status,status:n?.done||a?`completed`:r?`running`:e.status===`resume_failed`?`failed`:`waiting`,title:n?.text??`Agent 执行任务`,todoId:t,totalSteps:1,turnId:e.active_turn_id??void 0}}}):[],...C?[{id:`run:${C.goalId}`,kind:`run`,run:{agentId:he[C.goalId]?.agentId??C.agentId,agentLabel:MS(he[C.goalId]?.agentId??C.agentId),canInterrupt:!!he[C.goalId]?.turnId,completedSteps:C.agentTodos.filter(e=>e.done).length,goalId:C.goalId,goalTitle:C.title,latestActivity:C.agentSentence,resumable:he[C.goalId]?.resumable??!0,runId:`goal:${C.goalId}`,sessionId:he[C.goalId]?.sessionId,sessionStatus:he[C.goalId]?.status,status:he[C.goalId]?.turnId?`running`:C.state===`需修复`?`failed`:`waiting`,title:C.nextSentence,totalSteps:C.agentTodos.length||1,turnId:he[C.goalId]?.turnId,outputs:C.runEvidence?[{createdAt:C.runEvidence.generatedAt,kind:`evidence`,outputId:`${C.goalId}:latest-evidence`,title:C.runEvidence.label}]:[]}}]:[],...Pe.map(e=>({id:`message:${e.id}`,kind:`message`,message:{agentLabel:e.agentLabel,attachments:e.attachments,id:String(e.id),pending:e.pending,role:e.role,text:e.text||(e.pending?`Agent 正在处理…`:e.lines.join(` +`))}})),...(C?[C]:S.goals).flatMap(e=>e.runEvidence?[{id:`output:${e.goalId}:${e.runEvidence.generatedAt||`latest`}`,kind:`output`,output:{agentLabel:MS(e.agentId),createdAt:e.runEvidence.generatedAt,goalId:e.goalId,goalTitle:e.title,kind:`evidence`,outputId:`${e.goalId}:latest-evidence`,runId:e.runEvidence.runId??void 0,safePreview:e.runEvidence.safePreview,summary:e.runEvidence.summary,title:e.runEvidence.label,todoId:e.runEvidence.todoId??void 0}}]:[]),...C&&T?[{id:`output:${C.goalId}:report:${T.publication.publication_id}`,kind:`output`,output:{agentId:T.agent_id,agentLabel:MS(T.agent_id),createdAt:T.publication.delivered_at,goalId:C.goalId,goalTitle:C.title,kind:`report`,outputId:T.publication.publication_id,report:{addedCount:T.delta.added_count,changedCount:T.delta.changed_count,deliveredAt:T.publication.delivered_at,generationId:T.generation_id,items:T.delta.items.map(e=>({changeKind:e.change_kind,previousStatus:e.previous_status,sourceRef:e.source_ref,status:e.status,summary:e.summary,title:e.title})),periodEndAt:T.period_window.end_at,periodStartAt:T.period_window.start_at,predecessorPublicationId:T.publication.predecessor_publication_id,publicationId:T.publication.publication_id},safePreview:T.delta.items.map(e=>`${e.change_kind===`added`?`+`:`~`} ${e.title}\n${e.summary}`).join(` + +`),summary:T.summary,title:T.title}}]:[]],Ze=f.connectionState===`connected`,Qe=new Map(S.goals.map(e=>[e.goalId,e.title])),$e=e=>Wd(e,f.activeSource.statusUrl,Ze&&!l?.errors[e.goalId],Qe.get(e.goalId)),et={...my(S),userTodos:S.userTodos.map($e),attentionHistory:(S.attentionHistory??S.userTodos).map($e),periodicReports:{error:D,loading:ee},timeline:Xe};return(0,B.jsxs)(`div`,{className:p===`dark`?`dark`:``,"data-testid":`personal-goal-home`,children:[ye?(0,B.jsx)(`p`,{role:`status`,className:`m-0 bg-amber-50 px-4 py-2 text-sm text-amber-900`,children:_(ye===`partial`?`runs.discoveryPartial`:`runs.discoveryOffline`)}):null,(0,B.jsx)(Hx,{agents:j.map(e=>({adapterKind:e.adapterKind,agentId:e.agentId,available:e.available,capability:e.capability,interrupt:e.interrupt,label:e.label,location:e.location,resume:e.resume,source:e.source,streaming:e.streaming,toolCalls:e.toolCalls,trustScope:e.trustScope,workspaceCompatibility:e.available?`当前 Goal 写入前验证`:`不可用,需先修复 Endpoint`})),callbacks:{onApplyAttention:e=>Ye(e.goalId),onCorrectRun:async(e,t)=>{if(!e.sessionId)throw Error(`这个 Run 还没有可纠偏的执行 Session。`);let n=await Nh((await Ah({actionKind:`run.correct`,context:{kind:`run`,goal_id:e.goalId,todo_id:e.todoId},idempotencyKey:`workspace-run-correct-${e.sessionId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,message:t,session_id:e.sessionId},summary:`纠偏执行任务:${e.title}`})).proposal_id),r=typeof n.turn?.turn_id==`string`?n.turn.turn_id:void 0;if(ze(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:e.sessionId,status:r?`running`:`ready`,turnId:r}),r){R.current.set(e.goalId,r);let t=new AbortController;De.current.set(e.goalId,t);let n=``,i=Be(e.goalId,{activity:[`正在把纠偏送入原执行 Session`],agentLabel:e.agentLabel,lines:[],pending:!0,sourceLabel:`${e.agentLabel} · 执行 Session`,text:``});try{let a=await Xh(e.sessionId,r,{signal:t.signal,onDelta:t=>{n+=t,Ve(e.goalId,i,{text:n})}});Ve(e.goalId,i,{activity:[],pending:!1,text:kS(a.response.message||n.trim())||`${e.agentLabel} 已完成纠偏。`})}catch(t){let n=Oe.current.delete(e.goalId);Ve(e.goalId,i,{activity:[],pending:!1,text:n?`已中断。你可以在当前会话继续发送消息。`:t instanceof Error?t.message:`纠偏回合失败。`})}finally{R.current.delete(e.goalId),De.current.delete(e.goalId),ze(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:e.sessionId,status:`ready`})}}},onCloseRunSession:Ke,onInterruptRun:async e=>Ue(e),onOpenGoal:Ye,onOpenRunSession:async e=>{if(!e.sessionId)return;let t=e.sessionId,n=await Bh(t);Se(e=>({...e,[t]:n})),Ye(e.goalId),ue(t=>({...t,[e.goalId]:n.messages.map(t=>({agentLabel:t.role===`user`?void 0:e.agentLabel,attachments:wS(t.attachments),id:Ce.current++,lines:[],role:t.role===`user`?`user`:`assistant`,sourceLabel:t.role===`user`?void 0:`${e.agentLabel} · 执行 Session`,text:t.role===`user`?t.text:kS(t.text)}))})),ze(e.goalId,{agentId:e.agentId,resumable:n.session.resumable,sessionId:t,status:n.session.active_turn_id?`running`:n.session.status,turnId:n.session.active_turn_id??void 0})},onOpenOutput:e=>Ye(e.goalId),...b?{onPreviewGoalSubagentConfiguration:async e=>{let t=await tg(e);return{changed:t.changed,configuration:{allowedDomains:t.after.orchestration.allowed_domains,enabled:t.feature_summary.multi_subagent===`enabled`,maxChildren:t.after.orchestration.max_children,modelConfig:t.after.orchestration.model_config},previewId:t.preview_id}},onApplyGoalSubagentConfiguration:async({previewId:e,...t})=>{let n=await ng(t,e);return{allowedDomains:n.after.orchestration.allowed_domains,enabled:n.feature_summary.multi_subagent===`enabled`,maxChildren:n.after.orchestration.max_children,modelConfig:n.after.orchestration.model_config}}}:{},...g?{onExecuteGoalLifecycle:async({goalId:e,operation:t,reason:n})=>{let r=await vb(g,e,t,n);return{activationState:r.activation_state,projectionVerified:r.projection_verified}}}:{},onGoalActivationStateChange:n,onGoalDeleted:r,onReconcileStatus:a,onRetryGoalArchive:s,onExportOutput:async e=>{let t=[`# ${e.title}`,``,e.summary??``,``,e.safePreview??`此产出没有可用的公开安全预览。`,``,`Goal: ${e.goalId}`,`Todo: ${e.todoId??`unlinked`}`,`Run: ${e.runId??`unlinked`}`].join(` +`),n=URL.createObjectURL(new Blob([t],{type:`text/markdown;charset=utf-8`})),r=document.createElement(`a`);r.href=n,r.download=`${e.outputId.replace(/[^a-z0-9._-]+/gi,`-`)}.md`,r.click(),URL.revokeObjectURL(n)},onRefresh:o,onRetryResumeRun:We,onSelectAgent:qe,onSelectGoal:e=>e?Ye(e):Je(),onSendMessage:async(e,t,n,r)=>He(e,{agentId:t,goalId:n,attachments:r}),onStartNewRunSession:Ge},goalArchiveLoadState:e,model:et,readOnly:h,selectedAgentId:F.agentId,selectedGoalId:C?.goalId??null,statusSourceControl:f})]})}function oC({error:e,isLoading:t,onRetry:n,requestedUrl:r,theme:i,toggleTheme:a}){let o=!!(e&&/failed to fetch|networkerror|load failed/i.test(e)&&r.includes(`status.json`));return(0,B.jsx)(`div`,{className:i===`dark`?`dark`:``,children:(0,B.jsxs)(`main`,{className:`min-h-screen bg-[#f6f7f9] text-slate-950 dark:bg-[#09090b] dark:text-zinc-50`,children:[(0,B.jsxs)(`header`,{className:`flex min-h-16 flex-wrap items-center justify-between gap-3 border-b border-slate-200 bg-white px-4 py-3 dark:border-zinc-800 dark:bg-zinc-950 sm:px-6`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`h1`,{className:`text-xl font-semibold`,children:`LoopX Workspace`}),(0,B.jsx)(`p`,{className:`mt-1 break-all text-sm text-slate-500 dark:text-zinc-400`,children:`Personal Workspace`})]}),(0,B.jsx)(ry,{"aria-label":`切换主题`,onClick:a,size:`icon`,variant:`secondary`,children:i===`dark`?(0,B.jsx)(Jm,{className:`h-4 w-4`}):(0,B.jsx)(km,{className:`h-4 w-4`})})]}),(0,B.jsxs)(`div`,{className:`grid min-h-[calc(100vh-80px)] sm:grid-cols-[240px_1fr]`,children:[(0,B.jsxs)(`aside`,{className:`hidden border-r border-slate-200 p-6 dark:border-zinc-800 sm:block`,"aria-label":`Workspace`,children:[(0,B.jsx)(`strong`,{children:`LoopX`}),(0,B.jsx)(`p`,{className:`mt-6 text-sm`,children:`Workspace`}),(0,B.jsx)(`p`,{className:`mt-8 text-xs text-slate-500`,children:`Goals`}),[1,2,3].map(e=>(0,B.jsx)(`div`,{className:`mt-4 h-8 rounded bg-slate-100 dark:bg-zinc-900`},e))]}),(0,B.jsx)(`div`,{className:`p-4 sm:p-8`,children:(0,B.jsx)(iy,{"data-testid":`initial-status-state`,children:(0,B.jsx)(ay,{className:`flex min-h-64 items-center justify-center p-6`,children:(0,B.jsxs)(`div`,{className:`max-w-xl text-center`,children:[e?(0,B.jsx)(im,{className:`mx-auto h-6 w-6 text-rose-600 dark:text-rose-300`}):(0,B.jsx)(Im,{className:`mx-auto h-6 w-6 animate-spin text-slate-500 dark:text-zinc-400`}),(0,B.jsx)(`p`,{className:`mt-3 text-sm font-medium`,children:e?`无法加载实时状态`:`正在加载实时状态`}),e?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`mt-2 break-words text-sm leading-6 text-slate-500 dark:text-zinc-400`,children:o?`本地状态服务暂时未连接。升级或启动期间可能短暂断开,请重试;仍失败时重新打开 LoopX App,或运行 loopx doctor。`:e}),o?(0,B.jsx)(`p`,{className:`mt-2 text-xs leading-5 text-slate-400 dark:text-zinc-500`,children:`重新加载不会执行任务,也不会改变 Goal 配置。`}):null,(0,B.jsx)(`div`,{className:`mt-4 flex flex-wrap justify-center gap-2`,children:(0,B.jsxs)(ry,{disabled:t,onClick:n,children:[(0,B.jsx)(Im,{className:`h-4 w-4`}),`重试`]})})]}):(0,B.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-500 dark:text-zinc-400`,role:`status`,children:`正在连接 Workspace,Goal 列表将先出现,详细状态会逐个补齐。 / Connecting to your Workspace. Goals load independently.`})]})})})})]})]})})}function sC(){let e=iw.useSearch(),t=iw.useNavigate(),[n,r]=(0,z.useState)(`light`),[i,a]=(0,z.useState)(null),o=(0,z.useRef)(null),s=(0,z.useRef)(e.goalId);s.current=e.goalId;let[c,l]=(0,z.useState)(Op),[u,d]=(0,z.useState)({kind:`example`,label:`bundled example`}),[f,p]=(0,z.useState)(()=>tS(window.localStorage,window.location.href)),m=(0,z.useRef)(f);m.current=f;let[h,g]=(0,z.useState)(e.statusUrl),[_,v]=(0,z.useState)(null),[y,b]=(0,z.useState)(!1),[x,S]=(0,z.useState)({error:null,phase:`idle`}),[C,w]=(0,z.useState)(e.statusUrl.trim()||null),[T,E]=(0,z.useState)(!1),D=(0,z.useRef)(null),O=(0,z.useRef)(Xg(e.statusUrl.trim()||null)),ee=!T&&u.kind===`example`?e.statusUrl.trim():``,te=C??ee,ne=u.kind===`url`?u.label:dS,k=!!(_&&C),A=cS(f,C,ne,window.location.href),j=u.kind===`example`&&!T,M=c.attention_queue,N=c.run_history,P=(0,z.useMemo)(()=>mS(N.goals,M.items),[N.goals,M.items]);function F(e,t,n=0){S({error:null,phase:`loading`}),fS(ah(e,`stopped`,window.location.href)).then(r=>{if(!e_(O.current,t))return;let i=r.goal_projection?.registry_revision??null,a=t.registryRevision!==null&&t.registryRevision!==void 0&&i!==null&&t.registryRevision!==i;if(l(e=>C_(e,r)),a&&n<1){I(e,{background:!0,resyncAttempt:n+1});return}S(a?{error:`Goal 状态在加载历史时发生变化,请重试。`,phase:`error`}:{error:null,phase:`ready`})}).catch(e=>{e_(O.current,t)&&S({error:Dp(e),phase:`error`})})}function re(){let e=u.kind===`url`?u.label:h||dS,t=Qg(O.current,e,{background:!0});if(i){I(e);return}t&&F(e,t)}async function ie(e,n,r){if(r.background)return l(e=>C_(e,n)),!0;let i={kind:`url`,label:e};return O.current.loadedUrl=e,l(n),d(i),g(e),await t({search:t=>({...t,statusUrl:e})}),$g(O.current,r)?(O.current.requestedUrl=null,w(null),!0):!1}async function I(e,t={}){let n=e.trim(),r=t.background===!0;if(!n){r||v(`状态地址不能为空`);return}let c=Qg(O.current,n,{background:r,selectionRevision:t.selectionRevision});if(!c)return;o.current?.abort();let d=new AbortController;o.current=d,r||(D.current=null,E(!1),w(n),b(!0),v(null),S({error:null,phase:`idle`}));try{let e=await jp(n,window.location.href).catch(()=>null);if(!e_(O.current,c))return;if(e){let o=t.retryOnly&&u.kind===`url`&&u.label===n&&i?.directory.registry_revision===e.registry_revision?i.snapshots:{};a({directory:e,snapshots:o,errors:{}});let f={...e,goals:e.goals.filter(e=>!o[e.id])},p=!1,m=Mp(e);if(r)l(m);else if(!await ie(n,m,c))return;if(S({error:null,phase:`loading`}),await Np(n,window.location.href,f,(e,t,n)=>{n===`revision`&&(p=!0),a(r=>r&&{...r,snapshots:t?{...r.snapshots,[e]:t}:r.snapshots,errors:n?{...r.errors,[e]:n}:r.errors})},()=>e_(O.current,c),()=>s.current,d.signal),p&&(t.resyncAttempt??0)<1&&e_(O.current,c)){await I(n,{resyncAttempt:1});return}e_(O.current,c)&&S({error:null,phase:`ready`});return}let o=await fS(ah(n,`active`,window.location.href));if(!e_(O.current,c)||(a(null),c.registryRevision=o.goal_projection?.registry_revision??null,!await ie(n,o,c)))return;if(o.goal_projection?.scope!==`active`||o.goal_projection.complete){S({error:null,phase:`ready`});return}F(n,c,t.resyncAttempt??0)}catch(e){if(!$g(O.current,c))return;r||v(Dp(e))}finally{!r&&$g(O.current,c)&&b(!1)}}function ae(e,t={}){o.current?.abort();let n=Zg(O.current,e.statusUrl);D.current=null,E(!1),w(e.statusUrl),b(!0),v(null),(async()=>{if(t.ensureTunnel&&e.kind===`ssh_tunnel`){let t=new URL(e.statusUrl,window.location.href).port;if(t)try{await _b(e.label,t)}catch{}}O.current.selectionRevision===n&&await I(e.statusUrl,{selectionRevision:n})})()}function L(e){m.current=e,p(e);try{nS(window.localStorage,e)}catch{}}let oe={activeSource:A,connectionState:y?`loading`:k?`error`:`connected`,errorMessage:k?`未切换到 ${C??`所选来源`}:${_}`:null,onAdd:e=>{let t=iS(f,e,window.location.href);return`error`in t?{error:t.error}:(L(t.catalog),ae(t.source,{ensureTunnel:e.ensureTunnel}),{})},onConfiguredHostsLoaded:e=>{let t=m.current,n=rS(t,e);n!==t&&L(n)},onRemove:e=>{L(aS(f,e)),A.id===e&&ae(Xx)},onSelect:e=>{let t=f.sources.find(t=>t.id===e);t&&ae(t,{ensureTunnel:t.kind===`ssh_tunnel`})},sources:A.id===`temporary`?[...f.sources,A]:f.sources};(0,z.useEffect)(()=>{let t=e.statusUrl.trim();if(t){if(D.current===t||C&&C!==t)return;(u.kind!==`url`||u.label!==t)&&I(t);return}D.current=null,!T&&(C||u.kind===`example`&&I(dS))},[T,C,e.statusUrl,u.kind,u.label]),(0,z.useEffect)(()=>{if(e.statusUrl&&u.kind===`example`)return;let n=new Set(P.map(e=>e.goal.id));if(P.length===0){e.goalId&&t({search:e=>({...e,goalId:``})});return}e.goalId&&!n.has(e.goalId)&&x.phase!==`loading`&&t({search:e=>({...e,goalId:``})})},[x.phase,P,t,e.goalId,e.statusUrl,u.kind]),(0,z.useEffect)(()=>{if(!i||y||!e.goalId||u.kind!==`url`)return;let t=i.directory.goals.find(t=>t.id===e.goalId);t?.activation_state===`stopped`&&!i.snapshots[t.id]&&!i.errors[t.id]&&I(u.label,{retryOnly:!0})},[e.goalId,y,i,u]);function se(e){t({search:t=>({...t,goalId:e})})}return j?(0,B.jsx)(oC,{error:_,isLoading:y,onRetry:()=>void I(te||dS),requestedUrl:te||dS,theme:n,toggleTheme:()=>r(n===`dark`?`light`:`dark`)}):(0,B.jsx)(aC,{goalArchiveLoadState:x,isLoading:y,onGoalActivationStateChange:(e,t)=>{O.current.projectionRevision+=1,l(n=>wp(n,e,t)),a(n=>n&&{...n,snapshots:Object.fromEntries(Object.entries(n.snapshots).map(([n,r])=>[n,wp(r,e,t)]))})},onGoalDeleted:e=>{O.current.projectionRevision+=1,l(t=>Tp(t,e)),a(t=>t&&{...t,snapshots:Object.fromEntries(Object.entries(t.snapshots).filter(([t])=>t!==e))})},onSelectGoal:se,onReconcileStatus:()=>I(u.kind===`url`?u.label:h||dS,{background:!0}),onRetryGoalArchive:re,onRefresh:()=>I(u.kind===`url`?u.label:h||dS,{retryOnly:!!(i&&Object.keys(i.errors).length)}),payload:c,progress:i,rows:P,selectedGoalId:e.goalId,statusSourceControl:oe,theme:n,toggleTheme:()=>r(n===`dark`?`light`:`dark`)})}var cC=O_(`inline-flex items-center gap-1 rounded-md border px-2 py-0.5 text-xs font-medium`,{variants:{variant:{neutral:`border-slate-200 bg-white text-slate-700 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-300`,success:`border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-200`,warning:`border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-200`,info:`border-sky-200 bg-sky-50 text-sky-800 dark:border-sky-900 dark:bg-sky-950 dark:text-sky-200`,danger:`border-rose-200 bg-rose-50 text-rose-800 dark:border-rose-900 dark:bg-rose-950 dark:text-rose-200`}},defaultVariants:{variant:`neutral`}});function lC({className:e,variant:t,...n}){return(0,B.jsx)(`span`,{className:ty(cC({variant:t}),e),...n})}var uC=[{label:`status payload`,source:`apps/presentation/dashboard/src/data/status.ts`,detail:`status_contract, attention_queue, local_dashboard_api, run_history`},{label:`channel projection`,source:`apps/presentation/dashboard/src/data/goal-channel-frontstage.ts`,detail:`decision_frame, todos, gates, leases, artifacts, truth_contract`},{label:`public showcase catalog`,source:`docs/showcases/showcase-catalog.json`,detail:`case metadata, visual hints, evidence boundaries, story beats`},{label:`route smoke`,source:`apps/presentation/dashboard/smoke/frontstage-route-smoke.ts`,detail:`static route contract, source guards, component expectations`}],dC=[{axis:`schema`,current:`goal_channel_projection_v0`,proposed:`new optional projection field`,gate:`parser default plus route smoke assertion`},{axis:`truth`,current:`event ledger and active state remain source of truth`,proposed:`derived UI state only`,gate:`truth_contract must stay read-only`},{axis:`privacy`,current:`compact source refs and warnings`,proposed:`public-safe fixture field`,gate:`loopx check and browser fake-private fixture`},{axis:`interaction`,current:`render, filter, select, inspect`,proposed:`no browser write by default`,gate:`write affordance requires explicit loopback capability`}],fC=[{title:`Fixture sources`,body:`Use examples/status.example.json, browser-smoke fixtures, and docs/showcases/showcase-catalog.json.`},{title:`Required proof`,body:`Every projection addition needs parser coverage, route smoke assertions, and one browser or bundle check when UI output changes.`},{title:`Never include`,body:`Raw task text, trajectories, transcripts, local paths, private registry state, credentials, or internal document links.`}],pC=[`npm --prefix apps/presentation/dashboard run smoke:frontstage-route`,`npm --prefix apps/presentation/dashboard run smoke:frontstage-browser`,`npm --prefix apps/presentation/dashboard run smoke:frontstage-share-bundle`,`npm --prefix apps/presentation/dashboard run build`,`loopx check --scan-path apps/presentation/dashboard --scan-path docs/status-data-contract.md`],mC=[{name:`Projection lane`,badges:[`read-only`,`schema v0`],body:`Summarizes one compact projection lane without mutating the underlying LoopX state.`},{name:`Capability badge`,badges:[`loopback`,`dry-run`],body:`Shows an advertised local capability only after the status feed declares it.`},{name:`Boundary warning`,badges:[`public-safe`,`omitted`],body:`Names omitted private material and points contributors back to compact source references.`}];function hC({children:e,icon:t,title:n}){return(0,B.jsxs)(`section`,{className:`rounded-lg border border-slate-200 bg-white shadow-sm`,children:[(0,B.jsx)(`div`,{className:`flex items-center justify-between gap-3 border-b border-slate-200 px-4 py-3`,children:(0,B.jsxs)(`h2`,{className:`flex items-center gap-2 text-sm font-semibold text-slate-950`,children:[(0,B.jsx)(t,{className:`h-4 w-4 text-slate-500`}),n]})}),e]})}function gC(){return(0,B.jsx)(hC,{icon:Qp,title:`Status Contract Explorer`,children:(0,B.jsx)(`div`,{className:`grid gap-3 p-4 lg:grid-cols-2`,"data-testid":`developer-contract-explorer`,children:uC.map(e=>(0,B.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-3`,children:[(0,B.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,B.jsx)(lC,{variant:`info`,children:e.label}),(0,B.jsx)(lC,{variant:`neutral`,children:`public contract`})]}),(0,B.jsx)(`div`,{className:`mt-2 break-words font-mono text-xs text-slate-700`,children:e.source}),(0,B.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:e.detail})]},e.label))})})}function _C(){return(0,B.jsx)(hC,{icon:vm,title:`Projection Diffing`,children:(0,B.jsx)(`div`,{className:`overflow-x-auto`,"data-testid":`developer-projection-diffing`,children:(0,B.jsxs)(`table`,{className:`min-w-full border-separate border-spacing-0 text-left text-sm`,children:[(0,B.jsx)(`thead`,{children:(0,B.jsxs)(`tr`,{className:`bg-slate-50 text-xs uppercase tracking-normal text-slate-500`,children:[(0,B.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Axis`}),(0,B.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Current`}),(0,B.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Proposed`}),(0,B.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Gate`})]})}),(0,B.jsx)(`tbody`,{children:dC.map(e=>(0,B.jsxs)(`tr`,{className:`align-top`,children:[(0,B.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 font-semibold text-slate-950`,children:e.axis}),(0,B.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 text-slate-600`,children:e.current}),(0,B.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 text-slate-600`,children:e.proposed}),(0,B.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 text-slate-600`,children:e.gate})]},e.axis))})]})})})}function vC(){return(0,B.jsx)(hC,{icon:mm,title:`Fixture Generation`,children:(0,B.jsx)(`div`,{className:`grid gap-3 p-4 md:grid-cols-3`,"data-testid":`developer-fixture-generation`,children:fC.map(e=>(0,B.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-3`,children:[(0,B.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:e.title}),(0,B.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:e.body})]},e.title))})})}function yC(){return(0,B.jsx)(hC,{icon:om,title:`Smoke Checklist`,children:(0,B.jsx)(`div`,{className:`space-y-2 p-4`,"data-testid":`developer-smoke-checklist`,children:pC.map(e=>(0,B.jsxs)(`div`,{className:`flex items-start gap-3 rounded-md border border-slate-200 bg-slate-50 px-3 py-2`,children:[(0,B.jsx)(Yp,{className:`mt-0.5 h-4 w-4 shrink-0 text-emerald-600`}),(0,B.jsx)(`code`,{className:`break-all text-xs font-semibold leading-5 text-slate-700`,children:e})]},e))})})}function bC(){return(0,B.jsx)(hC,{icon:sm,title:`Component Examples`,children:(0,B.jsx)(`div`,{className:`grid gap-3 p-4 lg:grid-cols-3`,"data-testid":`developer-component-examples`,children:mC.map(e=>(0,B.jsxs)(`article`,{className:`rounded-md border border-slate-200 bg-slate-50 p-3`,children:[(0,B.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:e.badges.map(e=>(0,B.jsx)(lC,{variant:e===`read-only`||e===`public-safe`?`success`:`neutral`,children:e},e))}),(0,B.jsx)(`h3`,{className:`mt-3 text-sm font-semibold leading-6 text-slate-950`,children:e.name}),(0,B.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:e.body})]},e.name))})})}function xC(){return(0,B.jsx)(`main`,{className:`min-h-screen bg-[#f7f7f4] px-4 py-4 text-slate-950 sm:px-5`,"data-testid":`frontstage-developer-cockpit`,children:(0,B.jsxs)(`div`,{className:`mx-auto grid max-w-[1500px] gap-4 xl:grid-cols-[260px_minmax(0,1fr)]`,children:[(0,B.jsxs)(`aside`,{className:`rounded-lg border border-slate-200 bg-white p-4 shadow-sm xl:sticky xl:top-4 xl:self-start`,children:[(0,B.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,B.jsx)(`div`,{className:`flex h-9 w-9 items-center justify-center rounded-md border border-slate-200 bg-slate-950 text-white`,children:(0,B.jsx)(Ym,{className:`h-4 w-4`})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`div`,{className:`text-sm font-semibold`,children:`Developer Cockpit`}),(0,B.jsx)(`div`,{className:`text-xs text-slate-500`,children:`Projection extension`})]})]}),(0,B.jsxs)(`div`,{className:`mt-4 grid gap-2`,children:[(0,B.jsxs)(`a`,{className:`flex items-center gap-2 rounded-md border border-slate-200 px-3 py-2 text-sm font-medium`,href:`https://huangruiteng.github.io/loopx/`,children:[(0,B.jsx)(xm,{className:`h-4 w-4`}),`LoopX home`]}),(0,B.jsxs)(`a`,{className:`flex items-center gap-2 rounded-md border border-slate-200 px-3 py-2 text-sm font-medium`,href:`https://huangruiteng.github.io/loopx/docs/showcases/index.en.html`,children:[(0,B.jsx)(fm,{className:`h-4 w-4`}),`Public cases`]}),(0,B.jsxs)(`a`,{className:`flex items-center gap-2 rounded-md bg-slate-950 px-3 py-2 text-sm font-medium text-white`,href:`/chat/developers/projections/`,children:[(0,B.jsx)(sm,{className:`h-4 w-4`}),`Developer cockpit`]})]}),(0,B.jsxs)(`div`,{className:`mt-5 space-y-2 rounded-md border border-emerald-200 bg-emerald-50 p-3 text-xs leading-5 text-emerald-950`,children:[(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,B.jsx)(lC,{variant:`success`,children:`read-only`}),(0,B.jsx)(lC,{variant:`neutral`,children:`public fixtures`})]}),(0,B.jsx)(`p`,{children:`This route uses static public contracts only; live status feeds, registry files, and browser write APIs stay outside the cockpit.`})]})]}),(0,B.jsxs)(`section`,{className:`space-y-4`,children:[(0,B.jsx)(`div`,{className:`rounded-lg border border-slate-200 bg-white px-5 py-5 shadow-sm`,children:(0,B.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-4`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,B.jsx)(lC,{variant:`info`,children:`developers/projections`}),(0,B.jsx)(lC,{variant:`success`,children:`public-safe`}),(0,B.jsx)(lC,{variant:`neutral`,children:`no browser writes`})]}),(0,B.jsx)(`h1`,{className:`mt-3 text-3xl font-semibold tracking-normal text-slate-950`,children:`LoopX Projection Developer Cockpit`}),(0,B.jsx)(`p`,{className:`mt-2 max-w-3xl text-sm leading-6 text-slate-600`,children:`A read-only contributor workbench for adding dashboard/frontstage projections without reverse-engineering the large operator page.`})]}),(0,B.jsxs)(`div`,{className:`grid min-w-[260px] gap-2 text-sm`,children:[(0,B.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-2`,children:[(0,B.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-normal text-slate-500`,children:`Source of truth`}),(0,B.jsx)(`div`,{className:`mt-1 font-semibold text-slate-950`,children:`status contract + compact fixtures`})]}),(0,B.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-2`,children:[(0,B.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-normal text-slate-500`,children:`Boundary`}),(0,B.jsx)(`div`,{className:`mt-1 font-semibold text-slate-950`,children:`read-only extension surface`})]})]})]})}),(0,B.jsxs)(`div`,{className:`grid gap-4 xl:grid-cols-2`,children:[(0,B.jsx)(gC,{}),(0,B.jsx)(_C,{})]}),(0,B.jsxs)(`div`,{className:`grid gap-4 xl:grid-cols-[minmax(0,1fr)_420px]`,children:[(0,B.jsx)(vC,{}),(0,B.jsx)(yC,{})]}),(0,B.jsx)(bC,{}),(0,B.jsx)(hC,{icon:Wm,title:`Extension Boundary`,children:(0,B.jsxs)(`div`,{className:`grid gap-3 p-4 md:grid-cols-3`,"data-testid":`developer-extension-boundary`,children:[(0,B.jsxs)(`div`,{className:`rounded-md border border-emerald-200 bg-emerald-50 px-3 py-3`,children:[(0,B.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:`Allowed`}),(0,B.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:`Versioned parser defaults, public fixtures, read-only route panels, and focused smoke assertions.`})]}),(0,B.jsxs)(`div`,{className:`rounded-md border border-amber-200 bg-amber-50 px-3 py-3`,children:[(0,B.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:`Review`}),(0,B.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:`New dashboard dependencies, status contract fields, loopback capability display, and browser-visible workflows.`})]}),(0,B.jsxs)(`div`,{className:`rounded-md border border-rose-200 bg-rose-50 px-3 py-3`,children:[(0,B.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:`Stop`}),(0,B.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:`Credentials, private registry material, raw logs, transcripts, production actions, or default browser write authority.`})]})]})})]})]})})}var SC=J({value:G().finite(),total:G().finite().positive().optional(),unit:W().optional(),higher_is_better:K()}).passthrough(),CC=gd(W(),G().finite()).default({}),wC=J({outcome_status:W().optional(),failure_class:W(),causal_summary:W(),expectedness:W(),implication:W(),next_probe:W(),confidence:W(),evidence_refs:q(W()).optional()}).passthrough(),TC=J({arm_id:W(),selected_run_id:W().nullable(),score_countable:K(),metrics:gd(W(),SC),effort:CC,insight:wC.nullable().optional()}),EC=J({run_id:W(),case_id:W(),arm_id:W(),arm_role:W(),status:W(),protocol_id:W(),runner_revision:W().optional(),observed_at:W(),metrics:gd(W(),SC),countability:J({integrity_qualified:K(),official_result_present:K(),score_countable:K()}).passthrough(),treatment_fidelity:W(),effort:CC,redacted_insight:wC.nullable().optional(),upload_provenance:J({producer_id:W(),producer_version:W(),observed_at:W(),source_revision:W()}).passthrough()}).passthrough(),DC=J({case_denominator:G().int().nonnegative(),value_sum:G().finite(),value_mean:G().finite().nullable(),value_median:G().finite().nullable(),value_min:G().finite().nullable(),value_max:G().finite().nullable(),case_macro_rate:G().finite().optional(),suite_micro_rate:G().finite().optional(),suite_micro_numerator:G().finite().optional(),suite_micro_denominator:G().finite().positive().optional()}).passthrough(),OC=J({arm_id:W(),arm_role:W(),factor_assignments:gd(W(),W()),protocol_counts:gd(W(),G().int().nonnegative()).default({}),runner_revision_counts:gd(W(),G().int().nonnegative()).default({}),orchestrator_runtime_counts:gd(W(),G().int().nonnegative()).default({}),intended_case_count:G().int().positive(),run_count:G().int().nonnegative(),terminal_run_count:G().int().nonnegative(),selected_score_countable_case_count:G().int().nonnegative(),coverage_rate:G().finite().min(0).max(1),metrics:gd(W(),DC),binary_outcomes:gd(W(),J({success_count:G().int().nonnegative(),case_denominator:G().int().nonnegative(),success_rate:G().finite().min(0).max(1).nullable()})),effort:gd(W(),J({denominator:G().int().nonnegative(),mean:G().finite().nullable(),median:G().finite().nullable()})),failure_class_counts:gd(W(),G().int().nonnegative())}).passthrough(),kC=J({baseline_value:G().finite(),candidate_value:G().finite(),delta:G().finite(),direction:Y([`improved`,`flat`,`regressed`]).optional()}).passthrough(),AC=J({comparison_id:W(),comparison_anchor_run_id:W(),candidate_run_id:W(),candidate_arm_id:W(),primary_metric:W(),matched_pair_countable:X(!0),metric_deltas:gd(W(),kC)}).passthrough(),jC=J({ok:X(!0),schema_version:X(`benchmark_study_dashboard_v0`),benchmark_id:W(),study_id:W(),status:Y([`complete`,`provisional`]),design:J({protocol_id:W(),comparison_protocol_id:W(),baseline_arm_id:W(),case_set:J({case_set_id:W(),case_ids:q(W())}),metric_catalog:q(J({metric_name:W(),role:Y([`primary`,`guardrail`,`supporting`]),unit:W().optional(),higher_is_better:K(),binary:K()})),labels:gd(W(),W())}).passthrough(),campaign:J({intended_case_count:G().int().positive(),intended_arm_count:G().int().positive(),intended_cell_denominator:G().int().positive(),selected_score_countable_cell_count:G().int().nonnegative(),selected_score_countable_coverage_rate:G().finite().min(0).max(1),complete_declared_design_case_count:G().int().nonnegative(),ambiguous_score_countable_cell_count:G().int().nonnegative(),in_flight_run_count:G().int().nonnegative(),matched_pair_countable_count:G().int().nonnegative(),factorial_contrast_count:G().int().nonnegative(),factorial_contrast_countable_count:G().int().nonnegative(),runtime_observation_count:G().int().nonnegative(),runtime_classification_counts:gd(W(),G().int().nonnegative())}),arms:q(OC),contrasts:gd(W(),J({matched_pair_denominator:G().int().nonnegative(),primary_metric_directions:J({improved:G().int().nonnegative(),flat:G().int().nonnegative(),regressed:G().int().nonnegative()}),binary_metric_transitions:gd(W(),J({"0_to_1":G().int().nonnegative(),"1_to_0":G().int().nonnegative(),same:G().int().nonnegative()}))})),cases:q(J({case_id:W(),complete_declared_design:K(),arms:q(TC),eligible_comparisons:q(AC),largest_eligible_primary_contrast:AC.nullable()})),runs:q(EC),authority:J({score_source:W(),matched_comparison_source:W(),factorial_comparison_source:W().nullable(),manifest_changes_scores:X(!1),dashboard_is_execution_authority:X(!1)}),public_boundary:J({raw_task_recorded:X(!1),raw_trajectory_recorded:X(!1),hidden_evaluation_recorded:X(!1),raw_verifier_output_recorded:X(!1),credentials_recorded:X(!1),local_paths_recorded:X(!1)}),write_performed:X(!1),network_access_performed:X(!1)});function MC(e){return jC.parse(e)}function NC(e,t){let n=new URL(t),r=new URL(e||`/benchmark-study.example.json`,n);if(!new Set([`http:`,`https:`]).has(r.protocol))throw Error(`Benchmark dashboard source must use HTTP or HTTPS`);if(r.origin!==n.origin)throw Error(`Benchmark dashboard source must use same-origin local readback`);return r.toString()}var PC=[{id:`campaign`,label:`Campaign`},{id:`arms`,label:`Arms`},{id:`cases`,label:`Cases`},{id:`runs`,label:`Runs`}];function FC(e){return e==null?`—`:`${(e*100).toFixed(e>=.995?0:1)}%`}function IC(e){return e==null?`—`:new Intl.NumberFormat(`en`,{maximumFractionDigits:2,notation:`compact`}).format(e)}function LC(e){if(e==null)return`—`;let t=e/6e4;return t>=120?`${(t/60).toFixed(1)} h`:`${IC(t)} min`}function RC(e){let t=Object.entries(e);return t.length?t.map(([e,t])=>`${e} (${t})`).join(`, `):`—`}function zC(e){if(!e)return`—`;let t=e.total==null?IC(e.value):`${IC(e.value)}/${IC(e.total)}`;return e.unit?`${t} ${e.unit}`:t}function BC(e,t){let n=e.metrics[t];return!n||n.case_denominator===0?`—`:n.suite_micro_rate==null?`${IC(n.value_mean)} mean`:`${FC(n.suite_micro_rate)} · ${IC(n.suite_micro_numerator)}/${IC(n.suite_micro_denominator)}`}function VC(e,t){let n=e.largest_eligible_primary_contrast,r=n?.metric_deltas[t];if(!n||!r)return null;let i=r.delta>0?`+`:``;return{direction:r.direction,text:`${n.candidate_arm_id}: ${i}${IC(r.delta)}`}}function HC({children:e,tone:t=`neutral`}){return(0,B.jsx)(`span`,{className:`benchmark-state benchmark-state-${t}`,children:e})}function UC({packet:e,primaryMetric:t}){return(0,B.jsxs)(`div`,{className:`benchmark-view-stack`,children:[(0,B.jsxs)(`section`,{"aria-labelledby":`arm-summary-title`,children:[(0,B.jsxs)(`div`,{className:`benchmark-section-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`p`,{className:`benchmark-kicker`,children:`ARM SUMMARY`}),(0,B.jsx)(`h2`,{id:`arm-summary-title`,children:`Comparable outcomes, denominator first`})]}),(0,B.jsx)(`p`,{children:`Only one score-countable run per declared case × arm cell is selected.`})]}),(0,B.jsx)(`div`,{className:`benchmark-arm-grid`,children:e.arms.map(e=>{let n=Object.values(e.binary_outcomes)[0];return(0,B.jsxs)(`article`,{className:`benchmark-arm-card`,children:[(0,B.jsxs)(`div`,{className:`benchmark-card-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`span`,{className:`benchmark-mono`,children:e.arm_role}),(0,B.jsx)(`h3`,{children:e.arm_id})]}),(0,B.jsx)(HC,{tone:e.coverage_rate===1?`success`:`warning`,children:e.coverage_rate===1?`Complete`:`Provisional`})]}),(0,B.jsxs)(`dl`,{className:`benchmark-stat-list`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`dt`,{children:[`Primary · `,t]}),(0,B.jsx)(`dd`,{children:BC(e,t)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Score-countable coverage`}),(0,B.jsxs)(`dd`,{children:[e.selected_score_countable_case_count,`/`,e.intended_case_count]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Binary success`}),(0,B.jsx)(`dd`,{children:n?`${n.success_count}/${n.case_denominator}`:`Not declared`})]})]})]},e.arm_id)})})]}),(0,B.jsxs)(`section`,{"aria-labelledby":`contrast-title`,children:[(0,B.jsxs)(`div`,{className:`benchmark-section-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`p`,{className:`benchmark-kicker`,children:`MATCHED CONTRASTS`}),(0,B.jsx)(`h2`,{id:`contrast-title`,children:`Direction counts on eligible pairs`})]}),(0,B.jsx)(`p`,{children:`Raw run volume is never used as a comparison denominator.`})]}),(0,B.jsx)(`div`,{className:`benchmark-table-shell`,children:(0,B.jsxs)(`table`,{children:[(0,B.jsx)(`thead`,{children:(0,B.jsxs)(`tr`,{children:[(0,B.jsx)(`th`,{children:`Candidate arm`}),(0,B.jsx)(`th`,{children:`Matched denominator`}),(0,B.jsx)(`th`,{children:`Improved`}),(0,B.jsx)(`th`,{children:`Flat`}),(0,B.jsx)(`th`,{children:`Regressed`}),(0,B.jsx)(`th`,{children:`Binary transitions`})]})}),(0,B.jsxs)(`tbody`,{children:[Object.entries(e.contrasts).map(([e,t])=>(0,B.jsxs)(`tr`,{children:[(0,B.jsx)(`td`,{children:(0,B.jsx)(`strong`,{children:e})}),(0,B.jsx)(`td`,{children:t.matched_pair_denominator}),(0,B.jsx)(`td`,{className:`benchmark-positive`,children:t.primary_metric_directions.improved}),(0,B.jsx)(`td`,{children:t.primary_metric_directions.flat}),(0,B.jsx)(`td`,{className:`benchmark-negative`,children:t.primary_metric_directions.regressed}),(0,B.jsx)(`td`,{children:Object.entries(t.binary_metric_transitions).map(([e,t])=>`${e}: 0→1 ${t[`0_to_1`]}, 1→0 ${t[`1_to_0`]}, same ${t.same}`).join(` · `)||`—`})]},e)),Object.keys(e.contrasts).length===0&&(0,B.jsx)(`tr`,{children:(0,B.jsx)(`td`,{colSpan:6,children:`No matched comparisons are countable yet.`})})]})]})})]}),(0,B.jsxs)(`section`,{"aria-labelledby":`runtime-health-title`,children:[(0,B.jsxs)(`div`,{className:`benchmark-section-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`p`,{className:`benchmark-kicker`,children:`RUNTIME HEALTH`}),(0,B.jsx)(`h2`,{id:`runtime-health-title`,children:`Qualified observations, without execution authority`})]}),(0,B.jsxs)(`p`,{children:[e.campaign.runtime_observation_count,` public-safe runtime observations.`]})]}),(0,B.jsxs)(`div`,{className:`benchmark-runtime-list`,children:[Object.entries(e.campaign.runtime_classification_counts).map(([e,t])=>(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`span`,{children:e}),(0,B.jsx)(`strong`,{children:t})]},e)),e.campaign.runtime_observation_count===0&&(0,B.jsx)(`p`,{className:`benchmark-muted`,children:`No runtime observations uploaded.`})]})]})]})}function WC({packet:e}){return(0,B.jsx)(`div`,{className:`benchmark-detail-grid`,children:e.arms.map(t=>(0,B.jsxs)(`article`,{className:`benchmark-detail-card`,children:[(0,B.jsxs)(`div`,{className:`benchmark-card-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`span`,{className:`benchmark-mono`,children:t.arm_role}),(0,B.jsx)(`h2`,{children:t.arm_id})]}),(0,B.jsxs)(HC,{tone:t.coverage_rate===1?`success`:`warning`,children:[t.selected_score_countable_case_count,`/`,t.intended_case_count,` countable`]})]}),(0,B.jsx)(`div`,{className:`benchmark-factor-row`,children:Object.entries(t.factor_assignments).map(([e,t])=>(0,B.jsxs)(`span`,{children:[e,`: `,(0,B.jsx)(`strong`,{children:t})]},e))}),(0,B.jsxs)(`dl`,{className:`benchmark-stat-list`,children:[e.design.metric_catalog.map(e=>(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`dt`,{children:[e.role,` · `,e.metric_name]}),(0,B.jsx)(`dd`,{children:BC(t,e.metric_name)})]},e.metric_name)),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Runs terminal / observed`}),(0,B.jsxs)(`dd`,{children:[t.terminal_run_count,`/`,t.run_count]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Median duration`}),(0,B.jsx)(`dd`,{children:LC(t.effort.duration_ms?.median)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Protocols`}),(0,B.jsx)(`dd`,{children:RC(t.protocol_counts)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Runner revisions`}),(0,B.jsx)(`dd`,{children:RC(t.runner_revision_counts)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Orchestrator runtimes`}),(0,B.jsxs)(`dd`,{children:[Object.keys(t.orchestrator_runtime_counts).length||0,` distinct`]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Failure classes`}),(0,B.jsx)(`dd`,{children:RC(t.failure_class_counts)})]})]})]},t.arm_id))})}function GC({packet:e,primaryMetric:t,onOpenRun:n}){return(0,B.jsx)(`div`,{className:`benchmark-table-shell benchmark-wide-table`,children:(0,B.jsxs)(`table`,{children:[(0,B.jsx)(`thead`,{children:(0,B.jsxs)(`tr`,{children:[(0,B.jsx)(`th`,{children:`Case`}),(0,B.jsx)(`th`,{children:`Design status`}),(0,B.jsx)(`th`,{children:`Largest eligible delta`}),e.arms.map(e=>(0,B.jsx)(`th`,{children:e.arm_id},e.arm_id))]})}),(0,B.jsx)(`tbody`,{children:e.cases.map(r=>{let i=VC(r,t);return(0,B.jsxs)(`tr`,{children:[(0,B.jsx)(`td`,{children:(0,B.jsx)(`strong`,{children:r.case_id})}),(0,B.jsx)(`td`,{children:(0,B.jsx)(HC,{tone:r.complete_declared_design?`success`:`warning`,children:r.complete_declared_design?`Complete`:`Provisional`})}),(0,B.jsx)(`td`,{className:i?.direction===`improved`?`benchmark-positive`:i?.direction===`regressed`?`benchmark-negative`:void 0,children:i?.text??`—`}),r.arms.map(r=>(0,B.jsx)(`td`,{children:r.selected_run_id&&r.score_countable?(0,B.jsxs)(`button`,{className:`benchmark-cell-link`,onClick:()=>n(r.selected_run_id),type:`button`,children:[(0,B.jsxs)(`span`,{children:[t,`: `,zC(r.metrics[t])]}),e.design.metric_catalog.filter(e=>e.metric_name!==t).map(e=>(0,B.jsxs)(`small`,{className:`benchmark-cell-metric`,children:[e.metric_name,`: `,zC(r.metrics[e.metric_name])]},e.metric_name)),(0,B.jsxs)(`small`,{children:[`Countable · `,LC(r.effort.duration_ms),` `,(0,B.jsx)(Kp,{"aria-hidden":`true`,size:12})]}),r.insight&&(0,B.jsxs)(`small`,{children:[r.insight.failure_class,` · `,r.insight.confidence]})]}):(0,B.jsx)(`span`,{className:`benchmark-muted`,children:`Not countable`})},r.arm_id))]},r.case_id)})})]})})}function KC({run:e,packet:t}){return(0,B.jsxs)(`aside`,{"aria-label":`Run detail for ${e.run_id}`,className:`benchmark-run-detail`,children:[(0,B.jsxs)(`div`,{className:`benchmark-card-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`span`,{className:`benchmark-mono`,children:`RUN DETAIL`}),(0,B.jsx)(`h2`,{children:e.run_id})]}),(0,B.jsx)(HC,{tone:e.countability.score_countable?`success`:`warning`,children:e.countability.score_countable?`Score-countable`:`Diagnostic only`})]}),(0,B.jsxs)(`dl`,{className:`benchmark-stat-list benchmark-run-facts`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Case / arm`}),(0,B.jsxs)(`dd`,{children:[e.case_id,` · `,e.arm_id]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Lifecycle`}),(0,B.jsxs)(`dd`,{children:[e.status,` · `,e.observed_at]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Protocol`}),(0,B.jsx)(`dd`,{children:e.protocol_id})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Qualification`}),(0,B.jsxs)(`dd`,{children:[`Integrity `,e.countability.integrity_qualified?`qualified`:`not qualified`,` · result `,e.countability.official_result_present?`present`:`missing`]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Treatment fidelity`}),(0,B.jsx)(`dd`,{children:e.treatment_fidelity})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Effort`}),(0,B.jsxs)(`dd`,{children:[LC(e.effort.duration_ms),` · `,IC(e.effort.agent_steps),` steps · `,IC(e.effort.token_count),` tokens`]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Runner revision`}),(0,B.jsx)(`dd`,{children:e.runner_revision??`—`})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Upload provenance`}),(0,B.jsxs)(`dd`,{children:[e.upload_provenance.producer_id,` · `,e.upload_provenance.source_revision]})]})]}),(0,B.jsx)(`div`,{className:`benchmark-run-metrics`,children:t.design.metric_catalog.map(t=>(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`span`,{children:t.metric_name}),(0,B.jsx)(`strong`,{children:zC(e.metrics[t.metric_name])})]},t.metric_name))}),e.redacted_insight&&(0,B.jsxs)(`div`,{className:`benchmark-insight`,children:[(0,B.jsxs)(`span`,{className:`benchmark-mono`,children:[`REDACTED CASE INSIGHT · `,e.redacted_insight.confidence]}),(0,B.jsx)(`p`,{children:e.redacted_insight.causal_summary}),(0,B.jsxs)(`small`,{children:[`Implication: `,e.redacted_insight.implication]}),(0,B.jsx)(`br`,{}),(0,B.jsxs)(`small`,{children:[`Next probe: `,e.redacted_insight.next_probe]}),!!e.redacted_insight.evidence_refs?.length&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`br`,{}),(0,B.jsxs)(`small`,{children:[`Evidence: `,e.redacted_insight.evidence_refs.join(`, `)]})]})]})]})}function qC({packet:e,selectedRunId:t,onSelectRun:n}){let r=e.runs.find(e=>e.run_id===t)??e.runs[0];return(0,B.jsxs)(`div`,{className:`benchmark-runs-layout`,children:[(0,B.jsx)(`div`,{className:`benchmark-table-shell`,children:(0,B.jsxs)(`table`,{children:[(0,B.jsx)(`thead`,{children:(0,B.jsxs)(`tr`,{children:[(0,B.jsx)(`th`,{children:`Run`}),(0,B.jsx)(`th`,{children:`Case`}),(0,B.jsx)(`th`,{children:`Arm`}),(0,B.jsx)(`th`,{children:`Status`}),(0,B.jsx)(`th`,{children:`Countability`})]})}),(0,B.jsx)(`tbody`,{children:e.runs.map(e=>(0,B.jsxs)(`tr`,{"aria-selected":e.run_id===r?.run_id,children:[(0,B.jsx)(`td`,{children:(0,B.jsx)(`button`,{className:`benchmark-run-link`,onClick:()=>n(e.run_id),type:`button`,children:e.run_id})}),(0,B.jsx)(`td`,{children:e.case_id}),(0,B.jsx)(`td`,{children:e.arm_id}),(0,B.jsx)(`td`,{children:e.status}),(0,B.jsx)(`td`,{children:e.countability.score_countable?`Score-countable`:`Diagnostic only`})]},e.run_id))})]})}),r&&(0,B.jsx)(KC,{packet:e,run:r})]})}function JC(){let e=lw.useSearch(),t=lw.useNavigate(),[n,r]=(0,z.useState)(null),[i,a]=(0,z.useState)(null),[o,s]=(0,z.useState)(0),c=(0,z.useMemo)(()=>{let t=e.dashboardUrl||`/chat/benchmark-study.example.json`;try{return{url:NC(t,window.location.href),error:null}}catch(e){return{url:``,error:e instanceof Error?e.message:`Invalid dashboard source`}}},[e.dashboardUrl]);if((0,z.useEffect)(()=>{let e=!0;return r(null),a(null),c.error?(a(c.error),()=>{e=!1}):(fetch(c.url,{cache:`no-store`}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status} while loading the dashboard packet`);return MC(await e.json())}).then(t=>{e&&r(t)}).catch(t=>{e&&a(t instanceof Error?t.message:`Unable to load dashboard packet`)}),()=>{e=!1})},[o,c]),(0,z.useEffect)(()=>{n&&(document.title=`${n.design.labels.title??n.study_id} · LoopX Benchmark`)},[n]),i)return(0,B.jsxs)(`main`,{className:`benchmark-page benchmark-loading`,children:[(0,B.jsx)(im,{"aria-hidden":`true`}),(0,B.jsx)(`h1`,{children:`Dashboard packet unavailable`}),(0,B.jsx)(`p`,{children:i}),(0,B.jsxs)(`button`,{onClick:()=>s(e=>e+1),type:`button`,children:[(0,B.jsx)(Im,{"aria-hidden":`true`,size:16}),` Retry readback`]})]});if(!n)return(0,B.jsxs)(`main`,{"aria-busy":`true`,className:`benchmark-page benchmark-loading`,children:[(0,B.jsx)(Up,{"aria-hidden":`true`}),(0,B.jsx)(`h1`,{children:`Reading benchmark study`}),(0,B.jsx)(`p`,{children:`Validating the public-safe dashboard packet…`})]});let l=n.design.metric_catalog.find(e=>e.role===`primary`)?.metric_name??`primary`,u=(n,r=e.runId)=>t({search:e=>({...e,view:n,runId:r})}),d=new URL(c.url).pathname;return(0,B.jsxs)(`main`,{className:`benchmark-page`,children:[(0,B.jsxs)(`header`,{className:`benchmark-hero`,children:[(0,B.jsxs)(`div`,{className:`benchmark-hero-topline`,children:[(0,B.jsx)(`a`,{className:`benchmark-wordmark`,href:`/chat/`,children:`LoopX`}),(0,B.jsxs)(`div`,{className:`benchmark-readonly`,children:[(0,B.jsx)(Wm,{"aria-hidden":`true`,size:15}),` Derived read-only projection`]})]}),(0,B.jsxs)(`div`,{className:`benchmark-hero-grid`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`p`,{className:`benchmark-kicker`,children:[`BENCHMARK STUDY / `,n.benchmark_id]}),(0,B.jsxs)(`div`,{className:`benchmark-title-row`,children:[(0,B.jsx)(`h1`,{children:n.design.labels.title??n.study_id}),(0,B.jsx)(HC,{tone:n.status===`complete`?`success`:`warning`,children:n.status})]}),(0,B.jsx)(`p`,{className:`benchmark-lead`,children:`One declared study, explicit denominators, and the same countability rules from campaign summary to exact run.`})]}),(0,B.jsxs)(`dl`,{className:`benchmark-identity`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Study`}),(0,B.jsx)(`dd`,{children:n.study_id})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Protocol`}),(0,B.jsx)(`dd`,{children:n.design.protocol_id})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Case set`}),(0,B.jsx)(`dd`,{children:n.design.case_set.case_set_id})]})]})]}),(0,B.jsxs)(`div`,{className:`benchmark-kpi-grid`,children:[(0,B.jsxs)(`article`,{children:[(0,B.jsx)(lm,{"aria-hidden":`true`}),(0,B.jsx)(`span`,{children:`Score-countable cells`}),(0,B.jsxs)(`strong`,{children:[n.campaign.selected_score_countable_cell_count,(0,B.jsxs)(`small`,{children:[` / `,n.campaign.intended_cell_denominator]})]}),(0,B.jsxs)(`p`,{children:[FC(n.campaign.selected_score_countable_coverage_rate),` declared coverage`]})]}),(0,B.jsxs)(`article`,{children:[(0,B.jsx)(am,{"aria-hidden":`true`}),(0,B.jsx)(`span`,{children:`Complete designs`}),(0,B.jsxs)(`strong`,{children:[n.campaign.complete_declared_design_case_count,(0,B.jsxs)(`small`,{children:[` / `,n.campaign.intended_case_count]})]}),(0,B.jsx)(`p`,{children:`Cases with every declared arm`})]}),(0,B.jsxs)(`article`,{children:[(0,B.jsx)(Kp,{"aria-hidden":`true`}),(0,B.jsx)(`span`,{children:`Matched comparisons`}),(0,B.jsx)(`strong`,{children:n.campaign.matched_pair_countable_count}),(0,B.jsx)(`p`,{children:`Eligible pairs only`})]}),(0,B.jsxs)(`article`,{children:[(0,B.jsx)(Up,{"aria-hidden":`true`}),(0,B.jsx)(`span`,{children:`In flight`}),(0,B.jsx)(`strong`,{children:n.campaign.in_flight_run_count}),(0,B.jsx)(`p`,{children:n.status===`provisional`?`Coverage remains provisional`:`Declared coverage complete`})]})]})]}),(0,B.jsxs)(`nav`,{"aria-label":`Benchmark dashboard views`,className:`benchmark-tabs`,children:[PC.map(t=>(0,B.jsx)(`button`,{"aria-current":e.view===t.id?`page`:void 0,onClick:()=>u(t.id),type:`button`,children:t.label},t.id)),(0,B.jsxs)(`button`,{className:`benchmark-refresh`,onClick:()=>s(e=>e+1),type:`button`,children:[(0,B.jsx)(Im,{"aria-hidden":`true`,size:14}),` Refresh local readback`]})]}),(0,B.jsxs)(`div`,{className:`benchmark-content`,children:[e.view===`campaign`&&(0,B.jsx)(UC,{packet:n,primaryMetric:l}),e.view===`arms`&&(0,B.jsx)(WC,{packet:n}),e.view===`cases`&&(0,B.jsx)(GC,{onOpenRun:e=>u(`runs`,e),packet:n,primaryMetric:l}),e.view===`runs`&&(0,B.jsx)(qC,{onSelectRun:e=>u(`runs`,e),packet:n,selectedRunId:e.runId})]}),(0,B.jsxs)(`footer`,{className:`benchmark-footer`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(Wm,{"aria-hidden":`true`,size:16}),(0,B.jsxs)(`span`,{children:[`Scores: `,n.authority.score_source]}),(0,B.jsx)(`span`,{children:`Dashboard cannot launch, grade, or mutate runs.`})]}),(0,B.jsxs)(`code`,{title:d,children:[`local`,d]})]})]})}var YC=J({goalId:W().optional().default(``),statusUrl:W().optional().default(``)}),XC=J({goalId:W().optional().default(``),mode:Y([`showcase`,`developer`,`ops`]).optional().default(`showcase`),statusUrl:W().optional().default(``),todoLane:Y([`all`,`user`,`agent`]).optional().default(`all`),todoQuery:W().optional().default(``)}),ZC=XC.omit({mode:!0}),QC=J({dashboardUrl:W().optional().default(``),view:Y([`campaign`,`arms`,`cases`,`runs`]).optional().default(`campaign`),runId:W().optional().default(``)});function $C(){let e=`https://huangruiteng.github.io/loopx/docs/showcases/index.en.html`;return(0,z.useEffect)(()=>{window.location.replace(e)},[]),(0,B.jsx)(`a`,{href:e,children:`Open LoopX cases / 浏览案例`})}function ew({goalId:e,statusUrl:t}){let n=t?rh(t,window.location.href):null;return n?.error?(0,B.jsx)(`main`,{role:`alert`,children:n.error}):(0,B.jsx)(ii,{replace:!0,to:`/`,search:{goalId:e,statusUrl:t}})}function tw(){let e=aw.useSearch();return e.mode===`ops`?(0,B.jsx)(ew,{...e}):e.mode===`developer`?(0,B.jsx)(ii,{replace:!0,to:`/developers/projections`}):(0,B.jsx)($C,{})}function nw(){return(0,B.jsx)(ew,{...ow.useSearch()})}var rw=Ci({component:()=>(0,B.jsx)(Mi,{}),errorComponent:()=>(0,B.jsxs)(`main`,{role:`alert`,className:`p-8`,children:[(0,B.jsx)(`h1`,{children:`页面暂时无法显示 / Page unavailable`}),(0,B.jsx)(`p`,{children:`请重新加载页面;这不会执行任务。 / Reloading does not execute tasks.`}),(0,B.jsx)(`button`,{type:`button`,onClick:()=>window.location.reload(),children:`重新加载 / Reload`})]})}),iw=xi({getParentRoute:()=>rw,path:`/`,validateSearch:e=>YC.parse(e),component:sC}),aw=xi({getParentRoute:()=>rw,path:`/frontstage`,validateSearch:e=>XC.parse(e),component:tw}),ow=xi({getParentRoute:()=>rw,path:`/deprecated/frontstage/ops`,validateSearch:e=>ZC.parse(e),component:nw}),sw=xi({getParentRoute:()=>rw,path:`/frontstage/developer`,component:()=>(0,B.jsx)(ii,{replace:!0,to:`/developers/projections`})}),cw=xi({getParentRoute:()=>rw,path:`/developers/projections`,component:xC}),lw=xi({getParentRoute:()=>rw,path:`/benchmarks/study`,validateSearch:e=>QC.parse(e),component:JC}),uw=rw.addChildren([iw,aw,ow,sw,cw,lw]);function dw(e){return!e||e===`/`||e===`./`?`/`:(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}var fw=Li({routeTree:uw,basepath:dw(`/chat/`),trailingSlash:`preserve`}),pw=document.getElementById(`root`);if(!pw)throw Error(`Root element not found`);var mw=new Ae({defaultOptions:{queries:{refetchOnWindowFocus:!1,retry:1,staleTime:1e4}}});(0,Vi.createRoot)(pw).render((0,B.jsx)(Pe,{client:mw,children:(0,B.jsx)(qi,{children:(0,B.jsx)(Bi,{router:fw})})})); \ No newline at end of file diff --git a/loopx/web/chat/index.html b/loopx/web/chat/index.html index 768b0854e0..e651dc2dfa 100644 --- a/loopx/web/chat/index.html +++ b/loopx/web/chat/index.html @@ -18,7 +18,7 @@ content="LoopX 个人 Agent 工作区:在同一个频道里查看、纠偏并推进 Goal。" /> LoopX 个人 Agent 工作区 - + diff --git a/packages/loopx-finance-execution/README.md b/packages/loopx-finance-execution/README.md new file mode 100644 index 0000000000..a258aafc8d --- /dev/null +++ b/packages/loopx-finance-execution/README.md @@ -0,0 +1,29 @@ +# LoopX Finance Execution + +Status: optional M1 simulator. + +This distribution is the first financial consumer of LoopX's human-confirmed +operation envelope. It validates one immutable `finance_order_intent_v0` and +returns a deterministic simulated fill. It contains no venue client, signer, +credential reader, transfer path, reservation authority, or retrying network +submission. + +The Core typed-action store owns confirmation and the single execution claim. +This package accepts only a consumed claim whose operation and payload digests +match. Its `finance.operation.simulate` permission does not authorize a real +order. Every result is marked `simulation=true` and +`external_write_performed=false`. + +Install and enable it through the normal LoopX extension lifecycle before using +the M1 operation-card flow: + +```bash +python3 -m pip install ./packages/loopx-finance-execution +loopx extension install \ + --manifest packages/loopx-finance-execution/extension.toml \ + --execute --format json +loopx extension enable loopx-finance-execution --execute --format json +``` + +Real venue adapters are intentionally out of scope. They require the later +finance reservation, ambiguity/reconciliation and venue conformance milestones. diff --git a/packages/loopx-finance-execution/extension.toml b/packages/loopx-finance-execution/extension.toml new file mode 100644 index 0000000000..534326b567 --- /dev/null +++ b/packages/loopx-finance-execution/extension.toml @@ -0,0 +1,16 @@ +schema_version = "loopx_extension_manifest_v0" +id = "loopx-finance-execution" +version = "0.1.0" +requires_loopx_api = ">=1,<2" +permissions = ["finance.operation.simulate"] + +[runtime] +protocol = "finance_operation_executor_v0" +entrypoint = "loopx-finance-execution" +doctor_args = ["--doctor"] +required_permissions = ["finance.operation.simulate"] +timeout_seconds = 30 + +[[implements]] +capability_id = "human-confirmed-operation-executor" +protocol = "finance_operation_executor_v0" diff --git a/packages/loopx-finance-execution/pyproject.toml b/packages/loopx-finance-execution/pyproject.toml new file mode 100644 index 0000000000..6b34359860 --- /dev/null +++ b/packages/loopx-finance-execution/pyproject.toml @@ -0,0 +1,18 @@ +[build-system] +requires = ["setuptools>=69"] +build-backend = "setuptools.build_meta" + +[project] +name = "loopx-finance-execution" +version = "0.1.0" +description = "Simulated finance operation consumer for LoopX confirmation flows." +readme = "README.md" +requires-python = ">=3.11" +license = "Apache-2.0" +dependencies = [] + +[project.scripts] +loopx-finance-execution = "loopx_finance_execution.cli:main" + +[tool.setuptools.packages.find] +where = ["src"] diff --git a/packages/loopx-finance-execution/src/loopx_finance_execution/__init__.py b/packages/loopx-finance-execution/src/loopx_finance_execution/__init__.py new file mode 100644 index 0000000000..3d43e828b7 --- /dev/null +++ b/packages/loopx-finance-execution/src/loopx_finance_execution/__init__.py @@ -0,0 +1,5 @@ +"""Optional simulated finance executor for LoopX operation envelopes.""" + +from .simulator import execute_simulated_finance_operation + +__all__ = ["execute_simulated_finance_operation"] diff --git a/packages/loopx-finance-execution/src/loopx_finance_execution/cli.py b/packages/loopx-finance-execution/src/loopx_finance_execution/cli.py new file mode 100644 index 0000000000..b318f0966f --- /dev/null +++ b/packages/loopx-finance-execution/src/loopx_finance_execution/cli.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import argparse +import json +import sys +from collections.abc import Sequence + +from .simulator import execute_simulated_finance_operation + + +def run(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="loopx-finance-execution") + parser.add_argument("--doctor", action="store_true") + args = parser.parse_args(list(argv) if argv is not None else None) + if args.doctor: + return 0 + try: + request = json.load(sys.stdin) + result = execute_simulated_finance_operation(request) + except Exception as exc: # noqa: BLE001 - redact the process boundary + print( + json.dumps( + { + "ok": False, + "schema_version": "finance_operation_error_v0", + "error": type(exc).__name__, + "simulation": True, + "external_write_performed": False, + }, + sort_keys=True, + ) + ) + return 1 + print(json.dumps(result, sort_keys=True)) + return 0 + + +def main(argv: Sequence[str] | None = None) -> int: + return run(argv) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/loopx-finance-execution/src/loopx_finance_execution/simulator.py b/packages/loopx-finance-execution/src/loopx_finance_execution/simulator.py new file mode 100644 index 0000000000..cf3edfea89 --- /dev/null +++ b/packages/loopx-finance-execution/src/loopx_finance_execution/simulator.py @@ -0,0 +1,172 @@ +from __future__ import annotations + +from datetime import datetime, timezone +from decimal import Decimal, InvalidOperation +import hashlib +import json +import re +from collections.abc import Mapping +from typing import Any + + +REQUEST_SCHEMA_VERSION = "finance_operation_execute_request_v0" +ORDER_SCHEMA_VERSION = "finance_order_intent_v0" +OUTCOME_SCHEMA_VERSION = "loopx_operation_outcome_v0" +PROTOCOL = "finance_operation_executor_v0" +PERMISSION = "finance.operation.simulate" +OPERATION_KIND = "finance.order.simulate" +_OPAQUE = re.compile(r"^[A-Za-z0-9._:-]{1,200}$") +_SHA256 = re.compile(r"^[0-9a-f]{64}$") + + +def _digest(value: object) -> str: + encoded = json.dumps( + value, + allow_nan=False, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ).encode() + return hashlib.sha256(encoded).hexdigest() + + +def _token(value: object, *, field: str) -> str: + result = str(value or "").strip() + if not _OPAQUE.fullmatch(result): + raise ValueError(f"{field} must be a compact opaque id") + return result + + +def _decimal(value: object, *, field: str, positive: bool = True) -> Decimal: + if not isinstance(value, str) or len(value) > 80: + raise ValueError(f"{field} must be a decimal string") + try: + result = Decimal(value) + except InvalidOperation as exc: + raise ValueError(f"{field} must be a decimal string") from exc + if not result.is_finite() or (positive and result <= 0): + raise ValueError(f"{field} must be a positive finite decimal") + return result + + +def _normalize_order(value: object) -> dict[str, Any]: + if not isinstance(value, Mapping): + raise ValueError("finance operation payload must be an object") + allowed = { + "schema_version", + "asset", + "side", + "quantity", + "quantity_unit", + "order_type", + "limit_price", + "price_unit", + "time_in_force", + "reduce_only", + "maximum_fee", + "fee_unit", + } + if set(value) - allowed: + raise ValueError("finance order intent contains unsupported fields") + if value.get("schema_version") != ORDER_SCHEMA_VERSION: + raise ValueError(f"finance order intent must use {ORDER_SCHEMA_VERSION}") + side = str(value.get("side") or "").lower() + order_type = str(value.get("order_type") or "").lower() + if side not in {"buy", "sell"}: + raise ValueError("finance order side must be buy or sell") + if order_type != "limit": + raise ValueError("the M1 simulator accepts limit orders only") + if value.get("time_in_force") not in {"GTC", "IOC"}: + raise ValueError("finance order time_in_force must be GTC or IOC") + if not isinstance(value.get("reduce_only"), bool): + raise ValueError("finance order reduce_only must be true or false") + quantity = _decimal(value.get("quantity"), field="quantity") + limit_price = _decimal(value.get("limit_price"), field="limit_price") + maximum_fee = _decimal(value.get("maximum_fee"), field="maximum_fee") + return { + "schema_version": ORDER_SCHEMA_VERSION, + "asset": _token(value.get("asset"), field="asset"), + "side": side, + "quantity": str(quantity), + "quantity_unit": _token(value.get("quantity_unit"), field="quantity_unit"), + "order_type": order_type, + "limit_price": str(limit_price), + "price_unit": _token(value.get("price_unit"), field="price_unit"), + "time_in_force": value["time_in_force"], + "reduce_only": value["reduce_only"], + "maximum_fee": str(maximum_fee), + "fee_unit": _token(value.get("fee_unit"), field="fee_unit"), + } + + +def execute_simulated_finance_operation(value: object) -> dict[str, Any]: + if not isinstance(value, Mapping): + raise ValueError("finance executor request must be an object") + expected_fields = { + "schema_version", + "protocol", + "permission", + "operation_id", + "operation_kind", + "operation_schema", + "payload", + "payload_digest", + "confirmation_digest", + "claim_id", + "executor_revision", + "destination_account_ref", + } + if set(value) != expected_fields: + raise ValueError("finance executor request has unsupported or missing fields") + if value.get("schema_version") != REQUEST_SCHEMA_VERSION: + raise ValueError(f"finance executor request must use {REQUEST_SCHEMA_VERSION}") + if value.get("protocol") != PROTOCOL or value.get("permission") != PERMISSION: + raise ValueError("finance executor protocol or permission is unsupported") + if value.get("operation_kind") != OPERATION_KIND: + raise ValueError("finance executor operation kind is unsupported") + if value.get("operation_schema") != ORDER_SCHEMA_VERSION: + raise ValueError("finance executor operation schema is unsupported") + if value.get("destination_account_ref") != "account:simulation": + raise ValueError("M1 finance execution is restricted to account:simulation") + operation_id = _token(value.get("operation_id"), field="operation_id") + claim_id = _token(value.get("claim_id"), field="claim_id") + confirmation_digest = str(value.get("confirmation_digest") or "") + payload_digest = str(value.get("payload_digest") or "") + if not _SHA256.fullmatch(confirmation_digest): + raise ValueError("confirmation_digest must be lowercase SHA-256") + if not _SHA256.fullmatch(payload_digest): + raise ValueError("payload_digest must be lowercase SHA-256") + order = _normalize_order(value.get("payload")) + if _digest(value.get("payload")) != payload_digest: + raise ValueError("payload_digest does not match the finance order intent") + notional = Decimal(order["quantity"]) * Decimal(order["limit_price"]) + observed_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + return { + "ok": True, + "schema_version": OUTCOME_SCHEMA_VERSION, + "outcome": "simulated_filled", + "projection_verified": True, + "operation_id": operation_id, + "payload_digest": payload_digest, + "claim_id": claim_id, + "executor_revision": _token( + value.get("executor_revision"), field="executor_revision" + ), + "summary": ( + f"SIMULATION: {order['side'].upper()} {order['quantity']} " + f"{order['asset']} at {order['limit_price']} {order['price_unit']}." + ), + "details": { + "asset": order["asset"], + "side": order["side"], + "filled_quantity": order["quantity"], + "average_price": order["limit_price"], + "notional": str(notional), + "notional_unit": order["price_unit"], + "fee": "0", + "fee_unit": order["fee_unit"], + }, + "simulation": True, + "external_write_performed": False, + "observed_at": observed_at, + } diff --git a/tests/extensions/test_finance_execution_simulator.py b/tests/extensions/test_finance_execution_simulator.py new file mode 100644 index 0000000000..bf3fc2c852 --- /dev/null +++ b/tests/extensions/test_finance_execution_simulator.py @@ -0,0 +1,100 @@ +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +import sys +import tomllib + +import pytest + +from loopx.extensions.manifest import load_extension_manifest + + +ROOT = Path(__file__).resolve().parents[2] +EXTENSION_ROOT = ROOT / "packages" / "loopx-finance-execution" +sys.path.insert(0, str(EXTENSION_ROOT / "src")) + +from loopx_finance_execution.simulator import ( # noqa: E402 + execute_simulated_finance_operation, +) + + +def _digest(value: object) -> str: + return hashlib.sha256( + json.dumps( + value, ensure_ascii=False, sort_keys=True, separators=(",", ":") + ).encode() + ).hexdigest() + + +def _request() -> dict[str, object]: + payload = { + "schema_version": "finance_order_intent_v0", + "asset": "SYNTH", + "side": "buy", + "quantity": "1.25", + "quantity_unit": "SYNTH", + "order_type": "limit", + "limit_price": "8.00", + "price_unit": "TEST", + "time_in_force": "GTC", + "reduce_only": False, + "maximum_fee": "0.10", + "fee_unit": "TEST", + } + return { + "schema_version": "finance_operation_execute_request_v0", + "protocol": "finance_operation_executor_v0", + "permission": "finance.operation.simulate", + "operation_id": "proposal-fixture", + "operation_kind": "finance.order.simulate", + "operation_schema": "finance_order_intent_v0", + "payload": payload, + "payload_digest": _digest(payload), + "confirmation_digest": "a" * 64, + "claim_id": "claim-fixture", + "executor_revision": "simulator-v0", + "destination_account_ref": "account:simulation", + } + + +def test_simulator_returns_explicit_non_effectful_fill() -> None: + result = execute_simulated_finance_operation(_request()) + + assert result["outcome"] == "simulated_filled" + assert result["simulation"] is True + assert result["external_write_performed"] is False + assert result["details"]["notional"] == "10.0000" + assert result["payload_digest"] == _request()["payload_digest"] + + +def test_simulator_rejects_digest_drift_and_non_simulation_account() -> None: + drifted = _request() + drifted["payload"]["quantity"] = "2.00" + with pytest.raises(ValueError, match="payload_digest"): + execute_simulated_finance_operation(drifted) + + real_account = _request() + real_account["destination_account_ref"] = "account:venue" + with pytest.raises(ValueError, match="account:simulation"): + execute_simulated_finance_operation(real_account) + + +def test_manifest_requires_only_the_simulation_permission() -> None: + manifest = tomllib.loads( + (EXTENSION_ROOT / "extension.toml").read_text(encoding="utf-8") + ) + + assert manifest["permissions"] == ["finance.operation.simulate"] + assert manifest["runtime"]["required_permissions"] == ["finance.operation.simulate"] + assert manifest["runtime"]["protocol"] == "finance_operation_executor_v0" + normalized = load_extension_manifest(EXTENSION_ROOT / "extension.toml") + assert normalized["implementations"] == [ + { + "capability_id": "human-confirmed-operation-executor", + "protocol": "finance_operation_executor_v0", + "provider_id": "loopx-finance-execution", + "provider_version": "0.1.0", + } + ] diff --git a/tests/extensions/test_goal_channel_payload.py b/tests/extensions/test_goal_channel_payload.py deleted file mode 100644 index 62f90bb6b4..0000000000 --- a/tests/extensions/test_goal_channel_payload.py +++ /dev/null @@ -1,519 +0,0 @@ -from __future__ import annotations - -import json -from pathlib import Path -from typing import Any - -import pytest - -from loopx.extensions.lark.goal_channel_contracts import ( - GOAL_CHANNEL_BINDING_SCHEMA_VERSION, - read_goal_channel_binding, - write_goal_channel_binding, -) -from loopx.extensions.lark.goal_channel_payload import ( - FROZEN_PAYLOAD_REQUEST_SCHEMA, - deliver_goal_channel_payload, - prepare_goal_channel_payload, -) -from loopx.extensions.lark.goal_channel_targets import add_lark_goal_channel_target -from loopx.status import parse_active_state_todos -from loopx.todos import complete_goal_todo - - -GOAL_ID = "goal-public-fixture" -AGENT_ID = "codex-public-delivery" -CHAT_ID = "oc_public_fixture" -APP_ID = "cli_public_fixture" -SCOPE = "public_claim:action:publish-public-fixture" - - -def _fixture(tmp_path: Path) -> tuple[Path, Path, Path, Path]: - project = tmp_path / "project" - project.mkdir() - state = project / "ACTIVE_GOAL_STATE.md" - state.write_text( - "---\n" - f"goal_id: {GOAL_ID}\n" - "updated_at: 2026-09-12T00:00:00+00:00\n" - "---\n\n" - "## User Todo\n\n" - "## Agent Todo\n", - encoding="utf-8", - ) - runtime_root = tmp_path / "runtime" - registry_path = project / ".loopx" / "registry.json" - registry_path.parent.mkdir() - registry_path.write_text( - json.dumps( - { - "common_runtime_root": str(runtime_root), - "goals": [ - { - "id": GOAL_ID, - "repo": str(project), - "state_file": "ACTIVE_GOAL_STATE.md", - "adapter": {"kind": "read_only_project_map_v0"}, - "coordination": { - "agent_model": "peer_v1", - "registered_agents": [AGENT_ID], - }, - } - ], - } - ), - encoding="utf-8", - ) - target_path = runtime_root / "goal-channel-targets.json" - add_lark_goal_channel_target( - target_path=target_path, - target_name="public-route", - chat_id=CHAT_ID, - chat_name="Public Fixture", - identity_mode="project_bot", - sender_profile="project-reporter", - sender_identity="bot", - bot_app_id=APP_ID, - bot_display_name="Project Reporter", - cli_bin="lark-cli", - execute=True, - ) - binding_path = registry_path.parent / "goal-channel.json" - _write_binding(binding_path) - return registry_path, runtime_root, binding_path, target_path - - -def _write_binding(binding_path: Path, *, target_ref: str = "public-route") -> None: - write_goal_channel_binding( - binding_path, - { - "schema_version": GOAL_CHANNEL_BINDING_SCHEMA_VERSION, - "bindings": { - GOAL_ID: { - "goal_id": GOAL_ID, - "provider": "lark", - "enabled": True, - "target_ref": target_ref, - "channel": {}, - "identity": {}, - } - }, - }, - ) - - -def _request( - *, markdown: str = "Validated fact.\n\nRecommended next research step." -) -> dict[str, Any]: - return { - "schema_version": FROZEN_PAYLOAD_REQUEST_SCHEMA, - "capability_id": "example-capability", - "payload_ref": "example-result-v1", - "title": "Public research result", - "markdown": markdown, - "footer": "LoopX verified result", - "decision_scope": SCOPE, - "public_safe": True, - } - - -def _prepare_and_approve( - registry_path: Path, runtime_root: Path, binding_path: Path, target_path: Path -) -> dict[str, Any]: - prepared = prepare_goal_channel_payload( - _request(), - registry_path=registry_path, - runtime_root=runtime_root, - binding_path=binding_path, - target_path=target_path, - goal_id=GOAL_ID, - agent_id=AGENT_ID, - execute=True, - ) - complete_goal_todo( - registry_path=registry_path, - runtime_root_arg=str(runtime_root), - goal_id=GOAL_ID, - todo_id=prepared["details"]["approval_todo_id"], - role="user", - decision_outcome="approve", - evidence="owner approved the exact frozen public payload", - ) - return prepared - - -def _runner(calls: list[list[str]]): - sent_cards: dict[str, dict[str, Any]] = {} - - def run( - args: list[str], _cwd: Path | None, _timeout: float | None - ) -> dict[str, Any]: - calls.append(args) - if "auth" in args and "status" in args: - payload = { - "ok": True, - "appId": APP_ID, - "identities": { - "bot": { - "available": True, - "verified": True, - "appName": "Project Reporter", - } - }, - } - elif "chats" in args and "get" in args: - payload = {"ok": True, "data": {"chat_id": CHAT_ID}} - elif "+chat-members-list" in args: - payload = {"ok": True, "data": {"bots": [{"app_id": APP_ID}]}} - elif "+chat-messages-list" in args: - payload = { - "ok": True, - "has_more": False, - "messages": [ - { - "message_id": message_id, - "chat_id": CHAT_ID, - "sender": {"sender_type": "app", "id": APP_ID}, - "deleted": False, - "body": {"content": json.dumps(card)}, - } - for message_id, card in sent_cards.items() - ], - } - elif "+messages-send" in args: - message_id = f"om_payload_fixture_{len(sent_cards) + 1}" - sent_cards[message_id] = json.loads(args[args.index("--content") + 1]) - payload = {"ok": True, "data": {"message_id": message_id}} - elif "+messages-mget" in args: - message_id = args[args.index("--message-ids") + 1] - payload = { - "ok": True, - "data": { - "items": [ - { - "message_id": message_id, - "chat_id": CHAT_ID, - "sender": {"sender_type": "app", "id": APP_ID}, - "body": {"content": json.dumps(sent_cards[message_id])}, - } - ] - }, - } - else: # pragma: no cover - raise AssertionError(args) - return {"returncode": 0, "stdout": json.dumps(payload), "stderr": ""} - - return run - - -def test_prepare_creates_blocked_successor_and_exact_user_gate(tmp_path: Path) -> None: - registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) - result = prepare_goal_channel_payload( - _request(), - registry_path=registry_path, - runtime_root=runtime_root, - binding_path=binding_path, - target_path=target_path, - goal_id=GOAL_ID, - agent_id=AGENT_ID, - execute=True, - ) - - assert result["status"] == "approval_pending" - state = registry_path.parent.parent / "ACTIVE_GOAL_STATE.md" - parsed = parse_active_state_todos( - state.read_text(encoding="utf-8"), item_limit=None - ) - delivery = next( - item - for item in parsed["agent_todos"]["items"] - if item["todo_id"] == result["details"]["delivery_todo_id"] - ) - gate = next( - item - for item in parsed["user_todos"]["items"] - if item["todo_id"] == result["details"]["approval_todo_id"] - ) - assert delivery["status"] == "blocked" - assert ( - delivery["required_decision_scopes"][0]["scope_key"] == "publish-public-fixture" - ) - assert gate["unblocks_todo_id"] == delivery["todo_id"] - assert gate["decision_scope"] == delivery["required_decision_scopes"][0] - assert "Validated fact" not in state.read_text(encoding="utf-8") - - -def test_prepare_preview_has_no_durable_write(tmp_path: Path) -> None: - registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) - state = registry_path.parent.parent / "ACTIVE_GOAL_STATE.md" - before = state.read_text(encoding="utf-8") - - result = prepare_goal_channel_payload( - _request(), - registry_path=registry_path, - runtime_root=runtime_root, - binding_path=binding_path, - target_path=target_path, - goal_id=GOAL_ID, - agent_id=AGENT_ID, - execute=False, - ) - - assert result["status"] == "pending_execution" - assert state.read_text(encoding="utf-8") == before - assert not (runtime_root / "goals" / GOAL_ID / "goal_channel_payloads").exists() - - -def test_delivery_fails_closed_before_exact_approval(tmp_path: Path) -> None: - registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) - prepared = prepare_goal_channel_payload( - _request(), - registry_path=registry_path, - runtime_root=runtime_root, - binding_path=binding_path, - target_path=target_path, - goal_id=GOAL_ID, - agent_id=AGENT_ID, - execute=True, - ) - calls: list[list[str]] = [] - - with pytest.raises(ValueError, match="lacks exact approval"): - deliver_goal_channel_payload( - receipt_id=prepared["receipt_id"], - registry_path=registry_path, - runtime_root=runtime_root, - binding_path=binding_path, - target_path=target_path, - goal_id=GOAL_ID, - execute=True, - runner=_runner(calls), - ) - - assert calls == [] - - -def test_approved_delivery_is_verified_and_exact_replay_is_deduped( - tmp_path: Path, -) -> None: - registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) - prepared = _prepare_and_approve( - registry_path, runtime_root, binding_path, target_path - ) - calls: list[list[str]] = [] - runner = _runner(calls) - - first = deliver_goal_channel_payload( - receipt_id=prepared["receipt_id"], - registry_path=registry_path, - runtime_root=runtime_root, - binding_path=binding_path, - target_path=target_path, - goal_id=GOAL_ID, - execute=True, - runner=runner, - ) - replay = deliver_goal_channel_payload( - receipt_id=prepared["receipt_id"], - registry_path=registry_path, - runtime_root=runtime_root, - binding_path=binding_path, - target_path=target_path, - goal_id=GOAL_ID, - execute=True, - runner=runner, - ) - - assert first["status"] == replay["status"] == "satisfied" - assert first["external_write_performed"] is True - assert replay["external_write_performed"] is False - assert replay["details"]["semantic_dedupe_status"] == "existing_exact_message" - assert len([args for args in calls if "+messages-send" in args]) == 1 - - -def test_prepare_normalizes_agent_id_before_receipt_and_todos(tmp_path: Path) -> None: - registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) - prepared = prepare_goal_channel_payload( - _request(), - registry_path=registry_path, - runtime_root=runtime_root, - binding_path=binding_path, - target_path=target_path, - goal_id=GOAL_ID, - agent_id=" CODEX PUBLIC DELIVERY ", - execute=True, - ) - receipt_path = ( - runtime_root - / "goals" - / GOAL_ID - / "goal_channel_payloads" - / f"{prepared['receipt_id']}.json" - ) - receipt = json.loads(receipt_path.read_text(encoding="utf-8")) - assert receipt["agent_id"] == AGENT_ID - - complete_goal_todo( - registry_path=registry_path, - runtime_root_arg=str(runtime_root), - goal_id=GOAL_ID, - todo_id=prepared["details"]["approval_todo_id"], - role="user", - decision_outcome="approve", - evidence="owner approved the normalized agent fixture", - ) - result = deliver_goal_channel_payload( - receipt_id=prepared["receipt_id"], - registry_path=registry_path, - runtime_root=runtime_root, - binding_path=binding_path, - target_path=target_path, - goal_id=GOAL_ID, - execute=True, - runner=_runner([]), - ) - assert result["status"] == "satisfied" - - -def test_binding_mutation_during_history_scan_fails_before_send(tmp_path: Path) -> None: - registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) - prepared = _prepare_and_approve( - registry_path, runtime_root, binding_path, target_path - ) - calls: list[list[str]] = [] - base_runner = _runner(calls) - - def mutate_during_history( - args: list[str], cwd: Path | None, timeout: float | None - ) -> dict[str, Any]: - result = base_runner(args, cwd, timeout) - if "+chat-messages-list" in args: - binding = read_goal_channel_binding(binding_path) - binding["bindings"][GOAL_ID]["enabled"] = False - write_goal_channel_binding(binding_path, binding) - return result - - with pytest.raises(ValueError, match="Goal Channel delivery"): - deliver_goal_channel_payload( - receipt_id=prepared["receipt_id"], - registry_path=registry_path, - runtime_root=runtime_root, - binding_path=binding_path, - target_path=target_path, - goal_id=GOAL_ID, - execute=True, - runner=mutate_during_history, - ) - - assert not any("+messages-send" in args for args in calls) - - -def test_target_mutation_during_history_scan_fails_before_send(tmp_path: Path) -> None: - registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) - prepared = _prepare_and_approve( - registry_path, runtime_root, binding_path, target_path - ) - calls: list[list[str]] = [] - base_runner = _runner(calls) - - def mutate_during_history( - args: list[str], cwd: Path | None, timeout: float | None - ) -> dict[str, Any]: - result = base_runner(args, cwd, timeout) - if "+chat-messages-list" in args: - targets = json.loads(target_path.read_text(encoding="utf-8")) - targets["targets"]["public-route"]["channel"]["chat_id"] = ( - "oc_changed_fixture" - ) - target_path.write_text(json.dumps(targets), encoding="utf-8") - return result - - with pytest.raises(ValueError, match="Goal Channel delivery binding drifted"): - deliver_goal_channel_payload( - receipt_id=prepared["receipt_id"], - registry_path=registry_path, - runtime_root=runtime_root, - binding_path=binding_path, - target_path=target_path, - goal_id=GOAL_ID, - execute=True, - runner=mutate_during_history, - ) - - assert not any("+messages-send" in args for args in calls) - - -def test_approved_payload_and_route_drift_fail_before_send(tmp_path: Path) -> None: - registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) - prepared = _prepare_and_approve( - registry_path, runtime_root, binding_path, target_path - ) - receipt_path = ( - runtime_root - / "goals" - / GOAL_ID - / "goal_channel_payloads" - / f"{prepared['receipt_id']}.json" - ) - receipt = json.loads(receipt_path.read_text(encoding="utf-8")) - receipt["card"]["header"]["title"]["content"] = "Changed after approval" - receipt_path.write_text(json.dumps(receipt), encoding="utf-8") - calls: list[list[str]] = [] - with pytest.raises(ValueError, match="content drifted"): - deliver_goal_channel_payload( - receipt_id=prepared["receipt_id"], - registry_path=registry_path, - runtime_root=runtime_root, - binding_path=binding_path, - target_path=target_path, - goal_id=GOAL_ID, - execute=True, - runner=_runner(calls), - ) - assert calls == [] - - receipt_path.unlink() - prepared = _prepare_and_approve( - registry_path, runtime_root, binding_path, target_path - ) - binding = read_goal_channel_binding(binding_path) - binding["bindings"][GOAL_ID]["enabled"] = False - write_goal_channel_binding(binding_path, binding) - with pytest.raises(ValueError, match="enabled Lark Goal Channel binding"): - deliver_goal_channel_payload( - receipt_id=prepared["receipt_id"], - registry_path=registry_path, - runtime_root=runtime_root, - binding_path=binding_path, - target_path=target_path, - goal_id=GOAL_ID, - execute=True, - runner=_runner(calls), - ) - assert calls == [] - - -def test_prepare_rejects_non_public_scope_and_mentions(tmp_path: Path) -> None: - registry_path, runtime_root, binding_path, target_path = _fixture(tmp_path) - request = _request() - request["decision_scope"] = "write_scope:action:publish-public-fixture" - with pytest.raises(ValueError, match="public_claim:action"): - prepare_goal_channel_payload( - request, - registry_path=registry_path, - runtime_root=runtime_root, - binding_path=binding_path, - target_path=target_path, - goal_id=GOAL_ID, - agent_id=AGENT_ID, - ) - with pytest.raises(ValueError, match="mention"): - prepare_goal_channel_payload( - _request(markdown='Someone'), - registry_path=registry_path, - runtime_root=runtime_root, - binding_path=binding_path, - target_path=target_path, - goal_id=GOAL_ID, - agent_id=AGENT_ID, - ) diff --git a/tests/extensions/test_lark_event_collector_runtime.py b/tests/extensions/test_lark_event_collector_runtime.py index 96525f88af..ac6a58908b 100644 --- a/tests/extensions/test_lark_event_collector_runtime.py +++ b/tests/extensions/test_lark_event_collector_runtime.py @@ -1,12 +1,19 @@ from __future__ import annotations import json +from pathlib import Path import subprocess +import time +import pytest + +from loopx.extensions.lark import event_collector_runtime +from loopx.extensions.lark.event_collector import plan_lark_event_collector from loopx.extensions.lark.event_collector_runtime import ( _run_json_with_status, enrich_lark_event_reply_context, lark_event_requires_reply_context_lookup, + run_lark_event_collector, ) @@ -105,3 +112,139 @@ def runner(*_args: object, **_kwargs: object) -> subprocess.CompletedProcess[str assert enriched["sender_type"] == "app" assert enriched["sender_id"] == "cli_fixture_bot" + + +def _operation_callback_project(tmp_path: Path) -> tuple[Path, Path]: + project = tmp_path / "project" + project.mkdir() + subprocess.run(["git", "init", "-q", str(project)], check=True) + (project / ".gitignore").write_text(".loopx/\n", encoding="utf-8") + config_root = project / ".loopx" / "config" / "lark" + config_root.mkdir(parents=True) + (config_root / "inbox.json").write_text( + json.dumps( + { + "schema_version": "lark_event_inbox_config_v0", + "enabled": True, + "inbox_dir": ".loopx/inbox/operation", + "capture_scope": "configured_chat_all", + "reply": { + "enabled": True, + "sender_profile": "operation-bot", + "sender_identity": "bot", + "bot_display_name": "Operation Bot", + "chat_id": "oc_operation_fixture", + "placement_policy": "source_context", + "editorial_style": "bullet_points_preferred", + }, + } + ), + encoding="utf-8", + ) + collector = config_root / "collector.json" + collector.write_text( + json.dumps( + { + "schema_version": "lark_event_collector_config_v1", + "enabled": True, + "service_name": "loopx-operation-fixture", + "event_key": "im.message.receive_v1", + "identity": "bot", + "supervisor": "systemd", + "consume_timeout": "30m", + "lark_cli_bin": "lark-cli", + "operation_callbacks": {"enabled": True}, + "routes": [ + { + "route_key": "operation", + "chat_id": "oc_operation_fixture", + "event_inbox_config": ".loopx/config/lark/inbox.json", + } + ], + } + ), + encoding="utf-8", + ) + return project, collector + + +def test_operation_callback_plan_requires_pinned_runtime(tmp_path: Path) -> None: + project, collector = _operation_callback_project(tmp_path) + + plan = plan_lark_event_collector(project=project, config_path=collector) + + assert plan["ok"] is False + assert plan["status"] == "pinned_runtime_required" + assert plan["operation_callbacks_enabled"] is True + assert plan["operation_callback_console_configuration_preflighted"] is False + + +def test_collector_runs_independent_operation_callback_consumer( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + project, collector = _operation_callback_project(tmp_path) + runtime_root = tmp_path / "runtime" + cli = tmp_path / "lark-cli-fixture" + cli.write_text( + "#!/usr/bin/env python3\n" + "import json\n" + "import sys\n" + "import time\n" + "event_key = sys.argv[sys.argv.index('consume') + 1]\n" + "if event_key == 'card.action.trigger':\n" + " print(json.dumps({'type': event_key, 'chat_id': 'oc_operation_fixture'}), flush=True)\n" + " print(json.dumps({'type': event_key, 'chat_id': 'oc_operation_fixture'}), flush=True)\n" + "else:\n" + " time.sleep(0.2)\n", + encoding="utf-8", + ) + cli.chmod(0o755) + captured: list[dict[str, object]] = [] + + def handle(payload: dict[str, object], **kwargs: object) -> dict[str, object]: + captured.append({"payload": payload, **kwargs}) + return { + "ok": len(captured) > 1, + "schema_version": "lark_operation_callback_receipt_v0", + } + + monkeypatch.setattr( + event_collector_runtime, + "handle_goal_channel_operation_callback", + handle, + ) + + def runner(argv: list[str], **_kwargs: object) -> subprocess.CompletedProcess[str]: + assert "whoami" in argv + return subprocess.CompletedProcess( + args=argv, + returncode=0, + stdout=json.dumps({"appId": "cli_operation_fixture"}), + stderr="", + ) + + result = run_lark_event_collector( + project=project, + config_path=collector, + lark_cli_executable=str(cli), + runtime_root=runtime_root, + runner=runner, + ) + + deadline = time.monotonic() + 1 + while not captured and time.monotonic() < deadline: + time.sleep(0.01) + assert result["operation_callback_listener_started"] is True + assert result["operation_callback_received_count"] == 2 + assert result["operation_callback_verified_count"] == 1 + assert captured[0]["runtime_root"] == runtime_root.resolve() + assert captured[0]["action_store_root"] == runtime_root / "chat" / "actions" + status = json.loads( + ( + project / ".loopx/runtime/lark-collector/operation-callback-status.json" + ).read_text(encoding="utf-8") + ) + assert status["callback_delivery_verified"] is True + assert status["failed_callback_count"] == 1 + assert status["listener_active"] is False diff --git a/tests/extensions/test_lark_goal_channel.py b/tests/extensions/test_lark_goal_channel.py index cd505ba107..064ba512d2 100644 --- a/tests/extensions/test_lark_goal_channel.py +++ b/tests/extensions/test_lark_goal_channel.py @@ -2105,7 +2105,7 @@ def capture_doctor(**kwargs: Any) -> dict[str, Any]: assert not (unrelated_two / ".loopx").exists() -def test_cli_prepare_payload_uses_source_registry_runtime( +def test_cli_deliver_operation_uses_source_registry_runtime( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -2131,11 +2131,6 @@ def test_cli_prepare_payload_uses_source_registry_runtime( } ] global_registry_path.write_text(json.dumps(global_registry), encoding="utf-8") - request_path = tmp_path / "payload.json" - request_path.write_text( - json.dumps({"schema_version": "goal_channel_frozen_payload_request_v0"}), - encoding="utf-8", - ) captured: dict[str, Any] = {} printed: dict[str, Any] = {} @@ -2146,14 +2141,13 @@ def test_cli_prepare_payload_uses_source_registry_runtime( ) monkeypatch.setattr(goal_channel_cli, "_binding_target_name", lambda *args: "") - def capture_prepare(request: dict[str, Any], **kwargs: Any) -> dict[str, Any]: + def capture_delivery(**kwargs: Any) -> dict[str, Any]: captured.update(kwargs) - captured["request"] = request return { "ok": True, "goal_id": GOAL_ID, "provider": "lark", - "operation": "prepare_payload", + "operation": "deliver_operation_card", "status": "pending_execution", "execute": False, "external_write_performed": False, @@ -2162,15 +2156,14 @@ def capture_prepare(request: dict[str, Any], **kwargs: Any) -> dict[str, Any]: } monkeypatch.setattr( - goal_channel_cli, "prepare_goal_channel_payload", capture_prepare + goal_channel_cli, "deliver_goal_channel_operation_card", capture_delivery ) result = goal_channel_cli.handle_goal_channel_command( argparse.Namespace( command="goal-channel", - goal_channel_command="prepare-payload", + goal_channel_command="deliver-operation", goal_id=GOAL_ID, - agent_id="codex-public-delivery", - request_json=str(request_path), + proposal_id="proposal-public-fixture", binding_path=None, target_path=None, execute=False, @@ -2185,17 +2178,15 @@ def capture_prepare(request: dict[str, Any], **kwargs: Any) -> dict[str, Any]: assert result == 0 assert printed["ok"] is True - assert captured["registry_path"] == source_registry_path.resolve() - assert captured["runtime_root"] == source_runtime.resolve() + assert captured["proposal_id"] == "proposal-public-fixture" + assert captured["action_store_root"] == source_runtime / "chat" / "actions" + assert captured["runtime_root"] == source_runtime assert captured["binding_path"] == project / ".loopx" / "goal-channel.json" assert ( captured["target_path"] == (source_runtime / "goal-channel-targets.json").resolve() ) - assert captured["agent_id"] == "codex-public-delivery" - assert captured["request"] == { - "schema_version": "goal_channel_frozen_payload_request_v0" - } + assert captured["expected_goal_id"] == GOAL_ID @pytest.mark.parametrize( diff --git a/tests/extensions/test_lark_goal_channel_operation.py b/tests/extensions/test_lark_goal_channel_operation.py new file mode 100644 index 0000000000..76e638b458 --- /dev/null +++ b/tests/extensions/test_lark_goal_channel_operation.py @@ -0,0 +1,777 @@ +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +import hashlib +import json +from pathlib import Path +import threading +from typing import Any + +import pytest + +from loopx.chat_action_store import ActionConflictError, ChatActionStore +from loopx.chat_actions import ChatActionService +from loopx.cli_commands.goal_channel import _prepare_goal_channel_operation +from loopx.extensions.lark.goal_channel_contracts import ( + GOAL_CHANNEL_BINDING_SCHEMA_VERSION, + write_goal_channel_binding, +) +from loopx.extensions.lark.goal_channel_operation import ( + build_goal_channel_operation_card, + deliver_goal_channel_operation_card, + handle_goal_channel_operation_callback, + recover_goal_channel_operation_results, + recover_goal_channel_simulation_claims, +) +from loopx.extensions.lark import goal_channel_operation +from loopx.extensions.lark.goal_channel_targets import add_lark_goal_channel_target + + +GOAL_ID = "goal-operation-card-fixture" +AGENT_ID = "finance-operation-agent" +OPERATOR_ID = "ou_operation_owner" +CHAT_ID = "oc_operation_fixture" +APP_ID = "cli_operation_fixture" +TENANT_KEY = "tenant_operation_fixture" + + +def _digest(value: object) -> str: + return hashlib.sha256( + json.dumps( + value, ensure_ascii=False, sort_keys=True, separators=(",", ":") + ).encode() + ).hexdigest() + + +def _fixture( + tmp_path: Path, +) -> tuple[ChatActionStore, Path, Path, Path, Path]: + project = tmp_path / "project" + project.mkdir() + state = project / "ACTIVE_GOAL_STATE.md" + state.write_text( + f"---\ngoal_id: {GOAL_ID}\n---\n\n## User Todo\n\n## Agent Todo\n", + encoding="utf-8", + ) + runtime_root = tmp_path / "runtime" + registry_path = project / ".loopx" / "registry.json" + registry_path.parent.mkdir() + registry_path.write_text( + json.dumps( + { + "common_runtime_root": str(runtime_root), + "goals": [ + { + "id": GOAL_ID, + "repo": str(project), + "state_file": "ACTIVE_GOAL_STATE.md", + "coordination": {"registered_agents": [AGENT_ID]}, + } + ], + } + ), + encoding="utf-8", + ) + target_path = runtime_root / "goal-channel-targets.json" + add_lark_goal_channel_target( + target_path=target_path, + target_name="operation-route", + chat_id=CHAT_ID, + chat_name="Operation Fixture", + identity_mode="project_bot", + sender_profile="operation-bot", + sender_identity="bot", + bot_app_id=APP_ID, + bot_display_name="Operation Bot", + cli_bin="lark-cli", + execute=True, + ) + binding_path = registry_path.parent / "goal-channel.json" + write_goal_channel_binding( + binding_path, + { + "schema_version": GOAL_CHANNEL_BINDING_SCHEMA_VERSION, + "bindings": { + GOAL_ID: { + "goal_id": GOAL_ID, + "provider": "lark", + "enabled": True, + "agent_id": AGENT_ID, + "target_ref": "operation-route", + "channel": {}, + "identity": {}, + } + }, + }, + ) + store = ChatActionStore(runtime_root / "chat" / "actions") + return store, registry_path, runtime_root, binding_path, target_path + + +def _prepare(store: ChatActionStore, registry_path: Path) -> dict[str, Any]: + payload = { + "schema_version": "finance_order_intent_v0", + "asset": "SYNTH", + "side": "buy", + "quantity": "1.00", + "quantity_unit": "SYNTH", + "order_type": "limit", + "limit_price": "10.00", + "price_unit": "TEST", + "time_in_force": "GTC", + "reduce_only": False, + "maximum_fee": "0.10", + "fee_unit": "TEST", + } + service = ChatActionService(store=store, registry_path=registry_path) + return service.preview( + { + "action_kind": "operation.execute", + "summary": "Confirm one simulated finance order", + "idempotency_key": "operation-card-fixture-v1", + "context": {"kind": "goal", "goal_id": GOAL_ID}, + "normalized_parameters": { + "schema_version": "loopx_operation_request_v0", + "goal_id": GOAL_ID, + "agent_id": AGENT_ID, + "domain": "finance", + "operation_kind": "finance.order.simulate", + "operation_schema": "finance_order_intent_v0", + "payload_ref": "finance-order:operation-card-fixture", + "payload": payload, + "payload_digest": _digest(payload), + "projection": { + "schema_version": "loopx_operation_projection_v0", + "title": "Simulated trade request", + "subtitle": "Synthetic fixture · no venue call", + "focus": "BUY 1.00 SYNTH @ 10.00 TEST", + "fields": [ + {"label": "Order", "value": "Limit · GTC"}, + {"label": "Maximum fee", "value": "0.10 TEST"}, + ], + "warning": ( + "Simulation only. This card cannot submit, sign, or transfer." + ), + "simulated": True, + }, + "destination_account_ref": "account:simulation", + "expires_at": ( + datetime.now(timezone.utc) + timedelta(hours=1) + ).isoformat(), + "authorized_principals": [f"lark:{OPERATOR_ID}"], + "executor": { + "extension_id": "loopx-finance-execution", + "protocol": "finance_operation_executor_v0", + "permission": "finance.operation.simulate", + "revision": "simulator-v0", + }, + }, + } + ) + + +def _runner(calls: list[list[str]], sent_cards: dict[str, dict[str, Any]]): + def run( + args: list[str], _cwd: Path | None, _timeout: float | None + ) -> dict[str, Any]: + calls.append(args) + if "auth" in args and "status" in args: + payload = { + "ok": True, + "appId": APP_ID, + "identities": { + "bot": { + "available": True, + "verified": True, + "appName": "Operation Bot", + } + }, + } + elif "chats" in args and "get" in args: + payload = { + "ok": True, + "data": {"chat_id": CHAT_ID, "tenant_key": TENANT_KEY}, + } + elif "+chat-members-list" in args: + if args[args.index("--member-types") + 1] == "bot": + payload = {"ok": True, "data": {"bots": [{"app_id": APP_ID}]}} + else: + payload = { + "ok": True, + "data": { + "items": [ + { + "member_id": OPERATOR_ID, + "tenant_key": TENANT_KEY, + } + ] + }, + } + elif "+chat-messages-list" in args: + payload = { + "ok": True, + "has_more": False, + "messages": [ + { + "message_id": message_id, + "chat_id": CHAT_ID, + "sender": {"sender_type": "app", "id": APP_ID}, + "deleted": False, + "body": {"content": json.dumps(card)}, + } + for message_id, card in sent_cards.items() + ], + } + elif "+messages-send" in args: + message_id = "om_operation_card_fixture" + sent_cards[message_id] = json.loads(args[args.index("--content") + 1]) + payload = {"ok": True, "data": {"message_id": message_id}} + elif "+messages-mget" in args: + message_id = args[args.index("--message-ids") + 1] + payload = { + "ok": True, + "data": { + "items": [ + { + "message_id": message_id, + "chat_id": CHAT_ID, + "sender": {"sender_type": "app", "id": APP_ID}, + "body": {"content": json.dumps(sent_cards[message_id])}, + } + ] + }, + } + elif "messages" in args and "patch" in args: + message_id = args[args.index("--message-id") + 1] + update = json.loads(args[args.index("--data") + 1]) + sent_cards[message_id] = json.loads(update["content"]) + payload = {"ok": True, "code": 0} + elif any("interactive/v1/card/update" in item for item in args): + update = json.loads(args[args.index("--data") + 1]) + message_id = next(iter(sent_cards)) + sent_cards[message_id] = update["card"] + payload = {"ok": True, "code": 0} + else: # pragma: no cover + raise AssertionError(args) + return {"returncode": 0, "stdout": json.dumps(payload), "stderr": ""} + + return run + + +def _event(proposal: dict[str, Any], card: dict[str, Any]) -> dict[str, Any]: + action = card["body"]["elements"][3]["columns"][0]["elements"][0]["behaviors"][0][ + "value" + ] + return { + "type": "card.action.trigger", + "event_id": "evt_operation_card_fixture", + "timestamp": str(int(datetime.now(timezone.utc).timestamp() * 1000)), + "operator_id": OPERATOR_ID, + "message_id": proposal["operation"]["delivery"]["message_id"], + "chat_id": CHAT_ID, + "host": "im_message", + "token": "callback-token-fixture", + "action_tag": "button", + "action_value": json.dumps(action), + "action_name": "", + "form_value": "", + "card_content": json.dumps(card), + } + + +def test_card_is_one_bounded_non_forwardable_confirmation_projection( + tmp_path: Path, +) -> None: + store, registry, _runtime, _binding, _target = _fixture(tmp_path) + proposal = _prepare(store, registry) + + card = build_goal_channel_operation_card(proposal) + + assert card["schema"] == "2.0" + assert card["config"]["enable_forward"] is False + assert len(card["body"]["elements"]) == 4 + assert card["header"]["icon"]["token"] == "approval_colorful" + buttons = card["body"]["elements"][3]["columns"] + assert buttons[0]["elements"][0]["type"] == "primary_filled" + assert buttons[1]["elements"][0]["type"] == "danger" + assert { + button["elements"][0]["behaviors"][0]["value"]["decision"] for button in buttons + } == {"confirm", "reject"} + + +def test_cli_preparation_previews_without_write_then_persists_canonical_proposal( + tmp_path: Path, +) -> None: + store, registry, runtime, _binding, _target = _fixture(tmp_path) + order = { + "schema_version": "finance_order_intent_v0", + "asset": "SYNTH", + "side": "buy", + "quantity": "1.00", + "quantity_unit": "SYNTH", + "order_type": "limit", + "limit_price": "10.00", + "price_unit": "TEST", + "time_in_force": "GTC", + "reduce_only": False, + "maximum_fee": "0.10", + "fee_unit": "TEST", + } + request_path = tmp_path / "operation.json" + request_path.write_text( + json.dumps( + { + "schema_version": "loopx_operation_request_v0", + "domain": "finance", + "operation_kind": "finance.order.simulate", + "operation_schema": "finance_order_intent_v0", + "payload_ref": "finance-order:cli-fixture", + "payload": order, + "payload_digest": _digest(order), + "projection": { + "schema_version": "loopx_operation_projection_v0", + "title": "Simulated trade request", + "subtitle": "Synthetic fixture", + "focus": "BUY 1 SYNTH @ 10 TEST", + "fields": [{"label": "Order", "value": "Limit · GTC"}], + "warning": "Simulation only.", + "simulated": True, + }, + "destination_account_ref": "account:simulation", + "expires_at": ( + datetime.now(timezone.utc) + timedelta(hours=1) + ).isoformat(), + "authorized_principals": [f"lark:{OPERATOR_ID}"], + "executor": { + "extension_id": "loopx-finance-execution", + "protocol": "finance_operation_executor_v0", + "permission": "finance.operation.simulate", + "revision": "simulator-v0", + }, + } + ), + encoding="utf-8", + ) + preview = _prepare_goal_channel_operation( + registry_path=registry, + runtime_root=runtime, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + summary="Review one simulated order", + idempotency_key="cli-operation-fixture", + request_path=request_path, + execute=False, + ) + assert preview["status"] == "preview_ready" + assert store.list() == [] + + applied = _prepare_goal_channel_operation( + registry_path=registry, + runtime_root=runtime, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + summary="Review one simulated order", + idempotency_key="cli-operation-fixture", + request_path=request_path, + execute=True, + ) + assert applied["status"] == "awaiting_confirmation" + assert applied["details"]["durable_proposal_written"] is True + assert store.load(applied["receipt_id"])["operation"]["lifecycle_state"] == ( + "awaiting_confirmation" + ) + + +def test_delivery_stops_before_provider_write_when_executor_revision_drifted( + tmp_path: Path, +) -> None: + store, registry, runtime, binding, target = _fixture(tmp_path) + proposal = _prepare(store, registry) + calls: list[list[str]] = [] + + with pytest.raises(ActionConflictError, match="executor revision"): + deliver_goal_channel_operation_card( + proposal_id=proposal["proposal_id"], + action_store_root=store.root, + runtime_root=runtime, + binding_path=binding, + target_path=target, + execute=True, + runner=_runner(calls, {}), + executor_binding_resolver=lambda _parameters, _runtime: { + "revision": "different-revision" + }, + ) + + assert calls == [] + + +def test_delivery_callback_simulation_and_replay_share_one_claim( + tmp_path: Path, +) -> None: + store, registry, runtime, binding, target = _fixture(tmp_path) + proposal = _prepare(store, registry) + proposal_id = proposal["proposal_id"] + calls: list[list[str]] = [] + sent_cards: dict[str, dict[str, Any]] = {} + runner = _runner(calls, sent_cards) + + delivered = deliver_goal_channel_operation_card( + proposal_id=proposal_id, + action_store_root=store.root, + runtime_root=runtime, + binding_path=binding, + target_path=target, + execute=True, + runner=runner, + executor_binding_resolver=lambda _parameters, _runtime: { + "revision": "simulator-v0" + }, + ) + assert delivered["status"] == "awaiting_confirmation" + assert delivered["readback_verified"] is True + durable = store.load(proposal_id) + card = sent_cards[durable["operation"]["delivery"]["message_id"]] + event = _event(durable, card) + execution_count = 0 + + def executor(claimed: dict[str, Any]) -> dict[str, Any]: + nonlocal execution_count + execution_count += 1 + operation = claimed["operation"] + return { + "schema_version": "loopx_operation_outcome_v0", + "outcome": "simulated_filled", + "projection_verified": True, + "operation_id": operation["operation_id"], + "payload_digest": operation["payload_digest"], + "claim_id": operation["claim"]["claim_id"], + "executor_revision": operation["executor_revision"], + "summary": "Simulation completed without an external venue write.", + "simulation": True, + "external_write_performed": False, + "observed_at": datetime.now(timezone.utc).isoformat(), + } + + first = handle_goal_channel_operation_callback( + event, + runtime_root=runtime, + action_store_root=store.root, + profile_app_id=APP_ID, + cli_bin="lark-cli", + profile="operation-bot", + runner=runner, + executor=executor, + ) + replay = handle_goal_channel_operation_callback( + event, + runtime_root=runtime, + action_store_root=store.root, + profile_app_id=APP_ID, + cli_bin="lark-cli", + profile="operation-bot", + runner=runner, + executor=executor, + ) + + assert first["outcome"] == replay["outcome"] == "simulated_filled" + assert first["card_update_verified"] is True + assert first["external_write_performed"] is True + assert replay["external_write_performed"] is False + assert execution_count == 1 + assert store.load(proposal_id)["operation"]["lifecycle_state"] == ( + "outcome_observed" + ) + assert store.load(proposal_id)["operation"]["result_delivery"]["transport"] == ( + "callback_update" + ) + + +def test_concurrent_callback_replay_dispatches_the_claim_once(tmp_path: Path) -> None: + store, registry, runtime, binding, target = _fixture(tmp_path) + proposal = _prepare(store, registry) + proposal_id = proposal["proposal_id"] + calls: list[list[str]] = [] + sent_cards: dict[str, dict[str, Any]] = {} + runner = _runner(calls, sent_cards) + deliver_goal_channel_operation_card( + proposal_id=proposal_id, + action_store_root=store.root, + runtime_root=runtime, + binding_path=binding, + target_path=target, + execute=True, + runner=runner, + executor_binding_resolver=lambda _parameters, _runtime: { + "revision": "simulator-v0" + }, + ) + durable = store.load(proposal_id) + assert durable is not None + card = sent_cards[durable["operation"]["delivery"]["message_id"]] + event = _event(durable, card) + entered = threading.Event() + release = threading.Event() + executions = 0 + receipts: list[dict[str, Any]] = [] + failures: list[BaseException] = [] + + def executor(claimed: dict[str, Any]) -> dict[str, Any]: + nonlocal executions + executions += 1 + entered.set() + assert release.wait(timeout=2) + operation = claimed["operation"] + return { + "schema_version": "loopx_operation_outcome_v0", + "outcome": "simulated_filled", + "projection_verified": True, + "operation_id": operation["operation_id"], + "payload_digest": operation["payload_digest"], + "claim_id": operation["claim"]["claim_id"], + "executor_revision": operation["executor_revision"], + "summary": "Simulation completed once.", + "simulation": True, + "external_write_performed": False, + "observed_at": datetime.now(timezone.utc).isoformat(), + } + + def invoke() -> None: + try: + receipts.append( + handle_goal_channel_operation_callback( + event, + runtime_root=runtime, + action_store_root=store.root, + profile_app_id=APP_ID, + cli_bin="lark-cli", + profile="operation-bot", + runner=runner, + executor=executor, + ) + ) + except BaseException as exc: # pragma: no cover - asserted below + failures.append(exc) + + first = threading.Thread(target=invoke) + second = threading.Thread(target=invoke) + first.start() + assert entered.wait(timeout=2) + second.start() + release.set() + first.join(timeout=2) + second.join(timeout=2) + + assert failures == [] + assert executions == 1 + assert len(receipts) == 2 + assert all(receipt["outcome"] == "simulated_filled" for receipt in receipts) + + +def test_callback_does_not_claim_result_delivery_without_native_readback( + tmp_path: Path, +) -> None: + store, registry, runtime, binding, target = _fixture(tmp_path) + proposal = _prepare(store, registry) + calls: list[list[str]] = [] + sent_cards: dict[str, dict[str, Any]] = {} + runner = _runner(calls, sent_cards) + deliver_goal_channel_operation_card( + proposal_id=proposal["proposal_id"], + action_store_root=store.root, + runtime_root=runtime, + binding_path=binding, + target_path=target, + execute=True, + runner=runner, + executor_binding_resolver=lambda _parameters, _runtime: { + "revision": "simulator-v0" + }, + ) + durable = store.load(proposal["proposal_id"]) + assert durable is not None + message_id = durable["operation"]["delivery"]["message_id"] + event = _event(durable, sent_cards[message_id]) + + def stale_update_runner( + args: list[str], cwd: Path | None, timeout: float | None + ) -> dict[str, Any]: + if any("interactive/v1/card/update" in item for item in args): + return { + "returncode": 0, + "stdout": json.dumps({"ok": True, "code": 0}), + "stderr": "", + } + return runner(args, cwd, timeout) + + def executor(claimed: dict[str, Any]) -> dict[str, Any]: + operation = claimed["operation"] + return { + "schema_version": "loopx_operation_outcome_v0", + "outcome": "simulated_filled", + "projection_verified": True, + "operation_id": operation["operation_id"], + "payload_digest": operation["payload_digest"], + "claim_id": operation["claim"]["claim_id"], + "executor_revision": operation["executor_revision"], + "summary": "Simulation completed once.", + "simulation": True, + "external_write_performed": False, + "observed_at": datetime.now(timezone.utc).isoformat(), + } + + receipt = handle_goal_channel_operation_callback( + event, + runtime_root=runtime, + action_store_root=store.root, + profile_app_id=APP_ID, + cli_bin="lark-cli", + profile="operation-bot", + runner=stale_update_runner, + executor=executor, + ) + + assert receipt["ok"] is False + assert receipt["card_update_verified"] is False + assert receipt["external_write_performed"] is True + assert receipt["status"] == "result_delivery_pending" + assert store.load(proposal["proposal_id"])["operation"]["outcome"]["outcome"] == ( + "simulated_filled" + ) + + recovered = recover_goal_channel_operation_results( + action_store_root=store.root, + profile_app_id=APP_ID, + allowed_chat_ids={CHAT_ID}, + cli_bin="lark-cli", + profile="operation-bot", + runner=runner, + ) + + assert recovered == {"attempted": 1, "delivered": 1, "failed": 0} + readback = ChatActionStore(store.root).load(proposal["proposal_id"]) + assert readback["operation"]["result_delivery"]["transport"] == "message_patch" + + +def test_restart_recovers_only_claimed_non_effectful_simulation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + store, registry, runtime, binding, target = _fixture(tmp_path) + proposal = _prepare(store, registry) + calls: list[list[str]] = [] + sent_cards: dict[str, dict[str, Any]] = {} + deliver_goal_channel_operation_card( + proposal_id=proposal["proposal_id"], + action_store_root=store.root, + runtime_root=runtime, + binding_path=binding, + target_path=target, + execute=True, + runner=_runner(calls, sent_cards), + executor_binding_resolver=lambda _parameters, _runtime: { + "revision": "simulator-v0" + }, + ) + durable = store.load(proposal["proposal_id"]) + assert durable is not None + operation = durable["operation"] + store.decide_operation( + proposal["proposal_id"], + decision="confirm", + confirmation={ + "provider": "lark", + "event_id": "evt_restart_simulation_fixture", + "principal": f"lark:{OPERATOR_ID}", + "message_id": operation["delivery"]["message_id"], + "chat_id": CHAT_ID, + "app_id": APP_ID, + "surface_kind": "im_message", + "interaction_kind": "card_button", + "confirmation_digest": operation["confirmation_digest"], + "card_digest": operation["delivery"]["card_digest"], + "confirmed_at": datetime.now(timezone.utc).isoformat(), + }, + ) + + def recovered_executor(claimed: dict[str, Any], *, runtime_root: Path): + assert runtime_root == runtime + claimed_operation = claimed["operation"] + return { + "schema_version": "loopx_operation_outcome_v0", + "outcome": "simulated_filled", + "projection_verified": True, + "operation_id": claimed_operation["operation_id"], + "payload_digest": claimed_operation["payload_digest"], + "claim_id": claimed_operation["claim"]["claim_id"], + "executor_revision": claimed_operation["executor_revision"], + "summary": "Recovered simulation completed without an external write.", + "simulation": True, + "external_write_performed": False, + "observed_at": datetime.now(timezone.utc).isoformat(), + } + + monkeypatch.setattr( + goal_channel_operation, "_execute_claimed_operation", recovered_executor + ) + + first = recover_goal_channel_simulation_claims( + action_store_root=store.root, + runtime_root=runtime, + ) + replay = recover_goal_channel_simulation_claims( + action_store_root=store.root, + runtime_root=runtime, + ) + + assert first == {"attempted": 1, "observed": 1, "failed": 0} + assert replay == {"attempted": 0, "observed": 0, "failed": 0} + readback = ChatActionStore(store.root).load(proposal["proposal_id"]) + assert readback is not None + assert readback["operation"]["lifecycle_state"] == "outcome_observed" + assert readback["operation"]["outcome"]["external_write_performed"] is False + + +def test_forwarded_or_unauthorized_card_cannot_claim(tmp_path: Path) -> None: + store, registry, runtime, binding, target = _fixture(tmp_path) + proposal = _prepare(store, registry) + calls: list[list[str]] = [] + sent_cards: dict[str, dict[str, Any]] = {} + runner = _runner(calls, sent_cards) + deliver_goal_channel_operation_card( + proposal_id=proposal["proposal_id"], + action_store_root=store.root, + runtime_root=runtime, + binding_path=binding, + target_path=target, + execute=True, + runner=runner, + executor_binding_resolver=lambda _parameters, _runtime: { + "revision": "simulator-v0" + }, + ) + durable = store.load(proposal["proposal_id"]) + card = sent_cards[durable["operation"]["delivery"]["message_id"]] + event = _event(durable, card) + + with pytest.raises(ActionConflictError, match="delivered request"): + handle_goal_channel_operation_callback( + {**event, "message_id": "om_forwarded_fixture"}, + runtime_root=runtime, + action_store_root=store.root, + profile_app_id=APP_ID, + cli_bin="lark-cli", + profile="operation-bot", + runner=runner, + executor=lambda _proposal: {}, + ) + with pytest.raises(ActionConflictError, match="not authorized"): + handle_goal_channel_operation_callback( + {**event, "operator_id": "ou_untrusted_fixture"}, + runtime_root=runtime, + action_store_root=store.root, + profile_app_id=APP_ID, + cli_bin="lark-cli", + profile="operation-bot", + runner=runner, + executor=lambda _proposal: {}, + ) diff --git a/tests/extensions/test_lark_goal_channel_targets.py b/tests/extensions/test_lark_goal_channel_targets.py index 185b2587dc..3b517ffba6 100644 --- a/tests/extensions/test_lark_goal_channel_targets.py +++ b/tests/extensions/test_lark_goal_channel_targets.py @@ -154,35 +154,39 @@ def test_shared_target_cli_parses_add_setup_and_bounded_attach() -> None: "goal-second-public-fixture", ] ) - prepare = parser.parse_args( + deliver = parser.parse_args( [ "goal-channel", - "prepare-payload", + "deliver-operation", "--goal-id", GOAL_ID, - "--agent-id", - "codex-public-delivery", - "--request-json", - "payload.json", + "--proposal-id", + "proposal-public-fixture", ] ) - deliver = parser.parse_args( + prepare = parser.parse_args( [ "goal-channel", - "deliver-payload", + "prepare-operation", "--goal-id", GOAL_ID, - "--receipt-id", - "gcp_0123456789abcdef01234567", + "--agent-id", + "finance-agent", + "--summary", + "Review the simulated order", + "--idempotency-key", + "finance-order-fixture", + "--request-json", + "operation.json", ] ) assert target.goal_channel_target_command == "add" assert setup.target == "loopx-dev" assert attach.goal_id == [GOAL_ID, "goal-second-public-fixture"] - assert prepare.agent_id == "codex-public-delivery" - assert prepare.request_json == "payload.json" - assert deliver.receipt_id == "gcp_0123456789abcdef01234567" + assert deliver.proposal_id == "proposal-public-fixture" + assert prepare.agent_id == "finance-agent" + assert prepare.idempotency_key == "finance-order-fixture" bounded = goal_channel_cli._attach_goals( registry={}, diff --git a/tests/test_chat_operation_actions.py b/tests/test_chat_operation_actions.py new file mode 100644 index 0000000000..e428dcc196 --- /dev/null +++ b/tests/test_chat_operation_actions.py @@ -0,0 +1,246 @@ +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +import hashlib +import json +from pathlib import Path + +import pytest + +from loopx.chat_action_store import ActionConflictError, ChatActionStore +from loopx.chat_actions import ChatActionService, ProtectedActionGate + + +GOAL_ID = "goal-operation-fixture" +OPERATOR_ID = "ou_authorized_fixture" + + +def _digest(value: object) -> str: + encoded = json.dumps( + value, ensure_ascii=False, sort_keys=True, separators=(",", ":") + ).encode() + return hashlib.sha256(encoded).hexdigest() + + +def _service(tmp_path: Path) -> tuple[ChatActionService, ChatActionStore]: + project = tmp_path / "project" + project.mkdir() + (project / "ACTIVE_GOAL_STATE.md").write_text( + f"---\ngoal_id: {GOAL_ID}\n---\n\n## User Todo\n\n## Agent Todo\n", + encoding="utf-8", + ) + registry = project / ".loopx" / "registry.json" + registry.parent.mkdir() + registry.write_text( + json.dumps( + { + "goals": [ + { + "id": GOAL_ID, + "repo": str(project), + "state_file": "ACTIVE_GOAL_STATE.md", + "coordination": { + "registered_agents": ["finance-fixture-agent"] + }, + } + ] + } + ), + encoding="utf-8", + ) + store = ChatActionStore(tmp_path / "runtime" / "chat" / "actions") + return ChatActionService(store=store, registry_path=registry), store + + +def _request(*, payload: dict[str, object] | None = None) -> dict[str, object]: + operation_payload = payload or { + "schema_version": "finance_order_intent_v0", + "side": "buy", + "asset": "SYNTH", + "quantity": "1.00", + "order_type": "limit", + "limit_price": "10.00", + "time_in_force": "GTC", + "reduce_only": False, + } + return { + "action_kind": "operation.execute", + "summary": "Confirm one simulated finance order", + "idempotency_key": "operation-fixture-v1", + "context": {"kind": "goal", "goal_id": GOAL_ID}, + "normalized_parameters": { + "schema_version": "loopx_operation_request_v0", + "goal_id": GOAL_ID, + "agent_id": "finance-fixture-agent", + "domain": "finance", + "operation_kind": "finance.order.simulate", + "operation_schema": "finance_order_intent_v0", + "payload_ref": "finance-order:synthetic-1", + "payload": operation_payload, + "payload_digest": _digest(operation_payload), + "projection": { + "schema_version": "loopx_operation_projection_v0", + "title": "Simulated trade request", + "subtitle": "Synthetic fixture · no venue call", + "focus": "BUY 1.00 SYNTH @ 10.00", + "fields": [ + {"label": "Order type", "value": "Limit · GTC"}, + {"label": "Maximum notional", "value": "10.00 TEST"}, + ], + "warning": "Simulation only. This cannot submit, sign, or transfer.", + "simulated": True, + }, + "destination_account_ref": "account:simulation", + "expires_at": (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(), + "authorized_principals": [f"lark:{OPERATOR_ID}"], + "executor": { + "extension_id": "loopx-finance-execution", + "protocol": "finance_operation_executor_v0", + "permission": "finance.operation.simulate", + "revision": "simulator-v0", + }, + }, + } + + +def _delivery(proposal: dict[str, object]) -> dict[str, str]: + operation = proposal["operation"] + assert isinstance(operation, dict) + return { + "provider": "lark", + "message_id": "om_operation_fixture", + "chat_id": "oc_operation_fixture", + "app_id": "cli_operation_fixture", + "binding_digest": "a" * 64, + "card_digest": "b" * 64, + "delivered_at": datetime.now(timezone.utc).isoformat(), + } + + +def _confirmation( + proposal: dict[str, object], *, event_id: str = "evt-operation-1" +) -> dict[str, str]: + operation = proposal["operation"] + assert isinstance(operation, dict) + delivery = operation["delivery"] + assert isinstance(delivery, dict) + return { + "provider": "lark", + "event_id": event_id, + "principal": f"lark:{OPERATOR_ID}", + "message_id": str(delivery["message_id"]), + "chat_id": str(delivery["chat_id"]), + "app_id": str(delivery["app_id"]), + "surface_kind": "group_message_card", + "interaction_kind": "button_callback", + "confirmation_digest": str(operation["confirmation_digest"]), + "card_digest": str(delivery["card_digest"]), + "confirmed_at": datetime.now(timezone.utc).isoformat(), + } + + +def test_operation_preview_arms_one_canonical_gate_and_local_apply_cannot_claim( + tmp_path: Path, +) -> None: + service, store = _service(tmp_path) + + proposal = service.preview(_request()) + + assert proposal["status"] == "gated" + assert proposal["available_transitions"] == ["cancel"] + assert proposal["operation"]["lifecycle_state"] == "awaiting_confirmation" + assert proposal["gate"]["kind"] == "human_operation_confirmation" + with pytest.raises(ProtectedActionGate, match="local apply"): + service.apply(str(proposal["proposal_id"])) + assert store.load(str(proposal["proposal_id"]))["status"] == "gated" + + +def test_operation_digest_change_cannot_reuse_idempotency_key(tmp_path: Path) -> None: + service, _store = _service(tmp_path) + service.preview(_request()) + changed = _request( + payload={ + "schema_version": "finance_order_intent_v0", + "side": "buy", + "asset": "SYNTH", + "quantity": "2.00", + } + ) + + with pytest.raises(ActionConflictError, match="idempotency key"): + service.preview(changed) + + +def test_operation_rejects_non_finite_payload_numbers(tmp_path: Path) -> None: + service, _store = _service(tmp_path) + request = _request(payload={"schema_version": "fixture", "price": float("nan")}) + + with pytest.raises(ValueError, match="JSON"): + service.preview(request) + + +def test_lark_decision_claims_once_and_restart_preserves_outcome( + tmp_path: Path, +) -> None: + service, store = _service(tmp_path) + proposal = service.preview(_request()) + proposal_id = str(proposal["proposal_id"]) + delivered = store.record_operation_delivery( + proposal_id, delivery=_delivery(proposal) + ) + confirmation = _confirmation(delivered) + + forged = {**confirmation, "principal": "lark:ou_untrusted_fixture"} + with pytest.raises(ActionConflictError, match="not authorized"): + store.decide_operation(proposal_id, decision="confirm", confirmation=forged) + + claimed = store.decide_operation( + proposal_id, decision="confirm", confirmation=confirmation + ) + replay = store.decide_operation( + proposal_id, decision="confirm", confirmation=confirmation + ) + assert claimed["operation"]["lifecycle_state"] == "claimed" + assert replay["operation"]["claim"] == claimed["operation"]["claim"] + with pytest.raises(ActionConflictError, match="already consumed"): + store.decide_operation( + proposal_id, + decision="confirm", + confirmation={**confirmation, "event_id": "evt-operation-2"}, + ) + + outcome = { + "schema_version": "loopx_operation_outcome_v0", + "outcome": "simulated_filled", + "projection_verified": True, + "operation_id": proposal_id, + "payload_digest": claimed["operation"]["payload_digest"], + "summary": "Simulation completed without an external write.", + "observed_at": datetime.now(timezone.utc).isoformat(), + "external_write_performed": False, + } + observed = store.observe_operation_outcome(proposal_id, outcome=outcome) + restarted = ChatActionStore(store.root) + + assert observed["status"] == "applied" + assert restarted.load(proposal_id)["operation"]["outcome"] == outcome + assert restarted.observe_operation_outcome(proposal_id, outcome=outcome) == observed + + +def test_reject_is_terminal_without_executor_claim(tmp_path: Path) -> None: + service, store = _service(tmp_path) + proposal = service.preview(_request()) + proposal_id = str(proposal["proposal_id"]) + delivered = store.record_operation_delivery( + proposal_id, delivery=_delivery(proposal) + ) + + rejected = store.decide_operation( + proposal_id, + decision="reject", + confirmation=_confirmation(delivered), + ) + + assert rejected["status"] == "rejected" + assert rejected["operation"]["claim"] is None + assert rejected["operation"]["outcome"]["outcome"] == "rejected_by_operator" diff --git a/tests/test_license_metadata.py b/tests/test_license_metadata.py index 128f407303..e9da9d3b26 100644 --- a/tests/test_license_metadata.py +++ b/tests/test_license_metadata.py @@ -25,7 +25,9 @@ def test_root_license_is_canonical_apache_2_with_historical_notices() -> None: historical_mit = (ROOT / "LICENSE-MIT").read_text(encoding="utf-8") notice = (ROOT / "NOTICE").read_text(encoding="utf-8") - assert historical_mit.startswith("MIT License\n\nCopyright (c) 2026 LoopX contributors") + assert historical_mit.startswith( + "MIT License\n\nCopyright (c) 2026 LoopX contributors" + ) assert "releases through v0.4.7 were distributed under the MIT License" in notice @@ -34,10 +36,12 @@ def test_python_distributions_declare_apache_2() -> None: assert root_project["license"] == "Apache-2.0" assert set(root_project["license-files"]) == {"LICENSE", "NOTICE", "LICENSE-MIT"} - extension_project = _project_metadata( - "packages/loopx-finance-value-discovery/pyproject.toml" - ) - assert extension_project["license"] == "Apache-2.0" + for project_file in ( + "packages/loopx-finance-value-discovery/pyproject.toml", + "packages/loopx-finance-execution/pyproject.toml", + ): + extension_project = _project_metadata(project_file) + assert extension_project["license"] == "Apache-2.0" def test_npm_workspace_metadata_declares_apache_2() -> None: @@ -54,6 +58,8 @@ def test_public_docs_state_the_versioned_transition() -> None: assert "beginning with `v0.4.8`" in licensing assert "through `v0.4.7`" in licensing assert "git commit -s" in contributing - assert (ROOT / "DCO").read_text(encoding="utf-8").startswith( - "Developer Certificate of Origin\nVersion 1.1" + assert ( + (ROOT / "DCO") + .read_text(encoding="utf-8") + .startswith("Developer Certificate of Origin\nVersion 1.1") ) From 77b6548372a89649d5a007ad2e358fe175550000 Mon Sep 17 00:00:00 2001 From: huangruiteng <14976749+huangruiteng@users.noreply.github.com> Date: Mon, 14 Sep 2026 02:55:38 +0800 Subject: [PATCH 6/9] fix(dashboard): retain operation delivery receipts Signed-off-by: huangruiteng <14976749+huangruiteng@users.noreply.github.com> --- .../personal-workspace/channel-timeline.tsx | 2 +- .../personal-workspace/context-drawer.tsx | 14 +- .../src/features/personal-workspace/i18n.tsx | 8 + .../personal-workspace-contract.test.mjs | 2 + .../personal-workspace-page.tsx | 15 +- .../personal-workspace-browser/fixture.mjs | 5 +- .../typed-actions.mjs | 153 ++++++++++++++++++ loopx/web/chat/asset-retention.json | 6 +- .../{index-uHL7gp0q.js => index-LRc2f6MH.js} | 14 +- loopx/web/chat/index.html | 2 +- 10 files changed, 200 insertions(+), 21 deletions(-) rename loopx/web/chat/assets/{index-uHL7gp0q.js => index-LRc2f6MH.js} (74%) diff --git a/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx b/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx index ee083c2e19..9556112dfc 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx @@ -64,7 +64,7 @@ export function ChannelTimeline({ ); } diff --git a/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx b/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx index b7472b5124..8d3f250579 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx @@ -963,17 +963,21 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention {selection.item.actionKind} · {selection.item.status}

{selection.item.title}

{selection.item.impact}

- {selection.item.reviewPlan ?

{t(`actionReview.${selection.item.reviewPlan.reason}`)}

: null} + {selection.item.reviewPlan ?

{selection.item.actionKind === "operation.execute" && selection.item.status === "gated" + ? t("actionReview.operation_group_confirmation") + : selection.item.actionKind === "operation.execute" && selection.item.reviewPlan.reason === "readback_unverified" + ? t("actionReview.operation_result_delivery_pending") + : t(`actionReview.${selection.item.reviewPlan.reason}`)}

: null} {selection.item.status === "ready" ?

{t("drawer.proposalExplainer")}

: null}
{selection.item.fields.map((field) =>
{field.label}
{field.value}
)}
- {selection.item.status === "applied" ?

{t("drawer.proposalApplied")}

: null} - {selection.item.status === "applied" && selection.item.goalId ? : null} + {selection.item.status === "applied" ?

{selection.item.actionKind === "operation.execute" ? selection.item.primaryLabel : t("drawer.proposalApplied")}

: null} + {selection.item.status === "applied" && selection.item.actionKind !== "operation.execute" && selection.item.goalId ? : null} {selection.item.status === "stale" ?

{t("drawer.proposalStale")}

: null} {selection.item.status === "error" ?
{selection.item.reviewPlan?.reason === "readback_unverified" ? t("actionReview.readback_unverified") : t("drawer.proposalApplyFailed")}{selection.item.errorMessage ? {selection.item.errorMessage} : null}{t("drawer.proposalApplyFailedHint")}
: null} {selection.item.status === "rejected" ?

{t("drawer.proposalRejected")}

: null} {selection.item.status === "deferred" ?

{t("drawer.proposalDeferred")}

: null} - {selection.item.status === "gated" ?
{t("drawer.gateRequiresHost")}{t("drawer.gateRequiresHostDescription")}{selection.item.gate?.nextAction ? {selection.item.gate.nextAction} : null}
: null} + {selection.item.status === "gated" ?
{selection.item.actionKind === "operation.execute" ? selection.item.primaryLabel : t("drawer.gateRequiresHost")}{selection.item.actionKind === "operation.execute" ? selection.item.impact : t("drawer.gateRequiresHostDescription")}{selection.item.gate?.nextAction ? {selection.item.gate.nextAction} : null}
: null} {selection.item.status === "gated" && selection.item.actionKind === "gate.resolve" ? (() => { const fieldValue = (key: string) => selection.item.fields.find((field) => field.key === key)?.value; const gateGoalId = fieldValue("goal_id"); @@ -988,7 +992,7 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention ); })() : null} {!readOnly && selection.item.workspaceCandidates?.length ?
{selection.item.workspaceCandidates.map((candidate) => )}
: null} - {!readOnly && selection.item.status === "error" ? : !readOnly && selection.item.status !== "gated" ? : null} + {!readOnly && selection.item.actionKind !== "operation.execute" && selection.item.status === "error" ? : !readOnly && selection.item.actionKind !== "operation.execute" && selection.item.status !== "gated" ? : null} {!readOnly && selection.item.actionKind !== "operation.execute" && (["stale", "gated", "rejected"].includes(selection.item.status) || (selection.item.status === "ready" && selection.item.reviewPlan?.canApply === false)) ? : null} {!readOnly && selection.item.actionKind !== "operation.execute" && ["ready", "gated"].includes(selection.item.status) ?
: null} {!["applied", "applying"].includes(selection.item.status) ? : null} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx b/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx index 2366d39dc8..22764679fc 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx @@ -652,6 +652,8 @@ const en = { "actionReview.apply_pending": "Execution is in progress. Wait for its result before retrying.", "actionReview.readback_verified": "The action completed and its resulting state was verified.", "actionReview.readback_unverified": "The action returned without verified readback. Completion is not confirmed; recheck the state.", + "actionReview.operation_group_confirmation": "This exact request can only be confirmed on its original card in the bound Feishu group. The Dashboard does not expose a local execution control.", + "actionReview.operation_result_delivery_pending": "The operation outcome was recorded, but the original group result card has not passed readback verification yet.", "actionReview.apply_failed": "Execution did not complete. Check the failure and regenerate the preview before retrying.", "actionReview.inactive_proposal": "This proposal is no longer ready to execute. Recheck it before continuing.", "proposal.gate.default": "Host confirmation required", @@ -669,6 +671,8 @@ const en = { "proposal.primary.lifecycleStop": "Stop Goal", "proposal.primary.todoStart": "Create task and start execution", "proposal.primary.operationGroup": "Confirm in Feishu group", + "proposal.primary.operationResultPending": "Result card delivery pending", + "proposal.primary.operationResultVerified": "Verified result", "proposal.resultDelivery.verified": "Verified in the original group card", "proposal.resultDelivery.pending": "Pending verified return to the original group card", "proposal.summary.goalCreate": "Create Goal: {title}", @@ -1634,6 +1638,8 @@ const zhCN: Record = { "actionReview.apply_pending": "正在执行,请等待读回结果后再重试。", "actionReview.readback_verified": "操作已完成,结果状态已通过读回验证。", "actionReview.readback_unverified": "操作返回但未通过读回验证。尚不能确认完成,请重新检查状态。", + "actionReview.operation_group_confirmation": "这份精确请求只能在已绑定飞书群的原始卡片确认;Dashboard 不提供本地执行入口。", + "actionReview.operation_result_delivery_pending": "操作结果已经记录,但原群结果卡尚未通过回读核验。", "actionReview.apply_failed": "执行未完成。请检查失败原因并重新生成预览后再试。", "actionReview.inactive_proposal": "此提案当前不可执行。请重新检查后再继续。", "proposal.gate.default": "需要宿主确认", @@ -1651,6 +1657,8 @@ const zhCN: Record = { "proposal.primary.lifecycleStop": "停止 Goal", "proposal.primary.todoStart": "创建任务并开始执行", "proposal.primary.operationGroup": "前往飞书群确认", + "proposal.primary.operationResultPending": "结果卡回传待恢复", + "proposal.primary.operationResultVerified": "结果已核验", "proposal.resultDelivery.verified": "已在原群卡片完成回读核验", "proposal.resultDelivery.pending": "等待回传并核验原群卡片", "proposal.summary.goalCreate": "创建 Goal:{title}", diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs index 29c876535d..f9741f7bdd 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs +++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs @@ -98,6 +98,8 @@ assert.doesNotMatch(page.match(/function operationProposalFields[\s\S]*?\n\}/)?. assert.match(page, /t\("proposal\.primary\.operationGroup"\)/, "Operation confirmation routes users to the bound group"); assert.match(chatData, /result_delivery:/, "Dashboard retains operation result-delivery readback"); assert.match(actionReview, /operation\.execute" \|\| proposal\.operation\?\.result_delivery != null/, "An operation is not complete in the Dashboard until result delivery is verified"); +assert.match(page, /operation\.execute" && proposal\.status === "applied"/, "Dashboard restores terminal operation receipts from the canonical action store"); +assert.match(page, /proposal\.action_kind !== "operation\.execute"[\s\S]*reviewPlan\.interaction !== "completed"/, "Pending operation result-card readback remains visible instead of becoming a generic apply error"); assert.match(drawer, /selection\.item\.actionKind !== "operation\.execute"/, "Dashboard hides generic local controls for authenticated group operations"); assert.match(dashboard, /response\.protected_action/, "Agent semantic protected intent is projected only after the Chat response"); assert.match(dashboard, /normalizedMessage\.includes\(normalizedTarget\)/, "A model-invented protected target cannot reach typed preview"); diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx index 6e14af85f2..0970c4a94e 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx @@ -600,7 +600,11 @@ function workspaceProposal(proposal: TypedActionProposal, t: WorkspaceTranslate) summary: String(proposal.gate.summary ?? t("proposal.gate.default")), } : undefined, primaryLabel: proposal.action_kind === "operation.execute" - ? t("proposal.primary.operationGroup") + ? proposal.operation?.lifecycle_state === "outcome_observed" + ? proposal.operation.result_delivery + ? t("proposal.primary.operationResultVerified") + : t("proposal.primary.operationResultPending") + : t("proposal.primary.operationGroup") : proposal.action_kind === "goal.create" ? t("proposal.primary.goalCreate") : proposal.action_kind === "goal.lifecycle" && lifecycleOperation === "stop" ? t("proposal.primary.lifecycleStop") @@ -611,7 +615,11 @@ function workspaceProposal(proposal: TypedActionProposal, t: WorkspaceTranslate) : proposal.action_kind === "todo.create" && proposal.normalized_parameters.start_execution === true ? t("proposal.primary.todoStart") : t("proposal.primary.apply"), - status: proposal.status === "applied" && reviewPlan.interaction !== "completed" ? "error" : proposalStatus(proposal.status), + status: proposal.status === "applied" + && proposal.action_kind !== "operation.execute" + && reviewPlan.interaction !== "completed" + ? "error" + : proposalStatus(proposal.status), title: localizedSummary, }; } @@ -1050,7 +1058,8 @@ export function PersonalWorkspacePage({ .then((stored) => { if (cancelled) return; const restored = Object.fromEntries(stored - .filter((proposal) => ["ready", "gated", "deferred", "applying"].includes(proposal.status)) + .filter((proposal) => ["preview_ready", "gated", "deferred", "applying"].includes(proposal.status) + || (proposal.action_kind === "operation.execute" && proposal.status === "applied")) .map((proposal) => { const projected = workspaceProposal(proposal, t); return [projected.previewId, projected]; diff --git a/examples/personal-workspace-browser/fixture.mjs b/examples/personal-workspace-browser/fixture.mjs index 69a52aa7fc..17e051c67e 100644 --- a/examples/personal-workspace-browser/fixture.mjs +++ b/examples/personal-workspace-browser/fixture.mjs @@ -288,13 +288,16 @@ function filterStatusFixtureToScope(fixture, statusGeneration, scope) { } } -export async function installApi(page, { goalSubagentConfigurationEnabled = true } = {}) { +export async function installApi(page, { goalSubagentConfigurationEnabled = true, initialActionProposals = [] } = {}) { let turnCounter = 0; const runtime = page.__loopxRuntime ??= { actionProposals: new Map(), goalSubagentConfigurations: new Map(), larkConnections: [], messages: new Map(), sessions: new Map(), turnMessages: new Map() }; const actionProposals = runtime.actionProposals; const sessions = runtime.sessions; const messages = runtime.messages; const turnMessages = runtime.turnMessages; + for (const proposal of initialActionProposals) { + actionProposals.set(proposal.proposal_id, structuredClone(proposal)); + } // Like ChatStore, persist completion before serving it and replay after disconnect. const completedTurns = runtime.completedTurns ??= new Map(); const finishTurn = (sessionId, turnId, answer, protectedAction = null) => { diff --git a/examples/personal-workspace-browser/typed-actions.mjs b/examples/personal-workspace-browser/typed-actions.mjs index 7900643136..c2afd3f718 100644 --- a/examples/personal-workspace-browser/typed-actions.mjs +++ b/examples/personal-workspace-browser/typed-actions.mjs @@ -7,9 +7,162 @@ import { } from "./fixture.mjs"; import { openWorkspacePage } from "./scenario-context.mjs"; +function operationProposal({ id, title, lifecycleState, status, resultDelivery = null }) { + const outcomeObserved = lifecycleState === "outcome_observed"; + return { + schema_version: "loopx_chat_action_proposal_v1", + proposal_id: id, + action_kind: "operation.execute", + summary: title, + normalized_parameters: { + goal_id: "product-release", + payload: { private_fixture_marker: "must-not-render" }, + authorized_principals: ["lark:ou_private_fixture"], + projection: { + schema_version: "loopx_operation_projection_v0", + title, + subtitle: "Synthetic finance simulator", + focus: "BUY 1 SYNTH @ 10 TEST", + fields: [ + { label: "Order", value: "Limit · GTC" }, + { label: "Maximum fee", value: "0.10 TEST" }, + ], + warning: "Simulation only. No venue, signer, wallet, or transfer authority.", + simulated: true, + }, + }, + context: { kind: "goal", goal_id: "product-release" }, + expected_state_fingerprint: "fixture-operation-r1", + permission_classification: "protected", + validation_evidence: ["synthetic operation fixture"], + available_transitions: [], + status, + receipt: outcomeObserved ? { projection_verified: true, receipt_id: `${id}-outcome` } : null, + stale: null, + gate: status === "gated" ? { + kind: "human_confirmation_required", + summary: "Confirm the exact request in the bound Feishu group.", + next_action: "Use the original non-forwardable group card.", + } : null, + operation: { + schema_version: "loopx_operation_envelope_v0", + lifecycle_state: lifecycleState, + operation_id: id, + confirmation_digest: "a".repeat(64), + payload_digest: "b".repeat(64), + projection_digest: "c".repeat(64), + expires_at: "2026-09-15T10:00:00Z", + delivery: { provider: "lark", message_id: `${id}-message` }, + confirmation: outcomeObserved ? { provider: "lark" } : null, + claim: outcomeObserved ? { claim_id: `${id}-claim` } : null, + outcome: outcomeObserved ? { + schema_version: "loopx_operation_outcome_v0", + outcome: "simulated_filled", + projection_verified: true, + simulation: true, + external_write_performed: false, + } : null, + result_delivery: resultDelivery, + }, + created_at: "2026-09-14T01:00:00Z", + updated_at: "2026-09-14T01:00:01Z", + }; +} + export const typedActionsScenario = { id: "typed-actions", async run({ browser, collectCoverage, url }) { + const operationUi = await openWorkspacePage(browser, url, { + apiOptions: { + initialActionProposals: [ + operationProposal({ + id: "operation-awaiting-confirmation", + title: "Simulated order awaiting group confirmation", + lifecycleState: "awaiting_confirmation", + status: "gated", + }), + operationProposal({ + id: "operation-result-pending", + title: "Simulation result awaiting card readback", + lifecycleState: "outcome_observed", + status: "applied", + }), + operationProposal({ + id: "operation-result-verified", + title: "Verified simulated order result", + lifecycleState: "outcome_observed", + status: "applied", + resultDelivery: { + provider: "lark", + message_id: "operation-result-verified-message", + transport: "callback_update", + }, + }), + ], + }, + }); + try { + const { page } = operationUi; + await page.locator(".personal-goal-link", { hasText: "Product Release" }).click(); + await page.locator(".personal-goal-tabs button", { hasText: "Chat" }).click(); + + const pendingResult = page.locator(".personal-proposal-row", { + hasText: "Simulation result awaiting card readback", + }); + try { + await pendingResult.waitFor({ state: "visible" }); + } catch (error) { + throw new Error(`${error.message}; errors=${operationUi.errors.join(" | ")}; proposals=${await page.locator(".personal-proposal-row").allInnerTexts()}; body=${(await page.locator("body").innerText()).slice(0, 2000)}`); + } + if (!(await pendingResult.innerText()).includes("结果卡回传待恢复")) { + throw new Error("Pending result did not disclose unverified card delivery"); + } + await pendingResult.click(); + const pendingDrawer = page.locator('.personal-context-drawer[data-context-kind="proposal"]'); + await pendingDrawer.getByText("等待回传并核验原群卡片", { exact: true }).waitFor({ state: "visible" }); + const pendingText = await pendingDrawer.innerText(); + for (const privateValue of ["must-not-render", "ou_private_fixture"]) { + if (pendingText.includes(privateValue)) throw new Error(`Operation projection leaked ${privateValue}`); + } + if (await pendingDrawer.getByRole("button", { name: /重新生成|确认并应用|拒绝/ }).count()) { + throw new Error("Pending group operation exposed a local mutation control"); + } + await page.screenshot({ path: resolve(outputDir, "operation-result-pending.png"), fullPage: false, animations: "disabled" }); + await page.getByRole("button", { name: /关闭详情/ }).click(); + + const verifiedResult = page.locator(".personal-proposal-row", { + hasText: "Verified simulated order result", + }); + await verifiedResult.waitFor({ state: "visible" }); + if (!(await verifiedResult.innerText()).includes("结果已核验")) { + throw new Error("Verified result lost its exact delivery status"); + } + await verifiedResult.click(); + const verifiedDrawer = page.locator('.personal-context-drawer[data-context-kind="proposal"]'); + await verifiedDrawer.getByText("已在原群卡片完成回读核验", { exact: true }).waitFor({ state: "visible" }); + await page.screenshot({ path: resolve(outputDir, "operation-result-verified.png"), fullPage: false, animations: "disabled" }); + await page.getByRole("button", { name: /关闭详情/ }).click(); + + const gatedSummary = page.locator(".personal-gated-summary"); + await gatedSummary.locator("summary").click(); + const awaiting = gatedSummary.locator(".personal-proposal-row", { + hasText: "Simulated order awaiting group confirmation", + }); + await awaiting.waitFor({ state: "visible" }); + if (!(await awaiting.innerText()).includes("前往飞书群确认")) { + throw new Error("Awaiting operation did not route confirmation to Feishu"); + } + await awaiting.click(); + const awaitingDrawer = page.locator('.personal-context-drawer[data-context-kind="proposal"]'); + await awaitingDrawer.getByText("前往飞书群确认", { exact: true }).waitFor({ state: "visible" }); + if (await awaitingDrawer.getByRole("button", { name: /确认并应用|拒绝|稍后处理|重新生成/ }).count()) { + throw new Error("Awaiting group operation exposed a local decision control"); + } + await page.screenshot({ path: resolve(outputDir, "operation-awaiting-group-confirmation.png"), fullPage: false, animations: "disabled" }); + } finally { + await operationUi.close(); + } + // Real Goal button -> typed preview -> compiler -> drawer/apply, with only // the service boundary controlled. No test computes the plan under review. for (const width of [1512, 390]) { diff --git a/loopx/web/chat/asset-retention.json b/loopx/web/chat/asset-retention.json index 70e0fdb28d..be817d91ab 100644 --- a/loopx/web/chat/asset-retention.json +++ b/loopx/web/chat/asset-retention.json @@ -13,8 +13,8 @@ "assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2", "assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2", "assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2", - "assets/index-8CALBIjN.js", - "assets/index-B7B_kVDP.css" + "assets/index-B7B_kVDP.css", + "assets/index-LRc2f6MH.js" ], [ "assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2", @@ -29,7 +29,7 @@ "assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2", "assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2", "assets/index-B7B_kVDP.css", - "assets/index-uHL7gp0q.js" + "assets/index-8CALBIjN.js" ] ] } diff --git a/loopx/web/chat/assets/index-uHL7gp0q.js b/loopx/web/chat/assets/index-LRc2f6MH.js similarity index 74% rename from loopx/web/chat/assets/index-uHL7gp0q.js rename to loopx/web/chat/assets/index-LRc2f6MH.js index aaa77a41f1..70d570d21c 100644 --- a/loopx/web/chat/assets/index-uHL7gp0q.js +++ b/loopx/web/chat/assets/index-LRc2f6MH.js @@ -25,7 +25,7 @@ Notification: Only notify me when needed`,"composer.heartbeatTemplateWithoutGoal Goal: Frequency: Daily Stop condition: Goal completes -Notification: Only notify me when needed`,"composer.nextAction":`Ask what’s next`,"composer.nextActionPrompt":`What should I do next?`,"composer.prepareDraft":`Insert a draft and review before sending`,"composer.send":`Send`,"composer.sendMessage":`Send a message to LoopX`,"composer.sendMessageHint":`Send message`,"composer.sentImageAlt":`Remove image {name}`,"conversation.agentPending":`Working…`,"conversation.close":`Close conversation receipt`,"conversation.convertHint":`Turn the Agent’s latest reply into a Task draft`,"conversation.full":`View full conversation`,"conversation.receipt":`Conversation receipt`,"conversation.replying":`Replying`,"conversation.title":`Manager conversation`,"conversation.toTask":`Convert to Task`,"digest.away":`Runs since your previous visit`,"digest.completed":`new completions`,"digest.failed":`new failed/interrupted runs`,"digest.needsYou":`currently need confirmation`,"feedback.applying":`Running: {title}`,"feedback.cancelFailed":`Cancel failed: {error}`,"feedback.completed":`Completed: {title}`,"feedback.executionFailed":`Execution failed: {error}`,"feedback.gateRequired":`Your confirmation is required: {summary}`,"feedback.notCompleted":`Not completed: {status}`,"feedback.goalRefreshFailed":`The Goal opened, but its latest state could not be refreshed. Use Refresh to try again.`,"feedback.preparingPreview":`Preparing confirmation preview: {title}`,"feedback.previewFailed":`Could not prepare the confirmation preview: {error}`,"feedback.sendFailed":`Send failed: {error}`,"feedback.sendGenericError":`Could not send the message. Try again later.`,"feedback.stale":`State changed, so nothing was applied. Generate a new confirmation preview.`,"feedback.taskDraftCreated":`Created a Task draft from the reply. Edit and send it to review the confirmation preview.`,"goal.defaultTitle":`New personal Goal`,"goal.initialTodo":`Work toward the completion criteria: {criteria}`,"goal.objectiveBoundary":`Execution boundary: {boundary}`,"goal.objectiveCompletion":`Completion criteria: {criteria}`,"drawer.advancedDiagnostics":`Advanced diagnostics`,"drawer.agentWorking":`Agent is continuing; the record updates automatically.`,"drawer.analysis":`Analyzing`,"drawer.apply":`Confirm and apply`,"drawer.applying":`Applying…`,"drawer.attentionBlocking":`Blocking an Agent`,"drawer.attentionWaiting":`Waiting for your decision`,"drawer.autoNotify":`Human-gate auto notifications`,"drawer.branch":`Branch`,"drawer.closeDetail":`Close details and return to {context}`,"drawer.connected":`Connected`,"drawer.correctionDescription":`The message keeps the current Goal, Todo, and Agent Session context.`,"drawer.correctionLabel":`Guide {agent}`,"drawer.correctionPlaceholder":`For example: focus on permission risks first and do not commit yet…`,"drawer.correctionSend":`Send guidance`,"drawer.correctionTextarea":`Enter guidance for Goal {goal}, Agent {agent}, Run {run}`,"drawer.copyRepository":`Copy repository identity`,"drawer.copyRepositoryDone":`Repository identity copied`,"drawer.copyRepositoryError":`Copy failed. Check browser clipboard permission.`,"drawer.copyRepositorySuccess":`Copied. You can paste it into another tool.`,"drawer.cost":`Cost 24h / 7d`,"drawer.costShort":`Cost`,"drawer.durationShort":`Duration`,"drawer.period24h":`24h`,"drawer.period7d":`7d`,"drawer.tokens":`Tokens 24h / 7d`,"drawer.tokensShort":`tokens`,"drawer.usageNotMeasured":`Not measured`,"drawer.currentGoal":`Current Goal`,"attentionDetail.title":`Request details`,"attentionDetail.request":`What is requested`,"attentionDetail.decision":`Decision requested`,"attentionDetail.unknownRequest":`Not specified; review the source before deciding`,"attentionDetail.open":`Open in current projection`,"attentionDetail.closed":`Closed`,"attentionDetail.deferred":`Deferred`,"attentionDetail.superseded":`Replaced`,"attentionDetail.unknown":`Status not provided`,"attentionDetail.unavailable":`The source has not confirmed this item; refresh before acting`,"attentionDetail.unknownReason":`The source has not provided a reason.`,"attentionDetail.targetTodo":`Linked Todo to unblock`,"attentionDetail.targetAgent":`Agent named by the request`,"attentionDetail.scope":`Declared decision scope`,"attentionDetail.notProvided":`Not provided`,"attentionDetail.replacement":`Replacement Todo`,"attentionDetail.openReplacement":`Open replacement`,"attentionDetail.boundary":`Reading this detail does not resolve a gate or grant authority. Available decisions require a fresh preview.`,"drawer.decisionDefaultEvidence":`No additional public-safe evidence is attached. The next step will still show a Preview first.`,"drawer.decisionDefaultReason":`This decision affects the next step of the current Todo.`,"drawer.decisionDefer":`Decide later`,"drawer.decisionMore":`More decisions`,"drawer.decisionReject":`Reject`,"drawer.decisionReview":`Review impact and decide`,"drawer.dependencies":`Dependencies`,"drawer.detailsAndActions":`Details & actions`,"drawer.duration":`Duration 24h / 7d`,"drawer.evidence":`Evidence`,"drawer.executionHistory":`Execution history`,"drawer.executionRecord":`Run record`,"drawer.executionRecordAndResult":`Execution & result`,"drawer.explainDecision":`Explain this decision`,"drawer.gateApproveHint":`Run one command in the terminal to complete approval:`,"drawer.gateRejectHint":`Replace approve with reject at the end to decline. This notice disappears after the command runs.`,"drawer.gateRequiresHost":`Host confirmation required`,"drawer.gateRequiresHostDescription":`This page cannot approve this protected permission change. Nothing was written by your click.`,"drawer.goalAutoRun":`Automatic runs for this Goal`,"drawer.goalChanges":`Pending changes for this Goal`,"drawer.goalDetails":`Goal details`,"drawer.group":`Group`,"drawer.inspectorFull":`Switch to full screen`,"drawer.inspectorFullView":`Full-screen view`,"drawer.inspectorHalf":`Switch to half screen`,"drawer.inspectorHalfView":`Half-screen view`,"drawer.lastNotification":`Latest notification`,"drawer.larkConfigure":`Configure Lark connection`,"drawer.larkConnect":`Connect Lark App`,"drawer.larkConnection":`Lark connection`,"drawer.larkNotConfigured":`Not configured`,"drawer.larkNotConfiguredDescription":`After setup, LoopX sends a Feishu notification when this Goal needs your confirmation.`,"drawer.managerChanges":`Pending Manager changes`,"drawer.moreActions":`More actions`,"drawer.moreRunActions":`More run actions`,"drawer.nextTransition":`Next transition`,"drawer.noExecutionHistory":`No execution history yet.`,"drawer.noRun":`Execution Session has not started`,"drawer.noRunDescription":`Run records will appear here after an Agent starts execution.`,"drawer.notAssigned":`Unassigned`,"drawer.notLinked":`Not linked`,"drawer.notSet":`Not set`,"drawer.outputDetails":`Output details`,"drawer.outputRecorded":`This output is recorded on the current Goal.`,"drawer.outputSafePreview":`Public-safe output preview`,"drawer.outputRun":`Run`,"drawer.outputTodo":`Todo`,"drawer.outputs":`Outputs from this run`,"drawer.previewUnavailable":`No public-safe inline preview is available for this output.`,"drawer.priority":`Priority`,"drawer.progress":`Progress`,"drawer.proposalApplied":`Applied. LoopX state will refresh.`,"drawer.proposalApplyFailed":`Apply failed. No changes were written.`,"drawer.proposalApplyFailedHint":`Refresh the Goal state and regenerate. If it still fails, keep this page open and inspect advanced diagnostics.`,"drawer.proposalClose":`Close`,"drawer.proposalDefer":`Later`,"drawer.proposalDeferred":`Deferred. You can apply it later or regenerate it.`,"drawer.proposalEnterGoal":`Open new Goal`,"drawer.proposalExplainer":`After confirmation, LoopX applies this change and shows the write result. Closing or canceling changes nothing.`,"drawer.proposalRecheck":`Recheck against latest state`,"drawer.proposalRegenerate":`Retry with latest state`,"drawer.proposalRejected":`Rejected. This change will not be written.`,"drawer.proposalStale":`Source state changed. Recheck against the latest state.`,"drawer.proposalViewGoal":`View updated Goal`,"drawer.reassign":`Reassign to`,"drawer.reassignSummary":`Reassign: {task}`,"drawer.reason":`Reason`,"drawer.recoveryDescription":`Local history is preserved. Choose a recovery path.`,"drawer.recoveryFailed":`Upstream Session recovery failed`,"drawer.recoveryNewSession":`Start a new Session with context`,"drawer.recoveryRetry":`Retry recovery`,"drawer.repositoryRole":`Execution workspace`,"drawer.repository":`Repository`,"drawer.replyMode":`Reply mode`,"drawer.subagentApplied":`Applied and verified against the shared Goal state.`,"drawer.subagentAppliedRefreshFailed":`Applied and verified. The status view could not refresh; retry the page refresh later.`,"drawer.subagentApplying":`Applying and verifying shared-state readback…`,"drawer.subagentApplyFailed":`Could not apply the sub-agent setting.`,"drawer.subagentChildLimit":`Current limit`,"drawer.subagentConfirmDisable":`Confirm turning off sub-agent execution`,"drawer.subagentConfirmEnable":`Confirm turning on sub-agent execution`,"drawer.subagentCurrentBoundary":`Current task-domain restriction`,"drawer.subagentDescription":`Allows the runtime to create temporary child agents for independent tasks only after Todo, quota, capability, and write-scope gates pass. It does not force parallel work or grant durable authority.`,"drawer.subagentDisable":`Preview turning off sub-agent execution`,"drawer.subagentDisableSummary":`New child-agent execution will be disabled for this Goal. Existing Todo ownership and execution records stay unchanged.`,"drawer.subagentDomainInvalid":`The selected task-domain restriction is invalid.`,"drawer.subagentDomainTodoCount":`{count} matching open Todos`,"drawer.subagentDomains":`Task-domain restriction (optional)`,"drawer.subagentDomainsEmpty":`No open advancement Todo declares task_domain. Leave this empty to keep child execution unrestricted by task domain.`,"drawer.subagentDomainsHint":`Leave every option clear to apply no task-domain filter. Selecting domains admits only matching typed Todos; all other execution gates still apply.`,"drawer.subagentDomainsUnrestricted":`No task-domain restriction`,"drawer.subagentEnable":`Preview turning on sub-agent execution`,"drawer.subagentLabel":`Per-Goal execution boundary`,"drawer.subagentModel":`Child model`,"drawer.subagentEffort":`Child reasoning effort`,"drawer.subagentModelDefault":`Host default`,"drawer.subagentLunaPreset":`Use Luna / max`,"drawer.subagentClearModel":`Clear model preference`,"drawer.subagentModelHint":`Use Preview configuration update to save this preference. It can be saved while execution is off; host support is checked at launch.`,"drawer.subagentModelRequired":`Choose a child model before setting reasoning effort.`,"drawer.subagentMaxChildren":`Maximum child agents`,"drawer.subagentNoChange":`The current Goal already matches this setting; nothing was written.`,"drawer.subagentPending":`Pending confirmation`,"drawer.subagentPreviewBoundary":`Preview configuration update`,"drawer.subagentPreviewFailed":`Could not create the sub-agent setting preview.`,"drawer.subagentPreviewing":`Checking the latest Goal state…`,"drawer.subagentPreviewReady":`Preview locked. Confirm to apply this Goal setting.`,"drawer.subagentPreviewSummary":`Allow up to {count} child agents. Task-domain restriction: {domains}.`,"drawer.subagentRemoteReadOnly":`This source is read only. Open the Goal on its host to change the setting.`,"drawer.subagentTitle":`Adaptive sub-agent execution`,"drawer.remoteDetailsDescription":`SSH sources expose public-safe status only and do not read connection settings from the source host.`,"drawer.remoteDetailsUnavailable":`Remote details are not projected`,"drawer.resumeNo":`No`,"drawer.resumeYes":`Yes`,"drawer.runDetails":`Execution Session`,"drawer.runInterrupt":`Interrupt this run`,"drawer.runLatest":`View latest execution`,"drawer.runNewSession":`Start new Session`,"drawer.runCloseSession":`Close Session`,"drawer.runRecordEmpty":`No run record yet. The Agent has not started this execution. Check waiting conditions or resume the Session under Details & actions.`,"drawer.runRecordProjected":`No step-by-step record is available. LoopX read {completed}/{total} projected steps{outputs}; inspect the Session under Details & actions.`,"drawer.runRecordProjectedOutputs":` and {count} outputs`,"drawer.runRoleAssistant":`Completed`,"drawer.runRoleSystem":`Needs review`,"drawer.runRoleUser":`Task received`,"drawer.runView":`Session views`,"drawer.scheduleAdd":`Add scheduled check`,"drawer.scheduleDefaultNotification":`Notify only when you are needed`,"drawer.scheduleDefaultStop":`Goal completes or owner stops it`,"drawer.scheduleDefaultTarget":`Wake according to this Goal’s LoopX schedule.`,"drawer.scheduleEdit":`Change to every 2 hours`,"drawer.scheduleLast":`Last run`,"drawer.scheduleLocalTimezone":`Local timezone`,"drawer.scheduleNext":`Next run`,"drawer.scheduleNeverRun":`Not run yet`,"drawer.scheduleNotification":`Notification`,"drawer.schedulePause":`Pause`,"drawer.schedulePending":`Waiting for schedule`,"drawer.scheduleResume":`Resume`,"drawer.scheduleRunNow":`Run now`,"drawer.scheduleStop":`Stop {kind}`,"drawer.scheduleStopCondition":`Stop condition`,"drawer.scheduleTimezone":`Timezone`,"drawer.sessionRecoverable":`Resumable`,"drawer.sessionStatus":`Session status`,"drawer.setupHeartbeat":`Set up Heartbeat`,"drawer.taskActions":`Pending Todo actions`,"drawer.taskAdvancement":`Advancement task`,"drawer.taskBlock":`Mark blocked`,"drawer.taskComplete":`Mark complete`,"drawer.taskCompletedNote":`This task is retained as a read-only record.`,"drawer.taskCompletedTitle":`Task completed`,"drawer.taskDefer":`Defer`,"drawer.taskDeferCondition":`Todo defer resume condition`,"drawer.taskDeferInvalid":`Unsupported condition format; use one of the deterministic conditions below.`,"drawer.taskDeferPlaceholder":`For example, resume_at:2026-09-14T09:00:00+08:00`,"drawer.taskDeferReview":`Review defer`,"drawer.taskDeferSupported":`Supports todo_done, pr_merged, capacity_available, and timezone-aware resume_at conditions.`,"drawer.taskDeferUntil":`Defer until`,"drawer.taskDetails":`Todo details`,"drawer.taskInfo":`Task information`,"drawer.taskManage":`Manage task`,"drawer.taskNextCompleted":`Create a follow-up task`,"drawer.taskNextOpen":`Advance or update status`,"drawer.taskOrdinary":`Task`,"drawer.taskStatusBlocked":`Blocked`,"drawer.taskStatusDeferred":`Deferred`,"drawer.resumeWhen":`Resume condition`,"drawer.resumeState":`Resume state`,"drawer.resumePending":`Waiting for condition`,"drawer.resumeReady":`Ready to resume`,"drawer.resumeReceipt":`Resume receipt`,"drawer.taskNextDeferred":`Wait for the resume condition, then reassess`,"drawer.taskNextResumeReady":`Resume condition met; awaiting lifecycle replan`,"drawer.taskStatusCompleted":`Completed`,"drawer.taskStatusOpen":`Ready`,"drawer.taskSuccessor":`Create follow-up Todo`,"drawer.taskSuccessorNote":`Owner marked this blocked while waiting for more context.`,"drawer.taskSuccessorSummary":`Create follow-up Todo: {task}`,"drawer.taskSuccessorText":`Follow-up work for {task}`,"drawer.taskType":`Task type`,"drawer.topic":`Topic`,"drawer.trigger":`Trigger`,"drawer.titleAttention":`Needs you`,"drawer.titleOutput":`Output details`,"drawer.titleProposalApplied":`Execution result`,"drawer.titleProposalConfirm":`Confirm execution`,"drawer.titleSchedule":`Scheduled check`,"drawer.unconfigured":`Not configured`,"drawer.workspaceCandidates":`Available workspaces`,"files.emptySummary":`Public-safe output`,"files.empty":`No files, outputs, or verified reports yet.`,"files.loadingReports":`Loading verified milestone reports…`,"files.reportDelta":`+{added} added · {changed} changed`,"files.reportAdded":`added`,"files.reportChanged":`changed`,"files.reportGeneration":`Generation`,"files.reportLoadFailed":`Could not load verified reports`,"files.reportPublication":`Publication`,"files.title":`Files & Outputs`,"files.verifiedReport":`Verified milestone report`,"header.agentUnavailable":`Unavailable`,"header.chatRuntime":`Chat`,"header.workAgentCount":`{count} work Agents`,"header.chat":`Chat`,"header.files":`Files`,"header.goalCapabilities":`Capability settings`,"header.goalCapabilitiesDescription":`Manage overrides and inherited machine defaults.`,"header.goalDetails":`Goal details`,"header.goalDetailsDescription":`Review status, usage, repository, notifications, and sessions.`,"header.goalSettings":`Goal settings`,"header.goalSettingsDescription":`Open Goal details or capability settings`,"header.goalNavigation":`Goal navigation`,"header.goalView":`Goal view`,"header.live":`Live`,"header.manager":`LoopX Manager`,"header.managerDescription":`Your personal workspace across Goals`,"header.managerOverview":`Overview`,"header.managerView":`Manager view`,"header.openGoalNavigation":`Open Goal navigation`,"header.readOnlySourceDescription":`{source} is displayed read-only through an SSH tunnel`,"header.refresh":`Refresh status`,"header.refreshDone":`Updated just now`,"header.refreshFailed":`Refresh failed`,"header.refreshing":`Refreshing`,"header.selectAgent":`Select Agent`,"header.selectChatRuntime":`Select chat runtime`,"header.tasks":`Tasks`,"header.themeBrutal":`Switch to brutal theme`,"header.themePaper":`Switch to default theme`,"home.blockingSummary":`{count} are blocking an Agent.`,"home.completedGoals":`Completed Goals`,"home.empty":`Nothing here`,"startup.goalLoading":`Loading status…`,"startup.goalError":`Could not load status`,"startup.progress":`{loaded} of {total} active Goals loaded`,"startup.partial":`Goal states are updating. Counts are incomplete.`,"startup.independent":`Other Goals remain available while this Goal loads.`,"startup.error.timeout":`The request timed out. Retry when the local service is ready.`,"startup.error.network":`The connection was interrupted. Retry to reconnect.`,"startup.error.service":`The local service is temporarily unavailable. Retry to continue.`,"startup.error.revision":`The Goal directory changed during loading. Refresh to synchronize.`,"startup.error.scope":`This Goal is no longer available in the selected source. Refresh the directory.`,"startup.error.invalid":`The status response could not be read. Refresh or check for a LoopX update.`,"startup.retry":`Retry`,"startup.retryFailed":`Retry failed Goals`,"startup.failedCount":`{count} Goals could not be loaded. Ready Goals remain available.`,"home.greeting":`Hi, I’m your LoopX Manager`,"home.history":`History`,"home.lane.needsYou":`Needs you`,"home.lane.needsYouDescription":`Waiting for your decision, authorization, or context`,"home.lane.observing":`Observing`,"home.lane.observingDescription":`Monitoring continuously and notifying you when something changes`,"home.lane.running":`Running`,"home.lane.runningDescription":`Agents are making progress and reporting back`,"home.lane.scheduled":`Scheduled`,"home.lane.scheduledDescription":`Queued until its time or prerequisite arrives`,"home.noActivity":`No activity yet`,"home.noFirstActivity":`Waiting for first activity`,"home.noCompletedGoals":`No completed Goals yet`,"home.preservedState":`State is preserved and can be resumed`,"home.stopped":`Stopped`,"home.systemHealth":`System health: {summary}`,"home.taskCount":`{count} Tasks`,"home.todayAt":`Today {time}`,"home.waitingCount":`You have {count} items to handle.`,"home.workspace":`Goal workspace`,"lark.allMessages":`All messages in this topic`,"lark.allTopicMessages":`All topic messages`,"lark.agentIngress":`Agent ingress`,"lark.agentAppPermissions":`Every selected Agent needs a Lark App that is ready for group mentions and replies.`,"lark.agentApps":`Lark App per Agent`,"lark.agentAppsDescription":`The default App is preselected. Assign a different compatible App when an Agent needs its own bot identity.`,"lark.agentAppSelection":`Lark App for {agent}`,"lark.appCreated":`App created`,"lark.appCreateFailed":`Creation failed`,"lark.appLoading":`Loading available Lark Apps…`,"lark.appPermissions":`This App can send connection messages, but lacks the bot permissions required to receive group mentions or reply automatically. Enable im:message.group_at_msg:readonly, im:message.send_as_bot, and the im.message.receive_v1 event, publish a new version, then refresh.`,"lark.appProfile":`Lark App`,"lark.apps":`Lark Apps`,"lark.autoReplyUnavailable":`Auto reply unavailable`,"lark.autoReplyReady":`Auto reply ready`,"lark.bindGoal":`Bind to Goal`,"lark.cancel":`Cancel`,"lark.cardinality":`One Lark App · many Goals · one isolated route per Agent`,"lark.capture":`Capture`,"lark.captureAddressed":`Only messages that mention or reply to the App`,"lark.captureAll":`All messages in this Goal topic`,"lark.captureScope":`Capture scope`,"lark.captureScopeDescription":`Controls which Topic messages enter LoopX without expanding Agent permissions.`,"lark.closeConnection":`Close connection dialog`,"lark.closeCreate":`Close create dialog`,"lark.closeSettings":`Close Lark settings`,"lark.connect":`Connect`,"lark.connectAllAgents":`Connect every registered Agent`,"lark.connectAllAgentsAction":`Connect {count} Agents`,"lark.connectAllAgentsDescription":`Create {count} isolated Agent Topics in one guided action. Send requests inside the matching Topic; each Agent keeps its own route and inbox.`,"lark.connectApp":`Connect Lark App`,"lark.connection":`Connection`,"lark.connections":`Connections`,"lark.configuration":`Lark configuration`,"lark.continueFeishu":`Continue in Feishu`,"lark.createAutomatically":`Create Goal topic automatically`,"lark.createAutomaticallyDescription":`A dedicated, Agent-labelled Topic will be created for every selected Agent.`,"lark.defaultAgentAppDescription":`Used to find the target group and as the default for every selected Agent. Per-Agent choices below override it.`,"lark.description":`Manage reusable Lark Apps and connect group chats to Goals through dedicated topics.`,"lark.editConnection":`Edit Lark Connection`,"lark.goalConnections":`{count} Goal connections`,"lark.goalTopicConnections":`Lark Goal Topic connections`,"lark.groupChat":`Group chat`,"lark.groupEmpty":`This bot has not joined a group that can be connected. Add it to a Feishu group first, then return to refresh or search.`,"lark.groupLoading":`Reading groups joined by this bot…`,"lark.groupSearch":`Search groups joined by this bot`,"lark.historyPermission":`Group-history permission (separate capability)`,"lark.health.eventProcessed":`{events} events processed, {replies} replies sent.`,"lark.health.eventUnverified":`Event subscription needs verification`,"lark.health.eventUnverifiedDetail":`The provider listener is ready, but no event has arrived. Enable im.message.receive_v1 and group mention permissions, publish a new version, then send a new @ mention inside this Agent Topic. Group-level messages fail closed when multiple Agent routes exist.`,"lark.health.ignoredSelf":`The bot’s own message was ignored to prevent duplicate replies.`,"lark.health.invalidRouting":`Invalid routing configuration`,"lark.health.invalidRoutingDetail":`The connection was safely disabled. Select a processing mode again and save.`,"lark.health.lastStatus":`Latest event status: {status}`,"lark.health.listening":`Listening`,"lark.health.messageContextPermission":`Message permission required`,"lark.health.messageContextPermissionDetail":`A message event arrived, but group context could not be read. Publish and authorize group message read access for this App.`,"lark.health.notAddressed":`Latest message did not directly @ the bot`,"lark.health.notAddressedDetail":`Listening is healthy. This connection only responds to direct @ mentions or replies to the bot.`,"lark.health.notStarted":`Listener not started`,"lark.health.notStartedDetail":`Refresh the connection or restart LoopX, then try again.`,"lark.health.processingFailed":`Message processing failed`,"lark.health.processingFailedDetail":`The message event arrived, but Agent processing failed. Review local diagnostics and retry.`,"lark.health.queued":`Queued in the Agent inbox`,"lark.health.queuedDetail":`The message will be processed asynchronously by {agent} without starting a general Chat Session.`,"lark.health.sourceDisconnected":`Event connection disconnected`,"lark.health.sourceDisconnectedDetail":`The event consumer exited unexpectedly. Check that the app profile uses Feishu for Feishu apps or Lark for international Lark, then inspect connection and subscription errors. LoopX is retrying; successful history queries do not prove live delivery.`,"lark.health.retrying":`Retrying listener`,"lark.health.retryingDetail":`Event listening was interrupted and LoopX is retrying automatically.`,"lark.health.routeAmbiguous":`Message matches multiple Goals`,"lark.health.routeAmbiguousDetail":`The same bot and group have multiple full-group capture connections. Use a separate bot for each Agent or keep only one full-group connection.`,"lark.health.routeMismatch":`Message did not match this Goal Topic`,"lark.health.routeMismatchDetail":`The event came from another group or Topic. Reconnect this Goal to the correct group, then send a new @ mention.`,"lark.health.routeUnavailable":`Message cannot be routed to the Goal`,"lark.health.routeUnavailableDetail":`Connection data is incomplete. Reconnect this Goal, then send a new @ mention.`,"lark.health.starting":`Starting`,"lark.health.startingDetail":`LoopX is starting message event listening for this App.`,"lark.health.unavailable":`Auto reply unavailable`,"lark.health.waiting":`Waiting`,"lark.incomingMessages":`Incoming messages`,"lark.ingressAsync":`Async inbox`,"lark.ingressAsyncDescription":`Write to the Agent private inbox for a later explicit drain.`,"lark.editPreservesIdentity":`Saving preserves this App, group and Topic. Old connections upgrade to the Agent inbox by default.`,"lark.conversationKind":`Connection purpose`,"lark.managerConversation":`Manager · live conversation`,"lark.workerConversation":`Worker Agent · background tasks`,"lark.managerConversationDescription":`The built-in manager responds as you chat and delegates long-running work to background Agents. Group and private conversations keep separate histories.`,"lark.ingressLegacy":`Upgrade available`,"lark.ingressLegacyDescription":`Save this connection to upgrade to the Agent inbox. Existing messages remain in the same Topic.`,"lark.ingressQueue":`Queuing`,"lark.ingressQueueDescription":`Enter the same Agent Session's bounded FIFO queue and run after the current Turn.`,"lark.ingressSteering":`Steering`,"lark.ingressSteeringDescription":`Deliver to the active Turn and reject safely when no exact active Turn exists.`,"lark.loading":`Loading Lark configuration…`,"lark.management":`Lark management`,"lark.openEventSettings":`Open Feishu event settings`,"lark.mentions":`Mentions`,"lark.mentionsOnly":`Mentions only`,"lark.needsMessagePermissions":`Needs message permissions`,"lark.needsSetup":`Needs setup`,"lark.newApp":`New Lark App`,"lark.noAgentConfigured":`No Agent configured`,"lark.noConnections":`No matching connections.`,"lark.noProfiles":`No lark-cli App profiles are available yet.`,"lark.profileName":`Profile name`,"lark.profileValidation":`Profile can contain only letters, numbers, periods, underscores, and hyphens.`,"lark.processing":`Processing`,"lark.region":`Region`,"lark.registerAnother":`+ Register another Lark App — Create through Feishu`,"lark.reopenFeishu":`Reopen Feishu`,"lark.settingsConfigure":`Configure {goal}`,"lark.settingsDisconnect":`Disconnect {goal}`,"lark.replyMode":`Reply mode`,"lark.replyModeDescription":`Replies are limited to the source Topic to prevent cross-group or cross-Goal delivery.`,"lark.reusableApps":`{count} reusable Apps`,"lark.reusableWorkspaceApp":`Reusable workspace App`,"lark.routesUnverified":`{count} Lark routes pending verification`,"lark.saveConnection":`Save connection`,"lark.searchConnections":`Search Lark connections`,"lark.searchPlaceholder":`Search Apps, groups, Goals, or topics`,"lark.setupCopy":`LoopX opens the official Feishu creation page through lark-cli. App credentials stay in the system Keychain; LoopX stores only the profile reference.`,"lark.someoneMentions":`Someone mentions the Agent`,"lark.targetAgent":`Target Agent`,"lark.targetAgentDescription":`Choose a registered Agent in this Goal. This connection delivers to one Agent; it does not broadcast or grant permissions. Steering and Queuing require that Agent's exact active Session.`,"lark.agentUnavailable":`{agent} · no longer available`,"lark.selectRegisteredAgent":`Select an available registered Agent before connecting. The previous Agent will not be replaced automatically.`,"lark.topicPreview":`Topic preview`,"lark.topicReply":`Topic reply`,"lark.trigger":`Trigger`,"lark.waitingFeishu":`Waiting for Feishu`,"lark.waitingFeishuDescription":`Complete Feishu authorization in the new window. This page updates automatically when it is ready.`,"lark.waitingLink":`Generating the official Feishu creation link…`,"lark.error.appCreate":`Lark App creation failed`,"lark.error.appRequired":`Select a Lark App profile.`,"lark.error.bind":`Connection failed`,"lark.error.bindPreview":`Connection preview failed`,"lark.error.configuration":`Could not load Lark configuration`,"lark.error.groupLookup":`Could not read groups joined by this bot. Check the bot status and try again.`,"lark.error.groupLoad":`Could not load group chats`,"lark.error.invalidApp":`The Lark App profile is unavailable or has not completed authorization.`,"lark.error.messagePermissions":`This App lacks the bot permissions required for automatic replies. Enable im:message.group_at_msg:readonly and im:message:send_as_bot, publish a new version, then refresh.`,"lark.error.provider":`The Feishu API call failed without a verified receipt. Try again later.`,"lark.error.setupPoll":`Could not read creation status`,"lark.error.setupStart":`Could not start Lark App creation`,"lark.error.cliExecutable":`The configured lark-cli was found but cannot run. Check the installation or launch arguments.`,"lark.error.cliMissing":`lark-cli was not found. Install lark-cli and restart LoopX.`,"lark.error.cliStart":`lark-cli failed to start. Check the installation and restart LoopX.`,"lark.error.disconnect":`Disconnect failed`,"notifications.autoNotify":`Send automatically when your confirmation is required`,"notifications.bind":`Bind notification group`,"notifications.bindConfirm":`Bind “{goal}” to “{target}”. LoopX will verify that the bot is in the group and send a confirmation message.`,"notifications.bindFailed":`Binding failed`,"notifications.bound":`Bound`,"notifications.confirmBind":`Confirm binding`,"notifications.description":`Send Goal changes that need your confirmation to a Feishu group. Bindings and automatic delivery use the existing channel.`,"notifications.disabled":`Disabled`,"notifications.group":`Notification group: {target}`,"notifications.loadFailed":`Could not load notification groups`,"notifications.noTargets":`No notification groups are available. Group delivery uses a private bot identity; configure one from the terminal first:`,"notifications.notBound":`Not bound`,"notifications.recent":`Latest {time}`,"notifications.sentCount":`{count} sent`,"notifications.settings":`Goal notification bindings`,"notifications.setupFailed":`Could not update settings`,"notifications.title":`Feishu group notifications`,"proposal.field.agentId":`Agent`,"proposal.field.cadence":`Frequency`,"proposal.field.completionCriteria":`Completion criteria`,"proposal.field.executionBoundary":`Execution boundary`,"proposal.field.goalId":`Goal ID`,"proposal.field.heartbeat":`Heartbeat`,"proposal.field.initialTodos":`Initial tasks`,"proposal.field.objective":`Objective`,"proposal.field.operation":`Operation`,"proposal.field.operationState":`Operation state`,"proposal.field.confirmationBoundary":`Confirmation boundary`,"proposal.field.expiresAt":`Expires at`,"proposal.field.permission":`Permission`,"proposal.field.reason":`Reason`,"proposal.field.stopCondition":`Stop condition`,"proposal.field.target":`Check target`,"proposal.field.timezone":`Timezone`,"proposal.field.title":`Title`,"proposal.field.workspace":`Execution workspace`,"actionReview.targetChanged":`The preview target does not match the requested Goal and operation. Generate a new preview.`,"actionReview.ready_stop":`Pausing is reversible. This validated preview can apply directly; completion still requires verified readback.`,"actionReview.resume_review":`Review before restoring automatic scheduling. Quota, gates and Todo constraints still apply.`,"actionReview.delete_review":`Review removal of this stopped Goal from the registries. Project files and history are preserved.`,"actionReview.action_review":`Review the target and impact before applying this proposal.`,"actionReview.protected_action":`This action needs explicit review. Confirmation cannot replace required authority.`,"actionReview.unknown_permission":`The permission classification is not recognized. Recheck the proposal before continuing.`,"actionReview.unknown_action":`This lifecycle operation is not recognized. Recheck the proposal before continuing.`,"actionReview.incomplete_proposal":`The preview is missing validation or an available apply transition. Generate a new preview.`,"actionReview.authority_gate":`A gate prevents execution. Resolve its requirements, then recheck the proposal.`,"actionReview.stale_proposal":`The source state changed. Generate a new preview; the previous decision no longer applies.`,"actionReview.apply_pending":`Execution is in progress. Wait for its result before retrying.`,"actionReview.readback_verified":`The action completed and its resulting state was verified.`,"actionReview.readback_unverified":`The action returned without verified readback. Completion is not confirmed; recheck the state.`,"actionReview.apply_failed":`Execution did not complete. Check the failure and regenerate the preview before retrying.`,"actionReview.inactive_proposal":`This proposal is no longer ready to execute. Recheck it before continuing.`,"proposal.gate.default":`Host confirmation required`,"proposal.impact.default":`After confirmation, the canonical LoopX service will write the state change.`,"proposal.impact.goalCreate":`After confirmation, LoopX will create the Goal and its initial Todo, then let the selected Agent start the first run.`,"proposal.impact.lifecycleDelete":`After confirmation, this stopped Goal is removed from the source and global registries. Project files, history state, and backups are preserved.`,"proposal.impact.lifecycleResume":`After confirmation, the Goal becomes eligible for automatic scheduling and returns to Active Goals. Actual execution still follows quota, Gate, and Todo constraints.`,"proposal.impact.lifecycleStop":`After confirmation, automatic progress stops and the Goal moves to the collapsed Stopped list. History, Todos, and evidence remain available for resuming.`,"proposal.impact.protected":`This action must be completed through the protected LoopX write service.`,"proposal.impact.operation":`The exact terms are read-only here. Confirm or reject the same immutable request in the bound Feishu group; confirmation consumes one canonical claim.`,"proposal.primary.apply":`Confirm and apply`,"proposal.primary.goalCreate":`Create Goal and start first run`,"proposal.primary.lifecycleDelete":`Delete Goal`,"proposal.primary.lifecycleResume":`Resume Goal`,"proposal.primary.lifecycleStop":`Stop Goal`,"proposal.primary.todoStart":`Create task and start execution`,"proposal.primary.operationGroup":`Confirm in Feishu group`,"proposal.summary.goalCreate":`Create Goal: {title}`,"proposal.summary.heartbeat":`Set a Heartbeat for the current Goal`,"proposal.summary.lifecycleDelete":`Delete Goal: {title}`,"proposal.summary.lifecycleResume":`Resume Goal: {title}`,"proposal.summary.lifecycleStop":`Stop Goal: {title}`,"proposal.summary.monitor":`Create a scheduled check for the current Goal: {target}`,"proposal.workspace.current":`Current local workspace (no Repository bound)`,"proposal.workspace.named":`{workspace} (execution environment only; does not bind a repository)`,"proposal.workspaceGate.agentImpact":`Bind an Agent identity, then recheck the original action. No Goal has been written.`,"proposal.workspaceGate.agentTitle":`Bind an Agent first`,"proposal.workspaceGate.defaultSummary":`Select the Goal workspace.`,"proposal.workspaceGate.selectionImpact":`After selecting a workspace, LoopX will show the confirmation preview again. The selection itself does not write state.`,"proposal.workspaceGate.selectionTitle":`Select Goal workspace`,"projection.agentAdvancingGoal":`Agent is advancing the current Goal`,"projection.agentIdle":`Nothing needs your attention`,"projection.agentNeedsDecision":`Agent is waiting for your decision`,"projection.agentPreparingNextStep":`Agent is preparing the next step`,"projection.agentStopped":`Stopped by you; history, Todos, and evidence are preserved`,"projection.agentWaitingExternal":`Waiting for an external condition`,"projection.confirmAgentDecision":`Confirm the permission or decision the Agent needs next`,"projection.events24h":`{count} events in the last 24 hours`,"projection.firstReadOnlyAdapterCheck":`Run the first read-only adapter check and save progress`,"projection.goalVerified":`Goal state, Todos, and registration information verified`,"projection.latestRun":`Latest run`,"projection.latestValidation":`Latest validation`,"projection.nextUpdatePending":`Waiting for LoopX to update the next step`,"projection.publicSafeProjection":`Public-safe status projection`,"projection.refreshState":`Refresh LoopX status and confirm the current progress is still valid`,"projection.runEvidenceAvailable":`Run evidence is available`,"projection.runRecorded":`The latest LoopX run is recorded`,"projection.statusRefreshNeeded":`LoopX status needs to be refreshed`,"projection.todoStatusUpdated":`Todo status updated; confirming the next step`,"projection.validationRecorded":`The latest validation is recorded`,"runs.completed":`Completed`,"runs.failed":`Needs review`,"runs.interrupted":`Interrupted`,"runs.queued":`Scheduled`,"runs.ready":`Ready`,"runs.resumeFailed":`Recovery failed`,"runs.running":`Running`,"runs.unknown":`Unknown`,"runs.waiting":`Waiting`,"schedule.active":`Running`,"schedule.heartbeat":`Goal Heartbeat`,"schedule.monitor":`Scheduled & continuous task`,"schedule.paused":`Paused`,"schedule.summary":`Continuously checked under LoopX scheduling constraints`,"schedule.defaultTarget":`Check the current Goal for blockers, progress, and new outputs`,"schedule.unsupportedCalendar":`Scheduled checks do not currently support an exact weekday or time. Use a fixed interval such as “Every 30 minutes,” “Every 2 hours,” or “Daily.” The draft was preserved and no confirmation preview was created.`,"source.add":`Add source`,"source.addConfigured":`Add read-only source`,"source.addMethod":`Source setup method`,"source.addSsh":`Add SSH source`,"source.closeForm":`Close source form`,"source.configured":`Configured SSH`,"source.configuredCount":`Local SSH Hosts · {count}`,"source.configuredGroup":`Configured SSH Hosts · {count} (select to add)`,"source.connected":`Connected`,"source.connecting":`Connecting`,"source.controlPlane":`Control plane source`,"source.copy":`Copy`,"source.copyCommand":`Copy SSH tunnel command`,"source.copyError":`Could not copy the command. Copy it manually below.`,"source.copied":`Copied`,"source.description":`All explicit Hosts are loaded, including Include files. Wildcards are not listed. Run the command first; LoopX never reads SSH keys or configuration details.`,"source.host":`Local SSH Host`,"source.hostEmpty":`No explicit SSH Hosts are available in ~/.ssh/config.`,"source.hostLoadError":`Could not read local SSH Hosts.`,"source.hostPlaceholder":`Enter or search for a Host`,"source.invalid":`The SSH source settings are invalid.`,"source.loadingHosts":`Loading…`,"source.localInteractive":`Local interactive`,"source.localPort":`Local port`,"source.manual":`Manual URL`,"source.manualDescription":`Remote sources always remain read-only projections and never inherit local write permissions.`,"source.name":`Name`,"source.namePlaceholder":`Remote development machine`,"source.notAvailable":`Unavailable`,"source.readOnly":`SSH tunnel · read only`,"source.readOnlyNoticeDescription":`You can view Goals, Tasks, evidence, and run status. Writes, guidance, and Agent sessions remain on the source host.`,"source.readOnlyNoticeTitle":`Remote read-only projection`,"source.readOnlyWriteError":`Remote SSH tunnel sources are read-only projections and cannot perform control-plane writes.`,"source.refreshHosts":`Reload SSH Hosts`,"source.remove":`Remove source {source}`,"source.removeCurrent":`Remove current source`,"source.select":`Select control plane source`,"source.selectHost":`Select a configured SSH Host.`,"source.statusUrl":`Local forwarded URL`,"source.tunnelCommandPending":`Select a Host to generate the tunnel command`,"machine.absent":`Not configured`,"machine.action.create":`Create machine policy`,"machine.action.delete":`Remove machine policy`,"machine.action.unchanged":`No write required`,"machine.action.update":`Update machine policy`,"machine.applied":`Machine policy applied and read back successfully.`,"machine.applyError":`Machine policy could not be applied.`,"machine.applyPreview":`Apply reviewed preview`,"machine.changedNamespaces":`Changed namespaces`,"machine.capabilityCatalog":`Machine capability catalog`,"machine.capabilityEmpty":`No machine-configurable capabilities are registered.`,"machine.configured":`Configured`,"machine.confirmRollback":`Confirm rollback`,"machine.currentRevision":`Current revision`,"machine.currentValue":`Current machine value`,"machine.description":`Browse the same capability catalog as Goal settings. Configure supported machine defaults here; Goal-only capabilities are labeled explicitly.`,"capabilities.rawJson":`Advanced: raw JSON`,"machine.goalOnly":`This capability currently supports Goal configuration only. Open a Goal’s capability settings to configure it; no machine-wide default is applied.`,"machine.desiredRevision":`Desired revision`,"machine.editorUnavailable":`No editor is installed for this namespace`,"machine.editorUnavailableDescription":`The namespace remains visible in the registry. Install or upgrade its Dashboard editor before changing it.`,"machine.editorMode":`Editor mode`,"machine.liveDefault":`Live default; Goal override wins`,"machine.liveDefaultDescription":`Goals without an explicit override read the current machine policy at the capability’s next decision point. Changes and removal affect those existing Goals immediately; an explicit Goal override stays pinned.`,"machine.genericNamespaceDescription":`Edit this registered namespace as JSON. LoopX validates it with the capability-owned schema before previewing any write.`,"machine.jsonConfiguration":`Namespace configuration (JSON)`,"machine.jsonConfigurationHelp":`Only this namespace is updated. Other machine configuration is preserved, and Apply remains locked to the reviewed preview revision.`,"machine.jsonEditor":`JSON`,"machine.editJson":`Edit JSON`,"capabilities.jsonConfiguration":`Goal configuration (JSON)`,"capabilities.jsonHelp":`Edit registered fields for this Goal. Changes require a new preview before applying.`,"capabilities.jsonInvalid":`Enter a valid JSON object using only registered editable fields.`,"machine.backToForm":`Back to form`,"machine.jsonInvalid":`Enter one valid JSON object before previewing changes.`,"machine.loadError":`Machine configuration could not be loaded.`,"machine.machinePolicy":`Machine policy`,"machine.namespaceCount":`Registered namespaces`,"machine.namespaces":`Configuration namespaces`,"machine.periodicReport":`Periodic reports`,"machine.periodicReportDescription":`Default report policy for every Goal without an explicit override. Goal scheduling and delivery consume the effective configuration.`,"machine.periodicReportActivation":`Enabled means automatic delivery at validated stage boundaries`,"machine.periodicReportActivationDescription":`This is not a weekly timer. When LoopX validates a Goal stage completion, an Agent prepares and freezes the report, then automatically delivers it through the configured Goal Channel. The enabled subscription is standing delivery authority; failures and route drift stop closed for repair.`,"machine.changeQualityActivation":`Qualification is a quality gate, not new authority`,"machine.changeQualityActivationDescription":`Goals that inherit this policy qualify their exact final diff. safe_fix allows at most one bounded fix pass inside existing write authority; this setting never grants file, permission, or merge authority.`,"machine.replanCadenceActivation":`Review cadence changes timing, not execution authority`,"machine.replanCadenceActivationDescription":`Goals without an explicit override read this threshold before the next review decision. It does not create Turns, spend quota, or grant authority.`,"machine.preview":`Review exact machine change`,"machine.previewChanges":`Preview changes`,"machine.previewError":`A machine-policy preview could not be created.`,"machine.previewLocked":`Apply is locked to this exact revision. If machine state changes, LoopX requires a new preview.`,"machine.previewRollback":`Preview rollback`,"machine.previewRemoval":`Preview removal`,"machine.profilePreset":`Profile preset`,"machine.profilePresetHelp":`A capability-owned preset, such as weekly-progress.`,"machine.registry":`Typed registry`,"machine.requiredFields":`Enable requires a profile preset, Goal Channel route, and valid timezone.`,"machine.revision":`Machine revision`,"machine.revisionLockedReady":`All changes require a preview and apply only while that exact machine revision remains current.`,"machine.rollbackAvailable":`Rollback is available for the last apply`,"machine.rollbackDescription":`Preview the stored prior revision before restoring it.`,"machine.rollbackError":`The rollback could not be completed.`,"machine.rollbackPreviewDescription":`The prior revision is ready to restore. Confirm to apply this rollback.`,"machine.rolledBack":`The prior machine policy was restored and verified.`,"machine.removed":`Machine policy removed and the resulting configuration read back successfully.`,"machine.routeRef":`Goal Channel route`,"machine.routeRefHelp":`Use a public route alias; credentials and provider identifiers never enter this form.`,"machine.timezone":`Timezone`,"machine.timezoneHelp":`Use an IANA timezone, for example Asia/Shanghai.`,"machine.title":`Machine configuration`,"machine.unchanged":`Machine policy already matches this preview; nothing was written.`,"machine.visualEditor":`Guided`,"capabilities.atomicOverride":`Goal override is atomic`,"capabilities.atomicOverrideDescription":`A complete Goal value wins over the machine default. LoopX never mixes individual fields across scopes.`,"capabilities.applyFailed":`Goal capability changes were not applied.`,"capabilities.applyPreview":`Apply preview`,"capabilities.catalog":`Goal capability catalog`,"capabilities.chooseGoal":`Choose a Goal before inspecting its capabilities.`,"capabilities.defaultValue":`Declared default`,"capabilities.description":`Inspect the capabilities available to this Goal and the exact scope of each setting.`,"capabilities.editorPrepared":`Typed editor contract available`,"capabilities.effectiveSource":`Effective source`,"capabilities.empty":`No capability descriptors are available for this Goal.`,"capabilities.fields":`Registered fields`,"capabilities.goalPolicy":`Goal capability policy`,"capabilities.goalScope":`Goal`,"capabilities.goalValue":`Current Goal value`,"capabilities.loadFailed":`Could not load Goal capabilities`,"capabilities.loading":`Loading Goal capabilities…`,"capabilities.machineOnly":`This capability is configured only at machine scope.`,"capabilities.machineValue":`Live machine default`,"capabilities.machineScope":`Machine`,"capabilities.previewOnly":`Inspection is live. Goal writes remain unavailable until the revision-locked preview and apply path is connected.`,"capabilities.preview":`Revision-locked preview`,"capabilities.previewChanges":`Preview changes`,"capabilities.restoreInheritance":`Restore machine-default inheritance`,"capabilities.previewFailed":`Could not preview Goal capability changes.`,"capabilities.previewLocked":`Apply will re-check this exact plan revision and reject stale changes.`,"capabilities.partialWrite":`Goal value saved; shared projection needs reconciliation`,"capabilities.partialWriteDescription":`The source Goal configuration was written and read back. Its shared runtime projection did not synchronize, so do not submit the change again.`,"capabilities.refreshSource":`Refresh source value`,"capabilities.readOnly":`Read-only capability`,"capabilities.revisionLockedReady":`Changes require a preview and are applied only when its exact revision is still current.`,"capabilities.retry":`Retry`,"capabilities.source.capability_default":`Capability default`,"capabilities.source.goal_override":`Goal override`,"capabilities.source.machine_default":`Live machine default`,"capabilities.source.not_configured":`Not configured`,"capabilities.title":`Goal capabilities`,"settings.close":`Close settings`,"settings.appearance":`Appearance`,"settings.appearanceDescription":`Manage workspace display preferences in this browser.`,"settings.appearanceTabDescription":`Theme and display preferences`,"settings.capabilitiesTabDescription":`Capability overrides for this Goal`,"settings.back":`Back to workspace`,"settings.categories":`Settings categories`,"settings.description":`Manage workspace preferences and integrations.`,"settings.eyebrow":`Workspace preferences`,"settings.general":`General`,"settings.goalConnections":`Goal connections`,"settings.language":`Language`,"settings.languageDescription":`Choose the language used by the LoopX desktop workspace.`,"settings.languageEnglishDescription":`Use English for navigation, settings, and workspace controls.`,"settings.languageEnglish":`English`,"settings.languageSimplifiedChineseDescription":`Use Simplified Chinese for navigation, settings, and workspace controls.`,"settings.languageSimplifiedChinese":`Simplified Chinese`,"settings.languageStoredLocally":`This preference is stored only on this device.`,"settings.languageTabDescription":`Interface language for this device`,"settings.larkTabDescription":`Apps, group chats, and Goal Topic connections`,"settings.machineTabDescription":`Typed defaults shared by capabilities on this machine`,"settings.notifications":`Notifications`,"settings.open":`Settings`,"settings.themeDefault":`Paper`,"settings.themeDefaultDescription":`Calm and lightweight for long-running work.`,"settings.themeDescription":`Choose the workspace visual style. This preference is stored in the current browser.`,"settings.themeHighContrast":`High contrast`,"settings.themeHighContrastDescription":`Stronger borders and more prominent state blocks.`,"settings.themeLoopx":`LoopX standard`,"settings.themeLoopxDescription":`Precise monochrome surfaces, Geist type, and quiet hairline structure.`,"settings.title":`Settings`,"settings.workspaceDisplay":`Workspace display`,"settings.workspaceTheme":`Workspace theme`,"session.closeRecord":`Exit run record`,"session.details":`Session details`,"session.record":`Execution Session · Run record`,"session.recordDescription":`The timeline now shows messages and Turn records from this Session.`,"sidebar.createGoal":`Create Goal`,"sidebar.delete":`Delete`,"sidebar.deleteGoal":`Delete Goal`,"sidebar.manager":`LoopX Manager`,"sidebar.notifications":`Settings`,"sidebar.owner":`Personal workspace`,"sidebar.product":`Personal Agent workspace`,"sidebar.resume":`Resume`,"sidebar.resumeGoal":`Resume Goal`,"sidebar.stop":`Stop`,"tasks.historyLoading":`Loading history…`,"tasks.historyError":`History could not be loaded.`,"tasks.historyExpired":`History snapshot expired. Reload to continue.`,"tasks.historyRetry":`Reload`,"tasks.historyEnd":`End of completed history`,"tasks.historyMore":`Load more`,"tasks.historyLocalOnly":`Open this machine’s Dashboard to browse full history.`,"sidebar.sortGoals":`Reorder Goals`,"sidebar.dragGoal":`Drag to reorder, or use Reorder Goals`,"sidebar.moveUp":`Move {goal} up`,"sidebar.moveDown":`Move {goal} down`,"sidebar.goalMoved":`{goal} moved to position {position}`,"sidebar.orderNotSaved":`Order changed for this visit; browser storage is unavailable.`,"sidebar.stopGoal":`Stop Goal`,"sidebar.stopped":`Stopped`,"sidebar.stoppedLoading":`Loading stopped Goals`,"sidebar.stoppedLoadFailed":`Stopped Goals could not be loaded. Active Goals remain available.`,"sidebar.retryStopped":`Retry`,"state.completed":`Completed`,"state.needsRepair":`Needs repair`,"state.needsYou":`Needs you`,"state.quiet":`Quiet`,"state.running":`Running`,"state.stopped":`Stopped`,"state.waiting":`Waiting`,"tasks.blocked":`Blocked`,"tasks.agentLane":`Work Agent`,"tasks.agentLaneDescription":`Filter this Goal's projected work lanes`,"tasks.agentLaneFilter":`Filter by work Agent`,"tasks.allAgentLanes":`All Agents ({count})`,"tasks.chatAgentReplied":`Agent replied`,"tasks.chatPending":`Sent to Agent`,"tasks.chatPendingDescription":`Processing. Tasks update only after a task operation is confirmed.`,"tasks.chatRecent":`Recent conversation`,"tasks.chatUnchangedDescription":`This conversation did not directly change Tasks. Convert the reply to a Task draft and confirm it when execution is needed.`,"tasks.chatViewReply":`View reply`,"tasks.convertToTask":`Convert to Task`,"tasks.completed":`Completed`,"runs.discoveryPartial":`Some execution details are unavailable. Reconnecting; task summaries are not live execution status.`,"runs.discoveryOffline":`Execution service unavailable. Reconnecting; retained task summaries may be stale.`,"files.openConversation":`Go to conversation`,"files.exportSummary":`Export summary`,"tasks.viewDescription":`Decisions first, then work and recent completions`,"tasks.viewLabel":`Task view`,"tasks.listView":`List`,"tasks.boardView":`Board`,"tasks.completedSummary":`{count} tasks completed. Recent details are projected by the control plane when needed.`,"tasks.emptyCompleted":`No completed tasks yet.`,"tasks.emptyConfirm":`No tasks waiting for confirmation.`,"tasks.emptyRunning":`No queued or running tasks.`,"tasks.emptySchedules":`No scheduled tasks.`,"tasks.emptyGoal":`This Goal has no tasks yet. Describe the next step below and LoopX will show a confirmation preview first.`,"tasks.markComplete":`Mark complete: {name}`,"tasks.moreActions":`More actions: {name}`,"tasks.openExecution":`View execution: {name}`,"tasks.pending":`Pending`,"tasks.pendingAndRunning":`Queued / Running`,"tasks.scheduled":`Scheduled & continuous`,"tasks.sessionError":`Session issue`,"tasks.waiting":`Queued`,"tasks.waitingAge":`Waiting {age}`,"tasks.viewExecution":`View execution`,"tasks.viewResult":`View result`,"time.days":`{count} days`,"time.hours":`{count} hours`,"timeline.emptyGoal":`This Goal has no new activity`,"timeline.emptyGoalDescription":`Ask for progress or send new guidance.`,"timeline.emptyWorkspace":`Your workspace is quiet today`,"timeline.emptyWorkspaceDescription":`Describe a Goal to the LoopX Manager, or ask what deserves attention today.`,"timeline.gateHistory":`{count} historical Gates`,"timeline.pending":`Working…`,"timeline.runCompleted":`{run}: completed`,"timeline.review":`Review`,"timeline.reviewAndConfirm":`Review and confirm`,"timeline.waitingConfirmation":`Needs your confirmation`},"zh-CN":{"acceptance.connected":`已连接`,"acceptance.mapped":`已建立项目映射`,"acceptance.refreshed":`已刷新状态`,"acceptance.inspected":`已检查适配器`,"acceptance.recorded":`已记录执行`,"acceptance.judged":`已记录反馈`,"acceptance.approved":`已记录批准`,"acceptance.ready":`已记录控制器就绪`,"acceptance.attentionSource":`当前状态`,"acceptance.visionSource":`Agent 验收条件`,"acceptance.todoSource":`任务状态`,"acceptance.runSource":`最新执行证据`,"acceptance.title":`验收观察`,"acceptance.unavailable":`验收观测不可用,Goal 是否达成仍未知。`,"acceptance.partial":`当前仅有部分观测。任务完成或缺口列表为空,都不能证明 Goal 已通过验收。`,"acceptance.gaps":`仍需补充的证据`,"acceptance.reasonUnknown":`来源未提供原因`,"acceptance.unknown":`未知`,"acceptance.required":`所需证据或条件`,"acceptance.observed":`观测时间`,"acceptance.noGaps":`现有观测中没有缺口,尚未评估完整验收条件。`,"acceptance.guards":`待处理的门禁决策`,"acceptance.noGuards":`现有观测中没有待处理的门禁决策。`,"acceptance.scope":`决策范围`,"acceptance.next":`当前状态给出的下一步`,"acceptance.historical_progress":`已记录的历史进展`,"acceptance.historical":`历史生命周期记录不授予权限,也不代表通过验收。`,"acceptance.missing":`未获取的来源:`,"acceptance.truncated":`仅展示前 12 条观测。`,"common.actions":`操作`,"common.agent":`Agent`,"common.allMessages":`所有消息`,"common.cancel":`取消`,"common.close":`关闭`,"common.closeActionReceipt":`关闭操作回执`,"common.confirm":`确认`,"common.export":`导出`,"common.failed":`失败`,"common.goal":`Goal`,"common.loading":`加载中…`,"common.none":`无`,"common.off":`关闭`,"common.on":`开启`,"common.open":`打开`,"common.owner":`Owner`,"common.readOnly":`只读`,"common.recently":`刚刚`,"common.status":`状态`,"common.task":`Task`,"common.you":`你`,"common.waiting":`等待中`,"composer.addImage":`添加图片`,"composer.agentProgress":`向 Agent 获取进度报告`,"composer.agentProgressPrompt":`请给我一份当前 Goal 的进度报告:已完成、执行中、阻塞和下一步。`,"composer.attachImageHint":`选择、粘贴或拖入图片`,"composer.clarifyDefer":`暂缓 Todo 需要可自动判断的恢复条件。请补充 todo_done:、pr_merged:[owner/repo]#、capacity_available: 或 resume_at:<带时区 RFC3339 时间>。`,"composer.clarifySingleAction":`这句话包含多个可能修改状态的操作。请一次描述一项操作,我会逐项展示确认预览。`,"composer.createGoal":`创建新 Goal`,"composer.createGoalDraft":`Goal 草稿`,"composer.createGoalDraftDescription":`补充内容后发送,LoopX 会先展示待确认操作。`,"composer.createGoalDraftLead":`我想创建一个长期 Goal:`,"composer.createGoalTemplate":`我想创建一个长期 Goal: +Notification: Only notify me when needed`,"composer.nextAction":`Ask what’s next`,"composer.nextActionPrompt":`What should I do next?`,"composer.prepareDraft":`Insert a draft and review before sending`,"composer.send":`Send`,"composer.sendMessage":`Send a message to LoopX`,"composer.sendMessageHint":`Send message`,"composer.sentImageAlt":`Remove image {name}`,"conversation.agentPending":`Working…`,"conversation.close":`Close conversation receipt`,"conversation.convertHint":`Turn the Agent’s latest reply into a Task draft`,"conversation.full":`View full conversation`,"conversation.receipt":`Conversation receipt`,"conversation.replying":`Replying`,"conversation.title":`Manager conversation`,"conversation.toTask":`Convert to Task`,"digest.away":`Runs since your previous visit`,"digest.completed":`new completions`,"digest.failed":`new failed/interrupted runs`,"digest.needsYou":`currently need confirmation`,"feedback.applying":`Running: {title}`,"feedback.cancelFailed":`Cancel failed: {error}`,"feedback.completed":`Completed: {title}`,"feedback.executionFailed":`Execution failed: {error}`,"feedback.gateRequired":`Your confirmation is required: {summary}`,"feedback.notCompleted":`Not completed: {status}`,"feedback.goalRefreshFailed":`The Goal opened, but its latest state could not be refreshed. Use Refresh to try again.`,"feedback.preparingPreview":`Preparing confirmation preview: {title}`,"feedback.previewFailed":`Could not prepare the confirmation preview: {error}`,"feedback.sendFailed":`Send failed: {error}`,"feedback.sendGenericError":`Could not send the message. Try again later.`,"feedback.stale":`State changed, so nothing was applied. Generate a new confirmation preview.`,"feedback.taskDraftCreated":`Created a Task draft from the reply. Edit and send it to review the confirmation preview.`,"goal.defaultTitle":`New personal Goal`,"goal.initialTodo":`Work toward the completion criteria: {criteria}`,"goal.objectiveBoundary":`Execution boundary: {boundary}`,"goal.objectiveCompletion":`Completion criteria: {criteria}`,"drawer.advancedDiagnostics":`Advanced diagnostics`,"drawer.agentWorking":`Agent is continuing; the record updates automatically.`,"drawer.analysis":`Analyzing`,"drawer.apply":`Confirm and apply`,"drawer.applying":`Applying…`,"drawer.attentionBlocking":`Blocking an Agent`,"drawer.attentionWaiting":`Waiting for your decision`,"drawer.autoNotify":`Human-gate auto notifications`,"drawer.branch":`Branch`,"drawer.closeDetail":`Close details and return to {context}`,"drawer.connected":`Connected`,"drawer.correctionDescription":`The message keeps the current Goal, Todo, and Agent Session context.`,"drawer.correctionLabel":`Guide {agent}`,"drawer.correctionPlaceholder":`For example: focus on permission risks first and do not commit yet…`,"drawer.correctionSend":`Send guidance`,"drawer.correctionTextarea":`Enter guidance for Goal {goal}, Agent {agent}, Run {run}`,"drawer.copyRepository":`Copy repository identity`,"drawer.copyRepositoryDone":`Repository identity copied`,"drawer.copyRepositoryError":`Copy failed. Check browser clipboard permission.`,"drawer.copyRepositorySuccess":`Copied. You can paste it into another tool.`,"drawer.cost":`Cost 24h / 7d`,"drawer.costShort":`Cost`,"drawer.durationShort":`Duration`,"drawer.period24h":`24h`,"drawer.period7d":`7d`,"drawer.tokens":`Tokens 24h / 7d`,"drawer.tokensShort":`tokens`,"drawer.usageNotMeasured":`Not measured`,"drawer.currentGoal":`Current Goal`,"attentionDetail.title":`Request details`,"attentionDetail.request":`What is requested`,"attentionDetail.decision":`Decision requested`,"attentionDetail.unknownRequest":`Not specified; review the source before deciding`,"attentionDetail.open":`Open in current projection`,"attentionDetail.closed":`Closed`,"attentionDetail.deferred":`Deferred`,"attentionDetail.superseded":`Replaced`,"attentionDetail.unknown":`Status not provided`,"attentionDetail.unavailable":`The source has not confirmed this item; refresh before acting`,"attentionDetail.unknownReason":`The source has not provided a reason.`,"attentionDetail.targetTodo":`Linked Todo to unblock`,"attentionDetail.targetAgent":`Agent named by the request`,"attentionDetail.scope":`Declared decision scope`,"attentionDetail.notProvided":`Not provided`,"attentionDetail.replacement":`Replacement Todo`,"attentionDetail.openReplacement":`Open replacement`,"attentionDetail.boundary":`Reading this detail does not resolve a gate or grant authority. Available decisions require a fresh preview.`,"drawer.decisionDefaultEvidence":`No additional public-safe evidence is attached. The next step will still show a Preview first.`,"drawer.decisionDefaultReason":`This decision affects the next step of the current Todo.`,"drawer.decisionDefer":`Decide later`,"drawer.decisionMore":`More decisions`,"drawer.decisionReject":`Reject`,"drawer.decisionReview":`Review impact and decide`,"drawer.dependencies":`Dependencies`,"drawer.detailsAndActions":`Details & actions`,"drawer.duration":`Duration 24h / 7d`,"drawer.evidence":`Evidence`,"drawer.executionHistory":`Execution history`,"drawer.executionRecord":`Run record`,"drawer.executionRecordAndResult":`Execution & result`,"drawer.explainDecision":`Explain this decision`,"drawer.gateApproveHint":`Run one command in the terminal to complete approval:`,"drawer.gateRejectHint":`Replace approve with reject at the end to decline. This notice disappears after the command runs.`,"drawer.gateRequiresHost":`Host confirmation required`,"drawer.gateRequiresHostDescription":`This page cannot approve this protected permission change. Nothing was written by your click.`,"drawer.goalAutoRun":`Automatic runs for this Goal`,"drawer.goalChanges":`Pending changes for this Goal`,"drawer.goalDetails":`Goal details`,"drawer.group":`Group`,"drawer.inspectorFull":`Switch to full screen`,"drawer.inspectorFullView":`Full-screen view`,"drawer.inspectorHalf":`Switch to half screen`,"drawer.inspectorHalfView":`Half-screen view`,"drawer.lastNotification":`Latest notification`,"drawer.larkConfigure":`Configure Lark connection`,"drawer.larkConnect":`Connect Lark App`,"drawer.larkConnection":`Lark connection`,"drawer.larkNotConfigured":`Not configured`,"drawer.larkNotConfiguredDescription":`After setup, LoopX sends a Feishu notification when this Goal needs your confirmation.`,"drawer.managerChanges":`Pending Manager changes`,"drawer.moreActions":`More actions`,"drawer.moreRunActions":`More run actions`,"drawer.nextTransition":`Next transition`,"drawer.noExecutionHistory":`No execution history yet.`,"drawer.noRun":`Execution Session has not started`,"drawer.noRunDescription":`Run records will appear here after an Agent starts execution.`,"drawer.notAssigned":`Unassigned`,"drawer.notLinked":`Not linked`,"drawer.notSet":`Not set`,"drawer.outputDetails":`Output details`,"drawer.outputRecorded":`This output is recorded on the current Goal.`,"drawer.outputSafePreview":`Public-safe output preview`,"drawer.outputRun":`Run`,"drawer.outputTodo":`Todo`,"drawer.outputs":`Outputs from this run`,"drawer.previewUnavailable":`No public-safe inline preview is available for this output.`,"drawer.priority":`Priority`,"drawer.progress":`Progress`,"drawer.proposalApplied":`Applied. LoopX state will refresh.`,"drawer.proposalApplyFailed":`Apply failed. No changes were written.`,"drawer.proposalApplyFailedHint":`Refresh the Goal state and regenerate. If it still fails, keep this page open and inspect advanced diagnostics.`,"drawer.proposalClose":`Close`,"drawer.proposalDefer":`Later`,"drawer.proposalDeferred":`Deferred. You can apply it later or regenerate it.`,"drawer.proposalEnterGoal":`Open new Goal`,"drawer.proposalExplainer":`After confirmation, LoopX applies this change and shows the write result. Closing or canceling changes nothing.`,"drawer.proposalRecheck":`Recheck against latest state`,"drawer.proposalRegenerate":`Retry with latest state`,"drawer.proposalRejected":`Rejected. This change will not be written.`,"drawer.proposalStale":`Source state changed. Recheck against the latest state.`,"drawer.proposalViewGoal":`View updated Goal`,"drawer.reassign":`Reassign to`,"drawer.reassignSummary":`Reassign: {task}`,"drawer.reason":`Reason`,"drawer.recoveryDescription":`Local history is preserved. Choose a recovery path.`,"drawer.recoveryFailed":`Upstream Session recovery failed`,"drawer.recoveryNewSession":`Start a new Session with context`,"drawer.recoveryRetry":`Retry recovery`,"drawer.repositoryRole":`Execution workspace`,"drawer.repository":`Repository`,"drawer.replyMode":`Reply mode`,"drawer.subagentApplied":`Applied and verified against the shared Goal state.`,"drawer.subagentAppliedRefreshFailed":`Applied and verified. The status view could not refresh; retry the page refresh later.`,"drawer.subagentApplying":`Applying and verifying shared-state readback…`,"drawer.subagentApplyFailed":`Could not apply the sub-agent setting.`,"drawer.subagentChildLimit":`Current limit`,"drawer.subagentConfirmDisable":`Confirm turning off sub-agent execution`,"drawer.subagentConfirmEnable":`Confirm turning on sub-agent execution`,"drawer.subagentCurrentBoundary":`Current task-domain restriction`,"drawer.subagentDescription":`Allows the runtime to create temporary child agents for independent tasks only after Todo, quota, capability, and write-scope gates pass. It does not force parallel work or grant durable authority.`,"drawer.subagentDisable":`Preview turning off sub-agent execution`,"drawer.subagentDisableSummary":`New child-agent execution will be disabled for this Goal. Existing Todo ownership and execution records stay unchanged.`,"drawer.subagentDomainInvalid":`The selected task-domain restriction is invalid.`,"drawer.subagentDomainTodoCount":`{count} matching open Todos`,"drawer.subagentDomains":`Task-domain restriction (optional)`,"drawer.subagentDomainsEmpty":`No open advancement Todo declares task_domain. Leave this empty to keep child execution unrestricted by task domain.`,"drawer.subagentDomainsHint":`Leave every option clear to apply no task-domain filter. Selecting domains admits only matching typed Todos; all other execution gates still apply.`,"drawer.subagentDomainsUnrestricted":`No task-domain restriction`,"drawer.subagentEnable":`Preview turning on sub-agent execution`,"drawer.subagentLabel":`Per-Goal execution boundary`,"drawer.subagentModel":`Child model`,"drawer.subagentEffort":`Child reasoning effort`,"drawer.subagentModelDefault":`Host default`,"drawer.subagentLunaPreset":`Use Luna / max`,"drawer.subagentClearModel":`Clear model preference`,"drawer.subagentModelHint":`Use Preview configuration update to save this preference. It can be saved while execution is off; host support is checked at launch.`,"drawer.subagentModelRequired":`Choose a child model before setting reasoning effort.`,"drawer.subagentMaxChildren":`Maximum child agents`,"drawer.subagentNoChange":`The current Goal already matches this setting; nothing was written.`,"drawer.subagentPending":`Pending confirmation`,"drawer.subagentPreviewBoundary":`Preview configuration update`,"drawer.subagentPreviewFailed":`Could not create the sub-agent setting preview.`,"drawer.subagentPreviewing":`Checking the latest Goal state…`,"drawer.subagentPreviewReady":`Preview locked. Confirm to apply this Goal setting.`,"drawer.subagentPreviewSummary":`Allow up to {count} child agents. Task-domain restriction: {domains}.`,"drawer.subagentRemoteReadOnly":`This source is read only. Open the Goal on its host to change the setting.`,"drawer.subagentTitle":`Adaptive sub-agent execution`,"drawer.remoteDetailsDescription":`SSH sources expose public-safe status only and do not read connection settings from the source host.`,"drawer.remoteDetailsUnavailable":`Remote details are not projected`,"drawer.resumeNo":`No`,"drawer.resumeYes":`Yes`,"drawer.runDetails":`Execution Session`,"drawer.runInterrupt":`Interrupt this run`,"drawer.runLatest":`View latest execution`,"drawer.runNewSession":`Start new Session`,"drawer.runCloseSession":`Close Session`,"drawer.runRecordEmpty":`No run record yet. The Agent has not started this execution. Check waiting conditions or resume the Session under Details & actions.`,"drawer.runRecordProjected":`No step-by-step record is available. LoopX read {completed}/{total} projected steps{outputs}; inspect the Session under Details & actions.`,"drawer.runRecordProjectedOutputs":` and {count} outputs`,"drawer.runRoleAssistant":`Completed`,"drawer.runRoleSystem":`Needs review`,"drawer.runRoleUser":`Task received`,"drawer.runView":`Session views`,"drawer.scheduleAdd":`Add scheduled check`,"drawer.scheduleDefaultNotification":`Notify only when you are needed`,"drawer.scheduleDefaultStop":`Goal completes or owner stops it`,"drawer.scheduleDefaultTarget":`Wake according to this Goal’s LoopX schedule.`,"drawer.scheduleEdit":`Change to every 2 hours`,"drawer.scheduleLast":`Last run`,"drawer.scheduleLocalTimezone":`Local timezone`,"drawer.scheduleNext":`Next run`,"drawer.scheduleNeverRun":`Not run yet`,"drawer.scheduleNotification":`Notification`,"drawer.schedulePause":`Pause`,"drawer.schedulePending":`Waiting for schedule`,"drawer.scheduleResume":`Resume`,"drawer.scheduleRunNow":`Run now`,"drawer.scheduleStop":`Stop {kind}`,"drawer.scheduleStopCondition":`Stop condition`,"drawer.scheduleTimezone":`Timezone`,"drawer.sessionRecoverable":`Resumable`,"drawer.sessionStatus":`Session status`,"drawer.setupHeartbeat":`Set up Heartbeat`,"drawer.taskActions":`Pending Todo actions`,"drawer.taskAdvancement":`Advancement task`,"drawer.taskBlock":`Mark blocked`,"drawer.taskComplete":`Mark complete`,"drawer.taskCompletedNote":`This task is retained as a read-only record.`,"drawer.taskCompletedTitle":`Task completed`,"drawer.taskDefer":`Defer`,"drawer.taskDeferCondition":`Todo defer resume condition`,"drawer.taskDeferInvalid":`Unsupported condition format; use one of the deterministic conditions below.`,"drawer.taskDeferPlaceholder":`For example, resume_at:2026-09-14T09:00:00+08:00`,"drawer.taskDeferReview":`Review defer`,"drawer.taskDeferSupported":`Supports todo_done, pr_merged, capacity_available, and timezone-aware resume_at conditions.`,"drawer.taskDeferUntil":`Defer until`,"drawer.taskDetails":`Todo details`,"drawer.taskInfo":`Task information`,"drawer.taskManage":`Manage task`,"drawer.taskNextCompleted":`Create a follow-up task`,"drawer.taskNextOpen":`Advance or update status`,"drawer.taskOrdinary":`Task`,"drawer.taskStatusBlocked":`Blocked`,"drawer.taskStatusDeferred":`Deferred`,"drawer.resumeWhen":`Resume condition`,"drawer.resumeState":`Resume state`,"drawer.resumePending":`Waiting for condition`,"drawer.resumeReady":`Ready to resume`,"drawer.resumeReceipt":`Resume receipt`,"drawer.taskNextDeferred":`Wait for the resume condition, then reassess`,"drawer.taskNextResumeReady":`Resume condition met; awaiting lifecycle replan`,"drawer.taskStatusCompleted":`Completed`,"drawer.taskStatusOpen":`Ready`,"drawer.taskSuccessor":`Create follow-up Todo`,"drawer.taskSuccessorNote":`Owner marked this blocked while waiting for more context.`,"drawer.taskSuccessorSummary":`Create follow-up Todo: {task}`,"drawer.taskSuccessorText":`Follow-up work for {task}`,"drawer.taskType":`Task type`,"drawer.topic":`Topic`,"drawer.trigger":`Trigger`,"drawer.titleAttention":`Needs you`,"drawer.titleOutput":`Output details`,"drawer.titleProposalApplied":`Execution result`,"drawer.titleProposalConfirm":`Confirm execution`,"drawer.titleSchedule":`Scheduled check`,"drawer.unconfigured":`Not configured`,"drawer.workspaceCandidates":`Available workspaces`,"files.emptySummary":`Public-safe output`,"files.empty":`No files, outputs, or verified reports yet.`,"files.loadingReports":`Loading verified milestone reports…`,"files.reportDelta":`+{added} added · {changed} changed`,"files.reportAdded":`added`,"files.reportChanged":`changed`,"files.reportGeneration":`Generation`,"files.reportLoadFailed":`Could not load verified reports`,"files.reportPublication":`Publication`,"files.title":`Files & Outputs`,"files.verifiedReport":`Verified milestone report`,"header.agentUnavailable":`Unavailable`,"header.chatRuntime":`Chat`,"header.workAgentCount":`{count} work Agents`,"header.chat":`Chat`,"header.files":`Files`,"header.goalCapabilities":`Capability settings`,"header.goalCapabilitiesDescription":`Manage overrides and inherited machine defaults.`,"header.goalDetails":`Goal details`,"header.goalDetailsDescription":`Review status, usage, repository, notifications, and sessions.`,"header.goalSettings":`Goal settings`,"header.goalSettingsDescription":`Open Goal details or capability settings`,"header.goalNavigation":`Goal navigation`,"header.goalView":`Goal view`,"header.live":`Live`,"header.manager":`LoopX Manager`,"header.managerDescription":`Your personal workspace across Goals`,"header.managerOverview":`Overview`,"header.managerView":`Manager view`,"header.openGoalNavigation":`Open Goal navigation`,"header.readOnlySourceDescription":`{source} is displayed read-only through an SSH tunnel`,"header.refresh":`Refresh status`,"header.refreshDone":`Updated just now`,"header.refreshFailed":`Refresh failed`,"header.refreshing":`Refreshing`,"header.selectAgent":`Select Agent`,"header.selectChatRuntime":`Select chat runtime`,"header.tasks":`Tasks`,"header.themeBrutal":`Switch to brutal theme`,"header.themePaper":`Switch to default theme`,"home.blockingSummary":`{count} are blocking an Agent.`,"home.completedGoals":`Completed Goals`,"home.empty":`Nothing here`,"startup.goalLoading":`Loading status…`,"startup.goalError":`Could not load status`,"startup.progress":`{loaded} of {total} active Goals loaded`,"startup.partial":`Goal states are updating. Counts are incomplete.`,"startup.independent":`Other Goals remain available while this Goal loads.`,"startup.error.timeout":`The request timed out. Retry when the local service is ready.`,"startup.error.network":`The connection was interrupted. Retry to reconnect.`,"startup.error.service":`The local service is temporarily unavailable. Retry to continue.`,"startup.error.revision":`The Goal directory changed during loading. Refresh to synchronize.`,"startup.error.scope":`This Goal is no longer available in the selected source. Refresh the directory.`,"startup.error.invalid":`The status response could not be read. Refresh or check for a LoopX update.`,"startup.retry":`Retry`,"startup.retryFailed":`Retry failed Goals`,"startup.failedCount":`{count} Goals could not be loaded. Ready Goals remain available.`,"home.greeting":`Hi, I’m your LoopX Manager`,"home.history":`History`,"home.lane.needsYou":`Needs you`,"home.lane.needsYouDescription":`Waiting for your decision, authorization, or context`,"home.lane.observing":`Observing`,"home.lane.observingDescription":`Monitoring continuously and notifying you when something changes`,"home.lane.running":`Running`,"home.lane.runningDescription":`Agents are making progress and reporting back`,"home.lane.scheduled":`Scheduled`,"home.lane.scheduledDescription":`Queued until its time or prerequisite arrives`,"home.noActivity":`No activity yet`,"home.noFirstActivity":`Waiting for first activity`,"home.noCompletedGoals":`No completed Goals yet`,"home.preservedState":`State is preserved and can be resumed`,"home.stopped":`Stopped`,"home.systemHealth":`System health: {summary}`,"home.taskCount":`{count} Tasks`,"home.todayAt":`Today {time}`,"home.waitingCount":`You have {count} items to handle.`,"home.workspace":`Goal workspace`,"lark.allMessages":`All messages in this topic`,"lark.allTopicMessages":`All topic messages`,"lark.agentIngress":`Agent ingress`,"lark.agentAppPermissions":`Every selected Agent needs a Lark App that is ready for group mentions and replies.`,"lark.agentApps":`Lark App per Agent`,"lark.agentAppsDescription":`The default App is preselected. Assign a different compatible App when an Agent needs its own bot identity.`,"lark.agentAppSelection":`Lark App for {agent}`,"lark.appCreated":`App created`,"lark.appCreateFailed":`Creation failed`,"lark.appLoading":`Loading available Lark Apps…`,"lark.appPermissions":`This App can send connection messages, but lacks the bot permissions required to receive group mentions or reply automatically. Enable im:message.group_at_msg:readonly, im:message.send_as_bot, and the im.message.receive_v1 event, publish a new version, then refresh.`,"lark.appProfile":`Lark App`,"lark.apps":`Lark Apps`,"lark.autoReplyUnavailable":`Auto reply unavailable`,"lark.autoReplyReady":`Auto reply ready`,"lark.bindGoal":`Bind to Goal`,"lark.cancel":`Cancel`,"lark.cardinality":`One Lark App · many Goals · one isolated route per Agent`,"lark.capture":`Capture`,"lark.captureAddressed":`Only messages that mention or reply to the App`,"lark.captureAll":`All messages in this Goal topic`,"lark.captureScope":`Capture scope`,"lark.captureScopeDescription":`Controls which Topic messages enter LoopX without expanding Agent permissions.`,"lark.closeConnection":`Close connection dialog`,"lark.closeCreate":`Close create dialog`,"lark.closeSettings":`Close Lark settings`,"lark.connect":`Connect`,"lark.connectAllAgents":`Connect every registered Agent`,"lark.connectAllAgentsAction":`Connect {count} Agents`,"lark.connectAllAgentsDescription":`Create {count} isolated Agent Topics in one guided action. Send requests inside the matching Topic; each Agent keeps its own route and inbox.`,"lark.connectApp":`Connect Lark App`,"lark.connection":`Connection`,"lark.connections":`Connections`,"lark.configuration":`Lark configuration`,"lark.continueFeishu":`Continue in Feishu`,"lark.createAutomatically":`Create Goal topic automatically`,"lark.createAutomaticallyDescription":`A dedicated, Agent-labelled Topic will be created for every selected Agent.`,"lark.defaultAgentAppDescription":`Used to find the target group and as the default for every selected Agent. Per-Agent choices below override it.`,"lark.description":`Manage reusable Lark Apps and connect group chats to Goals through dedicated topics.`,"lark.editConnection":`Edit Lark Connection`,"lark.goalConnections":`{count} Goal connections`,"lark.goalTopicConnections":`Lark Goal Topic connections`,"lark.groupChat":`Group chat`,"lark.groupEmpty":`This bot has not joined a group that can be connected. Add it to a Feishu group first, then return to refresh or search.`,"lark.groupLoading":`Reading groups joined by this bot…`,"lark.groupSearch":`Search groups joined by this bot`,"lark.historyPermission":`Group-history permission (separate capability)`,"lark.health.eventProcessed":`{events} events processed, {replies} replies sent.`,"lark.health.eventUnverified":`Event subscription needs verification`,"lark.health.eventUnverifiedDetail":`The provider listener is ready, but no event has arrived. Enable im.message.receive_v1 and group mention permissions, publish a new version, then send a new @ mention inside this Agent Topic. Group-level messages fail closed when multiple Agent routes exist.`,"lark.health.ignoredSelf":`The bot’s own message was ignored to prevent duplicate replies.`,"lark.health.invalidRouting":`Invalid routing configuration`,"lark.health.invalidRoutingDetail":`The connection was safely disabled. Select a processing mode again and save.`,"lark.health.lastStatus":`Latest event status: {status}`,"lark.health.listening":`Listening`,"lark.health.messageContextPermission":`Message permission required`,"lark.health.messageContextPermissionDetail":`A message event arrived, but group context could not be read. Publish and authorize group message read access for this App.`,"lark.health.notAddressed":`Latest message did not directly @ the bot`,"lark.health.notAddressedDetail":`Listening is healthy. This connection only responds to direct @ mentions or replies to the bot.`,"lark.health.notStarted":`Listener not started`,"lark.health.notStartedDetail":`Refresh the connection or restart LoopX, then try again.`,"lark.health.processingFailed":`Message processing failed`,"lark.health.processingFailedDetail":`The message event arrived, but Agent processing failed. Review local diagnostics and retry.`,"lark.health.queued":`Queued in the Agent inbox`,"lark.health.queuedDetail":`The message will be processed asynchronously by {agent} without starting a general Chat Session.`,"lark.health.sourceDisconnected":`Event connection disconnected`,"lark.health.sourceDisconnectedDetail":`The event consumer exited unexpectedly. Check that the app profile uses Feishu for Feishu apps or Lark for international Lark, then inspect connection and subscription errors. LoopX is retrying; successful history queries do not prove live delivery.`,"lark.health.retrying":`Retrying listener`,"lark.health.retryingDetail":`Event listening was interrupted and LoopX is retrying automatically.`,"lark.health.routeAmbiguous":`Message matches multiple Goals`,"lark.health.routeAmbiguousDetail":`The same bot and group have multiple full-group capture connections. Use a separate bot for each Agent or keep only one full-group connection.`,"lark.health.routeMismatch":`Message did not match this Goal Topic`,"lark.health.routeMismatchDetail":`The event came from another group or Topic. Reconnect this Goal to the correct group, then send a new @ mention.`,"lark.health.routeUnavailable":`Message cannot be routed to the Goal`,"lark.health.routeUnavailableDetail":`Connection data is incomplete. Reconnect this Goal, then send a new @ mention.`,"lark.health.starting":`Starting`,"lark.health.startingDetail":`LoopX is starting message event listening for this App.`,"lark.health.unavailable":`Auto reply unavailable`,"lark.health.waiting":`Waiting`,"lark.incomingMessages":`Incoming messages`,"lark.ingressAsync":`Async inbox`,"lark.ingressAsyncDescription":`Write to the Agent private inbox for a later explicit drain.`,"lark.editPreservesIdentity":`Saving preserves this App, group and Topic. Old connections upgrade to the Agent inbox by default.`,"lark.conversationKind":`Connection purpose`,"lark.managerConversation":`Manager · live conversation`,"lark.workerConversation":`Worker Agent · background tasks`,"lark.managerConversationDescription":`The built-in manager responds as you chat and delegates long-running work to background Agents. Group and private conversations keep separate histories.`,"lark.ingressLegacy":`Upgrade available`,"lark.ingressLegacyDescription":`Save this connection to upgrade to the Agent inbox. Existing messages remain in the same Topic.`,"lark.ingressQueue":`Queuing`,"lark.ingressQueueDescription":`Enter the same Agent Session's bounded FIFO queue and run after the current Turn.`,"lark.ingressSteering":`Steering`,"lark.ingressSteeringDescription":`Deliver to the active Turn and reject safely when no exact active Turn exists.`,"lark.loading":`Loading Lark configuration…`,"lark.management":`Lark management`,"lark.openEventSettings":`Open Feishu event settings`,"lark.mentions":`Mentions`,"lark.mentionsOnly":`Mentions only`,"lark.needsMessagePermissions":`Needs message permissions`,"lark.needsSetup":`Needs setup`,"lark.newApp":`New Lark App`,"lark.noAgentConfigured":`No Agent configured`,"lark.noConnections":`No matching connections.`,"lark.noProfiles":`No lark-cli App profiles are available yet.`,"lark.profileName":`Profile name`,"lark.profileValidation":`Profile can contain only letters, numbers, periods, underscores, and hyphens.`,"lark.processing":`Processing`,"lark.region":`Region`,"lark.registerAnother":`+ Register another Lark App — Create through Feishu`,"lark.reopenFeishu":`Reopen Feishu`,"lark.settingsConfigure":`Configure {goal}`,"lark.settingsDisconnect":`Disconnect {goal}`,"lark.replyMode":`Reply mode`,"lark.replyModeDescription":`Replies are limited to the source Topic to prevent cross-group or cross-Goal delivery.`,"lark.reusableApps":`{count} reusable Apps`,"lark.reusableWorkspaceApp":`Reusable workspace App`,"lark.routesUnverified":`{count} Lark routes pending verification`,"lark.saveConnection":`Save connection`,"lark.searchConnections":`Search Lark connections`,"lark.searchPlaceholder":`Search Apps, groups, Goals, or topics`,"lark.setupCopy":`LoopX opens the official Feishu creation page through lark-cli. App credentials stay in the system Keychain; LoopX stores only the profile reference.`,"lark.someoneMentions":`Someone mentions the Agent`,"lark.targetAgent":`Target Agent`,"lark.targetAgentDescription":`Choose a registered Agent in this Goal. This connection delivers to one Agent; it does not broadcast or grant permissions. Steering and Queuing require that Agent's exact active Session.`,"lark.agentUnavailable":`{agent} · no longer available`,"lark.selectRegisteredAgent":`Select an available registered Agent before connecting. The previous Agent will not be replaced automatically.`,"lark.topicPreview":`Topic preview`,"lark.topicReply":`Topic reply`,"lark.trigger":`Trigger`,"lark.waitingFeishu":`Waiting for Feishu`,"lark.waitingFeishuDescription":`Complete Feishu authorization in the new window. This page updates automatically when it is ready.`,"lark.waitingLink":`Generating the official Feishu creation link…`,"lark.error.appCreate":`Lark App creation failed`,"lark.error.appRequired":`Select a Lark App profile.`,"lark.error.bind":`Connection failed`,"lark.error.bindPreview":`Connection preview failed`,"lark.error.configuration":`Could not load Lark configuration`,"lark.error.groupLookup":`Could not read groups joined by this bot. Check the bot status and try again.`,"lark.error.groupLoad":`Could not load group chats`,"lark.error.invalidApp":`The Lark App profile is unavailable or has not completed authorization.`,"lark.error.messagePermissions":`This App lacks the bot permissions required for automatic replies. Enable im:message.group_at_msg:readonly and im:message:send_as_bot, publish a new version, then refresh.`,"lark.error.provider":`The Feishu API call failed without a verified receipt. Try again later.`,"lark.error.setupPoll":`Could not read creation status`,"lark.error.setupStart":`Could not start Lark App creation`,"lark.error.cliExecutable":`The configured lark-cli was found but cannot run. Check the installation or launch arguments.`,"lark.error.cliMissing":`lark-cli was not found. Install lark-cli and restart LoopX.`,"lark.error.cliStart":`lark-cli failed to start. Check the installation and restart LoopX.`,"lark.error.disconnect":`Disconnect failed`,"notifications.autoNotify":`Send automatically when your confirmation is required`,"notifications.bind":`Bind notification group`,"notifications.bindConfirm":`Bind “{goal}” to “{target}”. LoopX will verify that the bot is in the group and send a confirmation message.`,"notifications.bindFailed":`Binding failed`,"notifications.bound":`Bound`,"notifications.confirmBind":`Confirm binding`,"notifications.description":`Send Goal changes that need your confirmation to a Feishu group. Bindings and automatic delivery use the existing channel.`,"notifications.disabled":`Disabled`,"notifications.group":`Notification group: {target}`,"notifications.loadFailed":`Could not load notification groups`,"notifications.noTargets":`No notification groups are available. Group delivery uses a private bot identity; configure one from the terminal first:`,"notifications.notBound":`Not bound`,"notifications.recent":`Latest {time}`,"notifications.sentCount":`{count} sent`,"notifications.settings":`Goal notification bindings`,"notifications.setupFailed":`Could not update settings`,"notifications.title":`Feishu group notifications`,"proposal.field.agentId":`Agent`,"proposal.field.cadence":`Frequency`,"proposal.field.completionCriteria":`Completion criteria`,"proposal.field.executionBoundary":`Execution boundary`,"proposal.field.goalId":`Goal ID`,"proposal.field.heartbeat":`Heartbeat`,"proposal.field.initialTodos":`Initial tasks`,"proposal.field.objective":`Objective`,"proposal.field.operation":`Operation`,"proposal.field.operationState":`Operation state`,"proposal.field.resultDelivery":`Result delivery`,"proposal.field.confirmationBoundary":`Confirmation boundary`,"proposal.field.expiresAt":`Expires at`,"proposal.field.permission":`Permission`,"proposal.field.reason":`Reason`,"proposal.field.stopCondition":`Stop condition`,"proposal.field.target":`Check target`,"proposal.field.timezone":`Timezone`,"proposal.field.title":`Title`,"proposal.field.workspace":`Execution workspace`,"actionReview.targetChanged":`The preview target does not match the requested Goal and operation. Generate a new preview.`,"actionReview.ready_stop":`Pausing is reversible. This validated preview can apply directly; completion still requires verified readback.`,"actionReview.resume_review":`Review before restoring automatic scheduling. Quota, gates and Todo constraints still apply.`,"actionReview.delete_review":`Review removal of this stopped Goal from the registries. Project files and history are preserved.`,"actionReview.action_review":`Review the target and impact before applying this proposal.`,"actionReview.protected_action":`This action needs explicit review. Confirmation cannot replace required authority.`,"actionReview.unknown_permission":`The permission classification is not recognized. Recheck the proposal before continuing.`,"actionReview.unknown_action":`This lifecycle operation is not recognized. Recheck the proposal before continuing.`,"actionReview.incomplete_proposal":`The preview is missing validation or an available apply transition. Generate a new preview.`,"actionReview.authority_gate":`A gate prevents execution. Resolve its requirements, then recheck the proposal.`,"actionReview.stale_proposal":`The source state changed. Generate a new preview; the previous decision no longer applies.`,"actionReview.apply_pending":`Execution is in progress. Wait for its result before retrying.`,"actionReview.readback_verified":`The action completed and its resulting state was verified.`,"actionReview.readback_unverified":`The action returned without verified readback. Completion is not confirmed; recheck the state.`,"actionReview.operation_group_confirmation":`This exact request can only be confirmed on its original card in the bound Feishu group. The Dashboard does not expose a local execution control.`,"actionReview.operation_result_delivery_pending":`The operation outcome was recorded, but the original group result card has not passed readback verification yet.`,"actionReview.apply_failed":`Execution did not complete. Check the failure and regenerate the preview before retrying.`,"actionReview.inactive_proposal":`This proposal is no longer ready to execute. Recheck it before continuing.`,"proposal.gate.default":`Host confirmation required`,"proposal.impact.default":`After confirmation, the canonical LoopX service will write the state change.`,"proposal.impact.goalCreate":`After confirmation, LoopX will create the Goal and its initial Todo, then let the selected Agent start the first run.`,"proposal.impact.lifecycleDelete":`After confirmation, this stopped Goal is removed from the source and global registries. Project files, history state, and backups are preserved.`,"proposal.impact.lifecycleResume":`After confirmation, the Goal becomes eligible for automatic scheduling and returns to Active Goals. Actual execution still follows quota, Gate, and Todo constraints.`,"proposal.impact.lifecycleStop":`After confirmation, automatic progress stops and the Goal moves to the collapsed Stopped list. History, Todos, and evidence remain available for resuming.`,"proposal.impact.protected":`This action must be completed through the protected LoopX write service.`,"proposal.impact.operation":`The exact terms are read-only here. Confirm or reject the same immutable request in the bound Feishu group; confirmation consumes one canonical claim.`,"proposal.primary.apply":`Confirm and apply`,"proposal.primary.goalCreate":`Create Goal and start first run`,"proposal.primary.lifecycleDelete":`Delete Goal`,"proposal.primary.lifecycleResume":`Resume Goal`,"proposal.primary.lifecycleStop":`Stop Goal`,"proposal.primary.todoStart":`Create task and start execution`,"proposal.primary.operationGroup":`Confirm in Feishu group`,"proposal.primary.operationResultPending":`Result card delivery pending`,"proposal.primary.operationResultVerified":`Verified result`,"proposal.resultDelivery.verified":`Verified in the original group card`,"proposal.resultDelivery.pending":`Pending verified return to the original group card`,"proposal.summary.goalCreate":`Create Goal: {title}`,"proposal.summary.heartbeat":`Set a Heartbeat for the current Goal`,"proposal.summary.lifecycleDelete":`Delete Goal: {title}`,"proposal.summary.lifecycleResume":`Resume Goal: {title}`,"proposal.summary.lifecycleStop":`Stop Goal: {title}`,"proposal.summary.monitor":`Create a scheduled check for the current Goal: {target}`,"proposal.workspace.current":`Current local workspace (no Repository bound)`,"proposal.workspace.named":`{workspace} (execution environment only; does not bind a repository)`,"proposal.workspaceGate.agentImpact":`Bind an Agent identity, then recheck the original action. No Goal has been written.`,"proposal.workspaceGate.agentTitle":`Bind an Agent first`,"proposal.workspaceGate.defaultSummary":`Select the Goal workspace.`,"proposal.workspaceGate.selectionImpact":`After selecting a workspace, LoopX will show the confirmation preview again. The selection itself does not write state.`,"proposal.workspaceGate.selectionTitle":`Select Goal workspace`,"projection.agentAdvancingGoal":`Agent is advancing the current Goal`,"projection.agentIdle":`Nothing needs your attention`,"projection.agentNeedsDecision":`Agent is waiting for your decision`,"projection.agentPreparingNextStep":`Agent is preparing the next step`,"projection.agentStopped":`Stopped by you; history, Todos, and evidence are preserved`,"projection.agentWaitingExternal":`Waiting for an external condition`,"projection.confirmAgentDecision":`Confirm the permission or decision the Agent needs next`,"projection.events24h":`{count} events in the last 24 hours`,"projection.firstReadOnlyAdapterCheck":`Run the first read-only adapter check and save progress`,"projection.goalVerified":`Goal state, Todos, and registration information verified`,"projection.latestRun":`Latest run`,"projection.latestValidation":`Latest validation`,"projection.nextUpdatePending":`Waiting for LoopX to update the next step`,"projection.publicSafeProjection":`Public-safe status projection`,"projection.refreshState":`Refresh LoopX status and confirm the current progress is still valid`,"projection.runEvidenceAvailable":`Run evidence is available`,"projection.runRecorded":`The latest LoopX run is recorded`,"projection.statusRefreshNeeded":`LoopX status needs to be refreshed`,"projection.todoStatusUpdated":`Todo status updated; confirming the next step`,"projection.validationRecorded":`The latest validation is recorded`,"runs.completed":`Completed`,"runs.failed":`Needs review`,"runs.interrupted":`Interrupted`,"runs.queued":`Scheduled`,"runs.ready":`Ready`,"runs.resumeFailed":`Recovery failed`,"runs.running":`Running`,"runs.unknown":`Unknown`,"runs.waiting":`Waiting`,"schedule.active":`Running`,"schedule.heartbeat":`Goal Heartbeat`,"schedule.monitor":`Scheduled & continuous task`,"schedule.paused":`Paused`,"schedule.summary":`Continuously checked under LoopX scheduling constraints`,"schedule.defaultTarget":`Check the current Goal for blockers, progress, and new outputs`,"schedule.unsupportedCalendar":`Scheduled checks do not currently support an exact weekday or time. Use a fixed interval such as “Every 30 minutes,” “Every 2 hours,” or “Daily.” The draft was preserved and no confirmation preview was created.`,"source.add":`Add source`,"source.addConfigured":`Add read-only source`,"source.addMethod":`Source setup method`,"source.addSsh":`Add SSH source`,"source.closeForm":`Close source form`,"source.configured":`Configured SSH`,"source.configuredCount":`Local SSH Hosts · {count}`,"source.configuredGroup":`Configured SSH Hosts · {count} (select to add)`,"source.connected":`Connected`,"source.connecting":`Connecting`,"source.controlPlane":`Control plane source`,"source.copy":`Copy`,"source.copyCommand":`Copy SSH tunnel command`,"source.copyError":`Could not copy the command. Copy it manually below.`,"source.copied":`Copied`,"source.description":`All explicit Hosts are loaded, including Include files. Wildcards are not listed. Run the command first; LoopX never reads SSH keys or configuration details.`,"source.host":`Local SSH Host`,"source.hostEmpty":`No explicit SSH Hosts are available in ~/.ssh/config.`,"source.hostLoadError":`Could not read local SSH Hosts.`,"source.hostPlaceholder":`Enter or search for a Host`,"source.invalid":`The SSH source settings are invalid.`,"source.loadingHosts":`Loading…`,"source.localInteractive":`Local interactive`,"source.localPort":`Local port`,"source.manual":`Manual URL`,"source.manualDescription":`Remote sources always remain read-only projections and never inherit local write permissions.`,"source.name":`Name`,"source.namePlaceholder":`Remote development machine`,"source.notAvailable":`Unavailable`,"source.readOnly":`SSH tunnel · read only`,"source.readOnlyNoticeDescription":`You can view Goals, Tasks, evidence, and run status. Writes, guidance, and Agent sessions remain on the source host.`,"source.readOnlyNoticeTitle":`Remote read-only projection`,"source.readOnlyWriteError":`Remote SSH tunnel sources are read-only projections and cannot perform control-plane writes.`,"source.refreshHosts":`Reload SSH Hosts`,"source.remove":`Remove source {source}`,"source.removeCurrent":`Remove current source`,"source.select":`Select control plane source`,"source.selectHost":`Select a configured SSH Host.`,"source.statusUrl":`Local forwarded URL`,"source.tunnelCommandPending":`Select a Host to generate the tunnel command`,"machine.absent":`Not configured`,"machine.action.create":`Create machine policy`,"machine.action.delete":`Remove machine policy`,"machine.action.unchanged":`No write required`,"machine.action.update":`Update machine policy`,"machine.applied":`Machine policy applied and read back successfully.`,"machine.applyError":`Machine policy could not be applied.`,"machine.applyPreview":`Apply reviewed preview`,"machine.changedNamespaces":`Changed namespaces`,"machine.capabilityCatalog":`Machine capability catalog`,"machine.capabilityEmpty":`No machine-configurable capabilities are registered.`,"machine.configured":`Configured`,"machine.confirmRollback":`Confirm rollback`,"machine.currentRevision":`Current revision`,"machine.currentValue":`Current machine value`,"machine.description":`Browse the same capability catalog as Goal settings. Configure supported machine defaults here; Goal-only capabilities are labeled explicitly.`,"capabilities.rawJson":`Advanced: raw JSON`,"machine.goalOnly":`This capability currently supports Goal configuration only. Open a Goal’s capability settings to configure it; no machine-wide default is applied.`,"machine.desiredRevision":`Desired revision`,"machine.editorUnavailable":`No editor is installed for this namespace`,"machine.editorUnavailableDescription":`The namespace remains visible in the registry. Install or upgrade its Dashboard editor before changing it.`,"machine.editorMode":`Editor mode`,"machine.liveDefault":`Live default; Goal override wins`,"machine.liveDefaultDescription":`Goals without an explicit override read the current machine policy at the capability’s next decision point. Changes and removal affect those existing Goals immediately; an explicit Goal override stays pinned.`,"machine.genericNamespaceDescription":`Edit this registered namespace as JSON. LoopX validates it with the capability-owned schema before previewing any write.`,"machine.jsonConfiguration":`Namespace configuration (JSON)`,"machine.jsonConfigurationHelp":`Only this namespace is updated. Other machine configuration is preserved, and Apply remains locked to the reviewed preview revision.`,"machine.jsonEditor":`JSON`,"machine.editJson":`Edit JSON`,"capabilities.jsonConfiguration":`Goal configuration (JSON)`,"capabilities.jsonHelp":`Edit registered fields for this Goal. Changes require a new preview before applying.`,"capabilities.jsonInvalid":`Enter a valid JSON object using only registered editable fields.`,"machine.backToForm":`Back to form`,"machine.jsonInvalid":`Enter one valid JSON object before previewing changes.`,"machine.loadError":`Machine configuration could not be loaded.`,"machine.machinePolicy":`Machine policy`,"machine.namespaceCount":`Registered namespaces`,"machine.namespaces":`Configuration namespaces`,"machine.periodicReport":`Periodic reports`,"machine.periodicReportDescription":`Default report policy for every Goal without an explicit override. Goal scheduling and delivery consume the effective configuration.`,"machine.periodicReportActivation":`Enabled means automatic delivery at validated stage boundaries`,"machine.periodicReportActivationDescription":`This is not a weekly timer. When LoopX validates a Goal stage completion, an Agent prepares and freezes the report, then automatically delivers it through the configured Goal Channel. The enabled subscription is standing delivery authority; failures and route drift stop closed for repair.`,"machine.changeQualityActivation":`Qualification is a quality gate, not new authority`,"machine.changeQualityActivationDescription":`Goals that inherit this policy qualify their exact final diff. safe_fix allows at most one bounded fix pass inside existing write authority; this setting never grants file, permission, or merge authority.`,"machine.replanCadenceActivation":`Review cadence changes timing, not execution authority`,"machine.replanCadenceActivationDescription":`Goals without an explicit override read this threshold before the next review decision. It does not create Turns, spend quota, or grant authority.`,"machine.preview":`Review exact machine change`,"machine.previewChanges":`Preview changes`,"machine.previewError":`A machine-policy preview could not be created.`,"machine.previewLocked":`Apply is locked to this exact revision. If machine state changes, LoopX requires a new preview.`,"machine.previewRollback":`Preview rollback`,"machine.previewRemoval":`Preview removal`,"machine.profilePreset":`Profile preset`,"machine.profilePresetHelp":`A capability-owned preset, such as weekly-progress.`,"machine.registry":`Typed registry`,"machine.requiredFields":`Enable requires a profile preset, Goal Channel route, and valid timezone.`,"machine.revision":`Machine revision`,"machine.revisionLockedReady":`All changes require a preview and apply only while that exact machine revision remains current.`,"machine.rollbackAvailable":`Rollback is available for the last apply`,"machine.rollbackDescription":`Preview the stored prior revision before restoring it.`,"machine.rollbackError":`The rollback could not be completed.`,"machine.rollbackPreviewDescription":`The prior revision is ready to restore. Confirm to apply this rollback.`,"machine.rolledBack":`The prior machine policy was restored and verified.`,"machine.removed":`Machine policy removed and the resulting configuration read back successfully.`,"machine.routeRef":`Goal Channel route`,"machine.routeRefHelp":`Use a public route alias; credentials and provider identifiers never enter this form.`,"machine.timezone":`Timezone`,"machine.timezoneHelp":`Use an IANA timezone, for example Asia/Shanghai.`,"machine.title":`Machine configuration`,"machine.unchanged":`Machine policy already matches this preview; nothing was written.`,"machine.visualEditor":`Guided`,"capabilities.atomicOverride":`Goal override is atomic`,"capabilities.atomicOverrideDescription":`A complete Goal value wins over the machine default. LoopX never mixes individual fields across scopes.`,"capabilities.applyFailed":`Goal capability changes were not applied.`,"capabilities.applyPreview":`Apply preview`,"capabilities.catalog":`Goal capability catalog`,"capabilities.chooseGoal":`Choose a Goal before inspecting its capabilities.`,"capabilities.defaultValue":`Declared default`,"capabilities.description":`Inspect the capabilities available to this Goal and the exact scope of each setting.`,"capabilities.editorPrepared":`Typed editor contract available`,"capabilities.effectiveSource":`Effective source`,"capabilities.empty":`No capability descriptors are available for this Goal.`,"capabilities.fields":`Registered fields`,"capabilities.goalPolicy":`Goal capability policy`,"capabilities.goalScope":`Goal`,"capabilities.goalValue":`Current Goal value`,"capabilities.loadFailed":`Could not load Goal capabilities`,"capabilities.loading":`Loading Goal capabilities…`,"capabilities.machineOnly":`This capability is configured only at machine scope.`,"capabilities.machineValue":`Live machine default`,"capabilities.machineScope":`Machine`,"capabilities.previewOnly":`Inspection is live. Goal writes remain unavailable until the revision-locked preview and apply path is connected.`,"capabilities.preview":`Revision-locked preview`,"capabilities.previewChanges":`Preview changes`,"capabilities.restoreInheritance":`Restore machine-default inheritance`,"capabilities.previewFailed":`Could not preview Goal capability changes.`,"capabilities.previewLocked":`Apply will re-check this exact plan revision and reject stale changes.`,"capabilities.partialWrite":`Goal value saved; shared projection needs reconciliation`,"capabilities.partialWriteDescription":`The source Goal configuration was written and read back. Its shared runtime projection did not synchronize, so do not submit the change again.`,"capabilities.refreshSource":`Refresh source value`,"capabilities.readOnly":`Read-only capability`,"capabilities.revisionLockedReady":`Changes require a preview and are applied only when its exact revision is still current.`,"capabilities.retry":`Retry`,"capabilities.source.capability_default":`Capability default`,"capabilities.source.goal_override":`Goal override`,"capabilities.source.machine_default":`Live machine default`,"capabilities.source.not_configured":`Not configured`,"capabilities.title":`Goal capabilities`,"settings.close":`Close settings`,"settings.appearance":`Appearance`,"settings.appearanceDescription":`Manage workspace display preferences in this browser.`,"settings.appearanceTabDescription":`Theme and display preferences`,"settings.capabilitiesTabDescription":`Capability overrides for this Goal`,"settings.back":`Back to workspace`,"settings.categories":`Settings categories`,"settings.description":`Manage workspace preferences and integrations.`,"settings.eyebrow":`Workspace preferences`,"settings.general":`General`,"settings.goalConnections":`Goal connections`,"settings.language":`Language`,"settings.languageDescription":`Choose the language used by the LoopX desktop workspace.`,"settings.languageEnglishDescription":`Use English for navigation, settings, and workspace controls.`,"settings.languageEnglish":`English`,"settings.languageSimplifiedChineseDescription":`Use Simplified Chinese for navigation, settings, and workspace controls.`,"settings.languageSimplifiedChinese":`Simplified Chinese`,"settings.languageStoredLocally":`This preference is stored only on this device.`,"settings.languageTabDescription":`Interface language for this device`,"settings.larkTabDescription":`Apps, group chats, and Goal Topic connections`,"settings.machineTabDescription":`Typed defaults shared by capabilities on this machine`,"settings.notifications":`Notifications`,"settings.open":`Settings`,"settings.themeDefault":`Paper`,"settings.themeDefaultDescription":`Calm and lightweight for long-running work.`,"settings.themeDescription":`Choose the workspace visual style. This preference is stored in the current browser.`,"settings.themeHighContrast":`High contrast`,"settings.themeHighContrastDescription":`Stronger borders and more prominent state blocks.`,"settings.themeLoopx":`LoopX standard`,"settings.themeLoopxDescription":`Precise monochrome surfaces, Geist type, and quiet hairline structure.`,"settings.title":`Settings`,"settings.workspaceDisplay":`Workspace display`,"settings.workspaceTheme":`Workspace theme`,"session.closeRecord":`Exit run record`,"session.details":`Session details`,"session.record":`Execution Session · Run record`,"session.recordDescription":`The timeline now shows messages and Turn records from this Session.`,"sidebar.createGoal":`Create Goal`,"sidebar.delete":`Delete`,"sidebar.deleteGoal":`Delete Goal`,"sidebar.manager":`LoopX Manager`,"sidebar.notifications":`Settings`,"sidebar.owner":`Personal workspace`,"sidebar.product":`Personal Agent workspace`,"sidebar.resume":`Resume`,"sidebar.resumeGoal":`Resume Goal`,"sidebar.stop":`Stop`,"tasks.historyLoading":`Loading history…`,"tasks.historyError":`History could not be loaded.`,"tasks.historyExpired":`History snapshot expired. Reload to continue.`,"tasks.historyRetry":`Reload`,"tasks.historyEnd":`End of completed history`,"tasks.historyMore":`Load more`,"tasks.historyLocalOnly":`Open this machine’s Dashboard to browse full history.`,"sidebar.sortGoals":`Reorder Goals`,"sidebar.dragGoal":`Drag to reorder, or use Reorder Goals`,"sidebar.moveUp":`Move {goal} up`,"sidebar.moveDown":`Move {goal} down`,"sidebar.goalMoved":`{goal} moved to position {position}`,"sidebar.orderNotSaved":`Order changed for this visit; browser storage is unavailable.`,"sidebar.stopGoal":`Stop Goal`,"sidebar.stopped":`Stopped`,"sidebar.stoppedLoading":`Loading stopped Goals`,"sidebar.stoppedLoadFailed":`Stopped Goals could not be loaded. Active Goals remain available.`,"sidebar.retryStopped":`Retry`,"state.completed":`Completed`,"state.needsRepair":`Needs repair`,"state.needsYou":`Needs you`,"state.quiet":`Quiet`,"state.running":`Running`,"state.stopped":`Stopped`,"state.waiting":`Waiting`,"tasks.blocked":`Blocked`,"tasks.agentLane":`Work Agent`,"tasks.agentLaneDescription":`Filter this Goal's projected work lanes`,"tasks.agentLaneFilter":`Filter by work Agent`,"tasks.allAgentLanes":`All Agents ({count})`,"tasks.chatAgentReplied":`Agent replied`,"tasks.chatPending":`Sent to Agent`,"tasks.chatPendingDescription":`Processing. Tasks update only after a task operation is confirmed.`,"tasks.chatRecent":`Recent conversation`,"tasks.chatUnchangedDescription":`This conversation did not directly change Tasks. Convert the reply to a Task draft and confirm it when execution is needed.`,"tasks.chatViewReply":`View reply`,"tasks.convertToTask":`Convert to Task`,"tasks.completed":`Completed`,"runs.discoveryPartial":`Some execution details are unavailable. Reconnecting; task summaries are not live execution status.`,"runs.discoveryOffline":`Execution service unavailable. Reconnecting; retained task summaries may be stale.`,"files.openConversation":`Go to conversation`,"files.exportSummary":`Export summary`,"tasks.viewDescription":`Decisions first, then work and recent completions`,"tasks.viewLabel":`Task view`,"tasks.listView":`List`,"tasks.boardView":`Board`,"tasks.completedSummary":`{count} tasks completed. Recent details are projected by the control plane when needed.`,"tasks.emptyCompleted":`No completed tasks yet.`,"tasks.emptyConfirm":`No tasks waiting for confirmation.`,"tasks.emptyRunning":`No queued or running tasks.`,"tasks.emptySchedules":`No scheduled tasks.`,"tasks.emptyGoal":`This Goal has no tasks yet. Describe the next step below and LoopX will show a confirmation preview first.`,"tasks.markComplete":`Mark complete: {name}`,"tasks.moreActions":`More actions: {name}`,"tasks.openExecution":`View execution: {name}`,"tasks.pending":`Pending`,"tasks.pendingAndRunning":`Queued / Running`,"tasks.scheduled":`Scheduled & continuous`,"tasks.sessionError":`Session issue`,"tasks.waiting":`Queued`,"tasks.waitingAge":`Waiting {age}`,"tasks.viewExecution":`View execution`,"tasks.viewResult":`View result`,"time.days":`{count} days`,"time.hours":`{count} hours`,"timeline.emptyGoal":`This Goal has no new activity`,"timeline.emptyGoalDescription":`Ask for progress or send new guidance.`,"timeline.emptyWorkspace":`Your workspace is quiet today`,"timeline.emptyWorkspaceDescription":`Describe a Goal to the LoopX Manager, or ask what deserves attention today.`,"timeline.gateHistory":`{count} historical Gates`,"timeline.pending":`Working…`,"timeline.runCompleted":`{run}: completed`,"timeline.review":`Review`,"timeline.reviewAndConfirm":`Review and confirm`,"timeline.waitingConfirmation":`Needs your confirmation`},"zh-CN":{"acceptance.connected":`已连接`,"acceptance.mapped":`已建立项目映射`,"acceptance.refreshed":`已刷新状态`,"acceptance.inspected":`已检查适配器`,"acceptance.recorded":`已记录执行`,"acceptance.judged":`已记录反馈`,"acceptance.approved":`已记录批准`,"acceptance.ready":`已记录控制器就绪`,"acceptance.attentionSource":`当前状态`,"acceptance.visionSource":`Agent 验收条件`,"acceptance.todoSource":`任务状态`,"acceptance.runSource":`最新执行证据`,"acceptance.title":`验收观察`,"acceptance.unavailable":`验收观测不可用,Goal 是否达成仍未知。`,"acceptance.partial":`当前仅有部分观测。任务完成或缺口列表为空,都不能证明 Goal 已通过验收。`,"acceptance.gaps":`仍需补充的证据`,"acceptance.reasonUnknown":`来源未提供原因`,"acceptance.unknown":`未知`,"acceptance.required":`所需证据或条件`,"acceptance.observed":`观测时间`,"acceptance.noGaps":`现有观测中没有缺口,尚未评估完整验收条件。`,"acceptance.guards":`待处理的门禁决策`,"acceptance.noGuards":`现有观测中没有待处理的门禁决策。`,"acceptance.scope":`决策范围`,"acceptance.next":`当前状态给出的下一步`,"acceptance.historical_progress":`已记录的历史进展`,"acceptance.historical":`历史生命周期记录不授予权限,也不代表通过验收。`,"acceptance.missing":`未获取的来源:`,"acceptance.truncated":`仅展示前 12 条观测。`,"common.actions":`操作`,"common.agent":`Agent`,"common.allMessages":`所有消息`,"common.cancel":`取消`,"common.close":`关闭`,"common.closeActionReceipt":`关闭操作回执`,"common.confirm":`确认`,"common.export":`导出`,"common.failed":`失败`,"common.goal":`Goal`,"common.loading":`加载中…`,"common.none":`无`,"common.off":`关闭`,"common.on":`开启`,"common.open":`打开`,"common.owner":`Owner`,"common.readOnly":`只读`,"common.recently":`刚刚`,"common.status":`状态`,"common.task":`Task`,"common.you":`你`,"common.waiting":`等待中`,"composer.addImage":`添加图片`,"composer.agentProgress":`向 Agent 获取进度报告`,"composer.agentProgressPrompt":`请给我一份当前 Goal 的进度报告:已完成、执行中、阻塞和下一步。`,"composer.attachImageHint":`选择、粘贴或拖入图片`,"composer.clarifyDefer":`暂缓 Todo 需要可自动判断的恢复条件。请补充 todo_done:、pr_merged:[owner/repo]#、capacity_available: 或 resume_at:<带时区 RFC3339 时间>。`,"composer.clarifySingleAction":`这句话包含多个可能修改状态的操作。请一次描述一项操作,我会逐项展示确认预览。`,"composer.createGoal":`创建新 Goal`,"composer.createGoalDraft":`Goal 草稿`,"composer.createGoalDraftDescription":`补充内容后发送,LoopX 会先展示待确认操作。`,"composer.createGoalDraftLead":`我想创建一个长期 Goal:`,"composer.createGoalTemplate":`我想创建一个长期 Goal: 目标: 完成标准: 执行边界(可选): @@ -44,7 +44,7 @@ Goal: Goal: 频率:每天 停止条件:Goal 完成 -通知:仅在需要我时`,"composer.nextAction":`询问下一步`,"composer.nextActionPrompt":`我现在该做什么?`,"composer.prepareDraft":`填入编辑框,确认后再发送`,"composer.send":`发送`,"composer.sendMessage":`向 LoopX 发送消息`,"composer.sendMessageHint":`发送消息`,"composer.sentImageAlt":`移除图片 {name}`,"conversation.agentPending":`正在整理…`,"conversation.close":`关闭对话回执`,"conversation.convertHint":`将 Agent 最新回复转为 Task 草稿`,"conversation.full":`查看完整对话`,"conversation.receipt":`对话回执`,"conversation.replying":`正在回复`,"conversation.title":`管家对话`,"conversation.toTask":`转为 Task`,"digest.away":`自上次访问以来的运行记录`,"digest.completed":`新增完成运行`,"digest.failed":`新增失败或中断`,"digest.needsYou":`当前待确认`,"feedback.applying":`正在执行:{title}`,"feedback.cancelFailed":`取消失败:{error}`,"feedback.completed":`已完成:{title}`,"feedback.executionFailed":`执行失败:{error}`,"feedback.gateRequired":`需要你确认:{summary}`,"feedback.notCompleted":`操作未完成:{status}`,"feedback.goalRefreshFailed":`已打开 Goal,但暂时无法刷新最新状态。请点击刷新重试。`,"feedback.preparingPreview":`正在准备确认预览:{title}`,"feedback.previewFailed":`无法准备确认预览:{error}`,"feedback.sendFailed":`发送失败:{error}`,"feedback.sendGenericError":`消息发送失败,请稍后重试。`,"feedback.stale":`状态已变化,操作未执行,请重新生成确认预览。`,"feedback.taskDraftCreated":`已根据回复生成 Task 草稿。编辑后发送,LoopX 会先展示确认预览。`,"goal.defaultTitle":`新的个人 Goal`,"goal.initialTodo":`按完成标准推进:{criteria}`,"goal.objectiveBoundary":`执行边界:{boundary}`,"goal.objectiveCompletion":`完成标准:{criteria}`,"drawer.advancedDiagnostics":`高级诊断`,"drawer.agentWorking":`Agent 正在继续执行,记录会自动更新。`,"drawer.analysis":`正在分析`,"drawer.apply":`确认并应用`,"drawer.applying":`正在应用…`,"drawer.attentionBlocking":`正在阻塞 Agent`,"drawer.attentionWaiting":`等待你的决定`,"drawer.autoNotify":`Human-gate 自动通知`,"drawer.branch":`分支`,"drawer.closeDetail":`关闭详情:返回{context}`,"drawer.connected":`已连接`,"drawer.correctionDescription":`消息会沿用当前 Goal、Todo 与 Agent Session 上下文。`,"drawer.correctionLabel":`与 {agent} 纠偏`,"drawer.correctionPlaceholder":`例如:先关注权限风险,暂时不要提交…`,"drawer.correctionSend":`发送纠偏`,"drawer.correctionTextarea":`输入纠偏信息:Goal {goal},Agent {agent},Run {run}`,"drawer.copyRepository":`复制仓库标识`,"drawer.copyRepositoryDone":`已复制仓库标识`,"drawer.copyRepositoryError":`复制失败,请检查浏览器剪贴板权限。`,"drawer.copyRepositorySuccess":`已复制,可粘贴到其他工具。`,"drawer.cost":`成本 24h / 7d`,"drawer.costShort":`成本`,"drawer.durationShort":`时长`,"drawer.period24h":`24 小时`,"drawer.period7d":`7 天`,"drawer.tokens":`Token 24 小时 / 7 天`,"drawer.tokensShort":`Token`,"drawer.usageNotMeasured":`未采集`,"drawer.currentGoal":`当前 Goal`,"attentionDetail.title":`事项说明`,"attentionDetail.request":`需要你做什么`,"attentionDetail.decision":`需要作出决定`,"attentionDetail.unknownRequest":`来源未明确,请先查看来源再判断`,"attentionDetail.open":`当前投影中待处理`,"attentionDetail.closed":`已关闭`,"attentionDetail.deferred":`已推迟`,"attentionDetail.superseded":`已被替代`,"attentionDetail.unknown":`来源未提供状态`,"attentionDetail.unavailable":`来源尚未确认当前事项,请刷新后再操作`,"attentionDetail.unknownReason":`来源尚未提供原因。`,"attentionDetail.targetTodo":`关联的待解锁 Todo`,"attentionDetail.targetAgent":`事项指定的 Agent`,"attentionDetail.scope":`声明的决策范围`,"attentionDetail.notProvided":`来源未提供`,"attentionDetail.replacement":`替代 Todo`,"attentionDetail.openReplacement":`打开替代事项`,"attentionDetail.boundary":`阅读详情不会关闭 gate 或授予权限;作出决定前仍需新的操作预览。`,"drawer.decisionDefaultEvidence":`当前状态没有附加公开安全证据;下一步仍会先展示 Preview。`,"drawer.decisionDefaultReason":`该决定会影响当前 Todo 的下一步执行。`,"drawer.decisionDefer":`稍后决定`,"drawer.decisionMore":`更多决定`,"drawer.decisionReject":`拒绝`,"drawer.decisionReview":`查看影响并决定`,"drawer.dependencies":`依赖`,"drawer.detailsAndActions":`详情与操作`,"drawer.duration":`运行时长 24h / 7d`,"drawer.evidence":`证据`,"drawer.executionHistory":`执行历史`,"drawer.executionRecord":`运行记录`,"drawer.executionRecordAndResult":`执行过程与结果`,"drawer.explainDecision":`解释此决定`,"drawer.gateApproveHint":`在终端执行一条命令即可完成审批:`,"drawer.gateRejectHint":`不同意就把末尾的 approve 换成 reject。执行后这条提醒会自动消失。`,"drawer.gateRequiresHost":`需要宿主确认`,"drawer.gateRequiresHostDescription":`页面无权直接批准这类权限变更,你的点击没有写入任何内容。`,"drawer.goalAutoRun":`当前 Goal 的自动运行`,"drawer.goalChanges":`当前 Goal 的待确认变更`,"drawer.goalDetails":`Goal 详情`,"drawer.group":`群聊`,"drawer.inspectorFull":`切换到全屏`,"drawer.inspectorFullView":`全屏查看`,"drawer.inspectorHalf":`切换到半屏`,"drawer.inspectorHalfView":`半屏查看`,"drawer.lastNotification":`最近通知`,"drawer.larkConfigure":`管理 Lark connection`,"drawer.larkConnect":`连接 Lark App`,"drawer.larkConnection":`Lark connection`,"drawer.larkNotConfigured":`未配置`,"drawer.larkNotConfiguredDescription":`配置后,当这个 Goal 出现需要你确认的变更时,会自动发飞书通知。`,"drawer.managerChanges":`管家待确认变更`,"drawer.moreActions":`更多操作`,"drawer.moreRunActions":`更多运行操作`,"drawer.nextTransition":`下一转换`,"drawer.noExecutionHistory":`暂无执行记录。`,"drawer.noRun":`尚未启动执行 Session`,"drawer.noRunDescription":`Agent 开始执行后,运行记录会稳定显示在这里。`,"drawer.notAssigned":`未分配`,"drawer.notLinked":`未关联`,"drawer.notSet":`未设置`,"drawer.outputDetails":`产出详情`,"drawer.outputRecorded":`该产出已记录到当前 Goal。`,"drawer.outputSafePreview":`公开安全产出预览`,"drawer.outputRun":`Run`,"drawer.outputTodo":`Todo`,"drawer.outputs":`本次运行产出`,"drawer.previewUnavailable":`此产出没有可用的公开安全内联预览。`,"drawer.priority":`优先级`,"drawer.progress":`进度`,"drawer.proposalApplied":`已应用,LoopX 状态将刷新。`,"drawer.proposalApplyFailed":`应用失败,没有写入任何变更。`,"drawer.proposalApplyFailedHint":`请刷新 Goal 状态后重新生成;若仍失败,可保留此页并查看高级诊断。`,"drawer.proposalClose":`关闭`,"drawer.proposalDefer":`稍后`,"drawer.proposalDeferred":`已暂缓,可稍后继续应用或重新生成。`,"drawer.proposalEnterGoal":`进入新 Goal`,"drawer.proposalExplainer":`确认后,LoopX 会执行这项变更并显示写入结果。关闭或取消不会修改任何状态。`,"drawer.proposalRecheck":`按最新状态重新检查`,"drawer.proposalRegenerate":`基于最新状态重试`,"drawer.proposalRejected":`已拒绝,这项变更不会写入。`,"drawer.proposalStale":`来源状态已变化,请按最新状态重新检查。`,"drawer.proposalViewGoal":`查看更新后的 Goal`,"drawer.reassign":`改派给`,"drawer.reassignSummary":`重新分配:{task}`,"drawer.reason":`原因`,"drawer.recoveryDescription":`本地历史已经保留,请选择恢复路径。`,"drawer.recoveryFailed":`上游 Session 恢复失败`,"drawer.recoveryNewSession":`携带上下文开始新 Session`,"drawer.recoveryRetry":`重试恢复`,"drawer.repositoryRole":`执行工作区`,"drawer.repository":`仓库`,"drawer.replyMode":`回复方式`,"drawer.subagentApplied":`已写入,并通过共享 Goal 状态读回校验。`,"drawer.subagentAppliedRefreshFailed":`已写入并通过共享 Goal 状态读回;状态投影刷新失败,可稍后手动刷新。`,"drawer.subagentApplying":`正在写入并校验共享状态读回…`,"drawer.subagentApplyFailed":`子代理设置写入失败。`,"drawer.subagentChildLimit":`当前上限`,"drawer.subagentConfirmDisable":`确认关闭子代理执行`,"drawer.subagentConfirmEnable":`确认开启子代理执行`,"drawer.subagentCurrentBoundary":`当前任务领域限制`,"drawer.subagentDescription":`仅在 Todo、配额、能力和写入范围门禁全部通过后,允许运行时为相互独立的任务临时创建子代理;不会强制并行,也不会授予持久权限。`,"drawer.subagentDisable":`预览关闭子代理执行`,"drawer.subagentDisableSummary":`这个 Goal 将不再创建新的子代理;现有 Todo 归属和执行记录不受影响。`,"drawer.subagentDomainInvalid":`所选任务领域限制无效。`,"drawer.subagentDomainTodoCount":`匹配 {count} 个开放 Todo`,"drawer.subagentDomains":`任务领域限制(可选)`,"drawer.subagentDomainsEmpty":`当前没有开放的 advancement Todo 声明 task_domain;保持为空即可不按任务领域限制子代理执行。`,"drawer.subagentDomainsHint":`全部不选表示不按任务领域过滤;选择后只放行匹配且已声明领域的 Todo,其他执行门禁始终生效。`,"drawer.subagentDomainsUnrestricted":`不限制任务领域`,"drawer.subagentEnable":`预览开启子代理执行`,"drawer.subagentLabel":`Per-Goal 执行边界`,"drawer.subagentModel":`子 Agent 模型`,"drawer.subagentEffort":`子 Agent 推理档位`,"drawer.subagentModelDefault":`宿主默认`,"drawer.subagentLunaPreset":`使用 Luna / max`,"drawer.subagentClearModel":`清除模型偏好`,"drawer.subagentModelHint":`填写后通过“预览配置调整”保存,执行关闭时也可保存偏好;启动时须核验宿主支持情况。`,"drawer.subagentModelRequired":`设置推理档位前请先指定子 Agent 模型。`,"drawer.subagentMaxChildren":`最多子代理数`,"drawer.subagentNoChange":`当前 Goal 已是这个设置,没有写入任何内容。`,"drawer.subagentPending":`待确认`,"drawer.subagentPreviewBoundary":`预览配置调整`,"drawer.subagentPreviewFailed":`无法生成子代理设置预览。`,"drawer.subagentPreviewing":`正在核对最新 Goal 状态…`,"drawer.subagentPreviewReady":`预览已锁定,确认后才会写入这个 Goal。`,"drawer.subagentPreviewSummary":`最多允许创建 {count} 个子代理;任务领域限制:{domains}。`,"drawer.subagentRemoteReadOnly":`当前来源只读,请在 Goal 所在主机上修改。`,"drawer.subagentTitle":`自适应子代理执行`,"drawer.remoteDetailsDescription":`SSH 来源只展示公开安全状态,不读取来源主机上的连接配置。`,"drawer.remoteDetailsUnavailable":`远端详情未投影`,"drawer.resumeNo":`否`,"drawer.resumeYes":`是`,"drawer.runDetails":`执行 Session`,"drawer.runInterrupt":`中断本次运行`,"drawer.runLatest":`查看最近执行过程`,"drawer.runNewSession":`开始新 Session`,"drawer.runCloseSession":`关闭 Session`,"drawer.runRecordEmpty":`还没有运行记录。Agent 尚未开始这次执行;请在“详情与操作”查看等待条件或恢复 Session。`,"drawer.runRecordProjected":`当前没有可展示的逐步运行记录。LoopX 已读取到 {completed}/{total} 的投影进度{outputs};请在“详情与操作”检查 Session 状态。`,"drawer.runRecordProjectedOutputs":`和 {count} 项产出`,"drawer.runRoleAssistant":`已完成`,"drawer.runRoleSystem":`需检查`,"drawer.runRoleUser":`收到任务`,"drawer.runView":`Session 视图`,"drawer.scheduleAdd":`添加定时检查`,"drawer.scheduleDefaultNotification":`仅在需要你时通知`,"drawer.scheduleDefaultStop":`Goal 完成或 owner 停止`,"drawer.scheduleDefaultTarget":`由 LoopX 调度器按 Goal 配置唤醒。`,"drawer.scheduleEdit":`改为每 2 小时`,"drawer.scheduleLast":`上次执行`,"drawer.scheduleLocalTimezone":`本地时区`,"drawer.scheduleNext":`下次执行`,"drawer.scheduleNeverRun":`尚未执行`,"drawer.scheduleNotification":`通知`,"drawer.schedulePause":`暂停`,"drawer.schedulePending":`等待调度`,"drawer.scheduleResume":`恢复`,"drawer.scheduleRunNow":`立即运行`,"drawer.scheduleStop":`停止{kind}`,"drawer.scheduleStopCondition":`停止条件`,"drawer.scheduleTimezone":`时区`,"drawer.sessionRecoverable":`可恢复`,"drawer.sessionStatus":`会话状态`,"drawer.setupHeartbeat":`设置 Heartbeat`,"drawer.taskActions":`Todo 待确认操作`,"drawer.taskAdvancement":`推进任务`,"drawer.taskBlock":`标记阻塞`,"drawer.taskComplete":`标记完成`,"drawer.taskCompletedNote":`该任务保留为只读记录。`,"drawer.taskCompletedTitle":`任务已完成`,"drawer.taskDefer":`暂缓`,"drawer.taskDeferCondition":`Todo 暂缓恢复条件`,"drawer.taskDeferInvalid":`条件格式不受支持;请使用下列可判定条件。`,"drawer.taskDeferPlaceholder":`例如 resume_at:2026-09-14T09:00:00+08:00`,"drawer.taskDeferReview":`检查暂缓`,"drawer.taskDeferSupported":`支持 todo_done、pr_merged、capacity_available 与带时区的 resume_at 条件。`,"drawer.taskDeferUntil":`暂缓至`,"drawer.taskDetails":`Todo 详情`,"drawer.taskInfo":`任务信息`,"drawer.taskManage":`管理任务`,"drawer.taskNextCompleted":`可创建后续任务`,"drawer.taskNextOpen":`推进或更新状态`,"drawer.taskOrdinary":`普通任务`,"drawer.taskStatusBlocked":`受阻`,"drawer.taskStatusDeferred":`已延期`,"drawer.resumeWhen":`恢复条件`,"drawer.resumeState":`恢复状态`,"drawer.resumePending":`等待条件满足`,"drawer.resumeReady":`可恢复`,"drawer.resumeReceipt":`恢复回执`,"drawer.taskNextDeferred":`等待恢复条件满足后重新评估`,"drawer.taskNextResumeReady":`恢复条件已满足,等待生命周期重新规划`,"drawer.taskStatusCompleted":`已完成`,"drawer.taskStatusOpen":`待执行`,"drawer.taskSuccessor":`创建后续 Todo`,"drawer.taskSuccessorNote":`Owner 标记为阻塞,等待补充上下文。`,"drawer.taskSuccessorSummary":`创建后续 Todo:{task}`,"drawer.taskSuccessorText":`{task} 的后续工作`,"drawer.taskType":`任务类型`,"drawer.topic":`Topic`,"drawer.trigger":`触发方式`,"drawer.titleAttention":`需要你`,"drawer.titleOutput":`产出详情`,"drawer.titleProposalApplied":`执行结果`,"drawer.titleProposalConfirm":`确认执行`,"drawer.titleSchedule":`定时检查`,"drawer.unconfigured":`未配置`,"drawer.workspaceCandidates":`可选择的工作区`,"files.emptySummary":`公开安全产出`,"files.empty":`还没有文件、产出或已验证的阶段周报。`,"files.loadingReports":`正在加载已验证的阶段周报…`,"files.reportDelta":`+{added} 新增 · {changed} 变化`,"files.reportAdded":`新增`,"files.reportChanged":`变化`,"files.reportGeneration":`生成批次`,"files.reportLoadFailed":`无法加载已验证周报`,"files.reportPublication":`发布批次`,"files.title":`Files & Outputs`,"files.verifiedReport":`已验证阶段周报`,"header.agentUnavailable":`不可用`,"header.chatRuntime":`Chat`,"header.workAgentCount":`{count} 个工作 Agent`,"header.chat":`Chat`,"header.files":`Files`,"header.goalCapabilities":`能力配置`,"header.goalCapabilitiesDescription":`管理 Goal override 与继承的本机默认值。`,"header.goalDetails":`Goal 详情`,"header.goalDetailsDescription":`查看状态、用量、仓库、通知与 Session。`,"header.goalSettings":`Goal 设置`,"header.goalSettingsDescription":`打开 Goal 详情或能力配置`,"header.goalNavigation":`Goal 导航`,"header.goalView":`Goal 视图`,"header.live":`实时`,"header.manager":`LoopX 管家`,"header.managerDescription":`跨 Goal 的个人工作入口`,"header.managerOverview":`总览`,"header.managerView":`管家视图`,"header.openGoalNavigation":`打开 Goal 导航`,"header.readOnlySourceDescription":`{source} 通过 SSH 隧道只读展示`,"header.refresh":`刷新状态`,"header.refreshDone":`刚刚更新`,"header.refreshFailed":`刷新失败`,"header.refreshing":`刷新中`,"header.selectAgent":`选择 Agent`,"header.selectChatRuntime":`选择聊天 Runtime`,"header.tasks":`Tasks`,"header.themeBrutal":`切换到野兽主题`,"header.themePaper":`切换到默认主题`,"home.blockingSummary":`其中 {count} 项正在阻塞 Agent。`,"home.completedGoals":`已完成的 Goal`,"home.empty":`当前没有`,"startup.goalLoading":`正在加载状态…`,"startup.goalError":`状态加载失败`,"startup.progress":`已加载 {loaded} / {total} 个活跃 Goal`,"startup.partial":`Goal 状态正在逐个更新,当前统计尚不完整。`,"startup.independent":`此 Goal 的加载不会阻塞其他 Goal,你可以先查看已加载的内容。`,"startup.error.timeout":`读取超时,可在本地服务就绪后重试。`,"startup.error.network":`连接中断,请重试以重新连接。`,"startup.error.service":`本地服务暂时不可用,请重试继续加载。`,"startup.error.revision":`加载期间 Goal 目录发生变化,请刷新以同步。`,"startup.error.scope":`该 Goal 已不在当前来源中,请刷新目录。`,"startup.error.invalid":`无法解析状态响应,请刷新或检查 LoopX 更新。`,"startup.retry":`重试`,"startup.retryFailed":`重试失败的 Goal`,"startup.failedCount":`{count} 个 Goal 加载失败,已加载的 Goal 可继续使用。`,"home.greeting":`你好,我是 LoopX 管家`,"home.history":`历史`,"home.lane.needsYou":`需要你`,"home.lane.needsYouDescription":`等待你的决定、授权或补充信息`,"home.lane.observing":`观察中`,"home.lane.observingDescription":`持续监控,出现变化时再提醒你`,"home.lane.running":`执行中`,"home.lane.runningDescription":`Agent 正在推进并持续回传进展`,"home.lane.scheduled":`已安排`,"home.lane.scheduledDescription":`已经安排,等待时间或前置条件`,"home.noActivity":`尚无活动`,"home.noFirstActivity":`等待首次活动`,"home.noCompletedGoals":`还没有已完成的 Goal`,"home.preservedState":`保留状态,可随时恢复`,"home.stopped":`已停止`,"home.systemHealth":`系统健康:{summary}`,"home.taskCount":`{count} 个 Task`,"home.todayAt":`今天 {time}`,"home.waitingCount":`你有 {count} 项需要处理。`,"home.workspace":`Goal 工作区`,"lark.allMessages":`此 Topic 中的所有消息`,"lark.allTopicMessages":`所有 Topic 消息`,"lark.agentIngress":`Agent 入站方式`,"lark.agentAppPermissions":`每个选中的 Agent 都需要一个已具备群聊提及和回复能力的 Lark App。`,"lark.agentApps":`每个 Agent 的 Lark App`,"lark.agentAppsDescription":`默认使用上方 App;需要独立机器人身份时,可为 Agent 选择另一个兼容 App。`,"lark.agentAppSelection":`{agent} 的 Lark App`,"lark.appCreated":`App 已创建`,"lark.appCreateFailed":`创建失败`,"lark.appLoading":`正在加载可用的 Lark Apps…`,"lark.appPermissions":`该 App 能发送建联消息,但缺少接收群聊 @ 消息或自动回复所需的机器人权限。请开启 im:message.group_at_msg:readonly、im:message.send_as_bot 和事件 im.message.receive_v1,发布新版后刷新。`,"lark.appProfile":`Lark App`,"lark.apps":`Lark Apps`,"lark.autoReplyUnavailable":`自动回复暂不可用`,"lark.autoReplyReady":`自动回复可用`,"lark.bindGoal":`绑定到 Goal`,"lark.cancel":`取消`,"lark.cardinality":`一个 Lark App · 多个 Goal · 每个 Agent 一条隔离路由`,"lark.capture":`接收范围`,"lark.captureAddressed":`仅接收提及 App 或回复 App 的消息`,"lark.captureAll":`接收此 Goal Topic 中的所有消息`,"lark.captureScope":`接收范围`,"lark.captureScopeDescription":`决定哪些 Topic 消息会进入 LoopX;不会扩大 Agent 权限。`,"lark.closeConnection":`关闭连接弹窗`,"lark.closeCreate":`关闭创建弹窗`,"lark.closeSettings":`关闭 Lark 设置`,"lark.connect":`连接`,"lark.connectAllAgents":`连接全部已注册 Agent`,"lark.connectAllAgentsAction":`一键连接 {count} 个 Agent`,"lark.connectAllAgentsDescription":`一次引导创建 {count} 个隔离的 Agent Topic;请在对应 Topic 内发送请求,每个 Agent 保留独立路由和收件箱。`,"lark.connectApp":`连接 Lark App`,"lark.connection":`连接`,"lark.connections":`连接`,"lark.configuration":`Lark 配置`,"lark.continueFeishu":`在飞书中继续`,"lark.createAutomatically":`自动创建 Goal Topic`,"lark.createAutomaticallyDescription":`将为每个选中的 Agent 创建带 Agent 标识的专属 Topic。`,"lark.defaultAgentAppDescription":`用于查找目标群聊,并作为所有选中 Agent 的默认 App;下方的逐 Agent 选择可覆盖它。`,"lark.description":`管理可复用的 Lark App,并用独立 Topic 将群聊连接到 Goal。`,"lark.editConnection":`编辑 Lark 连接`,"lark.goalConnections":`{count} 个 Goal 连接`,"lark.goalTopicConnections":`Lark Goal Topic 连接`,"lark.groupChat":`群聊`,"lark.groupEmpty":`该机器人尚未加入可连接的群。请先在飞书群设置中添加这个机器人,再回来刷新或搜索。`,"lark.groupLoading":`正在读取该机器人已加入的群…`,"lark.groupSearch":`搜索该机器人已加入的群`,"lark.historyPermission":`历史补读权限(独立能力)`,"lark.health.eventProcessed":`已处理 {events} 条事件,成功回复 {replies} 条。`,"lark.health.eventUnverified":`事件订阅待验证`,"lark.health.eventUnverifiedDetail":`Provider listener 已就绪,但尚未收到消息事件。请启用 im.message.receive_v1、开通群聊 @ 消息权限并发布新版,然后在这个 Agent Topic 内发送新的 @ 消息;存在多条 Agent 路由时,群顶层消息会 fail closed。`,"lark.health.ignoredSelf":`已忽略机器人自身发送的消息,避免重复回复。`,"lark.health.invalidRouting":`路由配置无效`,"lark.health.invalidRoutingDetail":`连接已安全停用,请重新选择处理方式并保存。`,"lark.health.lastStatus":`最近事件状态:{status}`,"lark.health.listening":`监听中`,"lark.health.messageContextPermission":`消息权限不足`,"lark.health.messageContextPermissionDetail":`已收到消息事件,但无法读取群消息上下文。请发布并授权该 App 的群消息读取权限。`,"lark.health.notAddressed":`最近消息未直接 @ 机器人`,"lark.health.notAddressedDetail":`监听正常;当前连接只响应直接 @ 机器人或对机器人的回复。`,"lark.health.notStarted":`监听未启动`,"lark.health.notStartedDetail":`请刷新连接或重新启动 LoopX 后再试。`,"lark.health.processingFailed":`消息处理失败`,"lark.health.processingFailedDetail":`已收到消息事件,但 Agent 处理失败。请查看本地诊断后重试。`,"lark.health.queued":`已进入 Agent 收件箱`,"lark.health.queuedDetail":`消息由 {agent} 异步处理,不会启动通用 Chat Session。`,"lark.health.sourceDisconnected":`实时消息连接断开`,"lark.health.sourceDisconnectedDetail":`消息监听进程意外退出。请核对应用档案的平台:飞书应用选飞书,国际版 Lark 应用选 Lark,再检查连接及订阅错误。LoopX 正在重试;历史消息能读取,不代表能实时收消息。`,"lark.health.retrying":`监听重试中`,"lark.health.retryingDetail":`事件监听暂时中断,LoopX 正在自动重试。`,"lark.health.routeAmbiguous":`消息匹配多个 Goal`,"lark.health.routeAmbiguousDetail":`同一 Bot 和群聊存在多个完整群捕获连接。请让每个 Agent 使用独立 Bot,或只保留一个完整群连接。`,"lark.health.routeMismatch":`消息未匹配当前 Goal Topic`,"lark.health.routeMismatchDetail":`事件来自其他群聊或 Topic。请重新选择群聊并连接该 Goal,然后发送一条新的 @ 消息。`,"lark.health.routeUnavailable":`消息无法路由到 Goal`,"lark.health.routeUnavailableDetail":`当前连接信息不完整。请重新连接该 Goal 后再发送一条新的 @ 消息。`,"lark.health.starting":`正在启动`,"lark.health.startingDetail":`LoopX 正在启动该 App 的消息事件监听。`,"lark.health.unavailable":`自动回复不可用`,"lark.health.waiting":`等待处理`,"lark.incomingMessages":`接收消息`,"lark.ingressAsync":`异步收件箱`,"lark.ingressAsyncDescription":`写入 Agent 私有收件箱,等待后续显式处理。`,"lark.editPreservesIdentity":`保存会保留此 App、群和 Topic;旧连接默认升级为 Agent 异步收件箱。`,"lark.conversationKind":`连接用途`,"lark.managerConversation":`管家 · 同步对话`,"lark.workerConversation":`工作 Agent · 后台任务`,"lark.managerConversationDescription":`内置管家即时回应对话,长任务交给后台 Agent。群聊与私聊分别保存上下文。`,"lark.ingressLegacy":`待升级`,"lark.ingressLegacyDescription":`保存连接即可升级为 Agent 异步收件箱,已有消息保留在原 Topic 中。`,"lark.ingressQueue":`排队`,"lark.ingressQueueDescription":`进入同一 Agent Session 的有界 FIFO 队列,当前 Turn 完成后处理。`,"lark.ingressSteering":`实时引导`,"lark.ingressSteeringDescription":`投到当前活跃 Turn;没有精确活跃 Turn 时安全拒绝。`,"lark.loading":`加载 Lark 配置…`,"lark.management":`Lark 管理`,"lark.openEventSettings":`查看飞书事件配置`,"lark.mentions":`提及机器人`,"lark.mentionsOnly":`仅提及消息`,"lark.needsMessagePermissions":`需要消息权限`,"lark.needsSetup":`需要设置`,"lark.newApp":`新建 Lark App`,"lark.noAgentConfigured":`未配置 Agent`,"lark.noConnections":`暂无匹配的连接。`,"lark.noProfiles":`还没有可用的 lark-cli App profile。`,"lark.profileName":`Profile 名称`,"lark.profileValidation":`Profile 只能包含字母、数字、点、下划线和连字符。`,"lark.processing":`处理方式`,"lark.region":`区域`,"lark.registerAnother":`+ 注册另一个 Lark App — 通过飞书创建`,"lark.reopenFeishu":`重新打开飞书`,"lark.settingsConfigure":`配置 {goal}`,"lark.settingsDisconnect":`解绑 {goal}`,"lark.replyMode":`回复方式`,"lark.replyModeDescription":`当前只支持在来源 Topic 内回复,避免跨群或跨 Goal 投递。`,"lark.reusableApps":`{count} 个可复用 App`,"lark.reusableWorkspaceApp":`可复用工作区 App`,"lark.routesUnverified":`{count} 条 Lark 路由尚未验证`,"lark.saveConnection":`保存连接`,"lark.searchConnections":`搜索 Lark 连接`,"lark.searchPlaceholder":`搜索 App、群、Goal 或 Topic`,"lark.setupCopy":`LoopX 将通过 lark-cli 打开飞书官方创建页面。应用凭证保存在系统 Keychain,LoopX 只保留 profile 引用。`,"lark.someoneMentions":`有人提及 Agent`,"lark.targetAgent":`目标 Agent`,"lark.targetAgentDescription":`选择该 Goal 内已注册的 Agent。此连接只投递给一个 Agent,不广播、不授予新权限。实时引导与排队需要该 Agent 的精确活跃 Session。`,"lark.agentUnavailable":`{agent} · 已不可用`,"lark.selectRegisteredAgent":`请先选择可用的已注册 Agent;不会自动替换原先的接收者。`,"lark.topicPreview":`Topic 预览`,"lark.topicReply":`Topic 回复`,"lark.trigger":`触发方式`,"lark.waitingFeishu":`等待飞书完成创建`,"lark.waitingFeishuDescription":`请在新窗口中完成飞书授权,完成后会自动回到这里。`,"lark.waitingLink":`正在生成飞书官方创建链接…`,"lark.error.appCreate":`Lark App 创建失败`,"lark.error.appRequired":`请选择一个 Lark App profile。`,"lark.error.bind":`绑定失败`,"lark.error.bindPreview":`绑定预览失败`,"lark.error.configuration":`Lark 配置加载失败`,"lark.error.groupLookup":`无法读取该机器人已加入的群。请检查机器人状态后重试。`,"lark.error.groupLoad":`群聊加载失败`,"lark.error.invalidApp":`Lark App profile 不可用或尚未完成授权。`,"lark.error.messagePermissions":`该 App 缺少自动回复所需的机器人权限。请开启 im:message.group_at_msg:readonly 和 im:message:send_as_bot,发布新版后回来刷新重试。`,"lark.error.provider":`飞书 API 调用失败,且没有生成已验证回执。请稍后重试。`,"lark.error.setupPoll":`创建状态查询失败`,"lark.error.setupStart":`无法启动 Lark App 创建流程`,"lark.error.cliExecutable":`已找到配置的 lark-cli,但当前无法执行。请检查安装或启动参数。`,"lark.error.cliMissing":`未发现 lark-cli。请先安装 lark-cli,然后重新启动 LoopX。`,"lark.error.cliStart":`lark-cli 启动失败。请检查安装状态,然后重新启动 LoopX。`,"lark.error.disconnect":`解绑失败`,"notifications.autoNotify":`需要你确认时自动推送到群里`,"notifications.bind":`绑定到通知群`,"notifications.bindConfirm":`将把「{goal}」绑定到通知群「{target}」,绑定时会验证机器人在群内并发送一条确认消息。`,"notifications.bindFailed":`绑定失败`,"notifications.bound":`已绑定`,"notifications.confirmBind":`确认绑定`,"notifications.description":`把 Goal 里需要你确认的变更推送到飞书群。绑定和开关在这里完成,推送逻辑沿用现有通道。`,"notifications.disabled":`已停用`,"notifications.group":`通知群:{target}`,"notifications.loadFailed":`通知群列表加载失败`,"notifications.noTargets":`还没有可用的通知群。通知群涉及机器人私有身份,请先在终端配置一次:`,"notifications.notBound":`未绑定`,"notifications.recent":`最近 {time}`,"notifications.sentCount":`已发送 {count} 条`,"notifications.settings":`Goal 通知绑定`,"notifications.setupFailed":`设置失败`,"notifications.title":`飞书群通知`,"proposal.field.agentId":`Agent`,"proposal.field.cadence":`频率`,"proposal.field.completionCriteria":`完成标准`,"proposal.field.executionBoundary":`执行边界`,"proposal.field.goalId":`Goal ID`,"proposal.field.heartbeat":`Heartbeat`,"proposal.field.initialTodos":`首个任务`,"proposal.field.objective":`目标`,"proposal.field.operation":`操作`,"proposal.field.operationState":`操作状态`,"proposal.field.confirmationBoundary":`确认边界`,"proposal.field.expiresAt":`过期时间`,"proposal.field.permission":`权限`,"proposal.field.reason":`原因`,"proposal.field.stopCondition":`停止条件`,"proposal.field.target":`检查内容`,"proposal.field.timezone":`时区`,"proposal.field.title":`标题`,"proposal.field.workspace":`执行工作区`,"actionReview.targetChanged":`预览目标与请求的 Goal 或操作不一致,请重新生成预览。`,"actionReview.ready_stop":`暂停可恢复。此预览已通过检查,可直接执行;完成仍需要读回验证。`,"actionReview.resume_review":`恢复自动调度前需要确认。实际执行仍受额度、Gate 和 Todo 约束。`,"actionReview.delete_review":`请确认从注册表移除这个已停止 Goal。项目文件与历史记录会保留。`,"actionReview.action_review":`执行前请检查此提案的目标与影响。`,"actionReview.protected_action":`此操作需要明确审阅。确认不能替代所需授权。`,"actionReview.unknown_permission":`无法识别权限分类。请重新检查提案后再继续。`,"actionReview.unknown_action":`无法识别此生命周期操作。请重新检查提案后再继续。`,"actionReview.incomplete_proposal":`预览缺少验证信息或可执行转换。请重新生成预览。`,"actionReview.authority_gate":`Gate 阻止执行。请满足其要求后重新检查提案。`,"actionReview.stale_proposal":`来源状态已变化。请重新生成预览,原决定不再适用。`,"actionReview.apply_pending":`正在执行,请等待读回结果后再重试。`,"actionReview.readback_verified":`操作已完成,结果状态已通过读回验证。`,"actionReview.readback_unverified":`操作返回但未通过读回验证。尚不能确认完成,请重新检查状态。`,"actionReview.apply_failed":`执行未完成。请检查失败原因并重新生成预览后再试。`,"actionReview.inactive_proposal":`此提案当前不可执行。请重新检查后再继续。`,"proposal.gate.default":`需要宿主确认`,"proposal.impact.default":`确认后会调用规范 LoopX 服务写入状态。`,"proposal.impact.goalCreate":`确认后会创建 Goal 和首个 Todo,并让选定 Agent 开始首轮推进。`,"proposal.impact.lifecycleDelete":`确认后会从 source registry 和 global registry 移除这个已停止 Goal;项目文件、历史状态文件和备份不会被删除。`,"proposal.impact.lifecycleResume":`确认后会恢复 Goal 的自动调度资格并移回 Active Goals;实际执行仍受 quota、Gate 和 Todo 约束。`,"proposal.impact.lifecycleStop":`确认后会停止自动推进,并将 Goal 移入折叠的「已停止」列表;历史、Todo 和证据都会保留,可随时恢复。`,"proposal.impact.protected":`该操作需要通过受保护的 LoopX 写入服务完成。`,"proposal.impact.operation":`这里仅展示同一份不可变条款。请在已绑定的飞书群确认或拒绝;确认只会消费一个规范 claim。`,"proposal.primary.apply":`确认并应用`,"proposal.primary.goalCreate":`创建 Goal 并开始首轮`,"proposal.primary.lifecycleDelete":`删除 Goal`,"proposal.primary.lifecycleResume":`恢复 Goal`,"proposal.primary.lifecycleStop":`停止 Goal`,"proposal.primary.todoStart":`创建任务并开始执行`,"proposal.primary.operationGroup":`前往飞书群确认`,"proposal.summary.goalCreate":`创建 Goal:{title}`,"proposal.summary.heartbeat":`为当前 Goal 设置 Heartbeat`,"proposal.summary.lifecycleDelete":`删除 Goal:{title}`,"proposal.summary.lifecycleResume":`恢复 Goal:{title}`,"proposal.summary.lifecycleStop":`停止 Goal:{title}`,"proposal.summary.monitor":`为当前 Goal 创建定时检查:{target}`,"proposal.workspace.current":`当前本地工作区(未绑定 Repository)`,"proposal.workspace.named":`{workspace}(仅提供执行环境,不会自动关联仓库)`,"proposal.workspaceGate.agentImpact":`先完成 Agent 身份绑定,再重新检查原操作;当前没有写入 Goal。`,"proposal.workspaceGate.agentTitle":`先绑定 Agent`,"proposal.workspaceGate.defaultSummary":`请选择 Goal 所属工作区。`,"proposal.workspaceGate.selectionImpact":`选择工作区后会重新展示待确认操作,选择本身不会写入状态。`,"proposal.workspaceGate.selectionTitle":`选择 Goal 工作区`,"projection.agentAdvancingGoal":`Agent 正在推进当前 Goal`,"projection.agentIdle":`暂无需要你处理`,"projection.agentNeedsDecision":`Agent 等待你的决定`,"projection.agentPreparingNextStep":`Agent 正在整理下一步`,"projection.agentStopped":`已由你停止;历史、Todo 和证据仍保留`,"projection.agentWaitingExternal":`正在等待外部条件`,"projection.confirmAgentDecision":`请确认 Agent 下一步需要的权限或决策`,"projection.events24h":`24 小时内 {count} 个事件`,"projection.firstReadOnlyAdapterCheck":`执行首次只读适配检查并保存进度`,"projection.goalVerified":`Goal 状态、Todo 与注册信息已验证`,"projection.latestRun":`最近运行`,"projection.latestValidation":`最近验证`,"projection.nextUpdatePending":`等待 LoopX 更新下一步`,"projection.publicSafeProjection":`公开安全状态投影`,"projection.refreshState":`刷新 LoopX 状态,确认当前进度仍然有效`,"projection.runEvidenceAvailable":`存在可查看的运行证据`,"projection.runRecorded":`最近一次 LoopX 运行已经记录`,"projection.statusRefreshNeeded":`LoopX 状态需要刷新`,"projection.todoStatusUpdated":`Todo 状态已经更新,正在确认下一步`,"projection.validationRecorded":`最近验证已经记录`,"runs.completed":`已完成`,"runs.failed":`需检查`,"runs.interrupted":`已中断`,"runs.queued":`已安排`,"runs.ready":`可继续`,"runs.resumeFailed":`恢复失败`,"runs.running":`执行中`,"runs.unknown":`状态未知`,"runs.waiting":`等待条件`,"schedule.active":`执行中`,"schedule.heartbeat":`Goal Heartbeat`,"schedule.monitor":`定时与持续任务`,"schedule.paused":`已暂停`,"schedule.summary":`按 LoopX 调度约束持续检查`,"schedule.defaultTarget":`检查当前 Goal 的阻塞、进度与新产出`,"schedule.unsupportedCalendar":`当前定时检查不支持精确到星期或时刻的日历计划。请改用固定间隔,例如“每 30 分钟”“每 2 小时”或“每天”;草稿已保留,没有生成待确认操作。`,"source.add":`添加来源`,"source.addConfigured":`添加只读来源`,"source.addMethod":`来源添加方式`,"source.addSsh":`添加 SSH 隧道来源`,"source.closeForm":`关闭来源表单`,"source.configured":`已配置 SSH`,"source.configuredCount":`本机 SSH Host · {count} 个`,"source.configuredGroup":`已配置 SSH Host · {count}(点击快速添加)`,"source.connected":`已连接`,"source.connecting":`连接中`,"source.controlPlane":`控制面来源`,"source.copy":`复制`,"source.copyCommand":`复制 SSH 隧道命令`,"source.copyError":`无法复制命令,请手动复制下方命令。`,"source.copied":`已复制`,"source.description":`已读取全部显式 Host(含 Include);通配规则不会作为具体来源。先运行命令,LoopX 不读取密钥或配置细节。`,"source.host":`本机 SSH Host`,"source.hostEmpty":`~/.ssh/config 中没有可直接选择的显式 Host。`,"source.hostLoadError":`无法读取本机 SSH Host。`,"source.hostPlaceholder":`输入或搜索 Host`,"source.invalid":`SSH 来源参数无效。`,"source.loadingHosts":`正在读取…`,"source.localInteractive":`本机交互`,"source.localPort":`本地端口`,"source.manual":`手动 URL`,"source.manualDescription":`远端来源始终按只读投影处理,不继承本机写权限。`,"source.name":`名称`,"source.namePlaceholder":`远程开发机`,"source.notAvailable":`不可用`,"source.readOnly":`SSH 隧道 · 只读`,"source.readOnlyNoticeDescription":`你可以查看 Goal、Task、证据与运行状态;写入、纠偏和 Agent 会话仍留在来源主机。`,"source.readOnlyNoticeTitle":`远端只读投影`,"source.readOnlyWriteError":`远端 SSH 隧道来源是只读投影,不能执行控制面写入。`,"source.refreshHosts":`重新读取 SSH Host`,"source.remove":`移除来源 {source}`,"source.removeCurrent":`移除当前来源`,"source.select":`选择控制面来源`,"source.selectHost":`请选择已配置的 SSH Host。`,"source.statusUrl":`本地转发 URL`,"source.tunnelCommandPending":`选择 Host 后生成隧道命令`,"machine.absent":`尚未配置`,"machine.action.create":`创建机器策略`,"machine.action.delete":`移除机器策略`,"machine.action.unchanged":`无需写入`,"machine.action.update":`更新机器策略`,"machine.applied":`机器策略已应用,并通过回读校验。`,"machine.applyError":`无法应用机器策略。`,"machine.applyPreview":`应用已审阅预览`,"machine.changedNamespaces":`变更的 Namespace`,"machine.capabilityCatalog":`机器能力目录`,"machine.capabilityEmpty":`当前没有注册可在机器作用域配置的能力。`,"machine.configured":`已配置`,"machine.confirmRollback":`确认回滚`,"machine.currentRevision":`当前 Revision`,"machine.currentValue":`当前机器值`,"machine.description":`与 Goal 设置共用能力目录。在这里管理受支持的机器默认值;仅支持 Goal 配置的能力会明确标注。`,"capabilities.rawJson":`高级:原始 JSON`,"machine.goalOnly":`此能力目前仅支持 Goal 级配置。请打开具体 Goal 的能力设置进行配置;这里不会设置机器级默认值。`,"machine.desiredRevision":`目标 Revision`,"machine.editorUnavailable":`当前版本未安装此 Namespace 的编辑器`,"machine.editorUnavailableDescription":`它仍会显示在 Registry 中;安装或升级对应的 Dashboard 编辑器后才能修改。`,"machine.editorMode":`编辑模式`,"machine.liveDefault":`实时默认值;Goal 显式覆盖优先`,"machine.liveDefaultDescription":`没有显式覆盖的 Goal 会在该能力下一次决策时读取当前机器策略。修改或移除策略会立即影响这些已有 Goal;显式 Goal 覆盖保持固定。`,"machine.genericNamespaceDescription":`使用 JSON 编辑这个已注册 Namespace。LoopX 会先按 capability 自己拥有的 schema 校验,再允许预览写入。`,"machine.jsonConfiguration":`Namespace 配置(JSON)`,"machine.jsonConfigurationHelp":`只更新当前 Namespace;其他机器配置会保留,Apply 仍锁定到已审阅的 Preview Revision。`,"machine.jsonEditor":`JSON`,"machine.editJson":`编辑 JSON`,"capabilities.jsonConfiguration":`Goal 配置(JSON)`,"capabilities.jsonHelp":`仅编辑当前 Goal 的已注册字段。修改后需重新预览才能应用。`,"capabilities.jsonInvalid":`请输入合法的 JSON 对象,且仅包含已注册的可编辑字段。`,"machine.backToForm":`返回表单`,"machine.jsonInvalid":`请先填写一个合法的 JSON object,再预览变更。`,"machine.loadError":`无法读取机器配置。`,"machine.machinePolicy":`机器策略`,"machine.namespaceCount":`已注册 Namespace`,"machine.namespaces":`配置 Namespace`,"machine.periodicReport":`周期报告`,"machine.periodicReportDescription":`为所有未显式覆盖的 Goal 提供默认报告策略;Goal 调度与发送消费解析后的有效配置。`,"machine.periodicReportActivation":`开启后将在已验证的阶段节点自动投递`,"machine.periodicReportActivationDescription":`这不是每周定时器。当 LoopX 验证 Goal 已完成一个阶段时,Agent 会生成并冻结报告,随后通过配置的 Goal Channel 自动发送。启用此订阅即授予持续投递权;发送失败或路由漂移会 fail closed 并进入修复。`,"machine.changeQualityActivation":`质量验证是质量门禁,不是新增授权`,"machine.changeQualityActivationDescription":`继承该策略的 Goal 会验证最终精确 diff。safe_fix 只允许在既有写入权限内执行至多一次有界修复;此设置不会授予文件、权限或合并权。`,"machine.replanCadenceActivation":`复核周期只改变时机,不改变执行权限`,"machine.replanCadenceActivationDescription":`没有显式覆盖的 Goal 会在下一次复核决策前读取此阈值;它不会创建 Turn、消耗配额或授予权限。`,"machine.preview":`审阅机器配置变更`,"machine.previewChanges":`预览变更`,"machine.previewError":`无法生成机器策略预览。`,"machine.previewLocked":`应用操作锁定到当前 Revision;若机器状态变化,LoopX 会要求重新预览。`,"machine.previewRollback":`预览回滚`,"machine.previewRemoval":`预览移除`,"machine.profilePreset":`Profile preset`,"machine.profilePresetHelp":`由 capability 管理的 preset,例如 weekly-progress。`,"machine.registry":`Typed Registry`,"machine.requiredFields":`开启后必须填写 profile preset、Goal Channel route 与有效时区。`,"machine.revision":`机器 Revision`,"machine.revisionLockedReady":`所有变更必须先预览;只有对应的机器 Revision 仍然有效时才会应用。`,"machine.rollbackAvailable":`可回滚上一次应用`,"machine.rollbackDescription":`先预览已保存的前一 Revision,再决定是否恢复。`,"machine.rollbackError":`无法完成回滚。`,"machine.rollbackPreviewDescription":`前一 Revision 已准备恢复,请确认执行本次回滚。`,"machine.rolledBack":`已恢复前一版机器策略,并通过校验。`,"machine.removed":`机器策略已移除,并通过回读校验。`,"machine.routeRef":`Goal Channel route`,"machine.routeRefHelp":`只填写公开 route alias;凭据与 provider identifier 不会进入此表单。`,"machine.timezone":`时区`,"machine.timezoneHelp":`填写 IANA 时区,例如 Asia/Shanghai。`,"machine.title":`机器配置`,"machine.unchanged":`机器策略已与预览一致,本次没有写入。`,"machine.visualEditor":`引导式`,"capabilities.atomicOverride":`Goal override 按完整配置生效`,"capabilities.atomicOverrideDescription":`Goal 的完整配置优先于机器默认值;LoopX 不会在两个作用域之间逐字段拼接。`,"capabilities.applyFailed":`Goal 能力变更未写入。`,"capabilities.applyPreview":`应用此预览`,"capabilities.catalog":`Goal 能力目录`,"capabilities.chooseGoal":`请先选择一个 Goal,再查看它的能力配置。`,"capabilities.defaultValue":`声明的默认值`,"capabilities.description":`查看当前 Goal 可用的能力,以及每项配置的准确作用域。`,"capabilities.editorPrepared":`已注册 typed editor contract`,"capabilities.effectiveSource":`当前生效来源`,"capabilities.empty":`当前 Goal 没有可用的能力描述。`,"capabilities.fields":`已注册字段`,"capabilities.goalPolicy":`Goal 能力策略`,"capabilities.goalScope":`Goal`,"capabilities.goalValue":`当前 Goal 值`,"capabilities.loadFailed":`无法加载 Goal 能力`,"capabilities.loading":`正在加载 Goal 能力…`,"capabilities.machineOnly":`此能力只能在机器作用域配置。`,"capabilities.machineValue":`实时机器默认值`,"capabilities.machineScope":`机器`,"capabilities.previewOnly":`当前读取结果来自真实配置;在 revision-locked preview/apply 路径接通前,Dashboard 不会提供 Goal 写入控件。`,"capabilities.preview":`锁定 revision 的变更预览`,"capabilities.previewChanges":`预览变更`,"capabilities.restoreInheritance":`恢复继承机器默认值`,"capabilities.previewFailed":`无法预览 Goal 能力变更。`,"capabilities.previewLocked":`应用时会重新校验这一个 plan revision;过期变更将被拒绝。`,"capabilities.partialWrite":`Goal 值已保存;共享投影仍需修复`,"capabilities.partialWriteDescription":`源 Goal 配置已经写入并回读,但共享 runtime 投影尚未同步;请勿重复提交本次变更。`,"capabilities.refreshSource":`刷新源配置`,"capabilities.readOnly":`只读能力`,"capabilities.revisionLockedReady":`所有变更必须先预览;只有对应的精确 revision 仍然有效时才会写入。`,"capabilities.retry":`重试`,"capabilities.source.capability_default":`能力默认值`,"capabilities.source.goal_override":`Goal override`,"capabilities.source.machine_default":`实时机器默认值`,"capabilities.source.not_configured":`未配置`,"capabilities.title":`Goal 能力`,"settings.close":`关闭设置`,"settings.appearance":`外观`,"settings.appearanceDescription":`管理当前浏览器里的工作区显示偏好。`,"settings.appearanceTabDescription":`主题和显示偏好`,"settings.capabilitiesTabDescription":`当前 Goal 的能力覆盖配置`,"settings.back":`返回工作区`,"settings.categories":`设置分类`,"settings.description":`管理工作区偏好与集成。`,"settings.eyebrow":`工作区偏好`,"settings.general":`通用`,"settings.goalConnections":`Goal 连接`,"settings.language":`语言`,"settings.languageDescription":`选择 LoopX Desktop 工作区使用的界面语言。`,"settings.languageEnglishDescription":`使用英文显示导航、设置和工作区控件。`,"settings.languageEnglish":`English`,"settings.languageSimplifiedChineseDescription":`使用简体中文显示导航、设置和工作区控件。`,"settings.languageSimplifiedChinese":`简体中文`,"settings.languageStoredLocally":`此偏好仅保存在当前设备。`,"settings.languageTabDescription":`当前设备的界面语言`,"settings.larkTabDescription":`App、群聊和 Goal Topic 连接`,"settings.machineTabDescription":`本机各 Capability 共享的 typed defaults`,"settings.notifications":`通知`,"settings.open":`设置`,"settings.themeDefault":`纸张`,"settings.themeDefaultDescription":`安静、轻量,适合长期查看。`,"settings.themeDescription":`选择工作区的视觉风格。设置会保存在当前浏览器本地。`,"settings.themeHighContrast":`高对比`,"settings.themeHighContrastDescription":`更强边框和更醒目的状态块。`,"settings.themeLoopx":`LoopX 标准`,"settings.themeLoopxDescription":`精确的黑白界面、Geist 字体与安静的细线结构。`,"settings.title":`设置`,"settings.workspaceDisplay":`工作区显示`,"settings.workspaceTheme":`工作区主题`,"session.closeRecord":`退出运行记录`,"session.details":`Session 详情`,"session.record":`执行 Session · 运行记录`,"session.recordDescription":`当前时间线已切换到这次 Session 的消息与 Turn 记录。`,"sidebar.createGoal":`创建 Goal`,"sidebar.delete":`删除`,"sidebar.deleteGoal":`删除 Goal`,"sidebar.manager":`LoopX 管家`,"sidebar.notifications":`设置`,"sidebar.owner":`个人工作区`,"sidebar.product":`个人 Agent 工作区`,"sidebar.resume":`恢复`,"sidebar.resumeGoal":`恢复 Goal`,"sidebar.stop":`停止`,"tasks.historyLoading":`正在加载历史…`,"tasks.historyError":`历史加载失败,已显示的内容仍可查看。`,"tasks.historyExpired":`历史快照已过期,重新加载后可继续查看。`,"tasks.historyRetry":`重新加载`,"tasks.historyEnd":`已显示全部完成记录`,"tasks.historyMore":`加载更多`,"tasks.historyLocalOnly":`请打开这台机器的 Dashboard 查看完整历史。`,"sidebar.sortGoals":`调整 Goal 顺序`,"sidebar.dragGoal":`拖拽调整顺序,或使用列表排序按钮`,"sidebar.moveUp":`上移 {goal}`,"sidebar.moveDown":`下移 {goal}`,"sidebar.goalMoved":`{goal} 已移至第 {position} 位`,"sidebar.orderNotSaved":`顺序已在本次页面生效;浏览器存储不可用,无法保存。`,"sidebar.stopGoal":`停止 Goal`,"sidebar.stopped":`已停止`,"sidebar.stoppedLoading":`正在加载已停止 Goal`,"sidebar.stoppedLoadFailed":`已停止 Goal 加载失败,其他 Goal 仍可使用。`,"sidebar.retryStopped":`重试`,"state.completed":`已完成`,"state.needsRepair":`需修复`,"state.needsYou":`等你`,"state.quiet":`安静运行`,"state.running":`推进中`,"state.stopped":`已停止`,"state.waiting":`等待条件`,"tasks.blocked":`受阻`,"tasks.agentLane":`工作 Agent`,"tasks.agentLaneDescription":`筛选这个 Goal 下的工作泳道`,"tasks.agentLaneFilter":`按工作 Agent 筛选`,"tasks.allAgentLanes":`全部 Agent({count})`,"tasks.chatAgentReplied":`Agent 已回复`,"tasks.chatPending":`已发送给 Agent`,"tasks.chatPendingDescription":`正在处理;只有经过确认的任务操作才会更新 Tasks。`,"tasks.chatRecent":`最近对话`,"tasks.chatUnchangedDescription":`本次对话没有直接修改 Tasks。需要执行时,可先转成 Task 草稿并确认。`,"tasks.chatViewReply":`查看回复`,"tasks.convertToTask":`转为 Task`,"tasks.completed":`已完成`,"runs.discoveryPartial":`部分执行详情暂不可用,正在重连;任务摘要不代表实时执行状态。`,"runs.discoveryOffline":`执行服务暂不可用,正在重连;保留的任务摘要可能已过时。`,"files.openConversation":`前往会话`,"files.exportSummary":`导出摘要`,"tasks.viewDescription":`先处理待确认,再查看工作与完成记录`,"tasks.viewLabel":`任务视图`,"tasks.listView":`列表`,"tasks.boardView":`看板`,"tasks.completedSummary":`已完成 {count} 项,近期完成明细由控制面按需投影。`,"tasks.emptyCompleted":`还没有完成的任务。`,"tasks.emptyConfirm":`没有待确认的任务。`,"tasks.emptyRunning":`没有待执行或进行中的任务。`,"tasks.emptySchedules":`没有定时任务。`,"tasks.emptyGoal":`这个 Goal 还没有任务。用下面的输入框描述下一步,LoopX 会先展示待确认操作。`,"tasks.markComplete":`标记完成:{name}`,"tasks.moreActions":`更多操作:{name}`,"tasks.openExecution":`查看执行过程:{name}`,"tasks.pending":`待处理`,"tasks.pendingAndRunning":`待执行 / 进行中`,"tasks.scheduled":`定时与持续`,"tasks.sessionError":`Session 异常`,"tasks.waiting":`待执行`,"tasks.waitingAge":`已等待 {age}`,"tasks.viewExecution":`查看执行过程`,"tasks.viewResult":`查看结果`,"time.days":`{count} 天`,"time.hours":`{count} 小时`,"timeline.emptyGoal":`这个 Goal 还没有新动态`,"timeline.emptyGoalDescription":`你可以直接询问进度或下发新的纠偏信息。`,"timeline.emptyWorkspace":`今天的工作区很安静`,"timeline.emptyWorkspaceDescription":`向 LoopX 管家描述一个 Goal,或询问今天最值得关注的事情。`,"timeline.gateHistory":`{count} 项历史 Gate`,"timeline.pending":`正在整理…`,"timeline.runCompleted":`{run}:已完成`,"timeline.review":`查看处理方式`,"timeline.reviewAndConfirm":`查看并确认`,"timeline.waitingConfirmation":`待你确认`}};function Gi(e,t){return t?Object.entries(t).reduce((e,[t,n])=>e.replaceAll(`{${t}}`,String(n)),e):e}function Ki(){try{return window.localStorage.getItem(`loopx-pw-locale`)===`en`?`en`:`zh-CN`}catch{return`zh-CN`}}function qi({children:e}){let[t,n]=(0,z.useState)(Ki);function r(e){n(e);try{window.localStorage.setItem(Ui,e)}catch{}}(0,z.useEffect)(()=>{document.documentElement.lang=t},[t]);let i=(0,z.useMemo)(()=>({locale:t,setLocale:r,t:(e,n)=>Gi(Wi[t][e],n)}),[t]);return(0,B.jsx)(Hi.Provider,{value:i,children:e})}function Ji(){let e=(0,z.useContext)(Hi);if(!e)throw Error(`useWorkspaceI18n must be used within WorkspaceI18nProvider`);return e}function Yi(e,t){let n={安静运行:`state.quiet`,等你:`state.needsYou`,等待条件:`state.waiting`,推进中:`state.running`,需修复:`state.needsRepair`,已完成:`state.completed`,已停止:`state.stopped`}[e];return n?Wi[t][n]:e}function Xi(e,t){let n={busy:`runs.running`,completed:`runs.completed`,failed:`runs.failed`,queued:`runs.queued`,ready:`runs.ready`,resume_failed:`runs.resumeFailed`,running:`runs.running`,waiting:`runs.waiting`};return e?n[e]?t(n[e]):e:t(`runs.unknown`)}function Zi(e,t){if(!e)return null;let n=new Date(e).getTime();if(Number.isNaN(n))return null;let r=Date.now()-n;if(r<36e5)return null;let i=Math.floor(r/864e5);return i>=1?t(`time.days`,{count:i}):t(`time.hours`,{count:Math.floor(r/36e5)})}var Qi;function H(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;en?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var $i=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},ea=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Qi=globalThis).__zod_globalConfig??(Qi.__zod_globalConfig={});var ta=globalThis.__zod_globalConfig;function na(e){return e&&Object.assign(ta,e),ta}function ra(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function ia(e,t){return typeof t==`bigint`?t.toString():t}function aa(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function oa(e){return e==null}function sa(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function ca(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r){};function ga(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var _a=aa(()=>{if(ta.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function va(e){if(ga(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return ga(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function ya(e){return va(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var ba=new Set([`string`,`number`,`symbol`]);function xa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Sa(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function U(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Ca(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var wa={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ta(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Sa(e,fa(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return da(this,`shape`,e),e},checks:[]}))}function Ea(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Sa(e,fa(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return da(this,`shape`,r),r},checks:[]}))}function Da(e,t){if(!va(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Sa(e,fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return da(this,`shape`,n),n}}))}function Oa(e,t){if(!va(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Sa(e,fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return da(this,`shape`,n),n}}))}function ka(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Sa(e,fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return da(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function Aa(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return Sa(t,fa(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return da(this,`shape`,i),i},checks:[]}))}function ja(e,t,n){return Sa(t,fa(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return da(this,`shape`,i),i}}))}function Ma(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Fa(e){return typeof e==`string`?e:e?.message}function Ia(e,t,n){let r=e.message?e.message:Fa(e.inst?._zod.def?.error?.(e))??Fa(t?.error?.(e))??Fa(n.customError?.(e))??Fa(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function La(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Ra(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var za=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ia,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ba=H(`$ZodError`,za),Va=H(`$ZodError`,za,{Parent:Error});function Ha(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ua(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new $i;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Ia(e,a,na())));throw ha(t,i?.callee),t}return o.value},Ga=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Ia(e,a,na())));throw ha(t,i?.callee),t}return o.value},Ka=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new $i;return a.issues.length?{success:!1,error:new(e??Ba)(a.issues.map(e=>Ia(e,i,na())))}:{success:!0,data:a.value}},qa=Ka(Va),Ja=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>Ia(e,i,na())))}:{success:!0,data:a.value}},Ya=Ja(Va),Xa=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Wa(e)(t,n,i)},Za=e=>(t,n,r)=>Wa(e)(t,n,r),Qa=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ga(e)(t,n,i)},$a=e=>async(t,n,r)=>Ga(e)(t,n,r),eo=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ka(e)(t,n,i)},to=e=>(t,n,r)=>Ka(e)(t,n,r),no=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ja(e)(t,n,i)},ro=e=>async(t,n,r)=>Ja(e)(t,n,r),io=/^[cC][0-9a-z]{6,}$/,ao=/^[0-9a-z]+$/,oo=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,so=/^[0-9a-vA-V]{20}$/,co=/^[A-Za-z0-9]{27}$/,lo=/^[a-zA-Z0-9_-]{21}$/,uo=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,fo=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,po=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,mo=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ho=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function go(){return new RegExp(ho,`u`)}var _o=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,vo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,yo=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,bo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xo=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,So=/^[A-Za-z0-9_-]*$/,Co=/^https?$/,wo=/^\+[1-9]\d{6,14}$/,To=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,Eo=RegExp(`^${To}$`);function Do(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Oo(e){return RegExp(`^${Do(e)}$`)}function ko(e){let t=Do({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${To}T(?:${r})$`)}var Ao=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},jo=/^-?\d+$/,Mo=/^-?\d+(?:\.\d+)?$/,No=/^(?:true|false)$/i,Po=/^null$/i,Fo=/^[^A-Z]*$/,Io=/^[^a-z]*$/,Lo=H(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ro={number:`number`,bigint:`bigint`,object:`date`},zo=H(`$ZodCheckLessThan`,(e,t)=>{Lo.init(e,t);let n=Ro[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value{(t.inclusive?r.value<=t.value:r.value{Lo.init(e,t);let n=Ro[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Vo=H(`$ZodCheckMultipleOf`,(e,t)=>{Lo.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):ca(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Ho=H(`$ZodCheckNumberFormat`,(e,t)=>{Lo.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=wa[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=jo)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}sa&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Uo=H(`$ZodCheckMaxLength`,(e,t)=>{var n;Lo.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!oa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum{let r=n.value;if(r.length<=t.maximum)return;let i=La(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Wo=H(`$ZodCheckMinLength`,(e,t)=>{var n;Lo.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!oa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=La(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Go=H(`$ZodCheckLengthEquals`,(e,t)=>{var n;Lo.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!oa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=La(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ko=H(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Lo.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),qo=H(`$ZodCheckRegex`,(e,t)=>{Ko.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Jo=H(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Fo,Ko.init(e,t)}),Yo=H(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Io,Ko.init(e,t)}),Xo=H(`$ZodCheckIncludes`,(e,t)=>{Lo.init(e,t);let n=xa(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Zo=H(`$ZodCheckStartsWith`,(e,t)=>{Lo.init(e,t);let n=RegExp(`^${xa(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Qo=H(`$ZodCheckEndsWith`,(e,t)=>{Lo.init(e,t);let n=RegExp(`.*${xa(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),$o=H(`$ZodCheckOverwrite`,(e,t)=>{Lo.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),es=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(` +通知:仅在需要我时`,"composer.nextAction":`询问下一步`,"composer.nextActionPrompt":`我现在该做什么?`,"composer.prepareDraft":`填入编辑框,确认后再发送`,"composer.send":`发送`,"composer.sendMessage":`向 LoopX 发送消息`,"composer.sendMessageHint":`发送消息`,"composer.sentImageAlt":`移除图片 {name}`,"conversation.agentPending":`正在整理…`,"conversation.close":`关闭对话回执`,"conversation.convertHint":`将 Agent 最新回复转为 Task 草稿`,"conversation.full":`查看完整对话`,"conversation.receipt":`对话回执`,"conversation.replying":`正在回复`,"conversation.title":`管家对话`,"conversation.toTask":`转为 Task`,"digest.away":`自上次访问以来的运行记录`,"digest.completed":`新增完成运行`,"digest.failed":`新增失败或中断`,"digest.needsYou":`当前待确认`,"feedback.applying":`正在执行:{title}`,"feedback.cancelFailed":`取消失败:{error}`,"feedback.completed":`已完成:{title}`,"feedback.executionFailed":`执行失败:{error}`,"feedback.gateRequired":`需要你确认:{summary}`,"feedback.notCompleted":`操作未完成:{status}`,"feedback.goalRefreshFailed":`已打开 Goal,但暂时无法刷新最新状态。请点击刷新重试。`,"feedback.preparingPreview":`正在准备确认预览:{title}`,"feedback.previewFailed":`无法准备确认预览:{error}`,"feedback.sendFailed":`发送失败:{error}`,"feedback.sendGenericError":`消息发送失败,请稍后重试。`,"feedback.stale":`状态已变化,操作未执行,请重新生成确认预览。`,"feedback.taskDraftCreated":`已根据回复生成 Task 草稿。编辑后发送,LoopX 会先展示确认预览。`,"goal.defaultTitle":`新的个人 Goal`,"goal.initialTodo":`按完成标准推进:{criteria}`,"goal.objectiveBoundary":`执行边界:{boundary}`,"goal.objectiveCompletion":`完成标准:{criteria}`,"drawer.advancedDiagnostics":`高级诊断`,"drawer.agentWorking":`Agent 正在继续执行,记录会自动更新。`,"drawer.analysis":`正在分析`,"drawer.apply":`确认并应用`,"drawer.applying":`正在应用…`,"drawer.attentionBlocking":`正在阻塞 Agent`,"drawer.attentionWaiting":`等待你的决定`,"drawer.autoNotify":`Human-gate 自动通知`,"drawer.branch":`分支`,"drawer.closeDetail":`关闭详情:返回{context}`,"drawer.connected":`已连接`,"drawer.correctionDescription":`消息会沿用当前 Goal、Todo 与 Agent Session 上下文。`,"drawer.correctionLabel":`与 {agent} 纠偏`,"drawer.correctionPlaceholder":`例如:先关注权限风险,暂时不要提交…`,"drawer.correctionSend":`发送纠偏`,"drawer.correctionTextarea":`输入纠偏信息:Goal {goal},Agent {agent},Run {run}`,"drawer.copyRepository":`复制仓库标识`,"drawer.copyRepositoryDone":`已复制仓库标识`,"drawer.copyRepositoryError":`复制失败,请检查浏览器剪贴板权限。`,"drawer.copyRepositorySuccess":`已复制,可粘贴到其他工具。`,"drawer.cost":`成本 24h / 7d`,"drawer.costShort":`成本`,"drawer.durationShort":`时长`,"drawer.period24h":`24 小时`,"drawer.period7d":`7 天`,"drawer.tokens":`Token 24 小时 / 7 天`,"drawer.tokensShort":`Token`,"drawer.usageNotMeasured":`未采集`,"drawer.currentGoal":`当前 Goal`,"attentionDetail.title":`事项说明`,"attentionDetail.request":`需要你做什么`,"attentionDetail.decision":`需要作出决定`,"attentionDetail.unknownRequest":`来源未明确,请先查看来源再判断`,"attentionDetail.open":`当前投影中待处理`,"attentionDetail.closed":`已关闭`,"attentionDetail.deferred":`已推迟`,"attentionDetail.superseded":`已被替代`,"attentionDetail.unknown":`来源未提供状态`,"attentionDetail.unavailable":`来源尚未确认当前事项,请刷新后再操作`,"attentionDetail.unknownReason":`来源尚未提供原因。`,"attentionDetail.targetTodo":`关联的待解锁 Todo`,"attentionDetail.targetAgent":`事项指定的 Agent`,"attentionDetail.scope":`声明的决策范围`,"attentionDetail.notProvided":`来源未提供`,"attentionDetail.replacement":`替代 Todo`,"attentionDetail.openReplacement":`打开替代事项`,"attentionDetail.boundary":`阅读详情不会关闭 gate 或授予权限;作出决定前仍需新的操作预览。`,"drawer.decisionDefaultEvidence":`当前状态没有附加公开安全证据;下一步仍会先展示 Preview。`,"drawer.decisionDefaultReason":`该决定会影响当前 Todo 的下一步执行。`,"drawer.decisionDefer":`稍后决定`,"drawer.decisionMore":`更多决定`,"drawer.decisionReject":`拒绝`,"drawer.decisionReview":`查看影响并决定`,"drawer.dependencies":`依赖`,"drawer.detailsAndActions":`详情与操作`,"drawer.duration":`运行时长 24h / 7d`,"drawer.evidence":`证据`,"drawer.executionHistory":`执行历史`,"drawer.executionRecord":`运行记录`,"drawer.executionRecordAndResult":`执行过程与结果`,"drawer.explainDecision":`解释此决定`,"drawer.gateApproveHint":`在终端执行一条命令即可完成审批:`,"drawer.gateRejectHint":`不同意就把末尾的 approve 换成 reject。执行后这条提醒会自动消失。`,"drawer.gateRequiresHost":`需要宿主确认`,"drawer.gateRequiresHostDescription":`页面无权直接批准这类权限变更,你的点击没有写入任何内容。`,"drawer.goalAutoRun":`当前 Goal 的自动运行`,"drawer.goalChanges":`当前 Goal 的待确认变更`,"drawer.goalDetails":`Goal 详情`,"drawer.group":`群聊`,"drawer.inspectorFull":`切换到全屏`,"drawer.inspectorFullView":`全屏查看`,"drawer.inspectorHalf":`切换到半屏`,"drawer.inspectorHalfView":`半屏查看`,"drawer.lastNotification":`最近通知`,"drawer.larkConfigure":`管理 Lark connection`,"drawer.larkConnect":`连接 Lark App`,"drawer.larkConnection":`Lark connection`,"drawer.larkNotConfigured":`未配置`,"drawer.larkNotConfiguredDescription":`配置后,当这个 Goal 出现需要你确认的变更时,会自动发飞书通知。`,"drawer.managerChanges":`管家待确认变更`,"drawer.moreActions":`更多操作`,"drawer.moreRunActions":`更多运行操作`,"drawer.nextTransition":`下一转换`,"drawer.noExecutionHistory":`暂无执行记录。`,"drawer.noRun":`尚未启动执行 Session`,"drawer.noRunDescription":`Agent 开始执行后,运行记录会稳定显示在这里。`,"drawer.notAssigned":`未分配`,"drawer.notLinked":`未关联`,"drawer.notSet":`未设置`,"drawer.outputDetails":`产出详情`,"drawer.outputRecorded":`该产出已记录到当前 Goal。`,"drawer.outputSafePreview":`公开安全产出预览`,"drawer.outputRun":`Run`,"drawer.outputTodo":`Todo`,"drawer.outputs":`本次运行产出`,"drawer.previewUnavailable":`此产出没有可用的公开安全内联预览。`,"drawer.priority":`优先级`,"drawer.progress":`进度`,"drawer.proposalApplied":`已应用,LoopX 状态将刷新。`,"drawer.proposalApplyFailed":`应用失败,没有写入任何变更。`,"drawer.proposalApplyFailedHint":`请刷新 Goal 状态后重新生成;若仍失败,可保留此页并查看高级诊断。`,"drawer.proposalClose":`关闭`,"drawer.proposalDefer":`稍后`,"drawer.proposalDeferred":`已暂缓,可稍后继续应用或重新生成。`,"drawer.proposalEnterGoal":`进入新 Goal`,"drawer.proposalExplainer":`确认后,LoopX 会执行这项变更并显示写入结果。关闭或取消不会修改任何状态。`,"drawer.proposalRecheck":`按最新状态重新检查`,"drawer.proposalRegenerate":`基于最新状态重试`,"drawer.proposalRejected":`已拒绝,这项变更不会写入。`,"drawer.proposalStale":`来源状态已变化,请按最新状态重新检查。`,"drawer.proposalViewGoal":`查看更新后的 Goal`,"drawer.reassign":`改派给`,"drawer.reassignSummary":`重新分配:{task}`,"drawer.reason":`原因`,"drawer.recoveryDescription":`本地历史已经保留,请选择恢复路径。`,"drawer.recoveryFailed":`上游 Session 恢复失败`,"drawer.recoveryNewSession":`携带上下文开始新 Session`,"drawer.recoveryRetry":`重试恢复`,"drawer.repositoryRole":`执行工作区`,"drawer.repository":`仓库`,"drawer.replyMode":`回复方式`,"drawer.subagentApplied":`已写入,并通过共享 Goal 状态读回校验。`,"drawer.subagentAppliedRefreshFailed":`已写入并通过共享 Goal 状态读回;状态投影刷新失败,可稍后手动刷新。`,"drawer.subagentApplying":`正在写入并校验共享状态读回…`,"drawer.subagentApplyFailed":`子代理设置写入失败。`,"drawer.subagentChildLimit":`当前上限`,"drawer.subagentConfirmDisable":`确认关闭子代理执行`,"drawer.subagentConfirmEnable":`确认开启子代理执行`,"drawer.subagentCurrentBoundary":`当前任务领域限制`,"drawer.subagentDescription":`仅在 Todo、配额、能力和写入范围门禁全部通过后,允许运行时为相互独立的任务临时创建子代理;不会强制并行,也不会授予持久权限。`,"drawer.subagentDisable":`预览关闭子代理执行`,"drawer.subagentDisableSummary":`这个 Goal 将不再创建新的子代理;现有 Todo 归属和执行记录不受影响。`,"drawer.subagentDomainInvalid":`所选任务领域限制无效。`,"drawer.subagentDomainTodoCount":`匹配 {count} 个开放 Todo`,"drawer.subagentDomains":`任务领域限制(可选)`,"drawer.subagentDomainsEmpty":`当前没有开放的 advancement Todo 声明 task_domain;保持为空即可不按任务领域限制子代理执行。`,"drawer.subagentDomainsHint":`全部不选表示不按任务领域过滤;选择后只放行匹配且已声明领域的 Todo,其他执行门禁始终生效。`,"drawer.subagentDomainsUnrestricted":`不限制任务领域`,"drawer.subagentEnable":`预览开启子代理执行`,"drawer.subagentLabel":`Per-Goal 执行边界`,"drawer.subagentModel":`子 Agent 模型`,"drawer.subagentEffort":`子 Agent 推理档位`,"drawer.subagentModelDefault":`宿主默认`,"drawer.subagentLunaPreset":`使用 Luna / max`,"drawer.subagentClearModel":`清除模型偏好`,"drawer.subagentModelHint":`填写后通过“预览配置调整”保存,执行关闭时也可保存偏好;启动时须核验宿主支持情况。`,"drawer.subagentModelRequired":`设置推理档位前请先指定子 Agent 模型。`,"drawer.subagentMaxChildren":`最多子代理数`,"drawer.subagentNoChange":`当前 Goal 已是这个设置,没有写入任何内容。`,"drawer.subagentPending":`待确认`,"drawer.subagentPreviewBoundary":`预览配置调整`,"drawer.subagentPreviewFailed":`无法生成子代理设置预览。`,"drawer.subagentPreviewing":`正在核对最新 Goal 状态…`,"drawer.subagentPreviewReady":`预览已锁定,确认后才会写入这个 Goal。`,"drawer.subagentPreviewSummary":`最多允许创建 {count} 个子代理;任务领域限制:{domains}。`,"drawer.subagentRemoteReadOnly":`当前来源只读,请在 Goal 所在主机上修改。`,"drawer.subagentTitle":`自适应子代理执行`,"drawer.remoteDetailsDescription":`SSH 来源只展示公开安全状态,不读取来源主机上的连接配置。`,"drawer.remoteDetailsUnavailable":`远端详情未投影`,"drawer.resumeNo":`否`,"drawer.resumeYes":`是`,"drawer.runDetails":`执行 Session`,"drawer.runInterrupt":`中断本次运行`,"drawer.runLatest":`查看最近执行过程`,"drawer.runNewSession":`开始新 Session`,"drawer.runCloseSession":`关闭 Session`,"drawer.runRecordEmpty":`还没有运行记录。Agent 尚未开始这次执行;请在“详情与操作”查看等待条件或恢复 Session。`,"drawer.runRecordProjected":`当前没有可展示的逐步运行记录。LoopX 已读取到 {completed}/{total} 的投影进度{outputs};请在“详情与操作”检查 Session 状态。`,"drawer.runRecordProjectedOutputs":`和 {count} 项产出`,"drawer.runRoleAssistant":`已完成`,"drawer.runRoleSystem":`需检查`,"drawer.runRoleUser":`收到任务`,"drawer.runView":`Session 视图`,"drawer.scheduleAdd":`添加定时检查`,"drawer.scheduleDefaultNotification":`仅在需要你时通知`,"drawer.scheduleDefaultStop":`Goal 完成或 owner 停止`,"drawer.scheduleDefaultTarget":`由 LoopX 调度器按 Goal 配置唤醒。`,"drawer.scheduleEdit":`改为每 2 小时`,"drawer.scheduleLast":`上次执行`,"drawer.scheduleLocalTimezone":`本地时区`,"drawer.scheduleNext":`下次执行`,"drawer.scheduleNeverRun":`尚未执行`,"drawer.scheduleNotification":`通知`,"drawer.schedulePause":`暂停`,"drawer.schedulePending":`等待调度`,"drawer.scheduleResume":`恢复`,"drawer.scheduleRunNow":`立即运行`,"drawer.scheduleStop":`停止{kind}`,"drawer.scheduleStopCondition":`停止条件`,"drawer.scheduleTimezone":`时区`,"drawer.sessionRecoverable":`可恢复`,"drawer.sessionStatus":`会话状态`,"drawer.setupHeartbeat":`设置 Heartbeat`,"drawer.taskActions":`Todo 待确认操作`,"drawer.taskAdvancement":`推进任务`,"drawer.taskBlock":`标记阻塞`,"drawer.taskComplete":`标记完成`,"drawer.taskCompletedNote":`该任务保留为只读记录。`,"drawer.taskCompletedTitle":`任务已完成`,"drawer.taskDefer":`暂缓`,"drawer.taskDeferCondition":`Todo 暂缓恢复条件`,"drawer.taskDeferInvalid":`条件格式不受支持;请使用下列可判定条件。`,"drawer.taskDeferPlaceholder":`例如 resume_at:2026-09-14T09:00:00+08:00`,"drawer.taskDeferReview":`检查暂缓`,"drawer.taskDeferSupported":`支持 todo_done、pr_merged、capacity_available 与带时区的 resume_at 条件。`,"drawer.taskDeferUntil":`暂缓至`,"drawer.taskDetails":`Todo 详情`,"drawer.taskInfo":`任务信息`,"drawer.taskManage":`管理任务`,"drawer.taskNextCompleted":`可创建后续任务`,"drawer.taskNextOpen":`推进或更新状态`,"drawer.taskOrdinary":`普通任务`,"drawer.taskStatusBlocked":`受阻`,"drawer.taskStatusDeferred":`已延期`,"drawer.resumeWhen":`恢复条件`,"drawer.resumeState":`恢复状态`,"drawer.resumePending":`等待条件满足`,"drawer.resumeReady":`可恢复`,"drawer.resumeReceipt":`恢复回执`,"drawer.taskNextDeferred":`等待恢复条件满足后重新评估`,"drawer.taskNextResumeReady":`恢复条件已满足,等待生命周期重新规划`,"drawer.taskStatusCompleted":`已完成`,"drawer.taskStatusOpen":`待执行`,"drawer.taskSuccessor":`创建后续 Todo`,"drawer.taskSuccessorNote":`Owner 标记为阻塞,等待补充上下文。`,"drawer.taskSuccessorSummary":`创建后续 Todo:{task}`,"drawer.taskSuccessorText":`{task} 的后续工作`,"drawer.taskType":`任务类型`,"drawer.topic":`Topic`,"drawer.trigger":`触发方式`,"drawer.titleAttention":`需要你`,"drawer.titleOutput":`产出详情`,"drawer.titleProposalApplied":`执行结果`,"drawer.titleProposalConfirm":`确认执行`,"drawer.titleSchedule":`定时检查`,"drawer.unconfigured":`未配置`,"drawer.workspaceCandidates":`可选择的工作区`,"files.emptySummary":`公开安全产出`,"files.empty":`还没有文件、产出或已验证的阶段周报。`,"files.loadingReports":`正在加载已验证的阶段周报…`,"files.reportDelta":`+{added} 新增 · {changed} 变化`,"files.reportAdded":`新增`,"files.reportChanged":`变化`,"files.reportGeneration":`生成批次`,"files.reportLoadFailed":`无法加载已验证周报`,"files.reportPublication":`发布批次`,"files.title":`Files & Outputs`,"files.verifiedReport":`已验证阶段周报`,"header.agentUnavailable":`不可用`,"header.chatRuntime":`Chat`,"header.workAgentCount":`{count} 个工作 Agent`,"header.chat":`Chat`,"header.files":`Files`,"header.goalCapabilities":`能力配置`,"header.goalCapabilitiesDescription":`管理 Goal override 与继承的本机默认值。`,"header.goalDetails":`Goal 详情`,"header.goalDetailsDescription":`查看状态、用量、仓库、通知与 Session。`,"header.goalSettings":`Goal 设置`,"header.goalSettingsDescription":`打开 Goal 详情或能力配置`,"header.goalNavigation":`Goal 导航`,"header.goalView":`Goal 视图`,"header.live":`实时`,"header.manager":`LoopX 管家`,"header.managerDescription":`跨 Goal 的个人工作入口`,"header.managerOverview":`总览`,"header.managerView":`管家视图`,"header.openGoalNavigation":`打开 Goal 导航`,"header.readOnlySourceDescription":`{source} 通过 SSH 隧道只读展示`,"header.refresh":`刷新状态`,"header.refreshDone":`刚刚更新`,"header.refreshFailed":`刷新失败`,"header.refreshing":`刷新中`,"header.selectAgent":`选择 Agent`,"header.selectChatRuntime":`选择聊天 Runtime`,"header.tasks":`Tasks`,"header.themeBrutal":`切换到野兽主题`,"header.themePaper":`切换到默认主题`,"home.blockingSummary":`其中 {count} 项正在阻塞 Agent。`,"home.completedGoals":`已完成的 Goal`,"home.empty":`当前没有`,"startup.goalLoading":`正在加载状态…`,"startup.goalError":`状态加载失败`,"startup.progress":`已加载 {loaded} / {total} 个活跃 Goal`,"startup.partial":`Goal 状态正在逐个更新,当前统计尚不完整。`,"startup.independent":`此 Goal 的加载不会阻塞其他 Goal,你可以先查看已加载的内容。`,"startup.error.timeout":`读取超时,可在本地服务就绪后重试。`,"startup.error.network":`连接中断,请重试以重新连接。`,"startup.error.service":`本地服务暂时不可用,请重试继续加载。`,"startup.error.revision":`加载期间 Goal 目录发生变化,请刷新以同步。`,"startup.error.scope":`该 Goal 已不在当前来源中,请刷新目录。`,"startup.error.invalid":`无法解析状态响应,请刷新或检查 LoopX 更新。`,"startup.retry":`重试`,"startup.retryFailed":`重试失败的 Goal`,"startup.failedCount":`{count} 个 Goal 加载失败,已加载的 Goal 可继续使用。`,"home.greeting":`你好,我是 LoopX 管家`,"home.history":`历史`,"home.lane.needsYou":`需要你`,"home.lane.needsYouDescription":`等待你的决定、授权或补充信息`,"home.lane.observing":`观察中`,"home.lane.observingDescription":`持续监控,出现变化时再提醒你`,"home.lane.running":`执行中`,"home.lane.runningDescription":`Agent 正在推进并持续回传进展`,"home.lane.scheduled":`已安排`,"home.lane.scheduledDescription":`已经安排,等待时间或前置条件`,"home.noActivity":`尚无活动`,"home.noFirstActivity":`等待首次活动`,"home.noCompletedGoals":`还没有已完成的 Goal`,"home.preservedState":`保留状态,可随时恢复`,"home.stopped":`已停止`,"home.systemHealth":`系统健康:{summary}`,"home.taskCount":`{count} 个 Task`,"home.todayAt":`今天 {time}`,"home.waitingCount":`你有 {count} 项需要处理。`,"home.workspace":`Goal 工作区`,"lark.allMessages":`此 Topic 中的所有消息`,"lark.allTopicMessages":`所有 Topic 消息`,"lark.agentIngress":`Agent 入站方式`,"lark.agentAppPermissions":`每个选中的 Agent 都需要一个已具备群聊提及和回复能力的 Lark App。`,"lark.agentApps":`每个 Agent 的 Lark App`,"lark.agentAppsDescription":`默认使用上方 App;需要独立机器人身份时,可为 Agent 选择另一个兼容 App。`,"lark.agentAppSelection":`{agent} 的 Lark App`,"lark.appCreated":`App 已创建`,"lark.appCreateFailed":`创建失败`,"lark.appLoading":`正在加载可用的 Lark Apps…`,"lark.appPermissions":`该 App 能发送建联消息,但缺少接收群聊 @ 消息或自动回复所需的机器人权限。请开启 im:message.group_at_msg:readonly、im:message.send_as_bot 和事件 im.message.receive_v1,发布新版后刷新。`,"lark.appProfile":`Lark App`,"lark.apps":`Lark Apps`,"lark.autoReplyUnavailable":`自动回复暂不可用`,"lark.autoReplyReady":`自动回复可用`,"lark.bindGoal":`绑定到 Goal`,"lark.cancel":`取消`,"lark.cardinality":`一个 Lark App · 多个 Goal · 每个 Agent 一条隔离路由`,"lark.capture":`接收范围`,"lark.captureAddressed":`仅接收提及 App 或回复 App 的消息`,"lark.captureAll":`接收此 Goal Topic 中的所有消息`,"lark.captureScope":`接收范围`,"lark.captureScopeDescription":`决定哪些 Topic 消息会进入 LoopX;不会扩大 Agent 权限。`,"lark.closeConnection":`关闭连接弹窗`,"lark.closeCreate":`关闭创建弹窗`,"lark.closeSettings":`关闭 Lark 设置`,"lark.connect":`连接`,"lark.connectAllAgents":`连接全部已注册 Agent`,"lark.connectAllAgentsAction":`一键连接 {count} 个 Agent`,"lark.connectAllAgentsDescription":`一次引导创建 {count} 个隔离的 Agent Topic;请在对应 Topic 内发送请求,每个 Agent 保留独立路由和收件箱。`,"lark.connectApp":`连接 Lark App`,"lark.connection":`连接`,"lark.connections":`连接`,"lark.configuration":`Lark 配置`,"lark.continueFeishu":`在飞书中继续`,"lark.createAutomatically":`自动创建 Goal Topic`,"lark.createAutomaticallyDescription":`将为每个选中的 Agent 创建带 Agent 标识的专属 Topic。`,"lark.defaultAgentAppDescription":`用于查找目标群聊,并作为所有选中 Agent 的默认 App;下方的逐 Agent 选择可覆盖它。`,"lark.description":`管理可复用的 Lark App,并用独立 Topic 将群聊连接到 Goal。`,"lark.editConnection":`编辑 Lark 连接`,"lark.goalConnections":`{count} 个 Goal 连接`,"lark.goalTopicConnections":`Lark Goal Topic 连接`,"lark.groupChat":`群聊`,"lark.groupEmpty":`该机器人尚未加入可连接的群。请先在飞书群设置中添加这个机器人,再回来刷新或搜索。`,"lark.groupLoading":`正在读取该机器人已加入的群…`,"lark.groupSearch":`搜索该机器人已加入的群`,"lark.historyPermission":`历史补读权限(独立能力)`,"lark.health.eventProcessed":`已处理 {events} 条事件,成功回复 {replies} 条。`,"lark.health.eventUnverified":`事件订阅待验证`,"lark.health.eventUnverifiedDetail":`Provider listener 已就绪,但尚未收到消息事件。请启用 im.message.receive_v1、开通群聊 @ 消息权限并发布新版,然后在这个 Agent Topic 内发送新的 @ 消息;存在多条 Agent 路由时,群顶层消息会 fail closed。`,"lark.health.ignoredSelf":`已忽略机器人自身发送的消息,避免重复回复。`,"lark.health.invalidRouting":`路由配置无效`,"lark.health.invalidRoutingDetail":`连接已安全停用,请重新选择处理方式并保存。`,"lark.health.lastStatus":`最近事件状态:{status}`,"lark.health.listening":`监听中`,"lark.health.messageContextPermission":`消息权限不足`,"lark.health.messageContextPermissionDetail":`已收到消息事件,但无法读取群消息上下文。请发布并授权该 App 的群消息读取权限。`,"lark.health.notAddressed":`最近消息未直接 @ 机器人`,"lark.health.notAddressedDetail":`监听正常;当前连接只响应直接 @ 机器人或对机器人的回复。`,"lark.health.notStarted":`监听未启动`,"lark.health.notStartedDetail":`请刷新连接或重新启动 LoopX 后再试。`,"lark.health.processingFailed":`消息处理失败`,"lark.health.processingFailedDetail":`已收到消息事件,但 Agent 处理失败。请查看本地诊断后重试。`,"lark.health.queued":`已进入 Agent 收件箱`,"lark.health.queuedDetail":`消息由 {agent} 异步处理,不会启动通用 Chat Session。`,"lark.health.sourceDisconnected":`实时消息连接断开`,"lark.health.sourceDisconnectedDetail":`消息监听进程意外退出。请核对应用档案的平台:飞书应用选飞书,国际版 Lark 应用选 Lark,再检查连接及订阅错误。LoopX 正在重试;历史消息能读取,不代表能实时收消息。`,"lark.health.retrying":`监听重试中`,"lark.health.retryingDetail":`事件监听暂时中断,LoopX 正在自动重试。`,"lark.health.routeAmbiguous":`消息匹配多个 Goal`,"lark.health.routeAmbiguousDetail":`同一 Bot 和群聊存在多个完整群捕获连接。请让每个 Agent 使用独立 Bot,或只保留一个完整群连接。`,"lark.health.routeMismatch":`消息未匹配当前 Goal Topic`,"lark.health.routeMismatchDetail":`事件来自其他群聊或 Topic。请重新选择群聊并连接该 Goal,然后发送一条新的 @ 消息。`,"lark.health.routeUnavailable":`消息无法路由到 Goal`,"lark.health.routeUnavailableDetail":`当前连接信息不完整。请重新连接该 Goal 后再发送一条新的 @ 消息。`,"lark.health.starting":`正在启动`,"lark.health.startingDetail":`LoopX 正在启动该 App 的消息事件监听。`,"lark.health.unavailable":`自动回复不可用`,"lark.health.waiting":`等待处理`,"lark.incomingMessages":`接收消息`,"lark.ingressAsync":`异步收件箱`,"lark.ingressAsyncDescription":`写入 Agent 私有收件箱,等待后续显式处理。`,"lark.editPreservesIdentity":`保存会保留此 App、群和 Topic;旧连接默认升级为 Agent 异步收件箱。`,"lark.conversationKind":`连接用途`,"lark.managerConversation":`管家 · 同步对话`,"lark.workerConversation":`工作 Agent · 后台任务`,"lark.managerConversationDescription":`内置管家即时回应对话,长任务交给后台 Agent。群聊与私聊分别保存上下文。`,"lark.ingressLegacy":`待升级`,"lark.ingressLegacyDescription":`保存连接即可升级为 Agent 异步收件箱,已有消息保留在原 Topic 中。`,"lark.ingressQueue":`排队`,"lark.ingressQueueDescription":`进入同一 Agent Session 的有界 FIFO 队列,当前 Turn 完成后处理。`,"lark.ingressSteering":`实时引导`,"lark.ingressSteeringDescription":`投到当前活跃 Turn;没有精确活跃 Turn 时安全拒绝。`,"lark.loading":`加载 Lark 配置…`,"lark.management":`Lark 管理`,"lark.openEventSettings":`查看飞书事件配置`,"lark.mentions":`提及机器人`,"lark.mentionsOnly":`仅提及消息`,"lark.needsMessagePermissions":`需要消息权限`,"lark.needsSetup":`需要设置`,"lark.newApp":`新建 Lark App`,"lark.noAgentConfigured":`未配置 Agent`,"lark.noConnections":`暂无匹配的连接。`,"lark.noProfiles":`还没有可用的 lark-cli App profile。`,"lark.profileName":`Profile 名称`,"lark.profileValidation":`Profile 只能包含字母、数字、点、下划线和连字符。`,"lark.processing":`处理方式`,"lark.region":`区域`,"lark.registerAnother":`+ 注册另一个 Lark App — 通过飞书创建`,"lark.reopenFeishu":`重新打开飞书`,"lark.settingsConfigure":`配置 {goal}`,"lark.settingsDisconnect":`解绑 {goal}`,"lark.replyMode":`回复方式`,"lark.replyModeDescription":`当前只支持在来源 Topic 内回复,避免跨群或跨 Goal 投递。`,"lark.reusableApps":`{count} 个可复用 App`,"lark.reusableWorkspaceApp":`可复用工作区 App`,"lark.routesUnverified":`{count} 条 Lark 路由尚未验证`,"lark.saveConnection":`保存连接`,"lark.searchConnections":`搜索 Lark 连接`,"lark.searchPlaceholder":`搜索 App、群、Goal 或 Topic`,"lark.setupCopy":`LoopX 将通过 lark-cli 打开飞书官方创建页面。应用凭证保存在系统 Keychain,LoopX 只保留 profile 引用。`,"lark.someoneMentions":`有人提及 Agent`,"lark.targetAgent":`目标 Agent`,"lark.targetAgentDescription":`选择该 Goal 内已注册的 Agent。此连接只投递给一个 Agent,不广播、不授予新权限。实时引导与排队需要该 Agent 的精确活跃 Session。`,"lark.agentUnavailable":`{agent} · 已不可用`,"lark.selectRegisteredAgent":`请先选择可用的已注册 Agent;不会自动替换原先的接收者。`,"lark.topicPreview":`Topic 预览`,"lark.topicReply":`Topic 回复`,"lark.trigger":`触发方式`,"lark.waitingFeishu":`等待飞书完成创建`,"lark.waitingFeishuDescription":`请在新窗口中完成飞书授权,完成后会自动回到这里。`,"lark.waitingLink":`正在生成飞书官方创建链接…`,"lark.error.appCreate":`Lark App 创建失败`,"lark.error.appRequired":`请选择一个 Lark App profile。`,"lark.error.bind":`绑定失败`,"lark.error.bindPreview":`绑定预览失败`,"lark.error.configuration":`Lark 配置加载失败`,"lark.error.groupLookup":`无法读取该机器人已加入的群。请检查机器人状态后重试。`,"lark.error.groupLoad":`群聊加载失败`,"lark.error.invalidApp":`Lark App profile 不可用或尚未完成授权。`,"lark.error.messagePermissions":`该 App 缺少自动回复所需的机器人权限。请开启 im:message.group_at_msg:readonly 和 im:message:send_as_bot,发布新版后回来刷新重试。`,"lark.error.provider":`飞书 API 调用失败,且没有生成已验证回执。请稍后重试。`,"lark.error.setupPoll":`创建状态查询失败`,"lark.error.setupStart":`无法启动 Lark App 创建流程`,"lark.error.cliExecutable":`已找到配置的 lark-cli,但当前无法执行。请检查安装或启动参数。`,"lark.error.cliMissing":`未发现 lark-cli。请先安装 lark-cli,然后重新启动 LoopX。`,"lark.error.cliStart":`lark-cli 启动失败。请检查安装状态,然后重新启动 LoopX。`,"lark.error.disconnect":`解绑失败`,"notifications.autoNotify":`需要你确认时自动推送到群里`,"notifications.bind":`绑定到通知群`,"notifications.bindConfirm":`将把「{goal}」绑定到通知群「{target}」,绑定时会验证机器人在群内并发送一条确认消息。`,"notifications.bindFailed":`绑定失败`,"notifications.bound":`已绑定`,"notifications.confirmBind":`确认绑定`,"notifications.description":`把 Goal 里需要你确认的变更推送到飞书群。绑定和开关在这里完成,推送逻辑沿用现有通道。`,"notifications.disabled":`已停用`,"notifications.group":`通知群:{target}`,"notifications.loadFailed":`通知群列表加载失败`,"notifications.noTargets":`还没有可用的通知群。通知群涉及机器人私有身份,请先在终端配置一次:`,"notifications.notBound":`未绑定`,"notifications.recent":`最近 {time}`,"notifications.sentCount":`已发送 {count} 条`,"notifications.settings":`Goal 通知绑定`,"notifications.setupFailed":`设置失败`,"notifications.title":`飞书群通知`,"proposal.field.agentId":`Agent`,"proposal.field.cadence":`频率`,"proposal.field.completionCriteria":`完成标准`,"proposal.field.executionBoundary":`执行边界`,"proposal.field.goalId":`Goal ID`,"proposal.field.heartbeat":`Heartbeat`,"proposal.field.initialTodos":`首个任务`,"proposal.field.objective":`目标`,"proposal.field.operation":`操作`,"proposal.field.operationState":`操作状态`,"proposal.field.resultDelivery":`结果回传`,"proposal.field.confirmationBoundary":`确认边界`,"proposal.field.expiresAt":`过期时间`,"proposal.field.permission":`权限`,"proposal.field.reason":`原因`,"proposal.field.stopCondition":`停止条件`,"proposal.field.target":`检查内容`,"proposal.field.timezone":`时区`,"proposal.field.title":`标题`,"proposal.field.workspace":`执行工作区`,"actionReview.targetChanged":`预览目标与请求的 Goal 或操作不一致,请重新生成预览。`,"actionReview.ready_stop":`暂停可恢复。此预览已通过检查,可直接执行;完成仍需要读回验证。`,"actionReview.resume_review":`恢复自动调度前需要确认。实际执行仍受额度、Gate 和 Todo 约束。`,"actionReview.delete_review":`请确认从注册表移除这个已停止 Goal。项目文件与历史记录会保留。`,"actionReview.action_review":`执行前请检查此提案的目标与影响。`,"actionReview.protected_action":`此操作需要明确审阅。确认不能替代所需授权。`,"actionReview.unknown_permission":`无法识别权限分类。请重新检查提案后再继续。`,"actionReview.unknown_action":`无法识别此生命周期操作。请重新检查提案后再继续。`,"actionReview.incomplete_proposal":`预览缺少验证信息或可执行转换。请重新生成预览。`,"actionReview.authority_gate":`Gate 阻止执行。请满足其要求后重新检查提案。`,"actionReview.stale_proposal":`来源状态已变化。请重新生成预览,原决定不再适用。`,"actionReview.apply_pending":`正在执行,请等待读回结果后再重试。`,"actionReview.readback_verified":`操作已完成,结果状态已通过读回验证。`,"actionReview.readback_unverified":`操作返回但未通过读回验证。尚不能确认完成,请重新检查状态。`,"actionReview.operation_group_confirmation":`这份精确请求只能在已绑定飞书群的原始卡片确认;Dashboard 不提供本地执行入口。`,"actionReview.operation_result_delivery_pending":`操作结果已经记录,但原群结果卡尚未通过回读核验。`,"actionReview.apply_failed":`执行未完成。请检查失败原因并重新生成预览后再试。`,"actionReview.inactive_proposal":`此提案当前不可执行。请重新检查后再继续。`,"proposal.gate.default":`需要宿主确认`,"proposal.impact.default":`确认后会调用规范 LoopX 服务写入状态。`,"proposal.impact.goalCreate":`确认后会创建 Goal 和首个 Todo,并让选定 Agent 开始首轮推进。`,"proposal.impact.lifecycleDelete":`确认后会从 source registry 和 global registry 移除这个已停止 Goal;项目文件、历史状态文件和备份不会被删除。`,"proposal.impact.lifecycleResume":`确认后会恢复 Goal 的自动调度资格并移回 Active Goals;实际执行仍受 quota、Gate 和 Todo 约束。`,"proposal.impact.lifecycleStop":`确认后会停止自动推进,并将 Goal 移入折叠的「已停止」列表;历史、Todo 和证据都会保留,可随时恢复。`,"proposal.impact.protected":`该操作需要通过受保护的 LoopX 写入服务完成。`,"proposal.impact.operation":`这里仅展示同一份不可变条款。请在已绑定的飞书群确认或拒绝;确认只会消费一个规范 claim。`,"proposal.primary.apply":`确认并应用`,"proposal.primary.goalCreate":`创建 Goal 并开始首轮`,"proposal.primary.lifecycleDelete":`删除 Goal`,"proposal.primary.lifecycleResume":`恢复 Goal`,"proposal.primary.lifecycleStop":`停止 Goal`,"proposal.primary.todoStart":`创建任务并开始执行`,"proposal.primary.operationGroup":`前往飞书群确认`,"proposal.primary.operationResultPending":`结果卡回传待恢复`,"proposal.primary.operationResultVerified":`结果已核验`,"proposal.resultDelivery.verified":`已在原群卡片完成回读核验`,"proposal.resultDelivery.pending":`等待回传并核验原群卡片`,"proposal.summary.goalCreate":`创建 Goal:{title}`,"proposal.summary.heartbeat":`为当前 Goal 设置 Heartbeat`,"proposal.summary.lifecycleDelete":`删除 Goal:{title}`,"proposal.summary.lifecycleResume":`恢复 Goal:{title}`,"proposal.summary.lifecycleStop":`停止 Goal:{title}`,"proposal.summary.monitor":`为当前 Goal 创建定时检查:{target}`,"proposal.workspace.current":`当前本地工作区(未绑定 Repository)`,"proposal.workspace.named":`{workspace}(仅提供执行环境,不会自动关联仓库)`,"proposal.workspaceGate.agentImpact":`先完成 Agent 身份绑定,再重新检查原操作;当前没有写入 Goal。`,"proposal.workspaceGate.agentTitle":`先绑定 Agent`,"proposal.workspaceGate.defaultSummary":`请选择 Goal 所属工作区。`,"proposal.workspaceGate.selectionImpact":`选择工作区后会重新展示待确认操作,选择本身不会写入状态。`,"proposal.workspaceGate.selectionTitle":`选择 Goal 工作区`,"projection.agentAdvancingGoal":`Agent 正在推进当前 Goal`,"projection.agentIdle":`暂无需要你处理`,"projection.agentNeedsDecision":`Agent 等待你的决定`,"projection.agentPreparingNextStep":`Agent 正在整理下一步`,"projection.agentStopped":`已由你停止;历史、Todo 和证据仍保留`,"projection.agentWaitingExternal":`正在等待外部条件`,"projection.confirmAgentDecision":`请确认 Agent 下一步需要的权限或决策`,"projection.events24h":`24 小时内 {count} 个事件`,"projection.firstReadOnlyAdapterCheck":`执行首次只读适配检查并保存进度`,"projection.goalVerified":`Goal 状态、Todo 与注册信息已验证`,"projection.latestRun":`最近运行`,"projection.latestValidation":`最近验证`,"projection.nextUpdatePending":`等待 LoopX 更新下一步`,"projection.publicSafeProjection":`公开安全状态投影`,"projection.refreshState":`刷新 LoopX 状态,确认当前进度仍然有效`,"projection.runEvidenceAvailable":`存在可查看的运行证据`,"projection.runRecorded":`最近一次 LoopX 运行已经记录`,"projection.statusRefreshNeeded":`LoopX 状态需要刷新`,"projection.todoStatusUpdated":`Todo 状态已经更新,正在确认下一步`,"projection.validationRecorded":`最近验证已经记录`,"runs.completed":`已完成`,"runs.failed":`需检查`,"runs.interrupted":`已中断`,"runs.queued":`已安排`,"runs.ready":`可继续`,"runs.resumeFailed":`恢复失败`,"runs.running":`执行中`,"runs.unknown":`状态未知`,"runs.waiting":`等待条件`,"schedule.active":`执行中`,"schedule.heartbeat":`Goal Heartbeat`,"schedule.monitor":`定时与持续任务`,"schedule.paused":`已暂停`,"schedule.summary":`按 LoopX 调度约束持续检查`,"schedule.defaultTarget":`检查当前 Goal 的阻塞、进度与新产出`,"schedule.unsupportedCalendar":`当前定时检查不支持精确到星期或时刻的日历计划。请改用固定间隔,例如“每 30 分钟”“每 2 小时”或“每天”;草稿已保留,没有生成待确认操作。`,"source.add":`添加来源`,"source.addConfigured":`添加只读来源`,"source.addMethod":`来源添加方式`,"source.addSsh":`添加 SSH 隧道来源`,"source.closeForm":`关闭来源表单`,"source.configured":`已配置 SSH`,"source.configuredCount":`本机 SSH Host · {count} 个`,"source.configuredGroup":`已配置 SSH Host · {count}(点击快速添加)`,"source.connected":`已连接`,"source.connecting":`连接中`,"source.controlPlane":`控制面来源`,"source.copy":`复制`,"source.copyCommand":`复制 SSH 隧道命令`,"source.copyError":`无法复制命令,请手动复制下方命令。`,"source.copied":`已复制`,"source.description":`已读取全部显式 Host(含 Include);通配规则不会作为具体来源。先运行命令,LoopX 不读取密钥或配置细节。`,"source.host":`本机 SSH Host`,"source.hostEmpty":`~/.ssh/config 中没有可直接选择的显式 Host。`,"source.hostLoadError":`无法读取本机 SSH Host。`,"source.hostPlaceholder":`输入或搜索 Host`,"source.invalid":`SSH 来源参数无效。`,"source.loadingHosts":`正在读取…`,"source.localInteractive":`本机交互`,"source.localPort":`本地端口`,"source.manual":`手动 URL`,"source.manualDescription":`远端来源始终按只读投影处理,不继承本机写权限。`,"source.name":`名称`,"source.namePlaceholder":`远程开发机`,"source.notAvailable":`不可用`,"source.readOnly":`SSH 隧道 · 只读`,"source.readOnlyNoticeDescription":`你可以查看 Goal、Task、证据与运行状态;写入、纠偏和 Agent 会话仍留在来源主机。`,"source.readOnlyNoticeTitle":`远端只读投影`,"source.readOnlyWriteError":`远端 SSH 隧道来源是只读投影,不能执行控制面写入。`,"source.refreshHosts":`重新读取 SSH Host`,"source.remove":`移除来源 {source}`,"source.removeCurrent":`移除当前来源`,"source.select":`选择控制面来源`,"source.selectHost":`请选择已配置的 SSH Host。`,"source.statusUrl":`本地转发 URL`,"source.tunnelCommandPending":`选择 Host 后生成隧道命令`,"machine.absent":`尚未配置`,"machine.action.create":`创建机器策略`,"machine.action.delete":`移除机器策略`,"machine.action.unchanged":`无需写入`,"machine.action.update":`更新机器策略`,"machine.applied":`机器策略已应用,并通过回读校验。`,"machine.applyError":`无法应用机器策略。`,"machine.applyPreview":`应用已审阅预览`,"machine.changedNamespaces":`变更的 Namespace`,"machine.capabilityCatalog":`机器能力目录`,"machine.capabilityEmpty":`当前没有注册可在机器作用域配置的能力。`,"machine.configured":`已配置`,"machine.confirmRollback":`确认回滚`,"machine.currentRevision":`当前 Revision`,"machine.currentValue":`当前机器值`,"machine.description":`与 Goal 设置共用能力目录。在这里管理受支持的机器默认值;仅支持 Goal 配置的能力会明确标注。`,"capabilities.rawJson":`高级:原始 JSON`,"machine.goalOnly":`此能力目前仅支持 Goal 级配置。请打开具体 Goal 的能力设置进行配置;这里不会设置机器级默认值。`,"machine.desiredRevision":`目标 Revision`,"machine.editorUnavailable":`当前版本未安装此 Namespace 的编辑器`,"machine.editorUnavailableDescription":`它仍会显示在 Registry 中;安装或升级对应的 Dashboard 编辑器后才能修改。`,"machine.editorMode":`编辑模式`,"machine.liveDefault":`实时默认值;Goal 显式覆盖优先`,"machine.liveDefaultDescription":`没有显式覆盖的 Goal 会在该能力下一次决策时读取当前机器策略。修改或移除策略会立即影响这些已有 Goal;显式 Goal 覆盖保持固定。`,"machine.genericNamespaceDescription":`使用 JSON 编辑这个已注册 Namespace。LoopX 会先按 capability 自己拥有的 schema 校验,再允许预览写入。`,"machine.jsonConfiguration":`Namespace 配置(JSON)`,"machine.jsonConfigurationHelp":`只更新当前 Namespace;其他机器配置会保留,Apply 仍锁定到已审阅的 Preview Revision。`,"machine.jsonEditor":`JSON`,"machine.editJson":`编辑 JSON`,"capabilities.jsonConfiguration":`Goal 配置(JSON)`,"capabilities.jsonHelp":`仅编辑当前 Goal 的已注册字段。修改后需重新预览才能应用。`,"capabilities.jsonInvalid":`请输入合法的 JSON 对象,且仅包含已注册的可编辑字段。`,"machine.backToForm":`返回表单`,"machine.jsonInvalid":`请先填写一个合法的 JSON object,再预览变更。`,"machine.loadError":`无法读取机器配置。`,"machine.machinePolicy":`机器策略`,"machine.namespaceCount":`已注册 Namespace`,"machine.namespaces":`配置 Namespace`,"machine.periodicReport":`周期报告`,"machine.periodicReportDescription":`为所有未显式覆盖的 Goal 提供默认报告策略;Goal 调度与发送消费解析后的有效配置。`,"machine.periodicReportActivation":`开启后将在已验证的阶段节点自动投递`,"machine.periodicReportActivationDescription":`这不是每周定时器。当 LoopX 验证 Goal 已完成一个阶段时,Agent 会生成并冻结报告,随后通过配置的 Goal Channel 自动发送。启用此订阅即授予持续投递权;发送失败或路由漂移会 fail closed 并进入修复。`,"machine.changeQualityActivation":`质量验证是质量门禁,不是新增授权`,"machine.changeQualityActivationDescription":`继承该策略的 Goal 会验证最终精确 diff。safe_fix 只允许在既有写入权限内执行至多一次有界修复;此设置不会授予文件、权限或合并权。`,"machine.replanCadenceActivation":`复核周期只改变时机,不改变执行权限`,"machine.replanCadenceActivationDescription":`没有显式覆盖的 Goal 会在下一次复核决策前读取此阈值;它不会创建 Turn、消耗配额或授予权限。`,"machine.preview":`审阅机器配置变更`,"machine.previewChanges":`预览变更`,"machine.previewError":`无法生成机器策略预览。`,"machine.previewLocked":`应用操作锁定到当前 Revision;若机器状态变化,LoopX 会要求重新预览。`,"machine.previewRollback":`预览回滚`,"machine.previewRemoval":`预览移除`,"machine.profilePreset":`Profile preset`,"machine.profilePresetHelp":`由 capability 管理的 preset,例如 weekly-progress。`,"machine.registry":`Typed Registry`,"machine.requiredFields":`开启后必须填写 profile preset、Goal Channel route 与有效时区。`,"machine.revision":`机器 Revision`,"machine.revisionLockedReady":`所有变更必须先预览;只有对应的机器 Revision 仍然有效时才会应用。`,"machine.rollbackAvailable":`可回滚上一次应用`,"machine.rollbackDescription":`先预览已保存的前一 Revision,再决定是否恢复。`,"machine.rollbackError":`无法完成回滚。`,"machine.rollbackPreviewDescription":`前一 Revision 已准备恢复,请确认执行本次回滚。`,"machine.rolledBack":`已恢复前一版机器策略,并通过校验。`,"machine.removed":`机器策略已移除,并通过回读校验。`,"machine.routeRef":`Goal Channel route`,"machine.routeRefHelp":`只填写公开 route alias;凭据与 provider identifier 不会进入此表单。`,"machine.timezone":`时区`,"machine.timezoneHelp":`填写 IANA 时区,例如 Asia/Shanghai。`,"machine.title":`机器配置`,"machine.unchanged":`机器策略已与预览一致,本次没有写入。`,"machine.visualEditor":`引导式`,"capabilities.atomicOverride":`Goal override 按完整配置生效`,"capabilities.atomicOverrideDescription":`Goal 的完整配置优先于机器默认值;LoopX 不会在两个作用域之间逐字段拼接。`,"capabilities.applyFailed":`Goal 能力变更未写入。`,"capabilities.applyPreview":`应用此预览`,"capabilities.catalog":`Goal 能力目录`,"capabilities.chooseGoal":`请先选择一个 Goal,再查看它的能力配置。`,"capabilities.defaultValue":`声明的默认值`,"capabilities.description":`查看当前 Goal 可用的能力,以及每项配置的准确作用域。`,"capabilities.editorPrepared":`已注册 typed editor contract`,"capabilities.effectiveSource":`当前生效来源`,"capabilities.empty":`当前 Goal 没有可用的能力描述。`,"capabilities.fields":`已注册字段`,"capabilities.goalPolicy":`Goal 能力策略`,"capabilities.goalScope":`Goal`,"capabilities.goalValue":`当前 Goal 值`,"capabilities.loadFailed":`无法加载 Goal 能力`,"capabilities.loading":`正在加载 Goal 能力…`,"capabilities.machineOnly":`此能力只能在机器作用域配置。`,"capabilities.machineValue":`实时机器默认值`,"capabilities.machineScope":`机器`,"capabilities.previewOnly":`当前读取结果来自真实配置;在 revision-locked preview/apply 路径接通前,Dashboard 不会提供 Goal 写入控件。`,"capabilities.preview":`锁定 revision 的变更预览`,"capabilities.previewChanges":`预览变更`,"capabilities.restoreInheritance":`恢复继承机器默认值`,"capabilities.previewFailed":`无法预览 Goal 能力变更。`,"capabilities.previewLocked":`应用时会重新校验这一个 plan revision;过期变更将被拒绝。`,"capabilities.partialWrite":`Goal 值已保存;共享投影仍需修复`,"capabilities.partialWriteDescription":`源 Goal 配置已经写入并回读,但共享 runtime 投影尚未同步;请勿重复提交本次变更。`,"capabilities.refreshSource":`刷新源配置`,"capabilities.readOnly":`只读能力`,"capabilities.revisionLockedReady":`所有变更必须先预览;只有对应的精确 revision 仍然有效时才会写入。`,"capabilities.retry":`重试`,"capabilities.source.capability_default":`能力默认值`,"capabilities.source.goal_override":`Goal override`,"capabilities.source.machine_default":`实时机器默认值`,"capabilities.source.not_configured":`未配置`,"capabilities.title":`Goal 能力`,"settings.close":`关闭设置`,"settings.appearance":`外观`,"settings.appearanceDescription":`管理当前浏览器里的工作区显示偏好。`,"settings.appearanceTabDescription":`主题和显示偏好`,"settings.capabilitiesTabDescription":`当前 Goal 的能力覆盖配置`,"settings.back":`返回工作区`,"settings.categories":`设置分类`,"settings.description":`管理工作区偏好与集成。`,"settings.eyebrow":`工作区偏好`,"settings.general":`通用`,"settings.goalConnections":`Goal 连接`,"settings.language":`语言`,"settings.languageDescription":`选择 LoopX Desktop 工作区使用的界面语言。`,"settings.languageEnglishDescription":`使用英文显示导航、设置和工作区控件。`,"settings.languageEnglish":`English`,"settings.languageSimplifiedChineseDescription":`使用简体中文显示导航、设置和工作区控件。`,"settings.languageSimplifiedChinese":`简体中文`,"settings.languageStoredLocally":`此偏好仅保存在当前设备。`,"settings.languageTabDescription":`当前设备的界面语言`,"settings.larkTabDescription":`App、群聊和 Goal Topic 连接`,"settings.machineTabDescription":`本机各 Capability 共享的 typed defaults`,"settings.notifications":`通知`,"settings.open":`设置`,"settings.themeDefault":`纸张`,"settings.themeDefaultDescription":`安静、轻量,适合长期查看。`,"settings.themeDescription":`选择工作区的视觉风格。设置会保存在当前浏览器本地。`,"settings.themeHighContrast":`高对比`,"settings.themeHighContrastDescription":`更强边框和更醒目的状态块。`,"settings.themeLoopx":`LoopX 标准`,"settings.themeLoopxDescription":`精确的黑白界面、Geist 字体与安静的细线结构。`,"settings.title":`设置`,"settings.workspaceDisplay":`工作区显示`,"settings.workspaceTheme":`工作区主题`,"session.closeRecord":`退出运行记录`,"session.details":`Session 详情`,"session.record":`执行 Session · 运行记录`,"session.recordDescription":`当前时间线已切换到这次 Session 的消息与 Turn 记录。`,"sidebar.createGoal":`创建 Goal`,"sidebar.delete":`删除`,"sidebar.deleteGoal":`删除 Goal`,"sidebar.manager":`LoopX 管家`,"sidebar.notifications":`设置`,"sidebar.owner":`个人工作区`,"sidebar.product":`个人 Agent 工作区`,"sidebar.resume":`恢复`,"sidebar.resumeGoal":`恢复 Goal`,"sidebar.stop":`停止`,"tasks.historyLoading":`正在加载历史…`,"tasks.historyError":`历史加载失败,已显示的内容仍可查看。`,"tasks.historyExpired":`历史快照已过期,重新加载后可继续查看。`,"tasks.historyRetry":`重新加载`,"tasks.historyEnd":`已显示全部完成记录`,"tasks.historyMore":`加载更多`,"tasks.historyLocalOnly":`请打开这台机器的 Dashboard 查看完整历史。`,"sidebar.sortGoals":`调整 Goal 顺序`,"sidebar.dragGoal":`拖拽调整顺序,或使用列表排序按钮`,"sidebar.moveUp":`上移 {goal}`,"sidebar.moveDown":`下移 {goal}`,"sidebar.goalMoved":`{goal} 已移至第 {position} 位`,"sidebar.orderNotSaved":`顺序已在本次页面生效;浏览器存储不可用,无法保存。`,"sidebar.stopGoal":`停止 Goal`,"sidebar.stopped":`已停止`,"sidebar.stoppedLoading":`正在加载已停止 Goal`,"sidebar.stoppedLoadFailed":`已停止 Goal 加载失败,其他 Goal 仍可使用。`,"sidebar.retryStopped":`重试`,"state.completed":`已完成`,"state.needsRepair":`需修复`,"state.needsYou":`等你`,"state.quiet":`安静运行`,"state.running":`推进中`,"state.stopped":`已停止`,"state.waiting":`等待条件`,"tasks.blocked":`受阻`,"tasks.agentLane":`工作 Agent`,"tasks.agentLaneDescription":`筛选这个 Goal 下的工作泳道`,"tasks.agentLaneFilter":`按工作 Agent 筛选`,"tasks.allAgentLanes":`全部 Agent({count})`,"tasks.chatAgentReplied":`Agent 已回复`,"tasks.chatPending":`已发送给 Agent`,"tasks.chatPendingDescription":`正在处理;只有经过确认的任务操作才会更新 Tasks。`,"tasks.chatRecent":`最近对话`,"tasks.chatUnchangedDescription":`本次对话没有直接修改 Tasks。需要执行时,可先转成 Task 草稿并确认。`,"tasks.chatViewReply":`查看回复`,"tasks.convertToTask":`转为 Task`,"tasks.completed":`已完成`,"runs.discoveryPartial":`部分执行详情暂不可用,正在重连;任务摘要不代表实时执行状态。`,"runs.discoveryOffline":`执行服务暂不可用,正在重连;保留的任务摘要可能已过时。`,"files.openConversation":`前往会话`,"files.exportSummary":`导出摘要`,"tasks.viewDescription":`先处理待确认,再查看工作与完成记录`,"tasks.viewLabel":`任务视图`,"tasks.listView":`列表`,"tasks.boardView":`看板`,"tasks.completedSummary":`已完成 {count} 项,近期完成明细由控制面按需投影。`,"tasks.emptyCompleted":`还没有完成的任务。`,"tasks.emptyConfirm":`没有待确认的任务。`,"tasks.emptyRunning":`没有待执行或进行中的任务。`,"tasks.emptySchedules":`没有定时任务。`,"tasks.emptyGoal":`这个 Goal 还没有任务。用下面的输入框描述下一步,LoopX 会先展示待确认操作。`,"tasks.markComplete":`标记完成:{name}`,"tasks.moreActions":`更多操作:{name}`,"tasks.openExecution":`查看执行过程:{name}`,"tasks.pending":`待处理`,"tasks.pendingAndRunning":`待执行 / 进行中`,"tasks.scheduled":`定时与持续`,"tasks.sessionError":`Session 异常`,"tasks.waiting":`待执行`,"tasks.waitingAge":`已等待 {age}`,"tasks.viewExecution":`查看执行过程`,"tasks.viewResult":`查看结果`,"time.days":`{count} 天`,"time.hours":`{count} 小时`,"timeline.emptyGoal":`这个 Goal 还没有新动态`,"timeline.emptyGoalDescription":`你可以直接询问进度或下发新的纠偏信息。`,"timeline.emptyWorkspace":`今天的工作区很安静`,"timeline.emptyWorkspaceDescription":`向 LoopX 管家描述一个 Goal,或询问今天最值得关注的事情。`,"timeline.gateHistory":`{count} 项历史 Gate`,"timeline.pending":`正在整理…`,"timeline.runCompleted":`{run}:已完成`,"timeline.review":`查看处理方式`,"timeline.reviewAndConfirm":`查看并确认`,"timeline.waitingConfirmation":`待你确认`}};function Gi(e,t){return t?Object.entries(t).reduce((e,[t,n])=>e.replaceAll(`{${t}}`,String(n)),e):e}function Ki(){try{return window.localStorage.getItem(`loopx-pw-locale`)===`en`?`en`:`zh-CN`}catch{return`zh-CN`}}function qi({children:e}){let[t,n]=(0,z.useState)(Ki);function r(e){n(e);try{window.localStorage.setItem(Ui,e)}catch{}}(0,z.useEffect)(()=>{document.documentElement.lang=t},[t]);let i=(0,z.useMemo)(()=>({locale:t,setLocale:r,t:(e,n)=>Gi(Wi[t][e],n)}),[t]);return(0,B.jsx)(Hi.Provider,{value:i,children:e})}function Ji(){let e=(0,z.useContext)(Hi);if(!e)throw Error(`useWorkspaceI18n must be used within WorkspaceI18nProvider`);return e}function Yi(e,t){let n={安静运行:`state.quiet`,等你:`state.needsYou`,等待条件:`state.waiting`,推进中:`state.running`,需修复:`state.needsRepair`,已完成:`state.completed`,已停止:`state.stopped`}[e];return n?Wi[t][n]:e}function Xi(e,t){let n={busy:`runs.running`,completed:`runs.completed`,failed:`runs.failed`,queued:`runs.queued`,ready:`runs.ready`,resume_failed:`runs.resumeFailed`,running:`runs.running`,waiting:`runs.waiting`};return e?n[e]?t(n[e]):e:t(`runs.unknown`)}function Zi(e,t){if(!e)return null;let n=new Date(e).getTime();if(Number.isNaN(n))return null;let r=Date.now()-n;if(r<36e5)return null;let i=Math.floor(r/864e5);return i>=1?t(`time.days`,{count:i}):t(`time.hours`,{count:Math.floor(r/36e5)})}var Qi;function H(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;en?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var $i=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},ea=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Qi=globalThis).__zod_globalConfig??(Qi.__zod_globalConfig={});var ta=globalThis.__zod_globalConfig;function na(e){return e&&Object.assign(ta,e),ta}function ra(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function ia(e,t){return typeof t==`bigint`?t.toString():t}function aa(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function oa(e){return e==null}function sa(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function ca(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r){};function ga(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var _a=aa(()=>{if(ta.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function va(e){if(ga(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return ga(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function ya(e){return va(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var ba=new Set([`string`,`number`,`symbol`]);function xa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Sa(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function U(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Ca(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var wa={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ta(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Sa(e,fa(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return da(this,`shape`,e),e},checks:[]}))}function Ea(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Sa(e,fa(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return da(this,`shape`,r),r},checks:[]}))}function Da(e,t){if(!va(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Sa(e,fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return da(this,`shape`,n),n}}))}function Oa(e,t){if(!va(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Sa(e,fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return da(this,`shape`,n),n}}))}function ka(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Sa(e,fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return da(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function Aa(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return Sa(t,fa(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return da(this,`shape`,i),i},checks:[]}))}function ja(e,t,n){return Sa(t,fa(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return da(this,`shape`,i),i}}))}function Ma(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Fa(e){return typeof e==`string`?e:e?.message}function Ia(e,t,n){let r=e.message?e.message:Fa(e.inst?._zod.def?.error?.(e))??Fa(t?.error?.(e))??Fa(n.customError?.(e))??Fa(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function La(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Ra(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var za=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ia,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ba=H(`$ZodError`,za),Va=H(`$ZodError`,za,{Parent:Error});function Ha(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ua(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new $i;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Ia(e,a,na())));throw ha(t,i?.callee),t}return o.value},Ga=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Ia(e,a,na())));throw ha(t,i?.callee),t}return o.value},Ka=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new $i;return a.issues.length?{success:!1,error:new(e??Ba)(a.issues.map(e=>Ia(e,i,na())))}:{success:!0,data:a.value}},qa=Ka(Va),Ja=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>Ia(e,i,na())))}:{success:!0,data:a.value}},Ya=Ja(Va),Xa=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Wa(e)(t,n,i)},Za=e=>(t,n,r)=>Wa(e)(t,n,r),Qa=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ga(e)(t,n,i)},$a=e=>async(t,n,r)=>Ga(e)(t,n,r),eo=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ka(e)(t,n,i)},to=e=>(t,n,r)=>Ka(e)(t,n,r),no=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ja(e)(t,n,i)},ro=e=>async(t,n,r)=>Ja(e)(t,n,r),io=/^[cC][0-9a-z]{6,}$/,ao=/^[0-9a-z]+$/,oo=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,so=/^[0-9a-vA-V]{20}$/,co=/^[A-Za-z0-9]{27}$/,lo=/^[a-zA-Z0-9_-]{21}$/,uo=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,fo=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,po=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,mo=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ho=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function go(){return new RegExp(ho,`u`)}var _o=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,vo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,yo=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,bo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xo=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,So=/^[A-Za-z0-9_-]*$/,Co=/^https?$/,wo=/^\+[1-9]\d{6,14}$/,To=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,Eo=RegExp(`^${To}$`);function Do(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Oo(e){return RegExp(`^${Do(e)}$`)}function ko(e){let t=Do({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${To}T(?:${r})$`)}var Ao=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},jo=/^-?\d+$/,Mo=/^-?\d+(?:\.\d+)?$/,No=/^(?:true|false)$/i,Po=/^null$/i,Fo=/^[^A-Z]*$/,Io=/^[^a-z]*$/,Lo=H(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ro={number:`number`,bigint:`bigint`,object:`date`},zo=H(`$ZodCheckLessThan`,(e,t)=>{Lo.init(e,t);let n=Ro[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value{(t.inclusive?r.value<=t.value:r.value{Lo.init(e,t);let n=Ro[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Vo=H(`$ZodCheckMultipleOf`,(e,t)=>{Lo.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):ca(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Ho=H(`$ZodCheckNumberFormat`,(e,t)=>{Lo.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=wa[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=jo)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}sa&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Uo=H(`$ZodCheckMaxLength`,(e,t)=>{var n;Lo.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!oa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum{let r=n.value;if(r.length<=t.maximum)return;let i=La(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Wo=H(`$ZodCheckMinLength`,(e,t)=>{var n;Lo.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!oa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=La(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Go=H(`$ZodCheckLengthEquals`,(e,t)=>{var n;Lo.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!oa(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=La(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ko=H(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Lo.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),qo=H(`$ZodCheckRegex`,(e,t)=>{Ko.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Jo=H(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Fo,Ko.init(e,t)}),Yo=H(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Io,Ko.init(e,t)}),Xo=H(`$ZodCheckIncludes`,(e,t)=>{Lo.init(e,t);let n=xa(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Zo=H(`$ZodCheckStartsWith`,(e,t)=>{Lo.init(e,t);let n=RegExp(`^${xa(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Qo=H(`$ZodCheckEndsWith`,(e,t)=>{Lo.init(e,t);let n=RegExp(`.*${xa(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),$o=H(`$ZodCheckOverwrite`,(e,t)=>{Lo.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),es=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(` `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(` `))}},ts={major:4,minor:4,patch:3},ns=H(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ts;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=Ma(e),i;for(let a of t){if(a._zod.def.when){if(Na(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new $i;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=Ma(e,t))});else{if(e.issues.length===t)continue;r||=Ma(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(Ma(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new $i;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new $i;return o.then(e=>t(e,r,a))}return t(o,r,a)}}ua(e,`~standard`,()=>({validate:t=>{try{let n=qa(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Ya(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),rs=H(`$ZodString`,(e,t)=>{ns.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ao(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),is=H(`$ZodStringFormat`,(e,t)=>{Ko.init(e,t),rs.init(e,t)}),as=H(`$ZodGUID`,(e,t)=>{t.pattern??=fo,is.init(e,t)}),os=H(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=po(e)}else t.pattern??=po();is.init(e,t)}),ss=H(`$ZodEmail`,(e,t)=>{t.pattern??=mo,is.init(e,t)}),cs=H(`$ZodURL`,(e,t)=>{is.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===Co.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),n.value=t.normalize?i.href:r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),ls=H(`$ZodEmoji`,(e,t)=>{t.pattern??=go(),is.init(e,t)}),us=H(`$ZodNanoID`,(e,t)=>{t.pattern??=lo,is.init(e,t)}),ds=H(`$ZodCUID`,(e,t)=>{t.pattern??=io,is.init(e,t)}),fs=H(`$ZodCUID2`,(e,t)=>{t.pattern??=ao,is.init(e,t)}),ps=H(`$ZodULID`,(e,t)=>{t.pattern??=oo,is.init(e,t)}),ms=H(`$ZodXID`,(e,t)=>{t.pattern??=so,is.init(e,t)}),hs=H(`$ZodKSUID`,(e,t)=>{t.pattern??=co,is.init(e,t)}),gs=H(`$ZodISODateTime`,(e,t)=>{t.pattern??=ko(t),is.init(e,t)}),_s=H(`$ZodISODate`,(e,t)=>{t.pattern??=Eo,is.init(e,t)}),vs=H(`$ZodISOTime`,(e,t)=>{t.pattern??=Oo(t),is.init(e,t)}),ys=H(`$ZodISODuration`,(e,t)=>{t.pattern??=uo,is.init(e,t)}),bs=H(`$ZodIPv4`,(e,t)=>{t.pattern??=_o,is.init(e,t),e._zod.bag.format=`ipv4`}),xs=H(`$ZodIPv6`,(e,t)=>{t.pattern??=vo,is.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),Ss=H(`$ZodCIDRv4`,(e,t)=>{t.pattern??=yo,is.init(e,t)}),Cs=H(`$ZodCIDRv6`,(e,t)=>{t.pattern??=bo,is.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function ws(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Ts=H(`$ZodBase64`,(e,t)=>{t.pattern??=xo,is.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{ws(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Es(e){if(!So.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return ws(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var Ds=H(`$ZodBase64URL`,(e,t)=>{t.pattern??=So,is.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Es(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Os=H(`$ZodE164`,(e,t)=>{t.pattern??=wo,is.init(e,t)});function ks(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var As=H(`$ZodJWT`,(e,t)=>{is.init(e,t),e._zod.check=n=>{ks(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),js=H(`$ZodNumber`,(e,t)=>{ns.init(e,t),e._zod.pattern=e._zod.bag.pattern??Mo,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Ms=H(`$ZodNumberFormat`,(e,t)=>{Ho.init(e,t),js.init(e,t)}),Ns=H(`$ZodBoolean`,(e,t)=>{ns.init(e,t),e._zod.pattern=No,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Ps=H(`$ZodNull`,(e,t)=>{ns.init(e,t),e._zod.pattern=Po,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),Fs=H(`$ZodUnknown`,(e,t)=>{ns.init(e,t),e._zod.parse=e=>e}),Is=H(`$ZodNever`,(e,t)=>{ns.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Ls(e,t,n){e.issues.length&&t.issues.push(...Pa(n,e.issues)),t.value[n]=e.value}var Rs=H(`$ZodArray`,(e,t)=>{ns.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;eLs(t,n,e))):Ls(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function zs(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...Pa(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function Bs(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Ca(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Vs(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>zs(e,n,i,t,u,d))):zs(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var Hs=H(`$ZodObject`,(e,t)=>{if(ns.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=aa(()=>Bs(t));ua(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=ga,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>zs(n,t,e,s,r,i))):zs(a,t,e,s,r,i)}return i?Vs(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Us=H(`$ZodObjectJIT`,(e,t)=>{Hs.init(e,t);let n=e._zod.parse,r=aa(()=>Bs(t)),i=e=>{let t=new es([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=pa(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=pa(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(` if (${n}.issues.length) { @@ -107,7 +107,7 @@ Goal: `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=ga,s=!ta.jitless,c=s&&_a.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?Vs([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function Ws(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Ma(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Ia(e,r,na())))}),t)}var Gs=H(`$ZodUnion`,(e,t)=>{ns.init(e,t),ua(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),ua(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),ua(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),ua(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>sa(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Ws(t,r,e,i)):Ws(o,r,e,i)}}),Ks=H(`$ZodIntersection`,(e,t)=>{ns.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Js(e,t,n)):Js(e,i,a)}});function qs(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(va(e)&&va(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=qs(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;re.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),Ma(e))return e;let o=qs(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var Ys=H(`$ZodTuple`,(e,t)=>{ns.init(e,t);let n=t.items;e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({input:a,inst:e,expected:`tuple`,code:`invalid_type`}),r;r.value=[];let o=[],s=Xs(n,`optin`),c=Xs(n,`optout`);if(!t.rest){if(a.lengthn.length&&r.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:a,inst:e,origin:`array`})}let l=Array(n.length);for(let e=0;e{l[e]=t})):l[e]=t}if(t.rest){let e=n.length-1,s=a.slice(n.length);for(let n of s){e++;let a=t.rest._zod.run({value:n,issues:[]},i);a instanceof Promise?o.push(a.then(t=>Zs(t,r,e))):Zs(a,r,e)}}return o.length?Promise.all(o).then(()=>Qs(l,r,n,a,c)):Qs(l,r,n,a,c)}});function Xs(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!==`optional`)return n+1;return 0}function Zs(e,t,n){e.issues.length&&t.issues.push(...Pa(n,e.issues)),t.value[n]=e.value}function Qs(e,t,n,r,i){for(let a=0;a=i){t.value.length=a;break}t.issues.push(...Pa(a,n.issues))}t.value[a]=n.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}var $s=H(`$ZodRecord`,(e,t)=>{ns.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!va(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>Ia(e,r,na())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...Pa(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...Pa(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&Mo.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Ia(e,r,na())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...Pa(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...Pa(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),ec=H(`$ZodEnum`,(e,t)=>{ns.init(e,t);let n=ra(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>ba.has(typeof e)).map(e=>typeof e==`string`?xa(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),tc=H(`$ZodLiteral`,(e,t)=>{if(ns.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?xa(e):e?xa(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),nc=H(`$ZodTransform`,(e,t)=>{ns.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new ea(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new $i;return n.value=i,n.fallback=!0,n}});function rc(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var ic=H(`$ZodOptional`,(e,t)=>{ns.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,ua(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ua(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${sa(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>rc(e,r)):rc(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),ac=H(`$ZodExactOptional`,(e,t)=>{ic.init(e,t),ua(e._zod,`values`,()=>t.innerType._zod.values),ua(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),oc=H(`$ZodNullable`,(e,t)=>{ns.init(e,t),ua(e._zod,`optin`,()=>t.innerType._zod.optin),ua(e._zod,`optout`,()=>t.innerType._zod.optout),ua(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${sa(e.source)}|null)$`):void 0}),ua(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),sc=H(`$ZodDefault`,(e,t)=>{ns.init(e,t),e._zod.optin=`optional`,ua(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>cc(e,t)):cc(r,t)}});function cc(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var lc=H(`$ZodPrefault`,(e,t)=>{ns.init(e,t),e._zod.optin=`optional`,ua(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),uc=H(`$ZodNonOptional`,(e,t)=>{ns.init(e,t),ua(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>dc(t,e)):dc(i,e)}});function dc(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var fc=H(`$ZodCatch`,(e,t)=>{ns.init(e,t),e._zod.optin=`optional`,ua(e._zod,`optout`,()=>t.innerType._zod.optout),ua(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Ia(e,n,na()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Ia(e,n,na()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),pc=H(`$ZodPipe`,(e,t)=>{ns.init(e,t),ua(e._zod,`values`,()=>t.in._zod.values),ua(e._zod,`optin`,()=>t.in._zod.optin),ua(e._zod,`optout`,()=>t.out._zod.optout),ua(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>mc(e,t.in,n)):mc(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>mc(e,t.out,n)):mc(r,t.out,n)}});function mc(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var hc=H(`$ZodReadonly`,(e,t)=>{ns.init(e,t),ua(e._zod,`propValues`,()=>t.innerType._zod.propValues),ua(e._zod,`values`,()=>t.innerType._zod.values),ua(e._zod,`optin`,()=>t.innerType?._zod?.optin),ua(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(gc):gc(r)}});function gc(e){return e.value=Object.freeze(e.value),e}var _c=H(`$ZodCustom`,(e,t)=>{Lo.init(e,t),ns.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>vc(t,n,r,e));vc(i,n,r,e)}});function vc(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Ra(e))}}var yc,bc=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function xc(){return new bc}(yc=globalThis).__zod_globalRegistry??(yc.__zod_globalRegistry=xc());var Sc=globalThis.__zod_globalRegistry;function Cc(e,t){return new e({type:`string`,...U(t)})}function wc(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...U(t)})}function Tc(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...U(t)})}function Ec(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...U(t)})}function Dc(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...U(t)})}function Oc(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...U(t)})}function kc(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...U(t)})}function Ac(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...U(t)})}function jc(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...U(t)})}function Mc(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...U(t)})}function Nc(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...U(t)})}function Pc(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...U(t)})}function Fc(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...U(t)})}function Ic(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...U(t)})}function Lc(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...U(t)})}function Rc(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...U(t)})}function zc(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...U(t)})}function Bc(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...U(t)})}function Vc(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...U(t)})}function Hc(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...U(t)})}function Uc(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...U(t)})}function Wc(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...U(t)})}function Gc(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...U(t)})}function Kc(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...U(t)})}function qc(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...U(t)})}function Jc(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...U(t)})}function Yc(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...U(t)})}function Xc(e,t){return new e({type:`number`,checks:[],...U(t)})}function Zc(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...U(t)})}function Qc(e,t){return new e({type:`boolean`,...U(t)})}function $c(e,t){return new e({type:`null`,...U(t)})}function el(e){return new e({type:`unknown`})}function tl(e,t){return new e({type:`never`,...U(t)})}function nl(e,t){return new zo({check:`less_than`,...U(t),value:e,inclusive:!1})}function rl(e,t){return new zo({check:`less_than`,...U(t),value:e,inclusive:!0})}function il(e,t){return new Bo({check:`greater_than`,...U(t),value:e,inclusive:!1})}function al(e,t){return new Bo({check:`greater_than`,...U(t),value:e,inclusive:!0})}function ol(e,t){return new Vo({check:`multiple_of`,...U(t),value:e})}function sl(e,t){return new Uo({check:`max_length`,...U(t),maximum:e})}function cl(e,t){return new Wo({check:`min_length`,...U(t),minimum:e})}function ll(e,t){return new Go({check:`length_equals`,...U(t),length:e})}function ul(e,t){return new qo({check:`string_format`,format:`regex`,...U(t),pattern:e})}function dl(e){return new Jo({check:`string_format`,format:`lowercase`,...U(e)})}function fl(e){return new Yo({check:`string_format`,format:`uppercase`,...U(e)})}function pl(e,t){return new Xo({check:`string_format`,format:`includes`,...U(t),includes:e})}function ml(e,t){return new Zo({check:`string_format`,format:`starts_with`,...U(t),prefix:e})}function hl(e,t){return new Qo({check:`string_format`,format:`ends_with`,...U(t),suffix:e})}function gl(e){return new $o({check:`overwrite`,tx:e})}function _l(e){return gl(t=>t.normalize(e))}function vl(){return gl(e=>e.trim())}function yl(){return gl(e=>e.toLowerCase())}function bl(){return gl(e=>e.toUpperCase())}function xl(){return gl(e=>ma(e))}function Sl(e,t,n){return new e({type:`array`,element:t,...U(n)})}function Cl(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...U(n)})}function wl(e,t){let n=Tl(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Ra(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Ra(r))}},e(t.value,t)),t);return n}function Tl(e,t){let n=new Lo({check:`custom`,...U(t)});return n._zod.check=e,n}function El(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Sc,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function Dl(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,Dl(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&Al(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Ol(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/ -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function kl(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Ml(t,`input`,e.processors),output:Ml(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function Al(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return Al(r.element,n);if(r.type===`set`)return Al(r.valueType,n);if(r.type===`lazy`)return Al(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return Al(r.innerType,n);if(r.type===`intersection`)return Al(r.left,n)||Al(r.right,n);if(r.type===`record`||r.type===`map`)return Al(r.keyType,n)||Al(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:Al(r.in,n)||Al(r.out,n);if(r.type===`object`){for(let e in r.shape)if(Al(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(Al(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(Al(e,n))return!0;return!!(r.rest&&Al(r.rest,n))}return!1}var jl=(e,t={})=>n=>{let r=El({...n,processors:t});return Dl(e,r),Ol(r,e),kl(r,e)},Ml=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=El({...i??{},target:a,io:t,processors:n});return Dl(e,o),Ol(o,e),kl(o,e)},Nl={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Pl=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Nl[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Fl=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},Il=(e,t,n,r)=>{n.type=`boolean`},Ll=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Rl=(e,t,n,r)=>{n.not={}},zl=(e,t,n,r)=>{let i=e._zod.def,a=ra(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Bl=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Vl=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Hl=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Ul=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=Dl(a.element,t,{...r,path:[...r.path,`items`]})},Wl=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=Dl(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Dl(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Gl=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>Dl(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Kl=(e,t,n,r)=>{let i=e._zod.def,a=Dl(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=Dl(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},ql=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>Dl(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?Dl(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},Jl=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=Dl(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=Dl(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=Dl(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},Yl=(e,t,n,r)=>{let i=e._zod.def,a=Dl(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Xl=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Zl=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Ql=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},$l=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},eu=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;Dl(o,t,r);let s=t.seen.get(e);s.ref=o},tu=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},nu=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ru=H(`ZodISODateTime`,(e,t)=>{gs.init(e,t),ju.init(e,t)});function iu(e){return Kc(ru,e)}var au=H(`ZodISODate`,(e,t)=>{_s.init(e,t),ju.init(e,t)});function ou(e){return qc(au,e)}var su=H(`ZodISOTime`,(e,t)=>{vs.init(e,t),ju.init(e,t)});function cu(e){return Jc(su,e)}var lu=H(`ZodISODuration`,(e,t)=>{ys.init(e,t),ju.init(e,t)});function uu(e){return Yc(lu,e)}var du=(e,t)=>{Ba.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Ua(e,t)},flatten:{value:t=>Ha(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,ia,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,ia,2)}},isEmpty:{get(){return e.issues.length===0}}})},fu=H(`ZodError`,du),pu=H(`ZodError`,du,{Parent:Error}),mu=Wa(pu),hu=Ga(pu),gu=Ka(pu),_u=Ja(pu),vu=Xa(pu),yu=Za(pu),bu=Qa(pu),xu=$a(pu),Su=eo(pu),Cu=to(pu),wu=no(pu),Tu=ro(pu),Eu=new WeakMap;function Du(e,t,n){let r=Object.getPrototypeOf(e),i=Eu.get(r);if(i||(i=new Set,Eu.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var Ou=H(`ZodType`,(e,t)=>(ns.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Ml(e,`input`),output:Ml(e,`output`)}}),e.toJSONSchema=jl(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>mu(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>gu(e,t,n),e.parseAsync=async(t,n)=>hu(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>_u(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>vu(e,t,n),e.decode=(t,n)=>yu(e,t,n),e.encodeAsync=async(t,n)=>bu(e,t,n),e.decodeAsync=async(t,n)=>xu(e,t,n),e.safeEncode=(t,n)=>Su(e,t,n),e.safeDecode=(t,n)=>Cu(e,t,n),e.safeEncodeAsync=async(t,n)=>wu(e,t,n),e.safeDecodeAsync=async(t,n)=>Tu(e,t,n),Du(e,`ZodType`,{check(...e){let t=this.def;return this.clone(fa(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Sa(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Bd(e,t))},superRefine(e,t){return this.check(Vd(e,t))},overwrite(e){return this.check(gl(e))},optional(){return Sd(this)},exactOptional(){return wd(this)},nullable(){return Ed(this)},nullish(){return Sd(Ed(this))},nonoptional(e){return Md(this,e)},array(){return q(this)},or(e){return ud([this,e])},and(e){return fd(this,e)},transform(e){return Id(this,bd(e))},default(e){return Od(this,e)},prefault(e){return Ad(this,e)},catch(e){return Pd(this,e)},pipe(e){return Id(this,e)},readonly(){return Rd(this)},describe(e){let t=this.clone();return Sc.add(t,{description:e}),t},meta(...e){if(e.length===0)return Sc.get(this);let t=this.clone();return Sc.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return Sc.get(e)?.description},configurable:!0}),e)),ku=H(`_ZodString`,(e,t)=>{rs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pl(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Du(e,`_ZodString`,{regex(...e){return this.check(ul(...e))},includes(...e){return this.check(pl(...e))},startsWith(...e){return this.check(ml(...e))},endsWith(...e){return this.check(hl(...e))},min(...e){return this.check(cl(...e))},max(...e){return this.check(sl(...e))},length(...e){return this.check(ll(...e))},nonempty(...e){return this.check(cl(1,...e))},lowercase(e){return this.check(dl(e))},uppercase(e){return this.check(fl(e))},trim(){return this.check(vl())},normalize(...e){return this.check(_l(...e))},toLowerCase(){return this.check(yl())},toUpperCase(){return this.check(bl())},slugify(){return this.check(xl())}})}),Au=H(`ZodString`,(e,t)=>{rs.init(e,t),ku.init(e,t),e.email=t=>e.check(wc(Mu,t)),e.url=t=>e.check(Ac(Fu,t)),e.jwt=t=>e.check(Gc(Xu,t)),e.emoji=t=>e.check(jc(Iu,t)),e.guid=t=>e.check(Tc(Nu,t)),e.uuid=t=>e.check(Ec(Pu,t)),e.uuidv4=t=>e.check(Dc(Pu,t)),e.uuidv6=t=>e.check(Oc(Pu,t)),e.uuidv7=t=>e.check(kc(Pu,t)),e.nanoid=t=>e.check(Mc(Lu,t)),e.guid=t=>e.check(Tc(Nu,t)),e.cuid=t=>e.check(Nc(Ru,t)),e.cuid2=t=>e.check(Pc(zu,t)),e.ulid=t=>e.check(Fc(Bu,t)),e.base64=t=>e.check(Hc(qu,t)),e.base64url=t=>e.check(Uc(Ju,t)),e.xid=t=>e.check(Ic(Vu,t)),e.ksuid=t=>e.check(Lc(Hu,t)),e.ipv4=t=>e.check(Rc(Uu,t)),e.ipv6=t=>e.check(zc(Wu,t)),e.cidrv4=t=>e.check(Bc(Gu,t)),e.cidrv6=t=>e.check(Vc(Ku,t)),e.e164=t=>e.check(Wc(Yu,t)),e.datetime=t=>e.check(iu(t)),e.date=t=>e.check(ou(t)),e.time=t=>e.check(cu(t)),e.duration=t=>e.check(uu(t))});function W(e){return Cc(Au,e)}var ju=H(`ZodStringFormat`,(e,t)=>{is.init(e,t),ku.init(e,t)}),Mu=H(`ZodEmail`,(e,t)=>{ss.init(e,t),ju.init(e,t)}),Nu=H(`ZodGUID`,(e,t)=>{as.init(e,t),ju.init(e,t)}),Pu=H(`ZodUUID`,(e,t)=>{os.init(e,t),ju.init(e,t)}),Fu=H(`ZodURL`,(e,t)=>{cs.init(e,t),ju.init(e,t)}),Iu=H(`ZodEmoji`,(e,t)=>{ls.init(e,t),ju.init(e,t)}),Lu=H(`ZodNanoID`,(e,t)=>{us.init(e,t),ju.init(e,t)}),Ru=H(`ZodCUID`,(e,t)=>{ds.init(e,t),ju.init(e,t)}),zu=H(`ZodCUID2`,(e,t)=>{fs.init(e,t),ju.init(e,t)}),Bu=H(`ZodULID`,(e,t)=>{ps.init(e,t),ju.init(e,t)}),Vu=H(`ZodXID`,(e,t)=>{ms.init(e,t),ju.init(e,t)}),Hu=H(`ZodKSUID`,(e,t)=>{hs.init(e,t),ju.init(e,t)}),Uu=H(`ZodIPv4`,(e,t)=>{bs.init(e,t),ju.init(e,t)}),Wu=H(`ZodIPv6`,(e,t)=>{xs.init(e,t),ju.init(e,t)}),Gu=H(`ZodCIDRv4`,(e,t)=>{Ss.init(e,t),ju.init(e,t)}),Ku=H(`ZodCIDRv6`,(e,t)=>{Cs.init(e,t),ju.init(e,t)}),qu=H(`ZodBase64`,(e,t)=>{Ts.init(e,t),ju.init(e,t)}),Ju=H(`ZodBase64URL`,(e,t)=>{Ds.init(e,t),ju.init(e,t)}),Yu=H(`ZodE164`,(e,t)=>{Os.init(e,t),ju.init(e,t)}),Xu=H(`ZodJWT`,(e,t)=>{As.init(e,t),ju.init(e,t)}),Zu=H(`ZodNumber`,(e,t)=>{js.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fl(e,t,n,r),Du(e,`ZodNumber`,{gt(e,t){return this.check(il(e,t))},gte(e,t){return this.check(al(e,t))},min(e,t){return this.check(al(e,t))},lt(e,t){return this.check(nl(e,t))},lte(e,t){return this.check(rl(e,t))},max(e,t){return this.check(rl(e,t))},int(e){return this.check($u(e))},safe(e){return this.check($u(e))},positive(e){return this.check(il(0,e))},nonnegative(e){return this.check(al(0,e))},negative(e){return this.check(nl(0,e))},nonpositive(e){return this.check(rl(0,e))},multipleOf(e,t){return this.check(ol(e,t))},step(e,t){return this.check(ol(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function G(e){return Xc(Zu,e)}var Qu=H(`ZodNumberFormat`,(e,t)=>{Ms.init(e,t),Zu.init(e,t)});function $u(e){return Zc(Qu,e)}var ed=H(`ZodBoolean`,(e,t)=>{Ns.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Il(e,t,n,r)});function K(e){return Qc(ed,e)}var td=H(`ZodNull`,(e,t)=>{Ps.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ll(e,t,n,r)});function nd(e){return $c(td,e)}var rd=H(`ZodUnknown`,(e,t)=>{Fs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function id(){return el(rd)}var ad=H(`ZodNever`,(e,t)=>{Is.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rl(e,t,n,r)});function od(e){return tl(ad,e)}var sd=H(`ZodArray`,(e,t)=>{Rs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ul(e,t,n,r),e.element=t.element,Du(e,`ZodArray`,{min(e,t){return this.check(cl(e,t))},nonempty(e){return this.check(cl(1,e))},max(e,t){return this.check(sl(e,t))},length(e,t){return this.check(ll(e,t))},unwrap(){return this.element}})});function q(e,t){return Sl(sd,e,t)}var cd=H(`ZodObject`,(e,t)=>{Us.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wl(e,t,n,r),ua(e,`shape`,()=>t.shape),Du(e,`ZodObject`,{keyof(){return Y(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:id()})},loose(){return this.clone({...this._zod.def,catchall:id()})},strict(){return this.clone({...this._zod.def,catchall:od()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Da(this,e)},safeExtend(e){return Oa(this,e)},merge(e){return ka(this,e)},pick(e){return Ta(this,e)},omit(e){return Ea(this,e)},partial(...e){return Aa(xd,this,e[0])},required(...e){return ja(jd,this,e[0])}})});function J(e,t){return new cd({type:`object`,shape:e??{},...U(t)})}var ld=H(`ZodUnion`,(e,t)=>{Gs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gl(e,t,n,r),e.options=t.options});function ud(e,t){return new ld({type:`union`,options:e,...U(t)})}var dd=H(`ZodIntersection`,(e,t)=>{Ks.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kl(e,t,n,r)});function fd(e,t){return new dd({type:`intersection`,left:e,right:t})}var pd=H(`ZodTuple`,(e,t)=>{Ys.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ql(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function md(e,t,n){let r=t instanceof ns;return new pd({type:`tuple`,items:e,rest:r?t:null,...U(r?n:t)})}var hd=H(`ZodRecord`,(e,t)=>{$s.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jl(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function gd(e,t,n){return!t||!t._zod?new hd({type:`record`,keyType:W(),valueType:e,...U(t)}):new hd({type:`record`,keyType:e,valueType:t,...U(n)})}var _d=H(`ZodEnum`,(e,t)=>{ec.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zl(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new _d({...t,checks:[],...U(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new _d({...t,checks:[],...U(r),entries:i})}});function Y(e,t){return new _d({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...U(t)})}var vd=H(`ZodLiteral`,(e,t)=>{tc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bl(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function X(e,t){return new vd({type:`literal`,values:Array.isArray(e)?e:[e],...U(t)})}var yd=H(`ZodTransform`,(e,t)=>{nc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hl(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new ea(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Ra(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Ra(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function bd(e){return new yd({type:`transform`,transform:e})}var xd=H(`ZodOptional`,(e,t)=>{ic.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Sd(e){return new xd({type:`optional`,innerType:e})}var Cd=H(`ZodExactOptional`,(e,t)=>{ac.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wd(e){return new Cd({type:`optional`,innerType:e})}var Td=H(`ZodNullable`,(e,t)=>{oc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ed(e){return new Td({type:`nullable`,innerType:e})}var Dd=H(`ZodDefault`,(e,t)=>{sc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Od(e,t){return new Dd({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ya(t)}})}var kd=H(`ZodPrefault`,(e,t)=>{lc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ql(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ad(e,t){return new kd({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ya(t)}})}var jd=H(`ZodNonOptional`,(e,t)=>{uc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Md(e,t){return new jd({type:`nonoptional`,innerType:e,...U(t)})}var Nd=H(`ZodCatch`,(e,t)=>{fc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$l(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Pd(e,t){return new Nd({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var Fd=H(`ZodPipe`,(e,t)=>{pc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>eu(e,t,n,r),e.in=t.in,e.out=t.out});function Id(e,t){return new Fd({type:`pipe`,in:e,out:t})}var Ld=H(`ZodReadonly`,(e,t)=>{hc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>tu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Rd(e){return new Ld({type:`readonly`,innerType:e})}var zd=H(`ZodCustom`,(e,t)=>{_c.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vl(e,t,n,r)});function Bd(e,t={}){return Cl(zd,e,t)}function Vd(e,t){return wl(e,t)}var Hd=e=>typeof e==`string`&&e.trim()?e.trim():null;function Ud(e){let t=e.decision_scope&&typeof e.decision_scope==`object`&&!Array.isArray(e.decision_scope)?e.decision_scope:{},n=Hd(t.kind),r=Hd(t.granularity),i=Hd(t.scope_key),a=Hd(e.superseded_by);return{interaction:e.task_class===`user_gate`?`decision`:`unknown`,lifecycle:a?`superseded`:e.status===`deferred`?`deferred`:e.done===!0||[`done`,`completed`,`closed`,`archived`].includes(String(e.status))?`closed`:e.status===`open`||e.status===`blocked`?`open`:`unknown`,reason:Hd(e.note),evidence:Hd(e.evidence),blocksAgent:Hd(e.blocks_agent),unblocksTodoId:Hd(e.unblocks_todo_id),decisionScope:n&&r&&i?{kind:n,granularity:r,scopeKey:i}:null,supersededBy:a}}function Wd(e,t,n,r){return{...e,sourceId:t,goalTitle:r??e.goalTitle,details:n?e.details:{...e.details??Ud({}),lifecycle:`unavailable`}}}function Gd(e,t){return t.find(t=>t.sourceId===e.sourceId&&t.goalId===e.goalId&&t.todoId===e.todoId)||{...e,details:{...e.details??Ud({}),lifecycle:`unavailable`}}}function Kd(e,t){let n=e.details?.supersededBy;if(!(!n||n===e.todoId||e.details?.lifecycle===`unavailable`))return t.find(t=>t.sourceId===e.sourceId&&t.goalId===e.goalId&&t.todoId===n)}function qd(e){return![`closed`,`deferred`,`superseded`,`unavailable`].includes(e.details?.lifecycle??`unknown`)}var Jd={ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,runtime_root:`$HOME/.codex/loopx`,goal_count:1,run_count:8440,status_contract:{schema_version:2,minimum_dashboard_schema_version:2,producer:`loopx status`,reload_hint:`scripts/macos-dashboard-launchagent.sh restart`},usage_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.471166+00:00`,sample_run_count:20,proxy_note:`run-history proxy; excludes token counts and raw thread logs`,totals:{runs_24h:20,runs_7d:20,quota_spend_slots_24h:11,quota_spend_slots_7d:11,automation_run_count_24h:11,automation_run_count_7d:11,progress_signal_run_count_24h:9,progress_signal_run_count_7d:9},goals:[{goal_id:`loopx-meta`,runs_24h:20,runs_7d:20,quota_spend_slots_24h:11,quota_spend_slots_7d:11,automation_run_count_24h:11,automation_run_count_7d:11,progress_signal_run_count_24h:9,progress_signal_run_count_7d:9,project_share_24h:1}]},event_ledger_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.360662+00:00`,sample_run_count:20,proxy_note:`append-only run-history projection; compact event-class counts only`,event_classes:[`accounting`,`decision`,`evidence`,`state`,`work`],totals:{events_24h:20,events_7d:20,by_class_24h:{accounting:11,decision:0,evidence:0,state:0,work:9},by_class_7d:{accounting:11,decision:0,evidence:0,state:0,work:9}},goals:[{goal_id:`loopx-meta`,events_24h:20,events_7d:20,by_class_24h:{accounting:11,decision:0,evidence:0,state:0,work:9},by_class_7d:{accounting:11,decision:0,evidence:0,state:0,work:9},latest_event_class:`accounting`,latest_event_at:`2026-07-06T14:37:32+08:00`}]},promotion_readiness_summary:{available:!0,source:`run_history_full_scan`,goal_id:`loopx-meta`,generated_at:`2026-07-05T20:02:02+08:00`,classification:`canary_promotion_readiness_smoke_group`,delivery_batch_scale:`multi_surface`,delivery_outcome:`primary_goal_outcome`,recommended_action:`Canary promotion-readiness smoke passed; promotion may proceed after doctor/status reports fresh evidence.`,json_exists:!0,markdown_exists:!0,freshness_window_hours:24,freshness_status:`fresh`,is_fresh:!0,requires_readiness_run:!1,age_seconds:67624,age_hours:18.78,freshness_reference_time:`2026-07-06T06:49:06.408527+00:00`,sample_run_count:0,proxy_note:`canary promotion-readiness projection from append-only run history; exact evidence stays in run artifacts`},promotion_gate:{ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,runtime_root:`$HOME/.codex/loopx`,gate:`promotion_readiness`,gate_state:`ready`,can_promote:!0,should_warn:!1,non_blocking:!0,recommended_action:`promotion readiness is fresh`,readiness:{available:!0,goal_id:`loopx-meta`,generated_at:`2026-07-05T20:02:02+08:00`,classification:`canary_promotion_readiness_smoke_group`,delivery_batch_scale:`multi_surface`,delivery_outcome:`primary_goal_outcome`,recommended_action:`Canary promotion-readiness smoke passed; promotion may proceed after doctor/status reports fresh evidence.`,json_exists:!0,markdown_exists:!0,runtime_root:`$HOME/.codex/loopx`,freshness_window_hours:24,freshness_status:`fresh`,is_fresh:!0,requires_readiness_run:!1,age_seconds:67624,age_hours:18.78,freshness_reference_time:`2026-07-06T06:49:06.471087+00:00`}},decision_freshness_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.471133+00:00`,sample_run_count:20,window_days:7,proxy_note:`checkpointed decision freshness projection; rebase old decisions at the decision point before reuse`,summary:{decision_count:0,stale_count:0,rebase_required_count:0,fresh_count:0},items:[]},todo_index:JSON.parse(`{"schema_version":"todo_index_v0","source":"live_loopx_status_public_slice","total_count":12,"current_projected_count":12,"rollout_event_count":94,"item_limit":12,"items":[{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo update recorded for todo_1596c3a678bb","schema_version":"todo_index_item_v0","todo_id":"todo_1596c3a678bb","role":"agent","status":"open","title":"todo update recorded for todo_1596c3a678bb","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:33:32Z","latest_event_status":"open","event_count":7,"event_kinds":["todo_update"]},{"goal_id":"loopx-meta","index":24,"done":false,"text":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","schema_version":"todo_index_item_v0","todo_id":"todo_15bc0926a494","role":"agent","status":"open","priority":"P0-REVENUE MONITOR","title":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"github_public_reply_metadata_monitor","claimed_by":"codex-value-explorer","evidence":"autonomous replan: bounded current value-explorer monitor lane with explicit expires_at.","note":"Set bounded watch expiry for metadata-only public reply monitor; no catch-up after expiry.","updated_at":"2026-07-05T06:27:15+08:00"},{"goal_id":"loopx-meta","index":17,"done":false,"text":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","schema_version":"todo_index_item_v0","todo_id":"todo_2bf560b48a0c","role":"agent","status":"open","priority":"P0","title":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"legacy_open_pr_rename_blocker","claimed_by":"codex-main-control"},{"goal_id":"loopx-meta","index":23,"done":false,"text":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","schema_version":"todo_index_item_v0","todo_id":"todo_3ed1c4a69164","role":"agent","status":"open","priority":"P0","title":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"skillsbench_local_verifier_reward_collection","claimed_by":"codex-main-control","required_capabilities":["benchmark_runner"]},{"goal_id":"loopx-meta","index":32,"done":false,"text":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","schema_version":"todo_index_item_v0","todo_id":"todo_44907a5f355d","role":"agent","status":"blocked","priority":"P0","title":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_raw_new_rerun","claimed_by":"codex-main-control","evidence":"Public-safe redacted live LoopX text; inspect local status for the full row.","note":"Do not spend a full citation-check loopx rerun yet: #865 fixed scored output paths and #874 added bootstrap preflight attribution, but citation-check itself still preflights as apt+verifier bootstrap risk on ECS.","updated_at":"2026-06-29T00:49:36+08:00"},{"goal_id":"loopx-meta","index":39,"done":false,"text":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","schema_version":"todo_index_item_v0","todo_id":"todo_4762c790e583","role":"agent","status":"blocked","priority":"P0","title":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_remote_rerun","claimed_by":"codex-main-control","evidence":"A prior benchmark adapter change was validated before the legacy surface was archived. Current research uses the RFC-linked benchmark workspace and toolkit boundary smokes.","note":"2026-06-29: fixed host-local ACP idle/no-output root cause in PR #894. ACP protocol tool_call_count=0 is now distinguished from reverse-channel task-facing bridge activity; repeated codex_exec_bridge_idle_timeout withou…","updated_at":"2026-06-29T19:40:32+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_584f55f8f3b4","schema_version":"todo_index_item_v0","todo_id":"todo_584f55f8f3b4","role":"agent","status":"open","title":"todo add recorded for todo_584f55f8f3b4","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:48:49Z","latest_event_status":"open","event_count":3,"event_kinds":["todo_add","todo_update"]},{"goal_id":"loopx-meta","index":40,"done":false,"text":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","schema_version":"todo_index_item_v0","todo_id":"todo_62debf065fec","role":"agent","status":"blocked","priority":"P0 MONITOR","title":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"monitor_skillsbench_batch","claimed_by":"codex-main-control","evidence":"Observed 2026-06-30T02:52+08: active-state target_key=skillsbench-goal-baseline-30case-20260629T1826Z-r10; local ps/tmux/recent artifact search found no r10 batch process or compact artifact; no raw task/log/trajectory …","updated_at":"2026-06-30T02:54:54+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_93bc6439c521","schema_version":"todo_index_item_v0","todo_id":"todo_93bc6439c521","role":"agent","status":"open","title":"todo add recorded for todo_93bc6439c521","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_claim","latest_event_at":"2026-07-06T06:32:52Z","latest_event_status":"open","event_count":2,"event_kinds":["todo_add","todo_claim"]},{"goal_id":"loopx-meta","index":27,"done":false,"text":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","schema_version":"todo_index_item_v0","todo_id":"todo_aad7e9716927","role":"agent","status":"blocked","priority":"P0","title":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"run_goal_start_product_mode_matrix","claimed_by":"codex-main-control","evidence":"driver.status shows DONE raw then RUN loopx-goal-start with no running driver; raw benchmark_run.compact first_blocker=skillsbench_codex_acp_provider_zero_activity; source guard requires --host-local-acp-launch for Loop…","note":"Remote run group skillsbench-raw-new-goal-start-20260627T0420Z produced a material closeout for citation-check raw only; raw compact attribution is skillsbench_codex_acp_provider_zero_activity with official score missin…","updated_at":"2026-06-27T13:05:47+08:00"},{"goal_id":"loopx-meta","index":21,"done":false,"text":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","schema_version":"todo_index_item_v0","todo_id":"todo_aec1873c7f28","role":"agent","status":"open","priority":"P0 MONITOR","title":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","claimed_by":"codex-main-control","note":"2026-06-23 projection fix: this is monitor context for the powerlifting run, not an advancement next action; current executable path is SkillsBench build cache/prewarm repair.","updated_at":"2026-06-23T10:37:43+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_c02cb7d19607","schema_version":"todo_index_item_v0","todo_id":"todo_c02cb7d19607","role":"agent","status":"open","title":"todo add recorded for todo_c02cb7d19607","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_add","latest_event_at":"2026-07-06T03:47:54Z","latest_event_status":"open","event_count":1,"event_kinds":["todo_add"]}]}`),agent_management_projection:{schema_version:`agent_management_projection_v0`,mode:`read_only`,goal_id:`loopx-meta`,generated_at:`2026-07-06T06:49:06Z`,style_hint:null,truth_contract:{todo_is_runtime_work_item:!0,projection_is_writable:!1,introduces_task_runtime:!1,write_api:!1},source_summary:{registered_agent_count:4,projected_agent_count:4,todo_source:`live_loopx_status_public_slice`,public_safe_export:!0},agents:[{agent_id:`codex-main-control`,agent_model:`peer_v1`,profile_role:`release-validation`,state:`blocked`,next_action:`Continue projected todo todo_2bf560b48a0c.`,last_activity_at:`2026-06-29T00:49:36+08:00`,evidence_refs:[`todo:todo_e72afc24f04a:evidence`],goal_ids:[`loopx-meta`],stale_claim_hint:{state:`activity_missing`,claimed_by:`codex-main-control`,reason:`claimed open todo has no projected activity timestamp`,recommended_operator_action:`inspect evidence before considering reassignment`},current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_2bf560b48a0c`,goal_id:`loopx-meta`,role:`agent`,status:`open`,priority:`P0`,title:`Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harn…`,task_class:`blocker`,action_kind:`legacy_open_pr_rename_blocker`,claimed_by:`codex-main-control`}},{agent_id:`codex-product-capability`,agent_model:`peer_v1`,profile_role:`product-validation`,state:`monitoring`,next_action:`Continue projected todo todo_ded745761822.`,last_activity_at:`2026-07-06T06:29:53Z`,evidence_refs:[`todo:todo_ded745761822:evidence`],goal_ids:[`loopx-meta`],current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_ded745761822`,goal_id:`loopx-meta`,role:`agent`,status:`open`,priority:`P0-LOCAL`,title:`Public-safe redacted live LoopX text; inspect local status for the full row.`,task_class:`continuous_monitor`,action_kind:`Public-safe redacted live LoopX text; inspect local status for the full row.`,claimed_by:`codex-product-capability`,updated_at:`2026-07-04T20:22:45+08:00`}},{agent_id:`codex-side-bypass`,agent_model:`peer_v1`,profile_role:`implementation-validation`,state:`waiting`,next_action:`Inspect status projection before taking work.`,last_activity_at:`2026-07-06T06:32:16Z`,evidence_refs:[`rollout_event:todo_complete:todo_22c946938115`],goal_ids:[`loopx-meta`]},{agent_id:`codex-value-explorer`,agent_model:`peer_v1`,profile_role:`value-exploration`,state:`monitoring`,next_action:`Continue projected todo todo_584f55f8f3b4.`,last_activity_at:`2026-07-06T09:39:59+08:00`,evidence_refs:[`rollout_event:todo_update:todo_584f55f8f3b4`],goal_ids:[`loopx-meta`],current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_584f55f8f3b4`,goal_id:`loopx-meta`,role:`agent`,status:`open`,title:`todo add recorded for todo_584f55f8f3b4`}}]},contract:{ok:!0,summary:{errors:0,warnings:1,checks:6},errors:[],warnings:["loopx-meta: duplicate index rows raw=8444 unique=8440 unexpected=3 artifact_identity_collisions=2 artifact_collision_rows=3 reward_overlays=1; inspect with `loopx history --goal-id loopx-meta inspect-index-duplicates`; artifact identity collisions need review…"],checks:[`registry goals checked: 12`,`registry boundary: shared_local_registry push_allowed=False tracked=False ignored=False`,`user-gate scopes checked: 6 open multi-agent gates`,`runtime root resolved: $HOME/.codex/loopx`,`run-history goals=28 runs=10210`,`public boundary scan clean: 1218 files`]},global_registry:{available:!0,ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,current_registry:`$HOME/.codex/loopx/registry.global.json`,current_registry_is_global:!0,global_goal_count:12,current_goal_count:12,source_registry_count:7,summary:{high:0,action:8,info:0,checks:2,findings:8},findings:[{kind:`source_registry_missing`,severity:`action`,message:"`cc-test` source registry is missing",recommended_action:"reconnect `cc-test` from its project or archive it if the project is obsolete",goal_id:`cc-test`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-test` active state file is missing",recommended_action:"repair `cc-test` state_file or reconnect the project",goal_id:`cc-test`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`cc-tmp` source registry is missing",recommended_action:"reconnect `cc-tmp` from its project or archive it if the project is obsolete",goal_id:`cc-tmp`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-tmp` active state file is missing",recommended_action:"repair `cc-tmp` state_file or reconnect the project",goal_id:`cc-tmp`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`cc-tmp-xdrchpuaul` source registry is missing",recommended_action:"reconnect `cc-tmp-xdrchpuaul` from its project or archive it if the project is obsolete",goal_id:`cc-tmp-xdrchpuaul`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-tmp-xdrchpuaul` active state file is missing",recommended_action:"repair `cc-tmp-xdrchpuaul` state_file or reconnect the project",goal_id:`cc-tmp-xdrchpuaul`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`loopx-auto-research-e2e-probe-20260628-2225-goal` source registry is missing",recommended_action:"reconnect `loopx-auto-research-e2e-probe-20260628-2225-goal` from its project or archive it if the project is obsolete",goal_id:`loopx-auto-research-e2e-probe-20260628-2225-goal`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`loopx-auto-research-e2e-probe-20260628-2225-goal` active state file is missing",recommended_action:"repair `loopx-auto-research-e2e-probe-20260628-2225-goal` state_file or reconnect the project",goal_id:`loopx-auto-research-e2e-probe-20260628-2225-goal`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`}],checks:[`global registry goals checked: 12`,`global source registries checked: 7`]},attention_queue:JSON.parse(`{"available":true,"item_count":1,"needs_user_or_controller":0,"needs_controller":0,"needs_codex":1,"watching_external_evidence":0,"items":[{"goal_id":"loopx-meta","status":"skillsbench_codex_cli_goal_tail4_keepalive_relaunched","lifecycle_phase":"adapter_inspected","lifecycle_flags":["adapter_inspected"],"waiting_on":"codex","severity":"action","recommended_action":"Monitor run_group skillsbench-codex-cli-goal-xhigh-tail4-keepalive-20260706T143132CST using public compact/public artifacts only; once benchmark_run.compact.json lands for each case, classify launcher/case/solver/verifi…","source":"latest_run","quota":{"compute":1.0,"window_hours":24,"slot_minutes":1,"allowed_slots":1440,"spent_slots":97,"state":"eligible","reason":"1 compute quota; eligible for the next automatic agent turn"},"agent_todos":{"source_section":"Agent Todo","total_count":12,"open_count":12,"done_count":0,"items":[{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo update recorded for todo_1596c3a678bb","schema_version":"todo_index_item_v0","todo_id":"todo_1596c3a678bb","role":"agent","status":"open","title":"todo update recorded for todo_1596c3a678bb","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:33:32Z","latest_event_status":"open","event_count":7,"event_kinds":["todo_update"]},{"goal_id":"loopx-meta","index":24,"done":false,"text":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","schema_version":"todo_index_item_v0","todo_id":"todo_15bc0926a494","role":"agent","status":"open","priority":"P0-REVENUE MONITOR","title":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"github_public_reply_metadata_monitor","claimed_by":"codex-value-explorer","evidence":"autonomous replan: bounded current value-explorer monitor lane with explicit expires_at.","note":"Set bounded watch expiry for metadata-only public reply monitor; no catch-up after expiry.","updated_at":"2026-07-05T06:27:15+08:00"},{"goal_id":"loopx-meta","index":17,"done":false,"text":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","schema_version":"todo_index_item_v0","todo_id":"todo_2bf560b48a0c","role":"agent","status":"open","priority":"P0","title":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"legacy_open_pr_rename_blocker","claimed_by":"codex-main-control"},{"goal_id":"loopx-meta","index":23,"done":false,"text":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","schema_version":"todo_index_item_v0","todo_id":"todo_3ed1c4a69164","role":"agent","status":"open","priority":"P0","title":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"skillsbench_local_verifier_reward_collection","claimed_by":"codex-main-control","required_capabilities":["benchmark_runner"]},{"goal_id":"loopx-meta","index":32,"done":false,"text":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","schema_version":"todo_index_item_v0","todo_id":"todo_44907a5f355d","role":"agent","status":"blocked","priority":"P0","title":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_raw_new_rerun","claimed_by":"codex-main-control","evidence":"Public-safe redacted live LoopX text; inspect local status for the full row.","note":"Do not spend a full citation-check loopx rerun yet: #865 fixed scored output paths and #874 added bootstrap preflight attribution, but citation-check itself still preflights as apt+verifier bootstrap risk on ECS.","updated_at":"2026-06-29T00:49:36+08:00"},{"goal_id":"loopx-meta","index":39,"done":false,"text":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","schema_version":"todo_index_item_v0","todo_id":"todo_4762c790e583","role":"agent","status":"blocked","priority":"P0","title":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_remote_rerun","claimed_by":"codex-main-control","evidence":"A prior benchmark adapter change was validated before the legacy surface was archived. Current research uses the RFC-linked benchmark workspace and toolkit boundary smokes.","note":"2026-06-29: fixed host-local ACP idle/no-output root cause in PR #894. ACP protocol tool_call_count=0 is now distinguished from reverse-channel task-facing bridge activity; repeated codex_exec_bridge_idle_timeout withou…","updated_at":"2026-06-29T19:40:32+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_584f55f8f3b4","schema_version":"todo_index_item_v0","todo_id":"todo_584f55f8f3b4","role":"agent","status":"open","title":"todo add recorded for todo_584f55f8f3b4","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:48:49Z","latest_event_status":"open","event_count":3,"event_kinds":["todo_add","todo_update"]},{"goal_id":"loopx-meta","index":40,"done":false,"text":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","schema_version":"todo_index_item_v0","todo_id":"todo_62debf065fec","role":"agent","status":"blocked","priority":"P0 MONITOR","title":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"monitor_skillsbench_batch","claimed_by":"codex-main-control","evidence":"Observed 2026-06-30T02:52+08: active-state target_key=skillsbench-goal-baseline-30case-20260629T1826Z-r10; local ps/tmux/recent artifact search found no r10 batch process or compact artifact; no raw task/log/trajectory …","updated_at":"2026-06-30T02:54:54+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_93bc6439c521","schema_version":"todo_index_item_v0","todo_id":"todo_93bc6439c521","role":"agent","status":"open","title":"todo add recorded for todo_93bc6439c521","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_claim","latest_event_at":"2026-07-06T06:32:52Z","latest_event_status":"open","event_count":2,"event_kinds":["todo_add","todo_claim"]},{"goal_id":"loopx-meta","index":27,"done":false,"text":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","schema_version":"todo_index_item_v0","todo_id":"todo_aad7e9716927","role":"agent","status":"blocked","priority":"P0","title":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"run_goal_start_product_mode_matrix","claimed_by":"codex-main-control","evidence":"driver.status shows DONE raw then RUN loopx-goal-start with no running driver; raw benchmark_run.compact first_blocker=skillsbench_codex_acp_provider_zero_activity; source guard requires --host-local-acp-launch for Loop…","note":"Remote run group skillsbench-raw-new-goal-start-20260627T0420Z produced a material closeout for citation-check raw only; raw compact attribution is skillsbench_codex_acp_provider_zero_activity with official score missin…","updated_at":"2026-06-27T13:05:47+08:00"},{"goal_id":"loopx-meta","index":21,"done":false,"text":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","schema_version":"todo_index_item_v0","todo_id":"todo_aec1873c7f28","role":"agent","status":"open","priority":"P0 MONITOR","title":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","claimed_by":"codex-main-control","note":"2026-06-23 projection fix: this is monitor context for the powerlifting run, not an advancement next action; current executable path is SkillsBench build cache/prewarm repair.","updated_at":"2026-06-23T10:37:43+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_c02cb7d19607","schema_version":"todo_index_item_v0","todo_id":"todo_c02cb7d19607","role":"agent","status":"open","title":"todo add recorded for todo_c02cb7d19607","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_add","latest_event_at":"2026-07-06T03:47:54Z","latest_event_status":"open","event_count":1,"event_kinds":["todo_add"]}]}}]}`),run_history:{available:!0,goal_count:1,run_count:5,goals:[{id:`loopx-meta`,domain:`loopx-platform`,status:`active-read-only`,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`],registry_member:!0,legacy_runtime_goal:!1,adapter_kind:`harness_self_improvement`,adapter_status:`connected-read-only`,index_exists:!0,raw_index_records:8444,unique_runs:8440,quota:{compute:1,window_hours:24,slot_minutes:1,allowed_slots:1440,spent_slots:97,state:`waiting`,reason:`no active Codex-ready work is currently selected`},latest_runs:[{generated_at:`2026-07-06T14:37:32+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-value-explorer`,recommended_action:`审阅 PR #1524 的 Agent Management 面板视觉方向:workspace hint 与 stale claim hint 是否符合预期;确认后允许 codex-value-explorer 自合并。`,health_check:`quota safe-bypass operator gate; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:55+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-main-control`,recommended_action:`[P1] Repair SkillsBench post-run debug gate consistency for countable codex-cli-goal official-zero runs: when attempt_accounting is countable and case_closeout_complete=true, do not project first_blocker=loopx_closeout_…`,health_check:`quota should-run eligible; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:54+08:00`,goal_id:`loopx-meta`,classification:`skillsbench_codex_cli_goal_tail4_keepalive_relaunched`,agent_id:`codex-main-control`,progress_scope:`goal`,delivery_batch_scale:`single_surface`,delivery_outcome:`outcome_progress`,recommended_action:`Monitor run_group skillsbench-codex-cli-goal-xhigh-tail4-keepalive-20260706T143132CST using public compact/public artifacts only; once benchmark_run.compact.json lands for each case, classify launcher/case/solver/verifi…`,health_check:`state_file 1/1; registry_goal 1/1; authority_sources 10`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:34+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-side-bypass`,recommended_action:`[P0] Rerun real KNN visible auto-research after the successor-link fix and verify evaluator completion projects a second-round hypothesis/frontier or explicit completion gate without manual intervention; keep evidence p…`,health_check:`quota should-run eligible; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:32:57+08:00`,goal_id:`loopx-meta`,classification:`auto_research_successor_link_fix_merged`,agent_id:`codex-side-bypass`,progress_scope:`agent_lane`,delivery_batch_scale:`implementation`,delivery_outcome:`outcome_progress`,recommended_action:`[P0] Rerun real KNN visible auto-research after the successor-link fix and verify evaluator completion projects a second-round hypothesis/frontier or explicit completion gate without manual intervention; keep evidence p…`,health_check:`state_file 1/1; registry_goal 1/1; authority_sources 0`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]}]}]}},Yd=W().nullable(),Xd=J({schema_version:X(`goal_acceptance_observation_projection_v0`),goal_id:W(),read_only:X(!0),acceptance_assessed:X(!1),coverage:Y([`partial`,`unavailable`]),missing_sources:q(W()),truncated:K(),historical_progress:q(J({kind:W(),observed_at:Yd,source:W(),evidence_refs:q(W())})),acceptance_gaps:q(J({kind:W(),owner:Yd,reason:Yd,evidence_required:Yd,observed_at:Yd,source:W()})),guards:q(J({kind:W(),todo_id:Yd,blocks_agent:Yd,owner:Yd,reason:Yd,evidence_required:Yd,decision_scope:Yd})),next_action:Yd,next_action_source:Yd}),Zd=ud([W(),G(),K(),nd()]),Qd=gd(W(),Zd),$d=J({todo_id:W().optional(),priority:W().optional(),status:W(),title:W(),claimed_by:W().optional(),task_class:W().optional(),action_kind:W().optional()}),ef=J({gate_id:W(),kind:W(),status:W(),blocks:q(W()).optional()}),tf=J({todo_id:W().optional(),owner_agent:W().optional(),status:W().optional(),lease_until:W().optional(),write_scope:q(W()).optional()}),nf=J({generated_at:W().optional(),classification:W().optional(),summary:W().optional()}),rf=J({kind:W().optional().default(`warning`),message:ud([W(),q(W())]).optional().default(`compact source warning`)}).passthrough(),af=J({schema_version:X(`goal_channel_projection_v0`),mode:X(`read_only`),goal_id:W(),display_name:W(),generated_at:W().optional().nullable(),latest_status:W(),waiting_on:W(),next_action:W(),source_refs:gd(W(),Zd),decision_frame:J({user_action_required:K(),agent_action_required:K(),quiet_noop_allowed:K()}),quota:Qd,user_todos:q($d).default([]),agent_todos:q($d).default([]),open_gates:q(ef).default([]),active_leases:q(tf).default([]),artifacts:q(Qd).default([]),recent_events:q(nf).default([]),source_warnings:q(rf).default([]),truth_contract:J({event_ledger_is_source_of_truth:K(),projection_is_writable:K(),recompute_rule:W(),write_authority:W()})}),of=J({compute:G().optional().default(1),window_hours:G().optional().default(24),slot_minutes:G().optional().default(1),allowed_slots:G().optional().nullable(),spent_slots:G().optional().default(0),state:W().optional().nullable(),next_eligible_at:W().optional().nullable(),reason:W().optional().nullable(),blocked_action_scope:W().optional().nullable(),focus_wait:K().optional().nullable(),handoff_outcome_floor_block:K().optional().nullable(),safe_bypass_allowed:K().optional().default(!1),safe_bypass_kind:W().optional().nullable(),safe_bypass_policy:W().optional().nullable(),post_handoff_outcome_gap_streak:G().optional().nullable(),outcome_gap_threshold:G().optional().nullable(),must_advance:q(W()).optional().default([]),avoid:q(W()).optional().default([])}).transform(e=>{let t=Math.max(1,e.slot_minutes),n=Math.round(e.window_hours*60*e.compute/t);return{...e,slot_minutes:t,allowed_slots:e.allowed_slots??n}}),sf=J({self_repair:J({enabled:K().optional().default(!1),allow_health_blocker_repair:K().optional().default(!1),allow_waiting_projection_repair:K().optional().default(!1)}).optional().nullable()}).passthrough(),cf=J({model_config:J({model:W(),reasoning_effort:W().optional()}).optional(),mode:W().optional().default(`default`),orchestration_mode:W().optional().nullable(),spawn_allowed:K().optional().default(!1),allowed:K().optional().nullable(),max_children:G().optional().default(0),allowed_domains:q(W()).optional().default([])}).passthrough(),lf=J({label:W().optional().nullable(),path:W(),anchor:W().optional().nullable(),exists:K().optional().default(!1),resolved_path:W().optional().nullable()}),uf=J({index:G(),done:K(),text:W(),schema_version:W().optional().nullable(),todo_id:W().optional().nullable(),role:W().optional().nullable(),status:W().optional().nullable(),resume_when:W().optional().nullable(),resume_ready:K().optional().nullable(),resume_condition:gd(W(),id()).optional().nullable(),priority:W().optional().nullable(),title:W().optional().nullable(),archive_state:W().optional().nullable(),source_section:W().optional().nullable(),task_class:W().optional().nullable(),task_domain:W().optional().nullable(),action_kind:W().optional().nullable(),claimed_by:W().optional().nullable(),required_capabilities:q(W()).optional(),note:W().optional().nullable(),evidence:W().optional().nullable(),updated_at:W().optional().nullable(),review_materials:q(lf).optional().default([])}).passthrough(),df=J({source_section:W().optional().nullable(),total_count:G().optional().default(0),open_count:G().optional().default(0),done_count:G().optional().default(0),advancement_done_count:G().optional(),items:q(uf).optional().default([]),deferred_items:q(uf).optional()}),ff=uf.extend({goal_id:W(),source:W().optional().nullable(),event_count:G().optional().default(0),event_kinds:q(W()).optional().default([]),latest_event_kind:W().optional().nullable(),latest_event_at:W().optional().nullable(),latest_event_status:W().optional().nullable(),agent_id:W().optional().nullable()}).passthrough(),pf=J({schema_version:W().optional().nullable(),source:W().optional().nullable(),total_count:G().optional().default(0),current_projected_count:G().optional().default(0),rollout_event_count:G().optional().default(0),item_limit:G().optional().nullable(),items:q(ff).optional().default([])}),mf=J({kind:W().optional().nullable(),label:W().optional().nullable(),path_safe:K().optional().default(!1),branch:W().optional().nullable(),write_scope:q(W()).optional().default([])}).passthrough(),hf=J({state:W().optional().nullable(),claimed_by:W().optional().nullable(),last_activity_at:W().optional().nullable(),threshold_hours:G().optional().nullable(),reason:W().optional().nullable(),recommended_operator_action:W().optional().nullable()}).passthrough(),gf=J({schema_version:W().optional().nullable(),todo_id:W().optional().nullable(),goal_id:W().optional().nullable(),role:W().optional().nullable(),status:W().optional().nullable(),priority:W().optional().nullable(),title:W().optional().nullable(),task_class:W().optional().nullable(),action_kind:W().optional().nullable(),claimed_by:W().optional().nullable(),required_write_scopes:q(W()).optional().default([]),workspace_ref:mf.optional().nullable()}).passthrough(),_f=J({schema_version:W().optional().nullable(),from_agent:W().optional().nullable(),to_agent:W().optional().nullable(),intent:W().optional().nullable(),summary:W().optional().nullable(),blocker:W().optional().nullable(),suggested_next_action:W().optional().nullable(),evidence_refs:q(W()).optional().default([]),updated_at:W().optional().nullable()}).passthrough(),vf=J({agent_id:W(),role:W().optional().nullable(),state:W().optional().nullable(),current_todo:gf.optional().nullable(),next_action:W().optional().nullable(),last_activity_at:W().optional().nullable(),evidence_refs:q(W()).optional().default([]),handoff_refs:q(W()).optional().default([]),handoff_note:_f.optional().nullable(),workspace_ref:mf.optional().nullable(),stale_claim_hint:hf.optional().nullable(),blocked_on:gf.optional().nullable(),goal_ids:q(W()).optional().default([])}).passthrough(),yf=J({schema_version:W().optional().nullable(),mode:W().optional().nullable(),goal_id:W().optional().nullable(),generated_at:W().optional().nullable(),style_hint:J({preferred:W().optional().nullable(),license_boundary:W().optional().nullable()}).optional().nullable(),truth_contract:J({todo_is_runtime_work_item:K().optional().default(!0),projection_is_writable:K().optional().default(!1),introduces_task_runtime:K().optional().default(!1),write_api:K().optional().default(!1)}).optional().nullable(),source_summary:J({registered_agent_count:G().optional().default(0),projected_agent_count:G().optional().default(0),todo_source:W().optional().nullable()}).optional().nullable(),agents:q(vf).optional().default([])}).passthrough(),bf=J({goal_id:W(),configured:K().optional().default(!1),enabled:K().optional().default(!1),human_gate_auto_notify_enabled:K().optional().default(!1),target_ref:W().optional().nullable(),receipt_count:G().optional().default(0),last_notified_at:W().optional().nullable()}).passthrough(),xf=J({schema_version:W().optional().nullable(),generated_at:W().optional().nullable(),goals:q(bf).optional().default([])}).passthrough(),Sf=J({source_section:W().optional().nullable(),open:G().optional().default(0),done:G().optional().default(0),total:G().optional().default(0),advancement_done_count:G().optional(),next:W().optional().nullable(),next_index:G().optional().nullable(),items:q(uf).optional().default([]),recent_completed_advancement_items:q(uf).optional().default([])}),Cf=J({goal_id:W(),status:W().optional().nullable(),waiting_on:W().optional().nullable(),severity:W().optional().nullable(),index:G().optional().nullable(),text:W(),source:W().optional().nullable()}),wf=J({source:W().optional().nullable(),open_count:G().optional().default(0),items:q(Cf).optional().default([])}),Tf=J({goal_id:W(),status:W().optional().nullable(),waiting_on:W().optional().nullable(),quota_state:W().optional().nullable(),priority:W().optional().nullable(),todo_index:G().optional().nullable(),text:W(),source:W().optional().nullable()}),Ef=J({source:W().optional().nullable(),open_count:G().optional().default(0),items:q(Tf).optional().default([])}),Df=J({generated_at:W().optional().nullable(),classification:W().optional().nullable(),summary:W().optional().nullable()}),Of=J({kind:W().optional().nullable(),source:W().optional().nullable(),severity:W().optional().nullable(),requires_refresh_state:K().optional().default(!1),reason:W().optional().nullable(),active_state_updated_at:W().optional().nullable(),latest_run_generated_at:W().optional().nullable(),latest_run_state_updated_at:W().optional().nullable(),latest_run_classification:W().optional().nullable(),recommended_action:W().optional().nullable()}),kf=J({generated_at:W().optional().nullable(),classification:W().optional().nullable(),delivery_batch_scale:W().optional().nullable(),delivery_outcome:W().optional().nullable(),health_check:W().optional().nullable(),json_exists:K().optional().nullable(),markdown_exists:K().optional().nullable()}),Af=J({project_asset_backed:K().optional(),same_source_should_run:K().optional(),codex_ready:K().optional(),handoff_has_next_action:K().optional(),handoff_has_stop_condition:K().optional(),handoff_sanitized_surface:K().optional()}).catchall(K()),jf=J({ready:K().optional().default(!1),codex_ready:K().optional().default(!1),source:W().optional().nullable(),quota_state:W().optional().nullable(),checks:Af.optional().default({}),handoff_status:W().optional().nullable(),handoff_ready_at:W().optional().nullable(),handoff_ready_classification:W().optional().nullable(),post_handoff_run_seen:K().optional().default(!1),post_handoff_latest_run:kf.optional().nullable(),post_handoff_recent_runs:q(kf).optional().default([]),post_handoff_small_scale_streak:G().int().nonnegative().optional().default(0),post_handoff_outcome_gap_streak:G().int().nonnegative().optional().default(0),next_probe:W().optional().nullable()}),Mf=J({schema_version:W().optional().nullable(),kind:W().optional().nullable(),missing_roles:q(W()).optional().default([]),source:W().optional().nullable(),recommended_action:W().optional().nullable()}),Nf=J({owner:W(),gate:W(),next_action:W(),stop_condition:W(),user_todos:Sf.optional().nullable(),agent_todos:Sf.optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),orchestration:cf.optional().nullable(),latest_validation:Df.optional().nullable(),stale_latest_run_warning:Of.optional().nullable(),todo_projection_gap:Mf.optional().nullable()}),Pf=J({goal_id:W(),activation_state:Y([`active`,`stopped`]).optional().default(`active`),status:W(),waiting_on:W(),severity:W(),recommended_action:W(),project_asset:Nf.optional().nullable(),handoff_readiness:jf.optional().nullable(),source:W().optional(),operator_question:W().optional().nullable(),agent_command:W().optional().nullable(),lifecycle_phase:W().optional().nullable(),lifecycle_flags:q(W()).optional().default([]),controller_stage:W().optional().nullable(),missing_gates:q(W()).optional().default([]),next_handoff_condition:W().optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),user_todos:df.optional().nullable(),agent_todos:df.optional().nullable(),stale_latest_run_warning:Of.optional().nullable(),dependency_blockers:wf.optional().nullable(),todo_state_file:W().optional().nullable(),goal_channel_projection:af.optional().nullable()}),Ff=J({recorded_at:W().optional().nullable(),decision:W().optional().nullable(),reward:W().optional().nullable(),reason_summary:W().optional().nullable(),follow_up:W().optional().nullable()}),If=J({recorded_at:W().optional().nullable(),gate:W().optional().nullable(),decision:W().optional().nullable(),operator_question:W().optional().nullable(),reason_summary:W().optional().nullable(),follow_up:W().optional().nullable(),agent_command:W().optional().nullable()}),Lf=J({version:W().optional().nullable(),goal_id:W().optional().nullable(),run_id:W().optional().nullable(),gate_id:W().optional().nullable(),created_state_ref:W().optional().nullable(),created_policy_version:W().optional().nullable(),interrupt_payload:J({question:W().optional().nullable(),choices:q(W()).optional().default([])}).optional().nullable(),allowed_decisions:q(W()).optional().default([]),operator_decision:W().optional().nullable(),latest_state_ref:W().optional().nullable(),freshness_check:W().optional().nullable(),precondition_check:W().optional().nullable(),migration_or_rebase_result:W().optional().nullable(),resulting_action:W().optional().nullable(),validation_after_resume:W().optional().nullable()}),Rf=J({id:W().optional().nullable(),ok:K().optional().nullable(),review:W().optional().nullable()}),zf=J({classification:W().optional().nullable(),read_only_observer_ready:K().optional().nullable(),decision_advisor_ready:K().optional().nullable(),write_controller_ready:K().optional().nullable(),missing_gates:q(W()).optional().default([]),review_judgment:W().optional().nullable(),next_handoff_condition:W().optional().nullable(),gates:q(Rf).optional().default([])}),Bf=J({declared:K().optional().default(!1),required:K().optional().default(!1),path:W().optional().nullable(),path_exists:K().optional().nullable(),read_status:W().optional().nullable(),default_entry_count:G().optional().default(0),default_entries_checked:G().optional().default(0),default_entries_present:G().optional().default(0),topic_authority_count:G().optional().default(0),project_material_count:G().optional().default(0),project_material_repository_count:G().optional().default(0),project_material_owner_review_required_count:G().optional().default(0),project_material_stale_count:G().optional().default(0),project_material_current_authority_count:G().optional().default(0),deprecated_source_count:G().optional().default(0),conflict_risk:W().optional().nullable()}),Vf=J({adapter_kind:W().optional().nullable(),adapter_status:W().optional().nullable(),authority_source_count:G().optional().nullable(),authority_registry_declared:K().optional().nullable(),authority_registry_path_exists:K().optional().nullable(),authority_registry_default_entry_count:G().optional().nullable(),authority_registry_default_entries_present:G().optional().nullable(),topic_authority_count:G().optional().nullable(),project_material_count:G().optional().nullable(),project_material_repository_count:G().optional().nullable(),project_material_owner_review_required_count:G().optional().nullable(),project_material_stale_count:G().optional().nullable(),project_material_current_authority_count:G().optional().nullable(),authority_registry_conflict_risk:W().optional().nullable(),guard_count:G().optional().nullable(),sections_found:G().optional().nullable(),sections_checked:G().optional().nullable(),files_present:G().optional().nullable(),files_checked:G().optional().nullable()}),Hf=J({generated_at:W(),goal_id:W(),classification:W().optional().nullable(),lifecycle_phase:W().optional().nullable(),lifecycle_flags:q(W()).optional().default([]),recommended_action:W().optional().nullable(),health_check:W().optional().nullable(),active_task_count:G().optional().nullable(),active_priorities:gd(W(),id()).optional().nullable(),cache_check:W().optional().nullable(),json_exists:K().optional().default(!1),markdown_exists:K().optional().default(!1),human_reward:Ff.optional().nullable(),operator_gate:If.optional().nullable(),operator_gate_resume_contract:Lf.optional().nullable(),controller_readiness:zf.optional().nullable(),project_map:Vf.optional().nullable()}),Uf=J({acceptance_observation:Xd.optional().nullable().catch(null),id:W(),activation_state:Y([`active`,`stopped`]).optional().default(`active`),display_name:W().optional().nullable(),domain:W().optional().nullable(),status:W().optional().nullable(),lifecycle_phase:W().optional().nullable(),lifecycle_flags:q(W()).optional().default([]),registry_member:K().optional().default(!1),legacy_runtime_goal:K().optional().default(!1),adapter_kind:W().optional().nullable(),adapter_status:W().optional().nullable(),authority_registry:Bf.optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),spawn_policy:cf.optional().nullable(),orchestration:cf.optional().nullable(),coordination:J({agent_model:W().optional().nullable(),registered_agents:q(W()).optional().default([])}).optional().nullable(),index_exists:K().optional().default(!1),raw_index_records:G().optional().default(0),unique_runs:G().optional().default(0),latest_runs:q(Hf).optional().default([])}),Wf=J({available:K(),goal_count:G().optional().default(0),run_count:G().optional().default(0),goals:q(Uf).optional().default([]),recent_runs:q(Hf).optional().default([])}),Gf=J({kind:W(),severity:W(),message:W(),recommended_action:W(),goal_id:W().optional().nullable(),path:W().optional().nullable(),goal_ids:q(W()).optional().default([])}),Kf=J({available:K(),ok:K(),registry:W(),current_registry:W().optional().nullable(),current_registry_is_global:K().optional().default(!1),global_goal_count:G().optional().default(0),current_goal_count:G().optional().default(0),source_registry_count:G().optional().default(0),summary:J({high:G().optional().default(0),action:G().optional().default(0),info:G().optional().default(0),checks:G().optional().default(0),findings:G().optional().default(0)}),findings:q(Gf).optional().default([]),checks:q(W()).optional().default([])}),qf=J({runs_24h:G().optional().default(0),runs_7d:G().optional().default(0),quota_spend_slots_24h:G().optional().default(0),quota_spend_slots_7d:G().optional().default(0),automation_run_count_24h:G().optional().default(0),automation_run_count_7d:G().optional().default(0),progress_signal_run_count_24h:G().optional().default(0),progress_signal_run_count_7d:G().optional().default(0),input_tokens_24h:G().optional(),input_tokens_7d:G().optional(),output_tokens_24h:G().optional(),output_tokens_7d:G().optional(),cache_tokens_24h:G().optional(),cache_tokens_7d:G().optional(),cost_usd_24h:G().optional(),cost_usd_7d:G().optional(),duration_ms_24h:G().optional(),duration_ms_7d:G().optional()}),Jf=qf.extend({goal_id:W(),project_share_24h:G().optional().default(0)}),Yf=J({available:K().optional().default(!0),source:W().optional().default(`run_history`),generated_at:W().optional().nullable(),sample_run_count:G().optional().default(0),proxy_note:W().optional().nullable(),totals:qf.optional().default({runs_24h:0,runs_7d:0,quota_spend_slots_24h:0,quota_spend_slots_7d:0,automation_run_count_24h:0,automation_run_count_7d:0,progress_signal_run_count_24h:0,progress_signal_run_count_7d:0}),goals:q(Jf).optional().default([])}).optional().nullable(),Xf=J({accounting:G().optional().default(0),decision:G().optional().default(0),evidence:G().optional().default(0),state:G().optional().default(0),work:G().optional().default(0)}),Zf={accounting:0,decision:0,evidence:0,state:0,work:0},Qf=J({events_24h:G().optional().default(0),events_7d:G().optional().default(0),by_class_24h:Xf.optional().default(Zf),by_class_7d:Xf.optional().default(Zf)}),$f=Qf.extend({goal_id:W(),latest_event_class:W().optional().nullable(),latest_event_at:W().optional().nullable()}),ep={events_24h:0,events_7d:0,by_class_24h:Zf,by_class_7d:Zf},tp=J({available:K().optional().default(!0),source:W().optional().default(`run_history`),generated_at:W().optional().nullable(),sample_run_count:G().optional().default(0),proxy_note:W().optional().nullable(),event_classes:q(W()).optional().default([`accounting`,`decision`,`evidence`,`state`,`work`]),totals:Qf.optional().default(ep),goals:q($f).optional().default([])}).optional().nullable(),np=J({available:K().optional().default(!1),source:W().optional().default(`run_history`),goal_id:W().optional().nullable(),generated_at:W().optional().nullable(),classification:W().optional().nullable(),delivery_batch_scale:W().optional().nullable(),delivery_outcome:W().optional().nullable(),recommended_action:W().optional().nullable(),json_exists:K().optional().default(!1),markdown_exists:K().optional().default(!1),freshness_window_hours:G().optional().default(24),freshness_status:W().optional().nullable(),is_fresh:K().optional().default(!1),requires_readiness_run:K().optional().default(!0),age_seconds:G().optional().nullable(),age_hours:G().optional().nullable(),freshness_reference_time:W().optional().nullable(),sample_run_count:G().optional().default(0),proxy_note:W().optional().nullable(),reason:W().optional().nullable()}).optional().nullable(),rp=J({ok:K().optional().default(!0),registry:W().optional().nullable(),runtime_root:W().optional().nullable(),gate:W().optional().default(`promotion_readiness`),gate_state:W().optional().default(`warning`),can_promote:K().optional().default(!1),should_warn:K().optional().default(!0),non_blocking:K().optional().default(!0),recommended_action:W().optional().nullable(),warning_message:W().optional().nullable(),readiness:np.default(null)}).optional().nullable(),ip=J({decision_count:G().optional().default(0),stale_count:G().optional().default(0),rebase_required_count:G().optional().default(0),fresh_count:G().optional().default(0)}),ap=J({goal_id:W(),decision_kind:W().optional().nullable(),decision_at:W().optional().nullable(),classification:W().optional().nullable(),age_days:G().optional().nullable(),stale_by_age:K().optional().default(!1),newer_event_count_7d:G().optional().default(0),newer_event_classes_7d:Xf.optional().default(Zf),freshness_state:W().optional().nullable(),requires_decision_point_rebase:K().optional().default(!1),reason:W().optional().nullable()}),op=J({available:K().optional().default(!0),source:W().optional().default(`run_history`),generated_at:W().optional().nullable(),sample_run_count:G().optional().default(0),window_days:G().optional().default(7),proxy_note:W().optional().nullable(),summary:ip.optional().default({decision_count:0,stale_count:0,rebase_required_count:0,fresh_count:0}),items:q(ap).optional().default([])}).optional().nullable(),sp=J({schema_version:G().optional().default(0),minimum_dashboard_schema_version:G().optional().default(2),producer:W().optional().nullable(),reload_hint:W().optional().nullable()}).optional().default({schema_version:0,minimum_dashboard_schema_version:2,producer:null,reload_hint:`scripts/macos-dashboard-launchagent.sh restart`}),cp=J({schema_version:X(`loopx_goal_projection_scope_v0`),scope:Y([`all`,`active`,`stopped`]),complete:K(),projected_goal_count:G().int().nonnegative(),registry_goal_count:G().int().nonnegative(),registry_revision:W().optional().nullable()}),lp=J({source:W().optional().default(`serve-status`),status_url:W().optional().nullable(),health_url:W().optional().nullable(),review_material_url:W().optional().nullable(),presentation_surfaces_url:W().optional().nullable(),presentation_detail_url:W().optional().nullable(),periodic_report_index_url:W().optional().nullable(),periodic_report_detail_url:W().optional().nullable(),ssh_hosts_url:W().optional().nullable(),reward_dry_run_url:W().optional().nullable(),reward_append_url:W().optional().nullable(),reward_write_enabled:K().optional().default(!1),configure_goal_dry_run_url:W().optional().nullable(),configure_goal_apply_url:W().optional().nullable(),control_plane_write_enabled:K().optional().default(!1)}).optional().nullable(),up=J({extension_id:W().min(1),surface_id:W().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/),extension_revision:W().min(1),payload_sha256:W().regex(/^[0-9a-f]{64}$/)}).strict(),dp=J({extension_id:W().min(1),extension_revision:W().min(1),surface_id:W().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/),surface_kind:W().regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/),title:W().min(1),view_schema:W().regex(/^[a-z][a-z0-9_]*_v\d+$/),visibility:Y([`public-safe`,`owner-only`]),goal_id:W().min(1).nullable(),generated_at:W().min(1).nullable(),review_due_at:W().min(1).nullable(),diagnostic:W().min(1).nullable(),empty_state_title:W().min(1),empty_state_detail:W().min(1)}),fp=ud([dp.extend({state:Y([`ready`,`review_due`]),goal_id:W().min(1),generated_at:W().min(1),detail_ref:up}).strict(),dp.extend({state:X(`empty`),detail_ref:od().optional()}).strict(),dp.extend({state:X(`invalid`),diagnostic:W().min(1),detail_ref:od().optional()}).strict()]),pp=J({schema_version:X(`extension_presentation_surfaces_v0`),count:G().int().nonnegative(),ready_count:G().int().nonnegative(),review_due_count:G().int().nonnegative(),empty_count:G().int().nonnegative(),invalid_count:G().int().nonnegative(),items:q(fp)}).strict(),mp={schema_version:`extension_presentation_surfaces_v0`,count:0,ready_count:0,review_due_count:0,empty_count:0,invalid_count:0,items:[]};J({ok:X(!0),presentation_surfaces:pp}).strict();var hp=J({goal_id:W().min(1),agent_id:W().min(1),generation_id:W().min(1),content_sha256:W().regex(/^sha256:[0-9a-f]{64}$/)}).strict(),gp=J({goal_id:W().min(1),agent_id:W().min(1),generation_id:W().min(1),publication_id:W().min(1),delivered_at:W().min(1),predecessor_publication_id:W().min(1).nullable().optional(),detail_ref:hp}).strict(),_p=J({schema_version:X(`periodic_report_workspace_index_v0`),count:G().int().nonnegative(),items:q(gp)}),vp=_p.extend({returned_count:G().int().nonnegative(),total_count:G().int().nonnegative(),limit:G().int().nonnegative(),offset:G().int().nonnegative(),truncated:K()}).strict(),yp=_p.strict().transform(e=>({...e,returned_count:e.count,total_count:e.count,limit:e.count,offset:0,truncated:!1})),bp=J({ok:X(!0),periodic_reports:ud([vp,yp])}).strict(),xp=J({schema_version:X(`periodic_report_workspace_projection_v0`),goal_id:W().min(1),agent_id:W().min(1),generation_id:W().min(1),generated_at:W().min(1),title:W().min(1),summary:W().min(1),content_sha256:W().regex(/^sha256:[0-9a-f]{64}$/),period_window:J({start_at:W().min(1),end_at:W().min(1)}).strict(),interaction:J({attention_kind:X(`progress`),interaction:X(`inform`),delivery:X(`surface`),form:X(`milestone_report`),writable:X(!1)}).strict(),delta:J({added_count:G().int().nonnegative(),changed_count:G().int().nonnegative(),item_count:G().int().positive(),items:q(J({fact_id:W().min(1),source_ref:W().min(1),title:W().min(1),summary:W().min(1),status:W().min(1),content_kind:W().min(1),change_kind:Y([`added`,`changed`]),previous_status:W().min(1).optional()}).strict())}).strict(),publication:J({publication_id:W().min(1),delivered_at:W().min(1),predecessor_publication_id:W().min(1).nullable().optional(),cursor_id:W().min(1)}).strict(),truth_contract:J({published_cursor_is_source_of_truth:X(!0),generation_receipt_is_delivery_receipt:X(!1),projection_is_writable:X(!1),browser_write_api:X(!1)}).strict()}).strict(),Sp=J({ok:X(!0),projection:xp}).strict(),Cp=J({ok:K(),registry:W(),runtime_root:W(),goal_count:G(),run_count:G(),status_contract:sp,goal_projection:cp.optional().nullable().default(null),local_dashboard_api:lp,contract:J({ok:K(),summary:J({errors:G(),warnings:G(),checks:G()}),errors:q(W()),warnings:q(W()),checks:q(W()).optional().default([])}),global_registry:Kf.optional().default({available:!1,ok:!0,registry:``,current_registry:null,current_registry_is_global:!1,global_goal_count:0,current_goal_count:0,source_registry_count:0,summary:{high:0,action:0,info:0,checks:0,findings:0},findings:[],checks:[]}),attention_queue:J({available:K(),item_count:G(),needs_user_or_controller:G(),needs_controller:G().optional().default(0),needs_codex:G(),watching_external_evidence:G(),autonomous_backlog_candidates:Ef.optional().nullable(),items:q(Pf)}),run_history:Wf.optional().default({available:!1,goal_count:0,run_count:0,goals:[],recent_runs:[]}),event_ledger_summary:tp.default(null),promotion_readiness_summary:np.default(null),promotion_gate:rp.default(null),decision_freshness_summary:op.default(null),usage_summary:Yf.default(null),todo_index:pf.optional().nullable().default(null),agent_management_projection:yf.optional().nullable().default(null),goal_channel_notification_projection:xf.optional().nullable().default(null),presentation_surfaces:pp.optional().default(mp)});J({ok:K(),dry_run:K().optional().default(!0),appended:K().optional().default(!1),goal_id:W().optional().nullable(),raw_index_records_before:G().optional().nullable(),preview_id:W().optional().nullable(),selected_run:J({generated_at:W().optional().nullable(),classification:W().optional().nullable(),recommended_action:W().optional().nullable(),json_exists:K().optional().nullable(),markdown_exists:K().optional().nullable()}).optional().nullable(),human_reward:Ff.optional().nullable(),active_state_summary:W().optional().nullable(),project_agent_visibility:J({source_of_truth:W().optional().nullable(),history_command:W().optional().nullable(),active_state_role:W().optional().nullable(),review_packet_role:W().optional().nullable()}).optional().nullable(),error:W().optional().nullable()});function wp(e,t,n){let r=e.run_history.goals.map(e=>e.id===t&&e.activation_state!==n?{...e,activation_state:n}:e),i=e.attention_queue.items.map(e=>e.goal_id===t&&e.activation_state!==n?{...e,activation_state:n}:e),a=r.some((t,n)=>t!==e.run_history.goals[n]),o=i.some((t,n)=>t!==e.attention_queue.items[n]);return!a&&!o?e:{...e,attention_queue:o?{...e.attention_queue,items:i}:e.attention_queue,run_history:a?{...e.run_history,goals:r}:e.run_history}}function Tp(e,t){let n=e.run_history.goals.filter(e=>e.id!==t),r=e.attention_queue.items.filter(e=>e.goal_id!==t);return n.length===e.run_history.goals.length&&r.length===e.attention_queue.items.length?e:{...e,attention_queue:{...e.attention_queue,items:r},run_history:{...e.run_history,goals:n}}}function Ep(e){return Cp.parse(e)}function Dp(e){return e instanceof fu?e.issues.map(e=>`${e.path.join(`.`)||`root`}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}var Op=Ep(Jd),kp=J({ok:X(!0),schema_version:X(`loopx_workspace_directory_v1`),registry_revision:W(),goals:q(J({id:W(),display_name:W(),activation_state:Y([`active`,`stopped`]),registry_member:X(!0)}))});function Ap(e,t,n){let r=new URL(e,n);r.searchParams.delete(`goal_activation`),r.searchParams.delete(`goal_id`),r.searchParams.delete(`view`);for(let[e,n]of Object.entries(t))r.searchParams.set(e,n);return r.toString()}async function jp(e,t){let n=await fetch(Ap(e,{view:`workspace-directory`},t),{cache:`no-store`,signal:AbortSignal.timeout(5e3)});if(!n.ok)return null;let r=kp.safeParse(await n.json());return r.success?r.data:null}function Mp(e){return Ep({ok:!0,registry:``,runtime_root:``,goal_count:e.goals.length,run_count:0,local_dashboard_api:{},contract:{ok:!0,summary:{errors:0,warnings:0,checks:0},errors:[],warnings:[]},attention_queue:{available:!1,item_count:0,needs_user_or_controller:0,needs_codex:0,watching_external_evidence:0,items:[]},run_history:{available:!1,goal_count:e.goals.length,run_count:0,goals:e.goals,recent_runs:[]}})}async function Np(e,t,n,r,i,a,o){let s=[...n.goals],c=new Map;async function l(){for(;s.length&&i()&&!o?.aborted;){let l=s.findIndex(e=>e.id===a()),u=l>=0?l:s.findIndex(e=>e.activation_state===`active`);if(u<0)return;let d=s.splice(u,1)[0],f=(c.get(d.id)??0)+1;c.set(d.id,f);let p=new AbortController,m=!1,h=()=>p.abort();o?.addEventListener(`abort`,h,{once:!0});let g=setTimeout(()=>{m=!0,p.abort()},3e4),_=null;try{let a=await fetch(Ap(e,{goal_id:d.id},t),{cache:`no-store`,signal:p.signal});if(!a.ok)_=a.status===409?`revision`:a.status>=500?`service`:`scope`;else{let e=await a.json();if(e.workspace_registry_revision!==n.registry_revision)_=`revision`;else{let t=Ep(e);!t.run_history.goals.some(e=>e.id===d.id)||t.run_history.goals.some(e=>e.id!==d.id)?_=`scope`:i()&&!o?.aborted&&r(d.id,t,null)}}}catch(e){_=m?`timeout`:e instanceof TypeError?`network`:`invalid`}finally{clearTimeout(g),o?.removeEventListener(`abort`,h)}if(!i()||o?.aborted)return;_&&[`timeout`,`network`,`service`].includes(_)&&f<3?(await new Promise(e=>setTimeout(e,f*1e3)),s.push(d)):_&&r(d.id,null,_)}}await Promise.all([l(),l()])}var Pp=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),Fp=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),Ip=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),Lp=e=>{let t=Ip(e);return t.charAt(0).toUpperCase()+t.slice(1)},Rp={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`},zp=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},Bp=(0,z.createContext)({}),Vp=()=>(0,z.useContext)(Bp),Hp=(0,z.forwardRef)(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>{let{size:l=24,strokeWidth:u=2,absoluteStrokeWidth:d=!1,color:f=`currentColor`,className:p=``}=Vp()??{},m=r??d?Number(n??u)*24/Number(t??l):n??u;return(0,z.createElement)(`svg`,{ref:c,...Rp,width:t??l??Rp.width,height:t??l??Rp.height,stroke:e??f,strokeWidth:m,className:Pp(`lucide`,p,i),...!a&&!zp(s)&&{"aria-hidden":`true`},...s},[...o.map(([e,t])=>(0,z.createElement)(e,t)),...Array.isArray(a)?a:[a]])}),Z=(e,t)=>{let n=(0,z.forwardRef)(({className:n,...r},i)=>(0,z.createElement)(Hp,{ref:i,iconNode:t,className:Pp(`lucide-${Fp(Lp(e))}`,`lucide-${e}`,n),...r}));return n.displayName=Lp(e),n},Up=Z(`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`}]]),Wp=Z(`arrow-down`,[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]),Gp=Z(`arrow-left`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]),Kp=Z(`arrow-right`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]),qp=Z(`arrow-up-down`,[[`path`,{d:`m21 16-4 4-4-4`,key:`f6ql7i`}],[`path`,{d:`M17 20V4`,key:`1ejh1v`}],[`path`,{d:`m3 8 4-4 4 4`,key:`11wl7u`}],[`path`,{d:`M7 4v16`,key:`1glfcx`}]]),Jp=Z(`arrow-up`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),Yp=Z(`badge-check`,[[`path`,{d:`M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z`,key:`3c2336`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),Xp=Z(`bell`,[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}]]),Zp=Z(`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`}]]),Qp=Z(`braces`,[[`path`,{d:`M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1`,key:`ezmyqa`}],[`path`,{d:`M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1`,key:`e1hn23`}]]),$p=Z(`calendar-clock`,[[`path`,{d:`M16 14v2.2l1.6 1`,key:`fo4ql5`}],[`path`,{d:`M16 2v4`,key:`4m81vk`}],[`path`,{d:`M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5`,key:`1osxxc`}],[`path`,{d:`M3 10h5`,key:`r794hk`}],[`path`,{d:`M8 2v4`,key:`1cmpym`}],[`circle`,{cx:`16`,cy:`16`,r:`6`,key:`qoo3c4`}]]),em=Z(`check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),tm=Z(`chevron-down`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),nm=Z(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),rm=Z(`chevron-up`,[[`path`,{d:`m18 15-6-6-6 6`,key:`153udz`}]]),im=Z(`circle-alert`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`12`,x2:`12`,y1:`8`,y2:`12`,key:`1pkeuh`}],[`line`,{x1:`12`,x2:`12.01`,y1:`16`,y2:`16`,key:`4dfq90`}]]),am=Z(`circle-check`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),om=Z(`clipboard-check`,[[`rect`,{width:`8`,height:`4`,x:`8`,y:`2`,rx:`1`,ry:`1`,key:`tgr4d6`}],[`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`,key:`116196`}],[`path`,{d:`m9 14 2 2 4-4`,key:`df797q`}]]),sm=Z(`code-xml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),cm=Z(`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`}]]),lm=Z(`database`,[[`ellipse`,{cx:`12`,cy:`5`,rx:`9`,ry:`3`,key:`msslwz`}],[`path`,{d:`M3 5V19A9 3 0 0 0 21 19V5`,key:`1wlel7`}],[`path`,{d:`M3 12A9 3 0 0 0 21 12`,key:`mv7ke4`}]]),um=Z(`download`,[[`path`,{d:`M12 15V3`,key:`m9g1x1`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`path`,{d:`m7 10 5 5 5-5`,key:`brsn70`}]]),dm=Z(`ellipsis`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]]),fm=Z(`external-link`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),pm=Z(`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`}]]),mm=Z(`file-braces`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1`,key:`1oajmo`}],[`path`,{d:`M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1`,key:`mpwhp6`}]]),hm=Z(`file-check-corner`,[[`path`,{d:`M10.5 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v6`,key:`g5mvt7`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`m14 20 2 2 4-4`,key:`15kota`}]]),gm=Z(`file-text`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),_m=Z(`git-branch`,[[`path`,{d:`M15 6a9 9 0 0 0-9 9V3`,key:`1cii5b`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}]]),vm=Z(`git-compare-arrows`,[[`circle`,{cx:`5`,cy:`6`,r:`3`,key:`1qnov2`}],[`path`,{d:`M12 6h5a2 2 0 0 1 2 2v7`,key:`1yj91y`}],[`path`,{d:`m15 9-3-3 3-3`,key:`1lwv8l`}],[`circle`,{cx:`19`,cy:`18`,r:`3`,key:`1qljk2`}],[`path`,{d:`M12 18H7a2 2 0 0 1-2-2V9`,key:`16sdep`}],[`path`,{d:`m9 15 3 3-3 3`,key:`1m3kbl`}]]),ym=Z(`info`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]),bm=Z(`languages`,[[`path`,{d:`m5 8 6 6`,key:`1wu5hv`}],[`path`,{d:`m4 14 6-6 2-3`,key:`1k1g8d`}],[`path`,{d:`M2 5h12`,key:`or177f`}],[`path`,{d:`M7 2h1`,key:`1t2jsx`}],[`path`,{d:`m22 22-5-10-5 10`,key:`don7ne`}],[`path`,{d:`M14 18h6`,key:`1m8k6r`}]]),xm=Z(`layout-dashboard`,[[`rect`,{width:`7`,height:`9`,x:`3`,y:`3`,rx:`1`,key:`10lvy0`}],[`rect`,{width:`7`,height:`5`,x:`14`,y:`3`,rx:`1`,key:`16une8`}],[`rect`,{width:`7`,height:`9`,x:`14`,y:`12`,rx:`1`,key:`1hutg5`}],[`rect`,{width:`7`,height:`5`,x:`3`,y:`16`,rx:`1`,key:`ldoo1y`}]]),Sm=Z(`list-plus`,[[`path`,{d:`M16 5H3`,key:`m91uny`}],[`path`,{d:`M11 12H3`,key:`51ecnj`}],[`path`,{d:`M16 19H3`,key:`zzsher`}],[`path`,{d:`M18 9v6`,key:`1twb98`}],[`path`,{d:`M21 12h-6`,key:`bt1uis`}]]),Cm=Z(`loader-circle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),wm=Z(`maximize-2`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`m21 3-7 7`,key:`1l2asr`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M9 21H3v-6`,key:`wtvkvv`}]]),Tm=Z(`menu`,[[`path`,{d:`M4 5h16`,key:`1tepv9`}],[`path`,{d:`M4 12h16`,key:`1lakjw`}],[`path`,{d:`M4 19h16`,key:`1djgab`}]]),Em=Z(`message-circle-question-mark`,[[`path`,{d:`M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719`,key:`1sd12s`}],[`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`,key:`1u773s`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),Dm=Z(`message-square-text`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}],[`path`,{d:`M7 11h10`,key:`1twpyw`}],[`path`,{d:`M7 15h6`,key:`d9of3u`}],[`path`,{d:`M7 7h8`,key:`af5zfr`}]]),Om=Z(`minimize-2`,[[`path`,{d:`m14 10 7-7`,key:`oa77jy`}],[`path`,{d:`M20 10h-6V4`,key:`mjg0md`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M4 14h6v6`,key:`rmj7iw`}]]),km=Z(`moon`,[[`path`,{d:`M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401`,key:`kfwtm`}]]),Am=Z(`palette`,[[`path`,{d:`M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z`,key:`e79jfc`}],[`circle`,{cx:`13.5`,cy:`6.5`,r:`.5`,fill:`currentColor`,key:`1okk4w`}],[`circle`,{cx:`17.5`,cy:`10.5`,r:`.5`,fill:`currentColor`,key:`f64h9f`}],[`circle`,{cx:`6.5`,cy:`12.5`,r:`.5`,fill:`currentColor`,key:`qy21gx`}],[`circle`,{cx:`8.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`fotxhn`}]]),jm=Z(`paperclip`,[[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551`,key:`1miecu`}]]),Mm=Z(`pause`,[[`rect`,{x:`14`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`kaeet6`}],[`rect`,{x:`5`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`1wsw3u`}]]),Nm=Z(`play`,[[`path`,{d:`M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z`,key:`10ikf1`}]]),Pm=Z(`plus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]),Fm=Z(`radio`,[[`path`,{d:`M16.247 7.761a6 6 0 0 1 0 8.478`,key:`1fwjs5`}],[`path`,{d:`M19.075 4.933a10 10 0 0 1 0 14.134`,key:`ehdyv1`}],[`path`,{d:`M4.925 19.067a10 10 0 0 1 0-14.134`,key:`1q22gi`}],[`path`,{d:`M7.753 16.239a6 6 0 0 1 0-8.478`,key:`r2q7qm`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}]]),Im=Z(`refresh-cw`,[[`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,key:`v9h5vc`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}],[`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,key:`3uifl3`}],[`path`,{d:`M8 16H3v5`,key:`1cv678`}]]),Lm=Z(`rotate-ccw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),Rm=Z(`rotate-cw`,[[`path`,{d:`M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8`,key:`1p45f6`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}]]),zm=Z(`search`,[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]),Bm=Z(`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`}]]),Vm=Z(`server-cog`,[[`path`,{d:`m10.852 14.772-.383.923`,key:`11vil6`}],[`path`,{d:`M13.148 14.772a3 3 0 1 0-2.296-5.544l-.383-.923`,key:`1v3clb`}],[`path`,{d:`m13.148 9.228.383-.923`,key:`t2zzyc`}],[`path`,{d:`m13.53 15.696-.382-.924a3 3 0 1 1-2.296-5.544`,key:`1bxfiv`}],[`path`,{d:`m14.772 10.852.923-.383`,key:`k9m8cz`}],[`path`,{d:`m14.772 13.148.923.383`,key:`1xvhww`}],[`path`,{d:`M4.5 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-.5`,key:`tn8das`}],[`path`,{d:`M4.5 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-.5`,key:`1g2pve`}],[`path`,{d:`M6 18h.01`,key:`uhywen`}],[`path`,{d:`M6 6h.01`,key:`1utrut`}],[`path`,{d:`m9.228 10.852-.923-.383`,key:`1wtb30`}],[`path`,{d:`m9.228 13.148-.923.383`,key:`1a830x`}]]),Hm=Z(`server`,[[`rect`,{width:`20`,height:`8`,x:`2`,y:`2`,rx:`2`,ry:`2`,key:`ngkwjq`}],[`rect`,{width:`20`,height:`8`,x:`2`,y:`14`,rx:`2`,ry:`2`,key:`iecqi9`}],[`line`,{x1:`6`,x2:`6.01`,y1:`6`,y2:`6`,key:`16zg32`}],[`line`,{x1:`6`,x2:`6.01`,y1:`18`,y2:`18`,key:`nzw8ys`}]]),Um=Z(`settings-2`,[[`path`,{d:`M14 17H5`,key:`gfn3mx`}],[`path`,{d:`M19 7h-9`,key:`6i9tg`}],[`circle`,{cx:`17`,cy:`17`,r:`3`,key:`18b49y`}],[`circle`,{cx:`7`,cy:`7`,r:`3`,key:`dfmy0x`}]]),Wm=Z(`shield-check`,[[`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`}]]),Gm=Z(`sliders-horizontal`,[[`path`,{d:`M10 5H3`,key:`1qgfaw`}],[`path`,{d:`M12 19H3`,key:`yhmn1j`}],[`path`,{d:`M14 3v4`,key:`1sua03`}],[`path`,{d:`M16 17v4`,key:`1q0r14`}],[`path`,{d:`M21 12h-9`,key:`1o4lsq`}],[`path`,{d:`M21 19h-5`,key:`1rlt1p`}],[`path`,{d:`M21 5h-7`,key:`1oszz2`}],[`path`,{d:`M8 10v4`,key:`tgpxqk`}],[`path`,{d:`M8 12H3`,key:`a7s4jb`}]]),Km=Z(`sparkles`,[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]]),qm=Z(`square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),Jm=Z(`sun`,[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]),Ym=Z(`test-tube-diagonal`,[[`path`,{d:`M21 7 6.82 21.18a2.83 2.83 0 0 1-3.99-.01a2.83 2.83 0 0 1 0-4L17 3`,key:`1ub6xw`}],[`path`,{d:`m16 2 6 6`,key:`1gw87d`}],[`path`,{d:`M12 16H4`,key:`1cjfip`}]]),Xm=Z(`trash-2`,[[`path`,{d:`M10 11v6`,key:`nco0om`}],[`path`,{d:`M14 11v6`,key:`outv1u`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`,key:`miytrc`}],[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`,key:`e791ji`}]]),Zm=Z(`triangle-alert`,[[`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`}]]),Qm=Z(`unlink`,[[`path`,{d:`m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71`,key:`yqzxt4`}],[`path`,{d:`m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71`,key:`4qinb0`}],[`line`,{x1:`8`,x2:`8`,y1:`2`,y2:`5`,key:`1041cp`}],[`line`,{x1:`2`,x2:`5`,y1:`8`,y2:`8`,key:`14m1p5`}],[`line`,{x1:`16`,x2:`16`,y1:`19`,y2:`22`,key:`rzdirn`}],[`line`,{x1:`19`,x2:`22`,y1:`16`,y2:`16`,key:`ox905f`}]]),$m=Z(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]);function eh(e){return/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(e)||e.startsWith(`//`)}function th(e){return[`localhost`,`127.0.0.1`,`::1`,`[::1]`].includes(e)}function nh(e,t,n){let r=e.trim();if(!r)return{error:`status URL is empty`};let i;try{i=new URL(r,t)}catch{return{error:`status URL is invalid`}}let a=!eh(r),o=th(i.hostname);return!a&&!o?{error:`${n} must be relative or loopback`}:{source:{isLoopback:o,isRelative:a,url:r}}}function rh(e,t){return nh(e,t,`statusUrl`)}function ih(e,t){let n=nh(e,t,`Ops statusUrl`);return n.error?{error:`${n.error}; use showcase mode for public links.`}:n}function ah(e,t,n){let r=new URL(e,n);return r.searchParams.set(`goal_activation`,t),r.toString()}function oh(e,t){if(!t||!e.isLoopback)return null;try{let n=new URL(e.url,window.location.href),r=new URL(t,n.origin);return th(r.hostname)?r.toString():null}catch{return null}}function sh(e,t){return{detailUrl:oh(t,e.local_dashboard_api?.periodic_report_detail_url),indexUrl:oh(t,e.local_dashboard_api?.periodic_report_index_url)}}async function ch(e,t){let n=new URL(e);n.searchParams.set(`goal_id`,t),n.searchParams.set(`limit`,`100`),n.searchParams.set(`offset`,`0`);let r=await fetch(n,{cache:`no-store`});if(!r.ok)throw Error(`HTTP ${r.status} while loading published reports`);return bp.parse(await r.json()).periodic_reports}async function lh(e,t){let n=new URL(e);Object.entries(t).forEach(([e,t])=>n.searchParams.set(e,t));let r=await fetch(n,{cache:`no-store`});if(!r.ok)throw Error(`HTTP ${r.status} while loading published report detail`);return Sp.parse(await r.json()).projection}function uh(e,t,n){let r=e.find(e=>e.agentId===t&&e.available)??e.find(e=>e.agentId===n&&e.available)??e.find(e=>e.available);if(!r)throw Error(`Chat requires at least one available route`);return r}function dh(e){return!!(e&&typeof e==`object`&&e.session_invalidated===!0)}var fh=``.replace(/\/+$/,``);function ph(e){return!fh||/^https?:\/\//.test(e)?e:new URL(e,`${fh}/`).toString()}var mh=J({todo_id:W().nullable(),role:W().nullable(),status:W(),priority:W().nullable(),text:W(),action_kind:W().nullable(),task_class:W().nullable(),claimed_by:W().nullable(),evidence:W().nullable()}),hh=J({goal_id:W(),title:W(),objective:W(),status:W(),waiting_on:W().nullable(),severity:W().nullable(),gate:W(),next_action:W(),top_todo:mh.nullable(),todos:q(mh),evidence:q(W()),quota:J({state:W().nullable(),spent_slots:G().nullable(),allowed_slots:G().nullable(),reason:W().nullable()})});J({ok:K(),schema_version:X(`loopx_chat_status_v0`),selected_goal_id:W().nullable(),goal_count:G(),goals:q(hh)});var gh=J({ok:X(!0),schema_version:Y([`loopx_chat_capabilities_v0`,`loopx_chat_capabilities_v1`]),agent_backend:W(),sandbox:W(),approval_policy:W(),todo_write:W(),goal_subagent_configuration:W().optional(),goal_id:W().nullable(),streaming:K().optional(),resume:K().optional(),interrupt:K().optional(),typed_actions:K().optional(),action_kinds:q(W()).optional(),adapters:q(J({agent_id:W(),display_name:W(),adapter_kind:W(),available:K(),streaming:K(),resume:K(),interrupt:K(),location:W().optional(),source:W().optional(),tool_calls:K().optional(),trust_scope:W().optional()})).optional(),lark_cli:J({available:K(),source:W(),version:W().nullable(),error_code:W().nullable()}).optional()}),_h=J({kind:X(`todo`),text:W(),priority:Y([`P0`,`P1`,`P2`]),rationale:W()}),vh=J({operation:Y([`merge`,`release`,`deploy`,`delete`,`payment`]),target:W().min(1).max(160),summary:W().max(300)}),yh=J({schema_version:X(`loopx_chat_agent_response_v0`),message:W(),proposals:q(_h),protected_action:vh.nullable().optional().default(null),gate:J({kind:W(),summary:W(),next_action:W()}).nullable()}),bh=J({closed:X(!0),ok:X(!0),session_id:W().min(1)});J({dry_run:X(!0),ok:X(!0),preview_id:W().min(1),todo:J({goal_id:W().min(1),text:W(),todo_id:W().optional()})});var xh=J({schema_version:X(`loopx_chat_todo_receipt_v0`),receipt_id:W().min(1),preview_id:W().min(1),goal_id:W().min(1),todo_id:W().min(1),status:X(`applied`),outcome:Y([`todo_added`,`todo_already_exists`]),already_exists:K(),preview_revision:W().nullable()});J({applied:X(!0),ok:X(!0),receipt:xh,todo:J({text:W(),todo_id:W()})});var Sh=J({model_config:J({model:W(),reasoning_effort:W().optional()}).optional(),mode:W(),spawn_allowed:K(),max_children:G().int().nonnegative(),allowed_domains:q(W()).optional().default([])}).passthrough(),Ch=J({ok:X(!0),dry_run:K(),execute:K(),written:K(),changed:K(),goal_id:W().min(1),changed_fields:q(W()),before:J({orchestration:Sh}).passthrough(),after:J({orchestration:Sh}).passthrough(),preview_id:W().min(1),feature_summary:J({multi_subagent:Y([`off`,`enabled`])}).passthrough(),global_sync:J({required:K(),executed:K(),readback:J({status:W(),verified:K()}).passthrough()}).passthrough()}),wh=J({id:W().min(1),outcome:Y([`approved`,`rejected`,`cancelled`]),projectionVerified:K().nullable(),proposal:_h,receipt:xh.nullable()}).superRefine((e,t)=>{e.outcome===`approved`&&!e.receipt&&t.addIssue({code:`custom`,message:`approved decision history requires a Todo receipt`,path:[`receipt`]}),e.outcome!==`approved`&&e.receipt&&t.addIssue({code:`custom`,message:`zero-write decision history must not include a Todo receipt`,path:[`receipt`]})});J({schema_version:X(`loopx_chat_decision_history_v0`),goal_id:W().min(1),decisions:q(wh).max(24)});var Th=class extends Error{payload;constructor(e,t){super(e),this.payload=t}},Eh=Y([`goal.create`,`goal.update`,`goal.lifecycle`,`todo.create`,`todo.update`,`agent.bind`,`heartbeat.bind`,`monitor.create`,`monitor.update`,`gate.resolve`,`run.correct`,`operation.execute`]),Dh=J({schema_version:X(`loopx_operation_envelope_v0`),lifecycle_state:Y([`prepared`,`awaiting_confirmation`,`claimed`,`outcome_observed`]),operation_id:W().min(1),confirmation_digest:W().min(1),payload_digest:W().min(1),projection_digest:W().min(1),expires_at:W().min(1),delivery:gd(W(),id()).nullable(),confirmation:gd(W(),id()).nullable(),claim:gd(W(),id()).nullable(),outcome:gd(W(),id()).nullable()}).passthrough(),Oh=J({schema_version:X(`loopx_chat_action_proposal_v1`),proposal_id:W().min(1),action_kind:Eh,summary:W().min(1),normalized_parameters:gd(W(),id()),context:gd(W(),id()),expected_state_fingerprint:W().min(1),permission_classification:W().min(1),validation_evidence:q(W().refine(e=>e.trim().length>0,`Validation evidence must be non-blank text`)),available_transitions:q(Y([`apply`,`cancel`,`regenerate`,`reject`,`defer`])),status:Y([`preview_ready`,`applying`,`gated`,`failed`,`rejected`,`deferred`,`cancelled`,`stale`,`applied`]),receipt:gd(W(),id()).nullable(),stale:gd(W(),id()).nullable(),gate:gd(W(),id()).nullable().optional(),error:gd(W(),id()).nullable().optional(),checkpoint:gd(W(),id()).nullable().optional(),regenerated_from:W().nullable().optional(),operation:Dh.nullable().optional(),created_at:W(),updated_at:W()}),kh=J({ok:X(!0),proposal:Oh});async function Ah(e){let t=await Ih(`/api/actions/preview`,{method:`POST`,body:JSON.stringify({action_kind:e.actionKind,context:e.context,idempotency_key:e.idempotencyKey,normalized_parameters:e.normalizedParameters,summary:e.summary})});return kh.parse(t).proposal}var jh=J({ok:X(!0),schema_version:X(`loopx_chat_action_list_v1`),proposals:q(Oh)});async function Mh(e={}){let t=new URLSearchParams;e.contextKind&&t.set(`context_kind`,e.contextKind),e.goalId&&t.set(`goal_id`,e.goalId);let n=t.size>0?`?${t.toString()}`:``;return jh.parse(await Ih(`/api/actions${n}`)).proposals}async function Nh(e){let t=await Ih(`/api/actions/${encodeURIComponent(e)}/apply`,{method:`POST`,body:`{}`});return J({ok:X(!0),proposal:Oh,turn:gd(W(),id()).nullable().optional()}).parse(t)}async function Ph(e){return kh.parse(await Ih(`/api/actions/${encodeURIComponent(e)}/cancel`,{method:`POST`,body:`{}`})).proposal}async function Fh(e,t){return kh.parse(await Ih(`/api/actions/${encodeURIComponent(e)}/${t}`,{method:`POST`,body:`{}`})).proposal}async function Ih(e,t){let n;try{n=await fetch(ph(e),{cache:`no-store`,...t,headers:{"Content-Type":`application/json`,...t?.headers}})}catch{throw new Th(`无法连接 LoopX Chat 服务。请确认 Dashboard 与 Chat 服务已启动且来自同一版本。`,{error_code:`chat_api_unavailable`})}let r=await n.text(),i=null;if(r.trim())try{i=JSON.parse(r)}catch{i=null}let a=i&&typeof i==`object`&&!Array.isArray(i)?i:{};if(!n.ok){let e=(a.proposal&&typeof a.proposal==`object`?a.proposal:null)?.status===`stale`?`来源状态已变化,请重新生成预览。`:null,t=n.status>=500?`LoopX Chat 服务暂时不可用(HTTP ${n.status})。请确认 Dashboard 与 Chat 服务已启动且来自同一版本。`:`LoopX Chat 请求失败(HTTP ${n.status})。`;throw new Th(e??String(a.error||t),Object.keys(a).length?a:{error_code:`chat_api_unavailable`,http_status:n.status})}if(i===null)throw new Th(`LoopX Chat 服务返回了无法识别的响应(HTTP ${n.status})。请确认 Dashboard 与 Chat 服务来自同一版本。`,{error_code:`invalid_chat_api_response`,http_status:n.status});return i}async function Lh(){return gh.parse(await Ih(`/api/chat/capabilities`))}async function Rh(e){return Ih(`/api/chat/projection-messages`,{method:`POST`,body:JSON.stringify({answer:e.answer,context_kind:e.contextKind,goal_id:e.goalId,question:e.question})})}async function zh(e,t=`codex`,n=`resume_latest`,r=`goal`){return Ih(`/api/chat/sessions`,{method:`POST`,body:JSON.stringify({goal_id:e,agent_id:t,mode:n,context_kind:r})})}async function Bh(e){return Ih(`/api/chat/sessions/${e}`)}async function Vh(e){let t=new URLSearchParams;return e.agentId&&t.set(`agent_id`,e.agentId),e.channelId&&t.set(`channel_id`,e.channelId),e.goalId&&t.set(`goal_id`,e.goalId),Ih(`/api/chat/sessions?${t.toString()}`)}function Hh(e){let t=new Map;for(let n of e)for(let e of n.messages)t.set(e.message_id,e);return[...t.values()].sort((e,t)=>e.created_at.localeCompare(t.created_at)||e.message_id.localeCompare(t.message_id))}async function Uh(e){let t=await Vh(e),n=await Promise.all(t.sessions.map(e=>Bh(e.session_id)));return{messages:Hh(n),sessions:t.sessions,snapshots:n}}async function Wh(e,t,n,r=[]){return Ih(`/api/chat/sessions/${e}/turns`,{method:`POST`,body:JSON.stringify({message:t,client_turn_id:n,...r.length?{attachments:r.map(e=>({data_url:e.dataUrl,id:e.id,mime_type:e.mimeType,name:e.name,size:e.size}))}:{}})})}function Gh(e){let t=e.split(` +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function kl(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Ml(t,`input`,e.processors),output:Ml(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function Al(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return Al(r.element,n);if(r.type===`set`)return Al(r.valueType,n);if(r.type===`lazy`)return Al(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return Al(r.innerType,n);if(r.type===`intersection`)return Al(r.left,n)||Al(r.right,n);if(r.type===`record`||r.type===`map`)return Al(r.keyType,n)||Al(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:Al(r.in,n)||Al(r.out,n);if(r.type===`object`){for(let e in r.shape)if(Al(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(Al(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(Al(e,n))return!0;return!!(r.rest&&Al(r.rest,n))}return!1}var jl=(e,t={})=>n=>{let r=El({...n,processors:t});return Dl(e,r),Ol(r,e),kl(r,e)},Ml=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=El({...i??{},target:a,io:t,processors:n});return Dl(e,o),Ol(o,e),kl(o,e)},Nl={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Pl=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Nl[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Fl=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},Il=(e,t,n,r)=>{n.type=`boolean`},Ll=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Rl=(e,t,n,r)=>{n.not={}},zl=(e,t,n,r)=>{let i=e._zod.def,a=ra(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Bl=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Vl=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Hl=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Ul=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=Dl(a.element,t,{...r,path:[...r.path,`items`]})},Wl=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=Dl(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Dl(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Gl=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>Dl(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Kl=(e,t,n,r)=>{let i=e._zod.def,a=Dl(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=Dl(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},ql=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>Dl(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?Dl(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},Jl=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=Dl(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=Dl(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=Dl(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},Yl=(e,t,n,r)=>{let i=e._zod.def,a=Dl(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Xl=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Zl=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Ql=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},$l=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},eu=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;Dl(o,t,r);let s=t.seen.get(e);s.ref=o},tu=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},nu=(e,t,n,r)=>{let i=e._zod.def;Dl(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ru=H(`ZodISODateTime`,(e,t)=>{gs.init(e,t),ju.init(e,t)});function iu(e){return Kc(ru,e)}var au=H(`ZodISODate`,(e,t)=>{_s.init(e,t),ju.init(e,t)});function ou(e){return qc(au,e)}var su=H(`ZodISOTime`,(e,t)=>{vs.init(e,t),ju.init(e,t)});function cu(e){return Jc(su,e)}var lu=H(`ZodISODuration`,(e,t)=>{ys.init(e,t),ju.init(e,t)});function uu(e){return Yc(lu,e)}var du=(e,t)=>{Ba.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Ua(e,t)},flatten:{value:t=>Ha(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,ia,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,ia,2)}},isEmpty:{get(){return e.issues.length===0}}})},fu=H(`ZodError`,du),pu=H(`ZodError`,du,{Parent:Error}),mu=Wa(pu),hu=Ga(pu),gu=Ka(pu),_u=Ja(pu),vu=Xa(pu),yu=Za(pu),bu=Qa(pu),xu=$a(pu),Su=eo(pu),Cu=to(pu),wu=no(pu),Tu=ro(pu),Eu=new WeakMap;function Du(e,t,n){let r=Object.getPrototypeOf(e),i=Eu.get(r);if(i||(i=new Set,Eu.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var Ou=H(`ZodType`,(e,t)=>(ns.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Ml(e,`input`),output:Ml(e,`output`)}}),e.toJSONSchema=jl(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>mu(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>gu(e,t,n),e.parseAsync=async(t,n)=>hu(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>_u(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>vu(e,t,n),e.decode=(t,n)=>yu(e,t,n),e.encodeAsync=async(t,n)=>bu(e,t,n),e.decodeAsync=async(t,n)=>xu(e,t,n),e.safeEncode=(t,n)=>Su(e,t,n),e.safeDecode=(t,n)=>Cu(e,t,n),e.safeEncodeAsync=async(t,n)=>wu(e,t,n),e.safeDecodeAsync=async(t,n)=>Tu(e,t,n),Du(e,`ZodType`,{check(...e){let t=this.def;return this.clone(fa(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Sa(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Bd(e,t))},superRefine(e,t){return this.check(Vd(e,t))},overwrite(e){return this.check(gl(e))},optional(){return Sd(this)},exactOptional(){return wd(this)},nullable(){return Ed(this)},nullish(){return Sd(Ed(this))},nonoptional(e){return Md(this,e)},array(){return q(this)},or(e){return ud([this,e])},and(e){return fd(this,e)},transform(e){return Id(this,bd(e))},default(e){return Od(this,e)},prefault(e){return Ad(this,e)},catch(e){return Pd(this,e)},pipe(e){return Id(this,e)},readonly(){return Rd(this)},describe(e){let t=this.clone();return Sc.add(t,{description:e}),t},meta(...e){if(e.length===0)return Sc.get(this);let t=this.clone();return Sc.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return Sc.get(e)?.description},configurable:!0}),e)),ku=H(`_ZodString`,(e,t)=>{rs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pl(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Du(e,`_ZodString`,{regex(...e){return this.check(ul(...e))},includes(...e){return this.check(pl(...e))},startsWith(...e){return this.check(ml(...e))},endsWith(...e){return this.check(hl(...e))},min(...e){return this.check(cl(...e))},max(...e){return this.check(sl(...e))},length(...e){return this.check(ll(...e))},nonempty(...e){return this.check(cl(1,...e))},lowercase(e){return this.check(dl(e))},uppercase(e){return this.check(fl(e))},trim(){return this.check(vl())},normalize(...e){return this.check(_l(...e))},toLowerCase(){return this.check(yl())},toUpperCase(){return this.check(bl())},slugify(){return this.check(xl())}})}),Au=H(`ZodString`,(e,t)=>{rs.init(e,t),ku.init(e,t),e.email=t=>e.check(wc(Mu,t)),e.url=t=>e.check(Ac(Fu,t)),e.jwt=t=>e.check(Gc(Xu,t)),e.emoji=t=>e.check(jc(Iu,t)),e.guid=t=>e.check(Tc(Nu,t)),e.uuid=t=>e.check(Ec(Pu,t)),e.uuidv4=t=>e.check(Dc(Pu,t)),e.uuidv6=t=>e.check(Oc(Pu,t)),e.uuidv7=t=>e.check(kc(Pu,t)),e.nanoid=t=>e.check(Mc(Lu,t)),e.guid=t=>e.check(Tc(Nu,t)),e.cuid=t=>e.check(Nc(Ru,t)),e.cuid2=t=>e.check(Pc(zu,t)),e.ulid=t=>e.check(Fc(Bu,t)),e.base64=t=>e.check(Hc(qu,t)),e.base64url=t=>e.check(Uc(Ju,t)),e.xid=t=>e.check(Ic(Vu,t)),e.ksuid=t=>e.check(Lc(Hu,t)),e.ipv4=t=>e.check(Rc(Uu,t)),e.ipv6=t=>e.check(zc(Wu,t)),e.cidrv4=t=>e.check(Bc(Gu,t)),e.cidrv6=t=>e.check(Vc(Ku,t)),e.e164=t=>e.check(Wc(Yu,t)),e.datetime=t=>e.check(iu(t)),e.date=t=>e.check(ou(t)),e.time=t=>e.check(cu(t)),e.duration=t=>e.check(uu(t))});function W(e){return Cc(Au,e)}var ju=H(`ZodStringFormat`,(e,t)=>{is.init(e,t),ku.init(e,t)}),Mu=H(`ZodEmail`,(e,t)=>{ss.init(e,t),ju.init(e,t)}),Nu=H(`ZodGUID`,(e,t)=>{as.init(e,t),ju.init(e,t)}),Pu=H(`ZodUUID`,(e,t)=>{os.init(e,t),ju.init(e,t)}),Fu=H(`ZodURL`,(e,t)=>{cs.init(e,t),ju.init(e,t)}),Iu=H(`ZodEmoji`,(e,t)=>{ls.init(e,t),ju.init(e,t)}),Lu=H(`ZodNanoID`,(e,t)=>{us.init(e,t),ju.init(e,t)}),Ru=H(`ZodCUID`,(e,t)=>{ds.init(e,t),ju.init(e,t)}),zu=H(`ZodCUID2`,(e,t)=>{fs.init(e,t),ju.init(e,t)}),Bu=H(`ZodULID`,(e,t)=>{ps.init(e,t),ju.init(e,t)}),Vu=H(`ZodXID`,(e,t)=>{ms.init(e,t),ju.init(e,t)}),Hu=H(`ZodKSUID`,(e,t)=>{hs.init(e,t),ju.init(e,t)}),Uu=H(`ZodIPv4`,(e,t)=>{bs.init(e,t),ju.init(e,t)}),Wu=H(`ZodIPv6`,(e,t)=>{xs.init(e,t),ju.init(e,t)}),Gu=H(`ZodCIDRv4`,(e,t)=>{Ss.init(e,t),ju.init(e,t)}),Ku=H(`ZodCIDRv6`,(e,t)=>{Cs.init(e,t),ju.init(e,t)}),qu=H(`ZodBase64`,(e,t)=>{Ts.init(e,t),ju.init(e,t)}),Ju=H(`ZodBase64URL`,(e,t)=>{Ds.init(e,t),ju.init(e,t)}),Yu=H(`ZodE164`,(e,t)=>{Os.init(e,t),ju.init(e,t)}),Xu=H(`ZodJWT`,(e,t)=>{As.init(e,t),ju.init(e,t)}),Zu=H(`ZodNumber`,(e,t)=>{js.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fl(e,t,n,r),Du(e,`ZodNumber`,{gt(e,t){return this.check(il(e,t))},gte(e,t){return this.check(al(e,t))},min(e,t){return this.check(al(e,t))},lt(e,t){return this.check(nl(e,t))},lte(e,t){return this.check(rl(e,t))},max(e,t){return this.check(rl(e,t))},int(e){return this.check($u(e))},safe(e){return this.check($u(e))},positive(e){return this.check(il(0,e))},nonnegative(e){return this.check(al(0,e))},negative(e){return this.check(nl(0,e))},nonpositive(e){return this.check(rl(0,e))},multipleOf(e,t){return this.check(ol(e,t))},step(e,t){return this.check(ol(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function G(e){return Xc(Zu,e)}var Qu=H(`ZodNumberFormat`,(e,t)=>{Ms.init(e,t),Zu.init(e,t)});function $u(e){return Zc(Qu,e)}var ed=H(`ZodBoolean`,(e,t)=>{Ns.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Il(e,t,n,r)});function K(e){return Qc(ed,e)}var td=H(`ZodNull`,(e,t)=>{Ps.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ll(e,t,n,r)});function nd(e){return $c(td,e)}var rd=H(`ZodUnknown`,(e,t)=>{Fs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function id(){return el(rd)}var ad=H(`ZodNever`,(e,t)=>{Is.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rl(e,t,n,r)});function od(e){return tl(ad,e)}var sd=H(`ZodArray`,(e,t)=>{Rs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ul(e,t,n,r),e.element=t.element,Du(e,`ZodArray`,{min(e,t){return this.check(cl(e,t))},nonempty(e){return this.check(cl(1,e))},max(e,t){return this.check(sl(e,t))},length(e,t){return this.check(ll(e,t))},unwrap(){return this.element}})});function q(e,t){return Sl(sd,e,t)}var cd=H(`ZodObject`,(e,t)=>{Us.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wl(e,t,n,r),ua(e,`shape`,()=>t.shape),Du(e,`ZodObject`,{keyof(){return Y(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:id()})},loose(){return this.clone({...this._zod.def,catchall:id()})},strict(){return this.clone({...this._zod.def,catchall:od()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Da(this,e)},safeExtend(e){return Oa(this,e)},merge(e){return ka(this,e)},pick(e){return Ta(this,e)},omit(e){return Ea(this,e)},partial(...e){return Aa(xd,this,e[0])},required(...e){return ja(jd,this,e[0])}})});function J(e,t){return new cd({type:`object`,shape:e??{},...U(t)})}var ld=H(`ZodUnion`,(e,t)=>{Gs.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gl(e,t,n,r),e.options=t.options});function ud(e,t){return new ld({type:`union`,options:e,...U(t)})}var dd=H(`ZodIntersection`,(e,t)=>{Ks.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kl(e,t,n,r)});function fd(e,t){return new dd({type:`intersection`,left:e,right:t})}var pd=H(`ZodTuple`,(e,t)=>{Ys.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ql(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function md(e,t,n){let r=t instanceof ns;return new pd({type:`tuple`,items:e,rest:r?t:null,...U(r?n:t)})}var hd=H(`ZodRecord`,(e,t)=>{$s.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jl(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function gd(e,t,n){return!t||!t._zod?new hd({type:`record`,keyType:W(),valueType:e,...U(t)}):new hd({type:`record`,keyType:e,valueType:t,...U(n)})}var _d=H(`ZodEnum`,(e,t)=>{ec.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zl(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new _d({...t,checks:[],...U(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new _d({...t,checks:[],...U(r),entries:i})}});function Y(e,t){return new _d({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...U(t)})}var vd=H(`ZodLiteral`,(e,t)=>{tc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bl(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function X(e,t){return new vd({type:`literal`,values:Array.isArray(e)?e:[e],...U(t)})}var yd=H(`ZodTransform`,(e,t)=>{nc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hl(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new ea(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Ra(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Ra(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function bd(e){return new yd({type:`transform`,transform:e})}var xd=H(`ZodOptional`,(e,t)=>{ic.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Sd(e){return new xd({type:`optional`,innerType:e})}var Cd=H(`ZodExactOptional`,(e,t)=>{ac.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wd(e){return new Cd({type:`optional`,innerType:e})}var Td=H(`ZodNullable`,(e,t)=>{oc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ed(e){return new Td({type:`nullable`,innerType:e})}var Dd=H(`ZodDefault`,(e,t)=>{sc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Od(e,t){return new Dd({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ya(t)}})}var kd=H(`ZodPrefault`,(e,t)=>{lc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ql(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ad(e,t){return new kd({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ya(t)}})}var jd=H(`ZodNonOptional`,(e,t)=>{uc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xl(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Md(e,t){return new jd({type:`nonoptional`,innerType:e,...U(t)})}var Nd=H(`ZodCatch`,(e,t)=>{fc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$l(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Pd(e,t){return new Nd({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var Fd=H(`ZodPipe`,(e,t)=>{pc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>eu(e,t,n,r),e.in=t.in,e.out=t.out});function Id(e,t){return new Fd({type:`pipe`,in:e,out:t})}var Ld=H(`ZodReadonly`,(e,t)=>{hc.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>tu(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Rd(e){return new Ld({type:`readonly`,innerType:e})}var zd=H(`ZodCustom`,(e,t)=>{_c.init(e,t),Ou.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vl(e,t,n,r)});function Bd(e,t={}){return Cl(zd,e,t)}function Vd(e,t){return wl(e,t)}var Hd=e=>typeof e==`string`&&e.trim()?e.trim():null;function Ud(e){let t=e.decision_scope&&typeof e.decision_scope==`object`&&!Array.isArray(e.decision_scope)?e.decision_scope:{},n=Hd(t.kind),r=Hd(t.granularity),i=Hd(t.scope_key),a=Hd(e.superseded_by);return{interaction:e.task_class===`user_gate`?`decision`:`unknown`,lifecycle:a?`superseded`:e.status===`deferred`?`deferred`:e.done===!0||[`done`,`completed`,`closed`,`archived`].includes(String(e.status))?`closed`:e.status===`open`||e.status===`blocked`?`open`:`unknown`,reason:Hd(e.note),evidence:Hd(e.evidence),blocksAgent:Hd(e.blocks_agent),unblocksTodoId:Hd(e.unblocks_todo_id),decisionScope:n&&r&&i?{kind:n,granularity:r,scopeKey:i}:null,supersededBy:a}}function Wd(e,t,n,r){return{...e,sourceId:t,goalTitle:r??e.goalTitle,details:n?e.details:{...e.details??Ud({}),lifecycle:`unavailable`}}}function Gd(e,t){return t.find(t=>t.sourceId===e.sourceId&&t.goalId===e.goalId&&t.todoId===e.todoId)||{...e,details:{...e.details??Ud({}),lifecycle:`unavailable`}}}function Kd(e,t){let n=e.details?.supersededBy;if(!(!n||n===e.todoId||e.details?.lifecycle===`unavailable`))return t.find(t=>t.sourceId===e.sourceId&&t.goalId===e.goalId&&t.todoId===n)}function qd(e){return![`closed`,`deferred`,`superseded`,`unavailable`].includes(e.details?.lifecycle??`unknown`)}var Jd={ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,runtime_root:`$HOME/.codex/loopx`,goal_count:1,run_count:8440,status_contract:{schema_version:2,minimum_dashboard_schema_version:2,producer:`loopx status`,reload_hint:`scripts/macos-dashboard-launchagent.sh restart`},usage_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.471166+00:00`,sample_run_count:20,proxy_note:`run-history proxy; excludes token counts and raw thread logs`,totals:{runs_24h:20,runs_7d:20,quota_spend_slots_24h:11,quota_spend_slots_7d:11,automation_run_count_24h:11,automation_run_count_7d:11,progress_signal_run_count_24h:9,progress_signal_run_count_7d:9},goals:[{goal_id:`loopx-meta`,runs_24h:20,runs_7d:20,quota_spend_slots_24h:11,quota_spend_slots_7d:11,automation_run_count_24h:11,automation_run_count_7d:11,progress_signal_run_count_24h:9,progress_signal_run_count_7d:9,project_share_24h:1}]},event_ledger_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.360662+00:00`,sample_run_count:20,proxy_note:`append-only run-history projection; compact event-class counts only`,event_classes:[`accounting`,`decision`,`evidence`,`state`,`work`],totals:{events_24h:20,events_7d:20,by_class_24h:{accounting:11,decision:0,evidence:0,state:0,work:9},by_class_7d:{accounting:11,decision:0,evidence:0,state:0,work:9}},goals:[{goal_id:`loopx-meta`,events_24h:20,events_7d:20,by_class_24h:{accounting:11,decision:0,evidence:0,state:0,work:9},by_class_7d:{accounting:11,decision:0,evidence:0,state:0,work:9},latest_event_class:`accounting`,latest_event_at:`2026-07-06T14:37:32+08:00`}]},promotion_readiness_summary:{available:!0,source:`run_history_full_scan`,goal_id:`loopx-meta`,generated_at:`2026-07-05T20:02:02+08:00`,classification:`canary_promotion_readiness_smoke_group`,delivery_batch_scale:`multi_surface`,delivery_outcome:`primary_goal_outcome`,recommended_action:`Canary promotion-readiness smoke passed; promotion may proceed after doctor/status reports fresh evidence.`,json_exists:!0,markdown_exists:!0,freshness_window_hours:24,freshness_status:`fresh`,is_fresh:!0,requires_readiness_run:!1,age_seconds:67624,age_hours:18.78,freshness_reference_time:`2026-07-06T06:49:06.408527+00:00`,sample_run_count:0,proxy_note:`canary promotion-readiness projection from append-only run history; exact evidence stays in run artifacts`},promotion_gate:{ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,runtime_root:`$HOME/.codex/loopx`,gate:`promotion_readiness`,gate_state:`ready`,can_promote:!0,should_warn:!1,non_blocking:!0,recommended_action:`promotion readiness is fresh`,readiness:{available:!0,goal_id:`loopx-meta`,generated_at:`2026-07-05T20:02:02+08:00`,classification:`canary_promotion_readiness_smoke_group`,delivery_batch_scale:`multi_surface`,delivery_outcome:`primary_goal_outcome`,recommended_action:`Canary promotion-readiness smoke passed; promotion may proceed after doctor/status reports fresh evidence.`,json_exists:!0,markdown_exists:!0,runtime_root:`$HOME/.codex/loopx`,freshness_window_hours:24,freshness_status:`fresh`,is_fresh:!0,requires_readiness_run:!1,age_seconds:67624,age_hours:18.78,freshness_reference_time:`2026-07-06T06:49:06.471087+00:00`}},decision_freshness_summary:{available:!0,source:`run_history`,generated_at:`2026-07-06T06:49:06.471133+00:00`,sample_run_count:20,window_days:7,proxy_note:`checkpointed decision freshness projection; rebase old decisions at the decision point before reuse`,summary:{decision_count:0,stale_count:0,rebase_required_count:0,fresh_count:0},items:[]},todo_index:JSON.parse(`{"schema_version":"todo_index_v0","source":"live_loopx_status_public_slice","total_count":12,"current_projected_count":12,"rollout_event_count":94,"item_limit":12,"items":[{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo update recorded for todo_1596c3a678bb","schema_version":"todo_index_item_v0","todo_id":"todo_1596c3a678bb","role":"agent","status":"open","title":"todo update recorded for todo_1596c3a678bb","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:33:32Z","latest_event_status":"open","event_count":7,"event_kinds":["todo_update"]},{"goal_id":"loopx-meta","index":24,"done":false,"text":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","schema_version":"todo_index_item_v0","todo_id":"todo_15bc0926a494","role":"agent","status":"open","priority":"P0-REVENUE MONITOR","title":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"github_public_reply_metadata_monitor","claimed_by":"codex-value-explorer","evidence":"autonomous replan: bounded current value-explorer monitor lane with explicit expires_at.","note":"Set bounded watch expiry for metadata-only public reply monitor; no catch-up after expiry.","updated_at":"2026-07-05T06:27:15+08:00"},{"goal_id":"loopx-meta","index":17,"done":false,"text":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","schema_version":"todo_index_item_v0","todo_id":"todo_2bf560b48a0c","role":"agent","status":"open","priority":"P0","title":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"legacy_open_pr_rename_blocker","claimed_by":"codex-main-control"},{"goal_id":"loopx-meta","index":23,"done":false,"text":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","schema_version":"todo_index_item_v0","todo_id":"todo_3ed1c4a69164","role":"agent","status":"open","priority":"P0","title":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"skillsbench_local_verifier_reward_collection","claimed_by":"codex-main-control","required_capabilities":["benchmark_runner"]},{"goal_id":"loopx-meta","index":32,"done":false,"text":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","schema_version":"todo_index_item_v0","todo_id":"todo_44907a5f355d","role":"agent","status":"blocked","priority":"P0","title":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_raw_new_rerun","claimed_by":"codex-main-control","evidence":"Public-safe redacted live LoopX text; inspect local status for the full row.","note":"Do not spend a full citation-check loopx rerun yet: #865 fixed scored output paths and #874 added bootstrap preflight attribution, but citation-check itself still preflights as apt+verifier bootstrap risk on ECS.","updated_at":"2026-06-29T00:49:36+08:00"},{"goal_id":"loopx-meta","index":39,"done":false,"text":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","schema_version":"todo_index_item_v0","todo_id":"todo_4762c790e583","role":"agent","status":"blocked","priority":"P0","title":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_remote_rerun","claimed_by":"codex-main-control","evidence":"A prior benchmark adapter change was validated before the legacy surface was archived. Current research uses the RFC-linked benchmark workspace and toolkit boundary smokes.","note":"2026-06-29: fixed host-local ACP idle/no-output root cause in PR #894. ACP protocol tool_call_count=0 is now distinguished from reverse-channel task-facing bridge activity; repeated codex_exec_bridge_idle_timeout withou…","updated_at":"2026-06-29T19:40:32+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_584f55f8f3b4","schema_version":"todo_index_item_v0","todo_id":"todo_584f55f8f3b4","role":"agent","status":"open","title":"todo add recorded for todo_584f55f8f3b4","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:48:49Z","latest_event_status":"open","event_count":3,"event_kinds":["todo_add","todo_update"]},{"goal_id":"loopx-meta","index":40,"done":false,"text":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","schema_version":"todo_index_item_v0","todo_id":"todo_62debf065fec","role":"agent","status":"blocked","priority":"P0 MONITOR","title":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"monitor_skillsbench_batch","claimed_by":"codex-main-control","evidence":"Observed 2026-06-30T02:52+08: active-state target_key=skillsbench-goal-baseline-30case-20260629T1826Z-r10; local ps/tmux/recent artifact search found no r10 batch process or compact artifact; no raw task/log/trajectory …","updated_at":"2026-06-30T02:54:54+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_93bc6439c521","schema_version":"todo_index_item_v0","todo_id":"todo_93bc6439c521","role":"agent","status":"open","title":"todo add recorded for todo_93bc6439c521","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_claim","latest_event_at":"2026-07-06T06:32:52Z","latest_event_status":"open","event_count":2,"event_kinds":["todo_add","todo_claim"]},{"goal_id":"loopx-meta","index":27,"done":false,"text":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","schema_version":"todo_index_item_v0","todo_id":"todo_aad7e9716927","role":"agent","status":"blocked","priority":"P0","title":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"run_goal_start_product_mode_matrix","claimed_by":"codex-main-control","evidence":"driver.status shows DONE raw then RUN loopx-goal-start with no running driver; raw benchmark_run.compact first_blocker=skillsbench_codex_acp_provider_zero_activity; source guard requires --host-local-acp-launch for Loop…","note":"Remote run group skillsbench-raw-new-goal-start-20260627T0420Z produced a material closeout for citation-check raw only; raw compact attribution is skillsbench_codex_acp_provider_zero_activity with official score missin…","updated_at":"2026-06-27T13:05:47+08:00"},{"goal_id":"loopx-meta","index":21,"done":false,"text":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","schema_version":"todo_index_item_v0","todo_id":"todo_aec1873c7f28","role":"agent","status":"open","priority":"P0 MONITOR","title":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","claimed_by":"codex-main-control","note":"2026-06-23 projection fix: this is monitor context for the powerlifting run, not an advancement next action; current executable path is SkillsBench build cache/prewarm repair.","updated_at":"2026-06-23T10:37:43+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_c02cb7d19607","schema_version":"todo_index_item_v0","todo_id":"todo_c02cb7d19607","role":"agent","status":"open","title":"todo add recorded for todo_c02cb7d19607","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_add","latest_event_at":"2026-07-06T03:47:54Z","latest_event_status":"open","event_count":1,"event_kinds":["todo_add"]}]}`),agent_management_projection:{schema_version:`agent_management_projection_v0`,mode:`read_only`,goal_id:`loopx-meta`,generated_at:`2026-07-06T06:49:06Z`,style_hint:null,truth_contract:{todo_is_runtime_work_item:!0,projection_is_writable:!1,introduces_task_runtime:!1,write_api:!1},source_summary:{registered_agent_count:4,projected_agent_count:4,todo_source:`live_loopx_status_public_slice`,public_safe_export:!0},agents:[{agent_id:`codex-main-control`,agent_model:`peer_v1`,profile_role:`release-validation`,state:`blocked`,next_action:`Continue projected todo todo_2bf560b48a0c.`,last_activity_at:`2026-06-29T00:49:36+08:00`,evidence_refs:[`todo:todo_e72afc24f04a:evidence`],goal_ids:[`loopx-meta`],stale_claim_hint:{state:`activity_missing`,claimed_by:`codex-main-control`,reason:`claimed open todo has no projected activity timestamp`,recommended_operator_action:`inspect evidence before considering reassignment`},current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_2bf560b48a0c`,goal_id:`loopx-meta`,role:`agent`,status:`open`,priority:`P0`,title:`Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harn…`,task_class:`blocker`,action_kind:`legacy_open_pr_rename_blocker`,claimed_by:`codex-main-control`}},{agent_id:`codex-product-capability`,agent_model:`peer_v1`,profile_role:`product-validation`,state:`monitoring`,next_action:`Continue projected todo todo_ded745761822.`,last_activity_at:`2026-07-06T06:29:53Z`,evidence_refs:[`todo:todo_ded745761822:evidence`],goal_ids:[`loopx-meta`],current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_ded745761822`,goal_id:`loopx-meta`,role:`agent`,status:`open`,priority:`P0-LOCAL`,title:`Public-safe redacted live LoopX text; inspect local status for the full row.`,task_class:`continuous_monitor`,action_kind:`Public-safe redacted live LoopX text; inspect local status for the full row.`,claimed_by:`codex-product-capability`,updated_at:`2026-07-04T20:22:45+08:00`}},{agent_id:`codex-side-bypass`,agent_model:`peer_v1`,profile_role:`implementation-validation`,state:`waiting`,next_action:`Inspect status projection before taking work.`,last_activity_at:`2026-07-06T06:32:16Z`,evidence_refs:[`rollout_event:todo_complete:todo_22c946938115`],goal_ids:[`loopx-meta`]},{agent_id:`codex-value-explorer`,agent_model:`peer_v1`,profile_role:`value-exploration`,state:`monitoring`,next_action:`Continue projected todo todo_584f55f8f3b4.`,last_activity_at:`2026-07-06T09:39:59+08:00`,evidence_refs:[`rollout_event:todo_update:todo_584f55f8f3b4`],goal_ids:[`loopx-meta`],current_todo:{schema_version:`todo_row_v0`,todo_id:`todo_584f55f8f3b4`,goal_id:`loopx-meta`,role:`agent`,status:`open`,title:`todo add recorded for todo_584f55f8f3b4`}}]},contract:{ok:!0,summary:{errors:0,warnings:1,checks:6},errors:[],warnings:["loopx-meta: duplicate index rows raw=8444 unique=8440 unexpected=3 artifact_identity_collisions=2 artifact_collision_rows=3 reward_overlays=1; inspect with `loopx history --goal-id loopx-meta inspect-index-duplicates`; artifact identity collisions need review…"],checks:[`registry goals checked: 12`,`registry boundary: shared_local_registry push_allowed=False tracked=False ignored=False`,`user-gate scopes checked: 6 open multi-agent gates`,`runtime root resolved: $HOME/.codex/loopx`,`run-history goals=28 runs=10210`,`public boundary scan clean: 1218 files`]},global_registry:{available:!0,ok:!0,registry:`$HOME/.codex/loopx/registry.global.json`,current_registry:`$HOME/.codex/loopx/registry.global.json`,current_registry_is_global:!0,global_goal_count:12,current_goal_count:12,source_registry_count:7,summary:{high:0,action:8,info:0,checks:2,findings:8},findings:[{kind:`source_registry_missing`,severity:`action`,message:"`cc-test` source registry is missing",recommended_action:"reconnect `cc-test` from its project or archive it if the project is obsolete",goal_id:`cc-test`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-test` active state file is missing",recommended_action:"repair `cc-test` state_file or reconnect the project",goal_id:`cc-test`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`cc-tmp` source registry is missing",recommended_action:"reconnect `cc-tmp` from its project or archive it if the project is obsolete",goal_id:`cc-tmp`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-tmp` active state file is missing",recommended_action:"repair `cc-tmp` state_file or reconnect the project",goal_id:`cc-tmp`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`cc-tmp-xdrchpuaul` source registry is missing",recommended_action:"reconnect `cc-tmp-xdrchpuaul` from its project or archive it if the project is obsolete",goal_id:`cc-tmp-xdrchpuaul`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`cc-tmp-xdrchpuaul` active state file is missing",recommended_action:"repair `cc-tmp-xdrchpuaul` state_file or reconnect the project",goal_id:`cc-tmp-xdrchpuaul`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`source_registry_missing`,severity:`action`,message:"`loopx-auto-research-e2e-probe-20260628-2225-goal` source registry is missing",recommended_action:"reconnect `loopx-auto-research-e2e-probe-20260628-2225-goal` from its project or archive it if the project is obsolete",goal_id:`loopx-auto-research-e2e-probe-20260628-2225-goal`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`},{kind:`state_file_missing`,severity:`action`,message:"`loopx-auto-research-e2e-probe-20260628-2225-goal` active state file is missing",recommended_action:"repair `loopx-auto-research-e2e-probe-20260628-2225-goal` state_file or reconnect the project",goal_id:`loopx-auto-research-e2e-probe-20260628-2225-goal`,path:`Public-safe redacted live LoopX text; inspect local status for the full row.`}],checks:[`global registry goals checked: 12`,`global source registries checked: 7`]},attention_queue:JSON.parse(`{"available":true,"item_count":1,"needs_user_or_controller":0,"needs_controller":0,"needs_codex":1,"watching_external_evidence":0,"items":[{"goal_id":"loopx-meta","status":"skillsbench_codex_cli_goal_tail4_keepalive_relaunched","lifecycle_phase":"adapter_inspected","lifecycle_flags":["adapter_inspected"],"waiting_on":"codex","severity":"action","recommended_action":"Monitor run_group skillsbench-codex-cli-goal-xhigh-tail4-keepalive-20260706T143132CST using public compact/public artifacts only; once benchmark_run.compact.json lands for each case, classify launcher/case/solver/verifi…","source":"latest_run","quota":{"compute":1.0,"window_hours":24,"slot_minutes":1,"allowed_slots":1440,"spent_slots":97,"state":"eligible","reason":"1 compute quota; eligible for the next automatic agent turn"},"agent_todos":{"source_section":"Agent Todo","total_count":12,"open_count":12,"done_count":0,"items":[{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo update recorded for todo_1596c3a678bb","schema_version":"todo_index_item_v0","todo_id":"todo_1596c3a678bb","role":"agent","status":"open","title":"todo update recorded for todo_1596c3a678bb","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:33:32Z","latest_event_status":"open","event_count":7,"event_kinds":["todo_update"]},{"goal_id":"loopx-meta","index":24,"done":false,"text":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","schema_version":"todo_index_item_v0","todo_id":"todo_15bc0926a494","role":"agent","status":"open","priority":"P0-REVENUE MONITOR","title":"Monitor ArcticDB #3179 LoopX comment https://github.com/man-group/ArcticDB/issues/3179#issuecomment-4797835630 for metadata-only maintainer reply signal; do not read private material or reply again without owner approva…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"github_public_reply_metadata_monitor","claimed_by":"codex-value-explorer","evidence":"autonomous replan: bounded current value-explorer monitor lane with explicit expires_at.","note":"Set bounded watch expiry for metadata-only public reply monitor; no catch-up after expiry.","updated_at":"2026-07-05T06:27:15+08:00"},{"goal_id":"loopx-meta","index":17,"done":false,"text":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","schema_version":"todo_index_item_v0","todo_id":"todo_2bf560b48a0c","role":"agent","status":"open","priority":"P0","title":"Block direct merge of legacy PR #199 until it is rebased/rewritten onto LoopX: rename goal_harness paths/imports and goal-harness CLI strings to loopx, rerun launch-artifact-handle smoke, and verify it does not reintrod…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"legacy_open_pr_rename_blocker","claimed_by":"codex-main-control"},{"goal_id":"loopx-meta","index":23,"done":false,"text":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","schema_version":"todo_index_item_v0","todo_id":"todo_3ed1c4a69164","role":"agent","status":"open","priority":"P0","title":"Fix or bypass local SkillsBench Docker verifier reward collection before using local fallback for canonical base/test comparison; organize-messy-files base on merged #668 reached final verifier but produced empty verifi…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"blocker","action_kind":"skillsbench_local_verifier_reward_collection","claimed_by":"codex-main-control","required_capabilities":["benchmark_runner"]},{"goal_id":"loopx-meta","index":32,"done":false,"text":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","schema_version":"todo_index_item_v0","todo_id":"todo_44907a5f355d","role":"agent","status":"blocked","priority":"P0","title":"Rerun SkillsBench raw vs loopx-goal-start-product-mode on citation-check and powerlifting with PR #779 merged; inspect compact public counters for soft_verify_exception_continued, probe_operation_count, task-facing solv…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_raw_new_rerun","claimed_by":"codex-main-control","evidence":"Public-safe redacted live LoopX text; inspect local status for the full row.","note":"Do not spend a full citation-check loopx rerun yet: #865 fixed scored output paths and #874 added bootstrap preflight attribution, but citation-check itself still preflights as apt+verifier bootstrap risk on ECS.","updated_at":"2026-06-29T00:49:36+08:00"},{"goal_id":"loopx-meta","index":39,"done":false,"text":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","schema_version":"todo_index_item_v0","todo_id":"todo_4762c790e583","role":"agent","status":"blocked","priority":"P0","title":"Run the next SkillsBench loopx-goal-start-product-mode reverse-channel case on latest main (no local Docker), prioritizing a currently bad or uncertain case, then update the public case ledger and true LoopX issue analy…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"skillsbench_goal_start_remote_rerun","claimed_by":"codex-main-control","evidence":"A prior benchmark adapter change was validated before the legacy surface was archived. Current research uses the RFC-linked benchmark workspace and toolkit boundary smokes.","note":"2026-06-29: fixed host-local ACP idle/no-output root cause in PR #894. ACP protocol tool_call_count=0 is now distinguished from reverse-channel task-facing bridge activity; repeated codex_exec_bridge_idle_timeout withou…","updated_at":"2026-06-29T19:40:32+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_584f55f8f3b4","schema_version":"todo_index_item_v0","todo_id":"todo_584f55f8f3b4","role":"agent","status":"open","title":"todo add recorded for todo_584f55f8f3b4","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_update","latest_event_at":"2026-07-06T06:48:49Z","latest_event_status":"open","event_count":3,"event_kinds":["todo_add","todo_update"]},{"goal_id":"loopx-meta","index":40,"done":false,"text":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","schema_version":"todo_index_item_v0","todo_id":"todo_62debf065fec","role":"agent","status":"blocked","priority":"P0 MONITOR","title":"Monitor r10 SkillsBench 30-case codex-app-server-goal-baseline batch, summarize completed compact results into the common case ledger, and stop/repair if setup/bootstrap creates new non-solver blockers.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","action_kind":"monitor_skillsbench_batch","claimed_by":"codex-main-control","evidence":"Observed 2026-06-30T02:52+08: active-state target_key=skillsbench-goal-baseline-30case-20260629T1826Z-r10; local ps/tmux/recent artifact search found no r10 batch process or compact artifact; no raw task/log/trajectory …","updated_at":"2026-06-30T02:54:54+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_93bc6439c521","schema_version":"todo_index_item_v0","todo_id":"todo_93bc6439c521","role":"agent","status":"open","title":"todo add recorded for todo_93bc6439c521","source":"rollout_event_log","agent_id":"codex-main-control","latest_event_kind":"todo_claim","latest_event_at":"2026-07-06T06:32:52Z","latest_event_status":"open","event_count":2,"event_kinds":["todo_add","todo_claim"]},{"goal_id":"loopx-meta","index":27,"done":false,"text":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","schema_version":"todo_index_item_v0","todo_id":"todo_aad7e9716927","role":"agent","status":"blocked","priority":"P0","title":"Run the SkillsBench two-arm comparison after the goal-start route is countable: raw Codex vs new loopx-goal-start-product-mode, reporting task_score/control_score/time and compact public-safe LoopX todo rollout evidence.","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"advancement_task","action_kind":"run_goal_start_product_mode_matrix","claimed_by":"codex-main-control","evidence":"driver.status shows DONE raw then RUN loopx-goal-start with no running driver; raw benchmark_run.compact first_blocker=skillsbench_codex_acp_provider_zero_activity; source guard requires --host-local-acp-launch for Loop…","note":"Remote run group skillsbench-raw-new-goal-start-20260627T0420Z produced a material closeout for citation-check raw only; raw compact attribution is skillsbench_codex_acp_provider_zero_activity with official score missin…","updated_at":"2026-06-27T13:05:47+08:00"},{"goal_id":"loopx-meta","index":21,"done":false,"text":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","schema_version":"todo_index_item_v0","todo_id":"todo_aec1873c7f28","role":"agent","status":"open","priority":"P0 MONITOR","title":"Observe remote official SkillsBench powerlifting-coef-calc base/test runtime-layer mountfix pair skillsbench-powerlifting-coef-calc-remote-canonical-runtime-mountfix-pair-20260623T022028Z: use compact/public artifacts o…","archive_state":"active","source_section":"Agent Todo","source":"attention_queue","task_class":"continuous_monitor","claimed_by":"codex-main-control","note":"2026-06-23 projection fix: this is monitor context for the powerlifting run, not an advancement next action; current executable path is SkillsBench build cache/prewarm repair.","updated_at":"2026-06-23T10:37:43+08:00"},{"goal_id":"loopx-meta","index":0,"done":false,"text":"todo add recorded for todo_c02cb7d19607","schema_version":"todo_index_item_v0","todo_id":"todo_c02cb7d19607","role":"agent","status":"open","title":"todo add recorded for todo_c02cb7d19607","source":"rollout_event_log","agent_id":"codex-value-explorer","latest_event_kind":"todo_add","latest_event_at":"2026-07-06T03:47:54Z","latest_event_status":"open","event_count":1,"event_kinds":["todo_add"]}]}}]}`),run_history:{available:!0,goal_count:1,run_count:5,goals:[{id:`loopx-meta`,domain:`loopx-platform`,status:`active-read-only`,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`],registry_member:!0,legacy_runtime_goal:!1,adapter_kind:`harness_self_improvement`,adapter_status:`connected-read-only`,index_exists:!0,raw_index_records:8444,unique_runs:8440,quota:{compute:1,window_hours:24,slot_minutes:1,allowed_slots:1440,spent_slots:97,state:`waiting`,reason:`no active Codex-ready work is currently selected`},latest_runs:[{generated_at:`2026-07-06T14:37:32+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-value-explorer`,recommended_action:`审阅 PR #1524 的 Agent Management 面板视觉方向:workspace hint 与 stale claim hint 是否符合预期;确认后允许 codex-value-explorer 自合并。`,health_check:`quota safe-bypass operator gate; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:55+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-main-control`,recommended_action:`[P1] Repair SkillsBench post-run debug gate consistency for countable codex-cli-goal official-zero runs: when attempt_accounting is countable and case_closeout_complete=true, do not project first_blocker=loopx_closeout_…`,health_check:`quota should-run eligible; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:54+08:00`,goal_id:`loopx-meta`,classification:`skillsbench_codex_cli_goal_tail4_keepalive_relaunched`,agent_id:`codex-main-control`,progress_scope:`goal`,delivery_batch_scale:`single_surface`,delivery_outcome:`outcome_progress`,recommended_action:`Monitor run_group skillsbench-codex-cli-goal-xhigh-tail4-keepalive-20260706T143132CST using public compact/public artifacts only; once benchmark_run.compact.json lands for each case, classify launcher/case/solver/verifi…`,health_check:`state_file 1/1; registry_goal 1/1; authority_sources 10`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:33:34+08:00`,goal_id:`loopx-meta`,classification:`quota_slot_spent`,agent_id:`codex-side-bypass`,recommended_action:`[P0] Rerun real KNN visible auto-research after the successor-link fix and verify evaluator completion projects a second-round hypothesis/frontier or explicit completion gate without manual intervention; keep evidence p…`,health_check:`quota should-run eligible; quota slot spend event public-safe`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]},{generated_at:`2026-07-06T14:32:57+08:00`,goal_id:`loopx-meta`,classification:`auto_research_successor_link_fix_merged`,agent_id:`codex-side-bypass`,progress_scope:`agent_lane`,delivery_batch_scale:`implementation`,delivery_outcome:`outcome_progress`,recommended_action:`[P0] Rerun real KNN visible auto-research after the successor-link fix and verify evaluator completion projects a second-round hypothesis/frontier or explicit completion gate without manual intervention; keep evidence p…`,health_check:`state_file 1/1; registry_goal 1/1; authority_sources 0`,json_exists:!0,markdown_exists:!0,lifecycle_phase:`adapter_inspected`,lifecycle_flags:[`adapter_inspected`]}]}]}},Yd=W().nullable(),Xd=J({schema_version:X(`goal_acceptance_observation_projection_v0`),goal_id:W(),read_only:X(!0),acceptance_assessed:X(!1),coverage:Y([`partial`,`unavailable`]),missing_sources:q(W()),truncated:K(),historical_progress:q(J({kind:W(),observed_at:Yd,source:W(),evidence_refs:q(W())})),acceptance_gaps:q(J({kind:W(),owner:Yd,reason:Yd,evidence_required:Yd,observed_at:Yd,source:W()})),guards:q(J({kind:W(),todo_id:Yd,blocks_agent:Yd,owner:Yd,reason:Yd,evidence_required:Yd,decision_scope:Yd})),next_action:Yd,next_action_source:Yd}),Zd=ud([W(),G(),K(),nd()]),Qd=gd(W(),Zd),$d=J({todo_id:W().optional(),priority:W().optional(),status:W(),title:W(),claimed_by:W().optional(),task_class:W().optional(),action_kind:W().optional()}),ef=J({gate_id:W(),kind:W(),status:W(),blocks:q(W()).optional()}),tf=J({todo_id:W().optional(),owner_agent:W().optional(),status:W().optional(),lease_until:W().optional(),write_scope:q(W()).optional()}),nf=J({generated_at:W().optional(),classification:W().optional(),summary:W().optional()}),rf=J({kind:W().optional().default(`warning`),message:ud([W(),q(W())]).optional().default(`compact source warning`)}).passthrough(),af=J({schema_version:X(`goal_channel_projection_v0`),mode:X(`read_only`),goal_id:W(),display_name:W(),generated_at:W().optional().nullable(),latest_status:W(),waiting_on:W(),next_action:W(),source_refs:gd(W(),Zd),decision_frame:J({user_action_required:K(),agent_action_required:K(),quiet_noop_allowed:K()}),quota:Qd,user_todos:q($d).default([]),agent_todos:q($d).default([]),open_gates:q(ef).default([]),active_leases:q(tf).default([]),artifacts:q(Qd).default([]),recent_events:q(nf).default([]),source_warnings:q(rf).default([]),truth_contract:J({event_ledger_is_source_of_truth:K(),projection_is_writable:K(),recompute_rule:W(),write_authority:W()})}),of=J({compute:G().optional().default(1),window_hours:G().optional().default(24),slot_minutes:G().optional().default(1),allowed_slots:G().optional().nullable(),spent_slots:G().optional().default(0),state:W().optional().nullable(),next_eligible_at:W().optional().nullable(),reason:W().optional().nullable(),blocked_action_scope:W().optional().nullable(),focus_wait:K().optional().nullable(),handoff_outcome_floor_block:K().optional().nullable(),safe_bypass_allowed:K().optional().default(!1),safe_bypass_kind:W().optional().nullable(),safe_bypass_policy:W().optional().nullable(),post_handoff_outcome_gap_streak:G().optional().nullable(),outcome_gap_threshold:G().optional().nullable(),must_advance:q(W()).optional().default([]),avoid:q(W()).optional().default([])}).transform(e=>{let t=Math.max(1,e.slot_minutes),n=Math.round(e.window_hours*60*e.compute/t);return{...e,slot_minutes:t,allowed_slots:e.allowed_slots??n}}),sf=J({self_repair:J({enabled:K().optional().default(!1),allow_health_blocker_repair:K().optional().default(!1),allow_waiting_projection_repair:K().optional().default(!1)}).optional().nullable()}).passthrough(),cf=J({model_config:J({model:W(),reasoning_effort:W().optional()}).optional(),mode:W().optional().default(`default`),orchestration_mode:W().optional().nullable(),spawn_allowed:K().optional().default(!1),allowed:K().optional().nullable(),max_children:G().optional().default(0),allowed_domains:q(W()).optional().default([])}).passthrough(),lf=J({label:W().optional().nullable(),path:W(),anchor:W().optional().nullable(),exists:K().optional().default(!1),resolved_path:W().optional().nullable()}),uf=J({index:G(),done:K(),text:W(),schema_version:W().optional().nullable(),todo_id:W().optional().nullable(),role:W().optional().nullable(),status:W().optional().nullable(),resume_when:W().optional().nullable(),resume_ready:K().optional().nullable(),resume_condition:gd(W(),id()).optional().nullable(),priority:W().optional().nullable(),title:W().optional().nullable(),archive_state:W().optional().nullable(),source_section:W().optional().nullable(),task_class:W().optional().nullable(),task_domain:W().optional().nullable(),action_kind:W().optional().nullable(),claimed_by:W().optional().nullable(),required_capabilities:q(W()).optional(),note:W().optional().nullable(),evidence:W().optional().nullable(),updated_at:W().optional().nullable(),review_materials:q(lf).optional().default([])}).passthrough(),df=J({source_section:W().optional().nullable(),total_count:G().optional().default(0),open_count:G().optional().default(0),done_count:G().optional().default(0),advancement_done_count:G().optional(),items:q(uf).optional().default([]),deferred_items:q(uf).optional()}),ff=uf.extend({goal_id:W(),source:W().optional().nullable(),event_count:G().optional().default(0),event_kinds:q(W()).optional().default([]),latest_event_kind:W().optional().nullable(),latest_event_at:W().optional().nullable(),latest_event_status:W().optional().nullable(),agent_id:W().optional().nullable()}).passthrough(),pf=J({schema_version:W().optional().nullable(),source:W().optional().nullable(),total_count:G().optional().default(0),current_projected_count:G().optional().default(0),rollout_event_count:G().optional().default(0),item_limit:G().optional().nullable(),items:q(ff).optional().default([])}),mf=J({kind:W().optional().nullable(),label:W().optional().nullable(),path_safe:K().optional().default(!1),branch:W().optional().nullable(),write_scope:q(W()).optional().default([])}).passthrough(),hf=J({state:W().optional().nullable(),claimed_by:W().optional().nullable(),last_activity_at:W().optional().nullable(),threshold_hours:G().optional().nullable(),reason:W().optional().nullable(),recommended_operator_action:W().optional().nullable()}).passthrough(),gf=J({schema_version:W().optional().nullable(),todo_id:W().optional().nullable(),goal_id:W().optional().nullable(),role:W().optional().nullable(),status:W().optional().nullable(),priority:W().optional().nullable(),title:W().optional().nullable(),task_class:W().optional().nullable(),action_kind:W().optional().nullable(),claimed_by:W().optional().nullable(),required_write_scopes:q(W()).optional().default([]),workspace_ref:mf.optional().nullable()}).passthrough(),_f=J({schema_version:W().optional().nullable(),from_agent:W().optional().nullable(),to_agent:W().optional().nullable(),intent:W().optional().nullable(),summary:W().optional().nullable(),blocker:W().optional().nullable(),suggested_next_action:W().optional().nullable(),evidence_refs:q(W()).optional().default([]),updated_at:W().optional().nullable()}).passthrough(),vf=J({agent_id:W(),role:W().optional().nullable(),state:W().optional().nullable(),current_todo:gf.optional().nullable(),next_action:W().optional().nullable(),last_activity_at:W().optional().nullable(),evidence_refs:q(W()).optional().default([]),handoff_refs:q(W()).optional().default([]),handoff_note:_f.optional().nullable(),workspace_ref:mf.optional().nullable(),stale_claim_hint:hf.optional().nullable(),blocked_on:gf.optional().nullable(),goal_ids:q(W()).optional().default([])}).passthrough(),yf=J({schema_version:W().optional().nullable(),mode:W().optional().nullable(),goal_id:W().optional().nullable(),generated_at:W().optional().nullable(),style_hint:J({preferred:W().optional().nullable(),license_boundary:W().optional().nullable()}).optional().nullable(),truth_contract:J({todo_is_runtime_work_item:K().optional().default(!0),projection_is_writable:K().optional().default(!1),introduces_task_runtime:K().optional().default(!1),write_api:K().optional().default(!1)}).optional().nullable(),source_summary:J({registered_agent_count:G().optional().default(0),projected_agent_count:G().optional().default(0),todo_source:W().optional().nullable()}).optional().nullable(),agents:q(vf).optional().default([])}).passthrough(),bf=J({goal_id:W(),configured:K().optional().default(!1),enabled:K().optional().default(!1),human_gate_auto_notify_enabled:K().optional().default(!1),target_ref:W().optional().nullable(),receipt_count:G().optional().default(0),last_notified_at:W().optional().nullable()}).passthrough(),xf=J({schema_version:W().optional().nullable(),generated_at:W().optional().nullable(),goals:q(bf).optional().default([])}).passthrough(),Sf=J({source_section:W().optional().nullable(),open:G().optional().default(0),done:G().optional().default(0),total:G().optional().default(0),advancement_done_count:G().optional(),next:W().optional().nullable(),next_index:G().optional().nullable(),items:q(uf).optional().default([]),recent_completed_advancement_items:q(uf).optional().default([])}),Cf=J({goal_id:W(),status:W().optional().nullable(),waiting_on:W().optional().nullable(),severity:W().optional().nullable(),index:G().optional().nullable(),text:W(),source:W().optional().nullable()}),wf=J({source:W().optional().nullable(),open_count:G().optional().default(0),items:q(Cf).optional().default([])}),Tf=J({goal_id:W(),status:W().optional().nullable(),waiting_on:W().optional().nullable(),quota_state:W().optional().nullable(),priority:W().optional().nullable(),todo_index:G().optional().nullable(),text:W(),source:W().optional().nullable()}),Ef=J({source:W().optional().nullable(),open_count:G().optional().default(0),items:q(Tf).optional().default([])}),Df=J({generated_at:W().optional().nullable(),classification:W().optional().nullable(),summary:W().optional().nullable()}),Of=J({kind:W().optional().nullable(),source:W().optional().nullable(),severity:W().optional().nullable(),requires_refresh_state:K().optional().default(!1),reason:W().optional().nullable(),active_state_updated_at:W().optional().nullable(),latest_run_generated_at:W().optional().nullable(),latest_run_state_updated_at:W().optional().nullable(),latest_run_classification:W().optional().nullable(),recommended_action:W().optional().nullable()}),kf=J({generated_at:W().optional().nullable(),classification:W().optional().nullable(),delivery_batch_scale:W().optional().nullable(),delivery_outcome:W().optional().nullable(),health_check:W().optional().nullable(),json_exists:K().optional().nullable(),markdown_exists:K().optional().nullable()}),Af=J({project_asset_backed:K().optional(),same_source_should_run:K().optional(),codex_ready:K().optional(),handoff_has_next_action:K().optional(),handoff_has_stop_condition:K().optional(),handoff_sanitized_surface:K().optional()}).catchall(K()),jf=J({ready:K().optional().default(!1),codex_ready:K().optional().default(!1),source:W().optional().nullable(),quota_state:W().optional().nullable(),checks:Af.optional().default({}),handoff_status:W().optional().nullable(),handoff_ready_at:W().optional().nullable(),handoff_ready_classification:W().optional().nullable(),post_handoff_run_seen:K().optional().default(!1),post_handoff_latest_run:kf.optional().nullable(),post_handoff_recent_runs:q(kf).optional().default([]),post_handoff_small_scale_streak:G().int().nonnegative().optional().default(0),post_handoff_outcome_gap_streak:G().int().nonnegative().optional().default(0),next_probe:W().optional().nullable()}),Mf=J({schema_version:W().optional().nullable(),kind:W().optional().nullable(),missing_roles:q(W()).optional().default([]),source:W().optional().nullable(),recommended_action:W().optional().nullable()}),Nf=J({owner:W(),gate:W(),next_action:W(),stop_condition:W(),user_todos:Sf.optional().nullable(),agent_todos:Sf.optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),orchestration:cf.optional().nullable(),latest_validation:Df.optional().nullable(),stale_latest_run_warning:Of.optional().nullable(),todo_projection_gap:Mf.optional().nullable()}),Pf=J({goal_id:W(),activation_state:Y([`active`,`stopped`]).optional().default(`active`),status:W(),waiting_on:W(),severity:W(),recommended_action:W(),project_asset:Nf.optional().nullable(),handoff_readiness:jf.optional().nullable(),source:W().optional(),operator_question:W().optional().nullable(),agent_command:W().optional().nullable(),lifecycle_phase:W().optional().nullable(),lifecycle_flags:q(W()).optional().default([]),controller_stage:W().optional().nullable(),missing_gates:q(W()).optional().default([]),next_handoff_condition:W().optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),user_todos:df.optional().nullable(),agent_todos:df.optional().nullable(),stale_latest_run_warning:Of.optional().nullable(),dependency_blockers:wf.optional().nullable(),todo_state_file:W().optional().nullable(),goal_channel_projection:af.optional().nullable()}),Ff=J({recorded_at:W().optional().nullable(),decision:W().optional().nullable(),reward:W().optional().nullable(),reason_summary:W().optional().nullable(),follow_up:W().optional().nullable()}),If=J({recorded_at:W().optional().nullable(),gate:W().optional().nullable(),decision:W().optional().nullable(),operator_question:W().optional().nullable(),reason_summary:W().optional().nullable(),follow_up:W().optional().nullable(),agent_command:W().optional().nullable()}),Lf=J({version:W().optional().nullable(),goal_id:W().optional().nullable(),run_id:W().optional().nullable(),gate_id:W().optional().nullable(),created_state_ref:W().optional().nullable(),created_policy_version:W().optional().nullable(),interrupt_payload:J({question:W().optional().nullable(),choices:q(W()).optional().default([])}).optional().nullable(),allowed_decisions:q(W()).optional().default([]),operator_decision:W().optional().nullable(),latest_state_ref:W().optional().nullable(),freshness_check:W().optional().nullable(),precondition_check:W().optional().nullable(),migration_or_rebase_result:W().optional().nullable(),resulting_action:W().optional().nullable(),validation_after_resume:W().optional().nullable()}),Rf=J({id:W().optional().nullable(),ok:K().optional().nullable(),review:W().optional().nullable()}),zf=J({classification:W().optional().nullable(),read_only_observer_ready:K().optional().nullable(),decision_advisor_ready:K().optional().nullable(),write_controller_ready:K().optional().nullable(),missing_gates:q(W()).optional().default([]),review_judgment:W().optional().nullable(),next_handoff_condition:W().optional().nullable(),gates:q(Rf).optional().default([])}),Bf=J({declared:K().optional().default(!1),required:K().optional().default(!1),path:W().optional().nullable(),path_exists:K().optional().nullable(),read_status:W().optional().nullable(),default_entry_count:G().optional().default(0),default_entries_checked:G().optional().default(0),default_entries_present:G().optional().default(0),topic_authority_count:G().optional().default(0),project_material_count:G().optional().default(0),project_material_repository_count:G().optional().default(0),project_material_owner_review_required_count:G().optional().default(0),project_material_stale_count:G().optional().default(0),project_material_current_authority_count:G().optional().default(0),deprecated_source_count:G().optional().default(0),conflict_risk:W().optional().nullable()}),Vf=J({adapter_kind:W().optional().nullable(),adapter_status:W().optional().nullable(),authority_source_count:G().optional().nullable(),authority_registry_declared:K().optional().nullable(),authority_registry_path_exists:K().optional().nullable(),authority_registry_default_entry_count:G().optional().nullable(),authority_registry_default_entries_present:G().optional().nullable(),topic_authority_count:G().optional().nullable(),project_material_count:G().optional().nullable(),project_material_repository_count:G().optional().nullable(),project_material_owner_review_required_count:G().optional().nullable(),project_material_stale_count:G().optional().nullable(),project_material_current_authority_count:G().optional().nullable(),authority_registry_conflict_risk:W().optional().nullable(),guard_count:G().optional().nullable(),sections_found:G().optional().nullable(),sections_checked:G().optional().nullable(),files_present:G().optional().nullable(),files_checked:G().optional().nullable()}),Hf=J({generated_at:W(),goal_id:W(),classification:W().optional().nullable(),lifecycle_phase:W().optional().nullable(),lifecycle_flags:q(W()).optional().default([]),recommended_action:W().optional().nullable(),health_check:W().optional().nullable(),active_task_count:G().optional().nullable(),active_priorities:gd(W(),id()).optional().nullable(),cache_check:W().optional().nullable(),json_exists:K().optional().default(!1),markdown_exists:K().optional().default(!1),human_reward:Ff.optional().nullable(),operator_gate:If.optional().nullable(),operator_gate_resume_contract:Lf.optional().nullable(),controller_readiness:zf.optional().nullable(),project_map:Vf.optional().nullable()}),Uf=J({acceptance_observation:Xd.optional().nullable().catch(null),id:W(),activation_state:Y([`active`,`stopped`]).optional().default(`active`),display_name:W().optional().nullable(),domain:W().optional().nullable(),status:W().optional().nullable(),lifecycle_phase:W().optional().nullable(),lifecycle_flags:q(W()).optional().default([]),registry_member:K().optional().default(!1),legacy_runtime_goal:K().optional().default(!1),adapter_kind:W().optional().nullable(),adapter_status:W().optional().nullable(),authority_registry:Bf.optional().nullable(),quota:of.optional().nullable(),control_plane:sf.optional().nullable(),spawn_policy:cf.optional().nullable(),orchestration:cf.optional().nullable(),coordination:J({agent_model:W().optional().nullable(),registered_agents:q(W()).optional().default([])}).optional().nullable(),index_exists:K().optional().default(!1),raw_index_records:G().optional().default(0),unique_runs:G().optional().default(0),latest_runs:q(Hf).optional().default([])}),Wf=J({available:K(),goal_count:G().optional().default(0),run_count:G().optional().default(0),goals:q(Uf).optional().default([]),recent_runs:q(Hf).optional().default([])}),Gf=J({kind:W(),severity:W(),message:W(),recommended_action:W(),goal_id:W().optional().nullable(),path:W().optional().nullable(),goal_ids:q(W()).optional().default([])}),Kf=J({available:K(),ok:K(),registry:W(),current_registry:W().optional().nullable(),current_registry_is_global:K().optional().default(!1),global_goal_count:G().optional().default(0),current_goal_count:G().optional().default(0),source_registry_count:G().optional().default(0),summary:J({high:G().optional().default(0),action:G().optional().default(0),info:G().optional().default(0),checks:G().optional().default(0),findings:G().optional().default(0)}),findings:q(Gf).optional().default([]),checks:q(W()).optional().default([])}),qf=J({runs_24h:G().optional().default(0),runs_7d:G().optional().default(0),quota_spend_slots_24h:G().optional().default(0),quota_spend_slots_7d:G().optional().default(0),automation_run_count_24h:G().optional().default(0),automation_run_count_7d:G().optional().default(0),progress_signal_run_count_24h:G().optional().default(0),progress_signal_run_count_7d:G().optional().default(0),input_tokens_24h:G().optional(),input_tokens_7d:G().optional(),output_tokens_24h:G().optional(),output_tokens_7d:G().optional(),cache_tokens_24h:G().optional(),cache_tokens_7d:G().optional(),cost_usd_24h:G().optional(),cost_usd_7d:G().optional(),duration_ms_24h:G().optional(),duration_ms_7d:G().optional()}),Jf=qf.extend({goal_id:W(),project_share_24h:G().optional().default(0)}),Yf=J({available:K().optional().default(!0),source:W().optional().default(`run_history`),generated_at:W().optional().nullable(),sample_run_count:G().optional().default(0),proxy_note:W().optional().nullable(),totals:qf.optional().default({runs_24h:0,runs_7d:0,quota_spend_slots_24h:0,quota_spend_slots_7d:0,automation_run_count_24h:0,automation_run_count_7d:0,progress_signal_run_count_24h:0,progress_signal_run_count_7d:0}),goals:q(Jf).optional().default([])}).optional().nullable(),Xf=J({accounting:G().optional().default(0),decision:G().optional().default(0),evidence:G().optional().default(0),state:G().optional().default(0),work:G().optional().default(0)}),Zf={accounting:0,decision:0,evidence:0,state:0,work:0},Qf=J({events_24h:G().optional().default(0),events_7d:G().optional().default(0),by_class_24h:Xf.optional().default(Zf),by_class_7d:Xf.optional().default(Zf)}),$f=Qf.extend({goal_id:W(),latest_event_class:W().optional().nullable(),latest_event_at:W().optional().nullable()}),ep={events_24h:0,events_7d:0,by_class_24h:Zf,by_class_7d:Zf},tp=J({available:K().optional().default(!0),source:W().optional().default(`run_history`),generated_at:W().optional().nullable(),sample_run_count:G().optional().default(0),proxy_note:W().optional().nullable(),event_classes:q(W()).optional().default([`accounting`,`decision`,`evidence`,`state`,`work`]),totals:Qf.optional().default(ep),goals:q($f).optional().default([])}).optional().nullable(),np=J({available:K().optional().default(!1),source:W().optional().default(`run_history`),goal_id:W().optional().nullable(),generated_at:W().optional().nullable(),classification:W().optional().nullable(),delivery_batch_scale:W().optional().nullable(),delivery_outcome:W().optional().nullable(),recommended_action:W().optional().nullable(),json_exists:K().optional().default(!1),markdown_exists:K().optional().default(!1),freshness_window_hours:G().optional().default(24),freshness_status:W().optional().nullable(),is_fresh:K().optional().default(!1),requires_readiness_run:K().optional().default(!0),age_seconds:G().optional().nullable(),age_hours:G().optional().nullable(),freshness_reference_time:W().optional().nullable(),sample_run_count:G().optional().default(0),proxy_note:W().optional().nullable(),reason:W().optional().nullable()}).optional().nullable(),rp=J({ok:K().optional().default(!0),registry:W().optional().nullable(),runtime_root:W().optional().nullable(),gate:W().optional().default(`promotion_readiness`),gate_state:W().optional().default(`warning`),can_promote:K().optional().default(!1),should_warn:K().optional().default(!0),non_blocking:K().optional().default(!0),recommended_action:W().optional().nullable(),warning_message:W().optional().nullable(),readiness:np.default(null)}).optional().nullable(),ip=J({decision_count:G().optional().default(0),stale_count:G().optional().default(0),rebase_required_count:G().optional().default(0),fresh_count:G().optional().default(0)}),ap=J({goal_id:W(),decision_kind:W().optional().nullable(),decision_at:W().optional().nullable(),classification:W().optional().nullable(),age_days:G().optional().nullable(),stale_by_age:K().optional().default(!1),newer_event_count_7d:G().optional().default(0),newer_event_classes_7d:Xf.optional().default(Zf),freshness_state:W().optional().nullable(),requires_decision_point_rebase:K().optional().default(!1),reason:W().optional().nullable()}),op=J({available:K().optional().default(!0),source:W().optional().default(`run_history`),generated_at:W().optional().nullable(),sample_run_count:G().optional().default(0),window_days:G().optional().default(7),proxy_note:W().optional().nullable(),summary:ip.optional().default({decision_count:0,stale_count:0,rebase_required_count:0,fresh_count:0}),items:q(ap).optional().default([])}).optional().nullable(),sp=J({schema_version:G().optional().default(0),minimum_dashboard_schema_version:G().optional().default(2),producer:W().optional().nullable(),reload_hint:W().optional().nullable()}).optional().default({schema_version:0,minimum_dashboard_schema_version:2,producer:null,reload_hint:`scripts/macos-dashboard-launchagent.sh restart`}),cp=J({schema_version:X(`loopx_goal_projection_scope_v0`),scope:Y([`all`,`active`,`stopped`]),complete:K(),projected_goal_count:G().int().nonnegative(),registry_goal_count:G().int().nonnegative(),registry_revision:W().optional().nullable()}),lp=J({source:W().optional().default(`serve-status`),status_url:W().optional().nullable(),health_url:W().optional().nullable(),review_material_url:W().optional().nullable(),presentation_surfaces_url:W().optional().nullable(),presentation_detail_url:W().optional().nullable(),periodic_report_index_url:W().optional().nullable(),periodic_report_detail_url:W().optional().nullable(),ssh_hosts_url:W().optional().nullable(),reward_dry_run_url:W().optional().nullable(),reward_append_url:W().optional().nullable(),reward_write_enabled:K().optional().default(!1),configure_goal_dry_run_url:W().optional().nullable(),configure_goal_apply_url:W().optional().nullable(),control_plane_write_enabled:K().optional().default(!1)}).optional().nullable(),up=J({extension_id:W().min(1),surface_id:W().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/),extension_revision:W().min(1),payload_sha256:W().regex(/^[0-9a-f]{64}$/)}).strict(),dp=J({extension_id:W().min(1),extension_revision:W().min(1),surface_id:W().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/),surface_kind:W().regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/),title:W().min(1),view_schema:W().regex(/^[a-z][a-z0-9_]*_v\d+$/),visibility:Y([`public-safe`,`owner-only`]),goal_id:W().min(1).nullable(),generated_at:W().min(1).nullable(),review_due_at:W().min(1).nullable(),diagnostic:W().min(1).nullable(),empty_state_title:W().min(1),empty_state_detail:W().min(1)}),fp=ud([dp.extend({state:Y([`ready`,`review_due`]),goal_id:W().min(1),generated_at:W().min(1),detail_ref:up}).strict(),dp.extend({state:X(`empty`),detail_ref:od().optional()}).strict(),dp.extend({state:X(`invalid`),diagnostic:W().min(1),detail_ref:od().optional()}).strict()]),pp=J({schema_version:X(`extension_presentation_surfaces_v0`),count:G().int().nonnegative(),ready_count:G().int().nonnegative(),review_due_count:G().int().nonnegative(),empty_count:G().int().nonnegative(),invalid_count:G().int().nonnegative(),items:q(fp)}).strict(),mp={schema_version:`extension_presentation_surfaces_v0`,count:0,ready_count:0,review_due_count:0,empty_count:0,invalid_count:0,items:[]};J({ok:X(!0),presentation_surfaces:pp}).strict();var hp=J({goal_id:W().min(1),agent_id:W().min(1),generation_id:W().min(1),content_sha256:W().regex(/^sha256:[0-9a-f]{64}$/)}).strict(),gp=J({goal_id:W().min(1),agent_id:W().min(1),generation_id:W().min(1),publication_id:W().min(1),delivered_at:W().min(1),predecessor_publication_id:W().min(1).nullable().optional(),detail_ref:hp}).strict(),_p=J({schema_version:X(`periodic_report_workspace_index_v0`),count:G().int().nonnegative(),items:q(gp)}),vp=_p.extend({returned_count:G().int().nonnegative(),total_count:G().int().nonnegative(),limit:G().int().nonnegative(),offset:G().int().nonnegative(),truncated:K()}).strict(),yp=_p.strict().transform(e=>({...e,returned_count:e.count,total_count:e.count,limit:e.count,offset:0,truncated:!1})),bp=J({ok:X(!0),periodic_reports:ud([vp,yp])}).strict(),xp=J({schema_version:X(`periodic_report_workspace_projection_v0`),goal_id:W().min(1),agent_id:W().min(1),generation_id:W().min(1),generated_at:W().min(1),title:W().min(1),summary:W().min(1),content_sha256:W().regex(/^sha256:[0-9a-f]{64}$/),period_window:J({start_at:W().min(1),end_at:W().min(1)}).strict(),interaction:J({attention_kind:X(`progress`),interaction:X(`inform`),delivery:X(`surface`),form:X(`milestone_report`),writable:X(!1)}).strict(),delta:J({added_count:G().int().nonnegative(),changed_count:G().int().nonnegative(),item_count:G().int().positive(),items:q(J({fact_id:W().min(1),source_ref:W().min(1),title:W().min(1),summary:W().min(1),status:W().min(1),content_kind:W().min(1),change_kind:Y([`added`,`changed`]),previous_status:W().min(1).optional()}).strict())}).strict(),publication:J({publication_id:W().min(1),delivered_at:W().min(1),predecessor_publication_id:W().min(1).nullable().optional(),cursor_id:W().min(1)}).strict(),truth_contract:J({published_cursor_is_source_of_truth:X(!0),generation_receipt_is_delivery_receipt:X(!1),projection_is_writable:X(!1),browser_write_api:X(!1)}).strict()}).strict(),Sp=J({ok:X(!0),projection:xp}).strict(),Cp=J({ok:K(),registry:W(),runtime_root:W(),goal_count:G(),run_count:G(),status_contract:sp,goal_projection:cp.optional().nullable().default(null),local_dashboard_api:lp,contract:J({ok:K(),summary:J({errors:G(),warnings:G(),checks:G()}),errors:q(W()),warnings:q(W()),checks:q(W()).optional().default([])}),global_registry:Kf.optional().default({available:!1,ok:!0,registry:``,current_registry:null,current_registry_is_global:!1,global_goal_count:0,current_goal_count:0,source_registry_count:0,summary:{high:0,action:0,info:0,checks:0,findings:0},findings:[],checks:[]}),attention_queue:J({available:K(),item_count:G(),needs_user_or_controller:G(),needs_controller:G().optional().default(0),needs_codex:G(),watching_external_evidence:G(),autonomous_backlog_candidates:Ef.optional().nullable(),items:q(Pf)}),run_history:Wf.optional().default({available:!1,goal_count:0,run_count:0,goals:[],recent_runs:[]}),event_ledger_summary:tp.default(null),promotion_readiness_summary:np.default(null),promotion_gate:rp.default(null),decision_freshness_summary:op.default(null),usage_summary:Yf.default(null),todo_index:pf.optional().nullable().default(null),agent_management_projection:yf.optional().nullable().default(null),goal_channel_notification_projection:xf.optional().nullable().default(null),presentation_surfaces:pp.optional().default(mp)});J({ok:K(),dry_run:K().optional().default(!0),appended:K().optional().default(!1),goal_id:W().optional().nullable(),raw_index_records_before:G().optional().nullable(),preview_id:W().optional().nullable(),selected_run:J({generated_at:W().optional().nullable(),classification:W().optional().nullable(),recommended_action:W().optional().nullable(),json_exists:K().optional().nullable(),markdown_exists:K().optional().nullable()}).optional().nullable(),human_reward:Ff.optional().nullable(),active_state_summary:W().optional().nullable(),project_agent_visibility:J({source_of_truth:W().optional().nullable(),history_command:W().optional().nullable(),active_state_role:W().optional().nullable(),review_packet_role:W().optional().nullable()}).optional().nullable(),error:W().optional().nullable()});function wp(e,t,n){let r=e.run_history.goals.map(e=>e.id===t&&e.activation_state!==n?{...e,activation_state:n}:e),i=e.attention_queue.items.map(e=>e.goal_id===t&&e.activation_state!==n?{...e,activation_state:n}:e),a=r.some((t,n)=>t!==e.run_history.goals[n]),o=i.some((t,n)=>t!==e.attention_queue.items[n]);return!a&&!o?e:{...e,attention_queue:o?{...e.attention_queue,items:i}:e.attention_queue,run_history:a?{...e.run_history,goals:r}:e.run_history}}function Tp(e,t){let n=e.run_history.goals.filter(e=>e.id!==t),r=e.attention_queue.items.filter(e=>e.goal_id!==t);return n.length===e.run_history.goals.length&&r.length===e.attention_queue.items.length?e:{...e,attention_queue:{...e.attention_queue,items:r},run_history:{...e.run_history,goals:n}}}function Ep(e){return Cp.parse(e)}function Dp(e){return e instanceof fu?e.issues.map(e=>`${e.path.join(`.`)||`root`}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}var Op=Ep(Jd),kp=J({ok:X(!0),schema_version:X(`loopx_workspace_directory_v1`),registry_revision:W(),goals:q(J({id:W(),display_name:W(),activation_state:Y([`active`,`stopped`]),registry_member:X(!0)}))});function Ap(e,t,n){let r=new URL(e,n);r.searchParams.delete(`goal_activation`),r.searchParams.delete(`goal_id`),r.searchParams.delete(`view`);for(let[e,n]of Object.entries(t))r.searchParams.set(e,n);return r.toString()}async function jp(e,t){let n=await fetch(Ap(e,{view:`workspace-directory`},t),{cache:`no-store`,signal:AbortSignal.timeout(5e3)});if(!n.ok)return null;let r=kp.safeParse(await n.json());return r.success?r.data:null}function Mp(e){return Ep({ok:!0,registry:``,runtime_root:``,goal_count:e.goals.length,run_count:0,local_dashboard_api:{},contract:{ok:!0,summary:{errors:0,warnings:0,checks:0},errors:[],warnings:[]},attention_queue:{available:!1,item_count:0,needs_user_or_controller:0,needs_codex:0,watching_external_evidence:0,items:[]},run_history:{available:!1,goal_count:e.goals.length,run_count:0,goals:e.goals,recent_runs:[]}})}async function Np(e,t,n,r,i,a,o){let s=[...n.goals],c=new Map;async function l(){for(;s.length&&i()&&!o?.aborted;){let l=s.findIndex(e=>e.id===a()),u=l>=0?l:s.findIndex(e=>e.activation_state===`active`);if(u<0)return;let d=s.splice(u,1)[0],f=(c.get(d.id)??0)+1;c.set(d.id,f);let p=new AbortController,m=!1,h=()=>p.abort();o?.addEventListener(`abort`,h,{once:!0});let g=setTimeout(()=>{m=!0,p.abort()},3e4),_=null;try{let a=await fetch(Ap(e,{goal_id:d.id},t),{cache:`no-store`,signal:p.signal});if(!a.ok)_=a.status===409?`revision`:a.status>=500?`service`:`scope`;else{let e=await a.json();if(e.workspace_registry_revision!==n.registry_revision)_=`revision`;else{let t=Ep(e);!t.run_history.goals.some(e=>e.id===d.id)||t.run_history.goals.some(e=>e.id!==d.id)?_=`scope`:i()&&!o?.aborted&&r(d.id,t,null)}}}catch(e){_=m?`timeout`:e instanceof TypeError?`network`:`invalid`}finally{clearTimeout(g),o?.removeEventListener(`abort`,h)}if(!i()||o?.aborted)return;_&&[`timeout`,`network`,`service`].includes(_)&&f<3?(await new Promise(e=>setTimeout(e,f*1e3)),s.push(d)):_&&r(d.id,null,_)}}await Promise.all([l(),l()])}var Pp=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),Fp=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),Ip=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),Lp=e=>{let t=Ip(e);return t.charAt(0).toUpperCase()+t.slice(1)},Rp={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`},zp=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},Bp=(0,z.createContext)({}),Vp=()=>(0,z.useContext)(Bp),Hp=(0,z.forwardRef)(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>{let{size:l=24,strokeWidth:u=2,absoluteStrokeWidth:d=!1,color:f=`currentColor`,className:p=``}=Vp()??{},m=r??d?Number(n??u)*24/Number(t??l):n??u;return(0,z.createElement)(`svg`,{ref:c,...Rp,width:t??l??Rp.width,height:t??l??Rp.height,stroke:e??f,strokeWidth:m,className:Pp(`lucide`,p,i),...!a&&!zp(s)&&{"aria-hidden":`true`},...s},[...o.map(([e,t])=>(0,z.createElement)(e,t)),...Array.isArray(a)?a:[a]])}),Z=(e,t)=>{let n=(0,z.forwardRef)(({className:n,...r},i)=>(0,z.createElement)(Hp,{ref:i,iconNode:t,className:Pp(`lucide-${Fp(Lp(e))}`,`lucide-${e}`,n),...r}));return n.displayName=Lp(e),n},Up=Z(`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`}]]),Wp=Z(`arrow-down`,[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]),Gp=Z(`arrow-left`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]),Kp=Z(`arrow-right`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]),qp=Z(`arrow-up-down`,[[`path`,{d:`m21 16-4 4-4-4`,key:`f6ql7i`}],[`path`,{d:`M17 20V4`,key:`1ejh1v`}],[`path`,{d:`m3 8 4-4 4 4`,key:`11wl7u`}],[`path`,{d:`M7 4v16`,key:`1glfcx`}]]),Jp=Z(`arrow-up`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),Yp=Z(`badge-check`,[[`path`,{d:`M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z`,key:`3c2336`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),Xp=Z(`bell`,[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}]]),Zp=Z(`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`}]]),Qp=Z(`braces`,[[`path`,{d:`M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1`,key:`ezmyqa`}],[`path`,{d:`M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1`,key:`e1hn23`}]]),$p=Z(`calendar-clock`,[[`path`,{d:`M16 14v2.2l1.6 1`,key:`fo4ql5`}],[`path`,{d:`M16 2v4`,key:`4m81vk`}],[`path`,{d:`M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5`,key:`1osxxc`}],[`path`,{d:`M3 10h5`,key:`r794hk`}],[`path`,{d:`M8 2v4`,key:`1cmpym`}],[`circle`,{cx:`16`,cy:`16`,r:`6`,key:`qoo3c4`}]]),em=Z(`check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),tm=Z(`chevron-down`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),nm=Z(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),rm=Z(`chevron-up`,[[`path`,{d:`m18 15-6-6-6 6`,key:`153udz`}]]),im=Z(`circle-alert`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`12`,x2:`12`,y1:`8`,y2:`12`,key:`1pkeuh`}],[`line`,{x1:`12`,x2:`12.01`,y1:`16`,y2:`16`,key:`4dfq90`}]]),am=Z(`circle-check`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),om=Z(`clipboard-check`,[[`rect`,{width:`8`,height:`4`,x:`8`,y:`2`,rx:`1`,ry:`1`,key:`tgr4d6`}],[`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`,key:`116196`}],[`path`,{d:`m9 14 2 2 4-4`,key:`df797q`}]]),sm=Z(`code-xml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),cm=Z(`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`}]]),lm=Z(`database`,[[`ellipse`,{cx:`12`,cy:`5`,rx:`9`,ry:`3`,key:`msslwz`}],[`path`,{d:`M3 5V19A9 3 0 0 0 21 19V5`,key:`1wlel7`}],[`path`,{d:`M3 12A9 3 0 0 0 21 12`,key:`mv7ke4`}]]),um=Z(`download`,[[`path`,{d:`M12 15V3`,key:`m9g1x1`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`path`,{d:`m7 10 5 5 5-5`,key:`brsn70`}]]),dm=Z(`ellipsis`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]]),fm=Z(`external-link`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),pm=Z(`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`}]]),mm=Z(`file-braces`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1`,key:`1oajmo`}],[`path`,{d:`M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1`,key:`mpwhp6`}]]),hm=Z(`file-check-corner`,[[`path`,{d:`M10.5 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v6`,key:`g5mvt7`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`m14 20 2 2 4-4`,key:`15kota`}]]),gm=Z(`file-text`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),_m=Z(`git-branch`,[[`path`,{d:`M15 6a9 9 0 0 0-9 9V3`,key:`1cii5b`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}]]),vm=Z(`git-compare-arrows`,[[`circle`,{cx:`5`,cy:`6`,r:`3`,key:`1qnov2`}],[`path`,{d:`M12 6h5a2 2 0 0 1 2 2v7`,key:`1yj91y`}],[`path`,{d:`m15 9-3-3 3-3`,key:`1lwv8l`}],[`circle`,{cx:`19`,cy:`18`,r:`3`,key:`1qljk2`}],[`path`,{d:`M12 18H7a2 2 0 0 1-2-2V9`,key:`16sdep`}],[`path`,{d:`m9 15 3 3-3 3`,key:`1m3kbl`}]]),ym=Z(`info`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]),bm=Z(`languages`,[[`path`,{d:`m5 8 6 6`,key:`1wu5hv`}],[`path`,{d:`m4 14 6-6 2-3`,key:`1k1g8d`}],[`path`,{d:`M2 5h12`,key:`or177f`}],[`path`,{d:`M7 2h1`,key:`1t2jsx`}],[`path`,{d:`m22 22-5-10-5 10`,key:`don7ne`}],[`path`,{d:`M14 18h6`,key:`1m8k6r`}]]),xm=Z(`layout-dashboard`,[[`rect`,{width:`7`,height:`9`,x:`3`,y:`3`,rx:`1`,key:`10lvy0`}],[`rect`,{width:`7`,height:`5`,x:`14`,y:`3`,rx:`1`,key:`16une8`}],[`rect`,{width:`7`,height:`9`,x:`14`,y:`12`,rx:`1`,key:`1hutg5`}],[`rect`,{width:`7`,height:`5`,x:`3`,y:`16`,rx:`1`,key:`ldoo1y`}]]),Sm=Z(`list-plus`,[[`path`,{d:`M16 5H3`,key:`m91uny`}],[`path`,{d:`M11 12H3`,key:`51ecnj`}],[`path`,{d:`M16 19H3`,key:`zzsher`}],[`path`,{d:`M18 9v6`,key:`1twb98`}],[`path`,{d:`M21 12h-6`,key:`bt1uis`}]]),Cm=Z(`loader-circle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),wm=Z(`maximize-2`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`m21 3-7 7`,key:`1l2asr`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M9 21H3v-6`,key:`wtvkvv`}]]),Tm=Z(`menu`,[[`path`,{d:`M4 5h16`,key:`1tepv9`}],[`path`,{d:`M4 12h16`,key:`1lakjw`}],[`path`,{d:`M4 19h16`,key:`1djgab`}]]),Em=Z(`message-circle-question-mark`,[[`path`,{d:`M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719`,key:`1sd12s`}],[`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`,key:`1u773s`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),Dm=Z(`message-square-text`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}],[`path`,{d:`M7 11h10`,key:`1twpyw`}],[`path`,{d:`M7 15h6`,key:`d9of3u`}],[`path`,{d:`M7 7h8`,key:`af5zfr`}]]),Om=Z(`minimize-2`,[[`path`,{d:`m14 10 7-7`,key:`oa77jy`}],[`path`,{d:`M20 10h-6V4`,key:`mjg0md`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M4 14h6v6`,key:`rmj7iw`}]]),km=Z(`moon`,[[`path`,{d:`M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401`,key:`kfwtm`}]]),Am=Z(`palette`,[[`path`,{d:`M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z`,key:`e79jfc`}],[`circle`,{cx:`13.5`,cy:`6.5`,r:`.5`,fill:`currentColor`,key:`1okk4w`}],[`circle`,{cx:`17.5`,cy:`10.5`,r:`.5`,fill:`currentColor`,key:`f64h9f`}],[`circle`,{cx:`6.5`,cy:`12.5`,r:`.5`,fill:`currentColor`,key:`qy21gx`}],[`circle`,{cx:`8.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`fotxhn`}]]),jm=Z(`paperclip`,[[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551`,key:`1miecu`}]]),Mm=Z(`pause`,[[`rect`,{x:`14`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`kaeet6`}],[`rect`,{x:`5`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`1wsw3u`}]]),Nm=Z(`play`,[[`path`,{d:`M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z`,key:`10ikf1`}]]),Pm=Z(`plus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]),Fm=Z(`radio`,[[`path`,{d:`M16.247 7.761a6 6 0 0 1 0 8.478`,key:`1fwjs5`}],[`path`,{d:`M19.075 4.933a10 10 0 0 1 0 14.134`,key:`ehdyv1`}],[`path`,{d:`M4.925 19.067a10 10 0 0 1 0-14.134`,key:`1q22gi`}],[`path`,{d:`M7.753 16.239a6 6 0 0 1 0-8.478`,key:`r2q7qm`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}]]),Im=Z(`refresh-cw`,[[`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,key:`v9h5vc`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}],[`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,key:`3uifl3`}],[`path`,{d:`M8 16H3v5`,key:`1cv678`}]]),Lm=Z(`rotate-ccw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),Rm=Z(`rotate-cw`,[[`path`,{d:`M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8`,key:`1p45f6`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}]]),zm=Z(`search`,[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]),Bm=Z(`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`}]]),Vm=Z(`server-cog`,[[`path`,{d:`m10.852 14.772-.383.923`,key:`11vil6`}],[`path`,{d:`M13.148 14.772a3 3 0 1 0-2.296-5.544l-.383-.923`,key:`1v3clb`}],[`path`,{d:`m13.148 9.228.383-.923`,key:`t2zzyc`}],[`path`,{d:`m13.53 15.696-.382-.924a3 3 0 1 1-2.296-5.544`,key:`1bxfiv`}],[`path`,{d:`m14.772 10.852.923-.383`,key:`k9m8cz`}],[`path`,{d:`m14.772 13.148.923.383`,key:`1xvhww`}],[`path`,{d:`M4.5 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-.5`,key:`tn8das`}],[`path`,{d:`M4.5 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-.5`,key:`1g2pve`}],[`path`,{d:`M6 18h.01`,key:`uhywen`}],[`path`,{d:`M6 6h.01`,key:`1utrut`}],[`path`,{d:`m9.228 10.852-.923-.383`,key:`1wtb30`}],[`path`,{d:`m9.228 13.148-.923.383`,key:`1a830x`}]]),Hm=Z(`server`,[[`rect`,{width:`20`,height:`8`,x:`2`,y:`2`,rx:`2`,ry:`2`,key:`ngkwjq`}],[`rect`,{width:`20`,height:`8`,x:`2`,y:`14`,rx:`2`,ry:`2`,key:`iecqi9`}],[`line`,{x1:`6`,x2:`6.01`,y1:`6`,y2:`6`,key:`16zg32`}],[`line`,{x1:`6`,x2:`6.01`,y1:`18`,y2:`18`,key:`nzw8ys`}]]),Um=Z(`settings-2`,[[`path`,{d:`M14 17H5`,key:`gfn3mx`}],[`path`,{d:`M19 7h-9`,key:`6i9tg`}],[`circle`,{cx:`17`,cy:`17`,r:`3`,key:`18b49y`}],[`circle`,{cx:`7`,cy:`7`,r:`3`,key:`dfmy0x`}]]),Wm=Z(`shield-check`,[[`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`}]]),Gm=Z(`sliders-horizontal`,[[`path`,{d:`M10 5H3`,key:`1qgfaw`}],[`path`,{d:`M12 19H3`,key:`yhmn1j`}],[`path`,{d:`M14 3v4`,key:`1sua03`}],[`path`,{d:`M16 17v4`,key:`1q0r14`}],[`path`,{d:`M21 12h-9`,key:`1o4lsq`}],[`path`,{d:`M21 19h-5`,key:`1rlt1p`}],[`path`,{d:`M21 5h-7`,key:`1oszz2`}],[`path`,{d:`M8 10v4`,key:`tgpxqk`}],[`path`,{d:`M8 12H3`,key:`a7s4jb`}]]),Km=Z(`sparkles`,[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]]),qm=Z(`square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),Jm=Z(`sun`,[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]),Ym=Z(`test-tube-diagonal`,[[`path`,{d:`M21 7 6.82 21.18a2.83 2.83 0 0 1-3.99-.01a2.83 2.83 0 0 1 0-4L17 3`,key:`1ub6xw`}],[`path`,{d:`m16 2 6 6`,key:`1gw87d`}],[`path`,{d:`M12 16H4`,key:`1cjfip`}]]),Xm=Z(`trash-2`,[[`path`,{d:`M10 11v6`,key:`nco0om`}],[`path`,{d:`M14 11v6`,key:`outv1u`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`,key:`miytrc`}],[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`,key:`e791ji`}]]),Zm=Z(`triangle-alert`,[[`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`}]]),Qm=Z(`unlink`,[[`path`,{d:`m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71`,key:`yqzxt4`}],[`path`,{d:`m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71`,key:`4qinb0`}],[`line`,{x1:`8`,x2:`8`,y1:`2`,y2:`5`,key:`1041cp`}],[`line`,{x1:`2`,x2:`5`,y1:`8`,y2:`8`,key:`14m1p5`}],[`line`,{x1:`16`,x2:`16`,y1:`19`,y2:`22`,key:`rzdirn`}],[`line`,{x1:`19`,x2:`22`,y1:`16`,y2:`16`,key:`ox905f`}]]),$m=Z(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]);function eh(e){return/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(e)||e.startsWith(`//`)}function th(e){return[`localhost`,`127.0.0.1`,`::1`,`[::1]`].includes(e)}function nh(e,t,n){let r=e.trim();if(!r)return{error:`status URL is empty`};let i;try{i=new URL(r,t)}catch{return{error:`status URL is invalid`}}let a=!eh(r),o=th(i.hostname);return!a&&!o?{error:`${n} must be relative or loopback`}:{source:{isLoopback:o,isRelative:a,url:r}}}function rh(e,t){return nh(e,t,`statusUrl`)}function ih(e,t){let n=nh(e,t,`Ops statusUrl`);return n.error?{error:`${n.error}; use showcase mode for public links.`}:n}function ah(e,t,n){let r=new URL(e,n);return r.searchParams.set(`goal_activation`,t),r.toString()}function oh(e,t){if(!t||!e.isLoopback)return null;try{let n=new URL(e.url,window.location.href),r=new URL(t,n.origin);return th(r.hostname)?r.toString():null}catch{return null}}function sh(e,t){return{detailUrl:oh(t,e.local_dashboard_api?.periodic_report_detail_url),indexUrl:oh(t,e.local_dashboard_api?.periodic_report_index_url)}}async function ch(e,t){let n=new URL(e);n.searchParams.set(`goal_id`,t),n.searchParams.set(`limit`,`100`),n.searchParams.set(`offset`,`0`);let r=await fetch(n,{cache:`no-store`});if(!r.ok)throw Error(`HTTP ${r.status} while loading published reports`);return bp.parse(await r.json()).periodic_reports}async function lh(e,t){let n=new URL(e);Object.entries(t).forEach(([e,t])=>n.searchParams.set(e,t));let r=await fetch(n,{cache:`no-store`});if(!r.ok)throw Error(`HTTP ${r.status} while loading published report detail`);return Sp.parse(await r.json()).projection}function uh(e,t,n){let r=e.find(e=>e.agentId===t&&e.available)??e.find(e=>e.agentId===n&&e.available)??e.find(e=>e.available);if(!r)throw Error(`Chat requires at least one available route`);return r}function dh(e){return!!(e&&typeof e==`object`&&e.session_invalidated===!0)}var fh=``.replace(/\/+$/,``);function ph(e){return!fh||/^https?:\/\//.test(e)?e:new URL(e,`${fh}/`).toString()}var mh=J({todo_id:W().nullable(),role:W().nullable(),status:W(),priority:W().nullable(),text:W(),action_kind:W().nullable(),task_class:W().nullable(),claimed_by:W().nullable(),evidence:W().nullable()}),hh=J({goal_id:W(),title:W(),objective:W(),status:W(),waiting_on:W().nullable(),severity:W().nullable(),gate:W(),next_action:W(),top_todo:mh.nullable(),todos:q(mh),evidence:q(W()),quota:J({state:W().nullable(),spent_slots:G().nullable(),allowed_slots:G().nullable(),reason:W().nullable()})});J({ok:K(),schema_version:X(`loopx_chat_status_v0`),selected_goal_id:W().nullable(),goal_count:G(),goals:q(hh)});var gh=J({ok:X(!0),schema_version:Y([`loopx_chat_capabilities_v0`,`loopx_chat_capabilities_v1`]),agent_backend:W(),sandbox:W(),approval_policy:W(),todo_write:W(),goal_subagent_configuration:W().optional(),goal_id:W().nullable(),streaming:K().optional(),resume:K().optional(),interrupt:K().optional(),typed_actions:K().optional(),action_kinds:q(W()).optional(),adapters:q(J({agent_id:W(),display_name:W(),adapter_kind:W(),available:K(),streaming:K(),resume:K(),interrupt:K(),location:W().optional(),source:W().optional(),tool_calls:K().optional(),trust_scope:W().optional()})).optional(),lark_cli:J({available:K(),source:W(),version:W().nullable(),error_code:W().nullable()}).optional()}),_h=J({kind:X(`todo`),text:W(),priority:Y([`P0`,`P1`,`P2`]),rationale:W()}),vh=J({operation:Y([`merge`,`release`,`deploy`,`delete`,`payment`]),target:W().min(1).max(160),summary:W().max(300)}),yh=J({schema_version:X(`loopx_chat_agent_response_v0`),message:W(),proposals:q(_h),protected_action:vh.nullable().optional().default(null),gate:J({kind:W(),summary:W(),next_action:W()}).nullable()}),bh=J({closed:X(!0),ok:X(!0),session_id:W().min(1)});J({dry_run:X(!0),ok:X(!0),preview_id:W().min(1),todo:J({goal_id:W().min(1),text:W(),todo_id:W().optional()})});var xh=J({schema_version:X(`loopx_chat_todo_receipt_v0`),receipt_id:W().min(1),preview_id:W().min(1),goal_id:W().min(1),todo_id:W().min(1),status:X(`applied`),outcome:Y([`todo_added`,`todo_already_exists`]),already_exists:K(),preview_revision:W().nullable()});J({applied:X(!0),ok:X(!0),receipt:xh,todo:J({text:W(),todo_id:W()})});var Sh=J({model_config:J({model:W(),reasoning_effort:W().optional()}).optional(),mode:W(),spawn_allowed:K(),max_children:G().int().nonnegative(),allowed_domains:q(W()).optional().default([])}).passthrough(),Ch=J({ok:X(!0),dry_run:K(),execute:K(),written:K(),changed:K(),goal_id:W().min(1),changed_fields:q(W()),before:J({orchestration:Sh}).passthrough(),after:J({orchestration:Sh}).passthrough(),preview_id:W().min(1),feature_summary:J({multi_subagent:Y([`off`,`enabled`])}).passthrough(),global_sync:J({required:K(),executed:K(),readback:J({status:W(),verified:K()}).passthrough()}).passthrough()}),wh=J({id:W().min(1),outcome:Y([`approved`,`rejected`,`cancelled`]),projectionVerified:K().nullable(),proposal:_h,receipt:xh.nullable()}).superRefine((e,t)=>{e.outcome===`approved`&&!e.receipt&&t.addIssue({code:`custom`,message:`approved decision history requires a Todo receipt`,path:[`receipt`]}),e.outcome!==`approved`&&e.receipt&&t.addIssue({code:`custom`,message:`zero-write decision history must not include a Todo receipt`,path:[`receipt`]})});J({schema_version:X(`loopx_chat_decision_history_v0`),goal_id:W().min(1),decisions:q(wh).max(24)});var Th=class extends Error{payload;constructor(e,t){super(e),this.payload=t}},Eh=Y([`goal.create`,`goal.update`,`goal.lifecycle`,`todo.create`,`todo.update`,`agent.bind`,`heartbeat.bind`,`monitor.create`,`monitor.update`,`gate.resolve`,`run.correct`,`operation.execute`]),Dh=J({schema_version:X(`loopx_operation_envelope_v0`),lifecycle_state:Y([`prepared`,`awaiting_confirmation`,`claimed`,`outcome_observed`]),operation_id:W().min(1),confirmation_digest:W().min(1),payload_digest:W().min(1),projection_digest:W().min(1),expires_at:W().min(1),delivery:gd(W(),id()).nullable(),confirmation:gd(W(),id()).nullable(),claim:gd(W(),id()).nullable(),outcome:gd(W(),id()).nullable(),result_delivery:gd(W(),id()).nullable().optional()}).passthrough(),Oh=J({schema_version:X(`loopx_chat_action_proposal_v1`),proposal_id:W().min(1),action_kind:Eh,summary:W().min(1),normalized_parameters:gd(W(),id()),context:gd(W(),id()),expected_state_fingerprint:W().min(1),permission_classification:W().min(1),validation_evidence:q(W().refine(e=>e.trim().length>0,`Validation evidence must be non-blank text`)),available_transitions:q(Y([`apply`,`cancel`,`regenerate`,`reject`,`defer`])),status:Y([`preview_ready`,`applying`,`gated`,`failed`,`rejected`,`deferred`,`cancelled`,`stale`,`applied`]),receipt:gd(W(),id()).nullable(),stale:gd(W(),id()).nullable(),gate:gd(W(),id()).nullable().optional(),error:gd(W(),id()).nullable().optional(),checkpoint:gd(W(),id()).nullable().optional(),regenerated_from:W().nullable().optional(),operation:Dh.nullable().optional(),created_at:W(),updated_at:W()}),kh=J({ok:X(!0),proposal:Oh});async function Ah(e){let t=await Ih(`/api/actions/preview`,{method:`POST`,body:JSON.stringify({action_kind:e.actionKind,context:e.context,idempotency_key:e.idempotencyKey,normalized_parameters:e.normalizedParameters,summary:e.summary})});return kh.parse(t).proposal}var jh=J({ok:X(!0),schema_version:X(`loopx_chat_action_list_v1`),proposals:q(Oh)});async function Mh(e={}){let t=new URLSearchParams;e.contextKind&&t.set(`context_kind`,e.contextKind),e.goalId&&t.set(`goal_id`,e.goalId);let n=t.size>0?`?${t.toString()}`:``;return jh.parse(await Ih(`/api/actions${n}`)).proposals}async function Nh(e){let t=await Ih(`/api/actions/${encodeURIComponent(e)}/apply`,{method:`POST`,body:`{}`});return J({ok:X(!0),proposal:Oh,turn:gd(W(),id()).nullable().optional()}).parse(t)}async function Ph(e){return kh.parse(await Ih(`/api/actions/${encodeURIComponent(e)}/cancel`,{method:`POST`,body:`{}`})).proposal}async function Fh(e,t){return kh.parse(await Ih(`/api/actions/${encodeURIComponent(e)}/${t}`,{method:`POST`,body:`{}`})).proposal}async function Ih(e,t){let n;try{n=await fetch(ph(e),{cache:`no-store`,...t,headers:{"Content-Type":`application/json`,...t?.headers}})}catch{throw new Th(`无法连接 LoopX Chat 服务。请确认 Dashboard 与 Chat 服务已启动且来自同一版本。`,{error_code:`chat_api_unavailable`})}let r=await n.text(),i=null;if(r.trim())try{i=JSON.parse(r)}catch{i=null}let a=i&&typeof i==`object`&&!Array.isArray(i)?i:{};if(!n.ok){let e=(a.proposal&&typeof a.proposal==`object`?a.proposal:null)?.status===`stale`?`来源状态已变化,请重新生成预览。`:null,t=n.status>=500?`LoopX Chat 服务暂时不可用(HTTP ${n.status})。请确认 Dashboard 与 Chat 服务已启动且来自同一版本。`:`LoopX Chat 请求失败(HTTP ${n.status})。`;throw new Th(e??String(a.error||t),Object.keys(a).length?a:{error_code:`chat_api_unavailable`,http_status:n.status})}if(i===null)throw new Th(`LoopX Chat 服务返回了无法识别的响应(HTTP ${n.status})。请确认 Dashboard 与 Chat 服务来自同一版本。`,{error_code:`invalid_chat_api_response`,http_status:n.status});return i}async function Lh(){return gh.parse(await Ih(`/api/chat/capabilities`))}async function Rh(e){return Ih(`/api/chat/projection-messages`,{method:`POST`,body:JSON.stringify({answer:e.answer,context_kind:e.contextKind,goal_id:e.goalId,question:e.question})})}async function zh(e,t=`codex`,n=`resume_latest`,r=`goal`){return Ih(`/api/chat/sessions`,{method:`POST`,body:JSON.stringify({goal_id:e,agent_id:t,mode:n,context_kind:r})})}async function Bh(e){return Ih(`/api/chat/sessions/${e}`)}async function Vh(e){let t=new URLSearchParams;return e.agentId&&t.set(`agent_id`,e.agentId),e.channelId&&t.set(`channel_id`,e.channelId),e.goalId&&t.set(`goal_id`,e.goalId),Ih(`/api/chat/sessions?${t.toString()}`)}function Hh(e){let t=new Map;for(let n of e)for(let e of n.messages)t.set(e.message_id,e);return[...t.values()].sort((e,t)=>e.created_at.localeCompare(t.created_at)||e.message_id.localeCompare(t.message_id))}async function Uh(e){let t=await Vh(e),n=await Promise.all(t.sessions.map(e=>Bh(e.session_id)));return{messages:Hh(n),sessions:t.sessions,snapshots:n}}async function Wh(e,t,n,r=[]){return Ih(`/api/chat/sessions/${e}/turns`,{method:`POST`,body:JSON.stringify({message:t,client_turn_id:n,...r.length?{attachments:r.map(e=>({data_url:e.dataUrl,id:e.id,mime_type:e.mimeType,name:e.name,size:e.size}))}:{}})})}function Gh(e){let t=e.split(` `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(` `);if(!t)return null;try{let e=JSON.parse(t);return!e.kind||!e.payload||typeof e.payload!=`object`?null:{event_id:String(e.event_id??``),sequence:Number(e.sequence??0),kind:String(e.kind),created_at:String(e.created_at??``),payload:e.payload}}catch{return null}}async function Kh(e,t,n){let r=``,i=0,a=!1;for(;!a&&i<4;){let o=typeof window>`u`?`http://127.0.0.1`:window.location.origin,s=new URL(ph(e),o);r&&s.searchParams.set(`after`,r);try{let e=await fetch(s,{cache:`no-store`,headers:{Accept:`text/event-stream`},signal:n});if(!e.ok||!e.body)throw new Th(`SSE HTTP ${e.status}`,{status:e.status});let o=e.body.getReader(),c=new TextDecoder,l=``;for(;;){let{done:e,value:n}=await o.read();l+=c.decode(n,{stream:!e}).replaceAll(`\r `,` @@ -115,11 +115,11 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. `);for(;i>=0;){let e=l.slice(0,i);l=l.slice(i+2);let n=Gh(e);n&&(n.event_id&&(r=n.event_id),t(n),a=[`turn.completed`,`turn.interrupted`,`turn.failed`].includes(n.kind)),i=l.indexOf(` -`)}if(e||a)break}i=a?i:i+1}catch(e){if(n?.aborted||(i+=1,i>=4))throw e;await new Promise(e=>globalThis.setTimeout(e,250*2**(i-1)))}}if(!a)throw new Th(`Agent 事件流连接已断开。`,{reconnect_attempts:i})}async function qh(e,t){return Ih(`/api/chat/sessions/${e}/turns/${t}/interrupt`,{method:`POST`,body:`{}`})}async function Jh(e,t,n={}){let r=await Wh(e,t,n.clientTurnId??crypto.randomUUID(),n.attachments);return n.onPhase?.(`turn.accepted`,r.turn_id),Yh(e,r.turn_id,r.events_url,n)}async function Yh(e,t,n,r={}){let i=null,a={failure:null,interrupted:null};try{await Kh(n,e=>{r.onPhase?.(e.kind,t),(e.kind===`answer.delta`||e.kind===`assistant.delta`)&&r.onDelta?.(String(e.payload.text??``)),e.kind===`agent.phase`&&r.onActivity?.(String(e.payload.label??`Agent 正在处理`)),e.kind===`turn.completed`&&(i=e.payload.response),e.kind===`turn.failed`&&(a.failure=e.payload),e.kind===`turn.interrupted`&&(a.interrupted=e.payload)},r.signal)}catch(i){throw i instanceof Th&&!r.signal?.aborted?new Th(i.message,{...i.payload,events_url:n,reconnectable:!0,session_id:e,turn_id:t}):i}if(a.failure)throw new Th(String(a.failure.message||`Agent 回合失败。`),a.failure);if(a.interrupted)throw new Th(`Agent 回合已中断。`,{...a.interrupted,error_code:`turn_interrupted`,session_id:e,turn_id:t});return{response:yh.parse(i),sessionId:e,turnId:t}}async function Xh(e,t,n={}){return Yh(e,t,`/api/chat/sessions/${e}/turns/${t}/events`,n)}async function Zh(e){let t=bh.parse(await Ih(`/api/chat/sessions/${e}`,{keepalive:!0,method:`DELETE`}));if(t.session_id!==e)throw new Th(`Agent 会话关闭回执与本次请求不一致。`,{session_id:t.session_id});return t}async function Qh(e){return Ih(`/api/chat/sessions/${e}/resume`,{method:`POST`,body:`{}`})}function $h(e){return{goal_id:e.goalId,enabled:e.enabled,...e.modelConfig===void 0?{}:{model_config:e.modelConfig},...e.enabled?{max_children:e.maxChildren,allowed_domains:e.allowedDomains}:{}}}function eg(e,t){let n=e.after.orchestration,r=[...new Set(t.allowedDomains)],i=e.feature_summary.multi_subagent===`enabled`;if(!(e.goal_id===t.goalId&&i===t.enabled&&(t.modelConfig===void 0||JSON.stringify(n.model_config??null)===JSON.stringify(t.modelConfig))&&(t.enabled?n.max_children===t.maxChildren&&JSON.stringify(n.allowed_domains)===JSON.stringify(r):n.spawn_allowed===!1&&n.max_children===0)))throw new Th(`Goal 子代理配置回执与本次请求不一致,界面已停止更新。`,{after:e.after,goal_id:e.goal_id});return e}async function tg(e){let t=Ch.parse(await Ih(`/api/chat/goal-subagents/dry-run`,{method:`POST`,body:JSON.stringify($h(e))}));if(!t.dry_run||t.execute||t.written)throw new Th(`Goal 子代理预览返回了非预览回执,已停止进入确认状态。`,{result:t});return eg(t,e)}async function ng(e,t){let n=Ch.parse(await Ih(`/api/chat/goal-subagents/apply`,{method:`POST`,body:JSON.stringify({...$h(e),preview_id:t})}));if(n.preview_id!==t||n.dry_run||!n.execute)throw new Th(`Goal 子代理写入回执与本次确认不一致,界面已停止更新。`,{result:n});if(n.changed&&(!n.written||!n.global_sync.executed||!n.global_sync.readback.verified))throw new Th(`Goal 子代理设置未通过共享状态读回验证。`,{result:n});return eg(n,e)}var rg=J({ok:X(!0),targets:q(J({enabled:K(),provider:W(),target_name:W()}))});async function ig(){return rg.parse(await Ih(`/api/chat/goal-channel/targets`)).targets}var ag=J({ok:K(),blocker:W().optional(),public_summary:W().optional(),status:W().optional()});async function og(e){return ag.parse(await Ih(`/api/chat/goal-channel/setup`,{method:`POST`,body:JSON.stringify({execute:e.execute,goal_id:e.goalId,target:e.target})}))}async function sg(e){return ag.parse(await Ih(`/api/chat/goal-channel/configure`,{method:`POST`,body:JSON.stringify({auto_notify_human_gates:e.autoNotify,goal_id:e.goalId})}))}var cg=J({schema_version:X(`periodic_report_schedule_v0`),schedule_id:W(),rrule:W(),timezone:W()});J({schema_version:X(`periodic_report_machine_defaults_v0`),enabled:K(),inheritance:X(`live_machine_default`),profile_preset:W().optional(),route_ref:W().optional(),timezone:W(),schedule:cg.nullable().optional()});var lg=J({schema_version:X(`loopx_machine_configuration_v0`),namespaces:gd(W(),gd(W(),id()))}),ug=J({namespace:W(),title:W(),description:W(),schema_versions:q(W()).min(1),configuration_template:gd(W(),id()),template_status:Y([`ready`,`schema_only`])}),dg=J({schema_version:X(`machine_configuration_catalog_v0`),namespaces:q(ug)}),fg=J({key:W(),label:W(),description:W(),input_kind:Y([`boolean`,`number`,`select`,`string_list`,`text`,`periodic_report_schedule`]),nullable:K().optional(),required:K(),minimum:G().int().optional(),maximum:G().int().optional(),options:q(W()).optional()}),pg=J({schema_version:X(`capability_configuration_editor_v0`),editable:K(),supported_scopes:q(Y([`goal`,`machine`])),writable_scopes:q(Y([`goal`,`machine`])),fields:q(fg),read_only_reason:W().optional()}),mg=J({schema_version:X(`capability_configuration_catalog_v0`),capabilities:q(J({capability_id:W(),display_name:W(),description:W(),available_scopes:q(Y([`goal`,`machine`])),machine_namespace:W().optional(),goal_feature_id:W().optional(),effective_value_policy:X(`goal_override_over_live_machine_default`).optional(),availability:W().optional(),default:gd(W(),id()).optional(),current:gd(W(),id()).optional(),machine_current:gd(W(),id()).optional(),effective_configuration:J({schema_version:X(`capability_configuration_resolution_v0`),capability_id:W(),source:Y([`goal_override`,`machine_default`,`capability_default`,`not_configured`]),configuration:gd(W(),id()).nullable(),inherited:K(),goal_override_present:K(),machine_default_present:K(),effective_revision:W()}).optional(),documentation:gd(W(),id()).optional(),context_contribution:J({supported_phases:q(Y([`before_plan`,`before_delegate`,`after_delegate_result`])),target:X(`coordinator`),activation:X(`with_capability`),receipt_required:X(!0)}).optional(),configuration_editor:pg}))}),hg=J({ok:X(!0),schema_version:X(`goal_configuration_inspection_v0`),status:X(`configured`),goal_id:W(),revision:W(),available_capabilities:q(W()),capability_catalog:mg}),gg=J({ok:X(!0),goal_id:W(),capability_id:W(),changed_fields:q(W()),goal_configuration:gd(W(),id()).nullable(),capability_catalog:mg}),_g=gg.extend({schema_version:X(`goal_configuration_update_plan_v0`),status:X(`preview`),action:Y([`create`,`update`,`delete`,`unchanged`]),current_revision:W(),desired_revision:W(),base_revision:W(),plan_revision:W(),writes_required:G().int().nonnegative()}),vg=ud([gg.extend({schema_version:X(`goal_configuration_transaction_v0`),status:Y([`applied`,`unchanged`]),plan_revision:W(),applied_revision:W(),readback_verified:X(!0)}),J({ok:X(!1),schema_version:X(`goal_configuration_transaction_v0`),status:X(`partial_write`),goal_id:W(),capability_id:W(),plan_revision:W(),applied_revision:W().nullable(),source_written:X(!0),shared_sync_pending:X(!0),readback_verified:K(),changed_fields:q(W()),goal_configuration:gd(W(),id()).nullable(),capability_catalog:mg,error:W(),recommended_action:W()})]),yg=J({ok:X(!0),available_namespaces:q(W()),namespace_catalog:dg.optional().default({schema_version:`machine_configuration_catalog_v0`,namespaces:[]}),capability_catalog:mg,changed_namespaces:q(W()).optional().default([]),machine_configuration:lg.nullable().optional()}),bg=yg.extend({schema_version:X(`machine_configuration_inspection_v0`),status:Y([`configured`,`absent`]),revision:W()}),xg=yg.extend({schema_version:X(`machine_configuration_update_plan_v0`),status:X(`preview`),action:Y([`create`,`update`,`delete`,`unchanged`]),current_revision:W(),desired_revision:W(),plan_revision:W(),writes_required:G().int().nonnegative(),machine_configuration:lg.nullable()}),Sg=yg.extend({schema_version:X(`machine_configuration_transaction_v0`),status:Y([`applied`,`unchanged`]),plan_revision:W(),transaction_id:W().nullable(),readback_verified:X(!0),rollback_available:K(),applied_revision:W().optional(),prior_revision:W().optional()}),Cg=yg.extend({schema_version:X(`machine_configuration_rollback_plan_v0`),status:X(`preview`),action:Y([`delete`,`restore`,`unchanged`,`blocked`]),reason:W(),transaction_id:W(),plan_revision:W(),rollback_allowed:K(),writes_required:G().int().nonnegative()}),wg=yg.extend({schema_version:X(`machine_configuration_rollback_receipt_v0`),status:Y([`rolled_back`,`unchanged`]),transaction_id:W(),plan_revision:W(),rollback_id:W().nullable(),readback_verified:X(!0)});async function Tg(){return bg.parse(await Ih(`/api/chat/machine-configuration`))}async function Eg(e){let t=new URLSearchParams({goal_id:e});return hg.parse(await Ih(`/api/chat/goal-configuration?${t.toString()}`))}async function Dg(e,t,n){return _g.parse(await Ih(`/api/chat/goal-configuration/preview`,{method:`POST`,body:JSON.stringify({goal_id:e,capability_id:t,configuration:n})}))}async function Og(e,t,n,r){return vg.parse(await Ih(`/api/chat/goal-configuration/apply`,{method:`POST`,body:JSON.stringify({goal_id:e,capability_id:t,configuration:n,expected_plan_revision:r})}))}async function kg(e,t){return xg.parse(await Ih(`/api/chat/machine-configuration/preview`,{method:`POST`,body:JSON.stringify({namespace:e,namespace_configuration:t})}))}async function Ag(e,t,n){return Sg.parse(await Ih(`/api/chat/machine-configuration/apply`,{method:`POST`,body:JSON.stringify({expected_plan_revision:n,namespace:e,namespace_configuration:t})}))}async function jg(e){return xg.parse(await Ih(`/api/chat/machine-configuration/preview`,{method:`POST`,body:JSON.stringify({namespace:e,operation:`remove`})}))}async function Mg(e,t){return Sg.parse(await Ih(`/api/chat/machine-configuration/apply`,{method:`POST`,body:JSON.stringify({expected_plan_revision:t,namespace:e,operation:`remove`})}))}async function Ng(e){return Cg.parse(await Ih(`/api/chat/machine-configuration/rollback`,{method:`POST`,body:JSON.stringify({execute:!1,transaction_id:e})}))}async function Pg(e,t){return wg.parse(await Ih(`/api/chat/machine-configuration/rollback`,{method:`POST`,body:JSON.stringify({execute:!0,expected_plan_revision:t,transaction_id:e})}))}var Fg=J({ok:X(!0),goals:q(J({goal_id:W(),repository:J({branch:W(),identity:W(),label:W(),read_only:X(!0)})}))});async function Ig(){return Fg.parse(await Ih(`/api/chat/goals/contexts`)).goals}var Lg=J({ok:X(!0),apps:q(J({active:K(),app_ref:W(),brand:W(),health_error_code:W().nullable().default(null),label:W(),ready:K(),reply_ready:K().default(!1)}))});async function Rg(){return Lg.parse(await Ih(`/api/chat/lark/apps`)).apps}var zg=J({ok:X(!0),app_ref:W(),error:W().nullable(),setup_id:W(),status:Y([`starting`,`waiting_for_feishu`,`ready`,`failed`,`cancelled`]),verification_url:W().url().nullable()});async function Bg(e){return zg.parse(await Ih(`/api/chat/lark/app-setups`,{method:`POST`,body:JSON.stringify({app_ref:e.appRef,brand:e.brand})}))}async function Vg(e){return zg.parse(await Ih(`/api/chat/lark/app-setups/${encodeURIComponent(e)}`))}async function Hg(e){return zg.parse(await Ih(`/api/chat/lark/app-setups/${encodeURIComponent(e)}`,{method:`DELETE`}))}var Ug=[`invalid_event`,`binding_unavailable`,`chat_mismatch`,`topic_mismatch`,`route_ambiguous`,`self_message`,`invalid_routing_state`,`not_addressed`],Wg=J({ok:X(!0),chats:q(J({chat_id:W(),chat_name:W()}))});async function Gg(e,t){let n=new URLSearchParams({app_ref:e});return t&&n.set(`query`,t),Wg.parse(await Ih(`/api/chat/lark/chats?${n.toString()}`)).chats}var Kg=J({ok:X(!0),connections:q(J({conversation_kind:Y([`goal`,`manager`]).default(`goal`),agent_id:W().nullable().default(null),connection_id:W(),app_label:W(),app_ref:W(),capture_scope:Y([`addressed_only`,`configured_chat_all`]).default(`addressed_only`),chat_name:W(),enabled:K(),goal_id:W(),goal_title:W(),health_error_code:W().nullable().default(null),history_permission_guidance:J({action:X(`enable_application_scopes_and_publish`),api_document_url:W().url(),capability:X(`group_history_pagination`),identity:X(`bot`),required_scopes:md([X(`im:message.group_msg`),X(`im:message.group_msg.include_bot:read`)]),schema_version:X(`lark_bot_group_history_permission_guidance_v0`)}).nullable().default(null),incoming_mode:Y([`mentions`,`all`]),ingress_mode:Y([`live_steering`,`session_queue`,`async_inbox`,`direct_session`]).default(`async_inbox`),event_count:G().int().nonnegative().default(0),last_event_reason:Y(Ug).nullable().default(null).catch(null),last_event_status:W().nullable().default(null),listener_error_code:W().nullable().default(null),listener_status:Y([`starting`,`listening`,`retrying`,`stopped`]).nullable().default(null),replied_count:G().int().nonnegative().default(0),reply_ready:K().default(!1),reply_mode:X(`topic_reply`),session_bound:K().default(!1),target_ref:W(),topic_name:W(),topic_setup_required:K()}))});async function qg(){return Kg.parse(await Ih(`/api/chat/lark/connections`)).connections}async function Jg(e){return ag.parse(await Ih(`/api/chat/lark/connections`,{method:`POST`,body:JSON.stringify({...e.agentBindings?{agent_bindings:e.agentBindings.map(e=>({agent_id:e.agentId,app_ref:e.appRef}))}:{},...e.agentId?{agent_id:e.agentId}:{},...e.appRef?{app_ref:e.appRef}:{},...e.connectionId?{connection_id:e.connectionId}:{},conversation_kind:e.conversationKind??`goal`,capture_scope:e.captureScope,chat_id:e.chatId,chat_name:e.chatName,execute:e.execute,goal_id:e.goalId,incoming_mode:e.incomingMode,ingress_mode:e.ingressMode,reply_mode:e.replyMode})}))}async function Yg(e,t){let n=new URLSearchParams({goal_id:e,connection_id:t});return ag.parse(await Ih(`/api/chat/lark/connections?${n.toString()}`,{method:`DELETE`}))}function Xg(e){return{loadedUrl:null,projectionRevision:0,requestedUrl:e,selectionRevision:0,requestGeneration:0}}function Zg(e,t){return e.selectionRevision+=1,e.requestedUrl=t,e.selectionRevision}function Qg(e,t,n){if(n.background)return e.requestedUrl!==null||e.loadedUrl!==t?null:(e.requestGeneration+=1,{background:!0,projectionRevision:e.projectionRevision,selectionRevision:e.selectionRevision,url:t,generation:e.requestGeneration});let r=n.selectionRevision??e.selectionRevision+1;return n.selectionRevision!==void 0&&e.selectionRevision!==r?null:(e.selectionRevision=r,e.projectionRevision+=1,e.requestedUrl=t,e.requestGeneration+=1,{background:!1,projectionRevision:e.projectionRevision,selectionRevision:r,url:t,generation:e.requestGeneration})}function $g(e,t){return t.generation===e.requestGeneration&&e.projectionRevision===t.projectionRevision&&e.selectionRevision===t.selectionRevision}function e_(e,t){return $g(e,t)&&(!t.background||e.requestedUrl===null&&e.loadedUrl===t.url)}function t_(e,t,n){return t.get(e)===n}function n_(e,t,n,r){return e.filter(e=>t_(r(e),n,t))}function r_(e,t,n){let r=new Set,i=[];for(let a of[...e,...t]){let e=n(a);e==null||r.has(e)||(r.add(e),i.push(a))}return i}var i_=[`runs_24h`,`runs_7d`,`quota_spend_slots_24h`,`quota_spend_slots_7d`,`automation_run_count_24h`,`automation_run_count_7d`,`progress_signal_run_count_24h`,`progress_signal_run_count_7d`],a_=[`input_tokens_24h`,`input_tokens_7d`,`output_tokens_24h`,`output_tokens_7d`,`cache_tokens_24h`,`cache_tokens_7d`,`cost_usd_24h`,`cost_usd_7d`,`duration_ms_24h`,`duration_ms_7d`],o_=[`accounting`,`decision`,`evidence`,`state`,`work`],s_={accounting:0,decision:0,evidence:0,state:0,work:0},c_={runs_24h:0,runs_7d:0,quota_spend_slots_24h:0,quota_spend_slots_7d:0,automation_run_count_24h:0,automation_run_count_7d:0,progress_signal_run_count_24h:0,progress_signal_run_count_7d:0};function l_(e,t){let n={...e};for(let r of i_)n[r]=(Number(e[r])||0)+(Number(t[r])||0);for(let r of a_)(e[r]!==void 0||t[r]!==void 0)&&(n[r]=(e[r]??0)+(t[r]??0));return n}function u_(e,t){return!e.length||t<=0?e:e.map(e=>({...e,project_share_24h:Math.round((Number(e.runs_24h)||0)/t*1e3)/1e3}))}function d_(e,t){let n={...e};for(let r of o_)n[r]=(e[r]??0)+(t[r]??0);return n}function f_(e){let t={events_24h:0,events_7d:0,by_class_24h:{...s_},by_class_7d:{...s_}};for(let n of e)t.events_24h+=n.events_24h,t.events_7d+=n.events_7d,t.by_class_24h=d_(t.by_class_24h,n.by_class_24h),t.by_class_7d=d_(t.by_class_7d,n.by_class_7d);return t}function p_(e,t,n){if(!e&&!t)return null;let r=n_(e?.goals??[],`active`,n,e=>e.goal_id),i=n_(t?.goals??[],`stopped`,n,e=>e.goal_id),a=r_(r,i,e=>e.goal_id),o=f_(r),s=f_(i),c={events_24h:o.events_24h+s.events_24h,events_7d:o.events_7d+s.events_7d,by_class_24h:d_(o.by_class_24h,s.by_class_24h),by_class_7d:d_(o.by_class_7d,s.by_class_7d)};return{...e??t,goals:a,sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),totals:c}}function m_(e,t,n){if(!e&&!t)return null;let r=r_([...n_(e?.items??[],`active`,n,e=>e.goal_id),...n_(t?.items??[],`stopped`,n,e=>e.goal_id)],[],e=>`${e.goal_id}:${e.decision_kind??``}:${e.decision_at??``}`),i={decision_count:(e?.summary.decision_count??0)+(t?.summary.decision_count??0),stale_count:r.filter(e=>e.stale_by_age).length,rebase_required_count:(e?.summary.rebase_required_count??0)+(t?.summary.rebase_required_count??0),fresh_count:(e?.summary.fresh_count??0)+(t?.summary.fresh_count??0)};return{...e??t,items:r,sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),summary:i}}function h_(e,t){return r_([...e,...t].sort((e,t)=>t.generated_at.localeCompare(e.generated_at)),[],e=>`${e.goal_id}:${e.generated_at}:${e.classification??``}`)}function g_(e,t,n){let r=r_(n_(e.items,`active`,n,e=>e.goal_id),n_(t.items,`stopped`,n,e=>e.goal_id),e=>e.goal_id);return{...e,item_count:r.length,items:r,needs_controller:r.filter(e=>e.waiting_on===`controller`).length,needs_codex:r.filter(e=>e.waiting_on===`codex`).length,needs_user_or_controller:r.filter(e=>[`user_or_controller`,`controller`].includes(e.waiting_on)).length,watching_external_evidence:r.filter(e=>e.waiting_on===`external_evidence`).length}}function __(e){let t=e.todo_id?.trim()||``;return t?`${e.goal_id}:${t}`:`${e.goal_id}:synthetic:${e.role??``}:${e.index??``}:${e.text??``}`}function v_(e){let t={...c_};for(let n of e){for(let e of i_)t[e]+=Number(n[e])||0;for(let e of a_)n[e]!==void 0&&(t[e]=(t[e]??0)+n[e])}return t}function y_(e,t,n){if(!e&&!t)return null;let r=n_(e?.items??[],`active`,n,e=>e.goal_id),i=n_(t?.items??[],`stopped`,n,e=>e.goal_id),a=r_(r,i,__);return{...e??t,current_projected_count:r.length+i.length,items:a,rollout_event_count:a.reduce((e,t)=>e+(t.event_count??0),0),total_count:a.length}}function b_(e,t,n){if(!e&&!t)return null;let r=n_(e?.goals??[],`active`,n,e=>e.goal_id),i=n_(t?.goals??[],`stopped`,n,e=>e.goal_id),a=r_(r,i,e=>e.goal_id),o=l_(v_(r),v_(i));return{...e??t,goals:u_(a,Number(o.runs_24h)||0),sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),totals:o}}function x_(e,t,n){if(!e&&!t)return null;let r=(e?.agents??[]).filter(e=>e.goal_ids.some(e=>t_(e,n,`active`))||(e.current_todo?.goal_id?t_(e.current_todo.goal_id,n,`active`):!1)),i=(t?.agents??[]).filter(e=>e.goal_ids.some(e=>t_(e,n,`stopped`))||(e.current_todo?.goal_id?t_(e.current_todo.goal_id,n,`stopped`):!1)),a=r_(r,i,e=>e.agent_id).map(e=>{let t=i.find(t=>t.agent_id===e.agent_id);return t?{...e,goal_ids:Array.from(new Set([...e.goal_ids??[],...t.goal_ids]))}:e});return{...e??t,agents:a,source_summary:(e??t)?.source_summary?{...(e??t).source_summary,projected_agent_count:a.length,registered_agent_count:new Set(a.map(e=>e.agent_id)).size}:(e??t)?.source_summary}}function S_(e,t,n){if(!e&&!t)return null;let r=r_(n_(e?.goals??[],`active`,n,e=>e.goal_id),n_(t?.goals??[],`stopped`,n,e=>e.goal_id),e=>e.goal_id);return{...e??t,goals:r}}function C_(e,t){let n=t.goal_projection?.scope;if(n!==`active`&&n!==`stopped`)return t;let r=n,i=t.run_history.goals,a=e.run_history.goals,o=r_(r===`active`?i:a.filter(e=>e.activation_state!==`stopped`),r===`stopped`?i:a.filter(e=>e.activation_state===`stopped`),e=>e.id),s=new Map(o.map(e=>[e.id,e.activation_state])),c=r===`active`?t:e,l=r===`stopped`?t:e,u=e.goal_projection?.registry_revision??null,d=t.goal_projection?.registry_revision??null,f=u===null||d===null||u===d;return{...e,agent_management_projection:x_(c.agent_management_projection,l.agent_management_projection,s),attention_queue:g_(c.attention_queue,l.attention_queue,s),decision_freshness_summary:m_(c.decision_freshness_summary,l.decision_freshness_summary,s),event_ledger_summary:p_(c.event_ledger_summary,l.event_ledger_summary,s),goal_channel_notification_projection:S_(c.goal_channel_notification_projection,l.goal_channel_notification_projection,s),goal_projection:{schema_version:`loopx_goal_projection_scope_v0`,...t.goal_projection,complete:f,projected_goal_count:o.length,registry_goal_count:t.goal_projection?.registry_goal_count??0,scope:`all`},run_history:{...e.run_history,goal_count:o.length,goals:o,recent_runs:h_(c.run_history.recent_runs,l.run_history.recent_runs),run_count:c.run_history.run_count+l.run_history.run_count},todo_index:y_(c.todo_index,l.todo_index,s),usage_summary:b_(c.usage_summary,l.usage_summary,s)}}function w_(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`){if(Array.isArray(e)){var i=e.length;for(t=0;ttypeof e==`boolean`?`${e}`:e===0?`0`:e,D_=T_,O_=(e,t)=>n=>{if(t?.variants==null)return D_(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=E_(t)||E_(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return D_(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)},k_=(e,t)=>{let n=Array(e.length+t.length);for(let t=0;t({classGroupId:e,validator:t}),j_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),M_=`-`,N_=[],P_=`arbitrary..`,F_=e=>{let t=R_(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return L_(e);let n=e.split(M_);return I_(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?k_(i,t):t:i||N_}return n[e]||N_}}},I_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=I_(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(M_):e.slice(t).join(M_),s=a.length;for(let e=0;ee.slice(1,-1).indexOf(`:`)===-1?void 0:(()=>{let t=e.slice(1,-1),n=t.indexOf(`:`),r=t.slice(0,n);return r?P_+r:void 0})(),R_=e=>{let{theme:t,classGroups:n}=e;return z_(n,t)},z_=(e,t)=>{let n=j_();for(let r in e){let i=e[r];B_(i,n,r,t)}return n},B_=(e,t,n,r)=>{let i=e.length;for(let a=0;a{if(typeof e==`string`){H_(e,t,n);return}if(typeof e==`function`){U_(e,t,n,r);return}W_(e,t,n,r)},H_=(e,t,n)=>{let r=e===``?t:G_(t,e);r.classGroupId=n},U_=(e,t,n,r)=>{if(K_(e)){B_(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(A_(n,e))},W_=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e{let n=e,r=t.split(M_),i=r.length;for(let e=0;e`isThemeGetter`in e&&e.isThemeGetter===!0,q_=e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null),i=(i,a)=>{n[i]=a,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];if(t!==void 0)return t;if((t=r[e])!==void 0)return i(e,t),t},set(e,t){e in n?n[e]=t:i(e,t)}}},J_=`!`,Y_=`:`,X_=[],Z_=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),Q_=e=>{let{prefix:t,experimentalParseClassName:n}=e,r=e=>{let t=[],n=0,r=0,i=0,a,o=e.length;for(let s=0;si?a-i:void 0;return Z_(t,l,c,u)};if(t){let e=t+Y_,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):Z_(X_,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},$_=e=>{let t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{let n=[],r=[];for(let i=0;i0&&(r.sort(),n.push(...r),r=[]),n.push(a)):r.push(a)}return r.length>0&&(r.sort(),n.push(...r)),n}},ev=e=>({cache:q_(e.cacheSize),parseClassName:Q_(e),sortModifiers:$_(e),postfixLookupClassGroupIds:tv(e),...F_(e)}),tv=e=>{let t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let e=0;e{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a,postfixLookupClassGroupIds:o}=t,s=[],c=e.trim().split(nv),l=``;for(let e=c.length-1;e>=0;--e){let t=c[e],{isExternal:u,modifiers:d,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:m}=n(t);if(u){l=t+(l.length>0?` `+l:l);continue}let h=!!m,g;if(h){g=r(p.substring(0,m));let e=g&&o[g]?r(p):void 0;e&&e!==g&&(g=e,h=!1)}else g=r(p);if(!g){if(!h){l=t+(l.length>0?` `+l:l);continue}if(g=r(p),!g){l=t+(l.length>0?` `+l:l);continue}h=!1}let _=d.length===0?``:d.length===1?d[0]:a(d).join(`:`),v=f?_+J_:_,y=v+g;if(s.indexOf(y)>-1)continue;s.push(y);let b=i(g,h);for(let e=0;e0?` `+l:l)}return l},iv=(...e)=>{let t=0,n,r,i=``;for(;t{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r{let n,r,i,a,o=o=>(n=ev(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,a=s,s(o)),s=e=>{let t=r(e);if(t)return t;let a=rv(e,n);return i(e,a),a};return a=o,(...e)=>a(iv(...e))},sv=[],cv=e=>{let t=t=>t[e]||sv;return t.isThemeGetter=!0,t},lv=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,uv=/^\((?:(\w[\w-]*):)?(.+)\)$/i,dv=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,fv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,pv=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,mv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,hv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,gv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,_v=e=>dv.test(e),vv=e=>!!e&&!Number.isNaN(Number(e)),yv=e=>!!e&&Number.isInteger(Number(e)),bv=e=>e.endsWith(`%`)&&vv(e.slice(0,-1)),xv=e=>fv.test(e),Sv=()=>!0,Cv=e=>pv.test(e)&&!mv.test(e),wv=()=>!1,Tv=e=>hv.test(e),Ev=e=>gv.test(e),Dv=e=>!Q(e)&&!$(e),Ov=e=>e.startsWith(`@container`)&&(e[10]===`/`&&e[11]!==void 0||e[11]===`s`&&e[16]!==void 0&&e.startsWith(`-size/`,10)||e[11]===`n`&&e[18]!==void 0&&e.startsWith(`-normal/`,10)),kv=e=>Wv(e,Jv,wv),Q=e=>lv.test(e),Av=e=>Wv(e,Yv,Cv),jv=e=>Wv(e,Xv,vv),Mv=e=>Wv(e,Qv,Sv),Nv=e=>Wv(e,Zv,wv),Pv=e=>Wv(e,Kv,wv),Fv=e=>Wv(e,qv,Ev),Iv=e=>Wv(e,$v,Tv),$=e=>uv.test(e),Lv=e=>Gv(e,Yv),Rv=e=>Gv(e,Zv),zv=e=>Gv(e,Kv),Bv=e=>Gv(e,Jv),Vv=e=>Gv(e,qv),Hv=e=>Gv(e,$v,!0),Uv=e=>Gv(e,Qv,!0),Wv=(e,t,n)=>{let r=lv.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Gv=(e,t,n=!1)=>{let r=uv.exec(e);return r?r[1]?t(r[1]):n:!1},Kv=e=>e===`position`||e===`percentage`,qv=e=>e===`image`||e===`url`,Jv=e=>e===`length`||e===`size`||e===`bg-size`,Yv=e=>e===`length`,Xv=e=>e===`number`,Zv=e=>e===`family-name`,Qv=e=>e===`number`||e===`weight`,$v=e=>e===`shadow`,ey=ov(()=>{let e=cv(`color`),t=cv(`font`),n=cv(`text`),r=cv(`font-weight`),i=cv(`tracking`),a=cv(`leading`),o=cv(`breakpoint`),s=cv(`container`),c=cv(`spacing`),l=cv(`radius`),u=cv(`shadow`),d=cv(`inset-shadow`),f=cv(`text-shadow`),p=cv(`drop-shadow`),m=cv(`blur`),h=cv(`perspective`),g=cv(`aspect`),_=cv(`ease`),v=cv(`animate`),y=()=>[`auto`,`avoid`,`all`,`avoid-page`,`page`,`left`,`right`,`column`],b=()=>[`center`,`top`,`bottom`,`left`,`right`,`top-left`,`left-top`,`top-right`,`right-top`,`bottom-right`,`right-bottom`,`bottom-left`,`left-bottom`],x=()=>[...b(),$,Q],S=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],C=()=>[`auto`,`contain`,`none`],w=()=>[$,Q,c],T=()=>[_v,`full`,`auto`,...w()],E=()=>[yv,`none`,`subgrid`,$,Q],D=()=>[`auto`,{span:[`full`,yv,$,Q]},yv,$,Q],O=()=>[yv,`auto`,$,Q],ee=()=>[`auto`,`min`,`max`,`fr`,$,Q],te=()=>[`start`,`end`,`center`,`between`,`around`,`evenly`,`stretch`,`baseline`,`center-safe`,`end-safe`],ne=()=>[`start`,`end`,`center`,`stretch`,`center-safe`,`end-safe`],k=()=>[`auto`,...w()],A=()=>[_v,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...w()],j=()=>[_v,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...w()],M=()=>[_v,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...w()],N=()=>[e,$,Q],P=()=>[...b(),zv,Pv,{position:[$,Q]}],F=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],re=()=>[`auto`,`cover`,`contain`,Bv,kv,{size:[$,Q]}],ie=()=>[bv,Lv,Av],I=()=>[``,`none`,`full`,l,$,Q],ae=()=>[``,vv,Lv,Av],L=()=>[`solid`,`dashed`,`dotted`,`double`],oe=()=>[`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`],se=()=>[vv,bv,zv,Pv],ce=()=>[``,`none`,m,$,Q],le=()=>[`none`,vv,$,Q],ue=()=>[`none`,vv,$,Q],de=()=>[vv,$,Q],fe=()=>[_v,`full`,...w()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[xv],breakpoint:[xv],color:[Sv],container:[xv],"drop-shadow":[xv],ease:[`in`,`out`,`in-out`],font:[Dv],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[xv],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[xv],shadow:[xv],spacing:[`px`,vv],text:[xv],"text-shadow":[xv],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,_v,Q,$,g]}],container:[`container`],"container-type":[{"@container":[``,`normal`,`size`,$,Q]}],"container-named":[Ov],columns:[{columns:[vv,Q,$,s]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":[`auto`,`avoid`,`avoid-page`,`avoid-column`]}],"box-decoration":[{"box-decoration":[`slice`,`clone`]}],box:[{box:[`border`,`content`]}],display:[`block`,`inline-block`,`inline`,`flex`,`inline-flex`,`table`,`inline-table`,`table-caption`,`table-cell`,`table-column`,`table-column-group`,`table-footer-group`,`table-header-group`,`table-row-group`,`table-row`,`flow-root`,`grid`,`inline-grid`,`contents`,`list-item`,`hidden`],sr:[`sr-only`,`not-sr-only`],float:[{float:[`right`,`left`,`none`,`start`,`end`]}],clear:[{clear:[`left`,`right`,`both`,`none`,`start`,`end`]}],isolation:[`isolate`,`isolation-auto`],"object-fit":[{object:[`contain`,`cover`,`fill`,`none`,`scale-down`]}],"object-position":[{object:x()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:[`static`,`fixed`,`absolute`,`relative`,`sticky`],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{"inset-s":T(),start:T()}],end:[{"inset-e":T(),end:T()}],"inset-bs":[{"inset-bs":T()}],"inset-be":[{"inset-be":T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:[`visible`,`invisible`,`collapse`],z:[{z:[yv,`auto`,$,Q]}],basis:[{basis:[_v,`full`,`auto`,s,...w()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[vv,_v,`auto`,`initial`,`none`,Q]}],grow:[{grow:[``,vv,$,Q]}],shrink:[{shrink:[``,vv,$,Q]}],order:[{order:[yv,`first`,`last`,`none`,$,Q]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":[`row`,`col`,`dense`,`row-dense`,`col-dense`]}],"auto-cols":[{"auto-cols":ee()}],"auto-rows":[{"auto-rows":ee()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...te(),`normal`]}],"justify-items":[{"justify-items":[...ne(),`normal`]}],"justify-self":[{"justify-self":[`auto`,...ne()]}],"align-content":[{content:[`normal`,...te()]}],"align-items":[{items:[...ne(),{baseline:[``,`last`]}]}],"align-self":[{self:[`auto`,...ne(),{baseline:[``,`last`]}]}],"place-content":[{"place-content":te()}],"place-items":[{"place-items":[...ne(),`baseline`]}],"place-self":[{"place-self":[`auto`,...ne()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pbs:[{pbs:w()}],pbe:[{pbe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:k()}],mx:[{mx:k()}],my:[{my:k()}],ms:[{ms:k()}],me:[{me:k()}],mbs:[{mbs:k()}],mbe:[{mbe:k()}],mt:[{mt:k()}],mr:[{mr:k()}],mb:[{mb:k()}],ml:[{ml:k()}],"space-x":[{"space-x":w()}],"space-x-reverse":[`space-x-reverse`],"space-y":[{"space-y":w()}],"space-y-reverse":[`space-y-reverse`],size:[{size:A()}],"inline-size":[{inline:[`auto`,...j()]}],"min-inline-size":[{"min-inline":[`auto`,...j()]}],"max-inline-size":[{"max-inline":[`none`,...j()]}],"block-size":[{block:[`auto`,...M()]}],"min-block-size":[{"min-block":[`auto`,...M()]}],"max-block-size":[{"max-block":[`none`,...M()]}],w:[{w:[s,`screen`,...A()]}],"min-w":[{"min-w":[s,`screen`,`none`,...A()]}],"max-w":[{"max-w":[s,`screen`,`none`,`prose`,{screen:[o]},...A()]}],h:[{h:[`screen`,`lh`,...A()]}],"min-h":[{"min-h":[`screen`,`lh`,`none`,...A()]}],"max-h":[{"max-h":[`screen`,`lh`,...A()]}],"font-size":[{text:[`base`,n,Lv,Av]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,Uv,Mv]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,bv,Q]}],"font-family":[{font:[Rv,Nv,t]}],"font-features":[{"font-features":[Q]}],"fvn-normal":[`normal-nums`],"fvn-ordinal":[`ordinal`],"fvn-slashed-zero":[`slashed-zero`],"fvn-figure":[`lining-nums`,`oldstyle-nums`],"fvn-spacing":[`proportional-nums`,`tabular-nums`],"fvn-fraction":[`diagonal-fractions`,`stacked-fractions`],tracking:[{tracking:[i,$,Q]}],"line-clamp":[{"line-clamp":[vv,`none`,$,jv]}],leading:[{leading:[a,...w()]}],"list-image":[{"list-image":[`none`,$,Q]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,$,Q]}],"text-alignment":[{text:[`left`,`center`,`right`,`justify`,`start`,`end`]}],"placeholder-color":[{placeholder:N()}],"text-color":[{text:N()}],"text-decoration":[`underline`,`overline`,`line-through`,`no-underline`],"text-decoration-style":[{decoration:[...L(),`wavy`]}],"text-decoration-thickness":[{decoration:[vv,`from-font`,`auto`,$,Av]}],"text-decoration-color":[{decoration:N()}],"underline-offset":[{"underline-offset":[vv,`auto`,$,Q]}],"text-transform":[`uppercase`,`lowercase`,`capitalize`,`normal-case`],"text-overflow":[`truncate`,`text-ellipsis`,`text-clip`],"text-wrap":[{text:[`wrap`,`nowrap`,`balance`,`pretty`]}],indent:[{indent:w()}],"tab-size":[{tab:[yv,$,Q]}],"vertical-align":[{align:[`baseline`,`top`,`middle`,`bottom`,`text-top`,`text-bottom`,`sub`,`super`,$,Q]}],whitespace:[{whitespace:[`normal`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]}],break:[{break:[`normal`,`words`,`all`,`keep`]}],wrap:[{wrap:[`break-word`,`anywhere`,`normal`]}],hyphens:[{hyphens:[`none`,`manual`,`auto`]}],content:[{content:[`none`,$,Q]}],"bg-attachment":[{bg:[`fixed`,`local`,`scroll`]}],"bg-clip":[{"bg-clip":[`border`,`padding`,`content`,`text`]}],"bg-origin":[{"bg-origin":[`border`,`padding`,`content`]}],"bg-position":[{bg:P()}],"bg-repeat":[{bg:F()}],"bg-size":[{bg:re()}],"bg-image":[{bg:[`none`,{linear:[{to:[`t`,`tr`,`r`,`br`,`b`,`bl`,`l`,`tl`]},yv,$,Q],radial:[``,$,Q],conic:[yv,$,Q]},Vv,Fv]}],"bg-color":[{bg:N()}],"gradient-from-pos":[{from:ie()}],"gradient-via-pos":[{via:ie()}],"gradient-to-pos":[{to:ie()}],"gradient-from":[{from:N()}],"gradient-via":[{via:N()}],"gradient-to":[{to:N()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:ae()}],"border-w-x":[{"border-x":ae()}],"border-w-y":[{"border-y":ae()}],"border-w-s":[{"border-s":ae()}],"border-w-e":[{"border-e":ae()}],"border-w-bs":[{"border-bs":ae()}],"border-w-be":[{"border-be":ae()}],"border-w-t":[{"border-t":ae()}],"border-w-r":[{"border-r":ae()}],"border-w-b":[{"border-b":ae()}],"border-w-l":[{"border-l":ae()}],"divide-x":[{"divide-x":ae()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":ae()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...L(),`hidden`,`none`]}],"divide-style":[{divide:[...L(),`hidden`,`none`]}],"border-color":[{border:N()}],"border-color-x":[{"border-x":N()}],"border-color-y":[{"border-y":N()}],"border-color-s":[{"border-s":N()}],"border-color-e":[{"border-e":N()}],"border-color-bs":[{"border-bs":N()}],"border-color-be":[{"border-be":N()}],"border-color-t":[{"border-t":N()}],"border-color-r":[{"border-r":N()}],"border-color-b":[{"border-b":N()}],"border-color-l":[{"border-l":N()}],"divide-color":[{divide:N()}],"outline-style":[{outline:[...L(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[vv,$,Q]}],"outline-w":[{outline:[``,vv,Lv,Av]}],"outline-color":[{outline:N()}],shadow:[{shadow:[``,`none`,u,Hv,Iv]}],"shadow-color":[{shadow:N()}],"inset-shadow":[{"inset-shadow":[`none`,d,Hv,Iv]}],"inset-shadow-color":[{"inset-shadow":N()}],"ring-w":[{ring:ae()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:N()}],"ring-offset-w":[{"ring-offset":[vv,Av]}],"ring-offset-color":[{"ring-offset":N()}],"inset-ring-w":[{"inset-ring":ae()}],"inset-ring-color":[{"inset-ring":N()}],"text-shadow":[{"text-shadow":[`none`,f,Hv,Iv]}],"text-shadow-color":[{"text-shadow":N()}],opacity:[{opacity:[vv,$,Q]}],"mix-blend":[{"mix-blend":[...oe(),`plus-darker`,`plus-lighter`]}],"bg-blend":[{"bg-blend":oe()}],"mask-clip":[{"mask-clip":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]},`mask-no-clip`],"mask-composite":[{mask:[`add`,`subtract`,`intersect`,`exclude`]}],"mask-image-linear-pos":[{"mask-linear":[vv]}],"mask-image-linear-from-pos":[{"mask-linear-from":se()}],"mask-image-linear-to-pos":[{"mask-linear-to":se()}],"mask-image-linear-from-color":[{"mask-linear-from":N()}],"mask-image-linear-to-color":[{"mask-linear-to":N()}],"mask-image-t-from-pos":[{"mask-t-from":se()}],"mask-image-t-to-pos":[{"mask-t-to":se()}],"mask-image-t-from-color":[{"mask-t-from":N()}],"mask-image-t-to-color":[{"mask-t-to":N()}],"mask-image-r-from-pos":[{"mask-r-from":se()}],"mask-image-r-to-pos":[{"mask-r-to":se()}],"mask-image-r-from-color":[{"mask-r-from":N()}],"mask-image-r-to-color":[{"mask-r-to":N()}],"mask-image-b-from-pos":[{"mask-b-from":se()}],"mask-image-b-to-pos":[{"mask-b-to":se()}],"mask-image-b-from-color":[{"mask-b-from":N()}],"mask-image-b-to-color":[{"mask-b-to":N()}],"mask-image-l-from-pos":[{"mask-l-from":se()}],"mask-image-l-to-pos":[{"mask-l-to":se()}],"mask-image-l-from-color":[{"mask-l-from":N()}],"mask-image-l-to-color":[{"mask-l-to":N()}],"mask-image-x-from-pos":[{"mask-x-from":se()}],"mask-image-x-to-pos":[{"mask-x-to":se()}],"mask-image-x-from-color":[{"mask-x-from":N()}],"mask-image-x-to-color":[{"mask-x-to":N()}],"mask-image-y-from-pos":[{"mask-y-from":se()}],"mask-image-y-to-pos":[{"mask-y-to":se()}],"mask-image-y-from-color":[{"mask-y-from":N()}],"mask-image-y-to-color":[{"mask-y-to":N()}],"mask-image-radial":[{"mask-radial":[$,Q]}],"mask-image-radial-from-pos":[{"mask-radial-from":se()}],"mask-image-radial-to-pos":[{"mask-radial-to":se()}],"mask-image-radial-from-color":[{"mask-radial-from":N()}],"mask-image-radial-to-color":[{"mask-radial-to":N()}],"mask-image-radial-shape":[{"mask-radial":[`circle`,`ellipse`]}],"mask-image-radial-size":[{"mask-radial":[{closest:[`side`,`corner`],farthest:[`side`,`corner`]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[vv]}],"mask-image-conic-from-pos":[{"mask-conic-from":se()}],"mask-image-conic-to-pos":[{"mask-conic-to":se()}],"mask-image-conic-from-color":[{"mask-conic-from":N()}],"mask-image-conic-to-color":[{"mask-conic-to":N()}],"mask-mode":[{mask:[`alpha`,`luminance`,`match`]}],"mask-origin":[{"mask-origin":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]}],"mask-position":[{mask:P()}],"mask-repeat":[{mask:F()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":[`alpha`,`luminance`]}],"mask-image":[{mask:[`none`,$,Q]}],filter:[{filter:[``,`none`,$,Q]}],blur:[{blur:ce()}],brightness:[{brightness:[vv,$,Q]}],contrast:[{contrast:[vv,$,Q]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,Hv,Iv]}],"drop-shadow-color":[{"drop-shadow":N()}],grayscale:[{grayscale:[``,vv,$,Q]}],"hue-rotate":[{"hue-rotate":[vv,$,Q]}],invert:[{invert:[``,vv,$,Q]}],saturate:[{saturate:[vv,$,Q]}],sepia:[{sepia:[``,vv,$,Q]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,$,Q]}],"backdrop-blur":[{"backdrop-blur":ce()}],"backdrop-brightness":[{"backdrop-brightness":[vv,$,Q]}],"backdrop-contrast":[{"backdrop-contrast":[vv,$,Q]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,vv,$,Q]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[vv,$,Q]}],"backdrop-invert":[{"backdrop-invert":[``,vv,$,Q]}],"backdrop-opacity":[{"backdrop-opacity":[vv,$,Q]}],"backdrop-saturate":[{"backdrop-saturate":[vv,$,Q]}],"backdrop-sepia":[{"backdrop-sepia":[``,vv,$,Q]}],"border-collapse":[{border:[`collapse`,`separate`]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:[`auto`,`fixed`]}],caption:[{caption:[`top`,`bottom`]}],transition:[{transition:[``,`all`,`colors`,`opacity`,`shadow`,`transform`,`none`,$,Q]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[vv,`initial`,$,Q]}],ease:[{ease:[`linear`,`initial`,_,$,Q]}],delay:[{delay:[vv,$,Q]}],animate:[{animate:[`none`,v,$,Q]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,$,Q]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:le()}],"rotate-x":[{"rotate-x":le()}],"rotate-y":[{"rotate-y":le()}],"rotate-z":[{"rotate-z":le()}],scale:[{scale:ue()}],"scale-x":[{"scale-x":ue()}],"scale-y":[{"scale-y":ue()}],"scale-z":[{"scale-z":ue()}],"scale-3d":[`scale-3d`],skew:[{skew:de()}],"skew-x":[{"skew-x":de()}],"skew-y":[{"skew-y":de()}],transform:[{transform:[$,Q,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:fe()}],"translate-x":[{"translate-x":fe()}],"translate-y":[{"translate-y":fe()}],"translate-z":[{"translate-z":fe()}],"translate-none":[`translate-none`],zoom:[{zoom:[yv,$,Q]}],accent:[{accent:N()}],appearance:[{appearance:[`none`,`auto`]}],"caret-color":[{caret:N()}],"color-scheme":[{scheme:[`normal`,`dark`,`light`,`light-dark`,`only-dark`,`only-light`]}],cursor:[{cursor:[`auto`,`default`,`pointer`,`wait`,`text`,`move`,`help`,`not-allowed`,`none`,`context-menu`,`progress`,`cell`,`crosshair`,`vertical-text`,`alias`,`copy`,`no-drop`,`grab`,`grabbing`,`all-scroll`,`col-resize`,`row-resize`,`n-resize`,`e-resize`,`s-resize`,`w-resize`,`ne-resize`,`nw-resize`,`se-resize`,`sw-resize`,`ew-resize`,`ns-resize`,`nesw-resize`,`nwse-resize`,`zoom-in`,`zoom-out`,$,Q]}],"field-sizing":[{"field-sizing":[`fixed`,`content`]}],"pointer-events":[{"pointer-events":[`auto`,`none`]}],resize:[{resize:[`none`,``,`y`,`x`]}],"scroll-behavior":[{scroll:[`auto`,`smooth`]}],"scrollbar-thumb-color":[{"scrollbar-thumb":N()}],"scrollbar-track-color":[{"scrollbar-track":N()}],"scrollbar-gutter":[{"scrollbar-gutter":[`auto`,`stable`,`both`]}],"scrollbar-w":[{scrollbar:[`auto`,`thin`,`none`]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mbs":[{"scroll-mbs":w()}],"scroll-mbe":[{"scroll-mbe":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pbs":[{"scroll-pbs":w()}],"scroll-pbe":[{"scroll-pbe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:[`start`,`end`,`center`,`align-none`]}],"snap-stop":[{snap:[`normal`,`always`]}],"snap-type":[{snap:[`none`,`x`,`y`,`both`]}],"snap-strictness":[{snap:[`mandatory`,`proximity`]}],touch:[{touch:[`auto`,`none`,`manipulation`]}],"touch-x":[{"touch-pan":[`x`,`left`,`right`]}],"touch-y":[{"touch-pan":[`y`,`up`,`down`]}],"touch-pz":[`touch-pinch-zoom`],select:[{select:[`none`,`text`,`all`,`auto`]}],"will-change":[{"will-change":[`auto`,`scroll`,`contents`,`transform`,$,Q]}],fill:[{fill:[`none`,...N()]}],"stroke-w":[{stroke:[vv,Lv,Av,jv]}],stroke:[{stroke:[`none`,...N()]}],"forced-color-adjust":[{"forced-color-adjust":[`auto`,`none`]}]},conflictingClassGroups:{"container-named":[`container-type`],overflow:[`overflow-x`,`overflow-y`],overscroll:[`overscroll-x`,`overscroll-y`],inset:[`inset-x`,`inset-y`,`inset-bs`,`inset-be`,`start`,`end`,`top`,`right`,`bottom`,`left`],"inset-x":[`right`,`left`],"inset-y":[`top`,`bottom`],flex:[`basis`,`grow`,`shrink`],gap:[`gap-x`,`gap-y`],p:[`px`,`py`,`ps`,`pe`,`pbs`,`pbe`,`pt`,`pr`,`pb`,`pl`],px:[`pr`,`pl`],py:[`pt`,`pb`],m:[`mx`,`my`,`ms`,`me`,`mbs`,`mbe`,`mt`,`mr`,`mb`,`ml`],mx:[`mr`,`ml`],my:[`mt`,`mb`],size:[`w`,`h`],"font-size":[`leading`],"fvn-normal":[`fvn-ordinal`,`fvn-slashed-zero`,`fvn-figure`,`fvn-spacing`,`fvn-fraction`],"fvn-ordinal":[`fvn-normal`],"fvn-slashed-zero":[`fvn-normal`],"fvn-figure":[`fvn-normal`],"fvn-spacing":[`fvn-normal`],"fvn-fraction":[`fvn-normal`],"line-clamp":[`display`,`overflow`],rounded:[`rounded-s`,`rounded-e`,`rounded-t`,`rounded-r`,`rounded-b`,`rounded-l`,`rounded-ss`,`rounded-se`,`rounded-ee`,`rounded-es`,`rounded-tl`,`rounded-tr`,`rounded-br`,`rounded-bl`],"rounded-s":[`rounded-ss`,`rounded-es`],"rounded-e":[`rounded-se`,`rounded-ee`],"rounded-t":[`rounded-tl`,`rounded-tr`],"rounded-r":[`rounded-tr`,`rounded-br`],"rounded-b":[`rounded-br`,`rounded-bl`],"rounded-l":[`rounded-tl`,`rounded-bl`],"border-spacing":[`border-spacing-x`,`border-spacing-y`],"border-w":[`border-w-x`,`border-w-y`,`border-w-s`,`border-w-e`,`border-w-bs`,`border-w-be`,`border-w-t`,`border-w-r`,`border-w-b`,`border-w-l`],"border-w-x":[`border-w-r`,`border-w-l`],"border-w-y":[`border-w-t`,`border-w-b`],"border-color":[`border-color-x`,`border-color-y`,`border-color-s`,`border-color-e`,`border-color-bs`,`border-color-be`,`border-color-t`,`border-color-r`,`border-color-b`,`border-color-l`],"border-color-x":[`border-color-r`,`border-color-l`],"border-color-y":[`border-color-t`,`border-color-b`],translate:[`translate-x`,`translate-y`,`translate-none`],"translate-none":[`translate`,`translate-x`,`translate-y`,`translate-z`],"scroll-m":[`scroll-mx`,`scroll-my`,`scroll-ms`,`scroll-me`,`scroll-mbs`,`scroll-mbe`,`scroll-mt`,`scroll-mr`,`scroll-mb`,`scroll-ml`],"scroll-mx":[`scroll-mr`,`scroll-ml`],"scroll-my":[`scroll-mt`,`scroll-mb`],"scroll-p":[`scroll-px`,`scroll-py`,`scroll-ps`,`scroll-pe`,`scroll-pbs`,`scroll-pbe`,`scroll-pt`,`scroll-pr`,`scroll-pb`,`scroll-pl`],"scroll-px":[`scroll-pr`,`scroll-pl`],"scroll-py":[`scroll-pt`,`scroll-pb`],touch:[`touch-x`,`touch-y`,`touch-pz`],"touch-x":[`touch`],"touch-y":[`touch`],"touch-pz":[`touch`]},conflictingClassGroupModifiers:{"font-size":[`leading`]},postfixLookupClassGroups:[`container-type`],orderSensitiveModifiers:[`*`,`**`,`after`,`backdrop`,`before`,`details-content`,`file`,`first-letter`,`first-line`,`marker`,`placeholder`,`selection`]}});function ty(...e){return ey(T_(e))}var ny=O_(`inline-flex h-9 shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-md border px-3 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400 disabled:pointer-events-none disabled:opacity-50 dark:focus-visible:ring-zinc-500`,{variants:{variant:{primary:`border-slate-900 bg-slate-950 text-white hover:bg-slate-800 dark:border-zinc-100 dark:bg-zinc-50 dark:text-zinc-950 dark:hover:bg-zinc-200`,secondary:`border-slate-200 bg-white text-slate-900 hover:bg-slate-50 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-100 dark:hover:bg-zinc-900`,ghost:`border-transparent bg-transparent text-slate-700 hover:bg-slate-100 dark:text-zinc-300 dark:hover:bg-zinc-900`},size:{sm:`h-8 px-2 text-xs`,md:`h-9 px-3 text-sm`,icon:`h-9 w-9 px-0`}},defaultVariants:{variant:`secondary`,size:`md`}});function ry({className:e,variant:t,size:n,...r}){return(0,B.jsx)(`button`,{className:ty(ny({variant:t,size:n}),e),type:`button`,...r})}function iy({className:e,...t}){return(0,B.jsx)(`section`,{className:ty(`rounded-lg border border-slate-200/80 bg-white/95 text-slate-950 shadow-[0_1px_2px_rgba(15,23,42,0.04)] dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50`,e),...t})}function ay({className:e,...t}){return(0,B.jsx)(`div`,{className:ty(`p-4 pt-0`,e),...t})}var oy=[`codex`,`claude`,`kiro`,`trae`,`coco`,`openai`,`anthropic`],sy=new Set([`acp`,`status_projection`]);function cy(e){let t=e.trim().toLowerCase().replace(/_/gu,`-`);for(let e of oy)if(t===e||t.startsWith(`${e}-`))return e;return t}function ly(e,t){let n=t?.trim().toLowerCase()??``;return n.length>0&&!sy.has(n)?cy(n):cy(e)}var uy={stop:`ready_stop`,resume:`resume_review`,delete:`delete_review`},dy=e=>typeof e==`string`&&e.trim().length>0;function fy(e){let t={schemaVersion:`action_review_plan_v0`,proposalId:e.proposal_id,sourceFingerprint:e.expected_state_fingerprint},n=(e,n)=>({...t,interaction:e,reason:n,canApply:!1}),r=e.action_kind===`goal.lifecycle`;if(r&&e.gate!=null||e.status===`gated`)return n(`gated`,`authority_gate`);if(r&&e.stale!=null||e.status===`stale`)return n(`refresh`,`stale_proposal`);if(e.status===`applied`)return e.receipt?.projection_verified===!0?n(`completed`,`readback_verified`):n(`repair`,`readback_unverified`);if(e.status===`applying`)return n(`pending`,`apply_pending`);if(e.status===`failed`||e.error!=null)return n(`repair`,`apply_failed`);if(e.status!==`preview_ready`&&e.status!==`deferred`)return n(`inactive`,`inactive_proposal`);let i=(e,n=!0)=>({...t,interaction:`review`,reason:e,canApply:n});if(e.action_kind!==`goal.lifecycle`)return i(e.permission_classification===`protected`?`protected_action`:`action_review`);if(!(dy(e.proposal_id)&&dy(e.expected_state_fingerprint)&&Oh.shape.validation_evidence.safeParse(e.validation_evidence).success&&e.validation_evidence.length>0&&e.available_transitions.includes(`apply`)))return n(`refresh`,`incomplete_proposal`);let{operation:a,goal_id:o}=e.normalized_parameters;if(!dy(o)||e.context.goal_id!=null&&e.context.goal_id!==o)return n(`refresh`,`incomplete_proposal`);if(a!==`stop`&&a!==`resume`&&a!==`delete`)return i(`unknown_action`,!1);if(e.permission_classification===`protected`)return i(`protected_action`);if(e.permission_classification!==`durable_write`)return i(`unknown_permission`,!1);let s=uy[a];return s===`ready_stop`&&e.status===`preview_ready`?{...t,interaction:`direct`,reason:s,canApply:!0}:i(s===`ready_stop`?`action_review`:s)}function py(e){if(e.error_code===`action_stale`||e.error_code===`action_conflict`)return!0;let t=e.proposal;return typeof t==`object`&&!!t&&`status`in t&&t.status===`stale`}function my(e){return{blockingTodoCount:e.blockingTodoCount,goalNotifications:e.goalNotifications,goals:e.goals,openUserTodoCount:e.openUserTodoCount,systemHealth:e.systemHealth,attentionHistory:e.attentionHistory,userTodos:e.userTodos,workers:e.workers}}function hy(e,t){return e.goals.find(e=>e.goalId===t)?.title??t}function gy(e){return e.activationState===`stopped`||e.state===`已停止`?`stopped`:e.state===`已完成`?`history`:e.needsYou||e.state===`等你`?`needs_you`:e.state===`推进中`||e.state===`需修复`?`running`:e.state===`安静运行`?`observing`:`scheduled`}function _y(e){let t=e;return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function vy(e){return`$${e.toFixed(2)}`}function yy(e){let t=e;return t>=36e5?`${(t/36e5).toFixed(1)}h`:t>=6e4?`${(t/6e4).toFixed(1)}m`:t>=1e3?`${Math.round(t/1e3)}s`:`${t}ms`}function by(e,t,n){return e==null?t:n(e)}function xy(e){return!!(e&&[e.tokens24h,e.tokens7d,e.costUsd24h,e.costUsd7d,e.durationMs24h,e.durationMs7d].some(e=>e!=null))}function Sy(e,t){if(!xy(e))return null;let n=(e,n,r,i)=>{let a=[n==null?null:`${_y(n)} ${t.tokens}`,r==null?null:`${t.cost}: ${vy(r)}`,i==null?null:`${t.duration}: ${yy(i)}`].filter(e=>e!==null);return a.length?`${e} ${a.join(` · `)}`:null};return n(t.period7d,e.tokens7d,e.costUsd7d,e.durationMs7d)??n(t.period24h,e.tokens24h,e.costUsd24h,e.durationMs24h)}function Cy({ariaLabel:e,className:t,icon:n,onChange:r,options:i,prefixLabel:a,value:o}){let s=(0,z.useId)(),c=(0,z.useRef)(null),l=(0,z.useRef)(null),u=(0,z.useRef)(new Map),[d,f]=(0,z.useState)(!1),[p,m]=(0,z.useState)(o),h=i.find(e=>e.value===o)??i[0],g=i.filter(e=>!e.disabled);(0,z.useEffect)(()=>{if(!d)return;let e=e=>{c.current?.contains(e.target)||f(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[d]),(0,z.useEffect)(()=>{d&&u.current.get(p)?.focus()},[p,d]);function _(e){m(e)}function v(e=`selected`){let t=e===`last`?g.at(-1):g[0],n=e===`selected`&&h&&!h.disabled?h:t;n&&(f(!0),_(n.value))}function y({restoreFocus:e=!1}={}){f(!1),e&&l.current?.focus()}function b(e){e.disabled||(r(e.value),y({restoreFocus:!0}))}function x(e){if(!g.length)return;let t=g.findIndex(e=>e.value===p),n=t<0?0:(t+e+g.length)%g.length;_(g[n].value)}function S(e){e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),v(`selected`)):e.key===`ArrowUp`&&(e.preventDefault(),v(`last`))}function C(e,t){if(e.key===`ArrowDown`)e.preventDefault(),x(1);else if(e.key===`ArrowUp`)e.preventDefault(),x(-1);else if(e.key===`Home`)e.preventDefault(),g[0]&&_(g[0].value);else if(e.key===`End`){e.preventDefault();let t=g.at(-1);t&&_(t.value)}else e.key===`Enter`||e.key===` `?(e.preventDefault(),b(t)):e.key===`Escape`?(e.preventDefault(),y({restoreFocus:!0})):e.key===`Tab`&&y()}let w;return(0,B.jsxs)(`div`,{className:`personal-select${t?` ${t}`:``}`,ref:c,children:[(0,B.jsxs)(`button`,{"aria-controls":s,"aria-expanded":d,"aria-haspopup":`listbox`,"aria-label":e,className:`personal-select-trigger`,"data-value":o,onClick:()=>d?y():v(),onKeyDown:S,ref:l,role:`combobox`,type:`button`,children:[n?(0,B.jsx)(`span`,{className:`personal-select-icon`,children:n}):null,(0,B.jsxs)(`span`,{className:`personal-select-value`,children:[a?(0,B.jsx)(`small`,{children:a}):null,(0,B.jsx)(`span`,{children:h?.label??o})]}),(0,B.jsx)(tm,{"aria-hidden":!0,className:d?`is-open`:void 0,size:14})]}),d?(0,B.jsx)(`div`,{"aria-label":e,className:`personal-select-listbox`,id:s,role:`listbox`,children:i.map(e=>{let t=e.group&&e.group!==w;return w=e.group,(0,B.jsxs)(`div`,{className:`personal-select-option-wrap`,children:[t?(0,B.jsx)(`div`,{className:`personal-select-group-label`,children:e.group}):null,(0,B.jsxs)(`button`,{"aria-disabled":e.disabled||void 0,"aria-selected":e.value===o,className:`personal-select-option`,disabled:e.disabled,id:`${s}-${e.value.replace(/[^a-z0-9_-]/gi,`-`)}`,onClick:()=>b(e),onFocus:()=>m(e.value),onKeyDown:t=>C(t,e),ref:t=>{t?u.current.set(e.value,t):u.current.delete(e.value)},role:`option`,tabIndex:e.value===p?0:-1,type:`button`,children:[(0,B.jsx)(`span`,{children:e.label}),e.value===o?(0,B.jsx)(em,{"aria-hidden":!0,size:15}):null]})]},e.value)})}):null]})}function wy({agents:e,managerChatOpen:t,mobileNavigationOpen:n,onOpenGoalCapabilities:r,onOpenGoalDetail:i,onOpenManagerChat:a,onRefresh:o,onOpenNavigation:s,onSelectGoalTab:c,onSelectAgent:l,onReturnManagerHome:u,refreshState:d,readOnlySourceLabel:f,selectedAgentId:p,selectedGoal:m,selectedGoalTab:h}){let{locale:g,t:_}=Ji(),[v,y]=(0,z.useState)(!1),b=(0,z.useRef)(null),x=(0,z.useRef)(null);(0,z.useEffect)(()=>{if(!v)return;function e(e){x.current?.contains(e.target)||y(!1)}function t(e){e.key===`Escape`&&(y(!1),b.current?.focus())}return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[v]),(0,z.useEffect)(()=>y(!1),[m?.goalId]);function S(e){y(!1),e?.()}let C=m?Sy(m.usage,{cost:_(`drawer.costShort`),duration:_(`drawer.durationShort`),period24h:_(`drawer.period24h`),period7d:_(`drawer.period7d`),tokens:_(`drawer.tokensShort`)}):null;return(0,B.jsxs)(`header`,{className:`personal-channel-header`,children:[(0,B.jsx)(`button`,{"aria-expanded":n??!1,"aria-label":_(`header.openGoalNavigation`),className:`personal-icon-button personal-mobile-menu`,onClick:s,type:`button`,children:(0,B.jsx)(Tm,{size:18})}),(0,B.jsxs)(`div`,{className:`personal-channel-title`,children:[(0,B.jsx)(`h1`,{children:m?.title??_(`header.manager`)}),m?(0,B.jsx)(`p`,{children:m.loadState?_(m.loadState===`error`?`startup.goalError`:`startup.goalLoading`):`${m.agentLaneCount&&m.agentLaneCount>1?_(`header.workAgentCount`,{count:m.agentLaneCount}):m.agentLabel??m.agentId} · ${m.loadState?_(m.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Yi(m.state,g)}${C?` · ${C}`:``} · ${m.nextSentence}`}):null]}),m?(0,B.jsxs)(`nav`,{"aria-label":_(`header.goalView`),className:`personal-goal-tabs`,children:[(0,B.jsx)(`button`,{"aria-current":h===`chat`?`page`:void 0,onClick:()=>c(`chat`),type:`button`,children:_(`header.chat`)}),(0,B.jsx)(`button`,{"aria-current":h===`tasks`?`page`:void 0,onClick:()=>c(`tasks`),type:`button`,children:_(`header.tasks`)}),(0,B.jsx)(`button`,{"aria-current":h===`files`?`page`:void 0,onClick:()=>c(`files`),type:`button`,children:_(`header.files`)})]}):(0,B.jsxs)(`nav`,{"aria-label":_(`header.managerView`),className:`personal-goal-tabs`,children:[(0,B.jsx)(`button`,{"aria-current":t?void 0:`page`,onClick:u,type:`button`,children:_(`header.managerOverview`)}),(0,B.jsx)(`button`,{"aria-current":t?`page`:void 0,onClick:a,type:`button`,children:_(`header.chat`)})]}),(0,B.jsxs)(`div`,{className:`personal-channel-actions`,children:[m&&i&&r?(0,B.jsxs)(`div`,{className:`personal-goal-tools`,ref:x,children:[(0,B.jsxs)(`button`,{"aria-expanded":v,"aria-haspopup":`menu`,"aria-label":_(`header.goalSettingsDescription`),className:`personal-goal-tools-trigger`,onClick:()=>y(e=>!e),ref:b,title:_(`header.goalSettingsDescription`),type:`button`,children:[(0,B.jsx)(Gm,{"aria-hidden":!0,size:16}),(0,B.jsx)(`span`,{children:_(`header.goalSettings`)}),(0,B.jsx)(tm,{"aria-hidden":!0,size:13})]}),v?(0,B.jsxs)(`fieldset`,{"aria-label":_(`header.goalSettings`),className:`personal-goal-tools-menu`,children:[(0,B.jsxs)(`button`,{onClick:()=>S(i),type:`button`,children:[(0,B.jsx)(ym,{"aria-hidden":!0,size:17}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:_(`header.goalDetails`)})})]}),(0,B.jsxs)(`button`,{onClick:()=>S(r),type:`button`,children:[(0,B.jsx)(Gm,{"aria-hidden":!0,size:17}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:_(`header.goalCapabilities`)})})]})]}):null]}):null,f?(0,B.jsxs)(`span`,{className:`personal-read-only-source`,title:_(`header.readOnlySourceDescription`,{source:f}),children:[(0,B.jsx)(pm,{size:15}),f,(0,B.jsx)(`small`,{children:_(`common.readOnly`)})]}):(0,B.jsx)(Cy,{ariaLabel:_(`header.selectChatRuntime`),className:`personal-agent-select`,icon:(0,B.jsx)(Zp,{size:16}),onChange:l,options:e.map(e=>({disabled:!e.available,label:`${e.label}${e.available?``:` · ${_(`header.agentUnavailable`)}`}`,value:e.agentId})),prefixLabel:_(`header.chatRuntime`),value:p}),(0,B.jsxs)(`span`,{className:`personal-live-indicator`,children:[(0,B.jsx)(`i`,{}),_(`header.live`)]}),o?(0,B.jsxs)(`span`,{className:`personal-refresh-control is-${d??`idle`}`,children:[d===`loading`?(0,B.jsx)(`small`,{children:_(`header.refreshing`)}):d===`done`?(0,B.jsx)(`small`,{children:_(`header.refreshDone`)}):d===`error`?(0,B.jsx)(`small`,{children:_(`header.refreshFailed`)}):null,(0,B.jsx)(`button`,{"aria-label":_(d===`loading`?`header.refreshing`:`header.refresh`),className:`personal-icon-button`,disabled:d===`loading`,onClick:o,type:`button`,children:(0,B.jsx)(Im,{className:d===`loading`?`is-spinning`:void 0,size:17})})]}):null]})]})}function Ty({attention:e,onSelect:t}){let{t:n}=Ji(),r=Zi(e.updatedAt,n);return(0,B.jsxs)(`button`,{className:`personal-timeline-row personal-attention-row`,"data-testid":`personal-browse-row`,onClick:t,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-row-icon is-attention`,children:(0,B.jsx)(im,{size:18})}),(0,B.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,B.jsxs)(`small`,{children:[e.goalTitle??e.goalId,` · `,n(`home.lane.needsYou`),r?` · ${n(`tasks.waitingAge`,{age:r})}`:``]}),(0,B.jsx)(`strong`,{children:e.text})]}),(0,B.jsx)(`span`,{className:`personal-priority-dot is-${e.priority??(e.blocking?`high`:`medium`)}`}),(0,B.jsx)(`span`,{className:`personal-row-status ${e.blocking?`is-blocking`:`is-pending`}`,children:e.blocking?n(`tasks.blocked`):n(`tasks.pending`)}),(0,B.jsx)(nm,{size:17})]})}var Ey=/(`[^`\n]+`)|(\*\*[^*\n]+(\*[^*\n]*)?\*\*)|(\[[^\]\n]{1,120}\]\(https?:\/\/[^)\s]+\))/g;function Dy(e,t){let n=[],r=0,i=0;for(let a of e.matchAll(Ey)){let o=a.index??0;o>r&&n.push(e.slice(r,o));let s=a[0],c=`${t}-i${i++}`;if(s.startsWith("`"))n.push((0,B.jsx)(`code`,{className:`personal-md-code`,children:s.slice(1,-1)},c));else if(s.startsWith(`**`))n.push((0,B.jsx)(`strong`,{children:s.slice(2,-2)},c));else{let e=s.indexOf(`](`),t=s.slice(1,e),r=s.slice(e+2,-1);n.push((0,B.jsx)(`a`,{className:`personal-md-link`,href:r,rel:`noreferrer`,target:`_blank`,children:t},c))}r=o+s.length}return r=4))throw e;await new Promise(e=>globalThis.setTimeout(e,250*2**(i-1)))}}if(!a)throw new Th(`Agent 事件流连接已断开。`,{reconnect_attempts:i})}async function qh(e,t){return Ih(`/api/chat/sessions/${e}/turns/${t}/interrupt`,{method:`POST`,body:`{}`})}async function Jh(e,t,n={}){let r=await Wh(e,t,n.clientTurnId??crypto.randomUUID(),n.attachments);return n.onPhase?.(`turn.accepted`,r.turn_id),Yh(e,r.turn_id,r.events_url,n)}async function Yh(e,t,n,r={}){let i=null,a={failure:null,interrupted:null};try{await Kh(n,e=>{r.onPhase?.(e.kind,t),(e.kind===`answer.delta`||e.kind===`assistant.delta`)&&r.onDelta?.(String(e.payload.text??``)),e.kind===`agent.phase`&&r.onActivity?.(String(e.payload.label??`Agent 正在处理`)),e.kind===`turn.completed`&&(i=e.payload.response),e.kind===`turn.failed`&&(a.failure=e.payload),e.kind===`turn.interrupted`&&(a.interrupted=e.payload)},r.signal)}catch(i){throw i instanceof Th&&!r.signal?.aborted?new Th(i.message,{...i.payload,events_url:n,reconnectable:!0,session_id:e,turn_id:t}):i}if(a.failure)throw new Th(String(a.failure.message||`Agent 回合失败。`),a.failure);if(a.interrupted)throw new Th(`Agent 回合已中断。`,{...a.interrupted,error_code:`turn_interrupted`,session_id:e,turn_id:t});return{response:yh.parse(i),sessionId:e,turnId:t}}async function Xh(e,t,n={}){return Yh(e,t,`/api/chat/sessions/${e}/turns/${t}/events`,n)}async function Zh(e){let t=bh.parse(await Ih(`/api/chat/sessions/${e}`,{keepalive:!0,method:`DELETE`}));if(t.session_id!==e)throw new Th(`Agent 会话关闭回执与本次请求不一致。`,{session_id:t.session_id});return t}async function Qh(e){return Ih(`/api/chat/sessions/${e}/resume`,{method:`POST`,body:`{}`})}function $h(e){return{goal_id:e.goalId,enabled:e.enabled,...e.modelConfig===void 0?{}:{model_config:e.modelConfig},...e.enabled?{max_children:e.maxChildren,allowed_domains:e.allowedDomains}:{}}}function eg(e,t){let n=e.after.orchestration,r=[...new Set(t.allowedDomains)],i=e.feature_summary.multi_subagent===`enabled`;if(!(e.goal_id===t.goalId&&i===t.enabled&&(t.modelConfig===void 0||JSON.stringify(n.model_config??null)===JSON.stringify(t.modelConfig))&&(t.enabled?n.max_children===t.maxChildren&&JSON.stringify(n.allowed_domains)===JSON.stringify(r):n.spawn_allowed===!1&&n.max_children===0)))throw new Th(`Goal 子代理配置回执与本次请求不一致,界面已停止更新。`,{after:e.after,goal_id:e.goal_id});return e}async function tg(e){let t=Ch.parse(await Ih(`/api/chat/goal-subagents/dry-run`,{method:`POST`,body:JSON.stringify($h(e))}));if(!t.dry_run||t.execute||t.written)throw new Th(`Goal 子代理预览返回了非预览回执,已停止进入确认状态。`,{result:t});return eg(t,e)}async function ng(e,t){let n=Ch.parse(await Ih(`/api/chat/goal-subagents/apply`,{method:`POST`,body:JSON.stringify({...$h(e),preview_id:t})}));if(n.preview_id!==t||n.dry_run||!n.execute)throw new Th(`Goal 子代理写入回执与本次确认不一致,界面已停止更新。`,{result:n});if(n.changed&&(!n.written||!n.global_sync.executed||!n.global_sync.readback.verified))throw new Th(`Goal 子代理设置未通过共享状态读回验证。`,{result:n});return eg(n,e)}var rg=J({ok:X(!0),targets:q(J({enabled:K(),provider:W(),target_name:W()}))});async function ig(){return rg.parse(await Ih(`/api/chat/goal-channel/targets`)).targets}var ag=J({ok:K(),blocker:W().optional(),public_summary:W().optional(),status:W().optional()});async function og(e){return ag.parse(await Ih(`/api/chat/goal-channel/setup`,{method:`POST`,body:JSON.stringify({execute:e.execute,goal_id:e.goalId,target:e.target})}))}async function sg(e){return ag.parse(await Ih(`/api/chat/goal-channel/configure`,{method:`POST`,body:JSON.stringify({auto_notify_human_gates:e.autoNotify,goal_id:e.goalId})}))}var cg=J({schema_version:X(`periodic_report_schedule_v0`),schedule_id:W(),rrule:W(),timezone:W()});J({schema_version:X(`periodic_report_machine_defaults_v0`),enabled:K(),inheritance:X(`live_machine_default`),profile_preset:W().optional(),route_ref:W().optional(),timezone:W(),schedule:cg.nullable().optional()});var lg=J({schema_version:X(`loopx_machine_configuration_v0`),namespaces:gd(W(),gd(W(),id()))}),ug=J({namespace:W(),title:W(),description:W(),schema_versions:q(W()).min(1),configuration_template:gd(W(),id()),template_status:Y([`ready`,`schema_only`])}),dg=J({schema_version:X(`machine_configuration_catalog_v0`),namespaces:q(ug)}),fg=J({key:W(),label:W(),description:W(),input_kind:Y([`boolean`,`number`,`select`,`string_list`,`text`,`periodic_report_schedule`]),nullable:K().optional(),required:K(),minimum:G().int().optional(),maximum:G().int().optional(),options:q(W()).optional()}),pg=J({schema_version:X(`capability_configuration_editor_v0`),editable:K(),supported_scopes:q(Y([`goal`,`machine`])),writable_scopes:q(Y([`goal`,`machine`])),fields:q(fg),read_only_reason:W().optional()}),mg=J({schema_version:X(`capability_configuration_catalog_v0`),capabilities:q(J({capability_id:W(),display_name:W(),description:W(),available_scopes:q(Y([`goal`,`machine`])),machine_namespace:W().optional(),goal_feature_id:W().optional(),effective_value_policy:X(`goal_override_over_live_machine_default`).optional(),availability:W().optional(),default:gd(W(),id()).optional(),current:gd(W(),id()).optional(),machine_current:gd(W(),id()).optional(),effective_configuration:J({schema_version:X(`capability_configuration_resolution_v0`),capability_id:W(),source:Y([`goal_override`,`machine_default`,`capability_default`,`not_configured`]),configuration:gd(W(),id()).nullable(),inherited:K(),goal_override_present:K(),machine_default_present:K(),effective_revision:W()}).optional(),documentation:gd(W(),id()).optional(),context_contribution:J({supported_phases:q(Y([`before_plan`,`before_delegate`,`after_delegate_result`])),target:X(`coordinator`),activation:X(`with_capability`),receipt_required:X(!0)}).optional(),configuration_editor:pg}))}),hg=J({ok:X(!0),schema_version:X(`goal_configuration_inspection_v0`),status:X(`configured`),goal_id:W(),revision:W(),available_capabilities:q(W()),capability_catalog:mg}),gg=J({ok:X(!0),goal_id:W(),capability_id:W(),changed_fields:q(W()),goal_configuration:gd(W(),id()).nullable(),capability_catalog:mg}),_g=gg.extend({schema_version:X(`goal_configuration_update_plan_v0`),status:X(`preview`),action:Y([`create`,`update`,`delete`,`unchanged`]),current_revision:W(),desired_revision:W(),base_revision:W(),plan_revision:W(),writes_required:G().int().nonnegative()}),vg=ud([gg.extend({schema_version:X(`goal_configuration_transaction_v0`),status:Y([`applied`,`unchanged`]),plan_revision:W(),applied_revision:W(),readback_verified:X(!0)}),J({ok:X(!1),schema_version:X(`goal_configuration_transaction_v0`),status:X(`partial_write`),goal_id:W(),capability_id:W(),plan_revision:W(),applied_revision:W().nullable(),source_written:X(!0),shared_sync_pending:X(!0),readback_verified:K(),changed_fields:q(W()),goal_configuration:gd(W(),id()).nullable(),capability_catalog:mg,error:W(),recommended_action:W()})]),yg=J({ok:X(!0),available_namespaces:q(W()),namespace_catalog:dg.optional().default({schema_version:`machine_configuration_catalog_v0`,namespaces:[]}),capability_catalog:mg,changed_namespaces:q(W()).optional().default([]),machine_configuration:lg.nullable().optional()}),bg=yg.extend({schema_version:X(`machine_configuration_inspection_v0`),status:Y([`configured`,`absent`]),revision:W()}),xg=yg.extend({schema_version:X(`machine_configuration_update_plan_v0`),status:X(`preview`),action:Y([`create`,`update`,`delete`,`unchanged`]),current_revision:W(),desired_revision:W(),plan_revision:W(),writes_required:G().int().nonnegative(),machine_configuration:lg.nullable()}),Sg=yg.extend({schema_version:X(`machine_configuration_transaction_v0`),status:Y([`applied`,`unchanged`]),plan_revision:W(),transaction_id:W().nullable(),readback_verified:X(!0),rollback_available:K(),applied_revision:W().optional(),prior_revision:W().optional()}),Cg=yg.extend({schema_version:X(`machine_configuration_rollback_plan_v0`),status:X(`preview`),action:Y([`delete`,`restore`,`unchanged`,`blocked`]),reason:W(),transaction_id:W(),plan_revision:W(),rollback_allowed:K(),writes_required:G().int().nonnegative()}),wg=yg.extend({schema_version:X(`machine_configuration_rollback_receipt_v0`),status:Y([`rolled_back`,`unchanged`]),transaction_id:W(),plan_revision:W(),rollback_id:W().nullable(),readback_verified:X(!0)});async function Tg(){return bg.parse(await Ih(`/api/chat/machine-configuration`))}async function Eg(e){let t=new URLSearchParams({goal_id:e});return hg.parse(await Ih(`/api/chat/goal-configuration?${t.toString()}`))}async function Dg(e,t,n){return _g.parse(await Ih(`/api/chat/goal-configuration/preview`,{method:`POST`,body:JSON.stringify({goal_id:e,capability_id:t,configuration:n})}))}async function Og(e,t,n,r){return vg.parse(await Ih(`/api/chat/goal-configuration/apply`,{method:`POST`,body:JSON.stringify({goal_id:e,capability_id:t,configuration:n,expected_plan_revision:r})}))}async function kg(e,t){return xg.parse(await Ih(`/api/chat/machine-configuration/preview`,{method:`POST`,body:JSON.stringify({namespace:e,namespace_configuration:t})}))}async function Ag(e,t,n){return Sg.parse(await Ih(`/api/chat/machine-configuration/apply`,{method:`POST`,body:JSON.stringify({expected_plan_revision:n,namespace:e,namespace_configuration:t})}))}async function jg(e){return xg.parse(await Ih(`/api/chat/machine-configuration/preview`,{method:`POST`,body:JSON.stringify({namespace:e,operation:`remove`})}))}async function Mg(e,t){return Sg.parse(await Ih(`/api/chat/machine-configuration/apply`,{method:`POST`,body:JSON.stringify({expected_plan_revision:t,namespace:e,operation:`remove`})}))}async function Ng(e){return Cg.parse(await Ih(`/api/chat/machine-configuration/rollback`,{method:`POST`,body:JSON.stringify({execute:!1,transaction_id:e})}))}async function Pg(e,t){return wg.parse(await Ih(`/api/chat/machine-configuration/rollback`,{method:`POST`,body:JSON.stringify({execute:!0,expected_plan_revision:t,transaction_id:e})}))}var Fg=J({ok:X(!0),goals:q(J({goal_id:W(),repository:J({branch:W(),identity:W(),label:W(),read_only:X(!0)})}))});async function Ig(){return Fg.parse(await Ih(`/api/chat/goals/contexts`)).goals}var Lg=J({ok:X(!0),apps:q(J({active:K(),app_ref:W(),brand:W(),health_error_code:W().nullable().default(null),label:W(),ready:K(),reply_ready:K().default(!1)}))});async function Rg(){return Lg.parse(await Ih(`/api/chat/lark/apps`)).apps}var zg=J({ok:X(!0),app_ref:W(),error:W().nullable(),setup_id:W(),status:Y([`starting`,`waiting_for_feishu`,`ready`,`failed`,`cancelled`]),verification_url:W().url().nullable()});async function Bg(e){return zg.parse(await Ih(`/api/chat/lark/app-setups`,{method:`POST`,body:JSON.stringify({app_ref:e.appRef,brand:e.brand})}))}async function Vg(e){return zg.parse(await Ih(`/api/chat/lark/app-setups/${encodeURIComponent(e)}`))}async function Hg(e){return zg.parse(await Ih(`/api/chat/lark/app-setups/${encodeURIComponent(e)}`,{method:`DELETE`}))}var Ug=[`invalid_event`,`binding_unavailable`,`chat_mismatch`,`topic_mismatch`,`route_ambiguous`,`self_message`,`invalid_routing_state`,`not_addressed`],Wg=J({ok:X(!0),chats:q(J({chat_id:W(),chat_name:W()}))});async function Gg(e,t){let n=new URLSearchParams({app_ref:e});return t&&n.set(`query`,t),Wg.parse(await Ih(`/api/chat/lark/chats?${n.toString()}`)).chats}var Kg=J({ok:X(!0),connections:q(J({conversation_kind:Y([`goal`,`manager`]).default(`goal`),agent_id:W().nullable().default(null),connection_id:W(),app_label:W(),app_ref:W(),capture_scope:Y([`addressed_only`,`configured_chat_all`]).default(`addressed_only`),chat_name:W(),enabled:K(),goal_id:W(),goal_title:W(),health_error_code:W().nullable().default(null),history_permission_guidance:J({action:X(`enable_application_scopes_and_publish`),api_document_url:W().url(),capability:X(`group_history_pagination`),identity:X(`bot`),required_scopes:md([X(`im:message.group_msg`),X(`im:message.group_msg.include_bot:read`)]),schema_version:X(`lark_bot_group_history_permission_guidance_v0`)}).nullable().default(null),incoming_mode:Y([`mentions`,`all`]),ingress_mode:Y([`live_steering`,`session_queue`,`async_inbox`,`direct_session`]).default(`async_inbox`),event_count:G().int().nonnegative().default(0),last_event_reason:Y(Ug).nullable().default(null).catch(null),last_event_status:W().nullable().default(null),listener_error_code:W().nullable().default(null),listener_status:Y([`starting`,`listening`,`retrying`,`stopped`]).nullable().default(null),replied_count:G().int().nonnegative().default(0),reply_ready:K().default(!1),reply_mode:X(`topic_reply`),session_bound:K().default(!1),target_ref:W(),topic_name:W(),topic_setup_required:K()}))});async function qg(){return Kg.parse(await Ih(`/api/chat/lark/connections`)).connections}async function Jg(e){return ag.parse(await Ih(`/api/chat/lark/connections`,{method:`POST`,body:JSON.stringify({...e.agentBindings?{agent_bindings:e.agentBindings.map(e=>({agent_id:e.agentId,app_ref:e.appRef}))}:{},...e.agentId?{agent_id:e.agentId}:{},...e.appRef?{app_ref:e.appRef}:{},...e.connectionId?{connection_id:e.connectionId}:{},conversation_kind:e.conversationKind??`goal`,capture_scope:e.captureScope,chat_id:e.chatId,chat_name:e.chatName,execute:e.execute,goal_id:e.goalId,incoming_mode:e.incomingMode,ingress_mode:e.ingressMode,reply_mode:e.replyMode})}))}async function Yg(e,t){let n=new URLSearchParams({goal_id:e,connection_id:t});return ag.parse(await Ih(`/api/chat/lark/connections?${n.toString()}`,{method:`DELETE`}))}function Xg(e){return{loadedUrl:null,projectionRevision:0,requestedUrl:e,selectionRevision:0,requestGeneration:0}}function Zg(e,t){return e.selectionRevision+=1,e.requestedUrl=t,e.selectionRevision}function Qg(e,t,n){if(n.background)return e.requestedUrl!==null||e.loadedUrl!==t?null:(e.requestGeneration+=1,{background:!0,projectionRevision:e.projectionRevision,selectionRevision:e.selectionRevision,url:t,generation:e.requestGeneration});let r=n.selectionRevision??e.selectionRevision+1;return n.selectionRevision!==void 0&&e.selectionRevision!==r?null:(e.selectionRevision=r,e.projectionRevision+=1,e.requestedUrl=t,e.requestGeneration+=1,{background:!1,projectionRevision:e.projectionRevision,selectionRevision:r,url:t,generation:e.requestGeneration})}function $g(e,t){return t.generation===e.requestGeneration&&e.projectionRevision===t.projectionRevision&&e.selectionRevision===t.selectionRevision}function e_(e,t){return $g(e,t)&&(!t.background||e.requestedUrl===null&&e.loadedUrl===t.url)}function t_(e,t,n){return t.get(e)===n}function n_(e,t,n,r){return e.filter(e=>t_(r(e),n,t))}function r_(e,t,n){let r=new Set,i=[];for(let a of[...e,...t]){let e=n(a);e==null||r.has(e)||(r.add(e),i.push(a))}return i}var i_=[`runs_24h`,`runs_7d`,`quota_spend_slots_24h`,`quota_spend_slots_7d`,`automation_run_count_24h`,`automation_run_count_7d`,`progress_signal_run_count_24h`,`progress_signal_run_count_7d`],a_=[`input_tokens_24h`,`input_tokens_7d`,`output_tokens_24h`,`output_tokens_7d`,`cache_tokens_24h`,`cache_tokens_7d`,`cost_usd_24h`,`cost_usd_7d`,`duration_ms_24h`,`duration_ms_7d`],o_=[`accounting`,`decision`,`evidence`,`state`,`work`],s_={accounting:0,decision:0,evidence:0,state:0,work:0},c_={runs_24h:0,runs_7d:0,quota_spend_slots_24h:0,quota_spend_slots_7d:0,automation_run_count_24h:0,automation_run_count_7d:0,progress_signal_run_count_24h:0,progress_signal_run_count_7d:0};function l_(e,t){let n={...e};for(let r of i_)n[r]=(Number(e[r])||0)+(Number(t[r])||0);for(let r of a_)(e[r]!==void 0||t[r]!==void 0)&&(n[r]=(e[r]??0)+(t[r]??0));return n}function u_(e,t){return!e.length||t<=0?e:e.map(e=>({...e,project_share_24h:Math.round((Number(e.runs_24h)||0)/t*1e3)/1e3}))}function d_(e,t){let n={...e};for(let r of o_)n[r]=(e[r]??0)+(t[r]??0);return n}function f_(e){let t={events_24h:0,events_7d:0,by_class_24h:{...s_},by_class_7d:{...s_}};for(let n of e)t.events_24h+=n.events_24h,t.events_7d+=n.events_7d,t.by_class_24h=d_(t.by_class_24h,n.by_class_24h),t.by_class_7d=d_(t.by_class_7d,n.by_class_7d);return t}function p_(e,t,n){if(!e&&!t)return null;let r=n_(e?.goals??[],`active`,n,e=>e.goal_id),i=n_(t?.goals??[],`stopped`,n,e=>e.goal_id),a=r_(r,i,e=>e.goal_id),o=f_(r),s=f_(i),c={events_24h:o.events_24h+s.events_24h,events_7d:o.events_7d+s.events_7d,by_class_24h:d_(o.by_class_24h,s.by_class_24h),by_class_7d:d_(o.by_class_7d,s.by_class_7d)};return{...e??t,goals:a,sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),totals:c}}function m_(e,t,n){if(!e&&!t)return null;let r=r_([...n_(e?.items??[],`active`,n,e=>e.goal_id),...n_(t?.items??[],`stopped`,n,e=>e.goal_id)],[],e=>`${e.goal_id}:${e.decision_kind??``}:${e.decision_at??``}`),i={decision_count:(e?.summary.decision_count??0)+(t?.summary.decision_count??0),stale_count:r.filter(e=>e.stale_by_age).length,rebase_required_count:(e?.summary.rebase_required_count??0)+(t?.summary.rebase_required_count??0),fresh_count:(e?.summary.fresh_count??0)+(t?.summary.fresh_count??0)};return{...e??t,items:r,sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),summary:i}}function h_(e,t){return r_([...e,...t].sort((e,t)=>t.generated_at.localeCompare(e.generated_at)),[],e=>`${e.goal_id}:${e.generated_at}:${e.classification??``}`)}function g_(e,t,n){let r=r_(n_(e.items,`active`,n,e=>e.goal_id),n_(t.items,`stopped`,n,e=>e.goal_id),e=>e.goal_id);return{...e,item_count:r.length,items:r,needs_controller:r.filter(e=>e.waiting_on===`controller`).length,needs_codex:r.filter(e=>e.waiting_on===`codex`).length,needs_user_or_controller:r.filter(e=>[`user_or_controller`,`controller`].includes(e.waiting_on)).length,watching_external_evidence:r.filter(e=>e.waiting_on===`external_evidence`).length}}function __(e){let t=e.todo_id?.trim()||``;return t?`${e.goal_id}:${t}`:`${e.goal_id}:synthetic:${e.role??``}:${e.index??``}:${e.text??``}`}function v_(e){let t={...c_};for(let n of e){for(let e of i_)t[e]+=Number(n[e])||0;for(let e of a_)n[e]!==void 0&&(t[e]=(t[e]??0)+n[e])}return t}function y_(e,t,n){if(!e&&!t)return null;let r=n_(e?.items??[],`active`,n,e=>e.goal_id),i=n_(t?.items??[],`stopped`,n,e=>e.goal_id),a=r_(r,i,__);return{...e??t,current_projected_count:r.length+i.length,items:a,rollout_event_count:a.reduce((e,t)=>e+(t.event_count??0),0),total_count:a.length}}function b_(e,t,n){if(!e&&!t)return null;let r=n_(e?.goals??[],`active`,n,e=>e.goal_id),i=n_(t?.goals??[],`stopped`,n,e=>e.goal_id),a=r_(r,i,e=>e.goal_id),o=l_(v_(r),v_(i));return{...e??t,goals:u_(a,Number(o.runs_24h)||0),sample_run_count:(e?.sample_run_count??0)+(t?.sample_run_count??0),totals:o}}function x_(e,t,n){if(!e&&!t)return null;let r=(e?.agents??[]).filter(e=>e.goal_ids.some(e=>t_(e,n,`active`))||(e.current_todo?.goal_id?t_(e.current_todo.goal_id,n,`active`):!1)),i=(t?.agents??[]).filter(e=>e.goal_ids.some(e=>t_(e,n,`stopped`))||(e.current_todo?.goal_id?t_(e.current_todo.goal_id,n,`stopped`):!1)),a=r_(r,i,e=>e.agent_id).map(e=>{let t=i.find(t=>t.agent_id===e.agent_id);return t?{...e,goal_ids:Array.from(new Set([...e.goal_ids??[],...t.goal_ids]))}:e});return{...e??t,agents:a,source_summary:(e??t)?.source_summary?{...(e??t).source_summary,projected_agent_count:a.length,registered_agent_count:new Set(a.map(e=>e.agent_id)).size}:(e??t)?.source_summary}}function S_(e,t,n){if(!e&&!t)return null;let r=r_(n_(e?.goals??[],`active`,n,e=>e.goal_id),n_(t?.goals??[],`stopped`,n,e=>e.goal_id),e=>e.goal_id);return{...e??t,goals:r}}function C_(e,t){let n=t.goal_projection?.scope;if(n!==`active`&&n!==`stopped`)return t;let r=n,i=t.run_history.goals,a=e.run_history.goals,o=r_(r===`active`?i:a.filter(e=>e.activation_state!==`stopped`),r===`stopped`?i:a.filter(e=>e.activation_state===`stopped`),e=>e.id),s=new Map(o.map(e=>[e.id,e.activation_state])),c=r===`active`?t:e,l=r===`stopped`?t:e,u=e.goal_projection?.registry_revision??null,d=t.goal_projection?.registry_revision??null,f=u===null||d===null||u===d;return{...e,agent_management_projection:x_(c.agent_management_projection,l.agent_management_projection,s),attention_queue:g_(c.attention_queue,l.attention_queue,s),decision_freshness_summary:m_(c.decision_freshness_summary,l.decision_freshness_summary,s),event_ledger_summary:p_(c.event_ledger_summary,l.event_ledger_summary,s),goal_channel_notification_projection:S_(c.goal_channel_notification_projection,l.goal_channel_notification_projection,s),goal_projection:{schema_version:`loopx_goal_projection_scope_v0`,...t.goal_projection,complete:f,projected_goal_count:o.length,registry_goal_count:t.goal_projection?.registry_goal_count??0,scope:`all`},run_history:{...e.run_history,goal_count:o.length,goals:o,recent_runs:h_(c.run_history.recent_runs,l.run_history.recent_runs),run_count:c.run_history.run_count+l.run_history.run_count},todo_index:y_(c.todo_index,l.todo_index,s),usage_summary:b_(c.usage_summary,l.usage_summary,s)}}function w_(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`){if(Array.isArray(e)){var i=e.length;for(t=0;ttypeof e==`boolean`?`${e}`:e===0?`0`:e,D_=T_,O_=(e,t)=>n=>{if(t?.variants==null)return D_(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=E_(t)||E_(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return D_(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)},k_=(e,t)=>{let n=Array(e.length+t.length);for(let t=0;t({classGroupId:e,validator:t}),j_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),M_=`-`,N_=[],P_=`arbitrary..`,F_=e=>{let t=R_(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return L_(e);let n=e.split(M_);return I_(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?k_(i,t):t:i||N_}return n[e]||N_}}},I_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=I_(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(M_):e.slice(t).join(M_),s=a.length;for(let e=0;ee.slice(1,-1).indexOf(`:`)===-1?void 0:(()=>{let t=e.slice(1,-1),n=t.indexOf(`:`),r=t.slice(0,n);return r?P_+r:void 0})(),R_=e=>{let{theme:t,classGroups:n}=e;return z_(n,t)},z_=(e,t)=>{let n=j_();for(let r in e){let i=e[r];B_(i,n,r,t)}return n},B_=(e,t,n,r)=>{let i=e.length;for(let a=0;a{if(typeof e==`string`){H_(e,t,n);return}if(typeof e==`function`){U_(e,t,n,r);return}W_(e,t,n,r)},H_=(e,t,n)=>{let r=e===``?t:G_(t,e);r.classGroupId=n},U_=(e,t,n,r)=>{if(K_(e)){B_(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(A_(n,e))},W_=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e{let n=e,r=t.split(M_),i=r.length;for(let e=0;e`isThemeGetter`in e&&e.isThemeGetter===!0,q_=e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null),i=(i,a)=>{n[i]=a,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];if(t!==void 0)return t;if((t=r[e])!==void 0)return i(e,t),t},set(e,t){e in n?n[e]=t:i(e,t)}}},J_=`!`,Y_=`:`,X_=[],Z_=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),Q_=e=>{let{prefix:t,experimentalParseClassName:n}=e,r=e=>{let t=[],n=0,r=0,i=0,a,o=e.length;for(let s=0;si?a-i:void 0;return Z_(t,l,c,u)};if(t){let e=t+Y_,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):Z_(X_,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},$_=e=>{let t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{let n=[],r=[];for(let i=0;i0&&(r.sort(),n.push(...r),r=[]),n.push(a)):r.push(a)}return r.length>0&&(r.sort(),n.push(...r)),n}},ev=e=>({cache:q_(e.cacheSize),parseClassName:Q_(e),sortModifiers:$_(e),postfixLookupClassGroupIds:tv(e),...F_(e)}),tv=e=>{let t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let e=0;e{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a,postfixLookupClassGroupIds:o}=t,s=[],c=e.trim().split(nv),l=``;for(let e=c.length-1;e>=0;--e){let t=c[e],{isExternal:u,modifiers:d,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:m}=n(t);if(u){l=t+(l.length>0?` `+l:l);continue}let h=!!m,g;if(h){g=r(p.substring(0,m));let e=g&&o[g]?r(p):void 0;e&&e!==g&&(g=e,h=!1)}else g=r(p);if(!g){if(!h){l=t+(l.length>0?` `+l:l);continue}if(g=r(p),!g){l=t+(l.length>0?` `+l:l);continue}h=!1}let _=d.length===0?``:d.length===1?d[0]:a(d).join(`:`),v=f?_+J_:_,y=v+g;if(s.indexOf(y)>-1)continue;s.push(y);let b=i(g,h);for(let e=0;e0?` `+l:l)}return l},iv=(...e)=>{let t=0,n,r,i=``;for(;t{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r{let n,r,i,a,o=o=>(n=ev(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,a=s,s(o)),s=e=>{let t=r(e);if(t)return t;let a=rv(e,n);return i(e,a),a};return a=o,(...e)=>a(iv(...e))},sv=[],cv=e=>{let t=t=>t[e]||sv;return t.isThemeGetter=!0,t},lv=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,uv=/^\((?:(\w[\w-]*):)?(.+)\)$/i,dv=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,fv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,pv=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,mv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,hv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,gv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,_v=e=>dv.test(e),vv=e=>!!e&&!Number.isNaN(Number(e)),yv=e=>!!e&&Number.isInteger(Number(e)),bv=e=>e.endsWith(`%`)&&vv(e.slice(0,-1)),xv=e=>fv.test(e),Sv=()=>!0,Cv=e=>pv.test(e)&&!mv.test(e),wv=()=>!1,Tv=e=>hv.test(e),Ev=e=>gv.test(e),Dv=e=>!Q(e)&&!$(e),Ov=e=>e.startsWith(`@container`)&&(e[10]===`/`&&e[11]!==void 0||e[11]===`s`&&e[16]!==void 0&&e.startsWith(`-size/`,10)||e[11]===`n`&&e[18]!==void 0&&e.startsWith(`-normal/`,10)),kv=e=>Wv(e,Jv,wv),Q=e=>lv.test(e),Av=e=>Wv(e,Yv,Cv),jv=e=>Wv(e,Xv,vv),Mv=e=>Wv(e,Qv,Sv),Nv=e=>Wv(e,Zv,wv),Pv=e=>Wv(e,Kv,wv),Fv=e=>Wv(e,qv,Ev),Iv=e=>Wv(e,$v,Tv),$=e=>uv.test(e),Lv=e=>Gv(e,Yv),Rv=e=>Gv(e,Zv),zv=e=>Gv(e,Kv),Bv=e=>Gv(e,Jv),Vv=e=>Gv(e,qv),Hv=e=>Gv(e,$v,!0),Uv=e=>Gv(e,Qv,!0),Wv=(e,t,n)=>{let r=lv.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Gv=(e,t,n=!1)=>{let r=uv.exec(e);return r?r[1]?t(r[1]):n:!1},Kv=e=>e===`position`||e===`percentage`,qv=e=>e===`image`||e===`url`,Jv=e=>e===`length`||e===`size`||e===`bg-size`,Yv=e=>e===`length`,Xv=e=>e===`number`,Zv=e=>e===`family-name`,Qv=e=>e===`number`||e===`weight`,$v=e=>e===`shadow`,ey=ov(()=>{let e=cv(`color`),t=cv(`font`),n=cv(`text`),r=cv(`font-weight`),i=cv(`tracking`),a=cv(`leading`),o=cv(`breakpoint`),s=cv(`container`),c=cv(`spacing`),l=cv(`radius`),u=cv(`shadow`),d=cv(`inset-shadow`),f=cv(`text-shadow`),p=cv(`drop-shadow`),m=cv(`blur`),h=cv(`perspective`),g=cv(`aspect`),_=cv(`ease`),v=cv(`animate`),y=()=>[`auto`,`avoid`,`all`,`avoid-page`,`page`,`left`,`right`,`column`],b=()=>[`center`,`top`,`bottom`,`left`,`right`,`top-left`,`left-top`,`top-right`,`right-top`,`bottom-right`,`right-bottom`,`bottom-left`,`left-bottom`],x=()=>[...b(),$,Q],S=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],C=()=>[`auto`,`contain`,`none`],w=()=>[$,Q,c],T=()=>[_v,`full`,`auto`,...w()],E=()=>[yv,`none`,`subgrid`,$,Q],D=()=>[`auto`,{span:[`full`,yv,$,Q]},yv,$,Q],O=()=>[yv,`auto`,$,Q],ee=()=>[`auto`,`min`,`max`,`fr`,$,Q],te=()=>[`start`,`end`,`center`,`between`,`around`,`evenly`,`stretch`,`baseline`,`center-safe`,`end-safe`],ne=()=>[`start`,`end`,`center`,`stretch`,`center-safe`,`end-safe`],k=()=>[`auto`,...w()],A=()=>[_v,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...w()],j=()=>[_v,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...w()],M=()=>[_v,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...w()],N=()=>[e,$,Q],P=()=>[...b(),zv,Pv,{position:[$,Q]}],F=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],re=()=>[`auto`,`cover`,`contain`,Bv,kv,{size:[$,Q]}],ie=()=>[bv,Lv,Av],I=()=>[``,`none`,`full`,l,$,Q],ae=()=>[``,vv,Lv,Av],L=()=>[`solid`,`dashed`,`dotted`,`double`],oe=()=>[`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`],se=()=>[vv,bv,zv,Pv],ce=()=>[``,`none`,m,$,Q],le=()=>[`none`,vv,$,Q],ue=()=>[`none`,vv,$,Q],de=()=>[vv,$,Q],fe=()=>[_v,`full`,...w()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[xv],breakpoint:[xv],color:[Sv],container:[xv],"drop-shadow":[xv],ease:[`in`,`out`,`in-out`],font:[Dv],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[xv],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[xv],shadow:[xv],spacing:[`px`,vv],text:[xv],"text-shadow":[xv],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,_v,Q,$,g]}],container:[`container`],"container-type":[{"@container":[``,`normal`,`size`,$,Q]}],"container-named":[Ov],columns:[{columns:[vv,Q,$,s]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":[`auto`,`avoid`,`avoid-page`,`avoid-column`]}],"box-decoration":[{"box-decoration":[`slice`,`clone`]}],box:[{box:[`border`,`content`]}],display:[`block`,`inline-block`,`inline`,`flex`,`inline-flex`,`table`,`inline-table`,`table-caption`,`table-cell`,`table-column`,`table-column-group`,`table-footer-group`,`table-header-group`,`table-row-group`,`table-row`,`flow-root`,`grid`,`inline-grid`,`contents`,`list-item`,`hidden`],sr:[`sr-only`,`not-sr-only`],float:[{float:[`right`,`left`,`none`,`start`,`end`]}],clear:[{clear:[`left`,`right`,`both`,`none`,`start`,`end`]}],isolation:[`isolate`,`isolation-auto`],"object-fit":[{object:[`contain`,`cover`,`fill`,`none`,`scale-down`]}],"object-position":[{object:x()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:[`static`,`fixed`,`absolute`,`relative`,`sticky`],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{"inset-s":T(),start:T()}],end:[{"inset-e":T(),end:T()}],"inset-bs":[{"inset-bs":T()}],"inset-be":[{"inset-be":T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:[`visible`,`invisible`,`collapse`],z:[{z:[yv,`auto`,$,Q]}],basis:[{basis:[_v,`full`,`auto`,s,...w()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[vv,_v,`auto`,`initial`,`none`,Q]}],grow:[{grow:[``,vv,$,Q]}],shrink:[{shrink:[``,vv,$,Q]}],order:[{order:[yv,`first`,`last`,`none`,$,Q]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":[`row`,`col`,`dense`,`row-dense`,`col-dense`]}],"auto-cols":[{"auto-cols":ee()}],"auto-rows":[{"auto-rows":ee()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...te(),`normal`]}],"justify-items":[{"justify-items":[...ne(),`normal`]}],"justify-self":[{"justify-self":[`auto`,...ne()]}],"align-content":[{content:[`normal`,...te()]}],"align-items":[{items:[...ne(),{baseline:[``,`last`]}]}],"align-self":[{self:[`auto`,...ne(),{baseline:[``,`last`]}]}],"place-content":[{"place-content":te()}],"place-items":[{"place-items":[...ne(),`baseline`]}],"place-self":[{"place-self":[`auto`,...ne()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pbs:[{pbs:w()}],pbe:[{pbe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:k()}],mx:[{mx:k()}],my:[{my:k()}],ms:[{ms:k()}],me:[{me:k()}],mbs:[{mbs:k()}],mbe:[{mbe:k()}],mt:[{mt:k()}],mr:[{mr:k()}],mb:[{mb:k()}],ml:[{ml:k()}],"space-x":[{"space-x":w()}],"space-x-reverse":[`space-x-reverse`],"space-y":[{"space-y":w()}],"space-y-reverse":[`space-y-reverse`],size:[{size:A()}],"inline-size":[{inline:[`auto`,...j()]}],"min-inline-size":[{"min-inline":[`auto`,...j()]}],"max-inline-size":[{"max-inline":[`none`,...j()]}],"block-size":[{block:[`auto`,...M()]}],"min-block-size":[{"min-block":[`auto`,...M()]}],"max-block-size":[{"max-block":[`none`,...M()]}],w:[{w:[s,`screen`,...A()]}],"min-w":[{"min-w":[s,`screen`,`none`,...A()]}],"max-w":[{"max-w":[s,`screen`,`none`,`prose`,{screen:[o]},...A()]}],h:[{h:[`screen`,`lh`,...A()]}],"min-h":[{"min-h":[`screen`,`lh`,`none`,...A()]}],"max-h":[{"max-h":[`screen`,`lh`,...A()]}],"font-size":[{text:[`base`,n,Lv,Av]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,Uv,Mv]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,bv,Q]}],"font-family":[{font:[Rv,Nv,t]}],"font-features":[{"font-features":[Q]}],"fvn-normal":[`normal-nums`],"fvn-ordinal":[`ordinal`],"fvn-slashed-zero":[`slashed-zero`],"fvn-figure":[`lining-nums`,`oldstyle-nums`],"fvn-spacing":[`proportional-nums`,`tabular-nums`],"fvn-fraction":[`diagonal-fractions`,`stacked-fractions`],tracking:[{tracking:[i,$,Q]}],"line-clamp":[{"line-clamp":[vv,`none`,$,jv]}],leading:[{leading:[a,...w()]}],"list-image":[{"list-image":[`none`,$,Q]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,$,Q]}],"text-alignment":[{text:[`left`,`center`,`right`,`justify`,`start`,`end`]}],"placeholder-color":[{placeholder:N()}],"text-color":[{text:N()}],"text-decoration":[`underline`,`overline`,`line-through`,`no-underline`],"text-decoration-style":[{decoration:[...L(),`wavy`]}],"text-decoration-thickness":[{decoration:[vv,`from-font`,`auto`,$,Av]}],"text-decoration-color":[{decoration:N()}],"underline-offset":[{"underline-offset":[vv,`auto`,$,Q]}],"text-transform":[`uppercase`,`lowercase`,`capitalize`,`normal-case`],"text-overflow":[`truncate`,`text-ellipsis`,`text-clip`],"text-wrap":[{text:[`wrap`,`nowrap`,`balance`,`pretty`]}],indent:[{indent:w()}],"tab-size":[{tab:[yv,$,Q]}],"vertical-align":[{align:[`baseline`,`top`,`middle`,`bottom`,`text-top`,`text-bottom`,`sub`,`super`,$,Q]}],whitespace:[{whitespace:[`normal`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]}],break:[{break:[`normal`,`words`,`all`,`keep`]}],wrap:[{wrap:[`break-word`,`anywhere`,`normal`]}],hyphens:[{hyphens:[`none`,`manual`,`auto`]}],content:[{content:[`none`,$,Q]}],"bg-attachment":[{bg:[`fixed`,`local`,`scroll`]}],"bg-clip":[{"bg-clip":[`border`,`padding`,`content`,`text`]}],"bg-origin":[{"bg-origin":[`border`,`padding`,`content`]}],"bg-position":[{bg:P()}],"bg-repeat":[{bg:F()}],"bg-size":[{bg:re()}],"bg-image":[{bg:[`none`,{linear:[{to:[`t`,`tr`,`r`,`br`,`b`,`bl`,`l`,`tl`]},yv,$,Q],radial:[``,$,Q],conic:[yv,$,Q]},Vv,Fv]}],"bg-color":[{bg:N()}],"gradient-from-pos":[{from:ie()}],"gradient-via-pos":[{via:ie()}],"gradient-to-pos":[{to:ie()}],"gradient-from":[{from:N()}],"gradient-via":[{via:N()}],"gradient-to":[{to:N()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:ae()}],"border-w-x":[{"border-x":ae()}],"border-w-y":[{"border-y":ae()}],"border-w-s":[{"border-s":ae()}],"border-w-e":[{"border-e":ae()}],"border-w-bs":[{"border-bs":ae()}],"border-w-be":[{"border-be":ae()}],"border-w-t":[{"border-t":ae()}],"border-w-r":[{"border-r":ae()}],"border-w-b":[{"border-b":ae()}],"border-w-l":[{"border-l":ae()}],"divide-x":[{"divide-x":ae()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":ae()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...L(),`hidden`,`none`]}],"divide-style":[{divide:[...L(),`hidden`,`none`]}],"border-color":[{border:N()}],"border-color-x":[{"border-x":N()}],"border-color-y":[{"border-y":N()}],"border-color-s":[{"border-s":N()}],"border-color-e":[{"border-e":N()}],"border-color-bs":[{"border-bs":N()}],"border-color-be":[{"border-be":N()}],"border-color-t":[{"border-t":N()}],"border-color-r":[{"border-r":N()}],"border-color-b":[{"border-b":N()}],"border-color-l":[{"border-l":N()}],"divide-color":[{divide:N()}],"outline-style":[{outline:[...L(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[vv,$,Q]}],"outline-w":[{outline:[``,vv,Lv,Av]}],"outline-color":[{outline:N()}],shadow:[{shadow:[``,`none`,u,Hv,Iv]}],"shadow-color":[{shadow:N()}],"inset-shadow":[{"inset-shadow":[`none`,d,Hv,Iv]}],"inset-shadow-color":[{"inset-shadow":N()}],"ring-w":[{ring:ae()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:N()}],"ring-offset-w":[{"ring-offset":[vv,Av]}],"ring-offset-color":[{"ring-offset":N()}],"inset-ring-w":[{"inset-ring":ae()}],"inset-ring-color":[{"inset-ring":N()}],"text-shadow":[{"text-shadow":[`none`,f,Hv,Iv]}],"text-shadow-color":[{"text-shadow":N()}],opacity:[{opacity:[vv,$,Q]}],"mix-blend":[{"mix-blend":[...oe(),`plus-darker`,`plus-lighter`]}],"bg-blend":[{"bg-blend":oe()}],"mask-clip":[{"mask-clip":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]},`mask-no-clip`],"mask-composite":[{mask:[`add`,`subtract`,`intersect`,`exclude`]}],"mask-image-linear-pos":[{"mask-linear":[vv]}],"mask-image-linear-from-pos":[{"mask-linear-from":se()}],"mask-image-linear-to-pos":[{"mask-linear-to":se()}],"mask-image-linear-from-color":[{"mask-linear-from":N()}],"mask-image-linear-to-color":[{"mask-linear-to":N()}],"mask-image-t-from-pos":[{"mask-t-from":se()}],"mask-image-t-to-pos":[{"mask-t-to":se()}],"mask-image-t-from-color":[{"mask-t-from":N()}],"mask-image-t-to-color":[{"mask-t-to":N()}],"mask-image-r-from-pos":[{"mask-r-from":se()}],"mask-image-r-to-pos":[{"mask-r-to":se()}],"mask-image-r-from-color":[{"mask-r-from":N()}],"mask-image-r-to-color":[{"mask-r-to":N()}],"mask-image-b-from-pos":[{"mask-b-from":se()}],"mask-image-b-to-pos":[{"mask-b-to":se()}],"mask-image-b-from-color":[{"mask-b-from":N()}],"mask-image-b-to-color":[{"mask-b-to":N()}],"mask-image-l-from-pos":[{"mask-l-from":se()}],"mask-image-l-to-pos":[{"mask-l-to":se()}],"mask-image-l-from-color":[{"mask-l-from":N()}],"mask-image-l-to-color":[{"mask-l-to":N()}],"mask-image-x-from-pos":[{"mask-x-from":se()}],"mask-image-x-to-pos":[{"mask-x-to":se()}],"mask-image-x-from-color":[{"mask-x-from":N()}],"mask-image-x-to-color":[{"mask-x-to":N()}],"mask-image-y-from-pos":[{"mask-y-from":se()}],"mask-image-y-to-pos":[{"mask-y-to":se()}],"mask-image-y-from-color":[{"mask-y-from":N()}],"mask-image-y-to-color":[{"mask-y-to":N()}],"mask-image-radial":[{"mask-radial":[$,Q]}],"mask-image-radial-from-pos":[{"mask-radial-from":se()}],"mask-image-radial-to-pos":[{"mask-radial-to":se()}],"mask-image-radial-from-color":[{"mask-radial-from":N()}],"mask-image-radial-to-color":[{"mask-radial-to":N()}],"mask-image-radial-shape":[{"mask-radial":[`circle`,`ellipse`]}],"mask-image-radial-size":[{"mask-radial":[{closest:[`side`,`corner`],farthest:[`side`,`corner`]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[vv]}],"mask-image-conic-from-pos":[{"mask-conic-from":se()}],"mask-image-conic-to-pos":[{"mask-conic-to":se()}],"mask-image-conic-from-color":[{"mask-conic-from":N()}],"mask-image-conic-to-color":[{"mask-conic-to":N()}],"mask-mode":[{mask:[`alpha`,`luminance`,`match`]}],"mask-origin":[{"mask-origin":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]}],"mask-position":[{mask:P()}],"mask-repeat":[{mask:F()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":[`alpha`,`luminance`]}],"mask-image":[{mask:[`none`,$,Q]}],filter:[{filter:[``,`none`,$,Q]}],blur:[{blur:ce()}],brightness:[{brightness:[vv,$,Q]}],contrast:[{contrast:[vv,$,Q]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,Hv,Iv]}],"drop-shadow-color":[{"drop-shadow":N()}],grayscale:[{grayscale:[``,vv,$,Q]}],"hue-rotate":[{"hue-rotate":[vv,$,Q]}],invert:[{invert:[``,vv,$,Q]}],saturate:[{saturate:[vv,$,Q]}],sepia:[{sepia:[``,vv,$,Q]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,$,Q]}],"backdrop-blur":[{"backdrop-blur":ce()}],"backdrop-brightness":[{"backdrop-brightness":[vv,$,Q]}],"backdrop-contrast":[{"backdrop-contrast":[vv,$,Q]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,vv,$,Q]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[vv,$,Q]}],"backdrop-invert":[{"backdrop-invert":[``,vv,$,Q]}],"backdrop-opacity":[{"backdrop-opacity":[vv,$,Q]}],"backdrop-saturate":[{"backdrop-saturate":[vv,$,Q]}],"backdrop-sepia":[{"backdrop-sepia":[``,vv,$,Q]}],"border-collapse":[{border:[`collapse`,`separate`]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:[`auto`,`fixed`]}],caption:[{caption:[`top`,`bottom`]}],transition:[{transition:[``,`all`,`colors`,`opacity`,`shadow`,`transform`,`none`,$,Q]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[vv,`initial`,$,Q]}],ease:[{ease:[`linear`,`initial`,_,$,Q]}],delay:[{delay:[vv,$,Q]}],animate:[{animate:[`none`,v,$,Q]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,$,Q]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:le()}],"rotate-x":[{"rotate-x":le()}],"rotate-y":[{"rotate-y":le()}],"rotate-z":[{"rotate-z":le()}],scale:[{scale:ue()}],"scale-x":[{"scale-x":ue()}],"scale-y":[{"scale-y":ue()}],"scale-z":[{"scale-z":ue()}],"scale-3d":[`scale-3d`],skew:[{skew:de()}],"skew-x":[{"skew-x":de()}],"skew-y":[{"skew-y":de()}],transform:[{transform:[$,Q,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:fe()}],"translate-x":[{"translate-x":fe()}],"translate-y":[{"translate-y":fe()}],"translate-z":[{"translate-z":fe()}],"translate-none":[`translate-none`],zoom:[{zoom:[yv,$,Q]}],accent:[{accent:N()}],appearance:[{appearance:[`none`,`auto`]}],"caret-color":[{caret:N()}],"color-scheme":[{scheme:[`normal`,`dark`,`light`,`light-dark`,`only-dark`,`only-light`]}],cursor:[{cursor:[`auto`,`default`,`pointer`,`wait`,`text`,`move`,`help`,`not-allowed`,`none`,`context-menu`,`progress`,`cell`,`crosshair`,`vertical-text`,`alias`,`copy`,`no-drop`,`grab`,`grabbing`,`all-scroll`,`col-resize`,`row-resize`,`n-resize`,`e-resize`,`s-resize`,`w-resize`,`ne-resize`,`nw-resize`,`se-resize`,`sw-resize`,`ew-resize`,`ns-resize`,`nesw-resize`,`nwse-resize`,`zoom-in`,`zoom-out`,$,Q]}],"field-sizing":[{"field-sizing":[`fixed`,`content`]}],"pointer-events":[{"pointer-events":[`auto`,`none`]}],resize:[{resize:[`none`,``,`y`,`x`]}],"scroll-behavior":[{scroll:[`auto`,`smooth`]}],"scrollbar-thumb-color":[{"scrollbar-thumb":N()}],"scrollbar-track-color":[{"scrollbar-track":N()}],"scrollbar-gutter":[{"scrollbar-gutter":[`auto`,`stable`,`both`]}],"scrollbar-w":[{scrollbar:[`auto`,`thin`,`none`]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mbs":[{"scroll-mbs":w()}],"scroll-mbe":[{"scroll-mbe":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pbs":[{"scroll-pbs":w()}],"scroll-pbe":[{"scroll-pbe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:[`start`,`end`,`center`,`align-none`]}],"snap-stop":[{snap:[`normal`,`always`]}],"snap-type":[{snap:[`none`,`x`,`y`,`both`]}],"snap-strictness":[{snap:[`mandatory`,`proximity`]}],touch:[{touch:[`auto`,`none`,`manipulation`]}],"touch-x":[{"touch-pan":[`x`,`left`,`right`]}],"touch-y":[{"touch-pan":[`y`,`up`,`down`]}],"touch-pz":[`touch-pinch-zoom`],select:[{select:[`none`,`text`,`all`,`auto`]}],"will-change":[{"will-change":[`auto`,`scroll`,`contents`,`transform`,$,Q]}],fill:[{fill:[`none`,...N()]}],"stroke-w":[{stroke:[vv,Lv,Av,jv]}],stroke:[{stroke:[`none`,...N()]}],"forced-color-adjust":[{"forced-color-adjust":[`auto`,`none`]}]},conflictingClassGroups:{"container-named":[`container-type`],overflow:[`overflow-x`,`overflow-y`],overscroll:[`overscroll-x`,`overscroll-y`],inset:[`inset-x`,`inset-y`,`inset-bs`,`inset-be`,`start`,`end`,`top`,`right`,`bottom`,`left`],"inset-x":[`right`,`left`],"inset-y":[`top`,`bottom`],flex:[`basis`,`grow`,`shrink`],gap:[`gap-x`,`gap-y`],p:[`px`,`py`,`ps`,`pe`,`pbs`,`pbe`,`pt`,`pr`,`pb`,`pl`],px:[`pr`,`pl`],py:[`pt`,`pb`],m:[`mx`,`my`,`ms`,`me`,`mbs`,`mbe`,`mt`,`mr`,`mb`,`ml`],mx:[`mr`,`ml`],my:[`mt`,`mb`],size:[`w`,`h`],"font-size":[`leading`],"fvn-normal":[`fvn-ordinal`,`fvn-slashed-zero`,`fvn-figure`,`fvn-spacing`,`fvn-fraction`],"fvn-ordinal":[`fvn-normal`],"fvn-slashed-zero":[`fvn-normal`],"fvn-figure":[`fvn-normal`],"fvn-spacing":[`fvn-normal`],"fvn-fraction":[`fvn-normal`],"line-clamp":[`display`,`overflow`],rounded:[`rounded-s`,`rounded-e`,`rounded-t`,`rounded-r`,`rounded-b`,`rounded-l`,`rounded-ss`,`rounded-se`,`rounded-ee`,`rounded-es`,`rounded-tl`,`rounded-tr`,`rounded-br`,`rounded-bl`],"rounded-s":[`rounded-ss`,`rounded-es`],"rounded-e":[`rounded-se`,`rounded-ee`],"rounded-t":[`rounded-tl`,`rounded-tr`],"rounded-r":[`rounded-tr`,`rounded-br`],"rounded-b":[`rounded-br`,`rounded-bl`],"rounded-l":[`rounded-tl`,`rounded-bl`],"border-spacing":[`border-spacing-x`,`border-spacing-y`],"border-w":[`border-w-x`,`border-w-y`,`border-w-s`,`border-w-e`,`border-w-bs`,`border-w-be`,`border-w-t`,`border-w-r`,`border-w-b`,`border-w-l`],"border-w-x":[`border-w-r`,`border-w-l`],"border-w-y":[`border-w-t`,`border-w-b`],"border-color":[`border-color-x`,`border-color-y`,`border-color-s`,`border-color-e`,`border-color-bs`,`border-color-be`,`border-color-t`,`border-color-r`,`border-color-b`,`border-color-l`],"border-color-x":[`border-color-r`,`border-color-l`],"border-color-y":[`border-color-t`,`border-color-b`],translate:[`translate-x`,`translate-y`,`translate-none`],"translate-none":[`translate`,`translate-x`,`translate-y`,`translate-z`],"scroll-m":[`scroll-mx`,`scroll-my`,`scroll-ms`,`scroll-me`,`scroll-mbs`,`scroll-mbe`,`scroll-mt`,`scroll-mr`,`scroll-mb`,`scroll-ml`],"scroll-mx":[`scroll-mr`,`scroll-ml`],"scroll-my":[`scroll-mt`,`scroll-mb`],"scroll-p":[`scroll-px`,`scroll-py`,`scroll-ps`,`scroll-pe`,`scroll-pbs`,`scroll-pbe`,`scroll-pt`,`scroll-pr`,`scroll-pb`,`scroll-pl`],"scroll-px":[`scroll-pr`,`scroll-pl`],"scroll-py":[`scroll-pt`,`scroll-pb`],touch:[`touch-x`,`touch-y`,`touch-pz`],"touch-x":[`touch`],"touch-y":[`touch`],"touch-pz":[`touch`]},conflictingClassGroupModifiers:{"font-size":[`leading`]},postfixLookupClassGroups:[`container-type`],orderSensitiveModifiers:[`*`,`**`,`after`,`backdrop`,`before`,`details-content`,`file`,`first-letter`,`first-line`,`marker`,`placeholder`,`selection`]}});function ty(...e){return ey(T_(e))}var ny=O_(`inline-flex h-9 shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-md border px-3 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400 disabled:pointer-events-none disabled:opacity-50 dark:focus-visible:ring-zinc-500`,{variants:{variant:{primary:`border-slate-900 bg-slate-950 text-white hover:bg-slate-800 dark:border-zinc-100 dark:bg-zinc-50 dark:text-zinc-950 dark:hover:bg-zinc-200`,secondary:`border-slate-200 bg-white text-slate-900 hover:bg-slate-50 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-100 dark:hover:bg-zinc-900`,ghost:`border-transparent bg-transparent text-slate-700 hover:bg-slate-100 dark:text-zinc-300 dark:hover:bg-zinc-900`},size:{sm:`h-8 px-2 text-xs`,md:`h-9 px-3 text-sm`,icon:`h-9 w-9 px-0`}},defaultVariants:{variant:`secondary`,size:`md`}});function ry({className:e,variant:t,size:n,...r}){return(0,B.jsx)(`button`,{className:ty(ny({variant:t,size:n}),e),type:`button`,...r})}function iy({className:e,...t}){return(0,B.jsx)(`section`,{className:ty(`rounded-lg border border-slate-200/80 bg-white/95 text-slate-950 shadow-[0_1px_2px_rgba(15,23,42,0.04)] dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50`,e),...t})}function ay({className:e,...t}){return(0,B.jsx)(`div`,{className:ty(`p-4 pt-0`,e),...t})}var oy=[`codex`,`claude`,`kiro`,`trae`,`coco`,`openai`,`anthropic`],sy=new Set([`acp`,`status_projection`]);function cy(e){let t=e.trim().toLowerCase().replace(/_/gu,`-`);for(let e of oy)if(t===e||t.startsWith(`${e}-`))return e;return t}function ly(e,t){let n=t?.trim().toLowerCase()??``;return n.length>0&&!sy.has(n)?cy(n):cy(e)}var uy={stop:`ready_stop`,resume:`resume_review`,delete:`delete_review`},dy=e=>typeof e==`string`&&e.trim().length>0;function fy(e){let t={schemaVersion:`action_review_plan_v0`,proposalId:e.proposal_id,sourceFingerprint:e.expected_state_fingerprint},n=(e,n)=>({...t,interaction:e,reason:n,canApply:!1}),r=e.action_kind===`goal.lifecycle`;if(r&&e.gate!=null||e.status===`gated`)return n(`gated`,`authority_gate`);if(r&&e.stale!=null||e.status===`stale`)return n(`refresh`,`stale_proposal`);if(e.status===`applied`)return e.receipt?.projection_verified===!0&&(e.action_kind!==`operation.execute`||e.operation?.result_delivery!=null)?n(`completed`,`readback_verified`):n(`repair`,`readback_unverified`);if(e.status===`applying`)return n(`pending`,`apply_pending`);if(e.status===`failed`||e.error!=null)return n(`repair`,`apply_failed`);if(e.status!==`preview_ready`&&e.status!==`deferred`)return n(`inactive`,`inactive_proposal`);let i=(e,n=!0)=>({...t,interaction:`review`,reason:e,canApply:n});if(e.action_kind!==`goal.lifecycle`)return i(e.permission_classification===`protected`?`protected_action`:`action_review`);if(!(dy(e.proposal_id)&&dy(e.expected_state_fingerprint)&&Oh.shape.validation_evidence.safeParse(e.validation_evidence).success&&e.validation_evidence.length>0&&e.available_transitions.includes(`apply`)))return n(`refresh`,`incomplete_proposal`);let{operation:a,goal_id:o}=e.normalized_parameters;if(!dy(o)||e.context.goal_id!=null&&e.context.goal_id!==o)return n(`refresh`,`incomplete_proposal`);if(a!==`stop`&&a!==`resume`&&a!==`delete`)return i(`unknown_action`,!1);if(e.permission_classification===`protected`)return i(`protected_action`);if(e.permission_classification!==`durable_write`)return i(`unknown_permission`,!1);let s=uy[a];return s===`ready_stop`&&e.status===`preview_ready`?{...t,interaction:`direct`,reason:s,canApply:!0}:i(s===`ready_stop`?`action_review`:s)}function py(e){if(e.error_code===`action_stale`||e.error_code===`action_conflict`)return!0;let t=e.proposal;return typeof t==`object`&&!!t&&`status`in t&&t.status===`stale`}function my(e){return{blockingTodoCount:e.blockingTodoCount,goalNotifications:e.goalNotifications,goals:e.goals,openUserTodoCount:e.openUserTodoCount,systemHealth:e.systemHealth,attentionHistory:e.attentionHistory,userTodos:e.userTodos,workers:e.workers}}function hy(e,t){return e.goals.find(e=>e.goalId===t)?.title??t}function gy(e){return e.activationState===`stopped`||e.state===`已停止`?`stopped`:e.state===`已完成`?`history`:e.needsYou||e.state===`等你`?`needs_you`:e.state===`推进中`||e.state===`需修复`?`running`:e.state===`安静运行`?`observing`:`scheduled`}function _y(e){let t=e;return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function vy(e){return`$${e.toFixed(2)}`}function yy(e){let t=e;return t>=36e5?`${(t/36e5).toFixed(1)}h`:t>=6e4?`${(t/6e4).toFixed(1)}m`:t>=1e3?`${Math.round(t/1e3)}s`:`${t}ms`}function by(e,t,n){return e==null?t:n(e)}function xy(e){return!!(e&&[e.tokens24h,e.tokens7d,e.costUsd24h,e.costUsd7d,e.durationMs24h,e.durationMs7d].some(e=>e!=null))}function Sy(e,t){if(!xy(e))return null;let n=(e,n,r,i)=>{let a=[n==null?null:`${_y(n)} ${t.tokens}`,r==null?null:`${t.cost}: ${vy(r)}`,i==null?null:`${t.duration}: ${yy(i)}`].filter(e=>e!==null);return a.length?`${e} ${a.join(` · `)}`:null};return n(t.period7d,e.tokens7d,e.costUsd7d,e.durationMs7d)??n(t.period24h,e.tokens24h,e.costUsd24h,e.durationMs24h)}function Cy({ariaLabel:e,className:t,icon:n,onChange:r,options:i,prefixLabel:a,value:o}){let s=(0,z.useId)(),c=(0,z.useRef)(null),l=(0,z.useRef)(null),u=(0,z.useRef)(new Map),[d,f]=(0,z.useState)(!1),[p,m]=(0,z.useState)(o),h=i.find(e=>e.value===o)??i[0],g=i.filter(e=>!e.disabled);(0,z.useEffect)(()=>{if(!d)return;let e=e=>{c.current?.contains(e.target)||f(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[d]),(0,z.useEffect)(()=>{d&&u.current.get(p)?.focus()},[p,d]);function _(e){m(e)}function v(e=`selected`){let t=e===`last`?g.at(-1):g[0],n=e===`selected`&&h&&!h.disabled?h:t;n&&(f(!0),_(n.value))}function y({restoreFocus:e=!1}={}){f(!1),e&&l.current?.focus()}function b(e){e.disabled||(r(e.value),y({restoreFocus:!0}))}function x(e){if(!g.length)return;let t=g.findIndex(e=>e.value===p),n=t<0?0:(t+e+g.length)%g.length;_(g[n].value)}function S(e){e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),v(`selected`)):e.key===`ArrowUp`&&(e.preventDefault(),v(`last`))}function C(e,t){if(e.key===`ArrowDown`)e.preventDefault(),x(1);else if(e.key===`ArrowUp`)e.preventDefault(),x(-1);else if(e.key===`Home`)e.preventDefault(),g[0]&&_(g[0].value);else if(e.key===`End`){e.preventDefault();let t=g.at(-1);t&&_(t.value)}else e.key===`Enter`||e.key===` `?(e.preventDefault(),b(t)):e.key===`Escape`?(e.preventDefault(),y({restoreFocus:!0})):e.key===`Tab`&&y()}let w;return(0,B.jsxs)(`div`,{className:`personal-select${t?` ${t}`:``}`,ref:c,children:[(0,B.jsxs)(`button`,{"aria-controls":s,"aria-expanded":d,"aria-haspopup":`listbox`,"aria-label":e,className:`personal-select-trigger`,"data-value":o,onClick:()=>d?y():v(),onKeyDown:S,ref:l,role:`combobox`,type:`button`,children:[n?(0,B.jsx)(`span`,{className:`personal-select-icon`,children:n}):null,(0,B.jsxs)(`span`,{className:`personal-select-value`,children:[a?(0,B.jsx)(`small`,{children:a}):null,(0,B.jsx)(`span`,{children:h?.label??o})]}),(0,B.jsx)(tm,{"aria-hidden":!0,className:d?`is-open`:void 0,size:14})]}),d?(0,B.jsx)(`div`,{"aria-label":e,className:`personal-select-listbox`,id:s,role:`listbox`,children:i.map(e=>{let t=e.group&&e.group!==w;return w=e.group,(0,B.jsxs)(`div`,{className:`personal-select-option-wrap`,children:[t?(0,B.jsx)(`div`,{className:`personal-select-group-label`,children:e.group}):null,(0,B.jsxs)(`button`,{"aria-disabled":e.disabled||void 0,"aria-selected":e.value===o,className:`personal-select-option`,disabled:e.disabled,id:`${s}-${e.value.replace(/[^a-z0-9_-]/gi,`-`)}`,onClick:()=>b(e),onFocus:()=>m(e.value),onKeyDown:t=>C(t,e),ref:t=>{t?u.current.set(e.value,t):u.current.delete(e.value)},role:`option`,tabIndex:e.value===p?0:-1,type:`button`,children:[(0,B.jsx)(`span`,{children:e.label}),e.value===o?(0,B.jsx)(em,{"aria-hidden":!0,size:15}):null]})]},e.value)})}):null]})}function wy({agents:e,managerChatOpen:t,mobileNavigationOpen:n,onOpenGoalCapabilities:r,onOpenGoalDetail:i,onOpenManagerChat:a,onRefresh:o,onOpenNavigation:s,onSelectGoalTab:c,onSelectAgent:l,onReturnManagerHome:u,refreshState:d,readOnlySourceLabel:f,selectedAgentId:p,selectedGoal:m,selectedGoalTab:h}){let{locale:g,t:_}=Ji(),[v,y]=(0,z.useState)(!1),b=(0,z.useRef)(null),x=(0,z.useRef)(null);(0,z.useEffect)(()=>{if(!v)return;function e(e){x.current?.contains(e.target)||y(!1)}function t(e){e.key===`Escape`&&(y(!1),b.current?.focus())}return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[v]),(0,z.useEffect)(()=>y(!1),[m?.goalId]);function S(e){y(!1),e?.()}let C=m?Sy(m.usage,{cost:_(`drawer.costShort`),duration:_(`drawer.durationShort`),period24h:_(`drawer.period24h`),period7d:_(`drawer.period7d`),tokens:_(`drawer.tokensShort`)}):null;return(0,B.jsxs)(`header`,{className:`personal-channel-header`,children:[(0,B.jsx)(`button`,{"aria-expanded":n??!1,"aria-label":_(`header.openGoalNavigation`),className:`personal-icon-button personal-mobile-menu`,onClick:s,type:`button`,children:(0,B.jsx)(Tm,{size:18})}),(0,B.jsxs)(`div`,{className:`personal-channel-title`,children:[(0,B.jsx)(`h1`,{children:m?.title??_(`header.manager`)}),m?(0,B.jsx)(`p`,{children:m.loadState?_(m.loadState===`error`?`startup.goalError`:`startup.goalLoading`):`${m.agentLaneCount&&m.agentLaneCount>1?_(`header.workAgentCount`,{count:m.agentLaneCount}):m.agentLabel??m.agentId} · ${m.loadState?_(m.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Yi(m.state,g)}${C?` · ${C}`:``} · ${m.nextSentence}`}):null]}),m?(0,B.jsxs)(`nav`,{"aria-label":_(`header.goalView`),className:`personal-goal-tabs`,children:[(0,B.jsx)(`button`,{"aria-current":h===`chat`?`page`:void 0,onClick:()=>c(`chat`),type:`button`,children:_(`header.chat`)}),(0,B.jsx)(`button`,{"aria-current":h===`tasks`?`page`:void 0,onClick:()=>c(`tasks`),type:`button`,children:_(`header.tasks`)}),(0,B.jsx)(`button`,{"aria-current":h===`files`?`page`:void 0,onClick:()=>c(`files`),type:`button`,children:_(`header.files`)})]}):(0,B.jsxs)(`nav`,{"aria-label":_(`header.managerView`),className:`personal-goal-tabs`,children:[(0,B.jsx)(`button`,{"aria-current":t?void 0:`page`,onClick:u,type:`button`,children:_(`header.managerOverview`)}),(0,B.jsx)(`button`,{"aria-current":t?`page`:void 0,onClick:a,type:`button`,children:_(`header.chat`)})]}),(0,B.jsxs)(`div`,{className:`personal-channel-actions`,children:[m&&i&&r?(0,B.jsxs)(`div`,{className:`personal-goal-tools`,ref:x,children:[(0,B.jsxs)(`button`,{"aria-expanded":v,"aria-haspopup":`menu`,"aria-label":_(`header.goalSettingsDescription`),className:`personal-goal-tools-trigger`,onClick:()=>y(e=>!e),ref:b,title:_(`header.goalSettingsDescription`),type:`button`,children:[(0,B.jsx)(Gm,{"aria-hidden":!0,size:16}),(0,B.jsx)(`span`,{children:_(`header.goalSettings`)}),(0,B.jsx)(tm,{"aria-hidden":!0,size:13})]}),v?(0,B.jsxs)(`fieldset`,{"aria-label":_(`header.goalSettings`),className:`personal-goal-tools-menu`,children:[(0,B.jsxs)(`button`,{onClick:()=>S(i),type:`button`,children:[(0,B.jsx)(ym,{"aria-hidden":!0,size:17}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:_(`header.goalDetails`)})})]}),(0,B.jsxs)(`button`,{onClick:()=>S(r),type:`button`,children:[(0,B.jsx)(Gm,{"aria-hidden":!0,size:17}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:_(`header.goalCapabilities`)})})]})]}):null]}):null,f?(0,B.jsxs)(`span`,{className:`personal-read-only-source`,title:_(`header.readOnlySourceDescription`,{source:f}),children:[(0,B.jsx)(pm,{size:15}),f,(0,B.jsx)(`small`,{children:_(`common.readOnly`)})]}):(0,B.jsx)(Cy,{ariaLabel:_(`header.selectChatRuntime`),className:`personal-agent-select`,icon:(0,B.jsx)(Zp,{size:16}),onChange:l,options:e.map(e=>({disabled:!e.available,label:`${e.label}${e.available?``:` · ${_(`header.agentUnavailable`)}`}`,value:e.agentId})),prefixLabel:_(`header.chatRuntime`),value:p}),(0,B.jsxs)(`span`,{className:`personal-live-indicator`,children:[(0,B.jsx)(`i`,{}),_(`header.live`)]}),o?(0,B.jsxs)(`span`,{className:`personal-refresh-control is-${d??`idle`}`,children:[d===`loading`?(0,B.jsx)(`small`,{children:_(`header.refreshing`)}):d===`done`?(0,B.jsx)(`small`,{children:_(`header.refreshDone`)}):d===`error`?(0,B.jsx)(`small`,{children:_(`header.refreshFailed`)}):null,(0,B.jsx)(`button`,{"aria-label":_(d===`loading`?`header.refreshing`:`header.refresh`),className:`personal-icon-button`,disabled:d===`loading`,onClick:o,type:`button`,children:(0,B.jsx)(Im,{className:d===`loading`?`is-spinning`:void 0,size:17})})]}):null]})]})}function Ty({attention:e,onSelect:t}){let{t:n}=Ji(),r=Zi(e.updatedAt,n);return(0,B.jsxs)(`button`,{className:`personal-timeline-row personal-attention-row`,"data-testid":`personal-browse-row`,onClick:t,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-row-icon is-attention`,children:(0,B.jsx)(im,{size:18})}),(0,B.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,B.jsxs)(`small`,{children:[e.goalTitle??e.goalId,` · `,n(`home.lane.needsYou`),r?` · ${n(`tasks.waitingAge`,{age:r})}`:``]}),(0,B.jsx)(`strong`,{children:e.text})]}),(0,B.jsx)(`span`,{className:`personal-priority-dot is-${e.priority??(e.blocking?`high`:`medium`)}`}),(0,B.jsx)(`span`,{className:`personal-row-status ${e.blocking?`is-blocking`:`is-pending`}`,children:e.blocking?n(`tasks.blocked`):n(`tasks.pending`)}),(0,B.jsx)(nm,{size:17})]})}var Ey=/(`[^`\n]+`)|(\*\*[^*\n]+(\*[^*\n]*)?\*\*)|(\[[^\]\n]{1,120}\]\(https?:\/\/[^)\s]+\))/g;function Dy(e,t){let n=[],r=0,i=0;for(let a of e.matchAll(Ey)){let o=a.index??0;o>r&&n.push(e.slice(r,o));let s=a[0],c=`${t}-i${i++}`;if(s.startsWith("`"))n.push((0,B.jsx)(`code`,{className:`personal-md-code`,children:s.slice(1,-1)},c));else if(s.startsWith(`**`))n.push((0,B.jsx)(`strong`,{children:s.slice(2,-2)},c));else{let e=s.indexOf(`](`),t=s.slice(1,e),r=s.slice(e+2,-1);n.push((0,B.jsx)(`a`,{className:`personal-md-link`,href:r,rel:`noreferrer`,target:`_blank`,children:t},c))}r=o+s.length}return r{r.length>0&&(n.push({type:`paragraph`,lines:r}),r=[])},a=0;for(;a{let n=`b${t}`;if(e.type===`code`)return(0,B.jsx)(`pre`,{className:`personal-md-pre`,children:(0,B.jsx)(`code`,{children:e.text})},n);if(e.type===`heading`)return(0,B.jsx)(`p`,{className:`personal-md-heading is-h${e.level}`,children:Dy(e.text,n)},n);if(e.type===`list`){let t=e.items.map((e,t)=>(0,B.jsx)(`li`,{children:Dy(e,`${n}-${t}`)},`${n}-${t}`));return e.ordered?(0,B.jsx)(`ol`,{className:`personal-md-list`,children:t},n):(0,B.jsx)(`ul`,{className:`personal-md-list`,children:t},n)}return(0,B.jsx)(`p`,{children:e.lines.map((e,t)=>(0,B.jsxs)(z.Fragment,{children:[t>0?(0,B.jsx)(`br`,{}):null,Dy(e,`${n}-${t}`)]},`${n}-${t}`))},n)})})}function My({onSelect:e,output:t}){let{t:n}=Ji(),r=t.kind===`report`?gm:hm;return(0,B.jsxs)(`button`,{className:`personal-timeline-row personal-output-row`,"data-output-kind":t.kind,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-row-icon is-output`,children:(0,B.jsx)(r,{size:18})}),(0,B.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,B.jsxs)(`small`,{children:[t.goalTitle??t.goalId,` · `,t.agentLabel??`LoopX`]}),(0,B.jsx)(`strong`,{children:t.title}),t.summary?(0,B.jsx)(`span`,{children:t.summary}):null,t.report?(0,B.jsxs)(`small`,{children:[n(`files.reportDelta`,{added:t.report.addedCount,changed:t.report.changedCount}),` · `,n(`files.verifiedReport`)]}):null]}),t.createdAt?(0,B.jsx)(`time`,{children:t.createdAt}):null,(0,B.jsx)(nm,{size:17})]})}var Ny={completed:`runs.completed`,failed:`runs.failed`,interrupted:`runs.interrupted`,queued:`runs.queued`,running:`runs.running`,waiting:`runs.waiting`};function Py({onSelect:e,run:t}){let{t:n}=Ji(),r=t.totalSteps>0?Math.min(100,t.completedSteps/t.totalSteps*100):0;return(0,B.jsxs)(`button`,{"aria-label":`${n(`tasks.viewExecution`)}:${t.title}`,className:`personal-timeline-row personal-run-row`,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-row-icon is-run`,children:(0,B.jsx)(Zp,{size:18})}),(0,B.jsxs)(`span`,{className:`personal-run-identity`,children:[(0,B.jsx)(`small`,{children:t.goalTitle}),(0,B.jsx)(`strong`,{children:t.agentLabel})]}),(0,B.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,B.jsx)(`strong`,{children:t.title}),(0,B.jsx)(`small`,{children:t.latestActivity})]}),(0,B.jsxs)(`span`,{className:`personal-run-progress`,"aria-label":`${t.completedSteps}/${t.totalSteps}`,children:[(0,B.jsxs)(`small`,{children:[t.completedSteps,`/`,t.totalSteps]}),(0,B.jsx)(`i`,{children:(0,B.jsx)(`b`,{style:{width:`${r}%`}})})]}),(0,B.jsxs)(`span`,{className:`personal-row-status is-${t.status}`,children:[t.status===`running`?(0,B.jsx)(Cm,{className:`personal-spin`,size:14}):null,n(Ny[t.status])]}),t.sessionId?(0,B.jsx)(`span`,{className:`personal-run-open-label`,children:n(`tasks.viewExecution`)}):null,(0,B.jsx)(nm,{size:17})]})}function Fy({onSelect:e,schedule:t}){let{t:n}=Ji(),r=t.scheduleKind===`heartbeat`;return(0,B.jsxs)(`button`,{"aria-label":`${r?`Heartbeat`:n(`tasks.scheduled`)}:${t.label};${t.status??`active`}`,className:`personal-schedule-row`,onClick:e,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-schedule-icon`,children:r?(0,B.jsx)(Fm,{size:17}):(0,B.jsx)($p,{size:17})}),(0,B.jsxs)(`span`,{className:`personal-schedule-copy`,children:[(0,B.jsx)(`small`,{children:n(r?`schedule.heartbeat`:`schedule.monitor`)}),(0,B.jsx)(`strong`,{children:t.label}),(0,B.jsx)(`p`,{children:t.schedule??n(`schedule.summary`)})]}),(0,B.jsx)(`span`,{className:`personal-schedule-status is-${t.status??`active`}`,children:t.status===`paused`?n(`schedule.paused`):n(`schedule.active`)}),(0,B.jsx)(nm,{size:16})]})}function Iy({items:e,onSelect:t,selectedGoal:n}){let{t:r}=Ji();if(e.length===0)return(0,B.jsxs)(`div`,{className:`personal-timeline-empty`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Km,{size:20})}),(0,B.jsx)(`strong`,{children:r(n?`timeline.emptyGoal`:`timeline.emptyWorkspace`)}),(0,B.jsx)(`p`,{children:r(n?`timeline.emptyGoalDescription`:`timeline.emptyWorkspaceDescription`)})]});let i=[...e].reverse().find(e=>e.kind===`message`&&e.message.role!==`user`||e.kind===`proposal`&&[`applied`,`stale`,`error`,`gated`].includes(e.proposal.status)||e.kind===`run`&&e.run.status===`completed`),a=i?.kind===`message`?`${i.message.agentLabel??r(`header.manager`)}:${i.message.pending?r(`timeline.pending`):i.message.text}`:i?.kind===`proposal`?`${i.proposal.title}:${i.proposal.status}`:i?.kind===`run`?r(`timeline.runCompleted`,{run:i.run.title}):``,o=e.filter(e=>e.kind===`proposal`&&e.proposal.status===`gated`),s=e.filter(e=>e.kind!==`proposal`),c=e.filter(e=>e.kind===`proposal`&&e.proposal.status!==`gated`);function l(e){return e.kind===`attention`?(0,B.jsx)(Ty,{attention:e.attention,onSelect:()=>t({item:e.attention,kind:`attention`})},e.id):e.kind===`run`?(0,B.jsx)(Py,{onSelect:()=>t({item:e.run,kind:`run`}),run:e.run},e.id):e.kind===`output`?(0,B.jsx)(My,{onSelect:()=>t({item:e.output,kind:`output`}),output:e.output},e.id):e.kind===`schedule`?(0,B.jsx)(Fy,{onSelect:()=>t({item:e.schedule,kind:`schedule`}),schedule:e.schedule},e.id):e.kind===`proposal`?(0,B.jsxs)(`button`,{className:`personal-proposal-row is-${e.proposal.status}`,onClick:()=>t({item:e.proposal,kind:`proposal`}),type:`button`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Km,{size:17})}),(0,B.jsxs)(`span`,{children:[(0,B.jsxs)(`small`,{children:[e.proposal.actionKind,` · `,e.proposal.status]}),(0,B.jsx)(`strong`,{children:e.proposal.title}),(0,B.jsx)(`p`,{children:e.proposal.impact})]}),(0,B.jsx)(`b`,{children:e.proposal.status===`gated`?r(`timeline.review`):e.proposal.primaryLabel??r(`timeline.reviewAndConfirm`)})]},e.id):(0,B.jsxs)(`article`,{className:`personal-message is-${e.message.role}`,children:[e.message.role===`user`?null:(0,B.jsx)(`span`,{className:`personal-message-avatar`,children:(0,B.jsx)(Zp,{size:17})}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:e.message.role===`user`?r(`common.you`):e.message.agentLabel??r(`header.manager`)}),e.message.time?(0,B.jsx)(`time`,{children:e.message.time}):null]}),e.message.attachments?.length?(0,B.jsx)(`div`,{className:`personal-message-images`,children:e.message.attachments.map(e=>(0,B.jsx)(`img`,{alt:e.name,src:e.dataUrl},e.id))}):null,e.message.role===`user`?(0,B.jsx)(`p`,{children:e.message.text}):(0,B.jsx)(jy,{text:e.message.text}),e.message.pending?(0,B.jsx)(`span`,{className:`personal-message-pending`,children:r(`timeline.pending`)}):null]})]},e.id)}return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{"aria-atomic":`true`,"aria-live":`polite`,className:`personal-live-region`,role:`status`,children:a}),(0,B.jsxs)(`div`,{className:`personal-channel-timeline`,children:[s.map(l),o.length?(0,B.jsxs)(`details`,{className:`personal-gated-summary`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Km,{size:16})}),(0,B.jsx)(`strong`,{children:r(`timeline.waitingConfirmation`)}),(0,B.jsx)(`small`,{children:r(`timeline.gateHistory`,{count:o.length})})]}),(0,B.jsx)(`div`,{children:o.map(l)})]}):null,c.map(l)]})]})}function Ly({goal:e}){let{t}=Ji(),n={connected:t(`acceptance.connected`),mapped:t(`acceptance.mapped`),refreshed:t(`acceptance.refreshed`),adapter_inspected:t(`acceptance.inspected`),run_recorded:t(`acceptance.recorded`),reward_judged:t(`acceptance.judged`),operator_approved:t(`acceptance.approved`),controller_ready:t(`acceptance.ready`),attention_queue:t(`acceptance.attentionSource`),agent_vision:t(`acceptance.visionSource`),todo_projection:t(`acceptance.todoSource`),current_run:t(`acceptance.runSource`)},r=e=>n[e]??t(`acceptance.unknown`),i=e.acceptanceObservation,a=e.loadState||!i||i.goal_id!==e.goalId||i.coverage===`unavailable`;return(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-acceptance`,"aria-label":t(`acceptance.title`),children:[(0,B.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,B.jsx)(`h3`,{children:t(`acceptance.title`)}),(0,B.jsx)(`em`,{children:t(`common.readOnly`)})]}),(0,B.jsx)(`p`,{role:`status`,children:t(a?`acceptance.unavailable`:`acceptance.partial`)}),!a&&i?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h4`,{children:t(`acceptance.gaps`)}),i.acceptance_gaps.length?i.acceptance_gaps.map((e,n)=>(0,B.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,B.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.owner`)}),(0,B.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,B.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.observed`)}),(0,B.jsx)(`dd`,{children:e.observed_at??t(`acceptance.unknown`)})]})]})]},`${e.kind}:${e.owner}:${n}`)):(0,B.jsx)(`p`,{children:t(`acceptance.noGaps`)}),(0,B.jsx)(`h4`,{children:t(`acceptance.guards`)}),i.guards.length?i.guards.map((e,n)=>(0,B.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,B.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.owner`)}),(0,B.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),e.blocks_agent?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.agent`)}),(0,B.jsx)(`dd`,{children:e.blocks_agent})]}):null,e.todo_id?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.task`)}),(0,B.jsx)(`dd`,{children:e.todo_id})]}):null,(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,B.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.scope`)}),(0,B.jsx)(`dd`,{children:e.decision_scope??t(`acceptance.unknown`)})]})]})]},`${e.todo_id}:${n}`)):(0,B.jsx)(`p`,{children:t(`acceptance.noGuards`)}),(0,B.jsx)(`h4`,{children:t(`acceptance.next`)}),(0,B.jsx)(`p`,{children:i.next_action??t(`acceptance.unknown`)}),(0,B.jsxs)(`details`,{children:[(0,B.jsxs)(`summary`,{children:[t(`acceptance.historical_progress`),` · `,i.historical_progress.length]}),(0,B.jsx)(`p`,{children:t(`acceptance.historical`)}),i.historical_progress.map(e=>(0,B.jsxs)(`p`,{children:[(0,B.jsx)(`strong`,{children:r(e.kind)}),` · `,e.observed_at??t(`acceptance.unknown`),` `,e.evidence_refs.join(`, `)]},e.kind))]}),i.missing_sources.length?(0,B.jsxs)(`p`,{children:[t(`acceptance.missing`),` `,i.missing_sources.map(r).join(`, `)]}):null,i.truncated?(0,B.jsx)(`p`,{children:t(`acceptance.truncated`)}):null]}):null]})}function Ry({item:e,successor:t,onSelect:n}){let{t:r}=Ji(),i=e.details;return(0,B.jsxs)(`section`,{className:`personal-detail-card`,"aria-label":r(`attentionDetail.title`),children:[(0,B.jsx)(`h3`,{children:r(`attentionDetail.title`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.request`)}),(0,B.jsx)(`dd`,{children:r(i?.interaction===`decision`?`attentionDetail.decision`:`attentionDetail.unknownRequest`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`common.status`)}),(0,B.jsx)(`dd`,{children:r(`attentionDetail.${i?.lifecycle??`unknown`}`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`drawer.reason`)}),(0,B.jsx)(`dd`,{children:i?.reason??e.explanation??r(`attentionDetail.unknownReason`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Todo`}),(0,B.jsx)(`dd`,{children:e.todoId})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.targetTodo`)}),(0,B.jsx)(`dd`,{children:i?.unblocksTodoId??r(`attentionDetail.notProvided`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.targetAgent`)}),(0,B.jsx)(`dd`,{children:i?.blocksAgent??r(`attentionDetail.notProvided`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.scope`)}),(0,B.jsx)(`dd`,{children:i?.decisionScope?`${i.decisionScope.kind} · ${i.decisionScope.granularity} · ${i.decisionScope.scopeKey}`:r(`attentionDetail.notProvided`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`drawer.evidence`)}),(0,B.jsx)(`dd`,{children:i?.evidence??e.evidence??r(`drawer.decisionDefaultEvidence`)})]})]}),i?.supersededBy?(0,B.jsxs)(`p`,{children:[r(`attentionDetail.replacement`),`: `,i.supersededBy]}):null,t&&n?(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>n(t),type:`button`,children:r(`attentionDetail.openReplacement`)}):null,(0,B.jsx)(`p`,{children:r(`attentionDetail.boundary`)})]})}function zy(e){return e.replace(/\s+/gu,` `).trim()}function By(e,t){let n=RegExp(`(?:不要|不需要|无需|禁止|别|暂不|do not\\b|don't\\b|without\\b).{0,10}(?:${t.source})`,`iu`),r=RegExp(`(?:${t.source}).{0,10}(?:不要|不需要|无需|禁止|关闭)`,`iu`),i=RegExp(`disable\\b.{0,10}(?:${t.source})|(?:turn|switch|set)\\b.{0,10}(?:${t.source}).{0,10}\\boff\\b|(?:${t.source})\\s+(?:is\\s+)?disabled\\b`,`iu`);return n.test(e)||r.test(e)||i.test(e)}function Vy(e){return/(我现在该做什么|下一步|哪些\s*Goal\s*在等我|需要我|谁在等我|Agent\s*在做什么|当前进度|总结(?:今天)?进展)/iu.test(e)}function Hy(e){let t=/(怎么|如何|为什么|给.*建议|分析一下|解释|只读)/u.test(e),n=/(解决一下|修复一下|处理一下|执行一下|改一下|跑(?:一下)?测试|rebase|push|提交|推送)/iu.test(e);return!t&&n&&/(帮我|请|给我|直接|现在|开始|bytedcli|codebase|git|rebase|push|提交|推送)/iu.test(e)}function Uy(e){return zy(e).toLowerCase().match(/(?:^|[\s,,;;:((:]|到|至)(?todo_done:todo_[a-z0-9_-]{3,64}|pr_merged:(?:(?:[a-z0-9_.-]{1,80})\/(?:[a-z0-9_.-]{1,100}))?#[1-9][0-9]{0,8}|capacity_available:[a-z][a-z0-9_:-]{0,63}|resume_at:[1-9][0-9]{3}-[0-9]{2}-[0-9]{2}t[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,3})?(?:z|[+-][0-9]{2}:[0-9]{2}))(?=$|[\s,,。;;))])/iu)?.groups?.condition??null}function Wy(e,t){let n=zy(e),r=[],i=t.agents.find(e=>{let t=n.toLowerCase();return t.includes(e.agentId.toLowerCase())||t.includes(e.label.toLowerCase())}),a=t.todos.find(e=>n.includes(e.todoId)||n.includes(e.text)),o=/(刚刚|已经|已)(?:经)?\s*(新增|创建|添加)(?:的)?\s*(todo|待办|任务)/iu.test(n),s=!!t.goalId&&!By(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n);if(!t.goalId&&!By(n,/goal|目标/iu)&&/(创建|新建|设置|create|start|set up).{0,24}(goal|目标)/iu.test(n)&&r.push({actionKind:`goal.create`,confidence:.97,normalizedParameters:{heartbeat_enabled:!By(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n)}}),t.goalId&&s&&r.push({actionKind:`heartbeat.bind`,confidence:.96,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&!s&&!By(n,/定时|监控|监测|持续观察|scheduled check|monitor/iu)&&/(定时|监控|监测|每.{0,8}(分钟|小时|天)|持续观察|scheduled check|monitor|every.{0,12}(minute|hour|day)|daily)/iu.test(n)&&r.push({actionKind:`monitor.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&i&&!By(n,/绑定|负责|接管|管理/iu)&&/((让|交给).{0,20}(管理|负责|接管).{0,8}(goal|目标)|(绑定).{0,12}(goal|目标)|(goal|目标).{0,12}(交给|绑定|负责|接管))/iu.test(n)&&r.push({actionKind:`agent.bind`,confidence:.96,normalizedParameters:{agent_id:i.agentId,goal_id:t.goalId}}),t.goalId&&!o&&!By(n,RegExp(`todo|待办|任务`,`iu`))&&/(创建|新建|新增|添加|加一个|记一个).{0,16}(todo|待办|任务)|(todo|待办|任务).{0,12}(创建|新建|新增|添加)|(?:create|add)(?:\s+(?:a|an|new))?\s+(?:todo|task)|(?:todo|task).{0,12}(?:create|add)/iu.test(n)&&r.push({actionKind:`todo.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&Hy(n)&&r.push({actionKind:`todo.create`,confidence:.9,normalizedParameters:{goal_id:t.goalId,start_execution:!0}}),t.goalId&&a){let e=!By(n,/完成|做完|关闭/u)&&/完成|做完|关闭/u.test(n)?`complete`:!By(n,/阻塞|卡住/u)&&/阻塞|卡住/u.test(n)?`block`:!By(n,/暂缓|稍后|推迟/u)&&/暂缓|稍后|推迟/u.test(n)?`defer`:i&&!By(n,/交给|分配给|改派/u)&&/交给|分配给|改派/u.test(n)?`reassign`:null;if(e){let i=e===`defer`?Uy(n):null;if(e===`defer`&&!i)return{actionKind:`todo.update`,confidence:.97,missingFields:[`resume_when`],normalizedParameters:{goal_id:t.goalId,operation:e,todo_id:a.todoId},route:`clarify`};r.push({actionKind:`todo.update`,confidence:.97,normalizedParameters:{goal_id:t.goalId,operation:e,...i?{resume_when:i}:{},todo_id:a.todoId}})}}let c=[...new Map(r.map(e=>[e.actionKind,e])).values()];return c.length>1?{actionKind:null,confidence:.4,missingFields:[`single_intent`],normalizedParameters:{},route:`clarify`}:c.length===1?{...c[0],missingFields:[],route:`typed_action`}:!t.goalId&&Vy(n)?{actionKind:null,confidence:.98,missingFields:[],normalizedParameters:{},route:`projection`}:{actionKind:null,confidence:.75,missingFields:[],normalizedParameters:{},route:`agent_chat`}}function Gy(e,t,n){if(!e)return{};if(!t.trim())return{modelConfig:null};let r={model:t.trim()};return n&&(r.reasoning_effort=n),{modelConfig:r}}var Ky=[`a[href]`,`button:not([disabled])`,`textarea:not([disabled])`,`select:not([disabled])`,`input:not([disabled])`,`[tabindex]:not([tabindex='-1'])`].join(`,`),qy=[{key:`drawer.taskBlock`,operation:`block`},{key:`drawer.taskSuccessor`,operation:`successor_create`}],Jy=[{key:`drawer.decisionReject`,resolution:`reject`},{key:`drawer.decisionDefer`,resolution:`defer`}],Yy=Array.from({length:32},(e,t)=>t+1),Xy=/^[a-z][a-z0-9_.-]{0,63}$/u;function Zy(e){let t=String(e??``).trim().toLowerCase();return Xy.test(t)?t:null}function Qy(e,t){return e.enabled===t.enabled&&e.maxChildren===t.maxChildren&&JSON.stringify(e.modelConfig??null)===JSON.stringify(t.modelConfig??null)&&[...e.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)===[...t.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)}function $y({agents:e,attentionHistory:t=[],onSelectAttention:n,callbacks:r,goalNotifications:i=[],goals:a=[],inspectorExpanded:o=!1,larkConnections:s=[],onClose:c,onToggleInspectorSize:l,readOnly:u=!1,runs:d=[],selection:f}){let{locale:p,t:m}=Ji(),[h,g]=(0,z.useState)(``),[_,v]=(0,z.useState)(!1),[y,b]=(0,z.useState)(`idle`),[x,S]=(0,z.useState)(`record`),[C,w]=(0,z.useState)([]),[T,E]=(0,z.useState)(null),[D,O]=(0,z.useState)(2),[ee,te]=(0,z.useState)(``),[ne,k]=(0,z.useState)(``),[A,j]=(0,z.useState)(`idle`),[M,N]=(0,z.useState)(null),[P,F]=(0,z.useState)(null),re=(0,z.useRef)(null),ie=(0,z.useRef)(null),[I,ae]=(0,z.useState)(e.find(e=>e.available)?.agentId??`codex`),[L,oe]=(0,z.useState)(``),se=(0,z.useRef)(null),ce=(0,z.useRef)(null),le=(0,z.useRef)(null),ue=(0,z.useRef)(null),de=f.kind===`run`?`run:${f.item.runId}`:f.kind===`proposal`?`proposal:${f.item.previewId}`:f.kind===`todo`?`todo:${f.item.todoId}`:f.kind===`attention`?`attention:${f.item.todoId}`:f.kind===`output`?`output:${f.item.outputId}`:f.kind===`schedule`?`schedule:${f.item.scheduleId}`:`goal:${f.item.goalId}`;(0,z.useEffect)(()=>{b(`idle`),v(!1),S(`record`),oe(``);let e=f.kind===`goal`?f.item.subagentExecution:void 0;w(e?.allowedDomains??[]),te(e?.modelConfig?.model??``),k(e?.modelConfig?.reasoning_effort??``),O(e?.maxChildren?Math.min(e.maxChildren,32):2),E(null),j(`idle`),N(null),F(null),re.current=e??null,ie.current=null},[de]);let fe=f.kind===`goal`?f.item.subagentExecution:void 0;(0,z.useEffect)(()=>{let e=re.current,t=fe?!e||!Qy(e,fe):e!==null;if(re.current=fe??null,!P){t&&fe&&(w(fe.allowedDomains),te(fe.modelConfig?.model??``),k(fe.modelConfig?.reasoning_effort??``),O(fe.maxChildren||2),E(null),j(`idle`),N(null));return}let n=ie.current;(!fe||Qy(P,fe)||n&&!Qy(n,fe))&&(fe&&(w(fe.allowedDomains),te(fe.modelConfig?.model??``),k(fe.modelConfig?.reasoning_effort??``),O(fe.maxChildren||2)),ie.current=null,F(null))},[fe,P]),(0,z.useEffect)(()=>{let e=document.activeElement;e instanceof HTMLElement&&!ce.current?.contains(e)&&(le.current=e);let t=window.requestAnimationFrame(()=>ue.current?.focus());return()=>window.cancelAnimationFrame(t)},[de]);let pe=(0,z.useCallback)(()=>{let e=le.current;c(),window.requestAnimationFrame(()=>e?.focus())},[c]);(0,z.useEffect)(()=>{function e(e){if(e.key===`Escape`){e.preventDefault(),pe();return}if(e.key===`Tab`&&f.kind!==`todo`){let t=Array.from(ce.current?.querySelectorAll(Ky)??[]).filter(e=>!e.hasAttribute(`disabled`)&&e.getAttribute(`aria-hidden`)!==`true`);if(t.length===0)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n.focus())}}return document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`keydown`,e)}},[pe,f.kind]);let me=f.kind===`attention`?m(`drawer.titleAttention`):f.kind===`todo`?m(`drawer.taskDetails`):f.kind===`run`?m(`drawer.runDetails`):f.kind===`output`?m(`drawer.titleOutput`):f.kind===`proposal`?m(f.item.status===`applied`?`drawer.titleProposalApplied`:`drawer.titleProposalConfirm`):f.kind===`schedule`?f.item.scheduleKind===`heartbeat`?`Heartbeat`:m(`drawer.titleSchedule`):m(`drawer.goalDetails`),he=f.kind===`proposal`?f.item.goalId??`manager`:f.item.goalId,ge=f.kind===`attention`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`todo`||f.kind===`run`?f.item.goalTitle:f.kind===`output`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`goal`?f.item.title:f.kind===`schedule`?m(`drawer.goalAutoRun`):f.item.goalId?m(`drawer.goalChanges`):m(`drawer.managerChanges`),_e=f.kind===`goal`?d.find(e=>e.goalId===f.item.goalId&&!!e.sessionId)??d.find(e=>e.goalId===f.item.goalId):null,ve=f.kind===`run`&&(f.item.completedSteps>0||!!f.item.latestActivity||!!f.item.outputs?.length),ye=f.kind===`attention`?Zi(f.item.updatedAt,m):null,be=Uy(L);async function xe(){f.kind!==`run`||!h.trim()||(await r.onCorrectRun?.(f.item,h.trim()),g(``))}async function Se(e,t,n,i){if(t===`successor_create`){await r.onPreviewAction?.({actionKind:`todo.create`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-successor-${e.todoId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,text:m(`drawer.taskSuccessorText`,{task:e.text})},summary:m(`drawer.taskSuccessorSummary`,{task:e.text})});return}await r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:e.claimedBy??I,goal_id:e.goalId,operation:t,...t===`block`?{note:m(`drawer.taskSuccessorNote`)}:{},...t===`defer`&&i?{resume_when:i}:{},todo_id:e.todoId},summary:`${n}:${e.text}`})}async function Ce(e,t,n){u||!qd(e)||await r.onPreviewAction?.({actionKind:`gate.resolve`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-decision-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,decision:t,todo_id:e.todoId},summary:`${n}:${e.text}`})}let we=f.kind===`goal`?P??f.item.subagentExecution??{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0}:{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0},Te=A===`previewing`||A===`applying`,Ee=(()=>{if(f.kind!==`goal`)return[];let e=new Map;for(let t of we.allowedDomains){let n=Zy(t);n&&e.set(n,{matchingTodoCount:0,value:n})}if(we.domainCandidates)for(let t of we.domainCandidates){let n=Zy(t.domain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+t.matchingTodoCount,value:n})}else for(let t of f.item.agentTodos){if(t.done||t.taskClass!==`advancement_task`)continue;let n=Zy(t.taskDomain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+1,value:n})}return[...e.values()]})();function R(){w(we.allowedDomains),te(we.modelConfig?.model??``),k(we.modelConfig?.reasoning_effort??``),O(we.maxChildren||2),E(null),j(`idle`),N(null)}function De(){let e=[...new Set(C.map(e=>Zy(e)))];return e.every(e=>!!e)?e:null}function Oe(e,t){w(n=>t?[...n,e].filter((e,t,n)=>n.indexOf(e)===t):n.filter(t=>t!==e)),N(null),j(`idle`),E(null)}async function ke(e,t=e){if(f.kind!==`goal`||!r.onPreviewGoalSubagentConfiguration)return;let n=e?De():[];if(t&&!ee.trim()&&ne){j(`error`),E(m(`drawer.subagentModelRequired`));return}if(e&&!n){j(`error`),E(m(`drawer.subagentDomainInvalid`)),N(null);return}let i={allowedDomains:n??[],enabled:e,goalId:f.item.goalId,maxChildren:e?D:0,...Gy(t,ee,ne)};j(`previewing`),E(m(`drawer.subagentPreviewing`)),N(null);try{let e=await r.onPreviewGoalSubagentConfiguration(i);if(!e.changed){ie.current=fe??null,F({...e.configuration,domainCandidates:we.domainCandidates}),w(e.configuration.allowedDomains),te(e.configuration.modelConfig?.model??``),k(e.configuration.modelConfig?.reasoning_effort??``),O(e.configuration.maxChildren||2),j(`success`),E(m(`drawer.subagentNoChange`));return}N({...i,changed:e.changed,previewId:e.previewId}),j(`ready`),E(m(`drawer.subagentPreviewReady`))}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentPreviewFailed`))}}async function Ae(){if(!(!M||!r.onApplyGoalSubagentConfiguration)){j(`applying`),E(m(`drawer.subagentApplying`));try{let e=await r.onApplyGoalSubagentConfiguration({allowedDomains:M.allowedDomains,enabled:M.enabled,goalId:M.goalId,maxChildren:M.maxChildren,modelConfig:M.modelConfig,previewId:M.previewId});ie.current=fe??null,F({...e,domainCandidates:we.domainCandidates}),w(e.allowedDomains),te(e.modelConfig?.model??``),k(e.modelConfig?.reasoning_effort??``),O(e.maxChildren||2),j(`success`),E(m(`drawer.subagentApplied`)),N(null);try{await r.onRefresh?.()}catch{j(`warning`),E(m(`drawer.subagentAppliedRefreshFailed`))}}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentApplyFailed`))}}}return(0,B.jsxs)(`div`,{"aria-labelledby":`personal-drawer-title`,"aria-modal":f.kind===`todo`?void 0:`true`,className:`personal-context-drawer`,"data-context-kind":f.kind,ref:ce,role:`dialog`,children:[(0,B.jsxs)(`header`,{className:`personal-drawer-header${f.kind===`todo`?` is-task-inspector`:``}`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`h2`,{id:`personal-drawer-title`,ref:ue,tabIndex:-1,children:me}),(0,B.jsx)(`p`,{children:ge})]}),(0,B.jsxs)(`div`,{className:`personal-drawer-header-actions`,children:[f.kind===`todo`&&l?(0,B.jsx)(`button`,{"aria-label":m(o?`drawer.inspectorHalf`:`drawer.inspectorFull`),className:`personal-icon-button personal-inspector-size`,onClick:l,title:m(o?`drawer.inspectorHalfView`:`drawer.inspectorFullView`),type:`button`,children:o?(0,B.jsx)(Om,{size:17}):(0,B.jsx)(wm,{size:17})}):null,(0,B.jsxs)(`button`,{"aria-label":m(`drawer.closeDetail`,{context:ge}),className:`personal-icon-button personal-drawer-close`,onClick:pe,ref:se,type:`button`,children:[(0,B.jsx)(Gp,{className:`personal-mobile-back`,size:18}),(0,B.jsx)($m,{className:`personal-desktop-close`,size:18})]})]})]}),(0,B.jsxs)(`div`,{className:`personal-drawer-body`,children:[f.kind===`attention`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card is-attention`,children:[(0,B.jsx)(`small`,{children:f.item.blocking?m(`drawer.attentionBlocking`):m(`drawer.attentionWaiting`)}),(0,B.jsx)(`h3`,{children:f.item.text}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,B.jsx)(`dd`,{children:f.item.priority??`medium`})]}),ye?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`common.waiting`)}),(0,B.jsx)(`dd`,{children:m(`tasks.waitingAge`,{age:ye})})]}):null]})]}),(0,B.jsx)(Ry,{item:f.item,onSelect:n,successor:Kd(f.item,t)}),!u&&qd(f.item)?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void Ce(f.item,`approve`,m(`common.confirm`)),type:`button`,children:[(0,B.jsx)(em,{size:17}),m(`drawer.decisionReview`)]}),(0,B.jsxs)(`details`,{className:`personal-compact-menu`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(dm,{size:17}),m(`drawer.decisionMore`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`button`,{onClick:()=>void r.onExplainDecision?.(f.item),type:`button`,children:[(0,B.jsx)(Em,{size:16}),m(`drawer.explainDecision`)]}),Jy.map(e=>(0,B.jsx)(`button`,{onClick:()=>void Ce(f.item,e.resolution,m(e.key)),type:`button`,children:m(e.key)},e.resolution))]})]})]}):null]}):null,f.kind===`todo`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-task-inspector-summary`,children:[(0,B.jsxs)(`div`,{className:`personal-task-inspector-status`,children:[(0,B.jsxs)(`span`,{className:f.item.done?`is-done`:f.item.status===`blocked`?`is-blocked`:`is-open`,children:[(0,B.jsx)(`i`,{}),f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)]}),f.item.priority?(0,B.jsx)(`span`,{children:f.item.priority}):null,(0,B.jsx)(`span`,{children:f.item.taskClass===`advancement_task`?m(`drawer.taskAdvancement`):f.item.taskClass??m(`drawer.taskOrdinary`)})]}),(0,B.jsx)(`h3`,{children:f.item.text})]}),(0,B.jsxs)(`section`,{"aria-label":m(`drawer.taskInfo`),className:`personal-task-inspector-fields`,children:[(0,B.jsx)(`h4`,{children:m(`drawer.taskInfo`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`common.owner`)}),(0,B.jsx)(`dd`,{children:f.item.ownerLabel??f.item.claimedBy??m(`drawer.notAssigned`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`common.status`)}),(0,B.jsx)(`dd`,{children:f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,B.jsx)(`dd`,{children:f.item.priority??m(`drawer.notSet`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.dependencies`)}),(0,B.jsx)(`dd`,{children:f.item.dependencies?.join(` · `)||m(`common.none`)})]}),f.item.status===`deferred`||f.item.resumeWhen?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.resumeWhen`)}),(0,B.jsx)(`dd`,{children:f.item.resumeWhen||m(`drawer.notSet`)})]}):null,f.item.resumeWhen?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.resumeState`)}),(0,B.jsx)(`dd`,{children:f.item.resumeReady?m(`drawer.resumeReady`):m(`drawer.resumePending`)})]}):null,f.item.resumeReceiptId?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.resumeReceipt`)}),(0,B.jsx)(`dd`,{children:f.item.resumeReceiptId})]}):null,(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.nextTransition`)}),(0,B.jsx)(`dd`,{children:f.item.nextTransition??(f.item.done?m(`drawer.taskNextCompleted`):f.item.resumeReady?m(`drawer.taskNextResumeReady`):f.item.status===`deferred`?m(`drawer.taskNextDeferred`):m(`drawer.taskNextOpen`))})]})]})]}),!u&&!f.item.done?(0,B.jsxs)(`div`,{className:`personal-task-inspector-actions`,"aria-label":m(`drawer.taskActions`),children:[(0,B.jsxs)(`details`,{className:`personal-task-management`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(dm,{size:16}),m(`drawer.taskManage`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:m(`drawer.reassign`)}),(0,B.jsxs)(`label`,{className:`personal-inline-agent-select`,children:[m(`drawer.reassign`),(0,B.jsx)(`select`,{"aria-label":m(`drawer.reassign`),onChange:e=>ae(e.target.value),value:I,children:e.filter(e=>e.available).map(e=>(0,B.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:f.item.goalId,kind:`todo`,todo_id:f.item.todoId},idempotencyKey:`workspace-todo-${f.item.todoId}-reassign-${I}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:I,goal_id:f.item.goalId,operation:`reassign`,todo_id:f.item.todoId},summary:m(`drawer.reassignSummary`,{task:f.item.text})}),type:`button`,children:m(`timeline.review`)})]}),(0,B.jsx)(`strong`,{children:m(`drawer.taskDeferUntil`)}),(0,B.jsxs)(`label`,{className:`personal-inline-agent-select personal-inline-resume-when`,children:[m(`drawer.taskDeferUntil`),(0,B.jsx)(`input`,{"aria-label":m(`drawer.taskDeferCondition`),"aria-invalid":!!L.trim()&&!be,onChange:e=>oe(e.target.value),placeholder:m(`drawer.taskDeferPlaceholder`),value:L}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:!be,onClick:()=>void Se(f.item,`defer`,m(`drawer.taskDefer`),be??void 0),type:`button`,children:m(`drawer.taskDeferReview`)}),(0,B.jsx)(`small`,{children:L.trim()&&!be?m(`drawer.taskDeferInvalid`):m(`drawer.taskDeferSupported`)})]}),(0,B.jsx)(`div`,{className:`personal-task-management-secondary`,children:qy.map(e=>(0,B.jsx)(`button`,{onClick:()=>void Se(f.item,e.operation,m(e.key)),type:`button`,children:m(e.key)},e.operation))})]})]}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void Se(f.item,`complete`,m(`drawer.taskComplete`)),type:`button`,children:[(0,B.jsx)(em,{size:17}),m(`drawer.taskComplete`)]})]}):null,f.item.done?(0,B.jsxs)(`div`,{className:`personal-task-completed-note`,children:[(0,B.jsx)(em,{size:16}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:m(`drawer.taskCompletedTitle`)}),(0,B.jsx)(`small`,{children:m(`drawer.taskCompletedNote`)})]})]}):null]}):null,f.kind===`goal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsx)(`small`,{children:Yi(f.item.state,p)}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.agentSentence}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.tokens`)}),(0,B.jsxs)(`dd`,{children:[by(f.item.usage?.tokens24h,m(`drawer.usageNotMeasured`),_y),` / `,by(f.item.usage?.tokens7d,m(`drawer.usageNotMeasured`),_y)]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.cost`)}),(0,B.jsxs)(`dd`,{children:[by(f.item.usage?.costUsd24h,m(`drawer.usageNotMeasured`),vy),` / `,by(f.item.usage?.costUsd7d,m(`drawer.usageNotMeasured`),vy)]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.duration`)}),(0,B.jsxs)(`dd`,{children:[by(f.item.usage?.durationMs24h,m(`drawer.usageNotMeasured`),yy),` / `,by(f.item.usage?.durationMs7d,m(`drawer.usageNotMeasured`),yy)]})]})]})]}),(0,B.jsx)(Ly,{goal:f.item}),(()=>{let e=i.find(e=>e.goalId===f.item.goalId),t=s.find(e=>e.goal_id===f.item.goalId);return(0,B.jsxs)(B.Fragment,{children:[f.item.repository?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-repository`,children:[(0,B.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,B.jsx)(`small`,{children:m(`drawer.repository`)}),(0,B.jsx)(`em`,{children:m(`common.readOnly`)})]}),(0,B.jsxs)(`h3`,{children:[(0,B.jsx)(_m,{size:16}),f.item.repository.label]}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.branch`)}),(0,B.jsx)(`dd`,{children:f.item.repository.branch||`detached`})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Role`}),(0,B.jsx)(`dd`,{children:m(`drawer.repositoryRole`)})]})]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>{let e=navigator.clipboard?.writeText(f.item.repository?.identity??``);if(!e){b(`error`);return}e.then(()=>b(`copied`)).catch(()=>b(`error`))},type:`button`,children:[(0,B.jsx)(cm,{size:15}),m(y===`copied`?`drawer.copyRepositoryDone`:`drawer.copyRepository`)]}),y===`error`?(0,B.jsx)(`p`,{className:`personal-copy-feedback is-error`,role:`status`,children:m(`drawer.copyRepositoryError`)}):y===`copied`?(0,B.jsx)(`p`,{className:`personal-copy-feedback`,role:`status`,children:m(`drawer.copyRepositorySuccess`)}):null]}):null,u?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,B.jsx)(`small`,{children:m(`drawer.larkConnection`)}),(0,B.jsx)(`h3`,{children:m(`drawer.remoteDetailsUnavailable`)}),(0,B.jsx)(`p`,{children:m(`drawer.remoteDetailsDescription`)})]}):(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,B.jsx)(`small`,{children:m(`drawer.larkConnection`)}),t?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`h3`,{children:[t.app_label,(0,B.jsx)(`span`,{className:`personal-connection-status`,children:m(`drawer.connected`)})]}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.group`)}),(0,B.jsx)(`dd`,{children:t.chat_name})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.topic`)}),(0,B.jsxs)(`dd`,{children:[`# `,t.topic_name]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.trigger`)}),(0,B.jsx)(`dd`,{children:t.incoming_mode===`mentions`?m(`lark.someoneMentions`):m(`lark.allMessages`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.replyMode`)}),(0,B.jsx)(`dd`,{children:m(`lark.topicReply`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.autoNotify`)}),(0,B.jsx)(`dd`,{children:e?.humanGateAutoNotifyEnabled?m(`common.on`):m(`common.off`)})]}),e?.lastNotifiedAt?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.lastNotification`)}),(0,B.jsx)(`dd`,{children:e.lastNotifiedAt})]}):null]})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h3`,{children:m(`drawer.larkNotConfigured`)}),(0,B.jsx)(`p`,{children:m(`drawer.larkNotConfiguredDescription`)})]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onOpenNotificationSettings?.(f.item.goalId),type:`button`,children:[(0,B.jsx)(Xp,{size:16}),m(t?`drawer.larkConfigure`:`drawer.larkConnect`)]})]})]})})(),(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-session`,children:[(0,B.jsx)(`small`,{children:m(`drawer.runDetails`)}),_e?.sessionId?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h3`,{children:Xi(_e.sessionStatus??_e.status,m)}),(0,B.jsx)(`p`,{children:_e.title}),r.onOpenRunSession?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onOpenRunSession?.(_e),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.runLatest`)]}):null]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h3`,{children:m(`drawer.noRun`)}),(0,B.jsx)(`p`,{children:m(`drawer.noRunDescription`)})]})]}),u?null:(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`heartbeat`,f.item.goalId),type:`button`,children:[(0,B.jsx)(Fm,{size:16}),m(`drawer.setupHeartbeat`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`monitor`,f.item.goalId),type:`button`,children:[(0,B.jsx)($p,{size:16}),m(`drawer.scheduleAdd`)]})]}),f.item.subagentExecution?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-subagents`,children:[(0,B.jsxs)(`div`,{className:`personal-subagent-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:m(`drawer.subagentLabel`)}),(0,B.jsxs)(`h3`,{children:[(0,B.jsx)(Zp,{size:16}),m(`drawer.subagentTitle`)]})]}),(0,B.jsxs)(`button`,{"aria-checked":we.enabled,"aria-label":m(M&&A===`ready`?`drawer.subagentPending`:we.enabled?`drawer.subagentDisable`:`drawer.subagentEnable`),className:`personal-subagent-switch`,"data-pending":M&&A===`ready`?`true`:void 0,disabled:u||Te||!!M||!r.onPreviewGoalSubagentConfiguration,onClick:()=>void ke(!we.enabled),role:`switch`,type:`button`,children:[(0,B.jsx)(`span`,{}),m(M&&A===`ready`?`drawer.subagentPending`:we.enabled?`common.on`:`common.off`)]})]}),(0,B.jsx)(`p`,{children:m(`drawer.subagentDescription`)}),M&&A===`ready`?(0,B.jsxs)(`div`,{className:`personal-subagent-preview`,children:[(0,B.jsx)(`strong`,{children:m(M.enabled?`drawer.subagentConfirmEnable`:`drawer.subagentConfirmDisable`)}),(0,B.jsx)(`p`,{children:M.enabled?m(`drawer.subagentPreviewSummary`,{count:M.maxChildren,domains:M.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)}):m(`drawer.subagentDisableSummary`)}),M.modelConfig===void 0?null:(0,B.jsxs)(`p`,{children:[m(`drawer.subagentModel`),`: `,M.modelConfig?.model||m(`drawer.subagentModelDefault`),` · `,M.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`button`,{className:`personal-primary-action`,onClick:()=>void Ae(),type:`button`,children:m(`common.confirm`)}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:R,type:`button`,children:m(`common.cancel`)})]})]}):null,T?(0,B.jsxs)(`p`,{className:`personal-subagent-feedback is-${A}`,role:`status`,children:[A===`previewing`||A===`applying`?(0,B.jsx)(Lm,{className:`personal-spin`,size:13}):null,T]}):null,(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentModel`)}),(0,B.jsx)(`dd`,{children:we.modelConfig?.model||m(`drawer.subagentModelDefault`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentEffort`)}),(0,B.jsx)(`dd`,{children:we.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentCurrentBoundary`)}),(0,B.jsx)(`dd`,{children:we.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentChildLimit`)}),(0,B.jsx)(`dd`,{children:we.maxChildren||0})]})]}),u?(0,B.jsx)(`p`,{className:`personal-subagent-read-only`,children:m(`drawer.subagentRemoteReadOnly`)}):(0,B.jsxs)(`div`,{className:`personal-subagent-fields`,children:[(0,B.jsxs)(`fieldset`,{className:`personal-subagent-domain-picker`,disabled:Te,children:[(0,B.jsx)(`legend`,{children:m(`drawer.subagentDomains`)}),Ee.length>0?(0,B.jsx)(`div`,{className:`personal-subagent-domain-options`,children:Ee.map(e=>{let t=C.includes(e.value);return(0,B.jsxs)(`label`,{className:`personal-subagent-domain-option${t?` is-selected`:``}`,children:[(0,B.jsx)(`input`,{"aria-label":e.value,checked:t,onChange:t=>Oe(e.value,t.target.checked),type:`checkbox`}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.value}),(0,B.jsx)(`small`,{children:m(`drawer.subagentDomainTodoCount`,{count:e.matchingTodoCount})})]})]},e.value)})}):(0,B.jsx)(`p`,{className:`personal-subagent-domain-empty`,children:m(`drawer.subagentDomainsEmpty`)}),(0,B.jsx)(`small`,{children:m(`drawer.subagentDomainsHint`)})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:m(`drawer.subagentModel`)}),(0,B.jsx)(`input`,{"aria-label":m(`drawer.subagentModel`),disabled:Te,value:ee,placeholder:`gpt-5.6-luna`,onChange:e=>{te(e.target.value),N(null),j(`idle`),E(null)}})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:m(`drawer.subagentEffort`)}),(0,B.jsxs)(`select`,{"aria-label":m(`drawer.subagentEffort`),disabled:Te,value:ne,onChange:e=>{k(e.target.value),N(null),j(`idle`),E(null)},children:[(0,B.jsx)(`option`,{value:``,children:m(`drawer.subagentModelDefault`)}),[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`].map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))]})]}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:Te,type:`button`,onClick:()=>{te(`gpt-5.6-luna`),k(`max`),N(null),j(`idle`),E(null)},children:m(`drawer.subagentLunaPreset`)}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:Te,type:`button`,onClick:()=>{te(``),k(``),N(null),j(`idle`),E(null)},children:m(`drawer.subagentClearModel`)}),(0,B.jsx)(`p`,{children:m(`drawer.subagentModelHint`)}),(0,B.jsxs)(`label`,{className:`personal-subagent-limit-field`,children:[(0,B.jsx)(`span`,{children:m(`drawer.subagentMaxChildren`)}),(0,B.jsx)(`select`,{"aria-label":m(`drawer.subagentMaxChildren`),disabled:Te,onChange:e=>{O(Number(e.target.value)),N(null),j(`idle`),E(null)},value:D,children:Yy.map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))})]}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:Te,onClick:()=>void ke(we.enabled,!0),type:`button`,children:m(`drawer.subagentPreviewBoundary`)})]})]}):null]}):null,f.kind===`run`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{"aria-label":m(`drawer.runView`),className:`personal-run-drawer-tabs`,role:`tablist`,children:[(0,B.jsx)(`button`,{"aria-selected":x===`record`,onClick:()=>S(`record`),role:`tab`,type:`button`,children:m(`drawer.executionRecordAndResult`)}),(0,B.jsx)(`button`,{"aria-selected":x===`details`,onClick:()=>S(`details`),role:`tab`,type:`button`,children:m(`drawer.detailsAndActions`)})]}),x===`record`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card personal-session-summary`,children:[(0,B.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Xi(f.item.sessionStatus??f.item.status,m)]}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.latestActivity}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,B.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]})]})]}),(0,B.jsxs)(`section`,{"aria-label":m(`drawer.executionRecord`),className:`personal-session-message-record`,children:[(0,B.jsx)(`h3`,{children:m(`drawer.executionRecord`)}),f.item.sessionMessages?.length?(0,B.jsx)(`ol`,{children:f.item.sessionMessages.map(e=>(0,B.jsxs)(`li`,{className:`is-${e.role}`,children:[(0,B.jsx)(`i`,{}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:e.role===`user`?m(`drawer.runRoleUser`):e.role===`assistant`?m(`drawer.runRoleAssistant`):m(`drawer.runRoleSystem`)}),e.createdAt?(0,B.jsx)(`time`,{children:new Date(e.createdAt).toLocaleTimeString(p,{hour:`2-digit`,minute:`2-digit`,hour12:!1})}):null]}),(0,B.jsx)(`p`,{children:e.text})]})]},e.messageId))}):(0,B.jsx)(`p`,{className:`personal-session-empty`,children:ve?m(`drawer.runRecordProjected`,{completed:f.item.completedSteps,outputs:f.item.outputs?.length?m(`drawer.runRecordProjectedOutputs`,{count:f.item.outputs.length}):``,total:f.item.totalSteps}):m(`drawer.runRecordEmpty`)}),f.item.status===`running`?(0,B.jsxs)(`div`,{className:`personal-session-active-step`,children:[(0,B.jsx)(`i`,{}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:m(`drawer.analysis`)}),(0,B.jsx)(`small`,{children:m(`drawer.agentWorking`)})]})]}):null]}),f.item.outputs?.length?(0,B.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-run-outputs-title`,children:[(0,B.jsx)(`h3`,{id:`personal-run-outputs-title`,children:m(`drawer.outputs`)}),(0,B.jsx)(`ol`,{children:f.item.outputs.map(e=>(0,B.jsx)(`li`,{children:(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsx)(`small`,{children:e.createdAt??e.kind??m(`files.emptySummary`)})]})},e.outputId))})]}):null]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Xi(f.item.status,m)]}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.latestActivity}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,B.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.sessionStatus`)}),(0,B.jsx)(`dd`,{children:Xi(f.item.sessionStatus??f.item.status,m)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.sessionRecoverable`)}),(0,B.jsx)(`dd`,{children:f.item.resumable===!1?m(`drawer.resumeNo`):m(`drawer.resumeYes`)})]})]})]}),f.item.sessionStatus===`resume_failed`&&!u?(0,B.jsxs)(`section`,{className:`personal-recovery-panel`,"aria-label":m(`drawer.recoveryFailed`),children:[(0,B.jsx)(`strong`,{children:m(`drawer.recoveryFailed`)}),(0,B.jsx)(`p`,{children:m(`drawer.recoveryDescription`)}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,B.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.recoveryNewSession`)]})]}):null,u?null:(0,B.jsxs)(`section`,{className:`personal-correction-panel`,children:[(0,B.jsx)(`header`,{children:(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:16}),m(`drawer.correctionLabel`,{agent:f.item.agentLabel})]})}),(0,B.jsx)(`p`,{children:m(`drawer.correctionDescription`)}),(0,B.jsxs)(`div`,{className:`personal-correction-composer`,children:[(0,B.jsx)(`textarea`,{"aria-label":m(`drawer.correctionTextarea`,{agent:f.item.agentLabel,goal:f.item.goalTitle,run:f.item.title}),onChange:e=>g(e.target.value),placeholder:m(`drawer.correctionPlaceholder`),rows:3,value:h}),(0,B.jsx)(`button`,{"aria-label":m(`drawer.correctionSend`),disabled:!h.trim(),onClick:()=>void xe(),type:`button`,children:(0,B.jsx)(Bm,{size:16})})]})]}),u?null:(0,B.jsxs)(`details`,{className:`personal-compact-menu personal-run-more`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(dm,{size:17}),m(`drawer.moreRunActions`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`button`,{disabled:!f.item.canInterrupt,onClick:()=>void r.onInterruptRun?.(f.item),type:`button`,children:[(0,B.jsx)(Mm,{size:16}),m(`drawer.runInterrupt`)]}),(0,B.jsxs)(`button`,{disabled:f.item.resumable===!1,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,B.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,B.jsxs)(`button`,{onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.runNewSession`)]}),(0,B.jsxs)(`button`,{onClick:()=>void r.onCloseRunSession?.(f.item),type:`button`,children:[(0,B.jsx)(qm,{size:16}),m(`drawer.runCloseSession`)]})]})]})]})]}):null,f.kind===`output`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsx)(`small`,{children:f.item.kind??`output`}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.summary??m(`drawer.outputRecorded`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.outputTodo`)}),(0,B.jsx)(`dd`,{children:f.item.todoId??m(`drawer.notLinked`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.outputRun`)}),(0,B.jsx)(`dd`,{children:f.item.runId??m(`drawer.notLinked`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Agent`}),(0,B.jsx)(`dd`,{children:f.item.agentLabel??f.item.agentId??`LoopX`})]})]})]}),f.item.report?(0,B.jsxs)(`section`,{className:`personal-report-detail`,"data-testid":`personal-periodic-report-detail`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsxs)(`strong`,{children:[`+`,f.item.report.addedCount]}),m(`files.reportAdded`)]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:f.item.report.changedCount}),m(`files.reportChanged`)]})]}),(0,B.jsxs)(`p`,{children:[f.item.report.periodStartAt,` → `,f.item.report.periodEndAt]}),(0,B.jsx)(`ol`,{children:f.item.report.items.map(e=>(0,B.jsxs)(`li`,{"data-change-kind":e.changeKind,children:[(0,B.jsxs)(`small`,{children:[e.changeKind,` · `,e.status]}),(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsx)(`p`,{children:e.summary})]},e.sourceRef))}),(0,B.jsxs)(`footer`,{children:[(0,B.jsxs)(`span`,{children:[m(`files.reportPublication`),`: `,f.item.report.publicationId]}),(0,B.jsxs)(`span`,{children:[m(`files.reportGeneration`),`: `,f.item.report.generationId]})]})]}):null,f.item.safePreview?(0,B.jsx)(`pre`,{"aria-label":m(`drawer.outputSafePreview`),className:`personal-safe-preview`,children:f.item.safePreview}):(0,B.jsx)(`p`,{className:`personal-preview-unavailable`,children:m(`drawer.previewUnavailable`)}),(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:!r.onOpenOutput,onClick:()=>{r.onOpenOutput?.(f.item),c()},type:`button`,children:[(0,B.jsx)(fm,{size:16}),m(`files.openConversation`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!r.onExportOutput,onClick:()=>void r.onExportOutput?.(f.item),type:`button`,children:[(0,B.jsx)(um,{size:16}),m(`files.exportSummary`)]})]})]}):null,f.kind===`proposal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-proposal-card`,children:[(0,B.jsxs)(`small`,{children:[f.item.actionKind,` · `,f.item.status]}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.impact}),f.item.reviewPlan?(0,B.jsx)(`p`,{className:`personal-proposal-explainer`,"data-action-review":f.item.reviewPlan.interaction,children:m(`actionReview.${f.item.reviewPlan.reason}`)}):null,f.item.status===`ready`?(0,B.jsx)(`p`,{className:`personal-proposal-explainer`,children:m(`drawer.proposalExplainer`)}):null,(0,B.jsx)(`dl`,{children:f.item.fields.map(e=>(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:e.label}),(0,B.jsx)(`dd`,{children:e.value})]},e.key))})]}),f.item.status===`applied`?(0,B.jsxs)(`p`,{className:`personal-proposal-state is-applied`,children:[(0,B.jsx)(em,{size:16}),m(`drawer.proposalApplied`)]}):null,f.item.status===`applied`&&f.item.goalId?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>{let e=f.item.goalId;c(),r.onOpenGoal?.(e)},type:`button`,children:[(0,B.jsx)(fm,{size:16}),f.item.actionKind===`goal.create`?m(`drawer.proposalEnterGoal`):m(`drawer.proposalViewGoal`)]}):null,f.item.status===`stale`?(0,B.jsx)(`p`,{className:`personal-proposal-state is-stale`,children:m(`drawer.proposalStale`)}):null,f.item.status===`error`?(0,B.jsxs)(`div`,{className:`personal-proposal-state is-error`,children:[(0,B.jsx)(`span`,{children:f.item.reviewPlan?.reason===`readback_unverified`?m(`actionReview.readback_unverified`):m(`drawer.proposalApplyFailed`)}),f.item.errorMessage?(0,B.jsx)(`small`,{children:f.item.errorMessage}):null,(0,B.jsx)(`small`,{children:m(`drawer.proposalApplyFailedHint`)})]}):null,f.item.status===`rejected`?(0,B.jsx)(`p`,{className:`personal-proposal-state is-error`,children:m(`drawer.proposalRejected`)}):null,f.item.status===`deferred`?(0,B.jsx)(`p`,{className:`personal-proposal-state is-gated`,children:m(`drawer.proposalDeferred`)}):null,f.item.status===`gated`?(0,B.jsxs)(`div`,{className:`personal-proposal-state is-gated`,children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:m(`drawer.gateRequiresHost`)}),m(`drawer.gateRequiresHostDescription`)]}),f.item.gate?.nextAction?(0,B.jsx)(`small`,{children:f.item.gate.nextAction}):null]}):null,f.item.status===`gated`&&f.item.actionKind===`gate.resolve`?(()=>{let e=e=>f.item.fields.find(t=>t.key===e)?.value,t=e(`goal_id`),n=e(`todo_id`);return!t||!n?null:(0,B.jsxs)(`section`,{className:`personal-detail-card personal-gate-cli-hint`,children:[(0,B.jsx)(`small`,{children:m(`drawer.gateApproveHint`)}),(0,B.jsxs)(`code`,{children:[`loopx todo complete --goal-id `,t,` --todo-id `,n,` --decision-outcome approve`]}),(0,B.jsx)(`small`,{children:m(`drawer.gateRejectHint`)})]})})():null,!u&&f.item.workspaceCandidates?.length?(0,B.jsx)(`div`,{className:`personal-workspace-candidates`,"aria-label":m(`drawer.workspaceCandidates`),children:f.item.workspaceCandidates.map(e=>(0,B.jsxs)(`button`,{onClick:()=>void r.onSelectWorkspaceCandidate?.(f.item,e.workspaceRef),type:`button`,children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsx)(`small`,{children:e.workspaceRef})]},e.workspaceRef))}):null,!u&&f.item.status===`error`?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,B.jsx)(Lm,{size:17}),m(`drawer.proposalRegenerate`)]}):!u&&f.item.status!==`gated`?(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:![`ready`,`deferred`].includes(f.item.status)||f.item.reviewPlan?.canApply===!1,onClick:()=>void r.onApplyProposal?.(f.item),type:`button`,children:[(0,B.jsx)(em,{size:17}),f.item.status===`applying`?m(`drawer.applying`):f.item.primaryLabel??m(`drawer.apply`)]}):null,!u&&([`stale`,`gated`,`rejected`].includes(f.item.status)||f.item.status===`ready`&&f.item.reviewPlan?.canApply===!1)?(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,B.jsx)(Lm,{size:16}),m(`drawer.proposalRecheck`)]}):null,!u&&[`ready`,`gated`].includes(f.item.status)?(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`defer`),type:`button`,children:m(`drawer.proposalDefer`)}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`reject`),type:`button`,children:m(`drawer.decisionReject`)})]}):null,[`applied`,`applying`].includes(f.item.status)?null:(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:c,type:`button`,children:m(`drawer.proposalClose`)})]}):null,f.kind===`schedule`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsxs)(`small`,{children:[f.item.scheduleKind===`heartbeat`?`Goal Heartbeat`:`continuous_monitor`,` · `,f.item.status??`active`]}),(0,B.jsx)(`h3`,{children:f.item.label}),(0,B.jsx)(`p`,{children:f.item.target??f.item.schedule??m(`drawer.scheduleDefaultTarget`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleTimezone`)}),(0,B.jsx)(`dd`,{children:f.item.timezone??m(`drawer.scheduleLocalTimezone`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleNext`)}),(0,B.jsx)(`dd`,{children:f.item.nextRunAt??m(`drawer.schedulePending`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleLast`)}),(0,B.jsx)(`dd`,{children:f.item.previousRunAt??m(`drawer.scheduleNeverRun`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleNotification`)}),(0,B.jsx)(`dd`,{children:f.item.notificationRule??m(`drawer.scheduleDefaultNotification`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleStopCondition`)}),(0,B.jsx)(`dd`,{children:f.item.stopCondition??m(`drawer.scheduleDefaultStop`)})]})]})]}),!u&&f.item.scheduleKind===`monitor`?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`run_now`),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.scheduleRunNow`)]}):null,u?null:(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,f.item.status===`paused`?`resume`:`pause`),type:`button`,children:[f.item.status===`paused`?(0,B.jsx)(Nm,{size:16}):(0,B.jsx)(Mm,{size:16}),f.item.status===`paused`?m(`drawer.scheduleResume`):m(`drawer.schedulePause`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`edit`),type:`button`,children:[(0,B.jsx)($p,{size:16}),m(`drawer.scheduleEdit`)]})]}),u?null:(0,B.jsxs)(`button`,{className:`personal-danger-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`stop`),type:`button`,children:[(0,B.jsx)(qm,{size:16}),m(`drawer.scheduleStop`,{kind:f.item.scheduleKind===`heartbeat`?` Heartbeat`:m(`drawer.titleSchedule`)})]}),(0,B.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-execution-history-title`,children:[(0,B.jsx)(`h3`,{id:`personal-execution-history-title`,children:m(`drawer.executionHistory`)}),f.item.executionHistory?.length?(0,B.jsx)(`ol`,{children:f.item.executionHistory.map((e,t)=>(0,B.jsxs)(`li`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsx)(`small`,{children:e.timestamp})]}),(0,B.jsx)(`em`,{className:`is-${e.status}`,children:e.status})]},`${e.timestamp}:${e.runId??t}`))}):(0,B.jsx)(`p`,{children:m(`drawer.noExecutionHistory`)})]})]}):null,f.kind===`run`||f.kind===`proposal`||f.kind===`schedule`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`button`,{"aria-expanded":_,className:`personal-diagnostics-trigger`,onClick:()=>v(e=>!e),type:`button`,children:[(0,B.jsx)(`span`,{children:m(`drawer.advancedDiagnostics`)}),(0,B.jsx)(tm,{className:_?`is-open`:``,size:16})]}),_?(0,B.jsxs)(`div`,{className:`personal-diagnostics`,children:[(0,B.jsxs)(`code`,{children:[`goal_id: `,he]}),(0,B.jsxs)(`code`,{children:[`kind: `,f.kind]}),f.kind===`run`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`code`,{children:[`session_id: `,f.item.sessionId??m(`drawer.notLinked`)]}),(0,B.jsxs)(`code`,{children:[`turn_id: `,f.item.turnId??m(`common.none`)]}),(0,B.jsxs)(`code`,{children:[`adapter: `,f.item.agentId]}),(0,B.jsxs)(`code`,{children:[`status: `,f.item.sessionStatus??f.item.status]})]}):f.kind===`proposal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`code`,{children:[`action: `,f.item.actionKind]}),(0,B.jsxs)(`code`,{children:[`status: `,f.item.status]})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`code`,{children:[`schedule_id: `,f.item.scheduleId]}),(0,B.jsxs)(`code`,{children:[`status: `,f.item.status??`active`]})]})]}):null]}):null]})]})}var eb=[`checking`,`connecting`,`downloading`,`installing_app`,`installing_runtime`],tb={desktop_status_unavailable:[`无法读取 App 更新状态。请重启 App 后再试;若仍失败,请重新安装最新 App。`,`Cannot read the App update status. Restart the App; if this persists, reinstall the latest App.`],update_feed_unavailable:[`此通道的更新源尚未就绪或暂时不可用。可稍后重新检查,当前版本仍可继续使用。`,`This channel's update feed is not ready or temporarily unavailable. Check again later; you can keep using this version.`],update_feed_invalid:[`更新源格式异常。请稍后重新检查。`,`The update feed is invalid. Check again later.`],update_platform_unavailable:[`此通道尚无适用于本机的更新包。`,`This channel has no update package for this platform.`],update_check_timeout:[`检查更新超时。请稍后重试。`,`The update check timed out. Try again later.`],update_network_failed:[`无法连接更新服务器。请检查网络后重试。`,`Cannot reach the update server. Check your connection and retry.`],update_download_or_signature_failed:[`更新包下载或签名校验失败,尚未安装。请重新检查更新。`,`Download or signature verification failed; the update was not installed. Check for updates again.`]};function nb(e,t=`update_failed`){return{phase:`error`,details:{code:typeof e==`string`&&Object.hasOwn(tb,e)?e:t}}}function rb(){let{locale:e}=Ji(),t=e===`zh-CN`,[n,r]=(0,z.useState)(!1),i=(0,z.useRef)(null),[a,o]=(0,z.useState)(`stable`),[s,c]=(0,z.useState)({phase:`idle`}),[l,u]=(0,z.useState)(``),[d,f]=(0,z.useState)(!1),p=(0,z.useRef)(!1),m=window.__TAURI__?.core.invoke,h=eb.includes(s.phase);(0,z.useEffect)(()=>{let e=i.current;if(!e)return;let t=()=>r(e.matches(`:popover-open`));return e.addEventListener(`toggle`,t),()=>e.removeEventListener(`toggle`,t)},[]),(0,z.useEffect)(()=>{if(!m)return;let e=!0;return m(`desktop_update_status`).then(t=>{if(!e)return;u(t.app_version),f(t.rollback_available===!0),t.state?.phase&&c(t.state);let n=t.state?.details?.channel??(t.app_version.includes(`-main.`)?`main`:`stable`);o(n),t.state?.phase||m(`desktop_update`,{action:`check`,channel:n}).then(t=>{e&&c(t)}).catch(t=>{e&&c(nb(t))})}).catch(()=>{e&&c(nb(null,`desktop_status_unavailable`))}),()=>{e=!1}},[m]),(0,z.useEffect)(()=>{if(!m||!h)return;let e=window.setInterval(()=>{m(`desktop_update_status`).then(e=>{e.state?.phase&&c(e.state)}).catch(()=>{})},1e3);return()=>window.clearInterval(e)},[m,h]);async function g(e){if(!(!m||p.current)){p.current=!0,c({phase:e===`check`?`checking`:e===`repair`?`installing_runtime`:`downloading`});try{if(!l){let e=await m(`desktop_update_status`);u(e.app_version),f(e.rollback_available===!0)}c(await m(`desktop_update`,{action:e,channel:a}))}catch(e){c(nb(e,l?`update_failed`:`desktop_status_unavailable`))}finally{p.current=!1}}}let _={service_error:t?`运行时已安装,但服务尚未连接。可重试更新、修复或恢复上版。`:`Runtime installed, but services are unavailable. Retry updates, repair, or restore the previous version.`,idle:t?`App 会检查可用更新,不会自动安装。`:`Updates are checked automatically, never installed without confirmation.`,runtime_required:t?`请完成匹配组件安装,或检查 App 更新。`:`Install matching components or check for an App update.`,connecting:t?`正在连接更新后的服务…`:`Connecting to updated services…`,checking:t?`正在检查更新…`:`Checking for updates…`,available:t?`新版本已就绪,一次更新 App 与匹配的运行时。`:`Update the App and its matching runtime together.`,up_to_date:t?`当前通道暂无更新。`:`No newer update on this channel.`,downloading:t?`正在下载并校验签名…`:`Downloading and verifying signature…`,installing_app:t?`正在安装 App,请保持窗口打开。`:`Installing the App. Keep this window open.`,installing_runtime:t?`正在安装匹配的运行时,请稍候…`:`Installing the matching runtime…`,restart_required:t?`重启后将自动完成运行时安装与服务连接。`:`Restart to finish runtime installation and reconnect services.`,ready:t?`更新完成,服务已就绪。`:`Update completed; services are ready.`,error:tb[s.details?.code??``]?.[+!t]??(t?`更新未完成。请重试;启动失败可尝试修复当前版本。`:`Update incomplete. Retry; repair this version if startup fails.`)},v=h?t?`正在更新…`:`Updating…`:s.phase===`available`?t?`有可用更新`:`Update available`:s.phase===`restart_required`?t?`重启完成更新`:`Restart to finish`:s.phase===`error`?t?`更新需重试`:`Retry update`:t?`更新 LoopX`:`Update LoopX`;return(0,B.jsxs)(`div`,{className:`personal-desktop-update`,children:[(0,B.jsxs)(`button`,{className:`personal-update-trigger`,type:`button`,"aria-expanded":n,"aria-controls":`desktop-update-panel`,onClick:e=>{i.current?.style.setProperty(`bottom`,`${window.innerHeight-e.currentTarget.getBoundingClientRect().top+8}px`),i.current?.togglePopover()},children:[(0,B.jsx)(um,{size:16,"aria-hidden":`true`}),(0,B.jsx)(`span`,{children:v}),(0,B.jsx)(rm,{size:14,"aria-hidden":`true`})]}),(0,B.jsxs)(`section`,{ref:i,popover:`auto`,id:`desktop-update-panel`,className:`personal-update-panel`,"aria-label":t?`LoopX 更新`:`LoopX updates`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:t?`LoopX 更新`:`LoopX updates`}),(0,B.jsx)(`button`,{type:`button`,"aria-label":t?`关闭更新面板`:`Close updates`,onClick:()=>i.current?.hidePopover(),children:(0,B.jsx)($m,{size:16,"aria-hidden":`true`})})]}),(0,B.jsxs)(`small`,{children:[l,` · `,a===`main`?t?`main 预览版`:`main preview`:t?`稳定版`:`Stable`]}),s.details?.version?(0,B.jsxs)(`p`,{children:[t?`目标版本:`:`Target: `,s.details.version]}):null,(0,B.jsxs)(`p`,{role:`status`,"aria-live":`polite`,children:[h?(0,B.jsx)(Im,{className:`is-spinning`,size:14,"aria-hidden":`true`}):null,_[s.phase]]}),s.phase===`downloading`&&s.details?.total?(0,B.jsx)(`progress`,{"aria-label":t?`下载进度`:`Download progress`,max:s.details.total,value:s.details.received??0}):null,m?(0,B.jsx)(`div`,{className:`personal-update-actions`,children:s.phase===`restart_required`?(0,B.jsx)(`button`,{type:`button`,onClick:()=>void g(`restart`),children:t?`重启完成更新`:`Restart to finish`}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`button`,{type:`button`,disabled:h,onClick:()=>void g(`check`),children:t?`检查更新`:`Check for updates`}),s.phase===`available`?(0,B.jsx)(`button`,{type:`button`,onClick:()=>void g(`apply`),children:t?`更新并准备重启`:`Install update`}):null]})}):(0,B.jsx)(`p`,{children:t?`请在 LoopX App 中更新;浏览器自身无需安装包。`:`Update from the LoopX App; the browser needs no installer.`}),(0,B.jsxs)(`details`,{children:[(0,B.jsx)(`summary`,{children:t?`高级选项`:`Advanced options`}),(0,B.jsxs)(`label`,{children:[t?`更新通道`:`Update channel`,(0,B.jsxs)(`select`,{disabled:h||s.phase===`restart_required`,value:a,onChange:e=>{o(e.target.value),c({phase:`idle`})},children:[(0,B.jsx)(`option`,{value:`stable`,children:t?`稳定版(推荐)`:`Stable (recommended)`}),(0,B.jsx)(`option`,{value:`main`,children:t?`main 预览版`:`main preview`})]})]}),(0,B.jsx)(`p`,{children:t?`App 与匹配的 CLI 一起更新,服务可能短暂断开。不删除 Goal 数据。`:`Updates the App and matching CLI. Services may briefly disconnect. Goal data is not deleted.`}),m?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{children:t?`启动失败时,可重装当前 App 随附的运行时。`:`If startup fails, reinstall this App's bundled runtime.`}),(0,B.jsx)(`button`,{disabled:h||s.phase===`restart_required`,type:`button`,onClick:()=>void g(`repair`),children:t?`修复当前版本`:`Repair this version`})]}):null,m&&d?(0,B.jsxs)(`details`,{children:[(0,B.jsx)(`summary`,{children:t?`恢复上个版本`:`Restore previous version`}),(0,B.jsx)(`p`,{children:t?`将恢复已保留的 App 和它的运行时,需要重启。`:`Restore the retained App and its runtime, then restart.`}),(0,B.jsx)(`button`,{disabled:h,type:`button`,onClick:()=>void g(`rollback`),children:t?`确认恢复上版`:`Restore previous version`})]}):null]})]})]})}var ib=e=>`loopx-sidebar-goal-order-v1:${encodeURIComponent(e)}`;function ab(e){try{let t=JSON.parse(e??`null`);return Array.isArray(t)&&t.every(e=>typeof e==`string`)?[...new Set(t)]:[]}catch{return[]}}function ob(e,t){let n=new Map(t.map((e,t)=>[e,t]));return[...e].sort((e,t)=>(n.get(e.goalId)??1/0)-(n.get(t.goalId)??1/0))}function sb(e,t,n,r,i){if(n===r||!t.includes(n)||!t.includes(r))return e;let a=[...new Set([...e,...t])].filter(e=>e!==n);return a.splice(a.indexOf(r)+Number(i),0,n),a}function cb(e,t){let n=ib(t),[r,i]=(0,z.useState)(()=>{try{return ab(localStorage.getItem(n))}catch{return[]}}),[a,o]=(0,z.useState)(!1),[s,c]=(0,z.useState)(null),[l,u]=(0,z.useState)(null),d=(0,z.useRef)(null),f=(0,z.useRef)(!1),p=ob(e,r),m=p.map(e=>e.goalId);function h(t,a,s){let l=sb(r,m,t,a,s);if(l===r)return;i(l);let u=ob(e,l),d=u.findIndex(e=>e.goalId===t),f=u[d];f&&c({title:f.title,position:d+1});try{localStorage.setItem(n,JSON.stringify(l)),o(!1)}catch{o(!0)}}function g(){d.current=null,u(null)}return{sorted:p,target:l,saveFailed:a,lastMoved:s,move:h,moveBy(e,t){let n=p[m.indexOf(e)+t];n&&h(e,n.goalId,t===1)},pointerProps:e=>({onPointerDown(t){f.current=!1,t.pointerType===`mouse`&&t.button===0&&(d.current={id:e,x:t.clientX,y:t.clientY,dragging:!1},t.currentTarget.setPointerCapture(t.pointerId))},onPointerMove(e){let t=d.current;if(!t||!t.dragging&&Math.hypot(e.clientX-t.x,e.clientY-t.y)<6)return;t.dragging=!0,f.current=!0;let n=document.elementFromPoint(e.clientX,e.clientY)?.closest(`[data-reorder-goal]`),r=e.currentTarget.closest(`.personal-goal-list`),i=n?.dataset.reorderGoal;if(!n||!i||!r?.contains(n)||i===t.id){u(null);return}let a=n.getBoundingClientRect();u({id:i,after:e.clientY>a.top+a.height/2})},onPointerUp(){d.current?.dragging&&l&&h(d.current.id,l.id,l.after),g()},onPointerCancel:g,onLostPointerCapture:g,onKeyDown(e){e.key===`Escape`&&g()},onClickCapture(e){f.current&&=(e.preventDefault(),e.stopPropagation(),!1)}})}}var lb=`/ssh-hosts`,ub=/^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;function db(e){return typeof e==`string`&&ub.test(e.trim())}function fb(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`SSH Host 列表响应无效。`);let t=e;if(t.ok!==!0||t.schema_version!==`ssh_host_catalog_v0`||!Array.isArray(t.hosts))throw Error(`SSH Host 列表协议不兼容,请更新本机 LoopX 服务。`);let n=new Set;return{hosts:t.hosts.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=String(e.alias??``).trim();return!db(t)||n.has(t)?[]:(n.add(t),[{alias:t}])}),schemaVersion:`ssh_host_catalog_v0`}}async function pb(e=fetch,t=lb){let n=await e(t,{cache:`no-store`});if(!n.ok)throw Error(`无法读取本机 SSH Host(HTTP ${n.status})。`);return fb(await n.json())}function mb(e,t){let n=e.trim();if(!db(n))return{error:`请选择有效的 SSH Host。`};let r=Number(t);return!Number.isInteger(r)||r<1024||r>65535?{error:`本地端口必须是 1024–65535 之间的整数。`}:{command:`ssh -N -L ${r}:127.0.0.1:8766 ${n}`,hostAlias:n,label:n,statusUrl:`http://127.0.0.1:${r}/status.json`}}var hb=`/api/ssh-source/ensure`,gb=`/api/ssh-source/goal-lifecycle`;async function _b(e,t){let n=await fetch(hb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({host_alias:e,local_port:Number(t)})}),r=await n.json().catch(()=>null);if(!n.ok)throw Error(r?.error??`无法建立 SSH 隧道来源。`);if(!r?.ok)throw Error(`无法建立 SSH 隧道来源。`);return r}async function vb(e,t,n,r,i=fetch){let a=await i(gb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({goal_id:t,host_alias:e,operation:n,reason:r})}),o=await a.json().catch(()=>null);if(!a.ok)throw Error(o?.error??`无法更新远端 Goal 生命周期。`);if(!o?.ok||o.schema_version!==`loopx_remote_goal_lifecycle_v1`||o.goal_id!==t||o.host_alias!==e||o.operation!==n||o.activation_state!==(n===`stop`?`stopped`:`active`)||o.projection_verified!==!0)throw Error(`远端 Goal 生命周期回读未验证。`);return o}function yb({activeSource:e,connectionState:t,errorMessage:n,onAdd:r,onConfiguredHostsLoaded:i,onRemove:a,onSelect:o,sources:s}){let{t:c}=Ji(),[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(null),[p,m]=(0,z.useState)(`configured`),[h,g]=(0,z.useState)([]),[_,v]=(0,z.useState)(null),[y,b]=(0,z.useState)(!1),[x,S]=(0,z.useState)(!1),[C,w]=(0,z.useState)(``),[T,E]=(0,z.useState)(``),[D,O]=(0,z.useState)(`8876`),[ee,te]=(0,z.useState)(``),ne=`configured:`,k=[...s.map(e=>({label:e.label,value:e.id})),...h.filter(e=>!s.some(t=>t.label===e.alias)).map(e=>({group:c(`source.configuredGroup`,{count:h.length}),label:e.alias,value:`${ne}${e.alias}`}))],A=(0,z.useMemo)(()=>h.some(e=>e.alias===C)?mb(C,D):{error:c(`source.selectHost`)},[h,C,D,c]);(0,z.useEffect)(()=>{j()},[]);async function j(){b(!0),v(null);try{let e=await pb();g(e.hosts),i?.(e.hosts.map(e=>e.alias)),w(t=>t||e.hosts[0]?.alias||``),e.hosts.length||v(c(`source.hostEmpty`))}catch(e){v(e instanceof Error?e.message:c(`source.hostLoadError`))}finally{b(!1)}}function M(){u(!0),m(`configured`),f(null),j()}function N(){u(!1),m(`configured`),v(null),S(!1),w(``),f(null),E(``),O(`8876`),te(``)}function P(){let e=r({label:T,statusUrl:ee});if(e.error){f(e.error);return}N()}function F(){if(`error`in A){f(A.error??c(`source.invalid`));return}let e=r({ensureTunnel:!0,hostAlias:A.hostAlias,label:A.label,statusUrl:A.statusUrl});if(e.error){f(e.error);return}N()}function re(e){let t=new Set;for(let e of s)try{t.add(new URL(e.statusUrl).port)}catch{}let n=`8877`;for(let e=8877;e<9077;e+=1)if(!t.has(String(e))){n=String(e);break}let i=mb(e,n);if(`error`in i){f(i.error??c(`source.invalid`));return}let a=r({ensureTunnel:!0,hostAlias:i.hostAlias,label:i.label,statusUrl:i.statusUrl});a.error?f(a.error):f(null),O(n)}async function ie(){if(`error`in A){f(A.error??c(`source.invalid`));return}try{await navigator.clipboard.writeText(A.command),S(!0),f(null)}catch{f(c(`source.copyError`))}}return(0,B.jsxs)(`section`,{"aria-label":c(`source.controlPlane`),className:`personal-status-source`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`span`,{children:`Control plane`}),(0,B.jsx)(`button`,{"aria-label":c(`source.addSsh`),onClick:M,title:c(`source.add`),type:`button`,children:(0,B.jsx)(Pm,{size:14})})]}),(0,B.jsx)(Cy,{ariaLabel:c(`source.select`),className:`personal-status-source-select`,icon:(0,B.jsx)(Hm,{size:15}),onChange:e=>{if(e.startsWith(ne)){re(e.slice(11));return}o(e)},options:k,value:e.id}),(0,B.jsxs)(`div`,{className:`personal-status-source-meta`,children:[(0,B.jsxs)(`span`,{className:`is-${t}`,children:[(0,B.jsx)(`i`,{}),c(t===`loading`?`source.connecting`:t===`error`?`source.notAvailable`:`source.connected`)]}),(0,B.jsx)(`small`,{children:e.readOnly?c(`source.readOnly`):c(`source.localInteractive`)}),e.kind===`ssh_tunnel`?(0,B.jsx)(`button`,{"aria-label":c(`source.remove`,{source:e.label}),onClick:()=>a(e.id),title:c(`source.removeCurrent`),type:`button`,children:(0,B.jsx)(Xm,{size:12})}):null]}),n?(0,B.jsx)(`p`,{className:`personal-status-source-error`,role:`alert`,children:n}):null,l?(0,B.jsxs)(`div`,{className:`personal-status-source-form`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:c(`source.addSsh`)}),(0,B.jsx)(`button`,{"aria-label":c(`source.closeForm`),onClick:N,type:`button`,children:(0,B.jsx)($m,{size:13})})]}),(0,B.jsxs)(`div`,{"aria-label":c(`source.addMethod`),className:`personal-status-source-modes`,role:`tablist`,children:[(0,B.jsx)(`button`,{"aria-selected":p===`configured`,onClick:()=>{m(`configured`),f(null)},role:`tab`,type:`button`,children:c(`source.configured`)}),(0,B.jsx)(`button`,{"aria-selected":p===`manual`,onClick:()=>{m(`manual`),f(null)},role:`tab`,type:`button`,children:c(`source.manual`)})]}),p===`configured`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.configuredCount`,{count:h.length})}),(0,B.jsxs)(`span`,{className:`personal-status-source-field-row`,children:[(0,B.jsx)(`input`,{"aria-label":c(`source.host`),disabled:y||!h.length,list:`loopx-configured-ssh-hosts`,onChange:e=>{w(e.target.value),S(!1)},placeholder:c(y?`source.loadingHosts`:`source.hostPlaceholder`),value:C}),(0,B.jsx)(`datalist`,{id:`loopx-configured-ssh-hosts`,children:h.map(e=>(0,B.jsx)(`option`,{value:e.alias},e.alias))}),(0,B.jsx)(`button`,{"aria-label":c(`source.refreshHosts`),disabled:y,onClick:()=>void j(),title:c(`source.refreshHosts`),type:`button`,children:(0,B.jsx)(Rm,{size:13})})]})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.localPort`)}),(0,B.jsx)(`input`,{"aria-label":c(`source.localPort`),inputMode:`numeric`,onChange:e=>{O(e.target.value),S(!1)},value:D})]}),(0,B.jsxs)(`div`,{className:`personal-status-source-command`,children:[(0,B.jsx)(`code`,{children:`error`in A?c(`source.tunnelCommandPending`):A.command}),(0,B.jsxs)(`button`,{"aria-label":c(`source.copyCommand`),disabled:`error`in A,onClick:()=>void ie(),type:`button`,children:[(0,B.jsx)(cm,{size:12}),c(x?`source.copied`:`source.copy`)]})]}),_?(0,B.jsx)(`p`,{className:`is-error`,children:_}):null,(0,B.jsx)(`p`,{children:c(`source.description`)}),(0,B.jsx)(`button`,{className:`personal-status-source-add`,disabled:`error`in A,onClick:F,type:`button`,children:c(`source.addConfigured`)})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.name`)}),(0,B.jsx)(`input`,{autoFocus:!0,maxLength:48,onChange:e=>E(e.target.value),placeholder:c(`source.namePlaceholder`),value:T})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.statusUrl`)}),(0,B.jsx)(`input`,{onChange:e=>te(e.target.value),placeholder:`http://127.0.0.1:8876/status.json`,value:ee})]}),(0,B.jsx)(`p`,{children:(0,B.jsx)(`code`,{children:`ssh -N -L 8876:127.0.0.1:8766 `})}),(0,B.jsx)(`p`,{children:c(`source.manualDescription`)}),(0,B.jsx)(`button`,{className:`personal-status-source-add`,onClick:P,type:`button`,children:c(`source.addConfigured`)})]}),d?(0,B.jsx)(`p`,{className:`is-error`,role:`alert`,children:d}):null]}):null]})}var bb={需修复:`is-danger`,等你:`is-warning`,等待条件:`is-info`,推进中:`is-success`,安静运行:`is-quiet`,已完成:`is-quiet`,已停止:`is-stopped`};function xb({attentionCount:e,goals:t,goalArchiveLoadState:n={error:null,phase:`ready`},lifecycleBusyGoalIds:r,goalLifecycleOperations:i,onRequestGoalCreate:a,onOpenSettings:o,onRetryGoalArchive:s,onRequestGoalLifecycle:c,onSelectGoal:l,selectedGoalId:u,statusSourceControl:d}){let{locale:f,t:p}=Ji(),[m,h]=(0,z.useState)(!1),g=cb(t.filter(e=>e.activationState!==`stopped`),d?.activeSource.statusUrl??`/status.json`),_=g.sorted,v=t.filter(e=>e.activationState===`stopped`),y=e=>!!c&&(!i||i.includes(e)),b=(e,t)=>(0,B.jsxs)(`div`,{className:`personal-goal-row${g.target?.id===e.goalId?g.target.after?` is-drop-after`:` is-drop-before`:``}`,"data-reorder-goal":t?void 0:e.goalId,"data-load-error":e.loadError,children:[(0,B.jsxs)(`button`,{...t?{}:g.pointerProps(e.goalId),title:t?void 0:p(`sidebar.dragGoal`),"aria-current":u===e.goalId?`page`:void 0,className:`personal-goal-link`,onClick:()=>l(e.goalId),type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-goal-state-dot ${e.loadState?``:bb[e.state]}`}),(0,B.jsxs)(`span`,{className:`personal-goal-link-copy`,children:[(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsxs)(`small`,{children:[e.loadState&&(!t||u===e.goalId)?p(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Yi(e.state,f),e.needsYou&&!t?` · ${p(`home.lane.needsYou`)}`:``]})]}),(0,B.jsx)(nm,{size:15})]}),!t&&m?(0,B.jsxs)(`div`,{className:`personal-goal-move-actions`,children:[(0,B.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveUp`,{goal:e.title}),disabled:_[0]?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,-1),children:(0,B.jsx)(Jp,{"aria-hidden":`true`,size:13})}),(0,B.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveDown`,{goal:e.title}),disabled:_.at(-1)?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,1),children:(0,B.jsx)(Wp,{"aria-hidden":`true`,size:13})})]}):null,c&&y(t?`resume`:`stop`)?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`button`,{"aria-label":`${p(t?`sidebar.resume`:`sidebar.stop`)} ${e.title}`,"aria-busy":r?.has(e.goalId)||void 0,className:`personal-goal-lifecycle${r?.has(e.goalId)?` is-pending`:``}`,disabled:r?.has(e.goalId),onClick:()=>c(e,t?`resume`:`stop`),title:p(t?`sidebar.resumeGoal`:`sidebar.stopGoal`),type:`button`,children:r?.has(e.goalId)?(0,B.jsx)(Cm,{size:13}):t?(0,B.jsx)(Lm,{size:13}):(0,B.jsx)(Mm,{size:13})}),t&&y(`delete`)?(0,B.jsx)(`button`,{"aria-label":`${p(`sidebar.delete`)} ${e.title}`,className:`personal-goal-lifecycle personal-goal-delete`,onClick:()=>c(e,`delete`),title:p(`sidebar.deleteGoal`),type:`button`,children:(0,B.jsx)(Xm,{size:13})}):null]}):null]},e.goalId);return(0,B.jsxs)(`div`,{className:`personal-goal-directory`,children:[(0,B.jsxs)(`div`,{className:`personal-sidebar-brand`,children:[(0,B.jsx)(`span`,{className:`personal-brand-mark`,children:(0,B.jsx)(Zp,{size:18})}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:`LoopX`})})]}),d?(0,B.jsx)(yb,{...d}):null,(0,B.jsxs)(`nav`,{"aria-label":p(`home.workspace`),className:`personal-sidebar-nav`,children:[(0,B.jsxs)(`button`,{"aria-current":u===null?`page`:void 0,className:`personal-manager-link`,onClick:()=>l(null),type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-manager-icon`,children:(0,B.jsx)(Zp,{size:17})}),(0,B.jsx)(`span`,{children:p(`sidebar.manager`)}),e>0?(0,B.jsx)(`span`,{className:`personal-sidebar-count`,children:e}):null,(0,B.jsx)(nm,{size:15})]}),(0,B.jsxs)(`div`,{className:`personal-sidebar-section-title`,children:[(0,B.jsx)(`span`,{children:`Goals`}),(0,B.jsxs)(`span`,{className:`personal-sidebar-title-actions`,children:[(0,B.jsx)(`small`,{children:_.length}),(0,B.jsx)(`button`,{"aria-label":p(`sidebar.sortGoals`),title:p(`sidebar.sortGoals`),"aria-pressed":m,onClick:()=>h(!m),type:`button`,children:(0,B.jsx)(qp,{"aria-hidden":`true`,size:15})}),a?(0,B.jsx)(`button`,{"aria-label":p(`sidebar.createGoal`),onClick:a,type:`button`,children:(0,B.jsx)(Pm,{size:15})}):null]})]}),g.saveFailed?(0,B.jsx)(`p`,{role:`status`,children:p(`sidebar.orderNotSaved`)}):null,(0,B.jsx)(`span`,{className:`personal-sr-only`,role:`status`,children:g.lastMoved?p(`sidebar.goalMoved`,{goal:g.lastMoved.title,position:g.lastMoved.position}):``}),(0,B.jsx)(`div`,{className:`personal-goal-list`,children:_.map(e=>b(e,!1))}),v.length||n.phase===`loading`||n.phase===`error`?(0,B.jsxs)(`details`,{className:`personal-stopped-goals`,open:n.phase===`error`||void 0,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(tm,{size:13}),(0,B.jsx)(`span`,{children:p(`sidebar.stopped`)}),n.phase===`loading`?(0,B.jsx)(Cm,{"aria-label":p(`sidebar.stoppedLoading`),className:`is-spinning`,size:13}):(0,B.jsx)(`small`,{children:v.length})]}),(0,B.jsxs)(`div`,{className:`personal-goal-list is-stopped`,children:[n.phase===`error`?(0,B.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`alert`,children:[(0,B.jsx)(`span`,{children:p(`sidebar.stoppedLoadFailed`)}),s?(0,B.jsx)(`button`,{onClick:s,type:`button`,children:p(`sidebar.retryStopped`)}):null]}):null,v.map(e=>b(e,!0))]})]}):null]}),(0,B.jsxs)(`div`,{className:`personal-sidebar-footer`,children:[(0,B.jsx)(rb,{}),o?(0,B.jsxs)(`button`,{"aria-label":p(`settings.open`),className:`personal-sidebar-utility`,onClick:o,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-sidebar-utility-icon`,children:(0,B.jsx)(Um,{size:17})}),(0,B.jsx)(`span`,{className:`personal-sidebar-utility-copy`,children:(0,B.jsx)(`strong`,{children:p(`settings.open`)})}),(0,B.jsx)(nm,{"aria-hidden":`true`,size:15})]}):null]})]})}var Sb=J({ok:X(!0),total:G().int().nonnegative(),next_cursor:W().nullable(),items:q(J({todo_id:W(),text:W(),claimed_by:W().nullable(),evidence:W().nullable(),priority:W().nullable(),task_class:W().nullable()})).max(40)});function Cb({goal:e,agentId:t,seed:n,enabled:r,listView:i=!1,onSelect:a}){let{t:o}=Ji(),s=(0,z.useId)(),[c,l]=(0,z.useState)(!1),u=!i||c,d=i?96:148,[f,p]=(0,z.useState)(n),[m,h]=(0,z.useState)(t===`all`?e.doneTodoCount??n.length:n.length),[g,_]=(0,z.useState)(void 0),[v,y]=(0,z.useState)(!1),[b,x]=(0,z.useState)(!1),[S,C]=(0,z.useState)(!1),[w,T]=(0,z.useState)({top:0,height:600}),[E,D]=(0,z.useState)(null),O=(0,z.useRef)(null),ee=(0,z.useRef)(null),[te,ne]=(0,z.useState)(0);(0,z.useEffect)(()=>{let e=O.current;if(!e)return;let t=new ResizeObserver(()=>T({top:e.scrollTop,height:e.clientHeight}));return t.observe(e),()=>{t.disconnect(),ee.current?.abort()}},[]);let k=g===void 0||w.top+w.height>=f.length*d-d*2;(0,z.useEffect)(()=>{if(!r||!u||!k||g===null||b||ee.current)return;let n=new AbortController;ee.current=n,y(!0);let i=new URLSearchParams({goal_id:e.goalId});t!==`all`&&i.set(`agent_id`,t),g&&i.set(`cursor`,g),fetch(`/api/chat/completed-todos?${i}`,{signal:n.signal}).then(async e=>{if(e.status===409&&C(!0),!e.ok)throw Error(`history unavailable`);let t=Sb.parse(await e.json());if(n.signal.aborted)return;let r=t.items.map(e=>({todoId:e.todo_id,text:e.text,claimedBy:e.claimed_by,evidence:e.evidence,priority:e.priority,taskClass:e.task_class,done:!0,status:`done`}));p(e=>g===void 0?r:[...e,...r.filter(t=>!e.some(e=>e.todoId===t.todoId))]),h(t.total),_(t.next_cursor)}).catch(()=>{n.signal.aborted||x(!0)}).finally(()=>{n.signal.aborted||(ee.current=null,y(!1))})},[r,u,k,g,b,te,e.goalId,t,v]),(0,z.useEffect)(()=>{O.current&&(O.current.scrollTop=0),T({top:0,height:O.current?.clientHeight??600}),D(null)},[i]);let A=Math.max(0,Math.floor(w.top/d)-3),j=Math.min(f.length,Math.ceil((w.top+w.height)/d)+3),M=Array.from({length:Math.max(0,j-A)},(e,t)=>A+t);return E!==null&&El(e=>!e),children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,children:c?`▾`:`▸`}),` `,o(`tasks.completed`)]}):(0,B.jsxs)(`strong`,{children:[(0,B.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-done`}),o(`tasks.completed`)]}),(0,B.jsx)(`span`,{children:m})]}),(0,B.jsxs)(`div`,{id:s,hidden:!u,"aria-label":o(`tasks.completed`),className:`personal-task-lane-scroll`,ref:O,role:`region`,tabIndex:0,onScroll:e=>T({top:e.currentTarget.scrollTop,height:e.currentTarget.clientHeight}),children:[(0,B.jsx)(`div`,{className:`personal-completed-window`,style:{height:f.length*d},children:M.map(t=>{let n=f[t];return(0,B.jsx)(`div`,{className:`personal-task-card personal-completed-row`,style:{top:t*d,height:d},children:(0,B.jsxs)(`button`,{type:`button`,onFocus:()=>D(t),onBlur:()=>D(null),onClick:()=>a({kind:`todo`,item:{...n,goalId:e.goalId,goalTitle:e.title,ownerLabel:n.claimedBy??e.agentLabel??e.agentId}}),children:[(0,B.jsx)(`span`,{className:`is-done`,children:`✓`}),(0,B.jsx)(`strong`,{children:n.text}),(0,B.jsx)(`small`,{children:n.claimedBy??e.agentLabel??e.agentId})]})},n.todoId)})}),(0,B.jsx)(`div`,{className:`personal-completed-footer`,role:`status`,children:v?o(`tasks.historyLoading`):b?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`span`,{children:o(S?`tasks.historyExpired`:`tasks.historyError`)}),(0,B.jsx)(`button`,{type:`button`,onClick:()=>{S&&(_(void 0),O.current&&(O.current.scrollTop=0)),C(!1),x(!1),ne(e=>e+1)},children:o(`tasks.historyRetry`)})]}):r?g===null?o(`tasks.historyEnd`):(0,B.jsx)(`button`,{type:`button`,onClick:()=>{O.current&&(O.current.scrollTop=f.length*d)},children:o(`tasks.historyMore`)}):o(`tasks.historyLocalOnly`)})]})]})}function wb({children:e,count:t,label:n,tone:r,listView:i=!1}){let a=(0,z.useId)(),o=(0,z.useRef)(null),s=(0,z.useRef)([]),c=(0,z.useRef)(null),[l,u]=(0,z.useState)({after:!1,before:!1}),d=(0,z.useCallback)(()=>{let e=o.current;if(!e)return;let t={after:Math.max(0,e.scrollHeight-e.clientHeight)-e.scrollTop>1,before:e.scrollTop>1};u(e=>e.after===t.after&&e.before===t.before?e:t)},[]);return(0,z.useEffect)(()=>{let e=o.current;if(!e)return;let t=new ResizeObserver(d);return c.current=t,t.observe(e),e.addEventListener(`scroll`,d,{passive:!0}),d(),()=>{t.disconnect(),c.current=null,s.current=[],e.removeEventListener(`scroll`,d)}},[i,d]),(0,z.useEffect)(()=>{let e=o.current,t=c.current;if(!e||!t)return;for(let e of s.current)t.unobserve(e);let n=Array.from(e.children).filter(e=>e instanceof HTMLElement);for(let e of n)t.observe(e);s.current=n,d()},[e,t,i,d]),i?!t&&r!==`done`?null:(0,B.jsxs)(`details`,{className:`personal-task-group tone-${r}`,open:!0,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(tm,{size:16}),(0,B.jsx)(`strong`,{children:n}),(0,B.jsx)(`span`,{children:t})]}),(0,B.jsx)(`div`,{className:`personal-task-list-rows`,children:e})]}):(0,B.jsxs)(`section`,{className:`personal-object-list personal-task-lane`,children:[(0,B.jsxs)(`header`,{id:a,children:[(0,B.jsxs)(`strong`,{children:[(0,B.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-${r}`}),n]}),(0,B.jsx)(`span`,{children:t})]}),(0,B.jsx)(`div`,{"aria-labelledby":a,className:`personal-task-lane-scroll${l.before?` has-overflow-before`:``}${l.after?` has-overflow-after`:``}`,ref:o,role:`region`,tabIndex:t>0?0:-1,children:e})]})}function Tb({historyEnabled:e=!1,goal:t,items:n,onDraftTaskFromMessage:r,onOpenChat:i,onQuickComplete:a,quickCompletingTodoIds:o,onSelect:s,selectedTodoId:c=null,userTodos:l}){let{t:u}=Ji(),[d,f]=(0,z.useState)(!1),[p,m]=(0,z.useState)({goalId:``,laneId:`all`}),h=(0,z.useRef)(null);(0,z.useEffect)(()=>{if(!c)return;let e=window.requestAnimationFrame(()=>h.current?.scrollIntoView({block:`nearest`,inline:`nearest`}));return()=>window.cancelAnimationFrame(e)},[c]);let g=l.filter(e=>e.goalId===t.goalId).map(e=>({...e,goalTitle:t.title})),_=e=>e.priority===`P0`?0:e.priority===`P1`?1:e.priority===`P2`?2:3,v=(0,z.useMemo)(()=>{let e=new Map((t.agentLanes??[]).map(e=>[e.agentId,e]));for(let n of t.agentTodos)n.claimedBy&&!e.has(n.claimedBy)&&e.set(n.claimedBy,{agentId:n.claimedBy,label:n.claimedBy});return[...e.values()]},[t.agentLanes,t.agentTodos]),y=p.goalId===t.goalId&&v.some(e=>e.agentId===p.laneId)?p.laneId:`all`,b=e=>y===`all`||e===y,x=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&!e.done).filter(e=>b(e.claimedBy)).sort((e,t)=>_(e)-_(t)),S=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&e.done).filter(e=>b(e.claimedBy)),C=n.filter(e=>e.kind===`schedule`&&b(e.schedule.agentId)),w=n.filter(e=>e.kind===`run`&&!!e.run.todoId&&b(e.run.agentId)),T=!g.length&&!x.length&&!S.length&&!C.length,E=n.filter(e=>e.kind===`message`&&(e.message.role===`user`||e.message.role===`assistant`)),D=E.reduce((e,t,n)=>t.message.role===`user`?n:e,-1),O=D>=0?E[D]?.message:null,ee=D>=0?E.slice(D+1).reverse().find(e=>e.message.role===`assistant`)?.message:null,te=D>=0&&E.slice(D+1).some(e=>e.message.role===`assistant`&&e.message.pending);return(0,B.jsxs)(`section`,{"aria-label":u(`header.tasks`),className:`personal-task-board${d?` is-list-view`:``}`,children:[(0,B.jsxs)(`header`,{className:`personal-task-view-toolbar`,children:[(0,B.jsx)(`div`,{children:(0,B.jsx)(`strong`,{children:u(`header.tasks`)})}),(0,B.jsxs)(`div`,{className:`personal-task-view-switch`,role:`group`,"aria-label":u(`tasks.viewLabel`),children:[(0,B.jsx)(`button`,{type:`button`,"aria-pressed":d,onClick:()=>f(!0),children:u(`tasks.listView`)}),(0,B.jsx)(`button`,{type:`button`,"aria-pressed":!d,onClick:()=>f(!1),children:u(`tasks.boardView`)})]})]}),v.length>1?(0,B.jsxs)(`section`,{"aria-label":u(`tasks.agentLaneFilter`),className:`personal-task-lane-filter`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(Zp,{size:15}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:u(`tasks.agentLane`)})})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{className:`sr-only`,children:u(`tasks.agentLaneFilter`)}),(0,B.jsxs)(`select`,{"aria-label":u(`tasks.agentLaneFilter`),onChange:e=>m({goalId:t.goalId,laneId:e.target.value}),value:y,children:[(0,B.jsx)(`option`,{value:`all`,children:u(`tasks.allAgentLanes`,{count:v.length})}),v.map(e=>(0,B.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))]}),(0,B.jsx)(tm,{"aria-hidden":!0,size:14})]})]}):null,O?(0,B.jsxs)(`section`,{"aria-label":u(`tasks.chatRecent`),className:`personal-task-chat-receipt`,children:[(0,B.jsx)(`span`,{className:`personal-task-chat-icon`,children:(0,B.jsx)(Dm,{size:18})}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:u(te?`tasks.chatPending`:ee?`tasks.chatAgentReplied`:`tasks.chatRecent`)}),(0,B.jsx)(`small`,{children:t.agentLabel??t.agentId})]}),(0,B.jsxs)(`p`,{className:`is-user`,children:[(0,B.jsx)(`b`,{children:u(`common.you`)}),O.text]}),ee&&!ee.pending?(0,B.jsxs)(`p`,{className:`is-assistant`,children:[(0,B.jsx)(`b`,{children:u(`common.agent`)}),ee.text]}):null,(0,B.jsx)(`small`,{children:u(te?`tasks.chatPendingDescription`:`tasks.chatUnchangedDescription`)})]}),(0,B.jsxs)(`footer`,{children:[(0,B.jsxs)(`button`,{onClick:i,type:`button`,children:[(0,B.jsx)(Dm,{size:14}),u(`tasks.chatViewReply`)]}),ee&&!te&&r?(0,B.jsxs)(`button`,{onClick:()=>r(ee.text),type:`button`,children:[(0,B.jsx)(Sm,{size:14}),u(`tasks.convertToTask`)]}):null]})]}):null,(0,B.jsxs)(`div`,{className:d?`personal-task-grouped-list`:`personal-task-kanban`,children:[(0,B.jsxs)(wb,{listView:d,count:g.length,label:u(`timeline.waitingConfirmation`),tone:`attention`,children:[g.map(e=>{let t=Zi(e.updatedAt,u);return(0,B.jsxs)(`button`,{onClick:()=>s({item:e,kind:`attention`}),type:`button`,children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,className:`is-attention`,children:`!`}),(0,B.jsx)(`strong`,{children:e.text}),(0,B.jsxs)(`small`,{children:[(0,B.jsx)(`span`,{className:`personal-row-status ${e.blocking?`is-blocking`:`is-pending`}`,children:e.blocking?u(`tasks.blocked`):u(`tasks.pending`)}),t?(0,B.jsx)(`span`,{className:`personal-task-age`,children:u(`tasks.waitingAge`,{age:t})}):null]})]},e.todoId)}),g.length?null:(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyConfirm`)})]}),(0,B.jsxs)(wb,{listView:d,count:x.length,label:u(`tasks.pendingAndRunning`),tone:`progress`,children:[x.map(e=>{let n={...e,goalId:t.goalId,goalTitle:t.title,ownerLabel:e.claimedBy??t.agentLabel??t.agentId},r=w.find(t=>t.run.todoId===e.todoId)?.run;return(0,B.jsxs)(`div`,{className:`personal-task-card${r?` has-session`:``}${c===e.todoId?` is-selected`:``}`,ref:c===e.todoId?e=>{h.current=e}:void 0,children:[(0,B.jsxs)(`button`,{"aria-pressed":c===e.todoId,onClick:()=>s({item:n,kind:`todo`}),type:`button`,children:[(0,B.jsx)(`span`,{children:`○`}),(0,B.jsx)(`strong`,{children:e.text}),(0,B.jsxs)(`small`,{children:[e.priority?(0,B.jsx)(`span`,{className:`personal-priority-badge is-${e.priority.toLowerCase()}`,children:e.priority}):null,e.status===`blocked`?(0,B.jsx)(`span`,{className:`personal-priority-badge is-blocked`,children:u(`tasks.blocked`)}):null,r?(0,B.jsx)(`span`,{className:`personal-task-session-status`,children:r.status===`running`||r.status===`queued`?u(`runs.running`):r.status===`failed`?u(`tasks.sessionError`):u(`common.waiting`)}):null,e.status===`deferred`?(0,B.jsx)(`span`,{className:`personal-task-session-status`,children:u(`drawer.taskStatusDeferred`)}):r?null:(0,B.jsx)(`span`,{className:`personal-task-session-status`,children:u(`tasks.waiting`)}),e.claimedBy??t.agentLabel??t.agentId]})]}),(0,B.jsxs)(`div`,{className:`personal-task-card-actions`,children:[r?(0,B.jsxs)(`button`,{className:`personal-task-session-link`,"aria-label":u(`tasks.openExecution`,{name:e.text}),onClick:()=>s({item:r,kind:`run`}),title:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`),type:`button`,children:[(0,B.jsx)(fm,{size:14}),(0,B.jsx)(`span`,{children:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`)})]}):null,a?(0,B.jsx)(`button`,{"aria-busy":o?.has(e.todoId)||void 0,"aria-label":u(`tasks.markComplete`,{name:e.text}),disabled:o?.has(e.todoId),onClick:()=>void a(n),title:u(`tasks.completed`),type:`button`,children:o?.has(e.todoId)?(0,B.jsx)(Cm,{className:`personal-spin`,size:14}):(0,B.jsx)(em,{size:14})}):null,(0,B.jsx)(`button`,{"aria-label":u(`tasks.moreActions`,{name:e.text}),onClick:()=>s({item:n,kind:`todo`}),title:u(`common.actions`),type:`button`,children:(0,B.jsx)(dm,{size:14})})]})]},e.todoId)}),x.length?null:(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyRunning`)})]}),(0,B.jsxs)(wb,{listView:d,count:C.length,label:u(`tasks.scheduled`),tone:`schedule`,children:[C.map(e=>(0,B.jsxs)(`button`,{onClick:()=>s({item:e.schedule,kind:`schedule`}),type:`button`,children:[(0,B.jsx)(`span`,{children:`◷`}),(0,B.jsx)(`strong`,{children:e.schedule.label}),(0,B.jsx)(`small`,{children:e.schedule.status===`paused`?u(`schedule.paused`):u(`schedule.active`)})]},e.id)),C.length?null:(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptySchedules`)})]}),(0,B.jsx)(Cb,{goal:t,agentId:y,seed:S,enabled:e,listView:d,onSelect:s},`${t.goalId}:${y}:${e}`)]}),T?(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyGoal`)}):null]})}function Eb(e,t){return{live_steering:{label:t(`lark.ingressSteering`),detail:t(`lark.ingressSteeringDescription`)},session_queue:{label:t(`lark.ingressQueue`),detail:t(`lark.ingressQueueDescription`)},async_inbox:{label:t(`lark.ingressAsync`),detail:t(`lark.ingressAsyncDescription`)},direct_session:{label:t(`lark.ingressLegacy`),detail:t(`lark.ingressLegacyDescription`)}}[e]}function Db(e,t){return e.listener_status===`starting`?{label:t(`lark.health.starting`),detail:t(`lark.health.startingDetail`),state:`not_ready`}:e.listener_status===`retrying`&&e.listener_error_code===`lark_event_source_disconnected`?{label:t(`lark.health.sourceDisconnected`),detail:t(`lark.health.sourceDisconnectedDetail`),state:`not_ready`}:e.listener_status===`retrying`?{label:t(`lark.health.retrying`),detail:t(`lark.health.retryingDetail`),state:`not_ready`}:e.listener_status===`stopped`||e.listener_status===null?{label:t(`lark.health.notStarted`),detail:t(`lark.health.notStartedDetail`),state:`not_ready`}:e.last_event_status===`message_context_permission_required`?{label:t(`lark.health.messageContextPermission`),detail:t(`lark.health.messageContextPermissionDetail`),state:`not_ready`}:e.last_event_status===`processing_failed`?{label:t(`lark.health.processingFailed`),detail:t(`lark.health.processingFailedDetail`),state:`not_ready`}:e.health_error_code===`invalid_routing_state`?{label:t(`lark.health.invalidRouting`),detail:t(`lark.health.invalidRoutingDetail`),state:`not_ready`}:e.last_event_status===`queued_for_agent`?{label:t(`lark.health.queued`),detail:t(`lark.health.queuedDetail`,{agent:e.agent_id??t(`lark.targetAgent`)}),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`not_addressed`?{label:t(`lark.health.notAddressed`),detail:t(`lark.health.notAddressedDetail`),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`self_message`?{label:t(`lark.health.listening`),detail:t(`lark.health.ignoredSelf`),state:`ready`}:e.health_error_code===`lark_event_route_mismatch`||[`chat_mismatch`,`topic_mismatch`,`route_ambiguous`].includes(e.last_event_reason??``)?{label:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguous`):t(`lark.health.routeMismatch`),detail:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguousDetail`):t(`lark.health.routeMismatchDetail`),state:`not_ready`}:[`invalid_event`,`binding_unavailable`].includes(e.last_event_reason??``)?{label:t(`lark.health.routeUnavailable`),detail:t(`lark.health.routeUnavailableDetail`),state:`not_ready`}:e.last_event_status===`replied_and_acknowledged`?{label:t(`lark.health.listening`),detail:t(`lark.health.eventProcessed`,{events:e.event_count,replies:e.replied_count}),state:`ready`}:e.health_error_code===`lark_event_delivery_unverified`||e.event_count===0?{label:t(`lark.health.eventUnverified`),detail:t(`lark.health.eventUnverifiedDetail`),state:`unverified`}:{label:e.reply_ready?t(`lark.health.listening`):t(`lark.health.unavailable`),detail:t(`lark.health.lastStatus`,{status:e.last_event_status??t(`lark.health.waiting`)}),state:e.reply_ready?`ready`:`not_ready`}}function Ob(e){return e.history_permission_guidance?.api_document_url??null}function kb(e,t,n){if(e instanceof Th){let t=String(e.payload.error_code??``);return{lark_cli_not_installed:n(`lark.error.cliMissing`),lark_cli_not_executable:n(`lark.error.cliExecutable`),lark_cli_start_failed:n(`lark.error.cliStart`),lark_message_permissions_required:n(`lark.error.messagePermissions`),lark_app_required:n(`lark.error.appRequired`),invalid_lark_app:n(`lark.error.invalidApp`),lark_group_lookup_failed:n(`lark.error.groupLookup`),provider_api_failed:n(`lark.error.provider`)}[t]??e.message}return e instanceof Error?e.message:t}function Ab({embedded:e=!1,focusGoalConnection:t=!1,goals:n,initialGoalId:r,onChanged:i,onClose:a}){let{t:o}=Ji(),[s,c]=(0,z.useState)(`connections`),[l,u]=(0,z.useState)([]),[d,f]=(0,z.useState)([]),[p,m]=(0,z.useState)(!0),[h,g]=(0,z.useState)(null),[_,v]=(0,z.useState)(``),[y,b]=(0,z.useState)(t),[x,S]=(0,z.useState)(``),[C,w]=(0,z.useState)(r??n[0]?.goalId??``),[T,E]=(0,z.useState)(``),[D,O]=(0,z.useState)([]),[ee,te]=(0,z.useState)(``),[ne,k]=(0,z.useState)(!1),[A,j]=(0,z.useState)(null),[M,N]=(0,z.useState)(`addressed_only`),[P,F]=(0,z.useState)(t&&r?`goal`:`manager`),[re,ie]=(0,z.useState)(`async_inbox`),[I,ae]=(0,z.useState)(`topic_reply`),[L,oe]=(0,z.useState)(``),[se,ce]=(0,z.useState)(!1),[le,ue]=(0,z.useState)({}),[de,fe]=(0,z.useState)(!1),[pe,me]=(0,z.useState)(null),[he,ge]=(0,z.useState)(null),[_e,ve]=(0,z.useState)(null),[ye,be]=(0,z.useState)(null),[xe,Se]=(0,z.useState)(!1),[Ce,we]=(0,z.useState)(`loopx-workspace-bot`),[Te,Ee]=(0,z.useState)(`feishu`),[R,De]=(0,z.useState)(null),[Oe,ke]=(0,z.useState)(!1),[Ae,je]=(0,z.useState)(null),Me=(0,z.useRef)(null),Ne=(0,z.useRef)(null),Pe=(0,z.useRef)(!1);async function Fe(){m(!0),g(null);try{let[e,t]=await Promise.all([Rg(),qg()]);u(e),f(t),S(t=>t||e.find(e=>e.reply_ready)?.app_ref||e.find(e=>e.ready)?.app_ref||e[0]?.app_ref||``)}catch(e){g(kb(e,o(`lark.error.configuration`),o))}finally{m(!1)}}(0,z.useEffect)(()=>{Fe()},[]),(0,z.useEffect)(()=>{if(!t||p||Pe.current||!r)return;Pe.current=!0;let e=d.find(e=>e.goal_id===r);e?Je(e):qe(n.find(e=>e.goalId===r))},[d,t,n,r,p]),(0,z.useEffect)(()=>{if(!y||!x||_e){O([]),te(``),k(!1),j(null);return}let e=!1;k(!0),j(null);let t=window.setTimeout(()=>{Gg(x,T).then(t=>{e||(O(t),te(e=>t.some(t=>t.chat_id===e)?e:t[0]?.chat_id??``))}).catch(t=>{e||(O([]),te(``),j(kb(t,o(`lark.error.groupLoad`),o)))}).finally(()=>{e||k(!1)})},180);return()=>{e=!0,window.clearTimeout(t)}},[x,T,y,_e]),(0,z.useEffect)(()=>{if(!xe||!R||[`ready`,`failed`,`cancelled`].includes(R.status))return;let e=!1,t=window.setTimeout(()=>{Vg(R.setup_id).then(async t=>{e||(De(t),t.verification_url&&Ne.current!==t.verification_url&&(Ne.current=t.verification_url,Me.current&&!Me.current.closed&&(Me.current.location.href=t.verification_url)),t.status===`ready`&&(await Fe(),S(t.app_ref),ue({}),Se(!1)),t.status===`failed`&&je(t.error??o(`lark.error.appCreate`)))}).catch(t=>{e||je(kb(t,o(`lark.error.setupPoll`),o))})},650);return()=>{e=!0,window.clearTimeout(t)}},[xe,R]);let V=n.find(e=>e.goalId===C),Ie=V?.agentId?[{agentId:V.agentId,label:V.agentLabel??V.agentId}]:[],Le=V?.agentLanes?.length?V.agentLanes:Ie,Re=Le.some(e=>e.agentId===L),ze=[];se?ze=Le.map(e=>({agentId:e.agentId,appRef:le[e.agentId]??x})):Re&&(ze=[{agentId:L,appRef:x}]);let Be=ze.map(e=>e.agentId),Ve=!!_e||ze.length>0&&ze.every(e=>l.some(t=>t.app_ref===e.appRef&&t.reply_ready)),He=o(`lark.connect`);he?He=o(`lark.saveConnection`):se&&(He=o(`lark.connectAllAgentsAction`,{count:Be.length}));let Ue=l.find(e=>e.app_ref===x),We=D.find(e=>e.chat_id===ee),Ge=(0,z.useMemo)(()=>{let e=_.trim().toLocaleLowerCase();return e?d.filter(t=>[t.app_label,t.chat_name,t.goal_title,t.topic_name].some(t=>t.toLocaleLowerCase().includes(e))):d},[d,_]),Ke=(0,z.useMemo)(()=>d.filter(e=>Db(e,o).state===`unverified`).length,[d,o]);function qe(e){let i=e??n.find(e=>e.goalId===r)??n[0];ge(null),ve(null),F(e||t?`goal`:`manager`),S(l.some(e=>e.app_ref===x)?x:l.find(e=>e.reply_ready)?.app_ref??l[0]?.app_ref??``),te(``),w(i?.goalId??``),oe(i?.agentId??``),ce(!1),ue({}),N(`addressed_only`),ie(`async_inbox`),ae(`topic_reply`),E(``),me(null),b(!0)}function Je(e){ge(e.goal_id),ve(e),F(e.conversation_kind??`goal`),S(e.app_ref),w(e.goal_id);let t=n.find(t=>t.goalId===e.goal_id),r=t?.agentLanes?.length?t.agentLanes:t?.agentId?[{agentId:t.agentId}]:[];oe(e.agent_id??(r.length===1?r[0].agentId:``)),ce(!1),ue({}),N(e.capture_scope),ie(e.ingress_mode===`direct_session`?`async_inbox`:e.ingress_mode),ae(e.reply_mode),E(e.chat_name),me(null),b(!0)}function Ye(){De(null),je(null),Ne.current=null,Se(!0)}async function Xe(){if(!(Oe||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Ce))){ke(!0),je(null),Ne.current=null,Me.current=window.open(window.location.href,`_blank`);try{let e=await Bg({appRef:Ce,brand:Te});De(e)}catch(e){Me.current?.close(),je(kb(e,o(`lark.error.setupStart`),o))}finally{ke(!1)}}}async function Ze(){let e=R;if(Se(!1),Me.current?.close(),e&&![`ready`,`failed`,`cancelled`].includes(e.status))try{await Hg(e.setup_id)}catch{}}async function Qe(){if(!(!x||!C||!_e&&!We||P===`goal`&&Be.length===0||de)){fe(!0),me(null);try{let e={...P===`manager`?{..._e?{connectionId:_e.connection_id}:{appRef:x,chatId:We.chat_id,chatName:We.chat_name}}:_e?{connectionId:_e.connection_id,agentId:L}:{agentBindings:ze,chatId:We.chat_id,chatName:We.chat_name},conversationKind:P,captureScope:P===`manager`?`addressed_only`:M,goalId:C,incomingMode:M===`configured_chat_all`?`all`:`mentions`,ingressMode:P===`manager`?`session_queue`:re,replyMode:I},t=await Jg({...e,execute:!1});if(!t.ok)throw new Th(t.public_summary??t.blocker??o(`lark.error.bindPreview`),{error_code:t.blocker??`provider_api_failed`});let n=await Jg({...e,execute:!0});if(!n.ok)throw new Th(n.public_summary??n.blocker??o(`lark.error.bind`),{error_code:n.blocker??`provider_api_failed`});b(!1),await Fe(),i?.()}catch(e){me(kb(e,o(`lark.error.bind`),o))}finally{fe(!1)}}}async function $e(e,t){if(ye!==t){be(t);return}try{await Yg(e,t),be(null),await Fe(),i?.()}catch(e){g(kb(e,o(`lark.error.disconnect`),o))}}return(0,B.jsxs)(`section`,{className:`personal-lark-settings${e?` is-embedded`:``}`,"aria-label":o(`lark.configuration`),children:[e?null:(0,B.jsxs)(`header`,{className:`personal-lark-header`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:o(`settings.goalConnections`)}),(0,B.jsx)(`h1`,{children:`Lark`})]}),(0,B.jsx)(`button`,{"aria-label":o(`lark.closeSettings`),className:`personal-icon-button`,onClick:a,type:`button`,children:(0,B.jsx)($m,{size:18})})]}),(0,B.jsxs)(`nav`,{className:`personal-lark-tabs`,"aria-label":o(`lark.management`),children:[(0,B.jsxs)(`button`,{"aria-current":s===`apps`?`page`:void 0,onClick:()=>c(`apps`),type:`button`,children:[o(`lark.apps`),` `,(0,B.jsx)(`span`,{children:p?`…`:l.length})]}),(0,B.jsxs)(`button`,{"aria-current":s===`connections`?`page`:void 0,onClick:()=>c(`connections`),type:`button`,children:[o(`lark.connections`),` `,(0,B.jsx)(`span`,{children:p?`…`:d.length})]})]}),h?(0,B.jsx)(`p`,{className:`personal-notification-error`,children:h}):null,p?(0,B.jsxs)(`div`,{className:`personal-lark-loading`,children:[(0,B.jsx)(Cm,{className:`is-spinning`,size:18}),o(`lark.loading`)]}):null,!p&&s===`apps`?(0,B.jsxs)(`div`,{className:`personal-lark-apps`,children:[(0,B.jsxs)(`div`,{className:`personal-lark-app-toolbar`,children:[(0,B.jsx)(`span`,{children:o(`lark.reusableApps`,{count:l.length})}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:Ye,type:`button`,children:[(0,B.jsx)(Pm,{size:16}),o(`lark.newApp`)]})]}),(0,B.jsxs)(`div`,{className:`personal-lark-app-grid`,children:[l.map(e=>(0,B.jsxs)(`article`,{className:`personal-lark-app-card`,children:[(0,B.jsx)(`span`,{className:`personal-lark-app-avatar`,children:(0,B.jsx)(Zp,{size:19})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsxs)(`small`,{children:[e.brand,` · lark-cli profile`]})]}),(0,B.jsx)(`em`,{className:e.reply_ready?`is-ready`:`is-off`,children:e.reply_ready?o(`lark.autoReplyReady`):e.ready?o(`lark.needsMessagePermissions`):o(`lark.needsSetup`)}),(0,B.jsxs)(`p`,{children:[o(`lark.goalConnections`,{count:d.filter(t=>t.app_ref===e.app_ref).length}),e.ready&&!e.reply_ready?` · ${o(`lark.autoReplyUnavailable`)}`:``]})]},e.app_ref)),l.length===0?(0,B.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noProfiles`)}):null]})]}):null,!p&&s===`connections`?(0,B.jsxs)(`div`,{className:`personal-lark-connections`,children:[Ke>0?(0,B.jsxs)(`p`,{className:`personal-lark-route-readiness`,role:`status`,children:[(0,B.jsx)(Dm,{size:15}),o(`lark.routesUnverified`,{count:Ke})]}):null,(0,B.jsxs)(`div`,{className:`personal-lark-toolbar`,children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(zm,{size:16}),(0,B.jsx)(`input`,{"aria-label":o(`lark.searchConnections`),onChange:e=>v(e.target.value),placeholder:o(`lark.searchPlaceholder`),type:`search`,value:_})]}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:l.length===0||n.length===0,onClick:()=>qe(),type:`button`,children:[(0,B.jsx)(Pm,{size:16}),o(`lark.connectApp`)]})]}),(0,B.jsxs)(`div`,{className:`personal-lark-table`,role:`table`,"aria-label":o(`lark.goalTopicConnections`),children:[(0,B.jsxs)(`div`,{className:`personal-lark-table-head`,role:`row`,children:[(0,B.jsx)(`span`,{children:o(`lark.connection`)}),(0,B.jsx)(`span`,{children:o(`common.goal`)}),(0,B.jsx)(`span`,{children:o(`lark.capture`)}),(0,B.jsx)(`span`,{children:o(`lark.processing`)}),(0,B.jsx)(`span`,{children:o(`common.actions`)})]}),Ge.map(e=>{let t=Db(e,o);return(0,B.jsxs)(`div`,{className:`personal-lark-table-row`,role:`row`,children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.chat_name}),(0,B.jsxs)(`small`,{children:[e.app_label,` · `,t.label]}),(0,B.jsx)(`small`,{children:t.detail}),t.state===`unverified`?(0,B.jsxs)(`a`,{href:`https://open.feishu.cn/document/server-docs/im-v1/message/events/receive?lang=zh-CN`,rel:`noreferrer`,target:`_blank`,children:[(0,B.jsx)(fm,{size:12}),o(`lark.openEventSettings`)]}):null,Ob(e)?(0,B.jsxs)(`a`,{href:Ob(e)??void 0,rel:`noreferrer`,target:`_blank`,children:[(0,B.jsx)(fm,{size:12}),o(`lark.historyPermission`)]}):null]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.goal_title}),(0,B.jsxs)(`small`,{children:[`# `,e.topic_name]})]}),(0,B.jsx)(`span`,{children:e.capture_scope===`addressed_only`?o(`lark.mentionsOnly`):o(`lark.allTopicMessages`)}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.conversation_kind===`manager`?o(`lark.managerConversation`):Eb(e.ingress_mode,o).label}),(0,B.jsx)(`small`,{children:e.conversation_kind===`manager`?o(`lark.managerConversationDescription`):e.agent_id??Eb(e.ingress_mode,o).detail})]}),(0,B.jsxs)(`span`,{className:`personal-lark-row-actions`,children:[(0,B.jsx)(`button`,{"aria-label":o(`lark.settingsConfigure`,{goal:e.goal_title}),onClick:()=>Je(e),type:`button`,children:(0,B.jsx)(Um,{size:15})}),(0,B.jsxs)(`button`,{"aria-label":o(`lark.settingsDisconnect`,{goal:e.goal_title}),className:ye===e.connection_id?`is-confirm`:``,onClick:()=>void $e(e.goal_id,e.connection_id),type:`button`,children:[(0,B.jsx)(Qm,{size:15}),ye===e.connection_id?o(`common.confirm`):null]})]})]},e.connection_id)}),Ge.length===0?(0,B.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noConnections`)}):null]})]}):null,y?(0,B.jsx)(`div`,{className:`personal-lark-modal-backdrop`,role:`presentation`,children:(0,B.jsxs)(`section`,{"aria-labelledby":`connect-lark-title`,"aria-modal":`true`,className:`personal-lark-modal`,role:`dialog`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:`Goal Topic connection`}),(0,B.jsx)(`h2`,{id:`connect-lark-title`,children:o(he?`lark.editConnection`:`lark.connectApp`)})]}),(0,B.jsx)(`button`,{"aria-label":o(`lark.closeConnection`),onClick:()=>b(!1),type:`button`,children:(0,B.jsx)($m,{size:18})})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.conversationKind`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.conversationKind`),disabled:!!_e,value:P,onChange:e=>F(e.target.value),children:[(0,B.jsx)(`option`,{value:`manager`,children:o(`lark.managerConversation`)}),(0,B.jsx)(`option`,{value:`goal`,children:o(`lark.workerConversation`)})]})]}),P===`manager`?(0,B.jsx)(`p`,{children:o(`lark.managerConversationDescription`)}):null,_e?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,B.jsx)(`div`,{children:_e.app_label})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,B.jsx)(`div`,{children:_e.chat_name})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,B.jsx)(`div`,{children:_e.goal_title})]}),(0,B.jsx)(`small`,{children:o(`lark.editPreservesIdentity`)})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,B.jsx)(`select`,{"aria-label":o(`lark.appProfile`),disabled:p,onChange:e=>{e.target.value===`__register__`?Ye():(S(e.target.value),ue({}))},value:x,children:p?(0,B.jsx)(`option`,{value:``,children:o(`lark.appLoading`)}):(0,B.jsxs)(B.Fragment,{children:[l.map(e=>(0,B.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref)),(0,B.jsx)(`option`,{value:`__register__`,children:o(`lark.registerAnother`)})]})}),(0,B.jsx)(`small`,{children:o(`lark.defaultAgentAppDescription`)})]}),Ue?.ready&&!Ue.reply_ready?(0,B.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.appPermissions`)}):null,(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,B.jsx)(`input`,{"aria-label":o(`lark.groupSearch`),onChange:e=>E(e.target.value),placeholder:o(`lark.groupSearch`),type:`search`,value:T}),ne?(0,B.jsxs)(`div`,{className:`personal-lark-group-state`,role:`status`,children:[(0,B.jsx)(Cm,{className:`is-spinning`,size:15}),o(`lark.groupLoading`)]}):null,!ne&&A?(0,B.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:A}):null,!ne&&!A&&D.length===0?(0,B.jsx)(`div`,{className:`personal-lark-group-state`,role:`status`,children:o(`lark.groupEmpty`)}):null,!ne&&!A&&D.length>0?(0,B.jsx)(`select`,{"aria-label":o(`lark.groupChat`),onChange:e=>te(e.target.value),value:ee,children:D.map(e=>(0,B.jsx)(`option`,{value:e.chat_id,children:e.chat_name},e.chat_id))}):null]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,B.jsx)(`select`,{"aria-label":o(`lark.bindGoal`),onChange:e=>{let t=e.target.value;w(t),oe(n.find(e=>e.goalId===t)?.agentId??``),ue({})},value:C,children:n.map(e=>(0,B.jsx)(`option`,{value:e.goalId,children:e.title},e.goalId))})]})]}),(0,B.jsxs)(`label`,{className:`personal-lark-check`,children:[(0,B.jsx)(`input`,{checked:!0,readOnly:!0,type:`checkbox`}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:o(`lark.createAutomatically`)}),(0,B.jsx)(`small`,{children:o(`lark.createAutomaticallyDescription`)})]})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.topicPreview`)}),(0,B.jsxs)(`div`,{className:`personal-lark-topic-preview`,children:[(0,B.jsx)(Dm,{size:15}),`# `,V?.title??V?.goalId??`Goal`]})]}),P===`goal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.captureScope`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.captureScope`),disabled:_e?.ingress_mode===`direct_session`,onChange:e=>N(e.target.value),value:M,children:[(0,B.jsx)(`option`,{value:`addressed_only`,children:o(`lark.captureAddressed`)}),(0,B.jsx)(`option`,{value:`configured_chat_all`,children:o(`lark.captureAll`)})]}),(0,B.jsx)(`small`,{children:o(`lark.captureScopeDescription`)})]}),(0,B.jsxs)(`fieldset`,{"aria-label":o(`lark.agentIngress`),className:`personal-lark-ingress`,children:[(0,B.jsx)(`legend`,{children:o(`lark.agentIngress`)}),(0,B.jsx)(`div`,{children:[`live_steering`,`session_queue`,`async_inbox`].map(e=>{let t=Eb(e,o);return(0,B.jsxs)(`label`,{className:re===e?`is-active`:``,children:[(0,B.jsx)(`input`,{"aria-label":t.label,checked:re===e,name:`lark-agent-ingress`,onChange:()=>ie(e),type:`radio`,value:e}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:t.label}),(0,B.jsx)(`small`,{children:t.detail})]})]},e)})})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.targetAgent`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.targetAgent`),disabled:!!_e?.agent_id,onChange:e=>oe(e.target.value),value:L,children:[Re?null:(0,B.jsx)(`option`,{disabled:!0,value:L,children:L?o(`lark.agentUnavailable`,{agent:L}):o(`lark.noAgentConfigured`)}),Le.map(e=>(0,B.jsx)(`option`,{value:e.agentId,children:e.label===e.agentId?e.agentId:`${e.label} · ${e.agentId}`},e.agentId))]}),(0,B.jsx)(`small`,{children:o(`lark.targetAgentDescription`)})]}),!he&&Le.length>1?(0,B.jsxs)(`label`,{"aria-label":o(`lark.connectAllAgents`),className:`personal-lark-check`,children:[(0,B.jsx)(`input`,{checked:se,onChange:e=>ce(e.target.checked),type:`checkbox`}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:o(`lark.connectAllAgents`)}),(0,B.jsx)(`small`,{children:o(`lark.connectAllAgentsDescription`,{count:Le.length})})]})]}):null,!he&&se&&Le.length>1?(0,B.jsxs)(`fieldset`,{"aria-label":o(`lark.agentApps`),className:`personal-lark-agent-apps`,children:[(0,B.jsx)(`legend`,{children:o(`lark.agentApps`)}),(0,B.jsx)(`small`,{children:o(`lark.agentAppsDescription`)}),(0,B.jsx)(`div`,{children:Le.map(e=>(0,B.jsxs)(`label`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsx)(`small`,{children:e.agentId})]}),(0,B.jsx)(`select`,{"aria-label":o(`lark.agentAppSelection`,{agent:e.label}),onChange:t=>ue(n=>({...n,[e.agentId]:t.target.value})),value:le[e.agentId]??x,children:l.map(e=>(0,B.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref))})]},e.agentId))})]}):null,se&&ze.length>0&&!Ve?(0,B.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.agentAppPermissions`)}):null,Be.length===0?(0,B.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:o(`lark.selectRegisteredAgent`)}):null]}):null,(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.replyMode`)}),(0,B.jsx)(`select`,{"aria-label":o(`lark.replyMode`),onChange:e=>ae(e.target.value),value:I,children:(0,B.jsx)(`option`,{value:`topic_reply`,children:o(`lark.topicReply`)})}),(0,B.jsx)(`small`,{children:o(`lark.replyModeDescription`)})]}),(0,B.jsxs)(`p`,{className:`personal-lark-cardinality`,children:[(0,B.jsx)(em,{size:15}),o(`lark.cardinality`)]}),pe?(0,B.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:pe}):null,(0,B.jsxs)(`footer`,{children:[(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>b(!1),type:`button`,children:o(`lark.cancel`)}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:p||!x||!_e&&(!Ue?.reply_ready||!ee)||P===`goal`&&(!Ve||Be.length===0)||!C||de,onClick:()=>void Qe(),type:`button`,children:[de?(0,B.jsx)(Cm,{className:`is-spinning`,size:15}):null,He]})]})]})}):null,xe?(0,B.jsx)(`div`,{className:`personal-lark-modal-backdrop is-setup`,role:`presentation`,children:(0,B.jsxs)(`section`,{"aria-labelledby":`new-lark-app-title`,"aria-modal":`true`,className:`personal-lark-modal personal-lark-setup-modal`,role:`dialog`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:o(`lark.reusableWorkspaceApp`)}),(0,B.jsx)(`h2`,{id:`new-lark-app-title`,children:o(`lark.newApp`)})]}),(0,B.jsx)(`button`,{"aria-label":o(`lark.closeCreate`),onClick:()=>void Ze(),type:`button`,children:(0,B.jsx)($m,{size:18})})]}),R?(0,B.jsxs)(`div`,{className:`personal-lark-setup-progress`,children:[(0,B.jsx)(`span`,{className:`personal-lark-setup-icon is-${R.status}`,children:R.status===`ready`?(0,B.jsx)(em,{size:22}):(0,B.jsx)(Cm,{className:R.status===`failed`?``:`is-spinning`,size:22})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:R.status===`ready`?o(`lark.appCreated`):R.status===`failed`?o(`lark.appCreateFailed`):o(`lark.waitingFeishu`)}),(0,B.jsx)(`p`,{children:R.status===`waiting_for_feishu`?o(`lark.waitingFeishuDescription`):R.status===`starting`?o(`lark.waitingLink`):R.error})]}),R.verification_url?(0,B.jsxs)(`a`,{href:R.verification_url,rel:`noreferrer`,target:`_blank`,children:[(0,B.jsx)(fm,{size:15}),o(`lark.reopenFeishu`)]}):null]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`personal-lark-setup-copy`,children:o(`lark.setupCopy`)}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.profileName`)}),(0,B.jsx)(`input`,{"aria-label":o(`lark.profileName`),autoComplete:`off`,onChange:e=>we(e.target.value),placeholder:`loopx-workspace-bot`,value:Ce})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.region`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.region`),onChange:e=>Ee(e.target.value),value:Te,children:[(0,B.jsx)(`option`,{value:`feishu`,children:`Feishu`}),(0,B.jsx)(`option`,{value:`lark`,children:`Lark`})]})]}),Ce&&!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Ce)?(0,B.jsx)(`p`,{className:`personal-notification-error`,children:o(`lark.profileValidation`)}):null]}),Ae?(0,B.jsx)(`p`,{className:`personal-notification-error`,children:Ae}):null,(0,B.jsxs)(`footer`,{children:[(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void Ze(),type:`button`,children:o(`lark.cancel`)}),R?null:(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:Oe||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Ce),onClick:()=>void Xe(),type:`button`,children:[Oe?(0,B.jsx)(Cm,{className:`is-spinning`,size:15}):(0,B.jsx)(fm,{size:15}),o(`lark.continueFeishu`)]})]})]})}):null]})}function jb(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function Mb(e,t,n){let r=jb(t),i=jb(n);return Object.fromEntries(e.fields.flatMap(({key:e,nullable:t})=>{let n=r[e],a=i[e];return Object.hasOwn(r,e)&&(n!=null||t&&n===null)?[[e,n]]:Object.hasOwn(i,e)&&a!=null?[[e,a]]:[]}))}function Nb(e,t){let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=new Set(e.fields.map(e=>e.key));return Object.keys(n).some(e=>!r.has(e))?null:n}function Pb(e,t,n){let r={...e,[t]:n},i=e.schedule;return t===`timezone`&&i&&typeof i==`object`&&`schema_version`in i&&i.schema_version===`periodic_report_schedule_v0`&&(r.schedule={...i,timezone:n}),r}function Fb({id:e,value:t,timezone:n,onChange:r}){let{locale:i}=Ji(),a=i===`zh-CN`,o=t&&typeof t==`object`&&!Array.isArray(t)?t:null,s=String(o?.rrule??``).split(`;`).map(e=>e.split(`=`)),c=Object.fromEntries(s.filter(e=>e.length===2)),l=[`MO`,`TU`,`WE`,`TH`,`FR`,`SA`,`SU`],u=(e,t)=>e!==void 0&&/^\d+$/.test(e)&&Number(e)<=t,d=!o||o.schema_version===`periodic_report_schedule_v0`&&[`DAILY`,`WEEKLY`].includes(c.FREQ)&&o.timezone===n&&s.every(e=>e.length===2&&[`FREQ`,`BYDAY`,`BYHOUR`,`BYMINUTE`,`INTERVAL`].includes(e[0]))&&new Set(s.map(([e])=>e)).size===s.length&&u(c.BYHOUR,23)&&u(c.BYMINUTE??`0`,59)&&(c.FREQ===`WEEKLY`?l.includes(c.BYDAY):!c.BYDAY)&&(!c.INTERVAL||c.INTERVAL===`1`),f=a?[`星期一`,`星期二`,`星期三`,`星期四`,`星期五`,`星期六`,`星期日`]:[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`];function p(e){let t={FREQ:`WEEKLY`,BYDAY:`MO`,BYHOUR:`9`,BYMINUTE:`0`,...c,...e};r?.({schema_version:`periodic_report_schedule_v0`,schedule_id:o?.schedule_id??`report-schedule`,timezone:n,rrule:[`FREQ=${t.FREQ}`,...t.FREQ===`WEEKLY`?[`BYDAY=${t.BYDAY}`]:[],`BYHOUR=${t.BYHOUR}`,`BYMINUTE=${t.BYMINUTE}`].join(`;`)})}return(0,B.jsxs)(`div`,{className:`personal-report-schedule`,children:[(0,B.jsxs)(`label`,{className:`is-boolean`,htmlFor:e,children:[(0,B.jsx)(`span`,{children:a?`按日历汇报`:`Calendar reports`}),(0,B.jsx)(`input`,{id:e,type:`checkbox`,role:`switch`,checked:!!o,disabled:!r,onChange:e=>e.target.checked?p({}):r?.(null)})]}),o?(0,B.jsxs)(B.Fragment,{children:[d?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{htmlFor:`${e}-frequency`,children:[(0,B.jsx)(`span`,{children:a?`频率`:`Frequency`}),(0,B.jsxs)(`select`,{id:`${e}-frequency`,value:c.FREQ,disabled:!r,onChange:e=>p({FREQ:e.target.value}),children:[(0,B.jsx)(`option`,{value:`DAILY`,children:a?`每天`:`Daily`}),(0,B.jsx)(`option`,{value:`WEEKLY`,children:a?`每周`:`Weekly`})]})]}),c.FREQ===`WEEKLY`&&(0,B.jsxs)(`label`,{htmlFor:`${e}-day`,children:[(0,B.jsx)(`span`,{children:a?`星期`:`Weekday`}),(0,B.jsx)(`select`,{id:`${e}-day`,value:c.BYDAY,disabled:!r,onChange:e=>p({BYDAY:e.target.value}),children:l.map((e,t)=>(0,B.jsx)(`option`,{value:e,children:f[t]},e))})]}),(0,B.jsxs)(`label`,{htmlFor:`${e}-time`,children:[(0,B.jsxs)(`span`,{children:[a?`当地时间`:`Local time`,` (`,n,`)`]}),(0,B.jsx)(`input`,{id:`${e}-time`,type:`time`,required:!0,disabled:!r,value:`${(c.BYHOUR??`9`).padStart(2,`0`)}:${(c.BYMINUTE??`0`).padStart(2,`0`)}`,onChange:e=>{if(!/^\d{2}:\d{2}$/.test(e.target.value))return;let[t,n]=e.target.value.split(`:`);p({BYHOUR:t,BYMINUTE:n})}})]})]}):(0,B.jsx)(`p`,{role:`alert`,children:a?`此计划需在 JSON 模式中编辑;当前内容已保留。`:`Edit this schedule in JSON mode; its current value is preserved.`}),(0,B.jsx)(`p`,{children:a?`由现有唤醒检查到期计划;实际送达以回执为准。`:`Existing wakes check the schedule; delivery is confirmed by its receipt.`})]}):(0,B.jsx)(`p`,{children:a?`未设置日历计划;保持阶段结束时汇报。`:`No calendar schedule; report at validated stage boundaries.`})]})}function Ib({copy:e,field:t,id:n,onChange:r,value:i,timezone:a}){let o=e[t.key]?.label??t.label,s=!r;if(t.input_kind===`periodic_report_schedule`)return(0,B.jsx)(Fb,{id:n,value:i,timezone:a,onChange:r?e=>r(t.key,e):void 0});if(t.input_kind===`boolean`)return(0,B.jsxs)(`label`,{className:`is-boolean`,htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsx)(`input`,{checked:i===!0,id:n,onChange:r?e=>r(t.key,e.target.checked):void 0,readOnly:s,role:`switch`,type:`checkbox`})]});if(t.input_kind===`select`)return(0,B.jsxs)(`label`,{htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsxs)(`select`,{id:n,onChange:r?e=>r(t.key,e.target.value):void 0,value:typeof i==`string`?i:``,children:[(0,B.jsx)(`option`,{value:``}),(t.options??[]).map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))]})]});if(t.input_kind===`string_list`)return(0,B.jsxs)(`label`,{htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsx)(`textarea`,{id:n,onChange:r?e=>r(t.key,e.target.value.split(/\r?\n/u).filter(Boolean)):void 0,readOnly:s,rows:4,value:Array.isArray(i)?i.join(` -`):``})]});let c=t.input_kind===`number`;return(0,B.jsxs)(`label`,{htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsx)(`input`,{id:n,max:t.maximum,min:t.minimum,onChange:r?e=>r(t.key,c?Number(e.target.value):e.target.value):void 0,readOnly:s,required:t.required,type:c?`number`:`text`,value:typeof i==`number`||typeof i==`string`?i:``})]})}function Lb({copy:e={},disabled:t=!1,editor:n,enabledAction:r,omitKeys:i=[],onChange:a,value:o}){let s=(0,z.useId)(),c=new Set(i);return(0,B.jsx)(`fieldset`,{className:`personal-capability-fields`,disabled:t,children:n.fields.filter(e=>!c.has(e.key)).map(t=>{let n=(0,B.jsx)(Ib,{copy:e,field:t,id:`${s}-${t.key.replace(/[^a-z0-9_-]/gi,`-`)}`,onChange:a,value:o[t.key],timezone:String(o.timezone??`UTC`)},t.key);return t.key===`enabled`&&t.input_kind===`boolean`?(0,B.jsxs)(`div`,{className:`personal-capability-enabled-row`,children:[n,r]},t.key):n})})}var Rb={en:{todo_replan_cadence:{displayName:`Goal review cadence`,description:`Configures the Goal review cadence.`},change_quality_qualification:{displayName:`Change quality qualification`,description:`Prepares a provider-neutral review packet, allows at most one policy-authorized safe-fix pass, and can require an exact-diff receipt.`},explore_graph:{displayName:`Explore Graph`,description:`Organizes bounded exploration as a typed evidence graph so branches, findings, and synthesis remain inspectable.`},explore_harness:{displayName:`Explore Harness`,description:`Selects a capability-owned planning and research harness profile for bounded multi-step exploration.`},lark_event_inbox:{displayName:`Lark event inbox`,description:`Receives provider events through a local-private inbox binding before LoopX projects them into governed work.`,readOnlyReason:`This capability requires a local-private inbox binding. Manage it in Lark settings or through the capability CLI.`},lark_kanban_heartbeat_sync:{displayName:`Lark Kanban heartbeat sync`,description:`Synchronizes accepted LoopX work state to the configured Lark Kanban heartbeat surface.`},local_authority_shadow:{displayName:`Local authority shadow`,description:`Observes post-commit Todo and task-lease state through the shared authority contract without taking write authority.`},multi_subagent:{displayName:`Adaptive child capacity`,description:`Sets bounded child-agent capacity and the public-safe responsibility domains in which parallel work may be delegated.`},peer_task_coordination:{displayName:`Registered-peer task coordination`,description:`Routes explicitly scoped peer-owned work to one registered coordinator without granting cross-owner mutation authority.`},periodic_report:{displayName:`Periodic reports`,description:`Turns validated Goal stage progress into a frozen report and automatically delivers it through the configured Goal Channel with exact readback.`},pull_request_review:{displayName:`Pull-request review`,description:`Ranks the public GitHub PR review queue with a machine-level default; it never grants GitHub, Todo, push, or merge authority.`},reward_memory:{displayName:`Reward Memory experiment`,description:`Configures a reviewed local-private provider binding for Goal-scoped Agent recall and evidence-backed outcome learning.`}},"zh-CN":{todo_replan_cadence:{displayName:`Goal 复核周期`,description:`配置 Goal 的复核周期。`},change_quality_qualification:{displayName:`变更质量验证`,description:`生成与 Provider 无关的审阅包,最多允许一次策略授权的安全修复,并可要求精确 diff 回执。`},explore_graph:{displayName:`探索图谱`,description:`把有界探索组织为 typed 证据图,让探索分支、发现与综合结论都可检查、可追溯。`},explore_harness:{displayName:`探索 Harness`,description:`为有界的多步探索选择由能力负责的规划与研究 Harness profile。`},lark_event_inbox:{displayName:`飞书事件收件箱`,description:`通过本机私有收件箱接收 Provider 事件,再由 LoopX 将其投影为受治理的工作。`,readOnlyReason:`此能力依赖本机私有的收件箱绑定,请在飞书设置或 capability CLI 中管理。`},lark_kanban_heartbeat_sync:{displayName:`飞书看板心跳同步`,description:`把 LoopX 已接受的工作状态同步到配置好的飞书看板心跳界面。`},local_authority_shadow:{displayName:`本地 Authority 影子观测`,description:`通过共享 Authority contract 观测提交后的 Todo 与 task lease 状态,但不取得写入权。`},multi_subagent:{displayName:`自适应子 Agent 容量`,description:`限定子 Agent 容量与可公开的职责域,只有落在这些边界内的工作才能并行委派。`},peer_task_coordination:{displayName:`已注册 Peer 任务协调`,description:`把明确限定的 Peer 工作路由给一个已注册协调者,不授予跨 Owner 修改权限。`},periodic_report:{displayName:`周期报告`,description:`把经过验证的 Goal 阶段进展整理为冻结报告,并通过配置的 Goal Channel 自动发送和精确回读。`},pull_request_review:{displayName:`Pull-request Review`,description:`配置公开 GitHub PR 审阅队列的本机默认排序;不会授予 GitHub、Todo、push 或 merge 权限。`},reward_memory:{displayName:`Reward Memory 实验`,description:`为 Goal 内 Agent 的召回与证据化结果学习配置经过审阅的本机私有 Provider 绑定。`}}},zb={en:{completed_todos:{label:`Completed Todos between Goal reviews`,description:`Machine default or explicit Goal override, from 1 to 5.`},allowed_domains:{label:`Allowed responsibility domains`,description:`Enter one bounded, public-safe domain per line.`},coordinator_agent_id:{label:`Coordinator Agent`,description:`Use an already registered Agent id; leave blank to disable coordination.`},enabled:{label:`Enabled`},model:{label:`Child model`,description:`For example gpt-5.6-luna. Blank clears the child model preference.`},reasoning_effort:{label:`Child reasoning effort`,description:`For example max; the host must support this model and effort.`},max_children:{label:`Maximum children`,description:`Hard upper bound for concurrently delegated child work.`},profile:{label:`Planner profile`,description:`Select one registered Explore Harness profile.`},profile_preset:{label:`Report profile`,description:`Capability-owned report profile, such as weekly-progress.`},review_priority:{label:`Review priority`,description:`Choose whether other developers' PRs or the authenticated reviewer's own PRs are ranked first.`},route_ref:{label:`Goal Channel route`,description:`Public route alias only; credentials and provider identifiers stay outside this form.`},safe_fix:{label:`Allow one bounded safe-fix pass`},strict_receipt:{label:`Require an exact-diff receipt`},timezone:{label:`Timezone`,description:`Use an IANA timezone, for example Asia/Shanghai.`},schedule:{label:`Calendar reports`,description:`Optional daily or weekly reports; no schedule preserves stage-only delivery.`},config_path:{label:`Local-private configuration path`,description:`Repo-relative ignored JSON under .loopx/config/. Leave blank to retain the current binding; the path is never returned.`},enabled_agents:{label:`Enabled Goal Agents`,description:`Enter one registered Goal-local Agent id per line. A private binding currently accepts exactly one Agent.`}},"zh-CN":{completed_todos:{label:`两次 Goal 复核间的已完成 Todo 数`,description:`可设置 1–5;机器默认值可被 Goal 显式覆盖。`},allowed_domains:{label:`允许的职责域`,description:`每行填写一个有边界、可公开的职责域。`},coordinator_agent_id:{label:`协调 Agent`,description:`填写一个已经注册的 Agent ID;留空表示关闭协调。`},enabled:{label:`启用`},model:{label:`子 Agent 模型`,description:`例如 gpt-5.6-luna;留空清除模型偏好。`},reasoning_effort:{label:`子 Agent 推理档位`,description:`例如 max;宿主须支持所选模型与档位。`},max_children:{label:`最大子 Agent 数`,description:`可同时委派的子任务硬上限。`},profile:{label:`规划 Profile`,description:`选择一个已注册的 Explore Harness profile。`},profile_preset:{label:`报告 Profile`,description:`由该能力管理的报告 profile,例如 weekly-progress。`},review_priority:{label:`审阅优先级`,description:`选择先排其他开发者的 PR,还是先排当前已认证审阅者自己的 PR。`},route_ref:{label:`Goal Channel 路由`,description:`只填写公开 route alias;凭据与 Provider 标识不会进入此表单。`},safe_fix:{label:`允许一次有界安全修复`},strict_receipt:{label:`要求精确 diff 回执`},timezone:{label:`时区`,description:`使用 IANA 时区,例如 Asia/Shanghai。`},schedule:{label:`日历汇报`,description:`可选每日或每周计划;未设置时保持阶段结束汇报。`},config_path:{label:`本机私有配置路径`,description:`填写 .loopx/config/ 下、相对仓库且被忽略的 JSON;留空保留当前绑定,路径不会被回传。`},enabled_agents:{label:`已启用的 Goal Agent`,description:`每行填写一个已注册的 Goal 内 Agent ID;私有绑定当前只接受一个 Agent。`}}};function Bb(e,t){let n=Rb[t][e.capability_id];return n?{...e,display_name:n.displayName,description:n.description,configuration_editor:{...e.configuration_editor,...n.readOnlyReason?{read_only_reason:n.readOnlyReason}:{}}}:e}function Vb(e){return zb[e]}Object.freeze(Object.keys(Rb.en).sort());function Hb(e,t){return e.available_scopes.includes(t)&&(t!==`machine`||!!e.machine_namespace)&&e.configuration_editor.editable&&e.configuration_editor.writable_scopes.includes(t)}function Ub({values:e,t}){return(0,B.jsxs)(`details`,{className:`personal-capability-raw-values`,children:[(0,B.jsx)(`summary`,{children:t(`capabilities.rawJson`)}),(0,B.jsx)(`div`,{className:`personal-capability-value-grid`,children:e.map(({label:e,value:t})=>(0,B.jsxs)(`section`,{children:[(0,B.jsx)(`strong`,{children:e}),(0,B.jsx)(`pre`,{children:t?JSON.stringify(t,null,2):`—`})]},e))})]})}function Wb({source:e,t}){return e?(0,B.jsxs)(`p`,{className:`personal-capability-effective-source`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:15}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:t(`capabilities.effectiveSource`)}),t(`capabilities.source.${e}`)]})]}):null}function Gb({available:e,description:t,t:n}){return e?null:(0,B.jsxs)(`section`,{className:`personal-capability-editor-status is-read-only`,children:[(0,B.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:n(`capabilities.readOnly`)}),(0,B.jsx)(`p`,{children:t})]})]})}function Kb(e){return e.availability?.includes(`experimental`)?4:e.capability_id===`multi_subagent`?3:e.configuration_editor.writable_scopes.length===0||e.availability===`supported_explicit_opt_in`?2:e.availability===`supported_explicit_override`?0:1}function qb(e,t){return[...e].sort((e,n)=>{let r=Kb(e)-Kb(n);if(r!==0)return r;let i=Bb(e,t),a=Bb(n,t);return i.display_name.localeCompare(a.display_name,t)||e.capability_id.localeCompare(n.capability_id)})}function Jb({capabilities:e,locale:t,onSelect:n,scope:r,selectedCapabilityId:i,t:a}){return(0,B.jsx)(`nav`,{"aria-label":a(r===`goal`?`capabilities.catalog`:`machine.capabilityCatalog`),className:`personal-capability-list`,tabIndex:0,children:qb(e,t).map(e=>{let o=Bb(e,t);return(0,B.jsxs)(`button`,{"aria-current":i===o.capability_id?`page`:void 0,onClick:()=>n(o.capability_id),type:`button`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:o.display_name})}),(0,B.jsx)(`em`,{children:a(o.available_scopes.includes(r)?r===`goal`?`capabilities.goalScope`:`capabilities.machineScope`:r===`machine`?`capabilities.goalScope`:`capabilities.machineScope`)})]},o.capability_id)})})}function Yb({capability:e,locale:t,source:n}){let{t:r}=Ji(),i=Bb(e,t);return(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`span`,{className:`personal-settings-icon`,children:(0,B.jsx)(Gm,{"aria-hidden":!0,size:18})}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`div`,{className:`personal-capability-heading-row`,children:[(0,B.jsx)(`h2`,{children:i.display_name}),(0,B.jsx)(Wb,{source:n,t:r})]}),e.context_contribution&&(0,B.jsxs)(`details`,{className:`personal-capability-help`,"data-testid":`capability-context-phases`,children:[(0,B.jsx)(`summary`,{children:t===`zh-CN`?`主 Agent 协作指导`:`Coordinator workflow guidance`}),(0,B.jsx)(`p`,{children:t===`zh-CN`?`随能力开启。支持以下阶段;此处展示能力范围,不能证明某次运行已读取或采纳。`:`Enabled with this capability. These are supported phases, not proof that a run read or adopted the guidance.`}),(0,B.jsx)(`dl`,{children:e.context_contribution.supported_phases.map(e=>(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:(0,B.jsx)(`code`,{children:e})}),(0,B.jsx)(`dd`,{children:Xb[e][t===`zh-CN`?`zh`:`en`]})]},e))}),(0,B.jsx)(`p`,{children:t===`zh-CN`?`LoopX Turn 在请求与结果中提供上下文;原生工具入口由 LoopX skill 调用同一只读接口。执行与采纳需另看运行证据。`:`LoopX Turn includes context in requests and results. For native tools, the LoopX skill reads the same interface. Execution and adoption require run evidence.`})]}),(0,B.jsxs)(`details`,{className:`personal-capability-help`,children:[(0,B.jsx)(`summary`,{children:t===`zh-CN`?`配置说明`:`Configuration help`}),(0,B.jsx)(`p`,{children:i.description}),(0,B.jsx)(`dl`,{children:e.configuration_editor.fields.map(e=>{let n=Vb(t)[e.key],r=n?.description??e.description;return r?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:n?.label??e.label}),(0,B.jsx)(`dd`,{children:r})]},e.key):null})})]},e.capability_id)]})]})}var Xb={before_plan:{zh:`规划前:识别独立问题并保留主 Agent 的核验与整合职责。`,en:`Before planning: identify independent questions and retain coordinator validation and integration.`},before_delegate:{zh:`委派前:明确子任务边界、模型偏好及预期证据。`,en:`Before delegation: specify task boundaries, model preferences and expected evidence.`},after_delegate_result:{zh:`回收后:核验结果,说明采纳决定并关联计划与成果。`,en:`After results: validate evidence, explain acceptance and link plans and deliverables.`}};function Zb({goalId:e,onApplied:t,selected:n,t:r}){let[i,a]=(0,z.useState)({busy:null,draft:{},partialWrite:null,preview:null}),[o,s]=(0,z.useState)(null),[c,l]=(0,z.useState)(`guided`),[u,d]=(0,z.useState)(``),f=(0,z.useMemo)(()=>n?Nb(n.configuration_editor,u):null,[n,u]),p=c===`guided`||f!==null;(0,z.useEffect)(()=>{l(`guided`),d(``),a({busy:null,draft:Mb(n?.configuration_editor??{fields:[]},n?.current??n?.effective_configuration?.configuration??n?.default,n?.default),partialWrite:null,preview:null}),s(null)},[n]);async function m(t){if(!(!n||i.busy||!p)){a(e=>({...e,busy:`preview`,partialWrite:null})),s(null);try{let r=await Dg(e,n.capability_id,t);a(e=>({...e,preview:r}))}catch(e){s(e instanceof Error?e.message:r(`capabilities.previewFailed`))}finally{a(e=>({...e,busy:null}))}}}async function h(){if(!(!n||!i.preview||i.busy||!p)){a(e=>({...e,busy:`apply`})),s(null);try{let r=Mb(n.configuration_editor,i.draft,n.default),o=await Og(e,n.capability_id,i.preview.action===`delete`?null:r,i.preview.plan_revision);a(e=>({...e,partialWrite:o.status===`partial_write`?o:null,preview:null})),o.status!==`partial_write`&&t()}catch(e){a(e=>({...e,preview:null})),s(e instanceof Error?e.message:r(`capabilities.applyFailed`))}finally{a(e=>({...e,busy:null}))}}}function g(e,t){a(r=>({...r,draft:n?.capability_id===`periodic_report`?Pb(r.draft,e,t):{...r.draft,[e]:t},preview:null})),s(null)}function _(e){if(!n||i.busy)return;d(e);let t=Nb(n.configuration_editor,e);a(e=>({...e,preview:null,draft:t?Mb(n.configuration_editor,t,n.default):e.draft})),s(null)}function v(){i.busy||!p||(c===`guided`&&d(JSON.stringify(i.draft,null,2)),l(c===`guided`?`json`:`guided`),a(e=>({...e,preview:null})))}return{apply:h,changeDraft:g,changeJson:_,changeMode:v,editorMode:c,jsonDraft:u,jsonValid:p,error:o,mutation:i,preview:m}}function Qb({mutationError:e,onApplied:t,partialWrite:n,preview:r}){let{t:i}=Ji();return(0,B.jsxs)(B.Fragment,{children:[e?(0,B.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:e}):null,n?(0,B.jsxs)(`section`,{"aria-live":`polite`,className:`personal-capability-recovery`,children:[(0,B.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:i(`capabilities.partialWrite`)}),(0,B.jsx)(`p`,{children:i(`capabilities.partialWriteDescription`)}),(0,B.jsx)(`small`,{children:n.recommended_action})]}),(0,B.jsxs)(`button`,{onClick:t,type:`button`,children:[(0,B.jsx)(Im,{"aria-hidden":!0,size:15}),i(`capabilities.refreshSource`)]})]}):null,r?(0,B.jsxs)(`section`,{className:`personal-capability-preview`,"aria-label":i(`capabilities.preview`),children:[(0,B.jsx)(`strong`,{children:i(`capabilities.preview`)}),(0,B.jsx)(`span`,{children:i(`machine.action.${r.action}`)}),(0,B.jsx)(`small`,{children:i(`capabilities.previewLocked`)})]}):null]})}function $b({catalog:e,goalId:t,onApplied:n}){let{locale:r,t:i}=Ji(),a=(0,z.useMemo)(()=>qb(e.capabilities,r),[e.capabilities,r]),[o,s]=(0,z.useState)(()=>a[0]?.capability_id??``),c=(0,z.useMemo)(()=>a.find(e=>e.capability_id===o)??a[0],[a,o]),l=(0,z.useMemo)(()=>c?Bb(c,r):void 0,[r,c]),{apply:u,changeDraft:d,changeJson:f,changeMode:p,editorMode:m,jsonDraft:h,jsonValid:g,error:_,mutation:v,preview:y}=Zb({goalId:t,onApplied:n,selected:l,t:i}),{busy:b,draft:x,partialWrite:S,preview:C}=v;if(!c||!l)return(0,B.jsx)(`p`,{className:`personal-capability-empty`,children:i(`capabilities.empty`)});let w=l.available_scopes.includes(`goal`),T=Hb(l,`goal`),E=l.configuration_editor.read_only_reason??i(w?`capabilities.previewOnly`:`capabilities.machineOnly`);async function D(){if(!l||!T||b||!g)return;let e=Mb(l.configuration_editor,x,l.default);await y(e)}async function O(){!T||b||await y(null)}return(0,B.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,B.jsx)(Jb,{capabilities:e.capabilities,locale:r,onSelect:s,scope:`goal`,selectedCapabilityId:l.capability_id,t:i}),(0,B.jsxs)(`article`,{"aria-label":l.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,B.jsx)(Yb,{capability:c,locale:r,source:l.effective_configuration?.source}),(0,B.jsx)(Gb,{available:T,t:i,description:E}),T?(0,B.jsxs)(B.Fragment,{children:[m===`json`||!l.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,B.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,B.jsxs)(`button`,{disabled:!!b||!g,onClick:p,type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),i(m===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,m===`guided`?(0,B.jsx)(`section`,{className:`personal-capability-field-summary`,children:(0,B.jsx)(Lb,{disabled:!!b,copy:Vb(r),editor:l.configuration_editor,onChange:d,value:x,enabledAction:(0,B.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:p,type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),i(`machine.editJson`)]})})}):(0,B.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`goal-configuration-json`,children:[(0,B.jsx)(`span`,{children:i(`capabilities.jsonConfiguration`)}),(0,B.jsx)(`textarea`,{id:`goal-configuration-json`,"aria-describedby":`goal-configuration-json-help`,disabled:!!b,onChange:e=>f(e.target.value),rows:12,spellCheck:!1,value:h}),(0,B.jsx)(`small`,{id:`goal-configuration-json-help`,children:i(`capabilities.jsonHelp`)}),g?null:(0,B.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:i(`capabilities.jsonInvalid`)})]})]}):null,(0,B.jsx)(Qb,{mutationError:_,onApplied:n,partialWrite:S,preview:C}),T?(0,B.jsxs)(`footer`,{className:`personal-capability-actions`,children:[l.current&&l.available_scopes.includes(`machine`)?(0,B.jsx)(`button`,{disabled:!!b||!g,onClick:()=>void O(),type:`button`,children:i(`capabilities.restoreInheritance`)}):null,(0,B.jsx)(`button`,{disabled:!!b||!g,onClick:()=>void D(),type:`button`,children:i(b===`preview`?`common.loading`:`capabilities.previewChanges`)}),(0,B.jsx)(`button`,{className:`is-primary`,disabled:!!b||!C||!g,onClick:()=>void u(),type:`button`,children:i(b===`apply`?`common.loading`:`capabilities.applyPreview`)})]}):null,(0,B.jsx)(Ub,{values:[{label:i(`capabilities.goalValue`),value:l.current},{label:i(l.machine_current?`capabilities.machineValue`:`capabilities.defaultValue`),value:l.machine_current??l.default}],t:i},c.capability_id)]})]})}function ex({goalId:e}){let{t}=Ji(),[n,r]=(0,z.useState)(null),[i,a]=(0,z.useState)(null),[o,s]=(0,z.useState)(!1);function c(){e&&(s(!0),a(null),Eg(e).then(r).catch(e=>a(e instanceof Error?e.message:t(`capabilities.loadFailed`))).finally(()=>s(!1)))}return(0,z.useEffect)(c,[e]),e?o&&!n?(0,B.jsxs)(`p`,{"aria-live":`polite`,className:`personal-capability-empty`,children:[(0,B.jsx)(Cm,{className:`personal-spin`,size:18}),t(`capabilities.loading`)]}):i?(0,B.jsxs)(`section`,{className:`personal-capability-error`,role:`alert`,children:[(0,B.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:t(`capabilities.loadFailed`)}),(0,B.jsx)(`small`,{children:i})]}),(0,B.jsxs)(`button`,{onClick:c,type:`button`,children:[(0,B.jsx)(Im,{"aria-hidden":!0,size:15}),t(`capabilities.retry`)]})]}):n?(0,B.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":n.revision,children:[(0,B.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:17}),t(`capabilities.atomicOverride`)]}),(0,B.jsx)(`p`,{children:t(`capabilities.atomicOverrideDescription`)})]}),(0,B.jsx)($b,{catalog:n.capability_catalog,goalId:e,onApplied:c})]}):null:(0,B.jsx)(`p`,{className:`personal-capability-empty`,children:t(`capabilities.chooseGoal`)})}function tx(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function nx(e,t){let n=t?.machine_namespace;return n?e?.machine_configuration?.namespaces[n]:void 0}function rx(e,t,n){return{...tx(e.default),...tx(t),...n}}function ix(e,t){for(let n of e.configuration_editor.fields){let e=t[n.key];if(n.required&&(e==null||e===``))return!1}return e.capability_id===`periodic_report`&&t.enabled===!0?!!(String(t.profile_preset??``).trim()&&String(t.route_ref??``).trim()&&String(t.timezone??``).trim()):!0}function ax(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:null}catch{return null}}function ox(e){return e?e===`absent`?e:e.replace(/^sha256:/,``).slice(0,12):`—`}function sx(){let{locale:e,t}=Ji(),[n,r]=(0,z.useState)(null),[i,a]=(0,z.useState)(``),[o,s]=(0,z.useState)({}),[c,l]=(0,z.useState)(`{}`),[u,d]=(0,z.useState)(`guided`),[f,p]=(0,z.useState)(null),[m,h]=(0,z.useState)(`upsert`),[g,_]=(0,z.useState)(null),[v,y]=(0,z.useState)(null),[b,x]=(0,z.useState)(`load`),[S,C]=(0,z.useState)(null),[w,T]=(0,z.useState)(null),E=(0,z.useMemo)(()=>qb(n?.capability_catalog.capabilities??[],e),[n,e]),D=E.find(e=>e.capability_id===i)??E.find(e=>Hb(e,`machine`))??E[0],O=D?Bb(D,e):void 0,ee=nx(n,O),te=!!(O?.machine_namespace&&ee),ne=!!(O&&Hb(O,`machine`)),k=(0,z.useMemo)(()=>ax(c),[c]),A=O?u===`json`?k:rx(O,ee,o):null,j=!!(O&&(u===`json`?k:ix(O,A??{})));async function M(){r(await Tg())}(0,z.useEffect)(()=>{let e=!0;return Tg().then(t=>{e&&r(t)}).catch(n=>{e&&C(n instanceof Error?n.message:t(`machine.loadError`))}).finally(()=>{e&&x(null)}),()=>{e=!1}},[t]),(0,z.useEffect)(()=>{if(!O)return;let e=nx(n,O),t=Mb(O.configuration_editor,e??O.default,O.default),r=rx(O,e,t);s(t),l(JSON.stringify(r,null,2)),d(ne?`guided`:`json`),p(null),h(`upsert`),y(null)},[n,i,e]);function N(e,t){s(n=>O?.capability_id===`periodic_report`?Pb(n,e,t):{...n,[e]:t}),p(null),h(`upsert`),C(null),T(null)}function P(e){if(O){if(e===`json`)l(JSON.stringify(rx(O,ee,o),null,2));else if(k)s(Mb(O.configuration_editor,k,O.default));else{C(t(`machine.jsonInvalid`));return}d(e),p(null),h(`upsert`),C(null)}}async function F(){if(!(!ne||!O?.machine_namespace||!A||!j||b)){x(`preview`),C(null),T(null);try{h(`upsert`),p(await kg(O.machine_namespace,A))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function re(){if(!(!ne||!O?.machine_namespace||!te||b)){x(`preview`),C(null),T(null);try{h(`remove`),p(await jg(O.machine_namespace))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function ie(){if(!ne||!O?.machine_namespace||!f||b||m===`upsert`&&!A)return;x(`apply`),C(null);let e=m;try{let n=e===`remove`?await Mg(O.machine_namespace,f.plan_revision):await Ag(O.machine_namespace,A,f.plan_revision);_(n),p(null),h(`upsert`),y(null),await M(),T(n.status===`applied`?t(e===`remove`?`machine.removed`:`machine.applied`):t(`machine.unchanged`))}catch(e){p(null),h(`upsert`),C(e instanceof Error?e.message:t(`machine.applyError`))}finally{x(null)}}async function I(){if(!(!g?.transaction_id||b)){x(`rollback-preview`),C(null);try{y(await Ng(g.transaction_id))}catch(e){C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}async function ae(){if(!(!g?.transaction_id||!v||b)){x(`rollback`),C(null);try{await Pg(g.transaction_id,v.plan_revision),_(null),y(null),p(null),await M(),T(t(`machine.rolledBack`))}catch(e){y(null),C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}return b===`load`?(0,B.jsx)(`div`,{className:`personal-machine-loading`,role:`status`,children:t(`common.loading`)}):O?(0,B.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":n?.revision,children:[(0,B.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:17}),t(`machine.liveDefault`)]}),(0,B.jsx)(`p`,{children:t(`machine.liveDefaultDescription`)})]}),(0,B.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,B.jsx)(Jb,{capabilities:E,locale:e,onSelect:a,scope:`machine`,selectedCapabilityId:O.capability_id,t}),(0,B.jsxs)(`article`,{"aria-label":O.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,B.jsx)(Yb,{capability:D,locale:e,source:O.available_scopes.includes(`machine`)?te?`machine_default`:`capability_default`:void 0}),(0,B.jsx)(Gb,{available:ne,t,description:O.available_scopes.includes(`machine`)?t(`machine.editorUnavailableDescription`):t(`machine.goalOnly`)}),O.capability_id===`periodic_report`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:ee?.schedule?e===`zh-CN`?`日历与阶段汇报`:`Calendar and stage reports`:t(`machine.periodicReportActivation`)}),(0,B.jsx)(`p`,{children:ee?.schedule?ee.enabled===!0?e===`zh-CN`?`已配置日历计划,由现有唤醒检查;是否送达请核对报告回执。`:`A calendar schedule is configured and checked by existing wakes. Verify delivery in the report receipt.`:e===`zh-CN`?`日历计划已保存;启用此能力后才会检查和投递。`:`The schedule is saved; enable this capability to check and deliver reports.`:t(`machine.periodicReportActivationDescription`)})]})]}):null,O.capability_id===`change_quality_qualification`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.changeQualityActivation`)}),(0,B.jsx)(`p`,{children:t(`machine.changeQualityActivationDescription`)})]})]}):null,O.capability_id===`todo_replan_cadence`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.replanCadenceActivation`)}),(0,B.jsx)(`p`,{children:t(`machine.replanCadenceActivationDescription`)})]})]}):null,O.capability_id===`pull_request_review`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:e===`zh-CN`?`只改变队列排序`:`Queue ordering only`}),(0,B.jsx)(`p`,{children:e===`zh-CN`?`默认先审阅其他开发者的 PR;选择 owner-first 才会优先当前已认证审阅者自己的 PR。此配置不会发布 review、写 Todo、push 或 merge。`:`The default reviews other developers' PRs first; choose owner-first only when the authenticated reviewer's own PRs should lead. This setting never posts a review, writes Todos, pushes, or merges.`})]})]}):null,ne?(0,B.jsxs)(B.Fragment,{children:[u===`json`||!O.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,B.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,B.jsxs)(`button`,{onClick:()=>P(u===`guided`?`json`:`guided`),type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),t(u===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,u===`guided`?(0,B.jsxs)(`section`,{className:`personal-capability-field-summary`,children:[(0,B.jsx)(Lb,{copy:Vb(e),disabled:!!b,editor:O.configuration_editor,onChange:N,value:o,enabledAction:(0,B.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:()=>P(`json`),type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),t(`machine.editJson`)]})}),j?null:(0,B.jsx)(`p`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.requiredFields`)})]}):(0,B.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`machine-configuration-json`,children:[(0,B.jsx)(`span`,{children:t(`machine.jsonConfiguration`)}),(0,B.jsx)(`textarea`,{"aria-describedby":`machine-configuration-json-help`,disabled:!!b,id:`machine-configuration-json`,onChange:e=>{l(e.target.value),p(null),C(null)},rows:12,spellCheck:!1,value:c}),(0,B.jsx)(`small`,{id:`machine-configuration-json-help`,children:t(`machine.jsonConfigurationHelp`)}),k?null:(0,B.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.jsonInvalid`)})]})]}):null,S?(0,B.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:S}):null,w?(0,B.jsxs)(`p`,{className:`personal-machine-notice`,role:`status`,"aria-live":`polite`,children:[(0,B.jsx)(em,{"aria-hidden":!0,size:16}),w]}):null,f?(0,B.jsxs)(`section`,{"aria-label":t(`machine.preview`),className:`personal-machine-preview`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.preview`)}),(0,B.jsx)(`span`,{children:t(`machine.action.${f.action}`)})]}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`machine.currentRevision`)}),(0,B.jsx)(`dd`,{title:f.current_revision,children:ox(f.current_revision)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`machine.desiredRevision`)}),(0,B.jsx)(`dd`,{title:f.desired_revision,children:ox(f.desired_revision)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`machine.changedNamespaces`)}),(0,B.jsx)(`dd`,{children:f.changed_namespaces.join(`, `)||t(`common.none`)})]})]}),(0,B.jsx)(`p`,{children:t(`machine.previewLocked`)})]}):null,g?.rollback_available&&g.transaction_id?(0,B.jsxs)(`section`,{className:`personal-machine-rollback`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.rollbackAvailable`)}),(0,B.jsx)(`p`,{children:t(v?`machine.rollbackPreviewDescription`:`machine.rollbackDescription`)})]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!!b||!!(v&&!v.rollback_allowed),onClick:()=>void(v?ae():I()),type:`button`,children:[(0,B.jsx)(Lm,{"aria-hidden":!0,size:15}),t(b===`rollback`||b===`rollback-preview`?`common.loading`:v?`machine.confirmRollback`:`machine.previewRollback`)]})]}):null,ne?(0,B.jsxs)(`footer`,{className:`personal-capability-actions`,children:[te?(0,B.jsxs)(`button`,{className:`is-danger`,disabled:!!b,onClick:()=>void re(),type:`button`,children:[(0,B.jsx)(Xm,{"aria-hidden":!0,size:15}),t(`machine.previewRemoval`)]}):null,(0,B.jsx)(`button`,{disabled:!!b||!j,onClick:()=>void F(),type:`button`,children:t(b===`preview`?`common.loading`:`machine.previewChanges`)}),(0,B.jsx)(`button`,{className:`is-primary`,disabled:!!b||!f,onClick:()=>void ie(),type:`button`,children:t(b===`apply`?`common.loading`:`machine.applyPreview`)})]}):null,O.available_scopes.includes(`machine`)?(0,B.jsx)(Ub,{values:[{label:t(`machine.currentValue`),value:ee},{label:t(`capabilities.defaultValue`),value:O.default}],t},O.capability_id):null]})]})]}):(0,B.jsx)(`p`,{className:`personal-capability-empty`,children:t(`machine.capabilityEmpty`)})}var cx={appearance:Am,capabilities:Gm,language:bm,lark:Um,machine:Vm};function lx({focusGoalConnection:e=!1,goals:t,initialGoalId:n,initialTab:r=`lark`,onChanged:i,onClose:a,onThemeChange:o,theme:s}){let{locale:c,setLocale:l,t:u}=Ji(),[d,f]=(0,z.useState)(r),p=[...n?[{key:`capabilities`,label:u(`capabilities.title`)}]:[],{key:`machine`,label:u(`machine.title`)},{key:`lark`,label:`Lark`},{key:`appearance`,label:u(`settings.appearance`)},{key:`language`,label:u(`settings.language`)}],m=[{label:u(`settings.languageEnglish`),value:`en`},{label:u(`settings.languageSimplifiedChinese`),value:`zh-CN`}],h={appearance:{title:u(`settings.appearance`)},capabilities:{title:u(`capabilities.title`)},language:{title:u(`settings.language`)},lark:{title:`Lark`},machine:{title:u(`machine.title`)}}[d];return(0,B.jsxs)(`section`,{"aria-label":u(`settings.title`),className:`personal-settings-page`,"data-pw-theme":s,children:[(0,B.jsxs)(`aside`,{className:`personal-settings-sidebar`,children:[(0,B.jsxs)(`button`,{className:`personal-settings-back`,onClick:a,type:`button`,children:[(0,B.jsx)(Gp,{size:17}),(0,B.jsx)(`span`,{children:u(`settings.back`)})]}),(0,B.jsxs)(`div`,{className:`personal-settings-title`,children:[(0,B.jsx)(`small`,{children:u(`settings.eyebrow`)}),(0,B.jsx)(`strong`,{children:u(`settings.title`)})]}),(0,B.jsx)(`nav`,{"aria-label":u(`settings.categories`),className:`personal-settings-tabs`,children:p.map(e=>{let t=cx[e.key];return(0,B.jsxs)(`button`,{"aria-current":d===e.key?`page`:void 0,onClick:()=>f(e.key),type:`button`,children:[(0,B.jsx)(t,{size:17}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:e.label})})]},e.key)})})]}),(0,B.jsxs)(`main`,{className:`personal-settings-body`,children:[(0,B.jsx)(`header`,{className:`personal-settings-header`,children:(0,B.jsx)(`div`,{children:(0,B.jsx)(`h1`,{children:h.title})})}),d===`lark`?(0,B.jsx)(Ab,{embedded:!0,focusGoalConnection:e,goals:t,initialGoalId:n,onChanged:i,onClose:a}):null,d===`machine`?(0,B.jsx)(sx,{}):null,d===`capabilities`?(0,B.jsx)(ex,{goalId:n}):null,d===`appearance`?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-appearance-settings`,children:[(0,B.jsx)(`small`,{children:u(`settings.workspaceDisplay`)}),(0,B.jsx)(`h3`,{children:u(`settings.appearance`)}),(0,B.jsxs)(`div`,{className:`personal-settings-choice-group`,role:`radiogroup`,"aria-label":u(`settings.workspaceTheme`),children:[(0,B.jsxs)(`button`,{"aria-checked":s===`loopx`,onClick:()=>o(`loopx`),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-settings-theme-swatch is-loopx`}),(0,B.jsx)(`strong`,{children:u(`settings.themeLoopx`)})]}),(0,B.jsxs)(`button`,{"aria-checked":s===`paper`,onClick:()=>o(`paper`),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-settings-theme-swatch is-paper`}),(0,B.jsx)(`strong`,{children:u(`settings.themeDefault`)})]}),(0,B.jsxs)(`button`,{"aria-checked":s===`brutal`,onClick:()=>o(`brutal`),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-settings-theme-swatch is-brutal`}),(0,B.jsx)(`strong`,{children:u(`settings.themeHighContrast`)})]})]})]}):null,d===`language`?(0,B.jsxs)(`section`,{className:`personal-settings-card`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`span`,{className:`personal-settings-icon`,children:(0,B.jsx)(bm,{size:18})}),(0,B.jsx)(`div`,{children:(0,B.jsx)(`h2`,{children:u(`settings.language`)})})]}),(0,B.jsx)(`div`,{"aria-label":u(`settings.language`),className:`personal-language-options`,role:`radiogroup`,children:m.map(e=>(0,B.jsxs)(`button`,{"aria-checked":c===e.value,className:c===e.value?`is-selected`:``,onClick:()=>l(e.value),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:e.label})}),c===e.value?(0,B.jsx)(em,{"aria-hidden":!0,size:17}):null]},e.value))})]}):null]})]})}var ux=`loopx-pw-theme`,dx=`loopx`;function fx(){try{let e=window.localStorage.getItem(ux);return e===`loopx`||e===`paper`||e===`brutal`?e:dx}catch{return dx}}function px(e){try{window.localStorage.setItem(ux,e)}catch{}}function mx({drawer:e,drawerMode:t=`panel`,drawerOpen:n,main:r,mobileSidebarOpen:i=!1,onCloseMobileSidebar:a,sidebar:o,theme:s=`loopx`}){let{t:c}=Ji(),l=(0,z.useRef)(null),u=(0,z.useRef)(null);return(0,z.useEffect)(()=>{if(!i)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null;let e=l.current?.querySelectorAll(`button:not([disabled]), a[href], select:not([disabled]), textarea:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])`);e?.[0]?.focus();function t(t){if(t.key!==`Tab`||!e?.length)return;let n=e[0],r=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),r.focus()):!t.shiftKey&&document.activeElement===r&&(t.preventDefault(),n.focus())}return document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`keydown`,t),u.current?.focus(),u.current=null}},[i]),(0,B.jsxs)(`section`,{className:`personal-workspace-shell${n?` has-drawer`:``}${n&&t.startsWith(`inspector`)?` has-task-inspector`:``}${t===`inspector-full`?` is-task-inspector-full`:``}${i?` mobile-sidebar-open`:``}`,"data-pw-theme":s,children:[i?(0,B.jsx)(`button`,{"aria-hidden":!0,className:`personal-sidebar-backdrop`,onClick:a,tabIndex:-1,type:`button`}):null,(0,B.jsx)(`aside`,{"aria-label":i?c(`header.goalNavigation`):void 0,"aria-modal":i?!0:void 0,className:`personal-workspace-sidebar`,"data-workspace-sidebar":!0,ref:l,role:i?`dialog`:void 0,children:(0,B.jsxs)(`div`,{className:`personal-workspace-sidebar-inner`,children:[i?(0,B.jsxs)(`button`,{className:`personal-sr-only`,onClick:a,type:`button`,children:[c(`common.close`),` `,c(`header.goalNavigation`)]}):null,o]})}),(0,B.jsx)(`main`,{"aria-hidden":i||void 0,className:`personal-workspace-main`,inert:i||void 0,children:r}),n?(0,B.jsx)(`aside`,{className:`personal-workspace-drawer`,"data-context-drawer":!0,"data-drawer-mode":t,children:e}):null]})}function hx(e){let t=e.match(/(?:下一步|建议|行动项|待办)[::\s]*([^\n]+)/u),n=t?t[1]:e;n=n.replace(/```[\s\S]*?```/g,``).replace(/`([^`]+)`/g,`$1`).replace(/\[([^\]]+)\]\([^)]+\)/g,`$1`).replace(/[#*~_>]/g,``).replace(/^[-*•\d+.\s]+/u,``).replace(/^(好的|没问题|收到|建议如下|任务如下|分析如下|结论[::])[\s,,::]*/u,``);let r=(n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean)[0]||n).replace(/\s+/gu,` `).trim();return Array.from(r).slice(0,120).join(``)}function gx(e){let t=new Map;return e.forEach(e=>{let n=e.fields.find(e=>e.key===`todo_id`)?.value??``,r=[e.actionKind,e.goalId??``,n,e.title].join(`:`);t.set(r,e)}),[...t.values()]}function _x(e,t,n){if(!e)return n(`home.noFirstActivity`);let r=new Date(e);if(Number.isNaN(r.getTime()))return e;let i=new Date,a=new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r);return r.toDateString()===i.toDateString()?n(`home.todayAt`,{time:a}):new Intl.DateTimeFormat(t,{month:`numeric`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r)}function vx({goals:e,onSelectGoal:t,onRetry:n,systemHealth:r}){let{locale:i,t:a}=Ji(),o=e.filter(e=>e.activationState===`active`),s=o.filter(e=>e.loadState===`error`).length,c=[{key:`needs_you`,label:a(`home.lane.needsYou`)},{key:`running`,label:a(`home.lane.running`)},{key:`observing`,label:a(`home.lane.observing`)},{key:`scheduled`,label:a(`home.lane.scheduled`)}],l=Object.fromEntries(c.map(e=>[e.key,[]])),u=[],d=[];e.filter(e=>!e.loadState).forEach(e=>{let t=gy(e);t===`history`?u.push(e):t===`stopped`?d.push(e):l[t].push(e)});let f=e=>(0,B.jsxs)(`button`,{className:`personal-home-goal-card`,"data-goal-state":e.loadState??e.state,"data-load-error":e.loadError,onClick:()=>t(e.goalId),type:`button`,children:[(0,B.jsxs)(`span`,{className:`personal-home-goal-meta`,children:[(0,B.jsx)(`i`,{}),e.agentLaneCount&&e.agentLaneCount>1?a(`header.workAgentCount`,{count:e.agentLaneCount}):e.agentLabel??e.agentId]}),(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsx)(`p`,{children:e.loadError?a(`startup.error.${e.loadError}`):e.needsYou??e.nextSentence}),(0,B.jsxs)(`footer`,{children:[(0,B.jsx)(`span`,{children:e.loadState?a(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Yi(e.state,i)}),(0,B.jsx)(`small`,{title:e.latestActivity,children:e.loadState?``:e.latestActivity?_x(e.latestActivity,i,a):e.agentTodos.length?a(`home.taskCount`,{count:e.agentTodos.length}):a(`home.noActivity`)})]})]},e.goalId);return(0,B.jsxs)(`section`,{"aria-label":a(`home.workspace`),className:`personal-home-board`,children:[r&&(!r.ok||r.issues.length>0||r.freshnessWarning)?(0,B.jsxs)(`div`,{className:`personal-system-health-banner`,role:`alert`,children:[(0,B.jsxs)(`div`,{className:`personal-system-health-header`,children:[(0,B.jsx)(im,{size:15}),(0,B.jsx)(`strong`,{children:a(`home.systemHealth`,{summary:r.summary})}),r.freshnessWarning?(0,B.jsxs)(`small`,{children:[`(`,r.freshnessWarning,`)`]}):null]}),r.issues.length>0?(0,B.jsx)(`ul`,{className:`personal-system-health-issues`,children:r.issues.map((e,t)=>(0,B.jsx)(`li`,{children:e},t))}):null]}):null,o.some(e=>e.loadState)?(0,B.jsxs)(`section`,{className:`personal-home-lane`,"aria-live":`polite`,children:[(0,B.jsx)(`header`,{children:a(`startup.progress`,{loaded:o.filter(e=>!e.loadState).length,total:o.length})}),s?(0,B.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`status`,children:[(0,B.jsx)(`span`,{children:a(`startup.failedCount`,{count:s})}),(0,B.jsx)(`button`,{className:`min-h-11 rounded-md border px-3 py-2 text-sm`,onClick:n,type:`button`,children:a(`startup.retryFailed`)})]}):null,o.filter(e=>e.loadState).map(f)]}):null,(0,B.jsx)(`div`,{className:`personal-home-lanes`,children:c.map(e=>(0,B.jsxs)(`section`,{className:`personal-home-lane is-${e.key}`,"data-testid":`personal-home-lane-${e.key}`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`i`,{}),e.label]}),(0,B.jsx)(`b`,{children:l[e.key].length})]}),(0,B.jsx)(`div`,{className:`personal-home-lane-list`,children:l[e.key].length?l[e.key].map(f):(0,B.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.empty`)})})]},e.key))}),(0,B.jsxs)(`details`,{className:`personal-home-history`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(`span`,{children:a(`home.history`)}),(0,B.jsx)(`b`,{children:u.length}),(0,B.jsx)(`small`,{children:a(`home.completedGoals`)})]}),(0,B.jsx)(`div`,{children:u.length?u.map(f):(0,B.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.noCompletedGoals`)})})]}),d.length?(0,B.jsxs)(`details`,{className:`personal-home-history is-stopped`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(`span`,{children:a(`home.stopped`)}),(0,B.jsx)(`b`,{children:d.length}),(0,B.jsx)(`small`,{children:a(`home.preservedState`)})]}),(0,B.jsx)(`div`,{children:d.map(f)})]}):null]})}function yx({items:e,onSelect:t,reportState:n}){let{locale:r,t:i}=Ji();return(0,B.jsxs)(`section`,{className:`personal-object-list personal-files-list`,"data-testid":`personal-goal-outputs`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:i(`files.title`)}),(0,B.jsx)(`span`,{children:e.length})]}),n?.loading?(0,B.jsxs)(`p`,{className:`personal-object-list-state`,role:`status`,children:[(0,B.jsx)(Im,{className:`is-spinning`,size:14}),i(`files.loadingReports`)]}):null,n?.error?(0,B.jsxs)(`p`,{className:`personal-object-list-state is-error`,role:`alert`,children:[(0,B.jsx)(im,{size:14}),i(`files.reportLoadFailed`),`: `,n.error]}):null,!n?.loading&&!n?.error&&e.length===0?(0,B.jsxs)(`p`,{className:`personal-object-list-state`,children:[(0,B.jsx)(gm,{size:14}),i(`files.empty`)]}):null,e.map(e=>(0,B.jsxs)(`button`,{"data-output-kind":e.output.kind,onClick:()=>t({item:e.output,kind:`output`}),type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-file-icon`,children:(0,B.jsx)(gm,{size:16})}),(0,B.jsx)(`strong`,{children:e.output.title}),e.output.report?(0,B.jsx)(`em`,{children:i(`files.reportDelta`,{added:e.output.report.addedCount,changed:e.output.report.changedCount})}):null,(0,B.jsx)(`p`,{children:e.output.summary??e.output.safePreview??e.output.kind??i(`files.emptySummary`)}),(0,B.jsx)(`small`,{title:e.output.createdAt,children:[e.output.goalTitle,e.output.kind===`report`?i(`files.verifiedReport`):null,e.output.todoId?`${i(`common.task`)} ${e.output.todoId}`:null,_x(e.output.createdAt,r,i)].filter(Boolean).join(` · `)})]},e.id))]})}function bx({agentLabel:e,messages:t,onClose:n,onDraftTask:r,onOpenConversation:i,title:a}){let{t:o}=Ji(),s=t.reduce((e,t,n)=>t.role===`user`?n:e,0),c=t.slice(Math.max(0,s)).slice(-3),l=c.filter(e=>e.role===`assistant`&&!e.pending).at(-1);return(0,z.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),(0,B.jsxs)(`aside`,{"aria-label":o(`conversation.receipt`),className:`personal-manager-conversation-tray`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:16}),(0,B.jsx)(`strong`,{children:a??o(`conversation.title`)}),(0,B.jsx)(`small`,{children:t.at(-1)?.pending?o(`conversation.replying`):o(`common.recently`)})]}),(0,B.jsxs)(`div`,{className:`personal-manager-conversation-actions`,children:[r&&l?(0,B.jsxs)(`button`,{className:`personal-manager-conversation-btn`,onClick:()=>r(l.text),title:o(`conversation.convertHint`),type:`button`,children:[(0,B.jsx)(Sm,{size:13}),(0,B.jsx)(`span`,{children:o(`conversation.toTask`)})]}):null,(0,B.jsx)(`button`,{className:`personal-manager-conversation-link`,onClick:i,type:`button`,children:o(`conversation.full`)}),n?(0,B.jsx)(`button`,{"aria-label":o(`conversation.close`),className:`personal-manager-conversation-close`,onClick:n,title:o(`conversation.close`),type:`button`,children:(0,B.jsx)($m,{size:14})}):null]})]}),(0,B.jsx)(`div`,{"aria-live":`polite`,className:`personal-manager-conversation-messages`,children:c.map(t=>(0,B.jsxs)(`article`,{className:`is-${t.role}`,children:[(0,B.jsx)(`strong`,{children:t.role===`user`?o(`common.you`):t.agentLabel??e??o(`header.manager`)}),(0,B.jsxs)(`div`,{className:`personal-manager-conversation-bubble`,children:[t.role===`user`?(0,B.jsx)(`p`,{children:t.text}):(0,B.jsx)(jy,{text:t.text}),t.pending?(0,B.jsx)(`small`,{children:o(`conversation.agentPending`)}):null]})]},t.id))})]})}function xx({onClose:e,onOpenDetails:t,run:n}){let{t:r}=Ji();return(0,B.jsxs)(`section`,{"aria-label":r(`session.record`),className:`personal-session-record`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:17}),r(`session.record`)]}),(0,B.jsx)(`button`,{"aria-label":r(`session.closeRecord`),onClick:e,type:`button`,children:(0,B.jsx)($m,{size:15})})]}),(0,B.jsx)(`div`,{children:(0,B.jsx)(`strong`,{children:n.title})}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Agent`}),(0,B.jsx)(`dd`,{children:n.agentLabel})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`common.status`)}),(0,B.jsx)(`dd`,{children:Xi(n.sessionStatus??n.status,r)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Session`}),(0,B.jsx)(`dd`,{title:n.sessionId,children:n.sessionId})]})]}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:t,type:`button`,children:r(`session.details`)})]})}function Sx(e,t,n){let r=[];if(t===null)return e.userTodos.slice(0,4).forEach(t=>r.push({attention:{...t,goalTitle:t.goalTitle??hy(e,t.goalId)},id:`attention:${t.todoId}`,kind:`attention`})),e.goals.filter(e=>gy(e)===`running`).slice(0,4).forEach(e=>r.push({id:`run:${e.goalId}`,kind:`run`,run:{agentId:e.agentId,agentLabel:e.agentLabel??e.agentId,completedSteps:e.doneTodoCount??e.agentTodos.filter(e=>e.done).length,goalId:e.goalId,goalTitle:e.title,latestActivity:e.agentSentence,runId:`goal:${e.goalId}`,status:`running`,title:e.nextSentence,totalSteps:Math.max((e.doneTodoCount??0)+e.agentTodos.filter(e=>!e.done).length,1)}})),r;let i=e.goals.find(e=>e.goalId===t);if(!i)return r;if(i.needsYou){let t=e.userTodos.find(e=>e.goalId===i.goalId);r.push({attention:t?{...t,goalTitle:i.title}:{blocking:i.needsYouBlocking??!1,goalId:i.goalId,goalTitle:i.title,text:i.needsYou,todoId:`${i.goalId}:attention`},id:`attention:${i.goalId}`,kind:`attention`})}r.push({id:`run:${i.goalId}`,kind:`run`,run:{agentId:i.agentId,agentLabel:i.agentLabel??i.agentId,completedSteps:i.doneTodoCount??i.agentTodos.filter(e=>e.done).length,goalId:i.goalId,goalTitle:i.title,latestActivity:i.agentSentence,runId:`goal:${i.goalId}`,status:i.state===`推进中`?`running`:i.state===`需修复`?`failed`:`waiting`,title:i.nextSentence,totalSteps:Math.max((i.doneTodoCount??0)+i.agentTodos.filter(e=>!e.done).length,1)}}),i.agentTodos.filter(e=>e.taskClass===`continuous_monitor`).forEach(t=>{let a=e.timeline?.find(e=>e.kind===`run`&&e.run.goalId===i.goalId&&e.run.todoId===t.todoId&&!!e.run.sessionId);r.push({id:`schedule:${i.goalId}:${t.todoId}`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:a?[{label:a.run.latestActivity||a.run.title,runId:a.run.runId,status:a.run.status===`waiting`||a.run.status===`queued`?`running`:a.run.status,timestamp:i.latestActivity||n(`common.recently`)}]:[],goalId:i.goalId,label:t.text,schedule:t.evidence??n(`schedule.summary`),scheduleId:t.todoId,scheduleKind:`monitor`,sessionId:a?.run.sessionId,status:t.done||t.status===`paused`?`paused`:`active`,stopCondition:n(`drawer.scheduleDefaultStop`),target:t.text,timezone:`Asia/Shanghai`}})});let a=e.timeline?.find(e=>e.kind===`proposal`&&e.proposal.actionKind===`heartbeat.bind`&&e.proposal.goalId===i.goalId);if(a){let e=e=>a.proposal.fields.find(t=>t.key===e)?.value;r.push({id:`schedule:${i.goalId}:heartbeat`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:[],goalId:i.goalId,label:`${n(`schedule.heartbeat`)} · ${i.title}`,nextRunAt:n(`drawer.schedulePending`),notificationRule:n(`drawer.scheduleDefaultNotification`),schedule:e(`cadence`)??n(`schedule.summary`),scheduleId:`${i.goalId}:heartbeat`,scheduleKind:`heartbeat`,status:a.proposal.status===`applied`?`active`:`draft`,stopCondition:e(`stop_condition`)??n(`drawer.scheduleDefaultStop`),timezone:e(`timezone`)??`Asia/Shanghai`}})}return r}function Cx(e){return e===`preview_ready`?`ready`:e===`cancelled`?`draft`:e===`failed`?`error`:e}function wx(e,t){let n={agent_id:t(`proposal.field.agentId`),cadence:t(`proposal.field.cadence`),completion_criteria:t(`proposal.field.completionCriteria`),execution_boundary:t(`proposal.field.executionBoundary`),goal_id:t(`proposal.field.goalId`),heartbeat:t(`proposal.field.heartbeat`),initial_todos:t(`proposal.field.initialTodos`),objective:t(`proposal.field.objective`),operation:t(`proposal.field.operation`),permission:t(`proposal.field.permission`),reason:t(`proposal.field.reason`),stop_condition:t(`proposal.field.stopCondition`),target:t(`proposal.field.target`),timezone:t(`proposal.field.timezone`),title:t(`proposal.field.title`),workspace_ref:t(`proposal.field.workspace`)},r=[`title`,`objective`,`completion_criteria`,`execution_boundary`,`permission`,`agent_id`,`workspace_ref`,`initial_todos`,`heartbeat`,`stop_condition`,`goal_id`];return Object.entries(e).sort(([e],[t])=>{let n=r.indexOf(e),i=r.indexOf(t);return(n<0?r.length:n)-(i<0?r.length:i)}).slice(0,10).map(([e,r])=>({key:e,label:n[e]??e.replaceAll(`_`,` `),value:e===`workspace_ref`?r===`current`?t(`proposal.workspace.current`):t(`proposal.workspace.named`,{workspace:String(r??`current`)}):Array.isArray(r)?r.join(` · `):typeof r==`object`&&r?JSON.stringify(r):String(r??`—`)}))}function Tx(e,t){let n=e.normalized_parameters.projection,r=n&&typeof n==`object`?n:{},i=Array.isArray(r.fields)?r.fields.flatMap((e,t)=>{if(!e||typeof e!=`object`)return[];let n=e;return typeof n.label!=`string`||typeof n.value!=`string`?[]:[{key:`projection:${t}`,label:n.label,value:n.value}]}).slice(0,8):[];return[{key:`operation_state`,label:t(`proposal.field.operationState`),value:e.operation?.lifecycle_state??e.status},...i,...typeof r.warning==`string`?[{key:`warning`,label:t(`proposal.field.confirmationBoundary`),value:r.warning}]:[],...e.operation?.expires_at?[{key:`expires_at`,label:t(`proposal.field.expiresAt`),value:e.operation.expires_at}]:[]].slice(0,10)}function Ex(e){if(e.action_kind!==`goal.lifecycle`)return;let t=e.normalized_parameters.operation;return t===`stop`||t===`resume`||t===`delete`?t:void 0}function Dx(e,t){let n=Ex(e),r=fy(e),i=typeof e.normalized_parameters.title==`string`?e.normalized_parameters.title:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:``,a=typeof e.normalized_parameters.target==`string`?e.normalized_parameters.target:``,o=e.normalized_parameters.projection,s=o&&typeof o==`object`&&typeof o.title==`string`?String(o.title):e.summary,c=e.action_kind===`operation.execute`?s:e.action_kind===`goal.create`?t(`proposal.summary.goalCreate`,{title:i}):e.action_kind===`heartbeat.bind`?t(`proposal.summary.heartbeat`):e.action_kind===`monitor.create`?t(`proposal.summary.monitor`,{target:a}):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.summary.lifecycleStop`,{title:i}):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.summary.lifecycleDelete`,{title:i}):e.action_kind===`goal.lifecycle`?t(`proposal.summary.lifecycleResume`,{title:i}):e.summary;return{actionKind:e.action_kind,reviewPlan:r,fields:e.action_kind===`operation.execute`?Tx(e,t):wx(e.normalized_parameters,t),goalId:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:void 0,impact:e.action_kind===`operation.execute`?t(`proposal.impact.operation`):e.action_kind===`goal.create`?t(`proposal.impact.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.impact.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.impact.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.impact.lifecycleResume`):e.permission_classification===`protected`?t(`proposal.impact.protected`):t(`proposal.impact.default`),previewId:e.proposal_id,lifecycleOperation:n,gate:e.gate?{kind:String(e.gate.kind??`protected_action`),nextAction:typeof e.gate.next_action==`string`?e.gate.next_action:void 0,summary:String(e.gate.summary??t(`proposal.gate.default`))}:void 0,primaryLabel:e.action_kind===`operation.execute`?t(`proposal.primary.operationGroup`):e.action_kind===`goal.create`?t(`proposal.primary.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.primary.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.primary.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.primary.lifecycleResume`):e.action_kind===`todo.create`&&e.normalized_parameters.start_execution===!0?t(`proposal.primary.todoStart`):t(`proposal.primary.apply`),status:e.status===`applied`&&r.interaction!==`completed`?`error`:Cx(e.status),title:c}}function Ox(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,42);if(t)return t;let n=2166136261;for(let t of e)n^=t.codePointAt(0)??0,n=Math.imul(n,16777619);return`goal-${(n>>>0).toString(36)}`}function kx(e,t){let n=e.match(/[「“"]([^」”"]{2,80})[」”"]/u)?.[1];return n?n.trim():e.replace(/^(请|帮我|我想|给我|创建|新建|设置|please|i want to|create|set up)+/iu,``).replace(/(一个|新的)?\s*(goal|目标)/giu,``).replace(/[,。!?].*$/u,``).trim().slice(0,80)||t(`goal.defaultTitle`)}function Ax(e,t){for(let n of e.split(/\r?\n/u)){let e=n.trim();for(let n of t){let t=e.match(RegExp(`^${n.replace(/[.*+?^${}()|[\]\\]/gu,`\\$&`)}\\s*[::]\\s*(.*)$`,`iu`));if(t?.[1]?.trim())return t[1].trim()}}return``}function jx(e,t){let n=Ax(e,[`目标`,`Objective`]),r=Ax(e,[`完成标准`,`Completion criteria`]),i=Ax(e,[`执行边界(可选)`,`执行边界`,`边界`,`Execution boundary (optional)`,`Execution boundary`,`Boundary`]),a=(n||kx(e,t)).split(/[。;;\n]/u)[0].trim().slice(0,80)||t(`goal.defaultTitle`),o=[n||a,r?t(`goal.objectiveCompletion`,{criteria:r}):``,i?t(`goal.objectiveBoundary`,{boundary:i}):``].filter(Boolean).join(` -`),s=/(只读|不调用外部工具|不修改(?:仓库|代码|状态)|read.?only|do not (?:call|use) external tools|do not modify (?:repositories|repository|code|state))/iu.test(i||e);return{completionCriteria:r,executionBoundary:i,initialTodos:r?[t(`goal.initialTodo`,{criteria:r})]:[],objective:o,permission:s?`read_only`:`workspace_write_on_confirmation`,title:a}}function Mx(e){let t=e.match(/(?:每|every)\s*(\d{1,3})\s*(?:分钟|minutes?)/iu)?.[1];if(t)return`${t}m`;let n=e.match(/(?:每|every)\s*(\d{1,2})\s*(?:小时|hours?)/iu)?.[1];return n?`${n}h`:/每小时|every hour|hourly/iu.test(e)?`1h`:(/每天|每日|早上|上午|daily|every day/iu.test(e),`1d`)}function Nx(e,t){return/(每周|星期|周[一二三四五六日天]|weekly|every\s+(?:mon|tues|wednes|thurs|fri|satur|sun)day|\d{1,2}\s*[::]\s*\d{2})/iu.test(e)?t(`schedule.unsupportedCalendar`):null}function Px(e,t){return Ax(e,[`检查内容`,`监控内容`,`目标`,`Check target`,`Monitor target`,`Target`])||e.replace(/^(?:为当前 Goal |for the current Goal )?(?:添加|配置|创建|add|configure|create)?\s*(?:定时检查|监控|scheduled check|monitor)[::]?/iu,``).split(/\r?\n/u)[0].trim()||t(`schedule.defaultTarget`)}function Fx(e){return/(mr|pr).{0,8}(合并|merge)/iu.test(e)?`pr_merged`:/发布完成|上线完成|release (?:is )?complete|deployment (?:is )?complete/iu.test(e)?`release_complete`:`goal_complete`}function Ix(e,t){let n=e.toLowerCase();return t.find(e=>n.includes(e.agentId.toLowerCase())||n.includes(e.label.toLowerCase()))}function Lx(e){let t=Ax(e,[`标题`,`任务标题`,`Todo 标题`]),n=Ax(e,[`内容`,`任务内容`,`Todo 内容`]);if(t)return[t,n].filter(Boolean).join(`:`).slice(0,400);let r=e.match(/[「“"]([^」”"]{2,200})[」”"]/u)?.[1];return r?r.trim():e.replace(/^(请|帮我|给我|为当前 Goal |新增|新建|创建|添加|加上|加一个|记一个)+/u,``).replace(/^(一个\s*)?(普通\s*)?(todo|待办|任务)(?:\s*到\s*Tasks?)?[::\s]*/iu,``).replace(/[。;;,,]\s*(?:不要|不需要|无需|禁止|别|暂不).{0,80}(?:heartbeat|心跳|定时|监控|执行).*$/iu,``).replace(/[,,]\s*(并且|然后|再)?\s*(交给|分配给|让).+$/u,``).replace(/\s*(交给|分配给|让)\s+.+$/u,``).trim().slice(0,400)||`推进当前 Goal 的下一项工作`}var Rx=new Set([`image/png`,`image/jpeg`,`image/webp`,`image/gif`]),zx=5242880,Bx=4;function Vx(e,t){return new Promise((n,r)=>{let i=new FileReader;i.onerror=()=>r(Error(t(`composer.imageReadError`,{name:e.name}))),i.onload=()=>n({dataUrl:String(i.result??``),id:crypto.randomUUID(),mimeType:e.type,name:e.name,size:e.size}),i.readAsDataURL(e)})}function Hx({agents:e=[{agentId:`codex`,available:!0,capability:`代码与项目执行`,label:`Codex`}],callbacks:t={},goalArchiveLoadState:n={error:null,phase:`ready`},model:r,readOnly:i=!1,selectedAgentId:a,selectedGoalId:o,statusSourceControl:s}){let{locale:c,t:l}=Ji(),[u,d]=(0,z.useState)(o??null),[f,p]=(0,z.useState)(a??e.find(e=>e.available)?.agentId??`codex`),[m,h]=(0,z.useState)(null),[g,_]=(0,z.useState)(!1),[v,y]=(0,z.useState)(null),[b,x]=(0,z.useState)({}),[S,C]=(0,z.useState)(`chat`),[w,T]=(0,z.useState)(!1),[E,D]=(0,z.useState)(!1),[O,ee]=(0,z.useState)(!1),[te,ne]=(0,z.useState)(()=>{try{let e=window.sessionStorage.getItem(`loopx-pw-composer-drafts`),t=e?JSON.parse(e):{};return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}),[k,A]=(0,z.useState)(!1),[j,M]=(0,z.useState)([]),[N,P]=(0,z.useState)(null),[F,re]=(0,z.useState)(null),[ie,I]=(0,z.useState)(()=>new Set),[ae,L]=(0,z.useState)(()=>new Set),[oe,se]=(0,z.useState)(`idle`),[ce,le]=(0,z.useState)([]),[ue,de]=(0,z.useState)(!1),[fe,pe]=(0,z.useState)(fx),[me,he]=(0,z.useState)({}),[ge,_e]=(0,z.useState)([]),ve=(0,z.useRef)(!1),ye=(0,z.useRef)(NaN),be=(0,z.useRef)(null),xe=(0,z.useRef)(null),Se=(0,z.useRef)(null),Ce=(0,z.useRef)(new Set),we=(0,z.useRef)(new Set),[Te,Ee]=(0,z.useState)(null),R=o===void 0?u:o,De=a??f,Oe=`${R??`manager`}:${De}`,ke=te[Oe]??``;(0,z.useEffect)(()=>{M([]),P(null)},[Oe]);function Ae(e,t){ne(n=>{let r={...n};t?r[e]=t:delete r[e];try{window.sessionStorage.setItem(`loopx-pw-composer-drafts`,JSON.stringify(r))}catch{}return r})}function je(e){Ae(Oe,e)}function Me(e){let t=te[Oe]?.trimEnd();je(t?`${t}\n${e}`:e),window.requestAnimationFrame(()=>be.current?.focus())}(0,z.useEffect)(()=>{let e=be.current;e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,120)}px`)},[ke]);let Ne=(0,z.useMemo)(()=>r.goals.map(e=>{let t=me[e.goalId];return t?{...e,repository:{branch:t.branch,identity:t.identity,label:t.label,readOnly:!0}}:e}),[me,r.goals]),Pe=(0,z.useMemo)(()=>Ne.filter(e=>gy(e)===`needs_you`).length,[Ne]),Fe=(0,z.useMemo)(()=>Ne.filter(e=>gy(e)===`needs_you`&&(e.needsYouBlocking||e.state===`等你`)).length,[Ne]),V=Ne.find(e=>e.goalId===R)??null,Ie=m?.kind===`settings`,Le=R,Re=(0,z.useMemo)(()=>{let e=Object.values(b).filter(e=>e.actionKind===`heartbeat.bind`&&e.goalId&&e.status===`applied`).map(e=>({id:`schedule:${e.goalId}:heartbeat`,kind:`schedule`,schedule:{agentId:De,executionHistory:[],goalId:e.goalId,label:e.title,nextRunAt:l(`drawer.schedulePending`),notificationRule:l(`drawer.scheduleDefaultNotification`),schedule:e.fields.find(e=>e.key===`cadence`)?.value??l(`schedule.summary`),scheduleId:`${e.goalId}:heartbeat`,scheduleKind:`heartbeat`,status:e.status===`applied`?`active`:`draft`,stopCondition:e.fields.find(e=>e.key===`stop_condition`)?.value??l(`drawer.scheduleDefaultStop`),timezone:e.fields.find(e=>e.key===`timezone`)?.value??`Asia/Shanghai`}})),t=[...Sx(r,Le,l),...r.timeline??[],...e,...gx(Object.values(b)).filter(e=>e.actionKind!==`heartbeat.bind`||e.status!==`applied`).map(e=>({id:`proposal:${e.previewId}`,kind:`proposal`,proposal:e}))];return[...new Map(t.map(e=>[e.id,e])).values()].filter(e=>e.kind!==`proposal`||![`stale`,`error`].includes(e.proposal.status)||ce.includes(e.proposal.previewId)).filter(e=>!R||e.kind===`message`?!0:e.kind===`proposal`?!e.proposal.goalId||e.proposal.goalId===R:e.kind===`attention`?e.attention.goalId===R:e.kind===`run`?e.run.goalId===R:e.kind===`schedule`?e.schedule.goalId===R:e.output.goalId===R)},[Le,r,b,De,R,ce,l]),ze=(0,z.useMemo)(()=>v?Re.filter(e=>e.kind===`message`?!0:e.kind===`run`?e.run.runId===v.runId:e.kind===`output`&&e.output.runId===v.runId):Re,[v,Re]);(0,z.useEffect)(()=>{if(!v)return;let e=Re.find(e=>e.kind===`run`&&e.run.runId===v.runId);!e||e.kind!==`run`||JSON.stringify({completedSteps:v.completedSteps,latestActivity:v.latestActivity,messages:v.sessionMessages,sessionStatus:v.sessionStatus,status:v.status,totalSteps:v.totalSteps})!==JSON.stringify({completedSteps:e.run.completedSteps,latestActivity:e.run.latestActivity,messages:e.run.sessionMessages,sessionStatus:e.run.sessionStatus,status:e.run.status,totalSteps:e.run.totalSteps})&&y(e.run)},[v,Re]);let Be=(0,z.useMemo)(()=>Re.flatMap(e=>e.kind===`message`?[e.message]:[]),[Re]),Ve=(0,z.useMemo)(()=>V?Re.flatMap(e=>e.kind===`message`?[e.message]:[]):[],[Re,V]);(0,z.useEffect)(()=>{V||w||Be.some(e=>e.pending)&&D(!0)},[w,Be,V]),(0,z.useEffect)(()=>{!V||S===`chat`||Ve.some(e=>e.pending)&&ee(!0)},[Ve,V,S]);let He=(0,z.useMemo)(()=>Re.filter(e=>e.kind===`message`||e.kind===`proposal`&&ce.includes(e.proposal.previewId)),[Re,ce]),Ue=He[He.length-1],We=Ue?.kind===`message`?Ue.message.text.length:0;(0,z.useEffect)(()=>{if(!w||!xe.current)return;let e=window.requestAnimationFrame(()=>{xe.current&&(xe.current.scrollTop=xe.current.scrollHeight)});return()=>window.cancelAnimationFrame(e)},[He.length,w,We]);let Ge=(0,z.useMemo)(()=>{if(m?.kind===`settings`)return null;if(m?.kind===`attention`)return{kind:`attention`,item:Gd(m.item,r.attentionHistory??r.userTodos)};if(m?.kind===`goal`){let e=Ne.find(e=>e.goalId===m.item.goalId);return e?{item:e,kind:`goal`}:m}if(m?.kind!==`run`)return m;let e=Re.find(e=>e.kind===`run`&&e.run.runId===m.item.runId);return e?{item:e.run,kind:`run`}:m},[Re,m,Ne,r.attentionHistory,r.userTodos]);(0,z.useEffect)(()=>{if(i){he({}),_e([]);return}let e=!1;return Promise.all([Ig(),qg()]).then(([t,n])=>{e||(he(Object.fromEntries(t.map(e=>[e.goal_id,e.repository]))),_e(n))}).catch(()=>{}),()=>{e=!0}},[i]),(0,z.useEffect)(()=>{if(!ue)return;function e(e){e.key===`Escape`&&de(!1)}return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[ue]),(0,z.useEffect)(()=>{if(R||!Re.length)return;if(!ve.current){ve.current=!0;try{ye.current=Date.parse(window.localStorage.getItem(`loopx-pw-last-visit`)??``),window.localStorage.setItem(`loopx-pw-last-visit`,new Date().toISOString())}catch{ye.current=NaN}}let e=ye.current,t=Re.filter(e=>e.kind===`run`).map(e=>e.run),n=t=>{let n=Date.parse(t??``);return!Number.isNaN(e)&&!Number.isNaN(n)&&n>e},r={attention:Pe,done:t.filter(e=>e.status===`completed`&&n(e.latestActivity)).length,failed:t.filter(e=>(e.status===`failed`||e.status===`interrupted`)&&n(e.latestActivity)).length};Ee(e=>e?.attention===r.attention&&e.done===r.done&&e.failed===r.failed?e:r)},[Re,Pe,R]),(0,z.useEffect)(()=>{if(i){x({});return}let e=!1;return Mh(R?{goalId:R}:{contextKind:`manager`}).then(t=>{if(e)return;let n=Object.fromEntries(t.filter(e=>[`ready`,`gated`,`deferred`,`applying`].includes(e.status)).map(e=>{let t=Dx(e,l);return[t.previewId,t]}));x(e=>({...e,...n}))}).catch(()=>{}),()=>{e=!0}},[i,R,l]);async function Ke(e,n={}){if(i)throw Error(l(`source.readOnlyWriteError`));let r;try{r=t.onPreviewAction?await t.onPreviewAction(e):Dx(await Ah(e),l)}catch(t){if(!(t instanceof Th)||t.payload.error_code!==`action_preview_gate`)throw t;let n=t.payload.gate&&typeof t.payload.gate==`object`?t.payload.gate:{},i=(Array.isArray(n.candidates)?n.candidates:[]).flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.workspace_ref==`string`&&typeof t.label==`string`?[{label:t.label,workspaceRef:t.workspace_ref}]:[]}),a=String(n.kind??`workspace_selection_required`),o=a===`agent_binding_required`||a===`agent_identity_selection_required`;r={actionKind:e.actionKind,fields:i.map(e=>({key:`workspace_ref:${e.workspaceRef}`,label:e.label,value:e.workspaceRef})),gate:{kind:a,nextAction:typeof n.next_action==`string`?n.next_action:void 0,summary:String(n.summary??l(`proposal.workspaceGate.defaultSummary`))},impact:l(o?`proposal.workspaceGate.agentImpact`:`proposal.workspaceGate.selectionImpact`),previewId:`workspace-choice-${Date.now().toString(36)}`,sourceRequest:e,status:`gated`,title:l(o?`proposal.workspaceGate.agentTitle`:`proposal.workspaceGate.selectionTitle`),workspaceCandidates:i}}return le(e=>e.includes(r.previewId)?e:[...e,r.previewId]),x(e=>({...e,[r.previewId]:r})),n.select!==!1&&h({item:r,kind:`proposal`}),r}function qe(){tt(null),Ae(`manager:${De}`,l(`composer.createGoalTemplate`)),window.requestAnimationFrame(()=>be.current?.focus())}async function Je(e,n){de(!1);let r={delete:`Deleted from the owner workspace`,resume:`Resumed from the owner workspace`,stop:`Stopped from the owner workspace`},i={delete:l(`proposal.summary.lifecycleDelete`,{title:e.title}),resume:l(`proposal.summary.lifecycleResume`,{title:e.title}),stop:l(`proposal.summary.lifecycleStop`,{title:e.title})},a=null,o=!1;try{if(n===`stop`){if(Ce.current.has(e.goalId))return;Ce.current.add(e.goalId),I(new Set(Ce.current)),h(null),a={goalId:e.goalId,next:`stopped`,optimisticApplied:!0,previous:e.activationState},re(l(`feedback.applying`,{title:i.stop})),t.onGoalActivationStateChange?.(e.goalId,`stopped`)}if(t.onExecuteGoalLifecycle){if(n===`delete`)throw Error(`The selected status source does not authorize Goal deletion.`);let a=await t.onExecuteGoalLifecycle({goalId:e.goalId,operation:n,reason:r[n]});if(!a.projectionVerified)throw Error(`Goal lifecycle projection did not verify.`);o=!0,t.onGoalActivationStateChange?.(e.goalId,a.activationState),re(l(`feedback.completed`,{title:i[n]})),n===`stop`&&tt(null),await(t.onReconcileStatus??t.onRefresh)?.();return}let s=await Ke({actionKind:`goal.lifecycle`,context:{kind:`goal_directory`,goal_id:e.goalId},idempotencyKey:`workspace-goal-${n}-${e.goalId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,operation:n,reason:r[n]},summary:i[n]},{select:n!==`stop`});if(s.goalId!==e.goalId||s.lifecycleOperation!==n)throw h(null),Error(l(`actionReview.targetChanged`));n===`stop`&&(s.reviewPlan?.interaction===`direct`?(o=!0,await Qe(s,{lifecycleProjection:a??void 0,presentation:`feedback`})):(a&&t.onGoalActivationStateChange?.(a.goalId,a.previous),re(s.gate?l(`feedback.gateRequired`,{summary:s.gate.summary}):l(`feedback.notCompleted`,{status:s.status})),h({item:s,kind:`proposal`})))}catch(e){a&&!o&&t.onGoalActivationStateChange?.(a.goalId,a.previous),re(l(`feedback.executionFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{n===`stop`&&(Ce.current.delete(e.goalId),I(new Set(Ce.current)))}}function Ye(e,t){je(l(t?e===`heartbeat`?`composer.heartbeatTemplate`:`composer.monitorTemplate`:e===`heartbeat`?`composer.heartbeatTemplateWithoutGoal`:`composer.monitorTemplateWithoutGoal`)),h(null),window.requestAnimationFrame(()=>be.current?.focus())}async function Xe(e,n,r=``){let i=await t.onRequestScheduleConfig?.(e,n);if(i){le(e=>e.includes(i.previewId)?e:[...e,i.previewId]),x(e=>({...e,[i.previewId]:i})),h({item:i,kind:`proposal`});return}if(!n){je(l(e===`heartbeat`?`composer.heartbeatGoalQuestion`:`composer.monitorGoalQuestion`));return}let a=Date.now().toString(36);await Ke({actionKind:e===`heartbeat`?`heartbeat.bind`:`monitor.create`,context:{kind:`schedule`,goal_id:n},idempotencyKey:`workspace-${e}-${n}-${a}`,normalizedParameters:e===`heartbeat`?{agent_id:De,cadence:Mx(r),goal_id:n,stop_condition:Fx(r),timezone:`Asia/Shanghai`}:{agent_id:De,cadence:Mx(r),goal_id:n,stop_condition:Fx(r),target:Px(r,l),target_key:`goal-${n}`,timezone:`Asia/Shanghai`},summary:e===`heartbeat`?l(`proposal.summary.heartbeat`):l(`proposal.summary.monitor`,{target:Px(r,l)})})}async function Ze(e){if(!we.current.has(e.todoId)){we.current.add(e.todoId),L(new Set(we.current)),re(l(`feedback.preparingPreview`,{title:e.text}));try{await Ke({actionKind:`todo.update`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-${e.todoId}-complete-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,operation:`complete`,todo_id:e.todoId},summary:l(`tasks.markComplete`,{name:e.text})}),re(null)}catch(e){re(l(`feedback.previewFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{we.current.delete(e.todoId),L(new Set(we.current))}}}async function Qe(e,n={}){if(e.reviewPlan&&!e.reviewPlan.canApply)return;let i=n.presentation!==`feedback`,a=e.actionKind===`goal.lifecycle`&&e.goalId&&(e.lifecycleOperation===`stop`||e.lifecycleOperation===`resume`)?{goalId:e.goalId,next:e.lifecycleOperation===`stop`?`stopped`:`active`,optimisticApplied:!1,previous:r.goals.find(t=>t.goalId===e.goalId)?.activationState??(e.lifecycleOperation===`stop`?`active`:`stopped`)}:null,o=n.lifecycleProjection??a;re(l(`feedback.applying`,{title:e.title}));let s={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:`pending`,reason:`apply_pending`,canApply:!1}:void 0,status:`applying`};x(t=>({...t,[e.previewId]:s})),i&&h({item:s,kind:`proposal`}),o&&!o.optimisticApplied&&t.onGoalActivationStateChange?.(o.goalId,o.next);try{if(t.onApplyProposal){await t.onApplyProposal(e);let n={...e,status:`applied`};if(x(t=>({...t,[e.previewId]:n})),i&&h({item:n,kind:`proposal`}),re(l(`feedback.completed`,{title:e.title})),e.actionKind===`goal.lifecycle`){(e.lifecycleOperation===`stop`||e.lifecycleOperation===`delete`)&&tt(null),e.lifecycleOperation===`delete`&&e.goalId&&t.onGoalDeleted?.(e.goalId);let n=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>n?.()).catch(()=>void 0)}return}let n=await Nh(e.previewId);if(n.proposal.proposal_id!==e.previewId||n.proposal.action_kind!==e.actionKind||e.actionKind===`goal.lifecycle`&&(n.proposal.normalized_parameters.goal_id!==e.goalId||Ex(n.proposal)!==e.lifecycleOperation))throw new Th(l(`actionReview.targetChanged`),{error_code:`action_response_mismatch`});let r=Dx(n.proposal,l);if(x(t=>({...t,[e.previewId]:r})),i&&h({item:r,kind:`proposal`}),r.reviewPlan?.interaction!==`completed`){o&&t.onGoalActivationStateChange?.(o.goalId,o.previous),h({item:r,kind:`proposal`}),re(n.proposal.status===`stale`?l(`feedback.stale`):l(`actionReview.${r.reviewPlan.reason}`));return}if(re(l(`feedback.completed`,{title:r.title})),r.actionKind===`todo.create`&&await t.onRefresh?.(),r.actionKind===`goal.lifecycle`&&(r.lifecycleOperation===`stop`||r.lifecycleOperation===`delete`)&&tt(null),r.actionKind===`goal.lifecycle`&&r.lifecycleOperation===`delete`&&r.goalId&&t.onGoalDeleted?.(r.goalId),r.actionKind===`goal.lifecycle`){let e=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>e?.()).catch(()=>void 0)}}catch(n){if(o&&t.onGoalActivationStateChange?.(o.goalId,o.previous),n instanceof Th&&n.payload.error_code===`protected_action`){let r=n.payload.gate,i=r&&typeof r==`object`?r:{},a={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:`gated`,reason:`authority_gate`,canApply:!1}:void 0,gate:{kind:String(i.kind??`protected_action`),nextAction:typeof i.next_action==`string`?i.next_action:void 0,summary:String(i.summary??n.message)},status:`gated`};x(t=>({...t,[e.previewId]:a})),h({item:a,kind:`proposal`}),re(l(`feedback.gateRequired`,{summary:a.gate.summary})),e.actionKind===`goal.create`&&e.goalId&&(t.onRefresh?.(),tt(e.goalId));return}let r=n instanceof Th&&py(n.payload),i=n instanceof Th&&n.payload.error_code===`action_response_mismatch`,a={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:r?`refresh`:`repair`,reason:i?`readback_unverified`:r?`stale_proposal`:`apply_failed`,canApply:!1}:void 0,errorMessage:n instanceof Error?n.message:String(n),status:r?`stale`:`error`};x(t=>({...t,[e.previewId]:a})),h({item:a,kind:`proposal`}),re(l(`feedback.executionFailed`,{error:a.errorMessage}))}}let $e={...t,onOpenRunSession:async e=>{e.goalId!==R&&tt(e.goalId),C(`chat`),await t.onOpenRunSession?.(e),y(e),h(null)},onOpenGoal:e=>{tt(e);let n=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>n?.()).catch(()=>{re(l(`feedback.goalRefreshFailed`))})},onOpenGoalView:e=>{C(e),e===`chat`&&y(null),h(null)},onOpenOutput:e=>{e.goalId!==R&&tt(e.goalId),C(`files`),t.onOpenOutput?.(e)},onApplyProposal:Qe,onCancelProposal:async e=>{h(null),x(t=>{let n={...t};return delete n[e.previewId],n});try{t.onCancelProposal?.(e),t.onCancelProposal||await Ph(e.previewId)}catch(t){x(t=>({...t,[e.previewId]:e})),re(l(`feedback.cancelFailed`,{error:t instanceof Error?t.message:String(t)}))}},onTransitionProposal:async(e,t)=>{let n=Dx(await Fh(e.previewId,t),l);le(e=>e.includes(n.previewId)?e:[...e,n.previewId]),x(r=>{let i={...r};return t===`regenerate`&&delete i[e.previewId],i[n.previewId]=n,i}),h({item:n,kind:`proposal`})},onSelectWorkspaceCandidate:async(e,t)=>{e.sourceRequest&&(x(t=>{let n={...t};return delete n[e.previewId],n}),await Ke({...e.sourceRequest,idempotencyKey:`${e.sourceRequest.idempotencyKey}-${t}`,normalizedParameters:{...e.sourceRequest.normalizedParameters,workspace_ref:t}}))},onPreviewAction:Ke,onRequestScheduleConfig:(e,t)=>Ye(e,t),onOpenNotificationSettings:e=>h({goalId:e,kind:`settings`,tab:`lark`}),onFetchNotificationTargets:()=>ig(),onSetupGoalChannel:e=>og(e),onToggleGoalAutoNotify:e=>sg(e),onUpdateSchedule:async(e,t)=>{let n=Date.now().toString(36),r=e.scheduleKind===`heartbeat`;await Ke({actionKind:r?`heartbeat.bind`:`monitor.update`,context:{kind:`schedule`,goal_id:e.goalId},idempotencyKey:`workspace-monitor-${e.scheduleId}-${t}-${n}`,normalizedParameters:{agent_id:e.agentId??De,...!r&&t===`run_now`?{endpoint_id:De}:{},...t===`edit`?{cadence:`2h`,...r?{timezone:e.timezone??`Asia/Shanghai`}:{}}:{},goal_id:e.goalId,operation:t,...!r&&t===`run_now`&&e.sessionId?{session_id:e.sessionId}:{},...r?{}:{todo_id:e.scheduleId}},summary:t===`pause`?`暂停自动运行:${e.label}`:t===`resume`?`恢复自动运行:${e.label}`:t===`run_now`?`立即运行:${e.label}`:t===`stop`?`停止自动运行:${e.label}`:`编辑自动运行生命周期:${e.label}`})}},et=i?{onOpenGoal:$e.onOpenGoal,onOpenGoalView:$e.onOpenGoalView,onOpenOutput:$e.onOpenOutput}:$e;function tt(e){d(e),T(!1),D(!1),ee(!1),y(null),h(null),C(`tasks`),de(!1),t.onSelectGoal?.(e)}function nt(e){p(e),t.onSelectAgent?.(e)}function rt(e){pe(e),px(e)}async function it(n){let r=n?[]:j,i=(n??ke).trim()||(r.length?l(`composer.imageAnalysisPrompt`):``);if(!(!i||k)){n||(je(``),M([])),P(null),A(!0);try{if(r.length){R?S!==`chat`&&ee(!0):D(!0);let e=await t.onSendMessage?.(i,De,R,r);e&&await Ke(e);return}let n=Wy(i,{agents:e.map(e=>({agentId:e.agentId,label:e.label})),goalId:R,todos:(V?.agentTodos??[]).map(e=>({text:e.text,todoId:e.todoId}))});if(n.route===`clarify`){je(i);let e=l(`composer.clarifySingleAction`);n.missingFields.includes(`resume_when`)&&(e=l(`composer.clarifyDefer`)),re(e);return}if(n.actionKind===`goal.create`){let e=jx(i,l),t=Ox(e.title);await Ke({actionKind:`goal.create`,context:{kind:`manager`,goal_id:null,natural_language:i},idempotencyKey:`workspace-goal-intent-${t}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:De,completion_criteria:e.completionCriteria,execution_boundary:e.executionBoundary,goal_id:t,heartbeat:{cadence:Mx(i),enabled:n.normalizedParameters.heartbeat_enabled===!0,timezone:`Asia/Shanghai`},initial_todos:e.initialTodos,objective:e.objective,permission:e.permission,stop_condition:Fx(i),title:e.title,workspace_ref:`current`},summary:l(`proposal.summary.goalCreate`,{title:e.title})});return}if(R&&n.actionKind===`heartbeat.bind`){await Xe(`heartbeat`,R,i);return}if(R&&n.actionKind===`monitor.create`){let e=Nx(i,l);if(e){je(i),re(e);return}await Xe(`monitor`,R,i);return}let a=Ix(i,e);if(R&&a&&n.actionKind===`agent.bind`){await Ke({actionKind:`agent.bind`,context:{kind:`goal`,goal_id:R,natural_language:i},idempotencyKey:`workspace-agent-bind-${R}-${a.agentId}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:a.agentId,goal_id:R},summary:`将 ${a.label} 绑定到 ${V?.title??R}`});return}if(R&&n.actionKind===`todo.create`){if(n.normalizedParameters.start_execution===!0){await Ke({actionKind:`todo.create`,context:{kind:`goal`,goal_id:R,natural_language:i},idempotencyKey:`workspace-task-start-${R}-${Date.now().toString(36)}`,normalizedParameters:{endpoint_id:a?.agentId??De,goal_id:R,start_execution:!0,text:i},summary:`交给 Agent 执行:${i.slice(0,120)}`});return}let e=a?.agentId??(/(交给|分配给|让).{0,24}(agent|codex|claude|kiro|kimi)/iu.test(i)?De:null);await Ke({actionKind:`todo.create`,context:{kind:`goal`,goal_id:R,natural_language:i},idempotencyKey:`workspace-todo-create-${R}-${Date.now().toString(36)}`,normalizedParameters:{...e?{endpoint_id:e}:{},goal_id:R,text:Lx(i)},summary:`创建 Todo:${Lx(i)}`});return}let o=V?.agentTodos.find(e=>i.includes(e.todoId)||i.includes(e.text)),s=typeof n.normalizedParameters.operation==`string`?n.normalizedParameters.operation:null;if(R&&o&&n.actionKind===`todo.update`&&s){await Ke({actionKind:`todo.update`,context:{kind:`todo`,goal_id:R,todo_id:o.todoId,natural_language:i},idempotencyKey:`workspace-todo-update-${o.todoId}-${s}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:De,...s===`reassign`&&a?{endpoint_id:a.agentId}:{},...s===`block`?{note:i}:{},...s===`defer`&&typeof n.normalizedParameters.resume_when==`string`?{resume_when:n.normalizedParameters.resume_when}:{},goal_id:R,operation:s,todo_id:o.todoId},summary:`更新 Todo:${o.text}`});return}R?S!==`chat`&&ee(!0):D(!0);let c=await t.onSendMessage?.(i,De,R);c&&await Ke(c)}catch(e){n||(je(i),M(r));let t=e instanceof Error?e.message:l(`feedback.sendGenericError`);re(l(`feedback.sendFailed`,{error:t}))}finally{A(!1)}}}let at=e.find(e=>e.agentId===De)?.label??De,ot=!V&&ke.startsWith(l(`composer.createGoalDraftLead`)),st=Re.filter(e=>e.kind===`run`&&!!e.run.sessionId&&!!e.run.canInterrupt&&(e.run.status===`running`||e.run.status===`queued`)).length;async function ct(e){if(!e?.length)return;let t=Bx-j.length,n=Array.from(e).slice(0,Math.max(0,t)),r=n.find(e=>!Rx.has(e.type)),i=n.find(e=>e.size>zx);if(t<=0){P(l(`composer.imageCountError`,{count:Bx}));return}if(r){P(l(`composer.imageTypeError`));return}if(i){P(l(`composer.imageSizeError`,{size:zx/1024/1024}));return}try{let t=await Promise.all(n.map(e=>Vx(e,l)));M(e=>[...e,...t].slice(0,Bx)),P(e.length>n.length?l(`composer.imageCountError`,{count:Bx}):null)}catch(e){P(e instanceof Error?e.message:l(`composer.imageReadGenericError`))}finally{Se.current&&(Se.current.value=``)}}function lt(e){let t=Array.from(e.clipboardData.items).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).flatMap(e=>{let t=e.getAsFile();return t?[t]:[]});t.length&&(e.preventDefault(),ct(t))}async function ut(){let e=await qg();_e(e)}async function dt(){await Promise.all([ut(),t.onRefresh?.()])}async function ft(){if(!(!t.onRefresh||oe===`loading`)){se(`loading`);try{await t.onRefresh(),se(`done`)}catch{se(`error`)}window.setTimeout(()=>se(`idle`),1800)}}return Ie?(0,B.jsx)(lx,{focusGoalConnection:!!(m?.kind===`settings`&&m.goalId),goals:Ne,initialGoalId:m?.kind===`settings`?m.goalId??R:R,initialTab:m?.kind===`settings`?m.tab??`lark`:`lark`,onChanged:()=>void dt(),onClose:()=>h(null),onThemeChange:rt,theme:fe}):(0,B.jsx)(mx,{drawer:Ge?(0,B.jsx)($y,{agents:e,attentionHistory:r.attentionHistory??r.userTodos,onSelectAttention:e=>h({kind:`attention`,item:e}),callbacks:et,goalNotifications:r.goalNotifications??[],goals:Ne,inspectorExpanded:g,larkConnections:i?[]:ge,onClose:()=>{Ge.kind===`proposal`&&[`applied`,`rejected`].includes(Ge.item.status)&&(Ge.item.actionKind!==`heartbeat.bind`||Ge.item.status!==`applied`)&&x(e=>{let t={...e};return delete t[Ge.item.previewId],t}),_(!1),h(null)},onToggleInspectorSize:()=>_(e=>!e),readOnly:i,runs:Re.flatMap(e=>e.kind===`run`?[e.run]:[]),selection:Ge}):null,drawerMode:Ge?.kind===`todo`?g?`inspector-full`:`inspector`:`panel`,drawerOpen:Ge!==null,mobileSidebarOpen:ue,onCloseMobileSidebar:()=>de(!1),theme:fe,main:(0,B.jsxs)(`div`,{className:`personal-channel`,children:[(0,B.jsx)(wy,{agents:e,managerChatOpen:w,mobileNavigationOpen:ue,onOpenGoalCapabilities:V?()=>h({goalId:V.goalId,kind:`settings`,tab:`capabilities`}):void 0,onOpenGoalDetail:V&&!V.loadState?()=>h({item:V,kind:`goal`}):void 0,onRefresh:t.onRefresh?()=>void ft():void 0,onOpenNavigation:()=>de(!0),onOpenManagerChat:()=>{D(!1),T(!0)},onSelectGoalTab:e=>{C(e),e===`chat`&&(y(null),ee(!1))},onSelectAgent:nt,onReturnManagerHome:()=>{T(!1),D(!1),window.requestAnimationFrame(()=>xe.current?.scrollTo({behavior:`smooth`,top:0}))},selectedAgentId:De,refreshState:oe,readOnlySourceLabel:i?s?.activeSource.label:void 0,selectedGoal:V,selectedGoalTab:S}),(0,B.jsxs)(`div`,{className:`personal-channel-scroll`,ref:xe,children:[!V&&!w&&Te&&Te.done+Te.failed+Te.attention>0?(0,B.jsxs)(`section`,{className:`personal-digest-card`,"aria-label":l(`digest.away`),children:[(0,B.jsx)(`strong`,{children:l(`digest.away`)}),(0,B.jsxs)(`div`,{className:`personal-digest-stats`,children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`b`,{children:Te.done}),l(`digest.completed`)]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`b`,{children:Te.failed}),l(`digest.failed`)]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`b`,{children:Te.attention}),l(`digest.needsYou`)]})]})]}):null,!V&&!w?(0,B.jsxs)(`section`,{className:`personal-manager-greeting`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Zp,{size:20})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:l(`home.greeting`)}),(0,B.jsx)(`p`,{children:r.goals.some(e=>e.activationState===`active`&&e.loadState)?l(`startup.partial`):(0,B.jsxs)(B.Fragment,{children:[l(`home.waitingCount`,{count:Pe}),` `,l(`home.blockingSummary`,{count:Fe})]})})]})]}):null,V?.loadState?(0,B.jsx)(`section`,{className:`personal-manager-greeting`,role:`status`,"data-testid":`goal-status-loading`,children:(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:l(V.loadState===`error`?`startup.goalError`:`startup.goalLoading`)}),(0,B.jsx)(`p`,{children:l(V.loadError?`startup.error.${V.loadError}`:`startup.independent`)}),V.loadState===`error`?(0,B.jsx)(`button`,{className:`min-h-11 rounded-md border px-3 py-2 text-sm`,type:`button`,onClick:()=>void t.onRefresh?.(),children:l(`startup.retry`)}):null]})}):V&&S===`tasks`?(0,B.jsx)(Tb,{historyEnabled:!i,goal:V,items:Re,onDraftTaskFromMessage:i?void 0:e=>{je(`创建一个 Task:${hx(e)}`),re(l(`feedback.taskDraftCreated`)),window.requestAnimationFrame(()=>be.current?.focus())},onOpenChat:()=>C(`chat`),onQuickComplete:i?void 0:Ze,onSelect:h,quickCompletingTodoIds:ae,selectedTodoId:Ge?.kind===`todo`?Ge.item.todoId:null,userTodos:r.userTodos}):V&&S===`files`?(0,B.jsx)(yx,{items:Re.filter(e=>e.kind===`output`),onSelect:h,reportState:r.periodicReports}):!V&&!w?(0,B.jsx)(vx,{goals:Ne,onRetry:()=>void t.onRefresh?.(),onSelectGoal:tt,systemHealth:r.systemHealth}):V?(0,B.jsxs)(B.Fragment,{children:[V&&v?.goalId===V.goalId?(0,B.jsx)(xx,{onClose:()=>y(null),onOpenDetails:()=>h({item:v,kind:`run`}),run:v}):null,(0,B.jsx)(Iy,{items:ze,onSelect:h,selectedGoal:V})]}):(0,B.jsx)(Iy,{items:He,onSelect:h,selectedGoal:null})]}),(0,B.jsx)(`div`,{className:`personal-composer-wrap`,children:i?(0,B.jsxs)(`div`,{className:`personal-read-only-notice`,children:[(0,B.jsx)(`strong`,{children:l(`source.readOnlyNoticeTitle`)}),(0,B.jsx)(`span`,{children:l(`source.readOnlyNoticeDescription`)})]}):(0,B.jsxs)(B.Fragment,{children:[!V&&!w&&E&&Be.length?(0,B.jsx)(bx,{messages:Be,onClose:()=>D(!1),onOpenConversation:()=>{D(!1),T(!0)}}):null,V&&S!==`chat`&&O&&Ve.length?(0,B.jsx)(bx,{agentLabel:at,messages:Ve,onClose:()=>ee(!1),onDraftTask:S===`tasks`?e=>{je(`创建一个 Task:${hx(e)}`),re(l(`feedback.taskDraftCreated`)),window.requestAnimationFrame(()=>be.current?.focus())}:void 0,onOpenConversation:()=>{ee(!1),C(`chat`)},title:`${V.title} · ${at}`}):null,F?(0,B.jsxs)(`div`,{className:`personal-action-feedback`,role:`status`,children:[(0,B.jsx)(`span`,{children:F}),(0,B.jsx)(`button`,{"aria-label":l(`common.closeActionReceipt`),onClick:()=>re(null),type:`button`,children:(0,B.jsx)($m,{size:14})})]}):null,(0,B.jsx)(`p`,{className:`personal-composer-hint`,children:V?st>0?l(`composer.goalRunningHint`,{agent:at,count:st}):l(`composer.goalMessageHint`,{agent:at}):l(`composer.managerMessageHint`)}),V?(0,B.jsxs)(`div`,{className:`personal-quick-prompts`,children:[(0,B.jsxs)(`button`,{"aria-label":l(`composer.nextAction`),className:`is-draft`,onClick:()=>Me(l(`composer.nextActionPrompt`)),title:l(`composer.prepareDraft`),type:`button`,children:[(0,B.jsx)(Em,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.nextAction`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]}),(0,B.jsxs)(`button`,{className:`is-immediate`,disabled:k,onClick:()=>void it(l(`composer.agentProgressPrompt`)),title:l(`composer.immediate`),type:`button`,children:[(0,B.jsx)(Bm,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.agentProgress`)}),(0,B.jsx)(`em`,{className:`personal-prompt-badge`,children:l(`composer.immediate`)})]}),(0,B.jsxs)(`button`,{"aria-label":l(`composer.monitor`),className:`is-draft`,onClick:()=>Ye(`monitor`,R),title:l(`composer.monitorHint`),type:`button`,children:[(0,B.jsx)($p,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.monitor`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]})]}):(0,B.jsxs)(`div`,{className:`personal-quick-prompts`,children:[(0,B.jsxs)(`button`,{"aria-label":l(`composer.globalTasks`),className:`is-draft`,onClick:()=>Me(l(`composer.globalTasksPrompt`)),title:l(`composer.prepareDraft`),type:`button`,children:[(0,B.jsx)(Em,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.globalTasks`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]}),(0,B.jsxs)(`button`,{className:`is-immediate`,disabled:k,onClick:()=>void it(l(`composer.globalProgressPrompt`)),title:l(`composer.immediate`),type:`button`,children:[(0,B.jsx)(Bm,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.globalProgress`)}),(0,B.jsx)(`em`,{className:`personal-prompt-badge`,children:l(`composer.immediate`)})]}),(0,B.jsxs)(`button`,{"aria-label":l(`composer.createGoal`),className:`is-draft`,onClick:qe,title:l(`composer.createGoalHint`),type:`button`,children:[(0,B.jsx)(Pm,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.createGoal`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]})]}),ot?(0,B.jsxs)(`div`,{className:`personal-goal-draft-status`,role:`status`,children:[(0,B.jsx)(`strong`,{children:l(`composer.createGoalDraft`)}),(0,B.jsx)(`span`,{children:l(`composer.createGoalDraftDescription`)})]}):null,j.length?(0,B.jsx)(`div`,{className:`personal-composer-images`,"aria-label":l(`composer.imagesPending`),children:j.map(e=>(0,B.jsxs)(`figure`,{children:[(0,B.jsx)(`img`,{alt:e.name,src:e.dataUrl}),(0,B.jsx)(`button`,{"aria-label":l(`composer.sentImageAlt`,{name:e.name}),onClick:()=>M(t=>t.filter(t=>t.id!==e.id)),type:`button`,children:(0,B.jsx)($m,{size:13})})]},e.id))}):null,N?(0,B.jsx)(`p`,{className:`personal-composer-error`,role:`alert`,children:N}):null,(0,B.jsxs)(`div`,{className:`personal-channel-composer`,onDragOver:e=>{[...e.dataTransfer.items].some(e=>e.kind===`file`&&e.type.startsWith(`image/`))&&e.preventDefault()},onDrop:e=>{let t=[...e.dataTransfer.files].filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),ct(t))},children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:17}),e.find(e=>e.agentId===De)?.label??De]}),(0,B.jsx)(`button`,{"aria-label":l(`composer.addImage`),className:`personal-composer-attach`,disabled:k||j.length>=Bx,onClick:()=>Se.current?.click(),title:l(`composer.attachImageHint`),type:`button`,children:(0,B.jsx)(jm,{size:17})}),(0,B.jsx)(`input`,{accept:`image/png,image/jpeg,image/webp,image/gif`,"aria-label":l(`composer.imagePicker`),className:`personal-composer-file-input`,disabled:k||j.length>=Bx,multiple:!0,onChange:e=>void ct(e.target.files),ref:Se,type:`file`}),(0,B.jsx)(`textarea`,{"aria-label":l(`composer.sendMessage`),onChange:e=>je(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),it())},onPaste:lt,placeholder:V?l(`composer.goalPlaceholder`,{goal:V.title}):l(`composer.managerPlaceholder`),ref:be,rows:1,value:ke}),(0,B.jsx)(`button`,{"aria-label":l(ot?`composer.createGoal`:`composer.send`),disabled:!ke.trim()&&j.length===0||k,onClick:()=>void it(),title:l(ot?`composer.createGoalHint`:`composer.sendMessageHint`),type:`button`,children:(0,B.jsx)(Bm,{size:18})})]})]})})]}),sidebar:(0,B.jsx)(xb,{attentionCount:Pe,goals:Ne,goalArchiveLoadState:n,goalLifecycleOperations:t.onExecuteGoalLifecycle?[`stop`,`resume`]:void 0,lifecycleBusyGoalIds:ie,onRequestGoalCreate:i?void 0:qe,onRequestGoalLifecycle:i&&!t.onExecuteGoalLifecycle?void 0:(e,t)=>void Je(e,t),onRetryGoalArchive:t.onRetryGoalArchive||t.onRefresh?()=>void(t.onRetryGoalArchive??t.onRefresh)?.():void 0,onOpenSettings:i?void 0:()=>h({kind:`settings`}),onSelectGoal:tt,selectedGoalId:R,statusSourceControl:s},s?.activeSource.statusUrl??`/status.json`)})}function Ux(e){return(e??``).replace(/\s+/gu,` `).trim()}function Wx(e,t=120){let n=Array.from(e);return n.length<=t?e:`${n.slice(0,t-1).join(``)}…`}function Gx(e,t,n){let r=Ux(e);return!r||r===`暂无`?n?t(n):``:/refresh-state|latest_run|latest run-derived/iu.test(r)?t(`projection.refreshState`):/first read-only adapter tick|read-only adapter/iu.test(r)?t(`projection.firstReadOnlyAdapterCheck`):/todo update recorded for/iu.test(r)?t(`projection.todoStatusUpdated`):/^(loopx|python3|npm|git|run)\s|\s--[a-z0-9-]+|\b[a-z]+_[a-z_]+\b/iu.test(r)?t(n??`projection.agentPreparingNextStep`):Wx(r)}function Kx(e,t){return t({advancing:`projection.agentAdvancingGoal`,idle:`projection.agentIdle`,needs_you:`projection.agentNeedsDecision`,stopped:`projection.agentStopped`,waiting_external:`projection.agentWaitingExternal`}[e])}function qx({eventCount:e,hasArtifact:t,hasLatestValidation:n},r){return{label:r(n?`projection.latestValidation`:`projection.latestRun`),metadata:e>0?r(`projection.events24h`,{count:e}):r(t?`projection.runEvidenceAvailable`:`projection.publicSafeProjection`)}}var Jx=`/status.json`,Yx=`loopx-status-source-catalog-v1`,Xx={id:`local`,kind:`local`,label:`本机`,readOnly:!1,statusUrl:Jx};function Zx(e,t){let n=ih(e,t).source;if(!n||!n.isLoopback||n.isRelative)return{error:`SSH 隧道来源必须使用显式的 localhost、127.0.0.1 或 ::1 URL。`};let r=new URL(n.url,t);return[`http:`,`https:`].includes(r.protocol)?{url:r.toString()}:{error:`状态来源只支持 HTTP 或 HTTPS。`}}function Qx(e){let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619);return`ssh-${(t>>>0).toString(36)}`}function $x(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;if(n.kind!==`ssh_tunnel`||typeof n.label!=`string`||typeof n.statusUrl!=`string`)return null;let r=n.label.trim(),i=Zx(n.statusUrl,t);if(!r||r.length>48||!(`url`in i))return null;let a=db(n.hostAlias)?n.hostAlias.trim():void 0;return{...a?{hostAlias:a}:{},id:Qx(i.url),kind:`ssh_tunnel`,label:r,readOnly:!0,statusUrl:i.url}}function eS(){return{schemaVersion:1,sources:[Xx]}}function tS(e,t){try{let n=e.getItem(Yx);if(!n)return eS();let r=JSON.parse(n);if(r.schemaVersion!==1||!Array.isArray(r.sources))return eS();let i=new Set([Xx.statusUrl]);return{schemaVersion:1,sources:[Xx,...r.sources.flatMap(e=>{let n=$x(e,t);return!n||i.has(n.statusUrl)?[]:(i.add(n.statusUrl),[n])})]}}catch{return eS()}}function nS(e,t){e.setItem(Yx,JSON.stringify({schemaVersion:1,sources:t.sources.filter(e=>e.kind===`ssh_tunnel`)}))}function rS(e,t){let n=new Set(t.filter(db).map(e=>e.trim())),r=!1,i=e.sources.map(e=>e.kind!==`ssh_tunnel`||e.hostAlias||!n.has(e.label)?e:(r=!0,{...e,hostAlias:e.label}));return r?{...e,sources:i}:e}function iS(e,t,n){let r=t.label.trim();if(!r)return{error:`请填写来源名称。`};if(r.length>48)return{error:`来源名称不能超过 48 个字符。`};let i=Zx(t.statusUrl,n);if(!(`url`in i))return i;if(e.sources.some(e=>e.statusUrl===i.url))return{error:`这个状态 URL 已经在来源目录中。`};if(t.hostAlias!==void 0&&!db(t.hostAlias))return{error:`请选择有效的 SSH Host。`};let a=t.hostAlias?.trim(),o={...a?{hostAlias:a}:{},id:Qx(i.url),kind:`ssh_tunnel`,label:r,readOnly:!0,statusUrl:i.url};return{catalog:{...e,sources:[...e.sources,o]},source:o}}function aS(e,t){return{...e,sources:e.sources.filter(e=>e.kind===`local`||e.id!==t)}}function oS(e,t,n){if(!t.trim()||ih(t,n).source?.isRelative)return Xx;let r=t.trim();try{r=new URL(r,n).toString()}catch{return null}return e.sources.find(e=>e.statusUrl===r)??null}function sS(e,t,n){return oS(e,t,n)||(ih(t,n).source?.isRelative?Xx:{id:`temporary`,kind:`ssh_tunnel`,label:`临时来源`,readOnly:!0,statusUrl:t.trim()})}function cS(e,t,n,r){return sS(e,t??n,r)}var lS={delete:`删除`,deploy:`部署`,merge:`合并`,payment:`付款`,release:`发布`};function uS(e,t,n){let r=t.replace(/\s+/gu,` `).trim().toLowerCase(),i=n.target.replace(/\s+/gu,` `).trim().toLowerCase();return!i||!r.includes(i)?null:{actionKind:`goal.update`,context:{goal_id:e,kind:`goal`,natural_language:t,semantic_proposal:{operation:n.operation,target:n.target}},idempotencyKey:`workspace-semantic-protected-${e}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e,status:`operator_gate_requested`},summary:`请求受保护操作:${lS[n.operation]} · ${n.target}`}}var dS=Jx;async function fS(e){let t=await fetch(e,{cache:`no-store`,signal:AbortSignal.timeout(3e4)});if(!t.ok)throw Error(`HTTP ${t.status} while loading ${e}`);return Ep(await t.json())}function pS(e,t){if(t?.controller_readiness?.decision_advisor_ready||t?.controller_readiness?.write_controller_ready)return`controller_ready`;if(t?.controller_readiness)return`controller_gated`;if(t?.human_reward)return`reward_judged`;if(t?.operator_gate?.decision===`approve`)return`operator_approved`;if(t?.operator_gate)return`operator_gated`;let n=e||t?.classification||``;return n===`connected_without_run`?`connected`:n===`read_only_project_map`||t?.project_map?`mapped`:n===`state_refreshed`?`refreshed`:n&&n!==`no_status`?`adapter_inspected`:`registered`}function mS(e,t){let n=new Map(t.map(e=>[e.goal_id,e])),r=new Set,i=e.map(e=>{r.add(e.id);let t=n.get(e.id),i=e.latest_runs[0],a=t?.lifecycle_phase??e.lifecycle_phase??i?.lifecycle_phase??pS(t?.status??i?.classification??e.status,i),o=t?.lifecycle_flags?.length?t.lifecycle_flags:e.lifecycle_flags?.length?e.lifecycle_flags:i?.lifecycle_flags?.length?i.lifecycle_flags:[a];return{goal:e,queueItem:t,latestRun:i,status:t?.status??i?.classification??e.status??`no_status`,waitingOn:t?.waiting_on??`clear`,severity:t?.severity??`clear`,lifecyclePhase:a,lifecycleFlags:o}});for(let e of t)r.has(e.goal_id)||i.push({goal:{activation_state:e.activation_state,id:e.goal_id,status:e.status,display_name:e.goal_id,latest_runs:[],lifecycle_flags:[e.lifecycle_phase??`registered`],registry_member:!0,legacy_runtime_goal:!1,index_exists:!1,raw_index_records:0,unique_runs:0},queueItem:e,status:e.status,waitingOn:e.waiting_on,severity:e.severity,lifecyclePhase:e.lifecycle_phase??`registered`,lifecycleFlags:e.lifecycle_flags??[`registered`]});return i}function hS(e){return(e??``).replace(/\s+/g,` `).trim()}function gS(e,t=132){let n=hS(e);return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function _S(e){let t=new Map;for(let n of e?.goals??[])t.set(n.goal_id,n);return t}function vS(e,t){return e===void 0||t===void 0?void 0:e+t}function yS(e,t){if(!e)return null;let n=t===`user`?e.queueItem?.project_asset?.user_todos:e.queueItem?.project_asset?.agent_todos;if(n?.items?.length)return{done_count:n.done??n.items.filter(e=>e.done).length,items:n.items,open_count:n.open??n.items.filter(e=>!e.done).length,total_count:n.total??n.items.length};let r=t===`user`?e.queueItem?.user_todos:e.queueItem?.agent_todos;return r?.items?.length?r:null}function bS(e){return e?.items.find(e=>!e.done)}function xS(e,t,n=`todos`){return e?.items?.length?{advancement_done_count:e.advancement_done_count??t?.advancement_done_count,done_count:e.done??e.items.filter(e=>e.done).length,items:e.items,open_count:e.open??e.items.filter(e=>!e.done).length,total_count:e.total??e.items.length}:t??null}function SS(e){return e?.queueItem?.project_asset?.quota?.state??e?.queueItem?.quota?.state??e?.goal.quota?.state??`waiting`}function CS(e,t,n){let r=[];for(let t of e){let e=yS(t,`agent`);for(let n of e?.items??[])r.push({goalId:t.goal.id,role:`agent`,todo:n})}let i=new Map;for(let e of r){let t=e.todo.claimed_by||`codex`,n=i.get(t)??[];n.push(e),i.set(t,n)}let a=new Map((n?.agents??[]).map(e=>[e.agent_id,e]));return Array.from(new Set([...i.keys(),...a.keys()])).map(e=>{let t=i.get(e)??[],n=a.get(e),r=Array.from(new Set([...t.map(e=>e.goalId),n?.current_todo?.goal_id,...n?.goal_ids??[]].filter(Boolean))),o=(t.filter(e=>!e.todo.done)[0]??t[0])?.goalId??n?.current_todo?.goal_id??r[0]??``,s=n?.last_activity_at??null;return{agentId:e,claimedTodos:t,currentTodo:n?.current_todo??null,evidenceRefs:[],goalIds:r,handoffNote:null,lastActivity:s,nextSafeAction:n?.next_action?.trim()||`Inspect status projection before taking work`,primaryGoalId:o,quotaHints:[],staleClaimHint:null,status:{label:`可用`,summary:`正常运行`,variant:`success`},workspaceRef:null}})}function wS(e){return e?.map(e=>({dataUrl:e.data_url,id:e.id,mimeType:e.mime_type,name:e.name,size:e.size}))}var TS=`loopx.personal-agent-selection.v1`;function ES(){if(typeof window>`u`)return{};try{let e=JSON.parse(window.localStorage.getItem(TS)??`{}`);return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(e=>typeof e[0]==`string`&&typeof e[1]==`string`))}catch{return{}}}var DS={需修复:`danger`,等你:`warning`,等待条件:`info`,推进中:`success`,安静运行:`neutral`,已停止:`neutral`,已完成:`neutral`};function OS(e,t){return hS(t)||e.replace(/^loopx[-_]/i,`LoopX `).split(/[-_]+/).filter(Boolean).map((e,t)=>t===0?`${e.slice(0,1).toUpperCase()}${e.slice(1)}`:e).join(` `)}function kS(e){return e.split(/\r?\n/u).filter(e=>!/^\s*GOAL_(STATUS|PROGRESS)\s*:/u.test(e)).map(e=>/^\s*GOAL_EVIDENCE\s*:/u.test(e)?e.replace(/^\s*GOAL_EVIDENCE\s*:/u,`验证依据:`):/^\s*NEXT_ACTION\s*:/u.test(e)?e.replace(/^\s*NEXT_ACTION\s*:/u,`下一步:`):e).join(` +`)});continue}let o=e.match(/^\s{0,3}#{1,4}\s+(.*)$/);if(o){i();let t=e.trimStart().match(/^#+/)?.[0].length??1;n.push({type:`heading`,level:t,text:o[1].trim()}),a+=1;continue}if(Oy.test(e)||ky.test(e)){i();let r=ky.test(e),o=r?ky:Oy,s=[];for(;a{let n=`b${t}`;if(e.type===`code`)return(0,B.jsx)(`pre`,{className:`personal-md-pre`,children:(0,B.jsx)(`code`,{children:e.text})},n);if(e.type===`heading`)return(0,B.jsx)(`p`,{className:`personal-md-heading is-h${e.level}`,children:Dy(e.text,n)},n);if(e.type===`list`){let t=e.items.map((e,t)=>(0,B.jsx)(`li`,{children:Dy(e,`${n}-${t}`)},`${n}-${t}`));return e.ordered?(0,B.jsx)(`ol`,{className:`personal-md-list`,children:t},n):(0,B.jsx)(`ul`,{className:`personal-md-list`,children:t},n)}return(0,B.jsx)(`p`,{children:e.lines.map((e,t)=>(0,B.jsxs)(z.Fragment,{children:[t>0?(0,B.jsx)(`br`,{}):null,Dy(e,`${n}-${t}`)]},`${n}-${t}`))},n)})})}function My({onSelect:e,output:t}){let{t:n}=Ji(),r=t.kind===`report`?gm:hm;return(0,B.jsxs)(`button`,{className:`personal-timeline-row personal-output-row`,"data-output-kind":t.kind,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-row-icon is-output`,children:(0,B.jsx)(r,{size:18})}),(0,B.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,B.jsxs)(`small`,{children:[t.goalTitle??t.goalId,` · `,t.agentLabel??`LoopX`]}),(0,B.jsx)(`strong`,{children:t.title}),t.summary?(0,B.jsx)(`span`,{children:t.summary}):null,t.report?(0,B.jsxs)(`small`,{children:[n(`files.reportDelta`,{added:t.report.addedCount,changed:t.report.changedCount}),` · `,n(`files.verifiedReport`)]}):null]}),t.createdAt?(0,B.jsx)(`time`,{children:t.createdAt}):null,(0,B.jsx)(nm,{size:17})]})}var Ny={completed:`runs.completed`,failed:`runs.failed`,interrupted:`runs.interrupted`,queued:`runs.queued`,running:`runs.running`,waiting:`runs.waiting`};function Py({onSelect:e,run:t}){let{t:n}=Ji(),r=t.totalSteps>0?Math.min(100,t.completedSteps/t.totalSteps*100):0;return(0,B.jsxs)(`button`,{"aria-label":`${n(`tasks.viewExecution`)}:${t.title}`,className:`personal-timeline-row personal-run-row`,"data-testid":`personal-browse-row`,onClick:e,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-row-icon is-run`,children:(0,B.jsx)(Zp,{size:18})}),(0,B.jsxs)(`span`,{className:`personal-run-identity`,children:[(0,B.jsx)(`small`,{children:t.goalTitle}),(0,B.jsx)(`strong`,{children:t.agentLabel})]}),(0,B.jsxs)(`span`,{className:`personal-row-copy`,children:[(0,B.jsx)(`strong`,{children:t.title}),(0,B.jsx)(`small`,{children:t.latestActivity})]}),(0,B.jsxs)(`span`,{className:`personal-run-progress`,"aria-label":`${t.completedSteps}/${t.totalSteps}`,children:[(0,B.jsxs)(`small`,{children:[t.completedSteps,`/`,t.totalSteps]}),(0,B.jsx)(`i`,{children:(0,B.jsx)(`b`,{style:{width:`${r}%`}})})]}),(0,B.jsxs)(`span`,{className:`personal-row-status is-${t.status}`,children:[t.status===`running`?(0,B.jsx)(Cm,{className:`personal-spin`,size:14}):null,n(Ny[t.status])]}),t.sessionId?(0,B.jsx)(`span`,{className:`personal-run-open-label`,children:n(`tasks.viewExecution`)}):null,(0,B.jsx)(nm,{size:17})]})}function Fy({onSelect:e,schedule:t}){let{t:n}=Ji(),r=t.scheduleKind===`heartbeat`;return(0,B.jsxs)(`button`,{"aria-label":`${r?`Heartbeat`:n(`tasks.scheduled`)}:${t.label};${t.status??`active`}`,className:`personal-schedule-row`,onClick:e,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-schedule-icon`,children:r?(0,B.jsx)(Fm,{size:17}):(0,B.jsx)($p,{size:17})}),(0,B.jsxs)(`span`,{className:`personal-schedule-copy`,children:[(0,B.jsx)(`small`,{children:n(r?`schedule.heartbeat`:`schedule.monitor`)}),(0,B.jsx)(`strong`,{children:t.label}),(0,B.jsx)(`p`,{children:t.schedule??n(`schedule.summary`)})]}),(0,B.jsx)(`span`,{className:`personal-schedule-status is-${t.status??`active`}`,children:t.status===`paused`?n(`schedule.paused`):n(`schedule.active`)}),(0,B.jsx)(nm,{size:16})]})}function Iy({items:e,onSelect:t,selectedGoal:n}){let{t:r}=Ji();if(e.length===0)return(0,B.jsxs)(`div`,{className:`personal-timeline-empty`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Km,{size:20})}),(0,B.jsx)(`strong`,{children:r(n?`timeline.emptyGoal`:`timeline.emptyWorkspace`)}),(0,B.jsx)(`p`,{children:r(n?`timeline.emptyGoalDescription`:`timeline.emptyWorkspaceDescription`)})]});let i=[...e].reverse().find(e=>e.kind===`message`&&e.message.role!==`user`||e.kind===`proposal`&&[`applied`,`stale`,`error`,`gated`].includes(e.proposal.status)||e.kind===`run`&&e.run.status===`completed`),a=i?.kind===`message`?`${i.message.agentLabel??r(`header.manager`)}:${i.message.pending?r(`timeline.pending`):i.message.text}`:i?.kind===`proposal`?`${i.proposal.title}:${i.proposal.status}`:i?.kind===`run`?r(`timeline.runCompleted`,{run:i.run.title}):``,o=e.filter(e=>e.kind===`proposal`&&e.proposal.status===`gated`),s=e.filter(e=>e.kind!==`proposal`),c=e.filter(e=>e.kind===`proposal`&&e.proposal.status!==`gated`);function l(e){return e.kind===`attention`?(0,B.jsx)(Ty,{attention:e.attention,onSelect:()=>t({item:e.attention,kind:`attention`})},e.id):e.kind===`run`?(0,B.jsx)(Py,{onSelect:()=>t({item:e.run,kind:`run`}),run:e.run},e.id):e.kind===`output`?(0,B.jsx)(My,{onSelect:()=>t({item:e.output,kind:`output`}),output:e.output},e.id):e.kind===`schedule`?(0,B.jsx)(Fy,{onSelect:()=>t({item:e.schedule,kind:`schedule`}),schedule:e.schedule},e.id):e.kind===`proposal`?(0,B.jsxs)(`button`,{className:`personal-proposal-row is-${e.proposal.status}`,onClick:()=>t({item:e.proposal,kind:`proposal`}),type:`button`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Km,{size:17})}),(0,B.jsxs)(`span`,{children:[(0,B.jsxs)(`small`,{children:[e.proposal.actionKind,` · `,e.proposal.status]}),(0,B.jsx)(`strong`,{children:e.proposal.title}),(0,B.jsx)(`p`,{children:e.proposal.impact})]}),(0,B.jsx)(`b`,{children:e.proposal.status===`gated`&&e.proposal.actionKind!==`operation.execute`?r(`timeline.review`):e.proposal.primaryLabel??r(`timeline.reviewAndConfirm`)})]},e.id):(0,B.jsxs)(`article`,{className:`personal-message is-${e.message.role}`,children:[e.message.role===`user`?null:(0,B.jsx)(`span`,{className:`personal-message-avatar`,children:(0,B.jsx)(Zp,{size:17})}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:e.message.role===`user`?r(`common.you`):e.message.agentLabel??r(`header.manager`)}),e.message.time?(0,B.jsx)(`time`,{children:e.message.time}):null]}),e.message.attachments?.length?(0,B.jsx)(`div`,{className:`personal-message-images`,children:e.message.attachments.map(e=>(0,B.jsx)(`img`,{alt:e.name,src:e.dataUrl},e.id))}):null,e.message.role===`user`?(0,B.jsx)(`p`,{children:e.message.text}):(0,B.jsx)(jy,{text:e.message.text}),e.message.pending?(0,B.jsx)(`span`,{className:`personal-message-pending`,children:r(`timeline.pending`)}):null]})]},e.id)}return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{"aria-atomic":`true`,"aria-live":`polite`,className:`personal-live-region`,role:`status`,children:a}),(0,B.jsxs)(`div`,{className:`personal-channel-timeline`,children:[s.map(l),o.length?(0,B.jsxs)(`details`,{className:`personal-gated-summary`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Km,{size:16})}),(0,B.jsx)(`strong`,{children:r(`timeline.waitingConfirmation`)}),(0,B.jsx)(`small`,{children:r(`timeline.gateHistory`,{count:o.length})})]}),(0,B.jsx)(`div`,{children:o.map(l)})]}):null,c.map(l)]})]})}function Ly({goal:e}){let{t}=Ji(),n={connected:t(`acceptance.connected`),mapped:t(`acceptance.mapped`),refreshed:t(`acceptance.refreshed`),adapter_inspected:t(`acceptance.inspected`),run_recorded:t(`acceptance.recorded`),reward_judged:t(`acceptance.judged`),operator_approved:t(`acceptance.approved`),controller_ready:t(`acceptance.ready`),attention_queue:t(`acceptance.attentionSource`),agent_vision:t(`acceptance.visionSource`),todo_projection:t(`acceptance.todoSource`),current_run:t(`acceptance.runSource`)},r=e=>n[e]??t(`acceptance.unknown`),i=e.acceptanceObservation,a=e.loadState||!i||i.goal_id!==e.goalId||i.coverage===`unavailable`;return(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-acceptance`,"aria-label":t(`acceptance.title`),children:[(0,B.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,B.jsx)(`h3`,{children:t(`acceptance.title`)}),(0,B.jsx)(`em`,{children:t(`common.readOnly`)})]}),(0,B.jsx)(`p`,{role:`status`,children:t(a?`acceptance.unavailable`:`acceptance.partial`)}),!a&&i?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h4`,{children:t(`acceptance.gaps`)}),i.acceptance_gaps.length?i.acceptance_gaps.map((e,n)=>(0,B.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,B.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.owner`)}),(0,B.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,B.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.observed`)}),(0,B.jsx)(`dd`,{children:e.observed_at??t(`acceptance.unknown`)})]})]})]},`${e.kind}:${e.owner}:${n}`)):(0,B.jsx)(`p`,{children:t(`acceptance.noGaps`)}),(0,B.jsx)(`h4`,{children:t(`acceptance.guards`)}),i.guards.length?i.guards.map((e,n)=>(0,B.jsxs)(`div`,{className:`personal-acceptance-observation`,children:[(0,B.jsx)(`p`,{children:e.reason??t(`acceptance.reasonUnknown`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.owner`)}),(0,B.jsx)(`dd`,{children:e.owner??t(`acceptance.unknown`)})]}),e.blocks_agent?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.agent`)}),(0,B.jsx)(`dd`,{children:e.blocks_agent})]}):null,e.todo_id?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`common.task`)}),(0,B.jsx)(`dd`,{children:e.todo_id})]}):null,(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.required`)}),(0,B.jsx)(`dd`,{children:e.evidence_required??t(`acceptance.unknown`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`acceptance.scope`)}),(0,B.jsx)(`dd`,{children:e.decision_scope??t(`acceptance.unknown`)})]})]})]},`${e.todo_id}:${n}`)):(0,B.jsx)(`p`,{children:t(`acceptance.noGuards`)}),(0,B.jsx)(`h4`,{children:t(`acceptance.next`)}),(0,B.jsx)(`p`,{children:i.next_action??t(`acceptance.unknown`)}),(0,B.jsxs)(`details`,{children:[(0,B.jsxs)(`summary`,{children:[t(`acceptance.historical_progress`),` · `,i.historical_progress.length]}),(0,B.jsx)(`p`,{children:t(`acceptance.historical`)}),i.historical_progress.map(e=>(0,B.jsxs)(`p`,{children:[(0,B.jsx)(`strong`,{children:r(e.kind)}),` · `,e.observed_at??t(`acceptance.unknown`),` `,e.evidence_refs.join(`, `)]},e.kind))]}),i.missing_sources.length?(0,B.jsxs)(`p`,{children:[t(`acceptance.missing`),` `,i.missing_sources.map(r).join(`, `)]}):null,i.truncated?(0,B.jsx)(`p`,{children:t(`acceptance.truncated`)}):null]}):null]})}function Ry({item:e,successor:t,onSelect:n}){let{t:r}=Ji(),i=e.details;return(0,B.jsxs)(`section`,{className:`personal-detail-card`,"aria-label":r(`attentionDetail.title`),children:[(0,B.jsx)(`h3`,{children:r(`attentionDetail.title`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.request`)}),(0,B.jsx)(`dd`,{children:r(i?.interaction===`decision`?`attentionDetail.decision`:`attentionDetail.unknownRequest`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`common.status`)}),(0,B.jsx)(`dd`,{children:r(`attentionDetail.${i?.lifecycle??`unknown`}`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`drawer.reason`)}),(0,B.jsx)(`dd`,{children:i?.reason??e.explanation??r(`attentionDetail.unknownReason`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Todo`}),(0,B.jsx)(`dd`,{children:e.todoId})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.targetTodo`)}),(0,B.jsx)(`dd`,{children:i?.unblocksTodoId??r(`attentionDetail.notProvided`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.targetAgent`)}),(0,B.jsx)(`dd`,{children:i?.blocksAgent??r(`attentionDetail.notProvided`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`attentionDetail.scope`)}),(0,B.jsx)(`dd`,{children:i?.decisionScope?`${i.decisionScope.kind} · ${i.decisionScope.granularity} · ${i.decisionScope.scopeKey}`:r(`attentionDetail.notProvided`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`drawer.evidence`)}),(0,B.jsx)(`dd`,{children:i?.evidence??e.evidence??r(`drawer.decisionDefaultEvidence`)})]})]}),i?.supersededBy?(0,B.jsxs)(`p`,{children:[r(`attentionDetail.replacement`),`: `,i.supersededBy]}):null,t&&n?(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>n(t),type:`button`,children:r(`attentionDetail.openReplacement`)}):null,(0,B.jsx)(`p`,{children:r(`attentionDetail.boundary`)})]})}function zy(e){return e.replace(/\s+/gu,` `).trim()}function By(e,t){let n=RegExp(`(?:不要|不需要|无需|禁止|别|暂不|do not\\b|don't\\b|without\\b).{0,10}(?:${t.source})`,`iu`),r=RegExp(`(?:${t.source}).{0,10}(?:不要|不需要|无需|禁止|关闭)`,`iu`),i=RegExp(`disable\\b.{0,10}(?:${t.source})|(?:turn|switch|set)\\b.{0,10}(?:${t.source}).{0,10}\\boff\\b|(?:${t.source})\\s+(?:is\\s+)?disabled\\b`,`iu`);return n.test(e)||r.test(e)||i.test(e)}function Vy(e){return/(我现在该做什么|下一步|哪些\s*Goal\s*在等我|需要我|谁在等我|Agent\s*在做什么|当前进度|总结(?:今天)?进展)/iu.test(e)}function Hy(e){let t=/(怎么|如何|为什么|给.*建议|分析一下|解释|只读)/u.test(e),n=/(解决一下|修复一下|处理一下|执行一下|改一下|跑(?:一下)?测试|rebase|push|提交|推送)/iu.test(e);return!t&&n&&/(帮我|请|给我|直接|现在|开始|bytedcli|codebase|git|rebase|push|提交|推送)/iu.test(e)}function Uy(e){return zy(e).toLowerCase().match(/(?:^|[\s,,;;:((:]|到|至)(?todo_done:todo_[a-z0-9_-]{3,64}|pr_merged:(?:(?:[a-z0-9_.-]{1,80})\/(?:[a-z0-9_.-]{1,100}))?#[1-9][0-9]{0,8}|capacity_available:[a-z][a-z0-9_:-]{0,63}|resume_at:[1-9][0-9]{3}-[0-9]{2}-[0-9]{2}t[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,3})?(?:z|[+-][0-9]{2}:[0-9]{2}))(?=$|[\s,,。;;))])/iu)?.groups?.condition??null}function Wy(e,t){let n=zy(e),r=[],i=t.agents.find(e=>{let t=n.toLowerCase();return t.includes(e.agentId.toLowerCase())||t.includes(e.label.toLowerCase())}),a=t.todos.find(e=>n.includes(e.todoId)||n.includes(e.text)),o=/(刚刚|已经|已)(?:经)?\s*(新增|创建|添加)(?:的)?\s*(todo|待办|任务)/iu.test(n),s=!!t.goalId&&!By(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n);if(!t.goalId&&!By(n,/goal|目标/iu)&&/(创建|新建|设置|create|start|set up).{0,24}(goal|目标)/iu.test(n)&&r.push({actionKind:`goal.create`,confidence:.97,normalizedParameters:{heartbeat_enabled:!By(n,/heartbeat|心跳/iu)&&/(heartbeat|心跳|每天推进|持续推进|daily progress)/iu.test(n)}}),t.goalId&&s&&r.push({actionKind:`heartbeat.bind`,confidence:.96,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&!s&&!By(n,/定时|监控|监测|持续观察|scheduled check|monitor/iu)&&/(定时|监控|监测|每.{0,8}(分钟|小时|天)|持续观察|scheduled check|monitor|every.{0,12}(minute|hour|day)|daily)/iu.test(n)&&r.push({actionKind:`monitor.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&i&&!By(n,/绑定|负责|接管|管理/iu)&&/((让|交给).{0,20}(管理|负责|接管).{0,8}(goal|目标)|(绑定).{0,12}(goal|目标)|(goal|目标).{0,12}(交给|绑定|负责|接管))/iu.test(n)&&r.push({actionKind:`agent.bind`,confidence:.96,normalizedParameters:{agent_id:i.agentId,goal_id:t.goalId}}),t.goalId&&!o&&!By(n,RegExp(`todo|待办|任务`,`iu`))&&/(创建|新建|新增|添加|加一个|记一个).{0,16}(todo|待办|任务)|(todo|待办|任务).{0,12}(创建|新建|新增|添加)|(?:create|add)(?:\s+(?:a|an|new))?\s+(?:todo|task)|(?:todo|task).{0,12}(?:create|add)/iu.test(n)&&r.push({actionKind:`todo.create`,confidence:.94,normalizedParameters:{goal_id:t.goalId}}),t.goalId&&Hy(n)&&r.push({actionKind:`todo.create`,confidence:.9,normalizedParameters:{goal_id:t.goalId,start_execution:!0}}),t.goalId&&a){let e=!By(n,/完成|做完|关闭/u)&&/完成|做完|关闭/u.test(n)?`complete`:!By(n,/阻塞|卡住/u)&&/阻塞|卡住/u.test(n)?`block`:!By(n,/暂缓|稍后|推迟/u)&&/暂缓|稍后|推迟/u.test(n)?`defer`:i&&!By(n,/交给|分配给|改派/u)&&/交给|分配给|改派/u.test(n)?`reassign`:null;if(e){let i=e===`defer`?Uy(n):null;if(e===`defer`&&!i)return{actionKind:`todo.update`,confidence:.97,missingFields:[`resume_when`],normalizedParameters:{goal_id:t.goalId,operation:e,todo_id:a.todoId},route:`clarify`};r.push({actionKind:`todo.update`,confidence:.97,normalizedParameters:{goal_id:t.goalId,operation:e,...i?{resume_when:i}:{},todo_id:a.todoId}})}}let c=[...new Map(r.map(e=>[e.actionKind,e])).values()];return c.length>1?{actionKind:null,confidence:.4,missingFields:[`single_intent`],normalizedParameters:{},route:`clarify`}:c.length===1?{...c[0],missingFields:[],route:`typed_action`}:!t.goalId&&Vy(n)?{actionKind:null,confidence:.98,missingFields:[],normalizedParameters:{},route:`projection`}:{actionKind:null,confidence:.75,missingFields:[],normalizedParameters:{},route:`agent_chat`}}function Gy(e,t,n){if(!e)return{};if(!t.trim())return{modelConfig:null};let r={model:t.trim()};return n&&(r.reasoning_effort=n),{modelConfig:r}}var Ky=[`a[href]`,`button:not([disabled])`,`textarea:not([disabled])`,`select:not([disabled])`,`input:not([disabled])`,`[tabindex]:not([tabindex='-1'])`].join(`,`),qy=[{key:`drawer.taskBlock`,operation:`block`},{key:`drawer.taskSuccessor`,operation:`successor_create`}],Jy=[{key:`drawer.decisionReject`,resolution:`reject`},{key:`drawer.decisionDefer`,resolution:`defer`}],Yy=Array.from({length:32},(e,t)=>t+1),Xy=/^[a-z][a-z0-9_.-]{0,63}$/u;function Zy(e){let t=String(e??``).trim().toLowerCase();return Xy.test(t)?t:null}function Qy(e,t){return e.enabled===t.enabled&&e.maxChildren===t.maxChildren&&JSON.stringify(e.modelConfig??null)===JSON.stringify(t.modelConfig??null)&&[...e.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)===[...t.allowedDomains].sort((e,t)=>e.localeCompare(t)).join(`\0`)}function $y({agents:e,attentionHistory:t=[],onSelectAttention:n,callbacks:r,goalNotifications:i=[],goals:a=[],inspectorExpanded:o=!1,larkConnections:s=[],onClose:c,onToggleInspectorSize:l,readOnly:u=!1,runs:d=[],selection:f}){let{locale:p,t:m}=Ji(),[h,g]=(0,z.useState)(``),[_,v]=(0,z.useState)(!1),[y,b]=(0,z.useState)(`idle`),[x,S]=(0,z.useState)(`record`),[C,w]=(0,z.useState)([]),[T,E]=(0,z.useState)(null),[D,O]=(0,z.useState)(2),[ee,te]=(0,z.useState)(``),[ne,k]=(0,z.useState)(``),[A,j]=(0,z.useState)(`idle`),[M,N]=(0,z.useState)(null),[P,F]=(0,z.useState)(null),re=(0,z.useRef)(null),ie=(0,z.useRef)(null),[I,ae]=(0,z.useState)(e.find(e=>e.available)?.agentId??`codex`),[L,oe]=(0,z.useState)(``),se=(0,z.useRef)(null),ce=(0,z.useRef)(null),le=(0,z.useRef)(null),ue=(0,z.useRef)(null),de=f.kind===`run`?`run:${f.item.runId}`:f.kind===`proposal`?`proposal:${f.item.previewId}`:f.kind===`todo`?`todo:${f.item.todoId}`:f.kind===`attention`?`attention:${f.item.todoId}`:f.kind===`output`?`output:${f.item.outputId}`:f.kind===`schedule`?`schedule:${f.item.scheduleId}`:`goal:${f.item.goalId}`;(0,z.useEffect)(()=>{b(`idle`),v(!1),S(`record`),oe(``);let e=f.kind===`goal`?f.item.subagentExecution:void 0;w(e?.allowedDomains??[]),te(e?.modelConfig?.model??``),k(e?.modelConfig?.reasoning_effort??``),O(e?.maxChildren?Math.min(e.maxChildren,32):2),E(null),j(`idle`),N(null),F(null),re.current=e??null,ie.current=null},[de]);let fe=f.kind===`goal`?f.item.subagentExecution:void 0;(0,z.useEffect)(()=>{let e=re.current,t=fe?!e||!Qy(e,fe):e!==null;if(re.current=fe??null,!P){t&&fe&&(w(fe.allowedDomains),te(fe.modelConfig?.model??``),k(fe.modelConfig?.reasoning_effort??``),O(fe.maxChildren||2),E(null),j(`idle`),N(null));return}let n=ie.current;(!fe||Qy(P,fe)||n&&!Qy(n,fe))&&(fe&&(w(fe.allowedDomains),te(fe.modelConfig?.model??``),k(fe.modelConfig?.reasoning_effort??``),O(fe.maxChildren||2)),ie.current=null,F(null))},[fe,P]),(0,z.useEffect)(()=>{let e=document.activeElement;e instanceof HTMLElement&&!ce.current?.contains(e)&&(le.current=e);let t=window.requestAnimationFrame(()=>ue.current?.focus());return()=>window.cancelAnimationFrame(t)},[de]);let pe=(0,z.useCallback)(()=>{let e=le.current;c(),window.requestAnimationFrame(()=>e?.focus())},[c]);(0,z.useEffect)(()=>{function e(e){if(e.key===`Escape`){e.preventDefault(),pe();return}if(e.key===`Tab`&&f.kind!==`todo`){let t=Array.from(ce.current?.querySelectorAll(Ky)??[]).filter(e=>!e.hasAttribute(`disabled`)&&e.getAttribute(`aria-hidden`)!==`true`);if(t.length===0)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n.focus())}}return document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`keydown`,e)}},[pe,f.kind]);let me=f.kind===`attention`?m(`drawer.titleAttention`):f.kind===`todo`?m(`drawer.taskDetails`):f.kind===`run`?m(`drawer.runDetails`):f.kind===`output`?m(`drawer.titleOutput`):f.kind===`proposal`?m(f.item.status===`applied`?`drawer.titleProposalApplied`:`drawer.titleProposalConfirm`):f.kind===`schedule`?f.item.scheduleKind===`heartbeat`?`Heartbeat`:m(`drawer.titleSchedule`):m(`drawer.goalDetails`),he=f.kind===`proposal`?f.item.goalId??`manager`:f.item.goalId,ge=f.kind===`attention`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`todo`||f.kind===`run`?f.item.goalTitle:f.kind===`output`?f.item.goalTitle??m(`drawer.currentGoal`):f.kind===`goal`?f.item.title:f.kind===`schedule`?m(`drawer.goalAutoRun`):f.item.goalId?m(`drawer.goalChanges`):m(`drawer.managerChanges`),_e=f.kind===`goal`?d.find(e=>e.goalId===f.item.goalId&&!!e.sessionId)??d.find(e=>e.goalId===f.item.goalId):null,ve=f.kind===`run`&&(f.item.completedSteps>0||!!f.item.latestActivity||!!f.item.outputs?.length),ye=f.kind===`attention`?Zi(f.item.updatedAt,m):null,be=Uy(L);async function xe(){f.kind!==`run`||!h.trim()||(await r.onCorrectRun?.(f.item,h.trim()),g(``))}async function Se(e,t,n,i){if(t===`successor_create`){await r.onPreviewAction?.({actionKind:`todo.create`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-successor-${e.todoId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,text:m(`drawer.taskSuccessorText`,{task:e.text})},summary:m(`drawer.taskSuccessorSummary`,{task:e.text})});return}await r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:e.claimedBy??I,goal_id:e.goalId,operation:t,...t===`block`?{note:m(`drawer.taskSuccessorNote`)}:{},...t===`defer`&&i?{resume_when:i}:{},todo_id:e.todoId},summary:`${n}:${e.text}`})}async function Ce(e,t,n){u||!qd(e)||await r.onPreviewAction?.({actionKind:`gate.resolve`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-decision-${e.todoId}-${t}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,decision:t,todo_id:e.todoId},summary:`${n}:${e.text}`})}let we=f.kind===`goal`?P??f.item.subagentExecution??{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0}:{allowedDomains:[],domainCandidates:[],enabled:!1,maxChildren:0},Te=A===`previewing`||A===`applying`,Ee=(()=>{if(f.kind!==`goal`)return[];let e=new Map;for(let t of we.allowedDomains){let n=Zy(t);n&&e.set(n,{matchingTodoCount:0,value:n})}if(we.domainCandidates)for(let t of we.domainCandidates){let n=Zy(t.domain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+t.matchingTodoCount,value:n})}else for(let t of f.item.agentTodos){if(t.done||t.taskClass!==`advancement_task`)continue;let n=Zy(t.taskDomain);if(!n)continue;let r=e.get(n);e.set(n,{matchingTodoCount:(r?.matchingTodoCount??0)+1,value:n})}return[...e.values()]})();function R(){w(we.allowedDomains),te(we.modelConfig?.model??``),k(we.modelConfig?.reasoning_effort??``),O(we.maxChildren||2),E(null),j(`idle`),N(null)}function De(){let e=[...new Set(C.map(e=>Zy(e)))];return e.every(e=>!!e)?e:null}function Oe(e,t){w(n=>t?[...n,e].filter((e,t,n)=>n.indexOf(e)===t):n.filter(t=>t!==e)),N(null),j(`idle`),E(null)}async function ke(e,t=e){if(f.kind!==`goal`||!r.onPreviewGoalSubagentConfiguration)return;let n=e?De():[];if(t&&!ee.trim()&&ne){j(`error`),E(m(`drawer.subagentModelRequired`));return}if(e&&!n){j(`error`),E(m(`drawer.subagentDomainInvalid`)),N(null);return}let i={allowedDomains:n??[],enabled:e,goalId:f.item.goalId,maxChildren:e?D:0,...Gy(t,ee,ne)};j(`previewing`),E(m(`drawer.subagentPreviewing`)),N(null);try{let e=await r.onPreviewGoalSubagentConfiguration(i);if(!e.changed){ie.current=fe??null,F({...e.configuration,domainCandidates:we.domainCandidates}),w(e.configuration.allowedDomains),te(e.configuration.modelConfig?.model??``),k(e.configuration.modelConfig?.reasoning_effort??``),O(e.configuration.maxChildren||2),j(`success`),E(m(`drawer.subagentNoChange`));return}N({...i,changed:e.changed,previewId:e.previewId}),j(`ready`),E(m(`drawer.subagentPreviewReady`))}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentPreviewFailed`))}}async function Ae(){if(!(!M||!r.onApplyGoalSubagentConfiguration)){j(`applying`),E(m(`drawer.subagentApplying`));try{let e=await r.onApplyGoalSubagentConfiguration({allowedDomains:M.allowedDomains,enabled:M.enabled,goalId:M.goalId,maxChildren:M.maxChildren,modelConfig:M.modelConfig,previewId:M.previewId});ie.current=fe??null,F({...e,domainCandidates:we.domainCandidates}),w(e.allowedDomains),te(e.modelConfig?.model??``),k(e.modelConfig?.reasoning_effort??``),O(e.maxChildren||2),j(`success`),E(m(`drawer.subagentApplied`)),N(null);try{await r.onRefresh?.()}catch{j(`warning`),E(m(`drawer.subagentAppliedRefreshFailed`))}}catch(e){j(`error`),E(e instanceof Error?e.message:m(`drawer.subagentApplyFailed`))}}}return(0,B.jsxs)(`div`,{"aria-labelledby":`personal-drawer-title`,"aria-modal":f.kind===`todo`?void 0:`true`,className:`personal-context-drawer`,"data-context-kind":f.kind,ref:ce,role:`dialog`,children:[(0,B.jsxs)(`header`,{className:`personal-drawer-header${f.kind===`todo`?` is-task-inspector`:``}`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`h2`,{id:`personal-drawer-title`,ref:ue,tabIndex:-1,children:me}),(0,B.jsx)(`p`,{children:ge})]}),(0,B.jsxs)(`div`,{className:`personal-drawer-header-actions`,children:[f.kind===`todo`&&l?(0,B.jsx)(`button`,{"aria-label":m(o?`drawer.inspectorHalf`:`drawer.inspectorFull`),className:`personal-icon-button personal-inspector-size`,onClick:l,title:m(o?`drawer.inspectorHalfView`:`drawer.inspectorFullView`),type:`button`,children:o?(0,B.jsx)(Om,{size:17}):(0,B.jsx)(wm,{size:17})}):null,(0,B.jsxs)(`button`,{"aria-label":m(`drawer.closeDetail`,{context:ge}),className:`personal-icon-button personal-drawer-close`,onClick:pe,ref:se,type:`button`,children:[(0,B.jsx)(Gp,{className:`personal-mobile-back`,size:18}),(0,B.jsx)($m,{className:`personal-desktop-close`,size:18})]})]})]}),(0,B.jsxs)(`div`,{className:`personal-drawer-body`,children:[f.kind===`attention`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card is-attention`,children:[(0,B.jsx)(`small`,{children:f.item.blocking?m(`drawer.attentionBlocking`):m(`drawer.attentionWaiting`)}),(0,B.jsx)(`h3`,{children:f.item.text}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,B.jsx)(`dd`,{children:f.item.priority??`medium`})]}),ye?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`common.waiting`)}),(0,B.jsx)(`dd`,{children:m(`tasks.waitingAge`,{age:ye})})]}):null]})]}),(0,B.jsx)(Ry,{item:f.item,onSelect:n,successor:Kd(f.item,t)}),!u&&qd(f.item)?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void Ce(f.item,`approve`,m(`common.confirm`)),type:`button`,children:[(0,B.jsx)(em,{size:17}),m(`drawer.decisionReview`)]}),(0,B.jsxs)(`details`,{className:`personal-compact-menu`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(dm,{size:17}),m(`drawer.decisionMore`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`button`,{onClick:()=>void r.onExplainDecision?.(f.item),type:`button`,children:[(0,B.jsx)(Em,{size:16}),m(`drawer.explainDecision`)]}),Jy.map(e=>(0,B.jsx)(`button`,{onClick:()=>void Ce(f.item,e.resolution,m(e.key)),type:`button`,children:m(e.key)},e.resolution))]})]})]}):null]}):null,f.kind===`todo`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-task-inspector-summary`,children:[(0,B.jsxs)(`div`,{className:`personal-task-inspector-status`,children:[(0,B.jsxs)(`span`,{className:f.item.done?`is-done`:f.item.status===`blocked`?`is-blocked`:`is-open`,children:[(0,B.jsx)(`i`,{}),f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)]}),f.item.priority?(0,B.jsx)(`span`,{children:f.item.priority}):null,(0,B.jsx)(`span`,{children:f.item.taskClass===`advancement_task`?m(`drawer.taskAdvancement`):f.item.taskClass??m(`drawer.taskOrdinary`)})]}),(0,B.jsx)(`h3`,{children:f.item.text})]}),(0,B.jsxs)(`section`,{"aria-label":m(`drawer.taskInfo`),className:`personal-task-inspector-fields`,children:[(0,B.jsx)(`h4`,{children:m(`drawer.taskInfo`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`common.owner`)}),(0,B.jsx)(`dd`,{children:f.item.ownerLabel??f.item.claimedBy??m(`drawer.notAssigned`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`common.status`)}),(0,B.jsx)(`dd`,{children:f.item.done?m(`drawer.taskStatusCompleted`):f.item.status===`deferred`?m(`drawer.taskStatusDeferred`):f.item.status===`blocked`?m(`drawer.taskStatusBlocked`):m(`drawer.taskStatusOpen`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.priority`)}),(0,B.jsx)(`dd`,{children:f.item.priority??m(`drawer.notSet`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.dependencies`)}),(0,B.jsx)(`dd`,{children:f.item.dependencies?.join(` · `)||m(`common.none`)})]}),f.item.status===`deferred`||f.item.resumeWhen?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.resumeWhen`)}),(0,B.jsx)(`dd`,{children:f.item.resumeWhen||m(`drawer.notSet`)})]}):null,f.item.resumeWhen?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.resumeState`)}),(0,B.jsx)(`dd`,{children:f.item.resumeReady?m(`drawer.resumeReady`):m(`drawer.resumePending`)})]}):null,f.item.resumeReceiptId?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.resumeReceipt`)}),(0,B.jsx)(`dd`,{children:f.item.resumeReceiptId})]}):null,(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.nextTransition`)}),(0,B.jsx)(`dd`,{children:f.item.nextTransition??(f.item.done?m(`drawer.taskNextCompleted`):f.item.resumeReady?m(`drawer.taskNextResumeReady`):f.item.status===`deferred`?m(`drawer.taskNextDeferred`):m(`drawer.taskNextOpen`))})]})]})]}),!u&&!f.item.done?(0,B.jsxs)(`div`,{className:`personal-task-inspector-actions`,"aria-label":m(`drawer.taskActions`),children:[(0,B.jsxs)(`details`,{className:`personal-task-management`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(dm,{size:16}),m(`drawer.taskManage`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:m(`drawer.reassign`)}),(0,B.jsxs)(`label`,{className:`personal-inline-agent-select`,children:[m(`drawer.reassign`),(0,B.jsx)(`select`,{"aria-label":m(`drawer.reassign`),onChange:e=>ae(e.target.value),value:I,children:e.filter(e=>e.available).map(e=>(0,B.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onPreviewAction?.({actionKind:`todo.update`,context:{goal_id:f.item.goalId,kind:`todo`,todo_id:f.item.todoId},idempotencyKey:`workspace-todo-${f.item.todoId}-reassign-${I}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:I,goal_id:f.item.goalId,operation:`reassign`,todo_id:f.item.todoId},summary:m(`drawer.reassignSummary`,{task:f.item.text})}),type:`button`,children:m(`timeline.review`)})]}),(0,B.jsx)(`strong`,{children:m(`drawer.taskDeferUntil`)}),(0,B.jsxs)(`label`,{className:`personal-inline-agent-select personal-inline-resume-when`,children:[m(`drawer.taskDeferUntil`),(0,B.jsx)(`input`,{"aria-label":m(`drawer.taskDeferCondition`),"aria-invalid":!!L.trim()&&!be,onChange:e=>oe(e.target.value),placeholder:m(`drawer.taskDeferPlaceholder`),value:L}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:!be,onClick:()=>void Se(f.item,`defer`,m(`drawer.taskDefer`),be??void 0),type:`button`,children:m(`drawer.taskDeferReview`)}),(0,B.jsx)(`small`,{children:L.trim()&&!be?m(`drawer.taskDeferInvalid`):m(`drawer.taskDeferSupported`)})]}),(0,B.jsx)(`div`,{className:`personal-task-management-secondary`,children:qy.map(e=>(0,B.jsx)(`button`,{onClick:()=>void Se(f.item,e.operation,m(e.key)),type:`button`,children:m(e.key)},e.operation))})]})]}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void Se(f.item,`complete`,m(`drawer.taskComplete`)),type:`button`,children:[(0,B.jsx)(em,{size:17}),m(`drawer.taskComplete`)]})]}):null,f.item.done?(0,B.jsxs)(`div`,{className:`personal-task-completed-note`,children:[(0,B.jsx)(em,{size:16}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:m(`drawer.taskCompletedTitle`)}),(0,B.jsx)(`small`,{children:m(`drawer.taskCompletedNote`)})]})]}):null]}):null,f.kind===`goal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsx)(`small`,{children:Yi(f.item.state,p)}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.agentSentence}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.tokens`)}),(0,B.jsxs)(`dd`,{children:[by(f.item.usage?.tokens24h,m(`drawer.usageNotMeasured`),_y),` / `,by(f.item.usage?.tokens7d,m(`drawer.usageNotMeasured`),_y)]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.cost`)}),(0,B.jsxs)(`dd`,{children:[by(f.item.usage?.costUsd24h,m(`drawer.usageNotMeasured`),vy),` / `,by(f.item.usage?.costUsd7d,m(`drawer.usageNotMeasured`),vy)]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.duration`)}),(0,B.jsxs)(`dd`,{children:[by(f.item.usage?.durationMs24h,m(`drawer.usageNotMeasured`),yy),` / `,by(f.item.usage?.durationMs7d,m(`drawer.usageNotMeasured`),yy)]})]})]})]}),(0,B.jsx)(Ly,{goal:f.item}),(()=>{let e=i.find(e=>e.goalId===f.item.goalId),t=s.find(e=>e.goal_id===f.item.goalId);return(0,B.jsxs)(B.Fragment,{children:[f.item.repository?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-repository`,children:[(0,B.jsxs)(`div`,{className:`personal-detail-card-title`,children:[(0,B.jsx)(`small`,{children:m(`drawer.repository`)}),(0,B.jsx)(`em`,{children:m(`common.readOnly`)})]}),(0,B.jsxs)(`h3`,{children:[(0,B.jsx)(_m,{size:16}),f.item.repository.label]}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.branch`)}),(0,B.jsx)(`dd`,{children:f.item.repository.branch||`detached`})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Role`}),(0,B.jsx)(`dd`,{children:m(`drawer.repositoryRole`)})]})]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>{let e=navigator.clipboard?.writeText(f.item.repository?.identity??``);if(!e){b(`error`);return}e.then(()=>b(`copied`)).catch(()=>b(`error`))},type:`button`,children:[(0,B.jsx)(cm,{size:15}),m(y===`copied`?`drawer.copyRepositoryDone`:`drawer.copyRepository`)]}),y===`error`?(0,B.jsx)(`p`,{className:`personal-copy-feedback is-error`,role:`status`,children:m(`drawer.copyRepositoryError`)}):y===`copied`?(0,B.jsx)(`p`,{className:`personal-copy-feedback`,role:`status`,children:m(`drawer.copyRepositorySuccess`)}):null]}):null,u?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,B.jsx)(`small`,{children:m(`drawer.larkConnection`)}),(0,B.jsx)(`h3`,{children:m(`drawer.remoteDetailsUnavailable`)}),(0,B.jsx)(`p`,{children:m(`drawer.remoteDetailsDescription`)})]}):(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-notification`,children:[(0,B.jsx)(`small`,{children:m(`drawer.larkConnection`)}),t?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`h3`,{children:[t.app_label,(0,B.jsx)(`span`,{className:`personal-connection-status`,children:m(`drawer.connected`)})]}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.group`)}),(0,B.jsx)(`dd`,{children:t.chat_name})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.topic`)}),(0,B.jsxs)(`dd`,{children:[`# `,t.topic_name]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.trigger`)}),(0,B.jsx)(`dd`,{children:t.incoming_mode===`mentions`?m(`lark.someoneMentions`):m(`lark.allMessages`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.replyMode`)}),(0,B.jsx)(`dd`,{children:m(`lark.topicReply`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.autoNotify`)}),(0,B.jsx)(`dd`,{children:e?.humanGateAutoNotifyEnabled?m(`common.on`):m(`common.off`)})]}),e?.lastNotifiedAt?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.lastNotification`)}),(0,B.jsx)(`dd`,{children:e.lastNotifiedAt})]}):null]})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h3`,{children:m(`drawer.larkNotConfigured`)}),(0,B.jsx)(`p`,{children:m(`drawer.larkNotConfiguredDescription`)})]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onOpenNotificationSettings?.(f.item.goalId),type:`button`,children:[(0,B.jsx)(Xp,{size:16}),m(t?`drawer.larkConfigure`:`drawer.larkConnect`)]})]})]})})(),(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-session`,children:[(0,B.jsx)(`small`,{children:m(`drawer.runDetails`)}),_e?.sessionId?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h3`,{children:Xi(_e.sessionStatus??_e.status,m)}),(0,B.jsx)(`p`,{children:_e.title}),r.onOpenRunSession?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onOpenRunSession?.(_e),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.runLatest`)]}):null]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`h3`,{children:m(`drawer.noRun`)}),(0,B.jsx)(`p`,{children:m(`drawer.noRunDescription`)})]})]}),u?null:(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`heartbeat`,f.item.goalId),type:`button`,children:[(0,B.jsx)(Fm,{size:16}),m(`drawer.setupHeartbeat`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>r.onRequestScheduleConfig?.(`monitor`,f.item.goalId),type:`button`,children:[(0,B.jsx)($p,{size:16}),m(`drawer.scheduleAdd`)]})]}),f.item.subagentExecution?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-goal-subagents`,children:[(0,B.jsxs)(`div`,{className:`personal-subagent-heading`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:m(`drawer.subagentLabel`)}),(0,B.jsxs)(`h3`,{children:[(0,B.jsx)(Zp,{size:16}),m(`drawer.subagentTitle`)]})]}),(0,B.jsxs)(`button`,{"aria-checked":we.enabled,"aria-label":m(M&&A===`ready`?`drawer.subagentPending`:we.enabled?`drawer.subagentDisable`:`drawer.subagentEnable`),className:`personal-subagent-switch`,"data-pending":M&&A===`ready`?`true`:void 0,disabled:u||Te||!!M||!r.onPreviewGoalSubagentConfiguration,onClick:()=>void ke(!we.enabled),role:`switch`,type:`button`,children:[(0,B.jsx)(`span`,{}),m(M&&A===`ready`?`drawer.subagentPending`:we.enabled?`common.on`:`common.off`)]})]}),(0,B.jsx)(`p`,{children:m(`drawer.subagentDescription`)}),M&&A===`ready`?(0,B.jsxs)(`div`,{className:`personal-subagent-preview`,children:[(0,B.jsx)(`strong`,{children:m(M.enabled?`drawer.subagentConfirmEnable`:`drawer.subagentConfirmDisable`)}),(0,B.jsx)(`p`,{children:M.enabled?m(`drawer.subagentPreviewSummary`,{count:M.maxChildren,domains:M.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)}):m(`drawer.subagentDisableSummary`)}),M.modelConfig===void 0?null:(0,B.jsxs)(`p`,{children:[m(`drawer.subagentModel`),`: `,M.modelConfig?.model||m(`drawer.subagentModelDefault`),` · `,M.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`button`,{className:`personal-primary-action`,onClick:()=>void Ae(),type:`button`,children:m(`common.confirm`)}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:R,type:`button`,children:m(`common.cancel`)})]})]}):null,T?(0,B.jsxs)(`p`,{className:`personal-subagent-feedback is-${A}`,role:`status`,children:[A===`previewing`||A===`applying`?(0,B.jsx)(Lm,{className:`personal-spin`,size:13}):null,T]}):null,(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentModel`)}),(0,B.jsx)(`dd`,{children:we.modelConfig?.model||m(`drawer.subagentModelDefault`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentEffort`)}),(0,B.jsx)(`dd`,{children:we.modelConfig?.reasoning_effort||m(`drawer.subagentModelDefault`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentCurrentBoundary`)}),(0,B.jsx)(`dd`,{children:we.allowedDomains.join(` · `)||m(`drawer.subagentDomainsUnrestricted`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.subagentChildLimit`)}),(0,B.jsx)(`dd`,{children:we.maxChildren||0})]})]}),u?(0,B.jsx)(`p`,{className:`personal-subagent-read-only`,children:m(`drawer.subagentRemoteReadOnly`)}):(0,B.jsxs)(`div`,{className:`personal-subagent-fields`,children:[(0,B.jsxs)(`fieldset`,{className:`personal-subagent-domain-picker`,disabled:Te,children:[(0,B.jsx)(`legend`,{children:m(`drawer.subagentDomains`)}),Ee.length>0?(0,B.jsx)(`div`,{className:`personal-subagent-domain-options`,children:Ee.map(e=>{let t=C.includes(e.value);return(0,B.jsxs)(`label`,{className:`personal-subagent-domain-option${t?` is-selected`:``}`,children:[(0,B.jsx)(`input`,{"aria-label":e.value,checked:t,onChange:t=>Oe(e.value,t.target.checked),type:`checkbox`}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.value}),(0,B.jsx)(`small`,{children:m(`drawer.subagentDomainTodoCount`,{count:e.matchingTodoCount})})]})]},e.value)})}):(0,B.jsx)(`p`,{className:`personal-subagent-domain-empty`,children:m(`drawer.subagentDomainsEmpty`)}),(0,B.jsx)(`small`,{children:m(`drawer.subagentDomainsHint`)})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:m(`drawer.subagentModel`)}),(0,B.jsx)(`input`,{"aria-label":m(`drawer.subagentModel`),disabled:Te,value:ee,placeholder:`gpt-5.6-luna`,onChange:e=>{te(e.target.value),N(null),j(`idle`),E(null)}})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:m(`drawer.subagentEffort`)}),(0,B.jsxs)(`select`,{"aria-label":m(`drawer.subagentEffort`),disabled:Te,value:ne,onChange:e=>{k(e.target.value),N(null),j(`idle`),E(null)},children:[(0,B.jsx)(`option`,{value:``,children:m(`drawer.subagentModelDefault`)}),[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`].map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))]})]}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:Te,type:`button`,onClick:()=>{te(`gpt-5.6-luna`),k(`max`),N(null),j(`idle`),E(null)},children:m(`drawer.subagentLunaPreset`)}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:Te,type:`button`,onClick:()=>{te(``),k(``),N(null),j(`idle`),E(null)},children:m(`drawer.subagentClearModel`)}),(0,B.jsx)(`p`,{children:m(`drawer.subagentModelHint`)}),(0,B.jsxs)(`label`,{className:`personal-subagent-limit-field`,children:[(0,B.jsx)(`span`,{children:m(`drawer.subagentMaxChildren`)}),(0,B.jsx)(`select`,{"aria-label":m(`drawer.subagentMaxChildren`),disabled:Te,onChange:e=>{O(Number(e.target.value)),N(null),j(`idle`),E(null)},value:D,children:Yy.map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))})]}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,disabled:Te,onClick:()=>void ke(we.enabled,!0),type:`button`,children:m(`drawer.subagentPreviewBoundary`)})]})]}):null]}):null,f.kind===`run`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{"aria-label":m(`drawer.runView`),className:`personal-run-drawer-tabs`,role:`tablist`,children:[(0,B.jsx)(`button`,{"aria-selected":x===`record`,onClick:()=>S(`record`),role:`tab`,type:`button`,children:m(`drawer.executionRecordAndResult`)}),(0,B.jsx)(`button`,{"aria-selected":x===`details`,onClick:()=>S(`details`),role:`tab`,type:`button`,children:m(`drawer.detailsAndActions`)})]}),x===`record`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card personal-session-summary`,children:[(0,B.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Xi(f.item.sessionStatus??f.item.status,m)]}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.latestActivity}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,B.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]})]})]}),(0,B.jsxs)(`section`,{"aria-label":m(`drawer.executionRecord`),className:`personal-session-message-record`,children:[(0,B.jsx)(`h3`,{children:m(`drawer.executionRecord`)}),f.item.sessionMessages?.length?(0,B.jsx)(`ol`,{children:f.item.sessionMessages.map(e=>(0,B.jsxs)(`li`,{className:`is-${e.role}`,children:[(0,B.jsx)(`i`,{}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:e.role===`user`?m(`drawer.runRoleUser`):e.role===`assistant`?m(`drawer.runRoleAssistant`):m(`drawer.runRoleSystem`)}),e.createdAt?(0,B.jsx)(`time`,{children:new Date(e.createdAt).toLocaleTimeString(p,{hour:`2-digit`,minute:`2-digit`,hour12:!1})}):null]}),(0,B.jsx)(`p`,{children:e.text})]})]},e.messageId))}):(0,B.jsx)(`p`,{className:`personal-session-empty`,children:ve?m(`drawer.runRecordProjected`,{completed:f.item.completedSteps,outputs:f.item.outputs?.length?m(`drawer.runRecordProjectedOutputs`,{count:f.item.outputs.length}):``,total:f.item.totalSteps}):m(`drawer.runRecordEmpty`)}),f.item.status===`running`?(0,B.jsxs)(`div`,{className:`personal-session-active-step`,children:[(0,B.jsx)(`i`,{}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:m(`drawer.analysis`)}),(0,B.jsx)(`small`,{children:m(`drawer.agentWorking`)})]})]}):null]}),f.item.outputs?.length?(0,B.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-run-outputs-title`,children:[(0,B.jsx)(`h3`,{id:`personal-run-outputs-title`,children:m(`drawer.outputs`)}),(0,B.jsx)(`ol`,{children:f.item.outputs.map(e=>(0,B.jsx)(`li`,{children:(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsx)(`small`,{children:e.createdAt??e.kind??m(`files.emptySummary`)})]})},e.outputId))})]}):null]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsxs)(`small`,{children:[f.item.agentLabel,` · `,Xi(f.item.status,m)]}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.latestActivity}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.progress`)}),(0,B.jsxs)(`dd`,{children:[f.item.completedSteps,`/`,f.item.totalSteps]})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.sessionStatus`)}),(0,B.jsx)(`dd`,{children:Xi(f.item.sessionStatus??f.item.status,m)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.sessionRecoverable`)}),(0,B.jsx)(`dd`,{children:f.item.resumable===!1?m(`drawer.resumeNo`):m(`drawer.resumeYes`)})]})]})]}),f.item.sessionStatus===`resume_failed`&&!u?(0,B.jsxs)(`section`,{className:`personal-recovery-panel`,"aria-label":m(`drawer.recoveryFailed`),children:[(0,B.jsx)(`strong`,{children:m(`drawer.recoveryFailed`)}),(0,B.jsx)(`p`,{children:m(`drawer.recoveryDescription`)}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,B.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.recoveryNewSession`)]})]}):null,u?null:(0,B.jsxs)(`section`,{className:`personal-correction-panel`,children:[(0,B.jsx)(`header`,{children:(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:16}),m(`drawer.correctionLabel`,{agent:f.item.agentLabel})]})}),(0,B.jsx)(`p`,{children:m(`drawer.correctionDescription`)}),(0,B.jsxs)(`div`,{className:`personal-correction-composer`,children:[(0,B.jsx)(`textarea`,{"aria-label":m(`drawer.correctionTextarea`,{agent:f.item.agentLabel,goal:f.item.goalTitle,run:f.item.title}),onChange:e=>g(e.target.value),placeholder:m(`drawer.correctionPlaceholder`),rows:3,value:h}),(0,B.jsx)(`button`,{"aria-label":m(`drawer.correctionSend`),disabled:!h.trim(),onClick:()=>void xe(),type:`button`,children:(0,B.jsx)(Bm,{size:16})})]})]}),u?null:(0,B.jsxs)(`details`,{className:`personal-compact-menu personal-run-more`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(dm,{size:17}),m(`drawer.moreRunActions`)]}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`button`,{disabled:!f.item.canInterrupt,onClick:()=>void r.onInterruptRun?.(f.item),type:`button`,children:[(0,B.jsx)(Mm,{size:16}),m(`drawer.runInterrupt`)]}),(0,B.jsxs)(`button`,{disabled:f.item.resumable===!1,onClick:()=>void r.onRetryResumeRun?.(f.item),type:`button`,children:[(0,B.jsx)(Lm,{size:16}),m(`drawer.recoveryRetry`)]}),(0,B.jsxs)(`button`,{onClick:()=>void r.onStartNewRunSession?.(f.item),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.runNewSession`)]}),(0,B.jsxs)(`button`,{onClick:()=>void r.onCloseRunSession?.(f.item),type:`button`,children:[(0,B.jsx)(qm,{size:16}),m(`drawer.runCloseSession`)]})]})]})]})]}):null,f.kind===`output`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsx)(`small`,{children:f.item.kind??`output`}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.summary??m(`drawer.outputRecorded`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Goal`}),(0,B.jsx)(`dd`,{children:f.item.goalTitle??f.item.goalId})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.outputTodo`)}),(0,B.jsx)(`dd`,{children:f.item.todoId??m(`drawer.notLinked`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.outputRun`)}),(0,B.jsx)(`dd`,{children:f.item.runId??m(`drawer.notLinked`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Agent`}),(0,B.jsx)(`dd`,{children:f.item.agentLabel??f.item.agentId??`LoopX`})]})]})]}),f.item.report?(0,B.jsxs)(`section`,{className:`personal-report-detail`,"data-testid":`personal-periodic-report-detail`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsxs)(`strong`,{children:[`+`,f.item.report.addedCount]}),m(`files.reportAdded`)]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:f.item.report.changedCount}),m(`files.reportChanged`)]})]}),(0,B.jsxs)(`p`,{children:[f.item.report.periodStartAt,` → `,f.item.report.periodEndAt]}),(0,B.jsx)(`ol`,{children:f.item.report.items.map(e=>(0,B.jsxs)(`li`,{"data-change-kind":e.changeKind,children:[(0,B.jsxs)(`small`,{children:[e.changeKind,` · `,e.status]}),(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsx)(`p`,{children:e.summary})]},e.sourceRef))}),(0,B.jsxs)(`footer`,{children:[(0,B.jsxs)(`span`,{children:[m(`files.reportPublication`),`: `,f.item.report.publicationId]}),(0,B.jsxs)(`span`,{children:[m(`files.reportGeneration`),`: `,f.item.report.generationId]})]})]}):null,f.item.safePreview?(0,B.jsx)(`pre`,{"aria-label":m(`drawer.outputSafePreview`),className:`personal-safe-preview`,children:f.item.safePreview}):(0,B.jsx)(`p`,{className:`personal-preview-unavailable`,children:m(`drawer.previewUnavailable`)}),(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:!r.onOpenOutput,onClick:()=>{r.onOpenOutput?.(f.item),c()},type:`button`,children:[(0,B.jsx)(fm,{size:16}),m(`files.openConversation`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!r.onExportOutput,onClick:()=>void r.onExportOutput?.(f.item),type:`button`,children:[(0,B.jsx)(um,{size:16}),m(`files.exportSummary`)]})]})]}):null,f.kind===`proposal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-proposal-card`,children:[(0,B.jsxs)(`small`,{children:[f.item.actionKind,` · `,f.item.status]}),(0,B.jsx)(`h3`,{children:f.item.title}),(0,B.jsx)(`p`,{children:f.item.impact}),f.item.reviewPlan?(0,B.jsx)(`p`,{className:`personal-proposal-explainer`,"data-action-review":f.item.reviewPlan.interaction,children:f.item.actionKind===`operation.execute`&&f.item.status===`gated`?m(`actionReview.operation_group_confirmation`):f.item.actionKind===`operation.execute`&&f.item.reviewPlan.reason===`readback_unverified`?m(`actionReview.operation_result_delivery_pending`):m(`actionReview.${f.item.reviewPlan.reason}`)}):null,f.item.status===`ready`?(0,B.jsx)(`p`,{className:`personal-proposal-explainer`,children:m(`drawer.proposalExplainer`)}):null,(0,B.jsx)(`dl`,{children:f.item.fields.map(e=>(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:e.label}),(0,B.jsx)(`dd`,{children:e.value})]},e.key))})]}),f.item.status===`applied`?(0,B.jsxs)(`p`,{className:`personal-proposal-state ${f.item.actionKind===`operation.execute`&&f.item.reviewPlan?.reason===`readback_unverified`?`is-gated`:`is-applied`}`,children:[(0,B.jsx)(em,{size:16}),f.item.actionKind===`operation.execute`?f.item.primaryLabel:m(`drawer.proposalApplied`)]}):null,f.item.status===`applied`&&f.item.actionKind!==`operation.execute`&&f.item.goalId?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>{let e=f.item.goalId;c(),r.onOpenGoal?.(e)},type:`button`,children:[(0,B.jsx)(fm,{size:16}),f.item.actionKind===`goal.create`?m(`drawer.proposalEnterGoal`):m(`drawer.proposalViewGoal`)]}):null,f.item.status===`stale`?(0,B.jsx)(`p`,{className:`personal-proposal-state is-stale`,children:m(`drawer.proposalStale`)}):null,f.item.status===`error`?(0,B.jsxs)(`div`,{className:`personal-proposal-state is-error`,children:[(0,B.jsx)(`span`,{children:f.item.reviewPlan?.reason===`readback_unverified`?m(`actionReview.readback_unverified`):m(`drawer.proposalApplyFailed`)}),f.item.errorMessage?(0,B.jsx)(`small`,{children:f.item.errorMessage}):null,(0,B.jsx)(`small`,{children:m(`drawer.proposalApplyFailedHint`)})]}):null,f.item.status===`rejected`?(0,B.jsx)(`p`,{className:`personal-proposal-state is-error`,children:m(`drawer.proposalRejected`)}):null,f.item.status===`deferred`?(0,B.jsx)(`p`,{className:`personal-proposal-state is-gated`,children:m(`drawer.proposalDeferred`)}):null,f.item.status===`gated`?(0,B.jsxs)(`div`,{className:`personal-proposal-state is-gated`,children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:f.item.actionKind===`operation.execute`?f.item.primaryLabel:m(`drawer.gateRequiresHost`)}),f.item.actionKind===`operation.execute`?f.item.impact:m(`drawer.gateRequiresHostDescription`)]}),f.item.gate?.nextAction?(0,B.jsx)(`small`,{children:f.item.gate.nextAction}):null]}):null,f.item.status===`gated`&&f.item.actionKind===`gate.resolve`?(()=>{let e=e=>f.item.fields.find(t=>t.key===e)?.value,t=e(`goal_id`),n=e(`todo_id`);return!t||!n?null:(0,B.jsxs)(`section`,{className:`personal-detail-card personal-gate-cli-hint`,children:[(0,B.jsx)(`small`,{children:m(`drawer.gateApproveHint`)}),(0,B.jsxs)(`code`,{children:[`loopx todo complete --goal-id `,t,` --todo-id `,n,` --decision-outcome approve`]}),(0,B.jsx)(`small`,{children:m(`drawer.gateRejectHint`)})]})})():null,!u&&f.item.workspaceCandidates?.length?(0,B.jsx)(`div`,{className:`personal-workspace-candidates`,"aria-label":m(`drawer.workspaceCandidates`),children:f.item.workspaceCandidates.map(e=>(0,B.jsxs)(`button`,{onClick:()=>void r.onSelectWorkspaceCandidate?.(f.item,e.workspaceRef),type:`button`,children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsx)(`small`,{children:e.workspaceRef})]},e.workspaceRef))}):null,!u&&f.item.actionKind!==`operation.execute`&&f.item.status===`error`?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,B.jsx)(Lm,{size:17}),m(`drawer.proposalRegenerate`)]}):!u&&f.item.actionKind!==`operation.execute`&&f.item.status!==`gated`?(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:![`ready`,`deferred`].includes(f.item.status)||f.item.reviewPlan?.canApply===!1,onClick:()=>void r.onApplyProposal?.(f.item),type:`button`,children:[(0,B.jsx)(em,{size:17}),f.item.status===`applying`?m(`drawer.applying`):f.item.primaryLabel??m(`drawer.apply`)]}):null,!u&&f.item.actionKind!==`operation.execute`&&([`stale`,`gated`,`rejected`].includes(f.item.status)||f.item.status===`ready`&&f.item.reviewPlan?.canApply===!1)?(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`regenerate`),type:`button`,children:[(0,B.jsx)(Lm,{size:16}),m(`drawer.proposalRecheck`)]}):null,!u&&f.item.actionKind!==`operation.execute`&&[`ready`,`gated`].includes(f.item.status)?(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`defer`),type:`button`,children:m(`drawer.proposalDefer`)}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onTransitionProposal?.(f.item,`reject`),type:`button`,children:m(`drawer.decisionReject`)})]}):null,[`applied`,`applying`].includes(f.item.status)?null:(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:c,type:`button`,children:m(`drawer.proposalClose`)})]}):null,f.kind===`schedule`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`section`,{className:`personal-detail-card`,children:[(0,B.jsxs)(`small`,{children:[f.item.scheduleKind===`heartbeat`?`Goal Heartbeat`:`continuous_monitor`,` · `,f.item.status??`active`]}),(0,B.jsx)(`h3`,{children:f.item.label}),(0,B.jsx)(`p`,{children:f.item.target??f.item.schedule??m(`drawer.scheduleDefaultTarget`)}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleTimezone`)}),(0,B.jsx)(`dd`,{children:f.item.timezone??m(`drawer.scheduleLocalTimezone`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleNext`)}),(0,B.jsx)(`dd`,{children:f.item.nextRunAt??m(`drawer.schedulePending`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleLast`)}),(0,B.jsx)(`dd`,{children:f.item.previousRunAt??m(`drawer.scheduleNeverRun`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleNotification`)}),(0,B.jsx)(`dd`,{children:f.item.notificationRule??m(`drawer.scheduleDefaultNotification`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:m(`drawer.scheduleStopCondition`)}),(0,B.jsx)(`dd`,{children:f.item.stopCondition??m(`drawer.scheduleDefaultStop`)})]})]})]}),!u&&f.item.scheduleKind===`monitor`?(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`run_now`),type:`button`,children:[(0,B.jsx)(Nm,{size:16}),m(`drawer.scheduleRunNow`)]}):null,u?null:(0,B.jsxs)(`div`,{className:`personal-drawer-action-grid`,children:[(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,f.item.status===`paused`?`resume`:`pause`),type:`button`,children:[f.item.status===`paused`?(0,B.jsx)(Nm,{size:16}):(0,B.jsx)(Mm,{size:16}),f.item.status===`paused`?m(`drawer.scheduleResume`):m(`drawer.schedulePause`)]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`edit`),type:`button`,children:[(0,B.jsx)($p,{size:16}),m(`drawer.scheduleEdit`)]})]}),u?null:(0,B.jsxs)(`button`,{className:`personal-danger-action`,onClick:()=>void r.onUpdateSchedule?.(f.item,`stop`),type:`button`,children:[(0,B.jsx)(qm,{size:16}),m(`drawer.scheduleStop`,{kind:f.item.scheduleKind===`heartbeat`?` Heartbeat`:m(`drawer.titleSchedule`)})]}),(0,B.jsxs)(`section`,{className:`personal-execution-history`,"aria-labelledby":`personal-execution-history-title`,children:[(0,B.jsx)(`h3`,{id:`personal-execution-history-title`,children:m(`drawer.executionHistory`)}),f.item.executionHistory?.length?(0,B.jsx)(`ol`,{children:f.item.executionHistory.map((e,t)=>(0,B.jsxs)(`li`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsx)(`small`,{children:e.timestamp})]}),(0,B.jsx)(`em`,{className:`is-${e.status}`,children:e.status})]},`${e.timestamp}:${e.runId??t}`))}):(0,B.jsx)(`p`,{children:m(`drawer.noExecutionHistory`)})]})]}):null,f.kind===`run`||f.kind===`proposal`||f.kind===`schedule`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`button`,{"aria-expanded":_,className:`personal-diagnostics-trigger`,onClick:()=>v(e=>!e),type:`button`,children:[(0,B.jsx)(`span`,{children:m(`drawer.advancedDiagnostics`)}),(0,B.jsx)(tm,{className:_?`is-open`:``,size:16})]}),_?(0,B.jsxs)(`div`,{className:`personal-diagnostics`,children:[(0,B.jsxs)(`code`,{children:[`goal_id: `,he]}),(0,B.jsxs)(`code`,{children:[`kind: `,f.kind]}),f.kind===`run`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`code`,{children:[`session_id: `,f.item.sessionId??m(`drawer.notLinked`)]}),(0,B.jsxs)(`code`,{children:[`turn_id: `,f.item.turnId??m(`common.none`)]}),(0,B.jsxs)(`code`,{children:[`adapter: `,f.item.agentId]}),(0,B.jsxs)(`code`,{children:[`status: `,f.item.sessionStatus??f.item.status]})]}):f.kind===`proposal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`code`,{children:[`action: `,f.item.actionKind]}),(0,B.jsxs)(`code`,{children:[`status: `,f.item.status]})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`code`,{children:[`schedule_id: `,f.item.scheduleId]}),(0,B.jsxs)(`code`,{children:[`status: `,f.item.status??`active`]})]})]}):null]}):null]})]})}var eb=[`checking`,`connecting`,`downloading`,`installing_app`,`installing_runtime`],tb={desktop_status_unavailable:[`无法读取 App 更新状态。请重启 App 后再试;若仍失败,请重新安装最新 App。`,`Cannot read the App update status. Restart the App; if this persists, reinstall the latest App.`],update_feed_unavailable:[`此通道的更新源尚未就绪或暂时不可用。可稍后重新检查,当前版本仍可继续使用。`,`This channel's update feed is not ready or temporarily unavailable. Check again later; you can keep using this version.`],update_feed_invalid:[`更新源格式异常。请稍后重新检查。`,`The update feed is invalid. Check again later.`],update_platform_unavailable:[`此通道尚无适用于本机的更新包。`,`This channel has no update package for this platform.`],update_check_timeout:[`检查更新超时。请稍后重试。`,`The update check timed out. Try again later.`],update_network_failed:[`无法连接更新服务器。请检查网络后重试。`,`Cannot reach the update server. Check your connection and retry.`],update_download_or_signature_failed:[`更新包下载或签名校验失败,尚未安装。请重新检查更新。`,`Download or signature verification failed; the update was not installed. Check for updates again.`]};function nb(e,t=`update_failed`){return{phase:`error`,details:{code:typeof e==`string`&&Object.hasOwn(tb,e)?e:t}}}function rb(){let{locale:e}=Ji(),t=e===`zh-CN`,[n,r]=(0,z.useState)(!1),i=(0,z.useRef)(null),[a,o]=(0,z.useState)(`stable`),[s,c]=(0,z.useState)({phase:`idle`}),[l,u]=(0,z.useState)(``),[d,f]=(0,z.useState)(!1),p=(0,z.useRef)(!1),m=window.__TAURI__?.core.invoke,h=eb.includes(s.phase);(0,z.useEffect)(()=>{let e=i.current;if(!e)return;let t=()=>r(e.matches(`:popover-open`));return e.addEventListener(`toggle`,t),()=>e.removeEventListener(`toggle`,t)},[]),(0,z.useEffect)(()=>{if(!m)return;let e=!0;return m(`desktop_update_status`).then(t=>{if(!e)return;u(t.app_version),f(t.rollback_available===!0),t.state?.phase&&c(t.state);let n=t.state?.details?.channel??(t.app_version.includes(`-main.`)?`main`:`stable`);o(n),t.state?.phase||m(`desktop_update`,{action:`check`,channel:n}).then(t=>{e&&c(t)}).catch(t=>{e&&c(nb(t))})}).catch(()=>{e&&c(nb(null,`desktop_status_unavailable`))}),()=>{e=!1}},[m]),(0,z.useEffect)(()=>{if(!m||!h)return;let e=window.setInterval(()=>{m(`desktop_update_status`).then(e=>{e.state?.phase&&c(e.state)}).catch(()=>{})},1e3);return()=>window.clearInterval(e)},[m,h]);async function g(e){if(!(!m||p.current)){p.current=!0,c({phase:e===`check`?`checking`:e===`repair`?`installing_runtime`:`downloading`});try{if(!l){let e=await m(`desktop_update_status`);u(e.app_version),f(e.rollback_available===!0)}c(await m(`desktop_update`,{action:e,channel:a}))}catch(e){c(nb(e,l?`update_failed`:`desktop_status_unavailable`))}finally{p.current=!1}}}let _={service_error:t?`运行时已安装,但服务尚未连接。可重试更新、修复或恢复上版。`:`Runtime installed, but services are unavailable. Retry updates, repair, or restore the previous version.`,idle:t?`App 会检查可用更新,不会自动安装。`:`Updates are checked automatically, never installed without confirmation.`,runtime_required:t?`请完成匹配组件安装,或检查 App 更新。`:`Install matching components or check for an App update.`,connecting:t?`正在连接更新后的服务…`:`Connecting to updated services…`,checking:t?`正在检查更新…`:`Checking for updates…`,available:t?`新版本已就绪,一次更新 App 与匹配的运行时。`:`Update the App and its matching runtime together.`,up_to_date:t?`当前通道暂无更新。`:`No newer update on this channel.`,downloading:t?`正在下载并校验签名…`:`Downloading and verifying signature…`,installing_app:t?`正在安装 App,请保持窗口打开。`:`Installing the App. Keep this window open.`,installing_runtime:t?`正在安装匹配的运行时,请稍候…`:`Installing the matching runtime…`,restart_required:t?`重启后将自动完成运行时安装与服务连接。`:`Restart to finish runtime installation and reconnect services.`,ready:t?`更新完成,服务已就绪。`:`Update completed; services are ready.`,error:tb[s.details?.code??``]?.[+!t]??(t?`更新未完成。请重试;启动失败可尝试修复当前版本。`:`Update incomplete. Retry; repair this version if startup fails.`)},v=h?t?`正在更新…`:`Updating…`:s.phase===`available`?t?`有可用更新`:`Update available`:s.phase===`restart_required`?t?`重启完成更新`:`Restart to finish`:s.phase===`error`?t?`更新需重试`:`Retry update`:t?`更新 LoopX`:`Update LoopX`;return(0,B.jsxs)(`div`,{className:`personal-desktop-update`,children:[(0,B.jsxs)(`button`,{className:`personal-update-trigger`,type:`button`,"aria-expanded":n,"aria-controls":`desktop-update-panel`,onClick:e=>{i.current?.style.setProperty(`bottom`,`${window.innerHeight-e.currentTarget.getBoundingClientRect().top+8}px`),i.current?.togglePopover()},children:[(0,B.jsx)(um,{size:16,"aria-hidden":`true`}),(0,B.jsx)(`span`,{children:v}),(0,B.jsx)(rm,{size:14,"aria-hidden":`true`})]}),(0,B.jsxs)(`section`,{ref:i,popover:`auto`,id:`desktop-update-panel`,className:`personal-update-panel`,"aria-label":t?`LoopX 更新`:`LoopX updates`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:t?`LoopX 更新`:`LoopX updates`}),(0,B.jsx)(`button`,{type:`button`,"aria-label":t?`关闭更新面板`:`Close updates`,onClick:()=>i.current?.hidePopover(),children:(0,B.jsx)($m,{size:16,"aria-hidden":`true`})})]}),(0,B.jsxs)(`small`,{children:[l,` · `,a===`main`?t?`main 预览版`:`main preview`:t?`稳定版`:`Stable`]}),s.details?.version?(0,B.jsxs)(`p`,{children:[t?`目标版本:`:`Target: `,s.details.version]}):null,(0,B.jsxs)(`p`,{role:`status`,"aria-live":`polite`,children:[h?(0,B.jsx)(Im,{className:`is-spinning`,size:14,"aria-hidden":`true`}):null,_[s.phase]]}),s.phase===`downloading`&&s.details?.total?(0,B.jsx)(`progress`,{"aria-label":t?`下载进度`:`Download progress`,max:s.details.total,value:s.details.received??0}):null,m?(0,B.jsx)(`div`,{className:`personal-update-actions`,children:s.phase===`restart_required`?(0,B.jsx)(`button`,{type:`button`,onClick:()=>void g(`restart`),children:t?`重启完成更新`:`Restart to finish`}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`button`,{type:`button`,disabled:h,onClick:()=>void g(`check`),children:t?`检查更新`:`Check for updates`}),s.phase===`available`?(0,B.jsx)(`button`,{type:`button`,onClick:()=>void g(`apply`),children:t?`更新并准备重启`:`Install update`}):null]})}):(0,B.jsx)(`p`,{children:t?`请在 LoopX App 中更新;浏览器自身无需安装包。`:`Update from the LoopX App; the browser needs no installer.`}),(0,B.jsxs)(`details`,{children:[(0,B.jsx)(`summary`,{children:t?`高级选项`:`Advanced options`}),(0,B.jsxs)(`label`,{children:[t?`更新通道`:`Update channel`,(0,B.jsxs)(`select`,{disabled:h||s.phase===`restart_required`,value:a,onChange:e=>{o(e.target.value),c({phase:`idle`})},children:[(0,B.jsx)(`option`,{value:`stable`,children:t?`稳定版(推荐)`:`Stable (recommended)`}),(0,B.jsx)(`option`,{value:`main`,children:t?`main 预览版`:`main preview`})]})]}),(0,B.jsx)(`p`,{children:t?`App 与匹配的 CLI 一起更新,服务可能短暂断开。不删除 Goal 数据。`:`Updates the App and matching CLI. Services may briefly disconnect. Goal data is not deleted.`}),m?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{children:t?`启动失败时,可重装当前 App 随附的运行时。`:`If startup fails, reinstall this App's bundled runtime.`}),(0,B.jsx)(`button`,{disabled:h||s.phase===`restart_required`,type:`button`,onClick:()=>void g(`repair`),children:t?`修复当前版本`:`Repair this version`})]}):null,m&&d?(0,B.jsxs)(`details`,{children:[(0,B.jsx)(`summary`,{children:t?`恢复上个版本`:`Restore previous version`}),(0,B.jsx)(`p`,{children:t?`将恢复已保留的 App 和它的运行时,需要重启。`:`Restore the retained App and its runtime, then restart.`}),(0,B.jsx)(`button`,{disabled:h,type:`button`,onClick:()=>void g(`rollback`),children:t?`确认恢复上版`:`Restore previous version`})]}):null]})]})]})}var ib=e=>`loopx-sidebar-goal-order-v1:${encodeURIComponent(e)}`;function ab(e){try{let t=JSON.parse(e??`null`);return Array.isArray(t)&&t.every(e=>typeof e==`string`)?[...new Set(t)]:[]}catch{return[]}}function ob(e,t){let n=new Map(t.map((e,t)=>[e,t]));return[...e].sort((e,t)=>(n.get(e.goalId)??1/0)-(n.get(t.goalId)??1/0))}function sb(e,t,n,r,i){if(n===r||!t.includes(n)||!t.includes(r))return e;let a=[...new Set([...e,...t])].filter(e=>e!==n);return a.splice(a.indexOf(r)+Number(i),0,n),a}function cb(e,t){let n=ib(t),[r,i]=(0,z.useState)(()=>{try{return ab(localStorage.getItem(n))}catch{return[]}}),[a,o]=(0,z.useState)(!1),[s,c]=(0,z.useState)(null),[l,u]=(0,z.useState)(null),d=(0,z.useRef)(null),f=(0,z.useRef)(!1),p=ob(e,r),m=p.map(e=>e.goalId);function h(t,a,s){let l=sb(r,m,t,a,s);if(l===r)return;i(l);let u=ob(e,l),d=u.findIndex(e=>e.goalId===t),f=u[d];f&&c({title:f.title,position:d+1});try{localStorage.setItem(n,JSON.stringify(l)),o(!1)}catch{o(!0)}}function g(){d.current=null,u(null)}return{sorted:p,target:l,saveFailed:a,lastMoved:s,move:h,moveBy(e,t){let n=p[m.indexOf(e)+t];n&&h(e,n.goalId,t===1)},pointerProps:e=>({onPointerDown(t){f.current=!1,t.pointerType===`mouse`&&t.button===0&&(d.current={id:e,x:t.clientX,y:t.clientY,dragging:!1},t.currentTarget.setPointerCapture(t.pointerId))},onPointerMove(e){let t=d.current;if(!t||!t.dragging&&Math.hypot(e.clientX-t.x,e.clientY-t.y)<6)return;t.dragging=!0,f.current=!0;let n=document.elementFromPoint(e.clientX,e.clientY)?.closest(`[data-reorder-goal]`),r=e.currentTarget.closest(`.personal-goal-list`),i=n?.dataset.reorderGoal;if(!n||!i||!r?.contains(n)||i===t.id){u(null);return}let a=n.getBoundingClientRect();u({id:i,after:e.clientY>a.top+a.height/2})},onPointerUp(){d.current?.dragging&&l&&h(d.current.id,l.id,l.after),g()},onPointerCancel:g,onLostPointerCapture:g,onKeyDown(e){e.key===`Escape`&&g()},onClickCapture(e){f.current&&=(e.preventDefault(),e.stopPropagation(),!1)}})}}var lb=`/ssh-hosts`,ub=/^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;function db(e){return typeof e==`string`&&ub.test(e.trim())}function fb(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`SSH Host 列表响应无效。`);let t=e;if(t.ok!==!0||t.schema_version!==`ssh_host_catalog_v0`||!Array.isArray(t.hosts))throw Error(`SSH Host 列表协议不兼容,请更新本机 LoopX 服务。`);let n=new Set;return{hosts:t.hosts.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=String(e.alias??``).trim();return!db(t)||n.has(t)?[]:(n.add(t),[{alias:t}])}),schemaVersion:`ssh_host_catalog_v0`}}async function pb(e=fetch,t=lb){let n=await e(t,{cache:`no-store`});if(!n.ok)throw Error(`无法读取本机 SSH Host(HTTP ${n.status})。`);return fb(await n.json())}function mb(e,t){let n=e.trim();if(!db(n))return{error:`请选择有效的 SSH Host。`};let r=Number(t);return!Number.isInteger(r)||r<1024||r>65535?{error:`本地端口必须是 1024–65535 之间的整数。`}:{command:`ssh -N -L ${r}:127.0.0.1:8766 ${n}`,hostAlias:n,label:n,statusUrl:`http://127.0.0.1:${r}/status.json`}}var hb=`/api/ssh-source/ensure`,gb=`/api/ssh-source/goal-lifecycle`;async function _b(e,t){let n=await fetch(hb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({host_alias:e,local_port:Number(t)})}),r=await n.json().catch(()=>null);if(!n.ok)throw Error(r?.error??`无法建立 SSH 隧道来源。`);if(!r?.ok)throw Error(`无法建立 SSH 隧道来源。`);return r}async function vb(e,t,n,r,i=fetch){let a=await i(gb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({goal_id:t,host_alias:e,operation:n,reason:r})}),o=await a.json().catch(()=>null);if(!a.ok)throw Error(o?.error??`无法更新远端 Goal 生命周期。`);if(!o?.ok||o.schema_version!==`loopx_remote_goal_lifecycle_v1`||o.goal_id!==t||o.host_alias!==e||o.operation!==n||o.activation_state!==(n===`stop`?`stopped`:`active`)||o.projection_verified!==!0)throw Error(`远端 Goal 生命周期回读未验证。`);return o}function yb({activeSource:e,connectionState:t,errorMessage:n,onAdd:r,onConfiguredHostsLoaded:i,onRemove:a,onSelect:o,sources:s}){let{t:c}=Ji(),[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(null),[p,m]=(0,z.useState)(`configured`),[h,g]=(0,z.useState)([]),[_,v]=(0,z.useState)(null),[y,b]=(0,z.useState)(!1),[x,S]=(0,z.useState)(!1),[C,w]=(0,z.useState)(``),[T,E]=(0,z.useState)(``),[D,O]=(0,z.useState)(`8876`),[ee,te]=(0,z.useState)(``),ne=`configured:`,k=[...s.map(e=>({label:e.label,value:e.id})),...h.filter(e=>!s.some(t=>t.label===e.alias)).map(e=>({group:c(`source.configuredGroup`,{count:h.length}),label:e.alias,value:`${ne}${e.alias}`}))],A=(0,z.useMemo)(()=>h.some(e=>e.alias===C)?mb(C,D):{error:c(`source.selectHost`)},[h,C,D,c]);(0,z.useEffect)(()=>{j()},[]);async function j(){b(!0),v(null);try{let e=await pb();g(e.hosts),i?.(e.hosts.map(e=>e.alias)),w(t=>t||e.hosts[0]?.alias||``),e.hosts.length||v(c(`source.hostEmpty`))}catch(e){v(e instanceof Error?e.message:c(`source.hostLoadError`))}finally{b(!1)}}function M(){u(!0),m(`configured`),f(null),j()}function N(){u(!1),m(`configured`),v(null),S(!1),w(``),f(null),E(``),O(`8876`),te(``)}function P(){let e=r({label:T,statusUrl:ee});if(e.error){f(e.error);return}N()}function F(){if(`error`in A){f(A.error??c(`source.invalid`));return}let e=r({ensureTunnel:!0,hostAlias:A.hostAlias,label:A.label,statusUrl:A.statusUrl});if(e.error){f(e.error);return}N()}function re(e){let t=new Set;for(let e of s)try{t.add(new URL(e.statusUrl).port)}catch{}let n=`8877`;for(let e=8877;e<9077;e+=1)if(!t.has(String(e))){n=String(e);break}let i=mb(e,n);if(`error`in i){f(i.error??c(`source.invalid`));return}let a=r({ensureTunnel:!0,hostAlias:i.hostAlias,label:i.label,statusUrl:i.statusUrl});a.error?f(a.error):f(null),O(n)}async function ie(){if(`error`in A){f(A.error??c(`source.invalid`));return}try{await navigator.clipboard.writeText(A.command),S(!0),f(null)}catch{f(c(`source.copyError`))}}return(0,B.jsxs)(`section`,{"aria-label":c(`source.controlPlane`),className:`personal-status-source`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`span`,{children:`Control plane`}),(0,B.jsx)(`button`,{"aria-label":c(`source.addSsh`),onClick:M,title:c(`source.add`),type:`button`,children:(0,B.jsx)(Pm,{size:14})})]}),(0,B.jsx)(Cy,{ariaLabel:c(`source.select`),className:`personal-status-source-select`,icon:(0,B.jsx)(Hm,{size:15}),onChange:e=>{if(e.startsWith(ne)){re(e.slice(11));return}o(e)},options:k,value:e.id}),(0,B.jsxs)(`div`,{className:`personal-status-source-meta`,children:[(0,B.jsxs)(`span`,{className:`is-${t}`,children:[(0,B.jsx)(`i`,{}),c(t===`loading`?`source.connecting`:t===`error`?`source.notAvailable`:`source.connected`)]}),(0,B.jsx)(`small`,{children:e.readOnly?c(`source.readOnly`):c(`source.localInteractive`)}),e.kind===`ssh_tunnel`?(0,B.jsx)(`button`,{"aria-label":c(`source.remove`,{source:e.label}),onClick:()=>a(e.id),title:c(`source.removeCurrent`),type:`button`,children:(0,B.jsx)(Xm,{size:12})}):null]}),n?(0,B.jsx)(`p`,{className:`personal-status-source-error`,role:`alert`,children:n}):null,l?(0,B.jsxs)(`div`,{className:`personal-status-source-form`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:c(`source.addSsh`)}),(0,B.jsx)(`button`,{"aria-label":c(`source.closeForm`),onClick:N,type:`button`,children:(0,B.jsx)($m,{size:13})})]}),(0,B.jsxs)(`div`,{"aria-label":c(`source.addMethod`),className:`personal-status-source-modes`,role:`tablist`,children:[(0,B.jsx)(`button`,{"aria-selected":p===`configured`,onClick:()=>{m(`configured`),f(null)},role:`tab`,type:`button`,children:c(`source.configured`)}),(0,B.jsx)(`button`,{"aria-selected":p===`manual`,onClick:()=>{m(`manual`),f(null)},role:`tab`,type:`button`,children:c(`source.manual`)})]}),p===`configured`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.configuredCount`,{count:h.length})}),(0,B.jsxs)(`span`,{className:`personal-status-source-field-row`,children:[(0,B.jsx)(`input`,{"aria-label":c(`source.host`),disabled:y||!h.length,list:`loopx-configured-ssh-hosts`,onChange:e=>{w(e.target.value),S(!1)},placeholder:c(y?`source.loadingHosts`:`source.hostPlaceholder`),value:C}),(0,B.jsx)(`datalist`,{id:`loopx-configured-ssh-hosts`,children:h.map(e=>(0,B.jsx)(`option`,{value:e.alias},e.alias))}),(0,B.jsx)(`button`,{"aria-label":c(`source.refreshHosts`),disabled:y,onClick:()=>void j(),title:c(`source.refreshHosts`),type:`button`,children:(0,B.jsx)(Rm,{size:13})})]})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.localPort`)}),(0,B.jsx)(`input`,{"aria-label":c(`source.localPort`),inputMode:`numeric`,onChange:e=>{O(e.target.value),S(!1)},value:D})]}),(0,B.jsxs)(`div`,{className:`personal-status-source-command`,children:[(0,B.jsx)(`code`,{children:`error`in A?c(`source.tunnelCommandPending`):A.command}),(0,B.jsxs)(`button`,{"aria-label":c(`source.copyCommand`),disabled:`error`in A,onClick:()=>void ie(),type:`button`,children:[(0,B.jsx)(cm,{size:12}),c(x?`source.copied`:`source.copy`)]})]}),_?(0,B.jsx)(`p`,{className:`is-error`,children:_}):null,(0,B.jsx)(`p`,{children:c(`source.description`)}),(0,B.jsx)(`button`,{className:`personal-status-source-add`,disabled:`error`in A,onClick:F,type:`button`,children:c(`source.addConfigured`)})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.name`)}),(0,B.jsx)(`input`,{autoFocus:!0,maxLength:48,onChange:e=>E(e.target.value),placeholder:c(`source.namePlaceholder`),value:T})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:c(`source.statusUrl`)}),(0,B.jsx)(`input`,{onChange:e=>te(e.target.value),placeholder:`http://127.0.0.1:8876/status.json`,value:ee})]}),(0,B.jsx)(`p`,{children:(0,B.jsx)(`code`,{children:`ssh -N -L 8876:127.0.0.1:8766 `})}),(0,B.jsx)(`p`,{children:c(`source.manualDescription`)}),(0,B.jsx)(`button`,{className:`personal-status-source-add`,onClick:P,type:`button`,children:c(`source.addConfigured`)})]}),d?(0,B.jsx)(`p`,{className:`is-error`,role:`alert`,children:d}):null]}):null]})}var bb={需修复:`is-danger`,等你:`is-warning`,等待条件:`is-info`,推进中:`is-success`,安静运行:`is-quiet`,已完成:`is-quiet`,已停止:`is-stopped`};function xb({attentionCount:e,goals:t,goalArchiveLoadState:n={error:null,phase:`ready`},lifecycleBusyGoalIds:r,goalLifecycleOperations:i,onRequestGoalCreate:a,onOpenSettings:o,onRetryGoalArchive:s,onRequestGoalLifecycle:c,onSelectGoal:l,selectedGoalId:u,statusSourceControl:d}){let{locale:f,t:p}=Ji(),[m,h]=(0,z.useState)(!1),g=cb(t.filter(e=>e.activationState!==`stopped`),d?.activeSource.statusUrl??`/status.json`),_=g.sorted,v=t.filter(e=>e.activationState===`stopped`),y=e=>!!c&&(!i||i.includes(e)),b=(e,t)=>(0,B.jsxs)(`div`,{className:`personal-goal-row${g.target?.id===e.goalId?g.target.after?` is-drop-after`:` is-drop-before`:``}`,"data-reorder-goal":t?void 0:e.goalId,"data-load-error":e.loadError,children:[(0,B.jsxs)(`button`,{...t?{}:g.pointerProps(e.goalId),title:t?void 0:p(`sidebar.dragGoal`),"aria-current":u===e.goalId?`page`:void 0,className:`personal-goal-link`,onClick:()=>l(e.goalId),type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-goal-state-dot ${e.loadState?``:bb[e.state]}`}),(0,B.jsxs)(`span`,{className:`personal-goal-link-copy`,children:[(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsxs)(`small`,{children:[e.loadState&&(!t||u===e.goalId)?p(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Yi(e.state,f),e.needsYou&&!t?` · ${p(`home.lane.needsYou`)}`:``]})]}),(0,B.jsx)(nm,{size:15})]}),!t&&m?(0,B.jsxs)(`div`,{className:`personal-goal-move-actions`,children:[(0,B.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveUp`,{goal:e.title}),disabled:_[0]?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,-1),children:(0,B.jsx)(Jp,{"aria-hidden":`true`,size:13})}),(0,B.jsx)(`button`,{type:`button`,"aria-label":p(`sidebar.moveDown`,{goal:e.title}),disabled:_.at(-1)?.goalId===e.goalId,onClick:()=>g.moveBy(e.goalId,1),children:(0,B.jsx)(Wp,{"aria-hidden":`true`,size:13})})]}):null,c&&y(t?`resume`:`stop`)?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`button`,{"aria-label":`${p(t?`sidebar.resume`:`sidebar.stop`)} ${e.title}`,"aria-busy":r?.has(e.goalId)||void 0,className:`personal-goal-lifecycle${r?.has(e.goalId)?` is-pending`:``}`,disabled:r?.has(e.goalId),onClick:()=>c(e,t?`resume`:`stop`),title:p(t?`sidebar.resumeGoal`:`sidebar.stopGoal`),type:`button`,children:r?.has(e.goalId)?(0,B.jsx)(Cm,{size:13}):t?(0,B.jsx)(Lm,{size:13}):(0,B.jsx)(Mm,{size:13})}),t&&y(`delete`)?(0,B.jsx)(`button`,{"aria-label":`${p(`sidebar.delete`)} ${e.title}`,className:`personal-goal-lifecycle personal-goal-delete`,onClick:()=>c(e,`delete`),title:p(`sidebar.deleteGoal`),type:`button`,children:(0,B.jsx)(Xm,{size:13})}):null]}):null]},e.goalId);return(0,B.jsxs)(`div`,{className:`personal-goal-directory`,children:[(0,B.jsxs)(`div`,{className:`personal-sidebar-brand`,children:[(0,B.jsx)(`span`,{className:`personal-brand-mark`,children:(0,B.jsx)(Zp,{size:18})}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:`LoopX`})})]}),d?(0,B.jsx)(yb,{...d}):null,(0,B.jsxs)(`nav`,{"aria-label":p(`home.workspace`),className:`personal-sidebar-nav`,children:[(0,B.jsxs)(`button`,{"aria-current":u===null?`page`:void 0,className:`personal-manager-link`,onClick:()=>l(null),type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-manager-icon`,children:(0,B.jsx)(Zp,{size:17})}),(0,B.jsx)(`span`,{children:p(`sidebar.manager`)}),e>0?(0,B.jsx)(`span`,{className:`personal-sidebar-count`,children:e}):null,(0,B.jsx)(nm,{size:15})]}),(0,B.jsxs)(`div`,{className:`personal-sidebar-section-title`,children:[(0,B.jsx)(`span`,{children:`Goals`}),(0,B.jsxs)(`span`,{className:`personal-sidebar-title-actions`,children:[(0,B.jsx)(`small`,{children:_.length}),(0,B.jsx)(`button`,{"aria-label":p(`sidebar.sortGoals`),title:p(`sidebar.sortGoals`),"aria-pressed":m,onClick:()=>h(!m),type:`button`,children:(0,B.jsx)(qp,{"aria-hidden":`true`,size:15})}),a?(0,B.jsx)(`button`,{"aria-label":p(`sidebar.createGoal`),onClick:a,type:`button`,children:(0,B.jsx)(Pm,{size:15})}):null]})]}),g.saveFailed?(0,B.jsx)(`p`,{role:`status`,children:p(`sidebar.orderNotSaved`)}):null,(0,B.jsx)(`span`,{className:`personal-sr-only`,role:`status`,children:g.lastMoved?p(`sidebar.goalMoved`,{goal:g.lastMoved.title,position:g.lastMoved.position}):``}),(0,B.jsx)(`div`,{className:`personal-goal-list`,children:_.map(e=>b(e,!1))}),v.length||n.phase===`loading`||n.phase===`error`?(0,B.jsxs)(`details`,{className:`personal-stopped-goals`,open:n.phase===`error`||void 0,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(tm,{size:13}),(0,B.jsx)(`span`,{children:p(`sidebar.stopped`)}),n.phase===`loading`?(0,B.jsx)(Cm,{"aria-label":p(`sidebar.stoppedLoading`),className:`is-spinning`,size:13}):(0,B.jsx)(`small`,{children:v.length})]}),(0,B.jsxs)(`div`,{className:`personal-goal-list is-stopped`,children:[n.phase===`error`?(0,B.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`alert`,children:[(0,B.jsx)(`span`,{children:p(`sidebar.stoppedLoadFailed`)}),s?(0,B.jsx)(`button`,{onClick:s,type:`button`,children:p(`sidebar.retryStopped`)}):null]}):null,v.map(e=>b(e,!0))]})]}):null]}),(0,B.jsxs)(`div`,{className:`personal-sidebar-footer`,children:[(0,B.jsx)(rb,{}),o?(0,B.jsxs)(`button`,{"aria-label":p(`settings.open`),className:`personal-sidebar-utility`,onClick:o,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-sidebar-utility-icon`,children:(0,B.jsx)(Um,{size:17})}),(0,B.jsx)(`span`,{className:`personal-sidebar-utility-copy`,children:(0,B.jsx)(`strong`,{children:p(`settings.open`)})}),(0,B.jsx)(nm,{"aria-hidden":`true`,size:15})]}):null]})]})}var Sb=J({ok:X(!0),total:G().int().nonnegative(),next_cursor:W().nullable(),items:q(J({todo_id:W(),text:W(),claimed_by:W().nullable(),evidence:W().nullable(),priority:W().nullable(),task_class:W().nullable()})).max(40)});function Cb({goal:e,agentId:t,seed:n,enabled:r,listView:i=!1,onSelect:a}){let{t:o}=Ji(),s=(0,z.useId)(),[c,l]=(0,z.useState)(!1),u=!i||c,d=i?96:148,[f,p]=(0,z.useState)(n),[m,h]=(0,z.useState)(t===`all`?e.doneTodoCount??n.length:n.length),[g,_]=(0,z.useState)(void 0),[v,y]=(0,z.useState)(!1),[b,x]=(0,z.useState)(!1),[S,C]=(0,z.useState)(!1),[w,T]=(0,z.useState)({top:0,height:600}),[E,D]=(0,z.useState)(null),O=(0,z.useRef)(null),ee=(0,z.useRef)(null),[te,ne]=(0,z.useState)(0);(0,z.useEffect)(()=>{let e=O.current;if(!e)return;let t=new ResizeObserver(()=>T({top:e.scrollTop,height:e.clientHeight}));return t.observe(e),()=>{t.disconnect(),ee.current?.abort()}},[]);let k=g===void 0||w.top+w.height>=f.length*d-d*2;(0,z.useEffect)(()=>{if(!r||!u||!k||g===null||b||ee.current)return;let n=new AbortController;ee.current=n,y(!0);let i=new URLSearchParams({goal_id:e.goalId});t!==`all`&&i.set(`agent_id`,t),g&&i.set(`cursor`,g),fetch(`/api/chat/completed-todos?${i}`,{signal:n.signal}).then(async e=>{if(e.status===409&&C(!0),!e.ok)throw Error(`history unavailable`);let t=Sb.parse(await e.json());if(n.signal.aborted)return;let r=t.items.map(e=>({todoId:e.todo_id,text:e.text,claimedBy:e.claimed_by,evidence:e.evidence,priority:e.priority,taskClass:e.task_class,done:!0,status:`done`}));p(e=>g===void 0?r:[...e,...r.filter(t=>!e.some(e=>e.todoId===t.todoId))]),h(t.total),_(t.next_cursor)}).catch(()=>{n.signal.aborted||x(!0)}).finally(()=>{n.signal.aborted||(ee.current=null,y(!1))})},[r,u,k,g,b,te,e.goalId,t,v]),(0,z.useEffect)(()=>{O.current&&(O.current.scrollTop=0),T({top:0,height:O.current?.clientHeight??600}),D(null)},[i]);let A=Math.max(0,Math.floor(w.top/d)-3),j=Math.min(f.length,Math.ceil((w.top+w.height)/d)+3),M=Array.from({length:Math.max(0,j-A)},(e,t)=>A+t);return E!==null&&El(e=>!e),children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,children:c?`▾`:`▸`}),` `,o(`tasks.completed`)]}):(0,B.jsxs)(`strong`,{children:[(0,B.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-done`}),o(`tasks.completed`)]}),(0,B.jsx)(`span`,{children:m})]}),(0,B.jsxs)(`div`,{id:s,hidden:!u,"aria-label":o(`tasks.completed`),className:`personal-task-lane-scroll`,ref:O,role:`region`,tabIndex:0,onScroll:e=>T({top:e.currentTarget.scrollTop,height:e.currentTarget.clientHeight}),children:[(0,B.jsx)(`div`,{className:`personal-completed-window`,style:{height:f.length*d},children:M.map(t=>{let n=f[t];return(0,B.jsx)(`div`,{className:`personal-task-card personal-completed-row`,style:{top:t*d,height:d},children:(0,B.jsxs)(`button`,{type:`button`,onFocus:()=>D(t),onBlur:()=>D(null),onClick:()=>a({kind:`todo`,item:{...n,goalId:e.goalId,goalTitle:e.title,ownerLabel:n.claimedBy??e.agentLabel??e.agentId}}),children:[(0,B.jsx)(`span`,{className:`is-done`,children:`✓`}),(0,B.jsx)(`strong`,{children:n.text}),(0,B.jsx)(`small`,{children:n.claimedBy??e.agentLabel??e.agentId})]})},n.todoId)})}),(0,B.jsx)(`div`,{className:`personal-completed-footer`,role:`status`,children:v?o(`tasks.historyLoading`):b?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`span`,{children:o(S?`tasks.historyExpired`:`tasks.historyError`)}),(0,B.jsx)(`button`,{type:`button`,onClick:()=>{S&&(_(void 0),O.current&&(O.current.scrollTop=0)),C(!1),x(!1),ne(e=>e+1)},children:o(`tasks.historyRetry`)})]}):r?g===null?o(`tasks.historyEnd`):(0,B.jsx)(`button`,{type:`button`,onClick:()=>{O.current&&(O.current.scrollTop=f.length*d)},children:o(`tasks.historyMore`)}):o(`tasks.historyLocalOnly`)})]})]})}function wb({children:e,count:t,label:n,tone:r,listView:i=!1}){let a=(0,z.useId)(),o=(0,z.useRef)(null),s=(0,z.useRef)([]),c=(0,z.useRef)(null),[l,u]=(0,z.useState)({after:!1,before:!1}),d=(0,z.useCallback)(()=>{let e=o.current;if(!e)return;let t={after:Math.max(0,e.scrollHeight-e.clientHeight)-e.scrollTop>1,before:e.scrollTop>1};u(e=>e.after===t.after&&e.before===t.before?e:t)},[]);return(0,z.useEffect)(()=>{let e=o.current;if(!e)return;let t=new ResizeObserver(d);return c.current=t,t.observe(e),e.addEventListener(`scroll`,d,{passive:!0}),d(),()=>{t.disconnect(),c.current=null,s.current=[],e.removeEventListener(`scroll`,d)}},[i,d]),(0,z.useEffect)(()=>{let e=o.current,t=c.current;if(!e||!t)return;for(let e of s.current)t.unobserve(e);let n=Array.from(e.children).filter(e=>e instanceof HTMLElement);for(let e of n)t.observe(e);s.current=n,d()},[e,t,i,d]),i?!t&&r!==`done`?null:(0,B.jsxs)(`details`,{className:`personal-task-group tone-${r}`,open:!0,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(tm,{size:16}),(0,B.jsx)(`strong`,{children:n}),(0,B.jsx)(`span`,{children:t})]}),(0,B.jsx)(`div`,{className:`personal-task-list-rows`,children:e})]}):(0,B.jsxs)(`section`,{className:`personal-object-list personal-task-lane`,children:[(0,B.jsxs)(`header`,{id:a,children:[(0,B.jsxs)(`strong`,{children:[(0,B.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-${r}`}),n]}),(0,B.jsx)(`span`,{children:t})]}),(0,B.jsx)(`div`,{"aria-labelledby":a,className:`personal-task-lane-scroll${l.before?` has-overflow-before`:``}${l.after?` has-overflow-after`:``}`,ref:o,role:`region`,tabIndex:t>0?0:-1,children:e})]})}function Tb({historyEnabled:e=!1,goal:t,items:n,onDraftTaskFromMessage:r,onOpenChat:i,onQuickComplete:a,quickCompletingTodoIds:o,onSelect:s,selectedTodoId:c=null,userTodos:l}){let{t:u}=Ji(),[d,f]=(0,z.useState)(!1),[p,m]=(0,z.useState)({goalId:``,laneId:`all`}),h=(0,z.useRef)(null);(0,z.useEffect)(()=>{if(!c)return;let e=window.requestAnimationFrame(()=>h.current?.scrollIntoView({block:`nearest`,inline:`nearest`}));return()=>window.cancelAnimationFrame(e)},[c]);let g=l.filter(e=>e.goalId===t.goalId).map(e=>({...e,goalTitle:t.title})),_=e=>e.priority===`P0`?0:e.priority===`P1`?1:e.priority===`P2`?2:3,v=(0,z.useMemo)(()=>{let e=new Map((t.agentLanes??[]).map(e=>[e.agentId,e]));for(let n of t.agentTodos)n.claimedBy&&!e.has(n.claimedBy)&&e.set(n.claimedBy,{agentId:n.claimedBy,label:n.claimedBy});return[...e.values()]},[t.agentLanes,t.agentTodos]),y=p.goalId===t.goalId&&v.some(e=>e.agentId===p.laneId)?p.laneId:`all`,b=e=>y===`all`||e===y,x=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&!e.done).filter(e=>b(e.claimedBy)).sort((e,t)=>_(e)-_(t)),S=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&e.done).filter(e=>b(e.claimedBy)),C=n.filter(e=>e.kind===`schedule`&&b(e.schedule.agentId)),w=n.filter(e=>e.kind===`run`&&!!e.run.todoId&&b(e.run.agentId)),T=!g.length&&!x.length&&!S.length&&!C.length,E=n.filter(e=>e.kind===`message`&&(e.message.role===`user`||e.message.role===`assistant`)),D=E.reduce((e,t,n)=>t.message.role===`user`?n:e,-1),O=D>=0?E[D]?.message:null,ee=D>=0?E.slice(D+1).reverse().find(e=>e.message.role===`assistant`)?.message:null,te=D>=0&&E.slice(D+1).some(e=>e.message.role===`assistant`&&e.message.pending);return(0,B.jsxs)(`section`,{"aria-label":u(`header.tasks`),className:`personal-task-board${d?` is-list-view`:``}`,children:[(0,B.jsxs)(`header`,{className:`personal-task-view-toolbar`,children:[(0,B.jsx)(`div`,{children:(0,B.jsx)(`strong`,{children:u(`header.tasks`)})}),(0,B.jsxs)(`div`,{className:`personal-task-view-switch`,role:`group`,"aria-label":u(`tasks.viewLabel`),children:[(0,B.jsx)(`button`,{type:`button`,"aria-pressed":d,onClick:()=>f(!0),children:u(`tasks.listView`)}),(0,B.jsx)(`button`,{type:`button`,"aria-pressed":!d,onClick:()=>f(!1),children:u(`tasks.boardView`)})]})]}),v.length>1?(0,B.jsxs)(`section`,{"aria-label":u(`tasks.agentLaneFilter`),className:`personal-task-lane-filter`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(Zp,{size:15}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:u(`tasks.agentLane`)})})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{className:`sr-only`,children:u(`tasks.agentLaneFilter`)}),(0,B.jsxs)(`select`,{"aria-label":u(`tasks.agentLaneFilter`),onChange:e=>m({goalId:t.goalId,laneId:e.target.value}),value:y,children:[(0,B.jsx)(`option`,{value:`all`,children:u(`tasks.allAgentLanes`,{count:v.length})}),v.map(e=>(0,B.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))]}),(0,B.jsx)(tm,{"aria-hidden":!0,size:14})]})]}):null,O?(0,B.jsxs)(`section`,{"aria-label":u(`tasks.chatRecent`),className:`personal-task-chat-receipt`,children:[(0,B.jsx)(`span`,{className:`personal-task-chat-icon`,children:(0,B.jsx)(Dm,{size:18})}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:u(te?`tasks.chatPending`:ee?`tasks.chatAgentReplied`:`tasks.chatRecent`)}),(0,B.jsx)(`small`,{children:t.agentLabel??t.agentId})]}),(0,B.jsxs)(`p`,{className:`is-user`,children:[(0,B.jsx)(`b`,{children:u(`common.you`)}),O.text]}),ee&&!ee.pending?(0,B.jsxs)(`p`,{className:`is-assistant`,children:[(0,B.jsx)(`b`,{children:u(`common.agent`)}),ee.text]}):null,(0,B.jsx)(`small`,{children:u(te?`tasks.chatPendingDescription`:`tasks.chatUnchangedDescription`)})]}),(0,B.jsxs)(`footer`,{children:[(0,B.jsxs)(`button`,{onClick:i,type:`button`,children:[(0,B.jsx)(Dm,{size:14}),u(`tasks.chatViewReply`)]}),ee&&!te&&r?(0,B.jsxs)(`button`,{onClick:()=>r(ee.text),type:`button`,children:[(0,B.jsx)(Sm,{size:14}),u(`tasks.convertToTask`)]}):null]})]}):null,(0,B.jsxs)(`div`,{className:d?`personal-task-grouped-list`:`personal-task-kanban`,children:[(0,B.jsxs)(wb,{listView:d,count:g.length,label:u(`timeline.waitingConfirmation`),tone:`attention`,children:[g.map(e=>{let t=Zi(e.updatedAt,u);return(0,B.jsxs)(`button`,{onClick:()=>s({item:e,kind:`attention`}),type:`button`,children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,className:`is-attention`,children:`!`}),(0,B.jsx)(`strong`,{children:e.text}),(0,B.jsxs)(`small`,{children:[(0,B.jsx)(`span`,{className:`personal-row-status ${e.blocking?`is-blocking`:`is-pending`}`,children:e.blocking?u(`tasks.blocked`):u(`tasks.pending`)}),t?(0,B.jsx)(`span`,{className:`personal-task-age`,children:u(`tasks.waitingAge`,{age:t})}):null]})]},e.todoId)}),g.length?null:(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyConfirm`)})]}),(0,B.jsxs)(wb,{listView:d,count:x.length,label:u(`tasks.pendingAndRunning`),tone:`progress`,children:[x.map(e=>{let n={...e,goalId:t.goalId,goalTitle:t.title,ownerLabel:e.claimedBy??t.agentLabel??t.agentId},r=w.find(t=>t.run.todoId===e.todoId)?.run;return(0,B.jsxs)(`div`,{className:`personal-task-card${r?` has-session`:``}${c===e.todoId?` is-selected`:``}`,ref:c===e.todoId?e=>{h.current=e}:void 0,children:[(0,B.jsxs)(`button`,{"aria-pressed":c===e.todoId,onClick:()=>s({item:n,kind:`todo`}),type:`button`,children:[(0,B.jsx)(`span`,{children:`○`}),(0,B.jsx)(`strong`,{children:e.text}),(0,B.jsxs)(`small`,{children:[e.priority?(0,B.jsx)(`span`,{className:`personal-priority-badge is-${e.priority.toLowerCase()}`,children:e.priority}):null,e.status===`blocked`?(0,B.jsx)(`span`,{className:`personal-priority-badge is-blocked`,children:u(`tasks.blocked`)}):null,r?(0,B.jsx)(`span`,{className:`personal-task-session-status`,children:r.status===`running`||r.status===`queued`?u(`runs.running`):r.status===`failed`?u(`tasks.sessionError`):u(`common.waiting`)}):null,e.status===`deferred`?(0,B.jsx)(`span`,{className:`personal-task-session-status`,children:u(`drawer.taskStatusDeferred`)}):r?null:(0,B.jsx)(`span`,{className:`personal-task-session-status`,children:u(`tasks.waiting`)}),e.claimedBy??t.agentLabel??t.agentId]})]}),(0,B.jsxs)(`div`,{className:`personal-task-card-actions`,children:[r?(0,B.jsxs)(`button`,{className:`personal-task-session-link`,"aria-label":u(`tasks.openExecution`,{name:e.text}),onClick:()=>s({item:r,kind:`run`}),title:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`),type:`button`,children:[(0,B.jsx)(fm,{size:14}),(0,B.jsx)(`span`,{children:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`)})]}):null,a?(0,B.jsx)(`button`,{"aria-busy":o?.has(e.todoId)||void 0,"aria-label":u(`tasks.markComplete`,{name:e.text}),disabled:o?.has(e.todoId),onClick:()=>void a(n),title:u(`tasks.completed`),type:`button`,children:o?.has(e.todoId)?(0,B.jsx)(Cm,{className:`personal-spin`,size:14}):(0,B.jsx)(em,{size:14})}):null,(0,B.jsx)(`button`,{"aria-label":u(`tasks.moreActions`,{name:e.text}),onClick:()=>s({item:n,kind:`todo`}),title:u(`common.actions`),type:`button`,children:(0,B.jsx)(dm,{size:14})})]})]},e.todoId)}),x.length?null:(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyRunning`)})]}),(0,B.jsxs)(wb,{listView:d,count:C.length,label:u(`tasks.scheduled`),tone:`schedule`,children:[C.map(e=>(0,B.jsxs)(`button`,{onClick:()=>s({item:e.schedule,kind:`schedule`}),type:`button`,children:[(0,B.jsx)(`span`,{children:`◷`}),(0,B.jsx)(`strong`,{children:e.schedule.label}),(0,B.jsx)(`small`,{children:e.schedule.status===`paused`?u(`schedule.paused`):u(`schedule.active`)})]},e.id)),C.length?null:(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptySchedules`)})]}),(0,B.jsx)(Cb,{goal:t,agentId:y,seed:S,enabled:e,listView:d,onSelect:s},`${t.goalId}:${y}:${e}`)]}),T?(0,B.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyGoal`)}):null]})}function Eb(e,t){return{live_steering:{label:t(`lark.ingressSteering`),detail:t(`lark.ingressSteeringDescription`)},session_queue:{label:t(`lark.ingressQueue`),detail:t(`lark.ingressQueueDescription`)},async_inbox:{label:t(`lark.ingressAsync`),detail:t(`lark.ingressAsyncDescription`)},direct_session:{label:t(`lark.ingressLegacy`),detail:t(`lark.ingressLegacyDescription`)}}[e]}function Db(e,t){return e.listener_status===`starting`?{label:t(`lark.health.starting`),detail:t(`lark.health.startingDetail`),state:`not_ready`}:e.listener_status===`retrying`&&e.listener_error_code===`lark_event_source_disconnected`?{label:t(`lark.health.sourceDisconnected`),detail:t(`lark.health.sourceDisconnectedDetail`),state:`not_ready`}:e.listener_status===`retrying`?{label:t(`lark.health.retrying`),detail:t(`lark.health.retryingDetail`),state:`not_ready`}:e.listener_status===`stopped`||e.listener_status===null?{label:t(`lark.health.notStarted`),detail:t(`lark.health.notStartedDetail`),state:`not_ready`}:e.last_event_status===`message_context_permission_required`?{label:t(`lark.health.messageContextPermission`),detail:t(`lark.health.messageContextPermissionDetail`),state:`not_ready`}:e.last_event_status===`processing_failed`?{label:t(`lark.health.processingFailed`),detail:t(`lark.health.processingFailedDetail`),state:`not_ready`}:e.health_error_code===`invalid_routing_state`?{label:t(`lark.health.invalidRouting`),detail:t(`lark.health.invalidRoutingDetail`),state:`not_ready`}:e.last_event_status===`queued_for_agent`?{label:t(`lark.health.queued`),detail:t(`lark.health.queuedDetail`,{agent:e.agent_id??t(`lark.targetAgent`)}),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`not_addressed`?{label:t(`lark.health.notAddressed`),detail:t(`lark.health.notAddressedDetail`),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`self_message`?{label:t(`lark.health.listening`),detail:t(`lark.health.ignoredSelf`),state:`ready`}:e.health_error_code===`lark_event_route_mismatch`||[`chat_mismatch`,`topic_mismatch`,`route_ambiguous`].includes(e.last_event_reason??``)?{label:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguous`):t(`lark.health.routeMismatch`),detail:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguousDetail`):t(`lark.health.routeMismatchDetail`),state:`not_ready`}:[`invalid_event`,`binding_unavailable`].includes(e.last_event_reason??``)?{label:t(`lark.health.routeUnavailable`),detail:t(`lark.health.routeUnavailableDetail`),state:`not_ready`}:e.last_event_status===`replied_and_acknowledged`?{label:t(`lark.health.listening`),detail:t(`lark.health.eventProcessed`,{events:e.event_count,replies:e.replied_count}),state:`ready`}:e.health_error_code===`lark_event_delivery_unverified`||e.event_count===0?{label:t(`lark.health.eventUnverified`),detail:t(`lark.health.eventUnverifiedDetail`),state:`unverified`}:{label:e.reply_ready?t(`lark.health.listening`):t(`lark.health.unavailable`),detail:t(`lark.health.lastStatus`,{status:e.last_event_status??t(`lark.health.waiting`)}),state:e.reply_ready?`ready`:`not_ready`}}function Ob(e){return e.history_permission_guidance?.api_document_url??null}function kb(e,t,n){if(e instanceof Th){let t=String(e.payload.error_code??``);return{lark_cli_not_installed:n(`lark.error.cliMissing`),lark_cli_not_executable:n(`lark.error.cliExecutable`),lark_cli_start_failed:n(`lark.error.cliStart`),lark_message_permissions_required:n(`lark.error.messagePermissions`),lark_app_required:n(`lark.error.appRequired`),invalid_lark_app:n(`lark.error.invalidApp`),lark_group_lookup_failed:n(`lark.error.groupLookup`),provider_api_failed:n(`lark.error.provider`)}[t]??e.message}return e instanceof Error?e.message:t}function Ab({embedded:e=!1,focusGoalConnection:t=!1,goals:n,initialGoalId:r,onChanged:i,onClose:a}){let{t:o}=Ji(),[s,c]=(0,z.useState)(`connections`),[l,u]=(0,z.useState)([]),[d,f]=(0,z.useState)([]),[p,m]=(0,z.useState)(!0),[h,g]=(0,z.useState)(null),[_,v]=(0,z.useState)(``),[y,b]=(0,z.useState)(t),[x,S]=(0,z.useState)(``),[C,w]=(0,z.useState)(r??n[0]?.goalId??``),[T,E]=(0,z.useState)(``),[D,O]=(0,z.useState)([]),[ee,te]=(0,z.useState)(``),[ne,k]=(0,z.useState)(!1),[A,j]=(0,z.useState)(null),[M,N]=(0,z.useState)(`addressed_only`),[P,F]=(0,z.useState)(t&&r?`goal`:`manager`),[re,ie]=(0,z.useState)(`async_inbox`),[I,ae]=(0,z.useState)(`topic_reply`),[L,oe]=(0,z.useState)(``),[se,ce]=(0,z.useState)(!1),[le,ue]=(0,z.useState)({}),[de,fe]=(0,z.useState)(!1),[pe,me]=(0,z.useState)(null),[he,ge]=(0,z.useState)(null),[_e,ve]=(0,z.useState)(null),[ye,be]=(0,z.useState)(null),[xe,Se]=(0,z.useState)(!1),[Ce,we]=(0,z.useState)(`loopx-workspace-bot`),[Te,Ee]=(0,z.useState)(`feishu`),[R,De]=(0,z.useState)(null),[Oe,ke]=(0,z.useState)(!1),[Ae,je]=(0,z.useState)(null),Me=(0,z.useRef)(null),Ne=(0,z.useRef)(null),Pe=(0,z.useRef)(!1);async function Fe(){m(!0),g(null);try{let[e,t]=await Promise.all([Rg(),qg()]);u(e),f(t),S(t=>t||e.find(e=>e.reply_ready)?.app_ref||e.find(e=>e.ready)?.app_ref||e[0]?.app_ref||``)}catch(e){g(kb(e,o(`lark.error.configuration`),o))}finally{m(!1)}}(0,z.useEffect)(()=>{Fe()},[]),(0,z.useEffect)(()=>{if(!t||p||Pe.current||!r)return;Pe.current=!0;let e=d.find(e=>e.goal_id===r);e?Je(e):qe(n.find(e=>e.goalId===r))},[d,t,n,r,p]),(0,z.useEffect)(()=>{if(!y||!x||_e){O([]),te(``),k(!1),j(null);return}let e=!1;k(!0),j(null);let t=window.setTimeout(()=>{Gg(x,T).then(t=>{e||(O(t),te(e=>t.some(t=>t.chat_id===e)?e:t[0]?.chat_id??``))}).catch(t=>{e||(O([]),te(``),j(kb(t,o(`lark.error.groupLoad`),o)))}).finally(()=>{e||k(!1)})},180);return()=>{e=!0,window.clearTimeout(t)}},[x,T,y,_e]),(0,z.useEffect)(()=>{if(!xe||!R||[`ready`,`failed`,`cancelled`].includes(R.status))return;let e=!1,t=window.setTimeout(()=>{Vg(R.setup_id).then(async t=>{e||(De(t),t.verification_url&&Ne.current!==t.verification_url&&(Ne.current=t.verification_url,Me.current&&!Me.current.closed&&(Me.current.location.href=t.verification_url)),t.status===`ready`&&(await Fe(),S(t.app_ref),ue({}),Se(!1)),t.status===`failed`&&je(t.error??o(`lark.error.appCreate`)))}).catch(t=>{e||je(kb(t,o(`lark.error.setupPoll`),o))})},650);return()=>{e=!0,window.clearTimeout(t)}},[xe,R]);let V=n.find(e=>e.goalId===C),Ie=V?.agentId?[{agentId:V.agentId,label:V.agentLabel??V.agentId}]:[],Le=V?.agentLanes?.length?V.agentLanes:Ie,Re=Le.some(e=>e.agentId===L),ze=[];se?ze=Le.map(e=>({agentId:e.agentId,appRef:le[e.agentId]??x})):Re&&(ze=[{agentId:L,appRef:x}]);let Be=ze.map(e=>e.agentId),Ve=!!_e||ze.length>0&&ze.every(e=>l.some(t=>t.app_ref===e.appRef&&t.reply_ready)),He=o(`lark.connect`);he?He=o(`lark.saveConnection`):se&&(He=o(`lark.connectAllAgentsAction`,{count:Be.length}));let Ue=l.find(e=>e.app_ref===x),We=D.find(e=>e.chat_id===ee),Ge=(0,z.useMemo)(()=>{let e=_.trim().toLocaleLowerCase();return e?d.filter(t=>[t.app_label,t.chat_name,t.goal_title,t.topic_name].some(t=>t.toLocaleLowerCase().includes(e))):d},[d,_]),Ke=(0,z.useMemo)(()=>d.filter(e=>Db(e,o).state===`unverified`).length,[d,o]);function qe(e){let i=e??n.find(e=>e.goalId===r)??n[0];ge(null),ve(null),F(e||t?`goal`:`manager`),S(l.some(e=>e.app_ref===x)?x:l.find(e=>e.reply_ready)?.app_ref??l[0]?.app_ref??``),te(``),w(i?.goalId??``),oe(i?.agentId??``),ce(!1),ue({}),N(`addressed_only`),ie(`async_inbox`),ae(`topic_reply`),E(``),me(null),b(!0)}function Je(e){ge(e.goal_id),ve(e),F(e.conversation_kind??`goal`),S(e.app_ref),w(e.goal_id);let t=n.find(t=>t.goalId===e.goal_id),r=t?.agentLanes?.length?t.agentLanes:t?.agentId?[{agentId:t.agentId}]:[];oe(e.agent_id??(r.length===1?r[0].agentId:``)),ce(!1),ue({}),N(e.capture_scope),ie(e.ingress_mode===`direct_session`?`async_inbox`:e.ingress_mode),ae(e.reply_mode),E(e.chat_name),me(null),b(!0)}function Ye(){De(null),je(null),Ne.current=null,Se(!0)}async function Xe(){if(!(Oe||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Ce))){ke(!0),je(null),Ne.current=null,Me.current=window.open(window.location.href,`_blank`);try{let e=await Bg({appRef:Ce,brand:Te});De(e)}catch(e){Me.current?.close(),je(kb(e,o(`lark.error.setupStart`),o))}finally{ke(!1)}}}async function Ze(){let e=R;if(Se(!1),Me.current?.close(),e&&![`ready`,`failed`,`cancelled`].includes(e.status))try{await Hg(e.setup_id)}catch{}}async function Qe(){if(!(!x||!C||!_e&&!We||P===`goal`&&Be.length===0||de)){fe(!0),me(null);try{let e={...P===`manager`?{..._e?{connectionId:_e.connection_id}:{appRef:x,chatId:We.chat_id,chatName:We.chat_name}}:_e?{connectionId:_e.connection_id,agentId:L}:{agentBindings:ze,chatId:We.chat_id,chatName:We.chat_name},conversationKind:P,captureScope:P===`manager`?`addressed_only`:M,goalId:C,incomingMode:M===`configured_chat_all`?`all`:`mentions`,ingressMode:P===`manager`?`session_queue`:re,replyMode:I},t=await Jg({...e,execute:!1});if(!t.ok)throw new Th(t.public_summary??t.blocker??o(`lark.error.bindPreview`),{error_code:t.blocker??`provider_api_failed`});let n=await Jg({...e,execute:!0});if(!n.ok)throw new Th(n.public_summary??n.blocker??o(`lark.error.bind`),{error_code:n.blocker??`provider_api_failed`});b(!1),await Fe(),i?.()}catch(e){me(kb(e,o(`lark.error.bind`),o))}finally{fe(!1)}}}async function $e(e,t){if(ye!==t){be(t);return}try{await Yg(e,t),be(null),await Fe(),i?.()}catch(e){g(kb(e,o(`lark.error.disconnect`),o))}}return(0,B.jsxs)(`section`,{className:`personal-lark-settings${e?` is-embedded`:``}`,"aria-label":o(`lark.configuration`),children:[e?null:(0,B.jsxs)(`header`,{className:`personal-lark-header`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:o(`settings.goalConnections`)}),(0,B.jsx)(`h1`,{children:`Lark`})]}),(0,B.jsx)(`button`,{"aria-label":o(`lark.closeSettings`),className:`personal-icon-button`,onClick:a,type:`button`,children:(0,B.jsx)($m,{size:18})})]}),(0,B.jsxs)(`nav`,{className:`personal-lark-tabs`,"aria-label":o(`lark.management`),children:[(0,B.jsxs)(`button`,{"aria-current":s===`apps`?`page`:void 0,onClick:()=>c(`apps`),type:`button`,children:[o(`lark.apps`),` `,(0,B.jsx)(`span`,{children:p?`…`:l.length})]}),(0,B.jsxs)(`button`,{"aria-current":s===`connections`?`page`:void 0,onClick:()=>c(`connections`),type:`button`,children:[o(`lark.connections`),` `,(0,B.jsx)(`span`,{children:p?`…`:d.length})]})]}),h?(0,B.jsx)(`p`,{className:`personal-notification-error`,children:h}):null,p?(0,B.jsxs)(`div`,{className:`personal-lark-loading`,children:[(0,B.jsx)(Cm,{className:`is-spinning`,size:18}),o(`lark.loading`)]}):null,!p&&s===`apps`?(0,B.jsxs)(`div`,{className:`personal-lark-apps`,children:[(0,B.jsxs)(`div`,{className:`personal-lark-app-toolbar`,children:[(0,B.jsx)(`span`,{children:o(`lark.reusableApps`,{count:l.length})}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,onClick:Ye,type:`button`,children:[(0,B.jsx)(Pm,{size:16}),o(`lark.newApp`)]})]}),(0,B.jsxs)(`div`,{className:`personal-lark-app-grid`,children:[l.map(e=>(0,B.jsxs)(`article`,{className:`personal-lark-app-card`,children:[(0,B.jsx)(`span`,{className:`personal-lark-app-avatar`,children:(0,B.jsx)(Zp,{size:19})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsxs)(`small`,{children:[e.brand,` · lark-cli profile`]})]}),(0,B.jsx)(`em`,{className:e.reply_ready?`is-ready`:`is-off`,children:e.reply_ready?o(`lark.autoReplyReady`):e.ready?o(`lark.needsMessagePermissions`):o(`lark.needsSetup`)}),(0,B.jsxs)(`p`,{children:[o(`lark.goalConnections`,{count:d.filter(t=>t.app_ref===e.app_ref).length}),e.ready&&!e.reply_ready?` · ${o(`lark.autoReplyUnavailable`)}`:``]})]},e.app_ref)),l.length===0?(0,B.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noProfiles`)}):null]})]}):null,!p&&s===`connections`?(0,B.jsxs)(`div`,{className:`personal-lark-connections`,children:[Ke>0?(0,B.jsxs)(`p`,{className:`personal-lark-route-readiness`,role:`status`,children:[(0,B.jsx)(Dm,{size:15}),o(`lark.routesUnverified`,{count:Ke})]}):null,(0,B.jsxs)(`div`,{className:`personal-lark-toolbar`,children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(zm,{size:16}),(0,B.jsx)(`input`,{"aria-label":o(`lark.searchConnections`),onChange:e=>v(e.target.value),placeholder:o(`lark.searchPlaceholder`),type:`search`,value:_})]}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:l.length===0||n.length===0,onClick:()=>qe(),type:`button`,children:[(0,B.jsx)(Pm,{size:16}),o(`lark.connectApp`)]})]}),(0,B.jsxs)(`div`,{className:`personal-lark-table`,role:`table`,"aria-label":o(`lark.goalTopicConnections`),children:[(0,B.jsxs)(`div`,{className:`personal-lark-table-head`,role:`row`,children:[(0,B.jsx)(`span`,{children:o(`lark.connection`)}),(0,B.jsx)(`span`,{children:o(`common.goal`)}),(0,B.jsx)(`span`,{children:o(`lark.capture`)}),(0,B.jsx)(`span`,{children:o(`lark.processing`)}),(0,B.jsx)(`span`,{children:o(`common.actions`)})]}),Ge.map(e=>{let t=Db(e,o);return(0,B.jsxs)(`div`,{className:`personal-lark-table-row`,role:`row`,children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.chat_name}),(0,B.jsxs)(`small`,{children:[e.app_label,` · `,t.label]}),(0,B.jsx)(`small`,{children:t.detail}),t.state===`unverified`?(0,B.jsxs)(`a`,{href:`https://open.feishu.cn/document/server-docs/im-v1/message/events/receive?lang=zh-CN`,rel:`noreferrer`,target:`_blank`,children:[(0,B.jsx)(fm,{size:12}),o(`lark.openEventSettings`)]}):null,Ob(e)?(0,B.jsxs)(`a`,{href:Ob(e)??void 0,rel:`noreferrer`,target:`_blank`,children:[(0,B.jsx)(fm,{size:12}),o(`lark.historyPermission`)]}):null]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.goal_title}),(0,B.jsxs)(`small`,{children:[`# `,e.topic_name]})]}),(0,B.jsx)(`span`,{children:e.capture_scope===`addressed_only`?o(`lark.mentionsOnly`):o(`lark.allTopicMessages`)}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.conversation_kind===`manager`?o(`lark.managerConversation`):Eb(e.ingress_mode,o).label}),(0,B.jsx)(`small`,{children:e.conversation_kind===`manager`?o(`lark.managerConversationDescription`):e.agent_id??Eb(e.ingress_mode,o).detail})]}),(0,B.jsxs)(`span`,{className:`personal-lark-row-actions`,children:[(0,B.jsx)(`button`,{"aria-label":o(`lark.settingsConfigure`,{goal:e.goal_title}),onClick:()=>Je(e),type:`button`,children:(0,B.jsx)(Um,{size:15})}),(0,B.jsxs)(`button`,{"aria-label":o(`lark.settingsDisconnect`,{goal:e.goal_title}),className:ye===e.connection_id?`is-confirm`:``,onClick:()=>void $e(e.goal_id,e.connection_id),type:`button`,children:[(0,B.jsx)(Qm,{size:15}),ye===e.connection_id?o(`common.confirm`):null]})]})]},e.connection_id)}),Ge.length===0?(0,B.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noConnections`)}):null]})]}):null,y?(0,B.jsx)(`div`,{className:`personal-lark-modal-backdrop`,role:`presentation`,children:(0,B.jsxs)(`section`,{"aria-labelledby":`connect-lark-title`,"aria-modal":`true`,className:`personal-lark-modal`,role:`dialog`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:`Goal Topic connection`}),(0,B.jsx)(`h2`,{id:`connect-lark-title`,children:o(he?`lark.editConnection`:`lark.connectApp`)})]}),(0,B.jsx)(`button`,{"aria-label":o(`lark.closeConnection`),onClick:()=>b(!1),type:`button`,children:(0,B.jsx)($m,{size:18})})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.conversationKind`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.conversationKind`),disabled:!!_e,value:P,onChange:e=>F(e.target.value),children:[(0,B.jsx)(`option`,{value:`manager`,children:o(`lark.managerConversation`)}),(0,B.jsx)(`option`,{value:`goal`,children:o(`lark.workerConversation`)})]})]}),P===`manager`?(0,B.jsx)(`p`,{children:o(`lark.managerConversationDescription`)}):null,_e?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,B.jsx)(`div`,{children:_e.app_label})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,B.jsx)(`div`,{children:_e.chat_name})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,B.jsx)(`div`,{children:_e.goal_title})]}),(0,B.jsx)(`small`,{children:o(`lark.editPreservesIdentity`)})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,B.jsx)(`select`,{"aria-label":o(`lark.appProfile`),disabled:p,onChange:e=>{e.target.value===`__register__`?Ye():(S(e.target.value),ue({}))},value:x,children:p?(0,B.jsx)(`option`,{value:``,children:o(`lark.appLoading`)}):(0,B.jsxs)(B.Fragment,{children:[l.map(e=>(0,B.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref)),(0,B.jsx)(`option`,{value:`__register__`,children:o(`lark.registerAnother`)})]})}),(0,B.jsx)(`small`,{children:o(`lark.defaultAgentAppDescription`)})]}),Ue?.ready&&!Ue.reply_ready?(0,B.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.appPermissions`)}):null,(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,B.jsx)(`input`,{"aria-label":o(`lark.groupSearch`),onChange:e=>E(e.target.value),placeholder:o(`lark.groupSearch`),type:`search`,value:T}),ne?(0,B.jsxs)(`div`,{className:`personal-lark-group-state`,role:`status`,children:[(0,B.jsx)(Cm,{className:`is-spinning`,size:15}),o(`lark.groupLoading`)]}):null,!ne&&A?(0,B.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:A}):null,!ne&&!A&&D.length===0?(0,B.jsx)(`div`,{className:`personal-lark-group-state`,role:`status`,children:o(`lark.groupEmpty`)}):null,!ne&&!A&&D.length>0?(0,B.jsx)(`select`,{"aria-label":o(`lark.groupChat`),onChange:e=>te(e.target.value),value:ee,children:D.map(e=>(0,B.jsx)(`option`,{value:e.chat_id,children:e.chat_name},e.chat_id))}):null]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,B.jsx)(`select`,{"aria-label":o(`lark.bindGoal`),onChange:e=>{let t=e.target.value;w(t),oe(n.find(e=>e.goalId===t)?.agentId??``),ue({})},value:C,children:n.map(e=>(0,B.jsx)(`option`,{value:e.goalId,children:e.title},e.goalId))})]})]}),(0,B.jsxs)(`label`,{className:`personal-lark-check`,children:[(0,B.jsx)(`input`,{checked:!0,readOnly:!0,type:`checkbox`}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:o(`lark.createAutomatically`)}),(0,B.jsx)(`small`,{children:o(`lark.createAutomaticallyDescription`)})]})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.topicPreview`)}),(0,B.jsxs)(`div`,{className:`personal-lark-topic-preview`,children:[(0,B.jsx)(Dm,{size:15}),`# `,V?.title??V?.goalId??`Goal`]})]}),P===`goal`?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.captureScope`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.captureScope`),disabled:_e?.ingress_mode===`direct_session`,onChange:e=>N(e.target.value),value:M,children:[(0,B.jsx)(`option`,{value:`addressed_only`,children:o(`lark.captureAddressed`)}),(0,B.jsx)(`option`,{value:`configured_chat_all`,children:o(`lark.captureAll`)})]}),(0,B.jsx)(`small`,{children:o(`lark.captureScopeDescription`)})]}),(0,B.jsxs)(`fieldset`,{"aria-label":o(`lark.agentIngress`),className:`personal-lark-ingress`,children:[(0,B.jsx)(`legend`,{children:o(`lark.agentIngress`)}),(0,B.jsx)(`div`,{children:[`live_steering`,`session_queue`,`async_inbox`].map(e=>{let t=Eb(e,o);return(0,B.jsxs)(`label`,{className:re===e?`is-active`:``,children:[(0,B.jsx)(`input`,{"aria-label":t.label,checked:re===e,name:`lark-agent-ingress`,onChange:()=>ie(e),type:`radio`,value:e}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:t.label}),(0,B.jsx)(`small`,{children:t.detail})]})]},e)})})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.targetAgent`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.targetAgent`),disabled:!!_e?.agent_id,onChange:e=>oe(e.target.value),value:L,children:[Re?null:(0,B.jsx)(`option`,{disabled:!0,value:L,children:L?o(`lark.agentUnavailable`,{agent:L}):o(`lark.noAgentConfigured`)}),Le.map(e=>(0,B.jsx)(`option`,{value:e.agentId,children:e.label===e.agentId?e.agentId:`${e.label} · ${e.agentId}`},e.agentId))]}),(0,B.jsx)(`small`,{children:o(`lark.targetAgentDescription`)})]}),!he&&Le.length>1?(0,B.jsxs)(`label`,{"aria-label":o(`lark.connectAllAgents`),className:`personal-lark-check`,children:[(0,B.jsx)(`input`,{checked:se,onChange:e=>ce(e.target.checked),type:`checkbox`}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:o(`lark.connectAllAgents`)}),(0,B.jsx)(`small`,{children:o(`lark.connectAllAgentsDescription`,{count:Le.length})})]})]}):null,!he&&se&&Le.length>1?(0,B.jsxs)(`fieldset`,{"aria-label":o(`lark.agentApps`),className:`personal-lark-agent-apps`,children:[(0,B.jsx)(`legend`,{children:o(`lark.agentApps`)}),(0,B.jsx)(`small`,{children:o(`lark.agentAppsDescription`)}),(0,B.jsx)(`div`,{children:Le.map(e=>(0,B.jsxs)(`label`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:e.label}),(0,B.jsx)(`small`,{children:e.agentId})]}),(0,B.jsx)(`select`,{"aria-label":o(`lark.agentAppSelection`,{agent:e.label}),onChange:t=>ue(n=>({...n,[e.agentId]:t.target.value})),value:le[e.agentId]??x,children:l.map(e=>(0,B.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref))})]},e.agentId))})]}):null,se&&ze.length>0&&!Ve?(0,B.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.agentAppPermissions`)}):null,Be.length===0?(0,B.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:o(`lark.selectRegisteredAgent`)}):null]}):null,(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.replyMode`)}),(0,B.jsx)(`select`,{"aria-label":o(`lark.replyMode`),onChange:e=>ae(e.target.value),value:I,children:(0,B.jsx)(`option`,{value:`topic_reply`,children:o(`lark.topicReply`)})}),(0,B.jsx)(`small`,{children:o(`lark.replyModeDescription`)})]}),(0,B.jsxs)(`p`,{className:`personal-lark-cardinality`,children:[(0,B.jsx)(em,{size:15}),o(`lark.cardinality`)]}),pe?(0,B.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:pe}):null,(0,B.jsxs)(`footer`,{children:[(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>b(!1),type:`button`,children:o(`lark.cancel`)}),(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:p||!x||!_e&&(!Ue?.reply_ready||!ee)||P===`goal`&&(!Ve||Be.length===0)||!C||de,onClick:()=>void Qe(),type:`button`,children:[de?(0,B.jsx)(Cm,{className:`is-spinning`,size:15}):null,He]})]})]})}):null,xe?(0,B.jsx)(`div`,{className:`personal-lark-modal-backdrop is-setup`,role:`presentation`,children:(0,B.jsxs)(`section`,{"aria-labelledby":`new-lark-app-title`,"aria-modal":`true`,className:`personal-lark-modal personal-lark-setup-modal`,role:`dialog`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`small`,{children:o(`lark.reusableWorkspaceApp`)}),(0,B.jsx)(`h2`,{id:`new-lark-app-title`,children:o(`lark.newApp`)})]}),(0,B.jsx)(`button`,{"aria-label":o(`lark.closeCreate`),onClick:()=>void Ze(),type:`button`,children:(0,B.jsx)($m,{size:18})})]}),R?(0,B.jsxs)(`div`,{className:`personal-lark-setup-progress`,children:[(0,B.jsx)(`span`,{className:`personal-lark-setup-icon is-${R.status}`,children:R.status===`ready`?(0,B.jsx)(em,{size:22}):(0,B.jsx)(Cm,{className:R.status===`failed`?``:`is-spinning`,size:22})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:R.status===`ready`?o(`lark.appCreated`):R.status===`failed`?o(`lark.appCreateFailed`):o(`lark.waitingFeishu`)}),(0,B.jsx)(`p`,{children:R.status===`waiting_for_feishu`?o(`lark.waitingFeishuDescription`):R.status===`starting`?o(`lark.waitingLink`):R.error})]}),R.verification_url?(0,B.jsxs)(`a`,{href:R.verification_url,rel:`noreferrer`,target:`_blank`,children:[(0,B.jsx)(fm,{size:15}),o(`lark.reopenFeishu`)]}):null]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`personal-lark-setup-copy`,children:o(`lark.setupCopy`)}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.profileName`)}),(0,B.jsx)(`input`,{"aria-label":o(`lark.profileName`),autoComplete:`off`,onChange:e=>we(e.target.value),placeholder:`loopx-workspace-bot`,value:Ce})]}),(0,B.jsxs)(`label`,{children:[(0,B.jsx)(`span`,{children:o(`lark.region`)}),(0,B.jsxs)(`select`,{"aria-label":o(`lark.region`),onChange:e=>Ee(e.target.value),value:Te,children:[(0,B.jsx)(`option`,{value:`feishu`,children:`Feishu`}),(0,B.jsx)(`option`,{value:`lark`,children:`Lark`})]})]}),Ce&&!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Ce)?(0,B.jsx)(`p`,{className:`personal-notification-error`,children:o(`lark.profileValidation`)}):null]}),Ae?(0,B.jsx)(`p`,{className:`personal-notification-error`,children:Ae}):null,(0,B.jsxs)(`footer`,{children:[(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void Ze(),type:`button`,children:o(`lark.cancel`)}),R?null:(0,B.jsxs)(`button`,{className:`personal-primary-action`,disabled:Oe||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(Ce),onClick:()=>void Xe(),type:`button`,children:[Oe?(0,B.jsx)(Cm,{className:`is-spinning`,size:15}):(0,B.jsx)(fm,{size:15}),o(`lark.continueFeishu`)]})]})]})}):null]})}function jb(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function Mb(e,t,n){let r=jb(t),i=jb(n);return Object.fromEntries(e.fields.flatMap(({key:e,nullable:t})=>{let n=r[e],a=i[e];return Object.hasOwn(r,e)&&(n!=null||t&&n===null)?[[e,n]]:Object.hasOwn(i,e)&&a!=null?[[e,a]]:[]}))}function Nb(e,t){let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=new Set(e.fields.map(e=>e.key));return Object.keys(n).some(e=>!r.has(e))?null:n}function Pb(e,t,n){let r={...e,[t]:n},i=e.schedule;return t===`timezone`&&i&&typeof i==`object`&&`schema_version`in i&&i.schema_version===`periodic_report_schedule_v0`&&(r.schedule={...i,timezone:n}),r}function Fb({id:e,value:t,timezone:n,onChange:r}){let{locale:i}=Ji(),a=i===`zh-CN`,o=t&&typeof t==`object`&&!Array.isArray(t)?t:null,s=String(o?.rrule??``).split(`;`).map(e=>e.split(`=`)),c=Object.fromEntries(s.filter(e=>e.length===2)),l=[`MO`,`TU`,`WE`,`TH`,`FR`,`SA`,`SU`],u=(e,t)=>e!==void 0&&/^\d+$/.test(e)&&Number(e)<=t,d=!o||o.schema_version===`periodic_report_schedule_v0`&&[`DAILY`,`WEEKLY`].includes(c.FREQ)&&o.timezone===n&&s.every(e=>e.length===2&&[`FREQ`,`BYDAY`,`BYHOUR`,`BYMINUTE`,`INTERVAL`].includes(e[0]))&&new Set(s.map(([e])=>e)).size===s.length&&u(c.BYHOUR,23)&&u(c.BYMINUTE??`0`,59)&&(c.FREQ===`WEEKLY`?l.includes(c.BYDAY):!c.BYDAY)&&(!c.INTERVAL||c.INTERVAL===`1`),f=a?[`星期一`,`星期二`,`星期三`,`星期四`,`星期五`,`星期六`,`星期日`]:[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`];function p(e){let t={FREQ:`WEEKLY`,BYDAY:`MO`,BYHOUR:`9`,BYMINUTE:`0`,...c,...e};r?.({schema_version:`periodic_report_schedule_v0`,schedule_id:o?.schedule_id??`report-schedule`,timezone:n,rrule:[`FREQ=${t.FREQ}`,...t.FREQ===`WEEKLY`?[`BYDAY=${t.BYDAY}`]:[],`BYHOUR=${t.BYHOUR}`,`BYMINUTE=${t.BYMINUTE}`].join(`;`)})}return(0,B.jsxs)(`div`,{className:`personal-report-schedule`,children:[(0,B.jsxs)(`label`,{className:`is-boolean`,htmlFor:e,children:[(0,B.jsx)(`span`,{children:a?`按日历汇报`:`Calendar reports`}),(0,B.jsx)(`input`,{id:e,type:`checkbox`,role:`switch`,checked:!!o,disabled:!r,onChange:e=>e.target.checked?p({}):r?.(null)})]}),o?(0,B.jsxs)(B.Fragment,{children:[d?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`label`,{htmlFor:`${e}-frequency`,children:[(0,B.jsx)(`span`,{children:a?`频率`:`Frequency`}),(0,B.jsxs)(`select`,{id:`${e}-frequency`,value:c.FREQ,disabled:!r,onChange:e=>p({FREQ:e.target.value}),children:[(0,B.jsx)(`option`,{value:`DAILY`,children:a?`每天`:`Daily`}),(0,B.jsx)(`option`,{value:`WEEKLY`,children:a?`每周`:`Weekly`})]})]}),c.FREQ===`WEEKLY`&&(0,B.jsxs)(`label`,{htmlFor:`${e}-day`,children:[(0,B.jsx)(`span`,{children:a?`星期`:`Weekday`}),(0,B.jsx)(`select`,{id:`${e}-day`,value:c.BYDAY,disabled:!r,onChange:e=>p({BYDAY:e.target.value}),children:l.map((e,t)=>(0,B.jsx)(`option`,{value:e,children:f[t]},e))})]}),(0,B.jsxs)(`label`,{htmlFor:`${e}-time`,children:[(0,B.jsxs)(`span`,{children:[a?`当地时间`:`Local time`,` (`,n,`)`]}),(0,B.jsx)(`input`,{id:`${e}-time`,type:`time`,required:!0,disabled:!r,value:`${(c.BYHOUR??`9`).padStart(2,`0`)}:${(c.BYMINUTE??`0`).padStart(2,`0`)}`,onChange:e=>{if(!/^\d{2}:\d{2}$/.test(e.target.value))return;let[t,n]=e.target.value.split(`:`);p({BYHOUR:t,BYMINUTE:n})}})]})]}):(0,B.jsx)(`p`,{role:`alert`,children:a?`此计划需在 JSON 模式中编辑;当前内容已保留。`:`Edit this schedule in JSON mode; its current value is preserved.`}),(0,B.jsx)(`p`,{children:a?`由现有唤醒检查到期计划;实际送达以回执为准。`:`Existing wakes check the schedule; delivery is confirmed by its receipt.`})]}):(0,B.jsx)(`p`,{children:a?`未设置日历计划;保持阶段结束时汇报。`:`No calendar schedule; report at validated stage boundaries.`})]})}function Ib({copy:e,field:t,id:n,onChange:r,value:i,timezone:a}){let o=e[t.key]?.label??t.label,s=!r;if(t.input_kind===`periodic_report_schedule`)return(0,B.jsx)(Fb,{id:n,value:i,timezone:a,onChange:r?e=>r(t.key,e):void 0});if(t.input_kind===`boolean`)return(0,B.jsxs)(`label`,{className:`is-boolean`,htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsx)(`input`,{checked:i===!0,id:n,onChange:r?e=>r(t.key,e.target.checked):void 0,readOnly:s,role:`switch`,type:`checkbox`})]});if(t.input_kind===`select`)return(0,B.jsxs)(`label`,{htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsxs)(`select`,{id:n,onChange:r?e=>r(t.key,e.target.value):void 0,value:typeof i==`string`?i:``,children:[(0,B.jsx)(`option`,{value:``}),(t.options??[]).map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))]})]});if(t.input_kind===`string_list`)return(0,B.jsxs)(`label`,{htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsx)(`textarea`,{id:n,onChange:r?e=>r(t.key,e.target.value.split(/\r?\n/u).filter(Boolean)):void 0,readOnly:s,rows:4,value:Array.isArray(i)?i.join(` +`):``})]});let c=t.input_kind===`number`;return(0,B.jsxs)(`label`,{htmlFor:n,children:[(0,B.jsx)(`span`,{children:o}),(0,B.jsx)(`input`,{id:n,max:t.maximum,min:t.minimum,onChange:r?e=>r(t.key,c?Number(e.target.value):e.target.value):void 0,readOnly:s,required:t.required,type:c?`number`:`text`,value:typeof i==`number`||typeof i==`string`?i:``})]})}function Lb({copy:e={},disabled:t=!1,editor:n,enabledAction:r,omitKeys:i=[],onChange:a,value:o}){let s=(0,z.useId)(),c=new Set(i);return(0,B.jsx)(`fieldset`,{className:`personal-capability-fields`,disabled:t,children:n.fields.filter(e=>!c.has(e.key)).map(t=>{let n=(0,B.jsx)(Ib,{copy:e,field:t,id:`${s}-${t.key.replace(/[^a-z0-9_-]/gi,`-`)}`,onChange:a,value:o[t.key],timezone:String(o.timezone??`UTC`)},t.key);return t.key===`enabled`&&t.input_kind===`boolean`?(0,B.jsxs)(`div`,{className:`personal-capability-enabled-row`,children:[n,r]},t.key):n})})}var Rb={en:{todo_replan_cadence:{displayName:`Goal review cadence`,description:`Configures the Goal review cadence.`},change_quality_qualification:{displayName:`Change quality qualification`,description:`Prepares a provider-neutral review packet, allows at most one policy-authorized safe-fix pass, and can require an exact-diff receipt.`},explore_graph:{displayName:`Explore Graph`,description:`Organizes bounded exploration as a typed evidence graph so branches, findings, and synthesis remain inspectable.`},explore_harness:{displayName:`Explore Harness`,description:`Selects a capability-owned planning and research harness profile for bounded multi-step exploration.`},lark_event_inbox:{displayName:`Lark event inbox`,description:`Receives provider events through a local-private inbox binding before LoopX projects them into governed work.`,readOnlyReason:`This capability requires a local-private inbox binding. Manage it in Lark settings or through the capability CLI.`},lark_kanban_heartbeat_sync:{displayName:`Lark Kanban heartbeat sync`,description:`Synchronizes accepted LoopX work state to the configured Lark Kanban heartbeat surface.`},local_authority_shadow:{displayName:`Local authority shadow`,description:`Observes post-commit Todo and task-lease state through the shared authority contract without taking write authority.`},multi_subagent:{displayName:`Adaptive child capacity`,description:`Sets bounded child-agent capacity and the public-safe responsibility domains in which parallel work may be delegated.`},peer_task_coordination:{displayName:`Registered-peer task coordination`,description:`Routes explicitly scoped peer-owned work to one registered coordinator without granting cross-owner mutation authority.`},periodic_report:{displayName:`Periodic reports`,description:`Turns validated Goal stage progress into a frozen report and automatically delivers it through the configured Goal Channel with exact readback.`},pull_request_review:{displayName:`Pull-request review`,description:`Ranks the public GitHub PR review queue with a machine-level default; it never grants GitHub, Todo, push, or merge authority.`},reward_memory:{displayName:`Reward Memory experiment`,description:`Configures a reviewed local-private provider binding for Goal-scoped Agent recall and evidence-backed outcome learning.`}},"zh-CN":{todo_replan_cadence:{displayName:`Goal 复核周期`,description:`配置 Goal 的复核周期。`},change_quality_qualification:{displayName:`变更质量验证`,description:`生成与 Provider 无关的审阅包,最多允许一次策略授权的安全修复,并可要求精确 diff 回执。`},explore_graph:{displayName:`探索图谱`,description:`把有界探索组织为 typed 证据图,让探索分支、发现与综合结论都可检查、可追溯。`},explore_harness:{displayName:`探索 Harness`,description:`为有界的多步探索选择由能力负责的规划与研究 Harness profile。`},lark_event_inbox:{displayName:`飞书事件收件箱`,description:`通过本机私有收件箱接收 Provider 事件,再由 LoopX 将其投影为受治理的工作。`,readOnlyReason:`此能力依赖本机私有的收件箱绑定,请在飞书设置或 capability CLI 中管理。`},lark_kanban_heartbeat_sync:{displayName:`飞书看板心跳同步`,description:`把 LoopX 已接受的工作状态同步到配置好的飞书看板心跳界面。`},local_authority_shadow:{displayName:`本地 Authority 影子观测`,description:`通过共享 Authority contract 观测提交后的 Todo 与 task lease 状态,但不取得写入权。`},multi_subagent:{displayName:`自适应子 Agent 容量`,description:`限定子 Agent 容量与可公开的职责域,只有落在这些边界内的工作才能并行委派。`},peer_task_coordination:{displayName:`已注册 Peer 任务协调`,description:`把明确限定的 Peer 工作路由给一个已注册协调者,不授予跨 Owner 修改权限。`},periodic_report:{displayName:`周期报告`,description:`把经过验证的 Goal 阶段进展整理为冻结报告,并通过配置的 Goal Channel 自动发送和精确回读。`},pull_request_review:{displayName:`Pull-request Review`,description:`配置公开 GitHub PR 审阅队列的本机默认排序;不会授予 GitHub、Todo、push 或 merge 权限。`},reward_memory:{displayName:`Reward Memory 实验`,description:`为 Goal 内 Agent 的召回与证据化结果学习配置经过审阅的本机私有 Provider 绑定。`}}},zb={en:{completed_todos:{label:`Completed Todos between Goal reviews`,description:`Machine default or explicit Goal override, from 1 to 5.`},allowed_domains:{label:`Allowed responsibility domains`,description:`Enter one bounded, public-safe domain per line.`},coordinator_agent_id:{label:`Coordinator Agent`,description:`Use an already registered Agent id; leave blank to disable coordination.`},enabled:{label:`Enabled`},model:{label:`Child model`,description:`For example gpt-5.6-luna. Blank clears the child model preference.`},reasoning_effort:{label:`Child reasoning effort`,description:`For example max; the host must support this model and effort.`},max_children:{label:`Maximum children`,description:`Hard upper bound for concurrently delegated child work.`},profile:{label:`Planner profile`,description:`Select one registered Explore Harness profile.`},profile_preset:{label:`Report profile`,description:`Capability-owned report profile, such as weekly-progress.`},review_priority:{label:`Review priority`,description:`Choose whether other developers' PRs or the authenticated reviewer's own PRs are ranked first.`},route_ref:{label:`Goal Channel route`,description:`Public route alias only; credentials and provider identifiers stay outside this form.`},safe_fix:{label:`Allow one bounded safe-fix pass`},strict_receipt:{label:`Require an exact-diff receipt`},timezone:{label:`Timezone`,description:`Use an IANA timezone, for example Asia/Shanghai.`},schedule:{label:`Calendar reports`,description:`Optional daily or weekly reports; no schedule preserves stage-only delivery.`},config_path:{label:`Local-private configuration path`,description:`Repo-relative ignored JSON under .loopx/config/. Leave blank to retain the current binding; the path is never returned.`},enabled_agents:{label:`Enabled Goal Agents`,description:`Enter one registered Goal-local Agent id per line. A private binding currently accepts exactly one Agent.`}},"zh-CN":{completed_todos:{label:`两次 Goal 复核间的已完成 Todo 数`,description:`可设置 1–5;机器默认值可被 Goal 显式覆盖。`},allowed_domains:{label:`允许的职责域`,description:`每行填写一个有边界、可公开的职责域。`},coordinator_agent_id:{label:`协调 Agent`,description:`填写一个已经注册的 Agent ID;留空表示关闭协调。`},enabled:{label:`启用`},model:{label:`子 Agent 模型`,description:`例如 gpt-5.6-luna;留空清除模型偏好。`},reasoning_effort:{label:`子 Agent 推理档位`,description:`例如 max;宿主须支持所选模型与档位。`},max_children:{label:`最大子 Agent 数`,description:`可同时委派的子任务硬上限。`},profile:{label:`规划 Profile`,description:`选择一个已注册的 Explore Harness profile。`},profile_preset:{label:`报告 Profile`,description:`由该能力管理的报告 profile,例如 weekly-progress。`},review_priority:{label:`审阅优先级`,description:`选择先排其他开发者的 PR,还是先排当前已认证审阅者自己的 PR。`},route_ref:{label:`Goal Channel 路由`,description:`只填写公开 route alias;凭据与 Provider 标识不会进入此表单。`},safe_fix:{label:`允许一次有界安全修复`},strict_receipt:{label:`要求精确 diff 回执`},timezone:{label:`时区`,description:`使用 IANA 时区,例如 Asia/Shanghai。`},schedule:{label:`日历汇报`,description:`可选每日或每周计划;未设置时保持阶段结束汇报。`},config_path:{label:`本机私有配置路径`,description:`填写 .loopx/config/ 下、相对仓库且被忽略的 JSON;留空保留当前绑定,路径不会被回传。`},enabled_agents:{label:`已启用的 Goal Agent`,description:`每行填写一个已注册的 Goal 内 Agent ID;私有绑定当前只接受一个 Agent。`}}};function Bb(e,t){let n=Rb[t][e.capability_id];return n?{...e,display_name:n.displayName,description:n.description,configuration_editor:{...e.configuration_editor,...n.readOnlyReason?{read_only_reason:n.readOnlyReason}:{}}}:e}function Vb(e){return zb[e]}Object.freeze(Object.keys(Rb.en).sort());function Hb(e,t){return e.available_scopes.includes(t)&&(t!==`machine`||!!e.machine_namespace)&&e.configuration_editor.editable&&e.configuration_editor.writable_scopes.includes(t)}function Ub({values:e,t}){return(0,B.jsxs)(`details`,{className:`personal-capability-raw-values`,children:[(0,B.jsx)(`summary`,{children:t(`capabilities.rawJson`)}),(0,B.jsx)(`div`,{className:`personal-capability-value-grid`,children:e.map(({label:e,value:t})=>(0,B.jsxs)(`section`,{children:[(0,B.jsx)(`strong`,{children:e}),(0,B.jsx)(`pre`,{children:t?JSON.stringify(t,null,2):`—`})]},e))})]})}function Wb({source:e,t}){return e?(0,B.jsxs)(`p`,{className:`personal-capability-effective-source`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:15}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:t(`capabilities.effectiveSource`)}),t(`capabilities.source.${e}`)]})]}):null}function Gb({available:e,description:t,t:n}){return e?null:(0,B.jsxs)(`section`,{className:`personal-capability-editor-status is-read-only`,children:[(0,B.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:n(`capabilities.readOnly`)}),(0,B.jsx)(`p`,{children:t})]})]})}function Kb(e){return e.availability?.includes(`experimental`)?4:e.capability_id===`multi_subagent`?3:e.configuration_editor.writable_scopes.length===0||e.availability===`supported_explicit_opt_in`?2:e.availability===`supported_explicit_override`?0:1}function qb(e,t){return[...e].sort((e,n)=>{let r=Kb(e)-Kb(n);if(r!==0)return r;let i=Bb(e,t),a=Bb(n,t);return i.display_name.localeCompare(a.display_name,t)||e.capability_id.localeCompare(n.capability_id)})}function Jb({capabilities:e,locale:t,onSelect:n,scope:r,selectedCapabilityId:i,t:a}){return(0,B.jsx)(`nav`,{"aria-label":a(r===`goal`?`capabilities.catalog`:`machine.capabilityCatalog`),className:`personal-capability-list`,tabIndex:0,children:qb(e,t).map(e=>{let o=Bb(e,t);return(0,B.jsxs)(`button`,{"aria-current":i===o.capability_id?`page`:void 0,onClick:()=>n(o.capability_id),type:`button`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:o.display_name})}),(0,B.jsx)(`em`,{children:a(o.available_scopes.includes(r)?r===`goal`?`capabilities.goalScope`:`capabilities.machineScope`:r===`machine`?`capabilities.goalScope`:`capabilities.machineScope`)})]},o.capability_id)})})}function Yb({capability:e,locale:t,source:n}){let{t:r}=Ji(),i=Bb(e,t);return(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`span`,{className:`personal-settings-icon`,children:(0,B.jsx)(Gm,{"aria-hidden":!0,size:18})}),(0,B.jsxs)(`div`,{children:[(0,B.jsxs)(`div`,{className:`personal-capability-heading-row`,children:[(0,B.jsx)(`h2`,{children:i.display_name}),(0,B.jsx)(Wb,{source:n,t:r})]}),e.context_contribution&&(0,B.jsxs)(`details`,{className:`personal-capability-help`,"data-testid":`capability-context-phases`,children:[(0,B.jsx)(`summary`,{children:t===`zh-CN`?`主 Agent 协作指导`:`Coordinator workflow guidance`}),(0,B.jsx)(`p`,{children:t===`zh-CN`?`随能力开启。支持以下阶段;此处展示能力范围,不能证明某次运行已读取或采纳。`:`Enabled with this capability. These are supported phases, not proof that a run read or adopted the guidance.`}),(0,B.jsx)(`dl`,{children:e.context_contribution.supported_phases.map(e=>(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:(0,B.jsx)(`code`,{children:e})}),(0,B.jsx)(`dd`,{children:Xb[e][t===`zh-CN`?`zh`:`en`]})]},e))}),(0,B.jsx)(`p`,{children:t===`zh-CN`?`LoopX Turn 在请求与结果中提供上下文;原生工具入口由 LoopX skill 调用同一只读接口。执行与采纳需另看运行证据。`:`LoopX Turn includes context in requests and results. For native tools, the LoopX skill reads the same interface. Execution and adoption require run evidence.`})]}),(0,B.jsxs)(`details`,{className:`personal-capability-help`,children:[(0,B.jsx)(`summary`,{children:t===`zh-CN`?`配置说明`:`Configuration help`}),(0,B.jsx)(`p`,{children:i.description}),(0,B.jsx)(`dl`,{children:e.configuration_editor.fields.map(e=>{let n=Vb(t)[e.key],r=n?.description??e.description;return r?(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:n?.label??e.label}),(0,B.jsx)(`dd`,{children:r})]},e.key):null})})]},e.capability_id)]})]})}var Xb={before_plan:{zh:`规划前:识别独立问题并保留主 Agent 的核验与整合职责。`,en:`Before planning: identify independent questions and retain coordinator validation and integration.`},before_delegate:{zh:`委派前:明确子任务边界、模型偏好及预期证据。`,en:`Before delegation: specify task boundaries, model preferences and expected evidence.`},after_delegate_result:{zh:`回收后:核验结果,说明采纳决定并关联计划与成果。`,en:`After results: validate evidence, explain acceptance and link plans and deliverables.`}};function Zb({goalId:e,onApplied:t,selected:n,t:r}){let[i,a]=(0,z.useState)({busy:null,draft:{},partialWrite:null,preview:null}),[o,s]=(0,z.useState)(null),[c,l]=(0,z.useState)(`guided`),[u,d]=(0,z.useState)(``),f=(0,z.useMemo)(()=>n?Nb(n.configuration_editor,u):null,[n,u]),p=c===`guided`||f!==null;(0,z.useEffect)(()=>{l(`guided`),d(``),a({busy:null,draft:Mb(n?.configuration_editor??{fields:[]},n?.current??n?.effective_configuration?.configuration??n?.default,n?.default),partialWrite:null,preview:null}),s(null)},[n]);async function m(t){if(!(!n||i.busy||!p)){a(e=>({...e,busy:`preview`,partialWrite:null})),s(null);try{let r=await Dg(e,n.capability_id,t);a(e=>({...e,preview:r}))}catch(e){s(e instanceof Error?e.message:r(`capabilities.previewFailed`))}finally{a(e=>({...e,busy:null}))}}}async function h(){if(!(!n||!i.preview||i.busy||!p)){a(e=>({...e,busy:`apply`})),s(null);try{let r=Mb(n.configuration_editor,i.draft,n.default),o=await Og(e,n.capability_id,i.preview.action===`delete`?null:r,i.preview.plan_revision);a(e=>({...e,partialWrite:o.status===`partial_write`?o:null,preview:null})),o.status!==`partial_write`&&t()}catch(e){a(e=>({...e,preview:null})),s(e instanceof Error?e.message:r(`capabilities.applyFailed`))}finally{a(e=>({...e,busy:null}))}}}function g(e,t){a(r=>({...r,draft:n?.capability_id===`periodic_report`?Pb(r.draft,e,t):{...r.draft,[e]:t},preview:null})),s(null)}function _(e){if(!n||i.busy)return;d(e);let t=Nb(n.configuration_editor,e);a(e=>({...e,preview:null,draft:t?Mb(n.configuration_editor,t,n.default):e.draft})),s(null)}function v(){i.busy||!p||(c===`guided`&&d(JSON.stringify(i.draft,null,2)),l(c===`guided`?`json`:`guided`),a(e=>({...e,preview:null})))}return{apply:h,changeDraft:g,changeJson:_,changeMode:v,editorMode:c,jsonDraft:u,jsonValid:p,error:o,mutation:i,preview:m}}function Qb({mutationError:e,onApplied:t,partialWrite:n,preview:r}){let{t:i}=Ji();return(0,B.jsxs)(B.Fragment,{children:[e?(0,B.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:e}):null,n?(0,B.jsxs)(`section`,{"aria-live":`polite`,className:`personal-capability-recovery`,children:[(0,B.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:i(`capabilities.partialWrite`)}),(0,B.jsx)(`p`,{children:i(`capabilities.partialWriteDescription`)}),(0,B.jsx)(`small`,{children:n.recommended_action})]}),(0,B.jsxs)(`button`,{onClick:t,type:`button`,children:[(0,B.jsx)(Im,{"aria-hidden":!0,size:15}),i(`capabilities.refreshSource`)]})]}):null,r?(0,B.jsxs)(`section`,{className:`personal-capability-preview`,"aria-label":i(`capabilities.preview`),children:[(0,B.jsx)(`strong`,{children:i(`capabilities.preview`)}),(0,B.jsx)(`span`,{children:i(`machine.action.${r.action}`)}),(0,B.jsx)(`small`,{children:i(`capabilities.previewLocked`)})]}):null]})}function $b({catalog:e,goalId:t,onApplied:n}){let{locale:r,t:i}=Ji(),a=(0,z.useMemo)(()=>qb(e.capabilities,r),[e.capabilities,r]),[o,s]=(0,z.useState)(()=>a[0]?.capability_id??``),c=(0,z.useMemo)(()=>a.find(e=>e.capability_id===o)??a[0],[a,o]),l=(0,z.useMemo)(()=>c?Bb(c,r):void 0,[r,c]),{apply:u,changeDraft:d,changeJson:f,changeMode:p,editorMode:m,jsonDraft:h,jsonValid:g,error:_,mutation:v,preview:y}=Zb({goalId:t,onApplied:n,selected:l,t:i}),{busy:b,draft:x,partialWrite:S,preview:C}=v;if(!c||!l)return(0,B.jsx)(`p`,{className:`personal-capability-empty`,children:i(`capabilities.empty`)});let w=l.available_scopes.includes(`goal`),T=Hb(l,`goal`),E=l.configuration_editor.read_only_reason??i(w?`capabilities.previewOnly`:`capabilities.machineOnly`);async function D(){if(!l||!T||b||!g)return;let e=Mb(l.configuration_editor,x,l.default);await y(e)}async function O(){!T||b||await y(null)}return(0,B.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,B.jsx)(Jb,{capabilities:e.capabilities,locale:r,onSelect:s,scope:`goal`,selectedCapabilityId:l.capability_id,t:i}),(0,B.jsxs)(`article`,{"aria-label":l.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,B.jsx)(Yb,{capability:c,locale:r,source:l.effective_configuration?.source}),(0,B.jsx)(Gb,{available:T,t:i,description:E}),T?(0,B.jsxs)(B.Fragment,{children:[m===`json`||!l.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,B.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,B.jsxs)(`button`,{disabled:!!b||!g,onClick:p,type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),i(m===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,m===`guided`?(0,B.jsx)(`section`,{className:`personal-capability-field-summary`,children:(0,B.jsx)(Lb,{disabled:!!b,copy:Vb(r),editor:l.configuration_editor,onChange:d,value:x,enabledAction:(0,B.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:p,type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),i(`machine.editJson`)]})})}):(0,B.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`goal-configuration-json`,children:[(0,B.jsx)(`span`,{children:i(`capabilities.jsonConfiguration`)}),(0,B.jsx)(`textarea`,{id:`goal-configuration-json`,"aria-describedby":`goal-configuration-json-help`,disabled:!!b,onChange:e=>f(e.target.value),rows:12,spellCheck:!1,value:h}),(0,B.jsx)(`small`,{id:`goal-configuration-json-help`,children:i(`capabilities.jsonHelp`)}),g?null:(0,B.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:i(`capabilities.jsonInvalid`)})]})]}):null,(0,B.jsx)(Qb,{mutationError:_,onApplied:n,partialWrite:S,preview:C}),T?(0,B.jsxs)(`footer`,{className:`personal-capability-actions`,children:[l.current&&l.available_scopes.includes(`machine`)?(0,B.jsx)(`button`,{disabled:!!b||!g,onClick:()=>void O(),type:`button`,children:i(`capabilities.restoreInheritance`)}):null,(0,B.jsx)(`button`,{disabled:!!b||!g,onClick:()=>void D(),type:`button`,children:i(b===`preview`?`common.loading`:`capabilities.previewChanges`)}),(0,B.jsx)(`button`,{className:`is-primary`,disabled:!!b||!C||!g,onClick:()=>void u(),type:`button`,children:i(b===`apply`?`common.loading`:`capabilities.applyPreview`)})]}):null,(0,B.jsx)(Ub,{values:[{label:i(`capabilities.goalValue`),value:l.current},{label:i(l.machine_current?`capabilities.machineValue`:`capabilities.defaultValue`),value:l.machine_current??l.default}],t:i},c.capability_id)]})]})}function ex({goalId:e}){let{t}=Ji(),[n,r]=(0,z.useState)(null),[i,a]=(0,z.useState)(null),[o,s]=(0,z.useState)(!1);function c(){e&&(s(!0),a(null),Eg(e).then(r).catch(e=>a(e instanceof Error?e.message:t(`capabilities.loadFailed`))).finally(()=>s(!1)))}return(0,z.useEffect)(c,[e]),e?o&&!n?(0,B.jsxs)(`p`,{"aria-live":`polite`,className:`personal-capability-empty`,children:[(0,B.jsx)(Cm,{className:`personal-spin`,size:18}),t(`capabilities.loading`)]}):i?(0,B.jsxs)(`section`,{className:`personal-capability-error`,role:`alert`,children:[(0,B.jsx)(Zm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{children:t(`capabilities.loadFailed`)}),(0,B.jsx)(`small`,{children:i})]}),(0,B.jsxs)(`button`,{onClick:c,type:`button`,children:[(0,B.jsx)(Im,{"aria-hidden":!0,size:15}),t(`capabilities.retry`)]})]}):n?(0,B.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":n.revision,children:[(0,B.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:17}),t(`capabilities.atomicOverride`)]}),(0,B.jsx)(`p`,{children:t(`capabilities.atomicOverrideDescription`)})]}),(0,B.jsx)($b,{catalog:n.capability_catalog,goalId:e,onApplied:c})]}):null:(0,B.jsx)(`p`,{className:`personal-capability-empty`,children:t(`capabilities.chooseGoal`)})}function tx(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function nx(e,t){let n=t?.machine_namespace;return n?e?.machine_configuration?.namespaces[n]:void 0}function rx(e,t,n){return{...tx(e.default),...tx(t),...n}}function ix(e,t){for(let n of e.configuration_editor.fields){let e=t[n.key];if(n.required&&(e==null||e===``))return!1}return e.capability_id===`periodic_report`&&t.enabled===!0?!!(String(t.profile_preset??``).trim()&&String(t.route_ref??``).trim()&&String(t.timezone??``).trim()):!0}function ax(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:null}catch{return null}}function ox(e){return e?e===`absent`?e:e.replace(/^sha256:/,``).slice(0,12):`—`}function sx(){let{locale:e,t}=Ji(),[n,r]=(0,z.useState)(null),[i,a]=(0,z.useState)(``),[o,s]=(0,z.useState)({}),[c,l]=(0,z.useState)(`{}`),[u,d]=(0,z.useState)(`guided`),[f,p]=(0,z.useState)(null),[m,h]=(0,z.useState)(`upsert`),[g,_]=(0,z.useState)(null),[v,y]=(0,z.useState)(null),[b,x]=(0,z.useState)(`load`),[S,C]=(0,z.useState)(null),[w,T]=(0,z.useState)(null),E=(0,z.useMemo)(()=>qb(n?.capability_catalog.capabilities??[],e),[n,e]),D=E.find(e=>e.capability_id===i)??E.find(e=>Hb(e,`machine`))??E[0],O=D?Bb(D,e):void 0,ee=nx(n,O),te=!!(O?.machine_namespace&&ee),ne=!!(O&&Hb(O,`machine`)),k=(0,z.useMemo)(()=>ax(c),[c]),A=O?u===`json`?k:rx(O,ee,o):null,j=!!(O&&(u===`json`?k:ix(O,A??{})));async function M(){r(await Tg())}(0,z.useEffect)(()=>{let e=!0;return Tg().then(t=>{e&&r(t)}).catch(n=>{e&&C(n instanceof Error?n.message:t(`machine.loadError`))}).finally(()=>{e&&x(null)}),()=>{e=!1}},[t]),(0,z.useEffect)(()=>{if(!O)return;let e=nx(n,O),t=Mb(O.configuration_editor,e??O.default,O.default),r=rx(O,e,t);s(t),l(JSON.stringify(r,null,2)),d(ne?`guided`:`json`),p(null),h(`upsert`),y(null)},[n,i,e]);function N(e,t){s(n=>O?.capability_id===`periodic_report`?Pb(n,e,t):{...n,[e]:t}),p(null),h(`upsert`),C(null),T(null)}function P(e){if(O){if(e===`json`)l(JSON.stringify(rx(O,ee,o),null,2));else if(k)s(Mb(O.configuration_editor,k,O.default));else{C(t(`machine.jsonInvalid`));return}d(e),p(null),h(`upsert`),C(null)}}async function F(){if(!(!ne||!O?.machine_namespace||!A||!j||b)){x(`preview`),C(null),T(null);try{h(`upsert`),p(await kg(O.machine_namespace,A))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function re(){if(!(!ne||!O?.machine_namespace||!te||b)){x(`preview`),C(null),T(null);try{h(`remove`),p(await jg(O.machine_namespace))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function ie(){if(!ne||!O?.machine_namespace||!f||b||m===`upsert`&&!A)return;x(`apply`),C(null);let e=m;try{let n=e===`remove`?await Mg(O.machine_namespace,f.plan_revision):await Ag(O.machine_namespace,A,f.plan_revision);_(n),p(null),h(`upsert`),y(null),await M(),T(n.status===`applied`?t(e===`remove`?`machine.removed`:`machine.applied`):t(`machine.unchanged`))}catch(e){p(null),h(`upsert`),C(e instanceof Error?e.message:t(`machine.applyError`))}finally{x(null)}}async function I(){if(!(!g?.transaction_id||b)){x(`rollback-preview`),C(null);try{y(await Ng(g.transaction_id))}catch(e){C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}async function ae(){if(!(!g?.transaction_id||!v||b)){x(`rollback`),C(null);try{await Pg(g.transaction_id,v.plan_revision),_(null),y(null),p(null),await M(),T(t(`machine.rolledBack`))}catch(e){y(null),C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}return b===`load`?(0,B.jsx)(`div`,{className:`personal-machine-loading`,role:`status`,children:t(`common.loading`)}):O?(0,B.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":n?.revision,children:[(0,B.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:17}),t(`machine.liveDefault`)]}),(0,B.jsx)(`p`,{children:t(`machine.liveDefaultDescription`)})]}),(0,B.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,B.jsx)(Jb,{capabilities:E,locale:e,onSelect:a,scope:`machine`,selectedCapabilityId:O.capability_id,t}),(0,B.jsxs)(`article`,{"aria-label":O.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,B.jsx)(Yb,{capability:D,locale:e,source:O.available_scopes.includes(`machine`)?te?`machine_default`:`capability_default`:void 0}),(0,B.jsx)(Gb,{available:ne,t,description:O.available_scopes.includes(`machine`)?t(`machine.editorUnavailableDescription`):t(`machine.goalOnly`)}),O.capability_id===`periodic_report`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:ee?.schedule?e===`zh-CN`?`日历与阶段汇报`:`Calendar and stage reports`:t(`machine.periodicReportActivation`)}),(0,B.jsx)(`p`,{children:ee?.schedule?ee.enabled===!0?e===`zh-CN`?`已配置日历计划,由现有唤醒检查;是否送达请核对报告回执。`:`A calendar schedule is configured and checked by existing wakes. Verify delivery in the report receipt.`:e===`zh-CN`?`日历计划已保存;启用此能力后才会检查和投递。`:`The schedule is saved; enable this capability to check and deliver reports.`:t(`machine.periodicReportActivationDescription`)})]})]}):null,O.capability_id===`change_quality_qualification`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.changeQualityActivation`)}),(0,B.jsx)(`p`,{children:t(`machine.changeQualityActivationDescription`)})]})]}):null,O.capability_id===`todo_replan_cadence`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.replanCadenceActivation`)}),(0,B.jsx)(`p`,{children:t(`machine.replanCadenceActivationDescription`)})]})]}):null,O.capability_id===`pull_request_review`?(0,B.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,B.jsx)(Wm,{"aria-hidden":!0,size:18}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:e===`zh-CN`?`只改变队列排序`:`Queue ordering only`}),(0,B.jsx)(`p`,{children:e===`zh-CN`?`默认先审阅其他开发者的 PR;选择 owner-first 才会优先当前已认证审阅者自己的 PR。此配置不会发布 review、写 Todo、push 或 merge。`:`The default reviews other developers' PRs first; choose owner-first only when the authenticated reviewer's own PRs should lead. This setting never posts a review, writes Todos, pushes, or merges.`})]})]}):null,ne?(0,B.jsxs)(B.Fragment,{children:[u===`json`||!O.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,B.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,B.jsxs)(`button`,{onClick:()=>P(u===`guided`?`json`:`guided`),type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),t(u===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,u===`guided`?(0,B.jsxs)(`section`,{className:`personal-capability-field-summary`,children:[(0,B.jsx)(Lb,{copy:Vb(e),disabled:!!b,editor:O.configuration_editor,onChange:N,value:o,enabledAction:(0,B.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:()=>P(`json`),type:`button`,children:[(0,B.jsx)(sm,{"aria-hidden":!0,size:14}),t(`machine.editJson`)]})}),j?null:(0,B.jsx)(`p`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.requiredFields`)})]}):(0,B.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`machine-configuration-json`,children:[(0,B.jsx)(`span`,{children:t(`machine.jsonConfiguration`)}),(0,B.jsx)(`textarea`,{"aria-describedby":`machine-configuration-json-help`,disabled:!!b,id:`machine-configuration-json`,onChange:e=>{l(e.target.value),p(null),C(null)},rows:12,spellCheck:!1,value:c}),(0,B.jsx)(`small`,{id:`machine-configuration-json-help`,children:t(`machine.jsonConfigurationHelp`)}),k?null:(0,B.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.jsonInvalid`)})]})]}):null,S?(0,B.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:S}):null,w?(0,B.jsxs)(`p`,{className:`personal-machine-notice`,role:`status`,"aria-live":`polite`,children:[(0,B.jsx)(em,{"aria-hidden":!0,size:16}),w]}):null,f?(0,B.jsxs)(`section`,{"aria-label":t(`machine.preview`),className:`personal-machine-preview`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.preview`)}),(0,B.jsx)(`span`,{children:t(`machine.action.${f.action}`)})]}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`machine.currentRevision`)}),(0,B.jsx)(`dd`,{title:f.current_revision,children:ox(f.current_revision)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`machine.desiredRevision`)}),(0,B.jsx)(`dd`,{title:f.desired_revision,children:ox(f.desired_revision)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:t(`machine.changedNamespaces`)}),(0,B.jsx)(`dd`,{children:f.changed_namespaces.join(`, `)||t(`common.none`)})]})]}),(0,B.jsx)(`p`,{children:t(`machine.previewLocked`)})]}):null,g?.rollback_available&&g.transaction_id?(0,B.jsxs)(`section`,{className:`personal-machine-rollback`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:t(`machine.rollbackAvailable`)}),(0,B.jsx)(`p`,{children:t(v?`machine.rollbackPreviewDescription`:`machine.rollbackDescription`)})]}),(0,B.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!!b||!!(v&&!v.rollback_allowed),onClick:()=>void(v?ae():I()),type:`button`,children:[(0,B.jsx)(Lm,{"aria-hidden":!0,size:15}),t(b===`rollback`||b===`rollback-preview`?`common.loading`:v?`machine.confirmRollback`:`machine.previewRollback`)]})]}):null,ne?(0,B.jsxs)(`footer`,{className:`personal-capability-actions`,children:[te?(0,B.jsxs)(`button`,{className:`is-danger`,disabled:!!b,onClick:()=>void re(),type:`button`,children:[(0,B.jsx)(Xm,{"aria-hidden":!0,size:15}),t(`machine.previewRemoval`)]}):null,(0,B.jsx)(`button`,{disabled:!!b||!j,onClick:()=>void F(),type:`button`,children:t(b===`preview`?`common.loading`:`machine.previewChanges`)}),(0,B.jsx)(`button`,{className:`is-primary`,disabled:!!b||!f,onClick:()=>void ie(),type:`button`,children:t(b===`apply`?`common.loading`:`machine.applyPreview`)})]}):null,O.available_scopes.includes(`machine`)?(0,B.jsx)(Ub,{values:[{label:t(`machine.currentValue`),value:ee},{label:t(`capabilities.defaultValue`),value:O.default}],t},O.capability_id):null]})]})]}):(0,B.jsx)(`p`,{className:`personal-capability-empty`,children:t(`machine.capabilityEmpty`)})}var cx={appearance:Am,capabilities:Gm,language:bm,lark:Um,machine:Vm};function lx({focusGoalConnection:e=!1,goals:t,initialGoalId:n,initialTab:r=`lark`,onChanged:i,onClose:a,onThemeChange:o,theme:s}){let{locale:c,setLocale:l,t:u}=Ji(),[d,f]=(0,z.useState)(r),p=[...n?[{key:`capabilities`,label:u(`capabilities.title`)}]:[],{key:`machine`,label:u(`machine.title`)},{key:`lark`,label:`Lark`},{key:`appearance`,label:u(`settings.appearance`)},{key:`language`,label:u(`settings.language`)}],m=[{label:u(`settings.languageEnglish`),value:`en`},{label:u(`settings.languageSimplifiedChinese`),value:`zh-CN`}],h={appearance:{title:u(`settings.appearance`)},capabilities:{title:u(`capabilities.title`)},language:{title:u(`settings.language`)},lark:{title:`Lark`},machine:{title:u(`machine.title`)}}[d];return(0,B.jsxs)(`section`,{"aria-label":u(`settings.title`),className:`personal-settings-page`,"data-pw-theme":s,children:[(0,B.jsxs)(`aside`,{className:`personal-settings-sidebar`,children:[(0,B.jsxs)(`button`,{className:`personal-settings-back`,onClick:a,type:`button`,children:[(0,B.jsx)(Gp,{size:17}),(0,B.jsx)(`span`,{children:u(`settings.back`)})]}),(0,B.jsxs)(`div`,{className:`personal-settings-title`,children:[(0,B.jsx)(`small`,{children:u(`settings.eyebrow`)}),(0,B.jsx)(`strong`,{children:u(`settings.title`)})]}),(0,B.jsx)(`nav`,{"aria-label":u(`settings.categories`),className:`personal-settings-tabs`,children:p.map(e=>{let t=cx[e.key];return(0,B.jsxs)(`button`,{"aria-current":d===e.key?`page`:void 0,onClick:()=>f(e.key),type:`button`,children:[(0,B.jsx)(t,{size:17}),(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:e.label})})]},e.key)})})]}),(0,B.jsxs)(`main`,{className:`personal-settings-body`,children:[(0,B.jsx)(`header`,{className:`personal-settings-header`,children:(0,B.jsx)(`div`,{children:(0,B.jsx)(`h1`,{children:h.title})})}),d===`lark`?(0,B.jsx)(Ab,{embedded:!0,focusGoalConnection:e,goals:t,initialGoalId:n,onChanged:i,onClose:a}):null,d===`machine`?(0,B.jsx)(sx,{}):null,d===`capabilities`?(0,B.jsx)(ex,{goalId:n}):null,d===`appearance`?(0,B.jsxs)(`section`,{className:`personal-detail-card personal-appearance-settings`,children:[(0,B.jsx)(`small`,{children:u(`settings.workspaceDisplay`)}),(0,B.jsx)(`h3`,{children:u(`settings.appearance`)}),(0,B.jsxs)(`div`,{className:`personal-settings-choice-group`,role:`radiogroup`,"aria-label":u(`settings.workspaceTheme`),children:[(0,B.jsxs)(`button`,{"aria-checked":s===`loopx`,onClick:()=>o(`loopx`),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-settings-theme-swatch is-loopx`}),(0,B.jsx)(`strong`,{children:u(`settings.themeLoopx`)})]}),(0,B.jsxs)(`button`,{"aria-checked":s===`paper`,onClick:()=>o(`paper`),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-settings-theme-swatch is-paper`}),(0,B.jsx)(`strong`,{children:u(`settings.themeDefault`)})]}),(0,B.jsxs)(`button`,{"aria-checked":s===`brutal`,onClick:()=>o(`brutal`),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-settings-theme-swatch is-brutal`}),(0,B.jsx)(`strong`,{children:u(`settings.themeHighContrast`)})]})]})]}):null,d===`language`?(0,B.jsxs)(`section`,{className:`personal-settings-card`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`span`,{className:`personal-settings-icon`,children:(0,B.jsx)(bm,{size:18})}),(0,B.jsx)(`div`,{children:(0,B.jsx)(`h2`,{children:u(`settings.language`)})})]}),(0,B.jsx)(`div`,{"aria-label":u(`settings.language`),className:`personal-language-options`,role:`radiogroup`,children:m.map(e=>(0,B.jsxs)(`button`,{"aria-checked":c===e.value,className:c===e.value?`is-selected`:``,onClick:()=>l(e.value),role:`radio`,type:`button`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(`strong`,{children:e.label})}),c===e.value?(0,B.jsx)(em,{"aria-hidden":!0,size:17}):null]},e.value))})]}):null]})]})}var ux=`loopx-pw-theme`,dx=`loopx`;function fx(){try{let e=window.localStorage.getItem(ux);return e===`loopx`||e===`paper`||e===`brutal`?e:dx}catch{return dx}}function px(e){try{window.localStorage.setItem(ux,e)}catch{}}function mx({drawer:e,drawerMode:t=`panel`,drawerOpen:n,main:r,mobileSidebarOpen:i=!1,onCloseMobileSidebar:a,sidebar:o,theme:s=`loopx`}){let{t:c}=Ji(),l=(0,z.useRef)(null),u=(0,z.useRef)(null);return(0,z.useEffect)(()=>{if(!i)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null;let e=l.current?.querySelectorAll(`button:not([disabled]), a[href], select:not([disabled]), textarea:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])`);e?.[0]?.focus();function t(t){if(t.key!==`Tab`||!e?.length)return;let n=e[0],r=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),r.focus()):!t.shiftKey&&document.activeElement===r&&(t.preventDefault(),n.focus())}return document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`keydown`,t),u.current?.focus(),u.current=null}},[i]),(0,B.jsxs)(`section`,{className:`personal-workspace-shell${n?` has-drawer`:``}${n&&t.startsWith(`inspector`)?` has-task-inspector`:``}${t===`inspector-full`?` is-task-inspector-full`:``}${i?` mobile-sidebar-open`:``}`,"data-pw-theme":s,children:[i?(0,B.jsx)(`button`,{"aria-hidden":!0,className:`personal-sidebar-backdrop`,onClick:a,tabIndex:-1,type:`button`}):null,(0,B.jsx)(`aside`,{"aria-label":i?c(`header.goalNavigation`):void 0,"aria-modal":i?!0:void 0,className:`personal-workspace-sidebar`,"data-workspace-sidebar":!0,ref:l,role:i?`dialog`:void 0,children:(0,B.jsxs)(`div`,{className:`personal-workspace-sidebar-inner`,children:[i?(0,B.jsxs)(`button`,{className:`personal-sr-only`,onClick:a,type:`button`,children:[c(`common.close`),` `,c(`header.goalNavigation`)]}):null,o]})}),(0,B.jsx)(`main`,{"aria-hidden":i||void 0,className:`personal-workspace-main`,inert:i||void 0,children:r}),n?(0,B.jsx)(`aside`,{className:`personal-workspace-drawer`,"data-context-drawer":!0,"data-drawer-mode":t,children:e}):null]})}function hx(e){let t=e.match(/(?:下一步|建议|行动项|待办)[::\s]*([^\n]+)/u),n=t?t[1]:e;n=n.replace(/```[\s\S]*?```/g,``).replace(/`([^`]+)`/g,`$1`).replace(/\[([^\]]+)\]\([^)]+\)/g,`$1`).replace(/[#*~_>]/g,``).replace(/^[-*•\d+.\s]+/u,``).replace(/^(好的|没问题|收到|建议如下|任务如下|分析如下|结论[::])[\s,,::]*/u,``);let r=(n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean)[0]||n).replace(/\s+/gu,` `).trim();return Array.from(r).slice(0,120).join(``)}function gx(e){let t=new Map;return e.forEach(e=>{let n=e.fields.find(e=>e.key===`todo_id`)?.value??``,r=[e.actionKind,e.goalId??``,n,e.title].join(`:`);t.set(r,e)}),[...t.values()]}function _x(e,t,n){if(!e)return n(`home.noFirstActivity`);let r=new Date(e);if(Number.isNaN(r.getTime()))return e;let i=new Date,a=new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r);return r.toDateString()===i.toDateString()?n(`home.todayAt`,{time:a}):new Intl.DateTimeFormat(t,{month:`numeric`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r)}function vx({goals:e,onSelectGoal:t,onRetry:n,systemHealth:r}){let{locale:i,t:a}=Ji(),o=e.filter(e=>e.activationState===`active`),s=o.filter(e=>e.loadState===`error`).length,c=[{key:`needs_you`,label:a(`home.lane.needsYou`)},{key:`running`,label:a(`home.lane.running`)},{key:`observing`,label:a(`home.lane.observing`)},{key:`scheduled`,label:a(`home.lane.scheduled`)}],l=Object.fromEntries(c.map(e=>[e.key,[]])),u=[],d=[];e.filter(e=>!e.loadState).forEach(e=>{let t=gy(e);t===`history`?u.push(e):t===`stopped`?d.push(e):l[t].push(e)});let f=e=>(0,B.jsxs)(`button`,{className:`personal-home-goal-card`,"data-goal-state":e.loadState??e.state,"data-load-error":e.loadError,onClick:()=>t(e.goalId),type:`button`,children:[(0,B.jsxs)(`span`,{className:`personal-home-goal-meta`,children:[(0,B.jsx)(`i`,{}),e.agentLaneCount&&e.agentLaneCount>1?a(`header.workAgentCount`,{count:e.agentLaneCount}):e.agentLabel??e.agentId]}),(0,B.jsx)(`strong`,{children:e.title}),(0,B.jsx)(`p`,{children:e.loadError?a(`startup.error.${e.loadError}`):e.needsYou??e.nextSentence}),(0,B.jsxs)(`footer`,{children:[(0,B.jsx)(`span`,{children:e.loadState?a(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Yi(e.state,i)}),(0,B.jsx)(`small`,{title:e.latestActivity,children:e.loadState?``:e.latestActivity?_x(e.latestActivity,i,a):e.agentTodos.length?a(`home.taskCount`,{count:e.agentTodos.length}):a(`home.noActivity`)})]})]},e.goalId);return(0,B.jsxs)(`section`,{"aria-label":a(`home.workspace`),className:`personal-home-board`,children:[r&&(!r.ok||r.issues.length>0||r.freshnessWarning)?(0,B.jsxs)(`div`,{className:`personal-system-health-banner`,role:`alert`,children:[(0,B.jsxs)(`div`,{className:`personal-system-health-header`,children:[(0,B.jsx)(im,{size:15}),(0,B.jsx)(`strong`,{children:a(`home.systemHealth`,{summary:r.summary})}),r.freshnessWarning?(0,B.jsxs)(`small`,{children:[`(`,r.freshnessWarning,`)`]}):null]}),r.issues.length>0?(0,B.jsx)(`ul`,{className:`personal-system-health-issues`,children:r.issues.map((e,t)=>(0,B.jsx)(`li`,{children:e},t))}):null]}):null,o.some(e=>e.loadState)?(0,B.jsxs)(`section`,{className:`personal-home-lane`,"aria-live":`polite`,children:[(0,B.jsx)(`header`,{children:a(`startup.progress`,{loaded:o.filter(e=>!e.loadState).length,total:o.length})}),s?(0,B.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`status`,children:[(0,B.jsx)(`span`,{children:a(`startup.failedCount`,{count:s})}),(0,B.jsx)(`button`,{className:`min-h-11 rounded-md border px-3 py-2 text-sm`,onClick:n,type:`button`,children:a(`startup.retryFailed`)})]}):null,o.filter(e=>e.loadState).map(f)]}):null,(0,B.jsx)(`div`,{className:`personal-home-lanes`,children:c.map(e=>(0,B.jsxs)(`section`,{className:`personal-home-lane is-${e.key}`,"data-testid":`personal-home-lane-${e.key}`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`i`,{}),e.label]}),(0,B.jsx)(`b`,{children:l[e.key].length})]}),(0,B.jsx)(`div`,{className:`personal-home-lane-list`,children:l[e.key].length?l[e.key].map(f):(0,B.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.empty`)})})]},e.key))}),(0,B.jsxs)(`details`,{className:`personal-home-history`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(`span`,{children:a(`home.history`)}),(0,B.jsx)(`b`,{children:u.length}),(0,B.jsx)(`small`,{children:a(`home.completedGoals`)})]}),(0,B.jsx)(`div`,{children:u.length?u.map(f):(0,B.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.noCompletedGoals`)})})]}),d.length?(0,B.jsxs)(`details`,{className:`personal-home-history is-stopped`,children:[(0,B.jsxs)(`summary`,{children:[(0,B.jsx)(`span`,{children:a(`home.stopped`)}),(0,B.jsx)(`b`,{children:d.length}),(0,B.jsx)(`small`,{children:a(`home.preservedState`)})]}),(0,B.jsx)(`div`,{children:d.map(f)})]}):null]})}function yx({items:e,onSelect:t,reportState:n}){let{locale:r,t:i}=Ji();return(0,B.jsxs)(`section`,{className:`personal-object-list personal-files-list`,"data-testid":`personal-goal-outputs`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsx)(`strong`,{children:i(`files.title`)}),(0,B.jsx)(`span`,{children:e.length})]}),n?.loading?(0,B.jsxs)(`p`,{className:`personal-object-list-state`,role:`status`,children:[(0,B.jsx)(Im,{className:`is-spinning`,size:14}),i(`files.loadingReports`)]}):null,n?.error?(0,B.jsxs)(`p`,{className:`personal-object-list-state is-error`,role:`alert`,children:[(0,B.jsx)(im,{size:14}),i(`files.reportLoadFailed`),`: `,n.error]}):null,!n?.loading&&!n?.error&&e.length===0?(0,B.jsxs)(`p`,{className:`personal-object-list-state`,children:[(0,B.jsx)(gm,{size:14}),i(`files.empty`)]}):null,e.map(e=>(0,B.jsxs)(`button`,{"data-output-kind":e.output.kind,onClick:()=>t({item:e.output,kind:`output`}),type:`button`,children:[(0,B.jsx)(`span`,{className:`personal-file-icon`,children:(0,B.jsx)(gm,{size:16})}),(0,B.jsx)(`strong`,{children:e.output.title}),e.output.report?(0,B.jsx)(`em`,{children:i(`files.reportDelta`,{added:e.output.report.addedCount,changed:e.output.report.changedCount})}):null,(0,B.jsx)(`p`,{children:e.output.summary??e.output.safePreview??e.output.kind??i(`files.emptySummary`)}),(0,B.jsx)(`small`,{title:e.output.createdAt,children:[e.output.goalTitle,e.output.kind===`report`?i(`files.verifiedReport`):null,e.output.todoId?`${i(`common.task`)} ${e.output.todoId}`:null,_x(e.output.createdAt,r,i)].filter(Boolean).join(` · `)})]},e.id))]})}function bx({agentLabel:e,messages:t,onClose:n,onDraftTask:r,onOpenConversation:i,title:a}){let{t:o}=Ji(),s=t.reduce((e,t,n)=>t.role===`user`?n:e,0),c=t.slice(Math.max(0,s)).slice(-3),l=c.filter(e=>e.role===`assistant`&&!e.pending).at(-1);return(0,z.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),(0,B.jsxs)(`aside`,{"aria-label":o(`conversation.receipt`),className:`personal-manager-conversation-tray`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:16}),(0,B.jsx)(`strong`,{children:a??o(`conversation.title`)}),(0,B.jsx)(`small`,{children:t.at(-1)?.pending?o(`conversation.replying`):o(`common.recently`)})]}),(0,B.jsxs)(`div`,{className:`personal-manager-conversation-actions`,children:[r&&l?(0,B.jsxs)(`button`,{className:`personal-manager-conversation-btn`,onClick:()=>r(l.text),title:o(`conversation.convertHint`),type:`button`,children:[(0,B.jsx)(Sm,{size:13}),(0,B.jsx)(`span`,{children:o(`conversation.toTask`)})]}):null,(0,B.jsx)(`button`,{className:`personal-manager-conversation-link`,onClick:i,type:`button`,children:o(`conversation.full`)}),n?(0,B.jsx)(`button`,{"aria-label":o(`conversation.close`),className:`personal-manager-conversation-close`,onClick:n,title:o(`conversation.close`),type:`button`,children:(0,B.jsx)($m,{size:14})}):null]})]}),(0,B.jsx)(`div`,{"aria-live":`polite`,className:`personal-manager-conversation-messages`,children:c.map(t=>(0,B.jsxs)(`article`,{className:`is-${t.role}`,children:[(0,B.jsx)(`strong`,{children:t.role===`user`?o(`common.you`):t.agentLabel??e??o(`header.manager`)}),(0,B.jsxs)(`div`,{className:`personal-manager-conversation-bubble`,children:[t.role===`user`?(0,B.jsx)(`p`,{children:t.text}):(0,B.jsx)(jy,{text:t.text}),t.pending?(0,B.jsx)(`small`,{children:o(`conversation.agentPending`)}):null]})]},t.id))})]})}function xx({onClose:e,onOpenDetails:t,run:n}){let{t:r}=Ji();return(0,B.jsxs)(`section`,{"aria-label":r(`session.record`),className:`personal-session-record`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:17}),r(`session.record`)]}),(0,B.jsx)(`button`,{"aria-label":r(`session.closeRecord`),onClick:e,type:`button`,children:(0,B.jsx)($m,{size:15})})]}),(0,B.jsx)(`div`,{children:(0,B.jsx)(`strong`,{children:n.title})}),(0,B.jsxs)(`dl`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Agent`}),(0,B.jsx)(`dd`,{children:n.agentLabel})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:r(`common.status`)}),(0,B.jsx)(`dd`,{children:Xi(n.sessionStatus??n.status,r)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`Session`}),(0,B.jsx)(`dd`,{title:n.sessionId,children:n.sessionId})]})]}),(0,B.jsx)(`button`,{className:`personal-secondary-action`,onClick:t,type:`button`,children:r(`session.details`)})]})}function Sx(e,t,n){let r=[];if(t===null)return e.userTodos.slice(0,4).forEach(t=>r.push({attention:{...t,goalTitle:t.goalTitle??hy(e,t.goalId)},id:`attention:${t.todoId}`,kind:`attention`})),e.goals.filter(e=>gy(e)===`running`).slice(0,4).forEach(e=>r.push({id:`run:${e.goalId}`,kind:`run`,run:{agentId:e.agentId,agentLabel:e.agentLabel??e.agentId,completedSteps:e.doneTodoCount??e.agentTodos.filter(e=>e.done).length,goalId:e.goalId,goalTitle:e.title,latestActivity:e.agentSentence,runId:`goal:${e.goalId}`,status:`running`,title:e.nextSentence,totalSteps:Math.max((e.doneTodoCount??0)+e.agentTodos.filter(e=>!e.done).length,1)}})),r;let i=e.goals.find(e=>e.goalId===t);if(!i)return r;if(i.needsYou){let t=e.userTodos.find(e=>e.goalId===i.goalId);r.push({attention:t?{...t,goalTitle:i.title}:{blocking:i.needsYouBlocking??!1,goalId:i.goalId,goalTitle:i.title,text:i.needsYou,todoId:`${i.goalId}:attention`},id:`attention:${i.goalId}`,kind:`attention`})}r.push({id:`run:${i.goalId}`,kind:`run`,run:{agentId:i.agentId,agentLabel:i.agentLabel??i.agentId,completedSteps:i.doneTodoCount??i.agentTodos.filter(e=>e.done).length,goalId:i.goalId,goalTitle:i.title,latestActivity:i.agentSentence,runId:`goal:${i.goalId}`,status:i.state===`推进中`?`running`:i.state===`需修复`?`failed`:`waiting`,title:i.nextSentence,totalSteps:Math.max((i.doneTodoCount??0)+i.agentTodos.filter(e=>!e.done).length,1)}}),i.agentTodos.filter(e=>e.taskClass===`continuous_monitor`).forEach(t=>{let a=e.timeline?.find(e=>e.kind===`run`&&e.run.goalId===i.goalId&&e.run.todoId===t.todoId&&!!e.run.sessionId);r.push({id:`schedule:${i.goalId}:${t.todoId}`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:a?[{label:a.run.latestActivity||a.run.title,runId:a.run.runId,status:a.run.status===`waiting`||a.run.status===`queued`?`running`:a.run.status,timestamp:i.latestActivity||n(`common.recently`)}]:[],goalId:i.goalId,label:t.text,schedule:t.evidence??n(`schedule.summary`),scheduleId:t.todoId,scheduleKind:`monitor`,sessionId:a?.run.sessionId,status:t.done||t.status===`paused`?`paused`:`active`,stopCondition:n(`drawer.scheduleDefaultStop`),target:t.text,timezone:`Asia/Shanghai`}})});let a=e.timeline?.find(e=>e.kind===`proposal`&&e.proposal.actionKind===`heartbeat.bind`&&e.proposal.goalId===i.goalId);if(a){let e=e=>a.proposal.fields.find(t=>t.key===e)?.value;r.push({id:`schedule:${i.goalId}:heartbeat`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:[],goalId:i.goalId,label:`${n(`schedule.heartbeat`)} · ${i.title}`,nextRunAt:n(`drawer.schedulePending`),notificationRule:n(`drawer.scheduleDefaultNotification`),schedule:e(`cadence`)??n(`schedule.summary`),scheduleId:`${i.goalId}:heartbeat`,scheduleKind:`heartbeat`,status:a.proposal.status===`applied`?`active`:`draft`,stopCondition:e(`stop_condition`)??n(`drawer.scheduleDefaultStop`),timezone:e(`timezone`)??`Asia/Shanghai`}})}return r}function Cx(e){return e===`preview_ready`?`ready`:e===`cancelled`?`draft`:e===`failed`?`error`:e}function wx(e,t){let n={agent_id:t(`proposal.field.agentId`),cadence:t(`proposal.field.cadence`),completion_criteria:t(`proposal.field.completionCriteria`),execution_boundary:t(`proposal.field.executionBoundary`),goal_id:t(`proposal.field.goalId`),heartbeat:t(`proposal.field.heartbeat`),initial_todos:t(`proposal.field.initialTodos`),objective:t(`proposal.field.objective`),operation:t(`proposal.field.operation`),permission:t(`proposal.field.permission`),reason:t(`proposal.field.reason`),stop_condition:t(`proposal.field.stopCondition`),target:t(`proposal.field.target`),timezone:t(`proposal.field.timezone`),title:t(`proposal.field.title`),workspace_ref:t(`proposal.field.workspace`)},r=[`title`,`objective`,`completion_criteria`,`execution_boundary`,`permission`,`agent_id`,`workspace_ref`,`initial_todos`,`heartbeat`,`stop_condition`,`goal_id`];return Object.entries(e).sort(([e],[t])=>{let n=r.indexOf(e),i=r.indexOf(t);return(n<0?r.length:n)-(i<0?r.length:i)}).slice(0,10).map(([e,r])=>({key:e,label:n[e]??e.replaceAll(`_`,` `),value:e===`workspace_ref`?r===`current`?t(`proposal.workspace.current`):t(`proposal.workspace.named`,{workspace:String(r??`current`)}):Array.isArray(r)?r.join(` · `):typeof r==`object`&&r?JSON.stringify(r):String(r??`—`)}))}function Tx(e,t){let n=e.normalized_parameters.projection,r=n&&typeof n==`object`?n:{},i=Array.isArray(r.fields)?r.fields.flatMap((e,t)=>{if(!e||typeof e!=`object`)return[];let n=e;return typeof n.label!=`string`||typeof n.value!=`string`?[]:[{key:`projection:${t}`,label:n.label,value:n.value}]}).slice(0,8):[];return[{key:`operation_state`,label:t(`proposal.field.operationState`),value:e.operation?.lifecycle_state??e.status},...e.operation?.lifecycle_state===`outcome_observed`?[{key:`result_delivery`,label:t(`proposal.field.resultDelivery`),value:e.operation.result_delivery?t(`proposal.resultDelivery.verified`):t(`proposal.resultDelivery.pending`)}]:[],...i,...typeof r.warning==`string`?[{key:`warning`,label:t(`proposal.field.confirmationBoundary`),value:r.warning}]:[],...e.operation?.expires_at?[{key:`expires_at`,label:t(`proposal.field.expiresAt`),value:e.operation.expires_at}]:[]].slice(0,10)}function Ex(e){if(e.action_kind!==`goal.lifecycle`)return;let t=e.normalized_parameters.operation;return t===`stop`||t===`resume`||t===`delete`?t:void 0}function Dx(e,t){let n=Ex(e),r=fy(e),i=typeof e.normalized_parameters.title==`string`?e.normalized_parameters.title:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:``,a=typeof e.normalized_parameters.target==`string`?e.normalized_parameters.target:``,o=e.normalized_parameters.projection,s=o&&typeof o==`object`&&typeof o.title==`string`?String(o.title):e.summary,c=e.action_kind===`operation.execute`?s:e.action_kind===`goal.create`?t(`proposal.summary.goalCreate`,{title:i}):e.action_kind===`heartbeat.bind`?t(`proposal.summary.heartbeat`):e.action_kind===`monitor.create`?t(`proposal.summary.monitor`,{target:a}):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.summary.lifecycleStop`,{title:i}):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.summary.lifecycleDelete`,{title:i}):e.action_kind===`goal.lifecycle`?t(`proposal.summary.lifecycleResume`,{title:i}):e.summary;return{actionKind:e.action_kind,reviewPlan:r,fields:e.action_kind===`operation.execute`?Tx(e,t):wx(e.normalized_parameters,t),goalId:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:void 0,impact:e.action_kind===`operation.execute`?t(`proposal.impact.operation`):e.action_kind===`goal.create`?t(`proposal.impact.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.impact.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.impact.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.impact.lifecycleResume`):e.permission_classification===`protected`?t(`proposal.impact.protected`):t(`proposal.impact.default`),previewId:e.proposal_id,lifecycleOperation:n,gate:e.gate?{kind:String(e.gate.kind??`protected_action`),nextAction:typeof e.gate.next_action==`string`?e.gate.next_action:void 0,summary:String(e.gate.summary??t(`proposal.gate.default`))}:void 0,primaryLabel:e.action_kind===`operation.execute`?e.operation?.lifecycle_state===`outcome_observed`?e.operation.result_delivery?t(`proposal.primary.operationResultVerified`):t(`proposal.primary.operationResultPending`):t(`proposal.primary.operationGroup`):e.action_kind===`goal.create`?t(`proposal.primary.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.primary.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.primary.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.primary.lifecycleResume`):e.action_kind===`todo.create`&&e.normalized_parameters.start_execution===!0?t(`proposal.primary.todoStart`):t(`proposal.primary.apply`),status:e.status===`applied`&&e.action_kind!==`operation.execute`&&r.interaction!==`completed`?`error`:Cx(e.status),title:c}}function Ox(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,42);if(t)return t;let n=2166136261;for(let t of e)n^=t.codePointAt(0)??0,n=Math.imul(n,16777619);return`goal-${(n>>>0).toString(36)}`}function kx(e,t){let n=e.match(/[「“"]([^」”"]{2,80})[」”"]/u)?.[1];return n?n.trim():e.replace(/^(请|帮我|我想|给我|创建|新建|设置|please|i want to|create|set up)+/iu,``).replace(/(一个|新的)?\s*(goal|目标)/giu,``).replace(/[,。!?].*$/u,``).trim().slice(0,80)||t(`goal.defaultTitle`)}function Ax(e,t){for(let n of e.split(/\r?\n/u)){let e=n.trim();for(let n of t){let t=e.match(RegExp(`^${n.replace(/[.*+?^${}()|[\]\\]/gu,`\\$&`)}\\s*[::]\\s*(.*)$`,`iu`));if(t?.[1]?.trim())return t[1].trim()}}return``}function jx(e,t){let n=Ax(e,[`目标`,`Objective`]),r=Ax(e,[`完成标准`,`Completion criteria`]),i=Ax(e,[`执行边界(可选)`,`执行边界`,`边界`,`Execution boundary (optional)`,`Execution boundary`,`Boundary`]),a=(n||kx(e,t)).split(/[。;;\n]/u)[0].trim().slice(0,80)||t(`goal.defaultTitle`),o=[n||a,r?t(`goal.objectiveCompletion`,{criteria:r}):``,i?t(`goal.objectiveBoundary`,{boundary:i}):``].filter(Boolean).join(` +`),s=/(只读|不调用外部工具|不修改(?:仓库|代码|状态)|read.?only|do not (?:call|use) external tools|do not modify (?:repositories|repository|code|state))/iu.test(i||e);return{completionCriteria:r,executionBoundary:i,initialTodos:r?[t(`goal.initialTodo`,{criteria:r})]:[],objective:o,permission:s?`read_only`:`workspace_write_on_confirmation`,title:a}}function Mx(e){let t=e.match(/(?:每|every)\s*(\d{1,3})\s*(?:分钟|minutes?)/iu)?.[1];if(t)return`${t}m`;let n=e.match(/(?:每|every)\s*(\d{1,2})\s*(?:小时|hours?)/iu)?.[1];return n?`${n}h`:/每小时|every hour|hourly/iu.test(e)?`1h`:(/每天|每日|早上|上午|daily|every day/iu.test(e),`1d`)}function Nx(e,t){return/(每周|星期|周[一二三四五六日天]|weekly|every\s+(?:mon|tues|wednes|thurs|fri|satur|sun)day|\d{1,2}\s*[::]\s*\d{2})/iu.test(e)?t(`schedule.unsupportedCalendar`):null}function Px(e,t){return Ax(e,[`检查内容`,`监控内容`,`目标`,`Check target`,`Monitor target`,`Target`])||e.replace(/^(?:为当前 Goal |for the current Goal )?(?:添加|配置|创建|add|configure|create)?\s*(?:定时检查|监控|scheduled check|monitor)[::]?/iu,``).split(/\r?\n/u)[0].trim()||t(`schedule.defaultTarget`)}function Fx(e){return/(mr|pr).{0,8}(合并|merge)/iu.test(e)?`pr_merged`:/发布完成|上线完成|release (?:is )?complete|deployment (?:is )?complete/iu.test(e)?`release_complete`:`goal_complete`}function Ix(e,t){let n=e.toLowerCase();return t.find(e=>n.includes(e.agentId.toLowerCase())||n.includes(e.label.toLowerCase()))}function Lx(e){let t=Ax(e,[`标题`,`任务标题`,`Todo 标题`]),n=Ax(e,[`内容`,`任务内容`,`Todo 内容`]);if(t)return[t,n].filter(Boolean).join(`:`).slice(0,400);let r=e.match(/[「“"]([^」”"]{2,200})[」”"]/u)?.[1];return r?r.trim():e.replace(/^(请|帮我|给我|为当前 Goal |新增|新建|创建|添加|加上|加一个|记一个)+/u,``).replace(/^(一个\s*)?(普通\s*)?(todo|待办|任务)(?:\s*到\s*Tasks?)?[::\s]*/iu,``).replace(/[。;;,,]\s*(?:不要|不需要|无需|禁止|别|暂不).{0,80}(?:heartbeat|心跳|定时|监控|执行).*$/iu,``).replace(/[,,]\s*(并且|然后|再)?\s*(交给|分配给|让).+$/u,``).replace(/\s*(交给|分配给|让)\s+.+$/u,``).trim().slice(0,400)||`推进当前 Goal 的下一项工作`}var Rx=new Set([`image/png`,`image/jpeg`,`image/webp`,`image/gif`]),zx=5242880,Bx=4;function Vx(e,t){return new Promise((n,r)=>{let i=new FileReader;i.onerror=()=>r(Error(t(`composer.imageReadError`,{name:e.name}))),i.onload=()=>n({dataUrl:String(i.result??``),id:crypto.randomUUID(),mimeType:e.type,name:e.name,size:e.size}),i.readAsDataURL(e)})}function Hx({agents:e=[{agentId:`codex`,available:!0,capability:`代码与项目执行`,label:`Codex`}],callbacks:t={},goalArchiveLoadState:n={error:null,phase:`ready`},model:r,readOnly:i=!1,selectedAgentId:a,selectedGoalId:o,statusSourceControl:s}){let{locale:c,t:l}=Ji(),[u,d]=(0,z.useState)(o??null),[f,p]=(0,z.useState)(a??e.find(e=>e.available)?.agentId??`codex`),[m,h]=(0,z.useState)(null),[g,_]=(0,z.useState)(!1),[v,y]=(0,z.useState)(null),[b,x]=(0,z.useState)({}),[S,C]=(0,z.useState)(`chat`),[w,T]=(0,z.useState)(!1),[E,D]=(0,z.useState)(!1),[O,ee]=(0,z.useState)(!1),[te,ne]=(0,z.useState)(()=>{try{let e=window.sessionStorage.getItem(`loopx-pw-composer-drafts`),t=e?JSON.parse(e):{};return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}),[k,A]=(0,z.useState)(!1),[j,M]=(0,z.useState)([]),[N,P]=(0,z.useState)(null),[F,re]=(0,z.useState)(null),[ie,I]=(0,z.useState)(()=>new Set),[ae,L]=(0,z.useState)(()=>new Set),[oe,se]=(0,z.useState)(`idle`),[ce,le]=(0,z.useState)([]),[ue,de]=(0,z.useState)(!1),[fe,pe]=(0,z.useState)(fx),[me,he]=(0,z.useState)({}),[ge,_e]=(0,z.useState)([]),ve=(0,z.useRef)(!1),ye=(0,z.useRef)(NaN),be=(0,z.useRef)(null),xe=(0,z.useRef)(null),Se=(0,z.useRef)(null),Ce=(0,z.useRef)(new Set),we=(0,z.useRef)(new Set),[Te,Ee]=(0,z.useState)(null),R=o===void 0?u:o,De=a??f,Oe=`${R??`manager`}:${De}`,ke=te[Oe]??``;(0,z.useEffect)(()=>{M([]),P(null)},[Oe]);function Ae(e,t){ne(n=>{let r={...n};t?r[e]=t:delete r[e];try{window.sessionStorage.setItem(`loopx-pw-composer-drafts`,JSON.stringify(r))}catch{}return r})}function je(e){Ae(Oe,e)}function Me(e){let t=te[Oe]?.trimEnd();je(t?`${t}\n${e}`:e),window.requestAnimationFrame(()=>be.current?.focus())}(0,z.useEffect)(()=>{let e=be.current;e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,120)}px`)},[ke]);let Ne=(0,z.useMemo)(()=>r.goals.map(e=>{let t=me[e.goalId];return t?{...e,repository:{branch:t.branch,identity:t.identity,label:t.label,readOnly:!0}}:e}),[me,r.goals]),Pe=(0,z.useMemo)(()=>Ne.filter(e=>gy(e)===`needs_you`).length,[Ne]),Fe=(0,z.useMemo)(()=>Ne.filter(e=>gy(e)===`needs_you`&&(e.needsYouBlocking||e.state===`等你`)).length,[Ne]),V=Ne.find(e=>e.goalId===R)??null,Ie=m?.kind===`settings`,Le=R,Re=(0,z.useMemo)(()=>{let e=Object.values(b).filter(e=>e.actionKind===`heartbeat.bind`&&e.goalId&&e.status===`applied`).map(e=>({id:`schedule:${e.goalId}:heartbeat`,kind:`schedule`,schedule:{agentId:De,executionHistory:[],goalId:e.goalId,label:e.title,nextRunAt:l(`drawer.schedulePending`),notificationRule:l(`drawer.scheduleDefaultNotification`),schedule:e.fields.find(e=>e.key===`cadence`)?.value??l(`schedule.summary`),scheduleId:`${e.goalId}:heartbeat`,scheduleKind:`heartbeat`,status:e.status===`applied`?`active`:`draft`,stopCondition:e.fields.find(e=>e.key===`stop_condition`)?.value??l(`drawer.scheduleDefaultStop`),timezone:e.fields.find(e=>e.key===`timezone`)?.value??`Asia/Shanghai`}})),t=[...Sx(r,Le,l),...r.timeline??[],...e,...gx(Object.values(b)).filter(e=>e.actionKind!==`heartbeat.bind`||e.status!==`applied`).map(e=>({id:`proposal:${e.previewId}`,kind:`proposal`,proposal:e}))];return[...new Map(t.map(e=>[e.id,e])).values()].filter(e=>e.kind!==`proposal`||![`stale`,`error`].includes(e.proposal.status)||ce.includes(e.proposal.previewId)).filter(e=>!R||e.kind===`message`?!0:e.kind===`proposal`?!e.proposal.goalId||e.proposal.goalId===R:e.kind===`attention`?e.attention.goalId===R:e.kind===`run`?e.run.goalId===R:e.kind===`schedule`?e.schedule.goalId===R:e.output.goalId===R)},[Le,r,b,De,R,ce,l]),ze=(0,z.useMemo)(()=>v?Re.filter(e=>e.kind===`message`?!0:e.kind===`run`?e.run.runId===v.runId:e.kind===`output`&&e.output.runId===v.runId):Re,[v,Re]);(0,z.useEffect)(()=>{if(!v)return;let e=Re.find(e=>e.kind===`run`&&e.run.runId===v.runId);!e||e.kind!==`run`||JSON.stringify({completedSteps:v.completedSteps,latestActivity:v.latestActivity,messages:v.sessionMessages,sessionStatus:v.sessionStatus,status:v.status,totalSteps:v.totalSteps})!==JSON.stringify({completedSteps:e.run.completedSteps,latestActivity:e.run.latestActivity,messages:e.run.sessionMessages,sessionStatus:e.run.sessionStatus,status:e.run.status,totalSteps:e.run.totalSteps})&&y(e.run)},[v,Re]);let Be=(0,z.useMemo)(()=>Re.flatMap(e=>e.kind===`message`?[e.message]:[]),[Re]),Ve=(0,z.useMemo)(()=>V?Re.flatMap(e=>e.kind===`message`?[e.message]:[]):[],[Re,V]);(0,z.useEffect)(()=>{V||w||Be.some(e=>e.pending)&&D(!0)},[w,Be,V]),(0,z.useEffect)(()=>{!V||S===`chat`||Ve.some(e=>e.pending)&&ee(!0)},[Ve,V,S]);let He=(0,z.useMemo)(()=>Re.filter(e=>e.kind===`message`||e.kind===`proposal`&&ce.includes(e.proposal.previewId)),[Re,ce]),Ue=He[He.length-1],We=Ue?.kind===`message`?Ue.message.text.length:0;(0,z.useEffect)(()=>{if(!w||!xe.current)return;let e=window.requestAnimationFrame(()=>{xe.current&&(xe.current.scrollTop=xe.current.scrollHeight)});return()=>window.cancelAnimationFrame(e)},[He.length,w,We]);let Ge=(0,z.useMemo)(()=>{if(m?.kind===`settings`)return null;if(m?.kind===`attention`)return{kind:`attention`,item:Gd(m.item,r.attentionHistory??r.userTodos)};if(m?.kind===`goal`){let e=Ne.find(e=>e.goalId===m.item.goalId);return e?{item:e,kind:`goal`}:m}if(m?.kind!==`run`)return m;let e=Re.find(e=>e.kind===`run`&&e.run.runId===m.item.runId);return e?{item:e.run,kind:`run`}:m},[Re,m,Ne,r.attentionHistory,r.userTodos]);(0,z.useEffect)(()=>{if(i){he({}),_e([]);return}let e=!1;return Promise.all([Ig(),qg()]).then(([t,n])=>{e||(he(Object.fromEntries(t.map(e=>[e.goal_id,e.repository]))),_e(n))}).catch(()=>{}),()=>{e=!0}},[i]),(0,z.useEffect)(()=>{if(!ue)return;function e(e){e.key===`Escape`&&de(!1)}return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[ue]),(0,z.useEffect)(()=>{if(R||!Re.length)return;if(!ve.current){ve.current=!0;try{ye.current=Date.parse(window.localStorage.getItem(`loopx-pw-last-visit`)??``),window.localStorage.setItem(`loopx-pw-last-visit`,new Date().toISOString())}catch{ye.current=NaN}}let e=ye.current,t=Re.filter(e=>e.kind===`run`).map(e=>e.run),n=t=>{let n=Date.parse(t??``);return!Number.isNaN(e)&&!Number.isNaN(n)&&n>e},r={attention:Pe,done:t.filter(e=>e.status===`completed`&&n(e.latestActivity)).length,failed:t.filter(e=>(e.status===`failed`||e.status===`interrupted`)&&n(e.latestActivity)).length};Ee(e=>e?.attention===r.attention&&e.done===r.done&&e.failed===r.failed?e:r)},[Re,Pe,R]),(0,z.useEffect)(()=>{if(i){x({});return}let e=!1;return Mh(R?{goalId:R}:{contextKind:`manager`}).then(t=>{if(e)return;let n=Object.fromEntries(t.filter(e=>[`preview_ready`,`gated`,`deferred`,`applying`].includes(e.status)||e.action_kind===`operation.execute`&&e.status===`applied`).map(e=>{let t=Dx(e,l);return[t.previewId,t]}));x(e=>({...e,...n}))}).catch(()=>{}),()=>{e=!0}},[i,R,l]);async function Ke(e,n={}){if(i)throw Error(l(`source.readOnlyWriteError`));let r;try{r=t.onPreviewAction?await t.onPreviewAction(e):Dx(await Ah(e),l)}catch(t){if(!(t instanceof Th)||t.payload.error_code!==`action_preview_gate`)throw t;let n=t.payload.gate&&typeof t.payload.gate==`object`?t.payload.gate:{},i=(Array.isArray(n.candidates)?n.candidates:[]).flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.workspace_ref==`string`&&typeof t.label==`string`?[{label:t.label,workspaceRef:t.workspace_ref}]:[]}),a=String(n.kind??`workspace_selection_required`),o=a===`agent_binding_required`||a===`agent_identity_selection_required`;r={actionKind:e.actionKind,fields:i.map(e=>({key:`workspace_ref:${e.workspaceRef}`,label:e.label,value:e.workspaceRef})),gate:{kind:a,nextAction:typeof n.next_action==`string`?n.next_action:void 0,summary:String(n.summary??l(`proposal.workspaceGate.defaultSummary`))},impact:l(o?`proposal.workspaceGate.agentImpact`:`proposal.workspaceGate.selectionImpact`),previewId:`workspace-choice-${Date.now().toString(36)}`,sourceRequest:e,status:`gated`,title:l(o?`proposal.workspaceGate.agentTitle`:`proposal.workspaceGate.selectionTitle`),workspaceCandidates:i}}return le(e=>e.includes(r.previewId)?e:[...e,r.previewId]),x(e=>({...e,[r.previewId]:r})),n.select!==!1&&h({item:r,kind:`proposal`}),r}function qe(){tt(null),Ae(`manager:${De}`,l(`composer.createGoalTemplate`)),window.requestAnimationFrame(()=>be.current?.focus())}async function Je(e,n){de(!1);let r={delete:`Deleted from the owner workspace`,resume:`Resumed from the owner workspace`,stop:`Stopped from the owner workspace`},i={delete:l(`proposal.summary.lifecycleDelete`,{title:e.title}),resume:l(`proposal.summary.lifecycleResume`,{title:e.title}),stop:l(`proposal.summary.lifecycleStop`,{title:e.title})},a=null,o=!1;try{if(n===`stop`){if(Ce.current.has(e.goalId))return;Ce.current.add(e.goalId),I(new Set(Ce.current)),h(null),a={goalId:e.goalId,next:`stopped`,optimisticApplied:!0,previous:e.activationState},re(l(`feedback.applying`,{title:i.stop})),t.onGoalActivationStateChange?.(e.goalId,`stopped`)}if(t.onExecuteGoalLifecycle){if(n===`delete`)throw Error(`The selected status source does not authorize Goal deletion.`);let a=await t.onExecuteGoalLifecycle({goalId:e.goalId,operation:n,reason:r[n]});if(!a.projectionVerified)throw Error(`Goal lifecycle projection did not verify.`);o=!0,t.onGoalActivationStateChange?.(e.goalId,a.activationState),re(l(`feedback.completed`,{title:i[n]})),n===`stop`&&tt(null),await(t.onReconcileStatus??t.onRefresh)?.();return}let s=await Ke({actionKind:`goal.lifecycle`,context:{kind:`goal_directory`,goal_id:e.goalId},idempotencyKey:`workspace-goal-${n}-${e.goalId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,operation:n,reason:r[n]},summary:i[n]},{select:n!==`stop`});if(s.goalId!==e.goalId||s.lifecycleOperation!==n)throw h(null),Error(l(`actionReview.targetChanged`));n===`stop`&&(s.reviewPlan?.interaction===`direct`?(o=!0,await Qe(s,{lifecycleProjection:a??void 0,presentation:`feedback`})):(a&&t.onGoalActivationStateChange?.(a.goalId,a.previous),re(s.gate?l(`feedback.gateRequired`,{summary:s.gate.summary}):l(`feedback.notCompleted`,{status:s.status})),h({item:s,kind:`proposal`})))}catch(e){a&&!o&&t.onGoalActivationStateChange?.(a.goalId,a.previous),re(l(`feedback.executionFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{n===`stop`&&(Ce.current.delete(e.goalId),I(new Set(Ce.current)))}}function Ye(e,t){je(l(t?e===`heartbeat`?`composer.heartbeatTemplate`:`composer.monitorTemplate`:e===`heartbeat`?`composer.heartbeatTemplateWithoutGoal`:`composer.monitorTemplateWithoutGoal`)),h(null),window.requestAnimationFrame(()=>be.current?.focus())}async function Xe(e,n,r=``){let i=await t.onRequestScheduleConfig?.(e,n);if(i){le(e=>e.includes(i.previewId)?e:[...e,i.previewId]),x(e=>({...e,[i.previewId]:i})),h({item:i,kind:`proposal`});return}if(!n){je(l(e===`heartbeat`?`composer.heartbeatGoalQuestion`:`composer.monitorGoalQuestion`));return}let a=Date.now().toString(36);await Ke({actionKind:e===`heartbeat`?`heartbeat.bind`:`monitor.create`,context:{kind:`schedule`,goal_id:n},idempotencyKey:`workspace-${e}-${n}-${a}`,normalizedParameters:e===`heartbeat`?{agent_id:De,cadence:Mx(r),goal_id:n,stop_condition:Fx(r),timezone:`Asia/Shanghai`}:{agent_id:De,cadence:Mx(r),goal_id:n,stop_condition:Fx(r),target:Px(r,l),target_key:`goal-${n}`,timezone:`Asia/Shanghai`},summary:e===`heartbeat`?l(`proposal.summary.heartbeat`):l(`proposal.summary.monitor`,{target:Px(r,l)})})}async function Ze(e){if(!we.current.has(e.todoId)){we.current.add(e.todoId),L(new Set(we.current)),re(l(`feedback.preparingPreview`,{title:e.text}));try{await Ke({actionKind:`todo.update`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-${e.todoId}-complete-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,operation:`complete`,todo_id:e.todoId},summary:l(`tasks.markComplete`,{name:e.text})}),re(null)}catch(e){re(l(`feedback.previewFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{we.current.delete(e.todoId),L(new Set(we.current))}}}async function Qe(e,n={}){if(e.reviewPlan&&!e.reviewPlan.canApply)return;let i=n.presentation!==`feedback`,a=e.actionKind===`goal.lifecycle`&&e.goalId&&(e.lifecycleOperation===`stop`||e.lifecycleOperation===`resume`)?{goalId:e.goalId,next:e.lifecycleOperation===`stop`?`stopped`:`active`,optimisticApplied:!1,previous:r.goals.find(t=>t.goalId===e.goalId)?.activationState??(e.lifecycleOperation===`stop`?`active`:`stopped`)}:null,o=n.lifecycleProjection??a;re(l(`feedback.applying`,{title:e.title}));let s={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:`pending`,reason:`apply_pending`,canApply:!1}:void 0,status:`applying`};x(t=>({...t,[e.previewId]:s})),i&&h({item:s,kind:`proposal`}),o&&!o.optimisticApplied&&t.onGoalActivationStateChange?.(o.goalId,o.next);try{if(t.onApplyProposal){await t.onApplyProposal(e);let n={...e,status:`applied`};if(x(t=>({...t,[e.previewId]:n})),i&&h({item:n,kind:`proposal`}),re(l(`feedback.completed`,{title:e.title})),e.actionKind===`goal.lifecycle`){(e.lifecycleOperation===`stop`||e.lifecycleOperation===`delete`)&&tt(null),e.lifecycleOperation===`delete`&&e.goalId&&t.onGoalDeleted?.(e.goalId);let n=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>n?.()).catch(()=>void 0)}return}let n=await Nh(e.previewId);if(n.proposal.proposal_id!==e.previewId||n.proposal.action_kind!==e.actionKind||e.actionKind===`goal.lifecycle`&&(n.proposal.normalized_parameters.goal_id!==e.goalId||Ex(n.proposal)!==e.lifecycleOperation))throw new Th(l(`actionReview.targetChanged`),{error_code:`action_response_mismatch`});let r=Dx(n.proposal,l);if(x(t=>({...t,[e.previewId]:r})),i&&h({item:r,kind:`proposal`}),r.reviewPlan?.interaction!==`completed`){o&&t.onGoalActivationStateChange?.(o.goalId,o.previous),h({item:r,kind:`proposal`}),re(n.proposal.status===`stale`?l(`feedback.stale`):l(`actionReview.${r.reviewPlan.reason}`));return}if(re(l(`feedback.completed`,{title:r.title})),r.actionKind===`todo.create`&&await t.onRefresh?.(),r.actionKind===`goal.lifecycle`&&(r.lifecycleOperation===`stop`||r.lifecycleOperation===`delete`)&&tt(null),r.actionKind===`goal.lifecycle`&&r.lifecycleOperation===`delete`&&r.goalId&&t.onGoalDeleted?.(r.goalId),r.actionKind===`goal.lifecycle`){let e=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>e?.()).catch(()=>void 0)}}catch(n){if(o&&t.onGoalActivationStateChange?.(o.goalId,o.previous),n instanceof Th&&n.payload.error_code===`protected_action`){let r=n.payload.gate,i=r&&typeof r==`object`?r:{},a={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:`gated`,reason:`authority_gate`,canApply:!1}:void 0,gate:{kind:String(i.kind??`protected_action`),nextAction:typeof i.next_action==`string`?i.next_action:void 0,summary:String(i.summary??n.message)},status:`gated`};x(t=>({...t,[e.previewId]:a})),h({item:a,kind:`proposal`}),re(l(`feedback.gateRequired`,{summary:a.gate.summary})),e.actionKind===`goal.create`&&e.goalId&&(t.onRefresh?.(),tt(e.goalId));return}let r=n instanceof Th&&py(n.payload),i=n instanceof Th&&n.payload.error_code===`action_response_mismatch`,a={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:r?`refresh`:`repair`,reason:i?`readback_unverified`:r?`stale_proposal`:`apply_failed`,canApply:!1}:void 0,errorMessage:n instanceof Error?n.message:String(n),status:r?`stale`:`error`};x(t=>({...t,[e.previewId]:a})),h({item:a,kind:`proposal`}),re(l(`feedback.executionFailed`,{error:a.errorMessage}))}}let $e={...t,onOpenRunSession:async e=>{e.goalId!==R&&tt(e.goalId),C(`chat`),await t.onOpenRunSession?.(e),y(e),h(null)},onOpenGoal:e=>{tt(e);let n=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>n?.()).catch(()=>{re(l(`feedback.goalRefreshFailed`))})},onOpenGoalView:e=>{C(e),e===`chat`&&y(null),h(null)},onOpenOutput:e=>{e.goalId!==R&&tt(e.goalId),C(`files`),t.onOpenOutput?.(e)},onApplyProposal:Qe,onCancelProposal:async e=>{h(null),x(t=>{let n={...t};return delete n[e.previewId],n});try{t.onCancelProposal?.(e),t.onCancelProposal||await Ph(e.previewId)}catch(t){x(t=>({...t,[e.previewId]:e})),re(l(`feedback.cancelFailed`,{error:t instanceof Error?t.message:String(t)}))}},onTransitionProposal:async(e,t)=>{let n=Dx(await Fh(e.previewId,t),l);le(e=>e.includes(n.previewId)?e:[...e,n.previewId]),x(r=>{let i={...r};return t===`regenerate`&&delete i[e.previewId],i[n.previewId]=n,i}),h({item:n,kind:`proposal`})},onSelectWorkspaceCandidate:async(e,t)=>{e.sourceRequest&&(x(t=>{let n={...t};return delete n[e.previewId],n}),await Ke({...e.sourceRequest,idempotencyKey:`${e.sourceRequest.idempotencyKey}-${t}`,normalizedParameters:{...e.sourceRequest.normalizedParameters,workspace_ref:t}}))},onPreviewAction:Ke,onRequestScheduleConfig:(e,t)=>Ye(e,t),onOpenNotificationSettings:e=>h({goalId:e,kind:`settings`,tab:`lark`}),onFetchNotificationTargets:()=>ig(),onSetupGoalChannel:e=>og(e),onToggleGoalAutoNotify:e=>sg(e),onUpdateSchedule:async(e,t)=>{let n=Date.now().toString(36),r=e.scheduleKind===`heartbeat`;await Ke({actionKind:r?`heartbeat.bind`:`monitor.update`,context:{kind:`schedule`,goal_id:e.goalId},idempotencyKey:`workspace-monitor-${e.scheduleId}-${t}-${n}`,normalizedParameters:{agent_id:e.agentId??De,...!r&&t===`run_now`?{endpoint_id:De}:{},...t===`edit`?{cadence:`2h`,...r?{timezone:e.timezone??`Asia/Shanghai`}:{}}:{},goal_id:e.goalId,operation:t,...!r&&t===`run_now`&&e.sessionId?{session_id:e.sessionId}:{},...r?{}:{todo_id:e.scheduleId}},summary:t===`pause`?`暂停自动运行:${e.label}`:t===`resume`?`恢复自动运行:${e.label}`:t===`run_now`?`立即运行:${e.label}`:t===`stop`?`停止自动运行:${e.label}`:`编辑自动运行生命周期:${e.label}`})}},et=i?{onOpenGoal:$e.onOpenGoal,onOpenGoalView:$e.onOpenGoalView,onOpenOutput:$e.onOpenOutput}:$e;function tt(e){d(e),T(!1),D(!1),ee(!1),y(null),h(null),C(`tasks`),de(!1),t.onSelectGoal?.(e)}function nt(e){p(e),t.onSelectAgent?.(e)}function rt(e){pe(e),px(e)}async function it(n){let r=n?[]:j,i=(n??ke).trim()||(r.length?l(`composer.imageAnalysisPrompt`):``);if(!(!i||k)){n||(je(``),M([])),P(null),A(!0);try{if(r.length){R?S!==`chat`&&ee(!0):D(!0);let e=await t.onSendMessage?.(i,De,R,r);e&&await Ke(e);return}let n=Wy(i,{agents:e.map(e=>({agentId:e.agentId,label:e.label})),goalId:R,todos:(V?.agentTodos??[]).map(e=>({text:e.text,todoId:e.todoId}))});if(n.route===`clarify`){je(i);let e=l(`composer.clarifySingleAction`);n.missingFields.includes(`resume_when`)&&(e=l(`composer.clarifyDefer`)),re(e);return}if(n.actionKind===`goal.create`){let e=jx(i,l),t=Ox(e.title);await Ke({actionKind:`goal.create`,context:{kind:`manager`,goal_id:null,natural_language:i},idempotencyKey:`workspace-goal-intent-${t}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:De,completion_criteria:e.completionCriteria,execution_boundary:e.executionBoundary,goal_id:t,heartbeat:{cadence:Mx(i),enabled:n.normalizedParameters.heartbeat_enabled===!0,timezone:`Asia/Shanghai`},initial_todos:e.initialTodos,objective:e.objective,permission:e.permission,stop_condition:Fx(i),title:e.title,workspace_ref:`current`},summary:l(`proposal.summary.goalCreate`,{title:e.title})});return}if(R&&n.actionKind===`heartbeat.bind`){await Xe(`heartbeat`,R,i);return}if(R&&n.actionKind===`monitor.create`){let e=Nx(i,l);if(e){je(i),re(e);return}await Xe(`monitor`,R,i);return}let a=Ix(i,e);if(R&&a&&n.actionKind===`agent.bind`){await Ke({actionKind:`agent.bind`,context:{kind:`goal`,goal_id:R,natural_language:i},idempotencyKey:`workspace-agent-bind-${R}-${a.agentId}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:a.agentId,goal_id:R},summary:`将 ${a.label} 绑定到 ${V?.title??R}`});return}if(R&&n.actionKind===`todo.create`){if(n.normalizedParameters.start_execution===!0){await Ke({actionKind:`todo.create`,context:{kind:`goal`,goal_id:R,natural_language:i},idempotencyKey:`workspace-task-start-${R}-${Date.now().toString(36)}`,normalizedParameters:{endpoint_id:a?.agentId??De,goal_id:R,start_execution:!0,text:i},summary:`交给 Agent 执行:${i.slice(0,120)}`});return}let e=a?.agentId??(/(交给|分配给|让).{0,24}(agent|codex|claude|kiro|kimi)/iu.test(i)?De:null);await Ke({actionKind:`todo.create`,context:{kind:`goal`,goal_id:R,natural_language:i},idempotencyKey:`workspace-todo-create-${R}-${Date.now().toString(36)}`,normalizedParameters:{...e?{endpoint_id:e}:{},goal_id:R,text:Lx(i)},summary:`创建 Todo:${Lx(i)}`});return}let o=V?.agentTodos.find(e=>i.includes(e.todoId)||i.includes(e.text)),s=typeof n.normalizedParameters.operation==`string`?n.normalizedParameters.operation:null;if(R&&o&&n.actionKind===`todo.update`&&s){await Ke({actionKind:`todo.update`,context:{kind:`todo`,goal_id:R,todo_id:o.todoId,natural_language:i},idempotencyKey:`workspace-todo-update-${o.todoId}-${s}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:De,...s===`reassign`&&a?{endpoint_id:a.agentId}:{},...s===`block`?{note:i}:{},...s===`defer`&&typeof n.normalizedParameters.resume_when==`string`?{resume_when:n.normalizedParameters.resume_when}:{},goal_id:R,operation:s,todo_id:o.todoId},summary:`更新 Todo:${o.text}`});return}R?S!==`chat`&&ee(!0):D(!0);let c=await t.onSendMessage?.(i,De,R);c&&await Ke(c)}catch(e){n||(je(i),M(r));let t=e instanceof Error?e.message:l(`feedback.sendGenericError`);re(l(`feedback.sendFailed`,{error:t}))}finally{A(!1)}}}let at=e.find(e=>e.agentId===De)?.label??De,ot=!V&&ke.startsWith(l(`composer.createGoalDraftLead`)),st=Re.filter(e=>e.kind===`run`&&!!e.run.sessionId&&!!e.run.canInterrupt&&(e.run.status===`running`||e.run.status===`queued`)).length;async function ct(e){if(!e?.length)return;let t=Bx-j.length,n=Array.from(e).slice(0,Math.max(0,t)),r=n.find(e=>!Rx.has(e.type)),i=n.find(e=>e.size>zx);if(t<=0){P(l(`composer.imageCountError`,{count:Bx}));return}if(r){P(l(`composer.imageTypeError`));return}if(i){P(l(`composer.imageSizeError`,{size:zx/1024/1024}));return}try{let t=await Promise.all(n.map(e=>Vx(e,l)));M(e=>[...e,...t].slice(0,Bx)),P(e.length>n.length?l(`composer.imageCountError`,{count:Bx}):null)}catch(e){P(e instanceof Error?e.message:l(`composer.imageReadGenericError`))}finally{Se.current&&(Se.current.value=``)}}function lt(e){let t=Array.from(e.clipboardData.items).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).flatMap(e=>{let t=e.getAsFile();return t?[t]:[]});t.length&&(e.preventDefault(),ct(t))}async function ut(){let e=await qg();_e(e)}async function dt(){await Promise.all([ut(),t.onRefresh?.()])}async function ft(){if(!(!t.onRefresh||oe===`loading`)){se(`loading`);try{await t.onRefresh(),se(`done`)}catch{se(`error`)}window.setTimeout(()=>se(`idle`),1800)}}return Ie?(0,B.jsx)(lx,{focusGoalConnection:!!(m?.kind===`settings`&&m.goalId),goals:Ne,initialGoalId:m?.kind===`settings`?m.goalId??R:R,initialTab:m?.kind===`settings`?m.tab??`lark`:`lark`,onChanged:()=>void dt(),onClose:()=>h(null),onThemeChange:rt,theme:fe}):(0,B.jsx)(mx,{drawer:Ge?(0,B.jsx)($y,{agents:e,attentionHistory:r.attentionHistory??r.userTodos,onSelectAttention:e=>h({kind:`attention`,item:e}),callbacks:et,goalNotifications:r.goalNotifications??[],goals:Ne,inspectorExpanded:g,larkConnections:i?[]:ge,onClose:()=>{Ge.kind===`proposal`&&[`applied`,`rejected`].includes(Ge.item.status)&&(Ge.item.actionKind!==`heartbeat.bind`||Ge.item.status!==`applied`)&&x(e=>{let t={...e};return delete t[Ge.item.previewId],t}),_(!1),h(null)},onToggleInspectorSize:()=>_(e=>!e),readOnly:i,runs:Re.flatMap(e=>e.kind===`run`?[e.run]:[]),selection:Ge}):null,drawerMode:Ge?.kind===`todo`?g?`inspector-full`:`inspector`:`panel`,drawerOpen:Ge!==null,mobileSidebarOpen:ue,onCloseMobileSidebar:()=>de(!1),theme:fe,main:(0,B.jsxs)(`div`,{className:`personal-channel`,children:[(0,B.jsx)(wy,{agents:e,managerChatOpen:w,mobileNavigationOpen:ue,onOpenGoalCapabilities:V?()=>h({goalId:V.goalId,kind:`settings`,tab:`capabilities`}):void 0,onOpenGoalDetail:V&&!V.loadState?()=>h({item:V,kind:`goal`}):void 0,onRefresh:t.onRefresh?()=>void ft():void 0,onOpenNavigation:()=>de(!0),onOpenManagerChat:()=>{D(!1),T(!0)},onSelectGoalTab:e=>{C(e),e===`chat`&&(y(null),ee(!1))},onSelectAgent:nt,onReturnManagerHome:()=>{T(!1),D(!1),window.requestAnimationFrame(()=>xe.current?.scrollTo({behavior:`smooth`,top:0}))},selectedAgentId:De,refreshState:oe,readOnlySourceLabel:i?s?.activeSource.label:void 0,selectedGoal:V,selectedGoalTab:S}),(0,B.jsxs)(`div`,{className:`personal-channel-scroll`,ref:xe,children:[!V&&!w&&Te&&Te.done+Te.failed+Te.attention>0?(0,B.jsxs)(`section`,{className:`personal-digest-card`,"aria-label":l(`digest.away`),children:[(0,B.jsx)(`strong`,{children:l(`digest.away`)}),(0,B.jsxs)(`div`,{className:`personal-digest-stats`,children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`b`,{children:Te.done}),l(`digest.completed`)]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`b`,{children:Te.failed}),l(`digest.failed`)]}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`b`,{children:Te.attention}),l(`digest.needsYou`)]})]})]}):null,!V&&!w?(0,B.jsxs)(`section`,{className:`personal-manager-greeting`,children:[(0,B.jsx)(`span`,{children:(0,B.jsx)(Zp,{size:20})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:l(`home.greeting`)}),(0,B.jsx)(`p`,{children:r.goals.some(e=>e.activationState===`active`&&e.loadState)?l(`startup.partial`):(0,B.jsxs)(B.Fragment,{children:[l(`home.waitingCount`,{count:Pe}),` `,l(`home.blockingSummary`,{count:Fe})]})})]})]}):null,V?.loadState?(0,B.jsx)(`section`,{className:`personal-manager-greeting`,role:`status`,"data-testid":`goal-status-loading`,children:(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:l(V.loadState===`error`?`startup.goalError`:`startup.goalLoading`)}),(0,B.jsx)(`p`,{children:l(V.loadError?`startup.error.${V.loadError}`:`startup.independent`)}),V.loadState===`error`?(0,B.jsx)(`button`,{className:`min-h-11 rounded-md border px-3 py-2 text-sm`,type:`button`,onClick:()=>void t.onRefresh?.(),children:l(`startup.retry`)}):null]})}):V&&S===`tasks`?(0,B.jsx)(Tb,{historyEnabled:!i,goal:V,items:Re,onDraftTaskFromMessage:i?void 0:e=>{je(`创建一个 Task:${hx(e)}`),re(l(`feedback.taskDraftCreated`)),window.requestAnimationFrame(()=>be.current?.focus())},onOpenChat:()=>C(`chat`),onQuickComplete:i?void 0:Ze,onSelect:h,quickCompletingTodoIds:ae,selectedTodoId:Ge?.kind===`todo`?Ge.item.todoId:null,userTodos:r.userTodos}):V&&S===`files`?(0,B.jsx)(yx,{items:Re.filter(e=>e.kind===`output`),onSelect:h,reportState:r.periodicReports}):!V&&!w?(0,B.jsx)(vx,{goals:Ne,onRetry:()=>void t.onRefresh?.(),onSelectGoal:tt,systemHealth:r.systemHealth}):V?(0,B.jsxs)(B.Fragment,{children:[V&&v?.goalId===V.goalId?(0,B.jsx)(xx,{onClose:()=>y(null),onOpenDetails:()=>h({item:v,kind:`run`}),run:v}):null,(0,B.jsx)(Iy,{items:ze,onSelect:h,selectedGoal:V})]}):(0,B.jsx)(Iy,{items:He,onSelect:h,selectedGoal:null})]}),(0,B.jsx)(`div`,{className:`personal-composer-wrap`,children:i?(0,B.jsxs)(`div`,{className:`personal-read-only-notice`,children:[(0,B.jsx)(`strong`,{children:l(`source.readOnlyNoticeTitle`)}),(0,B.jsx)(`span`,{children:l(`source.readOnlyNoticeDescription`)})]}):(0,B.jsxs)(B.Fragment,{children:[!V&&!w&&E&&Be.length?(0,B.jsx)(bx,{messages:Be,onClose:()=>D(!1),onOpenConversation:()=>{D(!1),T(!0)}}):null,V&&S!==`chat`&&O&&Ve.length?(0,B.jsx)(bx,{agentLabel:at,messages:Ve,onClose:()=>ee(!1),onDraftTask:S===`tasks`?e=>{je(`创建一个 Task:${hx(e)}`),re(l(`feedback.taskDraftCreated`)),window.requestAnimationFrame(()=>be.current?.focus())}:void 0,onOpenConversation:()=>{ee(!1),C(`chat`)},title:`${V.title} · ${at}`}):null,F?(0,B.jsxs)(`div`,{className:`personal-action-feedback`,role:`status`,children:[(0,B.jsx)(`span`,{children:F}),(0,B.jsx)(`button`,{"aria-label":l(`common.closeActionReceipt`),onClick:()=>re(null),type:`button`,children:(0,B.jsx)($m,{size:14})})]}):null,(0,B.jsx)(`p`,{className:`personal-composer-hint`,children:V?st>0?l(`composer.goalRunningHint`,{agent:at,count:st}):l(`composer.goalMessageHint`,{agent:at}):l(`composer.managerMessageHint`)}),V?(0,B.jsxs)(`div`,{className:`personal-quick-prompts`,children:[(0,B.jsxs)(`button`,{"aria-label":l(`composer.nextAction`),className:`is-draft`,onClick:()=>Me(l(`composer.nextActionPrompt`)),title:l(`composer.prepareDraft`),type:`button`,children:[(0,B.jsx)(Em,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.nextAction`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]}),(0,B.jsxs)(`button`,{className:`is-immediate`,disabled:k,onClick:()=>void it(l(`composer.agentProgressPrompt`)),title:l(`composer.immediate`),type:`button`,children:[(0,B.jsx)(Bm,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.agentProgress`)}),(0,B.jsx)(`em`,{className:`personal-prompt-badge`,children:l(`composer.immediate`)})]}),(0,B.jsxs)(`button`,{"aria-label":l(`composer.monitor`),className:`is-draft`,onClick:()=>Ye(`monitor`,R),title:l(`composer.monitorHint`),type:`button`,children:[(0,B.jsx)($p,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.monitor`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]})]}):(0,B.jsxs)(`div`,{className:`personal-quick-prompts`,children:[(0,B.jsxs)(`button`,{"aria-label":l(`composer.globalTasks`),className:`is-draft`,onClick:()=>Me(l(`composer.globalTasksPrompt`)),title:l(`composer.prepareDraft`),type:`button`,children:[(0,B.jsx)(Em,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.globalTasks`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]}),(0,B.jsxs)(`button`,{className:`is-immediate`,disabled:k,onClick:()=>void it(l(`composer.globalProgressPrompt`)),title:l(`composer.immediate`),type:`button`,children:[(0,B.jsx)(Bm,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.globalProgress`)}),(0,B.jsx)(`em`,{className:`personal-prompt-badge`,children:l(`composer.immediate`)})]}),(0,B.jsxs)(`button`,{"aria-label":l(`composer.createGoal`),className:`is-draft`,onClick:qe,title:l(`composer.createGoalHint`),type:`button`,children:[(0,B.jsx)(Pm,{size:13}),(0,B.jsx)(`span`,{children:l(`composer.createGoal`)}),(0,B.jsx)(`small`,{className:`personal-prompt-subtle`,children:l(`composer.draft`)})]})]}),ot?(0,B.jsxs)(`div`,{className:`personal-goal-draft-status`,role:`status`,children:[(0,B.jsx)(`strong`,{children:l(`composer.createGoalDraft`)}),(0,B.jsx)(`span`,{children:l(`composer.createGoalDraftDescription`)})]}):null,j.length?(0,B.jsx)(`div`,{className:`personal-composer-images`,"aria-label":l(`composer.imagesPending`),children:j.map(e=>(0,B.jsxs)(`figure`,{children:[(0,B.jsx)(`img`,{alt:e.name,src:e.dataUrl}),(0,B.jsx)(`button`,{"aria-label":l(`composer.sentImageAlt`,{name:e.name}),onClick:()=>M(t=>t.filter(t=>t.id!==e.id)),type:`button`,children:(0,B.jsx)($m,{size:13})})]},e.id))}):null,N?(0,B.jsx)(`p`,{className:`personal-composer-error`,role:`alert`,children:N}):null,(0,B.jsxs)(`div`,{className:`personal-channel-composer`,onDragOver:e=>{[...e.dataTransfer.items].some(e=>e.kind===`file`&&e.type.startsWith(`image/`))&&e.preventDefault()},onDrop:e=>{let t=[...e.dataTransfer.files].filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),ct(t))},children:[(0,B.jsxs)(`span`,{children:[(0,B.jsx)(Zp,{size:17}),e.find(e=>e.agentId===De)?.label??De]}),(0,B.jsx)(`button`,{"aria-label":l(`composer.addImage`),className:`personal-composer-attach`,disabled:k||j.length>=Bx,onClick:()=>Se.current?.click(),title:l(`composer.attachImageHint`),type:`button`,children:(0,B.jsx)(jm,{size:17})}),(0,B.jsx)(`input`,{accept:`image/png,image/jpeg,image/webp,image/gif`,"aria-label":l(`composer.imagePicker`),className:`personal-composer-file-input`,disabled:k||j.length>=Bx,multiple:!0,onChange:e=>void ct(e.target.files),ref:Se,type:`file`}),(0,B.jsx)(`textarea`,{"aria-label":l(`composer.sendMessage`),onChange:e=>je(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),it())},onPaste:lt,placeholder:V?l(`composer.goalPlaceholder`,{goal:V.title}):l(`composer.managerPlaceholder`),ref:be,rows:1,value:ke}),(0,B.jsx)(`button`,{"aria-label":l(ot?`composer.createGoal`:`composer.send`),disabled:!ke.trim()&&j.length===0||k,onClick:()=>void it(),title:l(ot?`composer.createGoalHint`:`composer.sendMessageHint`),type:`button`,children:(0,B.jsx)(Bm,{size:18})})]})]})})]}),sidebar:(0,B.jsx)(xb,{attentionCount:Pe,goals:Ne,goalArchiveLoadState:n,goalLifecycleOperations:t.onExecuteGoalLifecycle?[`stop`,`resume`]:void 0,lifecycleBusyGoalIds:ie,onRequestGoalCreate:i?void 0:qe,onRequestGoalLifecycle:i&&!t.onExecuteGoalLifecycle?void 0:(e,t)=>void Je(e,t),onRetryGoalArchive:t.onRetryGoalArchive||t.onRefresh?()=>void(t.onRetryGoalArchive??t.onRefresh)?.():void 0,onOpenSettings:i?void 0:()=>h({kind:`settings`}),onSelectGoal:tt,selectedGoalId:R,statusSourceControl:s},s?.activeSource.statusUrl??`/status.json`)})}function Ux(e){return(e??``).replace(/\s+/gu,` `).trim()}function Wx(e,t=120){let n=Array.from(e);return n.length<=t?e:`${n.slice(0,t-1).join(``)}…`}function Gx(e,t,n){let r=Ux(e);return!r||r===`暂无`?n?t(n):``:/refresh-state|latest_run|latest run-derived/iu.test(r)?t(`projection.refreshState`):/first read-only adapter tick|read-only adapter/iu.test(r)?t(`projection.firstReadOnlyAdapterCheck`):/todo update recorded for/iu.test(r)?t(`projection.todoStatusUpdated`):/^(loopx|python3|npm|git|run)\s|\s--[a-z0-9-]+|\b[a-z]+_[a-z_]+\b/iu.test(r)?t(n??`projection.agentPreparingNextStep`):Wx(r)}function Kx(e,t){return t({advancing:`projection.agentAdvancingGoal`,idle:`projection.agentIdle`,needs_you:`projection.agentNeedsDecision`,stopped:`projection.agentStopped`,waiting_external:`projection.agentWaitingExternal`}[e])}function qx({eventCount:e,hasArtifact:t,hasLatestValidation:n},r){return{label:r(n?`projection.latestValidation`:`projection.latestRun`),metadata:e>0?r(`projection.events24h`,{count:e}):r(t?`projection.runEvidenceAvailable`:`projection.publicSafeProjection`)}}var Jx=`/status.json`,Yx=`loopx-status-source-catalog-v1`,Xx={id:`local`,kind:`local`,label:`本机`,readOnly:!1,statusUrl:Jx};function Zx(e,t){let n=ih(e,t).source;if(!n||!n.isLoopback||n.isRelative)return{error:`SSH 隧道来源必须使用显式的 localhost、127.0.0.1 或 ::1 URL。`};let r=new URL(n.url,t);return[`http:`,`https:`].includes(r.protocol)?{url:r.toString()}:{error:`状态来源只支持 HTTP 或 HTTPS。`}}function Qx(e){let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619);return`ssh-${(t>>>0).toString(36)}`}function $x(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;if(n.kind!==`ssh_tunnel`||typeof n.label!=`string`||typeof n.statusUrl!=`string`)return null;let r=n.label.trim(),i=Zx(n.statusUrl,t);if(!r||r.length>48||!(`url`in i))return null;let a=db(n.hostAlias)?n.hostAlias.trim():void 0;return{...a?{hostAlias:a}:{},id:Qx(i.url),kind:`ssh_tunnel`,label:r,readOnly:!0,statusUrl:i.url}}function eS(){return{schemaVersion:1,sources:[Xx]}}function tS(e,t){try{let n=e.getItem(Yx);if(!n)return eS();let r=JSON.parse(n);if(r.schemaVersion!==1||!Array.isArray(r.sources))return eS();let i=new Set([Xx.statusUrl]);return{schemaVersion:1,sources:[Xx,...r.sources.flatMap(e=>{let n=$x(e,t);return!n||i.has(n.statusUrl)?[]:(i.add(n.statusUrl),[n])})]}}catch{return eS()}}function nS(e,t){e.setItem(Yx,JSON.stringify({schemaVersion:1,sources:t.sources.filter(e=>e.kind===`ssh_tunnel`)}))}function rS(e,t){let n=new Set(t.filter(db).map(e=>e.trim())),r=!1,i=e.sources.map(e=>e.kind!==`ssh_tunnel`||e.hostAlias||!n.has(e.label)?e:(r=!0,{...e,hostAlias:e.label}));return r?{...e,sources:i}:e}function iS(e,t,n){let r=t.label.trim();if(!r)return{error:`请填写来源名称。`};if(r.length>48)return{error:`来源名称不能超过 48 个字符。`};let i=Zx(t.statusUrl,n);if(!(`url`in i))return i;if(e.sources.some(e=>e.statusUrl===i.url))return{error:`这个状态 URL 已经在来源目录中。`};if(t.hostAlias!==void 0&&!db(t.hostAlias))return{error:`请选择有效的 SSH Host。`};let a=t.hostAlias?.trim(),o={...a?{hostAlias:a}:{},id:Qx(i.url),kind:`ssh_tunnel`,label:r,readOnly:!0,statusUrl:i.url};return{catalog:{...e,sources:[...e.sources,o]},source:o}}function aS(e,t){return{...e,sources:e.sources.filter(e=>e.kind===`local`||e.id!==t)}}function oS(e,t,n){if(!t.trim()||ih(t,n).source?.isRelative)return Xx;let r=t.trim();try{r=new URL(r,n).toString()}catch{return null}return e.sources.find(e=>e.statusUrl===r)??null}function sS(e,t,n){return oS(e,t,n)||(ih(t,n).source?.isRelative?Xx:{id:`temporary`,kind:`ssh_tunnel`,label:`临时来源`,readOnly:!0,statusUrl:t.trim()})}function cS(e,t,n,r){return sS(e,t??n,r)}var lS={delete:`删除`,deploy:`部署`,merge:`合并`,payment:`付款`,release:`发布`};function uS(e,t,n){let r=t.replace(/\s+/gu,` `).trim().toLowerCase(),i=n.target.replace(/\s+/gu,` `).trim().toLowerCase();return!i||!r.includes(i)?null:{actionKind:`goal.update`,context:{goal_id:e,kind:`goal`,natural_language:t,semantic_proposal:{operation:n.operation,target:n.target}},idempotencyKey:`workspace-semantic-protected-${e}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e,status:`operator_gate_requested`},summary:`请求受保护操作:${lS[n.operation]} · ${n.target}`}}var dS=Jx;async function fS(e){let t=await fetch(e,{cache:`no-store`,signal:AbortSignal.timeout(3e4)});if(!t.ok)throw Error(`HTTP ${t.status} while loading ${e}`);return Ep(await t.json())}function pS(e,t){if(t?.controller_readiness?.decision_advisor_ready||t?.controller_readiness?.write_controller_ready)return`controller_ready`;if(t?.controller_readiness)return`controller_gated`;if(t?.human_reward)return`reward_judged`;if(t?.operator_gate?.decision===`approve`)return`operator_approved`;if(t?.operator_gate)return`operator_gated`;let n=e||t?.classification||``;return n===`connected_without_run`?`connected`:n===`read_only_project_map`||t?.project_map?`mapped`:n===`state_refreshed`?`refreshed`:n&&n!==`no_status`?`adapter_inspected`:`registered`}function mS(e,t){let n=new Map(t.map(e=>[e.goal_id,e])),r=new Set,i=e.map(e=>{r.add(e.id);let t=n.get(e.id),i=e.latest_runs[0],a=t?.lifecycle_phase??e.lifecycle_phase??i?.lifecycle_phase??pS(t?.status??i?.classification??e.status,i),o=t?.lifecycle_flags?.length?t.lifecycle_flags:e.lifecycle_flags?.length?e.lifecycle_flags:i?.lifecycle_flags?.length?i.lifecycle_flags:[a];return{goal:e,queueItem:t,latestRun:i,status:t?.status??i?.classification??e.status??`no_status`,waitingOn:t?.waiting_on??`clear`,severity:t?.severity??`clear`,lifecyclePhase:a,lifecycleFlags:o}});for(let e of t)r.has(e.goal_id)||i.push({goal:{activation_state:e.activation_state,id:e.goal_id,status:e.status,display_name:e.goal_id,latest_runs:[],lifecycle_flags:[e.lifecycle_phase??`registered`],registry_member:!0,legacy_runtime_goal:!1,index_exists:!1,raw_index_records:0,unique_runs:0},queueItem:e,status:e.status,waitingOn:e.waiting_on,severity:e.severity,lifecyclePhase:e.lifecycle_phase??`registered`,lifecycleFlags:e.lifecycle_flags??[`registered`]});return i}function hS(e){return(e??``).replace(/\s+/g,` `).trim()}function gS(e,t=132){let n=hS(e);return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function _S(e){let t=new Map;for(let n of e?.goals??[])t.set(n.goal_id,n);return t}function vS(e,t){return e===void 0||t===void 0?void 0:e+t}function yS(e,t){if(!e)return null;let n=t===`user`?e.queueItem?.project_asset?.user_todos:e.queueItem?.project_asset?.agent_todos;if(n?.items?.length)return{done_count:n.done??n.items.filter(e=>e.done).length,items:n.items,open_count:n.open??n.items.filter(e=>!e.done).length,total_count:n.total??n.items.length};let r=t===`user`?e.queueItem?.user_todos:e.queueItem?.agent_todos;return r?.items?.length?r:null}function bS(e){return e?.items.find(e=>!e.done)}function xS(e,t,n=`todos`){return e?.items?.length?{advancement_done_count:e.advancement_done_count??t?.advancement_done_count,done_count:e.done??e.items.filter(e=>e.done).length,items:e.items,open_count:e.open??e.items.filter(e=>!e.done).length,total_count:e.total??e.items.length}:t??null}function SS(e){return e?.queueItem?.project_asset?.quota?.state??e?.queueItem?.quota?.state??e?.goal.quota?.state??`waiting`}function CS(e,t,n){let r=[];for(let t of e){let e=yS(t,`agent`);for(let n of e?.items??[])r.push({goalId:t.goal.id,role:`agent`,todo:n})}let i=new Map;for(let e of r){let t=e.todo.claimed_by||`codex`,n=i.get(t)??[];n.push(e),i.set(t,n)}let a=new Map((n?.agents??[]).map(e=>[e.agent_id,e]));return Array.from(new Set([...i.keys(),...a.keys()])).map(e=>{let t=i.get(e)??[],n=a.get(e),r=Array.from(new Set([...t.map(e=>e.goalId),n?.current_todo?.goal_id,...n?.goal_ids??[]].filter(Boolean))),o=(t.filter(e=>!e.todo.done)[0]??t[0])?.goalId??n?.current_todo?.goal_id??r[0]??``,s=n?.last_activity_at??null;return{agentId:e,claimedTodos:t,currentTodo:n?.current_todo??null,evidenceRefs:[],goalIds:r,handoffNote:null,lastActivity:s,nextSafeAction:n?.next_action?.trim()||`Inspect status projection before taking work`,primaryGoalId:o,quotaHints:[],staleClaimHint:null,status:{label:`可用`,summary:`正常运行`,variant:`success`},workspaceRef:null}})}function wS(e){return e?.map(e=>({dataUrl:e.data_url,id:e.id,mimeType:e.mime_type,name:e.name,size:e.size}))}var TS=`loopx.personal-agent-selection.v1`;function ES(){if(typeof window>`u`)return{};try{let e=JSON.parse(window.localStorage.getItem(TS)??`{}`);return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(e=>typeof e[0]==`string`&&typeof e[1]==`string`))}catch{return{}}}var DS={需修复:`danger`,等你:`warning`,等待条件:`info`,推进中:`success`,安静运行:`neutral`,已停止:`neutral`,已完成:`neutral`};function OS(e,t){return hS(t)||e.replace(/^loopx[-_]/i,`LoopX `).split(/[-_]+/).filter(Boolean).map((e,t)=>t===0?`${e.slice(0,1).toUpperCase()}${e.slice(1)}`:e).join(` `)}function kS(e){return e.split(/\r?\n/u).filter(e=>!/^\s*GOAL_(STATUS|PROGRESS)\s*:/u.test(e)).map(e=>/^\s*GOAL_EVIDENCE\s*:/u.test(e)?e.replace(/^\s*GOAL_EVIDENCE\s*:/u,`验证依据:`):/^\s*NEXT_ACTION\s*:/u.test(e)?e.replace(/^\s*NEXT_ACTION\s*:/u,`下一步:`):e).join(` `).trim()}function AS(e,t){return[`agent`,`assistant`].includes(e.trim().toLowerCase())&&t.trim().length>0}var jS=`已发现的项目 Agent`;function MS(e){switch(cy(e)){case`codex`:return`Codex`;case`claude`:return`Claude Code`;case`kiro`:return`Kiro CLI`;case`trae`:return`Trae CLI Agent`;case`coco`:return`Coco Agent`;default:return OS(e)}}function NS(e,t){switch(ly(e,t)){case`codex`:return`代码与项目执行`;case`claude`:return`复杂分析与长任务`;case`openai`:case`anthropic`:return`管家问答 · 无工具`;case`kiro`:return`终端编码 · 原生 /goal 循环`;case`trae`:return`前端与交互实现`;case`coco`:return`通用任务`;default:return jS}}function PS(e,t){let n=e.project_asset;return t===`user`?xS(n?.user_todos,e.user_todos,`project_asset.user_todos`):xS(n?.agent_todos,e.agent_todos,`project_asset.agent_todos`)}function FS(e){return gS(e.title??e.text,112)}function IS(e){let t=e.resume_condition?.resume_receipt;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t.receipt_id;return typeof n==`string`&&n.trim()?n.trim():null}function LS(e,t){return{resumeWhen:e.resume_when??null,resumeReady:e.resume_ready??null,resumeReceiptId:IS(e),claimedBy:e.claimed_by??null,done:e.status!==`deferred`&&e.done,evidence:e.evidence?gS(e.evidence,96):null,index:e.index,priority:e.priority??null,status:e.status??null,taskClass:e.task_class??null,taskDomain:e.task_domain??null,text:FS(e),todoId:e.todo_id?.trim()||`${t.goal.id}:agent:${e.index}`}}function RS(e){let t=e.queueItem?.agent_todos,n=t?.items??e.queueItem?.project_asset?.agent_todos?.items??[],r=new Map(n.map(t=>[t.todo_id?.trim()||`${e.goal.id}:agent:${t.index}`,t]));for(let n of t?.deferred_items??[]){let t=n.todo_id?.trim()||`${e.goal.id}:agent:${n.index}`;r.has(t)||r.set(t,n)}return[...r.values()]}function zS(e){return RS(e).map(t=>LS(t,e))}function BS(e,t,n){let r=new Map;for(let n of e.todo_index?.items??[]){if(n.goal_id!==t.goal.id||n.role!==`agent`)continue;let e=LS(n,t);r.set(e.todoId,e)}for(let e of n)r.has(e.todoId)||r.set(e.todoId,e);let i=new Map;for(let e of r.values()){if(e.done||e.taskClass!==`advancement_task`)continue;let t=e.taskDomain?.trim();t&&i.set(t,(i.get(t)??0)+1)}return[...i].map(([e,t])=>({domain:e,matchingTodoCount:t}))}function VS(e,t){return{claimedBy:e.claimed_by??null,done:e.status===`done`||e.status===`completed`,index:-1,priority:e.priority??null,status:e.status??null,taskClass:e.task_class??null,text:gS(e.title,112),todoId:e.todo_id?.trim()||`${t.goal.id}:agent:${e.claimed_by??`unknown`}:current`}}function HS(e,t,n){let r=new Map(e.map(e=>[e.todoId,e]));for(let e of t){let t=e.currentTodo;if(!t||t.goal_id!==n.goal.id)continue;let i=VS(t,n);r.has(i.todoId)||r.set(i.todoId,i)}return[...r.values()]}function US(e){let t=e.queueItem?.project_asset?.agent_todos,n=e.queueItem?.agent_todos,r=RS(e),i=t?.advancement_done_count??n?.advancement_done_count??t?.done??n?.done_count??null,a=r.filter(e=>e.done&&e.status!==`deferred`).length,o=Math.max(i??0,a),s=new Set(r.map(e=>e.todo_id?.trim()).filter(e=>!!e)),c=(t?.recent_completed_advancement_items??[]).filter(e=>!e.todo_id?.trim()||!s.has(e.todo_id.trim())).map(t=>LS(t,e)),l=r.find(e=>!e.done);return{doneTodoCount:o,nextTodoText:hS(t?.next??``)||(l?hS(l.title??``)||hS(l.text??``):``)||null,recentCompleted:c}}function WS(e,t){let n=hS(e);return n?/\b(state_file|registry_goal|authority_sources|source_registry)\b|\b[a-z_]+\s+\d+\/\d+/i.test(n)?t(`projection.goalVerified`):Gx(n,t,`projection.validationRecorded`):``}function GS(e,t=4){if(e.length<=t)return e;let n=e.findIndex(e=>!e.done);if(n<0)return e.slice(-t);let r=Math.max(0,Math.min(n-2,e.length-t));return e.slice(r,r+t)}function KS(e,t,n){let r=t.queueItem?.project_asset?.latest_validation,i=t.latestRun,a=e.event_ledger_summary?.goals.find(e=>e.goal_id===t.goal.id);if(!r&&!i&&!a)return null;let o=[WS(r?.summary,n),Gx(i?.health_check,n),Gx(i?.recommended_action,n)].find(e=>e!==``&&e!==`暂无`)??n(`projection.runRecorded`),s=qx({eventCount:a?.events_24h??0,hasArtifact:!!(i?.json_exists||i?.markdown_exists),hasLatestValidation:!!r},n);return{generatedAt:r?.generated_at??i?.generated_at??a?.latest_event_at??``,label:s.label,metadata:s.metadata,runId:i?`${t.goal.id}:${i.generated_at}`:null,safePreview:[o,s.metadata].filter(Boolean).join(` `),summary:o,todoId:t.queueItem?.project_asset?.agent_todos?.items.find(e=>!e.done)?.todo_id??null}}function qS(e){return[e.status,e.goal.status,e.latestRun?.classification,e.lifecyclePhase].filter(Boolean).some(e=>/(^|[_\s-])(done|complete|completed|finished|terminal|closed|success)([_\s-]|$)/i.test(e??``))}function JS(e,t){return e.global_registry?.findings?.find(e=>e.severity===`high`&&(e.goal_id===t.goal.id||e.goal_ids.includes(t.goal.id)))}function YS(e){return[e.status,e.goal.status,e.latestRun?.classification,e.lifecyclePhase].filter(Boolean).some(e=>/(^|[_\s-])(failure|failed|error|broken|unhealthy|blocked[_\s-]?health|health[_\s-]?blocked)([_\s-]|$)/i.test(e??``))}function XS(e,t){let n=t.queueItem?.stale_latest_run_warning;return t.severity===`high`||!!JS(e,t)||!!(n?.requires_refresh_state||n?.severity===`high`)||YS(t)}function ZS(e,t){let n=JS(e,t);return t.queueItem?.stale_latest_run_warning?.recommended_action??t.queueItem?.stale_latest_run_warning?.reason??n?.recommended_action??n?.message??t.queueItem?.recommended_action??t.latestRun?.recommended_action??null}function QS(e){let t=e.latestRun?.operator_gate,n=t?.decision?.trim().toLowerCase()??``,r=new Set([`approve`,`approved`,`reject`,`rejected`,`defer`,`deferred`,`cancel`,`cancelled`]),i=[e.queueItem?.recommended_action,e.latestRun?.recommended_action].filter(Boolean).join(` `),a=/(?:等待|需要)(?:用户|你|owner).{0,24}(?:批准|确认|授权|补充|选择|决定)|(?:批准|确认|授权).{0,16}(?:后|才能|方可)/i.test(i);return!!(t&&!r.has(n))||e.lifecyclePhase===`operator_gated`&&!r.has(n)||a}function $S(e,t){let n=e.latestRun?.operator_gate;return Gx(n?.operator_question??n?.reason_summary??n?.follow_up??e.queueItem?.recommended_action??e.latestRun?.recommended_action,t,`projection.confirmAgentDecision`)}function eC(e,t){if(t.goal.activation_state===`stopped`)return`已停止`;let n=yS(t,`user`),r=yS(t,`agent`),i=!!bS(n),a=!!bS(r);return[`user_or_controller`,`controller`].includes(t.waitingOn)||i||QS(t)?`等你`:XS(e,t)?`需修复`:t.waitingOn===`external_evidence`?`等待条件`:SS(t)===`eligible`||a?`推进中`:qS(t)?`已完成`:`安静运行`}function tC(e,t,n,r){if(n===`已停止`)return Kx(`stopped`,r);if(n===`需修复`)return Gx(ZS(e,t),r,`projection.statusRefreshNeeded`);if(n===`等你`)return Kx(`needs_you`,r);if(n===`推进中`){let e=[(yS(t,`agent`)?.items??[]).filter(e=>!e.done).flatMap(e=>[e.title,e.text]).map(e=>hS(e)).find(e=>e!==``&&e!==`暂无`),t.queueItem?.recommended_action,t.latestRun?.recommended_action].map(e=>hS(e)).find(e=>e!==``&&e!==`暂无`);return e?Gx(e,r,`projection.agentAdvancingGoal`):Kx(`advancing`,r)}return Kx(n===`等待条件`?`waiting_external`:`idle`,r)}function nC(e,t){return t.some(t=>e.includes(t))}function rC(e,t,n){if(t.goals.some(e=>e.activationState===`active`&&e.loadState))return{text:`Goal 状态尚未全部加载,暂不能给出完整统计。可先打开已加载的 Goal,失败项可重试。`,lines:[]};if(nC(n,[`Agent`,`agent`,`推进`,`在做`])){let e=t.goals.filter(e=>![`安静运行`,`已完成`,`已停止`].includes(e.state)),n=(e.length>0?e:t.goals).slice(0,3);return n.length===0?{text:`当前状态里还没有 Goal 可供汇总。`,lines:[]}:{text:e.length>0?`Agent 当前关注这些 Goal:`:`当前 Goal 都比较安静:`,lines:n.map(e=>`${e.title} · ${e.state} · ${e.agentSentence}`)}}if(nC(n,[`现在`,`下一步`,`我该`,`该做什么`,`优先处理`])){let e=t.userTodos[0];if(e)return{text:e.blocking?`先处理「${OS(e.goalId)}」:${e.text}`:`当前最先处理「${OS(e.goalId)}」:${e.text}`,lines:[]};let n=t.goals.find(e=>e.state===`需修复`);if(n)return{text:`没有待办,但这个 Goal 需要先修复。`,lines:[`${n.title} · ${n.agentSentence}`]};let r=t.goals.find(e=>e.state===`推进中`);return r?{text:`目前不需要你介入,Agent 正在推进。`,lines:[`${r.title} · ${r.agentSentence}`]}:{text:`当前系统很安静,没有需要你立即处理的事项。`,lines:[]}}if(nC(n,[`等我`,`阻塞`,`需要我`,`全局待办`]))return t.userTodos.length===0?{text:`目前没有 Goal 在等你,开放用户待办为 0。`,lines:[]}:{text:`有 ${t.userTodos.length} 项开放用户待办,阻塞项优先:`,lines:t.userTodos.slice(0,3).map(e=>`${OS(e.goalId)} · ${e.blocking?`阻塞`:`待处理`} · ${e.text}`)};if(nC(n,[`状态`,`异常`,`修复`,`健康`])){let n=t.systemHealth?!t.systemHealth.ok:!e.ok||!e.contract?.ok||!e.global_registry?.ok||(e.global_registry?.summary?.high??0)>0,r=t.goals.filter(e=>e.state===`需修复`),i=r.slice(0,n?2:3).map(e=>`${e.title} · ${e.agentSentence}`);return n&&i.push(`全局状态、契约或注册表健康检查未通过,请进入管理页检查。`),i.length===0?{text:`当前没有发现 Goal 级或全局健康异常。`,lines:[]}:{text:r.length>0?`当前需要关注这些健康问题:`:`Goal 状态正常,但全局健康需要检查:`,lines:i}}return{text:`当前管家支持三类问题:下一步、等待你的事项、Agent 与健康状态。`,lines:[`问“我现在该做什么?”`,`问“哪些 Goal 在等我?”`,`问“Agent 在做什么?”或当前健康状态`]}}function iC(e,t,n,r=!1){let i=new Map(t.map(e=>[e.goal.id,e])),a=new Set(e.run_history.goals.filter(e=>e.activation_state===`stopped`).map(e=>e.id)),o=_S(e.usage_summary),s=CS(t,e.todo_index,e.agent_management_projection),c=e.attention_queue.items.flatMap((e,t)=>{if(a.has(e.goal_id))return[];let n=[`user_or_controller`,`controller`].includes(e.waiting_on);return(PS(e,`user`)?.items??[]).map((r,i)=>({projectedDone:r.done,details:Ud(r),actionKind:r.action_kind??null,blocking:n,goalId:e.goal_id,sourceOrder:t,taskClass:r.task_class??null,text:FS(r),todoId:r.todo_id?.trim()||`${e.goal_id}:user:${r.index}`,todoOrder:i,updatedAt:r.updated_at??null}))}),l=c.filter(e=>!e.projectedDone),u=new Set(l.map(e=>e.goalId)),d=t.flatMap((t,r)=>a.has(t.goal.id)||u.has(t.goal.id)||!QS(t)?[]:[{details:Ud({task_class:`user_gate`,status:`open`,note:t.latestRun?.operator_gate?.reason_summary}),actionKind:`gate.resolve`,blocking:!0,goalId:t.goal.id,sourceOrder:e.attention_queue.items.length+r,taskClass:`user_gate`,text:$S(t,n),todoId:`${t.goal.id}:operator-gate`,todoOrder:0,updatedAt:t.latestRun?.operator_gate?.recorded_at??t.latestRun?.generated_at??null}]),f=[...l,...d].sort((e,t)=>Number(t.blocking)-Number(e.blocking)||e.sourceOrder-t.sourceOrder||e.todoOrder-t.todoOrder),p=e.run_history.goals.flatMap(t=>{if(t.registry_member===!1)return[];let a=i.get(t.id);if(!a)return[];let c=eC(e,a),l=f.find(e=>e.goalId===t.id),u=l?.text??null,d=US(a),p=t.coordination?.registered_agents??[],m=new Set(p),h=[...s.filter(e=>e.goalIds.includes(t.id)&&!/unassigned|unknown/i.test(e.agentId)&&(m.size===0||m.has(e.agentId))&&(e.currentTodo?.goal_id===t.id||e.claimedTodos.some(e=>e.goalId===t.id)))].sort((e,t)=>(t.lastActivity??``).localeCompare(e.lastActivity??``)),g=new Set(h.map(e=>e.agentId)),_=[...h.map(e=>({agentId:e.agentId,label:e.agentId,lastActivityAt:e.lastActivity,state:e.status.label})),...p.filter(e=>!g.has(e)).map(e=>({agentId:e,label:e,lastActivityAt:null,state:`registered`}))],v=h[0],y=HS(zS(a),h,a),b=[d.nextTodoText,a.queueItem?.recommended_action,a.latestRun?.recommended_action,tC(e,a,c,n)].map(e=>Gx(e,n)).find(e=>e!==``&&e!==`暂无`)??n(`projection.nextUpdatePending`);return[{activationState:t.activation_state,agentId:v?.agentId??p[0]??`codex`,agentLaneCount:_.length,agentLanes:_,agentLabel:v?.agentId,agentSentence:tC(e,a,c,n),agentTodos:[...y,...d.recentCompleted],doneTodoCount:d.doneTodoCount,acceptanceObservation:t.acceptance_observation,goalId:t.id,latestActivity:a.latestRun?.generated_at??``,needsYou:u,needsYouActionKind:l?.actionKind??null,needsYouBlocking:l?.blocking??!1,needsYouTaskClass:l?.taskClass??null,needsYouTodoId:l?.todoId??null,nextSentence:b,runEvidence:KS(e,a,n),state:c,...r?{subagentExecution:{allowedDomains:t.spawn_policy?.allowed_domains??[],domainCandidates:BS(e,a,y),enabled:t.spawn_policy?.mode===`multi_subagent`&&t.spawn_policy.spawn_allowed===!0&&t.spawn_policy.max_children>0,maxChildren:t.spawn_policy?.max_children??0,modelConfig:t.spawn_policy?.model_config}}:{},title:OS(t.id,t.display_name),usage:(()=>{let e=o.get(t.id);return e?{costUsd24h:e.cost_usd_24h,costUsd7d:e.cost_usd_7d,durationMs24h:e.duration_ms_24h,durationMs7d:e.duration_ms_7d,tokens24h:vS(e.input_tokens_24h,e.output_tokens_24h),tokens7d:vS(e.input_tokens_7d,e.output_tokens_7d)}:null})()}]}),m=[];if(e.ok||m.push(`状态载荷未标记为正常 (payload.ok === false)`),e.contract&&!e.contract.ok){let t=e.contract.summary,n=t?`${t.errors} 项错误 / ${t.warnings} 项警告`:e.contract.errors?.[0]||`请检查控制面契约`;m.push(`契约检查未通过: ${n}`)}if(e.global_registry){e.global_registry.ok||m.push(`注册表状态异常: ${e.global_registry.summary.high} 项高危`);for(let t of e.global_registry.findings||[])t.severity===`high`&&m.push(`[${t.kind}] ${t.message}`)}let h=e.decision_freshness_summary?.summary?.stale_count?`${e.decision_freshness_summary.summary.stale_count} 项决策状态已过期`:null,g=m.length===0&&!h,_={ok:g,summary:g?`所有控制面契约与注册表检查均正常`:`发现 ${m.length+ +!!h} 项系统健康关注点`,issues:m,freshnessWarning:h};return{blockingTodoCount:f.filter(e=>e.blocking).length,goalNotifications:(e.goal_channel_notification_projection?.goals??[]).map(e=>({goalId:e.goal_id,configured:e.configured,enabled:e.enabled,humanGateAutoNotifyEnabled:e.human_gate_auto_notify_enabled,lastNotifiedAt:e.last_notified_at??null,receiptCount:e.receipt_count,targetRef:e.target_ref??null})),goals:p,openUserTodoCount:f.length,systemHealth:_,attentionHistory:[...c,...d],userTodos:f,visibleUserTodos:f.slice(0,5),workers:(e.agent_management_projection?.agents??[]).map(e=>({agentId:e.agent_id,currentTodoGoalId:e.current_todo?.goal_id??null,currentTodoText:e.current_todo?.title?gS(e.current_todo.title,96):null,lastActivityAt:e.last_activity_at??null,state:e.state??null}))}}function aC({goalArchiveLoadState:e,isLoading:t,onGoalActivationStateChange:n,onGoalDeleted:r,onSelectGoal:i,onReconcileStatus:a,onRefresh:o,onRetryGoalArchive:s,payload:c,progress:l,rows:u,selectedGoalId:d,statusSourceControl:f,theme:p,toggleTheme:m}){let h=f.activeSource.readOnly,g=f.activeSource.kind===`ssh_tunnel`?f.activeSource.hostAlias:void 0,{t:_}=Ji(),[v,y]=(0,z.useState)([]),[b,x]=(0,z.useState)(!1),S=(0,z.useMemo)(()=>{let e=iC(c,u,_,b);if(!l)return e;let t=Object.values(l.snapshots).map(e=>iC(e,mS(e.run_history.goals,e.attention_queue.items),_,b)),n=new Map(t.flatMap(e=>e.goals).map(e=>[e.goalId,e])),r=e.goals.map(e=>n.get(e.goalId)??{...e,loadError:l.errors[e.goalId],loadState:l.errors[e.goalId]?`error`:`loading`,agentId:``,agentSentence:``,nextSentence:``,subagentExecution:void 0}),i=t.flatMap(e=>e.userTodos),a=r.some(e=>e.activationState===`active`&&e.loadState),o=[...new Set(t.flatMap(e=>e.systemHealth?.issues??[]))];return{...e,goals:r,userTodos:i,attentionHistory:t.flatMap(e=>e.attentionHistory??e.userTodos),visibleUserTodos:i.slice(0,5),openUserTodoCount:i.length,blockingTodoCount:i.filter(e=>e.blocking).length,workers:[...new Map(t.flatMap(e=>e.workers??[]).map(e=>[e.agentId,e])).values()],goalNotifications:t.flatMap(e=>e.goalNotifications??[]),systemHealth:a||t.length===0?void 0:{ok:t.every(e=>e.systemHealth?.ok),issues:o,summary:o.length?`发现 ${o.length} 项系统健康关注点`:`状态检查已完成`,freshnessWarning:t.map(e=>e.systemHealth?.freshnessWarning).filter(Boolean).join(`;`)||null}}},[c,u,l,b,_]),C=S.goals.find(e=>e.goalId===d)??null,w=l?.snapshots[d]??c,[T,E]=(0,z.useState)(null),[D,O]=(0,z.useState)(null),[ee,te]=(0,z.useState)(!1),ne=S.goals.some(e=>e.activationState===`active`&&e.loadState===`loading`)?`loading`:S.goals.map(e=>`${e.goalId}:${e.agentId}`).join(`|`),k=C?.goalId??`manager`;S.goals.some(e=>e.activationState===`active`&&e.loadState)||(S.systemHealth?!S.systemHealth.ok:!c.ok)||S.openUserTodoCount>0&&`${S.openUserTodoCount}${S.blockingTodoCount}`;let A=v.length>0?v.map(e=>({agentId:e.agent_id,adapterKind:e.adapter_kind,available:e.available,capability:NS(e.agent_id,e.adapter_kind),interrupt:e.interrupt,label:e.display_name,location:e.location,resume:e.resume,source:e.source,statusLabel:e.available?`可用`:`需要配置`,streaming:e.streaming,toolCalls:e.tool_calls,trustScope:e.trust_scope})):[{agentId:`codex`,available:!0,capability:NS(`codex`),label:`Codex`,statusLabel:`正在检测`}],j=[...A,{agentId:`status-only`,available:!0,capability:`不调用模型`,adapterKind:`status_projection`,interrupt:!1,label:`仅查状态`,resume:!0,statusLabel:`只读`,streaming:!1,toolCalls:!1,trustScope:`read_only`}],M=A.find(e=>e.label===`Codex`&&e.available)?.agentId??A.find(e=>e.available)?.agentId??`status-only`,[N,P]=(0,z.useState)(ES),F=uh(j,N[k]??M,M),[re,ie]=(0,z.useState)(!1),[I,ae]=(0,z.useState)(!1),[L,oe]=(0,z.useState)(`chat`),[se,ce]=(0,z.useState)(``),[le,ue]=(0,z.useState)({}),[de,fe]=(0,z.useState)({}),[pe,me]=(0,z.useState)(null),[he,ge]=(0,z.useState)({}),[_e,ve]=(0,z.useState)([]),[ye,be]=(0,z.useState)(null),[xe,Se]=(0,z.useState)({}),Ce=(0,z.useRef)(1),we=(0,z.useRef)(1),Te=(0,z.useRef)(new Map),Ee=(0,z.useRef)(new Set),R=(0,z.useRef)(new Map),De=(0,z.useRef)(new Map),Oe=(0,z.useRef)(new Set),ke=(0,z.useRef)(new Set),Ae=(0,z.useRef)(null),je=(0,z.useRef)(null),Me=(0,z.useRef)(null),Ne=(0,z.useRef)(null);(0,z.useRef)(null);let Pe=le[k]??[];de[k];let Fe=C?S.userTodos.filter(e=>e.goalId===C.goalId):S.userTodos,V=C?.agentTodos??[];GS(V,C?.needsYou?3:4);let Ie=V.filter(e=>e.done).length,Le=V.length>0?`${Ie}/${V.length}`:`暂无计划`;C&&({...S},Fe.filter(e=>e.blocking).length,Fe.length),(0,z.useEffect)(()=>{let e=rh(f.activeSource.statusUrl,window.location.href),t=e.source?sh(w,e.source):null;if(!C||!t?.indexUrl||!t.detailUrl){E(null),O(null),te(!1);return}let{detailUrl:n,indexUrl:r}=t,i=!1;return E(null),O(null),te(!0),ch(r,C.goalId).then(async e=>{let t=e.items[0]?.detail_ref;return t?lh(n,t):null}).then(e=>{i||E(e)}).catch(e=>{i||O(Dp(e))}).finally(()=>{i||te(!1)}),()=>{i=!0}},[w,C?.goalId,f.activeSource.statusUrl]);let Re=C?void 0:he[k]?.sessionId;(0,z.useEffect)(()=>{if(h||!Re)return;let e=!1,t,n=async()=>{try{let t=await Bh(Re);if(e)return;let n=t.messages.filter(e=>e.origin===`manager_followup`);ue(e=>{let t=e[k]??[],r=new Set(t.map(e=>e.sourceMessageId)),i=n.filter(e=>!r.has(e.message_id));return i.length?{...e,[k]:[...t,...i.map(e=>({id:Ce.current++,sourceMessageId:e.message_id,role:`assistant`,agentLabel:F.label,sourceLabel:`管家交接回执`,text:kS(e.text),lines:[]}))]}:e})}catch{}finally{e||(t=setTimeout(n,3e3))}};return n(),()=>{e=!0,t&&clearTimeout(t)}},[h,Re,k,F.label]);function ze(e,t){ge(n=>{if(t===null){let t={...n};return delete t[e],t}return{...n,[e]:t}})}(0,z.useEffect)(()=>{if(h){y([]),x(!1);return}let e=!1;return Lh().then(t=>{e||(y(t.adapters??[]),x(t.goal_subagent_configuration===`preview_locked`))}).catch(()=>{e||x(!1)}),()=>{e=!0}},[h]),(0,z.useEffect)(()=>{try{window.localStorage.setItem(TS,JSON.stringify(N))}catch{}},[N]),(0,z.useEffect)(()=>{if(h||!F.available)return;let e=k,t=`${e}:${F.agentId}`,n=C?`goal`:`manager`,r=C?`goal.${C.goalId}`:`manager`,i=!1,a=null,o=null;return(async()=>{try{let s=await Uh({agentId:F.agentId,channelId:r,goalId:C?.goalId});if(i||(ue(t=>(t[e]?.length??0)>0?t:{...t,[e]:s.messages.map(e=>({sourceMessageId:e.message_id,agentLabel:e.role===`user`?void 0:F.label,attachments:wS(e.attachments),id:Ce.current++,lines:[],role:e.role===`user`?`user`:`assistant`,sourceLabel:e.role===`user`?void 0:e.role===`error`?`本地会话记录`:`恢复的 ${F.label} 会话`,text:e.role===`user`?e.text:kS(e.text)}))}),F.agentId===`status-only`))return;let c=s.sessions[0];if(o=c?.session_id??null,c&&!c.resumable){Ee.current.add(t),ze(e,{agentId:F.agentId,resumable:!1,sessionId:c.session_id,status:`resume_failed`});return}let l=n===`manager`?``:C?.goalId??``;if(n===`goal`&&!l)return;let u=await zh(l,F.agentId,`resume_latest`,n);if(i)return;Te.current.set(t,u.session_id);let d=s.snapshots.find(e=>e.session.session_id===u.session_id),f=d?.session.active_turn_id??``;if(ze(e,{agentId:F.agentId,resumable:!0,sessionId:u.session_id,status:f?`running`:`ready`,turnId:f||void 0}),Ee.current.delete(t),!f)return;let p=`${u.session_id}:${f}`;if(ke.current.has(p))return;ke.current.add(p),R.current.set(e,f),ze(e,{agentId:F.agentId,resumable:!0,sessionId:u.session_id,status:`running`,turnId:f}),me(e),a=new AbortController,De.current.set(e,a);let m=``,h=Be(e,{activity:[`正在恢复进行中的 Agent 回合`],agentLabel:F.label,lines:[],pending:!0,sourceLabel:`恢复的 ${F.label} 会话`,text:``});try{let t=await Xh(u.session_id,f,{signal:a.signal,onDelta:t=>{m+=t,Ve(e,h,{text:m})},onActivity:t=>{ue(n=>({...n,[e]:(n[e]??[]).map(e=>e.id===h?{...e,activity:[...new Set([...e.activity??[],t])].slice(-6)}:e)}))}});if(i)return;Ve(e,h,{lines:t.response.gate?[t.response.gate.summary,t.response.gate.next_action].filter(Boolean).slice(0,2):[],pending:!1,text:t.response.message||m.trim()||`${F.label} 已完成分析。`});let n=S.goals.find(e=>e.goalId===d?.session.goal_id)??C??S.goals[0]??null;if(n&&t.response.proposals.length>0){let r=t.response.proposals.map(e=>({goalId:n.goalId,id:we.current++,previewId:null,proposal:e,receiptLabel:null,state:`candidate`,statusMessage:null}));fe(t=>({...t,[e]:[...t[e]??[],...r]}))}}catch(t){if(i)return;Ve(e,h,{activity:[],lines:[],pending:!1,reconnect:t instanceof Th&&t.payload.reconnectable===!0,sourceLabel:`LoopX Chat 本地后端`,text:t instanceof Error?t.message:`无法恢复进行中的 Agent 回合。`})}finally{ke.current.delete(p),R.current.get(e)===f&&R.current.delete(e),ze(e,{agentId:F.agentId,resumable:!0,sessionId:u.session_id,status:`ready`}),De.current.get(e)===a&&De.current.delete(e),i||me(t=>t===e?null:t)}}catch(n){if(i)return;n instanceof Th&&n.payload.error_code===`resume_failed`&&(Ee.current.add(t),o&&ze(e,{agentId:F.agentId,resumable:!1,sessionId:o,status:`resume_failed`}))}})(),()=>{i=!0,a?.abort()}},[k,S.goals[0]?.goalId,h,C?.goalId,F.agentId,F.available,F.label]),(0,z.useEffect)(()=>{if(h||C||S.goals.length===0||ne===`loading`)return;let e=!1;return Promise.all(S.goals.filter(e=>!e.loadState).map(async e=>{let t=await Vh({agentId:e.agentId,channelId:`goal.${e.goalId}`,goalId:e.goalId});return{goalId:e.goalId,session:t.sessions[0]??null}})).then(t=>{e||ge(e=>{let n={...e};for(let e of t)e.session&&(n[e.goalId]={agentId:e.session.agent_id,resumable:e.session.resumable,sessionId:e.session.session_id,status:e.session.active_turn_id?`running`:e.session.status,turnId:e.session.active_turn_id??void 0});return n})}).catch(()=>{}),()=>{e=!0}},[h,ne,C?.goalId]),(0,z.useEffect)(()=>{if(be(null),h){ve([]),Se({});return}if(!C){ve([]),Se({});return}let e=!1,t=0,n=0;ve([]),Se({});let r=async()=>{if(!e){if(document.hidden){t=window.setTimeout(()=>void r(),1e4);return}try{let t=await Vh({goalId:C.goalId});if(!e){let r=t.sessions.filter(e=>e.channel_id?.startsWith(`task.`));ve(r);let i=await Promise.allSettled(r.map(e=>Bh(e.session_id)));if(!e){let e=i.some(e=>e.status===`rejected`);n=e?n+1:0,be(e?`partial`:null),Se(Object.fromEntries(i.flatMap((e,t)=>e.status===`fulfilled`?[[r[t].session_id,e.value]]:[])))}}}catch{n+=1,e||be(`offline`)}e||(t=window.setTimeout(()=>void r(),Math.min(3e4,2e3*2**Math.min(n,4))))}};return r(),()=>{e=!0,window.clearTimeout(t)}},[h,C?.goalId]),(0,z.useEffect)(()=>{if(!re)return;let e=window.requestAnimationFrame(()=>{Ae.current?.querySelector(`[role="menuitem"]:not(:disabled)`)?.focus()});return()=>{window.cancelAnimationFrame(e),je.current?.focus()}},[re]),(0,z.useEffect)(()=>{if(!I)return;let e=window.requestAnimationFrame(()=>Me.current?.focus());return()=>{window.cancelAnimationFrame(e),Ne.current?.focus()}},[I]),(0,z.useEffect)(()=>{if(!re&&!I)return;let e=e=>{e.key===`Escape`&&(ie(!1),ae(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[re,I]);function Be(e,t){let n=Ce.current++;return ue(r=>({...r,[e]:[...r[e]??[],{...t,id:n,role:`assistant`}]})),n}function Ve(e,t,n){ue(r=>({...r,[e]:(r[e]??[]).map(e=>e.id===t?{...e,...n}:e)}))}async function He(e,t){let n=e.trim();if(!n)return;let r=t&&`goalId`in t?t.goalId??`manager`:k,i=r===`manager`?null:S.goals.find(e=>e.goalId===r)??null,a=t?.agentId?uh(j,t.agentId,M):F,o=r===`manager`?S:i?{...S,blockingTodoCount:S.userTodos.filter(e=>e.goalId===i.goalId&&e.blocking).length,goals:[i],openUserTodoCount:S.userTodos.filter(e=>e.goalId===i.goalId).length,userTodos:S.userTodos.filter(e=>e.goalId===i.goalId),visibleUserTodos:S.userTodos.filter(e=>e.goalId===i.goalId)}:S,s=Ce.current++;if(ue(e=>({...e,[r]:[...e[r]??[],{attachments:t?.attachments,id:s,lines:[],role:`user`,text:n}]})),ce(``),me(r),a.agentId===`status-only`||!i&&r!==`manager`){let e=rC(w,o,n),t=a.agentId===`status-only`;Be(r,{agentLabel:t?`仅查状态`:`LoopX 管家`,lines:e.lines.slice(0,3),sourceLabel:t?`LoopX 状态投影 · 仅查状态`:`LoopX 状态投影`,text:e.text}),Rh({answer:[e.text,...e.lines.slice(0,3)].filter(Boolean).join(` `),contextKind:r===`manager`?`manager`:`goal`,goalId:r===`manager`?void 0:r,question:n}).catch(()=>{}),me(null);return}let c=`${r}:${a.agentId}`,l=null;try{let e=Te.current.get(c);if(!e){let t=Ee.current.has(c)?`new`:`resume_latest`;e=(await zh(r===`manager`?``:i.goalId,a.agentId,t,r===`manager`?`manager`:`goal`)).session_id,Te.current.set(c,e),ze(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`ready`}),Ee.current.delete(c)}let o=``;l=Be(r,{activity:[`正在连接 Agent`],agentLabel:a.label,lines:[],pending:!0,sourceLabel:r===`manager`?`${a.label} 管家 · 跨 Goal`:`${a.label} Agent · ${OS(i.goalId)}`,text:``});let s=(await Jh(e,n,{attachments:t?.attachments,signal:(()=>{let e=new AbortController;return De.current.set(r,e),e.signal})(),onDelta:e=>{o+=e,l!==null&&Ve(r,l,{text:o})},onActivity:e=>{l!==null&&ue(t=>({...t,[r]:(t[r]??[]).map(t=>t.id===l?{...t,activity:[...new Set([...t.activity??[],e])].slice(-6)}:t)}))},onPhase:(t,n)=>{R.current.set(r,n),ze(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`running`,turnId:n})}})).response;if(Ve(r,l,{lines:s.gate?[s.gate.summary,s.gate.next_action].filter(Boolean).slice(0,2):[],pending:!1,text:kS(s.message||o.trim())||`${a.label} 已完成分析。`}),s.proposals.length>0&&!i&&Ve(r,l,{lines:[`请进入要修改的 Goal,预览并确认具体变更。`]}),s.proposals.length>0&&i){let e=s.proposals.map(e=>({goalId:i.goalId,id:we.current++,previewId:null,proposal:e,receiptLabel:null,state:`candidate`,statusMessage:null}));fe(t=>({...t,[r]:[...t[r]??[],...e]}))}if(r!==`manager`&&s.protected_action){let e=uS(r,n,s.protected_action);if(e)return e}}catch(e){if(Oe.current.delete(r)){let e={agentLabel:a.label,lines:[],pending:!1,sourceLabel:`${a.label} 会话`,text:`已中断。你可以在当前会话继续发送消息。`};l===null?Be(r,e):Ve(r,l,e);return}let t=e instanceof Th?e.payload:null;t&&dh(t)&&Te.current.delete(c),t?.error_code===`resume_failed`&&(Te.current.delete(c),Ee.current.add(c),ze(r,{agentId:a.agentId,resumable:!1,sessionId:he[r]?.sessionId??`resume-failed`,status:`resume_failed`}));let n=t?.gate,i=n&&typeof n==`object`?String(n.summary??``):``,o={agentLabel:a.label,lines:i?[i]:[],pending:!1,reconnect:t?.reconnectable===!0,sourceLabel:`LoopX Chat 本地后端`,text:t?.error_code===`resume_failed`?`原 ${a.label} 会话无法恢复。本地历史已经保留,请在运行详情里选择“重试恢复”或“开始新 Session”。`:e instanceof Error?e.message:`${a.label} 会话暂时不可用。`};l===null?Be(r,o):Ve(r,l,o)}finally{R.current.delete(r),De.current.delete(r);let e=Te.current.get(c);e&&ze(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`ready`}),me(e=>e===r?null:e)}}async function Ue(e){let t=e?.goalId??k,n=he[t],r=e?.agentId??n?.agentId??F.agentId,i=`${t}:${r}`,a=e?.sessionId??n?.sessionId??Te.current.get(i),o=e?.turnId??n?.turnId??R.current.get(t);if(!(!a||!o))try{Oe.current.add(t),await qh(a,o),De.current.get(t)?.abort()}catch(e){throw Oe.current.delete(t),e}finally{R.current.delete(t),ze(t,{agentId:r,resumable:!0,sessionId:a,status:`ready`}),De.current.delete(t),me(e=>e===t?null:e)}}async function We(e){let t=e.goalId,n=`${t}:${e.agentId}`,r=e.sessionId??he[t]?.sessionId??Te.current.get(n);if(r)try{let i=await Qh(r);Te.current.set(n,r),Ee.current.delete(n),ze(t,{agentId:e.agentId,resumable:i.session.resumable,sessionId:r,status:i.session.status})}catch{ze(t,{agentId:e.agentId,resumable:!1,sessionId:r,status:`resume_failed`})}}function Ge(e){let t=`${e.goalId}:${e.agentId}`;Te.current.delete(t),Ee.current.add(t),ze(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:`new-session-pending`,status:`ready`})}async function Ke(e){let t=`${e.goalId}:${e.agentId}`,n=e.sessionId??he[e.goalId]?.sessionId??Te.current.get(t);n&&n!==`new-session-pending`&&await Zh(n),Te.current.delete(t),Ee.current.add(t),ze(e.goalId,null)}function qe(e){j.some(t=>t.agentId===e&&t.available)&&(P(t=>({...t,[k]:e})),ie(!1))}function Je(){i(``),oe(`chat`)}function Ye(e){i(e),oe(`chat`)}C&&DS[C.state],C&&(`${F.label}${C.state}`,V.length>0&&`${Le}`,Fe.length>0&&`${Fe.length}`),C?.state===`需修复`||!C&&!c.ok?(C&&MS(C.agentId),C?.nextSentence,C?.agentSentence):C?.state===`等你`?(C.needsYouBlocking,C.needsYouBlocking,C.needsYou??C.nextSentence,C.needsYou):(C&&MS(C.agentId),C?.nextSentence);let Xe=[...!C&&he.manager?.status===`resume_failed`?[{id:`run:manager:resume-failed`,kind:`run`,run:{agentId:he.manager.agentId,agentLabel:MS(he.manager.agentId),canInterrupt:!1,completedSteps:0,goalId:`manager`,goalTitle:`LoopX 管家`,latestActivity:`本地聊天记录已保留,点我查看恢复方式。`,resumable:!1,runId:`manager:resume-failed`,sessionId:he.manager.sessionId,sessionStatus:`resume_failed`,status:`failed`,title:`上次会话需要恢复`,totalSteps:1,outputs:[]}}]:[],...C?_e.map(e=>{let t=e.channel_id?.startsWith(`task.`)?e.channel_id.slice(5):void 0,n=C.agentTodos.find(e=>e.todoId===t),r=!!e.active_turn_id,i=xe[e.session_id],a=i?.messages.some(e=>AS(e.role,e.text))===!0;return{id:`run:task:${e.session_id}`,kind:`run`,run:{agentId:e.agent_id,agentLabel:MS(e.agent_id),canInterrupt:r,completedSteps:n?.done||a?1:0,goalId:C.goalId,goalTitle:C.title,latestActivity:r?`Agent 正在执行,可进入 Session 查看过程或发送纠偏。`:a?`Agent 已返回结果,点击查看结果与完整运行记录。`:`执行 Session 已保留,可继续纠偏或恢复。`,resumable:e.resumable,runId:e.session_id,sessionId:e.session_id,sessionMessages:i?.messages.map(e=>({createdAt:e.created_at,messageId:e.message_id,role:e.role===`user`?`user`:AS(e.role,e.text)?`assistant`:`error`,text:e.role===`user`?e.text:kS(e.text)})),sessionStatus:a?`completed`:e.status,status:n?.done||a?`completed`:r?`running`:e.status===`resume_failed`?`failed`:`waiting`,title:n?.text??`Agent 执行任务`,todoId:t,totalSteps:1,turnId:e.active_turn_id??void 0}}}):[],...C?[{id:`run:${C.goalId}`,kind:`run`,run:{agentId:he[C.goalId]?.agentId??C.agentId,agentLabel:MS(he[C.goalId]?.agentId??C.agentId),canInterrupt:!!he[C.goalId]?.turnId,completedSteps:C.agentTodos.filter(e=>e.done).length,goalId:C.goalId,goalTitle:C.title,latestActivity:C.agentSentence,resumable:he[C.goalId]?.resumable??!0,runId:`goal:${C.goalId}`,sessionId:he[C.goalId]?.sessionId,sessionStatus:he[C.goalId]?.status,status:he[C.goalId]?.turnId?`running`:C.state===`需修复`?`failed`:`waiting`,title:C.nextSentence,totalSteps:C.agentTodos.length||1,turnId:he[C.goalId]?.turnId,outputs:C.runEvidence?[{createdAt:C.runEvidence.generatedAt,kind:`evidence`,outputId:`${C.goalId}:latest-evidence`,title:C.runEvidence.label}]:[]}}]:[],...Pe.map(e=>({id:`message:${e.id}`,kind:`message`,message:{agentLabel:e.agentLabel,attachments:e.attachments,id:String(e.id),pending:e.pending,role:e.role,text:e.text||(e.pending?`Agent 正在处理…`:e.lines.join(` diff --git a/loopx/web/chat/index.html b/loopx/web/chat/index.html index e651dc2dfa..dd72ad8753 100644 --- a/loopx/web/chat/index.html +++ b/loopx/web/chat/index.html @@ -18,7 +18,7 @@ content="LoopX 个人 Agent 工作区:在同一个频道里查看、纠偏并推进 Goal。" /> LoopX 个人 Agent 工作区 - + From 355d2eb846a71b2fa96a908893e2c5ef42a9fcb0 Mon Sep 17 00:00:00 2001 From: huangruiteng <14976749+huangruiteng@users.noreply.github.com> Date: Mon, 14 Sep 2026 02:59:00 +0800 Subject: [PATCH 7/9] chore(dashboard): normalize retained asset order Signed-off-by: huangruiteng <14976749+huangruiteng@users.noreply.github.com> --- loopx/web/chat/asset-retention.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/loopx/web/chat/asset-retention.json b/loopx/web/chat/asset-retention.json index be817d91ab..448bc32127 100644 --- a/loopx/web/chat/asset-retention.json +++ b/loopx/web/chat/asset-retention.json @@ -28,8 +28,8 @@ "assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2", "assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2", "assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2", - "assets/index-B7B_kVDP.css", - "assets/index-8CALBIjN.js" + "assets/index-8CALBIjN.js", + "assets/index-B7B_kVDP.css" ] ] } From 59a90fffe0925a9bc6268df58a0668e43830564f Mon Sep 17 00:00:00 2001 From: huangruiteng <14976749+huangruiteng@users.noreply.github.com> Date: Mon, 14 Sep 2026 03:05:46 +0800 Subject: [PATCH 8/9] docs(lark): clarify periodic route authority Signed-off-by: huangruiteng <14976749+huangruiteng@users.noreply.github.com> --- .../reference/protocols/periodic-report-v0.md | 29 ++++++++++++++----- .../test_lark_goal_channel_operation.py | 25 ++++++++++++++++ 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/docs/reference/protocols/periodic-report-v0.md b/docs/reference/protocols/periodic-report-v0.md index 31ab63f093..b5a95f6dd2 100644 --- a/docs/reference/protocols/periodic-report-v0.md +++ b/docs/reference/protocols/periodic-report-v0.md @@ -244,18 +244,33 @@ history read fails closed; the provider's stable one-hour idempotency key covers the remaining concurrent-send race. That provider key is versioned and bound to the final announcement kind, title, body, and footer, so a renderer change after an interrupted send cannot return an older, semantically different card under -the new retry. The command does not accept a chat, profile, -App identity, or sender override. Instead, -the Lark extension resolves the current Goal's local-private Goal Channel -binding and requires `mode=project_bot`, Bot sender identity, a non-default -profile, exact Bot App id and display name, and an enabled Lark channel. +the new retry. The command does not accept a chat, profile, App identity, or +sender override. Its route authority has two explicit, non-interchangeable +forms. When the Goal has a durable Goal Channel binding, that binding's +`target_ref` must match the effective periodic-report subscription. When no +Goal Channel binding exists, an enabled effective `periodic_report` +subscription with an explicit `route_ref` is the independent standing +authority, and the named target registry entry supplies the project-Bot route. +This unbound path constructs only an adapter-local resolved route; it neither +creates a durable Goal Channel binding nor authorizes `operation.execute` or +another Goal Channel producer. Both forms require `mode=project_bot`, Bot +sender identity, a non-default profile, exact Bot App id and display name, and +an enabled Lark channel. Before sending, it live-verifies that the bound profile authenticates as the same Bot App and can reach the same chat. After sending, it reads back the exact interactive card from that chat and requires the provider-native message sender to be an `app` whose id equals the bound Bot App id. Revalidating the profile alone is not sender proof. -Missing bindings, local-user mode, identity drift, or incomplete readback fail -closed; no environment-default or user-identity fallback exists. +Missing route authority, local-user mode, identity drift, or incomplete +readback fail closed; no environment-default or user-identity fallback exists. + +路由授权只有两种显式且不可混用的来源:若 Goal 已存在持久化 Goal Channel +binding,其 `target_ref` 必须与当前生效的周期报告订阅一致;若不存在 binding, +则必须由已启用且显式配置 `route_ref` 的 `periodic_report` 订阅提供独立的持续授权, +并从具名 target registry 解析 project Bot 路由。后一条路径只生成适配器内存中的 +resolved route,不会写入 Goal Channel binding,也不能授权 `operation.execute` 或 +其他 Goal Channel producer。缺少上述任一授权、使用本地用户身份、身份漂移或 +读回不完整时都必须在写入前关闭失败;环境变量默认路由和用户身份都不能兜底。 The governed pending-intent consumer persists the normalized generation bundle and writes one runnable, agent-owned delivery successor. The current effective diff --git a/tests/extensions/test_lark_goal_channel_operation.py b/tests/extensions/test_lark_goal_channel_operation.py index 76e638b458..f863faf44c 100644 --- a/tests/extensions/test_lark_goal_channel_operation.py +++ b/tests/extensions/test_lark_goal_channel_operation.py @@ -406,6 +406,31 @@ def test_delivery_stops_before_provider_write_when_executor_revision_drifted( assert calls == [] +def test_operation_delivery_never_uses_an_unbound_registered_target( + tmp_path: Path, +) -> None: + store, registry, runtime, binding, target = _fixture(tmp_path) + proposal = _prepare(store, registry) + binding.unlink() + calls: list[list[str]] = [] + + with pytest.raises(ValueError, match="durable binding"): + deliver_goal_channel_operation_card( + proposal_id=proposal["proposal_id"], + action_store_root=store.root, + runtime_root=runtime, + binding_path=binding, + target_path=target, + execute=True, + runner=_runner(calls, {}), + executor_binding_resolver=lambda _parameters, _runtime: { + "revision": "simulator-v0" + }, + ) + + assert calls == [] + + def test_delivery_callback_simulation_and_replay_share_one_claim( tmp_path: Path, ) -> None: From 868fa91692cdbb026ad727812f6106456a2f60d7 Mon Sep 17 00:00:00 2001 From: huangruiteng <14976749+huangruiteng@users.noreply.github.com> Date: Mon, 14 Sep 2026 03:29:26 +0800 Subject: [PATCH 9/9] refactor(chat): split typed action normalization Signed-off-by: huangruiteng <14976749+huangruiteng@users.noreply.github.com> --- loopx/chat_action_normalization.py | 626 +++++++++++++++++++++++++++++ loopx/chat_actions.py | 608 +--------------------------- 2 files changed, 632 insertions(+), 602 deletions(-) create mode 100644 loopx/chat_action_normalization.py diff --git a/loopx/chat_action_normalization.py b/loopx/chat_action_normalization.py new file mode 100644 index 0000000000..ea8fc17ab1 --- /dev/null +++ b/loopx/chat_action_normalization.py @@ -0,0 +1,626 @@ +"""Normalization owner for built-in typed Chat actions.""" + +from __future__ import annotations + +from datetime import timedelta +import re +from typing import Any, Mapping + +from .agent_registry import registered_agent_ids_for_goal +from .control_plane.runtime.time import now_utc, parse_timestamp, utc_isoformat +from .control_plane.todos.contract import require_supported_todo_resume_when +from .registry import registry_goals + + +_SHA256 = re.compile(r"^[0-9a-f]{64}$") +_AUTHORITY_PRINCIPAL = re.compile(r"^[a-z][a-z0-9._-]{0,30}:[A-Za-z0-9._:-]{1,200}$") + + +class ChatActionNormalizationMixin: + """Normalize typed action inputs without owning effects or persistence.""" + + def _normalize( + self, action_kind: str, parameters: Mapping[str, Any] + ) -> dict[str, Any]: + # Imported lazily to retain the compatibility helpers in chat_actions + # without introducing a module initialization cycle. + from .chat_actions import ( + ProtectedActionGate, + _digest, + _normalize_cadence, + _opaque, + _text, + ) + + if action_kind == "operation.execute": + values = self._allowed_parameters( + parameters, + allowed={ + "schema_version", + "goal_id", + "agent_id", + "domain", + "operation_kind", + "operation_schema", + "payload_ref", + "payload", + "payload_digest", + "projection", + "destination_account_ref", + "expires_at", + "authorized_principals", + "executor", + }, + ) + if values.get("schema_version") != "loopx_operation_request_v0": + raise ValueError( + "operation.execute requires loopx_operation_request_v0" + ) + goal_id = _opaque(values.get("goal_id"), field="goal_id") + goal = self._goal(goal_id) + agent_id = _opaque(values.get("agent_id"), field="agent_id") + if agent_id not in registered_agent_ids_for_goal(goal): + raise ValueError("operation agent_id must be registered for the Goal") + payload = values.get("payload") + if not isinstance(payload, Mapping): + raise ValueError("operation payload must be an object") + payload_digest = str(values.get("payload_digest") or "").strip() + if not _SHA256.fullmatch(payload_digest): + raise ValueError("operation payload_digest must be lowercase SHA-256") + if _digest(payload) != payload_digest: + raise ValueError("operation payload_digest does not match payload") + + projection = values.get("projection") + if not isinstance(projection, Mapping): + raise ValueError("operation projection must be an object") + projection_values = self._allowed_parameters( + projection, + allowed={ + "schema_version", + "title", + "subtitle", + "focus", + "fields", + "warning", + "simulated", + }, + ) + if ( + projection_values.get("schema_version") + != "loopx_operation_projection_v0" + ): + raise ValueError( + "operation projection requires loopx_operation_projection_v0" + ) + normalized_projection: dict[str, Any] = { + "schema_version": "loopx_operation_projection_v0", + "title": _text( + projection_values.get("title"), + field="projection.title", + limit=80, + ), + "subtitle": _text( + projection_values.get("subtitle"), + field="projection.subtitle", + limit=120, + ), + "focus": _text( + projection_values.get("focus"), + field="projection.focus", + limit=120, + ), + "warning": _text( + projection_values.get("warning"), + field="projection.warning", + limit=300, + ), + } + if not isinstance(projection_values.get("simulated"), bool): + raise ValueError("operation projection simulated must be true or false") + normalized_projection["simulated"] = projection_values["simulated"] + raw_fields = projection_values.get("fields") + if not isinstance(raw_fields, list) or not 1 <= len(raw_fields) <= 12: + raise ValueError("operation projection fields must contain 1-12 items") + normalized_fields: list[dict[str, str]] = [] + for index, raw_field in enumerate(raw_fields): + if not isinstance(raw_field, Mapping) or set(raw_field) != { + "label", + "value", + }: + raise ValueError( + f"operation projection field {index + 1} is invalid" + ) + normalized_fields.append( + { + "label": _text( + raw_field.get("label"), + field=f"projection.fields[{index}].label", + limit=40, + ), + "value": _text( + raw_field.get("value"), + field=f"projection.fields[{index}].value", + limit=120, + ), + } + ) + normalized_projection["fields"] = normalized_fields + + raw_executor = values.get("executor") + if not isinstance(raw_executor, Mapping) or set(raw_executor) != { + "extension_id", + "protocol", + "permission", + "revision", + }: + raise ValueError("operation executor binding is invalid") + executor = { + field: _opaque(raw_executor.get(field), field=f"executor.{field}") + for field in ( + "extension_id", + "protocol", + "permission", + "revision", + ) + } + expires_at = parse_timestamp( + _text(values.get("expires_at"), field="expires_at", limit=80) + ) + if expires_at is None: + raise ValueError("operation expires_at must be an ISO-8601 timestamp") + current = now_utc() + if not current < expires_at <= current + timedelta(days=7): + raise ValueError("operation expiry must be within the next seven days") + raw_principals = values.get("authorized_principals") + if ( + not isinstance(raw_principals, list) + or not 1 <= len(raw_principals) <= 20 + ): + raise ValueError( + "operation authorized_principals must contain 1-20 identities" + ) + principals: list[str] = [] + for raw_principal in raw_principals: + principal = str(raw_principal or "").strip() + if not _AUTHORITY_PRINCIPAL.fullmatch(principal): + raise ValueError( + "operation authorized_principals must use provider:subject values" + ) + if principal not in principals: + principals.append(principal) + return { + "schema_version": "loopx_operation_request_v0", + "goal_id": goal_id, + "agent_id": agent_id, + "domain": _opaque(values.get("domain"), field="domain"), + "operation_kind": _opaque( + values.get("operation_kind"), field="operation_kind" + ), + "operation_schema": _opaque( + values.get("operation_schema"), field="operation_schema" + ), + "payload_ref": _opaque(values.get("payload_ref"), field="payload_ref"), + "payload": dict(payload), + "payload_digest": payload_digest, + "projection": normalized_projection, + "projection_digest": _digest(normalized_projection), + "destination_account_ref": _opaque( + values.get("destination_account_ref"), + field="destination_account_ref", + ), + "expires_at": utc_isoformat(expires_at), + "authorized_principals": principals, + "executor": executor, + } + if action_kind == "todo.create": + values = self._allowed_parameters( + parameters, + allowed={ + "goal_id", + "text", + "agent_id", + "endpoint_id", + "start_execution", + }, + ) + goal_id = _opaque(values.get("goal_id"), field="goal_id") + self._goal(goal_id) + result = { + "goal_id": goal_id, + "text": _text(values.get("text"), field="text", limit=400), + } + if values.get("endpoint_id"): + endpoint_id = _opaque(values.get("endpoint_id"), field="endpoint_id") + result["endpoint_id"] = endpoint_id + result["agent_id"] = self._resolve_goal_agent(goal_id, endpoint_id) + elif values.get("agent_id"): + agent_id = _opaque(values.get("agent_id"), field="agent_id") + if agent_id not in registered_agent_ids_for_goal(self._goal(goal_id)): + raise ProtectedActionGate( + "agent.bind", + gate={ + "kind": "agent_binding_required", + "summary": "所选 Agent 身份尚未绑定到这个 Goal。", + "next_action": "先确认 Agent 绑定预览,再继续创建 Todo。", + "agent_id": agent_id, + "goal_id": goal_id, + }, + ) + result["agent_id"] = agent_id + if values.get("start_execution") is not None: + if not isinstance(values["start_execution"], bool): + raise ValueError("start_execution must be true or false") + result["start_execution"] = values["start_execution"] + if result.get("start_execution") and not result.get("agent_id"): + raise ValueError("start_execution requires an assigned Agent") + return result + if action_kind == "todo.update": + values = self._allowed_parameters( + parameters, + allowed={ + "goal_id", + "todo_id", + "text", + "status", + "note", + "agent_id", + "endpoint_id", + "operation", + "resume_when", + "successor_todo_ids", + "no_followup", + }, + ) + goal_id = _opaque(values.get("goal_id"), field="goal_id") + self._goal(goal_id) + result: dict[str, Any] = { + "goal_id": goal_id, + "todo_id": _opaque(values.get("todo_id"), field="todo_id"), + } + operation = str(values.get("operation") or "edit").strip().lower() + if operation not in { + "edit", + "reassign", + "block", + "defer", + "complete", + "successor", + }: + raise ValueError( + "todo.update operation must be edit, reassign, block, defer, complete, or successor" + ) + result["operation"] = operation + if values.get("text"): + result["text"] = _text(values["text"], field="text", limit=400) + if values.get("status"): + status = str(values["status"]).strip().lower() + if status not in {"open", "blocked", "deferred"}: + raise ValueError( + "todo.update status must be open, blocked, or deferred" + ) + result["status"] = status + if values.get("note"): + result["note"] = _text(values["note"], field="note", limit=600) + if values.get("endpoint_id"): + endpoint_id = _opaque(values["endpoint_id"], field="endpoint_id") + result["endpoint_id"] = endpoint_id + result["agent_id"] = self._resolve_goal_agent(goal_id, endpoint_id) + elif values.get("agent_id"): + result["agent_id"] = _opaque(values["agent_id"], field="agent_id") + if values.get("resume_when"): + result["resume_when"] = require_supported_todo_resume_when( + _text(values["resume_when"], field="resume_when", limit=240) + ) + if values.get("successor_todo_ids") is not None: + if not isinstance(values["successor_todo_ids"], list): + raise ValueError("successor_todo_ids must be a list") + result["successor_todo_ids"] = [ + _opaque(item, field="successor_todo_ids") + for item in values["successor_todo_ids"][:20] + ] + if values.get("no_followup") is not None: + if not isinstance(values["no_followup"], bool): + raise ValueError("no_followup must be true or false") + result["no_followup"] = values["no_followup"] + required_by_operation = { + "reassign": "agent_id", + "defer": "resume_when", + "successor": "successor_todo_ids", + } + required = required_by_operation.get(operation) + if required and not result.get(required): + raise ValueError(f"todo.update {operation} requires {required}") + if operation == "block" and not result.get("note"): + raise ValueError("todo.update block requires note") + if operation == "edit" and len(result) == 3: + raise ValueError("todo.update requires text, status, or note") + return result + if action_kind == "run.correct": + values = self._allowed_parameters( + parameters, + allowed={"goal_id", "session_id", "message", "client_turn_id"}, + ) + goal_id = _opaque(values.get("goal_id"), field="goal_id") + self._goal(goal_id) + session_id = _opaque(values.get("session_id"), field="session_id") + client_turn_id = values.get("client_turn_id") + normalized = { + "goal_id": goal_id, + "session_id": session_id, + "message": _text(values.get("message"), field="message", limit=4000), + } + if client_turn_id: + normalized["client_turn_id"] = _opaque( + client_turn_id, field="client_turn_id" + ) + return normalized + if action_kind == "goal.create": + values = self._allowed_parameters( + parameters, + allowed={ + "goal_id", + "title", + "objective", + "completion_criteria", + "execution_boundary", + "agent_id", + "workspace_ref", + "permission", + "heartbeat", + "stop_condition", + "initial_todos", + }, + ) + goal_id = _opaque(values.get("goal_id"), field="goal_id") + if any( + str(goal.get("id") or "") == goal_id + for goal in registry_goals(self._registry()) + ): + raise ValueError("goal_id already exists in the active LoopX registry") + result: dict[str, Any] = { + "goal_id": goal_id, + "title": _text(values.get("title"), field="title", limit=200), + } + for field in ( + "objective", + "completion_criteria", + "execution_boundary", + "permission", + "stop_condition", + ): + if values.get(field): + result[field] = _text(values[field], field=field, limit=1000) + for field in ("agent_id", "workspace_ref"): + if values.get(field): + result[field] = _opaque(values[field], field=field) + if result.get("agent_id"): + self._agent_eligibility(str(result["agent_id"])) + if values.get("heartbeat") is not None: + if not isinstance(values["heartbeat"], Mapping): + raise ValueError("heartbeat must be an object") + heartbeat = self._allowed_parameters( + values["heartbeat"], allowed={"enabled", "cadence", "timezone"} + ) + enabled = heartbeat.get("enabled") + if not isinstance(enabled, bool): + raise ValueError("heartbeat.enabled must be true or false") + normalized_heartbeat: dict[str, Any] = {"enabled": enabled} + if heartbeat.get("cadence"): + normalized_heartbeat["cadence"] = _normalize_cadence( + heartbeat["cadence"] + ) + if heartbeat.get("timezone"): + normalized_heartbeat["timezone"] = _text( + heartbeat["timezone"], field="heartbeat.timezone", limit=80 + ) + result["heartbeat"] = normalized_heartbeat + if values.get("initial_todos") is not None: + if not isinstance(values["initial_todos"], list): + raise ValueError("initial_todos must be a list") + result["initial_todos"] = [ + _text(item, field="initial_todos", limit=400) + for item in values["initial_todos"][:20] + ] + return result + if action_kind == "goal.update": + values = self._allowed_parameters( + parameters, + allowed={"goal_id", "title", "objective", "status", "write_scope"}, + ) + goal_id = _opaque(values.get("goal_id"), field="goal_id") + self._goal(goal_id) + result = {"goal_id": goal_id} + for field in ("title", "objective", "status"): + if values.get(field): + result[field] = _text(values[field], field=field, limit=1000) + if values.get("write_scope") is not None: + if not isinstance(values["write_scope"], list): + raise ValueError("write_scope must be a list") + result["write_scope"] = [ + _text(item, field="write_scope", limit=160) + for item in values["write_scope"][:20] + ] + if len(result) == 1: + raise ValueError("goal.update requires at least one change") + return result + if action_kind == "goal.lifecycle": + return self._normalize_goal_lifecycle(parameters) + if action_kind == "agent.bind": + values = self._allowed_parameters( + parameters, allowed={"goal_id", "agent_id"} + ) + goal_id = _opaque(values.get("goal_id"), field="goal_id") + self._goal(goal_id) + agent_id = _opaque(values.get("agent_id"), field="agent_id") + self._agent_eligibility(agent_id) + return { + "goal_id": goal_id, + "agent_id": agent_id, + } + if action_kind == "heartbeat.bind": + values = self._allowed_parameters( + parameters, + allowed={ + "goal_id", + "agent_id", + "cadence", + "timezone", + "stop_condition", + "notification_policy", + "operation", + }, + ) + goal_id = _opaque(values.get("goal_id"), field="goal_id") + self._goal(goal_id) + operation = str(values.get("operation") or "bind").strip().lower() + if operation not in {"bind", "edit", "pause", "resume", "stop"}: + raise ValueError( + "heartbeat operation must be bind, edit, pause, resume, or stop" + ) + agent_id = _opaque(values.get("agent_id"), field="agent_id") + self._agent_eligibility(agent_id) + result: dict[str, Any] = { + "goal_id": goal_id, + "agent_id": agent_id, + "operation": operation, + } + if values.get("cadence"): + result["cadence"] = _normalize_cadence(values["cadence"]) + if values.get("timezone"): + result["timezone"] = _text( + values["timezone"], field="timezone", limit=80 + ) + if values.get("stop_condition"): + result["stop_condition"] = _text( + values["stop_condition"], field="stop_condition", limit=160 + ).lower() + if values.get("notification_policy"): + result["notification_policy"] = _opaque( + values["notification_policy"], field="notification_policy" + ) + if operation == "bind" and not all( + result.get(field) for field in ("cadence", "timezone", "stop_condition") + ): + raise ValueError( + "heartbeat bind requires cadence, timezone, and stop_condition" + ) + if operation == "edit" and len(result) == 3: + raise ValueError("heartbeat edit requires a configuration change") + return result + if action_kind == "monitor.create": + values = self._allowed_parameters( + parameters, + allowed={ + "goal_id", + "agent_id", + "target", + "target_key", + "cadence", + "timezone", + "stop_condition", + "notification_rule", + }, + ) + goal_id = _opaque(values.get("goal_id"), field="goal_id") + self._goal(goal_id) + result = { + "goal_id": goal_id, + "agent_id": _opaque(values.get("agent_id"), field="agent_id"), + "target": _text(values.get("target"), field="target", limit=400), + "target_key": _opaque(values.get("target_key"), field="target_key"), + "cadence": _normalize_cadence(values.get("cadence")), + "timezone": _text(values.get("timezone"), field="timezone", limit=80), + } + stop_cond_raw = values.get("stop_condition") + if stop_cond_raw: + raw_text = _text(stop_cond_raw, field="stop_condition", limit=160) + parsed_ts = parse_timestamp(raw_text) + result["stop_condition"] = ( + utc_isoformat(parsed_ts) + if parsed_ts is not None + else raw_text.lower() + ) + if values.get("notification_rule"): + result["notification_rule"] = _text( + values["notification_rule"], field="notification_rule", limit=400 + ) + return result + if action_kind == "monitor.update": + values = self._allowed_parameters( + parameters, + allowed={ + "goal_id", + "todo_id", + "agent_id", + "operation", + "target", + "target_key", + "cadence", + "stop_condition", + "session_id", + "endpoint_id", + }, + ) + goal_id = _opaque(values.get("goal_id"), field="goal_id") + self._goal(goal_id) + operation = str(values.get("operation") or "").strip().lower() + if operation not in {"pause", "resume", "stop", "run_now", "edit"}: + raise ValueError( + "monitor.update operation must be pause, resume, stop, run_now, or edit" + ) + result = { + "goal_id": goal_id, + "todo_id": _opaque(values.get("todo_id"), field="todo_id"), + "agent_id": _opaque(values.get("agent_id"), field="agent_id"), + "operation": operation, + } + if values.get("endpoint_id"): + endpoint_id = _opaque(values["endpoint_id"], field="endpoint_id") + result["endpoint_id"] = endpoint_id + result["agent_id"] = self._resolve_goal_agent(goal_id, endpoint_id) + if values.get("target"): + result["target"] = _text(values["target"], field="target", limit=400) + if values.get("target_key"): + result["target_key"] = _opaque(values["target_key"], field="target_key") + if values.get("cadence"): + result["cadence"] = _normalize_cadence(values["cadence"]) + if values.get("stop_condition"): + raw_stop = _text( + values["stop_condition"], field="stop_condition", limit=160 + ) + parsed_ts = parse_timestamp(raw_stop) + result["stop_condition"] = ( + utc_isoformat(parsed_ts) + if parsed_ts is not None + else raw_stop.lower() + ) + if values.get("session_id"): + result["session_id"] = _opaque(values["session_id"], field="session_id") + if operation == "edit" and len(result) == 4: + raise ValueError( + "monitor edit requires target, target_key, cadence, or stop_condition" + ) + return result + if action_kind == "gate.resolve": + values = self._allowed_parameters( + parameters, + allowed={"goal_id", "todo_id", "decision", "note", "agent_id"}, + ) + goal_id = _opaque(values.get("goal_id"), field="goal_id") + self._goal(goal_id) + decision = str(values.get("decision") or "").strip().lower() + if decision not in {"approve", "reject", "cancel", "defer"}: + raise ValueError( + "gate decision must be approve, reject, cancel, or defer" + ) + result = { + "goal_id": goal_id, + "todo_id": _opaque(values.get("todo_id"), field="todo_id"), + "decision": decision, + } + if values.get("note"): + result["note"] = _text(values["note"], field="note", limit=600) + if values.get("agent_id"): + result["agent_id"] = _opaque(values["agent_id"], field="agent_id") + return result + raise ValueError(f"unsupported action_kind: {action_kind}") diff --git a/loopx/chat_actions.py b/loopx/chat_actions.py index 6c6e1ec108..fb248a6047 100644 --- a/loopx/chat_actions.py +++ b/loopx/chat_actions.py @@ -2,7 +2,6 @@ from __future__ import annotations -from datetime import timedelta import hashlib import json from pathlib import Path @@ -12,15 +11,15 @@ from .agent_registry import agent_profile_for_goal, registered_agent_ids_for_goal from .bootstrap import bootstrap_project from .chat import apply_todo_review_preview, build_todo_review_preview +from .chat_action_normalization import ChatActionNormalizationMixin from .chat_action_store import ActionConflictError, ChatActionStore from .chat_goal_lifecycle_actions import ChatGoalLifecycleActionMixin from .chat_monitor_actions import ChatMonitorActionMixin from .chat_store import ChatSessionStore from .chat_todo_actions import ChatTodoActionMixin from .configure_goal import configure_goal -from .control_plane.runtime.time import now_utc, parse_timestamp, utc_isoformat +from .control_plane.runtime.time import now_utc, parse_timestamp from .control_plane.scheduler.monitor_todo import monitor_next_due_at -from .control_plane.todos.contract import require_supported_todo_resume_when from .history import load_registry from .host_loop_activation import build_host_loop_activation_packet from .kiro_cli_goal_mode import KIRO_CLI_CHAT_AGENT_ID @@ -45,8 +44,6 @@ "operation.execute", } _OPAQUE_ID = re.compile(r"^[A-Za-z0-9._:-]{1,200}$") -_SHA256 = re.compile(r"^[0-9a-f]{64}$") -_AUTHORITY_PRINCIPAL = re.compile(r"^[a-z][a-z0-9._-]{0,30}:[A-Za-z0-9._:-]{1,200}$") # Runtime Endpoint ids and durable Goal agent ids are chosen independently, so # a family token collapses both onto the host that produced them: Endpoint # `codex` has to resolve to a registered `codex-main-control`. Every host that @@ -178,7 +175,10 @@ def _monitor_text(parameters: Mapping[str, Any]) -> str | None: class ChatActionService( - ChatGoalLifecycleActionMixin, ChatMonitorActionMixin, ChatTodoActionMixin + ChatActionNormalizationMixin, + ChatGoalLifecycleActionMixin, + ChatMonitorActionMixin, + ChatTodoActionMixin, ): """Validate previews and route applies through canonical LoopX services.""" @@ -365,602 +365,6 @@ def _allowed_parameters( raise ValueError(f"unknown typed action parameter: {sorted(unknown)[0]}") return dict(parameters) - def _normalize( - self, action_kind: str, parameters: Mapping[str, Any] - ) -> dict[str, Any]: - if action_kind == "operation.execute": - values = self._allowed_parameters( - parameters, - allowed={ - "schema_version", - "goal_id", - "agent_id", - "domain", - "operation_kind", - "operation_schema", - "payload_ref", - "payload", - "payload_digest", - "projection", - "destination_account_ref", - "expires_at", - "authorized_principals", - "executor", - }, - ) - if values.get("schema_version") != "loopx_operation_request_v0": - raise ValueError( - "operation.execute requires loopx_operation_request_v0" - ) - goal_id = _opaque(values.get("goal_id"), field="goal_id") - goal = self._goal(goal_id) - agent_id = _opaque(values.get("agent_id"), field="agent_id") - if agent_id not in registered_agent_ids_for_goal(goal): - raise ValueError("operation agent_id must be registered for the Goal") - payload = values.get("payload") - if not isinstance(payload, Mapping): - raise ValueError("operation payload must be an object") - payload_digest = str(values.get("payload_digest") or "").strip() - if not _SHA256.fullmatch(payload_digest): - raise ValueError("operation payload_digest must be lowercase SHA-256") - if _digest(payload) != payload_digest: - raise ValueError("operation payload_digest does not match payload") - - projection = values.get("projection") - if not isinstance(projection, Mapping): - raise ValueError("operation projection must be an object") - projection_values = self._allowed_parameters( - projection, - allowed={ - "schema_version", - "title", - "subtitle", - "focus", - "fields", - "warning", - "simulated", - }, - ) - if ( - projection_values.get("schema_version") - != "loopx_operation_projection_v0" - ): - raise ValueError( - "operation projection requires loopx_operation_projection_v0" - ) - normalized_projection: dict[str, Any] = { - "schema_version": "loopx_operation_projection_v0", - "title": _text( - projection_values.get("title"), - field="projection.title", - limit=80, - ), - "subtitle": _text( - projection_values.get("subtitle"), - field="projection.subtitle", - limit=120, - ), - "focus": _text( - projection_values.get("focus"), - field="projection.focus", - limit=120, - ), - "warning": _text( - projection_values.get("warning"), - field="projection.warning", - limit=300, - ), - } - if not isinstance(projection_values.get("simulated"), bool): - raise ValueError("operation projection simulated must be true or false") - normalized_projection["simulated"] = projection_values["simulated"] - raw_fields = projection_values.get("fields") - if not isinstance(raw_fields, list) or not 1 <= len(raw_fields) <= 12: - raise ValueError("operation projection fields must contain 1-12 items") - normalized_fields: list[dict[str, str]] = [] - for index, raw_field in enumerate(raw_fields): - if not isinstance(raw_field, Mapping) or set(raw_field) != { - "label", - "value", - }: - raise ValueError( - f"operation projection field {index + 1} is invalid" - ) - normalized_fields.append( - { - "label": _text( - raw_field.get("label"), - field=f"projection.fields[{index}].label", - limit=40, - ), - "value": _text( - raw_field.get("value"), - field=f"projection.fields[{index}].value", - limit=120, - ), - } - ) - normalized_projection["fields"] = normalized_fields - - raw_executor = values.get("executor") - if not isinstance(raw_executor, Mapping) or set(raw_executor) != { - "extension_id", - "protocol", - "permission", - "revision", - }: - raise ValueError("operation executor binding is invalid") - executor = { - field: _opaque(raw_executor.get(field), field=f"executor.{field}") - for field in ( - "extension_id", - "protocol", - "permission", - "revision", - ) - } - expires_at = parse_timestamp( - _text(values.get("expires_at"), field="expires_at", limit=80) - ) - if expires_at is None: - raise ValueError("operation expires_at must be an ISO-8601 timestamp") - current = now_utc() - if not current < expires_at <= current + timedelta(days=7): - raise ValueError("operation expiry must be within the next seven days") - raw_principals = values.get("authorized_principals") - if ( - not isinstance(raw_principals, list) - or not 1 <= len(raw_principals) <= 20 - ): - raise ValueError( - "operation authorized_principals must contain 1-20 identities" - ) - principals: list[str] = [] - for raw_principal in raw_principals: - principal = str(raw_principal or "").strip() - if not _AUTHORITY_PRINCIPAL.fullmatch(principal): - raise ValueError( - "operation authorized_principals must use provider:subject values" - ) - if principal not in principals: - principals.append(principal) - return { - "schema_version": "loopx_operation_request_v0", - "goal_id": goal_id, - "agent_id": agent_id, - "domain": _opaque(values.get("domain"), field="domain"), - "operation_kind": _opaque( - values.get("operation_kind"), field="operation_kind" - ), - "operation_schema": _opaque( - values.get("operation_schema"), field="operation_schema" - ), - "payload_ref": _opaque(values.get("payload_ref"), field="payload_ref"), - "payload": dict(payload), - "payload_digest": payload_digest, - "projection": normalized_projection, - "projection_digest": _digest(normalized_projection), - "destination_account_ref": _opaque( - values.get("destination_account_ref"), - field="destination_account_ref", - ), - "expires_at": utc_isoformat(expires_at), - "authorized_principals": principals, - "executor": executor, - } - if action_kind == "todo.create": - values = self._allowed_parameters( - parameters, - allowed={ - "goal_id", - "text", - "agent_id", - "endpoint_id", - "start_execution", - }, - ) - goal_id = _opaque(values.get("goal_id"), field="goal_id") - self._goal(goal_id) - result = { - "goal_id": goal_id, - "text": _text(values.get("text"), field="text", limit=400), - } - if values.get("endpoint_id"): - endpoint_id = _opaque(values.get("endpoint_id"), field="endpoint_id") - result["endpoint_id"] = endpoint_id - result["agent_id"] = self._resolve_goal_agent(goal_id, endpoint_id) - elif values.get("agent_id"): - agent_id = _opaque(values.get("agent_id"), field="agent_id") - if agent_id not in registered_agent_ids_for_goal(self._goal(goal_id)): - raise ProtectedActionGate( - "agent.bind", - gate={ - "kind": "agent_binding_required", - "summary": "所选 Agent 身份尚未绑定到这个 Goal。", - "next_action": "先确认 Agent 绑定预览,再继续创建 Todo。", - "agent_id": agent_id, - "goal_id": goal_id, - }, - ) - result["agent_id"] = agent_id - if values.get("start_execution") is not None: - if not isinstance(values["start_execution"], bool): - raise ValueError("start_execution must be true or false") - result["start_execution"] = values["start_execution"] - if result.get("start_execution") and not result.get("agent_id"): - raise ValueError("start_execution requires an assigned Agent") - return result - if action_kind == "todo.update": - values = self._allowed_parameters( - parameters, - allowed={ - "goal_id", - "todo_id", - "text", - "status", - "note", - "agent_id", - "endpoint_id", - "operation", - "resume_when", - "successor_todo_ids", - "no_followup", - }, - ) - goal_id = _opaque(values.get("goal_id"), field="goal_id") - self._goal(goal_id) - result: dict[str, Any] = { - "goal_id": goal_id, - "todo_id": _opaque(values.get("todo_id"), field="todo_id"), - } - operation = str(values.get("operation") or "edit").strip().lower() - if operation not in { - "edit", - "reassign", - "block", - "defer", - "complete", - "successor", - }: - raise ValueError( - "todo.update operation must be edit, reassign, block, defer, complete, or successor" - ) - result["operation"] = operation - if values.get("text"): - result["text"] = _text(values["text"], field="text", limit=400) - if values.get("status"): - status = str(values["status"]).strip().lower() - if status not in {"open", "blocked", "deferred"}: - raise ValueError( - "todo.update status must be open, blocked, or deferred" - ) - result["status"] = status - if values.get("note"): - result["note"] = _text(values["note"], field="note", limit=600) - if values.get("endpoint_id"): - endpoint_id = _opaque(values["endpoint_id"], field="endpoint_id") - result["endpoint_id"] = endpoint_id - result["agent_id"] = self._resolve_goal_agent(goal_id, endpoint_id) - elif values.get("agent_id"): - result["agent_id"] = _opaque(values["agent_id"], field="agent_id") - if values.get("resume_when"): - result["resume_when"] = require_supported_todo_resume_when( - _text(values["resume_when"], field="resume_when", limit=240) - ) - if values.get("successor_todo_ids") is not None: - if not isinstance(values["successor_todo_ids"], list): - raise ValueError("successor_todo_ids must be a list") - result["successor_todo_ids"] = [ - _opaque(item, field="successor_todo_ids") - for item in values["successor_todo_ids"][:20] - ] - if values.get("no_followup") is not None: - if not isinstance(values["no_followup"], bool): - raise ValueError("no_followup must be true or false") - result["no_followup"] = values["no_followup"] - required_by_operation = { - "reassign": "agent_id", - "defer": "resume_when", - "successor": "successor_todo_ids", - } - required = required_by_operation.get(operation) - if required and not result.get(required): - raise ValueError(f"todo.update {operation} requires {required}") - if operation == "block" and not result.get("note"): - raise ValueError("todo.update block requires note") - if operation == "edit" and len(result) == 3: - raise ValueError("todo.update requires text, status, or note") - return result - if action_kind == "run.correct": - values = self._allowed_parameters( - parameters, - allowed={"goal_id", "session_id", "message", "client_turn_id"}, - ) - goal_id = _opaque(values.get("goal_id"), field="goal_id") - self._goal(goal_id) - session_id = _opaque(values.get("session_id"), field="session_id") - client_turn_id = values.get("client_turn_id") - normalized = { - "goal_id": goal_id, - "session_id": session_id, - "message": _text(values.get("message"), field="message", limit=4000), - } - if client_turn_id: - normalized["client_turn_id"] = _opaque( - client_turn_id, field="client_turn_id" - ) - return normalized - if action_kind == "goal.create": - values = self._allowed_parameters( - parameters, - allowed={ - "goal_id", - "title", - "objective", - "completion_criteria", - "execution_boundary", - "agent_id", - "workspace_ref", - "permission", - "heartbeat", - "stop_condition", - "initial_todos", - }, - ) - goal_id = _opaque(values.get("goal_id"), field="goal_id") - if any( - str(goal.get("id") or "") == goal_id - for goal in registry_goals(self._registry()) - ): - raise ValueError("goal_id already exists in the active LoopX registry") - result: dict[str, Any] = { - "goal_id": goal_id, - "title": _text(values.get("title"), field="title", limit=200), - } - for field in ( - "objective", - "completion_criteria", - "execution_boundary", - "permission", - "stop_condition", - ): - if values.get(field): - result[field] = _text(values[field], field=field, limit=1000) - for field in ("agent_id", "workspace_ref"): - if values.get(field): - result[field] = _opaque(values[field], field=field) - if result.get("agent_id"): - self._agent_eligibility(str(result["agent_id"])) - if values.get("heartbeat") is not None: - if not isinstance(values["heartbeat"], Mapping): - raise ValueError("heartbeat must be an object") - heartbeat = self._allowed_parameters( - values["heartbeat"], allowed={"enabled", "cadence", "timezone"} - ) - enabled = heartbeat.get("enabled") - if not isinstance(enabled, bool): - raise ValueError("heartbeat.enabled must be true or false") - normalized_heartbeat: dict[str, Any] = {"enabled": enabled} - if heartbeat.get("cadence"): - normalized_heartbeat["cadence"] = _normalize_cadence( - heartbeat["cadence"] - ) - if heartbeat.get("timezone"): - normalized_heartbeat["timezone"] = _text( - heartbeat["timezone"], field="heartbeat.timezone", limit=80 - ) - result["heartbeat"] = normalized_heartbeat - if values.get("initial_todos") is not None: - if not isinstance(values["initial_todos"], list): - raise ValueError("initial_todos must be a list") - result["initial_todos"] = [ - _text(item, field="initial_todos", limit=400) - for item in values["initial_todos"][:20] - ] - return result - if action_kind == "goal.update": - values = self._allowed_parameters( - parameters, - allowed={"goal_id", "title", "objective", "status", "write_scope"}, - ) - goal_id = _opaque(values.get("goal_id"), field="goal_id") - self._goal(goal_id) - result = {"goal_id": goal_id} - for field in ("title", "objective", "status"): - if values.get(field): - result[field] = _text(values[field], field=field, limit=1000) - if values.get("write_scope") is not None: - if not isinstance(values["write_scope"], list): - raise ValueError("write_scope must be a list") - result["write_scope"] = [ - _text(item, field="write_scope", limit=160) - for item in values["write_scope"][:20] - ] - if len(result) == 1: - raise ValueError("goal.update requires at least one change") - return result - if action_kind == "goal.lifecycle": - return self._normalize_goal_lifecycle(parameters) - if action_kind == "agent.bind": - values = self._allowed_parameters( - parameters, allowed={"goal_id", "agent_id"} - ) - goal_id = _opaque(values.get("goal_id"), field="goal_id") - self._goal(goal_id) - agent_id = _opaque(values.get("agent_id"), field="agent_id") - self._agent_eligibility(agent_id) - return { - "goal_id": goal_id, - "agent_id": agent_id, - } - if action_kind == "heartbeat.bind": - values = self._allowed_parameters( - parameters, - allowed={ - "goal_id", - "agent_id", - "cadence", - "timezone", - "stop_condition", - "notification_policy", - "operation", - }, - ) - goal_id = _opaque(values.get("goal_id"), field="goal_id") - self._goal(goal_id) - operation = str(values.get("operation") or "bind").strip().lower() - if operation not in {"bind", "edit", "pause", "resume", "stop"}: - raise ValueError( - "heartbeat operation must be bind, edit, pause, resume, or stop" - ) - agent_id = _opaque(values.get("agent_id"), field="agent_id") - self._agent_eligibility(agent_id) - result: dict[str, Any] = { - "goal_id": goal_id, - "agent_id": agent_id, - "operation": operation, - } - if values.get("cadence"): - result["cadence"] = _normalize_cadence(values["cadence"]) - if values.get("timezone"): - result["timezone"] = _text( - values["timezone"], field="timezone", limit=80 - ) - if values.get("stop_condition"): - result["stop_condition"] = _text( - values["stop_condition"], field="stop_condition", limit=160 - ).lower() - if values.get("notification_policy"): - result["notification_policy"] = _opaque( - values["notification_policy"], field="notification_policy" - ) - if operation == "bind" and not all( - result.get(field) for field in ("cadence", "timezone", "stop_condition") - ): - raise ValueError( - "heartbeat bind requires cadence, timezone, and stop_condition" - ) - if operation == "edit" and len(result) == 3: - raise ValueError("heartbeat edit requires a configuration change") - return result - if action_kind == "monitor.create": - values = self._allowed_parameters( - parameters, - allowed={ - "goal_id", - "agent_id", - "target", - "target_key", - "cadence", - "timezone", - "stop_condition", - "notification_rule", - }, - ) - goal_id = _opaque(values.get("goal_id"), field="goal_id") - self._goal(goal_id) - result = { - "goal_id": goal_id, - "agent_id": _opaque(values.get("agent_id"), field="agent_id"), - "target": _text(values.get("target"), field="target", limit=400), - "target_key": _opaque(values.get("target_key"), field="target_key"), - "cadence": _normalize_cadence(values.get("cadence")), - "timezone": _text(values.get("timezone"), field="timezone", limit=80), - } - stop_cond_raw = values.get("stop_condition") - if stop_cond_raw: - raw_text = _text(stop_cond_raw, field="stop_condition", limit=160) - parsed_ts = parse_timestamp(raw_text) - result["stop_condition"] = ( - utc_isoformat(parsed_ts) - if parsed_ts is not None - else raw_text.lower() - ) - if values.get("notification_rule"): - result["notification_rule"] = _text( - values["notification_rule"], field="notification_rule", limit=400 - ) - return result - if action_kind == "monitor.update": - values = self._allowed_parameters( - parameters, - allowed={ - "goal_id", - "todo_id", - "agent_id", - "operation", - "target", - "target_key", - "cadence", - "stop_condition", - "session_id", - "endpoint_id", - }, - ) - goal_id = _opaque(values.get("goal_id"), field="goal_id") - self._goal(goal_id) - operation = str(values.get("operation") or "").strip().lower() - if operation not in {"pause", "resume", "stop", "run_now", "edit"}: - raise ValueError( - "monitor.update operation must be pause, resume, stop, run_now, or edit" - ) - result = { - "goal_id": goal_id, - "todo_id": _opaque(values.get("todo_id"), field="todo_id"), - "agent_id": _opaque(values.get("agent_id"), field="agent_id"), - "operation": operation, - } - if values.get("endpoint_id"): - endpoint_id = _opaque(values["endpoint_id"], field="endpoint_id") - result["endpoint_id"] = endpoint_id - result["agent_id"] = self._resolve_goal_agent(goal_id, endpoint_id) - if values.get("target"): - result["target"] = _text(values["target"], field="target", limit=400) - if values.get("target_key"): - result["target_key"] = _opaque(values["target_key"], field="target_key") - if values.get("cadence"): - result["cadence"] = _normalize_cadence(values["cadence"]) - if values.get("stop_condition"): - raw_stop = _text( - values["stop_condition"], field="stop_condition", limit=160 - ) - parsed_ts = parse_timestamp(raw_stop) - result["stop_condition"] = ( - utc_isoformat(parsed_ts) - if parsed_ts is not None - else raw_stop.lower() - ) - if values.get("session_id"): - result["session_id"] = _opaque(values["session_id"], field="session_id") - if operation == "edit" and len(result) == 4: - raise ValueError( - "monitor edit requires target, target_key, cadence, or stop_condition" - ) - return result - if action_kind == "gate.resolve": - values = self._allowed_parameters( - parameters, - allowed={"goal_id", "todo_id", "decision", "note", "agent_id"}, - ) - goal_id = _opaque(values.get("goal_id"), field="goal_id") - self._goal(goal_id) - decision = str(values.get("decision") or "").strip().lower() - if decision not in {"approve", "reject", "cancel", "defer"}: - raise ValueError( - "gate decision must be approve, reject, cancel, or defer" - ) - result = { - "goal_id": goal_id, - "todo_id": _opaque(values.get("todo_id"), field="todo_id"), - "decision": decision, - } - if values.get("note"): - result["note"] = _text(values["note"], field="note", limit=600) - if values.get("agent_id"): - result["agent_id"] = _opaque(values["agent_id"], field="agent_id") - return result - raise ValueError(f"unsupported action_kind: {action_kind}") - def _session_fingerprint(self, session_id: str, goal_id: str) -> str: if self.chat_store is None: raise ValueError("Chat Session state is unavailable")