From 2b6e6a91652e9db15185f09d4ba46ac4e608a2aa Mon Sep 17 00:00:00 2001 From: Daniel Ellison Date: Wed, 23 Sep 2026 13:19:27 -0400 Subject: [PATCH] Route agent memory writes through the lifecycle and complete memory diagnostics --- src/kai/application_host.py | 5 + src/kai/memory_admin.py | 14 +- src/kai/webhook.py | 114 +++++++- src/kai/workshop/client_api.py | 1 + src/kai/workshop/diagnostics.py | 160 +++++++++-- src/kai/workshop/memory_projection_status.py | 82 +++++- src/kai/workshop/memory_queries.py | 288 ++++++++++++++++++- src/kai/workshop/schema.py | 27 +- src/kai/workshop/static/app.js | 4 +- src/kai/workshop/temporal_memory.py | 5 +- tests/test_application_host.py | 3 + tests/test_memory_agent_writes.py | 244 ++++++++++++++++ tests/test_memory_legacy_episode_triage.py | 5 + tests/test_memory_owner_review.py | 10 +- tests/test_memory_triage_consolidation.py | 40 +++ tests/test_memory_write_path_sweep.py | 78 +++++ tests/test_webhook_api.py | 80 ++++++ tests/test_workshop_client_api.py | 2 +- tests/test_workshop_foundation.py | 1 + tests/test_workshop_memory_current_truth.py | 76 ++++- workshop-client/src/FactReview.test.tsx | 16 +- workshop-client/src/FactReview.tsx | 18 +- workshop-client/src/api.test.ts | 4 +- workshop-client/src/api.ts | 9 +- workshop-client/src/types.ts | 5 +- 25 files changed, 1226 insertions(+), 65 deletions(-) create mode 100644 tests/test_memory_agent_writes.py create mode 100644 tests/test_memory_write_path_sweep.py diff --git a/src/kai/application_host.py b/src/kai/application_host.py index ffa8de7a..01772146 100644 --- a/src/kai/application_host.py +++ b/src/kai/application_host.py @@ -488,6 +488,11 @@ async def start(self) -> KaiCoreServices: census_owners = await memory_queries.refresh_legacy_census() if census_owners: log.info("Counted legacy memory for %d owner(s)", census_owners) + # The same reason applies to vector drift: install status reads + # the stored audit rather than opening the vector store. + audited_owners = await memory_queries.refresh_vector_audits() + if audited_owners: + log.info("Audited memory vector rows for %d owner(s)", audited_owners) preference_documents = WorkshopPreferenceService( Path(self._config.session_db_path).parent, self._principal_storage, diff --git a/src/kai/memory_admin.py b/src/kai/memory_admin.py index 7ca00dcb..7dfa967d 100644 --- a/src/kai/memory_admin.py +++ b/src/kai/memory_admin.py @@ -1691,7 +1691,12 @@ def _cmd_projections(args: argparse.Namespace) -> int: """ from kai.config import load_config from kai.memory_quality_corpus import MemoryQualityCorpusError, resolve_human_principal - from kai.workshop.memory_projection_status import audit_vector_rows, expected_rows, projection_status + from kai.workshop.memory_projection_status import ( + audit_vector_rows, + expected_rows, + projection_status, + store_vector_audit, + ) config = load_config() db_path = Path(config.session_db_path) @@ -1743,11 +1748,14 @@ def report(label: str, statuses: list) -> None: rows = memory.get_all_for_lifecycle_projection(user_id=owner[0], runtime_profile_id=owner[1]) facts, episodes = expected[owner] audit = audit_vector_rows(rows, current_facts=facts, current_episodes=episodes) + # Install status reads the stored counts; refreshing them + # here keeps them as current as this full read. + store_vector_audit(db_path, audit, principal_id=owner[0], runtime_profile_id=owner[1]) print( f"memory projections: vector audit {owner[0]}/{owner[1]}; orphan={len(audit.orphan)}, " - f"unknown={len(audit.unknown)}, duplicate={audit.duplicate}" + f"unknown={len(audit.unknown)}, duplicate={audit.duplicate}, missing={len(audit.missing)}" ) - for memory_id in (*audit.orphan, *audit.unknown): + for memory_id in (*audit.orphan, *audit.unknown, *audit.missing): print(f" {memory_id}") finally: memory.close_memory() diff --git a/src/kai/webhook.py b/src/kai/webhook.py index 397b03dd..0e628598 100644 --- a/src/kai/webhook.py +++ b/src/kai/webhook.py @@ -123,7 +123,12 @@ WorkshopIntegrationNotificationService, ) from kai.workshop.internal_api_contexts import WorkshopInternalAPIExecutionContext -from kai.workshop.memory_queries import WorkshopMemoryQueryService +from kai.workshop.memory_queries import ( + WorkshopMemoryAccessDenied, + WorkshopMemoryMutationFailed, + WorkshopMemoryQueryService, + WorkshopMemoryValidationError, +) from kai.workshop.notification_preferences import WorkshopNotificationPreferenceService from kai.workshop.preferences import WorkshopPreferenceService from kai.workshop.principal_policies import WorkshopPrincipalPolicyService @@ -1738,12 +1743,14 @@ def _memory_disabled_response() -> web.Response: @_require_internal_api(InternalAPIOperation.MEMORY_ADD) async def _handle_memory_add(request: web.Request, principal: InternalAPIPrincipal) -> web.Response: """ - Store a structured memory via memory.add_structured(). + Store one fact the agent saves deliberately. - Wraps the existing add_structured() primitive used by the extraction - path. Lets authorized agent runtimes deliberately store facts without waiting for the extractor to pass - over a conversation. The primitive itself is unchanged; this handler - only adds the HTTP surface. + Lets authorized agent runtimes store facts without waiting for the + extractor to pass over a conversation. On a protected install the + fact is recorded as a canonical claim through the fact lifecycle, so + it is current truth and recalled like any other fact; only + `memory_type` "fact" is accepted there. Elsewhere it is written with + the add_structured() primitive the extraction path uses. Request body (JSON): content: str, required, non-empty after strip @@ -1763,7 +1770,10 @@ async def _handle_memory_add(request: web.Request, principal: InternalAPIPrincip 200 {"id": ""} on success 400 on bad input or a retired caller identity selector 401 on bad/missing internal API credential (handled by the decorator) - 503 when memory is disabled (precheck; do not retry, escalate) + 403 on a protected install when the runtime is not the principal's + 503 when memory is disabled (precheck; do not retry, escalate), or + on a protected install when the fact was recorded but its + search projection has not succeeded yet (it is retried) 500 when add_structured() returns None despite memory being enabled (the underlying store call failed; may be transient) """ @@ -1888,6 +1898,43 @@ async def _handle_memory_add(request: web.Request, principal: InternalAPIPrincip return web.json_response({"error": "Memory storage failed"}, status=500) final_metadata.update(_route_write_scope(None, active_project)) + # On a protected install the save becomes a canonical claim through + # the fact lifecycle. A direct vector write would have no claim, so + # the current-truth gate would treat it as legacy memory and, once the + # owner's legacy memory is reconciled, never recall it: the agent + # would be told the fact was saved while it silently vanished. The + # lifecycle only records facts; episodes come from extraction. + memory_queries = getattr(request.app[CORE_HOST_KEY].services, "memory_queries", None) + if getattr(api_config, "protected_install", False) and memory_queries is not None: + if memory_type != "fact": + return web.json_response( + {"error": "Only facts can be saved; episodes are recorded by extraction"}, status=400 + ) + if principal.principal_id is None: + return web.json_response({"error": "Memory access denied"}, status=403) + try: + memory_id = await memory_queries.record_agent_fact( + principal_id=principal.principal_id, + runtime_profile_id=principal.runtime_profile_id, + content=content, + tags=tags, + vector_metadata=final_metadata, + ) + except WorkshopMemoryValidationError as exc: + return web.json_response({"error": str(exc)}, status=400) + except WorkshopMemoryAccessDenied: + return web.json_response({"error": "Memory access denied"}, status=403) + except WorkshopMemoryMutationFailed as exc: + # The claim is canonical and its projection is retried at + # startup, but recall does not have it yet, so the agent must + # not report the save as complete. + return web.json_response({"error": str(exc)}, status=503) + except Exception: + log.exception("Canonical memory save failed for canonical principal") + return web.json_response({"error": "Memory storage failed"}, status=500) + log.info("Stored memory %s as a canonical claim through internal API authority", memory_id) + return web.json_response({"id": memory_id}) + # Defense-in-depth guard, matching the pattern used in the other # three memory handlers. add_structured catches its own internal # exceptions and returns None (which the None-check below maps to @@ -2077,7 +2124,13 @@ async def _handle_memory_stats(request: web.Request, principal: InternalAPIPrinc @_require_internal_api(InternalAPIOperation.MEMORY_DELETE_ALL) async def _handle_memory_delete_all(request: web.Request, principal: InternalAPIPrincipal) -> web.Response: """ - Delete all memories for a user via memory.delete_all(). + Forget all of the calling principal's memories. + + On a protected install every current fact is retracted through the + fact lifecycle (it leaves recall but stays in history and can be + restored) and legacy vector rows are deleted. Facts in an unresolved + conflict and canonical episodes are kept and counted. Elsewhere this + calls memory.delete_all(). Requires an exact-match confirm token in the body. Static well-known token (not per-request UUID) because the threat model @@ -2087,13 +2140,17 @@ async def _handle_memory_delete_all(request: web.Request, principal: InternalAPI confirm: str, required, must equal "delete-all-memories" Responses: - 200 {"status": "deleted"} on success + 200 {"status": "deleted"} on success; on a protected install it + also carries retracted, projection_failed, legacy_deleted, + kept_conflicts, and kept_episodes counts 400 on missing/wrong confirm or a retired caller identity selector 401 on bad secret - 503 when memory is disabled + 403 on a protected install when the runtime is not the principal's + 503 when memory is disabled, or when the search index could not be + read to find legacy rows - Caveat: delete_all() swallows internal errors (memory.py:1066-1069). - Partial failures inside Mem0 are logged but invisible at the API + Caveat: delete_all() swallows internal errors, so off a protected + install partial failures inside Mem0 are logged but invisible at the API layer. Surfacing them would require widening memory.py's error contract, which is out of scope for the foundation issue. """ @@ -2132,6 +2189,39 @@ async def _handle_memory_delete_all(request: web.Request, principal: InternalAPI return _memory_disabled_response() user_id = str(principal.principal_id) + # On a protected install every current fact is retracted through the + # fact lifecycle and only legacy rows are deleted outright. Deleting + # the vector rows directly would leave each canonical claim active + # with a projection pointing at a row that no longer exists, so recall + # would lose the facts while history and install status still counted + # them as current. Retraction also keeps each fact restorable. + api_config: Config = request.app[CONFIG_KEY] + memory_queries = getattr(request.app[CORE_HOST_KEY].services, "memory_queries", None) + if getattr(api_config, "protected_install", False) and memory_queries is not None: + if principal.principal_id is None: + return web.json_response({"error": "Memory access denied"}, status=403) + try: + result = await memory_queries.forget_all_for_agent( + principal_id=principal.principal_id, + runtime_profile_id=principal.runtime_profile_id, + ) + except WorkshopMemoryAccessDenied: + return web.json_response({"error": "Memory access denied"}, status=403) + except WorkshopMemoryMutationFailed as exc: + return web.json_response({"error": str(exc)}, status=503) + except Exception: + log.exception("Canonical forget-all failed for canonical principal") + return web.json_response({"error": "Memory delete failed"}, status=500) + return web.json_response( + { + "status": "deleted", + "retracted": result.retracted, + "projection_failed": result.projection_failed, + "legacy_deleted": result.legacy_deleted, + "kept_conflicts": result.kept_conflicts, + "kept_episodes": result.kept_episodes, + } + ) # Defense-in-depth guard, matching the pattern used in # _handle_memory_search and _handle_memory_stats. delete_all() # catches its own internal errors today (memory.py:1066-1069), so diff --git a/src/kai/workshop/client_api.py b/src/kai/workshop/client_api.py index cb727a80..f4a7de89 100644 --- a/src/kai/workshop/client_api.py +++ b/src/kai/workshop/client_api.py @@ -2882,6 +2882,7 @@ async def _handle_memory_projections_audit( "orphan": list(audit.orphan), "unknown": list(audit.unknown), "duplicate": audit.duplicate, + "missing": list(audit.missing), }, status=200, ) diff --git a/src/kai/workshop/diagnostics.py b/src/kai/workshop/diagnostics.py index ab515ebe..4e689380 100644 --- a/src/kai/workshop/diagnostics.py +++ b/src/kai/workshop/diagnostics.py @@ -2121,7 +2121,16 @@ def workshop_memory_current_truth_status(db_path: Path, *, memory_enabled: bool "SELECT 1 FROM memory_fact_revision_states s WHERE s.revision_id = r.revision_id " "AND s.claim_id = r.claim_id)", ) - legacy_unclassified, census_age = _legacy_census_summary(connection, tables) + legacy_unclassified, census_age, review_pending_owners, review_pending_rows = _legacy_census_summary( + connection, tables + ) + state_counts = { + str(row[0]): int(row[1]) + for row in connection.execute( + "SELECT state, COUNT(*) FROM memory_fact_revision_states GROUP BY state" + ).fetchall() + } + vector_drift, vector_missing, vector_age = _vector_audit_summary(connection, tables) staged_consolidations, consolidated_facts = _consolidation_summary(connection, tables) legacy_active, legacy_inactive = _legacy_admission_owner_counts(connection, tables) conflicts, oldest_conflict_days = _unresolved_conflict_summary(connection) @@ -2138,15 +2147,21 @@ def workshop_memory_current_truth_status(db_path: Path, *, memory_enabled: bool # No census yet means the count is unknown, which is not "complete". gaps = malformed + quarantined + projection_gaps + (legacy_unclassified if legacy_unclassified is not None else 1) gaps += failed_projections + blocked + # A vector store that disagrees with canonical state is a fault, and an + # audit that never ran is unknown, which is not "complete" either. + gaps += vector_drift if vector_drift is not None else 1 state = "active" if memory_enabled is True and gaps == 0 else "INCOMPLETE" if memory_enabled is None: state = "NOT VERIFIED" return ( f"{prefix} {state}; claims={claims}, revisions={revisions}, current={active}, " - f"inactive={inactive}, validity excluded={validity_excluded}, quarantined={quarantined}, " + f"inactive={inactive}, states=({_state_label(state_counts)}), " + f"validity excluded={validity_excluded}, quarantined={quarantined}, " f"operator admitted={operator_admitted}, " - f"legacy unclassified={_census_label(legacy_unclassified, census_age)}, projection gaps={projection_gaps}, " - f"integrity gaps={malformed}; " + f"legacy unclassified={_census_label(legacy_unclassified, census_age)}, " + f"legacy review pending={review_pending_owners} owner(s) ({review_pending_rows} rows), " + f"projection gaps={projection_gaps}, integrity gaps={malformed}; " + f"vector drift={_vector_audit_label(vector_drift, vector_missing, vector_age)}; " f"unresolved conflicts={conflicts}" f"{f' (oldest={oldest_conflict_days}d)' if conflicts else ''}; " f"projection failed={failed_projections} (facts={failed_facts}, episodes={failed_episodes}), " @@ -2208,25 +2223,99 @@ def _consolidation_summary(connection: sqlite3.Connection, tables: set[str]) -> return (int(row[0] or 0), int(row[1] or 0)) if row is not None else (0, 0) -def _legacy_census_summary(connection: sqlite3.Connection, tables: set[str]) -> tuple[int | None, str | None]: +def _legacy_census_summary(connection: sqlite3.Connection, tables: set[str]) -> tuple[int | None, str | None, int, int]: """ - Sum unclassified legacy rows across owners from the stored census. + Split unclassified legacy rows into gaps and rows still awaiting review. The service counts legacy rows at startup and after every reconciliation apply, because only it can read the vector store; this - reads the stored counts. Returns (None, None) before any census, and - otherwise the sum with the age of the oldest owner's count, so a stale - number is visible as stale. + reads the stored counts. An owner who has applied a reconciliation + audit has had the chance to classify every row, so any row still + unclassified is a gap (a row written outside the lifecycle since, for + example). An owner who never applied one is simply waiting on their + own review: their rows stay recallable through temporary legacy + admission, so they are reported as review pending, not as a gap. + + Returns (unclassified rows of reviewed owners, age of the oldest + count, owners pending review, their unclassified rows). The first two + are (None, None) before any census, so an unknown count is visible. """ if "memory_legacy_census" not in tables: - return None, None - row = connection.execute("SELECT COUNT(*), SUM(unclassified), MIN(counted_at) FROM memory_legacy_census").fetchone() + return None, None, 0, 0 + row = connection.execute("SELECT COUNT(*), MIN(counted_at) FROM memory_legacy_census").fetchone() if row is None or not row[0]: - return None, None - counted = datetime.fromisoformat(str(row[2]).replace("Z", "+00:00")) + return None, None, 0, 0 + counted = datetime.fromisoformat(str(row[1]).replace("Z", "+00:00")) if counted.tzinfo is None: counted = counted.replace(tzinfo=UTC) - return int(row[1] or 0), _age_label(datetime.now(UTC) - counted) + applied: set[tuple[str, str]] = set() + if "memory_reconciliation_audits" in tables: + applied = { + (str(item[0]), str(item[1])) + for item in connection.execute( + "SELECT principal_id, runtime_profile_id FROM memory_reconciliation_audits WHERE status = 'applied'" + ) + } + reviewed = pending_owners = pending_rows = 0 + for principal_id, runtime_profile_id, unclassified in connection.execute( + "SELECT principal_id, runtime_profile_id, unclassified FROM memory_legacy_census" + ): + if (str(principal_id), str(runtime_profile_id)) in applied: + reviewed += int(unclassified) + elif int(unclassified): + pending_owners += 1 + pending_rows += int(unclassified) + return reviewed, _age_label(datetime.now(UTC) - counted), pending_owners, pending_rows + + +def _vector_audit_summary(connection: sqlite3.Connection, tables: set[str]) -> tuple[int | None, int, str | None]: + """ + Sum the stored vector audit across owners. + + The service audits each owner's vector rows at startup and after + projection retries and stores only counts. Drift is every row or item + that disagrees with canonical state: orphan, unknown, and missing rows + plus items with duplicate rows. Missing rows are also returned on + their own because they are the one kind recall actually loses. + Returns (None, 0, None) before any audit, and otherwise the drift, + the missing count, and the age of the oldest owner's audit. + """ + if "memory_vector_audit" not in tables: + return None, 0, None + row = connection.execute( + "SELECT COUNT(*), SUM(orphan_rows + unknown_rows + duplicate_items + missing_rows), SUM(missing_rows), " + "MIN(checked_at) FROM memory_vector_audit" + ).fetchone() + if row is None or not row[0]: + return None, 0, None + checked = datetime.fromisoformat(str(row[3]).replace("Z", "+00:00")) + if checked.tzinfo is None: + checked = checked.replace(tzinfo=UTC) + return int(row[1] or 0), int(row[2] or 0), _age_label(datetime.now(UTC) - checked) + + +def _vector_audit_label(drift: int | None, missing: int, age: str | None) -> str: + if drift is None: + return "not checked" + return f"{drift} (missing={missing}, checked {age} ago)" + + +def _relationship_label(counts: dict[str, int]) -> str: + """Render episode follow-ups per relationship in a fixed order, zeros included.""" + order = ("repeated", "revisited", "outcome_changed", "invalidated_conclusion", "resolved_by") + rendered = [f"{name}={counts.get(name, 0)}" for name in order] + rendered.extend(f"{name}={count}" for name, count in sorted(counts.items()) if name not in order) + return ", ".join(rendered) + + +def _state_label(counts: dict[str, int]) -> str: + """Render revision counts per lifecycle state in a fixed order, zeros included.""" + order = ("active", "superseded", "retracted", "expired", "unresolved_conflict") + labels = {"unresolved_conflict": "conflicted"} + rendered = [f"{labels.get(name, name)}={counts.get(name, 0)}" for name in order] + # A state this code does not know is still shown, so it cannot hide. + rendered.extend(f"{name}={count}" for name, count in sorted(counts.items()) if name not in order) + return ", ".join(rendered) def _age_label(age: timedelta) -> str: @@ -2403,10 +2492,39 @@ def workshop_memory_reconciliation_status(db_path: Path) -> str: "AND r.input_sha256 = json_extract(g.recommendation_json, '$.input_sha256') " "AND r.output_sha256 = json_extract(g.recommendation_json, '$.output_sha256'))", ) + # An operation is replay-safe when its stored response names + # what it acted on and that target still accounts for it. + # Review decisions and applies name their audit. A policy + # replan names the plan it produced, which either still exists + # or was itself replanned later. Consolidation saves and + # cancels name their plan and consolidation; the consolidation + # either still exists or has a recorded cancellation. + # Anything else is a gap. + consolidations_known = "memory_reconciliation_triage_consolidations" in tables + consolidation_target = ( + "(EXISTS (SELECT 1 FROM memory_reconciliation_triage_consolidations c " + "WHERE c.consolidation_id = COALESCE(json_extract(o.response_json, '$.consolidation.consolidation_id'), " + "json_extract(o.response_json, '$.consolidation_id'))) " + "OR EXISTS (SELECT 1 FROM memory_reconciliation_operations x " + "WHERE json_extract(x.response_json, '$.cancelled') = 1 " + "AND json_extract(x.response_json, '$.consolidation_id') = COALESCE(" + "json_extract(o.response_json, '$.consolidation.consolidation_id'), " + "json_extract(o.response_json, '$.consolidation_id'))))" + if consolidations_known + else "0" + ) replay_gaps = _scalar( connection, "SELECT COUNT(*) FROM memory_reconciliation_operations o " - "WHERE json_extract(o.response_json, '$.audit_id') IS NULL", + "WHERE json_extract(o.response_json, '$.audit_id') IS NULL " + "AND NOT (o.client_operation_id LIKE 'replan:%' AND (" + "EXISTS (SELECT 1 FROM memory_reconciliation_triage_plans p " + "WHERE p.plan_id = json_extract(o.response_json, '$.new_plan_id')) " + "OR EXISTS (SELECT 1 FROM memory_reconciliation_operations r " + "WHERE r.client_operation_id = 'replan:' || json_extract(o.response_json, '$.new_plan_id')))) " + "AND NOT (EXISTS (SELECT 1 FROM memory_reconciliation_triage_plans p " + "WHERE p.plan_id = json_extract(o.response_json, '$.plan_id')) " + f"AND {consolidation_target})", ) finally: connection.close() @@ -2454,10 +2572,12 @@ def workshop_episode_history_status(db_path: Path, *, memory_enabled: bool | Non ) legacy = episodes - canonical followups = _scalar(connection, "SELECT COUNT(*) FROM memory_episode_followups") - repeated = _scalar( - connection, - "SELECT COUNT(*) FROM memory_episode_followups WHERE relationship = 'repeated'", - ) + relationships = { + str(row[0]): int(row[1]) + for row in connection.execute( + "SELECT relationship, COUNT(*) FROM memory_episode_followups GROUP BY relationship" + ).fetchall() + } pending = _scalar( connection, "SELECT COUNT(*) FROM memory_episode_vector_operations WHERE status IN ('pending', 'executing')", @@ -2489,7 +2609,7 @@ def workshop_episode_history_status(db_path: Path, *, memory_enabled: bool | Non state = "active" if pending == 0 and failed == 0 and gaps == 0 else "INCOMPLETE" return ( f"{prefix} {state}; episodes={episodes} (canonical={canonical}, legacy={legacy}), " - f"followups={followups} (repeated={repeated}), projections=(pending={pending}, failed={failed}), " + f"followups={followups} ({_relationship_label(relationships)}), projections=(pending={pending}, failed={failed}), " f"integrity gaps={gaps} (provenance={provenance_gaps}, projection={projection_gaps}); " "authority=immutable/canonical" ) diff --git a/src/kai/workshop/memory_projection_status.py b/src/kai/workshop/memory_projection_status.py index 8a0a23b3..7040f937 100644 --- a/src/kai/workshop/memory_projection_status.py +++ b/src/kai/workshop/memory_projection_status.py @@ -25,6 +25,8 @@ from collections import Counter from collections.abc import Iterable from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path import aiosqlite @@ -99,15 +101,21 @@ class VectorAudit: current row (left behind by a delete, a rewrite, or a duplicate add). - `unknown`: rows naming a claim or episode the owner does not have. - `duplicate`: claims or episodes with more than one row. - - The retrieval gate already keeps all of these out of recall; they are - wasted storage and noise in exclusion counts, not a leak. Memory ids - are kept so an operator can inspect them; content never is. + - `missing`: current rows canonical state expects that the store does + not have. Unlike the others this one is a loss, not noise: the + current-truth gate admits a fact only through its current row, so a + missing row is a current fact recall cannot return. + + The retrieval gate keeps orphan, unknown, and duplicate rows out of + recall; they are wasted storage and noise in exclusion counts, not a + leak. Memory ids are kept so an operator can inspect them; content + never is. """ orphan: tuple[str, ...] unknown: tuple[str, ...] duplicate: int + missing: tuple[str, ...] = () # ── Outbox queries ─────────────────────────────────────────────────── @@ -263,8 +271,10 @@ def audit_vector_rows( """ orphan: list[str] = [] unknown: list[str] = [] + present: set[str] = set() per_item: Counter[tuple[str, str]] = Counter() for row in rows: + present.add(row.id) claim_id = row.metadata.get(CANONICAL_CLAIM_ID_KEY) episode_id = row.metadata.get(CANONICAL_EPISODE_ID_KEY) if isinstance(claim_id, str) and claim_id: @@ -278,10 +288,14 @@ def audit_vector_rows( unknown.append(row.id) elif expected[item_id] != row.id: orphan.append(row.id) + expected_ids = { + memory_id for memory_id in (*current_facts.values(), *current_episodes.values()) if memory_id is not None + } return VectorAudit( orphan=tuple(sorted(orphan)), unknown=tuple(sorted(unknown)), duplicate=sum(1 for count in per_item.values() if count > 1), + missing=tuple(sorted(expected_ids - present)), ) @@ -319,6 +333,64 @@ async def expected_rows_async( return _expected_facts(facts), _expected_episodes(episodes) +def store_vector_audit( + db_path: Path, + audit: VectorAudit, + *, + principal_id: str, + runtime_profile_id: str, + now: datetime | None = None, +) -> None: + """ + Record one owner's latest vector audit counts for install status. + + Only counts and the time are stored, never memory ids or content, so + install status can report drift and its age without reading the + vector store. The row is replaced on every audit. + """ + connection = sqlite3.connect(str(db_path), timeout=30) + try: + connection.execute( + "INSERT INTO memory_vector_audit (" + "principal_id, runtime_profile_id, orphan_rows, unknown_rows, duplicate_items, missing_rows, checked_at" + ") VALUES (?, ?, ?, ?, ?, ?, ?) " + "ON CONFLICT (principal_id, runtime_profile_id) DO UPDATE SET orphan_rows = excluded.orphan_rows, " + "unknown_rows = excluded.unknown_rows, duplicate_items = excluded.duplicate_items, " + "missing_rows = excluded.missing_rows, checked_at = excluded.checked_at", + ( + principal_id, + runtime_profile_id, + len(audit.orphan), + len(audit.unknown), + audit.duplicate, + len(audit.missing), + (now or datetime.now(UTC)).isoformat(timespec="seconds"), + ), + ) + connection.commit() + finally: + connection.close() + + +def refresh_vector_audit(db_path: Path, *, principal_id: str, runtime_profile_id: str) -> VectorAudit: + """ + Audit one owner's vector rows against canonical state and store the counts. + + Call only from a process that holds the vector store (the service, or + the admin CLI with the service stopped). A read failure propagates and + the previous stored audit stays with its older time. + """ + rows = memory.get_all_for_lifecycle_projection(user_id=principal_id, runtime_profile_id=runtime_profile_id) + connection = sqlite3.connect(str(db_path), timeout=30) + try: + facts, episodes = expected_rows(connection, (principal_id, runtime_profile_id)) + finally: + connection.close() + audit = audit_vector_rows(rows, current_facts=facts, current_episodes=episodes) + store_vector_audit(db_path, audit, principal_id=principal_id, runtime_profile_id=runtime_profile_id) + return audit + + __all__ = [ "MAX_FAILED_ITEMS", "FailedProjection", @@ -330,4 +402,6 @@ async def expected_rows_async( "expected_rows_async", "projection_status", "projection_status_async", + "refresh_vector_audit", + "store_vector_audit", ] diff --git a/src/kai/workshop/memory_queries.py b/src/kai/workshop/memory_queries.py index 7db49623..a7b8f9fd 100644 --- a/src/kai/workshop/memory_queries.py +++ b/src/kai/workshop/memory_queries.py @@ -7,6 +7,7 @@ import hashlib import json import logging +import uuid from collections.abc import Mapping, Sequence from dataclasses import dataclass, field from datetime import UTC, datetime @@ -33,6 +34,7 @@ WorkshopExecutionStateRegistry, ) from kai.workshop.fact_lifecycle import ( + FactLifecycleAccessDenied, FactLifecycleConflict, FactMutationSource, FactRevisionInput, @@ -58,6 +60,8 @@ audit_vector_rows, expected_rows_async, projection_status_async, + refresh_vector_audit, + store_vector_audit, ) from kai.workshop.memory_reconciliation_review import WorkshopMemoryReconciliationReviewService from kai.workshop.memory_reconciliation_triage import WorkshopMemoryReconciliationTriageService @@ -261,6 +265,23 @@ class MemoryCreationSnapshot: created: bool +@dataclass(frozen=True, slots=True) +class AgentForgetAllResult: + """What forgetting all of an owner's memory did, for the internal API reply.""" + + # Active claims retracted through the lifecycle. + retracted: int + # Of those, claims whose vector delete failed and awaits retry; they + # stay in recall until it succeeds. + projection_failed: int + # Legacy vector rows (no canonical claim) deleted outright. + legacy_deleted: int + # Claims in an unresolved conflict, left for the owner to decide. + kept_conflicts: int + # Canonical episodes, which are immutable history and never deleted. + kept_episodes: int + + @dataclass(frozen=True, slots=True) class MemoryRecordPage: records: tuple[MemoryRecordSummary, ...] @@ -640,14 +661,7 @@ async def refresh_legacy_census(self) -> int: if not memory.is_enabled(): return 0 counted = 0 - owners = sorted( - { - (str(namespace.principal_id), str(namespace.runtime_profile_id)) - for namespaces in self._namespaces.values() - for namespace in namespaces - } - ) - for principal_id, runtime_profile_id in owners: + for principal_id, runtime_profile_id in self._owners(): try: await asyncio.to_thread( refresh_legacy_census, @@ -661,6 +675,44 @@ async def refresh_legacy_census(self) -> int: counted += 1 return counted + async def refresh_vector_audits(self) -> int: + """ + Audit every owner's vector rows against canonical state at startup. + + Install status reads the stored counts because, running as root, it + must not open the vector store the service holds. This runs after + projection recovery, so it sees the store as recovery left it. A + failure for one owner is logged and the others still run; that + owner's previous audit stays with its older time. Returns the + number of owners audited. + """ + if not memory.is_enabled(): + return 0 + audited = 0 + for principal_id, runtime_profile_id in self._owners(): + try: + await asyncio.to_thread( + refresh_vector_audit, + Path(self._config.session_db_path), + principal_id=principal_id, + runtime_profile_id=runtime_profile_id, + ) + except Exception: + log.warning("Vector audit failed for %s/%s", principal_id, runtime_profile_id, exc_info=True) + continue + audited += 1 + return audited + + def _owners(self) -> list[tuple[str, str]]: + """Every (principal, runtime profile) pair with a memory namespace, in a stable order.""" + return sorted( + { + (str(namespace.principal_id), str(namespace.runtime_profile_id)) + for namespaces in self._namespaces.values() + for namespace in namespaces + } + ) + def authority_for_principal( self, principal_id: str | PrincipalId, @@ -1275,6 +1327,201 @@ async def create_fact( ) return MemoryCreationSnapshot(await self.detail(authority, memory_id), True) + async def record_agent_fact( + self, + *, + principal_id: PrincipalId, + runtime_profile_id: RuntimeProfileId, + content: str, + tags: Sequence[str] | None, + vector_metadata: Mapping[str, object], + ) -> str: + """ + Record a fact an agent saved deliberately, as a canonical claim. + + The internal memory API used to write these straight to the vector + store. On a protected install such a row has no canonical claim, so + the current-truth gate treats it as legacy and, once the owner's + legacy memory is reconciled, never recalls it. Recording it through + the lifecycle makes it current truth like any other fact, with + history, conflict handling, and projection retry. + + The caller has already routed the scope (from the agent's workspace + project) and stamped provenance into `vector_metadata`. The agent + runtime is bound to one exact runtime profile, so the owner is + unambiguous even for a principal with several profiles. + + Each call is its own claim: the internal API carries no request id, + so a retried save is a new fact, exactly as the old direct write + was. The evidence names this save by a fresh id so its history + says where the fact came from. + + Returns: + The projected vector row id. + + Raises: + WorkshopMemoryValidationError: Content, tags, or scope invalid. + WorkshopMemoryAccessDenied: The runtime profile is not the + principal's. + WorkshopMemoryMutationFailed: The fact is canonical but its + search projection did not succeed (it is retried later). + """ + cleaned_content = self._validate_text(content, field="Content", maximum=MAX_CONTENT_CHARACTERS) + cleaned_tags = self._validate_tags(tags or ()) + scope = vector_metadata.get("scope") + project_id = vector_metadata.get("project_id") + if scope not in _VALID_MUTATION_SCOPES or ( + scope == memory.SCOPE_PROJECT and (not isinstance(project_id, str) or not project_id) + ): + raise WorkshopMemoryValidationError("Memory scope must be global or a named project") + confidence = vector_metadata.get("confidence", 0.9) + if isinstance(confidence, bool) or not isinstance(confidence, (int, float)): + raise WorkshopMemoryValidationError("Memory confidence must be a number") + try: + lifecycle_authority = await self._fact_lifecycle.authority_for(principal_id, runtime_profile_id) + except FactLifecycleAccessDenied as exc: + raise WorkshopMemoryAccessDenied("Memory access denied") from exc + save_id = f"agent-save-{uuid.uuid4().hex}" + now_value = datetime.now(UTC) + lock = self._mutation_locks.setdefault(principal_id, asyncio.Lock()) + async with lock: + mutation = await self._fact_lifecycle.create( + lifecycle_authority, + FactRevisionInput( + content=cleaned_content, + scope_kind=str(scope), + scope_key=str(project_id) if scope == memory.SCOPE_PROJECT else "", + reason="Fact saved deliberately by the owner's agent.", + evidence=({"kind": "agent", "reference_id": save_id, "sha256": None},), + vector_metadata={**vector_metadata, "tags": list(cleaned_tags)}, + confidence=float(confidence), + asserted_at=now_value, + observed_at=now_value, + valid_from=now_value, + ), + idempotency_key=f"workshop-memory:agent-save:{principal_id}:{runtime_profile_id}:{save_id}", + stable_claim_key=save_id, + ) + memory_id = mutation.memory_id + if not isinstance(memory_id, str) or not memory_id or mutation.projection_status != "succeeded": + raise WorkshopMemoryMutationFailed("The fact was saved but its search projection is pending; it is retried") + return memory_id + + async def forget_all_for_agent( + self, + *, + principal_id: PrincipalId, + runtime_profile_id: RuntimeProfileId, + ) -> AgentForgetAllResult: + """ + Forget every current fact of one owner, keeping its history. + + Deleting vector rows directly would leave every canonical claim + active with a projection that points at a row that no longer + exists: recall would lose the facts while history and install + status still counted them as current. Instead each active claim is + retracted through the lifecycle, which removes it from recall, + keeps it restorable, and records why. Legacy rows, which have no + canonical claim, are then deleted from the vector store. + + Claims in an unresolved conflict are already out of recall and + need the owner's decision, and canonical episodes are immutable + history, so both are kept and counted rather than touched. + + Raises: + WorkshopMemoryAccessDenied: The runtime profile is not the + principal's. + WorkshopMemoryMutationFailed: The vector store could not be + read to find legacy rows. + """ + try: + lifecycle_authority = await self._fact_lifecycle.authority_for(principal_id, runtime_profile_id) + except FactLifecycleAccessDenied as exc: + raise WorkshopMemoryAccessDenied("Memory access denied") from exc + operation_id = uuid.uuid4().hex + retracted = projection_failed = 0 + lock = self._mutation_locks.setdefault(principal_id, asyncio.Lock()) + async with lock: + async with self._store.connection.execute( + "SELECT c.claim_id, s.revision_id FROM memory_fact_claims c " + "JOIN memory_fact_revision_states s ON s.claim_id = c.claim_id " + "WHERE c.owner_principal_id = ? AND c.runtime_profile_id = ? AND s.state = 'active' " + "ORDER BY c.claim_id", + (str(principal_id), str(runtime_profile_id)), + ) as cursor: + active = [(str(row[0]), str(row[1])) for row in await cursor.fetchall()] + for claim_id, revision_id in active: + result = await self._fact_lifecycle.retract( + lifecycle_authority, + MemoryClaimId(claim_id), + MemoryRevisionId(revision_id), + reason="Forgotten with every other memory at the owner's request.", + idempotency_key=( + f"workshop-memory:forget-all:{principal_id}:{runtime_profile_id}:{operation_id}:{claim_id}" + ), + ) + retracted += 1 + if result.projection_status != "succeeded": + # The claim is retracted canonically; its vector row + # stays until the failed delete is retried. Counting it + # keeps the response honest about what recall shows now. + projection_failed += 1 + async with self._store.connection.execute( + "SELECT COUNT(DISTINCT c.claim_id) FROM memory_fact_claims c " + "JOIN memory_fact_revision_states s ON s.claim_id = c.claim_id " + "WHERE c.owner_principal_id = ? AND c.runtime_profile_id = ? AND s.state = 'unresolved_conflict'", + (str(principal_id), str(runtime_profile_id)), + ) as cursor: + row = await cursor.fetchone() + kept_conflicts = int(row[0]) if row is not None else 0 + async with self._store.connection.execute( + "SELECT COUNT(*) FROM memory_episodes WHERE owner_principal_id = ? AND runtime_profile_id = ?", + (str(principal_id), str(runtime_profile_id)), + ) as cursor: + row = await cursor.fetchone() + kept_episodes = int(row[0]) if row is not None else 0 + try: + rows = await asyncio.to_thread( + memory.get_all_for_lifecycle_projection, + user_id=str(principal_id), + runtime_profile_id=str(runtime_profile_id), + ) + except Exception as exc: + raise WorkshopMemoryMutationFailed("The search index could not be read") from exc + legacy_deleted = 0 + for item in rows: + # Rows carrying a canonical id belong to the lifecycle: the + # retractions above removed the current ones, and anything + # left is a pending projection the retry will settle. + if item.metadata.get(CANONICAL_CLAIM_ID_KEY) or item.metadata.get(CANONICAL_EPISODE_ID_KEY): + continue + deleted = await asyncio.to_thread( + memory.delete_by_id_for_lifecycle_projection, + user_id=str(principal_id), + memory_id=item.id, + runtime_profile_id=str(runtime_profile_id), + ) + if deleted: + legacy_deleted += 1 + log.info( + "Forgot all memory for %s/%s: retracted=%d, projection_failed=%d, legacy_deleted=%d, " + "kept_conflicts=%d, kept_episodes=%d", + principal_id, + runtime_profile_id, + retracted, + projection_failed, + legacy_deleted, + kept_conflicts, + kept_episodes, + ) + return AgentForgetAllResult( + retracted=retracted, + projection_failed=projection_failed, + legacy_deleted=legacy_deleted, + kept_conflicts=kept_conflicts, + kept_episodes=kept_episodes, + ) + async def edit( self, authority: MemoryQueryAuthority, @@ -2387,6 +2634,19 @@ async def retry_projections( runtime_profile_id=RuntimeProfileId(runtime_profile_id), episode_ids=None if everything else tuple(MemoryEpisodeId(item) for item in episode_ids or ()), ) + if facts.retried or episodes.retried: + # A retry changes which rows the store should hold, so the + # stored audit install status reads is refreshed with it. The + # retry result stands even if this read fails. + try: + await asyncio.to_thread( + refresh_vector_audit, + Path(self._config.session_db_path), + principal_id=str(authority.principal_id), + runtime_profile_id=runtime_profile_id, + ) + except Exception: + log.warning("Vector audit after projection retry failed", exc_info=True) return ProjectionRetryResult( facts.retried + episodes.retried, facts.succeeded + episodes.succeeded, @@ -2411,7 +2671,17 @@ async def audit_projections(self, authority: MemoryQueryAuthority) -> VectorAudi except Exception as exc: raise WorkshopMemoryMutationFailed("The search index could not be read") from exc facts, episodes = await expected_rows_async(self._store.connection, owner) - return audit_vector_rows(rows, current_facts=facts, current_episodes=episodes) + audit = audit_vector_rows(rows, current_facts=facts, current_episodes=episodes) + # The owner just paid for a full read, so install status gets the + # fresh counts too. + await asyncio.to_thread( + store_vector_audit, + Path(self._config.session_db_path), + audit, + principal_id=owner[0], + runtime_profile_id=owner[1], + ) + return audit async def unresolved_conflict_count(self, authority: MemoryQueryAuthority) -> int: """Count the owner's conflicted claims; zero when no runtime profile is unambiguous.""" diff --git a/src/kai/workshop/schema.py b/src/kai/workshop/schema.py index fe8defc7..3bbf0fd1 100644 --- a/src/kai/workshop/schema.py +++ b/src/kai/workshop/schema.py @@ -6,7 +6,7 @@ import aiosqlite -WORKSHOP_SCHEMA_VERSION = 95 +WORKSHOP_SCHEMA_VERSION = 96 @dataclass(frozen=True, slots=True) @@ -4607,6 +4607,30 @@ class SchemaMigration: ), ) +# The last vector-store audit per owner. Install status runs as root and +# must not open the service-owned vector store (its rows are unpickled), +# so the service audits each owner at startup and after projection +# retries, and install status reads the stored counts with their age, +# the same way it reads the legacy census. +_MEMORY_VECTOR_AUDIT_SCHEMA = SchemaMigration( + version=96, + name="memory_vector_audit", + statements=( + """ + CREATE TABLE memory_vector_audit ( + principal_id TEXT NOT NULL CHECK (length(principal_id) BETWEEN 1 AND 128), + runtime_profile_id TEXT NOT NULL CHECK (length(runtime_profile_id) BETWEEN 1 AND 128), + orphan_rows INTEGER NOT NULL CHECK (orphan_rows >= 0), + unknown_rows INTEGER NOT NULL CHECK (unknown_rows >= 0), + duplicate_items INTEGER NOT NULL CHECK (duplicate_items >= 0), + missing_rows INTEGER NOT NULL CHECK (missing_rows >= 0), + checked_at TEXT NOT NULL, + PRIMARY KEY (principal_id, runtime_profile_id) + ) + """, + ), +) + _MIGRATIONS = ( _INITIAL_SCHEMA, _DELIVERY_SCHEMA, @@ -4703,6 +4727,7 @@ class SchemaMigration: _MEMORY_ADMISSION_AUTHORITY_SCHEMA, _MEMORY_RECONCILIATION_RESUME_SCHEMA, _MEMORY_TRIAGE_CONSOLIDATION_SCHEMA, + _MEMORY_VECTOR_AUDIT_SCHEMA, ) diff --git a/src/kai/workshop/static/app.js b/src/kai/workshop/static/app.js index 63275c2e..cadabdc9 100644 --- a/src/kai/workshop/static/app.js +++ b/src/kai/workshop/static/app.js @@ -6,7 +6,7 @@ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r= `+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{ue=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?le(n):``}function K(e,t){switch(e.tag){case 26:case 27:case 5:return le(e.type);case 16:return le(`Lazy`);case 13:return e.child!==t&&t!==null?le(`Suspense Fallback`):le(`Suspense`);case 19:return le(`SuspenseList`);case 0:case 15:return G(e.type,!1);case 11:return G(e.type.render,!1);case 1:return G(e.type,!0);case 31:return le(`Activity`);default:return``}}function q(e){try{var t=``,n=null;do t+=K(e,n),n=e,e=e.return;while(e);return t}catch(e){return` Error generating stack: `+e.message+` `+e.stack}}var de=Object.prototype.hasOwnProperty,J=t.unstable_scheduleCallback,Y=t.unstable_cancelCallback,fe=t.unstable_shouldYield,pe=t.unstable_requestPaint,me=t.unstable_now,he=t.unstable_getCurrentPriorityLevel,X=t.unstable_ImmediatePriority,ge=t.unstable_UserBlockingPriority,_e=t.unstable_NormalPriority,ve=t.unstable_LowPriority,ye=t.unstable_IdlePriority,be=t.log,xe=t.unstable_setDisableYieldValue,Se=null,Ce=null;function we(e){if(typeof be==`function`&&xe(e),Ce&&typeof Ce.setStrictMode==`function`)try{Ce.setStrictMode(Se,e)}catch{}}var Te=Math.clz32?Math.clz32:Oe,Ee=Math.log,De=Math.LN2;function Oe(e){return e>>>=0,e===0?32:31-(Ee(e)/De|0)|0}var ke=256,Ae=262144,je=4194304;function Me(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Ne(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=Me(n))):i=Me(o):i=Me(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=Me(n))):i=Me(o)):i=Me(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function Pe(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Fe(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Ie(){var e=je;return je<<=1,!(je&62914560)&&(je=4194304),e}function Le(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Re(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function ze(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),Xt=!1;if(Yt)try{var Zt={};Object.defineProperty(Zt,"passive",{get:function(){Xt=!0}}),window.addEventListener(`test`,Zt,Zt),window.removeEventListener(`test`,Zt,Zt)}catch{Xt=!1}var Qt=null,$t=null,en=null;function tn(){if(en)return en;var e,t=$t,n=t.length,r,i=`value`in Qt?Qt.value:Qt.textContent,a=i.length;for(e=0;e=Pn),Ln=` `,Rn=!1;function zn(e,t){switch(e){case`keyup`:return Mn.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Bn(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Vn=!1;function Hn(e,t){switch(e){case`compositionend`:return Bn(t);case`keypress`:return t.which===32?(Rn=!0,Ln):null;case`textInput`:return e=t.data,e===Ln&&Rn?null:e;default:return null}}function Un(e,t){if(Vn)return e===`compositionend`||!Nn&&zn(e,t)?(e=tn(),en=$t=Qt=null,Vn=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=dr(n)}}function pr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?pr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function mr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Ct(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Ct(e.document)}return t}function hr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var gr=Yt&&`documentMode`in document&&11>=document.documentMode,_r=null,vr=null,yr=null,br=!1;function xr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;br||_r==null||_r!==Ct(r)||(r=_r,`selectionStart`in r&&hr(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),yr&&ur(yr,r)||(yr=r,r=Td(vr,`onSelect`),0>=o,i-=o,pi=1<<32-Te(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),Si&&hi(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),Si&&hi(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return Si&&hi(a,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),Si&&hi(a,g),u}function b(e,r,o,c){if(typeof o==`object`&&o&&o.type===y&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case _:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===y){if(r.tag===7){n(e,r.sibling),c=a(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===O&&ma(l)===r.type){n(e,r.sibling),c=a(r,o.props),xa(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===y?(c=ei(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=$r(o.type,o.key,o.props,null,e.mode,c),xa(c,o),c.return=e,e=c)}return s(e);case v:a:{for(l=o.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=a(r,o.children||[]),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}c=ri(o,e.mode,c),c.return=e,e=c}return s(e);case O:return o=ma(o),b(e,r,o,c)}if(F(o))return h(e,r,o,c);if(M(o)){if(l=M(o),typeof l!=`function`)throw Error(i(150));return o=l.call(o),g(e,r,o,c)}if(typeof o.then==`function`)return b(e,r,ba(o),c);if(o.$$typeof===C)return b(e,r,Ui(e,o),c);Sa(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=a(r,o),c.return=e,e=c):(n(e,r),c=ti(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{ya=0;var i=b(e,t,n,r);return va=null,i}catch(t){if(t===ca||t===ua)throw t;var a=Yr(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var wa=Ca(!0),Ta=Ca(!1),Ea=!1;function Da(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Oa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function ka(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Aa(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,jl&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=Kr(e),Gr(e,null,n),t}return Hr(e,r,t,n),Kr(e)}function ja(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ve(e,n)}}function Ma(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Na=!1;function Pa(){if(Na){var e=ea;if(e!==null)throw e}}function Fa(e,t,n,r){Na=!1;var i=e.updateQueue;Ea=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(Pl&f)===f:(r&f)===f){f!==0&&f===$i&&(Na=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var h=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(h=g.payload,typeof h==`function`){d=h.call(_,d,f);break a}d=h;break a;case 3:h.flags=h.flags&-65537|128;case 0:if(h=g.payload,f=typeof h==`function`?h.call(_,d,f):h,f==null)break a;d=m({},d,f);break a;case 2:Ea=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),Hl|=o,e.lanes=o,e.memoizedState=d}}function Ia(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function La(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=I.T,s={};I.T=s,ws(e,!1,t,n);try{var c=i(),l=I.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Cs(e,t,ra(c,r),uu(e)):Cs(e,t,r,uu(e))}catch(n){Cs(e,t,{then:function(){},status:`rejected`,reason:n},uu())}finally{L.p=a,o!==null&&s.types!==null&&(o.types=s.types),I.T=o}}function ps(){}function ms(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=hs(e).queue;fs(e,a,t,R,n===null?ps:function(){return gs(e),n(r)})}function hs(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:R,baseState:R,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:To,lastRenderedState:R},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:To,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function gs(e){var t=hs(e);t.next===null&&(t=e.alternate.memoizedState),Cs(e,t.next.queue,{},uu())}function _s(){return Hi(Qf)}function vs(){return bo().memoizedState}function ys(){return bo().memoizedState}function bs(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=uu();e=ka(n);var r=Aa(t,e,n);r!==null&&(fu(r,t,n),ja(r,t,n)),t={cache:Yi()},e.payload=t;return}t=t.return}}function xs(e,t,n){var r=uu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Ts(e)?Es(t,n):(n=Ur(e,t,n,r),n!==null&&(fu(n,e,r),Ds(n,t,r)))}function Ss(e,t,n){Cs(e,t,n,uu())}function Cs(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ts(e))Es(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,lr(s,o))return Hr(e,t,i,0),Ml===null&&Vr(),!1}catch{}if(n=Ur(e,t,i,r),n!==null)return fu(n,e,r),Ds(n,t,r),!0}return!1}function ws(e,t,n,r){if(r={lane:2,revertLane:ld(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Ts(e)){if(t)throw Error(i(479))}else t=Ur(e,n,r,2),t!==null&&fu(t,e,2)}function Ts(e){var t=e.alternate;return e===$a||t!==null&&t===$a}function Es(e,t){ro=no=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Ds(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ve(e,n)}}var Os={readContext:Hi,use:Co,useCallback:lo,useContext:lo,useEffect:lo,useImperativeHandle:lo,useLayoutEffect:lo,useInsertionEffect:lo,useMemo:lo,useReducer:lo,useRef:lo,useState:lo,useDebugValue:lo,useDeferredValue:lo,useTransition:lo,useSyncExternalStore:lo,useId:lo,useHostTransitionStatus:lo,useFormState:lo,useActionState:lo,useOptimistic:lo,useMemoCache:lo,useCacheRefresh:lo};Os.useEffectEvent=lo;var ks={readContext:Hi,use:Co,useCallback:function(e,t){return yo().memoizedState=[e,t===void 0?null:t],e},useContext:Hi,useEffect:$o,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),Zo(4194308,4,as.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Zo(4194308,4,e,t)},useInsertionEffect:function(e,t){Zo(4,2,e,t)},useMemo:function(e,t){var n=yo();t=t===void 0?null:t;var r=e();if(io){we(!0);try{e()}finally{we(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=yo();if(n!==void 0){var i=n(t);if(io){we(!0);try{n(t)}finally{we(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=xs.bind(null,$a,e),[r.memoizedState,e]},useRef:function(e){var t=yo();return e={current:e},t.memoizedState=e},useState:function(e){e=Fo(e);var t=e.queue,n=Ss.bind(null,$a,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:ss,useDeferredValue:function(e,t){return us(yo(),e,t)},useTransition:function(){var e=Fo(!1);return e=fs.bind(null,$a,e.queue,!0,!1),yo().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=$a,a=yo();if(Si){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Ml===null)throw Error(i(349));Pl&127||Ao(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,$o(Mo.bind(null,r,o,e),[e]),r.flags|=2048,Yo(9,{destroy:void 0},jo.bind(null,r,o,n,t),null),n},useId:function(){var e=yo(),t=Ml.identifierPrefix;if(Si){var n=mi,r=pi;n=(r&~(1<<32-Te(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=ao++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(a,{is:r.is}):s.createElement(a)}}o[qe]=t,o[Je]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(Pd(o,a,r),a){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&Cc(t)}}return Oc(t),wc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Cc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=ne.current,Oi(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=bi,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[qe]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||jd(e.nodeValue,n)),e||Ti(t,!0)}else e=Bd(e).createTextNode(r),e[qe]=t,t.stateNode=e}return Oc(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Oi(t),n!==null){if(e===null){if(!r)throw Error(i(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(557));e[qe]=t}else ki(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Oc(t),e=!1}else n=Ai(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(Ya(t),t):(Ya(t),null);if(t.flags&128)throw Error(i(558))}return Oc(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=Oi(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(i(318));if(a=t.memoizedState,a=a===null?null:a.dehydrated,!a)throw Error(i(317));a[qe]=t}else ki(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Oc(t),a=!1}else a=Ai(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(Ya(t),t):(Ya(t),null)}return Ya(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,a=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(a=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==a&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Ec(t,t.updateQueue),Oc(t),null);case 4:return ie(),e===null&&xd(t.stateNode.containerInfo),Oc(t),null;case 10:return Ii(t.type),Oc(t),null;case 19:if(V(Xa),r=t.memoizedState,r===null)return Oc(t),null;if(a=!!(t.flags&128),o=r.rendering,o===null){if(a)Dc(r,!1);else{if(Vl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=Za(e),o!==null){for(t.flags|=128,Dc(r,!1),e=o.updateQueue,t.updateQueue=e,Ec(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)Qr(n,e),n=n.sibling;return H(Xa,Xa.current&1|2),Si&&hi(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&me()>Ql&&(t.flags|=128,a=!0,Dc(r,!1),t.lanes=4194304)}}else{if(!a){if(e=Za(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Ec(t,e),Dc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!Si)return Oc(t),null}else 2*me()-r.renderingStartTime>Ql&&n!==536870912&&(t.flags|=128,a=!0,Dc(r,!1),t.lanes=4194304)}r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(Oc(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=me(),e.sibling=null,n=Xa.current,H(Xa,a?n&1|2:n&1),Si&&hi(t,r.treeForkCount),e);case 22:case 23:return Ya(t),Ha(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Oc(t),t.subtreeFlags&6&&(t.flags|=8192)):Oc(t),n=t.updateQueue,n!==null&&Ec(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&V(aa),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Ii(Ji),Oc(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function Ac(e,t){switch(vi(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ii(Ji),ie(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return oe(t),null;case 31:if(t.memoizedState!==null){if(Ya(t),t.alternate===null)throw Error(i(340));ki()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(Ya(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));ki()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return V(Xa),null;case 4:return ie(),null;case 10:return Ii(t.type),null;case 22:case 23:return Ya(t),Ha(),e!==null&&V(aa),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Ii(Ji),null;case 25:return null;default:return null}}function jc(e,t){switch(vi(t),t.tag){case 3:Ii(Ji),ie();break;case 26:case 27:case 5:oe(t);break;case 4:ie();break;case 31:t.memoizedState!==null&&Ya(t);break;case 13:Ya(t);break;case 19:V(Xa);break;case 10:Ii(t.type);break;case 22:case 23:Ya(t),Ha(),e!==null&&V(aa);break;case 24:Ii(Ji)}}function Mc(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){Hu(t,t.return,e)}}function Nc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){Hu(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Hu(t,t.return,e)}}function Pc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{La(t,n)}catch(t){Hu(e,e.return,t)}}}function Fc(e,t,n){n.props=Is(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Hu(e,t,n)}}function Ic(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){Hu(e,t,n)}}function Lc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){Hu(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){Hu(e,t,n)}else n.current=null}}function Rc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){Hu(e,e.return,t)}}function zc(e,t,n){try{var r=e.stateNode;Fd(r,e.type,n,t),r[Je]=t}catch(t){Hu(e,e.return,t)}}function Bc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Zd(e.type)||e.tag===4}function Vc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Bc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&Zd(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Hc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Bt));else if(r!==4&&(r===27&&Zd(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Hc(e,t,n),e=e.sibling;e!==null;)Hc(e,t,n),e=e.sibling}function Uc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&Zd(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(Uc(e,t,n),e=e.sibling;e!==null;)Uc(e,t,n),e=e.sibling}function Wc(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Pd(t,r,n),t[qe]=e,t[Je]=n}catch(t){Hu(e,e.return,t)}}var Gc=!1,Kc=!1,qc=!1,Jc=typeof WeakSet==`function`?WeakSet:Set,Yc=null;function Xc(e,t){if(e=e.containerInfo,Rd=sp,e=mr(e),hr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(zd={focusedElem:e,selectionRange:n},sp=!1,Yc=t;Yc!==null;)if(t=Yc,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,Yc=e;else for(;Yc!==null;){switch(t=Yc,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),Pd(o,r,n),o[qe]=e,ot(o),r=o;break a;case`link`:var s=Vf(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=fr(s,h),v=fr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,I.T=null,n=ou,ou=null;var o=nu,s=iu;if(tu=0,ru=nu=null,iu=0,jl&6)throw Error(i(331));var c=jl;if(jl|=4,El(o.current),vl(o,o.current,s,n),jl=c,nd(0,!1),Ce&&typeof Ce.onPostCommitFiberRoot==`function`)try{Ce.onPostCommitFiberRoot(Se,o)}catch{}return!0}finally{L.p=a,I.T=r,Ru(e,t)}}function Vu(e,t,n){t=ai(n,t),t=Hs(e.stateNode,t,2),e=Aa(e,t,2),e!==null&&(Re(e,2),td(e))}function Hu(e,t,n){if(e.tag===3)Vu(e,e,n);else for(;t!==null;){if(t.tag===3){Vu(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(eu===null||!eu.has(r))){e=ai(n,e),n=Us(2),r=Aa(t,n,2),r!==null&&(Ws(n,r,t,e),Re(r,2),td(r));break}}t=t.return}}function Uu(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Al;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(zl=!0,i.add(n),e=Wu.bind(null,e,t,n),t.then(e,e))}function Wu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Ml===e&&(Pl&n)===n&&(Vl===4||Vl===3&&(Pl&62914560)===Pl&&300>me()-Xl?!(jl&2)&&yu(e,0):Wl|=n,Kl===Pl&&(Kl=0)),td(e)}function Gu(e,t){t===0&&(t=Ie()),e=Wr(e,t),e!==null&&(Re(e,t),td(e))}function Ku(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Gu(e,n)}function qu(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}r!==null&&r.delete(t),Gu(e,n)}function Ju(e,t){return J(e,t)}var Yu=null,Xu=null,Zu=!1,Qu=!1,$u=!1,ed=0;function td(e){e!==Xu&&e.next===null&&(Xu===null?Yu=Xu=e:Xu=Xu.next=e),Qu=!0,Zu||(Zu=!0,cd())}function nd(e,t){if(!$u&&Qu){$u=!0;do for(var n=!1,r=Yu;r!==null;){if(!t){if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Te(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,sd(r,a))}else a=Pl,a=Ne(r,r===Ml?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||Pe(r,a)||(n=!0,sd(r,a))}r=r.next}while(n);$u=!1}}function rd(){id()}function id(){Qu=Zu=!1;var e=0;ed!==0&&Gd()&&(e=ed);for(var t=me(),n=null,r=Yu;r!==null;){var i=r.next,a=ad(r,t);a===0?(r.next=null,n===null?Yu=i:n.next=i,i===null&&(Xu=n)):(n=r,(e!==0||a&3)&&(Qu=!0)),r=i}tu!==0&&tu!==5||nd(e,!1),ed!==0&&(ed=0)}function ad(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Id(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function xf(e,t,n){var r=bf;if(r&&typeof t==`string`&&t){var i=Tt(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),hf.has(i)||(hf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Pd(t,`link`,e),ot(t),r.head.appendChild(t)))}}function Sf(e){_f.D(e),xf(`dns-prefetch`,e,null)}function Cf(e,t){_f.C(e,t),xf(`preconnect`,e,t)}function wf(e,t,n){_f.L(e,t,n);var r=bf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Tt(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Tt(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Tt(n.imageSizes)+`"]`)):i+=`[href="`+Tt(e)+`"]`;var a=i;switch(t){case`style`:a=Af(e);break;case`script`:a=Pf(e)}mf.has(a)||(e=m({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),mf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(jf(a))||t===`script`&&r.querySelector(Ff(a))||(t=r.createElement(`link`),Pd(t,`link`,e),ot(t),r.head.appendChild(t)))}}function Tf(e,t){_f.m(e,t);var n=bf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Tt(r)+`"][href="`+Tt(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Pf(e)}if(!mf.has(a)&&(e=m({rel:`modulepreload`,href:e},t),mf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(Ff(a)))return}r=n.createElement(`link`),Pd(r,`link`,e),ot(r),n.head.appendChild(r)}}}function Ef(e,t,n){_f.S(e,t,n);var r=bf;if(r&&e){var i=at(r).hoistableStyles,a=Af(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(jf(a)))s.loading=5;else{e=m({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=mf.get(a))&&Rf(e,n);var c=o=r.createElement(`link`);ot(c),Pd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Lf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Df(e,t){_f.X(e,t);var n=bf;if(n&&e){var r=at(n).hoistableScripts,i=Pf(e),a=r.get(i);a||(a=n.querySelector(Ff(i)),a||(e=m({src:e,async:!0},t),(t=mf.get(i))&&zf(e,t),a=n.createElement(`script`),ot(a),Pd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Of(e,t){_f.M(e,t);var n=bf;if(n&&e){var r=at(n).hoistableScripts,i=Pf(e),a=r.get(i);a||(a=n.querySelector(Ff(i)),a||(e=m({src:e,async:!0,type:`module`},t),(t=mf.get(i))&&zf(e,t),a=n.createElement(`script`),ot(a),Pd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function kf(e,t,n,r){var a=(a=ne.current)?gf(a):null;if(!a)throw Error(i(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=Af(n.href),n=at(a).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Af(n.href);var o=at(a).hoistableStyles,s=o.get(e);if(s||(a=a.ownerDocument||a,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=a.querySelector(jf(e)))&&!o._p&&(s.instance=o,s.state.loading=5),mf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},mf.set(e,n),o||Nf(a,e,n,s.state))),t&&r===null)throw Error(i(528,``));return s}if(t&&r!==null)throw Error(i(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Pf(n),n=at(a).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(i(444,e))}}function Af(e){return`href="`+Tt(e)+`"`}function jf(e){return`link[rel="stylesheet"][`+e+`]`}function Mf(e){return m({},e,{"data-precedence":e.precedence,precedence:null})}function Nf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),Pd(t,`link`,n),ot(t),e.head.appendChild(t))}function Pf(e){return`[src="`+Tt(e)+`"]`}function Ff(e){return`script[async]`+e}function If(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Tt(n.href)+`"]`);if(r)return t.instance=r,ot(r),r;var a=m({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),ot(r),Pd(r,`style`,a),Lf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Af(n.href);var o=e.querySelector(jf(a));if(o)return t.state.loading|=4,t.instance=o,ot(o),o;r=Mf(n),(a=mf.get(a))&&Rf(r,a),o=(e.ownerDocument||e).createElement(`link`),ot(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Pd(o,`link`,r),t.state.loading|=4,Lf(o,n.precedence,e),t.instance=o;case`script`:return o=Pf(n.src),(a=e.querySelector(Ff(o)))?(t.instance=a,ot(a),a):(r=n,(a=mf.get(o))&&(r=m({},n),zf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),ot(a),Pd(a,`link`,r),e.head.appendChild(a),t.instance=a);case`void`:return null;default:throw Error(i(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Lf(r,n.precedence,e));return t.instance}function Lf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function Uf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Wf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Gf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Af(r.href),a=t.querySelector(jf(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Jf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,ot(a);return}a=t.ownerDocument||t,r=Mf(r),(i=mf.get(i))&&Rf(r,i),a=a.createElement(`link`),ot(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Pd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=Jf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Kf=0;function qf(e,t){return e.stylesheets&&e.count===0&&Xf(e,e.stylesheets),0Kf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Jf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Xf(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Yf=null;function Xf(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Yf=new Map,t.forEach(Zf,e),Yf=null,Jf.call(e))}function Zf(e,t){if(!(t.state.loading&4)){var n=Yf.get(e);if(n)var r=n.get(null);else{n=new Map,Yf.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=g()})),v=d(),y=_(),b=/^chn_[0-9a-f]{32}$/,x=/^agt_[0-9a-f]{32}$/,S=/^adf_[0-9a-f]{32}$/,C=/^apv_[0-9a-f]{32}$/,w=/^adr_[0-9a-f]{32}$/,T=/^aen_[0-9a-f]{32}$/,E=/^prn_[0-9a-f]{32}$/,D=/^rtp_[0-9a-f]{32}$/,O=/^wsp_[0-9a-f]{32}$/,k=/^art_[0-9a-f]{32}$/,A=/^msg_[0-9a-f]{32}$/,j=/^ntf_[0-9a-f]{32}$/,M=/^[a-z][a-z0-9_]{0,31}$/,N=`atom-one-dark`,P=[{colorScheme:`dark`,displayName:`Atom One Dark`,themeId:N},{colorScheme:`light`,displayName:`Atom One Light`,themeId:`atom-one-light`},{colorScheme:`dark`,displayName:`Dracula`,themeId:`dracula`},{colorScheme:`dark`,displayName:`Nord`,themeId:`nord`},{colorScheme:`dark`,displayName:`Solarized Dark`,themeId:`solarized-dark`},{colorScheme:`light`,displayName:`Solarized Light`,themeId:`solarized-light`},{colorScheme:`dark`,displayName:`Catppuccin Mocha`,themeId:`catppuccin-mocha`},{colorScheme:`light`,displayName:`Catppuccin Latte`,themeId:`catppuccin-latte`},{colorScheme:`light`,displayName:`GitHub Light Default`,themeId:`github-light-default`},{colorScheme:`dark`,displayName:`GitHub Dark Default`,themeId:`github-dark-default`},{colorScheme:`dark`,displayName:`GitHub Dark Dimmed`,themeId:`github-dark-dimmed`}],F=`kai.workshop.theme-hint.v1`,I=new Map(P.map(e=>[e.themeId,e]));function L(e){return typeof e==`string`&&I.has(e)}function R(e,t=!0){let n=L(e)?e:N,r=I.get(n);if(!r)throw Error(`The default Workshop theme is unavailable.`);if(document.documentElement.dataset.workshopTheme=n,document.documentElement.style.colorScheme=r.colorScheme,t)try{sessionStorage.setItem(F,n)}catch{}return n}function ee(){try{return R(sessionStorage.getItem(F),!1)}catch{return R(N,!1)}}function z(){try{sessionStorage.removeItem(F)}catch{}R(N,!1)}var B=class extends Error{},V=class extends Error{},H=class extends Error{},te=class extends Error{},U=class extends Error{},ne=class extends Error{currentRevision;constructor(e,t){super(e),this.currentRevision=t}},re=class extends Error{currentRevision;constructor(e,t){super(e),this.currentRevision=t}},W=class extends Error{},ie=class extends Error{},ae=class extends Error{currentRevision;constructor(e,t){super(e),this.currentRevision=t}},oe=new Set([`thumbs_up`,`thumbs_down`,`heart`,`laugh`,`celebrate`,`eyes`,`check`,`thinking`,`surprised`,`sad`,`fire`,`question`]);function se(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!K(n))return null;let{count:e,reacted_by_viewer:r,reaction:i}=n;if(typeof i!=`string`||!oe.has(i)||!Number.isSafeInteger(e)||e<1||typeof r!=`boolean`)return null;t.push({count:e,reactedByViewer:r,reaction:i})}return t}var ce=new Set([`public`,`principal`,`conversation`,`principal_agent`,`agent_owner`,`channel_member`,`channel_owner`,`administrator`]),le=new Set([`native_surface`,`action_palette`,`administrator_only`,`presentation_alias`,`compatibility_only`]),ue=new Set([`none`,`context_dependent`,`required`]);function G(e){if(!K(e))return null;let{available:t,confirmation:n,description:r,disposition:i,input_shape:a,label:o,mutates_state:s,operation_id:c,palette_entry:l,scope:u,surface:d,unavailable_reason:f}=e;return t!==!0||typeof n!=`string`||!ue.has(n)||typeof r!=`string`||typeof i!=`string`||!le.has(i)||typeof a!=`string`||typeof o!=`string`||typeof s!=`boolean`||typeof c!=`string`||!/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)+$/.test(c)||typeof l!=`boolean`||typeof u!=`string`||!ce.has(u)||d!==null&&typeof d!=`string`||f!==null?null:{available:t,confirmation:n,description:r,disposition:i,inputShape:a,label:o,mutatesState:s,operationId:c,paletteEntry:l,scope:u,surface:d,unavailableReason:f}}function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q(){return{active:!1,stateVersion:0,url:null}}function de(e,t){if(!K(e))return q();let{active:n,state_version:r,url:i}=e;return typeof n!=`boolean`||!Number.isSafeInteger(r)||r<0||n&&r<1||(n?i!==`/v1/principals/${t}/avatar/${r}`:i!==null)?q():{active:n,stateVersion:r,url:i}}function J(e,t){if(!K(e)||!K(e.error))return t;let n=e.error.message;return typeof n==`string`&&n.length<=200?n:t}async function Y(e){try{return await e.json()}catch{return null}}var fe=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,pe=null;function me(){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function he(){return pe!==null&&fe.test(pe)||(pe=me()),pe}async function X(e,t,n={}){let r=new Headers(n.headers);r.set(`Authorization`,`Bearer ${e.token}`);let i=await fetch(t,{...n,cache:`no-store`,headers:r});if(i.status===401)throw new B(`This Workshop session expired or was revoked.`);if(i.status===403)throw new V(`This session cannot access that Workshop channel.`);return i}function ge(e,t){if(!K(e))return null;let{author_display_name:n,author_avatar:r,author_kind:i,author_principal_id:a,body:o,channel_id:s,created_at:c,event_position:l,latest_reply_at:u,message_id:d,reply_count:f,reply_participant_count:p,reply_participants:m,reply_to_message_id:h,thread_root_id:g,mentions:_,reactions:v,artifacts:y,standing_contribution:b,source_run_id:x}=e,S=b??!1,C=x??null,w=y??[],T=v??[];if(typeof n!=`string`||typeof i!=`string`||typeof a!=`string`||!E.test(a)||typeof o!=`string`||s!==t||typeof c!=`string`||!Number.isSafeInteger(l)||typeof d!=`string`||!A.test(d)||!Number.isSafeInteger(f)||f<0||!Number.isSafeInteger(p)||p<0||!Array.isArray(m)||m.length>3||pj)return null;O.push({kind:t,length:n,principalId:r,start:i}),M=i+n}let N=se(T);if(N===null)return null;let P=[];for(let e of m){if(!K(e))return null;let{avatar:t,display_name:n,kind:r,principal_id:i}=e;if(typeof i!=`string`||!E.test(i)||r!==`human`&&r!==`agent`||typeof n!=`string`||!n.trim())return null;P.push({avatar:r===`human`?de(t,i):null,displayName:n,kind:r,principalId:i})}return{artifacts:D,authorAvatar:i===`human`?de(r,a):null,authorDisplayName:n,authorKind:i,authorPrincipalId:a,body:o,channelId:t,createdAt:c,eventPosition:l,mentions:O,messageId:d,reactions:N,replyCount:f,replyParticipantCount:p,replyParticipants:P,replyToMessageId:h,latestReplyAt:u,threadRootId:g,standingContribution:S,sourceRunId:C}}var _e=new Set([`accepted`,`started`,`completed`,`failed`,`cancelled`]),ve=new Set([`run.accepted`,`run.started`,`run.cancellation_requested`,`run.completed`,`run.failed`,`run.cancelled`]);function ye(e,t){if(!K(e))return null;let{accepted_at:n,agent_id:r,cancellation_requested_at:i,channel_id:a,inbound_message_id:o,kind:s,result_message_id:c,run_id:l,started_at:u,status:d,terminal_at:f,terminal_code:p}=e;return typeof n!=`string`||typeof r!=`string`||!x.test(r)||i!==null&&typeof i!=`string`||a!==t||typeof o!=`string`||!A.test(o)||s!==`respond`&&s!==`observe`||c!==null&&typeof c!=`string`||typeof l!=`string`||u!==null&&typeof u!=`string`||typeof d!=`string`||!_e.has(d)||f!==null&&typeof f!=`string`||p!==null&&typeof p!=`string`?null:{acceptedAt:n,agentId:r,cancellationRequestedAt:i,channelId:t,inboundMessageId:o,kind:s,resultMessageId:c,runId:l,startedAt:u,status:d,terminalAt:f,terminalCode:p}}async function be(e,t){let n=await fetch(`/v1/client/enrollment/redeem`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({device_display_name:t,enrollment_token:e}),cache:`no-store`}),r=await Y(n);if(!n.ok||!K(r)||!K(r.session)||typeof r.session.token!=`string`||r.session.token.length===0)throw Error(J(r,`Enrollment failed.`));return r.session.token}async function xe(e){let t=await X({channelId:``,token:e},`/v1/client/navigation`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load Workshop navigation.`));if(!K(n)||n.version!==1||!K(n.principal)||typeof n.principal.principal_id!=`string`||!E.test(n.principal.principal_id)||typeof n.principal.display_name!=`string`||n.principal.handle!==null&&(typeof n.principal.handle!=`string`||!M.test(n.principal.handle))||!Array.isArray(n.workshops))throw Error(`Kai returned unsupported Workshop navigation.`);let r=n.workshops.map(e=>{if(!K(e)||typeof e.workshop_id!=`string`||!O.test(e.workshop_id)||typeof e.name!=`string`||typeof e.role!=`string`||!Array.isArray(e.channels))throw Error(`Kai returned unsupported Workshop navigation.`);return{channels:e.channels.map(e=>{if(!K(e)||typeof e.channel_id!=`string`||!b.test(e.channel_id)||e.name!==null&&typeof e.name!=`string`||![`direct`,`group`,`notification`].includes(String(e.kind))||typeof e.role!=`string`||e.archived_at!==void 0&&e.archived_at!==null&&typeof e.archived_at!=`string`||e.lifecycle_event_position!==void 0&&e.lifecycle_event_position!==null&&(typeof e.lifecycle_event_position!=`number`||!Number.isSafeInteger(e.lifecycle_event_position))||e.direct_message_archived_at!==void 0&&e.direct_message_archived_at!==null&&typeof e.direct_message_archived_at!=`string`||e.direct_message_archive_event_position!==void 0&&e.direct_message_archive_event_position!==null&&(typeof e.direct_message_archive_event_position!=`number`||!Number.isSafeInteger(e.direct_message_archive_event_position))||typeof e.can_submit_commands!=`boolean`||!Array.isArray(e.agents)||!Array.isArray(e.participants))throw Error(`Kai returned unsupported Workshop navigation.`);let t=e.agents.map(e=>{if(!K(e)||typeof e.agent_id!=`string`||!x.test(e.agent_id)||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.engaged!=`boolean`||typeof e.available!=`boolean`||![`draft`,`active`,`archived`].includes(String(e.lifecycle_state))||e.engaged_until!==null&&typeof e.engaged_until!=`string`||![`private`,`shared_channel`].includes(String(e.memory_scope))||e.runtime_profile_id!==null&&(typeof e.runtime_profile_id!=`string`||!D.test(e.runtime_profile_id))||e.sponsor_principal_id!==null&&(typeof e.sponsor_principal_id!=`string`||!E.test(e.sponsor_principal_id))||e.sponsor_display_name!==null&&typeof e.sponsor_display_name!=`string`||typeof e.name!=`string`||typeof e.handle!=`string`||!M.test(e.handle))throw Error(`Kai returned unsupported Workshop navigation.`);return{agentId:e.agent_id,available:e.available,engaged:e.engaged,engagedUntil:e.engaged_until,handle:e.handle,lifecycleState:e.lifecycle_state,memoryScope:e.memory_scope,name:e.name,principalId:e.principal_id,runtimeProfileId:e.runtime_profile_id,sponsorDisplayName:e.sponsor_display_name,sponsorPrincipalId:e.sponsor_principal_id}}),n=e.participants.map(e=>{if(!K(e)||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.kind!=`string`||typeof e.display_name!=`string`||e.handle!==null&&(typeof e.handle!=`string`||!M.test(e.handle)))throw Error(`Kai returned unsupported Workshop navigation.`);return{...e.kind===`human`?{avatar:de(e.avatar,e.principal_id)}:{},displayName:e.display_name,handle:e.handle,kind:e.kind,principalId:e.principal_id}});return{agents:t,...e.archived_at===void 0?{}:{archivedAt:e.archived_at},canSubmitCommands:e.can_submit_commands,channelId:e.channel_id,...e.direct_message_archive_event_position===void 0?{}:{directMessageArchiveEventPosition:e.direct_message_archive_event_position},...e.direct_message_archived_at===void 0?{}:{directMessageArchivedAt:e.direct_message_archived_at},kind:e.kind,...e.lifecycle_event_position===void 0?{}:{lifecycleEventPosition:e.lifecycle_event_position},name:e.name,participants:n,role:e.role}}),name:e.name,role:e.role,workshopId:e.workshop_id}});return{principal:{avatar:de(n.principal.avatar,n.principal.principal_id),displayName:n.principal.display_name,handle:n.principal.handle,principalId:n.principal.principal_id},workshops:r}}async function Se(e,t=null){let n=new URLSearchParams({channel_id:e.channelId});t!==null&&n.set(`agent_id`,t);let r=await X(e,`/v1/client/capabilities?${n.toString()}`),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not load available actions.`));if(!K(i)||i.version!==1||!K(i.context)||typeof i.context.administrator!=`boolean`||typeof i.context.agent!=`boolean`||typeof i.context.agent_owner!=`boolean`||typeof i.context.channel_owner!=`boolean`||typeof i.context.conversation!=`boolean`||typeof i.context.workspace!=`boolean`||!Array.isArray(i.capabilities))throw Error(`Kai returned unsupported action metadata.`);let a=i.capabilities.map(G);if(a.some(e=>e===null))throw Error(`Kai returned unsupported action metadata.`);return{capabilities:a,context:{administrator:i.context.administrator,agent:i.context.agent,agentOwner:i.context.agent_owner,channelOwner:i.context.channel_owner,conversation:i.context.conversation,workspace:i.context.workspace}}}var Ce=new Set([`healthy`,`degraded`,`disabled`,`unavailable`]);function we(e){return typeof e==`string`&&Ce.has(e)}async function Te(e){let t=await X(e,`/v1/client/administration/webhook-diagnostics`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load webhook diagnostics.`));if(!K(n)||n.version!==1||!we(n.state)||!K(n.listener)||!we(n.listener.state)||typeof n.listener.port!=`number`||!Number.isInteger(n.listener.port)||n.listener.port<1||!Array.isArray(n.endpoints)||!K(n.deliveries)||!we(n.deliveries.state)||!Array.isArray(n.guidance)||!n.guidance.every(e=>typeof e==`string`))throw Error(`Kai returned unsupported webhook diagnostics.`);let r=n.deliveries,i=n.endpoints.map(e=>!K(e)||typeof e.endpoint_class!=`string`||typeof e.display_name!=`string`||!we(e.state)||typeof e.description!=`string`?null:{description:e.description,displayName:e.display_name,endpointClass:e.endpoint_class,state:e.state});if(i.some(e=>e===null)||![`window_hours`,`pending`,`executing`,`retrying`,`succeeded`,`failed`].every(e=>typeof r[e]==`number`&&Number.isInteger(r[e])&&r[e]>=0))throw Error(`Kai returned unsupported webhook diagnostics.`);return{deliveries:{executing:r.executing,failed:r.failed,pending:r.pending,retrying:r.retrying,state:r.state,succeeded:r.succeeded,windowHours:r.window_hours},endpoints:i,guidance:n.guidance,listener:{port:n.listener.port,state:n.listener.state},state:n.state}}var Ee=new Set([`agent_delegation`,`image_input`,`text_generation`,`tool_activity`,`workspace_execution`]);function De(e){if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let n of e){if(typeof n!=`string`||!Ee.has(n)||t.includes(n))return null;t.push(n)}return t}var Oe=new Set([`context_read`,`reaction`,`progress_publish`,`thread_reply`,`artifact_publish`,`agent_delegation`,`standing_participation`]);function ke(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!=`string`||!Oe.has(n)||t.includes(n))return null;t.push(n)}return t}function Ae(e){if(!K(e)||typeof e.definition_id!=`string`||!S.test(e.definition_id)||typeof e.agent_id!=`string`||!x.test(e.agent_id)||typeof e.handle!=`string`||typeof e.display_name!=`string`||typeof e.description!=`string`||!K(e.presentation)||Object.keys(e.presentation).some(e=>e!==`avatar`)||e.presentation.avatar!==void 0&&typeof e.presentation.avatar!=`string`||![`draft`,`active`,`archived`].includes(String(e.lifecycle_state))||e.active_revision_id!==null&&(typeof e.active_revision_id!=`string`||!w.test(e.active_revision_id))||!Number.isSafeInteger(e.state_version)||e.state_version<1||typeof e.created_at!=`string`||e.created_by_principal_id!==null&&(typeof e.created_by_principal_id!=`string`||!E.test(e.created_by_principal_id))||e.owner_principal_id!==null&&(typeof e.owner_principal_id!=`string`||!E.test(e.owner_principal_id))||e.owner_display_name!==null&&typeof e.owner_display_name!=`string`||!Array.isArray(e.revisions))return null;let t=e.revisions.map(e=>{if(!K(e)||typeof e.revision_id!=`string`||!w.test(e.revision_id)||!Number.isSafeInteger(e.revision_number)||e.revision_number<1||typeof e.purpose!=`string`||typeof e.instructions!=`string`||typeof e.created_at!=`string`||e.created_by_principal_id!==null&&(typeof e.created_by_principal_id!=`string`||!E.test(e.created_by_principal_id))||!Number.isSafeInteger(e.event_position)||e.event_position<1)return null;let t=De(e.capabilities),n=ke(e.collaboration_operations);return!t||!n?null:{capabilities:t,collaborationOperations:n,createdAt:e.created_at,createdByPrincipalId:e.created_by_principal_id,eventPosition:e.event_position,instructions:e.instructions,purpose:e.purpose,revisionId:e.revision_id,revisionNumber:e.revision_number}});return t.some(e=>e===null)?null:{activeRevisionId:e.active_revision_id,agentId:e.agent_id,createdAt:e.created_at,createdByPrincipalId:e.created_by_principal_id,definitionId:e.definition_id,description:e.description,displayName:e.display_name,handle:e.handle,lifecycleState:e.lifecycle_state,ownerDisplayName:e.owner_display_name,ownerPrincipalId:e.owner_principal_id,presentation:e.presentation,revisions:t,stateVersion:e.state_version}}function je(e){if(!K(e)||e.enablement_id!==null&&(typeof e.enablement_id!=`string`||!T.test(e.enablement_id))||typeof e.definition_id!=`string`||!S.test(e.definition_id)||typeof e.agent_id!=`string`||!x.test(e.agent_id)||typeof e.handle!=`string`||typeof e.display_name!=`string`||![`available`,`enabled`,`disabled`].includes(String(e.lifecycle_state))||e.direct_channel_id!==null&&(typeof e.direct_channel_id!=`string`||!b.test(e.direct_channel_id))||e.runtime_profile_id!==null&&(typeof e.runtime_profile_id!=`string`||!D.test(e.runtime_profile_id))||e.state_version!==null&&(!Number.isSafeInteger(e.state_version)||e.state_version<1)||!Array.isArray(e.eligible_runtimes)||typeof e.can_manage!=`boolean`||typeof e.conversation_started!=`boolean`||e.owner_principal_id!==null&&(typeof e.owner_principal_id!=`string`||!E.test(e.owner_principal_id))||e.owner_runtime_profile_id!==null&&(typeof e.owner_runtime_profile_id!=`string`||!D.test(e.owner_runtime_profile_id)))return null;let t=e.eligible_runtimes.map(e=>!K(e)||typeof e.runtime_profile_id!=`string`||!D.test(e.runtime_profile_id)||typeof e.display_name!=`string`||!Array.isArray(e.backend_options)||e.backend_options.some(e=>typeof e!=`string`)?null:{backendOptions:e.backend_options,displayName:e.display_name,runtimeProfileId:e.runtime_profile_id});return t.some(e=>e===null)?null:{agentId:e.agent_id,definitionId:e.definition_id,directChannelId:e.direct_channel_id,displayName:e.display_name,eligibleRuntimes:t,enablementId:e.enablement_id,handle:e.handle,lifecycleState:e.lifecycle_state,runtimeProfileId:e.runtime_profile_id,stateVersion:e.state_version,canManage:e.can_manage,conversationStarted:e.conversation_started,ownerPrincipalId:e.owner_principal_id,ownerRuntimeProfileId:e.owner_runtime_profile_id}}function Me(e){if(!Array.isArray(e))return null;let t=e.map(e=>!K(e)||typeof e.code!=`string`||e.code.length===0||typeof e.detail!=`string`||e.detail.length===0?null:{code:e.code,detail:e.detail});return t.some(e=>e===null)?null:t}function Ne(e){if(!K(e)||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.ready!=`boolean`||!Array.isArray(e.runtimes))return null;let t=Me(e.blockers);if(!t)return null;let n=[`refreshing`,`succeeded`,`failed`,`unsupported`,`malformed`,`timed_out`,`invalidated`,`superseded`],r=[`available`,`not_advertised`,`unavailable`,`unknown`],i=[`ready`,`unverified`,`unavailable`,`misconfigured`],a=e.runtimes.map(e=>{if(!K(e)||typeof e.runtime_profile_id!=`string`||!D.test(e.runtime_profile_id)||typeof e.display_name!=`string`||e.display_name.length===0||typeof e.current_backend_option_id!=`string`||e.current_backend_option_id.length===0||e.default_workspace!==null&&typeof e.default_workspace!=`string`||!Number.isSafeInteger(e.default_timeout_seconds)||e.default_timeout_seconds<1||!Number.isSafeInteger(e.minimum_timeout_seconds)||e.minimum_timeout_seconds<1||!Number.isSafeInteger(e.maximum_timeout_seconds)||e.maximum_timeout_seconds{if(!K(e)||typeof e.option_id!=`string`||e.option_id.length===0||typeof e.backend!=`string`||e.backend.length===0||typeof e.provider!=`string`||e.provider.length===0||typeof e.current!=`boolean`||typeof e.readiness!=`string`||!i.includes(e.readiness)||typeof e.default_model!=`string`||e.default_model.length===0||e.catalogue_status!==null&&(typeof e.catalogue_status!=`string`||!n.includes(e.catalogue_status))||typeof e.catalogue_stale!=`boolean`||!Array.isArray(e.models))return null;let t=Me(e.blockers);if(!t)return null;let a=e.models.map(e=>!K(e)||typeof e.model_id!=`string`||e.model_id.length===0||typeof e.display_name!=`string`||e.display_name.length===0||typeof e.status!=`string`||!r.includes(e.status)||typeof e.selectable!=`boolean`||typeof e.retained!=`boolean`?null:{displayName:e.display_name,modelId:e.model_id,retained:e.retained,selectable:e.selectable,status:e.status});return a.some(e=>e===null)?null:{backend:e.backend,blockers:t,catalogueStale:e.catalogue_stale,catalogueStatus:e.catalogue_status,current:e.current,defaultModel:e.default_model,models:a,optionId:e.option_id,provider:e.provider,readiness:e.readiness}}),o=e.workspaces.map(e=>!K(e)||typeof e.path!=`string`||e.path.length===0||typeof e.name!=`string`||e.name.length===0||typeof e.default!=`boolean`||typeof e.available!=`boolean`?null:{available:e.available,default:e.default,name:e.name,path:e.path});return a.some(e=>e===null)||o.some(e=>e===null)?null:{backends:a,blockers:t,currentBackendOptionId:e.current_backend_option_id,defaultTimeoutSeconds:e.default_timeout_seconds,defaultWorkspace:e.default_workspace,displayName:e.display_name,maximumTimeoutSeconds:e.maximum_timeout_seconds,minimumTimeoutSeconds:e.minimum_timeout_seconds,ready:e.ready,runtimeProfileId:e.runtime_profile_id,workspaces:o}});return a.some(e=>e===null)?null:{blockers:t,principalId:e.principal_id,ready:e.ready,runtimes:a}}function Pe(e){let t=[`draft`,`needs_attention`,`provisioning`,`ready`],n=[`definition_created`,`revision_activated`,`enablement_created`,`runtime_registered`,`backend_selected`,`model_selected`,`workspace_selected`,`timeout_selected`,`collaboration_policy_set`,`ready`];if(!K(e)||typeof e.operation_id!=`string`||!C.test(e.operation_id)||typeof e.client_operation_id!=`string`||e.client_operation_id.length===0||typeof e.status!=`string`||!t.includes(e.status)||typeof e.replayed!=`boolean`||e.definition_id!==null&&(typeof e.definition_id!=`string`||!S.test(e.definition_id))||e.revision_id!==null&&(typeof e.revision_id!=`string`||!w.test(e.revision_id))||e.agent_id!==null&&(typeof e.agent_id!=`string`||!x.test(e.agent_id))||e.enablement_id!==null&&(typeof e.enablement_id!=`string`||!T.test(e.enablement_id))||e.direct_channel_id!==null&&(typeof e.direct_channel_id!=`string`||!b.test(e.direct_channel_id))||typeof e.runtime_profile_id!=`string`||!D.test(e.runtime_profile_id)||!Array.isArray(e.completed_stages)||e.completed_stages.some(e=>typeof e!=`string`||!n.includes(e))||e.next_stage!==null&&(typeof e.next_stage!=`string`||!n.includes(e.next_stage)))return null;let r=Me(e.blockers);return r?{agentId:e.agent_id,blockers:r,clientOperationId:e.client_operation_id,completedStages:e.completed_stages,definitionId:e.definition_id,directChannelId:e.direct_channel_id,enablementId:e.enablement_id,nextStage:e.next_stage,operationId:e.operation_id,replayed:e.replayed,revisionId:e.revision_id,runtimeProfileId:e.runtime_profile_id,status:e.status}:null}async function Fe(e,t,n,r){let i=await X({channelId:``,token:e},t,{body:JSON.stringify(n),headers:{"Content-Type":`application/json`},method:`POST`}),a=await Y(i);if(!i.ok)throw Error(J(a,r));let o=K(a)&&a.version===1?Ae(a.agent):null;if(!o)throw Error(`Kai returned an unsupported agent definition.`);return o}async function Ie(e,t,n){let r=await X({channelId:``,token:e},t,{body:JSON.stringify(n),headers:{"Content-Type":`application/json`},method:`POST`}),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not update this agent.`));let a=K(i)&&i.version===1?je(i.agent):null;if(!a)throw Error(`Kai returned unsupported agent enablement state.`);return a}async function Le(e){let t=await X({channelId:``,token:e},`/v1/client/agents`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load agents.`));if(!K(n)||n.version!==1||!Array.isArray(n.agents))throw Error(`Kai returned unsupported agent definitions.`);let r=n.agents.map(Ae);if(r.some(e=>e===null))throw Error(`Kai returned unsupported agent definitions.`);return r}async function Re(e){let t=await X({channelId:``,token:e},`/v1/client/agents/creation-options`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load agent creation options.`));let r=K(n)&&n.version===1?Ne(n.creation_options):null;if(!r)throw Error(`Kai returned unsupported agent creation options.`);return r}function ze(e){if(!K(e)||typeof e.client_operation_id!=`string`||!K(e.definition)||!K(e.revision)||!K(e.runtime)||!K(e.collaboration_policy))return null;let t=e.definition,n=e.revision,r=e.runtime,i=e.collaboration_policy,a=t.presentation,o=t.existing_definition_id;return typeof t.handle!=`string`||typeof t.display_name!=`string`||typeof t.description!=`string`||!K(a)||a.avatar!==void 0&&typeof a.avatar!=`string`||o!==void 0&&(typeof o!=`string`||!S.test(o))||typeof n.purpose!=`string`||typeof n.instructions!=`string`||!Array.isArray(n.capabilities)||n.capabilities.some(e=>typeof e!=`string`)||!Array.isArray(n.collaboration_operations)||n.collaboration_operations.some(e=>typeof e!=`string`)||!Array.isArray(i.allowed_operations)||i.allowed_operations.some(e=>typeof e!=`string`)||typeof r.runtime_profile_id!=`string`||typeof r.backend_option_id!=`string`||typeof r.model!=`string`||typeof r.workspace!=`string`||typeof r.timeout_seconds!=`number`?null:{allowedCollaborationOperations:i.allowed_operations,avatar:typeof a.avatar==`string`?a.avatar:``,backendOptionId:r.backend_option_id,capabilities:n.capabilities,clientOperationId:e.client_operation_id,collaborationOperations:n.collaboration_operations,description:t.description,displayName:t.display_name,...typeof o==`string`?{existingDefinitionId:o}:{},handle:t.handle,instructions:n.instructions,model:r.model,purpose:n.purpose,runtimeProfileId:r.runtime_profile_id,timeoutSeconds:r.timeout_seconds,workspace:r.workspace}}async function Be(e){let t=await X({channelId:``,token:e},`/v1/client/agents/provision`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load saved agent setup.`));if(!K(n)||n.version!==1||!Array.isArray(n.setups))throw Error(`Kai returned unsupported saved agent setup state.`);let r=n.setups.map(e=>{if(!K(e))return null;let t=Pe(e.provisioning),n=ze(e.request);return t&&n?{input:n,provisioning:t}:null});if(r.some(e=>e===null))throw Error(`Kai returned unsupported saved agent setup state.`);return r}async function Ve(e,t){let n=await X({channelId:``,token:e},`/v1/client/agents/provision`,{body:JSON.stringify({client_operation_id:t.clientOperationId,collaboration_policy:{allowed_operations:t.allowedCollaborationOperations},definition:{description:t.description,display_name:t.displayName,handle:t.handle,presentation:t.avatar.trim()?{avatar:t.avatar.trim()}:{},...t.existingDefinitionId?{existing_definition_id:t.existingDefinitionId}:{}},revision:{capabilities:t.capabilities,collaboration_operations:t.collaborationOperations,instructions:t.instructions,purpose:t.purpose},runtime:{backend_option_id:t.backendOptionId,model:t.model,runtime_profile_id:t.runtimeProfileId,timeout_seconds:t.timeoutSeconds,workspace:t.workspace}}),headers:{"Content-Type":`application/json`},method:`POST`}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not provision this agent.`));let i=K(r)&&r.version===1?Pe(r.provisioning):null;if(!i)throw Error(`Kai returned unsupported agent provisioning state.`);return i}async function He(e){let t=await X({channelId:``,token:e},`/v1/client/agent-enablement`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load agent access.`));if(!K(n)||n.version!==1||!Array.isArray(n.agents))throw Error(`Kai returned unsupported agent enablement state.`);let r=n.agents.map(je);if(r.some(e=>e===null))throw Error(`Kai returned unsupported agent enablement state.`);return r}function Ue(e){if(!K(e)||typeof e.definition_id!=`string`||!S.test(e.definition_id)||typeof e.owner_principal_id!=`string`||!E.test(e.owner_principal_id)||typeof e.can_manage!=`boolean`||!Number.isSafeInteger(e.policy_version)||e.policy_version<0||e.active_revision_id!==null&&(typeof e.active_revision_id!=`string`||!w.test(e.active_revision_id))||e.active_grants!==null&&(!Number.isSafeInteger(e.active_grants)||e.active_grants<0)||!Array.isArray(e.operations))return null;let t=e.operations.map(e=>!K(e)||typeof e.operation!=`string`||!Oe.has(e.operation)||typeof e.requested!=`boolean`||e.owner_allowed!==null&&typeof e.owner_allowed!=`boolean`||typeof e.host_allowed!=`boolean`||typeof e.effective_for_new_attempt!=`boolean`||e.unavailable_reason!==null&&typeof e.unavailable_reason!=`string`||e.quota!==null&&(!Number.isSafeInteger(e.quota)||e.quota<1)?null:{effectiveForNewAttempt:e.effective_for_new_attempt,hostAllowed:e.host_allowed,operation:e.operation,ownerAllowed:e.owner_allowed,quota:e.quota,requested:e.requested,unavailableReason:e.unavailable_reason});return t.some(e=>e===null)?null:{activeGrants:e.active_grants,activeRevisionId:e.active_revision_id,canManage:e.can_manage,definitionId:e.definition_id,operations:t,ownerPrincipalId:e.owner_principal_id,policyVersion:e.policy_version}}async function We(e,t){let n=await Y(e);if(!e.ok)throw Error(J(n,t));let r=K(n)&&n.version===1?Ue(n.policy):null;if(!r)throw Error(`Kai returned unsupported collaboration policy.`);return r}async function Z(e,t){return We(await X({channelId:``,token:e},`/v1/client/agents/${encodeURIComponent(t)}/collaboration-policy`),`Could not load collaboration policy.`)}function Ge(e,t=0){return Number.isSafeInteger(e)&&e>=t}function Ke(e,t){if(!K(e)||e.channel_id!==t||!K(e.policy)||!Array.isArray(e.subscriptions)||!Array.isArray(e.observations)||!Array.isArray(e.recent_runs)||typeof e.can_inspect_silent!=`boolean`)return null;let n=e.policy;if(typeof n.enabled!=`boolean`||typeof n.can_manage!=`boolean`||typeof n.host_enabled!=`boolean`||!Ge(n.policy_version)||!Ge(n.host_policy_version,1)||!Ge(n.max_agents_per_channel,1)||!Ge(n.coalescing_grace_seconds)||!Ge(n.max_messages_per_observe_run,1)||!Ge(n.max_pending_messages_per_scope,1)||!Ge(n.max_pending_age_seconds,1)||!Ge(n.max_observe_runs_per_hour,1)||!Ge(n.max_unsolicited_messages_per_hour,1)||!Ge(n.minimum_unsolicited_interval_seconds,1)||!Ge(n.quiet_expiry_seconds))return null;let r=[];for(let t of e.subscriptions){if(!K(t)||typeof t.agent_id!=`string`||!x.test(t.agent_id)||typeof t.agent_definition_id!=`string`||!S.test(t.agent_definition_id)||typeof t.agent_revision_id!=`string`||!w.test(t.agent_revision_id)||typeof t.agent_display_name!=`string`||typeof t.agent_handle!=`string`||![`active`,`paused_overflow`,`ended`].includes(String(t.lifecycle_state))||typeof t.started_by_principal_id!=`string`||!E.test(t.started_by_principal_id)||typeof t.started_by_message_id!=`string`||!A.test(t.started_by_message_id)||!Ge(t.owner_policy_version)||!Ge(t.channel_policy_version,1)||!Ge(t.host_policy_version,1)||!Ge(t.state_version,1)||typeof t.started_at!=`string`||t.quiet_expires_at!==null&&typeof t.quiet_expires_at!=`string`||t.end_reason!==null&&typeof t.end_reason!=`string`)return null;r.push({agentDefinitionId:t.agent_definition_id,agentDisplayName:t.agent_display_name,agentHandle:t.agent_handle,agentId:t.agent_id,agentRevisionId:t.agent_revision_id,channelPolicyVersion:t.channel_policy_version,endReason:t.end_reason,hostPolicyVersion:t.host_policy_version,lifecycleState:t.lifecycle_state,ownerPolicyVersion:t.owner_policy_version,quietExpiresAt:t.quiet_expires_at,startedAt:t.started_at,startedByMessageId:t.started_by_message_id,startedByPrincipalId:t.started_by_principal_id,stateVersion:t.state_version})}let i=[];for(let t of e.observations){if(!K(t)||typeof t.agent_id!=`string`||!x.test(t.agent_id)||![`channel`,`thread`].includes(String(t.scope_kind))||typeof t.scope_id!=`string`||!Ge(t.delivered_through_event_position)||!Ge(t.pending_through_event_position)||!Ge(t.considered_through_event_position)||!Ge(t.pending_message_count)||!Ge(t.state_version,1)||![`idle`,`pending`,`paused_overflow`].includes(String(t.lifecycle_state))||t.not_before!==null&&typeof t.not_before!=`string`||t.overflowed_at!==null&&typeof t.overflowed_at!=`string`||t.overflow_reason!==null&&typeof t.overflow_reason!=`string`||t.overflow_from_event_position!==null&&!Ge(t.overflow_from_event_position)||t.overflow_through_event_position!==null&&!Ge(t.overflow_through_event_position))return null;i.push({agentId:t.agent_id,consideredThroughEventPosition:t.considered_through_event_position,deliveredThroughEventPosition:t.delivered_through_event_position,lifecycleState:t.lifecycle_state,notBefore:t.not_before,overflowFromEventPosition:t.overflow_from_event_position,overflowReason:t.overflow_reason,overflowThroughEventPosition:t.overflow_through_event_position,overflowedAt:t.overflowed_at,pendingMessageCount:t.pending_message_count,pendingThroughEventPosition:t.pending_through_event_position,scopeId:t.scope_id,scopeKind:t.scope_kind,stateVersion:t.state_version})}let a=[];for(let t of e.recent_runs){if(!K(t)||typeof t.run_id!=`string`||typeof t.agent_id!=`string`||!x.test(t.agent_id)||typeof t.agent_display_name!=`string`||typeof t.status!=`string`||!_e.has(t.status)||typeof t.accepted_at!=`string`||t.started_at!==null&&typeof t.started_at!=`string`||t.terminal_at!==null&&typeof t.terminal_at!=`string`||t.terminal_code!==null&&typeof t.terminal_code!=`string`||![`channel`,`thread`].includes(String(t.scope_kind))||typeof t.scope_id!=`string`||!Ge(t.observed_from_event_position)||!Ge(t.observed_through_event_position)||!Ge(t.observed_message_count,1)||typeof t.human_anchor_message_id!=`string`||!A.test(t.human_anchor_message_id)||t.collaboration_grant_id!==null&&typeof t.collaboration_grant_id!=`string`||t.outcome!==null&&t.outcome!==`spoke`&&t.outcome!==`silent`&&t.outcome!==`publication_suppressed`)return null;a.push({acceptedAt:t.accepted_at,agentDisplayName:t.agent_display_name,agentId:t.agent_id,collaborationGrantId:t.collaboration_grant_id,humanAnchorMessageId:t.human_anchor_message_id,observedFromEventPosition:t.observed_from_event_position,observedMessageCount:t.observed_message_count,observedThroughEventPosition:t.observed_through_event_position,outcome:t.outcome,runId:t.run_id,scopeId:t.scope_id,scopeKind:t.scope_kind,startedAt:t.started_at,status:t.status,terminalAt:t.terminal_at,terminalCode:t.terminal_code})}return{canInspectSilent:e.can_inspect_silent,channelId:t,observations:i,policy:{canManage:n.can_manage,coalescingGraceSeconds:n.coalescing_grace_seconds,enabled:n.enabled,hostEnabled:n.host_enabled,hostPolicyVersion:n.host_policy_version,maxAgentsPerChannel:n.max_agents_per_channel,maxMessagesPerObserveRun:n.max_messages_per_observe_run,maxObserveRunsPerHour:n.max_observe_runs_per_hour,maxPendingAgeSeconds:n.max_pending_age_seconds,maxPendingMessagesPerScope:n.max_pending_messages_per_scope,maxUnsolicitedMessagesPerHour:n.max_unsolicited_messages_per_hour,minimumUnsolicitedIntervalSeconds:n.minimum_unsolicited_interval_seconds,policyVersion:n.policy_version,quietExpirySeconds:n.quiet_expiry_seconds},recentRuns:a,subscriptions:r}}async function qe(e,t,n){let r=await Y(e);if(!e.ok)throw Error(J(r,n));let i=K(r)&&r.version===1?Ke(r.standing_participation,t):null;if(!i)throw Error(`Kai returned unsupported standing-participation state.`);return i}async function Je(e,t=!1){let n=t?`?include_silent=1`:``;return qe(await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/standing-participation${n}`),e.channelId,`Could not load standing participation.`)}async function Ye(e,t,n,r){return qe(await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/standing-participation`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:t,expected_policy_version:n,client_operation_id:r})}),e.channelId,`Could not update standing participation.`)}async function Xe(e,t,n,r){return qe(await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/agents/${encodeURIComponent(t)}/standing-participation/resume`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scope_id:n.scopeId,expected_state_version:n.stateVersion,client_operation_id:r})}),e.channelId,`Could not resume standing observation.`)}async function Ze(e,t,n){return We(await X({channelId:``,token:e},`/v1/client/agents/${encodeURIComponent(t)}/collaboration-policy`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({allowed_operations:n.allowedOperations,client_operation_id:n.clientOperationId,expected_policy_version:n.expectedPolicyVersion})}),`Could not update collaboration policy.`)}async function Qe(e,t,n){return We(await X({channelId:``,token:e},`/v1/client/agents/${encodeURIComponent(t)}/collaboration-policy/revoke-active`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_operation_id:n})}),`Could not revoke active collaboration access.`)}async function $e(e,t){return Fe(e,`/v1/client/agents`,{capabilities:t.capabilities,collaboration_operations:t.collaborationOperations,description:t.description,display_name:t.displayName,handle:t.handle,idempotency_key:t.idempotencyKey,instructions:t.instructions,presentation:t.avatar.trim()?{avatar:t.avatar.trim()}:{},purpose:t.purpose},`Could not create this agent.`)}async function et(e,t,n){return Fe(e,`/v1/client/agents/${encodeURIComponent(t)}/revisions`,{capabilities:n.capabilities,collaboration_operations:n.collaborationOperations,expected_version:n.expectedVersion,idempotency_key:n.idempotencyKey,instructions:n.instructions,purpose:n.purpose},`Could not save this agent revision.`)}async function tt(e,t,n){return Fe(e,`/v1/client/agents/${encodeURIComponent(t)}/activate`,{expected_version:n.expectedVersion,idempotency_key:n.idempotencyKey,revision_id:n.revisionId},`Could not activate this agent revision.`)}async function nt(e,t,n){return Fe(e,`/v1/client/agents/${encodeURIComponent(t)}/archive`,{expected_version:n.expectedVersion,idempotency_key:n.idempotencyKey},`Could not archive this agent.`)}async function rt(e,t,n){return Ie(e,`/v1/client/agents/${encodeURIComponent(t)}/enable`,{...n.expectedVersion===null?{}:{expected_version:n.expectedVersion},idempotency_key:n.idempotencyKey,runtime_profile_id:n.runtimeProfileId})}async function it(e,t,n){return Ie(e,`/v1/client/agents/${encodeURIComponent(t)}/conversation`,{expected_version:n.expectedVersion,idempotency_key:n.idempotencyKey})}async function at(e,t){let n=await X({channelId:``,token:e},`/v1/channels`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agent_ids:t.agentIds,name:t.name,...t.originChannelId?{origin_channel_id:t.originChannelId}:{}})}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not create this channel.`));if(!K(r)||r.version!==1||!K(r.channel)||typeof r.channel.channel_id!=`string`||!b.test(r.channel.channel_id))throw Error(`Kai returned an unsupported channel creation response.`);return r.channel.channel_id}function ot(e){return!K(e)||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.display_name!=`string`||typeof e.handle!=`string`||!M.test(e.handle)||e.conversation_channel_id!==null&&(typeof e.conversation_channel_id!=`string`||!b.test(e.conversation_channel_id))?null:{avatar:de(e.avatar,e.principal_id),conversationChannelId:e.conversation_channel_id,displayName:e.display_name,handle:e.handle,principalId:e.principal_id}}async function st(e,t){if(!O.test(t))throw Error(`Invalid Workshop identity.`);let n=await X({channelId:``,token:e},`/v1/workshops/${encodeURIComponent(t)}/humans`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load Workshop people.`));if(!K(r)||r.version!==1||r.workshop_id!==t||!Array.isArray(r.humans))throw Error(`Kai returned unsupported Workshop people.`);let i=r.humans.map(ot);if(i.some(e=>e===null))throw Error(`Kai returned unsupported Workshop people.`);return i}async function ct(e,t,n){if(!O.test(t))throw Error(`Invalid Workshop identity.`);if(!E.test(n))throw Error(`Invalid human identity.`);let r=await X({channelId:``,token:e},`/v1/workshops/${encodeURIComponent(t)}/humans/${encodeURIComponent(n)}/conversation`,{method:`POST`}),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not start this conversation.`));let a=K(i)?i.conversation:null,o=K(a)&&K(a.peer)?a.peer:null,s=o&&K(a)?ot({...o,conversation_channel_id:a.channel_id}):null;if(!K(i)||i.version!==1||typeof i.created!=`boolean`||!K(a)||a.workshop_id!==t||typeof a.channel_id!=`string`||!b.test(a.channel_id)||a.kind!==`direct`||!s||s.principalId!==n)throw Error(`Kai returned an unsupported human conversation response.`);return{channelId:a.channel_id,created:i.created,peer:s,workshopId:t}}async function lt(e,t,n,r){if(!b.test(t))throw Error(`Invalid channel identity.`);let i=await X({channelId:t,token:e},`/v1/channels/${encodeURIComponent(t)}/${n}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_operation_id:r})}),a=await Y(i);if(!i.ok||!K(a)||a.version!==1||!K(a.channel)||a.channel.channel_id!==t||a.channel.archived!==(n===`archive`)||typeof a.channel.changed!=`boolean`||typeof a.channel.occurred_at!=`string`)throw Error(J(a,n===`archive`?`Could not archive this channel.`:`Could not restore this channel.`))}async function ut(e,t,n){await lt(e,t,`archive`,n)}async function dt(e,t,n){await lt(e,t,`restore`,n)}async function ft(e,t,n,r){if(!b.test(t))throw Error(`Invalid channel identity.`);let i=await X({channelId:t,token:e},`/v1/direct-messages/${encodeURIComponent(t)}/${n}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_operation_id:r})}),a=await Y(i);if(!i.ok||!K(a)||a.version!==1||!K(a.direct_message)||a.direct_message.channel_id!==t||a.direct_message.archived!==(n===`archive`)||typeof a.direct_message.changed!=`boolean`||typeof a.direct_message.occurred_at!=`string`)throw Error(J(a,n===`archive`?`Could not archive this direct message.`:`Could not restore this direct message.`))}async function pt(e,t,n){await ft(e,t,`archive`,n)}async function mt(e,t,n){await ft(e,t,`restore`,n)}function ht(e){return!K(e)||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.display_name!=`string`||typeof e.handle!=`string`||!M.test(e.handle)||![`owner`,`participant`,null].includes(e.role)?null:{avatar:de(e.avatar,e.principal_id),displayName:e.display_name,handle:e.handle,principalId:e.principal_id,role:e.role}}async function gt(e){let t=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/members`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load channel members.`));if(!K(n)||n.version!==1||n.channel_id!==e.channelId||typeof n.workshop_id!=`string`||!O.test(n.workshop_id)||typeof n.archived!=`boolean`||typeof n.can_manage!=`boolean`||!Number.isSafeInteger(n.state_version)||n.state_version<0||!Array.isArray(n.members)||!Array.isArray(n.eligible_humans))throw Error(`Kai returned unsupported channel membership state.`);let r=n.members.map(ht),i=n.eligible_humans.map(ht);if(r.some(e=>e===null)||i.some(e=>e===null))throw Error(`Kai returned unsupported channel membership state.`);return{archived:n.archived,canManage:n.can_manage,channelId:n.channel_id,eligibleHumans:i,members:r,stateVersion:n.state_version,workshopId:n.workshop_id}}async function _t(e,t,n,r,i){if(!E.test(t))throw Error(`Invalid human identity.`);let a=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/members/${encodeURIComponent(t)}/${n}`,{body:JSON.stringify({client_operation_id:i,expected_state_version:r}),headers:{"Content-Type":`application/json`},method:`POST`}),o=await Y(a);if(!a.ok||!K(o)||o.version!==1||o.operation!==n||typeof o.changed!=`boolean`||!Number.isSafeInteger(o.state_version))throw Error(J(o,`Could not update channel members.`));return o.state_version}async function vt(e,t,n,r){if(!x.test(t))throw Error(`Invalid agent identity.`);let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/agents/${encodeURIComponent(t)}/${n}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_operation_id:r})}),a=await Y(i);if(!i.ok||!K(a)||a.version!==1||a.operation!==n||typeof a.changed!=`boolean`)throw Error(J(a,n===`attach`?`Could not attach this agent.`:`Could not detach this agent.`))}async function yt(e,t,n){await vt(e,t,`attach`,n)}async function bt(e,t,n){await vt(e,t,`detach`,n)}async function xt(e,t,n,r=null){if(!x.test(t))throw Error(`Invalid agent identity.`);if(r!==null&&!A.test(r))throw Error(`Invalid thread root identity.`);let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/agents/${encodeURIComponent(t)}/dismiss`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_dismissal_id:n,...r?{thread_root_id:r}:{}})}),a=await Y(i);if(!i.ok||!K(a)||a.version!==1||a.dismissed!==!0||typeof a.replayed!=`boolean`)throw Error(J(a,`Could not dismiss this agent.`))}async function St(e,t,n,r){if(!A.test(t)||!oe.has(n))throw Error(`Invalid message reaction.`);let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/messages/${encodeURIComponent(t)}/reactions`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({reaction:n,active:r})}),a=await Y(i);if(!i.ok||!K(a)||a.version!==1||a.message_id!==t)throw Error(J(a,`Could not update this reaction.`));let o=se(a.reactions);if(o===null)throw Error(`Kai returned an unsupported reaction response.`);return o}async function Ct(e,t,n){if(!A.test(t)||!oe.has(n))throw Error(`Invalid message reaction.`);let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/messages/${encodeURIComponent(t)}/reactions/${encodeURIComponent(n)}/reactors`),i=await Y(r);if(!r.ok||!K(i)||i.version!==1||!Number.isSafeInteger(i.total)||i.total<0||typeof i.truncated!=`boolean`||!Array.isArray(i.reactors))throw Error(J(i,`Could not load reaction participants.`));let a=i.reactors.map(e=>{if(!K(e)||typeof e.principal_id!=`string`||!E.test(e.principal_id)||![`human`,`agent`].includes(String(e.kind))||typeof e.display_name!=`string`||e.handle!==null&&typeof e.handle!=`string`)throw Error(`Kai returned unsupported reaction participants.`);return{displayName:e.display_name,handle:e.handle,kind:e.kind,principalId:e.principal_id}});if(a.length>i.total)throw Error(`Kai returned unsupported reaction participants.`);return{reactors:a,total:i.total,truncated:i.truncated}}function wt(e){if(!Array.isArray(e))throw Error(`Kai returned unsupported settings capabilities.`);return e.map(e=>{if(!K(e)||typeof e.field!=`string`||![`runtime`,`workspace`].includes(String(e.scope))||![`authorized_workspace`,`backend_id`,`integer_seconds`,`model_id`,`text`].includes(String(e.value_type))||typeof e.resettable!=`boolean`||e.choices!==null&&(!Array.isArray(e.choices)||e.choices.some(e=>typeof e!=`string`))||e.minimum!==null&&!Number.isSafeInteger(e.minimum)||e.maximum!==null&&!Number.isSafeInteger(e.maximum))throw Error(`Kai returned unsupported settings capabilities.`);return{choices:e.choices,field:e.field,maximum:e.maximum,minimum:e.minimum,resettable:e.resettable,scope:e.scope,valueType:e.value_type}})}function Tt(e){if(e===null)return null;if(!K(e)||typeof e.operation!=`string`||typeof e.changed!=`boolean`||![`deferred_until_next_run`,`restarted`,`unchanged`].includes(String(e.runtime_action))||typeof e.provider_session_invalidated!=`boolean`)throw Error(`Kai returned an unsupported settings mutation result.`);return{changed:e.changed,operation:e.operation,providerSessionInvalidated:e.provider_session_invalidated,runtimeAction:e.runtime_action}}function Et(e,t){if(!K(e)||e.version!==1||e.channel_id!==t||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.runtime_profile_id!=`string`||typeof e.backend!=`string`||typeof e.backend_option_id!=`string`||typeof e.provider!=`string`||!Array.isArray(e.backend_options)||typeof e.workspace!=`string`||typeof e.revision!=`string`||!K(e.model)||typeof e.model.value!=`string`||typeof e.model.source!=`string`||typeof e.model.default_value!=`string`||!K(e.timeout_seconds)||!Number.isSafeInteger(e.timeout_seconds.value)||typeof e.timeout_seconds.source!=`string`||!Number.isSafeInteger(e.timeout_seconds.default_value)||!Array.isArray(e.workspaces)||e.model_options!==null&&!Array.isArray(e.model_options))throw Error(`Kai returned unsupported settings and workspace state.`);let n=e.workspaces.map(e=>{if(!K(e)||typeof e.path!=`string`||typeof e.name!=`string`||typeof e.current!=`boolean`||typeof e.home!=`boolean`||e.deletable!==void 0&&typeof e.deletable!=`boolean`)throw Error(`Kai returned unsupported workspace state.`);return{current:e.current,deletable:e.deletable===!0,home:e.home,name:e.name,path:e.path}}),r=e.backend_options.map(e=>{if(!K(e)||typeof e.option_id!=`string`||typeof e.backend!=`string`||typeof e.provider!=`string`||typeof e.current!=`boolean`)throw Error(`Kai returned unsupported backend policy.`);return{backend:e.backend,current:e.current,optionId:e.option_id,provider:e.provider}}),i=e.model_options===null?null:e.model_options.map(e=>{if(!K(e)||typeof e.model_id!=`string`||typeof e.display_name!=`string`||![`available`,`not_advertised`,`unavailable`,`unknown`].includes(String(e.status))||typeof e.selectable!=`boolean`||typeof e.retained!=`boolean`)throw Error(`Kai returned unsupported model options.`);return{displayName:e.display_name,modelId:e.model_id,retained:e.retained,selectable:e.selectable,sources:[],status:e.status}}),a=e.model_catalogue;if(a!==null&&(!K(a)||a.status!==null&&typeof a.status!=`string`||typeof a.stale!=`boolean`||typeof a.last_known_good!=`boolean`||a.last_attempt_at!==null&&typeof a.last_attempt_at!=`string`||a.last_successful_refresh_at!==null&&typeof a.last_successful_refresh_at!=`string`||a.error_code!==null&&typeof a.error_code!=`string`||a.error_detail!==null&&typeof a.error_detail!=`string`))throw Error(`Kai returned unsupported model catalogue status.`);return{backend:e.backend,backendOptionId:e.backend_option_id,backendOptions:r,channelId:t,model:{defaultValue:e.model.default_value,source:e.model.source,value:e.model.value},modelCatalogue:a===null?null:{errorCode:a.error_code,errorDetail:a.error_detail,lastAttemptAt:a.last_attempt_at,lastKnownGood:a.last_known_good,lastSuccessfulRefreshAt:a.last_successful_refresh_at,stale:a.stale,status:a.status},modelOptions:i,capabilities:wt(e.capabilities),mutation:Tt(e.mutation),principalId:e.principal_id,provider:e.provider,revision:e.revision,runtimeProfileId:e.runtime_profile_id,timeoutSeconds:{defaultValue:e.timeout_seconds.default_value,source:e.timeout_seconds.source,value:e.timeout_seconds.value},workspace:e.workspace,workspaces:n}}function Dt(e){if(!K(e)||e.version!==1||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.runtime_profile_id!=`string`||typeof e.workspace_base!=`string`&&e.workspace_base!==null||!Array.isArray(e.grants)||!(e.mutation===void 0||K(e.mutation)))throw Error(`Kai returned unsupported workspace grant state.`);let t=e.grants.map(e=>{if(!K(e)||typeof e.path!=`string`||typeof e.name!=`string`||typeof e.provenance!=`string`||typeof e.available!=`boolean`||typeof e.current!=`boolean`||typeof e.removable!=`boolean`)throw Error(`Kai returned unsupported workspace grant state.`);return{available:e.available,current:e.current,name:e.name,path:e.path,provenance:e.provenance,removable:e.removable}}),n=null;if(e.mutation!==void 0){if(!K(e.mutation)||typeof e.mutation.path!=`string`||typeof e.mutation.changed!=`boolean`)throw Error(`Kai returned unsupported workspace grant mutation.`);n={changed:e.mutation.changed,path:e.mutation.path}}return{grants:t,mutation:n,principalId:e.principal_id,runtimeProfileId:e.runtime_profile_id,workspaceBase:e.workspace_base}}function Ot(e){if(e==null)return null;if(!K(e)||e.requested_task_class!==null&&![`conversation`,`coding`,`vision`].includes(String(e.requested_task_class))||e.requested_backend_option_id!==null&&typeof e.requested_backend_option_id!=`string`||e.selected_backend_option_id!==null&&typeof e.selected_backend_option_id!=`string`||![`selected_default`,`routed`,`fallback_selected`,`rejected`].includes(String(e.disposition))||typeof e.reason_code!=`string`||e.policy_revision!==null&&typeof e.policy_revision!=`number`||typeof e.backend!=`string`||e.provider!==null&&typeof e.provider!=`string`||typeof e.model!=`string`||typeof e.evidence_version!=`number`||typeof e.decided_at!=`string`)throw Error(`Kai returned an unsupported routing decision.`);return{backend:e.backend,decidedAt:e.decided_at,disposition:e.disposition,evidenceVersion:e.evidence_version,model:e.model,policyRevision:e.policy_revision,provider:e.provider,reasonCode:e.reason_code,requestedBackendOptionId:e.requested_backend_option_id,requestedTaskClass:e.requested_task_class,selectedBackendOptionId:e.selected_backend_option_id}}function kt(e){if(!K(e)||e.version!==1||typeof e.runtime_profile_id!=`string`||typeof e.option_id!=`string`||typeof e.stale!=`boolean`||typeof e.last_known_good!=`boolean`||!Array.isArray(e.models)||e.refresh!==null&&!K(e.refresh))throw Error(`Kai returned an unsupported model catalogue.`);let t=e.models.map(e=>{if(!K(e)||typeof e.model_id!=`string`||typeof e.display_name!=`string`||![`available`,`not_advertised`,`unavailable`,`unknown`].includes(String(e.status))||typeof e.selectable!=`boolean`||typeof e.retained!=`boolean`||!Array.isArray(e.sources)||e.sources.some(e=>typeof e!=`string`))throw Error(`Kai returned unsupported model catalogue entries.`);return{displayName:e.display_name,modelId:e.model_id,retained:e.retained,selectable:e.selectable,sources:e.sources,status:e.status}}),n=e.refresh;if(n!==null&&(!K(n)||typeof n.status!=`string`||!Number.isSafeInteger(n.generation)||typeof n.last_attempt_at!=`string`||n.last_successful_refresh_at!==null&&typeof n.last_successful_refresh_at!=`string`||n.expires_at!==null&&typeof n.expires_at!=`string`||n.error_code!==null&&typeof n.error_code!=`string`||n.error_detail!==null&&typeof n.error_detail!=`string`))throw Error(`Kai returned unsupported model refresh status.`);return{lastKnownGood:e.last_known_good,models:t,optionId:e.option_id,refresh:n===null?null:{errorCode:n.error_code,errorDetail:n.error_detail,expiresAt:n.expires_at,generation:n.generation,lastAttemptAt:n.last_attempt_at,lastSuccessfulRefreshAt:n.last_successful_refresh_at,status:n.status},runtimeProfileId:e.runtime_profile_id,stale:e.stale}}function At(e){if(!K(e)||e.version!==1||e.github_login!==null&&typeof e.github_login!=`string`||typeof e.repositories_resettable!=`boolean`||!Array.isArray(e.repositories)||!K(e.pr_review)||typeof e.pr_review.enabled!=`boolean`||typeof e.pr_review.source!=`string`||typeof e.pr_review.resettable!=`boolean`||!K(e.issue_triage)||typeof e.issue_triage.enabled!=`boolean`||typeof e.issue_triage.source!=`string`||typeof e.issue_triage.resettable!=`boolean`||typeof e.token_stored!=`boolean`||typeof e.revision!=`string`||e.mutation!==null&&(!K(e.mutation)||typeof e.mutation.operation!=`string`||typeof e.mutation.changed!=`boolean`))throw Error(`Kai returned unsupported GitHub settings.`);let t=e.repositories.map(e=>{if(!K(e)||typeof e.repository!=`string`||typeof e.source!=`string`||typeof e.automation_authorized!=`boolean`)throw Error(`Kai returned unsupported GitHub repository settings.`);return{automationAuthorized:e.automation_authorized,repository:e.repository,source:e.source}}),n=e.mutation===null?null:{changed:e.mutation.changed,operation:e.mutation.operation};return{githubLogin:e.github_login,issueTriage:{enabled:e.issue_triage.enabled,resettable:e.issue_triage.resettable,source:e.issue_triage.source},mutation:n,prReview:{enabled:e.pr_review.enabled,resettable:e.pr_review.resettable,source:e.pr_review.source},repositories:t,repositoriesResettable:e.repositories_resettable,revision:e.revision,tokenStored:e.token_stored}}function jt(e){if(!K(e)||e.version!==1||!Array.isArray(e.destinations)||!Array.isArray(e.preferences)||typeof e.revision!=`string`||e.mutation!==null&&(!K(e.mutation)||typeof e.mutation.operation!=`string`||typeof e.mutation.changed!=`boolean`))throw Error(`Kai returned unsupported notification preferences.`);let t=e.destinations.map(e=>{if(!K(e)||typeof e.choice_id!=`string`||typeof e.display_name!=`string`||e.kind!==`direct`&&e.kind!==`notification`||!Array.isArray(e.supported_classes)||e.supported_classes.some(e=>e!==`github`&&e!==`generic`))throw Error(`Kai returned an unsupported notification destination.`);return{choiceId:e.choice_id,displayName:e.display_name,kind:e.kind,supportedClasses:e.supported_classes}}),n=e.preferences.map(e=>{if(!K(e)||e.integration_class!==`github`&&e.integration_class!==`generic`||typeof e.display_name!=`string`||typeof e.destination_choice_id!=`string`||typeof e.destination_name!=`string`||e.destination_kind!==`direct`&&e.destination_kind!==`notification`||typeof e.source!=`string`||typeof e.editable!=`boolean`||typeof e.resettable!=`boolean`)throw Error(`Kai returned an unsupported integration preference.`);return{destinationChoiceId:e.destination_choice_id,destinationKind:e.destination_kind,destinationName:e.destination_name,displayName:e.display_name,editable:e.editable,integrationClass:e.integration_class,resettable:e.resettable,source:e.source}});return{destinations:t,mutation:e.mutation===null?null:{changed:e.mutation.changed,operation:e.mutation.operation},preferences:n,revision:e.revision}}function Mt(e){let t=e=>e===`all`||e===`mentions_replies`||e===`muted`;if(!K(e)||e.version!==1||!Array.isArray(e.levels)||e.levels.some(e=>!t(e))||!Array.isArray(e.adapter_deliveries)||!Array.isArray(e.channels)||typeof e.muted_mentions_notify!=`boolean`||!K(e.do_not_disturb)||typeof e.do_not_disturb.enabled!=`boolean`||typeof e.do_not_disturb.timezone!=`string`||typeof e.do_not_disturb.start!=`string`||typeof e.do_not_disturb.end!=`string`||typeof e.revision!=`string`||e.mutation!==null&&(!K(e.mutation)||typeof e.mutation.operation!=`string`||typeof e.mutation.changed!=`boolean`))throw Error(`Kai returned unsupported channel notification policy.`);let n=e.channels.map(e=>{if(!K(e)||typeof e.channel_id!=`string`||typeof e.channel_name!=`string`||!t(e.level)||typeof e.source!=`string`)throw Error(`Kai returned an unsupported channel notification setting.`);return{channelId:e.channel_id,channelName:e.channel_name,level:e.level,source:e.source}});return{adapterDeliveries:e.adapter_deliveries.map(e=>{if(!K(e)||typeof e.transport!=`string`||typeof e.display_name!=`string`||typeof e.enabled!=`boolean`||typeof e.source!=`string`)throw Error(`Kai returned an unsupported adapter notification setting.`);return{displayName:e.display_name,enabled:e.enabled,source:e.source,transport:e.transport}}),channels:n,doNotDisturb:{enabled:e.do_not_disturb.enabled,timezone:e.do_not_disturb.timezone,start:e.do_not_disturb.start,end:e.do_not_disturb.end},levels:e.levels,mutedMentionsNotify:e.muted_mentions_notify,mutation:e.mutation===null?null:{changed:e.mutation.changed,operation:e.mutation.operation},revision:e.revision}}function Nt(e){if(!K(e)||e.version!==1||!K(e.voice_output)||typeof e.voice_output.available!=`boolean`||e.voice_output.unavailable_reason!==null&&typeof e.voice_output.unavailable_reason!=`string`||!Array.isArray(e.voice_output.modes)||!Array.isArray(e.voice_output.voices)||!Array.isArray(e.voice_output.bindings)||typeof e.revision!=`string`||e.mutation!==null&&(!K(e.mutation)||typeof e.mutation.operation!=`string`||typeof e.mutation.changed!=`boolean`))throw Error(`Kai returned unsupported client preferences.`);let t=e.voice_output.modes;if(t.some(e=>e!==`off`&&e!==`text_and_voice`&&e!==`voice_only`))throw Error(`Kai returned an unsupported client voice mode.`);let n=e.voice_output.voices.map(e=>{if(!K(e)||typeof e.value!=`string`||typeof e.display_name!=`string`)throw Error(`Kai returned an unsupported client voice.`);return{value:e.value,displayName:e.display_name}}),r=e.voice_output.bindings.map(e=>{if(!K(e)||typeof e.choice_id!=`string`||typeof e.client_name!=`string`||e.mode!==`off`&&e.mode!==`text_and_voice`&&e.mode!==`voice_only`||typeof e.voice!=`string`||typeof e.voice_name!=`string`||typeof e.editable!=`boolean`)throw Error(`Kai returned unsupported client-binding preferences.`);return{choiceId:e.choice_id,clientName:e.client_name,mode:e.mode,voice:e.voice,voiceName:e.voice_name,editable:e.editable}});return{mutation:e.mutation===null?null:{changed:e.mutation.changed,operation:e.mutation.operation},revision:e.revision,voiceOutput:{available:e.voice_output.available,unavailableReason:e.voice_output.unavailable_reason,modes:t,voices:n,bindings:r}}}function Pt(e){if(!K(e)||e.version!==1||!L(e.theme_id)||!Array.isArray(e.themes)||typeof e.revision!=`string`||e.mutation!==null&&(!K(e.mutation)||typeof e.mutation.operation!=`string`||typeof e.mutation.changed!=`boolean`))throw Error(`Kai returned unsupported appearance preferences.`);let t=e.themes.map(e=>{if(!K(e)||!L(e.theme_id)||typeof e.display_name!=`string`||e.color_scheme!==`dark`&&e.color_scheme!==`light`)throw Error(`Kai returned an unsupported Workshop theme.`);return{colorScheme:e.color_scheme,displayName:e.display_name,themeId:e.theme_id}});return{mutation:e.mutation===null?null:{changed:e.mutation.changed,operation:e.mutation.operation},revision:e.revision,themeId:e.theme_id,themes:t}}function Ft(e){if(!K(e)||e.version!==1||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.display_name!=`string`||typeof e.handle!=`string`||!M.test(e.handle)||!Number.isSafeInteger(e.state_version)||e.state_version<0||e.mutation!==null&&(!K(e.mutation)||typeof e.mutation.changed!=`boolean`||typeof e.mutation.replayed!=`boolean`))throw Error(`Kai returned an unsupported human profile.`);return{avatar:de(e.avatar,e.principal_id),principalId:e.principal_id,displayName:e.display_name,handle:e.handle,stateVersion:e.state_version,mutation:e.mutation===null?null:{changed:e.mutation.changed,replayed:e.mutation.replayed}}}function It(e){if(!K(e)||e.version!==1||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.active!=`boolean`||!Number.isSafeInteger(e.state_version)||e.state_version<0||e.mutation!==null&&(!K(e.mutation)||typeof e.mutation.changed!=`boolean`||typeof e.mutation.replayed!=`boolean`))throw Error(`Kai returned an unsupported human avatar.`);let t=de(e,e.principal_id);if(t.active!==e.active||t.stateVersion!==e.state_version)throw Error(`Kai returned an unsupported human avatar.`);let n=[e.media_type,e.byte_size,e.width,e.height,e.sha256];if(e.active){if(e.media_type!==`image/png`||!Number.isSafeInteger(e.byte_size)||e.byte_size<1||!Number.isSafeInteger(e.width)||e.width<1||!Number.isSafeInteger(e.height)||e.height<1||typeof e.sha256!=`string`||!/^[0-9a-f]{64}$/.test(e.sha256))throw Error(`Kai returned an unsupported human avatar.`)}else if(n.some(e=>e!==null))throw Error(`Kai returned an unsupported human avatar.`);return{...t,byteSize:e.byte_size,height:e.height,mediaType:e.media_type,mutation:e.mutation===null?null:{changed:e.mutation.changed,replayed:e.mutation.replayed},principalId:e.principal_id,sha256:e.sha256,width:e.width}}function Lt(e){if(!K(e)||e.version!==1||typeof e.workspace!=`string`||typeof e.revision!=`string`||!K(e.model)||typeof e.model.value!=`string`||typeof e.model.source!=`string`||typeof e.model.default_value!=`string`||!K(e.timeout_seconds)||!Number.isSafeInteger(e.timeout_seconds.value)||typeof e.timeout_seconds.source!=`string`||!Number.isSafeInteger(e.timeout_seconds.default_value)||!Array.isArray(e.environment_keys)||e.environment_keys.some(e=>typeof e!=`string`)||!Array.isArray(e.environment_variables)||e.environment_variables.some(e=>!K(e)||typeof e.key!=`string`||![`operator`,`principal`,`principal_override`].includes(String(e.provenance))||typeof e.editable!=`boolean`||typeof e.removable!=`boolean`)||!K(e.environment_policy)||!Number.isSafeInteger(e.environment_policy.maximum_keys)||!Number.isSafeInteger(e.environment_policy.maximum_key_characters)||!Number.isSafeInteger(e.environment_policy.maximum_value_bytes)||e.environment_policy.values_write_only!==!0||e.prompt!==null&&typeof e.prompt!=`string`||typeof e.has_prompt!=`boolean`||e.prompt_source!==null&&typeof e.prompt_source!=`string`||!Array.isArray(e.override_fields)||e.override_fields.some(e=>typeof e!=`string`))throw Error(`Kai returned unsupported workspace settings state.`);return{capabilities:wt(e.capabilities),environmentKeys:e.environment_keys,environmentPolicy:{maximumKeyCharacters:e.environment_policy.maximum_key_characters,maximumKeys:e.environment_policy.maximum_keys,maximumValueBytes:e.environment_policy.maximum_value_bytes,valuesWriteOnly:!0},environmentVariables:e.environment_variables.map(e=>{let t=e;return{editable:t.editable,key:t.key,provenance:t.provenance,removable:t.removable}}),hasPrompt:e.has_prompt,model:{defaultValue:e.model.default_value,source:e.model.source,value:e.model.value},mutation:Tt(e.mutation),overrideFields:e.override_fields,prompt:e.prompt,promptSource:e.prompt_source,revision:e.revision,timeoutSeconds:{defaultValue:e.timeout_seconds.default_value,source:e.timeout_seconds.source,value:e.timeout_seconds.value},workspace:e.workspace}}function Rt(e){if(!K(e)||e.version!==1||typeof e.principal_id!=`string`||typeof e.runtime_profile_id!=`string`||typeof e.current_workspace!=`string`||e.active_project_id!==null&&typeof e.active_project_id!=`string`||typeof e.revision!=`string`||!Array.isArray(e.projects)||e.projects.some(e=>!K(e)||typeof e.project_id!=`string`||typeof e.display_name!=`string`||!Array.isArray(e.workspace_roots)||e.workspace_roots.some(e=>typeof e!=`string`)||![`operator_pinned`,`principal_registered`,`principal_created`,`legacy_migrated`].includes(String(e.provenance))||typeof e.current!=`boolean`||typeof e.available!=`boolean`||typeof e.removable!=`boolean`||e.state_version!==null&&!Number.isSafeInteger(e.state_version))||e.mutation!==void 0&&(!K(e.mutation)||typeof e.mutation.project_id!=`string`||typeof e.mutation.changed!=`boolean`||typeof e.mutation.note!=`string`))throw Error(`Kai returned unsupported memory-project registry state.`);return{activeProjectId:e.active_project_id,currentWorkspace:e.current_workspace,mutation:e.mutation===void 0?null:{projectId:e.mutation.project_id,changed:e.mutation.changed,note:e.mutation.note},principalId:e.principal_id,projects:e.projects.map(e=>{let t=e;return{available:t.available,current:t.current,displayName:t.display_name,projectId:t.project_id,provenance:t.provenance,removable:t.removable,stateVersion:t.state_version,workspaceRoots:t.workspace_roots}}),revision:e.revision,runtimeProfileId:e.runtime_profile_id}}function zt(e){if(e.context_invalidation===void 0||e.context_invalidation===null)return;let t=e.context_invalidation;if(!K(t)||![`applied`,`pending`,`failed`,`unchanged`].includes(String(t.state))||!Number.isSafeInteger(t.applied)||t.applied<0||!Number.isSafeInteger(t.pending)||t.pending<0)throw Error(`Kai returned unsupported context-invalidation state.`);return{applied:t.applied,pending:t.pending,state:t.state}}function Bt(e){if(!K(e)||e.version!==1||!K(e.document)||typeof e.document.content!=`string`||typeof e.document.revision!=`string`||e.document.updated_at!==null&&typeof e.document.updated_at!=`string`||!Number.isSafeInteger(e.document.size_bytes)||!Number.isSafeInteger(e.document.max_bytes)||typeof e.document.editable!=`boolean`)throw Error(`Kai returned unsupported preference state.`);let t=zt(e);return{...t?{contextInvalidation:t}:{},content:e.document.content,editable:e.document.editable,maxBytes:e.document.max_bytes,revision:e.document.revision,sizeBytes:e.document.size_bytes,updatedAt:e.document.updated_at}}function Vt(e){if(!K(e)||e.version!==1||!K(e.document)||typeof e.document.content!=`string`||typeof e.document.revision!=`string`||!/^[0-9a-f]{64}$/.test(e.document.revision)||!Number.isSafeInteger(e.document.size_bytes)||!Number.isSafeInteger(e.document.max_bytes)||typeof e.document.editable!=`boolean`)throw Error(`Kai returned unsupported principal-policy state.`);let t=zt(e);return{...t?{contextInvalidation:t}:{},content:e.document.content,editable:e.document.editable,maxBytes:e.document.max_bytes,revision:e.document.revision,sizeBytes:e.document.size_bytes}}function Ht(e){if(!K(e)||e.version!==1||!Number.isSafeInteger(e.limit)||!Array.isArray(e.revisions))throw Error(`Kai returned unsupported preference history.`);let t=e.revisions.map(e=>{if(!K(e)||typeof e.revision!=`string`||typeof e.updated_at!=`string`||!Number.isSafeInteger(e.size_bytes))throw Error(`Kai returned unsupported preference history.`);return{revision:e.revision,sizeBytes:e.size_bytes,updatedAt:e.updated_at}});return{limit:e.limit,revisions:t}}function Ut(e){if(!K(e))return null;let t={};for(let[n,r]of Object.entries(e)){if(!Number.isSafeInteger(r)||r<0)return null;t[n]=r}return t}function Wt(e){if(!K(e)||!K(e.scope))return null;let t=Gt(e.scope);return typeof e.memory_id!=`string`||typeof e.kind!=`string`||![`fact`,`episode`].includes(e.kind)||typeof e.source!=`string`||typeof e.memory_type!=`string`||typeof e.preview!=`string`||typeof e.revision!=`string`||!Array.isArray(e.tags)||!e.tags.every(e=>typeof e==`string`)||typeof e.speaker!=`string`||typeof e.confidence!=`number`||typeof e.created_at!=`string`||typeof e.updated_at!=`string`||t===null?null:{confidence:e.confidence,createdAt:e.created_at,kind:e.kind,memoryId:e.memory_id,memoryType:e.memory_type,preview:e.preview,revision:e.revision,scope:t,source:e.source,speaker:e.speaker,tags:e.tags,updatedAt:e.updated_at}}function Gt(e){return!K(e)||typeof e.scope!=`string`||![`global`,`project`,`task`].includes(e.scope)||e.project_id!==null&&typeof e.project_id!=`string`||typeof e.scope_confidence!=`number`||typeof e.scope_source!=`string`||typeof e.legacy_defaulted!=`boolean`||typeof e.invalid_defaulted!=`boolean`||typeof e.retrievable!=`boolean`||e.exclusion_reason!==null&&typeof e.exclusion_reason!=`string`?null:{exclusionReason:e.exclusion_reason,invalidDefaulted:e.invalid_defaulted,legacyDefaulted:e.legacy_defaulted,projectId:e.project_id,retrievable:e.retrievable,scope:e.scope,scopeConfidence:e.scope_confidence,scopeSource:e.scope_source}}async function Kt(e){let t=await X({channelId:``,token:e},`/v1/memory/stats`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load memory statistics.`));if(!K(n)||n.version!==1||!K(n.stats))throw Error(`Kai returned unsupported memory statistics.`);let r=n.stats,i=Ut(r.by_scope),a=Ut(r.by_source),o=Ut(r.by_type),s=Array.isArray(r.allowed_projects)?r.allowed_projects.map(e=>K(e)&&typeof e.project_id==`string`&&typeof e.display_name==`string`?{projectId:e.project_id,displayName:e.display_name}:null):null;if(!Number.isSafeInteger(r.total)||!Number.isSafeInteger(r.facts)||!Number.isSafeInteger(r.episodes)||!Number.isSafeInteger(r.unresolved_conflicts)||!Number.isSafeInteger(r.projection_failures)||!i||!a||!o||!s||s.some(e=>e===null))throw Error(`Kai returned unsupported memory statistics.`);return{allowedProjects:s,byScope:i,bySource:a,byType:o,episodes:r.episodes,facts:r.facts,total:r.total,unresolvedConflicts:r.unresolved_conflicts,projectionFailures:r.projection_failures}}function qt(e){if(!K(e)||typeof e.candidate_id!=`string`||typeof e.state_sha256!=`string`||typeof e.category!=`string`||typeof e.uncertainty!=`string`||typeof e.rationale!=`string`||!K(e.proposed_action)||!K(e.decision)||!Array.isArray(e.evidence))return null;let t=e.decision;if(![`pending`,`approve`,`reject`,`defer`].includes(String(t.disposition))||!K(t.action)||typeof t.operator_note!=`string`||!Number.isSafeInteger(t.state_version))return null;let n=e.evidence.map(e=>!K(e)||typeof e.memory_id!=`string`||![`fact`,`episode`].includes(String(e.kind))||typeof e.text!=`string`||typeof e.scope!=`string`||typeof e.confidence!=`number`||typeof e.migration_classification!=`string`||!Array.isArray(e.migration_gaps)||!e.migration_gaps.every(e=>typeof e==`string`)||[`created_at`,`updated_at`,`project_id`,`source`,`backend`,`provider`,`model`,`prompt_version`,`schema_version`,`valid_from`,`valid_until`,`asserted_at`,`observed_at`,`occurred_from`,`occurred_until`].some(t=>e[t]!==null&&typeof e[t]!=`string`)?null:{assertedAt:e.asserted_at,backend:e.backend,confidence:e.confidence,createdAt:e.created_at,kind:e.kind,memoryId:e.memory_id,migrationClassification:e.migration_classification,migrationGaps:e.migration_gaps,model:e.model,observedAt:e.observed_at,occurredFrom:e.occurred_from,occurredUntil:e.occurred_until,projectId:e.project_id,promptVersion:e.prompt_version,provider:e.provider,schemaVersion:e.schema_version,scope:e.scope,source:e.source,text:e.text,updatedAt:e.updated_at,validFrom:e.valid_from,validUntil:e.valid_until});return n.some(e=>e===null)?null:{candidateId:e.candidate_id,category:e.category,decision:{action:t.action,disposition:t.disposition,operatorNote:t.operator_note,stateVersion:t.state_version},evidence:n,proposedAction:e.proposed_action,rationale:e.rationale,stateSha256:e.state_sha256,uncertainty:e.uncertainty}}function Jt(e){if(!K(e))return null;let t=Ut(e.resolution_counts),n=Ut(e.disposition_counts);if(typeof e.plan_id!=`string`||typeof e.audit_id!=`string`||![`open`,`applied`].includes(String(e.status))||!Number.isSafeInteger(e.review_version)||!Number.isSafeInteger(e.memory_count)||!Number.isSafeInteger(e.group_count)||!Number.isSafeInteger(e.deterministic_groups)||!Number.isSafeInteger(e.pending_deterministic_groups)||!Number.isSafeInteger(e.exception_groups)||!Number.isSafeInteger(e.recommended_groups)||e.applied_at!==null&&typeof e.applied_at!=`string`||!t||!n)return null;for(let e of[`adopt`,`consolidate`,`obsolete`,`needs_review`])if(!Number.isSafeInteger(t[e]))return null;for(let e of[`pending`,`approve`,`reject`,`defer`])if(!Number.isSafeInteger(n[e]))return null;return{appliedAt:e.applied_at,auditId:e.audit_id,deterministicGroups:e.deterministic_groups,pendingDeterministicGroups:e.pending_deterministic_groups,dispositionCounts:n,exceptionGroups:e.exception_groups,groupCount:e.group_count,memoryCount:e.memory_count,planId:e.plan_id,recommendedGroups:e.recommended_groups,resolutionCounts:t,reviewVersion:e.review_version,status:e.status}}function Yt(e){if(!K(e)||typeof e.group_id!=`string`||typeof e.classification!=`string`||![`adopt`,`consolidate`,`obsolete`,`needs_review`].includes(String(e.resolution))||typeof e.deterministic!=`boolean`||typeof e.bulk_eligible!=`boolean`||!K(e.decision)||!K(e.decision.recommendation)||!Array.isArray(e.prior_review_evidence))return null;let t=e.prior_review_evidence.map(e=>!K(e)||typeof e.candidate_id!=`string`||![`approve`,`reject`,`defer`].includes(String(e.disposition))||typeof e.operator_note!=`string`||!Number.isSafeInteger(e.state_version)||!Array.isArray(e.memory_ids)||!e.memory_ids.every(e=>typeof e==`string`)?null:{candidateId:e.candidate_id,disposition:e.disposition,memoryIds:e.memory_ids,operatorNote:e.operator_note,stateVersion:e.state_version});if(t.some(e=>e===null))return null;let n=qt({candidate_id:e.group_id,state_sha256:e.state_sha256,category:e.classification,uncertainty:e.deterministic?`low`:`high`,rationale:e.rationale,proposed_action:e.proposed_action,evidence:e.evidence,decision:e.decision});if(!n)return null;let r=e.missing_fields===void 0?[]:e.missing_fields,i=e.related_group_ids===void 0?[]:e.related_group_ids,a=e.consolidation_id===void 0?null:e.consolidation_id;return!Array.isArray(r)||!r.every(e=>typeof e==`string`)||!Array.isArray(i)||!i.every(e=>typeof e==`string`)||a!==null&&typeof a!=`string`?null:{bulkEligible:e.bulk_eligible,classification:e.classification,consolidationId:a,missingFields:r,relatedGroupIds:i,decision:{...n.decision,recommendation:e.decision.recommendation},deterministic:e.deterministic,evidence:n.evidence,groupId:e.group_id,priorReviewEvidence:t,proposedAction:n.proposedAction,rationale:n.rationale,resolution:e.resolution,stateSha256:n.stateSha256}}async function Xt(e){let t=await X({channelId:``,token:e},`/v1/memory/reconciliation`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load memory triage.`));if(!K(n)||n.version!==1||!(`triage`in n))throw Error(`Kai returned an unsupported memory triage summary.`);if(n.triage===null)return null;let r=Jt(n.triage);if(!r)throw Error(`Kai returned an unsupported memory triage summary.`);return r}async function Zt(e,t,n={}){let r=new URLSearchParams;n.disposition&&r.set(`disposition`,n.disposition),n.resolution&&r.set(`resolution`,n.resolution),n.exceptionsOnly&&r.set(`exceptions_only`,`1`),n.offset!==void 0&&r.set(`offset`,String(n.offset)),n.limit!==void 0&&r.set(`limit`,String(n.limit));let i=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/groups?${r}`),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not load memory triage groups.`));let o=K(a)?Jt(a.triage):null;if(!K(a)||a.version!==1||!o||!Array.isArray(a.groups)||a.next_offset!==null&&!Number.isSafeInteger(a.next_offset))throw Error(`Kai returned an unsupported memory triage page.`);let s=a.groups.map(Yt);if(s.some(e=>e===null))throw Error(`Kai returned an unsupported memory triage group.`);return{triage:o,groups:s,nextOffset:a.next_offset}}async function Qt(e,t,n,r=null){let i=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/safe/preview`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({group_ids:r,expected_review_version:n})}),a=await Y(i),o=K(a)?Ut(a.resolution_counts):null;if(!i.ok)throw Error(J(a,`Could not preview safe memory groups.`));if(!K(a)||a.version!==1||typeof a.plan_id!=`string`||typeof a.preview_sha256!=`string`||!Array.isArray(a.group_ids)||!a.group_ids.every(e=>typeof e==`string`)||!Number.isSafeInteger(a.group_count)||!Number.isSafeInteger(a.memory_count)||!Number.isSafeInteger(a.review_version)||!o)throw Error(`Kai returned an unsupported safe-memory preview.`);return{groupCount:a.group_count,groupIds:a.group_ids,memoryCount:a.memory_count,planId:a.plan_id,previewSha256:a.preview_sha256,resolutionCounts:o,reviewVersion:a.review_version}}async function $t(e,t){let n=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t.planId)}/safe/approve`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({group_ids:t.groupIds,expected_review_version:t.reviewVersion,preview_sha256:t.previewSha256,operator_note:`Approved deterministic legacy-memory triage after preview.`,confirmation:`approve deterministic memory groups`,client_operation_id:Fn()})}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not approve safe memory groups.`))}async function en(e,t,n,r){let i=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/groups/${encodeURIComponent(n)}/decision`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({disposition:r.disposition,action:r.action,operator_note:r.operatorNote,expected_state_version:r.expectedStateVersion,client_operation_id:Fn()})}),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not save memory triage decision.`))}function tn(e){return!K(e)||typeof e.consolidation_id!=`string`||!Number.isSafeInteger(e.revision)||!Array.isArray(e.group_ids)||!e.group_ids.every(e=>typeof e==`string`)||typeof e.content!=`string`||e.scope_kind!==`global`&&e.scope_kind!==`project`||e.scope_key!==null&&typeof e.scope_key!=`string`||typeof e.source_memory_id!=`string`||typeof e.operator_note!=`string`||!Number.isSafeInteger(e.selected_facts)||!Number.isSafeInteger(e.duplicates_excluded)?null:{consolidationId:e.consolidation_id,content:e.content,duplicatesExcluded:e.duplicates_excluded,groupIds:e.group_ids,operatorNote:e.operator_note,revision:e.revision,scopeKey:e.scope_key,scopeKind:e.scope_kind,selectedFacts:e.selected_facts,sourceMemoryId:e.source_memory_id}}async function nn(e,t){let n=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/consolidations`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load consolidations.`));let i=K(r)&&r.version===1&&Array.isArray(r.consolidations)?r.consolidations.map(tn):null;if(!i||i.some(e=>e===null))throw Error(`Kai returned unsupported consolidations.`);return i}async function rn(e,t,n){let r=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/consolidations`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({group_ids:n.groupIds,expected_state_versions:n.expectedStateVersions,canonical:{content:n.canonical.content,source_memory_id:n.canonical.sourceMemoryId,scope_kind:n.canonical.scopeKind,...n.canonical.scopeKind===`project`?{scope_key:n.canonical.scopeKey}:{}},operator_note:n.operatorNote,...n.consolidationId===void 0?{}:{consolidation_id:n.consolidationId,expected_revision:n.expectedRevision},client_operation_id:Fn()})}),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not save the consolidation.`));let a=K(i)&&i.version===1?tn(i.consolidation):null;if(!a)throw Error(`Kai returned an unsupported consolidation.`);return a}async function an(e,t,n,r){let i=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/consolidations/${encodeURIComponent(n)}/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({expected_revision:r,client_operation_id:Fn()})}),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not cancel the consolidation.`))}async function on(e,t){let n=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/recommend`,{method:`POST`}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not analyze uncertain memory groups.`));if(!K(r)||typeof r.recommended!=`number`||!Number.isFinite(r.recommended)||typeof r.remaining!=`number`||!Number.isFinite(r.remaining))throw Error(`Kai returned an unsupported memory triage analysis result.`);return{recommended:r.recommended,remaining:r.remaining}}async function sn(e,t,n){let r=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/apply`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({expected_review_version:n,confirmation:`apply grouped memory triage`,client_operation_id:Fn()})}),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not apply grouped memory triage.`));if(!K(i)||i.version!==1||!K(i.summary))throw Error(`Kai returned an unsupported memory triage receipt.`);return Ut(i.summary)??{}}function cn(e){if(!K(e)||e.version!==1||![`move_scope`,`delete`].includes(String(e.operation))||!Array.isArray(e.results))return null;let t=e.results.map(e=>{if(!K(e)||typeof e.memory_id!=`string`||![`succeeded`,`not_found`,`stale`,`failed`,`awaiting_reconciliation`].includes(String(e.outcome)))return null;let t=e.prior_scope===null?null:Gt(e.prior_scope),n=e.new_scope===null?null:Gt(e.new_scope);return e.prior_scope!==null&&t===null||e.new_scope!==null&&n===null?null:{memoryId:e.memory_id,newScope:n,outcome:e.outcome,priorScope:t}});return t.some(e=>e===null)?null:{operation:e.operation,results:t}}async function ln(e,t,n){let r=await X({channelId:``,token:e},t,n),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not update memories.`));let a=cn(i);if(!a)throw Error(`Kai returned an unsupported memory mutation result.`);return a}async function un(e,t,n){return ln(e,`/v1/memory/records/${encodeURIComponent(t)}/scope`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n.scope===`global`?{scope:`global`}:{scope:`project`,project_id:n.projectId})})}async function dn(e,t,n){return ln(e,`/v1/memory/actions/scope`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n.scope===`global`?{memory_ids:t,scope:`global`}:{memory_ids:t,scope:`project`,project_id:n.projectId})})}async function fn(e,t){return ln(e,`/v1/memory/records/${encodeURIComponent(t)}`,{method:`DELETE`})}async function pn(e,t){return ln(e,`/v1/memory/actions/delete`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({memory_ids:t})})}function mn(e){let t=new URLSearchParams;return e.kind!==void 0&&t.set(`kind`,e.kind),e.lifecycle!==void 0&&t.set(`lifecycle`,e.lifecycle),e.source!==void 0&&t.set(`source`,e.source),e.memoryType!==void 0&&t.set(`memory_type`,e.memoryType),e.tag!==void 0&&t.set(`tag`,e.tag),e.scope!==void 0&&t.set(`scope`,e.scope),e.projectId!==void 0&&t.set(`project_id`,e.projectId),e.limit!==void 0&&t.set(`limit`,String(e.limit)),t}async function hn(e,t={}){let n=mn(t);t.cursor!==void 0&&n.set(`cursor`,t.cursor),t.order!==void 0&&n.set(`order`,t.order);let r=n.size?`?${n}`:``,i=await X({channelId:``,token:e},`/v1/memory/records${r}`),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not load memories.`));if(!K(a)||a.version!==1||!Array.isArray(a.records)||a.next_cursor!==null&&typeof a.next_cursor!=`string`)throw Error(`Kai returned an unsupported memory page.`);let o=a.records.map(Wt);if(o.some(e=>e===null))throw Error(`Kai returned an unsupported memory record.`);return{nextCursor:a.next_cursor,records:o}}async function gn(e,t,n={}){let r=mn(n);r.set(`q`,t);let i=await X({channelId:``,token:e},`/v1/memory/search?${r}`),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not search memories.`));if(!K(a)||a.version!==1||a.active_project_id!==null&&typeof a.active_project_id!=`string`||typeof a.reason!=`string`||!Array.isArray(a.hits))throw Error(`Kai returned unsupported memory search results.`);let o=a.hits.map(e=>{if(!K(e)||typeof e.raw_score!=`number`||typeof e.adjusted_score!=`number`||typeof e.compact_recall!=`string`)return null;let t=Wt(e.record);return t?{adjustedScore:e.adjusted_score,compactRecall:e.compact_recall,rawScore:e.raw_score,record:t}:null});if(o.some(e=>e===null))throw Error(`Kai returned unsupported memory search results.`);return{activeProjectId:a.active_project_id,hits:o,reason:a.reason}}function _n(e){if(e===null)return null;if(K(e)&&!([`goal`,`context`,`approach`,`outcome`,`outcome_quality`].some(t=>typeof e[t]!=`string`)||e.lessons!==void 0&&typeof e.lessons!=`string`||!Array.isArray(e.tags)||!e.tags.every(e=>typeof e==`string`)||!Array.isArray(e.actors)||!e.actors.every(e=>typeof e==`string`)||![`success`,`partial`,`failure`].includes(String(e.outcome_quality))))return{actors:e.actors,approach:e.approach,context:e.context,goal:e.goal,lessons:typeof e.lessons==`string`?e.lessons:null,outcome:e.outcome,outcomeQuality:e.outcome_quality,tags:e.tags}}function vn(e){if(!K(e)||![`canonical`,`legacy`].includes(String(e.authority))||![`fact`,`episode`].includes(String(e.kind))||typeof e.identity!=`string`||typeof e.createdAt!=`string`||typeof e.currentState!=`string`||e.currentRevisionId!==null&&typeof e.currentRevisionId!=`string`||e.runtimeProfileId!==null&&typeof e.runtimeProfileId!=`string`||!K(e.scope)||typeof e.scope.kind!=`string`||e.scope.key!==null&&typeof e.scope.key!=`string`||!Array.isArray(e.revisions)||!Array.isArray(e.events)||!Array.isArray(e.followups))return null;let t=e.revisions.filter(K),n=e.events.filter(K),r=e.followups.filter(K);return t.length!==e.revisions.length||n.length!==e.events.length||r.length!==e.followups.length||t.some(e=>typeof e.revisionId!=`string`||typeof e.content!=`string`||typeof e.reason!=`string`||typeof e.state!=`string`||typeof e.storedAt!=`string`)||n.some(e=>typeof e.eventPosition!=`number`||typeof e.newState!=`string`||typeof e.occurredAt!=`string`||typeof e.reason!=`string`||typeof e.revisionId!=`string`||typeof e.transition!=`string`||e.previousState!==null&&typeof e.previousState!=`string`)||r.some(e=>typeof e.createdAt!=`string`||typeof e.reason!=`string`||typeof e.relationship!=`string`||typeof e.sourceEpisodeId!=`string`||typeof e.targetEpisodeId!=`string`)||e.migrationGaps!==void 0&&(!Array.isArray(e.migrationGaps)||!e.migrationGaps.every(e=>typeof e==`string`))?null:e}function yn(e){if(!K(e))return null;let t=Wt(e),n=_n(e.episode),r=vn(e.lifecycle);return!t||n===void 0||!r||typeof e.content!=`string`||typeof e.compact_recall!=`string`||e.confirmation_quote!==null&&typeof e.confirmation_quote!=`string`||e.prompt_version!==null&&typeof e.prompt_version!=`string`?null:{...t,compactRecall:e.compact_recall,confirmationQuote:e.confirmation_quote,content:e.content,episode:n,lifecycle:r,promptVersion:e.prompt_version}}async function bn(e,t){let n=await X({channelId:``,token:e},`/v1/memory/records/${encodeURIComponent(t)}`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load this memory.`));let i=K(r)&&r.version===1?yn(r.record):null;if(!i)throw Error(`Kai returned an unsupported memory detail.`);return i}function xn(e){return K(e)&&typeof e.kind==`string`&&(e.key===null||typeof e.key==`string`)?{kind:e.kind,key:e.key}:null}function Sn(e){if(!K(e)||typeof e.claim_id!=`string`||typeof e.opened_at!=`string`||!Array.isArray(e.revisions))return null;let t=xn(e.scope),n=e.revisions.map(e=>K(e)&&typeof e.revision_id==`string`&&typeof e.preview==`string`&&typeof e.stored_at==`string`?{preview:e.preview,revisionId:e.revision_id,storedAt:e.stored_at}:null);return!t||n.some(e=>e===null)?null:{claimId:e.claim_id,openedAt:e.opened_at,revisions:n,scope:t}}function Cn(e){if(!K(e)||typeof e.claim_id!=`string`||typeof e.revision_id!=`string`||typeof e.changed_at!=`string`||typeof e.reason!=`string`||typeof e.preview!=`string`||e.state!==`retracted`&&e.state!==`expired`)return null;let t=xn(e.scope);return t?{changedAt:e.changed_at,claimId:e.claim_id,preview:e.preview,reason:e.reason,revisionId:e.revision_id,scope:t,state:e.state}:null}async function wn(e,t,n,r,i){let a=await X({channelId:``,token:e},t),o=await Y(a);if(!a.ok)throw Error(J(o,i));let s=K(o)&&o.version===1&&Array.isArray(o[n])?o[n].map(r):null;if(!s||s.some(e=>e===null)||!K(o)||!Number.isSafeInteger(o.total))throw Error(`Kai returned an unsupported memory review list.`);return{items:s,total:o.total}}async function Tn(e){return wn(e,`/v1/memory/conflicts`,`conflicts`,Sn,`Could not load memory conflicts.`)}async function En(e){return wn(e,`/v1/memory/forgotten`,`facts`,Cn,`Could not load forgotten facts.`)}async function Dn(e,t){let n=await X({channelId:``,token:e},`/v1/memory/conflicts/${encodeURIComponent(t)}`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load this conflict.`));let i=K(r)&&r.version===1?vn(r.lifecycle):null;if(!i)throw Error(`Kai returned an unsupported memory conflict.`);return i}async function On(e,t,n,r){let i=await X({channelId:``,token:e},t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,client_operation_id:Fn()})}),a=await Y(i);if(i.status===409&&K(a)&&K(a.error)&&a.error.code===`memory_conflict_changed`)throw new ie(J(a,`This conflict changed since you opened it.`));if(!i.ok)throw Error(J(a,r));if(!K(a)||a.version!==1||typeof a.claim_id!=`string`||typeof a.active_revision_id!=`string`||typeof a.replayed!=`boolean`||a.memory_id!==null&&typeof a.memory_id!=`string`)throw Error(`Kai returned an unsupported memory review result.`);return{activeRevisionId:a.active_revision_id,claimId:a.claim_id,memoryId:a.memory_id,replayed:a.replayed}}async function kn(e,t,n){return On(e,`/v1/memory/conflicts/${encodeURIComponent(t)}/resolve`,{keep_revision_id:n.keepRevisionId,expected_revision_ids:n.expectedRevisionIds,note:n.note},`Could not resolve this conflict.`)}async function An(e,t,n){return On(e,`/v1/memory/forgotten/${encodeURIComponent(t)}/restore`,{revision_id:n.revisionId,note:n.note},`Could not restore this fact.`)}function jn(e){return!K(e)||e.kind!==`fact`&&e.kind!==`episode`||typeof e.id!=`string`||typeof e.operation!=`string`||!Number.isSafeInteger(e.attempts)||typeof e.updated_at!=`string`||typeof e.preview!=`string`||e.revision_id!==null&&typeof e.revision_id!=`string`||e.error_code!==null&&typeof e.error_code!=`string`?null:{attempts:e.attempts,errorCode:e.error_code,id:e.id,kind:e.kind,operation:e.operation,preview:e.preview,revisionId:e.revision_id,updatedAt:e.updated_at}}async function Mn(e){let t=await X({channelId:``,token:e},`/v1/memory/projections`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load search sync status.`));let r=K(n)&&n.version===1&&Array.isArray(n.failed)?n.failed.map(jn):null;if(!r||r.some(e=>e===null)||!K(n)||!Number.isSafeInteger(n.failed_total)||!Number.isSafeInteger(n.blocked))throw Error(`Kai returned an unsupported search sync status.`);return{blocked:n.blocked,failed:r,failedTotal:n.failed_total}}async function Nn(e){let t=await X({channelId:``,token:e},`/v1/memory/projections/audit`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not check the search index.`));let r=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`);if(!K(n)||n.version!==1||!r(n.orphan)||!r(n.unknown)||!Number.isSafeInteger(n.duplicate))throw Error(`Kai returned an unsupported search index check.`);return{duplicate:n.duplicate,orphan:n.orphan,unknown:n.unknown}}async function Pn(e,t={}){let n=await X({channelId:``,token:e},`/v1/memory/projections/retry`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...t.claimIds?{claim_ids:t.claimIds}:{},...t.episodeIds?{episode_ids:t.episodeIds}:{}})}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not retry search sync.`));if(!K(r)||r.version!==1||!Number.isSafeInteger(r.retried)||!Number.isSafeInteger(r.succeeded)||!Number.isSafeInteger(r.failed))throw Error(`Kai returned an unsupported search sync result.`);return{failed:r.failed,retried:r.retried,succeeded:r.succeeded}}function Fn(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`memory-${Date.now()}-${Math.random().toString(16).slice(2)}`}async function In(e,t,n){let r=await X({channelId:``,token:e},t,n),i=await Y(r);if(r.status===409&&K(i)&&K(i.error)&&typeof i.error.current_revision==`string`)throw new ae(J(i,`This memory changed since it was opened.`),i.error.current_revision);if(!r.ok)throw Error(J(i,`Could not save this memory.`));return i}async function Ln(e,t){let n=await In(e,`/v1/memory/records`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({kind:`fact`,content:t.content,tags:t.tags,scope:t.target.scope,...t.target.scope===`project`?{project_id:t.target.projectId}:{},request_id:t.requestId??Fn()})});if(!K(n)||n.version!==1||typeof n.created!=`boolean`)throw Error(`Kai returned an unsupported memory creation result.`);let r=yn(n.record);if(!r)throw Error(`Kai returned an unsupported memory creation result.`);return{created:n.created,record:r}}async function Rn(e,t){let n=t.kind===`fact`?{kind:`fact`,revision:t.revision,request_id:t.requestId??Fn(),content:t.content,tags:t.tags}:{kind:`episode`,revision:t.revision,request_id:t.requestId??Fn(),episode:{goal:t.episode.goal,context:t.episode.context,approach:t.episode.approach,outcome:t.episode.outcome,outcome_quality:t.episode.outcomeQuality,...t.episode.lessons?{lessons:t.episode.lessons}:{},tags:t.episode.tags,actors:t.episode.actors}},r=await In(e,`/v1/memory/records/${encodeURIComponent(t.memoryId)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!K(r)||r.version!==1||!Array.isArray(r.changed_fields)||!r.changed_fields.every(e=>typeof e==`string`)||typeof r.idempotent_replay!=`boolean`)throw Error(`Kai returned an unsupported memory edit result.`);let i=yn(r.record);if(!i)throw Error(`Kai returned an unsupported memory edit result.`);return{changedFields:r.changed_fields,idempotentReplay:r.idempotent_replay,record:i}}function zn(e){return!K(e)||typeof e.message_id!=`string`||typeof e.channel_id!=`string`||!b.test(e.channel_id)||typeof e.author_principal_id!=`string`||!E.test(e.author_principal_id)||typeof e.author_kind!=`string`||typeof e.author_display_name!=`string`||typeof e.body!=`string`||typeof e.created_at!=`string`?null:{authorDisplayName:e.author_display_name,authorKind:e.author_kind,authorPrincipalId:e.author_principal_id,body:e.body,channelId:e.channel_id,createdAt:e.created_at,messageId:e.message_id}}async function Bn(e,t){let n=await X({channelId:``,token:e},`/v1/memory/records/${encodeURIComponent(t)}/source`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load memory source context.`));if(!K(r)||r.version!==1||!K(r.source_context))throw Error(`Kai returned unsupported memory source context.`);let i=r.source_context,a=i.source===null?null:zn(i.source),o=i.result===null?null:zn(i.result);if(typeof i.status!=`string`||![`available`,`unavailable`].includes(i.status)||i.reason!==null&&typeof i.reason!=`string`||i.run_id!==null&&typeof i.run_id!=`string`||i.source!==null&&a===null||i.result!==null&&o===null)throw Error(`Kai returned unsupported memory source context.`);return{reason:i.reason,result:o,runId:i.run_id,source:a,status:i.status}}async function Vn(e){let t=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/settings`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load settings and workspaces.`));return Et(n,e.channelId)}function Hn(e){if(e===null)return null;if(!K(e)||typeof e.run_id!=`string`||typeof e.status!=`string`||![`accepted`,`started`,`completed`,`failed`,`cancelled`].includes(e.status)||typeof e.accepted_at!=`string`||typeof e.started_at!=`string`&&e.started_at!==null||typeof e.terminal_at!=`string`&&e.terminal_at!==null||typeof e.terminal_code!=`string`&&e.terminal_code!==null)throw Error(`Kai returned an unsupported runtime run status.`);return{acceptedAt:e.accepted_at,runId:e.run_id,startedAt:e.started_at,status:e.status,terminalAt:e.terminal_at,terminalCode:e.terminal_code}}async function Un(e,t=null){let n=await X(e,t===null?`/v1/channels/${encodeURIComponent(e.channelId)}/runtime-status`:`/v1/channels/${encodeURIComponent(e.channelId)}/runtime-status?agent_id=${encodeURIComponent(t)}`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load runtime status.`));if(!K(r)||r.version!==1||r.channel_id!==e.channelId||typeof r.agent_id!=`string`||!x.test(r.agent_id)||typeof r.agent_name!=`string`||typeof r.agent_handle!=`string`||typeof r.sponsor_display_name!=`string`||typeof r.can_manage_runtime!=`boolean`||typeof r.backend!=`string`||typeof r.provider!=`string`||!K(r.model)||typeof r.model.value!=`string`||typeof r.model.source!=`string`||!K(r.timeout_seconds)||!Number.isSafeInteger(r.timeout_seconds.value)||typeof r.timeout_seconds.source!=`string`||![`owner`,`neutral`].includes(String(r.workspace_mode))||typeof r.workspace_label!=`string`&&r.workspace_label!==null||typeof r.workspace!=`string`&&r.workspace!==null||typeof r.workspace_revision!=`string`&&r.workspace_revision!==null||!Array.isArray(r.workspaces)||![`alive`,`stopped`,`hidden`].includes(String(r.process_state))||![`not_started`,`active`,`refresh_pending`,`stateless`,`stale`].includes(String(r.provider_session_state))||![`not_started`,`active`,`refresh_pending`,`stale`].includes(String(r.continuity_state))||typeof r.session_created_at!=`string`&&r.session_created_at!==null||typeof r.session_updated_at!=`string`&&r.session_updated_at!==null||!(Number.isSafeInteger(r.fresh_session_generation)||r.fresh_session_generation===null)||typeof r.fresh_session_revision!=`string`&&r.fresh_session_revision!==null||typeof r.fresh_session_revision==`string`&&!/^[0-9a-f]{64}$/.test(r.fresh_session_revision)||!(r.operator_diagnostics===null||K(r.operator_diagnostics)))throw Error(`Kai returned an unsupported runtime lane status.`);let i=r.workspaces.map(e=>{if(!K(e)||typeof e.path!=`string`||typeof e.name!=`string`||typeof e.current!=`boolean`||typeof e.home!=`boolean`)throw Error(`Kai returned unsupported effective workspace choices.`);return{current:e.current,home:e.home,name:e.name,path:e.path}}),a=r.workspace_mode;if(a===`neutral`&&(r.workspace!==null||r.workspace_revision!==null||i.length!==0)||a===`owner`&&(typeof r.workspace!=`string`||typeof r.workspace_revision!=`string`))throw Error(`Kai returned an inconsistent effective workspace.`);let o=r.operator_diagnostics;if(o!==null&&(!K(o)||typeof o.runtime_profile_id!=`string`||!D.test(o.runtime_profile_id)||typeof o.provider_session_revision!=`string`&&o.provider_session_revision!==null||typeof o.provider_session_present!=`boolean`||typeof o.last_run_id!=`string`&&o.last_run_id!==null||!(Number.isSafeInteger(o.context_through_event_position)||o.context_through_event_position===null)))throw Error(`Kai returned unsupported runtime diagnostics.`);return{activeRun:Hn(r.active_run),agentHandle:r.agent_handle,agentId:r.agent_id,agentName:r.agent_name,backend:r.backend,canManageRuntime:r.can_manage_runtime,channelId:r.channel_id,continuityState:r.continuity_state,freshSessionGeneration:r.fresh_session_generation,freshSessionRevision:r.fresh_session_revision,lastRun:Hn(r.last_run),model:{source:r.model.source,value:r.model.value},operatorDiagnostics:o===null?null:{contextThroughEventPosition:o.context_through_event_position,lastRunId:o.last_run_id,providerSessionPresent:o.provider_session_present,providerSessionRevision:o.provider_session_revision,runtimeProfileId:o.runtime_profile_id},processState:r.process_state,provider:r.provider,providerSessionState:r.provider_session_state,sessionCreatedAt:r.session_created_at,sessionUpdatedAt:r.session_updated_at,sponsorDisplayName:r.sponsor_display_name,timeoutSeconds:{source:r.timeout_seconds.source,value:r.timeout_seconds.value},workspaceMode:a,workspaceLabel:r.workspace_label,workspace:r.workspace,workspaceRevision:r.workspace_revision,workspaces:i}}async function Wn(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/runtime-sessions/${encodeURIComponent(t)}/fresh`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_operation_id:n})}),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not start a fresh provider session.`));if(!K(i)||i.version!==1||i.channel_id!==e.channelId||i.agent_id!==t||typeof i.runtime_profile_id!=`string`||!D.test(i.runtime_profile_id)||!Number.isSafeInteger(i.generation)||i.generation<1||typeof i.revision!=`string`||!/^[0-9a-f]{64}$/.test(i.revision)||typeof i.prior_session_present!=`boolean`||typeof i.live_process_stopped!=`boolean`||typeof i.replayed!=`boolean`||!Array.isArray(i.preserved))throw Error(`Kai returned an unsupported fresh provider session result.`);return{agentId:i.agent_id,channelId:i.channel_id,generation:i.generation,liveProcessStopped:i.live_process_stopped,priorSessionPresent:i.prior_session_present,replayed:i.replayed,revision:i.revision,runtimeProfileId:i.runtime_profile_id}}async function Gn(e,t){let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/models?option_id=${encodeURIComponent(t)}`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load the model catalogue.`));return kt(r)}async function Kn(e,t){let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/models`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({option_id:t})}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not refresh the model catalogue.`));return kt(r)}async function qn(e){let t=await X(e,`/v1/settings/model-catalogue/refresh-all`,{method:`POST`}),n=await Y(t);if(!t.ok||!K(n)||n.version!==1||!Number.isSafeInteger(n.contexts)||!K(n.statuses)||Object.values(n.statuses).some(e=>!Number.isSafeInteger(e)))throw Error(J(n,`Could not refresh all model catalogues.`));return{contexts:n.contexts,statuses:n.statuses}}async function Jn(e,t,n,r){let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({option_id:t,model_id:n,display_label:r})}),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not save the operator model.`));return kt(a)}async function Yn(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/models`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({option_id:t,model_id:n})}),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not deactivate the operator model.`));return kt(i)}async function Xn(e){let t=await X(e,`/v1/settings/github`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load GitHub settings.`));return At(n)}async function Zn(e,t,n){let r=n.field===`repository`?{repository:{name:n.name,subscribed:n.subscribed}}:n.field===`repository_reset`?{reset_repositories:!0}:n.field===`toggle`?{toggle:{field:n.name,enabled:n.enabled}}:{token:n.token},i=await X(e,`/v1/settings/github`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,...r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`GitHub settings changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not update GitHub settings.`));return At(a)}function Qn(e){if(!K(e)||typeof e.review_job_id!=`string`||typeof e.repository!=`string`||!Number.isSafeInteger(e.pull_request_number)||![`pending`,`executing`,`succeeded`,`failed`,`cancelled`,`timed_out`].includes(String(e.status))||!Number.isSafeInteger(e.attempt_count)||e.last_error_code!==null&&typeof e.last_error_code!=`string`||typeof e.created_at!=`string`||typeof e.updated_at!=`string`||typeof e.replayed!=`boolean`||e.artifact!==null&&(!K(e.artifact)||typeof e.artifact.artifact_id!=`string`||typeof e.artifact.filename!=`string`||!Number.isSafeInteger(e.artifact.warning_count)||!Array.isArray(e.artifact.warnings)||e.artifact.warnings.some(e=>!K(e)||typeof e.source!=`string`||typeof e.message!=`string`)))throw Error(`Kai returned an unsupported review job.`);let t=e.artifact;return{artifact:t===null?null:{artifactId:t.artifact_id,filename:t.filename,warningCount:t.warning_count,warnings:t.warnings.map(e=>({message:e.message,source:e.source}))},attemptCount:e.attempt_count,createdAt:e.created_at,lastErrorCode:e.last_error_code,pullRequestNumber:e.pull_request_number,repository:e.repository,replayed:e.replayed,reviewJobId:e.review_job_id,status:e.status,updatedAt:e.updated_at}}async function $n(e){let t=await X(e,`/v1/client/reviews?limit=20`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load pull-request reviews.`));if(!K(n)||n.version!==1||!Array.isArray(n.jobs)||!K(n.submission)||!Array.isArray(n.submission.repositories)||n.submission.repositories.some(e=>typeof e!=`string`)||typeof n.submission.active_workspace!=`string`||n.submission.active_workspace_repository!==null&&typeof n.submission.active_workspace_repository!=`string`||n.submission.inferred_repository!==null&&typeof n.submission.inferred_repository!=`string`)throw Error(`Kai returned unsupported pull-request review options.`);return{jobs:n.jobs.map(Qn),submission:{activeWorkspace:n.submission.active_workspace,activeWorkspaceRepository:n.submission.active_workspace_repository,inferredRepository:n.submission.inferred_repository,repositories:n.submission.repositories}}}async function er(e,t,n,r){let i=await X(e,`/v1/client/reviews`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({repository:t,pull_request_number:n,client_operation_id:r})}),a=await Y(i);if(!i.ok||!K(a)||a.version!==1)throw Error(J(a,`Could not start the pull-request review.`));return Qn(a.job)}async function tr(e,t,n,r){let i=await X(e,`/v1/client/reviews/${encodeURIComponent(t)}/${n}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_operation_id:r})}),a=await Y(i);if(!i.ok||!K(a)||a.version!==1)throw Error(J(a,`Could not ${n} the pull-request review.`));return Qn(a.job)}async function nr(e,t){let n=await X(e,`/v1/client/reviews/${encodeURIComponent(t)}/artifact`);if(!n.ok){let e=await Y(n);throw Error(J(e,`Could not open the review artifact.`))}return n.blob()}async function rr(e,t){if(!t.artifact)throw Error(`This review has no artifact.`);let n=await X(e,`/v1/client/reviews/${encodeURIComponent(t.reviewJobId)}/artifact?download=1`);if(!n.ok)throw Error(`Could not download the review artifact.`);let r=URL.createObjectURL(await n.blob()),i=document.createElement(`a`);i.href=r,i.download=t.artifact.filename,i.click(),URL.revokeObjectURL(r)}async function ir(e){let t=await X(e,`/v1/settings/notifications`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load notification preferences.`));return jt(n)}async function ar(e,t,n){let r=n.field===`destination`?{destination_choice_id:n.choiceId,integration_class:n.integrationClass}:{integration_class:n.integrationClass,reset:!0},i=await X(e,`/v1/settings/notifications`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,...r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Notification preferences changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not update notification preferences.`));return jt(a)}async function or(e){let t=await X(e,`/v1/settings/channel-notifications`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load channel notification policy.`));return Mt(n)}async function sr(e,t,n){let r=n.field===`channel`?{channel:{channel_id:n.channelId,level:n.level}}:n.field===`muted_mentions_notify`?{muted_mentions_notify:n.enabled}:n.field===`adapter_delivery`?{adapter_delivery:{transport:n.transport,enabled:n.enabled}}:{do_not_disturb:{enabled:n.enabled,timezone:n.timezone,start:n.start,end:n.end}},i=await X(e,`/v1/settings/channel-notifications`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,...r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Channel notification policy changed since it was loaded.`));if(!i.ok)throw Error(J(a,`Could not update channel notification policy.`));return Mt(a)}async function cr(e){let t=await X(e,`/v1/settings/clients`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load client preferences.`));return Nt(n)}async function lr(e){let t=await X({channelId:``,token:e.token},`/v1/settings/appearance`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load appearance preferences.`));return Pt(n)}async function ur(e,t,n){let r=await X(e,`/v1/settings/appearance`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,theme_id:n})}),i=await Y(r);if(r.status===409)throw new W(J(i,`Appearance preferences changed since they were loaded.`));if(!r.ok)throw Error(J(i,`Could not update appearance preferences.`));return Pt(i)}async function dr(e){let t=await X({channelId:``,token:e.token},`/v1/settings/profile`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load your profile.`));return Ft(n)}async function fr(e){let t=await X({channelId:``,token:e.token},`/v1/settings/profile/avatar`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load your avatar.`));return It(n)}async function pr(e,t,n,r){let i=new FormData;i.append(`expected_state_version`,String(n)),i.append(`client_operation_id`,r),i.append(`file`,t,t.name);let a=await X({channelId:``,token:e.token},`/v1/settings/profile/avatar`,{method:`POST`,body:i}),o=await Y(a);if(a.status===409)throw new W(J(o,`Your avatar changed since it was loaded.`));if(!a.ok)throw Error(J(o,`Could not save your avatar.`));return It(o)}async function mr(e,t,n){let r=await X({channelId:``,token:e.token},`/v1/settings/profile/avatar`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({expected_state_version:t,client_operation_id:n})}),i=await Y(r);if(r.status===409)throw new W(J(i,`Your avatar changed since it was loaded.`));if(!r.ok)throw Error(J(i,`Could not clear your avatar.`));return It(i)}async function hr(e,t,n,r){let i=await X({channelId:``,token:e.token},`/v1/settings/profile`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({display_name:t,expected_state_version:n,client_operation_id:r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Your profile changed since it was loaded.`));if(!i.ok)throw Error(J(a,`Could not update your profile.`));return Ft(a)}async function gr(e,t,n){let r=n.field===`mode`?{mode:n.value}:{voice:n.value},i=await X(e,`/v1/settings/clients`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,binding_choice_id:n.bindingChoiceId,...r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Client preferences changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not update client preferences.`));return Nt(a)}async function _r(e,t,n){let r=n.field===`model`?{model:n.value}:n.field===`backend`?{backend:n.value}:n.field===`timeout`?{timeout_seconds:n.value}:{reset:n.value},i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/settings`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,...r})}),a=await Y(i);if(i.status===409)throw K(a)&&K(a.error)&&a.error.code===`runtime_busy`?Error(J(a,`Finish or stop the active run before switching backends.`)):new W(J(a,`Settings changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not update runtime settings.`));return Et(a,e.channelId)}async function vr(e){let t=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace-config`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load workspace settings.`));return Lt(n)}async function yr(e){let t=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/memory-projects`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load memory projects.`));return Rt(n)}async function br(e,t,n,r){let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/memory-projects`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,name:n,...r?{workspace_path:r}:{}})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Memory projects changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not register memory project.`));return Rt(a)}async function xr(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/memory-projects/${encodeURIComponent(n)}`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t})}),i=await Y(r);if(r.status===409)throw new W(J(i,`Memory projects changed since they were loaded.`));if(!r.ok)throw Error(J(i,`Could not unregister memory project.`));return Rt(i)}async function Sr(e,t,n){let r=n.field===`reset`?{reset:n.value}:{field:n.field,value:n.value},i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace-config`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,...r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Workspace settings changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not update workspace settings.`));return Lt(a)}async function Cr(e,t,n,r){let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace-environment/${encodeURIComponent(n)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,value:r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Workspace secrets changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not save workspace secret.`));return Lt(a)}async function wr(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace-environment/${encodeURIComponent(n)}`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t})}),i=await Y(r);if(r.status===409)throw new W(J(i,`Workspace secrets changed since they were loaded.`));if(!r.ok)throw Error(J(i,`Could not remove workspace secret.`));return Lt(i)}async function Tr(e){let t=await X(e,`/v1/preferences`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load preferences.`));return Bt(n)}async function Er(e){let t=await X(e,`/v1/principal-policy`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load principal policy.`));return Vt(n)}async function Dr(e,t,n){let r=await X(e,`/v1/principal-policy`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({content:t,revision:n})}),i=await Y(r);if(r.status===409){let e=K(i)&&K(i.error)&&typeof i.error.current_revision==`string`?i.error.current_revision:``;throw new re(J(i,`Principal policy changed since it was opened.`),e)}if(!r.ok)throw Error(J(i,`Could not save principal policy.`));return Vt(i)}async function Or(e,t,n){let r=await X(e,`/v1/preferences`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({content:t,revision:n})}),i=await Y(r);if(r.status===409){let e=K(i)&&K(i.error)&&typeof i.error.current_revision==`string`?i.error.current_revision:``;throw new ne(J(i,`Preferences changed since they were opened.`),e)}if(!r.ok)throw Error(J(i,`Could not save preferences.`));return Bt(i)}async function kr(e){let t=await X(e,`/v1/preferences/revisions`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load preference history.`));return Ht(n)}async function Ar(e,t,n){let r=await X(e,`/v1/preferences/revisions/${encodeURIComponent(t)}/restore`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:n})}),i=await Y(r);if(r.status===409){let e=K(i)&&K(i.error)&&typeof i.error.current_revision==`string`?i.error.current_revision:``;throw new ne(J(i,`Preferences changed before they could be restored.`),e)}if(!r.ok)throw Error(J(i,`Could not restore preferences.`));return Bt(i)}async function jr(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t,revision:n})}),i=await Y(r);if(r.status===409)throw new W(J(i,`Settings changed since they were loaded.`));if(!r.ok)throw Error(J(i,`Could not switch workspace.`));return Et(i,e.channelId)}async function Mr(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspaces`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t,revision:n})}),i=await Y(r);if(r.status===409)throw new W(J(i,`Settings changed since they were loaded.`));if(!r.ok)throw Error(J(i,`Could not create workspace.`));if(!K(i)||!K(i.creation)||typeof i.creation.path!=`string`||typeof i.creation.directory_created!=`boolean`||typeof i.creation.git_ready!=`boolean`||typeof i.creation.memory_project_registered!=`boolean`||typeof i.creation.memory_project_note!=`string`)throw Error(`Kai returned an unsupported workspace creation result.`);return{directoryCreated:i.creation.directory_created,gitReady:i.creation.git_ready,memoryProjectNote:i.creation.memory_project_note,memoryProjectRegistered:i.creation.memory_project_registered,path:i.creation.path,settings:Et(i,e.channelId)}}async function Nr(e,t,n,r){let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspaces`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t,confirmation:n,revision:r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Settings changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not delete workspace.`));if(!K(a)||!K(a.deletion)||typeof a.deletion.path!=`string`||typeof a.deletion.directory_deleted!=`boolean`||a.deletion.memory_project_unregistered!==null&&typeof a.deletion.memory_project_unregistered!=`string`)throw Error(`Kai returned an unsupported workspace deletion result.`);return{directoryDeleted:a.deletion.directory_deleted,memoryProjectUnregistered:a.deletion.memory_project_unregistered,path:a.deletion.path,settings:Et(a,e.channelId)}}async function Pr(e){let t=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace-grants`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load workspace access.`));return Dt(n)}async function Fr(e,t){let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace-grants`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t})}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not add workspace access.`));return Dt(r)}async function Ir(e,t){let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace-grants`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t})}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not remove workspace access.`));return Dt(r)}async function Lr(e,t,n,r=null,i=null){if(i!==null&&!A.test(i))throw Error(`Invalid thread identity.`);if(r&&i)throw Error(`Thread attachments are not available yet.`);let a=r?(()=>{let e=new FormData;return e.append(`client_message_id`,t),e.append(`body`,n),e.append(`file`,r,r.name),{body:e,method:`POST`}})():{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({body:n,client_message_id:t,...i?{thread_root_id:i}:{}})},o=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/commands`,a),s=await Y(o);if(!o.ok)throw Error(J(s,`Kai could not run this command.`));if(K(s)&&s.version===3&&typeof s.acceptance==`string`&&typeof s.message_id==`string`&&Array.isArray(s.runs)){let t=s.runs.map(t=>ye(t,e.channelId));if(t.some(e=>e===null))throw Error(`Kai returned an unsupported command response.`);return{acceptance:s.acceptance,messageId:s.message_id,runs:t}}if(!K(s)||s.version!==2||typeof s.acceptance!=`string`||typeof s.message_id!=`string`||typeof s.run_id!=`string`||!K(s.run))throw Error(`Kai returned an unsupported command response.`);let c=ye(s.run,e.channelId);if(!c||c.runId!==s.run_id)throw Error(`Kai returned an unsupported command response.`);return{acceptance:s.acceptance,messageId:s.message_id,runs:[c]}}async function Rr(e,t){if(!k.test(t))throw Error(`Invalid artifact identity.`);let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/artifacts/${encodeURIComponent(t)}/content`);if(!n.ok){let e=await Y(n);throw Error(J(e,`Could not load this attachment.`))}return await n.blob()}async function zr(e,t){let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/runs/${encodeURIComponent(t)}`),r=await Y(n),i=K(r)?ye(r.run,e.channelId):null;if(!n.ok||r===null)throw Error(J(r,`Could not inspect this run.`));if(!K(r)||r.version!==1||!i||i.runId!==t)throw Error(`Kai returned an unsupported run response.`);return{...i,routingDecision:Ot(r.routing_decision)}}var Br=new Set([`tool_call`,`tool_result`,`truncated`]);function Vr(e){return!K(e)||typeof e.seq!=`number`||!Number.isSafeInteger(e.seq)||typeof e.kind!=`string`||!Br.has(e.kind)||typeof e.summary!=`string`||typeof e.detail!=`string`||typeof e.is_diff!=`boolean`||typeof e.is_error!=`boolean`||typeof e.created_at!=`string`||e.tool_name!==null&&typeof e.tool_name!=`string`||e.tool_use_id!==null&&typeof e.tool_use_id!=`string`?null:{createdAt:e.created_at,detail:e.detail,isDiff:e.is_diff,isError:e.is_error,kind:e.kind,seq:e.seq,summary:e.summary,toolName:e.tool_name,toolUseId:e.tool_use_id}}async function Hr(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/runs/${encodeURIComponent(t)}/trace?after_seq=${encodeURIComponent(String(n))}`),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not load this run's trace.`));if(!K(i)||i.version!==1||i.run_id!==t||!Array.isArray(i.entries)||!Array.isArray(i.collaboration_activity)||typeof i.has_more!=`boolean`)throw Error(`Kai returned an unsupported trace response.`);let a=[];for(let e of i.entries){let t=Vr(e);if(!t)throw Error(`Kai returned an unsupported trace response.`);a.push(t)}let o=[];for(let e of i.collaboration_activity){if(!K(e)||!Number.isSafeInteger(e.event_position)||e.event_position<1||![`operation`,`revocation`].includes(String(e.kind))||e.operation!==null&&(typeof e.operation!=`string`||!Oe.has(e.operation))||typeof e.outcome!=`string`||e.detail!==null&&typeof e.detail!=`string`||typeof e.occurred_at!=`string`)throw Error(`Kai returned an unsupported trace response.`);o.push({detail:e.detail,eventPosition:e.event_position,kind:e.kind,occurredAt:e.occurred_at,operation:e.operation,outcome:e.outcome})}return{collaborationActivity:o,entries:a,hasMore:i.has_more}}function Ur(e){if(!K(e)||typeof e.kind!=`string`||typeof e.owner_kind!=`string`||e.owner_id!==null&&typeof e.owner_id!=`string`||typeof e.scope!=`string`||typeof e.trust_class!=`string`||typeof e.authority_class!=`string`||typeof e.refresh_class!=`string`||typeof e.delivery_role!=`string`||typeof e.state!=`string`||typeof e.reason!=`string`||e.revision!==null&&typeof e.revision!=`string`||e.history_boundary!==null&&!Number.isSafeInteger(e.history_boundary)||typeof e.delivery_shape!=`string`||!Number.isSafeInteger(e.rendered_bytes)||e.budget_bytes!==null&&!Number.isSafeInteger(e.budget_bytes)||!K(e.inspection))return null;let t=e.inspection;if(typeof t.title!=`string`||typeof t.description!=`string`||typeof t.source_reference!=`string`||t.preview!==null&&typeof t.preview!=`string`||![`exact`,`redacted`,`unavailable`].includes(String(t.preview_state))||t.preview_reason!==null&&typeof t.preview_reason!=`string`||typeof t.editable!=`boolean`||t.edit_target!==null&&![`principal_policy`,`personal_preferences`,`agent_definition`,`workspace_policy`].includes(String(t.edit_target))||t.edit_target_id!==void 0&&t.edit_target_id!==null&&typeof t.edit_target_id!=`string`||t.current_revision!==null&&typeof t.current_revision!=`string`||![`current`,`changed`,`not_checked`].includes(String(t.freshness))||t.change_effect!==null&&![`next_turn`,`provider_session_refresh`].includes(String(t.change_effect)))return null;let n=e.native_instruction_sources??[];if(!Array.isArray(n))return null;let r=n.map(e=>!K(e)||typeof e.scope!=`string`||typeof e.filename!=`string`||typeof e.path_sha256!=`string`||e.content_sha256!==null&&typeof e.content_sha256!=`string`?null:{contentSha256:e.content_sha256,filename:e.filename,pathSha256:e.path_sha256,scope:e.scope});if(r.some(e=>e===null))return null;let i=e.authorization_operations??null;return i!==null&&(!Array.isArray(i)||i.some(e=>typeof e!=`string`))?null:{authorityClass:e.authority_class,authorizationOperations:i,budgetBytes:e.budget_bytes,deliveryRole:e.delivery_role,deliveryShape:e.delivery_shape,historyBoundary:e.history_boundary,inspection:{changeEffect:t.change_effect,currentRevision:t.current_revision,description:t.description,editable:t.editable,editTarget:t.edit_target,editTargetId:t.edit_target_id??null,freshness:t.freshness,preview:t.preview,previewReason:t.preview_reason,previewState:t.preview_state,sourceReference:t.source_reference,title:t.title},kind:e.kind,nativeInstructionSources:r,ownerId:e.owner_id,ownerKind:e.owner_kind,reason:e.reason,refreshClass:e.refresh_class,renderedBytes:e.rendered_bytes,revision:e.revision,scope:e.scope,state:e.state,trustClass:e.trust_class}}async function Wr(e,t){let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/runs/${encodeURIComponent(t)}/context-manifests`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load this run's context stack.`));if(!K(r)||r.version!==1||r.channel_id!==e.channelId||r.run_id!==t||!Array.isArray(r.manifests))throw Error(`Kai returned an unsupported context stack.`);let i=r.manifests.map(n=>{if(!K(n)||typeof n.attempt_id!=`string`||n.run_id!==t||n.channel_id!==e.channelId||typeof n.agent_id!=`string`||typeof n.runtime_profile_id!=`string`||typeof n.backend!=`string`||n.provider!==null&&typeof n.provider!=`string`||typeof n.model!=`string`||typeof n.workspace_kind!=`string`||n.workspace_digest!==null&&typeof n.workspace_digest!=`string`||n.provider_session_revision!==null&&typeof n.provider_session_revision!=`string`||typeof n.manifest_sha256!=`string`||typeof n.created_at!=`string`||!Array.isArray(n.sources))return null;let r=n.sources.map(Ur);return r.some(e=>e===null)?null:{agentId:n.agent_id,attemptId:n.attempt_id,backend:n.backend,channelId:n.channel_id,createdAt:n.created_at,manifestSha256:n.manifest_sha256,model:n.model,provider:n.provider,providerSessionRevision:n.provider_session_revision,runId:t,runtimeProfileId:n.runtime_profile_id,sources:r,workspaceDigest:n.workspace_digest,workspaceKind:n.workspace_kind}});if(i.some(e=>e===null))throw Error(`Kai returned an unsupported context stack.`);return{channelId:e.channelId,manifests:i,runId:t}}async function Gr(e,t){let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/runs/${encodeURIComponent(t)}/cancel`,{method:`POST`}),r=await Y(n),i=K(r)?ye(r.run,e.channelId):null;if(!n.ok)throw Error(J(r,`Could not stop this run.`));if(!K(r)||r.version!==1||!i||i.runId!==t)throw Error(`Kai returned an unsupported cancellation response.`);return i}function Kr(e){if(!K(e))return null;let{channel_name:t,created_at:n,created_event_position:r,kind:i,last_event_position:a,notification_id:o,read:s,read_at:c,source_author_display_name:l,source_author_avatar:u,source_author_principal_id:d,source_channel_id:f,source_message_id:p,source_thread_root_id:m,state_version:h}=e;return t!==null&&typeof t!=`string`||typeof n!=`string`||!Number.isSafeInteger(r)||i!==`mention`&&i!==`reply`&&i!==`message`||!Number.isSafeInteger(a)||typeof o!=`string`||!j.test(o)||typeof s!=`boolean`||c!==null&&typeof c!=`string`||typeof l!=`string`||typeof d!=`string`||!E.test(d)||typeof f!=`string`||!b.test(f)||typeof p!=`string`||!A.test(p)||m!==null&&(typeof m!=`string`||!A.test(m))||!Number.isSafeInteger(h)||h<0?null:{channelName:t,createdAt:n,createdEventPosition:r,kind:i,lastEventPosition:a,notificationId:o,read:s,readAt:c,sourceAuthorDisplayName:l,sourceAuthorAvatar:de(u,d),sourceAuthorPrincipalId:d,sourceChannelId:f,sourceMessageId:p,sourceThreadRootId:m,stateVersion:h}}function qr(e){if(!K(e)||!Number.isSafeInteger(e.total)||!Number.isSafeInteger(e.unread)||!Number.isSafeInteger(e.read)||e.total<0||e.unread<0||e.read<0||e.total!==e.unread+e.read||!K(e.unread_by_channel))return null;let t={},n=0;for(let[r,i]of Object.entries(e.unread_by_channel)){if(!b.test(r)||!Number.isSafeInteger(i)||i<1)return null;t[r]=i,n+=i}return n===e.unread?{read:e.read,total:e.total,unread:e.unread,unreadByChannel:t}:null}function Jr(e){if(!K(e)||e.version!==1||!Array.isArray(e.notifications)||!Number.isSafeInteger(e.through_position)||e.through_position<0||e.next_cursor!==null&&typeof e.next_cursor!=`string`)throw Error(`Kai returned an unsupported Mentions inbox.`);let t=qr(e.counts),n=e.notifications.map(Kr);if(!t||n.some(e=>e===null))throw Error(`Kai returned an unsupported Mentions inbox.`);return{counts:t,nextCursor:e.next_cursor,notifications:n,throughPosition:e.through_position}}async function Yr(e,t={},n){let r=new URLSearchParams;t.cursor&&r.set(`cursor`,t.cursor),t.kind&&r.set(`kind`,t.kind),r.set(`limit`,String(t.limit??50)),t.unreadOnly&&r.set(`unread`,`1`);let i=await X({channelId:``,token:e},`/v1/client/notifications?${r}`,{signal:n}),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not load mentions.`));return Jr(a)}async function Xr(e,t={},n){let r=new URLSearchParams;t.kind&&r.set(`kind`,t.kind);let i=r.size>0?`?${r}`:``,a=await X({channelId:``,token:e},`/v1/client/notifications/counts${i}`,{signal:n}),o=await Y(a);if(!a.ok||!K(o)||o.version!==1)throw Error(J(o,`Could not load mention counts.`));let s=qr(o);if(!s)throw Error(`Kai returned unsupported mention counts.`);return s}async function Zr(e,t,n,r,i){if(!j.test(t))throw Error(`Invalid notification identity.`);let a=await X({channelId:``,token:e},`/v1/client/notifications/${encodeURIComponent(t)}/${r?`read`:`unread`}`,{body:JSON.stringify({client_operation_id:i,expected_state_version:n}),headers:{"Content-Type":`application/json`},method:`POST`}),o=await Y(a),s=K(o)?Kr(o.notification):null;if(!a.ok||!K(o)||o.version!==1||!s||typeof o.changed!=`boolean`||typeof o.replayed!=`boolean`)throw Error(J(o,`Could not update this mention.`));return{changed:o.changed,notification:s,replayed:o.replayed}}function Qr(e,t,n,r){return Zr(e,t,n,!0,r)}function $r(e,t,n,r){return Zr(e,t,n,!1,r)}async function ei(e,t,n){let r=await X({channelId:``,token:e},`/v1/client/notifications/read`,{body:JSON.stringify({client_operation_id:n,notifications:t.map(e=>({expected_state_version:e.expectedStateVersion,notification_id:e.notificationId}))}),headers:{"Content-Type":`application/json`},method:`POST`}),i=await Y(r);if(!r.ok||!K(i)||i.version!==1||!Array.isArray(i.notifications))throw Error(J(i,`Could not mark mentions read.`));return i.notifications.map(e=>{if(!K(e))throw Error(`Kai returned an unsupported mention mutation.`);let t=Kr(e.notification);if(!t||typeof e.changed!=`boolean`||typeof e.replayed!=`boolean`)throw Error(`Kai returned an unsupported mention mutation.`);return{changed:e.changed,notification:t,replayed:e.replayed}})}function ti(e){if(!K(e))return null;let{archived:t,channel_id:n,channel_kind:r,channel_name:i,first_unread_event_position:a,first_unread_message_id:o,last_event_position:s,membership_baseline_event_position:c,read_through_event_position:l,read_through_message_id:u,state_version:d,unread_count:f,unread_count_capped:p,unread_reply_count:m,unread_reply_count_capped:h,unread_thread_count:g,first_unread_thread_root_id:_,first_unread_thread_reply_id:v,first_unread_thread_event_position:y}=e;return typeof t!=`boolean`||typeof n!=`string`||!b.test(n)||r!==`direct`&&r!==`group`&&r!==`notification`||i!==null&&typeof i!=`string`||a!==null&&(!Number.isSafeInteger(a)||a<0)||o!==null&&(typeof o!=`string`||!A.test(o))||!Number.isSafeInteger(s)||s<0||!Number.isSafeInteger(c)||c<0||!Number.isSafeInteger(l)||l<0||u!==null&&(typeof u!=`string`||!A.test(u))||!Number.isSafeInteger(d)||d<0||!Number.isSafeInteger(f)||f<0||typeof p!=`boolean`||!Number.isSafeInteger(m)||m<0||typeof h!=`boolean`||!Number.isSafeInteger(g)||g<0||_!==null&&(typeof _!=`string`||!A.test(_))||v!==null&&(typeof v!=`string`||!A.test(v))||y!==null&&(!Number.isSafeInteger(y)||y<0)||_===null!=(v===null)||v===null!=(y===null)||m===0!=(v===null)||o===null!=(a===null)||f===0!=(o===null)?null:{archived:t,channelId:n,channelKind:r,channelName:i,firstUnreadEventPosition:a,firstUnreadMessageId:o,lastEventPosition:s,membershipBaselineEventPosition:c,readThroughEventPosition:l,readThroughMessageId:u,stateVersion:d,unreadCount:f,unreadCountCapped:p,unreadReplyCount:m,unreadReplyCountCapped:h,unreadThreadCount:g,firstUnreadThreadRootId:_,firstUnreadThreadReplyId:v,firstUnreadThreadEventPosition:y}}function ni(e){if(!K(e))return null;let{channel_id:t,thread_root_id:n,followed:r,follow_baseline_event_position:i,read_through_event_position:a,read_through_message_id:o,state_version:s,last_event_position:c,unread_count:l,unread_count_capped:u,first_unread_message_id:d,first_unread_event_position:f}=e;return typeof t!=`string`||!b.test(t)||typeof n!=`string`||!A.test(n)||typeof r!=`boolean`||!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(a)||a<0||o!==null&&(typeof o!=`string`||!A.test(o))||!Number.isSafeInteger(s)||s<0||!Number.isSafeInteger(c)||c<0||!Number.isSafeInteger(l)||l<0||typeof u!=`boolean`||d!==null&&(typeof d!=`string`||!A.test(d))||f!==null&&(!Number.isSafeInteger(f)||f<0)||d===null!=(f===null)||l===0!=(d===null)?null:{channelId:t,threadRootId:n,followed:r,followBaselineEventPosition:i,readThroughEventPosition:a,readThroughMessageId:o,stateVersion:s,lastEventPosition:c,unreadCount:l,unreadCountCapped:u,firstUnreadMessageId:d,firstUnreadEventPosition:f}}function ri(e){if(!K(e))return null;let t=ni(e.state),{channel_name:n,channel_archived:r,root_author_display_name:i,root_excerpt:a,root_created_at:o,latest_reply_message_id:s,latest_reply_author_display_name:c,latest_reply_excerpt:l,latest_reply_created_at:u}=e;return!t||!t.followed||n!==null&&typeof n!=`string`||typeof r!=`boolean`||typeof i!=`string`||typeof a!=`string`||a.length>280||typeof o!=`string`||s!==null&&(typeof s!=`string`||!A.test(s))||c!==null&&typeof c!=`string`||l!==null&&(typeof l!=`string`||l.length>280)||u!==null&&typeof u!=`string`||s===null!=(c===null)||s===null!=(l===null)||s===null!=(u===null)?null:{state:t,channelName:n,channelArchived:r,rootAuthorDisplayName:i,rootExcerpt:a,rootCreatedAt:o,latestReplyMessageId:s,latestReplyAuthorDisplayName:c,latestReplyExcerpt:l,latestReplyCreatedAt:u}}async function ii(e,t){let n=await X({channelId:``,token:e},`/v1/client/followed-threads`,{signal:t}),r=await Y(n),i=K(r)&&Array.isArray(r.threads)?r.threads.map(ri):[];if(!n.ok||!K(r)||r.version!==1||!Array.isArray(r.threads)||i.some(e=>e===null)||!Number.isSafeInteger(r.through_position)||r.through_position<0)throw Error(J(r,`Could not load followed threads.`));return{threads:i,throughPosition:r.through_position}}async function ai(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/threads/${encodeURIComponent(t)}/unread`,{signal:n}),i=await Y(r);if(r.status===404)throw new V(`This thread is no longer accessible.`);let a=K(i)?ni(i.state):null;if(!r.ok||!K(i)||i.version!==1||!a)throw Error(J(i,`Could not load thread unread state.`));return a}async function oi(e,t,n,r,i,a){let o={client_operation_id:i,expected_state_version:r};a!==void 0&&(o.message_id=a);let s=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/threads/${encodeURIComponent(t)}/${n}`,{body:JSON.stringify(o),headers:{"Content-Type":`application/json`},method:`POST`}),c=await Y(s);if(s.status===404)throw new V(`This thread is no longer accessible.`);if(s.status===409)throw new te(J(c,`Thread state changed in another tab.`));let l=K(c)?ni(c.state):null;if(!s.ok||!K(c)||c.version!==1||!l||typeof c.replayed!=`boolean`)throw Error(J(c,`Could not update thread unread state.`));return{replayed:c.replayed,state:l}}function si(e,t,n,r,i){return oi(e,t,n?`follow`:`unfollow`,r,i)}function ci(e,t,n,r,i){return oi(e,t,`read-position`,r,i,n)}async function li(e,t){let n=await X({channelId:``,token:e},`/v1/client/unread`,{signal:t}),r=await Y(n);if(!n.ok||!K(r)||r.version!==1||!Array.isArray(r.channels)||!Number.isSafeInteger(r.total_unread)||r.total_unread<0||typeof r.total_unread_capped!=`boolean`||!Number.isSafeInteger(r.through_position)||r.through_position<0)throw Error(J(r,`Could not load unread messages.`));let i=r.channels.map(ti);if(i.some(e=>e===null))throw Error(`Kai returned unsupported unread state.`);return{channels:i,throughPosition:r.through_position,totalUnread:r.total_unread,totalUnreadCapped:r.total_unread_capped}}async function ui(e,t,n,r){if(!A.test(t))throw Error(`Invalid message identity.`);let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/read-position`,{body:JSON.stringify({client_operation_id:r,expected_state_version:n,message_id:t}),headers:{"Content-Type":`application/json`},method:`POST`}),a=await Y(i);if(i.status===404)throw new V(`This session can no longer access that Workshop channel.`);if(i.status===409)throw new H(J(a,`Unread state changed in another tab.`));let o=K(a)?ti(a.state):null;if(!i.ok||!K(a)||a.version!==1||!o||typeof a.replayed!=`boolean`)throw Error(J(a,`Could not update unread messages.`));return{replayed:a.replayed,state:o}}async function di(e,t,n){if(!A.test(t))throw Error(`Invalid message identity.`);let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/messages/${encodeURIComponent(t)}`,{signal:n}),i=await Y(r),a=K(i)?ge(i.message,e.channelId):null;if(!r.ok||!K(i)||i.version!==1||!a)throw Error(J(i,`Could not open the source message.`));return a}function fi(e,t){if(!K(e)||e.version!==1||e.channel_id!==t||!Array.isArray(e.messages)||!Number.isSafeInteger(e.through_position))throw Error(`Kai returned an unsupported timeline response.`);let n=[];for(let r of e.messages){let e=ge(r,t);if(!e)throw Error(`Kai returned an unsupported timeline message.`);n.push(e)}return{messages:n,nextCursor:typeof e.next_cursor==`string`?e.next_cursor:null,throughPosition:e.through_position,previousCursor:typeof e.previous_cursor==`string`?e.previous_cursor:null}}async function pi(e,t,n=null){let r=new URLSearchParams({limit:`100`});if(n!==null){if(!A.test(n))throw Error(`Invalid unread message identity.`);r.set(`start_message_id`,n)}else r.set(`tail`,`1`);let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/timeline?${r}`,{signal:t}),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not load this channel.`));return fi(a,e.channelId)}async function mi(e,t,n,r){let i=new URLSearchParams({cursor:t,limit:`100`}),a=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/timeline?${i}`,{signal:r}),o=await Y(a);if(!a.ok)throw Error(J(o,`Could not load earlier messages.`));let s=fi(o,e.channelId);if(s.throughPosition!==n)throw Error(`The timeline snapshot changed while it was loading.`);return s}async function hi(e,t,n=null,r){if(!A.test(t))throw Error(`Invalid thread identity.`);let i=new URLSearchParams({limit:`100`});n&&i.set(`cursor`,n);let a=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/threads/${encodeURIComponent(t)}?${i}`,{signal:r}),o=await Y(a);if(!a.ok||!K(o)||o.version!==1||o.channel_id!==e.channelId||o.thread_root_id!==t||!Array.isArray(o.messages)||!Number.isSafeInteger(o.through_position))throw Error(J(o,`Could not load this thread.`));let s=ge(o.root,e.channelId),c=o.messages.map(t=>ge(t,e.channelId));if(!s||c.some(e=>e===null))throw Error(`Kai returned an unsupported thread response.`);return{root:s,messages:c,nextCursor:typeof o.next_cursor==`string`?o.next_cursor:null,throughPosition:o.through_position}}var gi=class{buffer=``;push(e){this.buffer+=e;let t=[],n=this.buffer.indexOf(` +`).replace(kd,``)}function jd(e,t){return t=Ad(t),Ad(e)===t}function Md(e,t,n,r,a,o){switch(n){case`children`:typeof r==`string`?t===`body`||t===`textarea`&&r===``||Mt(e,r):(typeof r==`number`||typeof r==`bigint`)&&t!==`body`&&Mt(e,``+r);break;case`className`:gt(e,`class`,r);break;case`tabIndex`:gt(e,`tabindex`,r);break;case`dir`:case`role`:case`viewBox`:case`width`:case`height`:gt(e,n,r);break;case`style`:Ft(e,r,o);break;case`data`:if(t!==`object`){gt(e,`data`,r);break}case`src`:case`href`:if(r===``&&(t!==`a`||n!==`href`)){e.removeAttribute(n);break}if(r==null||typeof r==`function`||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=zt(``+r),e.setAttribute(n,r);break;case`action`:case`formAction`:if(typeof r==`function`){e.setAttribute(n,`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}if(typeof o==`function`&&(n===`formAction`?(t!==`input`&&Md(e,t,`name`,a.name,a,null),Md(e,t,`formEncType`,a.formEncType,a,null),Md(e,t,`formMethod`,a.formMethod,a,null),Md(e,t,`formTarget`,a.formTarget,a,null)):(Md(e,t,`encType`,a.encType,a,null),Md(e,t,`method`,a.method,a,null),Md(e,t,`target`,a.target,a,null))),r==null||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=zt(``+r),e.setAttribute(n,r);break;case`onClick`:r!=null&&(e.onclick=Bt);break;case`onScroll`:r!=null&&vd(`scroll`,e);break;case`onScrollEnd`:r!=null&&vd(`scrollend`,e);break;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(i(61));if(n=r.__html,n!=null){if(a.children!=null)throw Error(i(60));e.innerHTML=n}}break;case`multiple`:e.multiple=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`muted`:e.muted=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`defaultValue`:case`defaultChecked`:case`innerHTML`:case`ref`:break;case`autoFocus`:break;case`xlinkHref`:if(r==null||typeof r==`function`||typeof r==`boolean`||typeof r==`symbol`){e.removeAttribute(`xlink:href`);break}n=zt(``+r),e.setAttributeNS(`http://www.w3.org/1999/xlink`,`xlink:href`,n);break;case`contentEditable`:case`spellCheck`:case`draggable`:case`value`:case`autoReverse`:case`externalResourcesRequired`:case`focusable`:case`preserveAlpha`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,``+r):e.removeAttribute(n);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`:r&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,``):e.removeAttribute(n);break;case`capture`:case`download`:!0===r?e.setAttribute(n,``):!1!==r&&r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,r):e.removeAttribute(n);break;case`cols`:case`rows`:case`size`:case`span`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`&&!isNaN(r)&&1<=r?e.setAttribute(n,r):e.removeAttribute(n);break;case`rowSpan`:case`start`:r==null||typeof r==`function`||typeof r==`symbol`||isNaN(r)?e.removeAttribute(n):e.setAttribute(n,r);break;case`popover`:vd(`beforetoggle`,e),vd(`toggle`,e),ht(e,`popover`,r);break;case`xlinkActuate`:_t(e,`http://www.w3.org/1999/xlink`,`xlink:actuate`,r);break;case`xlinkArcrole`:_t(e,`http://www.w3.org/1999/xlink`,`xlink:arcrole`,r);break;case`xlinkRole`:_t(e,`http://www.w3.org/1999/xlink`,`xlink:role`,r);break;case`xlinkShow`:_t(e,`http://www.w3.org/1999/xlink`,`xlink:show`,r);break;case`xlinkTitle`:_t(e,`http://www.w3.org/1999/xlink`,`xlink:title`,r);break;case`xlinkType`:_t(e,`http://www.w3.org/1999/xlink`,`xlink:type`,r);break;case`xmlBase`:_t(e,`http://www.w3.org/XML/1998/namespace`,`xml:base`,r);break;case`xmlLang`:_t(e,`http://www.w3.org/XML/1998/namespace`,`xml:lang`,r);break;case`xmlSpace`:_t(e,`http://www.w3.org/XML/1998/namespace`,`xml:space`,r);break;case`is`:ht(e,`is`,r);break;case`innerText`:case`textContent`:break;default:(!(2s)break;var u=c.transferSize,d=c.initiatorType;u&&Id(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function xf(e,t,n){var r=bf;if(r&&typeof t==`string`&&t){var i=Tt(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),hf.has(i)||(hf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Pd(t,`link`,e),ot(t),r.head.appendChild(t)))}}function Sf(e){_f.D(e),xf(`dns-prefetch`,e,null)}function Cf(e,t){_f.C(e,t),xf(`preconnect`,e,t)}function wf(e,t,n){_f.L(e,t,n);var r=bf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Tt(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Tt(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Tt(n.imageSizes)+`"]`)):i+=`[href="`+Tt(e)+`"]`;var a=i;switch(t){case`style`:a=Af(e);break;case`script`:a=Pf(e)}mf.has(a)||(e=m({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),mf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(jf(a))||t===`script`&&r.querySelector(Ff(a))||(t=r.createElement(`link`),Pd(t,`link`,e),ot(t),r.head.appendChild(t)))}}function Tf(e,t){_f.m(e,t);var n=bf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Tt(r)+`"][href="`+Tt(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Pf(e)}if(!mf.has(a)&&(e=m({rel:`modulepreload`,href:e},t),mf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(Ff(a)))return}r=n.createElement(`link`),Pd(r,`link`,e),ot(r),n.head.appendChild(r)}}}function Ef(e,t,n){_f.S(e,t,n);var r=bf;if(r&&e){var i=at(r).hoistableStyles,a=Af(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(jf(a)))s.loading=5;else{e=m({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=mf.get(a))&&Rf(e,n);var c=o=r.createElement(`link`);ot(c),Pd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Lf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Df(e,t){_f.X(e,t);var n=bf;if(n&&e){var r=at(n).hoistableScripts,i=Pf(e),a=r.get(i);a||(a=n.querySelector(Ff(i)),a||(e=m({src:e,async:!0},t),(t=mf.get(i))&&zf(e,t),a=n.createElement(`script`),ot(a),Pd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Of(e,t){_f.M(e,t);var n=bf;if(n&&e){var r=at(n).hoistableScripts,i=Pf(e),a=r.get(i);a||(a=n.querySelector(Ff(i)),a||(e=m({src:e,async:!0,type:`module`},t),(t=mf.get(i))&&zf(e,t),a=n.createElement(`script`),ot(a),Pd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function kf(e,t,n,r){var a=(a=ne.current)?gf(a):null;if(!a)throw Error(i(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=Af(n.href),n=at(a).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Af(n.href);var o=at(a).hoistableStyles,s=o.get(e);if(s||(a=a.ownerDocument||a,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=a.querySelector(jf(e)))&&!o._p&&(s.instance=o,s.state.loading=5),mf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},mf.set(e,n),o||Nf(a,e,n,s.state))),t&&r===null)throw Error(i(528,``));return s}if(t&&r!==null)throw Error(i(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Pf(n),n=at(a).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(i(444,e))}}function Af(e){return`href="`+Tt(e)+`"`}function jf(e){return`link[rel="stylesheet"][`+e+`]`}function Mf(e){return m({},e,{"data-precedence":e.precedence,precedence:null})}function Nf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),Pd(t,`link`,n),ot(t),e.head.appendChild(t))}function Pf(e){return`[src="`+Tt(e)+`"]`}function Ff(e){return`script[async]`+e}function If(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Tt(n.href)+`"]`);if(r)return t.instance=r,ot(r),r;var a=m({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),ot(r),Pd(r,`style`,a),Lf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Af(n.href);var o=e.querySelector(jf(a));if(o)return t.state.loading|=4,t.instance=o,ot(o),o;r=Mf(n),(a=mf.get(a))&&Rf(r,a),o=(e.ownerDocument||e).createElement(`link`),ot(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Pd(o,`link`,r),t.state.loading|=4,Lf(o,n.precedence,e),t.instance=o;case`script`:return o=Pf(n.src),(a=e.querySelector(Ff(o)))?(t.instance=a,ot(a),a):(r=n,(a=mf.get(o))&&(r=m({},n),zf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),ot(a),Pd(a,`link`,r),e.head.appendChild(a),t.instance=a);case`void`:return null;default:throw Error(i(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Lf(r,n.precedence,e));return t.instance}function Lf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function Uf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Wf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Gf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Af(r.href),a=t.querySelector(jf(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Jf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,ot(a);return}a=t.ownerDocument||t,r=Mf(r),(i=mf.get(i))&&Rf(r,i),a=a.createElement(`link`),ot(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Pd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=Jf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Kf=0;function qf(e,t){return e.stylesheets&&e.count===0&&Xf(e,e.stylesheets),0Kf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Jf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Xf(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Yf=null;function Xf(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Yf=new Map,t.forEach(Zf,e),Yf=null,Jf.call(e))}function Zf(e,t){if(!(t.state.loading&4)){var n=Yf.get(e);if(n)var r=n.get(null);else{n=new Map,Yf.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=g()})),v=d(),y=_(),b=/^chn_[0-9a-f]{32}$/,x=/^agt_[0-9a-f]{32}$/,S=/^adf_[0-9a-f]{32}$/,C=/^apv_[0-9a-f]{32}$/,w=/^adr_[0-9a-f]{32}$/,T=/^aen_[0-9a-f]{32}$/,E=/^prn_[0-9a-f]{32}$/,D=/^rtp_[0-9a-f]{32}$/,O=/^wsp_[0-9a-f]{32}$/,k=/^art_[0-9a-f]{32}$/,A=/^msg_[0-9a-f]{32}$/,j=/^ntf_[0-9a-f]{32}$/,M=/^[a-z][a-z0-9_]{0,31}$/,N=`atom-one-dark`,P=[{colorScheme:`dark`,displayName:`Atom One Dark`,themeId:N},{colorScheme:`light`,displayName:`Atom One Light`,themeId:`atom-one-light`},{colorScheme:`dark`,displayName:`Dracula`,themeId:`dracula`},{colorScheme:`dark`,displayName:`Nord`,themeId:`nord`},{colorScheme:`dark`,displayName:`Solarized Dark`,themeId:`solarized-dark`},{colorScheme:`light`,displayName:`Solarized Light`,themeId:`solarized-light`},{colorScheme:`dark`,displayName:`Catppuccin Mocha`,themeId:`catppuccin-mocha`},{colorScheme:`light`,displayName:`Catppuccin Latte`,themeId:`catppuccin-latte`},{colorScheme:`light`,displayName:`GitHub Light Default`,themeId:`github-light-default`},{colorScheme:`dark`,displayName:`GitHub Dark Default`,themeId:`github-dark-default`},{colorScheme:`dark`,displayName:`GitHub Dark Dimmed`,themeId:`github-dark-dimmed`}],F=`kai.workshop.theme-hint.v1`,I=new Map(P.map(e=>[e.themeId,e]));function L(e){return typeof e==`string`&&I.has(e)}function R(e,t=!0){let n=L(e)?e:N,r=I.get(n);if(!r)throw Error(`The default Workshop theme is unavailable.`);if(document.documentElement.dataset.workshopTheme=n,document.documentElement.style.colorScheme=r.colorScheme,t)try{sessionStorage.setItem(F,n)}catch{}return n}function ee(){try{return R(sessionStorage.getItem(F),!1)}catch{return R(N,!1)}}function z(){try{sessionStorage.removeItem(F)}catch{}R(N,!1)}var B=class extends Error{},V=class extends Error{},H=class extends Error{},te=class extends Error{},U=class extends Error{},ne=class extends Error{currentRevision;constructor(e,t){super(e),this.currentRevision=t}},re=class extends Error{currentRevision;constructor(e,t){super(e),this.currentRevision=t}},W=class extends Error{},ie=class extends Error{},ae=class extends Error{currentRevision;constructor(e,t){super(e),this.currentRevision=t}},oe=new Set([`thumbs_up`,`thumbs_down`,`heart`,`laugh`,`celebrate`,`eyes`,`check`,`thinking`,`surprised`,`sad`,`fire`,`question`]);function se(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!K(n))return null;let{count:e,reacted_by_viewer:r,reaction:i}=n;if(typeof i!=`string`||!oe.has(i)||!Number.isSafeInteger(e)||e<1||typeof r!=`boolean`)return null;t.push({count:e,reactedByViewer:r,reaction:i})}return t}var ce=new Set([`public`,`principal`,`conversation`,`principal_agent`,`agent_owner`,`channel_member`,`channel_owner`,`administrator`]),le=new Set([`native_surface`,`action_palette`,`administrator_only`,`presentation_alias`,`compatibility_only`]),ue=new Set([`none`,`context_dependent`,`required`]);function G(e){if(!K(e))return null;let{available:t,confirmation:n,description:r,disposition:i,input_shape:a,label:o,mutates_state:s,operation_id:c,palette_entry:l,scope:u,surface:d,unavailable_reason:f}=e;return t!==!0||typeof n!=`string`||!ue.has(n)||typeof r!=`string`||typeof i!=`string`||!le.has(i)||typeof a!=`string`||typeof o!=`string`||typeof s!=`boolean`||typeof c!=`string`||!/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)+$/.test(c)||typeof l!=`boolean`||typeof u!=`string`||!ce.has(u)||d!==null&&typeof d!=`string`||f!==null?null:{available:t,confirmation:n,description:r,disposition:i,inputShape:a,label:o,mutatesState:s,operationId:c,paletteEntry:l,scope:u,surface:d,unavailableReason:f}}function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q(){return{active:!1,stateVersion:0,url:null}}function de(e,t){if(!K(e))return q();let{active:n,state_version:r,url:i}=e;return typeof n!=`boolean`||!Number.isSafeInteger(r)||r<0||n&&r<1||(n?i!==`/v1/principals/${t}/avatar/${r}`:i!==null)?q():{active:n,stateVersion:r,url:i}}function J(e,t){if(!K(e)||!K(e.error))return t;let n=e.error.message;return typeof n==`string`&&n.length<=200?n:t}async function Y(e){try{return await e.json()}catch{return null}}var fe=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,pe=null;function me(){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function he(){return pe!==null&&fe.test(pe)||(pe=me()),pe}async function X(e,t,n={}){let r=new Headers(n.headers);r.set(`Authorization`,`Bearer ${e.token}`);let i=await fetch(t,{...n,cache:`no-store`,headers:r});if(i.status===401)throw new B(`This Workshop session expired or was revoked.`);if(i.status===403)throw new V(`This session cannot access that Workshop channel.`);return i}function ge(e,t){if(!K(e))return null;let{author_display_name:n,author_avatar:r,author_kind:i,author_principal_id:a,body:o,channel_id:s,created_at:c,event_position:l,latest_reply_at:u,message_id:d,reply_count:f,reply_participant_count:p,reply_participants:m,reply_to_message_id:h,thread_root_id:g,mentions:_,reactions:v,artifacts:y,standing_contribution:b,source_run_id:x}=e,S=b??!1,C=x??null,w=y??[],T=v??[];if(typeof n!=`string`||typeof i!=`string`||typeof a!=`string`||!E.test(a)||typeof o!=`string`||s!==t||typeof c!=`string`||!Number.isSafeInteger(l)||typeof d!=`string`||!A.test(d)||!Number.isSafeInteger(f)||f<0||!Number.isSafeInteger(p)||p<0||!Array.isArray(m)||m.length>3||pj)return null;O.push({kind:t,length:n,principalId:r,start:i}),M=i+n}let N=se(T);if(N===null)return null;let P=[];for(let e of m){if(!K(e))return null;let{avatar:t,display_name:n,kind:r,principal_id:i}=e;if(typeof i!=`string`||!E.test(i)||r!==`human`&&r!==`agent`||typeof n!=`string`||!n.trim())return null;P.push({avatar:r===`human`?de(t,i):null,displayName:n,kind:r,principalId:i})}return{artifacts:D,authorAvatar:i===`human`?de(r,a):null,authorDisplayName:n,authorKind:i,authorPrincipalId:a,body:o,channelId:t,createdAt:c,eventPosition:l,mentions:O,messageId:d,reactions:N,replyCount:f,replyParticipantCount:p,replyParticipants:P,replyToMessageId:h,latestReplyAt:u,threadRootId:g,standingContribution:S,sourceRunId:C}}var _e=new Set([`accepted`,`started`,`completed`,`failed`,`cancelled`]),ve=new Set([`run.accepted`,`run.started`,`run.cancellation_requested`,`run.completed`,`run.failed`,`run.cancelled`]);function ye(e,t){if(!K(e))return null;let{accepted_at:n,agent_id:r,cancellation_requested_at:i,channel_id:a,inbound_message_id:o,kind:s,result_message_id:c,run_id:l,started_at:u,status:d,terminal_at:f,terminal_code:p}=e;return typeof n!=`string`||typeof r!=`string`||!x.test(r)||i!==null&&typeof i!=`string`||a!==t||typeof o!=`string`||!A.test(o)||s!==`respond`&&s!==`observe`||c!==null&&typeof c!=`string`||typeof l!=`string`||u!==null&&typeof u!=`string`||typeof d!=`string`||!_e.has(d)||f!==null&&typeof f!=`string`||p!==null&&typeof p!=`string`?null:{acceptedAt:n,agentId:r,cancellationRequestedAt:i,channelId:t,inboundMessageId:o,kind:s,resultMessageId:c,runId:l,startedAt:u,status:d,terminalAt:f,terminalCode:p}}async function be(e,t){let n=await fetch(`/v1/client/enrollment/redeem`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({device_display_name:t,enrollment_token:e}),cache:`no-store`}),r=await Y(n);if(!n.ok||!K(r)||!K(r.session)||typeof r.session.token!=`string`||r.session.token.length===0)throw Error(J(r,`Enrollment failed.`));return r.session.token}async function xe(e){let t=await X({channelId:``,token:e},`/v1/client/navigation`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load Workshop navigation.`));if(!K(n)||n.version!==1||!K(n.principal)||typeof n.principal.principal_id!=`string`||!E.test(n.principal.principal_id)||typeof n.principal.display_name!=`string`||n.principal.handle!==null&&(typeof n.principal.handle!=`string`||!M.test(n.principal.handle))||!Array.isArray(n.workshops))throw Error(`Kai returned unsupported Workshop navigation.`);let r=n.workshops.map(e=>{if(!K(e)||typeof e.workshop_id!=`string`||!O.test(e.workshop_id)||typeof e.name!=`string`||typeof e.role!=`string`||!Array.isArray(e.channels))throw Error(`Kai returned unsupported Workshop navigation.`);return{channels:e.channels.map(e=>{if(!K(e)||typeof e.channel_id!=`string`||!b.test(e.channel_id)||e.name!==null&&typeof e.name!=`string`||![`direct`,`group`,`notification`].includes(String(e.kind))||typeof e.role!=`string`||e.archived_at!==void 0&&e.archived_at!==null&&typeof e.archived_at!=`string`||e.lifecycle_event_position!==void 0&&e.lifecycle_event_position!==null&&(typeof e.lifecycle_event_position!=`number`||!Number.isSafeInteger(e.lifecycle_event_position))||e.direct_message_archived_at!==void 0&&e.direct_message_archived_at!==null&&typeof e.direct_message_archived_at!=`string`||e.direct_message_archive_event_position!==void 0&&e.direct_message_archive_event_position!==null&&(typeof e.direct_message_archive_event_position!=`number`||!Number.isSafeInteger(e.direct_message_archive_event_position))||typeof e.can_submit_commands!=`boolean`||!Array.isArray(e.agents)||!Array.isArray(e.participants))throw Error(`Kai returned unsupported Workshop navigation.`);let t=e.agents.map(e=>{if(!K(e)||typeof e.agent_id!=`string`||!x.test(e.agent_id)||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.engaged!=`boolean`||typeof e.available!=`boolean`||![`draft`,`active`,`archived`].includes(String(e.lifecycle_state))||e.engaged_until!==null&&typeof e.engaged_until!=`string`||![`private`,`shared_channel`].includes(String(e.memory_scope))||e.runtime_profile_id!==null&&(typeof e.runtime_profile_id!=`string`||!D.test(e.runtime_profile_id))||e.sponsor_principal_id!==null&&(typeof e.sponsor_principal_id!=`string`||!E.test(e.sponsor_principal_id))||e.sponsor_display_name!==null&&typeof e.sponsor_display_name!=`string`||typeof e.name!=`string`||typeof e.handle!=`string`||!M.test(e.handle))throw Error(`Kai returned unsupported Workshop navigation.`);return{agentId:e.agent_id,available:e.available,engaged:e.engaged,engagedUntil:e.engaged_until,handle:e.handle,lifecycleState:e.lifecycle_state,memoryScope:e.memory_scope,name:e.name,principalId:e.principal_id,runtimeProfileId:e.runtime_profile_id,sponsorDisplayName:e.sponsor_display_name,sponsorPrincipalId:e.sponsor_principal_id}}),n=e.participants.map(e=>{if(!K(e)||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.kind!=`string`||typeof e.display_name!=`string`||e.handle!==null&&(typeof e.handle!=`string`||!M.test(e.handle)))throw Error(`Kai returned unsupported Workshop navigation.`);return{...e.kind===`human`?{avatar:de(e.avatar,e.principal_id)}:{},displayName:e.display_name,handle:e.handle,kind:e.kind,principalId:e.principal_id}});return{agents:t,...e.archived_at===void 0?{}:{archivedAt:e.archived_at},canSubmitCommands:e.can_submit_commands,channelId:e.channel_id,...e.direct_message_archive_event_position===void 0?{}:{directMessageArchiveEventPosition:e.direct_message_archive_event_position},...e.direct_message_archived_at===void 0?{}:{directMessageArchivedAt:e.direct_message_archived_at},kind:e.kind,...e.lifecycle_event_position===void 0?{}:{lifecycleEventPosition:e.lifecycle_event_position},name:e.name,participants:n,role:e.role}}),name:e.name,role:e.role,workshopId:e.workshop_id}});return{principal:{avatar:de(n.principal.avatar,n.principal.principal_id),displayName:n.principal.display_name,handle:n.principal.handle,principalId:n.principal.principal_id},workshops:r}}async function Se(e,t=null){let n=new URLSearchParams({channel_id:e.channelId});t!==null&&n.set(`agent_id`,t);let r=await X(e,`/v1/client/capabilities?${n.toString()}`),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not load available actions.`));if(!K(i)||i.version!==1||!K(i.context)||typeof i.context.administrator!=`boolean`||typeof i.context.agent!=`boolean`||typeof i.context.agent_owner!=`boolean`||typeof i.context.channel_owner!=`boolean`||typeof i.context.conversation!=`boolean`||typeof i.context.workspace!=`boolean`||!Array.isArray(i.capabilities))throw Error(`Kai returned unsupported action metadata.`);let a=i.capabilities.map(G);if(a.some(e=>e===null))throw Error(`Kai returned unsupported action metadata.`);return{capabilities:a,context:{administrator:i.context.administrator,agent:i.context.agent,agentOwner:i.context.agent_owner,channelOwner:i.context.channel_owner,conversation:i.context.conversation,workspace:i.context.workspace}}}var Ce=new Set([`healthy`,`degraded`,`disabled`,`unavailable`]);function we(e){return typeof e==`string`&&Ce.has(e)}async function Te(e){let t=await X(e,`/v1/client/administration/webhook-diagnostics`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load webhook diagnostics.`));if(!K(n)||n.version!==1||!we(n.state)||!K(n.listener)||!we(n.listener.state)||typeof n.listener.port!=`number`||!Number.isInteger(n.listener.port)||n.listener.port<1||!Array.isArray(n.endpoints)||!K(n.deliveries)||!we(n.deliveries.state)||!Array.isArray(n.guidance)||!n.guidance.every(e=>typeof e==`string`))throw Error(`Kai returned unsupported webhook diagnostics.`);let r=n.deliveries,i=n.endpoints.map(e=>!K(e)||typeof e.endpoint_class!=`string`||typeof e.display_name!=`string`||!we(e.state)||typeof e.description!=`string`?null:{description:e.description,displayName:e.display_name,endpointClass:e.endpoint_class,state:e.state});if(i.some(e=>e===null)||![`window_hours`,`pending`,`executing`,`retrying`,`succeeded`,`failed`].every(e=>typeof r[e]==`number`&&Number.isInteger(r[e])&&r[e]>=0))throw Error(`Kai returned unsupported webhook diagnostics.`);return{deliveries:{executing:r.executing,failed:r.failed,pending:r.pending,retrying:r.retrying,state:r.state,succeeded:r.succeeded,windowHours:r.window_hours},endpoints:i,guidance:n.guidance,listener:{port:n.listener.port,state:n.listener.state},state:n.state}}var Ee=new Set([`agent_delegation`,`image_input`,`text_generation`,`tool_activity`,`workspace_execution`]);function De(e){if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let n of e){if(typeof n!=`string`||!Ee.has(n)||t.includes(n))return null;t.push(n)}return t}var Oe=new Set([`context_read`,`reaction`,`progress_publish`,`thread_reply`,`artifact_publish`,`agent_delegation`,`standing_participation`]);function ke(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!=`string`||!Oe.has(n)||t.includes(n))return null;t.push(n)}return t}function Ae(e){if(!K(e)||typeof e.definition_id!=`string`||!S.test(e.definition_id)||typeof e.agent_id!=`string`||!x.test(e.agent_id)||typeof e.handle!=`string`||typeof e.display_name!=`string`||typeof e.description!=`string`||!K(e.presentation)||Object.keys(e.presentation).some(e=>e!==`avatar`)||e.presentation.avatar!==void 0&&typeof e.presentation.avatar!=`string`||![`draft`,`active`,`archived`].includes(String(e.lifecycle_state))||e.active_revision_id!==null&&(typeof e.active_revision_id!=`string`||!w.test(e.active_revision_id))||!Number.isSafeInteger(e.state_version)||e.state_version<1||typeof e.created_at!=`string`||e.created_by_principal_id!==null&&(typeof e.created_by_principal_id!=`string`||!E.test(e.created_by_principal_id))||e.owner_principal_id!==null&&(typeof e.owner_principal_id!=`string`||!E.test(e.owner_principal_id))||e.owner_display_name!==null&&typeof e.owner_display_name!=`string`||!Array.isArray(e.revisions))return null;let t=e.revisions.map(e=>{if(!K(e)||typeof e.revision_id!=`string`||!w.test(e.revision_id)||!Number.isSafeInteger(e.revision_number)||e.revision_number<1||typeof e.purpose!=`string`||typeof e.instructions!=`string`||typeof e.created_at!=`string`||e.created_by_principal_id!==null&&(typeof e.created_by_principal_id!=`string`||!E.test(e.created_by_principal_id))||!Number.isSafeInteger(e.event_position)||e.event_position<1)return null;let t=De(e.capabilities),n=ke(e.collaboration_operations);return!t||!n?null:{capabilities:t,collaborationOperations:n,createdAt:e.created_at,createdByPrincipalId:e.created_by_principal_id,eventPosition:e.event_position,instructions:e.instructions,purpose:e.purpose,revisionId:e.revision_id,revisionNumber:e.revision_number}});return t.some(e=>e===null)?null:{activeRevisionId:e.active_revision_id,agentId:e.agent_id,createdAt:e.created_at,createdByPrincipalId:e.created_by_principal_id,definitionId:e.definition_id,description:e.description,displayName:e.display_name,handle:e.handle,lifecycleState:e.lifecycle_state,ownerDisplayName:e.owner_display_name,ownerPrincipalId:e.owner_principal_id,presentation:e.presentation,revisions:t,stateVersion:e.state_version}}function je(e){if(!K(e)||e.enablement_id!==null&&(typeof e.enablement_id!=`string`||!T.test(e.enablement_id))||typeof e.definition_id!=`string`||!S.test(e.definition_id)||typeof e.agent_id!=`string`||!x.test(e.agent_id)||typeof e.handle!=`string`||typeof e.display_name!=`string`||![`available`,`enabled`,`disabled`].includes(String(e.lifecycle_state))||e.direct_channel_id!==null&&(typeof e.direct_channel_id!=`string`||!b.test(e.direct_channel_id))||e.runtime_profile_id!==null&&(typeof e.runtime_profile_id!=`string`||!D.test(e.runtime_profile_id))||e.state_version!==null&&(!Number.isSafeInteger(e.state_version)||e.state_version<1)||!Array.isArray(e.eligible_runtimes)||typeof e.can_manage!=`boolean`||typeof e.conversation_started!=`boolean`||e.owner_principal_id!==null&&(typeof e.owner_principal_id!=`string`||!E.test(e.owner_principal_id))||e.owner_runtime_profile_id!==null&&(typeof e.owner_runtime_profile_id!=`string`||!D.test(e.owner_runtime_profile_id)))return null;let t=e.eligible_runtimes.map(e=>!K(e)||typeof e.runtime_profile_id!=`string`||!D.test(e.runtime_profile_id)||typeof e.display_name!=`string`||!Array.isArray(e.backend_options)||e.backend_options.some(e=>typeof e!=`string`)?null:{backendOptions:e.backend_options,displayName:e.display_name,runtimeProfileId:e.runtime_profile_id});return t.some(e=>e===null)?null:{agentId:e.agent_id,definitionId:e.definition_id,directChannelId:e.direct_channel_id,displayName:e.display_name,eligibleRuntimes:t,enablementId:e.enablement_id,handle:e.handle,lifecycleState:e.lifecycle_state,runtimeProfileId:e.runtime_profile_id,stateVersion:e.state_version,canManage:e.can_manage,conversationStarted:e.conversation_started,ownerPrincipalId:e.owner_principal_id,ownerRuntimeProfileId:e.owner_runtime_profile_id}}function Me(e){if(!Array.isArray(e))return null;let t=e.map(e=>!K(e)||typeof e.code!=`string`||e.code.length===0||typeof e.detail!=`string`||e.detail.length===0?null:{code:e.code,detail:e.detail});return t.some(e=>e===null)?null:t}function Ne(e){if(!K(e)||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.ready!=`boolean`||!Array.isArray(e.runtimes))return null;let t=Me(e.blockers);if(!t)return null;let n=[`refreshing`,`succeeded`,`failed`,`unsupported`,`malformed`,`timed_out`,`invalidated`,`superseded`],r=[`available`,`not_advertised`,`unavailable`,`unknown`],i=[`ready`,`unverified`,`unavailable`,`misconfigured`],a=e.runtimes.map(e=>{if(!K(e)||typeof e.runtime_profile_id!=`string`||!D.test(e.runtime_profile_id)||typeof e.display_name!=`string`||e.display_name.length===0||typeof e.current_backend_option_id!=`string`||e.current_backend_option_id.length===0||e.default_workspace!==null&&typeof e.default_workspace!=`string`||!Number.isSafeInteger(e.default_timeout_seconds)||e.default_timeout_seconds<1||!Number.isSafeInteger(e.minimum_timeout_seconds)||e.minimum_timeout_seconds<1||!Number.isSafeInteger(e.maximum_timeout_seconds)||e.maximum_timeout_seconds{if(!K(e)||typeof e.option_id!=`string`||e.option_id.length===0||typeof e.backend!=`string`||e.backend.length===0||typeof e.provider!=`string`||e.provider.length===0||typeof e.current!=`boolean`||typeof e.readiness!=`string`||!i.includes(e.readiness)||typeof e.default_model!=`string`||e.default_model.length===0||e.catalogue_status!==null&&(typeof e.catalogue_status!=`string`||!n.includes(e.catalogue_status))||typeof e.catalogue_stale!=`boolean`||!Array.isArray(e.models))return null;let t=Me(e.blockers);if(!t)return null;let a=e.models.map(e=>!K(e)||typeof e.model_id!=`string`||e.model_id.length===0||typeof e.display_name!=`string`||e.display_name.length===0||typeof e.status!=`string`||!r.includes(e.status)||typeof e.selectable!=`boolean`||typeof e.retained!=`boolean`?null:{displayName:e.display_name,modelId:e.model_id,retained:e.retained,selectable:e.selectable,status:e.status});return a.some(e=>e===null)?null:{backend:e.backend,blockers:t,catalogueStale:e.catalogue_stale,catalogueStatus:e.catalogue_status,current:e.current,defaultModel:e.default_model,models:a,optionId:e.option_id,provider:e.provider,readiness:e.readiness}}),o=e.workspaces.map(e=>!K(e)||typeof e.path!=`string`||e.path.length===0||typeof e.name!=`string`||e.name.length===0||typeof e.default!=`boolean`||typeof e.available!=`boolean`?null:{available:e.available,default:e.default,name:e.name,path:e.path});return a.some(e=>e===null)||o.some(e=>e===null)?null:{backends:a,blockers:t,currentBackendOptionId:e.current_backend_option_id,defaultTimeoutSeconds:e.default_timeout_seconds,defaultWorkspace:e.default_workspace,displayName:e.display_name,maximumTimeoutSeconds:e.maximum_timeout_seconds,minimumTimeoutSeconds:e.minimum_timeout_seconds,ready:e.ready,runtimeProfileId:e.runtime_profile_id,workspaces:o}});return a.some(e=>e===null)?null:{blockers:t,principalId:e.principal_id,ready:e.ready,runtimes:a}}function Pe(e){let t=[`draft`,`needs_attention`,`provisioning`,`ready`],n=[`definition_created`,`revision_activated`,`enablement_created`,`runtime_registered`,`backend_selected`,`model_selected`,`workspace_selected`,`timeout_selected`,`collaboration_policy_set`,`ready`];if(!K(e)||typeof e.operation_id!=`string`||!C.test(e.operation_id)||typeof e.client_operation_id!=`string`||e.client_operation_id.length===0||typeof e.status!=`string`||!t.includes(e.status)||typeof e.replayed!=`boolean`||e.definition_id!==null&&(typeof e.definition_id!=`string`||!S.test(e.definition_id))||e.revision_id!==null&&(typeof e.revision_id!=`string`||!w.test(e.revision_id))||e.agent_id!==null&&(typeof e.agent_id!=`string`||!x.test(e.agent_id))||e.enablement_id!==null&&(typeof e.enablement_id!=`string`||!T.test(e.enablement_id))||e.direct_channel_id!==null&&(typeof e.direct_channel_id!=`string`||!b.test(e.direct_channel_id))||typeof e.runtime_profile_id!=`string`||!D.test(e.runtime_profile_id)||!Array.isArray(e.completed_stages)||e.completed_stages.some(e=>typeof e!=`string`||!n.includes(e))||e.next_stage!==null&&(typeof e.next_stage!=`string`||!n.includes(e.next_stage)))return null;let r=Me(e.blockers);return r?{agentId:e.agent_id,blockers:r,clientOperationId:e.client_operation_id,completedStages:e.completed_stages,definitionId:e.definition_id,directChannelId:e.direct_channel_id,enablementId:e.enablement_id,nextStage:e.next_stage,operationId:e.operation_id,replayed:e.replayed,revisionId:e.revision_id,runtimeProfileId:e.runtime_profile_id,status:e.status}:null}async function Fe(e,t,n,r){let i=await X({channelId:``,token:e},t,{body:JSON.stringify(n),headers:{"Content-Type":`application/json`},method:`POST`}),a=await Y(i);if(!i.ok)throw Error(J(a,r));let o=K(a)&&a.version===1?Ae(a.agent):null;if(!o)throw Error(`Kai returned an unsupported agent definition.`);return o}async function Ie(e,t,n){let r=await X({channelId:``,token:e},t,{body:JSON.stringify(n),headers:{"Content-Type":`application/json`},method:`POST`}),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not update this agent.`));let a=K(i)&&i.version===1?je(i.agent):null;if(!a)throw Error(`Kai returned unsupported agent enablement state.`);return a}async function Le(e){let t=await X({channelId:``,token:e},`/v1/client/agents`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load agents.`));if(!K(n)||n.version!==1||!Array.isArray(n.agents))throw Error(`Kai returned unsupported agent definitions.`);let r=n.agents.map(Ae);if(r.some(e=>e===null))throw Error(`Kai returned unsupported agent definitions.`);return r}async function Re(e){let t=await X({channelId:``,token:e},`/v1/client/agents/creation-options`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load agent creation options.`));let r=K(n)&&n.version===1?Ne(n.creation_options):null;if(!r)throw Error(`Kai returned unsupported agent creation options.`);return r}function ze(e){if(!K(e)||typeof e.client_operation_id!=`string`||!K(e.definition)||!K(e.revision)||!K(e.runtime)||!K(e.collaboration_policy))return null;let t=e.definition,n=e.revision,r=e.runtime,i=e.collaboration_policy,a=t.presentation,o=t.existing_definition_id;return typeof t.handle!=`string`||typeof t.display_name!=`string`||typeof t.description!=`string`||!K(a)||a.avatar!==void 0&&typeof a.avatar!=`string`||o!==void 0&&(typeof o!=`string`||!S.test(o))||typeof n.purpose!=`string`||typeof n.instructions!=`string`||!Array.isArray(n.capabilities)||n.capabilities.some(e=>typeof e!=`string`)||!Array.isArray(n.collaboration_operations)||n.collaboration_operations.some(e=>typeof e!=`string`)||!Array.isArray(i.allowed_operations)||i.allowed_operations.some(e=>typeof e!=`string`)||typeof r.runtime_profile_id!=`string`||typeof r.backend_option_id!=`string`||typeof r.model!=`string`||typeof r.workspace!=`string`||typeof r.timeout_seconds!=`number`?null:{allowedCollaborationOperations:i.allowed_operations,avatar:typeof a.avatar==`string`?a.avatar:``,backendOptionId:r.backend_option_id,capabilities:n.capabilities,clientOperationId:e.client_operation_id,collaborationOperations:n.collaboration_operations,description:t.description,displayName:t.display_name,...typeof o==`string`?{existingDefinitionId:o}:{},handle:t.handle,instructions:n.instructions,model:r.model,purpose:n.purpose,runtimeProfileId:r.runtime_profile_id,timeoutSeconds:r.timeout_seconds,workspace:r.workspace}}async function Be(e){let t=await X({channelId:``,token:e},`/v1/client/agents/provision`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load saved agent setup.`));if(!K(n)||n.version!==1||!Array.isArray(n.setups))throw Error(`Kai returned unsupported saved agent setup state.`);let r=n.setups.map(e=>{if(!K(e))return null;let t=Pe(e.provisioning),n=ze(e.request);return t&&n?{input:n,provisioning:t}:null});if(r.some(e=>e===null))throw Error(`Kai returned unsupported saved agent setup state.`);return r}async function Ve(e,t){let n=await X({channelId:``,token:e},`/v1/client/agents/provision`,{body:JSON.stringify({client_operation_id:t.clientOperationId,collaboration_policy:{allowed_operations:t.allowedCollaborationOperations},definition:{description:t.description,display_name:t.displayName,handle:t.handle,presentation:t.avatar.trim()?{avatar:t.avatar.trim()}:{},...t.existingDefinitionId?{existing_definition_id:t.existingDefinitionId}:{}},revision:{capabilities:t.capabilities,collaboration_operations:t.collaborationOperations,instructions:t.instructions,purpose:t.purpose},runtime:{backend_option_id:t.backendOptionId,model:t.model,runtime_profile_id:t.runtimeProfileId,timeout_seconds:t.timeoutSeconds,workspace:t.workspace}}),headers:{"Content-Type":`application/json`},method:`POST`}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not provision this agent.`));let i=K(r)&&r.version===1?Pe(r.provisioning):null;if(!i)throw Error(`Kai returned unsupported agent provisioning state.`);return i}async function He(e){let t=await X({channelId:``,token:e},`/v1/client/agent-enablement`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load agent access.`));if(!K(n)||n.version!==1||!Array.isArray(n.agents))throw Error(`Kai returned unsupported agent enablement state.`);let r=n.agents.map(je);if(r.some(e=>e===null))throw Error(`Kai returned unsupported agent enablement state.`);return r}function Ue(e){if(!K(e)||typeof e.definition_id!=`string`||!S.test(e.definition_id)||typeof e.owner_principal_id!=`string`||!E.test(e.owner_principal_id)||typeof e.can_manage!=`boolean`||!Number.isSafeInteger(e.policy_version)||e.policy_version<0||e.active_revision_id!==null&&(typeof e.active_revision_id!=`string`||!w.test(e.active_revision_id))||e.active_grants!==null&&(!Number.isSafeInteger(e.active_grants)||e.active_grants<0)||!Array.isArray(e.operations))return null;let t=e.operations.map(e=>!K(e)||typeof e.operation!=`string`||!Oe.has(e.operation)||typeof e.requested!=`boolean`||e.owner_allowed!==null&&typeof e.owner_allowed!=`boolean`||typeof e.host_allowed!=`boolean`||typeof e.effective_for_new_attempt!=`boolean`||e.unavailable_reason!==null&&typeof e.unavailable_reason!=`string`||e.quota!==null&&(!Number.isSafeInteger(e.quota)||e.quota<1)?null:{effectiveForNewAttempt:e.effective_for_new_attempt,hostAllowed:e.host_allowed,operation:e.operation,ownerAllowed:e.owner_allowed,quota:e.quota,requested:e.requested,unavailableReason:e.unavailable_reason});return t.some(e=>e===null)?null:{activeGrants:e.active_grants,activeRevisionId:e.active_revision_id,canManage:e.can_manage,definitionId:e.definition_id,operations:t,ownerPrincipalId:e.owner_principal_id,policyVersion:e.policy_version}}async function We(e,t){let n=await Y(e);if(!e.ok)throw Error(J(n,t));let r=K(n)&&n.version===1?Ue(n.policy):null;if(!r)throw Error(`Kai returned unsupported collaboration policy.`);return r}async function Z(e,t){return We(await X({channelId:``,token:e},`/v1/client/agents/${encodeURIComponent(t)}/collaboration-policy`),`Could not load collaboration policy.`)}function Ge(e,t=0){return Number.isSafeInteger(e)&&e>=t}function Ke(e,t){if(!K(e)||e.channel_id!==t||!K(e.policy)||!Array.isArray(e.subscriptions)||!Array.isArray(e.observations)||!Array.isArray(e.recent_runs)||typeof e.can_inspect_silent!=`boolean`)return null;let n=e.policy;if(typeof n.enabled!=`boolean`||typeof n.can_manage!=`boolean`||typeof n.host_enabled!=`boolean`||!Ge(n.policy_version)||!Ge(n.host_policy_version,1)||!Ge(n.max_agents_per_channel,1)||!Ge(n.coalescing_grace_seconds)||!Ge(n.max_messages_per_observe_run,1)||!Ge(n.max_pending_messages_per_scope,1)||!Ge(n.max_pending_age_seconds,1)||!Ge(n.max_observe_runs_per_hour,1)||!Ge(n.max_unsolicited_messages_per_hour,1)||!Ge(n.minimum_unsolicited_interval_seconds,1)||!Ge(n.quiet_expiry_seconds))return null;let r=[];for(let t of e.subscriptions){if(!K(t)||typeof t.agent_id!=`string`||!x.test(t.agent_id)||typeof t.agent_definition_id!=`string`||!S.test(t.agent_definition_id)||typeof t.agent_revision_id!=`string`||!w.test(t.agent_revision_id)||typeof t.agent_display_name!=`string`||typeof t.agent_handle!=`string`||![`active`,`paused_overflow`,`ended`].includes(String(t.lifecycle_state))||typeof t.started_by_principal_id!=`string`||!E.test(t.started_by_principal_id)||typeof t.started_by_message_id!=`string`||!A.test(t.started_by_message_id)||!Ge(t.owner_policy_version)||!Ge(t.channel_policy_version,1)||!Ge(t.host_policy_version,1)||!Ge(t.state_version,1)||typeof t.started_at!=`string`||t.quiet_expires_at!==null&&typeof t.quiet_expires_at!=`string`||t.end_reason!==null&&typeof t.end_reason!=`string`)return null;r.push({agentDefinitionId:t.agent_definition_id,agentDisplayName:t.agent_display_name,agentHandle:t.agent_handle,agentId:t.agent_id,agentRevisionId:t.agent_revision_id,channelPolicyVersion:t.channel_policy_version,endReason:t.end_reason,hostPolicyVersion:t.host_policy_version,lifecycleState:t.lifecycle_state,ownerPolicyVersion:t.owner_policy_version,quietExpiresAt:t.quiet_expires_at,startedAt:t.started_at,startedByMessageId:t.started_by_message_id,startedByPrincipalId:t.started_by_principal_id,stateVersion:t.state_version})}let i=[];for(let t of e.observations){if(!K(t)||typeof t.agent_id!=`string`||!x.test(t.agent_id)||![`channel`,`thread`].includes(String(t.scope_kind))||typeof t.scope_id!=`string`||!Ge(t.delivered_through_event_position)||!Ge(t.pending_through_event_position)||!Ge(t.considered_through_event_position)||!Ge(t.pending_message_count)||!Ge(t.state_version,1)||![`idle`,`pending`,`paused_overflow`].includes(String(t.lifecycle_state))||t.not_before!==null&&typeof t.not_before!=`string`||t.overflowed_at!==null&&typeof t.overflowed_at!=`string`||t.overflow_reason!==null&&typeof t.overflow_reason!=`string`||t.overflow_from_event_position!==null&&!Ge(t.overflow_from_event_position)||t.overflow_through_event_position!==null&&!Ge(t.overflow_through_event_position))return null;i.push({agentId:t.agent_id,consideredThroughEventPosition:t.considered_through_event_position,deliveredThroughEventPosition:t.delivered_through_event_position,lifecycleState:t.lifecycle_state,notBefore:t.not_before,overflowFromEventPosition:t.overflow_from_event_position,overflowReason:t.overflow_reason,overflowThroughEventPosition:t.overflow_through_event_position,overflowedAt:t.overflowed_at,pendingMessageCount:t.pending_message_count,pendingThroughEventPosition:t.pending_through_event_position,scopeId:t.scope_id,scopeKind:t.scope_kind,stateVersion:t.state_version})}let a=[];for(let t of e.recent_runs){if(!K(t)||typeof t.run_id!=`string`||typeof t.agent_id!=`string`||!x.test(t.agent_id)||typeof t.agent_display_name!=`string`||typeof t.status!=`string`||!_e.has(t.status)||typeof t.accepted_at!=`string`||t.started_at!==null&&typeof t.started_at!=`string`||t.terminal_at!==null&&typeof t.terminal_at!=`string`||t.terminal_code!==null&&typeof t.terminal_code!=`string`||![`channel`,`thread`].includes(String(t.scope_kind))||typeof t.scope_id!=`string`||!Ge(t.observed_from_event_position)||!Ge(t.observed_through_event_position)||!Ge(t.observed_message_count,1)||typeof t.human_anchor_message_id!=`string`||!A.test(t.human_anchor_message_id)||t.collaboration_grant_id!==null&&typeof t.collaboration_grant_id!=`string`||t.outcome!==null&&t.outcome!==`spoke`&&t.outcome!==`silent`&&t.outcome!==`publication_suppressed`)return null;a.push({acceptedAt:t.accepted_at,agentDisplayName:t.agent_display_name,agentId:t.agent_id,collaborationGrantId:t.collaboration_grant_id,humanAnchorMessageId:t.human_anchor_message_id,observedFromEventPosition:t.observed_from_event_position,observedMessageCount:t.observed_message_count,observedThroughEventPosition:t.observed_through_event_position,outcome:t.outcome,runId:t.run_id,scopeId:t.scope_id,scopeKind:t.scope_kind,startedAt:t.started_at,status:t.status,terminalAt:t.terminal_at,terminalCode:t.terminal_code})}return{canInspectSilent:e.can_inspect_silent,channelId:t,observations:i,policy:{canManage:n.can_manage,coalescingGraceSeconds:n.coalescing_grace_seconds,enabled:n.enabled,hostEnabled:n.host_enabled,hostPolicyVersion:n.host_policy_version,maxAgentsPerChannel:n.max_agents_per_channel,maxMessagesPerObserveRun:n.max_messages_per_observe_run,maxObserveRunsPerHour:n.max_observe_runs_per_hour,maxPendingAgeSeconds:n.max_pending_age_seconds,maxPendingMessagesPerScope:n.max_pending_messages_per_scope,maxUnsolicitedMessagesPerHour:n.max_unsolicited_messages_per_hour,minimumUnsolicitedIntervalSeconds:n.minimum_unsolicited_interval_seconds,policyVersion:n.policy_version,quietExpirySeconds:n.quiet_expiry_seconds},recentRuns:a,subscriptions:r}}async function qe(e,t,n){let r=await Y(e);if(!e.ok)throw Error(J(r,n));let i=K(r)&&r.version===1?Ke(r.standing_participation,t):null;if(!i)throw Error(`Kai returned unsupported standing-participation state.`);return i}async function Je(e,t=!1){let n=t?`?include_silent=1`:``;return qe(await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/standing-participation${n}`),e.channelId,`Could not load standing participation.`)}async function Ye(e,t,n,r){return qe(await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/standing-participation`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:t,expected_policy_version:n,client_operation_id:r})}),e.channelId,`Could not update standing participation.`)}async function Xe(e,t,n,r){return qe(await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/agents/${encodeURIComponent(t)}/standing-participation/resume`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scope_id:n.scopeId,expected_state_version:n.stateVersion,client_operation_id:r})}),e.channelId,`Could not resume standing observation.`)}async function Ze(e,t,n){return We(await X({channelId:``,token:e},`/v1/client/agents/${encodeURIComponent(t)}/collaboration-policy`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({allowed_operations:n.allowedOperations,client_operation_id:n.clientOperationId,expected_policy_version:n.expectedPolicyVersion})}),`Could not update collaboration policy.`)}async function Qe(e,t,n){return We(await X({channelId:``,token:e},`/v1/client/agents/${encodeURIComponent(t)}/collaboration-policy/revoke-active`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_operation_id:n})}),`Could not revoke active collaboration access.`)}async function $e(e,t){return Fe(e,`/v1/client/agents`,{capabilities:t.capabilities,collaboration_operations:t.collaborationOperations,description:t.description,display_name:t.displayName,handle:t.handle,idempotency_key:t.idempotencyKey,instructions:t.instructions,presentation:t.avatar.trim()?{avatar:t.avatar.trim()}:{},purpose:t.purpose},`Could not create this agent.`)}async function et(e,t,n){return Fe(e,`/v1/client/agents/${encodeURIComponent(t)}/revisions`,{capabilities:n.capabilities,collaboration_operations:n.collaborationOperations,expected_version:n.expectedVersion,idempotency_key:n.idempotencyKey,instructions:n.instructions,purpose:n.purpose},`Could not save this agent revision.`)}async function tt(e,t,n){return Fe(e,`/v1/client/agents/${encodeURIComponent(t)}/activate`,{expected_version:n.expectedVersion,idempotency_key:n.idempotencyKey,revision_id:n.revisionId},`Could not activate this agent revision.`)}async function nt(e,t,n){return Fe(e,`/v1/client/agents/${encodeURIComponent(t)}/archive`,{expected_version:n.expectedVersion,idempotency_key:n.idempotencyKey},`Could not archive this agent.`)}async function rt(e,t,n){return Ie(e,`/v1/client/agents/${encodeURIComponent(t)}/enable`,{...n.expectedVersion===null?{}:{expected_version:n.expectedVersion},idempotency_key:n.idempotencyKey,runtime_profile_id:n.runtimeProfileId})}async function it(e,t,n){return Ie(e,`/v1/client/agents/${encodeURIComponent(t)}/conversation`,{expected_version:n.expectedVersion,idempotency_key:n.idempotencyKey})}async function at(e,t){let n=await X({channelId:``,token:e},`/v1/channels`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agent_ids:t.agentIds,name:t.name,...t.originChannelId?{origin_channel_id:t.originChannelId}:{}})}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not create this channel.`));if(!K(r)||r.version!==1||!K(r.channel)||typeof r.channel.channel_id!=`string`||!b.test(r.channel.channel_id))throw Error(`Kai returned an unsupported channel creation response.`);return r.channel.channel_id}function ot(e){return!K(e)||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.display_name!=`string`||typeof e.handle!=`string`||!M.test(e.handle)||e.conversation_channel_id!==null&&(typeof e.conversation_channel_id!=`string`||!b.test(e.conversation_channel_id))?null:{avatar:de(e.avatar,e.principal_id),conversationChannelId:e.conversation_channel_id,displayName:e.display_name,handle:e.handle,principalId:e.principal_id}}async function st(e,t){if(!O.test(t))throw Error(`Invalid Workshop identity.`);let n=await X({channelId:``,token:e},`/v1/workshops/${encodeURIComponent(t)}/humans`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load Workshop people.`));if(!K(r)||r.version!==1||r.workshop_id!==t||!Array.isArray(r.humans))throw Error(`Kai returned unsupported Workshop people.`);let i=r.humans.map(ot);if(i.some(e=>e===null))throw Error(`Kai returned unsupported Workshop people.`);return i}async function ct(e,t,n){if(!O.test(t))throw Error(`Invalid Workshop identity.`);if(!E.test(n))throw Error(`Invalid human identity.`);let r=await X({channelId:``,token:e},`/v1/workshops/${encodeURIComponent(t)}/humans/${encodeURIComponent(n)}/conversation`,{method:`POST`}),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not start this conversation.`));let a=K(i)?i.conversation:null,o=K(a)&&K(a.peer)?a.peer:null,s=o&&K(a)?ot({...o,conversation_channel_id:a.channel_id}):null;if(!K(i)||i.version!==1||typeof i.created!=`boolean`||!K(a)||a.workshop_id!==t||typeof a.channel_id!=`string`||!b.test(a.channel_id)||a.kind!==`direct`||!s||s.principalId!==n)throw Error(`Kai returned an unsupported human conversation response.`);return{channelId:a.channel_id,created:i.created,peer:s,workshopId:t}}async function lt(e,t,n,r){if(!b.test(t))throw Error(`Invalid channel identity.`);let i=await X({channelId:t,token:e},`/v1/channels/${encodeURIComponent(t)}/${n}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_operation_id:r})}),a=await Y(i);if(!i.ok||!K(a)||a.version!==1||!K(a.channel)||a.channel.channel_id!==t||a.channel.archived!==(n===`archive`)||typeof a.channel.changed!=`boolean`||typeof a.channel.occurred_at!=`string`)throw Error(J(a,n===`archive`?`Could not archive this channel.`:`Could not restore this channel.`))}async function ut(e,t,n){await lt(e,t,`archive`,n)}async function dt(e,t,n){await lt(e,t,`restore`,n)}async function ft(e,t,n,r){if(!b.test(t))throw Error(`Invalid channel identity.`);let i=await X({channelId:t,token:e},`/v1/direct-messages/${encodeURIComponent(t)}/${n}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_operation_id:r})}),a=await Y(i);if(!i.ok||!K(a)||a.version!==1||!K(a.direct_message)||a.direct_message.channel_id!==t||a.direct_message.archived!==(n===`archive`)||typeof a.direct_message.changed!=`boolean`||typeof a.direct_message.occurred_at!=`string`)throw Error(J(a,n===`archive`?`Could not archive this direct message.`:`Could not restore this direct message.`))}async function pt(e,t,n){await ft(e,t,`archive`,n)}async function mt(e,t,n){await ft(e,t,`restore`,n)}function ht(e){return!K(e)||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.display_name!=`string`||typeof e.handle!=`string`||!M.test(e.handle)||![`owner`,`participant`,null].includes(e.role)?null:{avatar:de(e.avatar,e.principal_id),displayName:e.display_name,handle:e.handle,principalId:e.principal_id,role:e.role}}async function gt(e){let t=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/members`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load channel members.`));if(!K(n)||n.version!==1||n.channel_id!==e.channelId||typeof n.workshop_id!=`string`||!O.test(n.workshop_id)||typeof n.archived!=`boolean`||typeof n.can_manage!=`boolean`||!Number.isSafeInteger(n.state_version)||n.state_version<0||!Array.isArray(n.members)||!Array.isArray(n.eligible_humans))throw Error(`Kai returned unsupported channel membership state.`);let r=n.members.map(ht),i=n.eligible_humans.map(ht);if(r.some(e=>e===null)||i.some(e=>e===null))throw Error(`Kai returned unsupported channel membership state.`);return{archived:n.archived,canManage:n.can_manage,channelId:n.channel_id,eligibleHumans:i,members:r,stateVersion:n.state_version,workshopId:n.workshop_id}}async function _t(e,t,n,r,i){if(!E.test(t))throw Error(`Invalid human identity.`);let a=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/members/${encodeURIComponent(t)}/${n}`,{body:JSON.stringify({client_operation_id:i,expected_state_version:r}),headers:{"Content-Type":`application/json`},method:`POST`}),o=await Y(a);if(!a.ok||!K(o)||o.version!==1||o.operation!==n||typeof o.changed!=`boolean`||!Number.isSafeInteger(o.state_version))throw Error(J(o,`Could not update channel members.`));return o.state_version}async function vt(e,t,n,r){if(!x.test(t))throw Error(`Invalid agent identity.`);let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/agents/${encodeURIComponent(t)}/${n}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_operation_id:r})}),a=await Y(i);if(!i.ok||!K(a)||a.version!==1||a.operation!==n||typeof a.changed!=`boolean`)throw Error(J(a,n===`attach`?`Could not attach this agent.`:`Could not detach this agent.`))}async function yt(e,t,n){await vt(e,t,`attach`,n)}async function bt(e,t,n){await vt(e,t,`detach`,n)}async function xt(e,t,n,r=null){if(!x.test(t))throw Error(`Invalid agent identity.`);if(r!==null&&!A.test(r))throw Error(`Invalid thread root identity.`);let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/agents/${encodeURIComponent(t)}/dismiss`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_dismissal_id:n,...r?{thread_root_id:r}:{}})}),a=await Y(i);if(!i.ok||!K(a)||a.version!==1||a.dismissed!==!0||typeof a.replayed!=`boolean`)throw Error(J(a,`Could not dismiss this agent.`))}async function St(e,t,n,r){if(!A.test(t)||!oe.has(n))throw Error(`Invalid message reaction.`);let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/messages/${encodeURIComponent(t)}/reactions`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({reaction:n,active:r})}),a=await Y(i);if(!i.ok||!K(a)||a.version!==1||a.message_id!==t)throw Error(J(a,`Could not update this reaction.`));let o=se(a.reactions);if(o===null)throw Error(`Kai returned an unsupported reaction response.`);return o}async function Ct(e,t,n){if(!A.test(t)||!oe.has(n))throw Error(`Invalid message reaction.`);let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/messages/${encodeURIComponent(t)}/reactions/${encodeURIComponent(n)}/reactors`),i=await Y(r);if(!r.ok||!K(i)||i.version!==1||!Number.isSafeInteger(i.total)||i.total<0||typeof i.truncated!=`boolean`||!Array.isArray(i.reactors))throw Error(J(i,`Could not load reaction participants.`));let a=i.reactors.map(e=>{if(!K(e)||typeof e.principal_id!=`string`||!E.test(e.principal_id)||![`human`,`agent`].includes(String(e.kind))||typeof e.display_name!=`string`||e.handle!==null&&typeof e.handle!=`string`)throw Error(`Kai returned unsupported reaction participants.`);return{displayName:e.display_name,handle:e.handle,kind:e.kind,principalId:e.principal_id}});if(a.length>i.total)throw Error(`Kai returned unsupported reaction participants.`);return{reactors:a,total:i.total,truncated:i.truncated}}function wt(e){if(!Array.isArray(e))throw Error(`Kai returned unsupported settings capabilities.`);return e.map(e=>{if(!K(e)||typeof e.field!=`string`||![`runtime`,`workspace`].includes(String(e.scope))||![`authorized_workspace`,`backend_id`,`integer_seconds`,`model_id`,`text`].includes(String(e.value_type))||typeof e.resettable!=`boolean`||e.choices!==null&&(!Array.isArray(e.choices)||e.choices.some(e=>typeof e!=`string`))||e.minimum!==null&&!Number.isSafeInteger(e.minimum)||e.maximum!==null&&!Number.isSafeInteger(e.maximum))throw Error(`Kai returned unsupported settings capabilities.`);return{choices:e.choices,field:e.field,maximum:e.maximum,minimum:e.minimum,resettable:e.resettable,scope:e.scope,valueType:e.value_type}})}function Tt(e){if(e===null)return null;if(!K(e)||typeof e.operation!=`string`||typeof e.changed!=`boolean`||![`deferred_until_next_run`,`restarted`,`unchanged`].includes(String(e.runtime_action))||typeof e.provider_session_invalidated!=`boolean`)throw Error(`Kai returned an unsupported settings mutation result.`);return{changed:e.changed,operation:e.operation,providerSessionInvalidated:e.provider_session_invalidated,runtimeAction:e.runtime_action}}function Et(e,t){if(!K(e)||e.version!==1||e.channel_id!==t||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.runtime_profile_id!=`string`||typeof e.backend!=`string`||typeof e.backend_option_id!=`string`||typeof e.provider!=`string`||!Array.isArray(e.backend_options)||typeof e.workspace!=`string`||typeof e.revision!=`string`||!K(e.model)||typeof e.model.value!=`string`||typeof e.model.source!=`string`||typeof e.model.default_value!=`string`||!K(e.timeout_seconds)||!Number.isSafeInteger(e.timeout_seconds.value)||typeof e.timeout_seconds.source!=`string`||!Number.isSafeInteger(e.timeout_seconds.default_value)||!Array.isArray(e.workspaces)||e.model_options!==null&&!Array.isArray(e.model_options))throw Error(`Kai returned unsupported settings and workspace state.`);let n=e.workspaces.map(e=>{if(!K(e)||typeof e.path!=`string`||typeof e.name!=`string`||typeof e.current!=`boolean`||typeof e.home!=`boolean`||e.deletable!==void 0&&typeof e.deletable!=`boolean`)throw Error(`Kai returned unsupported workspace state.`);return{current:e.current,deletable:e.deletable===!0,home:e.home,name:e.name,path:e.path}}),r=e.backend_options.map(e=>{if(!K(e)||typeof e.option_id!=`string`||typeof e.backend!=`string`||typeof e.provider!=`string`||typeof e.current!=`boolean`)throw Error(`Kai returned unsupported backend policy.`);return{backend:e.backend,current:e.current,optionId:e.option_id,provider:e.provider}}),i=e.model_options===null?null:e.model_options.map(e=>{if(!K(e)||typeof e.model_id!=`string`||typeof e.display_name!=`string`||![`available`,`not_advertised`,`unavailable`,`unknown`].includes(String(e.status))||typeof e.selectable!=`boolean`||typeof e.retained!=`boolean`)throw Error(`Kai returned unsupported model options.`);return{displayName:e.display_name,modelId:e.model_id,retained:e.retained,selectable:e.selectable,sources:[],status:e.status}}),a=e.model_catalogue;if(a!==null&&(!K(a)||a.status!==null&&typeof a.status!=`string`||typeof a.stale!=`boolean`||typeof a.last_known_good!=`boolean`||a.last_attempt_at!==null&&typeof a.last_attempt_at!=`string`||a.last_successful_refresh_at!==null&&typeof a.last_successful_refresh_at!=`string`||a.error_code!==null&&typeof a.error_code!=`string`||a.error_detail!==null&&typeof a.error_detail!=`string`))throw Error(`Kai returned unsupported model catalogue status.`);return{backend:e.backend,backendOptionId:e.backend_option_id,backendOptions:r,channelId:t,model:{defaultValue:e.model.default_value,source:e.model.source,value:e.model.value},modelCatalogue:a===null?null:{errorCode:a.error_code,errorDetail:a.error_detail,lastAttemptAt:a.last_attempt_at,lastKnownGood:a.last_known_good,lastSuccessfulRefreshAt:a.last_successful_refresh_at,stale:a.stale,status:a.status},modelOptions:i,capabilities:wt(e.capabilities),mutation:Tt(e.mutation),principalId:e.principal_id,provider:e.provider,revision:e.revision,runtimeProfileId:e.runtime_profile_id,timeoutSeconds:{defaultValue:e.timeout_seconds.default_value,source:e.timeout_seconds.source,value:e.timeout_seconds.value},workspace:e.workspace,workspaces:n}}function Dt(e){if(!K(e)||e.version!==1||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.runtime_profile_id!=`string`||typeof e.workspace_base!=`string`&&e.workspace_base!==null||!Array.isArray(e.grants)||!(e.mutation===void 0||K(e.mutation)))throw Error(`Kai returned unsupported workspace grant state.`);let t=e.grants.map(e=>{if(!K(e)||typeof e.path!=`string`||typeof e.name!=`string`||typeof e.provenance!=`string`||typeof e.available!=`boolean`||typeof e.current!=`boolean`||typeof e.removable!=`boolean`)throw Error(`Kai returned unsupported workspace grant state.`);return{available:e.available,current:e.current,name:e.name,path:e.path,provenance:e.provenance,removable:e.removable}}),n=null;if(e.mutation!==void 0){if(!K(e.mutation)||typeof e.mutation.path!=`string`||typeof e.mutation.changed!=`boolean`)throw Error(`Kai returned unsupported workspace grant mutation.`);n={changed:e.mutation.changed,path:e.mutation.path}}return{grants:t,mutation:n,principalId:e.principal_id,runtimeProfileId:e.runtime_profile_id,workspaceBase:e.workspace_base}}function Ot(e){if(e==null)return null;if(!K(e)||e.requested_task_class!==null&&![`conversation`,`coding`,`vision`].includes(String(e.requested_task_class))||e.requested_backend_option_id!==null&&typeof e.requested_backend_option_id!=`string`||e.selected_backend_option_id!==null&&typeof e.selected_backend_option_id!=`string`||![`selected_default`,`routed`,`fallback_selected`,`rejected`].includes(String(e.disposition))||typeof e.reason_code!=`string`||e.policy_revision!==null&&typeof e.policy_revision!=`number`||typeof e.backend!=`string`||e.provider!==null&&typeof e.provider!=`string`||typeof e.model!=`string`||typeof e.evidence_version!=`number`||typeof e.decided_at!=`string`)throw Error(`Kai returned an unsupported routing decision.`);return{backend:e.backend,decidedAt:e.decided_at,disposition:e.disposition,evidenceVersion:e.evidence_version,model:e.model,policyRevision:e.policy_revision,provider:e.provider,reasonCode:e.reason_code,requestedBackendOptionId:e.requested_backend_option_id,requestedTaskClass:e.requested_task_class,selectedBackendOptionId:e.selected_backend_option_id}}function kt(e){if(!K(e)||e.version!==1||typeof e.runtime_profile_id!=`string`||typeof e.option_id!=`string`||typeof e.stale!=`boolean`||typeof e.last_known_good!=`boolean`||!Array.isArray(e.models)||e.refresh!==null&&!K(e.refresh))throw Error(`Kai returned an unsupported model catalogue.`);let t=e.models.map(e=>{if(!K(e)||typeof e.model_id!=`string`||typeof e.display_name!=`string`||![`available`,`not_advertised`,`unavailable`,`unknown`].includes(String(e.status))||typeof e.selectable!=`boolean`||typeof e.retained!=`boolean`||!Array.isArray(e.sources)||e.sources.some(e=>typeof e!=`string`))throw Error(`Kai returned unsupported model catalogue entries.`);return{displayName:e.display_name,modelId:e.model_id,retained:e.retained,selectable:e.selectable,sources:e.sources,status:e.status}}),n=e.refresh;if(n!==null&&(!K(n)||typeof n.status!=`string`||!Number.isSafeInteger(n.generation)||typeof n.last_attempt_at!=`string`||n.last_successful_refresh_at!==null&&typeof n.last_successful_refresh_at!=`string`||n.expires_at!==null&&typeof n.expires_at!=`string`||n.error_code!==null&&typeof n.error_code!=`string`||n.error_detail!==null&&typeof n.error_detail!=`string`))throw Error(`Kai returned unsupported model refresh status.`);return{lastKnownGood:e.last_known_good,models:t,optionId:e.option_id,refresh:n===null?null:{errorCode:n.error_code,errorDetail:n.error_detail,expiresAt:n.expires_at,generation:n.generation,lastAttemptAt:n.last_attempt_at,lastSuccessfulRefreshAt:n.last_successful_refresh_at,status:n.status},runtimeProfileId:e.runtime_profile_id,stale:e.stale}}function At(e){if(!K(e)||e.version!==1||e.github_login!==null&&typeof e.github_login!=`string`||typeof e.repositories_resettable!=`boolean`||!Array.isArray(e.repositories)||!K(e.pr_review)||typeof e.pr_review.enabled!=`boolean`||typeof e.pr_review.source!=`string`||typeof e.pr_review.resettable!=`boolean`||!K(e.issue_triage)||typeof e.issue_triage.enabled!=`boolean`||typeof e.issue_triage.source!=`string`||typeof e.issue_triage.resettable!=`boolean`||typeof e.token_stored!=`boolean`||typeof e.revision!=`string`||e.mutation!==null&&(!K(e.mutation)||typeof e.mutation.operation!=`string`||typeof e.mutation.changed!=`boolean`))throw Error(`Kai returned unsupported GitHub settings.`);let t=e.repositories.map(e=>{if(!K(e)||typeof e.repository!=`string`||typeof e.source!=`string`||typeof e.automation_authorized!=`boolean`)throw Error(`Kai returned unsupported GitHub repository settings.`);return{automationAuthorized:e.automation_authorized,repository:e.repository,source:e.source}}),n=e.mutation===null?null:{changed:e.mutation.changed,operation:e.mutation.operation};return{githubLogin:e.github_login,issueTriage:{enabled:e.issue_triage.enabled,resettable:e.issue_triage.resettable,source:e.issue_triage.source},mutation:n,prReview:{enabled:e.pr_review.enabled,resettable:e.pr_review.resettable,source:e.pr_review.source},repositories:t,repositoriesResettable:e.repositories_resettable,revision:e.revision,tokenStored:e.token_stored}}function jt(e){if(!K(e)||e.version!==1||!Array.isArray(e.destinations)||!Array.isArray(e.preferences)||typeof e.revision!=`string`||e.mutation!==null&&(!K(e.mutation)||typeof e.mutation.operation!=`string`||typeof e.mutation.changed!=`boolean`))throw Error(`Kai returned unsupported notification preferences.`);let t=e.destinations.map(e=>{if(!K(e)||typeof e.choice_id!=`string`||typeof e.display_name!=`string`||e.kind!==`direct`&&e.kind!==`notification`||!Array.isArray(e.supported_classes)||e.supported_classes.some(e=>e!==`github`&&e!==`generic`))throw Error(`Kai returned an unsupported notification destination.`);return{choiceId:e.choice_id,displayName:e.display_name,kind:e.kind,supportedClasses:e.supported_classes}}),n=e.preferences.map(e=>{if(!K(e)||e.integration_class!==`github`&&e.integration_class!==`generic`||typeof e.display_name!=`string`||typeof e.destination_choice_id!=`string`||typeof e.destination_name!=`string`||e.destination_kind!==`direct`&&e.destination_kind!==`notification`||typeof e.source!=`string`||typeof e.editable!=`boolean`||typeof e.resettable!=`boolean`)throw Error(`Kai returned an unsupported integration preference.`);return{destinationChoiceId:e.destination_choice_id,destinationKind:e.destination_kind,destinationName:e.destination_name,displayName:e.display_name,editable:e.editable,integrationClass:e.integration_class,resettable:e.resettable,source:e.source}});return{destinations:t,mutation:e.mutation===null?null:{changed:e.mutation.changed,operation:e.mutation.operation},preferences:n,revision:e.revision}}function Mt(e){let t=e=>e===`all`||e===`mentions_replies`||e===`muted`;if(!K(e)||e.version!==1||!Array.isArray(e.levels)||e.levels.some(e=>!t(e))||!Array.isArray(e.adapter_deliveries)||!Array.isArray(e.channels)||typeof e.muted_mentions_notify!=`boolean`||!K(e.do_not_disturb)||typeof e.do_not_disturb.enabled!=`boolean`||typeof e.do_not_disturb.timezone!=`string`||typeof e.do_not_disturb.start!=`string`||typeof e.do_not_disturb.end!=`string`||typeof e.revision!=`string`||e.mutation!==null&&(!K(e.mutation)||typeof e.mutation.operation!=`string`||typeof e.mutation.changed!=`boolean`))throw Error(`Kai returned unsupported channel notification policy.`);let n=e.channels.map(e=>{if(!K(e)||typeof e.channel_id!=`string`||typeof e.channel_name!=`string`||!t(e.level)||typeof e.source!=`string`)throw Error(`Kai returned an unsupported channel notification setting.`);return{channelId:e.channel_id,channelName:e.channel_name,level:e.level,source:e.source}});return{adapterDeliveries:e.adapter_deliveries.map(e=>{if(!K(e)||typeof e.transport!=`string`||typeof e.display_name!=`string`||typeof e.enabled!=`boolean`||typeof e.source!=`string`)throw Error(`Kai returned an unsupported adapter notification setting.`);return{displayName:e.display_name,enabled:e.enabled,source:e.source,transport:e.transport}}),channels:n,doNotDisturb:{enabled:e.do_not_disturb.enabled,timezone:e.do_not_disturb.timezone,start:e.do_not_disturb.start,end:e.do_not_disturb.end},levels:e.levels,mutedMentionsNotify:e.muted_mentions_notify,mutation:e.mutation===null?null:{changed:e.mutation.changed,operation:e.mutation.operation},revision:e.revision}}function Nt(e){if(!K(e)||e.version!==1||!K(e.voice_output)||typeof e.voice_output.available!=`boolean`||e.voice_output.unavailable_reason!==null&&typeof e.voice_output.unavailable_reason!=`string`||!Array.isArray(e.voice_output.modes)||!Array.isArray(e.voice_output.voices)||!Array.isArray(e.voice_output.bindings)||typeof e.revision!=`string`||e.mutation!==null&&(!K(e.mutation)||typeof e.mutation.operation!=`string`||typeof e.mutation.changed!=`boolean`))throw Error(`Kai returned unsupported client preferences.`);let t=e.voice_output.modes;if(t.some(e=>e!==`off`&&e!==`text_and_voice`&&e!==`voice_only`))throw Error(`Kai returned an unsupported client voice mode.`);let n=e.voice_output.voices.map(e=>{if(!K(e)||typeof e.value!=`string`||typeof e.display_name!=`string`)throw Error(`Kai returned an unsupported client voice.`);return{value:e.value,displayName:e.display_name}}),r=e.voice_output.bindings.map(e=>{if(!K(e)||typeof e.choice_id!=`string`||typeof e.client_name!=`string`||e.mode!==`off`&&e.mode!==`text_and_voice`&&e.mode!==`voice_only`||typeof e.voice!=`string`||typeof e.voice_name!=`string`||typeof e.editable!=`boolean`)throw Error(`Kai returned unsupported client-binding preferences.`);return{choiceId:e.choice_id,clientName:e.client_name,mode:e.mode,voice:e.voice,voiceName:e.voice_name,editable:e.editable}});return{mutation:e.mutation===null?null:{changed:e.mutation.changed,operation:e.mutation.operation},revision:e.revision,voiceOutput:{available:e.voice_output.available,unavailableReason:e.voice_output.unavailable_reason,modes:t,voices:n,bindings:r}}}function Pt(e){if(!K(e)||e.version!==1||!L(e.theme_id)||!Array.isArray(e.themes)||typeof e.revision!=`string`||e.mutation!==null&&(!K(e.mutation)||typeof e.mutation.operation!=`string`||typeof e.mutation.changed!=`boolean`))throw Error(`Kai returned unsupported appearance preferences.`);let t=e.themes.map(e=>{if(!K(e)||!L(e.theme_id)||typeof e.display_name!=`string`||e.color_scheme!==`dark`&&e.color_scheme!==`light`)throw Error(`Kai returned an unsupported Workshop theme.`);return{colorScheme:e.color_scheme,displayName:e.display_name,themeId:e.theme_id}});return{mutation:e.mutation===null?null:{changed:e.mutation.changed,operation:e.mutation.operation},revision:e.revision,themeId:e.theme_id,themes:t}}function Ft(e){if(!K(e)||e.version!==1||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.display_name!=`string`||typeof e.handle!=`string`||!M.test(e.handle)||!Number.isSafeInteger(e.state_version)||e.state_version<0||e.mutation!==null&&(!K(e.mutation)||typeof e.mutation.changed!=`boolean`||typeof e.mutation.replayed!=`boolean`))throw Error(`Kai returned an unsupported human profile.`);return{avatar:de(e.avatar,e.principal_id),principalId:e.principal_id,displayName:e.display_name,handle:e.handle,stateVersion:e.state_version,mutation:e.mutation===null?null:{changed:e.mutation.changed,replayed:e.mutation.replayed}}}function It(e){if(!K(e)||e.version!==1||typeof e.principal_id!=`string`||!E.test(e.principal_id)||typeof e.active!=`boolean`||!Number.isSafeInteger(e.state_version)||e.state_version<0||e.mutation!==null&&(!K(e.mutation)||typeof e.mutation.changed!=`boolean`||typeof e.mutation.replayed!=`boolean`))throw Error(`Kai returned an unsupported human avatar.`);let t=de(e,e.principal_id);if(t.active!==e.active||t.stateVersion!==e.state_version)throw Error(`Kai returned an unsupported human avatar.`);let n=[e.media_type,e.byte_size,e.width,e.height,e.sha256];if(e.active){if(e.media_type!==`image/png`||!Number.isSafeInteger(e.byte_size)||e.byte_size<1||!Number.isSafeInteger(e.width)||e.width<1||!Number.isSafeInteger(e.height)||e.height<1||typeof e.sha256!=`string`||!/^[0-9a-f]{64}$/.test(e.sha256))throw Error(`Kai returned an unsupported human avatar.`)}else if(n.some(e=>e!==null))throw Error(`Kai returned an unsupported human avatar.`);return{...t,byteSize:e.byte_size,height:e.height,mediaType:e.media_type,mutation:e.mutation===null?null:{changed:e.mutation.changed,replayed:e.mutation.replayed},principalId:e.principal_id,sha256:e.sha256,width:e.width}}function Lt(e){if(!K(e)||e.version!==1||typeof e.workspace!=`string`||typeof e.revision!=`string`||!K(e.model)||typeof e.model.value!=`string`||typeof e.model.source!=`string`||typeof e.model.default_value!=`string`||!K(e.timeout_seconds)||!Number.isSafeInteger(e.timeout_seconds.value)||typeof e.timeout_seconds.source!=`string`||!Number.isSafeInteger(e.timeout_seconds.default_value)||!Array.isArray(e.environment_keys)||e.environment_keys.some(e=>typeof e!=`string`)||!Array.isArray(e.environment_variables)||e.environment_variables.some(e=>!K(e)||typeof e.key!=`string`||![`operator`,`principal`,`principal_override`].includes(String(e.provenance))||typeof e.editable!=`boolean`||typeof e.removable!=`boolean`)||!K(e.environment_policy)||!Number.isSafeInteger(e.environment_policy.maximum_keys)||!Number.isSafeInteger(e.environment_policy.maximum_key_characters)||!Number.isSafeInteger(e.environment_policy.maximum_value_bytes)||e.environment_policy.values_write_only!==!0||e.prompt!==null&&typeof e.prompt!=`string`||typeof e.has_prompt!=`boolean`||e.prompt_source!==null&&typeof e.prompt_source!=`string`||!Array.isArray(e.override_fields)||e.override_fields.some(e=>typeof e!=`string`))throw Error(`Kai returned unsupported workspace settings state.`);return{capabilities:wt(e.capabilities),environmentKeys:e.environment_keys,environmentPolicy:{maximumKeyCharacters:e.environment_policy.maximum_key_characters,maximumKeys:e.environment_policy.maximum_keys,maximumValueBytes:e.environment_policy.maximum_value_bytes,valuesWriteOnly:!0},environmentVariables:e.environment_variables.map(e=>{let t=e;return{editable:t.editable,key:t.key,provenance:t.provenance,removable:t.removable}}),hasPrompt:e.has_prompt,model:{defaultValue:e.model.default_value,source:e.model.source,value:e.model.value},mutation:Tt(e.mutation),overrideFields:e.override_fields,prompt:e.prompt,promptSource:e.prompt_source,revision:e.revision,timeoutSeconds:{defaultValue:e.timeout_seconds.default_value,source:e.timeout_seconds.source,value:e.timeout_seconds.value},workspace:e.workspace}}function Rt(e){if(!K(e)||e.version!==1||typeof e.principal_id!=`string`||typeof e.runtime_profile_id!=`string`||typeof e.current_workspace!=`string`||e.active_project_id!==null&&typeof e.active_project_id!=`string`||typeof e.revision!=`string`||!Array.isArray(e.projects)||e.projects.some(e=>!K(e)||typeof e.project_id!=`string`||typeof e.display_name!=`string`||!Array.isArray(e.workspace_roots)||e.workspace_roots.some(e=>typeof e!=`string`)||![`operator_pinned`,`principal_registered`,`principal_created`,`legacy_migrated`].includes(String(e.provenance))||typeof e.current!=`boolean`||typeof e.available!=`boolean`||typeof e.removable!=`boolean`||e.state_version!==null&&!Number.isSafeInteger(e.state_version))||e.mutation!==void 0&&(!K(e.mutation)||typeof e.mutation.project_id!=`string`||typeof e.mutation.changed!=`boolean`||typeof e.mutation.note!=`string`))throw Error(`Kai returned unsupported memory-project registry state.`);return{activeProjectId:e.active_project_id,currentWorkspace:e.current_workspace,mutation:e.mutation===void 0?null:{projectId:e.mutation.project_id,changed:e.mutation.changed,note:e.mutation.note},principalId:e.principal_id,projects:e.projects.map(e=>{let t=e;return{available:t.available,current:t.current,displayName:t.display_name,projectId:t.project_id,provenance:t.provenance,removable:t.removable,stateVersion:t.state_version,workspaceRoots:t.workspace_roots}}),revision:e.revision,runtimeProfileId:e.runtime_profile_id}}function zt(e){if(e.context_invalidation===void 0||e.context_invalidation===null)return;let t=e.context_invalidation;if(!K(t)||![`applied`,`pending`,`failed`,`unchanged`].includes(String(t.state))||!Number.isSafeInteger(t.applied)||t.applied<0||!Number.isSafeInteger(t.pending)||t.pending<0)throw Error(`Kai returned unsupported context-invalidation state.`);return{applied:t.applied,pending:t.pending,state:t.state}}function Bt(e){if(!K(e)||e.version!==1||!K(e.document)||typeof e.document.content!=`string`||typeof e.document.revision!=`string`||e.document.updated_at!==null&&typeof e.document.updated_at!=`string`||!Number.isSafeInteger(e.document.size_bytes)||!Number.isSafeInteger(e.document.max_bytes)||typeof e.document.editable!=`boolean`)throw Error(`Kai returned unsupported preference state.`);let t=zt(e);return{...t?{contextInvalidation:t}:{},content:e.document.content,editable:e.document.editable,maxBytes:e.document.max_bytes,revision:e.document.revision,sizeBytes:e.document.size_bytes,updatedAt:e.document.updated_at}}function Vt(e){if(!K(e)||e.version!==1||!K(e.document)||typeof e.document.content!=`string`||typeof e.document.revision!=`string`||!/^[0-9a-f]{64}$/.test(e.document.revision)||!Number.isSafeInteger(e.document.size_bytes)||!Number.isSafeInteger(e.document.max_bytes)||typeof e.document.editable!=`boolean`)throw Error(`Kai returned unsupported principal-policy state.`);let t=zt(e);return{...t?{contextInvalidation:t}:{},content:e.document.content,editable:e.document.editable,maxBytes:e.document.max_bytes,revision:e.document.revision,sizeBytes:e.document.size_bytes}}function Ht(e){if(!K(e)||e.version!==1||!Number.isSafeInteger(e.limit)||!Array.isArray(e.revisions))throw Error(`Kai returned unsupported preference history.`);let t=e.revisions.map(e=>{if(!K(e)||typeof e.revision!=`string`||typeof e.updated_at!=`string`||!Number.isSafeInteger(e.size_bytes))throw Error(`Kai returned unsupported preference history.`);return{revision:e.revision,sizeBytes:e.size_bytes,updatedAt:e.updated_at}});return{limit:e.limit,revisions:t}}function Ut(e){if(!K(e))return null;let t={};for(let[n,r]of Object.entries(e)){if(!Number.isSafeInteger(r)||r<0)return null;t[n]=r}return t}function Wt(e){if(!K(e)||!K(e.scope))return null;let t=Gt(e.scope);return typeof e.memory_id!=`string`||typeof e.kind!=`string`||![`fact`,`episode`].includes(e.kind)||typeof e.source!=`string`||typeof e.memory_type!=`string`||typeof e.preview!=`string`||typeof e.revision!=`string`||!Array.isArray(e.tags)||!e.tags.every(e=>typeof e==`string`)||typeof e.speaker!=`string`||typeof e.confidence!=`number`||typeof e.created_at!=`string`||typeof e.updated_at!=`string`||t===null?null:{confidence:e.confidence,createdAt:e.created_at,kind:e.kind,memoryId:e.memory_id,memoryType:e.memory_type,preview:e.preview,revision:e.revision,scope:t,source:e.source,speaker:e.speaker,tags:e.tags,updatedAt:e.updated_at}}function Gt(e){return!K(e)||typeof e.scope!=`string`||![`global`,`project`,`task`].includes(e.scope)||e.project_id!==null&&typeof e.project_id!=`string`||typeof e.scope_confidence!=`number`||typeof e.scope_source!=`string`||typeof e.legacy_defaulted!=`boolean`||typeof e.invalid_defaulted!=`boolean`||typeof e.retrievable!=`boolean`||e.exclusion_reason!==null&&typeof e.exclusion_reason!=`string`?null:{exclusionReason:e.exclusion_reason,invalidDefaulted:e.invalid_defaulted,legacyDefaulted:e.legacy_defaulted,projectId:e.project_id,retrievable:e.retrievable,scope:e.scope,scopeConfidence:e.scope_confidence,scopeSource:e.scope_source}}async function Kt(e){let t=await X({channelId:``,token:e},`/v1/memory/stats`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load memory statistics.`));if(!K(n)||n.version!==1||!K(n.stats))throw Error(`Kai returned unsupported memory statistics.`);let r=n.stats,i=Ut(r.by_scope),a=Ut(r.by_source),o=Ut(r.by_type),s=Array.isArray(r.allowed_projects)?r.allowed_projects.map(e=>K(e)&&typeof e.project_id==`string`&&typeof e.display_name==`string`?{projectId:e.project_id,displayName:e.display_name}:null):null;if(!Number.isSafeInteger(r.total)||!Number.isSafeInteger(r.facts)||!Number.isSafeInteger(r.episodes)||!Number.isSafeInteger(r.unresolved_conflicts)||!Number.isSafeInteger(r.projection_failures)||!i||!a||!o||!s||s.some(e=>e===null))throw Error(`Kai returned unsupported memory statistics.`);return{allowedProjects:s,byScope:i,bySource:a,byType:o,episodes:r.episodes,facts:r.facts,total:r.total,unresolvedConflicts:r.unresolved_conflicts,projectionFailures:r.projection_failures}}function qt(e){if(!K(e)||typeof e.candidate_id!=`string`||typeof e.state_sha256!=`string`||typeof e.category!=`string`||typeof e.uncertainty!=`string`||typeof e.rationale!=`string`||!K(e.proposed_action)||!K(e.decision)||!Array.isArray(e.evidence))return null;let t=e.decision;if(![`pending`,`approve`,`reject`,`defer`].includes(String(t.disposition))||!K(t.action)||typeof t.operator_note!=`string`||!Number.isSafeInteger(t.state_version))return null;let n=e.evidence.map(e=>!K(e)||typeof e.memory_id!=`string`||![`fact`,`episode`].includes(String(e.kind))||typeof e.text!=`string`||typeof e.scope!=`string`||typeof e.confidence!=`number`||typeof e.migration_classification!=`string`||!Array.isArray(e.migration_gaps)||!e.migration_gaps.every(e=>typeof e==`string`)||[`created_at`,`updated_at`,`project_id`,`source`,`backend`,`provider`,`model`,`prompt_version`,`schema_version`,`valid_from`,`valid_until`,`asserted_at`,`observed_at`,`occurred_from`,`occurred_until`].some(t=>e[t]!==null&&typeof e[t]!=`string`)?null:{assertedAt:e.asserted_at,backend:e.backend,confidence:e.confidence,createdAt:e.created_at,kind:e.kind,memoryId:e.memory_id,migrationClassification:e.migration_classification,migrationGaps:e.migration_gaps,model:e.model,observedAt:e.observed_at,occurredFrom:e.occurred_from,occurredUntil:e.occurred_until,projectId:e.project_id,promptVersion:e.prompt_version,provider:e.provider,schemaVersion:e.schema_version,scope:e.scope,source:e.source,text:e.text,updatedAt:e.updated_at,validFrom:e.valid_from,validUntil:e.valid_until});return n.some(e=>e===null)?null:{candidateId:e.candidate_id,category:e.category,decision:{action:t.action,disposition:t.disposition,operatorNote:t.operator_note,stateVersion:t.state_version},evidence:n,proposedAction:e.proposed_action,rationale:e.rationale,stateSha256:e.state_sha256,uncertainty:e.uncertainty}}function Jt(e){if(!K(e))return null;let t=Ut(e.resolution_counts),n=Ut(e.disposition_counts);if(typeof e.plan_id!=`string`||typeof e.audit_id!=`string`||![`open`,`applied`].includes(String(e.status))||!Number.isSafeInteger(e.review_version)||!Number.isSafeInteger(e.memory_count)||!Number.isSafeInteger(e.group_count)||!Number.isSafeInteger(e.deterministic_groups)||!Number.isSafeInteger(e.pending_deterministic_groups)||!Number.isSafeInteger(e.exception_groups)||!Number.isSafeInteger(e.recommended_groups)||e.applied_at!==null&&typeof e.applied_at!=`string`||!t||!n)return null;for(let e of[`adopt`,`consolidate`,`obsolete`,`needs_review`])if(!Number.isSafeInteger(t[e]))return null;for(let e of[`pending`,`approve`,`reject`,`defer`])if(!Number.isSafeInteger(n[e]))return null;return{appliedAt:e.applied_at,auditId:e.audit_id,deterministicGroups:e.deterministic_groups,pendingDeterministicGroups:e.pending_deterministic_groups,dispositionCounts:n,exceptionGroups:e.exception_groups,groupCount:e.group_count,memoryCount:e.memory_count,planId:e.plan_id,recommendedGroups:e.recommended_groups,resolutionCounts:t,reviewVersion:e.review_version,status:e.status}}function Yt(e){if(!K(e)||typeof e.group_id!=`string`||typeof e.classification!=`string`||![`adopt`,`consolidate`,`obsolete`,`needs_review`].includes(String(e.resolution))||typeof e.deterministic!=`boolean`||typeof e.bulk_eligible!=`boolean`||!K(e.decision)||!K(e.decision.recommendation)||!Array.isArray(e.prior_review_evidence))return null;let t=e.prior_review_evidence.map(e=>!K(e)||typeof e.candidate_id!=`string`||![`approve`,`reject`,`defer`].includes(String(e.disposition))||typeof e.operator_note!=`string`||!Number.isSafeInteger(e.state_version)||!Array.isArray(e.memory_ids)||!e.memory_ids.every(e=>typeof e==`string`)?null:{candidateId:e.candidate_id,disposition:e.disposition,memoryIds:e.memory_ids,operatorNote:e.operator_note,stateVersion:e.state_version});if(t.some(e=>e===null))return null;let n=qt({candidate_id:e.group_id,state_sha256:e.state_sha256,category:e.classification,uncertainty:e.deterministic?`low`:`high`,rationale:e.rationale,proposed_action:e.proposed_action,evidence:e.evidence,decision:e.decision});if(!n)return null;let r=e.missing_fields===void 0?[]:e.missing_fields,i=e.related_group_ids===void 0?[]:e.related_group_ids,a=e.consolidation_id===void 0?null:e.consolidation_id;return!Array.isArray(r)||!r.every(e=>typeof e==`string`)||!Array.isArray(i)||!i.every(e=>typeof e==`string`)||a!==null&&typeof a!=`string`?null:{bulkEligible:e.bulk_eligible,classification:e.classification,consolidationId:a,missingFields:r,relatedGroupIds:i,decision:{...n.decision,recommendation:e.decision.recommendation},deterministic:e.deterministic,evidence:n.evidence,groupId:e.group_id,priorReviewEvidence:t,proposedAction:n.proposedAction,rationale:n.rationale,resolution:e.resolution,stateSha256:n.stateSha256}}async function Xt(e){let t=await X({channelId:``,token:e},`/v1/memory/reconciliation`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load memory triage.`));if(!K(n)||n.version!==1||!(`triage`in n))throw Error(`Kai returned an unsupported memory triage summary.`);if(n.triage===null)return null;let r=Jt(n.triage);if(!r)throw Error(`Kai returned an unsupported memory triage summary.`);return r}async function Zt(e,t,n={}){let r=new URLSearchParams;n.disposition&&r.set(`disposition`,n.disposition),n.resolution&&r.set(`resolution`,n.resolution),n.exceptionsOnly&&r.set(`exceptions_only`,`1`),n.offset!==void 0&&r.set(`offset`,String(n.offset)),n.limit!==void 0&&r.set(`limit`,String(n.limit));let i=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/groups?${r}`),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not load memory triage groups.`));let o=K(a)?Jt(a.triage):null;if(!K(a)||a.version!==1||!o||!Array.isArray(a.groups)||a.next_offset!==null&&!Number.isSafeInteger(a.next_offset))throw Error(`Kai returned an unsupported memory triage page.`);let s=a.groups.map(Yt);if(s.some(e=>e===null))throw Error(`Kai returned an unsupported memory triage group.`);return{triage:o,groups:s,nextOffset:a.next_offset}}async function Qt(e,t,n,r=null){let i=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/safe/preview`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({group_ids:r,expected_review_version:n})}),a=await Y(i),o=K(a)?Ut(a.resolution_counts):null;if(!i.ok)throw Error(J(a,`Could not preview safe memory groups.`));if(!K(a)||a.version!==1||typeof a.plan_id!=`string`||typeof a.preview_sha256!=`string`||!Array.isArray(a.group_ids)||!a.group_ids.every(e=>typeof e==`string`)||!Number.isSafeInteger(a.group_count)||!Number.isSafeInteger(a.memory_count)||!Number.isSafeInteger(a.review_version)||!o)throw Error(`Kai returned an unsupported safe-memory preview.`);return{groupCount:a.group_count,groupIds:a.group_ids,memoryCount:a.memory_count,planId:a.plan_id,previewSha256:a.preview_sha256,resolutionCounts:o,reviewVersion:a.review_version}}async function $t(e,t){let n=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t.planId)}/safe/approve`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({group_ids:t.groupIds,expected_review_version:t.reviewVersion,preview_sha256:t.previewSha256,operator_note:`Approved deterministic legacy-memory triage after preview.`,confirmation:`approve deterministic memory groups`,client_operation_id:Fn()})}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not approve safe memory groups.`))}async function en(e,t,n,r){let i=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/groups/${encodeURIComponent(n)}/decision`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({disposition:r.disposition,action:r.action,operator_note:r.operatorNote,expected_state_version:r.expectedStateVersion,client_operation_id:Fn()})}),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not save memory triage decision.`))}function tn(e){return!K(e)||typeof e.consolidation_id!=`string`||!Number.isSafeInteger(e.revision)||!Array.isArray(e.group_ids)||!e.group_ids.every(e=>typeof e==`string`)||typeof e.content!=`string`||e.scope_kind!==`global`&&e.scope_kind!==`project`||e.scope_key!==null&&typeof e.scope_key!=`string`||typeof e.source_memory_id!=`string`||typeof e.operator_note!=`string`||!Number.isSafeInteger(e.selected_facts)||!Number.isSafeInteger(e.duplicates_excluded)?null:{consolidationId:e.consolidation_id,content:e.content,duplicatesExcluded:e.duplicates_excluded,groupIds:e.group_ids,operatorNote:e.operator_note,revision:e.revision,scopeKey:e.scope_key,scopeKind:e.scope_kind,selectedFacts:e.selected_facts,sourceMemoryId:e.source_memory_id}}async function nn(e,t){let n=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/consolidations`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load consolidations.`));let i=K(r)&&r.version===1&&Array.isArray(r.consolidations)?r.consolidations.map(tn):null;if(!i||i.some(e=>e===null))throw Error(`Kai returned unsupported consolidations.`);return i}async function rn(e,t,n){let r=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/consolidations`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({group_ids:n.groupIds,expected_state_versions:n.expectedStateVersions,canonical:{content:n.canonical.content,source_memory_id:n.canonical.sourceMemoryId,scope_kind:n.canonical.scopeKind,...n.canonical.scopeKind===`project`?{scope_key:n.canonical.scopeKey}:{}},operator_note:n.operatorNote,...n.consolidationId===void 0?{}:{consolidation_id:n.consolidationId,expected_revision:n.expectedRevision},client_operation_id:Fn()})}),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not save the consolidation.`));let a=K(i)&&i.version===1?tn(i.consolidation):null;if(!a)throw Error(`Kai returned an unsupported consolidation.`);return a}async function an(e,t,n,r){let i=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/consolidations/${encodeURIComponent(n)}/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({expected_revision:r,client_operation_id:Fn()})}),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not cancel the consolidation.`))}async function on(e,t){let n=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/recommend`,{method:`POST`}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not analyze uncertain memory groups.`));if(!K(r)||typeof r.recommended!=`number`||!Number.isFinite(r.recommended)||typeof r.remaining!=`number`||!Number.isFinite(r.remaining))throw Error(`Kai returned an unsupported memory triage analysis result.`);return{recommended:r.recommended,remaining:r.remaining}}async function sn(e,t,n){let r=await X({channelId:``,token:e},`/v1/memory/reconciliation/triage/${encodeURIComponent(t)}/apply`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({expected_review_version:n,confirmation:`apply grouped memory triage`,client_operation_id:Fn()})}),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not apply grouped memory triage.`));if(!K(i)||i.version!==1||!K(i.summary))throw Error(`Kai returned an unsupported memory triage receipt.`);return Ut(i.summary)??{}}function cn(e){if(!K(e)||e.version!==1||![`move_scope`,`delete`].includes(String(e.operation))||!Array.isArray(e.results))return null;let t=e.results.map(e=>{if(!K(e)||typeof e.memory_id!=`string`||![`succeeded`,`not_found`,`stale`,`failed`,`awaiting_reconciliation`].includes(String(e.outcome)))return null;let t=e.prior_scope===null?null:Gt(e.prior_scope),n=e.new_scope===null?null:Gt(e.new_scope);return e.prior_scope!==null&&t===null||e.new_scope!==null&&n===null?null:{memoryId:e.memory_id,newScope:n,outcome:e.outcome,priorScope:t}});return t.some(e=>e===null)?null:{operation:e.operation,results:t}}async function ln(e,t,n){let r=await X({channelId:``,token:e},t,n),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not update memories.`));let a=cn(i);if(!a)throw Error(`Kai returned an unsupported memory mutation result.`);return a}async function un(e,t,n){return ln(e,`/v1/memory/records/${encodeURIComponent(t)}/scope`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n.scope===`global`?{scope:`global`}:{scope:`project`,project_id:n.projectId})})}async function dn(e,t,n){return ln(e,`/v1/memory/actions/scope`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n.scope===`global`?{memory_ids:t,scope:`global`}:{memory_ids:t,scope:`project`,project_id:n.projectId})})}async function fn(e,t){return ln(e,`/v1/memory/records/${encodeURIComponent(t)}`,{method:`DELETE`})}async function pn(e,t){return ln(e,`/v1/memory/actions/delete`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({memory_ids:t})})}function mn(e){let t=new URLSearchParams;return e.kind!==void 0&&t.set(`kind`,e.kind),e.lifecycle!==void 0&&t.set(`lifecycle`,e.lifecycle),e.source!==void 0&&t.set(`source`,e.source),e.memoryType!==void 0&&t.set(`memory_type`,e.memoryType),e.tag!==void 0&&t.set(`tag`,e.tag),e.scope!==void 0&&t.set(`scope`,e.scope),e.projectId!==void 0&&t.set(`project_id`,e.projectId),e.limit!==void 0&&t.set(`limit`,String(e.limit)),t}async function hn(e,t={}){let n=mn(t);t.cursor!==void 0&&n.set(`cursor`,t.cursor),t.order!==void 0&&n.set(`order`,t.order);let r=n.size?`?${n}`:``,i=await X({channelId:``,token:e},`/v1/memory/records${r}`),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not load memories.`));if(!K(a)||a.version!==1||!Array.isArray(a.records)||a.next_cursor!==null&&typeof a.next_cursor!=`string`)throw Error(`Kai returned an unsupported memory page.`);let o=a.records.map(Wt);if(o.some(e=>e===null))throw Error(`Kai returned an unsupported memory record.`);return{nextCursor:a.next_cursor,records:o}}async function gn(e,t,n={}){let r=mn(n);r.set(`q`,t);let i=await X({channelId:``,token:e},`/v1/memory/search?${r}`),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not search memories.`));if(!K(a)||a.version!==1||a.active_project_id!==null&&typeof a.active_project_id!=`string`||typeof a.reason!=`string`||!Array.isArray(a.hits))throw Error(`Kai returned unsupported memory search results.`);let o=a.hits.map(e=>{if(!K(e)||typeof e.raw_score!=`number`||typeof e.adjusted_score!=`number`||typeof e.compact_recall!=`string`)return null;let t=Wt(e.record);return t?{adjustedScore:e.adjusted_score,compactRecall:e.compact_recall,rawScore:e.raw_score,record:t}:null});if(o.some(e=>e===null))throw Error(`Kai returned unsupported memory search results.`);return{activeProjectId:a.active_project_id,hits:o,reason:a.reason}}function _n(e){if(e===null)return null;if(K(e)&&!([`goal`,`context`,`approach`,`outcome`,`outcome_quality`].some(t=>typeof e[t]!=`string`)||e.lessons!==void 0&&typeof e.lessons!=`string`||!Array.isArray(e.tags)||!e.tags.every(e=>typeof e==`string`)||!Array.isArray(e.actors)||!e.actors.every(e=>typeof e==`string`)||![`success`,`partial`,`failure`].includes(String(e.outcome_quality))))return{actors:e.actors,approach:e.approach,context:e.context,goal:e.goal,lessons:typeof e.lessons==`string`?e.lessons:null,outcome:e.outcome,outcomeQuality:e.outcome_quality,tags:e.tags}}function vn(e){if(!K(e)||![`canonical`,`legacy`].includes(String(e.authority))||![`fact`,`episode`].includes(String(e.kind))||typeof e.identity!=`string`||typeof e.createdAt!=`string`||typeof e.currentState!=`string`||e.currentRevisionId!==null&&typeof e.currentRevisionId!=`string`||e.runtimeProfileId!==null&&typeof e.runtimeProfileId!=`string`||!K(e.scope)||typeof e.scope.kind!=`string`||e.scope.key!==null&&typeof e.scope.key!=`string`||!Array.isArray(e.revisions)||!Array.isArray(e.events)||!Array.isArray(e.followups))return null;let t=e.revisions.filter(K),n=e.events.filter(K),r=e.followups.filter(K);return t.length!==e.revisions.length||n.length!==e.events.length||r.length!==e.followups.length||t.some(e=>typeof e.revisionId!=`string`||typeof e.content!=`string`||typeof e.reason!=`string`||typeof e.state!=`string`||typeof e.storedAt!=`string`)||n.some(e=>typeof e.eventPosition!=`number`||typeof e.newState!=`string`||typeof e.occurredAt!=`string`||typeof e.reason!=`string`||typeof e.revisionId!=`string`||typeof e.transition!=`string`||e.previousState!==null&&typeof e.previousState!=`string`)||r.some(e=>typeof e.createdAt!=`string`||typeof e.reason!=`string`||typeof e.relationship!=`string`||typeof e.sourceEpisodeId!=`string`||typeof e.targetEpisodeId!=`string`)||e.migrationGaps!==void 0&&(!Array.isArray(e.migrationGaps)||!e.migrationGaps.every(e=>typeof e==`string`))?null:e}function yn(e){if(!K(e))return null;let t=Wt(e),n=_n(e.episode),r=vn(e.lifecycle);return!t||n===void 0||!r||typeof e.content!=`string`||typeof e.compact_recall!=`string`||e.confirmation_quote!==null&&typeof e.confirmation_quote!=`string`||e.prompt_version!==null&&typeof e.prompt_version!=`string`?null:{...t,compactRecall:e.compact_recall,confirmationQuote:e.confirmation_quote,content:e.content,episode:n,lifecycle:r,promptVersion:e.prompt_version}}async function bn(e,t){let n=await X({channelId:``,token:e},`/v1/memory/records/${encodeURIComponent(t)}`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load this memory.`));let i=K(r)&&r.version===1?yn(r.record):null;if(!i)throw Error(`Kai returned an unsupported memory detail.`);return i}function xn(e){return K(e)&&typeof e.kind==`string`&&(e.key===null||typeof e.key==`string`)?{kind:e.kind,key:e.key}:null}function Sn(e){if(!K(e)||typeof e.claim_id!=`string`||typeof e.opened_at!=`string`||!Array.isArray(e.revisions))return null;let t=xn(e.scope),n=e.revisions.map(e=>K(e)&&typeof e.revision_id==`string`&&typeof e.preview==`string`&&typeof e.stored_at==`string`?{preview:e.preview,revisionId:e.revision_id,storedAt:e.stored_at}:null);return!t||n.some(e=>e===null)?null:{claimId:e.claim_id,openedAt:e.opened_at,revisions:n,scope:t}}function Cn(e){if(!K(e)||typeof e.claim_id!=`string`||typeof e.revision_id!=`string`||typeof e.changed_at!=`string`||typeof e.reason!=`string`||typeof e.preview!=`string`||e.state!==`retracted`&&e.state!==`expired`)return null;let t=xn(e.scope);return t?{changedAt:e.changed_at,claimId:e.claim_id,preview:e.preview,reason:e.reason,revisionId:e.revision_id,scope:t,state:e.state}:null}async function wn(e,t,n,r,i){let a=await X({channelId:``,token:e},t),o=await Y(a);if(!a.ok)throw Error(J(o,i));let s=K(o)&&o.version===1&&Array.isArray(o[n])?o[n].map(r):null;if(!s||s.some(e=>e===null)||!K(o)||!Number.isSafeInteger(o.total))throw Error(`Kai returned an unsupported memory review list.`);return{items:s,total:o.total}}async function Tn(e){return wn(e,`/v1/memory/conflicts`,`conflicts`,Sn,`Could not load memory conflicts.`)}async function En(e){return wn(e,`/v1/memory/forgotten`,`facts`,Cn,`Could not load forgotten facts.`)}async function Dn(e,t){let n=await X({channelId:``,token:e},`/v1/memory/conflicts/${encodeURIComponent(t)}`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load this conflict.`));let i=K(r)&&r.version===1?vn(r.lifecycle):null;if(!i)throw Error(`Kai returned an unsupported memory conflict.`);return i}async function On(e,t,n,r){let i=await X({channelId:``,token:e},t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,client_operation_id:Fn()})}),a=await Y(i);if(i.status===409&&K(a)&&K(a.error)&&a.error.code===`memory_conflict_changed`)throw new ie(J(a,`This conflict changed since you opened it.`));if(!i.ok)throw Error(J(a,r));if(!K(a)||a.version!==1||typeof a.claim_id!=`string`||typeof a.active_revision_id!=`string`||typeof a.replayed!=`boolean`||a.memory_id!==null&&typeof a.memory_id!=`string`)throw Error(`Kai returned an unsupported memory review result.`);return{activeRevisionId:a.active_revision_id,claimId:a.claim_id,memoryId:a.memory_id,replayed:a.replayed}}async function kn(e,t,n){return On(e,`/v1/memory/conflicts/${encodeURIComponent(t)}/resolve`,{keep_revision_id:n.keepRevisionId,expected_revision_ids:n.expectedRevisionIds,note:n.note},`Could not resolve this conflict.`)}async function An(e,t,n){return On(e,`/v1/memory/forgotten/${encodeURIComponent(t)}/restore`,{revision_id:n.revisionId,note:n.note},`Could not restore this fact.`)}function jn(e){return!K(e)||e.kind!==`fact`&&e.kind!==`episode`||typeof e.id!=`string`||typeof e.operation!=`string`||!Number.isSafeInteger(e.attempts)||typeof e.updated_at!=`string`||typeof e.preview!=`string`||e.revision_id!==null&&typeof e.revision_id!=`string`||e.error_code!==null&&typeof e.error_code!=`string`?null:{attempts:e.attempts,errorCode:e.error_code,id:e.id,kind:e.kind,operation:e.operation,preview:e.preview,revisionId:e.revision_id,updatedAt:e.updated_at}}async function Mn(e){let t=await X({channelId:``,token:e},`/v1/memory/projections`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load search sync status.`));let r=K(n)&&n.version===1&&Array.isArray(n.failed)?n.failed.map(jn):null;if(!r||r.some(e=>e===null)||!K(n)||!Number.isSafeInteger(n.failed_total)||!Number.isSafeInteger(n.blocked))throw Error(`Kai returned an unsupported search sync status.`);return{blocked:n.blocked,failed:r,failedTotal:n.failed_total}}async function Nn(e){let t=await X({channelId:``,token:e},`/v1/memory/projections/audit`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not check the search index.`));let r=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`);if(!K(n)||n.version!==1||!r(n.orphan)||!r(n.unknown)||!Number.isSafeInteger(n.duplicate)||!r(n.missing))throw Error(`Kai returned an unsupported search index check.`);return{duplicate:n.duplicate,missing:n.missing,orphan:n.orphan,unknown:n.unknown}}async function Pn(e,t={}){let n=await X({channelId:``,token:e},`/v1/memory/projections/retry`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...t.claimIds?{claim_ids:t.claimIds}:{},...t.episodeIds?{episode_ids:t.episodeIds}:{}})}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not retry search sync.`));if(!K(r)||r.version!==1||!Number.isSafeInteger(r.retried)||!Number.isSafeInteger(r.succeeded)||!Number.isSafeInteger(r.failed))throw Error(`Kai returned an unsupported search sync result.`);return{failed:r.failed,retried:r.retried,succeeded:r.succeeded}}function Fn(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`memory-${Date.now()}-${Math.random().toString(16).slice(2)}`}async function In(e,t,n){let r=await X({channelId:``,token:e},t,n),i=await Y(r);if(r.status===409&&K(i)&&K(i.error)&&typeof i.error.current_revision==`string`)throw new ae(J(i,`This memory changed since it was opened.`),i.error.current_revision);if(!r.ok)throw Error(J(i,`Could not save this memory.`));return i}async function Ln(e,t){let n=await In(e,`/v1/memory/records`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({kind:`fact`,content:t.content,tags:t.tags,scope:t.target.scope,...t.target.scope===`project`?{project_id:t.target.projectId}:{},request_id:t.requestId??Fn()})});if(!K(n)||n.version!==1||typeof n.created!=`boolean`)throw Error(`Kai returned an unsupported memory creation result.`);let r=yn(n.record);if(!r)throw Error(`Kai returned an unsupported memory creation result.`);return{created:n.created,record:r}}async function Rn(e,t){let n=t.kind===`fact`?{kind:`fact`,revision:t.revision,request_id:t.requestId??Fn(),content:t.content,tags:t.tags}:{kind:`episode`,revision:t.revision,request_id:t.requestId??Fn(),episode:{goal:t.episode.goal,context:t.episode.context,approach:t.episode.approach,outcome:t.episode.outcome,outcome_quality:t.episode.outcomeQuality,...t.episode.lessons?{lessons:t.episode.lessons}:{},tags:t.episode.tags,actors:t.episode.actors}},r=await In(e,`/v1/memory/records/${encodeURIComponent(t.memoryId)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!K(r)||r.version!==1||!Array.isArray(r.changed_fields)||!r.changed_fields.every(e=>typeof e==`string`)||typeof r.idempotent_replay!=`boolean`)throw Error(`Kai returned an unsupported memory edit result.`);let i=yn(r.record);if(!i)throw Error(`Kai returned an unsupported memory edit result.`);return{changedFields:r.changed_fields,idempotentReplay:r.idempotent_replay,record:i}}function zn(e){return!K(e)||typeof e.message_id!=`string`||typeof e.channel_id!=`string`||!b.test(e.channel_id)||typeof e.author_principal_id!=`string`||!E.test(e.author_principal_id)||typeof e.author_kind!=`string`||typeof e.author_display_name!=`string`||typeof e.body!=`string`||typeof e.created_at!=`string`?null:{authorDisplayName:e.author_display_name,authorKind:e.author_kind,authorPrincipalId:e.author_principal_id,body:e.body,channelId:e.channel_id,createdAt:e.created_at,messageId:e.message_id}}async function Bn(e,t){let n=await X({channelId:``,token:e},`/v1/memory/records/${encodeURIComponent(t)}/source`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load memory source context.`));if(!K(r)||r.version!==1||!K(r.source_context))throw Error(`Kai returned unsupported memory source context.`);let i=r.source_context,a=i.source===null?null:zn(i.source),o=i.result===null?null:zn(i.result);if(typeof i.status!=`string`||![`available`,`unavailable`].includes(i.status)||i.reason!==null&&typeof i.reason!=`string`||i.run_id!==null&&typeof i.run_id!=`string`||i.source!==null&&a===null||i.result!==null&&o===null)throw Error(`Kai returned unsupported memory source context.`);return{reason:i.reason,result:o,runId:i.run_id,source:a,status:i.status}}async function Vn(e){let t=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/settings`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load settings and workspaces.`));return Et(n,e.channelId)}function Hn(e){if(e===null)return null;if(!K(e)||typeof e.run_id!=`string`||typeof e.status!=`string`||![`accepted`,`started`,`completed`,`failed`,`cancelled`].includes(e.status)||typeof e.accepted_at!=`string`||typeof e.started_at!=`string`&&e.started_at!==null||typeof e.terminal_at!=`string`&&e.terminal_at!==null||typeof e.terminal_code!=`string`&&e.terminal_code!==null)throw Error(`Kai returned an unsupported runtime run status.`);return{acceptedAt:e.accepted_at,runId:e.run_id,startedAt:e.started_at,status:e.status,terminalAt:e.terminal_at,terminalCode:e.terminal_code}}async function Un(e,t=null){let n=await X(e,t===null?`/v1/channels/${encodeURIComponent(e.channelId)}/runtime-status`:`/v1/channels/${encodeURIComponent(e.channelId)}/runtime-status?agent_id=${encodeURIComponent(t)}`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load runtime status.`));if(!K(r)||r.version!==1||r.channel_id!==e.channelId||typeof r.agent_id!=`string`||!x.test(r.agent_id)||typeof r.agent_name!=`string`||typeof r.agent_handle!=`string`||typeof r.sponsor_display_name!=`string`||typeof r.can_manage_runtime!=`boolean`||typeof r.backend!=`string`||typeof r.provider!=`string`||!K(r.model)||typeof r.model.value!=`string`||typeof r.model.source!=`string`||!K(r.timeout_seconds)||!Number.isSafeInteger(r.timeout_seconds.value)||typeof r.timeout_seconds.source!=`string`||![`owner`,`neutral`].includes(String(r.workspace_mode))||typeof r.workspace_label!=`string`&&r.workspace_label!==null||typeof r.workspace!=`string`&&r.workspace!==null||typeof r.workspace_revision!=`string`&&r.workspace_revision!==null||!Array.isArray(r.workspaces)||![`alive`,`stopped`,`hidden`].includes(String(r.process_state))||![`not_started`,`active`,`refresh_pending`,`stateless`,`stale`].includes(String(r.provider_session_state))||![`not_started`,`active`,`refresh_pending`,`stale`].includes(String(r.continuity_state))||typeof r.session_created_at!=`string`&&r.session_created_at!==null||typeof r.session_updated_at!=`string`&&r.session_updated_at!==null||!(Number.isSafeInteger(r.fresh_session_generation)||r.fresh_session_generation===null)||typeof r.fresh_session_revision!=`string`&&r.fresh_session_revision!==null||typeof r.fresh_session_revision==`string`&&!/^[0-9a-f]{64}$/.test(r.fresh_session_revision)||!(r.operator_diagnostics===null||K(r.operator_diagnostics)))throw Error(`Kai returned an unsupported runtime lane status.`);let i=r.workspaces.map(e=>{if(!K(e)||typeof e.path!=`string`||typeof e.name!=`string`||typeof e.current!=`boolean`||typeof e.home!=`boolean`)throw Error(`Kai returned unsupported effective workspace choices.`);return{current:e.current,home:e.home,name:e.name,path:e.path}}),a=r.workspace_mode;if(a===`neutral`&&(r.workspace!==null||r.workspace_revision!==null||i.length!==0)||a===`owner`&&(typeof r.workspace!=`string`||typeof r.workspace_revision!=`string`))throw Error(`Kai returned an inconsistent effective workspace.`);let o=r.operator_diagnostics;if(o!==null&&(!K(o)||typeof o.runtime_profile_id!=`string`||!D.test(o.runtime_profile_id)||typeof o.provider_session_revision!=`string`&&o.provider_session_revision!==null||typeof o.provider_session_present!=`boolean`||typeof o.last_run_id!=`string`&&o.last_run_id!==null||!(Number.isSafeInteger(o.context_through_event_position)||o.context_through_event_position===null)))throw Error(`Kai returned unsupported runtime diagnostics.`);return{activeRun:Hn(r.active_run),agentHandle:r.agent_handle,agentId:r.agent_id,agentName:r.agent_name,backend:r.backend,canManageRuntime:r.can_manage_runtime,channelId:r.channel_id,continuityState:r.continuity_state,freshSessionGeneration:r.fresh_session_generation,freshSessionRevision:r.fresh_session_revision,lastRun:Hn(r.last_run),model:{source:r.model.source,value:r.model.value},operatorDiagnostics:o===null?null:{contextThroughEventPosition:o.context_through_event_position,lastRunId:o.last_run_id,providerSessionPresent:o.provider_session_present,providerSessionRevision:o.provider_session_revision,runtimeProfileId:o.runtime_profile_id},processState:r.process_state,provider:r.provider,providerSessionState:r.provider_session_state,sessionCreatedAt:r.session_created_at,sessionUpdatedAt:r.session_updated_at,sponsorDisplayName:r.sponsor_display_name,timeoutSeconds:{source:r.timeout_seconds.source,value:r.timeout_seconds.value},workspaceMode:a,workspaceLabel:r.workspace_label,workspace:r.workspace,workspaceRevision:r.workspace_revision,workspaces:i}}async function Wn(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/runtime-sessions/${encodeURIComponent(t)}/fresh`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_operation_id:n})}),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not start a fresh provider session.`));if(!K(i)||i.version!==1||i.channel_id!==e.channelId||i.agent_id!==t||typeof i.runtime_profile_id!=`string`||!D.test(i.runtime_profile_id)||!Number.isSafeInteger(i.generation)||i.generation<1||typeof i.revision!=`string`||!/^[0-9a-f]{64}$/.test(i.revision)||typeof i.prior_session_present!=`boolean`||typeof i.live_process_stopped!=`boolean`||typeof i.replayed!=`boolean`||!Array.isArray(i.preserved))throw Error(`Kai returned an unsupported fresh provider session result.`);return{agentId:i.agent_id,channelId:i.channel_id,generation:i.generation,liveProcessStopped:i.live_process_stopped,priorSessionPresent:i.prior_session_present,replayed:i.replayed,revision:i.revision,runtimeProfileId:i.runtime_profile_id}}async function Gn(e,t){let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/models?option_id=${encodeURIComponent(t)}`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load the model catalogue.`));return kt(r)}async function Kn(e,t){let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/models`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({option_id:t})}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not refresh the model catalogue.`));return kt(r)}async function qn(e){let t=await X(e,`/v1/settings/model-catalogue/refresh-all`,{method:`POST`}),n=await Y(t);if(!t.ok||!K(n)||n.version!==1||!Number.isSafeInteger(n.contexts)||!K(n.statuses)||Object.values(n.statuses).some(e=>!Number.isSafeInteger(e)))throw Error(J(n,`Could not refresh all model catalogues.`));return{contexts:n.contexts,statuses:n.statuses}}async function Jn(e,t,n,r){let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({option_id:t,model_id:n,display_label:r})}),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not save the operator model.`));return kt(a)}async function Yn(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/models`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({option_id:t,model_id:n})}),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not deactivate the operator model.`));return kt(i)}async function Xn(e){let t=await X(e,`/v1/settings/github`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load GitHub settings.`));return At(n)}async function Zn(e,t,n){let r=n.field===`repository`?{repository:{name:n.name,subscribed:n.subscribed}}:n.field===`repository_reset`?{reset_repositories:!0}:n.field===`toggle`?{toggle:{field:n.name,enabled:n.enabled}}:{token:n.token},i=await X(e,`/v1/settings/github`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,...r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`GitHub settings changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not update GitHub settings.`));return At(a)}function Qn(e){if(!K(e)||typeof e.review_job_id!=`string`||typeof e.repository!=`string`||!Number.isSafeInteger(e.pull_request_number)||![`pending`,`executing`,`succeeded`,`failed`,`cancelled`,`timed_out`].includes(String(e.status))||!Number.isSafeInteger(e.attempt_count)||e.last_error_code!==null&&typeof e.last_error_code!=`string`||typeof e.created_at!=`string`||typeof e.updated_at!=`string`||typeof e.replayed!=`boolean`||e.artifact!==null&&(!K(e.artifact)||typeof e.artifact.artifact_id!=`string`||typeof e.artifact.filename!=`string`||!Number.isSafeInteger(e.artifact.warning_count)||!Array.isArray(e.artifact.warnings)||e.artifact.warnings.some(e=>!K(e)||typeof e.source!=`string`||typeof e.message!=`string`)))throw Error(`Kai returned an unsupported review job.`);let t=e.artifact;return{artifact:t===null?null:{artifactId:t.artifact_id,filename:t.filename,warningCount:t.warning_count,warnings:t.warnings.map(e=>({message:e.message,source:e.source}))},attemptCount:e.attempt_count,createdAt:e.created_at,lastErrorCode:e.last_error_code,pullRequestNumber:e.pull_request_number,repository:e.repository,replayed:e.replayed,reviewJobId:e.review_job_id,status:e.status,updatedAt:e.updated_at}}async function $n(e){let t=await X(e,`/v1/client/reviews?limit=20`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load pull-request reviews.`));if(!K(n)||n.version!==1||!Array.isArray(n.jobs)||!K(n.submission)||!Array.isArray(n.submission.repositories)||n.submission.repositories.some(e=>typeof e!=`string`)||typeof n.submission.active_workspace!=`string`||n.submission.active_workspace_repository!==null&&typeof n.submission.active_workspace_repository!=`string`||n.submission.inferred_repository!==null&&typeof n.submission.inferred_repository!=`string`)throw Error(`Kai returned unsupported pull-request review options.`);return{jobs:n.jobs.map(Qn),submission:{activeWorkspace:n.submission.active_workspace,activeWorkspaceRepository:n.submission.active_workspace_repository,inferredRepository:n.submission.inferred_repository,repositories:n.submission.repositories}}}async function er(e,t,n,r){let i=await X(e,`/v1/client/reviews`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({repository:t,pull_request_number:n,client_operation_id:r})}),a=await Y(i);if(!i.ok||!K(a)||a.version!==1)throw Error(J(a,`Could not start the pull-request review.`));return Qn(a.job)}async function tr(e,t,n,r){let i=await X(e,`/v1/client/reviews/${encodeURIComponent(t)}/${n}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_operation_id:r})}),a=await Y(i);if(!i.ok||!K(a)||a.version!==1)throw Error(J(a,`Could not ${n} the pull-request review.`));return Qn(a.job)}async function nr(e,t){let n=await X(e,`/v1/client/reviews/${encodeURIComponent(t)}/artifact`);if(!n.ok){let e=await Y(n);throw Error(J(e,`Could not open the review artifact.`))}return n.blob()}async function rr(e,t){if(!t.artifact)throw Error(`This review has no artifact.`);let n=await X(e,`/v1/client/reviews/${encodeURIComponent(t.reviewJobId)}/artifact?download=1`);if(!n.ok)throw Error(`Could not download the review artifact.`);let r=URL.createObjectURL(await n.blob()),i=document.createElement(`a`);i.href=r,i.download=t.artifact.filename,i.click(),URL.revokeObjectURL(r)}async function ir(e){let t=await X(e,`/v1/settings/notifications`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load notification preferences.`));return jt(n)}async function ar(e,t,n){let r=n.field===`destination`?{destination_choice_id:n.choiceId,integration_class:n.integrationClass}:{integration_class:n.integrationClass,reset:!0},i=await X(e,`/v1/settings/notifications`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,...r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Notification preferences changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not update notification preferences.`));return jt(a)}async function or(e){let t=await X(e,`/v1/settings/channel-notifications`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load channel notification policy.`));return Mt(n)}async function sr(e,t,n){let r=n.field===`channel`?{channel:{channel_id:n.channelId,level:n.level}}:n.field===`muted_mentions_notify`?{muted_mentions_notify:n.enabled}:n.field===`adapter_delivery`?{adapter_delivery:{transport:n.transport,enabled:n.enabled}}:{do_not_disturb:{enabled:n.enabled,timezone:n.timezone,start:n.start,end:n.end}},i=await X(e,`/v1/settings/channel-notifications`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,...r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Channel notification policy changed since it was loaded.`));if(!i.ok)throw Error(J(a,`Could not update channel notification policy.`));return Mt(a)}async function cr(e){let t=await X(e,`/v1/settings/clients`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load client preferences.`));return Nt(n)}async function lr(e){let t=await X({channelId:``,token:e.token},`/v1/settings/appearance`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load appearance preferences.`));return Pt(n)}async function ur(e,t,n){let r=await X(e,`/v1/settings/appearance`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,theme_id:n})}),i=await Y(r);if(r.status===409)throw new W(J(i,`Appearance preferences changed since they were loaded.`));if(!r.ok)throw Error(J(i,`Could not update appearance preferences.`));return Pt(i)}async function dr(e){let t=await X({channelId:``,token:e.token},`/v1/settings/profile`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load your profile.`));return Ft(n)}async function fr(e){let t=await X({channelId:``,token:e.token},`/v1/settings/profile/avatar`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load your avatar.`));return It(n)}async function pr(e,t,n,r){let i=new FormData;i.append(`expected_state_version`,String(n)),i.append(`client_operation_id`,r),i.append(`file`,t,t.name);let a=await X({channelId:``,token:e.token},`/v1/settings/profile/avatar`,{method:`POST`,body:i}),o=await Y(a);if(a.status===409)throw new W(J(o,`Your avatar changed since it was loaded.`));if(!a.ok)throw Error(J(o,`Could not save your avatar.`));return It(o)}async function mr(e,t,n){let r=await X({channelId:``,token:e.token},`/v1/settings/profile/avatar`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({expected_state_version:t,client_operation_id:n})}),i=await Y(r);if(r.status===409)throw new W(J(i,`Your avatar changed since it was loaded.`));if(!r.ok)throw Error(J(i,`Could not clear your avatar.`));return It(i)}async function hr(e,t,n,r){let i=await X({channelId:``,token:e.token},`/v1/settings/profile`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({display_name:t,expected_state_version:n,client_operation_id:r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Your profile changed since it was loaded.`));if(!i.ok)throw Error(J(a,`Could not update your profile.`));return Ft(a)}async function gr(e,t,n){let r=n.field===`mode`?{mode:n.value}:{voice:n.value},i=await X(e,`/v1/settings/clients`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,binding_choice_id:n.bindingChoiceId,...r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Client preferences changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not update client preferences.`));return Nt(a)}async function _r(e,t,n){let r=n.field===`model`?{model:n.value}:n.field===`backend`?{backend:n.value}:n.field===`timeout`?{timeout_seconds:n.value}:{reset:n.value},i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/settings`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,...r})}),a=await Y(i);if(i.status===409)throw K(a)&&K(a.error)&&a.error.code===`runtime_busy`?Error(J(a,`Finish or stop the active run before switching backends.`)):new W(J(a,`Settings changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not update runtime settings.`));return Et(a,e.channelId)}async function vr(e){let t=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace-config`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load workspace settings.`));return Lt(n)}async function yr(e){let t=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/memory-projects`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load memory projects.`));return Rt(n)}async function br(e,t,n,r){let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/memory-projects`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,name:n,...r?{workspace_path:r}:{}})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Memory projects changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not register memory project.`));return Rt(a)}async function xr(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/memory-projects/${encodeURIComponent(n)}`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t})}),i=await Y(r);if(r.status===409)throw new W(J(i,`Memory projects changed since they were loaded.`));if(!r.ok)throw Error(J(i,`Could not unregister memory project.`));return Rt(i)}async function Sr(e,t,n){let r=n.field===`reset`?{reset:n.value}:{field:n.field,value:n.value},i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace-config`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,...r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Workspace settings changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not update workspace settings.`));return Lt(a)}async function Cr(e,t,n,r){let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace-environment/${encodeURIComponent(n)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t,value:r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Workspace secrets changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not save workspace secret.`));return Lt(a)}async function wr(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace-environment/${encodeURIComponent(n)}`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:t})}),i=await Y(r);if(r.status===409)throw new W(J(i,`Workspace secrets changed since they were loaded.`));if(!r.ok)throw Error(J(i,`Could not remove workspace secret.`));return Lt(i)}async function Tr(e){let t=await X(e,`/v1/preferences`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load preferences.`));return Bt(n)}async function Er(e){let t=await X(e,`/v1/principal-policy`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load principal policy.`));return Vt(n)}async function Dr(e,t,n){let r=await X(e,`/v1/principal-policy`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({content:t,revision:n})}),i=await Y(r);if(r.status===409){let e=K(i)&&K(i.error)&&typeof i.error.current_revision==`string`?i.error.current_revision:``;throw new re(J(i,`Principal policy changed since it was opened.`),e)}if(!r.ok)throw Error(J(i,`Could not save principal policy.`));return Vt(i)}async function Or(e,t,n){let r=await X(e,`/v1/preferences`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({content:t,revision:n})}),i=await Y(r);if(r.status===409){let e=K(i)&&K(i.error)&&typeof i.error.current_revision==`string`?i.error.current_revision:``;throw new ne(J(i,`Preferences changed since they were opened.`),e)}if(!r.ok)throw Error(J(i,`Could not save preferences.`));return Bt(i)}async function kr(e){let t=await X(e,`/v1/preferences/revisions`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load preference history.`));return Ht(n)}async function Ar(e,t,n){let r=await X(e,`/v1/preferences/revisions/${encodeURIComponent(t)}/restore`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({revision:n})}),i=await Y(r);if(r.status===409){let e=K(i)&&K(i.error)&&typeof i.error.current_revision==`string`?i.error.current_revision:``;throw new ne(J(i,`Preferences changed before they could be restored.`),e)}if(!r.ok)throw Error(J(i,`Could not restore preferences.`));return Bt(i)}async function jr(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t,revision:n})}),i=await Y(r);if(r.status===409)throw new W(J(i,`Settings changed since they were loaded.`));if(!r.ok)throw Error(J(i,`Could not switch workspace.`));return Et(i,e.channelId)}async function Mr(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspaces`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t,revision:n})}),i=await Y(r);if(r.status===409)throw new W(J(i,`Settings changed since they were loaded.`));if(!r.ok)throw Error(J(i,`Could not create workspace.`));if(!K(i)||!K(i.creation)||typeof i.creation.path!=`string`||typeof i.creation.directory_created!=`boolean`||typeof i.creation.git_ready!=`boolean`||typeof i.creation.memory_project_registered!=`boolean`||typeof i.creation.memory_project_note!=`string`)throw Error(`Kai returned an unsupported workspace creation result.`);return{directoryCreated:i.creation.directory_created,gitReady:i.creation.git_ready,memoryProjectNote:i.creation.memory_project_note,memoryProjectRegistered:i.creation.memory_project_registered,path:i.creation.path,settings:Et(i,e.channelId)}}async function Nr(e,t,n,r){let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspaces`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t,confirmation:n,revision:r})}),a=await Y(i);if(i.status===409)throw new W(J(a,`Settings changed since they were loaded.`));if(!i.ok)throw Error(J(a,`Could not delete workspace.`));if(!K(a)||!K(a.deletion)||typeof a.deletion.path!=`string`||typeof a.deletion.directory_deleted!=`boolean`||a.deletion.memory_project_unregistered!==null&&typeof a.deletion.memory_project_unregistered!=`string`)throw Error(`Kai returned an unsupported workspace deletion result.`);return{directoryDeleted:a.deletion.directory_deleted,memoryProjectUnregistered:a.deletion.memory_project_unregistered,path:a.deletion.path,settings:Et(a,e.channelId)}}async function Pr(e){let t=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace-grants`),n=await Y(t);if(!t.ok)throw Error(J(n,`Could not load workspace access.`));return Dt(n)}async function Fr(e,t){let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace-grants`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t})}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not add workspace access.`));return Dt(r)}async function Ir(e,t){let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/workspace-grants`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t})}),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not remove workspace access.`));return Dt(r)}async function Lr(e,t,n,r=null,i=null){if(i!==null&&!A.test(i))throw Error(`Invalid thread identity.`);if(r&&i)throw Error(`Thread attachments are not available yet.`);let a=r?(()=>{let e=new FormData;return e.append(`client_message_id`,t),e.append(`body`,n),e.append(`file`,r,r.name),{body:e,method:`POST`}})():{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({body:n,client_message_id:t,...i?{thread_root_id:i}:{}})},o=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/commands`,a),s=await Y(o);if(!o.ok)throw Error(J(s,`Kai could not run this command.`));if(K(s)&&s.version===3&&typeof s.acceptance==`string`&&typeof s.message_id==`string`&&Array.isArray(s.runs)){let t=s.runs.map(t=>ye(t,e.channelId));if(t.some(e=>e===null))throw Error(`Kai returned an unsupported command response.`);return{acceptance:s.acceptance,messageId:s.message_id,runs:t}}if(!K(s)||s.version!==2||typeof s.acceptance!=`string`||typeof s.message_id!=`string`||typeof s.run_id!=`string`||!K(s.run))throw Error(`Kai returned an unsupported command response.`);let c=ye(s.run,e.channelId);if(!c||c.runId!==s.run_id)throw Error(`Kai returned an unsupported command response.`);return{acceptance:s.acceptance,messageId:s.message_id,runs:[c]}}async function Rr(e,t){if(!k.test(t))throw Error(`Invalid artifact identity.`);let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/artifacts/${encodeURIComponent(t)}/content`);if(!n.ok){let e=await Y(n);throw Error(J(e,`Could not load this attachment.`))}return await n.blob()}async function zr(e,t){let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/runs/${encodeURIComponent(t)}`),r=await Y(n),i=K(r)?ye(r.run,e.channelId):null;if(!n.ok||r===null)throw Error(J(r,`Could not inspect this run.`));if(!K(r)||r.version!==1||!i||i.runId!==t)throw Error(`Kai returned an unsupported run response.`);return{...i,routingDecision:Ot(r.routing_decision)}}var Br=new Set([`tool_call`,`tool_result`,`truncated`]);function Vr(e){return!K(e)||typeof e.seq!=`number`||!Number.isSafeInteger(e.seq)||typeof e.kind!=`string`||!Br.has(e.kind)||typeof e.summary!=`string`||typeof e.detail!=`string`||typeof e.is_diff!=`boolean`||typeof e.is_error!=`boolean`||typeof e.created_at!=`string`||e.tool_name!==null&&typeof e.tool_name!=`string`||e.tool_use_id!==null&&typeof e.tool_use_id!=`string`?null:{createdAt:e.created_at,detail:e.detail,isDiff:e.is_diff,isError:e.is_error,kind:e.kind,seq:e.seq,summary:e.summary,toolName:e.tool_name,toolUseId:e.tool_use_id}}async function Hr(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/runs/${encodeURIComponent(t)}/trace?after_seq=${encodeURIComponent(String(n))}`),i=await Y(r);if(!r.ok)throw Error(J(i,`Could not load this run's trace.`));if(!K(i)||i.version!==1||i.run_id!==t||!Array.isArray(i.entries)||!Array.isArray(i.collaboration_activity)||typeof i.has_more!=`boolean`)throw Error(`Kai returned an unsupported trace response.`);let a=[];for(let e of i.entries){let t=Vr(e);if(!t)throw Error(`Kai returned an unsupported trace response.`);a.push(t)}let o=[];for(let e of i.collaboration_activity){if(!K(e)||!Number.isSafeInteger(e.event_position)||e.event_position<1||![`operation`,`revocation`].includes(String(e.kind))||e.operation!==null&&(typeof e.operation!=`string`||!Oe.has(e.operation))||typeof e.outcome!=`string`||e.detail!==null&&typeof e.detail!=`string`||typeof e.occurred_at!=`string`)throw Error(`Kai returned an unsupported trace response.`);o.push({detail:e.detail,eventPosition:e.event_position,kind:e.kind,occurredAt:e.occurred_at,operation:e.operation,outcome:e.outcome})}return{collaborationActivity:o,entries:a,hasMore:i.has_more}}function Ur(e){if(!K(e)||typeof e.kind!=`string`||typeof e.owner_kind!=`string`||e.owner_id!==null&&typeof e.owner_id!=`string`||typeof e.scope!=`string`||typeof e.trust_class!=`string`||typeof e.authority_class!=`string`||typeof e.refresh_class!=`string`||typeof e.delivery_role!=`string`||typeof e.state!=`string`||typeof e.reason!=`string`||e.revision!==null&&typeof e.revision!=`string`||e.history_boundary!==null&&!Number.isSafeInteger(e.history_boundary)||typeof e.delivery_shape!=`string`||!Number.isSafeInteger(e.rendered_bytes)||e.budget_bytes!==null&&!Number.isSafeInteger(e.budget_bytes)||!K(e.inspection))return null;let t=e.inspection;if(typeof t.title!=`string`||typeof t.description!=`string`||typeof t.source_reference!=`string`||t.preview!==null&&typeof t.preview!=`string`||![`exact`,`redacted`,`unavailable`].includes(String(t.preview_state))||t.preview_reason!==null&&typeof t.preview_reason!=`string`||typeof t.editable!=`boolean`||t.edit_target!==null&&![`principal_policy`,`personal_preferences`,`agent_definition`,`workspace_policy`].includes(String(t.edit_target))||t.edit_target_id!==void 0&&t.edit_target_id!==null&&typeof t.edit_target_id!=`string`||t.current_revision!==null&&typeof t.current_revision!=`string`||![`current`,`changed`,`not_checked`].includes(String(t.freshness))||t.change_effect!==null&&![`next_turn`,`provider_session_refresh`].includes(String(t.change_effect)))return null;let n=e.native_instruction_sources??[];if(!Array.isArray(n))return null;let r=n.map(e=>!K(e)||typeof e.scope!=`string`||typeof e.filename!=`string`||typeof e.path_sha256!=`string`||e.content_sha256!==null&&typeof e.content_sha256!=`string`?null:{contentSha256:e.content_sha256,filename:e.filename,pathSha256:e.path_sha256,scope:e.scope});if(r.some(e=>e===null))return null;let i=e.authorization_operations??null;return i!==null&&(!Array.isArray(i)||i.some(e=>typeof e!=`string`))?null:{authorityClass:e.authority_class,authorizationOperations:i,budgetBytes:e.budget_bytes,deliveryRole:e.delivery_role,deliveryShape:e.delivery_shape,historyBoundary:e.history_boundary,inspection:{changeEffect:t.change_effect,currentRevision:t.current_revision,description:t.description,editable:t.editable,editTarget:t.edit_target,editTargetId:t.edit_target_id??null,freshness:t.freshness,preview:t.preview,previewReason:t.preview_reason,previewState:t.preview_state,sourceReference:t.source_reference,title:t.title},kind:e.kind,nativeInstructionSources:r,ownerId:e.owner_id,ownerKind:e.owner_kind,reason:e.reason,refreshClass:e.refresh_class,renderedBytes:e.rendered_bytes,revision:e.revision,scope:e.scope,state:e.state,trustClass:e.trust_class}}async function Wr(e,t){let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/runs/${encodeURIComponent(t)}/context-manifests`),r=await Y(n);if(!n.ok)throw Error(J(r,`Could not load this run's context stack.`));if(!K(r)||r.version!==1||r.channel_id!==e.channelId||r.run_id!==t||!Array.isArray(r.manifests))throw Error(`Kai returned an unsupported context stack.`);let i=r.manifests.map(n=>{if(!K(n)||typeof n.attempt_id!=`string`||n.run_id!==t||n.channel_id!==e.channelId||typeof n.agent_id!=`string`||typeof n.runtime_profile_id!=`string`||typeof n.backend!=`string`||n.provider!==null&&typeof n.provider!=`string`||typeof n.model!=`string`||typeof n.workspace_kind!=`string`||n.workspace_digest!==null&&typeof n.workspace_digest!=`string`||n.provider_session_revision!==null&&typeof n.provider_session_revision!=`string`||typeof n.manifest_sha256!=`string`||typeof n.created_at!=`string`||!Array.isArray(n.sources))return null;let r=n.sources.map(Ur);return r.some(e=>e===null)?null:{agentId:n.agent_id,attemptId:n.attempt_id,backend:n.backend,channelId:n.channel_id,createdAt:n.created_at,manifestSha256:n.manifest_sha256,model:n.model,provider:n.provider,providerSessionRevision:n.provider_session_revision,runId:t,runtimeProfileId:n.runtime_profile_id,sources:r,workspaceDigest:n.workspace_digest,workspaceKind:n.workspace_kind}});if(i.some(e=>e===null))throw Error(`Kai returned an unsupported context stack.`);return{channelId:e.channelId,manifests:i,runId:t}}async function Gr(e,t){let n=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/runs/${encodeURIComponent(t)}/cancel`,{method:`POST`}),r=await Y(n),i=K(r)?ye(r.run,e.channelId):null;if(!n.ok)throw Error(J(r,`Could not stop this run.`));if(!K(r)||r.version!==1||!i||i.runId!==t)throw Error(`Kai returned an unsupported cancellation response.`);return i}function Kr(e){if(!K(e))return null;let{channel_name:t,created_at:n,created_event_position:r,kind:i,last_event_position:a,notification_id:o,read:s,read_at:c,source_author_display_name:l,source_author_avatar:u,source_author_principal_id:d,source_channel_id:f,source_message_id:p,source_thread_root_id:m,state_version:h}=e;return t!==null&&typeof t!=`string`||typeof n!=`string`||!Number.isSafeInteger(r)||i!==`mention`&&i!==`reply`&&i!==`message`||!Number.isSafeInteger(a)||typeof o!=`string`||!j.test(o)||typeof s!=`boolean`||c!==null&&typeof c!=`string`||typeof l!=`string`||typeof d!=`string`||!E.test(d)||typeof f!=`string`||!b.test(f)||typeof p!=`string`||!A.test(p)||m!==null&&(typeof m!=`string`||!A.test(m))||!Number.isSafeInteger(h)||h<0?null:{channelName:t,createdAt:n,createdEventPosition:r,kind:i,lastEventPosition:a,notificationId:o,read:s,readAt:c,sourceAuthorDisplayName:l,sourceAuthorAvatar:de(u,d),sourceAuthorPrincipalId:d,sourceChannelId:f,sourceMessageId:p,sourceThreadRootId:m,stateVersion:h}}function qr(e){if(!K(e)||!Number.isSafeInteger(e.total)||!Number.isSafeInteger(e.unread)||!Number.isSafeInteger(e.read)||e.total<0||e.unread<0||e.read<0||e.total!==e.unread+e.read||!K(e.unread_by_channel))return null;let t={},n=0;for(let[r,i]of Object.entries(e.unread_by_channel)){if(!b.test(r)||!Number.isSafeInteger(i)||i<1)return null;t[r]=i,n+=i}return n===e.unread?{read:e.read,total:e.total,unread:e.unread,unreadByChannel:t}:null}function Jr(e){if(!K(e)||e.version!==1||!Array.isArray(e.notifications)||!Number.isSafeInteger(e.through_position)||e.through_position<0||e.next_cursor!==null&&typeof e.next_cursor!=`string`)throw Error(`Kai returned an unsupported Mentions inbox.`);let t=qr(e.counts),n=e.notifications.map(Kr);if(!t||n.some(e=>e===null))throw Error(`Kai returned an unsupported Mentions inbox.`);return{counts:t,nextCursor:e.next_cursor,notifications:n,throughPosition:e.through_position}}async function Yr(e,t={},n){let r=new URLSearchParams;t.cursor&&r.set(`cursor`,t.cursor),t.kind&&r.set(`kind`,t.kind),r.set(`limit`,String(t.limit??50)),t.unreadOnly&&r.set(`unread`,`1`);let i=await X({channelId:``,token:e},`/v1/client/notifications?${r}`,{signal:n}),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not load mentions.`));return Jr(a)}async function Xr(e,t={},n){let r=new URLSearchParams;t.kind&&r.set(`kind`,t.kind);let i=r.size>0?`?${r}`:``,a=await X({channelId:``,token:e},`/v1/client/notifications/counts${i}`,{signal:n}),o=await Y(a);if(!a.ok||!K(o)||o.version!==1)throw Error(J(o,`Could not load mention counts.`));let s=qr(o);if(!s)throw Error(`Kai returned unsupported mention counts.`);return s}async function Zr(e,t,n,r,i){if(!j.test(t))throw Error(`Invalid notification identity.`);let a=await X({channelId:``,token:e},`/v1/client/notifications/${encodeURIComponent(t)}/${r?`read`:`unread`}`,{body:JSON.stringify({client_operation_id:i,expected_state_version:n}),headers:{"Content-Type":`application/json`},method:`POST`}),o=await Y(a),s=K(o)?Kr(o.notification):null;if(!a.ok||!K(o)||o.version!==1||!s||typeof o.changed!=`boolean`||typeof o.replayed!=`boolean`)throw Error(J(o,`Could not update this mention.`));return{changed:o.changed,notification:s,replayed:o.replayed}}function Qr(e,t,n,r){return Zr(e,t,n,!0,r)}function $r(e,t,n,r){return Zr(e,t,n,!1,r)}async function ei(e,t,n){let r=await X({channelId:``,token:e},`/v1/client/notifications/read`,{body:JSON.stringify({client_operation_id:n,notifications:t.map(e=>({expected_state_version:e.expectedStateVersion,notification_id:e.notificationId}))}),headers:{"Content-Type":`application/json`},method:`POST`}),i=await Y(r);if(!r.ok||!K(i)||i.version!==1||!Array.isArray(i.notifications))throw Error(J(i,`Could not mark mentions read.`));return i.notifications.map(e=>{if(!K(e))throw Error(`Kai returned an unsupported mention mutation.`);let t=Kr(e.notification);if(!t||typeof e.changed!=`boolean`||typeof e.replayed!=`boolean`)throw Error(`Kai returned an unsupported mention mutation.`);return{changed:e.changed,notification:t,replayed:e.replayed}})}function ti(e){if(!K(e))return null;let{archived:t,channel_id:n,channel_kind:r,channel_name:i,first_unread_event_position:a,first_unread_message_id:o,last_event_position:s,membership_baseline_event_position:c,read_through_event_position:l,read_through_message_id:u,state_version:d,unread_count:f,unread_count_capped:p,unread_reply_count:m,unread_reply_count_capped:h,unread_thread_count:g,first_unread_thread_root_id:_,first_unread_thread_reply_id:v,first_unread_thread_event_position:y}=e;return typeof t!=`boolean`||typeof n!=`string`||!b.test(n)||r!==`direct`&&r!==`group`&&r!==`notification`||i!==null&&typeof i!=`string`||a!==null&&(!Number.isSafeInteger(a)||a<0)||o!==null&&(typeof o!=`string`||!A.test(o))||!Number.isSafeInteger(s)||s<0||!Number.isSafeInteger(c)||c<0||!Number.isSafeInteger(l)||l<0||u!==null&&(typeof u!=`string`||!A.test(u))||!Number.isSafeInteger(d)||d<0||!Number.isSafeInteger(f)||f<0||typeof p!=`boolean`||!Number.isSafeInteger(m)||m<0||typeof h!=`boolean`||!Number.isSafeInteger(g)||g<0||_!==null&&(typeof _!=`string`||!A.test(_))||v!==null&&(typeof v!=`string`||!A.test(v))||y!==null&&(!Number.isSafeInteger(y)||y<0)||_===null!=(v===null)||v===null!=(y===null)||m===0!=(v===null)||o===null!=(a===null)||f===0!=(o===null)?null:{archived:t,channelId:n,channelKind:r,channelName:i,firstUnreadEventPosition:a,firstUnreadMessageId:o,lastEventPosition:s,membershipBaselineEventPosition:c,readThroughEventPosition:l,readThroughMessageId:u,stateVersion:d,unreadCount:f,unreadCountCapped:p,unreadReplyCount:m,unreadReplyCountCapped:h,unreadThreadCount:g,firstUnreadThreadRootId:_,firstUnreadThreadReplyId:v,firstUnreadThreadEventPosition:y}}function ni(e){if(!K(e))return null;let{channel_id:t,thread_root_id:n,followed:r,follow_baseline_event_position:i,read_through_event_position:a,read_through_message_id:o,state_version:s,last_event_position:c,unread_count:l,unread_count_capped:u,first_unread_message_id:d,first_unread_event_position:f}=e;return typeof t!=`string`||!b.test(t)||typeof n!=`string`||!A.test(n)||typeof r!=`boolean`||!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(a)||a<0||o!==null&&(typeof o!=`string`||!A.test(o))||!Number.isSafeInteger(s)||s<0||!Number.isSafeInteger(c)||c<0||!Number.isSafeInteger(l)||l<0||typeof u!=`boolean`||d!==null&&(typeof d!=`string`||!A.test(d))||f!==null&&(!Number.isSafeInteger(f)||f<0)||d===null!=(f===null)||l===0!=(d===null)?null:{channelId:t,threadRootId:n,followed:r,followBaselineEventPosition:i,readThroughEventPosition:a,readThroughMessageId:o,stateVersion:s,lastEventPosition:c,unreadCount:l,unreadCountCapped:u,firstUnreadMessageId:d,firstUnreadEventPosition:f}}function ri(e){if(!K(e))return null;let t=ni(e.state),{channel_name:n,channel_archived:r,root_author_display_name:i,root_excerpt:a,root_created_at:o,latest_reply_message_id:s,latest_reply_author_display_name:c,latest_reply_excerpt:l,latest_reply_created_at:u}=e;return!t||!t.followed||n!==null&&typeof n!=`string`||typeof r!=`boolean`||typeof i!=`string`||typeof a!=`string`||a.length>280||typeof o!=`string`||s!==null&&(typeof s!=`string`||!A.test(s))||c!==null&&typeof c!=`string`||l!==null&&(typeof l!=`string`||l.length>280)||u!==null&&typeof u!=`string`||s===null!=(c===null)||s===null!=(l===null)||s===null!=(u===null)?null:{state:t,channelName:n,channelArchived:r,rootAuthorDisplayName:i,rootExcerpt:a,rootCreatedAt:o,latestReplyMessageId:s,latestReplyAuthorDisplayName:c,latestReplyExcerpt:l,latestReplyCreatedAt:u}}async function ii(e,t){let n=await X({channelId:``,token:e},`/v1/client/followed-threads`,{signal:t}),r=await Y(n),i=K(r)&&Array.isArray(r.threads)?r.threads.map(ri):[];if(!n.ok||!K(r)||r.version!==1||!Array.isArray(r.threads)||i.some(e=>e===null)||!Number.isSafeInteger(r.through_position)||r.through_position<0)throw Error(J(r,`Could not load followed threads.`));return{threads:i,throughPosition:r.through_position}}async function ai(e,t,n){let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/threads/${encodeURIComponent(t)}/unread`,{signal:n}),i=await Y(r);if(r.status===404)throw new V(`This thread is no longer accessible.`);let a=K(i)?ni(i.state):null;if(!r.ok||!K(i)||i.version!==1||!a)throw Error(J(i,`Could not load thread unread state.`));return a}async function oi(e,t,n,r,i,a){let o={client_operation_id:i,expected_state_version:r};a!==void 0&&(o.message_id=a);let s=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/threads/${encodeURIComponent(t)}/${n}`,{body:JSON.stringify(o),headers:{"Content-Type":`application/json`},method:`POST`}),c=await Y(s);if(s.status===404)throw new V(`This thread is no longer accessible.`);if(s.status===409)throw new te(J(c,`Thread state changed in another tab.`));let l=K(c)?ni(c.state):null;if(!s.ok||!K(c)||c.version!==1||!l||typeof c.replayed!=`boolean`)throw Error(J(c,`Could not update thread unread state.`));return{replayed:c.replayed,state:l}}function si(e,t,n,r,i){return oi(e,t,n?`follow`:`unfollow`,r,i)}function ci(e,t,n,r,i){return oi(e,t,`read-position`,r,i,n)}async function li(e,t){let n=await X({channelId:``,token:e},`/v1/client/unread`,{signal:t}),r=await Y(n);if(!n.ok||!K(r)||r.version!==1||!Array.isArray(r.channels)||!Number.isSafeInteger(r.total_unread)||r.total_unread<0||typeof r.total_unread_capped!=`boolean`||!Number.isSafeInteger(r.through_position)||r.through_position<0)throw Error(J(r,`Could not load unread messages.`));let i=r.channels.map(ti);if(i.some(e=>e===null))throw Error(`Kai returned unsupported unread state.`);return{channels:i,throughPosition:r.through_position,totalUnread:r.total_unread,totalUnreadCapped:r.total_unread_capped}}async function ui(e,t,n,r){if(!A.test(t))throw Error(`Invalid message identity.`);let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/read-position`,{body:JSON.stringify({client_operation_id:r,expected_state_version:n,message_id:t}),headers:{"Content-Type":`application/json`},method:`POST`}),a=await Y(i);if(i.status===404)throw new V(`This session can no longer access that Workshop channel.`);if(i.status===409)throw new H(J(a,`Unread state changed in another tab.`));let o=K(a)?ti(a.state):null;if(!i.ok||!K(a)||a.version!==1||!o||typeof a.replayed!=`boolean`)throw Error(J(a,`Could not update unread messages.`));return{replayed:a.replayed,state:o}}async function di(e,t,n){if(!A.test(t))throw Error(`Invalid message identity.`);let r=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/messages/${encodeURIComponent(t)}`,{signal:n}),i=await Y(r),a=K(i)?ge(i.message,e.channelId):null;if(!r.ok||!K(i)||i.version!==1||!a)throw Error(J(i,`Could not open the source message.`));return a}function fi(e,t){if(!K(e)||e.version!==1||e.channel_id!==t||!Array.isArray(e.messages)||!Number.isSafeInteger(e.through_position))throw Error(`Kai returned an unsupported timeline response.`);let n=[];for(let r of e.messages){let e=ge(r,t);if(!e)throw Error(`Kai returned an unsupported timeline message.`);n.push(e)}return{messages:n,nextCursor:typeof e.next_cursor==`string`?e.next_cursor:null,throughPosition:e.through_position,previousCursor:typeof e.previous_cursor==`string`?e.previous_cursor:null}}async function pi(e,t,n=null){let r=new URLSearchParams({limit:`100`});if(n!==null){if(!A.test(n))throw Error(`Invalid unread message identity.`);r.set(`start_message_id`,n)}else r.set(`tail`,`1`);let i=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/timeline?${r}`,{signal:t}),a=await Y(i);if(!i.ok)throw Error(J(a,`Could not load this channel.`));return fi(a,e.channelId)}async function mi(e,t,n,r){let i=new URLSearchParams({cursor:t,limit:`100`}),a=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/timeline?${i}`,{signal:r}),o=await Y(a);if(!a.ok)throw Error(J(o,`Could not load earlier messages.`));let s=fi(o,e.channelId);if(s.throughPosition!==n)throw Error(`The timeline snapshot changed while it was loading.`);return s}async function hi(e,t,n=null,r){if(!A.test(t))throw Error(`Invalid thread identity.`);let i=new URLSearchParams({limit:`100`});n&&i.set(`cursor`,n);let a=await X(e,`/v1/channels/${encodeURIComponent(e.channelId)}/threads/${encodeURIComponent(t)}?${i}`,{signal:r}),o=await Y(a);if(!a.ok||!K(o)||o.version!==1||o.channel_id!==e.channelId||o.thread_root_id!==t||!Array.isArray(o.messages)||!Number.isSafeInteger(o.through_position))throw Error(J(o,`Could not load this thread.`));let s=ge(o.root,e.channelId),c=o.messages.map(t=>ge(t,e.channelId));if(!s||c.some(e=>e===null))throw Error(`Kai returned an unsupported thread response.`);return{root:s,messages:c,nextCursor:typeof o.next_cursor==`string`?o.next_cursor:null,throughPosition:o.through_position}}var gi=class{buffer=``;push(e){this.buffer+=e;let t=[],n=this.buffer.indexOf(` `);for(;n!==-1;){let e=this.parseBlock(this.buffer.slice(0,n));this.buffer=this.buffer.slice(n+2),e&&t.push(e),n=this.buffer.indexOf(` @@ -42,4 +42,4 @@ Error generating stack: `+e.message+` `))+1))}let o=`#`.repeat(i),s=n.enter(`headingAtx`),c=n.enter(`phrasing`);a.move(o+` `);let l=n.containerPhrasing(e,{before:`# `,after:` `,...a.current()});return/^[\t ]/.test(l)&&(l=Lf(l.charCodeAt(0))+l.slice(1)),l=l?o+` `+l:o,n.options.closeAtx&&(l+=` `+o),c(),s(),l}Uf.peek=Wf;function Uf(e){return e.value||``}function Wf(){return`<`}Gf.peek=Kf;function Gf(e,t,n,r){let i=Pf(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.enter(`image`),s=n.enter(`label`),c=n.createTracker(r),l=c.move(`![`);return l+=c.move(n.safe(e.alt,{before:l,after:`]`,...c.current()})),l+=c.move(`](`),s(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(s=n.enter(`destinationLiteral`),l+=c.move(`<`),l+=c.move(n.safe(e.url,{before:l,after:`>`,...c.current()})),l+=c.move(`>`)):(s=n.enter(`destinationRaw`),l+=c.move(n.safe(e.url,{before:l,after:e.title?` `:`)`,...c.current()}))),s(),e.title&&(s=n.enter(`title${a}`),l+=c.move(` `+i),l+=c.move(n.safe(e.title,{before:l,after:i,...c.current()})),l+=c.move(i),s()),l+=c.move(`)`),o(),l}function Kf(){return`!`}qf.peek=Jf;function qf(e,t,n,r){let i=e.referenceType,a=n.enter(`imageReference`),o=n.enter(`label`),s=n.createTracker(r),c=s.move(`![`),l=n.safe(e.alt,{before:c,after:`]`,...s.current()});c+=s.move(l+`][`),o();let u=n.stack;n.stack=[],o=n.enter(`reference`);let d=n.safe(n.associationId(e),{before:c,after:`]`,...s.current()});return o(),n.stack=u,a(),i===`full`||!l||l!==d?c+=s.move(d+`]`):i===`shortcut`?c=c.slice(0,-1):c+=s.move(`]`),c}function Jf(){return`!`}Yf.peek=Xf;function Yf(e,t,n){let r=e.value||``,i="`",a=-1;for(;RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=` `+r+` `);++a\u007F]/.test(e.url))}Qf.peek=$f;function Qf(e,t,n,r){let i=Pf(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.createTracker(r),s,c;if(Zf(e,n)){let t=n.stack;n.stack=[],s=n.enter(`autolink`);let r=o.move(`<`);return r+=o.move(n.containerPhrasing(e,{before:r,after:`>`,...o.current()})),r+=o.move(`>`),s(),n.stack=t,r}s=n.enter(`link`),c=n.enter(`label`);let l=o.move(`[`);return l+=o.move(n.containerPhrasing(e,{before:l,after:`](`,...o.current()})),l+=o.move(`](`),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter(`destinationLiteral`),l+=o.move(`<`),l+=o.move(n.safe(e.url,{before:l,after:`>`,...o.current()})),l+=o.move(`>`)):(c=n.enter(`destinationRaw`),l+=o.move(n.safe(e.url,{before:l,after:e.title?` `:`)`,...o.current()}))),c(),e.title&&(c=n.enter(`title${a}`),l+=o.move(` `+i),l+=o.move(n.safe(e.title,{before:l,after:i,...o.current()})),l+=o.move(i),c()),l+=o.move(`)`),s(),l}function $f(e,t,n){return Zf(e,n)?`<`:`[`}ep.peek=tp;function ep(e,t,n,r){let i=e.referenceType,a=n.enter(`linkReference`),o=n.enter(`label`),s=n.createTracker(r),c=s.move(`[`),l=n.containerPhrasing(e,{before:c,after:`]`,...s.current()});c+=s.move(l+`][`),o();let u=n.stack;n.stack=[],o=n.enter(`reference`);let d=n.safe(n.associationId(e),{before:c,after:`]`,...s.current()});return o(),n.stack=u,a(),i===`full`||!l||l!==d?c+=s.move(d+`]`):i===`shortcut`?c=c.slice(0,-1):c+=s.move(`]`),c}function tp(){return`[`}function np(e){let t=e.options.bullet||`*`;if(t!==`*`&&t!==`+`&&t!==`-`)throw Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function rp(e){let t=np(e),n=e.options.bulletOther;if(!n)return t===`*`?`-`:`*`;if(n!==`*`&&n!==`+`&&n!==`-`)throw Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function ip(e){let t=e.options.bulletOrdered||`.`;if(t!==`.`&&t!==`)`)throw Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function ap(e){let t=e.options.rule||`*`;if(t!==`*`&&t!==`-`&&t!==`_`)throw Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function op(e,t,n,r){let i=n.enter(`list`),a=n.bulletCurrent,o=e.ordered?ip(n):np(n),s=e.ordered?o===`.`?`)`:`.`:rp(n),c=t&&n.bulletLastUsed?o===n.bulletLastUsed:!1;if(!e.ordered){let t=e.children?e.children[0]:void 0;if((o===`*`||o===`-`)&&t&&(!t.children||!t.children[0])&&n.stack[n.stack.length-1]===`list`&&n.stack[n.stack.length-2]===`listItem`&&n.stack[n.stack.length-3]===`list`&&n.stack[n.stack.length-4]===`listItem`&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(c=!0),ap(n)===o&&t){let t=-1;for(;++t-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+a);let o=a.length+1;(i===`tab`||i===`mixed`&&(t&&t.type===`list`&&t.spread||e.spread))&&(o=Math.ceil(o/4)*4);let s=n.createTracker(r);s.move(a+` `.repeat(o-a.length)),s.shift(o);let c=n.enter(`listItem`),l=n.indentLines(n.containerFlow(e,s.current()),u);return c(),l;function u(e,t,n){return t?(n?``:` `.repeat(o))+e:(n?a:a+` `.repeat(o-a.length))+e}}function lp(e,t,n,r){let i=n.enter(`paragraph`),a=n.enter(`phrasing`),o=n.containerPhrasing(e,r);return a(),i(),o}var up=gu([`break`,`delete`,`emphasis`,`footnote`,`footnoteReference`,`image`,`imageReference`,`inlineCode`,`inlineMath`,`link`,`linkReference`,`mdxJsxTextElement`,`mdxTextExpression`,`strong`,`text`,`textDirective`]);function dp(e,t,n,r){return(e.children.some(function(e){return up(e)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function fp(e){let t=e.options.strong||`*`;if(t!==`*`&&t!==`_`)throw Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}pp.peek=mp;function pp(e,t,n,r){let i=fp(n),a=n.enter(`strong`),o=n.createTracker(r),s=o.move(i+i),c=o.move(n.containerPhrasing(e,{after:i,before:s,...o.current()})),l=c.charCodeAt(0),u=Rf(r.before.charCodeAt(r.before.length-1),l,i);u.inside&&(c=Lf(l)+c.slice(1));let d=c.charCodeAt(c.length-1),f=Rf(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+Lf(d));let p=o.move(i+i);return a(),n.attentionEncodeSurroundingInfo={after:f.outside,before:u.outside},s+c+p}function mp(e,t,n){return n.options.strong||`*`}function hp(e,t,n,r){return n.safe(e.value,r)}function gp(e){let t=e.options.ruleRepetition||3;if(t<3)throw Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function _p(e,t,n){let r=(ap(n)+(n.options.ruleSpaces?` `:``)).repeat(gp(n));return n.options.ruleSpaces?r.slice(0,-1):r}var vp={blockquote:wf,break:Of,code:Mf,definition:Ff,emphasis:zf,hardBreak:Of,heading:Hf,html:Uf,image:Gf,imageReference:qf,inlineCode:Yf,link:Qf,linkReference:ep,list:op,listItem:cp,paragraph:lp,root:dp,strong:pp,text:hp,thematicBreak:_p};function yp(){return{enter:{table:bp,tableData:wp,tableHeader:wp,tableRow:Sp},exit:{codeText:Tp,table:xp,tableData:Cp,tableHeader:Cp,tableRow:Cp}}}function bp(e){let t=e._align;this.enter({type:`table`,align:t.map(function(e){return e===`none`?null:e}),children:[]},e),this.data.inTable=!0}function xp(e){this.exit(e),this.data.inTable=void 0}function Sp(e){this.enter({type:`tableRow`,children:[]},e)}function Cp(e){this.exit(e)}function wp(e){this.enter({type:`tableCell`,children:[]},e)}function Tp(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,Ep));let n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function Ep(e,t){return t===`|`?t:e}function Dp(e){let t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,i=t.stringLength,a=n?` `:`|`;return{unsafe:[{character:`\r`,inConstruct:`tableCell`},{character:` `,inConstruct:`tableCell`},{atBreak:!0,character:`|`,after:`[ :-]`},{character:`|`,inConstruct:`tableCell`},{atBreak:!0,character:`:`,after:`-`},{atBreak:!0,character:`-`,after:`[:|-]`}],handlers:{inlineCode:f,table:o,tableCell:c,tableRow:s}};function o(e,t,n,r){return l(u(e,n,r),e.align)}function s(e,t,n,r){let i=l([d(e,n,r)]);return i.slice(0,i.indexOf(` -`))}function c(e,t,n,r){let i=n.enter(`tableCell`),o=n.enter(`phrasing`),s=n.containerPhrasing(e,{...r,before:a,after:a});return o(),i(),s}function l(e,t){return xf(e,{align:t,alignDelimiters:r,padding:n,stringLength:i})}function u(e,t,n){let r=e.children,i=-1,a=[],o=t.enter(`table`);for(;++i0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}var am={tokenize:pm,partial:!0};function om(){return{document:{91:{name:`gfmFootnoteDefinition`,tokenize:um,continuation:{tokenize:dm},exit:fm}},text:{91:{name:`gfmFootnoteCall`,tokenize:lm},93:{name:`gfmPotentialFootnoteCall`,add:`after`,tokenize:sm,resolveTo:cm}}}}function sm(e,t,n){let r=this,i=r.events.length,a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),o;for(;i--;){let e=r.events[i][1];if(e.type===`labelImage`){o=e;break}if(e.type===`gfmFootnoteCall`||e.type===`labelLink`||e.type===`label`||e.type===`image`||e.type===`link`)break}return s;function s(i){if(!o||!o._balanced)return n(i);let s=Fo(r.sliceSerialize({start:o.end,end:r.now()}));return s.codePointAt(0)!==94||!a.includes(s.slice(1))?n(i):(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(i),e.exit(`gfmFootnoteCallLabelMarker`),t(i))}}function cm(e,t){let n=e.length;for(;n--;)if(e[n][1].type===`labelImage`&&e[n][0]===`enter`){e[n][1];break}e[n+1][1].type=`data`,e[n+3][1].type=`gfmFootnoteCallLabelMarker`;let r={type:`gfmFootnoteCall`,start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:`gfmFootnoteCallMarker`,start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;let a={type:`gfmFootnoteCallString`,start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},o={type:`chunkString`,contentType:`string`,start:Object.assign({},a.start),end:Object.assign({},a.end)},s=[e[n+1],e[n+2],[`enter`,r,t],e[n+3],e[n+4],[`enter`,i,t],[`exit`,i,t],[`enter`,a,t],[`enter`,o,t],[`exit`,o,t],[`exit`,a,t],e[e.length-2],e[e.length-1],[`exit`,r,t]];return e.splice(n,e.length-n+1,...s),e}function lm(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a=0,o;return s;function s(t){return e.enter(`gfmFootnoteCall`),e.enter(`gfmFootnoteCallLabelMarker`),e.consume(t),e.exit(`gfmFootnoteCallLabelMarker`),c}function c(t){return t===94?(e.enter(`gfmFootnoteCallMarker`),e.consume(t),e.exit(`gfmFootnoteCallMarker`),e.enter(`gfmFootnoteCallString`),e.enter(`chunkString`).contentType=`string`,l):n(t)}function l(s){if(a>999||s===93&&!o||s===null||s===91||Wo(s))return n(s);if(s===93){e.exit(`chunkString`);let a=e.exit(`gfmFootnoteCallString`);return i.includes(Fo(r.sliceSerialize(a)))?(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(s),e.exit(`gfmFootnoteCallLabelMarker`),e.exit(`gfmFootnoteCall`),t):n(s)}return Wo(s)||(o=!0),a++,e.consume(s),s===92?u:l}function u(t){return t===91||t===92||t===93?(e.consume(t),a++,l):l(t)}}function um(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a,o=0,s;return c;function c(t){return e.enter(`gfmFootnoteDefinition`)._container=!0,e.enter(`gfmFootnoteDefinitionLabel`),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),l}function l(t){return t===94?(e.enter(`gfmFootnoteDefinitionMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionMarker`),e.enter(`gfmFootnoteDefinitionLabelString`),e.enter(`chunkString`).contentType=`string`,u):n(t)}function u(t){if(o>999||t===93&&!s||t===null||t===91||Wo(t))return n(t);if(t===93){e.exit(`chunkString`);let n=e.exit(`gfmFootnoteDefinitionLabelString`);return a=Fo(r.sliceSerialize(n)),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),e.exit(`gfmFootnoteDefinitionLabel`),f}return Wo(t)||(s=!0),o++,e.consume(t),t===92?d:u}function d(t){return t===91||t===92||t===93?(e.consume(t),o++,u):u(t)}function f(t){return t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),i.includes(a)||i.push(a),Xo(e,p,`gfmFootnoteDefinitionWhitespace`)):n(t)}function p(e){return t(e)}}function dm(e,t,n){return e.check(ds,t,e.attempt(am,t,n))}function fm(e){e.exit(`gfmFootnoteDefinition`)}function pm(e,t,n){let r=this;return Xo(e,i,`gfmFootnoteDefinitionIndent`,5);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`gfmFootnoteDefinitionIndent`&&i[2].sliceSerialize(i[1],!0).length===4?t(e):n(e)}}function mm(e){let t=(e||{}).singleTilde,n={name:`strikethrough`,tokenize:i,resolveAll:r};return t??=!0,{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function r(e,t){let n=-1;for(;++n1?r(a):(e.consume(a),o++,c);if(o<2&&!t)return r(a);let l=e.exit(`strikethroughSequenceTemporary`),u=rs(a);return l._open=!u||u===2&&!!s,l._close=!s||s===2&&!!u,n(a)}}}var hm=class{constructor(){this.map=[]}add(e,t,n){gm(this,e,t,n)}consume(e){if(this.map.sort(function(e,t){return e[0]-t[0]}),this.map.length===0)return;let t=this.map.length,n=[];for(;t>0;)--t,n.push(e.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),e.length=this.map[t][0];n.push(e.slice()),e.length=0;let r=n.pop();for(;r;){for(let t of r)e.push(t);r=n.pop()}this.map.length=0}};function gm(e,t,n,r){let i=0;if(n!==0||r.length!==0){for(;i-1;){let e=r.events[t][1].type;if(e===`lineEnding`||e===`linePrefix`)t--;else break}let i=t>-1?r.events[t][1].type:null,a=i===`tableHead`||i===`tableRow`?S:c;return a===S&&r.parser.lazy[r.now().line]?n(e):a(e)}function c(t){return e.enter(`tableHead`),e.enter(`tableRow`),l(t)}function l(e){return e===124?u(e):(o=!0,a+=1,u(e))}function u(t){return t===null?n(t):Uo(t)?a>1?(a=0,r.interrupt=!0,e.exit(`tableRow`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),p):n(t):Go(t)?Xo(e,u,`whitespace`)(t):(a+=1,o&&(o=!1,i+=1),t===124?(e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),o=!0,u):(e.enter(`data`),d(t)))}function d(t){return t===null||t===124||Wo(t)?(e.exit(`data`),u(t)):(e.consume(t),t===92?f:d)}function f(t){return t===92||t===124?(e.consume(t),d):d(t)}function p(t){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(t):(e.enter(`tableDelimiterRow`),o=!1,Go(t)?Xo(e,m,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):m(t))}function m(t){return t===45||t===58?g(t):t===124?(o=!0,e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),h):x(t)}function h(t){return Go(t)?Xo(e,g,`whitespace`)(t):g(t)}function g(t){return t===58?(a+=1,o=!0,e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),_):t===45?(a+=1,_(t)):t===null||Uo(t)?b(t):x(t)}function _(t){return t===45?(e.enter(`tableDelimiterFiller`),v(t)):x(t)}function v(t){return t===45?(e.consume(t),v):t===58?(o=!0,e.exit(`tableDelimiterFiller`),e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),y):(e.exit(`tableDelimiterFiller`),y(t))}function y(t){return Go(t)?Xo(e,b,`whitespace`)(t):b(t)}function b(n){return n===124?m(n):n===null||Uo(n)?!o||i!==a?x(n):(e.exit(`tableDelimiterRow`),e.exit(`tableHead`),t(n)):x(n)}function x(e){return n(e)}function S(t){return e.enter(`tableRow`),C(t)}function C(n){return n===124?(e.enter(`tableCellDivider`),e.consume(n),e.exit(`tableCellDivider`),C):n===null||Uo(n)?(e.exit(`tableRow`),t(n)):Go(n)?Xo(e,C,`whitespace`)(n):(e.enter(`data`),w(n))}function w(t){return t===null||t===124||Wo(t)?(e.exit(`data`),C(t)):(e.consume(t),t===92?T:w)}function T(t){return t===92||t===124?(e.consume(t),w):w(t)}}function bm(e,t){let n=-1,r=!0,i=0,a=[0,0,0,0],o=[0,0,0,0],s=!1,c=0,l,u,d,f=new hm;for(;++nn[2]+1){let t=n[2]+1,r=n[3]-n[2]-1;e.add(t,r,[])}}e.add(n[3]+1,0,[[`exit`,o,t]])}return i!==void 0&&(a.end=Object.assign({},Cm(t.events,i)),e.add(i,0,[[`exit`,a,t]]),a=void 0),a}function Sm(e,t,n,r,i){let a=[],o=Cm(t.events,n);i&&(i.end=Object.assign({},o),a.push([`exit`,i,t])),r.end=Object.assign({},o),a.push([`exit`,r,t]),e.add(n+1,0,a)}function Cm(e,t){let n=e[t],r=n[0]===`enter`?`start`:`end`;return n[1][r]}var wm={name:`tasklistCheck`,tokenize:Em};function Tm(){return{text:{91:wm}}}function Em(e,t,n){let r=this;return i;function i(t){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(t):(e.enter(`taskListCheck`),e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),a)}function a(t){return Wo(t)?(e.enter(`taskListCheckValueUnchecked`),e.consume(t),e.exit(`taskListCheckValueUnchecked`),o):t===88||t===120?(e.enter(`taskListCheckValueChecked`),e.consume(t),e.exit(`taskListCheckValueChecked`),o):n(t)}function o(t){return t===93?(e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),e.exit(`taskListCheck`),s):n(t)}function s(r){return Uo(r)?t(r):Go(r)?e.check({tokenize:Dm},t,n)(r):n(r)}}function Dm(e,t,n){return Xo(e,r,`whitespace`);function r(e){return e===null?n(e):t(e)}}function Om(e){return jo([Wp(),om(),mm(e),vm(),Tm()])}var km={};function Am(e){let t=this,n=e||km,r=t.data(),i=r.micromarkExtensions||=[],a=r.fromMarkdownExtensions||=[],o=r.toMarkdownExtensions||=[];i.push(Om(n)),a.push(Np()),o.push(Pp(n))}function jm(e,t){let n=Array.from(e),r=t.map(e=>({...e,endOffset:n.slice(0,e.start+e.length).join(``).length,startOffset:n.slice(0,e.start).join(``).length}));return()=>t=>{let n=t=>{if(!t.children)return;let i=[];for(let a of t.children){let t=a.position?.start?.offset;if(a.type!==`text`||typeof a.value!=`string`||t===void 0){n(a),i.push(a);continue}let o=t+a.value.length,s=r.filter(n=>n.startOffset>=t&&n.endOffset<=o&&e.slice(n.startOffset,n.endOffset)===a.value?.slice(n.startOffset-t,n.endOffset-t));if(s.length===0){i.push(a);continue}let c=0;for(let e of s){let n=e.startOffset-t;n>c&&i.push({type:`text`,value:a.value.slice(c,n)}),i.push({type:`strong`,data:{hName:`span`,hProperties:{className:[`message-mention`,`message-mention-${e.kind}`],"data-principal-id":e.principalId}},children:[{type:`text`,value:a.value.slice(n,n+(e.endOffset-e.startOffset))}]}),c=n+(e.endOffset-e.startOffset)}ct?(0,Q.jsx)(`a`,{...r,href:t,target:`_blank`,rel:`noopener noreferrer`,children:e}):(0,Q.jsx)(`span`,{className:`markdown-unsafe-link`,children:e}),img:({alt:e})=>(0,Q.jsx)(`span`,{className:`markdown-image-omitted`,children:e?`[Image: ${e}]`:`[Remote image omitted]`})},Nm=(0,v.memo)(function({body:e,mentions:t=[]}){let n=(0,v.useMemo)(()=>jm(e,t),[e,t]);return(0,Q.jsx)(`div`,{className:`markdown-message`,children:(0,Q.jsx)(Td,{components:Mm,remarkPlugins:[Am,n],children:e})})});function Pm(e,t){if(!b.test(e.channelId)||!k.test(t)||!e.token)throw Error(`Invalid artifact download authority.`);let n=document.createElement(`form`);n.action=`/v1/channels/${encodeURIComponent(e.channelId)}/artifacts/${encodeURIComponent(t)}/download`,n.method=`post`,n.target=`_self`,n.hidden=!0;let r=document.createElement(`input`);r.type=`hidden`,r.name=`session_token`,r.value=e.token,n.append(r),document.body.append(n);try{n.submit()}finally{n.remove()}}var Fm=500;function Im(e){switch(e){case`LifecycleProjectionReadError`:return`The search index could not be read`;case`FactLifecycleProjectionFailed`:case`EpisodeHistoryProjectionFailed`:return`The search index refused the write`;default:return e??`Unknown error`}}function Lm(e){if(e.retried===0)return`Nothing needed a retry.`;let t=e.failed>0?` ${e.failed} still failing.`:``;return`Retried ${e.retried}: ${e.succeeded} back in search.${t}`}function Rm(e){let t=new Date(e);return Number.isNaN(t.valueOf())?e:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}function zm(e){return e.kind===`project`&&e.key?`Project ${e.key}`:`Global`}function Bm(e){let t=[e.provider,e.model].filter(e=>!!e);return t.length>0?t.join(` · `):`Operator`}function Vm(e){return e?e.replaceAll(`_`,` `):`unknown`}function Hm(e){return e?e.revisions.filter(e=>e.state===`unresolved_conflict`).sort((e,t)=>e.storedAt.localeCompare(t.storedAt)):[]}function Um({detailPanelLayout:e,onAuthenticationFailure:t,onBack:n,onChanged:r,onOpenMemory:i,token:a}){let[o,s]=(0,v.useState)(`conflicts`),[c,l]=(0,v.useState)([]),[u,d]=(0,v.useState)(0),[f,p]=(0,v.useState)([]),[m,h]=(0,v.useState)(0),[g,_]=(0,v.useState)(null),[y,b]=(0,v.useState)(null),[x,S]=(0,v.useState)(!1),[C,w]=(0,v.useState)(!0),[T,E]=(0,v.useState)(null),[D,O]=(0,v.useState)(0),[k,A]=(0,v.useState)(null),[j,M]=(0,v.useState)(null),[N,P]=(0,v.useState)(null),[F,I]=(0,v.useState)(0),[L,R]=(0,v.useState)(null),[ee,z]=(0,v.useState)(``),[V,H]=(0,v.useState)(!1),[te,U]=(0,v.useState)(null),[ne,re]=(0,v.useState)(null),W=(0,v.useCallback)((e,n)=>(e instanceof B&&t(e.message),e instanceof Error?e.message:n),[t]);(0,v.useEffect)(()=>{let e=!1;return w(!0),E(null),Promise.all([Tn(a),En(a),Mn(a)]).then(([t,n,r])=>{e||(l(t.items),d(t.total),p(n.items),h(n.total),_(r))}).catch(t=>{e||E(W(t,`Could not load fact review.`))}).finally(()=>{e||w(!1)}),()=>{e=!0}},[W,D,a]),(0,v.useEffect)(()=>{if(M(null),P(null),o!==`conflicts`||!k)return;let e=!1;return Dn(a,k).then(t=>{e||M(t)}).catch(t=>{e||P(W(t,`Could not load this conflict.`))}),()=>{e=!0}},[F,W,k,o,a]);let ae=e=>{A(e),R(null),z(``),U(null)},oe=e=>{s(e),A(null),R(null),z(``),U(null)},se=c.find(e=>e.claimId===k)??null,ce=f.find(e=>e.claimId===k)??null,le=g?.failed.find(e=>e.id===k)??null,ue=Hm(j),G=L?.kind===`keep`?ue.find(e=>e.revisionId===L.revisionId)??null:null,K=async()=>{if(!(!L||!k)){H(!0),U(null);try{let e=L.kind===`keep`?await kn(a,k,{keepRevisionId:L.revisionId,expectedRevisionIds:ue.map(e=>e.revisionId),note:ee.trim()}):await An(a,k,{revisionId:ce?.revisionId??``,note:ee.trim()});re({memoryId:e.memoryId,text:L.kind===`keep`?`Kept the selected version. It is back in recall.`:`Restored the fact. It is current from now, with no end date.`}),A(null),R(null),z(``),O(e=>e+1),r()}catch(e){e instanceof ie?(R(null),U(`This conflict changed since you opened it. The latest versions are shown below.`),I(e=>e+1),O(e=>e+1)):U(W(e,`Could not save this decision.`))}finally{H(!1)}}},q=L&&(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-review-decision fact-review-confirmation`,"aria-label":`Confirm decision`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:L.kind===`keep`?`Keep this version`:`Restore this fact`}),(0,Q.jsx)(`p`,{children:L.kind===`keep`?`The kept version becomes the current fact. The other version will be kept in history as superseded.`:`The fact will be current from now, with no end date. Its earlier history stays as it is.`}),G?.admissionAuthority===`quarantined`&&(0,Q.jsx)(`p`,{className:`fact-review-warning`,role:`note`,children:`This version has incomplete provenance. It will stay out of recall until its admission is reviewed.`}),(0,Q.jsxs)(`label`,{children:[`Note (optional)`,(0,Q.jsx)(`textarea`,{value:ee,maxLength:Fm,onChange:e=>z(e.target.value)})]}),(0,Q.jsxs)(`div`,{className:`memory-review-toolbar`,children:[(0,Q.jsx)(`button`,{type:`button`,disabled:V,onClick:()=>void K(),children:V?`Saving…`:L.kind===`keep`?`Keep this version`:`Restore`}),(0,Q.jsx)(`button`,{type:`button`,disabled:V,onClick:()=>{R(null),z(``)},children:`Cancel`})]})]}),de=async e=>{H(!0),U(null);try{let t=await Pn(a,e===null?{}:e.kind===`fact`?{claimIds:[e.id]}:{episodeIds:[e.id]});re({memoryId:null,text:Lm(t)}),A(null),O(e=>e+1),r()}catch(e){U(W(e,`Could not retry search sync.`))}finally{H(!1)}},J=async()=>{S(!0),U(null);try{b(await Nn(a))}catch(e){U(W(e,`Could not check the search index.`))}finally{S(!1)}},Y=(g?.failed??[]).map(e=>(0,Q.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":k===e.id,className:`memory-record ${k===e.id?`selected`:``}`,onClick:()=>ae(e.id),children:[(0,Q.jsx)(`span`,{className:`memory-review-state failed`,children:`not in search`}),(0,Q.jsxs)(`span`,{className:`memory-record-copy`,children:[(0,Q.jsx)(`strong`,{children:e.preview}),(0,Q.jsxs)(`small`,{children:[e.kind===`fact`?`Fact`:`Episode`,` · `,e.operation,` · last tried `,Rm(e.updatedAt)]})]})]},`${e.kind}:${e.id}`)),fe=o===`sync`?Y:o===`conflicts`?c.map(e=>(0,Q.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":k===e.claimId,className:`memory-record ${k===e.claimId?`selected`:``}`,onClick:()=>ae(e.claimId),children:[(0,Q.jsx)(`span`,{className:`memory-review-state unresolved_conflict`,children:`conflict`}),(0,Q.jsxs)(`span`,{className:`memory-record-copy`,children:[(0,Q.jsx)(`strong`,{children:e.revisions.map(e=>e.preview).join(` / `)}),(0,Q.jsxs)(`small`,{children:[zm(e.scope),` · opened `,Rm(e.openedAt)]})]})]},e.claimId)):f.map(e=>(0,Q.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":k===e.claimId,className:`memory-record ${k===e.claimId?`selected`:``}`,onClick:()=>ae(e.claimId),children:[(0,Q.jsx)(`span`,{className:`memory-review-state ${e.state}`,children:e.state}),(0,Q.jsxs)(`span`,{className:`memory-record-copy`,children:[(0,Q.jsx)(`strong`,{children:e.preview}),(0,Q.jsxs)(`small`,{children:[zm(e.scope),` · `,Rm(e.changedAt)]})]})]},e.claimId));return(0,Q.jsxs)(`section`,{className:`memory-workspace memory-reconciliation-workspace`,"aria-label":`Fact review`,children:[(0,Q.jsxs)(`div`,{className:`memory-browser-pane`,children:[(0,Q.jsxs)(`header`,{className:`memory-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`breadcrumbs`,children:`Kai Workshop / Memory`}),(0,Q.jsx)(`h1`,{children:`Fact review`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Back to memories`,title:`Back to memories`,onClick:n,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})]}),(0,Q.jsxs)(`div`,{className:`memory-browser-scroll`,children:[(0,Q.jsxs)(`div`,{className:`fact-review-tabs`,role:`tablist`,"aria-label":`Fact review lists`,children:[(0,Q.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o===`conflicts`,onClick:()=>oe(`conflicts`),children:[`Conflicts `,(0,Q.jsx)(`span`,{children:u})]}),(0,Q.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o===`forgotten`,onClick:()=>oe(`forgotten`),children:[`Forgotten `,(0,Q.jsx)(`span`,{children:m})]}),(0,Q.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o===`sync`,onClick:()=>oe(`sync`),children:[`Search sync `,(0,Q.jsx)(`span`,{children:g?.failedTotal??0})]})]}),o===`sync`&&!C&&!T&&(0,Q.jsxs)(`section`,{className:`fact-review-sync-summary`,"aria-label":`Search sync summary`,children:[(0,Q.jsxs)(`p`,{className:`memory-review-explanation`,children:[`These facts and episodes are saved, but their search copy failed to update, so Kai cannot recall them yet.`,g&&g.blocked>0&&` ${g.blocked} later change${g.blocked===1?` is`:`s are`} waiting behind them.`]}),(0,Q.jsxs)(`div`,{className:`memory-review-toolbar`,children:[(0,Q.jsx)(`button`,{type:`button`,disabled:V||(g?.failedTotal??0)===0,onClick:()=>void de(null),children:`Retry all`}),(0,Q.jsx)(`button`,{type:`button`,disabled:x,onClick:()=>void J(),children:x?`Checking…`:`Check search index`})]}),y&&(0,Q.jsx)(`p`,{className:`memory-review-explanation`,role:`note`,children:y.orphan.length+y.unknown.length===0&&y.duplicate===0?`The search index matches your memory.`:`The search index has ${y.orphan.length} leftover and ${y.unknown.length} unknown row(s)${y.duplicate>0?`, and ${y.duplicate} item(s) with duplicates`:``}. Kai never recalls them; they only take up space.`}),te&&!le&&(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:te})]}),ne&&(0,Q.jsxs)(`p`,{className:`memory-mutation-report`,role:`status`,children:[ne.text,ne.memoryId&&(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(`button`,{type:`button`,className:`fact-review-link`,onClick:()=>i(ne.memoryId),children:`Open in memory`})]})]}),C?(0,Q.jsx)(`p`,{className:`memory-list-state`,role:`status`,children:`Loading fact review…`}):T?(0,Q.jsxs)(`div`,{className:`memory-list-state error`,role:`alert`,children:[(0,Q.jsx)(`p`,{children:T}),(0,Q.jsx)(`button`,{onClick:()=>O(e=>e+1),children:`Retry`})]}):fe.length===0?(0,Q.jsxs)(`div`,{className:`memory-list-state`,children:[(0,Q.jsx)(`h2`,{children:o===`conflicts`?`No open conflicts`:o===`forgotten`?`No forgotten facts`:`Everything is in search`}),(0,Q.jsx)(`p`,{children:o===`conflicts`?`Conflicts appear when an extracted update is not certain enough to replace a stored fact.`:o===`forgotten`?`Facts you forget, or that expire, appear here and can be restored.`:`Facts and episodes appear here if their search copy fails to update.`})]}):(0,Q.jsx)(`div`,{className:`memory-record-list memory-reconciliation-list`,role:`listbox`,"aria-label":o===`conflicts`?`Unresolved conflicts`:o===`forgotten`?`Forgotten facts`:`Search sync failures`,children:fe})]})]}),(0,Q.jsxs)(`aside`,{className:`context-pane memory-detail-pane`,"aria-label":`Fact review detail`,children:[e&&(0,Q.jsx)(`div`,{className:`context-resize-handle`,role:`separator`,"aria-label":`Resize fact review detail`,"aria-orientation":`vertical`,"aria-valuemin":e.minimumWidth,"aria-valuemax":e.maximumWidth,"aria-valuenow":e.width,tabIndex:0,onKeyDown:e.onKeyDown,onPointerDown:e.onPointerDown,onPointerMove:e.onPointerMove}),(0,Q.jsx)(`div`,{className:`memory-reconciliation-detail`,children:o===`conflicts`&&se?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`header`,{className:`memory-detail-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Unresolved conflict`}),(0,Q.jsx)(`h2`,{children:`Which version is true?`})]}),(0,Q.jsx)(`span`,{className:`memory-review-state unresolved_conflict`,children:`conflict`})]}),(0,Q.jsx)(`p`,{className:`memory-review-explanation`,children:`Neither version is recalled until you keep one. If neither wording is quite right, keep the closer one and edit it in memory.`}),te&&(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:te}),N?(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:N}):j?(0,Q.jsx)(`div`,{className:`fact-review-sides`,children:ue.map(e=>(0,Q.jsxs)(`article`,{className:`memory-review-evidence`,"aria-label":`Competing version`,children:[(0,Q.jsx)(Nm,{body:e.content}),(0,Q.jsxs)(`dl`,{className:`fact-review-facts`,children:[(0,Q.jsx)(`dt`,{children:`Stored`}),(0,Q.jsx)(`dd`,{children:Rm(e.storedAt)}),(0,Q.jsx)(`dt`,{children:`Source`}),(0,Q.jsx)(`dd`,{children:Bm(e)}),(0,Q.jsx)(`dt`,{children:`Confidence`}),(0,Q.jsx)(`dd`,{children:typeof e.confidence==`number`?`${Math.round(e.confidence*100)}%`:`Not recorded`}),(0,Q.jsx)(`dt`,{children:`Reason`}),(0,Q.jsx)(`dd`,{children:e.reason}),(0,Q.jsx)(`dt`,{children:`Admission`}),(0,Q.jsx)(`dd`,{children:Vm(e.admissionAuthority)})]}),(0,Q.jsx)(`button`,{type:`button`,disabled:V,onClick:()=>{R({kind:`keep`,revisionId:e.revisionId}),U(null)},children:`Keep this version`})]},e.revisionId))}):(0,Q.jsx)(`p`,{className:`memory-list-state`,role:`status`,children:`Loading conflict…`}),q]}):o===`forgotten`&&ce?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`header`,{className:`memory-detail-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:ce.state===`expired`?`Expired fact`:`Forgotten fact`}),(0,Q.jsx)(`h2`,{children:`Restore to current?`})]}),(0,Q.jsx)(`span`,{className:`memory-review-state ${ce.state}`,children:ce.state})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(Nm,{body:ce.preview}),(0,Q.jsxs)(`dl`,{className:`fact-review-facts`,children:[(0,Q.jsx)(`dt`,{children:`Scope`}),(0,Q.jsx)(`dd`,{children:zm(ce.scope)}),(0,Q.jsx)(`dt`,{children:ce.state===`expired`?`Expired`:`Forgotten`}),(0,Q.jsx)(`dd`,{children:Rm(ce.changedAt)}),(0,Q.jsx)(`dt`,{children:`Reason`}),(0,Q.jsx)(`dd`,{children:ce.reason})]})]}),te&&(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:te}),!L&&(0,Q.jsx)(`button`,{type:`button`,disabled:V,onClick:()=>{R({kind:`restore`}),U(null)},children:`Restore`}),q]}):o===`sync`&&le?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`header`,{className:`memory-detail-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`p`,{className:`overline`,children:[le.kind===`fact`?`Fact`:`Episode`,` not in search`]}),(0,Q.jsx)(`h2`,{children:`Retry search sync?`})]}),(0,Q.jsx)(`span`,{className:`memory-review-state failed`,children:`failed`})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(Nm,{body:le.preview}),(0,Q.jsxs)(`dl`,{className:`fact-review-facts`,children:[(0,Q.jsx)(`dt`,{children:`Step`}),(0,Q.jsx)(`dd`,{children:le.operation}),(0,Q.jsx)(`dt`,{children:`Attempts`}),(0,Q.jsx)(`dd`,{children:le.attempts}),(0,Q.jsx)(`dt`,{children:`Error`}),(0,Q.jsx)(`dd`,{children:Im(le.errorCode)}),(0,Q.jsx)(`dt`,{children:`Last tried`}),(0,Q.jsx)(`dd`,{children:Rm(le.updatedAt)})]})]}),(0,Q.jsxs)(`p`,{className:`memory-review-explanation`,children:[`The saved `,le.kind,` is unchanged. Retrying only updates its search copy`,le.kind===`fact`?`, then runs any later changes that were waiting on it`:``,`.`]}),te&&(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:te}),(0,Q.jsx)(`button`,{type:`button`,disabled:V,onClick:()=>void de(le),children:V?`Retrying…`:`Retry`})]}):(0,Q.jsx)(`div`,{className:`memory-list-state`,children:(0,Q.jsx)(`p`,{children:o===`conflicts`?`Select a conflict to compare its versions.`:o===`forgotten`?`Select a fact to see why it left current truth.`:`Select an item to see why it is not in search.`})})})]})]})}var Wm=(0,v.createContext)(null);function Gm({children:e}){let[t,n]=(0,v.useState)(null),r=(0,v.useRef)(null),i=(0,v.useRef)(null),a=(0,v.useCallback)(e=>{let t=r.current;t&&(r.current=null,n(null),t.resolve(e))},[]),o=(0,v.useCallback)(e=>(r.current?.resolve(!1),new Promise(t=>{let i={message:e,resolve:t};r.current=i,n(i)})),[]);return(0,v.useEffect)(()=>()=>{r.current?.resolve(!1),r.current=null},[]),(0,v.useEffect)(()=>{if(!t)return;i.current?.focus();let e=e=>{e.key===`Escape`&&(e.preventDefault(),a(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t,a]),(0,Q.jsxs)(Wm.Provider,{value:o,children:[e,t&&(0,Q.jsx)(`div`,{className:`confirmation-backdrop`,onMouseDown:e=>{e.target===e.currentTarget&&a(!1)},children:(0,Q.jsxs)(`section`,{className:`confirmation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`confirmation-dialog-title`,"aria-describedby":`confirmation-dialog-message`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Confirm action`}),(0,Q.jsx)(`h2`,{id:`confirmation-dialog-title`,children:`Continue?`}),(0,Q.jsx)(`p`,{id:`confirmation-dialog-message`,children:t.message}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`button`,{ref:i,type:`button`,className:`quiet-button`,onClick:()=>a(!1),children:`Cancel`}),(0,Q.jsx)(`button`,{type:`button`,className:`primary-button`,onClick:()=>a(!0),children:`Continue`})]})]})})]})}function Km(){let e=(0,v.useContext)(Wm);if(!e)throw Error(`useConfirmation must be used within ConfirmationProvider`);return e}var qm=8;function Jm(e){return e.evidence[0]?.text??`Unavailable fact`}function Ym(e){let t=e.evidence[0];return!t||t.migrationGaps.includes(`scope`)?`Scope not recorded`:t.scope===`project`&&t.projectId?`Project ${t.projectId}`:`Global`}function Xm(e){let t=new Set(e.map(e=>{let t=e.evidence[0];return!t||t.migrationGaps.includes(`scope`)?``:t.scope===`project`?`project:${t.projectId??``}`:`global`}));if(t.size!==1)return{kind:``,key:``};let[n]=[...t];return n===`global`?{kind:`global`,key:``}:n.startsWith(`project:`)&&n.length>8?{kind:`project`,key:n.slice(8)}:{kind:``,key:``}}function Zm(e,t){return e.evidence.length>0&&e.evidence.every(e=>e.kind===`fact`)&&(e.consolidationId===null||e.consolidationId===t)}function Qm({allowedProjects:e,anchor:t,availableGroups:n,consolidation:r,onAuthenticationFailure:i,onClose:a,onSaved:o,planId:s,token:c}){let l=Km(),u=(0,v.useMemo)(()=>new Map(n.map(e=>[e.groupId,e])),[n]),d=r?.consolidationId??null,[f,p]=(0,v.useState)(()=>{let e=r?.groupIds??[t.groupId,...t.relatedGroupIds];return[...new Set(e)].filter(e=>{let t=u.get(e);return t!==void 0&&Zm(t,d)})}),m=f.map(e=>u.get(e)).filter(e=>!!e),h=r?{kind:r.scopeKind,key:r.scopeKey??``}:Xm(m),[g,_]=(0,v.useState)(r?.content??Jm(t)),[y,b]=(0,v.useState)(r?.sourceMemoryId??t.evidence[0]?.memoryId??``),[x,S]=(0,v.useState)(h.kind),[C,w]=(0,v.useState)(h.key),[T,E]=(0,v.useState)(r?.operatorNote??``),[D,O]=(0,v.useState)(``),[k,A]=(0,v.useState)(!1),[j,M]=(0,v.useState)(null),N=D.trim()?n.filter(e=>!f.includes(e.groupId)&&Zm(e,d)&&Jm(e).toLowerCase().includes(D.trim().toLowerCase())).slice(0,qm):[],P=m.some(e=>e.evidence.some(e=>e.memoryId===y)),F=x!==`project`||e.some(e=>e.projectId===C),I=null;m.length<2?I=`Select at least two facts to consolidate.`:g.trim()?P?x?x===`project`&&!F&&(I=`Choose a project you currently have access to.`):I=`Choose a scope for the consolidated fact.`:I=`Choose the wording of one of the selected facts to start from.`:I=`Enter the consolidated fact's wording.`;let L=`${m.length} selected facts → 1 current fact; ${Math.max(m.length-1,0)} duplicates excluded`,R=(e,t)=>{e instanceof B&&i(e.message),M(e instanceof Error?e.message:t)},ee=e=>{p(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},z=e=>{_(Jm(e)),b(e.evidence[0]?.memoryId??``)},V=async()=>{if(!I&&await l(`${r?`Update`:`Save`} this consolidation? ${L}. Applying the plan keeps the other facts only as evidence; Kai will not recall them.`)){A(!0),M(null);try{await rn(c,s,{canonical:{content:g.trim(),scopeKey:x===`project`?C:null,scopeKind:x,sourceMemoryId:y},...r?{consolidationId:r.consolidationId,expectedRevision:r.revision}:{},expectedStateVersions:Object.fromEntries(m.map(e=>[e.groupId,e.decision.stateVersion])),groupIds:m.map(e=>e.groupId),operatorNote:T}),o(`Consolidation saved: ${L}.`)}catch(e){R(e,`Could not save the consolidation.`)}finally{A(!1)}}},H=async()=>{if(r&&await l(`Cancel this consolidation? Each fact gets back the decision it had before.`)){A(!0),M(null);try{await an(c,s,r.consolidationId,r.revision),o(`Consolidation cancelled; each fact has its earlier decision again.`)}catch(e){R(e,`Could not cancel the consolidation.`)}finally{A(!1)}}};return(0,Q.jsxs)(`section`,{className:`memory-reconciliation-detail memory-consolidation`,"aria-label":`Consolidate facts`,children:[(0,Q.jsxs)(`header`,{className:`memory-detail-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:r?`Saved consolidation`:`Consolidate facts`}),(0,Q.jsx)(`h2`,{children:`Several facts, one current fact`})]}),(0,Q.jsx)(`button`,{type:`button`,className:`panel-icon-button`,"aria-label":`Back to the fact`,title:`Back to the fact`,onClick:a,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Selected facts`}),(0,Q.jsx)(`p`,{className:`memory-review-explanation`,children:`Keep checked the facts that say the same thing. Use one's wording as a starting point, then edit it below.`}),(0,Q.jsx)(`ul`,{className:`memory-consolidation-facts`,children:m.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:!0,onChange:()=>ee(e.groupId)}),(0,Q.jsx)(`span`,{children:Jm(e)})]}),(0,Q.jsx)(`small`,{children:Ym(e)}),(0,Q.jsx)(`button`,{type:`button`,className:`quiet-button`,"aria-pressed":e.evidence[0]?.memoryId===y,onClick:()=>z(e),children:e.evidence[0]?.memoryId===y?`Wording source`:`Use this wording`})]},e.groupId))}),(0,Q.jsxs)(`label`,{className:`memory-consolidation-search`,children:[`Add another fact`,(0,Q.jsx)(`input`,{type:`search`,value:D,placeholder:`Search pending facts`,onChange:e=>O(e.target.value)})]}),N.length>0&&(0,Q.jsx)(`ul`,{className:`memory-consolidation-facts`,"aria-label":`Matching facts`,children:N.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:!1,onChange:()=>ee(e.groupId)}),(0,Q.jsx)(`span`,{children:Jm(e)})]}),(0,Q.jsx)(`small`,{children:Ym(e)})]},e.groupId))})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-review-correction`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Consolidated fact`}),(0,Q.jsxs)(`label`,{children:[`Wording`,(0,Q.jsx)(`textarea`,{value:g,maxLength:16384,onChange:e=>_(e.target.value)})]}),(0,Q.jsxs)(`label`,{children:[`Scope`,(0,Q.jsxs)(`select`,{value:x,onChange:e=>S(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:`Choose scope`}),(0,Q.jsx)(`option`,{value:`global`,children:`Global`}),(0,Q.jsx)(`option`,{value:`project`,children:`Project`})]})]}),x===`project`&&(0,Q.jsxs)(`label`,{children:[`Project`,(0,Q.jsxs)(`select`,{value:C,onChange:e=>w(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:`Choose project`}),e.map(e=>(0,Q.jsx)(`option`,{value:e.projectId,children:e.displayName},e.projectId))]})]}),(0,Q.jsxs)(`label`,{children:[`Note (optional)`,(0,Q.jsx)(`textarea`,{value:T,maxLength:4096,onChange:e=>E(e.target.value)})]})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-review-decision`,children:[(0,Q.jsx)(`p`,{className:`memory-consolidation-preview`,role:`status`,children:L}),I&&(0,Q.jsx)(`p`,{className:`memory-review-explanation`,children:I}),j&&(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:j}),(0,Q.jsxs)(`div`,{className:`memory-review-toolbar`,children:[(0,Q.jsx)(`button`,{type:`button`,disabled:k||I!==null,onClick:()=>void V(),children:k?`Saving…`:r?`Update consolidation`:`Save consolidation`}),r&&(0,Q.jsx)(`button`,{type:`button`,className:`danger`,disabled:k,onClick:()=>void H(),children:`Cancel consolidation`})]})]})]})}function $m(e){return e.replaceAll(`_`,` `).replace(/^./,e=>e.toUpperCase())}function eh(e){let t=e.replace(/\s+/g,` `).trim();return t.length>88?`${t.slice(0,87)}…`:t}function th(e){switch(e.kind){case`adopt_as_current`:case`adopt_corrected`:return{button:`Approve current-truth adoption`,label:`Adopt as current truth`,operatorAdmits:!0,verb:`adopt as current truth`};case`keep_first_retract_rest`:return{button:`Approve consolidation`,label:`Consolidate into current truth`,operatorAdmits:!0,verb:`consolidate into current truth`};case`expire_all`:return{button:`Approve obsolescence`,label:`Mark obsolete`,operatorAdmits:!1,verb:`mark obsolete`};case`record_episode_chain`:return{button:`Approve historical retention`,label:`Retain as retrievable history`,operatorAdmits:!0,verb:`retain as retrievable history`};default:return null}}function nh(e){if(e.length===0)return null;let t=th(e[0].proposedAction);return t&&e.every(e=>th(e.proposedAction)?.verb===t.verb)?t:null}function rh(e){return th(e.proposedAction)?.label??$m(e.resolution)}function ih(e,t){return e instanceof Error?e.message:t}function ah(e){if(e.disposition!==`approve`)return{className:e.disposition,label:e.disposition};switch(e.action.kind){case`expire_all`:return{className:`obsolete`,label:`obsolete`};case`consolidate`:return{className:`approve`,label:`consolidated`};case`keep_first_retract_rest`:return{className:`approve`,label:`consolidated`};case`record_episode_chain`:return{className:`approve`,label:`retained`};default:return{className:`approve`,label:`approved`}}}function oh(e){return`Group ${e.replace(/^mtg_/,``).slice(0,8)}`}function sh(e){return e?.classification===`incomplete_episode`}var ch={actors:`the people involved`,outcome_quality:`an outcome`};function lh(e){if(!e)return`defer`;if(sh(e))return e.decision.disposition===`defer`?`defer`:`reject`;if(e.decision.disposition===`reject`||e.decision.disposition===`defer`)return e.decision.disposition;let t=e.decision.disposition===`approve`?e.decision.action.kind:null,n=e.decision.recommendation.outcome,r=t??e.proposedAction.kind;return r===`expire_all`||n===`obsolete`?`obsolete`:r===`adopt_corrected`||r===`adopt_as_current`||r===`keep_first_retract_rest`||r===`record_episode_chain`||n===`adopt`||n===`consolidate`?`approve`:`defer`}function uh(e){if(!e||e.decision.disposition!==`approve`||e.decision.action.kind!==`adopt_corrected`)return null;let t=e.decision.action.replacement;return t&&typeof t==`object`&&!Array.isArray(t)?t:null}function dh(e){let t=uh(e)?.scope_kind;if(t===`global`||t===`project`)return t;let n=e?.evidence[0];return!n||n.kind!==`fact`||n.scope!==`global`&&n.scope!==`project`?``:e.evidence.every(e=>e.scope===n.scope&&e.projectId===n.projectId)?n.scope:``}function fh(e,t){let n=e.decision.recommendation.related_group_ids,r=Array.isArray(n)&&n.every(e=>typeof e==`string`)?n:String(e.decision.recommendation.rationale??``).match(/mtg_[a-z0-9]+/gi)??[];return[...new Set(r)].filter(n=>n!==e.groupId&&t.has(n))}function ph(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M7 4h10M7 9h10M7 14h6`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`m14.5 18 2 2 4-5`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.8`})]})}function mh({allowedProjects:e,availableGroups:t,group:n,onAuthenticationFailure:r,onConsolidate:i,onSelectGroup:a,onSaved:o,readOnly:s,token:c,planId:l}){let u=n?.evidence[0]??null,d=uh(n),[f,p]=(0,v.useState)(typeof d?.content==`string`?d.content:u?.text??``),[m,h]=(0,v.useState)(lh(n)),[g,_]=(0,v.useState)(dh(n)),[y,b]=(0,v.useState)(typeof d?.scope_key==`string`?d.scope_key:u?.projectId??``),[x,S]=(0,v.useState)(n?.decision.operatorNote??``),[C,w]=(0,v.useState)(!1),[T,E]=(0,v.useState)(null);if(!n||!u||!l)return(0,Q.jsxs)(`div`,{className:`memory-detail-empty`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`◇`}),(0,Q.jsx)(`h2`,{children:`No exception selected`}),(0,Q.jsx)(`p`,{children:`Only uncertain or conflicting memory groups require individual review.`})]});let D=n.decision.recommendation,O=f.trim()!==u.text,k=n.evidence.every(e=>e.kind===`fact`),A=n.evidence.every(e=>e.kind===`episode`),j=g!==u.scope||g===`project`&&y!==u.projectId,M=g!==`project`||e.some(e=>e.projectId===y),N=u.validUntil?Date.parse(u.validUntil):null,P=N!==null&&!Number.isNaN(N)&&N<=Date.now(),F=null;m===`approve`&&A?F={kind:`record_episode_chain`}:m===`obsolete`&&k?F={kind:`expire_all`}:m===`approve`&&k&&f.trim()&&g&&M&&(g!==`project`||y)&&(F=n.evidence.length>1||O||j||u.migrationGaps.includes(`scope`)||P?{kind:`adopt_corrected`,source_memory_id:u.memoryId,replacement:{content:f.trim(),scope_kind:g,scope_key:g===`project`?y:``,confidence:typeof u.confidence==`number`?u.confidence:.5,asserted_at:u.assertedAt,observed_at:u.observedAt,valid_from:P?null:u.validFrom,valid_until:P?null:u.validUntil}}:{kind:`adopt_as_current`});let I=m===`approve`||m===`obsolete`,L=!I||F!==null,R=I?`approve`:m,ee=A?`Retain as immutable history`:n.evidence.length>1?`Approve consolidation`:`Approve as current truth`,z=null;I&&F===null&&(z=!k&&!A?`This mixed evidence group cannot be approved.`:k&&!f.trim()?`Enter the current fact wording before approval.`:k&&!g?`Choose a scope before approval.`:k&&g===`project`&&!y?`Choose a project before approval.`:k&&g===`project`&&!M?`The selected project is not currently authorized for this runtime.`:`This decision is not available for the supplied evidence.`);let V=new Set(t.map(e=>e.groupId)),H=n.relatedGroupIds.length>0?n.relatedGroupIds.filter(e=>V.has(e)):fh(n,V),te=async e=>{e.preventDefault(),w(!0),E(null);try{let e=R===`approve`&&F?F:n.proposedAction;await en(c,l,n.groupId,{disposition:R,action:e,operatorNote:x,expectedStateVersion:n.decision.stateVersion}),o()}catch(e){e instanceof B&&r(e.message),E(ih(e,`Could not save this memory decision.`))}finally{w(!1)}};return(0,Q.jsxs)(`form`,{className:`memory-reconciliation-detail`,onSubmit:e=>void te(e),children:[(0,Q.jsxs)(`header`,{className:`memory-detail-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Exception review`}),(0,Q.jsx)(`h2`,{children:$m(n.classification)})]}),(0,Q.jsx)(`span`,{className:`memory-review-state ${ah(n.decision).className}`,children:ah(n.decision).label})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Why this needs judgment`}),sh(n)?(0,Q.jsxs)(`p`,{children:[`This legacy episode was saved without`,` `,n.missingFields.map(e=>ch[e]??e).join(` or `)||`required details`,`, so it can't be kept as a canonical episode. Kai won't guess them. Reject it, or defer.`]}):(0,Q.jsx)(`p`,{children:n.rationale})]}),Object.keys(D).length>0&&(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Model recommendation`}),(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`strong`,{children:$m(String(D.outcome??`needs_review`))}),typeof D.confidence==`number`&&` · ${Math.round(D.confidence*100)}% confidence`]}),(0,Q.jsx)(`p`,{children:String(D.rationale??`No rationale was returned.`)}),H.length>0&&(0,Q.jsxs)(`div`,{className:`memory-related-groups`,children:[(0,Q.jsx)(`p`,{children:`Related facts`}),H.map(e=>(0,Q.jsx)(`button`,{type:`button`,title:`Open this fact`,onClick:()=>a(e),children:eh(t.find(t=>t.groupId===e)?.evidence[0]?.text??`Unavailable fact`)},e)),k&&!s&&(0,Q.jsx)(`button`,{type:`button`,className:`memory-consolidate-button`,onClick:i,children:`Consolidate related facts…`})]}),(0,Q.jsx)(`p`,{className:`memory-review-explanation`,children:`Advisory only; it has not changed memory.`})]}),n.priorReviewEvidence.length>0&&(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Earlier raw review`}),n.priorReviewEvidence.map(e=>(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`strong`,{children:$m(e.disposition)}),e.operatorNote?` · ${e.operatorNote}`:` · No operator note`]},e.candidateId)),(0,Q.jsx)(`p`,{className:`memory-review-explanation`,children:`This earlier decision remains evidence. It was not silently converted into a grouped approval.`})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Evidence`}),n.evidence.map(e=>(0,Q.jsxs)(`article`,{className:`memory-review-evidence`,children:[(0,Q.jsx)(Nm,{body:e.text}),(0,Q.jsxs)(`small`,{children:[e.kind,` · `,e.scope,e.projectId?` · ${e.projectId}`:``]})]},e.memoryId))]}),(0,Q.jsxs)(`fieldset`,{className:`memory-review-controls`,disabled:s||C,children:[u.kind===`fact`&&(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-review-correction`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Canonical fact`}),(0,Q.jsxs)(`label`,{children:[`Current wording`,(0,Q.jsx)(`textarea`,{value:f,maxLength:16384,onChange:e=>p(e.target.value)})]}),(0,Q.jsxs)(`label`,{children:[`Scope`,(0,Q.jsxs)(`select`,{value:g,onChange:e=>_(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:`Choose scope`}),(0,Q.jsx)(`option`,{value:`global`,children:`Global`}),(0,Q.jsx)(`option`,{value:`project`,children:`Project`})]})]}),g===`project`&&(0,Q.jsxs)(`label`,{children:[`Project`,(0,Q.jsxs)(`select`,{value:y,onChange:e=>b(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:`Choose project`}),y&&!e.some(e=>e.projectId===y)&&(0,Q.jsxs)(`option`,{value:y,children:[y,` (unavailable)`]}),e.map(e=>(0,Q.jsx)(`option`,{value:e.projectId,children:e.displayName},e.projectId))]})]}),(0,Q.jsx)(`p`,{className:`memory-review-explanation`,children:`Adoption creates one current claim backed by every evidence row in this group. You may retain the wording or correct it.`})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-review-decision`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Review`}),(0,Q.jsxs)(`label`,{children:[`Decision`,(0,Q.jsxs)(`select`,{value:m,onChange:e=>h(e.target.value),children:[(k||A)&&!sh(n)&&(0,Q.jsx)(`option`,{value:`approve`,children:ee}),k&&(0,Q.jsx)(`option`,{value:`obsolete`,children:`Mark obsolete`}),(0,Q.jsx)(`option`,{value:`reject`,children:`Reject`}),(0,Q.jsx)(`option`,{value:`defer`,children:`Defer`})]})]}),z&&(0,Q.jsx)(`p`,{children:z}),F?.kind===`adopt_as_current`&&!O&&(0,Q.jsxs)(`p`,{children:[`Approve adopts this fact unchanged as current truth.`,n.priorReviewEvidence.length>0&&` The earlier decision remains audit evidence.`]}),(0,Q.jsxs)(`label`,{children:[`Operator note`,(0,Q.jsx)(`textarea`,{value:x,maxLength:4096,onChange:e=>S(e.target.value)})]}),T&&(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:T}),(0,Q.jsx)(`button`,{type:`submit`,disabled:s||C||!L,children:C?`Saving…`:`Save decision`}),k&&!sh(n)&&(0,Q.jsxs)(`p`,{className:`memory-review-explanation`,children:[`Same fact saved several times?`,` `,(0,Q.jsx)(`button`,{type:`button`,className:`fact-review-link`,disabled:s,onClick:i,children:`Consolidate with other facts…`})]})]})]})]})}function hh({allowedProjects:e,detailPanelLayout:t,onAuthenticationFailure:n,onBack:r,token:i}){let a=Km(),[o,s]=(0,v.useState)(null),[c,l]=(0,v.useState)([]),[u,d]=(0,v.useState)(null),[f,p]=(0,v.useState)(!0),[m,h]=(0,v.useState)(!1),[g,_]=(0,v.useState)(0),[y,b]=(0,v.useState)(null),[x,S]=(0,v.useState)(null),[C,w]=(0,v.useState)(null),[T,E]=(0,v.useState)([]),[D,O]=(0,v.useState)([]),[k,A]=(0,v.useState)(!1),j=(e,t)=>{e instanceof B&&n(e.message),b(ih(e,t))};(0,v.useEffect)(()=>{let e=!1;return p(!0),b(null),w(null),E([]),Xt(i).then(async t=>{if(e)return;if(s(t),l([]),A(!1),!t){d(null);return}let n=[],r=0,a=t;for(;r!==null;){let e=await Zt(i,t.planId,{exceptionsOnly:!0,limit:100,offset:r});n.push(...e.groups),a=e.triage,r=e.nextOffset}let o=await nn(i,t.planId);e||(s(a),l(n),O(o),d(e=>e!==null&&n.some(t=>t.groupId===e)?e:n[0]?.groupId??null))}).catch(t=>{e||j(t,`Could not load memory triage.`)}).finally(()=>{e||p(!1)}),()=>{e=!0}},[g,i]);let M=(0,v.useMemo)(()=>c.find(e=>e.groupId===u)??null,[c,u]),N=async()=>{if(o){h(!0),b(null);try{let e=[],t=0;for(;t!==null;){let n=await Zt(i,o.planId,{limit:100,offset:t});e.push(...n.groups.filter(e=>e.deterministic&&e.bulkEligible&&e.decision.disposition===`pending`)),t=n.nextOffset}let n=e[0];if(!n)throw Error(`No deterministic memory groups are pending.`);let r=JSON.stringify(n.proposedAction),a=e.filter(e=>JSON.stringify(e.proposedAction)===r),s=await Qt(i,o.planId,o.reviewVersion,a.map(e=>e.groupId));if(a.length!==s.groupCount)throw Error(`Kai returned an incomplete deterministic memory preview.`);w(s),E(a),S(`Review the complete grouped evidence below before approving it.`)}catch(e){j(e,`Could not preview deterministic memory groups.`)}finally{h(!1)}}},P=async()=>{if(!C)return;let e=C.resolutionCounts,t=nh(T);if(await a(t?`${$m(t.verb)} for ${C.memoryCount} deterministic legacy memories? `+(t.operatorAdmits?`Their original provenance will remain incomplete; your explicit approval supplies separate retrieval admission authority.`:`Their original provenance will remain incomplete and the canonical lifecycle will exclude them as obsolete.`):`Approve ${C.memoryCount} deterministic memories after reviewing the complete preview: ${e.adopt} adopt, ${e.consolidate} consolidate, ${e.obsolete} obsolete? No detected warning is not proof that a fact is true; your approval is the trust decision.`)){h(!0),b(null);try{await $t(i,C),S(t?`${C.memoryCount} deterministic legacy memories approved to ${t.verb} in ${C.groupCount} evidence-bound groups.`:`${C.memoryCount} deterministic memories approved in ${C.groupCount} evidence-bound groups.`),_(e=>e+1)}catch(e){j(e,`Could not approve deterministic memory groups.`)}finally{h(!1)}}},F=async()=>{if(o){h(!0),b(null);try{let e=await on(i,o.planId);S(e.remaining===0?`The configured memory-quality model analyzed all ${o.exceptionGroups} exception groups. Recommendations are advisory only.`:`The configured memory-quality model analyzed ${e.recommended} exception groups; ${e.remaining} remain. Recommendations are advisory only.`),_(e=>e+1)}catch(e){j(e,`Could not analyze uncertain memory groups.`)}finally{h(!1)}}},I=async()=>{if(o&&await a(`Apply this grouped plan through canonical fact and episode lifecycle events? A final receipt will record every outcome.`)){h(!0),b(null);try{let e=await sn(i,o.planId,o.reviewVersion);S(`${e.operator_admitted??0} operator admitted, ${e.adopted??0} adopted by lifecycle outcome, ${e.consolidated??0} consolidated, ${e.obsolete??0} obsolete, ${e.deferred??0} deferred, ${e.rejected??0} rejected, ${e.failed??0} failed, ${e.still_unresolved??0} still unresolved.`+((e.failed??0)>0?` ${e.failed} did not reach search; retry them under Search sync in Fact review.`:``)),_(e=>e+1)}catch(e){j(e,`Could not apply grouped memory triage.`)}finally{h(!1)}}};return(0,Q.jsxs)(`section`,{className:`memory-workspace memory-reconciliation-workspace`,"aria-label":`Memory reconciliation`,children:[(0,Q.jsxs)(`div`,{className:`memory-browser-pane`,children:[(0,Q.jsxs)(`header`,{className:`memory-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`breadcrumbs`,children:`Kai Workshop / Memory`}),(0,Q.jsx)(`h1`,{children:`Legacy triage`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Back to memories`,title:`Back to memories`,onClick:r,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})]}),(0,Q.jsx)(`div`,{className:`memory-browser-scroll`,children:f?(0,Q.jsx)(`p`,{className:`memory-list-state`,role:`status`,children:`Building grouped memory triage…`}):y?(0,Q.jsxs)(`div`,{className:`memory-list-state error`,role:`alert`,children:[(0,Q.jsx)(`p`,{children:y}),(0,Q.jsx)(`button`,{onClick:()=>_(e=>e+1),children:`Retry`})]}):o?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`section`,{className:`memory-reconciliation-summary`,"aria-label":`Triage summary`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:o.resolutionCounts.adopt}),(0,Q.jsx)(`span`,{children:`Retain`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:o.resolutionCounts.consolidate}),(0,Q.jsx)(`span`,{children:`Consolidate`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:o.resolutionCounts.obsolete}),(0,Q.jsx)(`span`,{children:`Obsolete`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:Math.max(o.dispositionCounts.pending-o.pendingDeterministicGroups,0)}),(0,Q.jsx)(`span`,{children:`Need review`})]})]}),o.status===`applied`&&(0,Q.jsx)(`p`,{className:`memory-review-explanation`,role:`status`,children:`Applied: every group was decided and the plan has changed memory. This view is a record of it.`}),(0,Q.jsxs)(`p`,{className:`memory-review-explanation`,children:[`The plan partitions `,o.memoryCount,` legacy memories into `,o.groupCount,` non-overlapping groups. Only uncertain or conflicting groups appear below.`]}),x&&(0,Q.jsx)(`p`,{className:`memory-mutation-report`,role:`status`,children:x}),(0,Q.jsxs)(`div`,{className:`memory-review-toolbar`,children:[(0,Q.jsx)(`button`,{type:`button`,disabled:o.pendingDeterministicGroups===0||m||o.status===`applied`,onClick:()=>void N(),children:C?`Refresh safe preview`:`Preview safe groups`}),(0,Q.jsx)(`button`,{type:`button`,disabled:o.exceptionGroups===0||o.recommendedGroups>=o.exceptionGroups||m||o.status===`applied`,onClick:()=>void F(),children:o.exceptionGroups>0&&o.recommendedGroups>=o.exceptionGroups?`Exceptions analyzed (${o.recommendedGroups})`:`Analyze exceptions`}),(0,Q.jsx)(`button`,{type:`button`,disabled:o.dispositionCounts.pending!==0||m||o.status===`applied`,onClick:()=>void I(),children:o.status===`applied`?`Applied`:`Apply plan`})]}),C&&(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-safe-preview`,"aria-label":`Deterministic memory preview`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Complete deterministic preview`}),(0,Q.jsxs)(`p`,{children:[C.memoryCount,` memories in `,C.groupCount,` evidence-bound groups.`,nh(T)?nh(T)?.operatorAdmits?` Their original provenance remains incomplete; your explicit approval supplies separate retrieval admission authority.`:` Their original provenance remains incomplete and the canonical lifecycle will keep them out of retrieval.`:` No detected warning is proof of truth; approval is your explicit trust decision.`]}),(0,Q.jsx)(`p`,{children:nh(T)?`Proposed outcome: ${C.memoryCount} ${nh(T)?.verb}.`:`Proposed outcomes: ${C.resolutionCounts.adopt} adopt, ${C.resolutionCounts.consolidate} consolidate, ${C.resolutionCounts.obsolete} obsolete.`}),T.map(e=>(0,Q.jsxs)(`details`,{children:[(0,Q.jsxs)(`summary`,{children:[$m(e.classification),` · `,eh(e.evidence[0]?.text??`Unavailable memory`),` · `,e.evidence.length,` `,e.evidence.length===1?`memory`:`memories`,` · `,rh(e)]}),(0,Q.jsx)(`p`,{children:e.rationale}),e.evidence.map(e=>(0,Q.jsxs)(`article`,{className:`memory-review-evidence`,children:[(0,Q.jsx)(Nm,{body:e.text}),(0,Q.jsxs)(`small`,{children:[e.scope,e.projectId?` · ${e.projectId}`:``]})]},e.memoryId))]},e.groupId)),(0,Q.jsx)(`button`,{type:`button`,disabled:m,onClick:()=>void P(),children:nh(T)?nh(T)?.button:`Approve preview`})]}),c.length===0?(0,Q.jsxs)(`div`,{className:`memory-list-state`,children:[(0,Q.jsx)(`h2`,{children:`No exceptional groups`}),(0,Q.jsx)(`p`,{children:`The deterministic preview contains everything in this audit.`})]}):(0,Q.jsx)(`div`,{className:`memory-record-list memory-reconciliation-list`,role:`listbox`,"aria-label":`Memory triage exceptions`,children:c.map(e=>(0,Q.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":u===e.groupId,className:`memory-record ${u===e.groupId?`selected`:``}`,onClick:()=>{A(!1),d(e.groupId)},children:[(0,Q.jsx)(`span`,{className:`memory-review-state ${ah(e.decision).className}`,children:ah(e.decision).label}),(0,Q.jsxs)(`span`,{className:`memory-record-copy`,children:[(0,Q.jsx)(`strong`,{children:e.evidence[0]?.text??`Unavailable memory`}),(0,Q.jsxs)(`small`,{children:[e.evidence.length===1?$m(e.classification):`${oh(e.groupId)} · ${$m(e.classification)} · ${e.evidence.length} memories`,e.consolidationId&&` · part of a consolidation`]})]})]},e.groupId))})]}):(0,Q.jsxs)(`div`,{className:`memory-list-state`,children:[(0,Q.jsx)(ph,{}),(0,Q.jsx)(`h2`,{children:`No reconciliation audit`}),(0,Q.jsx)(`p`,{children:`Run an authorized read-only audit first.`})]})})]}),(0,Q.jsxs)(`aside`,{className:`context-pane memory-detail-pane`,"aria-label":`Memory triage exception detail`,children:[t&&(0,Q.jsx)(`div`,{className:`context-resize-handle`,role:`separator`,"aria-label":`Resize memory triage detail`,"aria-orientation":`vertical`,"aria-valuemin":t.minimumWidth,"aria-valuemax":t.maximumWidth,"aria-valuenow":t.width,tabIndex:0,onKeyDown:t.onKeyDown,onPointerDown:t.onPointerDown,onPointerMove:t.onPointerMove}),M&&o&&o.status!==`applied`&&(k||M.consolidationId)?(0,Q.jsx)(Qm,{allowedProjects:e,anchor:M,availableGroups:c,consolidation:D.find(e=>e.consolidationId===M.consolidationId)??null,onAuthenticationFailure:n,onClose:()=>A(!1),onSaved:e=>{S(e),A(!1),_(e=>e+1)},planId:o.planId,token:i},`${M.groupId}:${M.consolidationId??`new`}:${M.decision.stateVersion}`):(0,Q.jsx)(mh,{allowedProjects:e,availableGroups:c,group:M,onAuthenticationFailure:n,onConsolidate:()=>A(!0),onSelectGroup:e=>{A(!1),d(e)},onSaved:()=>{S(`Exception decision saved.`),_(e=>e+1)},planId:o?.planId??null,readOnly:o?.status===`applied`,token:i},`${o?.planId??`none`}:${M?.groupId??`none`}:${M?.decision.stateVersion??0}`)]})]})}var gh={kind:``,lifecycle:``,projectId:``,scope:``,tag:``};function _h(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`circle`,{cx:`11`,cy:`11`,r:`7`,stroke:`currentColor`,strokeWidth:`2`}),(0,Q.jsx)(`path`,{d:`m16.25 16.25 4 4`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`2`})]})}function vh(e){return{kind:e.kind||void 0,lifecycle:e.lifecycle||void 0,projectId:e.projectId||void 0,scope:e.scope||void 0,tag:e.tag.trim()||void 0}}function yh(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`rect`,{x:`4`,y:`5`,width:`10`,height:`12`,rx:`1.5`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M17 8h1.5A1.5 1.5 0 0 1 20 9.5v9a1.5 1.5 0 0 1-1.5 1.5h-7A1.5 1.5 0 0 1 10 18.5V20`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M7 9h4M7 12.5h4`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`})]})}function bh(e){let t=new Date(e);return Number.isNaN(t.valueOf())?e:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}function xh(e){if(!e.retrievable)switch(e.exclusionReason){case`legacy_scope_quarantined`:return`Quarantined until its legacy scope is reviewed.`;case`invalid_scope_quarantined`:return`Quarantined because its stored scope is invalid.`;case`project_id_mismatch`:return`Unavailable outside project ${e.projectId??`unknown`}.`;case`project_scope_not_allowed`:return`Available only when project ${e.projectId??`unknown`} is active.`;case`task_scope_not_supported`:return`Task-scoped memories are not currently recalled.`;default:return`Not currently eligible for recall.`}return e.scope===`project`?`Available while project ${e.projectId??`unknown`} is active.`:e.scope===`task`?`Available in its assigned task context.`:`Available across your projects.`}function Sh(e){switch(e){case`explicit_creation`:return`This memory was saved explicitly, so no source conversation was linked.`;case`legacy_source`:return`This memory predates canonical source links.`;case`canonical_source_missing`:return`The canonical source conversation is no longer available.`;case`invalid_provenance`:return`The stored source reference is incomplete or invalid.`;case`source_not_authorized`:return`Your session cannot read the referenced source conversation.`;default:return`No canonical source conversation is available for this memory.`}}function Ch(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function wh(e){return e.split(/[,\n]/).map(e=>e.trim()).filter(Boolean)}function Th(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`memory-editor-${Date.now()}-${Math.random().toString(16).slice(2)}`}function Eh({allowedProjects:e,detail:t,onAuthenticationFailure:n,onClose:r,onReload:i,onSaved:a,token:o}){let s=Km(),c=t?.episode,[l,u]=(0,v.useState)(t?.content??``),[d,f]=(0,v.useState)((c?.tags??t?.tags??[]).join(`, `)),[p,m]=(0,v.useState)(`global`),[h,g]=(0,v.useState)(c?.goal??``),[_,y]=(0,v.useState)(c?.context??``),[b,x]=(0,v.useState)(c?.approach??``),[S,C]=(0,v.useState)(c?.outcome??``),[w,T]=(0,v.useState)(c?.outcomeQuality??`success`),[E,D]=(0,v.useState)(c?.lessons??``),[O,k]=(0,v.useState)((c?.actors??[]).join(`, `)),[A,j]=(0,v.useState)(!1),[M,N]=(0,v.useState)(null),[P,F]=(0,v.useState)(!1),[I]=(0,v.useState)(Th),L=t!==null,R=t?.kind===`episode`,ee=L?R?h!==(c?.goal??``)||_!==(c?.context??``)||b!==(c?.approach??``)||S!==(c?.outcome??``)||w!==(c?.outcomeQuality??`success`)||E!==(c?.lessons??``)||O!==(c?.actors??[]).join(`, `)||d!==(c?.tags??[]).join(`, `):l!==t.content||d!==t.tags.join(`, `):!!(l.trim()||d.trim()||p!==`global`);(0,v.useEffect)(()=>{if(!ee)return;let e=e=>{e.preventDefault()};return window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e)},[ee]);let z=async()=>{ee&&!await s(`Discard your unsaved memory changes?`)||r()},V=async e=>{e.preventDefault(),j(!0),N(null),F(!1);try{if(!t){let e=p.startsWith(`project:`)?{scope:`project`,projectId:p.slice(8)}:{scope:`global`},t=await Ln(o,{content:l,tags:wh(d),target:e,requestId:I});a(t.record,t.created?`Explicit memory created.`:`Memory was already created.`)}else if(R){let e=await Rn(o,{kind:`episode`,memoryId:t.memoryId,revision:t.revision,requestId:I,episode:{actors:wh(O),approach:b,context:_,goal:h,lessons:E.trim()||null,outcome:S,outcomeQuality:w,tags:wh(d)}});a(e.record,e.idempotentReplay?`Memory was already saved.`:`Episode updated and re-indexed.`)}else{let e=await Rn(o,{kind:`fact`,memoryId:t.memoryId,revision:t.revision,requestId:I,content:l,tags:wh(d)});a(e.record,e.idempotentReplay?`Memory was already saved.`:`Fact updated and re-indexed.`)}}catch(e){e instanceof ae?(F(!0),N(`This memory changed after you opened it. Reload the latest revision before saving again.`)):e instanceof B?(n(e.message),N(e.message)):N(e instanceof Error?e.message:`Could not save this memory.`)}finally{j(!1)}};return(0,Q.jsx)(`div`,{className:`memory-confirm-backdrop memory-editor-backdrop`,children:(0,Q.jsxs)(`section`,{className:`memory-editor`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`memory-editor-title`,children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:L?`Edit memory`:`New explicit memory`}),(0,Q.jsx)(`h2`,{id:`memory-editor-title`,children:L?`Correct ${R?`episode`:`fact`}`:`Create fact`})]}),(0,Q.jsx)(`button`,{type:`button`,className:`panel-icon-button`,"aria-label":`Close memory editor`,title:`Close memory editor`,disabled:A,onClick:()=>void z(),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsxs)(`form`,{onSubmit:e=>void V(e),children:[R?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{children:[`Goal `,(0,Q.jsx)(`span`,{children:`affects semantic retrieval`}),(0,Q.jsx)(`textarea`,{required:!0,maxLength:2e4,value:h,onChange:e=>g(e.target.value)})]}),(0,Q.jsxs)(`label`,{children:[`Context `,(0,Q.jsx)(`span`,{children:`affects semantic retrieval`}),(0,Q.jsx)(`textarea`,{required:!0,maxLength:2e4,value:_,onChange:e=>y(e.target.value)})]}),(0,Q.jsxs)(`label`,{children:[`Approach`,(0,Q.jsx)(`textarea`,{required:!0,maxLength:2e4,value:b,onChange:e=>x(e.target.value)})]}),(0,Q.jsxs)(`label`,{children:[`Outcome`,(0,Q.jsx)(`textarea`,{required:!0,maxLength:2e4,value:S,onChange:e=>C(e.target.value)})]}),(0,Q.jsxs)(`div`,{className:`memory-editor-grid`,children:[(0,Q.jsxs)(`label`,{children:[`Outcome quality`,(0,Q.jsxs)(`select`,{value:w,onChange:e=>T(e.target.value),children:[(0,Q.jsx)(`option`,{value:`success`,children:`Success`}),(0,Q.jsx)(`option`,{value:`partial`,children:`Partial`}),(0,Q.jsx)(`option`,{value:`failure`,children:`Failure`})]})]}),(0,Q.jsxs)(`label`,{children:[`Actors `,(0,Q.jsx)(`span`,{children:`comma-separated`}),(0,Q.jsx)(`input`,{maxLength:4096,value:O,onChange:e=>k(e.target.value)})]})]}),(0,Q.jsxs)(`label`,{children:[`Lessons `,(0,Q.jsx)(`span`,{children:`optional`}),(0,Q.jsx)(`textarea`,{maxLength:2e4,value:E,onChange:e=>D(e.target.value)})]})]}):(0,Q.jsxs)(`label`,{children:[`Content `,(0,Q.jsx)(`span`,{children:`affects semantic retrieval`}),(0,Q.jsx)(`textarea`,{required:!0,maxLength:1e5,value:l,onChange:e=>u(e.target.value)})]}),(0,Q.jsxs)(`label`,{children:[`Tags `,(0,Q.jsx)(`span`,{children:`comma- or line-separated`}),(0,Q.jsx)(`input`,{maxLength:4096,value:d,onChange:e=>f(e.target.value)})]}),!L&&(0,Q.jsxs)(`label`,{children:[`Recall scope`,(0,Q.jsxs)(`select`,{value:p,onChange:e=>m(e.target.value),children:[(0,Q.jsx)(`option`,{value:`global`,children:`Global scope`}),e.map(e=>(0,Q.jsx)(`option`,{value:`project:${e.projectId}`,children:e.displayName},e.projectId))]})]}),L&&(0,Q.jsx)(`p`,{className:`memory-editor-provenance`,children:`Source provenance and authority fields remain immutable. Saving regenerates the searchable vector.`}),M&&(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:M}),(0,Q.jsxs)(`footer`,{children:[P&&(0,Q.jsx)(`button`,{type:`button`,className:`quiet-button`,onClick:i,children:`Reload latest`}),(0,Q.jsx)(`button`,{type:`button`,className:`quiet-button`,disabled:A,onClick:()=>void z(),children:`Cancel`}),(0,Q.jsx)(`button`,{type:`submit`,disabled:A||L&&!ee,children:A?`Saving…`:L?`Save correction`:`Create memory`})]})]})]})})}function Dh({allowedProjects:e,busy:t,detail:n,error:r,loading:i,onDelete:a,onEdit:o,onMove:s,source:c,sourceError:l}){let[u,d]=(0,v.useState)(`global`);if(i)return(0,Q.jsx)(`p`,{className:`memory-detail-state`,role:`status`,children:`Loading memory details…`});if(r)return(0,Q.jsx)(`p`,{className:`memory-detail-state error`,role:`alert`,children:r});if(!n)return(0,Q.jsxs)(`div`,{className:`memory-detail-empty`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`◇`}),(0,Q.jsx)(`h2`,{children:`Select a memory`}),(0,Q.jsx)(`p`,{children:`Choose a fact or episode to inspect its content, scope, recall preview, and source.`})]});let f=n.lifecycle.authority===`legacy`;return(0,Q.jsxs)(`div`,{className:`memory-detail-scroll`,children:[(0,Q.jsxs)(`header`,{className:`memory-detail-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Memory detail`}),(0,Q.jsx)(`h2`,{children:n.kind===`episode`?`Episode`:`Fact`})]}),(0,Q.jsx)(`span`,{className:`memory-kind ${n.kind}`,children:n.kind})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Stored memory`}),(0,Q.jsx)(Nm,{body:n.content})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-lifecycle-history`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Lifecycle and provenance`}),(0,Q.jsxs)(`div`,{className:`memory-lifecycle-summary`,children:[(0,Q.jsx)(`span`,{className:`memory-review-state ${n.lifecycle.currentState}`,children:Ch(n.lifecycle.currentState)}),(0,Q.jsx)(`strong`,{children:n.lifecycle.authority===`canonical`?`Canonical authority`:`Legacy evidence`})]}),n.lifecycle.authority===`legacy`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{children:`This memory predates canonical lifecycle provenance and requires review. That does not mean it is false.`}),(0,Q.jsxs)(`p`,{className:`memory-review-gaps`,children:[`Missing: `,(n.lifecycle.migrationGaps??[`canonical provenance`]).map(Ch).join(`, `)]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`dl`,{className:`memory-metadata-grid`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Scope`}),(0,Q.jsx)(`dd`,{children:Ch(n.lifecycle.scope.kind)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Recorded`}),(0,Q.jsx)(`dd`,{children:bh(n.lifecycle.createdAt)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Revisions`}),(0,Q.jsx)(`dd`,{children:n.lifecycle.revisions.length})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`History events`}),(0,Q.jsx)(`dd`,{children:n.lifecycle.events.length})]})]}),(0,Q.jsxs)(`div`,{className:`memory-lifecycle-timeline`,children:[n.lifecycle.revisions.map(e=>(0,Q.jsxs)(`article`,{children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsx)(`span`,{className:`memory-review-state ${e.state}`,children:Ch(e.state)}),(0,Q.jsx)(`time`,{children:bh(e.storedAt)})]}),(0,Q.jsx)(Nm,{body:e.content}),(0,Q.jsx)(`p`,{children:e.reason}),(0,Q.jsxs)(`dl`,{className:`memory-metadata-grid`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Model`}),(0,Q.jsx)(`dd`,{children:e.model??`Not recorded`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Prompt`}),(0,Q.jsx)(`dd`,{children:e.promptVersion??`Not recorded`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Valid from`}),(0,Q.jsx)(`dd`,{children:e.validFrom?bh(e.validFrom):`Unbounded`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Valid until`}),(0,Q.jsx)(`dd`,{children:e.validUntil?bh(e.validUntil):`Current`})]})]})]},e.revisionId)),n.lifecycle.followups.map(e=>(0,Q.jsxs)(`article`,{children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsx)(`span`,{className:`memory-review-state historical`,children:Ch(e.relationship)}),(0,Q.jsx)(`time`,{children:bh(e.createdAt)})]}),(0,Q.jsx)(`p`,{children:e.reason}),(0,Q.jsxs)(`small`,{children:[e.sourceEpisodeId===n.lifecycle.identity?`Followed by`:`Follows`,` another episode.`]})]},`${e.sourceEpisodeId}:${e.targetEpisodeId}:${e.relationship}`))]})]})]}),n.episode&&Object.keys(n.episode).length>0&&(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Episode structure`}),(0,Q.jsx)(`dl`,{className:`memory-episode-fields`,children:Object.entries(n.episode).map(([e,t])=>(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:Ch(e)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Nm,{body:Array.isArray(t)?t.join(`, `):t??``})})]},e))})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section scope-card`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Recall scope`}),(0,Q.jsx)(`strong`,{children:n.scope.scope===`project`?`Project memory`:`${Ch(n.scope.scope)} memory`}),(0,Q.jsx)(`p`,{children:xh(n.scope)}),(0,Q.jsxs)(`dl`,{className:`memory-metadata-grid`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Speaker`}),(0,Q.jsx)(`dd`,{children:n.speaker})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Confidence`}),(0,Q.jsxs)(`dd`,{children:[Math.round(n.confidence*100),`%`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Source`}),(0,Q.jsx)(`dd`,{children:n.source})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Updated`}),(0,Q.jsx)(`dd`,{children:bh(n.updatedAt)})]})]})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-management`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Manage memory`}),f&&(0,Q.jsx)(`p`,{className:`memory-review-gaps`,children:`This memory is waiting for legacy reconciliation and can't be changed yet.`}),(0,Q.jsxs)(`label`,{children:[`Move to`,(0,Q.jsxs)(`select`,{disabled:f,value:u,onChange:e=>d(e.target.value),children:[(0,Q.jsx)(`option`,{value:`global`,children:`Global scope`}),e.map(e=>(0,Q.jsx)(`option`,{value:`project:${e.projectId}`,children:e.displayName},e.projectId))]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`button`,{type:`button`,disabled:t||f,onClick:()=>o(n),children:`Edit memory…`}),(0,Q.jsx)(`button`,{type:`button`,disabled:t||f,onClick:()=>s(n.memoryId,u),children:`Move memory…`}),(0,Q.jsx)(`button`,{className:`danger`,type:`button`,disabled:t||f,onClick:()=>a(n.memoryId),children:`Forget memory…`})]})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section recall-preview`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Agent recall preview`}),(0,Q.jsx)(`p`,{children:`This compact record—not the rich stored episode above—is what Kai can place in an agent prompt when this memory is recalled.`}),(0,Q.jsx)(`pre`,{children:n.compactRecall})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Source conversation`}),l?(0,Q.jsx)(`p`,{className:`memory-source-unavailable`,role:`alert`,children:l}):c?c.status===`unavailable`?(0,Q.jsx)(`p`,{className:`memory-source-unavailable`,children:Sh(c.reason)}):(0,Q.jsxs)(`div`,{className:`memory-source-context`,children:[c.source&&(0,Q.jsxs)(`article`,{children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsx)(`strong`,{children:c.source.authorDisplayName}),(0,Q.jsx)(`time`,{children:bh(c.source.createdAt)})]}),(0,Q.jsx)(Nm,{body:c.source.body})]}),c.result&&(0,Q.jsxs)(`article`,{className:`agent`,children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsx)(`strong`,{children:c.result.authorDisplayName}),(0,Q.jsx)(`time`,{children:bh(c.result.createdAt)})]}),(0,Q.jsx)(Nm,{body:c.result.body})]})]}):(0,Q.jsx)(`p`,{className:`memory-source-unavailable`,role:`status`,children:`Loading source context…`})]}),n.tags.length>0&&(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Tags`}),(0,Q.jsx)(`div`,{className:`memory-tags`,children:n.tags.map(e=>(0,Q.jsx)(`span`,{children:e},e))})]})]})}function Oh({detailPanelLayout:e,initialMemoryId:t,onAuthenticationFailure:n,onClose:r,onSelectMemory:i,token:a}){let[o,s]=(0,v.useState)(null),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(gh),[f,p]=(0,v.useState)(gh),[m,h]=(0,v.useState)(``),[g,_]=(0,v.useState)(``),[y,b]=(0,v.useState)(`newest`),[x,S]=(0,v.useState)(`relevance`),[C,w]=(0,v.useState)([]),[T,E]=(0,v.useState)([]),[D,O]=(0,v.useState)(null),[k,A]=(0,v.useState)(!0),[j,M]=(0,v.useState)(!1),[N,P]=(0,v.useState)(null),[F,I]=(0,v.useState)(0),[L,R]=(0,v.useState)(0),[ee,z]=(0,v.useState)(t),[V,H]=(0,v.useState)(null),[te,U]=(0,v.useState)(null),[ne,re]=(0,v.useState)(t!==null),[W,ie]=(0,v.useState)(null),[ae,oe]=(0,v.useState)(null),[se,ce]=(0,v.useState)(!1),[le,ue]=(0,v.useState)(()=>new Set),[G,K]=(0,v.useState)(`global`),[q,de]=(0,v.useState)(null),[J,Y]=(0,v.useState)(!1),[fe,pe]=(0,v.useState)(null),[me,he]=(0,v.useState)(null),[X,ge]=(0,v.useState)(!1),[_e,ve]=(0,v.useState)(!1),ye=(0,v.useRef)([]);(0,v.useEffect)(()=>{z(t)},[t]);let be=(0,v.useCallback)((e,t)=>e instanceof B?(n(e.message),e.message):e instanceof Error?e.message:t,[n]);(0,v.useEffect)(()=>{let e=!1;return l(null),Kt(a).then(t=>{e||s(t)}).catch(t=>{e||l(be(t,`Could not load memory statistics.`))}),()=>{e=!0}},[be,F,a]),(0,v.useEffect)(()=>{let e=!1;return A(!0),P(null),O(null),(g?gn(a,g,{...vh(f),limit:50}):hn(a,{...vh(f),limit:50,order:y})).then(t=>{e||(`hits`in t?(E(t.hits),w([])):(w(t.records),E([]),O(t.nextCursor)))}).catch(t=>{e||(P(be(t,`Could not load memories.`)),w([]),E([]))}).finally(()=>{e||A(!1)}),()=>{e=!0}},[y,f,be,F,g,a]);let xe=(0,v.useMemo)(()=>{if(!g)return C;let e=[...T];return x!==`relevance`&&e.sort((e,t)=>{let n=e.record.updatedAt.localeCompare(t.record.updatedAt);return x===`newest`?-n:n}),e.map(e=>e.record)},[C,T,x,g]);(0,v.useEffect)(()=>{!ee&&xe[0]&&(z(xe[0].memoryId),i(xe[0].memoryId))},[xe,i,ee]),(0,v.useEffect)(()=>{if(!ee){H(null),ie(null),re(!1);return}let e=!1;return re(!0),U(null),oe(null),H(null),ie(null),Promise.allSettled([bn(a,ee),Bn(a,ee)]).then(([t,n])=>{e||(t.status===`fulfilled`?H(t.value):U(be(t.reason,`Could not load this memory.`)),n.status===`fulfilled`?ie(n.value):oe(be(n.reason,`Could not load source context.`)),re(!1))}),()=>{e=!0}},[L,be,ee,a]);let Se=(0,v.useMemo)(()=>o?Object.keys(o.byScope).filter(e=>e.startsWith(`project:`)).map(e=>e.slice(8)).filter(Boolean).sort():[],[o]),Ce=o?.allowedProjects??[],we=(0,v.useCallback)(e=>{z(e),i(e)},[i]),Te=()=>{ce(!1),z(null),w([]),E([]),O(null),ue(new Set),i(null)},Ee=e=>{ue(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},De=()=>{ce(!1),ue(new Set)},Oe=e=>{let t={succeeded:0,not_found:0,stale:0,failed:0,awaiting_reconciliation:0};for(let n of e.results)t[n.outcome]+=1;let n=[`${t.succeeded} succeeded`];return t.stale&&n.push(`${t.stale} became stale`),t.not_found&&n.push(`${t.not_found} no longer existed`),t.failed&&n.push(`${t.failed} failed`),t.awaiting_reconciliation&&n.push(`${t.awaiting_reconciliation} ${t.awaiting_reconciliation===1?`is`:`are`} waiting for legacy reconciliation`),`${e.operation===`delete`?`Forget`:`Scope change`}: ${n.join(`, `)}.`},ke=async()=>{if(q){Y(!0),pe(null);try{let e;if(q.operation===`delete`)e=q.ids.length===1?await fn(a,q.ids[0]):await pn(a,q.ids);else{let t=q.target??`global`,n=t.startsWith(`project:`)?{scope:`project`,projectId:t.slice(8)}:{scope:`global`};e=q.ids.length===1?await un(a,q.ids[0],n):await dn(a,q.ids,n)}pe(Oe(e));let t=new Set(e.results.filter(e=>e.outcome!==`failed`).map(e=>e.memoryId));ue(e=>new Set([...e].filter(e=>!t.has(e)))),e.results.every(e=>e.outcome!==`failed`)&&(ce(!1),ue(new Set)),q.operation===`delete`&&(w(e=>e.filter(e=>!t.has(e.memoryId))),E(e=>e.filter(e=>!t.has(e.record.memoryId)))),ee&&t.has(ee)&&q.operation===`delete`&&(z(null),i(null)),de(null),I(e=>e+1),R(e=>e+1)}catch(e){pe(be(e,`Could not update memories.`)),de(null)}finally{Y(!1)}}},Ae=q?.ids.map(e=>({memoryId:e,preview:xe.find(t=>t.memoryId===e)?.preview??(V?.memoryId===e?V.preview:e)}))??[],je=async()=>{if(!(!D||j||g)){M(!0),P(null);try{let e=await hn(a,{...vh(f),cursor:D,limit:50,order:y});w(t=>[...t,...e.records]),O(e.nextCursor)}catch(e){P(be(e,`Could not load more memories.`))}finally{M(!1)}}},Me=e=>{e.preventDefault(),Te(),p({...u,tag:u.tag.trim()})},Ne=e=>{e.preventDefault(),Te(),_(m.trim())},Pe=()=>{Te(),d(gh),p(gh)},Fe=(e,t)=>{let n=e.key===`ArrowDown`?Math.min(t+1,xe.length-1):e.key===`ArrowUp`?Math.max(t-1,0):e.key===`Home`?0:e.key===`End`?xe.length-1:-1;if(n<0||n===t)return;e.preventDefault();let r=xe[n];r&&(se||we(r.memoryId),ye.current[n]?.focus())},Ie=g?T.length:C.length,Le=o?o.unresolvedConflicts+o.projectionFailures:0;return _e?(0,Q.jsx)(Um,{detailPanelLayout:e,onAuthenticationFailure:n,onBack:()=>ve(!1),onChanged:()=>I(e=>e+1),onOpenMemory:e=>{ve(!1),we(e)},token:a}):X?(0,Q.jsx)(hh,{allowedProjects:Ce,detailPanelLayout:e,onAuthenticationFailure:n,onBack:()=>ge(!1),token:a}):(0,Q.jsxs)(`section`,{className:`memory-workspace`,"aria-label":`Memory workspace`,children:[(0,Q.jsxs)(`div`,{className:`memory-browser-pane`,children:[(0,Q.jsxs)(`header`,{className:`memory-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`breadcrumbs`,children:`Kai Workshop / Memory`}),(0,Q.jsx)(`h1`,{children:`Memory`})]}),(0,Q.jsxs)(`div`,{className:`memory-header-actions`,children:[(0,Q.jsxs)(`button`,{className:`panel-icon-button fact-review-button`,type:`button`,"aria-label":Le>0?`Fact review, ${Le} waiting on you`:`Fact review`,title:`Fact review`,onClick:()=>ve(!0),children:[(0,Q.jsx)(yh,{}),Le>0&&(0,Q.jsx)(`span`,{className:`fact-review-badge`,"aria-hidden":`true`,children:Le})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Review legacy memory`,title:`Review legacy memory`,onClick:()=>ge(!0),children:(0,Q.jsx)(ph,{})}),(0,Q.jsx)(`button`,{className:`nav-add-button memory-add-button`,type:`button`,"aria-label":`Add fact`,title:`Add fact`,onClick:()=>he(`create`),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`})}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Back to conversation`,title:`Back to conversation`,onClick:r,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})]})]}),(0,Q.jsxs)(`div`,{className:`memory-browser-scroll`,children:[(0,Q.jsx)(`section`,{className:`memory-stats`,"aria-label":`Memory statistics`,children:o?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:o.total}),(0,Q.jsx)(`span`,{children:`Total memories`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:o.facts}),(0,Q.jsx)(`span`,{children:`Facts`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:o.episodes}),(0,Q.jsx)(`span`,{children:`Episodes`})]})]}):c?(0,Q.jsx)(`button`,{type:`button`,className:`memory-retry`,onClick:()=>I(e=>e+1),children:`Statistics unavailable · Retry`}):(0,Q.jsx)(`p`,{role:`status`,children:`Loading corpus summary…`})}),(0,Q.jsxs)(`form`,{className:`memory-search`,onSubmit:Ne,role:`search`,children:[(0,Q.jsx)(`label`,{htmlFor:`memory-query`,children:`Search memories`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`input`,{id:`memory-query`,type:`search`,maxLength:2e3,value:m,onChange:e=>h(e.target.value),placeholder:`Describe what you remember…`}),(0,Q.jsx)(`button`,{className:`memory-search-submit`,type:`submit`,"aria-label":`Search`,title:`Search`,children:(0,Q.jsx)(_h,{})}),g&&(0,Q.jsx)(`button`,{type:`button`,className:`quiet-button`,onClick:()=>{Te(),h(``),_(``)},children:`Clear search`})]})]}),(0,Q.jsxs)(`form`,{className:`memory-filters`,onSubmit:Me,children:[(0,Q.jsxs)(`label`,{children:[`Lifecycle`,(0,Q.jsxs)(`select`,{value:u.lifecycle,onChange:e=>d(t=>({...t,lifecycle:e.target.value})),children:[(0,Q.jsx)(`option`,{value:``,children:`Current projection and legacy`}),(0,Q.jsx)(`option`,{value:`active`,children:`Active current facts`}),(0,Q.jsx)(`option`,{value:`historical`,children:`History-bearing facts and episodes`}),(0,Q.jsx)(`option`,{value:`legacy`,children:`Legacy memories requiring review`})]})]}),(0,Q.jsxs)(`label`,{children:[`Kind`,(0,Q.jsxs)(`select`,{value:u.kind,onChange:e=>d(t=>({...t,kind:e.target.value})),children:[(0,Q.jsx)(`option`,{value:``,children:`Facts and episodes`}),(0,Q.jsx)(`option`,{value:`fact`,children:`Facts`}),(0,Q.jsx)(`option`,{value:`episode`,children:`Episodes`})]})]}),(0,Q.jsxs)(`label`,{children:[`Scope`,(0,Q.jsxs)(`select`,{value:u.scope,onChange:e=>d(t=>({...t,scope:e.target.value})),children:[(0,Q.jsx)(`option`,{value:``,children:`Every scope`}),(0,Q.jsx)(`option`,{value:`global`,children:`Global`}),(0,Q.jsx)(`option`,{value:`project`,children:`Project`}),(0,Q.jsx)(`option`,{value:`task`,children:`Task`})]})]}),(0,Q.jsxs)(`label`,{children:[`Project`,(0,Q.jsxs)(`select`,{value:u.projectId,onChange:e=>d(t=>({...t,projectId:e.target.value,scope:e.target.value?`project`:t.scope})),children:[(0,Q.jsx)(`option`,{value:``,children:`Every project`}),Se.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Q.jsxs)(`label`,{children:[`Tag`,(0,Q.jsx)(`input`,{value:u.tag,maxLength:128,onChange:e=>d(t=>({...t,tag:e.target.value})),placeholder:`e.g. preference`})]}),(0,Q.jsxs)(`div`,{className:`memory-filter-actions`,children:[(0,Q.jsx)(`button`,{type:`submit`,children:`Apply filters`}),(0,Q.jsx)(`button`,{type:`button`,className:`quiet-button`,onClick:Pe,children:`Clear filters`})]})]}),(0,Q.jsxs)(`div`,{className:`memory-results-heading`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:g?`Semantic matches`:`Memory corpus`}),(0,Q.jsx)(`h2`,{children:k?`Loading…`:`${Ie} ${g?`matches`:`loaded`}`})]}),(0,Q.jsxs)(`div`,{className:`memory-results-controls`,children:[(0,Q.jsxs)(`label`,{children:[`Sort`,g?(0,Q.jsxs)(`select`,{value:x,onChange:e=>S(e.target.value),children:[(0,Q.jsx)(`option`,{value:`relevance`,children:`Relevance`}),(0,Q.jsx)(`option`,{value:`newest`,children:`Newest first`}),(0,Q.jsx)(`option`,{value:`oldest`,children:`Oldest first`})]}):(0,Q.jsxs)(`select`,{value:y,onChange:e=>b(e.target.value),children:[(0,Q.jsx)(`option`,{value:`newest`,children:`Newest first`}),(0,Q.jsx)(`option`,{value:`oldest`,children:`Oldest first`})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`quiet-button memory-selection-toggle`,disabled:k||xe.length===0||J,onClick:()=>{se?De():(ue(new Set),ce(!0))},children:se?`Cancel selection`:`Select memories`})]})]}),fe&&(0,Q.jsx)(`p`,{className:`memory-mutation-report`,role:`status`,children:fe}),se&&(0,Q.jsxs)(`section`,{className:`memory-bulk-actions`,"aria-label":`Selected memory actions`,children:[(0,Q.jsxs)(`strong`,{children:[le.size,` selected`]}),(0,Q.jsxs)(`select`,{"aria-label":`Move selected memories to`,value:G,onChange:e=>K(e.target.value),children:[(0,Q.jsx)(`option`,{value:`global`,children:`Global scope`}),Ce.map(e=>(0,Q.jsx)(`option`,{value:`project:${e.projectId}`,children:e.displayName},e.projectId))]}),(0,Q.jsx)(`button`,{type:`button`,disabled:le.size===0||J,onClick:()=>de({ids:[...le],operation:`move_scope`,target:G}),children:`Move selected…`}),(0,Q.jsx)(`button`,{className:`danger`,type:`button`,disabled:le.size===0||J,onClick:()=>de({ids:[...le],operation:`delete`}),children:`Forget selected…`})]}),N?(0,Q.jsxs)(`div`,{className:`memory-list-state error`,role:`alert`,children:[(0,Q.jsx)(`p`,{children:N}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>I(e=>e+1),children:`Retry`})]}):k?(0,Q.jsx)(`p`,{className:`memory-list-state`,role:`status`,children:`Loading memories…`}):xe.length===0?(0,Q.jsxs)(`div`,{className:`memory-list-state`,children:[(0,Q.jsx)(`h3`,{children:`No memories found`}),(0,Q.jsx)(`p`,{children:`Clear search or filters to broaden this view.`})]}):(0,Q.jsx)(`div`,{className:`memory-record-list`,role:`listbox`,"aria-label":`Memory results`,children:xe.map((e,t)=>(0,Q.jsxs)(`div`,{className:`memory-record-row ${se?`selecting`:``}`,children:[se&&(0,Q.jsx)(`input`,{type:`checkbox`,"aria-label":`Select ${e.preview||e.memoryId}`,checked:le.has(e.memoryId),onChange:()=>Ee(e.memoryId)}),(0,Q.jsxs)(`button`,{ref:e=>{ye.current[t]=e},type:`button`,role:`option`,"aria-selected":se?le.has(e.memoryId):ee===e.memoryId,className:`memory-record ${(se?le.has(e.memoryId):ee===e.memoryId)?`selected`:``}`,onClick:()=>{se?Ee(e.memoryId):we(e.memoryId)},onKeyDown:e=>Fe(e,t),children:[(0,Q.jsx)(`span`,{className:`memory-kind ${e.kind}`,children:e.kind}),(0,Q.jsxs)(`span`,{className:`memory-record-copy`,children:[(0,Q.jsx)(`strong`,{children:e.preview||`Untitled memory`}),(0,Q.jsx)(`small`,{children:xh(e.scope)}),e.tags.length>0&&(0,Q.jsx)(`span`,{className:`memory-tags compact`,children:e.tags.slice(0,3).map(e=>(0,Q.jsx)(`span`,{children:e},e))})]}),(0,Q.jsx)(`time`,{children:bh(e.updatedAt)})]},e.memoryId)]},e.memoryId))}),D&&!g&&!N&&(0,Q.jsx)(`button`,{className:`memory-load-more`,type:`button`,disabled:j,onClick:()=>void je(),children:j?`Loading…`:`Load more memories`})]})]}),(0,Q.jsxs)(`aside`,{className:`context-pane memory-detail-pane`,"aria-label":se?`Memory selection`:`Memory detail`,children:[e&&(0,Q.jsx)(`div`,{className:`context-resize-handle`,role:`separator`,"aria-label":`Resize memory detail`,"aria-orientation":`vertical`,"aria-valuemin":e.minimumWidth,"aria-valuemax":e.maximumWidth,"aria-valuenow":e.width,tabIndex:0,onKeyDown:e.onKeyDown,onPointerDown:e.onPointerDown,onPointerMove:e.onPointerMove}),se?(0,Q.jsxs)(`div`,{className:`memory-selection-summary`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`◇`}),(0,Q.jsx)(`p`,{className:`overline`,children:`Batch selection`}),(0,Q.jsx)(`h2`,{children:le.size===0?`Choose memories`:`${le.size} ${le.size===1?`memory`:`memories`} selected`}),(0,Q.jsx)(`p`,{children:`Select the memories you want to move or forget. Cancel selection to return to the current memory details.`})]}):(0,Q.jsx)(Dh,{allowedProjects:Ce,busy:J,detail:V,error:te,loading:ne,onDelete:e=>de({ids:[e],operation:`delete`}),onEdit:e=>he(e),onMove:(e,t)=>de({ids:[e],operation:`move_scope`,target:t}),source:W,sourceError:ae})]}),q&&(0,Q.jsx)(`div`,{className:`memory-confirm-backdrop`,children:(0,Q.jsxs)(`section`,{className:`memory-confirm`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`memory-confirm-title`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Confirm memory change`}),(0,Q.jsx)(`h2`,{id:`memory-confirm-title`,children:q.operation===`delete`?`Forget ${q.ids.length} ${q.ids.length===1?`memory`:`memories`}?`:`Move ${q.ids.length} ${q.ids.length===1?`memory`:`memories`}?`}),(0,Q.jsx)(`p`,{children:q.operation===`delete`?`These records will be permanently removed from recall and cannot be restored here.`:`Their recall scope will change to ${q.target?.startsWith(`project:`)?`project ${q.target.slice(8)}`:`global`}.`}),(0,Q.jsx)(`ul`,{children:Ae.map(e=>(0,Q.jsx)(`li`,{children:e.preview},e.memoryId))}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`quiet-button`,disabled:J,onClick:()=>de(null),children:`Cancel`}),(0,Q.jsx)(`button`,{type:`button`,className:q.operation===`delete`?`danger`:``,disabled:J,onClick:()=>void ke(),children:J?`Applying…`:q.operation===`delete`?`Forget permanently`:`Confirm move`})]})]})}),me&&(0,Q.jsx)(Eh,{allowedProjects:Ce,detail:me===`create`?null:me,onAuthenticationFailure:n,onClose:()=>he(null),onReload:()=>{he(null),R(e=>e+1),I(e=>e+1)},onSaved:(e,t)=>{he(null),H(e),z(e.memoryId),i(e.memoryId),pe(t),R(e=>e+1),I(e=>e+1)},token:a})]})}function kh(e){return(0,Q.jsx)(Gm,{children:(0,Q.jsx)(Oh,{...e})})}function Ah(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M3.5 6.5h6l2 2h9v10h-17z`,stroke:`currentColor`,strokeLinejoin:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M12 11v5m-2.5-2.5h5`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`})]})}function jh(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M3.5 6.5h6l2 2h9v10h-17z`,stroke:`currentColor`,strokeLinejoin:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M12 11v5m-2.5-2.5h5`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M7 3.5h10`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`})]})}function Mh(e,t){return e instanceof Error&&e.message?e.message:t}function Nh(e,t){if(t)return`Private home`;switch(e){case`principal_created`:return`Created by you`;case`principal_added`:return`Added by you`;case`legacy_migrated`:return`Migrated access`;case`profile`:return`Runtime profile`;default:return e?e.replaceAll(`_`,` `):`Authorized workspace`}}function Ph(e){switch(e.provenance){case`operator_pinned`:return`Operator pinned`;case`principal_created`:return`Created with this workspace`;case`principal_registered`:return`Registered by you`;case`legacy_migrated`:return`Migrated registration`}}function Fh({detailPanelLayout:e,onAuthenticationFailure:t,onChannelAccessFailure:n,onClose:r,session:i}){let a=Km(),[o,s]=(0,v.useState)(null),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(null),[f,p]=(0,v.useState)(null),[m,h]=(0,v.useState)(!0),[g,_]=(0,v.useState)(!1),[y,b]=(0,v.useState)(null),[x,S]=(0,v.useState)(null),[C,w]=(0,v.useState)(!1),[T,E]=(0,v.useState)(``),[D,O]=(0,v.useState)(!1),[k,A]=(0,v.useState)(``),[j,M]=(0,v.useState)(!1),[N,P]=(0,v.useState)(``),[F,I]=(0,v.useState)(``),L=(0,v.useCallback)(e=>e instanceof B?(t(e.message),!0):e instanceof V&&(n(e.message),!0),[t,n]),R=(0,v.useCallback)(async(e=null)=>{h(!0),b(null);try{let[t,n,r]=await Promise.all([Vn(i),Pr(i),yr(i)]);s(t),l(n),d(r),p(n=>{let r=e??n??t.workspace;return t.workspaces.some(e=>e.path===r)?r:t.workspace})}catch(e){L(e)||b(Mh(e,`Could not load workspaces.`))}finally{h(!1)}},[L,i]);(0,v.useEffect)(()=>{R()},[R]);let ee=(0,v.useMemo)(()=>{if(!o)return[];let e=new Map((c?.grants??[]).map(e=>[e.path,e])),t=new Map;for(let e of u?.projects??[])for(let n of e.workspaceRoots)t.set(n,e);return o.workspaces.map(n=>({grant:e.get(n.path)??null,option:n,project:t.get(n.path)??null}))},[c,u,o]),z=ee.find(e=>e.option.path===f)??ee[0]??null,H=async e=>{if(e.preventDefault(),!(!o||g||!T.trim())){_(!0),b(null),S(null);try{let e=await Mr(i,T.trim(),o.revision),t=[e.directoryCreated?`Workspace created and selected.`:`That workspace already existed and is now selected.`];e.gitReady||t.push(`Git initialization failed; the workspace is still usable.`),e.memoryProjectRegistered||t.push(e.memoryProjectNote),w(!1),E(``),S(t.join(` `)),await R(e.path)}catch(e){e instanceof W?(await R(),b(`Workspace state changed elsewhere. The latest catalogue has been loaded.`)):L(e)||b(Mh(e,`Could not create workspace.`))}finally{_(!1)}}},te=async e=>{e.preventDefault();let t=k.trim();if(!(!t||g)){_(!0),b(null),S(null);try{let e=await Fr(i,t);O(!1),A(``),S(e.mutation?.changed?`Existing workspace access added.`:`That workspace was already available.`),await R(t)}catch(e){L(e)||b(Mh(e,`Could not add workspace access.`))}finally{_(!1)}}},U=async()=>{if(!(!z?.grant?.removable||g||!await a(`Remove access to ${z.option.name}? The directory and its files will not be deleted.`))){_(!0),b(null),S(null);try{let e=await Ir(i,z.option.path);S(e.mutation?.changed?`Access to ${z.option.name} was removed. The directory was not deleted.`:`Access to ${z.option.name} was already absent.`),await R()}catch(e){L(e)||b(Mh(e,`Could not remove workspace access.`))}finally{_(!1)}}},ne=async e=>{if(e.preventDefault(),!(!o||!z?.option.deletable||N!==z.option.name||g)){_(!0),b(null),S(null);try{let e=await Nr(i,z.option.name,N,o.revision);M(!1),P(``),S(e.directoryDeleted?`Workspace ${z.option.name} was permanently deleted.`:`Workspace ${z.option.name} was already absent; its Kai records were cleaned.`),await R()}catch(e){e instanceof W?(await R(),b(`Workspace state changed elsewhere. The latest catalogue has been loaded.`)):L(e)||b(Mh(e,`Could not delete workspace.`))}finally{_(!1)}}},re=async e=>{if(e.preventDefault(),!(!u||!z||!F.trim()||g)){_(!0),b(null),S(null);try{let e=await br(i,u.revision,F.trim(),z.option.path);d(e),I(``),S(e.mutation?.note??`Memory project registered.`)}catch(e){e instanceof W?(await R(z.option.path),b(`Memory projects changed elsewhere. The latest registry has been loaded.`)):L(e)||b(Mh(e,`Could not register memory project.`))}finally{_(!1)}}},ie=async()=>{if(!(!u||!z?.project?.removable||g||!await a(`Unregister memory project ${z.project.projectId}? Existing memories will not be deleted.`))){_(!0),b(null),S(null);try{let e=await xr(i,u.revision,z.project.projectId);d(e),S(e.mutation?.note??`Memory project unregistered.`)}catch(e){e instanceof W?(await R(z.option.path),b(`Memory projects changed elsewhere. The latest registry has been loaded.`)):L(e)||b(Mh(e,`Could not unregister memory project.`))}finally{_(!1)}}};return(0,Q.jsxs)(`main`,{className:`workspaces-workspace`,"aria-label":`Workspaces`,children:[(0,Q.jsxs)(`section`,{className:`workspaces-browser-pane`,children:[(0,Q.jsxs)(`header`,{className:`workspaces-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`breadcrumbs`,children:`Kai Workshop / Workspaces`}),(0,Q.jsx)(`h1`,{children:`Workspaces`})]}),(0,Q.jsxs)(`div`,{className:`workspaces-header-actions`,children:[(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Create workspace`,title:`Create private workspace`,disabled:g,onClick:()=>w(!0),children:(0,Q.jsx)(Ah,{})}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Add existing workspace`,title:`Add existing workspace`,disabled:g,onClick:()=>O(!0),children:(0,Q.jsx)(jh,{})}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Back to conversation`,title:`Back to conversation`,onClick:r,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})]})]}),(x||y)&&(0,Q.jsxs)(`div`,{className:`workspaces-notices`,"aria-live":`polite`,children:[x&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:x}),y&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:y})]}),(0,Q.jsx)(`section`,{className:`workspace-catalogue`,"aria-label":`Authorized workspaces`,children:m?(0,Q.jsx)(`p`,{className:`workspaces-empty`,children:`Loading workspaces…`}):ee.length===0?(0,Q.jsx)(`p`,{className:`workspaces-empty`,children:`No authorized workspaces.`}):(0,Q.jsx)(`ul`,{children:ee.map(e=>(0,Q.jsx)(`li`,{children:(0,Q.jsxs)(`button`,{className:e.option.path===z?.option.path?`selected`:``,type:`button`,onClick:()=>p(e.option.path),children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.option.name}),e.option.current&&(0,Q.jsx)(`span`,{className:`workspace-current`,children:`Current`})]}),(0,Q.jsx)(`small`,{children:e.option.path}),(0,Q.jsxs)(`small`,{children:[Nh(e.grant?.provenance??null,e.option.home),e.grant&&!e.grant.available?` · unavailable`:``]})]})},e.option.path))})})]}),(0,Q.jsxs)(`aside`,{className:`context-pane workspace-detail`,"aria-label":`Workspace detail`,children:[e&&(0,Q.jsx)(`div`,{className:`context-resize-handle`,role:`separator`,"aria-label":`Resize workspace detail`,"aria-orientation":`vertical`,"aria-valuemin":e.minimumWidth,"aria-valuemax":e.maximumWidth,"aria-valuenow":e.width,tabIndex:0,onKeyDown:e.onKeyDown,onPointerDown:e.onPointerDown,onPointerMove:e.onPointerMove}),(0,Q.jsx)(`div`,{className:`workspace-detail-scroll`,"aria-live":`polite`,children:z?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`workspace-detail-heading`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Selected workspace`}),(0,Q.jsx)(`h2`,{children:z.option.name})]}),z.option.current&&(0,Q.jsx)(`span`,{className:`workspace-status`,children:`Current`})]}),(0,Q.jsxs)(`dl`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Path`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:z.option.path})})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Access`}),(0,Q.jsx)(`dd`,{children:Nh(z.grant?.provenance??null,z.option.home)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Availability`}),(0,Q.jsx)(`dd`,{children:z.grant?.available===!1?`Unavailable`:`Available`})]})]}),(0,Q.jsxs)(`section`,{className:`workspace-project-detail`,children:[(0,Q.jsx)(`h3`,{children:`Memory project`}),z.project?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`strong`,{children:z.project.displayName})}),(0,Q.jsxs)(`p`,{children:[Ph(z.project),z.project.available?``:` · unavailable`]}),z.project.removable&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:g,onClick:()=>void ie(),children:`Unregister project`})]}):(0,Q.jsxs)(`form`,{className:`memory-project-registration`,onSubmit:e=>void re(e),children:[(0,Q.jsx)(`p`,{children:`Not registered as a memory project.`}),(0,Q.jsx)(`label`,{htmlFor:`workspace-project-name`,children:`Project name`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`input`,{id:`workspace-project-name`,type:`text`,maxLength:64,pattern:`[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}`,placeholder:z.option.name.toLowerCase().replaceAll(/[^a-z0-9_-]/g,`-`),value:F,disabled:g,onChange:e=>I(e.target.value)}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`submit`,"aria-label":`Register memory project`,title:`Register memory project`,disabled:g||!F.trim(),children:(0,Q.jsx)(Ah,{})})]})]})]}),(z.grant?.removable||z.option.deletable)&&(0,Q.jsxs)(`section`,{className:`workspace-detail-actions`,children:[(0,Q.jsx)(`h3`,{children:`Workspace actions`}),z.grant?.removable&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:g||z.option.current,title:z.option.current?`Switch away from this workspace before removing access`:void 0,onClick:()=>void U(),children:`Remove access`}),z.option.deletable&&(0,Q.jsx)(`button`,{className:`danger-button`,type:`button`,disabled:g,onClick:()=>{P(``),M(!0)},children:`Delete permanently`})]})]}):(0,Q.jsx)(`p`,{className:`workspaces-empty`,children:`Select a workspace.`})})]}),C&&o&&(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog workspace-creation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`create-workspace-title`,children:[(0,Q.jsxs)(`header`,{className:`workspace-creation-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Private workspace`}),(0,Q.jsx)(`h2`,{id:`create-workspace-title`,children:`Create workspace`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close workspace creation`,title:`Close workspace creation`,disabled:g,onClick:()=>{w(!1),E(``)},children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsx)(`p`,{children:`This creates a private directory inside your Kai home.`}),(0,Q.jsxs)(`form`,{onSubmit:e=>void H(e),children:[(0,Q.jsx)(`label`,{htmlFor:`workspace-name`,children:`Workspace name`}),(0,Q.jsx)(`input`,{id:`workspace-name`,type:`text`,autoFocus:!0,maxLength:64,value:T,disabled:g,onChange:e=>E(e.target.value)}),(0,Q.jsx)(`div`,{className:`form-actions`,children:(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:g||!T.trim(),children:g?`Creating…`:`Create workspace`})})]})]})}),D&&(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog workspace-creation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`add-existing-workspace-title`,children:[(0,Q.jsxs)(`header`,{className:`workspace-creation-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Existing directory`}),(0,Q.jsx)(`h2`,{id:`add-existing-workspace-title`,children:`Add existing workspace`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close existing workspace`,title:`Close existing workspace`,disabled:g,onClick:()=>{O(!1),A(``)},children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsx)(`p`,{children:`This grants Kai access to a directory that already exists. It does not create, move, or delete files.`}),(0,Q.jsxs)(`form`,{onSubmit:e=>void te(e),children:[(0,Q.jsx)(`label`,{htmlFor:`workspace-existing-path`,children:`Absolute directory path`}),(0,Q.jsx)(`input`,{id:`workspace-existing-path`,type:`text`,autoFocus:!0,value:k,disabled:g,placeholder:`/Users/you/projects/example`,autoCapitalize:`none`,autoCorrect:`off`,onChange:e=>A(e.target.value)}),(0,Q.jsx)(`div`,{className:`form-actions`,children:(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:g||!k.trim(),children:g?`Adding…`:`Add workspace access`})})]})]})}),j&&z&&(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog workspace-creation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`delete-workspace-title`,children:[(0,Q.jsxs)(`header`,{className:`workspace-creation-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Permanent deletion`}),(0,Q.jsx)(`h2`,{id:`delete-workspace-title`,children:`Delete workspace`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close workspace deletion`,title:`Close workspace deletion`,disabled:g,onClick:()=>{M(!1),P(``)},children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsxs)(`p`,{children:[`This permanently deletes `,(0,Q.jsx)(`strong`,{children:z.option.name}),` and removes it from Kai.`]}),(0,Q.jsxs)(`form`,{onSubmit:e=>void ne(e),children:[(0,Q.jsxs)(`label`,{htmlFor:`workspace-delete-confirmation`,children:[`Type `,(0,Q.jsx)(`strong`,{children:z.option.name}),` to confirm`]}),(0,Q.jsx)(`input`,{id:`workspace-delete-confirmation`,type:`text`,autoFocus:!0,value:N,disabled:g,onChange:e=>P(e.target.value)}),(0,Q.jsx)(`div`,{className:`form-actions`,children:(0,Q.jsx)(`button`,{className:`danger-button`,type:`submit`,disabled:g||N!==z.option.name,children:g?`Deleting…`:`Delete permanently`})})]})]})})]})}function Ih(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M6 6l12 12M18 6 6 18`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`})})}function Lh(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`circle`,{cx:`12`,cy:`12`,r:`8.5`,stroke:`currentColor`,strokeWidth:`1.7`}),(0,Q.jsx)(`path`,{d:`M12 7.5v5l3.2 2`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.7`})]})}function Rh(e){if(!e)return`Not currently scheduled`;let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function zh(e){let t;try{t=JSON.parse(e.scheduleData)}catch{return e.scheduleType}if(!t||typeof t!=`object`)return e.scheduleType;let n=t;if(e.scheduleType===`once`)return typeof n.run_at==`string`?`Once · ${Rh(n.run_at)}`:`Once`;if(e.scheduleType===`interval`){let e=n.seconds;return typeof e==`number`?e%3600==0?`Every ${e/3600} hour${e===3600?``:`s`}`:e%60==0?`Every ${e/60} minute${e===60?``:`s`}`:`Every ${e} seconds`:`Recurring interval`}let r=Array.isArray(n.times)?n.times.filter(e=>typeof e==`string`):[];return r.length?`Daily · ${r.join(`, `)} UTC`:`Daily`}function Bh(e){return e===`workshop_client`?`Workshop`:e.charAt(0).toUpperCase()+e.slice(1).replaceAll(`_`,` `)}function Vh({detailPanelLayout:e,onAuthenticationFailure:t,onClose:n,principalEvents:r,session:i}){let a=Km(),[o,s]=(0,v.useState)([]),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(!0),[f,p]=(0,v.useState)(!1),[m,h]=(0,v.useState)(null),[g,_]=(0,v.useState)(null),y=(0,v.useCallback)(async()=>{d(!0);try{let e=await vi(i);s(e),l(t=>e.some(e=>e.id===t)?t:e[0]?.id??null),h(null)}catch(e){e instanceof B?t(e.message):h(e instanceof Error?e.message:`Could not load scheduled jobs.`)}finally{d(!1)}},[t,i]);(0,v.useEffect)(()=>{y()},[y]),(0,v.useEffect)(()=>r.subscribe(e=>{(e.kind===`synchronize`||e.batch.changes.some(e=>e.jobChanges.length>0))&&y()}),[r,y]);let b=(0,v.useMemo)(()=>o.find(e=>e.id===c)??null,[o,c]),x=o.filter(e=>e.scheduleType===`once`),S=o.filter(e=>e.scheduleType!==`once`),C=async()=>{if(!(!b||f||!await a(`Cancel ${b.name}? Its active schedule will be removed, while existing conversation and delivery history will remain.`))){p(!0),h(null),_(null);try{await yi(i,b.id,`workshop-job-cancel-${b.id}-${Date.now()}`),_(`${b.name} was cancelled.`),await y()}catch(e){h(e instanceof Error?e.message:`Could not cancel scheduled job.`)}finally{p(!1)}}},w=(e,t)=>t.length?(0,Q.jsxs)(`section`,{className:`scheduled-job-group`,children:[(0,Q.jsx)(`h2`,{children:e}),(0,Q.jsx)(`ul`,{children:t.map(e=>(0,Q.jsx)(`li`,{children:(0,Q.jsxs)(`button`,{className:e.id===c?`selected`:``,type:`button`,onClick:()=>l(e.id),children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.name}),(0,Q.jsx)(`span`,{className:`scheduled-job-status`,children:`Active`})]}),(0,Q.jsx)(`small`,{children:zh(e)}),(0,Q.jsxs)(`small`,{children:[e.jobType===`reminder`?`Reminder`:`Agent task`,` · `,e.agentName]})]})},e.id))})]}):null;return(0,Q.jsxs)(`main`,{className:`workspaces-workspace scheduled-jobs-workspace`,"aria-label":`Scheduled jobs`,children:[(0,Q.jsxs)(`section`,{className:`workspaces-browser-pane`,children:[(0,Q.jsxs)(`header`,{className:`workspaces-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`breadcrumbs`,children:`Kai Workshop / Scheduled jobs`}),(0,Q.jsx)(`h1`,{children:`Scheduled jobs`})]}),(0,Q.jsx)(`div`,{className:`workspaces-header-actions`,children:(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Back to conversation`,title:`Back to conversation`,onClick:n,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})})]}),(g||m)&&(0,Q.jsxs)(`div`,{className:`workspaces-notices`,"aria-live":`polite`,children:[g&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:g}),m&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:m})]}),(0,Q.jsx)(`section`,{className:`scheduled-job-catalogue`,"aria-label":`Active scheduled jobs`,children:u?(0,Q.jsx)(`p`,{className:`workspaces-empty`,children:`Loading scheduled jobs…`}):o.length===0?(0,Q.jsxs)(`div`,{className:`scheduled-jobs-empty`,children:[(0,Q.jsx)(Lh,{}),(0,Q.jsx)(`h2`,{children:`No active scheduled jobs`}),(0,Q.jsx)(`p`,{children:`Jobs created through Kai will appear here for inspection and cancellation.`})]}):(0,Q.jsxs)(Q.Fragment,{children:[w(`Upcoming`,x),w(`Recurring`,S)]})})]}),(0,Q.jsxs)(`aside`,{className:`context-pane workspace-detail scheduled-job-detail`,"aria-label":`Scheduled job detail`,children:[e&&(0,Q.jsx)(`div`,{className:`context-resize-handle`,role:`separator`,"aria-label":`Resize scheduled job detail`,"aria-orientation":`vertical`,"aria-valuemin":e.minimumWidth,"aria-valuemax":e.maximumWidth,"aria-valuenow":e.width,tabIndex:0,onKeyDown:e.onKeyDown,onPointerDown:e.onPointerDown,onPointerMove:e.onPointerMove}),(0,Q.jsx)(`div`,{className:`workspace-detail-scroll`,"aria-live":`polite`,children:b?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`workspace-detail-heading`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Selected job`}),(0,Q.jsx)(`h2`,{children:b.name})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button danger-icon-button`,type:`button`,"aria-label":`Cancel scheduled job`,title:`Cancel scheduled job`,disabled:f,onClick:()=>void C(),children:(0,Q.jsx)(Ih,{})})]}),(0,Q.jsxs)(`dl`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Status`}),(0,Q.jsx)(`dd`,{children:`Active`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Schedule`}),(0,Q.jsx)(`dd`,{children:zh(b)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Next run`}),(0,Q.jsx)(`dd`,{children:Rh(b.nextRunAt)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Created`}),(0,Q.jsx)(`dd`,{children:Rh(b.createdAt)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Type`}),(0,Q.jsx)(`dd`,{children:b.jobType===`reminder`?`Reminder`:`Agent task`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Agent`}),(0,Q.jsx)(`dd`,{children:b.agentName})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Delivery`}),(0,Q.jsxs)(`dd`,{children:[b.channelName,b.deliveryTransports.length?` · ${b.deliveryTransports.map(Bh).join(`, `)}`:``]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Auto-removal`}),(0,Q.jsx)(`dd`,{children:b.autoRemove?`Enabled`:`Disabled`})]})]}),(0,Q.jsxs)(`section`,{className:`scheduled-job-prompt`,children:[(0,Q.jsx)(`h3`,{children:`Prompt`}),(0,Q.jsx)(`p`,{children:b.prompt})]})]}):(0,Q.jsx)(`p`,{className:`workspaces-empty`,children:`Select a scheduled job.`})})]})]})}var Hh=class{token;capacity;entries=new Map;pending=new Map;principalUrls=new Map;clock=0;disposed=!1;constructor(e,t=64){if(this.token=e,this.capacity=t,!Number.isInteger(t)||t<1)throw Error(`Avatar cache capacity must be positive.`)}async load(e,t){if(this.disposed)throw Error(`Avatar cache is unavailable.`);let n=this.principalUrls.get(e);n&&n!==t&&this.evict(n),this.principalUrls.set(e,t);let r=this.entries.get(t);if(r)return r.touched=++this.clock,r.objectUrl;let i=this.pending.get(t);if(i)return i;let a=this.fetch(t).finally(()=>this.pending.delete(t));return this.pending.set(t,a),a}replace(e,t){if(this.disposed)return;let n=this.principalUrls.get(e);n&&n!==t.url&&this.evict(n),t.url?this.principalUrls.set(e,t.url):this.principalUrls.delete(e)}dispose(){this.disposed=!0;for(let e of this.entries.values())URL.revokeObjectURL(e.objectUrl);this.entries.clear(),this.pending.clear(),this.principalUrls.clear()}async fetch(e){let t=await globalThis.fetch(e,{cache:`no-store`,headers:{Authorization:`Bearer ${this.token}`}});if(!t.ok||t.headers.get(`Content-Type`)?.split(`;`,1)[0]!==`image/png`)throw Error(`Avatar image is unavailable.`);let n=URL.createObjectURL(await t.blob());if(this.disposed||![...this.principalUrls.values()].includes(e))throw URL.revokeObjectURL(n),Error(`Avatar image is no longer current.`);return this.entries.set(e,{objectUrl:n,touched:++this.clock}),this.trim(),n}trim(){for(;this.entries.size>this.capacity;){let e=[...this.entries.entries()].reduce((e,t)=>e[1].touched<=t[1].touched?e:t);this.evict(e[0])}}evict(e){let t=this.entries.get(e);t&&(URL.revokeObjectURL(t.objectUrl),this.entries.delete(e));for(let[t,n]of this.principalUrls)n===e&&this.principalUrls.delete(t)}},Uh=(0,v.createContext)(null);function Wh({children:e,token:t}){let n=(0,v.useMemo)(()=>new Hh(t),[t]),[r,i]=(0,v.useState)(()=>new Map),a=(0,v.useMemo)(()=>({cache:n,overrides:r,setOverride:(e,t)=>{n.replace(e,t),i(n=>new Map(n).set(e,t))}}),[n,r]);return(0,v.useEffect)(()=>()=>n.dispose(),[n]),(0,Q.jsx)(Uh.Provider,{value:a,children:e})}function Gh(){let e=(0,v.useContext)(Uh);if(!e)throw Error(`Human avatars require an avatar cache provider.`);return e.setOverride}function Kh({avatar:e,className:t,displayName:n,label:r,principalId:i}){let a=(0,v.useContext)(Uh);if(!a)throw Error(`Human avatars require an avatar cache provider.`);let{cache:o}=a,s=a.overrides.get(i)??e,[c,l]=(0,v.useState)(null),u=n.trim().slice(0,1).toUpperCase()||`?`;return(0,v.useEffect)(()=>{let e=!0;return l(null),o.replace(i,s),!s.active||!s.url||o.load(i,s.url).then(t=>{e&&l(t)}).catch(()=>{e&&l(null)}),()=>{e=!1}},[o,s.active,s.stateVersion,s.url,i]),(0,Q.jsx)(`span`,{className:t,"aria-hidden":r?void 0:`true`,"aria-label":r,role:r?`img`:void 0,children:c?(0,Q.jsx)(`img`,{src:c,alt:``,onError:()=>l(null)}):u})}var qh=262144,Jh=new Set([`image/png`,`image/jpeg`,`image/gif`,`image/webp`]);function Yh(e){return{...e.avatar??{active:!1,stateVersion:0,url:null},byteSize:null,height:null,mediaType:null,mutation:null,principalId:e.principalId,sha256:null,width:null}}function Xh(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M4 6h4l1.4-2h5.2L16 6h4v14H4z`}),(0,Q.jsx)(`circle`,{cx:`12`,cy:`13`,r:`3.5`}),(0,Q.jsx)(`path`,{d:`M18 3v5m-2.5-2.5h5`})]})}function Zh(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M5 7h14M9 7V4h6v3m2 0-1 13H8L7 7m3 4v5m4-5v5`})})}function Qh(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M12 5v14M5 12h14`})})}function $h(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M5 7h14M9 7V4h6v3m2 0-1 13H8L7 7m3 4v5m4-5v5`})})}function eg(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`m4 20 4.2-1 10.6-10.6-3.2-3.2L5 15.8z`}),(0,Q.jsx)(`path`,{d:`m13.8 7 3.2 3.2`})]})}var tg={off:`Text only`,text_and_voice:`Text and voice`,voice_only:`Voice only`},ng=[{id:`settings-section-personal-preferences`,label:`Personal preferences`},{id:`settings-section-github`,label:`GitHub`},{id:`settings-section-notifications`,label:`Notification delivery`},{id:`settings-section-clients`,label:`Client preferences`}],rg={id:`settings-section-administration`,label:`Administration`},ig=[{id:`settings-section-runtime`,label:`Runtime settings`},{id:`settings-section-workspace`,label:`Workspace settings`}],ag=/^(?:[01]\d|2[0-3]):[0-5]\d$/,og=[`UTC`,`America/Toronto`,`America/Vancouver`,`America/Edmonton`,`America/Winnipeg`,`America/Halifax`,`America/St_Johns`,`America/New_York`,`America/Chicago`,`America/Denver`,`America/Los_Angeles`,`Europe/London`,`Europe/Paris`,`Asia/Tokyo`,`Australia/Sydney`];function sg(e){let t=Intl.supportedValuesOf,n=[];if(t)try{n=t(`timeZone`)}catch{n=[]}return[...new Set([`UTC`,e,...n.length>0?n:og])].filter(Boolean).sort((e,t)=>e.localeCompare(t))}function cg(e){if(!e)return`Not saved yet`;let t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}var lg=[`succeeded`,`unsupported`,`failed`,`timed_out`,`malformed`,`invalidated`,`refreshing`];function ug(e,t){let n=new Map(lg.map((e,t)=>[e,t])),r=Object.entries(t).filter(([,e])=>e>0).sort(([e],[t])=>(n.get(e)??lg.length)-(n.get(t)??lg.length)||e.localeCompare(t)).map(([e,t])=>`${t} ${e.replaceAll(`_`,` `)}`).join(`, `);return`Model catalogue refresh completed across ${e} authorized contexts${r?`: ${r}`:``}.`}function dg(e,t){return e.find(e=>e.field===t)??null}function fg(e){return!e||!e.changed||e.runtimeAction===`unchanged`?`No runtime change was needed.`:e.runtimeAction===`restarted`?e.providerSessionInvalidated?`Saved. The active runtime restarted and provider-session continuity was cleared.`:`Saved. The active runtime restarted.`:`Saved. The change will apply when this runtime starts next.`}function pg(e,t){return e instanceof Error?e.message:t}function mg({agentRuntime:e=!1,executionProfileControl:t,initialSection:n=null,nativeAgentRuntime:r=!1,onAuthenticationFailure:i,onChannelAccessFailure:a,onClose:o,onDirtyChange:s,onNavigationChanged:c,onHumanAvatarChanged:l,isAdministrator:u,runtimeLabel:d,runActive:f,session:p}){let m=Km(),[h,g]=(0,v.useState)(null),[_,y]=(0,v.useState)(``),[b,x]=(0,v.useState)(null),[S,C]=(0,v.useState)(null),[w,T]=(0,v.useState)(!0),[E,D]=(0,v.useState)(!1),[O,k]=(0,v.useState)(null),[A,j]=(0,v.useState)(null),[M,N]=(0,v.useState)(null),[P,F]=(0,v.useState)(``),[I,L]=(0,v.useState)(!0),[ee,z]=(0,v.useState)(!1),[H,te]=(0,v.useState)(null),[U,re]=(0,v.useState)(null),[ie,ae]=(0,v.useState)(null),[oe,se]=(0,v.useState)(!1),[ce,le]=(0,v.useState)(null),[ue,G]=(0,v.useState)(null),K=(0,v.useRef)(null),[q,de]=(0,v.useState)(null),[J,Y]=(0,v.useState)(null),[fe,pe]=(0,v.useState)(!0),[me,he]=(0,v.useState)(!1),[X,ge]=(0,v.useState)(null),[_e,ve]=(0,v.useState)(null),[ye,be]=(0,v.useState)(null),[xe,Se]=(0,v.useState)(null),[Ce,we]=(0,v.useState)(!1),[Ee,De]=(0,v.useState)(!1),[Oe,ke]=(0,v.useState)(null),[Ae,je]=(0,v.useState)(``),[Me,Ne]=(0,v.useState)(``),[Pe,Fe]=(0,v.useState)(``),[Ie,Le]=(0,v.useState)(``),[Re,ze]=(0,v.useState)(``),[Be,Ve]=(0,v.useState)(``),[He,Ue]=(0,v.useState)(``),[We,Z]=(0,v.useState)(``),[Ge,Ke]=(0,v.useState)(!1),[qe,Je]=(0,v.useState)(``),[Ye,Xe]=(0,v.useState)(``),[Ze,Qe]=(0,v.useState)(!1),[$e,et]=(0,v.useState)(!1),[tt,nt]=(0,v.useState)(null),[rt,it]=(0,v.useState)(null),[at,ot]=(0,v.useState)(!0),[st,ct]=(0,v.useState)(!1),[lt,ut]=(0,v.useState)(null),[dt,ft]=(0,v.useState)(null),[pt,mt]=(0,v.useState)(``),[ht,gt]=(0,v.useState)(``),[_t,vt]=(0,v.useState)(null),[yt,bt]=(0,v.useState)(!0),[xt,St]=(0,v.useState)(!1),[Ct,wt]=(0,v.useState)(null),[Tt,Et]=(0,v.useState)(null),[Dt,Ot]=(0,v.useState)(null),[kt,At]=(0,v.useState)(!0),[jt,Mt]=(0,v.useState)(!1),[Nt,Pt]=(0,v.useState)(null),[Ft,It]=(0,v.useState)(null),[Lt,Rt]=(0,v.useState)(!1),[zt,Bt]=(0,v.useState)(`UTC`),[Vt,Ht]=(0,v.useState)(`22:00`),[Ut,Wt]=(0,v.useState)(`07:00`),Gt=ag.test(Vt)&&ag.test(Ut)&&Vt!==Ut,Kt=(0,v.useMemo)(()=>sg(zt),[zt]),[qt,Jt]=(0,v.useState)(null),[Yt,Xt]=(0,v.useState)(!0),[Zt,Qt]=(0,v.useState)(!1),[$t,en]=(0,v.useState)(null),[tn,nn]=(0,v.useState)(null),[rn,an]=(0,v.useState)(null),[on,sn]=(0,v.useState)(``),[cn,ln]=(0,v.useState)(!0),[un,dn]=(0,v.useState)(!1),[fn,pn]=(0,v.useState)(null),[mn,hn]=(0,v.useState)(null),[gn,_n]=(0,v.useState)(null),[vn,yn]=(0,v.useState)(u),[bn,xn]=(0,v.useState)(null),Sn=(0,v.useRef)(null),Cn=e?ig:u?[...ng,rg]:ng,[wn,Tn]=(0,v.useState)(e?`settings-section-runtime`:n===`administration`&&u?`settings-section-administration`:n===`github`?`settings-section-github`:ng[0].id),En=e&&r,Dn=En?`agent-runtime-settings-title`:`settings-title`,On=h!==null&&_!==h.content,kn=M!==null&&P.trim()!==M.displayName,An=(0,v.useMemo)(()=>new TextEncoder().encode(_).length,[_]),jn=e=>{let t=document.getElementById(e);if(!t)return;let n=typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;Tn(e),t.scrollIntoView?.({behavior:n?`auto`:`smooth`,block:`start`})};(0,v.useEffect)(()=>{!e&&n!==null&&jn(`settings-section-${n}`)},[e,n,u]);let Mn=()=>{let e=Sn.current;if(!e)return;let t=Cn.flatMap(e=>{let t=document.getElementById(e.id);return t?[{item:e,element:t}]:[]});if(t.length===0)return;if(e.scrollTop+e.clientHeight>=e.scrollHeight-2){Tn(t[t.length-1].item.id);return}let n=e.getBoundingClientRect().top+32,r=t[0].item.id;for(let e of t){if(e.element.getBoundingClientRect().top>n)break;r=e.item.id}Tn(r)},Nn=(0,v.useCallback)(e=>e instanceof B?(i(e.message),!0):e instanceof V&&(a(e.message),!0),[i,a]),Pn=(0,v.useCallback)(e=>{g(e),y(e.content),C(null)},[]),Fn=(0,v.useCallback)(async()=>{x(await kr(p))},[p]),In=(0,v.useCallback)(async()=>{T(!0),k(null);try{let[e,t]=await Promise.all([Tr(p),kr(p)]);Pn(e),x(t)}catch(e){Nn(e)||k(pg(e,`Could not load personal preferences.`))}finally{T(!1)}},[Pn,Nn,p]),Ln=(0,v.useCallback)(async()=>{L(!0),te(null),le(null);try{let e=await dr(p);N(e),F(e.displayName);try{ae(await fr(p))}catch(t){ae(Yh(e)),Nn(t)||le(`Your avatar is temporarily unavailable. Showing your initial instead.`)}}catch(e){Nn(e)||te(pg(e,`Could not load your profile.`))}finally{L(!1)}},[Nn,p]),Rn=(0,v.useCallback)(e=>{de(e),Fe(e.backendOptionId),Le(e.model.value),ze(String(e.timeoutSeconds.value))},[]),zn=(0,v.useCallback)(e=>{Y(e),Ve(e.model.value),Ue(String(e.timeoutSeconds.value)),Z(e.prompt??``)},[]),Bn=(0,v.useCallback)(async()=>{pe(!0),ge(null),ve(null);try{let e=await Vn(p);Rn(e)}catch(e){Nn(e)||ge(pg(e,`Could not load runtime settings.`)),de(null),Y(null),pe(!1);return}try{zn(await vr(p))}catch(e){e instanceof B?i(e.message):(Y(null),ve(pg(e,`Could not load workspace settings.`)))}finally{pe(!1)}},[Rn,zn,Nn,i,p]);(0,v.useEffect)(()=>{if(!q||!Pe){Se(null);return}let e=!1;return we(!0),ke(null),Gn(p,Pe).then(t=>{e||Se(t)}).catch(t=>{!e&&!Nn(t)&&ke(pg(t,`Could not load the model catalogue.`))}).finally(()=>{e||we(!1)}),()=>{e=!0}},[Nn,q,Pe,p]);let Hn=async()=>{if(Pe){De(!0),ke(null);try{let e=await Kn(p,Pe);Se(e),Pe===q?.backendOptionId&&Rn(await Vn(p))}catch(e){Nn(e)||ke(pg(e,`Could not refresh the model catalogue.`))}finally{De(!1)}}},Un=async()=>{De(!0),ke(null);try{let e=await qn(p);be(ug(e.contexts,e.statuses)),Se(await Gn(p,Pe))}catch(e){Nn(e)||ke(pg(e,`Could not refresh all model catalogues.`))}finally{De(!1)}},Wn=async()=>{if(!(!Ae.trim()||!Me.trim())){De(!0),ke(null);try{Se(await Jn(p,Pe,Ae.trim(),Me.trim())),je(``),Ne(``)}catch(e){Nn(e)||ke(pg(e,`Could not save the operator model.`))}finally{De(!1)}}},Qn=async e=>{if(await m(`Deactivate operator model ${e}?`)){De(!0),ke(null);try{Se(await Yn(p,Pe,e))}catch(e){Nn(e)||ke(pg(e,`Could not deactivate the operator model.`))}finally{De(!1)}}},$n=(0,v.useCallback)(async()=>{ot(!0),ut(null);try{it(await Xn(p))}catch(e){Nn(e)||ut(pg(e,`Could not load GitHub settings.`))}finally{ot(!1)}},[Nn,p]),er=(0,v.useCallback)(async()=>{bt(!0),wt(null);try{vt(await ir(p))}catch(e){Nn(e)||wt(pg(e,`Could not load notification preferences.`))}finally{bt(!1)}},[Nn,p]),tr=(0,v.useCallback)(async()=>{At(!0),Pt(null);try{let e=await or(p);Ot(e),Rt(e.doNotDisturb.enabled),Bt(e.doNotDisturb.timezone),Ht(e.doNotDisturb.start),Wt(e.doNotDisturb.end)}catch(e){Nn(e)||Pt(pg(e,`Could not load channel notification policy.`))}finally{At(!1)}},[Nn,p]),nr=(0,v.useCallback)(async()=>{Xt(!0),en(null);try{Jt(await cr(p))}catch(e){Nn(e)||en(pg(e,`Could not load client preferences.`))}finally{Xt(!1)}},[Nn,p]),rr=(0,v.useCallback)(async()=>{ln(!0),pn(null);try{let e=await lr(p);an(e),sn(e.themeId),R(e.themeId)}catch(e){Nn(e)||pn(pg(e,`Could not load appearance preferences.`))}finally{ln(!1)}},[Nn,p]),yr=(0,v.useCallback)(async()=>{if(!u){_n(null),yn(!1);return}yn(!0),xn(null);try{_n(await Te(p))}catch(e){Nn(e)||xn(pg(e,`Could not load webhook diagnostics.`))}finally{yn(!1)}},[Nn,u,p]);(0,v.useEffect)(()=>{e?Bn():(In(),Ln(),$n(),er(),tr(),nr(),rr(),u&&yr())},[e,rr,nr,$n,tr,er,In,Ln,Bn,yr,u]),(0,v.useEffect)(()=>(s(On||kn),()=>s(!1)),[s,On,kn]),(0,v.useEffect)(()=>{if(!On&&!kn)return;let e=e=>{e.preventDefault(),e.returnValue=``};return window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e)},[On,kn]);let br=async()=>{if(!(!M||!kn)){z(!0),te(null),re(null);try{let e=globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`profile-${Date.now()}-${Math.random().toString(16).slice(2)}`,t=await hr(p,P,M.stateVersion,e);N(t),F(t.displayName),re(t.mutation?.changed?`Display name saved.`:`No change was needed.`),await c?.()}catch(e){e instanceof W?(await Ln(),te(`Your profile changed elsewhere. The latest display name has been reloaded.`)):Nn(e)||te(pg(e,`Could not save your display name.`))}finally{z(!1)}}},xr=async e=>{if(!(!ie||oe)){if(le(null),G(null),!Jh.has(e.type)){le(`Choose a PNG, JPEG, GIF, or WebP image.`);return}if(e.size>qh){le(`Avatar images must be no larger than 256 KiB.`);return}se(!0);try{let t=globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`avatar-${Date.now()}-${Math.random().toString(16).slice(2)}`,n=await pr(p,e,ie.stateVersion,t);ae(n),N(e=>e&&{...e,avatar:n}),l?.(n.principalId,n),G(`Avatar saved.`),await c?.()}catch(e){e instanceof W?(await Ln(),le(`Your avatar changed elsewhere. The latest image has been reloaded.`)):Nn(e)||le(pg(e,`Could not save your avatar.`))}finally{se(!1),K.current&&(K.current.value=``)}}},Er=async()=>{if(!(!ie||!ie.active||oe)){se(!0),le(null),G(null);try{let e=globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`avatar-clear-${Date.now()}-${Math.random().toString(16).slice(2)}`,t=await mr(p,ie.stateVersion,e);ae(t),N(e=>e&&{...e,avatar:t}),l?.(t.principalId,t),G(`Avatar cleared.`),await c?.()}catch(e){e instanceof W?(await Ln(),le(`Your avatar changed elsewhere. The latest image has been reloaded.`)):Nn(e)||le(pg(e,`Could not clear your avatar.`))}finally{se(!1)}}},Dr=async(e=h?.revision??``)=>{if(!(!h||An>h.maxBytes)){D(!0),k(null),j(null);try{let t=await Or(p,_,e);Pn(t),await Fn(),j(`Preferences saved. They will apply to the next eligible agent turn.`)}catch(e){if(e instanceof ne)try{let e=await Tr(p);C(e),k(`Preferences changed in another session. Compare both versions before choosing what to keep.`)}catch(t){Nn(t)||k(pg(t,e.message))}else Nn(e)||k(pg(e,`Could not save preferences.`))}finally{D(!1)}}},Mr=async e=>{if(!(!h||!await m(`Restore this private preference revision? The current text will be retained in revision history.`))){D(!0),k(null),j(null);try{let t=await Ar(p,e,h.revision);Pn(t),await Fn(),j(`Preference revision restored.`)}catch(e){e instanceof ne?k(`Preferences changed before the restore. Reload and review the latest revision.`):Nn(e)||k(pg(e,`Could not restore preferences.`))}finally{D(!1)}}},Nr=async(e,t)=>{if(!(!q||!await m(t))){he(!0),ge(null),be(null);try{let t=await _r(p,q.revision,e);Rn(t),zn(await vr(p)),be(fg(t.mutation))}catch(t){e.field===`backend`&&Fe(q.backendOptionId),t instanceof W?(await Bn(),ge(`Runtime settings changed elsewhere. The latest values have been reloaded.`)):Nn(t)||ge(pg(t,`Could not update runtime settings.`))}finally{he(!1)}}},Pr=async(e,t)=>{if(!(!J||!await m(t))){he(!0),ge(null),be(null);try{let t=await Sr(p,J.revision,e);zn(t),Rn(await Vn(p)),be(fg(t.mutation))}catch(e){e instanceof W?(await Bn(),ge(`Workspace settings changed elsewhere. The latest values have been reloaded.`)):Nn(e)||ge(pg(e,`Could not update workspace settings.`))}finally{he(!1)}}},Fr=e=>{Je(e??``),Xe(``),Qe(e!==null),nt(null),Ke(!0)},Ir=async()=>{if(!(!J||$e||!qe.trim()||!Ye)){et(!0),nt(null),be(null);try{let e=await Cr(p,J.revision,qe.trim(),Ye);zn(e),Rn(await Vn(p)),be(fg(e.mutation)),Ke(!1),Je(``),Xe(``),Qe(!1)}catch(e){e instanceof W?(await Bn(),nt(`Workspace secrets changed elsewhere. Reopen this form and enter the value again.`),Xe(``)):Nn(e)||nt(pg(e,`Could not save workspace secret.`))}finally{et(!1)}}},Lr=async e=>{if(!(!J||$e||!await m(`Remove ${e} from this workspace? The active runtime may restart.`))){et(!0),nt(null),be(null);try{let t=await wr(p,J.revision,e);zn(t),Rn(await Vn(p)),be(fg(t.mutation))}catch(e){e instanceof W?(await Bn(),nt(`Workspace secrets changed elsewhere. The latest state has been loaded.`)):Nn(e)||nt(pg(e,`Could not remove workspace secret.`))}finally{et(!1)}}},Rr=async(e,t=null)=>{if(!rt||t!==null&&!await m(t))return!1;ct(!0),ut(null),ft(null);try{let t=await Zn(p,rt.revision,e);return it(t),gt(``),ft(t.mutation?.changed?`GitHub settings saved.`:`No change was needed.`),!0}catch(e){return gt(``),e instanceof W?(await $n(),ut(`GitHub settings changed elsewhere. The latest values have been reloaded.`)):Nn(e)||ut(pg(e,`Could not update GitHub settings.`)),!1}finally{ct(!1)}},zr=async(e,t=null)=>{if(!(!_t||t!==null&&!await m(t))){St(!0),wt(null),Et(null);try{let t=await ar(p,_t.revision,e);vt(t),Et(t.mutation?.changed?`Notification destination saved.`:`No change was needed.`)}catch(e){e instanceof W?(await er(),wt(`Notification preferences changed elsewhere. The latest values have been reloaded.`)):Nn(e)||wt(pg(e,`Could not update notification preferences.`))}finally{St(!1)}}},Br=async e=>{if(Dt){Mt(!0),Pt(null),It(null);try{let t=await sr(p,Dt.revision,e);Ot(t),Rt(t.doNotDisturb.enabled),Bt(t.doNotDisturb.timezone),Ht(t.doNotDisturb.start),Wt(t.doNotDisturb.end),It(t.mutation?.changed?`Channel notification policy saved.`:`No change was needed.`)}catch(e){e instanceof W?(await tr(),Pt(`Channel notification policy changed elsewhere. The latest values have been reloaded.`)):Nn(e)||Pt(pg(e,`Could not update channel notification policy.`))}finally{Mt(!1)}}},Vr=async e=>{if(qt){Qt(!0),en(null),nn(null);try{let t=await gr(p,qt.revision,e);Jt(t),nn(t.mutation?.changed?`Client preference saved.`:`No change was needed.`)}catch(e){e instanceof W?(await nr(),en(`Client preferences changed elsewhere. The latest values have been reloaded.`)):Nn(e)||en(pg(e,`Could not update client preferences.`))}finally{Qt(!1)}}},Hr=async e=>{if(!rn)return;let t=rn.themeId;sn(e),R(e),dn(!0),pn(null),hn(null);try{let t=await ur(p,rn.revision,e);an(t),sn(t.themeId),R(t.themeId),hn(t.mutation?.changed?`Workshop appearance saved.`:`No change was needed.`)}catch(e){e instanceof W?(await rr(),pn(`Appearance preferences changed elsewhere. The latest value has been reloaded.`)):(sn(t),R(t),Nn(e)||pn(pg(e,`Could not update appearance preferences.`)))}finally{dn(!1)}},Ur=async e=>{if(!(!q||e===q.workspace||!await m(`Switch the active workspace? An active runtime may restart and provider-session continuity may be cleared.`))){he(!0),ge(null),be(null);try{let t=await jr(p,e,q.revision);Rn(t),zn(await vr(p)),be(fg(t.mutation))}catch(e){e instanceof W?(await Bn(),ge(`Workspace selection changed elsewhere. The latest state has been reloaded.`)):Nn(e)||ge(pg(e,`Could not switch workspace.`))}finally{he(!1)}}},Wr=q?dg(q.capabilities,`backend`):null,Gr=q?dg(q.capabilities,`model`):null,Kr=q?dg(q.capabilities,`timeout`):null,qr=J?dg(J.capabilities,`model`):null,Jr=J?dg(J.capabilities,`timeout`):null,Yr=J?dg(J.capabilities,`prompt`):null,Xr=q?q.workspaces.findIndex(e=>e.path===q.workspace):-1,Zr=(e,t,n,r)=>n?(0,Q.jsx)(`select`,{id:e,value:t,onChange:e=>r(e.target.value),children:n.map(e=>{let t=q?.modelOptions?.find(t=>t.modelId===e),n=t?.retained&&!t.selectable?` · not currently advertised`:``;return(0,Q.jsxs)(`option`,{value:e,disabled:t?!t.selectable:!1,children:[t?.displayName??e,n]},e)})}):(0,Q.jsx)(`input`,{id:e,type:`text`,value:t,onChange:e=>r(e.target.value)});return(0,Q.jsxs)(`section`,{className:En?`agent-runtime-controls`:`settings-workspace`,"aria-labelledby":En?void 0:Dn,"aria-label":En?`${d} runtime and workspace settings`:void 0,id:En?`agent-runtime-settings`:void 0,children:[!En&&(0,Q.jsxs)(`header`,{className:`settings-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`breadcrumbs`,children:e?`Agent runtime`:`Kai Workshop / Settings`}),(0,Q.jsx)(`h1`,{id:Dn,children:e?`${d} settings`:`Settings`})]}),!En&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":e?`Back to agent`:`Back to conversation`,title:e?`Back to agent`:`Back to conversation`,onClick:o,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})]}),!En&&(0,Q.jsx)(`nav`,{className:`settings-section-navigation`,"aria-label":`Settings sections`,children:(0,Q.jsx)(`div`,{children:Cn.map(e=>(0,Q.jsx)(`button`,{type:`button`,"aria-current":wn===e.id?`location`:void 0,onClick:()=>jn(e.id),children:e.label},e.id))})}),(0,Q.jsxs)(`div`,{className:En?`agent-runtime-controls-body`:`settings-scroll`,ref:En?void 0:Sn,onScroll:En?void 0:Mn,children:[!e&&(0,Q.jsxs)(`section`,{className:`settings-intro`,id:`settings-section-personal-preferences`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`section-number`,children:`01`}),(0,Q.jsx)(`h2`,{children:`Personal preferences`}),(0,Q.jsx)(`p`,{children:`Your Workshop profile and principal-wide guidance supplied to your agents.`})]}),(0,Q.jsxs)(`div`,{className:`settings-card-stack settings-personal-preferences`,children:[I?(0,Q.jsx)(`p`,{role:`status`,children:`Loading profile…`}):M?(0,Q.jsxs)(`form`,{className:`settings-card`,onSubmit:e=>{e.preventDefault(),br()},children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Profile`}),ie&&(0,Q.jsxs)(`div`,{className:`profile-avatar-editor`,children:[(0,Q.jsx)(Kh,{avatar:ie,className:`profile-avatar-preview`,displayName:P||M.displayName,label:`Your profile avatar`,principalId:M.principalId}),(0,Q.jsxs)(`div`,{className:`profile-avatar-actions`,children:[(0,Q.jsx)(`input`,{ref:K,className:`visually-hidden`,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,disabled:oe,"aria-label":`Choose avatar image`,onChange:e=>{let t=e.target.files?.[0];t&&xr(t)}}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":ie.active?`Change avatar`:`Add avatar`,title:ie.active?`Change avatar`:`Add avatar`,disabled:oe,onClick:()=>K.current?.click(),children:(0,Q.jsx)(Xh,{})}),ie.active&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Clear avatar`,title:`Clear avatar`,disabled:oe,onClick:()=>void Er(),children:(0,Q.jsx)(Zh,{})}),(0,Q.jsx)(`span`,{children:oe?`Saving…`:`PNG, JPEG, GIF, or WebP · 256 KiB max`})]})]}),(0,Q.jsx)(`label`,{htmlFor:`profile-display-name`,children:`Display name`}),(0,Q.jsx)(`input`,{id:`profile-display-name`,type:`text`,maxLength:200,value:P,disabled:ee,onChange:e=>{F(e.target.value),re(null)}}),(0,Q.jsxs)(`p`,{className:`settings-help`,children:[`Your name is shown throughout Workshop. Your unique handle remains @`,M.handle,`.`]}),(0,Q.jsx)(`div`,{className:`settings-actions`,children:(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:ee||!kn||P.trim().length===0,children:ee?`Saving…`:`Save display name`})}),U&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:U}),ue&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:ue}),H&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:H}),ce&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:ce})]}):(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:H??`Profile is unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void Ln(),children:`Retry`})]}),w?(0,Q.jsx)(`p`,{role:`status`,children:`Loading preferences…`}):h?(0,Q.jsxs)(`div`,{className:`preference-editor-card`,children:[(0,Q.jsx)(`label`,{htmlFor:`personal-preferences`,children:`Preference Markdown`}),(0,Q.jsx)(`textarea`,{id:`personal-preferences`,value:_,readOnly:!h.editable,disabled:E,onChange:e=>{y(e.target.value),j(null)},rows:14,spellCheck:!0}),(0,Q.jsxs)(`div`,{className:`preference-editor-meta`,children:[(0,Q.jsxs)(`span`,{children:[An.toLocaleString(),` / `,h.maxBytes.toLocaleString(),` bytes`]}),(0,Q.jsxs)(`span`,{children:[`Updated `,cg(h.updatedAt)]}),(0,Q.jsx)(`span`,{children:On?`Unsaved changes`:`Saved`})]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`button`,disabled:E||!h.editable||!On||An>h.maxBytes,onClick:()=>void Dr(),children:E?`Saving…`:`Save preferences`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:E||!On,onClick:()=>y(h.content),children:`Discard changes`})]}),An>h.maxBytes&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:`Preference text exceeds the protected size limit.`}),A&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:A}),O&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:O})]}):(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:O??`Preferences are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void In(),children:`Retry`})]}),S&&h&&(0,Q.jsxs)(`section`,{className:`preference-conflict`,"aria-labelledby":`preference-conflict-title`,children:[(0,Q.jsx)(`h3`,{id:`preference-conflict-title`,children:`Review concurrent changes`}),(0,Q.jsx)(`p`,{children:`Your draft remains untouched. Compare it with the latest saved text before replacing either version.`}),(0,Q.jsxs)(`div`,{className:`preference-compare`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`Your draft`}),(0,Q.jsx)(`pre`,{children:_})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`Latest saved`}),(0,Q.jsx)(`pre`,{children:S.content})]})]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>Pn(S),children:`Use latest saved`}),(0,Q.jsx)(`button`,{className:`primary-button`,type:`button`,disabled:E,onClick:()=>void(async()=>{await m(`Replace the latest saved preferences with your reviewed draft?`)&&Dr(S.revision)})(),children:`Reapply my draft…`})]})]}),b&&b.revisions.length>0&&(0,Q.jsxs)(`details`,{className:`preference-history`,children:[(0,Q.jsxs)(`summary`,{children:[`Private revision history (`,b.revisions.length,`)`]}),(0,Q.jsx)(`ol`,{children:b.revisions.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:cg(e.updatedAt)}),(0,Q.jsxs)(`small`,{children:[e.sizeBytes.toLocaleString(),` bytes`]})]}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:E||e.revision===h?.revision,onClick:()=>void Mr(e.revision),children:`Restore…`})]},e.revision))})]})]})]}),e&&(0,Q.jsxs)(`section`,{className:`settings-section`,id:`settings-section-runtime`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{children:`Runtime settings`}),(0,Q.jsxs)(`p`,{children:[`These controls apply only to `,d,`.`,` `,`Changes can restart an active runtime and clear provider-session continuity.`]})]}),fe?(0,Q.jsx)(`p`,{role:`status`,children:`Loading runtime policy…`}):q?(0,Q.jsxs)(`div`,{className:`settings-card-stack`,children:[t,(0,Q.jsxs)(`div`,{className:`settings-card-columns`,children:[(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[Wr&&(0,Q.jsxs)(`form`,{className:`settings-card`,onSubmit:e=>{e.preventDefault(),Nr({field:`backend`,value:Pe},`Switch backend? Your current provider session will end. Your next message will start on the selected backend; other people and Kai itself will not restart.`)},children:[(0,Q.jsx)(`label`,{htmlFor:`runtime-backend`,children:`Backend`}),(0,Q.jsx)(`select`,{id:`runtime-backend`,value:Pe,disabled:me||f,onChange:e=>Fe(e.target.value),children:q.backendOptions.map(e=>(0,Q.jsxs)(`option`,{value:e.optionId,children:[e.backend,` · `,e.provider]},e.optionId))}),(0,Q.jsxs)(`p`,{children:[`Active: `,(0,Q.jsx)(`strong`,{children:q.backend}),` · `,q.provider]}),(0,Q.jsx)(`p`,{children:f?`Finish or stop the active run before switching.`:`Only your runtime lane and provider session are replaced. If sign-in is required, your next message will explain how; you can switch back here immediately.`}),(0,Q.jsx)(`div`,{className:`settings-actions`,children:(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:me||f||Pe===q.backendOptionId,children:`Switch backend`})})]}),Gr&&(0,Q.jsxs)(`form`,{className:`settings-card`,onSubmit:e=>{e.preventDefault(),Nr({field:`model`,value:Ie},`Change the runtime model? The active runtime may restart and provider-session continuity will be cleared.`)},children:[(0,Q.jsx)(`label`,{htmlFor:`runtime-model`,children:`Runtime model`}),Zr(`runtime-model`,Ie,Gr.choices,Le),(0,Q.jsxs)(`p`,{children:[`Effective: `,(0,Q.jsx)(`strong`,{children:q.model.value}),` · `,q.model.source]}),(0,Q.jsxs)(`p`,{children:[`Policy default: `,q.model.defaultValue]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:me||Ie===q.model.value,children:`Apply`}),Gr.resettable&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:me||q.model.source===`runtime policy`,onClick:()=>void Nr({field:`reset`,value:`model`},`Reset the runtime model to protected policy? The active runtime may restart.`),children:`Reset`})]})]})]}),(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[(0,Q.jsxs)(`article`,{className:`settings-card policy-card`,children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Policy-controlled`}),(0,Q.jsx)(`dl`,{children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Authorized choices`}),(0,Q.jsx)(`dd`,{children:q.backendOptions.length})]})}),(0,Q.jsx)(`p`,{children:`Credentials, identity mappings, executable paths, assignments, and workspace grants remain operator managed.`})]}),Kr&&(0,Q.jsxs)(`form`,{className:`settings-card`,onSubmit:e=>{e.preventDefault(),Nr({field:`timeout`,value:Number(Re)},`Change the response timeout? The active runtime may restart and provider-session continuity will be cleared.`)},children:[(0,Q.jsx)(`label`,{htmlFor:`runtime-timeout`,children:`Response timeout`}),(0,Q.jsxs)(`div`,{className:`settings-number-input`,children:[(0,Q.jsx)(`input`,{id:`runtime-timeout`,type:`number`,min:Kr.minimum??void 0,max:Kr.maximum??void 0,value:Re,onChange:e=>ze(e.target.value)}),(0,Q.jsx)(`span`,{children:`seconds`})]}),(0,Q.jsxs)(`p`,{children:[`Effective: `,(0,Q.jsxs)(`strong`,{children:[q.timeoutSeconds.value,`s`]}),` · `,q.timeoutSeconds.source]}),(0,Q.jsxs)(`p`,{children:[`Allowed: `,Kr.minimum,`–`,Kr.maximum,`s`]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:me||!Re||Number(Re)===q.timeoutSeconds.value,children:`Apply`}),Kr.resettable&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:me||q.timeoutSeconds.source===`runtime policy`,onClick:()=>void Nr({field:`reset`,value:`timeout`},`Reset the timeout to protected policy? The active runtime may restart.`),children:`Reset`})]})]})]})]}),(0,Q.jsxs)(`details`,{className:`settings-card model-catalogue-card`,children:[(0,Q.jsxs)(`summary`,{"aria-label":`Model catalogue details`,children:[(0,Q.jsxs)(`span`,{className:`model-catalogue-summary-heading`,children:[(0,Q.jsx)(`span`,{className:`settings-card-label`,children:`Model catalogue`}),(0,Q.jsx)(`span`,{children:`Provider metadata and operator-managed choices`})]}),(0,Q.jsxs)(`span`,{className:`model-catalogue-summary-status`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Backend`}),xe?.optionId??q.backendOptionId]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Models`}),xe?xe.models.length:`—`]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Status`}),Ce?`Loading`:xe?`${xe.refresh?.status??`Not refreshed`}${xe.stale?` · stale`:``}`:`Unavailable`]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Last refresh`}),cg(xe?.refresh?.lastSuccessfulRefreshAt??null)]})]}),(0,Q.jsx)(`span`,{className:`model-catalogue-disclosure`,"aria-hidden":`true`,children:`⌄`})]}),(0,Q.jsxs)(`div`,{className:`model-catalogue-body`,children:[(0,Q.jsx)(`p`,{children:`Refreshes inspect provider metadata only. They never run a model, change your selected model, or interrupt active work.`}),Ce?(0,Q.jsx)(`p`,{role:`status`,children:`Loading catalogue…`}):xe?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`ul`,{className:`model-catalogue-list`,children:xe.models.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:e.displayName}),(0,Q.jsx)(`code`,{children:e.modelId}),(0,Q.jsxs)(`small`,{children:[e.status.replaceAll(`_`,` `),e.retained?` · retained selection`:``]}),u&&e.sources.includes(`operator`)&&(0,Q.jsx)(`button`,{className:`model-catalogue-remove`,type:`button`,disabled:Ee,onClick:()=>void Qn(e.modelId),children:`Deactivate operator entry`})]},e.modelId))}),xe.refresh?.errorDetail&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:xe.refresh.errorDetail})]}):null,(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:Ee||Ce,onClick:()=>void Hn(),children:Ee?`Refreshing…`:`Refresh models`}),u&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:Ee||Ce,onClick:()=>void Un(),children:`Refresh all contexts`})]}),u&&(0,Q.jsxs)(`form`,{className:`model-catalogue-operator-form`,onSubmit:e=>{e.preventDefault(),Wn()},children:[(0,Q.jsx)(`label`,{htmlFor:`operator-model-id`,children:`Operator-managed model ID`}),(0,Q.jsx)(`input`,{id:`operator-model-id`,type:`text`,value:Ae,onChange:e=>je(e.target.value)}),(0,Q.jsx)(`label`,{htmlFor:`operator-model-label`,children:`Display label`}),(0,Q.jsx)(`input`,{id:`operator-model-label`,type:`text`,value:Me,onChange:e=>Ne(e.target.value)}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`submit`,disabled:Ee||!Ae.trim()||!Me.trim(),children:`Add or update`})]}),Oe&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:Oe})]})]})]}):(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:X??`Runtime settings are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void Bn(),children:`Retry`})]}),ye&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:ye}),X&&q&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:X})]}),e&&q&&J&&(0,Q.jsxs)(`section`,{className:`settings-section`,id:`settings-section-workspace`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{children:`Workspace settings`}),(0,Q.jsx)(`p`,{children:`Choose the workspace this agent uses and manage overrides that apply only within it.`})]}),(0,Q.jsxs)(`div`,{className:`workspace-settings-heading`,children:[(0,Q.jsx)(`label`,{htmlFor:`settings-workspace`,children:`Active workspace`}),(0,Q.jsx)(`select`,{id:`settings-workspace`,value:String(Xr),disabled:me,onChange:e=>{let t=q.workspaces[Number(e.target.value)];t&&Ur(t.path)},children:q.workspaces.map((e,t)=>(0,Q.jsx)(`option`,{value:String(t),children:e.name},e.path))})]}),(0,Q.jsx)(`div`,{className:`settings-card-stack workspace-overrides`,children:(0,Q.jsxs)(`div`,{className:`settings-card-columns`,children:[(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[qr&&(0,Q.jsxs)(`form`,{className:`settings-card`,onSubmit:e=>{e.preventDefault(),Pr({field:`model`,value:Be},`Apply this model only to the active workspace? The active runtime may restart.`)},children:[(0,Q.jsx)(`label`,{htmlFor:`workspace-model`,children:`Workspace model override`}),Zr(`workspace-model`,Be,qr.choices,Ve),(0,Q.jsxs)(`p`,{children:[`Effective: `,(0,Q.jsx)(`strong`,{children:J.model.value}),` · `,J.model.source]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:me||Be===J.model.value,children:`Apply`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:me||!J.overrideFields.includes(`model`),onClick:()=>void Pr({field:`reset`,value:`model`},`Remove this workspace model override?`),children:`Reset`})]})]}),Yr&&(0,Q.jsxs)(`form`,{className:`settings-card prompt-card`,onSubmit:e=>{e.preventDefault(),Pr({field:`prompt`,value:We},`Apply this system prompt only to the active workspace? The active runtime may restart.`)},children:[(0,Q.jsx)(`label`,{htmlFor:`workspace-prompt`,children:`Workspace system prompt`}),(0,Q.jsx)(`textarea`,{id:`workspace-prompt`,rows:7,maxLength:Yr.maximum??void 0,value:We,onChange:e=>Z(e.target.value)}),(0,Q.jsx)(`p`,{children:J.hasPrompt?`Effective source: ${J.promptSource??`workspace`}`:`No workspace prompt is active.`}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:me||We===(J.prompt??``),children:`Apply`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:me||!J.overrideFields.includes(`prompt`),onClick:()=>void Pr({field:`reset`,value:`prompt`},`Remove this workspace prompt override?`),children:`Reset`})]})]})]}),(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[Jr&&(0,Q.jsxs)(`form`,{className:`settings-card`,onSubmit:e=>{e.preventDefault(),Pr({field:`timeout`,value:He},`Apply this timeout only to the active workspace? The active runtime may restart.`)},children:[(0,Q.jsx)(`label`,{htmlFor:`workspace-timeout`,children:`Workspace timeout override`}),(0,Q.jsxs)(`div`,{className:`settings-number-input`,children:[(0,Q.jsx)(`input`,{id:`workspace-timeout`,type:`number`,min:Jr.minimum??void 0,max:Jr.maximum??void 0,value:He,onChange:e=>Ue(e.target.value)}),(0,Q.jsx)(`span`,{children:`seconds`})]}),(0,Q.jsxs)(`p`,{children:[`Effective: `,(0,Q.jsxs)(`strong`,{children:[J.timeoutSeconds.value,`s`]}),` · `,J.timeoutSeconds.source]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:me||!He||Number(He)===J.timeoutSeconds.value,children:`Apply`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:me||!J.overrideFields.includes(`timeout`),onClick:()=>void Pr({field:`reset`,value:`timeout`},`Remove this workspace timeout override?`),children:`Reset`})]})]}),(0,Q.jsxs)(`article`,{className:`settings-card workspace-secret-card`,children:[(0,Q.jsxs)(`div`,{className:`workspace-secret-heading`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Workspace secrets`}),(0,Q.jsx)(`p`,{children:`Values are write-only and apply only to this workspace.`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Add workspace secret`,title:`Add workspace secret`,disabled:me||$e||J.environmentVariables.length>=J.environmentPolicy.maximumKeys,onClick:()=>Fr(null),children:(0,Q.jsx)(Qh,{})})]}),J.environmentVariables.length>0?(0,Q.jsx)(`ul`,{className:`workspace-secret-list`,children:J.environmentVariables.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.key}),(0,Q.jsx)(`small`,{children:e.provenance===`operator`?`Operator managed`:e.provenance===`principal_override`?`Personal override of operator policy`:`Managed by you`})]}),(0,Q.jsxs)(`span`,{className:`workspace-secret-actions`,children:[e.editable&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Replace ${e.key}`,title:`Replace ${e.key}`,disabled:$e,onClick:()=>Fr(e.key),children:(0,Q.jsx)(eg,{})}),e.removable&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Remove ${e.key}`,title:`Remove ${e.key}`,disabled:$e,onClick:()=>void Lr(e.key),children:(0,Q.jsx)($h,{})})]})]},e.key))}):(0,Q.jsx)(`p`,{children:`No workspace secrets configured.`}),tt&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:tt})]})]})]})})]}),Ge&&J&&(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog workspace-creation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`workspace-secret-title`,children:[(0,Q.jsxs)(`header`,{className:`workspace-creation-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Write-only value`}),(0,Q.jsx)(`h2`,{id:`workspace-secret-title`,children:Ze?`Replace workspace secret`:`Add workspace secret`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close workspace secret entry`,title:`Close workspace secret entry`,disabled:$e,onClick:()=>{Ke(!1),Je(``),Xe(``),Qe(!1),nt(null)},children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsx)(`p`,{children:`Kai stores the value without returning it to this or any other client.`}),(0,Q.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),Ir()},children:[(0,Q.jsx)(`label`,{htmlFor:`workspace-secret-key`,children:`Environment key`}),(0,Q.jsx)(`input`,{id:`workspace-secret-key`,type:`text`,autoFocus:!Ze,autoComplete:`off`,spellCheck:!1,maxLength:J.environmentPolicy.maximumKeyCharacters,value:qe,disabled:$e||Ze,onChange:e=>Je(e.target.value)}),(0,Q.jsx)(`label`,{htmlFor:`workspace-secret-value`,children:`Secret value`}),(0,Q.jsx)(`input`,{id:`workspace-secret-value`,type:`password`,autoFocus:Ze,autoComplete:`new-password`,value:Ye,disabled:$e,onChange:e=>Xe(e.target.value)}),tt&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:tt}),(0,Q.jsx)(`div`,{className:`form-actions`,children:(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:$e||!qe.trim()||!Ye,children:$e?`Saving…`:Ze?`Replace secret`:`Add secret`})})]})]})}),e&&q&&!J&&!fe&&(0,Q.jsxs)(`section`,{className:`settings-section`,id:`settings-section-workspace`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{children:`Workspace settings`}),(0,Q.jsx)(`p`,{children:`Runtime settings remain available, but workspace-specific overrides could not be loaded.`})]}),(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:_e??`Workspace settings are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void Bn(),children:`Retry`})]})]}),!e&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`section`,{className:`settings-section`,id:`settings-section-github`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`section-number`,children:`02`}),(0,Q.jsx)(`h2`,{children:`GitHub`}),(0,Q.jsx)(`p`,{children:`Personal notification subscriptions, automation choices, and a write-only access token. Repository execution authority remains operator controlled.`})]}),at?(0,Q.jsx)(`p`,{role:`status`,children:`Loading GitHub settings…`}):rt?(0,Q.jsxs)(`div`,{className:`settings-card-columns github-settings-grid`,children:[(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[(0,Q.jsxs)(`article`,{className:`settings-card policy-card`,children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Protected identity`}),(0,Q.jsx)(`dl`,{children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`GitHub login`}),(0,Q.jsx)(`dd`,{children:rt.githubLogin??`Not configured`})]})}),(0,Q.jsx)(`p`,{children:`This identity is operator managed and is used for GitHub actor routing.`})]}),(0,Q.jsxs)(`article`,{className:`settings-card`,children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Automation`}),(0,Q.jsxs)(`div`,{className:`github-toggle-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`PR reviews`}),(0,Q.jsxs)(`p`,{children:[rt.prReview.enabled?`On`:`Off`,` · `,rt.prReview.source]})]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsxs)(`button`,{className:`primary-button`,type:`button`,disabled:st,onClick:()=>void Rr({field:`toggle`,name:`pr_review`,enabled:!rt.prReview.enabled}),children:[`Turn `,rt.prReview.enabled?`off`:`on`]}),rt.prReview.resettable&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:st,onClick:()=>void Rr({field:`toggle`,name:`pr_review`,enabled:null},`Reset PR reviews to protected policy?`),children:`Reset`})]})]}),(0,Q.jsxs)(`div`,{className:`github-toggle-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`Issue triage`}),(0,Q.jsxs)(`p`,{children:[rt.issueTriage.enabled?`On`:`Off`,` · `,rt.issueTriage.source]})]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsxs)(`button`,{className:`primary-button`,type:`button`,disabled:st,onClick:()=>void Rr({field:`toggle`,name:`issue_triage`,enabled:!rt.issueTriage.enabled}),children:[`Turn `,rt.issueTriage.enabled?`off`:`on`]}),rt.issueTriage.resettable&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:st,onClick:()=>void Rr({field:`toggle`,name:`issue_triage`,enabled:null},`Reset issue triage to protected policy?`),children:`Reset`})]})]})]})]}),(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[(0,Q.jsxs)(`article`,{className:`settings-card github-repositories-card`,children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Subscribed repositories`}),rt.repositories.length>0?(0,Q.jsx)(`ul`,{className:`github-repository-list`,children:rt.repositories.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.repository}),(0,Q.jsxs)(`small`,{children:[e.source,` · `,e.automationAuthorized?`automation authorized`:`notifications only`]})]}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:st,onClick:()=>void Rr({field:`repository`,name:e.repository,subscribed:!1},`Unsubscribe from ${e.repository}?`),children:`Remove`})]},e.repository))}):(0,Q.jsx)(`p`,{children:`No repository subscriptions.`}),(0,Q.jsxs)(`form`,{className:`github-add-repository`,onSubmit:e=>{e.preventDefault();let t=pt.trim();t&&Rr({field:`repository`,name:t,subscribed:!0}).then(e=>{e&&mt(``)})},children:[(0,Q.jsx)(`label`,{htmlFor:`github-repository`,children:`Add notification subscription`}),(0,Q.jsxs)(`div`,{className:`settings-inline-input`,children:[(0,Q.jsx)(`input`,{id:`github-repository`,type:`text`,value:pt,disabled:st,placeholder:`owner/repository`,autoCapitalize:`none`,autoCorrect:`off`,onChange:e=>mt(e.target.value)}),(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:st||!pt.trim(),children:`Add`})]}),(0,Q.jsx)(`p`,{children:`Subscriptions outside protected repository policy receive notifications only.`})]}),rt.repositoriesResettable&&(0,Q.jsx)(`div`,{className:`settings-actions`,children:(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:st,onClick:()=>void Rr({field:`repository_reset`},`Reset all repository subscriptions to protected policy?`),children:`Reset subscriptions`})})]}),(0,Q.jsxs)(`form`,{className:`settings-card github-token-card`,onSubmit:e=>{e.preventDefault(),ht.trim()&&Rr({field:`token`,token:ht},rt.tokenStored?`Replace the stored GitHub token?`:null)},children:[(0,Q.jsx)(`label`,{htmlFor:`github-token`,children:`GitHub access token`}),(0,Q.jsxs)(`p`,{children:[`Status: `,(0,Q.jsx)(`strong`,{children:rt.tokenStored?`Stored`:`Not set`})]}),(0,Q.jsx)(`input`,{id:`github-token`,type:`password`,value:ht,disabled:st,autoComplete:`new-password`,placeholder:rt.tokenStored?`Enter a replacement token`:`Enter a token`,onChange:e=>gt(e.target.value)}),(0,Q.jsx)(`p`,{children:`The existing token is never returned to this browser.`}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:st||!ht.trim(),children:rt.tokenStored?`Replace token`:`Store token`}),rt.tokenStored&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:st,onClick:()=>void Rr({field:`token`,token:null},`Remove the stored GitHub token? Automated GitHub actions may stop working.`),children:`Remove token`})]})]})]})]}):(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:lt??`GitHub settings are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void $n(),children:`Retry`})]}),dt&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:dt}),lt&&rt&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:lt})]}),(0,Q.jsxs)(`section`,{className:`settings-section`,id:`settings-section-notifications`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`section-number`,children:`03`}),(0,Q.jsx)(`h2`,{children:`Notification delivery`}),(0,Q.jsx)(`p`,{children:`Choose which channel activity reaches your inbox, when adapter delivery should pause, and where personal integration notifications appear.`})]}),(0,Q.jsxs)(`div`,{className:`settings-section-content notification-settings-content`,children:[kt&&(0,Q.jsx)(`p`,{role:`status`,children:`Loading channel notification policy…`}),!kt&&!Dt&&(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:Nt??`Channel notification policy is unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void tr(),children:`Retry`})]}),yt&&(0,Q.jsx)(`p`,{role:`status`,children:`Loading notification destinations…`}),!yt&&!_t&&(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:Ct??`Notification preferences are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void er(),children:`Retry`})]}),(Dt||_t)&&(0,Q.jsxs)(`div`,{className:`settings-card-columns notification-preference-grid`,children:[(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[Dt?.adapterDeliveries.map(e=>(0,Q.jsxs)(`article`,{className:`settings-card`,children:[(0,Q.jsxs)(`label`,{className:`settings-checkbox-row`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:e.enabled,disabled:jt,onChange:t=>void Br({field:`adapter_delivery`,transport:e.transport,enabled:t.target.checked})}),(0,Q.jsxs)(`span`,{children:[e.displayName,` alerts`]})]}),(0,Q.jsxs)(`p`,{children:[`Send human mention and reply alerts through `,e.displayName,`. Conversations remain available when alerts are off.`]}),(0,Q.jsx)(`p`,{children:e.source})]},`adapter-${e.transport}`)),Dt?.channels.map(e=>(0,Q.jsxs)(`article`,{className:`settings-card`,children:[(0,Q.jsx)(`label`,{htmlFor:`channel-notification-${e.channelId}`,children:e.channelName}),(0,Q.jsxs)(`select`,{id:`channel-notification-${e.channelId}`,value:e.level,disabled:jt,onChange:t=>void Br({field:`channel`,channelId:e.channelId,level:t.target.value}),children:[(0,Q.jsx)(`option`,{value:`all`,children:`All messages`}),(0,Q.jsx)(`option`,{value:`mentions_replies`,children:`Mentions and replies`}),(0,Q.jsx)(`option`,{value:`muted`,children:`Muted`})]}),(0,Q.jsx)(`p`,{children:e.source})]},e.channelId))]}),(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[Dt&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`article`,{className:`settings-card`,children:[(0,Q.jsxs)(`label`,{className:`settings-checkbox-row`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:Dt.mutedMentionsNotify,disabled:jt,onChange:e=>void Br({field:`muted_mentions_notify`,enabled:e.target.checked})}),(0,Q.jsx)(`span`,{children:`Direct mentions override muted channels`})]}),(0,Q.jsx)(`p`,{children:`A direct @mention can still create an in-app notification.`})]}),(0,Q.jsxs)(`article`,{className:`settings-card settings-dnd-card`,children:[(0,Q.jsx)(`h3`,{children:`Do not disturb`}),(0,Q.jsxs)(`label`,{className:`settings-checkbox-row`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:Lt,disabled:jt,onChange:e=>Rt(e.target.checked)}),(0,Q.jsx)(`span`,{children:`Pause external delivery on this schedule`})]}),(0,Q.jsx)(`label`,{htmlFor:`dnd-timezone`,children:`Timezone`}),(0,Q.jsx)(`select`,{id:`dnd-timezone`,value:zt,disabled:jt,onChange:e=>Bt(e.target.value),children:Kt.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))}),(0,Q.jsxs)(`div`,{className:`settings-inline-fields`,children:[(0,Q.jsxs)(`label`,{htmlFor:`dnd-start`,children:[`Start`,(0,Q.jsx)(`input`,{id:`dnd-start`,type:`text`,inputMode:`numeric`,pattern:`(?:[01][0-9]|2[0-3]):[0-5][0-9]`,maxLength:5,value:Vt,disabled:jt,onChange:e=>Ht(e.target.value),placeholder:`22:00`,autoComplete:`off`})]}),(0,Q.jsxs)(`label`,{htmlFor:`dnd-end`,children:[`End`,(0,Q.jsx)(`input`,{id:`dnd-end`,type:`text`,inputMode:`numeric`,pattern:`(?:[01][0-9]|2[0-3]):[0-5][0-9]`,maxLength:5,value:Ut,disabled:jt,onChange:e=>Wt(e.target.value),placeholder:`07:00`,autoComplete:`off`})]})]}),(0,Q.jsx)(`div`,{className:`settings-actions`,children:(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:jt||!Gt,onClick:()=>void Br({field:`do_not_disturb`,enabled:Lt,timezone:zt,start:Vt,end:Ut}),children:`Save schedule`})}),!Gt&&(0,Q.jsx)(`p`,{className:`settings-control-error`,role:`alert`,children:`Enter different start and end times in 24-hour HH:MM format.`}),(0,Q.jsx)(`p`,{children:`Workshop notifications remain immediate. Adapter delivery uses this policy.`})]})]}),_t?.preferences.map(e=>{let t=_t.destinations.filter(t=>t.supportedClasses.includes(e.integrationClass));return(0,Q.jsxs)(`article`,{className:`settings-card`,children:[(0,Q.jsx)(`label`,{htmlFor:`notification-${e.integrationClass}`,children:e.displayName}),(0,Q.jsx)(`select`,{id:`notification-${e.integrationClass}`,value:e.destinationChoiceId,disabled:xt||!e.editable,onChange:t=>void zr({field:`destination`,integrationClass:e.integrationClass,choiceId:t.target.value}),children:t.map(e=>(0,Q.jsxs)(`option`,{value:e.choiceId,children:[e.displayName,` · `,e.kind]},e.choiceId))}),(0,Q.jsxs)(`p`,{children:[`Effective: `,(0,Q.jsx)(`strong`,{children:e.destinationName}),` · ${e.source}`]}),e.resettable&&(0,Q.jsx)(`div`,{className:`settings-actions`,children:(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:xt,onClick:()=>void zr({field:`reset`,integrationClass:e.integrationClass},`Reset ${e.displayName} delivery to protected policy?`),children:`Reset`})})]},e.integrationClass)})]})]}),Ft&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:Ft}),Nt&&Dt&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:Nt}),Tt&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:Tt}),Ct&&_t&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:Ct})]})]}),(0,Q.jsxs)(`section`,{className:`settings-section`,id:`settings-section-clients`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`section-number`,children:`04`}),(0,Q.jsx)(`h2`,{children:`Client preferences`}),(0,Q.jsx)(`p`,{children:`Control presentation on each connected client without changing how your other Kai clients behave.`})]}),(0,Q.jsxs)(`div`,{className:`settings-client-preferences`,children:[(0,Q.jsxs)(`div`,{className:`settings-card-columns`,children:[(0,Q.jsx)(`div`,{className:`settings-card-column`,children:cn?(0,Q.jsx)(`p`,{role:`status`,children:`Loading Workshop appearance…`}):rn?(0,Q.jsxs)(`article`,{className:`settings-card settings-appearance-card`,children:[(0,Q.jsx)(`h3`,{children:`Workshop appearance`}),(0,Q.jsx)(`p`,{children:`This theme follows your Workshop account across enrolled browsers.`}),(0,Q.jsx)(`label`,{htmlFor:`workshop-theme`,children:`Theme`}),(0,Q.jsx)(`select`,{id:`workshop-theme`,value:on,disabled:un,onChange:e=>void Hr(e.target.value),children:rn.themes.map(e=>(0,Q.jsx)(`option`,{value:e.themeId,children:e.displayName},e.themeId))})]}):(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:fn??`Appearance preferences are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void rr(),children:`Retry`})]})}),(0,Q.jsx)(`div`,{className:`settings-card-column`,children:Yt?(0,Q.jsx)(`p`,{role:`status`,children:`Loading client preferences…`}):qt?qt.voiceOutput.bindings.length>0?(0,Q.jsx)(Q.Fragment,{children:qt.voiceOutput.bindings.map(e=>(0,Q.jsxs)(`article`,{className:`settings-card`,children:[(0,Q.jsxs)(`h3`,{children:[e.clientName,` voice output`]}),!qt.voiceOutput.available&&(0,Q.jsx)(`p`,{children:qt.voiceOutput.unavailableReason}),(0,Q.jsx)(`label`,{htmlFor:`client-mode-${e.choiceId}`,children:`Response format`}),(0,Q.jsx)(`select`,{id:`client-mode-${e.choiceId}`,value:e.mode,disabled:Zt||!e.editable,onChange:t=>void Vr({field:`mode`,bindingChoiceId:e.choiceId,value:t.target.value}),children:qt.voiceOutput.modes.map(e=>(0,Q.jsx)(`option`,{value:e,children:tg[e]},e))}),(0,Q.jsx)(`label`,{htmlFor:`client-voice-${e.choiceId}`,children:`Voice`}),(0,Q.jsx)(`select`,{id:`client-voice-${e.choiceId}`,value:e.voice,disabled:Zt||!e.editable,onChange:t=>void Vr({field:`voice`,bindingChoiceId:e.choiceId,value:t.target.value}),children:qt.voiceOutput.voices.map(e=>(0,Q.jsx)(`option`,{value:e.value,children:e.displayName},e.value))})]},e.choiceId))}):(0,Q.jsx)(`p`,{children:`No voice-capable client binding is available for this account.`}):(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:$t??`Client preferences are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void nr(),children:`Retry`})]})})]}),mn&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:mn}),fn&&rn&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:fn}),tn&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:tn}),$t&&qt&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:$t})]})]}),u&&(0,Q.jsxs)(`section`,{className:`settings-section`,id:`settings-section-administration`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`section-number`,children:`05`}),(0,Q.jsx)(`h2`,{children:`Administration`}),(0,Q.jsx)(`p`,{children:`Read-only host service and integration health. Secrets, credentials, filesystem paths, and network addresses are never displayed.`})]}),(0,Q.jsxs)(`div`,{className:`settings-section-content administration-settings-content`,children:[vn?(0,Q.jsx)(`p`,{role:`status`,children:`Loading service and integration diagnostics…`}):gn?(0,Q.jsxs)(`article`,{className:`settings-card webhook-diagnostics-card`,children:[(0,Q.jsxs)(`div`,{className:`webhook-diagnostics-heading`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Service and integrations`}),(0,Q.jsx)(`h3`,{children:`Webhook diagnostics`})]}),(0,Q.jsx)(`span`,{className:`webhook-diagnostic-state`,"data-state":gn.state,children:gn.state})]}),(0,Q.jsxs)(`dl`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Shared listener`}),(0,Q.jsx)(`dd`,{children:gn.listener.state})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Port`}),(0,Q.jsx)(`dd`,{children:gn.listener.port})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Recent delivery health`}),(0,Q.jsxs)(`dd`,{children:[gn.deliveries.state,` · `,gn.deliveries.windowHours,`h`]})]})]}),(0,Q.jsxs)(`p`,{className:`settings-help`,children:[gn.deliveries.pending,` pending · `,gn.deliveries.executing,` executing · `,gn.deliveries.retrying,` retrying · `,gn.deliveries.succeeded,` succeeded · `,gn.deliveries.failed,` failed`]}),(0,Q.jsxs)(`details`,{className:`webhook-diagnostics-detail`,children:[(0,Q.jsx)(`summary`,{children:`Endpoint classes`}),(0,Q.jsx)(`ul`,{children:gn.endpoints.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:e.displayName}),(0,Q.jsx)(`span`,{className:`webhook-diagnostic-state`,"data-state":e.state,children:e.state})]}),(0,Q.jsx)(`p`,{children:e.description})]},e.endpointClass))})]}),gn.guidance.length>0&&(0,Q.jsxs)(`details`,{className:`webhook-diagnostics-detail`,children:[(0,Q.jsx)(`summary`,{children:`Setup guidance`}),(0,Q.jsx)(`ul`,{children:gn.guidance.map(e=>(0,Q.jsx)(`li`,{children:e},e))})]}),(0,Q.jsx)(`p`,{className:`settings-help`,children:`Diagnostics are read-only. Installation and webhook registration remain operator actions.`})]}):(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:bn??`Webhook diagnostics are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void yr(),children:`Retry`})]}),bn&&gn&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:bn})]})]})]})]})]})}function hg(e){return(0,Q.jsx)(Gm,{children:(0,Q.jsx)(mg,{...e})})}function gg(e){return(0,Q.jsx)(Gm,{children:(0,Q.jsx)(mg,{...e,agentRuntime:!0,nativeAgentRuntime:!0,onClose:()=>void 0,onDirtyChange:()=>void 0})})}function _g(){let e=new Uint8Array(12);return crypto.getRandomValues(e),`workshop-review:${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function vg(e){let t=e.trim(),n=/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:[/?#].*)?$/i.exec(t);if(n)return{repository:`${n[1]}/${n[2]}`.toLocaleLowerCase(),number:Number(n[3])};let r=/^([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#(\d+)$/.exec(t);if(r)return{repository:r[1].toLocaleLowerCase(),number:Number(r[2])};let i=/^#?(\d+)$/.exec(t);return i?{repository:null,number:Number(i[1])}:null}function yg({onAuthenticationFailure:e,onChannelAccessFailure:t,onClose:n,onSubmitted:r,session:i}){let[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(``),[l,u]=(0,v.useState)(``),[d,f]=(0,v.useState)(!0),[p,m]=(0,v.useState)(!1),[h,g]=(0,v.useState)(null),_=(0,v.useMemo)(()=>vg(s),[s]);(0,v.useEffect)(()=>{let n=!1;return $n(i).then(e=>{n||(o(e),u(e.submission.inferredRepository??(e.submission.repositories.length===1?e.submission.repositories[0]:``)))}).catch(r=>{n||(r instanceof B?e(r.message):r instanceof V?t(r.message):g(r instanceof Error?r.message:`Could not load review options.`))}).finally(()=>{n||f(!1)}),()=>{n=!0}},[e,t,i]);let y=_?.repository??(l||null),b=_!==null&&y!==null&&a?.submission.repositories.includes(y)===!0,x=async a=>{if(a.preventDefault(),!(!_||!y||!b)){m(!0),g(null);try{await er(i,y,_.number,_g()),r(),n()}catch(n){n instanceof B?e(n.message):n instanceof V?t(n.message):g(n instanceof Error?n.message:`Could not start the review.`)}finally{m(!1)}}};return(0,Q.jsx)(`div`,{className:`action-palette-backdrop`,onMouseDown:n,children:(0,Q.jsxs)(`section`,{"aria-labelledby":`review-dialog-title`,"aria-modal":`true`,className:`review-dialog`,onMouseDown:e=>e.stopPropagation(),role:`dialog`,children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`GitHub`}),(0,Q.jsx)(`h2`,{id:`review-dialog-title`,children:`Review pull request`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close review`,title:`Close`,onClick:n,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),d?(0,Q.jsx)(`p`,{role:`status`,children:`Loading authorized repositories…`}):a?(0,Q.jsxs)(`form`,{onSubmit:e=>void x(e),children:[(0,Q.jsx)(`label`,{htmlFor:`review-reference`,children:`Pull request`}),(0,Q.jsx)(`input`,{autoFocus:!0,id:`review-reference`,placeholder:`GitHub URL, owner/repository#123, or 123`,value:s,onChange:e=>c(e.target.value)}),(0,Q.jsx)(`label`,{htmlFor:`review-repository`,children:`Authorized repository`}),(0,Q.jsxs)(`select`,{id:`review-repository`,disabled:_!==null&&_.repository!==null,value:y??``,onChange:e=>u(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:`Choose a repository`}),a.submission.repositories.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]}),(0,Q.jsxs)(`div`,{className:`review-context`,children:[(0,Q.jsx)(`strong`,{children:`Active workspace`}),(0,Q.jsx)(`span`,{children:a.submission.activeWorkspace}),(0,Q.jsx)(`small`,{children:a.submission.activeWorkspaceRepository?`GitHub repository: ${a.submission.activeWorkspaceRepository}`:`No GitHub repository was detected for this workspace.`})]}),_?.repository&&!a.submission.repositories.includes(_.repository)&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:`That repository is not authorized for review.`}),h&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:h}),(0,Q.jsx)(`div`,{className:`form-actions`,children:(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:p||!b,children:p?`Starting…`:`Start review`})})]}):(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:h??`Review options are unavailable.`})]})})}var bg=[{description:`Create ordinary text responses.`,label:`Text generation`,value:`text_generation`},{description:`Expose bounded tool activity in the run inspector.`,label:`Tool activity`,value:`tool_activity`},{description:`Work within an already-authorized workspace.`,label:`Workspace execution`,value:`workspace_execution`},{description:`Accept images when the selected runtime supports them.`,label:`Image input`,value:`image_input`},{description:`Delegate bounded tasks to other active agents in a shared channel.`,label:`Agent delegation`,value:`agent_delegation`}],xg=[{description:`Read bounded canonical conversation context.`,label:`Context reading`,value:`context_read`},{description:`Add or remove reactions on messages.`,label:`Reactions`,value:`reaction`},{description:`Publish visible progress updates while working.`,label:`Progress updates`,value:`progress_publish`},{description:`Reply inside an existing thread.`,label:`Thread replies`,value:`thread_reply`},{description:`Publish a bounded artifact with provenance.`,label:`Artifacts`,value:`artifact_publish`},{description:`Delegate bounded work to another active agent.`,label:`Agent delegation`,value:`agent_delegation`},{description:`Remain available for bounded observation in opted-in group channels.`,label:`Standing participation`,value:`standing_participation`}],Sg={avatar:``,capabilities:[`text_generation`],collaborationOperations:[],description:``,displayName:``,handle:``,instructions:``,purpose:``},Cg=[`Identity`,`Role`,`Runtime`,`Review`];function wg(){if(typeof globalThis.crypto?.getRandomValues!=`function`)throw Error(`This browser cannot create secure operation identities.`);let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),`workshop-agent-provision-${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function Tg(e){let t=e.normalize(`NFKD`).replace(/[\u0300-\u036f]/g,``).toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``);return t?(/^[a-z]/.test(t)?t:`agent_${t}`).slice(0,32).replace(/_+$/g,``):``}function Eg(e){return`${e.backend} · ${e.provider}`}function Dg(e){return e.blockers.length===0&&e.readiness!==`unavailable`&&e.readiness!==`misconfigured`}function Og(e){let t=e.backends.find(t=>t.optionId===e.currentBackendOptionId);return t&&Dg(t)?t:e.backends.find(Dg)??t??e.backends[0]??null}function kg(e){return e.models.find(t=>t.modelId===e.defaultModel&&t.selectable)?.modelId??e.models.find(e=>e.selectable)?.modelId??``}function Ag(e){return e.workspaces.find(t=>t.path===e.defaultWorkspace&&t.available)?.path??e.workspaces.find(e=>e.available)?.path??``}function jg(e){return e?{backend_selected:`apply the backend`,collaboration_policy_set:`apply collaboration limits`,definition_created:`save the definition`,enablement_created:`authorize its runtime`,model_selected:`apply the model`,ready:`finish setup`,revision_activated:`activate Revision 1`,runtime_registered:`connect the runtime`,timeout_selected:`apply the response timeout`,workspace_selected:`apply the workspace`}[e]??`continue setup`:`finish setup`}function Mg({disabled:e,kind:t,selected:n,onChange:r}){return(0,Q.jsxs)(`fieldset`,{className:`agent-capability-choices`,disabled:e,children:[(0,Q.jsx)(`legend`,{children:t===`capabilities`?`Declared capabilities`:`Collaboration tools`}),(0,Q.jsx)(`p`,{children:t===`capabilities`?`Capabilities describe requirements; they do not grant credentials or data access.`:`Requested tools remain bounded by owner and host policy on every attempt.`}),(t===`capabilities`?bg:xg).map(e=>(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:n.includes(e.value),onChange:t=>{r(t.target.checked?[...n,e.value]:n.filter(t=>t!==e.value))}}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.label}),(0,Q.jsx)(`small`,{children:e.description})]})]},e.value))]})}function Ng({busy:e,existingHandles:t,options:n,optionsError:r,optionsLoading:i,resumeDraft:a,resumeInput:o,resumeProvisioning:s,onCancel:c,onCreateReady:l,onSaveDraft:u}){let d=Km(),f=o?{avatar:o.avatar,capabilities:o.capabilities,collaborationOperations:o.collaborationOperations,description:o.description,displayName:o.displayName,handle:o.handle,instructions:o.instructions,purpose:o.purpose}:a??Sg,[p,m]=(0,v.useState)(f),[h,g]=(0,v.useState)(o?`Review`:a?`Runtime`:`Identity`),[_,y]=(0,v.useState)(!1),[b,x]=(0,v.useState)(!0),[S,C]=(0,v.useState)(o?.runtimeProfileId??``),[w,T]=(0,v.useState)(o?.backendOptionId??``),[E,D]=(0,v.useState)(o?.model??``),[O,k]=(0,v.useState)({}),[A,j]=(0,v.useState)(o?.workspace??``),[M,N]=(0,v.useState)(null),[P,F]=(0,v.useState)(null),[I,L]=(0,v.useState)(o),[R,ee]=(0,v.useState)(s),[z]=(0,v.useState)(o?.clientOperationId??wg),B=n?.runtimes.find(e=>e.runtimeProfileId===S)??null,V=B?.backends.find(e=>e.optionId===w)??null,H=V?.models.find(e=>e.modelId===E)??null,te=B?.workspaces.find(e=>e.path===A)??null,U=I!==null;(0,v.useEffect)(()=>{if(!n||S||n.runtimes.length===0)return;let e=n.runtimes.find(e=>e.ready)??n.runtimes[0];if(!e)return;let t=Og(e),r=t?kg(t):``;C(e.runtimeProfileId),T(t?.optionId??``),D(r),k(t?{[t.optionId]:r}:{}),j(Ag(e))},[n,S]);let ne=(0,v.useMemo)(()=>{let e=[];return i&&e.push(`Runtime choices are still loading.`),r&&e.push(r),!i&&!n&&!r&&e.push(`Runtime choices are unavailable.`),n&&!n.ready&&e.push(...n.blockers.map(e=>e.detail)),B&&!B.ready&&(e.push(...B.blockers.map(e=>e.detail)),B.blockers.length===0&&e.push(`The selected runtime is not ready.`)),B&&!V&&e.push(`Choose an authorized backend.`),V&&(e.push(...V.blockers.map(e=>e.detail)),!Dg(V)&&V.blockers.length===0&&e.push(`${Eg(V)} is not ready for agent creation.`)),V&&(!H||!H.selectable)&&e.push(`Choose an available model for the selected backend.`),B&&(!te||!te.available)&&e.push(`Choose an available workspace.`),[...new Set(e)]},[n,r,i,V,H,B,te]),re=e=>{m(t=>({...t,...e})),y(!0),F(null)},W=async()=>{e||_&&!await d(`Discard your unsaved agent changes?`)||c()},ie=()=>p.displayName.trim()?/^[a-z][a-z0-9_]{0,31}$/.test(p.handle)?t.includes(p.handle)&&p.handle!==o?.handle&&p.handle!==a?.handle?`@${p.handle} is already in use. Choose another handle.`:null:`Use a handle beginning with a lowercase letter and containing only lowercase letters, numbers, and underscores.`:`Enter a display name.`,ae=()=>p.purpose.trim()?p.instructions.trim()?p.capabilities.length===0?`Select at least one declared capability.`:null:`Describe how this agent should behave.`:`Describe what this agent should do.`,oe=()=>{let e=h===`Identity`?ie():h===`Role`?ae():null;if(e){F(e);return}let t=Cg[Cg.indexOf(h)+1];t&&(F(null),g(t))},se=()=>{let e=Cg[Cg.indexOf(h)-1];e&&!U&&(F(null),g(e))},ce=e=>{let t=n?.runtimes.find(t=>t.runtimeProfileId===e);if(!t)return;let r=Og(t),i=r?O[r.optionId]||kg(r):``;C(t.runtimeProfileId),T(r?.optionId??``),D(i),j(Ag(t)),N(null),y(!0),F(null)},le=e=>{let t=B?.backends.find(t=>t.optionId===e);if(!t)return;let n=O[t.optionId],r=t.models.find(e=>e.modelId===E&&e.selectable)?.modelId,i=n||r||kg(t);T(t.optionId),D(i),k(e=>({...e,[t.optionId]:i})),N(r||n?null:i?`Model set to ${i}, the protected default for ${Eg(t)}.`:`No available model was found for ${Eg(t)}.`),y(!0),F(null)},ue=async()=>{let e=ie()??ae();if(e){F(e);return}F(null);try{await u(p)}catch(e){F(e instanceof Error?e.message:`Could not save this draft.`)}},G=async()=>{let e=ie()??ae();if(e){F(e);return}if(ne.length>0||!B||!V){F(ne[0]??`Runtime choices are incomplete.`);return}let t=I??{allowedCollaborationOperations:p.collaborationOperations,avatar:p.avatar,backendOptionId:V.optionId,capabilities:p.capabilities,clientOperationId:z,collaborationOperations:p.collaborationOperations,description:p.description,displayName:p.displayName,...a?{existingDefinitionId:a.definitionId}:{},handle:p.handle,instructions:p.instructions,model:E,purpose:p.purpose,runtimeProfileId:B.runtimeProfileId,timeoutSeconds:B.defaultTimeoutSeconds,workspace:A};L(t),F(null);try{let e=await l(t);e.status!==`ready`&&(ee(e),F(e.blockers[0]?.detail??`Agent setup needs attention. Your progress was saved and can be retried safely.`))}catch(e){F(e instanceof Error?e.message:`Could not create this agent.`)}},K=e=>{e.preventDefault(),h===`Review`?G():oe()},q=Cg.indexOf(h);return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsx)(`section`,{className:`channel-creation-dialog agent-creation-dialog agent-creation-wizard`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`create-agent-title`,children:(0,Q.jsxs)(`form`,{className:`agent-editor`,onSubmit:K,children:[(0,Q.jsxs)(`div`,{className:`agent-creation-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:o?`Saved agent setup`:a?`Draft agent`:`New software participant`}),(0,Q.jsx)(`h2`,{id:`create-agent-title`,children:o||a?`Continue ${p.displayName}`:`Create agent`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close agent creation`,title:`Close agent creation`,onClick:()=>void W(),disabled:e,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsx)(`ol`,{className:`agent-creation-progress`,"aria-label":`Agent creation progress`,children:Cg.map((e,t)=>(0,Q.jsxs)(`li`,{className:t<=q?`active`:void 0,"aria-current":e===h?`step`:void 0,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:t+1}),e]},e))}),h===`Identity`&&(0,Q.jsxs)(`section`,{className:`agent-creation-stage`,"aria-labelledby":`agent-identity-heading`,children:[(0,Q.jsxs)(`div`,{className:`agent-creation-stage-heading`,children:[(0,Q.jsx)(`h3`,{id:`agent-identity-heading`,children:`Identity`}),(0,Q.jsx)(`p`,{children:`How this agent will appear to people in Workshop.`})]}),(0,Q.jsxs)(`div`,{className:`agent-editor-grid`,children:[(0,Q.jsxs)(`label`,{children:[`Display name`,(0,Q.jsx)(`input`,{autoFocus:!0,maxLength:80,required:!0,disabled:U,value:p.displayName,onChange:e=>{let t=e.target.value;re({displayName:t,...b?{handle:Tg(t)}:{}})}})]}),(0,Q.jsxs)(`label`,{children:[`Handle`,(0,Q.jsx)(`span`,{className:`agent-field-hint`,children:`Unique, stable, and editable`}),(0,Q.jsxs)(`div`,{className:`agent-handle-input`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`@`}),(0,Q.jsx)(`input`,{maxLength:32,pattern:`[a-z][a-z0-9_]{0,31}`,required:!0,disabled:U,value:p.handle,onChange:e=>{x(!1),re({handle:e.target.value.toLowerCase()})}})]})]}),(0,Q.jsxs)(`label`,{children:[`Avatar text`,(0,Q.jsx)(`span`,{className:`agent-field-hint`,children:`Optional, up to 16 characters`}),(0,Q.jsx)(`input`,{maxLength:16,disabled:U,value:p.avatar,onChange:e=>re({avatar:e.target.value})})]})]}),(0,Q.jsxs)(`label`,{children:[`Description`,(0,Q.jsx)(`span`,{className:`agent-field-hint`,children:`A concise summary shown to other Workshop members`}),(0,Q.jsx)(`textarea`,{maxLength:1e3,rows:3,disabled:U,value:p.description,onChange:e=>re({description:e.target.value})})]})]}),h===`Role`&&(0,Q.jsxs)(`section`,{className:`agent-creation-stage`,"aria-labelledby":`agent-role-heading`,children:[(0,Q.jsxs)(`div`,{className:`agent-creation-stage-heading`,children:[(0,Q.jsx)(`h3`,{id:`agent-role-heading`,children:`Role`}),(0,Q.jsx)(`p`,{children:`Define the agent's purpose and behavioral boundaries.`})]}),(0,Q.jsxs)(`label`,{children:[`What should this agent do?`,(0,Q.jsx)(`textarea`,{autoFocus:!0,maxLength:2e3,required:!0,rows:4,disabled:U,value:p.purpose,onChange:e=>re({purpose:e.target.value})})]}),(0,Q.jsxs)(`label`,{children:[`How should it behave?`,(0,Q.jsx)(`span`,{className:`agent-field-hint`,children:`Instructions cannot grant authority.`}),(0,Q.jsx)(`textarea`,{maxLength:2e4,required:!0,rows:8,disabled:U,value:p.instructions,onChange:e=>re({instructions:e.target.value})})]}),(0,Q.jsxs)(`details`,{className:`agent-creation-advanced`,children:[(0,Q.jsx)(`summary`,{children:`Advanced capabilities`}),Mg({disabled:e||U,kind:`capabilities`,selected:p.capabilities,onChange:e=>re({capabilities:e})}),Mg({disabled:e||U,kind:`collaboration`,selected:p.collaborationOperations,onChange:e=>re({collaborationOperations:e})})]})]}),h===`Runtime`&&(0,Q.jsxs)(`section`,{className:`agent-creation-stage`,"aria-labelledby":`agent-runtime-heading`,children:[(0,Q.jsxs)(`div`,{className:`agent-creation-stage-heading`,children:[(0,Q.jsx)(`h3`,{id:`agent-runtime-heading`,children:`Runtime`}),(0,Q.jsx)(`p`,{children:`Choose from runtime access already authorized for you.`})]}),i&&(0,Q.jsx)(`p`,{className:`agent-creation-loading`,role:`status`,children:`Loading runtime choices…`}),!i&&B&&(0,Q.jsxs)(`div`,{className:`agent-runtime-choice-grid`,children:[n&&n.runtimes.length>1&&(0,Q.jsxs)(`details`,{className:`agent-creation-advanced agent-runtime-profile-choice`,children:[(0,Q.jsx)(`summary`,{children:`Advanced runtime`}),(0,Q.jsxs)(`label`,{children:[`Execution profile`,(0,Q.jsx)(`select`,{value:S,disabled:e||U,onChange:e=>ce(e.target.value),children:n.runtimes.map(e=>(0,Q.jsx)(`option`,{value:e.runtimeProfileId,children:e.displayName},e.runtimeProfileId))})]})]}),(0,Q.jsxs)(`label`,{children:[`Backend`,(0,Q.jsx)(`select`,{autoFocus:!0,value:w,disabled:e||U,onChange:e=>le(e.target.value),children:B.backends.map(e=>(0,Q.jsx)(`option`,{value:e.optionId,disabled:!Dg(e),children:Eg(e)},e.optionId))})]}),(0,Q.jsxs)(`label`,{children:[`Model`,(0,Q.jsx)(`select`,{value:E,disabled:e||U||!V,onChange:e=>{let t=e.target.value;D(t),k(e=>({...e,[w]:t})),N(null),y(!0),F(null)},children:V?.models.map(e=>(0,Q.jsx)(`option`,{value:e.modelId,disabled:!e.selectable,children:e.displayName},e.modelId))})]}),(0,Q.jsxs)(`label`,{children:[`Workspace`,(0,Q.jsx)(`select`,{value:A,disabled:e||U,onChange:e=>{j(e.target.value),y(!0),F(null)},children:B.workspaces.map(e=>(0,Q.jsx)(`option`,{value:e.path,disabled:!e.available,children:e.name},e.path))})]}),M&&(0,Q.jsx)(`p`,{className:`agent-runtime-notice`,role:`status`,children:M})]}),!i&&ne.length>0&&(0,Q.jsxs)(`section`,{className:`agent-creation-blockers`,"aria-label":`Creation readiness`,children:[(0,Q.jsx)(`strong`,{children:`Ready creation is not currently available`}),(0,Q.jsx)(`ul`,{children:ne.map(e=>(0,Q.jsx)(`li`,{children:e},e))}),(0,Q.jsx)(`p`,{children:`You can continue reviewing this agent and save it as a draft.`})]})]}),h===`Review`&&(0,Q.jsxs)(`section`,{className:`agent-creation-stage`,"aria-labelledby":`agent-review-heading`,children:[(0,Q.jsxs)(`div`,{className:`agent-creation-stage-heading`,children:[(0,Q.jsx)(`h3`,{id:`agent-review-heading`,children:`Review`}),(0,Q.jsx)(`p`,{children:`Confirm the definition and runtime choices before creating the agent.`})]}),(0,Q.jsxs)(`dl`,{className:`agent-creation-review`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Agent`}),(0,Q.jsxs)(`dd`,{children:[p.displayName,` · @`,p.handle]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Purpose`}),(0,Q.jsx)(`dd`,{children:p.purpose})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Backend`}),(0,Q.jsx)(`dd`,{children:V?Eg(V):`Not available`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Model`}),(0,Q.jsx)(`dd`,{children:(H?.displayName??E)||`Not available`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Workspace`}),(0,Q.jsx)(`dd`,{children:te?.name??`Not available`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Advanced requests`}),(0,Q.jsx)(`dd`,{children:p.collaborationOperations.length>0?p.collaborationOperations.map(e=>e.replaceAll(`_`,` `)).join(`, `):`None`})]})]}),(0,Q.jsx)(`p`,{className:`agent-conversation-notice`,children:`Creating this agent will not start a direct conversation or add it to a channel.`}),ne.length>0&&(0,Q.jsxs)(`section`,{className:`agent-creation-blockers`,"aria-label":`Creation readiness`,children:[(0,Q.jsx)(`strong`,{children:`Save as draft to keep this definition`}),(0,Q.jsx)(`ul`,{children:ne.map(e=>(0,Q.jsx)(`li`,{children:e},e))})]}),e&&(0,Q.jsx)(`p`,{className:`agent-creation-loading`,role:`status`,children:`Creating the agent and applying its runtime settings…`}),R&&R.status!==`ready`&&(0,Q.jsxs)(`section`,{className:`agent-creation-recovery`,children:[(0,Q.jsx)(`strong`,{children:`Setup needs attention`}),(0,Q.jsxs)(`p`,{children:[`Your choices and completed work are saved. The next step is to `,jg(R.nextStage),`.`]}),(0,Q.jsx)(`p`,{children:`Retry continues this exact setup without creating a duplicate agent.`}),(0,Q.jsxs)(`details`,{children:[(0,Q.jsx)(`summary`,{children:`Setup diagnostics`}),(0,Q.jsx)(`code`,{children:R.operationId}),(0,Q.jsxs)(`small`,{children:[R.completedStages.length,` completed stages · next: `,R.nextStage??`finish`]})]})]})]}),P&&(0,Q.jsx)(`p`,{className:`form-error agent-creation-error`,role:`alert`,children:P}),(0,Q.jsxs)(`div`,{className:`form-actions agent-creation-actions`,children:[(0,Q.jsx)(`span`,{children:q>0&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Back to ${Cg[q-1]}`,title:`Back to ${Cg[q-1]}`,disabled:e||U,onClick:se,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})}),(0,Q.jsx)(`span`,{className:`agent-creation-primary-actions`,children:h===`Review`?(0,Q.jsxs)(Q.Fragment,{children:[!a&&!o&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:e||U,onClick:()=>void ue(),children:`Save as draft`}),(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:e||ne.length>0,children:e?`Completing setup…`:U?`Retry setup`:a?`Complete setup`:`Create agent`})]}):(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:e||U,children:`Continue`})})]})]})})})}function Pg(e){if(typeof globalThis.crypto?.getRandomValues!=`function`)throw Error(`This browser cannot create secure operation identities.`);let t=new Uint8Array(16);return globalThis.crypto.getRandomValues(t),`workshop-agent-${e}-${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function Fg(e){return e.revisions.find(t=>t.revisionId===e.activeRevisionId)??null}function Ig(e){return e===`active`?`Ready`:e===`draft`?`Draft`:`Archived`}function Lg(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M20 15a3 3 0 0 1-3 3H9l-5 3V7a3 3 0 0 1 3-3h10a3 3 0 0 1 3 3z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`})})}function Rg(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}function zg({disabled:e,selected:t,onChange:n}){return(0,Q.jsxs)(`fieldset`,{className:`agent-capability-choices`,disabled:e,children:[(0,Q.jsx)(`legend`,{children:`Declared capabilities`}),(0,Q.jsx)(`p`,{children:`Capabilities describe requirements. They never grant tools, credentials, workspaces, services, or data access.`}),bg.map(e=>(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t.includes(e.value),onChange:r=>{n(r.target.checked?[...t,e.value]:t.filter(t=>t!==e.value))}}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.label}),(0,Q.jsx)(`small`,{children:e.description})]})]},e.value))]})}function Bg({disabled:e,selected:t,onChange:n}){return(0,Q.jsxs)(`fieldset`,{className:`agent-capability-choices`,disabled:e,children:[(0,Q.jsx)(`legend`,{children:`Requested collaboration tools`}),(0,Q.jsx)(`p`,{children:`This immutable revision requests operations. Owner and host policy still decide what a run actually receives.`}),xg.map(e=>(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t.includes(e.value),onChange:r=>n(r.target.checked?[...t,e.value]:t.filter(t=>t!==e.value))}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.label}),(0,Q.jsx)(`small`,{children:e.description})]})]},e.value))]})}function Vg({agent:e,busy:t,onCancel:n,onSave:r}){let i=e.revisions[e.revisions.length-1],[a,o]=(0,v.useState)(i?.purpose??``),[s,c]=(0,v.useState)(i?.instructions??``),[l,u]=(0,v.useState)(i?.capabilities??[`text_generation`]),[d,f]=(0,v.useState)(i?.collaborationOperations??[]),[p,m]=(0,v.useState)(null),h=async e=>{if(e.preventDefault(),l.length===0){m(`Select at least one declared capability.`);return}m(null);try{await r({capabilities:l,collaborationOperations:d,instructions:s,purpose:a})}catch(e){m(e instanceof Error?e.message:`Could not save this revision.`)}};return(0,Q.jsxs)(`form`,{className:`agent-revision-editor`,onSubmit:e=>void h(e),children:[(0,Q.jsx)(`h3`,{children:`New definition revision`}),(0,Q.jsx)(`p`,{children:`Saving creates an immutable revision. Activate it separately after review.`}),(0,Q.jsxs)(`label`,{children:[`Purpose`,(0,Q.jsx)(`textarea`,{maxLength:2e3,required:!0,rows:3,value:a,onChange:e=>o(e.target.value)})]}),(0,Q.jsxs)(`label`,{children:[`Instructions`,(0,Q.jsx)(`textarea`,{maxLength:2e4,required:!0,rows:10,value:s,onChange:e=>c(e.target.value)})]}),(0,Q.jsx)(zg,{disabled:t,selected:l,onChange:u}),(0,Q.jsx)(Bg,{disabled:t,selected:d,onChange:f}),p&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:p}),(0,Q.jsxs)(`div`,{className:`form-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:t,children:t?`Saving…`:`Save revision`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:n,disabled:t,children:`Cancel`})]})]})}function Hg({busy:e,policy:t,onRevoke:n,onSave:r}){let[i,a]=(0,v.useState)(t.operations.filter(e=>e.ownerAllowed).map(e=>e.operation));(0,v.useEffect)(()=>{a(t.operations.filter(e=>e.ownerAllowed).map(e=>e.operation))},[t]);let o=t.canManage&&t.operations.some(e=>e.ownerAllowed!==i.includes(e.operation));return(0,Q.jsxs)(`section`,{className:`agent-collaboration-policy`,children:[(0,Q.jsx)(`div`,{className:`agent-section-heading`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:t.canManage?`Owner policy`:`Collaboration access`}),(0,Q.jsx)(`h3`,{children:`Collaboration tools`}),t.canManage?(0,Q.jsx)(`p`,{children:`Policy changes apply to newly accepted attempts. Active attempts retain their immutable snapshot unless you revoke them below.`}):(0,Q.jsx)(`p`,{children:`This read-only view shows revision requests and resulting availability. Owner policy and active-run details remain private.`})]})}),(0,Q.jsx)(`div`,{className:`collaboration-policy-grid`,role:`list`,children:t.operations.map(n=>{let r=xg.find(e=>e.value===n.operation);return(0,Q.jsxs)(`article`,{role:`listitem`,children:[(0,Q.jsxs)(`label`,{children:[t.canManage&&(0,Q.jsx)(`input`,{type:`checkbox`,checked:i.includes(n.operation),disabled:e||!n.hostAllowed,onChange:e=>a(t=>e.target.checked?[...t,n.operation]:t.filter(e=>e!==n.operation))}),(0,Q.jsx)(`strong`,{children:r?.label??n.operation.replaceAll(`_`,` `)})]}),(0,Q.jsxs)(`dl`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Revision`}),(0,Q.jsx)(`dd`,{children:n.requested?`requested`:`not requested`})]}),t.canManage&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Owner`}),(0,Q.jsx)(`dd`,{children:n.ownerAllowed?`allowed`:`blocked`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Host`}),(0,Q.jsx)(`dd`,{children:n.hostAllowed?`available`:`unavailable`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Next attempt`}),(0,Q.jsx)(`dd`,{children:n.effectiveForNewAttempt?`effective`:`not effective`})]})]}),n.unavailableReason&&(0,Q.jsx)(`small`,{children:n.unavailableReason}),n.quota!==null&&(0,Q.jsxs)(`small`,{children:[`Per-attempt quota: `,n.quota]})]},n.operation)})}),t.canManage&&(0,Q.jsxs)(`div`,{className:`collaboration-policy-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`button`,disabled:e||!o,onClick:()=>void r(i),children:`Save policy`}),(0,Q.jsxs)(`button`,{className:`danger-button`,type:`button`,disabled:e||(t.activeGrants??0)===0,onClick:()=>void n(),children:[`Revoke active access (`,t.activeGrants??0,`)`]})]})]})}function Ug({activeChannelId:e,initialCreating:t,initialDefinitionId:n,initialSetupId:r,initialSection:i,isAdministrator:a,onAuthenticationFailure:o,onChannelAccessFailure:s,onClose:c,onCreateAgent:l,onNavigationChanged:u,onOpenChannel:d,onSelectAgent:f,principalId:p,principalName:m,principalEvents:h,runActive:g,token:_,workshopName:y}){let b=Km(),[x,S]=(0,v.useState)([]),[C,w]=(0,v.useState)([]),[T,E]=(0,v.useState)([]),[D,O]=(0,v.useState)(null),[k,A]=(0,v.useState)(n),[j,M]=(0,v.useState)(t),[N,P]=(0,v.useState)(null),[F,I]=(0,v.useState)(null),[L,R]=(0,v.useState)(!1),[ee,z]=(0,v.useState)(null),[H,te]=(0,v.useState)(!1),[U,ne]=(0,v.useState)(``),[re,W]=(0,v.useState)(!0),[ie,ae]=(0,v.useState)(!1),[oe,se]=(0,v.useState)(null),ce=h.subscribe,le=(0,v.useCallback)((e,t)=>{e instanceof B?o(e.message):e instanceof V&&s(e.message),se(e instanceof Error?e.message:t)},[o,s]),ue=(0,v.useCallback)(async()=>{let[e,t,r]=await Promise.all([Le(_),He(_),Be(_)]);S(e),w(t),E(r),A(t=>{let r=t??n;return r&&e.some(e=>e.definitionId===r)?r:null})},[n,_]);(0,v.useEffect)(()=>{let e=!1;return W(!0),ue().then(()=>{e||(W(!1),se(null))},t=>{e||(W(!1),le(t,`Could not load agents.`))}),()=>{e=!0}},[le,ue]),(0,v.useEffect)(()=>ce(e=>{(e.kind===`synchronize`||e.batch.changes.some(e=>e.agentChanges.length>0))&&Promise.all([ue(),u()]).catch(e=>le(e,`Could not refresh agents.`))}),[le,u,ue,ce]);let G=x.find(e=>e.definitionId===k)??null,K=C.find(e=>e.definitionId===k)??null,q=G?Fg(G):null,de=T.find(e=>e.provisioning.operationId===r)??null,J=j&&!de&&G?.lifecycleState===`draft`?(()=>{let e=G.revisions[0];return e?{avatar:G.presentation.avatar??``,capabilities:e.capabilities,collaborationOperations:e.collaborationOperations,definitionId:G.definitionId,description:G.description,displayName:G.displayName,handle:G.handle,instructions:e.instructions,purpose:e.purpose}:null})():null,Y=!n&&!r,fe=G?.ownerPrincipalId===p,pe=(0,v.useMemo)(()=>K?.lifecycleState===`enabled`&&K.directChannelId?{channelId:K.directChannelId,token:_}:null,[K?.directChannelId,K?.lifecycleState,_]);(0,v.useEffect)(()=>{M(t),n&&A(n)},[t,n]),(0,v.useEffect)(()=>{re||!j||Y||de||J||(M(!1),f(k))},[j,Y,re,f,J,de,k]),(0,v.useEffect)(()=>{let e=!1;return j?(P(null),I(null),R(!0),Re(_).then(t=>{e||(P(t),R(!1))},t=>{e||(t instanceof B?o(t.message):t instanceof V&&s(t.message),I(t instanceof Error?t.message:`Could not load agent creation options.`),R(!1))}),()=>{e=!0}):(P(null),I(null),R(!1),()=>{e=!0})},[j,o,s,_]),(0,v.useEffect)(()=>{te(!1)},[k]),(0,v.useEffect)(()=>{let e=!1;return O(null),k&&Z(_,k).then(t=>{e||O(t)},t=>{e||le(t,`Could not load collaboration policy.`)}),()=>{e=!0}},[le,k,_]),(0,v.useEffect)(()=>{ne(K?.runtimeProfileId??K?.eligibleRuntimes[0]?.runtimeProfileId??``)},[K?.eligibleRuntimes,K?.runtimeProfileId]),(0,v.useEffect)(()=>{if(i!==`runtime`||!pe)return;let e=window.setTimeout(()=>{document.getElementById(`agent-runtime-settings`)?.scrollIntoView?.({block:`start`})},0);return()=>window.clearTimeout(e)},[i,pe]);let me=async(e,t)=>{ae(!0),se(null);try{await e()}catch(e){le(e,t)}finally{ae(!1)}},he=async(e,t)=>{await ue(),await u(),M(!1),A(e),z(t?e:null),f(e)},X=async e=>{ae(!0);try{let t=await $e(_,{...e,idempotencyKey:Pg(`create`)});await he(t.definitionId,!1)}catch(e){throw e instanceof B?o(e.message):e instanceof V&&s(e.message),e}finally{ae(!1)}},ge=async e=>{ae(!0);try{let t=await Ve(_,e);return t.status===`ready`&&t.definitionId?await he(t.definitionId,!0):(await ue(),await u()),t}catch(e){throw e instanceof B?o(e.message):e instanceof V&&s(e.message),e}finally{ae(!1)}},_e=e=>G?me(async()=>{await et(_,G.definitionId,{...e,expectedVersion:G.stateVersion,idempotencyKey:Pg(`revision`)}),await ue(),te(!1)},`Could not save this revision.`):Promise.resolve(),ve=e=>!G||!D?Promise.resolve():me(async()=>{let t=await Ze(_,G.definitionId,{allowedOperations:e,clientOperationId:Pg(`collaboration-policy`),expectedPolicyVersion:D.policyVersion});O(t)},`Could not update collaboration policy.`),ye=async()=>{!G||!D||!await b(`Immediately revoke active collaboration access for @${G.handle}? Current attempts will be fenced.`)||await me(async()=>{let e=await Qe(_,G.definitionId,Pg(`collaboration-revoke`));O(e)},`Could not revoke active collaboration access.`)},be=e=>G?me(async()=>{await tt(_,G.definitionId,{expectedVersion:G.stateVersion,idempotencyKey:Pg(`activate`),revisionId:e}),await ue(),O(await Z(_,G.definitionId)),await u()},`Could not activate this agent revision.`):Promise.resolve(),xe=async()=>{!G||!await b(`Archive @${G.handle}? Existing history remains available, but the agent will no longer be runnable.`)||await me(async()=>{await nt(_,G.definitionId,{expectedVersion:G.stateVersion,idempotencyKey:Pg(`archive`)}),await ue(),await u()},`Could not archive this agent.`)},Se=()=>!G||!K||!U?Promise.resolve():me(async()=>{await rt(_,G.definitionId,{expectedVersion:K.stateVersion,idempotencyKey:Pg(`enable`),runtimeProfileId:U}),await ue(),await u()},`Could not enable this agent.`),Ce=()=>{if(!G||!K)return Promise.resolve();let e=G.definitionId;return me(async()=>{let t=K;if(t.lifecycleState!==`enabled`){let n=t.eligibleRuntimes[0];if(t.canManage||!n)throw Error(`This agent conversation is not available.`);t=await rt(_,e,{expectedVersion:t.stateVersion,idempotencyKey:Pg(`conversation-access`),runtimeProfileId:n.runtimeProfileId})}if(!t.directChannelId||t.stateVersion===null||(t.conversationStarted||(t=await it(_,e,{expectedVersion:t.stateVersion,idempotencyKey:Pg(`conversation`)})),!t.directChannelId))throw Error(`This agent conversation is not available.`);await ue(),await u(),await d(t.directChannelId)},`Could not open this agent conversation.`)},we=(0,v.useMemo)(()=>{let e=new Set(T.map(e=>e.provisioning.definitionId));return{archived:x.filter(e=>e.lifecycleState===`archived`).length,drafts:x.filter(t=>t.lifecycleState===`draft`&&!e.has(t.definitionId)).length,needsAttention:T.length,ready:x.filter(t=>t.lifecycleState===`active`&&!e.has(t.definitionId)).length}},[x,T]),Te=G&&K?.canManage&&K.eligibleRuntimes.length>1?(0,Q.jsxs)(`details`,{className:`settings-card agent-execution-profile-card`,children:[(0,Q.jsx)(`summary`,{children:`Advanced execution profile`}),(0,Q.jsxs)(`p`,{children:[`Choose which authorized execution context sponsors @`,G.handle,`. Backend and model choices remain in Runtime settings.`]}),(0,Q.jsxs)(`label`,{children:[`Execution profile`,(0,Q.jsx)(`select`,{value:U,disabled:ie,onChange:e=>ne(e.target.value),children:K.eligibleRuntimes.map(e=>(0,Q.jsx)(`option`,{value:e.runtimeProfileId,children:e.displayName},e.runtimeProfileId))})]}),K.lifecycleState===`enabled`&&U!==K.runtimeProfileId&&(0,Q.jsx)(`div`,{className:`settings-actions`,children:(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:ie||!U,onClick:()=>void Se(),children:ie?`Updating…`:`Change execution profile`})})]}):null;return(0,Q.jsxs)(`main`,{className:`agent-workspace`,"aria-label":`Agents workspace`,children:[(0,Q.jsxs)(`header`,{className:`agent-workspace-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`p`,{className:`breadcrumbs`,children:[y,` / Agents`]}),(0,Q.jsxs)(`div`,{className:`agent-workspace-title`,children:[(0,Q.jsx)(`h1`,{children:`Agents`}),(0,Q.jsxs)(`p`,{children:[we.ready,` ready · `,we.drafts,` drafts · `,we.needsAttention,` need attention · `,m]})]})]}),(0,Q.jsxs)(`div`,{className:`agent-header-actions`,children:[(0,Q.jsx)(`span`,{className:`agent-live-state ${h.connection.tone}`,role:`status`,children:h.connection.label}),(0,Q.jsxs)(`div`,{className:`agent-header-controls`,children:[(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Create agent`,title:`Create agent`,disabled:ie,onClick:()=>{M(!0),te(!1),l()},children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`+`})}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close agents`,title:`Close agents`,onClick:c,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]})]})]}),(0,Q.jsx)(`div`,{className:`agent-workspace-body`,children:(0,Q.jsxs)(`section`,{className:`agent-detail`,"aria-live":`polite`,children:[G?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`agent-detail-identity`,children:[(0,Q.jsx)(`span`,{className:`agent-detail-avatar`,"aria-hidden":`true`,children:G.presentation.avatar||G.displayName.slice(0,1).toUpperCase()}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`agent-detail-title-row`,children:[(0,Q.jsx)(`h2`,{children:G.displayName}),(0,Q.jsx)(`span`,{className:`agent-status ${G.lifecycleState}`,children:Ig(G.lifecycleState)}),G.lifecycleState===`active`&&K&&(K.lifecycleState===`enabled`&&K.directChannelId||!K.canManage&&K.lifecycleState!==`enabled`&&K.ownerRuntimeProfileId&&K.eligibleRuntimes.length>0)&&(0,Q.jsx)(`button`,{className:`panel-icon-button agent-conversation-button`,type:`button`,"aria-label":`${K.conversationStarted?`Open`:`Start`} conversation with ${G.displayName}`,title:`${K.conversationStarted?`Open`:`Start`} conversation with ${G.displayName}`,disabled:ie,onClick:()=>void Ce(),children:(0,Q.jsx)(Lg,{})})]}),(0,Q.jsxs)(`p`,{className:`agent-handle`,children:[`@`,G.handle]}),(0,Q.jsx)(`p`,{children:G.description||`No description has been provided.`})]})]}),ee===G.definitionId&&(0,Q.jsxs)(`section`,{className:`agent-ready-summary`,role:`status`,children:[(0,Q.jsx)(`strong`,{children:`Agent ready`}),(0,Q.jsx)(`p`,{children:`Revision 1 and the selected runtime settings are active. Start a conversation with the speech-bubble action when you are ready; no conversation was created automatically.`})]}),(0,Q.jsxs)(`section`,{className:`agent-authority-note`,children:[(0,Q.jsx)(`strong`,{children:fe?`You own and manage this agent.`:`Owned and managed by ${G.ownerDisplayName??`another Workshop member`}.`}),(0,Q.jsxs)(`p`,{children:[`Everyone talks to the same @`,G.handle,` definition and owner-sponsored runtime. Conversations, transcripts, and memory remain private to each person.`]})]}),G.lifecycleState===`active`&&K&&!K.canManage&&K.lifecycleState!==`enabled`&&(!K.ownerRuntimeProfileId||K.eligibleRuntimes.length===0)&&(0,Q.jsx)(`section`,{className:`agent-enablement-card`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Conversation unavailable`}),(0,Q.jsx)(`h3`,{children:K.ownerRuntimeProfileId?`Unavailable to this Workshop account`:`Waiting for the agent owner’s runtime`})]})}),G.lifecycleState===`active`&&K?.canManage&&K.lifecycleState!==`enabled`&&(0,Q.jsx)(`section`,{className:`agent-runtime-controls agent-runtime-setup`,"aria-label":`${G.displayName} runtime settings`,id:`agent-runtime-settings`,children:(0,Q.jsxs)(`section`,{className:`settings-section`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{children:`Runtime settings`}),(0,Q.jsx)(`p`,{children:`Enable this agent on one of your authorized execution profiles before choosing its backend, model, and workspace.`})]}),(0,Q.jsxs)(`div`,{className:`settings-card-stack`,children:[(0,Q.jsxs)(`article`,{className:`settings-card agent-runtime-setup-card`,children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Enable agent`}),K.eligibleRuntimes.length===0?(0,Q.jsx)(`p`,{children:`No authorized execution profile can satisfy this agent yet.`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{children:K.eligibleRuntimes.length===1?`Your authorized execution profile will be used automatically.`:`An eligible execution profile is selected. Use Advanced execution profile to choose another.`}),(0,Q.jsx)(`div`,{className:`settings-actions`,children:(0,Q.jsx)(`button`,{className:`primary-button`,type:`button`,disabled:ie||!U,onClick:()=>void Se(),children:ie?`Enabling…`:`Enable agent`})})]})]}),Te]})]})}),pe&&G&&fe&&(0,Q.jsx)(gg,{executionProfileControl:Te,isAdministrator:a,onAuthenticationFailure:o,onChannelAccessFailure:s,principalName:m,roleLabel:a?`Workshop administrator`:`Workshop member`,runtimeLabel:G.displayName,runActive:e===pe.channelId&&g,session:pe}),q?(0,Q.jsxs)(`section`,{className:`agent-active-revision`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Active definition`}),(0,Q.jsxs)(`h3`,{children:[`Revision `,q.revisionNumber]}),(0,Q.jsx)(`p`,{children:q.purpose}),(0,Q.jsx)(`div`,{className:`agent-capability-tags`,children:q.capabilities.map(e=>(0,Q.jsx)(`span`,{children:e.replaceAll(`_`,` `)},e))}),q.collaborationOperations.length>0&&(0,Q.jsx)(`div`,{className:`agent-capability-tags agent-collaboration-tags`,children:q.collaborationOperations.map(e=>(0,Q.jsx)(`span`,{children:e.replaceAll(`_`,` `)},e))})]}):(0,Q.jsx)(`p`,{className:`agent-state-copy`,children:`This draft is not active and cannot be enabled or run.`}),D&&(0,Q.jsx)(Hg,{busy:ie,policy:D,onRevoke:ye,onSave:ve}),fe&&G.lifecycleState!==`archived`&&(0,Q.jsxs)(`section`,{className:`agent-admin-controls`,children:[(0,Q.jsxs)(`div`,{className:`agent-section-heading`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Owner controls`}),(0,Q.jsx)(`h3`,{children:`Definition revisions`})]}),!H&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:ie,onClick:()=>te(!0),children:`New revision`})]}),H?(0,Q.jsx)(Vg,{agent:G,busy:ie,onCancel:()=>te(!1),onSave:_e}):(0,Q.jsx)(`ol`,{className:`agent-revision-list`,children:[...G.revisions].reverse().map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`strong`,{children:[`Revision `,e.revisionNumber]}),(0,Q.jsx)(`small`,{children:Rg(e.createdAt)})]}),(0,Q.jsx)(`p`,{children:e.purpose}),e.revisionId===G.activeRevisionId?(0,Q.jsx)(`span`,{className:`agent-status active`,children:`active`}):(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:ie,onClick:()=>void be(e.revisionId),children:`Activate`})]},e.revisionId))}),(0,Q.jsxs)(`div`,{className:`agent-archive-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`Archive definition`}),(0,Q.jsx)(`p`,{children:`Preserves messages and provenance while preventing future runs.`})]}),(0,Q.jsx)(`button`,{className:`danger-button`,type:`button`,disabled:ie,onClick:()=>void xe(),children:`Archive`})]})]}),G.lifecycleState===`archived`&&(0,Q.jsx)(`p`,{className:`agent-archived-note`,children:`This definition is archived. Historical conversations and revision provenance remain available, but it cannot be enabled or run.`})]}):re?(0,Q.jsx)(`p`,{className:`agent-state-copy`,children:`Loading agent details…`}):(0,Q.jsxs)(`div`,{className:`agent-empty-detail`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`@`}),(0,Q.jsx)(`h2`,{children:`No agent selected`}),(0,Q.jsx)(`p`,{children:`Choose an active agent from the sidebar or open the agent archive.`})]}),oe&&(0,Q.jsx)(`p`,{className:`agent-workspace-error`,role:`alert`,children:oe})]})}),j&&(Y||de||J)&&(0,Q.jsx)(Ng,{busy:ie,existingHandles:x.map(e=>e.handle),options:N,optionsError:F,optionsLoading:L,resumeDraft:J,resumeInput:de?.input??null,resumeProvisioning:de?.provisioning??null,onCancel:()=>{M(!1),f(k)},onCreateReady:ge,onSaveDraft:X},de?.provisioning.operationId??J?.definitionId??`new`)]})}function Wg({actions:e,connection:t,symbol:n,title:r,workshopName:i}){return(0,Q.jsxs)(`header`,{className:`conversation-header activity-workspace-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`p`,{className:`breadcrumbs`,children:[i,` / Activity`]}),(0,Q.jsxs)(`h2`,{children:[(0,Q.jsx)(`span`,{className:`activity-heading-symbol`,"aria-hidden":`true`,children:n}),r]})]}),(0,Q.jsxs)(`div`,{className:`conversation-actions`,children:[e,(0,Q.jsxs)(`span`,{className:`connection-indicator ${t.tone}`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`connection-dot`,"aria-hidden":`true`}),t.label]})]})]})}var Gg={active:!1,stateVersion:0,url:null};function Kg(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}function qg({connection:e,inbox:t,onOpen:n,workshopName:r}){let[i,a]=(0,v.useState)(null);return(0,Q.jsxs)(`section`,{className:`mentions-workspace`,"aria-label":`Mentions`,children:[(0,Q.jsx)(Wg,{actions:t.counts.unread>0?(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:t.pending,onClick:()=>void t.markAllRead(),children:t.counts.unread>100?`Mark next 100 read`:`Mark all read`}):null,connection:e,symbol:`@`,title:`Mentions`,workshopName:r}),(0,Q.jsxs)(`div`,{className:`mentions-summary`,"aria-live":`polite`,children:[(0,Q.jsx)(`strong`,{children:t.counts.unread}),(0,Q.jsx)(`span`,{children:t.counts.unread===1?`unread mention`:`unread mentions`})]}),(0,Q.jsxs)(`div`,{className:`mentions-notices`,children:[t.error&&(0,Q.jsx)(`p`,{className:`mentions-error`,role:`alert`,children:t.error}),i&&(0,Q.jsx)(`p`,{className:`mentions-error`,role:`alert`,children:i})]}),t.loading?(0,Q.jsx)(`p`,{className:`mentions-empty`,children:`Loading mentions…`}):t.notifications.length===0?(0,Q.jsxs)(`div`,{className:`mentions-empty`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`@`}),(0,Q.jsx)(`p`,{children:`No mentions yet.`})]}):(0,Q.jsx)(`ol`,{className:`mentions-list`,children:t.notifications.map(e=>(0,Q.jsxs)(`li`,{className:e.read?`read`:`unread`,children:[(0,Q.jsxs)(`button`,{className:`mention-source-link`,type:`button`,onClick:()=>{if(a(null),!n(e)){a(`You no longer have access to that mention's source channel.`);return}},children:[(0,Q.jsx)(Kh,{avatar:e.sourceAuthorAvatar??Gg,className:`mention-avatar`,displayName:e.sourceAuthorDisplayName,principalId:e.sourceAuthorPrincipalId}),(0,Q.jsxs)(`span`,{className:`mention-copy`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.sourceAuthorDisplayName}),` mentioned you in `,(0,Q.jsx)(`b`,{children:e.channelName??`a channel`})]}),(0,Q.jsxs)(`small`,{children:[e.sourceThreadRootId?`Thread reply`:`Channel message`,` · `,Kg(e.createdAt)]})]})]}),(0,Q.jsx)(`button`,{className:`mention-state-button`,type:`button`,disabled:t.pending,"aria-label":e.read?`Mark mention unread`:`Mark mention read`,title:e.read?`Mark unread`:`Mark read`,onClick:()=>void t.setRead(e,!e.read),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:e.read?`○`:`●`})})]},e.notificationId))}),t.hasMore&&(0,Q.jsx)(`button`,{className:`mentions-load-more`,type:`button`,disabled:t.loadingMore,onClick:t.loadMore,children:t.loadingMore?`Loading…`:`Load older mentions`})]})}function Jg(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}function Yg({followed:e=!1}){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:e?`currentColor`:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9M10 21h4`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.8`})})}function Xg({connection:e,following:t,onOpen:n,workshopName:r}){let[i,a]=(0,v.useState)(null);return(0,Q.jsxs)(`section`,{className:`following-workspace`,"aria-label":`Following`,children:[(0,Q.jsx)(Wg,{connection:e,symbol:(0,Q.jsx)(Yg,{}),title:`Following`,workshopName:r}),(0,Q.jsxs)(`div`,{className:`following-summary`,"aria-live":`polite`,children:[(0,Q.jsx)(`strong`,{children:t.threads.length}),(0,Q.jsx)(`span`,{children:t.threads.length===1?`followed thread`:`followed threads`}),t.totalUnread>0&&(0,Q.jsxs)(`span`,{children:[`· `,t.totalUnread,t.totalUnread>=1e3?`+`:``,` unread`]})]}),(0,Q.jsxs)(`div`,{className:`following-notices`,children:[t.error&&(0,Q.jsx)(`p`,{className:`following-error`,role:`alert`,children:t.error}),i&&(0,Q.jsx)(`p`,{className:`following-error`,role:`alert`,children:i})]}),t.loading?(0,Q.jsx)(`p`,{className:`following-empty`,children:`Loading followed threads…`}):t.threads.length===0?(0,Q.jsxs)(`div`,{className:`following-empty`,children:[(0,Q.jsx)(Yg,{}),(0,Q.jsx)(`p`,{children:`No followed threads.`})]}):(0,Q.jsx)(`ol`,{className:`following-list`,children:t.threads.map(e=>{let r=e.state.threadRootId,i=e.state.unreadCount;return(0,Q.jsxs)(`li`,{className:i>0?`unread`:`read`,children:[(0,Q.jsxs)(`button`,{className:`following-source-link`,type:`button`,onClick:()=>{a(null),n(e)||a(`You no longer have access to that thread's channel.`)},children:[(0,Q.jsxs)(`span`,{className:`following-channel`,children:[`# `,e.channelName??`Channel`,e.channelArchived&&(0,Q.jsx)(`small`,{children:`Archived`})]}),(0,Q.jsxs)(`span`,{className:`following-root`,children:[(0,Q.jsx)(`strong`,{children:e.rootAuthorDisplayName}),(0,Q.jsx)(`span`,{children:e.rootExcerpt||`Attachment or empty message`})]}),(0,Q.jsx)(`small`,{className:`following-latest`,children:e.latestReplyCreatedAt&&e.latestReplyAuthorDisplayName?`Latest reply by ${e.latestReplyAuthorDisplayName} · ${Jg(e.latestReplyCreatedAt)}`:`Started ${Jg(e.rootCreatedAt)}`}),i>0&&(0,Q.jsxs)(`span`,{className:`following-unread`,children:[i,e.state.unreadCountCapped?`+`:``,` unread`]})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button following-unfollow-button followed`,type:`button`,"aria-label":`Unfollow thread by ${e.rootAuthorDisplayName}`,"aria-pressed":`true`,title:`Unfollow thread`,disabled:t.pendingThreadIds.has(r),onClick:()=>void t.unfollow(e),children:(0,Q.jsx)(Yg,{followed:!0})})]},r)})})]})}function Zg(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`circle`,{cx:`6`,cy:`5`,r:`2`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`19`,r:`2`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`circle`,{cx:`18`,cy:`5`,r:`2`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M6 7v10M18 7v3a5 5 0 0 1-5 5H9`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`})]})}function Qg(e){return{pending:`Queued`,executing:`Running`,succeeded:`Completed`,failed:`Failed`,cancelled:`Cancelled`,timed_out:`Timed out`}[e]}function $g(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function e_(){return globalThis.crypto?.randomUUID?`workshop-review:${globalThis.crypto.randomUUID()}`:`workshop-review:${Date.now()}-${Math.random().toString(16).slice(2)}`}function t_({connection:e,onAuthenticationFailure:t,onChannelAccessFailure:n,onReviewPullRequest:r,revision:i,session:a,workshopName:o}){let s=Km(),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(!0),[f,p]=(0,v.useState)(null),[m,h]=(0,v.useState)(null),g=(0,v.useCallback)((e,r)=>{if(e instanceof B){t(e.message);return}if(e instanceof V){n(e.message);return}h(e instanceof Error?e.message:r)},[t,n]),_=(0,v.useCallback)(async(e=!0)=>{e&&d(!0),h(null);try{l(await $n(a))}catch(e){g(e,`Could not load pull-request reviews.`)}finally{e&&d(!1)}},[g,a]);(0,v.useEffect)(()=>{_()},[_]),(0,v.useEffect)(()=>{i>0&&_(!1)},[_,i]),(0,v.useEffect)(()=>{if(!c?.jobs.some(e=>e.status===`pending`||e.status===`executing`))return;let e=window.setTimeout(()=>void _(!1),2e3);return()=>window.clearTimeout(e)},[_,c]);let y=async(e,t)=>{if(!(t===`cancel`&&!await s(`Cancel the review of ${e.repository}#${e.pullRequestNumber}?`))){p(e.reviewJobId),h(null);try{await tr(a,e.reviewJobId,t,e_()),await _(!1)}catch(e){g(e,`Could not ${t} the pull-request review.`)}finally{p(null)}}},b=async e=>{let t=window.open(`about:blank`,`_blank`);if(!t){h(`The browser blocked the review artifact window.`);return}t.opener=null,p(e.reviewJobId),h(null);try{let n=URL.createObjectURL(await nr(a,e.reviewJobId));t.location.href=n,window.setTimeout(()=>URL.revokeObjectURL(n),6e4)}catch(e){t.close(),g(e,`Could not open the review artifact.`)}finally{p(null)}},x=c?.jobs.filter(e=>e.status===`pending`||e.status===`executing`).length??0;return(0,Q.jsxs)(`section`,{className:`reviews-workspace`,"aria-label":`Reviews`,children:[(0,Q.jsx)(Wg,{actions:(0,Q.jsx)(`button`,{"aria-label":`Review pull request`,className:`panel-icon-button reviews-launch-button`,title:`Review pull request`,type:`button`,onClick:r,children:(0,Q.jsx)(Zg,{})}),connection:e,symbol:(0,Q.jsx)(Zg,{}),title:`Reviews`,workshopName:o}),(0,Q.jsxs)(`div`,{className:`reviews-summary`,"aria-live":`polite`,children:[(0,Q.jsx)(`strong`,{children:c?.jobs.length??0}),(0,Q.jsx)(`span`,{children:c?.jobs.length===1?`review`:`reviews`}),x>0&&(0,Q.jsxs)(`span`,{children:[`· `,x,` active`]})]}),m&&(0,Q.jsx)(`p`,{className:`reviews-error`,role:`alert`,children:m}),u?(0,Q.jsx)(`p`,{className:`reviews-empty`,children:`Loading reviews…`}):!c||c.jobs.length===0?(0,Q.jsxs)(`div`,{className:`reviews-empty`,children:[(0,Q.jsx)(Zg,{}),(0,Q.jsx)(`p`,{children:`No on-demand reviews yet.`})]}):(0,Q.jsx)(`ol`,{className:`review-list`,children:c.jobs.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`div`,{className:`review-copy`,children:[(0,Q.jsxs)(`strong`,{children:[e.repository,`#`,e.pullRequestNumber]}),(0,Q.jsxs)(`small`,{children:[Qg(e.status),` · `,$g(e.updatedAt)]}),e.lastErrorCode&&(0,Q.jsxs)(`small`,{children:[`Error: `,e.lastErrorCode.replaceAll(`_`,` `)]}),e.artifact&&e.artifact.warningCount>0&&(0,Q.jsxs)(`details`,{className:`review-warnings`,children:[(0,Q.jsxs)(`summary`,{className:`review-warning`,children:[e.artifact.warningCount,` collection warning`,e.artifact.warningCount===1?``:`s`]}),(0,Q.jsx)(`ul`,{children:e.artifact.warnings.map((e,t)=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`strong`,{children:e.source.replaceAll(`_`,` `)}),`: `,e.message]},`${e.source}-${t}`))})]})]}),(0,Q.jsxs)(`div`,{className:`review-actions`,children:[e.artifact&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:f===e.reviewJobId,onClick:()=>void b(e),children:`Open`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:f===e.reviewJobId,onClick:()=>void rr(a,e).catch(e=>g(e,`Could not download the review artifact.`)),children:`Download`})]}),(e.status===`pending`||e.status===`executing`)&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:f===e.reviewJobId,onClick:()=>void y(e,`cancel`),children:`Cancel`}),(e.status===`failed`||e.status===`cancelled`||e.status===`timed_out`)&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:f===e.reviewJobId,onClick:()=>void y(e,`retry`),children:`Retry`})]})]},e.reviewJobId))})]})}var n_={read:0,total:0,unread:0,unreadByChannel:{}},r_={kind:`mention`};function i_(e){let t=new Uint8Array(8);return crypto.getRandomValues(t),`${e}-${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function a_(e,t){let n=e.filter(e=>e.notificationId!==t.notificationId);return n.push(t),n.sort((e,t)=>t.createdEventPosition-e.createdEventPosition)}function o_(e,t,n){let[r,i]=(0,v.useState)({counts:n_,error:null,hasMore:!1,loading:!0,loadingMore:!1,notifications:[],pending:!1}),a=(0,v.useRef)(null),o=(0,v.useRef)(!1),s=(0,v.useRef)(null),c=(0,v.useRef)(new Set),l=t.subscribe,u=(0,v.useCallback)(async t=>{let n=await Xr(e,r_,t);i(e=>({...e,counts:n}))},[e]),d=(0,v.useCallback)(async t=>{let n=await Yr(e,{...r_,limit:50},t);return a.current=n.nextCursor,i(e=>({...e,counts:n.counts,error:null,hasMore:n.nextCursor!==null,loading:!1,notifications:e.notifications.filter(e=>e.lastEventPosition>n.throughPosition).reduce(a_,n.notifications)})),n.throughPosition},[e]);(0,v.useEffect)(()=>{let e=new AbortController,t=()=>{s.current===null&&(s.current=window.setTimeout(()=>{s.current=null,u(e.signal).catch(e=>{e instanceof B&&n(e.message)})},100))},r=()=>{d(e.signal).catch(t=>{if(!e.signal.aborted){if(t instanceof B){n(t.message);return}i(e=>({...e,error:e.loading?t instanceof Error?t.message:`Could not load mentions.`:e.error,loading:!1}))}})},a=l(e=>{if(e.kind===`synchronize`){r();return}let n=!1;for(let t of e.batch.changes)for(let{notification:e}of t.notificationChanges)e.kind===`mention`&&(n=!0,i(t=>({...t,notifications:a_(t.notifications,e)})));n&&t()});return r(),()=>{a(),e.abort(),s.current!==null&&(window.clearTimeout(s.current),s.current=null)}},[n,u,d,l]);let f=(0,v.useCallback)(()=>{let t=a.current;!t||o.current||(o.current=!0,i(e=>({...e,loadingMore:!0})),Yr(e,{...r_,cursor:t,limit:50}).then(e=>{a.current=e.nextCursor,i(t=>{let n=new Set(t.notifications.map(e=>e.notificationId));return{...t,counts:e.counts,error:null,hasMore:e.nextCursor!==null,loadingMore:!1,notifications:[...t.notifications,...e.notifications.filter(e=>!n.has(e.notificationId))]}}),o.current=!1},e=>{if(o.current=!1,e instanceof B){n(e.message);return}i(t=>({...t,error:e instanceof Error?e.message:`Could not load more mentions.`,loadingMore:!1}))}))},[n,e]),p=(0,v.useCallback)(async(t,r)=>{i(e=>({...e,error:null,pending:!0}));try{let n=r?await Qr(e,t.notificationId,t.stateVersion,i_(`mention-read`)):await $r(e,t.notificationId,t.stateVersion,i_(`mention-unread`)),a=await Xr(e,r_);i(e=>({...e,counts:a,notifications:a_(e.notifications,n.notification),pending:!1}))}catch(e){if(e instanceof B){n(e.message);return}i(t=>({...t,error:e instanceof Error?e.message:`Could not update this mention.`,pending:!1}))}},[n,e]),m=(0,v.useCallback)(async()=>{i(e=>({...e,error:null,pending:!0}));try{let t=await Yr(e,{...r_,limit:100,unreadOnly:!0});if(t.notifications.length>0){let n=await ei(e,t.notifications.map(e=>({expectedStateVersion:e.stateVersion,notificationId:e.notificationId})),i_(`mentions-read`));i(e=>({...e,notifications:n.reduce((e,t)=>a_(e,t.notification),e.notifications)}))}let n=await Xr(e,r_);i(e=>({...e,counts:n,pending:!1}))}catch(e){if(e instanceof B){n(e.message);return}i(t=>({...t,error:e instanceof Error?e.message:`Could not mark mentions read.`,pending:!1}))}},[n,e]),h=(0,v.useCallback)(async t=>{let a=r.notifications.filter(e=>!e.read&&e.sourceMessageId===t&&!c.current.has(e.notificationId));if(a.length!==0){for(let e of a)c.current.add(e.notificationId);try{let t=await Promise.all(a.map(t=>Qr(e,t.notificationId,t.stateVersion,i_(`mention-viewed`)))),n=await Xr(e,r_);i(e=>({...e,counts:n,notifications:t.reduce((e,t)=>a_(e,t.notification),e.notifications)}))}catch(e){if(e instanceof B){n(e.message);return}i(t=>({...t,error:e instanceof Error?e.message:`Could not mark the displayed mention read.`}))}finally{for(let e of a)c.current.delete(e.notificationId)}}},[n,r.notifications,e]);return{...r,loadMore:f,markAllRead:m,markVisibleRead:h,setRead:p}}function s_(){let e=new Uint8Array(8);return crypto.getRandomValues(e),`following-unfollow-${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function c_(e,t,n){let[r,i]=(0,v.useState)({error:null,loading:!0,pendingThreadIds:new Set,threads:[],totalUnread:0}),a=(0,v.useRef)(null),o=t.subscribe,s=(0,v.useCallback)(async t=>{let n=await ii(e,t);i(e=>({...e,error:null,loading:!1,threads:n.threads,totalUnread:n.threads.reduce((e,t)=>Math.min(1e3,e+t.state.unreadCount),0)}))},[e]);(0,v.useEffect)(()=>{let e=new AbortController,t=()=>{s(e.signal).catch(t=>{if(!e.signal.aborted){if(t instanceof B){n(t.message);return}i(e=>({...e,error:t instanceof Error?t.message:`Could not load followed threads.`,loading:!1}))}})},r=()=>{a.current===null&&(a.current=window.setTimeout(()=>{a.current=null,t()},50))},c=o(e=>{if(e.kind===`synchronize`){t();return}e.batch.changes.some(e=>e.threadChanges.length>0||e.unreadChanges.length>0)&&r()});return t(),()=>{c(),e.abort(),a.current!==null&&(window.clearTimeout(a.current),a.current=null)}},[n,s,o]);let c=(0,v.useCallback)(async t=>{let r=t.state.threadRootId;i(e=>({...e,error:null,pendingThreadIds:new Set(e.pendingThreadIds).add(r)}));try{let n=await si({channelId:t.state.channelId,token:e},r,!1,t.state.stateVersion,s_());i(e=>{let t=new Set(e.pendingThreadIds);t.delete(r);let i=n.state.followed?e.threads:e.threads.filter(e=>e.state.threadRootId!==r);return{...e,pendingThreadIds:t,threads:i,totalUnread:i.reduce((e,t)=>Math.min(1e3,e+t.state.unreadCount),0)}})}catch(e){if(e instanceof B){n(e.message);return}if(e instanceof te||e instanceof V)try{await s()}catch{}i(t=>{let n=new Set(t.pendingThreadIds);return n.delete(r),{...t,error:e instanceof Error?e.message:`Could not unfollow this thread.`,pendingThreadIds:n}})}},[n,s,e]);return{...r,unfollow:c}}function l_(){let e=new Uint8Array(8);return crypto.getRandomValues(e),`channel-read-${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function u_(e){return Object.fromEntries(e.map(e=>[e.channelId,e]))}function d_(e){return Math.min((e?.unreadCount??0)+(e?.unreadReplyCount??0),1e3)}function f_(e,t,n,r){let[i,a]=(0,v.useState)({byChannel:{},error:null,loading:!0,totalUnread:0,totalUnreadCapped:!1}),o=(0,v.useRef)(i),s=(0,v.useRef)(new Map),c=(0,v.useRef)(new Set),l=t.subscribe;o.current=i;let u=(0,v.useCallback)(async t=>{let n=await li(e,t),r={byChannel:u_(n.channels),error:null,loading:!1,totalUnread:n.totalUnread,totalUnreadCapped:n.totalUnreadCapped};return o.current=r,a(r),n.throughPosition},[e]);(0,v.useEffect)(()=>{let e=new AbortController,t=()=>{u(e.signal).catch(t=>{if(!e.signal.aborted){if(t instanceof B){n(t.message);return}a(e=>({...e,error:e.loading?t instanceof Error?t.message:`Could not load unread messages.`:e.error,loading:!1}))}})},r=l(e=>{if(e.kind===`synchronize`){t();return}for(let t of e.batch.changes)for(let{state:e}of t.unreadChanges)a(t=>{let n=t.byChannel[e.channelId],r=Math.min(1e3,Math.max(0,t.totalUnread-d_(n)+d_(e))),i={...t,byChannel:{...t.byChannel,[e.channelId]:e},totalUnread:r};return o.current=i,i})});return t(),()=>{r(),e.abort()}},[n,u,l]);let d=(0,v.useCallback)((e,t)=>{let i=o.current.byChannel[e.channelId];if(!i||t.channelId!==e.channelId||t.threadRootId!==null||t.eventPosition<=i.readThroughEventPosition)return;let l=s.current.get(e.channelId);(!l||l.eventPosition{try{for(;s.current.has(e.channelId);){let t=s.current.get(e.channelId);if(s.current.delete(e.channelId),!t)continue;let i=o.current.byChannel[e.channelId];if(!(!i||t.eventPosition<=i.readThroughEventPosition))try{let n=await ui(e,t.messageId,i.stateVersion,l_());a(t=>{let r=t.byChannel[e.channelId],i={...t,byChannel:{...t.byChannel,[e.channelId]:n.state},totalUnread:Math.min(1e3,Math.max(0,t.totalUnread-d_(r)+d_(n.state)))};return o.current=i,i})}catch(c){if(c instanceof B){n(c.message);return}if(c instanceof V){r(c.message);return}if(c instanceof H){await u(),i=o.current.byChannel[e.channelId],i&&t.eventPosition>i.readThroughEventPosition&&s.current.set(e.channelId,t);continue}a(e=>({...e,error:c instanceof Error?c.message:`Could not update unread messages.`}))}}}finally{c.current.delete(e.channelId)}})())},[n,r,u]);return{...i,advanceVisible:d}}var p_=2e3;function m_(e){return new Promise(t=>{let n=window.setTimeout(t,p_);e.addEventListener(`abort`,()=>{window.clearTimeout(n),t()},{once:!0})})}function h_(e,t){let[n,r]=(0,v.useState)({label:`Connecting`,tone:`connecting`}),i=(0,v.useRef)(!1),a=(0,v.useRef)(new Set),o=(0,v.useRef)(t);o.current=t;let s=(0,v.useCallback)(e=>{for(let t of a.current)t(e)},[]),c=(0,v.useCallback)(e=>(a.current.add(e),i.current&&e({kind:`synchronize`}),()=>a.current.delete(e)),[]);return(0,v.useEffect)(()=>{let t=new AbortController,n=null,a=!0;return(async()=>{for(;!t.signal.aborted;){try{i.current=!1,r({label:`Connecting`,tone:`connecting`}),await bi(e,n,{onBatch:(e,t)=>{n=t,a&&(a=!1,i.current=!0,s({kind:`synchronize`})),s({batch:e,kind:`batch`})},onConnected:()=>{r({label:`Live`,tone:`connected`})}},t.signal)}catch(e){if(t.signal.aborted)return;if(i.current=!1,r({label:`Connecting`,tone:`connecting`}),e instanceof B){o.current(e.message);return}e instanceof U&&(n=null,a=!0)}await m_(t.signal)}})(),()=>{i.current=!1,t.abort()}},[s,e]),(0,v.useMemo)(()=>({connection:n,subscribe:c}),[n,c])}function g_({actions:e,error:t,loading:n,onClose:r,onInvoke:i}){let a=(0,v.useRef)(null),o=(0,v.useRef)(null),[s,c]=(0,v.useState)(``),[l,u]=(0,v.useState)(0),[d,f]=(0,v.useState)(null),[p,m]=(0,v.useState)(null),[h,g]=(0,v.useState)(null),_=(0,v.useMemo)(()=>{let t=s.trim().toLocaleLowerCase();return t?e.filter(({capability:e,targetLabel:n})=>[e.label,e.description,n??``].join(` `).toLocaleLowerCase().includes(t)):e},[e,s]);(0,v.useLayoutEffect)(()=>(o.current=document.activeElement instanceof HTMLElement?document.activeElement:null,a.current?.focus(),()=>o.current?.focus()),[]),(0,v.useEffect)(()=>{u(e=>Math.min(e,Math.max(_.length-1,0)))},[_.length]);let y=async e=>{if(d===null){f(e.key),g(null),m(null);try{let t=await i(e);t===null?r():m(t)}catch(e){g(e instanceof Error?e.message:`Could not complete this action.`)}finally{f(null)}}};return(0,Q.jsx)(`div`,{className:`action-palette-backdrop`,onMouseDown:r,children:(0,Q.jsxs)(`section`,{"aria-label":`Help and actions`,"aria-modal":`true`,className:`action-palette`,onMouseDown:e=>e.stopPropagation(),role:`dialog`,children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Kai Workshop`}),(0,Q.jsx)(`h2`,{children:`Help and actions`})]}),(0,Q.jsx)(`button`,{"aria-label":`Close help and actions`,className:`panel-icon-button`,onClick:r,title:`Close`,type:`button`,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsxs)(`label`,{className:`action-palette-search`,children:[(0,Q.jsx)(`span`,{className:`visually-hidden`,children:`Search actions`}),(0,Q.jsx)(`input`,{"aria-activedescendant":_[l]?`action-${_[l].key}`:void 0,"aria-controls":`action-palette-results`,"aria-expanded":`true`,"aria-label":`Search actions`,autoComplete:`off`,onChange:e=>{c(e.target.value),u(0),m(null)},onKeyDown:e=>{if(e.key===`Escape`){e.preventDefault(),r();return}if(e.key===`ArrowDown`||e.key===`ArrowUp`){if(e.preventDefault(),_.length===0)return;let t=e.key===`ArrowDown`?1:-1;u(e=>(e+t+_.length)%_.length);return}e.key===`Enter`&&_[l]&&(e.preventDefault(),y(_[l]))},placeholder:`Search actions and destinations…`,ref:a,role:`combobox`,value:s}),(0,Q.jsx)(`kbd`,{children:`Esc`})]}),(0,Q.jsx)(`div`,{className:`action-palette-results`,id:`action-palette-results`,role:`listbox`,children:n?(0,Q.jsx)(`p`,{role:`status`,children:`Loading available actions…`}):t?(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:t}):_.length===0?(0,Q.jsxs)(`p`,{children:[`No available actions match “`,s,`”.`]}):_.map((e,t)=>(0,Q.jsxs)(`button`,{"aria-selected":l===t,className:l===t?`selected`:``,disabled:d!==null,id:`action-${e.key}`,onClick:()=>void y(e),onMouseMove:()=>u(t),role:`option`,type:`button`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.capability.label}),(0,Q.jsx)(`small`,{children:e.capability.description})]}),e.targetLabel&&(0,Q.jsx)(`em`,{children:e.targetLabel})]},e.key))}),(p||h)&&(0,Q.jsx)(`p`,{className:h?`settings-error action-palette-feedback`:`action-palette-feedback`,role:h?`alert`:`status`,children:h??p}),(0,Q.jsxs)(`footer`,{children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`kbd`,{children:`↑`}),(0,Q.jsx)(`kbd`,{children:`↓`}),` navigate`]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`kbd`,{children:`Enter`}),` open`]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`kbd`,{children:`Esc`}),` close`]})]})]})})}var __=`kai.workshop.client-credential.v1`,v_=`kai.workshop.active-channel.v1`,y_=`kai.workshop.read-session.v1`,b_=`kai.workshop.active-runs.v2`,x_=`kai.workshop.active-run.v1`,S_=`kai.workshop.drafts.v1`,C_=`kai.workshop.timeline-viewports.v1`,w_=`kai.workshop.sidebar-layout.v4`,T_=`kai.workshop.context-sections.v1`,E_=96,D_=1.5,O_=176*D_,k_=O_,A_=420*D_,j_=56*D_,M_=/^[A-Za-z0-9_-]{1,256}$/,N_={active:!1,stateVersion:0,url:null};function P_(e,t){let n=new Map,r=new Set;for(let e of[...t].reverse())r.add(e.authorPrincipalId),n.has(e.authorPrincipalId)||n.set(e.authorPrincipalId,{avatar:e.authorKind===`human`?e.authorAvatar??N_:null,displayName:e.authorDisplayName,kind:e.authorKind===`human`?`human`:`agent`,principalId:e.authorPrincipalId});for(let t of e.replyParticipants)n.has(t.principalId)||n.set(t.principalId,t);let i=new Set(e.replyParticipants.map(e=>e.principalId)),a=e.replyParticipantCount===e.replyParticipants.length?[...r].filter(e=>!i.has(e)).length:0,o=[...n.values()].slice(0,3);return{replyParticipantCount:Math.max(e.replyParticipantCount+a,o.length),replyParticipants:o}}function F_(){let e=new URLSearchParams(window.location.search);if(e.get(`view`)===`workspaces`)return{kind:`workspaces`};if(e.get(`view`)===`scheduled-jobs`)return{kind:`scheduled-jobs`};if(e.get(`view`)===`mentions`)return{kind:`mentions`};if(e.get(`view`)===`following`)return{kind:`following`};if(e.get(`view`)===`reviews`)return{kind:`reviews`};if(e.get(`view`)===`settings`){let t=e.get(`runtime`),n=e.get(`agent`);return n&&S.test(n)?{creating:!1,definitionId:n,kind:`agents`,section:`runtime`,setupId:null}:{kind:`settings`,runtimeChannelId:t&&b.test(t)?t:null,section:e.get(`section`)===`administration`?`administration`:e.get(`section`)===`github`?`github`:null}}if(e.get(`view`)===`agents`){let t=e.get(`agent`);return{creating:e.get(`new`)===`1`,kind:`agents`,definitionId:t&&S.test(t)?t:null,section:e.get(`section`)===`runtime`?`runtime`:null,setupId:e.get(`setup`)&&C.test(e.get(`setup`))?e.get(`setup`):null}}if(e.get(`view`)!==`memory`){let t=e.get(`message`),n=e.get(`thread`);return{kind:`conversation`,...t&&A.test(t)?{messageId:t}:{},...n&&A.test(n)?{threadRootId:n}:{}}}let t=e.get(`memory`);return{kind:`memory`,memoryId:t&&M_.test(t)?t:null}}function I_(e,t){let n=new URL(window.location.href);n.searchParams.delete(`view`),n.searchParams.delete(`memory`),n.searchParams.delete(`agent`),n.searchParams.delete(`runtime`),n.searchParams.delete(`new`),n.searchParams.delete(`section`),n.searchParams.delete(`setup`),n.searchParams.delete(`message`),n.searchParams.delete(`thread`),e.kind===`memory`?(n.searchParams.set(`view`,`memory`),e.memoryId&&n.searchParams.set(`memory`,e.memoryId)):e.kind===`workspaces`?n.searchParams.set(`view`,`workspaces`):e.kind===`scheduled-jobs`?n.searchParams.set(`view`,`scheduled-jobs`):e.kind===`settings`?(n.searchParams.set(`view`,`settings`),e.runtimeChannelId&&n.searchParams.set(`runtime`,e.runtimeChannelId),e.section&&n.searchParams.set(`section`,e.section)):e.kind===`agents`?(n.searchParams.set(`view`,`agents`),e.definitionId&&n.searchParams.set(`agent`,e.definitionId),e.creating&&n.searchParams.set(`new`,`1`),e.section&&n.searchParams.set(`section`,e.section),e.setupId&&n.searchParams.set(`setup`,e.setupId)):e.kind===`mentions`?n.searchParams.set(`view`,`mentions`):e.kind===`following`?n.searchParams.set(`view`,`following`):e.kind===`reviews`?n.searchParams.set(`view`,`reviews`):e.kind===`conversation`&&(e.messageId&&n.searchParams.set(`message`,e.messageId),e.threadRootId&&n.searchParams.set(`thread`,e.threadRootId)),window.history[t===`push`?`pushState`:`replaceState`](null,``,`${n.pathname}${n.search}${n.hash}`)}function L_(e){return Math.min(A_,Math.max(O_,e))}function R_(){try{let e=JSON.parse(sessionStorage.getItem(w_)??`null`);if(typeof e==`object`&&e&&`collapsed`in e&&`width`in e&&typeof e.collapsed==`boolean`&&typeof e.width==`number`&&Number.isFinite(e.width))return{collapsed:e.collapsed,width:L_(e.width)}}catch{}return{collapsed:!1,width:k_}}function z_(e){sessionStorage.setItem(w_,JSON.stringify(e))}var B_=`kai.workshop.context-layout.v4`,V_=240*D_,H_=V_,U_=560*D_;function W_(e){return Math.min(U_,Math.max(V_,e))}function G_(){try{let e=JSON.parse(sessionStorage.getItem(B_)??`null`);if(typeof e==`object`&&e&&`width`in e&&typeof e.width==`number`&&Number.isFinite(e.width))return W_(e.width)}catch{}return H_}function K_(e){sessionStorage.setItem(B_,JSON.stringify({width:e}))}function q_(e){try{let t=JSON.parse(e??`null`);if(typeof t==`object`&&t&&`token`in t&&`channelId`in t&&typeof t.token==`string`&&t.token.length>0&&typeof t.channelId==`string`&&b.test(t.channelId))return{channelId:t.channelId,token:t.token}}catch{}return null}function J_(e){try{let t=JSON.parse(e??`null`);if(typeof t==`object`&&t&&`token`in t&&typeof t.token==`string`&&t.token.length>0)return t.token}catch{}return null}function Y_(){try{let e=JSON.parse(sessionStorage.getItem(v_)??`null`);if(typeof e==`object`&&e&&`channelId`in e&&typeof e.channelId==`string`&&b.test(e.channelId))return e.channelId}catch{}return sessionStorage.removeItem(v_),null}function X_(){let e=J_(localStorage.getItem(__)),t=Y_(),n=q_(sessionStorage.getItem(y_));return!e&&n?(e=n.token,t??=n.channelId,localStorage.setItem(__,JSON.stringify({token:n.token}))):e&&n?.token===e&&(t??=n.channelId),localStorage.getItem(__)&&!e&&localStorage.removeItem(__),sessionStorage.removeItem(y_),e?{channelId:t,token:e}:null}function Z_(e){localStorage.setItem(__,JSON.stringify({token:e.token})),sessionStorage.setItem(v_,JSON.stringify({channelId:e.channelId})),sessionStorage.removeItem(y_)}function Q_(){sessionStorage.removeItem(v_),sessionStorage.removeItem(y_),sessionStorage.removeItem(b_),sessionStorage.removeItem(x_),sessionStorage.removeItem(S_),sessionStorage.removeItem(C_)}function $_(){localStorage.removeItem(__),Q_()}function ev(e){try{let t=JSON.parse(sessionStorage.getItem(b_)??`null`);if(typeof t==`object`&&t&&e in t&&Array.isArray(t[e]))return(t[e]??[]).filter(e=>typeof e==`string`&&e.startsWith(`run_`))}catch{}try{let t=JSON.parse(sessionStorage.getItem(x_)??`null`);if(typeof t==`object`&&t){let n=t[e];if(typeof n==`string`&&n.startsWith(`run_`))return[n]}}catch{}return[]}function tv(e,t){let n={};try{let e=JSON.parse(sessionStorage.getItem(b_)??`{}`);typeof e==`object`&&e&&!Array.isArray(e)&&(n=Object.fromEntries(Object.entries(e).flatMap(([e,t])=>{if(!Array.isArray(t))return[];let n=t.filter(e=>typeof e==`string`&&e.startsWith(`run_`));return n.length>0?[[e,n]]:[]})))}catch{}let r=[...new Set(t.filter(e=>e.startsWith(`run_`)))];r.length>0?n[e]=r:delete n[e],sessionStorage.setItem(b_,JSON.stringify(n)),sessionStorage.removeItem(x_)}function nv(e){try{let t=JSON.parse(sessionStorage.getItem(S_)??`{}`);if(typeof t==`object`&&t&&e in t){let n=t[e];return typeof n==`string`&&n.length<=5e4?n:``}}catch{}return``}function rv(e,t){let n={};try{let e=JSON.parse(sessionStorage.getItem(S_)??`{}`);typeof e==`object`&&e&&!Array.isArray(e)&&(n=Object.fromEntries(Object.entries(e).filter(e=>typeof e[1]==`string`&&e[1].length<=5e4)))}catch{}t?n[e]=t:delete n[e],sessionStorage.setItem(S_,JSON.stringify(n))}function iv(e){try{let t=JSON.parse(sessionStorage.getItem(C_)??`{}`),n=typeof t==`object`&&t?t[e]:null;if(typeof n==`object`&&n&&`follow`in n&&`scrollTop`in n&&typeof n.follow==`boolean`&&typeof n.scrollTop==`number`&&Number.isFinite(n.scrollTop)&&n.scrollTop>=0)return{follow:n.follow,scrollTop:n.scrollTop}}catch{}return null}function av(e,t){let n={};try{let e=JSON.parse(sessionStorage.getItem(C_)??`{}`);typeof e==`object`&&e&&!Array.isArray(e)&&(n=e)}catch{}n[e]=t,sessionStorage.setItem(C_,JSON.stringify(n))}function ov(e){return e?.status===`accepted`||e?.status===`started`}function sv(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=E_}function cv(e){let t=new Date(e);return Number.isNaN(t.valueOf())?``:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}function lv(e,t){let n=new Date(e.startedAt??e.acceptedAt).valueOf(),r=e.terminalAt?new Date(e.terminalAt).valueOf():t;if(!Number.isFinite(n)||!Number.isFinite(r))return`Duration unavailable`;let i=Math.max(0,Math.floor((r-n)/1e3));return i<60?`${i}s`:`${Math.floor(i/60)}m ${i%60}s`}function uv(e){return e.status===`accepted`?e.cancellationRequestedAt?`Stopping when the agent reaches a safe boundary.`:`Queued for the configured agent.`:e.status===`started`?e.cancellationRequestedAt?`Stopping when the agent reaches a safe boundary.`:`The agent is working on this request.`:e.status===`completed`?`The agent completed this request.`:e.status===`cancelled`?`This request was cancelled.`:e.terminalCode&&{authentication_expired:`Sign in to the configured backend again, then retry.`,authentication_required:`Sign in to the configured backend, then retry.`,backend_crashed:`The agent process stopped unexpectedly. Retry this request.`,execution_interrupted:`Kai was interrupted while the agent was working. Retry this request.`,model_unavailable:`The configured model is unavailable. Choose an available model, then retry.`,no_response:`The agent ended without a response. Retry this request.`,provider_unavailable:`The provider is temporarily unavailable. Try again later.`,quota_exhausted:`The configured account has no usage allowance remaining.`,transient:`The provider failed temporarily. Try this request again.`}[e.terminalCode]||`The agent could not complete this request. Retry it or ask the operator to inspect Kai.`}function dv({existingSession:e,notice:t,onForget:n,onOpen:r}){let[i,a]=(0,v.useState)(`Workshop browser`),[o,s]=(0,v.useState)(``),[c,l]=(0,v.useState)(t),[u,d]=(0,v.useState)(!1),f=async t=>{if(t.preventDefault(),l(null),!e&&(!i.trim()||!o.trim())){l(`Device name and enrollment token are required.`);return}d(!0);try{await r({deviceDisplayName:i.trim(),enrollmentToken:o.trim()})}catch(e){s(``),l(e instanceof Error?e.message:`Enrollment failed.`),d(!1)}};return(0,Q.jsxs)(`main`,{className:`enrollment-page`,children:[(0,Q.jsx)(`div`,{className:`enrollment-glow`,"aria-hidden":`true`}),(0,Q.jsxs)(`header`,{className:`enrollment-brand`,children:[(0,Q.jsx)(`span`,{className:`brand-mark`,children:`K`}),(0,Q.jsx)(`span`,{children:`Kai Workshop`}),(0,Q.jsx)(`span`,{className:`preview-badge`,children:`Workshop preview`})]}),(0,Q.jsxs)(`section`,{className:`enrollment-layout`,children:[(0,Q.jsxs)(`div`,{className:`enrollment-intro`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`A shared place for meaningful work`}),(0,Q.jsx)(`h1`,{children:`People and agents, working in the same room.`}),(0,Q.jsx)(`p`,{className:`lede`,children:`Open the canonical conversation already shared with Telegram. Your history and live updates come from Kai—not from this browser.`}),(0,Q.jsxs)(`ol`,{className:`threshold-steps`,"aria-label":`How Workshop connects`,children:[(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:`01`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`Enroll this device`}),(0,Q.jsx)(`p`,{children:`Use a short-lived grant issued by the Kai operator.`})]})]}),(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:`02`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`Join the channel`}),(0,Q.jsx)(`p`,{children:`Read one canonical history across every client.`})]})]}),(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:`03`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`Stay in step`}),(0,Q.jsx)(`p`,{children:`New human and agent messages arrive live.`})]})]})]})]}),(0,Q.jsxs)(`div`,{className:`enrollment-card`,children:[(0,Q.jsxs)(`div`,{className:`card-heading`,children:[(0,Q.jsx)(`span`,{className:`section-number`,children:`01`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Secure client enrollment`}),(0,Q.jsx)(`h2`,{children:`Open a Workshop channel`})]})]}),e?(0,Q.jsx)(`p`,{className:`session-hint`,children:`Enrollment is complete for this browser profile. Retry Workshop discovery, or forget the session and enroll again.`}):(0,Q.jsx)(`p`,{className:`card-copy`,children:`The session credential remains in this browser profile for this Kai origin and is never written to the URL.`}),(0,Q.jsxs)(`form`,{onSubmit:e=>void f(e),noValidate:!0,children:[!e&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`label`,{htmlFor:`device-name`,children:`Device name`}),(0,Q.jsx)(`input`,{id:`device-name`,name:`device-name`,value:i,onChange:e=>a(e.target.value),maxLength:100,autoComplete:`off`,required:!0}),(0,Q.jsx)(`label`,{htmlFor:`enrollment-token`,children:`Enrollment token`}),(0,Q.jsx)(`input`,{id:`enrollment-token`,name:`enrollment-token`,type:`password`,value:o,onChange:e=>s(e.target.value),maxLength:512,placeholder:`kai_ws_enroll_v1.…`,autoComplete:`off`,spellCheck:!1,required:!0})]}),(0,Q.jsxs)(`div`,{className:`form-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:u,children:u?`Opening…`:`Open Workshop`}),e&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:n,children:`Forget session`})]}),c&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:c})]})]})]}),(0,Q.jsxs)(`footer`,{className:`enrollment-footer`,children:[(0,Q.jsx)(`span`,{children:`Server-authoritative collaboration`}),(0,Q.jsx)(`span`,{children:`·`}),(0,Q.jsx)(`span`,{children:`Telegram and Workshop in one history`})]})]})}function fv({connection:e}){return(0,Q.jsxs)(`span`,{className:`connection-indicator ${e.tone}`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`connection-dot`,"aria-hidden":`true`}),e.label]})}var pv=[{label:`Thumbs up`,reaction:`thumbs_up`,symbol:`👍`},{label:`Thumbs down`,reaction:`thumbs_down`,symbol:`👎`},{label:`Heart`,reaction:`heart`,symbol:`❤️`},{label:`Laugh`,reaction:`laugh`,symbol:`😄`},{label:`Celebrate`,reaction:`celebrate`,symbol:`🎉`},{label:`Eyes`,reaction:`eyes`,symbol:`👀`},{label:`Done`,reaction:`check`,symbol:`✅`},{label:`Thinking`,reaction:`thinking`,symbol:`🤔`},{label:`Surprised`,reaction:`surprised`,symbol:`😮`},{label:`Sad`,reaction:`sad`,symbol:`😢`},{label:`Fire`,reaction:`fire`,symbol:`🔥`},{label:`Question`,reaction:`question`,symbol:`❓`}];function mv({hasUnreadReplies:e=!1,highlighted:t=!1,message:n,notification:r=!1,onDownloadArtifact:i,onLoadArtifact:a,onMessageVisible:o,onOpenThread:s,onLoadReactors:c,onSetReaction:l}){let[u,d]=(0,v.useState)(!1),[f,p]=(0,v.useState)(null),[m,h]=(0,v.useState)(null),[g,_]=(0,v.useState)(null),[y,b]=(0,v.useState)({}),[x,S]=(0,v.useState)(null),[C,w]=(0,v.useState)(null),T=(0,v.useRef)(null),E=n.authorKind===`agent`,D=n.authorDisplayName||`Unknown author`,O=n.reactions??[],k=O.map(e=>`${e.reaction}:${e.count}:${e.reactedByViewer}`).join(`|`);(0,v.useEffect)(()=>{_(null),b({}),S(null),w(null)},[n.messageId,k]),(0,v.useEffect)(()=>{let e=T.current;if(!e||!o||!(`IntersectionObserver`in window))return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&o(n.messageId)},{root:e.closest(`.timeline-wrap`),rootMargin:`0px`,threshold:0});return t.observe(e),()=>t.disconnect()},[n.messageId,o]);let A=async(e,t)=>{if(!(!l||f!==null)){p(e),h(null);try{await l(n.messageId,e,t),d(!1)}catch(e){h(e instanceof Error?e.message:`Could not update this reaction.`)}finally{p(null)}}},j=e=>{_(e),!(!c||y[e]||x===e)&&(S(e),w(null),c(n.messageId,e).then(t=>{b(n=>({...n,[e]:t}))}).catch(()=>w(e)).finally(()=>S(t=>t===e?null:t)))};return r?(0,Q.jsxs)(`li`,{ref:T,className:`notification-row ${t?`focused-message`:``}`,"data-message-id":n.messageId,children:[(0,Q.jsx)(`span`,{className:`notification-source`,"aria-hidden":`true`,children:`GH`}),(0,Q.jsxs)(`article`,{children:[(0,Q.jsxs)(`header`,{className:`message-meta`,children:[(0,Q.jsx)(`strong`,{children:`GitHub`}),(0,Q.jsx)(`time`,{dateTime:n.createdAt,children:cv(n.createdAt)})]}),(0,Q.jsx)(Nm,{body:n.body,mentions:n.mentions}),n.artifacts.map(e=>(0,Q.jsx)(gv,{artifact:e,onDownload:i,onLoad:a},e.artifactId))]})]}):(0,Q.jsxs)(`li`,{ref:T,className:`message-row ${E?`agent`:`human`} ${t?`focused-message`:``}`,"data-message-id":n.messageId,children:[E?(0,Q.jsx)(`span`,{className:`message-avatar`,"aria-hidden":`true`,children:D.slice(0,1).toUpperCase()}):(0,Q.jsx)(Kh,{avatar:n.authorAvatar??N_,className:`message-avatar human`,displayName:D,principalId:n.authorPrincipalId}),(0,Q.jsxs)(`article`,{children:[(s||l)&&(0,Q.jsxs)(`div`,{className:`message-actions`,role:`group`,"aria-label":`Actions for message from ${D}`,children:[l&&(0,Q.jsxs)(`div`,{className:`reaction-picker-anchor`,children:[(0,Q.jsx)(`button`,{className:`message-action-button`,type:`button`,"aria-label":`Add reaction`,"aria-expanded":u,title:`Add reaction`,onClick:()=>{h(null),d(e=>!e)},children:(0,Q.jsx)(Vv,{})}),u&&(0,Q.jsx)(`div`,{className:`reaction-picker`,role:`menu`,"aria-label":`Choose a reaction`,onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),d(!1))},children:pv.map(e=>{let t=O.some(t=>t.reaction===e.reaction&&t.reactedByViewer);return(0,Q.jsx)(`button`,{type:`button`,role:`menuitemcheckbox`,"aria-checked":t,"aria-label":`${t?`Remove`:`Add`} ${e.label} reaction`,disabled:f!==null,onClick:()=>void A(e.reaction,!t),children:e.symbol},e.reaction)})})]}),s&&(0,Q.jsx)(`button`,{className:`message-action-button`,type:`button`,"aria-label":`Reply to message`,title:`Reply`,onClick:()=>s(n.messageId),children:(0,Q.jsx)(Rv,{})})]}),(0,Q.jsxs)(`header`,{className:`message-meta`,children:[(0,Q.jsxs)(`span`,{className:`message-author`,children:[(0,Q.jsx)(`strong`,{children:D}),n.standingContribution&&(0,Q.jsx)(`span`,{className:`standing-contribution-mark`,"aria-label":`Agent contribution from standing participation`,title:`Agent contribution from standing participation`,children:(0,Q.jsx)(ty,{})})]}),(0,Q.jsx)(`time`,{dateTime:n.createdAt,children:cv(n.createdAt)})]}),(0,Q.jsx)(Nm,{body:n.body,mentions:n.mentions}),n.artifacts.map(e=>(0,Q.jsx)(gv,{artifact:e,onDownload:i,onLoad:a},e.artifactId)),(O.length>0||s&&n.replyCount>0)&&(0,Q.jsxs)(`div`,{className:`message-engagement`,role:`group`,"aria-label":`Message engagement`,children:[O.length>0&&(0,Q.jsx)(`div`,{className:`message-reactions`,role:`group`,"aria-label":`Message reactions`,children:O.map(e=>{let t=pv.find(t=>t.reaction===e.reaction);if(!t)return null;let n=g===e.reaction,r=y[e.reaction];return(0,Q.jsxs)(`span`,{className:`reaction-chip-anchor`,onMouseEnter:()=>j(e.reaction),onMouseLeave:()=>_(null),children:[(0,Q.jsxs)(`button`,{className:e.reactedByViewer?`active`:``,type:`button`,"aria-label":`${t.label}: ${e.count}. ${e.reactedByViewer?`Remove your reaction`:`Add your reaction`}`,"aria-pressed":e.reactedByViewer,disabled:!l||f!==null,onClick:()=>void A(e.reaction,!e.reactedByViewer),onFocus:()=>j(e.reaction),onBlur:()=>_(null),children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:t.symbol}),(0,Q.jsx)(`span`,{children:e.count})]}),n&&c&&(0,Q.jsxs)(`div`,{className:`reaction-reactors`,role:`tooltip`,children:[(0,Q.jsxs)(`strong`,{children:[t.symbol,` `,t.label]}),x===e.reaction&&(0,Q.jsx)(`span`,{children:`Loading…`}),C===e.reaction&&(0,Q.jsx)(`span`,{children:`Participants unavailable`}),r&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`ul`,{children:r.reactors.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:e.displayName}),(0,Q.jsxs)(`small`,{children:[e.kind===`agent`?`Agent`:`Human`,e.handle?` · @${e.handle}`:``]})]},e.principalId))}),r.truncated&&(0,Q.jsxs)(`span`,{children:[`Showing `,r.reactors.length,` of `,r.total]})]})]})]},e.reaction)})}),s&&n.replyCount>0&&(0,Q.jsxs)(`button`,{className:`thread-summary`,type:`button`,"aria-label":`Open thread with ${n.replyCount} ${n.replyCount===1?`reply`:`replies`}${e?`, including unread replies`:``}`,title:`Open thread`,onClick:()=>s(n.messageId),children:[n.replyParticipants.length>0&&(0,Q.jsxs)(`span`,{className:`thread-participants`,"aria-hidden":`true`,children:[n.replyParticipants.map(e=>e.kind===`human`?(0,Q.jsx)(Kh,{avatar:e.avatar??N_,className:`thread-participant-avatar human`,displayName:e.displayName,principalId:e.principalId},e.principalId):(0,Q.jsx)(`span`,{className:`thread-participant-avatar agent`,title:e.displayName,children:e.displayName.trim().slice(0,1).toUpperCase()||`?`},e.principalId)),n.replyParticipantCount>n.replyParticipants.length&&(0,Q.jsxs)(`span`,{className:`thread-participant-overflow`,children:[`+`,n.replyParticipantCount-n.replyParticipants.length]})]}),(0,Q.jsxs)(`span`,{className:`thread-summary-count`,children:[n.replyCount,` `,n.replyCount===1?`reply`:`replies`]}),(0,Q.jsx)(`span`,{className:`thread-summary-label`,children:`View thread`}),e&&(0,Q.jsx)(`strong`,{children:`New replies`}),(0,Q.jsx)(zv,{})]})]}),m&&(0,Q.jsx)(`p`,{className:`reaction-error`,role:`alert`,children:m})]})]})}var hv=new Set([`image/gif`,`image/jpeg`,`image/png`,`image/webp`]);function gv({artifact:e,onDownload:t,onLoad:n}){let[r,i]=(0,v.useState)(null),[a,o]=(0,v.useState)(null),s=hv.has(e.mediaType)||e.mediaType.startsWith(`audio/`);return(0,v.useEffect)(()=>{if(!s)return;let t=!1,r=null;return n(e.artifactId).then(e=>{t||(r=URL.createObjectURL(e),i(r))}).catch(()=>{t||o(`Attachment preview unavailable.`)}),()=>{t=!0,r&&URL.revokeObjectURL(r)}},[e.artifactId,s,n]),(0,Q.jsxs)(`section`,{className:`message-artifact`,children:[r&&hv.has(e.mediaType)&&(0,Q.jsx)(`img`,{src:r,alt:e.originalFilename??`Attached image`}),r&&e.mediaType.startsWith(`audio/`)&&(0,Q.jsx)(`audio`,{src:r,controls:!0,preload:`metadata`}),(0,Q.jsxs)(`div`,{className:`artifact-meta`,children:[(0,Q.jsx)(`span`,{children:e.originalFilename??`Attachment`}),(0,Q.jsxs)(`small`,{children:[Math.max(1,Math.ceil(e.byteSize/1024)),` KB`]}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>{o(null);try{t(e.artifactId)}catch{o(`Could not download this attachment.`)}},children:`Download`})]}),a&&(0,Q.jsx)(`p`,{className:`artifact-error`,role:`alert`,children:a})]})}function _v(){if(typeof globalThis.crypto?.getRandomValues!=`function`)throw Error(`This browser cannot create secure command identities.`);let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),`browser-${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function vv(e){if(e.kind===`direct`){let t=e.participants.map(e=>e.displayName.trim()).filter(Boolean);if(t.length>0)return t.join(`, `);if(e.agents.length===1&&e.agents[0].name.trim())return e.agents[0].name.trim()}return e.name?.trim()||(e.kind===`notification`?`Notifications`:e.kind===`group`?`Group`:`Conversation`)}function yv(e){return e.kind===`notification`?`!`:e.kind===`direct`?`@`:`#`}function bv(e){let t=xv(e);return t<=0?``:`, ${`${t}${e?.unreadCountCapped||e?.unreadReplyCountCapped?` or more`:``}`} unread ${t===1&&!e?.unreadCountCapped&&!e?.unreadReplyCountCapped?`message`:`messages`}`}function xv(e){return Math.min((e?.unreadCount??0)+(e?.unreadReplyCount??0),1e3)}function Sv(e){return typeof e.archivedAt==`string`}function Cv(e){return e.kind===`direct`&&typeof e.directMessageArchivedAt==`string`}function wv(e){return e.kind===`direct`&&e.agents.length===0&&e.participants.length===1&&e.participants[0].kind===`human`}function Tv(e){return e===`admin`?`Administrator`:e===`member`?`Member`:e.charAt(0).toUpperCase()+e.slice(1)}function Ev(e,t){let n=e.slice(0,t),r=/(?:^|\s)@([^@\n]*)$/.exec(n);if(!r)return null;let i=r[1];return{end:t,query:i,start:t-i.length-1}}function Dv({agents:e,initialAgentIds:t,originChannelId:n,originName:r,onCancel:i,onCreate:a}){let[o,s]=(0,v.useState)(``),[c,l]=(0,v.useState)(()=>t.length>0?t:e[0]?[e[0].agentId]:[]),[u,d]=(0,v.useState)(!1),[f,p]=(0,v.useState)(null),m=async e=>{e.preventDefault();let t=o.trim();if(!t||c.length===0){p(`A channel name and at least one agent are required.`);return}d(!0),p(null);try{await a({agentIds:c,name:t,originChannelId:n})}catch(e){p(e instanceof Error?e.message:`Could not create this channel.`),d(!1)}};return(0,Q.jsx)(`div`,{className:`modal-backdrop`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`create-channel-title`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`New conversation space`}),(0,Q.jsx)(`h2`,{id:`create-channel-title`,children:`Create channel`}),r&&(0,Q.jsxs)(`p`,{children:[`Start from `,(0,Q.jsx)(`strong`,{children:r}),`.`]}),(0,Q.jsxs)(`form`,{onSubmit:e=>void m(e),children:[(0,Q.jsx)(`label`,{htmlFor:`channel-name`,children:`Channel name`}),(0,Q.jsx)(`input`,{id:`channel-name`,autoFocus:!0,maxLength:200,value:o,onChange:e=>s(e.target.value)}),(0,Q.jsxs)(`fieldset`,{children:[(0,Q.jsx)(`legend`,{children:`Agents`}),e.map(e=>(0,Q.jsxs)(`label`,{className:`channel-agent-choice`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:c.includes(e.agentId),onChange:t=>l(n=>t.target.checked?[...n,e.agentId]:n.filter(t=>t!==e.agentId))}),(0,Q.jsx)(`span`,{children:e.name})]},e.agentId))]}),f&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:f}),(0,Q.jsxs)(`div`,{className:`form-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:u,children:u?`Creating…`:`Create channel`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:i,disabled:u,children:`Cancel`})]})]})]})})}function Ov({onCancel:e,onLoad:t,onOpen:n}){let[r,i]=(0,v.useState)(null),[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(null);(0,v.useEffect)(()=>{let e=!1;return t().then(t=>{e||i(t)}).catch(t=>{e||c(t instanceof Error?t.message:`Could not load Workshop people.`)}),()=>{e=!0}},[t]);let l=async e=>{if(!a){o(e),c(null);try{await n(e)}catch(e){c(e instanceof Error?e.message:`Could not start this conversation.`),o(null)}}};return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog human-conversation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`human-conversation-title`,children:[(0,Q.jsxs)(`header`,{className:`channel-archive-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Direct messages`}),(0,Q.jsx)(`h2`,{id:`human-conversation-title`,children:`Start a conversation`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close people picker`,title:`Close`,disabled:a!==null,onClick:e,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),r===null&&!s&&(0,Q.jsx)(`p`,{className:`human-conversation-state`,role:`status`,children:`Loading people…`}),r?.length===0&&(0,Q.jsx)(`p`,{className:`human-conversation-state`,children:`No other people are available in this Workshop.`}),r&&r.length>0&&(0,Q.jsx)(`ul`,{className:`human-conversation-list`,children:r.map(e=>(0,Q.jsx)(`li`,{children:(0,Q.jsxs)(`button`,{type:`button`,disabled:a!==null,"aria-label":`${e.displayName}, @${e.handle}${e.conversationChannelId?`, conversation started`:``}`,onClick:()=>void l(e.principalId),children:[(0,Q.jsx)(Kh,{avatar:e.avatar??N_,className:`human-picker-avatar`,displayName:e.displayName,principalId:e.principalId}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.displayName}),(0,Q.jsxs)(`small`,{children:[`@`,e.handle]})]}),(0,Q.jsx)(`small`,{children:a===e.principalId?`Opening…`:e.conversationChannelId?`Open`:`Message`})]})},e.principalId))}),s&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:s})]})})}function kv({attachedAgents:e,enablements:t,onCancel:n,onSave:r}){let i=(0,v.useMemo)(()=>e.map(e=>e.agentId),[e]),[a,o]=(0,v.useState)(i),[s,c]=(0,v.useState)(!1),[l,u]=(0,v.useState)(null),d=(0,v.useMemo)(()=>{let n=new Map(t.filter(e=>e.lifecycleState===`enabled`).map(e=>[e.agentId,e]));for(let t of e)n.has(t.agentId)||n.set(t.agentId,{agentId:t.agentId,definitionId:``,directChannelId:null,displayName:t.name,eligibleRuntimes:[],enablementId:null,handle:t.name,lifecycleState:`disabled`,runtimeProfileId:t.runtimeProfileId,stateVersion:null,canManage:!1,conversationStarted:!1,ownerPrincipalId:null,ownerRuntimeProfileId:t.runtimeProfileId});return Array.from(n.values()).sort((e,t)=>e.displayName.localeCompare(t.displayName))},[e,t]),f=async e=>{e.preventDefault(),c(!0),u(null);try{await r(a)}catch(e){u(e instanceof Error?e.message:`Could not update channel agents.`),c(!1)}};return(0,Q.jsx)(`div`,{className:`modal-backdrop`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`manage-channel-agents-title`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Channel management`}),(0,Q.jsx)(`h2`,{id:`manage-channel-agents-title`,children:`Agents`}),(0,Q.jsx)(`p`,{children:`Attached agents use the runtime explicitly sponsored by your enabled direct agent. Shared channels never inject that sponsor’s personal preferences or memory. Detaching stops new mentions and wakes while preserving messages, completed runs, and any run already accepted.`}),(0,Q.jsxs)(`form`,{onSubmit:e=>void f(e),children:[(0,Q.jsxs)(`fieldset`,{children:[(0,Q.jsx)(`legend`,{children:`Attached agents`}),d.map(t=>{let n=e.find(e=>e.agentId===t.agentId),r=t.lifecycleState===`enabled`;return(0,Q.jsxs)(`label`,{className:`channel-agent-choice`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:a.includes(t.agentId),disabled:!r&&!n,onChange:e=>o(n=>e.target.checked?[...n,t.agentId]:n.filter(e=>e!==t.agentId))}),(0,Q.jsxs)(`span`,{children:[t.displayName,(0,Q.jsx)(`small`,{children:n?`${n.available?`Available`:`Unavailable`} · sponsored by ${n.sponsorDisplayName??`unknown`}`:`Available to attach`})]})]},t.agentId)})]}),l&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:l}),(0,Q.jsxs)(`div`,{className:`form-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:s,children:s?`Saving…`:`Save`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:n,disabled:s,children:`Cancel`})]})]})]})})}function Av({membership:e,onCancel:t,onChange:n}){let r=(0,v.useMemo)(()=>e.members.map(e=>e.principalId),[e.members]),[i,a]=(0,v.useState)(r),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(null),u=(0,v.useMemo)(()=>[...e.members,...e.eligibleHumans].sort((e,t)=>e.role===`owner`&&t.role!==`owner`?-1:t.role===`owner`&&e.role!==`owner`?1:e.displayName.localeCompare(t.displayName)),[e.eligibleHumans,e.members]),d=async a=>{a.preventDefault(),s(!0),l(null);try{let a=e.stateVersion,o=new Set(r),s=new Set(i);for(let t of e.members)t.role!==`owner`&&!s.has(t.principalId)&&(a=await n(t.principalId,`remove`,a,_v()));for(let t of e.eligibleHumans)!o.has(t.principalId)&&s.has(t.principalId)&&(a=await n(t.principalId,`add`,a,_v()));t()}catch(e){l(e instanceof Error?e.message:`Could not update channel members.`),s(!1)}};return(0,Q.jsx)(`div`,{className:`modal-backdrop`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`manage-channel-members-title`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Channel management`}),(0,Q.jsx)(`h2`,{id:`manage-channel-members-title`,children:`People`}),(0,Q.jsx)(`p`,{children:`Members can read this private channel and mention its people and agents. The channel owner is permanent; ownership transfer is not available.`}),(0,Q.jsxs)(`form`,{onSubmit:e=>void d(e),children:[(0,Q.jsxs)(`fieldset`,{children:[(0,Q.jsx)(`legend`,{children:`Human members`}),u.map(e=>(0,Q.jsxs)(`label`,{className:`channel-agent-choice`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:i.includes(e.principalId),disabled:o||e.role===`owner`,onChange:t=>a(n=>t.target.checked?[...n,e.principalId]:n.filter(t=>t!==e.principalId))}),(0,Q.jsx)(Kh,{avatar:e.avatar??N_,className:`human-picker-avatar`,displayName:e.displayName,principalId:e.principalId}),(0,Q.jsxs)(`span`,{children:[e.displayName,(0,Q.jsxs)(`small`,{children:[`@`,e.handle,e.role===`owner`?` · owner`:``]})]})]},e.principalId))]}),c&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:c}),(0,Q.jsxs)(`div`,{className:`form-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:o,children:o?`Saving…`:`Save`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:t,disabled:o,children:`Cancel`})]})]})]})})}function jv({busy:e,channelName:t,error:n,loading:r,onClose:i,onStandingChange:a,participation:o}){return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog channel-settings-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`channel-settings-title`,children:[(0,Q.jsxs)(`header`,{className:`channel-archive-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`p`,{className:`overline`,children:[`# `,t]}),(0,Q.jsx)(`h2`,{id:`channel-settings-title`,children:`Channel settings`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close channel settings`,title:`Close channel settings`,disabled:e,onClick:i,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsxs)(`section`,{className:`channel-settings-section`,"aria-labelledby":`channel-participation-title`,children:[(0,Q.jsx)(`h3`,{id:`channel-participation-title`,children:`Participation`}),r&&!o&&(0,Q.jsx)(`p`,{className:`channel-settings-state`,role:`status`,children:`Loading participation policy…`}),o&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`standing-policy-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:o.policy.enabled,disabled:!o.policy.canManage||e,onChange:e=>void a(e.target.checked)}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Standing participation`}),(0,Q.jsx)(`small`,{children:o.policy.enabled?o.policy.hostEnabled?`On for this channel`:`Requested here · unavailable on this host`:`Off for this channel`})]})]}),!o.policy.canManage&&(0,Q.jsx)(`p`,{children:`Only a channel owner can change this policy.`}),(0,Q.jsxs)(`details`,{className:`standing-limits`,children:[(0,Q.jsx)(`summary`,{children:`Host limits`}),(0,Q.jsxs)(`dl`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Agents`}),(0,Q.jsxs)(`dd`,{children:[o.policy.maxAgentsPerChannel,`/channel`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Observe batch`}),(0,Q.jsxs)(`dd`,{children:[o.policy.maxMessagesPerObserveRun,` messages`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Pending`}),(0,Q.jsxs)(`dd`,{children:[o.policy.maxPendingMessagesPerScope,`/scope`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Observation`}),(0,Q.jsxs)(`dd`,{children:[o.policy.maxObserveRunsPerHour,`/hour`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Contributions`}),(0,Q.jsxs)(`dd`,{children:[o.policy.maxUnsolicitedMessagesPerHour,`/hour`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Cooldown`}),(0,Q.jsxs)(`dd`,{children:[o.policy.minimumUnsolicitedIntervalSeconds,`s`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Quiet expiry`}),(0,Q.jsxs)(`dd`,{children:[o.policy.quietExpirySeconds,`s`]})]})]})]})]}),n&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:n})]})]})})}function Mv({channels:e,busyChannelId:t,onClose:n,onRestore:r,onView:i}){return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog channel-archive-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`channel-archive-title`,children:[(0,Q.jsxs)(`header`,{className:`channel-archive-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Channels`}),(0,Q.jsx)(`h2`,{id:`channel-archive-title`,children:`Archive`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close channel archive`,title:`Close channel archive`,onClick:n,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),e.length===0?(0,Q.jsx)(`p`,{className:`channel-archive-empty`,children:`No archived channels.`}):(0,Q.jsx)(`ul`,{className:`channel-archive-list`,children:e.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsxs)(`strong`,{children:[`# `,vv(e)]}),(0,Q.jsxs)(`small`,{children:[`Archived `,e.archivedAt?cv(e.archivedAt):``]})]}),(0,Q.jsxs)(`span`,{className:`channel-archive-actions`,children:[(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`View archived channel ${vv(e)}`,title:`View archived channel`,onClick:()=>i(e.channelId),children:(0,Q.jsx)(ey,{})}),e.role===`owner`&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Restore channel ${vv(e)}`,title:`Restore channel`,disabled:t!==null,onClick:()=>void r(e.channelId),children:(0,Q.jsx)(Kv,{})})]})]},e.channelId))})]})})}function Nv({channels:e,busyChannelId:t,onClose:n,onRestore:r,onView:i}){return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog channel-archive-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`direct-message-archive-title`,children:[(0,Q.jsxs)(`header`,{className:`channel-archive-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Direct messages`}),(0,Q.jsx)(`h2`,{id:`direct-message-archive-title`,children:`Archive`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close direct-message archive`,title:`Close direct-message archive`,onClick:n,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),e.length===0?(0,Q.jsx)(`p`,{className:`channel-archive-empty`,children:`No archived direct messages.`}):(0,Q.jsx)(`ul`,{className:`channel-archive-list`,children:e.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsxs)(`strong`,{children:[`@ `,vv(e)]}),(0,Q.jsxs)(`small`,{children:[`Archived `,e.directMessageArchivedAt?cv(e.directMessageArchivedAt):``]})]}),(0,Q.jsxs)(`span`,{className:`channel-archive-actions`,children:[(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`View archived direct message ${vv(e)}`,title:`View archived direct message`,onClick:()=>i(e.channelId),children:(0,Q.jsx)(ey,{})}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Restore direct message ${vv(e)}`,title:`Restore direct message`,disabled:t!==null,onClick:()=>void r(e.channelId),children:(0,Q.jsx)(Kv,{})})]})]},e.channelId))})]})})}function Pv({agents:e,onClose:t,onOpenConversation:n,onContinue:r,onView:i}){let a=e.filter(e=>e.state!==`Archived`),o=e.filter(e=>e.state===`Archived`),s=e=>(0,Q.jsx)(`ul`,{className:`channel-archive-list`,children:e.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.displayName}),(0,Q.jsxs)(`small`,{children:[`@`,e.handle,` · `,e.state]})]}),(0,Q.jsxs)(`span`,{className:`channel-archive-actions`,children:[e.state!==`Archived`&&(0,Q.jsx)(`button`,{className:`primary-button`,type:`button`,onClick:()=>r(e.definitionId,e.setupId),children:`Continue setup`}),e.conversationChannelId&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Open archived conversation with ${e.displayName}`,title:`Open archived conversation`,onClick:()=>n(e.conversationChannelId),children:(0,Q.jsx)(Rv,{})}),e.definitionId&&e.state===`Archived`&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`View archived agent ${e.displayName}`,title:`View archived agent`,onClick:()=>i(e.definitionId),children:(0,Q.jsx)(ey,{})})]})]},e.entryId))});return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog channel-archive-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`inactive-agents-title`,children:[(0,Q.jsxs)(`header`,{className:`channel-archive-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Agents`}),(0,Q.jsx)(`h2`,{id:`inactive-agents-title`,children:`Drafts and archive`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close drafts and archive`,title:`Close drafts and archive`,onClick:t,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),e.length===0?(0,Q.jsx)(`p`,{className:`channel-archive-empty`,children:`No draft or archived agents.`}):(0,Q.jsxs)(`div`,{className:`inactive-agent-sections`,children:[a.length>0&&(0,Q.jsxs)(`section`,{children:[(0,Q.jsx)(`h3`,{children:`Drafts`}),s(a)]}),o.length>0&&(0,Q.jsxs)(`section`,{children:[(0,Q.jsx)(`h3`,{children:`Archived agents`}),s(o)]})]})]})})}function Fv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`})})}function Iv(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`m22 2-7 20-4-9-9-4Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`}),(0,Q.jsx)(`path`,{d:`M22 2 11 13`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`})]})}function Lv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`currentColor`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`rect`,{x:`6`,y:`6`,width:`12`,height:`12`,rx:`1`})})}function Rv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M20 15a3 3 0 0 1-3 3H9l-5 3V7a3 3 0 0 1 3-3h10a3 3 0 0 1 3 3z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`})})}function zv(){return(0,Q.jsx)(`svg`,{className:`thread-summary-chevron`,"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`m9 18 6-6-6-6`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`})})}function Bv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`m7 9.5 5 5 5-5`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.75`})})}function Vv(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`circle`,{cx:`11`,cy:`11`,r:`8`,stroke:`currentColor`,strokeWidth:`2`}),(0,Q.jsx)(`path`,{d:`M8 9h.01M14 9h.01M7.5 13.5c1 1.5 2.2 2.2 3.5 2.2s2.5-.7 3.5-2.2M19 15v6M16 18h6`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`})]})}function Hv({followed:e}){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:e?`currentColor`:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`}),(0,Q.jsx)(`path`,{d:`M13.73 21a2 2 0 0 1-3.46 0`,fill:`none`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`})]})}function Uv(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`circle`,{cx:`12`,cy:`12`,r:`3`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-2.83 2.83-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 .6 1.7 1.7 0 0 0-.4 1.1V21H9.6v-.09A1.7 1.7 0 0 0 8.5 19.4a1.7 1.7 0 0 0-1.88.34l-.06.06-2.83-2.83.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-.6-1 1.7 1.7 0 0 0-1.1-.4H3V9.6h.09A1.7 1.7 0 0 0 4.6 8.5a1.7 1.7 0 0 0-.34-1.88l-.06-.06 2.83-2.83.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-.6 1.7 1.7 0 0 0 .4-1.1V3h4v.09A1.7 1.7 0 0 0 15.5 4.6a1.7 1.7 0 0 0 1.88-.34l.06-.06 2.83 2.83-.06.06A1.7 1.7 0 0 0 19.4 9c.14.38.36.72.66 1 .3.28.68.42 1.1.4H21v4h-.09A1.7 1.7 0 0 0 19.4 15Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`})]})}function Wv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M12 5v14M5 12h14`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`})})}function Gv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M4 7h16v13H4zM3 4h18v3H3zM9 11h6`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.8`})})}function Kv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M4 12a8 8 0 1 0 2.34-5.66L4 8.68M4 4v4.68h4.68`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.8`})})}function qv(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M20 11a8 8 0 1 0-2.34 5.66`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M20 5v6h-6`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.8`})]})}function Jv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M3.5 6.5h6l2 2h9v10h-17z`,stroke:`currentColor`,strokeLinejoin:`round`,strokeWidth:`1.8`})})}function Yv(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`circle`,{cx:`12`,cy:`12`,r:`8.5`,stroke:`currentColor`,strokeWidth:`1.7`}),(0,Q.jsx)(`path`,{d:`M12 7.5v5l3.2 2`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.7`})]})}function Xv(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`circle`,{cx:`6`,cy:`5`,r:`2`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`19`,r:`2`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`circle`,{cx:`18`,cy:`5`,r:`2`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M6 7v10M18 7v3a5 5 0 0 1-5 5H9`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`})]})}function Zv({action:e,children:t,className:n=``,revealKey:r=0,revealReady:i=!0,revealTargetId:a=null,title:o}){let[s,c]=(0,v.useState)(()=>Qv()[o]??!1),l=(0,v.useRef)(null);return(0,v.useEffect)(()=>{c(Qv()[o]??!1)},[o]),(0,v.useEffect)(()=>{if(r===0)return;if(!s){c(!0),$v(o,!0);return}if(!i)return;let e=a?l.current?.querySelector(`#${a}`):l.current;e?.focus({preventScroll:!0});let t=window.requestAnimationFrame(()=>{e?.scrollIntoView?.({behavior:`smooth`,block:`nearest`})});return()=>window.cancelAnimationFrame(t)},[s,r,i,a,o]),(0,Q.jsxs)(`details`,{className:`context-section${n?` ${n}`:``}`,open:s,ref:l,onToggle:e=>{let t=e.currentTarget.open;c(t),$v(o,t)},children:[(0,Q.jsxs)(`summary`,{className:`context-section-toggle`,children:[(0,Q.jsx)(`h3`,{className:`context-section-title`,children:o}),e&&(0,Q.jsx)(`span`,{className:`context-section-header-action`,onClick:e=>e.stopPropagation(),children:e})]}),(0,Q.jsx)(`div`,{className:`context-section-body`,children:t})]})}function Qv(){try{let e=JSON.parse(localStorage.getItem(T_)??`null`);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`boolean`))return e}catch{}return{}}function $v(e,t){try{localStorage.setItem(T_,JSON.stringify({...Qv(),[e]:t}))}catch{}}function ey(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z`,stroke:`currentColor`,strokeLinejoin:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`circle`,{cx:`12`,cy:`12`,r:`2.5`,stroke:`currentColor`,strokeWidth:`1.8`})]})}function ty(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z`,stroke:`currentColor`,strokeLinejoin:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`circle`,{cx:`12`,cy:`12`,r:`2.5`,stroke:`currentColor`,strokeWidth:`1.8`})]})}function ny(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M3 3l18 18M9.6 6.4A10.8 10.8 0 0 1 12 6c6 0 9.5 6 9.5 6a17 17 0 0 1-2.1 2.8M6.2 7.7C3.8 9.5 2.5 12 2.5 12s3.5 6 9.5 6c1 0 1.9-.2 2.7-.4M9.9 9.9a3 3 0 0 0 4.2 4.2`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.8`})})}function ry({activeStandingAgentIds:e,channelName:t,liveMessages:n,focusedMessage:r,onClose:i,onDownloadArtifact:a,onLoadArtifact:o,onLoadThread:s,onLoadThreadUnread:c,onLoadReactors:l,onAdvanceThreadRead:u,onSetThreadFollowed:d,onSuppressStanding:f,onMessageVisible:p,onSetReaction:m,onSubmitCommand:h,reactionUpdates:g,principalEvents:_,readOnly:y,rootMessage:b,runActive:x}){let[S,C]=(0,v.useState)(null),[w,T]=(0,v.useState)(null),[E,D]=(0,v.useState)(!1),[O,k]=(0,v.useState)(``),[A,j]=(0,v.useState)(!1),[M,N]=(0,v.useState)(null),[P,F]=(0,v.useState)(null),[I,L]=(0,v.useState)(null),[R,ee]=(0,v.useState)(!1),[z,B]=(0,v.useState)(!1),V=(0,v.useRef)(null),H=(0,v.useRef)(P),te=(0,v.useRef)(null),U=(0,v.useRef)(!1);H.current=P,(0,v.useEffect)(()=>{let e=new AbortController;return C(null),F(null),L(null),T(null),Promise.all([s(b.messageId,null,e.signal),c(b.messageId,e.signal)]).then(([e,t])=>{C(e),F(t),L(t.firstUnreadMessageId)},t=>{e.signal.aborted||T(t instanceof Error?t.message:`Could not load this thread.`)}),()=>e.abort()},[s,c,b.messageId]),(0,v.useEffect)(()=>_.subscribe(e=>{if(e.kind===`synchronize`){c(b.messageId).then(F,()=>void 0);return}for(let t of e.batch.changes)for(let e of t.threadChanges)e.state.threadRootId===b.messageId&&F(e.state)}),[c,_,b.messageId]),(0,v.useLayoutEffect)(()=>{let e=V.current;if(!e)return;let t=e.offsetHeight-e.clientHeight;e.style.height=`auto`,e.style.height=`${e.scrollHeight+t}px`},[O,b.messageId]);let ne=(0,v.useMemo)(()=>{let e=new Map;for(let t of S?.messages??[])e.set(t.messageId,t);for(let t of n)t.threadRootId===b.messageId&&e.set(t.messageId,t);return r?.threadRootId===b.messageId&&e.set(r.messageId,r),Array.from(e.values()).sort((e,t)=>e.eventPosition-t.eventPosition)},[r,n,b.messageId,S?.messages]);(0,v.useEffect)(()=>{if(!r)return;let e=window.requestAnimationFrame(()=>{document.querySelector(`[data-message-id="${r.messageId}"]`)?.scrollIntoView?.({behavior:`smooth`,block:`center`})});return()=>window.cancelAnimationFrame(e)},[r,ne.length]);let re=async()=>{if(!(!S?.nextCursor||E)){D(!0),T(null);try{let e=await s(b.messageId,S.nextCursor);C(t=>t&&{...t,messages:[...t.messages,...e.messages],nextCursor:e.nextCursor})}catch(e){T(e instanceof Error?e.message:`Could not load more replies.`)}finally{D(!1)}}},W=async e=>{e.preventDefault();let t=O.trim();if(!(!t||A||x)){j(!0),T(null);try{let e=M??_v();N(e),await h(e,t,null,b.messageId),k(``),N(null)}catch(e){T(e instanceof Error?e.message:`Kai could not send this reply.`)}finally{j(!1)}}},ie=async()=>{let e=H.current;if(!(!e||R)){ee(!0),T(null);try{let t=await d(b.messageId,!e.followed,e.stateVersion,_v());F(t.state),t.state.followed&&L(t.state.firstUnreadMessageId)}catch(e){T(e instanceof Error?e.message:`Could not update thread follow state.`);try{F(await c(b.messageId))}catch{}}finally{ee(!1)}}},ae=(0,v.useCallback)(e=>{if(p(e),document.visibilityState!==`visible`)return;let t=ne.find(t=>t.messageId===e),n=H.current;!t||!n?.followed||t.eventPosition<=n.readThroughEventPosition||((!te.current||te.current.eventPosition{try{for(;te.current;){let e=te.current;te.current=null;let t=H.current;if(!(!t?.followed||e.eventPosition<=t.readThroughEventPosition))try{let n=await u(b.messageId,e.messageId,t.stateVersion,_v());H.current=n.state,F(n.state)}catch{t=await c(b.messageId),H.current=t,F(t),t.followed&&e.eventPosition>t.readThroughEventPosition&&(te.current=e)}}}catch(e){T(e instanceof Error?e.message:`Could not update thread unread state.`)}finally{U.current=!1}})())},[u,c,p,ne,b.messageId]),oe=async()=>{if(!(z||e.length===0)){B(!0),T(null);try{await Promise.all(e.map(e=>f(e,b.messageId)))}catch(e){T(e instanceof Error?e.message:`Could not suppress standing observation.`)}finally{B(!1)}}};return(0,Q.jsxs)(`div`,{className:`thread-pane`,children:[(0,Q.jsxs)(`header`,{className:`thread-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`p`,{className:`overline`,children:[`Thread in `,t]}),(0,Q.jsxs)(`h2`,{children:[ne.length,` `,ne.length===1?`reply`:`replies`]})]}),(0,Q.jsxs)(`div`,{className:`thread-header-actions`,children:[e.length>0&&!y&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Suppress standing agents in this thread`,title:`Suppress standing agents in this thread`,disabled:z,onClick:()=>void oe(),children:(0,Q.jsx)(ny,{})}),P&&!y&&(0,Q.jsx)(`button`,{className:`panel-icon-button thread-follow-button${P.followed?` followed`:``}`,type:`button`,"aria-label":P.followed?`Unfollow thread`:`Follow thread`,"aria-pressed":P.followed,title:R?`Updating thread follow state`:P.followed?`Unfollow thread`:`Follow thread`,disabled:R,onClick:()=>void ie(),children:(0,Q.jsx)(Hv,{followed:P.followed})}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close thread`,title:`Close thread`,onClick:i,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]})]}),(0,Q.jsxs)(`div`,{className:`thread-scroll`,children:[(0,Q.jsxs)(`ol`,{className:`thread-message-list`,children:[(0,Q.jsx)(mv,{highlighted:r?.messageId===b.messageId,message:(()=>{let e=S?.root??b;return{...e,reactions:g[e.messageId]??e.reactions}})(),onDownloadArtifact:a,onLoadArtifact:o,onLoadReactors:l,onMessageVisible:p,onSetReaction:y?void 0:m}),ne.map(e=>(0,Q.jsxs)(v.Fragment,{children:[I===e.messageId&&(0,Q.jsx)(`li`,{className:`first-unread-divider`,role:`separator`,"aria-label":`First unread reply`,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`New replies`})}),(0,Q.jsx)(mv,{highlighted:r?.messageId===e.messageId,message:{...e,reactions:g[e.messageId]??e.reactions},onDownloadArtifact:a,onLoadArtifact:o,onLoadReactors:l,onMessageVisible:ae,onSetReaction:y?void 0:m})]},e.messageId))]}),!S&&!w&&(0,Q.jsx)(`p`,{className:`thread-state`,children:`Loading replies…`}),S?.nextCursor&&(0,Q.jsx)(`button`,{className:`timeline-earlier-button`,type:`button`,disabled:E,onClick:()=>void re(),children:E?`Loading…`:`Load more replies`})]}),y?(0,Q.jsx)(`p`,{className:`archived-read-only`,children:`Archived channels are read-only.`}):(0,Q.jsxs)(`form`,{className:`composer-form thread-composer`,onSubmit:e=>void W(e),children:[(0,Q.jsx)(`textarea`,{ref:V,"aria-label":`Reply in ${t}`,maxLength:5e4,placeholder:`Reply…`,rows:1,value:O,disabled:A||x,onChange:e=>{k(e.target.value),A||N(null)},onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),e.currentTarget.form?.requestSubmit())}}),(0,Q.jsx)(`button`,{className:`composer-icon-button send-button`,type:`submit`,"aria-busy":A,"aria-label":A?`Sending reply…`:`Send reply`,title:A?`Sending reply…`:`Send reply`,disabled:!O.trim()||A||x,children:(0,Q.jsx)(Iv,{})})]}),w&&(0,Q.jsx)(`p`,{className:`thread-error`,role:`alert`,children:w})]})}function iy({agentDestination:e,agentToken:t,channel:n,connection:r,earlier:i,later:a,messages:o,threadMessages:s,workspacesDestination:c,scheduledJobsDestination:l,memoryDestination:u,memoryToken:d,mentionsDestination:f,followingDestination:p,reviewsDestination:m,following:h,inbox:g,unread:_,principalEvents:y,unreadBoundaryMessageId:b,readActivatedInitially:x,focusedMessage:S,focusedThreadRoot:C,requestedThreadRootId:w,focusedMessageError:T,settingsDestination:E,settingsInitialSection:D,settingsRuntimeLabel:O,settingsSession:k,navigation:A,runActivities:j,runPreviews:M,runTrace:N,standingParticipationVersion:P,reactionUpdates:F,workshop:I,onForget:L,onAgentNavigationChanged:R,onArchiveChannel:ee,onArchiveDirectMessage:z,onAttachAgent:H,onCancelRun:te,onCreateChannel:U,onDismissAgent:ne,onDetachAgent:re,onDownloadArtifact:W,onLoadEarlier:ie,onLoadLater:ae,onJumpLatest:oe,onLoadArtifact:se,onLoadChannelMembers:ce,onLoadHumanPeers:le,onLoadRun:ue,onLoadRunTrace:G,onLoadRuntimeLaneStatus:K,onStartFreshProviderSession:q,onLoadThread:de,onLoadThreadUnread:J,onLoadReactors:Y,onAdvanceThreadRead:fe,onSetThreadFollowed:pe,onChangeChannelMember:me,onMemoryAuthenticationFailure:he,onOpenWorkspaces:X,onOpenScheduledJobs:ge,onOpenMemory:_e,onOpenMentions:ve,onOpenFollowing:ye,onOpenReviews:be,onOpenFollowedThread:xe,onOpenHumanNotification:Ce,onCreateAgent:we,onOpenAgentDefinition:Te,onOpenAgentSetup:Ee,onOpenAgentChannel:De,onOpenSettings:Oe,onRestoreChannel:ke,onRestoreDirectMessage:Ae,onSelectAgent:je,onSelectMemory:Me,onSelectChannel:Ne,onSetReaction:Pe,onSubmitCommand:Fe,onStartHumanConversation:Ie,onSwitchWorkspace:Re,onSettingsDirtyChange:ze,onSettingsAccessFailure:Ve}){let Ue=Km(),We=Gh(),Z=n.channelId,Ge=e!==null,Ke=c,qe=l,Ze=u!==null,Qe=f,$e=p,et=m,tt=E,nt=Ge||Ke||Ze||Qe||$e||et||tt,rt=vv(n),it=yv(n),at=wv(n),ot=Cv(n),st=Sv(n)||ot,[ct,lt]=(0,v.useState)(()=>nv(Z)),[ut,dt]=(0,v.useState)(null),[ft,pt]=(0,v.useState)(null),[mt,ht]=(0,v.useState)(!1),[gt,_t]=(0,v.useState)(null),[vt,yt]=(0,v.useState)(()=>new Set),[bt,xt]=(0,v.useState)({}),[St,Ct]=(0,v.useState)(()=>Date.now()),[wt,Tt]=(0,v.useState)(0),[Et,Dt]=(0,v.useState)(!1),[Ot,kt]=(0,v.useState)(x),[At,jt]=(0,v.useState)(R_),[Mt,Nt]=(0,v.useState)(!1),[Pt,Ft]=(0,v.useState)(G_),[It,Lt]=(0,v.useState)(!1),[Rt,zt]=(0,v.useState)(null),[Bt,Vt]=(0,v.useState)([]),Ht=(0,v.useMemo)(()=>Object.values(bt).sort((e,t)=>e.acceptedAt.localeCompare(t.acceptedAt)||e.runId.localeCompare(t.runId)),[bt]),Ut=(0,v.useMemo)(()=>Ht.filter(ov),[Ht]),Wt=(0,v.useMemo)(()=>Ut.filter(e=>e.kind===`respond`),[Ut]),Gt=(0,v.useMemo)(()=>{if(Ht.length===0)return[];let e=new Set(Ut.map(e=>e.inboundMessageId)),t=e.size>0?e:new Set([Ht[Ht.length-1].inboundMessageId]);return Ht.filter(e=>t.has(e.inboundMessageId))},[Ut,Ht]),Kt=Ht.map(e=>`${e.runId}:${e.status}:${e.cancellationRequestedAt??``}`).join(`|`),[qt,Jt]=(0,v.useState)(null),[Yt,Xt]=(0,v.useState)(null),Zt=Bt.length===1?Bt[0]:null,[Qt,$t]=(0,v.useState)(!1),[en,tn]=(0,v.useState)(!1),[nn,rn]=(0,v.useState)(!1),[an,on]=(0,v.useState)(!1),[sn,cn]=(0,v.useState)(0),[ln,un]=(0,v.useState)(!1),[dn,fn]=(0,v.useState)(null),[pn,mn]=(0,v.useState)([]),[hn,gn]=(0,v.useState)({agentId:null,key:0}),[_n,vn]=(0,v.useState)(null),[yn,bn]=(0,v.useState)(!1),[xn,Sn]=(0,v.useState)(!1),[Cn,wn]=(0,v.useState)(!1),[Tn,En]=(0,v.useState)(!1),[Dn,On]=(0,v.useState)(!1),[kn,An]=(0,v.useState)(null),[jn,Mn]=(0,v.useState)(null),[Nn,Pn]=(0,v.useState)([]),[Fn,In]=(0,v.useState)([]),[Ln,Rn]=(0,v.useState)([]),[zn,Bn]=(0,v.useState)(null),[Vn,Hn]=(0,v.useState)(!1),[Un,Wn]=(0,v.useState)(null),[Gn,Kn]=(0,v.useState)(!1),[qn,Jn]=(0,v.useState)({}),[Yn,Xn]=(0,v.useState)(null),[Zn,Qn]=(0,v.useState)(()=>Date.now()),[$n,er]=(0,v.useState)(null),[tr,nr]=(0,v.useState)(0),[rr,ar]=(0,v.useState)(null),[or,sr]=(0,v.useState)(null),[cr,lr]=(0,v.useState)(!1),[ur,dr]=(0,v.useState)(null),[fr,pr]=(0,v.useState)(!1),[mr,hr]=(0,v.useState)(null),[gr,_r]=(0,v.useState)(null),[vr,yr]=(0,v.useState)(!1),[br,xr]=(0,v.useState)(null),Sr=(0,v.useRef)(null),[Cr,wr]=(0,v.useState)(null),Tr=(0,v.useRef)(null),Er=(0,v.useRef)(null),Dr=(0,v.useRef)(null),Or=(0,v.useRef)(null),kr=(0,v.useRef)(null),Ar=(0,v.useRef)(null),jr=(0,v.useRef)({pointerX:0,width:0}),Mr=(0,v.useRef)({pointerX:0,width:0}),Nr=(0,v.useCallback)(e=>{g.markVisibleRead(e)},[g.markVisibleRead]),Pr=(0,v.useRef)(Z),Fr=(0,v.useRef)(!1),Ir=(0,v.useRef)(!0),Lr=(0,v.useRef)(0),Rr=(0,v.useRef)(0),zr=(0,v.useRef)(null),Br=(0,v.useCallback)(e=>{let t=Tr.current;t!==e&&(t&&Fr.current&&av(Z,{follow:Ir.current,scrollTop:t.scrollTop}),Tr.current=e,Fr.current=!1)},[Z]),Vr=A.principal.displayName||`You`,Hr=Tv(I.role),Ur=(0,v.useMemo)(()=>n.agents.filter(e=>e.lifecycleState===`active`&&e.runtimeProfileId!==null).map(e=>({agentId:e.agentId,definitionId:Nn.find(t=>t.agentId===e.agentId)?.definitionId??null,name:e.name})),[Nn,n.agents]),Wr=(0,v.useMemo)(()=>o.find(e=>e.messageId===Cr)??(C?.messageId===Cr?C:null),[C,o,Cr]),Gr=(0,v.useMemo)(()=>(C&&!o.some(e=>e.messageId===C.messageId)?[...o,C].sort((e,t)=>e.eventPosition-t.eventPosition):o).map(e=>{let t=s.filter(t=>t.threadRootId===e.messageId);return t.length===0?e:{...e,replyCount:e.replyCount+t.length,...P_(e,t),latestReplyAt:t[t.length-1].createdAt}}),[C,o,s]),Kr=(0,v.useCallback)(e=>{if(Nr(e),nt||!Ot||document.visibilityState!==`visible`||st)return;let t=Gr.find(t=>t.messageId===e);t&&_.advanceVisible({channelId:Z,token:d},t)},[nt,n,Z,Gr,Nr,d,Ot,_.advanceVisible]);(0,v.useEffect)(()=>{wr(null),kt(x)},[Z,x]),(0,v.useEffect)(()=>{S?.threadRootId&&wr(S.threadRootId)},[S]),(0,v.useEffect)(()=>{C?.messageId===w&&wr(w)},[C,w]),(0,v.useEffect)(()=>{if(!S||S.threadRootId!==null)return;let e=window.requestAnimationFrame(()=>{Tr.current?.querySelector(`[data-message-id="${S.messageId}"]`)?.scrollIntoView?.({behavior:`smooth`,block:`center`})});return()=>window.cancelAnimationFrame(e)},[Gr.length,S]);let qr=(0,v.useMemo)(()=>{let e=new Map;for(let t of I.channels)for(let n of t.agents)e.set(n.agentId,n);return Array.from(e.values()).sort((e,t)=>e.name.localeCompare(t.name))},[I.channels]),Jr=(0,v.useMemo)(()=>{let e=new Set(Ln.map(e=>e.provisioning.definitionId).filter(e=>e!==null));return Nn.filter(t=>!e.has(t.definitionId)).sort((e,t)=>e.displayName.localeCompare(t.displayName))},[Nn,Ln]),Yr=(0,v.useMemo)(()=>{let e=new Map;for(let t of Fn)t.lifecycleState!==`active`&&t.ownerPrincipalId===A.principal.principalId&&e.set(t.agentId,{entryId:t.agentId,conversationChannelId:null,definitionId:t.definitionId,displayName:t.displayName,handle:t.handle,setupId:null,state:t.lifecycleState===`archived`?`Archived`:`Draft`});for(let t of Ln){let n=Fn.find(e=>e.definitionId===t.provisioning.definitionId);e.set(t.provisioning.agentId??t.provisioning.operationId,{entryId:t.provisioning.operationId,conversationChannelId:null,definitionId:t.provisioning.definitionId,displayName:n?.displayName??t.input.displayName,handle:n?.handle??t.input.handle,setupId:t.provisioning.operationId,state:`Needs attention`})}for(let t of I.channels)if(t.kind===`direct`)for(let n of t.agents){if(n.lifecycleState!==`archived`)continue;let r=e.get(n.agentId);e.set(n.agentId,{entryId:n.agentId,conversationChannelId:t.channelId,definitionId:r?.definitionId??null,displayName:r?.displayName??n.name,handle:r?.handle??n.handle,setupId:r?.setupId??null,state:`Archived`})}return Array.from(e.values()).sort((e,t)=>e.displayName.localeCompare(t.displayName))},[Fn,Ln,A.principal.principalId,I.channels]),Xr=(0,v.useMemo)(()=>I.channels.filter(e=>e.kind===`direct`&&!Cv(e)&&!e.agents.some(e=>e.lifecycleState===`archived`)),[I.channels]),Zr=(0,v.useMemo)(()=>{if(n.kind!==`group`||!$n)return[];let e=new Map;for(let t of n.agents)e.set(t.principalId,{displayName:t.name,handle:t.handle,kind:`agent`,principalId:t.principalId});for(let t of n.participants)t.principalId===A.principal.principalId||t.handle===null||t.kind!==`agent`&&t.kind!==`human`||e.set(t.principalId,{displayName:t.displayName,handle:t.handle,kind:t.kind,principalId:t.principalId});let t=$n.query.trim().toLocaleLowerCase();return Array.from(e.values()).filter(e=>!t||e.handle.toLocaleLowerCase().startsWith(t)||e.displayName.toLocaleLowerCase().startsWith(t)).sort((e,t)=>e.handle.localeCompare(t.handle))},[n,$n,A.principal.principalId]);(0,v.useEffect)(()=>{if(n.kind!==`notification`){ar(null);return}let e=!0;return ir(k).then(t=>{e&&ar(t)}).catch(()=>{e&&ar(null)}),()=>{e=!1}},[n.kind,k]);let Qr=(0,v.useCallback)(e=>{let t=new Set(e.subscriptions.filter(e=>e.lifecycleState===`active`).map(e=>e.agentId)),n=Sr.current;if(n!==null){let t=e.subscriptions.filter(e=>e.lifecycleState===`active`&&!n.has(e.agentId));t.length>0&&xr(`${t.map(e=>e.agentDisplayName).join(`, `)} joined in as ${t.length===1?`a standing participant`:`standing participants`}.`)}Sr.current=t,sr(e)},[]),$r=(0,v.useCallback)(async(e=vr)=>{if(n.kind!==`group`)return null;let t=await Je({channelId:Z,token:d},e);return Qr(t),t},[Qr,n.kind,Z,d,vr]);(0,v.useEffect)(()=>{Sr.current=null,sr(null),xr(null),yr(!1),hr(null),En(!1)},[Z]),(0,v.useEffect)(()=>{if(n.kind!==`group`){sr(null),dr(null);return}let e=!0;return lr(!0),dr(null),Je({channelId:Z,token:d},vr).then(t=>{e&&Qr(t)},t=>{e&&dr(t instanceof Error?t.message:`Could not load standing participation.`)}).finally(()=>{e&&lr(!1)}),()=>{e=!1}},[Qr,n.kind,Z,d,vr,P]);let ei=Gt.at(-1)?.runId??null,{collaborationActivity:ti,entries:ni,failed:ri,loaded:ii}=Ii(ei,N,G);(0,v.useEffect)(()=>{z_(At)},[At]),(0,v.useEffect)(()=>{K_(Pt)},[Pt]),(0,v.useEffect)(()=>{if(n.kind!==`group`)return;let e=window.setInterval(()=>Qn(Date.now()),3e4);return()=>window.clearInterval(e)},[n.kind]);let ai=(0,v.useMemo)(()=>n.kind===`group`?n.agents.filter(e=>{let t=qn[e.agentId]??0,n=t?0:e.engagedUntil?Date.parse(e.engagedUntil):e.engaged?Zn:0;for(let r of o){let i=Date.parse(r.createdAt);!Number.isFinite(i)||i<=t||(r.authorPrincipalId===e.principalId||r.mentions.some(t=>t.kind===`agent`&&t.principalId===e.principalId))&&(n=Math.max(n,i+9e5))}return n>Zn&&n>t}):[],[n.agents,n.kind,qn,Zn,o]),oi=async(e,t=null)=>{if(!Yn){Xn(e),pt(null);try{await ne(e,_v(),t),t===null&&Jn(t=>({...t,[e]:Date.now()})),Qn(Date.now()),$r().catch(()=>void 0)}catch(e){pt(e instanceof Error?e.message:`Could not dismiss this agent.`)}finally{Xn(null)}}},si=async e=>{let t=or;if(!(!t||fr)){pr(!0),hr(null);try{Qr(await Ye({channelId:Z,token:d},e,t.policy.policyVersion,_v()))}catch(e){hr(e instanceof Error?e.message:`Could not update standing participation.`),await $r().catch(()=>void 0)}finally{pr(!1)}}},ci=async(e,t)=>{let n=`${e}:${t.scopeId}`;if(gr===null){_r(n),dr(null);try{Qr(await Xe({channelId:Z,token:d},e,t,_v()))}catch(e){dr(e instanceof Error?e.message:`Could not resume standing observation.`),await $r().catch(()=>void 0)}finally{_r(null)}}},li=(0,v.useCallback)(async()=>{try{let[e,n,r]=await Promise.all([Le(t),He(t),Be(t)]);In(e),Pn(n),Rn(r)}catch(e){throw e instanceof B?he(e.message):e instanceof V&&Ve(e.message),e}},[t,he,Ve]);(0,v.useEffect)(()=>{li().catch(e=>{pt(e instanceof Error?e.message:`Could not load visible agents.`)})},[li]);let ui=(0,v.useCallback)(async()=>{await Promise.all([R(),li()])},[R,li]),di=async()=>{if(!Vn){Hn(!0),pt(null);try{Bn(await He(t))}catch(e){pt(e instanceof Error?e.message:`Could not load available agents.`)}finally{Hn(!1)}}},fi=async()=>{if(!Gn){Kn(!0),pt(null);try{Wn(await ce())}catch(e){pt(e instanceof Error?e.message:`Could not load channel members.`)}finally{Kn(!1)}}},pi=async(e,t,n,r)=>{let i=await me(e,t,n,r);return await ui(),i},mi=async e=>{let t=new Set(n.agents.map(e=>e.agentId)),r=new Set(e);for(let e of t)r.has(e)||await re(e,_v());for(let e of r)t.has(e)||await H(e,_v());await ui(),Bn(null)},hi=async()=>{if(!(n.kind!==`group`||n.role!==`owner`||Sv(n)||kn||!await Ue(`Archive #${rt}? Its history will remain available and you can restore it later.`))){An(Z),pt(null);try{await ee(Z,_v())}catch(e){pt(e instanceof Error?e.message:`Could not archive this channel.`)}finally{An(null)}}},gi=async e=>{if(!kn){An(e),pt(null);try{await ke(e,_v()),bn(!1)}catch(e){pt(e instanceof Error?e.message:`Could not restore this channel.`)}finally{An(null)}}},_i=async()=>{if(!(n.kind!==`direct`||Cv(n)||jn||n.agents.some(e=>e.lifecycleState===`archived`)||!await Ue(`Archive your conversation with ${rt}? Its history will remain available and new activity will return it to Direct messages.`))){Mn(Z),pt(null);try{await z(Z,_v())}catch(e){pt(e instanceof Error?e.message:`Could not archive this direct message.`)}finally{Mn(null)}}},vi=async e=>{if(!jn){Mn(e),pt(null);try{await Ae(e,_v()),Sn(!1)}catch(e){pt(e instanceof Error?e.message:`Could not restore this direct message.`)}finally{Mn(null)}}},yi=async()=>{tn(!1),await Ue(`Forget this browser session? You will need to enroll again.`)&&L()},bi=(e,t)=>{er(Ev(e,t)),nr(0)},xi=e=>{if(!$n)return;let t=`@${e.handle} `,n=ct.slice(0,$n.start)+t+ct.slice($n.end),r=$n.start+t.length;lt(n),rv(Z,n),dt(null),er(null),Dr.current=r};(0,v.useEffect)(()=>{if(!en)return;let e=e=>{Ar.current?.contains(e.target)||tn(!1)},t=e=>{e.key===`Escape`&&tn(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[en]),(0,v.useEffect)(()=>{let e=e=>{e.key.toLocaleLowerCase()===`k`&&(e.metaKey||e.ctrlKey)&&!e.altKey&&(e.preventDefault(),tn(!1),rn(!0))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[]),(0,v.useEffect)(()=>{if(!nn)return;let e=!1;un(!0),fn(null);let t={channelId:Z,token:d};return Promise.all([Se(t),Promise.allSettled(Ur.map(e=>Se(t,e.agentId)))]).then(([t,n])=>{if(e)return;let r=new Map,i=(e,t)=>{if(!e.paletteEntry||e.operationId===`capabilities.discover`||(e.scope===`principal_agent`||e.scope===`agent_owner`)!=(t!==null))return;let n=`${e.operationId}-${t?.agentId??`global`}`;r.set(n,{capability:e,key:n,targetAgentId:t?.agentId??null,targetLabel:t?.name??null})};t.capabilities.forEach(e=>i(e,null)),n.forEach((e,t)=>{if(e.status!==`fulfilled`)return;let n=Ur[t];e.value.capabilities.forEach(e=>i(e,n))}),mn([...r.values()].sort((e,t)=>e.capability.label.localeCompare(t.capability.label)||(e.targetLabel??``).localeCompare(t.targetLabel??``)))}).catch(t=>{if(!e){if(t instanceof B){he(t.message);return}fn(t instanceof Error?t.message:`Could not load available actions.`)}}).finally(()=>{e||un(!1)}),()=>{e=!0}},[nn,Z,d,he,Ur]),(0,v.useEffect)(()=>{let e=!1;Vt([]),zt(null);let t=n.agents.filter(e=>e.lifecycleState===`active`&&e.runtimeProfileId!==null);if(!n.canSubmitCommands||at||t.length===0)return()=>{e=!0};let r=n.kind===`group`?t.map(e=>e.agentId):[null];return Promise.all(r.map(e=>K(e))).then(t=>{e||Vt(t)}).catch(t=>{e||zt(t instanceof Error?t.message:`Could not load runtime status.`)}),()=>{e=!0}},[n.agents,n.canSubmitCommands,n.kind,Z,at,K,Kt,nt]);let Si=async e=>{if(!(!Zt||Zt.workspaceMode===`neutral`||Zt.workspaceRevision===null||e===Zt.workspace)){zt(null),$t(!0);try{let t=await Re(e,Zt.workspaceRevision);Vt(e=>e.map(e=>({...e,workspace:t.workspace,workspaceLabel:t.workspaces.find(e=>e.current)?.name??e.workspaceLabel,workspaceRevision:t.revision,workspaces:t.workspaces}))),xt({})}catch(e){zt(e instanceof Error?e.message:`Could not switch workspace.`)}finally{$t(!1)}}},Ci=async e=>{if(!(qt!==null||e.activeRun!==null||!await Ue(`Start a fresh provider session for ${e.agentName}? This ends only this channel-and-agent provider session and its live process. Conversation history, messages, memories, settings, and this browser's enrollment are preserved.`))){Jt(e.agentId),Xt(null),zt(null);try{let t=await q(e.agentId,_v()),n=await K(e.agentId);Vt(t=>t.map(t=>t.agentId===e.agentId?n:t)),xt(t=>Object.fromEntries(Object.entries(t).filter(([,t])=>t.agentId!==e.agentId))),Xt(`Fresh provider session ready for ${e.agentName}. Revision ${t.revision.slice(0,12)}.`)}catch(e){zt(e instanceof Error?e.message:`Could not start a fresh provider session.`)}finally{Jt(null)}}},wi=async e=>{let{operationId:t}=e.capability;if(t===`workspace.catalogue.manage`)return X(),null;if(t===`memory.manage`)return _e(),null;if(t===`scheduled_jobs.manage`)return ge(),null;if(t===`integration.github.manage`)return Oe(`github`),null;if(t===`integration.github.review`)return rn(!1),on(!0),null;if(t===`administration.webhook_status.read`)return Oe(`administration`),null;if(t===`runtime.model.manage`||t===`runtime.backend.manage`){let t=Ur.find(t=>t.agentId===e.targetAgentId);if(!t?.definitionId)throw Error(`This agent's runtime settings are not available.`);return je(t.definitionId,`runtime`),null}if(t===`runtime.status.read`){if(!e.targetAgentId)throw Error(`Select an agent to inspect its runtime.`);return rn(!1),nt&&await Ne(Z),gn(t=>({agentId:e.targetAgentId,key:t.key+1})),null}if(t===`conversation.session.reset`){if(!e.targetAgentId)throw Error(`Select an agent to start a fresh session.`);let t=await K(e.targetAgentId);if(t.activeRun!==null)throw Error(`${t.agentName} has an active run. Stop it before starting a fresh session.`);return rn(!1),await Ci(t),null}throw Error(`This action does not yet have a native Workshop interaction.`)};(0,v.useLayoutEffect)(()=>{let e=Er.current;if(!e)return;let t=e.offsetHeight-e.clientHeight;if(e.style.height=`auto`,e.style.height=`${e.scrollHeight+t}px`,Dr.current!==null){let t=Dr.current;Dr.current=null,e.focus(),e.setSelectionRange(t,t)}},[ct,Z]),(0,v.useEffect)(()=>{if(!Mt)return;let e=()=>Nt(!1);return window.addEventListener(`pointerup`,e,{once:!0}),window.addEventListener(`pointercancel`,e,{once:!0}),()=>{window.removeEventListener(`pointerup`,e),window.removeEventListener(`pointercancel`,e)}},[Mt]),(0,v.useEffect)(()=>{if(!It)return;let e=()=>Lt(!1);return window.addEventListener(`pointerup`,e,{once:!0}),window.addEventListener(`pointercancel`,e,{once:!0}),()=>{window.removeEventListener(`pointerup`,e),window.removeEventListener(`pointercancel`,e)}},[It]);let Ti=e=>{At.collapsed||(e.currentTarget.setPointerCapture(e.pointerId),jr.current={pointerX:e.clientX,width:At.width},Nt(!0))},Ei=e=>{if(!Mt)return;let t=e.clientX-jr.current.pointerX;jt(e=>({...e,width:L_(jr.current.width+t)}))},Oi=e=>{let t=e.key===`ArrowLeft`?-1:+(e.key===`ArrowRight`);(t!==0||e.key===`Home`||e.key===`End`)&&(e.preventDefault(),jt(n=>({collapsed:!1,width:e.key===`Home`?O_:e.key===`End`?A_:L_(n.width+t*16*D_)})))},ki=()=>{jt(e=>({...e,collapsed:!e.collapsed}))},Ai=e=>{e.currentTarget.setPointerCapture(e.pointerId),Mr.current={pointerX:e.clientX,width:Pt},Lt(!0)},ji=e=>{if(!It)return;let t=Mr.current.pointerX-e.clientX;Ft(W_(Mr.current.width+t))},Mi=e=>{let t=e.key===`ArrowLeft`?1:e.key===`ArrowRight`?-1:0;(t!==0||e.key===`Home`||e.key===`End`)&&(e.preventDefault(),Ft(n=>e.key===`Home`?V_:e.key===`End`?U_:W_(n+t*16*D_)))};(0,v.useEffect)(()=>{xt({}),yt(new Set);let e=ev(Z);if(e.length===0)return;let t=!1;return Promise.allSettled(e.map(e=>ue(e))).then(e=>{if(!t){let t=e.flatMap(e=>e.status===`fulfilled`&&e.value.channelId===Z?[e.value]:[]);xt(Object.fromEntries(t.map(e=>[e.runId,e]))),e.some(e=>e.status===`rejected`)&&pt(`Could not restore every active agent run.`)}}),()=>{t=!0}},[Z,ue]),(0,v.useEffect)(()=>{j.length!==0&&xt(e=>{let t={...e};for(let e of j)e.run.channelId===Z&&(t[e.run.runId]=e.run);return t})},[Z,j]),(0,v.useEffect)(()=>{tv(Z,Ut.map(e=>e.runId))},[Ut,Z]),(0,v.useEffect)(()=>{if(Ut.length===0)return;Ct(Date.now());let e=window.setInterval(()=>Ct(Date.now()),1e3);return()=>window.clearInterval(e)},[Ut.length]),(0,v.useLayoutEffect)(()=>{let e=Tr.current;if(!e)return;Pr.current!==Z&&(Pr.current=Z,Fr.current=!1,Ir.current=!0,Lr.current=0,Rr.current=0,zr.current=null,Tt(0),Dt(!1));let t=o.reduce((e,t)=>Math.max(e,t.eventPosition),0),n=o[0]?.eventPosition??0;if(!Fr.current){if(o.length===0)return;let r=b?e.querySelector(`[data-message-id="${b}"]`):null,i=r?null:iv(Z);r?r.scrollIntoView?.({block:`start`}):e.scrollTop=i?.follow===!1?Math.min(i.scrollTop,e.scrollHeight):e.scrollHeight,Fr.current=!0,Ir.current=r?sv(e):i?.follow??!0,av(Z,{follow:Ir.current,scrollTop:e.scrollTop}),Dt(!sv(e)),Lr.current=t,Rr.current=n,Tt(0);return}let r=zr.current;r&&o.length>0&&ne.eventPosition>Lr.current).length;Lr.current=Math.max(Lr.current,t),i!==0&&(Ir.current?(e.scrollTop=e.scrollHeight,av(Z,{follow:!0,scrollTop:e.scrollTop}),Tt(0)):Tt(e=>e+i))},[nt,Z,o,b]),(0,v.useLayoutEffect)(()=>{let e=Tr.current;!e||!Fr.current||!Ir.current||(e.scrollTop=e.scrollHeight,av(Z,{follow:!0,scrollTop:e.scrollTop}))},[Z,ct,M]);let Ni=()=>{let e=Tr.current;if(!e||!Fr.current)return;kt(!0);let t=sv(e);Ir.current=t,Dt(!t),av(Z,{follow:t,scrollTop:e.scrollTop}),t&&Tt(0)},Pi=()=>{let e=Tr.current;if(e){if(Ir.current=!0,a.available){oe(),av(Z,{follow:!0,scrollTop:e.scrollTop}),Tt(0),Dt(!1);return}e.scrollTop=e.scrollHeight,av(Z,{follow:!0,scrollTop:e.scrollTop}),Tt(0),Dt(!1)}},Li=()=>{let e=Tr.current;e&&(zr.current={scrollHeight:e.scrollHeight,scrollTop:e.scrollTop}),ie()};(0,v.useEffect)(()=>{i.error&&(zr.current=null)},[i.error]);let Ri=async e=>{e.preventDefault();let t=ct.trim();if(!(!t&&!gt||mt||Wt.length>0)){pt(null),ht(!0);try{let e=ut??_v();dt(e);let n=await Fe(e,t,gt,null);lt(``),rv(Z,``),dt(null),_t(null),Or.current&&(Or.current.value=``),n.runs.length>0&&xt(e=>{let t={...e};for(let e of n.runs)e.runId in t||(t[e.runId]=e);return t})}catch(e){pt(e instanceof Error?e.message:`Kai could not run this command.`)}finally{ht(!1)}}},zi=async e=>{let t=e.filter(e=>ov(e)&&!vt.has(e.runId));if(t.length!==0){pt(null),yt(e=>new Set([...e,...t.map(e=>e.runId)]));try{let e=await Promise.allSettled(t.map(e=>te(e.runId))),n=e.flatMap(e=>e.status===`fulfilled`?[e.value]:[]);n.length>0&&xt(e=>({...e,...Object.fromEntries(n.map(e=>[e.runId,e]))}));let r=e.filter(e=>e.status===`rejected`);r.length>0&&pt(r.length===t.length?`Could not stop the selected agent run.`:`Stopped ${n.length} agent ${n.length===1?`run`:`runs`}; ${r.length} could not be stopped.`)}finally{let e=new Set(t.map(e=>e.runId));yt(t=>new Set([...t].filter(t=>!e.has(t))))}}},Bi=e=>zi([e]),Vi=()=>zi(Wt);return(0,Q.jsxs)(`main`,{className:`workshop-app ${Ge?`agents-open`:``} ${Ke?`workspaces-open`:``} ${qe?`scheduled-jobs-open`:``} ${Ze?`memory-open`:``} ${Qe?`mentions-open`:``} ${$e?`following-open`:``} ${et?`reviews-open`:``} ${tt?`settings-open`:``} ${At.collapsed?`sidebar-collapsed`:``} ${Mt||It?`pane-resizing`:``}`,style:{"--channel-sidebar-width":`${At.collapsed?j_:At.width}px`,"--context-pane-width":`${Pt}px`},children:[(0,Q.jsxs)(`aside`,{ref:kr,className:`channel-sidebar ${At.collapsed?`collapsed`:``}`,"aria-label":`Workshop navigation`,children:[(0,Q.jsxs)(`header`,{className:`sidebar-header`,children:[(0,Q.jsx)(`div`,{className:`sidebar-title`,children:(0,Q.jsx)(`p`,{className:`overline`,children:`Kai Workshop`})}),(0,Q.jsx)(`div`,{className:`sidebar-header-actions`,children:(0,Q.jsx)(`button`,{className:`sidebar-toggle`,type:`button`,"aria-label":At.collapsed?`Expand navigation`:`Collapse navigation`,"aria-expanded":!At.collapsed,title:At.collapsed?`Expand navigation`:`Collapse navigation`,onClick:ki,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:At.collapsed?`›`:`‹`})})})]}),(0,Q.jsxs)(`nav`,{children:[!At.collapsed&&(0,Q.jsxs)(`div`,{className:`nav-heading-row`,children:[(0,Q.jsx)(`p`,{className:`nav-heading`,children:`Channels`}),(0,Q.jsxs)(`div`,{className:`nav-heading-actions`,children:[(0,Q.jsx)(`button`,{className:`nav-tool-button`,type:`button`,"aria-label":`Archived channels`,title:`Archived channels`,onClick:()=>bn(!0),children:(0,Q.jsx)(Gv,{})}),(0,Q.jsx)(`button`,{className:`nav-add-button`,type:`button`,"aria-label":`Create channel`,title:`Create channel`,onClick:()=>vn({initialAgentIds:[],originChannelId:null,originName:null}),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`})})]})]}),I.channels.filter(e=>e.kind===`group`&&!Sv(e)).map(e=>{let t=xv(_.byChannel[e.channelId]),n=g.counts.unreadByChannel[e.channelId]??0;return(0,Q.jsxs)(`button`,{className:`channel-link ${t>0?`unread`:``} ${!nt&&e.channelId===Z?`active`:``}`,type:`button`,"aria-label":`${vv(e)}${bv(_.byChannel[e.channelId])}${n>0?`, ${n} unread mentions`:``}`,title:vv(e),onClick:()=>Ne(e.channelId),children:[(0,Q.jsx)(`span`,{children:yv(e)}),(0,Q.jsx)(`span`,{children:vv(e)}),(t>0||n>0||!nt&&e.channelId===Z)&&(0,Q.jsxs)(`span`,{className:`channel-link-status`,children:[t>0&&(0,Q.jsx)(`span`,{className:`unread-pip`,"aria-hidden":`true`}),n>0&&(0,Q.jsx)(`span`,{className:`mention-count`,"aria-label":`${n} unread mentions`,children:n>99?`99+`:n}),!nt&&e.channelId===Z&&(0,Q.jsx)(`span`,{className:`live-pip`,"aria-label":`Live`})]})]},e.channelId)}),!At.collapsed&&(0,Q.jsxs)(`div`,{className:`nav-heading-row`,children:[(0,Q.jsx)(`p`,{className:`nav-heading`,children:`Direct messages`}),(0,Q.jsxs)(`div`,{className:`nav-heading-actions`,children:[(0,Q.jsx)(`button`,{className:`nav-tool-button`,type:`button`,"aria-label":`Archived direct messages`,title:`Archived direct messages`,onClick:()=>Sn(!0),children:(0,Q.jsx)(Gv,{})}),(0,Q.jsx)(`button`,{className:`nav-add-button`,type:`button`,"aria-label":`Start direct message`,title:`Start direct message`,onClick:()=>On(!0),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`})})]})]}),Xr.map(e=>{let t=xv(_.byChannel[e.channelId]),n=e.agents.length===0?e.participants.find(e=>e.kind===`human`):void 0,r=!n&&e.agents.length===1?e.agents[0]:void 0;return(0,Q.jsxs)(`button`,{className:`channel-link ${t>0?`unread`:``} ${!nt&&e.channelId===Z?`active`:``}`,type:`button`,"aria-label":`${vv(e)}${bv(_.byChannel[e.channelId])}`,title:vv(e),onClick:()=>Ne(e.channelId),children:[n?(0,Q.jsx)(Kh,{avatar:n.avatar??N_,className:`channel-human-avatar`,displayName:n.displayName,principalId:n.principalId}):r?(0,Q.jsx)(`span`,{className:`channel-agent-avatar`,"aria-hidden":`true`,children:r.name.slice(0,1).toUpperCase()}):(0,Q.jsx)(`span`,{children:yv(e)}),(0,Q.jsx)(`span`,{children:vv(e)}),(t>0||!nt&&e.channelId===Z)&&(0,Q.jsxs)(`span`,{className:`channel-link-status`,children:[t>0&&(0,Q.jsx)(`span`,{className:`unread-pip`,"aria-hidden":`true`}),!nt&&e.channelId===Z&&(0,Q.jsx)(`span`,{className:`live-pip`,"aria-label":`Live`})]})]},e.channelId)}),(0,Q.jsx)(`p`,{className:`nav-heading`,children:`Activity`}),I.channels.filter(e=>e.kind===`notification`).map(e=>{let t=xv(_.byChannel[e.channelId]);return(0,Q.jsxs)(`button`,{className:`channel-link notification ${t>0?`unread`:``} ${!nt&&e.channelId===Z?`active`:``}`,type:`button`,"aria-label":`${vv(e)}${bv(_.byChannel[e.channelId])}`,title:vv(e),onClick:()=>Ne(e.channelId),children:[(0,Q.jsx)(`span`,{children:`!`}),(0,Q.jsx)(`span`,{children:vv(e)}),(t>0||!nt&&e.channelId===Z)&&(0,Q.jsxs)(`span`,{className:`channel-link-status`,children:[t>0&&(0,Q.jsx)(`span`,{className:`unread-pip`,"aria-hidden":`true`}),!nt&&e.channelId===Z&&(0,Q.jsx)(`span`,{className:`live-pip`,"aria-label":`Live`})]})]},e.channelId)}),(0,Q.jsxs)(`button`,{className:`channel-link mentions-link ${Qe?`active`:``}`,type:`button`,"aria-label":`Mentions${g.counts.unread>0?`, ${g.counts.unread} unread`:``}`,title:`Mentions`,onClick:ve,children:[(0,Q.jsx)(`span`,{className:`workspace-nav-icon mentions-nav-icon`,"aria-hidden":`true`,children:`@`}),(0,Q.jsx)(`span`,{children:`Mentions`}),(g.counts.unread>0||Qe)&&(0,Q.jsxs)(`span`,{className:`channel-link-status`,children:[g.counts.unread>0&&(0,Q.jsx)(`span`,{className:`mention-count`,"aria-hidden":`true`,children:g.counts.unread>99?`99+`:g.counts.unread}),Qe&&(0,Q.jsx)(`span`,{className:`live-pip`,"aria-label":`Open`})]})]}),(0,Q.jsxs)(`button`,{className:`channel-link following-link ${$e?`active`:``}`,type:`button`,"aria-label":`Following${h.totalUnread>0?`, ${h.totalUnread} unread`:``}`,title:`Following`,onClick:ye,children:[(0,Q.jsx)(`span`,{className:`workspace-nav-icon following-nav-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(Hv,{followed:!1})}),(0,Q.jsx)(`span`,{children:`Following`}),(h.totalUnread>0||$e)&&(0,Q.jsxs)(`span`,{className:`channel-link-status`,children:[h.totalUnread>0&&(0,Q.jsx)(`span`,{className:`mention-count`,"aria-hidden":`true`,children:h.totalUnread>99?`99+`:h.totalUnread}),$e&&(0,Q.jsx)(`span`,{className:`live-pip`,"aria-label":`Open`})]})]}),(0,Q.jsxs)(`button`,{className:`channel-link reviews-link ${et?`active`:``}`,type:`button`,"aria-label":`Reviews`,title:`Reviews`,onClick:be,children:[(0,Q.jsx)(`span`,{className:`workspace-nav-icon reviews-nav-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(Xv,{})}),(0,Q.jsx)(`span`,{children:`Reviews`}),et&&(0,Q.jsx)(`span`,{className:`channel-link-status`,children:(0,Q.jsx)(`span`,{className:`live-pip`,"aria-label":`Open`})})]}),!At.collapsed&&(0,Q.jsxs)(`div`,{className:`nav-heading-row`,children:[(0,Q.jsx)(`p`,{className:`nav-heading`,children:`Agents`}),(0,Q.jsxs)(`div`,{className:`nav-heading-actions`,children:[Yr.length>0&&(0,Q.jsx)(`button`,{className:`nav-tool-button`,type:`button`,"aria-label":`Your drafts and archived agents`,title:`Your drafts and archived agents`,onClick:()=>wn(!0),children:(0,Q.jsx)(Gv,{})}),(0,Q.jsx)(`button`,{className:`nav-add-button`,type:`button`,"aria-label":`Create agent`,title:`Create agent`,onClick:we,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`})})]})]}),Jr.map(t=>{let n=ai.some(e=>e.agentId===t.agentId),r=Ge&&e?.definitionId===t.definitionId;return(0,Q.jsxs)(`button`,{className:`agent-link ${n?`engaged`:``} ${r?`active`:``}`,type:`button`,title:`Manage ${t.displayName}`,"aria-label":`Manage ${t.displayName}`,onClick:()=>void Te(t.definitionId),children:[(0,Q.jsx)(`span`,{className:`mini-avatar`,children:t.displayName.slice(0,1).toUpperCase()}),(0,Q.jsx)(`span`,{children:(0,Q.jsx)(`strong`,{children:t.displayName})}),r&&(0,Q.jsx)(`span`,{className:`live-pip`,"aria-label":`Open`})]},t.definitionId)})]}),(0,Q.jsxs)(`footer`,{ref:Ar,className:`sidebar-footer ${Ke||qe||Ze||tt?`active`:``}`,children:[en&&(0,Q.jsxs)(`div`,{className:`profile-menu`,role:`menu`,"aria-label":`Your Kai menu`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Your Kai`}),(0,Q.jsxs)(`button`,{type:`button`,role:`menuitem`,"aria-current":Ke?`page`:void 0,onClick:()=>{tn(!1),X()},children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(Jv,{})}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Workspaces`}),(0,Q.jsx)(`small`,{children:`Authorized directories`})]})]}),(0,Q.jsxs)(`button`,{type:`button`,role:`menuitem`,"aria-current":qe?`page`:void 0,onClick:()=>{tn(!1),ge()},children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(Yv,{})}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Scheduled jobs`}),(0,Q.jsx)(`small`,{children:`Upcoming and recurring work`})]})]}),(0,Q.jsxs)(`button`,{type:`button`,role:`menuitem`,"aria-current":Ze?`page`:void 0,onClick:()=>{tn(!1),_e()},children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`◇`}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Memory`}),(0,Q.jsx)(`small`,{children:`Facts and episodes`})]})]}),(0,Q.jsxs)(`button`,{type:`button`,role:`menuitem`,"aria-current":tt?`page`:void 0,onClick:()=>{tn(!1),Oe()},children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`⚙`}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Settings`}),(0,Q.jsx)(`small`,{children:`Profile and preferences`})]})]}),(0,Q.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{tn(!1),rn(!0)},children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`?`}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Help and actions`}),(0,Q.jsx)(`small`,{children:`Search available operations · ⌘/Ctrl-K`})]})]}),(0,Q.jsx)(`div`,{className:`profile-menu-separator`}),(0,Q.jsxs)(`button`,{className:`forget-session-menu-item`,type:`button`,role:`menuitem`,onClick:()=>void yi(),children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`↪`}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Forget session`}),(0,Q.jsx)(`small`,{children:`Enroll this browser again`})]})]})]}),(0,Q.jsxs)(`button`,{className:`profile-trigger`,type:`button`,"aria-haspopup":`menu`,"aria-expanded":en,"aria-label":`${Vr} profile`,title:`${Vr} — ${Hr}`,onClick:()=>tn(e=>!e),children:[(0,Q.jsx)(Kh,{avatar:A.principal.avatar??N_,className:`mini-avatar human`,displayName:Vr,principalId:A.principal.principalId}),(0,Q.jsxs)(`span`,{className:`profile-copy`,children:[(0,Q.jsx)(`strong`,{children:Vr}),(0,Q.jsx)(`small`,{children:Hr})]}),(0,Q.jsx)(`span`,{className:`profile-chevron`,"aria-hidden":`true`,children:`⌃`})]})]}),!At.collapsed&&(0,Q.jsx)(`div`,{className:`sidebar-resize-handle`,role:`separator`,"aria-label":`Resize navigation`,"aria-orientation":`vertical`,"aria-valuemin":O_,"aria-valuemax":A_,"aria-valuenow":At.width,tabIndex:0,onKeyDown:Oi,onPointerDown:Ti,onPointerMove:Ei})]}),Ge&&e?(0,Q.jsx)(Ug,{activeChannelId:Z,initialCreating:e.creating,initialDefinitionId:e.definitionId,initialSetupId:e.setupId,initialSection:e.section,isAdministrator:I.role===`admin`,onAuthenticationFailure:he,onChannelAccessFailure:Ve,onClose:()=>Ne(Z),onCreateAgent:we,onNavigationChanged:ui,onOpenChannel:De,onSelectAgent:je,principalId:A.principal.principalId,principalName:Vr,principalEvents:y,runActive:Wt.length>0,token:t,workshopName:I.name}):Ke?(0,Q.jsx)(Fh,{detailPanelLayout:{maximumWidth:U_,minimumWidth:V_,onKeyDown:Mi,onPointerDown:Ai,onPointerMove:ji,width:Pt},onAuthenticationFailure:he,onChannelAccessFailure:Ve,onClose:()=>Ne(Z),session:k}):qe?(0,Q.jsx)(Vh,{detailPanelLayout:{maximumWidth:U_,minimumWidth:V_,onKeyDown:Mi,onPointerDown:Ai,onPointerMove:ji,width:Pt},onAuthenticationFailure:he,onClose:()=>Ne(Z),principalEvents:y,session:k}):tt?(0,Q.jsx)(hg,{initialSection:D,onAuthenticationFailure:he,onChannelAccessFailure:Ve,onClose:()=>Ne(Z),onDirtyChange:ze,onHumanAvatarChanged:We,onNavigationChanged:R,isAdministrator:I.role===`admin`,principalName:Vr,roleLabel:Hr,runtimeLabel:O,runActive:Wt.length>0,session:k}):u?(0,Q.jsx)(kh,{detailPanelLayout:{maximumWidth:U_,minimumWidth:V_,onKeyDown:Mi,onPointerDown:Ai,onPointerMove:ji,width:Pt},initialMemoryId:u.memoryId,onAuthenticationFailure:he,onClose:()=>Ne(Z),onSelectMemory:Me,token:d}):Qe?(0,Q.jsx)(qg,{connection:r,inbox:g,onOpen:Ce,workshopName:I.name}):$e?(0,Q.jsx)(Xg,{connection:r,following:h,onOpen:xe,workshopName:I.name}):et?(0,Q.jsx)(t_,{connection:r,onAuthenticationFailure:he,onChannelAccessFailure:Ve,onReviewPullRequest:()=>on(!0),revision:sn,session:k,workshopName:I.name}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`section`,{className:`conversation-pane`,children:[(0,Q.jsxs)(`header`,{className:`conversation-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`p`,{className:`breadcrumbs`,children:[I.name,` / `,n.kind===`notification`?`Activity`:n.kind===`direct`?`Direct messages`:`Channels`]}),(0,Q.jsxs)(`h2`,{children:[it,` `,rt]})]}),(0,Q.jsxs)(`div`,{className:`conversation-actions`,children:[(0,Q.jsx)(fv,{connection:r}),(0,Q.jsx)(`button`,{className:`quiet-button mobile-settings-button`,type:`button`,onClick:()=>Oe(),children:`Settings`})]})]}),(0,Q.jsxs)(`div`,{ref:Br,className:`timeline-wrap`,"aria-label":`Conversation timeline`,onScroll:Ni,onPointerDown:()=>kt(!0),onKeyDown:()=>kt(!0),tabIndex:0,children:[(0,Q.jsxs)(`div`,{className:`channel-introduction ${n.kind===`notification`?`notification`:``}`,children:[(0,Q.jsx)(`span`,{className:`channel-symbol`,children:it}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:n.kind===`notification`?`Durable notification feed`:n.kind===`direct`?`Direct conversation`:`Canonical conversation`}),(0,Q.jsx)(`h3`,{children:at?`Conversation with ${rt}`:`Welcome to ${rt}`}),(0,Q.jsx)(`p`,{children:Sv(n)?`This channel is archived. Its history remains available, but it is read-only until restored.`:ot?`This direct message is archived for you. Its history remains available, but it is read-only until restored.`:n.kind===`notification`?`Authenticated GitHub activity appears here live and is delivered to every configured client.`:at?`Messages here are private to you and ${rt}.`:`Messages below come from ${rt}’s durable conversation history across every connected client.`}),n.kind===`notification`&&rr&&(0,Q.jsxs)(`p`,{className:`notification-routing-summary`,children:[`Active delivery: `,rr.preferences.map(e=>`${e.displayName} → ${e.destinationName}`).join(` · `)]})]})]}),i.available&&(0,Q.jsxs)(`div`,{className:`timeline-earlier`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`timeline-earlier-button`,onClick:Li,disabled:i.loading,children:i.loading?`Loading earlier messages…`:`Load earlier messages`}),i.error&&(0,Q.jsx)(`p`,{className:`timeline-earlier-error`,children:i.error})]}),T&&(0,Q.jsxs)(`p`,{className:`source-navigation-error`,role:`alert`,children:[T,` You can return to Mentions and update its read state there.`]}),Gr.length===0?(0,Q.jsx)(`p`,{className:`empty-timeline`,children:`No messages yet. New activity will appear here.`}):(0,Q.jsxs)(`ol`,{className:`message-list ${n.kind===`notification`?`notification-feed`:``}`,"aria-live":`polite`,children:[Gr.map(e=>(0,Q.jsxs)(v.Fragment,{children:[b===e.messageId&&(0,Q.jsx)(`li`,{className:`first-unread-divider`,role:`separator`,"aria-label":`First unread message`,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`New messages`})}),(0,Q.jsx)(mv,{hasUnreadReplies:_.byChannel[n.channelId]?.firstUnreadThreadRootId===e.messageId,highlighted:S?.messageId===e.messageId,message:e,notification:n.kind===`notification`,onDownloadArtifact:W,onLoadArtifact:se,onLoadReactors:Y,onMessageVisible:Kr,onSetReaction:st?void 0:Pe,onOpenThread:(n.kind===`group`||at)&&!st?wr:void 0})]},e.messageId)),n.kind!==`notification`&&!at&&[...M].sort((e,t)=>e.sequence-t.sequence||e.runId.localeCompare(t.runId)).map(e=>{let t=n.agents.find(t=>t.agentId===e.agentId)?.name??`Agent`;return(0,Q.jsxs)(`li`,{className:`message-row agent run-preview`,children:[(0,Q.jsx)(`span`,{className:`message-avatar`,"aria-hidden":`true`,children:t.slice(0,1).toUpperCase()}),(0,Q.jsxs)(`article`,{children:[(0,Q.jsxs)(`header`,{className:`message-meta`,children:[(0,Q.jsx)(`strong`,{children:t}),(0,Q.jsx)(`span`,{className:`run-preview-label`,children:`writing`})]}),(0,Q.jsx)(Nm,{body:e.text})]})]},e.runId)})]}),a.available&&(0,Q.jsxs)(`div`,{className:`timeline-later`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`timeline-earlier-button`,onClick:ae,disabled:a.loading,children:a.loading?`Loading newer messages…`:`Load newer messages`}),a.error&&(0,Q.jsx)(`p`,{className:`timeline-earlier-error`,children:a.error})]})]}),(0,Q.jsxs)(`footer`,{className:`composer-preview`,children:[(Et||wt>0)&&(0,Q.jsx)(`button`,{className:`new-messages-button`,type:`button`,onClick:Pi,"aria-label":wt>0?void 0:`Jump to latest messages`,children:wt===0?`Jump to latest`:wt===1?`1 new message`:`${wt} new messages`}),n.canSubmitCommands?(0,Q.jsxs)(`form`,{className:`composer-form`,onSubmit:e=>void Ri(e),children:[(0,Q.jsx)(`input`,{ref:Or,className:`artifact-input`,type:`file`,"aria-label":`Attach a file`,onChange:e=>{_t(e.target.files?.[0]??null),dt(null)}}),(0,Q.jsx)(`button`,{className:`attach-button composer-icon-button`,type:`button`,"aria-label":`Attach`,title:`Attach a file`,disabled:mt||Wt.length>0,onClick:()=>Or.current?.click(),children:(0,Q.jsx)(Fv,{})}),(0,Q.jsx)(`textarea`,{ref:Er,"aria-label":`Message ${rt}`,disabled:mt||Wt.length>0,value:ct,onChange:e=>{let t=e.target.value;lt(t),rv(Z,t),bi(t,e.target.selectionStart??t.length),mt||dt(null)},onKeyDown:e=>{if(e.key===`/`&&ct.length===0&>===null&&!e.metaKey&&!e.ctrlKey&&!e.altKey){e.preventDefault(),rn(!0);return}if($n&&Zr.length>0){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let t=e.key===`ArrowDown`?1:-1;nr(e=>(e+t+Zr.length)%Zr.length);return}if(e.key===`Escape`){e.preventDefault(),er(null);return}if(e.key===`Tab`||e.key===`Enter`&&!e.shiftKey){e.preventDefault(),xi(Zr[Math.min(tr,Zr.length-1)]);return}}e.key!==`Enter`||e.shiftKey||e.nativeEvent.isComposing||e.nativeEvent.keyCode===229||(e.preventDefault(),e.currentTarget.form?.requestSubmit())},maxLength:5e4,placeholder:`Message ${rt}…`,rows:1}),$n&&Zr.length>0&&(0,Q.jsx)(`div`,{className:`mention-autocomplete`,role:`listbox`,"aria-label":`Channel members`,children:Zr.map((e,t)=>(0,Q.jsxs)(`button`,{className:t===tr?`selected`:``,type:`button`,role:`option`,"aria-label":`@${e.handle} — ${e.displayName} — ${e.kind}`,"aria-selected":t===tr,onMouseDown:e=>e.preventDefault(),onClick:()=>xi(e),children:[(0,Q.jsxs)(`strong`,{children:[`@`,e.handle]}),(0,Q.jsxs)(`span`,{children:[e.displayName,` · `,e.kind]})]},e.principalId))}),Wt.length>0?(0,Q.jsx)(`button`,{className:`stop-button composer-icon-button`,type:`button`,"aria-busy":Wt.every(e=>vt.has(e.runId)),"aria-label":Wt.length===1?`Stop agent run`:`Stop all agent runs`,title:Wt.length===1?`Stop agent run`:`Stop all agent runs`,disabled:Wt.every(e=>vt.has(e.runId)),onClick:()=>void Vi(),children:(0,Q.jsx)(Lv,{})}):(0,Q.jsx)(`button`,{className:`send-button composer-icon-button`,type:`submit`,"aria-busy":mt,"aria-label":mt?`Sending…`:`Send`,title:mt?`Sending…`:`Send`,disabled:mt||!ct.trim()&&!gt,children:(0,Q.jsx)(Iv,{})})]}):(0,Q.jsx)(`p`,{className:`read-only-channel-notice`,children:n.kind===`notification`?`This channel is outbound-only. Kai records delivery here, but it does not accept conversation commands.`:ot?`This direct message is archived for you. Restore it to send messages.`:n.kind===`direct`&&n.agents.some(e=>e.lifecycleState===`archived`)?`This agent has been archived. This conversation is read-only.`:`Sending messages from Workshop is not available for this conversation yet.`}),ft&&(0,Q.jsx)(`p`,{className:`composer-error`,role:`alert`,children:ft}),gt&&(0,Q.jsxs)(`div`,{className:`selected-artifact`,children:[(0,Q.jsx)(`span`,{children:gt.name}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>{_t(null),dt(null),Or.current&&(Or.current.value=``)},children:`Remove`})]})]})]}),(0,Q.jsxs)(`aside`,{className:`context-pane`,"aria-label":`Channel context`,children:[(0,Q.jsx)(`div`,{className:`context-resize-handle`,role:`separator`,"aria-label":`Resize channel context`,"aria-orientation":`vertical`,"aria-valuemin":V_,"aria-valuemax":U_,"aria-valuenow":Pt,tabIndex:0,onKeyDown:Mi,onPointerDown:Ai,onPointerMove:ji}),Wr?(0,Q.jsx)(ry,{activeStandingAgentIds:(or?.subscriptions??[]).filter(e=>e.lifecycleState===`active`).map(e=>e.agentId),channelName:rt,liveMessages:s,focusedMessage:S,onClose:()=>wr(null),onDownloadArtifact:W,onLoadArtifact:se,onLoadThread:de,onLoadThreadUnread:J,onLoadReactors:Y,onMessageVisible:Nr,onAdvanceThreadRead:fe,onSetThreadFollowed:pe,onSuppressStanding:(e,t)=>oi(e,t),onSetReaction:Pe,onSubmitCommand:Fe,reactionUpdates:F,principalEvents:y,readOnly:st,rootMessage:Wr,runActive:Wt.length>0}):(0,Q.jsxs)(`div`,{className:`context-scroll`,children:[(0,Q.jsx)(`header`,{className:`context-channel-header`,children:(0,Q.jsxs)(`div`,{className:`context-channel-heading`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Channel context`}),(0,Q.jsxs)(`div`,{className:`context-channel-title-row`,children:[(0,Q.jsxs)(`h2`,{children:[it,` `,rt]}),n.kind===`group`&&(!Sv(n)||n.role===`owner`)&&(0,Q.jsxs)(`div`,{className:`context-channel-actions`,children:[!Sv(n)&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Channel settings`,title:`Channel settings`,onClick:()=>En(!0),children:(0,Q.jsx)(Uv,{})}),n.role===`owner`&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":Sv(n)?`Restore channel`:`Archive channel`,title:Sv(n)?`Restore channel`:`Archive channel`,disabled:kn!==null||Wt.length>0,onClick:()=>void(Sv(n)?gi(Z):hi()),children:Sv(n)?(0,Q.jsx)(Kv,{}):(0,Q.jsx)(Gv,{})})]}),n.kind===`direct`&&!n.agents.some(e=>e.lifecycleState===`archived`)&&(0,Q.jsx)(`div`,{className:`context-channel-actions`,children:(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":ot?`Restore direct message`:`Archive direct message`,title:ot?`Restore direct message`:`Archive direct message`,disabled:jn!==null||Wt.length>0,onClick:()=>void(ot?vi(Z):_i()),children:ot?(0,Q.jsx)(Kv,{}):(0,Q.jsx)(Gv,{})})})]})]})}),Sv(n)&&(0,Q.jsx)(Zv,{className:`archived-channel-state`,title:`Archived`,children:(0,Q.jsx)(`p`,{children:`This channel is preserved and read-only. Restore it to resume activity.`})}),ot&&(0,Q.jsx)(Zv,{className:`archived-channel-state`,title:`Archived for you`,children:(0,Q.jsx)(`p`,{children:`This conversation is preserved and hidden from your normal list. Restore it to send messages.`})}),(n.kind===`group`||at)&&(0,Q.jsx)(Zv,{action:n.kind===`group`&&(n.role===`owner`||I.role===`admin`)&&!Sv(n)?(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Manage channel members`,title:`Manage channel members`,disabled:Gn,onClick:()=>void fi(),children:(0,Q.jsx)(Wv,{})}):void 0,className:`agent-attention-section`,title:`People`,children:(0,Q.jsxs)(`ul`,{children:[(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(Kh,{avatar:A.principal.avatar??N_,className:`context-person-avatar`,displayName:A.principal.displayName,principalId:A.principal.principalId}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:A.principal.displayName}),(0,Q.jsxs)(`small`,{children:[A.principal.handle?`@${A.principal.handle}`:``,!at&&` · ${n.role}`]})]})]}),n.participants.filter(e=>e.kind===`human`).map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(Kh,{avatar:e.avatar??N_,className:`context-person-avatar`,displayName:e.displayName,principalId:e.principalId}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.displayName}),e.handle&&(0,Q.jsxs)(`small`,{children:[`@`,e.handle,!at&&` · participant`]})]})]},e.principalId))]})}),n.kind===`group`&&(0,Q.jsxs)(Zv,{action:n.role===`owner`&&!Sv(n)?(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Manage channel agents`,title:`Manage channel agents`,disabled:Vn,onClick:()=>void di(),children:(0,Q.jsx)(Uv,{})}):void 0,className:`agent-attention-section`,title:`Agents`,children:[br&&(0,Q.jsx)(`p`,{className:`standing-notice`,role:`status`,children:br}),n.agents.length===0&&(0,Q.jsx)(`p`,{children:`No agents are attached.`}),(0,Q.jsx)(`ul`,{children:n.agents.map(e=>{let t=ai.some(t=>t.agentId===e.agentId),n=or?.subscriptions.find(t=>t.agentId===e.agentId),r=or?.observations.find(t=>t.agentId===e.agentId&&t.lifecycleState===`paused_overflow`),i=n?.lifecycleState===`active`;return(0,Q.jsxs)(`li`,{children:[i&&(0,Q.jsx)(`span`,{className:`standing-agent-mark`,title:`Standing participant`,children:(0,Q.jsx)(ty,{})}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.name}),(0,Q.jsx)(`small`,{children:i?`Joined in ${cv(n.startedAt)} · standing`:n?.lifecycleState===`ended`?`Standing ended${n.endReason?` · ${n.endReason.replaceAll(`_`,` `)}`:``}`:e.available?t?`Awake in this channel`:`Available · not standing`:`Unavailable until its sponsor re-enables this runtime`}),r&&(0,Q.jsxs)(`small`,{className:`standing-overflow`,children:[`Observation paused · `,r.pendingMessageCount,` pending`]}),(0,Q.jsxs)(`small`,{children:[`Sponsored by `,e.sponsorDisplayName??`unknown`,` · shared-channel memory`]})]}),r?(0,Q.jsx)(`button`,{className:`panel-icon-button standing-agent-action`,type:`button`,"aria-label":`Resume ${e.name}'s standing observation`,title:`Resume ${e.name}'s standing observation`,disabled:gr!==null,onClick:()=>void ci(e.agentId,r),children:(0,Q.jsx)(Kv,{})}):(i||t)&&(0,Q.jsx)(`button`,{className:`panel-icon-button standing-agent-action`,type:`button`,"aria-label":i?`Dismiss ${e.name} from standing participation`:`Dismiss ${e.name}`,title:i?`Dismiss standing participant`:`Dismiss agent attention`,disabled:Yn===e.agentId,onClick:()=>void oi(e.agentId),children:(0,Q.jsx)(ny,{})})]},e.agentId)})}),ur&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:ur})]}),(0,Q.jsx)(Zv,{title:`Authority`,children:(0,Q.jsx)(`p`,{children:at?`Only you and ${rt} can read and send messages here.`:n.canSubmitCommands?`You can read and send messages in this channel. Mention an agent to direct a request to it.`:`You can read this outbound channel, but you cannot send messages here.`})}),!at&&(0,Q.jsxs)(Zv,{className:`trace-section`,revealKey:hn.key,revealReady:hn.agentId===null||Bt.some(e=>e.agentId===hn.agentId),revealTargetId:hn.agentId?`runtime-status-${hn.agentId}`:null,title:`Runtime`,children:[Bt.length>0?(0,Q.jsx)(`div`,{className:`runtime-lane-statuses`,children:Bt.map(e=>{let t=e.activeRun??e.lastRun;return(0,Q.jsxs)(`div`,{className:`runtime-settings`,id:`runtime-status-${e.agentId}`,tabIndex:-1,children:[(0,Q.jsxs)(`div`,{className:`runtime-lane-heading`,children:[(0,Q.jsx)(`p`,{className:`settings-source`,children:n.kind===`group`?e.agentName:`Agent runtime`}),(0,Q.jsx)(`button`,{className:`panel-icon-button runtime-fresh-session`,type:`button`,"aria-label":`Start a fresh provider session for ${e.agentName}`,title:`Start fresh provider session`,disabled:qt!==null||e.activeRun!==null,onClick:()=>void Ci(e),children:(0,Q.jsx)(qv,{})})]}),(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`strong`,{children:e.backend}),e.provider?` · ${e.provider}`:``]}),(0,Q.jsxs)(`p`,{children:[`Model: `,(0,Q.jsx)(`code`,{children:e.model.value}),(0,Q.jsx)(`br`,{}),`Timeout: `,e.timeoutSeconds.value,`s`]}),!e.canManageRuntime&&(0,Q.jsxs)(`p`,{className:`settings-source`,children:[`Sponsored by `,e.sponsorDisplayName]}),(0,Q.jsxs)(`p`,{className:`settings-source`,children:[`Session: `,e.providerSessionState.replaceAll(`_`,` `),t?` · Last run: ${t.status}`:` · No runs yet`]})]},e.agentId)})}):Rt?(0,Q.jsx)(`p`,{className:`settings-error`,children:Rt}):n.canSubmitCommands?(0,Q.jsx)(`p`,{children:`Loading runtime status…`}):(0,Q.jsx)(`p`,{children:`No agent runtime is assigned to this channel.`}),Rt&&Bt.length>0&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:Rt}),Yt&&(0,Q.jsx)(`p`,{className:`settings-success`,role:`status`,children:Yt})]}),!at&&(0,Q.jsxs)(Zv,{className:`trace-section`,title:`Workspace`,children:[Bt.length>0?(0,Q.jsx)(`div`,{className:`runtime-lane-statuses`,children:Bt.map(e=>(0,Q.jsx)(`div`,{className:`runtime-settings`,children:e.workspaceMode===`neutral`?(0,Q.jsx)(`p`,{className:`settings-source`,children:`No shared workspace`}):(0,Q.jsxs)(`div`,{className:`runtime-workspace-select`,children:[(0,Q.jsx)(`select`,{"aria-label":`Your workspace`,value:e.workspace??``,disabled:Qt||Wt.length>0,onChange:e=>void Si(e.target.value),children:e.workspaces.map(e=>(0,Q.jsx)(`option`,{value:e.path,children:e.name},e.path))}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(Bv,{})})]})},e.agentId))}):Rt?(0,Q.jsx)(`p`,{className:`settings-error`,children:Rt}):n.canSubmitCommands?(0,Q.jsx)(`p`,{children:`Loading workspace status…`}):(0,Q.jsx)(`p`,{children:`No agent workspace is assigned to this channel.`}),Rt&&Bt.length>0&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:Rt})]}),!at&&(0,Q.jsxs)(Zv,{className:`trace-section`,title:`Inspector`,children:[Bt.some(e=>e.operatorDiagnostics)&&(0,Q.jsxs)(`div`,{className:`runtime-lane-diagnostics`,children:[(0,Q.jsx)(`h3`,{children:`Runtime diagnostics`}),Bt.map(e=>e.operatorDiagnostics&&(0,Q.jsxs)(`dl`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Agent`}),(0,Q.jsx)(`dd`,{children:e.agentName})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Process`}),(0,Q.jsx)(`dd`,{children:e.processState})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Continuity`}),(0,Q.jsx)(`dd`,{children:e.continuityState.replaceAll(`_`,` `)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Profile`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:e.operatorDiagnostics.runtimeProfileId})})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Context boundary`}),(0,Q.jsx)(`dd`,{children:e.operatorDiagnostics.contextThroughEventPosition??`none`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Session updated`}),(0,Q.jsx)(`dd`,{children:e.sessionUpdatedAt?cv(e.sessionUpdatedAt):`not started`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Provider session revision`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:e.operatorDiagnostics.providerSessionRevision??`none`})})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Fresh-session revision`}),(0,Q.jsxs)(`dd`,{children:[(0,Q.jsx)(`code`,{children:e.freshSessionRevision??`none`}),e.freshSessionGeneration===null?``:` · generation ${e.freshSessionGeneration}`]})]})]},e.agentId))]}),or&&(0,Q.jsxs)(`details`,{className:`standing-run-inspector`,children:[(0,Q.jsxs)(`summary`,{children:[`Standing observations (`,or.recentRuns.length,`)`]}),or.canInspectSilent&&(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:vr,onChange:e=>yr(e.target.checked)}),`Show authorized silent observations`]}),or.recentRuns.length===0?(0,Q.jsx)(`p`,{children:`No visible standing observations.`}):(0,Q.jsx)(`ol`,{children:or.recentRuns.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`strong`,{children:[e.agentDisplayName,` · `,e.outcome??e.status]}),(0,Q.jsxs)(`small`,{children:[e.scopeKind,` · messages `,e.observedFromEventPosition,`–`,e.observedThroughEventPosition,` · batch `,e.observedMessageCount]}),(0,Q.jsxs)(`small`,{children:[`Anchor `,e.humanAnchorMessageId]}),(0,Q.jsxs)(`small`,{children:[`Grant `,e.collaborationGrantId??`none`,` · `,or.policy.maxObserveRunsPerHour,` observations/hour · `,or.policy.maxUnsolicitedMessagesPerHour,` contributions/hour`]}),(0,Q.jsx)(`code`,{title:e.runId,children:e.runId})]},e.runId))})]}),(0,Q.jsx)(Di,{collaborationActivity:ti,entries:ni,failed:ri,loaded:ii,runId:ei}),(0,Q.jsxs)(`details`,{className:`context-stack-panel`,children:[(0,Q.jsx)(`summary`,{children:`Context stack`}),(0,Q.jsx)(Fi,{session:{channelId:Z,token:d},runId:ei,onNavigate:e=>{e.inspection.editTargetId&&(e.inspection.editTarget===`agent_definition`||e.inspection.editTarget===`workspace_policy`)&&je(e.inspection.editTargetId,e.inspection.editTarget===`workspace_policy`?`runtime`:null)}})]})]})]}),Gt.length>0&&!at&&(0,Q.jsxs)(`section`,{className:`agent-activity-dock`,"aria-label":`Agent activity`,"aria-live":`polite`,children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsx)(`h2`,{children:`Agent activity`}),(0,Q.jsx)(`span`,{children:Gt.length})]}),(0,Q.jsx)(`ol`,{children:Gt.map(e=>{let t=n.agents.find(t=>t.agentId===e.agentId)?.name??`Agent`,r=vt.has(e.runId);return(0,Q.jsxs)(`li`,{className:`agent-activity-row ${e.status}`,children:[(0,Q.jsx)(`span`,{className:`agent-activity-avatar`,"aria-hidden":`true`,children:t.slice(0,1).toUpperCase()}),(0,Q.jsxs)(`span`,{className:`agent-activity-description`,children:[(0,Q.jsx)(`strong`,{children:t}),(0,Q.jsx)(`small`,{children:uv(e)})]}),(0,Q.jsxs)(`span`,{className:`agent-activity-state`,children:[(0,Q.jsx)(`strong`,{children:e.status}),(0,Q.jsx)(`small`,{children:lv(e,St)})]}),ov(e)&&e.kind===`respond`&&(0,Q.jsx)(`button`,{className:`panel-icon-button agent-activity-stop`,type:`button`,"aria-label":`Stop ${t}`,title:`Stop ${t}`,disabled:r,onClick:()=>void Bi(e),children:(0,Q.jsx)(Lv,{})})]},e.runId)})})]})]}),Tn&&n.kind===`group`&&(0,Q.jsx)(jv,{busy:fr,channelName:rt,error:mr??(or?null:ur),loading:cr,onClose:()=>En(!1),onStandingChange:si,participation:or}),yn&&(0,Q.jsx)(Mv,{channels:I.channels.filter(e=>e.kind===`group`&&Sv(e)),busyChannelId:kn,onClose:()=>bn(!1),onRestore:gi,onView:e=>{bn(!1),Ne(e)}}),xn&&(0,Q.jsx)(Nv,{channels:I.channels.filter(e=>Cv(e)&&!e.agents.some(e=>e.lifecycleState===`archived`)),busyChannelId:jn,onClose:()=>Sn(!1),onRestore:vi,onView:e=>{Sn(!1),Ne(e)}}),zn&&(0,Q.jsx)(kv,{attachedAgents:n.agents,enablements:zn,onCancel:()=>Bn(null),onSave:mi}),Un&&(0,Q.jsx)(Av,{membership:Un,onCancel:()=>Wn(null),onChange:pi})]}),Cn&&(0,Q.jsx)(Pv,{agents:Yr,onClose:()=>wn(!1),onOpenConversation:e=>{wn(!1),De(e)},onContinue:(e,t)=>{wn(!1),Ee(e,t)},onView:e=>{wn(!1),Te(e)}}),_n&&(0,Q.jsx)(Dv,{agents:qr,initialAgentIds:_n.initialAgentIds,originChannelId:_n.originChannelId,originName:_n.originName,onCancel:()=>vn(null),onCreate:async e=>{await U(e),vn(null)}}),Dn&&(0,Q.jsx)(Ov,{onCancel:()=>On(!1),onLoad:le,onOpen:async e=>{await Ie(e),On(!1)}}),nn&&(0,Q.jsx)(g_,{actions:pn,error:dn,loading:ln,onClose:()=>rn(!1),onInvoke:wi}),an&&(0,Q.jsx)(yg,{onAuthenticationFailure:he,onChannelAccessFailure:Ve,onClose:()=>on(!1),onSubmitted:()=>{cn(e=>e+1),be()},session:k})]})}function ay(e,t){for(let n of e.workshops){let e=n.channels.find(e=>e.channelId===t);if(e)return{channel:e,workshop:n}}return null}function oy(e,t){if(t){let n=ay(e,t);if(n)return n}for(let t of e.workshops){let e=t.channels.find(e=>e.canSubmitCommands);if(e)return{channel:e,workshop:t}}for(let t of e.workshops)if(t.channels[0])return{channel:t.channels[0],workshop:t};return null}function sy({destination:e,navigation:t,session:n,readActivationChannelId:r,onAuthenticationFailure:i,onArchiveChannel:a,onArchiveDirectMessage:o,onChannelAccessFailure:s,onCreateChannel:c,onStartHumanConversation:l,onForget:u,onAgentNavigationChanged:d,onCreateAgent:f,onOpenAgentDefinition:p,onOpenAgentSetup:m,onOpenAgentChannel:h,onOpenWorkspaces:g,onOpenScheduledJobs:_,onOpenMemory:y,onOpenMentions:b,onOpenFollowing:x,onOpenReviews:S,onOpenFollowedThread:C,onOpenHumanNotification:w,onOpenSettings:T,onRestoreChannel:E,onRestoreDirectMessage:D,onSelectChannel:O,onSelectAgent:k,onSelectMemory:A,onSettingsDirtyChange:j}){let M=ay(t,n.channelId),N=t.workshops.flatMap(e=>e.channels),P=(e.kind===`settings`&&e.runtimeChannelId?N.find(t=>t.channelId===e.runtimeChannelId&&t.kind===`direct`&&t.agents.length>0&&t.canSubmitCommands):void 0)??N.find(e=>e.kind===`direct`&&e.agents.length>0&&e.canSubmitCommands)??N.find(e=>e.canSubmitCommands)??M?.channel,F=(0,v.useMemo)(()=>({channelId:P?.channelId??n.channelId,token:n.token}),[n.channelId,n.token,P?.channelId]),I=h_(n.token,i),L=I.subscribe,R=o_(n.token,I,i),ee=c_(n.token,I,i),z=f_(n.token,I,i,s);(0,v.useEffect)(()=>L(e=>{(e.kind===`synchronize`||e.batch.changes.some(e=>e.agentChanges.length>0))&&d().catch(()=>void 0)}),[d,L]);let[H,te]=(0,v.useState)(null);(0,v.useEffect)(()=>{if(e.kind!==`conversation`){te(null);return}z.loading||H?.channelId===n.channelId||te({channelId:n.channelId,messageId:z.byChannel[n.channelId]?.firstUnreadMessageId??null})},[e.kind,n.channelId,H?.channelId,z.byChannel,z.loading]);let U=e.kind!==`conversation`||H?.channelId===n.channelId,[ne,re]=(0,v.useState)(null),[W,ie]=(0,v.useState)(null),[ae,oe]=(0,v.useState)(null),{connection:se,messages:ce,threadMessages:le,reactionUpdates:ue,runActivities:G,runPreviews:K,runTrace:q,standingParticipationVersion:de,earlier:J,later:Y,loadEarlier:fe,loadLater:pe,jumpLatest:me,updateReactions:he}=Hi(n,M!==null&&e.kind!==`agents`&&U,H?.channelId===n.channelId?H.messageId:null,i,s);(0,v.useEffect)(()=>{if(e.kind!==`conversation`||!e.messageId){re(null),ie(null),oe(null);return}let t=new AbortController,r=e.messageId;return re(null),ie(null),oe(null),(async()=>{try{let e=await di(n,r,t.signal),i=e.threadRootId?await di(n,e.threadRootId,t.signal):e;t.signal.aborted||(re(e),ie(i))}catch(e){if(t.signal.aborted)return;if(e instanceof B){i(e.message);return}oe(e instanceof Error?e.message:`This mention's source message is no longer accessible.`)}})(),()=>t.abort()},[e,i,n]);let X=(0,v.useCallback)(async e=>{try{return await e()}catch(e){throw e instanceof B?i(e.message):e instanceof V&&s(e.message),e}},[i,s]),ge=(0,v.useCallback)(()=>{if(!M)throw Error(`Workshop access changed.`);return X(()=>st(n.token,M.workshop.workshopId))},[M,n.token,X]),_e=(0,v.useCallback)(e=>{if(!M)throw Error(`Workshop access changed.`);return l(M.workshop.workshopId,e)},[l,M]),ve=(0,v.useCallback)(e=>X(()=>zr(n,e)),[n,X]),ye=(0,v.useCallback)((e,t)=>X(()=>Hr(n,e,t)),[n,X]),be=(0,v.useCallback)(e=>X(()=>Gr(n,e)),[n,X]),xe=(0,v.useCallback)((e,t,r,i)=>X(()=>Lr(n,e,t,r,i)),[n,X]),Se=(0,v.useCallback)((e,t,r)=>X(()=>hi(n,e,t,r)),[n,X]),Ce=(0,v.useCallback)((e,t)=>X(()=>ai(n,e,t)),[n,X]),we=(0,v.useCallback)((e,t,r,i)=>X(()=>ci(n,e,t,r,i)),[n,X]),Te=(0,v.useCallback)((e,t,r,i)=>X(()=>si(n,e,t,r,i)),[n,X]),Ee=(0,v.useCallback)(e=>X(()=>Rr(n,e)),[n,X]),De=(0,v.useCallback)(e=>Pm(n,e),[n]),Oe=(0,v.useCallback)(async e=>{try{return await Un(n,e)}catch(e){throw e instanceof B&&i(e.message),e}},[i,n]),ke=(0,v.useCallback)((e,t)=>X(()=>Wn(n,e,t)),[n,X]),Ae=(0,v.useCallback)((e,t)=>X(()=>jr(n,e,t)),[n,X]),je=(0,v.useCallback)((e,t,r=null)=>X(()=>xt(n,e,t,r)),[n,X]),Me=(0,v.useCallback)((e,t)=>X(()=>yt(n,e,t)),[n,X]),Ne=(0,v.useCallback)((e,t)=>X(()=>bt(n,e,t)),[n,X]),Pe=(0,v.useCallback)(()=>X(()=>gt(n)),[n,X]),Fe=(0,v.useCallback)((e,t,r,i)=>X(()=>_t(n,e,t,r,i)),[n,X]),Ie=(0,v.useCallback)((e,t,r)=>X(async()=>{let i=await St(n,e,t,r);he(e,i)}),[n,he,X]),Le=(0,v.useCallback)((e,t)=>X(()=>Ct(n,e,t)),[n,X]);return M?(0,Q.jsx)(iy,{agentDestination:e.kind===`agents`?e:null,agentToken:n.token,channel:M.channel,connection:se,earlier:J,later:Y,messages:ce,threadMessages:le,workspacesDestination:e.kind===`workspaces`,scheduledJobsDestination:e.kind===`scheduled-jobs`,memoryDestination:e.kind===`memory`?e:null,mentionsDestination:e.kind===`mentions`,followingDestination:e.kind===`following`,reviewsDestination:e.kind===`reviews`,following:ee,inbox:R,unread:z,principalEvents:I,unreadBoundaryMessageId:H?.channelId===n.channelId?H.messageId:null,readActivatedInitially:r===n.channelId,focusedMessage:ne,focusedThreadRoot:W,requestedThreadRootId:e.kind===`conversation`?e.threadRootId??null:null,focusedMessageError:ae,memoryToken:n.token,settingsDestination:e.kind===`settings`,settingsInitialSection:e.kind===`settings`?e.section:null,settingsRuntimeLabel:P?vv(P):`assigned runtime`,settingsSession:F,navigation:t,onLoadEarlier:fe,onLoadLater:pe,onJumpLatest:me,onDownloadArtifact:De,onLoadArtifact:Ee,onLoadChannelMembers:Pe,onLoadHumanPeers:ge,runActivities:G,runPreviews:K,runTrace:q,standingParticipationVersion:de,reactionUpdates:ue,workshop:M.workshop,onForget:u,onAgentNavigationChanged:d,onArchiveChannel:a,onArchiveDirectMessage:o,onAttachAgent:Me,onCreateAgent:f,onCancelRun:be,onCreateChannel:c,onDismissAgent:je,onDetachAgent:Ne,onLoadRun:ve,onLoadRunTrace:ye,onLoadRuntimeLaneStatus:Oe,onStartFreshProviderSession:ke,onLoadThread:Se,onLoadThreadUnread:Ce,onAdvanceThreadRead:we,onSetThreadFollowed:Te,onChangeChannelMember:Fe,onMemoryAuthenticationFailure:i,onOpenAgentChannel:h,onOpenAgentDefinition:p,onOpenAgentSetup:m,onOpenWorkspaces:g,onOpenScheduledJobs:_,onOpenMemory:y,onOpenMentions:b,onOpenFollowing:x,onOpenReviews:S,onOpenFollowedThread:C,onOpenHumanNotification:w,onOpenSettings:T,onRestoreChannel:E,onRestoreDirectMessage:D,onSelectMemory:A,onSelectAgent:k,onSelectChannel:O,onSetReaction:Ie,onLoadReactors:Le,onSubmitCommand:xe,onStartHumanConversation:_e,onSwitchWorkspace:Ae,onSettingsAccessFailure:s,onSettingsDirtyChange:j}):(0,Q.jsx)(`main`,{className:`loading-workshop`,children:`Workshop access changed.`})}function cy(){let e=Km(),[t,n]=(0,v.useState)(()=>X_()),[r,i]=(0,v.useState)(null),[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(()=>t?`workshop`:`enrollment`),[l,u]=(0,v.useState)(null),[d,f]=(0,v.useState)(F_),[p,m]=(0,v.useState)(!1),[h,g]=(0,v.useState)(null);(0,v.useEffect)(()=>{let e=e=>{if(e.storageArea!==localStorage||e.key!==__)return;let r=J_(e.newValue);if(!r){Q_(),z(),n(null),i(null),o(null),u(`Workshop session was forgotten in another tab.`),c(`enrollment`),m(!1),g(null);return}r!==t?.token&&(n({channelId:Y_(),token:r}),i(null),o(null),u(null),c(`workshop`),m(!1),g(null))};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[t?.token]),(0,v.useEffect)(()=>{let t=async()=>{let t=F_();if(d.kind===`settings`&&t.kind!==`settings`&&p&&!await e(`Discard unsaved preference changes?`)){I_(d,`push`);return}f(t)},n=()=>{t()};return window.addEventListener(`popstate`,n),()=>window.removeEventListener(`popstate`,n)},[e,d,p]);let _=(0,v.useCallback)((e=null)=>{$_(),z(),n(null),i(null),o(null),u(e),c(`enrollment`),m(!1),g(null)},[]),y=(0,v.useCallback)(e=>_(e),[_]),b=(0,v.useCallback)((e,t,r,a)=>{let s=oy(t,r);if(!s)throw Error(`This Workshop account has no accessible channels.`);let l={channelId:s.channel.channelId,token:e};Z_(l),n({channelId:l.channelId,token:e}),i(l),o(t),R(a.themeId),u(null),c(`workshop`)},[]);(0,v.useEffect)(()=>{if(s!==`workshop`||!t||a)return;let e=!1;return Promise.all([xe(t.token),lr({token:t.token})]).then(([n,r])=>{e||b(t.token,n,t.channelId,r)}).catch(t=>{if(!e){if(t instanceof B){_(t.message);return}u(t instanceof Error?t.message:`Could not load Workshop navigation.`),c(`enrollment`)}}),()=>{e=!0}},[t,b,_,a,s]);let x=async({deviceDisplayName:e,enrollmentToken:n})=>{let r=t?.token??await be(n,e),[i,a]=await Promise.all([xe(r),lr({token:r})]);b(r,i,t?.channelId??null,a)},S=(0,v.useCallback)(async e=>{if(r)try{let[e,t]=await Promise.all([xe(r.token),lr({token:r.token})]);b(r.token,e,r.channelId,t)}catch(t){if(t instanceof B){_(t.message);return}u(t instanceof Error?t.message:e),o(null),c(`enrollment`)}},[b,_,r]),C=(0,v.useCallback)(e=>{S(e)},[S]),w=async t=>{if(!r||!a||!ay(a,t)||d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let n={...r,channelId:t};g(t),Z_(n),i(n);let o={kind:`conversation`};f(o),I_(o,`push`)},T=async()=>{if(d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let t={kind:`workspaces`};f(t),I_(t,`push`)},E=async()=>{if(d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let t={kind:`scheduled-jobs`};f(t),I_(t,`push`)},D=async()=>{if(d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let t={kind:`memory`,memoryId:null};f(t),I_(t,`push`)},O=async()=>{if(d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let t={kind:`mentions`};f(t),I_(t,`push`)},k=async()=>{if(d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let t={kind:`following`};f(t),I_(t,`push`)},A=async()=>{if(d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let t={kind:`reviews`};f(t),I_(t,`push`)},j=e=>{let t=e.state.channelId;if(!r||!a||!ay(a,t))return!1;let n={...r,channelId:t};g(null),Z_(n),i(n);let o={kind:`conversation`,messageId:e.state.firstUnreadMessageId??e.latestReplyMessageId??e.state.threadRootId,threadRootId:e.state.threadRootId};return f(o),I_(o,`push`),!0},M=e=>{if(!r||!a||!ay(a,e.sourceChannelId))return!1;let t={...r,channelId:e.sourceChannelId};g(e.sourceChannelId),Z_(t),i(t);let n={kind:`conversation`,messageId:e.sourceMessageId,threadRootId:e.sourceThreadRootId};return f(n),I_(n,`push`),!0},N=async(t=null,n=!1,r=null,i=null)=>{if(d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let a={creating:n,definitionId:t,kind:`agents`,section:r,setupId:i};f(a),I_(a,`push`)},P=(e=null)=>{let t={kind:`settings`,runtimeChannelId:null,section:e};f(t),I_(t,`push`)},F=(0,v.useCallback)(e=>{let t={kind:`memory`,memoryId:e};f(t),I_(t,`replace`)},[]),I=(0,v.useCallback)((e,t=null)=>{let n={creating:!1,definitionId:e,kind:`agents`,section:t,setupId:null};f(n),I_(n,`replace`)},[]),L=async e=>{await N(e)},ee=async(e,t)=>{await N(e,!0,null,t)},H=(0,v.useCallback)(async()=>{if(r)try{let e=await xe(r.token),t=ay(e,r.channelId),a=t??oy(e,null);if(!a)throw Error(`This Workshop account has no accessible channels.`);if(!t){let e={...r,channelId:a.channel.channelId};Z_(e),n({channelId:e.channelId,token:e.token}),i(e)}o(e)}catch(e){if(e instanceof B)_(e.message);else throw e}},[_,r]),te=(0,v.useCallback)(async e=>{if(!r)throw Error(`Workshop is not connected.`);try{let t=await xe(r.token);if(!ay(t,e))throw new V(`This session cannot access that agent conversation.`);let a={...r,channelId:e};g(e),Z_(a),n({channelId:e,token:r.token}),i(a),o(t);let s={kind:`conversation`};f(s),I_(s,`push`)}catch(e){throw e instanceof B?_(e.message):e instanceof V&&C(e.message),e}},[_,C,r]),U=async e=>{if(!r)throw Error(`Workshop is not connected.`);try{let t=await at(r.token,e),[n,i]=await Promise.all([xe(r.token),lr({token:r.token})]);b(r.token,n,t,i),g(t);let a={kind:`conversation`};f(a),I_(a,`push`)}catch(e){throw e instanceof B?y(e.message):e instanceof V&&C(e.message),e}},ne=async(e,t)=>{if(!r)throw Error(`Workshop is not connected.`);try{let n=await ct(r.token,e,t),[i,a]=await Promise.all([xe(r.token),lr({token:r.token})]);b(r.token,i,n.channelId,a),g(n.channelId);let o={kind:`conversation`};f(o),I_(o,`push`)}catch(e){throw e instanceof B?y(e.message):e instanceof V&&C(e.message),e}},re=async(e,t,n)=>{if(!r)throw Error(`Workshop is not connected.`);try{n===`archive`?await ut(r.token,e,t):await dt(r.token,e,t);let[i,a]=await Promise.all([xe(r.token),lr({token:r.token})]);b(r.token,i,n===`restore`?e:r.channelId,a)}catch(e){throw e instanceof B?y(e.message):e instanceof V&&C(e.message),e}},W=async(e,t,n)=>{if(!r)throw Error(`Workshop is not connected.`);try{n===`archive`?await pt(r.token,e,t):await mt(r.token,e,t);let i=await xe(r.token);b(r.token,i,e,await lr({token:r.token}))}catch(e){throw e instanceof B?y(e.message):e instanceof V&&C(e.message),e}};return s===`enrollment`?(0,Q.jsx)(dv,{existingSession:t!==null,notice:l,onForget:()=>_(),onOpen:x},`${t?`correction`:`fresh`}:${l??``}`):!r||!a?(0,Q.jsx)(`main`,{className:`loading-workshop`,children:`Opening Kai Workshop…`}):(0,Q.jsx)(Wh,{token:r.token,children:(0,Q.jsx)(sy,{destination:d,navigation:a,session:r,readActivationChannelId:h,onAuthenticationFailure:y,onArchiveChannel:(e,t)=>re(e,t,`archive`),onArchiveDirectMessage:(e,t)=>W(e,t,`archive`),onChannelAccessFailure:C,onCreateChannel:U,onStartHumanConversation:ne,onForget:()=>_(),onAgentNavigationChanged:H,onCreateAgent:()=>void N(null,!0),onOpenAgentChannel:te,onOpenAgentDefinition:L,onOpenAgentSetup:ee,onOpenWorkspaces:()=>void T(),onOpenScheduledJobs:()=>void E(),onOpenMemory:()=>void D(),onOpenMentions:()=>void O(),onOpenFollowing:()=>void k(),onOpenReviews:()=>void A(),onOpenFollowedThread:j,onOpenHumanNotification:M,onOpenSettings:P,onRestoreChannel:(e,t)=>re(e,t,`restore`),onRestoreDirectMessage:(e,t)=>W(e,t,`restore`),onSelectChannel:w,onSelectAgent:I,onSelectMemory:F,onSettingsDirtyChange:m},r.channelId)})}function ly(){return(0,Q.jsx)(Gm,{children:(0,Q.jsx)(cy,{})})}ee();var uy=document.getElementById(`root`);if(!uy)throw Error(`Kai Workshop root element is unavailable`);(0,y.createRoot)(uy).render((0,Q.jsx)(v.StrictMode,{children:(0,Q.jsx)(ly,{})})); \ No newline at end of file +`))}function c(e,t,n,r){let i=n.enter(`tableCell`),o=n.enter(`phrasing`),s=n.containerPhrasing(e,{...r,before:a,after:a});return o(),i(),s}function l(e,t){return xf(e,{align:t,alignDelimiters:r,padding:n,stringLength:i})}function u(e,t,n){let r=e.children,i=-1,a=[],o=t.enter(`table`);for(;++i0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}var am={tokenize:pm,partial:!0};function om(){return{document:{91:{name:`gfmFootnoteDefinition`,tokenize:um,continuation:{tokenize:dm},exit:fm}},text:{91:{name:`gfmFootnoteCall`,tokenize:lm},93:{name:`gfmPotentialFootnoteCall`,add:`after`,tokenize:sm,resolveTo:cm}}}}function sm(e,t,n){let r=this,i=r.events.length,a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),o;for(;i--;){let e=r.events[i][1];if(e.type===`labelImage`){o=e;break}if(e.type===`gfmFootnoteCall`||e.type===`labelLink`||e.type===`label`||e.type===`image`||e.type===`link`)break}return s;function s(i){if(!o||!o._balanced)return n(i);let s=Fo(r.sliceSerialize({start:o.end,end:r.now()}));return s.codePointAt(0)!==94||!a.includes(s.slice(1))?n(i):(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(i),e.exit(`gfmFootnoteCallLabelMarker`),t(i))}}function cm(e,t){let n=e.length;for(;n--;)if(e[n][1].type===`labelImage`&&e[n][0]===`enter`){e[n][1];break}e[n+1][1].type=`data`,e[n+3][1].type=`gfmFootnoteCallLabelMarker`;let r={type:`gfmFootnoteCall`,start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:`gfmFootnoteCallMarker`,start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;let a={type:`gfmFootnoteCallString`,start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},o={type:`chunkString`,contentType:`string`,start:Object.assign({},a.start),end:Object.assign({},a.end)},s=[e[n+1],e[n+2],[`enter`,r,t],e[n+3],e[n+4],[`enter`,i,t],[`exit`,i,t],[`enter`,a,t],[`enter`,o,t],[`exit`,o,t],[`exit`,a,t],e[e.length-2],e[e.length-1],[`exit`,r,t]];return e.splice(n,e.length-n+1,...s),e}function lm(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a=0,o;return s;function s(t){return e.enter(`gfmFootnoteCall`),e.enter(`gfmFootnoteCallLabelMarker`),e.consume(t),e.exit(`gfmFootnoteCallLabelMarker`),c}function c(t){return t===94?(e.enter(`gfmFootnoteCallMarker`),e.consume(t),e.exit(`gfmFootnoteCallMarker`),e.enter(`gfmFootnoteCallString`),e.enter(`chunkString`).contentType=`string`,l):n(t)}function l(s){if(a>999||s===93&&!o||s===null||s===91||Wo(s))return n(s);if(s===93){e.exit(`chunkString`);let a=e.exit(`gfmFootnoteCallString`);return i.includes(Fo(r.sliceSerialize(a)))?(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(s),e.exit(`gfmFootnoteCallLabelMarker`),e.exit(`gfmFootnoteCall`),t):n(s)}return Wo(s)||(o=!0),a++,e.consume(s),s===92?u:l}function u(t){return t===91||t===92||t===93?(e.consume(t),a++,l):l(t)}}function um(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a,o=0,s;return c;function c(t){return e.enter(`gfmFootnoteDefinition`)._container=!0,e.enter(`gfmFootnoteDefinitionLabel`),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),l}function l(t){return t===94?(e.enter(`gfmFootnoteDefinitionMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionMarker`),e.enter(`gfmFootnoteDefinitionLabelString`),e.enter(`chunkString`).contentType=`string`,u):n(t)}function u(t){if(o>999||t===93&&!s||t===null||t===91||Wo(t))return n(t);if(t===93){e.exit(`chunkString`);let n=e.exit(`gfmFootnoteDefinitionLabelString`);return a=Fo(r.sliceSerialize(n)),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),e.exit(`gfmFootnoteDefinitionLabel`),f}return Wo(t)||(s=!0),o++,e.consume(t),t===92?d:u}function d(t){return t===91||t===92||t===93?(e.consume(t),o++,u):u(t)}function f(t){return t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),i.includes(a)||i.push(a),Xo(e,p,`gfmFootnoteDefinitionWhitespace`)):n(t)}function p(e){return t(e)}}function dm(e,t,n){return e.check(ds,t,e.attempt(am,t,n))}function fm(e){e.exit(`gfmFootnoteDefinition`)}function pm(e,t,n){let r=this;return Xo(e,i,`gfmFootnoteDefinitionIndent`,5);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`gfmFootnoteDefinitionIndent`&&i[2].sliceSerialize(i[1],!0).length===4?t(e):n(e)}}function mm(e){let t=(e||{}).singleTilde,n={name:`strikethrough`,tokenize:i,resolveAll:r};return t??=!0,{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function r(e,t){let n=-1;for(;++n1?r(a):(e.consume(a),o++,c);if(o<2&&!t)return r(a);let l=e.exit(`strikethroughSequenceTemporary`),u=rs(a);return l._open=!u||u===2&&!!s,l._close=!s||s===2&&!!u,n(a)}}}var hm=class{constructor(){this.map=[]}add(e,t,n){gm(this,e,t,n)}consume(e){if(this.map.sort(function(e,t){return e[0]-t[0]}),this.map.length===0)return;let t=this.map.length,n=[];for(;t>0;)--t,n.push(e.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),e.length=this.map[t][0];n.push(e.slice()),e.length=0;let r=n.pop();for(;r;){for(let t of r)e.push(t);r=n.pop()}this.map.length=0}};function gm(e,t,n,r){let i=0;if(n!==0||r.length!==0){for(;i-1;){let e=r.events[t][1].type;if(e===`lineEnding`||e===`linePrefix`)t--;else break}let i=t>-1?r.events[t][1].type:null,a=i===`tableHead`||i===`tableRow`?S:c;return a===S&&r.parser.lazy[r.now().line]?n(e):a(e)}function c(t){return e.enter(`tableHead`),e.enter(`tableRow`),l(t)}function l(e){return e===124?u(e):(o=!0,a+=1,u(e))}function u(t){return t===null?n(t):Uo(t)?a>1?(a=0,r.interrupt=!0,e.exit(`tableRow`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),p):n(t):Go(t)?Xo(e,u,`whitespace`)(t):(a+=1,o&&(o=!1,i+=1),t===124?(e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),o=!0,u):(e.enter(`data`),d(t)))}function d(t){return t===null||t===124||Wo(t)?(e.exit(`data`),u(t)):(e.consume(t),t===92?f:d)}function f(t){return t===92||t===124?(e.consume(t),d):d(t)}function p(t){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(t):(e.enter(`tableDelimiterRow`),o=!1,Go(t)?Xo(e,m,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):m(t))}function m(t){return t===45||t===58?g(t):t===124?(o=!0,e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),h):x(t)}function h(t){return Go(t)?Xo(e,g,`whitespace`)(t):g(t)}function g(t){return t===58?(a+=1,o=!0,e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),_):t===45?(a+=1,_(t)):t===null||Uo(t)?b(t):x(t)}function _(t){return t===45?(e.enter(`tableDelimiterFiller`),v(t)):x(t)}function v(t){return t===45?(e.consume(t),v):t===58?(o=!0,e.exit(`tableDelimiterFiller`),e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),y):(e.exit(`tableDelimiterFiller`),y(t))}function y(t){return Go(t)?Xo(e,b,`whitespace`)(t):b(t)}function b(n){return n===124?m(n):n===null||Uo(n)?!o||i!==a?x(n):(e.exit(`tableDelimiterRow`),e.exit(`tableHead`),t(n)):x(n)}function x(e){return n(e)}function S(t){return e.enter(`tableRow`),C(t)}function C(n){return n===124?(e.enter(`tableCellDivider`),e.consume(n),e.exit(`tableCellDivider`),C):n===null||Uo(n)?(e.exit(`tableRow`),t(n)):Go(n)?Xo(e,C,`whitespace`)(n):(e.enter(`data`),w(n))}function w(t){return t===null||t===124||Wo(t)?(e.exit(`data`),C(t)):(e.consume(t),t===92?T:w)}function T(t){return t===92||t===124?(e.consume(t),w):w(t)}}function bm(e,t){let n=-1,r=!0,i=0,a=[0,0,0,0],o=[0,0,0,0],s=!1,c=0,l,u,d,f=new hm;for(;++nn[2]+1){let t=n[2]+1,r=n[3]-n[2]-1;e.add(t,r,[])}}e.add(n[3]+1,0,[[`exit`,o,t]])}return i!==void 0&&(a.end=Object.assign({},Cm(t.events,i)),e.add(i,0,[[`exit`,a,t]]),a=void 0),a}function Sm(e,t,n,r,i){let a=[],o=Cm(t.events,n);i&&(i.end=Object.assign({},o),a.push([`exit`,i,t])),r.end=Object.assign({},o),a.push([`exit`,r,t]),e.add(n+1,0,a)}function Cm(e,t){let n=e[t],r=n[0]===`enter`?`start`:`end`;return n[1][r]}var wm={name:`tasklistCheck`,tokenize:Em};function Tm(){return{text:{91:wm}}}function Em(e,t,n){let r=this;return i;function i(t){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(t):(e.enter(`taskListCheck`),e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),a)}function a(t){return Wo(t)?(e.enter(`taskListCheckValueUnchecked`),e.consume(t),e.exit(`taskListCheckValueUnchecked`),o):t===88||t===120?(e.enter(`taskListCheckValueChecked`),e.consume(t),e.exit(`taskListCheckValueChecked`),o):n(t)}function o(t){return t===93?(e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),e.exit(`taskListCheck`),s):n(t)}function s(r){return Uo(r)?t(r):Go(r)?e.check({tokenize:Dm},t,n)(r):n(r)}}function Dm(e,t,n){return Xo(e,r,`whitespace`);function r(e){return e===null?n(e):t(e)}}function Om(e){return jo([Wp(),om(),mm(e),vm(),Tm()])}var km={};function Am(e){let t=this,n=e||km,r=t.data(),i=r.micromarkExtensions||=[],a=r.fromMarkdownExtensions||=[],o=r.toMarkdownExtensions||=[];i.push(Om(n)),a.push(Np()),o.push(Pp(n))}function jm(e,t){let n=Array.from(e),r=t.map(e=>({...e,endOffset:n.slice(0,e.start+e.length).join(``).length,startOffset:n.slice(0,e.start).join(``).length}));return()=>t=>{let n=t=>{if(!t.children)return;let i=[];for(let a of t.children){let t=a.position?.start?.offset;if(a.type!==`text`||typeof a.value!=`string`||t===void 0){n(a),i.push(a);continue}let o=t+a.value.length,s=r.filter(n=>n.startOffset>=t&&n.endOffset<=o&&e.slice(n.startOffset,n.endOffset)===a.value?.slice(n.startOffset-t,n.endOffset-t));if(s.length===0){i.push(a);continue}let c=0;for(let e of s){let n=e.startOffset-t;n>c&&i.push({type:`text`,value:a.value.slice(c,n)}),i.push({type:`strong`,data:{hName:`span`,hProperties:{className:[`message-mention`,`message-mention-${e.kind}`],"data-principal-id":e.principalId}},children:[{type:`text`,value:a.value.slice(n,n+(e.endOffset-e.startOffset))}]}),c=n+(e.endOffset-e.startOffset)}ct?(0,Q.jsx)(`a`,{...r,href:t,target:`_blank`,rel:`noopener noreferrer`,children:e}):(0,Q.jsx)(`span`,{className:`markdown-unsafe-link`,children:e}),img:({alt:e})=>(0,Q.jsx)(`span`,{className:`markdown-image-omitted`,children:e?`[Image: ${e}]`:`[Remote image omitted]`})},Nm=(0,v.memo)(function({body:e,mentions:t=[]}){let n=(0,v.useMemo)(()=>jm(e,t),[e,t]);return(0,Q.jsx)(`div`,{className:`markdown-message`,children:(0,Q.jsx)(Td,{components:Mm,remarkPlugins:[Am,n],children:e})})});function Pm(e,t){if(!b.test(e.channelId)||!k.test(t)||!e.token)throw Error(`Invalid artifact download authority.`);let n=document.createElement(`form`);n.action=`/v1/channels/${encodeURIComponent(e.channelId)}/artifacts/${encodeURIComponent(t)}/download`,n.method=`post`,n.target=`_self`,n.hidden=!0;let r=document.createElement(`input`);r.type=`hidden`,r.name=`session_token`,r.value=e.token,n.append(r),document.body.append(n);try{n.submit()}finally{n.remove()}}var Fm=500;function Im(e){switch(e){case`LifecycleProjectionReadError`:return`The search index could not be read`;case`FactLifecycleProjectionFailed`:case`EpisodeHistoryProjectionFailed`:return`The search index refused the write`;default:return e??`Unknown error`}}function Lm(e){if(e.retried===0)return`Nothing needed a retry.`;let t=e.failed>0?` ${e.failed} still failing.`:``;return`Retried ${e.retried}: ${e.succeeded} back in search.${t}`}function Rm(e){let t=new Date(e);return Number.isNaN(t.valueOf())?e:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}function zm(e){return e.kind===`project`&&e.key?`Project ${e.key}`:`Global`}function Bm(e){let t=[e.provider,e.model].filter(e=>!!e);return t.length>0?t.join(` · `):`Operator`}function Vm(e){return e?e.replaceAll(`_`,` `):`unknown`}function Hm(e){return e?e.revisions.filter(e=>e.state===`unresolved_conflict`).sort((e,t)=>e.storedAt.localeCompare(t.storedAt)):[]}function Um({detailPanelLayout:e,onAuthenticationFailure:t,onBack:n,onChanged:r,onOpenMemory:i,token:a}){let[o,s]=(0,v.useState)(`conflicts`),[c,l]=(0,v.useState)([]),[u,d]=(0,v.useState)(0),[f,p]=(0,v.useState)([]),[m,h]=(0,v.useState)(0),[g,_]=(0,v.useState)(null),[y,b]=(0,v.useState)(null),[x,S]=(0,v.useState)(!1),[C,w]=(0,v.useState)(!0),[T,E]=(0,v.useState)(null),[D,O]=(0,v.useState)(0),[k,A]=(0,v.useState)(null),[j,M]=(0,v.useState)(null),[N,P]=(0,v.useState)(null),[F,I]=(0,v.useState)(0),[L,R]=(0,v.useState)(null),[ee,z]=(0,v.useState)(``),[V,H]=(0,v.useState)(!1),[te,U]=(0,v.useState)(null),[ne,re]=(0,v.useState)(null),W=(0,v.useCallback)((e,n)=>(e instanceof B&&t(e.message),e instanceof Error?e.message:n),[t]);(0,v.useEffect)(()=>{let e=!1;return w(!0),E(null),Promise.all([Tn(a),En(a),Mn(a)]).then(([t,n,r])=>{e||(l(t.items),d(t.total),p(n.items),h(n.total),_(r))}).catch(t=>{e||E(W(t,`Could not load fact review.`))}).finally(()=>{e||w(!1)}),()=>{e=!0}},[W,D,a]),(0,v.useEffect)(()=>{if(M(null),P(null),o!==`conflicts`||!k)return;let e=!1;return Dn(a,k).then(t=>{e||M(t)}).catch(t=>{e||P(W(t,`Could not load this conflict.`))}),()=>{e=!0}},[F,W,k,o,a]);let ae=e=>{A(e),R(null),z(``),U(null)},oe=e=>{s(e),A(null),R(null),z(``),U(null)},se=c.find(e=>e.claimId===k)??null,ce=f.find(e=>e.claimId===k)??null,le=g?.failed.find(e=>e.id===k)??null,ue=Hm(j),G=L?.kind===`keep`?ue.find(e=>e.revisionId===L.revisionId)??null:null,K=async()=>{if(!(!L||!k)){H(!0),U(null);try{let e=L.kind===`keep`?await kn(a,k,{keepRevisionId:L.revisionId,expectedRevisionIds:ue.map(e=>e.revisionId),note:ee.trim()}):await An(a,k,{revisionId:ce?.revisionId??``,note:ee.trim()});re({memoryId:e.memoryId,text:L.kind===`keep`?`Kept the selected version. It is back in recall.`:`Restored the fact. It is current from now, with no end date.`}),A(null),R(null),z(``),O(e=>e+1),r()}catch(e){e instanceof ie?(R(null),U(`This conflict changed since you opened it. The latest versions are shown below.`),I(e=>e+1),O(e=>e+1)):U(W(e,`Could not save this decision.`))}finally{H(!1)}}},q=L&&(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-review-decision fact-review-confirmation`,"aria-label":`Confirm decision`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:L.kind===`keep`?`Keep this version`:`Restore this fact`}),(0,Q.jsx)(`p`,{children:L.kind===`keep`?`The kept version becomes the current fact. The other version will be kept in history as superseded.`:`The fact will be current from now, with no end date. Its earlier history stays as it is.`}),G?.admissionAuthority===`quarantined`&&(0,Q.jsx)(`p`,{className:`fact-review-warning`,role:`note`,children:`This version has incomplete provenance. It will stay out of recall until its admission is reviewed.`}),(0,Q.jsxs)(`label`,{children:[`Note (optional)`,(0,Q.jsx)(`textarea`,{value:ee,maxLength:Fm,onChange:e=>z(e.target.value)})]}),(0,Q.jsxs)(`div`,{className:`memory-review-toolbar`,children:[(0,Q.jsx)(`button`,{type:`button`,disabled:V,onClick:()=>void K(),children:V?`Saving…`:L.kind===`keep`?`Keep this version`:`Restore`}),(0,Q.jsx)(`button`,{type:`button`,disabled:V,onClick:()=>{R(null),z(``)},children:`Cancel`})]})]}),de=async e=>{H(!0),U(null);try{let t=await Pn(a,e===null?{}:e.kind===`fact`?{claimIds:[e.id]}:{episodeIds:[e.id]});re({memoryId:null,text:Lm(t)}),A(null),O(e=>e+1),r()}catch(e){U(W(e,`Could not retry search sync.`))}finally{H(!1)}},J=async()=>{S(!0),U(null);try{b(await Nn(a))}catch(e){U(W(e,`Could not check the search index.`))}finally{S(!1)}},Y=(g?.failed??[]).map(e=>(0,Q.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":k===e.id,className:`memory-record ${k===e.id?`selected`:``}`,onClick:()=>ae(e.id),children:[(0,Q.jsx)(`span`,{className:`memory-review-state failed`,children:`not in search`}),(0,Q.jsxs)(`span`,{className:`memory-record-copy`,children:[(0,Q.jsx)(`strong`,{children:e.preview}),(0,Q.jsxs)(`small`,{children:[e.kind===`fact`?`Fact`:`Episode`,` · `,e.operation,` · last tried `,Rm(e.updatedAt)]})]})]},`${e.kind}:${e.id}`)),fe=o===`sync`?Y:o===`conflicts`?c.map(e=>(0,Q.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":k===e.claimId,className:`memory-record ${k===e.claimId?`selected`:``}`,onClick:()=>ae(e.claimId),children:[(0,Q.jsx)(`span`,{className:`memory-review-state unresolved_conflict`,children:`conflict`}),(0,Q.jsxs)(`span`,{className:`memory-record-copy`,children:[(0,Q.jsx)(`strong`,{children:e.revisions.map(e=>e.preview).join(` / `)}),(0,Q.jsxs)(`small`,{children:[zm(e.scope),` · opened `,Rm(e.openedAt)]})]})]},e.claimId)):f.map(e=>(0,Q.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":k===e.claimId,className:`memory-record ${k===e.claimId?`selected`:``}`,onClick:()=>ae(e.claimId),children:[(0,Q.jsx)(`span`,{className:`memory-review-state ${e.state}`,children:e.state}),(0,Q.jsxs)(`span`,{className:`memory-record-copy`,children:[(0,Q.jsx)(`strong`,{children:e.preview}),(0,Q.jsxs)(`small`,{children:[zm(e.scope),` · `,Rm(e.changedAt)]})]})]},e.claimId));return(0,Q.jsxs)(`section`,{className:`memory-workspace memory-reconciliation-workspace`,"aria-label":`Fact review`,children:[(0,Q.jsxs)(`div`,{className:`memory-browser-pane`,children:[(0,Q.jsxs)(`header`,{className:`memory-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`breadcrumbs`,children:`Kai Workshop / Memory`}),(0,Q.jsx)(`h1`,{children:`Fact review`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Back to memories`,title:`Back to memories`,onClick:n,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})]}),(0,Q.jsxs)(`div`,{className:`memory-browser-scroll`,children:[(0,Q.jsxs)(`div`,{className:`fact-review-tabs`,role:`tablist`,"aria-label":`Fact review lists`,children:[(0,Q.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o===`conflicts`,onClick:()=>oe(`conflicts`),children:[`Conflicts `,(0,Q.jsx)(`span`,{children:u})]}),(0,Q.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o===`forgotten`,onClick:()=>oe(`forgotten`),children:[`Forgotten `,(0,Q.jsx)(`span`,{children:m})]}),(0,Q.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o===`sync`,onClick:()=>oe(`sync`),children:[`Search sync `,(0,Q.jsx)(`span`,{children:g?.failedTotal??0})]})]}),o===`sync`&&!C&&!T&&(0,Q.jsxs)(`section`,{className:`fact-review-sync-summary`,"aria-label":`Search sync summary`,children:[(0,Q.jsxs)(`p`,{className:`memory-review-explanation`,children:[`These facts and episodes are saved, but their search copy failed to update, so Kai cannot recall them yet.`,g&&g.blocked>0&&` ${g.blocked} later change${g.blocked===1?` is`:`s are`} waiting behind them.`]}),(0,Q.jsxs)(`div`,{className:`memory-review-toolbar`,children:[(0,Q.jsx)(`button`,{type:`button`,disabled:V||(g?.failedTotal??0)===0,onClick:()=>void de(null),children:`Retry all`}),(0,Q.jsx)(`button`,{type:`button`,disabled:x,onClick:()=>void J(),children:x?`Checking…`:`Check search index`})]}),y&&(0,Q.jsx)(`p`,{className:`memory-review-explanation`,role:`note`,children:y.orphan.length+y.unknown.length+y.missing.length===0&&y.duplicate===0?`The search index matches your memory.`:[y.missing.length>0?`${y.missing.length} current fact(s) have no search row, so Kai cannot recall them.`:``,y.orphan.length+y.unknown.length+y.duplicate>0?`The search index has ${y.orphan.length} leftover and ${y.unknown.length} unknown row(s)${y.duplicate>0?`, and ${y.duplicate} item(s) with duplicates`:``}. Kai never recalls them; they only take up space.`:``].filter(Boolean).join(` `)}),te&&!le&&(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:te})]}),ne&&(0,Q.jsxs)(`p`,{className:`memory-mutation-report`,role:`status`,children:[ne.text,ne.memoryId&&(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(`button`,{type:`button`,className:`fact-review-link`,onClick:()=>i(ne.memoryId),children:`Open in memory`})]})]}),C?(0,Q.jsx)(`p`,{className:`memory-list-state`,role:`status`,children:`Loading fact review…`}):T?(0,Q.jsxs)(`div`,{className:`memory-list-state error`,role:`alert`,children:[(0,Q.jsx)(`p`,{children:T}),(0,Q.jsx)(`button`,{onClick:()=>O(e=>e+1),children:`Retry`})]}):fe.length===0?(0,Q.jsxs)(`div`,{className:`memory-list-state`,children:[(0,Q.jsx)(`h2`,{children:o===`conflicts`?`No open conflicts`:o===`forgotten`?`No forgotten facts`:`Everything is in search`}),(0,Q.jsx)(`p`,{children:o===`conflicts`?`Conflicts appear when an extracted update is not certain enough to replace a stored fact.`:o===`forgotten`?`Facts you forget, or that expire, appear here and can be restored.`:`Facts and episodes appear here if their search copy fails to update.`})]}):(0,Q.jsx)(`div`,{className:`memory-record-list memory-reconciliation-list`,role:`listbox`,"aria-label":o===`conflicts`?`Unresolved conflicts`:o===`forgotten`?`Forgotten facts`:`Search sync failures`,children:fe})]})]}),(0,Q.jsxs)(`aside`,{className:`context-pane memory-detail-pane`,"aria-label":`Fact review detail`,children:[e&&(0,Q.jsx)(`div`,{className:`context-resize-handle`,role:`separator`,"aria-label":`Resize fact review detail`,"aria-orientation":`vertical`,"aria-valuemin":e.minimumWidth,"aria-valuemax":e.maximumWidth,"aria-valuenow":e.width,tabIndex:0,onKeyDown:e.onKeyDown,onPointerDown:e.onPointerDown,onPointerMove:e.onPointerMove}),(0,Q.jsx)(`div`,{className:`memory-reconciliation-detail`,children:o===`conflicts`&&se?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`header`,{className:`memory-detail-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Unresolved conflict`}),(0,Q.jsx)(`h2`,{children:`Which version is true?`})]}),(0,Q.jsx)(`span`,{className:`memory-review-state unresolved_conflict`,children:`conflict`})]}),(0,Q.jsx)(`p`,{className:`memory-review-explanation`,children:`Neither version is recalled until you keep one. If neither wording is quite right, keep the closer one and edit it in memory.`}),te&&(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:te}),N?(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:N}):j?(0,Q.jsx)(`div`,{className:`fact-review-sides`,children:ue.map(e=>(0,Q.jsxs)(`article`,{className:`memory-review-evidence`,"aria-label":`Competing version`,children:[(0,Q.jsx)(Nm,{body:e.content}),(0,Q.jsxs)(`dl`,{className:`fact-review-facts`,children:[(0,Q.jsx)(`dt`,{children:`Stored`}),(0,Q.jsx)(`dd`,{children:Rm(e.storedAt)}),(0,Q.jsx)(`dt`,{children:`Source`}),(0,Q.jsx)(`dd`,{children:Bm(e)}),(0,Q.jsx)(`dt`,{children:`Confidence`}),(0,Q.jsx)(`dd`,{children:typeof e.confidence==`number`?`${Math.round(e.confidence*100)}%`:`Not recorded`}),(0,Q.jsx)(`dt`,{children:`Reason`}),(0,Q.jsx)(`dd`,{children:e.reason}),(0,Q.jsx)(`dt`,{children:`Admission`}),(0,Q.jsx)(`dd`,{children:Vm(e.admissionAuthority)})]}),(0,Q.jsx)(`button`,{type:`button`,disabled:V,onClick:()=>{R({kind:`keep`,revisionId:e.revisionId}),U(null)},children:`Keep this version`})]},e.revisionId))}):(0,Q.jsx)(`p`,{className:`memory-list-state`,role:`status`,children:`Loading conflict…`}),q]}):o===`forgotten`&&ce?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`header`,{className:`memory-detail-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:ce.state===`expired`?`Expired fact`:`Forgotten fact`}),(0,Q.jsx)(`h2`,{children:`Restore to current?`})]}),(0,Q.jsx)(`span`,{className:`memory-review-state ${ce.state}`,children:ce.state})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(Nm,{body:ce.preview}),(0,Q.jsxs)(`dl`,{className:`fact-review-facts`,children:[(0,Q.jsx)(`dt`,{children:`Scope`}),(0,Q.jsx)(`dd`,{children:zm(ce.scope)}),(0,Q.jsx)(`dt`,{children:ce.state===`expired`?`Expired`:`Forgotten`}),(0,Q.jsx)(`dd`,{children:Rm(ce.changedAt)}),(0,Q.jsx)(`dt`,{children:`Reason`}),(0,Q.jsx)(`dd`,{children:ce.reason})]})]}),te&&(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:te}),!L&&(0,Q.jsx)(`button`,{type:`button`,disabled:V,onClick:()=>{R({kind:`restore`}),U(null)},children:`Restore`}),q]}):o===`sync`&&le?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`header`,{className:`memory-detail-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`p`,{className:`overline`,children:[le.kind===`fact`?`Fact`:`Episode`,` not in search`]}),(0,Q.jsx)(`h2`,{children:`Retry search sync?`})]}),(0,Q.jsx)(`span`,{className:`memory-review-state failed`,children:`failed`})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(Nm,{body:le.preview}),(0,Q.jsxs)(`dl`,{className:`fact-review-facts`,children:[(0,Q.jsx)(`dt`,{children:`Step`}),(0,Q.jsx)(`dd`,{children:le.operation}),(0,Q.jsx)(`dt`,{children:`Attempts`}),(0,Q.jsx)(`dd`,{children:le.attempts}),(0,Q.jsx)(`dt`,{children:`Error`}),(0,Q.jsx)(`dd`,{children:Im(le.errorCode)}),(0,Q.jsx)(`dt`,{children:`Last tried`}),(0,Q.jsx)(`dd`,{children:Rm(le.updatedAt)})]})]}),(0,Q.jsxs)(`p`,{className:`memory-review-explanation`,children:[`The saved `,le.kind,` is unchanged. Retrying only updates its search copy`,le.kind===`fact`?`, then runs any later changes that were waiting on it`:``,`.`]}),te&&(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:te}),(0,Q.jsx)(`button`,{type:`button`,disabled:V,onClick:()=>void de(le),children:V?`Retrying…`:`Retry`})]}):(0,Q.jsx)(`div`,{className:`memory-list-state`,children:(0,Q.jsx)(`p`,{children:o===`conflicts`?`Select a conflict to compare its versions.`:o===`forgotten`?`Select a fact to see why it left current truth.`:`Select an item to see why it is not in search.`})})})]})]})}var Wm=(0,v.createContext)(null);function Gm({children:e}){let[t,n]=(0,v.useState)(null),r=(0,v.useRef)(null),i=(0,v.useRef)(null),a=(0,v.useCallback)(e=>{let t=r.current;t&&(r.current=null,n(null),t.resolve(e))},[]),o=(0,v.useCallback)(e=>(r.current?.resolve(!1),new Promise(t=>{let i={message:e,resolve:t};r.current=i,n(i)})),[]);return(0,v.useEffect)(()=>()=>{r.current?.resolve(!1),r.current=null},[]),(0,v.useEffect)(()=>{if(!t)return;i.current?.focus();let e=e=>{e.key===`Escape`&&(e.preventDefault(),a(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t,a]),(0,Q.jsxs)(Wm.Provider,{value:o,children:[e,t&&(0,Q.jsx)(`div`,{className:`confirmation-backdrop`,onMouseDown:e=>{e.target===e.currentTarget&&a(!1)},children:(0,Q.jsxs)(`section`,{className:`confirmation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`confirmation-dialog-title`,"aria-describedby":`confirmation-dialog-message`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Confirm action`}),(0,Q.jsx)(`h2`,{id:`confirmation-dialog-title`,children:`Continue?`}),(0,Q.jsx)(`p`,{id:`confirmation-dialog-message`,children:t.message}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`button`,{ref:i,type:`button`,className:`quiet-button`,onClick:()=>a(!1),children:`Cancel`}),(0,Q.jsx)(`button`,{type:`button`,className:`primary-button`,onClick:()=>a(!0),children:`Continue`})]})]})})]})}function Km(){let e=(0,v.useContext)(Wm);if(!e)throw Error(`useConfirmation must be used within ConfirmationProvider`);return e}var qm=8;function Jm(e){return e.evidence[0]?.text??`Unavailable fact`}function Ym(e){let t=e.evidence[0];return!t||t.migrationGaps.includes(`scope`)?`Scope not recorded`:t.scope===`project`&&t.projectId?`Project ${t.projectId}`:`Global`}function Xm(e){let t=new Set(e.map(e=>{let t=e.evidence[0];return!t||t.migrationGaps.includes(`scope`)?``:t.scope===`project`?`project:${t.projectId??``}`:`global`}));if(t.size!==1)return{kind:``,key:``};let[n]=[...t];return n===`global`?{kind:`global`,key:``}:n.startsWith(`project:`)&&n.length>8?{kind:`project`,key:n.slice(8)}:{kind:``,key:``}}function Zm(e,t){return e.evidence.length>0&&e.evidence.every(e=>e.kind===`fact`)&&(e.consolidationId===null||e.consolidationId===t)}function Qm({allowedProjects:e,anchor:t,availableGroups:n,consolidation:r,onAuthenticationFailure:i,onClose:a,onSaved:o,planId:s,token:c}){let l=Km(),u=(0,v.useMemo)(()=>new Map(n.map(e=>[e.groupId,e])),[n]),d=r?.consolidationId??null,[f,p]=(0,v.useState)(()=>{let e=r?.groupIds??[t.groupId,...t.relatedGroupIds];return[...new Set(e)].filter(e=>{let t=u.get(e);return t!==void 0&&Zm(t,d)})}),m=f.map(e=>u.get(e)).filter(e=>!!e),h=r?{kind:r.scopeKind,key:r.scopeKey??``}:Xm(m),[g,_]=(0,v.useState)(r?.content??Jm(t)),[y,b]=(0,v.useState)(r?.sourceMemoryId??t.evidence[0]?.memoryId??``),[x,S]=(0,v.useState)(h.kind),[C,w]=(0,v.useState)(h.key),[T,E]=(0,v.useState)(r?.operatorNote??``),[D,O]=(0,v.useState)(``),[k,A]=(0,v.useState)(!1),[j,M]=(0,v.useState)(null),N=D.trim()?n.filter(e=>!f.includes(e.groupId)&&Zm(e,d)&&Jm(e).toLowerCase().includes(D.trim().toLowerCase())).slice(0,qm):[],P=m.some(e=>e.evidence.some(e=>e.memoryId===y)),F=x!==`project`||e.some(e=>e.projectId===C),I=null;m.length<2?I=`Select at least two facts to consolidate.`:g.trim()?P?x?x===`project`&&!F&&(I=`Choose a project you currently have access to.`):I=`Choose a scope for the consolidated fact.`:I=`Choose the wording of one of the selected facts to start from.`:I=`Enter the consolidated fact's wording.`;let L=`${m.length} selected facts → 1 current fact; ${Math.max(m.length-1,0)} duplicates excluded`,R=(e,t)=>{e instanceof B&&i(e.message),M(e instanceof Error?e.message:t)},ee=e=>{p(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},z=e=>{_(Jm(e)),b(e.evidence[0]?.memoryId??``)},V=async()=>{if(!I&&await l(`${r?`Update`:`Save`} this consolidation? ${L}. Applying the plan keeps the other facts only as evidence; Kai will not recall them.`)){A(!0),M(null);try{await rn(c,s,{canonical:{content:g.trim(),scopeKey:x===`project`?C:null,scopeKind:x,sourceMemoryId:y},...r?{consolidationId:r.consolidationId,expectedRevision:r.revision}:{},expectedStateVersions:Object.fromEntries(m.map(e=>[e.groupId,e.decision.stateVersion])),groupIds:m.map(e=>e.groupId),operatorNote:T}),o(`Consolidation saved: ${L}.`)}catch(e){R(e,`Could not save the consolidation.`)}finally{A(!1)}}},H=async()=>{if(r&&await l(`Cancel this consolidation? Each fact gets back the decision it had before.`)){A(!0),M(null);try{await an(c,s,r.consolidationId,r.revision),o(`Consolidation cancelled; each fact has its earlier decision again.`)}catch(e){R(e,`Could not cancel the consolidation.`)}finally{A(!1)}}};return(0,Q.jsxs)(`section`,{className:`memory-reconciliation-detail memory-consolidation`,"aria-label":`Consolidate facts`,children:[(0,Q.jsxs)(`header`,{className:`memory-detail-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:r?`Saved consolidation`:`Consolidate facts`}),(0,Q.jsx)(`h2`,{children:`Several facts, one current fact`})]}),(0,Q.jsx)(`button`,{type:`button`,className:`panel-icon-button`,"aria-label":`Back to the fact`,title:`Back to the fact`,onClick:a,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Selected facts`}),(0,Q.jsx)(`p`,{className:`memory-review-explanation`,children:`Keep checked the facts that say the same thing. Use one's wording as a starting point, then edit it below.`}),(0,Q.jsx)(`ul`,{className:`memory-consolidation-facts`,children:m.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:!0,onChange:()=>ee(e.groupId)}),(0,Q.jsx)(`span`,{children:Jm(e)})]}),(0,Q.jsx)(`small`,{children:Ym(e)}),(0,Q.jsx)(`button`,{type:`button`,className:`quiet-button`,"aria-pressed":e.evidence[0]?.memoryId===y,onClick:()=>z(e),children:e.evidence[0]?.memoryId===y?`Wording source`:`Use this wording`})]},e.groupId))}),(0,Q.jsxs)(`label`,{className:`memory-consolidation-search`,children:[`Add another fact`,(0,Q.jsx)(`input`,{type:`search`,value:D,placeholder:`Search pending facts`,onChange:e=>O(e.target.value)})]}),N.length>0&&(0,Q.jsx)(`ul`,{className:`memory-consolidation-facts`,"aria-label":`Matching facts`,children:N.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:!1,onChange:()=>ee(e.groupId)}),(0,Q.jsx)(`span`,{children:Jm(e)})]}),(0,Q.jsx)(`small`,{children:Ym(e)})]},e.groupId))})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-review-correction`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Consolidated fact`}),(0,Q.jsxs)(`label`,{children:[`Wording`,(0,Q.jsx)(`textarea`,{value:g,maxLength:16384,onChange:e=>_(e.target.value)})]}),(0,Q.jsxs)(`label`,{children:[`Scope`,(0,Q.jsxs)(`select`,{value:x,onChange:e=>S(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:`Choose scope`}),(0,Q.jsx)(`option`,{value:`global`,children:`Global`}),(0,Q.jsx)(`option`,{value:`project`,children:`Project`})]})]}),x===`project`&&(0,Q.jsxs)(`label`,{children:[`Project`,(0,Q.jsxs)(`select`,{value:C,onChange:e=>w(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:`Choose project`}),e.map(e=>(0,Q.jsx)(`option`,{value:e.projectId,children:e.displayName},e.projectId))]})]}),(0,Q.jsxs)(`label`,{children:[`Note (optional)`,(0,Q.jsx)(`textarea`,{value:T,maxLength:4096,onChange:e=>E(e.target.value)})]})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-review-decision`,children:[(0,Q.jsx)(`p`,{className:`memory-consolidation-preview`,role:`status`,children:L}),I&&(0,Q.jsx)(`p`,{className:`memory-review-explanation`,children:I}),j&&(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:j}),(0,Q.jsxs)(`div`,{className:`memory-review-toolbar`,children:[(0,Q.jsx)(`button`,{type:`button`,disabled:k||I!==null,onClick:()=>void V(),children:k?`Saving…`:r?`Update consolidation`:`Save consolidation`}),r&&(0,Q.jsx)(`button`,{type:`button`,className:`danger`,disabled:k,onClick:()=>void H(),children:`Cancel consolidation`})]})]})]})}function $m(e){return e.replaceAll(`_`,` `).replace(/^./,e=>e.toUpperCase())}function eh(e){let t=e.replace(/\s+/g,` `).trim();return t.length>88?`${t.slice(0,87)}…`:t}function th(e){switch(e.kind){case`adopt_as_current`:case`adopt_corrected`:return{button:`Approve current-truth adoption`,label:`Adopt as current truth`,operatorAdmits:!0,verb:`adopt as current truth`};case`keep_first_retract_rest`:return{button:`Approve consolidation`,label:`Consolidate into current truth`,operatorAdmits:!0,verb:`consolidate into current truth`};case`expire_all`:return{button:`Approve obsolescence`,label:`Mark obsolete`,operatorAdmits:!1,verb:`mark obsolete`};case`record_episode_chain`:return{button:`Approve historical retention`,label:`Retain as retrievable history`,operatorAdmits:!0,verb:`retain as retrievable history`};default:return null}}function nh(e){if(e.length===0)return null;let t=th(e[0].proposedAction);return t&&e.every(e=>th(e.proposedAction)?.verb===t.verb)?t:null}function rh(e){return th(e.proposedAction)?.label??$m(e.resolution)}function ih(e,t){return e instanceof Error?e.message:t}function ah(e){if(e.disposition!==`approve`)return{className:e.disposition,label:e.disposition};switch(e.action.kind){case`expire_all`:return{className:`obsolete`,label:`obsolete`};case`consolidate`:return{className:`approve`,label:`consolidated`};case`keep_first_retract_rest`:return{className:`approve`,label:`consolidated`};case`record_episode_chain`:return{className:`approve`,label:`retained`};default:return{className:`approve`,label:`approved`}}}function oh(e){return`Group ${e.replace(/^mtg_/,``).slice(0,8)}`}function sh(e){return e?.classification===`incomplete_episode`}var ch={actors:`the people involved`,outcome_quality:`an outcome`};function lh(e){if(!e)return`defer`;if(sh(e))return e.decision.disposition===`defer`?`defer`:`reject`;if(e.decision.disposition===`reject`||e.decision.disposition===`defer`)return e.decision.disposition;let t=e.decision.disposition===`approve`?e.decision.action.kind:null,n=e.decision.recommendation.outcome,r=t??e.proposedAction.kind;return r===`expire_all`||n===`obsolete`?`obsolete`:r===`adopt_corrected`||r===`adopt_as_current`||r===`keep_first_retract_rest`||r===`record_episode_chain`||n===`adopt`||n===`consolidate`?`approve`:`defer`}function uh(e){if(!e||e.decision.disposition!==`approve`||e.decision.action.kind!==`adopt_corrected`)return null;let t=e.decision.action.replacement;return t&&typeof t==`object`&&!Array.isArray(t)?t:null}function dh(e){let t=uh(e)?.scope_kind;if(t===`global`||t===`project`)return t;let n=e?.evidence[0];return!n||n.kind!==`fact`||n.scope!==`global`&&n.scope!==`project`?``:e.evidence.every(e=>e.scope===n.scope&&e.projectId===n.projectId)?n.scope:``}function fh(e,t){let n=e.decision.recommendation.related_group_ids,r=Array.isArray(n)&&n.every(e=>typeof e==`string`)?n:String(e.decision.recommendation.rationale??``).match(/mtg_[a-z0-9]+/gi)??[];return[...new Set(r)].filter(n=>n!==e.groupId&&t.has(n))}function ph(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M7 4h10M7 9h10M7 14h6`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`m14.5 18 2 2 4-5`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.8`})]})}function mh({allowedProjects:e,availableGroups:t,group:n,onAuthenticationFailure:r,onConsolidate:i,onSelectGroup:a,onSaved:o,readOnly:s,token:c,planId:l}){let u=n?.evidence[0]??null,d=uh(n),[f,p]=(0,v.useState)(typeof d?.content==`string`?d.content:u?.text??``),[m,h]=(0,v.useState)(lh(n)),[g,_]=(0,v.useState)(dh(n)),[y,b]=(0,v.useState)(typeof d?.scope_key==`string`?d.scope_key:u?.projectId??``),[x,S]=(0,v.useState)(n?.decision.operatorNote??``),[C,w]=(0,v.useState)(!1),[T,E]=(0,v.useState)(null);if(!n||!u||!l)return(0,Q.jsxs)(`div`,{className:`memory-detail-empty`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`◇`}),(0,Q.jsx)(`h2`,{children:`No exception selected`}),(0,Q.jsx)(`p`,{children:`Only uncertain or conflicting memory groups require individual review.`})]});let D=n.decision.recommendation,O=f.trim()!==u.text,k=n.evidence.every(e=>e.kind===`fact`),A=n.evidence.every(e=>e.kind===`episode`),j=g!==u.scope||g===`project`&&y!==u.projectId,M=g!==`project`||e.some(e=>e.projectId===y),N=u.validUntil?Date.parse(u.validUntil):null,P=N!==null&&!Number.isNaN(N)&&N<=Date.now(),F=null;m===`approve`&&A?F={kind:`record_episode_chain`}:m===`obsolete`&&k?F={kind:`expire_all`}:m===`approve`&&k&&f.trim()&&g&&M&&(g!==`project`||y)&&(F=n.evidence.length>1||O||j||u.migrationGaps.includes(`scope`)||P?{kind:`adopt_corrected`,source_memory_id:u.memoryId,replacement:{content:f.trim(),scope_kind:g,scope_key:g===`project`?y:``,confidence:typeof u.confidence==`number`?u.confidence:.5,asserted_at:u.assertedAt,observed_at:u.observedAt,valid_from:P?null:u.validFrom,valid_until:P?null:u.validUntil}}:{kind:`adopt_as_current`});let I=m===`approve`||m===`obsolete`,L=!I||F!==null,R=I?`approve`:m,ee=A?`Retain as immutable history`:n.evidence.length>1?`Approve consolidation`:`Approve as current truth`,z=null;I&&F===null&&(z=!k&&!A?`This mixed evidence group cannot be approved.`:k&&!f.trim()?`Enter the current fact wording before approval.`:k&&!g?`Choose a scope before approval.`:k&&g===`project`&&!y?`Choose a project before approval.`:k&&g===`project`&&!M?`The selected project is not currently authorized for this runtime.`:`This decision is not available for the supplied evidence.`);let V=new Set(t.map(e=>e.groupId)),H=n.relatedGroupIds.length>0?n.relatedGroupIds.filter(e=>V.has(e)):fh(n,V),te=async e=>{e.preventDefault(),w(!0),E(null);try{let e=R===`approve`&&F?F:n.proposedAction;await en(c,l,n.groupId,{disposition:R,action:e,operatorNote:x,expectedStateVersion:n.decision.stateVersion}),o()}catch(e){e instanceof B&&r(e.message),E(ih(e,`Could not save this memory decision.`))}finally{w(!1)}};return(0,Q.jsxs)(`form`,{className:`memory-reconciliation-detail`,onSubmit:e=>void te(e),children:[(0,Q.jsxs)(`header`,{className:`memory-detail-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Exception review`}),(0,Q.jsx)(`h2`,{children:$m(n.classification)})]}),(0,Q.jsx)(`span`,{className:`memory-review-state ${ah(n.decision).className}`,children:ah(n.decision).label})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Why this needs judgment`}),sh(n)?(0,Q.jsxs)(`p`,{children:[`This legacy episode was saved without`,` `,n.missingFields.map(e=>ch[e]??e).join(` or `)||`required details`,`, so it can't be kept as a canonical episode. Kai won't guess them. Reject it, or defer.`]}):(0,Q.jsx)(`p`,{children:n.rationale})]}),Object.keys(D).length>0&&(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Model recommendation`}),(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`strong`,{children:$m(String(D.outcome??`needs_review`))}),typeof D.confidence==`number`&&` · ${Math.round(D.confidence*100)}% confidence`]}),(0,Q.jsx)(`p`,{children:String(D.rationale??`No rationale was returned.`)}),H.length>0&&(0,Q.jsxs)(`div`,{className:`memory-related-groups`,children:[(0,Q.jsx)(`p`,{children:`Related facts`}),H.map(e=>(0,Q.jsx)(`button`,{type:`button`,title:`Open this fact`,onClick:()=>a(e),children:eh(t.find(t=>t.groupId===e)?.evidence[0]?.text??`Unavailable fact`)},e)),k&&!s&&(0,Q.jsx)(`button`,{type:`button`,className:`memory-consolidate-button`,onClick:i,children:`Consolidate related facts…`})]}),(0,Q.jsx)(`p`,{className:`memory-review-explanation`,children:`Advisory only; it has not changed memory.`})]}),n.priorReviewEvidence.length>0&&(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Earlier raw review`}),n.priorReviewEvidence.map(e=>(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`strong`,{children:$m(e.disposition)}),e.operatorNote?` · ${e.operatorNote}`:` · No operator note`]},e.candidateId)),(0,Q.jsx)(`p`,{className:`memory-review-explanation`,children:`This earlier decision remains evidence. It was not silently converted into a grouped approval.`})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Evidence`}),n.evidence.map(e=>(0,Q.jsxs)(`article`,{className:`memory-review-evidence`,children:[(0,Q.jsx)(Nm,{body:e.text}),(0,Q.jsxs)(`small`,{children:[e.kind,` · `,e.scope,e.projectId?` · ${e.projectId}`:``]})]},e.memoryId))]}),(0,Q.jsxs)(`fieldset`,{className:`memory-review-controls`,disabled:s||C,children:[u.kind===`fact`&&(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-review-correction`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Canonical fact`}),(0,Q.jsxs)(`label`,{children:[`Current wording`,(0,Q.jsx)(`textarea`,{value:f,maxLength:16384,onChange:e=>p(e.target.value)})]}),(0,Q.jsxs)(`label`,{children:[`Scope`,(0,Q.jsxs)(`select`,{value:g,onChange:e=>_(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:`Choose scope`}),(0,Q.jsx)(`option`,{value:`global`,children:`Global`}),(0,Q.jsx)(`option`,{value:`project`,children:`Project`})]})]}),g===`project`&&(0,Q.jsxs)(`label`,{children:[`Project`,(0,Q.jsxs)(`select`,{value:y,onChange:e=>b(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:`Choose project`}),y&&!e.some(e=>e.projectId===y)&&(0,Q.jsxs)(`option`,{value:y,children:[y,` (unavailable)`]}),e.map(e=>(0,Q.jsx)(`option`,{value:e.projectId,children:e.displayName},e.projectId))]})]}),(0,Q.jsx)(`p`,{className:`memory-review-explanation`,children:`Adoption creates one current claim backed by every evidence row in this group. You may retain the wording or correct it.`})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-review-decision`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Review`}),(0,Q.jsxs)(`label`,{children:[`Decision`,(0,Q.jsxs)(`select`,{value:m,onChange:e=>h(e.target.value),children:[(k||A)&&!sh(n)&&(0,Q.jsx)(`option`,{value:`approve`,children:ee}),k&&(0,Q.jsx)(`option`,{value:`obsolete`,children:`Mark obsolete`}),(0,Q.jsx)(`option`,{value:`reject`,children:`Reject`}),(0,Q.jsx)(`option`,{value:`defer`,children:`Defer`})]})]}),z&&(0,Q.jsx)(`p`,{children:z}),F?.kind===`adopt_as_current`&&!O&&(0,Q.jsxs)(`p`,{children:[`Approve adopts this fact unchanged as current truth.`,n.priorReviewEvidence.length>0&&` The earlier decision remains audit evidence.`]}),(0,Q.jsxs)(`label`,{children:[`Operator note`,(0,Q.jsx)(`textarea`,{value:x,maxLength:4096,onChange:e=>S(e.target.value)})]}),T&&(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:T}),(0,Q.jsx)(`button`,{type:`submit`,disabled:s||C||!L,children:C?`Saving…`:`Save decision`}),k&&!sh(n)&&(0,Q.jsxs)(`p`,{className:`memory-review-explanation`,children:[`Same fact saved several times?`,` `,(0,Q.jsx)(`button`,{type:`button`,className:`fact-review-link`,disabled:s,onClick:i,children:`Consolidate with other facts…`})]})]})]})]})}function hh({allowedProjects:e,detailPanelLayout:t,onAuthenticationFailure:n,onBack:r,token:i}){let a=Km(),[o,s]=(0,v.useState)(null),[c,l]=(0,v.useState)([]),[u,d]=(0,v.useState)(null),[f,p]=(0,v.useState)(!0),[m,h]=(0,v.useState)(!1),[g,_]=(0,v.useState)(0),[y,b]=(0,v.useState)(null),[x,S]=(0,v.useState)(null),[C,w]=(0,v.useState)(null),[T,E]=(0,v.useState)([]),[D,O]=(0,v.useState)([]),[k,A]=(0,v.useState)(!1),j=(e,t)=>{e instanceof B&&n(e.message),b(ih(e,t))};(0,v.useEffect)(()=>{let e=!1;return p(!0),b(null),w(null),E([]),Xt(i).then(async t=>{if(e)return;if(s(t),l([]),A(!1),!t){d(null);return}let n=[],r=0,a=t;for(;r!==null;){let e=await Zt(i,t.planId,{exceptionsOnly:!0,limit:100,offset:r});n.push(...e.groups),a=e.triage,r=e.nextOffset}let o=await nn(i,t.planId);e||(s(a),l(n),O(o),d(e=>e!==null&&n.some(t=>t.groupId===e)?e:n[0]?.groupId??null))}).catch(t=>{e||j(t,`Could not load memory triage.`)}).finally(()=>{e||p(!1)}),()=>{e=!0}},[g,i]);let M=(0,v.useMemo)(()=>c.find(e=>e.groupId===u)??null,[c,u]),N=async()=>{if(o){h(!0),b(null);try{let e=[],t=0;for(;t!==null;){let n=await Zt(i,o.planId,{limit:100,offset:t});e.push(...n.groups.filter(e=>e.deterministic&&e.bulkEligible&&e.decision.disposition===`pending`)),t=n.nextOffset}let n=e[0];if(!n)throw Error(`No deterministic memory groups are pending.`);let r=JSON.stringify(n.proposedAction),a=e.filter(e=>JSON.stringify(e.proposedAction)===r),s=await Qt(i,o.planId,o.reviewVersion,a.map(e=>e.groupId));if(a.length!==s.groupCount)throw Error(`Kai returned an incomplete deterministic memory preview.`);w(s),E(a),S(`Review the complete grouped evidence below before approving it.`)}catch(e){j(e,`Could not preview deterministic memory groups.`)}finally{h(!1)}}},P=async()=>{if(!C)return;let e=C.resolutionCounts,t=nh(T);if(await a(t?`${$m(t.verb)} for ${C.memoryCount} deterministic legacy memories? `+(t.operatorAdmits?`Their original provenance will remain incomplete; your explicit approval supplies separate retrieval admission authority.`:`Their original provenance will remain incomplete and the canonical lifecycle will exclude them as obsolete.`):`Approve ${C.memoryCount} deterministic memories after reviewing the complete preview: ${e.adopt} adopt, ${e.consolidate} consolidate, ${e.obsolete} obsolete? No detected warning is not proof that a fact is true; your approval is the trust decision.`)){h(!0),b(null);try{await $t(i,C),S(t?`${C.memoryCount} deterministic legacy memories approved to ${t.verb} in ${C.groupCount} evidence-bound groups.`:`${C.memoryCount} deterministic memories approved in ${C.groupCount} evidence-bound groups.`),_(e=>e+1)}catch(e){j(e,`Could not approve deterministic memory groups.`)}finally{h(!1)}}},F=async()=>{if(o){h(!0),b(null);try{let e=await on(i,o.planId);S(e.remaining===0?`The configured memory-quality model analyzed all ${o.exceptionGroups} exception groups. Recommendations are advisory only.`:`The configured memory-quality model analyzed ${e.recommended} exception groups; ${e.remaining} remain. Recommendations are advisory only.`),_(e=>e+1)}catch(e){j(e,`Could not analyze uncertain memory groups.`)}finally{h(!1)}}},I=async()=>{if(o&&await a(`Apply this grouped plan through canonical fact and episode lifecycle events? A final receipt will record every outcome.`)){h(!0),b(null);try{let e=await sn(i,o.planId,o.reviewVersion);S(`${e.operator_admitted??0} operator admitted, ${e.adopted??0} adopted by lifecycle outcome, ${e.consolidated??0} consolidated, ${e.obsolete??0} obsolete, ${e.deferred??0} deferred, ${e.rejected??0} rejected, ${e.failed??0} failed, ${e.still_unresolved??0} still unresolved.`+((e.failed??0)>0?` ${e.failed} did not reach search; retry them under Search sync in Fact review.`:``)),_(e=>e+1)}catch(e){j(e,`Could not apply grouped memory triage.`)}finally{h(!1)}}};return(0,Q.jsxs)(`section`,{className:`memory-workspace memory-reconciliation-workspace`,"aria-label":`Memory reconciliation`,children:[(0,Q.jsxs)(`div`,{className:`memory-browser-pane`,children:[(0,Q.jsxs)(`header`,{className:`memory-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`breadcrumbs`,children:`Kai Workshop / Memory`}),(0,Q.jsx)(`h1`,{children:`Legacy triage`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Back to memories`,title:`Back to memories`,onClick:r,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})]}),(0,Q.jsx)(`div`,{className:`memory-browser-scroll`,children:f?(0,Q.jsx)(`p`,{className:`memory-list-state`,role:`status`,children:`Building grouped memory triage…`}):y?(0,Q.jsxs)(`div`,{className:`memory-list-state error`,role:`alert`,children:[(0,Q.jsx)(`p`,{children:y}),(0,Q.jsx)(`button`,{onClick:()=>_(e=>e+1),children:`Retry`})]}):o?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`section`,{className:`memory-reconciliation-summary`,"aria-label":`Triage summary`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:o.resolutionCounts.adopt}),(0,Q.jsx)(`span`,{children:`Retain`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:o.resolutionCounts.consolidate}),(0,Q.jsx)(`span`,{children:`Consolidate`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:o.resolutionCounts.obsolete}),(0,Q.jsx)(`span`,{children:`Obsolete`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:Math.max(o.dispositionCounts.pending-o.pendingDeterministicGroups,0)}),(0,Q.jsx)(`span`,{children:`Need review`})]})]}),o.status===`applied`&&(0,Q.jsx)(`p`,{className:`memory-review-explanation`,role:`status`,children:`Applied: every group was decided and the plan has changed memory. This view is a record of it.`}),(0,Q.jsxs)(`p`,{className:`memory-review-explanation`,children:[`The plan partitions `,o.memoryCount,` legacy memories into `,o.groupCount,` non-overlapping groups. Only uncertain or conflicting groups appear below.`]}),x&&(0,Q.jsx)(`p`,{className:`memory-mutation-report`,role:`status`,children:x}),(0,Q.jsxs)(`div`,{className:`memory-review-toolbar`,children:[(0,Q.jsx)(`button`,{type:`button`,disabled:o.pendingDeterministicGroups===0||m||o.status===`applied`,onClick:()=>void N(),children:C?`Refresh safe preview`:`Preview safe groups`}),(0,Q.jsx)(`button`,{type:`button`,disabled:o.exceptionGroups===0||o.recommendedGroups>=o.exceptionGroups||m||o.status===`applied`,onClick:()=>void F(),children:o.exceptionGroups>0&&o.recommendedGroups>=o.exceptionGroups?`Exceptions analyzed (${o.recommendedGroups})`:`Analyze exceptions`}),(0,Q.jsx)(`button`,{type:`button`,disabled:o.dispositionCounts.pending!==0||m||o.status===`applied`,onClick:()=>void I(),children:o.status===`applied`?`Applied`:`Apply plan`})]}),C&&(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-safe-preview`,"aria-label":`Deterministic memory preview`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Complete deterministic preview`}),(0,Q.jsxs)(`p`,{children:[C.memoryCount,` memories in `,C.groupCount,` evidence-bound groups.`,nh(T)?nh(T)?.operatorAdmits?` Their original provenance remains incomplete; your explicit approval supplies separate retrieval admission authority.`:` Their original provenance remains incomplete and the canonical lifecycle will keep them out of retrieval.`:` No detected warning is proof of truth; approval is your explicit trust decision.`]}),(0,Q.jsx)(`p`,{children:nh(T)?`Proposed outcome: ${C.memoryCount} ${nh(T)?.verb}.`:`Proposed outcomes: ${C.resolutionCounts.adopt} adopt, ${C.resolutionCounts.consolidate} consolidate, ${C.resolutionCounts.obsolete} obsolete.`}),T.map(e=>(0,Q.jsxs)(`details`,{children:[(0,Q.jsxs)(`summary`,{children:[$m(e.classification),` · `,eh(e.evidence[0]?.text??`Unavailable memory`),` · `,e.evidence.length,` `,e.evidence.length===1?`memory`:`memories`,` · `,rh(e)]}),(0,Q.jsx)(`p`,{children:e.rationale}),e.evidence.map(e=>(0,Q.jsxs)(`article`,{className:`memory-review-evidence`,children:[(0,Q.jsx)(Nm,{body:e.text}),(0,Q.jsxs)(`small`,{children:[e.scope,e.projectId?` · ${e.projectId}`:``]})]},e.memoryId))]},e.groupId)),(0,Q.jsx)(`button`,{type:`button`,disabled:m,onClick:()=>void P(),children:nh(T)?nh(T)?.button:`Approve preview`})]}),c.length===0?(0,Q.jsxs)(`div`,{className:`memory-list-state`,children:[(0,Q.jsx)(`h2`,{children:`No exceptional groups`}),(0,Q.jsx)(`p`,{children:`The deterministic preview contains everything in this audit.`})]}):(0,Q.jsx)(`div`,{className:`memory-record-list memory-reconciliation-list`,role:`listbox`,"aria-label":`Memory triage exceptions`,children:c.map(e=>(0,Q.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":u===e.groupId,className:`memory-record ${u===e.groupId?`selected`:``}`,onClick:()=>{A(!1),d(e.groupId)},children:[(0,Q.jsx)(`span`,{className:`memory-review-state ${ah(e.decision).className}`,children:ah(e.decision).label}),(0,Q.jsxs)(`span`,{className:`memory-record-copy`,children:[(0,Q.jsx)(`strong`,{children:e.evidence[0]?.text??`Unavailable memory`}),(0,Q.jsxs)(`small`,{children:[e.evidence.length===1?$m(e.classification):`${oh(e.groupId)} · ${$m(e.classification)} · ${e.evidence.length} memories`,e.consolidationId&&` · part of a consolidation`]})]})]},e.groupId))})]}):(0,Q.jsxs)(`div`,{className:`memory-list-state`,children:[(0,Q.jsx)(ph,{}),(0,Q.jsx)(`h2`,{children:`No reconciliation audit`}),(0,Q.jsx)(`p`,{children:`Run an authorized read-only audit first.`})]})})]}),(0,Q.jsxs)(`aside`,{className:`context-pane memory-detail-pane`,"aria-label":`Memory triage exception detail`,children:[t&&(0,Q.jsx)(`div`,{className:`context-resize-handle`,role:`separator`,"aria-label":`Resize memory triage detail`,"aria-orientation":`vertical`,"aria-valuemin":t.minimumWidth,"aria-valuemax":t.maximumWidth,"aria-valuenow":t.width,tabIndex:0,onKeyDown:t.onKeyDown,onPointerDown:t.onPointerDown,onPointerMove:t.onPointerMove}),M&&o&&o.status!==`applied`&&(k||M.consolidationId)?(0,Q.jsx)(Qm,{allowedProjects:e,anchor:M,availableGroups:c,consolidation:D.find(e=>e.consolidationId===M.consolidationId)??null,onAuthenticationFailure:n,onClose:()=>A(!1),onSaved:e=>{S(e),A(!1),_(e=>e+1)},planId:o.planId,token:i},`${M.groupId}:${M.consolidationId??`new`}:${M.decision.stateVersion}`):(0,Q.jsx)(mh,{allowedProjects:e,availableGroups:c,group:M,onAuthenticationFailure:n,onConsolidate:()=>A(!0),onSelectGroup:e=>{A(!1),d(e)},onSaved:()=>{S(`Exception decision saved.`),_(e=>e+1)},planId:o?.planId??null,readOnly:o?.status===`applied`,token:i},`${o?.planId??`none`}:${M?.groupId??`none`}:${M?.decision.stateVersion??0}`)]})]})}var gh={kind:``,lifecycle:``,projectId:``,scope:``,tag:``};function _h(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`circle`,{cx:`11`,cy:`11`,r:`7`,stroke:`currentColor`,strokeWidth:`2`}),(0,Q.jsx)(`path`,{d:`m16.25 16.25 4 4`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`2`})]})}function vh(e){return{kind:e.kind||void 0,lifecycle:e.lifecycle||void 0,projectId:e.projectId||void 0,scope:e.scope||void 0,tag:e.tag.trim()||void 0}}function yh(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`rect`,{x:`4`,y:`5`,width:`10`,height:`12`,rx:`1.5`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M17 8h1.5A1.5 1.5 0 0 1 20 9.5v9a1.5 1.5 0 0 1-1.5 1.5h-7A1.5 1.5 0 0 1 10 18.5V20`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M7 9h4M7 12.5h4`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`})]})}function bh(e){let t=new Date(e);return Number.isNaN(t.valueOf())?e:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}function xh(e){if(!e.retrievable)switch(e.exclusionReason){case`legacy_scope_quarantined`:return`Quarantined until its legacy scope is reviewed.`;case`invalid_scope_quarantined`:return`Quarantined because its stored scope is invalid.`;case`project_id_mismatch`:return`Unavailable outside project ${e.projectId??`unknown`}.`;case`project_scope_not_allowed`:return`Available only when project ${e.projectId??`unknown`} is active.`;case`task_scope_not_supported`:return`Task-scoped memories are not currently recalled.`;default:return`Not currently eligible for recall.`}return e.scope===`project`?`Available while project ${e.projectId??`unknown`} is active.`:e.scope===`task`?`Available in its assigned task context.`:`Available across your projects.`}function Sh(e){switch(e){case`explicit_creation`:return`This memory was saved explicitly, so no source conversation was linked.`;case`legacy_source`:return`This memory predates canonical source links.`;case`canonical_source_missing`:return`The canonical source conversation is no longer available.`;case`invalid_provenance`:return`The stored source reference is incomplete or invalid.`;case`source_not_authorized`:return`Your session cannot read the referenced source conversation.`;default:return`No canonical source conversation is available for this memory.`}}function Ch(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function wh(e){return e.split(/[,\n]/).map(e=>e.trim()).filter(Boolean)}function Th(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`memory-editor-${Date.now()}-${Math.random().toString(16).slice(2)}`}function Eh({allowedProjects:e,detail:t,onAuthenticationFailure:n,onClose:r,onReload:i,onSaved:a,token:o}){let s=Km(),c=t?.episode,[l,u]=(0,v.useState)(t?.content??``),[d,f]=(0,v.useState)((c?.tags??t?.tags??[]).join(`, `)),[p,m]=(0,v.useState)(`global`),[h,g]=(0,v.useState)(c?.goal??``),[_,y]=(0,v.useState)(c?.context??``),[b,x]=(0,v.useState)(c?.approach??``),[S,C]=(0,v.useState)(c?.outcome??``),[w,T]=(0,v.useState)(c?.outcomeQuality??`success`),[E,D]=(0,v.useState)(c?.lessons??``),[O,k]=(0,v.useState)((c?.actors??[]).join(`, `)),[A,j]=(0,v.useState)(!1),[M,N]=(0,v.useState)(null),[P,F]=(0,v.useState)(!1),[I]=(0,v.useState)(Th),L=t!==null,R=t?.kind===`episode`,ee=L?R?h!==(c?.goal??``)||_!==(c?.context??``)||b!==(c?.approach??``)||S!==(c?.outcome??``)||w!==(c?.outcomeQuality??`success`)||E!==(c?.lessons??``)||O!==(c?.actors??[]).join(`, `)||d!==(c?.tags??[]).join(`, `):l!==t.content||d!==t.tags.join(`, `):!!(l.trim()||d.trim()||p!==`global`);(0,v.useEffect)(()=>{if(!ee)return;let e=e=>{e.preventDefault()};return window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e)},[ee]);let z=async()=>{ee&&!await s(`Discard your unsaved memory changes?`)||r()},V=async e=>{e.preventDefault(),j(!0),N(null),F(!1);try{if(!t){let e=p.startsWith(`project:`)?{scope:`project`,projectId:p.slice(8)}:{scope:`global`},t=await Ln(o,{content:l,tags:wh(d),target:e,requestId:I});a(t.record,t.created?`Explicit memory created.`:`Memory was already created.`)}else if(R){let e=await Rn(o,{kind:`episode`,memoryId:t.memoryId,revision:t.revision,requestId:I,episode:{actors:wh(O),approach:b,context:_,goal:h,lessons:E.trim()||null,outcome:S,outcomeQuality:w,tags:wh(d)}});a(e.record,e.idempotentReplay?`Memory was already saved.`:`Episode updated and re-indexed.`)}else{let e=await Rn(o,{kind:`fact`,memoryId:t.memoryId,revision:t.revision,requestId:I,content:l,tags:wh(d)});a(e.record,e.idempotentReplay?`Memory was already saved.`:`Fact updated and re-indexed.`)}}catch(e){e instanceof ae?(F(!0),N(`This memory changed after you opened it. Reload the latest revision before saving again.`)):e instanceof B?(n(e.message),N(e.message)):N(e instanceof Error?e.message:`Could not save this memory.`)}finally{j(!1)}};return(0,Q.jsx)(`div`,{className:`memory-confirm-backdrop memory-editor-backdrop`,children:(0,Q.jsxs)(`section`,{className:`memory-editor`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`memory-editor-title`,children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:L?`Edit memory`:`New explicit memory`}),(0,Q.jsx)(`h2`,{id:`memory-editor-title`,children:L?`Correct ${R?`episode`:`fact`}`:`Create fact`})]}),(0,Q.jsx)(`button`,{type:`button`,className:`panel-icon-button`,"aria-label":`Close memory editor`,title:`Close memory editor`,disabled:A,onClick:()=>void z(),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsxs)(`form`,{onSubmit:e=>void V(e),children:[R?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{children:[`Goal `,(0,Q.jsx)(`span`,{children:`affects semantic retrieval`}),(0,Q.jsx)(`textarea`,{required:!0,maxLength:2e4,value:h,onChange:e=>g(e.target.value)})]}),(0,Q.jsxs)(`label`,{children:[`Context `,(0,Q.jsx)(`span`,{children:`affects semantic retrieval`}),(0,Q.jsx)(`textarea`,{required:!0,maxLength:2e4,value:_,onChange:e=>y(e.target.value)})]}),(0,Q.jsxs)(`label`,{children:[`Approach`,(0,Q.jsx)(`textarea`,{required:!0,maxLength:2e4,value:b,onChange:e=>x(e.target.value)})]}),(0,Q.jsxs)(`label`,{children:[`Outcome`,(0,Q.jsx)(`textarea`,{required:!0,maxLength:2e4,value:S,onChange:e=>C(e.target.value)})]}),(0,Q.jsxs)(`div`,{className:`memory-editor-grid`,children:[(0,Q.jsxs)(`label`,{children:[`Outcome quality`,(0,Q.jsxs)(`select`,{value:w,onChange:e=>T(e.target.value),children:[(0,Q.jsx)(`option`,{value:`success`,children:`Success`}),(0,Q.jsx)(`option`,{value:`partial`,children:`Partial`}),(0,Q.jsx)(`option`,{value:`failure`,children:`Failure`})]})]}),(0,Q.jsxs)(`label`,{children:[`Actors `,(0,Q.jsx)(`span`,{children:`comma-separated`}),(0,Q.jsx)(`input`,{maxLength:4096,value:O,onChange:e=>k(e.target.value)})]})]}),(0,Q.jsxs)(`label`,{children:[`Lessons `,(0,Q.jsx)(`span`,{children:`optional`}),(0,Q.jsx)(`textarea`,{maxLength:2e4,value:E,onChange:e=>D(e.target.value)})]})]}):(0,Q.jsxs)(`label`,{children:[`Content `,(0,Q.jsx)(`span`,{children:`affects semantic retrieval`}),(0,Q.jsx)(`textarea`,{required:!0,maxLength:1e5,value:l,onChange:e=>u(e.target.value)})]}),(0,Q.jsxs)(`label`,{children:[`Tags `,(0,Q.jsx)(`span`,{children:`comma- or line-separated`}),(0,Q.jsx)(`input`,{maxLength:4096,value:d,onChange:e=>f(e.target.value)})]}),!L&&(0,Q.jsxs)(`label`,{children:[`Recall scope`,(0,Q.jsxs)(`select`,{value:p,onChange:e=>m(e.target.value),children:[(0,Q.jsx)(`option`,{value:`global`,children:`Global scope`}),e.map(e=>(0,Q.jsx)(`option`,{value:`project:${e.projectId}`,children:e.displayName},e.projectId))]})]}),L&&(0,Q.jsx)(`p`,{className:`memory-editor-provenance`,children:`Source provenance and authority fields remain immutable. Saving regenerates the searchable vector.`}),M&&(0,Q.jsx)(`p`,{className:`memory-editor-error`,role:`alert`,children:M}),(0,Q.jsxs)(`footer`,{children:[P&&(0,Q.jsx)(`button`,{type:`button`,className:`quiet-button`,onClick:i,children:`Reload latest`}),(0,Q.jsx)(`button`,{type:`button`,className:`quiet-button`,disabled:A,onClick:()=>void z(),children:`Cancel`}),(0,Q.jsx)(`button`,{type:`submit`,disabled:A||L&&!ee,children:A?`Saving…`:L?`Save correction`:`Create memory`})]})]})]})})}function Dh({allowedProjects:e,busy:t,detail:n,error:r,loading:i,onDelete:a,onEdit:o,onMove:s,source:c,sourceError:l}){let[u,d]=(0,v.useState)(`global`);if(i)return(0,Q.jsx)(`p`,{className:`memory-detail-state`,role:`status`,children:`Loading memory details…`});if(r)return(0,Q.jsx)(`p`,{className:`memory-detail-state error`,role:`alert`,children:r});if(!n)return(0,Q.jsxs)(`div`,{className:`memory-detail-empty`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`◇`}),(0,Q.jsx)(`h2`,{children:`Select a memory`}),(0,Q.jsx)(`p`,{children:`Choose a fact or episode to inspect its content, scope, recall preview, and source.`})]});let f=n.lifecycle.authority===`legacy`;return(0,Q.jsxs)(`div`,{className:`memory-detail-scroll`,children:[(0,Q.jsxs)(`header`,{className:`memory-detail-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Memory detail`}),(0,Q.jsx)(`h2`,{children:n.kind===`episode`?`Episode`:`Fact`})]}),(0,Q.jsx)(`span`,{className:`memory-kind ${n.kind}`,children:n.kind})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Stored memory`}),(0,Q.jsx)(Nm,{body:n.content})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-lifecycle-history`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Lifecycle and provenance`}),(0,Q.jsxs)(`div`,{className:`memory-lifecycle-summary`,children:[(0,Q.jsx)(`span`,{className:`memory-review-state ${n.lifecycle.currentState}`,children:Ch(n.lifecycle.currentState)}),(0,Q.jsx)(`strong`,{children:n.lifecycle.authority===`canonical`?`Canonical authority`:`Legacy evidence`})]}),n.lifecycle.authority===`legacy`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{children:`This memory predates canonical lifecycle provenance and requires review. That does not mean it is false.`}),(0,Q.jsxs)(`p`,{className:`memory-review-gaps`,children:[`Missing: `,(n.lifecycle.migrationGaps??[`canonical provenance`]).map(Ch).join(`, `)]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`dl`,{className:`memory-metadata-grid`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Scope`}),(0,Q.jsx)(`dd`,{children:Ch(n.lifecycle.scope.kind)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Recorded`}),(0,Q.jsx)(`dd`,{children:bh(n.lifecycle.createdAt)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Revisions`}),(0,Q.jsx)(`dd`,{children:n.lifecycle.revisions.length})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`History events`}),(0,Q.jsx)(`dd`,{children:n.lifecycle.events.length})]})]}),(0,Q.jsxs)(`div`,{className:`memory-lifecycle-timeline`,children:[n.lifecycle.revisions.map(e=>(0,Q.jsxs)(`article`,{children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsx)(`span`,{className:`memory-review-state ${e.state}`,children:Ch(e.state)}),(0,Q.jsx)(`time`,{children:bh(e.storedAt)})]}),(0,Q.jsx)(Nm,{body:e.content}),(0,Q.jsx)(`p`,{children:e.reason}),(0,Q.jsxs)(`dl`,{className:`memory-metadata-grid`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Model`}),(0,Q.jsx)(`dd`,{children:e.model??`Not recorded`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Prompt`}),(0,Q.jsx)(`dd`,{children:e.promptVersion??`Not recorded`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Valid from`}),(0,Q.jsx)(`dd`,{children:e.validFrom?bh(e.validFrom):`Unbounded`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Valid until`}),(0,Q.jsx)(`dd`,{children:e.validUntil?bh(e.validUntil):`Current`})]})]})]},e.revisionId)),n.lifecycle.followups.map(e=>(0,Q.jsxs)(`article`,{children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsx)(`span`,{className:`memory-review-state historical`,children:Ch(e.relationship)}),(0,Q.jsx)(`time`,{children:bh(e.createdAt)})]}),(0,Q.jsx)(`p`,{children:e.reason}),(0,Q.jsxs)(`small`,{children:[e.sourceEpisodeId===n.lifecycle.identity?`Followed by`:`Follows`,` another episode.`]})]},`${e.sourceEpisodeId}:${e.targetEpisodeId}:${e.relationship}`))]})]})]}),n.episode&&Object.keys(n.episode).length>0&&(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Episode structure`}),(0,Q.jsx)(`dl`,{className:`memory-episode-fields`,children:Object.entries(n.episode).map(([e,t])=>(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:Ch(e)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Nm,{body:Array.isArray(t)?t.join(`, `):t??``})})]},e))})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section scope-card`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Recall scope`}),(0,Q.jsx)(`strong`,{children:n.scope.scope===`project`?`Project memory`:`${Ch(n.scope.scope)} memory`}),(0,Q.jsx)(`p`,{children:xh(n.scope)}),(0,Q.jsxs)(`dl`,{className:`memory-metadata-grid`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Speaker`}),(0,Q.jsx)(`dd`,{children:n.speaker})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Confidence`}),(0,Q.jsxs)(`dd`,{children:[Math.round(n.confidence*100),`%`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Source`}),(0,Q.jsx)(`dd`,{children:n.source})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Updated`}),(0,Q.jsx)(`dd`,{children:bh(n.updatedAt)})]})]})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section memory-management`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Manage memory`}),f&&(0,Q.jsx)(`p`,{className:`memory-review-gaps`,children:`This memory is waiting for legacy reconciliation and can't be changed yet.`}),(0,Q.jsxs)(`label`,{children:[`Move to`,(0,Q.jsxs)(`select`,{disabled:f,value:u,onChange:e=>d(e.target.value),children:[(0,Q.jsx)(`option`,{value:`global`,children:`Global scope`}),e.map(e=>(0,Q.jsx)(`option`,{value:`project:${e.projectId}`,children:e.displayName},e.projectId))]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`button`,{type:`button`,disabled:t||f,onClick:()=>o(n),children:`Edit memory…`}),(0,Q.jsx)(`button`,{type:`button`,disabled:t||f,onClick:()=>s(n.memoryId,u),children:`Move memory…`}),(0,Q.jsx)(`button`,{className:`danger`,type:`button`,disabled:t||f,onClick:()=>a(n.memoryId),children:`Forget memory…`})]})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section recall-preview`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Agent recall preview`}),(0,Q.jsx)(`p`,{children:`This compact record—not the rich stored episode above—is what Kai can place in an agent prompt when this memory is recalled.`}),(0,Q.jsx)(`pre`,{children:n.compactRecall})]}),(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Source conversation`}),l?(0,Q.jsx)(`p`,{className:`memory-source-unavailable`,role:`alert`,children:l}):c?c.status===`unavailable`?(0,Q.jsx)(`p`,{className:`memory-source-unavailable`,children:Sh(c.reason)}):(0,Q.jsxs)(`div`,{className:`memory-source-context`,children:[c.source&&(0,Q.jsxs)(`article`,{children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsx)(`strong`,{children:c.source.authorDisplayName}),(0,Q.jsx)(`time`,{children:bh(c.source.createdAt)})]}),(0,Q.jsx)(Nm,{body:c.source.body})]}),c.result&&(0,Q.jsxs)(`article`,{className:`agent`,children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsx)(`strong`,{children:c.result.authorDisplayName}),(0,Q.jsx)(`time`,{children:bh(c.result.createdAt)})]}),(0,Q.jsx)(Nm,{body:c.result.body})]})]}):(0,Q.jsx)(`p`,{className:`memory-source-unavailable`,role:`status`,children:`Loading source context…`})]}),n.tags.length>0&&(0,Q.jsxs)(`section`,{className:`memory-detail-section`,children:[(0,Q.jsx)(`p`,{className:`memory-section-label`,children:`Tags`}),(0,Q.jsx)(`div`,{className:`memory-tags`,children:n.tags.map(e=>(0,Q.jsx)(`span`,{children:e},e))})]})]})}function Oh({detailPanelLayout:e,initialMemoryId:t,onAuthenticationFailure:n,onClose:r,onSelectMemory:i,token:a}){let[o,s]=(0,v.useState)(null),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(gh),[f,p]=(0,v.useState)(gh),[m,h]=(0,v.useState)(``),[g,_]=(0,v.useState)(``),[y,b]=(0,v.useState)(`newest`),[x,S]=(0,v.useState)(`relevance`),[C,w]=(0,v.useState)([]),[T,E]=(0,v.useState)([]),[D,O]=(0,v.useState)(null),[k,A]=(0,v.useState)(!0),[j,M]=(0,v.useState)(!1),[N,P]=(0,v.useState)(null),[F,I]=(0,v.useState)(0),[L,R]=(0,v.useState)(0),[ee,z]=(0,v.useState)(t),[V,H]=(0,v.useState)(null),[te,U]=(0,v.useState)(null),[ne,re]=(0,v.useState)(t!==null),[W,ie]=(0,v.useState)(null),[ae,oe]=(0,v.useState)(null),[se,ce]=(0,v.useState)(!1),[le,ue]=(0,v.useState)(()=>new Set),[G,K]=(0,v.useState)(`global`),[q,de]=(0,v.useState)(null),[J,Y]=(0,v.useState)(!1),[fe,pe]=(0,v.useState)(null),[me,he]=(0,v.useState)(null),[X,ge]=(0,v.useState)(!1),[_e,ve]=(0,v.useState)(!1),ye=(0,v.useRef)([]);(0,v.useEffect)(()=>{z(t)},[t]);let be=(0,v.useCallback)((e,t)=>e instanceof B?(n(e.message),e.message):e instanceof Error?e.message:t,[n]);(0,v.useEffect)(()=>{let e=!1;return l(null),Kt(a).then(t=>{e||s(t)}).catch(t=>{e||l(be(t,`Could not load memory statistics.`))}),()=>{e=!0}},[be,F,a]),(0,v.useEffect)(()=>{let e=!1;return A(!0),P(null),O(null),(g?gn(a,g,{...vh(f),limit:50}):hn(a,{...vh(f),limit:50,order:y})).then(t=>{e||(`hits`in t?(E(t.hits),w([])):(w(t.records),E([]),O(t.nextCursor)))}).catch(t=>{e||(P(be(t,`Could not load memories.`)),w([]),E([]))}).finally(()=>{e||A(!1)}),()=>{e=!0}},[y,f,be,F,g,a]);let xe=(0,v.useMemo)(()=>{if(!g)return C;let e=[...T];return x!==`relevance`&&e.sort((e,t)=>{let n=e.record.updatedAt.localeCompare(t.record.updatedAt);return x===`newest`?-n:n}),e.map(e=>e.record)},[C,T,x,g]);(0,v.useEffect)(()=>{!ee&&xe[0]&&(z(xe[0].memoryId),i(xe[0].memoryId))},[xe,i,ee]),(0,v.useEffect)(()=>{if(!ee){H(null),ie(null),re(!1);return}let e=!1;return re(!0),U(null),oe(null),H(null),ie(null),Promise.allSettled([bn(a,ee),Bn(a,ee)]).then(([t,n])=>{e||(t.status===`fulfilled`?H(t.value):U(be(t.reason,`Could not load this memory.`)),n.status===`fulfilled`?ie(n.value):oe(be(n.reason,`Could not load source context.`)),re(!1))}),()=>{e=!0}},[L,be,ee,a]);let Se=(0,v.useMemo)(()=>o?Object.keys(o.byScope).filter(e=>e.startsWith(`project:`)).map(e=>e.slice(8)).filter(Boolean).sort():[],[o]),Ce=o?.allowedProjects??[],we=(0,v.useCallback)(e=>{z(e),i(e)},[i]),Te=()=>{ce(!1),z(null),w([]),E([]),O(null),ue(new Set),i(null)},Ee=e=>{ue(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},De=()=>{ce(!1),ue(new Set)},Oe=e=>{let t={succeeded:0,not_found:0,stale:0,failed:0,awaiting_reconciliation:0};for(let n of e.results)t[n.outcome]+=1;let n=[`${t.succeeded} succeeded`];return t.stale&&n.push(`${t.stale} became stale`),t.not_found&&n.push(`${t.not_found} no longer existed`),t.failed&&n.push(`${t.failed} failed`),t.awaiting_reconciliation&&n.push(`${t.awaiting_reconciliation} ${t.awaiting_reconciliation===1?`is`:`are`} waiting for legacy reconciliation`),`${e.operation===`delete`?`Forget`:`Scope change`}: ${n.join(`, `)}.`},ke=async()=>{if(q){Y(!0),pe(null);try{let e;if(q.operation===`delete`)e=q.ids.length===1?await fn(a,q.ids[0]):await pn(a,q.ids);else{let t=q.target??`global`,n=t.startsWith(`project:`)?{scope:`project`,projectId:t.slice(8)}:{scope:`global`};e=q.ids.length===1?await un(a,q.ids[0],n):await dn(a,q.ids,n)}pe(Oe(e));let t=new Set(e.results.filter(e=>e.outcome!==`failed`).map(e=>e.memoryId));ue(e=>new Set([...e].filter(e=>!t.has(e)))),e.results.every(e=>e.outcome!==`failed`)&&(ce(!1),ue(new Set)),q.operation===`delete`&&(w(e=>e.filter(e=>!t.has(e.memoryId))),E(e=>e.filter(e=>!t.has(e.record.memoryId)))),ee&&t.has(ee)&&q.operation===`delete`&&(z(null),i(null)),de(null),I(e=>e+1),R(e=>e+1)}catch(e){pe(be(e,`Could not update memories.`)),de(null)}finally{Y(!1)}}},Ae=q?.ids.map(e=>({memoryId:e,preview:xe.find(t=>t.memoryId===e)?.preview??(V?.memoryId===e?V.preview:e)}))??[],je=async()=>{if(!(!D||j||g)){M(!0),P(null);try{let e=await hn(a,{...vh(f),cursor:D,limit:50,order:y});w(t=>[...t,...e.records]),O(e.nextCursor)}catch(e){P(be(e,`Could not load more memories.`))}finally{M(!1)}}},Me=e=>{e.preventDefault(),Te(),p({...u,tag:u.tag.trim()})},Ne=e=>{e.preventDefault(),Te(),_(m.trim())},Pe=()=>{Te(),d(gh),p(gh)},Fe=(e,t)=>{let n=e.key===`ArrowDown`?Math.min(t+1,xe.length-1):e.key===`ArrowUp`?Math.max(t-1,0):e.key===`Home`?0:e.key===`End`?xe.length-1:-1;if(n<0||n===t)return;e.preventDefault();let r=xe[n];r&&(se||we(r.memoryId),ye.current[n]?.focus())},Ie=g?T.length:C.length,Le=o?o.unresolvedConflicts+o.projectionFailures:0;return _e?(0,Q.jsx)(Um,{detailPanelLayout:e,onAuthenticationFailure:n,onBack:()=>ve(!1),onChanged:()=>I(e=>e+1),onOpenMemory:e=>{ve(!1),we(e)},token:a}):X?(0,Q.jsx)(hh,{allowedProjects:Ce,detailPanelLayout:e,onAuthenticationFailure:n,onBack:()=>ge(!1),token:a}):(0,Q.jsxs)(`section`,{className:`memory-workspace`,"aria-label":`Memory workspace`,children:[(0,Q.jsxs)(`div`,{className:`memory-browser-pane`,children:[(0,Q.jsxs)(`header`,{className:`memory-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`breadcrumbs`,children:`Kai Workshop / Memory`}),(0,Q.jsx)(`h1`,{children:`Memory`})]}),(0,Q.jsxs)(`div`,{className:`memory-header-actions`,children:[(0,Q.jsxs)(`button`,{className:`panel-icon-button fact-review-button`,type:`button`,"aria-label":Le>0?`Fact review, ${Le} waiting on you`:`Fact review`,title:`Fact review`,onClick:()=>ve(!0),children:[(0,Q.jsx)(yh,{}),Le>0&&(0,Q.jsx)(`span`,{className:`fact-review-badge`,"aria-hidden":`true`,children:Le})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Review legacy memory`,title:`Review legacy memory`,onClick:()=>ge(!0),children:(0,Q.jsx)(ph,{})}),(0,Q.jsx)(`button`,{className:`nav-add-button memory-add-button`,type:`button`,"aria-label":`Add fact`,title:`Add fact`,onClick:()=>he(`create`),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`})}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Back to conversation`,title:`Back to conversation`,onClick:r,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})]})]}),(0,Q.jsxs)(`div`,{className:`memory-browser-scroll`,children:[(0,Q.jsx)(`section`,{className:`memory-stats`,"aria-label":`Memory statistics`,children:o?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:o.total}),(0,Q.jsx)(`span`,{children:`Total memories`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:o.facts}),(0,Q.jsx)(`span`,{children:`Facts`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:o.episodes}),(0,Q.jsx)(`span`,{children:`Episodes`})]})]}):c?(0,Q.jsx)(`button`,{type:`button`,className:`memory-retry`,onClick:()=>I(e=>e+1),children:`Statistics unavailable · Retry`}):(0,Q.jsx)(`p`,{role:`status`,children:`Loading corpus summary…`})}),(0,Q.jsxs)(`form`,{className:`memory-search`,onSubmit:Ne,role:`search`,children:[(0,Q.jsx)(`label`,{htmlFor:`memory-query`,children:`Search memories`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`input`,{id:`memory-query`,type:`search`,maxLength:2e3,value:m,onChange:e=>h(e.target.value),placeholder:`Describe what you remember…`}),(0,Q.jsx)(`button`,{className:`memory-search-submit`,type:`submit`,"aria-label":`Search`,title:`Search`,children:(0,Q.jsx)(_h,{})}),g&&(0,Q.jsx)(`button`,{type:`button`,className:`quiet-button`,onClick:()=>{Te(),h(``),_(``)},children:`Clear search`})]})]}),(0,Q.jsxs)(`form`,{className:`memory-filters`,onSubmit:Me,children:[(0,Q.jsxs)(`label`,{children:[`Lifecycle`,(0,Q.jsxs)(`select`,{value:u.lifecycle,onChange:e=>d(t=>({...t,lifecycle:e.target.value})),children:[(0,Q.jsx)(`option`,{value:``,children:`Current projection and legacy`}),(0,Q.jsx)(`option`,{value:`active`,children:`Active current facts`}),(0,Q.jsx)(`option`,{value:`historical`,children:`History-bearing facts and episodes`}),(0,Q.jsx)(`option`,{value:`legacy`,children:`Legacy memories requiring review`})]})]}),(0,Q.jsxs)(`label`,{children:[`Kind`,(0,Q.jsxs)(`select`,{value:u.kind,onChange:e=>d(t=>({...t,kind:e.target.value})),children:[(0,Q.jsx)(`option`,{value:``,children:`Facts and episodes`}),(0,Q.jsx)(`option`,{value:`fact`,children:`Facts`}),(0,Q.jsx)(`option`,{value:`episode`,children:`Episodes`})]})]}),(0,Q.jsxs)(`label`,{children:[`Scope`,(0,Q.jsxs)(`select`,{value:u.scope,onChange:e=>d(t=>({...t,scope:e.target.value})),children:[(0,Q.jsx)(`option`,{value:``,children:`Every scope`}),(0,Q.jsx)(`option`,{value:`global`,children:`Global`}),(0,Q.jsx)(`option`,{value:`project`,children:`Project`}),(0,Q.jsx)(`option`,{value:`task`,children:`Task`})]})]}),(0,Q.jsxs)(`label`,{children:[`Project`,(0,Q.jsxs)(`select`,{value:u.projectId,onChange:e=>d(t=>({...t,projectId:e.target.value,scope:e.target.value?`project`:t.scope})),children:[(0,Q.jsx)(`option`,{value:``,children:`Every project`}),Se.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Q.jsxs)(`label`,{children:[`Tag`,(0,Q.jsx)(`input`,{value:u.tag,maxLength:128,onChange:e=>d(t=>({...t,tag:e.target.value})),placeholder:`e.g. preference`})]}),(0,Q.jsxs)(`div`,{className:`memory-filter-actions`,children:[(0,Q.jsx)(`button`,{type:`submit`,children:`Apply filters`}),(0,Q.jsx)(`button`,{type:`button`,className:`quiet-button`,onClick:Pe,children:`Clear filters`})]})]}),(0,Q.jsxs)(`div`,{className:`memory-results-heading`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:g?`Semantic matches`:`Memory corpus`}),(0,Q.jsx)(`h2`,{children:k?`Loading…`:`${Ie} ${g?`matches`:`loaded`}`})]}),(0,Q.jsxs)(`div`,{className:`memory-results-controls`,children:[(0,Q.jsxs)(`label`,{children:[`Sort`,g?(0,Q.jsxs)(`select`,{value:x,onChange:e=>S(e.target.value),children:[(0,Q.jsx)(`option`,{value:`relevance`,children:`Relevance`}),(0,Q.jsx)(`option`,{value:`newest`,children:`Newest first`}),(0,Q.jsx)(`option`,{value:`oldest`,children:`Oldest first`})]}):(0,Q.jsxs)(`select`,{value:y,onChange:e=>b(e.target.value),children:[(0,Q.jsx)(`option`,{value:`newest`,children:`Newest first`}),(0,Q.jsx)(`option`,{value:`oldest`,children:`Oldest first`})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`quiet-button memory-selection-toggle`,disabled:k||xe.length===0||J,onClick:()=>{se?De():(ue(new Set),ce(!0))},children:se?`Cancel selection`:`Select memories`})]})]}),fe&&(0,Q.jsx)(`p`,{className:`memory-mutation-report`,role:`status`,children:fe}),se&&(0,Q.jsxs)(`section`,{className:`memory-bulk-actions`,"aria-label":`Selected memory actions`,children:[(0,Q.jsxs)(`strong`,{children:[le.size,` selected`]}),(0,Q.jsxs)(`select`,{"aria-label":`Move selected memories to`,value:G,onChange:e=>K(e.target.value),children:[(0,Q.jsx)(`option`,{value:`global`,children:`Global scope`}),Ce.map(e=>(0,Q.jsx)(`option`,{value:`project:${e.projectId}`,children:e.displayName},e.projectId))]}),(0,Q.jsx)(`button`,{type:`button`,disabled:le.size===0||J,onClick:()=>de({ids:[...le],operation:`move_scope`,target:G}),children:`Move selected…`}),(0,Q.jsx)(`button`,{className:`danger`,type:`button`,disabled:le.size===0||J,onClick:()=>de({ids:[...le],operation:`delete`}),children:`Forget selected…`})]}),N?(0,Q.jsxs)(`div`,{className:`memory-list-state error`,role:`alert`,children:[(0,Q.jsx)(`p`,{children:N}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>I(e=>e+1),children:`Retry`})]}):k?(0,Q.jsx)(`p`,{className:`memory-list-state`,role:`status`,children:`Loading memories…`}):xe.length===0?(0,Q.jsxs)(`div`,{className:`memory-list-state`,children:[(0,Q.jsx)(`h3`,{children:`No memories found`}),(0,Q.jsx)(`p`,{children:`Clear search or filters to broaden this view.`})]}):(0,Q.jsx)(`div`,{className:`memory-record-list`,role:`listbox`,"aria-label":`Memory results`,children:xe.map((e,t)=>(0,Q.jsxs)(`div`,{className:`memory-record-row ${se?`selecting`:``}`,children:[se&&(0,Q.jsx)(`input`,{type:`checkbox`,"aria-label":`Select ${e.preview||e.memoryId}`,checked:le.has(e.memoryId),onChange:()=>Ee(e.memoryId)}),(0,Q.jsxs)(`button`,{ref:e=>{ye.current[t]=e},type:`button`,role:`option`,"aria-selected":se?le.has(e.memoryId):ee===e.memoryId,className:`memory-record ${(se?le.has(e.memoryId):ee===e.memoryId)?`selected`:``}`,onClick:()=>{se?Ee(e.memoryId):we(e.memoryId)},onKeyDown:e=>Fe(e,t),children:[(0,Q.jsx)(`span`,{className:`memory-kind ${e.kind}`,children:e.kind}),(0,Q.jsxs)(`span`,{className:`memory-record-copy`,children:[(0,Q.jsx)(`strong`,{children:e.preview||`Untitled memory`}),(0,Q.jsx)(`small`,{children:xh(e.scope)}),e.tags.length>0&&(0,Q.jsx)(`span`,{className:`memory-tags compact`,children:e.tags.slice(0,3).map(e=>(0,Q.jsx)(`span`,{children:e},e))})]}),(0,Q.jsx)(`time`,{children:bh(e.updatedAt)})]},e.memoryId)]},e.memoryId))}),D&&!g&&!N&&(0,Q.jsx)(`button`,{className:`memory-load-more`,type:`button`,disabled:j,onClick:()=>void je(),children:j?`Loading…`:`Load more memories`})]})]}),(0,Q.jsxs)(`aside`,{className:`context-pane memory-detail-pane`,"aria-label":se?`Memory selection`:`Memory detail`,children:[e&&(0,Q.jsx)(`div`,{className:`context-resize-handle`,role:`separator`,"aria-label":`Resize memory detail`,"aria-orientation":`vertical`,"aria-valuemin":e.minimumWidth,"aria-valuemax":e.maximumWidth,"aria-valuenow":e.width,tabIndex:0,onKeyDown:e.onKeyDown,onPointerDown:e.onPointerDown,onPointerMove:e.onPointerMove}),se?(0,Q.jsxs)(`div`,{className:`memory-selection-summary`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`◇`}),(0,Q.jsx)(`p`,{className:`overline`,children:`Batch selection`}),(0,Q.jsx)(`h2`,{children:le.size===0?`Choose memories`:`${le.size} ${le.size===1?`memory`:`memories`} selected`}),(0,Q.jsx)(`p`,{children:`Select the memories you want to move or forget. Cancel selection to return to the current memory details.`})]}):(0,Q.jsx)(Dh,{allowedProjects:Ce,busy:J,detail:V,error:te,loading:ne,onDelete:e=>de({ids:[e],operation:`delete`}),onEdit:e=>he(e),onMove:(e,t)=>de({ids:[e],operation:`move_scope`,target:t}),source:W,sourceError:ae})]}),q&&(0,Q.jsx)(`div`,{className:`memory-confirm-backdrop`,children:(0,Q.jsxs)(`section`,{className:`memory-confirm`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`memory-confirm-title`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Confirm memory change`}),(0,Q.jsx)(`h2`,{id:`memory-confirm-title`,children:q.operation===`delete`?`Forget ${q.ids.length} ${q.ids.length===1?`memory`:`memories`}?`:`Move ${q.ids.length} ${q.ids.length===1?`memory`:`memories`}?`}),(0,Q.jsx)(`p`,{children:q.operation===`delete`?`These records will be permanently removed from recall and cannot be restored here.`:`Their recall scope will change to ${q.target?.startsWith(`project:`)?`project ${q.target.slice(8)}`:`global`}.`}),(0,Q.jsx)(`ul`,{children:Ae.map(e=>(0,Q.jsx)(`li`,{children:e.preview},e.memoryId))}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`quiet-button`,disabled:J,onClick:()=>de(null),children:`Cancel`}),(0,Q.jsx)(`button`,{type:`button`,className:q.operation===`delete`?`danger`:``,disabled:J,onClick:()=>void ke(),children:J?`Applying…`:q.operation===`delete`?`Forget permanently`:`Confirm move`})]})]})}),me&&(0,Q.jsx)(Eh,{allowedProjects:Ce,detail:me===`create`?null:me,onAuthenticationFailure:n,onClose:()=>he(null),onReload:()=>{he(null),R(e=>e+1),I(e=>e+1)},onSaved:(e,t)=>{he(null),H(e),z(e.memoryId),i(e.memoryId),pe(t),R(e=>e+1),I(e=>e+1)},token:a})]})}function kh(e){return(0,Q.jsx)(Gm,{children:(0,Q.jsx)(Oh,{...e})})}function Ah(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M3.5 6.5h6l2 2h9v10h-17z`,stroke:`currentColor`,strokeLinejoin:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M12 11v5m-2.5-2.5h5`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`})]})}function jh(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M3.5 6.5h6l2 2h9v10h-17z`,stroke:`currentColor`,strokeLinejoin:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M12 11v5m-2.5-2.5h5`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M7 3.5h10`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`})]})}function Mh(e,t){return e instanceof Error&&e.message?e.message:t}function Nh(e,t){if(t)return`Private home`;switch(e){case`principal_created`:return`Created by you`;case`principal_added`:return`Added by you`;case`legacy_migrated`:return`Migrated access`;case`profile`:return`Runtime profile`;default:return e?e.replaceAll(`_`,` `):`Authorized workspace`}}function Ph(e){switch(e.provenance){case`operator_pinned`:return`Operator pinned`;case`principal_created`:return`Created with this workspace`;case`principal_registered`:return`Registered by you`;case`legacy_migrated`:return`Migrated registration`}}function Fh({detailPanelLayout:e,onAuthenticationFailure:t,onChannelAccessFailure:n,onClose:r,session:i}){let a=Km(),[o,s]=(0,v.useState)(null),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(null),[f,p]=(0,v.useState)(null),[m,h]=(0,v.useState)(!0),[g,_]=(0,v.useState)(!1),[y,b]=(0,v.useState)(null),[x,S]=(0,v.useState)(null),[C,w]=(0,v.useState)(!1),[T,E]=(0,v.useState)(``),[D,O]=(0,v.useState)(!1),[k,A]=(0,v.useState)(``),[j,M]=(0,v.useState)(!1),[N,P]=(0,v.useState)(``),[F,I]=(0,v.useState)(``),L=(0,v.useCallback)(e=>e instanceof B?(t(e.message),!0):e instanceof V&&(n(e.message),!0),[t,n]),R=(0,v.useCallback)(async(e=null)=>{h(!0),b(null);try{let[t,n,r]=await Promise.all([Vn(i),Pr(i),yr(i)]);s(t),l(n),d(r),p(n=>{let r=e??n??t.workspace;return t.workspaces.some(e=>e.path===r)?r:t.workspace})}catch(e){L(e)||b(Mh(e,`Could not load workspaces.`))}finally{h(!1)}},[L,i]);(0,v.useEffect)(()=>{R()},[R]);let ee=(0,v.useMemo)(()=>{if(!o)return[];let e=new Map((c?.grants??[]).map(e=>[e.path,e])),t=new Map;for(let e of u?.projects??[])for(let n of e.workspaceRoots)t.set(n,e);return o.workspaces.map(n=>({grant:e.get(n.path)??null,option:n,project:t.get(n.path)??null}))},[c,u,o]),z=ee.find(e=>e.option.path===f)??ee[0]??null,H=async e=>{if(e.preventDefault(),!(!o||g||!T.trim())){_(!0),b(null),S(null);try{let e=await Mr(i,T.trim(),o.revision),t=[e.directoryCreated?`Workspace created and selected.`:`That workspace already existed and is now selected.`];e.gitReady||t.push(`Git initialization failed; the workspace is still usable.`),e.memoryProjectRegistered||t.push(e.memoryProjectNote),w(!1),E(``),S(t.join(` `)),await R(e.path)}catch(e){e instanceof W?(await R(),b(`Workspace state changed elsewhere. The latest catalogue has been loaded.`)):L(e)||b(Mh(e,`Could not create workspace.`))}finally{_(!1)}}},te=async e=>{e.preventDefault();let t=k.trim();if(!(!t||g)){_(!0),b(null),S(null);try{let e=await Fr(i,t);O(!1),A(``),S(e.mutation?.changed?`Existing workspace access added.`:`That workspace was already available.`),await R(t)}catch(e){L(e)||b(Mh(e,`Could not add workspace access.`))}finally{_(!1)}}},U=async()=>{if(!(!z?.grant?.removable||g||!await a(`Remove access to ${z.option.name}? The directory and its files will not be deleted.`))){_(!0),b(null),S(null);try{let e=await Ir(i,z.option.path);S(e.mutation?.changed?`Access to ${z.option.name} was removed. The directory was not deleted.`:`Access to ${z.option.name} was already absent.`),await R()}catch(e){L(e)||b(Mh(e,`Could not remove workspace access.`))}finally{_(!1)}}},ne=async e=>{if(e.preventDefault(),!(!o||!z?.option.deletable||N!==z.option.name||g)){_(!0),b(null),S(null);try{let e=await Nr(i,z.option.name,N,o.revision);M(!1),P(``),S(e.directoryDeleted?`Workspace ${z.option.name} was permanently deleted.`:`Workspace ${z.option.name} was already absent; its Kai records were cleaned.`),await R()}catch(e){e instanceof W?(await R(),b(`Workspace state changed elsewhere. The latest catalogue has been loaded.`)):L(e)||b(Mh(e,`Could not delete workspace.`))}finally{_(!1)}}},re=async e=>{if(e.preventDefault(),!(!u||!z||!F.trim()||g)){_(!0),b(null),S(null);try{let e=await br(i,u.revision,F.trim(),z.option.path);d(e),I(``),S(e.mutation?.note??`Memory project registered.`)}catch(e){e instanceof W?(await R(z.option.path),b(`Memory projects changed elsewhere. The latest registry has been loaded.`)):L(e)||b(Mh(e,`Could not register memory project.`))}finally{_(!1)}}},ie=async()=>{if(!(!u||!z?.project?.removable||g||!await a(`Unregister memory project ${z.project.projectId}? Existing memories will not be deleted.`))){_(!0),b(null),S(null);try{let e=await xr(i,u.revision,z.project.projectId);d(e),S(e.mutation?.note??`Memory project unregistered.`)}catch(e){e instanceof W?(await R(z.option.path),b(`Memory projects changed elsewhere. The latest registry has been loaded.`)):L(e)||b(Mh(e,`Could not unregister memory project.`))}finally{_(!1)}}};return(0,Q.jsxs)(`main`,{className:`workspaces-workspace`,"aria-label":`Workspaces`,children:[(0,Q.jsxs)(`section`,{className:`workspaces-browser-pane`,children:[(0,Q.jsxs)(`header`,{className:`workspaces-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`breadcrumbs`,children:`Kai Workshop / Workspaces`}),(0,Q.jsx)(`h1`,{children:`Workspaces`})]}),(0,Q.jsxs)(`div`,{className:`workspaces-header-actions`,children:[(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Create workspace`,title:`Create private workspace`,disabled:g,onClick:()=>w(!0),children:(0,Q.jsx)(Ah,{})}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Add existing workspace`,title:`Add existing workspace`,disabled:g,onClick:()=>O(!0),children:(0,Q.jsx)(jh,{})}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Back to conversation`,title:`Back to conversation`,onClick:r,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})]})]}),(x||y)&&(0,Q.jsxs)(`div`,{className:`workspaces-notices`,"aria-live":`polite`,children:[x&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:x}),y&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:y})]}),(0,Q.jsx)(`section`,{className:`workspace-catalogue`,"aria-label":`Authorized workspaces`,children:m?(0,Q.jsx)(`p`,{className:`workspaces-empty`,children:`Loading workspaces…`}):ee.length===0?(0,Q.jsx)(`p`,{className:`workspaces-empty`,children:`No authorized workspaces.`}):(0,Q.jsx)(`ul`,{children:ee.map(e=>(0,Q.jsx)(`li`,{children:(0,Q.jsxs)(`button`,{className:e.option.path===z?.option.path?`selected`:``,type:`button`,onClick:()=>p(e.option.path),children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.option.name}),e.option.current&&(0,Q.jsx)(`span`,{className:`workspace-current`,children:`Current`})]}),(0,Q.jsx)(`small`,{children:e.option.path}),(0,Q.jsxs)(`small`,{children:[Nh(e.grant?.provenance??null,e.option.home),e.grant&&!e.grant.available?` · unavailable`:``]})]})},e.option.path))})})]}),(0,Q.jsxs)(`aside`,{className:`context-pane workspace-detail`,"aria-label":`Workspace detail`,children:[e&&(0,Q.jsx)(`div`,{className:`context-resize-handle`,role:`separator`,"aria-label":`Resize workspace detail`,"aria-orientation":`vertical`,"aria-valuemin":e.minimumWidth,"aria-valuemax":e.maximumWidth,"aria-valuenow":e.width,tabIndex:0,onKeyDown:e.onKeyDown,onPointerDown:e.onPointerDown,onPointerMove:e.onPointerMove}),(0,Q.jsx)(`div`,{className:`workspace-detail-scroll`,"aria-live":`polite`,children:z?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`workspace-detail-heading`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Selected workspace`}),(0,Q.jsx)(`h2`,{children:z.option.name})]}),z.option.current&&(0,Q.jsx)(`span`,{className:`workspace-status`,children:`Current`})]}),(0,Q.jsxs)(`dl`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Path`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:z.option.path})})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Access`}),(0,Q.jsx)(`dd`,{children:Nh(z.grant?.provenance??null,z.option.home)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Availability`}),(0,Q.jsx)(`dd`,{children:z.grant?.available===!1?`Unavailable`:`Available`})]})]}),(0,Q.jsxs)(`section`,{className:`workspace-project-detail`,children:[(0,Q.jsx)(`h3`,{children:`Memory project`}),z.project?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`strong`,{children:z.project.displayName})}),(0,Q.jsxs)(`p`,{children:[Ph(z.project),z.project.available?``:` · unavailable`]}),z.project.removable&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:g,onClick:()=>void ie(),children:`Unregister project`})]}):(0,Q.jsxs)(`form`,{className:`memory-project-registration`,onSubmit:e=>void re(e),children:[(0,Q.jsx)(`p`,{children:`Not registered as a memory project.`}),(0,Q.jsx)(`label`,{htmlFor:`workspace-project-name`,children:`Project name`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`input`,{id:`workspace-project-name`,type:`text`,maxLength:64,pattern:`[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}`,placeholder:z.option.name.toLowerCase().replaceAll(/[^a-z0-9_-]/g,`-`),value:F,disabled:g,onChange:e=>I(e.target.value)}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`submit`,"aria-label":`Register memory project`,title:`Register memory project`,disabled:g||!F.trim(),children:(0,Q.jsx)(Ah,{})})]})]})]}),(z.grant?.removable||z.option.deletable)&&(0,Q.jsxs)(`section`,{className:`workspace-detail-actions`,children:[(0,Q.jsx)(`h3`,{children:`Workspace actions`}),z.grant?.removable&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:g||z.option.current,title:z.option.current?`Switch away from this workspace before removing access`:void 0,onClick:()=>void U(),children:`Remove access`}),z.option.deletable&&(0,Q.jsx)(`button`,{className:`danger-button`,type:`button`,disabled:g,onClick:()=>{P(``),M(!0)},children:`Delete permanently`})]})]}):(0,Q.jsx)(`p`,{className:`workspaces-empty`,children:`Select a workspace.`})})]}),C&&o&&(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog workspace-creation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`create-workspace-title`,children:[(0,Q.jsxs)(`header`,{className:`workspace-creation-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Private workspace`}),(0,Q.jsx)(`h2`,{id:`create-workspace-title`,children:`Create workspace`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close workspace creation`,title:`Close workspace creation`,disabled:g,onClick:()=>{w(!1),E(``)},children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsx)(`p`,{children:`This creates a private directory inside your Kai home.`}),(0,Q.jsxs)(`form`,{onSubmit:e=>void H(e),children:[(0,Q.jsx)(`label`,{htmlFor:`workspace-name`,children:`Workspace name`}),(0,Q.jsx)(`input`,{id:`workspace-name`,type:`text`,autoFocus:!0,maxLength:64,value:T,disabled:g,onChange:e=>E(e.target.value)}),(0,Q.jsx)(`div`,{className:`form-actions`,children:(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:g||!T.trim(),children:g?`Creating…`:`Create workspace`})})]})]})}),D&&(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog workspace-creation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`add-existing-workspace-title`,children:[(0,Q.jsxs)(`header`,{className:`workspace-creation-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Existing directory`}),(0,Q.jsx)(`h2`,{id:`add-existing-workspace-title`,children:`Add existing workspace`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close existing workspace`,title:`Close existing workspace`,disabled:g,onClick:()=>{O(!1),A(``)},children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsx)(`p`,{children:`This grants Kai access to a directory that already exists. It does not create, move, or delete files.`}),(0,Q.jsxs)(`form`,{onSubmit:e=>void te(e),children:[(0,Q.jsx)(`label`,{htmlFor:`workspace-existing-path`,children:`Absolute directory path`}),(0,Q.jsx)(`input`,{id:`workspace-existing-path`,type:`text`,autoFocus:!0,value:k,disabled:g,placeholder:`/Users/you/projects/example`,autoCapitalize:`none`,autoCorrect:`off`,onChange:e=>A(e.target.value)}),(0,Q.jsx)(`div`,{className:`form-actions`,children:(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:g||!k.trim(),children:g?`Adding…`:`Add workspace access`})})]})]})}),j&&z&&(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog workspace-creation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`delete-workspace-title`,children:[(0,Q.jsxs)(`header`,{className:`workspace-creation-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Permanent deletion`}),(0,Q.jsx)(`h2`,{id:`delete-workspace-title`,children:`Delete workspace`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close workspace deletion`,title:`Close workspace deletion`,disabled:g,onClick:()=>{M(!1),P(``)},children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsxs)(`p`,{children:[`This permanently deletes `,(0,Q.jsx)(`strong`,{children:z.option.name}),` and removes it from Kai.`]}),(0,Q.jsxs)(`form`,{onSubmit:e=>void ne(e),children:[(0,Q.jsxs)(`label`,{htmlFor:`workspace-delete-confirmation`,children:[`Type `,(0,Q.jsx)(`strong`,{children:z.option.name}),` to confirm`]}),(0,Q.jsx)(`input`,{id:`workspace-delete-confirmation`,type:`text`,autoFocus:!0,value:N,disabled:g,onChange:e=>P(e.target.value)}),(0,Q.jsx)(`div`,{className:`form-actions`,children:(0,Q.jsx)(`button`,{className:`danger-button`,type:`submit`,disabled:g||N!==z.option.name,children:g?`Deleting…`:`Delete permanently`})})]})]})})]})}function Ih(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M6 6l12 12M18 6 6 18`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`})})}function Lh(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`circle`,{cx:`12`,cy:`12`,r:`8.5`,stroke:`currentColor`,strokeWidth:`1.7`}),(0,Q.jsx)(`path`,{d:`M12 7.5v5l3.2 2`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.7`})]})}function Rh(e){if(!e)return`Not currently scheduled`;let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function zh(e){let t;try{t=JSON.parse(e.scheduleData)}catch{return e.scheduleType}if(!t||typeof t!=`object`)return e.scheduleType;let n=t;if(e.scheduleType===`once`)return typeof n.run_at==`string`?`Once · ${Rh(n.run_at)}`:`Once`;if(e.scheduleType===`interval`){let e=n.seconds;return typeof e==`number`?e%3600==0?`Every ${e/3600} hour${e===3600?``:`s`}`:e%60==0?`Every ${e/60} minute${e===60?``:`s`}`:`Every ${e} seconds`:`Recurring interval`}let r=Array.isArray(n.times)?n.times.filter(e=>typeof e==`string`):[];return r.length?`Daily · ${r.join(`, `)} UTC`:`Daily`}function Bh(e){return e===`workshop_client`?`Workshop`:e.charAt(0).toUpperCase()+e.slice(1).replaceAll(`_`,` `)}function Vh({detailPanelLayout:e,onAuthenticationFailure:t,onClose:n,principalEvents:r,session:i}){let a=Km(),[o,s]=(0,v.useState)([]),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(!0),[f,p]=(0,v.useState)(!1),[m,h]=(0,v.useState)(null),[g,_]=(0,v.useState)(null),y=(0,v.useCallback)(async()=>{d(!0);try{let e=await vi(i);s(e),l(t=>e.some(e=>e.id===t)?t:e[0]?.id??null),h(null)}catch(e){e instanceof B?t(e.message):h(e instanceof Error?e.message:`Could not load scheduled jobs.`)}finally{d(!1)}},[t,i]);(0,v.useEffect)(()=>{y()},[y]),(0,v.useEffect)(()=>r.subscribe(e=>{(e.kind===`synchronize`||e.batch.changes.some(e=>e.jobChanges.length>0))&&y()}),[r,y]);let b=(0,v.useMemo)(()=>o.find(e=>e.id===c)??null,[o,c]),x=o.filter(e=>e.scheduleType===`once`),S=o.filter(e=>e.scheduleType!==`once`),C=async()=>{if(!(!b||f||!await a(`Cancel ${b.name}? Its active schedule will be removed, while existing conversation and delivery history will remain.`))){p(!0),h(null),_(null);try{await yi(i,b.id,`workshop-job-cancel-${b.id}-${Date.now()}`),_(`${b.name} was cancelled.`),await y()}catch(e){h(e instanceof Error?e.message:`Could not cancel scheduled job.`)}finally{p(!1)}}},w=(e,t)=>t.length?(0,Q.jsxs)(`section`,{className:`scheduled-job-group`,children:[(0,Q.jsx)(`h2`,{children:e}),(0,Q.jsx)(`ul`,{children:t.map(e=>(0,Q.jsx)(`li`,{children:(0,Q.jsxs)(`button`,{className:e.id===c?`selected`:``,type:`button`,onClick:()=>l(e.id),children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.name}),(0,Q.jsx)(`span`,{className:`scheduled-job-status`,children:`Active`})]}),(0,Q.jsx)(`small`,{children:zh(e)}),(0,Q.jsxs)(`small`,{children:[e.jobType===`reminder`?`Reminder`:`Agent task`,` · `,e.agentName]})]})},e.id))})]}):null;return(0,Q.jsxs)(`main`,{className:`workspaces-workspace scheduled-jobs-workspace`,"aria-label":`Scheduled jobs`,children:[(0,Q.jsxs)(`section`,{className:`workspaces-browser-pane`,children:[(0,Q.jsxs)(`header`,{className:`workspaces-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`breadcrumbs`,children:`Kai Workshop / Scheduled jobs`}),(0,Q.jsx)(`h1`,{children:`Scheduled jobs`})]}),(0,Q.jsx)(`div`,{className:`workspaces-header-actions`,children:(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Back to conversation`,title:`Back to conversation`,onClick:n,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})})]}),(g||m)&&(0,Q.jsxs)(`div`,{className:`workspaces-notices`,"aria-live":`polite`,children:[g&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:g}),m&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:m})]}),(0,Q.jsx)(`section`,{className:`scheduled-job-catalogue`,"aria-label":`Active scheduled jobs`,children:u?(0,Q.jsx)(`p`,{className:`workspaces-empty`,children:`Loading scheduled jobs…`}):o.length===0?(0,Q.jsxs)(`div`,{className:`scheduled-jobs-empty`,children:[(0,Q.jsx)(Lh,{}),(0,Q.jsx)(`h2`,{children:`No active scheduled jobs`}),(0,Q.jsx)(`p`,{children:`Jobs created through Kai will appear here for inspection and cancellation.`})]}):(0,Q.jsxs)(Q.Fragment,{children:[w(`Upcoming`,x),w(`Recurring`,S)]})})]}),(0,Q.jsxs)(`aside`,{className:`context-pane workspace-detail scheduled-job-detail`,"aria-label":`Scheduled job detail`,children:[e&&(0,Q.jsx)(`div`,{className:`context-resize-handle`,role:`separator`,"aria-label":`Resize scheduled job detail`,"aria-orientation":`vertical`,"aria-valuemin":e.minimumWidth,"aria-valuemax":e.maximumWidth,"aria-valuenow":e.width,tabIndex:0,onKeyDown:e.onKeyDown,onPointerDown:e.onPointerDown,onPointerMove:e.onPointerMove}),(0,Q.jsx)(`div`,{className:`workspace-detail-scroll`,"aria-live":`polite`,children:b?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`workspace-detail-heading`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Selected job`}),(0,Q.jsx)(`h2`,{children:b.name})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button danger-icon-button`,type:`button`,"aria-label":`Cancel scheduled job`,title:`Cancel scheduled job`,disabled:f,onClick:()=>void C(),children:(0,Q.jsx)(Ih,{})})]}),(0,Q.jsxs)(`dl`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Status`}),(0,Q.jsx)(`dd`,{children:`Active`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Schedule`}),(0,Q.jsx)(`dd`,{children:zh(b)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Next run`}),(0,Q.jsx)(`dd`,{children:Rh(b.nextRunAt)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Created`}),(0,Q.jsx)(`dd`,{children:Rh(b.createdAt)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Type`}),(0,Q.jsx)(`dd`,{children:b.jobType===`reminder`?`Reminder`:`Agent task`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Agent`}),(0,Q.jsx)(`dd`,{children:b.agentName})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Delivery`}),(0,Q.jsxs)(`dd`,{children:[b.channelName,b.deliveryTransports.length?` · ${b.deliveryTransports.map(Bh).join(`, `)}`:``]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Auto-removal`}),(0,Q.jsx)(`dd`,{children:b.autoRemove?`Enabled`:`Disabled`})]})]}),(0,Q.jsxs)(`section`,{className:`scheduled-job-prompt`,children:[(0,Q.jsx)(`h3`,{children:`Prompt`}),(0,Q.jsx)(`p`,{children:b.prompt})]})]}):(0,Q.jsx)(`p`,{className:`workspaces-empty`,children:`Select a scheduled job.`})})]})]})}var Hh=class{token;capacity;entries=new Map;pending=new Map;principalUrls=new Map;clock=0;disposed=!1;constructor(e,t=64){if(this.token=e,this.capacity=t,!Number.isInteger(t)||t<1)throw Error(`Avatar cache capacity must be positive.`)}async load(e,t){if(this.disposed)throw Error(`Avatar cache is unavailable.`);let n=this.principalUrls.get(e);n&&n!==t&&this.evict(n),this.principalUrls.set(e,t);let r=this.entries.get(t);if(r)return r.touched=++this.clock,r.objectUrl;let i=this.pending.get(t);if(i)return i;let a=this.fetch(t).finally(()=>this.pending.delete(t));return this.pending.set(t,a),a}replace(e,t){if(this.disposed)return;let n=this.principalUrls.get(e);n&&n!==t.url&&this.evict(n),t.url?this.principalUrls.set(e,t.url):this.principalUrls.delete(e)}dispose(){this.disposed=!0;for(let e of this.entries.values())URL.revokeObjectURL(e.objectUrl);this.entries.clear(),this.pending.clear(),this.principalUrls.clear()}async fetch(e){let t=await globalThis.fetch(e,{cache:`no-store`,headers:{Authorization:`Bearer ${this.token}`}});if(!t.ok||t.headers.get(`Content-Type`)?.split(`;`,1)[0]!==`image/png`)throw Error(`Avatar image is unavailable.`);let n=URL.createObjectURL(await t.blob());if(this.disposed||![...this.principalUrls.values()].includes(e))throw URL.revokeObjectURL(n),Error(`Avatar image is no longer current.`);return this.entries.set(e,{objectUrl:n,touched:++this.clock}),this.trim(),n}trim(){for(;this.entries.size>this.capacity;){let e=[...this.entries.entries()].reduce((e,t)=>e[1].touched<=t[1].touched?e:t);this.evict(e[0])}}evict(e){let t=this.entries.get(e);t&&(URL.revokeObjectURL(t.objectUrl),this.entries.delete(e));for(let[t,n]of this.principalUrls)n===e&&this.principalUrls.delete(t)}},Uh=(0,v.createContext)(null);function Wh({children:e,token:t}){let n=(0,v.useMemo)(()=>new Hh(t),[t]),[r,i]=(0,v.useState)(()=>new Map),a=(0,v.useMemo)(()=>({cache:n,overrides:r,setOverride:(e,t)=>{n.replace(e,t),i(n=>new Map(n).set(e,t))}}),[n,r]);return(0,v.useEffect)(()=>()=>n.dispose(),[n]),(0,Q.jsx)(Uh.Provider,{value:a,children:e})}function Gh(){let e=(0,v.useContext)(Uh);if(!e)throw Error(`Human avatars require an avatar cache provider.`);return e.setOverride}function Kh({avatar:e,className:t,displayName:n,label:r,principalId:i}){let a=(0,v.useContext)(Uh);if(!a)throw Error(`Human avatars require an avatar cache provider.`);let{cache:o}=a,s=a.overrides.get(i)??e,[c,l]=(0,v.useState)(null),u=n.trim().slice(0,1).toUpperCase()||`?`;return(0,v.useEffect)(()=>{let e=!0;return l(null),o.replace(i,s),!s.active||!s.url||o.load(i,s.url).then(t=>{e&&l(t)}).catch(()=>{e&&l(null)}),()=>{e=!1}},[o,s.active,s.stateVersion,s.url,i]),(0,Q.jsx)(`span`,{className:t,"aria-hidden":r?void 0:`true`,"aria-label":r,role:r?`img`:void 0,children:c?(0,Q.jsx)(`img`,{src:c,alt:``,onError:()=>l(null)}):u})}var qh=262144,Jh=new Set([`image/png`,`image/jpeg`,`image/gif`,`image/webp`]);function Yh(e){return{...e.avatar??{active:!1,stateVersion:0,url:null},byteSize:null,height:null,mediaType:null,mutation:null,principalId:e.principalId,sha256:null,width:null}}function Xh(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M4 6h4l1.4-2h5.2L16 6h4v14H4z`}),(0,Q.jsx)(`circle`,{cx:`12`,cy:`13`,r:`3.5`}),(0,Q.jsx)(`path`,{d:`M18 3v5m-2.5-2.5h5`})]})}function Zh(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M5 7h14M9 7V4h6v3m2 0-1 13H8L7 7m3 4v5m4-5v5`})})}function Qh(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M12 5v14M5 12h14`})})}function $h(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M5 7h14M9 7V4h6v3m2 0-1 13H8L7 7m3 4v5m4-5v5`})})}function eg(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`m4 20 4.2-1 10.6-10.6-3.2-3.2L5 15.8z`}),(0,Q.jsx)(`path`,{d:`m13.8 7 3.2 3.2`})]})}var tg={off:`Text only`,text_and_voice:`Text and voice`,voice_only:`Voice only`},ng=[{id:`settings-section-personal-preferences`,label:`Personal preferences`},{id:`settings-section-github`,label:`GitHub`},{id:`settings-section-notifications`,label:`Notification delivery`},{id:`settings-section-clients`,label:`Client preferences`}],rg={id:`settings-section-administration`,label:`Administration`},ig=[{id:`settings-section-runtime`,label:`Runtime settings`},{id:`settings-section-workspace`,label:`Workspace settings`}],ag=/^(?:[01]\d|2[0-3]):[0-5]\d$/,og=[`UTC`,`America/Toronto`,`America/Vancouver`,`America/Edmonton`,`America/Winnipeg`,`America/Halifax`,`America/St_Johns`,`America/New_York`,`America/Chicago`,`America/Denver`,`America/Los_Angeles`,`Europe/London`,`Europe/Paris`,`Asia/Tokyo`,`Australia/Sydney`];function sg(e){let t=Intl.supportedValuesOf,n=[];if(t)try{n=t(`timeZone`)}catch{n=[]}return[...new Set([`UTC`,e,...n.length>0?n:og])].filter(Boolean).sort((e,t)=>e.localeCompare(t))}function cg(e){if(!e)return`Not saved yet`;let t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}var lg=[`succeeded`,`unsupported`,`failed`,`timed_out`,`malformed`,`invalidated`,`refreshing`];function ug(e,t){let n=new Map(lg.map((e,t)=>[e,t])),r=Object.entries(t).filter(([,e])=>e>0).sort(([e],[t])=>(n.get(e)??lg.length)-(n.get(t)??lg.length)||e.localeCompare(t)).map(([e,t])=>`${t} ${e.replaceAll(`_`,` `)}`).join(`, `);return`Model catalogue refresh completed across ${e} authorized contexts${r?`: ${r}`:``}.`}function dg(e,t){return e.find(e=>e.field===t)??null}function fg(e){return!e||!e.changed||e.runtimeAction===`unchanged`?`No runtime change was needed.`:e.runtimeAction===`restarted`?e.providerSessionInvalidated?`Saved. The active runtime restarted and provider-session continuity was cleared.`:`Saved. The active runtime restarted.`:`Saved. The change will apply when this runtime starts next.`}function pg(e,t){return e instanceof Error?e.message:t}function mg({agentRuntime:e=!1,executionProfileControl:t,initialSection:n=null,nativeAgentRuntime:r=!1,onAuthenticationFailure:i,onChannelAccessFailure:a,onClose:o,onDirtyChange:s,onNavigationChanged:c,onHumanAvatarChanged:l,isAdministrator:u,runtimeLabel:d,runActive:f,session:p}){let m=Km(),[h,g]=(0,v.useState)(null),[_,y]=(0,v.useState)(``),[b,x]=(0,v.useState)(null),[S,C]=(0,v.useState)(null),[w,T]=(0,v.useState)(!0),[E,D]=(0,v.useState)(!1),[O,k]=(0,v.useState)(null),[A,j]=(0,v.useState)(null),[M,N]=(0,v.useState)(null),[P,F]=(0,v.useState)(``),[I,L]=(0,v.useState)(!0),[ee,z]=(0,v.useState)(!1),[H,te]=(0,v.useState)(null),[U,re]=(0,v.useState)(null),[ie,ae]=(0,v.useState)(null),[oe,se]=(0,v.useState)(!1),[ce,le]=(0,v.useState)(null),[ue,G]=(0,v.useState)(null),K=(0,v.useRef)(null),[q,de]=(0,v.useState)(null),[J,Y]=(0,v.useState)(null),[fe,pe]=(0,v.useState)(!0),[me,he]=(0,v.useState)(!1),[X,ge]=(0,v.useState)(null),[_e,ve]=(0,v.useState)(null),[ye,be]=(0,v.useState)(null),[xe,Se]=(0,v.useState)(null),[Ce,we]=(0,v.useState)(!1),[Ee,De]=(0,v.useState)(!1),[Oe,ke]=(0,v.useState)(null),[Ae,je]=(0,v.useState)(``),[Me,Ne]=(0,v.useState)(``),[Pe,Fe]=(0,v.useState)(``),[Ie,Le]=(0,v.useState)(``),[Re,ze]=(0,v.useState)(``),[Be,Ve]=(0,v.useState)(``),[He,Ue]=(0,v.useState)(``),[We,Z]=(0,v.useState)(``),[Ge,Ke]=(0,v.useState)(!1),[qe,Je]=(0,v.useState)(``),[Ye,Xe]=(0,v.useState)(``),[Ze,Qe]=(0,v.useState)(!1),[$e,et]=(0,v.useState)(!1),[tt,nt]=(0,v.useState)(null),[rt,it]=(0,v.useState)(null),[at,ot]=(0,v.useState)(!0),[st,ct]=(0,v.useState)(!1),[lt,ut]=(0,v.useState)(null),[dt,ft]=(0,v.useState)(null),[pt,mt]=(0,v.useState)(``),[ht,gt]=(0,v.useState)(``),[_t,vt]=(0,v.useState)(null),[yt,bt]=(0,v.useState)(!0),[xt,St]=(0,v.useState)(!1),[Ct,wt]=(0,v.useState)(null),[Tt,Et]=(0,v.useState)(null),[Dt,Ot]=(0,v.useState)(null),[kt,At]=(0,v.useState)(!0),[jt,Mt]=(0,v.useState)(!1),[Nt,Pt]=(0,v.useState)(null),[Ft,It]=(0,v.useState)(null),[Lt,Rt]=(0,v.useState)(!1),[zt,Bt]=(0,v.useState)(`UTC`),[Vt,Ht]=(0,v.useState)(`22:00`),[Ut,Wt]=(0,v.useState)(`07:00`),Gt=ag.test(Vt)&&ag.test(Ut)&&Vt!==Ut,Kt=(0,v.useMemo)(()=>sg(zt),[zt]),[qt,Jt]=(0,v.useState)(null),[Yt,Xt]=(0,v.useState)(!0),[Zt,Qt]=(0,v.useState)(!1),[$t,en]=(0,v.useState)(null),[tn,nn]=(0,v.useState)(null),[rn,an]=(0,v.useState)(null),[on,sn]=(0,v.useState)(``),[cn,ln]=(0,v.useState)(!0),[un,dn]=(0,v.useState)(!1),[fn,pn]=(0,v.useState)(null),[mn,hn]=(0,v.useState)(null),[gn,_n]=(0,v.useState)(null),[vn,yn]=(0,v.useState)(u),[bn,xn]=(0,v.useState)(null),Sn=(0,v.useRef)(null),Cn=e?ig:u?[...ng,rg]:ng,[wn,Tn]=(0,v.useState)(e?`settings-section-runtime`:n===`administration`&&u?`settings-section-administration`:n===`github`?`settings-section-github`:ng[0].id),En=e&&r,Dn=En?`agent-runtime-settings-title`:`settings-title`,On=h!==null&&_!==h.content,kn=M!==null&&P.trim()!==M.displayName,An=(0,v.useMemo)(()=>new TextEncoder().encode(_).length,[_]),jn=e=>{let t=document.getElementById(e);if(!t)return;let n=typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;Tn(e),t.scrollIntoView?.({behavior:n?`auto`:`smooth`,block:`start`})};(0,v.useEffect)(()=>{!e&&n!==null&&jn(`settings-section-${n}`)},[e,n,u]);let Mn=()=>{let e=Sn.current;if(!e)return;let t=Cn.flatMap(e=>{let t=document.getElementById(e.id);return t?[{item:e,element:t}]:[]});if(t.length===0)return;if(e.scrollTop+e.clientHeight>=e.scrollHeight-2){Tn(t[t.length-1].item.id);return}let n=e.getBoundingClientRect().top+32,r=t[0].item.id;for(let e of t){if(e.element.getBoundingClientRect().top>n)break;r=e.item.id}Tn(r)},Nn=(0,v.useCallback)(e=>e instanceof B?(i(e.message),!0):e instanceof V&&(a(e.message),!0),[i,a]),Pn=(0,v.useCallback)(e=>{g(e),y(e.content),C(null)},[]),Fn=(0,v.useCallback)(async()=>{x(await kr(p))},[p]),In=(0,v.useCallback)(async()=>{T(!0),k(null);try{let[e,t]=await Promise.all([Tr(p),kr(p)]);Pn(e),x(t)}catch(e){Nn(e)||k(pg(e,`Could not load personal preferences.`))}finally{T(!1)}},[Pn,Nn,p]),Ln=(0,v.useCallback)(async()=>{L(!0),te(null),le(null);try{let e=await dr(p);N(e),F(e.displayName);try{ae(await fr(p))}catch(t){ae(Yh(e)),Nn(t)||le(`Your avatar is temporarily unavailable. Showing your initial instead.`)}}catch(e){Nn(e)||te(pg(e,`Could not load your profile.`))}finally{L(!1)}},[Nn,p]),Rn=(0,v.useCallback)(e=>{de(e),Fe(e.backendOptionId),Le(e.model.value),ze(String(e.timeoutSeconds.value))},[]),zn=(0,v.useCallback)(e=>{Y(e),Ve(e.model.value),Ue(String(e.timeoutSeconds.value)),Z(e.prompt??``)},[]),Bn=(0,v.useCallback)(async()=>{pe(!0),ge(null),ve(null);try{let e=await Vn(p);Rn(e)}catch(e){Nn(e)||ge(pg(e,`Could not load runtime settings.`)),de(null),Y(null),pe(!1);return}try{zn(await vr(p))}catch(e){e instanceof B?i(e.message):(Y(null),ve(pg(e,`Could not load workspace settings.`)))}finally{pe(!1)}},[Rn,zn,Nn,i,p]);(0,v.useEffect)(()=>{if(!q||!Pe){Se(null);return}let e=!1;return we(!0),ke(null),Gn(p,Pe).then(t=>{e||Se(t)}).catch(t=>{!e&&!Nn(t)&&ke(pg(t,`Could not load the model catalogue.`))}).finally(()=>{e||we(!1)}),()=>{e=!0}},[Nn,q,Pe,p]);let Hn=async()=>{if(Pe){De(!0),ke(null);try{let e=await Kn(p,Pe);Se(e),Pe===q?.backendOptionId&&Rn(await Vn(p))}catch(e){Nn(e)||ke(pg(e,`Could not refresh the model catalogue.`))}finally{De(!1)}}},Un=async()=>{De(!0),ke(null);try{let e=await qn(p);be(ug(e.contexts,e.statuses)),Se(await Gn(p,Pe))}catch(e){Nn(e)||ke(pg(e,`Could not refresh all model catalogues.`))}finally{De(!1)}},Wn=async()=>{if(!(!Ae.trim()||!Me.trim())){De(!0),ke(null);try{Se(await Jn(p,Pe,Ae.trim(),Me.trim())),je(``),Ne(``)}catch(e){Nn(e)||ke(pg(e,`Could not save the operator model.`))}finally{De(!1)}}},Qn=async e=>{if(await m(`Deactivate operator model ${e}?`)){De(!0),ke(null);try{Se(await Yn(p,Pe,e))}catch(e){Nn(e)||ke(pg(e,`Could not deactivate the operator model.`))}finally{De(!1)}}},$n=(0,v.useCallback)(async()=>{ot(!0),ut(null);try{it(await Xn(p))}catch(e){Nn(e)||ut(pg(e,`Could not load GitHub settings.`))}finally{ot(!1)}},[Nn,p]),er=(0,v.useCallback)(async()=>{bt(!0),wt(null);try{vt(await ir(p))}catch(e){Nn(e)||wt(pg(e,`Could not load notification preferences.`))}finally{bt(!1)}},[Nn,p]),tr=(0,v.useCallback)(async()=>{At(!0),Pt(null);try{let e=await or(p);Ot(e),Rt(e.doNotDisturb.enabled),Bt(e.doNotDisturb.timezone),Ht(e.doNotDisturb.start),Wt(e.doNotDisturb.end)}catch(e){Nn(e)||Pt(pg(e,`Could not load channel notification policy.`))}finally{At(!1)}},[Nn,p]),nr=(0,v.useCallback)(async()=>{Xt(!0),en(null);try{Jt(await cr(p))}catch(e){Nn(e)||en(pg(e,`Could not load client preferences.`))}finally{Xt(!1)}},[Nn,p]),rr=(0,v.useCallback)(async()=>{ln(!0),pn(null);try{let e=await lr(p);an(e),sn(e.themeId),R(e.themeId)}catch(e){Nn(e)||pn(pg(e,`Could not load appearance preferences.`))}finally{ln(!1)}},[Nn,p]),yr=(0,v.useCallback)(async()=>{if(!u){_n(null),yn(!1);return}yn(!0),xn(null);try{_n(await Te(p))}catch(e){Nn(e)||xn(pg(e,`Could not load webhook diagnostics.`))}finally{yn(!1)}},[Nn,u,p]);(0,v.useEffect)(()=>{e?Bn():(In(),Ln(),$n(),er(),tr(),nr(),rr(),u&&yr())},[e,rr,nr,$n,tr,er,In,Ln,Bn,yr,u]),(0,v.useEffect)(()=>(s(On||kn),()=>s(!1)),[s,On,kn]),(0,v.useEffect)(()=>{if(!On&&!kn)return;let e=e=>{e.preventDefault(),e.returnValue=``};return window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e)},[On,kn]);let br=async()=>{if(!(!M||!kn)){z(!0),te(null),re(null);try{let e=globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`profile-${Date.now()}-${Math.random().toString(16).slice(2)}`,t=await hr(p,P,M.stateVersion,e);N(t),F(t.displayName),re(t.mutation?.changed?`Display name saved.`:`No change was needed.`),await c?.()}catch(e){e instanceof W?(await Ln(),te(`Your profile changed elsewhere. The latest display name has been reloaded.`)):Nn(e)||te(pg(e,`Could not save your display name.`))}finally{z(!1)}}},xr=async e=>{if(!(!ie||oe)){if(le(null),G(null),!Jh.has(e.type)){le(`Choose a PNG, JPEG, GIF, or WebP image.`);return}if(e.size>qh){le(`Avatar images must be no larger than 256 KiB.`);return}se(!0);try{let t=globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`avatar-${Date.now()}-${Math.random().toString(16).slice(2)}`,n=await pr(p,e,ie.stateVersion,t);ae(n),N(e=>e&&{...e,avatar:n}),l?.(n.principalId,n),G(`Avatar saved.`),await c?.()}catch(e){e instanceof W?(await Ln(),le(`Your avatar changed elsewhere. The latest image has been reloaded.`)):Nn(e)||le(pg(e,`Could not save your avatar.`))}finally{se(!1),K.current&&(K.current.value=``)}}},Er=async()=>{if(!(!ie||!ie.active||oe)){se(!0),le(null),G(null);try{let e=globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`avatar-clear-${Date.now()}-${Math.random().toString(16).slice(2)}`,t=await mr(p,ie.stateVersion,e);ae(t),N(e=>e&&{...e,avatar:t}),l?.(t.principalId,t),G(`Avatar cleared.`),await c?.()}catch(e){e instanceof W?(await Ln(),le(`Your avatar changed elsewhere. The latest image has been reloaded.`)):Nn(e)||le(pg(e,`Could not clear your avatar.`))}finally{se(!1)}}},Dr=async(e=h?.revision??``)=>{if(!(!h||An>h.maxBytes)){D(!0),k(null),j(null);try{let t=await Or(p,_,e);Pn(t),await Fn(),j(`Preferences saved. They will apply to the next eligible agent turn.`)}catch(e){if(e instanceof ne)try{let e=await Tr(p);C(e),k(`Preferences changed in another session. Compare both versions before choosing what to keep.`)}catch(t){Nn(t)||k(pg(t,e.message))}else Nn(e)||k(pg(e,`Could not save preferences.`))}finally{D(!1)}}},Mr=async e=>{if(!(!h||!await m(`Restore this private preference revision? The current text will be retained in revision history.`))){D(!0),k(null),j(null);try{let t=await Ar(p,e,h.revision);Pn(t),await Fn(),j(`Preference revision restored.`)}catch(e){e instanceof ne?k(`Preferences changed before the restore. Reload and review the latest revision.`):Nn(e)||k(pg(e,`Could not restore preferences.`))}finally{D(!1)}}},Nr=async(e,t)=>{if(!(!q||!await m(t))){he(!0),ge(null),be(null);try{let t=await _r(p,q.revision,e);Rn(t),zn(await vr(p)),be(fg(t.mutation))}catch(t){e.field===`backend`&&Fe(q.backendOptionId),t instanceof W?(await Bn(),ge(`Runtime settings changed elsewhere. The latest values have been reloaded.`)):Nn(t)||ge(pg(t,`Could not update runtime settings.`))}finally{he(!1)}}},Pr=async(e,t)=>{if(!(!J||!await m(t))){he(!0),ge(null),be(null);try{let t=await Sr(p,J.revision,e);zn(t),Rn(await Vn(p)),be(fg(t.mutation))}catch(e){e instanceof W?(await Bn(),ge(`Workspace settings changed elsewhere. The latest values have been reloaded.`)):Nn(e)||ge(pg(e,`Could not update workspace settings.`))}finally{he(!1)}}},Fr=e=>{Je(e??``),Xe(``),Qe(e!==null),nt(null),Ke(!0)},Ir=async()=>{if(!(!J||$e||!qe.trim()||!Ye)){et(!0),nt(null),be(null);try{let e=await Cr(p,J.revision,qe.trim(),Ye);zn(e),Rn(await Vn(p)),be(fg(e.mutation)),Ke(!1),Je(``),Xe(``),Qe(!1)}catch(e){e instanceof W?(await Bn(),nt(`Workspace secrets changed elsewhere. Reopen this form and enter the value again.`),Xe(``)):Nn(e)||nt(pg(e,`Could not save workspace secret.`))}finally{et(!1)}}},Lr=async e=>{if(!(!J||$e||!await m(`Remove ${e} from this workspace? The active runtime may restart.`))){et(!0),nt(null),be(null);try{let t=await wr(p,J.revision,e);zn(t),Rn(await Vn(p)),be(fg(t.mutation))}catch(e){e instanceof W?(await Bn(),nt(`Workspace secrets changed elsewhere. The latest state has been loaded.`)):Nn(e)||nt(pg(e,`Could not remove workspace secret.`))}finally{et(!1)}}},Rr=async(e,t=null)=>{if(!rt||t!==null&&!await m(t))return!1;ct(!0),ut(null),ft(null);try{let t=await Zn(p,rt.revision,e);return it(t),gt(``),ft(t.mutation?.changed?`GitHub settings saved.`:`No change was needed.`),!0}catch(e){return gt(``),e instanceof W?(await $n(),ut(`GitHub settings changed elsewhere. The latest values have been reloaded.`)):Nn(e)||ut(pg(e,`Could not update GitHub settings.`)),!1}finally{ct(!1)}},zr=async(e,t=null)=>{if(!(!_t||t!==null&&!await m(t))){St(!0),wt(null),Et(null);try{let t=await ar(p,_t.revision,e);vt(t),Et(t.mutation?.changed?`Notification destination saved.`:`No change was needed.`)}catch(e){e instanceof W?(await er(),wt(`Notification preferences changed elsewhere. The latest values have been reloaded.`)):Nn(e)||wt(pg(e,`Could not update notification preferences.`))}finally{St(!1)}}},Br=async e=>{if(Dt){Mt(!0),Pt(null),It(null);try{let t=await sr(p,Dt.revision,e);Ot(t),Rt(t.doNotDisturb.enabled),Bt(t.doNotDisturb.timezone),Ht(t.doNotDisturb.start),Wt(t.doNotDisturb.end),It(t.mutation?.changed?`Channel notification policy saved.`:`No change was needed.`)}catch(e){e instanceof W?(await tr(),Pt(`Channel notification policy changed elsewhere. The latest values have been reloaded.`)):Nn(e)||Pt(pg(e,`Could not update channel notification policy.`))}finally{Mt(!1)}}},Vr=async e=>{if(qt){Qt(!0),en(null),nn(null);try{let t=await gr(p,qt.revision,e);Jt(t),nn(t.mutation?.changed?`Client preference saved.`:`No change was needed.`)}catch(e){e instanceof W?(await nr(),en(`Client preferences changed elsewhere. The latest values have been reloaded.`)):Nn(e)||en(pg(e,`Could not update client preferences.`))}finally{Qt(!1)}}},Hr=async e=>{if(!rn)return;let t=rn.themeId;sn(e),R(e),dn(!0),pn(null),hn(null);try{let t=await ur(p,rn.revision,e);an(t),sn(t.themeId),R(t.themeId),hn(t.mutation?.changed?`Workshop appearance saved.`:`No change was needed.`)}catch(e){e instanceof W?(await rr(),pn(`Appearance preferences changed elsewhere. The latest value has been reloaded.`)):(sn(t),R(t),Nn(e)||pn(pg(e,`Could not update appearance preferences.`)))}finally{dn(!1)}},Ur=async e=>{if(!(!q||e===q.workspace||!await m(`Switch the active workspace? An active runtime may restart and provider-session continuity may be cleared.`))){he(!0),ge(null),be(null);try{let t=await jr(p,e,q.revision);Rn(t),zn(await vr(p)),be(fg(t.mutation))}catch(e){e instanceof W?(await Bn(),ge(`Workspace selection changed elsewhere. The latest state has been reloaded.`)):Nn(e)||ge(pg(e,`Could not switch workspace.`))}finally{he(!1)}}},Wr=q?dg(q.capabilities,`backend`):null,Gr=q?dg(q.capabilities,`model`):null,Kr=q?dg(q.capabilities,`timeout`):null,qr=J?dg(J.capabilities,`model`):null,Jr=J?dg(J.capabilities,`timeout`):null,Yr=J?dg(J.capabilities,`prompt`):null,Xr=q?q.workspaces.findIndex(e=>e.path===q.workspace):-1,Zr=(e,t,n,r)=>n?(0,Q.jsx)(`select`,{id:e,value:t,onChange:e=>r(e.target.value),children:n.map(e=>{let t=q?.modelOptions?.find(t=>t.modelId===e),n=t?.retained&&!t.selectable?` · not currently advertised`:``;return(0,Q.jsxs)(`option`,{value:e,disabled:t?!t.selectable:!1,children:[t?.displayName??e,n]},e)})}):(0,Q.jsx)(`input`,{id:e,type:`text`,value:t,onChange:e=>r(e.target.value)});return(0,Q.jsxs)(`section`,{className:En?`agent-runtime-controls`:`settings-workspace`,"aria-labelledby":En?void 0:Dn,"aria-label":En?`${d} runtime and workspace settings`:void 0,id:En?`agent-runtime-settings`:void 0,children:[!En&&(0,Q.jsxs)(`header`,{className:`settings-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`breadcrumbs`,children:e?`Agent runtime`:`Kai Workshop / Settings`}),(0,Q.jsx)(`h1`,{id:Dn,children:e?`${d} settings`:`Settings`})]}),!En&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":e?`Back to agent`:`Back to conversation`,title:e?`Back to agent`:`Back to conversation`,onClick:o,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})]}),!En&&(0,Q.jsx)(`nav`,{className:`settings-section-navigation`,"aria-label":`Settings sections`,children:(0,Q.jsx)(`div`,{children:Cn.map(e=>(0,Q.jsx)(`button`,{type:`button`,"aria-current":wn===e.id?`location`:void 0,onClick:()=>jn(e.id),children:e.label},e.id))})}),(0,Q.jsxs)(`div`,{className:En?`agent-runtime-controls-body`:`settings-scroll`,ref:En?void 0:Sn,onScroll:En?void 0:Mn,children:[!e&&(0,Q.jsxs)(`section`,{className:`settings-intro`,id:`settings-section-personal-preferences`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`section-number`,children:`01`}),(0,Q.jsx)(`h2`,{children:`Personal preferences`}),(0,Q.jsx)(`p`,{children:`Your Workshop profile and principal-wide guidance supplied to your agents.`})]}),(0,Q.jsxs)(`div`,{className:`settings-card-stack settings-personal-preferences`,children:[I?(0,Q.jsx)(`p`,{role:`status`,children:`Loading profile…`}):M?(0,Q.jsxs)(`form`,{className:`settings-card`,onSubmit:e=>{e.preventDefault(),br()},children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Profile`}),ie&&(0,Q.jsxs)(`div`,{className:`profile-avatar-editor`,children:[(0,Q.jsx)(Kh,{avatar:ie,className:`profile-avatar-preview`,displayName:P||M.displayName,label:`Your profile avatar`,principalId:M.principalId}),(0,Q.jsxs)(`div`,{className:`profile-avatar-actions`,children:[(0,Q.jsx)(`input`,{ref:K,className:`visually-hidden`,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,disabled:oe,"aria-label":`Choose avatar image`,onChange:e=>{let t=e.target.files?.[0];t&&xr(t)}}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":ie.active?`Change avatar`:`Add avatar`,title:ie.active?`Change avatar`:`Add avatar`,disabled:oe,onClick:()=>K.current?.click(),children:(0,Q.jsx)(Xh,{})}),ie.active&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Clear avatar`,title:`Clear avatar`,disabled:oe,onClick:()=>void Er(),children:(0,Q.jsx)(Zh,{})}),(0,Q.jsx)(`span`,{children:oe?`Saving…`:`PNG, JPEG, GIF, or WebP · 256 KiB max`})]})]}),(0,Q.jsx)(`label`,{htmlFor:`profile-display-name`,children:`Display name`}),(0,Q.jsx)(`input`,{id:`profile-display-name`,type:`text`,maxLength:200,value:P,disabled:ee,onChange:e=>{F(e.target.value),re(null)}}),(0,Q.jsxs)(`p`,{className:`settings-help`,children:[`Your name is shown throughout Workshop. Your unique handle remains @`,M.handle,`.`]}),(0,Q.jsx)(`div`,{className:`settings-actions`,children:(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:ee||!kn||P.trim().length===0,children:ee?`Saving…`:`Save display name`})}),U&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:U}),ue&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:ue}),H&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:H}),ce&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:ce})]}):(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:H??`Profile is unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void Ln(),children:`Retry`})]}),w?(0,Q.jsx)(`p`,{role:`status`,children:`Loading preferences…`}):h?(0,Q.jsxs)(`div`,{className:`preference-editor-card`,children:[(0,Q.jsx)(`label`,{htmlFor:`personal-preferences`,children:`Preference Markdown`}),(0,Q.jsx)(`textarea`,{id:`personal-preferences`,value:_,readOnly:!h.editable,disabled:E,onChange:e=>{y(e.target.value),j(null)},rows:14,spellCheck:!0}),(0,Q.jsxs)(`div`,{className:`preference-editor-meta`,children:[(0,Q.jsxs)(`span`,{children:[An.toLocaleString(),` / `,h.maxBytes.toLocaleString(),` bytes`]}),(0,Q.jsxs)(`span`,{children:[`Updated `,cg(h.updatedAt)]}),(0,Q.jsx)(`span`,{children:On?`Unsaved changes`:`Saved`})]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`button`,disabled:E||!h.editable||!On||An>h.maxBytes,onClick:()=>void Dr(),children:E?`Saving…`:`Save preferences`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:E||!On,onClick:()=>y(h.content),children:`Discard changes`})]}),An>h.maxBytes&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:`Preference text exceeds the protected size limit.`}),A&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:A}),O&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:O})]}):(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:O??`Preferences are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void In(),children:`Retry`})]}),S&&h&&(0,Q.jsxs)(`section`,{className:`preference-conflict`,"aria-labelledby":`preference-conflict-title`,children:[(0,Q.jsx)(`h3`,{id:`preference-conflict-title`,children:`Review concurrent changes`}),(0,Q.jsx)(`p`,{children:`Your draft remains untouched. Compare it with the latest saved text before replacing either version.`}),(0,Q.jsxs)(`div`,{className:`preference-compare`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`Your draft`}),(0,Q.jsx)(`pre`,{children:_})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`Latest saved`}),(0,Q.jsx)(`pre`,{children:S.content})]})]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>Pn(S),children:`Use latest saved`}),(0,Q.jsx)(`button`,{className:`primary-button`,type:`button`,disabled:E,onClick:()=>void(async()=>{await m(`Replace the latest saved preferences with your reviewed draft?`)&&Dr(S.revision)})(),children:`Reapply my draft…`})]})]}),b&&b.revisions.length>0&&(0,Q.jsxs)(`details`,{className:`preference-history`,children:[(0,Q.jsxs)(`summary`,{children:[`Private revision history (`,b.revisions.length,`)`]}),(0,Q.jsx)(`ol`,{children:b.revisions.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:cg(e.updatedAt)}),(0,Q.jsxs)(`small`,{children:[e.sizeBytes.toLocaleString(),` bytes`]})]}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:E||e.revision===h?.revision,onClick:()=>void Mr(e.revision),children:`Restore…`})]},e.revision))})]})]})]}),e&&(0,Q.jsxs)(`section`,{className:`settings-section`,id:`settings-section-runtime`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{children:`Runtime settings`}),(0,Q.jsxs)(`p`,{children:[`These controls apply only to `,d,`.`,` `,`Changes can restart an active runtime and clear provider-session continuity.`]})]}),fe?(0,Q.jsx)(`p`,{role:`status`,children:`Loading runtime policy…`}):q?(0,Q.jsxs)(`div`,{className:`settings-card-stack`,children:[t,(0,Q.jsxs)(`div`,{className:`settings-card-columns`,children:[(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[Wr&&(0,Q.jsxs)(`form`,{className:`settings-card`,onSubmit:e=>{e.preventDefault(),Nr({field:`backend`,value:Pe},`Switch backend? Your current provider session will end. Your next message will start on the selected backend; other people and Kai itself will not restart.`)},children:[(0,Q.jsx)(`label`,{htmlFor:`runtime-backend`,children:`Backend`}),(0,Q.jsx)(`select`,{id:`runtime-backend`,value:Pe,disabled:me||f,onChange:e=>Fe(e.target.value),children:q.backendOptions.map(e=>(0,Q.jsxs)(`option`,{value:e.optionId,children:[e.backend,` · `,e.provider]},e.optionId))}),(0,Q.jsxs)(`p`,{children:[`Active: `,(0,Q.jsx)(`strong`,{children:q.backend}),` · `,q.provider]}),(0,Q.jsx)(`p`,{children:f?`Finish or stop the active run before switching.`:`Only your runtime lane and provider session are replaced. If sign-in is required, your next message will explain how; you can switch back here immediately.`}),(0,Q.jsx)(`div`,{className:`settings-actions`,children:(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:me||f||Pe===q.backendOptionId,children:`Switch backend`})})]}),Gr&&(0,Q.jsxs)(`form`,{className:`settings-card`,onSubmit:e=>{e.preventDefault(),Nr({field:`model`,value:Ie},`Change the runtime model? The active runtime may restart and provider-session continuity will be cleared.`)},children:[(0,Q.jsx)(`label`,{htmlFor:`runtime-model`,children:`Runtime model`}),Zr(`runtime-model`,Ie,Gr.choices,Le),(0,Q.jsxs)(`p`,{children:[`Effective: `,(0,Q.jsx)(`strong`,{children:q.model.value}),` · `,q.model.source]}),(0,Q.jsxs)(`p`,{children:[`Policy default: `,q.model.defaultValue]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:me||Ie===q.model.value,children:`Apply`}),Gr.resettable&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:me||q.model.source===`runtime policy`,onClick:()=>void Nr({field:`reset`,value:`model`},`Reset the runtime model to protected policy? The active runtime may restart.`),children:`Reset`})]})]})]}),(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[(0,Q.jsxs)(`article`,{className:`settings-card policy-card`,children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Policy-controlled`}),(0,Q.jsx)(`dl`,{children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Authorized choices`}),(0,Q.jsx)(`dd`,{children:q.backendOptions.length})]})}),(0,Q.jsx)(`p`,{children:`Credentials, identity mappings, executable paths, assignments, and workspace grants remain operator managed.`})]}),Kr&&(0,Q.jsxs)(`form`,{className:`settings-card`,onSubmit:e=>{e.preventDefault(),Nr({field:`timeout`,value:Number(Re)},`Change the response timeout? The active runtime may restart and provider-session continuity will be cleared.`)},children:[(0,Q.jsx)(`label`,{htmlFor:`runtime-timeout`,children:`Response timeout`}),(0,Q.jsxs)(`div`,{className:`settings-number-input`,children:[(0,Q.jsx)(`input`,{id:`runtime-timeout`,type:`number`,min:Kr.minimum??void 0,max:Kr.maximum??void 0,value:Re,onChange:e=>ze(e.target.value)}),(0,Q.jsx)(`span`,{children:`seconds`})]}),(0,Q.jsxs)(`p`,{children:[`Effective: `,(0,Q.jsxs)(`strong`,{children:[q.timeoutSeconds.value,`s`]}),` · `,q.timeoutSeconds.source]}),(0,Q.jsxs)(`p`,{children:[`Allowed: `,Kr.minimum,`–`,Kr.maximum,`s`]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:me||!Re||Number(Re)===q.timeoutSeconds.value,children:`Apply`}),Kr.resettable&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:me||q.timeoutSeconds.source===`runtime policy`,onClick:()=>void Nr({field:`reset`,value:`timeout`},`Reset the timeout to protected policy? The active runtime may restart.`),children:`Reset`})]})]})]})]}),(0,Q.jsxs)(`details`,{className:`settings-card model-catalogue-card`,children:[(0,Q.jsxs)(`summary`,{"aria-label":`Model catalogue details`,children:[(0,Q.jsxs)(`span`,{className:`model-catalogue-summary-heading`,children:[(0,Q.jsx)(`span`,{className:`settings-card-label`,children:`Model catalogue`}),(0,Q.jsx)(`span`,{children:`Provider metadata and operator-managed choices`})]}),(0,Q.jsxs)(`span`,{className:`model-catalogue-summary-status`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Backend`}),xe?.optionId??q.backendOptionId]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Models`}),xe?xe.models.length:`—`]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Status`}),Ce?`Loading`:xe?`${xe.refresh?.status??`Not refreshed`}${xe.stale?` · stale`:``}`:`Unavailable`]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Last refresh`}),cg(xe?.refresh?.lastSuccessfulRefreshAt??null)]})]}),(0,Q.jsx)(`span`,{className:`model-catalogue-disclosure`,"aria-hidden":`true`,children:`⌄`})]}),(0,Q.jsxs)(`div`,{className:`model-catalogue-body`,children:[(0,Q.jsx)(`p`,{children:`Refreshes inspect provider metadata only. They never run a model, change your selected model, or interrupt active work.`}),Ce?(0,Q.jsx)(`p`,{role:`status`,children:`Loading catalogue…`}):xe?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`ul`,{className:`model-catalogue-list`,children:xe.models.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:e.displayName}),(0,Q.jsx)(`code`,{children:e.modelId}),(0,Q.jsxs)(`small`,{children:[e.status.replaceAll(`_`,` `),e.retained?` · retained selection`:``]}),u&&e.sources.includes(`operator`)&&(0,Q.jsx)(`button`,{className:`model-catalogue-remove`,type:`button`,disabled:Ee,onClick:()=>void Qn(e.modelId),children:`Deactivate operator entry`})]},e.modelId))}),xe.refresh?.errorDetail&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:xe.refresh.errorDetail})]}):null,(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:Ee||Ce,onClick:()=>void Hn(),children:Ee?`Refreshing…`:`Refresh models`}),u&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:Ee||Ce,onClick:()=>void Un(),children:`Refresh all contexts`})]}),u&&(0,Q.jsxs)(`form`,{className:`model-catalogue-operator-form`,onSubmit:e=>{e.preventDefault(),Wn()},children:[(0,Q.jsx)(`label`,{htmlFor:`operator-model-id`,children:`Operator-managed model ID`}),(0,Q.jsx)(`input`,{id:`operator-model-id`,type:`text`,value:Ae,onChange:e=>je(e.target.value)}),(0,Q.jsx)(`label`,{htmlFor:`operator-model-label`,children:`Display label`}),(0,Q.jsx)(`input`,{id:`operator-model-label`,type:`text`,value:Me,onChange:e=>Ne(e.target.value)}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`submit`,disabled:Ee||!Ae.trim()||!Me.trim(),children:`Add or update`})]}),Oe&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:Oe})]})]})]}):(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:X??`Runtime settings are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void Bn(),children:`Retry`})]}),ye&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:ye}),X&&q&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:X})]}),e&&q&&J&&(0,Q.jsxs)(`section`,{className:`settings-section`,id:`settings-section-workspace`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{children:`Workspace settings`}),(0,Q.jsx)(`p`,{children:`Choose the workspace this agent uses and manage overrides that apply only within it.`})]}),(0,Q.jsxs)(`div`,{className:`workspace-settings-heading`,children:[(0,Q.jsx)(`label`,{htmlFor:`settings-workspace`,children:`Active workspace`}),(0,Q.jsx)(`select`,{id:`settings-workspace`,value:String(Xr),disabled:me,onChange:e=>{let t=q.workspaces[Number(e.target.value)];t&&Ur(t.path)},children:q.workspaces.map((e,t)=>(0,Q.jsx)(`option`,{value:String(t),children:e.name},e.path))})]}),(0,Q.jsx)(`div`,{className:`settings-card-stack workspace-overrides`,children:(0,Q.jsxs)(`div`,{className:`settings-card-columns`,children:[(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[qr&&(0,Q.jsxs)(`form`,{className:`settings-card`,onSubmit:e=>{e.preventDefault(),Pr({field:`model`,value:Be},`Apply this model only to the active workspace? The active runtime may restart.`)},children:[(0,Q.jsx)(`label`,{htmlFor:`workspace-model`,children:`Workspace model override`}),Zr(`workspace-model`,Be,qr.choices,Ve),(0,Q.jsxs)(`p`,{children:[`Effective: `,(0,Q.jsx)(`strong`,{children:J.model.value}),` · `,J.model.source]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:me||Be===J.model.value,children:`Apply`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:me||!J.overrideFields.includes(`model`),onClick:()=>void Pr({field:`reset`,value:`model`},`Remove this workspace model override?`),children:`Reset`})]})]}),Yr&&(0,Q.jsxs)(`form`,{className:`settings-card prompt-card`,onSubmit:e=>{e.preventDefault(),Pr({field:`prompt`,value:We},`Apply this system prompt only to the active workspace? The active runtime may restart.`)},children:[(0,Q.jsx)(`label`,{htmlFor:`workspace-prompt`,children:`Workspace system prompt`}),(0,Q.jsx)(`textarea`,{id:`workspace-prompt`,rows:7,maxLength:Yr.maximum??void 0,value:We,onChange:e=>Z(e.target.value)}),(0,Q.jsx)(`p`,{children:J.hasPrompt?`Effective source: ${J.promptSource??`workspace`}`:`No workspace prompt is active.`}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:me||We===(J.prompt??``),children:`Apply`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:me||!J.overrideFields.includes(`prompt`),onClick:()=>void Pr({field:`reset`,value:`prompt`},`Remove this workspace prompt override?`),children:`Reset`})]})]})]}),(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[Jr&&(0,Q.jsxs)(`form`,{className:`settings-card`,onSubmit:e=>{e.preventDefault(),Pr({field:`timeout`,value:He},`Apply this timeout only to the active workspace? The active runtime may restart.`)},children:[(0,Q.jsx)(`label`,{htmlFor:`workspace-timeout`,children:`Workspace timeout override`}),(0,Q.jsxs)(`div`,{className:`settings-number-input`,children:[(0,Q.jsx)(`input`,{id:`workspace-timeout`,type:`number`,min:Jr.minimum??void 0,max:Jr.maximum??void 0,value:He,onChange:e=>Ue(e.target.value)}),(0,Q.jsx)(`span`,{children:`seconds`})]}),(0,Q.jsxs)(`p`,{children:[`Effective: `,(0,Q.jsxs)(`strong`,{children:[J.timeoutSeconds.value,`s`]}),` · `,J.timeoutSeconds.source]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:me||!He||Number(He)===J.timeoutSeconds.value,children:`Apply`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:me||!J.overrideFields.includes(`timeout`),onClick:()=>void Pr({field:`reset`,value:`timeout`},`Remove this workspace timeout override?`),children:`Reset`})]})]}),(0,Q.jsxs)(`article`,{className:`settings-card workspace-secret-card`,children:[(0,Q.jsxs)(`div`,{className:`workspace-secret-heading`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Workspace secrets`}),(0,Q.jsx)(`p`,{children:`Values are write-only and apply only to this workspace.`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Add workspace secret`,title:`Add workspace secret`,disabled:me||$e||J.environmentVariables.length>=J.environmentPolicy.maximumKeys,onClick:()=>Fr(null),children:(0,Q.jsx)(Qh,{})})]}),J.environmentVariables.length>0?(0,Q.jsx)(`ul`,{className:`workspace-secret-list`,children:J.environmentVariables.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.key}),(0,Q.jsx)(`small`,{children:e.provenance===`operator`?`Operator managed`:e.provenance===`principal_override`?`Personal override of operator policy`:`Managed by you`})]}),(0,Q.jsxs)(`span`,{className:`workspace-secret-actions`,children:[e.editable&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Replace ${e.key}`,title:`Replace ${e.key}`,disabled:$e,onClick:()=>Fr(e.key),children:(0,Q.jsx)(eg,{})}),e.removable&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Remove ${e.key}`,title:`Remove ${e.key}`,disabled:$e,onClick:()=>void Lr(e.key),children:(0,Q.jsx)($h,{})})]})]},e.key))}):(0,Q.jsx)(`p`,{children:`No workspace secrets configured.`}),tt&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:tt})]})]})]})})]}),Ge&&J&&(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog workspace-creation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`workspace-secret-title`,children:[(0,Q.jsxs)(`header`,{className:`workspace-creation-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Write-only value`}),(0,Q.jsx)(`h2`,{id:`workspace-secret-title`,children:Ze?`Replace workspace secret`:`Add workspace secret`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close workspace secret entry`,title:`Close workspace secret entry`,disabled:$e,onClick:()=>{Ke(!1),Je(``),Xe(``),Qe(!1),nt(null)},children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsx)(`p`,{children:`Kai stores the value without returning it to this or any other client.`}),(0,Q.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),Ir()},children:[(0,Q.jsx)(`label`,{htmlFor:`workspace-secret-key`,children:`Environment key`}),(0,Q.jsx)(`input`,{id:`workspace-secret-key`,type:`text`,autoFocus:!Ze,autoComplete:`off`,spellCheck:!1,maxLength:J.environmentPolicy.maximumKeyCharacters,value:qe,disabled:$e||Ze,onChange:e=>Je(e.target.value)}),(0,Q.jsx)(`label`,{htmlFor:`workspace-secret-value`,children:`Secret value`}),(0,Q.jsx)(`input`,{id:`workspace-secret-value`,type:`password`,autoFocus:Ze,autoComplete:`new-password`,value:Ye,disabled:$e,onChange:e=>Xe(e.target.value)}),tt&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:tt}),(0,Q.jsx)(`div`,{className:`form-actions`,children:(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:$e||!qe.trim()||!Ye,children:$e?`Saving…`:Ze?`Replace secret`:`Add secret`})})]})]})}),e&&q&&!J&&!fe&&(0,Q.jsxs)(`section`,{className:`settings-section`,id:`settings-section-workspace`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{children:`Workspace settings`}),(0,Q.jsx)(`p`,{children:`Runtime settings remain available, but workspace-specific overrides could not be loaded.`})]}),(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:_e??`Workspace settings are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void Bn(),children:`Retry`})]})]}),!e&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`section`,{className:`settings-section`,id:`settings-section-github`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`section-number`,children:`02`}),(0,Q.jsx)(`h2`,{children:`GitHub`}),(0,Q.jsx)(`p`,{children:`Personal notification subscriptions, automation choices, and a write-only access token. Repository execution authority remains operator controlled.`})]}),at?(0,Q.jsx)(`p`,{role:`status`,children:`Loading GitHub settings…`}):rt?(0,Q.jsxs)(`div`,{className:`settings-card-columns github-settings-grid`,children:[(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[(0,Q.jsxs)(`article`,{className:`settings-card policy-card`,children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Protected identity`}),(0,Q.jsx)(`dl`,{children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`GitHub login`}),(0,Q.jsx)(`dd`,{children:rt.githubLogin??`Not configured`})]})}),(0,Q.jsx)(`p`,{children:`This identity is operator managed and is used for GitHub actor routing.`})]}),(0,Q.jsxs)(`article`,{className:`settings-card`,children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Automation`}),(0,Q.jsxs)(`div`,{className:`github-toggle-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`PR reviews`}),(0,Q.jsxs)(`p`,{children:[rt.prReview.enabled?`On`:`Off`,` · `,rt.prReview.source]})]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsxs)(`button`,{className:`primary-button`,type:`button`,disabled:st,onClick:()=>void Rr({field:`toggle`,name:`pr_review`,enabled:!rt.prReview.enabled}),children:[`Turn `,rt.prReview.enabled?`off`:`on`]}),rt.prReview.resettable&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:st,onClick:()=>void Rr({field:`toggle`,name:`pr_review`,enabled:null},`Reset PR reviews to protected policy?`),children:`Reset`})]})]}),(0,Q.jsxs)(`div`,{className:`github-toggle-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`Issue triage`}),(0,Q.jsxs)(`p`,{children:[rt.issueTriage.enabled?`On`:`Off`,` · `,rt.issueTriage.source]})]}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsxs)(`button`,{className:`primary-button`,type:`button`,disabled:st,onClick:()=>void Rr({field:`toggle`,name:`issue_triage`,enabled:!rt.issueTriage.enabled}),children:[`Turn `,rt.issueTriage.enabled?`off`:`on`]}),rt.issueTriage.resettable&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:st,onClick:()=>void Rr({field:`toggle`,name:`issue_triage`,enabled:null},`Reset issue triage to protected policy?`),children:`Reset`})]})]})]})]}),(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[(0,Q.jsxs)(`article`,{className:`settings-card github-repositories-card`,children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Subscribed repositories`}),rt.repositories.length>0?(0,Q.jsx)(`ul`,{className:`github-repository-list`,children:rt.repositories.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.repository}),(0,Q.jsxs)(`small`,{children:[e.source,` · `,e.automationAuthorized?`automation authorized`:`notifications only`]})]}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:st,onClick:()=>void Rr({field:`repository`,name:e.repository,subscribed:!1},`Unsubscribe from ${e.repository}?`),children:`Remove`})]},e.repository))}):(0,Q.jsx)(`p`,{children:`No repository subscriptions.`}),(0,Q.jsxs)(`form`,{className:`github-add-repository`,onSubmit:e=>{e.preventDefault();let t=pt.trim();t&&Rr({field:`repository`,name:t,subscribed:!0}).then(e=>{e&&mt(``)})},children:[(0,Q.jsx)(`label`,{htmlFor:`github-repository`,children:`Add notification subscription`}),(0,Q.jsxs)(`div`,{className:`settings-inline-input`,children:[(0,Q.jsx)(`input`,{id:`github-repository`,type:`text`,value:pt,disabled:st,placeholder:`owner/repository`,autoCapitalize:`none`,autoCorrect:`off`,onChange:e=>mt(e.target.value)}),(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:st||!pt.trim(),children:`Add`})]}),(0,Q.jsx)(`p`,{children:`Subscriptions outside protected repository policy receive notifications only.`})]}),rt.repositoriesResettable&&(0,Q.jsx)(`div`,{className:`settings-actions`,children:(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:st,onClick:()=>void Rr({field:`repository_reset`},`Reset all repository subscriptions to protected policy?`),children:`Reset subscriptions`})})]}),(0,Q.jsxs)(`form`,{className:`settings-card github-token-card`,onSubmit:e=>{e.preventDefault(),ht.trim()&&Rr({field:`token`,token:ht},rt.tokenStored?`Replace the stored GitHub token?`:null)},children:[(0,Q.jsx)(`label`,{htmlFor:`github-token`,children:`GitHub access token`}),(0,Q.jsxs)(`p`,{children:[`Status: `,(0,Q.jsx)(`strong`,{children:rt.tokenStored?`Stored`:`Not set`})]}),(0,Q.jsx)(`input`,{id:`github-token`,type:`password`,value:ht,disabled:st,autoComplete:`new-password`,placeholder:rt.tokenStored?`Enter a replacement token`:`Enter a token`,onChange:e=>gt(e.target.value)}),(0,Q.jsx)(`p`,{children:`The existing token is never returned to this browser.`}),(0,Q.jsxs)(`div`,{className:`settings-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:st||!ht.trim(),children:rt.tokenStored?`Replace token`:`Store token`}),rt.tokenStored&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:st,onClick:()=>void Rr({field:`token`,token:null},`Remove the stored GitHub token? Automated GitHub actions may stop working.`),children:`Remove token`})]})]})]})]}):(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:lt??`GitHub settings are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void $n(),children:`Retry`})]}),dt&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:dt}),lt&&rt&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:lt})]}),(0,Q.jsxs)(`section`,{className:`settings-section`,id:`settings-section-notifications`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`section-number`,children:`03`}),(0,Q.jsx)(`h2`,{children:`Notification delivery`}),(0,Q.jsx)(`p`,{children:`Choose which channel activity reaches your inbox, when adapter delivery should pause, and where personal integration notifications appear.`})]}),(0,Q.jsxs)(`div`,{className:`settings-section-content notification-settings-content`,children:[kt&&(0,Q.jsx)(`p`,{role:`status`,children:`Loading channel notification policy…`}),!kt&&!Dt&&(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:Nt??`Channel notification policy is unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void tr(),children:`Retry`})]}),yt&&(0,Q.jsx)(`p`,{role:`status`,children:`Loading notification destinations…`}),!yt&&!_t&&(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:Ct??`Notification preferences are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void er(),children:`Retry`})]}),(Dt||_t)&&(0,Q.jsxs)(`div`,{className:`settings-card-columns notification-preference-grid`,children:[(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[Dt?.adapterDeliveries.map(e=>(0,Q.jsxs)(`article`,{className:`settings-card`,children:[(0,Q.jsxs)(`label`,{className:`settings-checkbox-row`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:e.enabled,disabled:jt,onChange:t=>void Br({field:`adapter_delivery`,transport:e.transport,enabled:t.target.checked})}),(0,Q.jsxs)(`span`,{children:[e.displayName,` alerts`]})]}),(0,Q.jsxs)(`p`,{children:[`Send human mention and reply alerts through `,e.displayName,`. Conversations remain available when alerts are off.`]}),(0,Q.jsx)(`p`,{children:e.source})]},`adapter-${e.transport}`)),Dt?.channels.map(e=>(0,Q.jsxs)(`article`,{className:`settings-card`,children:[(0,Q.jsx)(`label`,{htmlFor:`channel-notification-${e.channelId}`,children:e.channelName}),(0,Q.jsxs)(`select`,{id:`channel-notification-${e.channelId}`,value:e.level,disabled:jt,onChange:t=>void Br({field:`channel`,channelId:e.channelId,level:t.target.value}),children:[(0,Q.jsx)(`option`,{value:`all`,children:`All messages`}),(0,Q.jsx)(`option`,{value:`mentions_replies`,children:`Mentions and replies`}),(0,Q.jsx)(`option`,{value:`muted`,children:`Muted`})]}),(0,Q.jsx)(`p`,{children:e.source})]},e.channelId))]}),(0,Q.jsxs)(`div`,{className:`settings-card-column`,children:[Dt&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`article`,{className:`settings-card`,children:[(0,Q.jsxs)(`label`,{className:`settings-checkbox-row`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:Dt.mutedMentionsNotify,disabled:jt,onChange:e=>void Br({field:`muted_mentions_notify`,enabled:e.target.checked})}),(0,Q.jsx)(`span`,{children:`Direct mentions override muted channels`})]}),(0,Q.jsx)(`p`,{children:`A direct @mention can still create an in-app notification.`})]}),(0,Q.jsxs)(`article`,{className:`settings-card settings-dnd-card`,children:[(0,Q.jsx)(`h3`,{children:`Do not disturb`}),(0,Q.jsxs)(`label`,{className:`settings-checkbox-row`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:Lt,disabled:jt,onChange:e=>Rt(e.target.checked)}),(0,Q.jsx)(`span`,{children:`Pause external delivery on this schedule`})]}),(0,Q.jsx)(`label`,{htmlFor:`dnd-timezone`,children:`Timezone`}),(0,Q.jsx)(`select`,{id:`dnd-timezone`,value:zt,disabled:jt,onChange:e=>Bt(e.target.value),children:Kt.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))}),(0,Q.jsxs)(`div`,{className:`settings-inline-fields`,children:[(0,Q.jsxs)(`label`,{htmlFor:`dnd-start`,children:[`Start`,(0,Q.jsx)(`input`,{id:`dnd-start`,type:`text`,inputMode:`numeric`,pattern:`(?:[01][0-9]|2[0-3]):[0-5][0-9]`,maxLength:5,value:Vt,disabled:jt,onChange:e=>Ht(e.target.value),placeholder:`22:00`,autoComplete:`off`})]}),(0,Q.jsxs)(`label`,{htmlFor:`dnd-end`,children:[`End`,(0,Q.jsx)(`input`,{id:`dnd-end`,type:`text`,inputMode:`numeric`,pattern:`(?:[01][0-9]|2[0-3]):[0-5][0-9]`,maxLength:5,value:Ut,disabled:jt,onChange:e=>Wt(e.target.value),placeholder:`07:00`,autoComplete:`off`})]})]}),(0,Q.jsx)(`div`,{className:`settings-actions`,children:(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:jt||!Gt,onClick:()=>void Br({field:`do_not_disturb`,enabled:Lt,timezone:zt,start:Vt,end:Ut}),children:`Save schedule`})}),!Gt&&(0,Q.jsx)(`p`,{className:`settings-control-error`,role:`alert`,children:`Enter different start and end times in 24-hour HH:MM format.`}),(0,Q.jsx)(`p`,{children:`Workshop notifications remain immediate. Adapter delivery uses this policy.`})]})]}),_t?.preferences.map(e=>{let t=_t.destinations.filter(t=>t.supportedClasses.includes(e.integrationClass));return(0,Q.jsxs)(`article`,{className:`settings-card`,children:[(0,Q.jsx)(`label`,{htmlFor:`notification-${e.integrationClass}`,children:e.displayName}),(0,Q.jsx)(`select`,{id:`notification-${e.integrationClass}`,value:e.destinationChoiceId,disabled:xt||!e.editable,onChange:t=>void zr({field:`destination`,integrationClass:e.integrationClass,choiceId:t.target.value}),children:t.map(e=>(0,Q.jsxs)(`option`,{value:e.choiceId,children:[e.displayName,` · `,e.kind]},e.choiceId))}),(0,Q.jsxs)(`p`,{children:[`Effective: `,(0,Q.jsx)(`strong`,{children:e.destinationName}),` · ${e.source}`]}),e.resettable&&(0,Q.jsx)(`div`,{className:`settings-actions`,children:(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:xt,onClick:()=>void zr({field:`reset`,integrationClass:e.integrationClass},`Reset ${e.displayName} delivery to protected policy?`),children:`Reset`})})]},e.integrationClass)})]})]}),Ft&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:Ft}),Nt&&Dt&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:Nt}),Tt&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:Tt}),Ct&&_t&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:Ct})]})]}),(0,Q.jsxs)(`section`,{className:`settings-section`,id:`settings-section-clients`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`section-number`,children:`04`}),(0,Q.jsx)(`h2`,{children:`Client preferences`}),(0,Q.jsx)(`p`,{children:`Control presentation on each connected client without changing how your other Kai clients behave.`})]}),(0,Q.jsxs)(`div`,{className:`settings-client-preferences`,children:[(0,Q.jsxs)(`div`,{className:`settings-card-columns`,children:[(0,Q.jsx)(`div`,{className:`settings-card-column`,children:cn?(0,Q.jsx)(`p`,{role:`status`,children:`Loading Workshop appearance…`}):rn?(0,Q.jsxs)(`article`,{className:`settings-card settings-appearance-card`,children:[(0,Q.jsx)(`h3`,{children:`Workshop appearance`}),(0,Q.jsx)(`p`,{children:`This theme follows your Workshop account across enrolled browsers.`}),(0,Q.jsx)(`label`,{htmlFor:`workshop-theme`,children:`Theme`}),(0,Q.jsx)(`select`,{id:`workshop-theme`,value:on,disabled:un,onChange:e=>void Hr(e.target.value),children:rn.themes.map(e=>(0,Q.jsx)(`option`,{value:e.themeId,children:e.displayName},e.themeId))})]}):(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:fn??`Appearance preferences are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void rr(),children:`Retry`})]})}),(0,Q.jsx)(`div`,{className:`settings-card-column`,children:Yt?(0,Q.jsx)(`p`,{role:`status`,children:`Loading client preferences…`}):qt?qt.voiceOutput.bindings.length>0?(0,Q.jsx)(Q.Fragment,{children:qt.voiceOutput.bindings.map(e=>(0,Q.jsxs)(`article`,{className:`settings-card`,children:[(0,Q.jsxs)(`h3`,{children:[e.clientName,` voice output`]}),!qt.voiceOutput.available&&(0,Q.jsx)(`p`,{children:qt.voiceOutput.unavailableReason}),(0,Q.jsx)(`label`,{htmlFor:`client-mode-${e.choiceId}`,children:`Response format`}),(0,Q.jsx)(`select`,{id:`client-mode-${e.choiceId}`,value:e.mode,disabled:Zt||!e.editable,onChange:t=>void Vr({field:`mode`,bindingChoiceId:e.choiceId,value:t.target.value}),children:qt.voiceOutput.modes.map(e=>(0,Q.jsx)(`option`,{value:e,children:tg[e]},e))}),(0,Q.jsx)(`label`,{htmlFor:`client-voice-${e.choiceId}`,children:`Voice`}),(0,Q.jsx)(`select`,{id:`client-voice-${e.choiceId}`,value:e.voice,disabled:Zt||!e.editable,onChange:t=>void Vr({field:`voice`,bindingChoiceId:e.choiceId,value:t.target.value}),children:qt.voiceOutput.voices.map(e=>(0,Q.jsx)(`option`,{value:e.value,children:e.displayName},e.value))})]},e.choiceId))}):(0,Q.jsx)(`p`,{children:`No voice-capable client binding is available for this account.`}):(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:$t??`Client preferences are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void nr(),children:`Retry`})]})})]}),mn&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:mn}),fn&&rn&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:fn}),tn&&(0,Q.jsx)(`p`,{className:`settings-notice`,role:`status`,children:tn}),$t&&qt&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:$t})]})]}),u&&(0,Q.jsxs)(`section`,{className:`settings-section`,id:`settings-section-administration`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`section-number`,children:`05`}),(0,Q.jsx)(`h2`,{children:`Administration`}),(0,Q.jsx)(`p`,{children:`Read-only host service and integration health. Secrets, credentials, filesystem paths, and network addresses are never displayed.`})]}),(0,Q.jsxs)(`div`,{className:`settings-section-content administration-settings-content`,children:[vn?(0,Q.jsx)(`p`,{role:`status`,children:`Loading service and integration diagnostics…`}):gn?(0,Q.jsxs)(`article`,{className:`settings-card webhook-diagnostics-card`,children:[(0,Q.jsxs)(`div`,{className:`webhook-diagnostics-heading`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Service and integrations`}),(0,Q.jsx)(`h3`,{children:`Webhook diagnostics`})]}),(0,Q.jsx)(`span`,{className:`webhook-diagnostic-state`,"data-state":gn.state,children:gn.state})]}),(0,Q.jsxs)(`dl`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Shared listener`}),(0,Q.jsx)(`dd`,{children:gn.listener.state})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Port`}),(0,Q.jsx)(`dd`,{children:gn.listener.port})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Recent delivery health`}),(0,Q.jsxs)(`dd`,{children:[gn.deliveries.state,` · `,gn.deliveries.windowHours,`h`]})]})]}),(0,Q.jsxs)(`p`,{className:`settings-help`,children:[gn.deliveries.pending,` pending · `,gn.deliveries.executing,` executing · `,gn.deliveries.retrying,` retrying · `,gn.deliveries.succeeded,` succeeded · `,gn.deliveries.failed,` failed`]}),(0,Q.jsxs)(`details`,{className:`webhook-diagnostics-detail`,children:[(0,Q.jsx)(`summary`,{children:`Endpoint classes`}),(0,Q.jsx)(`ul`,{children:gn.endpoints.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:e.displayName}),(0,Q.jsx)(`span`,{className:`webhook-diagnostic-state`,"data-state":e.state,children:e.state})]}),(0,Q.jsx)(`p`,{children:e.description})]},e.endpointClass))})]}),gn.guidance.length>0&&(0,Q.jsxs)(`details`,{className:`webhook-diagnostics-detail`,children:[(0,Q.jsx)(`summary`,{children:`Setup guidance`}),(0,Q.jsx)(`ul`,{children:gn.guidance.map(e=>(0,Q.jsx)(`li`,{children:e},e))})]}),(0,Q.jsx)(`p`,{className:`settings-help`,children:`Diagnostics are read-only. Installation and webhook registration remain operator actions.`})]}):(0,Q.jsxs)(`div`,{className:`settings-failure`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:bn??`Webhook diagnostics are unavailable.`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:()=>void yr(),children:`Retry`})]}),bn&&gn&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:bn})]})]})]})]})]})}function hg(e){return(0,Q.jsx)(Gm,{children:(0,Q.jsx)(mg,{...e})})}function gg(e){return(0,Q.jsx)(Gm,{children:(0,Q.jsx)(mg,{...e,agentRuntime:!0,nativeAgentRuntime:!0,onClose:()=>void 0,onDirtyChange:()=>void 0})})}function _g(){let e=new Uint8Array(12);return crypto.getRandomValues(e),`workshop-review:${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function vg(e){let t=e.trim(),n=/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:[/?#].*)?$/i.exec(t);if(n)return{repository:`${n[1]}/${n[2]}`.toLocaleLowerCase(),number:Number(n[3])};let r=/^([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#(\d+)$/.exec(t);if(r)return{repository:r[1].toLocaleLowerCase(),number:Number(r[2])};let i=/^#?(\d+)$/.exec(t);return i?{repository:null,number:Number(i[1])}:null}function yg({onAuthenticationFailure:e,onChannelAccessFailure:t,onClose:n,onSubmitted:r,session:i}){let[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(``),[l,u]=(0,v.useState)(``),[d,f]=(0,v.useState)(!0),[p,m]=(0,v.useState)(!1),[h,g]=(0,v.useState)(null),_=(0,v.useMemo)(()=>vg(s),[s]);(0,v.useEffect)(()=>{let n=!1;return $n(i).then(e=>{n||(o(e),u(e.submission.inferredRepository??(e.submission.repositories.length===1?e.submission.repositories[0]:``)))}).catch(r=>{n||(r instanceof B?e(r.message):r instanceof V?t(r.message):g(r instanceof Error?r.message:`Could not load review options.`))}).finally(()=>{n||f(!1)}),()=>{n=!0}},[e,t,i]);let y=_?.repository??(l||null),b=_!==null&&y!==null&&a?.submission.repositories.includes(y)===!0,x=async a=>{if(a.preventDefault(),!(!_||!y||!b)){m(!0),g(null);try{await er(i,y,_.number,_g()),r(),n()}catch(n){n instanceof B?e(n.message):n instanceof V?t(n.message):g(n instanceof Error?n.message:`Could not start the review.`)}finally{m(!1)}}};return(0,Q.jsx)(`div`,{className:`action-palette-backdrop`,onMouseDown:n,children:(0,Q.jsxs)(`section`,{"aria-labelledby":`review-dialog-title`,"aria-modal":`true`,className:`review-dialog`,onMouseDown:e=>e.stopPropagation(),role:`dialog`,children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`GitHub`}),(0,Q.jsx)(`h2`,{id:`review-dialog-title`,children:`Review pull request`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close review`,title:`Close`,onClick:n,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),d?(0,Q.jsx)(`p`,{role:`status`,children:`Loading authorized repositories…`}):a?(0,Q.jsxs)(`form`,{onSubmit:e=>void x(e),children:[(0,Q.jsx)(`label`,{htmlFor:`review-reference`,children:`Pull request`}),(0,Q.jsx)(`input`,{autoFocus:!0,id:`review-reference`,placeholder:`GitHub URL, owner/repository#123, or 123`,value:s,onChange:e=>c(e.target.value)}),(0,Q.jsx)(`label`,{htmlFor:`review-repository`,children:`Authorized repository`}),(0,Q.jsxs)(`select`,{id:`review-repository`,disabled:_!==null&&_.repository!==null,value:y??``,onChange:e=>u(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:`Choose a repository`}),a.submission.repositories.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]}),(0,Q.jsxs)(`div`,{className:`review-context`,children:[(0,Q.jsx)(`strong`,{children:`Active workspace`}),(0,Q.jsx)(`span`,{children:a.submission.activeWorkspace}),(0,Q.jsx)(`small`,{children:a.submission.activeWorkspaceRepository?`GitHub repository: ${a.submission.activeWorkspaceRepository}`:`No GitHub repository was detected for this workspace.`})]}),_?.repository&&!a.submission.repositories.includes(_.repository)&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:`That repository is not authorized for review.`}),h&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:h}),(0,Q.jsx)(`div`,{className:`form-actions`,children:(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:p||!b,children:p?`Starting…`:`Start review`})})]}):(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:h??`Review options are unavailable.`})]})})}var bg=[{description:`Create ordinary text responses.`,label:`Text generation`,value:`text_generation`},{description:`Expose bounded tool activity in the run inspector.`,label:`Tool activity`,value:`tool_activity`},{description:`Work within an already-authorized workspace.`,label:`Workspace execution`,value:`workspace_execution`},{description:`Accept images when the selected runtime supports them.`,label:`Image input`,value:`image_input`},{description:`Delegate bounded tasks to other active agents in a shared channel.`,label:`Agent delegation`,value:`agent_delegation`}],xg=[{description:`Read bounded canonical conversation context.`,label:`Context reading`,value:`context_read`},{description:`Add or remove reactions on messages.`,label:`Reactions`,value:`reaction`},{description:`Publish visible progress updates while working.`,label:`Progress updates`,value:`progress_publish`},{description:`Reply inside an existing thread.`,label:`Thread replies`,value:`thread_reply`},{description:`Publish a bounded artifact with provenance.`,label:`Artifacts`,value:`artifact_publish`},{description:`Delegate bounded work to another active agent.`,label:`Agent delegation`,value:`agent_delegation`},{description:`Remain available for bounded observation in opted-in group channels.`,label:`Standing participation`,value:`standing_participation`}],Sg={avatar:``,capabilities:[`text_generation`],collaborationOperations:[],description:``,displayName:``,handle:``,instructions:``,purpose:``},Cg=[`Identity`,`Role`,`Runtime`,`Review`];function wg(){if(typeof globalThis.crypto?.getRandomValues!=`function`)throw Error(`This browser cannot create secure operation identities.`);let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),`workshop-agent-provision-${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function Tg(e){let t=e.normalize(`NFKD`).replace(/[\u0300-\u036f]/g,``).toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``);return t?(/^[a-z]/.test(t)?t:`agent_${t}`).slice(0,32).replace(/_+$/g,``):``}function Eg(e){return`${e.backend} · ${e.provider}`}function Dg(e){return e.blockers.length===0&&e.readiness!==`unavailable`&&e.readiness!==`misconfigured`}function Og(e){let t=e.backends.find(t=>t.optionId===e.currentBackendOptionId);return t&&Dg(t)?t:e.backends.find(Dg)??t??e.backends[0]??null}function kg(e){return e.models.find(t=>t.modelId===e.defaultModel&&t.selectable)?.modelId??e.models.find(e=>e.selectable)?.modelId??``}function Ag(e){return e.workspaces.find(t=>t.path===e.defaultWorkspace&&t.available)?.path??e.workspaces.find(e=>e.available)?.path??``}function jg(e){return e?{backend_selected:`apply the backend`,collaboration_policy_set:`apply collaboration limits`,definition_created:`save the definition`,enablement_created:`authorize its runtime`,model_selected:`apply the model`,ready:`finish setup`,revision_activated:`activate Revision 1`,runtime_registered:`connect the runtime`,timeout_selected:`apply the response timeout`,workspace_selected:`apply the workspace`}[e]??`continue setup`:`finish setup`}function Mg({disabled:e,kind:t,selected:n,onChange:r}){return(0,Q.jsxs)(`fieldset`,{className:`agent-capability-choices`,disabled:e,children:[(0,Q.jsx)(`legend`,{children:t===`capabilities`?`Declared capabilities`:`Collaboration tools`}),(0,Q.jsx)(`p`,{children:t===`capabilities`?`Capabilities describe requirements; they do not grant credentials or data access.`:`Requested tools remain bounded by owner and host policy on every attempt.`}),(t===`capabilities`?bg:xg).map(e=>(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:n.includes(e.value),onChange:t=>{r(t.target.checked?[...n,e.value]:n.filter(t=>t!==e.value))}}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.label}),(0,Q.jsx)(`small`,{children:e.description})]})]},e.value))]})}function Ng({busy:e,existingHandles:t,options:n,optionsError:r,optionsLoading:i,resumeDraft:a,resumeInput:o,resumeProvisioning:s,onCancel:c,onCreateReady:l,onSaveDraft:u}){let d=Km(),f=o?{avatar:o.avatar,capabilities:o.capabilities,collaborationOperations:o.collaborationOperations,description:o.description,displayName:o.displayName,handle:o.handle,instructions:o.instructions,purpose:o.purpose}:a??Sg,[p,m]=(0,v.useState)(f),[h,g]=(0,v.useState)(o?`Review`:a?`Runtime`:`Identity`),[_,y]=(0,v.useState)(!1),[b,x]=(0,v.useState)(!0),[S,C]=(0,v.useState)(o?.runtimeProfileId??``),[w,T]=(0,v.useState)(o?.backendOptionId??``),[E,D]=(0,v.useState)(o?.model??``),[O,k]=(0,v.useState)({}),[A,j]=(0,v.useState)(o?.workspace??``),[M,N]=(0,v.useState)(null),[P,F]=(0,v.useState)(null),[I,L]=(0,v.useState)(o),[R,ee]=(0,v.useState)(s),[z]=(0,v.useState)(o?.clientOperationId??wg),B=n?.runtimes.find(e=>e.runtimeProfileId===S)??null,V=B?.backends.find(e=>e.optionId===w)??null,H=V?.models.find(e=>e.modelId===E)??null,te=B?.workspaces.find(e=>e.path===A)??null,U=I!==null;(0,v.useEffect)(()=>{if(!n||S||n.runtimes.length===0)return;let e=n.runtimes.find(e=>e.ready)??n.runtimes[0];if(!e)return;let t=Og(e),r=t?kg(t):``;C(e.runtimeProfileId),T(t?.optionId??``),D(r),k(t?{[t.optionId]:r}:{}),j(Ag(e))},[n,S]);let ne=(0,v.useMemo)(()=>{let e=[];return i&&e.push(`Runtime choices are still loading.`),r&&e.push(r),!i&&!n&&!r&&e.push(`Runtime choices are unavailable.`),n&&!n.ready&&e.push(...n.blockers.map(e=>e.detail)),B&&!B.ready&&(e.push(...B.blockers.map(e=>e.detail)),B.blockers.length===0&&e.push(`The selected runtime is not ready.`)),B&&!V&&e.push(`Choose an authorized backend.`),V&&(e.push(...V.blockers.map(e=>e.detail)),!Dg(V)&&V.blockers.length===0&&e.push(`${Eg(V)} is not ready for agent creation.`)),V&&(!H||!H.selectable)&&e.push(`Choose an available model for the selected backend.`),B&&(!te||!te.available)&&e.push(`Choose an available workspace.`),[...new Set(e)]},[n,r,i,V,H,B,te]),re=e=>{m(t=>({...t,...e})),y(!0),F(null)},W=async()=>{e||_&&!await d(`Discard your unsaved agent changes?`)||c()},ie=()=>p.displayName.trim()?/^[a-z][a-z0-9_]{0,31}$/.test(p.handle)?t.includes(p.handle)&&p.handle!==o?.handle&&p.handle!==a?.handle?`@${p.handle} is already in use. Choose another handle.`:null:`Use a handle beginning with a lowercase letter and containing only lowercase letters, numbers, and underscores.`:`Enter a display name.`,ae=()=>p.purpose.trim()?p.instructions.trim()?p.capabilities.length===0?`Select at least one declared capability.`:null:`Describe how this agent should behave.`:`Describe what this agent should do.`,oe=()=>{let e=h===`Identity`?ie():h===`Role`?ae():null;if(e){F(e);return}let t=Cg[Cg.indexOf(h)+1];t&&(F(null),g(t))},se=()=>{let e=Cg[Cg.indexOf(h)-1];e&&!U&&(F(null),g(e))},ce=e=>{let t=n?.runtimes.find(t=>t.runtimeProfileId===e);if(!t)return;let r=Og(t),i=r?O[r.optionId]||kg(r):``;C(t.runtimeProfileId),T(r?.optionId??``),D(i),j(Ag(t)),N(null),y(!0),F(null)},le=e=>{let t=B?.backends.find(t=>t.optionId===e);if(!t)return;let n=O[t.optionId],r=t.models.find(e=>e.modelId===E&&e.selectable)?.modelId,i=n||r||kg(t);T(t.optionId),D(i),k(e=>({...e,[t.optionId]:i})),N(r||n?null:i?`Model set to ${i}, the protected default for ${Eg(t)}.`:`No available model was found for ${Eg(t)}.`),y(!0),F(null)},ue=async()=>{let e=ie()??ae();if(e){F(e);return}F(null);try{await u(p)}catch(e){F(e instanceof Error?e.message:`Could not save this draft.`)}},G=async()=>{let e=ie()??ae();if(e){F(e);return}if(ne.length>0||!B||!V){F(ne[0]??`Runtime choices are incomplete.`);return}let t=I??{allowedCollaborationOperations:p.collaborationOperations,avatar:p.avatar,backendOptionId:V.optionId,capabilities:p.capabilities,clientOperationId:z,collaborationOperations:p.collaborationOperations,description:p.description,displayName:p.displayName,...a?{existingDefinitionId:a.definitionId}:{},handle:p.handle,instructions:p.instructions,model:E,purpose:p.purpose,runtimeProfileId:B.runtimeProfileId,timeoutSeconds:B.defaultTimeoutSeconds,workspace:A};L(t),F(null);try{let e=await l(t);e.status!==`ready`&&(ee(e),F(e.blockers[0]?.detail??`Agent setup needs attention. Your progress was saved and can be retried safely.`))}catch(e){F(e instanceof Error?e.message:`Could not create this agent.`)}},K=e=>{e.preventDefault(),h===`Review`?G():oe()},q=Cg.indexOf(h);return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsx)(`section`,{className:`channel-creation-dialog agent-creation-dialog agent-creation-wizard`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`create-agent-title`,children:(0,Q.jsxs)(`form`,{className:`agent-editor`,onSubmit:K,children:[(0,Q.jsxs)(`div`,{className:`agent-creation-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:o?`Saved agent setup`:a?`Draft agent`:`New software participant`}),(0,Q.jsx)(`h2`,{id:`create-agent-title`,children:o||a?`Continue ${p.displayName}`:`Create agent`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close agent creation`,title:`Close agent creation`,onClick:()=>void W(),disabled:e,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsx)(`ol`,{className:`agent-creation-progress`,"aria-label":`Agent creation progress`,children:Cg.map((e,t)=>(0,Q.jsxs)(`li`,{className:t<=q?`active`:void 0,"aria-current":e===h?`step`:void 0,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:t+1}),e]},e))}),h===`Identity`&&(0,Q.jsxs)(`section`,{className:`agent-creation-stage`,"aria-labelledby":`agent-identity-heading`,children:[(0,Q.jsxs)(`div`,{className:`agent-creation-stage-heading`,children:[(0,Q.jsx)(`h3`,{id:`agent-identity-heading`,children:`Identity`}),(0,Q.jsx)(`p`,{children:`How this agent will appear to people in Workshop.`})]}),(0,Q.jsxs)(`div`,{className:`agent-editor-grid`,children:[(0,Q.jsxs)(`label`,{children:[`Display name`,(0,Q.jsx)(`input`,{autoFocus:!0,maxLength:80,required:!0,disabled:U,value:p.displayName,onChange:e=>{let t=e.target.value;re({displayName:t,...b?{handle:Tg(t)}:{}})}})]}),(0,Q.jsxs)(`label`,{children:[`Handle`,(0,Q.jsx)(`span`,{className:`agent-field-hint`,children:`Unique, stable, and editable`}),(0,Q.jsxs)(`div`,{className:`agent-handle-input`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`@`}),(0,Q.jsx)(`input`,{maxLength:32,pattern:`[a-z][a-z0-9_]{0,31}`,required:!0,disabled:U,value:p.handle,onChange:e=>{x(!1),re({handle:e.target.value.toLowerCase()})}})]})]}),(0,Q.jsxs)(`label`,{children:[`Avatar text`,(0,Q.jsx)(`span`,{className:`agent-field-hint`,children:`Optional, up to 16 characters`}),(0,Q.jsx)(`input`,{maxLength:16,disabled:U,value:p.avatar,onChange:e=>re({avatar:e.target.value})})]})]}),(0,Q.jsxs)(`label`,{children:[`Description`,(0,Q.jsx)(`span`,{className:`agent-field-hint`,children:`A concise summary shown to other Workshop members`}),(0,Q.jsx)(`textarea`,{maxLength:1e3,rows:3,disabled:U,value:p.description,onChange:e=>re({description:e.target.value})})]})]}),h===`Role`&&(0,Q.jsxs)(`section`,{className:`agent-creation-stage`,"aria-labelledby":`agent-role-heading`,children:[(0,Q.jsxs)(`div`,{className:`agent-creation-stage-heading`,children:[(0,Q.jsx)(`h3`,{id:`agent-role-heading`,children:`Role`}),(0,Q.jsx)(`p`,{children:`Define the agent's purpose and behavioral boundaries.`})]}),(0,Q.jsxs)(`label`,{children:[`What should this agent do?`,(0,Q.jsx)(`textarea`,{autoFocus:!0,maxLength:2e3,required:!0,rows:4,disabled:U,value:p.purpose,onChange:e=>re({purpose:e.target.value})})]}),(0,Q.jsxs)(`label`,{children:[`How should it behave?`,(0,Q.jsx)(`span`,{className:`agent-field-hint`,children:`Instructions cannot grant authority.`}),(0,Q.jsx)(`textarea`,{maxLength:2e4,required:!0,rows:8,disabled:U,value:p.instructions,onChange:e=>re({instructions:e.target.value})})]}),(0,Q.jsxs)(`details`,{className:`agent-creation-advanced`,children:[(0,Q.jsx)(`summary`,{children:`Advanced capabilities`}),Mg({disabled:e||U,kind:`capabilities`,selected:p.capabilities,onChange:e=>re({capabilities:e})}),Mg({disabled:e||U,kind:`collaboration`,selected:p.collaborationOperations,onChange:e=>re({collaborationOperations:e})})]})]}),h===`Runtime`&&(0,Q.jsxs)(`section`,{className:`agent-creation-stage`,"aria-labelledby":`agent-runtime-heading`,children:[(0,Q.jsxs)(`div`,{className:`agent-creation-stage-heading`,children:[(0,Q.jsx)(`h3`,{id:`agent-runtime-heading`,children:`Runtime`}),(0,Q.jsx)(`p`,{children:`Choose from runtime access already authorized for you.`})]}),i&&(0,Q.jsx)(`p`,{className:`agent-creation-loading`,role:`status`,children:`Loading runtime choices…`}),!i&&B&&(0,Q.jsxs)(`div`,{className:`agent-runtime-choice-grid`,children:[n&&n.runtimes.length>1&&(0,Q.jsxs)(`details`,{className:`agent-creation-advanced agent-runtime-profile-choice`,children:[(0,Q.jsx)(`summary`,{children:`Advanced runtime`}),(0,Q.jsxs)(`label`,{children:[`Execution profile`,(0,Q.jsx)(`select`,{value:S,disabled:e||U,onChange:e=>ce(e.target.value),children:n.runtimes.map(e=>(0,Q.jsx)(`option`,{value:e.runtimeProfileId,children:e.displayName},e.runtimeProfileId))})]})]}),(0,Q.jsxs)(`label`,{children:[`Backend`,(0,Q.jsx)(`select`,{autoFocus:!0,value:w,disabled:e||U,onChange:e=>le(e.target.value),children:B.backends.map(e=>(0,Q.jsx)(`option`,{value:e.optionId,disabled:!Dg(e),children:Eg(e)},e.optionId))})]}),(0,Q.jsxs)(`label`,{children:[`Model`,(0,Q.jsx)(`select`,{value:E,disabled:e||U||!V,onChange:e=>{let t=e.target.value;D(t),k(e=>({...e,[w]:t})),N(null),y(!0),F(null)},children:V?.models.map(e=>(0,Q.jsx)(`option`,{value:e.modelId,disabled:!e.selectable,children:e.displayName},e.modelId))})]}),(0,Q.jsxs)(`label`,{children:[`Workspace`,(0,Q.jsx)(`select`,{value:A,disabled:e||U,onChange:e=>{j(e.target.value),y(!0),F(null)},children:B.workspaces.map(e=>(0,Q.jsx)(`option`,{value:e.path,disabled:!e.available,children:e.name},e.path))})]}),M&&(0,Q.jsx)(`p`,{className:`agent-runtime-notice`,role:`status`,children:M})]}),!i&&ne.length>0&&(0,Q.jsxs)(`section`,{className:`agent-creation-blockers`,"aria-label":`Creation readiness`,children:[(0,Q.jsx)(`strong`,{children:`Ready creation is not currently available`}),(0,Q.jsx)(`ul`,{children:ne.map(e=>(0,Q.jsx)(`li`,{children:e},e))}),(0,Q.jsx)(`p`,{children:`You can continue reviewing this agent and save it as a draft.`})]})]}),h===`Review`&&(0,Q.jsxs)(`section`,{className:`agent-creation-stage`,"aria-labelledby":`agent-review-heading`,children:[(0,Q.jsxs)(`div`,{className:`agent-creation-stage-heading`,children:[(0,Q.jsx)(`h3`,{id:`agent-review-heading`,children:`Review`}),(0,Q.jsx)(`p`,{children:`Confirm the definition and runtime choices before creating the agent.`})]}),(0,Q.jsxs)(`dl`,{className:`agent-creation-review`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Agent`}),(0,Q.jsxs)(`dd`,{children:[p.displayName,` · @`,p.handle]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Purpose`}),(0,Q.jsx)(`dd`,{children:p.purpose})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Backend`}),(0,Q.jsx)(`dd`,{children:V?Eg(V):`Not available`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Model`}),(0,Q.jsx)(`dd`,{children:(H?.displayName??E)||`Not available`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Workspace`}),(0,Q.jsx)(`dd`,{children:te?.name??`Not available`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Advanced requests`}),(0,Q.jsx)(`dd`,{children:p.collaborationOperations.length>0?p.collaborationOperations.map(e=>e.replaceAll(`_`,` `)).join(`, `):`None`})]})]}),(0,Q.jsx)(`p`,{className:`agent-conversation-notice`,children:`Creating this agent will not start a direct conversation or add it to a channel.`}),ne.length>0&&(0,Q.jsxs)(`section`,{className:`agent-creation-blockers`,"aria-label":`Creation readiness`,children:[(0,Q.jsx)(`strong`,{children:`Save as draft to keep this definition`}),(0,Q.jsx)(`ul`,{children:ne.map(e=>(0,Q.jsx)(`li`,{children:e},e))})]}),e&&(0,Q.jsx)(`p`,{className:`agent-creation-loading`,role:`status`,children:`Creating the agent and applying its runtime settings…`}),R&&R.status!==`ready`&&(0,Q.jsxs)(`section`,{className:`agent-creation-recovery`,children:[(0,Q.jsx)(`strong`,{children:`Setup needs attention`}),(0,Q.jsxs)(`p`,{children:[`Your choices and completed work are saved. The next step is to `,jg(R.nextStage),`.`]}),(0,Q.jsx)(`p`,{children:`Retry continues this exact setup without creating a duplicate agent.`}),(0,Q.jsxs)(`details`,{children:[(0,Q.jsx)(`summary`,{children:`Setup diagnostics`}),(0,Q.jsx)(`code`,{children:R.operationId}),(0,Q.jsxs)(`small`,{children:[R.completedStages.length,` completed stages · next: `,R.nextStage??`finish`]})]})]})]}),P&&(0,Q.jsx)(`p`,{className:`form-error agent-creation-error`,role:`alert`,children:P}),(0,Q.jsxs)(`div`,{className:`form-actions agent-creation-actions`,children:[(0,Q.jsx)(`span`,{children:q>0&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Back to ${Cg[q-1]}`,title:`Back to ${Cg[q-1]}`,disabled:e||U,onClick:se,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`←`})})}),(0,Q.jsx)(`span`,{className:`agent-creation-primary-actions`,children:h===`Review`?(0,Q.jsxs)(Q.Fragment,{children:[!a&&!o&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:e||U,onClick:()=>void ue(),children:`Save as draft`}),(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:e||ne.length>0,children:e?`Completing setup…`:U?`Retry setup`:a?`Complete setup`:`Create agent`})]}):(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:e||U,children:`Continue`})})]})]})})})}function Pg(e){if(typeof globalThis.crypto?.getRandomValues!=`function`)throw Error(`This browser cannot create secure operation identities.`);let t=new Uint8Array(16);return globalThis.crypto.getRandomValues(t),`workshop-agent-${e}-${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function Fg(e){return e.revisions.find(t=>t.revisionId===e.activeRevisionId)??null}function Ig(e){return e===`active`?`Ready`:e===`draft`?`Draft`:`Archived`}function Lg(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M20 15a3 3 0 0 1-3 3H9l-5 3V7a3 3 0 0 1 3-3h10a3 3 0 0 1 3 3z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`})})}function Rg(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}function zg({disabled:e,selected:t,onChange:n}){return(0,Q.jsxs)(`fieldset`,{className:`agent-capability-choices`,disabled:e,children:[(0,Q.jsx)(`legend`,{children:`Declared capabilities`}),(0,Q.jsx)(`p`,{children:`Capabilities describe requirements. They never grant tools, credentials, workspaces, services, or data access.`}),bg.map(e=>(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t.includes(e.value),onChange:r=>{n(r.target.checked?[...t,e.value]:t.filter(t=>t!==e.value))}}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.label}),(0,Q.jsx)(`small`,{children:e.description})]})]},e.value))]})}function Bg({disabled:e,selected:t,onChange:n}){return(0,Q.jsxs)(`fieldset`,{className:`agent-capability-choices`,disabled:e,children:[(0,Q.jsx)(`legend`,{children:`Requested collaboration tools`}),(0,Q.jsx)(`p`,{children:`This immutable revision requests operations. Owner and host policy still decide what a run actually receives.`}),xg.map(e=>(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t.includes(e.value),onChange:r=>n(r.target.checked?[...t,e.value]:t.filter(t=>t!==e.value))}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.label}),(0,Q.jsx)(`small`,{children:e.description})]})]},e.value))]})}function Vg({agent:e,busy:t,onCancel:n,onSave:r}){let i=e.revisions[e.revisions.length-1],[a,o]=(0,v.useState)(i?.purpose??``),[s,c]=(0,v.useState)(i?.instructions??``),[l,u]=(0,v.useState)(i?.capabilities??[`text_generation`]),[d,f]=(0,v.useState)(i?.collaborationOperations??[]),[p,m]=(0,v.useState)(null),h=async e=>{if(e.preventDefault(),l.length===0){m(`Select at least one declared capability.`);return}m(null);try{await r({capabilities:l,collaborationOperations:d,instructions:s,purpose:a})}catch(e){m(e instanceof Error?e.message:`Could not save this revision.`)}};return(0,Q.jsxs)(`form`,{className:`agent-revision-editor`,onSubmit:e=>void h(e),children:[(0,Q.jsx)(`h3`,{children:`New definition revision`}),(0,Q.jsx)(`p`,{children:`Saving creates an immutable revision. Activate it separately after review.`}),(0,Q.jsxs)(`label`,{children:[`Purpose`,(0,Q.jsx)(`textarea`,{maxLength:2e3,required:!0,rows:3,value:a,onChange:e=>o(e.target.value)})]}),(0,Q.jsxs)(`label`,{children:[`Instructions`,(0,Q.jsx)(`textarea`,{maxLength:2e4,required:!0,rows:10,value:s,onChange:e=>c(e.target.value)})]}),(0,Q.jsx)(zg,{disabled:t,selected:l,onChange:u}),(0,Q.jsx)(Bg,{disabled:t,selected:d,onChange:f}),p&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:p}),(0,Q.jsxs)(`div`,{className:`form-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:t,children:t?`Saving…`:`Save revision`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:n,disabled:t,children:`Cancel`})]})]})}function Hg({busy:e,policy:t,onRevoke:n,onSave:r}){let[i,a]=(0,v.useState)(t.operations.filter(e=>e.ownerAllowed).map(e=>e.operation));(0,v.useEffect)(()=>{a(t.operations.filter(e=>e.ownerAllowed).map(e=>e.operation))},[t]);let o=t.canManage&&t.operations.some(e=>e.ownerAllowed!==i.includes(e.operation));return(0,Q.jsxs)(`section`,{className:`agent-collaboration-policy`,children:[(0,Q.jsx)(`div`,{className:`agent-section-heading`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:t.canManage?`Owner policy`:`Collaboration access`}),(0,Q.jsx)(`h3`,{children:`Collaboration tools`}),t.canManage?(0,Q.jsx)(`p`,{children:`Policy changes apply to newly accepted attempts. Active attempts retain their immutable snapshot unless you revoke them below.`}):(0,Q.jsx)(`p`,{children:`This read-only view shows revision requests and resulting availability. Owner policy and active-run details remain private.`})]})}),(0,Q.jsx)(`div`,{className:`collaboration-policy-grid`,role:`list`,children:t.operations.map(n=>{let r=xg.find(e=>e.value===n.operation);return(0,Q.jsxs)(`article`,{role:`listitem`,children:[(0,Q.jsxs)(`label`,{children:[t.canManage&&(0,Q.jsx)(`input`,{type:`checkbox`,checked:i.includes(n.operation),disabled:e||!n.hostAllowed,onChange:e=>a(t=>e.target.checked?[...t,n.operation]:t.filter(e=>e!==n.operation))}),(0,Q.jsx)(`strong`,{children:r?.label??n.operation.replaceAll(`_`,` `)})]}),(0,Q.jsxs)(`dl`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Revision`}),(0,Q.jsx)(`dd`,{children:n.requested?`requested`:`not requested`})]}),t.canManage&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Owner`}),(0,Q.jsx)(`dd`,{children:n.ownerAllowed?`allowed`:`blocked`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Host`}),(0,Q.jsx)(`dd`,{children:n.hostAllowed?`available`:`unavailable`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Next attempt`}),(0,Q.jsx)(`dd`,{children:n.effectiveForNewAttempt?`effective`:`not effective`})]})]}),n.unavailableReason&&(0,Q.jsx)(`small`,{children:n.unavailableReason}),n.quota!==null&&(0,Q.jsxs)(`small`,{children:[`Per-attempt quota: `,n.quota]})]},n.operation)})}),t.canManage&&(0,Q.jsxs)(`div`,{className:`collaboration-policy-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`button`,disabled:e||!o,onClick:()=>void r(i),children:`Save policy`}),(0,Q.jsxs)(`button`,{className:`danger-button`,type:`button`,disabled:e||(t.activeGrants??0)===0,onClick:()=>void n(),children:[`Revoke active access (`,t.activeGrants??0,`)`]})]})]})}function Ug({activeChannelId:e,initialCreating:t,initialDefinitionId:n,initialSetupId:r,initialSection:i,isAdministrator:a,onAuthenticationFailure:o,onChannelAccessFailure:s,onClose:c,onCreateAgent:l,onNavigationChanged:u,onOpenChannel:d,onSelectAgent:f,principalId:p,principalName:m,principalEvents:h,runActive:g,token:_,workshopName:y}){let b=Km(),[x,S]=(0,v.useState)([]),[C,w]=(0,v.useState)([]),[T,E]=(0,v.useState)([]),[D,O]=(0,v.useState)(null),[k,A]=(0,v.useState)(n),[j,M]=(0,v.useState)(t),[N,P]=(0,v.useState)(null),[F,I]=(0,v.useState)(null),[L,R]=(0,v.useState)(!1),[ee,z]=(0,v.useState)(null),[H,te]=(0,v.useState)(!1),[U,ne]=(0,v.useState)(``),[re,W]=(0,v.useState)(!0),[ie,ae]=(0,v.useState)(!1),[oe,se]=(0,v.useState)(null),ce=h.subscribe,le=(0,v.useCallback)((e,t)=>{e instanceof B?o(e.message):e instanceof V&&s(e.message),se(e instanceof Error?e.message:t)},[o,s]),ue=(0,v.useCallback)(async()=>{let[e,t,r]=await Promise.all([Le(_),He(_),Be(_)]);S(e),w(t),E(r),A(t=>{let r=t??n;return r&&e.some(e=>e.definitionId===r)?r:null})},[n,_]);(0,v.useEffect)(()=>{let e=!1;return W(!0),ue().then(()=>{e||(W(!1),se(null))},t=>{e||(W(!1),le(t,`Could not load agents.`))}),()=>{e=!0}},[le,ue]),(0,v.useEffect)(()=>ce(e=>{(e.kind===`synchronize`||e.batch.changes.some(e=>e.agentChanges.length>0))&&Promise.all([ue(),u()]).catch(e=>le(e,`Could not refresh agents.`))}),[le,u,ue,ce]);let G=x.find(e=>e.definitionId===k)??null,K=C.find(e=>e.definitionId===k)??null,q=G?Fg(G):null,de=T.find(e=>e.provisioning.operationId===r)??null,J=j&&!de&&G?.lifecycleState===`draft`?(()=>{let e=G.revisions[0];return e?{avatar:G.presentation.avatar??``,capabilities:e.capabilities,collaborationOperations:e.collaborationOperations,definitionId:G.definitionId,description:G.description,displayName:G.displayName,handle:G.handle,instructions:e.instructions,purpose:e.purpose}:null})():null,Y=!n&&!r,fe=G?.ownerPrincipalId===p,pe=(0,v.useMemo)(()=>K?.lifecycleState===`enabled`&&K.directChannelId?{channelId:K.directChannelId,token:_}:null,[K?.directChannelId,K?.lifecycleState,_]);(0,v.useEffect)(()=>{M(t),n&&A(n)},[t,n]),(0,v.useEffect)(()=>{re||!j||Y||de||J||(M(!1),f(k))},[j,Y,re,f,J,de,k]),(0,v.useEffect)(()=>{let e=!1;return j?(P(null),I(null),R(!0),Re(_).then(t=>{e||(P(t),R(!1))},t=>{e||(t instanceof B?o(t.message):t instanceof V&&s(t.message),I(t instanceof Error?t.message:`Could not load agent creation options.`),R(!1))}),()=>{e=!0}):(P(null),I(null),R(!1),()=>{e=!0})},[j,o,s,_]),(0,v.useEffect)(()=>{te(!1)},[k]),(0,v.useEffect)(()=>{let e=!1;return O(null),k&&Z(_,k).then(t=>{e||O(t)},t=>{e||le(t,`Could not load collaboration policy.`)}),()=>{e=!0}},[le,k,_]),(0,v.useEffect)(()=>{ne(K?.runtimeProfileId??K?.eligibleRuntimes[0]?.runtimeProfileId??``)},[K?.eligibleRuntimes,K?.runtimeProfileId]),(0,v.useEffect)(()=>{if(i!==`runtime`||!pe)return;let e=window.setTimeout(()=>{document.getElementById(`agent-runtime-settings`)?.scrollIntoView?.({block:`start`})},0);return()=>window.clearTimeout(e)},[i,pe]);let me=async(e,t)=>{ae(!0),se(null);try{await e()}catch(e){le(e,t)}finally{ae(!1)}},he=async(e,t)=>{await ue(),await u(),M(!1),A(e),z(t?e:null),f(e)},X=async e=>{ae(!0);try{let t=await $e(_,{...e,idempotencyKey:Pg(`create`)});await he(t.definitionId,!1)}catch(e){throw e instanceof B?o(e.message):e instanceof V&&s(e.message),e}finally{ae(!1)}},ge=async e=>{ae(!0);try{let t=await Ve(_,e);return t.status===`ready`&&t.definitionId?await he(t.definitionId,!0):(await ue(),await u()),t}catch(e){throw e instanceof B?o(e.message):e instanceof V&&s(e.message),e}finally{ae(!1)}},_e=e=>G?me(async()=>{await et(_,G.definitionId,{...e,expectedVersion:G.stateVersion,idempotencyKey:Pg(`revision`)}),await ue(),te(!1)},`Could not save this revision.`):Promise.resolve(),ve=e=>!G||!D?Promise.resolve():me(async()=>{let t=await Ze(_,G.definitionId,{allowedOperations:e,clientOperationId:Pg(`collaboration-policy`),expectedPolicyVersion:D.policyVersion});O(t)},`Could not update collaboration policy.`),ye=async()=>{!G||!D||!await b(`Immediately revoke active collaboration access for @${G.handle}? Current attempts will be fenced.`)||await me(async()=>{let e=await Qe(_,G.definitionId,Pg(`collaboration-revoke`));O(e)},`Could not revoke active collaboration access.`)},be=e=>G?me(async()=>{await tt(_,G.definitionId,{expectedVersion:G.stateVersion,idempotencyKey:Pg(`activate`),revisionId:e}),await ue(),O(await Z(_,G.definitionId)),await u()},`Could not activate this agent revision.`):Promise.resolve(),xe=async()=>{!G||!await b(`Archive @${G.handle}? Existing history remains available, but the agent will no longer be runnable.`)||await me(async()=>{await nt(_,G.definitionId,{expectedVersion:G.stateVersion,idempotencyKey:Pg(`archive`)}),await ue(),await u()},`Could not archive this agent.`)},Se=()=>!G||!K||!U?Promise.resolve():me(async()=>{await rt(_,G.definitionId,{expectedVersion:K.stateVersion,idempotencyKey:Pg(`enable`),runtimeProfileId:U}),await ue(),await u()},`Could not enable this agent.`),Ce=()=>{if(!G||!K)return Promise.resolve();let e=G.definitionId;return me(async()=>{let t=K;if(t.lifecycleState!==`enabled`){let n=t.eligibleRuntimes[0];if(t.canManage||!n)throw Error(`This agent conversation is not available.`);t=await rt(_,e,{expectedVersion:t.stateVersion,idempotencyKey:Pg(`conversation-access`),runtimeProfileId:n.runtimeProfileId})}if(!t.directChannelId||t.stateVersion===null||(t.conversationStarted||(t=await it(_,e,{expectedVersion:t.stateVersion,idempotencyKey:Pg(`conversation`)})),!t.directChannelId))throw Error(`This agent conversation is not available.`);await ue(),await u(),await d(t.directChannelId)},`Could not open this agent conversation.`)},we=(0,v.useMemo)(()=>{let e=new Set(T.map(e=>e.provisioning.definitionId));return{archived:x.filter(e=>e.lifecycleState===`archived`).length,drafts:x.filter(t=>t.lifecycleState===`draft`&&!e.has(t.definitionId)).length,needsAttention:T.length,ready:x.filter(t=>t.lifecycleState===`active`&&!e.has(t.definitionId)).length}},[x,T]),Te=G&&K?.canManage&&K.eligibleRuntimes.length>1?(0,Q.jsxs)(`details`,{className:`settings-card agent-execution-profile-card`,children:[(0,Q.jsx)(`summary`,{children:`Advanced execution profile`}),(0,Q.jsxs)(`p`,{children:[`Choose which authorized execution context sponsors @`,G.handle,`. Backend and model choices remain in Runtime settings.`]}),(0,Q.jsxs)(`label`,{children:[`Execution profile`,(0,Q.jsx)(`select`,{value:U,disabled:ie,onChange:e=>ne(e.target.value),children:K.eligibleRuntimes.map(e=>(0,Q.jsx)(`option`,{value:e.runtimeProfileId,children:e.displayName},e.runtimeProfileId))})]}),K.lifecycleState===`enabled`&&U!==K.runtimeProfileId&&(0,Q.jsx)(`div`,{className:`settings-actions`,children:(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:ie||!U,onClick:()=>void Se(),children:ie?`Updating…`:`Change execution profile`})})]}):null;return(0,Q.jsxs)(`main`,{className:`agent-workspace`,"aria-label":`Agents workspace`,children:[(0,Q.jsxs)(`header`,{className:`agent-workspace-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`p`,{className:`breadcrumbs`,children:[y,` / Agents`]}),(0,Q.jsxs)(`div`,{className:`agent-workspace-title`,children:[(0,Q.jsx)(`h1`,{children:`Agents`}),(0,Q.jsxs)(`p`,{children:[we.ready,` ready · `,we.drafts,` drafts · `,we.needsAttention,` need attention · `,m]})]})]}),(0,Q.jsxs)(`div`,{className:`agent-header-actions`,children:[(0,Q.jsx)(`span`,{className:`agent-live-state ${h.connection.tone}`,role:`status`,children:h.connection.label}),(0,Q.jsxs)(`div`,{className:`agent-header-controls`,children:[(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Create agent`,title:`Create agent`,disabled:ie,onClick:()=>{M(!0),te(!1),l()},children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`+`})}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close agents`,title:`Close agents`,onClick:c,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]})]})]}),(0,Q.jsx)(`div`,{className:`agent-workspace-body`,children:(0,Q.jsxs)(`section`,{className:`agent-detail`,"aria-live":`polite`,children:[G?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`agent-detail-identity`,children:[(0,Q.jsx)(`span`,{className:`agent-detail-avatar`,"aria-hidden":`true`,children:G.presentation.avatar||G.displayName.slice(0,1).toUpperCase()}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`agent-detail-title-row`,children:[(0,Q.jsx)(`h2`,{children:G.displayName}),(0,Q.jsx)(`span`,{className:`agent-status ${G.lifecycleState}`,children:Ig(G.lifecycleState)}),G.lifecycleState===`active`&&K&&(K.lifecycleState===`enabled`&&K.directChannelId||!K.canManage&&K.lifecycleState!==`enabled`&&K.ownerRuntimeProfileId&&K.eligibleRuntimes.length>0)&&(0,Q.jsx)(`button`,{className:`panel-icon-button agent-conversation-button`,type:`button`,"aria-label":`${K.conversationStarted?`Open`:`Start`} conversation with ${G.displayName}`,title:`${K.conversationStarted?`Open`:`Start`} conversation with ${G.displayName}`,disabled:ie,onClick:()=>void Ce(),children:(0,Q.jsx)(Lg,{})})]}),(0,Q.jsxs)(`p`,{className:`agent-handle`,children:[`@`,G.handle]}),(0,Q.jsx)(`p`,{children:G.description||`No description has been provided.`})]})]}),ee===G.definitionId&&(0,Q.jsxs)(`section`,{className:`agent-ready-summary`,role:`status`,children:[(0,Q.jsx)(`strong`,{children:`Agent ready`}),(0,Q.jsx)(`p`,{children:`Revision 1 and the selected runtime settings are active. Start a conversation with the speech-bubble action when you are ready; no conversation was created automatically.`})]}),(0,Q.jsxs)(`section`,{className:`agent-authority-note`,children:[(0,Q.jsx)(`strong`,{children:fe?`You own and manage this agent.`:`Owned and managed by ${G.ownerDisplayName??`another Workshop member`}.`}),(0,Q.jsxs)(`p`,{children:[`Everyone talks to the same @`,G.handle,` definition and owner-sponsored runtime. Conversations, transcripts, and memory remain private to each person.`]})]}),G.lifecycleState===`active`&&K&&!K.canManage&&K.lifecycleState!==`enabled`&&(!K.ownerRuntimeProfileId||K.eligibleRuntimes.length===0)&&(0,Q.jsx)(`section`,{className:`agent-enablement-card`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Conversation unavailable`}),(0,Q.jsx)(`h3`,{children:K.ownerRuntimeProfileId?`Unavailable to this Workshop account`:`Waiting for the agent owner’s runtime`})]})}),G.lifecycleState===`active`&&K?.canManage&&K.lifecycleState!==`enabled`&&(0,Q.jsx)(`section`,{className:`agent-runtime-controls agent-runtime-setup`,"aria-label":`${G.displayName} runtime settings`,id:`agent-runtime-settings`,children:(0,Q.jsxs)(`section`,{className:`settings-section`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{children:`Runtime settings`}),(0,Q.jsx)(`p`,{children:`Enable this agent on one of your authorized execution profiles before choosing its backend, model, and workspace.`})]}),(0,Q.jsxs)(`div`,{className:`settings-card-stack`,children:[(0,Q.jsxs)(`article`,{className:`settings-card agent-runtime-setup-card`,children:[(0,Q.jsx)(`p`,{className:`settings-card-label`,children:`Enable agent`}),K.eligibleRuntimes.length===0?(0,Q.jsx)(`p`,{children:`No authorized execution profile can satisfy this agent yet.`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{children:K.eligibleRuntimes.length===1?`Your authorized execution profile will be used automatically.`:`An eligible execution profile is selected. Use Advanced execution profile to choose another.`}),(0,Q.jsx)(`div`,{className:`settings-actions`,children:(0,Q.jsx)(`button`,{className:`primary-button`,type:`button`,disabled:ie||!U,onClick:()=>void Se(),children:ie?`Enabling…`:`Enable agent`})})]})]}),Te]})]})}),pe&&G&&fe&&(0,Q.jsx)(gg,{executionProfileControl:Te,isAdministrator:a,onAuthenticationFailure:o,onChannelAccessFailure:s,principalName:m,roleLabel:a?`Workshop administrator`:`Workshop member`,runtimeLabel:G.displayName,runActive:e===pe.channelId&&g,session:pe}),q?(0,Q.jsxs)(`section`,{className:`agent-active-revision`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Active definition`}),(0,Q.jsxs)(`h3`,{children:[`Revision `,q.revisionNumber]}),(0,Q.jsx)(`p`,{children:q.purpose}),(0,Q.jsx)(`div`,{className:`agent-capability-tags`,children:q.capabilities.map(e=>(0,Q.jsx)(`span`,{children:e.replaceAll(`_`,` `)},e))}),q.collaborationOperations.length>0&&(0,Q.jsx)(`div`,{className:`agent-capability-tags agent-collaboration-tags`,children:q.collaborationOperations.map(e=>(0,Q.jsx)(`span`,{children:e.replaceAll(`_`,` `)},e))})]}):(0,Q.jsx)(`p`,{className:`agent-state-copy`,children:`This draft is not active and cannot be enabled or run.`}),D&&(0,Q.jsx)(Hg,{busy:ie,policy:D,onRevoke:ye,onSave:ve}),fe&&G.lifecycleState!==`archived`&&(0,Q.jsxs)(`section`,{className:`agent-admin-controls`,children:[(0,Q.jsxs)(`div`,{className:`agent-section-heading`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Owner controls`}),(0,Q.jsx)(`h3`,{children:`Definition revisions`})]}),!H&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:ie,onClick:()=>te(!0),children:`New revision`})]}),H?(0,Q.jsx)(Vg,{agent:G,busy:ie,onCancel:()=>te(!1),onSave:_e}):(0,Q.jsx)(`ol`,{className:`agent-revision-list`,children:[...G.revisions].reverse().map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`strong`,{children:[`Revision `,e.revisionNumber]}),(0,Q.jsx)(`small`,{children:Rg(e.createdAt)})]}),(0,Q.jsx)(`p`,{children:e.purpose}),e.revisionId===G.activeRevisionId?(0,Q.jsx)(`span`,{className:`agent-status active`,children:`active`}):(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:ie,onClick:()=>void be(e.revisionId),children:`Activate`})]},e.revisionId))}),(0,Q.jsxs)(`div`,{className:`agent-archive-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`Archive definition`}),(0,Q.jsx)(`p`,{children:`Preserves messages and provenance while preventing future runs.`})]}),(0,Q.jsx)(`button`,{className:`danger-button`,type:`button`,disabled:ie,onClick:()=>void xe(),children:`Archive`})]})]}),G.lifecycleState===`archived`&&(0,Q.jsx)(`p`,{className:`agent-archived-note`,children:`This definition is archived. Historical conversations and revision provenance remain available, but it cannot be enabled or run.`})]}):re?(0,Q.jsx)(`p`,{className:`agent-state-copy`,children:`Loading agent details…`}):(0,Q.jsxs)(`div`,{className:`agent-empty-detail`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`@`}),(0,Q.jsx)(`h2`,{children:`No agent selected`}),(0,Q.jsx)(`p`,{children:`Choose an active agent from the sidebar or open the agent archive.`})]}),oe&&(0,Q.jsx)(`p`,{className:`agent-workspace-error`,role:`alert`,children:oe})]})}),j&&(Y||de||J)&&(0,Q.jsx)(Ng,{busy:ie,existingHandles:x.map(e=>e.handle),options:N,optionsError:F,optionsLoading:L,resumeDraft:J,resumeInput:de?.input??null,resumeProvisioning:de?.provisioning??null,onCancel:()=>{M(!1),f(k)},onCreateReady:ge,onSaveDraft:X},de?.provisioning.operationId??J?.definitionId??`new`)]})}function Wg({actions:e,connection:t,symbol:n,title:r,workshopName:i}){return(0,Q.jsxs)(`header`,{className:`conversation-header activity-workspace-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`p`,{className:`breadcrumbs`,children:[i,` / Activity`]}),(0,Q.jsxs)(`h2`,{children:[(0,Q.jsx)(`span`,{className:`activity-heading-symbol`,"aria-hidden":`true`,children:n}),r]})]}),(0,Q.jsxs)(`div`,{className:`conversation-actions`,children:[e,(0,Q.jsxs)(`span`,{className:`connection-indicator ${t.tone}`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`connection-dot`,"aria-hidden":`true`}),t.label]})]})]})}var Gg={active:!1,stateVersion:0,url:null};function Kg(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}function qg({connection:e,inbox:t,onOpen:n,workshopName:r}){let[i,a]=(0,v.useState)(null);return(0,Q.jsxs)(`section`,{className:`mentions-workspace`,"aria-label":`Mentions`,children:[(0,Q.jsx)(Wg,{actions:t.counts.unread>0?(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:t.pending,onClick:()=>void t.markAllRead(),children:t.counts.unread>100?`Mark next 100 read`:`Mark all read`}):null,connection:e,symbol:`@`,title:`Mentions`,workshopName:r}),(0,Q.jsxs)(`div`,{className:`mentions-summary`,"aria-live":`polite`,children:[(0,Q.jsx)(`strong`,{children:t.counts.unread}),(0,Q.jsx)(`span`,{children:t.counts.unread===1?`unread mention`:`unread mentions`})]}),(0,Q.jsxs)(`div`,{className:`mentions-notices`,children:[t.error&&(0,Q.jsx)(`p`,{className:`mentions-error`,role:`alert`,children:t.error}),i&&(0,Q.jsx)(`p`,{className:`mentions-error`,role:`alert`,children:i})]}),t.loading?(0,Q.jsx)(`p`,{className:`mentions-empty`,children:`Loading mentions…`}):t.notifications.length===0?(0,Q.jsxs)(`div`,{className:`mentions-empty`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`@`}),(0,Q.jsx)(`p`,{children:`No mentions yet.`})]}):(0,Q.jsx)(`ol`,{className:`mentions-list`,children:t.notifications.map(e=>(0,Q.jsxs)(`li`,{className:e.read?`read`:`unread`,children:[(0,Q.jsxs)(`button`,{className:`mention-source-link`,type:`button`,onClick:()=>{if(a(null),!n(e)){a(`You no longer have access to that mention's source channel.`);return}},children:[(0,Q.jsx)(Kh,{avatar:e.sourceAuthorAvatar??Gg,className:`mention-avatar`,displayName:e.sourceAuthorDisplayName,principalId:e.sourceAuthorPrincipalId}),(0,Q.jsxs)(`span`,{className:`mention-copy`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.sourceAuthorDisplayName}),` mentioned you in `,(0,Q.jsx)(`b`,{children:e.channelName??`a channel`})]}),(0,Q.jsxs)(`small`,{children:[e.sourceThreadRootId?`Thread reply`:`Channel message`,` · `,Kg(e.createdAt)]})]})]}),(0,Q.jsx)(`button`,{className:`mention-state-button`,type:`button`,disabled:t.pending,"aria-label":e.read?`Mark mention unread`:`Mark mention read`,title:e.read?`Mark unread`:`Mark read`,onClick:()=>void t.setRead(e,!e.read),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:e.read?`○`:`●`})})]},e.notificationId))}),t.hasMore&&(0,Q.jsx)(`button`,{className:`mentions-load-more`,type:`button`,disabled:t.loadingMore,onClick:t.loadMore,children:t.loadingMore?`Loading…`:`Load older mentions`})]})}function Jg(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}function Yg({followed:e=!1}){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:e?`currentColor`:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9M10 21h4`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.8`})})}function Xg({connection:e,following:t,onOpen:n,workshopName:r}){let[i,a]=(0,v.useState)(null);return(0,Q.jsxs)(`section`,{className:`following-workspace`,"aria-label":`Following`,children:[(0,Q.jsx)(Wg,{connection:e,symbol:(0,Q.jsx)(Yg,{}),title:`Following`,workshopName:r}),(0,Q.jsxs)(`div`,{className:`following-summary`,"aria-live":`polite`,children:[(0,Q.jsx)(`strong`,{children:t.threads.length}),(0,Q.jsx)(`span`,{children:t.threads.length===1?`followed thread`:`followed threads`}),t.totalUnread>0&&(0,Q.jsxs)(`span`,{children:[`· `,t.totalUnread,t.totalUnread>=1e3?`+`:``,` unread`]})]}),(0,Q.jsxs)(`div`,{className:`following-notices`,children:[t.error&&(0,Q.jsx)(`p`,{className:`following-error`,role:`alert`,children:t.error}),i&&(0,Q.jsx)(`p`,{className:`following-error`,role:`alert`,children:i})]}),t.loading?(0,Q.jsx)(`p`,{className:`following-empty`,children:`Loading followed threads…`}):t.threads.length===0?(0,Q.jsxs)(`div`,{className:`following-empty`,children:[(0,Q.jsx)(Yg,{}),(0,Q.jsx)(`p`,{children:`No followed threads.`})]}):(0,Q.jsx)(`ol`,{className:`following-list`,children:t.threads.map(e=>{let r=e.state.threadRootId,i=e.state.unreadCount;return(0,Q.jsxs)(`li`,{className:i>0?`unread`:`read`,children:[(0,Q.jsxs)(`button`,{className:`following-source-link`,type:`button`,onClick:()=>{a(null),n(e)||a(`You no longer have access to that thread's channel.`)},children:[(0,Q.jsxs)(`span`,{className:`following-channel`,children:[`# `,e.channelName??`Channel`,e.channelArchived&&(0,Q.jsx)(`small`,{children:`Archived`})]}),(0,Q.jsxs)(`span`,{className:`following-root`,children:[(0,Q.jsx)(`strong`,{children:e.rootAuthorDisplayName}),(0,Q.jsx)(`span`,{children:e.rootExcerpt||`Attachment or empty message`})]}),(0,Q.jsx)(`small`,{className:`following-latest`,children:e.latestReplyCreatedAt&&e.latestReplyAuthorDisplayName?`Latest reply by ${e.latestReplyAuthorDisplayName} · ${Jg(e.latestReplyCreatedAt)}`:`Started ${Jg(e.rootCreatedAt)}`}),i>0&&(0,Q.jsxs)(`span`,{className:`following-unread`,children:[i,e.state.unreadCountCapped?`+`:``,` unread`]})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button following-unfollow-button followed`,type:`button`,"aria-label":`Unfollow thread by ${e.rootAuthorDisplayName}`,"aria-pressed":`true`,title:`Unfollow thread`,disabled:t.pendingThreadIds.has(r),onClick:()=>void t.unfollow(e),children:(0,Q.jsx)(Yg,{followed:!0})})]},r)})})]})}function Zg(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`circle`,{cx:`6`,cy:`5`,r:`2`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`19`,r:`2`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`circle`,{cx:`18`,cy:`5`,r:`2`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M6 7v10M18 7v3a5 5 0 0 1-5 5H9`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`})]})}function Qg(e){return{pending:`Queued`,executing:`Running`,succeeded:`Completed`,failed:`Failed`,cancelled:`Cancelled`,timed_out:`Timed out`}[e]}function $g(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function e_(){return globalThis.crypto?.randomUUID?`workshop-review:${globalThis.crypto.randomUUID()}`:`workshop-review:${Date.now()}-${Math.random().toString(16).slice(2)}`}function t_({connection:e,onAuthenticationFailure:t,onChannelAccessFailure:n,onReviewPullRequest:r,revision:i,session:a,workshopName:o}){let s=Km(),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(!0),[f,p]=(0,v.useState)(null),[m,h]=(0,v.useState)(null),g=(0,v.useCallback)((e,r)=>{if(e instanceof B){t(e.message);return}if(e instanceof V){n(e.message);return}h(e instanceof Error?e.message:r)},[t,n]),_=(0,v.useCallback)(async(e=!0)=>{e&&d(!0),h(null);try{l(await $n(a))}catch(e){g(e,`Could not load pull-request reviews.`)}finally{e&&d(!1)}},[g,a]);(0,v.useEffect)(()=>{_()},[_]),(0,v.useEffect)(()=>{i>0&&_(!1)},[_,i]),(0,v.useEffect)(()=>{if(!c?.jobs.some(e=>e.status===`pending`||e.status===`executing`))return;let e=window.setTimeout(()=>void _(!1),2e3);return()=>window.clearTimeout(e)},[_,c]);let y=async(e,t)=>{if(!(t===`cancel`&&!await s(`Cancel the review of ${e.repository}#${e.pullRequestNumber}?`))){p(e.reviewJobId),h(null);try{await tr(a,e.reviewJobId,t,e_()),await _(!1)}catch(e){g(e,`Could not ${t} the pull-request review.`)}finally{p(null)}}},b=async e=>{let t=window.open(`about:blank`,`_blank`);if(!t){h(`The browser blocked the review artifact window.`);return}t.opener=null,p(e.reviewJobId),h(null);try{let n=URL.createObjectURL(await nr(a,e.reviewJobId));t.location.href=n,window.setTimeout(()=>URL.revokeObjectURL(n),6e4)}catch(e){t.close(),g(e,`Could not open the review artifact.`)}finally{p(null)}},x=c?.jobs.filter(e=>e.status===`pending`||e.status===`executing`).length??0;return(0,Q.jsxs)(`section`,{className:`reviews-workspace`,"aria-label":`Reviews`,children:[(0,Q.jsx)(Wg,{actions:(0,Q.jsx)(`button`,{"aria-label":`Review pull request`,className:`panel-icon-button reviews-launch-button`,title:`Review pull request`,type:`button`,onClick:r,children:(0,Q.jsx)(Zg,{})}),connection:e,symbol:(0,Q.jsx)(Zg,{}),title:`Reviews`,workshopName:o}),(0,Q.jsxs)(`div`,{className:`reviews-summary`,"aria-live":`polite`,children:[(0,Q.jsx)(`strong`,{children:c?.jobs.length??0}),(0,Q.jsx)(`span`,{children:c?.jobs.length===1?`review`:`reviews`}),x>0&&(0,Q.jsxs)(`span`,{children:[`· `,x,` active`]})]}),m&&(0,Q.jsx)(`p`,{className:`reviews-error`,role:`alert`,children:m}),u?(0,Q.jsx)(`p`,{className:`reviews-empty`,children:`Loading reviews…`}):!c||c.jobs.length===0?(0,Q.jsxs)(`div`,{className:`reviews-empty`,children:[(0,Q.jsx)(Zg,{}),(0,Q.jsx)(`p`,{children:`No on-demand reviews yet.`})]}):(0,Q.jsx)(`ol`,{className:`review-list`,children:c.jobs.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`div`,{className:`review-copy`,children:[(0,Q.jsxs)(`strong`,{children:[e.repository,`#`,e.pullRequestNumber]}),(0,Q.jsxs)(`small`,{children:[Qg(e.status),` · `,$g(e.updatedAt)]}),e.lastErrorCode&&(0,Q.jsxs)(`small`,{children:[`Error: `,e.lastErrorCode.replaceAll(`_`,` `)]}),e.artifact&&e.artifact.warningCount>0&&(0,Q.jsxs)(`details`,{className:`review-warnings`,children:[(0,Q.jsxs)(`summary`,{className:`review-warning`,children:[e.artifact.warningCount,` collection warning`,e.artifact.warningCount===1?``:`s`]}),(0,Q.jsx)(`ul`,{children:e.artifact.warnings.map((e,t)=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`strong`,{children:e.source.replaceAll(`_`,` `)}),`: `,e.message]},`${e.source}-${t}`))})]})]}),(0,Q.jsxs)(`div`,{className:`review-actions`,children:[e.artifact&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:f===e.reviewJobId,onClick:()=>void b(e),children:`Open`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:f===e.reviewJobId,onClick:()=>void rr(a,e).catch(e=>g(e,`Could not download the review artifact.`)),children:`Download`})]}),(e.status===`pending`||e.status===`executing`)&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:f===e.reviewJobId,onClick:()=>void y(e,`cancel`),children:`Cancel`}),(e.status===`failed`||e.status===`cancelled`||e.status===`timed_out`)&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,disabled:f===e.reviewJobId,onClick:()=>void y(e,`retry`),children:`Retry`})]})]},e.reviewJobId))})]})}var n_={read:0,total:0,unread:0,unreadByChannel:{}},r_={kind:`mention`};function i_(e){let t=new Uint8Array(8);return crypto.getRandomValues(t),`${e}-${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function a_(e,t){let n=e.filter(e=>e.notificationId!==t.notificationId);return n.push(t),n.sort((e,t)=>t.createdEventPosition-e.createdEventPosition)}function o_(e,t,n){let[r,i]=(0,v.useState)({counts:n_,error:null,hasMore:!1,loading:!0,loadingMore:!1,notifications:[],pending:!1}),a=(0,v.useRef)(null),o=(0,v.useRef)(!1),s=(0,v.useRef)(null),c=(0,v.useRef)(new Set),l=t.subscribe,u=(0,v.useCallback)(async t=>{let n=await Xr(e,r_,t);i(e=>({...e,counts:n}))},[e]),d=(0,v.useCallback)(async t=>{let n=await Yr(e,{...r_,limit:50},t);return a.current=n.nextCursor,i(e=>({...e,counts:n.counts,error:null,hasMore:n.nextCursor!==null,loading:!1,notifications:e.notifications.filter(e=>e.lastEventPosition>n.throughPosition).reduce(a_,n.notifications)})),n.throughPosition},[e]);(0,v.useEffect)(()=>{let e=new AbortController,t=()=>{s.current===null&&(s.current=window.setTimeout(()=>{s.current=null,u(e.signal).catch(e=>{e instanceof B&&n(e.message)})},100))},r=()=>{d(e.signal).catch(t=>{if(!e.signal.aborted){if(t instanceof B){n(t.message);return}i(e=>({...e,error:e.loading?t instanceof Error?t.message:`Could not load mentions.`:e.error,loading:!1}))}})},a=l(e=>{if(e.kind===`synchronize`){r();return}let n=!1;for(let t of e.batch.changes)for(let{notification:e}of t.notificationChanges)e.kind===`mention`&&(n=!0,i(t=>({...t,notifications:a_(t.notifications,e)})));n&&t()});return r(),()=>{a(),e.abort(),s.current!==null&&(window.clearTimeout(s.current),s.current=null)}},[n,u,d,l]);let f=(0,v.useCallback)(()=>{let t=a.current;!t||o.current||(o.current=!0,i(e=>({...e,loadingMore:!0})),Yr(e,{...r_,cursor:t,limit:50}).then(e=>{a.current=e.nextCursor,i(t=>{let n=new Set(t.notifications.map(e=>e.notificationId));return{...t,counts:e.counts,error:null,hasMore:e.nextCursor!==null,loadingMore:!1,notifications:[...t.notifications,...e.notifications.filter(e=>!n.has(e.notificationId))]}}),o.current=!1},e=>{if(o.current=!1,e instanceof B){n(e.message);return}i(t=>({...t,error:e instanceof Error?e.message:`Could not load more mentions.`,loadingMore:!1}))}))},[n,e]),p=(0,v.useCallback)(async(t,r)=>{i(e=>({...e,error:null,pending:!0}));try{let n=r?await Qr(e,t.notificationId,t.stateVersion,i_(`mention-read`)):await $r(e,t.notificationId,t.stateVersion,i_(`mention-unread`)),a=await Xr(e,r_);i(e=>({...e,counts:a,notifications:a_(e.notifications,n.notification),pending:!1}))}catch(e){if(e instanceof B){n(e.message);return}i(t=>({...t,error:e instanceof Error?e.message:`Could not update this mention.`,pending:!1}))}},[n,e]),m=(0,v.useCallback)(async()=>{i(e=>({...e,error:null,pending:!0}));try{let t=await Yr(e,{...r_,limit:100,unreadOnly:!0});if(t.notifications.length>0){let n=await ei(e,t.notifications.map(e=>({expectedStateVersion:e.stateVersion,notificationId:e.notificationId})),i_(`mentions-read`));i(e=>({...e,notifications:n.reduce((e,t)=>a_(e,t.notification),e.notifications)}))}let n=await Xr(e,r_);i(e=>({...e,counts:n,pending:!1}))}catch(e){if(e instanceof B){n(e.message);return}i(t=>({...t,error:e instanceof Error?e.message:`Could not mark mentions read.`,pending:!1}))}},[n,e]),h=(0,v.useCallback)(async t=>{let a=r.notifications.filter(e=>!e.read&&e.sourceMessageId===t&&!c.current.has(e.notificationId));if(a.length!==0){for(let e of a)c.current.add(e.notificationId);try{let t=await Promise.all(a.map(t=>Qr(e,t.notificationId,t.stateVersion,i_(`mention-viewed`)))),n=await Xr(e,r_);i(e=>({...e,counts:n,notifications:t.reduce((e,t)=>a_(e,t.notification),e.notifications)}))}catch(e){if(e instanceof B){n(e.message);return}i(t=>({...t,error:e instanceof Error?e.message:`Could not mark the displayed mention read.`}))}finally{for(let e of a)c.current.delete(e.notificationId)}}},[n,r.notifications,e]);return{...r,loadMore:f,markAllRead:m,markVisibleRead:h,setRead:p}}function s_(){let e=new Uint8Array(8);return crypto.getRandomValues(e),`following-unfollow-${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function c_(e,t,n){let[r,i]=(0,v.useState)({error:null,loading:!0,pendingThreadIds:new Set,threads:[],totalUnread:0}),a=(0,v.useRef)(null),o=t.subscribe,s=(0,v.useCallback)(async t=>{let n=await ii(e,t);i(e=>({...e,error:null,loading:!1,threads:n.threads,totalUnread:n.threads.reduce((e,t)=>Math.min(1e3,e+t.state.unreadCount),0)}))},[e]);(0,v.useEffect)(()=>{let e=new AbortController,t=()=>{s(e.signal).catch(t=>{if(!e.signal.aborted){if(t instanceof B){n(t.message);return}i(e=>({...e,error:t instanceof Error?t.message:`Could not load followed threads.`,loading:!1}))}})},r=()=>{a.current===null&&(a.current=window.setTimeout(()=>{a.current=null,t()},50))},c=o(e=>{if(e.kind===`synchronize`){t();return}e.batch.changes.some(e=>e.threadChanges.length>0||e.unreadChanges.length>0)&&r()});return t(),()=>{c(),e.abort(),a.current!==null&&(window.clearTimeout(a.current),a.current=null)}},[n,s,o]);let c=(0,v.useCallback)(async t=>{let r=t.state.threadRootId;i(e=>({...e,error:null,pendingThreadIds:new Set(e.pendingThreadIds).add(r)}));try{let n=await si({channelId:t.state.channelId,token:e},r,!1,t.state.stateVersion,s_());i(e=>{let t=new Set(e.pendingThreadIds);t.delete(r);let i=n.state.followed?e.threads:e.threads.filter(e=>e.state.threadRootId!==r);return{...e,pendingThreadIds:t,threads:i,totalUnread:i.reduce((e,t)=>Math.min(1e3,e+t.state.unreadCount),0)}})}catch(e){if(e instanceof B){n(e.message);return}if(e instanceof te||e instanceof V)try{await s()}catch{}i(t=>{let n=new Set(t.pendingThreadIds);return n.delete(r),{...t,error:e instanceof Error?e.message:`Could not unfollow this thread.`,pendingThreadIds:n}})}},[n,s,e]);return{...r,unfollow:c}}function l_(){let e=new Uint8Array(8);return crypto.getRandomValues(e),`channel-read-${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function u_(e){return Object.fromEntries(e.map(e=>[e.channelId,e]))}function d_(e){return Math.min((e?.unreadCount??0)+(e?.unreadReplyCount??0),1e3)}function f_(e,t,n,r){let[i,a]=(0,v.useState)({byChannel:{},error:null,loading:!0,totalUnread:0,totalUnreadCapped:!1}),o=(0,v.useRef)(i),s=(0,v.useRef)(new Map),c=(0,v.useRef)(new Set),l=t.subscribe;o.current=i;let u=(0,v.useCallback)(async t=>{let n=await li(e,t),r={byChannel:u_(n.channels),error:null,loading:!1,totalUnread:n.totalUnread,totalUnreadCapped:n.totalUnreadCapped};return o.current=r,a(r),n.throughPosition},[e]);(0,v.useEffect)(()=>{let e=new AbortController,t=()=>{u(e.signal).catch(t=>{if(!e.signal.aborted){if(t instanceof B){n(t.message);return}a(e=>({...e,error:e.loading?t instanceof Error?t.message:`Could not load unread messages.`:e.error,loading:!1}))}})},r=l(e=>{if(e.kind===`synchronize`){t();return}for(let t of e.batch.changes)for(let{state:e}of t.unreadChanges)a(t=>{let n=t.byChannel[e.channelId],r=Math.min(1e3,Math.max(0,t.totalUnread-d_(n)+d_(e))),i={...t,byChannel:{...t.byChannel,[e.channelId]:e},totalUnread:r};return o.current=i,i})});return t(),()=>{r(),e.abort()}},[n,u,l]);let d=(0,v.useCallback)((e,t)=>{let i=o.current.byChannel[e.channelId];if(!i||t.channelId!==e.channelId||t.threadRootId!==null||t.eventPosition<=i.readThroughEventPosition)return;let l=s.current.get(e.channelId);(!l||l.eventPosition{try{for(;s.current.has(e.channelId);){let t=s.current.get(e.channelId);if(s.current.delete(e.channelId),!t)continue;let i=o.current.byChannel[e.channelId];if(!(!i||t.eventPosition<=i.readThroughEventPosition))try{let n=await ui(e,t.messageId,i.stateVersion,l_());a(t=>{let r=t.byChannel[e.channelId],i={...t,byChannel:{...t.byChannel,[e.channelId]:n.state},totalUnread:Math.min(1e3,Math.max(0,t.totalUnread-d_(r)+d_(n.state)))};return o.current=i,i})}catch(c){if(c instanceof B){n(c.message);return}if(c instanceof V){r(c.message);return}if(c instanceof H){await u(),i=o.current.byChannel[e.channelId],i&&t.eventPosition>i.readThroughEventPosition&&s.current.set(e.channelId,t);continue}a(e=>({...e,error:c instanceof Error?c.message:`Could not update unread messages.`}))}}}finally{c.current.delete(e.channelId)}})())},[n,r,u]);return{...i,advanceVisible:d}}var p_=2e3;function m_(e){return new Promise(t=>{let n=window.setTimeout(t,p_);e.addEventListener(`abort`,()=>{window.clearTimeout(n),t()},{once:!0})})}function h_(e,t){let[n,r]=(0,v.useState)({label:`Connecting`,tone:`connecting`}),i=(0,v.useRef)(!1),a=(0,v.useRef)(new Set),o=(0,v.useRef)(t);o.current=t;let s=(0,v.useCallback)(e=>{for(let t of a.current)t(e)},[]),c=(0,v.useCallback)(e=>(a.current.add(e),i.current&&e({kind:`synchronize`}),()=>a.current.delete(e)),[]);return(0,v.useEffect)(()=>{let t=new AbortController,n=null,a=!0;return(async()=>{for(;!t.signal.aborted;){try{i.current=!1,r({label:`Connecting`,tone:`connecting`}),await bi(e,n,{onBatch:(e,t)=>{n=t,a&&(a=!1,i.current=!0,s({kind:`synchronize`})),s({batch:e,kind:`batch`})},onConnected:()=>{r({label:`Live`,tone:`connected`})}},t.signal)}catch(e){if(t.signal.aborted)return;if(i.current=!1,r({label:`Connecting`,tone:`connecting`}),e instanceof B){o.current(e.message);return}e instanceof U&&(n=null,a=!0)}await m_(t.signal)}})(),()=>{i.current=!1,t.abort()}},[s,e]),(0,v.useMemo)(()=>({connection:n,subscribe:c}),[n,c])}function g_({actions:e,error:t,loading:n,onClose:r,onInvoke:i}){let a=(0,v.useRef)(null),o=(0,v.useRef)(null),[s,c]=(0,v.useState)(``),[l,u]=(0,v.useState)(0),[d,f]=(0,v.useState)(null),[p,m]=(0,v.useState)(null),[h,g]=(0,v.useState)(null),_=(0,v.useMemo)(()=>{let t=s.trim().toLocaleLowerCase();return t?e.filter(({capability:e,targetLabel:n})=>[e.label,e.description,n??``].join(` `).toLocaleLowerCase().includes(t)):e},[e,s]);(0,v.useLayoutEffect)(()=>(o.current=document.activeElement instanceof HTMLElement?document.activeElement:null,a.current?.focus(),()=>o.current?.focus()),[]),(0,v.useEffect)(()=>{u(e=>Math.min(e,Math.max(_.length-1,0)))},[_.length]);let y=async e=>{if(d===null){f(e.key),g(null),m(null);try{let t=await i(e);t===null?r():m(t)}catch(e){g(e instanceof Error?e.message:`Could not complete this action.`)}finally{f(null)}}};return(0,Q.jsx)(`div`,{className:`action-palette-backdrop`,onMouseDown:r,children:(0,Q.jsxs)(`section`,{"aria-label":`Help and actions`,"aria-modal":`true`,className:`action-palette`,onMouseDown:e=>e.stopPropagation(),role:`dialog`,children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Kai Workshop`}),(0,Q.jsx)(`h2`,{children:`Help and actions`})]}),(0,Q.jsx)(`button`,{"aria-label":`Close help and actions`,className:`panel-icon-button`,onClick:r,title:`Close`,type:`button`,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsxs)(`label`,{className:`action-palette-search`,children:[(0,Q.jsx)(`span`,{className:`visually-hidden`,children:`Search actions`}),(0,Q.jsx)(`input`,{"aria-activedescendant":_[l]?`action-${_[l].key}`:void 0,"aria-controls":`action-palette-results`,"aria-expanded":`true`,"aria-label":`Search actions`,autoComplete:`off`,onChange:e=>{c(e.target.value),u(0),m(null)},onKeyDown:e=>{if(e.key===`Escape`){e.preventDefault(),r();return}if(e.key===`ArrowDown`||e.key===`ArrowUp`){if(e.preventDefault(),_.length===0)return;let t=e.key===`ArrowDown`?1:-1;u(e=>(e+t+_.length)%_.length);return}e.key===`Enter`&&_[l]&&(e.preventDefault(),y(_[l]))},placeholder:`Search actions and destinations…`,ref:a,role:`combobox`,value:s}),(0,Q.jsx)(`kbd`,{children:`Esc`})]}),(0,Q.jsx)(`div`,{className:`action-palette-results`,id:`action-palette-results`,role:`listbox`,children:n?(0,Q.jsx)(`p`,{role:`status`,children:`Loading available actions…`}):t?(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:t}):_.length===0?(0,Q.jsxs)(`p`,{children:[`No available actions match “`,s,`”.`]}):_.map((e,t)=>(0,Q.jsxs)(`button`,{"aria-selected":l===t,className:l===t?`selected`:``,disabled:d!==null,id:`action-${e.key}`,onClick:()=>void y(e),onMouseMove:()=>u(t),role:`option`,type:`button`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.capability.label}),(0,Q.jsx)(`small`,{children:e.capability.description})]}),e.targetLabel&&(0,Q.jsx)(`em`,{children:e.targetLabel})]},e.key))}),(p||h)&&(0,Q.jsx)(`p`,{className:h?`settings-error action-palette-feedback`:`action-palette-feedback`,role:h?`alert`:`status`,children:h??p}),(0,Q.jsxs)(`footer`,{children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`kbd`,{children:`↑`}),(0,Q.jsx)(`kbd`,{children:`↓`}),` navigate`]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`kbd`,{children:`Enter`}),` open`]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`kbd`,{children:`Esc`}),` close`]})]})]})})}var __=`kai.workshop.client-credential.v1`,v_=`kai.workshop.active-channel.v1`,y_=`kai.workshop.read-session.v1`,b_=`kai.workshop.active-runs.v2`,x_=`kai.workshop.active-run.v1`,S_=`kai.workshop.drafts.v1`,C_=`kai.workshop.timeline-viewports.v1`,w_=`kai.workshop.sidebar-layout.v4`,T_=`kai.workshop.context-sections.v1`,E_=96,D_=1.5,O_=176*D_,k_=O_,A_=420*D_,j_=56*D_,M_=/^[A-Za-z0-9_-]{1,256}$/,N_={active:!1,stateVersion:0,url:null};function P_(e,t){let n=new Map,r=new Set;for(let e of[...t].reverse())r.add(e.authorPrincipalId),n.has(e.authorPrincipalId)||n.set(e.authorPrincipalId,{avatar:e.authorKind===`human`?e.authorAvatar??N_:null,displayName:e.authorDisplayName,kind:e.authorKind===`human`?`human`:`agent`,principalId:e.authorPrincipalId});for(let t of e.replyParticipants)n.has(t.principalId)||n.set(t.principalId,t);let i=new Set(e.replyParticipants.map(e=>e.principalId)),a=e.replyParticipantCount===e.replyParticipants.length?[...r].filter(e=>!i.has(e)).length:0,o=[...n.values()].slice(0,3);return{replyParticipantCount:Math.max(e.replyParticipantCount+a,o.length),replyParticipants:o}}function F_(){let e=new URLSearchParams(window.location.search);if(e.get(`view`)===`workspaces`)return{kind:`workspaces`};if(e.get(`view`)===`scheduled-jobs`)return{kind:`scheduled-jobs`};if(e.get(`view`)===`mentions`)return{kind:`mentions`};if(e.get(`view`)===`following`)return{kind:`following`};if(e.get(`view`)===`reviews`)return{kind:`reviews`};if(e.get(`view`)===`settings`){let t=e.get(`runtime`),n=e.get(`agent`);return n&&S.test(n)?{creating:!1,definitionId:n,kind:`agents`,section:`runtime`,setupId:null}:{kind:`settings`,runtimeChannelId:t&&b.test(t)?t:null,section:e.get(`section`)===`administration`?`administration`:e.get(`section`)===`github`?`github`:null}}if(e.get(`view`)===`agents`){let t=e.get(`agent`);return{creating:e.get(`new`)===`1`,kind:`agents`,definitionId:t&&S.test(t)?t:null,section:e.get(`section`)===`runtime`?`runtime`:null,setupId:e.get(`setup`)&&C.test(e.get(`setup`))?e.get(`setup`):null}}if(e.get(`view`)!==`memory`){let t=e.get(`message`),n=e.get(`thread`);return{kind:`conversation`,...t&&A.test(t)?{messageId:t}:{},...n&&A.test(n)?{threadRootId:n}:{}}}let t=e.get(`memory`);return{kind:`memory`,memoryId:t&&M_.test(t)?t:null}}function I_(e,t){let n=new URL(window.location.href);n.searchParams.delete(`view`),n.searchParams.delete(`memory`),n.searchParams.delete(`agent`),n.searchParams.delete(`runtime`),n.searchParams.delete(`new`),n.searchParams.delete(`section`),n.searchParams.delete(`setup`),n.searchParams.delete(`message`),n.searchParams.delete(`thread`),e.kind===`memory`?(n.searchParams.set(`view`,`memory`),e.memoryId&&n.searchParams.set(`memory`,e.memoryId)):e.kind===`workspaces`?n.searchParams.set(`view`,`workspaces`):e.kind===`scheduled-jobs`?n.searchParams.set(`view`,`scheduled-jobs`):e.kind===`settings`?(n.searchParams.set(`view`,`settings`),e.runtimeChannelId&&n.searchParams.set(`runtime`,e.runtimeChannelId),e.section&&n.searchParams.set(`section`,e.section)):e.kind===`agents`?(n.searchParams.set(`view`,`agents`),e.definitionId&&n.searchParams.set(`agent`,e.definitionId),e.creating&&n.searchParams.set(`new`,`1`),e.section&&n.searchParams.set(`section`,e.section),e.setupId&&n.searchParams.set(`setup`,e.setupId)):e.kind===`mentions`?n.searchParams.set(`view`,`mentions`):e.kind===`following`?n.searchParams.set(`view`,`following`):e.kind===`reviews`?n.searchParams.set(`view`,`reviews`):e.kind===`conversation`&&(e.messageId&&n.searchParams.set(`message`,e.messageId),e.threadRootId&&n.searchParams.set(`thread`,e.threadRootId)),window.history[t===`push`?`pushState`:`replaceState`](null,``,`${n.pathname}${n.search}${n.hash}`)}function L_(e){return Math.min(A_,Math.max(O_,e))}function R_(){try{let e=JSON.parse(sessionStorage.getItem(w_)??`null`);if(typeof e==`object`&&e&&`collapsed`in e&&`width`in e&&typeof e.collapsed==`boolean`&&typeof e.width==`number`&&Number.isFinite(e.width))return{collapsed:e.collapsed,width:L_(e.width)}}catch{}return{collapsed:!1,width:k_}}function z_(e){sessionStorage.setItem(w_,JSON.stringify(e))}var B_=`kai.workshop.context-layout.v4`,V_=240*D_,H_=V_,U_=560*D_;function W_(e){return Math.min(U_,Math.max(V_,e))}function G_(){try{let e=JSON.parse(sessionStorage.getItem(B_)??`null`);if(typeof e==`object`&&e&&`width`in e&&typeof e.width==`number`&&Number.isFinite(e.width))return W_(e.width)}catch{}return H_}function K_(e){sessionStorage.setItem(B_,JSON.stringify({width:e}))}function q_(e){try{let t=JSON.parse(e??`null`);if(typeof t==`object`&&t&&`token`in t&&`channelId`in t&&typeof t.token==`string`&&t.token.length>0&&typeof t.channelId==`string`&&b.test(t.channelId))return{channelId:t.channelId,token:t.token}}catch{}return null}function J_(e){try{let t=JSON.parse(e??`null`);if(typeof t==`object`&&t&&`token`in t&&typeof t.token==`string`&&t.token.length>0)return t.token}catch{}return null}function Y_(){try{let e=JSON.parse(sessionStorage.getItem(v_)??`null`);if(typeof e==`object`&&e&&`channelId`in e&&typeof e.channelId==`string`&&b.test(e.channelId))return e.channelId}catch{}return sessionStorage.removeItem(v_),null}function X_(){let e=J_(localStorage.getItem(__)),t=Y_(),n=q_(sessionStorage.getItem(y_));return!e&&n?(e=n.token,t??=n.channelId,localStorage.setItem(__,JSON.stringify({token:n.token}))):e&&n?.token===e&&(t??=n.channelId),localStorage.getItem(__)&&!e&&localStorage.removeItem(__),sessionStorage.removeItem(y_),e?{channelId:t,token:e}:null}function Z_(e){localStorage.setItem(__,JSON.stringify({token:e.token})),sessionStorage.setItem(v_,JSON.stringify({channelId:e.channelId})),sessionStorage.removeItem(y_)}function Q_(){sessionStorage.removeItem(v_),sessionStorage.removeItem(y_),sessionStorage.removeItem(b_),sessionStorage.removeItem(x_),sessionStorage.removeItem(S_),sessionStorage.removeItem(C_)}function $_(){localStorage.removeItem(__),Q_()}function ev(e){try{let t=JSON.parse(sessionStorage.getItem(b_)??`null`);if(typeof t==`object`&&t&&e in t&&Array.isArray(t[e]))return(t[e]??[]).filter(e=>typeof e==`string`&&e.startsWith(`run_`))}catch{}try{let t=JSON.parse(sessionStorage.getItem(x_)??`null`);if(typeof t==`object`&&t){let n=t[e];if(typeof n==`string`&&n.startsWith(`run_`))return[n]}}catch{}return[]}function tv(e,t){let n={};try{let e=JSON.parse(sessionStorage.getItem(b_)??`{}`);typeof e==`object`&&e&&!Array.isArray(e)&&(n=Object.fromEntries(Object.entries(e).flatMap(([e,t])=>{if(!Array.isArray(t))return[];let n=t.filter(e=>typeof e==`string`&&e.startsWith(`run_`));return n.length>0?[[e,n]]:[]})))}catch{}let r=[...new Set(t.filter(e=>e.startsWith(`run_`)))];r.length>0?n[e]=r:delete n[e],sessionStorage.setItem(b_,JSON.stringify(n)),sessionStorage.removeItem(x_)}function nv(e){try{let t=JSON.parse(sessionStorage.getItem(S_)??`{}`);if(typeof t==`object`&&t&&e in t){let n=t[e];return typeof n==`string`&&n.length<=5e4?n:``}}catch{}return``}function rv(e,t){let n={};try{let e=JSON.parse(sessionStorage.getItem(S_)??`{}`);typeof e==`object`&&e&&!Array.isArray(e)&&(n=Object.fromEntries(Object.entries(e).filter(e=>typeof e[1]==`string`&&e[1].length<=5e4)))}catch{}t?n[e]=t:delete n[e],sessionStorage.setItem(S_,JSON.stringify(n))}function iv(e){try{let t=JSON.parse(sessionStorage.getItem(C_)??`{}`),n=typeof t==`object`&&t?t[e]:null;if(typeof n==`object`&&n&&`follow`in n&&`scrollTop`in n&&typeof n.follow==`boolean`&&typeof n.scrollTop==`number`&&Number.isFinite(n.scrollTop)&&n.scrollTop>=0)return{follow:n.follow,scrollTop:n.scrollTop}}catch{}return null}function av(e,t){let n={};try{let e=JSON.parse(sessionStorage.getItem(C_)??`{}`);typeof e==`object`&&e&&!Array.isArray(e)&&(n=e)}catch{}n[e]=t,sessionStorage.setItem(C_,JSON.stringify(n))}function ov(e){return e?.status===`accepted`||e?.status===`started`}function sv(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=E_}function cv(e){let t=new Date(e);return Number.isNaN(t.valueOf())?``:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}function lv(e,t){let n=new Date(e.startedAt??e.acceptedAt).valueOf(),r=e.terminalAt?new Date(e.terminalAt).valueOf():t;if(!Number.isFinite(n)||!Number.isFinite(r))return`Duration unavailable`;let i=Math.max(0,Math.floor((r-n)/1e3));return i<60?`${i}s`:`${Math.floor(i/60)}m ${i%60}s`}function uv(e){return e.status===`accepted`?e.cancellationRequestedAt?`Stopping when the agent reaches a safe boundary.`:`Queued for the configured agent.`:e.status===`started`?e.cancellationRequestedAt?`Stopping when the agent reaches a safe boundary.`:`The agent is working on this request.`:e.status===`completed`?`The agent completed this request.`:e.status===`cancelled`?`This request was cancelled.`:e.terminalCode&&{authentication_expired:`Sign in to the configured backend again, then retry.`,authentication_required:`Sign in to the configured backend, then retry.`,backend_crashed:`The agent process stopped unexpectedly. Retry this request.`,execution_interrupted:`Kai was interrupted while the agent was working. Retry this request.`,model_unavailable:`The configured model is unavailable. Choose an available model, then retry.`,no_response:`The agent ended without a response. Retry this request.`,provider_unavailable:`The provider is temporarily unavailable. Try again later.`,quota_exhausted:`The configured account has no usage allowance remaining.`,transient:`The provider failed temporarily. Try this request again.`}[e.terminalCode]||`The agent could not complete this request. Retry it or ask the operator to inspect Kai.`}function dv({existingSession:e,notice:t,onForget:n,onOpen:r}){let[i,a]=(0,v.useState)(`Workshop browser`),[o,s]=(0,v.useState)(``),[c,l]=(0,v.useState)(t),[u,d]=(0,v.useState)(!1),f=async t=>{if(t.preventDefault(),l(null),!e&&(!i.trim()||!o.trim())){l(`Device name and enrollment token are required.`);return}d(!0);try{await r({deviceDisplayName:i.trim(),enrollmentToken:o.trim()})}catch(e){s(``),l(e instanceof Error?e.message:`Enrollment failed.`),d(!1)}};return(0,Q.jsxs)(`main`,{className:`enrollment-page`,children:[(0,Q.jsx)(`div`,{className:`enrollment-glow`,"aria-hidden":`true`}),(0,Q.jsxs)(`header`,{className:`enrollment-brand`,children:[(0,Q.jsx)(`span`,{className:`brand-mark`,children:`K`}),(0,Q.jsx)(`span`,{children:`Kai Workshop`}),(0,Q.jsx)(`span`,{className:`preview-badge`,children:`Workshop preview`})]}),(0,Q.jsxs)(`section`,{className:`enrollment-layout`,children:[(0,Q.jsxs)(`div`,{className:`enrollment-intro`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`A shared place for meaningful work`}),(0,Q.jsx)(`h1`,{children:`People and agents, working in the same room.`}),(0,Q.jsx)(`p`,{className:`lede`,children:`Open the canonical conversation already shared with Telegram. Your history and live updates come from Kai—not from this browser.`}),(0,Q.jsxs)(`ol`,{className:`threshold-steps`,"aria-label":`How Workshop connects`,children:[(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:`01`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`Enroll this device`}),(0,Q.jsx)(`p`,{children:`Use a short-lived grant issued by the Kai operator.`})]})]}),(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:`02`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`Join the channel`}),(0,Q.jsx)(`p`,{children:`Read one canonical history across every client.`})]})]}),(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:`03`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:`Stay in step`}),(0,Q.jsx)(`p`,{children:`New human and agent messages arrive live.`})]})]})]})]}),(0,Q.jsxs)(`div`,{className:`enrollment-card`,children:[(0,Q.jsxs)(`div`,{className:`card-heading`,children:[(0,Q.jsx)(`span`,{className:`section-number`,children:`01`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Secure client enrollment`}),(0,Q.jsx)(`h2`,{children:`Open a Workshop channel`})]})]}),e?(0,Q.jsx)(`p`,{className:`session-hint`,children:`Enrollment is complete for this browser profile. Retry Workshop discovery, or forget the session and enroll again.`}):(0,Q.jsx)(`p`,{className:`card-copy`,children:`The session credential remains in this browser profile for this Kai origin and is never written to the URL.`}),(0,Q.jsxs)(`form`,{onSubmit:e=>void f(e),noValidate:!0,children:[!e&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`label`,{htmlFor:`device-name`,children:`Device name`}),(0,Q.jsx)(`input`,{id:`device-name`,name:`device-name`,value:i,onChange:e=>a(e.target.value),maxLength:100,autoComplete:`off`,required:!0}),(0,Q.jsx)(`label`,{htmlFor:`enrollment-token`,children:`Enrollment token`}),(0,Q.jsx)(`input`,{id:`enrollment-token`,name:`enrollment-token`,type:`password`,value:o,onChange:e=>s(e.target.value),maxLength:512,placeholder:`kai_ws_enroll_v1.…`,autoComplete:`off`,spellCheck:!1,required:!0})]}),(0,Q.jsxs)(`div`,{className:`form-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:u,children:u?`Opening…`:`Open Workshop`}),e&&(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:n,children:`Forget session`})]}),c&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:c})]})]})]}),(0,Q.jsxs)(`footer`,{className:`enrollment-footer`,children:[(0,Q.jsx)(`span`,{children:`Server-authoritative collaboration`}),(0,Q.jsx)(`span`,{children:`·`}),(0,Q.jsx)(`span`,{children:`Telegram and Workshop in one history`})]})]})}function fv({connection:e}){return(0,Q.jsxs)(`span`,{className:`connection-indicator ${e.tone}`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`connection-dot`,"aria-hidden":`true`}),e.label]})}var pv=[{label:`Thumbs up`,reaction:`thumbs_up`,symbol:`👍`},{label:`Thumbs down`,reaction:`thumbs_down`,symbol:`👎`},{label:`Heart`,reaction:`heart`,symbol:`❤️`},{label:`Laugh`,reaction:`laugh`,symbol:`😄`},{label:`Celebrate`,reaction:`celebrate`,symbol:`🎉`},{label:`Eyes`,reaction:`eyes`,symbol:`👀`},{label:`Done`,reaction:`check`,symbol:`✅`},{label:`Thinking`,reaction:`thinking`,symbol:`🤔`},{label:`Surprised`,reaction:`surprised`,symbol:`😮`},{label:`Sad`,reaction:`sad`,symbol:`😢`},{label:`Fire`,reaction:`fire`,symbol:`🔥`},{label:`Question`,reaction:`question`,symbol:`❓`}];function mv({hasUnreadReplies:e=!1,highlighted:t=!1,message:n,notification:r=!1,onDownloadArtifact:i,onLoadArtifact:a,onMessageVisible:o,onOpenThread:s,onLoadReactors:c,onSetReaction:l}){let[u,d]=(0,v.useState)(!1),[f,p]=(0,v.useState)(null),[m,h]=(0,v.useState)(null),[g,_]=(0,v.useState)(null),[y,b]=(0,v.useState)({}),[x,S]=(0,v.useState)(null),[C,w]=(0,v.useState)(null),T=(0,v.useRef)(null),E=n.authorKind===`agent`,D=n.authorDisplayName||`Unknown author`,O=n.reactions??[],k=O.map(e=>`${e.reaction}:${e.count}:${e.reactedByViewer}`).join(`|`);(0,v.useEffect)(()=>{_(null),b({}),S(null),w(null)},[n.messageId,k]),(0,v.useEffect)(()=>{let e=T.current;if(!e||!o||!(`IntersectionObserver`in window))return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&o(n.messageId)},{root:e.closest(`.timeline-wrap`),rootMargin:`0px`,threshold:0});return t.observe(e),()=>t.disconnect()},[n.messageId,o]);let A=async(e,t)=>{if(!(!l||f!==null)){p(e),h(null);try{await l(n.messageId,e,t),d(!1)}catch(e){h(e instanceof Error?e.message:`Could not update this reaction.`)}finally{p(null)}}},j=e=>{_(e),!(!c||y[e]||x===e)&&(S(e),w(null),c(n.messageId,e).then(t=>{b(n=>({...n,[e]:t}))}).catch(()=>w(e)).finally(()=>S(t=>t===e?null:t)))};return r?(0,Q.jsxs)(`li`,{ref:T,className:`notification-row ${t?`focused-message`:``}`,"data-message-id":n.messageId,children:[(0,Q.jsx)(`span`,{className:`notification-source`,"aria-hidden":`true`,children:`GH`}),(0,Q.jsxs)(`article`,{children:[(0,Q.jsxs)(`header`,{className:`message-meta`,children:[(0,Q.jsx)(`strong`,{children:`GitHub`}),(0,Q.jsx)(`time`,{dateTime:n.createdAt,children:cv(n.createdAt)})]}),(0,Q.jsx)(Nm,{body:n.body,mentions:n.mentions}),n.artifacts.map(e=>(0,Q.jsx)(gv,{artifact:e,onDownload:i,onLoad:a},e.artifactId))]})]}):(0,Q.jsxs)(`li`,{ref:T,className:`message-row ${E?`agent`:`human`} ${t?`focused-message`:``}`,"data-message-id":n.messageId,children:[E?(0,Q.jsx)(`span`,{className:`message-avatar`,"aria-hidden":`true`,children:D.slice(0,1).toUpperCase()}):(0,Q.jsx)(Kh,{avatar:n.authorAvatar??N_,className:`message-avatar human`,displayName:D,principalId:n.authorPrincipalId}),(0,Q.jsxs)(`article`,{children:[(s||l)&&(0,Q.jsxs)(`div`,{className:`message-actions`,role:`group`,"aria-label":`Actions for message from ${D}`,children:[l&&(0,Q.jsxs)(`div`,{className:`reaction-picker-anchor`,children:[(0,Q.jsx)(`button`,{className:`message-action-button`,type:`button`,"aria-label":`Add reaction`,"aria-expanded":u,title:`Add reaction`,onClick:()=>{h(null),d(e=>!e)},children:(0,Q.jsx)(Vv,{})}),u&&(0,Q.jsx)(`div`,{className:`reaction-picker`,role:`menu`,"aria-label":`Choose a reaction`,onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),d(!1))},children:pv.map(e=>{let t=O.some(t=>t.reaction===e.reaction&&t.reactedByViewer);return(0,Q.jsx)(`button`,{type:`button`,role:`menuitemcheckbox`,"aria-checked":t,"aria-label":`${t?`Remove`:`Add`} ${e.label} reaction`,disabled:f!==null,onClick:()=>void A(e.reaction,!t),children:e.symbol},e.reaction)})})]}),s&&(0,Q.jsx)(`button`,{className:`message-action-button`,type:`button`,"aria-label":`Reply to message`,title:`Reply`,onClick:()=>s(n.messageId),children:(0,Q.jsx)(Rv,{})})]}),(0,Q.jsxs)(`header`,{className:`message-meta`,children:[(0,Q.jsxs)(`span`,{className:`message-author`,children:[(0,Q.jsx)(`strong`,{children:D}),n.standingContribution&&(0,Q.jsx)(`span`,{className:`standing-contribution-mark`,"aria-label":`Agent contribution from standing participation`,title:`Agent contribution from standing participation`,children:(0,Q.jsx)(ty,{})})]}),(0,Q.jsx)(`time`,{dateTime:n.createdAt,children:cv(n.createdAt)})]}),(0,Q.jsx)(Nm,{body:n.body,mentions:n.mentions}),n.artifacts.map(e=>(0,Q.jsx)(gv,{artifact:e,onDownload:i,onLoad:a},e.artifactId)),(O.length>0||s&&n.replyCount>0)&&(0,Q.jsxs)(`div`,{className:`message-engagement`,role:`group`,"aria-label":`Message engagement`,children:[O.length>0&&(0,Q.jsx)(`div`,{className:`message-reactions`,role:`group`,"aria-label":`Message reactions`,children:O.map(e=>{let t=pv.find(t=>t.reaction===e.reaction);if(!t)return null;let n=g===e.reaction,r=y[e.reaction];return(0,Q.jsxs)(`span`,{className:`reaction-chip-anchor`,onMouseEnter:()=>j(e.reaction),onMouseLeave:()=>_(null),children:[(0,Q.jsxs)(`button`,{className:e.reactedByViewer?`active`:``,type:`button`,"aria-label":`${t.label}: ${e.count}. ${e.reactedByViewer?`Remove your reaction`:`Add your reaction`}`,"aria-pressed":e.reactedByViewer,disabled:!l||f!==null,onClick:()=>void A(e.reaction,!e.reactedByViewer),onFocus:()=>j(e.reaction),onBlur:()=>_(null),children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:t.symbol}),(0,Q.jsx)(`span`,{children:e.count})]}),n&&c&&(0,Q.jsxs)(`div`,{className:`reaction-reactors`,role:`tooltip`,children:[(0,Q.jsxs)(`strong`,{children:[t.symbol,` `,t.label]}),x===e.reaction&&(0,Q.jsx)(`span`,{children:`Loading…`}),C===e.reaction&&(0,Q.jsx)(`span`,{children:`Participants unavailable`}),r&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`ul`,{children:r.reactors.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:e.displayName}),(0,Q.jsxs)(`small`,{children:[e.kind===`agent`?`Agent`:`Human`,e.handle?` · @${e.handle}`:``]})]},e.principalId))}),r.truncated&&(0,Q.jsxs)(`span`,{children:[`Showing `,r.reactors.length,` of `,r.total]})]})]})]},e.reaction)})}),s&&n.replyCount>0&&(0,Q.jsxs)(`button`,{className:`thread-summary`,type:`button`,"aria-label":`Open thread with ${n.replyCount} ${n.replyCount===1?`reply`:`replies`}${e?`, including unread replies`:``}`,title:`Open thread`,onClick:()=>s(n.messageId),children:[n.replyParticipants.length>0&&(0,Q.jsxs)(`span`,{className:`thread-participants`,"aria-hidden":`true`,children:[n.replyParticipants.map(e=>e.kind===`human`?(0,Q.jsx)(Kh,{avatar:e.avatar??N_,className:`thread-participant-avatar human`,displayName:e.displayName,principalId:e.principalId},e.principalId):(0,Q.jsx)(`span`,{className:`thread-participant-avatar agent`,title:e.displayName,children:e.displayName.trim().slice(0,1).toUpperCase()||`?`},e.principalId)),n.replyParticipantCount>n.replyParticipants.length&&(0,Q.jsxs)(`span`,{className:`thread-participant-overflow`,children:[`+`,n.replyParticipantCount-n.replyParticipants.length]})]}),(0,Q.jsxs)(`span`,{className:`thread-summary-count`,children:[n.replyCount,` `,n.replyCount===1?`reply`:`replies`]}),(0,Q.jsx)(`span`,{className:`thread-summary-label`,children:`View thread`}),e&&(0,Q.jsx)(`strong`,{children:`New replies`}),(0,Q.jsx)(zv,{})]})]}),m&&(0,Q.jsx)(`p`,{className:`reaction-error`,role:`alert`,children:m})]})]})}var hv=new Set([`image/gif`,`image/jpeg`,`image/png`,`image/webp`]);function gv({artifact:e,onDownload:t,onLoad:n}){let[r,i]=(0,v.useState)(null),[a,o]=(0,v.useState)(null),s=hv.has(e.mediaType)||e.mediaType.startsWith(`audio/`);return(0,v.useEffect)(()=>{if(!s)return;let t=!1,r=null;return n(e.artifactId).then(e=>{t||(r=URL.createObjectURL(e),i(r))}).catch(()=>{t||o(`Attachment preview unavailable.`)}),()=>{t=!0,r&&URL.revokeObjectURL(r)}},[e.artifactId,s,n]),(0,Q.jsxs)(`section`,{className:`message-artifact`,children:[r&&hv.has(e.mediaType)&&(0,Q.jsx)(`img`,{src:r,alt:e.originalFilename??`Attached image`}),r&&e.mediaType.startsWith(`audio/`)&&(0,Q.jsx)(`audio`,{src:r,controls:!0,preload:`metadata`}),(0,Q.jsxs)(`div`,{className:`artifact-meta`,children:[(0,Q.jsx)(`span`,{children:e.originalFilename??`Attachment`}),(0,Q.jsxs)(`small`,{children:[Math.max(1,Math.ceil(e.byteSize/1024)),` KB`]}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>{o(null);try{t(e.artifactId)}catch{o(`Could not download this attachment.`)}},children:`Download`})]}),a&&(0,Q.jsx)(`p`,{className:`artifact-error`,role:`alert`,children:a})]})}function _v(){if(typeof globalThis.crypto?.getRandomValues!=`function`)throw Error(`This browser cannot create secure command identities.`);let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),`browser-${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function vv(e){if(e.kind===`direct`){let t=e.participants.map(e=>e.displayName.trim()).filter(Boolean);if(t.length>0)return t.join(`, `);if(e.agents.length===1&&e.agents[0].name.trim())return e.agents[0].name.trim()}return e.name?.trim()||(e.kind===`notification`?`Notifications`:e.kind===`group`?`Group`:`Conversation`)}function yv(e){return e.kind===`notification`?`!`:e.kind===`direct`?`@`:`#`}function bv(e){let t=xv(e);return t<=0?``:`, ${`${t}${e?.unreadCountCapped||e?.unreadReplyCountCapped?` or more`:``}`} unread ${t===1&&!e?.unreadCountCapped&&!e?.unreadReplyCountCapped?`message`:`messages`}`}function xv(e){return Math.min((e?.unreadCount??0)+(e?.unreadReplyCount??0),1e3)}function Sv(e){return typeof e.archivedAt==`string`}function Cv(e){return e.kind===`direct`&&typeof e.directMessageArchivedAt==`string`}function wv(e){return e.kind===`direct`&&e.agents.length===0&&e.participants.length===1&&e.participants[0].kind===`human`}function Tv(e){return e===`admin`?`Administrator`:e===`member`?`Member`:e.charAt(0).toUpperCase()+e.slice(1)}function Ev(e,t){let n=e.slice(0,t),r=/(?:^|\s)@([^@\n]*)$/.exec(n);if(!r)return null;let i=r[1];return{end:t,query:i,start:t-i.length-1}}function Dv({agents:e,initialAgentIds:t,originChannelId:n,originName:r,onCancel:i,onCreate:a}){let[o,s]=(0,v.useState)(``),[c,l]=(0,v.useState)(()=>t.length>0?t:e[0]?[e[0].agentId]:[]),[u,d]=(0,v.useState)(!1),[f,p]=(0,v.useState)(null),m=async e=>{e.preventDefault();let t=o.trim();if(!t||c.length===0){p(`A channel name and at least one agent are required.`);return}d(!0),p(null);try{await a({agentIds:c,name:t,originChannelId:n})}catch(e){p(e instanceof Error?e.message:`Could not create this channel.`),d(!1)}};return(0,Q.jsx)(`div`,{className:`modal-backdrop`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`create-channel-title`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`New conversation space`}),(0,Q.jsx)(`h2`,{id:`create-channel-title`,children:`Create channel`}),r&&(0,Q.jsxs)(`p`,{children:[`Start from `,(0,Q.jsx)(`strong`,{children:r}),`.`]}),(0,Q.jsxs)(`form`,{onSubmit:e=>void m(e),children:[(0,Q.jsx)(`label`,{htmlFor:`channel-name`,children:`Channel name`}),(0,Q.jsx)(`input`,{id:`channel-name`,autoFocus:!0,maxLength:200,value:o,onChange:e=>s(e.target.value)}),(0,Q.jsxs)(`fieldset`,{children:[(0,Q.jsx)(`legend`,{children:`Agents`}),e.map(e=>(0,Q.jsxs)(`label`,{className:`channel-agent-choice`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:c.includes(e.agentId),onChange:t=>l(n=>t.target.checked?[...n,e.agentId]:n.filter(t=>t!==e.agentId))}),(0,Q.jsx)(`span`,{children:e.name})]},e.agentId))]}),f&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:f}),(0,Q.jsxs)(`div`,{className:`form-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:u,children:u?`Creating…`:`Create channel`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:i,disabled:u,children:`Cancel`})]})]})]})})}function Ov({onCancel:e,onLoad:t,onOpen:n}){let[r,i]=(0,v.useState)(null),[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(null);(0,v.useEffect)(()=>{let e=!1;return t().then(t=>{e||i(t)}).catch(t=>{e||c(t instanceof Error?t.message:`Could not load Workshop people.`)}),()=>{e=!0}},[t]);let l=async e=>{if(!a){o(e),c(null);try{await n(e)}catch(e){c(e instanceof Error?e.message:`Could not start this conversation.`),o(null)}}};return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog human-conversation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`human-conversation-title`,children:[(0,Q.jsxs)(`header`,{className:`channel-archive-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Direct messages`}),(0,Q.jsx)(`h2`,{id:`human-conversation-title`,children:`Start a conversation`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close people picker`,title:`Close`,disabled:a!==null,onClick:e,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),r===null&&!s&&(0,Q.jsx)(`p`,{className:`human-conversation-state`,role:`status`,children:`Loading people…`}),r?.length===0&&(0,Q.jsx)(`p`,{className:`human-conversation-state`,children:`No other people are available in this Workshop.`}),r&&r.length>0&&(0,Q.jsx)(`ul`,{className:`human-conversation-list`,children:r.map(e=>(0,Q.jsx)(`li`,{children:(0,Q.jsxs)(`button`,{type:`button`,disabled:a!==null,"aria-label":`${e.displayName}, @${e.handle}${e.conversationChannelId?`, conversation started`:``}`,onClick:()=>void l(e.principalId),children:[(0,Q.jsx)(Kh,{avatar:e.avatar??N_,className:`human-picker-avatar`,displayName:e.displayName,principalId:e.principalId}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.displayName}),(0,Q.jsxs)(`small`,{children:[`@`,e.handle]})]}),(0,Q.jsx)(`small`,{children:a===e.principalId?`Opening…`:e.conversationChannelId?`Open`:`Message`})]})},e.principalId))}),s&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:s})]})})}function kv({attachedAgents:e,enablements:t,onCancel:n,onSave:r}){let i=(0,v.useMemo)(()=>e.map(e=>e.agentId),[e]),[a,o]=(0,v.useState)(i),[s,c]=(0,v.useState)(!1),[l,u]=(0,v.useState)(null),d=(0,v.useMemo)(()=>{let n=new Map(t.filter(e=>e.lifecycleState===`enabled`).map(e=>[e.agentId,e]));for(let t of e)n.has(t.agentId)||n.set(t.agentId,{agentId:t.agentId,definitionId:``,directChannelId:null,displayName:t.name,eligibleRuntimes:[],enablementId:null,handle:t.name,lifecycleState:`disabled`,runtimeProfileId:t.runtimeProfileId,stateVersion:null,canManage:!1,conversationStarted:!1,ownerPrincipalId:null,ownerRuntimeProfileId:t.runtimeProfileId});return Array.from(n.values()).sort((e,t)=>e.displayName.localeCompare(t.displayName))},[e,t]),f=async e=>{e.preventDefault(),c(!0),u(null);try{await r(a)}catch(e){u(e instanceof Error?e.message:`Could not update channel agents.`),c(!1)}};return(0,Q.jsx)(`div`,{className:`modal-backdrop`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`manage-channel-agents-title`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Channel management`}),(0,Q.jsx)(`h2`,{id:`manage-channel-agents-title`,children:`Agents`}),(0,Q.jsx)(`p`,{children:`Attached agents use the runtime explicitly sponsored by your enabled direct agent. Shared channels never inject that sponsor’s personal preferences or memory. Detaching stops new mentions and wakes while preserving messages, completed runs, and any run already accepted.`}),(0,Q.jsxs)(`form`,{onSubmit:e=>void f(e),children:[(0,Q.jsxs)(`fieldset`,{children:[(0,Q.jsx)(`legend`,{children:`Attached agents`}),d.map(t=>{let n=e.find(e=>e.agentId===t.agentId),r=t.lifecycleState===`enabled`;return(0,Q.jsxs)(`label`,{className:`channel-agent-choice`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:a.includes(t.agentId),disabled:!r&&!n,onChange:e=>o(n=>e.target.checked?[...n,t.agentId]:n.filter(e=>e!==t.agentId))}),(0,Q.jsxs)(`span`,{children:[t.displayName,(0,Q.jsx)(`small`,{children:n?`${n.available?`Available`:`Unavailable`} · sponsored by ${n.sponsorDisplayName??`unknown`}`:`Available to attach`})]})]},t.agentId)})]}),l&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:l}),(0,Q.jsxs)(`div`,{className:`form-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:s,children:s?`Saving…`:`Save`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:n,disabled:s,children:`Cancel`})]})]})]})})}function Av({membership:e,onCancel:t,onChange:n}){let r=(0,v.useMemo)(()=>e.members.map(e=>e.principalId),[e.members]),[i,a]=(0,v.useState)(r),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(null),u=(0,v.useMemo)(()=>[...e.members,...e.eligibleHumans].sort((e,t)=>e.role===`owner`&&t.role!==`owner`?-1:t.role===`owner`&&e.role!==`owner`?1:e.displayName.localeCompare(t.displayName)),[e.eligibleHumans,e.members]),d=async a=>{a.preventDefault(),s(!0),l(null);try{let a=e.stateVersion,o=new Set(r),s=new Set(i);for(let t of e.members)t.role!==`owner`&&!s.has(t.principalId)&&(a=await n(t.principalId,`remove`,a,_v()));for(let t of e.eligibleHumans)!o.has(t.principalId)&&s.has(t.principalId)&&(a=await n(t.principalId,`add`,a,_v()));t()}catch(e){l(e instanceof Error?e.message:`Could not update channel members.`),s(!1)}};return(0,Q.jsx)(`div`,{className:`modal-backdrop`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`manage-channel-members-title`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Channel management`}),(0,Q.jsx)(`h2`,{id:`manage-channel-members-title`,children:`People`}),(0,Q.jsx)(`p`,{children:`Members can read this private channel and mention its people and agents. The channel owner is permanent; ownership transfer is not available.`}),(0,Q.jsxs)(`form`,{onSubmit:e=>void d(e),children:[(0,Q.jsxs)(`fieldset`,{children:[(0,Q.jsx)(`legend`,{children:`Human members`}),u.map(e=>(0,Q.jsxs)(`label`,{className:`channel-agent-choice`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:i.includes(e.principalId),disabled:o||e.role===`owner`,onChange:t=>a(n=>t.target.checked?[...n,e.principalId]:n.filter(t=>t!==e.principalId))}),(0,Q.jsx)(Kh,{avatar:e.avatar??N_,className:`human-picker-avatar`,displayName:e.displayName,principalId:e.principalId}),(0,Q.jsxs)(`span`,{children:[e.displayName,(0,Q.jsxs)(`small`,{children:[`@`,e.handle,e.role===`owner`?` · owner`:``]})]})]},e.principalId))]}),c&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:c}),(0,Q.jsxs)(`div`,{className:`form-actions`,children:[(0,Q.jsx)(`button`,{className:`primary-button`,type:`submit`,disabled:o,children:o?`Saving…`:`Save`}),(0,Q.jsx)(`button`,{className:`quiet-button`,type:`button`,onClick:t,disabled:o,children:`Cancel`})]})]})]})})}function jv({busy:e,channelName:t,error:n,loading:r,onClose:i,onStandingChange:a,participation:o}){return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog channel-settings-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`channel-settings-title`,children:[(0,Q.jsxs)(`header`,{className:`channel-archive-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`p`,{className:`overline`,children:[`# `,t]}),(0,Q.jsx)(`h2`,{id:`channel-settings-title`,children:`Channel settings`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close channel settings`,title:`Close channel settings`,disabled:e,onClick:i,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),(0,Q.jsxs)(`section`,{className:`channel-settings-section`,"aria-labelledby":`channel-participation-title`,children:[(0,Q.jsx)(`h3`,{id:`channel-participation-title`,children:`Participation`}),r&&!o&&(0,Q.jsx)(`p`,{className:`channel-settings-state`,role:`status`,children:`Loading participation policy…`}),o&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`standing-policy-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:o.policy.enabled,disabled:!o.policy.canManage||e,onChange:e=>void a(e.target.checked)}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Standing participation`}),(0,Q.jsx)(`small`,{children:o.policy.enabled?o.policy.hostEnabled?`On for this channel`:`Requested here · unavailable on this host`:`Off for this channel`})]})]}),!o.policy.canManage&&(0,Q.jsx)(`p`,{children:`Only a channel owner can change this policy.`}),(0,Q.jsxs)(`details`,{className:`standing-limits`,children:[(0,Q.jsx)(`summary`,{children:`Host limits`}),(0,Q.jsxs)(`dl`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Agents`}),(0,Q.jsxs)(`dd`,{children:[o.policy.maxAgentsPerChannel,`/channel`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Observe batch`}),(0,Q.jsxs)(`dd`,{children:[o.policy.maxMessagesPerObserveRun,` messages`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Pending`}),(0,Q.jsxs)(`dd`,{children:[o.policy.maxPendingMessagesPerScope,`/scope`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Observation`}),(0,Q.jsxs)(`dd`,{children:[o.policy.maxObserveRunsPerHour,`/hour`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Contributions`}),(0,Q.jsxs)(`dd`,{children:[o.policy.maxUnsolicitedMessagesPerHour,`/hour`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Cooldown`}),(0,Q.jsxs)(`dd`,{children:[o.policy.minimumUnsolicitedIntervalSeconds,`s`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Quiet expiry`}),(0,Q.jsxs)(`dd`,{children:[o.policy.quietExpirySeconds,`s`]})]})]})]})]}),n&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:n})]})]})})}function Mv({channels:e,busyChannelId:t,onClose:n,onRestore:r,onView:i}){return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog channel-archive-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`channel-archive-title`,children:[(0,Q.jsxs)(`header`,{className:`channel-archive-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Channels`}),(0,Q.jsx)(`h2`,{id:`channel-archive-title`,children:`Archive`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close channel archive`,title:`Close channel archive`,onClick:n,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),e.length===0?(0,Q.jsx)(`p`,{className:`channel-archive-empty`,children:`No archived channels.`}):(0,Q.jsx)(`ul`,{className:`channel-archive-list`,children:e.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsxs)(`strong`,{children:[`# `,vv(e)]}),(0,Q.jsxs)(`small`,{children:[`Archived `,e.archivedAt?cv(e.archivedAt):``]})]}),(0,Q.jsxs)(`span`,{className:`channel-archive-actions`,children:[(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`View archived channel ${vv(e)}`,title:`View archived channel`,onClick:()=>i(e.channelId),children:(0,Q.jsx)(ey,{})}),e.role===`owner`&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Restore channel ${vv(e)}`,title:`Restore channel`,disabled:t!==null,onClick:()=>void r(e.channelId),children:(0,Q.jsx)(Kv,{})})]})]},e.channelId))})]})})}function Nv({channels:e,busyChannelId:t,onClose:n,onRestore:r,onView:i}){return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog channel-archive-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`direct-message-archive-title`,children:[(0,Q.jsxs)(`header`,{className:`channel-archive-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Direct messages`}),(0,Q.jsx)(`h2`,{id:`direct-message-archive-title`,children:`Archive`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close direct-message archive`,title:`Close direct-message archive`,onClick:n,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),e.length===0?(0,Q.jsx)(`p`,{className:`channel-archive-empty`,children:`No archived direct messages.`}):(0,Q.jsx)(`ul`,{className:`channel-archive-list`,children:e.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsxs)(`strong`,{children:[`@ `,vv(e)]}),(0,Q.jsxs)(`small`,{children:[`Archived `,e.directMessageArchivedAt?cv(e.directMessageArchivedAt):``]})]}),(0,Q.jsxs)(`span`,{className:`channel-archive-actions`,children:[(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`View archived direct message ${vv(e)}`,title:`View archived direct message`,onClick:()=>i(e.channelId),children:(0,Q.jsx)(ey,{})}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Restore direct message ${vv(e)}`,title:`Restore direct message`,disabled:t!==null,onClick:()=>void r(e.channelId),children:(0,Q.jsx)(Kv,{})})]})]},e.channelId))})]})})}function Pv({agents:e,onClose:t,onOpenConversation:n,onContinue:r,onView:i}){let a=e.filter(e=>e.state!==`Archived`),o=e.filter(e=>e.state===`Archived`),s=e=>(0,Q.jsx)(`ul`,{className:`channel-archive-list`,children:e.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.displayName}),(0,Q.jsxs)(`small`,{children:[`@`,e.handle,` · `,e.state]})]}),(0,Q.jsxs)(`span`,{className:`channel-archive-actions`,children:[e.state!==`Archived`&&(0,Q.jsx)(`button`,{className:`primary-button`,type:`button`,onClick:()=>r(e.definitionId,e.setupId),children:`Continue setup`}),e.conversationChannelId&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Open archived conversation with ${e.displayName}`,title:`Open archived conversation`,onClick:()=>n(e.conversationChannelId),children:(0,Q.jsx)(Rv,{})}),e.definitionId&&e.state===`Archived`&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`View archived agent ${e.displayName}`,title:`View archived agent`,onClick:()=>i(e.definitionId),children:(0,Q.jsx)(ey,{})})]})]},e.entryId))});return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`section`,{className:`channel-creation-dialog channel-archive-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`inactive-agents-title`,children:[(0,Q.jsxs)(`header`,{className:`channel-archive-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Agents`}),(0,Q.jsx)(`h2`,{id:`inactive-agents-title`,children:`Drafts and archive`})]}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close drafts and archive`,title:`Close drafts and archive`,onClick:t,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]}),e.length===0?(0,Q.jsx)(`p`,{className:`channel-archive-empty`,children:`No draft or archived agents.`}):(0,Q.jsxs)(`div`,{className:`inactive-agent-sections`,children:[a.length>0&&(0,Q.jsxs)(`section`,{children:[(0,Q.jsx)(`h3`,{children:`Drafts`}),s(a)]}),o.length>0&&(0,Q.jsxs)(`section`,{children:[(0,Q.jsx)(`h3`,{children:`Archived agents`}),s(o)]})]})]})})}function Fv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`})})}function Iv(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`m22 2-7 20-4-9-9-4Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`}),(0,Q.jsx)(`path`,{d:`M22 2 11 13`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`})]})}function Lv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`currentColor`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`rect`,{x:`6`,y:`6`,width:`12`,height:`12`,rx:`1`})})}function Rv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M20 15a3 3 0 0 1-3 3H9l-5 3V7a3 3 0 0 1 3-3h10a3 3 0 0 1 3 3z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`})})}function zv(){return(0,Q.jsx)(`svg`,{className:`thread-summary-chevron`,"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`m9 18 6-6-6-6`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`})})}function Bv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`m7 9.5 5 5 5-5`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.75`})})}function Vv(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`circle`,{cx:`11`,cy:`11`,r:`8`,stroke:`currentColor`,strokeWidth:`2`}),(0,Q.jsx)(`path`,{d:`M8 9h.01M14 9h.01M7.5 13.5c1 1.5 2.2 2.2 3.5 2.2s2.5-.7 3.5-2.2M19 15v6M16 18h6`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`})]})}function Hv({followed:e}){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:e?`currentColor`:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`}),(0,Q.jsx)(`path`,{d:`M13.73 21a2 2 0 0 1-3.46 0`,fill:`none`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`})]})}function Uv(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`circle`,{cx:`12`,cy:`12`,r:`3`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-2.83 2.83-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 .6 1.7 1.7 0 0 0-.4 1.1V21H9.6v-.09A1.7 1.7 0 0 0 8.5 19.4a1.7 1.7 0 0 0-1.88.34l-.06.06-2.83-2.83.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-.6-1 1.7 1.7 0 0 0-1.1-.4H3V9.6h.09A1.7 1.7 0 0 0 4.6 8.5a1.7 1.7 0 0 0-.34-1.88l-.06-.06 2.83-2.83.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-.6 1.7 1.7 0 0 0 .4-1.1V3h4v.09A1.7 1.7 0 0 0 15.5 4.6a1.7 1.7 0 0 0 1.88-.34l.06-.06 2.83 2.83-.06.06A1.7 1.7 0 0 0 19.4 9c.14.38.36.72.66 1 .3.28.68.42 1.1.4H21v4h-.09A1.7 1.7 0 0 0 19.4 15Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`})]})}function Wv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M12 5v14M5 12h14`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`})})}function Gv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M4 7h16v13H4zM3 4h18v3H3zM9 11h6`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.8`})})}function Kv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M4 12a8 8 0 1 0 2.34-5.66L4 8.68M4 4v4.68h4.68`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.8`})})}function qv(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M20 11a8 8 0 1 0-2.34 5.66`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M20 5v6h-6`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.8`})]})}function Jv(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M3.5 6.5h6l2 2h9v10h-17z`,stroke:`currentColor`,strokeLinejoin:`round`,strokeWidth:`1.8`})})}function Yv(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`circle`,{cx:`12`,cy:`12`,r:`8.5`,stroke:`currentColor`,strokeWidth:`1.7`}),(0,Q.jsx)(`path`,{d:`M12 7.5v5l3.2 2`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.7`})]})}function Xv(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`circle`,{cx:`6`,cy:`5`,r:`2`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`19`,r:`2`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`circle`,{cx:`18`,cy:`5`,r:`2`,stroke:`currentColor`,strokeWidth:`1.8`}),(0,Q.jsx)(`path`,{d:`M6 7v10M18 7v3a5 5 0 0 1-5 5H9`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.8`})]})}function Zv({action:e,children:t,className:n=``,revealKey:r=0,revealReady:i=!0,revealTargetId:a=null,title:o}){let[s,c]=(0,v.useState)(()=>Qv()[o]??!1),l=(0,v.useRef)(null);return(0,v.useEffect)(()=>{c(Qv()[o]??!1)},[o]),(0,v.useEffect)(()=>{if(r===0)return;if(!s){c(!0),$v(o,!0);return}if(!i)return;let e=a?l.current?.querySelector(`#${a}`):l.current;e?.focus({preventScroll:!0});let t=window.requestAnimationFrame(()=>{e?.scrollIntoView?.({behavior:`smooth`,block:`nearest`})});return()=>window.cancelAnimationFrame(t)},[s,r,i,a,o]),(0,Q.jsxs)(`details`,{className:`context-section${n?` ${n}`:``}`,open:s,ref:l,onToggle:e=>{let t=e.currentTarget.open;c(t),$v(o,t)},children:[(0,Q.jsxs)(`summary`,{className:`context-section-toggle`,children:[(0,Q.jsx)(`h3`,{className:`context-section-title`,children:o}),e&&(0,Q.jsx)(`span`,{className:`context-section-header-action`,onClick:e=>e.stopPropagation(),children:e})]}),(0,Q.jsx)(`div`,{className:`context-section-body`,children:t})]})}function Qv(){try{let e=JSON.parse(localStorage.getItem(T_)??`null`);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`boolean`))return e}catch{}return{}}function $v(e,t){try{localStorage.setItem(T_,JSON.stringify({...Qv(),[e]:t}))}catch{}}function ey(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z`,stroke:`currentColor`,strokeLinejoin:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`circle`,{cx:`12`,cy:`12`,r:`2.5`,stroke:`currentColor`,strokeWidth:`1.8`})]})}function ty(){return(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:[(0,Q.jsx)(`path`,{d:`M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z`,stroke:`currentColor`,strokeLinejoin:`round`,strokeWidth:`1.8`}),(0,Q.jsx)(`circle`,{cx:`12`,cy:`12`,r:`2.5`,stroke:`currentColor`,strokeWidth:`1.8`})]})}function ny(){return(0,Q.jsx)(`svg`,{"aria-hidden":`true`,fill:`none`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,Q.jsx)(`path`,{d:`M3 3l18 18M9.6 6.4A10.8 10.8 0 0 1 12 6c6 0 9.5 6 9.5 6a17 17 0 0 1-2.1 2.8M6.2 7.7C3.8 9.5 2.5 12 2.5 12s3.5 6 9.5 6c1 0 1.9-.2 2.7-.4M9.9 9.9a3 3 0 0 0 4.2 4.2`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.8`})})}function ry({activeStandingAgentIds:e,channelName:t,liveMessages:n,focusedMessage:r,onClose:i,onDownloadArtifact:a,onLoadArtifact:o,onLoadThread:s,onLoadThreadUnread:c,onLoadReactors:l,onAdvanceThreadRead:u,onSetThreadFollowed:d,onSuppressStanding:f,onMessageVisible:p,onSetReaction:m,onSubmitCommand:h,reactionUpdates:g,principalEvents:_,readOnly:y,rootMessage:b,runActive:x}){let[S,C]=(0,v.useState)(null),[w,T]=(0,v.useState)(null),[E,D]=(0,v.useState)(!1),[O,k]=(0,v.useState)(``),[A,j]=(0,v.useState)(!1),[M,N]=(0,v.useState)(null),[P,F]=(0,v.useState)(null),[I,L]=(0,v.useState)(null),[R,ee]=(0,v.useState)(!1),[z,B]=(0,v.useState)(!1),V=(0,v.useRef)(null),H=(0,v.useRef)(P),te=(0,v.useRef)(null),U=(0,v.useRef)(!1);H.current=P,(0,v.useEffect)(()=>{let e=new AbortController;return C(null),F(null),L(null),T(null),Promise.all([s(b.messageId,null,e.signal),c(b.messageId,e.signal)]).then(([e,t])=>{C(e),F(t),L(t.firstUnreadMessageId)},t=>{e.signal.aborted||T(t instanceof Error?t.message:`Could not load this thread.`)}),()=>e.abort()},[s,c,b.messageId]),(0,v.useEffect)(()=>_.subscribe(e=>{if(e.kind===`synchronize`){c(b.messageId).then(F,()=>void 0);return}for(let t of e.batch.changes)for(let e of t.threadChanges)e.state.threadRootId===b.messageId&&F(e.state)}),[c,_,b.messageId]),(0,v.useLayoutEffect)(()=>{let e=V.current;if(!e)return;let t=e.offsetHeight-e.clientHeight;e.style.height=`auto`,e.style.height=`${e.scrollHeight+t}px`},[O,b.messageId]);let ne=(0,v.useMemo)(()=>{let e=new Map;for(let t of S?.messages??[])e.set(t.messageId,t);for(let t of n)t.threadRootId===b.messageId&&e.set(t.messageId,t);return r?.threadRootId===b.messageId&&e.set(r.messageId,r),Array.from(e.values()).sort((e,t)=>e.eventPosition-t.eventPosition)},[r,n,b.messageId,S?.messages]);(0,v.useEffect)(()=>{if(!r)return;let e=window.requestAnimationFrame(()=>{document.querySelector(`[data-message-id="${r.messageId}"]`)?.scrollIntoView?.({behavior:`smooth`,block:`center`})});return()=>window.cancelAnimationFrame(e)},[r,ne.length]);let re=async()=>{if(!(!S?.nextCursor||E)){D(!0),T(null);try{let e=await s(b.messageId,S.nextCursor);C(t=>t&&{...t,messages:[...t.messages,...e.messages],nextCursor:e.nextCursor})}catch(e){T(e instanceof Error?e.message:`Could not load more replies.`)}finally{D(!1)}}},W=async e=>{e.preventDefault();let t=O.trim();if(!(!t||A||x)){j(!0),T(null);try{let e=M??_v();N(e),await h(e,t,null,b.messageId),k(``),N(null)}catch(e){T(e instanceof Error?e.message:`Kai could not send this reply.`)}finally{j(!1)}}},ie=async()=>{let e=H.current;if(!(!e||R)){ee(!0),T(null);try{let t=await d(b.messageId,!e.followed,e.stateVersion,_v());F(t.state),t.state.followed&&L(t.state.firstUnreadMessageId)}catch(e){T(e instanceof Error?e.message:`Could not update thread follow state.`);try{F(await c(b.messageId))}catch{}}finally{ee(!1)}}},ae=(0,v.useCallback)(e=>{if(p(e),document.visibilityState!==`visible`)return;let t=ne.find(t=>t.messageId===e),n=H.current;!t||!n?.followed||t.eventPosition<=n.readThroughEventPosition||((!te.current||te.current.eventPosition{try{for(;te.current;){let e=te.current;te.current=null;let t=H.current;if(!(!t?.followed||e.eventPosition<=t.readThroughEventPosition))try{let n=await u(b.messageId,e.messageId,t.stateVersion,_v());H.current=n.state,F(n.state)}catch{t=await c(b.messageId),H.current=t,F(t),t.followed&&e.eventPosition>t.readThroughEventPosition&&(te.current=e)}}}catch(e){T(e instanceof Error?e.message:`Could not update thread unread state.`)}finally{U.current=!1}})())},[u,c,p,ne,b.messageId]),oe=async()=>{if(!(z||e.length===0)){B(!0),T(null);try{await Promise.all(e.map(e=>f(e,b.messageId)))}catch(e){T(e instanceof Error?e.message:`Could not suppress standing observation.`)}finally{B(!1)}}};return(0,Q.jsxs)(`div`,{className:`thread-pane`,children:[(0,Q.jsxs)(`header`,{className:`thread-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`p`,{className:`overline`,children:[`Thread in `,t]}),(0,Q.jsxs)(`h2`,{children:[ne.length,` `,ne.length===1?`reply`:`replies`]})]}),(0,Q.jsxs)(`div`,{className:`thread-header-actions`,children:[e.length>0&&!y&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Suppress standing agents in this thread`,title:`Suppress standing agents in this thread`,disabled:z,onClick:()=>void oe(),children:(0,Q.jsx)(ny,{})}),P&&!y&&(0,Q.jsx)(`button`,{className:`panel-icon-button thread-follow-button${P.followed?` followed`:``}`,type:`button`,"aria-label":P.followed?`Unfollow thread`:`Follow thread`,"aria-pressed":P.followed,title:R?`Updating thread follow state`:P.followed?`Unfollow thread`:`Follow thread`,disabled:R,onClick:()=>void ie(),children:(0,Q.jsx)(Hv,{followed:P.followed})}),(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Close thread`,title:`Close thread`,onClick:i,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`×`})})]})]}),(0,Q.jsxs)(`div`,{className:`thread-scroll`,children:[(0,Q.jsxs)(`ol`,{className:`thread-message-list`,children:[(0,Q.jsx)(mv,{highlighted:r?.messageId===b.messageId,message:(()=>{let e=S?.root??b;return{...e,reactions:g[e.messageId]??e.reactions}})(),onDownloadArtifact:a,onLoadArtifact:o,onLoadReactors:l,onMessageVisible:p,onSetReaction:y?void 0:m}),ne.map(e=>(0,Q.jsxs)(v.Fragment,{children:[I===e.messageId&&(0,Q.jsx)(`li`,{className:`first-unread-divider`,role:`separator`,"aria-label":`First unread reply`,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`New replies`})}),(0,Q.jsx)(mv,{highlighted:r?.messageId===e.messageId,message:{...e,reactions:g[e.messageId]??e.reactions},onDownloadArtifact:a,onLoadArtifact:o,onLoadReactors:l,onMessageVisible:ae,onSetReaction:y?void 0:m})]},e.messageId))]}),!S&&!w&&(0,Q.jsx)(`p`,{className:`thread-state`,children:`Loading replies…`}),S?.nextCursor&&(0,Q.jsx)(`button`,{className:`timeline-earlier-button`,type:`button`,disabled:E,onClick:()=>void re(),children:E?`Loading…`:`Load more replies`})]}),y?(0,Q.jsx)(`p`,{className:`archived-read-only`,children:`Archived channels are read-only.`}):(0,Q.jsxs)(`form`,{className:`composer-form thread-composer`,onSubmit:e=>void W(e),children:[(0,Q.jsx)(`textarea`,{ref:V,"aria-label":`Reply in ${t}`,maxLength:5e4,placeholder:`Reply…`,rows:1,value:O,disabled:A||x,onChange:e=>{k(e.target.value),A||N(null)},onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),e.currentTarget.form?.requestSubmit())}}),(0,Q.jsx)(`button`,{className:`composer-icon-button send-button`,type:`submit`,"aria-busy":A,"aria-label":A?`Sending reply…`:`Send reply`,title:A?`Sending reply…`:`Send reply`,disabled:!O.trim()||A||x,children:(0,Q.jsx)(Iv,{})})]}),w&&(0,Q.jsx)(`p`,{className:`thread-error`,role:`alert`,children:w})]})}function iy({agentDestination:e,agentToken:t,channel:n,connection:r,earlier:i,later:a,messages:o,threadMessages:s,workspacesDestination:c,scheduledJobsDestination:l,memoryDestination:u,memoryToken:d,mentionsDestination:f,followingDestination:p,reviewsDestination:m,following:h,inbox:g,unread:_,principalEvents:y,unreadBoundaryMessageId:b,readActivatedInitially:x,focusedMessage:S,focusedThreadRoot:C,requestedThreadRootId:w,focusedMessageError:T,settingsDestination:E,settingsInitialSection:D,settingsRuntimeLabel:O,settingsSession:k,navigation:A,runActivities:j,runPreviews:M,runTrace:N,standingParticipationVersion:P,reactionUpdates:F,workshop:I,onForget:L,onAgentNavigationChanged:R,onArchiveChannel:ee,onArchiveDirectMessage:z,onAttachAgent:H,onCancelRun:te,onCreateChannel:U,onDismissAgent:ne,onDetachAgent:re,onDownloadArtifact:W,onLoadEarlier:ie,onLoadLater:ae,onJumpLatest:oe,onLoadArtifact:se,onLoadChannelMembers:ce,onLoadHumanPeers:le,onLoadRun:ue,onLoadRunTrace:G,onLoadRuntimeLaneStatus:K,onStartFreshProviderSession:q,onLoadThread:de,onLoadThreadUnread:J,onLoadReactors:Y,onAdvanceThreadRead:fe,onSetThreadFollowed:pe,onChangeChannelMember:me,onMemoryAuthenticationFailure:he,onOpenWorkspaces:X,onOpenScheduledJobs:ge,onOpenMemory:_e,onOpenMentions:ve,onOpenFollowing:ye,onOpenReviews:be,onOpenFollowedThread:xe,onOpenHumanNotification:Ce,onCreateAgent:we,onOpenAgentDefinition:Te,onOpenAgentSetup:Ee,onOpenAgentChannel:De,onOpenSettings:Oe,onRestoreChannel:ke,onRestoreDirectMessage:Ae,onSelectAgent:je,onSelectMemory:Me,onSelectChannel:Ne,onSetReaction:Pe,onSubmitCommand:Fe,onStartHumanConversation:Ie,onSwitchWorkspace:Re,onSettingsDirtyChange:ze,onSettingsAccessFailure:Ve}){let Ue=Km(),We=Gh(),Z=n.channelId,Ge=e!==null,Ke=c,qe=l,Ze=u!==null,Qe=f,$e=p,et=m,tt=E,nt=Ge||Ke||Ze||Qe||$e||et||tt,rt=vv(n),it=yv(n),at=wv(n),ot=Cv(n),st=Sv(n)||ot,[ct,lt]=(0,v.useState)(()=>nv(Z)),[ut,dt]=(0,v.useState)(null),[ft,pt]=(0,v.useState)(null),[mt,ht]=(0,v.useState)(!1),[gt,_t]=(0,v.useState)(null),[vt,yt]=(0,v.useState)(()=>new Set),[bt,xt]=(0,v.useState)({}),[St,Ct]=(0,v.useState)(()=>Date.now()),[wt,Tt]=(0,v.useState)(0),[Et,Dt]=(0,v.useState)(!1),[Ot,kt]=(0,v.useState)(x),[At,jt]=(0,v.useState)(R_),[Mt,Nt]=(0,v.useState)(!1),[Pt,Ft]=(0,v.useState)(G_),[It,Lt]=(0,v.useState)(!1),[Rt,zt]=(0,v.useState)(null),[Bt,Vt]=(0,v.useState)([]),Ht=(0,v.useMemo)(()=>Object.values(bt).sort((e,t)=>e.acceptedAt.localeCompare(t.acceptedAt)||e.runId.localeCompare(t.runId)),[bt]),Ut=(0,v.useMemo)(()=>Ht.filter(ov),[Ht]),Wt=(0,v.useMemo)(()=>Ut.filter(e=>e.kind===`respond`),[Ut]),Gt=(0,v.useMemo)(()=>{if(Ht.length===0)return[];let e=new Set(Ut.map(e=>e.inboundMessageId)),t=e.size>0?e:new Set([Ht[Ht.length-1].inboundMessageId]);return Ht.filter(e=>t.has(e.inboundMessageId))},[Ut,Ht]),Kt=Ht.map(e=>`${e.runId}:${e.status}:${e.cancellationRequestedAt??``}`).join(`|`),[qt,Jt]=(0,v.useState)(null),[Yt,Xt]=(0,v.useState)(null),Zt=Bt.length===1?Bt[0]:null,[Qt,$t]=(0,v.useState)(!1),[en,tn]=(0,v.useState)(!1),[nn,rn]=(0,v.useState)(!1),[an,on]=(0,v.useState)(!1),[sn,cn]=(0,v.useState)(0),[ln,un]=(0,v.useState)(!1),[dn,fn]=(0,v.useState)(null),[pn,mn]=(0,v.useState)([]),[hn,gn]=(0,v.useState)({agentId:null,key:0}),[_n,vn]=(0,v.useState)(null),[yn,bn]=(0,v.useState)(!1),[xn,Sn]=(0,v.useState)(!1),[Cn,wn]=(0,v.useState)(!1),[Tn,En]=(0,v.useState)(!1),[Dn,On]=(0,v.useState)(!1),[kn,An]=(0,v.useState)(null),[jn,Mn]=(0,v.useState)(null),[Nn,Pn]=(0,v.useState)([]),[Fn,In]=(0,v.useState)([]),[Ln,Rn]=(0,v.useState)([]),[zn,Bn]=(0,v.useState)(null),[Vn,Hn]=(0,v.useState)(!1),[Un,Wn]=(0,v.useState)(null),[Gn,Kn]=(0,v.useState)(!1),[qn,Jn]=(0,v.useState)({}),[Yn,Xn]=(0,v.useState)(null),[Zn,Qn]=(0,v.useState)(()=>Date.now()),[$n,er]=(0,v.useState)(null),[tr,nr]=(0,v.useState)(0),[rr,ar]=(0,v.useState)(null),[or,sr]=(0,v.useState)(null),[cr,lr]=(0,v.useState)(!1),[ur,dr]=(0,v.useState)(null),[fr,pr]=(0,v.useState)(!1),[mr,hr]=(0,v.useState)(null),[gr,_r]=(0,v.useState)(null),[vr,yr]=(0,v.useState)(!1),[br,xr]=(0,v.useState)(null),Sr=(0,v.useRef)(null),[Cr,wr]=(0,v.useState)(null),Tr=(0,v.useRef)(null),Er=(0,v.useRef)(null),Dr=(0,v.useRef)(null),Or=(0,v.useRef)(null),kr=(0,v.useRef)(null),Ar=(0,v.useRef)(null),jr=(0,v.useRef)({pointerX:0,width:0}),Mr=(0,v.useRef)({pointerX:0,width:0}),Nr=(0,v.useCallback)(e=>{g.markVisibleRead(e)},[g.markVisibleRead]),Pr=(0,v.useRef)(Z),Fr=(0,v.useRef)(!1),Ir=(0,v.useRef)(!0),Lr=(0,v.useRef)(0),Rr=(0,v.useRef)(0),zr=(0,v.useRef)(null),Br=(0,v.useCallback)(e=>{let t=Tr.current;t!==e&&(t&&Fr.current&&av(Z,{follow:Ir.current,scrollTop:t.scrollTop}),Tr.current=e,Fr.current=!1)},[Z]),Vr=A.principal.displayName||`You`,Hr=Tv(I.role),Ur=(0,v.useMemo)(()=>n.agents.filter(e=>e.lifecycleState===`active`&&e.runtimeProfileId!==null).map(e=>({agentId:e.agentId,definitionId:Nn.find(t=>t.agentId===e.agentId)?.definitionId??null,name:e.name})),[Nn,n.agents]),Wr=(0,v.useMemo)(()=>o.find(e=>e.messageId===Cr)??(C?.messageId===Cr?C:null),[C,o,Cr]),Gr=(0,v.useMemo)(()=>(C&&!o.some(e=>e.messageId===C.messageId)?[...o,C].sort((e,t)=>e.eventPosition-t.eventPosition):o).map(e=>{let t=s.filter(t=>t.threadRootId===e.messageId);return t.length===0?e:{...e,replyCount:e.replyCount+t.length,...P_(e,t),latestReplyAt:t[t.length-1].createdAt}}),[C,o,s]),Kr=(0,v.useCallback)(e=>{if(Nr(e),nt||!Ot||document.visibilityState!==`visible`||st)return;let t=Gr.find(t=>t.messageId===e);t&&_.advanceVisible({channelId:Z,token:d},t)},[nt,n,Z,Gr,Nr,d,Ot,_.advanceVisible]);(0,v.useEffect)(()=>{wr(null),kt(x)},[Z,x]),(0,v.useEffect)(()=>{S?.threadRootId&&wr(S.threadRootId)},[S]),(0,v.useEffect)(()=>{C?.messageId===w&&wr(w)},[C,w]),(0,v.useEffect)(()=>{if(!S||S.threadRootId!==null)return;let e=window.requestAnimationFrame(()=>{Tr.current?.querySelector(`[data-message-id="${S.messageId}"]`)?.scrollIntoView?.({behavior:`smooth`,block:`center`})});return()=>window.cancelAnimationFrame(e)},[Gr.length,S]);let qr=(0,v.useMemo)(()=>{let e=new Map;for(let t of I.channels)for(let n of t.agents)e.set(n.agentId,n);return Array.from(e.values()).sort((e,t)=>e.name.localeCompare(t.name))},[I.channels]),Jr=(0,v.useMemo)(()=>{let e=new Set(Ln.map(e=>e.provisioning.definitionId).filter(e=>e!==null));return Nn.filter(t=>!e.has(t.definitionId)).sort((e,t)=>e.displayName.localeCompare(t.displayName))},[Nn,Ln]),Yr=(0,v.useMemo)(()=>{let e=new Map;for(let t of Fn)t.lifecycleState!==`active`&&t.ownerPrincipalId===A.principal.principalId&&e.set(t.agentId,{entryId:t.agentId,conversationChannelId:null,definitionId:t.definitionId,displayName:t.displayName,handle:t.handle,setupId:null,state:t.lifecycleState===`archived`?`Archived`:`Draft`});for(let t of Ln){let n=Fn.find(e=>e.definitionId===t.provisioning.definitionId);e.set(t.provisioning.agentId??t.provisioning.operationId,{entryId:t.provisioning.operationId,conversationChannelId:null,definitionId:t.provisioning.definitionId,displayName:n?.displayName??t.input.displayName,handle:n?.handle??t.input.handle,setupId:t.provisioning.operationId,state:`Needs attention`})}for(let t of I.channels)if(t.kind===`direct`)for(let n of t.agents){if(n.lifecycleState!==`archived`)continue;let r=e.get(n.agentId);e.set(n.agentId,{entryId:n.agentId,conversationChannelId:t.channelId,definitionId:r?.definitionId??null,displayName:r?.displayName??n.name,handle:r?.handle??n.handle,setupId:r?.setupId??null,state:`Archived`})}return Array.from(e.values()).sort((e,t)=>e.displayName.localeCompare(t.displayName))},[Fn,Ln,A.principal.principalId,I.channels]),Xr=(0,v.useMemo)(()=>I.channels.filter(e=>e.kind===`direct`&&!Cv(e)&&!e.agents.some(e=>e.lifecycleState===`archived`)),[I.channels]),Zr=(0,v.useMemo)(()=>{if(n.kind!==`group`||!$n)return[];let e=new Map;for(let t of n.agents)e.set(t.principalId,{displayName:t.name,handle:t.handle,kind:`agent`,principalId:t.principalId});for(let t of n.participants)t.principalId===A.principal.principalId||t.handle===null||t.kind!==`agent`&&t.kind!==`human`||e.set(t.principalId,{displayName:t.displayName,handle:t.handle,kind:t.kind,principalId:t.principalId});let t=$n.query.trim().toLocaleLowerCase();return Array.from(e.values()).filter(e=>!t||e.handle.toLocaleLowerCase().startsWith(t)||e.displayName.toLocaleLowerCase().startsWith(t)).sort((e,t)=>e.handle.localeCompare(t.handle))},[n,$n,A.principal.principalId]);(0,v.useEffect)(()=>{if(n.kind!==`notification`){ar(null);return}let e=!0;return ir(k).then(t=>{e&&ar(t)}).catch(()=>{e&&ar(null)}),()=>{e=!1}},[n.kind,k]);let Qr=(0,v.useCallback)(e=>{let t=new Set(e.subscriptions.filter(e=>e.lifecycleState===`active`).map(e=>e.agentId)),n=Sr.current;if(n!==null){let t=e.subscriptions.filter(e=>e.lifecycleState===`active`&&!n.has(e.agentId));t.length>0&&xr(`${t.map(e=>e.agentDisplayName).join(`, `)} joined in as ${t.length===1?`a standing participant`:`standing participants`}.`)}Sr.current=t,sr(e)},[]),$r=(0,v.useCallback)(async(e=vr)=>{if(n.kind!==`group`)return null;let t=await Je({channelId:Z,token:d},e);return Qr(t),t},[Qr,n.kind,Z,d,vr]);(0,v.useEffect)(()=>{Sr.current=null,sr(null),xr(null),yr(!1),hr(null),En(!1)},[Z]),(0,v.useEffect)(()=>{if(n.kind!==`group`){sr(null),dr(null);return}let e=!0;return lr(!0),dr(null),Je({channelId:Z,token:d},vr).then(t=>{e&&Qr(t)},t=>{e&&dr(t instanceof Error?t.message:`Could not load standing participation.`)}).finally(()=>{e&&lr(!1)}),()=>{e=!1}},[Qr,n.kind,Z,d,vr,P]);let ei=Gt.at(-1)?.runId??null,{collaborationActivity:ti,entries:ni,failed:ri,loaded:ii}=Ii(ei,N,G);(0,v.useEffect)(()=>{z_(At)},[At]),(0,v.useEffect)(()=>{K_(Pt)},[Pt]),(0,v.useEffect)(()=>{if(n.kind!==`group`)return;let e=window.setInterval(()=>Qn(Date.now()),3e4);return()=>window.clearInterval(e)},[n.kind]);let ai=(0,v.useMemo)(()=>n.kind===`group`?n.agents.filter(e=>{let t=qn[e.agentId]??0,n=t?0:e.engagedUntil?Date.parse(e.engagedUntil):e.engaged?Zn:0;for(let r of o){let i=Date.parse(r.createdAt);!Number.isFinite(i)||i<=t||(r.authorPrincipalId===e.principalId||r.mentions.some(t=>t.kind===`agent`&&t.principalId===e.principalId))&&(n=Math.max(n,i+9e5))}return n>Zn&&n>t}):[],[n.agents,n.kind,qn,Zn,o]),oi=async(e,t=null)=>{if(!Yn){Xn(e),pt(null);try{await ne(e,_v(),t),t===null&&Jn(t=>({...t,[e]:Date.now()})),Qn(Date.now()),$r().catch(()=>void 0)}catch(e){pt(e instanceof Error?e.message:`Could not dismiss this agent.`)}finally{Xn(null)}}},si=async e=>{let t=or;if(!(!t||fr)){pr(!0),hr(null);try{Qr(await Ye({channelId:Z,token:d},e,t.policy.policyVersion,_v()))}catch(e){hr(e instanceof Error?e.message:`Could not update standing participation.`),await $r().catch(()=>void 0)}finally{pr(!1)}}},ci=async(e,t)=>{let n=`${e}:${t.scopeId}`;if(gr===null){_r(n),dr(null);try{Qr(await Xe({channelId:Z,token:d},e,t,_v()))}catch(e){dr(e instanceof Error?e.message:`Could not resume standing observation.`),await $r().catch(()=>void 0)}finally{_r(null)}}},li=(0,v.useCallback)(async()=>{try{let[e,n,r]=await Promise.all([Le(t),He(t),Be(t)]);In(e),Pn(n),Rn(r)}catch(e){throw e instanceof B?he(e.message):e instanceof V&&Ve(e.message),e}},[t,he,Ve]);(0,v.useEffect)(()=>{li().catch(e=>{pt(e instanceof Error?e.message:`Could not load visible agents.`)})},[li]);let ui=(0,v.useCallback)(async()=>{await Promise.all([R(),li()])},[R,li]),di=async()=>{if(!Vn){Hn(!0),pt(null);try{Bn(await He(t))}catch(e){pt(e instanceof Error?e.message:`Could not load available agents.`)}finally{Hn(!1)}}},fi=async()=>{if(!Gn){Kn(!0),pt(null);try{Wn(await ce())}catch(e){pt(e instanceof Error?e.message:`Could not load channel members.`)}finally{Kn(!1)}}},pi=async(e,t,n,r)=>{let i=await me(e,t,n,r);return await ui(),i},mi=async e=>{let t=new Set(n.agents.map(e=>e.agentId)),r=new Set(e);for(let e of t)r.has(e)||await re(e,_v());for(let e of r)t.has(e)||await H(e,_v());await ui(),Bn(null)},hi=async()=>{if(!(n.kind!==`group`||n.role!==`owner`||Sv(n)||kn||!await Ue(`Archive #${rt}? Its history will remain available and you can restore it later.`))){An(Z),pt(null);try{await ee(Z,_v())}catch(e){pt(e instanceof Error?e.message:`Could not archive this channel.`)}finally{An(null)}}},gi=async e=>{if(!kn){An(e),pt(null);try{await ke(e,_v()),bn(!1)}catch(e){pt(e instanceof Error?e.message:`Could not restore this channel.`)}finally{An(null)}}},_i=async()=>{if(!(n.kind!==`direct`||Cv(n)||jn||n.agents.some(e=>e.lifecycleState===`archived`)||!await Ue(`Archive your conversation with ${rt}? Its history will remain available and new activity will return it to Direct messages.`))){Mn(Z),pt(null);try{await z(Z,_v())}catch(e){pt(e instanceof Error?e.message:`Could not archive this direct message.`)}finally{Mn(null)}}},vi=async e=>{if(!jn){Mn(e),pt(null);try{await Ae(e,_v()),Sn(!1)}catch(e){pt(e instanceof Error?e.message:`Could not restore this direct message.`)}finally{Mn(null)}}},yi=async()=>{tn(!1),await Ue(`Forget this browser session? You will need to enroll again.`)&&L()},bi=(e,t)=>{er(Ev(e,t)),nr(0)},xi=e=>{if(!$n)return;let t=`@${e.handle} `,n=ct.slice(0,$n.start)+t+ct.slice($n.end),r=$n.start+t.length;lt(n),rv(Z,n),dt(null),er(null),Dr.current=r};(0,v.useEffect)(()=>{if(!en)return;let e=e=>{Ar.current?.contains(e.target)||tn(!1)},t=e=>{e.key===`Escape`&&tn(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[en]),(0,v.useEffect)(()=>{let e=e=>{e.key.toLocaleLowerCase()===`k`&&(e.metaKey||e.ctrlKey)&&!e.altKey&&(e.preventDefault(),tn(!1),rn(!0))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[]),(0,v.useEffect)(()=>{if(!nn)return;let e=!1;un(!0),fn(null);let t={channelId:Z,token:d};return Promise.all([Se(t),Promise.allSettled(Ur.map(e=>Se(t,e.agentId)))]).then(([t,n])=>{if(e)return;let r=new Map,i=(e,t)=>{if(!e.paletteEntry||e.operationId===`capabilities.discover`||(e.scope===`principal_agent`||e.scope===`agent_owner`)!=(t!==null))return;let n=`${e.operationId}-${t?.agentId??`global`}`;r.set(n,{capability:e,key:n,targetAgentId:t?.agentId??null,targetLabel:t?.name??null})};t.capabilities.forEach(e=>i(e,null)),n.forEach((e,t)=>{if(e.status!==`fulfilled`)return;let n=Ur[t];e.value.capabilities.forEach(e=>i(e,n))}),mn([...r.values()].sort((e,t)=>e.capability.label.localeCompare(t.capability.label)||(e.targetLabel??``).localeCompare(t.targetLabel??``)))}).catch(t=>{if(!e){if(t instanceof B){he(t.message);return}fn(t instanceof Error?t.message:`Could not load available actions.`)}}).finally(()=>{e||un(!1)}),()=>{e=!0}},[nn,Z,d,he,Ur]),(0,v.useEffect)(()=>{let e=!1;Vt([]),zt(null);let t=n.agents.filter(e=>e.lifecycleState===`active`&&e.runtimeProfileId!==null);if(!n.canSubmitCommands||at||t.length===0)return()=>{e=!0};let r=n.kind===`group`?t.map(e=>e.agentId):[null];return Promise.all(r.map(e=>K(e))).then(t=>{e||Vt(t)}).catch(t=>{e||zt(t instanceof Error?t.message:`Could not load runtime status.`)}),()=>{e=!0}},[n.agents,n.canSubmitCommands,n.kind,Z,at,K,Kt,nt]);let Si=async e=>{if(!(!Zt||Zt.workspaceMode===`neutral`||Zt.workspaceRevision===null||e===Zt.workspace)){zt(null),$t(!0);try{let t=await Re(e,Zt.workspaceRevision);Vt(e=>e.map(e=>({...e,workspace:t.workspace,workspaceLabel:t.workspaces.find(e=>e.current)?.name??e.workspaceLabel,workspaceRevision:t.revision,workspaces:t.workspaces}))),xt({})}catch(e){zt(e instanceof Error?e.message:`Could not switch workspace.`)}finally{$t(!1)}}},Ci=async e=>{if(!(qt!==null||e.activeRun!==null||!await Ue(`Start a fresh provider session for ${e.agentName}? This ends only this channel-and-agent provider session and its live process. Conversation history, messages, memories, settings, and this browser's enrollment are preserved.`))){Jt(e.agentId),Xt(null),zt(null);try{let t=await q(e.agentId,_v()),n=await K(e.agentId);Vt(t=>t.map(t=>t.agentId===e.agentId?n:t)),xt(t=>Object.fromEntries(Object.entries(t).filter(([,t])=>t.agentId!==e.agentId))),Xt(`Fresh provider session ready for ${e.agentName}. Revision ${t.revision.slice(0,12)}.`)}catch(e){zt(e instanceof Error?e.message:`Could not start a fresh provider session.`)}finally{Jt(null)}}},wi=async e=>{let{operationId:t}=e.capability;if(t===`workspace.catalogue.manage`)return X(),null;if(t===`memory.manage`)return _e(),null;if(t===`scheduled_jobs.manage`)return ge(),null;if(t===`integration.github.manage`)return Oe(`github`),null;if(t===`integration.github.review`)return rn(!1),on(!0),null;if(t===`administration.webhook_status.read`)return Oe(`administration`),null;if(t===`runtime.model.manage`||t===`runtime.backend.manage`){let t=Ur.find(t=>t.agentId===e.targetAgentId);if(!t?.definitionId)throw Error(`This agent's runtime settings are not available.`);return je(t.definitionId,`runtime`),null}if(t===`runtime.status.read`){if(!e.targetAgentId)throw Error(`Select an agent to inspect its runtime.`);return rn(!1),nt&&await Ne(Z),gn(t=>({agentId:e.targetAgentId,key:t.key+1})),null}if(t===`conversation.session.reset`){if(!e.targetAgentId)throw Error(`Select an agent to start a fresh session.`);let t=await K(e.targetAgentId);if(t.activeRun!==null)throw Error(`${t.agentName} has an active run. Stop it before starting a fresh session.`);return rn(!1),await Ci(t),null}throw Error(`This action does not yet have a native Workshop interaction.`)};(0,v.useLayoutEffect)(()=>{let e=Er.current;if(!e)return;let t=e.offsetHeight-e.clientHeight;if(e.style.height=`auto`,e.style.height=`${e.scrollHeight+t}px`,Dr.current!==null){let t=Dr.current;Dr.current=null,e.focus(),e.setSelectionRange(t,t)}},[ct,Z]),(0,v.useEffect)(()=>{if(!Mt)return;let e=()=>Nt(!1);return window.addEventListener(`pointerup`,e,{once:!0}),window.addEventListener(`pointercancel`,e,{once:!0}),()=>{window.removeEventListener(`pointerup`,e),window.removeEventListener(`pointercancel`,e)}},[Mt]),(0,v.useEffect)(()=>{if(!It)return;let e=()=>Lt(!1);return window.addEventListener(`pointerup`,e,{once:!0}),window.addEventListener(`pointercancel`,e,{once:!0}),()=>{window.removeEventListener(`pointerup`,e),window.removeEventListener(`pointercancel`,e)}},[It]);let Ti=e=>{At.collapsed||(e.currentTarget.setPointerCapture(e.pointerId),jr.current={pointerX:e.clientX,width:At.width},Nt(!0))},Ei=e=>{if(!Mt)return;let t=e.clientX-jr.current.pointerX;jt(e=>({...e,width:L_(jr.current.width+t)}))},Oi=e=>{let t=e.key===`ArrowLeft`?-1:+(e.key===`ArrowRight`);(t!==0||e.key===`Home`||e.key===`End`)&&(e.preventDefault(),jt(n=>({collapsed:!1,width:e.key===`Home`?O_:e.key===`End`?A_:L_(n.width+t*16*D_)})))},ki=()=>{jt(e=>({...e,collapsed:!e.collapsed}))},Ai=e=>{e.currentTarget.setPointerCapture(e.pointerId),Mr.current={pointerX:e.clientX,width:Pt},Lt(!0)},ji=e=>{if(!It)return;let t=Mr.current.pointerX-e.clientX;Ft(W_(Mr.current.width+t))},Mi=e=>{let t=e.key===`ArrowLeft`?1:e.key===`ArrowRight`?-1:0;(t!==0||e.key===`Home`||e.key===`End`)&&(e.preventDefault(),Ft(n=>e.key===`Home`?V_:e.key===`End`?U_:W_(n+t*16*D_)))};(0,v.useEffect)(()=>{xt({}),yt(new Set);let e=ev(Z);if(e.length===0)return;let t=!1;return Promise.allSettled(e.map(e=>ue(e))).then(e=>{if(!t){let t=e.flatMap(e=>e.status===`fulfilled`&&e.value.channelId===Z?[e.value]:[]);xt(Object.fromEntries(t.map(e=>[e.runId,e]))),e.some(e=>e.status===`rejected`)&&pt(`Could not restore every active agent run.`)}}),()=>{t=!0}},[Z,ue]),(0,v.useEffect)(()=>{j.length!==0&&xt(e=>{let t={...e};for(let e of j)e.run.channelId===Z&&(t[e.run.runId]=e.run);return t})},[Z,j]),(0,v.useEffect)(()=>{tv(Z,Ut.map(e=>e.runId))},[Ut,Z]),(0,v.useEffect)(()=>{if(Ut.length===0)return;Ct(Date.now());let e=window.setInterval(()=>Ct(Date.now()),1e3);return()=>window.clearInterval(e)},[Ut.length]),(0,v.useLayoutEffect)(()=>{let e=Tr.current;if(!e)return;Pr.current!==Z&&(Pr.current=Z,Fr.current=!1,Ir.current=!0,Lr.current=0,Rr.current=0,zr.current=null,Tt(0),Dt(!1));let t=o.reduce((e,t)=>Math.max(e,t.eventPosition),0),n=o[0]?.eventPosition??0;if(!Fr.current){if(o.length===0)return;let r=b?e.querySelector(`[data-message-id="${b}"]`):null,i=r?null:iv(Z);r?r.scrollIntoView?.({block:`start`}):e.scrollTop=i?.follow===!1?Math.min(i.scrollTop,e.scrollHeight):e.scrollHeight,Fr.current=!0,Ir.current=r?sv(e):i?.follow??!0,av(Z,{follow:Ir.current,scrollTop:e.scrollTop}),Dt(!sv(e)),Lr.current=t,Rr.current=n,Tt(0);return}let r=zr.current;r&&o.length>0&&ne.eventPosition>Lr.current).length;Lr.current=Math.max(Lr.current,t),i!==0&&(Ir.current?(e.scrollTop=e.scrollHeight,av(Z,{follow:!0,scrollTop:e.scrollTop}),Tt(0)):Tt(e=>e+i))},[nt,Z,o,b]),(0,v.useLayoutEffect)(()=>{let e=Tr.current;!e||!Fr.current||!Ir.current||(e.scrollTop=e.scrollHeight,av(Z,{follow:!0,scrollTop:e.scrollTop}))},[Z,ct,M]);let Ni=()=>{let e=Tr.current;if(!e||!Fr.current)return;kt(!0);let t=sv(e);Ir.current=t,Dt(!t),av(Z,{follow:t,scrollTop:e.scrollTop}),t&&Tt(0)},Pi=()=>{let e=Tr.current;if(e){if(Ir.current=!0,a.available){oe(),av(Z,{follow:!0,scrollTop:e.scrollTop}),Tt(0),Dt(!1);return}e.scrollTop=e.scrollHeight,av(Z,{follow:!0,scrollTop:e.scrollTop}),Tt(0),Dt(!1)}},Li=()=>{let e=Tr.current;e&&(zr.current={scrollHeight:e.scrollHeight,scrollTop:e.scrollTop}),ie()};(0,v.useEffect)(()=>{i.error&&(zr.current=null)},[i.error]);let Ri=async e=>{e.preventDefault();let t=ct.trim();if(!(!t&&!gt||mt||Wt.length>0)){pt(null),ht(!0);try{let e=ut??_v();dt(e);let n=await Fe(e,t,gt,null);lt(``),rv(Z,``),dt(null),_t(null),Or.current&&(Or.current.value=``),n.runs.length>0&&xt(e=>{let t={...e};for(let e of n.runs)e.runId in t||(t[e.runId]=e);return t})}catch(e){pt(e instanceof Error?e.message:`Kai could not run this command.`)}finally{ht(!1)}}},zi=async e=>{let t=e.filter(e=>ov(e)&&!vt.has(e.runId));if(t.length!==0){pt(null),yt(e=>new Set([...e,...t.map(e=>e.runId)]));try{let e=await Promise.allSettled(t.map(e=>te(e.runId))),n=e.flatMap(e=>e.status===`fulfilled`?[e.value]:[]);n.length>0&&xt(e=>({...e,...Object.fromEntries(n.map(e=>[e.runId,e]))}));let r=e.filter(e=>e.status===`rejected`);r.length>0&&pt(r.length===t.length?`Could not stop the selected agent run.`:`Stopped ${n.length} agent ${n.length===1?`run`:`runs`}; ${r.length} could not be stopped.`)}finally{let e=new Set(t.map(e=>e.runId));yt(t=>new Set([...t].filter(t=>!e.has(t))))}}},Bi=e=>zi([e]),Vi=()=>zi(Wt);return(0,Q.jsxs)(`main`,{className:`workshop-app ${Ge?`agents-open`:``} ${Ke?`workspaces-open`:``} ${qe?`scheduled-jobs-open`:``} ${Ze?`memory-open`:``} ${Qe?`mentions-open`:``} ${$e?`following-open`:``} ${et?`reviews-open`:``} ${tt?`settings-open`:``} ${At.collapsed?`sidebar-collapsed`:``} ${Mt||It?`pane-resizing`:``}`,style:{"--channel-sidebar-width":`${At.collapsed?j_:At.width}px`,"--context-pane-width":`${Pt}px`},children:[(0,Q.jsxs)(`aside`,{ref:kr,className:`channel-sidebar ${At.collapsed?`collapsed`:``}`,"aria-label":`Workshop navigation`,children:[(0,Q.jsxs)(`header`,{className:`sidebar-header`,children:[(0,Q.jsx)(`div`,{className:`sidebar-title`,children:(0,Q.jsx)(`p`,{className:`overline`,children:`Kai Workshop`})}),(0,Q.jsx)(`div`,{className:`sidebar-header-actions`,children:(0,Q.jsx)(`button`,{className:`sidebar-toggle`,type:`button`,"aria-label":At.collapsed?`Expand navigation`:`Collapse navigation`,"aria-expanded":!At.collapsed,title:At.collapsed?`Expand navigation`:`Collapse navigation`,onClick:ki,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:At.collapsed?`›`:`‹`})})})]}),(0,Q.jsxs)(`nav`,{children:[!At.collapsed&&(0,Q.jsxs)(`div`,{className:`nav-heading-row`,children:[(0,Q.jsx)(`p`,{className:`nav-heading`,children:`Channels`}),(0,Q.jsxs)(`div`,{className:`nav-heading-actions`,children:[(0,Q.jsx)(`button`,{className:`nav-tool-button`,type:`button`,"aria-label":`Archived channels`,title:`Archived channels`,onClick:()=>bn(!0),children:(0,Q.jsx)(Gv,{})}),(0,Q.jsx)(`button`,{className:`nav-add-button`,type:`button`,"aria-label":`Create channel`,title:`Create channel`,onClick:()=>vn({initialAgentIds:[],originChannelId:null,originName:null}),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`})})]})]}),I.channels.filter(e=>e.kind===`group`&&!Sv(e)).map(e=>{let t=xv(_.byChannel[e.channelId]),n=g.counts.unreadByChannel[e.channelId]??0;return(0,Q.jsxs)(`button`,{className:`channel-link ${t>0?`unread`:``} ${!nt&&e.channelId===Z?`active`:``}`,type:`button`,"aria-label":`${vv(e)}${bv(_.byChannel[e.channelId])}${n>0?`, ${n} unread mentions`:``}`,title:vv(e),onClick:()=>Ne(e.channelId),children:[(0,Q.jsx)(`span`,{children:yv(e)}),(0,Q.jsx)(`span`,{children:vv(e)}),(t>0||n>0||!nt&&e.channelId===Z)&&(0,Q.jsxs)(`span`,{className:`channel-link-status`,children:[t>0&&(0,Q.jsx)(`span`,{className:`unread-pip`,"aria-hidden":`true`}),n>0&&(0,Q.jsx)(`span`,{className:`mention-count`,"aria-label":`${n} unread mentions`,children:n>99?`99+`:n}),!nt&&e.channelId===Z&&(0,Q.jsx)(`span`,{className:`live-pip`,"aria-label":`Live`})]})]},e.channelId)}),!At.collapsed&&(0,Q.jsxs)(`div`,{className:`nav-heading-row`,children:[(0,Q.jsx)(`p`,{className:`nav-heading`,children:`Direct messages`}),(0,Q.jsxs)(`div`,{className:`nav-heading-actions`,children:[(0,Q.jsx)(`button`,{className:`nav-tool-button`,type:`button`,"aria-label":`Archived direct messages`,title:`Archived direct messages`,onClick:()=>Sn(!0),children:(0,Q.jsx)(Gv,{})}),(0,Q.jsx)(`button`,{className:`nav-add-button`,type:`button`,"aria-label":`Start direct message`,title:`Start direct message`,onClick:()=>On(!0),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`})})]})]}),Xr.map(e=>{let t=xv(_.byChannel[e.channelId]),n=e.agents.length===0?e.participants.find(e=>e.kind===`human`):void 0,r=!n&&e.agents.length===1?e.agents[0]:void 0;return(0,Q.jsxs)(`button`,{className:`channel-link ${t>0?`unread`:``} ${!nt&&e.channelId===Z?`active`:``}`,type:`button`,"aria-label":`${vv(e)}${bv(_.byChannel[e.channelId])}`,title:vv(e),onClick:()=>Ne(e.channelId),children:[n?(0,Q.jsx)(Kh,{avatar:n.avatar??N_,className:`channel-human-avatar`,displayName:n.displayName,principalId:n.principalId}):r?(0,Q.jsx)(`span`,{className:`channel-agent-avatar`,"aria-hidden":`true`,children:r.name.slice(0,1).toUpperCase()}):(0,Q.jsx)(`span`,{children:yv(e)}),(0,Q.jsx)(`span`,{children:vv(e)}),(t>0||!nt&&e.channelId===Z)&&(0,Q.jsxs)(`span`,{className:`channel-link-status`,children:[t>0&&(0,Q.jsx)(`span`,{className:`unread-pip`,"aria-hidden":`true`}),!nt&&e.channelId===Z&&(0,Q.jsx)(`span`,{className:`live-pip`,"aria-label":`Live`})]})]},e.channelId)}),(0,Q.jsx)(`p`,{className:`nav-heading`,children:`Activity`}),I.channels.filter(e=>e.kind===`notification`).map(e=>{let t=xv(_.byChannel[e.channelId]);return(0,Q.jsxs)(`button`,{className:`channel-link notification ${t>0?`unread`:``} ${!nt&&e.channelId===Z?`active`:``}`,type:`button`,"aria-label":`${vv(e)}${bv(_.byChannel[e.channelId])}`,title:vv(e),onClick:()=>Ne(e.channelId),children:[(0,Q.jsx)(`span`,{children:`!`}),(0,Q.jsx)(`span`,{children:vv(e)}),(t>0||!nt&&e.channelId===Z)&&(0,Q.jsxs)(`span`,{className:`channel-link-status`,children:[t>0&&(0,Q.jsx)(`span`,{className:`unread-pip`,"aria-hidden":`true`}),!nt&&e.channelId===Z&&(0,Q.jsx)(`span`,{className:`live-pip`,"aria-label":`Live`})]})]},e.channelId)}),(0,Q.jsxs)(`button`,{className:`channel-link mentions-link ${Qe?`active`:``}`,type:`button`,"aria-label":`Mentions${g.counts.unread>0?`, ${g.counts.unread} unread`:``}`,title:`Mentions`,onClick:ve,children:[(0,Q.jsx)(`span`,{className:`workspace-nav-icon mentions-nav-icon`,"aria-hidden":`true`,children:`@`}),(0,Q.jsx)(`span`,{children:`Mentions`}),(g.counts.unread>0||Qe)&&(0,Q.jsxs)(`span`,{className:`channel-link-status`,children:[g.counts.unread>0&&(0,Q.jsx)(`span`,{className:`mention-count`,"aria-hidden":`true`,children:g.counts.unread>99?`99+`:g.counts.unread}),Qe&&(0,Q.jsx)(`span`,{className:`live-pip`,"aria-label":`Open`})]})]}),(0,Q.jsxs)(`button`,{className:`channel-link following-link ${$e?`active`:``}`,type:`button`,"aria-label":`Following${h.totalUnread>0?`, ${h.totalUnread} unread`:``}`,title:`Following`,onClick:ye,children:[(0,Q.jsx)(`span`,{className:`workspace-nav-icon following-nav-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(Hv,{followed:!1})}),(0,Q.jsx)(`span`,{children:`Following`}),(h.totalUnread>0||$e)&&(0,Q.jsxs)(`span`,{className:`channel-link-status`,children:[h.totalUnread>0&&(0,Q.jsx)(`span`,{className:`mention-count`,"aria-hidden":`true`,children:h.totalUnread>99?`99+`:h.totalUnread}),$e&&(0,Q.jsx)(`span`,{className:`live-pip`,"aria-label":`Open`})]})]}),(0,Q.jsxs)(`button`,{className:`channel-link reviews-link ${et?`active`:``}`,type:`button`,"aria-label":`Reviews`,title:`Reviews`,onClick:be,children:[(0,Q.jsx)(`span`,{className:`workspace-nav-icon reviews-nav-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(Xv,{})}),(0,Q.jsx)(`span`,{children:`Reviews`}),et&&(0,Q.jsx)(`span`,{className:`channel-link-status`,children:(0,Q.jsx)(`span`,{className:`live-pip`,"aria-label":`Open`})})]}),!At.collapsed&&(0,Q.jsxs)(`div`,{className:`nav-heading-row`,children:[(0,Q.jsx)(`p`,{className:`nav-heading`,children:`Agents`}),(0,Q.jsxs)(`div`,{className:`nav-heading-actions`,children:[Yr.length>0&&(0,Q.jsx)(`button`,{className:`nav-tool-button`,type:`button`,"aria-label":`Your drafts and archived agents`,title:`Your drafts and archived agents`,onClick:()=>wn(!0),children:(0,Q.jsx)(Gv,{})}),(0,Q.jsx)(`button`,{className:`nav-add-button`,type:`button`,"aria-label":`Create agent`,title:`Create agent`,onClick:we,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`})})]})]}),Jr.map(t=>{let n=ai.some(e=>e.agentId===t.agentId),r=Ge&&e?.definitionId===t.definitionId;return(0,Q.jsxs)(`button`,{className:`agent-link ${n?`engaged`:``} ${r?`active`:``}`,type:`button`,title:`Manage ${t.displayName}`,"aria-label":`Manage ${t.displayName}`,onClick:()=>void Te(t.definitionId),children:[(0,Q.jsx)(`span`,{className:`mini-avatar`,children:t.displayName.slice(0,1).toUpperCase()}),(0,Q.jsx)(`span`,{children:(0,Q.jsx)(`strong`,{children:t.displayName})}),r&&(0,Q.jsx)(`span`,{className:`live-pip`,"aria-label":`Open`})]},t.definitionId)})]}),(0,Q.jsxs)(`footer`,{ref:Ar,className:`sidebar-footer ${Ke||qe||Ze||tt?`active`:``}`,children:[en&&(0,Q.jsxs)(`div`,{className:`profile-menu`,role:`menu`,"aria-label":`Your Kai menu`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Your Kai`}),(0,Q.jsxs)(`button`,{type:`button`,role:`menuitem`,"aria-current":Ke?`page`:void 0,onClick:()=>{tn(!1),X()},children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(Jv,{})}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Workspaces`}),(0,Q.jsx)(`small`,{children:`Authorized directories`})]})]}),(0,Q.jsxs)(`button`,{type:`button`,role:`menuitem`,"aria-current":qe?`page`:void 0,onClick:()=>{tn(!1),ge()},children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(Yv,{})}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Scheduled jobs`}),(0,Q.jsx)(`small`,{children:`Upcoming and recurring work`})]})]}),(0,Q.jsxs)(`button`,{type:`button`,role:`menuitem`,"aria-current":Ze?`page`:void 0,onClick:()=>{tn(!1),_e()},children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`◇`}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Memory`}),(0,Q.jsx)(`small`,{children:`Facts and episodes`})]})]}),(0,Q.jsxs)(`button`,{type:`button`,role:`menuitem`,"aria-current":tt?`page`:void 0,onClick:()=>{tn(!1),Oe()},children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`⚙`}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Settings`}),(0,Q.jsx)(`small`,{children:`Profile and preferences`})]})]}),(0,Q.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{tn(!1),rn(!0)},children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`?`}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Help and actions`}),(0,Q.jsx)(`small`,{children:`Search available operations · ⌘/Ctrl-K`})]})]}),(0,Q.jsx)(`div`,{className:`profile-menu-separator`}),(0,Q.jsxs)(`button`,{className:`forget-session-menu-item`,type:`button`,role:`menuitem`,onClick:()=>void yi(),children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`↪`}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:`Forget session`}),(0,Q.jsx)(`small`,{children:`Enroll this browser again`})]})]})]}),(0,Q.jsxs)(`button`,{className:`profile-trigger`,type:`button`,"aria-haspopup":`menu`,"aria-expanded":en,"aria-label":`${Vr} profile`,title:`${Vr} — ${Hr}`,onClick:()=>tn(e=>!e),children:[(0,Q.jsx)(Kh,{avatar:A.principal.avatar??N_,className:`mini-avatar human`,displayName:Vr,principalId:A.principal.principalId}),(0,Q.jsxs)(`span`,{className:`profile-copy`,children:[(0,Q.jsx)(`strong`,{children:Vr}),(0,Q.jsx)(`small`,{children:Hr})]}),(0,Q.jsx)(`span`,{className:`profile-chevron`,"aria-hidden":`true`,children:`⌃`})]})]}),!At.collapsed&&(0,Q.jsx)(`div`,{className:`sidebar-resize-handle`,role:`separator`,"aria-label":`Resize navigation`,"aria-orientation":`vertical`,"aria-valuemin":O_,"aria-valuemax":A_,"aria-valuenow":At.width,tabIndex:0,onKeyDown:Oi,onPointerDown:Ti,onPointerMove:Ei})]}),Ge&&e?(0,Q.jsx)(Ug,{activeChannelId:Z,initialCreating:e.creating,initialDefinitionId:e.definitionId,initialSetupId:e.setupId,initialSection:e.section,isAdministrator:I.role===`admin`,onAuthenticationFailure:he,onChannelAccessFailure:Ve,onClose:()=>Ne(Z),onCreateAgent:we,onNavigationChanged:ui,onOpenChannel:De,onSelectAgent:je,principalId:A.principal.principalId,principalName:Vr,principalEvents:y,runActive:Wt.length>0,token:t,workshopName:I.name}):Ke?(0,Q.jsx)(Fh,{detailPanelLayout:{maximumWidth:U_,minimumWidth:V_,onKeyDown:Mi,onPointerDown:Ai,onPointerMove:ji,width:Pt},onAuthenticationFailure:he,onChannelAccessFailure:Ve,onClose:()=>Ne(Z),session:k}):qe?(0,Q.jsx)(Vh,{detailPanelLayout:{maximumWidth:U_,minimumWidth:V_,onKeyDown:Mi,onPointerDown:Ai,onPointerMove:ji,width:Pt},onAuthenticationFailure:he,onClose:()=>Ne(Z),principalEvents:y,session:k}):tt?(0,Q.jsx)(hg,{initialSection:D,onAuthenticationFailure:he,onChannelAccessFailure:Ve,onClose:()=>Ne(Z),onDirtyChange:ze,onHumanAvatarChanged:We,onNavigationChanged:R,isAdministrator:I.role===`admin`,principalName:Vr,roleLabel:Hr,runtimeLabel:O,runActive:Wt.length>0,session:k}):u?(0,Q.jsx)(kh,{detailPanelLayout:{maximumWidth:U_,minimumWidth:V_,onKeyDown:Mi,onPointerDown:Ai,onPointerMove:ji,width:Pt},initialMemoryId:u.memoryId,onAuthenticationFailure:he,onClose:()=>Ne(Z),onSelectMemory:Me,token:d}):Qe?(0,Q.jsx)(qg,{connection:r,inbox:g,onOpen:Ce,workshopName:I.name}):$e?(0,Q.jsx)(Xg,{connection:r,following:h,onOpen:xe,workshopName:I.name}):et?(0,Q.jsx)(t_,{connection:r,onAuthenticationFailure:he,onChannelAccessFailure:Ve,onReviewPullRequest:()=>on(!0),revision:sn,session:k,workshopName:I.name}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`section`,{className:`conversation-pane`,children:[(0,Q.jsxs)(`header`,{className:`conversation-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`p`,{className:`breadcrumbs`,children:[I.name,` / `,n.kind===`notification`?`Activity`:n.kind===`direct`?`Direct messages`:`Channels`]}),(0,Q.jsxs)(`h2`,{children:[it,` `,rt]})]}),(0,Q.jsxs)(`div`,{className:`conversation-actions`,children:[(0,Q.jsx)(fv,{connection:r}),(0,Q.jsx)(`button`,{className:`quiet-button mobile-settings-button`,type:`button`,onClick:()=>Oe(),children:`Settings`})]})]}),(0,Q.jsxs)(`div`,{ref:Br,className:`timeline-wrap`,"aria-label":`Conversation timeline`,onScroll:Ni,onPointerDown:()=>kt(!0),onKeyDown:()=>kt(!0),tabIndex:0,children:[(0,Q.jsxs)(`div`,{className:`channel-introduction ${n.kind===`notification`?`notification`:``}`,children:[(0,Q.jsx)(`span`,{className:`channel-symbol`,children:it}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`overline`,children:n.kind===`notification`?`Durable notification feed`:n.kind===`direct`?`Direct conversation`:`Canonical conversation`}),(0,Q.jsx)(`h3`,{children:at?`Conversation with ${rt}`:`Welcome to ${rt}`}),(0,Q.jsx)(`p`,{children:Sv(n)?`This channel is archived. Its history remains available, but it is read-only until restored.`:ot?`This direct message is archived for you. Its history remains available, but it is read-only until restored.`:n.kind===`notification`?`Authenticated GitHub activity appears here live and is delivered to every configured client.`:at?`Messages here are private to you and ${rt}.`:`Messages below come from ${rt}’s durable conversation history across every connected client.`}),n.kind===`notification`&&rr&&(0,Q.jsxs)(`p`,{className:`notification-routing-summary`,children:[`Active delivery: `,rr.preferences.map(e=>`${e.displayName} → ${e.destinationName}`).join(` · `)]})]})]}),i.available&&(0,Q.jsxs)(`div`,{className:`timeline-earlier`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`timeline-earlier-button`,onClick:Li,disabled:i.loading,children:i.loading?`Loading earlier messages…`:`Load earlier messages`}),i.error&&(0,Q.jsx)(`p`,{className:`timeline-earlier-error`,children:i.error})]}),T&&(0,Q.jsxs)(`p`,{className:`source-navigation-error`,role:`alert`,children:[T,` You can return to Mentions and update its read state there.`]}),Gr.length===0?(0,Q.jsx)(`p`,{className:`empty-timeline`,children:`No messages yet. New activity will appear here.`}):(0,Q.jsxs)(`ol`,{className:`message-list ${n.kind===`notification`?`notification-feed`:``}`,"aria-live":`polite`,children:[Gr.map(e=>(0,Q.jsxs)(v.Fragment,{children:[b===e.messageId&&(0,Q.jsx)(`li`,{className:`first-unread-divider`,role:`separator`,"aria-label":`First unread message`,children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`New messages`})}),(0,Q.jsx)(mv,{hasUnreadReplies:_.byChannel[n.channelId]?.firstUnreadThreadRootId===e.messageId,highlighted:S?.messageId===e.messageId,message:e,notification:n.kind===`notification`,onDownloadArtifact:W,onLoadArtifact:se,onLoadReactors:Y,onMessageVisible:Kr,onSetReaction:st?void 0:Pe,onOpenThread:(n.kind===`group`||at)&&!st?wr:void 0})]},e.messageId)),n.kind!==`notification`&&!at&&[...M].sort((e,t)=>e.sequence-t.sequence||e.runId.localeCompare(t.runId)).map(e=>{let t=n.agents.find(t=>t.agentId===e.agentId)?.name??`Agent`;return(0,Q.jsxs)(`li`,{className:`message-row agent run-preview`,children:[(0,Q.jsx)(`span`,{className:`message-avatar`,"aria-hidden":`true`,children:t.slice(0,1).toUpperCase()}),(0,Q.jsxs)(`article`,{children:[(0,Q.jsxs)(`header`,{className:`message-meta`,children:[(0,Q.jsx)(`strong`,{children:t}),(0,Q.jsx)(`span`,{className:`run-preview-label`,children:`writing`})]}),(0,Q.jsx)(Nm,{body:e.text})]})]},e.runId)})]}),a.available&&(0,Q.jsxs)(`div`,{className:`timeline-later`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`timeline-earlier-button`,onClick:ae,disabled:a.loading,children:a.loading?`Loading newer messages…`:`Load newer messages`}),a.error&&(0,Q.jsx)(`p`,{className:`timeline-earlier-error`,children:a.error})]})]}),(0,Q.jsxs)(`footer`,{className:`composer-preview`,children:[(Et||wt>0)&&(0,Q.jsx)(`button`,{className:`new-messages-button`,type:`button`,onClick:Pi,"aria-label":wt>0?void 0:`Jump to latest messages`,children:wt===0?`Jump to latest`:wt===1?`1 new message`:`${wt} new messages`}),n.canSubmitCommands?(0,Q.jsxs)(`form`,{className:`composer-form`,onSubmit:e=>void Ri(e),children:[(0,Q.jsx)(`input`,{ref:Or,className:`artifact-input`,type:`file`,"aria-label":`Attach a file`,onChange:e=>{_t(e.target.files?.[0]??null),dt(null)}}),(0,Q.jsx)(`button`,{className:`attach-button composer-icon-button`,type:`button`,"aria-label":`Attach`,title:`Attach a file`,disabled:mt||Wt.length>0,onClick:()=>Or.current?.click(),children:(0,Q.jsx)(Fv,{})}),(0,Q.jsx)(`textarea`,{ref:Er,"aria-label":`Message ${rt}`,disabled:mt||Wt.length>0,value:ct,onChange:e=>{let t=e.target.value;lt(t),rv(Z,t),bi(t,e.target.selectionStart??t.length),mt||dt(null)},onKeyDown:e=>{if(e.key===`/`&&ct.length===0&>===null&&!e.metaKey&&!e.ctrlKey&&!e.altKey){e.preventDefault(),rn(!0);return}if($n&&Zr.length>0){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let t=e.key===`ArrowDown`?1:-1;nr(e=>(e+t+Zr.length)%Zr.length);return}if(e.key===`Escape`){e.preventDefault(),er(null);return}if(e.key===`Tab`||e.key===`Enter`&&!e.shiftKey){e.preventDefault(),xi(Zr[Math.min(tr,Zr.length-1)]);return}}e.key!==`Enter`||e.shiftKey||e.nativeEvent.isComposing||e.nativeEvent.keyCode===229||(e.preventDefault(),e.currentTarget.form?.requestSubmit())},maxLength:5e4,placeholder:`Message ${rt}…`,rows:1}),$n&&Zr.length>0&&(0,Q.jsx)(`div`,{className:`mention-autocomplete`,role:`listbox`,"aria-label":`Channel members`,children:Zr.map((e,t)=>(0,Q.jsxs)(`button`,{className:t===tr?`selected`:``,type:`button`,role:`option`,"aria-label":`@${e.handle} — ${e.displayName} — ${e.kind}`,"aria-selected":t===tr,onMouseDown:e=>e.preventDefault(),onClick:()=>xi(e),children:[(0,Q.jsxs)(`strong`,{children:[`@`,e.handle]}),(0,Q.jsxs)(`span`,{children:[e.displayName,` · `,e.kind]})]},e.principalId))}),Wt.length>0?(0,Q.jsx)(`button`,{className:`stop-button composer-icon-button`,type:`button`,"aria-busy":Wt.every(e=>vt.has(e.runId)),"aria-label":Wt.length===1?`Stop agent run`:`Stop all agent runs`,title:Wt.length===1?`Stop agent run`:`Stop all agent runs`,disabled:Wt.every(e=>vt.has(e.runId)),onClick:()=>void Vi(),children:(0,Q.jsx)(Lv,{})}):(0,Q.jsx)(`button`,{className:`send-button composer-icon-button`,type:`submit`,"aria-busy":mt,"aria-label":mt?`Sending…`:`Send`,title:mt?`Sending…`:`Send`,disabled:mt||!ct.trim()&&!gt,children:(0,Q.jsx)(Iv,{})})]}):(0,Q.jsx)(`p`,{className:`read-only-channel-notice`,children:n.kind===`notification`?`This channel is outbound-only. Kai records delivery here, but it does not accept conversation commands.`:ot?`This direct message is archived for you. Restore it to send messages.`:n.kind===`direct`&&n.agents.some(e=>e.lifecycleState===`archived`)?`This agent has been archived. This conversation is read-only.`:`Sending messages from Workshop is not available for this conversation yet.`}),ft&&(0,Q.jsx)(`p`,{className:`composer-error`,role:`alert`,children:ft}),gt&&(0,Q.jsxs)(`div`,{className:`selected-artifact`,children:[(0,Q.jsx)(`span`,{children:gt.name}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>{_t(null),dt(null),Or.current&&(Or.current.value=``)},children:`Remove`})]})]})]}),(0,Q.jsxs)(`aside`,{className:`context-pane`,"aria-label":`Channel context`,children:[(0,Q.jsx)(`div`,{className:`context-resize-handle`,role:`separator`,"aria-label":`Resize channel context`,"aria-orientation":`vertical`,"aria-valuemin":V_,"aria-valuemax":U_,"aria-valuenow":Pt,tabIndex:0,onKeyDown:Mi,onPointerDown:Ai,onPointerMove:ji}),Wr?(0,Q.jsx)(ry,{activeStandingAgentIds:(or?.subscriptions??[]).filter(e=>e.lifecycleState===`active`).map(e=>e.agentId),channelName:rt,liveMessages:s,focusedMessage:S,onClose:()=>wr(null),onDownloadArtifact:W,onLoadArtifact:se,onLoadThread:de,onLoadThreadUnread:J,onLoadReactors:Y,onMessageVisible:Nr,onAdvanceThreadRead:fe,onSetThreadFollowed:pe,onSuppressStanding:(e,t)=>oi(e,t),onSetReaction:Pe,onSubmitCommand:Fe,reactionUpdates:F,principalEvents:y,readOnly:st,rootMessage:Wr,runActive:Wt.length>0}):(0,Q.jsxs)(`div`,{className:`context-scroll`,children:[(0,Q.jsx)(`header`,{className:`context-channel-header`,children:(0,Q.jsxs)(`div`,{className:`context-channel-heading`,children:[(0,Q.jsx)(`p`,{className:`overline`,children:`Channel context`}),(0,Q.jsxs)(`div`,{className:`context-channel-title-row`,children:[(0,Q.jsxs)(`h2`,{children:[it,` `,rt]}),n.kind===`group`&&(!Sv(n)||n.role===`owner`)&&(0,Q.jsxs)(`div`,{className:`context-channel-actions`,children:[!Sv(n)&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Channel settings`,title:`Channel settings`,onClick:()=>En(!0),children:(0,Q.jsx)(Uv,{})}),n.role===`owner`&&(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":Sv(n)?`Restore channel`:`Archive channel`,title:Sv(n)?`Restore channel`:`Archive channel`,disabled:kn!==null||Wt.length>0,onClick:()=>void(Sv(n)?gi(Z):hi()),children:Sv(n)?(0,Q.jsx)(Kv,{}):(0,Q.jsx)(Gv,{})})]}),n.kind===`direct`&&!n.agents.some(e=>e.lifecycleState===`archived`)&&(0,Q.jsx)(`div`,{className:`context-channel-actions`,children:(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":ot?`Restore direct message`:`Archive direct message`,title:ot?`Restore direct message`:`Archive direct message`,disabled:jn!==null||Wt.length>0,onClick:()=>void(ot?vi(Z):_i()),children:ot?(0,Q.jsx)(Kv,{}):(0,Q.jsx)(Gv,{})})})]})]})}),Sv(n)&&(0,Q.jsx)(Zv,{className:`archived-channel-state`,title:`Archived`,children:(0,Q.jsx)(`p`,{children:`This channel is preserved and read-only. Restore it to resume activity.`})}),ot&&(0,Q.jsx)(Zv,{className:`archived-channel-state`,title:`Archived for you`,children:(0,Q.jsx)(`p`,{children:`This conversation is preserved and hidden from your normal list. Restore it to send messages.`})}),(n.kind===`group`||at)&&(0,Q.jsx)(Zv,{action:n.kind===`group`&&(n.role===`owner`||I.role===`admin`)&&!Sv(n)?(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Manage channel members`,title:`Manage channel members`,disabled:Gn,onClick:()=>void fi(),children:(0,Q.jsx)(Wv,{})}):void 0,className:`agent-attention-section`,title:`People`,children:(0,Q.jsxs)(`ul`,{children:[(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(Kh,{avatar:A.principal.avatar??N_,className:`context-person-avatar`,displayName:A.principal.displayName,principalId:A.principal.principalId}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:A.principal.displayName}),(0,Q.jsxs)(`small`,{children:[A.principal.handle?`@${A.principal.handle}`:``,!at&&` · ${n.role}`]})]})]}),n.participants.filter(e=>e.kind===`human`).map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(Kh,{avatar:e.avatar??N_,className:`context-person-avatar`,displayName:e.displayName,principalId:e.principalId}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.displayName}),e.handle&&(0,Q.jsxs)(`small`,{children:[`@`,e.handle,!at&&` · participant`]})]})]},e.principalId))]})}),n.kind===`group`&&(0,Q.jsxs)(Zv,{action:n.role===`owner`&&!Sv(n)?(0,Q.jsx)(`button`,{className:`panel-icon-button`,type:`button`,"aria-label":`Manage channel agents`,title:`Manage channel agents`,disabled:Vn,onClick:()=>void di(),children:(0,Q.jsx)(Uv,{})}):void 0,className:`agent-attention-section`,title:`Agents`,children:[br&&(0,Q.jsx)(`p`,{className:`standing-notice`,role:`status`,children:br}),n.agents.length===0&&(0,Q.jsx)(`p`,{children:`No agents are attached.`}),(0,Q.jsx)(`ul`,{children:n.agents.map(e=>{let t=ai.some(t=>t.agentId===e.agentId),n=or?.subscriptions.find(t=>t.agentId===e.agentId),r=or?.observations.find(t=>t.agentId===e.agentId&&t.lifecycleState===`paused_overflow`),i=n?.lifecycleState===`active`;return(0,Q.jsxs)(`li`,{children:[i&&(0,Q.jsx)(`span`,{className:`standing-agent-mark`,title:`Standing participant`,children:(0,Q.jsx)(ty,{})}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:e.name}),(0,Q.jsx)(`small`,{children:i?`Joined in ${cv(n.startedAt)} · standing`:n?.lifecycleState===`ended`?`Standing ended${n.endReason?` · ${n.endReason.replaceAll(`_`,` `)}`:``}`:e.available?t?`Awake in this channel`:`Available · not standing`:`Unavailable until its sponsor re-enables this runtime`}),r&&(0,Q.jsxs)(`small`,{className:`standing-overflow`,children:[`Observation paused · `,r.pendingMessageCount,` pending`]}),(0,Q.jsxs)(`small`,{children:[`Sponsored by `,e.sponsorDisplayName??`unknown`,` · shared-channel memory`]})]}),r?(0,Q.jsx)(`button`,{className:`panel-icon-button standing-agent-action`,type:`button`,"aria-label":`Resume ${e.name}'s standing observation`,title:`Resume ${e.name}'s standing observation`,disabled:gr!==null,onClick:()=>void ci(e.agentId,r),children:(0,Q.jsx)(Kv,{})}):(i||t)&&(0,Q.jsx)(`button`,{className:`panel-icon-button standing-agent-action`,type:`button`,"aria-label":i?`Dismiss ${e.name} from standing participation`:`Dismiss ${e.name}`,title:i?`Dismiss standing participant`:`Dismiss agent attention`,disabled:Yn===e.agentId,onClick:()=>void oi(e.agentId),children:(0,Q.jsx)(ny,{})})]},e.agentId)})}),ur&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:ur})]}),(0,Q.jsx)(Zv,{title:`Authority`,children:(0,Q.jsx)(`p`,{children:at?`Only you and ${rt} can read and send messages here.`:n.canSubmitCommands?`You can read and send messages in this channel. Mention an agent to direct a request to it.`:`You can read this outbound channel, but you cannot send messages here.`})}),!at&&(0,Q.jsxs)(Zv,{className:`trace-section`,revealKey:hn.key,revealReady:hn.agentId===null||Bt.some(e=>e.agentId===hn.agentId),revealTargetId:hn.agentId?`runtime-status-${hn.agentId}`:null,title:`Runtime`,children:[Bt.length>0?(0,Q.jsx)(`div`,{className:`runtime-lane-statuses`,children:Bt.map(e=>{let t=e.activeRun??e.lastRun;return(0,Q.jsxs)(`div`,{className:`runtime-settings`,id:`runtime-status-${e.agentId}`,tabIndex:-1,children:[(0,Q.jsxs)(`div`,{className:`runtime-lane-heading`,children:[(0,Q.jsx)(`p`,{className:`settings-source`,children:n.kind===`group`?e.agentName:`Agent runtime`}),(0,Q.jsx)(`button`,{className:`panel-icon-button runtime-fresh-session`,type:`button`,"aria-label":`Start a fresh provider session for ${e.agentName}`,title:`Start fresh provider session`,disabled:qt!==null||e.activeRun!==null,onClick:()=>void Ci(e),children:(0,Q.jsx)(qv,{})})]}),(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`strong`,{children:e.backend}),e.provider?` · ${e.provider}`:``]}),(0,Q.jsxs)(`p`,{children:[`Model: `,(0,Q.jsx)(`code`,{children:e.model.value}),(0,Q.jsx)(`br`,{}),`Timeout: `,e.timeoutSeconds.value,`s`]}),!e.canManageRuntime&&(0,Q.jsxs)(`p`,{className:`settings-source`,children:[`Sponsored by `,e.sponsorDisplayName]}),(0,Q.jsxs)(`p`,{className:`settings-source`,children:[`Session: `,e.providerSessionState.replaceAll(`_`,` `),t?` · Last run: ${t.status}`:` · No runs yet`]})]},e.agentId)})}):Rt?(0,Q.jsx)(`p`,{className:`settings-error`,children:Rt}):n.canSubmitCommands?(0,Q.jsx)(`p`,{children:`Loading runtime status…`}):(0,Q.jsx)(`p`,{children:`No agent runtime is assigned to this channel.`}),Rt&&Bt.length>0&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:Rt}),Yt&&(0,Q.jsx)(`p`,{className:`settings-success`,role:`status`,children:Yt})]}),!at&&(0,Q.jsxs)(Zv,{className:`trace-section`,title:`Workspace`,children:[Bt.length>0?(0,Q.jsx)(`div`,{className:`runtime-lane-statuses`,children:Bt.map(e=>(0,Q.jsx)(`div`,{className:`runtime-settings`,children:e.workspaceMode===`neutral`?(0,Q.jsx)(`p`,{className:`settings-source`,children:`No shared workspace`}):(0,Q.jsxs)(`div`,{className:`runtime-workspace-select`,children:[(0,Q.jsx)(`select`,{"aria-label":`Your workspace`,value:e.workspace??``,disabled:Qt||Wt.length>0,onChange:e=>void Si(e.target.value),children:e.workspaces.map(e=>(0,Q.jsx)(`option`,{value:e.path,children:e.name},e.path))}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(Bv,{})})]})},e.agentId))}):Rt?(0,Q.jsx)(`p`,{className:`settings-error`,children:Rt}):n.canSubmitCommands?(0,Q.jsx)(`p`,{children:`Loading workspace status…`}):(0,Q.jsx)(`p`,{children:`No agent workspace is assigned to this channel.`}),Rt&&Bt.length>0&&(0,Q.jsx)(`p`,{className:`settings-error`,role:`alert`,children:Rt})]}),!at&&(0,Q.jsxs)(Zv,{className:`trace-section`,title:`Inspector`,children:[Bt.some(e=>e.operatorDiagnostics)&&(0,Q.jsxs)(`div`,{className:`runtime-lane-diagnostics`,children:[(0,Q.jsx)(`h3`,{children:`Runtime diagnostics`}),Bt.map(e=>e.operatorDiagnostics&&(0,Q.jsxs)(`dl`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Agent`}),(0,Q.jsx)(`dd`,{children:e.agentName})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Process`}),(0,Q.jsx)(`dd`,{children:e.processState})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Continuity`}),(0,Q.jsx)(`dd`,{children:e.continuityState.replaceAll(`_`,` `)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Profile`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:e.operatorDiagnostics.runtimeProfileId})})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Context boundary`}),(0,Q.jsx)(`dd`,{children:e.operatorDiagnostics.contextThroughEventPosition??`none`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Session updated`}),(0,Q.jsx)(`dd`,{children:e.sessionUpdatedAt?cv(e.sessionUpdatedAt):`not started`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Provider session revision`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:e.operatorDiagnostics.providerSessionRevision??`none`})})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Fresh-session revision`}),(0,Q.jsxs)(`dd`,{children:[(0,Q.jsx)(`code`,{children:e.freshSessionRevision??`none`}),e.freshSessionGeneration===null?``:` · generation ${e.freshSessionGeneration}`]})]})]},e.agentId))]}),or&&(0,Q.jsxs)(`details`,{className:`standing-run-inspector`,children:[(0,Q.jsxs)(`summary`,{children:[`Standing observations (`,or.recentRuns.length,`)`]}),or.canInspectSilent&&(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:vr,onChange:e=>yr(e.target.checked)}),`Show authorized silent observations`]}),or.recentRuns.length===0?(0,Q.jsx)(`p`,{children:`No visible standing observations.`}):(0,Q.jsx)(`ol`,{children:or.recentRuns.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`strong`,{children:[e.agentDisplayName,` · `,e.outcome??e.status]}),(0,Q.jsxs)(`small`,{children:[e.scopeKind,` · messages `,e.observedFromEventPosition,`–`,e.observedThroughEventPosition,` · batch `,e.observedMessageCount]}),(0,Q.jsxs)(`small`,{children:[`Anchor `,e.humanAnchorMessageId]}),(0,Q.jsxs)(`small`,{children:[`Grant `,e.collaborationGrantId??`none`,` · `,or.policy.maxObserveRunsPerHour,` observations/hour · `,or.policy.maxUnsolicitedMessagesPerHour,` contributions/hour`]}),(0,Q.jsx)(`code`,{title:e.runId,children:e.runId})]},e.runId))})]}),(0,Q.jsx)(Di,{collaborationActivity:ti,entries:ni,failed:ri,loaded:ii,runId:ei}),(0,Q.jsxs)(`details`,{className:`context-stack-panel`,children:[(0,Q.jsx)(`summary`,{children:`Context stack`}),(0,Q.jsx)(Fi,{session:{channelId:Z,token:d},runId:ei,onNavigate:e=>{e.inspection.editTargetId&&(e.inspection.editTarget===`agent_definition`||e.inspection.editTarget===`workspace_policy`)&&je(e.inspection.editTargetId,e.inspection.editTarget===`workspace_policy`?`runtime`:null)}})]})]})]}),Gt.length>0&&!at&&(0,Q.jsxs)(`section`,{className:`agent-activity-dock`,"aria-label":`Agent activity`,"aria-live":`polite`,children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsx)(`h2`,{children:`Agent activity`}),(0,Q.jsx)(`span`,{children:Gt.length})]}),(0,Q.jsx)(`ol`,{children:Gt.map(e=>{let t=n.agents.find(t=>t.agentId===e.agentId)?.name??`Agent`,r=vt.has(e.runId);return(0,Q.jsxs)(`li`,{className:`agent-activity-row ${e.status}`,children:[(0,Q.jsx)(`span`,{className:`agent-activity-avatar`,"aria-hidden":`true`,children:t.slice(0,1).toUpperCase()}),(0,Q.jsxs)(`span`,{className:`agent-activity-description`,children:[(0,Q.jsx)(`strong`,{children:t}),(0,Q.jsx)(`small`,{children:uv(e)})]}),(0,Q.jsxs)(`span`,{className:`agent-activity-state`,children:[(0,Q.jsx)(`strong`,{children:e.status}),(0,Q.jsx)(`small`,{children:lv(e,St)})]}),ov(e)&&e.kind===`respond`&&(0,Q.jsx)(`button`,{className:`panel-icon-button agent-activity-stop`,type:`button`,"aria-label":`Stop ${t}`,title:`Stop ${t}`,disabled:r,onClick:()=>void Bi(e),children:(0,Q.jsx)(Lv,{})})]},e.runId)})})]})]}),Tn&&n.kind===`group`&&(0,Q.jsx)(jv,{busy:fr,channelName:rt,error:mr??(or?null:ur),loading:cr,onClose:()=>En(!1),onStandingChange:si,participation:or}),yn&&(0,Q.jsx)(Mv,{channels:I.channels.filter(e=>e.kind===`group`&&Sv(e)),busyChannelId:kn,onClose:()=>bn(!1),onRestore:gi,onView:e=>{bn(!1),Ne(e)}}),xn&&(0,Q.jsx)(Nv,{channels:I.channels.filter(e=>Cv(e)&&!e.agents.some(e=>e.lifecycleState===`archived`)),busyChannelId:jn,onClose:()=>Sn(!1),onRestore:vi,onView:e=>{Sn(!1),Ne(e)}}),zn&&(0,Q.jsx)(kv,{attachedAgents:n.agents,enablements:zn,onCancel:()=>Bn(null),onSave:mi}),Un&&(0,Q.jsx)(Av,{membership:Un,onCancel:()=>Wn(null),onChange:pi})]}),Cn&&(0,Q.jsx)(Pv,{agents:Yr,onClose:()=>wn(!1),onOpenConversation:e=>{wn(!1),De(e)},onContinue:(e,t)=>{wn(!1),Ee(e,t)},onView:e=>{wn(!1),Te(e)}}),_n&&(0,Q.jsx)(Dv,{agents:qr,initialAgentIds:_n.initialAgentIds,originChannelId:_n.originChannelId,originName:_n.originName,onCancel:()=>vn(null),onCreate:async e=>{await U(e),vn(null)}}),Dn&&(0,Q.jsx)(Ov,{onCancel:()=>On(!1),onLoad:le,onOpen:async e=>{await Ie(e),On(!1)}}),nn&&(0,Q.jsx)(g_,{actions:pn,error:dn,loading:ln,onClose:()=>rn(!1),onInvoke:wi}),an&&(0,Q.jsx)(yg,{onAuthenticationFailure:he,onChannelAccessFailure:Ve,onClose:()=>on(!1),onSubmitted:()=>{cn(e=>e+1),be()},session:k})]})}function ay(e,t){for(let n of e.workshops){let e=n.channels.find(e=>e.channelId===t);if(e)return{channel:e,workshop:n}}return null}function oy(e,t){if(t){let n=ay(e,t);if(n)return n}for(let t of e.workshops){let e=t.channels.find(e=>e.canSubmitCommands);if(e)return{channel:e,workshop:t}}for(let t of e.workshops)if(t.channels[0])return{channel:t.channels[0],workshop:t};return null}function sy({destination:e,navigation:t,session:n,readActivationChannelId:r,onAuthenticationFailure:i,onArchiveChannel:a,onArchiveDirectMessage:o,onChannelAccessFailure:s,onCreateChannel:c,onStartHumanConversation:l,onForget:u,onAgentNavigationChanged:d,onCreateAgent:f,onOpenAgentDefinition:p,onOpenAgentSetup:m,onOpenAgentChannel:h,onOpenWorkspaces:g,onOpenScheduledJobs:_,onOpenMemory:y,onOpenMentions:b,onOpenFollowing:x,onOpenReviews:S,onOpenFollowedThread:C,onOpenHumanNotification:w,onOpenSettings:T,onRestoreChannel:E,onRestoreDirectMessage:D,onSelectChannel:O,onSelectAgent:k,onSelectMemory:A,onSettingsDirtyChange:j}){let M=ay(t,n.channelId),N=t.workshops.flatMap(e=>e.channels),P=(e.kind===`settings`&&e.runtimeChannelId?N.find(t=>t.channelId===e.runtimeChannelId&&t.kind===`direct`&&t.agents.length>0&&t.canSubmitCommands):void 0)??N.find(e=>e.kind===`direct`&&e.agents.length>0&&e.canSubmitCommands)??N.find(e=>e.canSubmitCommands)??M?.channel,F=(0,v.useMemo)(()=>({channelId:P?.channelId??n.channelId,token:n.token}),[n.channelId,n.token,P?.channelId]),I=h_(n.token,i),L=I.subscribe,R=o_(n.token,I,i),ee=c_(n.token,I,i),z=f_(n.token,I,i,s);(0,v.useEffect)(()=>L(e=>{(e.kind===`synchronize`||e.batch.changes.some(e=>e.agentChanges.length>0))&&d().catch(()=>void 0)}),[d,L]);let[H,te]=(0,v.useState)(null);(0,v.useEffect)(()=>{if(e.kind!==`conversation`){te(null);return}z.loading||H?.channelId===n.channelId||te({channelId:n.channelId,messageId:z.byChannel[n.channelId]?.firstUnreadMessageId??null})},[e.kind,n.channelId,H?.channelId,z.byChannel,z.loading]);let U=e.kind!==`conversation`||H?.channelId===n.channelId,[ne,re]=(0,v.useState)(null),[W,ie]=(0,v.useState)(null),[ae,oe]=(0,v.useState)(null),{connection:se,messages:ce,threadMessages:le,reactionUpdates:ue,runActivities:G,runPreviews:K,runTrace:q,standingParticipationVersion:de,earlier:J,later:Y,loadEarlier:fe,loadLater:pe,jumpLatest:me,updateReactions:he}=Hi(n,M!==null&&e.kind!==`agents`&&U,H?.channelId===n.channelId?H.messageId:null,i,s);(0,v.useEffect)(()=>{if(e.kind!==`conversation`||!e.messageId){re(null),ie(null),oe(null);return}let t=new AbortController,r=e.messageId;return re(null),ie(null),oe(null),(async()=>{try{let e=await di(n,r,t.signal),i=e.threadRootId?await di(n,e.threadRootId,t.signal):e;t.signal.aborted||(re(e),ie(i))}catch(e){if(t.signal.aborted)return;if(e instanceof B){i(e.message);return}oe(e instanceof Error?e.message:`This mention's source message is no longer accessible.`)}})(),()=>t.abort()},[e,i,n]);let X=(0,v.useCallback)(async e=>{try{return await e()}catch(e){throw e instanceof B?i(e.message):e instanceof V&&s(e.message),e}},[i,s]),ge=(0,v.useCallback)(()=>{if(!M)throw Error(`Workshop access changed.`);return X(()=>st(n.token,M.workshop.workshopId))},[M,n.token,X]),_e=(0,v.useCallback)(e=>{if(!M)throw Error(`Workshop access changed.`);return l(M.workshop.workshopId,e)},[l,M]),ve=(0,v.useCallback)(e=>X(()=>zr(n,e)),[n,X]),ye=(0,v.useCallback)((e,t)=>X(()=>Hr(n,e,t)),[n,X]),be=(0,v.useCallback)(e=>X(()=>Gr(n,e)),[n,X]),xe=(0,v.useCallback)((e,t,r,i)=>X(()=>Lr(n,e,t,r,i)),[n,X]),Se=(0,v.useCallback)((e,t,r)=>X(()=>hi(n,e,t,r)),[n,X]),Ce=(0,v.useCallback)((e,t)=>X(()=>ai(n,e,t)),[n,X]),we=(0,v.useCallback)((e,t,r,i)=>X(()=>ci(n,e,t,r,i)),[n,X]),Te=(0,v.useCallback)((e,t,r,i)=>X(()=>si(n,e,t,r,i)),[n,X]),Ee=(0,v.useCallback)(e=>X(()=>Rr(n,e)),[n,X]),De=(0,v.useCallback)(e=>Pm(n,e),[n]),Oe=(0,v.useCallback)(async e=>{try{return await Un(n,e)}catch(e){throw e instanceof B&&i(e.message),e}},[i,n]),ke=(0,v.useCallback)((e,t)=>X(()=>Wn(n,e,t)),[n,X]),Ae=(0,v.useCallback)((e,t)=>X(()=>jr(n,e,t)),[n,X]),je=(0,v.useCallback)((e,t,r=null)=>X(()=>xt(n,e,t,r)),[n,X]),Me=(0,v.useCallback)((e,t)=>X(()=>yt(n,e,t)),[n,X]),Ne=(0,v.useCallback)((e,t)=>X(()=>bt(n,e,t)),[n,X]),Pe=(0,v.useCallback)(()=>X(()=>gt(n)),[n,X]),Fe=(0,v.useCallback)((e,t,r,i)=>X(()=>_t(n,e,t,r,i)),[n,X]),Ie=(0,v.useCallback)((e,t,r)=>X(async()=>{let i=await St(n,e,t,r);he(e,i)}),[n,he,X]),Le=(0,v.useCallback)((e,t)=>X(()=>Ct(n,e,t)),[n,X]);return M?(0,Q.jsx)(iy,{agentDestination:e.kind===`agents`?e:null,agentToken:n.token,channel:M.channel,connection:se,earlier:J,later:Y,messages:ce,threadMessages:le,workspacesDestination:e.kind===`workspaces`,scheduledJobsDestination:e.kind===`scheduled-jobs`,memoryDestination:e.kind===`memory`?e:null,mentionsDestination:e.kind===`mentions`,followingDestination:e.kind===`following`,reviewsDestination:e.kind===`reviews`,following:ee,inbox:R,unread:z,principalEvents:I,unreadBoundaryMessageId:H?.channelId===n.channelId?H.messageId:null,readActivatedInitially:r===n.channelId,focusedMessage:ne,focusedThreadRoot:W,requestedThreadRootId:e.kind===`conversation`?e.threadRootId??null:null,focusedMessageError:ae,memoryToken:n.token,settingsDestination:e.kind===`settings`,settingsInitialSection:e.kind===`settings`?e.section:null,settingsRuntimeLabel:P?vv(P):`assigned runtime`,settingsSession:F,navigation:t,onLoadEarlier:fe,onLoadLater:pe,onJumpLatest:me,onDownloadArtifact:De,onLoadArtifact:Ee,onLoadChannelMembers:Pe,onLoadHumanPeers:ge,runActivities:G,runPreviews:K,runTrace:q,standingParticipationVersion:de,reactionUpdates:ue,workshop:M.workshop,onForget:u,onAgentNavigationChanged:d,onArchiveChannel:a,onArchiveDirectMessage:o,onAttachAgent:Me,onCreateAgent:f,onCancelRun:be,onCreateChannel:c,onDismissAgent:je,onDetachAgent:Ne,onLoadRun:ve,onLoadRunTrace:ye,onLoadRuntimeLaneStatus:Oe,onStartFreshProviderSession:ke,onLoadThread:Se,onLoadThreadUnread:Ce,onAdvanceThreadRead:we,onSetThreadFollowed:Te,onChangeChannelMember:Fe,onMemoryAuthenticationFailure:i,onOpenAgentChannel:h,onOpenAgentDefinition:p,onOpenAgentSetup:m,onOpenWorkspaces:g,onOpenScheduledJobs:_,onOpenMemory:y,onOpenMentions:b,onOpenFollowing:x,onOpenReviews:S,onOpenFollowedThread:C,onOpenHumanNotification:w,onOpenSettings:T,onRestoreChannel:E,onRestoreDirectMessage:D,onSelectMemory:A,onSelectAgent:k,onSelectChannel:O,onSetReaction:Ie,onLoadReactors:Le,onSubmitCommand:xe,onStartHumanConversation:_e,onSwitchWorkspace:Ae,onSettingsAccessFailure:s,onSettingsDirtyChange:j}):(0,Q.jsx)(`main`,{className:`loading-workshop`,children:`Workshop access changed.`})}function cy(){let e=Km(),[t,n]=(0,v.useState)(()=>X_()),[r,i]=(0,v.useState)(null),[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(()=>t?`workshop`:`enrollment`),[l,u]=(0,v.useState)(null),[d,f]=(0,v.useState)(F_),[p,m]=(0,v.useState)(!1),[h,g]=(0,v.useState)(null);(0,v.useEffect)(()=>{let e=e=>{if(e.storageArea!==localStorage||e.key!==__)return;let r=J_(e.newValue);if(!r){Q_(),z(),n(null),i(null),o(null),u(`Workshop session was forgotten in another tab.`),c(`enrollment`),m(!1),g(null);return}r!==t?.token&&(n({channelId:Y_(),token:r}),i(null),o(null),u(null),c(`workshop`),m(!1),g(null))};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[t?.token]),(0,v.useEffect)(()=>{let t=async()=>{let t=F_();if(d.kind===`settings`&&t.kind!==`settings`&&p&&!await e(`Discard unsaved preference changes?`)){I_(d,`push`);return}f(t)},n=()=>{t()};return window.addEventListener(`popstate`,n),()=>window.removeEventListener(`popstate`,n)},[e,d,p]);let _=(0,v.useCallback)((e=null)=>{$_(),z(),n(null),i(null),o(null),u(e),c(`enrollment`),m(!1),g(null)},[]),y=(0,v.useCallback)(e=>_(e),[_]),b=(0,v.useCallback)((e,t,r,a)=>{let s=oy(t,r);if(!s)throw Error(`This Workshop account has no accessible channels.`);let l={channelId:s.channel.channelId,token:e};Z_(l),n({channelId:l.channelId,token:e}),i(l),o(t),R(a.themeId),u(null),c(`workshop`)},[]);(0,v.useEffect)(()=>{if(s!==`workshop`||!t||a)return;let e=!1;return Promise.all([xe(t.token),lr({token:t.token})]).then(([n,r])=>{e||b(t.token,n,t.channelId,r)}).catch(t=>{if(!e){if(t instanceof B){_(t.message);return}u(t instanceof Error?t.message:`Could not load Workshop navigation.`),c(`enrollment`)}}),()=>{e=!0}},[t,b,_,a,s]);let x=async({deviceDisplayName:e,enrollmentToken:n})=>{let r=t?.token??await be(n,e),[i,a]=await Promise.all([xe(r),lr({token:r})]);b(r,i,t?.channelId??null,a)},S=(0,v.useCallback)(async e=>{if(r)try{let[e,t]=await Promise.all([xe(r.token),lr({token:r.token})]);b(r.token,e,r.channelId,t)}catch(t){if(t instanceof B){_(t.message);return}u(t instanceof Error?t.message:e),o(null),c(`enrollment`)}},[b,_,r]),C=(0,v.useCallback)(e=>{S(e)},[S]),w=async t=>{if(!r||!a||!ay(a,t)||d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let n={...r,channelId:t};g(t),Z_(n),i(n);let o={kind:`conversation`};f(o),I_(o,`push`)},T=async()=>{if(d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let t={kind:`workspaces`};f(t),I_(t,`push`)},E=async()=>{if(d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let t={kind:`scheduled-jobs`};f(t),I_(t,`push`)},D=async()=>{if(d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let t={kind:`memory`,memoryId:null};f(t),I_(t,`push`)},O=async()=>{if(d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let t={kind:`mentions`};f(t),I_(t,`push`)},k=async()=>{if(d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let t={kind:`following`};f(t),I_(t,`push`)},A=async()=>{if(d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let t={kind:`reviews`};f(t),I_(t,`push`)},j=e=>{let t=e.state.channelId;if(!r||!a||!ay(a,t))return!1;let n={...r,channelId:t};g(null),Z_(n),i(n);let o={kind:`conversation`,messageId:e.state.firstUnreadMessageId??e.latestReplyMessageId??e.state.threadRootId,threadRootId:e.state.threadRootId};return f(o),I_(o,`push`),!0},M=e=>{if(!r||!a||!ay(a,e.sourceChannelId))return!1;let t={...r,channelId:e.sourceChannelId};g(e.sourceChannelId),Z_(t),i(t);let n={kind:`conversation`,messageId:e.sourceMessageId,threadRootId:e.sourceThreadRootId};return f(n),I_(n,`push`),!0},N=async(t=null,n=!1,r=null,i=null)=>{if(d.kind===`settings`&&p&&!await e(`Discard unsaved preference changes?`))return;let a={creating:n,definitionId:t,kind:`agents`,section:r,setupId:i};f(a),I_(a,`push`)},P=(e=null)=>{let t={kind:`settings`,runtimeChannelId:null,section:e};f(t),I_(t,`push`)},F=(0,v.useCallback)(e=>{let t={kind:`memory`,memoryId:e};f(t),I_(t,`replace`)},[]),I=(0,v.useCallback)((e,t=null)=>{let n={creating:!1,definitionId:e,kind:`agents`,section:t,setupId:null};f(n),I_(n,`replace`)},[]),L=async e=>{await N(e)},ee=async(e,t)=>{await N(e,!0,null,t)},H=(0,v.useCallback)(async()=>{if(r)try{let e=await xe(r.token),t=ay(e,r.channelId),a=t??oy(e,null);if(!a)throw Error(`This Workshop account has no accessible channels.`);if(!t){let e={...r,channelId:a.channel.channelId};Z_(e),n({channelId:e.channelId,token:e.token}),i(e)}o(e)}catch(e){if(e instanceof B)_(e.message);else throw e}},[_,r]),te=(0,v.useCallback)(async e=>{if(!r)throw Error(`Workshop is not connected.`);try{let t=await xe(r.token);if(!ay(t,e))throw new V(`This session cannot access that agent conversation.`);let a={...r,channelId:e};g(e),Z_(a),n({channelId:e,token:r.token}),i(a),o(t);let s={kind:`conversation`};f(s),I_(s,`push`)}catch(e){throw e instanceof B?_(e.message):e instanceof V&&C(e.message),e}},[_,C,r]),U=async e=>{if(!r)throw Error(`Workshop is not connected.`);try{let t=await at(r.token,e),[n,i]=await Promise.all([xe(r.token),lr({token:r.token})]);b(r.token,n,t,i),g(t);let a={kind:`conversation`};f(a),I_(a,`push`)}catch(e){throw e instanceof B?y(e.message):e instanceof V&&C(e.message),e}},ne=async(e,t)=>{if(!r)throw Error(`Workshop is not connected.`);try{let n=await ct(r.token,e,t),[i,a]=await Promise.all([xe(r.token),lr({token:r.token})]);b(r.token,i,n.channelId,a),g(n.channelId);let o={kind:`conversation`};f(o),I_(o,`push`)}catch(e){throw e instanceof B?y(e.message):e instanceof V&&C(e.message),e}},re=async(e,t,n)=>{if(!r)throw Error(`Workshop is not connected.`);try{n===`archive`?await ut(r.token,e,t):await dt(r.token,e,t);let[i,a]=await Promise.all([xe(r.token),lr({token:r.token})]);b(r.token,i,n===`restore`?e:r.channelId,a)}catch(e){throw e instanceof B?y(e.message):e instanceof V&&C(e.message),e}},W=async(e,t,n)=>{if(!r)throw Error(`Workshop is not connected.`);try{n===`archive`?await pt(r.token,e,t):await mt(r.token,e,t);let i=await xe(r.token);b(r.token,i,e,await lr({token:r.token}))}catch(e){throw e instanceof B?y(e.message):e instanceof V&&C(e.message),e}};return s===`enrollment`?(0,Q.jsx)(dv,{existingSession:t!==null,notice:l,onForget:()=>_(),onOpen:x},`${t?`correction`:`fresh`}:${l??``}`):!r||!a?(0,Q.jsx)(`main`,{className:`loading-workshop`,children:`Opening Kai Workshop…`}):(0,Q.jsx)(Wh,{token:r.token,children:(0,Q.jsx)(sy,{destination:d,navigation:a,session:r,readActivationChannelId:h,onAuthenticationFailure:y,onArchiveChannel:(e,t)=>re(e,t,`archive`),onArchiveDirectMessage:(e,t)=>W(e,t,`archive`),onChannelAccessFailure:C,onCreateChannel:U,onStartHumanConversation:ne,onForget:()=>_(),onAgentNavigationChanged:H,onCreateAgent:()=>void N(null,!0),onOpenAgentChannel:te,onOpenAgentDefinition:L,onOpenAgentSetup:ee,onOpenWorkspaces:()=>void T(),onOpenScheduledJobs:()=>void E(),onOpenMemory:()=>void D(),onOpenMentions:()=>void O(),onOpenFollowing:()=>void k(),onOpenReviews:()=>void A(),onOpenFollowedThread:j,onOpenHumanNotification:M,onOpenSettings:P,onRestoreChannel:(e,t)=>re(e,t,`restore`),onRestoreDirectMessage:(e,t)=>W(e,t,`restore`),onSelectChannel:w,onSelectAgent:I,onSelectMemory:F,onSettingsDirtyChange:m},r.channelId)})}function ly(){return(0,Q.jsx)(Gm,{children:(0,Q.jsx)(cy,{})})}ee();var uy=document.getElementById(`root`);if(!uy)throw Error(`Kai Workshop root element is unavailable`);(0,y.createRoot)(uy).render((0,Q.jsx)(v.StrictMode,{children:(0,Q.jsx)(ly,{})})); \ No newline at end of file diff --git a/src/kai/workshop/temporal_memory.py b/src/kai/workshop/temporal_memory.py index 36088dbc..a21d3e59 100644 --- a/src/kai/workshop/temporal_memory.py +++ b/src/kai/workshop/temporal_memory.py @@ -233,7 +233,10 @@ def _evidence(payload: dict[str, Any], *, canonical: bool) -> str: if not isinstance(item, dict) or set(item) != {"kind", "reference_id", "sha256"}: raise ValueError("Temporal memory evidence entries have an invalid shape") kind = _required_text(item.get("kind"), field="evidence kind", maximum=32) - if kind not in {"message", "run", "operator", "legacy"}: + # `agent` names a fact the owner's agent saved deliberately through + # the internal memory API; that save has no message or run id of its + # own, so it is cited by the save's id instead. + if kind not in {"message", "run", "operator", "legacy", "agent"}: raise ValueError("Temporal memory evidence kind is invalid") reference_id = _required_text(item.get("reference_id"), field="evidence reference", maximum=128) digest = item.get("sha256") diff --git a/tests/test_application_host.py b/tests/test_application_host.py index a8bcbee9..7f1fb7e5 100644 --- a/tests/test_application_host.py +++ b/tests/test_application_host.py @@ -200,6 +200,9 @@ async def recover_fact_projections(self) -> int: async def refresh_legacy_census(self) -> int: return 0 + async def refresh_vector_audits(self) -> int: + return 0 + class _FakeIntegrationNotifications: def __init__(self, events: list[str]) -> None: diff --git a/tests/test_memory_agent_writes.py b/tests/test_memory_agent_writes.py new file mode 100644 index 00000000..a8372c74 --- /dev/null +++ b/tests/test_memory_agent_writes.py @@ -0,0 +1,244 @@ +""" +Agent memory writes and the stored vector audit on a protected install. + +The internal memory API lets an agent save a fact or forget everything. +These tests run those paths through the Workshop memory query service, +the real fact lifecycle and vector adapter, and the real protected +current-truth gate, with only Mem0's storage replaced (the harness from +the canonical write-path tests). Recall assertions go through +`memory.search`, so a save that reached the store but not current truth +shows up as missing, exactly as it would for the agent. +""" + +# ruff: noqa: F811 - tests take the imported `protected` fixture as a parameter by name. + +from __future__ import annotations + +import sqlite3 +from pathlib import Path + +import pytest + +from kai import memory, memory_reconciliation +from kai.workshop.diagnostics import workshop_memory_current_truth_status +from kai.workshop.memory_queries import WorkshopMemoryMutationFailed +from kai.workshop.memory_reconciliation_review import record_reconciliation_audit +from tests.test_memory_canonical_write_path import ( # noqa: F401 - pytest fixture import + NOW, + PRINCIPAL_ID, + RUNTIME_ID, + _new, + _recall, + _store_fact, + protected, +) +from tests.test_memory_owner_review import _conflict, _query_service + + +def _agent_metadata(**overrides: object) -> dict[str, object]: + """The metadata the internal API handler builds for a global explicit save.""" + return { + "speaker": "assistant", + "confidence": 0.9, + "source": "explicit", + **memory.build_scope_metadata(scope="global", project_id=None, scope_source="extraction_default"), + **overrides, + } + + +def _legacy_row(content: str) -> str: + """ + Write a row the way the internal API used to: owner-stamped, no claim. + + The protected gate treats such a row as legacy memory, which is the + failure the lifecycle path fixes; here it stands for legacy rows an + owner still has when they forget everything. + """ + memory_id = memory.add_structured( + content, + user_id=str(PRINCIPAL_ID), + memory_type="fact", + metadata={"source": "explicit", "speaker": "assistant", "confidence": 0.9}, + runtime_profile_id=str(RUNTIME_ID), + ) + assert memory_id is not None + return memory_id + + +# ── Saving ─────────────────────────────────────────────────────────── + + +async def test_agent_save_is_current_truth_and_recalled(protected, tmp_path: Path) -> None: + store, provider, _lifecycle = protected + service, authority = _query_service(store, tmp_path) + + memory_id = await service.record_agent_fact( + principal_id=PRINCIPAL_ID, + runtime_profile_id=RUNTIME_ID, + content="The operator drinks Earl Grey.", + tags=["tea"], + vector_metadata=_agent_metadata(), + ) + + assert _recall() == ["The operator drinks Earl Grey."] + assert provider.rows[memory_id]["metadata"]["tags"] == ["tea"] + assert provider.rows[memory_id]["metadata"]["source"] == "explicit" + # History names where the fact came from. + detail = await service.detail(authority, memory_id) + assert detail.lifecycle is not None + (revision,) = detail.lifecycle["revisions"] + assert revision["state"] == "active" + assert revision["reason"] == "Fact saved deliberately by the owner's agent." + + +async def test_the_old_direct_write_is_not_recalled(protected, tmp_path: Path) -> None: + # The defect the lifecycle path fixes: once the owner's legacy memory + # is reconciled, a claimless row is never admitted by the gate. + store, _provider, _lifecycle = protected + audit = memory_reconciliation.build_audit( + principal_id=str(PRINCIPAL_ID), runtime_profile_id=str(RUNTIME_ID), rows=[], now=NOW + ) + record_reconciliation_audit(tmp_path / "kai.db", audit) + await store.connection.execute( + "UPDATE memory_reconciliation_audits SET status = 'applied', applied_at = ?", (NOW.isoformat(),) + ) + await store.connection.commit() + + _legacy_row("The operator drinks Earl Grey.") + + assert _recall() == [] + + +async def test_agent_save_in_a_project_keeps_its_scope(protected, tmp_path: Path) -> None: + store, _provider, _lifecycle = protected + service, _authority = _query_service(store, tmp_path) + + await service.record_agent_fact( + principal_id=PRINCIPAL_ID, + runtime_profile_id=RUNTIME_ID, + content="The build uses make check.", + tags=None, + vector_metadata=_agent_metadata( + **memory.build_scope_metadata(scope="project", project_id="kai", scope_source="extraction_default") + ), + ) + + async with store.connection.execute("SELECT scope_kind, scope_key FROM memory_fact_claims") as cursor: + assert [tuple(row) for row in await cursor.fetchall()] == [("project", "kai")] + + +async def test_agent_save_with_a_failed_projection_is_reported(protected, tmp_path: Path, monkeypatch) -> None: + store, provider, _lifecycle = protected + service, _authority = _query_service(store, tmp_path) + + def refuse(*_args, **_kwargs): + raise RuntimeError("vector store unavailable") + + monkeypatch.setattr(provider, "add", refuse) + + with pytest.raises(WorkshopMemoryMutationFailed): + await service.record_agent_fact( + principal_id=PRINCIPAL_ID, + runtime_profile_id=RUNTIME_ID, + content="The operator drinks Earl Grey.", + tags=None, + vector_metadata=_agent_metadata(), + ) + + # The claim is canonical and waits for the retry; it is not lost. + async with store.connection.execute( + "SELECT status FROM memory_fact_vector_operations ORDER BY event_position" + ) as cursor: + assert [str(row[0]) for row in await cursor.fetchall()] == ["failed"] + + +# ── Forgetting everything ──────────────────────────────────────────── + + +async def test_forget_all_retracts_facts_deletes_legacy_rows_and_keeps_conflicts(protected, tmp_path: Path) -> None: + store, provider, _lifecycle = protected + claim_in_conflict = await _conflict(store, provider) + await _store_fact(store, _new("The operator uses a Mac mini."), run=3) + legacy_id = _legacy_row("An old legacy fact.") + service, authority = _query_service(store, tmp_path) + + result = await service.forget_all_for_agent(principal_id=PRINCIPAL_ID, runtime_profile_id=RUNTIME_ID) + + assert (result.retracted, result.projection_failed, result.legacy_deleted) == (1, 0, 1) + assert (result.kept_conflicts, result.kept_episodes) == (1, 0) + assert _recall() == [] + assert legacy_id not in provider.rows + # Every forgotten fact stays in history and can be restored. + forgotten = await service.list_forgotten(authority) + assert [item.preview for item in forgotten.items] == ["The operator uses a Mac mini."] + conflicts = await service.list_conflicts(authority) + assert [item.claim_id for item in conflicts.items] == [claim_in_conflict] + + +async def test_forget_all_is_safe_to_repeat(protected, tmp_path: Path) -> None: + store, _provider, _lifecycle = protected + await _store_fact(store, _new("The operator uses a Mac mini."), run=1) + service, _authority = _query_service(store, tmp_path) + + await service.forget_all_for_agent(principal_id=PRINCIPAL_ID, runtime_profile_id=RUNTIME_ID) + again = await service.forget_all_for_agent(principal_id=PRINCIPAL_ID, runtime_profile_id=RUNTIME_ID) + + assert (again.retracted, again.legacy_deleted) == (0, 0) + + +# ── Stored vector audit ────────────────────────────────────────────── + + +def _stored_audit(database: Path) -> list[tuple[int, int, int, int]]: + connection = sqlite3.connect(database) + try: + return [ + (int(row[0]), int(row[1]), int(row[2]), int(row[3])) + for row in connection.execute( + "SELECT orphan_rows, unknown_rows, duplicate_items, missing_rows FROM memory_vector_audit" + ) + ] + finally: + connection.close() + + +async def test_startup_audit_is_stored_and_install_status_reads_it(protected, tmp_path: Path) -> None: + store, provider, _lifecycle = protected + await _store_fact(store, _new("The operator prefers dark themes."), run=1) + service, _authority = _query_service(store, tmp_path) + database = tmp_path / "kai.db" + assert "vector drift=not checked" in workshop_memory_current_truth_status(database, memory_enabled=True) + + assert await service.refresh_vector_audits() == 1 + + assert _stored_audit(database) == [(0, 0, 0, 0)] + assert "vector drift=0 (missing=0, checked 0m ago)" in workshop_memory_current_truth_status( + database, memory_enabled=True + ) + + # A current fact whose row vanished is a loss recall cannot return. + provider.rows.clear() + await service.refresh_vector_audits() + + assert _stored_audit(database) == [(0, 0, 0, 1)] + status = workshop_memory_current_truth_status(database, memory_enabled=True) + assert "vector drift=1 (missing=1," in status + assert status.startswith("Workshop memory current truth: INCOMPLETE;") + + +async def test_projection_retry_refreshes_the_stored_audit(protected, tmp_path: Path, monkeypatch) -> None: + store, provider, _lifecycle = protected + original_add = provider.add + + def refuse(*_args, **_kwargs): + raise RuntimeError("vector store unavailable") + + monkeypatch.setattr(provider, "add", refuse) + await _store_fact(store, _new("The operator prefers dark themes."), run=1) + monkeypatch.setattr(provider, "add", original_add) + service, authority = _query_service(store, tmp_path) + + result = await service.retry_projections(authority, claim_ids=None, episode_ids=None) + + assert result.succeeded == 1 + assert _stored_audit(tmp_path / "kai.db") == [(0, 0, 0, 0)] diff --git a/tests/test_memory_legacy_episode_triage.py b/tests/test_memory_legacy_episode_triage.py index 6857f35c..57230a51 100644 --- a/tests/test_memory_legacy_episode_triage.py +++ b/tests/test_memory_legacy_episode_triage.py @@ -285,6 +285,11 @@ async def test_an_open_older_plan_moves_forward_keeping_unchanged_decisions(tmp_ assert [item["disposition"] for item in record["dropped"]] == ["approve"] async with store.connection.execute("PRAGMA foreign_key_check") as cursor: assert await cursor.fetchall() == [] + # The replan record names the plan it produced, so install status + # accounts for it instead of reporting a replay gap. + from kai.workshop.diagnostics import workshop_memory_reconciliation_status + + assert "replay gaps=0;" in workshop_memory_reconciliation_status(tmp_path / "kai.db") finally: await store.close() diff --git a/tests/test_memory_owner_review.py b/tests/test_memory_owner_review.py index 955f7954..59f4e27b 100644 --- a/tests/test_memory_owner_review.py +++ b/tests/test_memory_owner_review.py @@ -57,7 +57,15 @@ def _query_service(store, tmp_path: Path) -> tuple[WorkshopMemoryQueryService, o legacy_runtime_key=1, ) service = WorkshopMemoryQueryService( - Config(telegram_bot_token="token", allowed_user_ids={1}, memory_enabled=True), + # The service writes stored audits through `session_db_path`, which + # in production is the store's own database; the fixture's store + # lives at tmp_path / "kai.db". + Config( + telegram_bot_token="token", + allowed_user_ids={1}, + memory_enabled=True, + session_db_path=tmp_path / "kai.db", + ), store, _RuntimePool(tmp_path), # type: ignore[arg-type] WorkshopExecutionStateRegistry((namespace,)), diff --git a/tests/test_memory_triage_consolidation.py b/tests/test_memory_triage_consolidation.py index 7a56d4dc..e6a6685b 100644 --- a/tests/test_memory_triage_consolidation.py +++ b/tests/test_memory_triage_consolidation.py @@ -306,3 +306,43 @@ def test_related_facts_come_from_the_recommendation_and_must_be_other_fact_group assert related_group_ids(current, prose, groups) == ["mtg_" + "b" * 32] assert related_group_ids(current, structured, groups) == ["mtg_" + "b" * 32] assert related_group_ids(current, {}, groups) == [] + + +async def test_consolidation_operations_are_not_replay_gaps(tmp_path: Path, monkeypatch) -> None: + # Consolidation saves and cancels carry no audit id by design; install + # status accounts for them through their plan and consolidation. + from kai.workshop.diagnostics import workshop_memory_reconciliation_status + + owner = await _Owner(tmp_path, list(_FACTS)).start(monkeypatch) + try: + plan_id, groups = await _groups(owner) + kept = (await _stage(owner, plan_id, groups, ["fact-1", "fact-2"], operation="stage-kept"))["consolidation"] + _plan, groups = await _groups(owner) + cancelled = ( + await _stage( + owner, + plan_id, + groups, + ["fact-3", "fact-4"], + operation="stage-cancelled", + canonical={**_CANONICAL, "source_memory_id": "fact-3"}, + ) + )["consolidation"] + await owner.triage().cancel_consolidation( + owner.principal, plan_id, cancelled["consolidation_id"], expected_revision=1, client_operation_id="cancel" + ) + + assert kept["consolidation_id"] != cancelled["consolidation_id"] + assert "replay gaps=0;" in workshop_memory_reconciliation_status(owner.db_path) + + # An operation nothing accounts for is still a gap. + connection = sqlite3.connect(owner.db_path) + connection.execute( + "INSERT INTO memory_reconciliation_operations VALUES (?, 'stray', ?, '{}', '2026-01-01T00:00:00Z')", + (str(owner.principal), "0" * 64), + ) + connection.commit() + connection.close() + assert "replay gaps=1;" in workshop_memory_reconciliation_status(owner.db_path) + finally: + await owner.close() diff --git a/tests/test_memory_write_path_sweep.py b/tests/test_memory_write_path_sweep.py new file mode 100644 index 00000000..e7cfbbd5 --- /dev/null +++ b/tests/test_memory_write_path_sweep.py @@ -0,0 +1,78 @@ +""" +Every direct vector-store write or delete outside `kai.memory` is a reviewed exception. + +On a protected install, current truth lives in the canonical fact and +episode lifecycle; the vector store is only its projection. A module that +writes or deletes vector rows directly bypasses that authority: a direct +write creates a row the current-truth gate never recalls once the owner's +legacy memory is reconciled, and a direct delete leaves a claim active +with a projection pointing at nothing. + +This test lists every production call site of the direct primitives with +the reason it is allowed, and fails on any site not in the list and on any +listed site that no longer exists, so the list stays exact. A new write +path should go through `MemoryFactLifecycleService` or +`MemoryEpisodeHistoryService` instead of being added here. +""" + +from __future__ import annotations + +import ast +from pathlib import Path + +import kai + +# The primitives that touch vector rows without the lifecycle. +_PRIMITIVES = frozenset({"add_structured", "delete_by_id", "delete_all"}) + +# (module path under src/kai, enclosing function, primitive) -> why it is allowed. +_ALLOWED = { + ("workshop/fact_lifecycle.py", "add", "add_structured"): "the fact lifecycle's own vector adapter", + ("workshop/episode_history.py", "add", "add_structured"): "the episode lifecycle's own vector adapter", + ("workshop/memory_queries.py", "delete", "delete_by_id"): "deleting a legacy episode row, which has no lifecycle", + ("webhook.py", "_handle_memory_add", "add_structured"): "installs without protected canonical authority", + ("webhook.py", "_handle_memory_delete_all", "delete_all"): "installs without protected canonical authority", + ("memory_extraction.py", "_store_facts", "add_structured"): "extraction runs without canonical provenance", + ("memory_extraction.py", "_store_facts", "delete_by_id"): "extraction runs without canonical provenance", + ("memory_extraction.py", "_generate_episode", "add_structured"): "episode runs without canonical provenance", + ("memory_scope_review.py", "run_apply", "delete_by_id"): "operator legacy scope review, legacy rows only", + ("memory_admin.py", "_cmd_purge_sandbox", "delete_all"): "operator purge of a sandbox evaluation user", +} + + +def _call_sites(root: Path) -> set[tuple[str, str, str]]: + """Find every reference to a primitive as `memory.` or a bare imported name.""" + sites: set[tuple[str, str, str]] = set() + for path in sorted(root.rglob("*.py")): + relative = path.relative_to(root).as_posix() + # `kai.memory` defines the primitives; the eval harness writes to + # sandbox users that never reach a protected owner's recall. + if relative == "memory.py" or relative.startswith("eval/"): + continue + tree = ast.parse(path.read_text(encoding="utf-8")) + + def visit(node: ast.AST, function: str, relative: str = relative) -> None: + for child in ast.iter_child_nodes(node): + inner = child.name if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)) else function + if ( + isinstance(child, ast.Attribute) + and child.attr in _PRIMITIVES + and isinstance(child.value, ast.Name) + and child.value.id in {"memory", "memory_module"} + ): + sites.add((relative, function, child.attr)) + if isinstance(child, ast.Name) and child.id in _PRIMITIVES and isinstance(child.ctx, ast.Load): + sites.add((relative, function, child.id)) + visit(child, inner) + + visit(tree, "") + return sites + + +def test_direct_vector_writes_are_exactly_the_reviewed_sites() -> None: + root = Path(kai.__file__).parent + + sites = _call_sites(root) + + assert sites - set(_ALLOWED) == set(), "route new memory writes through the fact or episode lifecycle" + assert set(_ALLOWED) - sites == set(), "remove allowlist entries whose call site is gone" diff --git a/tests/test_webhook_api.py b/tests/test_webhook_api.py index 3975bff6..972fce6b 100644 --- a/tests/test_webhook_api.py +++ b/tests/test_webhook_api.py @@ -55,6 +55,7 @@ RunId, ) from kai.workshop.internal_api_contexts import WorkshopInternalAPIExecutionContext +from kai.workshop.memory_queries import WorkshopMemoryMutationFailed from kai.workshop.proactive_publication import ProactivePublicationResult from kai.workshop.scheduler import WorkshopScheduledJobRegistrationError from kai.workshop.storage_namespaces import ( @@ -3706,6 +3707,85 @@ async def test_returns_500_when_serialization_raises(self, mock_request): assert body == {"error": "Memory stats failed"} +def _protect(mock_request, service) -> None: + """Make the mock request a protected install with `service` as its memory query service.""" + mock_request.app[CONFIG_KEY] = SimpleNamespace(memory_projects={}, protected_install=True) + mock_request.app[CORE_HOST_KEY].services.memory_queries = service + + +class TestProtectedMemoryWrites: + """On a protected install, explicit saves and forget-all go through the fact lifecycle.""" + + async def test_save_is_recorded_as_a_canonical_claim(self, mock_request): + mock_request.headers = {"X-Webhook-Secret": "test-secret"} + mock_request.json = AsyncMock(return_value={"content": "User likes Earl Grey", "tags": ["tea"]}) + service = SimpleNamespace(record_agent_fact=AsyncMock(return_value="vec-1")) + _protect(mock_request, service) + + with ( + patch("kai.memory.is_enabled", return_value=True), + patch("kai.memory.add_structured") as direct_write, + ): + resp = await _handle_memory_add(mock_request) + + assert resp.status == 200 + assert json.loads(resp.body.decode()) == {"id": "vec-1"} + # The direct vector write would create a row recall never admits. + direct_write.assert_not_called() + call = service.record_agent_fact.await_args.kwargs + assert call["content"] == "User likes Earl Grey" + assert call["tags"] == ["tea"] + assert call["vector_metadata"]["source"] == "explicit" + assert call["vector_metadata"]["scope"] == "global" + + async def test_save_reports_a_pending_projection_as_unavailable(self, mock_request): + mock_request.headers = {"X-Webhook-Secret": "test-secret"} + mock_request.json = AsyncMock(return_value={"content": "User likes Earl Grey"}) + service = SimpleNamespace( + record_agent_fact=AsyncMock(side_effect=WorkshopMemoryMutationFailed("projection pending")) + ) + _protect(mock_request, service) + + with patch("kai.memory.is_enabled", return_value=True): + resp = await _handle_memory_add(mock_request) + + # The agent must not report the save as done while recall lacks it. + assert resp.status == 503 + + async def test_save_refuses_non_fact_types(self, mock_request): + mock_request.headers = {"X-Webhook-Secret": "test-secret"} + mock_request.json = AsyncMock(return_value={"content": "Deployed", "memory_type": "episode"}) + service = SimpleNamespace(record_agent_fact=AsyncMock()) + _protect(mock_request, service) + + with patch("kai.memory.is_enabled", return_value=True): + resp = await _handle_memory_add(mock_request) + + assert resp.status == 400 + service.record_agent_fact.assert_not_awaited() + + async def test_forget_all_retracts_instead_of_deleting_rows(self, mock_request): + mock_request.headers = {"X-Webhook-Secret": "test-secret"} + mock_request.json = AsyncMock(return_value={"confirm": "delete-all-memories"}) + result = SimpleNamespace(retracted=3, projection_failed=0, legacy_deleted=2, kept_conflicts=1, kept_episodes=4) + service = SimpleNamespace(forget_all_for_agent=AsyncMock(return_value=result)) + _protect(mock_request, service) + + with patch("kai.memory.is_enabled", return_value=True), patch("kai.memory.delete_all") as wipe: + resp = await _call_memory_delete_all_as_authorized(mock_request) + + assert resp.status == 200 + assert json.loads(resp.body.decode()) == { + "status": "deleted", + "retracted": 3, + "projection_failed": 0, + "legacy_deleted": 2, + "kept_conflicts": 1, + "kept_episodes": 4, + } + wipe.assert_not_called() + + class TestMemoryDeleteAll: """DELETE /api/memory/all""" diff --git a/tests/test_workshop_client_api.py b/tests/test_workshop_client_api.py index c02fcf25..d7d10de6 100644 --- a/tests/test_workshop_client_api.py +++ b/tests/test_workshop_client_api.py @@ -1942,7 +1942,7 @@ async def test_projection_routes_serialize_review_audit_and_retry(tmp_path: Path ], } audit = await client.get("/v1/memory/projections/audit", headers=headers) - assert await audit.json() == {"version": 1, "orphan": ["vec-2"], "unknown": [], "duplicate": 1} + assert await audit.json() == {"version": 1, "orphan": ["vec-2"], "unknown": [], "duplicate": 1, "missing": []} everything = await client.post("/v1/memory/projections/retry", headers=headers, json={}) named = await client.post("/v1/memory/projections/retry", headers=headers, json={"claim_ids": ["mcl_1"]}) diff --git a/tests/test_workshop_foundation.py b/tests/test_workshop_foundation.py index 9a9ca27a..f022d4ac 100644 --- a/tests/test_workshop_foundation.py +++ b/tests/test_workshop_foundation.py @@ -619,6 +619,7 @@ async def test_version_one_database_upgrades_additively(self, tmp_path: Path, mo 93, 94, 95, + 96, ] finally: await upgraded.close() diff --git a/tests/test_workshop_memory_current_truth.py b/tests/test_workshop_memory_current_truth.py index 5b084716..447c019e 100644 --- a/tests/test_workshop_memory_current_truth.py +++ b/tests/test_workshop_memory_current_truth.py @@ -85,6 +85,24 @@ def _database(path: Path) -> sqlite3.Connection: ); -- The service counts legacy rows at startup; here nothing is unclassified. INSERT INTO memory_legacy_census VALUES ('prn_x', 'rtp_x', 0, 0, 0, 0, strftime('%Y-%m-%dT%H:%M:%SZ', 'now')); + CREATE TABLE memory_reconciliation_audits ( + audit_id TEXT PRIMARY KEY, + principal_id TEXT NOT NULL, + runtime_profile_id TEXT NOT NULL, + status TEXT NOT NULL + ); + CREATE TABLE memory_vector_audit ( + principal_id TEXT NOT NULL, + runtime_profile_id TEXT NOT NULL, + orphan_rows INTEGER NOT NULL, + unknown_rows INTEGER NOT NULL, + duplicate_items INTEGER NOT NULL, + missing_rows INTEGER NOT NULL, + checked_at TEXT NOT NULL, + PRIMARY KEY (principal_id, runtime_profile_id) + ); + -- The service audits vector rows at startup; here the store matches. + INSERT INTO memory_vector_audit VALUES ('prn_x', 'rtp_x', 0, 0, 0, 0, strftime('%Y-%m-%dT%H:%M:%SZ', 'now')); """ ) return connection @@ -427,8 +445,10 @@ def test_status_surfaces_quarantine_projection_and_legacy_gaps(tmp_path: Path) - "UPDATE memory_fact_revisions SET migration_classification = 'legacy_quarantined', " "admission_authority = 'quarantined'" ) - # The latest census found two legacy rows nothing has settled. + # The latest census found two legacy rows nothing has settled, for an + # owner who applied a reconciliation audit, so they are gaps. connection.execute("UPDATE memory_legacy_census SET legacy_rows = 2, unclassified = 2") + connection.execute("INSERT INTO memory_reconciliation_audits VALUES ('mra_x', 'prn_x', 'rtp_x', 'applied')") connection.commit() connection.close() incomplete = workshop_memory_current_truth_status(database, memory_enabled=True) @@ -442,3 +462,57 @@ def test_status_surfaces_quarantine_projection_and_legacy_gaps(tmp_path: Path) - connection.close() uncounted = workshop_memory_current_truth_status(database, memory_enabled=True) assert "legacy unclassified=not counted" in uncounted and "INCOMPLETE" in uncounted + + +def test_status_reports_owners_awaiting_review_without_marking_gaps(tmp_path: Path) -> None: + # An owner who never applied a reconciliation audit keeps temporary + # legacy admission, so their unclassified rows wait on their own review + # and are not integrity gaps. + from kai.workshop.diagnostics import workshop_memory_current_truth_status + + database = tmp_path / "kai.db" + connection = _database(database) + _insert_revision(connection) + connection.execute("UPDATE memory_legacy_census SET legacy_rows = 7, unclassified = 7") + connection.commit() + connection.close() + + status = workshop_memory_current_truth_status(database, memory_enabled=True) + + assert status.startswith("Workshop memory current truth: active;") + assert "legacy unclassified=0 (counted 0m ago)" in status + assert "legacy review pending=1 owner(s) (7 rows)" in status + + +def test_status_counts_revisions_per_lifecycle_state(tmp_path: Path) -> None: + from kai.workshop.diagnostics import workshop_memory_current_truth_status + + database = tmp_path / "kai.db" + connection = _database(database) + _insert_revision(connection) + connection.execute( + "INSERT INTO memory_fact_revision_states VALUES ('mrv_old', 'mcl_x', 'superseded', 1), " + "('mrv_gone', 'mcl_y', 'retracted', 2), ('mrv_split', 'mcl_z', 'unresolved_conflict', 3)" + ) + connection.commit() + connection.close() + + status = workshop_memory_current_truth_status(database, memory_enabled=True) + + assert "states=(active=1, superseded=1, retracted=1, expired=0, conflicted=1)" in status + + +def test_status_without_a_vector_audit_is_incomplete(tmp_path: Path) -> None: + from kai.workshop.diagnostics import workshop_memory_current_truth_status + + database = tmp_path / "kai.db" + connection = _database(database) + _insert_revision(connection) + connection.execute("DELETE FROM memory_vector_audit") + connection.commit() + connection.close() + + status = workshop_memory_current_truth_status(database, memory_enabled=True) + + assert status.startswith("Workshop memory current truth: INCOMPLETE;") + assert "vector drift=not checked" in status diff --git a/workshop-client/src/FactReview.test.tsx b/workshop-client/src/FactReview.test.tsx index b276f6e1..f38f202a 100644 --- a/workshop-client/src/FactReview.test.tsx +++ b/workshop-client/src/FactReview.test.tsx @@ -271,7 +271,7 @@ describe("Workshop fact review", () => { it("retries everything and checks the search index on request", async () => { vi.mocked(loadMemoryProjections).mockResolvedValue(syncStatus); vi.mocked(retryMemoryProjections).mockResolvedValue({ failed: 1, retried: 2, succeeded: 1 }); - vi.mocked(loadMemoryProjectionAudit).mockResolvedValue({ duplicate: 1, orphan: ["vec-2"], unknown: [] }); + vi.mocked(loadMemoryProjectionAudit).mockResolvedValue({ duplicate: 1, missing: [], orphan: ["vec-2"], unknown: [] }); const user = userEvent.setup(); renderReview(); @@ -285,4 +285,18 @@ describe("Workshop fact review", () => { expect(retryMemoryProjections).toHaveBeenCalledWith("session-secret", {}); expect(await screen.findByRole("status")).toHaveTextContent("Retried 2: 1 back in search. 1 still failing."); }); + + it("leads the index check with current facts recall cannot return", async () => { + vi.mocked(loadMemoryProjections).mockResolvedValue(syncStatus); + vi.mocked(loadMemoryProjectionAudit).mockResolvedValue({ duplicate: 0, missing: ["vec-7"], orphan: [], unknown: [] }); + const user = userEvent.setup(); + renderReview(); + + await user.click(await screen.findByRole("tab", { name: /Search sync/ })); + await user.click(screen.getByRole("button", { name: "Check search index" })); + + const note = await screen.findByRole("note"); + expect(note).toHaveTextContent("1 current fact(s) have no search row, so Kai cannot recall them."); + expect(note).not.toHaveTextContent("leftover"); + }); }); diff --git a/workshop-client/src/FactReview.tsx b/workshop-client/src/FactReview.tsx index fa4aa3cd..fd1354f4 100644 --- a/workshop-client/src/FactReview.tsx +++ b/workshop-client/src/FactReview.tsx @@ -390,11 +390,21 @@ export function FactReview({ {audit && (

- {audit.orphan.length + audit.unknown.length === 0 && audit.duplicate === 0 + {audit.orphan.length + audit.unknown.length + audit.missing.length === 0 && audit.duplicate === 0 ? "The search index matches your memory." - : `The search index has ${audit.orphan.length} leftover and ${audit.unknown.length} unknown row(s)` + - `${audit.duplicate > 0 ? `, and ${audit.duplicate} item(s) with duplicates` : ""}. ` + - "Kai never recalls them; they only take up space."} + : [ + // Missing rows come first: they are current facts + // Kai cannot recall, unlike leftovers, which only + // take up space. + audit.missing.length > 0 + ? `${audit.missing.length} current fact(s) have no search row, so Kai cannot recall them.` + : "", + audit.orphan.length + audit.unknown.length + audit.duplicate > 0 + ? `The search index has ${audit.orphan.length} leftover and ${audit.unknown.length} unknown row(s)` + + `${audit.duplicate > 0 ? `, and ${audit.duplicate} item(s) with duplicates` : ""}. ` + + "Kai never recalls them; they only take up space." + : "", + ].filter(Boolean).join(" ")}

)} {decisionError && !selectedSync &&

{decisionError}

} diff --git a/workshop-client/src/api.test.ts b/workshop-client/src/api.test.ts index 108a8ffe..2bad591d 100644 --- a/workshop-client/src/api.test.ts +++ b/workshop-client/src/api.test.ts @@ -1254,7 +1254,7 @@ describe("Workshop client API", () => { preview: "Dark themes.", }], })) - .mockResolvedValueOnce(Response.json({ version: 1, orphan: ["vec-2"], unknown: [], duplicate: 1 })) + .mockResolvedValueOnce(Response.json({ version: 1, orphan: ["vec-2"], unknown: [], duplicate: 1, missing: ["vec-9"] })) .mockResolvedValueOnce(Response.json({ version: 1, retried: 1, succeeded: 1, failed: 0 })) .mockResolvedValueOnce(Response.json({ version: 1, failed_total: 1, blocked: 0, failed: [{ kind: "row" }] })); vi.stubGlobal("fetch", fetchMock); @@ -1274,7 +1274,7 @@ describe("Workshop client API", () => { }], }); await expect(loadMemoryProjectionAudit("session-secret")).resolves.toEqual({ - duplicate: 1, orphan: ["vec-2"], unknown: [], + duplicate: 1, missing: ["vec-9"], orphan: ["vec-2"], unknown: [], }); await expect(retryMemoryProjections("session-secret", { episodeIds: ["mep_1"] })).resolves.toEqual({ failed: 0, retried: 1, succeeded: 1, diff --git a/workshop-client/src/api.ts b/workshop-client/src/api.ts index 40feab9e..6ef47d08 100644 --- a/workshop-client/src/api.ts +++ b/workshop-client/src/api.ts @@ -5262,11 +5262,16 @@ export async function loadMemoryProjectionAudit(token: string): Promise typeof item === "string"); if ( !isRecord(payload) || payload.version !== 1 || !isIdList(payload.orphan) || - !isIdList(payload.unknown) || !Number.isSafeInteger(payload.duplicate) + !isIdList(payload.unknown) || !Number.isSafeInteger(payload.duplicate) || !isIdList(payload.missing) ) { throw new Error("Kai returned an unsupported search index check."); } - return { duplicate: payload.duplicate as number, orphan: payload.orphan, unknown: payload.unknown }; + return { + duplicate: payload.duplicate as number, + missing: payload.missing, + orphan: payload.orphan, + unknown: payload.unknown, + }; } // Retrying only resets items that are already failed, so a repeated diff --git a/workshop-client/src/types.ts b/workshop-client/src/types.ts index e88ed4d9..003fa352 100644 --- a/workshop-client/src/types.ts +++ b/workshop-client/src/types.ts @@ -1371,9 +1371,12 @@ export interface WorkshopMemoryProjectionReview { } // Search rows that no longer match canonical state. Recall never uses -// them; they are reported so the owner knows the index has leftovers. +// orphan, unknown, or duplicate rows; they are reported so the owner +// knows the index has leftovers. Missing rows are the opposite: current +// facts whose row is gone, which recall cannot return. export interface WorkshopMemoryProjectionAudit { duplicate: number; + missing: string[]; orphan: string[]; unknown: string[]; }