fix(ui): stabilize company chat result topology

This commit is contained in:
LZH-YS1998 committed 2026-07-14 20:31:10 +08:00
1 parent 0a6246aff9
commit 5938b4c215
25 files changed
+1917 -381

No files matched your search

+65 -2
View File
@@ -144,6 +144,7 @@ from opc.layer2_organization.work_item_identity import (
projection_id_for_task, projection_id_for_task,
projection_id_for_work_item, projection_id_for_work_item,
rework_projection_id_for_gate, rework_projection_id_for_gate,
result_delivery_identity_payload_for_task,
turn_type_for_task, turn_type_for_task,
turn_type_for_work_item, turn_type_for_work_item,
work_item_identity_payload, work_item_identity_payload,
@@ -9076,6 +9077,48 @@ class OPCEngine:
in {"suspending", "suspended"} in {"suspending", "suspended"}
) )
@staticmethod
def _ensure_result_delivery_identity_for_commit(
task: Task,
result: TaskResult,
) -> dict[str, str]:
"""Reuse the runtime's immutable delivery id or mint one once.
A runtime-generated canonical turn is not guaranteed to be copied back
into mutable Task metadata. The TaskResult artifact is therefore the
hand-off boundary between runtime persistence and the engine mirrors.
External/pause results without a canonical turn receive a per-result
execution seed here. Runtime/provider *session* ids are deliberately
excluded because those sessions survive resume and can produce several
legitimate deliveries for the same task and retry count.
The generated identity is written back to ``TaskResult.artifacts``
before the task result is persisted. Replaying that durable result is
therefore stable instead of minting a second UI row after a restart.
"""
artifacts = dict(result.artifacts or {})
canonical_turn_id = str(
artifacts.get("canonical_turn_id")
or artifacts.get("conversation_turn_id")
or ""
).strip()
persisted_delivery_id = str(artifacts.get("result_delivery_id") or "").strip()
execution_id = str(artifacts.get("result_execution_id") or "").strip()
if not persisted_delivery_id and not canonical_turn_id and not execution_id:
execution_id = uuid.uuid4().hex
identity = result_delivery_identity_payload_for_task(
task,
canonical_turn_id=canonical_turn_id,
execution_id=execution_id,
result_delivery_id=persisted_delivery_id,
)
result.artifacts = {
**artifacts,
**({"result_execution_id": execution_id} if execution_id else {}),
**identity,
}
return identity
async def _execute_registered_task_attempt(self, task: Task) -> TaskResult: async def _execute_registered_task_attempt(self, task: Task) -> TaskResult:
try: try:
result = await self._run_task_once(task) result = await self._run_task_once(task)
@@ -9115,6 +9158,7 @@ class OPCEngine:
"company runtime was suspended before result commit" "company runtime was suspended before result commit"
) )
self._apply_runtime_state_to_task(task, result) self._apply_runtime_state_to_task(task, result)
result_identity = self._ensure_result_delivery_identity_for_commit(task, result)
task.status = result.status task.status = result.status
task.result = {"content": result.content, "artifacts": result.artifacts} task.result = {"content": result.content, "artifacts": result.artifacts}
await self.store.save_task(task) await self.store.save_task(task)
@@ -9131,6 +9175,8 @@ class OPCEngine:
"status": result.status.value, "status": result.status.value,
"employee_id": str(assignment.get("employee_id", "")).strip(), "employee_id": str(assignment.get("employee_id", "")).strip(),
"role_id": str(assignment.get("role_id") or task.assigned_to or "").strip(), "role_id": str(assignment.get("role_id") or task.assigned_to or "").strip(),
"child_session_id": str(task.session_id),
**result_identity,
**work_item_identity_payload_for_task(task), **work_item_identity_payload_for_task(task),
}, },
) )
@@ -9141,7 +9187,7 @@ class OPCEngine:
and task.session_id != task.parent_session_id and task.session_id != task.parent_session_id
): ):
assignment = dict(task.metadata.get("employee_assignment", {}) or {}) assignment = dict(task.metadata.get("employee_assignment", {}) or {})
await self.memory.record_assistant_turn( child_result_message = await self.memory.record_assistant_turn(
session_id=task.session_id, session_id=task.session_id,
content=result.content, content=result.content,
project_id=task.project_id, project_id=task.project_id,
@@ -9152,6 +9198,8 @@ class OPCEngine:
"status": result.status.value, "status": result.status.value,
"employee_id": str(assignment.get("employee_id", "")).strip(), "employee_id": str(assignment.get("employee_id", "")).strip(),
"role_id": str(assignment.get("role_id") or task.assigned_to or "").strip(), "role_id": str(assignment.get("role_id") or task.assigned_to or "").strip(),
"child_session_id": str(task.session_id),
**result_identity,
**work_item_identity_payload_for_task(task), **work_item_identity_payload_for_task(task),
}, },
) )
@@ -9161,6 +9209,11 @@ class OPCEngine:
task=task, task=task,
result_content=result.content, result_content=result.content,
artifacts=result.artifacts, artifacts=result.artifacts,
result_delivery_id=result_identity.get("result_delivery_id", ""),
source_result_message_id=str(
getattr(child_result_message, "message_id", "") or ""
),
canonical_turn_id=result_identity.get("canonical_turn_id", ""),
) )
if result.status == TaskStatus.DONE: if result.status == TaskStatus.DONE:
await self._record_task_mode_external_result_reply(task, result.content) await self._record_task_mode_external_result_reply(task, result.content)
@@ -9197,6 +9250,7 @@ class OPCEngine:
"company runtime was suspended before retry result commit" "company runtime was suspended before retry result commit"
) )
self._apply_runtime_state_to_task(task, result) self._apply_runtime_state_to_task(task, result)
result_identity = self._ensure_result_delivery_identity_for_commit(task, result)
task.status = result.status task.status = result.status
task.result = {"content": result.content, "artifacts": result.artifacts} task.result = {"content": result.content, "artifacts": result.artifacts}
await self.store.save_task(task) await self.store.save_task(task)
@@ -9214,6 +9268,8 @@ class OPCEngine:
"retry_count": task.retry_count, "retry_count": task.retry_count,
"employee_id": str(assignment.get("employee_id", "")).strip(), "employee_id": str(assignment.get("employee_id", "")).strip(),
"role_id": str(assignment.get("role_id") or task.assigned_to or "").strip(), "role_id": str(assignment.get("role_id") or task.assigned_to or "").strip(),
"child_session_id": str(task.session_id),
**result_identity,
**work_item_identity_payload_for_task(task), **work_item_identity_payload_for_task(task),
}, },
) )
@@ -9224,7 +9280,7 @@ class OPCEngine:
and task.session_id != task.parent_session_id and task.session_id != task.parent_session_id
): ):
assignment = dict(task.metadata.get("employee_assignment", {}) or {}) assignment = dict(task.metadata.get("employee_assignment", {}) or {})
await self.memory.record_assistant_turn( child_result_message = await self.memory.record_assistant_turn(
session_id=task.session_id, session_id=task.session_id,
content=result.content, content=result.content,
project_id=task.project_id, project_id=task.project_id,
@@ -9236,6 +9292,8 @@ class OPCEngine:
"retry_count": task.retry_count, "retry_count": task.retry_count,
"employee_id": str(assignment.get("employee_id", "")).strip(), "employee_id": str(assignment.get("employee_id", "")).strip(),
"role_id": str(assignment.get("role_id") or task.assigned_to or "").strip(), "role_id": str(assignment.get("role_id") or task.assigned_to or "").strip(),
"child_session_id": str(task.session_id),
**result_identity,
**work_item_identity_payload_for_task(task), **work_item_identity_payload_for_task(task),
}, },
) )
@@ -9245,6 +9303,11 @@ class OPCEngine:
task=task, task=task,
result_content=result.content, result_content=result.content,
artifacts=result.artifacts, artifacts=result.artifacts,
result_delivery_id=result_identity.get("result_delivery_id", ""),
source_result_message_id=str(
getattr(child_result_message, "message_id", "") or ""
),
canonical_turn_id=result_identity.get("canonical_turn_id", ""),
) )
if result.status == TaskStatus.DONE: if result.status == TaskStatus.DONE:
await self._record_task_mode_external_result_reply(task, result.content) await self._record_task_mode_external_result_reply(task, result.content)
@@ -7,6 +7,8 @@ from typing import Any, Mapping
WORK_ITEM_PROJECTION_ID_KEY = "work_item_projection_id" WORK_ITEM_PROJECTION_ID_KEY = "work_item_projection_id"
WORK_ITEM_TURN_TYPE_KEY = "work_item_turn_type" WORK_ITEM_TURN_TYPE_KEY = "work_item_turn_type"
RESULT_DELIVERY_ID_KEY = "result_delivery_id"
SOURCE_TASK_ID_KEY = "source_task_id"
GATE_REWORK_PROJECTION_ID_KEY = "rework_projection_id" GATE_REWORK_PROJECTION_ID_KEY = "rework_projection_id"
GATE_TARGET_PROJECTION_ID_KEY = "target_projection_id" GATE_TARGET_PROJECTION_ID_KEY = "target_projection_id"
GATE_TARGET_PROJECTION_IDS_KEY = "target_projection_ids" GATE_TARGET_PROJECTION_IDS_KEY = "target_projection_ids"
@@ -259,6 +261,94 @@ def work_item_identity_payload_for_task(
) )
def canonical_result_turn_id_for_task(
task: Any,
*,
canonical_turn_id: str = "",
) -> str:
"""Return the canonical conversation turn owning a task result.
Runtime events also carry iteration-scoped ``turn_id`` values. Result
surfaces must never use those values as their logical delivery identity,
so this helper only falls back to the task's canonical runtime fields.
"""
explicit = _clean(canonical_turn_id)
if explicit:
return explicit
metadata = dict(getattr(task, "metadata", {}) or {}) if task is not None else {}
runtime_metadata = dict(metadata.get("runtime_v2", {}) or {})
for source in (metadata, runtime_metadata):
for key in (
"canonical_turn_id",
"conversation_turn_id",
"current_turn_id",
"runtime_v2_current_turn_id",
):
value = _clean(source.get(key))
if value:
return value
return ""
def result_delivery_id_for_task(
task: Any,
*,
canonical_turn_id: str = "",
execution_id: str = "",
result_delivery_id: str = "",
) -> str:
"""Build one stable identity shared by every surface of a task result.
The attempt suffix keeps a failed result and its retry distinct while the
canonical turn (when available) links the runtime final, child result and
parent mirror without inspecting their display text.
"""
explicit = _clean(result_delivery_id)
if explicit:
return explicit
task_id = _clean(getattr(task, "id", ""))
turn_id = canonical_result_turn_id_for_task(
task,
canonical_turn_id=canonical_turn_id,
)
execution = _clean(execution_id)
if not task_id or (not turn_id and not execution):
return ""
try:
attempt = max(0, int(getattr(task, "retry_count", 0) or 0))
except (TypeError, ValueError):
attempt = 0
identity_kind = "turn" if turn_id else "execution"
identity_value = turn_id or execution
return f"result:task:{task_id}:{identity_kind}:{identity_value}:attempt:{attempt}"
def result_delivery_identity_payload_for_task(
task: Any,
*,
canonical_turn_id: str = "",
execution_id: str = "",
result_delivery_id: str = "",
) -> dict[str, str]:
"""Return structured lineage shared by persisted result projections."""
delivery_id = result_delivery_id_for_task(
task,
canonical_turn_id=canonical_turn_id,
execution_id=execution_id,
result_delivery_id=result_delivery_id,
)
source_task_id = _clean(getattr(task, "id", ""))
canonical_id = canonical_result_turn_id_for_task(
task,
canonical_turn_id=canonical_turn_id,
)
return {
**({RESULT_DELIVERY_ID_KEY: delivery_id} if delivery_id else {}),
**({SOURCE_TASK_ID_KEY: source_task_id} if source_task_id else {}),
**({"canonical_turn_id": canonical_id} if canonical_id else {}),
}
def migrate_work_item_projection_metadata( def migrate_work_item_projection_metadata(
metadata: Mapping[str, Any] | None, metadata: Mapping[str, Any] | None,
*, *,
+23
View File
@@ -19,6 +19,7 @@ from opc.core.models import OPCEvent, PermissionResolution, Task, TaskResult, Ta
from opc.layer2_organization.collaboration_policy import ownership_guard_violation from opc.layer2_organization.collaboration_policy import ownership_guard_violation
from opc.layer2_organization.work_item_identity import ( from opc.layer2_organization.work_item_identity import (
projection_id_for_task, projection_id_for_task,
result_delivery_identity_payload_for_task,
turn_type_for_task, turn_type_for_task,
work_item_identity_payload_for_task, work_item_identity_payload_for_task,
) )
@@ -703,6 +704,14 @@ class NativeRuntimeV2:
runtime_notes=runtime_notes, runtime_notes=runtime_notes,
) )
if verification_gate is not None: if verification_gate is not None:
verification_gate.artifacts = {
**dict(verification_gate.artifacts or {}),
"runtime_session_id": runtime_session_id,
**result_delivery_identity_payload_for_task(
task,
canonical_turn_id=conversation_turn_id,
),
}
await self._save_runtime_session( await self._save_runtime_session(
runtime_session_id, runtime_session_id,
task, task,
@@ -728,6 +737,10 @@ class NativeRuntimeV2:
artifacts = { artifacts = {
**aggregated_artifacts, **aggregated_artifacts,
"runtime_session_id": runtime_session_id, "runtime_session_id": runtime_session_id,
**result_delivery_identity_payload_for_task(
task,
canonical_turn_id=conversation_turn_id,
),
"permission_requests": self._permission_requests_from_results([]), "permission_requests": self._permission_requests_from_results([]),
"active_subagents": active_subagents, "active_subagents": active_subagents,
"compaction_boundaries": list(compaction_boundaries), "compaction_boundaries": list(compaction_boundaries),
@@ -2799,6 +2812,16 @@ class NativeRuntimeV2:
"runtime_session_id": runtime_session_id, "runtime_session_id": runtime_session_id,
"source_kind": source_kind, "source_kind": source_kind,
} }
if not tool_calls:
metadata.update(
result_delivery_identity_payload_for_task(
task,
canonical_turn_id=canonical_turn_id,
)
)
metadata.update(work_item_identity_payload_for_task(task))
if task.session_id:
metadata["child_session_id"] = str(task.session_id)
if is_company_mode: if is_company_mode:
metadata["execution_mode"] = "company_mode" metadata["execution_mode"] = "company_mode"
metadata["company_runtime_raw_turn"] = True metadata["company_runtime_raw_turn"] = True
+9
View File
@@ -713,6 +713,9 @@ class MemoryManager:
task: Any, task: Any,
result_content: str, result_content: str,
artifacts: dict[str, Any] | None = None, artifacts: dict[str, Any] | None = None,
result_delivery_id: str = "",
source_result_message_id: str = "",
canonical_turn_id: str = "",
) -> None: ) -> None:
if not self.store: if not self.store:
return return
@@ -728,9 +731,13 @@ class MemoryManager:
metadata={ metadata={
"kind": "child_result", "kind": "child_result",
"child_session_id": child_session_id, "child_session_id": child_session_id,
"source_task_id": str(getattr(task, "id", "") or ""),
"task_title": getattr(task, "title", ""), "task_title": getattr(task, "title", ""),
"employee_id": str(assignment.get("employee_id", "")).strip(), "employee_id": str(assignment.get("employee_id", "")).strip(),
"role_id": str(assignment.get("role_id") or getattr(task, "assigned_to", "") or "").strip(), "role_id": str(assignment.get("role_id") or getattr(task, "assigned_to", "") or "").strip(),
**({"result_delivery_id": str(result_delivery_id).strip()} if str(result_delivery_id).strip() else {}),
**({"source_result_message_id": str(source_result_message_id).strip()} if str(source_result_message_id).strip() else {}),
**({"canonical_turn_id": str(canonical_turn_id).strip()} if str(canonical_turn_id).strip() else {}),
**work_item_identity_payload_for_task(task), **work_item_identity_payload_for_task(task),
}, },
) )
@@ -747,6 +754,8 @@ class MemoryManager:
"agent_id": getattr(task, "assigned_to", ""), "agent_id": getattr(task, "assigned_to", ""),
"summary": summary, "summary": summary,
"artifacts": self._compact_artifacts(artifacts or {}), "artifacts": self._compact_artifacts(artifacts or {}),
**({"result_delivery_id": str(result_delivery_id).strip()} if str(result_delivery_id).strip() else {}),
**({"source_result_message_id": str(source_result_message_id).strip()} if str(source_result_message_id).strip() else {}),
}, },
) )
+171 -84
View File
@@ -575,23 +575,43 @@ class ChatStore:
@staticmethod @staticmethod
def _strip_narrative_title_prefix(content: str) -> str: def _strip_narrative_title_prefix(content: str) -> str:
trimmed = str(content or "").strip() trimmed = str(content or "").strip()
markdown_title = re.match(r"^\*\*(.{8,160}?)\*\*:\s+([\s\S]+)$", trimmed) # Only discard an explicit, anchored narrative wrapper. The former
if markdown_title: # fallback used the first ``": "`` anywhere in the first 160
# characters, so ordinary Markdown such as ``**Work Item 1: ...**``
# was progressively truncated every time a sync was merged. Peeling
# explicit nested wrappers to a fixed point keeps this comparison
# helper idempotent without interpreting body punctuation as structure.
while True:
markdown_title = re.match(r"^\*\*(.{8,160}?)\*\*:\s+([\s\S]+)$", trimmed)
if not markdown_title:
return trimmed
body = markdown_title.group(2).strip() body = markdown_title.group(2).strip()
if len(body) >= 80: if len(body) < 80 or body == trimmed:
return body return trimmed
colon_index = trimmed.find(": ") trimmed = body
if colon_index < 8 or colon_index > 160:
return trimmed @classmethod
prefix = trimmed[:colon_index].replace("*", "").strip() def _select_duplicate_display_content(
body = trimmed[colon_index + 2 :].strip() cls,
if len(body) < 80: preferred: dict[str, Any],
return trimmed secondary: dict[str, Any],
if not re.search(r"[A-Za-z\u4e00-\u9fff]", prefix): ) -> str:
return trimmed """Choose an exact input body; never persist the comparison key itself."""
if re.match(r"^(https?|file)$", prefix, flags=re.IGNORECASE): preferred_content = str(preferred.get("content", "") or "")
return trimmed secondary_content = str(secondary.get("content", "") or "")
return body preferred_key = cls._normalize_duplicate_content(preferred_content)
if not preferred_key or preferred_key != cls._normalize_duplicate_content(secondary_content):
return preferred_content
# If one real surface is already the comparison body while the other
# carries an explicit narrative wrapper/footer, reuse that real body.
# This preserves the historical visible answer without manufacturing
# display text from a lossy canonicalization function.
if (
secondary_content.strip() == preferred_key
and preferred_content.strip() != preferred_key
):
return secondary_content
return preferred_content
@staticmethod @staticmethod
def _message_timestamp(message: dict[str, Any]) -> float: def _message_timestamp(message: dict[str, Any]) -> float:
@@ -663,6 +683,9 @@ class ChatStore:
normalized = str(value or "").strip() normalized = str(value or "").strip()
if normalized: if normalized:
keys.add(normalized) keys.add(normalized)
result_delivery_id = str(metadata.get("result_delivery_id", "") or "").strip()
if result_delivery_id:
keys.add(f"result_delivery:{result_delivery_id}")
return keys return keys
@classmethod @classmethod
@@ -681,10 +704,15 @@ class ChatStore:
cls, cls,
existing: dict[str, Any], existing: dict[str, Any],
candidate: dict[str, Any], candidate: dict[str, Any],
*,
prefer_candidate: bool = False,
) -> dict[str, Any]: ) -> dict[str, Any]:
preferred = existing preferred = existing
secondary = candidate secondary = candidate
if cls._message_preference_score(candidate) > cls._message_preference_score(existing): if (
prefer_candidate
or cls._message_preference_score(candidate) > cls._message_preference_score(existing)
):
preferred = candidate preferred = candidate
secondary = existing secondary = existing
@@ -694,12 +722,7 @@ class ChatStore:
secondary_meta = dict(secondary.get("metadata", {}) or {}) secondary_meta = dict(secondary.get("metadata", {}) or {})
preferred_meta = dict(preferred.get("metadata", {}) or {}) preferred_meta = dict(preferred.get("metadata", {}) or {})
merged["metadata"] = {**secondary_meta, **preferred_meta} merged["metadata"] = {**secondary_meta, **preferred_meta}
normalized_content = cls._normalize_duplicate_content(preferred.get("content", "")) merged["content"] = cls._select_duplicate_display_content(preferred, secondary)
if (
normalized_content
and normalized_content == cls._normalize_duplicate_content(secondary.get("content", ""))
):
merged["content"] = normalized_content
shared_ids = cls._message_identity_keys(existing) & cls._message_identity_keys(candidate) shared_ids = cls._message_identity_keys(existing) & cls._message_identity_keys(candidate)
canonical_id = "" canonical_id = ""
@@ -742,7 +765,10 @@ class ChatStore:
return ( return (
str(existing.get("sender", "") or "") == str(candidate.get("sender", "") or "") str(existing.get("sender", "") or "") == str(candidate.get("sender", "") or "")
and str(existing.get("sender_name", "") or "") == str(candidate.get("sender_name", "") or "") and str(existing.get("sender_name", "") or "") == str(candidate.get("sender_name", "") or "")
and cls._normalize_duplicate_content(existing.get("content", "")) == cls._normalize_duplicate_content(candidate.get("content", "")) # Display content is persisted data, not a duplicate-comparison
# key. Exact comparison lets authoritative transcript backfill
# repair a legacy row whose body was destructively normalized.
and str(existing.get("content", "") or "") == str(candidate.get("content", "") or "")
and cls._message_timestamp(existing) == cls._message_timestamp(candidate) and cls._message_timestamp(existing) == cls._message_timestamp(candidate)
and str(existing.get("reply_to_id", "") or "") == str(candidate.get("reply_to_id", "") or "") and str(existing.get("reply_to_id", "") or "") == str(candidate.get("reply_to_id", "") or "")
and list(existing.get("mentions", []) or []) == list(candidate.get("mentions", []) or []) and list(existing.get("mentions", []) or []) == list(candidate.get("mentions", []) or [])
@@ -791,6 +817,55 @@ class ChatStore:
return None return None
return await self._message_scope(str(message_id).strip()) return await self._message_scope(str(message_id).strip())
async def _persist_merged_message(
self,
existing: dict[str, Any],
merged: dict[str, Any],
*,
channel_id: str,
project_id: str,
preserve_timestamp: bool = False,
) -> tuple[dict[str, Any], bool]:
"""Persist a duplicate merge while retaining the mounted cache row.
Semantic transcript duplicates can have a different source message id.
Keeping the existing cache identity (and, for semantic replacement, its
timestamp) upgrades the row in place instead of moving it in the UI.
"""
persisted_id = str(existing.get("message_id", "") or existing.get("id", "") or "")
existing_timestamp = self._message_timestamp(existing)
merged_timestamp = (
existing_timestamp
if preserve_timestamp and existing_timestamp
else self._message_timestamp(merged) or time.time()
)
persisted = {
**merged,
"message_id": persisted_id,
"channel_id": channel_id,
"timestamp": merged_timestamp,
"created_at": merged_timestamp,
}
if self._message_persisted_equal(existing, persisted):
return persisted, False
await self._db.execute(
"UPDATE messages SET sender = ?, sender_name = ?, content = ?, timestamp = ?, "
"reply_to_id = ?, mentions = ?, metadata = ? WHERE message_id = ? AND channel_id = ? AND project_id = ?",
(
persisted["sender"],
persisted["sender_name"],
persisted["content"],
merged_timestamp,
persisted.get("reply_to_id"),
json.dumps(persisted.get("mentions", [])),
json.dumps(persisted.get("metadata", {})),
persisted_id,
channel_id,
project_id,
),
)
return persisted, True
async def _merge_into_same_scope_row( async def _merge_into_same_scope_row(
self, self,
message_id: str, message_id: str,
@@ -798,13 +873,14 @@ class ChatStore:
channel_id: str, channel_id: str,
project_id: str, project_id: str,
candidate: dict[str, Any], candidate: dict[str, Any],
) -> dict[str, Any] | None: prefer_candidate: bool = False,
) -> tuple[dict[str, Any], bool] | None:
"""Merge ``candidate`` into an already-persisted row with the same id/scope. """Merge ``candidate`` into an already-persisted row with the same id/scope.
Returns the merged row when the update happened (or nothing changed), or Returns ``(merged row, materially changed)`` or ``None`` when the row
None when the row could not be loaded. Backfill and the live insert path could not be loaded. Backfill and the live insert path can race on the
can race on the same message id; the duplicate must merge in place, never same message id; the duplicate must merge in place, never be re-inserted
be re-inserted under a scoped alias id in the same channel. under a scoped alias id in the same channel.
""" """
cursor = await self._db.execute( cursor = await self._db.execute(
"SELECT message_id, channel_id, sender, sender_name, content, " "SELECT message_id, channel_id, sender, sender_name, content, "
@@ -816,29 +892,17 @@ class ChatStore:
if row is None: if row is None:
return None return None
existing = self._row_to_message_dict(row) existing = self._row_to_message_dict(row)
merged = self._merge_duplicate_messages(existing, candidate) merged = self._merge_duplicate_messages(
if self._message_persisted_equal(existing, merged): existing,
return merged candidate,
merged_timestamp = self._message_timestamp(merged) or time.time() prefer_candidate=prefer_candidate,
await self._db.execute( )
"UPDATE messages SET sender = ?, sender_name = ?, content = ?, timestamp = ?, " return await self._persist_merged_message(
"reply_to_id = ?, mentions = ?, metadata = ? WHERE message_id = ? AND channel_id = ? AND project_id = ?", existing,
( merged,
merged["sender"], channel_id=channel_id,
merged["sender_name"], project_id=project_id,
merged["content"],
merged_timestamp,
merged.get("reply_to_id"),
json.dumps(merged.get("mentions", [])),
json.dumps(merged.get("metadata", {})),
message_id,
channel_id,
project_id,
),
) )
merged["timestamp"] = merged_timestamp
merged["created_at"] = merged_timestamp
return merged
async def _allocate_scoped_message_id( async def _allocate_scoped_message_id(
self, self,
@@ -1581,35 +1645,24 @@ class ChatStore:
existing_index = existing_positions.get(mid) existing_index = existing_positions.get(mid)
if existing_index is not None: if existing_index is not None:
existing_match = existing_messages[existing_index] existing_match = existing_messages[existing_index]
merged_existing = self._merge_duplicate_messages(existing_match, normalized_message) # This candidate came directly from the durable transcript.
if not self._message_persisted_equal(existing_match, merged_existing): # For the same identity its original display body is
merged_timestamp = self._message_timestamp(merged_existing) or time.time() # authoritative, while metadata unique to the cache is
await self._db.execute( # still retained by the merge.
"UPDATE messages SET sender = ?, sender_name = ?, content = ?, timestamp = ?, " merged_existing = self._merge_duplicate_messages(
"reply_to_id = ?, mentions = ?, metadata = ? WHERE message_id = ? AND channel_id = ? AND project_id = ?", existing_match,
( normalized_message,
merged_existing["sender"], prefer_candidate=True,
merged_existing["sender_name"], )
merged_existing["content"], persisted, did_change = await self._persist_merged_message(
merged_timestamp, existing_match,
merged_existing.get("reply_to_id"), merged_existing,
json.dumps(merged_existing.get("mentions", [])), channel_id=channel_id,
json.dumps(merged_existing.get("metadata", {})), project_id=project_id,
mid, )
channel_id, if did_change:
project_id, semantic_index.replace(existing_index, persisted)
), inserted_messages.append(persisted)
)
semantic_index.replace(existing_index, {
**merged_existing,
"created_at": merged_timestamp,
})
inserted_messages.append({
**merged_existing,
"channel_id": channel_id,
"timestamp": merged_timestamp,
"created_at": merged_timestamp,
})
changed_existing = True changed_existing = True
continue continue
@@ -1623,10 +1676,15 @@ class ChatStore:
channel_id=channel_id, channel_id=channel_id,
project_id=project_id, project_id=project_id,
candidate=normalized_message, candidate=normalized_message,
prefer_candidate=True,
) )
if merged is not None: if merged is not None:
persisted, did_change = merged
existing_ids.add(mid) existing_ids.add(mid)
existing_positions[mid] = semantic_index.append(merged) existing_positions[mid] = semantic_index.append(persisted)
if did_change:
inserted_messages.append(persisted)
changed_existing = True
continue continue
if existing_scope and existing_scope != (channel_id, project_id): if existing_scope and existing_scope != (channel_id, project_id):
metadata = dict(normalized_message.get("metadata", {}) or {}) metadata = dict(normalized_message.get("metadata", {}) or {})
@@ -1644,9 +1702,33 @@ class ChatStore:
excluded_message_ids=consumed_existing_ids, excluded_message_ids=consumed_existing_ids,
) )
if duplicate_index is not None: if duplicate_index is not None:
consumed_existing_ids.add( existing_duplicate = existing_messages[duplicate_index]
existing_messages[duplicate_index]["message_id"] existing_id = str(existing_duplicate["message_id"])
# Prefer the authoritative transcript on an equal score, but
# do not replace a stronger canonical result surface with a
# lower-priority mirror. The existing cache id and timestamp
# remain stable either way.
prefer_candidate = (
self._message_preference_score(normalized_message)
>= self._message_preference_score(existing_duplicate)
) )
merged_duplicate = self._merge_duplicate_messages(
existing_duplicate,
normalized_message,
prefer_candidate=prefer_candidate,
)
persisted, did_change = await self._persist_merged_message(
existing_duplicate,
merged_duplicate,
channel_id=channel_id,
project_id=project_id,
preserve_timestamp=True,
)
if did_change:
semantic_index.replace(duplicate_index, persisted)
inserted_messages.append(persisted)
changed_existing = True
consumed_existing_ids.add(existing_id)
continue continue
try: try:
@@ -1674,11 +1756,16 @@ class ChatStore:
channel_id=channel_id, channel_id=channel_id,
project_id=project_id, project_id=project_id,
candidate=normalized_message, candidate=normalized_message,
prefer_candidate=True,
) )
if merged is not None: if merged is not None:
persisted, did_change = merged
merged_id = normalized_message["message_id"] merged_id = normalized_message["message_id"]
existing_ids.add(merged_id) existing_ids.add(merged_id)
existing_positions[merged_id] = semantic_index.append(merged) existing_positions[merged_id] = semantic_index.append(persisted)
if did_change:
inserted_messages.append(persisted)
changed_existing = True
continue continue
metadata = dict(normalized_message.get("metadata", {}) or {}) metadata = dict(normalized_message.get("metadata", {}) or {})
metadata.setdefault("ui_message_id", normalized_message["message_id"]) metadata.setdefault("ui_message_id", normalized_message["message_id"])
@@ -1,12 +1,12 @@
import{g as da,r as B3}from"./phaser-DFK5Ua9d.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&i(a)}).observe(document,{childList:!0,subtree:!0});function n(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(r){if(r.ep)return;r.ep=!0;const o=n(r);fetch(r.href,o)}})();var lg={exports:{}},Mc={};var vk;function $3(){if(vk)return Mc;vk=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(i,r,o){var a=null;if(o!==void 0&&(a=""+o),r.key!==void 0&&(a=""+r.key),"key"in r){o={};for(var c in r)c!=="key"&&(o[c]=r[c])}else o=r;return r=o.ref,{$$typeof:e,type:i,key:a,ref:r!==void 0?r:null,props:o}}return Mc.Fragment=t,Mc.jsx=n,Mc.jsxs=n,Mc}var bk;function H3(){return bk||(bk=1,lg.exports=$3()),lg.exports}var u=H3(),cg={exports:{}},St={};var _k;function F3(){if(_k)return St;_k=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),a=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),p=Symbol.for("react.activity"),g=Symbol.iterator;function x(U){return U===null||typeof U!="object"?null:(U=g&&U[g]||U["@@iterator"],typeof U=="function"?U:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},b=Object.assign,k={};function w(U,Z,F){this.props=U,this.context=Z,this.refs=k,this.updater=F||v}w.prototype.isReactComponent={},w.prototype.setState=function(U,Z){if(typeof U!="object"&&typeof U!="function"&&U!=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,U,Z,"setState")},w.prototype.forceUpdate=function(U){this.updater.enqueueForceUpdate(this,U,"forceUpdate")};function S(){}S.prototype=w.prototype;function j(U,Z,F){this.props=U,this.context=Z,this.refs=k,this.updater=F||v}var N=j.prototype=new S;N.constructor=j,b(N,w.prototype),N.isPureReactComponent=!0;var O=Array.isArray;function R(){}var D={H:null,A:null,T:null,S:null},I=Object.prototype.hasOwnProperty;function L(U,Z,F){var K=F.ref;return{$$typeof:e,type:U,key:Z,ref:K!==void 0?K:null,props:F}}function M(U,Z){return L(U.type,Z,U.props)}function A(U){return typeof U=="object"&&U!==null&&U.$$typeof===e}function B(U){var Z={"=":"=0",":":"=2"};return"$"+U.replace(/[=:]/g,function(F){return Z[F]})}var W=/\/+/g;function P(U,Z){return typeof U=="object"&&U!==null&&U.key!=null?B(""+U.key):Z.toString(36)}function G(U){switch(U.status){case"fulfilled":return U.value;case"rejected":throw U.reason;default:switch(typeof U.status=="string"?U.then(R,R):(U.status="pending",U.then(function(Z){U.status==="pending"&&(U.status="fulfilled",U.value=Z)},function(Z){U.status==="pending"&&(U.status="rejected",U.reason=Z)})),U.status){case"fulfilled":return U.value;case"rejected":throw U.reason}}throw U}function $(U,Z,F,K,ee){var te=typeof U;(te==="undefined"||te==="boolean")&&(U=null);var se=!1;if(U===null)se=!0;else switch(te){case"bigint":case"string":case"number":se=!0;break;case"object":switch(U.$$typeof){case e:case t:se=!0;break;case h:return se=U._init,$(se(U._payload),Z,F,K,ee)}}if(se)return ee=ee(U),se=K===""?"."+P(U,0):K,O(ee)?(F="",se!=null&&(F=se.replace(W,"$&/")+"/"),$(ee,Z,F,"",function(ie){return ie})):ee!=null&&(A(ee)&&(ee=M(ee,F+(ee.key==null||U&&U.key===ee.key?"":(""+ee.key).replace(W,"$&/")+"/")+se)),Z.push(ee)),1;se=0;var ae=K===""?".":K+":";if(O(U))for(var ue=0;ue<U.length;ue++)K=U[ue],te=ae+P(K,ue),se+=$(K,Z,F,te,ee);else if(ue=x(U),typeof ue=="function")for(U=ue.call(U),ue=0;!(K=U.next()).done;)K=K.value,te=ae+P(K,ue++),se+=$(K,Z,F,te,ee);else if(te==="object"){if(typeof U.then=="function")return $(G(U),Z,F,K,ee);throw Z=String(U),Error("Objects are not valid as a React child (found: "+(Z==="[object Object]"?"object with keys {"+Object.keys(U).join(", ")+"}":Z)+"). If you meant to render a collection of children, use an array instead.")}return se}function q(U,Z,F){if(U==null)return U;var K=[],ee=0;return $(U,K,"","",function(te){return Z.call(F,te,ee++)}),K}function Y(U){if(U._status===-1){var Z=U._result;Z=Z(),Z.then(function(F){(U._status===0||U._status===-1)&&(U._status=1,U._result=F)},function(F){(U._status===0||U._status===-1)&&(U._status=2,U._result=F)}),U._status===-1&&(U._status=0,U._result=Z)}if(U._status===1)return U._reLine truncated import{g as ma,r as WM}from"./phaser-DFK5Ua9d.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&i(a)}).observe(document,{childList:!0,subtree:!0});function n(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(r){if(r.ep)return;r.ep=!0;const o=n(r);fetch(r.href,o)}})();var lg={exports:{}},Mc={};var Ck;function YM(){if(Ck)return Mc;Ck=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(i,r,o){var a=null;if(o!==void 0&&(a=""+o),r.key!==void 0&&(a=""+r.key),"key"in r){o={};for(var c in r)c!=="key"&&(o[c]=r[c])}else o=r;return r=o.ref,{$$typeof:e,type:i,key:a,ref:r!==void 0?r:null,props:o}}return Mc.Fragment=t,Mc.jsx=n,Mc.jsxs=n,Mc}var jk;function XM(){return jk||(jk=1,lg.exports=YM()),lg.exports}var u=XM(),cg={exports:{}},St={};var Ek;function KM(){if(Ek)return St;Ek=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),a=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),p=Symbol.for("react.activity"),g=Symbol.iterator;function x(U){return U===null||typeof U!="object"?null:(U=g&&U[g]||U["@@iterator"],typeof U=="function"?U:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,k={};function w(U,Z,F){this.props=U,this.context=Z,this.refs=k,this.updater=F||v}w.prototype.isReactComponent={},w.prototype.setState=function(U,Z){if(typeof U!="object"&&typeof U!="function"&&U!=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,U,Z,"setState")},w.prototype.forceUpdate=function(U){this.updater.enqueueForceUpdate(this,U,"forceUpdate")};function S(){}S.prototype=w.prototype;function j(U,Z,F){this.props=U,this.context=Z,this.refs=k,this.updater=F||v}var N=j.prototype=new S;N.constructor=j,_(N,w.prototype),N.isPureReactComponent=!0;var O=Array.isArray;function R(){}var D={H:null,A:null,T:null,S:null},I=Object.prototype.hasOwnProperty;function L(U,Z,F){var K=F.ref;return{$$typeof:e,type:U,key:Z,ref:K!==void 0?K:null,props:F}}function M(U,Z){return L(U.type,Z,U.props)}function A(U){return typeof U=="object"&&U!==null&&U.$$typeof===e}function B(U){var Z={"=":"=0",":":"=2"};return"$"+U.replace(/[=:]/g,function(F){return Z[F]})}var W=/\/+/g;function P(U,Z){return typeof U=="object"&&U!==null&&U.key!=null?B(""+U.key):Z.toString(36)}function G(U){switch(U.status){case"fulfilled":return U.value;case"rejected":throw U.reason;default:switch(typeof U.status=="string"?U.then(R,R):(U.status="pending",U.then(function(Z){U.status==="pending"&&(U.status="fulfilled",U.value=Z)},function(Z){U.status==="pending"&&(U.status="rejected",U.reason=Z)})),U.status){case"fulfilled":return U.value;case"rejected":throw U.reason}}throw U}function $(U,Z,F,K,ee){var te=typeof U;(te==="undefined"||te==="boolean")&&(U=null);var se=!1;if(U===null)se=!0;else switch(te){case"bigint":case"string":case"number":se=!0;break;case"object":switch(U.$$typeof){case e:case t:se=!0;break;case h:return se=U._init,$(se(U._payload),Z,F,K,ee)}}if(se)return ee=ee(U),se=K===""?"."+P(U,0):K,O(ee)?(F="",se!=null&&(F=se.replace(W,"$&/")+"/"),$(ee,Z,F,"",function(ie){return ie})):ee!=null&&(A(ee)&&(ee=M(ee,F+(ee.key==null||U&&U.key===ee.key?"":(""+ee.key).replace(W,"$&/")+"/")+se)),Z.push(ee)),1;se=0;var ae=K===""?".":K+":";if(O(U))for(var ue=0;ue<U.length;ue++)K=U[ue],te=ae+P(K,ue),se+=$(K,Z,F,te,ee);else if(ue=x(U),typeof ue=="function")for(U=ue.call(U),ue=0;!(K=U.next()).done;)K=K.value,te=ae+P(K,ue++),se+=$(K,Z,F,te,ee);else if(te==="object"){if(typeof U.then=="function")return $(G(U),Z,F,K,ee);throw Z=String(U),Error("Objects are not valid as a React child (found: "+(Z==="[object Object]"?"object with keys {"+Object.keys(U).join(", ")+"}":Z)+"). If you meant to render a collection of children, use an array instead.")}return se}function q(U,Z,F){if(U==null)return U;var K=[],ee=0;return $(U,K,"","",function(te){return Z.call(F,te,ee++)}),K}function Y(U){if(U._status===-1){var Z=U._result;Z=Z(),Z.then(function(F){(U._status===0||U._status===-1)&&(U._status=1,U._result=F)},function(F){(U._status===0||U._status===-1)&&(U._status=2,U._result=F)}),U._status===-1&&(U._status=0,U._result=Z)}if(U._status===1)return U._reLine truncated
at`)?" (<anonymous>)":-1<f.stack.indexOf("@")?"@unknown:0:0":""}return` at`)?" (<anonymous>)":-1<f.stack.indexOf("@")?"@unknown:0:0":""}return`
`+je+s+Te}var Ze=!1;function Ye(s,l){if(!s||Ze)return"";Ze=!0;var f=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var y={DetermineComponentFrameRoot:function(){try{if(l){var Ne=function(){throw Error()};if(Object.defineProperty(Ne.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ne,[])}catch(_e){var xe=_e}Reflect.construct(s,[],Ne)}else{try{Ne.call()}catch(_e){xe=_e}s.call(Ne.prototype)}}else{try{throw Error()}catch(_e){xe=_e}(Ne=s())&&typeof Ne.catch=="function"&&Ne.catch(function(){})}}catch(_e){if(_e&&xe&&typeof _e.stack=="string")return[_e.stack,xe.stack]}return[null,null]}};y.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var _=Object.getOwnPropertyDescriptor(y.DetermineComponentFrameRoot,"name");_&&_.configurable&&Object.defineProperty(y.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var E=y.DetermineComponentFrameRoot(),H=E[0],X=E[1];if(H&&X){var re=H.split(` `+je+s+Te}var Ze=!1;function Xe(s,l){if(!s||Ze)return"";Ze=!0;var f=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var y={DetermineComponentFrameRoot:function(){try{if(l){var Ne=function(){throw Error()};if(Object.defineProperty(Ne.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ne,[])}catch(_e){var xe=_e}Reflect.construct(s,[],Ne)}else{try{Ne.call()}catch(_e){xe=_e}s.call(Ne.prototype)}}else{try{throw Error()}catch(_e){xe=_e}(Ne=s())&&typeof Ne.catch=="function"&&Ne.catch(function(){})}}catch(_e){if(_e&&xe&&typeof _e.stack=="string")return[_e.stack,xe.stack]}return[null,null]}};y.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var b=Object.getOwnPropertyDescriptor(y.DetermineComponentFrameRoot,"name");b&&b.configurable&&Object.defineProperty(y.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var E=y.DetermineComponentFrameRoot(),H=E[0],X=E[1];if(H&&X){var re=H.split(`
`),ye=X.split(` `),ye=X.split(`
`);for(_=y=0;y<re.length&&!re[y].includes("DetermineComponentFrameRoot");)y++;for(;_<ye.length&&!ye[_].includes("DetermineComponentFrameRoot");)_++;if(y===re.length||_===ye.length)for(y=re.length-1,_=ye.length-1;1<=y&&0<=_&&re[y]!==ye[_];)_--;for(;1<=y&&0<=_;y--,_--)if(re[y]!==ye[_]){if(y!==1||_!==1)do if(y--,_--,0>_||re[y]!==ye[_]){var Ce=` `);for(b=y=0;y<re.length&&!re[y].includes("DetermineComponentFrameRoot");)y++;for(;b<ye.length&&!ye[b].includes("DetermineComponentFrameRoot");)b++;if(y===re.length||b===ye.length)for(y=re.length-1,b=ye.length-1;1<=y&&0<=b&&re[y]!==ye[b];)b--;for(;1<=y&&0<=b;y--,b--)if(re[y]!==ye[b]){if(y!==1||b!==1)do if(y--,b--,0>b||re[y]!==ye[b]){var Ce=`
`+re[y].replace(" at new "," at ");return s.displayName&&Ce.includes("<anonymous>")&&(Ce=Ce.replace("<anonymous>",s.displayName)),Ce}while(1<=y&&0<=_);break}}}finally{Ze=!1,Error.prepareStackTrace=f}return(f=s?s.displayName||s.name:"")?Ge(f):""}function mt(s,l){switch(s.tag){case 26:case 27:case 5:return Ge(s.type);case 16:return Ge("Lazy");case 13:return s.child!==l&&l!==null?Ge("Suspense Fallback"):Ge("Suspense");case 19:return Ge("SuspenseList");case 0:case 15:return Ye(s.type,!1);case 11:return Ye(s.type.render,!1);case 1:return Ye(s.type,!0);case 31:return Ge("Activity");default:return""}}function Ft(s){try{var l="",f=null;do l+=mt(s,f),f=s,s=s.return;while(s);return l}catch(y){return` `+re[y].replace(" at new "," at ");return s.displayName&&Ce.includes("<anonymous>")&&(Ce=Ce.replace("<anonymous>",s.displayName)),Ce}while(1<=y&&0<=b);break}}}finally{Ze=!1,Error.prepareStackTrace=f}return(f=s?s.displayName||s.name:"")?Ge(f):""}function mt(s,l){switch(s.tag){case 26:case 27:case 5:return Ge(s.type);case 16:return Ge("Lazy");case 13:return s.child!==l&&l!==null?Ge("Suspense Fallback"):Ge("Suspense");case 19:return Ge("SuspenseList");case 0:case 15:return Xe(s.type,!1);case 11:return Xe(s.type.render,!1);case 1:return Xe(s.type,!0);case 31:return Ge("Activity");default:return""}}function Ft(s){try{var l="",f=null;do l+=mt(s,f),f=s,s=s.return;while(s);return l}catch(y){return`
Error generating stack: `+y.message+` Error generating stack: `+y.message+`
`+y.stack}}var Mt=Object.prototype.hasOwnProperty,jt=e.unstable_scheduleCallback,he=e.unstable_cancelCallback,ze=e.unstable_shouldYield,ot=e.unstable_requestPaint,Ve=e.unstable_now,lt=e.unstable_getCurrentPriorityLevel,me=e.unstable_ImmediatePriority,be=e.unstable_UserBlockingPriority,Ae=e.unstable_NormalPriority,Be=e.unstable_LowPriority,We=e.unstable_IdlePriority,Lt=e.log,pt=e.unstable_setDisableYieldValue,ke=null,qe=null;function Qe(s){if(typeof Lt=="function"&&pt(s),qe&&typeof qe.setStrictMode=="function")try{qe.setStrictMode(ke,s)}catch{}}var $e=Math.clz32?Math.clz32:ei,He=Math.log,Vt=Math.LN2;function ei(s){return s>>>=0,s===0?32:31-(He(s)/Vt|0)|0}var vt=256,bt=262144,vn=4194304;function On(s){var l=s&42;if(l!==0)return l;switch(s&-s){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 s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function wt(s,l,f){var y=s.pendingLanes;if(y===0)return 0;var _=0,E=s.suspendedLanes,H=s.pingedLanes;s=s.warmLanes;var X=y&134217727;return X!==0?(y=X&~E,y!==0?_=On(y):(H&=X,H!==0?_=On(H):f||(f=X&~s,f!==0&&(_=On(f))))):(X=y&~E,X!==0?_=On(X):H!==0?_=On(H):f||(f=y&~s,f!==0&&(_=On(f)))),_===0?0:l!==0&&l!==_&&(l&E)===0&&(E=_&-_,f=l&-l,E>=f||E===32&&(f&4194048)!==0)?l:_}function zt(s,l){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&l)===0}function Hn(s,l){switch(s){case 1:case 2:case 4:case 8:case 64:return l+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 l+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 Me(){var s=vn;return vn<<=1,(vn&62914560)===0&&(vn=4194304),s}function ht(s){for(var l=[],f=0;31>f;f++)l.push(s);return l}function gt(s,l){s.pendingLanes|=l,l!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function fi(s,l,f,y,_,E){var H=s.pendingLanes;s.pendingLanes=f,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=f,s.entangledLanes&=f,s.errorRecoveryDisabledLanes&=f,s.shellSuspendCounter=0;var X=s.entanglements,re=s.expirationTimes,ye=s.hiddenUpdates;for(f=H&~f;0<f;){var Ce=31-$e(f),Ne=1<<Ce;X[Ce]=0,re[Ce]=-1;var xe=ye[Ce];if(xe!==null)for(ye[Ce]=null,Ce=0;Ce<xe.length;Ce++){var _e=xe[Ce];_e!==null&&(_e.lane&=-536870913)}f&=~Ne}y!==0&&Vn(s,y,0),E!==0&&_===0&&s.tag!==0&&(s.suspendedLanes|=E&~(H&~l))}function Vn(s,l,f){s.pendingLanes|=l,s.suspendedLanes&=~l;var y=31-$e(l);s.entangledLanes|=l,s.entanglements[y]=s.entanglements[y]|1073741824|f&261930}function pn(s,l){var f=s.entangledLanes|=l;for(s=s.entanglements;f;){var y=31-$e(f),_=1<<y;_&l|s[y]&l&&(s[y]|=l),f&=~_}}function Fn(s,l){var f=l&-l;return f=(f&42)!==0?1:tt(f),(f&(s.suspendedLanes|l))!==0?0:f}function tt(s){switch(s){case 2:s=1;break;case 8:s=4;break;case 32:s=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:s=128;break;case 268435456:s=134217728;break;default:s=0}return s}function mi(s){return s&=-s,2<s?8<s?(s&134217727)!==0?32:268435456:8:2}function Si(){var s=q.p;return s!==0?s:(s=window.event,s===void 0?32:fk(s.type))}function Rn(s,l){var f=q.p;try{return q.p=s,l()}finally{q.p=f}}var wn=Math.random().toString(36).slice(2),$t="__reactFiber$"+wn,Cn="__reactProps$"+wn,Xt="__reactContainer$"+wn,Re="__reactEvents$"+wn,kt="__reactListeners$"+wn,bn="__reactHandles$"+wn,wi="__reactResources$"+wn,In="__reactMarker$"+wn;function It(s){delete s[$t],delete s[Cn],delete s[Re],delete s[kt],delete s[bn]}function yi(s){var l=s[$t];if(l)return l;for(var f=s.parentNode;f;){if(l=f[Xt]||f[$t]){if(f=l.alternate,l.child!==null||f!==null&&f.child!==null)for(s=K_(s);s!==null;){if(f=s[$t])return f;s=K_(s)}return l}s=f,f=s.parentNode}return null}function Zn(s){if(s=s[$t]||s[Xt]){var l=s.tag;if(l===5||l===6||l===13||l===31||l===26||l===27||l===3)return s}return null}function ti(s){var l=s.tag;if(l===5||l===26||l===27||l===6)return s.stateNode;throw Error(i(33))}function ln(s){var l=s[wi];return l||(l=s[wi]={hoistableStyles:new Map,hoistableScripts:new Map}),l}function Kt(s){s[In]=!0}var Tt=new Set,Zt={};function Un(s,l){dn(s,l),dn(s+"Capture",l)}function dn(s,l){for(Zt[s]=l,s=0;s<l.length;s++)Tt.add(l[s])}var Je=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u2 Line truncated `+y.stack}}var Dt=Object.prototype.hasOwnProperty,jt=e.unstable_scheduleCallback,he=e.unstable_cancelCallback,ze=e.unstable_shouldYield,ot=e.unstable_requestPaint,Ve=e.unstable_now,lt=e.unstable_getCurrentPriorityLevel,me=e.unstable_ImmediatePriority,be=e.unstable_UserBlockingPriority,Ae=e.unstable_NormalPriority,Be=e.unstable_LowPriority,We=e.unstable_IdlePriority,zt=e.log,ht=e.unstable_setDisableYieldValue,ke=null,qe=null;function Qe(s){if(typeof zt=="function"&&ht(s),qe&&typeof qe.setStrictMode=="function")try{qe.setStrictMode(ke,s)}catch{}}var $e=Math.clz32?Math.clz32:ei,Fe=Math.log,Vt=Math.LN2;function ei(s){return s>>>=0,s===0?32:31-(Fe(s)/Vt|0)|0}var vt=256,bt=262144,vn=4194304;function On(s){var l=s&42;if(l!==0)return l;switch(s&-s){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 s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function wt(s,l,f){var y=s.pendingLanes;if(y===0)return 0;var b=0,E=s.suspendedLanes,H=s.pingedLanes;s=s.warmLanes;var X=y&134217727;return X!==0?(y=X&~E,y!==0?b=On(y):(H&=X,H!==0?b=On(H):f||(f=X&~s,f!==0&&(b=On(f))))):(X=y&~E,X!==0?b=On(X):H!==0?b=On(H):f||(f=y&~s,f!==0&&(b=On(f)))),b===0?0:l!==0&&l!==b&&(l&E)===0&&(E=b&-b,f=l&-l,E>=f||E===32&&(f&4194048)!==0)?l:b}function Pt(s,l){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&l)===0}function Hn(s,l){switch(s){case 1:case 2:case 4:case 8:case 64:return l+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 l+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 Me(){var s=vn;return vn<<=1,(vn&62914560)===0&&(vn=4194304),s}function gt(s){for(var l=[],f=0;31>f;f++)l.push(s);return l}function pt(s,l){s.pendingLanes|=l,l!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function mi(s,l,f,y,b,E){var H=s.pendingLanes;s.pendingLanes=f,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=f,s.entangledLanes&=f,s.errorRecoveryDisabledLanes&=f,s.shellSuspendCounter=0;var X=s.entanglements,re=s.expirationTimes,ye=s.hiddenUpdates;for(f=H&~f;0<f;){var Ce=31-$e(f),Ne=1<<Ce;X[Ce]=0,re[Ce]=-1;var xe=ye[Ce];if(xe!==null)for(ye[Ce]=null,Ce=0;Ce<xe.length;Ce++){var _e=xe[Ce];_e!==null&&(_e.lane&=-536870913)}f&=~Ne}y!==0&&Vn(s,y,0),E!==0&&b===0&&s.tag!==0&&(s.suspendedLanes|=E&~(H&~l))}function Vn(s,l,f){s.pendingLanes|=l,s.suspendedLanes&=~l;var y=31-$e(l);s.entangledLanes|=l,s.entanglements[y]=s.entanglements[y]|1073741824|f&261930}function pn(s,l){var f=s.entangledLanes|=l;for(s=s.entanglements;f;){var y=31-$e(f),b=1<<y;b&l|s[y]&l&&(s[y]|=l),f&=~b}}function Fn(s,l){var f=l&-l;return f=(f&42)!==0?1:tt(f),(f&(s.suspendedLanes|l))!==0?0:f}function tt(s){switch(s){case 2:s=1;break;case 8:s=4;break;case 32:s=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:s=128;break;case 268435456:s=134217728;break;default:s=0}return s}function pi(s){return s&=-s,2<s?8<s?(s&134217727)!==0?32:268435456:8:2}function Si(){var s=q.p;return s!==0?s:(s=window.event,s===void 0?32:xk(s.type))}function Rn(s,l){var f=q.p;try{return q.p=s,l()}finally{q.p=f}}var wn=Math.random().toString(36).slice(2),Ht="__reactFiber$"+wn,Cn="__reactProps$"+wn,Wt="__reactContainer$"+wn,Re="__reactEvents$"+wn,kt="__reactListeners$"+wn,bn="__reactHandles$"+wn,wi="__reactResources$"+wn,In="__reactMarker$"+wn;function It(s){delete s[Ht],delete s[Cn],delete s[Re],delete s[kt],delete s[bn]}function yi(s){var l=s[Ht];if(l)return l;for(var f=s.parentNode;f;){if(l=f[Wt]||f[Ht]){if(f=l.alternate,l.child!==null||f!==null&&f.child!==null)for(s=nk(s);s!==null;){if(f=s[Ht])return f;s=nk(s)}return l}s=f,f=s.parentNode}return null}function Zn(s){if(s=s[Ht]||s[Wt]){var l=s.tag;if(l===5||l===6||l===13||l===31||l===26||l===27||l===3)return s}return null}function ti(s){var l=s.tag;if(l===5||l===26||l===27||l===6)return s.stateNode;throw Error(i(33))}function ln(s){var l=s[wi];return l||(l=s[wi]={hoistableStyles:new Map,hoistableScripts:new Map}),l}function Yt(s){s[In]=!0}var Tt=new Set,Xt={};function Un(s,l){dn(s,l),dn(s+"Capture",l)}function dn(s,l){for(Xt[s]=l,s=0;s<l.length;s++)Tt.add(l[s])}var Je=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u2 Line truncated
`).replace(a3,"")}function $_(s,l){return l=B_(l),B_(s)===l}function kn(s,l,f,y,_,E){switch(f){case"children":typeof y=="string"?l==="body"||l==="textarea"&&y===""||nt(s,y):(typeof y=="number"||typeof y=="bigint")&&l!=="body"&&nt(s,""+y);break;case"className":Gn(s,"class",y);break;case"tabIndex":Gn(s,"tabindex",y);break;case"dir":case"role":case"viewBox":case"width":case"height":Gn(s,f,y);break;case"style":qn(s,y,E);break;case"data":if(l!=="object"){Gn(s,"data",y);break}case"src":case"href":if(y===""&&(l!=="a"||f!=="href")){s.removeAttribute(f);break}if(y==null||typeof y=="function"||typeof y=="symbol"||typeof y=="boolean"){s.removeAttribute(f);break}y=Ui(""+y),s.setAttribute(f,y);break;case"action":case"formAction":if(typeof y=="function"){s.setAttribute(f,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof E=="function"&&(f==="formAction"?(l!=="input"&&kn(s,l,"name",_.name,_,null),kn(s,l,"formEncType",_.formEncType,_,null),kn(s,l,"formMethod",_.formMethod,_,null),kn(s,l,"formTarget",_.formTarget,_,null)):(kn(s,l,"encType",_.encType,_,null),kn(s,l,"method",_.method,_,null),kn(s,l,"target",_.target,_,null)));if(y==null||typeof y=="symbol"||typeof y=="boolean"){s.removeAttribute(f);break}y=Ui(""+y),s.setAttribute(f,y);break;case"onClick":y!=null&&(s.onclick=Gi);break;case"onScroll":y!=null&&Wt("scroll",s);break;case"onScrollEnd":y!=null&&Wt("scrollend",s);break;case"dangerouslySetInnerHTML":if(y!=null){if(typeof y!="object"||!("__html"in y))throw Error(i(61));if(f=y.__html,f!=null){if(_.children!=null)throw Error(i(60));s.innerHTML=f}}break;case"multiple":s.multiple=y&&typeof y!="function"&&typeof y!="symbol";break;case"muted":s.muted=y&&typeof y!="function"&&typeof y!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(y==null||typeof y=="function"||typeof y=="boolean"||typeof y=="symbol"){s.removeAttribute("xlink:href");break}f=Ui(""+y),s.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",f);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":y!=null&&typeof y!="function"&&typeof y!="symbol"?s.setAttribute(f,""+y):s.removeAttribute(f);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":y&&typeof y!="function"&&typeof y!="symbol"?s.setAttribute(f,""):s.removeAttribute(f);break;case"capture":case"download":y===!0?s.setAttribute(f,""):y!==!1&&y!=null&&typeof y!="function"&&typeof y!="symbol"?s.setAttribute(f,y):s.removeAttribute(f);break;case"cols":case"rows":case"size":case"span":y!=null&&typeof y!="function"&&typeof y!="symbol"&&!isNaN(y)&&1<=y?s.setAttribute(f,y):s.removeAttribute(f);break;case"rowSpan":case"start":y==null||typeof y=="function"||typeof y=="symbol"||isNaN(y)?s.removeAttribute(f):s.setAttribute(f,y);break;case"popover":Wt("beforetoggle",s),Wt("toggle",s),An(s,"popover",y);break;case"xlinkActuate":jn(s,"http://www.w3.org/1999/xlink","xlink:actuate",y);break;case"xlinkArcrole":jn(s,"http://www.w3.org/1999/xlink","xlink:arcrole",y);break;case"xlinkRole":jn(s,"http://www.w3.org/1999/xlink","xlink:role",y);break;case"xlinkShow":jn(s,"http://www.w3.org/1999/xlink","xlink:show",y);break;case"xlinkTitle":jn(s,"http://www.w3.org/1999/xlink","xlink:title",y);break;case"xlinkType":jn(s,"http://www.w3.org/1999/xlink","xlink:type",y);break;case"xmlBase":jn(s,"http://www.w3.org/XML/1998/namespace","xml:base",y);break;case"xmlLang":jn(s,"http://www.w3.org/XML/1998/namespace","xml:lang",y);break;case"xmlSpace":jn(s,"http://www.w3.org/XML/1998/namespace","xml:space",y);break;case"is":An(s,"is",y);break;case"innerText":case"textContent":break;default:(!(2<f.length)||f[0]!=="o"&&f[0]!=="O"||f[1]!=="n"&&f[1]!=="N")&&(f=tn.get(f)||f,An(s,f,y))}}function Uh(s,l,f,y,_,E){switch(f){case"style":qn(s,y,E);break;case"dangerouslySetInnerHTML":if(y!=null){if(typeof y!="object"||!("__html"in y))throw Error(i(61));if(f=y.__html,f!=null){if(_.children!=null)throw Error(i(60));s.innerHTML=f}}break;case"children":typeof y=="string"?nt(s,y):(typeof y=="number"||typeof y=="bigint")&&nt(s,""+y);break;case"onScroll":y!=null&&Wt("scroll",s);break;case"onScrollEnd":y!=null&&Wt("scrollend",s);break;case"onClick":y!=null&&(s.onclick=Gi);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"inne Line truncated `).replace(hM,"")}function q_(s,l){return l=G_(l),G_(s)===l}function kn(s,l,f,y,b,E){switch(f){case"children":typeof y=="string"?l==="body"||l==="textarea"&&y===""||nt(s,y):(typeof y=="number"||typeof y=="bigint")&&l!=="body"&&nt(s,""+y);break;case"className":Gn(s,"class",y);break;case"tabIndex":Gn(s,"tabindex",y);break;case"dir":case"role":case"viewBox":case"width":case"height":Gn(s,f,y);break;case"style":qn(s,y,E);break;case"data":if(l!=="object"){Gn(s,"data",y);break}case"src":case"href":if(y===""&&(l!=="a"||f!=="href")){s.removeAttribute(f);break}if(y==null||typeof y=="function"||typeof y=="symbol"||typeof y=="boolean"){s.removeAttribute(f);break}y=Vi(""+y),s.setAttribute(f,y);break;case"action":case"formAction":if(typeof y=="function"){s.setAttribute(f,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof E=="function"&&(f==="formAction"?(l!=="input"&&kn(s,l,"name",b.name,b,null),kn(s,l,"formEncType",b.formEncType,b,null),kn(s,l,"formMethod",b.formMethod,b,null),kn(s,l,"formTarget",b.formTarget,b,null)):(kn(s,l,"encType",b.encType,b,null),kn(s,l,"method",b.method,b,null),kn(s,l,"target",b.target,b,null)));if(y==null||typeof y=="symbol"||typeof y=="boolean"){s.removeAttribute(f);break}y=Vi(""+y),s.setAttribute(f,y);break;case"onClick":y!=null&&(s.onclick=Ui);break;case"onScroll":y!=null&&Gt("scroll",s);break;case"onScrollEnd":y!=null&&Gt("scrollend",s);break;case"dangerouslySetInnerHTML":if(y!=null){if(typeof y!="object"||!("__html"in y))throw Error(i(61));if(f=y.__html,f!=null){if(b.children!=null)throw Error(i(60));s.innerHTML=f}}break;case"multiple":s.multiple=y&&typeof y!="function"&&typeof y!="symbol";break;case"muted":s.muted=y&&typeof y!="function"&&typeof y!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(y==null||typeof y=="function"||typeof y=="boolean"||typeof y=="symbol"){s.removeAttribute("xlink:href");break}f=Vi(""+y),s.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",f);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":y!=null&&typeof y!="function"&&typeof y!="symbol"?s.setAttribute(f,""+y):s.removeAttribute(f);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":y&&typeof y!="function"&&typeof y!="symbol"?s.setAttribute(f,""):s.removeAttribute(f);break;case"capture":case"download":y===!0?s.setAttribute(f,""):y!==!1&&y!=null&&typeof y!="function"&&typeof y!="symbol"?s.setAttribute(f,y):s.removeAttribute(f);break;case"cols":case"rows":case"size":case"span":y!=null&&typeof y!="function"&&typeof y!="symbol"&&!isNaN(y)&&1<=y?s.setAttribute(f,y):s.removeAttribute(f);break;case"rowSpan":case"start":y==null||typeof y=="function"||typeof y=="symbol"||isNaN(y)?s.removeAttribute(f):s.setAttribute(f,y);break;case"popover":Gt("beforetoggle",s),Gt("toggle",s),An(s,"popover",y);break;case"xlinkActuate":jn(s,"http://www.w3.org/1999/xlink","xlink:actuate",y);break;case"xlinkArcrole":jn(s,"http://www.w3.org/1999/xlink","xlink:arcrole",y);break;case"xlinkRole":jn(s,"http://www.w3.org/1999/xlink","xlink:role",y);break;case"xlinkShow":jn(s,"http://www.w3.org/1999/xlink","xlink:show",y);break;case"xlinkTitle":jn(s,"http://www.w3.org/1999/xlink","xlink:title",y);break;case"xlinkType":jn(s,"http://www.w3.org/1999/xlink","xlink:type",y);break;case"xmlBase":jn(s,"http://www.w3.org/XML/1998/namespace","xml:base",y);break;case"xmlLang":jn(s,"http://www.w3.org/XML/1998/namespace","xml:lang",y);break;case"xmlSpace":jn(s,"http://www.w3.org/XML/1998/namespace","xml:space",y);break;case"is":An(s,"is",y);break;case"innerText":case"textContent":break;default:(!(2<f.length)||f[0]!=="o"&&f[0]!=="O"||f[1]!=="n"&&f[1]!=="N")&&(f=nn.get(f)||f,An(s,f,y))}}function Uh(s,l,f,y,b,E){switch(f){case"style":qn(s,y,E);break;case"dangerouslySetInnerHTML":if(y!=null){if(typeof y!="object"||!("__html"in y))throw Error(i(61));if(f=y.__html,f!=null){if(b.children!=null)throw Error(i(60));s.innerHTML=f}}break;case"children":typeof y=="string"?nt(s,y):(typeof y=="number"||typeof y=="bigint")&&nt(s,""+y);break;case"onScroll":y!=null&&Gt("scroll",s);break;case"onScrollEnd":y!=null&&Gt("scrollend",s);break;case"onClick":y!=null&&(s.onclick=Ui);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"inne Line truncated
`),ae=p.map(([ue,ie])=>` [${ue}, ${ie}],`).join(` `),ae=p.map(([ue,ie])=>` [${ue}, ${ie}],`).join(`
`);return`const MAP_STR: string[] = [ `);return`const MAP_STR: string[] = [
${se} ${se}
@@ -14,20 +14,32 @@ ${se}
const SEATS: [number, number][] = [ const SEATS: [number, number][] = [
${ae} ${ae}
]`})(),Z=()=>R(te=>Math.min(te+.25,3)),F=()=>R(te=>Math.max(te-.25,.5)),K=m.flat().filter(te=>te===1).length,ee=m.flat().filter(te=>te===0).length;return u.jsxs("div",{className:"collision-editor",children:[u.jsxs("div",{className:"ce-toolbar",children:[u.jsxs("div",{className:"ce-toolbar-group",children:[u.jsx("span",{className:"ce-title",children:"Map Editor"}),u.jsx("select",{className:"ce-office-select",value:a,onChange:te=>A(te.target.value),children:r.map(te=>u.jsx("option",{value:te.id,children:te.name},te.id))})]}),u.jsxs("div",{className:"ce-toolbar-group",children:[u.jsxs("button",{className:`ce-mode-btn ${x==="wall"?"active wall":""}`,onClick:()=>v("wall"),children:[u.jsx("span",{className:"ce-mode-dot wall"})," Wall"]}),u.jsxs("button",{className:`ce-mode-btn ${x==="floor"?"active floor":""}`,onClick:()=>v("floor"),children:[u.jsx("span",{className:"ce-mode-dot floor"})," Floor"]}),u.jsxs("button",{className:`ce-mode-btn ${x==="seat"?"active seat":""}`,onClick:()=>v("seat"),children:[u.jsx("span",{className:"ce-mode-dot seat"})," Seat"]})]}),u.jsxs("div",{className:"ce-toolbar-group",children:[u.jsx("button",{className:"ce-btn",onClick:F,children:"-"}),u.jsxs("span",{className:"ce-zoom-label",children:[Math.round(O*100),"%"]}),u.jsx("button",{className:"ce-btn",onClick:Z,children:"+"}),u.jsx("button",{className:`ce-btn${D?" active":""}`,onClick:()=>I(te=>!te),children:"Grid"})]}),u.jsxs("div",{className:"ce-toolbar-group",children:[u.jsx("button",{className:`ce-btn apply${j?" success":""}`,onClick:Y,children:j?"Applied":"Apply"}),u.jsx("button",{className:`ce-btn${w?" active":""}`,onClick:Q,children:"Export"}),u.jsx("button",{className:"ce-btn danger",onClick:V,children:"Reset"})]}),u.jsxs("div",{className:"ce-toolbar-group ce-stats",children:[u.jsxs("span",{children:["Walls: ",K]}),u.jsxs("span",{children:["Floor: ",ee]}),u.jsxs("span",{children:["Seats: ",p.length]})]})]}),u.jsxs("div",{className:"ce-body",children:[u.jsx("div",{className:"ce-canvas-wrap",style:{overflow:"auto"},children:u.jsx("canvas",{ref:t,style:{width:L*T*O,height:M*T*O,imageRendering:"pixelated",cursor:x==="seat"?"crosshair":"cell"},onMouseDown:G,onMouseMove:$,onMouseUp:q,onMouseLeave:q})}),w&&u.jsxs("div",{className:"ce-export-panel",children:[u.jsxs("div",{className:"ce-export-header",children:[u.jsx("span",{children:"Export — copy to source code"}),u.jsx("button",{className:"ce-btn",onClick:()=>navigator.clipboard.writeText(U),children:"Copy"})]}),u.jsx("textarea",{className:"ce-export-textarea",value:U,readOnly:!0,rows:20})]})]})]})}let e4=0;function gi(e,t,n={}){return{event_id:`test-${++e4}`,type:e,agent_id:t,data:n,timestamp:Date.now()/1e3}}function Pn(e){return new Promise(t=>setTimeout(t,e))}async function t4(e){const t=[],n=e.getScene();if(!n)return t.push({name:"scene-ready",pass:!1,detail:"OfficeScene not initialized"}),t;console.log("%c[EventTest] Starting full event test suite (multi-office)...","color: #6366f1; font-weight: bold");for(const A of[...n.agents.keys()])n.removeAgent(A);await Pn(100);const i=Kn();t.push({name:"offices-loaded",pass:i.length>=3,detail:`${i.length} offices loaded: ${i.map(A=>A.name).join(", ")}`});const r=["agent-A","agent-B","agent-C","agent-D","agent-E","agent-F"];for(const A of r)e.pushEvent(gi("agent_active",A));await Pn(300);const o=new Set;let a=!1;for(const A of r){const B=n.getAgent(A);B&&B.seatId&&(o.has(B.seatId)&&(a=!0),o.add(B.seatId))}t.push({name:"desk-assignment-unique",pass:!a&&o.size===r.length,detail:`Assigned ${o.size} unique seats to ${r.length} agents. IDs: [${[...o].join(", ")}]`});const c=r.every(A=>n.getAgent(A)?.officeId!=null);t.push({name:"agents-have-officeId",pass:c,detail:r.map(A=>`${A}=${n.getAgent(A)?.officeId}`).join(", ")}),e.pushEvent(gi("tool_start","agent-A",{tool_name:"shell"})),await Pn(200);const d=n.getAgent("agent-A");t.push({name:"tool_start-state",pass:d.isActive===!0&&d.currentTool==="shell",detail:`isActive=${d.isActive}, currentTool=${d.currentTool}`}),e.pushEvent(gi("tool_done","agent-A",{tool_name:"shell"})),await Pn(100),t.push({name:"tool_done-celebrate",pass:d.agentState==="celebrate",detail:`state=${d.agentState}`});for(let A=0;A<20&&d.agentState==="celebrate";A++)await Pn(500);t.push({name:"celebrate-to-idle",pass:d.agentState!=="celebrate",detail:`state=${d.agentState}`}),e.pushEvent(gi("waiting","agent-B")),await Pn(200);const m=n.getAgent("agent-B");t.push({name:"waiting-state",pass:m.isActive===!1&&(m.agentState==="walk"||m.agentState==="idle"||m.agentState==="coffee"),detail:`isActive=${m.isActive}, state=${m.agentState}`}),e.pushEvent(gi("reflect_start","agent-C")),await Pn(200);const h=n.getAgent("agent-C");t.push({name:"reflect_start-state",pass:h.currentTool==="Reflect"&&(h.agentState==="walk"||h.agentState==="reflect"),detail:`currentTool=${h.currentTool}, state=${h.agentState}`}),e.pushEvent(gi("reflect_done","agent-C")),await Pn(100),t.push({name:"reflect_done-celebrate",pass:h.agentState==="celebrate",detail:`staLine truncated ]`})(),Z=()=>R(te=>Math.min(te+.25,3)),F=()=>R(te=>Math.max(te-.25,.5)),K=m.flat().filter(te=>te===1).length,ee=m.flat().filter(te=>te===0).length;return u.jsxs("div",{className:"collision-editor",children:[u.jsxs("div",{className:"ce-toolbar",children:[u.jsxs("div",{className:"ce-toolbar-group",children:[u.jsx("span",{className:"ce-title",children:"Map Editor"}),u.jsx("select",{className:"ce-office-select",value:a,onChange:te=>A(te.target.value),children:r.map(te=>u.jsx("option",{value:te.id,children:te.name},te.id))})]}),u.jsxs("div",{className:"ce-toolbar-group",children:[u.jsxs("button",{className:`ce-mode-btn ${x==="wall"?"active wall":""}`,onClick:()=>v("wall"),children:[u.jsx("span",{className:"ce-mode-dot wall"})," Wall"]}),u.jsxs("button",{className:`ce-mode-btn ${x==="floor"?"active floor":""}`,onClick:()=>v("floor"),children:[u.jsx("span",{className:"ce-mode-dot floor"})," Floor"]}),u.jsxs("button",{className:`ce-mode-btn ${x==="seat"?"active seat":""}`,onClick:()=>v("seat"),children:[u.jsx("span",{className:"ce-mode-dot seat"})," Seat"]})]}),u.jsxs("div",{className:"ce-toolbar-group",children:[u.jsx("button",{className:"ce-btn",onClick:F,children:"-"}),u.jsxs("span",{className:"ce-zoom-label",children:[Math.round(O*100),"%"]}),u.jsx("button",{className:"ce-btn",onClick:Z,children:"+"}),u.jsx("button",{className:`ce-btn${D?" active":""}`,onClick:()=>I(te=>!te),children:"Grid"})]}),u.jsxs("div",{className:"ce-toolbar-group",children:[u.jsx("button",{className:`ce-btn apply${j?" success":""}`,onClick:Y,children:j?"Applied":"Apply"}),u.jsx("button",{className:`ce-btn${w?" active":""}`,onClick:Q,children:"Export"}),u.jsx("button",{className:"ce-btn danger",onClick:V,children:"Reset"})]}),u.jsxs("div",{className:"ce-toolbar-group ce-stats",children:[u.jsxs("span",{children:["Walls: ",K]}),u.jsxs("span",{children:["Floor: ",ee]}),u.jsxs("span",{children:["Seats: ",p.length]})]})]}),u.jsxs("div",{className:"ce-body",children:[u.jsx("div",{className:"ce-canvas-wrap",style:{overflow:"auto"},children:u.jsx("canvas",{ref:t,style:{width:L*T*O,height:M*T*O,imageRendering:"pixelated",cursor:x==="seat"?"crosshair":"cell"},onMouseDown:G,onMouseMove:$,onMouseUp:q,onMouseLeave:q})}),w&&u.jsxs("div",{className:"ce-export-panel",children:[u.jsxs("div",{className:"ce-export-header",children:[u.jsx("span",{children:"Export — copy to source code"}),u.jsx("button",{className:"ce-btn",onClick:()=>navigator.clipboard.writeText(U),children:"Copy"})]}),u.jsx("textarea",{className:"ce-export-textarea",value:U,readOnly:!0,rows:20})]})]})]})}let l4=0;function gi(e,t,n={}){return{event_id:`test-${++l4}`,type:e,agent_id:t,data:n,timestamp:Date.now()/1e3}}function Pn(e){return new Promise(t=>setTimeout(t,e))}async function c4(e){const t=[],n=e.getScene();if(!n)return t.push({name:"scene-ready",pass:!1,detail:"OfficeScene not initialized"}),t;console.log("%c[EventTest] Starting full event test suite (multi-office)...","color: #6366f1; font-weight: bold");for(const A of[...n.agents.keys()])n.removeAgent(A);await Pn(100);const i=Kn();t.push({name:"offices-loaded",pass:i.length>=3,detail:`${i.length} offices loaded: ${i.map(A=>A.name).join(", ")}`});const r=["agent-A","agent-B","agent-C","agent-D","agent-E","agent-F"];for(const A of r)e.pushEvent(gi("agent_active",A));await Pn(300);const o=new Set;let a=!1;for(const A of r){const B=n.getAgent(A);B&&B.seatId&&(o.has(B.seatId)&&(a=!0),o.add(B.seatId))}t.push({name:"desk-assignment-unique",pass:!a&&o.size===r.length,detail:`Assigned ${o.size} unique seats to ${r.length} agents. IDs: [${[...o].join(", ")}]`});const c=r.every(A=>n.getAgent(A)?.officeId!=null);t.push({name:"agents-have-officeId",pass:c,detail:r.map(A=>`${A}=${n.getAgent(A)?.officeId}`).join(", ")}),e.pushEvent(gi("tool_start","agent-A",{tool_name:"shell"})),await Pn(200);const d=n.getAgent("agent-A");t.push({name:"tool_start-state",pass:d.isActive===!0&&d.currentTool==="shell",detail:`isActive=${d.isActive}, currentTool=${d.currentTool}`}),e.pushEvent(gi("tool_done","agent-A",{tool_name:"shell"})),await Pn(100),t.push({name:"tool_done-celebrate",pass:d.agentState==="celebrate",detail:`state=${d.agentState}`});for(let A=0;A<20&&d.agentState==="celebrate";A++)await Pn(500);t.push({name:"celebrate-to-idle",pass:d.agentState!=="celebrate",detail:`state=${d.agentState}`}),e.pushEvent(gi("waiting","agent-B")),await Pn(200);const m=n.getAgent("agent-B");t.push({name:"waiting-state",pass:m.isActive===!1&&(m.agentState==="walk"||m.agentState==="idle"||m.agentState==="coffee"),detail:`isActive=${m.isActive}, state=${m.agentState}`}),e.pushEvent(gi("reflect_start","agent-C")),await Pn(200);const h=n.getAgent("agent-C");t.push({name:"reflect_start-state",pass:h.currentTool==="Reflect"&&(h.agentState==="walk"||h.agentState==="reflect"),detail:`currentTool=${h.currentTool}, state=${h.agentState}`}),e.pushEvent(gi("reflect_done","agent-C")),await Pn(100),t.push({name:"reflect_done-celebrate",pass:h.agentState==="celebrate",detail:`staLine truncated
font-size: .6rem; font-size: .6rem;
font-weight: bold; font-weight: bold;
color: hsl(${Math.max(0,Math.min(120-120*k,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(o&&n.skipInitialOnChange)&&n.onChange(r),o=!1,r}return a.updateDeps=c=>{i=c},a}function Wk(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const d4=(e,t)=>Math.abs(e-t)<1.01,f4=(e,t,n)=>{let i;return function(...r){e.clearTimeout(i),i=e.setTimeout(()=>t.apply(this,r),n)}},Yk=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},m4=e=>e,p4=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),i=[];for(let r=t;r<=n;r++)i.push(r);return i},h4=(e,t)=>{const n=e.scrollElement;if(!n)return;const i=e.targetWindow;if(!i)return;const r=a=>{const{width:c,height:d}=a;t({width:Math.round(c),height:Math.round(d)})};if(r(Yk(n)),!i.ResizeObserver)return()=>{};const o=new i.ResizeObserver(a=>{const c=()=>{const d=a[0];if(d?.borderBoxSize){const m=d.borderBoxSize[0];if(m){r({width:m.inlineSize,height:m.blockSize});return}}r(Yk(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(c):c()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},Xk={passive:!0},Kk=typeof window>"u"?!0:"onscrollend"in window,g4=(e,t)=>{const n=e.scrollElement;if(!n)return;const i=e.targetWindow;if(!i)return;let r=0;const o=e.options.useScrollendEvent&&Kk?()=>{}:f4(i,()=>{t(r,!1)},e.options.isScrollingResetDelay),a=h=>()=>{const{horizontal:p,isRtl:g}=e.options;r=p?n.scrollLeft*(g&&-1||1):n.scrollTop,o(),t(r,h)},c=a(!0),d=a(!1);n.addEventListener("scroll",c,Xk);const m=e.options.useScrollendEvent&&Kk;return m&&n.addEventListener("scrollend",d,Xk),()=>{n.removeEventListener("scroll",c),m&&n.removeEventListener("scrollend",d)}},y4=(e,t,n)=>{if(t?.borderBoxSize){const i=t.borderBoxSize[0];if(i)return Math.round(i[n.options.horizontal?"inlineSize":"blockSize"])}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},x4=(e,{adjustments:t=0,behavior:n},i)=>{var r,o;const a=e+t;(o=(r=i.scrollElement)==null?void 0:r.scrollTo)==null||o.call(r,{[i.options.horizontal?"left":"top"]:a,behavior:n})};class v4{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var n,i,r;return((r=(i=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:i.now)==null?void 0:r.call(i))??Date.now()},this.observer=(()=>{let n=null;const i=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(r=>{r.forEach(o=>{const a=()=>{const c=o.target,d=this.indexFromElement(c);if(!c.isConnected){this.observer.unobserve(c);return}this.shouldMeasureDuringScroll(d)&&this.resizeItem(d,this.options.measureElement(c,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()})}));return{disconnect:()=>{var r;(r=i())==null||r.disconnect(),n=null},observe:r=>{var o;return(o=i())==null?void 0:o.observe(r,{box:"border-box"})},unobserve:r=>{var o;return(o=i())==null?void 0:o.unobserve(r)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([i,r])=>{typeof r>"u"&&delete n[i]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:m4,rangeExtractor:p4,onChange:()=>{},measureElement:y4,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...n}},this.notify=n=>{var i,r;(r=(i=this.options).onChange)==null||r.call(i,this,n)},this.maybeNotify=Za(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const i=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==i){if(this.cleanup(),!i){this.maybeNotify();return}this.scrollElement=i,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(r=>{this.observer.observe(r)} Line truncated color: hsl(${Math.max(0,Math.min(120-120*k,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(o&&n.skipInitialOnChange)&&n.onChange(r),o=!1,r}return a.updateDeps=c=>{i=c},a}function Jk(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const v4=(e,t)=>Math.abs(e-t)<1.01,b4=(e,t,n)=>{let i;return function(...r){e.clearTimeout(i),i=e.setTimeout(()=>t.apply(this,r),n)}},eS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},_4=e=>e,k4=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),i=[];for(let r=t;r<=n;r++)i.push(r);return i},S4=(e,t)=>{const n=e.scrollElement;if(!n)return;const i=e.targetWindow;if(!i)return;const r=a=>{const{width:c,height:d}=a;t({width:Math.round(c),height:Math.round(d)})};if(r(eS(n)),!i.ResizeObserver)return()=>{};const o=new i.ResizeObserver(a=>{const c=()=>{const d=a[0];if(d?.borderBoxSize){const m=d.borderBoxSize[0];if(m){r({width:m.inlineSize,height:m.blockSize});return}}r(eS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(c):c()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},tS={passive:!0},nS=typeof window>"u"?!0:"onscrollend"in window,w4=(e,t)=>{const n=e.scrollElement;if(!n)return;const i=e.targetWindow;if(!i)return;let r=0;const o=e.options.useScrollendEvent&&nS?()=>{}:b4(i,()=>{t(r,!1)},e.options.isScrollingResetDelay),a=h=>()=>{const{horizontal:p,isRtl:g}=e.options;r=p?n.scrollLeft*(g&&-1||1):n.scrollTop,o(),t(r,h)},c=a(!0),d=a(!1);n.addEventListener("scroll",c,tS);const m=e.options.useScrollendEvent&&nS;return m&&n.addEventListener("scrollend",d,tS),()=>{n.removeEventListener("scroll",c),m&&n.removeEventListener("scrollend",d)}},C4=(e,t,n)=>{if(t?.borderBoxSize){const i=t.borderBoxSize[0];if(i)return Math.round(i[n.options.horizontal?"inlineSize":"blockSize"])}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},j4=(e,{adjustments:t=0,behavior:n},i)=>{var r,o;const a=e+t;(o=(r=i.scrollElement)==null?void 0:r.scrollTo)==null||o.call(r,{[i.options.horizontal?"left":"top"]:a,behavior:n})};class E4{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var n,i,r;return((r=(i=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:i.now)==null?void 0:r.call(i))??Date.now()},this.observer=(()=>{let n=null;const i=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(r=>{r.forEach(o=>{const a=()=>{const c=o.target,d=this.indexFromElement(c);if(!c.isConnected){this.observer.unobserve(c);return}this.shouldMeasureDuringScroll(d)&&this.resizeItem(d,this.options.measureElement(c,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()})}));return{disconnect:()=>{var r;(r=i())==null||r.disconnect(),n=null},observe:r=>{var o;return(o=i())==null?void 0:o.observe(r,{box:"border-box"})},unobserve:r=>{var o;return(o=i())==null?void 0:o.unobserve(r)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([i,r])=>{typeof r>"u"&&delete n[i]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:_4,rangeExtractor:k4,onChange:()=>{},measureElement:C4,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...n}},this.notify=n=>{var i,r;(r=(i=this.options).onChange)==null||r.call(i,this,n)},this.maybeNotify=Za(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const i=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==i){if(this.cleanup(),!i){this.maybeNotify();return}this.scrollElement=i,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(r=>{this.observer.observe(r)} Line truncated
`).replace(/\r/g,`
`).split(`
`).map(i=>i.trimEnd()).join(`
`).replace(/\n{3,}/g,`
`).trim();for(;;){const i=t.match(/^\*\*([^\r\n]{8,160}?)\*\*:(?:[ \t]+|\r?\n+)([\s\S]+)$/);if(!i)break;const r=i[2].trim();if(r.length<80||r===t)break;t=r}const n=t.split(/\n{2,}/).map(i=>i.trim()).filter(Boolean);return n.length>1&&/^Verification:\s/i.test(n[n.length-1])&&(t=n.slice(0,-1).join(`
`).trim()),e5(t).slice(0,2e3)}function $x(e){const t=e.metadata??{};switch(String(t.transcript_kind??t.kind??"").trim()){case"child_task_result":return 80;case"child_task_result_retry":return 79;case"company_role_result":return 75;case"company_role_result_retry":return 74;case"child_result":return 70;case"runtime_v2_assistant":return 60;case"runtime_v2_company_assistant":return 20;case"top_level_reply":return 40}return String(t.kind??"").trim()==="worker_notification"?20:0}function aS(e){return String(e.content??"").replace(/\r\n/g,`
`).replace(/\r/g,`
`).split(`
`).map(t=>t.trimEnd()).join(`
`).trim().length}function lS(e){const t=e.metadata??{};let n=0;return String(t.source??"").trim()==="engine"&&(n+=4),String(t.source_result_message_id??"").trim()&&(n+=2),(t.authoritative_output===!0||t.canonical_result===!0)&&(n+=1),n}function n5(e,t){const n=[[$x(e),$x(t)],[lS(e),lS(t)],[aS(e),aS(t)]];for(const[o,a]of n)if(o!==a)return o>a?1:-1;const i=e.id.localeCompare(t.id);if(i!==0)return i;const r=e.content.localeCompare(t.content);return r!==0?r:e.timestamp===t.timestamp?0:e.timestamp>t.timestamp?1:-1}function dE(e){if($x(e)<=0)return"";const t=uE(e);if(t)return`result:${t}`;const n=t5(e.content);return n?`result:${n}`:""}function tf(e){if(!e)return;const t=e.replace(/,/g,"").trim();if(!t)return;const n=Number(t);return Number.isFinite(n)?Math.max(0,Math.round(n)):void 0}function cS(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,Math.min(Math.round(e),100))}function kl(e){if(!e)return;const t=String(e.execMode??"").trim();if(!(t==="company"||t==="org"||t==="custom"||!!e.isCompanyRuntime||!!e.roleWorkItems||!!e.executorRoleWorkItems))return;const i=Object.values(e.executorRoleWorkItems??e.roleWorkItems??{});if(i.length===0)return;const r=i.map(o=>o.aggregatedStatus);if(r.some(o=>o==="active"))return"running";if(r.some(o=>o==="waiting")||r.some(o=>o==="pending"))return"pending";if(r.every(o=>o==="failed"))return"failed";if(r.every(o=>o==="done")||r.some(o=>o==="done"))return"done"}function i5(e){const t={};for(const n of e??[]){const i=`${n.summary??""} ${n.detail??""}`.trim();if(!i)continue;const r=Z4.exec(i);if(r){const c=tf(r[1]),d=tf(r[2]);typeof c=="number"&&(t.contextTokens=c),typeof d=="number"&&d>0&&(t.contextWindow=d)}const o=J4.exec(i);if(o){t.contextRemainingPct=cS(tf(o[1]));continue}const a=Q4.exec(i);if(a){const c=cS(tf(a[1]));typeof c=="number"&&(t.contextRemainingPct=100-c)}}return t}function qf(e){const t=i5(e.progressLog),n=e.contextTokens??t.contextTokens,i=e.contextWindow??t.contextWindow,r=e.contextRemainingPct??t.contextRemainingPct;return n===e.contextTokens&&i===e.contextWindow&&r===e.contextRemainingPct?e:{...e,contextTokens:n,contextWindow:i,contextRemainingPct:r}}function fE(e){const t=new Set,n=[];for(const i of e)t.has(i.taskId)||(t.add(i.taskId),n.push(i));return n}function r5(e){return!!(String(e?.workItemRoleId??"").trim()||String(e?.workItemRoleName??"").trim())}function Af(e,t){if(!e||e.mode==="child")return[];const n=new Set;e.sessionId&&n.add(e.sessionId),n.add(e.taskId);const i=String(e.originTaskId??e.taskId??"").trim(),r=new Map;for(const c of e.workItemLog??[]){const d=c.executionTurnId||c.runtimeTaskId;d&&!r.has(d)&&r.set(d,r.size)}const o=new Set;return t.filter(c=>{if(c.taskId===e.taskId||o.has(c.taskId))return!1;const d=!!c.parentSessionId&&n.has(c.parentSessionId),m=r.has(c.taskId),h=!!i&&String(c.originTaskId??"").trim()===i;return!d&&!m&&!h?!1:(o.add(c.taskId),!0)}).sort((c,d)=>{const m=r.get(c.taskId),h=r.get(d.taskId);return m!=null&&h!=null&&m!==h?m-h:m!=null&&h==null?-1:m==null&&h!=null?1:d.updatedAt-c.updatedAt})}function uS(e,t){const n=Af(e,t);return!e||e.mode==="child"||!r5(e)?n:fE([e,...n])}function Wf(e,t){if(!e||e.mode==="child")return[];const n=String(e.sessionId??"").trim();if(!n)return[];const i=new Set;return t.filter(r=>r.taskId===e.taskId||i.has(r.taskId)||String(r.sessionId??"").trim()!==n?!1:(i.add(r.taskId),!0)).sort((r,o)=>o.updatedAt-r.updatedAt)}function s5(e){const t=String(e?.execMode??"").trim();return t==="company"||t==="org"||t==="custom"}function dS(e){const t=ss(e)?1e9:0,n=String(e.draftAssistantText??"").trim()?1e10:0,i=Math.max(0,e.messageCount??0)*1e4,r=(e.progressLog?.length??0)*100;return n+t+i+r+e.updatedAt}function fS(e){const t=cE(e),n=ss(e)?1e11:0,i=String(e.draftAssistantText??"").trim()?1e10:0,r=typeof t.usedPct=="number"||typeof t.usedTokens=="number"||typeof t.windowTokens=="number"?1e10:0,o=typeof e.inputTokens=="number"||typeof e.outputTokens=="number"||typeof e.totalTokens=="number"?1e9:0,a=Math.max(0,e.messageCount??0)*1e4,c=(e.progressLog?.length??0)*100;return n+i+r+o+a+c}function Yf(e,t){if(!e)return{timelineSessions:[],displaySession:null,runtimeSession:null,projectedFromChild:!1};const n=qf(e);if(e.mode==="child"||t.length===0)return{timelineSessions:[n],displaySession:n,runtimeSession:n,projectedFromChild:!1};const i=t.map(qf),r=i.filter(p=>p.status!=="cancelled"),o=r.length>0?r:i,a=fE([n,...o]),c=s5(e),d=[...a].sort((p,g)=>dS(g)-dS(p))[0]??n,m=c?n:d,h=[...a].sort((p,g)=>fS(g)-fS(p))[0]??m;return{timelineSessions:a,displaySession:m,runtimeSession:h,projectedFromChild:!c&&m.taskId!==e.taskId}}function mS(e,t,n){if(!e)return null;const i=qf(e),r=t??i,o=kl(r)??kl(i),a=Xf(n.length>0?n:[i]);return{...i,status:o??(r.status||i.status),assigneeIds:r.assigneeIds.length>0?r.assigneeIds:i.assigneeIds,agentStatus:r.agentStatus??i.agentStatus,currentTool:r.currentTool??i.currentTool,displayTool:r.displayTool??r.currentTool??i.displayTool??i.currentTool,toolElapsedMs:r.toolElapsedMs??i.toolElapsed Line truncated
The error may be correlated with this previous error: The error may be correlated with this previous error:
${te.current.stack} ${te.current.stack}
`),je}Kf(()=>{te.current=void 0,F.current=void 0,U.current=ue});const ie=C.useMemo(()=>C.createElement(k,{...ue,ref:L}),[L,k,ue]);return C.useMemo(()=>v?C.createElement(A.Provider,{value:V},ie):ie,[A,ie,V])}const R=C.memo(N);if(R.WrappedComponent=k,R.displayName=N.displayName=S,d){const I=C.forwardRef(function(M,A){return C.createElement(R,{...M,reactReduxForwardedRef:A})});return I.displayName=S,I.WrappedComponent=k,Bx(I,k)}return Bx(R,k)}}var fE=iD;function rD(e){const{children:t,context:n,serverState:i,store:r}=e,o=C.useMemo(()=>{const d=cE(r);return{store:r,subscription:d,getServerState:i?()=>i:void 0}},[r,i]),a=C.useMemo(()=>r.getState(),[r]);Kf(()=>{const{subscription:d}=o;return d.onStateChange=d.notifyNestedSubs,d.trySubscribe(),a!==r.getState()&&d.notifyNestedSubs(),()=>{d.tryUnsubscribe(),d.onStateChange=void 0}},[o,a]);const c=n||dE;return C.createElement(c.Provider,{value:o},t)}var sD=rD,oD="Invariant failed";function aD(e,t){throw new Error(oD)}var Hr=function(t){var n=t.top,i=t.right,r=t.bottom,o=t.left,a=i-o,c=r-n,d={top:n,right:i,bottom:r,left:o,width:a,height:c,x:o,y:n,center:{x:(i+o)/2,y:(r+n)/2}};return d},Pv=function(t,n){return{top:t.top-n.top,left:t.left-n.left,bottom:t.bottom+n.bottom,right:t.right+n.right}},_S=function(t,n){return{top:t.top+n.top,left:t.left+n.left,bottom:t.bottom-n.bottom,right:t.right-n.right}},lD=function(t,n){return{top:t.top+n.y,left:t.left+n.x,bottom:t.bottom+n.y,right:t.right+n.x}},Cg={top:0,right:0,bottom:0,left:0},Bv=function(t){var n=t.borderBox,i=t.margin,r=i===void 0?Cg:i,o=t.border,a=o===void 0?Cg:o,c=t.padding,d=c===void 0?Cg:c,m=Hr(Pv(n,r)),h=Hr(_S(n,a)),p=Hr(_S(h,d));return{marginBox:m,borderBox:Hr(n),paddingBox:h,contentBox:p,margin:r,border:a,padding:d}},Er=function(t){var n=t.slice(0,-2),i=t.slice(-2);if(i!=="px")return 0;var r=Number(n);return isNaN(r)&&aD(),r},cD=function(){return{x:window.pageXOffset,y:window.pageYOffset}},Zf=function(t,n){var i=t.borderBox,r=t.border,o=t.margin,a=t.padding,c=lD(i,n);return Bv({borderBox:c,border:r,margin:o,padding:a})},Qf=function(t,n){return n===void 0&&(n=cD()),Zf(t,n)},mE=function(t,n){var i={top:Er(n.marginTop),right:Er(n.marginRight),bottom:Er(n.marginBottom),left:Er(n.marginLeft)},r={top:Er(n.paddingTop),right:Er(n.paddingRight),bottom:Er(n.paddingBottom),left:Er(n.paddingLeft)},o={top:Er(n.borderTopWidth),right:Er(n.borderRightWidth),bottom:Er(n.borderBottomWidth),left:Er(n.borderLeftWidth)};return Bv({borderBox:t,margin:i,padding:r,border:o})},pE=function(t){var n=t.getBoundingClientRect(),i=window.getComputedStyle(t);return mE(n,i)},xu=function(t){var n=[],i=null,r=function(){for(var a=arguments.length,c=new Array(a),d=0;d<a;d++)c[d]=arguments[d];n=c,!i&&(i=requestAnimationFrame(function(){i=null,t.apply(void 0,n)}))};return r.cancel=function(){i&&(cancelAnimationFrame(i),i=null)},r};function Jf(){return Jf=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},Jf.apply(null,arguments)}function hE(e,t){}hE.bind(null,"warn");hE.bind(null,"error");function _o(){}function uD(e,t){return{...e,...t}}function Rr(e,t,n){const i=t.map(r=>{const o=uD(n,r.options);return e.addEventListener(r.eventName,r.fn,o),function(){e.removeEventListener(r.eventName,r.fn,o)}});return function(){i.forEach(o=>{o()})}}const dD="Invariant failed";class em extends Error{}em.prototype.toString=function(){return this.message};function Oe(e,t){throw new em(dD)}let fD=class extends Nt.Component{constructor(...t){super(...t),this.callbacks=null,this.unbind=_o,this.onWindowError=n=>{const i=this.getCallbacks();i.isDragging()&&i.tryAbort(),n.error instanceof em&&n.preventDefault()},this.getCallbacks=()=>{if(!this.callbacks)throw new Error("Unable to find AppCallbacks in <ErrorBoundary/>");return this.callbacks},this.setCallbacks=n=>{this.callbacks=n}}componentDidMount(){this.unbind=Rr(window,[{eventName:"error",fn:this.onWindowError}])}componentDidCatch(t){if(t instanceof em){this.setState({});return}throw t}componentWillUnmount(){this.unbind()}render(){return this.props.children(this.setCallbacks)}};const mD=` `),je}Kf(()=>{te.current=void 0,F.current=void 0,U.current=ue});const ie=C.useMemo(()=>C.createElement(k,{...ue,ref:L}),[L,k,ue]);return C.useMemo(()=>v?C.createElement(A.Provider,{value:V},ie):ie,[A,ie,V])}const R=C.memo(N);if(R.WrappedComponent=k,R.displayName=N.displayName=S,d){const I=C.forwardRef(function(M,A){return C.createElement(R,{...M,reactReduxForwardedRef:A})});return I.displayName=S,I.WrappedComponent=k,Vx(I,k)}return Vx(R,k)}}var kE=hD;function gD(e){const{children:t,context:n,serverState:i,store:r}=e,o=C.useMemo(()=>{const d=vE(r);return{store:r,subscription:d,getServerState:i?()=>i:void 0}},[r,i]),a=C.useMemo(()=>r.getState(),[r]);Kf(()=>{const{subscription:d}=o;return d.onStateChange=d.notifyNestedSubs,d.trySubscribe(),a!==r.getState()&&d.notifyNestedSubs(),()=>{d.tryUnsubscribe(),d.onStateChange=void 0}},[o,a]);const c=n||_E;return C.createElement(c.Provider,{value:o},t)}var yD=gD,xD="Invariant failed";function vD(e,t){throw new Error(xD)}var $r=function(t){var n=t.top,i=t.right,r=t.bottom,o=t.left,a=i-o,c=r-n,d={top:n,right:i,bottom:r,left:o,width:a,height:c,x:o,y:n,center:{x:(i+o)/2,y:(r+n)/2}};return d},Uv=function(t,n){return{top:t.top-n.top,left:t.left-n.left,bottom:t.bottom+n.bottom,right:t.right+n.right}},IS=function(t,n){return{top:t.top+n.top,left:t.left+n.left,bottom:t.bottom-n.bottom,right:t.right-n.right}},bD=function(t,n){return{top:t.top+n.y,left:t.left+n.x,bottom:t.bottom+n.y,right:t.right+n.x}},jg={top:0,right:0,bottom:0,left:0},Gv=function(t){var n=t.borderBox,i=t.margin,r=i===void 0?jg:i,o=t.border,a=o===void 0?jg:o,c=t.padding,d=c===void 0?jg:c,m=$r(Uv(n,r)),h=$r(IS(n,a)),p=$r(IS(h,d));return{marginBox:m,borderBox:$r(n),paddingBox:h,contentBox:p,margin:r,border:a,padding:d}},jr=function(t){var n=t.slice(0,-2),i=t.slice(-2);if(i!=="px")return 0;var r=Number(n);return isNaN(r)&&vD(),r},_D=function(){return{x:window.pageXOffset,y:window.pageYOffset}},Zf=function(t,n){var i=t.borderBox,r=t.border,o=t.margin,a=t.padding,c=bD(i,n);return Gv({borderBox:c,border:r,margin:o,padding:a})},Qf=function(t,n){return n===void 0&&(n=_D()),Zf(t,n)},SE=function(t,n){var i={top:jr(n.marginTop),right:jr(n.marginRight),bottom:jr(n.marginBottom),left:jr(n.marginLeft)},r={top:jr(n.paddingTop),right:jr(n.paddingRight),bottom:jr(n.paddingBottom),left:jr(n.paddingLeft)},o={top:jr(n.borderTopWidth),right:jr(n.borderRightWidth),bottom:jr(n.borderBottomWidth),left:jr(n.borderLeftWidth)};return Gv({borderBox:t,margin:i,padding:r,border:o})},wE=function(t){var n=t.getBoundingClientRect(),i=window.getComputedStyle(t);return SE(n,i)},yu=function(t){var n=[],i=null,r=function(){for(var a=arguments.length,c=new Array(a),d=0;d<a;d++)c[d]=arguments[d];n=c,!i&&(i=requestAnimationFrame(function(){i=null,t.apply(void 0,n)}))};return r.cancel=function(){i&&(cancelAnimationFrame(i),i=null)},r};function Jf(){return Jf=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},Jf.apply(null,arguments)}function CE(e,t){}CE.bind(null,"warn");CE.bind(null,"error");function _o(){}function kD(e,t){return{...e,...t}}function Tr(e,t,n){const i=t.map(r=>{const o=kD(n,r.options);return e.addEventListener(r.eventName,r.fn,o),function(){e.removeEventListener(r.eventName,r.fn,o)}});return function(){i.forEach(o=>{o()})}}const SD="Invariant failed";class em extends Error{}em.prototype.toString=function(){return this.message};function Oe(e,t){throw new em(SD)}let wD=class extends Nt.Component{constructor(...t){super(...t),this.callbacks=null,this.unbind=_o,this.onWindowError=n=>{const i=this.getCallbacks();i.isDragging()&&i.tryAbort(),n.error instanceof em&&n.preventDefault()},this.getCallbacks=()=>{if(!this.callbacks)throw new Error("Unable to find AppCallbacks in <ErrorBoundary/>");return this.callbacks},this.setCallbacks=n=>{this.callbacks=n}}componentDidMount(){this.unbind=Tr(window,[{eventName:"error",fn:this.onWindowError}])}componentDidCatch(t){if(t instanceof em){this.setState({});return}throw t}componentWillUnmount(){this.unbind()}render(){return this.props.children(this.setCallbacks)}};const CD=`
Press space bar to start a drag. Press space bar to start a drag.
When dragging you can use the arrow keys to move the item around and escape to cancel. When dragging you can use the arrow keys to move the item around and escape to cancel.
Some screen readers may require you to be in focus mode or to use your pass through key Some screen readers may require you to be in focus mode or to use your pass through key
`,tm=e=>e+1,pD=e=>` `,tm=e=>e+1,jD=e=>`
You have lifted an item in position ${tm(e.source.index)} You have lifted an item in position ${tm(e.source.index)}
`,gE=(e,t)=>{const n=e.droppableId===t.droppableId,i=tm(e.index),r=tm(t.index);return n?` `,jE=(e,t)=>{const n=e.droppableId===t.droppableId,i=tm(e.index),r=tm(t.index);return n?`
You have moved the item from position ${i} You have moved the item from position ${i}
to position ${r} to position ${r}
`:` `:`
@@ -35,38 +47,38 @@ ${te.current.stack}
in list ${e.droppableId} in list ${e.droppableId}
to list ${t.droppableId} to list ${t.droppableId}
in position ${r} in position ${r}
`},yE=(e,t,n)=>t.droppableId===n.droppableId?` `},EE=(e,t,n)=>t.droppableId===n.droppableId?`
The item ${e} The item ${e}
has been combined with ${n.draggableId}`:` has been combined with ${n.draggableId}`:`
The item ${e} The item ${e}
in list ${t.droppableId} in list ${t.droppableId}
has been combined with ${n.draggableId} has been combined with ${n.draggableId}
in list ${n.droppableId} in list ${n.droppableId}
`,hD=e=>{const t=e.destination;if(t)return gE(e.source,t);const n=e.combine;return n?yE(e.draggableId,e.source,n):"You are over an area that cannot be dropped on"},kS=e=>` `,ED=e=>{const t=e.destination;if(t)return jE(e.source,t);const n=e.combine;return n?EE(e.draggableId,e.source,n):"You are over an area that cannot be dropped on"},TS=e=>`
The item has returned to its starting position The item has returned to its starting position
of ${tm(e.index)} of ${tm(e.index)}
`,gD=e=>{if(e.reason==="CANCEL")return` `,ND=e=>{if(e.reason==="CANCEL")return`
Movement cancelled. Movement cancelled.
${kS(e.source)} ${TS(e.source)}
`;const t=e.destination,n=e.combine;return t?` `;const t=e.destination,n=e.combine;return t?`
You have dropped the item. You have dropped the item.
${gE(e.source,t)} ${jE(e.source,t)}
`:n?` `:n?`
You have dropped the item. You have dropped the item.
${yE(e.draggableId,e.source,n)} ${EE(e.draggableId,e.source,n)}
`:` `:`
The item has been dropped while not over a drop area. The item has been dropped while not over a drop area.
${kS(e.source)} ${TS(e.source)}
`},Mf={dragHandleUsageInstructions:mD,onDragStart:pD,onDragUpdate:hD,onDragEnd:gD};function yD(e,t){return!!(e===t||Number.isNaN(e)&&Number.isNaN(t))}function xE(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!yD(e[n],t[n]))return!1;return!0}function nn(e,t){const n=C.useState(()=>({inputs:t,result:e()}))[0],i=C.useRef(!0),r=C.useRef(n),a=i.current||!!(t&&r.current.inputs&&xE(t,r.current.inputs))?r.current:{inputs:t,result:e()};return C.useEffect(()=>{i.current=!1,r.current=a},[a]),a.result}function it(e,t){return nn(()=>e,t)}const ki={x:0,y:0},Ti=(e,t)=>({x:e.x+t.x,y:e.y+t.y}),fr=(e,t)=>({x:e.x-t.x,y:e.y-t.y}),ko=(e,t)=>e.x===t.x&&e.y===t.y,Vl=e=>({x:e.x!==0?-e.x:0,y:e.y!==0?-e.y:0}),sa=(e,t,n=0)=>e==="x"?{x:t,y:n}:{x:n,y:t},vu=(e,t)=>Math.sqrt((t.x-e.x)**2+(t.y-e.y)**2),SS=(e,t)=>Math.min(...t.map(n=>vu(e,n))),vE=e=>t=>({x:e(t.x),y:e(t.y)});var xD=(e,t)=>{const n=Hr({top:Math.max(t.top,e.top),right:Math.min(t.right,e.right),bottom:Math.min(t.bottom,e.bottom),left:Math.max(t.left,e.left)});return n.width<=0||n.height<=0?null:n};const Pu=(e,t)=>({top:e.top+t.y,left:e.left+t.x,bottom:e.bottom+t.y,right:e.right+t.x}),wS=e=>[{x:e.left,y:e.top},{x:e.right,y:e.top},{x:e.left,y:e.bottom},{x:e.right,y:e.bottom}],vD={top:0,right:0,bottom:0,left:0},bD=(e,t)=>t?Pu(e,t.scroll.diff.displacement):e,_D=(e,t,n)=>n&&n.increasedBy?{...e,[t.end]:e[t.end]+n.increasedBy[t.line]}:e,kD=(e,t)=>t&&t.shouldClipSubject?xD(t.pageMarginBox,e):Hr(e);var wl=({page:e,withPlaceholder:t,axis:n,frame:i})=>{const r=bD(e.marginBox,i),o=_D(r,n,t),a=kD(o,i);return{page:e,withPlaceholder:t,active:a}},$v=(e,t)=>{e.frame||Oe();const n=e.frame,i=fr(t,n.scroll.initial),r=Vl(i),o={...n,scroll:{initial:n.scroll.initial,current:t,diff:{value:i,displacement:r},max:n.scroll.max}},a=wl({page:e.subject.page,withPlaceholder:e.subject.withPlaceholder,axis:e.axis,frame:o});return{...e,frame:o,subject:a}};function _i(e,t=xE){let n=null;function i(...r){if(n&&n.lastThis===this&&t(r,n.lastArgs))return n.lastResult;const o=e.apply(this,r);return n={lastResult:o,lastArgs:r,lastThis:this},o}return i.clear=function(){n=null},i}const bE=_i(e=>e.reduce((t,n)=>(t[n.descriptor.id]=n,t),{})),_E=_i(e=>e.reduce((t,n)=>(t[n.descriptor.id]=n,t),{})),Lm=_i(e=>Object.values(e)),SD=_i(e=>Object.values(e));var Ul=_i((e,t)=>SD(t).filter(i=>e===i.descriptor.droppableId).sort((i,r)=>i.descriptor.index-r.descriptor.index));function Hv(e){return e.at&&e.at.type==="REORDER"?e.at.destination:null}function zm(e){return e.at&&e.at.type==="COMBINE"?e.at.combine:null}var Pm=_i((e,t)=>t.filter(n=>n.descriptor.id!==e.descriptor.id)),wD=({isMovingForward:e,draggable:t,destination:n,insideDestination:i,previousImpact:r})=>{if(!n.isCombineEnabled||!Hv(r))return null;function a(x){const v={type:"COMBINE",combine:{draggableId:x,droppableId:n.descriptor.id}};return{...r,at:v}}const c=r.displaced.all,d=c.length?c[0]:null;if(e)return d?a(d):null;const m=Pm(t,i);if(!d){if(!m.length)return null;const x=m[m.length-1];return a(x.descriptor.id)}const h=m.findIndex(x=>x.descriptor.id===d);h===-1&&Oe();const p=h-1;if(p<0)return null;const g=m[p];return a(g.descriptor.id)},Gl=(e,t)=>e.descriptor.droppableId===t.descriptor.id;const kE={point:ki,value:0},bu={invisible:{},visible:{},all:[]},CD={displaced:bu,displacedBy:kE,at:null};var Ar=(e,t)=>n=>e<=n&&n<=t,SE=e=>{const t=Ar(e.top,e.bottom),n=Ar(e.left,e.right);return i=>{if(t(i.top)&&t(i.bottom)&&n(i.left)&&n(i.right))return!0;const o=t(i.top)||t(i.bottom),a=n(i.left)||n(i.right);if(o&&a)return!0;const d=i.top<e.top&&i.bottom>e.bottom,m=i.left<e.left&&i.right>e.right;return d&&m?!0:d&&a||m&&o}},jD=e=>{const t=Ar(e.top,e.bottom),n=Ar(e.left,e.right);return i=>t(i.top)&&t(i.bottom)&&n(i.left)&&n(i.right)};const Fv={direction:"vertical",line:"y",crossAxisLine:"x",start:"top",end:"bottom",size:"height",crossAxisStart:"left",crossAxisEnd:"right",crossAxisSize:"width"},wE={direction:"horizontal",line:"x",crossAxisLine:"y",start:"left",end:"right",size:"width",crossAxisStart:"top",crossAxisEnd:"bottom",crossAxisSize:"height"};var ED=e=>t=>{const n=Ar(t.top,t.bottom),i=Ar(t.left,t.right);return r=>e===Fv?n(r.top)&&n(r.bottom):i(r.left)&&i(r.right)};const ND=(e,t)=>{const n=t.frame?t.frame.scroll.diff.displacement:ki;return Pu(e,n)},ID=(e,t,n)=>t.subject.active?n(t.subject.active)(e):!1,TD=(e,t,n)=>n(t)(e),Vv=({target:e,destination:t,viewport:n,withDroppableDisplacement:i,isVisibleThroughFrameFn:r})=>{const o=i?ND(e,t):e;return ID(o,t,r)&&TD(o,n,r)},RD=e=>Vv({...e,isVisibleThroughFrameFn:SE}),CE=e=>Vv({...e,isVisibleThroughFrameFn:jD}),AD=e=>Vv({...e,isVisibleThroughFrameFn:ED(e.destination.axis)}),MD=(e,t,n)=>{if(typeof n=="boolean")return n;if(!t)return!0;const{invisible:i,visible:r}=t;if(i[e])return!1;const o=r[e];return o?o.shouldAnimate:!0};function DD(e,t){const n=e.page.marginBox,i={top:t.point.y,right:0,bottom:0,left:t.point.x};return Hr(Pv(n,i))}function _u({afterDragging:e,destination:t,displacedBy:n,viewport:i,forceShouldAnimate:r,la Line truncated `},Mf={dragHandleUsageInstructions:CD,onDragStart:jD,onDragUpdate:ED,onDragEnd:ND};function ID(e,t){return!!(e===t||Number.isNaN(e)&&Number.isNaN(t))}function NE(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!ID(e[n],t[n]))return!1;return!0}function rn(e,t){const n=C.useState(()=>({inputs:t,result:e()}))[0],i=C.useRef(!0),r=C.useRef(n),a=i.current||!!(t&&r.current.inputs&&NE(t,r.current.inputs))?r.current:{inputs:t,result:e()};return C.useEffect(()=>{i.current=!1,r.current=a},[a]),a.result}function it(e,t){return rn(()=>e,t)}const ki={x:0,y:0},Ti=(e,t)=>({x:e.x+t.x,y:e.y+t.y}),fr=(e,t)=>({x:e.x-t.x,y:e.y-t.y}),ko=(e,t)=>e.x===t.x&&e.y===t.y,Fl=e=>({x:e.x!==0?-e.x:0,y:e.y!==0?-e.y:0}),aa=(e,t,n=0)=>e==="x"?{x:t,y:n}:{x:n,y:t},xu=(e,t)=>Math.sqrt((t.x-e.x)**2+(t.y-e.y)**2),RS=(e,t)=>Math.min(...t.map(n=>xu(e,n))),IE=e=>t=>({x:e(t.x),y:e(t.y)});var TD=(e,t)=>{const n=$r({top:Math.max(t.top,e.top),right:Math.min(t.right,e.right),bottom:Math.min(t.bottom,e.bottom),left:Math.max(t.left,e.left)});return n.width<=0||n.height<=0?null:n};const zu=(e,t)=>({top:e.top+t.y,left:e.left+t.x,bottom:e.bottom+t.y,right:e.right+t.x}),AS=e=>[{x:e.left,y:e.top},{x:e.right,y:e.top},{x:e.left,y:e.bottom},{x:e.right,y:e.bottom}],RD={top:0,right:0,bottom:0,left:0},AD=(e,t)=>t?zu(e,t.scroll.diff.displacement):e,MD=(e,t,n)=>n&&n.increasedBy?{...e,[t.end]:e[t.end]+n.increasedBy[t.line]}:e,DD=(e,t)=>t&&t.shouldClipSubject?TD(t.pageMarginBox,e):$r(e);var Sl=({page:e,withPlaceholder:t,axis:n,frame:i})=>{const r=AD(e.marginBox,i),o=MD(r,n,t),a=DD(o,i);return{page:e,withPlaceholder:t,active:a}},qv=(e,t)=>{e.frame||Oe();const n=e.frame,i=fr(t,n.scroll.initial),r=Fl(i),o={...n,scroll:{initial:n.scroll.initial,current:t,diff:{value:i,displacement:r},max:n.scroll.max}},a=Sl({page:e.subject.page,withPlaceholder:e.subject.withPlaceholder,axis:e.axis,frame:o});return{...e,frame:o,subject:a}};function _i(e,t=NE){let n=null;function i(...r){if(n&&n.lastThis===this&&t(r,n.lastArgs))return n.lastResult;const o=e.apply(this,r);return n={lastResult:o,lastArgs:r,lastThis:this},o}return i.clear=function(){n=null},i}const TE=_i(e=>e.reduce((t,n)=>(t[n.descriptor.id]=n,t),{})),RE=_i(e=>e.reduce((t,n)=>(t[n.descriptor.id]=n,t),{})),Lm=_i(e=>Object.values(e)),OD=_i(e=>Object.values(e));var Vl=_i((e,t)=>OD(t).filter(i=>e===i.descriptor.droppableId).sort((i,r)=>i.descriptor.index-r.descriptor.index));function Wv(e){return e.at&&e.at.type==="REORDER"?e.at.destination:null}function zm(e){return e.at&&e.at.type==="COMBINE"?e.at.combine:null}var Pm=_i((e,t)=>t.filter(n=>n.descriptor.id!==e.descriptor.id)),LD=({isMovingForward:e,draggable:t,destination:n,insideDestination:i,previousImpact:r})=>{if(!n.isCombineEnabled||!Wv(r))return null;function a(x){const v={type:"COMBINE",combine:{draggableId:x,droppableId:n.descriptor.id}};return{...r,at:v}}const c=r.displaced.all,d=c.length?c[0]:null;if(e)return d?a(d):null;const m=Pm(t,i);if(!d){if(!m.length)return null;const x=m[m.length-1];return a(x.descriptor.id)}const h=m.findIndex(x=>x.descriptor.id===d);h===-1&&Oe();const p=h-1;if(p<0)return null;const g=m[p];return a(g.descriptor.id)},Ul=(e,t)=>e.descriptor.droppableId===t.descriptor.id;const AE={point:ki,value:0},vu={invisible:{},visible:{},all:[]},zD={displaced:vu,displacedBy:AE,at:null};var Rr=(e,t)=>n=>e<=n&&n<=t,ME=e=>{const t=Rr(e.top,e.bottom),n=Rr(e.left,e.right);return i=>{if(t(i.top)&&t(i.bottom)&&n(i.left)&&n(i.right))return!0;const o=t(i.top)||t(i.bottom),a=n(i.left)||n(i.right);if(o&&a)return!0;const d=i.top<e.top&&i.bottom>e.bottom,m=i.left<e.left&&i.right>e.right;return d&&m?!0:d&&a||m&&o}},PD=e=>{const t=Rr(e.top,e.bottom),n=Rr(e.left,e.right);return i=>t(i.top)&&t(i.bottom)&&n(i.left)&&n(i.right)};const Yv={direction:"vertical",line:"y",crossAxisLine:"x",start:"top",end:"bottom",size:"height",crossAxisStart:"left",crossAxisEnd:"right",crossAxisSize:"width"},DE={direction:"horizontal",line:"x",crossAxisLine:"y",start:"left",end:"right",size:"width",crossAxisStart:"top",crossAxisEnd:"bottom",crossAxisSize:"height"};var BD=e=>t=>{const n=Rr(t.top,t.bottom),i=Rr(t.left,t.right);return r=>e===Yv?n(r.top)&&n(r.bottom):i(r.left)&&i(r.right)};const $D=(e,t)=>{const n=t.frame?t.frame.scroll.diff.displacement:ki;return zu(e,n)},HD=(e,t,n)=>t.subject.active?n(t.subject.active)(e):!1,FD=(e,t,n)=>n(t)(e),Xv=({target:e,destination:t,viewport:n,withDroppableDisplacement:i,isVisibleThroughFrameFn:r})=>{const o=i?$D(e,t):e;return HD(o,t,r)&&FD(o,n,r)},VD=e=>Xv({...e,isVisibleThroughFrameFn:ME}),OE=e=>Xv({...e,isVisibleThroughFrameFn:PD}),UD=e=>Xv({...e,isVisibleThroughFrameFn:BD(e.destination.axis)}),GD=(e,t,n)=>{if(typeof n=="boolean")return n;if(!t)return!0;const{invisible:i,visible:r}=t;if(i[e])return!1;const o=r[e];return o?o.shouldAnimate:!0};function qD(e,t){const n=e.page.marginBox,i={top:t.point.y,right:0,bottom:0,left:t.point.x};return $r(Uv(n,i))}function bu({afterDragging:e,destination:t,displacedBy:n,viewport:i,forceShouldAnimate:r,la Line truncated
cursor: -webkit-grab; cursor: -webkit-grab;
cursor: grab; cursor: grab;
`;return{selector:t(jl.contextId),styles:{always:` `;return{selector:t(Cl.contextId),styles:{always:`
-webkit-touch-callout: none; -webkit-touch-callout: none;
-webkit-tap-highlight-color: rgba(0,0,0,0); -webkit-tap-highlight-color: rgba(0,0,0,0);
touch-action: manipulation; touch-action: manipulation;
`,resting:c,dragging:OL,dropAnimating:c}}})(),i=(()=>{const c=` `,resting:c,dragging:WL,dropAnimating:c}}})(),i=(()=>{const c=`
transition: ${au.outOfTheWay}; transition: ${au.outOfTheWay};
`;return{selector:t(Ux.contextId),styles:{dragging:c,dropAnimating:c,userCancel:c}}})(),r={selector:t(ML.contextId),styles:{always:"overflow-anchor: none;"}},a=[i,n,r,{selector:"body",styles:{dragging:` `;return{selector:t(Yx.contextId),styles:{dragging:c,dropAnimating:c,userCancel:c}}})(),r={selector:t(GL.contextId),styles:{always:"overflow-anchor: none;"}},a=[i,n,r,{selector:"body",styles:{dragging:`
cursor: grabbing; cursor: grabbing;
cursor: -webkit-grabbing; cursor: -webkit-grabbing;
user-select: none; user-select: none;
@@ -74,49 +86,49 @@ ${te.current.stack}
-moz-user-select: none; -moz-user-select: none;
-ms-user-select: none; -ms-user-select: none;
overflow-anchor: none; overflow-anchor: none;
`}}];return{always:Pc(a,"always"),resting:Pc(a,"resting"),dragging:Pc(a,"dragging"),dropAnimating:Pc(a,"dropAnimating"),userCancel:Pc(a,"userCancel")}};const pr=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u"?C.useLayoutEffect:C.useEffect,Tg=()=>{const e=document.querySelector("head");return e||Oe(),e},PS=e=>{const t=document.createElement("style");return e&&t.setAttribute("nonce",e),t.type="text/css",t};function zL(e,t){const n=nn(()=>LL(e),[e]),i=C.useRef(null),r=C.useRef(null),o=it(_i(p=>{const g=r.current;g||Oe(),g.textContent=p}),[]),a=it(p=>{const g=i.current;g||Oe(),g.textContent=p},[]);pr(()=>{!i.current&&!r.current||Oe();const p=PS(t),g=PS(t);return i.current=p,r.current=g,p.setAttribute(`${Cl}-always`,e),g.setAttribute(`${Cl}-dynamic`,e),Tg().appendChild(p),Tg().appendChild(g),a(n.always),o(n.resting),()=>{const x=v=>{const b=v.current;b||Oe(),Tg().removeChild(b),v.current=null};x(i),x(r)}},[t,a,o,n.always,n.resting,e]);const c=it(()=>o(n.dragging),[o,n.dragging]),d=it(p=>{if(p==="DROP"){o(n.dropAnimating);return}o(n.userCancel)},[o,n.dropAnimating,n.userCancel]),m=it(()=>{r.current&&o(n.resting)},[o,n.resting]);return nn(()=>({dragging:c,dropping:d,resting:m}),[c,d,m])}function QE(e,t){return Array.from(e.querySelectorAll(t))}var JE=e=>e&&e.ownerDocument&&e.ownerDocument.defaultView?e.ownerDocument.defaultView:window;function $m(e){return e instanceof JE(e).HTMLElement}function PL(e,t){const n=`[${jl.contextId}="${e}"]`,i=QE(document,n);if(!i.length)return null;const r=i.find(o=>o.getAttribute(jl.draggableId)===t);return!r||!$m(r)?null:r}function BL(e){const t=C.useRef({}),n=C.useRef(null),i=C.useRef(null),r=C.useRef(!1),o=it(function(g,x){const v={id:g,focus:x};return t.current[g]=v,function(){const k=t.current;k[g]!==v&&delete k[g]}},[]),a=it(function(g){const x=PL(e,g);x&&x!==document.activeElement&&x.focus()},[e]),c=it(function(g,x){n.current===g&&(n.current=x)},[]),d=it(function(){i.current||r.current&&(i.current=requestAnimationFrame(()=>{i.current=null;const g=n.current;g&&a(g)}))},[a]),m=it(function(g){n.current=null;const x=document.activeElement;x&&x.getAttribute(jl.draggableId)===g&&(n.current=g)},[]);return pr(()=>(r.current=!0,function(){r.current=!1;const g=i.current;g&&cancelAnimationFrame(g)}),[]),nn(()=>({register:o,tryRecordFocus:m,tryRestoreFocusRecorded:d,tryShiftRecord:c}),[o,m,d,c])}function $L(){const e={draggables:{},droppables:{}},t=[];function n(p){return t.push(p),function(){const x=t.indexOf(p);x!==-1&&t.splice(x,1)}}function i(p){t.length&&t.forEach(g=>g(p))}function r(p){return e.draggables[p]||null}function o(p){const g=r(p);return g||Oe(),g}const a={register:p=>{e.draggables[p.descriptor.id]=p,i({type:"ADDITION",value:p})},update:(p,g)=>{const x=e.draggables[g.descriptor.id];x&&x.uniqueId===p.uniqueId&&(delete e.draggables[g.descriptor.id],e.draggables[p.descriptor.id]=p)},unregister:p=>{const g=p.descriptor.id,x=r(g);x&&p.uniqueId===x.uniqueId&&(delete e.draggables[g],e.droppables[p.descriptor.droppableId]&&i({type:"REMOVAL",value:p}))},getById:o,findById:r,exists:p=>!!r(p),getAllByType:p=>Object.values(e.draggables).filter(g=>g.descriptor.type===p)};function c(p){return e.droppables[p]||null}function d(p){const g=c(p);return g||Oe(),g}const m={register:p=>{e.droppables[p.descriptor.id]=p},unregister:p=>{const g=c(p.descriptor.id);g&&p.uniqueId===g.uniqueId&&delete e.droppables[p.descriptor.id]},getById:d,findById:c,exists:p=>!!c(p),getAllByType:p=>Object.values(e.droppables).filter(g=>g.descriptor.type===p)};function h(){e.draggables={},e.droppables={},t.length=0}return{draggable:a,droppable:m,subscribe:n,clean:h}}function HL(){const e=nn($L,[]);return C.useEffect(()=>function(){e.clean()},[e]),e}var e0=Nt.createContext(null),im=()=>{const e=document.body;return e||Oe(),e};const FL={position:"absolute",width:"1px",height:"1px",margin:"-1px",border:"0",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)","clip-path":"inset(100%)"},VL=e=>`rfd-announcement-${e}`;function UL(e){const t=nn(()=>VL(e),[e]),n=C.useRef(null);return C.useEffect(function(){const o=document.createElement("div");return n.current=o,o.id=t,o.setAttribute("aria-live","assertive"),o.setAttribute("aria-atomic","true"),Jf(o.style,FL),im().appendChild(o),function(){setTimeout(function(){const d=im();d.contains(o)&&d.removeChild(o),o===n.current&&(n.current=null)})}},[t]),it(r=>{const o=n.current;if(o){o.textContent=r;return}},[])}const GL={separator:"::"};function t0(e,t=GL){const n=Nt.useId();return nn(()=>`${e}${t.separator}${n}`,[t.separator,e,n])}function qL({contextId:e,uniqueId:t}){return`rfd-hidden-text-${e}-${t}`}function WL({contextId:e,text:t}){const n=t0("hidden-text",{separator:"-"}),i=nn(()=>qL({contextId:e,uniqueId:n}),[n,e]);return C.useEffect(function(){const o=document.createElement("div");return o.id=i,o.textContent=t,o.style.display="none",im().appendChild(o),function(){const c=im();c.contains(o)&&c.removeChild(o)}},[i,t]),i}var Hm=Nt.c Line truncated `}}];return{always:Pc(a,"always"),resting:Pc(a,"resting"),dragging:Pc(a,"dragging"),dropAnimating:Pc(a,"dropAnimating"),userCancel:Pc(a,"userCancel")}};const pr=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u"?C.useLayoutEffect:C.useEffect,Rg=()=>{const e=document.querySelector("head");return e||Oe(),e},qS=e=>{const t=document.createElement("style");return e&&t.setAttribute("nonce",e),t.type="text/css",t};function XL(e,t){const n=rn(()=>YL(e),[e]),i=C.useRef(null),r=C.useRef(null),o=it(_i(p=>{const g=r.current;g||Oe(),g.textContent=p}),[]),a=it(p=>{const g=i.current;g||Oe(),g.textContent=p},[]);pr(()=>{!i.current&&!r.current||Oe();const p=qS(t),g=qS(t);return i.current=p,r.current=g,p.setAttribute(`${wl}-always`,e),g.setAttribute(`${wl}-dynamic`,e),Rg().appendChild(p),Rg().appendChild(g),a(n.always),o(n.resting),()=>{const x=v=>{const _=v.current;_||Oe(),Rg().removeChild(_),v.current=null};x(i),x(r)}},[t,a,o,n.always,n.resting,e]);const c=it(()=>o(n.dragging),[o,n.dragging]),d=it(p=>{if(p==="DROP"){o(n.dropAnimating);return}o(n.userCancel)},[o,n.dropAnimating,n.userCancel]),m=it(()=>{r.current&&o(n.resting)},[o,n.resting]);return rn(()=>({dragging:c,dropping:d,resting:m}),[c,d,m])}function lN(e,t){return Array.from(e.querySelectorAll(t))}var cN=e=>e&&e.ownerDocument&&e.ownerDocument.defaultView?e.ownerDocument.defaultView:window;function $m(e){return e instanceof cN(e).HTMLElement}function KL(e,t){const n=`[${Cl.contextId}="${e}"]`,i=lN(document,n);if(!i.length)return null;const r=i.find(o=>o.getAttribute(Cl.draggableId)===t);return!r||!$m(r)?null:r}function ZL(e){const t=C.useRef({}),n=C.useRef(null),i=C.useRef(null),r=C.useRef(!1),o=it(function(g,x){const v={id:g,focus:x};return t.current[g]=v,function(){const k=t.current;k[g]!==v&&delete k[g]}},[]),a=it(function(g){const x=KL(e,g);x&&x!==document.activeElement&&x.focus()},[e]),c=it(function(g,x){n.current===g&&(n.current=x)},[]),d=it(function(){i.current||r.current&&(i.current=requestAnimationFrame(()=>{i.current=null;const g=n.current;g&&a(g)}))},[a]),m=it(function(g){n.current=null;const x=document.activeElement;x&&x.getAttribute(Cl.draggableId)===g&&(n.current=g)},[]);return pr(()=>(r.current=!0,function(){r.current=!1;const g=i.current;g&&cancelAnimationFrame(g)}),[]),rn(()=>({register:o,tryRecordFocus:m,tryRestoreFocusRecorded:d,tryShiftRecord:c}),[o,m,d,c])}function QL(){const e={draggables:{},droppables:{}},t=[];function n(p){return t.push(p),function(){const x=t.indexOf(p);x!==-1&&t.splice(x,1)}}function i(p){t.length&&t.forEach(g=>g(p))}function r(p){return e.draggables[p]||null}function o(p){const g=r(p);return g||Oe(),g}const a={register:p=>{e.draggables[p.descriptor.id]=p,i({type:"ADDITION",value:p})},update:(p,g)=>{const x=e.draggables[g.descriptor.id];x&&x.uniqueId===p.uniqueId&&(delete e.draggables[g.descriptor.id],e.draggables[p.descriptor.id]=p)},unregister:p=>{const g=p.descriptor.id,x=r(g);x&&p.uniqueId===x.uniqueId&&(delete e.draggables[g],e.droppables[p.descriptor.droppableId]&&i({type:"REMOVAL",value:p}))},getById:o,findById:r,exists:p=>!!r(p),getAllByType:p=>Object.values(e.draggables).filter(g=>g.descriptor.type===p)};function c(p){return e.droppables[p]||null}function d(p){const g=c(p);return g||Oe(),g}const m={register:p=>{e.droppables[p.descriptor.id]=p},unregister:p=>{const g=c(p.descriptor.id);g&&p.uniqueId===g.uniqueId&&delete e.droppables[p.descriptor.id]},getById:d,findById:c,exists:p=>!!c(p),getAllByType:p=>Object.values(e.droppables).filter(g=>g.descriptor.type===p)};function h(){e.draggables={},e.droppables={},t.length=0}return{draggable:a,droppable:m,subscribe:n,clean:h}}function JL(){const e=rn(QL,[]);return C.useEffect(()=>function(){e.clean()},[e]),e}var o0=Nt.createContext(null),im=()=>{const e=document.body;return e||Oe(),e};const e6={position:"absolute",width:"1px",height:"1px",margin:"-1px",border:"0",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)","clip-path":"inset(100%)"},t6=e=>`rfd-announcement-${e}`;function n6(e){const t=rn(()=>t6(e),[e]),n=C.useRef(null);return C.useEffect(function(){const o=document.createElement("div");return n.current=o,o.id=t,o.setAttribute("aria-live","assertive"),o.setAttribute("aria-atomic","true"),Jf(o.style,e6),im().appendChild(o),function(){setTimeout(function(){const d=im();d.contains(o)&&d.removeChild(o),o===n.current&&(n.current=null)})}},[t]),it(r=>{const o=n.current;if(o){o.textContent=r;return}},[])}const i6={separator:"::"};function a0(e,t=i6){const n=Nt.useId();return rn(()=>`${e}${t.separator}${n}`,[t.separator,e,n])}function r6({contextId:e,uniqueId:t}){return`rfd-hidden-text-${e}-${t}`}function s6({contextId:e,text:t}){const n=a0("hidden-text",{separator:"-"}),i=rn(()=>r6({contextId:e,uniqueId:n}),[n,e]);return C.useEffect(function(){const o=document.createElement("div");return o.id=i,o.textContent=t,o.style.display="none",im().appendChild(o),function(){const c=im();c.contains(o)&&c.removeChild(o)}},[i,t]),i}var Hm=Nt.c Line truncated
`,m="/",h="*",p="",g="comment",x="declaration";function v(k,w){if(typeof k!="string")throw new TypeError("First argument must be a string");if(!k)return[];w=w||{};var S=1,j=1;function N(P){var G=P.match(t);G&&(S+=G.length);var $=P.lastIndexOf(d);j=~$?P.length-$:j+P.length}function O(){var P={line:S,column:j};return function(G){return G.position=new R(P),L(),G}}function R(P){this.start=P,this.end={line:S,column:j},this.source=w.source}R.prototype.content=k;function D(P){var G=new Error(w.source+":"+S+":"+j+": "+P);if(G.reason=P,G.filename=w.source,G.line=S,G.column=j,G.source=k,!w.silent)throw G}function I(P){var G=P.exec(k);if(G){var $=G[0];return N($),k=k.slice($.length),G}}function L(){I(n)}function M(P){var G;for(P=P||[];G=A();)G!==!1&&P.push(G);return P}function A(){var P=O();if(!(m!=k.charAt(0)||h!=k.charAt(1))){for(var G=2;p!=k.charAt(G)&&(h!=k.charAt(G)||m!=k.charAt(G+1));)++G;if(G+=2,p===k.charAt(G-1))return D("End of comment missing");var $=k.slice(2,G-2);return j+=2,N($),k=k.slice(G),j+=2,P({type:g,comment:$})}}function B(){var P=O(),G=I(i);if(G){if(A(),!I(r))return D("property missing ':'");var $=I(o),q=P({type:x,property:b(G[0].replace(e,p)),value:$?b($[0].replace(e,p)):p});return I(a),q}}function W(){var P=[];M(P);for(var G;G=B();)G!==!1&&(P.push(G),M(P));return P}return L(),W()}function b(k){return k?k.replace(c,p):p}return Bg=v,Bg}var nw;function mz(){if(nw)return el;nw=1;var e=el&&el.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(el,"__esModule",{value:!0}),el.default=n;const t=e(fz());function n(i,r){let o=null;if(!i||typeof i!="string")return o;const a=(0,t.default)(i),c=typeof r=="function";return a.forEach(d=>{if(d.type!=="declaration")return;const{property:m,value:h}=d;c?r(m,h,d):h&&(o=o||{},o[m]=h)}),o}return el}var Fc={},iw;function pz(){if(iw)return Fc;iw=1,Object.defineProperty(Fc,"__esModule",{value:!0}),Fc.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,o=function(m){return!m||n.test(m)||e.test(m)},a=function(m,h){return h.toUpperCase()},c=function(m,h){return"".concat(h,"-")},d=function(m,h){return h===void 0&&(h={}),o(m)?m:(m=m.toLowerCase(),h.reactCompat?m=m.replace(r,c):m=m.replace(i,c),m.replace(t,a))};return Fc.camelCase=d,Fc}var Vc,rw;function hz(){if(rw)return Vc;rw=1;var e=Vc&&Vc.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},t=e(mz()),n=pz();function i(r,o){var a={};return!r||typeof r!="string"||(0,t.default)(r,function(c,d){c&&d&&(a[(0,n.camelCase)(c,o)]=d)}),a}return i.default=i,Vc=i,Vc}var gz=hz();const yz=da(gz),CN=jN("end"),a0=jN("start");function jN(e){return t;function t(n){const i=n&&n.position&&n.position[e]||{};if(typeof i.line=="number"&&i.line>0&&typeof i.column=="number"&&i.column>0)return{line:i.line,column:i.column,offset:typeof i.offset=="number"&&i.offset>-1?i.offset:void 0}}}function xz(e){const t=a0(e),n=CN(e);if(t&&n)return{start:t,end:n}}function lu(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?sw(e.position):"start"in e||"end"in e?sw(e):"line"in e||"column"in e?Xx(e):""}function Xx(e){return ow(e&&e.line)+":"+ow(e&&e.column)}function sw(e){return Xx(e&&e.start)+"-"+Xx(e&&e.end)}function ow(e){return e&&typeof e=="number"?e:1}class Pi extends Error{constructor(t,n,i){super(),typeof n=="string"&&(i=n,n=void 0);let r="",o={},a=!1;if(n&&("line"in n&&"column"in n?o={place:n}:"start"in n&&"end"in n?o={place:n}:"type"in n?o={ancestors:[n],place:n.position}:o={...n}),typeof t=="string"?r=t:!o.cause&&t&&(a=!0,r=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof i=="string"){const d=i.indexOf(":");d===-1?o.ruleId=i:(o.source=i.slice(0,d),o.ruleId=i.slice(d+1))}if(!o.place&&o.ancestors&&o.ancestors){const d=o.ancestors[o.ancestors.length-1];d&&(o.place=d.position)}const c=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=c?c.line:void 0,this.name=lu(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=a&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Pi.prototype.file="";Pi.prototype.name="";Pi.prototype.reason="";Pi.prototype.message="";Pi.prototype.stack="";Pi.prototype.column=void 0;Pi.prototype.line=void 0;Pi.prototype.ancestors=void 0;Pi.prototype.cause=void 0;Pi.prototype.fatal=void 0;Pi.prototype.place=void 0;Pi.prototype.ruleId=void 0;Pi.prototype.source=void 0;const l0={}.hasOwnProperty,vz=new Map,bz=/[A-Z]/g,_z=new Set(["table","tbody","thead","tfoot","tr"]),kz=new Set(["td","th"]),EN="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Sz(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let i;if(t.development){if(typeof t.j Line truncated `,m="/",h="*",p="",g="comment",x="declaration";function v(k,w){if(typeof k!="string")throw new TypeError("First argument must be a string");if(!k)return[];w=w||{};var S=1,j=1;function N(P){var G=P.match(t);G&&(S+=G.length);var $=P.lastIndexOf(d);j=~$?P.length-$:j+P.length}function O(){var P={line:S,column:j};return function(G){return G.position=new R(P),L(),G}}function R(P){this.start=P,this.end={line:S,column:j},this.source=w.source}R.prototype.content=k;function D(P){var G=new Error(w.source+":"+S+":"+j+": "+P);if(G.reason=P,G.filename=w.source,G.line=S,G.column=j,G.source=k,!w.silent)throw G}function I(P){var G=P.exec(k);if(G){var $=G[0];return N($),k=k.slice($.length),G}}function L(){I(n)}function M(P){var G;for(P=P||[];G=A();)G!==!1&&P.push(G);return P}function A(){var P=O();if(!(m!=k.charAt(0)||h!=k.charAt(1))){for(var G=2;p!=k.charAt(G)&&(h!=k.charAt(G)||m!=k.charAt(G+1));)++G;if(G+=2,p===k.charAt(G-1))return D("End of comment missing");var $=k.slice(2,G-2);return j+=2,N($),k=k.slice(G),j+=2,P({type:g,comment:$})}}function B(){var P=O(),G=I(i);if(G){if(A(),!I(r))return D("property missing ':'");var $=I(o),q=P({type:x,property:_(G[0].replace(e,p)),value:$?_($[0].replace(e,p)):p});return I(a),q}}function W(){var P=[];M(P);for(var G;G=B();)G!==!1&&(P.push(G),M(P));return P}return L(),W()}function _(k){return k?k.replace(c,p):p}return $g=v,$g}var uw;function C8(){if(uw)return el;uw=1;var e=el&&el.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(el,"__esModule",{value:!0}),el.default=n;const t=e(w8());function n(i,r){let o=null;if(!i||typeof i!="string")return o;const a=(0,t.default)(i),c=typeof r=="function";return a.forEach(d=>{if(d.type!=="declaration")return;const{property:m,value:h}=d;c?r(m,h,d):h&&(o=o||{},o[m]=h)}),o}return el}var Fc={},dw;function j8(){if(dw)return Fc;dw=1,Object.defineProperty(Fc,"__esModule",{value:!0}),Fc.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,o=function(m){return!m||n.test(m)||e.test(m)},a=function(m,h){return h.toUpperCase()},c=function(m,h){return"".concat(h,"-")},d=function(m,h){return h===void 0&&(h={}),o(m)?m:(m=m.toLowerCase(),h.reactCompat?m=m.replace(r,c):m=m.replace(i,c),m.replace(t,a))};return Fc.camelCase=d,Fc}var Vc,fw;function E8(){if(fw)return Vc;fw=1;var e=Vc&&Vc.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},t=e(C8()),n=j8();function i(r,o){var a={};return!r||typeof r!="string"||(0,t.default)(r,function(c,d){c&&d&&(a[(0,n.camelCase)(c,o)]=d)}),a}return i.default=i,Vc=i,Vc}var N8=E8();const I8=ma(N8),ON=LN("end"),m0=LN("start");function LN(e){return t;function t(n){const i=n&&n.position&&n.position[e]||{};if(typeof i.line=="number"&&i.line>0&&typeof i.column=="number"&&i.column>0)return{line:i.line,column:i.column,offset:typeof i.offset=="number"&&i.offset>-1?i.offset:void 0}}}function T8(e){const t=m0(e),n=ON(e);if(t&&n)return{start:t,end:n}}function lu(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?mw(e.position):"start"in e||"end"in e?mw(e):"line"in e||"column"in e?Jx(e):""}function Jx(e){return pw(e&&e.line)+":"+pw(e&&e.column)}function mw(e){return Jx(e&&e.start)+"-"+Jx(e&&e.end)}function pw(e){return e&&typeof e=="number"?e:1}class zi extends Error{constructor(t,n,i){super(),typeof n=="string"&&(i=n,n=void 0);let r="",o={},a=!1;if(n&&("line"in n&&"column"in n?o={place:n}:"start"in n&&"end"in n?o={place:n}:"type"in n?o={ancestors:[n],place:n.position}:o={...n}),typeof t=="string"?r=t:!o.cause&&t&&(a=!0,r=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof i=="string"){const d=i.indexOf(":");d===-1?o.ruleId=i:(o.source=i.slice(0,d),o.ruleId=i.slice(d+1))}if(!o.place&&o.ancestors&&o.ancestors){const d=o.ancestors[o.ancestors.length-1];d&&(o.place=d.position)}const c=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=c?c.line:void 0,this.name=lu(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=a&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}zi.prototype.file="";zi.prototype.name="";zi.prototype.reason="";zi.prototype.message="";zi.prototype.stack="";zi.prototype.column=void 0;zi.prototype.line=void 0;zi.prototype.ancestors=void 0;zi.prototype.cause=void 0;zi.prototype.fatal=void 0;zi.prototype.place=void 0;zi.prototype.ruleId=void 0;zi.prototype.source=void 0;const p0={}.hasOwnProperty,R8=new Map,A8=/[A-Z]/g,M8=new Set(["table","tbody","thead","tfoot","tr"]),D8=new Set(["td","th"]),zN="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function O8(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let i;if(t.development){if(typeof t.j Line truncated
`;break}case-3:{a=`\r `;break}case-3:{a=`\r
`;break}case-2:{a=t?" ":" ";break}case-1:{if(!t&&r)continue;a=" ";break}default:a=String.fromCharCode(o)}r=o===-2,i.push(a)}return i.join("")}function RB(e){const i={constructs:AN([EB,...(e||{}).extensions||[]]),content:r(qz),defined:[],document:r(Yz),flow:r(fB),lazy:{},string:r(hB),text:r(gB)};return i;function r(o){return a;function a(c){return NB(i,o,c)}}}function AB(e){for(;!zN(e););return e}const gw=/[\0\t\n\r]/g;function MB(){let e=1,t="",n=!0,i;return r;function r(o,a,c){const d=[];let m,h,p,g,x;for(o=t+(typeof o=="string"?o.toString():new TextDecoder(a||void 0).decode(o)),p=0,t="",n&&(o.charCodeAt(0)===65279&&p++,n=void 0);p<o.length;){if(gw.lastIndex=p,m=gw.exec(o),g=m&&m.index!==void 0?m.index:o.length,x=o.charCodeAt(g),!m){t=o.slice(p);break}if(x===10&&p===g&&i)d.push(-3),i=void 0;else switch(i&&(d.push(-5),i=void 0),p<g&&(d.push(o.slice(p,g)),e+=g-p),x){case 0:{d.push(65533),e++;break}case 9:{for(h=Math.ceil(e/4)*4,d.push(-2);e++<h;)d.push(-1);break}case 10:{d.push(-4),e=1;break}default:i=!0,e=1}p=g+1}return c&&(i&&d.push(-5),t&&d.push(t),d.push(null)),d}}const DB=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function OB(e){return e.replace(DB,LB)}function LB(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const r=n.charCodeAt(1),o=r===120||r===88;return MN(n.slice(o?2:1),o?16:10)}return f0(n)||e}const VN={}.hasOwnProperty;function zB(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),PB(n)(AB(RB(n).document().write(MB()(e,t,!0))))}function PB(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Mt),autolinkProtocol:L,autolinkEmail:L,atxHeading:o(Ze),blockQuote:o(ie),characterEscape:L,characterReference:L,codeFenced:o(we),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:o(we,a),codeText:o(je,a),codeTextData:L,data:L,codeFlowValue:L,definition:o(Te),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:o(Ge),hardBreakEscape:o(Ye),hardBreakTrailing:o(Ye),htmlFlow:o(mt,a),htmlFlowData:L,htmlText:o(mt,a),htmlTextData:L,image:o(Ft),label:a,link:o(Mt),listItem:o(he),listItemValue:g,listOrdered:o(jt,p),listUnordered:o(jt),paragraph:o(ze),reference:F,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:o(Ze),strong:o(ot),thematicBreak:o(lt)},exit:{atxHeading:d(),atxHeadingSequence:O,autolink:d(),autolinkEmail:ue,autolinkProtocol:ae,blockQuote:d(),characterEscapeValue:M,characterReferenceMarkerHexadecimal:ee,characterReferenceMarkerNumeric:ee,characterReferenceValue:te,characterReference:se,codeFenced:d(k),codeFencedFence:b,codeFencedFenceInfo:x,codeFencedFenceMeta:v,codeFlowValue:M,codeIndented:d(w),codeText:d(G),codeTextData:M,data:M,definition:d(),definitionDestinationString:N,definitionLabelString:S,definitionTitleString:j,emphasis:d(),hardBreakEscape:d(B),hardBreakTrailing:d(B),htmlFlow:d(W),htmlFlowData:M,htmlText:d(P),htmlTextData:M,image:d(q),label:Q,labelText:Y,lineEnding:A,link:d($),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:K,resourceDestinationString:V,resourceTitleString:U,resource:Z,setextHeading:d(I),setextHeadingLineSequence:D,setextHeadingText:R,strong:d(),thematicBreak:d()}};UN(t,(e||{}).mdastExtensions||[]);const n={};return i;function i(me){let be={type:"root",children:[]};const Ae={stack:[be],tokenStack:[],config:t,enter:c,exit:m,buffer:a,resume:h,data:n},Be=[];let We=-1;for(;++We<me.length;)if(me[We][1].type==="listOrdered"||me[We][1].type==="listUnordered")if(me[We][0]==="enter")Be.push(We);else{const Lt=Be.pop();We=r(me,Lt,We)}for(We=-1;++We<me.length;){const Lt=t[me[We][0]];VN.call(Lt,me[We][1].type)&&Lt[me[We][1].type].call(Object.assign({sliceSerialize:me[We][2].sliceSerialize},Ae),me[We][1])}if(Ae.tokenStack.length>0){const Lt=Ae.tokenStack[Ae.tokenStack.length-1];(Lt[1]||yw).call(Ae,void 0,Lt[0])}for(be.position={start:po(me.length>0?me[0][1].start:{line:1,column:1,offset:0}),end:po(me.length>0?me[me.length-2][1].end:{line:1,column:1,offset:0})},We=-1;++We<t.transforms.length;)be=t.transforms[We](be)||be;return be}function r(me,be,Ae){let Be=be-1,We=-1,Lt=!1,pt,ke,qe,Qe;for(;++Be<=Ae;){const $e=me[Be];switch($e[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{$e[0]==="enter"?We++:We--,Qe=void 0;break}case"lineEndingBlank":{$e[0]==="enter"&&(pt&&!Qe&&!We&&!qe&&(qe=Be),Qe=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Qe=void 0}if(!We&&$e[0]==="enter"&&$e[1].type==="listItemPrefix"||We===-1&&$e[0]==="exit"&&($e[1].type==="listUnordered"||$e[1].type==="listOrdered")){if(pt){let He=Be;for(ke=void 0;He--;){const Vt=me[He];if(Vt[1].type==="lineEnding"||Vt[1].type==="lineEndingBlank"){if(Vt[0]==="exit")continue;ke&&(me[ke][1].type="lineEndingBlank",Lt=!0),Vt[1].type="lineEnding",ke=He}else if(!(Vt[1].type==="linePrefix"||Vt[1].type==="blockQuotePrefix"||Vt[1].type==="blockQuotePrefixWhitespace"Line truncated `;break}case-2:{a=t?" ":" ";break}case-1:{if(!t&&r)continue;a=" ";break}default:a=String.fromCharCode(o)}r=o===-2,i.push(a)}return i.join("")}function VB(e){const i={constructs:FN([BB,...(e||{}).extensions||[]]),content:r(rP),defined:[],document:r(oP),flow:r(wB),lazy:{},string:r(EB),text:r(NB)};return i;function r(o){return a;function a(c){return $B(i,o,c)}}}function UB(e){for(;!WN(e););return e}const ww=/[\0\t\n\r]/g;function GB(){let e=1,t="",n=!0,i;return r;function r(o,a,c){const d=[];let m,h,p,g,x;for(o=t+(typeof o=="string"?o.toString():new TextDecoder(a||void 0).decode(o)),p=0,t="",n&&(o.charCodeAt(0)===65279&&p++,n=void 0);p<o.length;){if(ww.lastIndex=p,m=ww.exec(o),g=m&&m.index!==void 0?m.index:o.length,x=o.charCodeAt(g),!m){t=o.slice(p);break}if(x===10&&p===g&&i)d.push(-3),i=void 0;else switch(i&&(d.push(-5),i=void 0),p<g&&(d.push(o.slice(p,g)),e+=g-p),x){case 0:{d.push(65533),e++;break}case 9:{for(h=Math.ceil(e/4)*4,d.push(-2);e++<h;)d.push(-1);break}case 10:{d.push(-4),e=1;break}default:i=!0,e=1}p=g+1}return c&&(i&&d.push(-5),t&&d.push(t),d.push(null)),d}}const qB=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function WB(e){return e.replace(qB,YB)}function YB(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const r=n.charCodeAt(1),o=r===120||r===88;return VN(n.slice(o?2:1),o?16:10)}return x0(n)||e}const JN={}.hasOwnProperty;function XB(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),KB(n)(UB(VB(n).document().write(GB()(e,t,!0))))}function KB(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Dt),autolinkProtocol:L,autolinkEmail:L,atxHeading:o(Ze),blockQuote:o(ie),characterEscape:L,characterReference:L,codeFenced:o(we),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:o(we,a),codeText:o(je,a),codeTextData:L,data:L,codeFlowValue:L,definition:o(Te),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:o(Ge),hardBreakEscape:o(Xe),hardBreakTrailing:o(Xe),htmlFlow:o(mt,a),htmlFlowData:L,htmlText:o(mt,a),htmlTextData:L,image:o(Ft),label:a,link:o(Dt),listItem:o(he),listItemValue:g,listOrdered:o(jt,p),listUnordered:o(jt),paragraph:o(ze),reference:F,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:o(Ze),strong:o(ot),thematicBreak:o(lt)},exit:{atxHeading:d(),atxHeadingSequence:O,autolink:d(),autolinkEmail:ue,autolinkProtocol:ae,blockQuote:d(),characterEscapeValue:M,characterReferenceMarkerHexadecimal:ee,characterReferenceMarkerNumeric:ee,characterReferenceValue:te,characterReference:se,codeFenced:d(k),codeFencedFence:_,codeFencedFenceInfo:x,codeFencedFenceMeta:v,codeFlowValue:M,codeIndented:d(w),codeText:d(G),codeTextData:M,data:M,definition:d(),definitionDestinationString:N,definitionLabelString:S,definitionTitleString:j,emphasis:d(),hardBreakEscape:d(B),hardBreakTrailing:d(B),htmlFlow:d(W),htmlFlowData:M,htmlText:d(P),htmlTextData:M,image:d(q),label:Q,labelText:Y,lineEnding:A,link:d($),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:K,resourceDestinationString:V,resourceTitleString:U,resource:Z,setextHeading:d(I),setextHeadingLineSequence:D,setextHeadingText:R,strong:d(),thematicBreak:d()}};eI(t,(e||{}).mdastExtensions||[]);const n={};return i;function i(me){let be={type:"root",children:[]};const Ae={stack:[be],tokenStack:[],config:t,enter:c,exit:m,buffer:a,resume:h,data:n},Be=[];let We=-1;for(;++We<me.length;)if(me[We][1].type==="listOrdered"||me[We][1].type==="listUnordered")if(me[We][0]==="enter")Be.push(We);else{const zt=Be.pop();We=r(me,zt,We)}for(We=-1;++We<me.length;){const zt=t[me[We][0]];JN.call(zt,me[We][1].type)&&zt[me[We][1].type].call(Object.assign({sliceSerialize:me[We][2].sliceSerialize},Ae),me[We][1])}if(Ae.tokenStack.length>0){const zt=Ae.tokenStack[Ae.tokenStack.length-1];(zt[1]||Cw).call(Ae,void 0,zt[0])}for(be.position={start:ho(me.length>0?me[0][1].start:{line:1,column:1,offset:0}),end:ho(me.length>0?me[me.length-2][1].end:{line:1,column:1,offset:0})},We=-1;++We<t.transforms.length;)be=t.transforms[We](be)||be;return be}function r(me,be,Ae){let Be=be-1,We=-1,zt=!1,ht,ke,qe,Qe;for(;++Be<=Ae;){const $e=me[Be];switch($e[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{$e[0]==="enter"?We++:We--,Qe=void 0;break}case"lineEndingBlank":{$e[0]==="enter"&&(ht&&!Qe&&!We&&!qe&&(qe=Be),Qe=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Qe=void 0}if(!We&&$e[0]==="enter"&&$e[1].type==="listItemPrefix"||We===-1&&$e[0]==="exit"&&($e[1].type==="listUnordered"||$e[1].type==="listOrdered")){if(ht){let Fe=Be;for(ke=void 0;Fe--;){const Vt=me[Fe];if(Vt[1].type==="lineEnding"||Vt[1].type==="lineEndingBlank"){if(Vt[0]==="exit")continue;ke&&(me[ke][1].type="lineEndingBlank",zt=!0),Vt[1].type="lineEnding",ke=Fe}else if(!(Vt[1].type==="linePrefix"||Vt[1].type==="blockQuotePrefix"||Vt[1].type==="blockQuotePrefixWhitespace"Line truncated
`}]}function VB(e,t){const n=t.value?t.value+` `}]}function t9(e,t){const n=t.value?t.value+`
`:"",i={},r=t.lang?t.lang.split(/\s+/):[];r.length>0&&(i.className=["language-"+r[0]]);let o={type:"element",tagName:"code",properties:i,children:[{type:"text",value:n}]};return t.meta&&(o.data={meta:t.meta}),e.patch(t,o),o=e.applyData(t,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(t,o),o}function UB(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function GB(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function qB(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(t.identifier).toUpperCase(),r=Wl(i.toLowerCase()),o=e.footnoteOrder.indexOf(i);let a,c=e.footnoteCounts.get(i);c===void 0?(c=0,e.footnoteOrder.push(i),a=e.footnoteOrder.length):a=o+1,c+=1,e.footnoteCounts.set(i,c);const d={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+r,id:n+"fnref-"+r+(c>1?"-"+c:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};e.patch(t,d);const m={type:"element",tagName:"sup",properties:{},children:[d]};return e.patch(t,m),e.applyData(t,m)}function WB(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function YB(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function GN(e,t){const n=t.referenceType;let i="]";if(n==="collapsed"?i+="[]":n==="full"&&(i+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+i}];const r=e.all(t),o=r[0];o&&o.type==="text"?o.value="["+o.value:r.unshift({type:"text",value:"["});const a=r[r.length-1];return a&&a.type==="text"?a.value+=i:r.push({type:"text",value:i}),r}function XB(e,t){const n=String(t.identifier).toUpperCase(),i=e.definitionById.get(n);if(!i)return GN(e,t);const r={src:Wl(i.url||""),alt:t.alt};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,o),e.applyData(t,o)}function KB(e,t){const n={src:Wl(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const i={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,i),e.applyData(t,i)}function ZB(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const i={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,i),e.applyData(t,i)}function QB(e,t){const n=String(t.identifier).toUpperCase(),i=e.definitionById.get(n);if(!i)return GN(e,t);const r={href:Wl(i.url||"")};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function JB(e,t){const n={href:Wl(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const i={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function e9(e,t,n){const i=e.all(t),r=n?t9(n):qN(t),o={},a=[];if(typeof t.checked=="boolean"){const h=i[0];let p;h&&h.type==="element"&&h.tagName==="p"?p=h:(p={type:"element",tagName:"p",properties:{},children:[]},i.unshift(p)),p.children.length>0&&p.children.unshift({type:"text",value:" "}),p.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let c=-1;for(;++c<i.length;){const h=i[c];(r||c!==0||h.type!=="element"||h.tagName!=="p")&&a.push({type:"text",value:` `:"",i={},r=t.lang?t.lang.split(/\s+/):[];r.length>0&&(i.className=["language-"+r[0]]);let o={type:"element",tagName:"code",properties:i,children:[{type:"text",value:n}]};return t.meta&&(o.data={meta:t.meta}),e.patch(t,o),o=e.applyData(t,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(t,o),o}function n9(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function i9(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function r9(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(t.identifier).toUpperCase(),r=ql(i.toLowerCase()),o=e.footnoteOrder.indexOf(i);let a,c=e.footnoteCounts.get(i);c===void 0?(c=0,e.footnoteOrder.push(i),a=e.footnoteOrder.length):a=o+1,c+=1,e.footnoteCounts.set(i,c);const d={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+r,id:n+"fnref-"+r+(c>1?"-"+c:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};e.patch(t,d);const m={type:"element",tagName:"sup",properties:{},children:[d]};return e.patch(t,m),e.applyData(t,m)}function s9(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function o9(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function tI(e,t){const n=t.referenceType;let i="]";if(n==="collapsed"?i+="[]":n==="full"&&(i+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+i}];const r=e.all(t),o=r[0];o&&o.type==="text"?o.value="["+o.value:r.unshift({type:"text",value:"["});const a=r[r.length-1];return a&&a.type==="text"?a.value+=i:r.push({type:"text",value:i}),r}function a9(e,t){const n=String(t.identifier).toUpperCase(),i=e.definitionById.get(n);if(!i)return tI(e,t);const r={src:ql(i.url||""),alt:t.alt};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,o),e.applyData(t,o)}function l9(e,t){const n={src:ql(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const i={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,i),e.applyData(t,i)}function c9(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const i={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,i),e.applyData(t,i)}function u9(e,t){const n=String(t.identifier).toUpperCase(),i=e.definitionById.get(n);if(!i)return tI(e,t);const r={href:ql(i.url||"")};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function d9(e,t){const n={href:ql(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const i={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function f9(e,t,n){const i=e.all(t),r=n?m9(n):nI(t),o={},a=[];if(typeof t.checked=="boolean"){const h=i[0];let p;h&&h.type==="element"&&h.tagName==="p"?p=h:(p={type:"element",tagName:"p",properties:{},children:[]},i.unshift(p)),p.children.length>0&&p.children.unshift({type:"text",value:" "}),p.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let c=-1;for(;++c<i.length;){const h=i[c];(r||c!==0||h.type!=="element"||h.tagName!=="p")&&a.push({type:"text",value:`
`}),h.type==="element"&&h.tagName==="p"&&!r?a.push(...h.children):a.push(h)}const d=i[i.length-1];d&&(r||d.type!=="element"||d.tagName!=="p")&&a.push({type:"text",value:` `}),h.type==="element"&&h.tagName==="p"&&!r?a.push(...h.children):a.push(h)}const d=i[i.length-1];d&&(r||d.type!=="element"||d.tagName!=="p")&&a.push({type:"text",value:`
`});const m={type:"element",tagName:"li",properties:o,children:a};return e.patch(t,m),e.applyData(t,m)}function t9(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const n=e.children;let i=-1;for(;!t&&++i<n.length;)t=qN(n[i])}return t}function qN(e){const t=e.spread;return t??e.children.length>1}function n9(e,t){const n={},i=e.all(t);let r=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++r<i.length;){const a=i[r];if(a.type==="element"&&a.tagName==="li"&&a.properties&&Array.isArray(a.properties.className)&&a.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const o={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(i,!0)};return e.patch(t,o),e.applyData(t,o)}function i9(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function r9(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function s9(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function o9(e,t){const n=e.all(t),i=n.shift(),r=[];if(i){const a={type:"element",tagName:"thead",properties:{},children:e.wrap([i],!0)};e.patch(t.children[0],a),r.push(a)}if(n.length>0){const a={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},c=a0(t.children[1]),d=CN(t.children[t.children.length-1]);c&&d&&(a.position={start:c,end:d}),r.push(a)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(r,!0)};return e.patch(t,o),e.applyData(t,o)}function a9(e,t,n){const i=n?n.children:void 0,o=(i?i.indexOf(t):1)===0?"th":"td",a=n&&n.type==="table"?n.align:void 0,c=a?a.length:t.children.length;let d=-1;const m=[];for(;++d<c;){const p=t.children[d],g={},x=a?a[d]:void 0;x&&(g.align=x);let v={type:"element",tagName:o,properties:g,children:[]};p&&(v.children=e.all(p),e.patch(p,v),v=e.applyData(p,v)),m.push(v)}const h={type:"element",tagName:"tr",properties:{},children:e.wrap(m,!0)};return e.patch(t,h),e.applyData(t,h)}function l9(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const xw=9,vw=32;function c9(e){const t=String(e),n=/\r?\n|\r/g;let i=n.exec(t),r=0;const o=[];for(;i;)o.push(bw(t.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=n.exec(t);return o.push(bw(t.slice(r),r>0,!1)),o.join("")}function bw(e,t,n){let i=0,r=e.length;if(t){let o=e.codePointAt(i);for(;o===xw||o===vw;)i++,o=e.codePointAt(i)}if(n){let o=e.codePointAt(r-1);for(;o===xw||o===vw;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function u9(e,t){const n={type:"text",value:c9(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function d9(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const f9={blockquote:HB,break:FB,code:VB,delete:UB,emphasis:GB,footnoteReference:qB,heading:WB,html:YB,imageReference:XB,image:KB,inlineCode:ZB,linkReference:QB,link:JB,listItem:e9,list:n9,paragraph:i9,root:r9,strong:s9,table:o9,tableCell:l9,tableRow:a9,text:u9,thematicBreak:d9,toml:af,yaml:af,definition:af,footnoteDefinition:af};function af(){}const WN=-1,Wm=0,uu=1,cm=2,p0=3,h0=4,g0=5,y0=6,YN=7,XN=8,_w=typeof self=="object"?self:globalThis,m9=(e,t)=>{const n=(r,o)=>(e.set(o,r),r),i=r=>{if(e.has(r))return e.get(r);const[o,a]=t[r];switch(o){case Wm:case WN:return n(a,r);case uu:{const c=n([],r);for(const d of a)c.push(i(d));return c}case cm:{const c=n({},r);for(const[d,m]of a)c[i(d)]=i(m);return c}case p0:return n(new Date(a),r);case h0:{const{source:c,flags:d}=a;return n(new RegExp(c,d),r)}case g0:{const c=n(new Map,r);for(const[d,m]of a)c.set(i(d),i(m));return c}case y0:{const c=n(new Set,r);for(const d of a)c.add(i(d));return c}case YN:{const{name:c,message:d}=a;return n(new _w[c](d),r)}case XN:return n(BigInt(a),r);case"BigInt":return n(Object(BigInt(a)),r);case"ArrayBuffer":return n(new Uint8Array(a).buffer,a);case"DataView":{const{buffer:c}=new Uint8Array(a);return n(new DataView(c),a)}}return n(new _w[o](a),r)};return i},kw=e=>m9(new Map,e)(0),tl="",{toString:p9}={},{keys:h9}=Object,Gc=e=>{const t=typeof e;if(t!=="object"||!e)return[Wm,t];const n=p9.call(e).slice(8,-1);switch(n){case"Array":return[uu,tl];case"Object":return[cm,tl];case"Date":return[p0,tl];case"RegExp":return[h0,tl];case"Map":return[g0,tl];case"Set":return[y0,tl];case"DataView":return[uu,n]}return n.includes("Array")?[uu,n]:n.includes("Error")?[YN,n]:[cm,n]},lf=([e,t])=>e===Wm&&(t==="function"||t==="symbol"),g9=(e,t,n,i)=>{const r=(a,c)=>{const d=i.push(a)-1;return n.set(c,d),d},o=a=>{if(n.has(a))return n.get(a);let[c,d]=Gc(a);switch(c){case Wm:{let h=a;switch(d){case"bigint":c=XN,h=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+d);h=null;break;case"undefined":return r([WN],a)}return r([c,h],a)}case uu:{if(d){let g=a;return d==="DataView"?g=new Uint8Array(a.buffer):d==="ArrayBuffer"&&(g=new Uint8Array( Line truncated `});const m={type:"element",tagName:"li",properties:o,children:a};return e.patch(t,m),e.applyData(t,m)}function m9(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const n=e.children;let i=-1;for(;!t&&++i<n.length;)t=nI(n[i])}return t}function nI(e){const t=e.spread;return t??e.children.length>1}function p9(e,t){const n={},i=e.all(t);let r=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++r<i.length;){const a=i[r];if(a.type==="element"&&a.tagName==="li"&&a.properties&&Array.isArray(a.properties.className)&&a.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const o={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(i,!0)};return e.patch(t,o),e.applyData(t,o)}function h9(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function g9(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function y9(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function x9(e,t){const n=e.all(t),i=n.shift(),r=[];if(i){const a={type:"element",tagName:"thead",properties:{},children:e.wrap([i],!0)};e.patch(t.children[0],a),r.push(a)}if(n.length>0){const a={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},c=m0(t.children[1]),d=ON(t.children[t.children.length-1]);c&&d&&(a.position={start:c,end:d}),r.push(a)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(r,!0)};return e.patch(t,o),e.applyData(t,o)}function v9(e,t,n){const i=n?n.children:void 0,o=(i?i.indexOf(t):1)===0?"th":"td",a=n&&n.type==="table"?n.align:void 0,c=a?a.length:t.children.length;let d=-1;const m=[];for(;++d<c;){const p=t.children[d],g={},x=a?a[d]:void 0;x&&(g.align=x);let v={type:"element",tagName:o,properties:g,children:[]};p&&(v.children=e.all(p),e.patch(p,v),v=e.applyData(p,v)),m.push(v)}const h={type:"element",tagName:"tr",properties:{},children:e.wrap(m,!0)};return e.patch(t,h),e.applyData(t,h)}function b9(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const jw=9,Ew=32;function _9(e){const t=String(e),n=/\r?\n|\r/g;let i=n.exec(t),r=0;const o=[];for(;i;)o.push(Nw(t.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=n.exec(t);return o.push(Nw(t.slice(r),r>0,!1)),o.join("")}function Nw(e,t,n){let i=0,r=e.length;if(t){let o=e.codePointAt(i);for(;o===jw||o===Ew;)i++,o=e.codePointAt(i)}if(n){let o=e.codePointAt(r-1);for(;o===jw||o===Ew;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function k9(e,t){const n={type:"text",value:_9(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function S9(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const w9={blockquote:JB,break:e9,code:t9,delete:n9,emphasis:i9,footnoteReference:r9,heading:s9,html:o9,imageReference:a9,image:l9,inlineCode:c9,linkReference:u9,link:d9,listItem:f9,list:p9,paragraph:h9,root:g9,strong:y9,table:x9,tableCell:b9,tableRow:v9,text:k9,thematicBreak:S9,toml:af,yaml:af,definition:af,footnoteDefinition:af};function af(){}const iI=-1,Wm=0,uu=1,cm=2,b0=3,_0=4,k0=5,S0=6,rI=7,sI=8,Iw=typeof self=="object"?self:globalThis,C9=(e,t)=>{const n=(r,o)=>(e.set(o,r),r),i=r=>{if(e.has(r))return e.get(r);const[o,a]=t[r];switch(o){case Wm:case iI:return n(a,r);case uu:{const c=n([],r);for(const d of a)c.push(i(d));return c}case cm:{const c=n({},r);for(const[d,m]of a)c[i(d)]=i(m);return c}case b0:return n(new Date(a),r);case _0:{const{source:c,flags:d}=a;return n(new RegExp(c,d),r)}case k0:{const c=n(new Map,r);for(const[d,m]of a)c.set(i(d),i(m));return c}case S0:{const c=n(new Set,r);for(const d of a)c.add(i(d));return c}case rI:{const{name:c,message:d}=a;return n(new Iw[c](d),r)}case sI:return n(BigInt(a),r);case"BigInt":return n(Object(BigInt(a)),r);case"ArrayBuffer":return n(new Uint8Array(a).buffer,a);case"DataView":{const{buffer:c}=new Uint8Array(a);return n(new DataView(c),a)}}return n(new Iw[o](a),r)};return i},Tw=e=>C9(new Map,e)(0),tl="",{toString:j9}={},{keys:E9}=Object,Gc=e=>{const t=typeof e;if(t!=="object"||!e)return[Wm,t];const n=j9.call(e).slice(8,-1);switch(n){case"Array":return[uu,tl];case"Object":return[cm,tl];case"Date":return[b0,tl];case"RegExp":return[_0,tl];case"Map":return[k0,tl];case"Set":return[S0,tl];case"DataView":return[uu,n]}return n.includes("Array")?[uu,n]:n.includes("Error")?[rI,n]:[cm,n]},lf=([e,t])=>e===Wm&&(t==="function"||t==="symbol"),N9=(e,t,n,i)=>{const r=(a,c)=>{const d=i.push(a)-1;return n.set(c,d),d},o=a=>{if(n.has(a))return n.get(a);let[c,d]=Gc(a);switch(c){case Wm:{let h=a;switch(d){case"bigint":c=sI,h=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+d);h=null;break;case"undefined":return r([iI],a)}return r([c,h],a)}case uu:{if(d){let g=a;return d==="DataView"?g=new Uint8Array(a.buffer):d==="ArrayBuffer"&&(g=new Uint8Array( Line truncated
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:` `},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
`}]}}const Ym=(function(e){if(e==null)return S9;if(typeof e=="function")return Xm(e);if(typeof e=="object")return Array.isArray(e)?b9(e):_9(e);if(typeof e=="string")return k9(e);throw new Error("Expected function, string, or object as test")});function b9(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=Ym(e[n]);return Xm(i);function i(...r){let o=-1;for(;++o<t.length;)if(t[o].apply(this,r))return!0;return!1}}function _9(e){const t=e;return Xm(n);function n(i){const r=i;let o;for(o in e)if(r[o]!==t[o])return!1;return!0}}function k9(e){return Xm(t);function t(n){return n&&n.type===e}}function Xm(e){return t;function t(n,i,r){return!!(w9(n)&&e.call(this,n,typeof i=="number"?i:void 0,r||void 0))}}function S9(){return!0}function w9(e){return e!==null&&typeof e=="object"&&"type"in e}const KN=[],C9=!0,Qx=!1,j9="skip";function ZN(e,t,n,i){let r;typeof t=="function"&&typeof n!="function"?(i=n,n=t):r=t;const o=Ym(r),a=i?-1:1;c(e,void 0,[])();function c(d,m,h){const p=d&&typeof d=="object"?d:{};if(typeof p.type=="string"){const x=typeof p.tagName=="string"?p.tagName:typeof p.name=="string"?p.name:void 0;Object.defineProperty(g,"name",{value:"node ("+(d.type+(x?"<"+x+">":""))+")"})}return g;function g(){let x=KN,v,b,k;if((!t||o(d,m,h[h.length-1]||void 0))&&(x=E9(n(d,h)),x[0]===Qx))return x;if("children"in d&&d.children){const w=d;if(w.children&&x[0]!==j9)for(b=(i?w.children.length:-1)+a,k=h.concat(w);b>-1&&b<w.children.length;){const S=w.children[b];if(v=c(S,b,k)(),v[0]===Qx)return v;b=typeof v[1]=="number"?v[1]:b+a}}return x}}}function E9(e){return Array.isArray(e)?e:typeof e=="number"?[C9,e]:e==null?KN:[e]}function x0(e,t,n,i){let r,o,a;typeof t=="function"&&typeof n!="function"?(o=void 0,a=t,r=n):(o=t,a=n,r=i),ZN(e,o,c,r);function c(d,m){const h=m[m.length-1],p=h?h.children.indexOf(d):void 0;return a(d,p,h)}}const Jx={}.hasOwnProperty,N9={};function I9(e,t){const n=t||N9,i=new Map,r=new Map,o=new Map,a={...f9,...n.handlers},c={all:m,applyData:R9,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:a,one:d,options:n,patch:T9,wrap:M9};return x0(e,function(h){if(h.type==="definition"||h.type==="footnoteDefinition"){const p=h.type==="definition"?i:r,g=String(h.identifier).toUpperCase();p.has(g)||p.set(g,h)}}),c;function d(h,p){const g=h.type,x=c.handlers[g];if(Jx.call(c.handlers,g)&&x)return x(c,h,p);if(c.options.passThrough&&c.options.passThrough.includes(g)){if("children"in h){const{children:b,...k}=h,w=um(k);return w.children=c.all(h),w}return um(h)}return(c.options.unknownHandler||A9)(c,h,p)}function m(h){const p=[];if("children"in h){const g=h.children;let x=-1;for(;++x<g.length;){const v=c.one(g[x],h);if(v){if(x&&g[x-1].type==="break"&&(!Array.isArray(v)&&v.type==="text"&&(v.value=ww(v.value)),!Array.isArray(v)&&v.type==="element")){const b=v.children[0];b&&b.type==="text"&&(b.value=ww(b.value))}Array.isArray(v)?p.push(...v):p.push(v)}}}return p}}function T9(e,t){e.position&&(t.position=xz(e))}function R9(e,t){let n=t;if(e&&e.data){const i=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;if(typeof i=="string")if(n.type==="element")n.tagName=i;else{const a="children"in n?n.children:[n];n={type:"element",tagName:i,properties:{},children:a}}n.type==="element"&&o&&Object.assign(n.properties,um(o)),"children"in n&&n.children&&r!==null&&r!==void 0&&(n.children=r)}return n}function A9(e,t){const n=t.data||{},i="value"in t&&!(Jx.call(n,"hProperties")||Jx.call(n,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function M9(e,t){const n=[];let i=-1;for(t&&n.push({type:"text",value:` `}]}}const Ym=(function(e){if(e==null)return O9;if(typeof e=="function")return Xm(e);if(typeof e=="object")return Array.isArray(e)?A9(e):M9(e);if(typeof e=="string")return D9(e);throw new Error("Expected function, string, or object as test")});function A9(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=Ym(e[n]);return Xm(i);function i(...r){let o=-1;for(;++o<t.length;)if(t[o].apply(this,r))return!0;return!1}}function M9(e){const t=e;return Xm(n);function n(i){const r=i;let o;for(o in e)if(r[o]!==t[o])return!1;return!0}}function D9(e){return Xm(t);function t(n){return n&&n.type===e}}function Xm(e){return t;function t(n,i,r){return!!(L9(n)&&e.call(this,n,typeof i=="number"?i:void 0,r||void 0))}}function O9(){return!0}function L9(e){return e!==null&&typeof e=="object"&&"type"in e}const oI=[],z9=!0,nv=!1,P9="skip";function aI(e,t,n,i){let r;typeof t=="function"&&typeof n!="function"?(i=n,n=t):r=t;const o=Ym(r),a=i?-1:1;c(e,void 0,[])();function c(d,m,h){const p=d&&typeof d=="object"?d:{};if(typeof p.type=="string"){const x=typeof p.tagName=="string"?p.tagName:typeof p.name=="string"?p.name:void 0;Object.defineProperty(g,"name",{value:"node ("+(d.type+(x?"<"+x+">":""))+")"})}return g;function g(){let x=oI,v,_,k;if((!t||o(d,m,h[h.length-1]||void 0))&&(x=B9(n(d,h)),x[0]===nv))return x;if("children"in d&&d.children){const w=d;if(w.children&&x[0]!==P9)for(_=(i?w.children.length:-1)+a,k=h.concat(w);_>-1&&_<w.children.length;){const S=w.children[_];if(v=c(S,_,k)(),v[0]===nv)return v;_=typeof v[1]=="number"?v[1]:_+a}}return x}}}function B9(e){return Array.isArray(e)?e:typeof e=="number"?[z9,e]:e==null?oI:[e]}function w0(e,t,n,i){let r,o,a;typeof t=="function"&&typeof n!="function"?(o=void 0,a=t,r=n):(o=t,a=n,r=i),aI(e,o,c,r);function c(d,m){const h=m[m.length-1],p=h?h.children.indexOf(d):void 0;return a(d,p,h)}}const iv={}.hasOwnProperty,$9={};function H9(e,t){const n=t||$9,i=new Map,r=new Map,o=new Map,a={...w9,...n.handlers},c={all:m,applyData:V9,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:a,one:d,options:n,patch:F9,wrap:G9};return w0(e,function(h){if(h.type==="definition"||h.type==="footnoteDefinition"){const p=h.type==="definition"?i:r,g=String(h.identifier).toUpperCase();p.has(g)||p.set(g,h)}}),c;function d(h,p){const g=h.type,x=c.handlers[g];if(iv.call(c.handlers,g)&&x)return x(c,h,p);if(c.options.passThrough&&c.options.passThrough.includes(g)){if("children"in h){const{children:_,...k}=h,w=um(k);return w.children=c.all(h),w}return um(h)}return(c.options.unknownHandler||U9)(c,h,p)}function m(h){const p=[];if("children"in h){const g=h.children;let x=-1;for(;++x<g.length;){const v=c.one(g[x],h);if(v){if(x&&g[x-1].type==="break"&&(!Array.isArray(v)&&v.type==="text"&&(v.value=Aw(v.value)),!Array.isArray(v)&&v.type==="element")){const _=v.children[0];_&&_.type==="text"&&(_.value=Aw(_.value))}Array.isArray(v)?p.push(...v):p.push(v)}}}return p}}function F9(e,t){e.position&&(t.position=T8(e))}function V9(e,t){let n=t;if(e&&e.data){const i=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;if(typeof i=="string")if(n.type==="element")n.tagName=i;else{const a="children"in n?n.children:[n];n={type:"element",tagName:i,properties:{},children:a}}n.type==="element"&&o&&Object.assign(n.properties,um(o)),"children"in n&&n.children&&r!==null&&r!==void 0&&(n.children=r)}return n}function U9(e,t){const n=t.data||{},i="value"in t&&!(iv.call(n,"hProperties")||iv.call(n,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function G9(e,t){const n=[];let i=-1;for(t&&n.push({type:"text",value:`
`});++i<e.length;)i&&n.push({type:"text",value:` `});++i<e.length;)i&&n.push({type:"text",value:`
`}),n.push(e[i]);return t&&e.length>0&&n.push({type:"text",value:` `}),n.push(e[i]);return t&&e.length>0&&n.push({type:"text",value:`
`}),n}function ww(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Cw(e,t){const n=I9(e,t),i=n.one(e,void 0),r=v9(n),o=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&o.children.push({type:"text",value:` `}),n}function Aw(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Mw(e,t){const n=H9(e,t),i=n.one(e,void 0),r=R9(n),o=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
`},r),o}function D9(e,t){return e&&"run"in e?async function(n,i){const r=Cw(n,{file:i,...t});await e.run(r,i)}:function(n,i){return Cw(n,{file:i,...e||t})}}function jw(e){if(e)throw e}var Vg,Ew;function O9(){if(Ew)return Vg;Ew=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=function(m){return typeof Array.isArray=="function"?Array.isArray(m):t.call(m)==="[object Array]"},o=function(m){if(!m||t.call(m)!=="[object Object]")return!1;var h=e.call(m,"constructor"),p=m.constructor&&m.constructor.prototype&&e.call(m.constructor.prototype,"isPrototypeOf");if(m.constructor&&!h&&!p)return!1;var g;for(g in m);return typeof g>"u"||e.call(m,g)},a=function(m,h){n&&h.name==="__proto__"?n(m,h.name,{enumerable:!0,configurable:!0,value:h.newValue,writable:!0}):m[h.name]=h.newValue},c=function(m,h){if(h==="__proto__")if(e.call(m,h)){if(i)return i(m,h).value}else return;return m[h]};return Vg=function d(){var m,h,p,g,x,v,b=arguments[0],k=1,w=arguments.length,S=!1;for(typeof b=="boolean"&&(S=b,b=arguments[1]||{},k=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});k<w;++k)if(m=arguments[k],m!=null)for(h in m)p=c(b,h),g=c(m,h),b!==g&&(S&&g&&(o(g)||(x=r(g)))?(x?(x=!1,v=p&&r(p)?p:[]):v=p&&o(p)?p:{},a(b,{name:h,newValue:d(S,v,g)})):typeof g<"u"&&a(b,{name:h,newValue:g}));return b},Vg}var L9=O9();const Ug=da(L9);function ev(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function z9(){const e=[],t={run:n,use:i};return t;function n(...r){let o=-1;const a=r.pop();if(typeof a!="function")throw new TypeError("Expected function as last argument, not "+a);c(null,...r);function c(d,...m){const h=e[++o];let p=-1;if(d){a(d);return}for(;++p<r.length;)(m[p]===null||m[p]===void 0)&&(m[p]=r[p]);r=m,h?P9(h,c)(...m):a(null,...m)}}function i(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),t}}function P9(e,t){let n;return i;function i(...a){const c=e.length>a.length;let d;c&&a.push(r);try{d=e.apply(this,a)}catch(m){const h=m;if(c&&n)throw h;return r(h)}c||(d&&d.then&&typeof d.then=="function"?d.then(o,r):d instanceof Error?r(d):o(d))}function r(a,...c){n||(n=!0,t(a,...c))}function o(a){r(null,a)}}const es={basename:B9,dirname:$9,extname:H9,join:F9,sep:"/"};function B9(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Fu(e);let n=0,i=-1,r=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;r--;)if(e.codePointAt(r)===47){if(o){n=r+1;break}}else i<0&&(o=!0,i=r+1);return i<0?"":e.slice(n,i)}if(t===e)return"";let a=-1,c=t.length-1;for(;r--;)if(e.codePointAt(r)===47){if(o){n=r+1;break}}else a<0&&(o=!0,a=r+1),c>-1&&(e.codePointAt(r)===t.codePointAt(c--)?c<0&&(i=r):(c=-1,i=a));return n===i?i=a:i<0&&(i=e.length),e.slice(n,i)}function $9(e){if(Fu(e),e.length===0)return".";let t=-1,n=e.length,i;for(;--n;)if(e.codePointAt(n)===47){if(i){t=n;break}}else i||(i=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function H9(e){Fu(e);let t=e.length,n=-1,i=0,r=-1,o=0,a;for(;t--;){const c=e.codePointAt(t);if(c===47){if(a){i=t+1;break}continue}n<0&&(a=!0,n=t+1),c===46?r<0?r=t:o!==1&&(o=1):r>-1&&(o=-1)}return r<0||n<0||o===0||o===1&&r===n-1&&r===i+1?"":e.slice(r,n)}function F9(...e){let t=-1,n;for(;++t<e.length;)Fu(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":V9(n)}function V9(e){Fu(e);const t=e.codePointAt(0)===47;let n=U9(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function U9(e,t){let n="",i=0,r=-1,o=0,a=-1,c,d;for(;++a<=e.length;){if(a<e.length)c=e.codePointAt(a);else{if(c===47)break;c=47}if(c===47){if(!(r===a-1||o===1))if(r!==a-1&&o===2){if(n.length<2||i!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(d=n.lastIndexOf("/"),d!==n.length-1){d<0?(n="",i=0):(n=n.slice(0,d),i=n.length-1-n.lastIndexOf("/")),r=a,o=0;continue}}else if(n.length>0){n="",i=0,r=a,o=0;continue}}t&&(n=n.length>0?n+"/..":"..",i=2)}else n.length>0?n+="/"+e.slice(r+1,a):n=e.slice(r+1,a),i=a-r-1;r=a,o=0}else c===46&&o>-1?o++:o=-1}return n}function Fu(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const G9={cwd:q9};function q9(){return"/"}function tv(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function W9(e){if(typeof e=="string")e=new URL(e);else if(!tv(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return Y9(e)}function Y9(e){if(e.hostname!==""){consLine truncated `},r),o}function q9(e,t){return e&&"run"in e?async function(n,i){const r=Mw(n,{file:i,...t});await e.run(r,i)}:function(n,i){return Mw(n,{file:i,...e||t})}}function Dw(e){if(e)throw e}var Ug,Ow;function W9(){if(Ow)return Ug;Ow=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=function(m){return typeof Array.isArray=="function"?Array.isArray(m):t.call(m)==="[object Array]"},o=function(m){if(!m||t.call(m)!=="[object Object]")return!1;var h=e.call(m,"constructor"),p=m.constructor&&m.constructor.prototype&&e.call(m.constructor.prototype,"isPrototypeOf");if(m.constructor&&!h&&!p)return!1;var g;for(g in m);return typeof g>"u"||e.call(m,g)},a=function(m,h){n&&h.name==="__proto__"?n(m,h.name,{enumerable:!0,configurable:!0,value:h.newValue,writable:!0}):m[h.name]=h.newValue},c=function(m,h){if(h==="__proto__")if(e.call(m,h)){if(i)return i(m,h).value}else return;return m[h]};return Ug=function d(){var m,h,p,g,x,v,_=arguments[0],k=1,w=arguments.length,S=!1;for(typeof _=="boolean"&&(S=_,_=arguments[1]||{},k=2),(_==null||typeof _!="object"&&typeof _!="function")&&(_={});k<w;++k)if(m=arguments[k],m!=null)for(h in m)p=c(_,h),g=c(m,h),_!==g&&(S&&g&&(o(g)||(x=r(g)))?(x?(x=!1,v=p&&r(p)?p:[]):v=p&&o(p)?p:{},a(_,{name:h,newValue:d(S,v,g)})):typeof g<"u"&&a(_,{name:h,newValue:g}));return _},Ug}var Y9=W9();const Gg=ma(Y9);function rv(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function X9(){const e=[],t={run:n,use:i};return t;function n(...r){let o=-1;const a=r.pop();if(typeof a!="function")throw new TypeError("Expected function as last argument, not "+a);c(null,...r);function c(d,...m){const h=e[++o];let p=-1;if(d){a(d);return}for(;++p<r.length;)(m[p]===null||m[p]===void 0)&&(m[p]=r[p]);r=m,h?K9(h,c)(...m):a(null,...m)}}function i(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),t}}function K9(e,t){let n;return i;function i(...a){const c=e.length>a.length;let d;c&&a.push(r);try{d=e.apply(this,a)}catch(m){const h=m;if(c&&n)throw h;return r(h)}c||(d&&d.then&&typeof d.then=="function"?d.then(o,r):d instanceof Error?r(d):o(d))}function r(a,...c){n||(n=!0,t(a,...c))}function o(a){r(null,a)}}const Jr={basename:Z9,dirname:Q9,extname:J9,join:e$,sep:"/"};function Z9(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Hu(e);let n=0,i=-1,r=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;r--;)if(e.codePointAt(r)===47){if(o){n=r+1;break}}else i<0&&(o=!0,i=r+1);return i<0?"":e.slice(n,i)}if(t===e)return"";let a=-1,c=t.length-1;for(;r--;)if(e.codePointAt(r)===47){if(o){n=r+1;break}}else a<0&&(o=!0,a=r+1),c>-1&&(e.codePointAt(r)===t.codePointAt(c--)?c<0&&(i=r):(c=-1,i=a));return n===i?i=a:i<0&&(i=e.length),e.slice(n,i)}function Q9(e){if(Hu(e),e.length===0)return".";let t=-1,n=e.length,i;for(;--n;)if(e.codePointAt(n)===47){if(i){t=n;break}}else i||(i=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function J9(e){Hu(e);let t=e.length,n=-1,i=0,r=-1,o=0,a;for(;t--;){const c=e.codePointAt(t);if(c===47){if(a){i=t+1;break}continue}n<0&&(a=!0,n=t+1),c===46?r<0?r=t:o!==1&&(o=1):r>-1&&(o=-1)}return r<0||n<0||o===0||o===1&&r===n-1&&r===i+1?"":e.slice(r,n)}function e$(...e){let t=-1,n;for(;++t<e.length;)Hu(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":t$(n)}function t$(e){Hu(e);const t=e.codePointAt(0)===47;let n=n$(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function n$(e,t){let n="",i=0,r=-1,o=0,a=-1,c,d;for(;++a<=e.length;){if(a<e.length)c=e.codePointAt(a);else{if(c===47)break;c=47}if(c===47){if(!(r===a-1||o===1))if(r!==a-1&&o===2){if(n.length<2||i!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(d=n.lastIndexOf("/"),d!==n.length-1){d<0?(n="",i=0):(n=n.slice(0,d),i=n.length-1-n.lastIndexOf("/")),r=a,o=0;continue}}else if(n.length>0){n="",i=0,r=a,o=0;continue}}t&&(n=n.length>0?n+"/..":"..",i=2)}else n.length>0?n+="/"+e.slice(r+1,a):n=e.slice(r+1,a),i=a-r-1;r=a,o=0}else c===46&&o>-1?o++:o=-1}return n}function Hu(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const i$={cwd:r$};function r$(){return"/"}function sv(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function s$(e){if(typeof e=="string")e=new URL(e);else if(!sv(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return o$(e)}function o$(e){if(e.hostname!==""){consLine truncated
`:" ")+o.indentLines(o.containerFlow(i,c.current()),t?tI:P$))),m(),d}}function P$(e,t,n){return t===0?e:tI(e,t,n)}function tI(e,t,n){return(n?"":" ")+e}const B$=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];nI.peek=U$;function $$(){return{canContainEols:["delete"],enter:{strikethrough:F$},exit:{strikethrough:V$}}}function H$(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:B$}],handlers:{delete:nI}}}function F$(e){this.enter({type:"delete",children:[]},e)}function V$(e){this.exit(e)}function nI(e,t,n,i){const r=n.createTracker(i),o=n.enter("strikethrough");let a=r.move("~~");return a+=n.containerPhrasing(e,{...r.current(),before:a,after:"~"}),a+=r.move("~~"),o(),a}function U$(){return"~"}function G$(e){return e.length}function q$(e,t){const n=t||{},i=(n.align||[]).concat(),r=n.stringLength||G$,o=[],a=[],c=[],d=[];let m=0,h=-1;for(;++h<e.length;){const b=[],k=[];let w=-1;for(e[h].length>m&&(m=e[h].length);++w<e[h].length;){const S=W$(e[h][w]);if(n.alignDelimiters!==!1){const j=r(S);k[w]=j,(d[w]===void 0||j>d[w])&&(d[w]=j)}b.push(S)}a[h]=b,c[h]=k}let p=-1;if(typeof i=="object"&&"length"in i)for(;++p<m;)o[p]=Dw(i[p]);else{const b=Dw(i);for(;++p<m;)o[p]=b}p=-1;const g=[],x=[];for(;++p<m;){const b=o[p];let k="",w="";b===99?(k=":",w=":"):b===108?k=":":b===114&&(w=":");let S=n.alignDelimiters===!1?1:Math.max(1,d[p]-k.length-w.length);const j=k+"-".repeat(S)+w;n.alignDelimiters!==!1&&(S=k.length+S+w.length,S>d[p]&&(d[p]=S),x[p]=S),g[p]=j}a.splice(1,0,g),c.splice(1,0,x),h=-1;const v=[];for(;++h<a.length;){const b=a[h],k=c[h];p=-1;const w=[];for(;++p<m;){const S=b[p]||"";let j="",N="";if(n.alignDelimiters!==!1){const O=d[p]-(k[p]||0),R=o[p];R===114?j=" ".repeat(O):R===99?O%2?(j=" ".repeat(O/2+.5),N=" ".repeat(O/2-.5)):(j=" ".repeat(O/2),N=j):N=" ".repeat(O)}n.delimiterStart!==!1&&!p&&w.push("|"),n.padding!==!1&&!(n.alignDelimiters===!1&&S==="")&&(n.delimiterStart!==!1||p)&&w.push(" "),n.alignDelimiters!==!1&&w.push(j),w.push(S),n.alignDelimiters!==!1&&w.push(N),n.padding!==!1&&w.push(" "),(n.delimiterEnd!==!1||p!==m-1)&&w.push("|")}v.push(n.delimiterEnd===!1?w.join("").replace(/ +$/,""):w.join(""))}return v.join(` `:" ")+o.indentLines(o.containerFlow(i,c.current()),t?dI:K$))),m(),d}}function K$(e,t,n){return t===0?e:dI(e,t,n)}function dI(e,t,n){return(n?"":" ")+e}const Z$=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];fI.peek=n7;function Q$(){return{canContainEols:["delete"],enter:{strikethrough:e7},exit:{strikethrough:t7}}}function J$(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:Z$}],handlers:{delete:fI}}}function e7(e){this.enter({type:"delete",children:[]},e)}function t7(e){this.exit(e)}function fI(e,t,n,i){const r=n.createTracker(i),o=n.enter("strikethrough");let a=r.move("~~");return a+=n.containerPhrasing(e,{...r.current(),before:a,after:"~"}),a+=r.move("~~"),o(),a}function n7(){return"~"}function i7(e){return e.length}function r7(e,t){const n=t||{},i=(n.align||[]).concat(),r=n.stringLength||i7,o=[],a=[],c=[],d=[];let m=0,h=-1;for(;++h<e.length;){const _=[],k=[];let w=-1;for(e[h].length>m&&(m=e[h].length);++w<e[h].length;){const S=s7(e[h][w]);if(n.alignDelimiters!==!1){const j=r(S);k[w]=j,(d[w]===void 0||j>d[w])&&(d[w]=j)}_.push(S)}a[h]=_,c[h]=k}let p=-1;if(typeof i=="object"&&"length"in i)for(;++p<m;)o[p]=Fw(i[p]);else{const _=Fw(i);for(;++p<m;)o[p]=_}p=-1;const g=[],x=[];for(;++p<m;){const _=o[p];let k="",w="";_===99?(k=":",w=":"):_===108?k=":":_===114&&(w=":");let S=n.alignDelimiters===!1?1:Math.max(1,d[p]-k.length-w.length);const j=k+"-".repeat(S)+w;n.alignDelimiters!==!1&&(S=k.length+S+w.length,S>d[p]&&(d[p]=S),x[p]=S),g[p]=j}a.splice(1,0,g),c.splice(1,0,x),h=-1;const v=[];for(;++h<a.length;){const _=a[h],k=c[h];p=-1;const w=[];for(;++p<m;){const S=_[p]||"";let j="",N="";if(n.alignDelimiters!==!1){const O=d[p]-(k[p]||0),R=o[p];R===114?j=" ".repeat(O):R===99?O%2?(j=" ".repeat(O/2+.5),N=" ".repeat(O/2-.5)):(j=" ".repeat(O/2),N=j):N=" ".repeat(O)}n.delimiterStart!==!1&&!p&&w.push("|"),n.padding!==!1&&!(n.alignDelimiters===!1&&S==="")&&(n.delimiterStart!==!1||p)&&w.push(" "),n.alignDelimiters!==!1&&w.push(j),w.push(S),n.alignDelimiters!==!1&&w.push(N),n.padding!==!1&&w.push(" "),(n.delimiterEnd!==!1||p!==m-1)&&w.push("|")}v.push(n.delimiterEnd===!1?w.join("").replace(/ +$/,""):w.join(""))}return v.join(`
`)}function W$(e){return e==null?"":String(e)}function Dw(e){const t=typeof e=="string"?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function Y$(e,t,n,i){const r=n.enter("blockquote"),o=n.createTracker(i);o.move("> "),o.shift(2);const a=n.indentLines(n.containerFlow(e,o.current()),X$);return r(),a}function X$(e,t,n){return">"+(n?"":" ")+e}function K$(e,t){return Ow(e,t.inConstruct,!0)&&!Ow(e,t.notInConstruct,!1)}function Ow(e,t,n){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return n;let i=-1;for(;++i<t.length;)if(e.includes(t[i]))return!0;return!1}function Lw(e,t,n,i){let r=-1;for(;++r<n.unsafe.length;)if(n.unsafe[r].character===` `)}function s7(e){return e==null?"":String(e)}function Fw(e){const t=typeof e=="string"?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function o7(e,t,n,i){const r=n.enter("blockquote"),o=n.createTracker(i);o.move("> "),o.shift(2);const a=n.indentLines(n.containerFlow(e,o.current()),a7);return r(),a}function a7(e,t,n){return">"+(n?"":" ")+e}function l7(e,t){return Vw(e,t.inConstruct,!0)&&!Vw(e,t.notInConstruct,!1)}function Vw(e,t,n){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return n;let i=-1;for(;++i<t.length;)if(e.includes(t[i]))return!0;return!1}function Uw(e,t,n,i){let r=-1;for(;++r<n.unsafe.length;)if(n.unsafe[r].character===`
`&&K$(n.stack,n.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\ `&&l7(n.stack,n.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
`}function Z$(e,t){const n=String(e);let i=n.indexOf(t),r=i,o=0,a=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;i!==-1;)i===r?++o>a&&(a=o):o=1,r=i+t.length,i=n.indexOf(t,r);return a}function Q$(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function J$(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function e7(e,t,n,i){const r=J$(n),o=e.value||"",a=r==="`"?"GraveAccent":"Tilde";if(Q$(e,n)){const p=n.enter("codeIndented"),g=n.indentLines(o,t7);return p(),g}const c=n.createTracker(i),d=r.repeat(Math.max(Z$(o,r)+1,3)),m=n.enter("codeFenced");let h=c.move(d);if(e.lang){const p=n.enter(`codeFencedLang${a}`);h+=c.move(n.safe(e.lang,{before:h,after:" ",encode:["`"],...c.current()})),p()}if(e.lang&&e.meta){const p=n.enter(`codeFencedMeta${a}`);h+=c.move(" "),h+=c.move(n.safe(e.meta,{before:h,after:` `}function c7(e,t){const n=String(e);let i=n.indexOf(t),r=i,o=0,a=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;i!==-1;)i===r?++o>a&&(a=o):o=1,r=i+t.length,i=n.indexOf(t,r);return a}function u7(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function d7(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function f7(e,t,n,i){const r=d7(n),o=e.value||"",a=r==="`"?"GraveAccent":"Tilde";if(u7(e,n)){const p=n.enter("codeIndented"),g=n.indentLines(o,m7);return p(),g}const c=n.createTracker(i),d=r.repeat(Math.max(c7(o,r)+1,3)),m=n.enter("codeFenced");let h=c.move(d);if(e.lang){const p=n.enter(`codeFencedLang${a}`);h+=c.move(n.safe(e.lang,{before:h,after:" ",encode:["`"],...c.current()})),p()}if(e.lang&&e.meta){const p=n.enter(`codeFencedMeta${a}`);h+=c.move(" "),h+=c.move(n.safe(e.meta,{before:h,after:`
`,encode:["`"],...c.current()})),p()}return h+=c.move(` `,encode:["`"],...c.current()})),p()}return h+=c.move(`
`),o&&(h+=c.move(o+` `),o&&(h+=c.move(o+`
`)),h+=c.move(d),m(),h}function t7(e,t,n){return(n?"":" ")+e}function b0(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function n7(e,t,n,i){const r=b0(n),o=r==='"'?"Quote":"Apostrophe",a=n.enter("definition");let c=n.enter("label");const d=n.createTracker(i);let m=d.move("[");return m+=d.move(n.safe(n.associationId(e),{before:m,after:"]",...d.current()})),m+=d.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=n.enter("destinationLiteral"),m+=d.move("<"),m+=d.move(n.safe(e.url,{before:m,after:">",...d.current()})),m+=d.move(">")):(c=n.enter("destinationRaw"),m+=d.move(n.safe(e.url,{before:m,after:e.title?" ":` `)),h+=c.move(d),m(),h}function m7(e,t,n){return(n?"":" ")+e}function j0(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function p7(e,t,n,i){const r=j0(n),o=r==='"'?"Quote":"Apostrophe",a=n.enter("definition");let c=n.enter("label");const d=n.createTracker(i);let m=d.move("[");return m+=d.move(n.safe(n.associationId(e),{before:m,after:"]",...d.current()})),m+=d.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=n.enter("destinationLiteral"),m+=d.move("<"),m+=d.move(n.safe(e.url,{before:m,after:">",...d.current()})),m+=d.move(">")):(c=n.enter("destinationRaw"),m+=d.move(n.safe(e.url,{before:m,after:e.title?" ":`
`,...d.current()}))),c(),e.title&&(c=n.enter(`title${o}`),m+=d.move(" "+r),m+=d.move(n.safe(e.title,{before:m,after:r,...d.current()})),m+=d.move(r),c()),a(),m}function i7(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Eu(e){return"&#x"+e.toString(16).toUpperCase()+";"}function dm(e,t,n){const i=Tl(e),r=Tl(t);return i===void 0?r===void 0?n==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:i===1?r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}iI.peek=r7;function iI(e,t,n,i){const r=i7(n),o=n.enter("emphasis"),a=n.createTracker(i),c=a.move(r);let d=a.move(n.containerPhrasing(e,{after:r,before:c,...a.current()}));const m=d.charCodeAt(0),h=dm(i.before.charCodeAt(i.before.length-1),m,r);h.inside&&(d=Eu(m)+d.slice(1));const p=d.charCodeAt(d.length-1),g=dm(i.after.charCodeAt(0),p,r);g.inside&&(d=d.slice(0,-1)+Eu(p));const x=a.move(r);return o(),n.attentionEncodeSurroundingInfo={after:g.outside,before:h.outside},c+d+x}function r7(e,t,n){return n.options.emphasis||"*"}function s7(e,t){let n=!1;return x0(e,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return n=!0,Qx}),!!((!e.depth||e.depth<3)&&d0(e)&&(t.options.setext||n))}function o7(e,t,n,i){const r=Math.max(Math.min(6,e.depth||1),1),o=n.createTracker(i);if(s7(e,n)){const h=n.enter("headingSetext"),p=n.enter("phrasing"),g=n.containerPhrasing(e,{...o.current(),before:` `,...d.current()}))),c(),e.title&&(c=n.enter(`title${o}`),m+=d.move(" "+r),m+=d.move(n.safe(e.title,{before:m,after:r,...d.current()})),m+=d.move(r),c()),a(),m}function h7(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function ju(e){return"&#x"+e.toString(16).toUpperCase()+";"}function dm(e,t,n){const i=Il(e),r=Il(t);return i===void 0?r===void 0?n==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:i===1?r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}mI.peek=g7;function mI(e,t,n,i){const r=h7(n),o=n.enter("emphasis"),a=n.createTracker(i),c=a.move(r);let d=a.move(n.containerPhrasing(e,{after:r,before:c,...a.current()}));const m=d.charCodeAt(0),h=dm(i.before.charCodeAt(i.before.length-1),m,r);h.inside&&(d=ju(m)+d.slice(1));const p=d.charCodeAt(d.length-1),g=dm(i.after.charCodeAt(0),p,r);g.inside&&(d=d.slice(0,-1)+ju(p));const x=a.move(r);return o(),n.attentionEncodeSurroundingInfo={after:g.outside,before:h.outside},c+d+x}function g7(e,t,n){return n.options.emphasis||"*"}function y7(e,t){let n=!1;return w0(e,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return n=!0,nv}),!!((!e.depth||e.depth<3)&&y0(e)&&(t.options.setext||n))}function x7(e,t,n,i){const r=Math.max(Math.min(6,e.depth||1),1),o=n.createTracker(i);if(y7(e,n)){const h=n.enter("headingSetext"),p=n.enter("phrasing"),g=n.containerPhrasing(e,{...o.current(),before:`
`,after:` `,after:`
`});return p(),h(),g+` `});return p(),h(),g+`
`+(r===1?"=":"-").repeat(g.length-(Math.max(g.lastIndexOf("\r"),g.lastIndexOf(` `+(r===1?"=":"-").repeat(g.length-(Math.max(g.lastIndexOf("\r"),g.lastIndexOf(`
`))+1))}const a="#".repeat(r),c=n.enter("headingAtx"),d=n.enter("phrasing");o.move(a+" ");let m=n.containerPhrasing(e,{before:"# ",after:` `))+1))}const a="#".repeat(r),c=n.enter("headingAtx"),d=n.enter("phrasing");o.move(a+" ");let m=n.containerPhrasing(e,{before:"# ",after:`
`,...o.current()});return/^[\t ]/.test(m)&&(m=Eu(m.charCodeAt(0))+m.slice(1)),m=m?a+" "+m:a,n.options.closeAtx&&(m+=" "+a),d(),c(),m}rI.peek=a7;function rI(e){return e.value||""}function a7(){return"<"}sI.peek=l7;function sI(e,t,n,i){const r=b0(n),o=r==='"'?"Quote":"Apostrophe",a=n.enter("image");let c=n.enter("label");const d=n.createTracker(i);let m=d.move("![");return m+=d.move(n.safe(e.alt,{before:m,after:"]",...d.current()})),m+=d.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter("destinationLiteral"),m+=d.move("<"),m+=d.move(n.safe(e.url,{before:m,after:">",...d.current()})),m+=d.move(">")):(c=n.enter("destinationRaw"),m+=d.move(n.safe(e.url,{before:m,after:e.title?" ":")",...d.current()}))),c(),e.title&&(c=n.enter(`title${o}`),m+=d.move(" "+r),m+=d.move(n.safe(e.title,{before:m,after:r,...d.current()})),m+=d.move(r),c()),m+=d.move(")"),a(),m}function l7(){return"!"}oI.peek=c7;function oI(e,t,n,i){const r=e.referenceType,o=n.enter("imageReference");let a=n.enter("label");const c=n.createTracker(i);let d=c.move("![");const m=n.safe(e.alt,{before:d,after:"]",...c.current()});d+=c.move(m+"]["),a();const h=n.stack;n.stack=[],a=n.enter("reference");const p=n.safe(n.associationId(e),{before:d,after:"]",...c.current()});return a(),n.stack=h,o(),r==="full"||!m||m!==p?d+=c.move(p+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function c7(){return"!"}aI.peek=u7;function aI(e,t,n){let i=e.value||"",r="`",o=-1;for(;new RegExp("(^|[^`])"+r+"([^`]|$)").test(i);)r+="`";for(/[^ \r\n]/.test(i)&&(/^[ \r\n]/.test(i)&&/[ \r\n]$/.test(i)||/^`|`$/.test(i))&&(i=" "+i+" ");++o<n.unsafe.length;){const a=n.unsafe[o],c=n.compilePattern(a);let d;if(a.atBreak)for(;d=c.exec(i);){let m=d.index;i.charCodeAt(m)===10&&i.charCodeAt(m-1)===13&&m--,i=i.slice(0,m)+" "+i.slice(d.index+1)}}return r+i+r}function u7(){return"`"}function lI(e,t){const n=d0(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(n===e.url||"mailto:"+n===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}cI.peek=d7;function cI(e,t,n,i){const r=b0(n),o=r==='"'?"Quote":"Apostrophe",a=n.createTracker(i);let c,d;if(lI(e,n)){const h=n.stack;n.stack=[],c=n.enter("autolink");let p=a.move("<");return p+=a.move(n.containerPhrasing(e,{before:p,after:">",...a.current()})),p+=a.move(">"),c(),n.stack=h,p}c=n.enter("link"),d=n.enter("label");let m=a.move("[");return m+=a.move(n.containerPhrasing(e,{before:m,after:"](",...a.current()})),m+=a.move("]("),d(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(d=n.enter("destinationLiteral"),m+=a.move("<"),m+=a.move(n.safe(e.url,{before:m,after:">",...a.current()})),m+=a.move(">")):(d=n.enter("destinationRaw"),m+=a.move(n.safe(e.url,{before:m,after:e.title?" ":")",...a.current()}))),d(),e.title&&(d=n.enter(`title${o}`),m+=a.move(" "+r),m+=a.move(n.safe(e.title,{before:m,after:r,...a.current()})),m+=a.move(r),d()),m+=a.move(")"),c(),m}function d7(e,t,n){return lI(e,n)?"<":"["}uI.peek=f7;function uI(e,t,n,i){const r=e.referenceType,o=n.enter("linkReference");let a=n.enter("label");const c=n.createTracker(i);let d=c.move("[");const m=n.containerPhrasing(e,{before:d,after:"]",...c.current()});d+=c.move(m+"]["),a();const h=n.stack;n.stack=[],a=n.enter("reference");const p=n.safe(n.associationId(e),{before:d,after:"]",...c.current()});return a(),n.stack=h,o(),r==="full"||!m||m!==p?d+=c.move(p+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function f7(){return"["}function _0(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function m7(e){const t=_0(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function p7(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function dI(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function h7(e,t,n,i){const r=n.enter("list"),o=n.bulletCurrent;let a=e.ordered?p7(n):_0(n);const c=e.ordered?a==="."?")":".":m7(n);let d=t&&n.bulletLastUsed?a===n.bulletLastUsed:!1;if(!e.ordered){const h=e.children?e.children[0]:void 0;if((a==="*"||a==="-")&&h&&(!h.children||!h.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(d=!0),dI(n)===a&&h){let p=-1;for(;++p<e.chilLine truncated `,...o.current()});return/^[\t ]/.test(m)&&(m=ju(m.charCodeAt(0))+m.slice(1)),m=m?a+" "+m:a,n.options.closeAtx&&(m+=" "+a),d(),c(),m}pI.peek=v7;function pI(e){return e.value||""}function v7(){return"<"}hI.peek=b7;function hI(e,t,n,i){const r=j0(n),o=r==='"'?"Quote":"Apostrophe",a=n.enter("image");let c=n.enter("label");const d=n.createTracker(i);let m=d.move("![");return m+=d.move(n.safe(e.alt,{before:m,after:"]",...d.current()})),m+=d.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter("destinationLiteral"),m+=d.move("<"),m+=d.move(n.safe(e.url,{before:m,after:">",...d.current()})),m+=d.move(">")):(c=n.enter("destinationRaw"),m+=d.move(n.safe(e.url,{before:m,after:e.title?" ":")",...d.current()}))),c(),e.title&&(c=n.enter(`title${o}`),m+=d.move(" "+r),m+=d.move(n.safe(e.title,{before:m,after:r,...d.current()})),m+=d.move(r),c()),m+=d.move(")"),a(),m}function b7(){return"!"}gI.peek=_7;function gI(e,t,n,i){const r=e.referenceType,o=n.enter("imageReference");let a=n.enter("label");const c=n.createTracker(i);let d=c.move("![");const m=n.safe(e.alt,{before:d,after:"]",...c.current()});d+=c.move(m+"]["),a();const h=n.stack;n.stack=[],a=n.enter("reference");const p=n.safe(n.associationId(e),{before:d,after:"]",...c.current()});return a(),n.stack=h,o(),r==="full"||!m||m!==p?d+=c.move(p+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function _7(){return"!"}yI.peek=k7;function yI(e,t,n){let i=e.value||"",r="`",o=-1;for(;new RegExp("(^|[^`])"+r+"([^`]|$)").test(i);)r+="`";for(/[^ \r\n]/.test(i)&&(/^[ \r\n]/.test(i)&&/[ \r\n]$/.test(i)||/^`|`$/.test(i))&&(i=" "+i+" ");++o<n.unsafe.length;){const a=n.unsafe[o],c=n.compilePattern(a);let d;if(a.atBreak)for(;d=c.exec(i);){let m=d.index;i.charCodeAt(m)===10&&i.charCodeAt(m-1)===13&&m--,i=i.slice(0,m)+" "+i.slice(d.index+1)}}return r+i+r}function k7(){return"`"}function xI(e,t){const n=y0(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(n===e.url||"mailto:"+n===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}vI.peek=S7;function vI(e,t,n,i){const r=j0(n),o=r==='"'?"Quote":"Apostrophe",a=n.createTracker(i);let c,d;if(xI(e,n)){const h=n.stack;n.stack=[],c=n.enter("autolink");let p=a.move("<");return p+=a.move(n.containerPhrasing(e,{before:p,after:">",...a.current()})),p+=a.move(">"),c(),n.stack=h,p}c=n.enter("link"),d=n.enter("label");let m=a.move("[");return m+=a.move(n.containerPhrasing(e,{before:m,after:"](",...a.current()})),m+=a.move("]("),d(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(d=n.enter("destinationLiteral"),m+=a.move("<"),m+=a.move(n.safe(e.url,{before:m,after:">",...a.current()})),m+=a.move(">")):(d=n.enter("destinationRaw"),m+=a.move(n.safe(e.url,{before:m,after:e.title?" ":")",...a.current()}))),d(),e.title&&(d=n.enter(`title${o}`),m+=a.move(" "+r),m+=a.move(n.safe(e.title,{before:m,after:r,...a.current()})),m+=a.move(r),d()),m+=a.move(")"),c(),m}function S7(e,t,n){return xI(e,n)?"<":"["}bI.peek=w7;function bI(e,t,n,i){const r=e.referenceType,o=n.enter("linkReference");let a=n.enter("label");const c=n.createTracker(i);let d=c.move("[");const m=n.containerPhrasing(e,{before:d,after:"]",...c.current()});d+=c.move(m+"]["),a();const h=n.stack;n.stack=[],a=n.enter("reference");const p=n.safe(n.associationId(e),{before:d,after:"]",...c.current()});return a(),n.stack=h,o(),r==="full"||!m||m!==p?d+=c.move(p+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function w7(){return"["}function E0(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function C7(e){const t=E0(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function j7(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function _I(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function E7(e,t,n,i){const r=n.enter("list"),o=n.bulletCurrent;let a=e.ordered?j7(n):E0(n);const c=e.ordered?a==="."?")":".":C7(n);let d=t&&n.bulletLastUsed?a===n.bulletLastUsed:!1;if(!e.ordered){const h=e.children?e.children[0]:void 0;if((a==="*"||a==="-")&&h&&(!h.children||!h.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(d=!0),_I(n)===a&&h){let p=-1;for(;++p<e.chilLine truncated
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:g,table:a,tableCell:d,tableRow:c}};function a(x,v,b,k){return m(h(x,b,k),x.align)}function c(x,v,b,k){const w=p(x,b,k),S=m([w]);return S.slice(0,S.indexOf(` `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:g,table:a,tableCell:d,tableRow:c}};function a(x,v,_,k){return m(h(x,_,k),x.align)}function c(x,v,_,k){const w=p(x,_,k),S=m([w]);return S.slice(0,S.indexOf(`
`))}function d(x,v,b,k){const w=b.enter("tableCell"),S=b.enter("phrasing"),j=b.containerPhrasing(x,{...k,before:o,after:o});return S(),w(),j}function m(x,v){return q$(x,{align:v,alignDelimiters:i,padding:n,stringLength:r})}function h(x,v,b){const k=x.children;let w=-1;const S=[],j=v.enter("table");for(;++w<k.length;)S[w]=p(k[w],v,b);return j(),S}function p(x,v,b){const k=x.children;let w=-1;const S=[],j=v.enter("tableRow");for(;++w<k.length;)S[w]=d(k[w],x,v,b);return j(),S}function g(x,v,b){let k=mI.inlineCode(x,v,b);return b.stack.includes("tableCell")&&(k=k.replace(/\|/g,"\\$&")),k}}function M7(){return{exit:{taskListCheckValueChecked:Pw,taskListCheckValueUnchecked:Pw,paragraph:O7}}}function D7(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:L7}}}function Pw(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function O7(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const i=n.children[0];if(i&&i.type==="text"){const r=t.children;let o=-1,a;for(;++o<r.length;){const c=r[o];if(c.type==="paragraph"){a=c;break}}a===n&&(i.value=i.value.slice(1),i.value.length===0?n.children.shift():n.position&&i.position&&typeof i.position.start.offset=="number"&&(i.position.start.column++,i.position.start.offset++,n.position.start=Object.assign({},i.position.start)))}}this.exit(e)}function L7(e,t,n,i){const r=e.children[0],o=typeof e.checked=="boolean"&&r&&r.type==="paragraph",a="["+(e.checked?"x":" ")+"] ",c=n.createTracker(i);o&&c.move(a);let d=mI.listItem(e,t,n,{...i,...c.current()});return o&&(d=d.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,m)),d;function m(h){return h+a}}function z7(){return[h$(),L$(),$$(),j7(),M7()]}function P7(e){return{extensions:[g$(),z$(e),H$(),A7(e),D7()]}}const B7={tokenize:G7,partial:!0},pI={tokenize:q7,partial:!0},hI={tokenize:W7,partial:!0},gI={tokenize:Y7,partial:!0},$7={tokenize:X7,partial:!0},yI={name:"wwwAutolink",tokenize:V7,previous:vI},xI={name:"protocolAutolink",tokenize:U7,previous:bI},zs={name:"emailAutolink",tokenize:F7,previous:_I},cs={};function H7(){return{text:cs}}let Ko=48;for(;Ko<123;)cs[Ko]=zs,Ko++,Ko===58?Ko=65:Ko===91&&(Ko=97);cs[43]=zs;cs[45]=zs;cs[46]=zs;cs[95]=zs;cs[72]=[zs,xI];cs[104]=[zs,xI];cs[87]=[zs,yI];cs[119]=[zs,yI];function F7(e,t,n){const i=this;let r,o;return a;function a(p){return!nv(p)||!_I.call(i,i.previous)||k0(i.events)?n(p):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(p))}function c(p){return nv(p)?(e.consume(p),c):p===64?(e.consume(p),d):n(p)}function d(p){return p===46?e.check($7,h,m)(p):p===45||p===95||zi(p)?(o=!0,e.consume(p),d):h(p)}function m(p){return e.consume(p),r=!0,d}function h(p){return o&&r&&Vi(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(p)):n(p)}}function V7(e,t,n){const i=this;return r;function r(a){return a!==87&&a!==119||!vI.call(i,i.previous)||k0(i.events)?n(a):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(B7,e.attempt(pI,e.attempt(hI,o),n),n)(a))}function o(a){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(a)}}function U7(e,t,n){const i=this;let r="",o=!1;return a;function a(p){return(p===72||p===104)&&bI.call(i,i.previous)&&!k0(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(p),e.consume(p),c):n(p)}function c(p){if(Vi(p)&&r.length<5)return r+=String.fromCodePoint(p),e.consume(p),c;if(p===58){const g=r.toLowerCase();if(g==="http"||g==="https")return e.consume(p),d}return n(p)}function d(p){return p===47?(e.consume(p),o?m:(o=!0,d)):n(p)}function m(p){return p===null||lm(p)||Nn(p)||oa(p)||Gm(p)?n(p):e.attempt(pI,e.attempt(hI,h),n)(p)}function h(p){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(p)}}function G7(e,t,n){let i=0;return r;function r(a){return(a===87||a===119)&&i<3?(i++,e.consume(a),r):a===46&&i===3?(e.consume(a),o):n(a)}function o(a){return a===null?n(a):t(a)}}function q7(e,t,n){let i,r,o;return a;function a(m){return m===46||m===95?e.check(gI,d,c)(m):m===null||Nn(m)||oa(m)||m!==45&&Gm(m)?d(m):(o=!0,e.consume(m),a)}function c(m){return m===95?i=!0:(r=i,i=void 0),e.consume(m),a}function d(m){return r||i||!o?n(m):t(m)}}function W7(e,t){let n=0,i=0;return r;function r(a){return a===40?(n++,e.consume(a),r):a===41&&i<n?o(a):a===33||a===34||a===38||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===60||a===63||a===93||a===95||a===126?e.check(gI,t,o)(a):a===null||Nn(a)||oa(a)?t(a):(e.consume(a),r)}function o(a){return a===41&&i++,e.consume(a),r}}function Y7(e,t,n){return i;function i(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),i):c===38?(e.consume(c),o):c===93?(e.consume(c),r):c===60||c===null||Nn(c)||oa(c)?t(c):n(c)}function r(c){return c===null||c===40||c===91||Nn(c)||oa(c)?t(c):i(c)}function o(c){return Vi(c)?a(c):n(c)}function a(c){re Line truncated `))}function d(x,v,_,k){const w=_.enter("tableCell"),S=_.enter("phrasing"),j=_.containerPhrasing(x,{...k,before:o,after:o});return S(),w(),j}function m(x,v){return r7(x,{align:v,alignDelimiters:i,padding:n,stringLength:r})}function h(x,v,_){const k=x.children;let w=-1;const S=[],j=v.enter("table");for(;++w<k.length;)S[w]=p(k[w],v,_);return j(),S}function p(x,v,_){const k=x.children;let w=-1;const S=[],j=v.enter("tableRow");for(;++w<k.length;)S[w]=d(k[w],x,v,_);return j(),S}function g(x,v,_){let k=SI.inlineCode(x,v,_);return _.stack.includes("tableCell")&&(k=k.replace(/\|/g,"\\$&")),k}}function G7(){return{exit:{taskListCheckValueChecked:qw,taskListCheckValueUnchecked:qw,paragraph:W7}}}function q7(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:Y7}}}function qw(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function W7(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const i=n.children[0];if(i&&i.type==="text"){const r=t.children;let o=-1,a;for(;++o<r.length;){const c=r[o];if(c.type==="paragraph"){a=c;break}}a===n&&(i.value=i.value.slice(1),i.value.length===0?n.children.shift():n.position&&i.position&&typeof i.position.start.offset=="number"&&(i.position.start.column++,i.position.start.offset++,n.position.start=Object.assign({},i.position.start)))}}this.exit(e)}function Y7(e,t,n,i){const r=e.children[0],o=typeof e.checked=="boolean"&&r&&r.type==="paragraph",a="["+(e.checked?"x":" ")+"] ",c=n.createTracker(i);o&&c.move(a);let d=SI.listItem(e,t,n,{...i,...c.current()});return o&&(d=d.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,m)),d;function m(h){return h+a}}function X7(){return[E$(),Y$(),Q$(),P7(),G7()]}function K7(e){return{extensions:[N$(),X$(e),J$(),U7(e),q7()]}}const Z7={tokenize:iH,partial:!0},wI={tokenize:rH,partial:!0},CI={tokenize:sH,partial:!0},jI={tokenize:oH,partial:!0},Q7={tokenize:aH,partial:!0},EI={name:"wwwAutolink",tokenize:tH,previous:II},NI={name:"protocolAutolink",tokenize:nH,previous:TI},zs={name:"emailAutolink",tokenize:eH,previous:RI},ls={};function J7(){return{text:ls}}let Ko=48;for(;Ko<123;)ls[Ko]=zs,Ko++,Ko===58?Ko=65:Ko===91&&(Ko=97);ls[43]=zs;ls[45]=zs;ls[46]=zs;ls[95]=zs;ls[72]=[zs,NI];ls[104]=[zs,NI];ls[87]=[zs,EI];ls[119]=[zs,EI];function eH(e,t,n){const i=this;let r,o;return a;function a(p){return!ov(p)||!RI.call(i,i.previous)||N0(i.events)?n(p):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(p))}function c(p){return ov(p)?(e.consume(p),c):p===64?(e.consume(p),d):n(p)}function d(p){return p===46?e.check(Q7,h,m)(p):p===45||p===95||Li(p)?(o=!0,e.consume(p),d):h(p)}function m(p){return e.consume(p),r=!0,d}function h(p){return o&&r&&Fi(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(p)):n(p)}}function tH(e,t,n){const i=this;return r;function r(a){return a!==87&&a!==119||!II.call(i,i.previous)||N0(i.events)?n(a):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(Z7,e.attempt(wI,e.attempt(CI,o),n),n)(a))}function o(a){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(a)}}function nH(e,t,n){const i=this;let r="",o=!1;return a;function a(p){return(p===72||p===104)&&TI.call(i,i.previous)&&!N0(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(p),e.consume(p),c):n(p)}function c(p){if(Fi(p)&&r.length<5)return r+=String.fromCodePoint(p),e.consume(p),c;if(p===58){const g=r.toLowerCase();if(g==="http"||g==="https")return e.consume(p),d}return n(p)}function d(p){return p===47?(e.consume(p),o?m:(o=!0,d)):n(p)}function m(p){return p===null||lm(p)||Nn(p)||la(p)||Gm(p)?n(p):e.attempt(wI,e.attempt(CI,h),n)(p)}function h(p){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(p)}}function iH(e,t,n){let i=0;return r;function r(a){return(a===87||a===119)&&i<3?(i++,e.consume(a),r):a===46&&i===3?(e.consume(a),o):n(a)}function o(a){return a===null?n(a):t(a)}}function rH(e,t,n){let i,r,o;return a;function a(m){return m===46||m===95?e.check(jI,d,c)(m):m===null||Nn(m)||la(m)||m!==45&&Gm(m)?d(m):(o=!0,e.consume(m),a)}function c(m){return m===95?i=!0:(r=i,i=void 0),e.consume(m),a}function d(m){return r||i||!o?n(m):t(m)}}function sH(e,t){let n=0,i=0;return r;function r(a){return a===40?(n++,e.consume(a),r):a===41&&i<n?o(a):a===33||a===34||a===38||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===60||a===63||a===93||a===95||a===126?e.check(jI,t,o)(a):a===null||Nn(a)||la(a)?t(a):(e.consume(a),r)}function o(a){return a===41&&i++,e.consume(a),r}}function oH(e,t,n){return i;function i(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),i):c===38?(e.consume(c),o):c===93?(e.consume(c),r):c===60||c===null||Nn(c)||la(c)?t(c):n(c)}function r(c){return c===null||c===40||c===91||Nn(c)||la(c)?t(c):i(c)}function o(c){return Fi(c)?a(c):n(c)}function a(c){re Line truncated
`),m=d.length>vH,h=m?d.length-ty*2:0,p=C.useCallback(()=>{navigator.clipboard.writeText(a),i(!0),setTimeout(()=>i(!1),1500)},[a]);return u.jsxs("div",{className:"code-block-wrap",children:[u.jsxs("div",{className:"code-block-header",children:[u.jsxs("span",{className:"code-block-lang",children:[c||"code",m?` (${d.length} lines)`:""]}),u.jsx("button",{className:"code-block-copy",onClick:p,children:n?u.jsxs(u.Fragment,{children:[u.jsx(Fl,{})," ",u.jsx("span",{children:"Copied"})]}):u.jsxs(u.Fragment,{children:[u.jsx(Am,{})," ",u.jsx("span",{children:"Copy"})]})})]}),u.jsx("pre",{children:u.jsx("code",{className:e,children:m&&!r?u.jsxs(u.Fragment,{children:[d.slice(0,ty).join(` `),m=d.length>RH,h=m?d.length-ny*2:0,p=C.useCallback(()=>{navigator.clipboard.writeText(a),i(!0),setTimeout(()=>i(!1),1500)},[a]);return u.jsxs("div",{className:"code-block-wrap",children:[u.jsxs("div",{className:"code-block-header",children:[u.jsxs("span",{className:"code-block-lang",children:[c||"code",m?` (${d.length} lines)`:""]}),u.jsx("button",{className:"code-block-copy",onClick:p,children:n?u.jsxs(u.Fragment,{children:[u.jsx(Hl,{})," ",u.jsx("span",{children:"Copied"})]}):u.jsxs(u.Fragment,{children:[u.jsx(Rm,{})," ",u.jsx("span",{children:"Copy"})]})})]}),u.jsx("pre",{children:u.jsx("code",{className:e,children:m&&!r?u.jsxs(u.Fragment,{children:[d.slice(0,ny).join(`
`)+` `)+`
`,u.jsxs("span",{className:"code-block-omitted",onClick:()=>o(!0),children:["... +",h," lines (click to expand)"]}),` `,u.jsxs("span",{className:"code-block-omitted",onClick:()=>o(!0),children:["... +",h," lines (click to expand)"]}),`
`+d.slice(-ty).join(` `+d.slice(-ny).join(`
`)]}):a})}),m&&r&&u.jsxs("button",{className:"code-block-collapse-btn",onClick:()=>o(!1),children:["Collapse (",d.length," lines)"]})]})}const _H={code({className:e,children:t,...n}){return e?.startsWith("language-")?u.jsx(bH,{className:e,children:t}):u.jsx("code",{className:e,...n,children:t})}},kH=3e3,SH=60,ny=800;function $w(e){if(e.length>kH)return!0;let t=0;for(let n=0;n<e.length;n++)if(e[n]===` `)]}):a})}),m&&r&&u.jsxs("button",{className:"code-block-collapse-btn",onClick:()=>o(!1),children:["Collapse (",d.length," lines)"]})]})}const MH={code({className:e,children:t,...n}){return e?.startsWith("language-")?u.jsx(AH,{className:e,children:t}):u.jsx("code",{className:e,...n,children:t})}},DH=3e3,OH=60,iy=800;function Yw(e){if(e.length>DH)return!0;let t=0;for(let n=0;n<e.length;n++)if(e[n]===`
`&&++t>=SH)return!0;return!1}function wH(e){const t=e.lastIndexOf(` `&&++t>=OH)return!0;return!1}function LH(e){const t=e.lastIndexOf(`
`,ny);return e.slice(0,t>ny/2?t:ny)}const bi=Nt.memo(function({content:t,className:n="msg-content-agent",collapseMode:i="auto"}){const r=i!=="never"&&$w(t),[o,a]=C.useState(r);C.useEffect(()=>{a(i!=="never"&&$w(t))},[i,t]);const c=o?wH(t):t,d=t.split(` `,iy);return e.slice(0,t>iy/2?t:iy)}const bi=Nt.memo(function({content:t,className:n="msg-content-agent",collapseMode:i="auto"}){const r=i!=="never"&&Yw(t),[o,a]=C.useState(r);C.useEffect(()=>{a(i!=="never"&&Yw(t))},[i,t]);const c=o?LH(t):t,d=t.split(`
`).length,m=t.length;return u.jsxs("div",{className:n,children:[u.jsx(s$,{remarkPlugins:[xH],components:_H,children:c}),r&&o&&u.jsxs("button",{className:"msg-collapse-toggle",onClick:()=>a(!1),children:["Show more (",d," lines, ",(m/1e3).toFixed(1),"k chars)"]}),r&&!o&&u.jsx("button",{className:"msg-collapse-toggle",onClick:()=>a(!0),children:"Show less"})]})}),Hw={native:"OpenOPC Native",codex:"Codex",claude_code:"Claude Code",cursor:"Cursor",opencode:"OpenCode"},Nu="codex",iy="native",CH=["codex","native","claude_code","cursor","opencode"],jH=["native","codex","claude_code","cursor","opencode"];function kI(e){if(!e)return{kind:"fallback"};if(e.kind==="employee"){const t=String(e.id??e.employee_id??"").trim();return t?{kind:"employee",id:t}:{kind:"fallback"}}if(e.kind==="template"){const t=String(e.id??e.template_id??"").trim();return t?{kind:"template",id:t}:{kind:"fallback"}}return{kind:"fallback"}}function SI(e){const t=kI(e);return t.kind==="fallback"?"fallback:":`${t.kind}:${t.id??""}`}function EH(e,t,n){const i=String(e.role_id??"").trim(),r=String(e.role_label??"").trim(),o=`${i} ${r} ${e.role_responsibility??""}`.toLowerCase(),a=new Set((e.same_role_employee_ids??[]).map(m=>String(m??"").trim()).filter(Boolean)),c=t.map(m=>{const h=String(m.employee_id??"").trim(),p=String(m.employee_name??h).trim()||h,g=String(m.role_id??"").trim(),x=String(m.category??"").trim(),v=[g,x].filter(Boolean).join(" · ")||h;return{kind:"employee",id:h,name:p,subtitle:v,category:x,searchText:`${h} ${p} ${g} ${x} ${(m.domains??[]).join(" ")} ${(m.tags??[]).join(" ")}`.toLowerCase(),rank:a.has(h)||g===i?0:2}}).filter(m=>m.id).sort((m,h)=>m.rank-h.rank||m.name.localeCompare(h.name)),d=n.map(m=>{const h=String(m.template_id??"").trim(),p=String(m.template_name??h).trim()||h,g=String(m.category??"").trim(),x=[g,h].filter(Boolean).join(" · ")||h,v=`${h} ${p} ${g} ${(m.domains??[]).join(" ")} ${(m.tags??[]).join(" ")}`.toLowerCase(),b=o.split(/[^a-z0-9]+/).filter(k=>k.length>=3).reduce((k,w)=>k+(v.includes(w)?1:0),0);return{kind:"template",id:h,name:p,subtitle:x,category:g,searchText:v,rank:b}}).filter(m=>m.id).sort((m,h)=>h.rank-m.rank||m.name.localeCompare(h.name));return[...c,...d,{kind:"fallback",id:"",name:"Fallback role-only",subtitle:"No employee override",category:"fallback",searchText:"fallback role only no employee override"}]}function NH(e,t){const n=SI(t);return e.find(i=>`${i.kind}:${i.id}`===n)??e[0]}function IH(e,t){const n=t.toLowerCase().split(/\s+/).filter(Boolean);return n.length===0?!0:n.every(i=>e.searchText.includes(i))}function TH(e){return e.map(t=>{const n=String(t.role_id??"").trim(),i=String(t.existing_employee?.employee_id??"").trim(),r=String(t.candidate?.template_id??"").trim(),o=i?{kind:"employee",id:i}:r?{kind:"template",id:r}:{kind:"fallback"};return{role_id:n,role_label:t.role_labels?.[0]??n,role_responsibility:"",default_selection:o,same_role_employee_ids:t.existing_employee_ids??[],fallback_available:!0,default_agent:t.default_agent??Nu,selected_agent:t.selected_agent??t.default_agent??Nu,default_source:"recruitment"}}).filter(t=>t.role_id)}function RH(e,t){return t.kind==="template"&&e?.candidate?.template_id===t.id?e.candidate.proposed_name||e.candidate.template_name||t.name:t.kind==="employee"&&e?.existing_employee?.employee_id===t.id&&e.existing_employee.employee_name||t.name}function Fw(e,t){const n={},i=e.staffing_selections??{};for(const r of t){const o=String(r.role_id??"").trim();o&&(n[o]=kI(i[o]??r.default_selection))}return n}function Vw(e,t){const n=e.recruitment_role_agents??{},i={};for(const r of t){const o=String(r.role_id??"").trim();o&&(i[o]=n[o]??r.selected_agent??r.default_agent??Nu)}return i}function AH(e){return!!(String(e.checkpoint_response_message_id??"").trim()||String(e.checkpoint_responded_at??"").trim()||String(e.checkpoint_reply_kind??"").trim())}const MH=Nt.memo(function({meta:t,onReply:n,responded:i}){const r=t.proposals??[],o=C.useMemo(()=>{const L={};for(const M of r){const A=String(M.role_id??"").trim();A&&(L[A]=M)}return L},[r]),a=C.useMemo(()=>t.staffing_roles?.length?t.staffing_roles:TH(r),[t.staffing_roles,r]),c=t.staffing_pool?.employees??[],d=t.staffing_pool?.templates??[],m=t.recruitment_rationales??[],h=C.useMemo(()=>{const L={};for(const M of a){const A=String(M.role_id??"").trim();A&&(L[A]=EH(M,c,d))}return L},[c,a,d]),[p,g]=C.useState({}),[x,v]=C.useState(""),[b,k]=C.useState(()=>Fw(t,a)),[w,S]=C.useState(()=>Vw(t,a)),[j,N]=C.useState(t.recruitment_agent??iy),O=i;C.useEffect(()=>{!O||!AH(t)||(k(Fw(t,a)),S(Vw(t,a)),N(t.recruitment_agent??iy))},[O,t,a]),C.useEffect(()=>{N(t.recruitment_agent??iy)},[t.recruitment_agent]);const R=C.useCallback(L=>{const M=String(t.checkpoint_id??"").trim();if(!M)throw new Error("Recruitment checkpoint reply requires checkpoint_id metadata.");const A=String(t.checkpoint_type??"").trim();return{response_to_checkpoint_id:M,response_to_checkpoint_type:A||"company_recruitment_confirmation",checkpoint_reply_kind:L,staffin Line truncated `).length,m=t.length;return u.jsxs("div",{className:n,children:[u.jsx(y$,{remarkPlugins:[TH],components:MH,children:c}),r&&o&&u.jsxs("button",{className:"msg-collapse-toggle",onClick:()=>a(!1),children:["Show more (",d," lines, ",(m/1e3).toFixed(1),"k chars)"]}),r&&!o&&u.jsx("button",{className:"msg-collapse-toggle",onClick:()=>a(!0),children:"Show less"})]})}),Xw={native:"OpenOPC Native",codex:"Codex",claude_code:"Claude Code",cursor:"Cursor",opencode:"OpenCode"},Eu="codex",ry="native",zH=["codex","native","claude_code","cursor","opencode"],PH=["native","codex","claude_code","cursor","opencode"];function AI(e){if(!e)return{kind:"fallback"};if(e.kind==="employee"){const t=String(e.id??e.employee_id??"").trim();return t?{kind:"employee",id:t}:{kind:"fallback"}}if(e.kind==="template"){const t=String(e.id??e.template_id??"").trim();return t?{kind:"template",id:t}:{kind:"fallback"}}return{kind:"fallback"}}function MI(e){const t=AI(e);return t.kind==="fallback"?"fallback:":`${t.kind}:${t.id??""}`}function BH(e,t,n){const i=String(e.role_id??"").trim(),r=String(e.role_label??"").trim(),o=`${i} ${r} ${e.role_responsibility??""}`.toLowerCase(),a=new Set((e.same_role_employee_ids??[]).map(m=>String(m??"").trim()).filter(Boolean)),c=t.map(m=>{const h=String(m.employee_id??"").trim(),p=String(m.employee_name??h).trim()||h,g=String(m.role_id??"").trim(),x=String(m.category??"").trim(),v=[g,x].filter(Boolean).join(" · ")||h;return{kind:"employee",id:h,name:p,subtitle:v,category:x,searchText:`${h} ${p} ${g} ${x} ${(m.domains??[]).join(" ")} ${(m.tags??[]).join(" ")}`.toLowerCase(),rank:a.has(h)||g===i?0:2}}).filter(m=>m.id).sort((m,h)=>m.rank-h.rank||m.name.localeCompare(h.name)),d=n.map(m=>{const h=String(m.template_id??"").trim(),p=String(m.template_name??h).trim()||h,g=String(m.category??"").trim(),x=[g,h].filter(Boolean).join(" · ")||h,v=`${h} ${p} ${g} ${(m.domains??[]).join(" ")} ${(m.tags??[]).join(" ")}`.toLowerCase(),_=o.split(/[^a-z0-9]+/).filter(k=>k.length>=3).reduce((k,w)=>k+(v.includes(w)?1:0),0);return{kind:"template",id:h,name:p,subtitle:x,category:g,searchText:v,rank:_}}).filter(m=>m.id).sort((m,h)=>h.rank-m.rank||m.name.localeCompare(h.name));return[...c,...d,{kind:"fallback",id:"",name:"Fallback role-only",subtitle:"No employee override",category:"fallback",searchText:"fallback role only no employee override"}]}function $H(e,t){const n=MI(t);return e.find(i=>`${i.kind}:${i.id}`===n)??e[0]}function HH(e,t){const n=t.toLowerCase().split(/\s+/).filter(Boolean);return n.length===0?!0:n.every(i=>e.searchText.includes(i))}function FH(e){return e.map(t=>{const n=String(t.role_id??"").trim(),i=String(t.existing_employee?.employee_id??"").trim(),r=String(t.candidate?.template_id??"").trim(),o=i?{kind:"employee",id:i}:r?{kind:"template",id:r}:{kind:"fallback"};return{role_id:n,role_label:t.role_labels?.[0]??n,role_responsibility:"",default_selection:o,same_role_employee_ids:t.existing_employee_ids??[],fallback_available:!0,default_agent:t.default_agent??Eu,selected_agent:t.selected_agent??t.default_agent??Eu,default_source:"recruitment"}}).filter(t=>t.role_id)}function VH(e,t){return t.kind==="template"&&e?.candidate?.template_id===t.id?e.candidate.proposed_name||e.candidate.template_name||t.name:t.kind==="employee"&&e?.existing_employee?.employee_id===t.id&&e.existing_employee.employee_name||t.name}function Kw(e,t){const n={},i=e.staffing_selections??{};for(const r of t){const o=String(r.role_id??"").trim();o&&(n[o]=AI(i[o]??r.default_selection))}return n}function Zw(e,t){const n=e.recruitment_role_agents??{},i={};for(const r of t){const o=String(r.role_id??"").trim();o&&(i[o]=n[o]??r.selected_agent??r.default_agent??Eu)}return i}function UH(e){return!!(String(e.checkpoint_response_message_id??"").trim()||String(e.checkpoint_responded_at??"").trim()||String(e.checkpoint_reply_kind??"").trim())}const GH=Nt.memo(function({meta:t,onReply:n,responded:i}){const r=t.proposals??[],o=C.useMemo(()=>{const L={};for(const M of r){const A=String(M.role_id??"").trim();A&&(L[A]=M)}return L},[r]),a=C.useMemo(()=>t.staffing_roles?.length?t.staffing_roles:FH(r),[t.staffing_roles,r]),c=t.staffing_pool?.employees??[],d=t.staffing_pool?.templates??[],m=t.recruitment_rationales??[],h=C.useMemo(()=>{const L={};for(const M of a){const A=String(M.role_id??"").trim();A&&(L[A]=BH(M,c,d))}return L},[c,a,d]),[p,g]=C.useState({}),[x,v]=C.useState(""),[_,k]=C.useState(()=>Kw(t,a)),[w,S]=C.useState(()=>Zw(t,a)),[j,N]=C.useState(t.recruitment_agent??ry),O=i;C.useEffect(()=>{!O||!UH(t)||(k(Kw(t,a)),S(Zw(t,a)),N(t.recruitment_agent??ry))},[O,t,a]),C.useEffect(()=>{N(t.recruitment_agent??ry)},[t.recruitment_agent]);const R=C.useCallback(L=>{const M=String(t.checkpoint_id??"").trim();if(!M)throw new Error("Recruitment checkpoint reply requires checkpoint_id metadata.");const A=String(t.checkpoint_type??"").trim();return{response_to_checkpoint_id:M,response_to_checkpoint_type:A||"company_recruitment_confirmation",checkpoint_reply_kind:L,staffin Line truncated
`).map(t=>t.trim()).find(Boolean)??e}function GH(e){switch(e){case"timeout":case"timed_out":case"expired":return"Expired";case"stale":case"invalid":return"Inactive";case"cancelled":case"canceled":return"Cancelled";case"resolved":return"Resolved";default:return"Responded"}}const Yw=Nt.memo(function({meta:t,onReply:n,responded:i}){const r=i,o=String(t.checkpoint_status??"").trim().toLowerCase(),a=GH(o),c=String(t.prompt??t.summary??""),d=C.useMemo(()=>c.split(` `).map(t=>t.trim()).find(Boolean)??e}function iF(e){switch(e){case"timeout":case"timed_out":case"expired":return"Expired";case"stale":case"invalid":return"Inactive";case"cancelled":case"canceled":return"Cancelled";case"resolved":return"Resolved";default:return"Responded"}}const nC=Nt.memo(function({meta:t,onReply:n,responded:i}){const r=i,o=String(t.checkpoint_status??"").trim().toLowerCase(),a=iF(o),c=String(t.prompt??t.summary??""),d=C.useMemo(()=>c.split(`
`).map(O=>O.trim()).filter(Boolean),[c]),m=UH(c).replace(/^\[[^\]]+\]\s*/,"")||"Action Required",h=d.slice(1).join(` `).map(O=>O.trim()).filter(Boolean),[c]),m=nF(c).replace(/^\[[^\]]+\]\s*/,"")||"Action Required",h=d.slice(1).join(`
`).trim(),p=String(t.summary??"").trim(),g=(t.options??[]).filter(O=>!!O?.id),x=C.useMemo(()=>(t.active_subagents??[]).filter(O=>!!O&&typeof O=="object"),[t.active_subagents]),v=C.useMemo(()=>(t.permission_requests??[]).filter(O=>!!O&&typeof O=="object"),[t.permission_requests]),b=String(t.worktree_path??"").trim(),k=x.length>0||v.length>0||!!b,[w,S]=C.useState(""),j=!!w&&!r;C.useEffect(()=>{if(!j)return;const O=window.setTimeout(()=>S(""),VH);return()=>window.clearTimeout(O)},[j,w]);const N=C.useCallback(O=>{r||j||(S(O.id),n(O.label||O.id))},[r,j,n]);return u.jsxs("div",{className:"ckpt-panel ckpt-escalation",children:[u.jsxs("div",{className:"ckpt-header",children:[u.jsx("div",{className:"ckpt-icon ckpt-icon-escalation",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M8 1.5L14.5 13H1.5L8 1.5Z"}),u.jsx("path",{d:"M8 5.5V9"}),u.jsx("circle",{cx:"8",cy:"11.5",r:"0.75",fill:"currentColor",stroke:"none"})]})}),u.jsx("div",{className:"ckpt-title",children:m}),u.jsx("span",{className:"ckpt-badge ckpt-badge-scope",children:String(t.escalation_type??"decision_needed").replace(/_/g," ")}),r&&u.jsx("span",{className:"ckpt-badge ckpt-badge-responded",children:a})]}),p&&p!==m&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Summary"}),u.jsx(bi,{content:p,className:"ckpt-markdown"})]}),h&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Request"}),u.jsx(bi,{content:h,className:"ckpt-markdown"})]}),k&&u.jsxs("details",{className:"ckpt-runtime-details",children:[u.jsx("summary",{children:"Runtime State"}),u.jsxs("div",{className:"ckpt-runtime-body",children:[b&&u.jsxs("div",{children:["Worktree: ",u.jsx("code",{children:b})]}),x.length>0&&u.jsxs("div",{children:["Active subagents: ",x.length]}),v.length>0&&u.jsxs("div",{children:["Pending permission records: ",v.length]})]})]}),!r&&g.length>0&&u.jsx("div",{className:"ckpt-actions ckpt-escalation-actions",children:g.map(O=>u.jsx("button",{className:`ckpt-btn ${O.id.includes("deny")?"ckpt-btn-deny":"ckpt-btn-approve"}${j?" ckpt-btn-submitting":""}`,onClick:()=>N(O),disabled:j,children:j&&w===O.id?"Submitting…":O.label||O.id},O.id))}),j&&u.jsx("div",{className:"ckpt-escalation-hint",children:"Decision sent — waiting for server confirmation…"}),!r&&t.default_action&&u.jsxs("div",{className:"ckpt-escalation-hint",children:["Default on timeout: ",u.jsx("code",{children:t.default_action})]})]})});function qH(e){return e.split(` `).trim(),p=String(t.summary??"").trim(),g=(t.options??[]).filter(O=>!!O?.id),x=C.useMemo(()=>(t.active_subagents??[]).filter(O=>!!O&&typeof O=="object"),[t.active_subagents]),v=C.useMemo(()=>(t.permission_requests??[]).filter(O=>!!O&&typeof O=="object"),[t.permission_requests]),_=String(t.worktree_path??"").trim(),k=x.length>0||v.length>0||!!_,[w,S]=C.useState(""),j=!!w&&!r;C.useEffect(()=>{if(!j)return;const O=window.setTimeout(()=>S(""),tF);return()=>window.clearTimeout(O)},[j,w]);const N=C.useCallback(O=>{r||j||(S(O.id),n(O.label||O.id))},[r,j,n]);return u.jsxs("div",{className:"ckpt-panel ckpt-escalation",children:[u.jsxs("div",{className:"ckpt-header",children:[u.jsx("div",{className:"ckpt-icon ckpt-icon-escalation",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M8 1.5L14.5 13H1.5L8 1.5Z"}),u.jsx("path",{d:"M8 5.5V9"}),u.jsx("circle",{cx:"8",cy:"11.5",r:"0.75",fill:"currentColor",stroke:"none"})]})}),u.jsx("div",{className:"ckpt-title",children:m}),u.jsx("span",{className:"ckpt-badge ckpt-badge-scope",children:String(t.escalation_type??"decision_needed").replace(/_/g," ")}),r&&u.jsx("span",{className:"ckpt-badge ckpt-badge-responded",children:a})]}),p&&p!==m&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Summary"}),u.jsx(bi,{content:p,className:"ckpt-markdown"})]}),h&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Request"}),u.jsx(bi,{content:h,className:"ckpt-markdown"})]}),k&&u.jsxs("details",{className:"ckpt-runtime-details",children:[u.jsx("summary",{children:"Runtime State"}),u.jsxs("div",{className:"ckpt-runtime-body",children:[_&&u.jsxs("div",{children:["Worktree: ",u.jsx("code",{children:_})]}),x.length>0&&u.jsxs("div",{children:["Active subagents: ",x.length]}),v.length>0&&u.jsxs("div",{children:["Pending permission records: ",v.length]})]})]}),!r&&g.length>0&&u.jsx("div",{className:"ckpt-actions ckpt-escalation-actions",children:g.map(O=>u.jsx("button",{className:`ckpt-btn ${O.id.includes("deny")?"ckpt-btn-deny":"ckpt-btn-approve"}${j?" ckpt-btn-submitting":""}`,onClick:()=>N(O),disabled:j,children:j&&w===O.id?"Submitting…":O.label||O.id},O.id))}),j&&u.jsx("div",{className:"ckpt-escalation-hint",children:"Decision sent — waiting for server confirmation…"}),!r&&t.default_action&&u.jsxs("div",{className:"ckpt-escalation-hint",children:["Default on timeout: ",u.jsx("code",{children:t.default_action})]})]})});function rF(e){return e.split(`
`).map(t=>t.trim()).find(Boolean)??e}function WH(e){switch(e){case"ignored":return"Ignored";case"timeout":case"timed_out":case"expired":return"Expired";case"stale":case"invalid":return"Inactive";case"superseded":return"Superseded";case"cancelled":case"canceled":return"Cancelled";case"resolved":return"Resolved";default:return"Responded"}}const YH=Nt.memo(function({meta:t,onReply:n,responded:i}){const r=i,[o,a]=C.useState(""),[c,d]=C.useState(null),m=String(t.checkpoint_status??"").trim().toLowerCase(),h=WH(m),p=String(t.prompt??t.summary??"").trim(),x=`${String(t.work_item_projection_title??qH(p)??"Human Review").trim()||"Human Review"} (for self-evolution)`,v=String(t.summary??"").trim(),b=C.useMemo(()=>(t.active_subagents??[]).filter(I=>!!I&&typeof I=="object"),[t.active_subagents]),k=C.useMemo(()=>(t.permission_requests??[]).filter(I=>!!I&&typeof I=="object"),[t.permission_requests]),w=String(t.worktree_path??"").trim(),S=b.length>0||k.length>0||!!w,j=r||c!==null,N=C.useCallback((I,L="")=>{const M=String(t.checkpoint_id??"").trim();if(!M)throw new Error("Delivery self-evolution reply requires checkpoint_id metadata.");const A={response_to_checkpoint_id:M,response_to_checkpoint_type:"company_delivery_feedback",checkpoint_reply_kind:I};return(I==="approve"||I==="feedback")&&(A.self_evolution_trigger=!0,A.human_feedback_text=L),A},[t.checkpoint_id]),O=C.useCallback(()=>{if(j)return;const I=N("approve");d("approve"),n("I fully agree with this delivery.",I)},[j,N,n]),R=C.useCallback(()=>{const I=o.trim();if(j||!I)return;const L=N("feedback",I);d("feedback"),n(I,L),a("")},[j,N,o,n]),D=C.useCallback(()=>{if(j)return;const I=N("ignore");d("ignore"),n("Ignore this self-evolution review.",I)},[j,N,n]);return u.jsxs("div",{className:"ckpt-panel ckpt-delivery-feedback",children:[u.jsxs("div",{className:"ckpt-header",children:[u.jsx("div",{className:"ckpt-icon ckpt-icon-user-input",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M8 1.5L14 5v4.5c0 2.25-1.8 4.25-6 5-4.2-.75-6-2.75-6-5V5L8 1.5Z"}),u.jsx("path",{d:"M5.5 8.25L7.25 10l3.25-4"})]})}),u.jsx("div",{className:"ckpt-title",children:x}),u.jsx("span",{className:"ckpt-badge ckpt-badge-scope",children:String(t.feedback_scope??"final").replace(/_/g," ")}),r&&u.jsx("span",{className:"ckpt-badge ckpt-badge-responded",children:h})]}),v&&v!==x&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Summary"}),u.jsx(bi,{content:v,className:"ckpt-markdown"})]}),p&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Review Request"}),u.jsx(bi,{content:p,className:"ckpt-markdown"})]}),S&&u.jsxs("details",{className:"ckpt-runtime-details",children:[u.jsx("summary",{children:"Runtime State"}),u.jsxs("div",{className:"ckpt-runtime-body",children:[w&&u.jsxs("div",{children:["Worktree: ",u.jsx("code",{children:w})]}),b.length>0&&u.jsxs("div",{children:["Active subagents: ",b.length]}),k.length>0&&u.jsxs("div",{children:["Pending permission records: ",k.length]})]})]}),!r&&u.jsxs("div",{className:"ckpt-actions ckpt-actions-inline-feedback",children:[u.jsx("button",{className:"ckpt-btn ckpt-btn-approve",onClick:O,disabled:j,children:"Fully Agree"}),u.jsx("button",{className:"ckpt-btn ckpt-btn-cancel",onClick:D,disabled:j,children:"Ignore"}),u.jsx("textarea",{className:"ckpt-feedback-input ckpt-feedback-inline-input",placeholder:"Feedback for self-evolution...",value:o,onChange:I=>a(I.target.value),disabled:j,rows:2}),u.jsx("button",{className:"ckpt-btn ckpt-btn-feedback",onClick:R,disabled:j||!o.trim(),children:"Send Feedback"})]})]})}),df="__other__",XH=["A","B","C"];function ts(e){return String(e??"").trim()}function KH(e,t){const n=ts(e.question),i=ts(e.header);if(!n&&!i)return null;const r=(e.options??[]).slice(0,3).map((o,a)=>({id:ts(o.id)||String.fromCharCode(97+a),label:ts(o.label),description:ts(o.description)})).filter(o=>o.label);return{id:ts(e.id)||`question_${t+1}`,header:i,question:n||i,options:r,allow_freeform:e.allow_freeform!==!1,required:e.required!==!1}}const ZH=Nt.memo(function({meta:t,onReply:n,responded:i}){const[r,o]=C.useState(""),[a,c]=C.useState({}),d=i,m=String(t.work_item_projection_title??t.work_item_projection_id??"Input Needed").trim()||"Input Needed",h=String(t.summary??"").trim(),p=String(t.prompt??"").trim(),g=String(t.context_note??"").trim(),x=String(t.resume_hint??"").trim(),v=C.useMemo(()=>(t.questions??[]).map(q=>String(q).trim()).filter(Boolean),[t.questions]),b=C.useMemo(()=>(t.input_questions??[]).map((q,Y)=>KH(q,Y)).filter(q=>q!==null),[t.input_questions]),k=b.some(q=>(q.options??[]).length>0),w=C.useMemo(()=>(t.required_fields??[]).map(q=>String(q).trim()).filter(Boolean),[t.required_fields]),S=C.useMemo(()=>(t.active_subagents??[]).filter(q=>!!q&&typeof q=="object"),[t.active_subagents]),j=C.useMemo(( Line truncated `).map(t=>t.trim()).find(Boolean)??e}function sF(e){switch(e){case"ignored":return"Ignored";case"timeout":case"timed_out":case"expired":return"Expired";case"stale":case"invalid":return"Inactive";case"superseded":return"Superseded";case"cancelled":case"canceled":return"Cancelled";case"resolved":return"Resolved";default:return"Responded"}}const oF=Nt.memo(function({meta:t,onReply:n,responded:i}){const r=i,[o,a]=C.useState(""),[c,d]=C.useState(null),m=String(t.checkpoint_status??"").trim().toLowerCase(),h=sF(m),p=String(t.prompt??t.summary??"").trim(),x=`${String(t.work_item_projection_title??rF(p)??"Human Review").trim()||"Human Review"} (for self-evolution)`,v=String(t.summary??"").trim(),_=C.useMemo(()=>(t.active_subagents??[]).filter(I=>!!I&&typeof I=="object"),[t.active_subagents]),k=C.useMemo(()=>(t.permission_requests??[]).filter(I=>!!I&&typeof I=="object"),[t.permission_requests]),w=String(t.worktree_path??"").trim(),S=_.length>0||k.length>0||!!w,j=r||c!==null,N=C.useCallback((I,L="")=>{const M=String(t.checkpoint_id??"").trim();if(!M)throw new Error("Delivery self-evolution reply requires checkpoint_id metadata.");const A={response_to_checkpoint_id:M,response_to_checkpoint_type:"company_delivery_feedback",checkpoint_reply_kind:I};return(I==="approve"||I==="feedback")&&(A.self_evolution_trigger=!0,A.human_feedback_text=L),A},[t.checkpoint_id]),O=C.useCallback(()=>{if(j)return;const I=N("approve");d("approve"),n("I fully agree with this delivery.",I)},[j,N,n]),R=C.useCallback(()=>{const I=o.trim();if(j||!I)return;const L=N("feedback",I);d("feedback"),n(I,L),a("")},[j,N,o,n]),D=C.useCallback(()=>{if(j)return;const I=N("ignore");d("ignore"),n("Ignore this self-evolution review.",I)},[j,N,n]);return u.jsxs("div",{className:"ckpt-panel ckpt-delivery-feedback",children:[u.jsxs("div",{className:"ckpt-header",children:[u.jsx("div",{className:"ckpt-icon ckpt-icon-user-input",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M8 1.5L14 5v4.5c0 2.25-1.8 4.25-6 5-4.2-.75-6-2.75-6-5V5L8 1.5Z"}),u.jsx("path",{d:"M5.5 8.25L7.25 10l3.25-4"})]})}),u.jsx("div",{className:"ckpt-title",children:x}),u.jsx("span",{className:"ckpt-badge ckpt-badge-scope",children:String(t.feedback_scope??"final").replace(/_/g," ")}),r&&u.jsx("span",{className:"ckpt-badge ckpt-badge-responded",children:h})]}),v&&v!==x&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Summary"}),u.jsx(bi,{content:v,className:"ckpt-markdown"})]}),p&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Review Request"}),u.jsx(bi,{content:p,className:"ckpt-markdown"})]}),S&&u.jsxs("details",{className:"ckpt-runtime-details",children:[u.jsx("summary",{children:"Runtime State"}),u.jsxs("div",{className:"ckpt-runtime-body",children:[w&&u.jsxs("div",{children:["Worktree: ",u.jsx("code",{children:w})]}),_.length>0&&u.jsxs("div",{children:["Active subagents: ",_.length]}),k.length>0&&u.jsxs("div",{children:["Pending permission records: ",k.length]})]})]}),!r&&u.jsxs("div",{className:"ckpt-actions ckpt-actions-inline-feedback",children:[u.jsx("button",{className:"ckpt-btn ckpt-btn-approve",onClick:O,disabled:j,children:"Fully Agree"}),u.jsx("button",{className:"ckpt-btn ckpt-btn-cancel",onClick:D,disabled:j,children:"Ignore"}),u.jsx("textarea",{className:"ckpt-feedback-input ckpt-feedback-inline-input",placeholder:"Feedback for self-evolution...",value:o,onChange:I=>a(I.target.value),disabled:j,rows:2}),u.jsx("button",{className:"ckpt-btn ckpt-btn-feedback",onClick:R,disabled:j||!o.trim(),children:"Send Feedback"})]})]})}),df="__other__",aF=["A","B","C"];function es(e){return String(e??"").trim()}function lF(e,t){const n=es(e.question),i=es(e.header);if(!n&&!i)return null;const r=(e.options??[]).slice(0,3).map((o,a)=>({id:es(o.id)||String.fromCharCode(97+a),label:es(o.label),description:es(o.description)})).filter(o=>o.label);return{id:es(e.id)||`question_${t+1}`,header:i,question:n||i,options:r,allow_freeform:e.allow_freeform!==!1,required:e.required!==!1}}const cF=Nt.memo(function({meta:t,onReply:n,responded:i}){const[r,o]=C.useState(""),[a,c]=C.useState({}),d=i,m=String(t.work_item_projection_title??t.work_item_projection_id??"Input Needed").trim()||"Input Needed",h=String(t.summary??"").trim(),p=String(t.prompt??"").trim(),g=String(t.context_note??"").trim(),x=String(t.resume_hint??"").trim(),v=C.useMemo(()=>(t.questions??[]).map(q=>String(q).trim()).filter(Boolean),[t.questions]),_=C.useMemo(()=>(t.input_questions??[]).map((q,Y)=>lF(q,Y)).filter(q=>q!==null),[t.input_questions]),k=_.some(q=>(q.options??[]).length>0),w=C.useMemo(()=>(t.required_fields??[]).map(q=>String(q).trim()).filter(Boolean),[t.required_fields]),S=C.useMemo(()=>(t.active_subagents??[]).filter(q=>!!q&&typeof q=="object"),[t.active_subagents]),j=C.useMemo(( Line truncated
`),{user_input_answers:q})},[a,P,b,d,n]);return u.jsxs("div",{className:"ckpt-panel ckpt-user-input",children:[u.jsxs("div",{className:"ckpt-header",children:[u.jsx("div",{className:"ckpt-icon ckpt-icon-user-input",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M3 3.5h10v6H6.5L3 13V3.5Z"}),u.jsx("path",{d:"M5.5 6h5"}),u.jsx("path",{d:"M5.5 8h3.5"})]})}),u.jsx("div",{className:"ckpt-title",children:m}),u.jsx("span",{className:"ckpt-badge ckpt-badge-scope",children:"awaiting input"}),d&&u.jsx("span",{className:"ckpt-badge ckpt-badge-responded",children:"Responded"})]}),h&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Summary"}),u.jsx(bi,{content:h,className:"ckpt-markdown"})]}),p&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Request"}),u.jsx(bi,{content:p,className:"ckpt-markdown"})]}),k?u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Questions"}),u.jsx("div",{className:"ckpt-choice-list",children:b.map(q=>{const Y=a[q.id]??{freeformText:""},Q=q.options??[],V=q.allow_freeform!==!1,U=V&&(Q.length===0||Y.selectedOptionId===df);return u.jsxs("div",{className:"ckpt-choice-question",children:[q.header&&u.jsx("div",{className:"ckpt-question-header",children:q.header}),u.jsx(bi,{content:q.question,className:"ckpt-markdown"}),Q.length>0&&u.jsxs("div",{className:"ckpt-choice-grid",children:[Q.map((Z,F)=>{const K=Y.selectedOptionId===Z.id;return u.jsxs("button",{className:`ckpt-choice-option${K?" is-selected":""}`,onClick:()=>A(q.id,Z.id),children:[u.jsx("span",{className:"ckpt-choice-letter",children:XH[F]??"?"}),u.jsxs("span",{className:"ckpt-choice-copy",children:[u.jsx("span",{className:"ckpt-choice-label",children:Z.label}),Z.description&&u.jsx("span",{className:"ckpt-choice-desc",children:Z.description})]})]},Z.id)}),V&&u.jsxs("button",{className:`ckpt-choice-option${Y.selectedOptionId===df?" is-selected":""}`,onClick:()=>A(q.id,df),children:[u.jsx("span",{className:"ckpt-choice-letter",children:"D"}),u.jsxs("span",{className:"ckpt-choice-copy",children:[u.jsx("span",{className:"ckpt-choice-label",children:"Other"}),u.jsx("span",{className:"ckpt-choice-desc",children:"Enter a custom answer"})]})]})]}),U&&u.jsx("textarea",{className:"ckpt-feedback-input ckpt-other-field",placeholder:"Type your answer...",value:Y.freeformText,onChange:Z=>B(q.id,Z.target.value),rows:3})]},q.id)})})]}):v.length>0&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Questions"}),u.jsx("ul",{className:"ckpt-task-list",children:v.map(q=>u.jsx("li",{children:q},q))})]}),w.length>0&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Required Fields"}),u.jsx("div",{className:"ckpt-task-tags",children:w.map(q=>u.jsx("span",{className:"ckpt-field-tag",children:q},q))})]}),g&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Context"}),u.jsx(bi,{content:g,className:"ckpt-markdown ckpt-markdown-muted"})]}),x&&u.jsx("div",{className:"ckpt-escalation-hint",children:x}),M&&u.jsxs("details",{className:"ckpt-runtime-details",children:[u.jsx("summary",{children:"Runtime State"}),u.jsxs("div",{className:"ckpt-runtime-body",children:[O&&u.jsxs("div",{children:["Requester: ",u.jsx("code",{children:O})]}),D&&u.jsxs("div",{children:["Work item: ",u.jsx("code",{children:D})]}),R&&u.jsxs("div",{children:["Task: ",u.jsx("code",{children:R})]}),I&&u.jsxs("div",{children:["Seat: ",u.jsx("code",{children:I})]}),N&&u.jsxs("div",{children:["Worktree: ",u.jsx("code",{children:N})]}),S.length>0&&u.jsxs("div",{children:["Active subagents: ",S.length]}),j.length>0&&u.jsxs("div",{children:["Pending permission records: ",j.length]})]})]}),!d&&u.jsxs("div",{className:"ckpt-feedback-area",children:[k?null:u.jsx("textarea",{className:"ckpt-feedback-input",placeholder:"Reply with the missing input to continue...",value:r,onChange:q=>o(q.target.value),rows:3}),u.jsx("div",{className:"ckpt-feedback-btns",children:u.jsx("button",{className:"ckpt-btn ckpt-btn-approve",onClick:k?$:G,disabled:k?!P:!r.trim(),children:"Send Reply"})})]})]})}),rv={todo:"To do",in_progress:"In progress",in_review:"In review",done:"Done"};function sy(e,t){if(t&&t in rv)return t;switch(e){case"active":return"in_progress";case"waiting":return"in_review";case"done":return"done";case"failed":return"done";case"pending":return"todo";default:return"todo"}}function ff(e){return rv[e]??rv.todo}const Xw={active:0,waiting:1,failed:2,done:3,pending:4};function QH(e){if(e.length===0)return"pending";let t=e[0],n=Xw[t]??99;for(const i of e){const r=Xw[i]??99;r<n&&(t=i,n=r)}return t}const JH={native:"Native",codex:"Codex",claude_code:"Claude Code",cursor Line truncated `),{user_input_answers:q})},[a,P,_,d,n]);return u.jsxs("div",{className:"ckpt-panel ckpt-user-input",children:[u.jsxs("div",{className:"ckpt-header",children:[u.jsx("div",{className:"ckpt-icon ckpt-icon-user-input",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M3 3.5h10v6H6.5L3 13V3.5Z"}),u.jsx("path",{d:"M5.5 6h5"}),u.jsx("path",{d:"M5.5 8h3.5"})]})}),u.jsx("div",{className:"ckpt-title",children:m}),u.jsx("span",{className:"ckpt-badge ckpt-badge-scope",children:"awaiting input"}),d&&u.jsx("span",{className:"ckpt-badge ckpt-badge-responded",children:"Responded"})]}),h&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Summary"}),u.jsx(bi,{content:h,className:"ckpt-markdown"})]}),p&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Request"}),u.jsx(bi,{content:p,className:"ckpt-markdown"})]}),k?u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Questions"}),u.jsx("div",{className:"ckpt-choice-list",children:_.map(q=>{const Y=a[q.id]??{freeformText:""},Q=q.options??[],V=q.allow_freeform!==!1,U=V&&(Q.length===0||Y.selectedOptionId===df);return u.jsxs("div",{className:"ckpt-choice-question",children:[q.header&&u.jsx("div",{className:"ckpt-question-header",children:q.header}),u.jsx(bi,{content:q.question,className:"ckpt-markdown"}),Q.length>0&&u.jsxs("div",{className:"ckpt-choice-grid",children:[Q.map((Z,F)=>{const K=Y.selectedOptionId===Z.id;return u.jsxs("button",{className:`ckpt-choice-option${K?" is-selected":""}`,onClick:()=>A(q.id,Z.id),children:[u.jsx("span",{className:"ckpt-choice-letter",children:aF[F]??"?"}),u.jsxs("span",{className:"ckpt-choice-copy",children:[u.jsx("span",{className:"ckpt-choice-label",children:Z.label}),Z.description&&u.jsx("span",{className:"ckpt-choice-desc",children:Z.description})]})]},Z.id)}),V&&u.jsxs("button",{className:`ckpt-choice-option${Y.selectedOptionId===df?" is-selected":""}`,onClick:()=>A(q.id,df),children:[u.jsx("span",{className:"ckpt-choice-letter",children:"D"}),u.jsxs("span",{className:"ckpt-choice-copy",children:[u.jsx("span",{className:"ckpt-choice-label",children:"Other"}),u.jsx("span",{className:"ckpt-choice-desc",children:"Enter a custom answer"})]})]})]}),U&&u.jsx("textarea",{className:"ckpt-feedback-input ckpt-other-field",placeholder:"Type your answer...",value:Y.freeformText,onChange:Z=>B(q.id,Z.target.value),rows:3})]},q.id)})})]}):v.length>0&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Questions"}),u.jsx("ul",{className:"ckpt-task-list",children:v.map(q=>u.jsx("li",{children:q},q))})]}),w.length>0&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Required Fields"}),u.jsx("div",{className:"ckpt-task-tags",children:w.map(q=>u.jsx("span",{className:"ckpt-field-tag",children:q},q))})]}),g&&u.jsxs("div",{className:"ckpt-section",children:[u.jsx("div",{className:"ckpt-section-title",children:"Context"}),u.jsx(bi,{content:g,className:"ckpt-markdown ckpt-markdown-muted"})]}),x&&u.jsx("div",{className:"ckpt-escalation-hint",children:x}),M&&u.jsxs("details",{className:"ckpt-runtime-details",children:[u.jsx("summary",{children:"Runtime State"}),u.jsxs("div",{className:"ckpt-runtime-body",children:[O&&u.jsxs("div",{children:["Requester: ",u.jsx("code",{children:O})]}),D&&u.jsxs("div",{children:["Work item: ",u.jsx("code",{children:D})]}),R&&u.jsxs("div",{children:["Task: ",u.jsx("code",{children:R})]}),I&&u.jsxs("div",{children:["Seat: ",u.jsx("code",{children:I})]}),N&&u.jsxs("div",{children:["Worktree: ",u.jsx("code",{children:N})]}),S.length>0&&u.jsxs("div",{children:["Active subagents: ",S.length]}),j.length>0&&u.jsxs("div",{children:["Pending permission records: ",j.length]})]})]}),!d&&u.jsxs("div",{className:"ckpt-feedback-area",children:[k?null:u.jsx("textarea",{className:"ckpt-feedback-input",placeholder:"Reply with the missing input to continue...",value:r,onChange:q=>o(q.target.value),rows:3}),u.jsx("div",{className:"ckpt-feedback-btns",children:u.jsx("button",{className:"ckpt-btn ckpt-btn-approve",onClick:k?$:G,disabled:k?!P:!r.trim(),children:"Send Reply"})})]})]})}),lv={todo:"To do",in_progress:"In progress",in_review:"In review",done:"Done"};function oy(e,t){if(t&&t in lv)return t;switch(e){case"active":return"in_progress";case"waiting":return"in_review";case"done":return"done";case"failed":return"done";case"pending":return"todo";default:return"todo"}}function ff(e){return lv[e]??lv.todo}const iC={active:0,waiting:1,failed:2,done:3,pending:4};function uF(e){if(e.length===0)return"pending";let t=e[0],n=iC[t]??99;for(const i of e){const r=iC[i]??99;r<n&&(t=i,n=r)}return t}const dF={native:"Native",codex:"Codex",claude_code:"Claude Code",cursor Line truncated
`)[0].slice(0,140),tone:"danger"};const o=t.match(/^\[Company:([^\]]+)\]\s*(.+)$/);if(o){const d=o[1].split("::"),m=d[0]||"company",h=o[2].trim(),p=h.toLowerCase(),g=p.includes("completed")||p.includes("done")?"success":p.includes("blocked")||p.includes("failed")?"warning":"info";return{kind:"company_event",label:`${m.toUpperCase()} · ${d[1]??""}`.replace(/ · $/,""),summary:h,tone:g}}const a=t.match(/^(Review needed|Status digest|Blocked|Completion):\s*(.+)$/i);if(a){const d=a[1].replace(/\b\w/g,h=>h.toUpperCase()),m=du(a[2]);return{kind:"company_event",label:d,summary:m,tone:/^Blocked$/i.test(a[1])?"warning":"info"}}const c=t.match(/^NO_DELEGATION_JUSTIFICATION:\s*(.+)$/i);return c?{kind:"company_event",label:"Delegation check",summary:du(c[1]).slice(0,180),tone:"info"}:null}function IF(e,t){const{isCompanyRuntime:n,detailMode:i}=t;if(!n||i==="full"||Sl(e.metadata))return null;const r=II(e.content);if(!r)return null;const o=e.sender==="system"||e.metadata?.type==="system",a=r.kind==="company_event"||e.content.startsWith("[Company:");return!o&&!a?null:{msg:e,classification:r}}function TF(e,t={}){const{isCompanyRuntime:n=!1,detailMode:i="summary"}=t,r=[];let o=[],a=0;const c=new Set,d=new Set,m=()=>{if(o.length===0)return;const h=o[0].msg;r.push({kind:"ops-bundle",id:`ops:${xo(h)}`,timestamp:h.timestamp,events:o,sortOrder:a}),o=[]};return e.forEach((h,p)=>{const g=p*2+1,x=IF(h,{isCompanyRuntime:n,detailMode:i});if(x){o.length===0&&(a=g),o.push(x);return}const v=i==="summary"?NI(h.content):null;if(v){const b=[h.sender,Math.round(h.timestamp/1e3),v.kind,du(v.summary||v.acceptanceSummary||"").slice(0,500),v.verdict??"",v.deliverables.map(k=>`${k.name}:${k.path}`).join("|").slice(0,800)].join("");if(c.has(b))return;c.add(b)}if(i==="summary"&&!Sl(h.metadata)){const b=du(xF(h.content)).slice(0,1200);if(b){const k=vF(h)?["result",b].join(""):[h.sender,Math.round(h.timestamp/1e3),b].join("");if(d.has(k))return;d.add(k)}}m(),r.push({kind:"message",id:xo(h),timestamp:h.timestamp,msg:h,sortOrder:g})}),m(),r}const RF=Nt.memo(function({msg:t,showDate:n,dateStr:i,classification:r}){const[o,a]=C.useState(!1),c=t.content.trim()!==`[${r.label}] ${r.summary}`.trim()&&t.content.trim().length>r.summary.length+4;return u.jsxs("div",{children:[n&&u.jsx("div",{className:"msg-date-sep",children:u.jsx("span",{children:i})}),u.jsxs("div",{className:`msg-ops-row msg-ops-tone-${r.tone}${o?" expanded":""}`,onClick:c?()=>a(d=>!d):void 0,role:c?"button":void 0,tabIndex:c?0:-1,children:[u.jsx("span",{className:"msg-ops-dot","aria-hidden":"true"}),u.jsx("span",{className:"msg-ops-label",children:r.label}),r.summary&&u.jsx("span",{className:"msg-ops-summary",title:r.summary,children:r.summary}),u.jsx("span",{className:"msg-ops-time",title:Os(t.timestamp),children:jo(t.timestamp)}),c&&u.jsx("span",{className:`msg-ops-chevron${o?" open":""}`,"aria-hidden":"true",children:u.jsx(ss,{down:o})})]}),c&&o&&u.jsx("div",{className:"msg-ops-details",children:u.jsx("pre",{className:"msg-ops-details-pre",children:t.content})})]})}),AF=Nt.memo(function({events:t,showDate:n,dateStr:i}){const[r,o]=C.useState(!1);if(t.length===0)return null;const a=t[0].msg,c=t[t.length-1].msg,d=t.reduce((p,g)=>{const x=g.classification.kind==="company_event"?"company":g.classification.kind.startsWith("external")?"runtime":"delegation";return p[x]=(p[x]??0)+1,p},{}),m=Object.entries(d).map(([p,g])=>`${g} ${p}`).join(" · "),h=`${t.length} technical event${t.length===1?"":"s"} hidden`;return u.jsxs("div",{children:[n&&u.jsx("div",{className:"msg-date-sep",children:u.jsx("span",{children:i})}),u.jsxs("button",{type:"button",className:`msg-ops-bundle${r?" expanded":""}`,onClick:()=>o(p=>!p),title:`${Os(a.timestamp)} - ${Os(c.timestamp)}`,children:[u.jsx("span",{className:"msg-ops-bundle-dot"}),u.jsx("span",{className:"msg-ops-bundle-title",children:h}),u.jsx("span",{className:"msg-ops-bundle-summary",children:m}),u.jsx("span",{className:"msg-ops-bundle-time",children:jo(a.timestamp)}),u.jsx("span",{className:"msg-ops-bundle-chevron",children:u.jsx(ss,{down:r})})]}),r&&u.jsx("div",{className:"msg-ops-bundle-details",children:t.map(({msg:p,classification:g})=>u.jsxs("div",{className:`msg-ops-bundle-event msg-ops-tone-${g.tone}`,children:[u.jsx("span",{className:"msg-ops-dot"}),u.jsx("span",{className:"msg-ops-label",children:g.label}),u.jsx("span",{className:"msg-ops-summary",children:g.summary}),u.jsx("span",{className:"msg-ops-time",title:Os(p.timestamp),children:jo(p.timestamp)})]},p.id))})]})});function MF(e){return e.kind==="review"?`Review · ${e.verdict?e.verdict.replace(/_/g," "):"review"}`:e.kind==="report"?"Report":"Update"}const DF=Nt.memo(function({msg:t,payload:n,showDate:i,dateStr:r,isCopied:o,onCopy:a}){const c=EI(t.sender==="system"?t.senderName||"OPC":t.sender),d=t.senderDeleted?"[Deleted]":t.senderName,m=MF(n),h=n.summary||n.acceptanceSummary||m;return u.jsxs("div",{children:[i&&u.jsx("div",{className:"msg-date-sep",children:u.jsx("span",{children:r})}),u. Line truncated `)[0].slice(0,140),tone:"danger"};const o=t.match(/^\[Company:([^\]]+)\]\s*(.+)$/);if(o){const d=o[1].split("::"),m=d[0]||"company",h=o[2].trim(),p=h.toLowerCase(),g=p.includes("completed")||p.includes("done")?"success":p.includes("blocked")||p.includes("failed")?"warning":"info";return{kind:"company_event",label:`${m.toUpperCase()} · ${d[1]??""}`.replace(/ · $/,""),summary:h,tone:g}}const a=t.match(/^(Review needed|Status digest|Blocked|Completion):\s*(.+)$/i);if(a){const d=a[1].replace(/\b\w/g,h=>h.toUpperCase()),m=uy(a[2]);return{kind:"company_event",label:d,summary:m,tone:/^Blocked$/i.test(a[1])?"warning":"info"}}const c=t.match(/^NO_DELEGATION_JUSTIFICATION:\s*(.+)$/i);return c?{kind:"company_event",label:"Delegation check",summary:uy(c[1]).slice(0,180),tone:"info"}:null}function BF(e,t){const{isCompanyRuntime:n,detailMode:i}=t;if(!n||i==="full"||gu(e.metadata))return null;const r=PI(e.content);if(!r)return null;const o=e.sender==="system"||e.metadata?.type==="system",a=r.kind==="company_event"||e.content.startsWith("[Company:");return!o&&!a?null:{msg:e,classification:r}}function $F(e,t={}){const{isCompanyRuntime:n=!1,detailMode:i="summary"}=t,r=[];let o=[],a=0;const c=()=>{if(o.length===0)return;const d=o[0].msg;r.push({kind:"ops-bundle",id:`ops:${ia(d)}`,timestamp:d.timestamp,events:o,sortOrder:a}),o=[]};return e.forEach((d,m)=>{const h=m*2+1,p=BF(d,{isCompanyRuntime:n,detailMode:i});if(p){o.length===0&&(a=h),o.push(p);return}c(),r.push({kind:"message",id:ia(d),timestamp:d.timestamp,msg:d,sortOrder:h})}),c(),r}const HF=Nt.memo(function({msg:t,showDate:n,dateStr:i,classification:r}){const[o,a]=C.useState(!1),c=t.content.trim()!==`[${r.label}] ${r.summary}`.trim()&&t.content.trim().length>r.summary.length+4;return u.jsxs("div",{children:[n&&u.jsx("div",{className:"msg-date-sep",children:u.jsx("span",{children:i})}),u.jsxs("div",{className:`msg-ops-row msg-ops-tone-${r.tone}${o?" expanded":""}`,onClick:c?()=>a(d=>!d):void 0,role:c?"button":void 0,tabIndex:c?0:-1,children:[u.jsx("span",{className:"msg-ops-dot","aria-hidden":"true"}),u.jsx("span",{className:"msg-ops-label",children:r.label}),r.summary&&u.jsx("span",{className:"msg-ops-summary",title:r.summary,children:r.summary}),u.jsx("span",{className:"msg-ops-time",title:Os(t.timestamp),children:jo(t.timestamp)}),c&&u.jsx("span",{className:`msg-ops-chevron${o?" open":""}`,"aria-hidden":"true",children:u.jsx(rs,{down:o})})]}),c&&o&&u.jsx("div",{className:"msg-ops-details",children:u.jsx("pre",{className:"msg-ops-details-pre",children:t.content})})]})}),FF=Nt.memo(function({events:t,showDate:n,dateStr:i}){const[r,o]=C.useState(!1);if(t.length===0)return null;const a=t[0].msg,c=t[t.length-1].msg,d=t.reduce((p,g)=>{const x=g.classification.kind==="company_event"?"company":g.classification.kind.startsWith("external")?"runtime":"delegation";return p[x]=(p[x]??0)+1,p},{}),m=Object.entries(d).map(([p,g])=>`${g} ${p}`).join(" · "),h=`${t.length} technical event${t.length===1?"":"s"} hidden`;return u.jsxs("div",{children:[n&&u.jsx("div",{className:"msg-date-sep",children:u.jsx("span",{children:i})}),u.jsxs("button",{type:"button",className:`msg-ops-bundle${r?" expanded":""}`,onClick:()=>o(p=>!p),title:`${Os(a.timestamp)} - ${Os(c.timestamp)}`,children:[u.jsx("span",{className:"msg-ops-bundle-dot"}),u.jsx("span",{className:"msg-ops-bundle-title",children:h}),u.jsx("span",{className:"msg-ops-bundle-summary",children:m}),u.jsx("span",{className:"msg-ops-bundle-time",children:jo(a.timestamp)}),u.jsx("span",{className:"msg-ops-bundle-chevron",children:u.jsx(rs,{down:r})})]}),r&&u.jsx("div",{className:"msg-ops-bundle-details",children:t.map(({msg:p,classification:g})=>u.jsxs("div",{className:`msg-ops-bundle-event msg-ops-tone-${g.tone}`,children:[u.jsx("span",{className:"msg-ops-dot"}),u.jsx("span",{className:"msg-ops-label",children:g.label}),u.jsx("span",{className:"msg-ops-summary",children:g.summary}),u.jsx("span",{className:"msg-ops-time",title:Os(p.timestamp),children:jo(p.timestamp)})]},p.id))})]})});function VF(e){return e.kind==="review"?`Review · ${e.verdict?e.verdict.replace(/_/g," "):"review"}`:e.kind==="report"?"Report":"Update"}const UF=Nt.memo(function({msg:t,payload:n,showDate:i,dateStr:r,isCopied:o,onCopy:a}){const c=zI(t.sender==="system"?t.senderName||"OPC":t.sender),d=t.senderDeleted?"[Deleted]":t.senderName,m=VF(n),h=n.summary||n.acceptanceSummary||m;return u.jsxs("div",{children:[i&&u.jsx("div",{className:"msg-date-sep",children:u.jsx("span",{children:r})}),u.jsxs("div",{className:"msg-row agent msg-row-project-update",children:[u.jsx("div",{className:"msg-avatar agent-avatar",style:{background:c},children:d.charAt(0).toUpperCase()}),u.jsxs("div",{className:"msg-body",children:[u.jsxs("div",{className:"msg-agent-header",children:[u.jsx("span",{className:"msg-sender",style:{color:c},children:d}),u.jsx("span",{className:"msg-time",title:Os(t.timestamp),children:jo(t.timestamp)})]}),u.jsxs("div",{className:`msg-project-update-card msg-project-uLine truncated
Set up at least one role before running a task. Set up at least one role before running a task.
@@ -129,27 +141,27 @@ Go to Org tab now?`)&&n?.(),!1;const d=[],m=new Set(i.map(x=>x.role_id));o.runti
`+d.map(x=>"• "+x).join(` `+d.map(x=>"• "+x).join(`
`)+` `)+`
Run anyway?`):!0}function fV(e){if(!e)return!1;const t=Um(e);return!!(t.projectRun?.run_id||t.runtimeTeams.length>0||t.runtimeSeats.length>0)}function mV(e,t){return e?e.execMode==="company"||e.execMode==="org"||e.execMode==="custom"?"summary":"full":"summary"}function hy(e,t=0){if(!e)return!1;const n=String(e.execMode??"").trim().toLowerCase();return t>0||!!e.isCompanyRuntime||!!e.roleWorkItems||!!e.executorRoleWorkItems||n==="company"||n==="org"||n==="custom"}function pC(e){return String(e?.originTaskId??e?.taskId??"").trim()||null}function pV({boardColor:e,title:t,onCommit:n}){const[i,r]=C.useState(!1),[o,a]=C.useState(t),c=C.useRef(null);C.useEffect(()=>{i||a(t)},[t,i]);const d=C.useCallback(()=>{const h=o.trim();h&&h!==t?n(h):a(t),r(!1)},[o,t,n]),m=C.useCallback(()=>{a(t),r(!0),setTimeout(()=>c.current?.select(),0)},[t]);return u.jsx("div",{className:"board-selector",children:u.jsx("div",{className:"board-tabs",children:u.jsxs("span",{className:"board-tab active board-tab-editable",style:{"--board-color":e},children:[u.jsx("span",{className:"board-tab-dot",style:{background:e}}),i?u.jsx("input",{ref:c,className:"board-tab-title-input",value:o,onChange:h=>a(h.target.value),onBlur:d,onKeyDown:h=>{h.key==="Enter"&&d(),h.key==="Escape"&&(a(t),r(!1))}}):u.jsx("span",{className:"board-tab-title",onClick:m,title:"Click to edit session title",children:t})]})})})}function hV({boardStore:e,agents:t,officeMap:n,execMode:i,companyProfile:r,taskPreferredAgent:o,chatStore:a,sessionStore:c,projectId:d,onRunTask:m,onCreateTask:h,onMoveTask:p,onCreateSession:g,onSessionSend:x,onSecretarySend:v,onDeleteSession:b,onTitleChange:k,onSessionConfigChange:w,onSessionTaskAgentChange:S,onContinueInNewChat:j,onSessionStop:N,onSessionResume:O,onSessionComplete:R,onLoadSessionDetail:D,onOpenExecutionPanel:I,onCollabSync:L,orgInfoData:M,onNavigateToOrg:A,commsState:B,commsMessage:W,onCommsRefresh:P,onCommsReadMessage:G,savedOrgsList:$,activeSavedOrg:q,onSavedOrgsList:Y,onSavedOrgLoad:Q}){const{sessions:V,activeSessionId:U,activeSession:Z}=c,{markRead:F}=a,[K,ee]=C.useState("collapsed"),{width:te,isResizing:se,handleMouseDown:ae}=cV({initialWidth:380,minWidth:300,maxWidth:600,onCollapse:()=>ee("collapsed")}),[ue,ie]=C.useState("chat"),[we,je]=C.useState(null),[Te,Ge]=C.useState({kind:"activity"}),[Ze,Ye]=C.useState([]),[mt,Ft]=C.useState(!1),[Mt,jt]=C.useState({}),he=C.useRef(D),ze=C.useRef(V),ot=C.useRef(a.getChannelMessages),Ve=C.useRef({scope:null,active:new Set,child:null}),lt=C.useRef(new Set),me=C.useRef(0);ze.current=V,ot.current=a.getChannelMessages;const be=i==="company"||i==="org"||i==="custom",Ae=`secretary:${d}`,Be=`activity:${d}`,We=C.useMemo(()=>we?V.find(de=>de.taskId===we)??null:null,[V,we]),Lt=C.useMemo(()=>Te.kind!=="task-detail"?null:e.tasks.find(de=>de.id===Te.taskId)??null,[Te,e.tasks]),pt=C.useMemo(()=>{const de=Vm(Lt);return de?V.find(ve=>ve.taskId===de||ve.runtimeTaskId===de||ve.executionTurnId===de)??null:null},[V,Lt]),ke=C.useMemo(()=>pt?a.getChannelMessages(pt.channelId):[],[a.messages,a.getChannelMessages,pt]),qe=C.useMemo(()=>Af(Z,V),[V,Z]),Qe=C.useMemo(()=>Wf(Z,V),[V,Z]),$e=C.useMemo(()=>Yf(Z,[...Qe,...qe]),[Z,qe,Qe]);C.useEffect(()=>{he.current=D},[D]);const He=C.useCallback((de,ve,Pe="summary")=>{const ut=he.current;if(!ut||!de)return;const on=me.current,ce=ze.current.find(_t=>_t.taskId===de)?.channelId,Se=ve&&ce&&ve.channelId!==ce?ot.current(ce).find(_t=>Gf(_t,Pe)):ve,Le=[on,de,Pe,Se?.timestamp??"latest",Se?.id??""].join("|");if(lt.current.has(Le))return;lt.current.add(Le),jt(_t=>_t[de]?_t:{..._t,[de]:!0});let Ue;try{Ue=ut(de,{limit:uV,beforeCreatedAt:Se?.timestamp,beforeMessageId:Se?.id,detailLevel:Pe})}catch{lt.current.delete(Le),me.current===on&&(jt(ct=>ct[de]?{...ct,[de]:!1}:ct),Ve.current.active.delete(`${de}:${Pe}`),Ve.current.child===de&&(Ve.current.child=null));return}return Promise.resolve(Ue).catch(()=>{me.current===on&&(Ve.current.active.delete(`${de}:${Pe}`),Ve.current.child===de&&(Ve.current.child=null))}).finally(()=>{if(lt.current.delete(Le),me.current!==on)return;const _t=`${on}|${de}|`;[...lt.current.keys()].some(nt=>nt.startsWith(_t))||jt(nt=>nt[de]?{...nt,[de]:!1}:nt)})},[]),Vt=C.useCallback(de=>!!Mt[de],[Mt]);C.useLayoutEffect(()=>{me.current+=1,lt.current.clear(),Ve.current={scope:null,active:new Set,child:null},jt({})},[d]),C.useEffect(()=>()=>{me.current+=1,lt.current.clear()},[]),C.useEffect(()=>{we&&!We&&je(null)},[we,We]),C.useEffect(()=>{Te.kind==="task-detail"&&!Lt&&Ge({kind:"activity"})},[Te,Lt]);const ei=C.useRef(null);C.useEffect(()=>{if(!pt){ei.current=null;return}ei.current!==pt.taskId&&(ei.current=pt.taskId,He(pt.taskId,void 0,"full"))},[pt,He]),C.useEffect(()=>{if(!we){Ve.current.child=null;return}Ve.current.child!==we&&(Ve.current.child=we,He(we,void 0,"full"))},[we,He]),C.useEffect(()=>{if(!U){Ve.current.scope=null,Ve.current.active.clear();return}Ve.current.scope!==U&&(Ve.current.scope=U,Ve.current.active.clear());const de=$e.timelineSessions.length>0?$e.timelin Line truncated Run anyway?`):!0}function kV(e){if(!e)return!1;const t=Um(e);return!!(t.projectRun?.run_id||t.runtimeTeams.length>0||t.runtimeSeats.length>0)}function SV(e,t){return e?e.execMode==="company"||e.execMode==="org"||e.execMode==="custom"?"summary":"full":"summary"}function yy(e,t=0){if(!e)return!1;const n=String(e.execMode??"").trim().toLowerCase();return t>0||!!e.isCompanyRuntime||!!e.roleWorkItems||!!e.executorRoleWorkItems||n==="company"||n==="org"||n==="custom"}function kC(e){return String(e?.originTaskId??e?.taskId??"").trim()||null}function wV({boardColor:e,title:t,onCommit:n}){const[i,r]=C.useState(!1),[o,a]=C.useState(t),c=C.useRef(null);C.useEffect(()=>{i||a(t)},[t,i]);const d=C.useCallback(()=>{const h=o.trim();h&&h!==t?n(h):a(t),r(!1)},[o,t,n]),m=C.useCallback(()=>{a(t),r(!0),setTimeout(()=>c.current?.select(),0)},[t]);return u.jsx("div",{className:"board-selector",children:u.jsx("div",{className:"board-tabs",children:u.jsxs("span",{className:"board-tab active board-tab-editable",style:{"--board-color":e},children:[u.jsx("span",{className:"board-tab-dot",style:{background:e}}),i?u.jsx("input",{ref:c,className:"board-tab-title-input",value:o,onChange:h=>a(h.target.value),onBlur:d,onKeyDown:h=>{h.key==="Enter"&&d(),h.key==="Escape"&&(a(t),r(!1))}}):u.jsx("span",{className:"board-tab-title",onClick:m,title:"Click to edit session title",children:t})]})})})}function CV({boardStore:e,agents:t,officeMap:n,execMode:i,companyProfile:r,taskPreferredAgent:o,chatStore:a,sessionStore:c,projectId:d,onRunTask:m,onCreateTask:h,onMoveTask:p,onCreateSession:g,onSessionSend:x,onSecretarySend:v,onDeleteSession:_,onTitleChange:k,onSessionConfigChange:w,onSessionTaskAgentChange:S,onContinueInNewChat:j,onSessionStop:N,onSessionResume:O,onSessionComplete:R,onLoadSessionDetail:D,onOpenExecutionPanel:I,onCollabSync:L,orgInfoData:M,onNavigateToOrg:A,commsState:B,commsMessage:W,onCommsRefresh:P,onCommsReadMessage:G,savedOrgsList:$,activeSavedOrg:q,onSavedOrgsList:Y,onSavedOrgLoad:Q}){const{sessions:V,activeSessionId:U,activeSession:Z}=c,{markRead:F}=a,[K,ee]=C.useState("collapsed"),{width:te,isResizing:se,handleMouseDown:ae}=vV({initialWidth:380,minWidth:300,maxWidth:600,onCollapse:()=>ee("collapsed")}),[ue,ie]=C.useState("chat"),[we,je]=C.useState(null),[Te,Ge]=C.useState({kind:"activity"}),[Ze,Xe]=C.useState([]),[mt,Ft]=C.useState(!1),[Dt,jt]=C.useState({}),he=C.useRef(D),ze=C.useRef(V),ot=C.useRef(a.getChannelMessages),Ve=C.useRef({scope:null,active:new Set,child:null}),lt=C.useRef(new Set),me=C.useRef(0);ze.current=V,ot.current=a.getChannelMessages;const be=i==="company"||i==="org"||i==="custom",Ae=`secretary:${d}`,Be=`activity:${d}`,We=C.useMemo(()=>we?V.find(de=>de.taskId===we)??null:null,[V,we]),zt=C.useMemo(()=>Te.kind!=="task-detail"?null:e.tasks.find(de=>de.id===Te.taskId)??null,[Te,e.tasks]),ht=C.useMemo(()=>{const de=Vm(zt);return de?V.find(ve=>ve.taskId===de||ve.runtimeTaskId===de||ve.executionTurnId===de)??null:null},[V,zt]),ke=C.useMemo(()=>ht?a.getChannelMessages(ht.channelId):[],[a.messages,a.getChannelMessages,ht]),qe=C.useMemo(()=>Af(Z,V),[V,Z]),Qe=C.useMemo(()=>Wf(Z,V),[V,Z]),$e=C.useMemo(()=>Yf(Z,[...Qe,...qe]),[Z,qe,Qe]);C.useEffect(()=>{he.current=D},[D]);const Fe=C.useCallback((de,ve,Pe="summary")=>{const ut=he.current;if(!ut||!de)return;const an=me.current,ce=ze.current.find(_t=>_t.taskId===de)?.channelId,Se=ve&&ce&&ve.channelId!==ce?ot.current(ce).find(_t=>$v(_t,Pe)):ve,Le=[an,de,Pe,Se?.timestamp??"latest",Se?.id??""].join("|");if(lt.current.has(Le))return;lt.current.add(Le),jt(_t=>_t[de]?_t:{..._t,[de]:!0});let Ue;try{Ue=ut(de,{limit:bV,beforeCreatedAt:Se?.timestamp,beforeMessageId:Se?.id,detailLevel:Pe})}catch{lt.current.delete(Le),me.current===an&&(jt(ct=>ct[de]?{...ct,[de]:!1}:ct),Ve.current.active.delete(`${de}:${Pe}`),Ve.current.child===de&&(Ve.current.child=null));return}return Promise.resolve(Ue).catch(()=>{me.current===an&&(Ve.current.active.delete(`${de}:${Pe}`),Ve.current.child===de&&(Ve.current.child=null))}).finally(()=>{if(lt.current.delete(Le),me.current!==an)return;const _t=`${an}|${de}|`;[...lt.current.keys()].some(nt=>nt.startsWith(_t))||jt(nt=>nt[de]?{...nt,[de]:!1}:nt)})},[]),Vt=C.useCallback(de=>!!Dt[de],[Dt]);C.useLayoutEffect(()=>{me.current+=1,lt.current.clear(),Ve.current={scope:null,active:new Set,child:null},jt({})},[d]),C.useEffect(()=>()=>{me.current+=1,lt.current.clear()},[]),C.useEffect(()=>{we&&!We&&je(null)},[we,We]),C.useEffect(()=>{Te.kind==="task-detail"&&!zt&&Ge({kind:"activity"})},[Te,zt]);const ei=C.useRef(null);C.useEffect(()=>{if(!ht){ei.current=null;return}ei.current!==ht.taskId&&(ei.current=ht.taskId,Fe(ht.taskId,void 0,"full"))},[ht,Fe]),C.useEffect(()=>{if(!we){Ve.current.child=null;return}Ve.current.child!==we&&(Ve.current.child=we,Fe(we,void 0,"full"))},[we,Fe]),C.useEffect(()=>{if(!U){Ve.current.scope=null,Ve.current.active.clear();return}Ve.current.scope!==U&&(Ve.current.scope=U,Ve.current.active.clear());const de=$e.timelineSessions.length>0?$e.timelin Line truncated
`).replace(/\r/g,` `).replace(/\r/g,`
`).split(` `).split(`
`).map(r=>r.trimEnd()).join(` `).map(t=>t.trimEnd()).join(`
`).replace(/\n{3,}/g,` `).replace(/\n{3,}/g,`
`).trim(),n=yV(t),i=n.split(/\n{2,}/).map(r=>r.trim()).filter(Boolean);return i.length>1&&/^Verification:\s/i.test(i[i.length-1])?i.slice(0,-1).join(` `).trim()}function wC(e){const t=dv(e),n=EV(t),i=n.split(/\n{2,}/).map(r=>r.trim()).filter(Boolean);return i.length>1&&/^Verification:\s/i.test(i[i.length-1])?i.slice(0,-1).join(`
`).trim():n}function yV(e){const t=String(e||"").trim(),n=t.match(/^\*\*(.{8,160}?)\*\*:\s+([\s\S]+)$/);if(n){const a=n[2].trim();if(a.length>=80)return a}const i=t.indexOf(": ");if(i<8||i>160)return t;const r=t.slice(0,i).replace(/\*/g,"").trim(),o=t.slice(i+2).trim();return o.length<80||!/[A-Za-z\u4e00-\u9fff]/.test(r)||/^(https?|file)$/i.test(r)?t:o}function Rl(e){const t=Br(e),n=new Set,i=typeof t.checkpoint_type=="string"?t.checkpoint_type.trim():"",r=typeof t.checkpoint_id=="string"?t.checkpoint_id.trim():"";for(const o of[e.id,typeof t.ui_message_id=="string"?t.ui_message_id:"",i&&r?`checkpoint:${i}:${r}`:""]){const a=String(o??"").trim();a&&n.add(a)}return n}function cl(e){return new Set([...Rl(e)].map(t=>`${e.channelId}\0${t}`))}function xV(e){return e.startsWith("checkpoint:")}function ci(e){return typeof e.timestamp=="number"?e.timestamp:0}function av(e){return String(e.id??"").startsWith("msg-")}function DI(e){return!av(e)}function gC(e){const t={};for(const n of e){if(!DI(n))continue;const i=ci(n);i>(t[n.channelId]??0)&&(t[n.channelId]=i)}return t}function vV(e,t,n){return n<=(e[t]??0)?e:{...e,[t]:n}}function bV(e,t){const n={};for(const i of e){if(!DI(i)||i.sender==="user")continue;const r=t[i.channelId]??0;ci(i)<=r||(n[i.channelId]=(n[i.channelId]??0)+1)}return n}function yC(e){const t=String(e.sender??"").trim().toLowerCase(),n=Br(e),i=typeof n.role=="string"?n.role.trim().toLowerCase():"";return t==="user"||i==="user"?"user":"assistant"}function xC(e){const t=Br(e),n=String(e.sender??"").trim().toLowerCase();let i=0;const r=OI(e);return r&&(i+=1e3+r),t.source==="engine"&&(i+=100),n&&n!=="system"&&(i+=20),n&&!["assistant","system","user"].includes(n)&&(i+=5),e.replyToId&&(i+=2),i+=Math.min(Object.keys(t).length,10),i}function vC(e){return String(Br(e).source??"").trim().toLowerCase()==="engine"}function OI(e){const t=Br(e),n=String(t.transcript_kind??"").trim();if(n)return hC[n]??0;const i=String(t.kind??"").trim();return hC[i]??0}function Al(e){return OI(e)>0}function LI(e,t){if(e.channelId!==t.channelId)return!1;const n=Rl(e),i=Rl(t);for(const r of n)if(i.has(r))return!0;return!1}function mm(e,t){if(LI(e,t))return!0;if(e.channelId!==t.channelId||yC(e)!==yC(t)||fm(e.content)!==fm(t.content))return!1;const n=Al(e)&&Al(t);if(!n&&String(e.replyToId??"")!==String(t.replyToId??"")||!(vC(e)||vC(t)))return!1;const i=ci(e),r=ci(t);return!(!n&&i&&r&&Math.abs(i-r)>C0)}function pm(e,t,n=!1){let i=e,r=t;const o=av(e),a=av(t);o!==a?(i=o?t:e,r=o?e:t):(n||xC(t)>xC(e))&&(i=t,r=e);const c=[];for(const j of[r.mentions,i.mentions])for(const N of j??[])c.includes(N)||c.push(N);const d=Rl(e),m=Rl(t);let h="";for(const j of d)if(m.has(j)&&!xV(j)){h=j;break}const p=fm(i.content),g=p&&p===fm(r.content)?p:i.content,x=String(Br(e).checkpoint_id??"").trim(),v=String(Br(t).checkpoint_id??"").trim(),b=!!x&&x===v,k=Al(e)&&Al(t),w=k?String(Br(e).ui_timeline_id??Br(t).ui_timeline_id??Dv(e)).trim():"",S={...Br(r),...Br(i)};return w&&(S.ui_timeline_id=w),{...r,...i,...h?{id:h}:{},content:g,metadata:S,mentions:c,timestamp:b||k?ci(e)||ci(t):ci(i)||ci(r)}}function bC(e){const t=[],n=new Map;for(const i of[...e].sort((r,o)=>ci(r)-ci(o))){const r=cl(i);let o=-1,a=!1;for(const d of r){const m=n.get(d);if(m!==void 0){o=m,a=t[m].id===i.id;break}}if(o===-1){const d=ci(i),m=Al(i);for(let h=t.length-1;h>=0;h--){const p=ci(t[h]);if(!m&&d>0&&p>0&&d-p>C0)break;if(mm(t[h],i)){o=h;break}}}const c=o===-1?t.length:o;o===-1?t.push(i):t[o]=pm(t[o],i,a);for(const d of cl(t[c]))n.has(d)||n.set(d,c)}return t}function _V(e,t){const n=[...e],i=new Map;n.forEach((r,o)=>{for(const a of cl(r))i.set(a,o)});for(const r of[...t].sort((o,a)=>ci(o)-ci(a))){let o=-1;for(const a of cl(r)){const c=i.get(a);if(c!==void 0){o=c;break}}if(o<0){for(let a=n.length-1;a>=0;a-=1)if(mm(n[a],r)){o=a;break}}if(o<0)o=n.length,n.push(r);else{const a=n[o];n[o]=pm(a,r,a.id===r.id)}for(const a of cl(r))i.set(a,o);for(const a of cl(n[o]))i.set(a,o)}return n.sort((r,o)=>ci(r)===ci(o)?r.id.localeCompare(o.id):ci(r)-ci(o))}function kV(e,t){switch(t.type){case"SET":return t.channels;case"CLEAR":return[];case"ADD":return e.some(n=>n.id===t.channel.id)?e:[...e,t.channel];case"REMOVE":return e.filter(n=>n.id!==t.channelId);case"REMOVE_PARTICIPANT":return e.map(n=>({...n,participants:n.participants.filter(i=>i!==t.agentId)}));default:return e}}function SV(e,t){switch(t.type){case"SET":{const n=bC(t.messages);if(e.length===0)return n;const i=e.filter(r=>typeof r.id=="string"&&r.id.startsWith("msg-")&&!n.some(o=>mm(r,o)));return i.length===0?n:bC([...n,...i])}case"CLEAR":return[];case"ADD":{const n=ci(t.message);Rl(t.message);let i=!1;for(let r=e.length-1;r>=0;r--){const o=ci(e[r]);if(!i&&n>0&&o>0&&n-o>C0&&(i=!0),LI(e[r],t.message)){const a=[...e];return a[r]=pm(e[r],t.message,e[r].id===t.message.id),a}if((Al(t.message)||!i)&&mm(e[r],t.message)){const a=[...e];return a[r]=pm(e[r],t.message),a}}return[...e,t.message]}case"MERGE":return t.messages.length===0?e:_V(e,t.messages);case"MARK_ Line truncated `).trim():n}function EV(e){let t=String(e||"").trim();for(;;){const n=t.match(/^\*\*([^\r\n]{8,160}?)\*\*:(?:[ \t]+|\r?\n+)([\s\S]+)$/);if(!n)return t;const i=n[2].trim();if(i.length<80||i===t)return t;t=i}}function NV(e,t,n,i){if(!i)return n.content;const r=dv(e.content),o=dv(t.content);return!r||!o||r===o?n.content:r.endsWith(o)?e.content:o.endsWith(r)?t.content:n.content}function Tl(e){const t=Pr(e),n=new Set,i=typeof t.checkpoint_type=="string"?t.checkpoint_type.trim():"",r=typeof t.checkpoint_id=="string"?t.checkpoint_id.trim():"";for(const o of[e.id,typeof t.ui_message_id=="string"?t.ui_message_id:"",typeof t.result_delivery_id=="string"&&t.result_delivery_id.trim()?`delivery:${t.result_delivery_id.trim()}`:"",i&&r?`checkpoint:${i}:${r}`:""]){const a=String(o??"").trim();a&&n.add(a)}return n}function cl(e){return new Set([...Tl(e)].map(t=>`${e.channelId}\0${t}`))}function IV(e){return e.startsWith("checkpoint:")||e.startsWith("delivery:")}function ui(e){return typeof e.timestamp=="number"?e.timestamp:0}function fv(e){return String(e.id??"").startsWith("msg-")}function VI(e){return!fv(e)}function CC(e){const t={};for(const n of e){if(!VI(n))continue;const i=ui(n);i>(t[n.channelId]??0)&&(t[n.channelId]=i)}return t}function TV(e,t,n){return n<=(e[t]??0)?e:{...e,[t]:n}}function RV(e,t){const n={};for(const i of e){if(!VI(i)||i.sender==="user")continue;const r=t[i.channelId]??0;ui(i)<=r||(n[i.channelId]=(n[i.channelId]??0)+1)}return n}function jC(e){const t=String(e.sender??"").trim().toLowerCase(),n=Pr(e),i=typeof n.role=="string"?n.role.trim().toLowerCase():"";return t==="user"||i==="user"?"user":"assistant"}function EC(e){const t=Pr(e),n=String(e.sender??"").trim().toLowerCase();let i=0;const r=UI(e);return r&&(i+=1e3+r),t.source==="engine"&&(i+=100),n&&n!=="system"&&(i+=20),n&&!["assistant","system","user"].includes(n)&&(i+=5),e.replyToId&&(i+=2),i+=Math.min(Object.keys(t).length,10),i}function NC(e){return String(Pr(e).source??"").trim().toLowerCase()==="engine"}function UI(e){const t=Pr(e),n=String(t.transcript_kind??"").trim();if(n)return SC[n]??0;const i=String(t.kind??"").trim();return SC[i]??0}function Rl(e){return UI(e)>0}function GI(e,t){if(e.channelId!==t.channelId)return!1;const n=Tl(e),i=Tl(t);for(const r of n)if(i.has(r))return!0;return!1}function fm(e,t){if(GI(e,t))return!0;if(e.channelId!==t.channelId||jC(e)!==jC(t)||wC(e.content)!==wC(t.content))return!1;const n=Rl(e)&&Rl(t);if(!n&&String(e.replyToId??"")!==String(t.replyToId??"")||!(NC(e)||NC(t)))return!1;const i=ui(e),r=ui(t);return!(!n&&i&&r&&Math.abs(i-r)>R0)}function mm(e,t,n=!1){let i=e,r=t;const o=fv(e),a=fv(t);o!==a?(i=o?t:e,r=o?e:t):(n||EC(t)>EC(e))&&(i=t,r=e);const c=[];for(const j of[r.mentions,i.mentions])for(const N of j??[])c.includes(N)||c.push(N);const d=Tl(e),m=Tl(t);let h=!1,p="";for(const j of d)m.has(j)&&(IV(j)||(h=!0,p||(p=j)));const g=NV(e,t,i,h),x=String(Pr(e).checkpoint_id??"").trim(),v=String(Pr(t).checkpoint_id??"").trim(),_=!!x&&x===v,k=Rl(e)&&Rl(t),w=k?String(Pr(e).ui_timeline_id??Pr(t).ui_timeline_id??Bv(e)).trim():"",S={...Pr(r),...Pr(i)};return w&&(S.ui_timeline_id=w),{...r,...i,...p?{id:p}:{},content:g,metadata:S,mentions:c,timestamp:_||k?ui(e)||ui(t):ui(i)||ui(r)}}function IC(e){const t=[],n=new Map;for(const i of[...e].sort((r,o)=>ui(r)-ui(o))){const r=cl(i);let o=-1,a=!1;for(const d of r){const m=n.get(d);if(m!==void 0){o=m,a=t[m].id===i.id;break}}if(o===-1){const d=ui(i),m=Rl(i);for(let h=t.length-1;h>=0;h--){const p=ui(t[h]);if(!m&&d>0&&p>0&&d-p>R0)break;if(fm(t[h],i)){o=h;break}}}const c=o===-1?t.length:o;o===-1?t.push(i):t[o]=mm(t[o],i,a);for(const d of cl(t[c]))n.has(d)||n.set(d,c)}return t}function AV(e,t){const n=[...e],i=new Map;n.forEach((r,o)=>{for(const a of cl(r))i.set(a,o)});for(const r of[...t].sort((o,a)=>ui(o)-ui(a))){let o=-1;for(const a of cl(r)){const c=i.get(a);if(c!==void 0){o=c;break}}if(o<0){for(let a=n.length-1;a>=0;a-=1)if(fm(n[a],r)){o=a;break}}if(o<0)o=n.length,n.push(r);else{const a=n[o];n[o]=mm(a,r,a.id===r.id)}for(const a of cl(r))i.set(a,o);for(const a of cl(n[o]))i.set(a,o)}return n.sort((r,o)=>ui(r)===ui(o)?r.id.localeCompare(o.id):ui(r)-ui(o))}function MV(e,t){switch(t.type){case"SET":return t.channels;case"CLEAR":return[];case"ADD":return e.some(n=>n.id===t.channel.id)?e:[...e,t.channel];case"REMOVE":return e.filter(n=>n.id!==t.channelId);case"REMOVE_PARTICIPANT":return e.map(n=>({...n,participants:n.participants.filter(i=>i!==t.agentId)}));default:return e}}function DV(e,t){switch(t.type){case"SET":{const n=IC(t.messages);if(e.length===0)return n;const i=e.filter(r=>typeof r.id=="string"&&r.id.startsWith("msg-")&&!n.some(o=>fm(r,o)));return i.length===0?n:IC([...n,...i])}case"CLEAR":return[];case"ADD":{const n=ui(t.message);Tl(t.message);let i=!1;for(let r=e.length-1;r>=0;r--){const o=ui(e[r]);if(!i&&n>0&&o>0&&n-o>R0&&(i=!0),GI(e[r],t.message)){const a=[...e];return a[r]=mm(e[r],t.message,e[r].id===t.message.id),a}if((Rl(t.message)||!i)&&fm(e[r],t.message)){const a=[ Line truncated
${t}`:`${e}${t}`}function CV(e,t){const n=e.trim().replace(/\s+/g," ");return n?n.length>120?`${n.slice(0,120).trimEnd()}...`:n:t||"Thinking"}function jV(e){return{timestamp:Number.isFinite(e.timestamp)?e.timestamp:Date.now(),type:e.type,summary:typeof e.summary=="string"?e.summary:"",detail:typeof e.detail=="string"&&e.detail?e.detail:void 0,turnId:typeof e.turnId=="string"&&e.turnId?e.turnId:void 0,itemId:typeof e.itemId=="string"&&e.itemId?e.itemId:void 0,streamId:typeof e.streamId=="string"&&e.streamId?e.streamId:void 0,toolCallId:typeof e.toolCallId=="string"&&e.toolCallId?e.toolCallId:void 0,permissionGroupKey:typeof e.permissionGroupKey=="string"&&e.permissionGroupKey?e.permissionGroupKey:void 0,seq:typeof e.seq=="number"&&Number.isFinite(e.seq)?e.seq:void 0,executionMode:typeof e.executionMode=="string"&&e.executionMode?e.executionMode:void 0}}function hm(e){const t=e.itemId||e.streamId;return t?`${e.type}:${e.turnId??""}:${t}`:e.toolCallId&&(e.type==="tool_call"||e.type==="autonomy")?`${e.type}:${e.turnId??""}:${e.toolCallId}`:e.permissionGroupKey&&e.type==="autonomy"?`${e.type}:${e.turnId??""}:${e.permissionGroupKey}`:""}function EV(e,t){const n=hm(e),i=hm(t);return n&&i?n===i:t.timestamp-e.timestamp>Km||e.type!==t.type?!1:e.type==="thinking"||e.type==="assistant"?!0:e.type==="tool_call"?e.summary===t.summary:!1}function NV(e,t){return t.timestamp-e.timestamp<=Km&&e.type===t.type&&e.summary===t.summary&&(e.detail??"")===(t.detail??"")}function IV(e,t){if(e.type==="thinking"||e.type==="assistant"){const n=lv(e.detail??"",t.detail??"","thinking");return{timestamp:e.timestamp,type:e.type,summary:CV(n,t.summary||e.summary),detail:n||void 0,turnId:t.turnId??e.turnId,itemId:t.itemId??e.itemId,streamId:t.streamId??e.streamId,toolCallId:t.toolCallId??e.toolCallId,permissionGroupKey:t.permissionGroupKey??e.permissionGroupKey,seq:t.seq??e.seq,executionMode:t.executionMode??e.executionMode}}if(e.type==="tool_call"){const n=lv(e.detail??"",t.detail??"","tool_call");return{timestamp:e.timestamp,type:"tool_call",summary:t.summary||e.summary,detail:n||void 0,turnId:t.turnId??e.turnId,itemId:t.itemId??e.itemId,streamId:t.streamId??e.streamId,toolCallId:t.toolCallId??e.toolCallId,permissionGroupKey:t.permissionGroupKey??e.permissionGroupKey,seq:t.seq??e.seq,executionMode:t.executionMode??e.executionMode}}return t}function zI(e,t,n=100){const i=jV(t),r=hm(i),o=r?[...e].reverse().findIndex(d=>hm(d)===r):-1,a=o>=0?e.length-1-o:e.length-1,c=e[a];return c?r&&o>=0&&typeof c.seq=="number"&&typeof i.seq=="number"&&i.seq<=c.seq?e:NV(c,i)?yl([...e.slice(0,a),c,...e.slice(a+1)],n):EV(c,i)?yl([...e.slice(0,a),IV(c,i),...e.slice(a+1)],n):yl([...e,i],n):[i]}function PI(e,t=100){return(Array.isArray(e)?e:[]).reduce((n,i)=>zI(n,i,t),[])}function TV(e){return{timestamp:Number.isFinite(e.timestamp)?e.timestamp:Date.now(),type:e.type,workItemProjectionId:typeof e.workItemProjectionId=="string"&&e.workItemProjectionId?e.workItemProjectionId:void 0,workItemTurnType:typeof e.workItemTurnType=="string"&&e.workItemTurnType?e.workItemTurnType:void 0,workItemProjectionTitle:typeof e.workItemProjectionTitle=="string"&&e.workItemProjectionTitle?e.workItemProjectionTitle:void 0,runtimeTaskId:typeof e.runtimeTaskId=="string"&&e.runtimeTaskId?e.runtimeTaskId:void 0,executionTurnId:typeof e.executionTurnId=="string"&&e.executionTurnId?e.executionTurnId:void 0,roleName:typeof e.roleName=="string"&&e.roleName?e.roleName:void 0,detail:typeof e.detail=="string"&&e.detail?e.detail:void 0}}function BI(e,t){return e.type===t.type&&(e.workItemProjectionId??"")===(t.workItemProjectionId??"")&&(e.workItemTurnType??"")===(t.workItemTurnType??"")&&(e.workItemProjectionTitle??"")===(t.workItemProjectionTitle??"")&&(e.executionTurnId??e.runtimeTaskId??"")===(t.executionTurnId??t.runtimeTaskId??"")&&(e.roleName??"")===(t.roleName??"")}function RV(e,t){return t.timestamp-e.timestamp<=Km&&BI(e,t)&&(e.type==="thinking"||e.type==="tool_call")}function AV(e,t){return BI(e,t)&&(e.detail??"")===(t.detail??"")&&t.timestamp-e.timestamp<=Km}function MV(e,t){const n=t.type==="tool_call"?"tool_call":"thinking";return{...e,...t,timestamp:t.timestamp,detail:lv(e.detail??"",t.detail??"",n)||void 0}}function $I(e,t,n=100){const i=TV(t),r=e[e.length-1];return r?AV(r,i)?yl([...e.slice(0,-1),{...r,timestamp:i.timestamp}],n):RV(r,i)?yl([...e.slice(0,-1),MV(r,i)],n):yl([...e,i],n):[i]}function HI(e,t=100){return(Array.isArray(e)?e:[]).reduce((n,i)=>$I(n,i,t),[])}function cv(e){const t=String(e??"").trim().toLowerCase();return t==="company"?"company":t==="org"||t==="custom"?"org":"task"}function DV(e){return String(e??"").trim().toLowerCase()==="custom"?"custom":"corporate"}function FI(e){const t=String(e.execMode??"").trim().toLowerCase(),n=String(e.companyProfile??"").trim().toLowerCase(),i=String(e.orgId??"").trim(),o=t.length>0?cv(t):n==="custom"||i?"org":cv(t);return o==="org"?{...e,execMode:"org",companyProfile:"custom",orgId:i||void 0}:o==="company"?{...e,execMode:"company" Line truncated ${t}`:`${e}${t}`}function LV(e,t){const n=e.trim().replace(/\s+/g," ");return n?n.length>120?`${n.slice(0,120).trimEnd()}...`:n:t||"Thinking"}function zV(e){return{timestamp:Number.isFinite(e.timestamp)?e.timestamp:Date.now(),type:e.type,summary:typeof e.summary=="string"?e.summary:"",detail:typeof e.detail=="string"&&e.detail?e.detail:void 0,turnId:typeof e.turnId=="string"&&e.turnId?e.turnId:void 0,itemId:typeof e.itemId=="string"&&e.itemId?e.itemId:void 0,streamId:typeof e.streamId=="string"&&e.streamId?e.streamId:void 0,toolCallId:typeof e.toolCallId=="string"&&e.toolCallId?e.toolCallId:void 0,permissionGroupKey:typeof e.permissionGroupKey=="string"&&e.permissionGroupKey?e.permissionGroupKey:void 0,seq:typeof e.seq=="number"&&Number.isFinite(e.seq)?e.seq:void 0,executionMode:typeof e.executionMode=="string"&&e.executionMode?e.executionMode:void 0}}function pm(e){const t=e.itemId||e.streamId;return t?`${e.type}:${e.turnId??""}:${t}`:e.toolCallId&&(e.type==="tool_call"||e.type==="autonomy")?`${e.type}:${e.turnId??""}:${e.toolCallId}`:e.permissionGroupKey&&e.type==="autonomy"?`${e.type}:${e.turnId??""}:${e.permissionGroupKey}`:""}function PV(e,t){const n=pm(e),i=pm(t);return n&&i?n===i:t.timestamp-e.timestamp>Km||e.type!==t.type?!1:e.type==="thinking"||e.type==="assistant"?!0:e.type==="tool_call"?e.summary===t.summary:!1}function BV(e,t){return t.timestamp-e.timestamp<=Km&&e.type===t.type&&e.summary===t.summary&&(e.detail??"")===(t.detail??"")}function $V(e,t){if(e.type==="thinking"||e.type==="assistant"){const n=mv(e.detail??"",t.detail??"","thinking");return{timestamp:e.timestamp,type:e.type,summary:LV(n,t.summary||e.summary),detail:n||void 0,turnId:t.turnId??e.turnId,itemId:t.itemId??e.itemId,streamId:t.streamId??e.streamId,toolCallId:t.toolCallId??e.toolCallId,permissionGroupKey:t.permissionGroupKey??e.permissionGroupKey,seq:t.seq??e.seq,executionMode:t.executionMode??e.executionMode}}if(e.type==="tool_call"){const n=mv(e.detail??"",t.detail??"","tool_call");return{timestamp:e.timestamp,type:"tool_call",summary:t.summary||e.summary,detail:n||void 0,turnId:t.turnId??e.turnId,itemId:t.itemId??e.itemId,streamId:t.streamId??e.streamId,toolCallId:t.toolCallId??e.toolCallId,permissionGroupKey:t.permissionGroupKey??e.permissionGroupKey,seq:t.seq??e.seq,executionMode:t.executionMode??e.executionMode}}return t}function qI(e,t,n=100){const i=zV(t),r=pm(i),o=r?[...e].reverse().findIndex(d=>pm(d)===r):-1,a=o>=0?e.length-1-o:e.length-1,c=e[a];return c?r&&o>=0&&typeof c.seq=="number"&&typeof i.seq=="number"&&i.seq<=c.seq?e:BV(c,i)?yl([...e.slice(0,a),c,...e.slice(a+1)],n):PV(c,i)?yl([...e.slice(0,a),$V(c,i),...e.slice(a+1)],n):yl([...e,i],n):[i]}function WI(e,t=100){return(Array.isArray(e)?e:[]).reduce((n,i)=>qI(n,i,t),[])}function HV(e){return{timestamp:Number.isFinite(e.timestamp)?e.timestamp:Date.now(),type:e.type,workItemProjectionId:typeof e.workItemProjectionId=="string"&&e.workItemProjectionId?e.workItemProjectionId:void 0,workItemTurnType:typeof e.workItemTurnType=="string"&&e.workItemTurnType?e.workItemTurnType:void 0,workItemProjectionTitle:typeof e.workItemProjectionTitle=="string"&&e.workItemProjectionTitle?e.workItemProjectionTitle:void 0,runtimeTaskId:typeof e.runtimeTaskId=="string"&&e.runtimeTaskId?e.runtimeTaskId:void 0,executionTurnId:typeof e.executionTurnId=="string"&&e.executionTurnId?e.executionTurnId:void 0,roleName:typeof e.roleName=="string"&&e.roleName?e.roleName:void 0,detail:typeof e.detail=="string"&&e.detail?e.detail:void 0}}function YI(e,t){return e.type===t.type&&(e.workItemProjectionId??"")===(t.workItemProjectionId??"")&&(e.workItemTurnType??"")===(t.workItemTurnType??"")&&(e.workItemProjectionTitle??"")===(t.workItemProjectionTitle??"")&&(e.executionTurnId??e.runtimeTaskId??"")===(t.executionTurnId??t.runtimeTaskId??"")&&(e.roleName??"")===(t.roleName??"")}function FV(e,t){return t.timestamp-e.timestamp<=Km&&YI(e,t)&&(e.type==="thinking"||e.type==="tool_call")}function VV(e,t){return YI(e,t)&&(e.detail??"")===(t.detail??"")&&t.timestamp-e.timestamp<=Km}function UV(e,t){const n=t.type==="tool_call"?"tool_call":"thinking";return{...e,...t,timestamp:t.timestamp,detail:mv(e.detail??"",t.detail??"",n)||void 0}}function XI(e,t,n=100){const i=HV(t),r=e[e.length-1];return r?VV(r,i)?yl([...e.slice(0,-1),{...r,timestamp:i.timestamp}],n):FV(r,i)?yl([...e.slice(0,-1),UV(r,i)],n):yl([...e,i],n):[i]}function KI(e,t=100){return(Array.isArray(e)?e:[]).reduce((n,i)=>XI(n,i,t),[])}function pv(e){const t=String(e??"").trim().toLowerCase();return t==="company"?"company":t==="org"||t==="custom"?"org":"task"}function GV(e){return String(e??"").trim().toLowerCase()==="custom"?"custom":"corporate"}function ZI(e){const t=String(e.execMode??"").trim().toLowerCase(),n=String(e.companyProfile??"").trim().toLowerCase(),i=String(e.orgId??"").trim(),o=t.length>0?pv(t):n==="custom"||i?"org":pv(t);return o==="org"?{...e,execMode:"org",companyProfile:"custom",orgId:i||void 0}:o==="company"?{...e,execMode:"company" Line truncated
`)),[L,M]=C.useState(!1),A=C.useRef(e.role_id);C.useEffect(()=>{A.current!==e.role_id&&(A.current=e.role_id,d(e.name),h(e.responsibility),g(e.reports_to),v(e.icon??null),k(new Set(e.can_spawn)),S(new Set(e.tools)),N(e.runtime_policy?.execution_strategy??"auto"),R(e.preferred_external_agent??null),I((e.prompt_refs??[]).join(` `)),[L,M]=C.useState(!1),A=C.useRef(e.role_id);C.useEffect(()=>{A.current!==e.role_id&&(A.current=e.role_id,d(e.name),h(e.responsibility),g(e.reports_to),v(e.icon??null),k(new Set(e.can_spawn)),S(new Set(e.tools)),N(e.runtime_policy?.execution_strategy??"auto"),R(e.preferred_external_agent??null),I((e.prompt_refs??[]).join(`
`)),M(!1))},[e]);const B=C.useRef({}),W=C.useRef(null),P=C.useRef(e.role_id);C.useEffect(()=>{P.current=e.role_id},[e.role_id]);const G=C.useCallback(()=>{W.current&&(clearTimeout(W.current),W.current=null);const ie=B.current;B.current={},Object.keys(ie).length!==0&&r(P.current,ie)},[r]),$=C.useCallback(ie=>{i||(B.current={...B.current,...ie},W.current&&clearTimeout(W.current),W.current=setTimeout(G,500))},[G,i]);C.useEffect(()=>()=>{W.current&&(clearTimeout(W.current),W.current=null);const ie=B.current;Object.keys(ie).length>0&&(B.current={},r(P.current,ie))},[r]);const q=ie=>{d(ie),$({name:ie})},Y=ie=>{h(ie),$({responsibility:ie})},Q=ie=>{g(ie),$({reports_to:ie})},V=ie=>{v(ie),$({icon:ie})},U=ie=>{N(ie),$({execution_strategy:ie})},Z=ie=>{R(ie),$({preferred_external_agent:ie})},F=ie=>{I(ie);const we=ie.split(` `)),M(!1))},[e]);const B=C.useRef({}),W=C.useRef(null),P=C.useRef(e.role_id);C.useEffect(()=>{P.current=e.role_id},[e.role_id]);const G=C.useCallback(()=>{W.current&&(clearTimeout(W.current),W.current=null);const ie=B.current;B.current={},Object.keys(ie).length!==0&&r(P.current,ie)},[r]),$=C.useCallback(ie=>{i||(B.current={...B.current,...ie},W.current&&clearTimeout(W.current),W.current=setTimeout(G,500))},[G,i]);C.useEffect(()=>()=>{W.current&&(clearTimeout(W.current),W.current=null);const ie=B.current;Object.keys(ie).length>0&&(B.current={},r(P.current,ie))},[r]);const q=ie=>{d(ie),$({name:ie})},Y=ie=>{h(ie),$({responsibility:ie})},Q=ie=>{g(ie),$({reports_to:ie})},V=ie=>{v(ie),$({icon:ie})},U=ie=>{N(ie),$({execution_strategy:ie})},Z=ie=>{R(ie),$({preferred_external_agent:ie})},F=ie=>{I(ie);const we=ie.split(`
`).map(je=>je.trim()).filter(Boolean);$({prompt_refs:we})},K=ie=>{const we=new Set(b);we.has(ie)?we.delete(ie):we.add(ie),k(we),$({can_spawn:Array.from(we)})},ee=ie=>{const we=new Set(w);we.has(ie)?we.delete(ie):we.add(ie),S(we),$({tools:Array.from(we)})},te=C.useMemo(()=>t.filter(ie=>ie.role_id!==e.role_id),[t,e.role_id]),se=C.useMemo(()=>n.filter(ie=>(ie.role_ids?.length?ie.role_ids:[ie.role_id]).includes(e.role_id)).length,[n,e.role_id]),ae=C.useMemo(()=>D.split(` `).map(je=>je.trim()).filter(Boolean);$({prompt_refs:we})},K=ie=>{const we=new Set(_);we.has(ie)?we.delete(ie):we.add(ie),k(we),$({can_spawn:Array.from(we)})},ee=ie=>{const we=new Set(w);we.has(ie)?we.delete(ie):we.add(ie),S(we),$({tools:Array.from(we)})},te=C.useMemo(()=>t.filter(ie=>ie.role_id!==e.role_id),[t,e.role_id]),se=C.useMemo(()=>n.filter(ie=>(ie.role_ids?.length?ie.role_ids:[ie.role_id]).includes(e.role_id)).length,[n,e.role_id]),ae=C.useMemo(()=>D.split(`
`).filter(ie=>ie.trim()).length,[D]),ue=()=>{if(!L){M(!0);return}G(),o(e.role_id)};return u.jsxs("aside",{className:"ri-panel","aria-label":`Inspector for role ${e.name}`,children:[u.jsxs("header",{className:"ri-panel-header",children:[u.jsx("img",{src:Vu(x),alt:"",className:"ri-panel-icon"}),u.jsxs("div",{className:"ri-panel-title-wrap",children:[u.jsx("h3",{className:"ri-panel-title",children:c||"(unnamed)"}),u.jsx("code",{className:"ri-panel-id",children:e.role_id})]}),u.jsx("button",{className:"btn btn-ghost btn-sm ri-panel-close",onClick:a,title:"Close (Esc)",children:"✕"})]}),u.jsxs("div",{className:"ri-panel-body",children:[u.jsxs(nl,{title:"Identity",defaultExpanded:!0,children:[u.jsx(Nr,{label:"Name",children:u.jsx("input",{className:"ri-text-input",value:c,onChange:ie=>q(ie.target.value),disabled:i})}),u.jsx(Nr,{label:"Responsibility",children:u.jsx("textarea",{className:"ri-textarea",rows:3,value:m,onChange:ie=>Y(ie.target.value),disabled:i})}),u.jsx(Nr,{label:"Icon",children:u.jsx(oU,{value:x,onChange:V,readOnly:i})})]}),u.jsxs(nl,{title:"Hierarchy",defaultExpanded:!0,children:[u.jsx(Nr,{label:"Reports to",children:u.jsxs("select",{className:"ri-select",value:p,onChange:ie=>Q(ie.target.value),disabled:i,children:[u.jsx("option",{value:"owner",children:"You (Owner)"}),te.map(ie=>u.jsx("option",{value:ie.role_id,children:ie.name},ie.role_id))]})}),u.jsx(Nr,{label:"Can delegate to",children:u.jsx(aU,{allIds:te.map(ie=>ie.role_id),labelFor:ie=>te.find(we=>we.role_id===ie)?.name??ie,selected:b,onToggle:K,readOnly:i})}),u.jsx(Nr,{label:"Employees assigned",children:u.jsx("span",{className:"ri-meta-value",children:se})})]}),u.jsx(nl,{title:`Tools (${w.size})`,children:u.jsx(lU,{tools:w,onToggle:ee,readOnly:i})}),u.jsx(nl,{title:`Prompts (${ae})`,children:u.jsx(Nr,{label:"Prompt refs / inline",children:u.jsx("textarea",{className:"ri-textarea ri-textarea-mono",rows:5,placeholder:"One prompt ref or inline instruction per line",value:D,onChange:ie=>F(ie.target.value),disabled:i})})}),u.jsxs(nl,{title:"Runtime policy",children:[u.jsx(Nr,{label:"Execution strategy",children:u.jsx("div",{className:"ri-radio-group",children:rU.map(ie=>u.jsxs("label",{className:"ri-radio",title:ie.hint,children:[u.jsx("input",{type:"radio",name:`exec-strategy-${e.role_id}`,value:ie.value,checked:j===ie.value,onChange:()=>U(ie.value),disabled:i}),ie.label]},ie.value))})}),j==="external"&&u.jsx(Nr,{label:"Preferred external agent",children:u.jsxs("select",{className:"ri-select",value:O??"",onChange:ie=>Z(ie.target.value||null),disabled:i,children:[u.jsx("option",{value:"",children:"(any)"}),iU.map(ie=>u.jsx("option",{value:ie,children:ie},ie))]})})]}),u.jsxs(nl,{title:"Advanced",children:[u.jsx(Nr,{label:"Role type",children:u.jsx("span",{className:"ri-meta-value",children:e.role_type??"worker"})}),u.jsx(Nr,{label:"Skills",children:u.jsx("span",{className:"ri-meta-value",children:e.skill_refs&&e.skill_refs.length>0?e.skill_refs.join(", "):"(none)"})}),u.jsx(Nr,{label:"Artifact contract",children:u.jsx("span",{className:"ri-meta-value",children:e.artifact_contract_ref??"(none)"})})]})]}),!i&&u.jsx("footer",{className:"ri-panel-footer",children:u.jsx("button",{className:`btn btn-sm ${L?"btn-danger":"btn-ghost"}`,onClick:ue,onBlur:()=>M(!1),children:L?"Confirm delete?":"Delete role"})})]})}function nl({title:e,defaultExpanded:t=!1,children:n}){const[i,r]=C.useState(t);return u.jsxs("section",{className:`ri-group${i?" is-expanded":""}`,children:[u.jsxs("button",{className:"ri-group-header",onClick:()=>r(o=>!o),children:[u.jsx("span",{className:"ri-group-caret",children:i?"▾":"▸"}),u.jsx("span",{className:"ri-group-title",children:e})]}),i&&u.jsx("div",{className:"ri-group-body",children:n})]})}function Nr({label:e,children:t}){return u.jsxs("div",{className:"ri-field",children:[u.jsx("label",{className:"ri-field-label",children:e}),u.jsx("div",{className:"ri-field-control",children:t})]})}function oU({value:e,onChange:t,readOnly:n}){const[i,r]=C.useState(!1);return u.jsxs("div",{className:"ri-icon-picker",children:[u.jsxs("button",{className:"ri-icon-picker-trigger",onClick:()=>!n&&r(o=>!o),disabled:n,children:[u.jsx("img",{src:Vu(e),alt:"",className:"ri-icon-picker-current"}),u.jsx("span",{className:"ri-icon-picker-label",children:e??"generic"})]}),i&&u.jsxs("div",{className:"ri-icon-picker-popover",children:[u.jsx("button",{className:`ri-icon-option${e===null?" is-active":""}`,onClick:()=>{t(null),r(!1)},title:"Default icon",children:u.jsx("img",{src:fu.generic,alt:""})}),tU.filter(o=>o!=="generic").map(o=>u.jsx("button",{className:`ri-icon-option${e===o?" is-active":""}`,onClick:()=>{t(o),r(!1)},title:o,children:u.jsx("img",{src:fu[o],alt:o})},o))]})]})}function aU({allIds:e,labelFor:t,selected:n,onToggle:i,readOnly:r}){const[o,a]=C.useState(!1),c=e.filter(d=>!n.has(d));return u.jsxs("div",{className:"ri-multiselect",children:[u.jsxs("div",{className:"ri-chips",children:[Array.from(n).map(d=>u.jsxs("span",{className:"ri-ch Line truncated `).filter(ie=>ie.trim()).length,[D]),ue=()=>{if(!L){M(!0);return}G(),o(e.role_id)};return u.jsxs("aside",{className:"ri-panel","aria-label":`Inspector for role ${e.name}`,children:[u.jsxs("header",{className:"ri-panel-header",children:[u.jsx("img",{src:Fu(x),alt:"",className:"ri-panel-icon"}),u.jsxs("div",{className:"ri-panel-title-wrap",children:[u.jsx("h3",{className:"ri-panel-title",children:c||"(unnamed)"}),u.jsx("code",{className:"ri-panel-id",children:e.role_id})]}),u.jsx("button",{className:"btn btn-ghost btn-sm ri-panel-close",onClick:a,title:"Close (Esc)",children:"✕"})]}),u.jsxs("div",{className:"ri-panel-body",children:[u.jsxs(nl,{title:"Identity",defaultExpanded:!0,children:[u.jsx(Er,{label:"Name",children:u.jsx("input",{className:"ri-text-input",value:c,onChange:ie=>q(ie.target.value),disabled:i})}),u.jsx(Er,{label:"Responsibility",children:u.jsx("textarea",{className:"ri-textarea",rows:3,value:m,onChange:ie=>Y(ie.target.value),disabled:i})}),u.jsx(Er,{label:"Icon",children:u.jsx(yU,{value:x,onChange:V,readOnly:i})})]}),u.jsxs(nl,{title:"Hierarchy",defaultExpanded:!0,children:[u.jsx(Er,{label:"Reports to",children:u.jsxs("select",{className:"ri-select",value:p,onChange:ie=>Q(ie.target.value),disabled:i,children:[u.jsx("option",{value:"owner",children:"You (Owner)"}),te.map(ie=>u.jsx("option",{value:ie.role_id,children:ie.name},ie.role_id))]})}),u.jsx(Er,{label:"Can delegate to",children:u.jsx(xU,{allIds:te.map(ie=>ie.role_id),labelFor:ie=>te.find(we=>we.role_id===ie)?.name??ie,selected:_,onToggle:K,readOnly:i})}),u.jsx(Er,{label:"Employees assigned",children:u.jsx("span",{className:"ri-meta-value",children:se})})]}),u.jsx(nl,{title:`Tools (${w.size})`,children:u.jsx(vU,{tools:w,onToggle:ee,readOnly:i})}),u.jsx(nl,{title:`Prompts (${ae})`,children:u.jsx(Er,{label:"Prompt refs / inline",children:u.jsx("textarea",{className:"ri-textarea ri-textarea-mono",rows:5,placeholder:"One prompt ref or inline instruction per line",value:D,onChange:ie=>F(ie.target.value),disabled:i})})}),u.jsxs(nl,{title:"Runtime policy",children:[u.jsx(Er,{label:"Execution strategy",children:u.jsx("div",{className:"ri-radio-group",children:hU.map(ie=>u.jsxs("label",{className:"ri-radio",title:ie.hint,children:[u.jsx("input",{type:"radio",name:`exec-strategy-${e.role_id}`,value:ie.value,checked:j===ie.value,onChange:()=>U(ie.value),disabled:i}),ie.label]},ie.value))})}),j==="external"&&u.jsx(Er,{label:"Preferred external agent",children:u.jsxs("select",{className:"ri-select",value:O??"",onChange:ie=>Z(ie.target.value||null),disabled:i,children:[u.jsx("option",{value:"",children:"(any)"}),pU.map(ie=>u.jsx("option",{value:ie,children:ie},ie))]})})]}),u.jsxs(nl,{title:"Advanced",children:[u.jsx(Er,{label:"Role type",children:u.jsx("span",{className:"ri-meta-value",children:e.role_type??"worker"})}),u.jsx(Er,{label:"Skills",children:u.jsx("span",{className:"ri-meta-value",children:e.skill_refs&&e.skill_refs.length>0?e.skill_refs.join(", "):"(none)"})}),u.jsx(Er,{label:"Artifact contract",children:u.jsx("span",{className:"ri-meta-value",children:e.artifact_contract_ref??"(none)"})})]})]}),!i&&u.jsx("footer",{className:"ri-panel-footer",children:u.jsx("button",{className:`btn btn-sm ${L?"btn-danger":"btn-ghost"}`,onClick:ue,onBlur:()=>M(!1),children:L?"Confirm delete?":"Delete role"})})]})}function nl({title:e,defaultExpanded:t=!1,children:n}){const[i,r]=C.useState(t);return u.jsxs("section",{className:`ri-group${i?" is-expanded":""}`,children:[u.jsxs("button",{className:"ri-group-header",onClick:()=>r(o=>!o),children:[u.jsx("span",{className:"ri-group-caret",children:i?"▾":"▸"}),u.jsx("span",{className:"ri-group-title",children:e})]}),i&&u.jsx("div",{className:"ri-group-body",children:n})]})}function Er({label:e,children:t}){return u.jsxs("div",{className:"ri-field",children:[u.jsx("label",{className:"ri-field-label",children:e}),u.jsx("div",{className:"ri-field-control",children:t})]})}function yU({value:e,onChange:t,readOnly:n}){const[i,r]=C.useState(!1);return u.jsxs("div",{className:"ri-icon-picker",children:[u.jsxs("button",{className:"ri-icon-picker-trigger",onClick:()=>!n&&r(o=>!o),disabled:n,children:[u.jsx("img",{src:Fu(e),alt:"",className:"ri-icon-picker-current"}),u.jsx("span",{className:"ri-icon-picker-label",children:e??"generic"})]}),i&&u.jsxs("div",{className:"ri-icon-picker-popover",children:[u.jsx("button",{className:`ri-icon-option${e===null?" is-active":""}`,onClick:()=>{t(null),r(!1)},title:"Default icon",children:u.jsx("img",{src:du.generic,alt:""})}),fU.filter(o=>o!=="generic").map(o=>u.jsx("button",{className:`ri-icon-option${e===o?" is-active":""}`,onClick:()=>{t(o),r(!1)},title:o,children:u.jsx("img",{src:du[o],alt:o})},o))]})]})}function xU({allIds:e,labelFor:t,selected:n,onToggle:i,readOnly:r}){const[o,a]=C.useState(!1),c=e.filter(d=>!n.has(d));return u.jsxs("div",{className:"ri-multiselect",children:[u.jsxs("div",{className:"ri-chips",children:[Array.from(n).map(d=>u.jsxs("span",{className:"ri-ch Line truncated
font-size: .6rem; font-size: .6rem;
font-weight: bold; font-weight: bold;
color: hsl(${Math.max(0,Math.min(120-120*g,120))}deg 100% 31%);`,n?.key)}return r}}function xt(e,t,n,i){return{debug:()=>{var r;return(r=e?.debugAll)!=null?r:e[t]},key:!1,onChange:i}}function dU(e,t,n,i){const r=()=>{var a;return(a=o.getValue())!=null?a:e.options.renderFallbackValue},o={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(i),renderValue:r,getContext:yt(()=>[e,n,t,o],(a,c,d,m)=>({table:a,column:c,row:d,cell:m,getValue:m.getValue,renderValue:m.renderValue}),xt(e.options,"debugCells"))};return e._features.forEach(a=>{a.createCell==null||a.createCell(o,n,t,e)},{}),o}function fU(e,t,n,i){var r,o;const c={...e._getDefaultColumnDef(),...t},d=c.accessorKey;let m=(r=(o=c.id)!=null?o:d?typeof String.prototype.replaceAll=="function"?d.replaceAll(".","_"):d.replace(/\./g,"_"):void 0)!=null?r:typeof c.header=="string"?c.header:void 0,h;if(c.accessorFn?h=c.accessorFn:d&&(d.includes(".")?h=g=>{let x=g;for(const b of d.split(".")){var v;x=(v=x)==null?void 0:v[b]}return x}:h=g=>g[c.accessorKey]),!m)throw new Error;let p={id:`${String(m)}`,accessorFn:h,parent:i,depth:n,columnDef:c,columns:[],getFlatColumns:yt(()=>[!0],()=>{var g;return[p,...(g=p.columns)==null?void 0:g.flatMap(x=>x.getFlatColumns())]},xt(e.options,"debugColumns")),getLeafColumns:yt(()=>[e._getOrderColumnsFn()],g=>{var x;if((x=p.columns)!=null&&x.length){let v=p.columns.flatMap(b=>b.getLeafColumns());return g(v)}return[p]},xt(e.options,"debugColumns"))};for(const g of e._features)g.createColumn==null||g.createColumn(p,e);return p}const Li="debugHeaders";function CC(e,t,n){var i;let o={id:(i=n.id)!=null?i:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const a=[],c=d=>{d.subHeaders&&d.subHeaders.length&&d.subHeaders.map(c),a.push(d)};return c(o),a},getContext:()=>({table:e,header:o,column:t})};return e._features.forEach(a=>{a.createHeader==null||a.createHeader(o,e)}),o}const mU={createTable:e=>{e.getHeaderGroups=yt(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,i,r)=>{var o,a;const c=(o=i?.map(p=>n.find(g=>g.id===p)).filter(Boolean))!=null?o:[],d=(a=r?.map(p=>n.find(g=>g.id===p)).filter(Boolean))!=null?a:[],m=n.filter(p=>!(i!=null&&i.includes(p.id))&&!(r!=null&&r.includes(p.id)));return gf(t,[...c,...m,...d],e)},xt(e.options,Li)),e.getCenterHeaderGroups=yt(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,i,r)=>(n=n.filter(o=>!(i!=null&&i.includes(o.id))&&!(r!=null&&r.includes(o.id))),gf(t,n,e,"center")),xt(e.options,Li)),e.getLeftHeaderGroups=yt(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,i)=>{var r;const o=(r=i?.map(a=>n.find(c=>c.id===a)).filter(Boolean))!=null?r:[];return gf(t,o,e,"left")},xt(e.options,Li)),e.getRightHeaderGroups=yt(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,i)=>{var r;const o=(r=i?.map(a=>n.find(c=>c.id===a)).filter(Boolean))!=null?r:[];return gf(t,o,e,"right")},xt(e.options,Li)),e.getFooterGroups=yt(()=>[e.getHeaderGroups()],t=>[...t].reverse(),xt(e.options,Li)),e.getLeftFooterGroups=yt(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),xt(e.options,Li)),e.getCenterFooterGroups=yt(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),xt(e.options,Li)),e.getRightFooterGroups=yt(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),xt(e.options,Li)),e.getFlatHeaders=yt(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),xt(e.options,Li)),e.getLeftFlatHeaders=yt(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),xt(e.options,Li)),e.getCenterFlatHeaders=yt(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),xt(e.options,Li)),e.getRightFlatHeaders=yt(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),xt(e.options,Li)),e.getCenterLeafHeaders=yt(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var i;return!((i=n.subHeaders)!=null&&i.length)}),xt(e.options,Li)),e.getLeftLeafHeaders=yt(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var i;return!((i=n.subHeaders)!=null&&i.length)}),xt(e.options,Li)),e.getRightLeafHeaders=yt(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var i;return!((i=n.subHeaders)!=null&&i.length)}),xt(e.options,Li)),e.getLeafHeaders=yt(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,i)=>{var r,o,a,c,d,m;return[...(r=(o=t[0])==null?void 0:o.headers)!=null?r:[],...(a=(c=n[0])==null?void 0:c.headers)!=null?a:[],...(d=(m=i[0])==null?void 0:m.headers)!=null?d:[]].map(h=>h.getLeafHeaders()).flat()},xt(e.options,Li))}};function gf(e,t,n,i){var r,o;let a=0;const c=function(g,x){x===void 0&&(x=1),a=Math.max(a,x),g.filter(v=>v.getIsVisible()).forEach(v=>{var b;(b=v.columns)!=null&&b.length&&c(v.columns,x+1)},0)};c(e);let d=[];const m=(g,x)=>{const v={depth:x,id:[i,`${x}`].filter(Boolean).jo Line truncated color: hsl(${Math.max(0,Math.min(120-120*g,120))}deg 100% 31%);`,n?.key)}return r}}function xt(e,t,n,i){return{debug:()=>{var r;return(r=e?.debugAll)!=null?r:e[t]},key:!1,onChange:i}}function kU(e,t,n,i){const r=()=>{var a;return(a=o.getValue())!=null?a:e.options.renderFallbackValue},o={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(i),renderValue:r,getContext:yt(()=>[e,n,t,o],(a,c,d,m)=>({table:a,column:c,row:d,cell:m,getValue:m.getValue,renderValue:m.renderValue}),xt(e.options,"debugCells"))};return e._features.forEach(a=>{a.createCell==null||a.createCell(o,n,t,e)},{}),o}function SU(e,t,n,i){var r,o;const c={...e._getDefaultColumnDef(),...t},d=c.accessorKey;let m=(r=(o=c.id)!=null?o:d?typeof String.prototype.replaceAll=="function"?d.replaceAll(".","_"):d.replace(/\./g,"_"):void 0)!=null?r:typeof c.header=="string"?c.header:void 0,h;if(c.accessorFn?h=c.accessorFn:d&&(d.includes(".")?h=g=>{let x=g;for(const _ of d.split(".")){var v;x=(v=x)==null?void 0:v[_]}return x}:h=g=>g[c.accessorKey]),!m)throw new Error;let p={id:`${String(m)}`,accessorFn:h,parent:i,depth:n,columnDef:c,columns:[],getFlatColumns:yt(()=>[!0],()=>{var g;return[p,...(g=p.columns)==null?void 0:g.flatMap(x=>x.getFlatColumns())]},xt(e.options,"debugColumns")),getLeafColumns:yt(()=>[e._getOrderColumnsFn()],g=>{var x;if((x=p.columns)!=null&&x.length){let v=p.columns.flatMap(_=>_.getLeafColumns());return g(v)}return[p]},xt(e.options,"debugColumns"))};for(const g of e._features)g.createColumn==null||g.createColumn(p,e);return p}const Oi="debugHeaders";function DC(e,t,n){var i;let o={id:(i=n.id)!=null?i:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const a=[],c=d=>{d.subHeaders&&d.subHeaders.length&&d.subHeaders.map(c),a.push(d)};return c(o),a},getContext:()=>({table:e,header:o,column:t})};return e._features.forEach(a=>{a.createHeader==null||a.createHeader(o,e)}),o}const wU={createTable:e=>{e.getHeaderGroups=yt(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,i,r)=>{var o,a;const c=(o=i?.map(p=>n.find(g=>g.id===p)).filter(Boolean))!=null?o:[],d=(a=r?.map(p=>n.find(g=>g.id===p)).filter(Boolean))!=null?a:[],m=n.filter(p=>!(i!=null&&i.includes(p.id))&&!(r!=null&&r.includes(p.id)));return gf(t,[...c,...m,...d],e)},xt(e.options,Oi)),e.getCenterHeaderGroups=yt(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,i,r)=>(n=n.filter(o=>!(i!=null&&i.includes(o.id))&&!(r!=null&&r.includes(o.id))),gf(t,n,e,"center")),xt(e.options,Oi)),e.getLeftHeaderGroups=yt(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,i)=>{var r;const o=(r=i?.map(a=>n.find(c=>c.id===a)).filter(Boolean))!=null?r:[];return gf(t,o,e,"left")},xt(e.options,Oi)),e.getRightHeaderGroups=yt(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,i)=>{var r;const o=(r=i?.map(a=>n.find(c=>c.id===a)).filter(Boolean))!=null?r:[];return gf(t,o,e,"right")},xt(e.options,Oi)),e.getFooterGroups=yt(()=>[e.getHeaderGroups()],t=>[...t].reverse(),xt(e.options,Oi)),e.getLeftFooterGroups=yt(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),xt(e.options,Oi)),e.getCenterFooterGroups=yt(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),xt(e.options,Oi)),e.getRightFooterGroups=yt(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),xt(e.options,Oi)),e.getFlatHeaders=yt(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),xt(e.options,Oi)),e.getLeftFlatHeaders=yt(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),xt(e.options,Oi)),e.getCenterFlatHeaders=yt(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),xt(e.options,Oi)),e.getRightFlatHeaders=yt(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),xt(e.options,Oi)),e.getCenterLeafHeaders=yt(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var i;return!((i=n.subHeaders)!=null&&i.length)}),xt(e.options,Oi)),e.getLeftLeafHeaders=yt(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var i;return!((i=n.subHeaders)!=null&&i.length)}),xt(e.options,Oi)),e.getRightLeafHeaders=yt(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var i;return!((i=n.subHeaders)!=null&&i.length)}),xt(e.options,Oi)),e.getLeafHeaders=yt(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,i)=>{var r,o,a,c,d,m;return[...(r=(o=t[0])==null?void 0:o.headers)!=null?r:[],...(a=(c=n[0])==null?void 0:c.headers)!=null?a:[],...(d=(m=i[0])==null?void 0:m.headers)!=null?d:[]].map(h=>h.getLeafHeaders()).flat()},xt(e.options,Oi))}};function gf(e,t,n,i){var r,o;let a=0;const c=function(g,x){x===void 0&&(x=1),a=Math.max(a,x),g.filter(v=>v.getIsVisible()).forEach(v=>{var _;(_=v.columns)!=null&&_.length&&c(v.columns,x+1)},0)};c(e);let d=[];const m=(g,x)=>{const v={depth:x,id:[i,`${x}`].filter(Boolean).jo Line truncated
`).replace(` `).replace(`
`,` `,`
+`).split(` +`).split(`
`)),h=m.reduce((p,g)=>p.concat(...g),[]);return[m,h]}return[[],[]]},[e]);return C.useEffect(()=>{const d=t?.target??y2,m=t?.actInsideInputWithModifier??!0;if(e!==null){const h=x=>{if(r.current=x.ctrlKey||x.metaKey||x.shiftKey||x.altKey,(!r.current||r.current&&!m)&&$T(x))return!1;const b=v2(x.code,c);if(o.current.add(x[b]),x2(a,o.current,!1)){const k=x.composedPath?.()?.[0]||x.target,w=k?.nodeName==="BUTTON"||k?.nodeName==="A";t.preventDefault!==!1&&(r.current||!w)&&x.preventDefault(),i(!0)}},p=x=>{const v=v2(x.code,c);x2(a,o.current,!0)?(i(!1),o.current.clear()):o.current.delete(x[v]),x.key==="Meta"&&o.current.clear(),r.current=!1},g=()=>{o.current.clear(),i(!1)};return d?.addEventListener("keydown",h),d?.addEventListener("keyup",p),window.addEventListener("blur",g),window.addEventListener("contextmenu",g),()=>{d?.removeEventListener("keydown",h),d?.removeEventListener("keyup",p),window.removeEventListener("blur",g),window.removeEventListener("contextmenu",g)}}},[e,i]),n}function x2(e,t,n){return e.filter(i=>n||i.length===t.size).some(i=>i.every(r=>t.has(r)))}function v2(e,t){return t.includes(e)?"code":"key"}const uK=()=>{const e=$n();return C.useMemo(()=>({zoomIn:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1.2,t):Promise.resolve(!1)},zoomOut:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1/1.2,t):Promise.resolve(!1)},zoomTo:(t,n)=>{const{panZoom:i}=e.getState();return i?i.scaleTo(t,n):Promise.resolve(!1)},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{const{transform:[i,r,o],panZoom:a}=e.getState();return a?(await a.setViewport({x:t.x??i,y:t.y??r,zoom:t.zoom??o},n),Promise.resolve(!0)):Promise.resolve(!1)},getViewport:()=>{const[t,n,i]=e.getState().transform;return{x:t,y:n,zoom:i}},setCenter:async(t,n,i)=>e.getState().setCenter(t,n,i),fitBounds:async(t,n)=>{const{width:i,height:r,minZoom:o,maxZoom:a,panZoom:c}=e.getState(),d=P0(t,i,r,o,a,n?.padding??.1);return c?(await c.setViewport(d,{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),Promise.resolve(!0)):Promise.resolve(!1)},screenToFlowPosition:(t,n={})=>{const{transform:i,snapGrid:r,snapToGrid:o,domNode:a}=e.getState();if(!a)return t;const{x:c,y:d}=a.getBoundingClientRect(),m={x:t.x-c,y:t.y-d},h=n.snapGrid??r,p=n.snapToGrid??o;return Xu(m,i,p,h)},flowToScreenPosition:t=>{const{transform:n,domNode:i}=e.getState();if(!i)return t;const{x:r,y:o}=i.getBoundingClientRect(),a=Cm(t,n);return{x:a.x+r,y:a.y+o}}}),[])};function lR(e,t){const n=[],i=new Map,r=[];for(const o of e)if(o.type==="add"){r.push(o);continue}else if(o.type==="remove"||o.type==="replace")i.set(o.id,[o]);else{const a=i.get(o.id);a?a.push(o):i.set(o.id,[o])}for(const o of t){const a=i.get(o.id);if(!a){n.push(o);continue}if(a[0].type==="remove")continue;if(a[0].type==="replace"){n.push({...a[0].item});continue}const c={...o};for(const d of a)dK(d,c);n.push(c)}return r.length&&r.forEach(o=>{o.index!==void 0?n.splice(o.index,0,{...o.item}):n.push({...o.item})}),n}function dK(e,t){switch(e.type){case"select":{t.selected=e.selected;break}case"position":{typeof e.position<"u"&&(t.position=e.position),typeof e.dragging<"u"&&(t.dragging=e.dragging);break}case"dimensions":{typeof e.dimensions<"u"&&(t.measured={...e.dimensions},e.setAttributes&&((e.setAttributes===!0||e.setAttributes==="width")&&(t.width=e.dimensions.width),(e.setAttributes===!0||e.setAttributes==="height")&&(t.height=e.dimensions.height))),typeof e.resizing=="boolean"&&(t.resizing=e.resizing);break}}}function cR(e,t){return lR(e,t)}function fK(e,t){return lR(e,t)}function ta(e,t){return{id:e,type:"select",selected:t}}function dl(e,t=new Set,n=!1){const i=[];for(const[r,o]of e){const a=t.has(r);!(o.selected===void 0&&!a)&&o.selected!==a&&(n&&(o.selected=a),i.push(ta(o.id,a)))}return i}function b2({items:e=[],lookup:t}){const n=[],i=new Map(e.map(r=>[r.id,r]));for(const[r,o]of e.entries()){const a=t.get(o.id),c=a?.internals?.userNode??a;c!==void 0&&c!==o&&n.push({id:o.id,item:o,type:"replace"}),c===void 0&&n.push({item:o,type:"add",index:r})}for(const[r]of t)i.get(r)===void 0&&n.push({id:r,type:"remove"});return n}function _2(e){return{id:e.id,type:"remove"}}const k2=e=>OY(e),mK=e=>AT(e);function uR(e){return C.forwardRef(e)}function S2(e){const[t,n]=C.useState(BigInt(0)),[i]=C.useState(()=>pK(()=>n(r=>r+BigInt(1))));return Nv(()=>{const r=i.get();r.length&&(e(r),i.reset())},[t]),i}function pK(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}const dR=C.createContext(null);function hK({children:e}){const t=$n(),n=C.useCallback(c=>{const{nodes:d=[],setNodes:m,hasDefaultNodes:h,onNodesChange:p,nodeLookup:g,fitViewQueued:x,onNodesChangeMiddlewareMap:v}=t.getState();let b=d;for(const w of c)b=typeof w=="function"?w(b):w;let k=b2({items:b,lookup:g});for(const w of v.values())k=w(k);h&&m(b),k.length>0?p?.(k):x&&window.requestAnimationFrame(()=>{const{fitViewQueued:w,nodes:S,setNodes:j}=t.getState();w&&j(S)})},[]),i=S2(n),r=C.useCallback(c=>{const{edges:d=[],setEdges:m,hasDefaul Line truncated `)),h=m.reduce((p,g)=>p.concat(...g),[]);return[m,h]}return[[],[]]},[e]);return C.useEffect(()=>{const d=t?.target??j2,m=t?.actInsideInputWithModifier??!0;if(e!==null){const h=x=>{if(r.current=x.ctrlKey||x.metaKey||x.shiftKey||x.altKey,(!r.current||r.current&&!m)&&XT(x))return!1;const _=N2(x.code,c);if(o.current.add(x[_]),E2(a,o.current,!1)){const k=x.composedPath?.()?.[0]||x.target,w=k?.nodeName==="BUTTON"||k?.nodeName==="A";t.preventDefault!==!1&&(r.current||!w)&&x.preventDefault(),i(!0)}},p=x=>{const v=N2(x.code,c);E2(a,o.current,!0)?(i(!1),o.current.clear()):o.current.delete(x[v]),x.key==="Meta"&&o.current.clear(),r.current=!1},g=()=>{o.current.clear(),i(!1)};return d?.addEventListener("keydown",h),d?.addEventListener("keyup",p),window.addEventListener("blur",g),window.addEventListener("contextmenu",g),()=>{d?.removeEventListener("keydown",h),d?.removeEventListener("keyup",p),window.removeEventListener("blur",g),window.removeEventListener("contextmenu",g)}}},[e,i]),n}function E2(e,t,n){return e.filter(i=>n||i.length===t.size).some(i=>i.every(r=>t.has(r)))}function N2(e,t){return t.includes(e)?"code":"key"}const _K=()=>{const e=$n();return C.useMemo(()=>({zoomIn:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1.2,t):Promise.resolve(!1)},zoomOut:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1/1.2,t):Promise.resolve(!1)},zoomTo:(t,n)=>{const{panZoom:i}=e.getState();return i?i.scaleTo(t,n):Promise.resolve(!1)},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{const{transform:[i,r,o],panZoom:a}=e.getState();return a?(await a.setViewport({x:t.x??i,y:t.y??r,zoom:t.zoom??o},n),Promise.resolve(!0)):Promise.resolve(!1)},getViewport:()=>{const[t,n,i]=e.getState().transform;return{x:t,y:n,zoom:i}},setCenter:async(t,n,i)=>e.getState().setCenter(t,n,i),fitBounds:async(t,n)=>{const{width:i,height:r,minZoom:o,maxZoom:a,panZoom:c}=e.getState(),d=U0(t,i,r,o,a,n?.padding??.1);return c?(await c.setViewport(d,{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),Promise.resolve(!0)):Promise.resolve(!1)},screenToFlowPosition:(t,n={})=>{const{transform:i,snapGrid:r,snapToGrid:o,domNode:a}=e.getState();if(!a)return t;const{x:c,y:d}=a.getBoundingClientRect(),m={x:t.x-c,y:t.y-d},h=n.snapGrid??r,p=n.snapToGrid??o;return Yu(m,i,p,h)},flowToScreenPosition:t=>{const{transform:n,domNode:i}=e.getState();if(!i)return t;const{x:r,y:o}=i.getBoundingClientRect(),a=wm(t,n);return{x:a.x+r,y:a.y+o}}}),[])};function yR(e,t){const n=[],i=new Map,r=[];for(const o of e)if(o.type==="add"){r.push(o);continue}else if(o.type==="remove"||o.type==="replace")i.set(o.id,[o]);else{const a=i.get(o.id);a?a.push(o):i.set(o.id,[o])}for(const o of t){const a=i.get(o.id);if(!a){n.push(o);continue}if(a[0].type==="remove")continue;if(a[0].type==="replace"){n.push({...a[0].item});continue}const c={...o};for(const d of a)kK(d,c);n.push(c)}return r.length&&r.forEach(o=>{o.index!==void 0?n.splice(o.index,0,{...o.item}):n.push({...o.item})}),n}function kK(e,t){switch(e.type){case"select":{t.selected=e.selected;break}case"position":{typeof e.position<"u"&&(t.position=e.position),typeof e.dragging<"u"&&(t.dragging=e.dragging);break}case"dimensions":{typeof e.dimensions<"u"&&(t.measured={...e.dimensions},e.setAttributes&&((e.setAttributes===!0||e.setAttributes==="width")&&(t.width=e.dimensions.width),(e.setAttributes===!0||e.setAttributes==="height")&&(t.height=e.dimensions.height))),typeof e.resizing=="boolean"&&(t.resizing=e.resizing);break}}}function xR(e,t){return yR(e,t)}function SK(e,t){return yR(e,t)}function ta(e,t){return{id:e,type:"select",selected:t}}function dl(e,t=new Set,n=!1){const i=[];for(const[r,o]of e){const a=t.has(r);!(o.selected===void 0&&!a)&&o.selected!==a&&(n&&(o.selected=a),i.push(ta(o.id,a)))}return i}function I2({items:e=[],lookup:t}){const n=[],i=new Map(e.map(r=>[r.id,r]));for(const[r,o]of e.entries()){const a=t.get(o.id),c=a?.internals?.userNode??a;c!==void 0&&c!==o&&n.push({id:o.id,item:o,type:"replace"}),c===void 0&&n.push({item:o,type:"add",index:r})}for(const[r]of t)i.get(r)===void 0&&n.push({id:r,type:"remove"});return n}function T2(e){return{id:e.id,type:"remove"}}const R2=e=>qY(e),wK=e=>HT(e);function vR(e){return C.forwardRef(e)}function A2(e){const[t,n]=C.useState(BigInt(0)),[i]=C.useState(()=>CK(()=>n(r=>r+BigInt(1))));return Mv(()=>{const r=i.get();r.length&&(e(r),i.reset())},[t]),i}function CK(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}const bR=C.createContext(null);function jK({children:e}){const t=$n(),n=C.useCallback(c=>{const{nodes:d=[],setNodes:m,hasDefaultNodes:h,onNodesChange:p,nodeLookup:g,fitViewQueued:x,onNodesChangeMiddlewareMap:v}=t.getState();let _=d;for(const w of c)_=typeof w=="function"?w(_):w;let k=I2({items:_,lookup:g});for(const w of v.values())k=w(k);h&&m(_),k.length>0?p?.(k):x&&window.requestAnimationFrame(()=>{const{fitViewQueued:w,nodes:S,setNodes:j}=t.getState();w&&j(S)})},[]),i=A2(n),r=C.useCallback(c=>{const{edges:d=[],setEdges:m,hasDefaul Line truncated
M${I.x},${I.y}h${I.width}v${I.height}h${-I.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}zR.displayName="MiniMap";const nQ=C.memo(zR),iQ=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,rQ={[Bl.Line]:"right",[Bl.Handle]:"bottom-right"};function sQ({nodeId:e,position:t,variant:n=Bl.Handle,className:i,style:r=void 0,children:o,color:a,minWidth:c=10,minHeight:d=10,maxWidth:m=Number.MAX_VALUE,maxHeight:h=Number.MAX_VALUE,keepAspectRatio:p=!1,resizeDirection:g,autoScale:x=!0,shouldResize:v,onResizeStart:b,onResize:k,onResizeEnd:w}){const S=pR(),j=typeof e=="string"?e:S,N=$n(),O=C.useRef(null),R=n===Bl.Handle,D=sn(C.useCallback(iQ(R&&x),[R,x]),Bn),I=C.useRef(null),L=t??rQ[n];C.useEffect(()=>{if(!(!O.current||!j))return I.current||(I.current=MX({domNode:O.current,nodeId:j,getStoreItems:()=>{const{nodeLookup:A,transform:B,snapGrid:W,snapToGrid:P,nodeOrigin:G,domNode:$}=N.getState();return{nodeLookup:A,transform:B,snapGrid:W,snapToGrid:P,nodeOrigin:G,paneDomNode:$}},onChange:(A,B)=>{const{triggerNodeChanges:W,nodeLookup:P,parentLookup:G,nodeOrigin:$}=N.getState(),q=[],Y={x:A.x,y:A.y},Q=P.get(j);if(Q&&Q.expandParent&&Q.parentId){const V=Q.origin??$,U=A.width??Q.measured.width??0,Z=A.height??Q.measured.height??0,F={id:Q.id,parentId:Q.parentId,rect:{width:U,height:Z,...PT({x:A.x??Q.position.x,y:A.y??Q.position.y},{width:U,height:Z},Q.parentId,P,V)}},K=U0([F],P,G,$);q.push(...K),Y.x=A.x?Math.max(V[0]*U,A.x):void 0,Y.y=A.y?Math.max(V[1]*Z,A.y):void 0}if(Y.x!==void 0&&Y.y!==void 0){const V={id:j,type:"position",position:{...Y}};q.push(V)}if(A.width!==void 0&&A.height!==void 0){const U={id:j,type:"dimensions",resizing:!0,setAttributes:g?g==="horizontal"?"width":"height":!0,dimensions:{width:A.width,height:A.height}};q.push(U)}for(const V of B){const U={...V,type:"position"};q.push(U)}W(q)},onEnd:({width:A,height:B})=>{const W={id:j,type:"dimensions",resizing:!1,dimensions:{width:A,height:B}};N.getState().triggerNodeChanges([W])}})),I.current.update({controlPosition:L,boundaries:{minWidth:c,minHeight:d,maxWidth:m,maxHeight:h},keepAspectRatio:p,resizeDirection:g,onResizeStart:b,onResize:k,onResizeEnd:w,shouldResize:v}),()=>{I.current?.destroy()}},[L,c,d,m,h,p,b,k,w,v]);const M=L.split("-");return u.jsx("div",{className:di(["react-flow__resize-control","nodrag",...M,n,i]),ref:O,style:{...r,scale:D,...a&&{[R?"backgroundColor":"borderColor"]:a}},children:o})}C.memo(sQ);const oQ=C.memo(function({data:t}){const n=["oc-canvas-node",t.isOwner&&"is-owner",t.isSelected&&"is-selected",t.isDropTarget&&"is-drop-target"].filter(Boolean).join(" "),i=Vu(t.icon);return u.jsxs("div",{className:n,children:[u.jsx($l,{type:"target",position:st.Top,className:"oc-canvas-handle"}),u.jsxs("div",{className:"oc-canvas-node-row",children:[u.jsx("div",{className:"oc-canvas-node-chip",children:u.jsx("span",{className:"oc-canvas-node-chip-icon",style:{WebkitMaskImage:`url("${i}")`,maskImage:`url("${i}")`},"aria-hidden":!0})}),u.jsxs("div",{className:"oc-canvas-node-text",children:[u.jsx("span",{className:"oc-canvas-node-name",children:t.name}),u.jsxs("div",{className:"oc-canvas-node-meta",children:[t.employeeNames.length>0?u.jsxs("span",{className:"oc-canvas-node-person",title:t.employeeNames.join(", "),children:[t.employeeNames[0],t.employeeNames.length>1?` +${t.employeeNames.length-1}`:""]}):u.jsx("span",{className:"oc-canvas-node-id",children:t.roleId}),t.employeeCount>0&&u.jsx("span",{className:"oc-canvas-node-badge",children:t.employeeCount})]})]})]}),u.jsx($l,{type:"source",position:st.Bottom,className:"oc-canvas-handle"})]})});var zy,O2;function W0(){if(O2)return zy;O2=1;var e="\0",t="\0",n="";class i{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>{};_defaultEdgeLabelFn=()=>{};_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(h){h&&(this._isDirected=Object.hasOwn(h,"directed")?h.directed:!0,this._isMultigraph=Object.hasOwn(h,"multigraph")?h.multigraph:!1,this._isCompound=Object.hasOwn(h,"compound")?h.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[t]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(h){return this._label=h,this}graph(){return this._label}setDefaultNodeLabel(h){return this._defaultNodeLabelFn=h,typeof h!="function"&&(this._defaultNodeLabelFn=()=>h),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var h=this;return this.nodes().filter(p=>Object.keys(h._in[p]).length===0)}sinks(){var h=this;return this.nodes().filter(p=>Object.keys(h._out[p]).length===0)}setNodes(h,p){var g=arguments,x=this;return h.forEach(function(v){g.length>1?x.setNode(v,p):x.setNode(v)}),this}setNode(h,p){return Object.hasOwn(this._nodes,h)?(arguments.length>1&&(this._nodes[h]=p),this):(this._nodes[h]=arguments.length>1?p:this._defaultNodeLabelFn(h),this._isCompound&&(this._parent[h]=t, Line truncated M${I.x},${I.y}h${I.width}v${I.height}h${-I.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}qR.displayName="MiniMap";const mQ=C.memo(qR),pQ=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,hQ={[Pl.Line]:"right",[Pl.Handle]:"bottom-right"};function gQ({nodeId:e,position:t,variant:n=Pl.Handle,className:i,style:r=void 0,children:o,color:a,minWidth:c=10,minHeight:d=10,maxWidth:m=Number.MAX_VALUE,maxHeight:h=Number.MAX_VALUE,keepAspectRatio:p=!1,resizeDirection:g,autoScale:x=!0,shouldResize:v,onResizeStart:_,onResize:k,onResizeEnd:w}){const S=SR(),j=typeof e=="string"?e:S,N=$n(),O=C.useRef(null),R=n===Pl.Handle,D=on(C.useCallback(pQ(R&&x),[R,x]),Bn),I=C.useRef(null),L=t??hQ[n];C.useEffect(()=>{if(!(!O.current||!j))return I.current||(I.current=UX({domNode:O.current,nodeId:j,getStoreItems:()=>{const{nodeLookup:A,transform:B,snapGrid:W,snapToGrid:P,nodeOrigin:G,domNode:$}=N.getState();return{nodeLookup:A,transform:B,snapGrid:W,snapToGrid:P,nodeOrigin:G,paneDomNode:$}},onChange:(A,B)=>{const{triggerNodeChanges:W,nodeLookup:P,parentLookup:G,nodeOrigin:$}=N.getState(),q=[],Y={x:A.x,y:A.y},Q=P.get(j);if(Q&&Q.expandParent&&Q.parentId){const V=Q.origin??$,U=A.width??Q.measured.width??0,Z=A.height??Q.measured.height??0,F={id:Q.id,parentId:Q.parentId,rect:{width:U,height:Z,...WT({x:A.x??Q.position.x,y:A.y??Q.position.y},{width:U,height:Z},Q.parentId,P,V)}},K=K0([F],P,G,$);q.push(...K),Y.x=A.x?Math.max(V[0]*U,A.x):void 0,Y.y=A.y?Math.max(V[1]*Z,A.y):void 0}if(Y.x!==void 0&&Y.y!==void 0){const V={id:j,type:"position",position:{...Y}};q.push(V)}if(A.width!==void 0&&A.height!==void 0){const U={id:j,type:"dimensions",resizing:!0,setAttributes:g?g==="horizontal"?"width":"height":!0,dimensions:{width:A.width,height:A.height}};q.push(U)}for(const V of B){const U={...V,type:"position"};q.push(U)}W(q)},onEnd:({width:A,height:B})=>{const W={id:j,type:"dimensions",resizing:!1,dimensions:{width:A,height:B}};N.getState().triggerNodeChanges([W])}})),I.current.update({controlPosition:L,boundaries:{minWidth:c,minHeight:d,maxWidth:m,maxHeight:h},keepAspectRatio:p,resizeDirection:g,onResizeStart:_,onResize:k,onResizeEnd:w,shouldResize:v}),()=>{I.current?.destroy()}},[L,c,d,m,h,p,_,k,w,v]);const M=L.split("-");return u.jsx("div",{className:fi(["react-flow__resize-control","nodrag",...M,n,i]),ref:O,style:{...r,scale:D,...a&&{[R?"backgroundColor":"borderColor"]:a}},children:o})}C.memo(gQ);const yQ=C.memo(function({data:t}){const n=["oc-canvas-node",t.isOwner&&"is-owner",t.isSelected&&"is-selected",t.isDropTarget&&"is-drop-target"].filter(Boolean).join(" "),i=Fu(t.icon);return u.jsxs("div",{className:n,children:[u.jsx(Bl,{type:"target",position:st.Top,className:"oc-canvas-handle"}),u.jsxs("div",{className:"oc-canvas-node-row",children:[u.jsx("div",{className:"oc-canvas-node-chip",children:u.jsx("span",{className:"oc-canvas-node-chip-icon",style:{WebkitMaskImage:`url("${i}")`,maskImage:`url("${i}")`},"aria-hidden":!0})}),u.jsxs("div",{className:"oc-canvas-node-text",children:[u.jsx("span",{className:"oc-canvas-node-name",children:t.name}),u.jsxs("div",{className:"oc-canvas-node-meta",children:[t.employeeNames.length>0?u.jsxs("span",{className:"oc-canvas-node-person",title:t.employeeNames.join(", "),children:[t.employeeNames[0],t.employeeNames.length>1?` +${t.employeeNames.length-1}`:""]}):u.jsx("span",{className:"oc-canvas-node-id",children:t.roleId}),t.employeeCount>0&&u.jsx("span",{className:"oc-canvas-node-badge",children:t.employeeCount})]})]})]}),u.jsx(Bl,{type:"source",position:st.Bottom,className:"oc-canvas-handle"})]})});var By,U2;function J0(){if(U2)return By;U2=1;var e="\0",t="\0",n="";class i{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>{};_defaultEdgeLabelFn=()=>{};_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(h){h&&(this._isDirected=Object.hasOwn(h,"directed")?h.directed:!0,this._isMultigraph=Object.hasOwn(h,"multigraph")?h.multigraph:!1,this._isCompound=Object.hasOwn(h,"compound")?h.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[t]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(h){return this._label=h,this}graph(){return this._label}setDefaultNodeLabel(h){return this._defaultNodeLabelFn=h,typeof h!="function"&&(this._defaultNodeLabelFn=()=>h),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var h=this;return this.nodes().filter(p=>Object.keys(h._in[p]).length===0)}sinks(){var h=this;return this.nodes().filter(p=>Object.keys(h._out[p]).length===0)}setNodes(h,p){var g=arguments,x=this;return h.forEach(function(v){g.length>1?x.setNode(v,p):x.setNode(v)}),this}setNode(h,p){return Object.hasOwn(this._nodes,h)?(arguments.length>1&&(this._nodes[h]=p),this):(this._nodes[h]=arguments.length>1?p:this._defaultNodeLabelFn(h),this._isCompound&&(this._parent[h]=t, Line truncated
${i}`}),u.jsx(qV,{projects:Se.projects,activeId:Se.activeProjectId,onSelect:J=>{const z=_t(J);t.current?.switchProject(J,z)},onCreate:J=>{t.current?.createProject(J)},onDelete:J=>t.current?.deleteProject(J)})]}),u.jsxs("div",{className:"topbar-center",children:[u.jsxs("div",{className:"page-nav",children:[u.jsxs("button",{className:`page-nav-btn${B==="workspace"?" active":""}`,onClick:()=>W("workspace"),children:["Workspace",(()=>{const J=Pt.channels.reduce((z,ne)=>z+Pt.getUnreadCount(ne.id),0);return J>0?u.jsx("span",{className:"nav-unread-badge",children:J>99?"99+":J}):null})()]}),u.jsx("button",{className:`page-nav-btn${B==="office"?" active":""}`,onClick:()=>W("office"),children:"Office"}),u.jsx("button",{className:`page-nav-btn${B==="org"?" active":""}`,onClick:()=>W("org"),children:"Org"})]}),u.jsxs("div",{className:"stat-chips",children:[u.jsxs("span",{className:"stat-chip",children:[u.jsx("b",{children:ds.totalAgents})," agents"]}),u.jsxs("span",{className:"stat-chip",children:[u.jsx("b",{children:ds.totalSkills})," skills"]}),u.jsxs("span",{className:"stat-chip",children:[u.jsx("b",{children:on.getOpenTaskCount()})," tasks"]})]})]}),u.jsxs("div",{className:"topbar-right",children:[u.jsxs("select",{className:"theme-select",value:Zt,title:"Outdoor lighting override",onChange:J=>{const z=J.target.value;Un(z);try{z==="auto"?(localStorage.removeItem("opc_outdoor_override"),localStorage.removeItem("opc_outdoor_day"),localStorage.removeItem("opc_outdoor_night")):(localStorage.setItem("opc_outdoor_override",z),localStorage.removeItem("opc_outdoor_day"),localStorage.removeItem("opc_outdoor_night"))}catch{}e.current.syncOutdoorLighting()},children:[u.jsx("option",{value:"auto",children:"Outdoor auto"}),u.jsx("option",{value:"day",children:"Outdoor day"}),u.jsx("option",{value:"night",children:"Outdoor night"})]}),u.jsxs("select",{className:"theme-select",value:j,onChange:J=>N(J.target.value),children:[u.jsx("option",{value:"midnight",children:"Midnight"}),u.jsx("option",{value:"neon",children:"Neon"}),u.jsx("option",{value:"paper",children:"Paper"}),u.jsx("option",{value:"retro",children:"Retro"}),u.jsx("option",{value:"terminal",children:"Terminal"}),u.jsx("option",{value:"cozy",children:"Cozy"}),u.jsx("option",{value:"openopc",children:"OpenOPC"})]}),u.jsx("button",{className:`icon-btn ${$?"active":""}`,onClick:()=>q(J=>!J),title:"Developer Tools",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[u.jsx("path",{d:"M5.5 2L2 5.5 5.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),u.jsx("path",{d:"M10.5 7L14 10.5 10.5 14",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})]}),B==="workspace"&&u.jsx(hV,{boardStore:on,chatStore:Pt,sessionStore:ce,agents:P,officeMap:Ku,execMode:V,companyProfile:Z,taskPreferredAgent:K,projectId:Se.activeProjectId,orgInfoData:te,onNavigateToOrg:()=>W("org"),savedOrgsList:We,activeSavedOrg:pt,onSavedOrgsList:gn,onSavedOrgLoad:ma,commsState:ae,commsMessage:ie,onCommsRefresh:J=>{const{project_id:z,...ne}=J??{};t.current?.commsState(Je(),ne)},onCommsReadMessage:J=>t.current?.commsReadMessage(Je(),J),onRunTask:(J,z,ne,oe,pe)=>{t.current?.send({type:"run_task",project_id:Je(),task_id:J,title:z,description:ne,mode:oe,profile:pe})},onCreateTask:(J,z,ne,oe)=>{t.current?.send({type:"kanban_create_task",project_id:Je(),title:J,board_id:z,column_id:ne,task_id:oe})},onMoveTask:(J,z)=>{t.current?.send({type:"kanban_move_task",project_id:Je(),task_id:J,column_id:z})},onCreateSession:()=>{if(pn.current||wn.current)return;const J=Je();ut(J),t.current?.createSession(J,void 0,V,Ax(V),K,Qo(V,pt))},onSessionSend:(J,z,ne,oe)=>t.current?.sessionSend(Je(),J,z,ne,oe),onSecretarySend:J=>t.current?.secretarySend(Je(),J),onDeleteSession:J=>t.current?.deleteSession(Je(),J),onTitleChange:(J,z)=>t.current?.sessionUpdateTitle(Je(),J,z),onSessionConfigChange:Ao,onSessionTaskAgentChange:fp,onContinueInNewChat:Xl,onSessionStop:Mo,onSessionResume:ya,onSessionComplete:J=>t.current?.sessionComplete(Je(),J),onLoadSessionDetail:(J,z)=>{const ne=t.current;if(ne)return ne.sessionDetail(Je(),J,{...z,include:z?.detailLevel==="full"?["messages","session_state","progress","work_items","runtime_context"]:["messages","session_state"],viewGeneration:tt.current}).then(oe=>{if(oe.ok===!1)throw new Error(String(oe.error??"session_detail failed"))})},onOpenExecutionPanel:J=>Tt(J),onCollabSync:()=>t.current?.collabSync(Je(),void 0,tt.current)}),B==="org"&&u.jsx("div",{className:"org-page",children:u.jsx(hJ,{data:te,sessionRecruitmentByRole:Ue,talents:je,employeeDetail:Ye,reorgProposals:Ft,isCustomMode:ms,onRequestData:()=>t.current?.orgInfo(),onRequestTalents:()=>t.current?.talentList(),onRequestEmployeeDetail:J=>t.current?.employeeDetail(J),onHireTalent:(J,z)=>{kt(J),t.current?.talentHire(J,z,void 0,te?.organization_id||pt||void 0)},hiringTemplateId:Re,onImportEmployee:J=>t.current?.importEmployeeAsAgent(J),onRe Line truncated ${i}`}),u.jsx(iU,{projects:Se.projects,activeId:Se.activeProjectId,onSelect:J=>{const z=_t(J);t.current?.switchProject(J,z)},onCreate:J=>{t.current?.createProject(J)},onDelete:J=>t.current?.deleteProject(J)})]}),u.jsxs("div",{className:"topbar-center",children:[u.jsxs("div",{className:"page-nav",children:[u.jsxs("button",{className:`page-nav-btn${B==="workspace"?" active":""}`,onClick:()=>W("workspace"),children:["Workspace",(()=>{const J=Bt.channels.reduce((z,ne)=>z+Bt.getUnreadCount(ne.id),0);return J>0?u.jsx("span",{className:"nav-unread-badge",children:J>99?"99+":J}):null})()]}),u.jsx("button",{className:`page-nav-btn${B==="office"?" active":""}`,onClick:()=>W("office"),children:"Office"}),u.jsx("button",{className:`page-nav-btn${B==="org"?" active":""}`,onClick:()=>W("org"),children:"Org"})]}),u.jsxs("div",{className:"stat-chips",children:[u.jsxs("span",{className:"stat-chip",children:[u.jsx("b",{children:us.totalAgents})," agents"]}),u.jsxs("span",{className:"stat-chip",children:[u.jsx("b",{children:us.totalSkills})," skills"]}),u.jsxs("span",{className:"stat-chip",children:[u.jsx("b",{children:an.getOpenTaskCount()})," tasks"]})]})]}),u.jsxs("div",{className:"topbar-right",children:[u.jsxs("select",{className:"theme-select",value:Xt,title:"Outdoor lighting override",onChange:J=>{const z=J.target.value;Un(z);try{z==="auto"?(localStorage.removeItem("opc_outdoor_override"),localStorage.removeItem("opc_outdoor_day"),localStorage.removeItem("opc_outdoor_night")):(localStorage.setItem("opc_outdoor_override",z),localStorage.removeItem("opc_outdoor_day"),localStorage.removeItem("opc_outdoor_night"))}catch{}e.current.syncOutdoorLighting()},children:[u.jsx("option",{value:"auto",children:"Outdoor auto"}),u.jsx("option",{value:"day",children:"Outdoor day"}),u.jsx("option",{value:"night",children:"Outdoor night"})]}),u.jsxs("select",{className:"theme-select",value:j,onChange:J=>N(J.target.value),children:[u.jsx("option",{value:"midnight",children:"Midnight"}),u.jsx("option",{value:"neon",children:"Neon"}),u.jsx("option",{value:"paper",children:"Paper"}),u.jsx("option",{value:"retro",children:"Retro"}),u.jsx("option",{value:"terminal",children:"Terminal"}),u.jsx("option",{value:"cozy",children:"Cozy"}),u.jsx("option",{value:"openopc",children:"OpenOPC"})]}),u.jsx("button",{className:`icon-btn ${$?"active":""}`,onClick:()=>q(J=>!J),title:"Developer Tools",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[u.jsx("path",{d:"M5.5 2L2 5.5 5.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),u.jsx("path",{d:"M10.5 7L14 10.5 10.5 14",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})]}),B==="workspace"&&u.jsx(CV,{boardStore:an,chatStore:Bt,sessionStore:ce,agents:P,officeMap:Xu,execMode:V,companyProfile:Z,taskPreferredAgent:K,projectId:Se.activeProjectId,orgInfoData:te,onNavigateToOrg:()=>W("org"),savedOrgsList:We,activeSavedOrg:ht,onSavedOrgsList:gn,onSavedOrgLoad:ha,commsState:ae,commsMessage:ie,onCommsRefresh:J=>{const{project_id:z,...ne}=J??{};t.current?.commsState(Je(),ne)},onCommsReadMessage:J=>t.current?.commsReadMessage(Je(),J),onRunTask:(J,z,ne,oe,pe)=>{t.current?.send({type:"run_task",project_id:Je(),task_id:J,title:z,description:ne,mode:oe,profile:pe})},onCreateTask:(J,z,ne,oe)=>{t.current?.send({type:"kanban_create_task",project_id:Je(),title:J,board_id:z,column_id:ne,task_id:oe})},onMoveTask:(J,z)=>{t.current?.send({type:"kanban_move_task",project_id:Je(),task_id:J,column_id:z})},onCreateSession:()=>{if(pn.current||wn.current)return;const J=Je();ut(J),t.current?.createSession(J,void 0,V,Dx(V),K,Qo(V,ht))},onSessionSend:(J,z,ne,oe)=>t.current?.sessionSend(Je(),J,z,ne,oe),onSecretarySend:J=>t.current?.secretarySend(Je(),J),onDeleteSession:J=>t.current?.deleteSession(Je(),J),onTitleChange:(J,z)=>t.current?.sessionUpdateTitle(Je(),J,z),onSessionConfigChange:Ao,onSessionTaskAgentChange:fp,onContinueInNewChat:Yl,onSessionStop:Mo,onSessionResume:va,onSessionComplete:J=>t.current?.sessionComplete(Je(),J),onLoadSessionDetail:(J,z)=>{const ne=t.current;if(ne)return ne.sessionDetail(Je(),J,{...z,include:z?.detailLevel==="full"?["messages","session_state","progress","work_items","runtime_context"]:["messages","session_state"],viewGeneration:tt.current}).then(oe=>{if(oe.ok===!1)throw new Error(String(oe.error??"session_detail failed"))})},onOpenExecutionPanel:J=>Tt(J),onCollabSync:()=>t.current?.collabSync(Je(),void 0,tt.current)}),B==="org"&&u.jsx("div",{className:"org-page",children:u.jsx(jJ,{data:te,sessionRecruitmentByRole:Ue,talents:je,employeeDetail:Xe,reorgProposals:Ft,isCustomMode:fs,onRequestData:()=>t.current?.orgInfo(),onRequestTalents:()=>t.current?.talentList(),onRequestEmployeeDetail:J=>t.current?.employeeDetail(J),onHireTalent:(J,z)=>{kt(J),t.current?.talentHire(J,z,void 0,te?.organization_id||ht||void 0)},hiringTemplateId:Re,onImportEmployee:J=>t.current?.importEmployeeAsAgent(J),onRe Line truncated
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="data:," /> <link rel="icon" href="data:," />
<title>OpenOPC Pixel Office</title> <title>OpenOPC Pixel Office</title>
<script type="module" crossorigin src="./assets/index-Cson66Y4.js"></script> <script type="module" crossorigin src="./assets/index-CTK-c7_K.js"></script>
<link rel="modulepreload" crossorigin href="./assets/phaser-DFK5Ua9d.js"> <link rel="modulepreload" crossorigin href="./assets/phaser-DFK5Ua9d.js">
<link rel="stylesheet" crossorigin href="./assets/index-DEvLDWDw.css"> <link rel="stylesheet" crossorigin href="./assets/index-DEvLDWDw.css">
</head> </head>
@@ -127,16 +127,37 @@ assert.match(
'runtime events carrying a non-empty tool_name must update stable displayTool (empty tool_name keeps the sticky last command)', 'runtime events carrying a non-empty tool_name must update stable displayTool (empty tool_name keeps the sticky last command)',
) )
// 8. Assistant streaming drafts must disappear at real terminal boundaries. // 8. A streaming draft is one mounted logical turn. Completion/checkpoint
// events cannot remove it before the matching persisted final is merged.
assert.match( assert.match(
src, src,
/evt\.type === 'turn_completed' \|\| evt\.type === 'turn_failed' \|\| evt\.type === 'checkpoint_saved'/, /const turnId = resolveCanonicalTurnId\(data\) \|\| undefined/,
'runtime terminal/checkpoint events must clear task-mode Live Reply drafts', 'runtime deltas must use the shared canonical-turn resolver',
) )
assert.match( assert.match(
src, src,
/detailHasFinalForDraft[\s\S]*runtime_v2_assistant[\s\S]*ss\.clearDraft\(detailTaskId\)/, /const startsNewCanonicalTurn = evt\.type === 'turn_started'[\s\S]*turnId !== activeDraftTurnId[\s\S]*evt\.type === 'turn_failed' \|\| startsNewCanonicalTurn/,
'session_detail backfill of the final runtime assistant turn must clear matching Live Reply drafts', 'only failure or a genuinely new canonical turn may clear an uncommitted draft',
)
assert.doesNotMatch(
src,
/evt\.type === 'turn_completed'[^\n]*clearDraft|evt\.type === 'checkpoint_saved'[^\n]*clearDraft/,
'turn completion and checkpoint persistence must not clear a draft ahead of its final message',
)
assert.match(
src,
/detailHasFinalForDraft[\s\S]*terminalAssistantTurnId\(message\) === draftTurnId[\s\S]*ss\.clearDraft\(detailTaskId\)/,
'session_detail may clear only after merging the matching terminal assistant turn',
)
assert.match(
src,
/cs\.addMessageFromBackend\(mapped\)[\s\S]*terminalTurnId = terminalAssistantTurnId\(mapped\)[\s\S]*terminalTurnId === activeDraftTurnId[\s\S]*clearDraft\(taskId\)/,
'session_message/chat_new_message must merge a matching terminal final before clearing its draft',
)
assert.doesNotMatch(
src,
/mapped\.sender !== 'user'\)\s*\{\s*sessionStoreRef\.current\?\.clearDraft/,
'an unrelated non-user session message must never clear an active draft',
) )
// 9. Summary/full pagination and transport-local failures have independent // 9. Summary/full pagination and transport-local failures have independent
+27 -19
View File
@@ -24,6 +24,7 @@ import { companyRuntimeControlPatchForBoardStatus } from './lib/sessionRuntime'
import { getExecutionTurnId } from './lib/workItemRuntimeIds' import { getExecutionTurnId } from './lib/workItemRuntimeIds'
import { normalizeSessionCompanyProfile, normalizeSessionExecMode } from './lib/sessionIdentity' import { normalizeSessionCompanyProfile, normalizeSessionExecMode } from './lib/sessionIdentity'
import { extractSessionRecruitmentByRole, sessionChannelId } from './lib/sessionRecruitment' import { extractSessionRecruitmentByRole, sessionChannelId } from './lib/sessionRecruitment'
import { resolveCanonicalTurnId, terminalAssistantTurnId } from './lib/turnIdentity'
import { unassignAgent } from './game/map/OfficeStore' import { unassignAgent } from './game/map/OfficeStore'
import type { AgentAnimStatus, EmployeeAssignment, KanbanPhase, KanbanTask, RoleAggregatedStatus, RoleWorkItemSummary, Session, TaskPreferredAgent } from './types/kanban' import type { AgentAnimStatus, EmployeeAssignment, KanbanPhase, KanbanTask, RoleAggregatedStatus, RoleWorkItemSummary, Session, TaskPreferredAgent } from './types/kanban'
@@ -919,9 +920,11 @@ export default function App() {
const taskId = typeof data.task_id === 'string' ? data.task_id : '' const taskId = typeof data.task_id === 'string' ? data.task_id : ''
if (taskId) { if (taskId) {
const isDeltaEvent = evt.type === 'assistant_delta' || evt.type === 'thinking_delta' const isDeltaEvent = evt.type === 'assistant_delta' || evt.type === 'thinking_delta'
const bufferedDraftTurnId = pendingDeltaFlushRef.current.get(taskId)?.draftTurnId
// Store-write ordering guarantee: everything buffered for this // Store-write ordering guarantee: everything buffered for this
// task lands before a non-delta event (turn boundaries call // task lands before a non-delta event. A matching terminal
// clearDraft; the draft must be flushed first, not after). // message replaces the draft later; flushing here must not make
// a completion boundary remove the visible turn prematurely.
if (!isDeltaEvent) flushPendingDeltas(taskId) if (!isDeltaEvent) flushPendingDeltas(taskId)
const ss = sessionStoreRef.current const ss = sessionStoreRef.current
const bs = boardStoreRef.current const bs = boardStoreRef.current
@@ -931,13 +934,10 @@ export default function App() {
: '' : ''
const executionMode = typeof data.execution_mode === 'string' ? data.execution_mode : '' const executionMode = typeof data.execution_mode === 'string' ? data.execution_mode : ''
const isTaskModeRuntime = executionMode === 'task_mode' || projectionId === 'task_mode_execution' const isTaskModeRuntime = executionMode === 'task_mode' || projectionId === 'task_mode_execution'
const turnId = typeof data.turn_id === 'string' && data.turn_id // Drafts represent one logical assistant turn. The shared
? data.turn_id // resolver deliberately prefers conversation identity over the
: typeof data.canonical_turn_id === 'string' && data.canonical_turn_id // iteration-scoped runtime turn id.
? data.canonical_turn_id const turnId = resolveCanonicalTurnId(data) || undefined
: typeof data.execution_turn_id === 'string' && data.execution_turn_id
? data.execution_turn_id
: undefined
const marksCompanyRuntime = const marksCompanyRuntime =
!!projectionId && projectionId !== 'task_mode_execution' && !isTaskModeRuntime !!projectionId && projectionId !== 'task_mode_execution' && !isTaskModeRuntime
if (marksCompanyRuntime && !isDeltaEvent && existingSession?.isCompanyRuntime !== true) { if (marksCompanyRuntime && !isDeltaEvent && existingSession?.isCompanyRuntime !== true) {
@@ -993,7 +993,14 @@ export default function App() {
entry.kanbanPatch = { ...entry.kanbanPatch, ...kanbanPatch } entry.kanbanPatch = { ...entry.kanbanPatch, ...kanbanPatch }
scheduleDeltaFlush() scheduleDeltaFlush()
} else { } else {
if (evt.type === 'turn_started' || evt.type === 'turn_completed' || evt.type === 'turn_failed' || evt.type === 'checkpoint_saved') { const activeDraftTurnId = String(
bufferedDraftTurnId ?? existingSession?.draftTurnId ?? '',
).trim()
const startsNewCanonicalTurn = evt.type === 'turn_started'
&& !!turnId
&& !!activeDraftTurnId
&& turnId !== activeDraftTurnId
if (evt.type === 'turn_failed' || startsNewCanonicalTurn) {
ss?.clearDraft(taskId) ss?.clearDraft(taskId)
} }
ss?.updateSession(taskId, runtimePartial) ss?.updateSession(taskId, runtimePartial)
@@ -1084,14 +1091,9 @@ export default function App() {
payload.client_history_page === true, payload.client_history_page === true,
) )
const draftTurnId = String(existingSession?.draftTurnId ?? '').trim() const draftTurnId = String(existingSession?.draftTurnId ?? '').trim()
const detailHasFinalForDraft = !!draftTurnId && detailMessages.some((message) => { const detailHasFinalForDraft = !!draftTurnId
if (message.sender === 'user') return false && !!cs
const metadata = message.metadata ?? {} && detailMessages.some(message => terminalAssistantTurnId(message) === draftTurnId)
const transcriptKind = String(metadata.transcript_kind ?? metadata.kind ?? '').trim()
if (transcriptKind !== 'runtime_v2_assistant') return false
const messageTurnId = String(metadata.canonical_turn_id ?? metadata.turn_id ?? '').trim()
return messageTurnId === draftTurnId
})
if (detailHasFinalForDraft) { if (detailHasFinalForDraft) {
ss.clearDraft(detailTaskId) ss.clearDraft(detailTaskId)
} }
@@ -1672,8 +1674,14 @@ export default function App() {
console.debug('[onSessionMessage]', mapped.sender, mapped.channelId, mapped.content?.slice(0, 60)) console.debug('[onSessionMessage]', mapped.sender, mapped.channelId, mapped.content?.slice(0, 60))
cs.addMessageFromBackend(mapped) cs.addMessageFromBackend(mapped)
const taskId = mapped.channelId.startsWith('session:') ? mapped.channelId.slice('session:'.length) : '' const taskId = mapped.channelId.startsWith('session:') ? mapped.channelId.slice('session:'.length) : ''
const terminalTurnId = terminalAssistantTurnId(mapped)
const activeDraftTurnId = String(
sessionStoreRef.current?.sessions.find(session => session.taskId === taskId)?.draftTurnId ?? '',
).trim()
if (taskId && mapped.sender !== 'user') { if (taskId && mapped.sender !== 'user') {
sessionStoreRef.current?.clearDraft(taskId) if (terminalTurnId && terminalTurnId === activeDraftTurnId) {
sessionStoreRef.current?.clearDraft(taskId)
}
// Force refresh — session messages are critical content that must sync // Force refresh — session messages are critical content that must sync
scheduleSessionDetailRefresh(taskId, 'full', true) scheduleSessionDetailRefresh(taskId, 'full', true)
} }
@@ -241,6 +241,153 @@ assert.equal(repeatedNativeCompanySync.length, 1)
assert.equal(repeatedNativeCompanySync[0].metadata?.ui_timeline_id, 'message:native-raw-1') assert.equal(repeatedNativeCompanySync[0].metadata?.ui_timeline_id, 'message:native-raw-1')
assert.equal(repeatedNativeCompanySync[0].timestamp, 5) assert.equal(repeatedNativeCompanySync[0].timestamp, 5)
const structuredDeliveryMerge = __chatStoreTestUtils.dedupeMessages([
{
...nativeCompanyRawTurn,
content: 'Raw runtime wording before the canonical result wrapper.',
metadata: {
...nativeCompanyRawTurn.metadata,
result_delivery_id: 'result:company-turn-1:attempt:0',
},
},
{
...companyRoleResult,
content: 'Canonical committed wording may differ without creating another row.',
metadata: {
...companyRoleResult.metadata,
result_delivery_id: 'result:company-turn-1:attempt:0',
},
},
])
assert.equal(structuredDeliveryMerge.length, 1)
assert.equal(structuredDeliveryMerge[0].id, 'role-result-1')
assert.equal(
structuredDeliveryMerge[0].content,
'Canonical committed wording may differ without creating another row.',
)
const deliveryMirrorWithLongerWrapper = __chatStoreTestUtils.dedupeMessages([
{
...nativeCompanyRawTurn,
content: 'Runtime wrapper that must not outrank the committed surface.\n\nCanonical result body.',
metadata: {
...nativeCompanyRawTurn.metadata,
result_delivery_id: 'result:company-turn-wrapper:attempt:0',
},
},
{
...companyRoleResult,
content: 'Canonical result body.',
metadata: {
...companyRoleResult.metadata,
result_delivery_id: 'result:company-turn-wrapper:attempt:0',
},
},
])
assert.equal(deliveryMirrorWithLongerWrapper.length, 1)
assert.equal(
deliveryMirrorWithLongerWrapper[0].content,
'Canonical result body.',
'delivery mirrors follow surface authority; suffix repair only applies to one persistent message id',
)
const ctoDispatchContent = `Both work items have been successfully dispatched to my senior engineer. Here's the status:
## Dispatch Summary
**Work Item 1: OpenOPC Source Code Architecture Deep-Dive Analysis**
- ID: \`1ed5f5f1-ac41-49a1-b1fa-23bbc9adab82\`
- Owner: senior_engineer
- Scope: \`openopc-source-analysis\`
- Output: \`/data2/bjdwhzzh/project-hku/OpenOPC_workplace/0009/openopc-architecture-analysis.md\`
- Covers: Layered architecture, the work-item state machine, collaboration policy, and seat executor mechanisms.
**Work Item 2: External Multi-Agent Frameworks Architecture Research**
- ID: \`d0307208-6b95-44c1-9b51-6bf073bbdcef\`
- Owner: senior_engineer
Both work items are independent and can execute in parallel.`
const ctoCompanyFinal: ChatMessage = {
id: 'runtime-v2-company-assistant-final:cto-turn-9',
channelId: 'session:cto-work-item',
sender: 'cto',
senderName: 'CTO',
content: ctoDispatchContent,
timestamp: 20,
mentions: [],
metadata: {
source: 'engine',
transcript_kind: 'runtime_v2_company_assistant',
canonical_turn_id: 'cto-turn-9',
ui_message_id: 'runtime-v2-company-assistant-final:cto-turn-9',
},
}
const repeatedCtoSnapshot = __chatStoreTestUtils.dedupeMessages([
ctoCompanyFinal,
{ ...ctoCompanyFinal, metadata: { ...ctoCompanyFinal.metadata } },
])
assert.equal(repeatedCtoSnapshot.length, 1)
assert.equal(
repeatedCtoSnapshot[0].content,
ctoDispatchContent,
'comparison normalization must never peel Work Item, ID, or Owner fields from rendered content',
)
let repeatedCtoMerge = [ctoCompanyFinal]
for (let replay = 0; replay < 6; replay += 1) {
repeatedCtoMerge = __chatStoreTestUtils.mergeMessagesIntoExisting(
repeatedCtoMerge,
[{ ...ctoCompanyFinal, metadata: { ...ctoCompanyFinal.metadata } }],
)
assert.equal(repeatedCtoMerge.length, 1)
assert.equal(
repeatedCtoMerge[0].content,
ctoDispatchContent,
`identical MERGE replay ${replay + 1} must preserve the complete source text`,
)
}
const truncatedCtoContent = ctoDispatchContent.slice(
ctoDispatchContent.indexOf('OpenOPC Source Code Architecture Deep-Dive Analysis**'),
)
const truncatedCtoFinal: ChatMessage = {
...ctoCompanyFinal,
content: truncatedCtoContent,
}
let interleavedCtoReplay = [ctoCompanyFinal]
for (const replayedMessage of [
truncatedCtoFinal,
ctoCompanyFinal,
truncatedCtoFinal,
ctoCompanyFinal,
]) {
interleavedCtoReplay = __chatStoreTestUtils.mergeMessagesIntoExisting(
interleavedCtoReplay,
[{ ...replayedMessage, metadata: { ...replayedMessage.metadata } }],
)
assert.equal(interleavedCtoReplay.length, 1)
assert.equal(
interleavedCtoReplay[0].content,
ctoDispatchContent,
'a same-identity truncated cache replay must neither replace nor duplicate the complete message',
)
}
const repairedCtoReplay = __chatStoreTestUtils.mergeMessagesIntoExisting(
[truncatedCtoFinal],
[ctoCompanyFinal],
)
assert.equal(repairedCtoReplay.length, 1)
assert.equal(repairedCtoReplay[0].content, ctoDispatchContent)
assert.equal(
__chatStoreTestUtils.mergeMessagesIntoExisting(repairedCtoReplay, [truncatedCtoFinal])[0].content,
ctoDispatchContent,
'once a complete same-identity source arrives, later truncated replays must not regress it',
)
const mountedHighPriorityResult: ChatMessage = { const mountedHighPriorityResult: ChatMessage = {
...companyRoleResult, ...companyRoleResult,
id: 'mounted-high-result', id: 'mounted-high-result',
@@ -23,8 +23,8 @@ function messageMetadata(message: ChatMessage): Record<string, unknown> {
return (message.metadata ?? {}) as Record<string, unknown> return (message.metadata ?? {}) as Record<string, unknown>
} }
function normalizeMessageContent(content: string): string { function normalizeMessageFormatting(content: string): string {
const normalized = String(content ?? '') return String(content ?? '')
.replace(/\r\n/g, '\n') .replace(/\r\n/g, '\n')
.replace(/\r/g, '\n') .replace(/\r/g, '\n')
.split('\n') .split('\n')
@@ -32,6 +32,10 @@ function normalizeMessageContent(content: string): string {
.join('\n') .join('\n')
.replace(/\n{3,}/g, '\n\n') .replace(/\n{3,}/g, '\n\n')
.trim() .trim()
}
function normalizeMessageContent(content: string): string {
const normalized = normalizeMessageFormatting(content)
const titleStripped = stripNarrativeTitlePrefix(normalized) const titleStripped = stripNarrativeTitlePrefix(normalized)
const paragraphs = titleStripped.split(/\n{2,}/).map(part => part.trim()).filter(Boolean) const paragraphs = titleStripped.split(/\n{2,}/).map(part => part.trim()).filter(Boolean)
if (paragraphs.length > 1 && /^Verification:\s/i.test(paragraphs[paragraphs.length - 1])) { if (paragraphs.length > 1 && /^Verification:\s/i.test(paragraphs[paragraphs.length - 1])) {
@@ -41,21 +45,40 @@ function normalizeMessageContent(content: string): string {
} }
function stripNarrativeTitlePrefix(content: string): string { function stripNarrativeTitlePrefix(content: string): string {
const trimmed = String(content || '').trim() let trimmed = String(content || '').trim()
const markdownTitle = trimmed.match(/^\*\*(.{8,160}?)\*\*:\s+([\s\S]+)$/) // Only an explicit, first-line "**Title**: body" wrapper is removable.
if (markdownTitle) { // Searching for an arbitrary `: ` in the first N characters is destructive:
// ordinary Markdown such as "**Work Item 1: ...**" and list fields such as
// "- ID: ..." would be peeled one layer at a time on repeated syncs.
for (;;) {
const markdownTitle = trimmed.match(/^\*\*([^\r\n]{8,160}?)\*\*:(?:[ \t]+|\r?\n+)([\s\S]+)$/)
if (!markdownTitle) return trimmed
const body = markdownTitle[2].trim() const body = markdownTitle[2].trim()
if (body.length >= 80) return body if (body.length < 80 || body === trimmed) return trimmed
trimmed = body
} }
const colonIndex = trimmed.indexOf(': ') }
if (colonIndex < 8 || colonIndex > 160) return trimmed
const prefix = trimmed.slice(0, colonIndex).replace(/\*/g, '').trim() function losslessIdentityContent(
const body = trimmed.slice(colonIndex + 2).trim() existing: ChatMessage,
if (body.length < 80) return trimmed candidate: ChatMessage,
if (!/[A-Za-z\u4e00-\u9fff]/.test(prefix)) return trimmed preferred: ChatMessage,
if (/^(https?|file)$/i.test(prefix)) return trimmed sharesConcreteIdentity: boolean,
return body ): string {
if (!sharesConcreteIdentity) return preferred.content
const existingComparable = normalizeMessageFormatting(existing.content)
const candidateComparable = normalizeMessageFormatting(candidate.content)
if (!existingComparable || !candidateComparable || existingComparable === candidateComparable) {
return preferred.content
}
// A cache/detail replay can contain a prefix-truncated copy of the same
// persistent message. Preserve the lossless source regardless of arrival
// order; unrelated edits still follow the normal preference rules.
if (existingComparable.endsWith(candidateComparable)) return existing.content
if (candidateComparable.endsWith(existingComparable)) return candidate.content
return preferred.content
} }
function messageIdentityKeys(message: ChatMessage): Set<string> { function messageIdentityKeys(message: ChatMessage): Set<string> {
@@ -66,6 +89,9 @@ function messageIdentityKeys(message: ChatMessage): Set<string> {
for (const value of [ for (const value of [
message.id, message.id,
typeof metadata.ui_message_id === 'string' ? metadata.ui_message_id : '', typeof metadata.ui_message_id === 'string' ? metadata.ui_message_id : '',
typeof metadata.result_delivery_id === 'string' && metadata.result_delivery_id.trim()
? `delivery:${metadata.result_delivery_id.trim()}`
: '',
checkpointType && checkpointId ? `checkpoint:${checkpointType}:${checkpointId}` : '', checkpointType && checkpointId ? `checkpoint:${checkpointType}:${checkpointId}` : '',
]) { ]) {
const normalized = String(value ?? '').trim() const normalized = String(value ?? '').trim()
@@ -81,7 +107,7 @@ function scopedMessageIdentityKeys(message: ChatMessage): Set<string> {
} }
function isDerivedIdentityKey(value: string): boolean { function isDerivedIdentityKey(value: string): boolean {
return value.startsWith('checkpoint:') return value.startsWith('checkpoint:') || value.startsWith('delivery:')
} }
function messageTimestamp(message: ChatMessage): number { function messageTimestamp(message: ChatMessage): number {
@@ -229,18 +255,17 @@ function mergeDuplicateMessages(
const existingIds = messageIdentityKeys(existing) const existingIds = messageIdentityKeys(existing)
const candidateIds = messageIdentityKeys(candidate) const candidateIds = messageIdentityKeys(candidate)
let sharesConcreteIdentity = false
let canonicalId = '' let canonicalId = ''
for (const id of existingIds) { for (const id of existingIds) {
if (candidateIds.has(id) && !isDerivedIdentityKey(id)) { if (!candidateIds.has(id)) continue
canonicalId = id if (!isDerivedIdentityKey(id)) {
break sharesConcreteIdentity = true
if (!canonicalId) canonicalId = id
} }
} }
const normalizedContent = normalizeMessageContent(preferred.content) const content = losslessIdentityContent(existing, candidate, preferred, sharesConcreteIdentity)
const content = normalizedContent && normalizedContent === normalizeMessageContent(secondary.content)
? normalizedContent
: preferred.content
const existingCheckpointId = String(messageMetadata(existing).checkpoint_id ?? '').trim() const existingCheckpointId = String(messageMetadata(existing).checkpoint_id ?? '').trim()
const candidateCheckpointId = String(messageMetadata(candidate).checkpoint_id ?? '').trim() const candidateCheckpointId = String(messageMetadata(candidate).checkpoint_id ?? '').trim()
@@ -17,6 +17,16 @@ assert.match(
assert.match(messageListSource, /scrollPolicy = 'follow'/, 'main transcript behavior should default to follow mode') assert.match(messageListSource, /scrollPolicy = 'follow'/, 'main transcript behavior should default to follow mode')
assert.doesNotMatch(messageListSource, /useVirtualizer/, 'chat transcript must use stable normal DOM rows') assert.doesNotMatch(messageListSource, /useVirtualizer/, 'chat transcript must use stable normal DOM rows')
assert.doesNotMatch(messageListSource, /PROGRAMMATIC_SCROLL_GRACE_MS/, 'scroll behavior must not regress to timer-based intent guessing') assert.doesNotMatch(messageListSource, /PROGRAMMATIC_SCROLL_GRACE_MS/, 'scroll behavior must not regress to timer-based intent guessing')
assert.doesNotMatch(
messageListSource,
/seenNarrativeMessages|seenProjectUpdates/,
'MessageList must not independently remove durable rows using rendered content',
)
assert.match(
messageListSource,
/terminalAssistantTurnId\(message\)/,
'draft suppression must use the shared committed-turn resolver',
)
const progressWithoutServerId = { const progressWithoutServerId = {
type: 'status_change' as const, type: 'status_change' as const,
@@ -147,7 +157,16 @@ const companyTurnKeys = [
metadata: { kind: 'company_role_result', canonical_turn_id: sharedCompanyTurn }, metadata: { kind: 'company_role_result', canonical_turn_id: sharedCompanyTurn },
}), }),
] ]
assert.equal(new Set(companyTurnKeys).size, companyTurnKeys.length, 'distinct company rows sharing a turn need unique DOM keys') assert.equal(
companyTurnKeys[1],
companyTurnKeys[2],
'company draft/final surfaces for one canonical turn must reuse the same DOM slot',
)
assert.notEqual(
companyTurnKeys[2],
companyTurnKeys[3],
'a separately committed role result keeps its result-delivery identity',
)
const narrativeItems = buildNarrativeMessageItems([ const narrativeItems = buildNarrativeMessageItems([
baseMessage('m1', '[Company:cto::execute::abc] starting Research source reliability', 1000), baseMessage('m1', '[Company:cto::execute::abc] starting Research source reliability', 1000),
@@ -163,35 +182,63 @@ assert.equal(narrativeItems[0].kind === 'ops-bundle' ? narrativeItems[0].events.
assert.equal(narrativeItems[1].kind, 'message') assert.equal(narrativeItems[1].kind, 'message')
assert.equal(narrativeItems[2].kind, 'ops-bundle') assert.equal(narrativeItems[2].kind, 'ops-bundle')
const longResult = 'Completed the focused recheck and produced the QA artifact with caveats for downstream aggregation.'
const dedupedProjectUpdates = buildNarrativeMessageItems([ const dedupedProjectUpdates = buildNarrativeMessageItems([
baseMessage('u1', prefixedPayload, 2000, 'qa_analyst'), baseMessage('u1', prefixedPayload, 2000, 'qa_analyst'),
baseMessage('u2', `**Report #1: Recheck remediated screen**: ${prefixedPayload}`, 2000, 'qa_analyst'), baseMessage('u2', `**Report #1: Recheck remediated screen**: ${prefixedPayload}`, 2000, 'qa_analyst'),
], { isCompanyRuntime: true, detailMode: 'summary' }) ], { isCompanyRuntime: true, detailMode: 'summary' })
assert.equal(dedupedProjectUpdates.length, 1) assert.equal(
dedupedProjectUpdates.length,
2,
'renderer must preserve distinct project-update rows; upstream identity owns consolidation',
)
assert.equal(dedupedProjectUpdates[0].kind, 'message') assert.equal(dedupedProjectUpdates[0].kind, 'message')
assert.equal(dedupedProjectUpdates[0].kind === 'message' ? dedupedProjectUpdates[0].msg.id : '', 'u1') assert.equal(dedupedProjectUpdates[0].kind === 'message' ? dedupedProjectUpdates[0].msg.id : '', 'u1')
const longResult = 'Completed the focused recheck and produced the QA artifact with caveats for downstream aggregation.' const identicalDurableNarratives = buildNarrativeMessageItems([
const dedupedNarrativeMessages = buildNarrativeMessageItems([ baseMessage('same-content-1', longResult, 2500, 'qa_analyst'),
baseMessage('same-content-2', longResult, 2500, 'qa_analyst'),
], { isCompanyRuntime: true, detailMode: 'summary' })
assert.deepEqual(
identicalDurableNarratives.map(item => item.kind === 'message' ? item.msg.id : item.id),
['same-content-1', 'same-content-2'],
'distinct stable identities must survive even when sender, timestamp, and content are identical',
)
const ambiguousNarrativeMessages = buildNarrativeMessageItems([
baseMessage('n1', longResult, 3000, 'qa_analyst'), baseMessage('n1', longResult, 3000, 'qa_analyst'),
baseMessage('n2', `Recheck remediated ten-bagger candidate screen: ${longResult}`, 3000, 'qa_analyst'), baseMessage('n2', `Recheck remediated ten-bagger candidate screen: ${longResult}`, 3000, 'qa_analyst'),
], { isCompanyRuntime: true, detailMode: 'summary' }) ], { isCompanyRuntime: true, detailMode: 'summary' })
assert.equal(dedupedNarrativeMessages.length, 1) assert.equal(
assert.equal(dedupedNarrativeMessages[0].kind === 'message' ? dedupedNarrativeMessages[0].msg.id : '', 'n1') ambiguousNarrativeMessages.length,
2,
'plain narrative prefixes are content and must not be stripped to guess message identity',
)
const duplicatedResultSurface = buildNarrativeMessageItems([ const duplicatedResultSurface = buildNarrativeMessageItems([
{ {
...baseMessage('r1', longResult, 4000, 'chao'), ...baseMessage('r1', longResult, 4000, 'chao'),
metadata: { source: 'engine', transcript_kind: 'child_task_result' }, metadata: {
source: 'engine',
transcript_kind: 'child_task_result',
result_delivery_id: 'delivery-r1',
},
}, },
{ {
...baseMessage('r2', `Deliver final result to user: ${longResult}`, 4500, 'system'), ...baseMessage('r2', `Deliver final result to user: ${longResult}`, 4500, 'system'),
senderName: 'Company Member', senderName: 'Company Member',
metadata: { source: 'runtime_event', kind: 'worker_notification', notification_kind: 'task_complete' }, metadata: {
source: 'engine',
transcript_kind: 'child_result',
result_delivery_id: 'delivery-r1',
},
}, },
], { isCompanyRuntime: true, detailMode: 'summary' }) ], { isCompanyRuntime: true, detailMode: 'summary' })
assert.equal(duplicatedResultSurface.length, 1) assert.equal(
assert.equal(duplicatedResultSurface[0].kind === 'message' ? duplicatedResultSurface[0].msg.id : '', 'r1') duplicatedResultSurface.length,
2,
'MessageList must not run a second result consolidator after the store/company projection',
)
const fullItems = buildNarrativeMessageItems([ const fullItems = buildNarrativeMessageItems([
baseMessage('m1', '[Company:cto::execute::abc] starting Research source reliability', 1000), baseMessage('m1', '[Company:cto::execute::abc] starting Research source reliability', 1000),
@@ -4,6 +4,7 @@ import type { ProgressEntry, RoleWorkItemSummary, Session, WorkItemProgressEntry
import { progressEntryKey } from '../lib/progressEntryKey' import { progressEntryKey } from '../lib/progressEntryKey'
import { stableMessageTimelineKey } from '../lib/messageTimelineIdentity' import { stableMessageTimelineKey } from '../lib/messageTimelineIdentity'
import { isMessageVisibleAtDetailLevel, resultSurfaceDedupeKey } from '../lib/workItemSessions' import { isMessageVisibleAtDetailLevel, resultSurfaceDedupeKey } from '../lib/workItemSessions'
import { resolveCanonicalTurnId, terminalAssistantTurnId } from '../lib/turnIdentity'
import { IconCopy, IconCheck, IconChat, IconSparkle, IconShield, IconActivity, IconChevron } from './SvgIcons' import { IconCopy, IconCheck, IconChat, IconSparkle, IconShield, IconActivity, IconChevron } from './SvgIcons'
import { AgentProgressBlock, AgentProgressEntryCard, INLINE_PROGRESS_ENTRY_TYPES } from './AgentProgressBlock' import { AgentProgressBlock, AgentProgressEntryCard, INLINE_PROGRESS_ENTRY_TYPES } from './AgentProgressBlock'
import { MarkdownBody } from './MarkdownBody' import { MarkdownBody } from './MarkdownBody'
@@ -345,13 +346,6 @@ export function messageTimelineKey(message: ChatMessage): string {
return stableMessageTimelineKey(message) return stableMessageTimelineKey(message)
} }
function terminalAssistantTurnId(message: ChatMessage): string {
const timelineKey = messageTimelineKey(message)
return timelineKey.startsWith('turn:assistant:')
? timelineKey.slice('turn:assistant:'.length)
: ''
}
function formatTime(ts: number) { function formatTime(ts: number) {
return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false }) return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })
} }
@@ -400,44 +394,6 @@ function compactWhitespace(value: string): string {
return value.replace(/\s+/g, ' ').trim() return value.replace(/\s+/g, ' ').trim()
} }
function stripNarrativeTitlePrefix(content: string): string {
const trimmed = String(content || '').trim()
const markdownTitle = trimmed.match(/^\*\*(.{8,160}?)\*\*:\s+([\s\S]+)$/)
if (markdownTitle) {
const body = markdownTitle[2].trim()
if (body.length >= 80) return body
}
const colonIndex = trimmed.indexOf(': ')
if (colonIndex < 8 || colonIndex > 160) return trimmed
const prefix = trimmed.slice(0, colonIndex).replace(/\*/g, '').trim()
const body = trimmed.slice(colonIndex + 2).trim()
if (body.length < 80) return trimmed
if (!/[A-Za-z\u4e00-\u9fff]/.test(prefix)) return trimmed
if (/^(https?|file)$/i.test(prefix)) return trimmed
return body
}
function isResultSurfaceMessage(message: ChatMessage): boolean {
const transcriptKind = String(message.metadata?.transcript_kind ?? message.metadata?.kind ?? '').trim()
if ([
'runtime_v2_assistant',
'runtime_v2_company_assistant',
'top_level_reply',
'company_role_result',
'company_role_result_retry',
'child_task_result',
'child_task_result_retry',
'child_result',
].includes(transcriptKind)) {
return true
}
if (String(message.metadata?.kind ?? '').trim() === 'worker_notification') {
return true
}
return false
}
function parseJsonObjectText(content: string): Record<string, unknown> | null { function parseJsonObjectText(content: string): Record<string, unknown> | null {
const trimmed = String(content || '').trim() const trimmed = String(content || '').trim()
if (!trimmed) return null if (!trimmed) return null
@@ -830,8 +786,6 @@ export function buildNarrativeMessageItems(
const items: TimelineItem[] = [] const items: TimelineItem[] = []
let bundle: SystemOpsBundleEvent[] = [] let bundle: SystemOpsBundleEvent[] = []
let bundleSortOrder = 0 let bundleSortOrder = 0
const seenProjectUpdates = new Set<string>()
const seenNarrativeMessages = new Set<string>()
const flushBundle = () => { const flushBundle = () => {
if (bundle.length === 0) return if (bundle.length === 0) return
@@ -854,33 +808,6 @@ export function buildNarrativeMessageItems(
bundle.push(ops) bundle.push(ops)
return return
} }
const projectUpdate = detailMode === 'summary' ? parseProjectUpdatePayload(msg.content) : null
if (projectUpdate) {
const dedupeKey = [
msg.sender,
Math.round(msg.timestamp / 1000),
projectUpdate.kind,
compactWhitespace(projectUpdate.summary || projectUpdate.acceptanceSummary || '').slice(0, 500),
projectUpdate.verdict ?? '',
projectUpdate.deliverables.map(item => `${item.name}:${item.path}`).join('|').slice(0, 800),
].join('\u0001')
if (seenProjectUpdates.has(dedupeKey)) return
seenProjectUpdates.add(dedupeKey)
}
if (detailMode === 'summary' && !isCheckpointCardMetadata(msg.metadata)) {
const canonicalContent = compactWhitespace(stripNarrativeTitlePrefix(msg.content)).slice(0, 1200)
if (canonicalContent) {
const dedupeKey = isResultSurfaceMessage(msg)
? ['result', canonicalContent].join('\u0001')
: [
msg.sender,
Math.round(msg.timestamp / 1000),
canonicalContent,
].join('\u0001')
if (seenNarrativeMessages.has(dedupeKey)) return
seenNarrativeMessages.add(dedupeKey)
}
}
flushBundle() flushBundle()
items.push({ items.push({
kind: 'message', kind: 'message',
@@ -1331,7 +1258,7 @@ export const MessageList = React.memo(function MessageList({
for (const message of timelineMessages) { for (const message of timelineMessages) {
const thinking = String(message.metadata?.runtime_thinking ?? '').trim() const thinking = String(message.metadata?.runtime_thinking ?? '').trim()
if (!thinking) continue if (!thinking) continue
const turnId = String(message.metadata?.canonical_turn_id ?? message.metadata?.turn_id ?? '').trim() const turnId = resolveCanonicalTurnId(message.metadata)
if (turnId && thinkingProgressTurnIds.has(turnId)) continue if (turnId && thinkingProgressTurnIds.has(turnId)) continue
entries.push({ entries.push({
type: 'thinking' as const, type: 'thinking' as const,
@@ -1,4 +1,103 @@
import type { ChatMessage } from '../types/chat' import type { ChatMessage } from '../types/chat'
import { resolveCanonicalTurnId, terminalAssistantTurnId } from './turnIdentity'
const COMMITTED_RESULT_SURFACE_KINDS = new Set([
'child_task_result',
'child_task_result_retry',
'company_role_result',
'company_role_result_retry',
'child_result',
'top_level_reply',
])
const RUNTIME_RESULT_SURFACE_KINDS = new Set([
'runtime_v2_assistant',
'runtime_v2_company_assistant',
])
function metadataValue(metadata: Record<string, unknown>, ...keys: string[]): string {
for (const key of keys) {
const value = String(metadata[key] ?? '').trim()
if (value) return value
}
return ''
}
function resultGenerationSuffix(metadata: Record<string, unknown>, kind: string): string {
const explicitAttempt = metadataValue(
metadata,
'result_attempt',
'attempt',
'attempt_index',
'retry_count',
'retryCount',
)
const attempt = explicitAttempt || (kind.endsWith('_retry') ? 'retry' : '')
const revision = metadataValue(
metadata,
'result_revision',
'delivery_revision',
'revision',
)
return [
attempt ? `attempt:${attempt}` : '',
revision ? `revision:${revision}` : '',
].filter(Boolean).join(':')
}
function withResultGeneration(
base: string,
metadata: Record<string, unknown>,
kind: string,
): string {
const suffix = resultGenerationSuffix(metadata, kind)
return suffix ? `${base}:${suffix}` : base
}
/** Stable protocol identity shared by mirrors of one committed result. */
export function stableResultDeliveryKey(message: ChatMessage): string {
const metadata = (message.metadata ?? {}) as Record<string, unknown>
const kind = String(metadata.transcript_kind ?? metadata.kind ?? '').trim()
if (!COMMITTED_RESULT_SURFACE_KINDS.has(kind) && !RUNTIME_RESULT_SURFACE_KINDS.has(kind)) {
return ''
}
const deliveryId = metadataValue(
metadata,
'canonical_delivery_id',
'result_delivery_id',
'delivery_id',
)
if (deliveryId) return `delivery:${deliveryId}`
if (RUNTIME_RESULT_SURFACE_KINDS.has(kind)) {
const turnId = resolveCanonicalTurnId(metadata)
return turnId ? `turn:${turnId}` : ''
}
// A committed result belongs to a task/work-item delivery, not merely to
// the surrounding conversation turn. Parallel roles commonly share that
// turn, so a turn-only fallback would collapse independent deliveries.
const explicitSourceTaskId = metadataValue(metadata, 'source_task_id', 'child_task_id')
const sourceTaskId = explicitSourceTaskId || (
kind === 'top_level_reply'
? ''
: metadataValue(metadata, 'task_id', 'taskId')
)
if (sourceTaskId) {
return withResultGeneration(`source-task:${sourceTaskId}`, metadata, kind)
}
const workItemId = metadataValue(metadata, 'work_item_id', 'work_item_projection_id')
if (workItemId) {
return withResultGeneration(`work-item:${workItemId}`, metadata, kind)
}
const childSessionId = metadataValue(metadata, 'child_session_id')
return childSessionId
? withResultGeneration(`child-session:${childSessionId}`, metadata, kind)
: ''
}
export function stableMessageTimelineKey(message: ChatMessage): string { export function stableMessageTimelineKey(message: ChatMessage): string {
const metadata = message.metadata ?? {} const metadata = message.metadata ?? {}
@@ -21,10 +120,19 @@ export function stableMessageTimelineKey(message: ChatMessage): string {
const retainedTimelineId = String(metadata.ui_timeline_id ?? '').trim() const retainedTimelineId = String(metadata.ui_timeline_id ?? '').trim()
if (retainedTimelineId) return retainedTimelineId if (retainedTimelineId) return retainedTimelineId
const turnId = String(metadata.canonical_turn_id ?? metadata.turn_id ?? '').trim() // Only a streamed runtime terminal owns the live draft's React slot.
if (!isUserTurn && turnId && transcriptKind === 'runtime_v2_assistant') { // Committed result surfaces may expose the same conversation turn through
// terminalAssistantTurnId, but their row identity must remain delivery/task
// scoped so parallel role results cannot collide.
const turnId = RUNTIME_RESULT_SURFACE_KINDS.has(transcriptKind)
? terminalAssistantTurnId(message)
: ''
if (!isUserTurn && turnId) {
return `turn:assistant:${turnId}` return `turn:assistant:${turnId}`
} }
const resultDeliveryKey = stableResultDeliveryKey(message)
if (!isUserTurn && resultDeliveryKey) return `result:${resultDeliveryKey}`
return `message:${message.id}` return `message:${message.id}`
} }
@@ -0,0 +1,50 @@
import type { ChatMessage, ChatMessageMeta } from '../types/chat'
const TERMINAL_ASSISTANT_KINDS = new Set([
'runtime_v2_assistant',
'runtime_v2_company_assistant',
'child_task_result',
'child_task_result_retry',
'company_role_result',
'company_role_result_retry',
'child_result',
'top_level_reply',
])
export function resolveCanonicalTurnId(
metadata: ChatMessageMeta | Record<string, unknown> | null | undefined,
): string {
const source = (metadata ?? {}) as Record<string, unknown>
for (const key of [
'canonical_turn_id',
'conversation_turn_id',
'turn_id',
'execution_turn_id',
]) {
const value = String(source[key] ?? '').trim()
if (value) return value
}
return ''
}
export function terminalAssistantTurnId(message: ChatMessage): string {
if (message.sender === 'user') return ''
const metadata = (message.metadata ?? {}) as Record<string, unknown>
const kind = String(metadata.transcript_kind ?? metadata.kind ?? '').trim()
if (!TERMINAL_ASSISTANT_KINDS.has(kind)) return ''
if (kind === 'runtime_v2_company_assistant') {
// Company tool-call iterations intentionally share this transcript kind
// and canonical turn with the final answer. Treating every iteration as
// terminal hides the live draft during detail refresh, then grows it back
// on the next delta. Only the actual final surface may replace the draft.
const uiMessageId = String(metadata.ui_message_id ?? '').trim()
const isFinal = metadata.company_final_turn === true
|| !!String(metadata.result_delivery_id ?? '').trim()
|| uiMessageId.startsWith('runtime-v2-company-assistant-final:')
// Snapshot translation retains final-vs-intermediate as visibility even
// when reading records created before structured delivery ids existed.
|| String(metadata.detail_visibility ?? '').trim() === 'summary'
if (!isFinal) return ''
}
return resolveCanonicalTurnId(metadata)
}
@@ -2,8 +2,10 @@ import assert from 'node:assert/strict'
import type { ChatMessage } from '../types/chat' import type { ChatMessage } from '../types/chat'
import type { Session } from '../types/kanban' import type { Session } from '../types/kanban'
import { mapBackendSession, mergeSessionDetailHasMore } from './collabSync' import { mapBackendSession, mergeSessionDetailHasMore } from './collabSync'
import { stableMessageTimelineKey, stableResultDeliveryKey } from './messageTimelineIdentity'
import { canonicalizeSessionExecutionIdentity } from './sessionIdentity' import { canonicalizeSessionExecutionIdentity } from './sessionIdentity'
import { deriveCompanyRuntimeDisplayStatus, getConversationHeaderSession, getConversationSessionView, getWorkItemChildSessions, getWorkItemRoleSessions, mergeConversationMessages, projectSessionConversation, selectCompanySummaryMessages } from './workItemSessions' import { resolveCanonicalTurnId, terminalAssistantTurnId } from './turnIdentity'
import { deriveCompanyRuntimeDisplayStatus, getConversationHeaderSession, getConversationSessionView, getWorkItemChildSessions, getWorkItemRoleSessions, mergeConversationMessages, projectSessionConversation, resultSurfaceDedupeKey, selectCompanySummaryMessages } from './workItemSessions'
function makeSession(overrides: Partial<Session> & Pick<Session, 'taskId' | 'channelId' | 'title' | 'status' | 'columnId' | 'assigneeIds' | 'priority' | 'tags' | 'progressLog' | 'createdAt' | 'updatedAt' | 'messageCount'>): Session { function makeSession(overrides: Partial<Session> & Pick<Session, 'taskId' | 'channelId' | 'title' | 'status' | 'columnId' | 'assigneeIds' | 'priority' | 'tags' | 'progressLog' | 'createdAt' | 'updatedAt' | 'messageCount'>): Session {
return { return {
@@ -338,12 +340,380 @@ assert.deepEqual(
[ [
'parent-user', 'parent-user',
'canonical-role-result', 'canonical-role-result',
'summary-company-final',
'summary-terminal-b',
'child-checkpoint', 'child-checkpoint',
'child-checkpoint-response', 'child-checkpoint-response',
].sort(), ].sort(),
) )
const companyRuntimeTurn = resultMessage(
'company-runtime-turn',
'session:company-child',
'A company runtime terminal surface.',
{
source: 'engine',
transcript_kind: 'runtime_v2_company_assistant',
canonical_turn_id: 'company-turn-0009',
result_delivery_id: 'company-delivery-0009',
},
'assistant',
)
assert.equal(
stableMessageTimelineKey(companyRuntimeTurn),
'turn:assistant:company-turn-0009',
)
const conversationOnlyRuntimeTurn = resultMessage(
'company-runtime-conversation-turn',
'session:company-child',
'A terminal surface with only its conversation identity.',
{
source: 'engine',
transcript_kind: 'runtime_v2_company_assistant',
conversation_turn_id: 'conversation-turn-only',
turn_id: 'iteration-turn-must-not-win',
execution_turn_id: 'execution-turn-must-not-win',
detail_visibility: 'summary',
},
'assistant',
)
assert.equal(
resolveCanonicalTurnId(conversationOnlyRuntimeTurn.metadata),
'conversation-turn-only',
)
assert.equal(terminalAssistantTurnId(conversationOnlyRuntimeTurn), 'conversation-turn-only')
assert.equal(
terminalAssistantTurnId({
...conversationOnlyRuntimeTurn,
metadata: {
...conversationOnlyRuntimeTurn.metadata,
detail_visibility: 'full',
},
}),
'',
'a company tool-call iteration must not suppress the active draft',
)
assert.equal(
stableMessageTimelineKey(conversationOnlyRuntimeTurn),
'turn:assistant:conversation-turn-only',
)
assert.equal(
terminalAssistantTurnId({
...conversationOnlyRuntimeTurn,
metadata: {
...conversationOnlyRuntimeTurn.metadata,
transcript_kind: 'company_role_result',
},
}),
'conversation-turn-only',
'committed result kinds must participate in terminal-turn matching',
)
assert.equal(
stableMessageTimelineKey({
...conversationOnlyRuntimeTurn,
metadata: {
...conversationOnlyRuntimeTurn.metadata,
transcript_kind: 'company_role_result',
source_task_id: 'committed-source-task',
},
}),
'result:source-task:committed-source-task',
'a committed terminal may expose its turn for matching without taking the runtime draft key',
)
const project0009CtoResult = [
'Both work items have been successfully dispatched to my senior engineer. Here\'s the status:',
'',
'## Dispatch Summary',
'',
'**Work Item 1: OpenOPC Source Code Architecture Deep-Dive Analysis**',
'- ID: `1ed5f5f1-ac41-49a1-b1fa-23bbc9adab82`',
'- Owner: senior_engineer',
'- Scope: `openopc-source-analysis`',
'- Output: `/data2/bjdwhzzh/project-hku/OpenOPC_workplace/0009/openopc-architecture-analysis.md`',
'- Covers: Layered architecture, collaboration policy, seat executor pattern, and self-evolution mechanisms.',
'',
'**Work Item 2: External Multi-Agent Frameworks Architecture Research**',
'- ID: `d0307208-6b95-44c1-9b51-6bf073bbdcef`',
'- Owner: senior_engineer',
'- Scope: `external-frameworks-research`',
'- Output: `/data2/bjdwhzzh/project-hku/OpenOPC_workplace/0009/external-frameworks-analysis.md`',
'',
'Both are independent and can execute in parallel. The runtime will monitor their completion.',
].join('\n')
const project0009WorkItemSuffix = project0009CtoResult.slice(
project0009CtoResult.indexOf('OpenOPC Source Code Architecture Deep-Dive Analysis'),
)
const project0009IdSuffix = project0009CtoResult.slice(
project0009CtoResult.indexOf('`1ed5f5f1-ac41-49a1-b1fa-23bbc9adab82`'),
)
// Content fallback must not treat arbitrary Markdown colons as removable
// narrative wrappers. The old normalization repeatedly turned the full 0009
// result into these two shorter variants, which changed the rendered height.
const fallback0009Full = resultMessage(
'0009-fallback-full',
'session:company-root',
project0009CtoResult,
{ source: 'engine', transcript_kind: 'child_result' },
'assistant',
)
const fallback0009WorkItem = resultMessage(
'0009-fallback-work-item',
'session:company-child',
project0009WorkItemSuffix,
{ source: 'engine', transcript_kind: 'runtime_v2_assistant' },
'assistant',
)
const fallback0009Id = resultMessage(
'0009-fallback-id',
'session:company-child',
project0009IdSuffix,
{ source: 'engine', transcript_kind: 'runtime_v2_assistant' },
'assistant',
)
assert.notEqual(resultSurfaceDedupeKey(fallback0009Full), resultSurfaceDedupeKey(fallback0009WorkItem))
assert.notEqual(resultSurfaceDedupeKey(fallback0009WorkItem), resultSurfaceDedupeKey(fallback0009Id))
const committed0009Parent = {
...resultMessage(
'0009-parent-result',
'session:company-root',
project0009CtoResult,
{
source: 'engine',
transcript_kind: 'child_result',
source_task_id: 'cto-task-0009',
},
'assistant',
),
timestamp: 2_000,
}
const committed0009Child = {
...resultMessage(
'0009-child-result',
'session:company-child',
project0009CtoResult,
{
source: 'engine',
transcript_kind: 'child_task_result',
task_id: 'cto-task-0009',
},
'assistant',
),
timestamp: 2_010,
}
const raw0009WorkItem = {
...fallback0009WorkItem,
metadata: {
...fallback0009WorkItem.metadata,
detail_visibility: 'summary' as const,
canonical_turn_id: 'cto-turn-0009',
},
timestamp: 2_020,
}
const raw0009Id = {
...fallback0009Id,
metadata: {
...fallback0009Id.metadata,
detail_visibility: 'summary' as const,
canonical_turn_id: 'cto-turn-0009',
},
timestamp: 2_030,
}
for (const messages of [
[committed0009Parent, committed0009Child, raw0009WorkItem, raw0009Id],
[raw0009Id, raw0009WorkItem, committed0009Child, committed0009Parent],
]) {
const summary = selectCompanySummaryMessages(messages, 'session:company-root')
assert.equal(summary.length, 1)
assert.equal(summary[0]?.id, '0009-child-result')
assert.equal(summary[0]?.content, project0009CtoResult)
assert.equal(stableMessageTimelineKey(summary[0]!), 'result:source-task:cto-task-0009')
}
const sameRoleText = 'The role completed its independent architecture analysis and committed the result.'
const multiRoleSummary = selectCompanySummaryMessages([
resultMessage(
'0009-cto-role-result',
'session:company-cto',
sameRoleText,
{
source: 'engine',
transcript_kind: 'company_role_result',
work_item_projection_id: '0009-cto-work-item',
},
'assistant',
),
resultMessage(
'0009-coo-role-result',
'session:company-coo',
sameRoleText,
{
source: 'engine',
transcript_kind: 'company_role_result',
work_item_projection_id: '0009-coo-work-item',
},
'assistant',
),
], 'session:company-root')
assert.deepEqual(
multiRoleSummary.map(message => stableMessageTimelineKey(message)).sort(),
[
'result:work-item:0009-coo-work-item',
'result:work-item:0009-cto-work-item',
],
)
const sharedConversationTurn = 'shared-company-conversation-turn'
const parallelRoleResults = [
resultMessage(
'parallel-cto-result',
'session:company-cto',
'CTO completed the architecture assessment.',
{
source: 'engine',
transcript_kind: 'company_role_result',
canonical_turn_id: sharedConversationTurn,
work_item_projection_id: 'architecture-assessment',
},
'assistant',
),
resultMessage(
'parallel-coo-result',
'session:company-coo',
'COO completed the feature assessment.',
{
source: 'engine',
transcript_kind: 'company_role_result',
canonical_turn_id: sharedConversationTurn,
work_item_projection_id: 'feature-assessment',
},
'assistant',
),
]
assert.deepEqual(
parallelRoleResults.map(resultSurfaceDedupeKey),
[
'result:work-item:architecture-assessment',
'result:work-item:feature-assessment',
],
'parallel committed roles must use work-item identity before a shared conversation turn',
)
assert.equal(
selectCompanySummaryMessages(parallelRoleResults, 'session:company-root').length,
2,
)
const versionedSourceResult = resultMessage(
'versioned-source-result',
'session:company-child',
'Versioned result.',
{
source: 'engine',
transcript_kind: 'company_role_result_retry',
source_task_id: 'source-task-versioned',
retry_count: 2,
delivery_revision: 4,
} as ChatMessage['metadata'],
'assistant',
)
assert.equal(
stableResultDeliveryKey(versionedSourceResult),
'source-task:source-task-versioned:attempt:2:revision:4',
)
const fullEqualPriorityResult = {
...resultMessage(
'full-equal-priority',
'session:company-child-a',
'The complete authoritative body includes every required architectural conclusion and its supporting rationale.',
{
source: 'engine',
transcript_kind: 'company_role_result',
result_delivery_id: 'deterministic-delivery',
},
'assistant',
),
timestamp: 2_100,
}
const truncatedEqualPriorityResult = {
...resultMessage(
'truncated-equal-priority',
'session:company-child-b',
'supporting rationale.',
{
source: 'engine',
transcript_kind: 'company_role_result',
result_delivery_id: 'deterministic-delivery',
},
'assistant',
),
timestamp: 2_200,
}
for (const groups of [
[[fullEqualPriorityResult], [truncatedEqualPriorityResult]],
[[truncatedEqualPriorityResult], [fullEqualPriorityResult]],
]) {
const merged = mergeConversationMessages(groups)
assert.equal(merged.length, 1)
assert.equal(merged[0]?.id, 'full-equal-priority')
assert.equal(merged[0]?.content, fullEqualPriorityResult.content)
assert.equal(merged[0]?.timestamp, 2_100)
assert.equal(
stableMessageTimelineKey(merged[0]!),
'result:delivery:deterministic-delivery',
)
const replayed = mergeConversationMessages([
merged,
[truncatedEqualPriorityResult],
])
assert.equal(replayed.length, 1)
assert.equal(replayed[0]?.id, 'full-equal-priority')
assert.equal(replayed[0]?.content, fullEqualPriorityResult.content)
}
const equalLengthStableWinner = {
...resultMessage(
'z-stable-winner',
'session:company-child-a',
'BBBB',
{
source: 'engine',
transcript_kind: 'company_role_result',
result_delivery_id: 'equal-length-delivery',
},
'assistant',
),
timestamp: 3_200,
}
const equalLengthLoser = {
...resultMessage(
'a-stable-loser',
'session:company-child-b',
'AAAA',
{
source: 'engine',
transcript_kind: 'company_role_result',
result_delivery_id: 'equal-length-delivery',
},
'assistant',
),
timestamp: 3_100,
}
for (const groups of [
[[equalLengthStableWinner], [equalLengthLoser]],
[[equalLengthLoser], [equalLengthStableWinner]],
]) {
const firstMerge = mergeConversationMessages(groups)
assert.equal(firstMerge[0]?.id, 'z-stable-winner')
assert.equal(firstMerge[0]?.content, 'BBBB')
assert.equal(firstMerge[0]?.timestamp, 3_100)
const replayed = mergeConversationMessages([firstMerge, [equalLengthLoser]])
assert.equal(replayed[0]?.id, 'z-stable-winner')
assert.equal(replayed[0]?.content, 'BBBB')
}
assert.equal(companyHeaderView?.status, 'running') assert.equal(companyHeaderView?.status, 'running')
assert.equal(companyHeaderView?.contextTokens, 0) assert.equal(companyHeaderView?.contextTokens, 0)
assert.equal(companyHeaderView?.contextWindow, 128000) assert.equal(companyHeaderView?.contextWindow, 128000)
@@ -2,7 +2,7 @@ import type { ChatMessage } from '../types/chat'
import type { ProgressEntry, Session } from '../types/kanban' import type { ProgressEntry, Session } from '../types/kanban'
import { getContextUsageMetrics } from './contextUsage' import { getContextUsageMetrics } from './contextUsage'
import { isSessionWorking } from './sessionRuntime' import { isSessionWorking } from './sessionRuntime'
import { stableMessageTimelineKey } from './messageTimelineIdentity' import { stableMessageTimelineKey, stableResultDeliveryKey } from './messageTimelineIdentity'
const CONTEXT_TOKENS_RE = /(\d[\d,]*)\s*\/\s*(\d[\d,]*)\s+tokens/i const CONTEXT_TOKENS_RE = /(\d[\d,]*)\s*\/\s*(\d[\d,]*)\s+tokens/i
const USED_PCT_RE = /(\d{1,3})%\s*used/i const USED_PCT_RE = /(\d{1,3})%\s*used/i
@@ -20,22 +20,32 @@ function compactWhitespace(value: string): string {
return value.replace(/\s+/g, ' ').trim() return value.replace(/\s+/g, ' ').trim()
} }
function stripNarrativeTitlePrefix(content: string): string { function normalizeResultContentFallback(content: string): string {
const trimmed = String(content || '').trim() let normalized = String(content || '')
const markdownTitle = trimmed.match(/^\*\*(.{8,160}?)\*\*:\s+([\s\S]+)$/) .replace(/\r\n/g, '\n')
if (markdownTitle) { .replace(/\r/g, '\n')
const body = markdownTitle[2].trim() .split('\n')
if (body.length >= 80) return body .map(line => line.trimEnd())
} .join('\n')
const colonIndex = trimmed.indexOf(': ') .replace(/\n{3,}/g, '\n\n')
if (colonIndex < 8 || colonIndex > 160) return trimmed .trim()
const prefix = trimmed.slice(0, colonIndex).replace(/\*/g, '').trim() // Some result mirrors add one explicit Markdown narrative label. Only
const body = trimmed.slice(colonIndex + 2).trim() // remove that anchored wrapper; a colon later in Markdown (for example
if (body.length < 80) return trimmed // "**Work Item 1: ..." or "- ID: ...") is message content, not a title.
if (!/[A-Za-z\u4e00-\u9fff]/.test(prefix)) return trimmed for (;;) {
if (/^(https?|file)$/i.test(prefix)) return trimmed const markdownTitle = normalized.match(/^\*\*([^\r\n]{8,160}?)\*\*:(?:[ \t]+|\r?\n+)([\s\S]+)$/)
return body if (!markdownTitle) break
const body = markdownTitle[2].trim()
if (body.length < 80 || body === normalized) break
normalized = body
}
const paragraphs = normalized.split(/\n{2,}/).map(part => part.trim()).filter(Boolean)
if (paragraphs.length > 1 && /^Verification:\s/i.test(paragraphs[paragraphs.length - 1])) {
normalized = paragraphs.slice(0, -1).join('\n\n').trim()
}
return compactWhitespace(normalized).slice(0, 2000)
} }
function resultSurfacePriority(message: ChatMessage): number { function resultSurfacePriority(message: ChatMessage): number {
@@ -67,9 +77,52 @@ function resultSurfacePriority(message: ChatMessage): number {
return 0 return 0
} }
function normalizedResultContentLength(message: ChatMessage): number {
return String(message.content ?? '')
.replace(/\r\n/g, '\n')
.replace(/\r/g, '\n')
.split('\n')
.map(line => line.trimEnd())
.join('\n')
.trim()
.length
}
function resultAuthorityScore(message: ChatMessage): number {
const metadata = (message.metadata ?? {}) as Record<string, unknown>
let score = 0
if (String(metadata.source ?? '').trim() === 'engine') score += 4
if (String(metadata.source_result_message_id ?? '').trim()) score += 2
if (metadata.authoritative_output === true || metadata.canonical_result === true) score += 1
return score
}
function compareResultSurfacePreference(left: ChatMessage, right: ChatMessage): number {
const numericComparisons: Array<[number, number]> = [
[resultSurfacePriority(left), resultSurfacePriority(right)],
[resultAuthorityScore(left), resultAuthorityScore(right)],
[normalizedResultContentLength(left), normalizedResultContentLength(right)],
]
for (const [leftValue, rightValue] of numericComparisons) {
if (leftValue !== rightValue) return leftValue > rightValue ? 1 : -1
}
const idComparison = left.id.localeCompare(right.id)
if (idComparison !== 0) return idComparison
const contentComparison = left.content.localeCompare(right.content)
if (contentComparison !== 0) return contentComparison
// Result chronology is later rewritten to the earliest underlying delivery.
// Timestamp is therefore safe only after immutable identity/content have
// tied; it must never be able to flip the selected surface on replay.
if (left.timestamp === right.timestamp) return 0
return left.timestamp > right.timestamp ? 1 : -1
}
export function resultSurfaceDedupeKey(message: ChatMessage): string { export function resultSurfaceDedupeKey(message: ChatMessage): string {
if (resultSurfacePriority(message) <= 0) return '' if (resultSurfacePriority(message) <= 0) return ''
const content = compactWhitespace(stripNarrativeTitlePrefix(message.content)).slice(0, 2000) const deliveryKey = stableResultDeliveryKey(message)
if (deliveryKey) return `result:${deliveryKey}`
const content = normalizeResultContentFallback(message.content)
return content ? `result:${content}` : '' return content ? `result:${content}` : ''
} }
@@ -492,7 +545,7 @@ export function mergeConversationMessages(messageGroups: ChatMessage[][]): ChatM
const existingIndex = resultKeyIndex.get(resultKey) const existingIndex = resultKeyIndex.get(resultKey)
if (existingIndex !== undefined) { if (existingIndex !== undefined) {
const existing = merged[existingIndex] const existing = merged[existingIndex]
const candidateWins = resultSurfacePriority(message) > resultSurfacePriority(existing) const candidateWins = compareResultSurfacePreference(message, existing) > 0
const preferred = candidateWins ? message : existing const preferred = candidateWins ? message : existing
const secondary = candidateWins ? existing : message const secondary = candidateWins ? existing : message
merged[existingIndex] = { merged[existingIndex] = {
@@ -505,7 +558,7 @@ export function mergeConversationMessages(messageGroups: ChatMessage[][]): ChatM
metadata: { metadata: {
...(secondary.metadata ?? {}), ...(secondary.metadata ?? {}),
...(preferred.metadata ?? {}), ...(preferred.metadata ?? {}),
ui_timeline_id: stableMessageTimelineKey(existing), ui_timeline_id: resultKey || stableMessageTimelineKey(existing),
}, },
} }
continue continue
@@ -541,22 +594,6 @@ export function selectCompanySummaryMessages(
messages: ChatMessage[], messages: ChatMessage[],
parentChannelId: string, parentChannelId: string,
): ChatMessage[] { ): ChatMessage[] {
const terminalAssistantTurn = (message: ChatMessage): string => {
const metadata = (message.metadata ?? {}) as Record<string, unknown>
const kind = String(metadata.transcript_kind ?? metadata.kind ?? '').trim()
if (kind !== 'runtime_v2_assistant' && kind !== 'runtime_v2_company_assistant') return ''
return String(metadata.canonical_turn_id ?? metadata.turn_id ?? '').trim()
}
const parentTerminalTurns = new Set(
messages
.filter(message => (
message.channelId === parentChannelId
&& isMessageVisibleAtDetailLevel(message, 'summary')
))
.map(terminalAssistantTurn)
.filter(Boolean),
)
const childTerminalByTurn = new Map<string, ChatMessage>()
const durableMessages: ChatMessage[] = [] const durableMessages: ChatMessage[] = []
for (const message of messages) { for (const message of messages) {
if (message.channelId === parentChannelId) { if (message.channelId === parentChannelId) {
@@ -584,38 +621,8 @@ export function selectCompanySummaryMessages(
'top_level_reply', 'top_level_reply',
].includes(kind)) { ].includes(kind)) {
durableMessages.push(message) durableMessages.push(message)
continue
}
// Snapshot builder deliberately marks the final runtime surface as
// summary-visible. Preserve that durable contract instead of reusing the
// result-dedupe priority table as a visibility threshold.
const isSummaryTerminal = String(metadata.detail_visibility ?? '').trim() === 'summary'
&& (kind === 'runtime_v2_assistant' || kind === 'runtime_v2_company_assistant')
if (!isSummaryTerminal) continue
const turnId = terminalAssistantTurn(message)
if (!turnId) {
durableMessages.push(message)
continue
}
if (parentTerminalTurns.has(turnId)) continue
const existing = childTerminalByTurn.get(turnId)
if (!existing) {
childTerminalByTurn.set(turnId, message)
continue
}
const existingPriority = resultSurfacePriority(existing)
const candidatePriority = resultSurfacePriority(message)
if (candidatePriority > existingPriority) {
childTerminalByTurn.set(turnId, message)
} else if (
candidatePriority === existingPriority
&& (message.timestamp > existing.timestamp
|| (message.timestamp === existing.timestamp && message.id.localeCompare(existing.id) > 0))
) {
childTerminalByTurn.set(turnId, message)
} }
} }
durableMessages.push(...childTerminalByTurn.values())
return mergeConversationMessages([durableMessages]) return mergeConversationMessages([durableMessages])
} }
@@ -472,7 +472,7 @@ async function runTimelineIdentityCases(page: Page, baseUrl: string): Promise<vo
collapsed: !!committed.querySelector('.msg-collapse-toggle'), collapsed: !!committed.querySelector('.msg-collapse-toggle'),
} }
}) })
assert.equal(finalizedDraft.reused, true, 'draft -> runtime_v2_assistant final must reuse the same outer timeline DOM node') assert.equal(finalizedDraft.reused, true, 'draft -> runtime_v2_company_assistant final must reuse the same outer timeline DOM node')
assert.equal(finalizedDraft.collapsed, false, 'a mounted expanded draft must not auto-collapse when its final arrives') assert.equal(finalizedDraft.collapsed, false, 'a mounted expanded draft must not auto-collapse when its final arrives')
assert.ok( assert.ok(
finalizedDraft.height >= draftGeometry.height - 4, finalizedDraft.height >= draftGeometry.height - 4,
@@ -366,7 +366,8 @@ function Fixture() {
mentions: [], mentions: [],
metadata: { metadata: {
canonical_turn_id: LIVE_TURN_ID, canonical_turn_id: LIVE_TURN_ID,
transcript_kind: 'runtime_v2_assistant', result_delivery_id: `result:${LIVE_TURN_ID}:attempt:0`,
transcript_kind: 'runtime_v2_company_assistant',
}, },
}, },
]) ])
@@ -341,7 +341,13 @@ export interface ChatMessageMeta {
/** UI-only identity retained across semantic result-surface replacement. */ /** UI-only identity retained across semantic result-surface replacement. */
ui_timeline_id?: string ui_timeline_id?: string
canonical_turn_id?: string canonical_turn_id?: string
conversation_turn_id?: string
turn_id?: string turn_id?: string
execution_turn_id?: string
result_delivery_id?: string
source_result_message_id?: string
source_task_id?: string
child_session_id?: string
execution_mode?: string execution_mode?: string
transcript_kind?: string transcript_kind?: string
detail_visibility?: DetailVisibility detail_visibility?: DetailVisibility
+40 -26
View File
@@ -192,23 +192,33 @@ def _normalize_duplicate_content(content: Any) -> str:
def _strip_narrative_title_prefix(content: str) -> str: def _strip_narrative_title_prefix(content: str) -> str:
trimmed = str(content or "").strip() trimmed = str(content or "").strip()
markdown_title = re.match(r"^\*\*(.{8,160}?)\*\*:\s+([\s\S]+)$", trimmed) # Comparison-only canonicalization may unwrap a deliberate leading title,
if markdown_title: # but must never interpret a colon inside ordinary Markdown body text as a
# wrapper boundary. Resolve explicit nested wrappers to a fixed point so
# the comparison key itself is idempotent.
while True:
markdown_title = re.match(r"^\*\*(.{8,160}?)\*\*:\s+([\s\S]+)$", trimmed)
if not markdown_title:
return trimmed
body = markdown_title.group(2).strip() body = markdown_title.group(2).strip()
if len(body) >= 80: if len(body) < 80 or body == trimmed:
return body return trimmed
colon_index = trimmed.find(": ") trimmed = body
if colon_index < 8 or colon_index > 160:
return trimmed
prefix = trimmed[:colon_index].replace("*", "").strip() def _select_duplicate_display_content(
body = trimmed[colon_index + 2 :].strip() preferred: dict[str, Any],
if len(body) < 80: secondary: dict[str, Any],
return trimmed ) -> str:
if not re.search(r"[A-Za-z\u4e00-\u9fff]", prefix): """Return one original surface body, never the lossy comparison key."""
return trimmed preferred_content = str(preferred.get("content", "") or "")
if re.match(r"^(https?|file)$", prefix, flags=re.IGNORECASE): secondary_content = str(secondary.get("content", "") or "")
return trimmed preferred_key = _normalize_duplicate_content(preferred_content)
return body if not preferred_key or preferred_key != _normalize_duplicate_content(secondary_content):
return preferred_content
if secondary_content.strip() == preferred_key and preferred_content.strip() != preferred_key:
return secondary_content
return preferred_content
def _normalize_transcript_detail_level(value: Any) -> TranscriptDetailLevel: def _normalize_transcript_detail_level(value: Any) -> TranscriptDetailLevel:
@@ -1132,7 +1142,19 @@ def _transcript_item_to_ui_message(
**({"runtime_thinking": runtime_thinking} if runtime_thinking else {}), **({"runtime_thinking": runtime_thinking} if runtime_thinking else {}),
**({ **({
key: message_metadata.get(key) key: message_metadata.get(key)
for key in ("canonical_turn_id", "turn_id") for key in (
"canonical_turn_id",
"turn_id",
"result_delivery_id",
"source_result_message_id",
"source_task_id",
"child_session_id",
"conversation_turn_id",
"execution_turn_id",
"work_item_projection_id",
"work_item_turn_type",
"runtime_session_id",
)
if message_metadata.get(key) if message_metadata.get(key)
}), }),
**ui_meta, **ui_meta,
@@ -1193,18 +1215,10 @@ def collapse_adjacent_transcript_duplicates(messages: list[dict[str, Any]]) -> l
): ):
merged_visibility = "full" merged_visibility = "full"
merged_metadata["detail_visibility"] = merged_visibility merged_metadata["detail_visibility"] = merged_visibility
preferred_content = str(preferred.get("content", "") or "")
secondary_content = str(secondary.get("content", "") or "")
normalized_content = _normalize_duplicate_content(preferred_content)
merged_content = (
normalized_content
if normalized_content and normalized_content == _normalize_duplicate_content(secondary_content)
else preferred_content
)
collapsed[-1] = { collapsed[-1] = {
**secondary, **secondary,
**preferred, **preferred,
"content": merged_content, "content": _select_duplicate_display_content(preferred, secondary),
"metadata": merged_metadata, "metadata": merged_metadata,
} }
return collapsed return collapsed
+47
View File
@@ -37,6 +37,7 @@ from opc.layer2_organization.work_item_identity import (
migrate_work_item_projection_metadata, migrate_work_item_projection_metadata,
projection_id_for_work_item, projection_id_for_work_item,
rework_projection_id_for_gate, rework_projection_id_for_gate,
result_delivery_identity_payload_for_task,
target_projection_id_for_decision, target_projection_id_for_decision,
target_projection_ids_for_decision, target_projection_ids_for_decision,
work_item_identity_payload, work_item_identity_payload,
@@ -217,6 +218,52 @@ class WorkItemProjectionIdentityTests(unittest.TestCase):
self.assertEqual(payload[WORK_ITEM_PROJECTION_ID_KEY], "task-proj") self.assertEqual(payload[WORK_ITEM_PROJECTION_ID_KEY], "task-proj")
self.assertEqual(payload[WORK_ITEM_TURN_TYPE_KEY], "report") self.assertEqual(payload[WORK_ITEM_TURN_TYPE_KEY], "report")
def test_result_delivery_identity_uses_canonical_turn_and_retry_attempt(self) -> None:
task = SimpleNamespace(
id="task-1",
retry_count=2,
metadata={"runtime_v2_current_turn_id": "canonical-turn-1"},
)
payload = result_delivery_identity_payload_for_task(task)
self.assertEqual(
payload["result_delivery_id"],
"result:task:task-1:turn:canonical-turn-1:attempt:2",
)
self.assertEqual(payload["source_task_id"], "task-1")
self.assertEqual(payload["canonical_turn_id"], "canonical-turn-1")
def test_result_delivery_identity_does_not_collide_for_parallel_tasks(self) -> None:
first = SimpleNamespace(id="task-1", retry_count=0, metadata={})
second = SimpleNamespace(id="task-2", retry_count=0, metadata={})
first_payload = result_delivery_identity_payload_for_task(
first,
canonical_turn_id="shared-parent-turn",
)
second_payload = result_delivery_identity_payload_for_task(
second,
canonical_turn_id="shared-parent-turn",
)
self.assertNotEqual(
first_payload["result_delivery_id"],
second_payload["result_delivery_id"],
)
self.assertIn(":task-1:", first_payload["result_delivery_id"])
self.assertIn(":task-2:", second_payload["result_delivery_id"])
def test_result_delivery_identity_requires_an_execution_scope(self) -> None:
task = SimpleNamespace(id="reused-task", retry_count=0, metadata={})
self.assertEqual(result_delivery_identity_payload_for_task(task), {
"source_task_id": "reused-task",
})
first = result_delivery_identity_payload_for_task(task, execution_id="execution-1")
second = result_delivery_identity_payload_for_task(task, execution_id="execution-2")
self.assertNotEqual(first["result_delivery_id"], second["result_delivery_id"])
def test_migrate_projection_metadata_backfills_from_fallbacks_without_overwriting(self) -> None: def test_migrate_projection_metadata_backfills_from_fallbacks_without_overwriting(self) -> None:
migrated, changed = migrate_work_item_projection_metadata( migrated, changed = migrate_work_item_projection_metadata(
{}, {},
+153 -1
View File
@@ -67,8 +67,95 @@ class MemoryManagerCompactionTests(unittest.IsolatedAsyncioTestCase):
compactor.maybe_compact_after_message.assert_not_awaited() compactor.maybe_compact_after_message.assert_not_awaited()
async def test_parent_child_result_preserves_structured_source_lineage(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
store = _MemoryStoreStub()
memory = MemoryManager(Path(tmpdir), project_id="0009", store=store)
task = Task(
id="task-cto-result",
title="CTO Result",
assigned_to="cto",
project_id="0009",
session_id="child-session",
parent_session_id="parent-session",
metadata={"work_item_projection_id": "cto::analysis"},
)
await memory.record_child_session_result(
"parent-session",
"child-session",
task=task,
result_content="done",
result_delivery_id=(
"result:task:task-cto-result:turn:canonical-cto-turn:attempt:0"
),
source_result_message_id="source-result-message",
canonical_turn_id="canonical-cto-turn",
)
metadata = store.session_messages[-1].metadata
self.assertEqual(
metadata["result_delivery_id"],
"result:task:task-cto-result:turn:canonical-cto-turn:attempt:0",
)
self.assertEqual(metadata["source_result_message_id"], "source-result-message")
self.assertEqual(metadata["source_task_id"], "task-cto-result")
self.assertEqual(metadata["child_session_id"], "child-session")
self.assertEqual(metadata["canonical_turn_id"], "canonical-cto-turn")
class SharedRoleSessionExecutionTests(unittest.IsolatedAsyncioTestCase): class SharedRoleSessionExecutionTests(unittest.IsolatedAsyncioTestCase):
def test_fallback_delivery_identity_is_per_result_not_per_provider_session(self) -> None:
task = Task(
id="shared-role-task",
title="Shared role",
assigned_to="cto",
retry_count=0,
)
first = TaskResult(
status=TaskStatus.AWAITING_HUMAN,
content="first pause",
artifacts={"provider_session_id": "provider-session-reused"},
)
second = TaskResult(
status=TaskStatus.DONE,
content="second result",
artifacts={"provider_session_id": "provider-session-reused"},
)
first_identity = OPCEngine._ensure_result_delivery_identity_for_commit(task, first)
second_identity = OPCEngine._ensure_result_delivery_identity_for_commit(task, second)
self.assertNotEqual(
first_identity["result_delivery_id"],
second_identity["result_delivery_id"],
)
self.assertNotEqual(
first.artifacts["result_execution_id"],
second.artifacts["result_execution_id"],
)
self.assertNotIn("provider-session-reused", first_identity["result_delivery_id"])
def test_fallback_delivery_identity_is_stable_after_result_persistence(self) -> None:
task = Task(id="external-task", title="External", assigned_to="cto")
result = TaskResult(
status=TaskStatus.DONE,
content="done",
artifacts={"runtime_session_id": "runtime-session-reused"},
)
first_identity = OPCEngine._ensure_result_delivery_identity_for_commit(task, result)
persisted_artifacts = dict(result.artifacts)
reloaded = TaskResult(
status=TaskStatus.DONE,
content="done",
artifacts=persisted_artifacts,
)
replay_identity = OPCEngine._ensure_result_delivery_identity_for_commit(task, reloaded)
self.assertEqual(replay_identity, first_identity)
self.assertEqual(reloaded.artifacts, persisted_artifacts)
async def test_company_shared_role_session_keeps_results_local(self) -> None: async def test_company_shared_role_session_keeps_results_local(self) -> None:
engine = OPCEngine() engine = OPCEngine()
engine.store = SimpleNamespace( engine.store = SimpleNamespace(
@@ -81,7 +168,11 @@ class SharedRoleSessionExecutionTests(unittest.IsolatedAsyncioTestCase):
record_task_completion_async=AsyncMock(), record_task_completion_async=AsyncMock(),
) )
engine._run_task_once = AsyncMock( engine._run_task_once = AsyncMock(
return_value=TaskResult(status=TaskStatus.DONE, content="done", artifacts={}) return_value=TaskResult(
status=TaskStatus.DONE,
content="done",
artifacts={"result_delivery_id": "delivery-shared-role"},
)
) )
engine._apply_runtime_state_to_task = lambda task, result: None engine._apply_runtime_state_to_task = lambda task, result: None
@@ -105,3 +196,64 @@ class SharedRoleSessionExecutionTests(unittest.IsolatedAsyncioTestCase):
engine.memory.record_assistant_turn.assert_awaited_once() engine.memory.record_assistant_turn.assert_awaited_once()
engine.memory.record_child_session_result.assert_not_awaited() engine.memory.record_child_session_result.assert_not_awaited()
metadata = engine.memory.record_assistant_turn.await_args.kwargs["metadata"]
self.assertEqual(metadata["result_delivery_id"], "delivery-shared-role")
self.assertEqual(metadata["source_task_id"], "task-cmo-review")
self.assertEqual(metadata["child_session_id"], "app14:role:cmo")
async def test_child_result_and_parent_mirror_share_delivery_identity(self) -> None:
engine = OPCEngine()
engine.store = SimpleNamespace(
get_task=AsyncMock(return_value=None),
save_task=AsyncMock(),
)
engine.memory = SimpleNamespace(
record_assistant_turn=AsyncMock(
return_value=SimpleNamespace(message_id="source-result-message")
),
record_child_session_result=AsyncMock(),
record_task_completion_async=AsyncMock(),
)
engine._run_task_once = AsyncMock(
return_value=TaskResult(
status=TaskStatus.DONE,
content="done",
artifacts={
"canonical_turn_id": "runtime-generated-turn",
"result_delivery_id": (
"result:task:task-cto-result:turn:runtime-generated-turn:attempt:0"
),
"runtime_session_id": "runtime-session-1",
},
)
)
engine._apply_runtime_state_to_task = lambda task, result: None
task = Task(
id="task-cto-result",
title="CTO Result",
assigned_to="cto",
status=TaskStatus.PENDING,
project_id="0009",
session_id="child-session",
parent_session_id="parent-session",
metadata={
"execution_mode": "company_mode",
"work_item_projection_id": "cto::analysis",
},
)
await engine._execute_task(task)
child_metadata = engine.memory.record_assistant_turn.await_args.kwargs["metadata"]
parent_call = engine.memory.record_child_session_result.await_args.kwargs
self.assertEqual(
child_metadata["result_delivery_id"],
"result:task:task-cto-result:turn:runtime-generated-turn:attempt:0",
)
self.assertEqual(
parent_call["result_delivery_id"],
child_metadata["result_delivery_id"],
)
self.assertEqual(parent_call["source_result_message_id"], "source-result-message")
self.assertEqual(parent_call["canonical_turn_id"], "runtime-generated-turn")
+8
View File
@@ -414,6 +414,13 @@ class NativeRuntimeV2Tests(unittest.IsolatedAsyncioTestCase):
# cannot swallow it into the frozen shared-iteration row. # cannot swallow it into the frozen shared-iteration row.
self.assertTrue(metadata["company_final_turn"]) self.assertTrue(metadata["company_final_turn"])
self.assertEqual(metadata["ui_message_id"], "runtime-v2-company-assistant-final:ui-turn:company") self.assertEqual(metadata["ui_message_id"], "runtime-v2-company-assistant-final:ui-turn:company")
self.assertEqual(
metadata["result_delivery_id"],
"result:task:company-role-task:turn:ui-turn:company:attempt:0",
)
self.assertEqual(metadata["source_task_id"], "company-role-task")
self.assertEqual(metadata["child_session_id"], "sess-company")
self.assertEqual(metadata["work_item_projection_id"], "chao::intake")
self.assertNotIn("visible_speaker", metadata) self.assertNotIn("visible_speaker", metadata)
await runtime._persist_assistant_turn( await runtime._persist_assistant_turn(
@@ -429,6 +436,7 @@ class NativeRuntimeV2Tests(unittest.IsolatedAsyncioTestCase):
intermediate_metadata = memory.appended_messages[-1]["kwargs"]["metadata"] intermediate_metadata = memory.appended_messages[-1]["kwargs"]["metadata"]
self.assertEqual(intermediate_metadata["kind"], "runtime_v2_company_assistant") self.assertEqual(intermediate_metadata["kind"], "runtime_v2_company_assistant")
self.assertNotIn("company_final_turn", intermediate_metadata) self.assertNotIn("company_final_turn", intermediate_metadata)
self.assertNotIn("result_delivery_id", intermediate_metadata)
self.assertEqual( self.assertEqual(
intermediate_metadata["ui_message_id"], intermediate_metadata["ui_message_id"],
"runtime-v2-company-assistant:ui-turn:company", "runtime-v2-company-assistant:ui-turn:company",
+315 -1
View File
@@ -16,10 +16,34 @@ from opc.plugins.office_ui.chat_store import (
_MessageMatchIndex, _MessageMatchIndex,
_MessageMatchState, _MessageMatchState,
) )
from opc.plugins.office_ui.snapshot_builder import build_transcript_ui_messages from opc.plugins.office_ui.snapshot_builder import (
build_transcript_ui_messages,
collapse_adjacent_transcript_duplicates,
)
from opc.plugins.office_ui.ws_handler import WSHandler from opc.plugins.office_ui.ws_handler import WSHandler
_WORK_ITEM_RESULT = """Both work items have been successfully dispatched and can execute in parallel.
**Dispatch Summary**
**Work Item 1: OpenOPC Source Code Architecture Deep-Dive Analysis**
- ID: `1ed5f5f1-ac41-49a1-b1fa-23bbc9adab82`
- Owner: senior_engineer
- Scope: `openopc-source-analysis`
- Output: `/workspace/openopc-architecture-analysis.md`
- Covers: Layered architecture, work-item state machines, collaboration policy, and seat executors.
**Work Item 2: External Multi-Agent Frameworks Architecture Research**
- ID: `d0307208-6b95-44c1-9b51-6bf073bbdcef`
- Owner: senior_engineer
- Scope: `external-frameworks-research`
- Output: `/workspace/external-frameworks-analysis.md`
- Covers: Architecture models, coordination, communication, extensibility, and implementation details.
Both are independent and can execute in parallel."""
class TranscriptStorePaginationTests(unittest.IsolatedAsyncioTestCase): class TranscriptStorePaginationTests(unittest.IsolatedAsyncioTestCase):
async def test_summary_page_filters_full_detail_rows_before_limit(self) -> None: async def test_summary_page_filters_full_detail_rows_before_limit(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir: with tempfile.TemporaryDirectory() as tmpdir:
@@ -216,6 +240,43 @@ class TranscriptStorePaginationTests(unittest.IsolatedAsyncioTestCase):
detail_level="summary", detail_level="summary",
)) ))
def test_renderer_preserves_structured_result_lineage(self) -> None:
lineage = {
"canonical_turn_id": "turn-canonical",
"turn_id": "turn-execution",
"result_delivery_id": "delivery-1",
"source_result_message_id": "source-message-1",
"source_task_id": "source-task-1",
"child_session_id": "child-session-1",
"conversation_turn_id": "conversation-turn-1",
"execution_turn_id": "execution-turn-1",
"work_item_projection_id": "architecture",
"work_item_turn_type": "delivery",
"runtime_session_id": "runtime-session-1",
}
rendered = build_transcript_ui_messages(
[{
"message": SimpleNamespace(
message_id="result-message-1",
role="assistant",
agent_id="cto",
created_at=datetime(2026, 7, 14, 10, 0, 0),
summary_flag=False,
metadata={"kind": "child_result", **lineage},
),
"parts": [SimpleNamespace(
part_type="text",
payload={"text": "Completed architecture analysis."},
)],
}],
channel_id="session:parent-task",
task_id="parent-task",
)
self.assertEqual(len(rendered), 1)
for key, value in lineage.items():
self.assertEqual(rendered[0]["metadata"].get(key), value)
class ChatStorePaginationTests(unittest.TestCase): class ChatStorePaginationTests(unittest.TestCase):
@staticmethod @staticmethod
@@ -293,6 +354,129 @@ class ChatStorePaginationTests(unittest.TestCase):
actual = store._dedupe_messages(messages) actual = store._dedupe_messages(messages)
self.assertEqual(actual, expected) self.assertEqual(actual, expected)
def test_work_item_colons_are_not_treated_as_narrative_wrappers(self) -> None:
normalized = ChatStore._normalize_duplicate_content(_WORK_ITEM_RESULT)
self.assertEqual(normalized, _WORK_ITEM_RESULT)
self.assertEqual(ChatStore._normalize_duplicate_content(normalized), normalized)
def test_duplicate_merge_keeps_work_item_display_content_across_replays(self) -> None:
store = ChatStore(None) # type: ignore[arg-type]
current = {
"message_id": "runtime-final",
"channel_id": "session:cto",
"sender": "assistant",
"sender_name": "CTO",
"content": _WORK_ITEM_RESULT,
"created_at": 1.0,
"reply_to_id": None,
"mentions": [],
"metadata": {
"source": "engine",
"transcript_kind": "runtime_v2_company_assistant",
},
}
canonical = {
**current,
"message_id": "child-task-result",
"created_at": 2.0,
"metadata": {
"source": "engine",
"transcript_kind": "child_task_result",
},
}
for _ in range(6):
current = store._merge_duplicate_messages(current, canonical)
self.assertEqual(current["content"], _WORK_ITEM_RESULT)
def test_duplicate_merge_reuses_an_original_unwrapped_surface(self) -> None:
store = ChatStore(None) # type: ignore[arg-type]
body = "Canonical answer " + ("with implementation details. " * 8)
wrapped = {
"message_id": "runtime-final",
"channel_id": "session:answer",
"sender": "assistant",
"sender_name": "OPC",
"content": f"**Top level answer**: {body}",
"created_at": 1.0,
"metadata": {
"source": "engine",
"transcript_kind": "runtime_v2_assistant",
},
}
unwrapped = {
**wrapped,
"message_id": "top-level-reply",
"content": body,
"created_at": 2.0,
"metadata": {
"source": "engine",
"transcript_kind": "top_level_reply",
},
}
merged = store._merge_duplicate_messages(wrapped, unwrapped)
self.assertEqual(merged["content"], unwrapped["content"])
self.assertIn(merged["content"], (wrapped["content"], unwrapped["content"]))
def test_result_delivery_identity_is_namespaced_without_canonical_turn_fallback(self) -> None:
store = ChatStore(None) # type: ignore[arg-type]
existing = {
"message_id": "raw-final",
"channel_id": "session:result",
"sender": "assistant",
"content": "runtime wording",
"created_at": 1.0,
"metadata": {
"result_delivery_id": "delivery-1",
"canonical_turn_id": "turn-shared",
},
}
delivered = {
**existing,
"message_id": "child-task-result",
"content": "canonical result wording",
"metadata": {
"result_delivery_id": "delivery-1",
"canonical_turn_id": "turn-shared",
},
}
unrelated_user = {
**existing,
"message_id": "user-turn",
"sender": "user",
"content": "different user text",
"metadata": {"canonical_turn_id": "turn-shared"},
}
self.assertIn("result_delivery:delivery-1", store._message_identity_keys(existing))
self.assertTrue(store._messages_semantically_match(existing, delivered))
self.assertFalse(store._messages_semantically_match(existing, unrelated_user))
def test_transcript_collapse_keeps_work_item_display_content_across_replays(self) -> None:
runtime = {
"message_id": "runtime-final",
"sender": "assistant",
"sender_name": "CTO",
"content": _WORK_ITEM_RESULT,
"created_at": 1.0,
"metadata": {"transcript_kind": "runtime_v2_company_assistant"},
}
canonical = {
**runtime,
"message_id": "child-task-result",
"created_at": 2.0,
"metadata": {"transcript_kind": "child_task_result"},
}
collapsed = collapse_adjacent_transcript_duplicates([runtime, canonical])
self.assertEqual(len(collapsed), 1)
self.assertEqual(collapsed[0]["content"], _WORK_ITEM_RESULT)
replayed = collapse_adjacent_transcript_duplicates([runtime, collapsed[0]])
self.assertEqual(len(replayed), 1)
self.assertEqual(replayed[0]["content"], _WORK_ITEM_RESULT)
def test_indexed_dedupe_normalizes_long_content_once_per_row(self) -> None: def test_indexed_dedupe_normalizes_long_content_once_per_row(self) -> None:
class CountingChatStore(ChatStore): class CountingChatStore(ChatStore):
normalize_calls = 0 normalize_calls = 0
@@ -501,6 +685,136 @@ class ChatStorePaginationTests(unittest.TestCase):
await db.close() await db.close()
tmpdir.cleanup() tmpdir.cleanup()
def test_backfill_same_id_repairs_destructively_normalized_content(self) -> None:
asyncio.run(self._exercise_backfill_same_id_repairs_content())
async def _exercise_backfill_same_id_repairs_content(self) -> None:
tmpdir = tempfile.TemporaryDirectory()
db = _SQLiteConnectionAdapter(str(Path(tmpdir.name) / "ui-state.db"))
store = ChatStore(db) # type: ignore[arg-type]
await store.initialize()
channel_id = "session:work-item-repair"
project_id = "test-project"
damaged_content = _WORK_ITEM_RESULT[_WORK_ITEM_RESULT.index("OpenOPC Source"):]
metadata = {
"source": "engine",
"transcript_kind": "child_result",
"legacy_cache_marker": True,
}
authoritative = {
"message_id": "result-message-1",
"sender": "assistant",
"sender_name": "CTO",
"content": _WORK_ITEM_RESULT,
"created_at": 1.0,
"metadata": {
"source": "engine",
"transcript_kind": "child_result",
},
}
try:
await store.insert_message(
channel_id,
"assistant",
"CTO",
damaged_content,
metadata=metadata,
message_id="result-message-1",
project_id=project_id,
created_at=1.0,
)
repaired = await store.backfill_messages(
channel_id,
[authoritative],
project_id=project_id,
)
replayed = await store.backfill_messages(
channel_id,
[authoritative],
project_id=project_id,
)
rows = await store.get_channel_messages(
channel_id,
limit=20,
project_id=project_id,
)
self.assertEqual([message["message_id"] for message in repaired], ["result-message-1"])
self.assertEqual(replayed, [])
self.assertEqual(len(rows), 1)
self.assertEqual(rows[0]["content"], _WORK_ITEM_RESULT)
self.assertTrue(rows[0]["metadata"].get("legacy_cache_marker"))
finally:
await db.close()
tmpdir.cleanup()
def test_backfill_semantic_duplicate_upgrades_existing_row_in_place(self) -> None:
asyncio.run(self._exercise_backfill_semantic_duplicate_upgrade())
async def _exercise_backfill_semantic_duplicate_upgrade(self) -> None:
tmpdir = tempfile.TemporaryDirectory()
db = _SQLiteConnectionAdapter(str(Path(tmpdir.name) / "ui-state.db"))
store = ChatStore(db) # type: ignore[arg-type]
await store.initialize()
channel_id = "session:semantic-result-repair"
project_id = "test-project"
authoritative_content = _WORK_ITEM_RESULT
authoritative = {
"message_id": "source-result-message",
"sender": "cto",
"sender_name": "CTO",
"content": authoritative_content,
"created_at": 2.0,
"metadata": {
"source": "engine",
"transcript_kind": "child_task_result",
},
}
try:
await store.insert_message(
channel_id,
"assistant",
"CTO",
f"**Legacy result**: {_WORK_ITEM_RESULT}",
metadata={
"source": "engine",
"transcript_kind": "runtime_v2_company_assistant",
"legacy_cache_marker": True,
},
message_id="mounted-cache-row",
project_id=project_id,
created_at=1.0,
)
upgraded = await store.backfill_messages(
channel_id,
[authoritative],
project_id=project_id,
)
replayed = await store.backfill_messages(
channel_id,
[authoritative],
project_id=project_id,
)
rows = await store.get_channel_messages(
channel_id,
limit=20,
project_id=project_id,
)
self.assertEqual([message["message_id"] for message in upgraded], ["mounted-cache-row"])
self.assertEqual(replayed, [])
self.assertEqual(len(rows), 1)
self.assertEqual(rows[0]["message_id"], "mounted-cache-row")
self.assertEqual(rows[0]["created_at"], 1.0)
self.assertEqual(rows[0]["content"], authoritative_content)
self.assertEqual(rows[0]["metadata"].get("transcript_kind"), "child_task_result")
self.assertTrue(rows[0]["metadata"].get("legacy_cache_marker"))
finally:
await db.close()
tmpdir.cleanup()
def test_summary_cache_page_filters_before_raw_fetch_limit(self) -> None: def test_summary_cache_page_filters_before_raw_fetch_limit(self) -> None:
asyncio.run(self._exercise_summary_cache_page()) asyncio.run(self._exercise_summary_cache_page())