@codemem/server 0.45.0-rc.2 → 0.46.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/static/app.js CHANGED
@@ -1,14 +1,14 @@
1
- (function(){var dm=Object.defineProperty,vC=(e,t)=>{let n={};for(var r in e)dm(n,r,{get:e[r],enumerable:!0});return t||dm(n,Symbol.toStringTag,{value:"Module"}),n};function Se(e){if(!e||typeof e!="object")return;const t=e.error;return typeof t=="string"?t:void 0}async function je(e,t){const n=t?await fetch(e,t):await fetch(e);if(!n.ok)throw new Error(`${e}: ${n.status} ${n.statusText}`);return n.json()}async function Ce(e){const t=await e.text();try{return{text:t,payload:t?JSON.parse(t):{}}}catch{return{text:t,payload:{}}}}function um(e,t,n,r,i){const o=new URLSearchParams;return o.set("project",e||""),typeof t=="number"&&o.set("limit",String(t)),typeof n=="number"&&o.set("offset",String(n)),r&&o.set("scope",r),i&&o.set("q",i),o.toString()}async function yC(){return je("/api/observer-status")}async function bC(){return je("/api/config")}async function _C(e){const t=await fetch("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.text();let r=null;if(n)try{r=JSON.parse(n)}catch{}if(!t.ok){const i=Se(r)||n||"request failed";throw new Error(i)}return r}async function Rl(){return je("/api/coordinator/admin/status")}async function pm(e){return je(`/api/coordinator/admin/groups${e?"?include_archived=1":""}`)}async function wC(e){const t=await fetch("/api/coordinator/admin/groups",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function SC(e,t){const n=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:t})}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function CC(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/archive`,{method:"POST"}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function RC(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/unarchive`,{method:"POST"}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function IC(e,t=!1){const n=new URLSearchParams;t&&n.set("include_inactive","1");const r=n.size?`?${n.toString()}`:"";return je(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes${r}`)}async function kC(e,t){const n=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function fm(e,t,n=!1){const r=new URLSearchParams;n&&r.set("include_revoked","1");const i=r.size?`?${r.toString()}`:"";return je(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members${i}`)}async function TC(e,t,n){const r=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),{text:i,payload:o}=await Ce(r);if(!r.ok)throw new Error(Se(o)||i||"request failed");return o}async function PC(e,t,n,r={}){const i=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),{text:o,payload:s}=await Ce(i);if(!i.ok)throw new Error(Se(s)||o||"request failed");return s}async function NC(e){const t=new URLSearchParams;e&&t.set("group_id",e);const n=t.size?`?${t.toString()}`:"";return je(`/api/coordinator/admin/join-requests${n}`)}async function mm(e,t=!0){const n=new URLSearchParams;e&&n.set("group_id",e),t&&n.set("include_disabled","1");const r=n.size?`?${n.toString()}`:"";return je(`/api/coordinator/admin/devices${r}`)}async function EC(e,t){const n=await fetch(`/api/coordinator/admin/join-requests/${encodeURIComponent(e)}/${t}`,{method:"POST"}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function AC(e,t,n){const r=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({group_id:t,display_name:n})}),{text:i,payload:o}=await Ce(r);if(!r.ok)throw new Error(Se(o)||i||"request failed");return o}async function xC(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/disable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function DC(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/enable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function LC(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/remove?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function hm(e){const t=await fetch("/api/coordinator/admin/invites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function gm(e,t){const n=um(e,t?.limit,t?.offset,t?.scope,t?.q);return je(`/api/observations?${n}`)}async function $C(e,t){const n=await fetch("/api/memories/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({memory_id:e,visibility:t})}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function OC(e,t){const n=await fetch("/api/memories/project",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({memory_id:e,project:t})}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function jC(e){const t=await fetch("/api/memories/forget",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({memory_id:e})}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function vm(e,t){const n=um(e,t?.limit,t?.offset,t?.scope,t?.q);return je(`/api/summaries?${n}`)}async function MC(e){const t=await fetch("/api/pack/trace",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function FC(e=1200){const t=new AbortController,n=window.setTimeout(()=>t.abort(),e);try{const r=await fetch("/api/runtime",{cache:"no-store",signal:t.signal});if(!r.ok)throw new Error(`/api/runtime: ${r.status} ${r.statusText}`)}finally{window.clearTimeout(n)}}async function BC(){return je("/api/runtime")}async function Va(){return(await je("/api/projects")).projects||[]}function qC(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return!["available","no_data","unavailable"].includes(t.availability)||t.captureVersion!=="opencode-retained-v1"||t.windowLimit!==1e3||typeof t.periodStart!="string"||!Number.isFinite(Date.parse(t.periodStart))||typeof t.periodEnd!="string"||!Number.isFinite(Date.parse(t.periodEnd))||Date.parse(t.periodStart)>Date.parse(t.periodEnd)||![t.freshEvaluations,t.evaluationsWithDuplicates,t.candidateItems,t.duplicatesOmitted,t.beforeTokens,t.afterTokens,t.estimatedTokensAvoided,t.missingRetainedMetadata,t.invalidRetainedMetadata,t.packMetadataGaps,t.unmeasuredAttempts].every(n=>Number.isSafeInteger(n)&&n>=0&&n<=1e9)||t.freshEvaluations+t.unmeasuredAttempts>1e3||[t.evaluationsWithDuplicates,t.missingRetainedMetadata,t.invalidRetainedMetadata,t.packMetadataGaps].some(n=>n>t.freshEvaluations)||t.candidateItems>t.freshEvaluations*50||t.duplicatesOmitted>t.candidateItems||t.afterTokens>t.beforeTokens||t.estimatedTokensAvoided!==t.beforeTokens-t.afterTokens||t.availability==="available"!=t.freshEvaluations>0?null:t}async function UC(){return je("/api/stats")}async function GC(e){return je(`/api/usage?project=${encodeURIComponent(e)}`)}async function HC(e){return je(`/api/session?project=${encodeURIComponent(e)}`)}async function VC(e){return je(`/api/raw-events?project=${encodeURIComponent(e)}`)}var Ka=class extends Error{statusCode;errorCode;constructor(e,t){super(t),this.statusCode=e,this.errorCode=t,this.name="RecipientPolicyTeamRenameApiError"}},KC=new Set(["team_name_invalid","team_not_found","team_rename_stale","team_link_stale","team_link_ambiguous","team_coordinator_rename_failed","team_local_rename_pending","team_rename_failed"]);async function zC(e){let t;try{t=await fetch(`/api/sync/recipient-policy/v1/teams/${encodeURIComponent(e.teamId)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({displayName:e.displayName,expectedDisplayName:e.expectedDisplayName})})}catch{throw new Ka(0,"team_rename_failed")}const{payload:n}=await Ce(t);if(!t.ok){const r=n&&typeof n=="object"&&"error"in n?String(n.error):"";throw new Ka(t.status,KC.has(r)?r:"team_rename_failed")}if(n?.version!==1||typeof n.teamId!="string"||typeof n.displayName!="string"||typeof n.revision!="string"||typeof n.linkedCoordinatorGroupRenamed!="boolean")throw new Ka(t.status,"team_rename_failed");return n}var WC=new Set(["device_display_name_invalid","device_display_name_required","device_display_name_too_long","invite_already_bound","invite_expired","invite_identity_conflict","invite_invalid","inviter_identity_invalid","project_invite_acceptance_failed","project_invite_bootstrap_incomplete","project_invite_self_acceptance_forbidden","project_invite_trust_state_invalid","project_sync_enablement_failed","recipient_display_name_invalid","recipient_display_name_required","recipient_display_name_too_long"]),ym=class extends Error{errorCode;constructor(e,t){super(e),this.errorCode=t,this.name="ProjectInviteAcceptanceError"}};async function Il(e,t="",n){const r=new URLSearchParams;e&&r.set("includeDiagnostics","1"),t&&r.set("project",t),n?.includeJoinRequests&&r.set("includeJoinRequests","1");const i=r.size?`?${r.toString()}`:"";return je(`/api/sync/status${i}`)}async function kl(e,t,n){const r=await fetch("/api/sync/invites/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({invite:e,...t})}),{text:i,payload:o}=await Ce(r);if(!r.ok){const s=typeof o?.detail=="string"?o.detail.trim():"",c=Se(o),l=s||c||i||"request failed";throw n==="project_share_invite"&&c&&WC.has(c)?new ym(l,c):new Error(l)}return o}async function bm(e,t={}){const n=await fetch("/api/sync/invites/inspect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({invite:e,...t})}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function JC(){return je("/api/sync/actors")}async function YC(e=!1){return je(`/api/sync/pairing${e?"?includeDiagnostics=1":""}`)}async function _m(e){const t=await fetch(`/api/sync/peers/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function wm(e,t){const n=await fetch("/api/sync/peers/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({peer_device_id:e,name:t})}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function XC(e,t){const n={peer_device_id:e};t?.fingerprint&&(n.fingerprint=t.fingerprint),t?.expectedGroupId&&(n.expected_group_id=t.expectedGroupId),t?.expectedIncomingRequestId&&(n.expected_incoming_request_id=t.expectedIncomingRequestId);const r=await fetch("/api/sync/peers/accept-discovered",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await r.text();let o={};try{const c=i?JSON.parse(i):null;c&&typeof c=="object"&&!Array.isArray(c)&&(o=c)}catch{o={}}const s=typeof o.detail=="string"?o.detail:void 0;if(!r.ok)throw new Error(s||Se(o)||i||"request failed");return o}var Sm=class extends Error{preview;constructor(e){super("Project forget confirmation required"),this.name="ProjectForgetConfirmationError",this.preview=e}},za=class extends Error{requiredGuardrails;requiredGuardrailTokens;guardrailWarnings;constructor(e){super("Sharing domain guardrail confirmation required"),this.name="SharingDomainGuardrailConfirmationError",this.requiredGuardrails=e.required_guardrails??[],this.requiredGuardrailTokens=e.required_guardrail_tokens??[],this.guardrailWarnings=e.guardrail_warnings??[]}},Cm=class extends Error{preview;constructor(e){super("Legacy shared review confirmation required"),this.name="LegacySharedReviewConfirmationError",this.preview=e}},Tl=class extends Error{statusCode;errorCode;result;constructor(e,t,n){super(t),this.statusCode=e,this.errorCode=t,this.result=n,this.name="DeviceIdentityBindingApiError"}},Pl=1,Rm=new Set(["team_setup_incomplete","team_setup_roster_changed","team_setup_assignment_changed","team_setup_roster_unavailable","team_setup_conflict","team_setup_confirmation_stale","team_setup_completion_unavailable","team_setup_completion_conflict","team_setup_completion_invalid","team_setup_failed"]),QC=new Set(["coordinator_route_missing","coordinator_rejected_manifest","coordinator_unreachable","local_candidate_scan_budget_exceeded","coordinator_roster_unavailable"]),ZC=new Set(["needs_setup","in_progress","stale","ready"]),eR=new Set(["reviewing","ready_to_finish","unavailable","completed"]),tR=new Set(["setup_incomplete","setup_unavailable","setup_completed","device_inactive","device_active","assignment_evidence_inactive","assignment_required","assignment_unavailable","decision_unresolved","mapping_unavailable","automatic_mapping"]);function nt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Kn(e,t){const n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((i,o)=>i===r[o])}function zt(e){return typeof e=="string"||e===null}function wr(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function on(e,t){return Array.isArray(e)&&e.every(t)}function Im(e){return nt(e)?typeof e.candidateRef=="string"&&typeof e.displayName=="string"&&typeof e.status=="string"&&ZC.has(e.status)&&wr(e.deviceCount)&&wr(e.projectCount)&&wr(e.unresolvedDeviceCount)&&wr(e.unresolvedProjectCount):!1}function nR(e){return nt(e)&&e.version===Pl&&on(e.candidates,t=>Im(t)&&t.status!=="ready")}function rR(e){return nt(e)?e.kind==="absent"||e.kind==="existing"&&wr(e.assignmentVersion)&&typeof e.identityRef=="string":!1}function zn(e){return!nt(e)||!Kn(e,["blockedReason","enabled"])?!1:e.enabled===!0?e.blockedReason===null:e.enabled===!1&&typeof e.blockedReason=="string"&&tR.has(e.blockedReason)}function iR(e){return!nt(e)||!Kn(e,["assignIdentity","clearDecision","exclude","include","remove"])?!1:zn(e.assignIdentity)&&zn(e.include)&&zn(e.exclude)&&zn(e.remove)&&zn(e.clearDecision)}function oR(e){return nt(e)?typeof e.deviceRef=="string"&&typeof e.displayName=="string"&&typeof e.enabled=="boolean"&&zt(e.existingIdentityRef)&&zt(e.suggestedIdentityRef)&&(e.verifiedEvidenceKind==="active_assignment"||e.verifiedEvidenceKind===null)&&typeof e.decision=="string"&&["unresolved","included","excluded","removed"].includes(e.decision)&&zt(e.targetIdentityRef)&&rR(e.expectation)&&iR(e.actions):!1}function aR(e){return nt(e)?typeof e.projectRef=="string"&&typeof e.displayName=="string"&&typeof e.resolution=="string"&&["unresolved","deterministic","explicit"].includes(e.resolution)&&zt(e.canonicalProjectRef)&&zt(e.resolvedProjectRef)&&on(e.mappingChoices,t=>nt(t)&&typeof t.resolvedProjectRef=="string"&&typeof t.displayName=="string")&&nt(e.actions)&&Kn(e.actions,["map"])&&zn(e.actions.map):!1}function sR(e){if(!nt(e))return!1;const t=n=>typeof n=="string"&&["add","update","remove"].includes(n);return on(e.teamChanges,n=>nt(n)&&typeof n.teamRef=="string"&&typeof n.teamDisplayName=="string"&&t(n.change)&&[null,"person_all_devices","reviewed_allowlist"].includes(n.fromDeviceEligibilityMode)&&n.toDeviceEligibilityMode==="reviewed_allowlist")&&on(e.membershipChanges,n=>nt(n)&&typeof n.teamRef=="string"&&typeof n.teamDisplayName=="string"&&typeof n.identityRef=="string"&&typeof n.identityDisplayName=="string"&&t(n.change))&&on(e.projectChanges,n=>nt(n)&&typeof n.projectRef=="string"&&typeof n.projectDisplayName=="string"&&zt(n.fromCanonicalProjectRef)&&zt(n.fromResolvedProjectRef)&&zt(n.fromResolvedProjectDisplayName)&&zt(n.toCanonicalProjectRef)&&zt(n.toResolvedProjectRef)&&zt(n.toResolvedProjectDisplayName)&&t(n.change))&&on(e.recipientChanges,n=>nt(n)&&typeof n.canonicalProjectRef=="string"&&typeof n.canonicalProjectDisplayName=="string"&&(n.canonicalProjectKind==="project"||n.canonicalProjectKind==="legacy_default_sharing")&&n.recipientKind==="team"&&typeof n.recipientRef=="string"&&typeof n.recipientDisplayName=="string"&&t(n.change))&&on(e.deviceAccessChanges,n=>nt(n)&&typeof n.canonicalProjectRef=="string"&&typeof n.canonicalProjectDisplayName=="string"&&(n.canonicalProjectKind==="project"||n.canonicalProjectKind==="legacy_default_sharing")&&typeof n.deviceRef=="string"&&typeof n.deviceDisplayName=="string"&&typeof n.change=="string"&&["add","remove"].includes(n.change))}function cR(e){return nt(e)&&Kn(e,["finish","refresh"])&&zn(e.refresh)&&zn(e.finish)}function km(e,t,n){return e.every(r=>Object.values(r.actions).every(i=>!i.enabled&&i.blockedReason===n))&&t.every(r=>!r.actions.map.enabled&&r.actions.map.blockedReason===n)}function fi(e){if(!nt(e)||!(e.version===Pl&&Im(e.candidate)&&typeof e.attemptId=="string"&&typeof e.state=="string"&&eR.has(e.state)&&wr(e.unresolvedDeviceCount)&&wr(e.unresolvedProjectCount)&&on(e.devices,oR)&&on(e.projects,aR)&&cR(e.actions)&&on(e.identityChoices,o=>nt(o)&&typeof o.identityRef=="string"&&typeof o.displayName=="string")))return!1;const t=e.actions,n=e.devices,r=e.projects,i=["actions","attemptId","candidate","devices","identityChoices","projects","state","unresolvedDeviceCount","unresolvedProjectCount","version"];return e.state==="ready_to_finish"?Kn(e,[...i,"accessDelta","accessDeltaDigest","finishDigest","viewerAccessDeltaDigest"])&&t.refresh.enabled===!0&&t.finish.enabled===!0&&typeof e.finishDigest=="string"&&typeof e.accessDeltaDigest=="string"&&typeof e.viewerAccessDeltaDigest=="string"&&sR(e.accessDelta):e.state==="unavailable"?Kn(e,[...i,"unavailableReason"])&&typeof e.unavailableReason=="string"&&Rm.has(e.unavailableReason)&&t.refresh.enabled===!0&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_unavailable"&&km(n,r,"setup_unavailable"):e.state==="completed"?Kn(e,i)&&t.refresh.enabled===!1&&t.refresh.blockedReason==="setup_completed"&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_completed"&&km(n,r,"setup_completed"):Kn(e,i)&&e.state==="reviewing"&&t.refresh.enabled===!0&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_incomplete"}function lR(e){return nt(e)&&e.version===Pl&&e.status==="completed"&&typeof e.teamRef=="string"&&typeof e.attemptId=="string"&&typeof e.accessDeltaDigest=="string"&&typeof e.completedAt=="string"}var wt=class extends Error{statusCode;errorCode;reason;constructor(e,t,n){super(t),this.statusCode=e,this.errorCode=t,this.reason=n,this.name="LegacyTeamSetupApiError"}};function Wn(e){return e?`/api/sync/team-setup/v1/${encodeURIComponent(e)}`:"/api/sync/team-setup/v1"}async function Jn(e,t,n){let r;try{r=await fetch(e,n)}catch{throw new wt(0,"team_setup_failed")}let i;try{const o=await r.text();if(!o)throw new Error("empty Team setup response");i=JSON.parse(o)}catch{throw new wt(r.status,"team_setup_failed")}if(!r.ok){const o=i&&typeof i=="object"&&"error"in i&&typeof i.error=="string"?i.error:"",s=Rm.has(o)?o:"team_setup_failed",c=i&&typeof i=="object"&&"reason"in i&&typeof i.reason=="string"?i.reason:"",l=QC.has(c)?c:void 0;throw new wt(r.status,s,l)}if(!t(i))throw new wt(r.status,"team_setup_failed");return i}function mi(e,t){return{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}}function Tm(){return Jn(Wn(),nR)}function dR(e){return Jn(Wn(e),fi)}function uR(e,t,n){return Jn(`${Wn(e)}/devices/${encodeURIComponent(t)}/assignment`,fi,mi("PUT",n))}function pR(e,t,n){return Jn(`${Wn(e)}/devices/${encodeURIComponent(t)}/decision`,fi,mi("PUT",n))}function fR(e,t,n){return Jn(`${Wn(e)}/devices/${encodeURIComponent(t)}/decision`,fi,mi("DELETE",n))}function mR(e,t,n){return Jn(`${Wn(e)}/projects/${encodeURIComponent(t)}/mapping`,fi,mi("PUT",n))}function hR(e){return Jn(`${Wn(e)}/refresh`,fi,mi("POST",{}))}function gR(e,t){return Jn(`${Wn(e)}/finish`,lR,mi("POST",t))}var Nl=class extends Error{result;constructor(e){super("Recipient policy changed after review"),this.name="RecipientPolicyEdgesStaleError",this.result=e}};function El(){return je("/api/sync/recipient-policy/v1/intent")}function Al(){return je("/api/sync/recipient-policy/v1/device-inventory")}async function Pm(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await Ce(n);if(!n.ok){const o=i?.errorCode||i?.error||Se(i)||r||"request_failed",s=i&&"status"in i?i:null;throw new Tl(n.status,o,s)}return i}function Nm(e){return Pm("/api/sync/recipient-policy/v1/device-bindings/preview",e)}function Em(e){return Pm("/api/sync/recipient-policy/v1/device-bindings/commit",e)}function vR(){return je("/api/sync/recipient-policy/v1/reconciliation-status")}async function Am(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await Ce(n);if(!n.ok){if(n.status===409&&i&&typeof i=="object"&&i.status==="stale")throw new Nl(i);if(n.status===409&&i&&typeof i=="object"&&i.status==="conflict")return i;const o=i&&typeof i=="object"&&"errorCode"in i?String(i.errorCode??""):"";throw new Error(o||Se(i)||r||"request failed")}return i}function yR(e){return Am("/api/sync/recipient-policy/v1/edges/preview",e)}function bR(e){return Am("/api/sync/recipient-policy/v1/edges/commit",e)}async function xm(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}function _R(e){return xm("/api/sync/recipient-policy/v1/invites/preview",e)}function wR(e){return xm("/api/sync/recipient-policy/v1/invites",e)}async function SR(){const e=await je("/api/sync/recipient-policy/v1/review"),t=e.continuity??null;if(e.categoryCounts)return{...e,continuity:t,categoryCounts:{actionableReview:e.reviewItems.length,preservedContinuity:Math.max(0,e.categoryCounts.preservedContinuity),blockedRepair:e.blockedItems.length}};const n=Math.max(0,(t?.findingCount??0)-e.reviewItems.length);return{...e,continuity:t,categoryCounts:{actionableReview:e.reviewItems.length,preservedContinuity:n,blockedRepair:e.blockedItems.length}}}async function CR(){return je("/api/sync/sharing-domains/settings")}async function bo(e={}){const t=new URLSearchParams;for(const[r,i]of Object.entries(e))i==null||i===""||t.set(r,String(i));const n=t.toString();return je(`/api/sync/projects${n?`?${n}`:""}`)}async function Dm(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}function RR(e){return Dm("/api/sync/project-invites/preview",e)}function IR(e){return Dm("/api/sync/project-invites",e)}function Lm(){return je("/api/sync/share-operations")}function kR(e){return je(`/api/sync/share-operations/${encodeURIComponent(e)}`)}async function TR(e){const t=await fetch(`/api/sync/share-operations/${encodeURIComponent(e)}/advance`,{method:"POST"}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");if(!r?.operation)throw new Error("response missing share operation");return r.operation}async function PR(e){const t=await fetch("/api/sync/sharing-domains/project-mappings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new za(r):new Error(Se(r)||n||"request failed");const i=r?.mapping;if(!i)throw new Error("response missing mapping");return{...i,guardrail_warnings:r.guardrail_warnings??i.guardrail_warnings}}async function NR(e){const t=await fetch("/api/sync/sharing-domains/project-mappings/bulk",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new za(r):new Error(Se(r)||n||"request failed");if(!Array.isArray(r?.mappings))throw new Error("response missing mappings");return r.mappings}async function ER(e){const t=await fetch(`/api/sync/sharing-domains/project-mappings/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return!!r?.deleted}async function AR(e){const t=await fetch("/api/sync/projects/reassign-project",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project reassignment");return r}async function xR(e){const t=await fetch("/api/sync/projects/forget",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw r?.error==="project_forget_confirmation_required"&&r.preview?new Sm(r.preview):new Error(Se(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project forget result");return r}async function DR(e){const t=await fetch("/api/sync/legacy-shared-review/reassign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw r?.error==="legacy_review_confirmation_required"&&r.preview?new Cm(r.preview):new Error(Se(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing legacy review reassignment");return r}async function LR(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/preferences`),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");const i=r?.preferences;if(!i)throw new Error("response missing preferences");return i}async function $R(e,t){const n=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/preferences`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");const o=i?.preferences;if(!o)throw new Error("response missing preferences");return o}async function OR(e){const t=await fetch("/api/sync/actors",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:e})}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function jR(e,t){const n=await fetch("/api/sync/actors/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({actor_id:e,display_name:t})}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function $m(e,t){const n=await fetch("/api/sync/actors/merge",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({primary_actor_id:e,secondary_actor_id:t})}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function MR(e){const t=await fetch("/api/sync/actors/deactivate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({actor_id:e})}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function FR(e){const t=await fetch("/api/sync/legacy-devices/claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({origin_device_id:e})}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function xl(e){const t=typeof e=="string"?e.trim():e?.address?.trim(),n=typeof e=="string"?"":e?.peerDeviceId?.trim(),r={};t&&(r.address=t),n&&(r.peer_device_id=n);const i=await fetch("/api/sync/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),{text:o,payload:s}=await Ce(i);if(!i.ok)throw new Error(Se(s)||o||"request failed");if(!o)throw new Error("empty sync response");if(!Array.isArray(s?.items))throw new Error(o||"invalid sync response");return s}async function BR(){return je("/api/update-status")}function qR(e){return{current_version:"unknown",channel:null,latest_version:null,update_available:!1,first_seen_at:null,checked_at:null,stale:!1,install_kind:"unknown",auto_update_eligible:!1,recommended_action:"Check network access and try again.",error:e instanceof Error?e.message:"Update status request failed."}}function Wa(e){return e!==null&&typeof e=="object"?e:null}function Om(e){const t=Wa(e),n=Wa(t?.status),r=Wa(Wa(t?.coordinator_enrollment_reconciliation_issues??n?.coordinator_enrollment_reconciliation_issues)?.counts)?.open;return typeof r=="number"&&Number.isSafeInteger(r)&&r>0?r:0}var _o,ge,jm,Mm,Yn,Fm,Bm,qm,Dl,Ja,wo,Um,Ll,$l,Ol,Gm,Ya={},Xa=[],UR=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,So=Array.isArray;function an(e,t){for(var n in t)e[n]=t[n];return e}function jl(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function y(e,t,n){var r,i,o,s={};for(o in t)o=="key"?r=t[o]:o=="ref"?i=t[o]:s[o]=t[o];if(arguments.length>2&&(s.children=arguments.length>3?_o.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(o in e.defaultProps)s[o]===void 0&&(s[o]=e.defaultProps[o]);return Co(e,s,r,i,null)}function Co(e,t,n,r,i){var o={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++jm,__i:-1,__u:0};return i==null&&ge.vnode!=null&&ge.vnode(o),o}function Hm(){return{current:null}}function z(e){return e.children}function Mt(e,t){this.props=e,this.context=t}function Sr(e,t){if(t==null)return e.__?Sr(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?Sr(e):null}function GR(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],i=[],o=an({},t);o.__v=t.__v+1,ge.vnode&&ge.vnode(o),Fl(e.__P,o,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??Sr(t),!!(32&t.__u),i),o.__v=t.__v,o.__.__k[o.__i]=o,Xm(r,o,i),t.__e=t.__=null,o.__e!=n&&Vm(o)}}function Vm(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),Vm(e)}function Ml(e){(!e.__d&&(e.__d=!0)&&Yn.push(e)&&!Qa.__r++||Fm!=ge.debounceRendering)&&((Fm=ge.debounceRendering)||Bm)(Qa)}function Qa(){try{for(var e,t=1;Yn.length;)Yn.length>t&&Yn.sort(qm),e=Yn.shift(),t=Yn.length,GR(e)}finally{Yn.length=Qa.__r=0}}function Km(e,t,n,r,i,o,s,c,l,d,u){var p,f,m,v,g,h,b=r&&r.__k||Xa,w=t.length;for(l=HR(n,t,b,l,w),p=0;p<w;p++)(m=n.__k[p])!=null&&(f=m.__i!=-1&&b[m.__i]||Ya,m.__i=p,h=Fl(e,m,f,i,o,s,c,l,d,u),v=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&Bl(f.ref,null,m),u.push(m.ref,m.__c||v,m)),g==null&&v!=null&&(g=v),4&m.__u?(l=zm(m,l,e),f.__e&&(f.__e=null)):typeof m.type=="function"&&h!==void 0?l=h:v&&(l=v.nextSibling),m.__u&=-7);return n.__e=g,l}function HR(e,t,n,r,i){var o,s,c,l,d,u=n.length,p=u,f=0;for(e.__k=new Array(i),o=0;o<i;o++)(s=t[o])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[o]=Co(null,s,null,null,null):So(s)?s=e.__k[o]=Co(z,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[o]=Co(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[o]=s,l=o+f,s.__=e,s.__b=e.__b+1,c=null,(d=s.__i=VR(s,n,l,p))!=-1&&(p--,(c=n[d])&&(c.__u|=2)),c==null||c.__v==null?(d==-1&&(i>u?f--:i<u&&f++),typeof s.type!="function"&&(s.__u|=4)):d!=l&&(d==l-1?f--:d==l+1?f++:(d>l?f--:f++,s.__u|=4))):e.__k[o]=null;if(p)for(o=0;o<u;o++)(c=n[o])!=null&&(2&c.__u)==0&&(c.__e==r&&(r=Sr(c)),Zm(c,c));return r}function zm(e,t,n){var r,i;if(typeof e.type=="function"){for(r=e.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=e,t=zm(r[i],t,n));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=Sr(e)),t=n.insertBefore(e.__e,t||null));do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function Cn(e,t){return t=t||[],e==null||typeof e=="boolean"||(So(e)?e.some(function(n){Cn(n,t)}):t.push(e)),t}function VR(e,t,n,r){var i,o,s,c=e.key,l=e.type,d=t[n],u=d!=null&&(2&d.__u)==0;if(d===null&&c==null||u&&c==d.key&&l==d.type)return n;if(r>(u?1:0)){for(i=n-1,o=n+1;i>=0||o<t.length;)if((d=t[s=i>=0?i--:o++])!=null&&(2&d.__u)==0&&c==d.key&&l==d.type)return s}return-1}function Wm(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||UR.test(t)?n:n+"px"}function Za(e,t,n,r,i){var o,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||Wm(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Wm(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")o=t!=(t=t.replace(Um,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+o]=n,n?r?n[wo]=r[wo]:(n[wo]=Ll,e.addEventListener(t,o?Ol:$l,o)):e.removeEventListener(t,o?Ol:$l,o);else{if(i=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Jm(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[Ja]==null)t[Ja]=Ll++;else if(t[Ja]<n[wo])return;return n(ge.event?ge.event(t):t)}}}function Fl(e,t,n,r,i,o,s,c,l,d){var u,p,f,m,v,g,h,b,w,_,R,I,T,A,O,F,N=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),o=[c=t.__e=n.__e]),(u=ge.__b)&&u(t);e:if(typeof N=="function"){p=s.length;try{if(w=t.props,_=N.prototype&&N.prototype.render,R=(u=N.contextType)&&r[u.__c],I=u?R?R.props.value:u.__:r,n.__c?b=(f=t.__c=n.__c).__=f.__E:(_?t.__c=f=new N(w,I):(t.__c=f=new Mt(w,I),f.constructor=N,f.render=zR),R&&R.sub(f),f.state||(f.state={}),f.__n=r,m=f.__d=!0,f.__h=[],f._sb=[]),_&&f.__s==null&&(f.__s=f.state),_&&N.getDerivedStateFromProps!=null&&(f.__s==f.state&&(f.__s=an({},f.__s)),an(f.__s,N.getDerivedStateFromProps(w,f.__s))),v=f.props,g=f.state,f.__v=t,m)_&&N.getDerivedStateFromProps==null&&f.componentWillMount!=null&&f.componentWillMount(),_&&f.componentDidMount!=null&&f.__h.push(f.componentDidMount);else{if(_&&N.getDerivedStateFromProps==null&&w!==v&&f.componentWillReceiveProps!=null&&f.componentWillReceiveProps(w,I),t.__v==n.__v||!f.__e&&f.shouldComponentUpdate!=null&&f.shouldComponentUpdate(w,f.__s,I)===!1){t.__v!=n.__v&&(f.props=w,f.state=f.__s,f.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(L){L&&(L.__=t)}),Xa.push.apply(f.__h,f._sb),f._sb=[],f.__h.length&&s.push(f),c=Sr(n);break e}f.componentWillUpdate!=null&&f.componentWillUpdate(w,f.__s,I),_&&f.componentDidUpdate!=null&&f.__h.push(function(){f.componentDidUpdate(v,g,h)})}if(f.context=I,f.props=w,f.__P=e,f.__e=!1,T=ge.__r,A=0,_)f.state=f.__s,f.__d=!1,T&&T(t),u=f.render(f.props,f.state,f.context),Xa.push.apply(f.__h,f._sb),f._sb=[];else do f.__d=!1,T&&T(t),u=f.render(f.props,f.state,f.context),f.state=f.__s;while(f.__d&&++A<25);f.state=f.__s,f.getChildContext!=null&&(r=an(an({},r),f.getChildContext())),_&&!m&&f.getSnapshotBeforeUpdate!=null&&(h=f.getSnapshotBeforeUpdate(v,g)),O=u!=null&&u.type===z&&u.key==null?Qm(u.props.children):u,c=Km(e,So(O)?O:[O],t,n,r,i,o,s,c,l,d),f.base=t.__e,t.__u&=-161,f.__h.length&&s.push(f),b&&(f.__E=f.__=null)}catch(L){if(s.length=p,t.__v=null,l||o!=null){if(L.then){for(t.__u|=l?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;o!=null&&(o[o.indexOf(c)]=null),t.__e=c}else if(o!=null)for(F=o.length;F--;)jl(o[F])}else t.__e=n.__e;t.__k??=n.__k||[],L.then||Ym(t),ge.__e(L,t,n)}}else o==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=KR(n.__e,t,n,r,i,o,s,l,d);return(u=ge.diffed)&&u(t),128&t.__u?void 0:c}function Ym(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Ym))}function Xm(e,t,n){for(var r=0;r<n.length;r++)Bl(n[r],n[++r],n[++r]);ge.__c&&ge.__c(t,e),e.some(function(i){try{e=i.__h,i.__h=[],e.some(function(o){o.call(i)})}catch(o){ge.__e(o,i.__v)}})}function Qm(e){return typeof e!="object"||e==null||e.__b>0?e:So(e)?e.map(Qm):e.constructor!==void 0?null:an({},e)}function KR(e,t,n,r,i,o,s,c,l){var d,u,p,f,m,v,g,h=n.props||Ya,b=t.props,w=t.type;if(w=="svg"?i="http://www.w3.org/2000/svg":w=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),o!=null){for(d=0;d<o.length;d++)if((m=o[d])&&"setAttribute"in m==!!w&&(w?m.localName==w:m.nodeType==3)){e=m,o[d]=null;break}}if(e==null){if(w==null)return document.createTextNode(b);e=document.createElementNS(i,w,b.is&&b),c&&(ge.__m&&ge.__m(t,o),c=!1),o=null}if(w==null)h===b||c&&e.data==b||(e.data=b);else{if(o=w=="textarea"&&b.defaultValue!=null?null:o&&_o.call(e.childNodes),!c&&o!=null)for(h={},d=0;d<e.attributes.length;d++)h[(m=e.attributes[d]).name]=m.value;for(d in h)m=h[d],d=="dangerouslySetInnerHTML"?p=m:d=="children"||d in b||d=="value"&&"defaultValue"in b||d=="checked"&&"defaultChecked"in b||Za(e,d,null,m,i);for(d in b)m=b[d],d=="children"?f=m:d=="dangerouslySetInnerHTML"?u=m:d=="value"?v=m:d=="checked"?g=m:c&&typeof m!="function"||h[d]===m||Za(e,d,m,h[d],i);if(u)c||p&&(u.__html==p.__html||u.__html==e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(p&&(e.innerHTML=""),Km(t.type=="template"?e.content:e,So(f)?f:[f],t,n,r,w=="foreignObject"?"http://www.w3.org/1999/xhtml":i,o,s,o?o[0]:n.__k&&Sr(n,0),c,l),o!=null)for(d=o.length;d--;)jl(o[d]);c&&w!="textarea"||(d="value",w=="progress"&&v==null?e.removeAttribute("value"):v!=null&&(v!==e[d]||w=="progress"&&!v||w=="option"&&v!=h[d])&&Za(e,d,v,h[d],i),d="checked",g!=null&&g!=e[d]&&Za(e,d,g,h[d],i))}return e}function Bl(e,t,n){try{if(typeof e=="function"){var r=typeof e.__u=="function";r&&e.__u(),r&&t==null||(e.__u=e(t))}else e.current=t}catch(i){ge.__e(i,n)}}function Zm(e,t,n){var r,i;if(ge.unmount&&ge.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||Bl(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(o){ge.__e(o,t)}r.base=r.__P=r.__n=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&Zm(r[i],t,n||typeof e.type!="function");n||jl(e.__e),e.__c=e.__=e.__e=void 0}function zR(e,t,n){return this.constructor(e,n)}function Ue(e,t,n){var r,i,o,s;t==document&&(t=document.documentElement),ge.__&&ge.__(e,t),i=(r=typeof n=="function")?null:n&&n.__k||t.__k,o=[],s=[],Fl(t,e=(!r&&n||t).__k=y(z,null,[e]),i||Ya,Ya,t.namespaceURI,!r&&n?[n]:i?null:t.firstChild?_o.call(t.childNodes):null,o,!r&&n?n:i?i.__e:t.firstChild,r,s),Xm(o,e,s),e.props.children=null}function eh(e,t){Ue(e,t,eh)}function WR(e,t,n){var r,i,o,s,c=an({},e.props);for(o in e.type&&e.type.defaultProps&&(s=e.type.defaultProps),t)o=="key"?r=t[o]:o=="ref"?i=t[o]:c[o]=t[o]===void 0&&s!=null?s[o]:t[o];return arguments.length>2&&(c.children=arguments.length>3?_o.call(arguments,2):n),Co(e.type,c,r||e.key,i||e.ref,null)}function Cr(e){function t(n){var r,i;return this.getChildContext||(r=new Set,(i={})[t.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&r.forEach(function(s){s.__e=!0,Ml(s)})},this.sub=function(o){r.add(o);var s=o.componentWillUnmount;o.componentWillUnmount=function(){r&&r.delete(o),s&&s.call(o)}}),n.children}return t.__c="__cC"+Gm++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}_o=Xa.slice,ge={__e:function(e,t,n,r){for(var i,o,s;t=t.__;)if((i=t.__c)&&!i.__)try{if((o=i.constructor)&&o.getDerivedStateFromError!=null&&(i.setState(o.getDerivedStateFromError(e)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(e,r||{}),s=i.__d),s)return i.__E=i}catch(c){e=c}throw e}},jm=0,Mm=function(e){return e!=null&&e.constructor===void 0},Mt.prototype.setState=function(e,t){var n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=an({},this.state);typeof e=="function"&&(e=e(an({},n),this.props)),e&&an(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Ml(this))},Mt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Ml(this))},Mt.prototype.render=z,Yn=[],Bm=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,qm=function(e,t){return e.__v.__b-t.__v.__b},Qa.__r=0,Dl=Math.random().toString(8),Ja="__d"+Dl,wo="__a"+Dl,Um=/(PointerCapture)$|Capture$/i,Ll=0,$l=Jm(!1),Ol=Jm(!0),Gm=0;var Rn,Be,ql,th,hi=0,nh=[],Je=ge,rh=Je.__b,ih=Je.__r,oh=Je.diffed,ah=Je.__c,sh=Je.unmount,ch=Je.__;function Rr(e,t){Je.__h&&Je.__h(Be,e,hi||t),hi=0;var n=Be.__H||(Be.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function x(e){return hi=1,In(dh,e)}function In(e,t,n){var r=Rr(Rn++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):dh(void 0,t),function(c){var l=r.__N?r.__N[0]:r.__[0],d=r.t(l,c);l!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=Be,!Be.__f)){var i=function(c,l,d){if(!r.__c.__H)return!0;var u=!1,p=r.__c.props!==c;if(r.__c.__H.__.some(function(m){if(m.__N){u=!0;var v=m.__[0];m.__=m.__N,m.__N=void 0,v!==m.__[0]&&(p=!0)}}),o){var f=o.call(this,c,l,d);return u?f||p:f}return!u||p};Be.__f=!0;var o=Be.shouldComponentUpdate,s=Be.componentWillUpdate;Be.componentWillUpdate=function(c,l,d){if(this.__e){var u=o;o=void 0,i(c,l,d),o=u}s&&s.call(this,c,l,d)},Be.shouldComponentUpdate=i}return r.__N||r.__}function V(e,t){var n=Rr(Rn++,3);!Je.__s&&Hl(n.__H,t)&&(n.__=e,n.u=t,Be.__H.__h.push(n))}function It(e,t){var n=Rr(Rn++,4);!Je.__s&&Hl(n.__H,t)&&(n.__=e,n.u=t,Be.__h.push(n))}function B(e){return hi=5,ke(function(){return{current:e}},[])}function es(e,t,n){hi=6,It(function(){if(typeof e=="function"){var r=e(t());return function(){e(null),r&&typeof r=="function"&&r()}}if(e)return e.current=t(),function(){return e.current=null}},n==null?n:n.concat(e))}function ke(e,t){var n=Rr(Rn++,7);return Hl(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function ae(e,t){return hi=8,ke(function(){return e},t)}function kn(e){var t=Be.context[e.__c],n=Rr(Rn++,9);return n.c=e,t?(n.__??(n.__=!0,t.sub(Be)),t.props.value):e.__}function Ul(e,t){Je.useDebugValue&&Je.useDebugValue(t?t(e):e)}function JR(e){var t=Rr(Rn++,10),n=x();return t.__=e,Be.componentDidCatch||(Be.componentDidCatch=function(r,i){t.__&&t.__(r,i),n[1](r)}),[n[0],function(){n[1](void 0)}]}function Ir(){var e=Rr(Rn++,11);if(!e.__){for(var t=Be.__v;t!==null&&!t.__m&&t.__!==null;)t=t.__;var n=t.__m||(t.__m=[0,0]);e.__="P"+n[0]+"-"+n[1]++}return e.__}function YR(){for(var e;e=nh.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(ts),t.__h.some(Gl),t.__h=[]}catch(n){t.__h=[],Je.__e(n,e.__v)}}}Je.__b=function(e){Be=null,rh&&rh(e)},Je.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),ch&&ch(e,t)},Je.__r=function(e){ih&&ih(e),Rn=0;var t=(Be=e.__c).__H;t&&(ql===Be?(t.__h=[],Be.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(ts),t.__h.some(Gl),t.__h=[],Rn=0)),ql=Be},Je.diffed=function(e){oh&&oh(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(nh.push(t)!==1&&th===Je.requestAnimationFrame||((th=Je.requestAnimationFrame)||XR)(YR)),t.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),ql=Be=null},Je.__c=function(e,t){t.some(function(n){try{n.__h.some(ts),n.__h=n.__h.filter(function(r){return!r.__||Gl(r)})}catch(r){t.some(function(i){i.__h&&(i.__h=[])}),t=[],Je.__e(r,n.__v)}}),ah&&ah(e,t)},Je.unmount=function(e){sh&&sh(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{ts(r)}catch(i){t=i}}),n.__H=void 0,t&&Je.__e(t,n.__v))};var lh=typeof requestAnimationFrame=="function";function XR(e){var t,n=function(){clearTimeout(r),lh&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);lh&&(t=requestAnimationFrame(n))}function ts(e){var t=Be,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),Be=t}function Gl(e){var t=Be;e.__c=e.__(),Be=t}function Hl(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function dh(e,t){return typeof t=="function"?t(e):t}var QR=0,M2=Array.isArray;function a(e,t,n,r,i,o){t||(t={});var s,c,l=t;if("ref"in l)for(c in l={},t)c=="ref"?s=t[c]:l[c]=t[c];var d={type:e,props:l,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--QR,__i:-1,__u:0,__source:i,__self:o};if(typeof e=="function"&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return ge.vnode&&ge.vnode(d),d}function kr({ariaDisabled:e=!1,ariaLabel:t,className:n="modal-close-button",disabled:r=!1,onClick:i,label:o="Close"}){return a("button",{"aria-disabled":e?"true":void 0,"aria-label":t,className:n,disabled:r,onClick:()=>{e||i()},type:"button",children:[a("i",{"aria-hidden":"true",className:"modal-close-button-icon","data-lucide":"x"}),a("span",{className:"modal-close-button-label",children:o})]})}var gi=vC({Children:()=>Tr,Component:()=>Mt,Fragment:()=>z,PureComponent:()=>ns,StrictMode:()=>z,Suspense:()=>Ro,SuspenseList:()=>vi,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:()=>Ph,cloneElement:()=>Pr,createContext:()=>Cr,createElement:()=>y,createFactory:()=>Nh,createPortal:()=>sn,createRef:()=>Hm,default:()=>dI,findDOMNode:()=>Dh,flushSync:()=>rs,forwardRef:()=>J,hydrate:()=>Ch,isElement:()=>$h,isFragment:()=>Eh,isMemo:()=>Ah,isValidElement:()=>Tn,lazy:()=>bh,memo:()=>ph,render:()=>Sh,startTransition:()=>Wl,unmountComponentAtNode:()=>xh,unstable_batchedUpdates:()=>Lh,useCallback:()=>ae,useContext:()=>kn,useDebugValue:()=>Ul,useDeferredValue:()=>Jl,useEffect:()=>V,useErrorBoundary:()=>JR,useId:()=>Ir,useImperativeHandle:()=>es,useInsertionEffect:()=>Xl,useLayoutEffect:()=>It,useMemo:()=>ke,useReducer:()=>In,useRef:()=>B,useState:()=>x,useSyncExternalStore:()=>Kl,useTransition:()=>Yl,version:()=>lI});function uh(e,t){for(var n in t)e[n]=t[n];return e}function Vl(e,t){for(var n in e)if(n!=="__source"&&!(n in t))return!0;for(var r in t)if(r!=="__source"&&e[r]!==t[r])return!0;return!1}function Kl(e,t){var n=t(),r=x({t:{__:n,u:t}}),i=r[0].t,o=r[1];return It(function(){i.__=n,i.u=t,zl(i)&&o({t:i})},[e,n,t]),V(function(){return zl(i)&&o({t:i}),e(function(){zl(i)&&o({t:i})})},[e]),n}function zl(e){try{return!((t=e.__)===(n=e.u())&&(t!==0||1/t==1/n)||t!=t&&n!=n)}catch{return!0}var t,n}function Wl(e){e()}function Jl(e){return e}function Yl(){return[!1,Wl]}var Xl=It;function ns(e,t){this.props=e,this.context=t}function ph(e,t){function n(i){var o=this.props.ref;return o!=i.ref&&o&&(typeof o=="function"?o(null):o.current=null),t?!t(this.props,i)||o!=i.ref:Vl(this.props,i)}function r(i){return this.shouldComponentUpdate=n,y(e,i)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(ns.prototype=new Mt).isPureReactComponent=!0,ns.prototype.shouldComponentUpdate=function(e,t){return Vl(this.props,e)||Vl(this.state,t)};var fh=ge.__b;ge.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),fh&&fh(e)};var ZR=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function J(e){function t(n){var r=uh({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=ZR,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var mh=function(e,t){return e==null?null:Cn(Cn(e).map(t))},Tr={map:mh,forEach:mh,count:function(e){return e?Cn(e).length:0},only:function(e){var t=Cn(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:Cn},eI=ge.__e;ge.__e=function(e,t,n,r){if(e.then){for(var i,o=t;o=o.__;)if((i=o.__c)&&i.__c)return t.__e??(t.__e=n.__e,t.__k=n.__k||[]),i.__c(e,t)}eI(e,t,n,r)};var hh=ge.unmount;function gh(e,t,n){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),e.__c.__H=null),(e=uh({},e)).__c!=null&&(e.__c.__P===n&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(r){return gh(r,t,n)})),e}function vh(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return vh(r,t,n)}),e.__c&&e.__c.__P===t&&(e.__e&&n.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=n)),e}function Ro(){this.__u=0,this.o=null,this.__b=null}function yh(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function bh(e){var t,n,r,i=null;function o(s){if(t||(t=e()).then(function(c){c&&(i=c.default||c),r=!0},function(c){n=c,r=!0}),n)throw n;if(!r)throw t;return i?y(i,s):null}return o.displayName="Lazy",o.__f=!0,o}function vi(){this.i=null,this.l=null}ge.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),hh&&hh(e)},(Ro.prototype=new Mt).__c=function(e,t){var n=t.__c,r=this;r.o??=[],r.o.push(n);var i=yh(r.__v),o=!1,s=function(){o||r.__z||(o=!0,n.__R=null,i?i(l):l())};n.__R=s;var c=n.__P;n.__P=null;var l=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=vh(d,d.__c.__P,d.__c.__O)}var u;for(r.setState({__a:r.__b=null});u=r.o.pop();)u.__P=c,u.forceUpdate()}};r.__u++||32&t.__u||r.setState({__a:r.__b=r.__v.__k[0]}),e.then(s,s)},Ro.prototype.componentWillUnmount=function(){this.o=[]},Ro.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=gh(this.__b,n,r.__O=r.__P)}this.__b=null}var i=t.__a&&y(z,null,e.fallback);return i&&(i.__u&=-33),[y(z,null,t.__a?null:e.children),i]};var _h=function(e,t,n){if(++n[1]===n[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(n=e.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;e.i=n=n[2]}};function tI(e){return this.getChildContext=function(){return e.context},e.children}function nI(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Ue(null,t.v),t.v=null,t.h=null},t.h&&t.h!==n&&t.componentWillUnmount(),!t.v){for(var r=t.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;t.h=n,t.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},namespaceURI:n.namespaceURI,insertBefore:function(i,o){this.childNodes.push(i),t.h.insertBefore(i,o)},removeChild:function(i){this.childNodes.splice(this.childNodes.indexOf(i)>>>1,1),t.h.removeChild(i)}}}Ue(y(tI,{context:t.context},e.__v),t.v)}function sn(e,t){var n=y(nI,{__v:e,h:t});return n.containerInfo=t,n}(vi.prototype=new Mt).__a=function(e){var t=this,n=yh(t.__v),r=t.l.get(e);return r[0]++,function(i){var o=function(){t.props.revealOrder?(r.push(i),_h(t,e,r)):i()};n?n(o):o()}},vi.prototype.render=function(e){this.i=null,this.l=new Map;var t=Cn(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var n=t.length;n--;)this.l.set(t[n],this.i=[1,0,this.i]);return e.children},vi.prototype.componentDidUpdate=vi.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){_h(e,n,t)})};var wh=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,rI=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,iI=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,oI=/[A-Z0-9]/g,aI=typeof document<"u",sI=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function Sh(e,t,n){return t.__k??(t.textContent=""),Ue(e,t),typeof n=="function"&&n(),e?e.__c:null}function Ch(e,t,n){return eh(e,t),typeof n=="function"&&n(),e?e.__c:null}Mt.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(Mt.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var Rh=ge.event;ge.event=function(e){return Rh&&(e=Rh(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var Ql,cI={configurable:!0,get:function(){return this.class}},Ih=ge.vnode;ge.vnode=function(e){typeof e.type=="string"&&(function(t){var n=t.props,r=t.type,i={},o=r.indexOf("-")==-1;for(var s in n){var c=n[s];if(!(s==="value"&&"defaultValue"in n&&c==null||aI&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var l=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&c===!0?c="":l==="translate"&&c==="no"?c=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?s="ondblclick":l!=="onchange"||r!=="input"&&r!=="textarea"||sI(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":iI.test(s)&&(s=l):l=s="oninput":o&&rI.test(s)?s=s.replace(oI,"-$&").toLowerCase():c===null&&(c=void 0),l==="oninput"&&i[s=l]&&(s="oninputCapture"),i[s]=c}}r=="select"&&(i.multiple&&Array.isArray(i.value)&&(i.value=Cn(n.children).forEach(function(d){d.props.selected=i.value.indexOf(d.props.value)!=-1})),i.defaultValue!=null&&(i.value=Cn(n.children).forEach(function(d){d.props.selected=i.multiple?i.defaultValue.indexOf(d.props.value)!=-1:i.defaultValue==d.props.value}))),n.class&&!n.className?(i.class=n.class,Object.defineProperty(i,"className",cI)):n.className&&(i.class=i.className=n.className),t.props=i})(e),e.$$typeof=wh,Ih&&Ih(e)};var kh=ge.__r;ge.__r=function(e){kh&&kh(e),Ql=e.__c};var Th=ge.diffed;ge.diffed=function(e){Th&&Th(e);var t=e.props,n=e.__e;n!=null&&e.type==="textarea"&&"value"in t&&t.value!==n.value&&(n.value=t.value==null?"":t.value),Ql=null};var Ph={ReactCurrentDispatcher:{current:{readContext:function(e){return Ql.__n[e.__c].props.value},useCallback:ae,useContext:kn,useDebugValue:Ul,useDeferredValue:Jl,useEffect:V,useId:Ir,useImperativeHandle:es,useInsertionEffect:Xl,useLayoutEffect:It,useMemo:ke,useReducer:In,useRef:B,useState:x,useSyncExternalStore:Kl,useTransition:Yl}}},lI="18.3.1";function Nh(e){return y.bind(null,e)}function Tn(e){return!!e&&e.$$typeof===wh}function Eh(e){return Tn(e)&&e.type===z}function Ah(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Pr(e){return Tn(e)?WR.apply(null,arguments):e}function xh(e){return!!e.__k&&(Ue(null,e),!0)}function Dh(e){return e&&(e.base||e.nodeType===1&&e)||null}var Lh=function(e,t){return e(t)},rs=function(e,t){var n,r=ge.debounceRendering;ge.debounceRendering=function(o){n=o};try{var i=e(t);return n&&n(),i}finally{ge.debounceRendering=r}},$h=Tn,dI={useState:x,useId:Ir,useReducer:In,useEffect:V,useLayoutEffect:It,useInsertionEffect:Xl,useTransition:Yl,useDeferredValue:Jl,useSyncExternalStore:Kl,startTransition:Wl,useRef:B,useImperativeHandle:es,useMemo:ke,useCallback:ae,useContext:kn,useDebugValue:Ul,version:"18.3.1",Children:Tr,render:Sh,hydrate:Ch,unmountComponentAtNode:xh,createPortal:sn,createElement:y,createContext:Cr,createFactory:Nh,cloneElement:Pr,createRef:Hm,Fragment:z,isValidElement:Tn,isElement:$h,isFragment:Eh,isMemo:Ah,findDOMNode:Dh,Component:Mt,PureComponent:ns,memo:ph,forwardRef:J,flushSync:rs,unstable_batchedUpdates:Lh,StrictMode:z,Suspense:Ro,SuspenseList:vi,lazy:bh,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Ph},uI=Object.defineProperty,yi=(e,t)=>uI(e,"name",{value:t,configurable:!0}),Oh=!!(typeof window<"u"&&window.document&&window.document.createElement);function te(e,t,{checkForDefaultPrevented:n=!0}={}){return yi(function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)},"handleEvent")}yi(te,"composeEventHandlers");function pI(e){if(!Oh)throw new Error("Cannot access window outside of the DOM");return e?.ownerDocument?.defaultView??window}yi(pI,"getOwnerWindow");function Zl(e){if(!Oh)throw new Error("Cannot access document outside of the DOM");return e?.ownerDocument??document}yi(Zl,"getOwnerDocument");function jh(e,t=!1){const{activeElement:n}=Zl(e);if(!n?.nodeName)return null;if(Mh(n)&&n.contentDocument)return jh(n.contentDocument.body,t);if(t){const r=n.getAttribute("aria-activedescendant");if(r){const i=Zl(n).getElementById(r);if(i)return i}}return n}yi(jh,"getActiveElement");function Mh(e){return e.tagName==="IFRAME"}yi(Mh,"isFrame");var fI=Object.defineProperty,ed=(e,t)=>fI(e,"name",{value:t,configurable:!0});function td(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}ed(td,"setRef");function Fh(...e){return t=>{let n=!1;const r=e.map(i=>{const o=td(i,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let i=0;i<r.length;i++){const o=r[i];typeof o=="function"?o():td(e[i],null)}}}}ed(Fh,"composeRefs");function Re(...e){return ae(Fh(...e),e)}ed(Re,"useComposedRefs");var mI=Object.defineProperty,Ft=(e,t)=>mI(e,"name",{value:t,configurable:!0});function hI(e,t){const n=Cr(t);n.displayName=e+"Context";const r=Ft(o=>{const{children:s,...c}=o,l=ke(()=>c,Object.values(c));return a(n.Provider,{value:l,children:s})},"Provider");r.displayName=e+"Provider";function i(o,s={}){const{optional:c=!1}=s,l=kn(n);if(l)return l;if(t!==void 0)return t;if(!c)throw new Error(`\`${o}\` must be used within \`${e}\``)}return Ft(i,"useContext"),[r,i]}Ft(hI,"createContext");function dt(e,t=[]){let n=[];function r(o,s){const c=Cr(s);c.displayName=o+"Context";const l=n.length;n=[...n,s];const d=Ft(p=>{const{scope:f,children:m,...v}=p,g=f?.[e]?.[l]||c,h=ke(()=>v,Object.values(v));return a(g.Provider,{value:h,children:m})},"Provider");d.displayName=o+"Provider";function u(p,f,m={}){const{optional:v=!1}=m,g=f?.[e]?.[l]||c,h=kn(g);if(h)return h;if(s!==void 0)return s;if(!v)throw new Error(`\`${p}\` must be used within \`${o}\``)}return Ft(u,"useContext"),[d,u]}Ft(r,"createContext");const i=Ft(()=>{const o=n.map(s=>Cr(s));return Ft(function(c){const l=c?.[e]||o;return ke(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])},"useScope")},"createScope");return i.scopeName=e,[r,Bh(i,...t)]}Ft(dt,"createContextScope");function Bh(...e){const t=e[0];if(e.length===1)return t;const n=Ft(()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return Ft(function(o){const s=r.reduce((c,{useScope:l,scopeName:d})=>{const u=l(o)[`__scope${d}`];return{...c,...u}},{});return ke(()=>({[`__scope${t.scopeName}`]:s}),[s])},"useComposedScopes")},"createScope");return n.scopeName=t.scopeName,n}Ft(Bh,"composeContextScopes");var Ze=globalThis?.document?It:()=>{},gI=Object.defineProperty,vI=(e,t)=>gI(e,"name",{value:t,configurable:!0}),yI=gi[" useId ".trim().toString()]||(()=>{}),bI=0;function Et(e){const[t,n]=x(yI());return Ze(()=>{e||n(r=>r??String(bI++))},[e]),e||(t?`radix-${t}`:"")}vI(Et,"useId");var _I=Object.defineProperty,wI=(e,t)=>_I(e,"name",{value:t,configurable:!0}),qh=gi[" useEffectEvent ".trim().toString()],Uh=gi[" useInsertionEffect ".trim().toString()];function Gh(e){if(typeof qh=="function")return qh(e);const t=B(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof Uh=="function"?Uh(()=>{t.current=e}):Ze(()=>{t.current=e}),ke(()=>((...n)=>t.current?.(...n)),[])}wI(Gh,"useEffectEvent");var SI=Object.defineProperty,Io=(e,t)=>SI(e,"name",{value:t,configurable:!0}),CI=gi[" useInsertionEffect ".trim().toString()]||Ze;function At({prop:e,defaultProp:t,onChange:n=Io(()=>{},"onChange"),caller:r}){const[i,o,s]=Hh({defaultProp:t,onChange:n}),c=e!==void 0;return[c?e:i,ae(d=>{if(c){const u=Vh(d)?d(e):d;u!==e&&s.current?.(u)}else o(d)},[c,e,o,s])]}Io(At,"useControllableState");function Hh({defaultProp:e,onChange:t}){const[n,r]=x(e),i=B(n),o=B(t);return CI(()=>{o.current=t},[t]),V(()=>{i.current!==n&&(o.current?.(n),i.current=n)},[n,i]),[n,r,o]}Io(Hh,"useUncontrolledState");function Vh(e){return typeof e=="function"}Io(Vh,"isFunction");var Kh=Symbol("RADIX:SYNC_STATE");function RI(e,t,n,r){const{prop:i,defaultProp:o,onChange:s,caller:c}=t,l=i!==void 0,d=Gh(s),u=[{...n,state:o}];r&&u.push(r);const[p,f]=In((h,b)=>{if(b.type===Kh)return{...h,state:b.state};const w=e(h,b);return l&&!Object.is(w.state,h.state)&&d(w.state),w},...u),m=p.state,v=B(m);V(()=>{v.current!==m&&(v.current=m,l||d(m))},[m,v,l]);const g=ke(()=>i!==void 0?{...p,state:i}:p,[p,i]);return V(()=>{l&&!Object.is(i,p.state)&&f({type:Kh,state:i})},[i,p.state,l]),[g,f]}Io(RI,"useControllableStateReducer");var II=Object.defineProperty,Wt=(e,t)=>II(e,"name",{value:t,configurable:!0});function cn(e){const t=J((n,r)=>{let{children:i,...o}=n,s=null,c=!1;const l=[];nd(i)&&typeof is=="function"&&(i=is(i._payload)),Tr.forEach(i,f=>{if(Xh(f)){c=!0;const m=f;let v="child"in m.props?m.props.child:m.props.children;nd(v)&&typeof is=="function"&&(v=is(v._payload)),s=kI(m,v),l.push(s?.props?.children)}else l.push(f)}),s?s=Pr(s,void 0,l):!c&&Tr.count(i)===1&&Tn(i)&&(s=i);const d=s?Yh(s):void 0,u=Re(r,d);if(!s){if(i||i===0)throw new Error(c?NI(e):PI(e));return i}const p=Jh(o,s.props??{});return s.type!==z&&(p.ref=r?u:d),Pr(s,p)});return t.displayName=`${e}.Slot`,t}Wt(cn,"createSlot");var zh=Symbol.for("radix.slottable");function Wh(e){const t=Wt(n=>"child"in n?n.children(n.child):n.children,"Slottable");return t.displayName=`${e}.Slottable`,t.__radixId=zh,t}Wt(Wh,"createSlottable");var kI=Wt((e,t)=>{if("child"in e.props){const n=e.props.child;return Tn(n)?Pr(n,void 0,e.props.children(n.props.children)):null}return Tn(t)?t:null},"getSlottableElementFromSlottable");function Jh(e,t){const n={...t};for(const r in t){const i=e[r],o=t[r];/^on[A-Z]/.test(r)?i&&o?n[r]=(...s)=>{const c=o(...s);return i(...s),c}:i&&(n[r]=i):r==="style"?n[r]={...i,...o}:r==="className"&&(n[r]=[i,o].filter(Boolean).join(" "))}return{...e,...n}}Wt(Jh,"mergeProps");function Yh(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}Wt(Yh,"getElementRef");function Xh(e){return Tn(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===zh}Wt(Xh,"isSlottable");var TI=Symbol.for("react.lazy");function nd(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===TI&&"_payload"in e&&Qh(e._payload)}Wt(nd,"isLazyComponent");function Qh(e){return typeof e=="object"&&e!==null&&"then"in e}Wt(Qh,"isPromiseLike");var PI=Wt(e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),NI=Wt(e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),is=gi[" use ".trim().toString()],EI=Object.defineProperty,AI=(e,t)=>EI(e,"name",{value:t,configurable:!0}),ye=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const n=cn(`Primitive.${t}`),r=J((i,o)=>{const{asChild:s,...c}=i,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),a(l,{...c,ref:o})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function os(e,t){e&&rs(()=>e.dispatchEvent(t))}AI(os,"dispatchDiscreteCustomEvent");var xI=Object.defineProperty,DI=(e,t)=>xI(e,"name",{value:t,configurable:!0});function ht(e){const t=B(e);return V(()=>{t.current=e}),ke(()=>((...n)=>t.current?.(...n)),[])}DI(ht,"useCallbackRef");var LI=Object.defineProperty,rt=(e,t)=>LI(e,"name",{value:t,configurable:!0}),rd="dismissableLayer.update",$I="dismissableLayer.pointerDownOutside",OI="dismissableLayer.focusOutside",Zh,id=Cr({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),bi=J(rt(function(t,n){const{disableOutsidePointerEvents:r=!1,deferPointerDownOutside:i=!1,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:c,onInteractOutside:l,onDismiss:d,...u}=t,p=kn(id),[f,m]=x(null),v=f?.ownerDocument??globalThis?.document,[,g]=x({}),h=Re(n,m),b=Array.from(p.layers),[w]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),_=w?b.indexOf(w):-1,R=f?b.indexOf(f):-1,I=p.layersWithOutsidePointerEventsDisabled.size>0,T=R>=_,A=B(!1),O=tg(D=>{s?.(D),l?.(D),D.defaultPrevented||d?.()},{ownerDocument:v,deferPointerDownOutside:i,isDeferredPointerDownOutsideRef:A,dismissableSurfaces:p.dismissableSurfaces,shouldHandlePointerDownOutside:ae(D=>{if(!(D instanceof Node))return!1;const G=[...p.branches].some(q=>q.contains(D));return T&&!G},[p.branches,T])}),F=ng(D=>{if(i&&A.current)return;const G=D.target;[...p.branches].some(q=>q.contains(G))||(c?.(D),l?.(D),D.defaultPrevented||d?.())},v),N=f?R===b.length-1:!1,L=ht(D=>{D.key==="Escape"&&(o?.(D),!D.defaultPrevented&&d&&(D.preventDefault(),d()))});return V(()=>{if(N)return v.addEventListener("keydown",L,{capture:!0}),()=>v.removeEventListener("keydown",L,{capture:!0})},[v,N,L]),V(()=>{if(f)return r&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(Zh=v.body.style.pointerEvents,v.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(f)),p.layers.add(f),od(),()=>{r&&(p.layersWithOutsidePointerEventsDisabled.delete(f),p.layersWithOutsidePointerEventsDisabled.size===0&&(v.body.style.pointerEvents=Zh))}},[f,v,r,p]),V(()=>()=>{f&&(p.layers.delete(f),p.layersWithOutsidePointerEventsDisabled.delete(f),od())},[f,p]),V(()=>{const D=rt(()=>g({}),"handleUpdate");return document.addEventListener(rd,D),()=>document.removeEventListener(rd,D)},[]),a(ye.div,{...u,ref:h,style:{pointerEvents:I?T?"auto":"none":void 0,...t.style},onFocusCapture:te(t.onFocusCapture,F.onFocusCapture),onBlurCapture:te(t.onBlurCapture,F.onBlurCapture),onPointerDownCapture:te(t.onPointerDownCapture,O.onPointerDownCapture)})},"DismissableLayer")),jI=J(rt(function(t,n){const r=kn(id),i=B(null),o=Re(n,i);return V(()=>{const s=i.current;if(s)return r.branches.add(s),()=>{r.branches.delete(s)}},[r.branches]),a(ye.div,{...t,ref:o})},"DismissableLayerBranch"));function eg(){const e=kn(id),[t,n]=x(null);return V(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}rt(eg,"useDismissableLayerSurface");var MI=rt(()=>!0,"IS_TRUE");function tg(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:o,shouldHandlePointerDownOutside:s=MI}=t,c=ht(e),l=B(!1),d=B(!1),u=B(new Map),p=B(()=>{});return V(()=>{function f(){d.current=!1,i.current=!1,u.current.clear()}rt(f,"resetOutsideInteraction");function m(){return Array.from(u.current.values()).some(Boolean)}rt(m,"isOutsideInteractionIntercepted");function v(_){if(!d.current)return;const R=_.target;R instanceof Node&&[...o].some(I=>I.contains(R))||u.current.set(_.type,!0),_.type==="click"&&window.setTimeout(()=>{d.current&&p.current()},0)}rt(v,"handleInteractionCapture");function g(_){d.current&&u.current.set(_.type,!1)}rt(g,"handleInteractionBubble");const h=rt(_=>{if(_.target&&!l.current){let R=function(){n.removeEventListener("click",p.current);const T=m();f(),T||ad($I,c,I,{discrete:!0})};if(rt(R,"handleAndDispatchPointerDownOutsideEvent"),!s(_.target)){n.removeEventListener("click",p.current),f(),l.current=!1;return}const I={originalEvent:_};d.current=!0,i.current=r&&_.button===0,u.current.clear(),!r||_.button!==0?R():(n.removeEventListener("click",p.current),p.current=R,n.addEventListener("click",p.current,{once:!0}))}else n.removeEventListener("click",p.current),f();l.current=!1},"handlePointerDown"),b=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const _ of b)n.addEventListener(_,v,!0),n.addEventListener(_,g);const w=window.setTimeout(()=>{n.addEventListener("pointerdown",h)},0);return()=>{window.clearTimeout(w),n.removeEventListener("pointerdown",h),n.removeEventListener("click",p.current);for(const _ of b)n.removeEventListener(_,v,!0),n.removeEventListener(_,g)}},[n,c,r,i,o,s]),{onPointerDownCapture:rt(()=>l.current=!0,"onPointerDownCapture")}}rt(tg,"usePointerDownOutside");function ng(e,t=globalThis?.document){const n=ht(e),r=B(!1);return V(()=>{const i=rt(o=>{o.target&&!r.current&&ad(OI,n,{originalEvent:o},{discrete:!1})},"handleFocus");return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:rt(()=>r.current=!0,"onFocusCapture"),onBlurCapture:rt(()=>r.current=!1,"onBlurCapture")}}rt(ng,"useFocusOutside");function od(){const e=new CustomEvent(rd);document.dispatchEvent(e)}rt(od,"dispatchUpdate");function ad(e,t,n,{discrete:r}){const i=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?os(i,o):i.dispatchEvent(o)}rt(ad,"handleAndDispatchCustomEvent");var FI=bi,BI=jI,qI=Object.defineProperty,St=(e,t)=>qI(e,"name",{value:t,configurable:!0}),sd="focusScope.autoFocusOnMount",cd="focusScope.autoFocusOnUnmount",rg={bubbles:!1,cancelable:!0},as=J(St(function(t,n){const{loop:r=!1,trapped:i=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...c}=t,[l,d]=x(null),u=ht(o),p=ht(s),f=B(null),m=Re(n,d),v=B({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;V(()=>{if(i){let h=function(R){if(v.paused||!l)return;const I=R.target;l.contains(I)?f.current=I:Pn(f.current,{select:!0})},b=function(R){if(v.paused||!l)return;const I=R.relatedTarget;I!==null&&(l.contains(I)||Pn(f.current,{select:!0}))},w=function(R){if(document.activeElement===document.body)for(const I of R)I.removedNodes.length>0&&Pn(l)};St(h,"handleFocusIn"),St(b,"handleFocusOut"),St(w,"handleMutations"),document.addEventListener("focusin",h),document.addEventListener("focusout",b);const _=new MutationObserver(w);return l&&_.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",h),document.removeEventListener("focusout",b),_.disconnect()}}},[i,l,v.paused]),V(()=>{if(l){cg.add(v);const h=document.activeElement;if(!l.contains(h)){const b=new CustomEvent(sd,rg);l.addEventListener(sd,u),l.dispatchEvent(b),b.defaultPrevented||(ig(dg(ld(l)),{select:!0}),document.activeElement===h&&Pn(l))}return()=>{l.removeEventListener(sd,u),setTimeout(()=>{const b=new CustomEvent(cd,rg);l.addEventListener(cd,p),l.dispatchEvent(b),b.defaultPrevented||Pn(h??document.body,{select:!0}),l.removeEventListener(cd,p),cg.remove(v)},0)}}},[l,u,p,v]);const g=ae(h=>{if(!r&&!i||v.paused)return;const b=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,w=document.activeElement;if(b&&w){const _=h.currentTarget,[R,I]=og(_);R&&I?!h.shiftKey&&w===I?(h.preventDefault(),r&&Pn(R,{select:!0})):h.shiftKey&&w===R&&(h.preventDefault(),r&&Pn(I,{select:!0})):w===_&&h.preventDefault()}},[r,i,v.paused]);return a(ye.div,{tabIndex:-1,...c,ref:m,onKeyDown:g})},"FocusScope"));function ig(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Pn(r,{select:t}),document.activeElement!==n)return}St(ig,"focusFirst");function og(e){const t=ld(e);return[dd(t,e),dd(t.reverse(),e)]}St(og,"getTabbableEdges");function ld(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:St(r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}St(ld,"getTabbableCandidates");function dd(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):ag(r,{upTo:t})))return r}St(dd,"findVisible");function ag(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}St(ag,"isHidden");function sg(e){return e instanceof HTMLInputElement&&"select"in e}St(sg,"isSelectableInput");function Pn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&sg(e)&&t&&e.select()}}St(Pn,"focus");var cg=lg();function lg(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=ud(e,t),e.unshift(t)},remove(t){e=ud(e,t),e[0]?.resume()}}}St(lg,"createFocusScopesStack");function ud(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}St(ud,"arrayRemove");function dg(e){return e.filter(t=>t.tagName!=="A")}St(dg,"removeLinks");var UI=Object.defineProperty,GI=(e,t)=>UI(e,"name",{value:t,configurable:!0}),_i=J(GI(function(t,n){const{container:r,...i}=t,[o,s]=x(!1);Ze(()=>s(!0),[]);const c=r||o&&globalThis?.document?.body;return c?sn(a(ye.div,{...i,ref:n}),c):null},"Portal")),HI=Object.defineProperty,Nn=(e,t)=>HI(e,"name",{value:t,configurable:!0});function ug(e,t){return In((n,r)=>t[n][r]??n,e)}Nn(ug,"useStateMachine");var kt=Nn(e=>{const{present:t,children:n}=e,r=pg(t),i=typeof n=="function"?n({present:r.isPresent}):Tr.only(n),o=fg(r.ref,mg(i));return typeof n=="function"||r.isPresent?Pr(i,{ref:o}):null},"Presence");function pg(e){const[t,n]=x(),r=B(null),i=B(e),o=B("none"),s=B(void 0),[c,l]=ug(e?"mounted":"unmounted",{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return V(()=>{c==="mounted"?(o.current=s.current??wi(r.current),s.current=void 0):o.current="none"},[c]),Ze(()=>{const d=r.current,u=i.current;if(u!==e){const p=o.current,f=wi(d);e?(s.current=f,l("MOUNT")):f==="none"||d?.display==="none"?l("UNMOUNT"):l(u&&p!==f?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,l]),Ze(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,p=Nn(m=>{const v=wi(r.current).includes(CSS.escape(m.animationName));if(m.target===t&&v&&(l("ANIMATION_END"),!i.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",d=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},"handleAnimationEnd"),f=Nn(m=>{m.target===t&&(o.current=wi(r.current))},"handleAnimationStart");return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",p),t.addEventListener("animationend",p),()=>{u.clearTimeout(d),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",p),t.removeEventListener("animationend",p)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:ae(d=>{if(d){const u=getComputedStyle(d);r.current=u,s.current=wi(u)}else r.current=null;n(d)},[])}}Nn(pg,"usePresence");function pd(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}Nn(pd,"setRef");function fg(...e){const t=B(e);return t.current=e,ae(n=>{const r=t.current;let i=!1;const o=r.map(s=>{const c=pd(s,n);return!i&&typeof c=="function"&&(i=!0),c});if(i)return()=>{for(let s=0;s<o.length;s++){const c=o[s];typeof c=="function"?c():pd(r[s],null)}}},[])}Nn(fg,"useStableComposedRefs");function wi(e){return e?.animationName||"none"}Nn(wi,"getAnimationName");function mg(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}Nn(mg,"getElementRef");var VI=Object.defineProperty,fd=(e,t)=>VI(e,"name",{value:t,configurable:!0}),ss=0,Si=null;function KI(e){return Ci(),e.children}fd(KI,"FocusGuards");function Ci(){V(()=>{Si||(Si={start:md(),end:md()});const{start:e,end:t}=Si;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),ss++,()=>{ss===1&&(Si?.start.remove(),Si?.end.remove(),Si=null),ss=Math.max(0,ss-1)}},[])}fd(Ci,"useFocusGuards");function md(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}fd(md,"createFocusGuard");var ln=function(){return ln=Object.assign||function(t){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])}return t},ln.apply(this,arguments)};function hg(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function zI(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,o;r<i;r++)(o||!(r in t))&&(o||(o=Array.prototype.slice.call(t,0,r)),o[r]=t[r]);return e.concat(o||Array.prototype.slice.call(t))}var cs="right-scroll-bar-position",ls="width-before-scroll-bar",WI="with-scroll-bars-hidden",JI="--removed-body-scroll-bar-size";function hd(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function YI(e,t){var n=x(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var i=n.value;i!==r&&(n.value=r,n.callback(r,i))}}}})[0];return n.callback=t,n.facade}var XI=typeof window<"u"?It:V,gg=new WeakMap;function QI(e,t){var n=YI(t||null,function(r){return e.forEach(function(i){return hd(i,r)})});return XI(function(){var r=gg.get(n);if(r){var i=new Set(r),o=new Set(e),s=n.current;i.forEach(function(c){o.has(c)||hd(c,null)}),o.forEach(function(c){i.has(c)||hd(c,s)})}gg.set(n,e)},[e]),n}function ZI(e){return e}function ek(e,t){t===void 0&&(t=ZI);var n=[],r=!1;return{read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(i){var o=t(i,r);return n.push(o),function(){n=n.filter(function(s){return s!==o})}},assignSyncMedium:function(i){for(r=!0;n.length;){var o=n;n=[],o.forEach(i)}n={push:function(s){return i(s)},filter:function(){return n}}},assignMedium:function(i){r=!0;var o=[];if(n.length){var s=n;n=[],s.forEach(i),o=n}var c=function(){var d=o;o=[],d.forEach(i)},l=function(){return Promise.resolve().then(c)};l(),n={push:function(d){o.push(d),l()},filter:function(d){return o=o.filter(d),n}}}}}function tk(e){e===void 0&&(e={});var t=ek(null);return t.options=ln({async:!0,ssr:!1},e),t}var vg=function(e){var t=e.sideCar,n=hg(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return y(r,ln({},n))};vg.isSideCarExport=!0;function nk(e,t){return e.useMedium(t),vg}var yg=tk(),gd=function(){},ds=J(function(e,t){var n=B(null),r=x({onScrollCapture:gd,onWheelCapture:gd,onTouchMoveCapture:gd}),i=r[0],o=r[1],s=e.forwardProps,c=e.children,l=e.className,d=e.removeScrollBar,u=e.enabled,p=e.shards,f=e.sideCar,m=e.noRelative,v=e.noIsolation,g=e.inert,h=e.allowPinchZoom,b=e.as,w=b===void 0?"div":b,_=e.gapMode,R=hg(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),I=f,T=QI([n,t]),A=ln(ln({},R),i);return y(z,null,u&&y(I,{sideCar:yg,removeScrollBar:d,shards:p,noRelative:m,noIsolation:v,inert:g,setCallbacks:o,allowPinchZoom:!!h,lockRef:n,gapMode:_}),s?Pr(Tr.only(c),ln(ln({},A),{ref:T})):y(w,ln({},A,{className:l,ref:T}),c))});ds.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},ds.classNames={fullWidth:ls,zeroRight:cs};var bg,rk=function(){if(bg)return bg;if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function ik(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=rk();return t&&e.setAttribute("nonce",t),e}function ok(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function ak(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}var sk=function(){var e=0,t=null;return{add:function(n){e==0&&(t=ik())&&(ok(t,n),ak(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},ck=function(){var e=sk();return function(t,n){V(function(){return e.add(t),function(){e.remove()}},[t&&n])}},_g=function(){var e=ck(),t=function(n){var r=n.styles,i=n.dynamic;return e(r,i),null};return t},lk={left:0,top:0,right:0,gap:0},vd=function(e){return parseInt(e||"",10)||0},dk=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],i=t[e==="padding"?"paddingRight":"marginRight"];return[vd(n),vd(r),vd(i)]},uk=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return lk;var t=dk(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},pk=_g(),ko="data-scroll-locked",fk=function(e,t,n,r){var i=e.left,o=e.top,s=e.right,c=e.gap;return n===void 0&&(n="margin"),`
2
- .`.concat(WI,` {
1
+ (function(){var Om=Object.defineProperty,oR=(e,t)=>{let n={};for(var r in e)Om(n,r,{get:e[r],enumerable:!0});return t||Om(n,Symbol.toStringTag,{value:"Module"}),n},Hl=15e3,Mm=class extends Error{timeoutMs;constructor(e){super(`Viewer read exceeded its ${e}ms deadline`),this.name="ReadTimeoutError",this.timeoutMs=e}};function Vl(e){return e.reason??new DOMException("The request was aborted","AbortError")}function Zo(e,t){return t.aborted?Promise.reject(Vl(t)):new Promise((n,r)=>{const i=()=>t.removeEventListener("abort",a),a=()=>{i(),r(Vl(t))};t.addEventListener("abort",a,{once:!0}),e.then(s=>{i(),n(s)},s=>{i(),r(s)})})}function Fm(e=Hl,t){const n=new AbortController,r=()=>n.abort(Vl(t));t?.aborted?r():t?.addEventListener("abort",r,{once:!0});const i=window.setTimeout(()=>n.abort(new Mm(e)),e);return{abort:(a=new DOMException("The request was aborted","AbortError"))=>n.abort(a),dispose:()=>{window.clearTimeout(i),t?.removeEventListener("abort",r)},signal:n.signal}}function Bm(e){return e instanceof Mm}function he(e){if(!e||typeof e!="object")return;const t=e.error;return typeof t=="string"?t:void 0}async function je(e,t={}){const{deadlineMs:n=Hl,signal:r,...i}=t,a=Fm(n,r);try{await Zo(Promise.resolve(),a.signal);const s=await Zo(fetch(e,{...i,signal:a.signal}),a.signal);if(!s.ok)throw new Error(`${e}: ${s.status} ${s.statusText}`);return await Zo(s.json(),a.signal)}finally{a.dispose()}}async function _e(e){const t=await e.text();try{return{text:t,payload:t?JSON.parse(t):{}}}catch{return{text:t,payload:{}}}}function qm(e,t,n,r,i){const a=new URLSearchParams;return a.set("project",e||""),typeof t=="number"&&a.set("limit",String(t)),typeof n=="number"&&a.set("offset",String(n)),r&&a.set("scope",r),i&&a.set("q",i),a.toString()}async function sR(e={}){return je("/api/observer-status",e)}async function cR(e={}){return je("/api/config",e)}async function lR(e){const t=await fetch("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.text();let r=null;if(n)try{r=JSON.parse(n)}catch{}if(!t.ok){const i=he(r)||n||"request failed";throw new Error(i)}return r}async function Kl(e={}){return je("/api/coordinator/admin/status",e)}async function Um(e,t={}){return je(`/api/coordinator/admin/groups${e?"?include_archived=1":""}`,t)}async function dR(e){const t=await fetch("/api/coordinator/admin/groups",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(he(r)||n||"request failed");return r}async function uR(e,t){const n=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:t})}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(he(i)||r||"request failed");return i}async function pR(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/archive`,{method:"POST"}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(he(r)||n||"request failed");return r}async function fR(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/unarchive`,{method:"POST"}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(he(r)||n||"request failed");return r}async function mR(e,t=!1){const n=new URLSearchParams;t&&n.set("include_inactive","1");const r=n.size?`?${n.toString()}`:"";return je(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes${r}`)}async function hR(e,t){const n=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(he(i)||r||"request failed");return i}async function Gm(e,t,n=!1){const r=new URLSearchParams;n&&r.set("include_revoked","1");const i=r.size?`?${r.toString()}`:"";return je(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members${i}`)}async function gR(e,t,n){const r=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),{text:i,payload:a}=await _e(r);if(!r.ok)throw new Error(he(a)||i||"request failed");return a}async function vR(e,t,n,r={}){const i=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),{text:a,payload:s}=await _e(i);if(!i.ok)throw new Error(he(s)||a||"request failed");return s}async function yR(e,t={}){const n=new URLSearchParams;e&&n.set("group_id",e);const r=n.size?`?${n.toString()}`:"";return je(`/api/coordinator/admin/join-requests${r}`,t)}async function Hm(e,t=!0,n={}){const r=new URLSearchParams;e&&r.set("group_id",e),t&&r.set("include_disabled","1");const i=r.size?`?${r.toString()}`:"";return je(`/api/coordinator/admin/devices${i}`,n)}async function bR(e,t){const n=await fetch(`/api/coordinator/admin/join-requests/${encodeURIComponent(e)}/${t}`,{method:"POST"}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(he(i)||r||"request failed");return i}async function _R(e,t,n){const r=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({group_id:t,display_name:n})}),{text:i,payload:a}=await _e(r);if(!r.ok)throw new Error(he(a)||i||"request failed");return a}async function wR(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/disable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(he(i)||r||"request failed");return i}async function SR(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/enable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(he(i)||r||"request failed");return i}async function CR(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/remove?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(he(i)||r||"request failed");return i}async function Vm(e){const t=await fetch("/api/coordinator/admin/invites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(he(r)||n||"request failed");return r}async function Km(e,t){const n=qm(e,t?.limit,t?.offset,t?.scope,t?.q);return je(`/api/observations?${n}`,{signal:t?.signal})}async function RR(e,t){const n=await fetch("/api/memories/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({memory_id:e,visibility:t})}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(he(i)||r||"request failed");return i}async function IR(e,t){const n=await fetch("/api/memories/project",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({memory_id:e,project:t})}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(he(i)||r||"request failed");return i}async function kR(e){const t=await fetch("/api/memories/forget",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({memory_id:e})}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(he(r)||n||"request failed");return r}async function zm(e,t){const n=qm(e,t?.limit,t?.offset,t?.scope,t?.q);return je(`/api/summaries?${n}`,{signal:t?.signal})}async function TR(e){const t=await fetch("/api/pack/trace",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(he(r)||n||"request failed");return r}async function PR(e=1200){const t=new AbortController,n=window.setTimeout(()=>t.abort(),e);try{const r=await fetch("/api/runtime",{cache:"no-store",signal:t.signal});if(!r.ok)throw new Error(`/api/runtime: ${r.status} ${r.statusText}`)}finally{window.clearTimeout(n)}}async function NR(){return je("/api/runtime")}function ER(e={}){return je("/api/viewer-status",e)}async function es(e={}){return(await je("/api/projects",e)).projects||[]}function wt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function AR(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ts(e){const t=AR(e);return t!==null&&t>=0&&t<=1?t:null}function kt(e){return Number.isSafeInteger(e)&&Number(e)>=0?Number(e):null}function zl(e){return!wt(e)||e.token_unit!=="tokens"||["tokens_read","tokens_written","tokens_saved","count","measured_count","estimated_count","unavailable_count","legacy_text_length_count","legacy_unclassified_count"].some(t=>kt(e[t])===null)?null:{tokens_read:Number(e.tokens_read),tokens_written:Number(e.tokens_written),tokens_saved:Number(e.tokens_saved),count:Number(e.count),token_unit:"tokens",measured_count:Number(e.measured_count),estimated_count:Number(e.estimated_count),unavailable_count:Number(e.unavailable_count),legacy_text_length_count:Number(e.legacy_text_length_count),legacy_unclassified_count:Number(e.legacy_unclassified_count)}}function xR(e){return!wt(e)||typeof e.event!="string"||e.token_unit!=="tokens"||["count","total_tokens_read","total_tokens_written","total_tokens_saved","measured_count","estimated_count","unavailable_count","legacy_text_length_count","legacy_unclassified_count"].some(t=>kt(e[t])===null)?null:{event:e.event,count:Number(e.count),total_tokens_read:Number(e.total_tokens_read),total_tokens_written:Number(e.total_tokens_written),total_tokens_saved:Number(e.total_tokens_saved),token_unit:"tokens",measured_count:Number(e.measured_count),estimated_count:Number(e.estimated_count),unavailable_count:Number(e.unavailable_count),legacy_text_length_count:Number(e.legacy_text_length_count),legacy_unclassified_count:Number(e.legacy_unclassified_count)}}function Wl(e){if(!Array.isArray(e))return null;const t=e.map(xR);return t.every(n=>n!==null)?t:null}function DR(e){if(!wt(e)||typeof e.created_at!="string"||kt(e.tokens_read)===null||kt(e.tokens_saved)===null||e.metadata_json!==null&&!wt(e.metadata_json))return null;const t=e.metadata_json;return t&&(t.exact_duplicates_collapsed!==void 0&&kt(t.exact_duplicates_collapsed)===null||t.exact_dedupe_enabled!==void 0&&typeof t.exact_dedupe_enabled!="boolean")?null:{created_at:e.created_at,tokens_read:e.tokens_read,tokens_saved:e.tokens_saved,metadata_json:t?{exact_duplicates_collapsed:t.exact_duplicates_collapsed,exact_dedupe_enabled:t.exact_dedupe_enabled}:null}}function LR(e){return!wt(e)||!wt(e.progress)||typeof e.kind!="string"||typeof e.title!="string"||typeof e.status!="string"||e.message!==null&&typeof e.message!="string"||e.error!==null&&typeof e.error!="string"||kt(e.progress.current)===null||e.progress.total!==null&&kt(e.progress.total)===null||typeof e.progress.unit!="string"?null:e}function ns(e){throw new Error(`Invalid ${e} response`)}function $R(e){if(!wt(e)||!wt(e.database)||!Array.isArray(e.maintenance_jobs))return null;const t=e.database;if(typeof t.path!="string"||kt(t.size_bytes)===null||kt(t.active_memory_items)===null||ts(t.vector_coverage)===null||ts(t.tags_coverage)===null)return null;const n=e.maintenance_jobs.map(LR);if(!n.every(i=>i!==null))return null;let r;if(e.reliability!==void 0){if(!wt(e.reliability))return null;const{counts:i,rates:a}=e.reliability;if(!wt(i)||!wt(a)||kt(i.errored_batches)===null||ts(a.flush_success_rate)===null||ts(a.dropped_event_rate)===null)return null;r={counts:{errored_batches:i.errored_batches},rates:{flush_success_rate:a.flush_success_rate,dropped_event_rate:a.dropped_event_rate}}}return{automatic_recall:Wm(e.automatic_recall),database:{path:t.path,size_bytes:t.size_bytes,active_memory_items:t.active_memory_items,vector_coverage:t.vector_coverage,tags_coverage:t.tags_coverage},reliability:r,maintenance_jobs:n}}function jR(e){if(!wt(e))return null;const t=Wl(e.events),n=Wl(e.events_global),r=e.events_filtered===null?null:Wl(e.events_filtered),i=zl(e.totals),a=zl(e.totals_global),s=e.totals_filtered===null?null:zl(e.totals_filtered);if(!t||!n||r===null&&e.events_filtered!==null||!i||!a||s===null&&e.totals_filtered!==null||!Array.isArray(e.recent_packs))return null;const c=e.recent_packs.map(DR);return c.every(l=>l!==null)?{events:t,events_global:n,events_filtered:r,totals:i,totals_global:a,totals_filtered:s,recent_packs:c}:null}function OR(e){return!wt(e)||["total","memories","artifacts","prompts","observations"].some(t=>kt(e[t])===null)?null:{total:Number(e.total),memories:Number(e.memories),artifacts:Number(e.artifacts),prompts:Number(e.prompts),observations:Number(e.observations)}}function MR(e){return!wt(e)||kt(e.pending)===null||kt(e.sessions)===null?null:{pending:e.pending,sessions:e.sessions}}function FR(e){const t=["freshEvaluations","evaluationsWithDuplicates","candidateItems","duplicatesOmitted","beforeTokens","afterTokens","estimatedTokensAvoided","missingRetainedMetadata","invalidRetainedMetadata","packMetadataGaps","unmeasuredAttempts"];return t.some(n=>kt(e[n])===null)?null:Object.fromEntries(t.map(n=>[n,Number(e[n])]))}function BR(e,t){const{freshEvaluations:n,evaluationsWithDuplicates:r,candidateItems:i,duplicatesOmitted:a,beforeTokens:s,afterTokens:c,estimatedTokensAvoided:l,missingRetainedMetadata:d,invalidRetainedMetadata:u,packMetadataGaps:p,unmeasuredAttempts:f}=e;return!(n+f>1e3||[r,d,u,p].some(m=>m>n)||i>n*50||a>i||c>s||l!==s-c||t==="available"!=n>0)}function Wm(e){if(!wt(e))return null;const t=e;if(t.availability!=="available"&&t.availability!=="no_data"&&t.availability!=="unavailable"||t.captureVersion!=="opencode-retained-v1"||t.windowLimit!==1e3||typeof t.periodStart!="string"||!Number.isFinite(Date.parse(t.periodStart))||typeof t.periodEnd!="string"||!Number.isFinite(Date.parse(t.periodEnd))||Date.parse(t.periodStart)>Date.parse(t.periodEnd))return null;const n=FR(t);return!n||Object.values(n).some(r=>r>1e9)||!BR(n,t.availability)?null:{availability:t.availability,periodStart:t.periodStart,periodEnd:t.periodEnd,windowLimit:1e3,...n,captureVersion:t.captureVersion}}async function qR(e={}){return $R(await je("/api/stats",e))??ns("/api/stats")}async function UR(e,t={}){return jR(await je(`/api/usage?project=${encodeURIComponent(e)}`,t))??ns("/api/usage")}async function GR(e,t={}){return OR(await je(`/api/session?project=${encodeURIComponent(e)}`,t))??ns("/api/session")}async function HR(e,t={}){return MR(await je(`/api/raw-events?project=${encodeURIComponent(e)}`,t))??ns("/api/raw-events")}var VR=["team_name_invalid","team_not_found","team_rename_stale","team_link_stale","team_link_ambiguous","team_coordinator_rename_failed","team_local_rename_pending","team_rename_failed"],KR=["keep_current_setup","reject_suggestion","keep_project_local","keep_identities_separate","remove_stale_device"],DH=new Set(KR),rs=class extends Error{statusCode;errorCode;constructor(e,t){super(t),this.statusCode=e,this.errorCode=t,this.name="RecipientPolicyTeamRenameApiError"}},zR=new Set(VR);async function WR(e){let t;try{t=await fetch(`/api/sync/recipient-policy/v1/teams/${encodeURIComponent(e.teamId)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({displayName:e.displayName,expectedDisplayName:e.expectedDisplayName})})}catch{throw new rs(0,"team_rename_failed")}const{payload:n}=await _e(t);if(!t.ok){const r=n&&typeof n=="object"&&"error"in n?String(n.error):"";throw new rs(t.status,zR.has(r)?r:"team_rename_failed")}if(n?.version!==1||typeof n.teamId!="string"||typeof n.displayName!="string"||typeof n.revision!="string"||typeof n.linkedCoordinatorGroupRenamed!="boolean")throw new rs(t.status,"team_rename_failed");return n}var JR=new Set(["device_display_name_invalid","device_display_name_required","device_display_name_too_long","invite_already_bound","invite_expired","invite_identity_conflict","invite_invalid","inviter_identity_invalid","project_invite_acceptance_failed","project_invite_bootstrap_incomplete","project_invite_self_acceptance_forbidden","project_invite_trust_state_invalid","project_sync_enablement_failed","recipient_display_name_invalid","recipient_display_name_required","recipient_display_name_too_long"]),Jm=class extends Error{errorCode;constructor(e,t){super(e),this.errorCode=t,this.name="ProjectInviteAcceptanceError"}};async function Jl(e,t="",n){const r=new URLSearchParams;e&&r.set("includeDiagnostics","1"),t&&r.set("project",t),n?.includeJoinRequests&&r.set("includeJoinRequests","1");const i=r.size?`?${r.toString()}`:"";return je(`/api/sync/status${i}`,{signal:n?.signal})}async function Yl(e,t,n){const r=await fetch("/api/sync/invites/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({invite:e,...t})}),{text:i,payload:a}=await _e(r);if(!r.ok){const s=typeof a?.detail=="string"?a.detail.trim():"",c=he(a),l=s||c||i||"request failed";throw n==="project_share_invite"&&c&&JR.has(c)?new Jm(l,c):new Error(l)}return a}async function Ym(e,t={}){const n=await fetch("/api/sync/invites/inspect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({invite:e,...t})}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(he(i)||r||"request failed");return i}async function YR(e={}){return je("/api/sync/actors",e)}async function XR(e=!1,t={}){return je(`/api/sync/pairing${e?"?includeDiagnostics=1":""}`,t)}async function Xm(e){const t=await fetch(`/api/sync/peers/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(he(r)||n||"request failed");return r}async function Qm(e,t){const n=await fetch("/api/sync/peers/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({peer_device_id:e,name:t})}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(he(i)||r||"request failed");return i}async function QR(e,t){const n={peer_device_id:e};t?.fingerprint&&(n.fingerprint=t.fingerprint),t?.expectedGroupId&&(n.expected_group_id=t.expectedGroupId),t?.expectedIncomingRequestId&&(n.expected_incoming_request_id=t.expectedIncomingRequestId);const r=await fetch("/api/sync/peers/accept-discovered",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await r.text();let a={};try{const c=i?JSON.parse(i):null;c&&typeof c=="object"&&!Array.isArray(c)&&(a=c)}catch{a={}}const s=typeof a.detail=="string"?a.detail:void 0;if(!r.ok)throw new Error(s||he(a)||i||"request failed");return a}var Zm=class extends Error{preview;constructor(e){super("Project forget confirmation required"),this.name="ProjectForgetConfirmationError",this.preview=e}},is=class extends Error{requiredGuardrails;requiredGuardrailTokens;guardrailWarnings;constructor(e){super("Sharing domain guardrail confirmation required"),this.name="SharingDomainGuardrailConfirmationError",this.requiredGuardrails=e.required_guardrails??[],this.requiredGuardrailTokens=e.required_guardrail_tokens??[],this.guardrailWarnings=e.guardrail_warnings??[]}},eh=class extends Error{preview;constructor(e){super("Legacy shared review confirmation required"),this.name="LegacySharedReviewConfirmationError",this.preview=e}},th=class extends Error{result;constructor(e){super("Recipient policy review source state changed"),this.name="RecipientPolicyReviewStaleError",this.result=e}},Xl=class extends Error{statusCode;errorCode;result;constructor(e,t,n){super(t),this.statusCode=e,this.errorCode=t,this.result=n,this.name="DeviceIdentityBindingApiError"}},Ql=1,nh=new Set(["team_setup_incomplete","team_setup_roster_changed","team_setup_assignment_changed","team_setup_roster_unavailable","team_setup_conflict","team_setup_confirmation_stale","team_setup_completion_unavailable","team_setup_completion_conflict","team_setup_completion_invalid","team_setup_failed"]),ZR=new Set(["coordinator_route_missing","coordinator_rejected_manifest","coordinator_unreachable","local_candidate_scan_budget_exceeded","coordinator_roster_unavailable"]),eI=new Set(["needs_setup","in_progress","stale","ready"]),tI=new Set(["reviewing","ready_to_finish","unavailable","completed"]),nI=new Set(["setup_incomplete","setup_unavailable","setup_completed","device_inactive","device_active","assignment_evidence_inactive","assignment_required","assignment_unavailable","decision_unresolved","mapping_unavailable","automatic_mapping"]);function nt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Xn(e,t){const n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((i,a)=>i===r[a])}function Wt(e){return typeof e=="string"||e===null}function Nr(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function sn(e,t){return Array.isArray(e)&&e.every(t)}function rh(e){return nt(e)?typeof e.candidateRef=="string"&&typeof e.displayName=="string"&&typeof e.status=="string"&&eI.has(e.status)&&Nr(e.deviceCount)&&Nr(e.projectCount)&&Nr(e.unresolvedDeviceCount)&&Nr(e.unresolvedProjectCount):!1}function rI(e){return nt(e)&&e.version===Ql&&sn(e.candidates,t=>rh(t)&&t.status!=="ready")}function iI(e){return nt(e)?e.kind==="absent"||e.kind==="existing"&&Nr(e.assignmentVersion)&&typeof e.identityRef=="string":!1}function Qn(e){return!nt(e)||!Xn(e,["blockedReason","enabled"])?!1:e.enabled===!0?e.blockedReason===null:e.enabled===!1&&typeof e.blockedReason=="string"&&nI.has(e.blockedReason)}function aI(e){return!nt(e)||!Xn(e,["assignIdentity","clearDecision","exclude","include","remove"])?!1:Qn(e.assignIdentity)&&Qn(e.include)&&Qn(e.exclude)&&Qn(e.remove)&&Qn(e.clearDecision)}function oI(e){return nt(e)?typeof e.deviceRef=="string"&&typeof e.displayName=="string"&&typeof e.enabled=="boolean"&&Wt(e.existingIdentityRef)&&Wt(e.suggestedIdentityRef)&&(e.verifiedEvidenceKind==="active_assignment"||e.verifiedEvidenceKind===null)&&typeof e.decision=="string"&&["unresolved","included","excluded","removed"].includes(e.decision)&&Wt(e.targetIdentityRef)&&iI(e.expectation)&&aI(e.actions):!1}function sI(e){return nt(e)?typeof e.projectRef=="string"&&typeof e.displayName=="string"&&typeof e.resolution=="string"&&["unresolved","deterministic","explicit"].includes(e.resolution)&&Wt(e.canonicalProjectRef)&&Wt(e.resolvedProjectRef)&&sn(e.mappingChoices,t=>nt(t)&&typeof t.resolvedProjectRef=="string"&&typeof t.displayName=="string")&&nt(e.actions)&&Xn(e.actions,["map"])&&Qn(e.actions.map):!1}function cI(e){if(!nt(e))return!1;const t=n=>typeof n=="string"&&["add","update","remove"].includes(n);return sn(e.teamChanges,n=>nt(n)&&typeof n.teamRef=="string"&&typeof n.teamDisplayName=="string"&&t(n.change)&&[null,"person_all_devices","reviewed_allowlist"].includes(n.fromDeviceEligibilityMode)&&n.toDeviceEligibilityMode==="reviewed_allowlist")&&sn(e.membershipChanges,n=>nt(n)&&typeof n.teamRef=="string"&&typeof n.teamDisplayName=="string"&&typeof n.identityRef=="string"&&typeof n.identityDisplayName=="string"&&t(n.change))&&sn(e.projectChanges,n=>nt(n)&&typeof n.projectRef=="string"&&typeof n.projectDisplayName=="string"&&Wt(n.fromCanonicalProjectRef)&&Wt(n.fromResolvedProjectRef)&&Wt(n.fromResolvedProjectDisplayName)&&Wt(n.toCanonicalProjectRef)&&Wt(n.toResolvedProjectRef)&&Wt(n.toResolvedProjectDisplayName)&&t(n.change))&&sn(e.recipientChanges,n=>nt(n)&&typeof n.canonicalProjectRef=="string"&&typeof n.canonicalProjectDisplayName=="string"&&(n.canonicalProjectKind==="project"||n.canonicalProjectKind==="legacy_default_sharing")&&n.recipientKind==="team"&&typeof n.recipientRef=="string"&&typeof n.recipientDisplayName=="string"&&t(n.change))&&sn(e.deviceAccessChanges,n=>nt(n)&&typeof n.canonicalProjectRef=="string"&&typeof n.canonicalProjectDisplayName=="string"&&(n.canonicalProjectKind==="project"||n.canonicalProjectKind==="legacy_default_sharing")&&typeof n.deviceRef=="string"&&typeof n.deviceDisplayName=="string"&&typeof n.change=="string"&&["add","remove"].includes(n.change))}function lI(e){return nt(e)&&Xn(e,["finish","refresh"])&&Qn(e.refresh)&&Qn(e.finish)}function ih(e,t,n){return e.every(r=>Object.values(r.actions).every(i=>!i.enabled&&i.blockedReason===n))&&t.every(r=>!r.actions.map.enabled&&r.actions.map.blockedReason===n)}function _i(e){if(!nt(e)||!(e.version===Ql&&rh(e.candidate)&&typeof e.attemptId=="string"&&typeof e.state=="string"&&tI.has(e.state)&&Nr(e.unresolvedDeviceCount)&&Nr(e.unresolvedProjectCount)&&sn(e.devices,oI)&&sn(e.projects,sI)&&lI(e.actions)&&sn(e.identityChoices,a=>nt(a)&&typeof a.identityRef=="string"&&typeof a.displayName=="string")))return!1;const t=e.actions,n=e.devices,r=e.projects,i=["actions","attemptId","candidate","devices","identityChoices","projects","state","unresolvedDeviceCount","unresolvedProjectCount","version"];return e.state==="ready_to_finish"?Xn(e,[...i,"accessDelta","accessDeltaDigest","finishDigest","viewerAccessDeltaDigest"])&&t.refresh.enabled===!0&&t.finish.enabled===!0&&typeof e.finishDigest=="string"&&typeof e.accessDeltaDigest=="string"&&typeof e.viewerAccessDeltaDigest=="string"&&cI(e.accessDelta):e.state==="unavailable"?Xn(e,[...i,"unavailableReason"])&&typeof e.unavailableReason=="string"&&nh.has(e.unavailableReason)&&t.refresh.enabled===!0&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_unavailable"&&ih(n,r,"setup_unavailable"):e.state==="completed"?Xn(e,i)&&t.refresh.enabled===!1&&t.refresh.blockedReason==="setup_completed"&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_completed"&&ih(n,r,"setup_completed"):Xn(e,i)&&e.state==="reviewing"&&t.refresh.enabled===!0&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_incomplete"}function dI(e){return nt(e)&&e.version===Ql&&e.status==="completed"&&typeof e.teamRef=="string"&&typeof e.attemptId=="string"&&typeof e.accessDeltaDigest=="string"&&typeof e.completedAt=="string"}var St=class extends Error{statusCode;errorCode;reason;constructor(e,t,n){super(t),this.statusCode=e,this.errorCode=t,this.reason=n,this.name="LegacyTeamSetupApiError"}};function Zn(e){return e?`/api/sync/team-setup/v1/${encodeURIComponent(e)}`:"/api/sync/team-setup/v1"}async function er(e,t,n){let r;try{r=await fetch(e,n)}catch{throw new St(0,"team_setup_failed")}let i;try{const a=await r.text();if(!a)throw new Error("empty Team setup response");i=JSON.parse(a)}catch{throw new St(r.status,"team_setup_failed")}if(!r.ok){const a=i&&typeof i=="object"&&"error"in i&&typeof i.error=="string"?i.error:"",s=nh.has(a)?a:"team_setup_failed",c=i&&typeof i=="object"&&"reason"in i&&typeof i.reason=="string"?i.reason:"",l=ZR.has(c)?c:void 0;throw new St(r.status,s,l)}if(!t(i))throw new St(r.status,"team_setup_failed");return i}function wi(e,t){return{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}}function ah(e={}){const t=e.signal?{signal:e.signal}:void 0;return er(Zn(),rI,t)}function uI(e){return er(Zn(e),_i)}function pI(e,t,n){return er(`${Zn(e)}/devices/${encodeURIComponent(t)}/assignment`,_i,wi("PUT",n))}function fI(e,t,n){return er(`${Zn(e)}/devices/${encodeURIComponent(t)}/decision`,_i,wi("PUT",n))}function mI(e,t,n){return er(`${Zn(e)}/devices/${encodeURIComponent(t)}/decision`,_i,wi("DELETE",n))}function hI(e,t,n){return er(`${Zn(e)}/projects/${encodeURIComponent(t)}/mapping`,_i,wi("PUT",n))}function gI(e){return er(`${Zn(e)}/refresh`,_i,wi("POST",{}))}function vI(e,t){return er(`${Zn(e)}/finish`,dI,wi("POST",t))}var Zl=class extends Error{result;constructor(e){super("Recipient policy changed after review"),this.name="RecipientPolicyEdgesStaleError",this.result=e}};function ed(e={}){return je("/api/sync/recipient-policy/v1/intent",e)}function td(e={}){return je("/api/sync/recipient-policy/v1/device-inventory",e)}async function oh(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await _e(n);if(!n.ok){const a=i?.errorCode||i?.error||he(i)||r||"request_failed",s=i&&"status"in i?i:null;throw new Xl(n.status,a,s)}return i}function sh(e){return oh("/api/sync/recipient-policy/v1/device-bindings/preview",e)}function ch(e){return oh("/api/sync/recipient-policy/v1/device-bindings/commit",e)}function yI(e={}){return je("/api/sync/recipient-policy/v1/reconciliation-status",e)}async function lh(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await _e(n);if(!n.ok){if(n.status===409&&i&&typeof i=="object"&&i.status==="stale")throw new Zl(i);if(n.status===409&&i&&typeof i=="object"&&i.status==="conflict")return i;const a=i&&typeof i=="object"&&"errorCode"in i?String(i.errorCode??""):"";throw new Error(a||he(i)||r||"request failed")}return i}function bI(e){return lh("/api/sync/recipient-policy/v1/edges/preview",e)}function _I(e){return lh("/api/sync/recipient-policy/v1/edges/commit",e)}async function dh(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(he(i)||r||"request failed");return i}function wI(e){return dh("/api/sync/recipient-policy/v1/invites/preview",e)}function SI(e){return dh("/api/sync/recipient-policy/v1/invites",e)}async function CI(e={}){const t=await je("/api/sync/recipient-policy/v1/review",e),n=t.continuity??null;if(t.categoryCounts)return{...t,continuity:n,categoryCounts:{actionableReview:t.reviewItems.length,preservedContinuity:Math.max(0,t.categoryCounts.preservedContinuity),blockedRepair:t.blockedItems.length}};const r=Math.max(0,(n?.findingCount??0)-t.reviewItems.length);return{...t,continuity:n,categoryCounts:{actionableReview:t.reviewItems.length,preservedContinuity:r,blockedRepair:t.blockedItems.length}}}async function RI(e){const t=await fetch("/api/sync/recipient-policy/v1/review/resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await _e(t);if(!t.ok)throw t.status===409&&r?.status==="stale"?new th(r):new Error(he(r)||n||"request failed");return r}async function II(e){const t=await fetch("/api/sync/recipient-policy/v1/review/resolve-bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({requests:e})}),{text:n,payload:r}=await _e(t);if(!t.ok&&t.status!==207)throw new Error(he(r)||n||"request failed");return r}async function kI(e={}){return je("/api/sync/sharing-domains/settings",e)}async function Sa(e={}){const{signal:t,...n}=e,r=new URLSearchParams;for(const[a,s]of Object.entries(n))s==null||s===""||r.set(a,String(s));const i=r.toString();return je(`/api/sync/projects${i?`?${i}`:""}`,{signal:t})}async function uh(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(he(i)||r||"request failed");return i}function TI(e){return uh("/api/sync/project-invites/preview",e)}function PI(e){return uh("/api/sync/project-invites",e)}function ph(e={}){return je("/api/sync/share-operations",e)}function NI(e){return je(`/api/sync/share-operations/${encodeURIComponent(e)}`)}async function EI(e){const t=await fetch(`/api/sync/share-operations/${encodeURIComponent(e)}/advance`,{method:"POST"}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(he(r)||n||"request failed");if(!r?.operation)throw new Error("response missing share operation");return r.operation}async function AI(e){const t=await fetch("/api/sync/sharing-domains/project-mappings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await _e(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new is(r):new Error(he(r)||n||"request failed");const i=r?.mapping;if(!i)throw new Error("response missing mapping");return{...i,guardrail_warnings:r.guardrail_warnings??i.guardrail_warnings}}async function xI(e){const t=await fetch("/api/sync/sharing-domains/project-mappings/bulk",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await _e(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new is(r):new Error(he(r)||n||"request failed");if(!Array.isArray(r?.mappings))throw new Error("response missing mappings");return r.mappings}async function DI(e){const t=await fetch(`/api/sync/sharing-domains/project-mappings/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(he(r)||n||"request failed");return!!r?.deleted}async function LI(e){const t=await fetch("/api/sync/projects/reassign-project",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(he(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project reassignment");return r}async function $I(e){const t=await fetch("/api/sync/projects/forget",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await _e(t);if(!t.ok)throw r?.error==="project_forget_confirmation_required"&&r.preview?new Zm(r.preview):new Error(he(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project forget result");return r}async function jI(e){const t=await fetch("/api/sync/legacy-shared-review/reassign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await _e(t);if(!t.ok)throw r?.error==="legacy_review_confirmation_required"&&r.preview?new eh(r.preview):new Error(he(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing legacy review reassignment");return r}async function OI(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/preferences`),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(he(r)||n||"request failed");const i=r?.preferences;if(!i)throw new Error("response missing preferences");return i}async function MI(e,t){const n=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/preferences`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(he(i)||r||"request failed");const a=i?.preferences;if(!a)throw new Error("response missing preferences");return a}async function FI(e){const t=await fetch("/api/sync/actors",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:e})}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(he(r)||n||"request failed");return r}async function BI(e,t){const n=await fetch("/api/sync/actors/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({actor_id:e,display_name:t})}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(he(i)||r||"request failed");return i}async function fh(e,t){const n=await fetch("/api/sync/actors/merge",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({primary_actor_id:e,secondary_actor_id:t})}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(he(i)||r||"request failed");return i}async function qI(e){const t=await fetch("/api/sync/actors/deactivate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({actor_id:e})}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(he(r)||n||"request failed");return r}async function UI(e){const t=await fetch("/api/sync/legacy-devices/claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({origin_device_id:e})}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(he(r)||n||"request failed");return r}async function nd(e){const t=typeof e=="string"?e.trim():e?.address?.trim(),n=typeof e=="string"?"":e?.peerDeviceId?.trim(),r={};t&&(r.address=t),n&&(r.peer_device_id=n);const i=await fetch("/api/sync/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),{text:a,payload:s}=await _e(i);if(!i.ok)throw new Error(he(s)||a||"request failed");if(!a)throw new Error("empty sync response");if(!Array.isArray(s?.items))throw new Error(a||"invalid sync response");return s}async function GI(e={}){return je("/api/update-status",e)}function HI(e){return{current_version:"unknown",channel:null,latest_version:null,update_available:!1,first_seen_at:null,checked_at:null,stale:!1,install_kind:"unknown",auto_update_eligible:!1,recommended_action:"Check network access and try again.",error:e instanceof Error?e.message:"Update status request failed."}}function as(e){return e!==null&&typeof e=="object"?e:null}function mh(e){const t=as(e),n=as(t?.status),r=as(as(t?.coordinator_enrollment_reconciliation_issues??n?.coordinator_enrollment_reconciliation_issues)?.counts)?.open;return typeof r=="number"&&Number.isSafeInteger(r)&&r>0?r:0}var Ca,pe,hh,gh,tr,vh,yh,bh,rd,os,Ra,_h,id,ad,od,wh,ss={},cs=[],VI=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ia=Array.isArray;function cn(e,t){for(var n in t)e[n]=t[n];return e}function sd(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function g(e,t,n){var r,i,a,s={};for(a in t)a=="key"?r=t[a]:a=="ref"?i=t[a]:s[a]=t[a];if(arguments.length>2&&(s.children=arguments.length>3?Ca.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(a in e.defaultProps)s[a]===void 0&&(s[a]=e.defaultProps[a]);return ka(e,s,r,i,null)}function ka(e,t,n,r,i){var a={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++hh,__i:-1,__u:0};return i==null&&pe.vnode!=null&&pe.vnode(a),a}function Sh(){return{current:null}}function z(e){return e.children}function qt(e,t){this.props=e,this.context=t}function Er(e,t){if(t==null)return e.__?Er(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?Er(e):null}function KI(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],i=[],a=cn({},t);a.__v=t.__v+1,pe.vnode&&pe.vnode(a),ld(e.__P,a,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??Er(t),!!(32&t.__u),i),a.__v=t.__v,a.__.__k[a.__i]=a,Nh(r,a,i),t.__e=t.__=null,a.__e!=n&&Ch(a)}}function Ch(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),Ch(e)}function cd(e){(!e.__d&&(e.__d=!0)&&tr.push(e)&&!ls.__r++||vh!=pe.debounceRendering)&&((vh=pe.debounceRendering)||yh)(ls)}function ls(){try{for(var e,t=1;tr.length;)tr.length>t&&tr.sort(bh),e=tr.shift(),t=tr.length,KI(e)}finally{tr.length=ls.__r=0}}function Rh(e,t,n,r,i,a,s,c,l,d,u){var p,f,m,v,b,h,y=r&&r.__k||cs,w=t.length;for(l=zI(n,t,y,l,w),p=0;p<w;p++)(m=n.__k[p])!=null&&(f=m.__i!=-1&&y[m.__i]||ss,m.__i=p,h=ld(e,m,f,i,a,s,c,l,d,u),v=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&dd(f.ref,null,m),u.push(m.ref,m.__c||v,m)),b==null&&v!=null&&(b=v),4&m.__u?(l=Ih(m,l,e),f.__e&&(f.__e=null)):typeof m.type=="function"&&h!==void 0?l=h:v&&(l=v.nextSibling),m.__u&=-7);return n.__e=b,l}function zI(e,t,n,r,i){var a,s,c,l,d,u=n.length,p=u,f=0;for(e.__k=new Array(i),a=0;a<i;a++)(s=t[a])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[a]=ka(null,s,null,null,null):Ia(s)?s=e.__k[a]=ka(z,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[a]=ka(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[a]=s,l=a+f,s.__=e,s.__b=e.__b+1,c=null,(d=s.__i=WI(s,n,l,p))!=-1&&(p--,(c=n[d])&&(c.__u|=2)),c==null||c.__v==null?(d==-1&&(i>u?f--:i<u&&f++),typeof s.type!="function"&&(s.__u|=4)):d!=l&&(d==l-1?f--:d==l+1?f++:(d>l?f--:f++,s.__u|=4))):e.__k[a]=null;if(p)for(a=0;a<u;a++)(c=n[a])!=null&&(2&c.__u)==0&&(c.__e==r&&(r=Er(c)),Ah(c,c));return r}function Ih(e,t,n){var r,i;if(typeof e.type=="function"){for(r=e.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=e,t=Ih(r[i],t,n));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=Er(e)),t=n.insertBefore(e.__e,t||null));do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function Tn(e,t){return t=t||[],e==null||typeof e=="boolean"||(Ia(e)?e.some(function(n){Tn(n,t)}):t.push(e)),t}function WI(e,t,n,r){var i,a,s,c=e.key,l=e.type,d=t[n],u=d!=null&&(2&d.__u)==0;if(d===null&&c==null||u&&c==d.key&&l==d.type)return n;if(r>(u?1:0)){for(i=n-1,a=n+1;i>=0||a<t.length;)if((d=t[s=i>=0?i--:a++])!=null&&(2&d.__u)==0&&c==d.key&&l==d.type)return s}return-1}function kh(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||VI.test(t)?n:n+"px"}function ds(e,t,n,r,i){var a,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||kh(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||kh(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")a=t!=(t=t.replace(_h,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+a]=n,n?r?n[Ra]=r[Ra]:(n[Ra]=id,e.addEventListener(t,a?od:ad,a)):e.removeEventListener(t,a?od:ad,a);else{if(i=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Th(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[os]==null)t[os]=id++;else if(t[os]<n[Ra])return;return n(pe.event?pe.event(t):t)}}}function ld(e,t,n,r,i,a,s,c,l,d){var u,p,f,m,v,b,h,y,w,_,R,I,T,A,L,F,N=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),a=[c=t.__e=n.__e]),(u=pe.__b)&&u(t);e:if(typeof N=="function"){p=s.length;try{if(w=t.props,_=N.prototype&&N.prototype.render,R=(u=N.contextType)&&r[u.__c],I=u?R?R.props.value:u.__:r,n.__c?y=(f=t.__c=n.__c).__=f.__E:(_?t.__c=f=new N(w,I):(t.__c=f=new qt(w,I),f.constructor=N,f.render=YI),R&&R.sub(f),f.state||(f.state={}),f.__n=r,m=f.__d=!0,f.__h=[],f._sb=[]),_&&f.__s==null&&(f.__s=f.state),_&&N.getDerivedStateFromProps!=null&&(f.__s==f.state&&(f.__s=cn({},f.__s)),cn(f.__s,N.getDerivedStateFromProps(w,f.__s))),v=f.props,b=f.state,f.__v=t,m)_&&N.getDerivedStateFromProps==null&&f.componentWillMount!=null&&f.componentWillMount(),_&&f.componentDidMount!=null&&f.__h.push(f.componentDidMount);else{if(_&&N.getDerivedStateFromProps==null&&w!==v&&f.componentWillReceiveProps!=null&&f.componentWillReceiveProps(w,I),t.__v==n.__v||!f.__e&&f.shouldComponentUpdate!=null&&f.shouldComponentUpdate(w,f.__s,I)===!1){t.__v!=n.__v&&(f.props=w,f.state=f.__s,f.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(j){j&&(j.__=t)}),cs.push.apply(f.__h,f._sb),f._sb=[],f.__h.length&&s.push(f),c=Er(n);break e}f.componentWillUpdate!=null&&f.componentWillUpdate(w,f.__s,I),_&&f.componentDidUpdate!=null&&f.__h.push(function(){f.componentDidUpdate(v,b,h)})}if(f.context=I,f.props=w,f.__P=e,f.__e=!1,T=pe.__r,A=0,_)f.state=f.__s,f.__d=!1,T&&T(t),u=f.render(f.props,f.state,f.context),cs.push.apply(f.__h,f._sb),f._sb=[];else do f.__d=!1,T&&T(t),u=f.render(f.props,f.state,f.context),f.state=f.__s;while(f.__d&&++A<25);f.state=f.__s,f.getChildContext!=null&&(r=cn(cn({},r),f.getChildContext())),_&&!m&&f.getSnapshotBeforeUpdate!=null&&(h=f.getSnapshotBeforeUpdate(v,b)),L=u!=null&&u.type===z&&u.key==null?Eh(u.props.children):u,c=Rh(e,Ia(L)?L:[L],t,n,r,i,a,s,c,l,d),f.base=t.__e,t.__u&=-161,f.__h.length&&s.push(f),y&&(f.__E=f.__=null)}catch(j){if(s.length=p,t.__v=null,l||a!=null){if(j.then){for(t.__u|=l?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;a!=null&&(a[a.indexOf(c)]=null),t.__e=c}else if(a!=null)for(F=a.length;F--;)sd(a[F])}else t.__e=n.__e;t.__k??=n.__k||[],j.then||Ph(t),pe.__e(j,t,n)}}else a==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=JI(n.__e,t,n,r,i,a,s,l,d);return(u=pe.diffed)&&u(t),128&t.__u?void 0:c}function Ph(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Ph))}function Nh(e,t,n){for(var r=0;r<n.length;r++)dd(n[r],n[++r],n[++r]);pe.__c&&pe.__c(t,e),e.some(function(i){try{e=i.__h,i.__h=[],e.some(function(a){a.call(i)})}catch(a){pe.__e(a,i.__v)}})}function Eh(e){return typeof e!="object"||e==null||e.__b>0?e:Ia(e)?e.map(Eh):e.constructor!==void 0?null:cn({},e)}function JI(e,t,n,r,i,a,s,c,l){var d,u,p,f,m,v,b,h=n.props||ss,y=t.props,w=t.type;if(w=="svg"?i="http://www.w3.org/2000/svg":w=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),a!=null){for(d=0;d<a.length;d++)if((m=a[d])&&"setAttribute"in m==!!w&&(w?m.localName==w:m.nodeType==3)){e=m,a[d]=null;break}}if(e==null){if(w==null)return document.createTextNode(y);e=document.createElementNS(i,w,y.is&&y),c&&(pe.__m&&pe.__m(t,a),c=!1),a=null}if(w==null)h===y||c&&e.data==y||(e.data=y);else{if(a=w=="textarea"&&y.defaultValue!=null?null:a&&Ca.call(e.childNodes),!c&&a!=null)for(h={},d=0;d<e.attributes.length;d++)h[(m=e.attributes[d]).name]=m.value;for(d in h)m=h[d],d=="dangerouslySetInnerHTML"?p=m:d=="children"||d in y||d=="value"&&"defaultValue"in y||d=="checked"&&"defaultChecked"in y||ds(e,d,null,m,i);for(d in y)m=y[d],d=="children"?f=m:d=="dangerouslySetInnerHTML"?u=m:d=="value"?v=m:d=="checked"?b=m:c&&typeof m!="function"||h[d]===m||ds(e,d,m,h[d],i);if(u)c||p&&(u.__html==p.__html||u.__html==e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(p&&(e.innerHTML=""),Rh(t.type=="template"?e.content:e,Ia(f)?f:[f],t,n,r,w=="foreignObject"?"http://www.w3.org/1999/xhtml":i,a,s,a?a[0]:n.__k&&Er(n,0),c,l),a!=null)for(d=a.length;d--;)sd(a[d]);c&&w!="textarea"||(d="value",w=="progress"&&v==null?e.removeAttribute("value"):v!=null&&(v!==e[d]||w=="progress"&&!v||w=="option"&&v!=h[d])&&ds(e,d,v,h[d],i),d="checked",b!=null&&b!=e[d]&&ds(e,d,b,h[d],i))}return e}function dd(e,t,n){try{if(typeof e=="function"){var r=typeof e.__u=="function";r&&e.__u(),r&&t==null||(e.__u=e(t))}else e.current=t}catch(i){pe.__e(i,n)}}function Ah(e,t,n){var r,i;if(pe.unmount&&pe.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||dd(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(a){pe.__e(a,t)}r.base=r.__P=r.__n=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&Ah(r[i],t,n||typeof e.type!="function");n||sd(e.__e),e.__c=e.__=e.__e=void 0}function YI(e,t,n){return this.constructor(e,n)}function Ue(e,t,n){var r,i,a,s;t==document&&(t=document.documentElement),pe.__&&pe.__(e,t),i=(r=typeof n=="function")?null:n&&n.__k||t.__k,a=[],s=[],ld(t,e=(!r&&n||t).__k=g(z,null,[e]),i||ss,ss,t.namespaceURI,!r&&n?[n]:i?null:t.firstChild?Ca.call(t.childNodes):null,a,!r&&n?n:i?i.__e:t.firstChild,r,s),Nh(a,e,s),e.props.children=null}function xh(e,t){Ue(e,t,xh)}function XI(e,t,n){var r,i,a,s,c=cn({},e.props);for(a in e.type&&e.type.defaultProps&&(s=e.type.defaultProps),t)a=="key"?r=t[a]:a=="ref"?i=t[a]:c[a]=t[a]===void 0&&s!=null?s[a]:t[a];return arguments.length>2&&(c.children=arguments.length>3?Ca.call(arguments,2):n),ka(e.type,c,r||e.key,i||e.ref,null)}function Ar(e){function t(n){var r,i;return this.getChildContext||(r=new Set,(i={})[t.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(a){this.props.value!=a.value&&r.forEach(function(s){s.__e=!0,cd(s)})},this.sub=function(a){r.add(a);var s=a.componentWillUnmount;a.componentWillUnmount=function(){r&&r.delete(a),s&&s.call(a)}}),n.children}return t.__c="__cC"+wh++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}Ca=cs.slice,pe={__e:function(e,t,n,r){for(var i,a,s;t=t.__;)if((i=t.__c)&&!i.__)try{if((a=i.constructor)&&a.getDerivedStateFromError!=null&&(i.setState(a.getDerivedStateFromError(e)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(e,r||{}),s=i.__d),s)return i.__E=i}catch(c){e=c}throw e}},hh=0,gh=function(e){return e!=null&&e.constructor===void 0},qt.prototype.setState=function(e,t){var n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=cn({},this.state);typeof e=="function"&&(e=e(cn({},n),this.props)),e&&cn(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),cd(this))},qt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),cd(this))},qt.prototype.render=z,tr=[],yh=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,bh=function(e,t){return e.__v.__b-t.__v.__b},ls.__r=0,rd=Math.random().toString(8),os="__d"+rd,Ra="__a"+rd,_h=/(PointerCapture)$|Capture$/i,id=0,ad=Th(!1),od=Th(!0),wh=0;var Pn,Be,ud,Dh,Si=0,Lh=[],We=pe,$h=We.__b,jh=We.__r,Oh=We.diffed,Mh=We.__c,Fh=We.unmount,Bh=We.__;function xr(e,t){We.__h&&We.__h(Be,e,Si||t),Si=0;var n=Be.__H||(Be.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function D(e){return Si=1,Nn(Uh,e)}function Nn(e,t,n){var r=xr(Pn++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Uh(void 0,t),function(c){var l=r.__N?r.__N[0]:r.__[0],d=r.t(l,c);l!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=Be,!Be.__f)){var i=function(c,l,d){if(!r.__c.__H)return!0;var u=!1,p=r.__c.props!==c;if(r.__c.__H.__.some(function(m){if(m.__N){u=!0;var v=m.__[0];m.__=m.__N,m.__N=void 0,v!==m.__[0]&&(p=!0)}}),a){var f=a.call(this,c,l,d);return u?f||p:f}return!u||p};Be.__f=!0;var a=Be.shouldComponentUpdate,s=Be.componentWillUpdate;Be.componentWillUpdate=function(c,l,d){if(this.__e){var u=a;a=void 0,i(c,l,d),a=u}s&&s.call(this,c,l,d)},Be.shouldComponentUpdate=i}return r.__N||r.__}function V(e,t){var n=xr(Pn++,3);!We.__s&&md(n.__H,t)&&(n.__=e,n.u=t,Be.__H.__h.push(n))}function Tt(e,t){var n=xr(Pn++,4);!We.__s&&md(n.__H,t)&&(n.__=e,n.u=t,Be.__h.push(n))}function B(e){return Si=5,Ie(function(){return{current:e}},[])}function us(e,t,n){Si=6,Tt(function(){if(typeof e=="function"){var r=e(t());return function(){e(null),r&&typeof r=="function"&&r()}}if(e)return e.current=t(),function(){return e.current=null}},n==null?n:n.concat(e))}function Ie(e,t){var n=xr(Pn++,7);return md(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function oe(e,t){return Si=8,Ie(function(){return e},t)}function En(e){var t=Be.context[e.__c],n=xr(Pn++,9);return n.c=e,t?(n.__??(n.__=!0,t.sub(Be)),t.props.value):e.__}function pd(e,t){We.useDebugValue&&We.useDebugValue(t?t(e):e)}function QI(e){var t=xr(Pn++,10),n=D();return t.__=e,Be.componentDidCatch||(Be.componentDidCatch=function(r,i){t.__&&t.__(r,i),n[1](r)}),[n[0],function(){n[1](void 0)}]}function Dr(){var e=xr(Pn++,11);if(!e.__){for(var t=Be.__v;t!==null&&!t.__m&&t.__!==null;)t=t.__;var n=t.__m||(t.__m=[0,0]);e.__="P"+n[0]+"-"+n[1]++}return e.__}function ZI(){for(var e;e=Lh.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(ps),t.__h.some(fd),t.__h=[]}catch(n){t.__h=[],We.__e(n,e.__v)}}}We.__b=function(e){Be=null,$h&&$h(e)},We.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Bh&&Bh(e,t)},We.__r=function(e){jh&&jh(e),Pn=0;var t=(Be=e.__c).__H;t&&(ud===Be?(t.__h=[],Be.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(ps),t.__h.some(fd),t.__h=[],Pn=0)),ud=Be},We.diffed=function(e){Oh&&Oh(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Lh.push(t)!==1&&Dh===We.requestAnimationFrame||((Dh=We.requestAnimationFrame)||ek)(ZI)),t.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),ud=Be=null},We.__c=function(e,t){t.some(function(n){try{n.__h.some(ps),n.__h=n.__h.filter(function(r){return!r.__||fd(r)})}catch(r){t.some(function(i){i.__h&&(i.__h=[])}),t=[],We.__e(r,n.__v)}}),Mh&&Mh(e,t)},We.unmount=function(e){Fh&&Fh(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{ps(r)}catch(i){t=i}}),n.__H=void 0,t&&We.__e(t,n.__v))};var qh=typeof requestAnimationFrame=="function";function ek(e){var t,n=function(){clearTimeout(r),qh&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);qh&&(t=requestAnimationFrame(n))}function ps(e){var t=Be,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),Be=t}function fd(e){var t=Be;e.__c=e.__(),Be=t}function md(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function Uh(e,t){return typeof t=="function"?t(e):t}var tk=0,LH=Array.isArray;function o(e,t,n,r,i,a){t||(t={});var s,c,l=t;if("ref"in l)for(c in l={},t)c=="ref"?s=t[c]:l[c]=t[c];var d={type:e,props:l,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--tk,__i:-1,__u:0,__source:i,__self:a};if(typeof e=="function"&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return pe.vnode&&pe.vnode(d),d}function Lr({ariaDisabled:e=!1,ariaLabel:t,className:n="modal-close-button",disabled:r=!1,onClick:i,label:a="Close"}){return o("button",{"aria-disabled":e?"true":void 0,"aria-label":t,className:n,disabled:r,onClick:()=>{e||i()},type:"button",children:[o("i",{"aria-hidden":"true",className:"modal-close-button-icon","data-lucide":"x"}),o("span",{className:"modal-close-button-label",children:a})]})}var Ci=oR({Children:()=>$r,Component:()=>qt,Fragment:()=>z,PureComponent:()=>fs,StrictMode:()=>z,Suspense:()=>Ta,SuspenseList:()=>Ri,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:()=>og,cloneElement:()=>jr,createContext:()=>Ar,createElement:()=>g,createFactory:()=>sg,createPortal:()=>ln,createRef:()=>Sh,default:()=>fk,findDOMNode:()=>ug,flushSync:()=>ms,forwardRef:()=>W,hydrate:()=>tg,isElement:()=>fg,isFragment:()=>cg,isMemo:()=>lg,isValidElement:()=>An,lazy:()=>Xh,memo:()=>Hh,render:()=>eg,startTransition:()=>yd,unmountComponentAtNode:()=>dg,unstable_batchedUpdates:()=>pg,useCallback:()=>oe,useContext:()=>En,useDebugValue:()=>pd,useDeferredValue:()=>bd,useEffect:()=>V,useErrorBoundary:()=>QI,useId:()=>Dr,useImperativeHandle:()=>us,useInsertionEffect:()=>wd,useLayoutEffect:()=>Tt,useMemo:()=>Ie,useReducer:()=>Nn,useRef:()=>B,useState:()=>D,useSyncExternalStore:()=>gd,useTransition:()=>_d,version:()=>pk});function Gh(e,t){for(var n in t)e[n]=t[n];return e}function hd(e,t){for(var n in e)if(n!=="__source"&&!(n in t))return!0;for(var r in t)if(r!=="__source"&&e[r]!==t[r])return!0;return!1}function gd(e,t){var n=t(),r=D({t:{__:n,u:t}}),i=r[0].t,a=r[1];return Tt(function(){i.__=n,i.u=t,vd(i)&&a({t:i})},[e,n,t]),V(function(){return vd(i)&&a({t:i}),e(function(){vd(i)&&a({t:i})})},[e]),n}function vd(e){try{return!((t=e.__)===(n=e.u())&&(t!==0||1/t==1/n)||t!=t&&n!=n)}catch{return!0}var t,n}function yd(e){e()}function bd(e){return e}function _d(){return[!1,yd]}var wd=Tt;function fs(e,t){this.props=e,this.context=t}function Hh(e,t){function n(i){var a=this.props.ref;return a!=i.ref&&a&&(typeof a=="function"?a(null):a.current=null),t?!t(this.props,i)||a!=i.ref:hd(this.props,i)}function r(i){return this.shouldComponentUpdate=n,g(e,i)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(fs.prototype=new qt).isPureReactComponent=!0,fs.prototype.shouldComponentUpdate=function(e,t){return hd(this.props,e)||hd(this.state,t)};var Vh=pe.__b;pe.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Vh&&Vh(e)};var nk=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function W(e){function t(n){var r=Gh({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=nk,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Kh=function(e,t){return e==null?null:Tn(Tn(e).map(t))},$r={map:Kh,forEach:Kh,count:function(e){return e?Tn(e).length:0},only:function(e){var t=Tn(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:Tn},rk=pe.__e;pe.__e=function(e,t,n,r){if(e.then){for(var i,a=t;a=a.__;)if((i=a.__c)&&i.__c)return t.__e??(t.__e=n.__e,t.__k=n.__k||[]),i.__c(e,t)}rk(e,t,n,r)};var zh=pe.unmount;function Wh(e,t,n){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),e.__c.__H=null),(e=Gh({},e)).__c!=null&&(e.__c.__P===n&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(r){return Wh(r,t,n)})),e}function Jh(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return Jh(r,t,n)}),e.__c&&e.__c.__P===t&&(e.__e&&n.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=n)),e}function Ta(){this.__u=0,this.o=null,this.__b=null}function Yh(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function Xh(e){var t,n,r,i=null;function a(s){if(t||(t=e()).then(function(c){c&&(i=c.default||c),r=!0},function(c){n=c,r=!0}),n)throw n;if(!r)throw t;return i?g(i,s):null}return a.displayName="Lazy",a.__f=!0,a}function Ri(){this.i=null,this.l=null}pe.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),zh&&zh(e)},(Ta.prototype=new qt).__c=function(e,t){var n=t.__c,r=this;r.o??=[],r.o.push(n);var i=Yh(r.__v),a=!1,s=function(){a||r.__z||(a=!0,n.__R=null,i?i(l):l())};n.__R=s;var c=n.__P;n.__P=null;var l=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=Jh(d,d.__c.__P,d.__c.__O)}var u;for(r.setState({__a:r.__b=null});u=r.o.pop();)u.__P=c,u.forceUpdate()}};r.__u++||32&t.__u||r.setState({__a:r.__b=r.__v.__k[0]}),e.then(s,s)},Ta.prototype.componentWillUnmount=function(){this.o=[]},Ta.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=Wh(this.__b,n,r.__O=r.__P)}this.__b=null}var i=t.__a&&g(z,null,e.fallback);return i&&(i.__u&=-33),[g(z,null,t.__a?null:e.children),i]};var Qh=function(e,t,n){if(++n[1]===n[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(n=e.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;e.i=n=n[2]}};function ik(e){return this.getChildContext=function(){return e.context},e.children}function ak(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Ue(null,t.v),t.v=null,t.h=null},t.h&&t.h!==n&&t.componentWillUnmount(),!t.v){for(var r=t.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;t.h=n,t.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},namespaceURI:n.namespaceURI,insertBefore:function(i,a){this.childNodes.push(i),t.h.insertBefore(i,a)},removeChild:function(i){this.childNodes.splice(this.childNodes.indexOf(i)>>>1,1),t.h.removeChild(i)}}}Ue(g(ik,{context:t.context},e.__v),t.v)}function ln(e,t){var n=g(ak,{__v:e,h:t});return n.containerInfo=t,n}(Ri.prototype=new qt).__a=function(e){var t=this,n=Yh(t.__v),r=t.l.get(e);return r[0]++,function(i){var a=function(){t.props.revealOrder?(r.push(i),Qh(t,e,r)):i()};n?n(a):a()}},Ri.prototype.render=function(e){this.i=null,this.l=new Map;var t=Tn(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var n=t.length;n--;)this.l.set(t[n],this.i=[1,0,this.i]);return e.children},Ri.prototype.componentDidUpdate=Ri.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Qh(e,n,t)})};var Zh=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,ok=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,sk=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,ck=/[A-Z0-9]/g,lk=typeof document<"u",dk=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function eg(e,t,n){return t.__k??(t.textContent=""),Ue(e,t),typeof n=="function"&&n(),e?e.__c:null}function tg(e,t,n){return xh(e,t),typeof n=="function"&&n(),e?e.__c:null}qt.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(qt.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var ng=pe.event;pe.event=function(e){return ng&&(e=ng(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var Sd,uk={configurable:!0,get:function(){return this.class}},rg=pe.vnode;pe.vnode=function(e){typeof e.type=="string"&&(function(t){var n=t.props,r=t.type,i={},a=r.indexOf("-")==-1;for(var s in n){var c=n[s];if(!(s==="value"&&"defaultValue"in n&&c==null||lk&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var l=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&c===!0?c="":l==="translate"&&c==="no"?c=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?s="ondblclick":l!=="onchange"||r!=="input"&&r!=="textarea"||dk(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":sk.test(s)&&(s=l):l=s="oninput":a&&ok.test(s)?s=s.replace(ck,"-$&").toLowerCase():c===null&&(c=void 0),l==="oninput"&&i[s=l]&&(s="oninputCapture"),i[s]=c}}r=="select"&&(i.multiple&&Array.isArray(i.value)&&(i.value=Tn(n.children).forEach(function(d){d.props.selected=i.value.indexOf(d.props.value)!=-1})),i.defaultValue!=null&&(i.value=Tn(n.children).forEach(function(d){d.props.selected=i.multiple?i.defaultValue.indexOf(d.props.value)!=-1:i.defaultValue==d.props.value}))),n.class&&!n.className?(i.class=n.class,Object.defineProperty(i,"className",uk)):n.className&&(i.class=i.className=n.className),t.props=i})(e),e.$$typeof=Zh,rg&&rg(e)};var ig=pe.__r;pe.__r=function(e){ig&&ig(e),Sd=e.__c};var ag=pe.diffed;pe.diffed=function(e){ag&&ag(e);var t=e.props,n=e.__e;n!=null&&e.type==="textarea"&&"value"in t&&t.value!==n.value&&(n.value=t.value==null?"":t.value),Sd=null};var og={ReactCurrentDispatcher:{current:{readContext:function(e){return Sd.__n[e.__c].props.value},useCallback:oe,useContext:En,useDebugValue:pd,useDeferredValue:bd,useEffect:V,useId:Dr,useImperativeHandle:us,useInsertionEffect:wd,useLayoutEffect:Tt,useMemo:Ie,useReducer:Nn,useRef:B,useState:D,useSyncExternalStore:gd,useTransition:_d}}},pk="18.3.1";function sg(e){return g.bind(null,e)}function An(e){return!!e&&e.$$typeof===Zh}function cg(e){return An(e)&&e.type===z}function lg(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function jr(e){return An(e)?XI.apply(null,arguments):e}function dg(e){return!!e.__k&&(Ue(null,e),!0)}function ug(e){return e&&(e.base||e.nodeType===1&&e)||null}var pg=function(e,t){return e(t)},ms=function(e,t){var n,r=pe.debounceRendering;pe.debounceRendering=function(a){n=a};try{var i=e(t);return n&&n(),i}finally{pe.debounceRendering=r}},fg=An,fk={useState:D,useId:Dr,useReducer:Nn,useEffect:V,useLayoutEffect:Tt,useInsertionEffect:wd,useTransition:_d,useDeferredValue:bd,useSyncExternalStore:gd,startTransition:yd,useRef:B,useImperativeHandle:us,useMemo:Ie,useCallback:oe,useContext:En,useDebugValue:pd,version:"18.3.1",Children:$r,render:eg,hydrate:tg,unmountComponentAtNode:dg,createPortal:ln,createElement:g,createContext:Ar,createFactory:sg,cloneElement:jr,createRef:Sh,Fragment:z,isValidElement:An,isElement:fg,isFragment:cg,isMemo:lg,findDOMNode:ug,Component:qt,PureComponent:fs,memo:Hh,forwardRef:W,flushSync:ms,unstable_batchedUpdates:pg,StrictMode:z,Suspense:Ta,SuspenseList:Ri,lazy:Xh,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:og},mk=Object.defineProperty,Ii=(e,t)=>mk(e,"name",{value:t,configurable:!0}),mg=!!(typeof window<"u"&&window.document&&window.document.createElement);function ne(e,t,{checkForDefaultPrevented:n=!0}={}){return Ii(function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)},"handleEvent")}Ii(ne,"composeEventHandlers");function hk(e){if(!mg)throw new Error("Cannot access window outside of the DOM");return e?.ownerDocument?.defaultView??window}Ii(hk,"getOwnerWindow");function Cd(e){if(!mg)throw new Error("Cannot access document outside of the DOM");return e?.ownerDocument??document}Ii(Cd,"getOwnerDocument");function hg(e,t=!1){const{activeElement:n}=Cd(e);if(!n?.nodeName)return null;if(gg(n)&&n.contentDocument)return hg(n.contentDocument.body,t);if(t){const r=n.getAttribute("aria-activedescendant");if(r){const i=Cd(n).getElementById(r);if(i)return i}}return n}Ii(hg,"getActiveElement");function gg(e){return e.tagName==="IFRAME"}Ii(gg,"isFrame");var gk=Object.defineProperty,Rd=(e,t)=>gk(e,"name",{value:t,configurable:!0});function Id(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}Rd(Id,"setRef");function vg(...e){return t=>{let n=!1;const r=e.map(i=>{const a=Id(i,t);return!n&&typeof a=="function"&&(n=!0),a});if(n)return()=>{for(let i=0;i<r.length;i++){const a=r[i];typeof a=="function"?a():Id(e[i],null)}}}}Rd(vg,"composeRefs");function Se(...e){return oe(vg(...e),e)}Rd(Se,"useComposedRefs");var vk=Object.defineProperty,Ut=(e,t)=>vk(e,"name",{value:t,configurable:!0});function yk(e,t){const n=Ar(t);n.displayName=e+"Context";const r=Ut(a=>{const{children:s,...c}=a,l=Ie(()=>c,Object.values(c));return o(n.Provider,{value:l,children:s})},"Provider");r.displayName=e+"Provider";function i(a,s={}){const{optional:c=!1}=s,l=En(n);if(l)return l;if(t!==void 0)return t;if(!c)throw new Error(`\`${a}\` must be used within \`${e}\``)}return Ut(i,"useContext"),[r,i]}Ut(yk,"createContext");function dt(e,t=[]){let n=[];function r(a,s){const c=Ar(s);c.displayName=a+"Context";const l=n.length;n=[...n,s];const d=Ut(p=>{const{scope:f,children:m,...v}=p,b=f?.[e]?.[l]||c,h=Ie(()=>v,Object.values(v));return o(b.Provider,{value:h,children:m})},"Provider");d.displayName=a+"Provider";function u(p,f,m={}){const{optional:v=!1}=m,b=f?.[e]?.[l]||c,h=En(b);if(h)return h;if(s!==void 0)return s;if(!v)throw new Error(`\`${p}\` must be used within \`${a}\``)}return Ut(u,"useContext"),[d,u]}Ut(r,"createContext");const i=Ut(()=>{const a=n.map(s=>Ar(s));return Ut(function(c){const l=c?.[e]||a;return Ie(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])},"useScope")},"createScope");return i.scopeName=e,[r,yg(i,...t)]}Ut(dt,"createContextScope");function yg(...e){const t=e[0];if(e.length===1)return t;const n=Ut(()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return Ut(function(a){const s=r.reduce((c,{useScope:l,scopeName:d})=>{const u=l(a)[`__scope${d}`];return{...c,...u}},{});return Ie(()=>({[`__scope${t.scopeName}`]:s}),[s])},"useComposedScopes")},"createScope");return n.scopeName=t.scopeName,n}Ut(yg,"composeContextScopes");var Xe=globalThis?.document?Tt:()=>{},bk=Object.defineProperty,_k=(e,t)=>bk(e,"name",{value:t,configurable:!0}),wk=Ci[" useId ".trim().toString()]||(()=>{}),Sk=0;function xt(e){const[t,n]=D(wk());return Xe(()=>{e||n(r=>r??String(Sk++))},[e]),e||(t?`radix-${t}`:"")}_k(xt,"useId");var Ck=Object.defineProperty,Rk=(e,t)=>Ck(e,"name",{value:t,configurable:!0}),bg=Ci[" useEffectEvent ".trim().toString()],_g=Ci[" useInsertionEffect ".trim().toString()];function wg(e){if(typeof bg=="function")return bg(e);const t=B(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof _g=="function"?_g(()=>{t.current=e}):Xe(()=>{t.current=e}),Ie(()=>((...n)=>t.current?.(...n)),[])}Rk(wg,"useEffectEvent");var Ik=Object.defineProperty,Pa=(e,t)=>Ik(e,"name",{value:t,configurable:!0}),kk=Ci[" useInsertionEffect ".trim().toString()]||Xe;function Dt({prop:e,defaultProp:t,onChange:n=Pa(()=>{},"onChange"),caller:r}){const[i,a,s]=Sg({defaultProp:t,onChange:n}),c=e!==void 0;return[c?e:i,oe(d=>{if(c){const u=Cg(d)?d(e):d;u!==e&&s.current?.(u)}else a(d)},[c,e,a,s])]}Pa(Dt,"useControllableState");function Sg({defaultProp:e,onChange:t}){const[n,r]=D(e),i=B(n),a=B(t);return kk(()=>{a.current=t},[t]),V(()=>{i.current!==n&&(a.current?.(n),i.current=n)},[n,i]),[n,r,a]}Pa(Sg,"useUncontrolledState");function Cg(e){return typeof e=="function"}Pa(Cg,"isFunction");var Rg=Symbol("RADIX:SYNC_STATE");function Tk(e,t,n,r){const{prop:i,defaultProp:a,onChange:s,caller:c}=t,l=i!==void 0,d=wg(s),u=[{...n,state:a}];r&&u.push(r);const[p,f]=Nn((h,y)=>{if(y.type===Rg)return{...h,state:y.state};const w=e(h,y);return l&&!Object.is(w.state,h.state)&&d(w.state),w},...u),m=p.state,v=B(m);V(()=>{v.current!==m&&(v.current=m,l||d(m))},[m,v,l]);const b=Ie(()=>i!==void 0?{...p,state:i}:p,[p,i]);return V(()=>{l&&!Object.is(i,p.state)&&f({type:Rg,state:i})},[i,p.state,l]),[b,f]}Pa(Tk,"useControllableStateReducer");var Pk=Object.defineProperty,Jt=(e,t)=>Pk(e,"name",{value:t,configurable:!0});function dn(e){const t=W((n,r)=>{let{children:i,...a}=n,s=null,c=!1;const l=[];kd(i)&&typeof hs=="function"&&(i=hs(i._payload)),$r.forEach(i,f=>{if(Ng(f)){c=!0;const m=f;let v="child"in m.props?m.props.child:m.props.children;kd(v)&&typeof hs=="function"&&(v=hs(v._payload)),s=Nk(m,v),l.push(s?.props?.children)}else l.push(f)}),s?s=jr(s,void 0,l):!c&&$r.count(i)===1&&An(i)&&(s=i);const d=s?Pg(s):void 0,u=Se(r,d);if(!s){if(i||i===0)throw new Error(c?xk(e):Ak(e));return i}const p=Tg(a,s.props??{});return s.type!==z&&(p.ref=r?u:d),jr(s,p)});return t.displayName=`${e}.Slot`,t}Jt(dn,"createSlot");var Ig=Symbol.for("radix.slottable");function kg(e){const t=Jt(n=>"child"in n?n.children(n.child):n.children,"Slottable");return t.displayName=`${e}.Slottable`,t.__radixId=Ig,t}Jt(kg,"createSlottable");var Nk=Jt((e,t)=>{if("child"in e.props){const n=e.props.child;return An(n)?jr(n,void 0,e.props.children(n.props.children)):null}return An(t)?t:null},"getSlottableElementFromSlottable");function Tg(e,t){const n={...t};for(const r in t){const i=e[r],a=t[r];/^on[A-Z]/.test(r)?i&&a?n[r]=(...s)=>{const c=a(...s);return i(...s),c}:i&&(n[r]=i):r==="style"?n[r]={...i,...a}:r==="className"&&(n[r]=[i,a].filter(Boolean).join(" "))}return{...e,...n}}Jt(Tg,"mergeProps");function Pg(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}Jt(Pg,"getElementRef");function Ng(e){return An(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Ig}Jt(Ng,"isSlottable");var Ek=Symbol.for("react.lazy");function kd(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Ek&&"_payload"in e&&Eg(e._payload)}Jt(kd,"isLazyComponent");function Eg(e){return typeof e=="object"&&e!==null&&"then"in e}Jt(Eg,"isPromiseLike");var Ak=Jt(e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),xk=Jt(e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),hs=Ci[" use ".trim().toString()],Dk=Object.defineProperty,Lk=(e,t)=>Dk(e,"name",{value:t,configurable:!0}),ge=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const n=dn(`Primitive.${t}`),r=W((i,a)=>{const{asChild:s,...c}=i,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o(l,{...c,ref:a})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function gs(e,t){e&&ms(()=>e.dispatchEvent(t))}Lk(gs,"dispatchDiscreteCustomEvent");var $k=Object.defineProperty,jk=(e,t)=>$k(e,"name",{value:t,configurable:!0});function ht(e){const t=B(e);return V(()=>{t.current=e}),Ie(()=>((...n)=>t.current?.(...n)),[])}jk(ht,"useCallbackRef");var Ok=Object.defineProperty,rt=(e,t)=>Ok(e,"name",{value:t,configurable:!0}),Td="dismissableLayer.update",Mk="dismissableLayer.pointerDownOutside",Fk="dismissableLayer.focusOutside",Ag,Pd=Ar({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),ki=W(rt(function(t,n){const{disableOutsidePointerEvents:r=!1,deferPointerDownOutside:i=!1,onEscapeKeyDown:a,onPointerDownOutside:s,onFocusOutside:c,onInteractOutside:l,onDismiss:d,...u}=t,p=En(Pd),[f,m]=D(null),v=f?.ownerDocument??globalThis?.document,[,b]=D({}),h=Se(n,m),y=Array.from(p.layers),[w]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),_=w?y.indexOf(w):-1,R=f?y.indexOf(f):-1,I=p.layersWithOutsidePointerEventsDisabled.size>0,T=R>=_,A=B(!1),L=Dg(x=>{s?.(x),l?.(x),x.defaultPrevented||d?.()},{ownerDocument:v,deferPointerDownOutside:i,isDeferredPointerDownOutsideRef:A,dismissableSurfaces:p.dismissableSurfaces,shouldHandlePointerDownOutside:oe(x=>{if(!(x instanceof Node))return!1;const U=[...p.branches].some(q=>q.contains(x));return T&&!U},[p.branches,T])}),F=Lg(x=>{if(i&&A.current)return;const U=x.target;[...p.branches].some(q=>q.contains(U))||(c?.(x),l?.(x),x.defaultPrevented||d?.())},v),N=f?R===y.length-1:!1,j=ht(x=>{x.key==="Escape"&&(a?.(x),!x.defaultPrevented&&d&&(x.preventDefault(),d()))});return V(()=>{if(N)return v.addEventListener("keydown",j,{capture:!0}),()=>v.removeEventListener("keydown",j,{capture:!0})},[v,N,j]),V(()=>{if(f)return r&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(Ag=v.body.style.pointerEvents,v.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(f)),p.layers.add(f),Nd(),()=>{r&&(p.layersWithOutsidePointerEventsDisabled.delete(f),p.layersWithOutsidePointerEventsDisabled.size===0&&(v.body.style.pointerEvents=Ag))}},[f,v,r,p]),V(()=>()=>{f&&(p.layers.delete(f),p.layersWithOutsidePointerEventsDisabled.delete(f),Nd())},[f,p]),V(()=>{const x=rt(()=>b({}),"handleUpdate");return document.addEventListener(Td,x),()=>document.removeEventListener(Td,x)},[]),o(ge.div,{...u,ref:h,style:{pointerEvents:I?T?"auto":"none":void 0,...t.style},onFocusCapture:ne(t.onFocusCapture,F.onFocusCapture),onBlurCapture:ne(t.onBlurCapture,F.onBlurCapture),onPointerDownCapture:ne(t.onPointerDownCapture,L.onPointerDownCapture)})},"DismissableLayer")),Bk=W(rt(function(t,n){const r=En(Pd),i=B(null),a=Se(n,i);return V(()=>{const s=i.current;if(s)return r.branches.add(s),()=>{r.branches.delete(s)}},[r.branches]),o(ge.div,{...t,ref:a})},"DismissableLayerBranch"));function xg(){const e=En(Pd),[t,n]=D(null);return V(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}rt(xg,"useDismissableLayerSurface");var qk=rt(()=>!0,"IS_TRUE");function Dg(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:a,shouldHandlePointerDownOutside:s=qk}=t,c=ht(e),l=B(!1),d=B(!1),u=B(new Map),p=B(()=>{});return V(()=>{function f(){d.current=!1,i.current=!1,u.current.clear()}rt(f,"resetOutsideInteraction");function m(){return Array.from(u.current.values()).some(Boolean)}rt(m,"isOutsideInteractionIntercepted");function v(_){if(!d.current)return;const R=_.target;R instanceof Node&&[...a].some(I=>I.contains(R))||u.current.set(_.type,!0),_.type==="click"&&window.setTimeout(()=>{d.current&&p.current()},0)}rt(v,"handleInteractionCapture");function b(_){d.current&&u.current.set(_.type,!1)}rt(b,"handleInteractionBubble");const h=rt(_=>{if(_.target&&!l.current){let R=function(){n.removeEventListener("click",p.current);const T=m();f(),T||Ed(Mk,c,I,{discrete:!0})};if(rt(R,"handleAndDispatchPointerDownOutsideEvent"),!s(_.target)){n.removeEventListener("click",p.current),f(),l.current=!1;return}const I={originalEvent:_};d.current=!0,i.current=r&&_.button===0,u.current.clear(),!r||_.button!==0?R():(n.removeEventListener("click",p.current),p.current=R,n.addEventListener("click",p.current,{once:!0}))}else n.removeEventListener("click",p.current),f();l.current=!1},"handlePointerDown"),y=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const _ of y)n.addEventListener(_,v,!0),n.addEventListener(_,b);const w=window.setTimeout(()=>{n.addEventListener("pointerdown",h)},0);return()=>{window.clearTimeout(w),n.removeEventListener("pointerdown",h),n.removeEventListener("click",p.current);for(const _ of y)n.removeEventListener(_,v,!0),n.removeEventListener(_,b)}},[n,c,r,i,a,s]),{onPointerDownCapture:rt(()=>l.current=!0,"onPointerDownCapture")}}rt(Dg,"usePointerDownOutside");function Lg(e,t=globalThis?.document){const n=ht(e),r=B(!1);return V(()=>{const i=rt(a=>{a.target&&!r.current&&Ed(Fk,n,{originalEvent:a},{discrete:!1})},"handleFocus");return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:rt(()=>r.current=!0,"onFocusCapture"),onBlurCapture:rt(()=>r.current=!1,"onBlurCapture")}}rt(Lg,"useFocusOutside");function Nd(){const e=new CustomEvent(Td);document.dispatchEvent(e)}rt(Nd,"dispatchUpdate");function Ed(e,t,n,{discrete:r}){const i=n.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?gs(i,a):i.dispatchEvent(a)}rt(Ed,"handleAndDispatchCustomEvent");var Uk=ki,Gk=Bk,Hk=Object.defineProperty,Ct=(e,t)=>Hk(e,"name",{value:t,configurable:!0}),Ad="focusScope.autoFocusOnMount",xd="focusScope.autoFocusOnUnmount",$g={bubbles:!1,cancelable:!0},vs=W(Ct(function(t,n){const{loop:r=!1,trapped:i=!1,onMountAutoFocus:a,onUnmountAutoFocus:s,...c}=t,[l,d]=D(null),u=ht(a),p=ht(s),f=B(null),m=Se(n,d),v=B({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;V(()=>{if(i){let h=function(R){if(v.paused||!l)return;const I=R.target;l.contains(I)?f.current=I:xn(f.current,{select:!0})},y=function(R){if(v.paused||!l)return;const I=R.relatedTarget;I!==null&&(l.contains(I)||xn(f.current,{select:!0}))},w=function(R){if(document.activeElement===document.body)for(const I of R)I.removedNodes.length>0&&xn(l)};Ct(h,"handleFocusIn"),Ct(y,"handleFocusOut"),Ct(w,"handleMutations"),document.addEventListener("focusin",h),document.addEventListener("focusout",y);const _=new MutationObserver(w);return l&&_.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",h),document.removeEventListener("focusout",y),_.disconnect()}}},[i,l,v.paused]),V(()=>{if(l){Bg.add(v);const h=document.activeElement;if(!l.contains(h)){const y=new CustomEvent(Ad,$g);l.addEventListener(Ad,u),l.dispatchEvent(y),y.defaultPrevented||(jg(Ug(Dd(l)),{select:!0}),document.activeElement===h&&xn(l))}return()=>{l.removeEventListener(Ad,u),setTimeout(()=>{const y=new CustomEvent(xd,$g);l.addEventListener(xd,p),l.dispatchEvent(y),y.defaultPrevented||xn(h??document.body,{select:!0}),l.removeEventListener(xd,p),Bg.remove(v)},0)}}},[l,u,p,v]);const b=oe(h=>{if(!r&&!i||v.paused)return;const y=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,w=document.activeElement;if(y&&w){const _=h.currentTarget,[R,I]=Og(_);R&&I?!h.shiftKey&&w===I?(h.preventDefault(),r&&xn(R,{select:!0})):h.shiftKey&&w===R&&(h.preventDefault(),r&&xn(I,{select:!0})):w===_&&h.preventDefault()}},[r,i,v.paused]);return o(ge.div,{tabIndex:-1,...c,ref:m,onKeyDown:b})},"FocusScope"));function jg(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(xn(r,{select:t}),document.activeElement!==n)return}Ct(jg,"focusFirst");function Og(e){const t=Dd(e);return[Ld(t,e),Ld(t.reverse(),e)]}Ct(Og,"getTabbableEdges");function Dd(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:Ct(r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}Ct(Dd,"getTabbableCandidates");function Ld(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):Mg(r,{upTo:t})))return r}Ct(Ld,"findVisible");function Mg(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}Ct(Mg,"isHidden");function Fg(e){return e instanceof HTMLInputElement&&"select"in e}Ct(Fg,"isSelectableInput");function xn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Fg(e)&&t&&e.select()}}Ct(xn,"focus");var Bg=qg();function qg(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=$d(e,t),e.unshift(t)},remove(t){e=$d(e,t),e[0]?.resume()}}}Ct(qg,"createFocusScopesStack");function $d(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}Ct($d,"arrayRemove");function Ug(e){return e.filter(t=>t.tagName!=="A")}Ct(Ug,"removeLinks");var Vk=Object.defineProperty,Kk=(e,t)=>Vk(e,"name",{value:t,configurable:!0}),Ti=W(Kk(function(t,n){const{container:r,...i}=t,[a,s]=D(!1);Xe(()=>s(!0),[]);const c=r||a&&globalThis?.document?.body;return c?ln(o(ge.div,{...i,ref:n}),c):null},"Portal")),zk=Object.defineProperty,Dn=(e,t)=>zk(e,"name",{value:t,configurable:!0});function Gg(e,t){return Nn((n,r)=>t[n][r]??n,e)}Dn(Gg,"useStateMachine");var Pt=Dn(e=>{const{present:t,children:n}=e,r=Hg(t),i=typeof n=="function"?n({present:r.isPresent}):$r.only(n),a=Vg(r.ref,Kg(i));return typeof n=="function"||r.isPresent?jr(i,{ref:a}):null},"Presence");function Hg(e){const[t,n]=D(),r=B(null),i=B(e),a=B("none"),s=B(void 0),[c,l]=Gg(e?"mounted":"unmounted",{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return V(()=>{c==="mounted"?(a.current=s.current??Pi(r.current),s.current=void 0):a.current="none"},[c]),Xe(()=>{const d=r.current,u=i.current;if(u!==e){const p=a.current,f=Pi(d);e?(s.current=f,l("MOUNT")):f==="none"||d?.display==="none"?l("UNMOUNT"):l(u&&p!==f?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,l]),Xe(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,p=Dn(m=>{const v=Pi(r.current).includes(CSS.escape(m.animationName));if(m.target===t&&v&&(l("ANIMATION_END"),!i.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",d=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},"handleAnimationEnd"),f=Dn(m=>{m.target===t&&(a.current=Pi(r.current))},"handleAnimationStart");return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",p),t.addEventListener("animationend",p),()=>{u.clearTimeout(d),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",p),t.removeEventListener("animationend",p)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:oe(d=>{if(d){const u=getComputedStyle(d);r.current=u,s.current=Pi(u)}else r.current=null;n(d)},[])}}Dn(Hg,"usePresence");function jd(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}Dn(jd,"setRef");function Vg(...e){const t=B(e);return t.current=e,oe(n=>{const r=t.current;let i=!1;const a=r.map(s=>{const c=jd(s,n);return!i&&typeof c=="function"&&(i=!0),c});if(i)return()=>{for(let s=0;s<a.length;s++){const c=a[s];typeof c=="function"?c():jd(r[s],null)}}},[])}Dn(Vg,"useStableComposedRefs");function Pi(e){return e?.animationName||"none"}Dn(Pi,"getAnimationName");function Kg(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}Dn(Kg,"getElementRef");var Wk=Object.defineProperty,Od=(e,t)=>Wk(e,"name",{value:t,configurable:!0}),ys=0,Ni=null;function Jk(e){return Ei(),e.children}Od(Jk,"FocusGuards");function Ei(){V(()=>{Ni||(Ni={start:Md(),end:Md()});const{start:e,end:t}=Ni;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),ys++,()=>{ys===1&&(Ni?.start.remove(),Ni?.end.remove(),Ni=null),ys=Math.max(0,ys-1)}},[])}Od(Ei,"useFocusGuards");function Md(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}Od(Md,"createFocusGuard");var un=function(){return un=Object.assign||function(t){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},un.apply(this,arguments)};function zg(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function Yk(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||(a=Array.prototype.slice.call(t,0,r)),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}var bs="right-scroll-bar-position",_s="width-before-scroll-bar",Xk="with-scroll-bars-hidden",Qk="--removed-body-scroll-bar-size";function Fd(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Zk(e,t){var n=D(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var i=n.value;i!==r&&(n.value=r,n.callback(r,i))}}}})[0];return n.callback=t,n.facade}var eT=typeof window<"u"?Tt:V,Wg=new WeakMap;function tT(e,t){var n=Zk(t||null,function(r){return e.forEach(function(i){return Fd(i,r)})});return eT(function(){var r=Wg.get(n);if(r){var i=new Set(r),a=new Set(e),s=n.current;i.forEach(function(c){a.has(c)||Fd(c,null)}),a.forEach(function(c){i.has(c)||Fd(c,s)})}Wg.set(n,e)},[e]),n}function nT(e){return e}function rT(e,t){t===void 0&&(t=nT);var n=[],r=!1;return{read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(i){var a=t(i,r);return n.push(a),function(){n=n.filter(function(s){return s!==a})}},assignSyncMedium:function(i){for(r=!0;n.length;){var a=n;n=[],a.forEach(i)}n={push:function(s){return i(s)},filter:function(){return n}}},assignMedium:function(i){r=!0;var a=[];if(n.length){var s=n;n=[],s.forEach(i),a=n}var c=function(){var d=a;a=[],d.forEach(i)},l=function(){return Promise.resolve().then(c)};l(),n={push:function(d){a.push(d),l()},filter:function(d){return a=a.filter(d),n}}}}}function iT(e){e===void 0&&(e={});var t=rT(null);return t.options=un({async:!0,ssr:!1},e),t}var Jg=function(e){var t=e.sideCar,n=zg(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return g(r,un({},n))};Jg.isSideCarExport=!0;function aT(e,t){return e.useMedium(t),Jg}var Yg=iT(),Bd=function(){},ws=W(function(e,t){var n=B(null),r=D({onScrollCapture:Bd,onWheelCapture:Bd,onTouchMoveCapture:Bd}),i=r[0],a=r[1],s=e.forwardProps,c=e.children,l=e.className,d=e.removeScrollBar,u=e.enabled,p=e.shards,f=e.sideCar,m=e.noRelative,v=e.noIsolation,b=e.inert,h=e.allowPinchZoom,y=e.as,w=y===void 0?"div":y,_=e.gapMode,R=zg(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),I=f,T=tT([n,t]),A=un(un({},R),i);return g(z,null,u&&g(I,{sideCar:Yg,removeScrollBar:d,shards:p,noRelative:m,noIsolation:v,inert:b,setCallbacks:a,allowPinchZoom:!!h,lockRef:n,gapMode:_}),s?jr($r.only(c),un(un({},A),{ref:T})):g(w,un({},A,{className:l,ref:T}),c))});ws.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},ws.classNames={fullWidth:_s,zeroRight:bs};var Xg,oT=function(){if(Xg)return Xg;if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function sT(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=oT();return t&&e.setAttribute("nonce",t),e}function cT(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function lT(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}var dT=function(){var e=0,t=null;return{add:function(n){e==0&&(t=sT())&&(cT(t,n),lT(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},uT=function(){var e=dT();return function(t,n){V(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Qg=function(){var e=uT(),t=function(n){var r=n.styles,i=n.dynamic;return e(r,i),null};return t},pT={left:0,top:0,right:0,gap:0},qd=function(e){return parseInt(e||"",10)||0},fT=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],i=t[e==="padding"?"paddingRight":"marginRight"];return[qd(n),qd(r),qd(i)]},mT=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return pT;var t=fT(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},hT=Qg(),Na="data-scroll-locked",gT=function(e,t,n,r){var i=e.left,a=e.top,s=e.right,c=e.gap;return n===void 0&&(n="margin"),`
2
+ .`.concat(Xk,` {
3
3
  overflow: hidden `).concat(r,`;
4
4
  padding-right: `).concat(c,"px ").concat(r,`;
5
5
  }
6
- body[`).concat(ko,`] {
6
+ body[`).concat(Na,`] {
7
7
  overflow: hidden `).concat(r,`;
8
8
  overscroll-behavior: contain;
9
9
  `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&`
10
10
  padding-left: `.concat(i,`px;
11
- padding-top: `).concat(o,`px;
11
+ padding-top: `).concat(a,`px;
12
12
  padding-right: `).concat(s,`px;
13
13
  margin-left:0;
14
14
  margin-top:0;
@@ -16,96 +16,95 @@
16
16
  `),n==="padding"&&"padding-right: ".concat(c,"px ").concat(r,";")].filter(Boolean).join(""),`
17
17
  }
18
18
 
19
- .`).concat(cs,` {
19
+ .`).concat(bs,` {
20
20
  right: `).concat(c,"px ").concat(r,`;
21
21
  }
22
22
 
23
- .`).concat(ls,` {
23
+ .`).concat(_s,` {
24
24
  margin-right: `).concat(c,"px ").concat(r,`;
25
25
  }
26
26
 
27
- .`).concat(cs," .").concat(cs,` {
27
+ .`).concat(bs," .").concat(bs,` {
28
28
  right: 0 `).concat(r,`;
29
29
  }
30
30
 
31
- .`).concat(ls," .").concat(ls,` {
31
+ .`).concat(_s," .").concat(_s,` {
32
32
  margin-right: 0 `).concat(r,`;
33
33
  }
34
34
 
35
- body[`).concat(ko,`] {
36
- `).concat(JI,": ").concat(c,`px;
35
+ body[`).concat(Na,`] {
36
+ `).concat(Qk,": ").concat(c,`px;
37
37
  }
38
- `)},wg=function(){var e=parseInt(document.body.getAttribute("data-scroll-locked")||"0",10);return isFinite(e)?e:0},mk=function(){V(function(){return document.body.setAttribute(ko,(wg()+1).toString()),function(){var e=wg()-1;e<=0?document.body.removeAttribute(ko):document.body.setAttribute(ko,e.toString())}},[])},hk=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;mk();var o=ke(function(){return uk(i)},[i]);return y(pk,{styles:fk(o,!t,i,n?"":"!important")})},yd=!1;if(typeof window<"u")try{var us=Object.defineProperty({},"passive",{get:function(){return yd=!0,!0}});window.addEventListener("test",us,us),window.removeEventListener("test",us,us)}catch{yd=!1}var Ri=yd?{passive:!1}:!1,gk=function(e){return e.tagName==="TEXTAREA"},Sg=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!gk(e)&&n[t]==="visible")},vk=function(e){return Sg(e,"overflowY")},yk=function(e){return Sg(e,"overflowX")},Cg=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host),Rg(e,r)){var i=Ig(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},bk=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},_k=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},Rg=function(e,t){return e==="v"?vk(t):yk(t)},Ig=function(e,t){return e==="v"?bk(t):_k(t)},wk=function(e,t){return e==="h"&&t==="rtl"?-1:1},Sk=function(e,t,n,r,i){var o=wk(e,window.getComputedStyle(t).direction),s=o*r,c=n.target,l=t.contains(c),d=!1,u=s>0,p=0,f=0;do{if(!c)break;var m=Ig(e,c),v=m[0],g=m[1]-m[2]-o*v;(v||g)&&Rg(e,c)&&(p+=g,f+=v);var h=c.parentNode;c=h&&h.nodeType===Node.DOCUMENT_FRAGMENT_NODE?h.host:h}while(!l&&c!==document.body||l&&(t.contains(c)||t===c));return(u&&(i&&Math.abs(p)<1||!i&&s>p)||!u&&(i&&Math.abs(f)<1||!i&&-s>f))&&(d=!0),d},ps=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},kg=function(e){return[e.deltaX,e.deltaY]},Tg=function(e){return e&&"current"in e?e.current:e},Ck=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Rk=function(e){return`
38
+ `)},Zg=function(){var e=parseInt(document.body.getAttribute("data-scroll-locked")||"0",10);return isFinite(e)?e:0},vT=function(){V(function(){return document.body.setAttribute(Na,(Zg()+1).toString()),function(){var e=Zg()-1;e<=0?document.body.removeAttribute(Na):document.body.setAttribute(Na,e.toString())}},[])},yT=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;vT();var a=Ie(function(){return mT(i)},[i]);return g(hT,{styles:gT(a,!t,i,n?"":"!important")})},Ud=!1;if(typeof window<"u")try{var Ss=Object.defineProperty({},"passive",{get:function(){return Ud=!0,!0}});window.addEventListener("test",Ss,Ss),window.removeEventListener("test",Ss,Ss)}catch{Ud=!1}var Ai=Ud?{passive:!1}:!1,bT=function(e){return e.tagName==="TEXTAREA"},ev=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!bT(e)&&n[t]==="visible")},_T=function(e){return ev(e,"overflowY")},wT=function(e){return ev(e,"overflowX")},tv=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host),nv(e,r)){var i=rv(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},ST=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},CT=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},nv=function(e,t){return e==="v"?_T(t):wT(t)},rv=function(e,t){return e==="v"?ST(t):CT(t)},RT=function(e,t){return e==="h"&&t==="rtl"?-1:1},IT=function(e,t,n,r,i){var a=RT(e,window.getComputedStyle(t).direction),s=a*r,c=n.target,l=t.contains(c),d=!1,u=s>0,p=0,f=0;do{if(!c)break;var m=rv(e,c),v=m[0],b=m[1]-m[2]-a*v;(v||b)&&nv(e,c)&&(p+=b,f+=v);var h=c.parentNode;c=h&&h.nodeType===Node.DOCUMENT_FRAGMENT_NODE?h.host:h}while(!l&&c!==document.body||l&&(t.contains(c)||t===c));return(u&&(i&&Math.abs(p)<1||!i&&s>p)||!u&&(i&&Math.abs(f)<1||!i&&-s>f))&&(d=!0),d},Cs=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},iv=function(e){return[e.deltaX,e.deltaY]},av=function(e){return e&&"current"in e?e.current:e},kT=function(e,t){return e[0]===t[0]&&e[1]===t[1]},TT=function(e){return`
39
39
  .block-interactivity-`.concat(e,` {pointer-events: none;}
40
40
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
41
- `)},Ik=0,Ii=[];function kk(e){var t=B([]),n=B([0,0]),r=B(),i=x(Ik++)[0],o=x(_g)[0],s=B(e);V(function(){s.current=e},[e]),V(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var g=zI([e.lockRef.current],(e.shards||[]).map(Tg),!0).filter(Boolean);return g.forEach(function(h){return h.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),g.forEach(function(h){return h.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var c=ae(function(g,h){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!s.current.allowPinchZoom;var b=ps(g),w=n.current,_="deltaX"in g?g.deltaX:w[0]-b[0],R="deltaY"in g?g.deltaY:w[1]-b[1],I,T=g.target,A=Math.abs(_)>Math.abs(R)?"h":"v";if("touches"in g&&A==="h"&&T.type==="range")return!1;var O=window.getSelection(),F=O&&O.anchorNode;if(F&&(F===T||F.contains(T)))return!1;var N=Cg(A,T);if(!N)return!0;if(N?I=A:(I=A==="v"?"h":"v",N=Cg(A,T)),!N)return!1;if(!r.current&&"changedTouches"in g&&(_||R)&&(r.current=I),!I)return!0;var L=r.current||I;return Sk(L,h,g,L==="h"?_:R,!0)},[]),l=ae(function(g){var h=g;if(!(!Ii.length||Ii[Ii.length-1]!==o)){var b="deltaY"in h?kg(h):ps(h),w=t.current.filter(function(R){return R.name===h.type&&(R.target===h.target||h.target===R.shadowParent)&&Ck(R.delta,b)})[0];if(w&&w.should){h.cancelable&&h.preventDefault();return}if(!w){var _=(s.current.shards||[]).map(Tg).filter(Boolean).filter(function(R){return R.contains(h.target)});(_.length>0?c(h,_[0]):!s.current.noIsolation)&&h.cancelable&&h.preventDefault()}}},[]),d=ae(function(g,h,b,w){var _={name:g,delta:h,target:b,should:w,shadowParent:Tk(b)};t.current.push(_),setTimeout(function(){t.current=t.current.filter(function(R){return R!==_})},1)},[]),u=ae(function(g){n.current=ps(g),r.current=void 0},[]),p=ae(function(g){d(g.type,kg(g),g.target,c(g,e.lockRef.current))},[]),f=ae(function(g){d(g.type,ps(g),g.target,c(g,e.lockRef.current))},[]);V(function(){return Ii.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:f}),document.addEventListener("wheel",l,Ri),document.addEventListener("touchmove",l,Ri),document.addEventListener("touchstart",u,Ri),function(){Ii=Ii.filter(function(g){return g!==o}),document.removeEventListener("wheel",l,Ri),document.removeEventListener("touchmove",l,Ri),document.removeEventListener("touchstart",u,Ri)}},[]);var m=e.removeScrollBar,v=e.inert;return y(z,null,v?y(o,{styles:Rk(i)}):null,m?y(hk,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Tk(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var Pk=nk(yg,kk),To=J(function(e,t){return y(ds,ln({},e,{ref:t,sideCar:Pk}))});To.classNames=ds.classNames;var Nk=function(e){return typeof document>"u"?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},ki=new WeakMap,fs=new WeakMap,ms={},bd=0,Pg=function(e){return e&&(e.host||Pg(e.parentNode))},Ek=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=Pg(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},Ak=function(e,t,n,r){var i=Ek(t,Array.isArray(e)?e:[e]);ms[n]||(ms[n]=new WeakMap);var o=ms[n],s=[],c=new Set,l=new Set(i),d=function(p){!p||c.has(p)||(c.add(p),d(p.parentNode))};i.forEach(d);var u=function(p){!p||l.has(p)||Array.prototype.forEach.call(p.children,function(f){if(c.has(f))u(f);else try{var m=f.getAttribute(r),v=m!==null&&m!=="false",g=(ki.get(f)||0)+1,h=(o.get(f)||0)+1;ki.set(f,g),o.set(f,h),s.push(f),g===1&&v&&fs.set(f,!0),h===1&&f.setAttribute(n,"true"),v||f.setAttribute(r,"true")}catch(b){console.error("aria-hidden: cannot operate on ",f,b)}})};return u(t),c.clear(),bd++,function(){s.forEach(function(p){var f=ki.get(p)-1,m=o.get(p)-1;ki.set(p,f),o.set(p,m),f||(fs.has(p)||p.removeAttribute(r),fs.delete(p)),m||p.removeAttribute(n)}),bd--,bd||(ki=new WeakMap,ki=new WeakMap,fs=new WeakMap,ms={})}},hs=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=t||Nk(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),Ak(r,i,n,"aria-hidden")):function(){return null}},xk=Object.defineProperty,dn=(e,t)=>xk(e,"name",{value:t,configurable:!0}),_d="Dialog",[Ng,F2]=dt(_d),[Dk,Xn]=Ng(_d),Lk=dn(e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:o,modal:s=!0}=e,c=B(null),l=B(null),[d,u]=At({prop:r,defaultProp:i??!1,onChange:o,caller:_d}),[p,f]=x(0),[m,v]=x(0);return a(Dk,{scope:t,triggerRef:c,contentRef:l,contentId:Et(),titleId:Et(),descriptionId:Et(),titlePresent:p>0,descriptionPresent:m>0,setTitleCount:f,setDescriptionCount:v,open:d,onOpenChange:u,onOpenToggle:ae(()=>u(g=>!g),[u]),modal:s,children:n})},"Dialog"),Eg="DialogPortal",[$k,Ag]=Ng(Eg,{forceMount:void 0}),Ok=dn(e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,o=Xn(Eg,t);return a($k,{scope:t,forceMount:n,children:Tr.map(r,s=>a(kt,{present:n||o.open,children:a(_i,{asChild:!0,container:i,children:s})}))})},"DialogPortal"),wd="DialogOverlay",jk=J(dn(function(t,n){const r=Ag(wd,t.__scopeDialog),{forceMount:i=r.forceMount,...o}=t,s=Xn(wd,t.__scopeDialog);return s.modal?a(kt,{present:i||s.open,children:a(Fk,{...o,ref:n})}):null},"DialogOverlay")),Mk=cn("DialogOverlay.RemoveScroll"),Fk=J(dn(function(t,n){const{__scopeDialog:r,...i}=t,o=Xn(wd,r),s=eg(),c=Re(n,s);return a(To,{as:Mk,allowPinchZoom:!0,shards:[o.contentRef],children:a(ye.div,{"data-state":Sd(o.open),...i,ref:c,style:{pointerEvents:"auto",...i.style}})})},"DialogOverlayImpl")),Po="DialogContent",Bk=J(dn(function(t,n){const r=Ag(Po,t.__scopeDialog),{forceMount:i=r.forceMount,...o}=t,s=Xn(Po,t.__scopeDialog);return a(kt,{present:i||s.open,children:s.modal?a(qk,{...o,ref:n}):a(Uk,{...o,ref:n})})},"DialogContent")),qk=J(dn(function(t,n){const r=Xn(Po,t.__scopeDialog),i=B(null),o=Re(n,r.contentRef,i);return V(()=>{const s=i.current;if(s)return hs(s)},[]),a(xg,{...t,ref:o,trapFocus:r.open,disableOutsidePointerEvents:r.open,onCloseAutoFocus:te(t.onCloseAutoFocus,s=>{s.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:te(t.onPointerDownOutside,s=>{const c=s.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0;(c.button===2||l)&&s.preventDefault()}),onFocusOutside:te(t.onFocusOutside,s=>s.preventDefault())})},"DialogContentModal")),Uk=J(dn(function(t,n){const r=Xn(Po,t.__scopeDialog),i=B(!1),o=B(!1);return a(xg,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{t.onCloseAutoFocus?.(s),s.defaultPrevented||(i.current||r.triggerRef.current?.focus(),s.preventDefault()),i.current=!1,o.current=!1},onInteractOutside:s=>{t.onInteractOutside?.(s),s.defaultPrevented||(i.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const c=s.target;r.triggerRef.current?.contains(c)&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})},"DialogContentNonModal")),xg=J(dn(function(t,n){const{__scopeDialog:r,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:s,...c}=t,l=Xn(Po,r);return Ci(),a(z,{children:a(as,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:o,onUnmountAutoFocus:s,children:a(bi,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionPresent?l.descriptionId:void 0,"aria-labelledby":l.titlePresent?l.titleId:void 0,"data-state":Sd(l.open),...c,ref:n,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})},"DialogContentImpl")),Gk="DialogTitle",Hk=J(dn(function(t,n){const{__scopeDialog:r,...i}=t,o=Xn(Gk,r),{setTitleCount:s}=o;return Ze(()=>(s(c=>c+1),()=>s(c=>c-1)),[s]),a(ye.h2,{id:o.titleId,...i,ref:n})},"DialogTitle"));function Sd(e){return e?"open":"closed"}dn(Sd,"getState");function Qn({ariaDescribedby:e,ariaLabelledby:t,children:n,contentClassName:r,contentId:i,modal:o=!0,onCloseAutoFocus:s,onEscapeKeyDown:c,onInteractOutside:l,onOpenAutoFocus:d,onOpenChange:u,open:p,overlayClassName:f,overlayId:m,slotId:v}){return a(Lk,{modal:o,open:p,onOpenChange:u,children:p?a(Ok,{children:[a(jk,{asChild:!0,children:a("div",{className:f,id:m})}),a(Bk,{"aria-describedby":e,"aria-labelledby":t,asChild:!0,onCloseAutoFocus:s,onEscapeKeyDown:c,onInteractOutside:l,onOpenAutoFocus:d,children:a("div",{role:"dialog",className:r,id:i,onClick:g=>{g.target===g.currentTarget&&u(!1)},tabIndex:-1,children:n??(v?a("div",{id:v}):null)})})]}):null})}function Dg(e){return a(Hk,{...e})}function Vk(e,t){return e.canonicalId<t.canonicalId?-1:e.canonicalId>t.canonicalId?1:0}function No(e){return e.normalize("NFKC").replace(/\u200B/gu,"").replace(/\s+/gu," ").trim().toLowerCase()}function Lg(e){const t=new Map;for(const n of e){const r=t.get(n.canonicalId);(!r||n.displayName<r.displayName)&&t.set(n.canonicalId,n)}return[...t.values()].sort(Vk)}function Nr(e){const t=new Map;for(const r of Lg(e)){const i=No(r.displayName),o=t.get(i);o?o.push(r):t.set(i,[r])}const n=new Map;for(const r of t.values())for(const[i,o]of r.entries())n.set(o.canonicalId,r.length>1?`${o.displayName} — duplicate name ${i+1} of ${r.length}`:o.displayName);return n}function Kk(e){const t=new Map;for(const n of Lg(e)){const r=No(n.displayName),i=t.get(r);i?i.canonicalIds.push(n.canonicalId):t.set(r,{displayName:n.displayName,canonicalIds:[n.canonicalId],firstCanonicalId:n.canonicalId})}return[...t.values()].sort((n,r)=>{const i=No(n.displayName).localeCompare(No(r.displayName));return i!==0?i:n.firstCanonicalId<r.firstCanonicalId?-1:n.firstCanonicalId>r.firstCanonicalId?1:0}).map(n=>({displayName:n.displayName,identityCount:n.canonicalIds.length}))}var $g=500,gs=null,Eo=null,Ao=null;function xo(e){return Eo?Eo(e)?(Ao=document.activeElement instanceof HTMLElement?document.activeElement:null,!0):!1:(Ao=document.activeElement instanceof HTMLElement?document.activeElement:null,gs=e,!0)}function ut(e){return e.recipientKind==="identity"?`identity:${e.identityId}`:`team:${e.teamId}`}function Og(e){const t=e.indexOf(":"),n=e.slice(0,t),r=e.slice(t+1);return r?n==="identity"?{recipientKind:"identity",identityId:r}:n==="team"?{recipientKind:"team",teamId:r}:null:null}function Do(e){return e.recipientKind==="identity"?ut({recipientKind:"identity",identityId:e.identityId}):ut({recipientKind:"team",teamId:e.teamId})}function zk(e,t){return Do(e)===ut(t)}function Cd(e,t){const n=[...new Set(e)].sort((r,i)=>r<i?-1:r>i?1:0);return new Map(n.map((r,i)=>[r,n.length===1?t:`${t} ${i+1} of ${n.length}`]))}function Wk(e,t){if(t?.mode!=="project-manage")return new Map;const n=new Set(e.teams.map(c=>c.teamId)),r=new Set(e.identities.map(c=>c.identityId)),i=e.projectRecipients.filter(c=>c.status==="active"&&c.canonicalProjectIdentity===t.projectId),o=i.flatMap(c=>c.recipientKind==="team"&&!n.has(c.teamId)?[Do(c)]:[]),s=i.flatMap(c=>c.recipientKind==="identity"&&!r.has(c.identityId)?[Do(c)]:[]);return new Map([...Cd(o,"Unavailable Team"),...Cd(s,"Unavailable Identity")])}function Jk(e,t,n){if(t?.mode!=="recipient-manage")return new Map;const r=new Set(e.map(i=>i.canonicalProjectIdentity));return Cd(n.filter(i=>!r.has(i)),"Unavailable Project")}function jg(e,t){return e instanceof Nl?"Recipient access changed after this review. Review the refreshed changes before trying again.":t}function Mg({checked:e,description:t,disabled:n,label:r,onChange:i}){const o=`recipient-policy-choice-${Ir()}`;return a("label",{className:"sync-dialog-radio-option recipient-policy-management-choice recipient-policy-management-target",htmlFor:o,children:[a("input",{checked:e,disabled:n,id:o,onChange:i,type:"checkbox"}),a("span",{children:[a("strong",{className:"recipient-policy-management-name",children:r}),a("span",{className:"small recipient-policy-management-description",children:t})]})]})}function Yk(e,t,n){const r=e.teamMemberships.filter(c=>c.status==="active"),i=new Map(e.identities.map(c=>[c.identityId,c])),o=[...e.teams.filter(c=>c.status==="active").map(c=>{const l=r.filter(d=>d.teamId===c.teamId).map(d=>i.get(d.identityId)?.displayName).filter(d=>!!d);return{key:ut({recipientKind:"team",teamId:c.teamId}),label:c.displayName,description:`Team · ${l.length.toLocaleString()} current ${l.length===1?"member":"members"}${l.length?`: ${l.join(", ")}`:""}`}}),...e.identities.filter(c=>c.status==="active"||c.status==="pending").map(c=>({key:ut({recipientKind:"identity",identityId:c.identityId}),label:c.displayName,description:`Identity · ${c.status==="pending"?"pending · ":""}locally verified`}))];if(t?.mode!=="project-manage")return o;const s=new Set(o.map(c=>c.key));for(const c of e.projectRecipients){if(c.status!=="active"||c.canonicalProjectIdentity!==t.projectId)continue;const l=Do(c);if(!s.has(l)){if(c.recipientKind==="team"){const d=e.teams.find(p=>p.teamId===c.teamId),u=n.get(l)??"Unavailable Team";o.push({key:l,label:d?.displayName??u,description:`${d?.status==="archived"?"Archived Team":u} · existing access can only be removed`})}else{const d=i.get(c.identityId),u=n.get(l)??"Unavailable Identity";o.push({key:l,label:d?.displayName??u,description:`${d?.status==="merged"?"Merged Identity":u} · existing access can only be removed`})}s.add(l)}}return o}function Fg(e){return e.mode==="project-add"?[...new Set(e.projectIds)]:e.mode==="project-manage"?[e.projectId]:[]}function Xk(e,t){const n=t.projectRecipients.filter(r=>r.status==="active");return e.mode==="project-add"?[]:e.mode==="project-manage"?n.filter(r=>r.canonicalProjectIdentity===e.projectId).map(Do):n.filter(r=>zk(r,e.recipient)).map(r=>r.canonicalProjectIdentity)}function Qk(e,t,n,r){const i=Nr(e.map(d=>({canonicalId:d.canonicalProjectIdentity,displayName:d.displayName}))),o=t.mode==="recipient-add"?e.filter(d=>!n.includes(d.canonicalProjectIdentity)):e,s=o.map(d=>({...d,displayName:i.get(d.canonicalProjectIdentity)??d.displayName,description:`${d.existingMemoryCount.toLocaleString()} existing memories`}));if(t.mode!=="recipient-manage")return s;const c=new Set(o.map(d=>d.canonicalProjectIdentity)),l=n.filter(d=>!c.has(d));for(const d of l){const u=r.get(d)??"Unavailable Project";s.push({canonicalProjectIdentity:d,displayName:u,existingMemoryCount:0,description:`${u} · existing access can only be removed`})}return s}function Zk(e,t,n){return e.mode==="project-add"?Fg(e).flatMap(r=>t.flatMap(i=>{const o=Og(i);return o?[{canonicalProjectIdentity:r,recipient:o,action:"add"}]:[]})):e.mode==="project-manage"?[...new Set([...n,...t])].flatMap(r=>{const i=Og(r);return!i||n.includes(r)===t.includes(r)?[]:[{canonicalProjectIdentity:e.projectId,recipient:i,action:t.includes(r)?"add":"remove"}]}):e.mode==="recipient-add"?t.map(r=>({canonicalProjectIdentity:r,recipient:e.recipient,action:"add"})):[...new Set([...n,...t])].flatMap(r=>n.includes(r)===t.includes(r)?[]:[{canonicalProjectIdentity:r,recipient:e.recipient,action:t.includes(r)?"add":"remove"}])}function eT(e){return e.mode==="project-add"?{title:"Add recipient access",description:"Choose the Teams and Identities that should receive the selected Projects.",legend:"Choose recipients"}:e.mode==="project-manage"?{title:"Manage Project recipients",description:"Choose exactly which Teams and Identities receive this Project.",legend:"Project recipients"}:e.mode==="recipient-add"?{title:"Add Projects",description:"Choose additional Projects for this recipient. Existing access cannot be removed here.",legend:"Additional Projects"}:{title:"Manage recipient Projects",description:"Choose exactly which Projects this recipient receives.",legend:"Recipient Projects"}}function Bg(e,t){let n=!1,r=!1,i=!1,o=!1;const s=ut(t);for(const c of e){const{change:l,outcome:d}=c;ut(l.recipient)===s&&(l.action==="add"?(i=!0,d==="added"&&(n=!0)):(o=!0,d==="removed"&&(r=!0)))}return n&&r?"Mixed changes":r?"Removing access":n?"Adding access":i&&!o?"Already has access":o&&!i?"Already without access":"No changes"}function tT(e){const t=new Set(e.selectedRecipients.map(ut)),n=new Map;for(const r of e.normalizedChanges){const i=ut(r.recipient);t.has(i)||n.set(i,r.recipient)}return[...n.values()]}function nT(e){const t=new Set;return e.filter(n=>t.has(n.deviceId)?!1:(t.add(n.deviceId),!0))}function Rd(e,t){const n=t.get(e.canonicalProjectIdentity);return n||(e.displayName!==e.canonicalProjectIdentity?e.displayName:"Unavailable Project")}function rT({preview:e,projectLabels:t,recipientLabels:n}){const r=nT(e.effectiveDevices),i=tT(e);return a("div",{className:"sync-dialog-stack recipient-policy-management-review",children:[a("section",{"aria-labelledby":"recipient-policy-review-projects",children:[a("h3",{id:"recipient-policy-review-projects",children:"Projects affected"}),a("ul",{children:e.projects.map(o=>a("li",{children:[a("strong",{className:"recipient-policy-management-name",children:Rd(o,t)}),a("span",{children:[" ","— Access changes affect ",o.existingMemoryCount.toLocaleString()," existing memories",o.futureMemoriesShared?" and future activity":"; future activity is not included"]})]},o.canonicalProjectIdentity))})]}),a("section",{"aria-labelledby":"recipient-policy-review-recipients",children:[a("h3",{id:"recipient-policy-review-recipients",children:"Recipient changes"}),a("ul",{children:[e.selectedRecipients.map(o=>a("li",{children:[a("strong",{className:"recipient-policy-management-name",children:o.displayName})," ",a("span",{children:["— ",Bg(e.outcomes,o)," · "]}),o.recipientKind==="identity"?a("span",{children:"Identity · locally verified"}):a("span",{className:"recipient-policy-management-recipient-context",children:["Team · ",o.currentMembers.length.toLocaleString()," current"," ",o.currentMembers.length===1?"member":"members",o.currentMembers.length?a(z,{children:[":"," ",a("span",{className:"recipient-policy-management-member-names",children:o.currentMembers.map(s=>s.displayName).join(", ")})]}):null,". Future Team members"," ",o.futureMembersInherit?"inherit":"do not inherit"," access."]})]},ut(o))),i.map(o=>a("li",{children:[a("strong",{className:"recipient-policy-management-name",children:n.get(ut(o))??(o.recipientKind==="team"?"Unavailable Team":"Unavailable Identity")})," ",a("span",{children:["— ",Bg(e.outcomes,o)," ·"," ",o.recipientKind==="team"?"Team":"Identity"]})]},ut(o)))]})]}),a("section",{"aria-labelledby":"recipient-policy-review-availability",children:[a("h3",{id:"recipient-policy-review-availability",children:"Resulting availability"}),r.length?a(z,{children:[a("p",{children:["After the update, the affected Projects will be available on"," ",r.length.toLocaleString()," current"," ",r.length===1?"device":"devices"," across all recipients."]}),a("ul",{children:r.map(o=>a("li",{className:"recipient-policy-management-name",children:o.displayName},o.deviceId))})]}):a("p",{children:"After the update, no recipient devices will have access to the affected Projects yet — for example, a Team with no current members. Your own access on this device is not affected."})]}),a("details",{className:"recipient-policy-management-details",children:[a("summary",{children:"Change details"}),a("p",{className:"small",children:[e.addCount.toLocaleString()," ",e.addCount===1?"add":"adds"," ·"," ",e.removeCount.toLocaleString()," ",e.removeCount===1?"remove":"removes"," ","· ",e.netWriteCount.toLocaleString()," ",e.netWriteCount===1?"write":"writes"]}),e.unchangedProjects.length?a(z,{children:[a("p",{className:"small recipient-policy-management-detail-label",children:a("strong",{children:"Unchanged Projects"})}),a("ul",{"aria-label":"Unchanged Projects",children:e.unchangedProjects.map(o=>a("li",{className:"recipient-policy-management-name",children:Rd(o,t)},o.canonicalProjectIdentity))})]}):null]})]})}function iT({preview:e,projectLabels:t,recipientLabels:n,result:r}){const i=r.status==="applied"?"Applied":r.status==="not_found"?"Not found":`${r.status.charAt(0).toUpperCase()}${r.status.slice(1)}`;return a("div",{className:"sync-dialog-stack recipient-policy-management-result",children:a("details",{className:"recipient-policy-management-details",children:[a("summary",{children:"Technical details"}),a("p",{children:["Status: ",i,". Writes: ",r.writeCount.toLocaleString(),"."]}),r.errorCode?a("p",{children:["Error code: ",r.errorCode.replaceAll("_"," "),"."]}):null,r.outcomes.length?a("ul",{children:r.outcomes.map(o=>{const s=e.projects.find(d=>d.canonicalProjectIdentity===o.change.canonicalProjectIdentity),c=s?Rd(s,t):t.get(o.change.canonicalProjectIdentity)??"Unavailable Project",l=e.selectedRecipients.find(d=>ut(d)===ut(o.change.recipient))?.displayName??n.get(ut(o.change.recipient))??(o.change.recipient.recipientKind==="team"?"Team":"Identity");return a("li",{children:[o.change.action==="add"?"Add":"Remove"," ",l," ",o.change.action==="add"?"to":"from"," ",c,":"," ",o.outcome.replaceAll("_"," ")]},`${o.change.canonicalProjectIdentity}:${ut(o.change.recipient)}`)})}):null]})})}function oT({intent:e,options:t,projects:n}){const[r,i]=x(null),[o,s]=x([]),[c,l]=x([]),[d,u]=x(null),[p,f]=x(null),[m,v]=x(null),[g,h]=x(""),[b,w]=x(!1),_=B(!1),R=B(new Map),I=B(new Map),T=ke(()=>Wk(e,r),[e,r]),A=ke(()=>Yk(e,r,T),[e,r,T]),O=ke(()=>new Map([...e.teams.map(X=>[`team:${X.teamId}`,X.displayName]),...e.identities.map(X=>[`identity:${X.identityId}`,X.displayName]),...T]),[e,T]),F=ke(()=>Jk(n,r,c),[c,n,r]),N=ke(()=>new Set(n.map(X=>X.canonicalProjectIdentity)),[n]),L=ke(()=>{const X=Nr(n.map(ce=>({canonicalId:ce.canonicalProjectIdentity,displayName:ce.displayName})));return new Map([...X,...F])},[n,F]);if(V(()=>{if(Eo=X=>{if(_.current)return!1;const ce=Xk(X,e);return i(X),l(ce),s(X.mode==="recipient-add"?[]:ce),u(null),f(null),R.current=new Map,I.current=new Map,v(null),h(""),w(!1),_.current=!1,!0},gs){const X=gs;gs=null,Eo(X)}return()=>{Eo=null}},[e]),V(()=>{p&&document.getElementById("recipient-policy-management-title")?.focus()},[p]),!r)return null;const D=eT(r),G=Fg(r),q=r.mode==="recipient-manage"?!1:G.some(X=>!N.has(X)),$=(r.mode==="recipient-add"||r.mode==="recipient-manage")&&!A.some(X=>X.key===ut(r.recipient)),E=t.loading||t.loadError||q||$,S=Zk(r,o,c),M=S.length>$g,H=(r.mode==="project-add"||r.mode==="recipient-add")&&o.length===0,U=r.mode!=="project-add"&&r.mode!=="recipient-add"&&S.length===0,re=Qk(n,r,c,F),oe=p?.status==="applied",ie=p?oe?"Recipient access updated":"Recipient access needs attention":d?"Review recipient access":D.title,se=p?oe?"The reviewed recipient access changes are applied.":"Some reviewed recipient access changes were not applied. Review the technical details.":d?"Confirm the exact Projects, recipients, and resulting access.":D.description,ue=()=>{_.current||(i(null),u(null),f(null),R.current=new Map,I.current=new Map,v(null),h(""))},Pe=X=>{s(ce=>ce.includes(X)?ce.filter(be=>be!==X):[...ce,X]),v(null),h("")},Ie=async()=>{if(!(E||H||U||M||_.current)){_.current=!0,w(!0),v(null),h("Reviewing exact recipient access changes.");try{const X=await yR({version:1,changes:S});R.current=new Map(O),I.current=new Map(L),u(X),h("Review ready. Confirm the exact changes.")}catch(X){v(jg(X,"Unable to review recipient access changes.")),h("")}finally{_.current=!1,w(!1)}}},le=async()=>{if(!(!d||_.current)){_.current=!0,w(!0),v(null),h("Saving recipient access changes.");try{const X=await bR({version:1,changes:d.normalizedChanges,reviewedPolicyDigest:d.reviewedPolicyDigest});f(X),h("");try{await t.onCommitted?.(X)}catch{v("Recipient access was saved, but this view could not refresh.")}}catch(X){X instanceof Nl&&(u(null),R.current=new Map,I.current=new Map,h("")),v(jg(X,"Unable to save recipient access changes."))}finally{_.current=!1,w(!1)}}};let ve=null;return t.loading?ve="Loading the complete recipient access inventory…":t.loadError?ve="The complete recipient access inventory is unavailable. Refresh and try again.":q?ve="One selected Project is no longer available. Refresh and try again.":$&&(ve="This recipient is no longer available. Refresh and try again."),a(Qn,{ariaDescribedby:"recipient-policy-management-description",ariaLabelledby:"recipient-policy-management-title",contentClassName:"modal recipient-policy-management-dialog",contentId:"recipientPolicyManagementDialog",onCloseAutoFocus:X=>{X.preventDefault();const ce=r.mode.startsWith("project-")?"tabBtn-projects":"tabBtn-sharing",be=Ao?.isConnected?Ao:document.getElementById(ce);be instanceof HTMLElement&&be.focus(),Ao=null},onOpenAutoFocus:X=>{const ce=document.getElementById("recipient-policy-management-title");ce&&(X.preventDefault(),ce.focus())},onOpenChange:X=>{X||ue()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientPolicyManagementDialogBackdrop",children:a("div",{"aria-busy":b||t.loading?"true":"false",className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:"recipient-policy-management-title",tabIndex:-1,children:ie}),a(kr,{ariaLabel:`Close ${ie}`,className:"modal-close-button recipient-policy-management-target",disabled:b,onClick:ue})]}),a("div",{className:"modal-body recipient-policy-management-selection",children:[a("p",{className:"small",id:"recipient-policy-management-description",children:se}),ve?a("p",{"aria-live":"polite",role:t.loadError?"alert":"status",children:ve}):p&&d?a(iT,{preview:d,projectLabels:I.current,recipientLabels:R.current,result:p}):d?a(rT,{preview:d,projectLabels:I.current,recipientLabels:R.current}):r.mode==="recipient-add"||r.mode==="recipient-manage"?a("fieldset",{className:"sync-dialog-radio-list",disabled:b,children:[a("legend",{children:D.legend}),re.length?re.map(X=>a(Mg,{checked:o.includes(X.canonicalProjectIdentity),description:X.description,disabled:b,label:X.displayName,onChange:()=>Pe(X.canonicalProjectIdentity)},X.canonicalProjectIdentity)):a("p",{className:"small",role:"status",children:r.mode==="recipient-add"?"No additional Projects are available.":"No Projects are available."})]}):a("fieldset",{className:"sync-dialog-radio-list",disabled:b,children:[a("legend",{children:D.legend}),A.length?A.map(X=>a(Mg,{checked:o.includes(X.key),description:X.description,disabled:b,label:X.label,onChange:()=>Pe(X.key)},X.key)):a("p",{className:"small",role:"status",children:"No active Teams or Identities are available."})]}),p?null:a("p",{"aria-live":"polite",className:"small recipient-policy-management-status",role:"status",children:g}),m?a("p",{"aria-live":"assertive",role:"alert",children:m}):null,M?a("p",{"aria-live":"assertive",role:"alert",children:["This selection creates ",S.length.toLocaleString()," access changes. Review at most ",$g.toLocaleString()," changes at a time; reduce the selection and try again."]}):null]}),a("div",{className:"modal-footer recipient-policy-management-actions",children:[a("button",{className:"settings-button recipient-policy-management-target",disabled:b,onClick:d&&!p?()=>{u(null),R.current=new Map,I.current=new Map,h("")}:ue,type:"button",children:p?"Done":d?"Back":"Cancel"}),!p&&!ve?a("button",{className:"settings-button sync-dialog-confirm recipient-policy-management-target",disabled:b||!d&&(H||U||M),onClick:()=>{d?le():Ie()},type:"button",children:b?d?"Saving…":"Reviewing…":d?"Confirm changes":"Review changes"}):null]})]})})}function qg(e,t,n,r={}){Ue(a(oT,{intent:n,options:r,projects:t}),e)}function vs(e){return e.identity_source!=="unmapped"&&e.read_only!==!0}function aT(e){const t=new Map;for(const n of e)n.read_only_reason==="peer_received"&&t.set(n.workspace_identity,{canonicalProjectIdentity:n.workspace_identity,displayName:n.display_project,existingMemoryCount:n.memory_count??0,latestSessionAt:n.latest_session_at??null});return[...t.values()].sort((n,r)=>n.displayName.localeCompare(r.displayName)||n.canonicalProjectIdentity.localeCompare(r.canonicalProjectIdentity))}function ys(e){const t=new Map;for(const n of e)vs(n)&&t.set(n.workspace_identity,{canonicalProjectIdentity:n.workspace_identity,displayName:n.display_project,existingMemoryCount:n.memory_count??0});return[...t.values()].sort((n,r)=>n.displayName.localeCompare(r.displayName)||n.canonicalProjectIdentity.localeCompare(r.canonicalProjectIdentity))}function Ug({detailRowCount:e=3,label:t}){return a(z,{children:[a("span",{className:"sr-only",role:"status",children:t}),a("div",{"aria-busy":"true",className:"loading-card-list",children:Array.from({length:2},(n,r)=>a("div",{"aria-hidden":"true",className:"loading-card",children:[a("div",{className:"loading-card-header",children:[a("span",{className:`loading-card-line loading-card-title ${r%2?"w-45":"w-60"}`}),a("span",{className:"loading-card-badge"})]}),a("div",{className:"loading-card-details",children:Array.from({length:e},(i,o)=>a("div",{className:"loading-card-detail",children:[a("span",{className:"loading-card-line loading-card-label"}),a("span",{className:`loading-card-line ${(r+o)%2?"w-45":"w-60"}`})]},o))})]},r))})]})}function sT(e){return e.state!=="configured"}function Gg(e){return e?.items.filter(sT)??[]}function bs(e,t){return e.truncated?{blocked:!0,recovery:"Refresh Devices after the complete inventory is available."}:e.coordinatorEvidence.availability==="available"?{blocked:!1,recovery:null}:e.coordinatorEvidence.safeErrorCode==="coordinator_not_configured"&&t.isLocal?{blocked:!1,recovery:null}:{blocked:!0,recovery:"Refresh Devices after coordinator device information is available."}}var cT=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,lT=/^(?:actor|device|identity|local):\S+$/iu,dT=/^(?:actor|device|identity)[_-][a-z0-9][a-z0-9._:-]{4,}$/iu,uT=/^pending[_-]\S+$/iu,pT=/^[a-f0-9]{12,64}$/iu,fT=/^(?=.{1,253}$)(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.){2,}[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?|[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.local)$/iu;function Id(e){return[cT,lT,dT,uT,pT,fT].some(t=>t.test(e))}function Ti(e){if(typeof e!="string"||[...e].some(n=>/[\p{Cc}\p{Cf}]/u.test(n)))return"";const t=e.replace(/\s+/gu," ").trim();return!t||[...t].length>120||Id(t)?"":t}var Pi=null,Ni=null;function _s(e=[],t=""){if(Ni){const n=Ni(e,t);return n||(Pi=null),n}return Pi={projectIds:e,teammateName:t},window.location.hash="#projects",!0}function Hg(e){return!e.read_only&&e.identity_source!=="unmapped"&&e.memory_count!=null&&!e.guardrail_warnings.some(t=>t.requires_confirmation)}function Vg(e,t){if(!(e instanceof Error))return t;switch(e.message){case"team_sharing_not_configured":return"Set up Team sharing before creating an invitation.";case"team_selection_ambiguous":return"Choose one active Team in settings before creating an invitation.";case"project_selection_ambiguous":return"One selected project has a name collision. Review its project identity first.";case"project_selection_unsupported":case"project_selection_unknown":case"reviewed_project_set_changed":return"The selected projects changed. Review the invitation again.";default:return t}}function mT(e){const t=`share-project-${Ir()}`,n=Hg(e.project);return a("label",{className:"sync-dialog-radio-option",htmlFor:t,children:[a("input",{checked:e.selected,disabled:!n,id:t,onChange:()=>e.onToggle(e.project.workspace_identity),type:"checkbox"}),a("span",{children:[a("strong",{children:e.project.display_project}),a("span",{className:"small",children:n?`${(e.project.memory_count??0).toLocaleString()} existing memories`:"Unavailable until this project identity is reviewed"})]})]})}function hT({preview:e}){return a("div",{className:"sync-dialog-stack",children:[a("p",{children:a("strong",{children:[e.teammate.display_name," will receive:"]})}),e.teammate.match==="existing"?a("p",{className:"small",children:"This invitation will use the existing teammate."}):null,a("ul",{children:e.projects.map(t=>a("li",{children:[t.existing_memory_count.toLocaleString()," existing memories and future activity from ",t.display_name]},t.project_id))}),a("p",{children:a("strong",{children:"No other projects will be shared."})})]})}function gT({projects:e,inventoryError:t}){const[n,r]=x(!1),[i,o]=x(""),[s,c]=x([]),[l,d]=x(null),[u,p]=x(null),[f,m]=x(null),[v,g]=x(!1),[h,b]=x(null),[w,_]=x(!1),R=ke(()=>e.filter(Hg),[e]);V(()=>{if(Ni=(N,L="")=>{if(t)return!1;const D=[...new Set(N)],G=D.some(q=>!R.some($=>$.workspace_identity===q));return o(L.trim()),c(G?[]:D),_(G),d(null),p(null),m(G?"The original project selection is no longer available. Refresh Projects and try again.":null),b(null),r(!0),!0},Pi){const N=Pi;Pi=null,Ni(N.projectIds,N.teammateName)}return()=>{Ni=null}},[R,t]),V(()=>{t&&(Pi=null,r(!1),o(""),c([]),d(null),p(null),m(null),b(null),_(!1))},[t]);const I=()=>{v||r(!1)},T=N=>{c(L=>L.includes(N)?L.filter(D=>D!==N):[...L,N])},A=async()=>{if(m(null),!i.trim()){m("Enter your teammate's name.");return}if(s.length===0){m("Select at least one project.");return}g(!0);try{d(await RR({teammate_name:i.trim(),project_ids:s}))}catch(N){m(Vg(N,"Unable to review this invitation."))}finally{g(!1)}},O=async()=>{if(l){m(null),g(!0);try{p(await IR({teammate_name:l.teammate.display_name,project_ids:l.projects.map(N=>N.project_id),reviewed_project_set_digest:l.reviewed_project_set_digest}))}catch(N){N instanceof Error&&N.message==="reviewed_project_set_changed"&&d(null),m(Vg(N,"Unable to create this invitation."))}finally{g(!1)}}},F=async()=>{if(u){m(null),b(null);try{if(!navigator.clipboard)throw new Error("Clipboard access is unavailable.");await navigator.clipboard.writeText(u.invite.link),b("Invite copied.")}catch(N){m(N instanceof Error?N.message:"Unable to copy the invitation.")}}};return a(z,{children:[a("button",{"aria-describedby":t?"project-share-inventory-error":void 0,className:"settings-button",disabled:t||R.length===0,onClick:()=>Ni?.([]),type:"button",children:"Share projects"}),t?a("p",{className:"small",id:"project-share-inventory-error",role:"status",children:"The complete project list is unavailable. Refresh Projects to try again."}):null,n?a(Qn,{ariaDescribedby:"project-share-description",ariaLabelledby:"project-share-title",contentClassName:"modal",contentId:"projectShareDialog",onOpenChange:N=>{N||I()},open:!0,overlayClassName:"modal-backdrop",overlayId:"projectShareDialogBackdrop",children:a("div",{className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:"project-share-title",children:"Share projects"}),a("button",{"aria-label":"Close Share projects",disabled:v,onClick:I,type:"button",children:"×"})]}),a("div",{"aria-busy":v,className:"modal-body",children:[a("p",{className:"small",id:"project-share-description",children:"Choose a teammate and the exact projects they may receive after accepting."}),u?a("div",{children:[a("p",{role:"status",children:["Invitation created for ",u.teammate.display_name,"."]}),a("p",{children:["Sharing starts after acceptance:"," ",u.projects.map(N=>N.display_name).join(", "),"."]}),a("p",{className:"small",children:["Invitation expires ",new Date(u.invite.expires_at).toLocaleString(),"."]}),a("button",{className:"settings-button",onClick:()=>{F()},type:"button",children:"Copy invite"}),h?a("p",{role:"status",children:h}):null]}):l?a(hT,{preview:l}):a(z,{children:[a("label",{className:"field",htmlFor:"project-share-teammate",children:[a("span",{children:"Who are you sharing with?"}),a("input",{autoFocus:!0,className:"sync-dialog-input",id:"project-share-teammate",maxLength:120,onInput:N=>o(N.currentTarget.value),type:"text",value:i})]}),a("fieldset",{className:"sync-dialog-radio-list",children:[a("legend",{children:"Select exact projects"}),e.map(N=>a(mT,{onToggle:T,project:N,selected:s.includes(N.workspace_identity)},N.workspace_identity))]})]}),f?a("p",{role:"alert",children:f}):null]}),a("div",{className:"modal-footer",children:[a("button",{className:"settings-button",disabled:v,onClick:I,type:"button",children:u?"Done":"Cancel"}),u?null:a("button",{className:"settings-button sync-dialog-confirm",disabled:v||w,onClick:()=>{l?O():A()},type:"button",children:v?l?"Creating invite…":"Reviewing…":l?"Create invite":"Review sharing"})]})]})}):null]})}function Kg(e,t,n={}){Ue(a(gT,{inventoryError:n.inventoryError===!0,projects:t}),e)}function kd(e){return Ti(String(e??"").trim())}function Ei(e,t){const n=e.trim();return n?[...n].length>120?`${t} must use 120 characters or fewer.`:[...n].some(r=>/[\p{Cc}\p{Cf}]/u.test(r))?`${t} cannot include control or format characters.`:Id(n)?`${t} must use a human-readable name.`:"":`${t} is required.`}function vT(e){return{...e,status:e.status==="pending_setup"?"pending_setup":void 0,setup_state:e.setup_state==="pending_inviter"||e.setup_state==="restart_required"?e.setup_state:void 0,restart_required:e.restart_required===!0,detail:typeof e.detail=="string"?e.detail:void 0,type:e.type==="project_share"?"project_share":void 0}}function ws(e,t){return e instanceof Error?e instanceof ym?{device_display_name_invalid:"Enter a human-readable device name instead of an internal identifier.",device_display_name_required:"Enter a device display name.",device_display_name_too_long:"Use a device display name with 120 characters or fewer.",invite_already_bound:"This invitation was accepted by another device. Ask the owner to create a new invitation.",invite_expired:"This invitation expired. Ask the owner to create a new invitation.",invite_identity_conflict:"This invitation does not match this Identity. Ask the owner to create a new invitation for this recipient.",invite_invalid:"This invitation is no longer valid. Ask the owner to create a new invitation.",inviter_identity_invalid:"The owner's device identity could not be verified. Ask the owner to review the share and create a new invitation.",project_invite_acceptance_failed:"The invitation could not be accepted safely. Retry once, then ask the owner to review the share.",project_invite_bootstrap_incomplete:"The owner's device is not ready to establish trust yet. Retry once, then ask the owner to review the share.",project_invite_self_acceptance_forbidden:"The owner cannot accept this recipient invitation on the owner's device.",project_invite_trust_state_invalid:"The owner's trust setup could not be verified. Ask the owner to review the share.",project_sync_enablement_failed:"The invitation was accepted, but Project setup could not be enabled because the codemem config is not writable. Make the config writable, then check Sync to finish setup.",recipient_display_name_invalid:"Enter a human-readable Identity name instead of an internal identifier.",recipient_display_name_required:"Enter an Identity display name.",recipient_display_name_too_long:"Use an Identity display name with 120 characters or fewer."}[e.errorCode]??t:e.message==="reviewed_onboarding_stale"?"Invitation details changed. Review them again before creating it.":e.message==="recipient_invite_review_unavailable"?"The invitation review is unavailable. Ask the owner to create a new invitation.":e.message==="recipient_invite_intent_mismatch"?"The invitation details do not match the reviewed access. Ask the owner to create a new invitation.":e.message==="invite_identity_conflict"?"This device already belongs to a different Identity. Use a fresh device or ask the owner for the correct invitation.":e.message==="recipient_display_name_invalid"?"Enter a human-readable Identity name instead of an internal identifier.":e.message==="recipient_display_name_required"?"Enter an Identity display name before accepting.":e.message==="recipient_display_name_too_long"?"Use an Identity display name with 120 characters or fewer.":t:t}function Lo(e){return`${e.toLocaleString()} existing ${e===1?"memory":"memories"}`}function yT({preview:e}){return e.projects.length===0?a("p",{className:"small",children:"No Projects are currently shared with this Team."}):a("ul",{children:e.projects.map(t=>a("li",{children:[a("strong",{children:t.displayName})," — ",Lo(t.existingMemoryCount)," and future activity"]},t.canonicalProjectIdentity))})}function bT({preview:e}){return a("div",{className:"sync-dialog-stack",children:[a("p",{children:a("strong",{children:["Current Projects for ",e.team?.displayName??"this Team"]})}),a(yT,{preview:e}),a("p",{children:"Future Projects shared with this Team will also be inherited by this member."}),a("p",{children:a("strong",{children:"No other Projects will be shared through this invitation."})})]})}function _T({preview:e}){const t=e.projects.filter(r=>r.sources.some(i=>i.kind==="direct")),n=e.projects.filter(r=>r.sources.some(i=>i.kind==="team"));return a("div",{className:"sync-dialog-stack",children:[a("section",{"aria-labelledby":"add-device-direct-projects",children:[a("h3",{id:"add-device-direct-projects",children:"Direct Projects"}),t.length?a("ul",{children:t.map(r=>a("li",{children:[r.displayName," — ",Lo(r.existingMemoryCount)," and future activity"]},r.canonicalProjectIdentity))}):a("p",{className:"small",children:"No Projects are shared directly."})]}),a("section",{"aria-labelledby":"add-device-team-projects",children:[a("h3",{id:"add-device-team-projects",children:"Projects through Teams"}),n.length?a("ul",{children:n.map(r=>{const i=r.sources.filter(o=>o.kind==="team").map(o=>o.displayName);return a("li",{children:[r.displayName," — ",Lo(r.existingMemoryCount)," and future activity",i.length?` through ${i.join(", ")}`:" through a Team"]},r.canonicalProjectIdentity)})}):a("p",{className:"small",children:"No Projects are inherited through Teams."})]}),a("section",{"aria-labelledby":"add-device-excluded-projects",children:[a("h3",{id:"add-device-excluded-projects",children:"Not included"}),e.excludedProjects.length?a("ul",{children:e.excludedProjects.map(r=>a("li",{children:[r.displayName," — ",Lo(r.existingMemoryCount)]},r.canonicalProjectIdentity))}):a("p",{className:"small",children:"No other Projects are excluded."}),a("p",{className:"small",children:"This device will not receive the Projects listed here."})]}),e.projects.length>0?a("p",{className:"small",role:"note",children:"The lists above describe access, not delivery: Project data does not sync to the invited device until the Project owner’s device completes access setup for it. Until then, shared memories remain on the Identity’s existing devices."}):null]})}function zg({preview:e}){return e.journey==="team"?a(bT,{preview:e}):a(_T,{preview:e})}function wT({error:e,name:t,onChange:n}){return a("section",{"aria-labelledby":"recipient-onboarding-name-title",children:[a("h3",{id:"recipient-onboarding-name-title",children:"Who will receive access"}),a("label",{className:"field",htmlFor:"recipient-onboarding-name",children:[a("span",{children:"Identity display name"}),a("input",{"aria-describedby":e?"recipient-onboarding-name-error":void 0,"aria-invalid":!!e,id:"recipient-onboarding-name",onInput:r=>n(r.currentTarget.value),placeholder:"Your name — e.g. Alex Rivera",value:t})]}),e?a("p",{className:"small",id:"recipient-onboarding-name-error",role:"alert",children:e}):null]})}function ST({deviceName:e,deviceNameError:t,invite:n,onDeviceNameChange:r,onRecipientNameChange:i,recipientName:o,recipientNameError:s}){const c=n.projects??[];return a("div",{className:"sync-dialog-stack",children:[a("section",{"aria-labelledby":"project-share-invitation-recipient",children:[a("h3",{id:"project-share-invitation-recipient",children:"Who will receive access"}),a("p",{children:"Review these display names before importing the invitation."}),a("label",{className:"field",htmlFor:"project-share-recipient-name",children:[a("span",{children:"Identity display name"}),a("input",{"aria-describedby":s?"project-share-recipient-name-error":void 0,"aria-invalid":!!s,id:"project-share-recipient-name",onInput:l=>i(l.currentTarget.value),placeholder:"Your name — e.g. Alex Rivera",value:o})]}),s?a("p",{className:"small",id:"project-share-recipient-name-error",role:"alert",children:s}):null,a("label",{className:"field",htmlFor:"project-share-device-name",children:[a("span",{children:"Device display name"}),a("input",{"aria-describedby":t?"project-share-device-name-error":void 0,"aria-invalid":!!t,id:"project-share-device-name",onInput:l=>r(l.currentTarget.value),placeholder:"This device — e.g. Work Laptop",value:e})]}),t?a("p",{className:"small",id:"project-share-device-name-error",role:"alert",children:t}):null]}),a("section",{"aria-labelledby":"project-share-invitation-projects",children:[a("h3",{id:"project-share-invitation-projects",tabIndex:-1,children:"Exact Projects shared directly"}),n.inviter_name?a("p",{children:["Invitation from ",n.inviter_name,"."]}):null,a("p",{children:["You will receive ",a("strong",{children:"direct access only"})," to the exact Projects listed below."]}),c.length?a("ul",{children:c.map((l,d)=>a("li",{children:[a("strong",{children:l.display_name})," —"," ",Lo(l.existing_memory_count)," and future activity"]},`${l.display_name}:${d}`))}):a("p",{role:"alert",children:"Project details are unavailable. Ask the owner to create a new invitation before accepting."})]}),a("p",{children:a("strong",{children:"Accepting this invitation does not join a Team."})}),a("p",{children:a("strong",{children:"No other Projects are included."})})]})}function CT({result:e}){const t=e.restart_required===!0||e.setup_state==="restart_required",n=e.type==="project_share"&&e.status==="pending_setup";return a("div",{className:"sync-dialog-stack",children:[a("h3",{id:"project-share-invitation-result",tabIndex:-1,children:"Project invitation accepted"}),t?a("p",{role:"status",children:[a("strong",{children:"Project setup is pending and codemem must be restarted."})," Restart codemem to start the sync service. Access remains pending until setup and the first sync finish."]}):n?a("p",{role:"status",children:[a("strong",{children:"Project setup is pending."})," The owner still needs to finish access setup, and the Projects will appear after the first sync completes."]}):a("p",{role:"status",children:"The invitation was accepted, but Project setup status could not be confirmed. Check Sync before expecting Project data."})]})}function RT({result:e}){const t=e.kind==="team_member"?"Team invitation accepted":"Device added",n=[e.restartRequired?"recipient-invitation-result-detail":null,e.deliveryPending?"recipient-invitation-result-delivery":null].filter(Boolean).join(" ")||void 0;return a("section",{"aria-describedby":n,"aria-labelledby":"recipient-invitation-result-title",className:"recipient-policy-invitation-result",id:"recipient-invitation-result",tabIndex:-1,children:[a("span",{"aria-hidden":"true",className:"recipient-policy-invitation-result-mark",children:"✓"}),a("div",{className:"recipient-policy-invitation-result-copy",children:[a("h3",{id:"recipient-invitation-result-title",children:t}),e.restartRequired?a("p",{id:"recipient-invitation-result-detail",children:e.detail}):null,e.deliveryPending?a("p",{className:"small",id:"recipient-invitation-result-delivery",children:"Existing shared Projects do not sync to this device until the Project owner’s device completes access setup for it."}):null]})]})}function Wg(e,t){return e==="team_member"?{kind:e,policy_team_id:t}:{kind:e,target_identity_id:t}}function IT({intent:e}){const t=e.teams.filter(W=>W.status==="active"),n=e.identities.filter(W=>W.status==="active"),[r,i]=x(null),[o,s]=x("team_member"),[c,l]=x(t[0]?.teamId??""),[d,u]=x(""),[p,f]=x(null),[m,v]=x(null),[g,h]=x(null),[b,w]=x(null),[_,R]=x(""),[I,T]=x(""),[A,O]=x(""),[F,N]=x(null),[L,D]=x(!1),[G,q]=x(""),[$,E]=x(""),S=B(null),M=B(0),H=B(""),U=B(!1);V(()=>{if(b){document.getElementById("recipient-invitation-result")?.focus();return}if(g){document.getElementById("project-share-invitation-result")?.focus();return}m?.kind==="project_share_invite"&&document.getElementById("project-share-invitation-projects")?.focus()},[m,g,b]);const re=()=>{M.current+=1,H.current="",U.current=!1,u(""),f(null),v(null),h(null),w(null),R(""),T(""),O(""),N(null),q(""),E("")},oe=(W,de)=>{re(),S.current=de,i(W)},ie=()=>{L||(i(null),re())},se=W=>{M.current+=1,H.current=W,u(W)},ue=W=>{s(W),l(W==="team_member"?t[0]?.teamId??"":n[0]?.identityId??""),re()},Pe=async()=>{if(c){D(!0),E(""),q("Reviewing invitation…");try{const W=await _R(Wg(o,c));f(W.preview),q("Review ready. Confirm the invitation details.")}catch(W){E(ws(W,"Unable to review this invitation.")),q("")}finally{D(!1)}}},Ie=async()=>{if(p){D(!0),E(""),q("Creating invitation…");try{const W=await wR({...Wg(o,c),reviewed_onboarding_digest:p.reviewedOnboardingDigest});N(W),q("Invitation created.")}catch(W){W instanceof Error&&W.message==="reviewed_onboarding_stale"&&f(null),E(ws(W,"Unable to create this invitation.")),q("")}finally{D(!1)}}},le=async()=>{const W=H.current.trim(),de=M.current;if(!W){E("Paste an invitation first.");return}const ne=()=>M.current===de&&H.current.trim()===W;D(!0),E(""),q("Reviewing invitation…");try{const xe=await bm(W);if(!ne())return;v(xe),xe.kind==="team_member"?R(kd(xe.recipient_name)):xe.kind==="project_share_invite"&&(T(kd(xe.recipient_name)),O(kd(xe.device_name))),q(xe.kind==="add_device"?(xe.onboarding?.projects?.length??0)>0?"Review ready. Existing shared Projects sync to the invited device only after the owner’s device completes access setup. Confirm before accepting.":"Review ready. Confirm before accepting.":xe.kind==="team_member"?"Review ready. Confirm before accepting.":xe.kind==="project_share_invite"?"Review ready. Confirm the exact Projects before accepting.":"Open Advanced, then Sync, to review and import this legacy invitation.")}catch(xe){if(!ne())return;E(ws(xe,"Unable to review this invitation.")),q("")}finally{D(!1)}},ve=async()=>{if(!(L||U.current||b)&&!(!m||m.kind==="legacy_team_invite")&&!(m.kind==="project_share_invite"&&!(m.projects?.length??0))&&!(m.kind==="project_share_invite"&&(Ei(I,"Identity display name")||Ei(A,"Device display name")))&&!(m.kind==="team_member"&&Ei(_,"Identity display name"))){U.current=!0,D(!0),E(""),q("Accepting invitation…");try{const W=m.kind==="project_share_invite"?await kl(d.trim(),{recipient_name:I.trim(),device_name:A.trim()},m.kind):await kl(d.trim(),{...m.kind==="team_member"?{recipient_name:_.trim()}:{},device_name:m.device_name,reviewed_onboarding_digest:m.onboarding.reviewedOnboardingDigest},m.kind);if(m.kind==="project_share_invite")h(vT(W)),q("");else{const de=m.kind,ne=W.restart_required===!0||W.setup_state==="restart_required";w({kind:de,restartRequired:ne,detail:de==="team_member"?"Restart codemem to finish joining this Team.":"Restart codemem to finish adding this device.",deliveryPending:de==="add_device"&&(m.onboarding?.projects?.length??0)>0}),q("")}}catch(W){U.current=!1;const de=m.kind==="project_share_invite"?"Unable to accept this Project invitation. Ask the owner to create a new invitation, then try again.":"Unable to accept this invitation.";E(ws(W,de)),q("")}finally{D(!1)}}},X=async()=>{const W=F?.invite.link||F?.invite.encoded||"";if(!W){E("The invitation text is unavailable.");return}try{await navigator.clipboard.writeText(W),q("Invitation copied.")}catch{E("Unable to copy the invitation.")}},ce=m?.kind==="team_member"||m?.kind==="add_device"?m.onboarding:null,be=m?.kind==="project_share_invite"?m:null,fe=m?.kind==="team_member"?Ei(_,"Identity display name"):"",We=be?Ei(I,"Identity display name"):"",he=be?Ei(A,"Device display name"):"";return a("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:[a("article",{className:"peer-card peer-card--padded recipient-policy-sharing-card",children:[a("h3",{children:"Create an invitation"}),a("p",{children:"Invite a Team member, add a device, or share an exact set of Projects."}),a("div",{className:"peer-actions recipient-policy-sharing-responsive-actions",children:[a("button",{className:"settings-button recipient-policy-sharing-target-24",disabled:t.length===0,onClick:W=>{ue("team_member"),oe("create",W.currentTarget)},type:"button",children:"Invite Team member"}),a("button",{className:"settings-button recipient-policy-sharing-target-24",disabled:n.length===0,onClick:W=>{ue("add_device"),oe("create",W.currentTarget)},type:"button",children:"Add a device"}),a("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>_s(),type:"button",children:"Share exact Projects"})]}),t.length===0&&n.length===0?a("p",{className:"small",role:"status",children:"No active Teams or Identities are available."}):null]}),a("article",{className:"peer-card peer-card--padded recipient-policy-sharing-card",children:[a("h3",{children:"Accept an invitation"}),a("p",{children:"Review Team membership, device access, or exact Project access before accepting."}),a("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:W=>oe("accept",W.currentTarget),type:"button",children:"Review invitation"}),a("p",{className:"small",children:"Legacy invitation import remains under Advanced, in Sync."})]}),r?a(Qn,{ariaDescribedby:"recipient-invitation-description",ariaLabelledby:"recipient-invitation-title",contentClassName:"modal recipient-policy-invitation-dialog",contentId:"recipientInvitationDialog",onCloseAutoFocus:W=>{W.preventDefault(),S.current?.focus(),S.current=null},onOpenAutoFocus:W=>{W.preventDefault(),document.getElementById("recipient-invitation-title")?.focus()},onOpenChange:W=>{W||ie()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientInvitationDialogBackdrop",children:a("div",{"aria-busy":L,className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:"recipient-invitation-title",tabIndex:-1,children:b?"Invitation accepted":r==="create"?"Create invitation":"Review invitation"}),a(kr,{ariaLabel:"Close invitation",className:"modal-close-button recipient-policy-sharing-target-24",disabled:L,onClick:ie})]}),a("div",{className:"modal-body",children:[a("p",{className:"small",id:"recipient-invitation-description",children:b?"The invitation has been accepted.":"Confirm exactly what this invitation includes before continuing."}),r==="create"&&!p&&!F?a("label",{className:"field",htmlFor:"recipient-invitation-target",children:[a("span",{children:o==="team_member"?"Team":"Identity"}),a("select",{id:"recipient-invitation-target",onChange:W=>l(W.currentTarget.value),value:c,children:(o==="team_member"?t:n).map(W=>a("option",{value:"teamId"in W?W.teamId:W.identityId,children:W.displayName},"teamId"in W?W.teamId:W.identityId))})]}):r==="accept"&&!m&&!b?a("label",{className:"field",htmlFor:"recipient-invitation-value",children:[a("span",{children:"Invitation"}),a("textarea",{id:"recipient-invitation-value",onInput:W=>{se(W.currentTarget.value),v(null),h(null),q(""),E("")},rows:5,value:d})]}):null,p?a(zg,{preview:p}):null,ce&&!b?a(zg,{preview:ce}):null,m?.kind==="team_member"&&!b?a(wT,{error:fe,name:_,onChange:W=>{R(W),E("")}}):null,be&&!g?a(ST,{deviceName:A,deviceNameError:he,invite:be,onDeviceNameChange:W=>{O(W),E("")},onRecipientNameChange:W=>{T(W),E("")},recipientName:I,recipientNameError:We}):null,g?a(CT,{result:g}):null,b?a(RT,{result:b}):null,F?a("div",{children:[a("p",{children:"Share the invitation with the recipient."}),a("button",{className:"settings-button",onClick:()=>{X()},type:"button",children:"Copy invitation"})]}):null,m?.kind==="legacy_team_invite"?a("p",{children:"Open Advanced, then Sync, to review and import this legacy invitation."}):null,a("p",{"aria-live":"polite",className:"small",role:"status",children:G}),$?a("p",{"aria-live":"assertive",role:"alert",children:$}):null]}),a("div",{className:"modal-footer recipient-policy-sharing-responsive-actions",children:[a("button",{className:"settings-button",disabled:L,onClick:ie,type:"button",children:F||g||b?"Done":"Cancel"}),r==="create"&&!F?a("button",{className:"settings-button sync-dialog-confirm",disabled:L||!c,onClick:()=>{p?Ie():Pe()},type:"button",children:L?"Working…":p?"Create invitation":"Review invitation"}):r==="accept"&&!m&&!b?a("button",{className:"settings-button sync-dialog-confirm",disabled:L,onClick:()=>{le()},type:"button",children:L?"Reviewing…":"Review invitation"}):ce&&!b||be&&!g?a("button",{className:"settings-button sync-dialog-confirm",disabled:L||!!(m?.kind==="team_member"&&fe)||!!(be&&(!be.projects?.length||We||he)),onClick:()=>{ve()},type:"button",children:L?"Accepting…":be?"Accept Project access":"Accept invitation"}):null]})]})}):null]})}function kT(e){const t=e.trim();return t?[...t].length>120?"Team name must use 120 characters or fewer.":[...t].some(n=>/[\p{Cc}\p{Cf}]/u.test(n))?"Team name cannot include control or format characters.":Id(t)?"Enter a human-readable Team name.":"":"Team name is required."}function TT(e){return e instanceof Ka?e.errorCode==="team_name_invalid"?"Enter a valid human-readable Team name.":e.errorCode==="team_not_found"?"This Team is no longer available. Refresh Sharing and try again.":e.errorCode==="team_rename_stale"?"This Team changed since you opened settings. Refresh Sharing and try again.":e.errorCode==="team_link_stale"?"This Team’s connected setup is no longer configured. Refresh Sharing before renaming it.":e.errorCode==="team_link_ambiguous"?"This Team has conflicting connected setup records. Nothing was changed. Review the Team setup before retrying.":e.errorCode==="team_coordinator_rename_failed"?"The connected Team service could not be updated. Nothing changed locally. Try again.":e.errorCode==="team_local_rename_pending"?"The connected Team service was updated, but Sharing could not save the name locally. Try again to finish.":"The Team could not be renamed safely. Try again.":"The Team could not be renamed. Try again."}function PT({descriptionId:e,disabled:t,displayName:n,onRenamed:r,renameTeam:i=zC,teamId:o}){const[s,c]=x(!1),[l,d]=x(n),[u,p]=x(!1),[f,m]=x(""),[v,g]=x(""),h=B(null),b=B(null),w=B(null);V(()=>{v&&!u&&w.current?.focus()},[u,v]);const _=()=>{u||(c(!1),m(""),g(""))},R=async()=>{const I=kT(l);if(I){m(I);return}if(!u){p(!0),m(""),g("");try{const T=await i({teamId:o,displayName:l,expectedDisplayName:n});d(T.displayName),g(`Team renamed to ${T.displayName}.`);try{await r?.()===!1&&g(`Team renamed to ${T.displayName}, but Sharing could not refresh.`)}catch{g(`Team renamed to ${T.displayName}, but Sharing could not refresh.`)}}catch(T){m(TT(T))}finally{p(!1)}}};return a(z,{children:[a("button",{"aria-describedby":e,"aria-disabled":t?"true":void 0,"aria-label":`Team settings for ${n}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",onClick:()=>{t||(d(n),m(""),g(""),c(!0))},ref:h,type:"button",children:"Team settings"}),a(Qn,{ariaDescribedby:"recipient-policy-team-settings-description",ariaLabelledby:"recipient-policy-team-settings-title",contentClassName:"modal recipient-policy-team-settings-dialog",contentId:"recipientPolicyTeamSettingsDialog",onCloseAutoFocus:I=>{I.preventDefault(),h.current?.focus()},onEscapeKeyDown:I=>{u&&I.preventDefault()},onInteractOutside:I=>{u&&I.preventDefault()},onOpenAutoFocus:I=>{I.preventDefault(),b.current?.focus(),b.current?.select()},onOpenChange:I=>{I||_()},open:s,overlayClassName:"modal-backdrop",overlayId:"recipientPolicyTeamSettingsDialogBackdrop",children:a("div",{"aria-busy":u?"true":"false",className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:"recipient-policy-team-settings-title",children:"Team settings"}),a(kr,{ariaLabel:"Close Team settings",disabled:u,onClick:_})]}),a("div",{className:"modal-body",children:[a("p",{className:"small",id:"recipient-policy-team-settings-description",children:"Change the name shown for this Team in Sharing."}),a("label",{className:"form-field",htmlFor:"recipient-policy-team-settings-name",children:[a("span",{children:"Team name"}),a("input",{disabled:u||!!v,id:"recipient-policy-team-settings-name",maxLength:120,onInput:I=>{d(I.currentTarget.value),m("")},ref:b,value:l})]}),u?a("p",{"aria-live":"polite",role:"status",children:"Saving Team name…"}):null,f?a("p",{"aria-live":"assertive",role:"alert",children:f}):null,v?a("p",{"aria-live":"polite",role:"status",children:v}):null]}),a("div",{className:"modal-footer recipient-policy-team-settings-actions",children:[a("button",{className:"settings-button",disabled:u,onClick:_,ref:w,type:"button",children:v?"Done":"Cancel"}),v?null:a("button",{className:"settings-button sync-dialog-confirm",disabled:u||!l.trim()||l.trim()===n,onClick:()=>{R()},type:"button",children:u?"Saving…":f?"Try again":"Save"})]})]})})]})}var Jg={needs_setup:"Ready to review",in_progress:"Migration in progress",stale:"Migration review needs update"},Yg={needs_setup:"needs_attention",in_progress:"suggested",stale:"needs_attention"},Td={role:"list"},Pd={role:"listitem"};function NT(e){return typeof e=="string"&&Object.hasOwn(Jg,e)?Jg[e]:"Ready to review"}function ET(e){return typeof e=="string"&&Object.hasOwn(Yg,e)?Yg[e]:"needs_attention"}function AT(e){const t=new Map;for(const n of e){const r=n.displayName.trim().toLowerCase(),i=t.get(r);i?t.set(r,{...i,candidates:[...i.candidates,n]}):t.set(r,{displayName:n.displayName,candidates:[n]})}return[...t.values()].map(n=>({...n,candidates:[...n.candidates].sort((r,i)=>r.candidateRef<i.candidateRef?-1:r.candidateRef>i.candidateRef?1:0)}))}function xT({candidates:e,onOpenTeamSetup:t}){if(e.length===0)return null;const n=AT(e);return a("aside",{"aria-labelledby":"sharing-team-setup-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[a("h3",{id:"sharing-team-setup-heading",children:"Legacy groups to migrate"}),a("p",{children:"Current devices are proposed for review. No Team membership or Project access changes happen until you finish the migration."}),a("ul",{...Td,className:"recipient-policy-sharing-team-setup-list","aria-label":"Team setup status",children:n.map(r=>y("li",{...Pd,className:"recipient-policy-sharing-team-setup-group",key:r.displayName},r.candidates.length>1?a("div",{className:"recipient-policy-sharing-team-setup-group-title",children:[a("strong",{children:r.displayName}),a("span",{className:"small",children:[r.candidates.length," Teams"]})]}):null,a("div",{className:"recipient-policy-sharing-team-setup-rows",children:r.candidates.map((i,o)=>{const s=`${o+1} of ${r.candidates.length}`,c=`${Jt(i.deviceCount,"device")}, ${Jt(i.projectCount,"Project")}`,l=r.candidates.length>1?`Review and migrate ${r.displayName} ${s}: ${c}`:`Review and migrate ${i.displayName}: ${c}`;return a("div",{className:"recipient-policy-sharing-team-setup-row",children:[a("span",{className:"recipient-policy-sharing-team-setup-label",children:[r.candidates.length>1?a("span",{className:"small",children:["Team ",s," · ",c]}):a(z,{children:[a("strong",{children:i.displayName}),a("span",{className:"small",children:[" · ",c]})]}),a("span",{"aria-hidden":"true",className:"recipient-policy-sharing-team-setup-separator",children:[" ","—"," "]})]}),a("span",{className:"recipient-policy-sharing-team-setup-status",children:a("span",{className:`project-status-badge ${ET(i.status)}`.trim(),children:NT(i.status)})}),a("span",{className:"recipient-policy-sharing-team-setup-action",children:t?a("button",{"aria-label":l,className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t(i.candidateRef),type:"button",children:"Review and migrate"}):null})]},i.candidateRef)})})))})]})}var Er=[{id:"teams",label:"Teams"},{id:"identities",label:"Identities"},{id:"received",label:"Received"},{id:"invitations",label:"Invitations"}];function Jt(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function DT(e,t){return e.length?e.join(", "):t}var Xg=3;function Nd({empty:e,label:t,names:n}){return n.length===0?a(z,{children:e}):n.length<=Xg?a(z,{children:DT(n,e)}):a(z,{children:[n.slice(0,Xg).join(", "),a("span",{"aria-hidden":"true",children:", …"}),a("details",{className:"recipient-policy-sharing-name-details",children:[a("summary",{children:["View all ",Jt(n.length,t)]}),a("ul",{...Td,"aria-label":`All ${t}s`,children:n.map((r,i)=>y("li",{...Pd,key:`${i}-${r}`},r))})]})]})}function Qg(e,t){return[...new Set(e)].map(n=>({canonicalId:n,displayName:t.get(n)?.displayName??"Unavailable Project"}))}var Zg=3;function ev({empty:e,identities:t,qualifier:n}){if(t.length===0)return a(z,{children:e});const r=Kk(t),i=s=>s.identityCount>1?`${s.displayName} (${Jt(s.identityCount,"identity","identities")})`:s.displayName,o=r.slice(0,Zg);return a(z,{children:[Jt(t.length,`${n} Project identity`,`${n} Project identities`)," ","— ",o.map(i).join(", "),r.length>Zg?a(z,{children:[a("span",{"aria-hidden":"true",children:", …"}),a("details",{className:"recipient-policy-sharing-project-details",children:[a("summary",{children:["View all ",Jt(r.length,"Project name group")]}),a("ul",{...Td,"aria-label":`All ${n} Project identity groups`,children:r.map(s=>y("li",{...Pd,key:s.displayName},i(s)))})]})]}):null]})}function tv({descriptionId:e,disabled:t,displayName:n,recipient:r}){const i=()=>{xo({mode:"recipient-manage",recipient:r})},o=()=>{xo({mode:"recipient-add",recipient:r})};return a(z,{children:[a("div",{className:"peer-actions recipient-policy-sharing-actions recipient-policy-sharing-responsive-actions",children:[a("button",{"aria-describedby":e,"aria-disabled":t?"true":void 0,"aria-label":`Add projects for ${n}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",onClick:()=>{t||o()},type:"button",children:"Add projects"}),a("button",{"aria-describedby":e,"aria-disabled":t?"true":void 0,"aria-label":`Manage projects for ${n}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",onClick:()=>{t||i()},type:"button",children:"Manage projects"})]}),a("p",{className:"small",id:e,children:t?"Team and Identity Project changes are disabled until a refresh succeeds.":"Add projects only adds the selected Projects after you preview the exact changes."})]})}function LT({disableMutations:e,intent:t,onTeamRenamed:n,projects:r,renameTeam:i}){const o=t.teams.filter(l=>l.status==="active"),s=new Map(t.identities.filter(l=>l.status==="active").map(l=>[l.identityId,l])),c=new Map(r.map(l=>[l.canonicalProjectIdentity,l]));return o.length===0?a("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No active Teams are available for Project sharing."}):a("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:o.map((l,d)=>{const u=[...new Set(t.teamMemberships.filter(h=>h.status==="active"&&h.teamId===l.teamId&&s.has(h.identityId)).map(h=>h.identityId))],p=u.map(h=>s.get(h)?.displayName??""),f=new Set(t.identityDevices.filter(h=>h.status==="active"&&u.includes(h.identityId)).map(h=>h.deviceId)).size,m=Qg(t.projectRecipients.filter(h=>h.status==="active"&&h.recipientKind==="team"&&h.teamId===l.teamId).map(h=>h.canonicalProjectIdentity),c),v=`recipient-policy-sharing-team-title-${d}`,g=`recipient-policy-sharing-team-add-description-${d}`;return a("article",{"aria-labelledby":v,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-team-card",children:[a("div",{className:"peer-title recipient-policy-sharing-card-title",children:[a("h3",{id:v,children:l.displayName}),a("span",{className:"badge actor-badge",children:"Team"})]}),a("dl",{className:"recipient-policy-sharing-details",children:[a("div",{children:[a("dt",{children:"Current members"}),a("dd",{children:[Jt(p.length,"active member")," —"," ",a(Nd,{empty:"No active members",label:"member",names:p})]})]}),a("div",{children:[a("dt",{children:"Registered devices"}),a("dd",{children:Jt(f,"active registered device")})]}),a("div",{children:[a("dt",{children:"Shared projects"}),a("dd",{children:a(ev,{empty:"No Projects shared",identities:m,qualifier:"active shared"})})]}),a("div",{children:[a("dt",{children:"Future Team members"}),a("dd",{children:"Yes — future Team members inherit the Team’s shared Projects."})]})]}),a(tv,{descriptionId:g,disabled:e,displayName:l.displayName,recipient:{recipientKind:"team",teamId:l.teamId}}),a("div",{className:"peer-actions recipient-policy-sharing-actions recipient-policy-sharing-responsive-actions",children:a(PT,{descriptionId:g,disabled:e,displayName:l.displayName,onRenamed:n,renameTeam:i,teamId:l.teamId})})]},l.teamId)})})}function $T({disableMutations:e,intent:t,projects:n}){const r=t.identities.filter(s=>s.status==="active"),i=new Map(t.teams.filter(s=>s.status==="active").map(s=>[s.teamId,s])),o=new Map(n.map(s=>[s.canonicalProjectIdentity,s]));return r.length===0?a("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No active Identities are available for Project sharing."}):a("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:r.map((s,c)=>{const l=t.identityDevices.filter(m=>m.status==="active"&&m.identityId===s.identityId),d=[...new Set(t.teamMemberships.filter(m=>m.status==="active"&&m.identityId===s.identityId&&i.has(m.teamId)).map(m=>m.teamId))].map(m=>i.get(m)?.displayName??""),u=Qg(t.projectRecipients.filter(m=>m.status==="active"&&m.recipientKind==="identity"&&m.identityId===s.identityId).map(m=>m.canonicalProjectIdentity),o),p=`recipient-policy-sharing-identity-title-${c}`,f=`recipient-policy-sharing-identity-add-description-${c}`;return a("article",{"aria-labelledby":p,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-identity-card",children:[a("div",{className:"peer-title recipient-policy-sharing-card-title",children:[a("h3",{id:p,children:s.displayName}),a("span",{className:"badge actor-badge local",children:"Local identity"})]}),a("dl",{className:"recipient-policy-sharing-details",children:[a("div",{children:[a("dt",{children:"Verification"}),a("dd",{children:"Local identity"})]}),a("div",{children:[a("dt",{children:"Registered devices"}),a("dd",{children:[Jt(l.length,"active registered device")," —"," ",a(Nd,{empty:"No active devices",label:"device",names:l.map(m=>m.displayName)})]})]}),a("div",{children:[a("dt",{children:"Team memberships"}),a("dd",{children:[Jt(d.length,"active Team membership")," —"," ",a(Nd,{empty:"No active Team memberships",label:"Team membership",names:d})]})]}),a("div",{children:[a("dt",{children:"Directly shared projects"}),a("dd",{children:a(ev,{empty:"No Projects shared directly",identities:u,qualifier:"directly shared active"})})]})]}),a("p",{className:"small",children:"Team Projects are shown on Team cards because per-device eligibility cannot be inferred from Identity membership alone."}),a(tv,{descriptionId:f,disabled:e,displayName:s.displayName,recipient:{recipientKind:"identity",identityId:s.identityId}})]},s.identityId)})})}function OT({received:e}){return e.length===0?a("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No received Projects on this device. Accepted invitations appear here once their first sync completes."}):a("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:e.map((t,n)=>{const r=`recipient-policy-sharing-received-title-${n}`;return a("article",{"aria-labelledby":r,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-received-card",children:[a("div",{className:"peer-title recipient-policy-sharing-card-title",children:[a("h3",{id:r,children:t.displayName}),a("span",{className:"badge actor-badge",children:"Received"})]}),a("dl",{className:"recipient-policy-sharing-details",children:[a("div",{children:[a("dt",{children:"Memories on this device"}),a("dd",{children:Jt(t.existingMemoryCount,"memory","memories")})]}),a("div",{children:[a("dt",{children:"Latest activity"}),a("dd",{children:t.latestSessionAt?new Date(t.latestSessionAt).toLocaleString():"No recent sessions"})]})]}),a("p",{className:"small",children:"This Project is received from another device. Access is managed where the Project is shared from; this device keeps it read-only."})]},t.canonicalProjectIdentity)})})}function jT({intent:e,options:t,projects:n}){const[r,i]=x(()=>e.teams.some(m=>m.status==="active")?"teams":"identities"),o=B(t.loading===!0||t.loadError===!0),s=B([]),c=Gg(t.deviceInventory),l=c.length,d=t.coordinatorEnrollmentIssueCount??0,u=e.teams.some(m=>m.status==="active");V(()=>{if(o.current&&!t.loading&&!t.loadError){o.current=!1,i(u?"teams":"identities");return}u||i(m=>m==="teams"?"identities":m)},[u,t.loadError,t.loading]);const p=m=>{const v=Er[m];v&&(i(v.id),s.current[m]?.focus())},f=(m,v)=>{let g=null;m.key==="ArrowRight"?g=(v+1)%Er.length:m.key==="ArrowLeft"?g=(v-1+Er.length)%Er.length:m.key==="Home"?g=0:m.key==="End"&&(g=Er.length-1),g!==null&&(m.preventDefault(),p(g))};return a("section",{className:"recipient-policy-sharing recipient-policy-sharing-responsive-surface",children:[a("header",{className:"recipient-policy-sharing-header",children:[a("h2",{children:"Sharing"}),a("p",{className:"small",children:"See who receives Projects, how Team membership carries Project access, and where to make changes."})]}),a(xT,{candidates:t.teamSetupSummary?.candidates??[],onOpenTeamSetup:t.onOpenTeamSetup}),t.teamSetupLoading&&!t.teamSetupSummary?a("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:"Team setup status is loading."}):null,t.teamSetupUnavailable?a("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:t.teamSetupSummary?"Team setup status is temporarily unavailable. The previous Team setup status is being shown.":"Team setup status is temporarily unavailable."}):null,t.deviceInventoryUnavailable?a("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:"Device Identity information is unavailable. Devices needing setup or review cannot be shown until a refresh succeeds."}):null,l>0&&!t.deviceInventoryUnavailable?a("aside",{"aria-labelledby":"sharing-device-setup-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[a("h3",{id:"sharing-device-setup-heading",children:"Identity setup needed"}),a("p",{children:[l.toLocaleString()," ",l===1?"device needs":"devices need"," setup, pairing, or review before ownership can be shown accurately."]}),a("p",{className:"small",children:"Identity setup records device ownership only. It does not grant Projects, Team membership, or sync access."}),t.onReviewDevices?a("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onReviewDevices?.(c[0]?.deviceId),type:"button",children:"Review devices"}):null]}):null,d>0?a("aside",{"aria-labelledby":"sharing-coordinator-reconciliation-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[a("h3",{id:"sharing-coordinator-reconciliation-heading",children:"Device setup reconciliation needs attention"}),a("p",{children:[d.toLocaleString()," coordinator enrollment",d===1?" could":"s could"," not be safely reconciled. Sharing remains unchanged until the device evidence is valid."]}),a("p",{className:"small",children:"Coordinator groups are discovery boundaries, not policy Teams, and do not prove device ownership."}),t.onReviewDevices?a("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onReviewDevices?.(),type:"button",children:"Review devices"}):null]}):null,t.refreshError?a("p",{"aria-live":"assertive",className:"recipient-policy-sharing-state recipient-policy-sharing-error",role:"alert",children:"Refresh failed; showing previous Sharing details. Team and Identity Project changes are disabled until a refresh succeeds."}):null,a("div",{"aria-label":"Sharing views",className:"recipient-policy-sharing-tabs recipient-policy-sharing-responsive-tabs",role:"tablist",children:Er.map((m,v)=>a("button",{"aria-controls":`recipient-policy-sharing-panel-${m.id}`,"aria-selected":r===m.id,className:`tab-btn recipient-policy-sharing-tab recipient-policy-sharing-target recipient-policy-sharing-target-24${r===m.id?" active":""}`,id:`recipient-policy-sharing-tab-${m.id}`,onClick:()=>i(m.id),onKeyDown:g=>f(g,v),ref:g=>{s.current[v]=g},role:"tab",tabIndex:r===m.id?0:-1,type:"button",children:m.label},m.id))}),Er.map(m=>a(z,{children:a("div",{"aria-labelledby":`recipient-policy-sharing-tab-${m.id}`,className:"recipient-policy-sharing-panel",hidden:r!==m.id,id:`recipient-policy-sharing-panel-${m.id}`,role:"tabpanel",tabIndex:0,children:t.loading?r===m.id?a(Ug,{detailRowCount:4,label:"Loading Sharing details"}):null:t.loadError?r===m.id?a("p",{"aria-live":"assertive",className:"recipient-policy-sharing-state recipient-policy-sharing-error",role:"alert",children:"Sharing details are unavailable. Refresh and try again."}):null:m.id==="teams"?a(LT,{disableMutations:t.refreshError===!0,intent:e,onTeamRenamed:t.onTeamRenamed,projects:n,renameTeam:t.renameTeam}):m.id==="identities"?a($T,{disableMutations:t.refreshError===!0,intent:e,projects:n}):m.id==="received"?a(OT,{received:t.received??[]}):a(IT,{intent:e})})},m.id))]})}function MT(e,t,n,r={}){Ue(a(jT,{intent:n,options:r,projects:t}),e)}var Ed={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]};async function FT(){const e=[];let t=0;for(;;){const n=await bo({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return{manageable:ys(e),received:aT(e)}}var BT={loadDeviceInventory:Al,loadIntent:El,loadProjects:FT,loadSyncStatus:Il,loadTeamSetupSummary:Tm,mountManagement:qg,mountSharing:MT};function qT(e={},t={}){const n={...BT,...e};let r=0,i=null,o=0,s,c,l=!1,d=!1,u=!1,p=!1,f=null;const m=(g={})=>{const h=v(++r,g);return i=h,h};async function v(g,h){const b=document.getElementById("recipientPolicySharingMount");if(!b){if(!h.requireTeamSetupSummary)return!0;try{return await n.loadTeamSetupSummary(),!0}catch{return!1}}const w=document.getElementById("recipientPolicyManagementMount");l=!0,d=!1;let _=()=>{const E=f;n.mountSharing(b,E?.inventory.manageable??[],E?.intent??Ed,E?{coordinatorEnrollmentIssueCount:o,deviceInventory:s,deviceInventoryUnavailable:p,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,onTeamRenamed:()=>m({requireTeamSetupSummary:!0}),received:E.inventory.received,...u?{refreshError:!0}:{},teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d}:{loading:!0,teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d})};_();const R=Promise.resolve().then(()=>n.loadTeamSetupSummary()).then(E=>(g!==r||(c=E,l=!1,d=!1,_()),!0),()=>(g!==r||(l=!1,d=!0,_()),!1)),[I,T,A,O]=await Promise.allSettled([n.loadProjects(),n.loadIntent(),n.loadDeviceInventory(),n.loadSyncStatus(!1,"",{includeJoinRequests:!1})]);if(g!==r)return h.requireTeamSetupSummary?(await R,!1):i??!1;const F=A.status==="rejected";A.status==="fulfilled"&&(s=A.value),O.status==="fulfilled"&&(o=Om(O.value));let N,L,D;const G=I.status==="fulfilled"&&T.status==="fulfilled";if(u=!G,p=F,G){const E=I.value,S=T.value;f={intent:S,inventory:E},N=E.manageable,L=S,D={coordinatorEnrollmentIssueCount:o,deviceInventory:s,deviceInventoryUnavailable:F,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,onTeamRenamed:()=>m({requireTeamSetupSummary:!0}),received:E.received},w&&n.mountManagement(w,E.manageable,S,{onCommitted:async()=>{await m()}})}else if(f){const E=f;N=E.inventory.manageable,L=E.intent,D={coordinatorEnrollmentIssueCount:o,deviceInventory:s,deviceInventoryUnavailable:F,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,onTeamRenamed:()=>m({requireTeamSetupSummary:!0}),received:E.inventory.received,refreshError:!0}}else N=[],L=Ed,D={deviceInventoryUnavailable:F,loadError:!0};const q=()=>{n.mountSharing(b,N,L,{...D,teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d})};if(q(),_=q,!G&&w&&n.mountManagement(w,[],Ed,{loadError:!0}),!h.requireTeamSetupSummary)return G;const $=await R;return g!==r?!1:G&&$}return m}var nv=["info","warning","error"],rv=["viewer","observer","capture","sync","storage","maintenance"],UT=["#health","#advanced/sync/diagnostics"],GT=100,HT=128,VT=64,KT=128,zT=2e3,iv=256,WT=2e3,JT=2e3,YT=2048,ov=class extends Error{status;constructor(e,t){super(`Diagnostics request failed: ${e} ${t}`),this.status=e,this.name="DiagnosticEventsRequestError"}};function XT(e){const t=new URLSearchParams;return typeof e.limit=="number"&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor),e.severity?.length&&t.set("severity",e.severity.join(",")),e.subsystem?.length&&t.set("subsystem",e.subsystem.join(",")),t.set("includeTechnical",e.includeTechnical?"1":"0"),t.toString()}function $o(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ss(e,t){return Object.keys(e).every(n=>t.includes(n))}function En(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t}function av(e){return En(e,VT)&&Number.isFinite(Date.parse(e))}function Ad(e){return typeof e=="string"&&UT.includes(e)}function QT(e){return!$o(e)||!Ss(e,["label","href","command"])||!En(e.label,iv)||e.href!==void 0&&!Ad(e.href)?!1:e.command===void 0||En(e.command,WT)}function ZT(e){return!$o(e)||!Ss(e,["kind","label"])||!En(e.label,iv)?!1:e.kind==="session"||e.kind==="device"||e.kind==="operation"}function eP(e){return!$o(e)||!Ss(e,["available","text"])||typeof e.available!="boolean"?!1:e.text===void 0?!0:e.available&&En(e.text,JT)}function tP(e){return!$o(e)||!Ss(e,["id","occurred_at","severity","subsystem","code","message","recovery","correlation","technical_detail"])||!En(e.id,HT)||!av(e.occurred_at)||!nv.includes(e.severity)||!rv.includes(e.subsystem)||!En(e.code,KT)||!En(e.message,zT)||e.recovery!==void 0&&!QT(e.recovery)||e.correlation!==void 0&&!ZT(e.correlation)?!1:e.technical_detail===void 0||eP(e.technical_detail)}function nP(e){if(!$o(e)||e.contract_version!==1||!Array.isArray(e.items)||e.items.length>GT)return null;let t=null;if(e.next_cursor!==null){if(!En(e.next_cursor,YT))return null;t=e.next_cursor}return e.redacted!==!0||!av(e.generated_at)?null:{contract_version:1,items:e.items.filter(tP),next_cursor:t,redacted:e.redacted,generated_at:e.generated_at}}async function rP(e={}){const t=XT(e),n=await fetch(`/api/diagnostics/events?${t}`,{cache:"no-store",method:"GET",signal:e.signal});if(!n.ok)throw new ov(n.status,n.statusText);const r=nP(await n.json());if(!r)throw new Error("Unsupported diagnostics response");return r}var B2=20,sv={connection_lost:{code:"viewer_connection_lost",message:"The viewer connection was interrupted. Automatic recovery started.",severity:"warning",subsystem:"viewer"},reconnect_requested:{code:"viewer_reconnect_requested",message:"A viewer reconnection check was requested.",severity:"info",subsystem:"viewer"},connection_restored:{code:"viewer_connection_restored",message:"The viewer connection and page data were restored.",severity:"info",subsystem:"viewer"}},Cs=!1,iP=0,Rs=[],xd=new Set;function Dd(){return[...Rs]}function Ld(e){if(!Object.hasOwn(sv,e))return;const t=sv[e];if(e==="connection_lost"&&Cs||e==="reconnect_requested"&&Rs[0]?.code===t.code||e==="connection_restored"&&!Cs)return;const n=new Date().toISOString(),r={id:`viewer-session-${Date.now()}-${++iP}`,occurred_at:n,...t};Rs=[r,...Rs].slice(0,20),e==="connection_lost"&&(Cs=!0),e==="connection_restored"&&(Cs=!1);for(const i of xd)i(r)}function oP(e){return xd.add(e),()=>xd.delete(e)}var q2=200;function $d(){return{open:!1,severity:"",subsystem:"",includeTechnical:!1,paused:!1,rows:[],sessionRows:[],queuedSessionRows:[],queuedRows:[],queuedNextCursor:void 0,nextCursor:null,generatedAt:null,loading:!1,error:!1,announcement:"",copyStatus:"",hiddenSessionIds:[],queryRevision:0,pollRevision:0}}function Od(e){return xt([...e.sessionRows,...e.rows].filter(t=>cv(e,t)).sort((t,n)=>Date.parse(n.occurred_at)-Date.parse(t.occurred_at)))}function cv(e,t){return e.severity&&t.severity!==e.severity?!1:!e.subsystem||t.subsystem===e.subsystem}function aP(e){const t=e.queuedSessionRows.filter(n=>cv(e,n));return e.queuedRows.length+t.length}function xt(e,t=200){const n=new Set;return e.filter(r=>n.has(r.id)||n.size>=t?!1:(n.add(r.id),!0))}function sP(e,t,n){const r=t==="older"&&n;return{...e,includeTechnical:t==="technical"?!1:e.includeTechnical,nextCursor:r?null:e.nextCursor,loading:!1,error:!0,announcement:"",queryRevision:r?e.queryRevision+1:e.queryRevision}}function jd(e,t){return{...e,...t,rows:[],queuedRows:[],queuedNextCursor:void 0,nextCursor:null,generatedAt:null,loading:!1,error:!1,announcement:"",copyStatus:"",queryRevision:e.queryRevision+1}}function Md(e,t,n){return t?n?{...t,occurred_at:e.occurred_at}:t:e}function cP(e,t,n){const r=new Map(t.items.map(p=>[p.id,p])),i=new Map(e.rows.map(p=>[p.id,p])),o=t.items.filter(p=>!i.has(p.id));if(!e.rows.length)return{...e,rows:t.items.slice(0,200),queuedNextCursor:void 0,nextCursor:t.next_cursor};if(!n){const p=xt([...t.items,...e.rows]);return{...e,rows:p,queuedRows:[],queuedNextCursor:void 0,nextCursor:t.next_cursor}}const s=t.items.filter(p=>{const f=i.get(p.id);return f!==void 0&&f.occurred_at!==p.occurred_at}),c=xt([...o,...s]),l=new Set(c.map(p=>p.id)),d=e.rows.map(p=>Md(p,r.get(p.id),l.has(p.id))),u=xt([...c,...e.queuedRows]);return{...e,rows:d,queuedRows:u,queuedNextCursor:t.next_cursor,announcement:u.length>0?`${u.length} new diagnostic events are waiting.`:""}}function lP(e,t){const n={...e,generatedAt:t.response.generated_at,loading:!1,error:!1,announcement:""};if(t.mode==="replace")return{...n,rows:t.response.items.slice(0,200),queuedRows:[],queuedNextCursor:void 0,nextCursor:t.response.next_cursor};if(t.mode==="older")return{...n,rows:xt([...e.rows,...t.response.items]),queuedNextCursor:e.queuedRows.length?e.queuedNextCursor:void 0,nextCursor:t.response.next_cursor};if(t.mode==="technical"){const r=new Map(t.response.items.map(i=>[i.id,i]));return{...n,rows:e.rows.map(i=>Md(i,r.get(i.id),!0)),queuedRows:e.queuedRows.map(i=>Md(i,r.get(i.id),!0)),nextCursor:e.nextCursor}}return cP(n,t.response,t.readingOlder)}function dP(e,t){return t.type==="open"?{...$d(),open:!0,severity:t.severity,subsystem:t.subsystem,sessionRows:t.sessionRows,queryRevision:e.queryRevision+1}:t.type==="close"?$d():t.type==="set_severity"?jd(e,{severity:t.severity}):t.type==="set_subsystem"?jd(e,{subsystem:t.subsystem}):t.type==="reset_filters"?jd(e,{severity:"",subsystem:""}):t.type==="set_paused"?{...e,loading:t.paused?!1:e.loading,paused:t.paused,pollRevision:t.paused?e.pollRevision:e.pollRevision+1}:t.type==="reveal_technical"?{...e,includeTechnical:!0}:null}function uP(e,t){return t.type==="request_started"?{...e,loading:t.mode!=="poll"}:t.type==="request_succeeded"?lP(e,t):t.type==="request_failed"?sP(e,t.mode,t.restartQuery):null}function lv(e,t,n=!1){if(e.paused||!e.open)return e;const r=t.filter(s=>!e.hiddenSessionIds.includes(s.id));if(!n)return{...e,sessionRows:xt([...r,...e.queuedSessionRows,...e.sessionRows],20),queuedSessionRows:[]};const i=new Set(e.sessionRows.map(s=>s.id)),o=xt([...r.filter(s=>!i.has(s.id)),...e.queuedSessionRows],20);return{...e,queuedSessionRows:o}}function pP(e,t){if(t.type==="session_event_recorded")return lv(e,[t.event],t.readingOlder);if(t.type==="refresh_session_rows")return lv(e,t.events,t.readingOlder);if(t.type==="clear_view"){const n=[...new Set([...t.sessionEvents.map(r=>r.id),...e.queuedSessionRows.map(r=>r.id),...e.sessionRows.map(r=>r.id),...e.hiddenSessionIds])].slice(0,20);return{...e,rows:[],sessionRows:[],queuedSessionRows:[],queuedRows:[],queuedNextCursor:void 0,nextCursor:null,generatedAt:null,loading:!1,error:!1,announcement:"Diagnostics view cleared.",copyStatus:"",hiddenSessionIds:n}}return t.type==="set_copy_status"?{...e,copyStatus:t.status}:t.type!=="show_queued"?null:fP(e)}function fP(e){const t=xt([...e.queuedRows,...e.rows],201),n=t.length>200&&e.queuedNextCursor!==void 0;return{...e,rows:t.slice(0,200),sessionRows:xt([...e.queuedSessionRows,...e.sessionRows],20),queuedSessionRows:[],queuedRows:[],queuedNextCursor:void 0,nextCursor:n?e.queuedNextCursor:e.nextCursor,announcement:""}}function mP(e,t){const n=dP(e,t);if(n)return n;const r=uP(e,t);return r||(pP(e,t)??e)}var hP=Math.ceil(200/50);async function gP(e){const t=new Map(e.existingRows.map(o=>[o.id,o.occurred_at]));let n=e.request,r=null,i=0;for(;;){const o=await e.loadEvents(n);i+=1;const s=xt([...r?.items??[],...o.items]);r={...o,items:s};const c=o.items.some(l=>t.get(l.id)===l.occurred_at);if(t.size===0||c){const l=xt([...s,...e.existingRows],201),d=c&&l.length<=200;return{...r,next_cursor:d?e.existingNextCursor:o.next_cursor}}if(!o.next_cursor||s.length>=200||i>=hP)return r;n={...e.request,cursor:o.next_cursor,limit:Math.min(50,200-s.length)}}}async function vP(e){const t=new Set(e.existingRows.map(o=>o.id));let n=e.request,r=null,i=0;for(;;){const o=await e.loadEvents(n);i+=1;const s=xt([...r?.items??[],...o.items]);r={...o,items:s};const c=new Set(s.map(l=>l.id));if([...t].every(l=>c.has(l)))return r;if(!o.next_cursor||s.length>=200||i*50>=200)throw new Error("Technical diagnostic history could not be refreshed completely.");n={...e.request,cursor:o.next_cursor,limit:Math.min(50,200-s.length)}}}function yP(e,t,n){const r=200-Od(t).length;return{limit:e==="older"?Math.max(1,Math.min(50,r)):50,cursor:e==="older"?t.nextCursor??void 0:void 0,severity:t.severity?[t.severity]:void 0,subsystem:t.subsystem?[t.subsystem]:void 0,includeTechnical:t.includeTechnical,signal:n}}function bP(e,t,n,r){const i=yP(t,n,r);return t==="technical"?vP({loadEvents:e,request:i,existingRows:xt([...n.queuedRows,...n.rows],n.queuedRows.length+n.rows.length)}):t!=="poll"?e(i):gP({loadEvents:e,request:i,existingRows:n.rows,existingNextCursor:n.nextCursor})}function _P(e,t){return e==="older"&&t instanceof ov&&t.status===400}function Fd(e){return e.current!==null&&e.current.scrollTop>24}function wP(e){return e instanceof DOMException&&e.name==="AbortError"}var SP=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function dv(e){if(!e?.isConnected||!e.matches(SP)||e.matches(':disabled, [aria-disabled="true"]'))return!1;let t=e;for(;t;){if(t.hidden||t.inert||t.hasAttribute("inert")||t.getAttribute("aria-hidden")==="true")return!1;const n=getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden"||n.visibility==="collapse"||n.opacity==="0")return!1;t=t.parentElement}return!0}function CP(){const e=document.querySelector('.tab-btn[aria-current="page"]');return dv(e)?e:null}function RP(e){const t=e==="#health"?"health":"advanced";return document.getElementById(`tabBtn-${t}`)}function IP(e,t,n){if(e.preventDefault(),n.current){n.current=!1,t.current=null;return}const r=t.current;dv(r)?r.focus():CP()?.focus(),t.current=null}function kP(e){const{dispatch:t,abortRequest:n,openerRef:r,recoveryNavigationRef:i}=e;return{open(o={}){n(),i.current=!1,r.current=o.trigger??document.activeElement,t({type:"open",severity:o.severity??"",subsystem:o.subsystem??"",sessionRows:Dd()})},close(){n(),t({type:"close"})},navigateToRecovery(o){n(),i.current=!0,t({type:"close"}),queueMicrotask(()=>{window.location.hash=o,setTimeout(()=>RP(o)?.focus(),0)})},restoreFocus(o){IP(o,r,i)}}}function TP(e){const{state:t,dispatch:n,abortRequest:r}=e;return{setSeverity(i){r(),n({type:"set_severity",severity:i})},setSubsystem(i){r(),n({type:"set_subsystem",subsystem:i})},resetFilters(){r(),n({type:"reset_filters"})},togglePaused(){t.paused||r(),n({type:"set_paused",paused:!t.paused})},revealTechnical(){r(),n({type:"reveal_technical"})}}}async function PP(e,t){if(!globalThis.confirm("Copied diagnostics may contain sensitive operational context. Copy the visible redacted events?"))return;const n=AP(Od(e));try{await navigator.clipboard.writeText(n),t({type:"set_copy_status",status:"Visible redacted events copied."})}catch{t({type:"set_copy_status",status:"Visible events could not be copied. Check clipboard permission and try again."})}}function NP(e){const{state:t,dispatch:n,abortRequest:r,listRef:i}=e;return{showQueued(){n({type:"show_queued"}),i.current&&(i.current.scrollTop=0)},clearView(){r(),n({type:"clear_view",sessionEvents:Dd()})},copyVisibleEvents:()=>PP(t,n)}}function EP(e){return{...kP(e),refresh:()=>e.runRequest("poll"),retry:()=>e.runRequest(e.state.rows.length>0?"poll":"replace","retry"),loadOlder:()=>e.runRequest("older"),...TP(e),...NP(e)}}function AP(e){return JSON.stringify(e.map(t=>{const n=Ad(t.recovery?.href)||!!t.recovery?.command;return{occurred_at:t.occurred_at,severity:t.severity,subsystem:t.subsystem,code:t.code,message:t.message,...n?{recovery_label:t.recovery?.label}:{},...t.correlation?.label?{correlation_label:t.correlation.label}:{}}}),null,2)}function xP(e){const t=B(e),n=B(null),r=B(0);return t.current=e,{stateRef:t,requestRef:n,generationRef:r}}function DP(e,t){const n=B(t);n.current=t,V(()=>{e.open&&n.current("replace")},[e.open,e.queryRevision]),V(()=>{!e.open||e.pollRevision===0||n.current("poll")},[e.open,e.pollRevision]),V(()=>{!e.open||!e.includeTechnical||n.current("technical")},[e.includeTechnical,e.open])}function LP(e){const{state:t,dispatch:n,loadEvents:r,listRef:i}=e,{stateRef:o,requestRef:s,generationRef:c}=xP(t);function l(){c.current+=1,s.current?.controller.abort(),s.current=null}function d(p,f){const m=o.current;return m.open?p!=="poll"?!1:s.current!==null?!0:f==="retry"?!1:m.paused||document.visibilityState==="hidden":!0}async function u(p,f="routine"){if(d(p,f))return;n({type:"refresh_session_rows",events:Dd(),readingOlder:Fd(i)});const m=new AbortController;s.current?.controller.abort();const v=++c.current;s.current={controller:m,generation:v},n({type:"request_started",mode:p});try{const g=o.current,h=await bP(r,p,g,m.signal);if(v!==c.current)return;n({type:"request_succeeded",mode:p,response:h,readingOlder:Fd(i)})}catch(g){if(v!==c.current||wP(g))return;n({type:"request_failed",mode:p,restartQuery:_P(p,g)})}finally{v===c.current&&(s.current=null)}}return DP(t,u),{abortRequest:l,runRequest:u}}function $P(e){const[t,n]=In(mP,$d()),r=B(null),i=B(!1),o=B(null),{abortRequest:s,runRequest:c}=LP({state:t,dispatch:n,loadEvents:e,listRef:o});V(()=>oP(d=>{n({type:"session_event_recorded",event:d,readingOlder:Fd(o)})}),[]);const l=EP({state:t,dispatch:n,abortRequest:s,runRequest:c,openerRef:r,recoveryNavigationRef:i,listRef:o});return{state:t,visibleRows:Od(t),listRef:o,...l}}function Bd(e){return e==="error"?{icon:"×",label:"Error"}:e==="warning"?{icon:"!",label:"Warning"}:{icon:"i",label:"Info"}}function OP({event:e,includeTechnical:t,onRecoveryNavigation:n}){const r=Bd(e.severity),i=e.recovery?.href;return a("li",{className:`diagnostics-event diagnostics-event--${e.severity}`,children:[a("div",{className:"diagnostics-event-heading",children:[a("span",{className:"diagnostics-severity",children:[a("span",{"aria-hidden":"true",className:"diagnostics-severity-icon",children:r.icon}),r.label]}),a("time",{dateTime:e.occurred_at,children:new Date(e.occurred_at).toLocaleString()})]}),a("div",{className:"diagnostics-event-context",children:[a("span",{children:e.subsystem}),a("code",{children:e.code})]}),a("p",{children:e.message}),e.correlation?a("div",{className:"diagnostics-event-meta",children:[e.correlation.kind,": ",e.correlation.label]}):null,t&&e.technical_detail?.text?a("details",{className:"diagnostics-technical-detail",children:[a("summary",{children:"Technical detail"}),a("pre",{children:e.technical_detail.text})]}):null,Ad(i)?a("a",{className:"diagnostics-recovery",href:i,onClick:o=>{o.preventDefault(),n(i)},children:e.recovery?.label}):null,e.recovery?.command?a("div",{className:"diagnostics-recovery-command",children:[a("span",{children:e.recovery.label}),a("code",{children:e.recovery.command})]}):null]})}function jP(){return a("div",{"aria-busy":"true","aria-label":"Loading diagnostics",className:"diagnostics-loading",role:"status",children:["first","second","third"].map(e=>a("div",{className:"diagnostics-loading-row",children:[a("span",{}),a("span",{}),a("span",{})]},e))})}function MP({controller:e}){const{state:t}=e;return a(z,{children:[a("div",{className:"diagnostics-controls",children:[a("label",{children:[a("span",{children:"Severity"}),a("select",{"aria-label":"Diagnostic severity",onChange:n=>e.setSeverity(n.currentTarget.value),value:t.severity,children:[a("option",{value:"",children:"All severities"}),nv.map(n=>a("option",{value:n,children:Bd(n).label},n))]})]}),a("label",{children:[a("span",{children:"Subsystem"}),a("select",{"aria-label":"Diagnostic subsystem",onChange:n=>e.setSubsystem(n.currentTarget.value),value:t.subsystem,children:[a("option",{value:"",children:"All subsystems"}),rv.map(n=>a("option",{value:n,children:n},n))]})]}),a("button",{className:"settings-button",onClick:e.togglePaused,type:"button",children:t.paused?"Resume updates":"Pause updates"})]}),a("div",{className:"diagnostics-secondary-controls",children:[a("div",{className:"diagnostics-secondary-actions",children:[a("button",{className:"settings-button",disabled:t.includeTechnical||t.loading,onClick:e.revealTechnical,type:"button",children:t.includeTechnical?"Technical details shown":"Reveal technical details"}),a("button",{className:"settings-button",onClick:e.clearView,type:"button",children:"Clear view"}),a("button",{className:"settings-button",disabled:!e.visibleRows.length,onClick:()=>{e.copyVisibleEvents()},type:"button",children:"Copy visible redacted events"})]}),a("span",{className:"diagnostics-generated-at",children:t.generatedAt?`Generated ${new Date(t.generatedAt).toLocaleTimeString()}`:"Not loaded yet"})]})]})}function FP({controller:e}){const{state:t}=e,n=aP(t),r=t.error&&t.rows.length?"Showing stale events.":"";return a(z,{children:[a("div",{"aria-atomic":"true","aria-live":"polite",className:"sr-only",children:t.announcement}),a("div",{"aria-atomic":"true","aria-live":"polite",className:"diagnostics-copy-status",children:t.copyStatus}),t.subsystem||t.severity?a("div",{className:"diagnostics-filter-context",children:["Showing"," ",t.severity?`${Bd(t.severity).label.toLowerCase()} `:"",t.subsystem?`${t.subsystem} `:"","events from the recent retained window."]}):null,t.paused?a("div",{className:"diagnostics-notice",role:"status",children:"Updates are paused. Resume when you are ready to fetch newer events."}):null,t.error?a("div",{className:"diagnostics-notice diagnostics-notice--error",role:"alert",children:[a("span",{children:["Diagnostics could not be refreshed. ",r]}),a("button",{className:"settings-button",onClick:()=>{e.retry()},type:"button",children:"Retry"})]}):null,n?a("button",{className:"diagnostics-new-events",onClick:e.showQueued,type:"button",children:["Show ",n," new ",n===1?"event":"events"]}):null]})}function BP({controller:e}){const{state:t}=e,n=e.visibleRows,r=!!(t.severity||t.subsystem),i=!!t.nextCursor&&n.length<200&&!t.loading;return a("div",{className:"diagnostics-event-list",ref:e.listRef,children:[t.loading&&!n.length?a(jP,{}):null,!t.loading&&!t.error&&!n.length?a("div",{className:"diagnostics-empty",children:[a("p",{children:"No events match the recent retained window."}),r?a("button",{className:"settings-button",onClick:e.resetFilters,type:"button",children:"Reset filters"}):null]}):null,n.length?a("ul",{"aria-label":"Diagnostic events",children:n.map(o=>a(OP,{event:o,includeTechnical:t.includeTechnical,onRecoveryNavigation:e.navigateToRecovery},o.id))}):null,i?a("button",{className:"settings-button diagnostics-load-older",onClick:()=>{e.loadOlder()},type:"button",children:"Load older"}):null,n.length>=200?a("div",{className:"diagnostics-limit-note",children:["Showing the newest ",200," events."]}):null]})}function qP({controller:e}){return a(Qn,{ariaDescribedby:"diagnosticsDrawerDescription",ariaLabelledby:"diagnosticsDrawerTitle",contentClassName:"diagnostics-drawer",contentId:"diagnosticsDrawer",onCloseAutoFocus:e.restoreFocus,onOpenAutoFocus:t=>{t.preventDefault(),document.getElementById("diagnosticsDrawerTitle")?.focus()},onOpenChange:t=>{t||e.close()},open:e.state.open,overlayClassName:"diagnostics-drawer-overlay",overlayId:"diagnosticsDrawerOverlay",children:[a("header",{className:"diagnostics-drawer-header",children:[a("div",{children:[a(Dg,{id:"diagnosticsDrawerTitle",tabIndex:-1,children:"Diagnostics"}),a("p",{id:"diagnosticsDrawerDescription",children:"Recent redacted operational events. Filters apply only to this drawer."})]}),a(kr,{ariaLabel:"Close diagnostics",onClick:e.close})]}),a(MP,{controller:e}),a(FP,{controller:e}),a(BP,{controller:e})]})}var Ai=null;function UP({dependencies:e}){const t=$P(e.loadEvents??rP);return V(()=>{const n={open:t.open,refresh:t.refresh,close:t.close};return Ai=n,()=>{Ai===n&&(Ai=null)}},[t.open,t.refresh,t.close]),a(qP,{controller:t})}function GP(e,t={}){Ue(a(UP,{dependencies:t}),e)}function Ar(e={}){Ai?.open(e)}function uv(e){Ai?.close(),e&&queueMicrotask(e)}async function HP(){await Ai?.refresh()}function VP(){document.getElementById("healthOpenDiagnostics")?.addEventListener("click",e=>{Ar({trigger:e.currentTarget})}),document.getElementById("syncOpenDiagnostics")?.addEventListener("click",e=>{Ar({subsystem:"sync",trigger:e.currentTarget})}),document.getElementById("viewerReconnectDiagnostics")?.addEventListener("click",e=>{Ar({subsystem:"viewer",trigger:e.currentTarget})})}var KP=Symbol.for("preact-signals");function Is(){if(An>1)An--;else{var e,t=!1;for((function(){var i=Ps;for(Ps=void 0;i!==void 0;){var o=i.S;if(o.v===i.v)for(var s=o.t;s!==void 0;s=s.x)s.i===i.i&&(s.i=o.i);i=i.o}})();jo!==void 0;){var n=jo;for(jo=void 0,Ts++;n!==void 0;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&fv(n))try{n.c()}catch(i){t||(e=i,t=!0)}n=r}}if(Ts=0,An--,t)throw e}}function zP(e){if(An>0)return e();qd=++WP,An++;try{return e()}finally{Is()}}var Oo,Ve=void 0;function ks(e){var t=Ve,n=Oo;Ve=void 0,Oo=void 0;try{return e()}finally{Ve=t,Oo=n}}var jo=void 0,An=0,Ts=0,WP=0,qd=0,Ps=void 0,Ns=0;function pv(e){if(Ve!==void 0){var t=e.n;if(t===void 0||t.t!==Ve)return t={i:0,S:e,p:Ve.s,n:void 0,t:Ve,e:void 0,x:void 0,r:t},Ve.s!==void 0&&(Ve.s.n=t),Ve.s=t,e.n=t,32&Ve.f&&e.S(t),t;if(t.i===-1)return t.i=0,t.n!==void 0&&(t.n.p=t.p,t.p!==void 0&&(t.p.n=t.n),t.p=Ve.s,t.n=void 0,Ve.s.n=t,Ve.s=t),t}}function pt(e,t){this.v=e,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=t?.watched,this.Z=t?.unwatched,this.name=t?.name}pt.prototype.brand=KP,pt.prototype.h=function(){return!0},pt.prototype.S=function(e){var t=this,n=this.t;n!==e&&e.e===void 0&&(e.x=n,this.t=e,n!==void 0?n.e=e:ks(function(){var r;(r=t.W)==null||r.call(t)}))},pt.prototype.U=function(e){var t=this;if(this.t!==void 0){var n=e.e,r=e.x;n!==void 0&&(n.x=r,e.e=void 0),r!==void 0&&(r.e=n,e.x=void 0),e===this.t&&(this.t=r,r===void 0&&ks(function(){var i;(i=t.Z)==null||i.call(t)}))}},pt.prototype.subscribe=function(e){var t=this;return Mo(function(){var n=t.value;ks(function(){return e(n)})},{name:"sub"})},pt.prototype.valueOf=function(){return this.value},pt.prototype.toString=function(){return this.value+""},pt.prototype.toJSON=function(){return this.value},pt.prototype.peek=function(){var e=this;return ks(function(){return e.value})},Object.defineProperty(pt.prototype,"value",{get:function(){var e=pv(this);return e!==void 0&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(Ts>100)throw new Error("Cycle detected");(function(n){An!==0&&Ts===0&&n.l!==qd&&(n.l=qd,Ps={S:n,v:n.v,i:n.i,o:Ps})})(this),this.v=e,this.i++,Ns++,An++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{Is()}}}});function Ud(e,t){return new pt(e,t)}function fv(e){for(var t=e.s;t!==void 0;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function mv(e){for(var t=e.s;t!==void 0;t=t.n){var n=t.S.n;if(n!==void 0&&(t.r=n),t.S.n=t,t.i=-1,t.n===void 0){e.s=t;break}}}function hv(e){for(var t=e.s,n=void 0;t!==void 0;){var r=t.p;t.i===-1?(t.S.U(t),r!==void 0&&(r.n=t.n),t.n!==void 0&&(t.n.p=r)):n=t,t.S.n=t.r,t.r!==void 0&&(t.r=void 0),t=r}e.s=n}function xr(e,t){pt.call(this,void 0,t),this.x=e,this.s=void 0,this.g=Ns-1,this.f=4}xr.prototype=new pt,xr.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Ns))return!0;if(this.g=Ns,this.f|=1,this.i>0&&!fv(this))return this.f&=-2,!0;var e=Ve;try{mv(this),Ve=this;var t=this.x();(16&this.f||this.v!==t||this.i===0)&&(this.v=t,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return Ve=e,hv(this),this.f&=-2,!0},xr.prototype.S=function(e){if(this.t===void 0){this.f|=36;for(var t=this.s;t!==void 0;t=t.n)t.S.S(t)}pt.prototype.S.call(this,e)},xr.prototype.U=function(e){if(this.t!==void 0&&(pt.prototype.U.call(this,e),this.t===void 0)){this.f&=-33;for(var t=this.s;t!==void 0;t=t.n)t.S.U(t)}},xr.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var e=this.t;e!==void 0;e=e.x)e.t.N()}},Object.defineProperty(xr.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var e=pv(this);if(this.h(),e!==void 0&&(e.i=this.i),16&this.f)throw this.v;return this.v}});function gv(e,t){return new xr(e,t)}function vv(e){var t=e.m;if(e.m=void 0,typeof t=="function"){An++;var n=Ve;Ve=void 0;try{t()}catch(r){throw e.f&=-2,e.f|=8,Gd(e),r}finally{Ve=n,Is()}}}function Gd(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,vv(e)}function JP(e){if(Ve!==this)throw new Error("Out-of-order effect");hv(this),Ve=e,this.f&=-2,8&this.f&&Gd(this),Is()}function xi(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=t?.name,Oo&&Oo.push(this)}xi.prototype.c=function(){var e=this.S();try{if(8&this.f||this.x===void 0)return;var t=this.x();typeof t=="function"&&(this.m=t)}finally{e()}},xi.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,vv(this),mv(this),An++;var e=Ve;return Ve=this,JP.bind(this,e)},xi.prototype.N=function(){2&this.f||(this.f|=2,this.u=jo,jo=this)},xi.prototype.d=function(){this.f|=8,1&this.f||Gd(this)},xi.prototype.dispose=function(){this.d()};function Mo(e,t){var n=new xi(e,t);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var yv,Hd,Es,YP=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,bv=[];Mo(function(){yv=this.N})();function Di(e,t){ge[e]=t.bind(null,ge[e]||function(){})}function As(e){if(Es){var t=Es;Es=void 0,t()}Es=e&&e.S()}function _v(e){var t=this,n=e.data,r=QP(n);r.name="ReactiveDom",r.value=n;var i=ke(function(){for(var c=t,l=t.__v;l=l.__;)if(l.__c){l.__c.__$f|=4;break}var d=gv(function(){var m=r.value.value;return m===0?0:m===!0?"":m||""}),u=gv(function(){return!Array.isArray(d.value)&&!Mm(d.value)}),p=Mo(function(){if(this.N=wv,u.value){var m=d.value;c.__v&&c.__v.__e&&c.__v.__e.nodeType===3&&(c.__v.__e.data=m)}}),f=t.__$u.d;return t.__$u.d=function(){p(),f.call(this)},[u,d]},[]),o=i[0],s=i[1];return o.value?s.peek():s.value}_v.displayName="ReactiveTextNode",Object.defineProperties(pt.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:_v},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}}),Di("__b",function(e,t){if(typeof t.type=="string"){var n,r=t.props;for(var i in r)if(i!=="children"){var o=r[i];o instanceof pt&&(n||(t.__np=n={}),n[i]=o,r[i]=o.peek())}}e(t)}),Di("__r",function(e,t){if(e(t),t.type!==z){As();var n,r=t.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,o){var s;return Mo(function(){s=this},{name:o}),s.c=i,s})((function(i){return function(){var o;YP&&((o=this.y)==null||o.call(this)),i.__$f|=1,i.setState({})}})(r),typeof t.type=="function"?t.type.displayName||t.type.name:""))),Hd=r,As(n)}}),Di("__e",function(e,t,n,r){As(),Hd=void 0,e(t,n,r)}),Di("diffed",function(e,t){As(),Hd=void 0;var n;if(typeof t.type=="string"&&(n=t.__e)){var r=t.__np,i=t.props,o=n.U;if(o)for(var s in o){var c=o[s];c===void 0||r&&s in r||(c.d(),o[s]=void 0)}if(r){o||(o={},n.U=o);for(var l in r){var d=o[l],u=r[l];d===void 0?(d=XP(n,l,u,i),o[l]=d):d.o(u,i)}}}e(t)});function XP(e,t,n,r){var i=t in e&&e.ownerSVGElement===void 0,o=Ud(n);return{o:function(s,c){o.value=s,r=c},d:Mo(function(){this.N=wv;var s=o.value.value;r[t]!==s&&(r[t]=s,i?e[t]=s:s!=null&&(s!==!1||t[4]==="-")?e.setAttribute(t,s):e.removeAttribute(t))})}}Di("unmount",function(e,t){if(typeof t.type=="string"){var n=t.__e;if(n){var r=n.U;if(r){n.U=void 0;for(var i in r){var o=r[i];o&&o.d()}}}var s=t.__np;if(s){var c=t.props;for(var l in s)c[l]=s[l]}t.__np=void 0}else{var d=t.__c;if(d){var u=d.__$u;u&&(d.__$u=void 0,u.d())}}e(t)}),Di("__h",function(e,t,n,r){r<3&&(t.__$f|=2),e(t,n,r)}),Mt.prototype.shouldComponentUpdate=function(e,t){if(this.__R)return!0;var n=this.__$u,r=n&&n.s!==void 0;for(var i in t)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var o=2&this.__$f;if(!(r||o||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var s in e)if(s!=="__source"&&e[s]!==this.props[s])return!0;for(var c in this.props)if(!(c in e))return!0;return!1};function QP(e,t){return ke(function(){return Ud(e,t)},[])}var ZP=function(e){queueMicrotask(function(){queueMicrotask(e)})};function eN(){zP(function(){for(var e;e=bv.shift();)yv.call(e)})}function wv(){bv.push(this)===1&&(ge.requestAnimationFrame||ZP)(eN)}var tN=Object.defineProperty,at=(e,t)=>tN(e,"name",{value:t,configurable:!0});function Fo(e){const t=e+"CollectionProvider",[n,r]=dt(t),[i,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=at(g=>{const{scope:h,children:b}=g,w=B(null),_=B(new Map).current;return a(i,{scope:h,itemMap:_,collectionRef:w,children:b})},"CollectionProvider");s.displayName=t;const c=e+"CollectionSlot",l=cn(c),d=J((g,h)=>{const{scope:b,children:w}=g,_=o(c,b),R=Re(h,_.collectionRef);return a(l,{ref:R,children:w})});d.displayName=c;const u=e+"CollectionItemSlot",p="data-radix-collection-item",f=cn(u),m=J((g,h)=>{const{scope:b,children:w,..._}=g,R=B(null),I=Re(h,R),T=o(u,b);return V(()=>(T.itemMap.set(R,{ref:R,..._}),()=>{T.itemMap.delete(R)})),a(f,{[p]:"",ref:I,children:w})});m.displayName=u;function v(g){const h=o(e+"CollectionConsumer",g);return ae(()=>{const b=h.collectionRef.current;if(!b)return[];const w=Array.from(b.querySelectorAll(`[${p}]`));return Array.from(h.itemMap.values()).sort((_,R)=>w.indexOf(_.ref.current)-w.indexOf(R.ref.current))},[h.collectionRef,h.itemMap])}return at(v,"useCollection"),[{Provider:s,Slot:d,ItemSlot:m},v,r]}at(Fo,"createCollection");var Sv=new WeakMap,Vd=class _r extends Map{static{at(this,"OrderedDict")}#e;constructor(t){super(t),this.#e=[...super.keys()],Sv.set(this,!0)}set(t,n){return Sv.get(this)&&(this.has(t)?this.#e[this.#e.indexOf(t)]=t:this.#e.push(t)),super.set(t,n),this}insert(t,n,r){const i=this.has(n),o=this.#e.length,s=Kd(t);let c=s>=0?s:o+s;const l=c<0||c>=o?-1:c;if(l===this.size||i&&l===this.size-1||l===-1)return this.set(n,r),this;const d=this.size+(i?0:1);s<0&&c++;const u=[...this.#e];let p,f=!1;for(let m=c;m<d;m++)if(c===m){let v=u[m];u[m]===n&&(v=u[m+1]),i&&this.delete(n),p=this.get(v),this.set(n,r)}else{!f&&u[m-1]===n&&(f=!0);const v=u[f?m:m-1],g=p;p=this.get(v),this.delete(v),this.set(v,g)}return this}with(t,n,r){const i=new _r(this);return i.insert(t,n,r),i}before(t){const n=this.#e.indexOf(t)-1;if(!(n<0))return this.entryAt(n)}setBefore(t,n,r){const i=this.#e.indexOf(t);return i===-1?this:this.insert(i,n,r)}after(t){let n=this.#e.indexOf(t);if(n=n===-1||n===this.size-1?-1:n+1,n!==-1)return this.entryAt(n)}setAfter(t,n,r){const i=this.#e.indexOf(t);return i===-1?this:this.insert(i+1,n,r)}first(){return this.entryAt(0)}last(){return this.entryAt(-1)}clear(){return this.#e=[],super.clear()}delete(t){const n=super.delete(t);return n&&this.#e.splice(this.#e.indexOf(t),1),n}deleteAt(t){const n=this.keyAt(t);return n!==void 0?this.delete(n):!1}at(t){const n=xs(this.#e,t);if(n!==void 0)return this.get(n)}entryAt(t){const n=xs(this.#e,t);if(n!==void 0)return[n,this.get(n)]}indexOf(t){return this.#e.indexOf(t)}keyAt(t){return xs(this.#e,t)}from(t,n){const r=this.indexOf(t);if(r===-1)return;let i=r+n;return i<0&&(i=0),i>=this.size&&(i=this.size-1),this.at(i)}keyFrom(t,n){const r=this.indexOf(t);if(r===-1)return;let i=r+n;return i<0&&(i=0),i>=this.size&&(i=this.size-1),this.keyAt(i)}find(t,n){let r=0;for(const i of this){if(Reflect.apply(t,n,[i,r,this]))return i;r++}}findIndex(t,n){let r=0;for(const i of this){if(Reflect.apply(t,n,[i,r,this]))return r;r++}return-1}filter(t,n){const r=[];let i=0;for(const o of this)Reflect.apply(t,n,[o,i,this])&&r.push(o),i++;return new _r(r)}map(t,n){const r=[];let i=0;for(const o of this)r.push([o[0],Reflect.apply(t,n,[o,i,this])]),i++;return new _r(r)}reduce(...t){const[n,r]=t;let i=0,o=r??this.at(0);for(const s of this)i===0&&t.length===1?o=s:o=Reflect.apply(n,this,[o,s,i,this]),i++;return o}reduceRight(...t){const[n,r]=t;let i=r??this.at(-1);for(let o=this.size-1;o>=0;o--){const s=this.at(o);o===this.size-1&&t.length===1?i=s:i=Reflect.apply(n,this,[i,s,o,this])}return i}toSorted(t){const n=[...this.entries()].sort(t);return new _r(n)}toReversed(){const t=new _r;for(let n=this.size-1;n>=0;n--){const r=this.keyAt(n),i=this.get(r);t.set(r,i)}return t}toSpliced(...t){const n=[...this.entries()];return n.splice(...t),new _r(n)}slice(t,n){const r=new _r;let i=this.size-1;if(t===void 0)return r;t<0&&(t=t+this.size),n!==void 0&&n>0&&(i=n-1);for(let o=t;o<=i;o++){const s=this.keyAt(o),c=this.get(s);r.set(s,c)}return r}every(t,n){let r=0;for(const i of this){if(!Reflect.apply(t,n,[i,r,this]))return!1;r++}return!0}some(t,n){let r=0;for(const i of this){if(Reflect.apply(t,n,[i,r,this]))return!0;r++}return!1}};function xs(e,t){if("at"in Array.prototype)return Array.prototype.at.call(e,t);const n=Cv(e,t);return n===-1?void 0:e[n]}at(xs,"at");function Cv(e,t){const n=e.length,r=Kd(t),i=r>=0?r:n+r;return i<0||i>=n?-1:i}at(Cv,"toSafeIndex");function Kd(e){return e!==e||e===0?0:Math.trunc(e)}at(Kd,"toSafeInteger");function nN(e){const t=e+"CollectionProvider",[n,r]=dt(t),[i,o]=n(t,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new Vd,setItemMap:at(()=>{},"setItemMap")}),s=at(({state:w,..._})=>w?a(l,{..._,state:w}):a(c,{..._}),"CollectionProvider");s.displayName=t;const c=at(w=>{const _=h();return a(l,{...w,state:_})},"CollectionInit");c.displayName=t+"Init";const l=at(w=>{const{scope:_,children:R,state:I}=w,T=B(null),[A,O]=x(null),F=Re(T,O),[N,L]=I;return V(()=>{if(!A)return;const D=kv(()=>{});return D.observe(A,{childList:!0,subtree:!0}),()=>{D.disconnect()}},[A]),a(i,{scope:_,itemMap:N,setItemMap:L,collectionRef:F,collectionRefObject:T,collectionElement:A,children:R})},"CollectionProviderImpl");l.displayName=t+"Impl";const d=e+"CollectionSlot",u=cn(d),p=J((w,_)=>{const{scope:R,children:I}=w,T=o(d,R),A=Re(_,T.collectionRef);return a(u,{ref:A,children:I})});p.displayName=d;const f=e+"CollectionItemSlot",m="data-radix-collection-item",v=cn(f),g=J((w,_)=>{const{scope:R,children:I,...T}=w,A=B(null),[O,F]=x(null),N=Re(_,A,F),{setItemMap:L}=o(f,R),D=B(T);Rv(D.current,T)||(D.current=T);const G=D.current;return V(()=>{const q=G;return L($=>O?$.has(O)?$.set(O,{...q,element:O}).toSorted(zd):($.set(O,{...q,element:O}),$.toSorted(zd)):$),()=>{L($=>!O||!$.has(O)?$:($.delete(O),new Vd($)))}},[O,G,L]),a(v,{[m]:"",ref:N,children:I})});g.displayName=f;function h(){return x(new Vd)}at(h,"useInitCollection");function b(w){const{itemMap:_}=o(e+"CollectionConsumer",w);return _}return at(b,"useCollection"),[{Provider:s,Slot:p,ItemSlot:g},{createCollectionScope:r,useCollection:b,useInitCollection:h}]}at(nN,"createCollection");function Rv(e,t){if(e===t)return!0;if(typeof e!="object"||typeof t!="object"||e==null||t==null)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const i of n)if(!Object.prototype.hasOwnProperty.call(t,i)||e[i]!==t[i])return!1;return!0}at(Rv,"shallowEqual");function Iv(e,t){return!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_PRECEDING)}at(Iv,"isElementPreceding");function zd(e,t){return!e[1].element||!t[1].element?0:Iv(e[1].element,t[1].element)?-1:1}at(zd,"sortByDocumentPosition");function kv(e){return new MutationObserver(t=>{for(const n of t)if(n.type==="childList"){e();return}})}at(kv,"getChildListObserver");var rN=Object.defineProperty,iN=(e,t)=>rN(e,"name",{value:t,configurable:!0}),Tv=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),Wd=J(iN(function(t,n){return a(ye.span,{...t,ref:n,style:{...Tv,...t.style}})},"VisuallyHidden")),oN=Wd,aN=Object.defineProperty,Ge=(e,t)=>aN(e,"name",{value:t,configurable:!0}),Pv="ToastProvider",[Jd,Nv,sN]=Fo("Toast"),[Ev,U2]=dt("Toast",[sN]),[cN,Ds]=Ev(Pv),lN=Ge(e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:i="right",swipeThreshold:o=50,announcerContainer:s,children:c}=e,[l,d]=x(null),[u,p]=x(0),f=B(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${Pv}\`. Expected non-empty \`string\`.`),a(Jd.Provider,{scope:t,children:a(cN,{scope:t,label:n,duration:r,swipeDirection:i,swipeThreshold:o,toastCount:u,viewport:l,onViewportChange:d,onToastAdd:ae(()=>p(m=>m+1),[]),onToastRemove:ae(()=>p(m=>m-1),[]),isClosePausedRef:f,announcerContainer:s,children:c})})},"ToastProvider"),dN="ToastViewport",uN=["F8"],Yd="toast.viewportPause",Xd="toast.viewportResume",pN=J(Ge(function(t,n){const{__scopeToast:r,hotkey:i=uN,label:o="Notifications ({hotkey})",...s}=t,c=Ds(dN,r),l=Nv(r),d=B(null),u=B(null),p=B(null),f=B(null),m=Re(n,f,c.onViewportChange),v=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),g=c.toastCount>0;V(()=>{const b=Ge(w=>{i.length!==0&&i.every(_=>w[_]||w.code===_)&&f.current?.focus()},"handleKeyDown");return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[i]),V(()=>{const b=d.current,w=f.current;if(g&&b&&w){const _=Ge(()=>{if(!c.isClosePausedRef.current){const A=new CustomEvent(Yd);w.dispatchEvent(A),c.isClosePausedRef.current=!0}},"handlePause"),R=Ge(()=>{if(c.isClosePausedRef.current){const A=new CustomEvent(Xd);w.dispatchEvent(A),c.isClosePausedRef.current=!1}},"handleResume"),I=Ge(A=>{b.contains(A.relatedTarget)||R()},"handleFocusOutResume"),T=Ge(()=>{b.contains(document.activeElement)||R()},"handlePointerLeaveResume");return b.addEventListener("focusin",_),b.addEventListener("focusout",I),b.addEventListener("pointermove",_),b.addEventListener("pointerleave",T),window.addEventListener("blur",_),window.addEventListener("focus",R),()=>{b.removeEventListener("focusin",_),b.removeEventListener("focusout",I),b.removeEventListener("pointermove",_),b.removeEventListener("pointerleave",T),window.removeEventListener("blur",_),window.removeEventListener("focus",R)}}},[g,c.isClosePausedRef]);const h=ae(({tabbingDirection:b})=>{const w=l().map(_=>{const R=_.ref.current,I=[R,...$v(R)];return b==="forwards"?I:I.reverse()});return(b==="forwards"?w.reverse():w).flat()},[l]);return V(()=>{const b=f.current;if(b){const w=Ge(_=>{const R=_.altKey||_.ctrlKey||_.metaKey;if(_.key==="Tab"&&!R){const I=document.activeElement,T=_.shiftKey;if(_.target===b&&T){u.current?.focus();return}const A=h({tabbingDirection:T?"backwards":"forwards"}),O=A.findIndex(F=>F===I);$s(A.slice(O+1))?_.preventDefault():T?u.current?.focus():p.current?.focus()}},"handleKeyDown");return b.addEventListener("keydown",w),()=>b.removeEventListener("keydown",w)}},[l,h]),a(BI,{ref:d,role:"region","aria-label":o.replace("{hotkey}",v),tabIndex:-1,style:{pointerEvents:g?void 0:"none"},children:[g&&a(Av,{ref:u,onFocusFromOutsideViewport:()=>{$s(h({tabbingDirection:"forwards"}))}}),a(Jd.Slot,{scope:r,children:a(ye.ol,{tabIndex:-1,...s,ref:m})}),g&&a(Av,{ref:p,onFocusFromOutsideViewport:()=>{$s(h({tabbingDirection:"backwards"}))}})]})},"ToastViewport")),fN="ToastFocusProxy",Av=J(Ge(function(t,n){const{__scopeToast:r,onFocusFromOutsideViewport:i,...o}=t,s=Ds(fN,r);return a(Wd,{tabIndex:0,...o,ref:n,style:{position:"fixed"},onFocus:c=>{const l=c.relatedTarget;s.viewport?.contains(l)||i()}})},"ToastFocusProxy")),Ls="Toast",mN="toast.swipeStart",hN="toast.swipeMove",gN="toast.swipeCancel",vN="toast.swipeEnd",yN=J(Ge(function(t,n){const{forceMount:r,open:i,defaultOpen:o,onOpenChange:s,...c}=t,[l,d]=At({prop:i,defaultProp:o??!0,onChange:s,caller:Ls});return a(kt,{present:r||l,children:a(wN,{open:l,...c,ref:n,onClose:()=>d(!1),onPause:ht(t.onPause),onResume:ht(t.onResume),onSwipeStart:te(t.onSwipeStart,u=>{u.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:te(t.onSwipeMove,u=>{const{x:p,y:f}=u.detail.delta;u.currentTarget.setAttribute("data-swipe","move"),u.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${p}px`),u.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${f}px`)}),onSwipeCancel:te(t.onSwipeCancel,u=>{u.currentTarget.setAttribute("data-swipe","cancel"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),u.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:te(t.onSwipeEnd,u=>{const{x:p,y:f}=u.detail.delta;u.currentTarget.setAttribute("data-swipe","end"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),u.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${p}px`),u.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${f}px`),d(!1)})})})},"Toast")),[bN,_N]=Ev(Ls,{onClose(){}}),wN=J(Ge(function(t,n){const{__scopeToast:r,type:i="foreground",duration:o,open:s,onClose:c,onEscapeKeyDown:l,onPause:d,onResume:u,onSwipeStart:p,onSwipeMove:f,onSwipeCancel:m,onSwipeEnd:v,...g}=t,h=Ds(Ls,r),b=Nv(r),[w,_]=x(null),R=Re(n,_),I=B(null),T=B(null),A=o||h.duration,O=B(0),F=B(A),N=B(0),{onToastAdd:L,onToastRemove:D}=h,G=ht(()=>{w?.contains(document.activeElement)&&h.viewport?.focus(),c()}),q=ae(E=>{!E||E===1/0||(window.clearTimeout(N.current),O.current=new Date().getTime(),N.current=window.setTimeout(G,E))},[G]);V(()=>{const E=h.viewport;if(E){const S=Ge(()=>{q(F.current),u?.()},"handleResume"),M=Ge(()=>{const H=new Date().getTime()-O.current;F.current=F.current-H,window.clearTimeout(N.current),d?.()},"handlePause");return E.addEventListener(Yd,M),E.addEventListener(Xd,S),()=>{E.removeEventListener(Yd,M),E.removeEventListener(Xd,S)}}},[h.viewport,A,d,u,q]),V(()=>{s&&!h.isClosePausedRef.current&&q(A)},[s,A,h.isClosePausedRef,q]),V(()=>()=>{window.clearTimeout(N.current)},[]),V(()=>(L(),()=>D()),[L,D]);const $=ke(()=>w?Qd(w):null,[w]);return h.viewport?a(z,{children:[$&&a(SN,{__scopeToast:r,role:"status","aria-live":i==="foreground"?"assertive":"polite",children:$}),a(bN,{scope:r,onClose:G,children:sn(a(Jd.ItemSlot,{scope:r,children:a(FI,{asChild:!0,onEscapeKeyDown:te(l,E=>{b().some(S=>S.ref.current?.contains(E.target))||G()}),children:a(ye.li,{tabIndex:0,"data-state":s?"open":"closed","data-swipe-direction":h.swipeDirection,...g,ref:R,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:te(t.onKeyDown,E=>{E.key==="Escape"&&(l?.(E.nativeEvent),E.nativeEvent.defaultPrevented||G())}),onPointerDown:te(t.onPointerDown,E=>{E.button===0&&(I.current={x:E.clientX,y:E.clientY})}),onPointerMove:te(t.onPointerMove,E=>{if(!I.current)return;const S=E.clientX-I.current.x,M=E.clientY-I.current.y,H=!!T.current,U=["left","right"].includes(h.swipeDirection),re=["left","up"].includes(h.swipeDirection)?Math.min:Math.max,oe=U?re(0,S):0,ie=U?0:re(0,M),se=E.pointerType==="touch"?10:2,ue={x:oe,y:ie},Pe={originalEvent:E,delta:ue};H?(T.current=ue,Bo(hN,f,Pe,{discrete:!1})):xv(ue,h.swipeDirection,se)?(T.current=ue,Bo(mN,p,Pe,{discrete:!1}),E.target.setPointerCapture(E.pointerId)):(Math.abs(S)>se||Math.abs(M)>se)&&(I.current=null)}),onPointerUp:te(t.onPointerUp,E=>{const S=T.current,M=E.target;if(M.hasPointerCapture(E.pointerId)&&M.releasePointerCapture(E.pointerId),T.current=null,I.current=null,S){const H=E.currentTarget,U={originalEvent:E,delta:S};xv(S,h.swipeDirection,h.swipeThreshold)?Bo(vN,v,U,{discrete:!0}):Bo(gN,m,U,{discrete:!0}),H.addEventListener("click",re=>re.preventDefault(),{once:!0})}})})})}),h.viewport)})]}):null},"ToastImpl")),SN=Ge(e=>{const{__scopeToast:t,children:n,...r}=e,i=Ds(Ls,t),[o,s]=x(!1),[c,l]=x(!1);return Dv(()=>s(!0)),V(()=>{const d=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(d)},[]),c?null:a(_i,{asChild:!0,container:i.announcerContainer||void 0,children:a(Wd,{...r,children:o&&a(z,{children:[i.label," ",n]})})})},"ToastAnnounce"),CN=J(Ge(function(t,n){const{__scopeToast:r,...i}=t;return a(ye.div,{...i,ref:n})},"ToastDescription")),RN="ToastClose",IN=J(Ge(function(t,n){const{__scopeToast:r,...i}=t,o=_N(RN,r);return a(kN,{asChild:!0,children:a(ye.button,{type:"button",...i,ref:n,onClick:te(t.onClick,o.onClose)})})},"ToastClose")),kN=J(Ge(function(t,n){const{__scopeToast:r,altText:i,...o}=t;return a(ye.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":i||void 0,...o,ref:n})},"ToastAnnounceExclude"));function Qd(e){const t=[];return Array.from(e.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),Lv(n)){const r=n.ariaHidden||n.hidden||n.style.display==="none",i=n.dataset.radixToastAnnounceExclude==="";if(!r)if(i){const o=n.dataset.radixToastAnnounceAlt;o&&t.push(o)}else t.push(...Qd(n))}}),t}Ge(Qd,"getAnnounceTextContent");function Bo(e,t,n,{discrete:r}){const i=n.originalEvent.currentTarget,o=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?os(i,o):i.dispatchEvent(o)}Ge(Bo,"handleAndDispatchCustomEvent");var xv=Ge((e,t,n=0)=>{const r=Math.abs(e.x),i=Math.abs(e.y),o=r>i;return t==="left"||t==="right"?o&&r>n:!o&&i>n},"isDeltaInDirection");function Dv(e=()=>{}){const t=ht(e);Ze(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}Ge(Dv,"useNextFrame");function Lv(e){return e.nodeType===e.ELEMENT_NODE}Ge(Lv,"isHTMLElement");function $v(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:Ge(r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}Ge($v,"getTabbableCandidates");function $s(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}Ge($s,"focusFirst");var TN=lN,PN=pN,NN=yN,EN=CN,AN=IN,qo=Ud([]),xN=1;function DN(e,t="success",n=8e3){if(!e)return;const r=xN++;qo.value=[...qo.value,{id:r,message:e,variant:t,durationMs:n}]}function LN(e){qo.value=qo.value.filter(t=>t.id!==e)}function $N(){const e=qo.value;return a(TN,{duration:8e3,swipeDirection:"right",children:[e.map(t=>a(NN,{className:`toast-root toast-${t.variant}`,duration:t.durationMs,onOpenChange:n=>{n||LN(t.id)},type:t.variant==="error"||t.variant==="warning"?"foreground":"background",children:[a(EN,{className:"toast-message",children:t.message}),a(AN,{"aria-label":"Dismiss",className:"toast-close",children:"×"})]},t.id)),a(PN,{className:"toast-viewport"})]})}function ON(e){Ue(a($N,{}),e)}function Os(e,t,n){const r=document.createElement(e);return t&&(r.className=t),n!=null&&(r.textContent=String(n)),r}function Le(e){return document.getElementById(e)}function Zd(e){return document.getElementById(e)}function js(e){return document.getElementById(e)}function Ov(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function jN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function MN(e,t){const n=t.trim();if(!n)return Ov(e);const r=Ov(e);try{const i=new RegExp(`(${jN(n)})`,"ig");return r.replace(i,'<mark class="match">$1</mark>')}catch{return r}}async function Uo(e,t){const n=t.textContent;try{await navigator.clipboard.writeText(e),t.textContent="Copied"}catch{t.textContent="Copy failed"}setTimeout(()=>{t.textContent=n||"Copy"},1200)}var FN=new Set(["BUTTON","A","SELECT"]),BN=new Set(["button","checkbox","color","file","image","radio","range","reset","submit"]);function qN(e){return!e||typeof e.closest!="function"?!1:e.closest('[data-primary-action-ignore="true"]')!==null}function UN(e){return e?!!(e instanceof HTMLTextAreaElement||"isContentEditable"in e&&e.isContentEditable):!1}function GN(e){return e?FN.has(e.tagName)?!0:e instanceof HTMLInputElement&&BN.has(e.type):!1}function HN(e){return e.metaKey||e.ctrlKey}function Li(e,t){if(t.disabled||e.defaultPrevented||e.isComposing||e.key!=="Enter"&&e.key!=="Escape")return;const n=e.target instanceof HTMLElement?e.target:null;if(!qN(n)){if(e.key==="Escape"){if(!t.onCancel)return;e.preventDefault(),t.onCancel();return}GN(n)||UN(n)&&!HN(e)||(e.preventDefault(),t.onSubmit())}}var Dr=["feed","projects","sharing","devices","health","advanced"],jv=["sync","coordinator-admin"],eu="codemem-tab",Mv="codemem-advanced-section",Fv="codemem-feed-filter",Bv="codemem-feed-scope",VN="codemem-sync-diagnostics",qv="codemem-sync-pairing",Uv="codemem-sync-redact",Gv=["all","observations","summaries"],Hv=["all","mine","theirs"],C={activeTab:"feed",advancedSection:"sync",currentProject:"",refreshState:"idle",refreshInFlight:!1,refreshQueued:!1,refreshTimer:null,feedTypeFilter:"all",feedScopeFilter:"all",feedQuery:"",lastFeedItems:[],lastFeedFilteredCount:0,lastFeedSignature:"",pendingFeedItems:null,itemViewState:new Map,itemExpandState:new Map,newItemKeys:new Set,lastStatsPayload:null,lastUsagePayload:null,lastRawEventsPayload:null,lastUpdateStatus:null,lastSyncStatus:null,lastDeviceIdentityInventory:null,deviceIdentityInventoryLoadError:!1,pendingDeviceIdentityFocus:void 0,lastSyncActors:[],lastSyncPeers:[],lastShareOperations:[],shareOperationsLoadError:!1,pendingAcceptedSyncPeers:[],lastSyncSharingReview:[],lastSyncLegacySharedReview:null,lastSyncCoordinator:null,lastSyncCoordinatorAdminStatus:null,lastCoordinatorAdminStatus:null,coordinatorAdminTargetGroup:"",knownProjects:[],lastProjectCoordinatorAdminGroups:[],lastCoordinatorAdminGroups:[],lastCoordinatorAdminJoinRequests:[],lastCoordinatorAdminDevices:[],lastSyncJoinRequests:[],lastTeamInvite:null,lastTeamJoin:null,syncJoinFlowFeedback:null,syncPeerFeedbackById:new Map,syncPeersSectionFeedback:null,syncJoinRequestsFeedback:null,syncDiscoveredFeedback:null,pendingCoordinatorApprovalsByDeviceId:new Map,lastSyncAttempts:[],lastSyncLegacyDevices:[],lastSyncViewModel:null,lastSyncDuplicatePersonDecisions:{},pairingPayloadRaw:null,pairingCommandRaw:"",configDefaults:{},configPath:"",settingsDirty:!1,syncDiagnosticsOpen:!1,syncPairingOpen:!1};function KN(e){return[...Dr]}function Go(e,t){return e==="sync"||e==="coordinator-admin"?"advanced":Dr.includes(e)?e:"feed"}function tu(e=window.location.hash){const t=e.replace(/^#/,"").split("/")[0];return jv.includes(t)?"advanced":Dr.includes(t)?t:null}function nu(e=window.location.hash){const[t,n]=e.replace(/^#/,"").split("/");return t==="sync"?"sync":t==="coordinator-admin"?"teams":t!=="advanced"?null:n==="teams"?"teams":"sync"}function zN(){const e=tu();if(e)return Go(e,C.lastCoordinatorAdminStatus);const t=localStorage.getItem(eu);return t&&(Dr.includes(t)||jv.includes(t))?Go(t,C.lastCoordinatorAdminStatus):"feed"}function WN(){const e=nu();if(e)return e;const t=localStorage.getItem(eu);return t==="coordinator-admin"?"teams":t==="sync"?"sync":localStorage.getItem(Mv)==="teams"?"teams":"sync"}function ru(e,t=!1){C.advancedSection=e,localStorage.setItem(Mv,e),t&&(window.location.hash=`advanced/${e}`)}function Vv(e,t={}){const n=Go(e,C.lastCoordinatorAdminStatus);C.activeTab=n,localStorage.setItem(eu,n);const r=tu();t.canonicalHash?window.location.hash=n:r!==n&&(window.location.hash=n==="advanced"?`advanced/${C.advancedSection}`:n)}function JN(){const e=localStorage.getItem(Fv)||"all";return Gv.includes(e)?e:"all"}function YN(){const e=localStorage.getItem(Bv)||"all";return Hv.includes(e)?e:"all"}function XN(e){C.feedTypeFilter=Gv.includes(e)?e:"all",localStorage.setItem(Fv,C.feedTypeFilter)}function Kv(e){C.feedScopeFilter=Hv.includes(e)?e:"all",localStorage.setItem(Bv,C.feedScopeFilter)}function QN(){return localStorage.getItem(VN)==="1"}function ZN(e){C.syncPairingOpen=e;try{localStorage.setItem(qv,e?"1":"0")}catch{}}function Ho(){return localStorage.getItem(Uv)!=="0"}function eE(e){localStorage.setItem(Uv,e?"1":"0")}function tE(){C.activeTab=zN(),C.advancedSection=WN(),C.feedTypeFilter=JN(),C.feedScopeFilter=YN(),C.syncDiagnosticsOpen=QN();try{C.syncPairingOpen=localStorage.getItem(qv)==="1"}catch{C.syncPairingOpen=!1}}function nE(e,t,n){t.left>=n.left&&t.right<=n.right||e.scrollIntoView({block:"nearest",inline:"nearest"})}function rE(){let e=null,t=null,n=null,r=null,i=null;return o=>{if(o.hidden)return;const s=o.closest(".tab-bar");if(!s)return;const c=o.getBoundingClientRect(),l=s.getBoundingClientRect(),d=c.left+s.scrollLeft,u=c.right+s.scrollLeft;o===e&&d===t&&u===n&&l.left===r&&l.right===i||(e=o,t=d,n=u,r=l.left,i=l.right,nE(o,c,l))}}var iu=[{id:"light",label:"Light",mode:"light"},{id:"dark",label:"Dark",mode:"dark"}],zv="codemem-theme";function Wv(e){const t=iu.find(r=>r.id===e);if(t)return t;const n=e.startsWith("dark")?"dark":"light";return iu.find(r=>r.id===n)||iu[0]}function ou(){const e=localStorage.getItem(zv);return e?Wv(e).id:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Jv(e){const t=Wv(e);document.documentElement.setAttribute("data-theme",t.mode),document.documentElement.setAttribute("data-color-mode",t.mode),t.id===t.mode?document.documentElement.removeAttribute("data-theme-variant"):document.documentElement.setAttribute("data-theme-variant",t.id),localStorage.setItem(zv,t.id)}function iE(e){if(!e)return;const t=n=>{const r=n==="dark"?"sun":"moon",i=n==="dark"?"Switch to light theme":"Switch to dark theme";e.setAttribute("aria-label",i),e.textContent="";const o=document.createElement("i");o.setAttribute("data-lucide",r),o.setAttribute("aria-hidden","true"),e.appendChild(o),globalThis.lucide?.createIcons?.()};t(ou()==="dark"?"dark":"light"),e.addEventListener("click",()=>{const n=ou()==="dark"?"light":"dark";Jv(n),t(n)})}var oE=Object.defineProperty,aE=(e,t)=>oE(e,"name",{value:t,configurable:!0}),sE=Cr(void 0);function $i(e){const t=kn(sE);return e||t||"ltr"}aE($i,"useDirection");var cE=Object.defineProperty,au=(e,t)=>cE(e,"name",{value:t,configurable:!0}),su=!1;function Yv(){const[e,t]=x(su);return V(()=>{su||(su=!0,t(!0))},[]),e}au(Yv,"useIsHydrated");var Xv=gi[" useSyncExternalStore ".trim().toString()];function Qv(){return()=>{}}au(Qv,"subscribe");function Zv(){return Xv(Qv,()=>!0,()=>!1)}au(Zv,"useIsHydratedModern");var lE=typeof Xv=="function"?Zv:Yv,dE=Object.defineProperty,Lr=(e,t)=>dE(e,"name",{value:t,configurable:!0}),cu="rovingFocusGroup.onEntryFocus",uE={bubbles:!1,cancelable:!0},Ms="RovingFocusGroup",[lu,ey,pE]=Fo(Ms),[fE,Oi]=dt(Ms,[pE]),[mE,hE]=fE(Ms),gE=J(Lr(function(t,n){return a(lu.Provider,{scope:t.__scopeRovingFocusGroup,children:a(lu.Slot,{scope:t.__scopeRovingFocusGroup,children:a(vE,{...t,ref:n})})})},"RovingFocusGroup")),vE=J(Lr(function(t,n){const{__scopeRovingFocusGroup:r,orientation:i,loop:o=!1,dir:s,currentTabStopId:c,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:d,onEntryFocus:u,preventScrollOnEntryFocus:p=!1,...f}=t,m=B(null),v=Re(n,m),g=$i(s),[h,b]=At({prop:c,defaultProp:l??null,onChange:d,caller:Ms}),[w,_]=x(!1),R=ht(u),I=ey(r),T=B(!1),[A,O]=x(0);return V(()=>{const F=m.current;if(F)return F.addEventListener(cu,R),()=>F.removeEventListener(cu,R)},[R]),a(mE,{scope:r,orientation:i,dir:g,loop:o,currentTabStopId:h,onItemFocus:ae(F=>b(F),[b]),onItemShiftTab:ae(()=>_(!0),[]),onFocusableItemAdd:ae(()=>O(F=>F+1),[]),onFocusableItemRemove:ae(()=>O(F=>F-1),[]),children:a(ye.div,{tabIndex:w||A===0?-1:0,"data-orientation":i,...f,ref:v,style:{outline:"none",...t.style},onMouseDown:te(t.onMouseDown,()=>{T.current=!0}),onFocus:te(t.onFocus,F=>{const N=!T.current;if(F.target===F.currentTarget&&N&&!w){const L=new CustomEvent(cu,uE);if(F.currentTarget.dispatchEvent(L),!L.defaultPrevented){const D=I().filter(G=>G.focusable);du([D.find(G=>G.active),D.find(G=>G.id===h),...D].filter(Boolean).map(G=>G.ref.current),p)}}T.current=!1}),onBlur:te(t.onBlur,()=>_(!1))})})},"RovingFocusGroupImpl")),yE="RovingFocusGroupItem",bE=J(Lr(function(t,n){const{__scopeRovingFocusGroup:r,focusable:i=!0,active:o=!1,tabStopId:s,children:c,...l}=t,d=Et(),u=s||d,p=hE(yE,r),f=p.currentTabStopId===u,m=ey(r),{onFocusableItemAdd:v,onFocusableItemRemove:g,currentTabStopId:h}=p,b=lE();return Ze(()=>{if(!(!b||!i))return v(),()=>g()},[b,i,v,g]),V(()=>{if(!(b||!i))return v(),()=>g()},[b,i,v,g]),a(lu.ItemSlot,{scope:r,id:u,focusable:i,active:o,children:a(ye.span,{tabIndex:f?0:-1,"data-orientation":p.orientation,...l,ref:n,onMouseDown:te(t.onMouseDown,w=>{i?p.onItemFocus(u):w.preventDefault()}),onFocus:te(t.onFocus,()=>p.onItemFocus(u)),onKeyDown:te(t.onKeyDown,w=>{if(w.key==="Tab"&&w.shiftKey){p.onItemShiftTab();return}if(w.target!==w.currentTarget)return;const _=ny(w,p.orientation,p.dir);if(_!==void 0){if(w.metaKey||w.ctrlKey||w.altKey||w.shiftKey)return;w.preventDefault();let R=m().filter(I=>I.focusable).map(I=>I.ref.current);if(_==="last")R.reverse();else if(_==="prev"||_==="next"){_==="prev"&&R.reverse();const I=R.indexOf(w.currentTarget);R=p.loop?ry(R,I+1):R.slice(I+1)}setTimeout(()=>du(R))}}),children:typeof c=="function"?c({isCurrentTabStop:f,hasTabStop:h!=null}):c})})},"RovingFocusGroupItem")),_E={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function ty(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}Lr(ty,"getDirectionAwareKey");function ny(e,t,n){const r=ty(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return _E[r]}Lr(ny,"getFocusIntent");function du(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}Lr(du,"focusFirst");function ry(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Lr(ry,"wrapArray");var uu=gE,pu=bE,wE=Object.defineProperty,ji=(e,t)=>wE(e,"name",{value:t,configurable:!0}),fu="Tabs",[SE,G2]=dt(fu,[Oi]),iy=Oi(),[CE,mu]=SE(fu),RE=J(ji(function(t,n){const{__scopeTabs:r,value:i,onValueChange:o,defaultValue:s,orientation:c="horizontal",dir:l,activationMode:d="automatic",...u}=t,p=$i(l),[f,m]=At({prop:i,onChange:o,defaultProp:s??"",caller:fu});return a(CE,{scope:r,baseId:Et(),value:f,onValueChange:m,orientation:c,dir:p,activationMode:d,children:a(ye.div,{dir:p,"data-orientation":c,...u,ref:n})})},"Tabs")),IE="TabsList",kE=J(ji(function(t,n){const{__scopeTabs:r,loop:i=!0,...o}=t,s=mu(IE,r),c=iy(r);return a(uu,{asChild:!0,...c,orientation:s.orientation,dir:s.dir,loop:i,children:a(ye.div,{role:"tablist","aria-orientation":s.orientation,...o,ref:n})})},"TabsList")),TE="TabsTrigger",PE=J(ji(function(t,n){const{__scopeTabs:r,value:i,disabled:o=!1,...s}=t,c=mu(TE,r),l=iy(r),d=hu(c.baseId,i),u=gu(c.baseId,i),p=i===c.value;return a(pu,{asChild:!0,...l,focusable:!o,active:p,children:a(ye.button,{type:"button",role:"tab","aria-selected":p,"aria-controls":u,"data-state":p?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:d,...s,ref:n,onMouseDown:te(t.onMouseDown,f=>{!o&&f.button===0&&f.ctrlKey===!1?c.onValueChange(i):f.preventDefault()}),onKeyDown:te(t.onKeyDown,f=>{o||f.target!==f.currentTarget||[" ","Enter"].includes(f.key)&&c.onValueChange(i)}),onFocus:te(t.onFocus,()=>{const f=c.activationMode!=="manual";!p&&!o&&f&&c.onValueChange(i)})})})},"TabsTrigger")),NE="TabsContent",EE=J(ji(function(t,n){const{__scopeTabs:r,value:i,forceMount:o,children:s,...c}=t,l=mu(NE,r),d=hu(l.baseId,i),u=gu(l.baseId,i),p=i===l.value,f=B(p);return V(()=>{const m=requestAnimationFrame(()=>f.current=!1);return()=>cancelAnimationFrame(m)},[]),a(kt,{present:o||p,children:({present:m})=>a(ye.div,{"data-state":p?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":d,hidden:!m,id:u,tabIndex:0,...c,ref:n,style:{...t.style,animationDuration:f.current?"0s":void 0},children:m&&s})})},"TabsContent"));function hu(e,t){return`${e}-trigger-${t}`}ji(hu,"makeTriggerId");function gu(e,t){return`${e}-content-${t}`}ji(gu,"makeContentId");var AE=RE,xE=kE,DE=PE,LE=EE;function oy({ariaLabel:e,children:t,listClassName:n,onValueChange:r,tabs:i,triggerClassName:o,value:s}){return a(AE,{onValueChange:r,value:s,children:[a(xE,{"aria-label":e,className:n,children:i.map(c=>a(DE,{className:o,disabled:c.disabled,value:c.value,children:c.label},c.value))}),t]})}function $r({children:e,className:t,forceMount:n=!1,value:r}){return a(LE,{className:t,forceMount:n?!0:void 0,value:r,children:e})}function Te(e){return a("input",{...e})}function Fs(){return{aliases:new Map,duplicateDisplayNames:new Map,reservedDisplayNames:new Set}}function ay(e,t=Fs()){for(const o of e){const s=String(o.display_name||"").trim();s&&t.reservedDisplayNames.add(s)}for(const[o,s]of t.aliases)t.reservedDisplayNames.has(s)&&t.aliases.delete(o);const n=new Set([...t.reservedDisplayNames,...t.aliases.values()]),r=e.filter(o=>!String(o.display_name||"").trim()).map(o=>String(o.device_id||"").trim()).filter(Boolean).sort((o,s)=>o.localeCompare(s));let i=Math.max(0,...[...t.aliases.values()].map(o=>{const s=/^Unnamed device (\d+)$/.exec(o);return s?Number(s[1]):0}));for(const o of r){if(t.aliases.has(o))continue;let s;do i+=1,s=`Unnamed device ${i}`;while(n.has(s));t.aliases.set(o,s),n.add(s)}return t.aliases}function Bs(e,t=Fs()){const n=ay(e,t),r=new Map,i=new Map,o=new Map,s=new Set;for(const l of e){const d=String(l.device_id||"").trim(),u=String(l.display_name||"").trim();if(!d)continue;if(!u){r.set(d,n.get(d)||"Unnamed device");continue}o.set(d,u),s.add(u);const p=i.get(u)??[];p.push(d),i.set(u,p)}for(const[l,d]of t.duplicateDisplayNames){const u=o.get(l);(u&&u!==d.sourceName||s.has(d.displayName))&&t.duplicateDisplayNames.delete(l)}const c=new Set([...s,...[...t.duplicateDisplayNames.values()].map(l=>l.displayName)]);for(const[l,d]of i)for(const u of d.sort((p,f)=>p.localeCompare(f))){const p=t.duplicateDisplayNames.get(u);if(p?.sourceName===l){r.set(u,p.displayName);continue}if(d.length===1){r.set(u,l);continue}let f=0,m;do f+=1,m=`${l} · Device ${f}`;while(c.has(m));r.set(u,m),t.duplicateDisplayNames.set(u,{displayName:m,sourceName:l}),c.add(m)}return r}function $E(e,t,n=""){const r=String(e.device_id||"").trim(),i=String(e.group_id||t||"").trim(),o=n||String(e.display_name||"").trim()||"Unnamed device",s=e.enabled!==!1&&e.enabled!==0,c=[`Device ID ${r||"unknown"}`];return i&&c.push(`Group ID ${i}`),{advancedDetail:`Advanced: ${c.join(" · ")}`,deviceId:r,displayName:o,statusLabel:s?"Enabled in this coordinator group":"Disabled in this coordinator group",teamId:i}}var sy={status:"coordinator status",groups:"coordinator groups",joinRequests:"join requests",devices:"devices"};function qs(){return{availability:"unknown",retrying:!1}}function OE(){return{status:qs(),groups:qs(),joinRequests:qs(),devices:qs()}}function Vo(e,t){e[t]={...e[t],retrying:!0}}function vu(e,t){e[t]={...e[t],retrying:!1}}function Us(e,t){e[t]={availability:"fresh",retrying:!1}}function un(e,t,n){e[t]={availability:n??(e[t].availability==="fresh"||e[t].availability==="stale")?"stale":"unavailable",retrying:!1}}function yu(e,t){e[t]={availability:"not_applicable",retrying:!1}}function Or(e,t){return e[t].availability==="fresh"||e[t].availability==="stale"}function xn(e,...t){return t.every(n=>e[n].availability==="fresh"&&!e[n].retrying)}function Mi(e,t){return e[t].availability==="not_applicable"}function bu(e){const t=Object.entries(e),n=t.filter(([,i])=>i.availability==="stale").map(([i])=>sy[i]),r=t.filter(([,i])=>i.availability==="unavailable").map(([i])=>sy[i]);return n.length===0&&r.length===0?null:{stale:n,unavailable:r,retrying:t.some(([,i])=>i.retrying)}}var jE="codemem-coordinator-admin-target-group",P={recovery:OE(),loadGeneration:0,recoveryAnnouncement:"",recoveryFocusPending:!1,recoveryRetryRequested:!1,activeSection:"groups",inviteGroup:"",inviteTtlHours:"24",invitePolicy:"auto_admit",invitePending:!1,showArchivedGroups:!1,createGroupId:"",createGroupDisplayName:"",groupActionPendingId:"",groupActionPendingKind:"",joinReviewPendingId:"",joinReviewPendingAction:"",deviceActionPendingId:"",deviceActionPendingKind:"",joinRequestsSnapshotTarget:null,devicesSnapshotTarget:null,groupRenameDrafts:new Map,groupPresentationAliases:new Map,deviceRenameDrafts:new Map,deviceRenameServerNames:new Map,unnamedDeviceAliases:Fs(),groupPreferencesOpen:new Set,groupPreferencesDrafts:new Map,groupScopeManagementOpen:new Set,groupScopeManagementDrafts:new Map,teamSetupGuide:null,availableProjects:[]};function cy(){return P.loadGeneration+=1,P.loadGeneration}function _u(e){return P.loadGeneration===e}function ME(e){const{summary:t,fresh:n,runDevice:r,snapshotMatchesTarget:i}=e,o=i&&Or(P.recovery,"devices"),s=Mi(P.recovery,"devices"),c=o&&Array.isArray(C.lastCoordinatorAdminDevices)?C.lastCoordinatorAdminDevices:[],l=Bs(c,P.unnamedDeviceAliases);return y($r,{className:"coordinator-admin-panel",value:"devices"},y("h3",null,"Enrolled devices"),y("p",{class:"peer-submeta"},t.readiness==="ready"?"Rename, disable, re-enable, or remove devices from the selected coordinator group. Space transport access is managed below; policy Team membership and Project access stay in Sharing.":"Finish coordinator setup first. Device administration stays disabled until legacy administration is ready."),s?y("div",{class:"peer-meta"},"Complete legacy coordinator setup to load enrolled devices. No device data is expected yet."):o?c.length?y("div",{class:"peer-list"},c.map(d=>{const u=$E(d,String(C.lastCoordinatorAdminStatus?.active_group||""),l.get(String(d.device_id||"").trim())),{deviceId:p,displayName:f,teamId:m}=u,v=P.deviceActionPendingId===p,g=P.deviceRenameDrafts.get(p)??String(d.display_name||""),h=d.enabled!==!1&&d.enabled!==0,b=!n||!p||v;return y("div",{class:"peer-card peer-card--padded",key:p||String(d.fingerprint||"unknown")},y("div",{class:"peer-title"},y("strong",null,f)),y("div",{class:"peer-submeta"},u.statusLabel),y("details",{class:"coordinator-admin-diagnostics"},y("summary",null,"Diagnostics"),y("div",{class:"peer-meta"},u.advancedDetail)),y("form",{class:"coordinator-admin-form",onSubmit:w=>{w.preventDefault(),!b&&r(p,m,f,"rename")}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"Display name"),y(Te,{class:"peer-scope-input",disabled:!n||v,onInput:w=>{P.deviceRenameDrafts.set(p,String(w.currentTarget.value||""))},type:"text",value:g}))),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:b,type:"submit"},v&&P.deviceActionPendingKind==="rename"?"Renaming…":"Rename"),h?y("button",{class:"settings-button danger",disabled:b,onClick:()=>r(p,m,f,"disable"),type:"button"},v&&P.deviceActionPendingKind==="disable"?"Disabling…":"Disable"):y("button",{class:"settings-button",disabled:b,onClick:()=>r(p,m,f,"enable"),type:"button"},v&&P.deviceActionPendingKind==="enable"?"Enabling…":"Enable"),y("button",{class:"settings-button danger",disabled:b,onClick:()=>r(p,m,f,"remove"),type:"button"},v&&P.deviceActionPendingKind==="remove"?"Removing…":"Remove"))))})):y("div",{class:"peer-meta"},t.readiness==="ready"?"No enrolled devices found for the active coordinator group.":"Device administration will appear here once setup is complete."):y("div",{class:"peer-meta"},"Enrolled devices are unavailable. Retry to load current devices; no empty result is being assumed."))}var FE=Object.defineProperty,Ko=(e,t)=>FE(e,"name",{value:t,configurable:!0}),wu="Collapsible",[BE,H2]=dt(wu),[qE,Su]=BE(wu),UE=J(Ko(function(t,n){const{__scopeCollapsible:r,open:i,defaultOpen:o,disabled:s,onOpenChange:c,...l}=t,[d,u]=At({prop:i,defaultProp:o??!1,onChange:c,caller:wu});return a(qE,{scope:r,disabled:s,contentId:Et(),open:d,onOpenToggle:ae(()=>u(p=>!p),[u]),children:a(ye.div,{"data-state":Gs(d),"data-disabled":s?"":void 0,...l,ref:n})})},"Collapsible")),GE="CollapsibleTrigger",HE=J(Ko(function(t,n){const{__scopeCollapsible:r,...i}=t,o=Su(GE,r);return a(ye.button,{type:"button","aria-controls":o.open?o.contentId:void 0,"aria-expanded":o.open||!1,"data-state":Gs(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...i,ref:n,onClick:te(t.onClick,o.onOpenToggle)})},"CollapsibleTrigger")),ly="CollapsibleContent",VE=J(Ko(function(t,n){const{forceMount:r,...i}=t,o=Su(ly,t.__scopeCollapsible);return a(kt,{present:r||o.open,children:({present:s})=>a(KE,{...i,ref:n,present:s})})},"CollapsibleContent")),KE=J(Ko(function(t,n){const{__scopeCollapsible:r,present:i,children:o,...s}=t,c=Su(ly,r),[l,d]=x(i),u=B(null),p=Re(n,u),f=B(0),m=f.current,v=B(0),g=v.current,h=c.open||l,b=B(h),w=B(void 0);return V(()=>{const _=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(_)},[]),Ze(()=>{const _=u.current;if(_){w.current=w.current||{transitionDuration:_.style.transitionDuration,animationName:_.style.animationName},_.style.transitionDuration="0s",_.style.animationName="none";const R=_.getBoundingClientRect();f.current=R.height,v.current=R.width,b.current||(_.style.transitionDuration=w.current.transitionDuration,_.style.animationName=w.current.animationName),d(i)}},[c.open,i]),a(ye.div,{"data-state":Gs(c.open),"data-disabled":c.disabled?"":void 0,id:c.contentId,hidden:!h,...s,ref:p,style:{"--radix-collapsible-content-height":m?`${m}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...t.style},children:h&&o})},"CollapsibleContentImpl"));function Gs(e){return e?"open":"closed"}Ko(Gs,"getState");var zo=UE,Cu=HE,Wo=VE,zE=["top","right","bottom","left"],Zn=Math.min,Dt=Math.max,Hs=Math.round,Vs=Math.floor,pn=e=>({x:e,y:e}),WE={left:"right",right:"left",bottom:"top",top:"bottom"};function Ru(e,t,n){return Dt(e,Zn(t,n))}function Dn(e,t){return typeof e=="function"?e(t):e}function Ln(e){return e.split("-")[0]}function Fi(e){return e.split("-")[1]}function Iu(e){return e==="x"?"y":"x"}function ku(e){return e==="y"?"height":"width"}function fn(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function Tu(e){return Iu(fn(e))}function JE(e,t,n){n===void 0&&(n=!1);const r=Fi(e),i=Tu(e),o=ku(i);let s=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(s=Ks(s)),[s,Ks(s)]}function YE(e){const t=Ks(e);return[Pu(e),t,Pu(t)]}function Pu(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}var dy=["left","right"],uy=["right","left"],XE=["top","bottom"],QE=["bottom","top"];function ZE(e,t,n){switch(e){case"top":case"bottom":return n?t?uy:dy:t?dy:uy;case"left":case"right":return t?XE:QE;default:return[]}}function eA(e,t,n,r){const i=Fi(e);let o=ZE(Ln(e),n==="start",r);return i&&(o=o.map(s=>s+"-"+i),t&&(o=o.concat(o.map(Pu)))),o}function Ks(e){const t=Ln(e);return WE[t]+e.slice(t.length)}function tA(e){return{top:0,right:0,bottom:0,left:0,...e}}function py(e){return typeof e!="number"?tA(e):{top:e,right:e,bottom:e,left:e}}function zs(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function fy(e,t,n){let{reference:r,floating:i}=e;const o=fn(t),s=Tu(t),c=ku(s),l=Ln(t),d=o==="y",u=r.x+r.width/2-i.width/2,p=r.y+r.height/2-i.height/2,f=r[c]/2-i[c]/2;let m;switch(l){case"top":m={x:u,y:r.y-i.height};break;case"bottom":m={x:u,y:r.y+r.height};break;case"right":m={x:r.x+r.width,y:p};break;case"left":m={x:r.x-i.width,y:p};break;default:m={x:r.x,y:r.y}}switch(Fi(t)){case"start":m[s]-=f*(n&&d?-1:1);break;case"end":m[s]+=f*(n&&d?-1:1)}return m}async function nA(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:o,rects:s,elements:c,strategy:l}=e,{boundary:d="clippingAncestors",rootBoundary:u="viewport",elementContext:p="floating",altBoundary:f=!1,padding:m=0}=Dn(t,e),v=py(m),g=c[f?p==="floating"?"reference":"floating":p],h=zs(await o.getClippingRect({element:(n=await(o.isElement==null?void 0:o.isElement(g)))==null||n?g:g.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(c.floating)),boundary:d,rootBoundary:u,strategy:l})),b=p==="floating"?{x:r,y:i,width:s.floating.width,height:s.floating.height}:s.reference,w=await(o.getOffsetParent==null?void 0:o.getOffsetParent(c.floating)),_=await(o.isElement==null?void 0:o.isElement(w))?await(o.getScale==null?void 0:o.getScale(w))||{x:1,y:1}:{x:1,y:1},R=zs(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:b,offsetParent:w,strategy:l}):b);return{top:(h.top-R.top+v.top)/_.y,bottom:(R.bottom-h.bottom+v.bottom)/_.y,left:(h.left-R.left+v.left)/_.x,right:(R.right-h.right+v.right)/_.x}}var rA=50,iA=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:s}=n,c=s.detectOverflow?s:{...s,detectOverflow:nA},l=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:p}=fy(d,r,l),f=r,m=0;const v={};for(let g=0;g<o.length;g++){const h=o[g];if(!h)continue;const{name:b,fn:w}=h,{x:_,y:R,data:I,reset:T}=await w({x:u,y:p,initialPlacement:r,placement:f,strategy:i,middlewareData:v,rects:d,platform:c,elements:{reference:e,floating:t}});u=_??u,p=R??p,v[b]={...v[b],...I},T&&m<rA&&(m++,typeof T=="object"&&(T.placement&&(f=T.placement),T.rects&&(d=T.rects===!0?await s.getElementRects({reference:e,floating:t,strategy:i}):T.rects),{x:u,y:p}=fy(d,f,l)),g=-1)}return{x:u,y:p,placement:f,strategy:i,middlewareData:v}},oA=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:o,platform:s,elements:c,middlewareData:l}=t,{element:d,padding:u=0}=Dn(e,t)||{};if(d==null)return{};const p=py(u),f={x:n,y:r},m=Tu(i),v=ku(m),g=await s.getDimensions(d),h=m==="y",b=h?"top":"left",w=h?"bottom":"right",_=h?"clientHeight":"clientWidth",R=o.reference[v]+o.reference[m]-f[m]-o.floating[v],I=f[m]-o.reference[m],T=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=T?T[_]:0;(!A||!await(s.isElement==null?void 0:s.isElement(T)))&&(A=c.floating[_]||o.floating[v]);const O=R/2-I/2,F=A/2-g[v]/2-1,N=Zn(p[b],F),L=Zn(p[w],F),D=N,G=A-g[v]-L,q=A/2-g[v]/2+O,$=Ru(D,q,G),E=!l.arrow&&Fi(i)!=null&&q!==$&&o.reference[v]/2-(q<D?N:L)-g[v]/2<0,S=E?q<D?q-D:q-G:0;return{[m]:f[m]+S,data:{[m]:$,centerOffset:q-$-S,...E&&{alignmentOffset:S}},reset:E}}}),aA=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:o,rects:s,initialPlacement:c,platform:l,elements:d}=t,{mainAxis:u=!0,crossAxis:p=!0,fallbackPlacements:f,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:v="none",flipAlignment:g=!0,...h}=Dn(e,t);if((n=o.arrow)!=null&&n.alignmentOffset)return{};const b=Ln(i),w=fn(c),_=Ln(c)===c,R=await(l.isRTL==null?void 0:l.isRTL(d.floating)),I=f||(_||!g?[Ks(c)]:YE(c)),T=v!=="none";!f&&T&&I.push(...eA(c,g,v,R));const A=[c,...I],O=await l.detectOverflow(t,h),F=[];let N=((r=o.flip)==null?void 0:r.overflows)||[];if(u&&F.push(O[b]),p){const q=JE(i,s,R);F.push(O[q[0]],O[q[1]])}if(N=[...N,{placement:i,overflows:F}],!F.every(q=>q<=0)){var L,D;const q=(((L=o.flip)==null?void 0:L.index)||0)+1,$=A[q];if($&&(!(p==="alignment"&&w!==fn($))||N.every(S=>fn(S.placement)===w?S.overflows[0]>0:!0)))return{data:{index:q,overflows:N},reset:{placement:$}};let E=(D=N.filter(S=>S.overflows[0]<=0).sort((S,M)=>S.overflows[1]-M.overflows[1])[0])==null?void 0:D.placement;if(!E)switch(m){case"bestFit":{var G;const S=(G=N.filter(M=>{if(T){const H=fn(M.placement);return H===w||H==="y"}return!0}).map(M=>[M.placement,M.overflows.filter(H=>H>0).reduce((H,U)=>H+U,0)]).sort((M,H)=>M[1]-H[1])[0])==null?void 0:G[0];S&&(E=S);break}case"initialPlacement":E=c}if(i!==E)return{reset:{placement:E}}}return{}}}};function my(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function hy(e){return zE.some(t=>e[t]>=0)}var sA=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...o}=Dn(e,t);switch(i){case"referenceHidden":{const s=my(await r.detectOverflow(t,{...o,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:hy(s)}}}case"escaped":{const s=my(await r.detectOverflow(t,{...o,altBoundary:!0}),n.floating);return{data:{escapedOffsets:s,escaped:hy(s)}}}default:return{}}}}},gy=new Set(["left","top"]);async function cA(e,t){const{placement:n,platform:r,elements:i}=e,o=await(r.isRTL==null?void 0:r.isRTL(i.floating)),s=Ln(n),c=Fi(n),l=fn(n)==="y",d=gy.has(s)?-1:1,u=o&&l?-1:1,p=Dn(t,e);let{mainAxis:f,crossAxis:m,alignmentAxis:v}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return c&&typeof v=="number"&&(m=c==="end"?v*-1:v),l?{x:m*u,y:f*d}:{x:f*d,y:m*u}}var lA=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:o,placement:s,middlewareData:c}=t,l=await cA(t,e);return s===((n=c.offset)==null?void 0:n.placement)&&(r=c.arrow)!=null&&r.alignmentOffset?{}:{x:i+l.x,y:o+l.y,data:{...l,placement:s}}}}},dA=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:s=!0,crossAxis:c=!1,limiter:l={fn:b=>{let{x:w,y:_}=b;return{x:w,y:_}}},...d}=Dn(e,t),u={x:n,y:r},p=await o.detectOverflow(t,d),f=fn(Ln(i)),m=Iu(f);let v=u[m],g=u[f];if(s){const b=m==="y"?"top":"left",w=m==="y"?"bottom":"right",_=v+p[b],R=v-p[w];v=Ru(_,v,R)}if(c){const b=f==="y"?"top":"left",w=f==="y"?"bottom":"right",_=g+p[b],R=g-p[w];g=Ru(_,g,R)}const h=l.fn({...t,[m]:v,[f]:g});return{...h,data:{x:h.x-n,y:h.y-r,enabled:{[m]:s,[f]:c}}}}}},uA=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:i,rects:o,middlewareData:s}=t,{offset:c=0,mainAxis:l=!0,crossAxis:d=!0}=Dn(e,t),u={x:n,y:r},p=fn(i),f=Iu(p);let m=u[f],v=u[p];const g=Dn(c,t),h=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(l){const _=f==="y"?"height":"width",R=o.reference[f]-o.floating[_]+h.mainAxis,I=o.reference[f]+o.reference[_]-h.mainAxis;m<R?m=R:m>I&&(m=I)}if(d){var b,w;const _=f==="y"?"width":"height",R=gy.has(Ln(i)),I=o.reference[p]-o.floating[_]+(R&&((b=s.offset)==null?void 0:b[p])||0)+(R?0:h.crossAxis),T=o.reference[p]+o.reference[_]+(R?0:((w=s.offset)==null?void 0:w[p])||0)-(R?h.crossAxis:0);v<I?v=I:v>T&&(v=T)}return{[f]:m,[p]:v}}}},pA=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:i,rects:o,platform:s,elements:c}=t,{apply:l=()=>{},...d}=Dn(e,t),u=await s.detectOverflow(t,d),p=Ln(i),f=Fi(i),m=fn(i)==="y",{width:v,height:g}=o.floating;let h,b;p==="top"||p==="bottom"?(h=p,b=f===(await(s.isRTL==null?void 0:s.isRTL(c.floating))?"start":"end")?"left":"right"):(b=p,h=f==="end"?"top":"bottom");const w=g-u.top-u.bottom,_=v-u.left-u.right,R=Zn(g-u[h],w),I=Zn(v-u[b],_),T=!t.middlewareData.shift;let A=R,O=I;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(O=_),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(A=w),T&&!f){const N=Dt(u.left,0),L=Dt(u.right,0),D=Dt(u.top,0),G=Dt(u.bottom,0);m?O=v-2*(N!==0||L!==0?N+L:Dt(u.left,u.right)):A=g-2*(D!==0||G!==0?D+G:Dt(u.top,u.bottom))}await l({...t,availableWidth:O,availableHeight:A});const F=await s.getDimensions(c.floating);return v!==F.width||g!==F.height?{reset:{rects:!0}}:{}}}};function Ws(){return typeof window<"u"}function Bi(e){return vy(e)?(e.nodeName||"").toLowerCase():"#document"}function Lt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function mn(e){var t;return(t=(vy(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function vy(e){return Ws()?e instanceof Node||e instanceof Lt(e).Node:!1}function Yt(e){return Ws()?e instanceof Element||e instanceof Lt(e).Element:!1}function $n(e){return Ws()?e instanceof HTMLElement||e instanceof Lt(e).HTMLElement:!1}function yy(e){return!Ws()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Lt(e).ShadowRoot}function Jo(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Xt(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function fA(e){return/^(table|td|th)$/.test(Bi(e))}function Js(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}var mA=/transform|translate|scale|rotate|perspective|filter/,hA=/paint|layout|strict|content/,jr=e=>!!e&&e!=="none",Nu;function Eu(e){const t=Yt(e)?Xt(e):e;return jr(t.transform)||jr(t.translate)||jr(t.scale)||jr(t.rotate)||jr(t.perspective)||!Au()&&(jr(t.backdropFilter)||jr(t.filter))||mA.test(t.willChange||"")||hA.test(t.contain||"")}function gA(e){let t=er(e);for(;$n(t)&&!qi(t);){if(Eu(t))return t;if(Js(t))return null;t=er(t)}return null}function Au(){return Nu==null&&(Nu=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Nu}function qi(e){return/^(html|body|#document)$/.test(Bi(e))}function Xt(e){return Lt(e).getComputedStyle(e)}function Ys(e){return Yt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function er(e){if(Bi(e)==="html")return e;const t=e.assignedSlot||e.parentNode||yy(e)&&e.host||mn(e);return yy(t)?t.host:t}function by(e){const t=er(e);return qi(t)?e.ownerDocument?e.ownerDocument.body:e.body:$n(t)&&Jo(t)?t:by(t)}function Yo(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=by(e),o=i===((r=e.ownerDocument)==null?void 0:r.body),s=Lt(i);if(o){const c=xu(s);return t.concat(s,s.visualViewport||[],Jo(i)?i:[],c&&n?Yo(c):[])}else return t.concat(i,Yo(i,[],n))}function xu(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function _y(e){const t=Xt(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=$n(e),o=i?e.offsetWidth:n,s=i?e.offsetHeight:r,c=Hs(n)!==o||Hs(r)!==s;return c&&(n=o,r=s),{width:n,height:r,$:c}}function Du(e){return Yt(e)?e:e.contextElement}function Ui(e){const t=Du(e);if(!$n(t))return pn(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=_y(t);let s=(o?Hs(n.width):n.width)/r,c=(o?Hs(n.height):n.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!c||!Number.isFinite(c))&&(c=1),{x:s,y:c}}var vA=pn(0);function wy(e){const t=Lt(e);return!Au()||!t.visualViewport?vA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function yA(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Lt(e)?!1:t}function Mr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),o=Du(e);let s=pn(1);t&&(r?Yt(r)&&(s=Ui(r)):s=Ui(e));const c=yA(o,n,r)?wy(o):pn(0);let l=(i.left+c.x)/s.x,d=(i.top+c.y)/s.y,u=i.width/s.x,p=i.height/s.y;if(o){const f=Lt(o),m=r&&Yt(r)?Lt(r):r;let v=f,g=xu(v);for(;g&&r&&m!==v;){const h=Ui(g),b=g.getBoundingClientRect(),w=Xt(g),_=b.left+(g.clientLeft+parseFloat(w.paddingLeft))*h.x,R=b.top+(g.clientTop+parseFloat(w.paddingTop))*h.y;l*=h.x,d*=h.y,u*=h.x,p*=h.y,l+=_,d+=R,v=Lt(g),g=xu(v)}}return zs({width:u,height:p,x:l,y:d})}function Xs(e,t){const n=Ys(e).scrollLeft;return t?t.left+n:Mr(mn(e)).left+n}function Sy(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Xs(e,n),y:n.top+t.scrollTop}}function bA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o=i==="fixed",s=mn(r),c=t?Js(t.floating):!1;if(r===s||c&&o)return n;let l={scrollLeft:0,scrollTop:0},d=pn(1);const u=pn(0),p=$n(r);if((p||!p&&!o)&&((Bi(r)!=="body"||Jo(s))&&(l=Ys(r)),p)){const m=Mr(r);d=Ui(r),u.x=m.x+r.clientLeft,u.y=m.y+r.clientTop}const f=s&&!p&&!o?Sy(s,l):pn(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-l.scrollLeft*d.x+u.x+f.x,y:n.y*d.y-l.scrollTop*d.y+u.y+f.y}}function _A(e){return Array.from(e.getClientRects())}function wA(e){const t=mn(e),n=Ys(e),r=e.ownerDocument.body,i=Dt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),o=Dt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+Xs(e);const c=-n.scrollTop;return Xt(r).direction==="rtl"&&(s+=Dt(t.clientWidth,r.clientWidth)-i),{width:i,height:o,x:s,y:c}}var Cy=25;function SA(e,t){const n=Lt(e),r=mn(e),i=n.visualViewport;let o=r.clientWidth,s=r.clientHeight,c=0,l=0;if(i){o=i.width,s=i.height;const u=Au();(!u||u&&t==="fixed")&&(c=i.offsetLeft,l=i.offsetTop)}const d=Xs(r);if(d<=0){const u=r.ownerDocument,p=u.body,f=getComputedStyle(p),m=u.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,v=Math.abs(r.clientWidth-p.clientWidth-m);v<=Cy&&(o-=v)}else d<=Cy&&(o+=d);return{width:o,height:s,x:c,y:l}}function CA(e,t){const n=Mr(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=$n(e)?Ui(e):pn(1);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}function Ry(e,t,n){let r;if(t==="viewport")r=SA(e,n);else if(t==="document")r=wA(mn(e));else if(Yt(t))r=CA(t,n);else{const i=wy(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return zs(r)}function Iy(e,t){const n=er(e);return n===t||!Yt(n)||qi(n)?!1:Xt(n).position==="fixed"||Iy(n,t)}function RA(e,t){const n=t.get(e);if(n)return n;let r=Yo(e,[],!1).filter(c=>Yt(c)&&Bi(c)!=="body"),i=null;const o=Xt(e).position==="fixed";let s=o?er(e):e;for(;Yt(s)&&!qi(s);){const c=Xt(s),l=Eu(s);!l&&c.position==="fixed"&&(i=null),(o?!l&&!i:!l&&c.position==="static"&&i&&(i.position==="absolute"||i.position==="fixed")||Jo(s)&&!l&&Iy(e,s))?r=r.filter(d=>d!==s):i=c,s=er(s)}return t.set(e,r),r}function IA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[...n==="clippingAncestors"?Js(t)?[]:RA(t,this._c):[].concat(n),r],s=Ry(t,o[0],i);let c=s.top,l=s.right,d=s.bottom,u=s.left;for(let p=1;p<o.length;p++){const f=Ry(t,o[p],i);c=Dt(f.top,c),l=Zn(f.right,l),d=Zn(f.bottom,d),u=Dt(f.left,u)}return{width:l-u,height:d-c,x:u,y:c}}function kA(e){const{width:t,height:n}=_y(e);return{width:t,height:n}}function TA(e,t,n){const r=$n(t),i=mn(t),o=n==="fixed",s=Mr(e,!0,o,t);let c={scrollLeft:0,scrollTop:0};const l=pn(0);function d(){l.x=Xs(i)}if(r||!r&&!o)if((Bi(t)!=="body"||Jo(i))&&(c=Ys(t)),r){const p=Mr(t,!0,o,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else i&&d();o&&!r&&i&&d();const u=i&&!r&&!o?Sy(i,c):pn(0);return{x:s.left+c.scrollLeft-l.x-u.x,y:s.top+c.scrollTop-l.y-u.y,width:s.width,height:s.height}}function Lu(e){return Xt(e).position==="static"}function ky(e,t){if(!$n(e)||Xt(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return mn(e)===n&&(n=n.ownerDocument.body),n}function Ty(e,t){const n=Lt(e);if(Js(e))return n;if(!$n(e)){let i=er(e);for(;i&&!qi(i);){if(Yt(i)&&!Lu(i))return i;i=er(i)}return n}let r=ky(e,t);for(;r&&fA(r)&&Lu(r);)r=ky(r,t);return r&&qi(r)&&Lu(r)&&!Eu(r)?n:r||gA(e)||n}var PA=async function(e){const t=this.getOffsetParent||Ty,n=this.getDimensions,r=await n(e.floating);return{reference:TA(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function NA(e){return Xt(e).direction==="rtl"}var EA={convertOffsetParentRelativeRectToViewportRelativeRect:bA,getDocumentElement:mn,getClippingRect:IA,getOffsetParent:Ty,getElementRects:PA,getClientRects:_A,getDimensions:kA,getScale:Ui,isElement:Yt,isRTL:NA};function Py(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function AA(e,t){let n=null,r;const i=mn(e);function o(){var c;clearTimeout(r),(c=n)==null||c.disconnect(),n=null}function s(c,l){c===void 0&&(c=!1),l===void 0&&(l=1),o();const d=e.getBoundingClientRect(),{left:u,top:p,width:f,height:m}=d;if(c||t(),!f||!m)return;const v=Vs(p),g=Vs(i.clientWidth-(u+f)),h=Vs(i.clientHeight-(p+m)),b=Vs(u),w={rootMargin:-v+"px "+-g+"px "+-h+"px "+-b+"px",threshold:Dt(0,Zn(1,l))||1};let _=!0;function R(I){const T=I[0].intersectionRatio;if(T!==l){if(!_)return s();T?s(!1,T):r=setTimeout(()=>{s(!1,1e-7)},1e3)}T===1&&!Py(d,e.getBoundingClientRect())&&s(),_=!1}try{n=new IntersectionObserver(R,{...w,root:i.ownerDocument})}catch{n=new IntersectionObserver(R,w)}n.observe(e)}return s(!0),o}function xA(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:c=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,d=Du(e),u=i||o?[...d?Yo(d):[],...t?Yo(t):[]]:[];u.forEach(b=>{i&&b.addEventListener("scroll",n,{passive:!0}),o&&b.addEventListener("resize",n)});const p=d&&c?AA(d,n):null;let f=-1,m=null;s&&(m=new ResizeObserver(b=>{let[w]=b;w&&w.target===d&&m&&t&&(m.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var _;(_=m)==null||_.observe(t)})),n()}),d&&!l&&m.observe(d),t&&m.observe(t));let v,g=l?Mr(e):null;l&&h();function h(){const b=Mr(e);g&&!Py(g,b)&&n(),g=b,v=requestAnimationFrame(h)}return n(),()=>{var b;u.forEach(w=>{i&&w.removeEventListener("scroll",n),o&&w.removeEventListener("resize",n)}),p?.(),(b=m)==null||b.disconnect(),m=null,l&&cancelAnimationFrame(v)}}var DA=lA,LA=dA,$A=aA,OA=pA,jA=sA,Ny=oA,MA=uA,FA=(e,t,n)=>{const r=new Map,i={platform:EA,...n},o={...i.platform,_c:r};return iA(e,t,{...i,platform:o})},Qs=typeof document<"u"?It:function(){};function Zs(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Zs(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const o=i[r];if(!(o==="_owner"&&e.$$typeof)&&!Zs(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function Ey(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Ay(e,t){const n=Ey(e);return Math.round(t*n)/n}function $u(e){const t=B(e);return Qs(()=>{t.current=e}),t}function BA(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:o,floating:s}={},transform:c=!0,whileElementsMounted:l,open:d}=e,[u,p]=x({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=x(r);Zs(f,r)||m(r);const[v,g]=x(null),[h,b]=x(null),w=ae(M=>{M!==T.current&&(T.current=M,g(M))},[]),_=ae(M=>{M!==A.current&&(A.current=M,b(M))},[]),R=o||v,I=s||h,T=B(null),A=B(null),O=B(u),F=l!=null,N=$u(l),L=$u(i),D=$u(d),G=ae(()=>{if(!T.current||!A.current)return;const M={placement:t,strategy:n,middleware:f};L.current&&(M.platform=L.current),FA(T.current,A.current,M).then(H=>{const U={...H,isPositioned:D.current!==!1};q.current&&!Zs(O.current,U)&&(O.current=U,rs(()=>{p(U)}))})},[f,t,n,L,D]);Qs(()=>{d===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,p(M=>({...M,isPositioned:!1})))},[d]);const q=B(!1);Qs(()=>(q.current=!0,()=>{q.current=!1}),[]),Qs(()=>{if(R&&(T.current=R),I&&(A.current=I),R&&I){if(N.current)return N.current(R,I,G);G()}},[R,I,G,N,F]);const $=ke(()=>({reference:T,floating:A,setReference:w,setFloating:_}),[w,_]),E=ke(()=>({reference:R,floating:I}),[R,I]),S=ke(()=>{const M={position:n,left:0,top:0};if(!E.floating)return M;const H=Ay(E.floating,u.x),U=Ay(E.floating,u.y);return c?{...M,transform:"translate("+H+"px, "+U+"px)",...Ey(E.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:H,top:U}},[n,c,E.floating,u.x,u.y]);return ke(()=>({...u,update:G,refs:$,elements:E,floatingStyles:S}),[u,G,$,E,S])}var qA=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Ny({element:r.current,padding:i}).fn(n):{}:r?Ny({element:r,padding:i}).fn(n):{}}}},UA=(e,t)=>{const n=DA(e);return{name:n.name,fn:n.fn,options:[e,t]}},GA=(e,t)=>{const n=LA(e);return{name:n.name,fn:n.fn,options:[e,t]}},HA=(e,t)=>({fn:MA(e).fn,options:[e,t]}),VA=(e,t)=>{const n=$A(e);return{name:n.name,fn:n.fn,options:[e,t]}},KA=(e,t)=>{const n=OA(e);return{name:n.name,fn:n.fn,options:[e,t]}},zA=(e,t)=>{const n=jA(e);return{name:n.name,fn:n.fn,options:[e,t]}},WA=(e,t)=>{const n=qA(e);return{name:n.name,fn:n.fn,options:[e,t]}},JA=Object.defineProperty,YA=(e,t)=>JA(e,"name",{value:t,configurable:!0}),XA=J(YA(function(t,n){const{children:r,width:i=10,height:o=5,...s}=t;return a(ye.svg,{...s,ref:n,width:i,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?r:a("polygon",{points:"0,0 30,0 15,10"})})},"Arrow")),QA=XA,ZA=Object.defineProperty,ex=(e,t)=>ZA(e,"name",{value:t,configurable:!0});function ec(e){const[t,n]=x(void 0);return Ze(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const o=i[0];let s,c;if("borderBoxSize"in o){const l=o.borderBoxSize,d=Array.isArray(l)?l[0]:l;s=d.inlineSize,c=d.blockSize}else s=e.offsetWidth,c=e.offsetHeight;n({width:s,height:c})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}ex(ec,"useSize");var tx=Object.defineProperty,On=(e,t)=>tx(e,"name",{value:t,configurable:!0}),xy="Popper",[Dy,tr]=dt(xy),[nx,Ly]=Dy(xy),rx=On(e=>{const{__scopePopper:t,children:n}=e,[r,i]=x(null),[o,s]=x(void 0);return a(nx,{scope:t,anchor:r,onAnchorChange:i,placementState:o,setPlacementState:s,children:n})},"Popper"),ix="PopperAnchor",ox=J(On(function(t,n){const{__scopePopper:r,virtualRef:i,...o}=t,s=Ly(ix,r),c=B(null),l=s.onAnchorChange,d=ae(g=>{c.current=g,g&&l(g)},[l]),u=Re(n,d),p=B(null);V(()=>{if(!i)return;const g=p.current;p.current=i.current,g!==p.current&&l(p.current)});const f=s.placementState&&tc(s.placementState),m=f?.[0],v=f?.[1];return i?null:a(ye.div,{"data-radix-popper-side":m,"data-radix-popper-align":v,...o,ref:u})},"PopperAnchor")),$y="PopperContent",[ax,sx]=Dy($y),cx=J(On(function(t,n){const{__scopePopper:r,side:i="bottom",sideOffset:o=0,align:s="center",alignOffset:c=0,arrowPadding:l=0,avoidCollisions:d=!0,collisionBoundary:u=[],collisionPadding:p=0,sticky:f="partial",hideWhenDetached:m=!1,updatePositionStrategy:v="optimized",onPlaced:g,...h}=t,b=Ly($y,r),[w,_]=x(null),R=Re(n,_),[I,T]=x(null),A=ec(I),O=A?.width??0,F=A?.height??0,N=i+(s!=="center"?"-"+s:""),L=typeof p=="number"?p:{top:0,right:0,bottom:0,left:0,...p},D=Array.isArray(u)?u:[u],G=D.length>0,q={padding:L,boundary:D.filter(Oy),altBoundary:G},{refs:$,floatingStyles:E,placement:S,isPositioned:M,middlewareData:H}=BA({strategy:"fixed",placement:N,whileElementsMounted:On((...ve)=>xA(...ve,{animationFrame:v==="always"}),"whileElementsMounted"),elements:{reference:b.anchor},middleware:[UA({mainAxis:o+F,alignmentAxis:c}),d&&GA({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?HA():void 0,...q}),d&&VA({...q}),KA({...q,apply:On(({elements:ve,rects:X,availableWidth:ce,availableHeight:be})=>{const{width:fe,height:We}=X.reference,he=ve.floating.style;he.setProperty("--radix-popper-available-width",`${ce}px`),he.setProperty("--radix-popper-available-height",`${be}px`),he.setProperty("--radix-popper-anchor-width",`${fe}px`),he.setProperty("--radix-popper-anchor-height",`${We}px`)},"apply")}),I&&WA({element:I,padding:l}),px({arrowWidth:O,arrowHeight:F}),m&&zA({strategy:"referenceHidden",...q,boundary:G?q.boundary:void 0})]}),U=b.setPlacementState;Ze(()=>(U(S),()=>{U(void 0)}),[S,U]);const[re,oe]=tc(S),ie=ht(g);Ze(()=>{M&&ie?.()},[M,ie]);const se=H.arrow?.x,ue=H.arrow?.y,Pe=H.arrow?.centerOffset!==0,[Ie,le]=x();return Ze(()=>{w&&le(window.getComputedStyle(w).zIndex)},[w]),a("div",{ref:$.setFloating,"data-radix-popper-content-wrapper":"",style:{...E,transform:M?E.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ie,"--radix-popper-transform-origin":[H.transformOrigin?.x,H.transformOrigin?.y].join(" "),...H.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:a(ax,{scope:r,placedSide:re,placedAlign:oe,onArrowChange:T,arrowX:se,arrowY:ue,shouldHideArrow:Pe,children:a(ye.div,{"data-side":re,"data-align":oe,...h,ref:R,style:{...h.style,animation:M?h.style?.animation:"none"}})})})},"PopperContent")),lx="PopperArrow",dx={top:"bottom",right:"left",bottom:"top",left:"right"},ux=J(On(function(t,n){const{__scopePopper:r,...i}=t,o=sx(lx,r),s=dx[o.placedSide];return a("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:a(QA,{...i,ref:n,style:{...i.style,display:"block"}})})},"PopperArrow"));function Oy(e){return e!==null}On(Oy,"isNotNull");var px=On(e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,o=i.arrow?.centerOffset!==0,s=o?0:e.arrowWidth,c=o?0:e.arrowHeight,[l,d]=tc(n),u={start:"0%",center:"50%",end:"100%"}[d],p=(i.arrow?.x??0)+s/2,f=(i.arrow?.y??0)+c/2;let m="",v="";return l==="bottom"?(m=o?u:`${p}px`,v=`${-c}px`):l==="top"?(m=o?u:`${p}px`,v=`${r.floating.height+c}px`):l==="right"?(m=`${-c}px`,v=o?u:`${f}px`):l==="left"&&(m=`${r.floating.width+c}px`,v=o?u:`${f}px`),{data:{x:m,y:v}}}}),"transformOrigin");function tc(e){const[t,n="center"]=e.split("-");return[t,n]}On(tc,"getSideAndAlignFromPlacement");var nc=rx,Xo=ox,rc=cx,fx=ux,mx=Object.defineProperty,jn=(e,t)=>mx(e,"name",{value:t,configurable:!0}),Ou="Popover",[jy,V2]=dt(Ou,[tr]),ic=tr(),[hx,Fr]=jy(Ou),gx=jn(e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:o,modal:s=!1}=e,c=ic(t),l=B(null),[d,u]=x(!1),[p,f]=At({prop:r,defaultProp:i??!1,onChange:o,caller:Ou});return a(nc,{...c,children:a(hx,{scope:t,contentId:Et(),triggerRef:l,open:p,onOpenChange:f,onOpenToggle:ae(()=>f(m=>!m),[f]),hasCustomAnchor:d,onCustomAnchorAdd:ae(()=>u(!0),[]),onCustomAnchorRemove:ae(()=>u(!1),[]),modal:s,children:n})})},"Popover"),vx="PopoverAnchor",yx=J(jn(function(t,n){const{__scopePopover:r,...i}=t,o=Fr(vx,r),s=ic(r),{onCustomAnchorAdd:c,onCustomAnchorRemove:l}=o;return V(()=>(c(),()=>l()),[c,l]),a(Xo,{...s,...i,ref:n})},"PopoverAnchor")),bx="PopoverTrigger",_x=J(jn(function(t,n){const{__scopePopover:r,...i}=t,o=Fr(bx,r),s=ic(r),c=Re(n,o.triggerRef),l=a(ye.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":ju(o.open),...i,ref:c,onClick:te(t.onClick,o.onOpenToggle)});return o.hasCustomAnchor?l:a(Xo,{asChild:!0,...s,children:l})},"PopoverTrigger")),My="PopoverPortal",[wx,Sx]=jy(My,{forceMount:void 0}),Cx=jn(e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,o=Fr(My,t);return a(wx,{scope:t,forceMount:n,children:a(kt,{present:n||o.open,children:a(_i,{asChild:!0,container:i,children:r})})})},"PopoverPortal"),Qo="PopoverContent",Rx=J(jn(function(t,n){const r=Sx(Qo,t.__scopePopover),{forceMount:i=r.forceMount,...o}=t,s=Fr(Qo,t.__scopePopover);return a(kt,{present:i||s.open,children:s.modal?a(kx,{...o,ref:n}):a(Tx,{...o,ref:n})})},"PopoverContent")),Ix=cn("PopoverContent.RemoveScroll"),kx=J(jn(function(t,n){const r=Fr(Qo,t.__scopePopover),i=B(null),o=Re(n,i),s=B(!1);return V(()=>{const c=i.current;if(c)return hs(c)},[]),a(To,{as:Ix,allowPinchZoom:!0,children:a(Fy,{...t,ref:o,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:te(t.onCloseAutoFocus,c=>{c.preventDefault(),s.current||r.triggerRef.current?.focus()}),onPointerDownOutside:te(t.onPointerDownOutside,c=>{const l=c.detail.originalEvent,d=l.button===0&&l.ctrlKey===!0,u=l.button===2||d;s.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:te(t.onFocusOutside,c=>c.preventDefault(),{checkForDefaultPrevented:!1})})})},"PopoverContentModal")),Tx=J(jn(function(t,n){const r=Fr(Qo,t.__scopePopover),i=B(!1),o=B(!1);return a(Fy,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{t.onCloseAutoFocus?.(s),s.defaultPrevented||(i.current||r.triggerRef.current?.focus(),s.preventDefault()),i.current=!1,o.current=!1},onInteractOutside:s=>{t.onInteractOutside?.(s),s.defaultPrevented||(i.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const c=s.target;r.triggerRef.current?.contains(c)&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})},"PopoverContentNonModal")),Fy=J(jn(function(t,n){const{__scopePopover:r,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:s,disableOutsidePointerEvents:c,onEscapeKeyDown:l,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:p,...f}=t,m=Fr(Qo,r),v=ic(r);return Ci(),a(as,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:o,onUnmountAutoFocus:s,children:a(bi,{asChild:!0,disableOutsidePointerEvents:c,onInteractOutside:p,onEscapeKeyDown:l,onPointerDownOutside:d,onFocusOutside:u,onDismiss:()=>m.onOpenChange(!1),deferPointerDownOutside:!0,children:a(rc,{"data-state":ju(m.open),role:"dialog",id:m.contentId,...v,...f,ref:n,style:{...f.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})},"PopoverContentImpl"));function ju(e){return e?"open":"closed"}jn(ju,"getState");var By=gx,Px=yx,Nx=_x,qy=Cx,Uy=Rx;function Mu(e){return e.trim()}function Gy({values:e,onValuesChange:t,availableProjects:n,placeholder:r,emptyLabel:i,disabled:o,"aria-labelledby":s}){const[c,l]=x(!1),[d,u]=x(""),[p,f]=x(0),m=B(null),v=ke(()=>{const N=new Set,L=[];for(const D of[...n,...e]){const G=Mu(D);!G||N.has(G)||(N.add(G),L.push(G))}return L.sort((D,G)=>D.localeCompare(G))},[n,e]),g=Mu(d),h=g.toLowerCase(),b=ke(()=>h?v.filter(N=>N.toLowerCase().includes(h)):v,[v,h]),w=g?v.some(N=>N.toLowerCase()===h):!1,_=!!g&&!w,R=b.length+(_?1:0);V(()=>{p>=R&&f(Math.max(0,R-1))},[R,p]),V(()=>{if(!c)return;const N=requestAnimationFrame(()=>m.current?.focus());return()=>cancelAnimationFrame(N)},[c]);const I=N=>{e.includes(N)?t(e.filter(L=>L!==N)):t(Array.from(new Set([...e,N])))},T=N=>{const L=Mu(N);L&&(t(Array.from(new Set([...e,L]))),u(""),f(0))},A=N=>{if(N<b.length){const L=b[N];L&&I(L);return}_&&T(g)},O=N=>{if(N.key==="ArrowDown"){N.preventDefault(),f(L=>Math.min(R-1,L+1));return}if(N.key==="ArrowUp"){N.preventDefault(),f(L=>Math.max(0,L-1));return}if(N.key==="Enter"){N.preventDefault(),A(p);return}},F=N=>{t(e.filter(L=>L!==N))};return a("div",{class:"project-scope-picker",children:[a("ul",{"aria-labelledby":s,class:"project-scope-picker-selected",children:e.length===0?a("li",{class:"project-scope-picker-selected-empty",children:i||"No projects selected."}):e.map(N=>a("li",{class:"project-scope-picker-selected-chip",children:[a("span",{children:N}),o?null:a("button",{"aria-label":`Remove ${N}`,class:"project-scope-picker-selected-remove",onClick:()=>F(N),type:"button",children:"×"})]},N))}),a(By,{onOpenChange:N=>{l(N),N||(u(""),f(0))},open:c,children:[a(Nx,{asChild:!0,children:a("button",{class:"project-scope-picker-trigger settings-button",disabled:o,type:"button",children:[a("span",{"aria-hidden":"true",children:"+"}),a("span",{children:r||"Add project"})]})}),a(qy,{children:a(Uy,{align:"start",class:"project-scope-picker-popover",sideOffset:6,children:[a("input",{"aria-label":"Search projects",class:"project-scope-picker-search",onInput:N=>{u(N.currentTarget.value),f(0)},onKeyDown:O,placeholder:"Search or create…",ref:m,type:"text",value:d}),a("div",{class:"project-scope-picker-results",role:"listbox",children:[b.length===0&&!_?a("div",{class:"project-scope-picker-empty-row",children:"No projects yet. Type a name to create one."}):null,b.map((N,L)=>{const D=e.includes(N);return a("button",{"aria-selected":D,class:L===p?"project-scope-picker-row project-scope-picker-row--active":"project-scope-picker-row",onClick:()=>{f(L),I(N)},onMouseEnter:()=>f(L),role:"option",type:"button",children:[a("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:D?"✓":""}),a("span",{class:"project-scope-picker-row-label",children:N})]},N)}),_?a("button",{"aria-selected":!1,class:p===b.length?"project-scope-picker-row project-scope-picker-row--create project-scope-picker-row--active":"project-scope-picker-row project-scope-picker-row--create",onClick:()=>T(g),onMouseEnter:()=>f(b.length),role:"option",type:"button",children:[a("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:"+"}),a("span",{class:"project-scope-picker-row-label",children:`Create "${g}"`})]}):null]})]})})]})]})}var Ex=Object.defineProperty,nr=(e,t)=>Ex(e,"name",{value:t,configurable:!0}),Fu="Switch",[Ax,K2]=dt(Fu),[xx,Bu]=Ax(Fu);function Hy(e){const{__scopeSwitch:t,checked:n,children:r,defaultChecked:i,disabled:o,form:s,name:c,onCheckedChange:l,required:d,value:u="on",internal_do_not_use_render:p}=e,[f,m]=At({prop:n,defaultProp:i??!1,onChange:l,caller:Fu}),[v,g]=x(null),[h,b]=x(null),w=B(!1),[_,R]=In(T=>T+1,0),I={checked:f,setChecked:m,disabled:o,control:v,setControl:g,name:c,form:s,value:u,hasConsumerStoppedPropagationRef:w,userInteractionCount:_,onUserInteraction:R,required:d,defaultChecked:i,isFormControl:v?!!s||!!v.closest("form"):!0,bubbleInput:h,setBubbleInput:b};return a(xx,{scope:t,...I,children:Vy(p)?p(I):r})}nr(Hy,"SwitchProvider");var Dx="SwitchTrigger",Lx=J(nr(function({__scopeSwitch:t,onClick:n,...r},i){const{control:o,form:s,value:c,disabled:l,checked:d,required:u,setControl:p,setChecked:f,hasConsumerStoppedPropagationRef:m,onUserInteraction:v,isFormControl:g,bubbleInput:h}=Bu(Dx,t),b=Re(i,p),w=B(d);return V(()=>{const _=s?o?.ownerDocument.getElementById(s):o?.form;if(_ instanceof HTMLFormElement){const R=nr(()=>f(w.current),"reset");return _.addEventListener("reset",R),()=>_.removeEventListener("reset",R)}},[o,s,f]),a(ye.button,{type:"button",role:"switch","aria-checked":d,"aria-required":u,"data-state":qu(d),"data-disabled":l?"":void 0,disabled:l,value:c,...r,ref:b,onClick:te(n,_=>{v(),f(R=>!R),h&&g&&(m.current=_.isPropagationStopped(),m.current||_.stopPropagation())})})},"SwitchTrigger")),$x=J(nr(function(t,n){const{__scopeSwitch:r,name:i,checked:o,defaultChecked:s,required:c,disabled:l,value:d,onCheckedChange:u,form:p,...f}=t;return a(Hy,{__scopeSwitch:r,checked:o,defaultChecked:s,disabled:l,required:c,onCheckedChange:u,name:i,form:p,value:d,internal_do_not_use_render:({isFormControl:m})=>a(z,{children:[a(Lx,{...f,ref:n,__scopeSwitch:r}),m&&a(Fx,{__scopeSwitch:r})]})})},"Switch")),Ox="SwitchThumb",jx=J(nr(function(t,n){const{__scopeSwitch:r,...i}=t,o=Bu(Ox,r);return a(ye.span,{"data-state":qu(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:n})},"SwitchThumb")),Mx="SwitchBubbleInput",Fx=J(nr(function({__scopeSwitch:t,onClick:n,...r},i){const{control:o,hasConsumerStoppedPropagationRef:s,userInteractionCount:c,checked:l,defaultChecked:d,required:u,disabled:p,name:f,value:m,form:v,bubbleInput:g,setBubbleInput:h}=Bu(Mx,t),b=Re(i,h),w=ec(o),_=B(!1),R=B(l),I=B(c);V(()=>{const A=g;if(!A)return;const O=window.HTMLInputElement.prototype,F=Object.getOwnPropertyDescriptor(O,"checked").set,N=c!==I.current;I.current=c;const L=R.current!==l;R.current=l;const D=!(N&&s.current);if(L&&F){_.current=!N;const G=new Event("click",{bubbles:D});F.call(A,l),A.dispatchEvent(G),_.current=!1}},[g,l,s,c]);const T=B(l);return a(ye.input,{type:"checkbox","aria-hidden":!0,defaultChecked:d??T.current,required:u,disabled:p,name:f,value:m,form:v,...r,tabIndex:-1,ref:b,onClick:te(n,A=>{_.current&&A.stopPropagation()}),style:{...r.style,...w,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"SwitchBubbleInput"));function Vy(e){return typeof e=="function"}nr(Vy,"isFunction");function qu(e){return e?"checked":"unchecked"}nr(qu,"getState");function Gi({"aria-labelledby":e,checked:t,className:n,disabled:r=!1,id:i,name:o,onCheckedChange:s,thumbClassName:c}){return a($x,{"aria-labelledby":e,checked:t,className:n,disabled:r,id:i,name:o,onCheckedChange:s,children:a(jx,{className:c})})}function Z(e,t="success"){DN(e,t)}function Mn(e){return String(e||"").trim().replace(/\/+$/u,"")}function Ky(e){return`${jE}:${Mn(e)}`}function Bx(e){try{return localStorage.getItem(Ky(e))||""}catch{return""}}function qx(e,t){try{localStorage.setItem(Ky(e),t)}catch{}}function Fn(){return String(C.coordinatorAdminTargetGroup||"").trim()}function oc(){const e=String(C.lastCoordinatorAdminStatus?.coordinator_url||"").trim(),t=Fn()||String(C.lastCoordinatorAdminStatus?.active_group||"").trim()||rr()[0]?.group_id||"";return e&&t?{coordinatorUrl:e,groupId:t}:null}function $t(e){const t=oc();return!!(e&&t&&Mn(e.coordinatorUrl)===Mn(t.coordinatorUrl)&&e.groupId===t.groupId)}function Uu(e){C.coordinatorAdminTargetGroup=e,qx(C.lastCoordinatorAdminStatus?.coordinator_url||null,e)}function rr(){return(Array.isArray(C.lastCoordinatorAdminGroups)?C.lastCoordinatorAdminGroups:[]).map(e=>({archived_at:e.archived_at??null,display_name:e.display_name??null,group_id:String(e.group_id||"").trim()})).filter(e=>e.group_id)}function Gu(e,t){const n=String(t||"").trim(),r=rr(),i=new Set(r.map(l=>String(l.display_name||"").trim()).filter(Boolean));n&&i.add(n);for(const[l,d]of P.groupPresentationAliases)i.has(d)&&P.groupPresentationAliases.delete(l);if(n)return n;const o=P.groupPresentationAliases.get(e);if(o)return o;for(const l of P.groupPresentationAliases.values())i.add(l);let s=1,c=`Unnamed coordinator group ${s}`;for(;i.has(c);)s+=1,c=`Unnamed coordinator group ${s}`;return P.groupPresentationAliases.set(e,c),c}function Ux(){const e=new Map;for(const t of rr())e.set(t.group_id,t.display_name||"");P.groupRenameDrafts.clear();for(const[t,n]of e.entries())P.groupRenameDrafts.set(t,n)}function Gx(){const e=Fn();return rr().find(t=>t.group_id===e)||null}function zy(){const e=C.lastCoordinatorAdminStatus,t=rr(),n=String(e?.active_group||"").trim(),r=Bx(e?.coordinator_url||null),i=Fn(),o=new Set(t.map(l=>l.group_id)),s=i||r||n||t[0]?.group_id||"",c=s&&(o.size===0||o.has(s))?s:n||t[0]?.group_id||"";return Uu(c),c}function Hx(){const e=new Map,t=new Map,n=Array.isArray(C.lastCoordinatorAdminDevices)?C.lastCoordinatorAdminDevices:[];for(const r of n){const i=String(r.device_id||"").trim();if(!i)continue;const o=String(r.display_name||""),s=P.deviceRenameDrafts.get(i),c=P.deviceRenameServerNames.get(i),l=s!==void 0&&(c===void 0||s!==c);e.set(i,l?s:o),t.set(i,o)}P.deviceRenameDrafts.clear();for(const[r,i]of e.entries())P.deviceRenameDrafts.set(r,i);P.deviceRenameServerNames.clear();for(const[r,i]of t.entries())P.deviceRenameServerNames.set(r,i)}function Vx(e,t){return t&&t.groupId===e?t:null}function Kx(e,t){return e?.loaded&&e.default_space_scope_id?"Configured":e?.loaded?"Not configured":t?.defaultSpaceLabel?t.defaultSpaceLabel:t?.defaultSpaceScopeId?"Configured":"Open legacy group defaults to inspect"}function zx(e,t){return e?.loaded?e.auto_grant_default_space_on_join?"On for the default Space":"Off — Space access stays explicit":t?.autoGrantDefaultSpaceOnJoin===!0?"On for the default Space":t?.autoGrantDefaultSpaceOnJoin===!1?"Off — Space access stays explicit":"Open legacy group defaults to inspect"}function Wx(e){return e?.loaded?e.scopes.filter(t=>String(t.status||"active")==="active").length:null}function Jx(e){const t=Wx(e);return t===null?"Open Spaces to inspect access grants":`${t} active ${t===1?"Space":"Spaces"}`}function Yx(e){const t=Vx(e.groupId,e.setupGuide);return{autoGrant:zx(e.preferences,t),defaultSpace:Kx(e.preferences,t),spaces:Jx(e.scopeManagement)}}var Hu=null,ac=null,Vu=null;function Xx(){return Hu}function Ku(e){ac=e}function Wy(e){Vu=e}function Qx(e){return Vu===e}function Zx(e){return e?e.kind==="confirm"?!1:e.kind==="input"?null:{action:"cancel"}:null}function zu(e){return!Hu||!ac?!0:(console.warn(`Ignored sync ${e} dialog request because another sync dialog is already open.`),!1)}function sc(e){Hu=e,Vu?.(e)}function ir(e){const t=ac;ac=null,sc(null),t?.(e)}function e0(e){return e==="danger"?"sync-dialog-confirm danger":"sync-dialog-confirm"}var t0=J(function({value:t,onValueChange:n,suggestions:r,onSubmit:i,maxSuggestions:o=20,onKeyDown:s,onFocus:c,onBlur:l,className:d,...u},p){const f=B(null);es(p,()=>f.current,[]);const[m,v]=x(!1),[g,h]=x(-1),b=ke(()=>{const I=t.trim().toLowerCase();return(I?r.filter(T=>T.toLowerCase().includes(I)):r).slice(0,o)},[t,r,o]);V(()=>{g>=b.length&&h(b.length-1)},[b.length,g]);const w=m&&b.length>0,_=I=>{n(I),v(!1),h(-1),f.current?.focus()};return a(By,{open:w,onOpenChange:v,children:[a(Px,{asChild:!0,children:a("input",{...u,ref:f,className:d,value:t,onInput:I=>{n(I.currentTarget.value),v(!0),h(-1)},onFocus:I=>{c?.(I)},onBlur:I=>{window.setTimeout(()=>v(!1),120),l?.(I)},onKeyDown:I=>{if(I.key==="ArrowDown"){I.preventDefault(),v(!0),h(T=>b.length===0?-1:Math.min(T+1,b.length-1));return}if(I.key==="ArrowUp"){I.preventDefault(),m||v(!0),h(T=>Math.max(T-1,-1));return}if(I.key==="Escape"&&w){I.preventDefault(),v(!1),h(-1);return}if((I.key==="Tab"||I.key==="Enter")&&g>=0){const T=b[g];if(T){I.preventDefault(),_(T);return}}if(I.key==="Enter"&&i){I.preventDefault(),i();return}s?.(I)},role:"combobox","aria-autocomplete":"list","aria-expanded":w,"aria-controls":"autocompleteListbox","aria-activedescendant":g>=0?`autocomplete-option-${g}`:void 0})}),a(qy,{children:a(Uy,{align:"start",className:"autocomplete-popover",onOpenAutoFocus:I=>I.preventDefault(),onCloseAutoFocus:I=>I.preventDefault(),sideOffset:4,style:{width:"var(--radix-popover-trigger-width)"},children:a("div",{className:"autocomplete-listbox",id:"autocompleteListbox",role:"listbox",children:b.map((I,T)=>{const A=T===g;return a("div",{"aria-selected":A,className:A?"autocomplete-option active":"autocomplete-option",id:`autocomplete-option-${T}`,onMouseDown:O=>{O.preventDefault(),_(I)},onMouseEnter:()=>h(T),role:"option",tabIndex:-1,children:I},I)})})})})]})}),n0=Object.defineProperty,gt=(e,t)=>n0(e,"name",{value:t,configurable:!0}),Jy="Radio",[r0,Yy]=dt(Jy),[i0,cc]=r0(Jy);function Xy(e){const{__scopeRadio:t,checked:n=!1,children:r,disabled:i,form:o,name:s,onCheck:c,required:l,value:d="on",internal_do_not_use_render:u}=e,[p,f]=x(null),[m,v]=x(null),g=B(!1),[h,b]=In(_=>_+1,0),w={checked:n,disabled:i,required:l,name:s,form:o,value:d,control:p,setControl:f,hasConsumerStoppedPropagationRef:g,userInteractionCount:h,onUserInteraction:b,isFormControl:p?!!o||!!p.closest("form"):!0,bubbleInput:m,setBubbleInput:v,onCheck:gt(()=>c?.(),"onCheck")};return a(i0,{scope:t,...w,children:Qy(u)?u(w):r})}gt(Xy,"RadioProvider");var o0="RadioTrigger",a0=J(gt(function({__scopeRadio:t,onClick:n,...r},i){const{checked:o,disabled:s,value:c,setControl:l,onCheck:d,hasConsumerStoppedPropagationRef:u,onUserInteraction:p,isFormControl:f,bubbleInput:m}=cc(o0,t),v=Re(i,l);return a(ye.button,{type:"button",role:"radio","aria-checked":o,"data-state":Wu(o),"data-disabled":s?"":void 0,disabled:s,value:c,...r,ref:v,onClick:te(n,g=>{o||(p(),d()),m&&f&&(u.current=g.isPropagationStopped(),u.current||g.stopPropagation())})})},"RadioTrigger")),s0="RadioIndicator",c0=J(gt(function(t,n){const{__scopeRadio:r,forceMount:i,...o}=t,s=cc(s0,r);return a(kt,{present:i||s.checked,children:a(ye.span,{"data-state":Wu(s.checked),"data-disabled":s.disabled?"":void 0,...o,ref:n})})},"RadioIndicator")),l0="RadioBubbleInput",d0=J(gt(function({__scopeRadio:t,onClick:n,...r},i){const{control:o,checked:s,required:c,disabled:l,name:d,value:u,form:p,bubbleInput:f,setBubbleInput:m,hasConsumerStoppedPropagationRef:v,userInteractionCount:g}=cc(l0,t),h=Re(i,m),b=ec(o),w=B(!1),_=B(s),R=B(g);V(()=>{const T=f;if(!T)return;const A=window.HTMLInputElement.prototype,O=Object.getOwnPropertyDescriptor(A,"checked").set,F=g!==R.current;R.current=g;const N=_.current!==s;_.current=s;const L=!(F&&v.current);if(N&&O){w.current=!F;const D=new Event("click",{bubbles:L});O.call(T,s),T.dispatchEvent(D),w.current=!1}},[f,s,v,g]);const I=B(s);return a(ye.input,{type:"radio","aria-hidden":!0,defaultChecked:I.current,required:c,disabled:l,name:d,value:u,form:p,...r,tabIndex:-1,ref:h,onClick:te(n,T=>{w.current&&T.stopPropagation()}),style:{...r.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"RadioBubbleInput"));function Qy(e){return typeof e=="function"}gt(Qy,"isFunction");function Wu(e){return e?"checked":"unchecked"}gt(Wu,"getState");var u0=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Ju="RadioGroup",[p0,z2]=dt(Ju,[Oi,Yy]),Zy=Oi(),lc=Yy(),[f0,m0]=p0(Ju),h0=J(gt(function(t,n){const{__scopeRadioGroup:r,name:i,form:o,defaultValue:s,value:c,required:l=!1,disabled:d=!1,orientation:u,dir:p,loop:f=!0,onValueChange:m,...v}=t,g=Zy(r),h=$i(p),[b,w]=At({prop:c,defaultProp:s??null,onChange:m,caller:Ju}),[_,R]=x(null),I=Re(n,R),T=B(b);return V(()=>{const A=o?_?.ownerDocument.getElementById(o):_?.closest("form");if(A instanceof HTMLFormElement){const O=gt(()=>w(T.current),"reset");return A.addEventListener("reset",O),()=>A.removeEventListener("reset",O)}},[_,o,w]),a(f0,{scope:r,name:i,form:o,required:l,disabled:d,value:b,onValueChange:w,children:a(uu,{asChild:!0,...g,orientation:u,dir:h,loop:f,children:a(ye.div,{role:"radiogroup","aria-required":l,"aria-orientation":u,"data-disabled":d?"":void 0,dir:h,...v,ref:I})})})},"RadioGroup")),g0="RadioGroupItemProvider",v0="RadioGroupItemTrigger";function eb(e){const{__scopeRadioGroup:t,value:n,disabled:r,children:i,internal_do_not_use_render:o}=e,s=m0(g0,t),c=lc(t),l=s.disabled||r;return a(Xy,{...c,checked:s.value===n,disabled:l,required:s.required,name:s.name,form:s.form,value:n,onCheck:()=>s.onValueChange(n),internal_do_not_use_render:o,children:i})}gt(eb,"RadioGroupItemProvider");var y0=J(gt(function(t,n){const{__scopeRadioGroup:r,...i}=t,o=Zy(r),s=lc(r),{checked:c,disabled:l}=cc(v0,s.__scopeRadio),d=B(null),u=Re(n,d),p=B(!1);return V(()=>{const f=gt(v=>{u0.includes(v.key)&&(p.current=!0)},"handleKeyDown"),m=gt(()=>p.current=!1,"handleKeyUp");return document.addEventListener("keydown",f),document.addEventListener("keyup",m),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",m)}},[]),a(pu,{asChild:!0,...o,focusable:!l,active:c,children:a(a0,{...s,...i,ref:u,onKeyDown:te(i.onKeyDown,f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:te(i.onFocus,()=>{p.current&&d.current?.click()})})})},"RadioGroupItemTrigger")),b0=J(gt(function(t,n){const{__scopeRadioGroup:r,value:i,disabled:o,...s}=t;return a(eb,{__scopeRadioGroup:r,value:i,disabled:o,internal_do_not_use_render:({isFormControl:c})=>a(z,{children:[a(y0,{...s,ref:n,__scopeRadioGroup:r}),c&&a(_0,{__scopeRadioGroup:r})]})})},"RadioGroupItem")),_0=J(gt(function(t,n){const{__scopeRadioGroup:r,...i}=t,o=lc(r);return a(d0,{...o,...i,ref:n})},"RadioGroupItemBubbleInput")),w0=J(gt(function(t,n){const{__scopeRadioGroup:r,...i}=t,o=lc(r);return a(c0,{...o,...i,ref:n})},"RadioGroupIndicator"));function S0({ariaDescribedby:e,ariaLabel:t,autoFocusValue:n,indicatorClassName:r,itemClassName:i,itemLabelClassName:o,name:s,onValueChange:c,options:l,rootClassName:d,value:u}){return a(h0,{"aria-describedby":e,"aria-label":t,className:d,name:s,onValueChange:c,value:u,children:l.map((p,f)=>{const m=`radio-option-input-${f}`,v=`radio-option-label-${f}`;return a("label",{className:i,htmlFor:m,children:[a(b0,{id:m,"aria-labelledby":v,autoFocus:n===p.value,disabled:p.disabled,value:p.value,children:a(w0,{className:r})}),a("span",{className:o,id:v,children:p.label})]},p.value)})})}var C0=Object.defineProperty,R0=(e,t)=>C0(e,"name",{value:t,configurable:!0});function Yu(e,[t,n]){return Math.min(n,Math.max(t,e))}R0(Yu,"clamp");var I0=Object.defineProperty,k0=(e,t)=>I0(e,"name",{value:t,configurable:!0});function tb(e){const t=B({value:e,previous:e});return ke(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}k0(tb,"usePrevious");var T0=Object.defineProperty,Me=(e,t)=>T0(e,"name",{value:t,configurable:!0}),P0=[" ","Enter","ArrowUp","ArrowDown"],N0=[" ","Enter"],Hi="Select",[dc,Xu,E0]=Fo(Hi),[Br,W2]=dt(Hi,[E0,tr]),Qu=tr(),[A0,or]=Br(Hi),[x0,D0]=Br(Hi);function nb(e){const{__scopeSelect:t,children:n,open:r,defaultOpen:i,onOpenChange:o,value:s,defaultValue:c,onValueChange:l,dir:d,name:u,autoComplete:p,disabled:f,required:m,form:v,internal_do_not_use_render:g}=e,h=Qu(t),[b,w]=x(null),[_,R]=x(null),[I,T]=x(!1),A=$i(d),[O,F]=At({prop:r,defaultProp:i??!1,onChange:o,caller:Hi}),[N,L]=At({prop:s,defaultProp:c,onChange:l,caller:Hi}),D=B(null),G=B(N);V(()=>{const oe=v?b?.ownerDocument.getElementById(v):b?.form;if(oe instanceof HTMLFormElement){const ie=Me(()=>L(G.current),"reset");return oe.addEventListener("reset",ie),()=>oe.removeEventListener("reset",ie)}},[v,b,L]);const q=b?!!v||!!b.closest("form"):!0,[$,E]=x(new Set),S=Et(),M=Array.from($).map(oe=>oe.props.value).join(";"),H=ae(oe=>{E(ie=>new Set(ie).add(oe))},[]),U=ae(oe=>{E(ie=>{const se=new Set(ie);return se.delete(oe),se})},[]),re={required:m,trigger:b,onTriggerChange:w,valueNode:_,onValueNodeChange:R,valueNodeHasChildren:I,onValueNodeHasChildrenChange:T,contentId:S,value:N,onValueChange:L,open:O,onOpenChange:F,dir:A,triggerPointerDownPosRef:D,disabled:f,name:u,autoComplete:p,form:v,nativeOptions:$,nativeSelectKey:M,isFormControl:q};return a(nc,{...h,children:a(A0,{scope:t,...re,children:a(dc.Provider,{scope:t,children:a(x0,{scope:t,onNativeOptionAdd:H,onNativeOptionRemove:U,children:sb(g)?g(re):n})})})})}Me(nb,"SelectProvider");var L0=Me(e=>{const{__scopeSelect:t,children:n,...r}=e;return a(nb,{__scopeSelect:t,...r,internal_do_not_use_render:({isFormControl:i})=>a(z,{children:[n,i?a(rD,{__scopeSelect:t}):null]})})},"Select"),$0="SelectTrigger",O0=J(Me(function(t,n){const{__scopeSelect:r,disabled:i=!1,...o}=t,s=Qu(r),c=or($0,r),l=c.disabled||i,d=Re(n,c.onTriggerChange),u=Xu(r),p=B("touch"),[f,m,v]=ep(h=>{const b=u().filter(_=>!_.disabled),w=tp(b,h,b.find(_=>_.value===c.value));w!==void 0&&c.onValueChange(w.value)}),g=Me(h=>{l||(c.onOpenChange(!0),v()),h&&(c.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)})},"handleOpen");return a(Xo,{asChild:!0,...s,children:a(ye.button,{type:"button",role:"combobox","aria-controls":c.open?c.contentId:void 0,"aria-expanded":c.open,"aria-required":c.required,"aria-autocomplete":"none",dir:c.dir,"data-state":c.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":Zo(c.value)?"":void 0,...o,ref:d,onClick:te(o.onClick,h=>{h.currentTarget.focus(),p.current!=="mouse"&&g(h)}),onPointerDown:te(o.onPointerDown,h=>{p.current=h.pointerType;const b=h.target;b.hasPointerCapture(h.pointerId)&&b.releasePointerCapture(h.pointerId),h.button===0&&h.ctrlKey===!1&&h.pointerType==="mouse"&&(g(h),h.preventDefault())}),onKeyDown:te(o.onKeyDown,h=>{const b=f.current!=="";!(h.ctrlKey||h.altKey||h.metaKey)&&h.key.length===1&&m(h.key),!(b&&h.key===" ")&&P0.includes(h.key)&&(g(),h.preventDefault())})})})},"SelectTrigger")),j0="SelectValue",M0=J(Me(function(t,n){const{__scopeSelect:r,className:i,style:o,children:s,placeholder:c="",...l}=t,d=or(j0,r),{onValueNodeHasChildrenChange:u}=d,p=s!==void 0,f=Re(n,d.onValueNodeChange);Ze(()=>{u(p)},[u,p]);const m=Zo(d.value);return a(ye.span,{...l,asChild:m?!1:l.asChild,ref:f,style:{pointerEvents:"none"},children:a(z,{children:m?c:s},m?"placeholder":"value")})},"SelectValue")),F0=J(Me(function(t,n){const{__scopeSelect:r,children:i,...o}=t;return a(ye.span,{"aria-hidden":!0,...o,ref:n,children:i||"▼"})},"SelectIcon")),[B0,q0]=Br("SelectPortal",{forceMount:void 0}),U0=Me(e=>{const{__scopeSelect:t,forceMount:n,...r}=e;return a(B0,{scope:e.__scopeSelect,forceMount:n,children:a(_i,{asChild:!0,...r})})},"SelectPortal"),qr="SelectContent",G0=J(Me(function(t,n){const r=q0(qr,t.__scopeSelect),{forceMount:i=r.forceMount,...o}=t,s=or(qr,t.__scopeSelect),[c,l]=x();return Ze(()=>{l(new DocumentFragment)},[]),a(kt,{present:i||s.open,children:({present:d})=>d?a(K0,{...o,ref:n}):a(H0,{...o,fragment:c})})},"SelectContent")),H0=J(Me(function(t,n){const{__scopeSelect:r,children:i,fragment:o}=t;return o?sn(a(rb,{scope:r,children:a(dc.Slot,{scope:r,children:a("div",{ref:n,children:i})})}),o):null},"SelectContentFragment")),Qt=10,[rb,uc]=Br(qr),V0=cn("SelectContent.RemoveScroll"),K0=J(Me(function(t,n){const{__scopeSelect:r}=t,{position:i="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:s,onPointerDownOutside:c,side:l,sideOffset:d,align:u,alignOffset:p,arrowPadding:f,collisionBoundary:m,collisionPadding:v,sticky:g,hideWhenDetached:h,avoidCollisions:b,...w}=t,_=or(qr,r),[R,I]=x(null),[T,A]=x(null),O=Re(n,I),[F,N]=x(null),[L,D]=x(null),G=Xu(r),[q,$]=x(!1),E=B(!1);V(()=>{if(R)return hs(R)},[R]),Ci();const S=ae(le=>{const[ve,...X]=G().map(fe=>fe.ref.current),[ce]=X.slice(-1),be=document.activeElement;for(const fe of le)if(fe===be||(fe?.scrollIntoView({block:"nearest"}),fe===ve&&T&&(T.scrollTop=0),fe===ce&&T&&(T.scrollTop=T.scrollHeight),fe?.focus(),document.activeElement!==be))return},[G,T]),M=ae(()=>S([F,R]),[S,F,R]);V(()=>{q&&M()},[q,M]);const{onOpenChange:H,triggerPointerDownPosRef:U}=_;V(()=>{if(R){let le={x:0,y:0};const ve=Me(ce=>{le={x:Math.abs(Math.round(ce.pageX)-(U.current?.x??0)),y:Math.abs(Math.round(ce.pageY)-(U.current?.y??0))}},"handlePointerMove"),X=Me(ce=>{le.x<=10&&le.y<=10?ce.preventDefault():ce.composedPath().includes(R)||H(!1),document.removeEventListener("pointermove",ve),U.current=null},"handlePointerUp");return U.current!==null&&(document.addEventListener("pointermove",ve),document.addEventListener("pointerup",X,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ve),document.removeEventListener("pointerup",X,{capture:!0})}}},[R,H,U]),V(()=>{const le=Me(()=>H(!1),"close");return window.addEventListener("blur",le),window.addEventListener("resize",le),()=>{window.removeEventListener("blur",le),window.removeEventListener("resize",le)}},[H]);const[re,oe]=ep(le=>{const ve=G().filter(ce=>!ce.disabled),X=tp(ve,le,ve.find(ce=>ce.ref.current===document.activeElement));X&&setTimeout(()=>X.ref.current?.focus())}),ie=ae((le,ve,X)=>{const ce=!E.current&&!X;(_.value!==void 0&&_.value===ve||ce)&&(N(le),ce&&(E.current=!0))},[_.value]),se=ae(()=>R?.focus(),[R]),ue=ae((le,ve,X)=>{const ce=!E.current&&!X;(_.value!==void 0&&_.value===ve||ce)&&D(le)},[_.value]),Pe=i==="popper"?ib:z0,Ie=Pe===ib?{side:l,sideOffset:d,align:u,alignOffset:p,arrowPadding:f,collisionBoundary:m,collisionPadding:v,sticky:g,hideWhenDetached:h,avoidCollisions:b}:{};return a(rb,{scope:r,content:R,viewport:T,onViewportChange:A,itemRefCallback:ie,selectedItem:F,onItemLeave:se,itemTextRefCallback:ue,focusSelectedItem:M,selectedItemText:L,position:i,isPositioned:q,searchRef:re,children:a(To,{as:V0,allowPinchZoom:!0,children:a(as,{asChild:!0,trapped:_.open,onMountAutoFocus:le=>{le.preventDefault()},onUnmountAutoFocus:te(o,le=>{_.trigger?.focus({preventScroll:!0}),le.preventDefault()}),children:a(bi,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:c,onFocusOutside:le=>le.preventDefault(),onDismiss:()=>_.onOpenChange(!1),children:a(Pe,{role:"listbox",id:_.contentId,"data-state":_.open?"open":"closed",dir:_.dir,onContextMenu:le=>le.preventDefault(),...w,...Ie,onPlaced:()=>$(!0),ref:O,style:{display:"flex",flexDirection:"column",outline:"none",...w.style},onKeyDown:te(w.onKeyDown,le=>{const ve=le.ctrlKey||le.altKey||le.metaKey;if(le.key==="Tab"&&le.preventDefault(),!ve&&le.key.length===1&&oe(le.key),["ArrowUp","ArrowDown","Home","End"].includes(le.key)){let X=G().filter(ce=>!ce.disabled).map(ce=>ce.ref.current);if(["ArrowUp","End"].includes(le.key)&&(X=X.slice().reverse()),["ArrowUp","ArrowDown"].includes(le.key)){const ce=le.target,be=X.indexOf(ce);X=X.slice(be+1)}setTimeout(()=>S(X)),le.preventDefault()}})})})})})})},"SelectContentImpl")),z0=J(Me(function(t,n){const{__scopeSelect:r,onPlaced:i,...o}=t,s=or(qr,r),c=uc(qr,r),[l,d]=x(null),[u,p]=x(null),f=Re(n,p),m=Xu(r),v=B(!1),g=B(!0),{viewport:h,selectedItem:b,selectedItemText:w,focusSelectedItem:_}=c,R=ae(()=>{if(s.trigger&&s.valueNode&&l&&u&&h&&b&&w){const O=s.trigger.getBoundingClientRect(),F=u.getBoundingClientRect(),N=s.valueNode.getBoundingClientRect(),L=w.getBoundingClientRect();if(s.dir!=="rtl"){const ce=L.left-F.left,be=N.left-ce,fe=O.left-be,We=O.width+fe,he=Math.max(We,F.width),W=window.innerWidth-Qt,de=Yu(be,[Qt,Math.max(Qt,W-he)]);l.style.minWidth=We+"px",l.style.left=de+"px"}else{const ce=F.right-L.right,be=window.innerWidth-N.right-ce,fe=window.innerWidth-O.right-be,We=O.width+fe,he=Math.max(We,F.width),W=window.innerWidth-Qt,de=Yu(be,[Qt,Math.max(Qt,W-he)]);l.style.minWidth=We+"px",l.style.right=de+"px"}const D=m(),G=window.innerHeight-Qt*2,q=h.scrollHeight,$=window.getComputedStyle(u),E=parseInt($.borderTopWidth,10),S=parseInt($.paddingTop,10),M=parseInt($.borderBottomWidth,10),H=parseInt($.paddingBottom,10),U=E+S+q+H+M,re=Math.min(b.offsetHeight*5,U),oe=window.getComputedStyle(h),ie=parseInt(oe.paddingTop,10),se=parseInt(oe.paddingBottom,10),ue=O.top+O.height/2-Qt,Pe=G-ue,Ie=b.offsetHeight/2,le=b.offsetTop+Ie,ve=E+S+le,X=U-ve;if(ve<=ue){const ce=D.length>0&&b===D[D.length-1].ref.current;l.style.bottom="0px";const be=u.clientHeight-h.offsetTop-h.offsetHeight,fe=ve+Math.max(Pe,Ie+(ce?se:0)+be+M);l.style.height=fe+"px"}else{const ce=D.length>0&&b===D[0].ref.current;l.style.top="0px";const be=Math.max(ue,E+h.offsetTop+(ce?ie:0)+Ie)+X;l.style.height=be+"px",h.scrollTop=ve-ue+h.offsetTop}l.style.margin=`${Qt}px 0`,l.style.minHeight=re+"px",l.style.maxHeight=G+"px",i?.(),requestAnimationFrame(()=>v.current=!0)}},[m,s.trigger,s.valueNode,l,u,h,b,w,s.dir,i]);Ze(()=>R(),[R]);const[I,T]=x();Ze(()=>{u&&T(window.getComputedStyle(u).zIndex)},[u]);const A=ae(O=>{O&&g.current===!0&&(R(),_?.(),g.current=!1)},[R,_]);return a(W0,{scope:r,contentWrapper:l,shouldExpandOnScrollRef:v,onScrollButtonChange:A,children:a("div",{ref:d,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:I},children:a(ye.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})},"SelectItemAlignedPosition")),ib=J(Me(function(t,n){const{__scopeSelect:r,align:i="start",collisionPadding:o=Qt,...s}=t,c=Qu(r);return a(rc,{...c,...s,ref:n,align:i,collisionPadding:o,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})},"SelectPopperPosition")),[W0,J0]=Br(qr,{}),ob="SelectViewport",Y0=J(Me(function(t,n){const{__scopeSelect:r,nonce:i,...o}=t,s=uc(ob,r),c=J0(ob,r),l=Re(n,s.onViewportChange),d=B(0);return a(z,{children:[a("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:i}),a(dc.Slot,{scope:r,children:a(ye.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:te(o.onScroll,u=>{const p=u.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:m}=c;if(m?.current&&f){const v=Math.abs(d.current-p.scrollTop);if(v>0){const g=window.innerHeight-Qt*2,h=parseFloat(f.style.minHeight),b=parseFloat(f.style.height),w=Math.max(h,b);if(w<g){const _=w+v,R=Math.min(g,_),I=_-R;f.style.height=R+"px",f.style.bottom==="0px"&&(p.scrollTop=I>0?I:0,f.style.justifyContent="flex-end")}}}d.current=p.scrollTop})})})]})},"SelectViewport")),[J2,Y2]=Br("SelectGroup"),Zu="SelectItem",[X0,ab]=Br(Zu),Q0=J(Me(function(t,n){const{__scopeSelect:r,value:i,disabled:o=!1,textValue:s,...c}=t,l=or(Zu,r),d=uc(Zu,r),u=l.value===i,[p,f]=x(s??""),[m,v]=x(!1),g=ht(R=>d.itemRefCallback?.(R,i,o)),h=Re(n,g),b=Et(),w=B("touch"),_=Me(()=>{o||(l.onValueChange(i),l.onOpenChange(!1))},"handleSelect");return a(X0,{scope:r,value:i,disabled:o,textId:b,isSelected:u,onItemTextChange:ae(R=>{f(I=>I||(R?.textContent??"").trim())},[]),children:a(dc.ItemSlot,{scope:r,value:i,disabled:o,textValue:p,children:a(ye.div,{role:"option","aria-labelledby":b,"data-highlighted":m?"":void 0,"aria-selected":u&&m,"data-state":u?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...c,ref:h,onFocus:te(c.onFocus,()=>v(!0)),onBlur:te(c.onBlur,()=>v(!1)),onClick:te(c.onClick,()=>{w.current!=="mouse"&&_()}),onPointerUp:te(c.onPointerUp,()=>{w.current==="mouse"&&_()}),onPointerDown:te(c.onPointerDown,R=>{w.current=R.pointerType}),onPointerMove:te(c.onPointerMove,R=>{w.current=R.pointerType,o?d.onItemLeave?.():w.current==="mouse"&&R.currentTarget.focus({preventScroll:!0})}),onPointerLeave:te(c.onPointerLeave,R=>{R.currentTarget===document.activeElement&&d.onItemLeave?.()}),onKeyDown:te(c.onKeyDown,R=>{o||R.target!==R.currentTarget||d.searchRef?.current!==""&&R.key===" "||(N0.includes(R.key)&&_(),R.key===" "&&R.preventDefault())})})})})},"SelectItem")),pc="SelectItemText",Z0=J(Me(function(t,n){const{__scopeSelect:r,className:i,style:o,...s}=t,c=or(pc,r),l=uc(pc,r),d=ab(pc,r),u=D0(pc,r),[p,f]=x(null),m=ht(_=>l.itemTextRefCallback?.(_,d.value,d.disabled)),v=Re(n,f,d.onItemTextChange,m),g=p?.textContent,h=ke(()=>a("option",{value:d.value,disabled:d.disabled,children:g},d.value),[d.disabled,d.value,g]),{onNativeOptionAdd:b,onNativeOptionRemove:w}=u;return Ze(()=>(b(h),()=>w(h)),[b,w,h]),a(z,{children:[a(ye.span,{id:d.textId,...s,ref:v}),d.isSelected&&c.valueNode&&!c.valueNodeHasChildren&&!Zo(c.value)?sn(s.children,c.valueNode):null]})},"SelectItemText")),eD="SelectItemIndicator",tD=J(Me(function(t,n){const{__scopeSelect:r,...i}=t;return ab(eD,r).isSelected?a(ye.span,{"aria-hidden":!0,...i,ref:n}):null},"SelectItemIndicator")),nD="SelectBubbleInput",rD=J(Me(function({__scopeSelect:t,...n},r){const i=or(nD,t),{value:o,onValueChange:s,required:c,disabled:l,name:d,autoComplete:u,form:p}=i,{nativeOptions:f,nativeSelectKey:m}=i,v=B(null),g=Re(r,v),h=o??"",b=tb(h),w=Array.from(f).some(_=>(_.props.value??"")==="");return V(()=>{const _=v.current;if(!_)return;const R=window.HTMLSelectElement.prototype,I=Object.getOwnPropertyDescriptor(R,"value").set;if(b!==h&&I){const T=new Event("change",{bubbles:!0});I.call(_,h),_.dispatchEvent(T)}},[b,h]),a(ye.select,{"aria-hidden":!0,required:c,tabIndex:-1,name:d,autoComplete:u,disabled:l,form:p,onChange:_=>s(_.target.value),...n,style:{...Tv,...n.style},ref:g,defaultValue:h,children:[Zo(o)&&!w?a("option",{value:""}):null,Array.from(f)]},m)},"SelectBubbleInput"));function sb(e){return typeof e=="function"}Me(sb,"isFunction");function Zo(e){return e===""||e===void 0}Me(Zo,"shouldShowPlaceholder");function ep(e){const t=ht(e),n=B(""),r=B(0),i=ae(s=>{const c=n.current+s;t(c),Me((function l(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}),"updateSearch")(c)},[t]),o=ae(()=>{n.current="",window.clearTimeout(r.current)},[]);return V(()=>()=>window.clearTimeout(r.current),[]),[n,i,o]}Me(ep,"useTypeaheadSearch");function tp(e,t,n){const r=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let o=cb(e,Math.max(i,0));r.length===1&&(o=o.filter(c=>c!==n));const s=o.find(c=>c.textValue.toLowerCase().startsWith(r.toLowerCase()));return s!==n?s:void 0}Me(tp,"findNextItem");function cb(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Me(cb,"wrapArray");var lb="__codemem-empty-select__";function iD(){return a("svg",{"aria-hidden":"true",fill:"none",height:"14",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",width:"14",children:[a("title",{children:"Open"}),a("path",{d:"m6 9 6 6 6-6"})]})}function oD(){return a("svg",{"aria-hidden":"true",fill:"none",height:"14",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",width:"14",children:[a("title",{children:"Selected"}),a("path",{d:"M20 6 9 17l-5-5"})]})}function np(e){return e===""?lb:e}function aD(e){return e===lb?"":e}function ar({ariaLabel:e,className:t,contentClassName:n,disabled:r=!1,id:i,itemClassName:o,onValueChange:s,options:c,placeholder:l,triggerClassName:d,value:u,viewportClassName:p}){const f=u?np(u):void 0;return a(L0,{disabled:r,onValueChange:m=>s(aD(m)),value:f,children:[a(O0,{"aria-label":e,className:d??t,"data-value":u,id:i,type:"button",children:[a(M0,{placeholder:l}),a(F0,{className:"sync-radix-select-icon","aria-hidden":"true",children:a(iD,{})})]}),a(U0,{children:a(G0,{className:n,position:"popper",children:a(Y0,{className:p,children:c.map(m=>a(Q0,{className:o,disabled:m.disabled,value:np(m.value),children:[a(Z0,{children:m.label}),a(tD,{className:"sync-radix-select-indicator",children:a(oD,{})})]},np(m.value)))})})})]})}function sD({descriptionId:e,request:t}){const[n,r]=x("choice"),i=t.actors.find(b=>b.isLocal)?.actorId||t.actors[0]?.actorId||"",[o,s]=x(i),[c,l]=x("");V(()=>{r("choice");const b=t.actors.find(_=>_.isLocal)?.actorId||t.actors[0]?.actorId||"",w=t.actors.find(_=>_.actorId!==b)?.actorId||"";s(b),l(w)},[t]);const d=t.actors.find(b=>b.actorId===o)||t.actors[0],u=t.actors.filter(b=>b.actorId!==o),p=u.find(b=>b.actorId===c)||u[0],f=t.actors.map(b=>({label:a(z,{children:[b.label,b.isLocal?" (You)":""]}),value:b.actorId})),m=u.map(b=>({label:`${b.label}${b.isLocal?" (You)":""}`,value:b.actorId})),v=!!(d?.actorId&&p?.actorId),g=()=>{!d?.actorId||!p?.actorId||ir({action:"merge",primaryActorId:d.actorId,secondaryActorId:p.actorId})},h=b=>{const w=b.target instanceof HTMLElement?b.target:null;b.defaultPrevented||b.isComposing||b.key!=="Enter"||w?.closest(".sync-dialog-radio-list")&&v&&(b.preventDefault(),g())};return n==="choice"?a("div",{className:"sync-dialog-stack",children:a("ul",{className:"sync-dialog-choice-list",children:[a("li",{children:a("button",{autoFocus:!0,className:"settings-button","data-primary-action":"true","data-sync-primary-action":"true",onClick:()=>r("merge"),type:"button",children:"These are both me"})}),a("li",{children:a("button",{className:"settings-button",onClick:()=>ir({action:"different-people"}),type:"button",children:"These are different people"})}),a("li",{children:a("button",{className:"settings-button",onClick:()=>ir({action:"cancel"}),type:"button",children:"Decide later"})})]})}):a("div",{className:"sync-dialog-stack",onKeyDown:b=>{h(b),Li(b,{onSubmit:g,disabled:!v})},children:[a("div",{className:"small",id:e,children:"Choose which person should remain after combining these duplicates."}),a(S0,{ariaDescribedby:e,ariaLabel:"Person to keep after combining duplicates",autoFocusValue:o,indicatorClassName:"sync-dialog-radio-indicator",itemClassName:"sync-dialog-radio-option",itemLabelClassName:"sync-dialog-radio-label",name:"syncDuplicatePrimaryActor",onValueChange:s,options:f,rootClassName:"sync-dialog-radio-list",value:o}),a("div",{className:"field",children:[a("label",{className:"small",htmlFor:"syncDuplicateSecondaryActor",children:"Person to combine into the selected record"}),a(ar,{ariaLabel:"Person to combine into the selected record",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:m.length===0,id:"syncDuplicateSecondaryActor",itemClassName:"sync-radix-select-item",onValueChange:l,options:m,placeholder:"No merge target available",triggerClassName:"sync-radix-select-trigger sync-dialog-input",value:p?.actorId||"",viewportClassName:"sync-radix-select-viewport"})]}),a("div",{className:"sync-dialog-actions",children:[a("button",{className:"settings-button",onClick:()=>r("choice"),type:"button",children:"Back"}),a("button",{className:"settings-button","data-primary-action":"true",disabled:!v,onClick:g,type:"button",children:"Combine people"})]})]})}function cD({descriptionId:e,request:t,titleId:n}){const[r,i]=x(t.kind==="input"&&t.initialValue||""),[o,s]=x(null),c=t.kind!=="duplicate-person",l="syncDialogInputError";V(()=>{t.kind==="input"&&(i(t.initialValue||""),s(null))},[t]);const d=c&&t.cancelLabel||"Cancel",u=c?t.confirmLabel||(t.kind==="confirm"?"Confirm":"Save"):"Confirm",p=()=>{if(t.kind==="confirm"){ir(!0);return}if(t.kind==="duplicate-person")return;const f=r.trim(),m=t.validate?.(f)||null;if(m){s(m);return}ir(f)};return a("div",{className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:n,children:t.title}),a(kr,{ariaLabel:`Close ${t.title}`,onClick:()=>ir(t.kind==="confirm"?!1:null)})]}),a("div",{className:"modal-body",children:[t.kind!=="duplicate-person"?a("div",{className:"small",id:e,children:t.description}):null,t.kind==="duplicate-person"?a("div",{className:"small",id:e,children:t.summary}):null,t.kind==="input"?a("div",{className:"field",children:[t.suggestions?.length?a(t0,{"aria-describedby":o?`${e} ${l}`:e,autoFocus:!0,className:o?"sync-dialog-input sync-field-error":"sync-dialog-input","data-sync-primary-action":"true",onSubmit:p,onValueChange:f=>{i(f),o&&s(null)},placeholder:t.placeholder,suggestions:t.suggestions,value:r}):a(Te,{"aria-describedby":o?`${e} ${l}`:e,autoFocus:!0,className:o?"sync-dialog-input sync-field-error":"sync-dialog-input","data-sync-primary-action":"true",onInput:f=>{i(f.currentTarget.value),o&&s(null)},onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),p())},placeholder:t.placeholder,type:"text",value:r}),o?a("div",{className:"sync-field-hint",id:l,children:o}):null]}):null,t.kind==="duplicate-person"?a(sD,{descriptionId:e,request:t}):null]}),a("div",{className:"modal-footer",children:[a("div",{className:"small"}),a("div",{className:"sync-dialog-actions",children:[a("button",{className:"settings-button","data-sync-dialog-action":"cancel",onClick:()=>ir(t.kind==="confirm"?!1:null),type:"button",children:d}),t.kind!=="duplicate-person"?a("button",{autoFocus:!0,className:`settings-button ${e0(t.kind==="confirm"?t.tone:void 0)}`,"data-sync-dialog-action":"confirm",onClick:p,type:"button",children:u}):null]})]})]})}function lD(){const[e,t]=x(Xx());V(()=>(Wy(t),()=>{Qx(t)&&Wy(null)}),[]);const n=!!e,r=ke(()=>`sync-dialog-title-${e?.kind||"none"}`,[e?.kind]),i=ke(()=>`sync-dialog-description-${e?.kind||"none"}`,[e?.kind]);return e?a(Qn,{ariaDescribedby:i,ariaLabelledby:r,contentClassName:"modal",contentId:"syncDialog",onInteractOutside:l=>{const d=l.detail?.originalEvent?.target;d instanceof Element&&d.closest(".autocomplete-popover")&&l.preventDefault()},onOpenAutoFocus:l=>{const d=document.querySelector('#syncDialog [data-sync-primary-action="true"]');if(e?.kind==="input"&&d){l.preventDefault(),d.focus();return}const u=(e?.kind==="confirm"?e.autoFocusAction??"confirm":"confirm")==="cancel"?'#syncDialog [data-sync-dialog-action="cancel"]':'#syncDialog [data-sync-dialog-action="confirm"]',p=document.querySelector(u);p&&(l.preventDefault(),p.focus())},onOpenChange:l=>{l||ir(e?.kind==="confirm"?!1:null)},open:n,overlayClassName:"modal-backdrop",overlayId:"syncDialogBackdrop",children:e?a(cD,{descriptionId:i,request:e,titleId:r}):null}):null}var Ur=null;function fc(){Ur?.isConnected||(Ur=document.getElementById("syncDialogMount"),Ur||(Ur=document.createElement("div"),Ur.id="syncDialogMount",document.body.appendChild(Ur)),Ue(a(lD,{}),Ur))}function hn(e){return fc(),zu("confirm")?new Promise(t=>{Ku(n=>t(!!n)),sc({kind:"confirm",...e})}):Promise.resolve(!1)}function rp(e){return fc(),zu("input")?new Promise(t=>{Ku(n=>t(typeof n=="string"?n:null)),sc({kind:"input",...e})}):Promise.resolve(null)}function dD(e){return fc(),zu("duplicate-person")?new Promise(t=>{Ku(n=>t(n||{action:"cancel"})),sc({kind:"duplicate-person",...e})}):Promise.resolve(Zx({kind:"duplicate-person",...e}))}function uD(e){return e.readiness==="ready"?null:"Legacy Space management needs the coordinator URL, target group, and admin secret before it can list Spaces or change transport memberships."}function pD(e){const t=String(e||"active").trim();return t?t.replaceAll("_"," "):"active"}function db(e){const t=String(e.label||"").trim()||"Untitled Space",n=pD(e.status),r=String(e.kind||"user").replaceAll("_"," "),i=String(e.scope_id||"").trim()||"unknown",o=e.membership_epoch==null?"—":String(e.membership_epoch);return{title:t,summary:`${n} Space · ${r}`,advancedDetail:`Space ID ${i} · Membership epoch ${o}`}}function fD(e){const t={active:"Space access active",revoked:"Space access revoked",not_member:"No Space access"},n=e.role.replaceAll("_"," "),r=e.status==="not_member"?t[e.status]:`${t[e.status]} · ${n}`,i=e.membershipEpoch==null?"—":String(e.membershipEpoch);return{statusLabel:t[e.status],detail:r,advancedDetail:`Device ID ${e.deviceId} · Membership epoch ${i}`}}function mD(e,t,n){return`Revoke ${t||"this device"} from ${db(e).title}?`}function hD(e,t,n=Fs()){const r=Bs(e,n),i=new Map(t.map(o=>[String(o.device_id||"").trim(),o]).filter(([o])=>o.length>0));return e.map(o=>{const s=String(o.device_id||"").trim();if(!s)return null;const c=i.get(s),l=String(c?.status||"").trim(),d=c?l==="revoked"?"revoked":"active":"not_member",u=typeof c?.membership_epoch=="number"&&Number.isFinite(c.membership_epoch)?Math.trunc(c.membership_epoch):null;return{deviceId:s,displayName:r.get(s)||"Unnamed device",enabled:o.enabled!==!1&&o.enabled!==0,status:d,role:String(c?.role||"member"),membershipEpoch:u,updatedAt:c?.updated_at?String(c.updated_at):null}}).filter(o=>o!==null).sort((o,s)=>{const c={active:0,revoked:1,not_member:2};return c[o.status]-c[s.status]||o.displayName.localeCompare(s.displayName,void 0,{numeric:!0})})}function gD(e,t,n,r){const i=String(n||"").trim();return r||e.length>0||!i?e:t.filter(o=>String(o.group_id||"").trim()===i)}var X2=8;function vD(){return{loaded:!1,loading:!1,availability:"unknown",error:"",includeInactive:!1,devicesLoaded:!1,scopes:[],membersByScope:new Map,memberAvailabilityByScope:new Map,devices:[],createScopeId:"",createLabel:"",createKind:"team",createPanelOpen:!1,actionPendingKey:"",actionPendingKind:"",loadGeneration:0,recoveryAnnouncement:"",recoveryFocusPending:!1,recoveryRetryRequested:!1}}function mc(e){if(!e||typeof e!="object")throw new Error("Invalid list payload");const t=e.items;if(!Array.isArray(t))throw new Error("Invalid list payload");return t}function qe(e){let t=P.groupScopeManagementDrafts.get(e);return t||(t=vD(),P.groupScopeManagementDrafts.set(e,t)),t}function Ke(e,t){P.groupScopeManagementDrafts.set(e,t)}function ip(e,t){const n=e instanceof Error?e.message:"";return n.includes("group_archived")||n.includes("Group is archived")?"Restore this legacy coordinator group before changing Space access.":n.includes("group_not_found")||n.includes("Group not found")?"This legacy coordinator group no longer exists. Refresh Advanced administration.":n.includes("scope_not_found")||n.includes("Scope not found")?"This Space no longer exists. Refresh legacy Spaces before retrying.":n.includes("scope_not_active")||n.includes("Scope is not active")?"Restore this legacy Space before changing its access.":n.includes("scopeId already exists")?"A Space already uses that ID. Choose a different Space ID or refresh legacy Spaces. Sharing policy is unchanged.":n.includes("device_not_enrolled_for_scope_group")||n.includes("device must be enrolled")?"This device is no longer enrolled in the legacy coordinator group. Refresh devices before retrying.":n.includes("membership_not_found")?"This device no longer has access to the Space. Refresh legacy Spaces.":t}function ea(){Z("Coordinator data changed or is refreshing. Wait for recovery to finish, then try again.","warning")}function Vi(e,t){return e.availability==="fresh"&&!e.loading&&(!t||e.memberAvailabilityByScope.get(t)==="fresh")&&xn(P.recovery,"status","groups")}async function yD(e,t,n){const r=new Array(e.length);let i=0;async function o(){for(;i<e.length;){const s=i++;r[s]=await n(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),r}async function Gr(e,t,n=qe(e).includeInactive){const r=qe(e),i=r.loadGeneration+1;Ke(e,{...r,loading:!0,error:"",includeInactive:n,loadGeneration:i,recoveryAnnouncement:r.recoveryRetryRequested?r.recoveryAnnouncement:""});const o=()=>P.groupScopeManagementDrafts.get(e)?.loadGeneration===i;t();try{const[l,d]=await Promise.all([IC(e,n),mm(e,!0)]);if(!o())return;const u=mc(l),p=mc(d),f=await yD(u.slice(0,8),4,async w=>{const _=String(w.scope_id||"").trim();if(!_)return{scopeId:_,attempted:!0,members:[]};try{return{scopeId:_,attempted:!0,members:mc(await fm(e,_,!0))}}catch{return{scopeId:_,attempted:!0}}});if(!o())return;const m=qe(e),v=[...f,...u.slice(8).map(w=>({scopeId:String(w.scope_id||"").trim(),attempted:!1}))],g=new Map,h=new Map;for(const w of v){if(!w.scopeId)continue;if(w.members){g.set(w.scopeId,w.members),h.set(w.scopeId,"fresh");continue}const _=m.membersByScope.get(w.scopeId),R=m.memberAvailabilityByScope.get(w.scopeId);_&&(R==="fresh"||R==="stale")?(g.set(w.scopeId,_),h.set(w.scopeId,"stale")):h.set(w.scopeId,w.attempted?"unavailable":"deferred")}const b=v.filter(w=>w.attempted&&w.scopeId&&!w.members).length;Ke(e,{...m,loaded:!0,loading:!1,availability:"fresh",recoveryAnnouncement:b?"":m.recoveryAnnouncement,error:b?`Membership details could not be refreshed for ${b} ${b===1?"Space":"Spaces"}. Successfully loaded Space data remains available.`:"",includeInactive:n,devicesLoaded:!0,scopes:u,devices:p,membersByScope:g,memberAvailabilityByScope:h,actionPendingKey:"",actionPendingKind:""})}catch{if(!o())return;const l=qe(e),d=l.availability==="fresh"||l.availability==="stale";Ke(e,{...l,availability:d?"stale":"unavailable",loading:!1,recoveryAnnouncement:"",error:d?"Legacy Spaces could not be refreshed. Previously loaded Space and membership details are still shown.":"Legacy Spaces are unavailable. No empty Space list is being assumed."})}if(!o())return;const s=qe(e);if(s.recoveryRetryRequested&&s.availability==="fresh"&&![...s.memberAvailabilityByScope.values()].some(l=>l==="stale"||l==="unavailable")){const l=[...s.memberAvailabilityByScope.values()].filter(d=>d==="deferred").length;Ke(e,{...s,recoveryAnnouncement:l?`Spaces refreshed. Membership details for ${l} ${l===1?"Space":"Spaces"} can be loaded on demand.`:"Spaces and membership details refreshed.",recoveryFocusPending:!0,recoveryRetryRequested:!1})}else s.recoveryRetryRequested&&Ke(e,{...s,recoveryAnnouncement:"Retry finished, but some Space data still needs attention. Retained details remain unchanged.",recoveryFocusPending:!0,recoveryRetryRequested:!1});t();const c=qe(e);c.recoveryFocusPending&&(Ke(e,{...c,recoveryFocusPending:!1}),queueMicrotask(()=>document.getElementById(`coordinatorAdminSpacesStatus-${e}`)?.focus()))}function op(e,t){P.groupScopeManagementOpen.add(e),qe(e),t(),Gr(e,t)}function ub(e,t){P.groupScopeManagementOpen.delete(e),t()}async function bD(e,t,n){const r=qe(e);if(!Vi(r)){ea();return}if(r.actionPendingKey)return;const i=r.loadGeneration,o=P.loadGeneration;Ke(e,{...r,actionPendingKey:`load:${t}`,actionPendingKind:"load"}),n();try{const s=await fm(e,t,!0),c=qe(e);if(c.loadGeneration!==i||P.loadGeneration!==o||!Vi(c)){c.actionPendingKey===`load:${t}`&&(Ke(e,{...c,actionPendingKey:"",actionPendingKind:""}),n()),ea();return}const l=new Map(c.membersByScope);l.set(t,mc(s));const d=new Map(c.memberAvailabilityByScope);d.set(t,"fresh"),Ke(e,{...c,membersByScope:l,memberAvailabilityByScope:d,actionPendingKey:"",actionPendingKind:"",error:""})}catch{const s=qe(e);if(s.loadGeneration!==i)return;const c=new Map(s.memberAvailabilityByScope);c.set(t,s.membersByScope.has(t)?"stale":"unavailable"),Ke(e,{...s,memberAvailabilityByScope:c,actionPendingKey:"",actionPendingKind:"",error:"Membership details could not be loaded. Existing Space data is unchanged."})}n()}async function _D(e,t){const n=qe(e);if(!Vi(n)){ea();return}if(n.actionPendingKey)return;const r=n.createScopeId.trim(),i=n.createLabel.trim(),o=n.createKind.trim()||"team";if(!r||!i){Z("Enter a Space ID and label before creating a Space.","warning");return}Ke(e,{...n,actionPendingKey:`create:${r}`,actionPendingKind:"create",error:""}),t();try{await kC(e,{scope_id:r,label:i,kind:o});const s=qe(e);Ke(e,{...s,createScopeId:"",createLabel:"",createKind:"team",createPanelOpen:!1,actionPendingKey:"",actionPendingKind:""}),Z("Space created. Grant devices explicitly before data can sync."),await Gr(e,t,s.includeInactive),queueMicrotask(()=>document.getElementById(`coordinatorAdminCreateSpaceTrigger-${e}`)?.focus())}catch(s){Ke(e,{...qe(e),actionPendingKey:"",actionPendingKind:"",error:ip(s,"Could not create the legacy Space. Sharing policy is unchanged; retry after coordinator recovery.")}),t()}}async function wD(e,t,n,r){const i=qe(e);if(!Vi(i,t)){ea();return}const o=`grant:${t}:${n}`;if(!i.actionPendingKey){Ke(e,{...i,actionPendingKey:o,actionPendingKind:"grant",error:""}),r();try{await TC(e,t,{device_id:n,role:"member"});const s=qe(e);Ke(e,{...s,actionPendingKey:"",actionPendingKind:""}),Z("Device granted access to the Space."),await Gr(e,r,s.includeInactive)}catch(s){Ke(e,{...qe(e),actionPendingKey:"",actionPendingKind:"",error:ip(s,"Could not grant legacy Space transport access. Sharing policy is unchanged; retry after coordinator recovery.")}),r()}}}async function SD(e,t,n,r,i){const o=String(t.scope_id||"").trim();if(!o)return;const s=qe(e);if(!Vi(s,o)){ea();return}const c=s.loadGeneration,l=P.loadGeneration;if(!await hn({title:mD(t,r,n),description:"Revocation blocks future sync for this Space. It does not remove data already copied to the revoked device; offline devices, backups, copied databases, malicious peers, or old versions may retain data.",confirmLabel:"Revoke membership",cancelLabel:"Keep membership",tone:"danger"}))return;const d=qe(e),u=d.scopes.find(m=>String(m.scope_id||"").trim()===o),p=d.membersByScope.get(o)?.find(m=>String(m.device_id||"")===n&&String(m.status||"active")==="active");if(d.loadGeneration!==c||P.loadGeneration!==l||!Vi(d,o)||!u||!p||d.actionPendingKey){Z("Space membership data changed while confirmation was open. Review current access and try again.","warning");return}const f=`revoke:${o}:${n}`;Ke(e,{...d,actionPendingKey:f,actionPendingKind:"revoke",error:""}),i();try{await PC(e,o,n);const m=qe(e);Ke(e,{...m,actionPendingKey:"",actionPendingKind:""}),Z("Space access revoked. Future sync is blocked for that device."),await Gr(e,i,m.includeInactive)}catch(m){Ke(e,{...qe(e),actionPendingKey:"",actionPendingKind:"",error:ip(m,"Could not revoke legacy Space transport access. Sharing policy is unchanged; retry after coordinator recovery.")}),i()}}function CD(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=$t(P.devicesSnapshotTarget)?C.lastCoordinatorAdminDevices:[],c=gD(n.devices,s,e,n.devicesLoaded),l=hD(c,n.membersByScope.get(o)??[],P.unnamedDeviceAliases);return l.length?y("div",{class:"coordinator-admin-scope-member-list"},l.map(d=>{const u=`${n.actionPendingKind}:${o}:${d.deviceId}`,p=n.actionPendingKey===u,f=d.enabled&&d.status!=="active",m=d.status==="active",v=fD(d);return y("div",{class:"coordinator-admin-scope-member-row",key:d.deviceId},y("div",{class:"coordinator-admin-scope-member-copy"},y("strong",null,d.displayName),y("span",null,v.detail),y("details",{class:"coordinator-admin-diagnostics"},y("summary",null,"Diagnostics"),y("span",{class:"peer-meta"},v.advancedDetail)),d.enabled?null:y("span",null,"Device is disabled in this coordinator group.")),y("div",{class:"peer-actions"},f?y("button",{class:"settings-button",disabled:!r||!!n.actionPendingKey,onClick:()=>{wD(e,o,d.deviceId,i)},type:"button"},p&&n.actionPendingKind==="grant"?"Granting…":"Grant access"):null,m?y("button",{class:"settings-button danger",disabled:!r||!!n.actionPendingKey,onClick:()=>{SD(e,t,d.deviceId,d.displayName,i)},type:"button"},p&&n.actionPendingKind==="revoke"?"Revoking…":"Revoke access"):null))})):y("div",{class:"peer-submeta coordinator-admin-empty-state",role:"status"},"No devices are enrolled in this coordinator group yet. Enroll a device before granting this Space.")}function RD(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=db(t),c=n.memberAvailabilityByScope.get(o),l=n.actionPendingKey===`load:${o}`,d=c==="stale"||c==="unavailable"||c==="deferred";return y("div",{class:"peer-card peer-card--padded coordinator-admin-scope-card",key:o||s.title},y("div",{class:"peer-title"},y("h5",{class:"coordinator-admin-card-title"},s.title),y("span",{class:"badge actor-badge"},"Legacy Space")),y("div",{class:"peer-submeta"},s.summary),y("details",{class:"coordinator-admin-diagnostics"},y("summary",null,"Diagnostics"),y("div",{class:"peer-meta"},s.advancedDetail)),y("div",{class:"peer-submeta"},"Devices below are enrolled in the coordinator group; only active Space members can sync this transport boundary."),c==="stale"?y("div",{class:"peer-submeta coordinator-admin-inline-warning",role:"status"},"Membership refresh failed for this Space. Previously loaded memberships are shown and changes are disabled."):c==="unavailable"?y("div",{class:"peer-submeta coordinator-admin-inline-warning",role:"status"},"Membership details are unavailable for this Space. No empty membership list is being assumed."):c==="deferred"?y("div",{class:"peer-submeta coordinator-admin-inline-warning",role:"status"},"Membership details were deferred to keep this large Space list bounded. Load them before changing access."):null,d?y("button",{class:"settings-button",disabled:!!n.actionPendingKey,onClick:()=>{bD(e,o,i)},type:"button"},l?"Loading membership…":c==="stale"?"Refresh membership":"Load membership"):null,c==="unavailable"||c==="deferred"?null:CD(e,t,n,r&&c==="fresh",i))}function ap(e,t,n){const r=[...t.memberAvailabilityByScope.values()].filter(s=>s==="stale"||s==="unavailable").length,i=t.availability==="stale"||t.availability==="unavailable"||r>0,o=()=>{const s=qe(e);s.loading||s.actionPendingKey||(Ke(e,{...s,recoveryAnnouncement:"Retrying Spaces and membership details…",recoveryRetryRequested:!0}),Gr(e,n,s.includeInactive))};return y("div",{"aria-atomic":"true","aria-live":"polite",class:i?"coordinator-admin-inline-warning coordinator-admin-recovery-notice":t.recoveryAnnouncement?"peer-meta coordinator-admin-recovery-status":"coordinator-admin-recovery-status",id:`coordinatorAdminSpacesStatus-${e}`,role:"status",tabIndex:-1},i?y(z,null,y("div",{class:"coordinator-admin-legacy-notice-copy"},y("h4",{class:"coordinator-admin-drawer-title"},"Spaces need attention"),t.recoveryAnnouncement?y("p",{class:"peer-submeta"},t.recoveryAnnouncement):null,y("p",{class:"peer-submeta"},t.availability==="unavailable"?"Current Space data could not be loaded. No empty result is being shown, and no data loss is implied.":t.availability==="stale"?"Previously loaded Spaces are shown. Mutations are disabled until a retry succeeds.":`Membership details need recovery for ${r} ${r===1?"Space":"Spaces"}. Successfully loaded Spaces remain current.`)),y("button",{class:"settings-button",disabled:t.loading||!!t.actionPendingKey,onClick:o,type:"button"},t.loading?"Retrying…":"Retry")):t.recoveryAnnouncement)}function ID(e){const{groupId:t,ready:n,summary:r,renderShell:i}=e,o=P.groupScopeManagementDrafts.get(t);if(!o)return null;const s=uD(r);if(s)return y("div",{class:"peer-meta coordinator-admin-inline-warning"},s);if(o.availability==="unavailable")return y(z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),y("div",{class:"peer-submeta"},"Coordinator groups discover and enroll devices. Spaces are technical transport boundaries here. These controls do not manage policy Team membership or Project access in Sharing."),ap(t,o,i));if(!o.loaded)return y(z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),y("div",{class:"peer-submeta"},"Coordinator groups discover and enroll devices. Spaces are technical transport boundaries here. These controls do not manage policy Team membership or Project access in Sharing."),ap(t,o,i),y("div",{"aria-live":"polite",class:"peer-submeta",role:"status"},"Loading Spaces…"));const c=!n||o.availability!=="fresh"||!!o.actionPendingKey||o.loading,l=o.loading||!!o.actionPendingKey,d=`coordinatorAdminCreateSpacePanel-${t}`,u=`coordinatorAdminCreateSpaceTrigger-${t}`,p=`coordinatorAdminCreateSpaceId-${t}`;return y(z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),y("div",{class:"peer-submeta"},"Coordinator groups discover and enroll devices. Spaces are technical transport boundaries here. These controls do not manage policy Team membership or Project access in Sharing."),ap(t,o,i),y(zo,{onOpenChange:f=>{Ke(t,{...qe(t),createPanelOpen:f}),i(),f&&queueMicrotask(()=>document.getElementById(p)?.focus())},open:o.createPanelOpen},y(z,null,y("div",{class:"section-actions coordinator-admin-space-toolbar"},y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:`coord-admin-domain-inactive-${t}`},"Show inactive Spaces"),y(Gi,{"aria-labelledby":`coord-admin-domain-inactive-${t}`,checked:o.includeInactive,className:"coordinator-admin-switch",disabled:l,onCheckedChange:f=>{qe(t).actionPendingKey||Gr(t,i,f)},thumbClassName:"coordinator-admin-switch-thumb"})),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:l,onClick:()=>{qe(t).actionPendingKey||Gr(t,i,o.includeInactive)},type:"button"},o.loading?"Refreshing…":"Refresh"),y(Cu,{"aria-controls":d,"aria-expanded":o.createPanelOpen,class:"settings-button coordinator-admin-scope-trigger",id:u,type:"button"},"Create legacy Space"))),y(Wo,{"aria-busy":o.actionPendingKind==="create"?"true":"false","aria-labelledby":u,class:"coordinator-admin-create-space-panel",forceMount:!0,id:d},y("form",{class:"coordinator-admin-form",onSubmit:f=>{f.preventDefault(),!c&&_D(t,i)}},y("p",{class:"peer-submeta"},"Create a Space only for legacy transport or recovery. Team membership and Project access stay in Sharing."),y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"Space ID"),y(Te,{class:"peer-scope-input",disabled:c,id:p,onInput:f=>{const m=qe(t);Ke(t,{...m,createScopeId:String(f.currentTarget.value||"")})},placeholder:"acme-work",type:"text",value:o.createScopeId})),y("label",{class:"coordinator-admin-field"},y("span",null,"Label"),y(Te,{class:"peer-scope-input",disabled:c,onInput:f=>{const m=qe(t);Ke(t,{...m,createLabel:String(f.currentTarget.value||"")})},placeholder:"Acme Work",type:"text",value:o.createLabel})),y("label",{class:"coordinator-admin-field"},y("span",null,"Kind"),y(Te,{class:"peer-scope-input",disabled:c,onInput:f=>{const m=qe(t);Ke(t,{...m,createKind:String(f.currentTarget.value||"")})},placeholder:"team",type:"text",value:o.createKind}))),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:c,type:"submit"},o.actionPendingKind==="create"?"Creating…":"Create Space")))))),o.error?y("div",{"aria-live":"assertive",class:"peer-submeta coordinator-admin-error",role:"alert"},o.error):null,o.scopes.length?y("div",{class:"coordinator-admin-scope-card-list"},o.scopes.map(f=>RD(t,f,o,n&&o.availability==="fresh"&&!o.loading,i))):y("div",{class:"peer-meta coordinator-admin-empty-state",role:"status"},"No Spaces are defined for this coordinator group yet. Create a Space only for legacy transport or recovery, then grant specific devices. Sharing policy remains separate."))}function pb(){return y("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},y("title",null,"Chevron"),y("path",{d:"m9 18 6-6-6-6"}))}function kD(){return{projects_include:[],projects_exclude:[],auto_seed_scope:!0,default_space_scope_id:"",auto_grant_default_space_on_join:!1,loaded:!1,loading:!1,availability:"unknown",loadGeneration:0,recoveryAnnouncement:"",recoveryFocusPending:!1,recoveryRetryRequested:!1,saving:!1,error:""}}async function fb(e,t){const n=P.groupPreferencesDrafts.get(e)??kD(),r=n.loadGeneration+1;P.groupPreferencesDrafts.set(e,{...n,loading:!0,error:"",loadGeneration:r,recoveryAnnouncement:n.recoveryRetryRequested?n.recoveryAnnouncement:""});const i=()=>P.groupPreferencesDrafts.get(e)?.loadGeneration===r;t();try{const s=await LR(e);if(!i())return;const c=P.groupPreferencesDrafts.get(e)??n;P.groupPreferencesDrafts.set(e,{...c,projects_include:Array.isArray(s.projects_include)?[...s.projects_include]:[],projects_exclude:Array.isArray(s.projects_exclude)?[...s.projects_exclude]:[],auto_seed_scope:s.auto_seed_scope,default_space_scope_id:s.default_space_scope_id||"",auto_grant_default_space_on_join:s.auto_grant_default_space_on_join===!0,loaded:!0,loading:!1,availability:"fresh",saving:!1,error:"",recoveryAnnouncement:c.recoveryRetryRequested?"Group defaults refreshed. Current values are available.":c.recoveryAnnouncement,recoveryFocusPending:c.recoveryRetryRequested,recoveryRetryRequested:!1})}catch{if(!i())return;const s=P.groupPreferencesDrafts.get(e)??n,c=s.availability==="fresh"||s.availability==="stale",l=s.recoveryRetryRequested;P.groupPreferencesDrafts.set(e,{...s,loading:!1,availability:c?"stale":"unavailable",recoveryAnnouncement:l?"Retry finished, but group defaults are still unavailable. Retained values remain unchanged.":"",recoveryFocusPending:l,recoveryRetryRequested:!1,error:c?"Legacy group defaults could not be refreshed. Previously loaded values are still shown.":"Legacy group defaults are unavailable. No default values are being assumed."})}t();const o=P.groupPreferencesDrafts.get(e);o?.recoveryFocusPending&&(P.groupPreferencesDrafts.set(e,{...o,recoveryFocusPending:!1}),queueMicrotask(()=>document.getElementById(`coord-admin-group-defaults-recovery-${e}`)?.focus()))}async function sp(e,t){P.groupPreferencesOpen.add(e),t(),await fb(e,t)}function hc(e,t){P.groupPreferencesOpen.delete(e),t()}function mb(e,t){const n=P.groupPreferencesDrafts.get(e);n&&(P.groupPreferencesDrafts.set(e,{...n,recoveryAnnouncement:"Retrying group defaults…",recoveryRetryRequested:!0}),fb(e,t))}async function TD(e,t){const n=P.groupPreferencesDrafts.get(e);if(!n||n.availability!=="fresh"||n.loading||!xn(P.recovery,"status","groups")||n.saving)return;const r={projects_include:n.projects_include.length>0?[...n.projects_include]:null,projects_exclude:n.projects_exclude.length>0?[...n.projects_exclude]:null,auto_seed_scope:n.auto_seed_scope,default_space_scope_id:n.default_space_scope_id||null,auto_grant_default_space_on_join:n.auto_grant_default_space_on_join};P.groupPreferencesDrafts.set(e,{...n,saving:!0,error:""}),t();try{await $R(e,r),Z("Legacy coordinator group defaults saved. Sharing policy and Project access are unchanged."),hc(e,t)}catch{const i=P.groupPreferencesDrafts.get(e);if(!i)return;P.groupPreferencesDrafts.set(e,{...i,saving:!1,error:"Could not save legacy group defaults. Sharing policy is unchanged; retry after coordinator recovery."}),t()}}function PD(e,t,n){const r=P.groupPreferencesDrafts.get(e);if(!r)return null;const i=`coord-admin-group-defaults-recovery-${e}`;if(!r.loaded&&r.availability!=="unavailable")return y(z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Legacy group defaults"),y("div",{"aria-atomic":"true","aria-live":"polite",id:i,role:"status",tabIndex:-1},"Loading project defaults…"));if(r.availability==="unavailable")return y(z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Legacy group defaults"),y("div",{"aria-atomic":"true","aria-live":"polite",class:"coordinator-admin-inline-warning coordinator-admin-recovery-notice",id:i,role:"status",tabIndex:-1},y("div",{class:"coordinator-admin-legacy-notice-copy"},y("strong",null,"Group defaults are unavailable"),r.recoveryAnnouncement?y("span",{class:"peer-submeta"},r.recoveryAnnouncement):null,y("span",{class:"peer-submeta"},"Current values could not be loaded. No defaults are being assumed or changed.")),y("button",{class:"settings-button",disabled:r.loading,onClick:()=>mb(e,t),type:"button"},r.loading?"Retrying…":"Retry")));const o=`coord-admin-scope-autoseed-${e}`,s=`coord-admin-default-space-autogrant-${e}`,c=`coord-admin-scope-include-${e}`,l=`coord-admin-scope-exclude-${e}`,d=n&&r.availability==="fresh"&&!r.loading,u=!d||r.saving||!r.auto_seed_scope;return y(z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Legacy group defaults"),y("div",{"aria-atomic":"true","aria-live":"polite",class:r.availability==="stale"?"coordinator-admin-inline-warning coordinator-admin-recovery-notice":"coordinator-admin-recovery-status",id:i,role:"status",tabIndex:-1},r.availability==="stale"?y(z,null,y("span",{class:"peer-submeta"},"Previously loaded group defaults are shown. Saving is disabled until refresh succeeds."),r.recoveryAnnouncement?y("span",{class:"peer-submeta"},r.recoveryAnnouncement):null,y("button",{class:"settings-button",disabled:r.loading,onClick:()=>mb(e,t),type:"button"},r.loading?"Retrying…":"Retry")):r.recoveryAnnouncement),y("div",{class:"peer-submeta"},"Space access grants decide what new devices can sync. Advanced sharing rules only narrow future writes after Space access already exists."),y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:o},"Auto-apply advanced rules to new devices"),y(Gi,{"aria-labelledby":o,checked:r.auto_seed_scope,className:"coordinator-admin-switch",disabled:!d||r.saving,onCheckedChange:p=>{const f=P.groupPreferencesDrafts.get(e)??r;P.groupPreferencesDrafts.set(e,{...f,auto_seed_scope:p}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:s},"Auto-grant default Space on coordinator join"),y(Gi,{"aria-labelledby":s,checked:r.auto_grant_default_space_on_join,className:"coordinator-admin-switch",disabled:!d||r.saving||!r.default_space_scope_id,onCheckedChange:p=>{const f=P.groupPreferencesDrafts.get(e)??r;P.groupPreferencesDrafts.set(e,{...f,auto_grant_default_space_on_join:p}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),r.default_space_scope_id?y("div",{class:"peer-submeta"},"Default Space configured."):y("div",{class:"peer-submeta"},"No default Space has been created yet."),y("div",{class:"coordinator-admin-field"},y("span",{id:c},"Include template"),y(Gy,{"aria-labelledby":c,availableProjects:P.availableProjects,disabled:u,emptyLabel:"All projects allowed.",onValuesChange:p=>{const f=P.groupPreferencesDrafts.get(e)??r;P.groupPreferencesDrafts.set(e,{...f,projects_include:p}),t()},placeholder:"Add project",values:r.projects_include}),y("span",{class:"peer-submeta"},"Leave empty to allow every project inside the granted Space. Type to search or create a new name.")),y("div",{class:"coordinator-admin-field"},y("span",{id:l},"Exclude template"),y(Gy,{"aria-labelledby":l,availableProjects:P.availableProjects,disabled:u,emptyLabel:"Nothing excluded.",onValuesChange:p=>{const f=P.groupPreferencesDrafts.get(e)??r;P.groupPreferencesDrafts.set(e,{...f,projects_exclude:p}),t()},placeholder:"Add project",values:r.projects_exclude})),r.error?y("div",{class:"peer-submeta coordinator-admin-error"},r.error):null,y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:!d||r.saving,onClick:()=>{TD(e,t)},type:"button"},r.saving?"Saving…":"Save defaults"),y("button",{class:"settings-button",disabled:r.saving,onClick:()=>hc(e,t),type:"button"},"Cancel")))}function ND(e){const t=P.teamSetupGuide;if(!t)return null;const n=Gu(t.groupId,t.displayName),r={default_space:"default Space setup",default_space_grant:"default Space access grant"}[t.setupWarning?.step||""]||"default Space setup";return y("div",{class:"peer-meta coordinator-admin-empty-state"},y("h4",{class:"coordinator-admin-drawer-title"},`Set up legacy group ${n}`),y("div",{class:"peer-submeta"},"This coordinator group organizes technical discovery and enrollment. It is not a policy Team; use Sharing to manage Team membership and Project access."),t.setupWarning?y("div",{class:"peer-meta coordinator-admin-inline-warning"},`Legacy coordinator group created, but ${r} failed. Automatic repair is not available yet; use Spaces to inspect or create transport access manually. Sharing policy is unchanged.`):y("div",{class:"peer-submeta"},t.defaultSpaceScopeId?t.defaultSpaceLabel?`Default Space ready: ${t.defaultSpaceLabel}. New devices can receive this Space when auto-grant is enabled.`:"Default Space ready. New devices can receive this Space when auto-grant is enabled.":"Default Space status is unknown. Check Spaces before inviting teammates."),y("ol",{class:"peer-submeta"},y("li",null,"Review legacy group defaults and the auto-grant default Space setting."),y("li",null,"Use legacy enrollment only when compatibility or recovery requires it."),y("li",null,"Open Sharing for Team membership and Project access.")),y("div",{class:"peer-actions"},y("button",{class:"settings-button",onClick:()=>{P.groupPreferencesOpen.add(t.groupId),sp(t.groupId,e)},type:"button"},"Review legacy defaults"),y("button",{class:"settings-button",onClick:()=>{op(t.groupId,e)},type:"button"},"Check Spaces"),y("button",{class:"settings-button",onClick:()=>{P.inviteGroup=t.groupId,P.activeSection="invites",e()},type:"button"},"Create legacy device invite"),y("button",{class:"settings-button",onClick:()=>{window.location.hash="projects"},type:"button"},"Open Projects"),y("button",{class:"settings-button",onClick:()=>{P.teamSetupGuide=null,e()},type:"button"},"Dismiss")))}function ED(e,t){return t?e?"Unarchiving…":"Archiving…":e?"Unarchive":"Archive"}function AD(e){const{summary:t,fresh:n,createGroup:r,runGroup:i,renderShell:o,reloadData:s}=e,c=Or(P.recovery,"groups"),l=Mi(P.recovery,"groups"),d=String(C.lastCoordinatorAdminStatus?.active_group||"").trim(),u=Fn(),p=rr(),f=p.filter(b=>!b.archived_at),m=p.filter(b=>b.archived_at),v=P.showArchivedGroups?p:f,g=u?p.some(b=>b.group_id===u):!1,h=[`${f.length} active`];return m.length&&h.push(`${m.length} archived`),y($r,{className:"coordinator-admin-panel",value:"groups"},y("h3",null,"Coordinator groups"),y("p",{class:"peer-submeta"},u?`Managing the selected coordinator group${d&&d!==u?" · this node uses a different group for discovery":""}`:d?`This node uses ${d} for discovery. Select a coordinator group below to manage it.`:"No coordinator group selected yet. Create one or select an existing group to manage."),p.length?y("p",{class:"peer-submeta"},h.join(" · ")):null,!g&&u?y("div",{class:"peer-meta coordinator-admin-inline-warning"},"The selected legacy group is configured locally but does not exist in the coordinator yet. Create it below or switch to another coordinator group once one exists."):null,ND(o),(()=>{const b=!n||P.groupActionPendingKind==="create";return y("form",{class:"coordinator-admin-form",onSubmit:w=>{w.preventDefault(),!b&&r()}},y("div",{class:"peer-meta coordinator-admin-inline-warning",role:"note"},"Creating a coordinator group changes legacy discovery and transport setup only. It does not create a policy Team or grant Project access in Sharing."),y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"New coordinator group ID"),y(Te,{class:"peer-scope-input",disabled:b,onInput:w=>{P.createGroupId=String(w.currentTarget.value||"")},placeholder:"group-alpha",type:"text",value:P.createGroupId})),y("label",{class:"coordinator-admin-field"},y("span",null,"Legacy group display name"),y(Te,{class:"peer-scope-input",disabled:b,onInput:w=>{P.createGroupDisplayName=String(w.currentTarget.value||"")},placeholder:"Legacy group Alpha",type:"text",value:P.createGroupDisplayName}))),y("div",{class:"section-actions coordinator-admin-groups-toolbar"},y("div",{class:"coordinator-admin-primary-actions"},y("button",{class:"settings-button",disabled:b,type:"submit"},P.groupActionPendingKind==="create"?"Creating…":"Create coordinator group")),y("div",{class:"coordinator-admin-secondary-actions"},y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:"coordinatorAdminShowArchivedLabel"},"Show archived"),y(Gi,{"aria-labelledby":"coordinatorAdminShowArchivedLabel",checked:P.showArchivedGroups,className:"coordinator-admin-switch",onCheckedChange:w=>{P.showArchivedGroups=w,o()},thumbClassName:"coordinator-admin-switch-thumb"})))))})(),l?y("div",{class:"peer-meta"},"Complete legacy coordinator setup before loading coordinator groups. No group list is expected yet."):c?v.length?y("div",{class:"peer-list"},v.map(b=>{const w=b.group_id===u,_=P.groupActionPendingId===b.group_id,R=!!b.archived_at,I=P.groupRenameDrafts.get(b.group_id)??b.display_name??"",T=I.trim()||Gu(b.group_id,b.display_name),A=P.groupPreferencesOpen.has(b.group_id),O=P.groupScopeManagementOpen.has(b.group_id),F=R?"unarchive":"archive",N=ED(R,_&&P.groupActionPendingKind===F),L=Yx({groupId:b.group_id,preferences:P.groupPreferencesDrafts.get(b.group_id),scopeManagement:P.groupScopeManagementDrafts.get(b.group_id),setupGuide:P.teamSetupGuide});return y("div",{class:"peer-card peer-card--padded",key:b.group_id},y("div",{class:"peer-title"},y("strong",null,T)),y("div",{class:"peer-submeta"},R?"Archived coordinator group":"Active coordinator group"),y("details",{class:"coordinator-admin-diagnostics"},y("summary",null,"Diagnostics"),y("div",{class:"peer-meta"},`Group ID ${b.group_id}`)),y("div",{class:"coordinator-admin-summary-grid"},y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Default Space"),y("strong",null,L.defaultSpace)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Auto-grant"),y("strong",null,L.autoGrant)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Spaces"),y("strong",null,L.spaces))),d===b.group_id?y("div",{class:"peer-submeta"},"This node uses this coordinator group for discovery."):null,y("label",{class:"coordinator-admin-field"},y("span",null,"Legacy group display name"),y(Te,{class:"peer-scope-input",disabled:!n||_,onInput:D=>{P.groupRenameDrafts.set(b.group_id,String(D.currentTarget.value||""))},type:"text",value:I})),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:!n||w,onClick:()=>{Uu(b.group_id),s()},type:"button"},w?"Managing":"Manage group"),y("button",{class:"settings-button",disabled:!n||_,onClick:()=>i(b.group_id,I,"rename"),type:"button"},_&&P.groupActionPendingKind==="rename"?"Renaming…":"Rename group"),y("button",{"aria-expanded":A,"aria-controls":`coord-admin-project-defaults-drawer-${b.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":A?"open":"closed",disabled:_,onClick:()=>{A?hc(b.group_id,o):sp(b.group_id,o)},type:"button"},y("span",null,"Legacy group defaults"),y("span",{"aria-hidden":"true",class:"device-row-chevron"},y(pb,null))),y("button",{"aria-expanded":O,"aria-controls":`coord-admin-spaces-drawer-${b.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":O?"open":"closed",disabled:_,onClick:()=>{O?ub(b.group_id,o):op(b.group_id,o)},type:"button"},y("span",null,"Spaces & access"),y("span",{"aria-hidden":"true",class:"device-row-chevron"},y(pb,null))),y("button",{class:R?"settings-button":"settings-button danger",disabled:!n||_,onClick:()=>i(b.group_id,b.display_name||b.group_id,F),type:"button"},N)),y(zo,{open:A,onOpenChange:D=>{D?sp(b.group_id,o):hc(b.group_id,o)}},y(Wo,{"aria-label":`Project defaults for ${T}`,class:"coordinator-admin-group-preferences",id:`coord-admin-project-defaults-drawer-${b.group_id}`},A?PD(b.group_id,o,n):null)),y(zo,{open:O,onOpenChange:D=>{D?op(b.group_id,o):ub(b.group_id,o)}},y(Wo,{"aria-label":`Spaces for ${T}`,class:"coordinator-admin-group-preferences coordinator-admin-domain-management",id:`coord-admin-spaces-drawer-${b.group_id}`},O?ID({groupId:b.group_id,ready:n,renderShell:o,summary:t}):null)))})):y("div",{class:"peer-meta coordinator-admin-empty-state"},t.readiness==="ready"?P.showArchivedGroups?"No coordinator groups are available yet.":"No active coordinator groups yet. Create one only for legacy discovery or recovery.":"Coordinator group browsing will appear here once setup is complete."):y("div",{class:"peer-meta coordinator-admin-empty-state"},"Coordinator groups are unavailable. Retry to load current groups; no empty result is being assumed."))}function Ki(e){return a("textarea",{...e})}function xD(e){const{summary:t,fresh:n,createInvite:r,renderShell:i}=e,o=C.lastCoordinatorAdminStatus,s=Fn()||String(o?.active_group||"").trim(),c=P.inviteGroup.trim()||s,l=String(C.lastTeamInvite?.encoded||"").trim(),d=Array.isArray(C.lastTeamInvite?.warnings)?C.lastTeamInvite?.warnings:[],u=!n||P.invitePending;return y($r,{className:"coordinator-admin-panel",value:"invites"},y("h3",null,"Legacy coordinator invites"),y("p",{class:"peer-submeta"},n?"Legacy coordinator invites enroll a device in the selected group for discovery. They do not add policy Team membership or grant Project access; use Sharing for both.":t.readiness==="ready"?"Legacy invite creation is disabled until current coordinator status and group data are available. Previously generated invites remain available to copy.":"Finish coordinator setup first. Legacy invite creation stays disabled until the local configuration is ready."),y("form",{class:"coordinator-admin-form",onSubmit:p=>{p.preventDefault(),!u&&r()}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"Coordinator group"),y(Te,{class:"peer-scope-input",disabled:!n,onInput:p=>{P.inviteGroup=String(p.currentTarget.value||""),i()},placeholder:s||"group-alpha",type:"text",value:P.inviteGroup})),y("label",{class:"coordinator-admin-field"},y("span",null,"Join policy"),y(ar,{ariaLabel:"Invite join policy",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:!n,id:"coordinatorAdminInvitePolicy",itemClassName:"sync-radix-select-item",onValueChange:p=>{P.invitePolicy=p==="approval_required"?"approval_required":"auto_admit",i()},options:[{value:"auto_admit",label:"Auto-admit to coordinator group"},{value:"approval_required",label:"Require approval to join group"}],triggerClassName:"sync-radix-select-trigger sync-actor-select",value:P.invitePolicy,viewportClassName:"sync-radix-select-viewport"})),y("label",{class:"coordinator-admin-field"},y("span",null,"Expires in (hours)"),y(Te,{class:"peer-scope-input",disabled:!n,min:"1",onInput:p=>{P.inviteTtlHours=String(p.currentTarget.value||"")},type:"number",value:P.inviteTtlHours}))),y("div",{class:"section-actions"},y("button",{class:"settings-button",disabled:u,type:"submit"},P.invitePending?"Creating…":"Create legacy coordinator invite"),c?y("span",{class:"peer-submeta"},"Using the selected coordinator group"):null)),l?y("label",{class:"coordinator-admin-field"},y("span",null,"Generated invite"),y(Ki,{class:"feed-search coordinator-admin-output",readOnly:!0,value:l}),y("button",{class:"settings-button sync-action-copy",type:"button",onClick:p=>Uo(l,p.currentTarget)},"Copy")):null,d?.length?y("div",{class:"peer-meta coordinator-admin-warning-list"},d.join(" · ")):null,y("h3",null,"Project sharing operations"),y("p",{class:"peer-submeta"},"Read-only status from the project-first sharing flow. Start new sharing from Projects."),C.lastShareOperations.length>0?y("ul",{class:"peer-scope-rejections-list","aria-label":"Project sharing operations"},...C.lastShareOperations.map(p=>y("li",{key:p.operation_id},y("strong",null,p.person.display_name),y("span",null,` — ${p.projects.map(f=>f.display_name).join(", ")} — ${p.lifecycle.label}`)))):y("div",{class:"peer-meta"},"No project sharing operations yet."))}function DD(e){const{summary:t,fresh:n,reviewJoinRequest:r,snapshotMatchesTarget:i}=e,o=i&&Or(P.recovery,"joinRequests"),s=Mi(P.recovery,"joinRequests"),c=o&&Array.isArray(C.lastCoordinatorAdminJoinRequests)?C.lastCoordinatorAdminJoinRequests:[],l=c.map(u=>({device_id:String(u.device_id||"").trim()||`join-request:${String(u.request_id||"").trim()}`,display_name:u.display_name})),d=Bs(l,P.unnamedDeviceAliases);return y($r,{className:"coordinator-admin-panel",value:"join-requests"},y("h3",null,"Pending join requests"),y("p",{class:"peer-submeta"},t.readiness==="ready"?"Approve or deny devices that want to join this legacy coordinator group. Space transport access is handled by legacy group defaults and can be reviewed in Spaces; Sharing policy is separate.":"Finish coordinator setup first. Join request review stays disabled until legacy administration is ready."),s?y("div",{class:"peer-meta"},"Complete legacy coordinator setup to load join requests. No join queue is expected yet."):o?c.length?y("div",{class:"peer-list"},c.map(u=>{const p=String(u.request_id||"").trim(),f=String(u.device_id||"").trim(),m=f||`join-request:${p}`,v=d.get(m)||"Unnamed device",g=String(u.fingerprint||"").trim(),h=[`Device ID ${f||"unknown"}`];g&&h.push(`Fingerprint ${g}`);const b=P.joinReviewPendingId===p;return y("div",{class:"peer-card peer-card--padded",key:p||f},y("div",{class:"peer-title"},y("strong",null,v)),y("details",{class:"coordinator-admin-diagnostics"},y("summary",null,"Diagnostics"),y("div",{class:"peer-meta"},`Advanced: ${h.join(" · ")}`)),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:!n||!p||b,onClick:()=>r(p,"approve"),type:"button"},b&&P.joinReviewPendingAction==="approve"?"Approving…":"Approve"),y("button",{class:"settings-button danger",disabled:!n||!p||b,onClick:()=>r(p,"deny"),type:"button"},b&&P.joinReviewPendingAction==="deny"?"Denying…":"Deny")))})):y("div",{class:"peer-meta"},t.readiness==="ready"?"No pending join requests right now.":"Join request review will appear here once setup is complete."):y("div",{class:"peer-meta"},"Join requests are unavailable. Retry to load the current queue; no empty result is being assumed."))}var LD=new Map([["display_name_required","Enter a device name before renaming it."],["display_name_invalid","Enter a valid device name and retry."],["display_name_too_long","The device name is too long. Use a shorter name and retry."]]);function $D(e){const t=e instanceof Error?e.message:"";return t.includes("group_archived")||t.includes("Group is archived")?"This legacy coordinator group is archived. Choose an active group or refresh coordinator groups.":t.includes("group_not_found")||t.includes("Group not found")?"This legacy coordinator group no longer exists. Choose an active group or refresh coordinator groups.":"Could not create the legacy coordinator invite. Sharing policy is unchanged; check coordinator recovery status and retry."}function OD(e){return e instanceof Error?e.message.includes("request_not_found")||e.message.includes("join request not found"):!1}function jD(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("group_not_found")||t.includes("group not found")}function MD(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("device_not_found")||t.includes("device not found")}function FD(e){const{renderShell:t,reloadData:n}=e,r=(...d)=>xn(P.recovery,...d)?!0:(Z("Coordinator data changed or is refreshing. Wait for recovery to finish, then try again.","warning"),!1);async function i(){if(!r("status","groups")||P.groupActionPendingKind)return;const d=Mn(C.lastCoordinatorAdminStatus?.coordinator_url),u=P.createGroupId.trim();if(!u){Z("Enter a coordinator group ID before creating a legacy group.","warning");return}const p=P.createGroupDisplayName.trim();P.groupActionPendingKind="create",t();try{const f=await wC({group_id:u,display_name:p||null});if(Mn(C.lastCoordinatorAdminStatus?.coordinator_url)!==d)return;const m=f.default_space,v=(m&&"scope"in m?m.scope:m)??{},g=m&&"preferences"in m?m.preferences:null,h=String(v?.scope_id||"");P.createGroupId="",P.createGroupDisplayName="",P.teamSetupGuide={groupId:u,displayName:String(f.group?.display_name||p||""),defaultSpaceScopeId:h,defaultSpaceLabel:String(v?.label||""),autoGrantDefaultSpaceOnJoin:typeof g?.auto_grant_default_space_on_join=="boolean"?g.auto_grant_default_space_on_join:null,setupWarning:f.setup_warning||null};try{await n(),Uu(u),await n()}catch{Z("Legacy coordinator group created, but coordinator data could not refresh. Check coordinator recovery status before retrying.","warning");return}f.setup_warning?Z("Legacy coordinator group created, but default Space setup needs repair. Sharing policy is unchanged.","warning"):h?Z("Legacy coordinator group created with a default Space. Sharing policy is unchanged.","success"):Z("Legacy coordinator group created, but default Space status is unknown. Sharing policy is unchanged.","warning")}catch{Z("Could not create the legacy coordinator group. No Sharing policy or Project access changed; check coordinator recovery status and retry.","warning")}finally{P.groupActionPendingKind="",t()}}async function o(d,u,p){if(!r("status","groups")||!d||P.groupActionPendingId)return;const f=u.trim();if(p==="rename"&&!f){Z("Enter a legacy group display name before renaming it.","warning");return}const m=C.lastCoordinatorAdminGroups.find(w=>w.group_id===d),v=Gu(d,m?.display_name),g=oc();if(!await hn({title:p==="rename"?`Rename ${v}?`:`${p==="archive"?"Archive":"Unarchive"} ${v}?`,description:p==="rename"?`Target: ${v}. New name: ${f}. This renames the technical coordinator group only. It does not rename a policy Team or change membership or Project access in Sharing.`:p==="archive"?`Target: ${v}. The group stays visible and restorable, but coordinator presence, peer discovery, Space grants, legacy invites, and joins stop. Archiving also removes this group from this device's local coordinator configuration. Policy Team membership and Project access in Sharing are separate and unchanged.`:`Target: ${v}. This reactivates the remote coordinator group for devices still configured for it. It does not re-add this group to this device's local coordinator configuration; restore that separately before expecting coordinator presence or peer discovery here. It does not restore or change policy Team membership or Project access in Sharing.`,confirmLabel:p==="rename"?"Rename coordinator group":p==="archive"?"Archive coordinator group":"Unarchive coordinator group",cancelLabel:p==="rename"?"Keep current group name":p==="archive"?"Keep group active":"Keep group archived",tone:p==="archive"?"danger":"default"}))return;if(!$t(g)){Z("Coordinator group data changed while confirmation was open. Review the current group and try again.","warning");return}if(!xn(P.recovery,"status","groups")){Z("Coordinator group data changed while confirmation was open. Review the current group and try again.","warning");return}const h=C.lastCoordinatorAdminGroups.find(w=>String(w.group_id||"")===d);if(!h||P.groupActionPendingId){Z("Coordinator group data changed while confirmation was open. Review the current group and try again.","warning");return}const b=P.groupRenameDrafts.get(d)??String(h.display_name||"");P.groupActionPendingId=d,P.groupActionPendingKind=p,t();try{const w=p==="rename"?"renamed":p==="archive"?"archived":"unarchived";p==="rename"&&await SC(d,b),p==="archive"&&await CC(d),p==="unarchive"&&await RC(d);try{await n()}catch{Z(`Legacy coordinator group ${w}, but coordinator data could not refresh. Check coordinator recovery status before retrying.`,"warning");return}Z(p==="rename"?"Legacy coordinator group renamed. Sharing Team names are unchanged.":p==="archive"?"Legacy coordinator group archived. Sharing policy is unchanged.":"Legacy coordinator group unarchived. This device's local coordinator configuration and Sharing policy are unchanged.","success")}catch(w){if(jD(w))try{await n(),Z("This legacy coordinator group changed or no longer exists. Coordinator groups were refreshed.","warning")}catch{Z("This legacy coordinator group changed or no longer exists. Refresh coordinator groups before trying another action.","warning")}else Z(`Could not ${p} the legacy coordinator group. Sharing policy is unchanged; check coordinator recovery status and retry.`,"warning")}finally{P.groupActionPendingId="",P.groupActionPendingKind="",t()}}async function s(){if(!r("status","groups")||P.invitePending)return;const d=C.lastCoordinatorAdminStatus,u=Mn(d?.coordinator_url),p=Fn()||String(d?.active_group||"").trim(),f=P.inviteGroup.trim()||p,m=Number(P.inviteTtlHours);if(!f){Z("Choose a coordinator group before creating a legacy invite.","warning");return}if(!Number.isFinite(m)||m<1){Z("Invite lifetime must be at least 1 hour.","warning");return}P.invitePending=!0,t();try{const v=await hm({group_id:f,policy:P.invitePolicy,ttl_hours:m}),g=C.lastCoordinatorAdminStatus,h=Fn()||String(g?.active_group||"").trim(),b=P.inviteGroup.trim()||h;if(Mn(g?.coordinator_url)!==u||b!==f)return;C.lastTeamInvite=v,P.inviteGroup=f;const w=Array.isArray(v.warnings)?v.warnings:[];Z(w.length?`Invite created. Review ${w.length===1?"the warning":`${w.length} warnings`} before sharing it.`:"Legacy coordinator invite created. It does not grant Sharing Project access.",w.length?"warning":"success")}catch(v){Z($D(v),"warning")}finally{P.invitePending=!1,t()}}async function c(d,u){if(!$t(P.joinRequestsSnapshotTarget)||!r("status","joinRequests")||P.joinReviewPendingId)return;const p=P.joinRequestsSnapshotTarget;P.joinReviewPendingId=d,P.joinReviewPendingAction=u,t();try{const f=await EC(d,u);if(!$t(p))return;try{await n()}catch{Z(`Join request ${u==="approve"?"approved":"denied"}, but pending requests could not refresh. Check coordinator recovery status before reviewing another request.`,"warning");return}u==="approve"&&f.setup_warning?Z("Join request approved, but default Space access needs repair.","warning"):Z(u==="approve"?"Join request approved.":"Join request denied.","success")}catch(f){if(!$t(p))return;if(OD(f))try{await n(),Z("This legacy coordinator join request no longer exists. Pending requests were refreshed.","warning")}catch{Z("This legacy coordinator join request no longer exists. Refresh pending requests before reviewing another request.","warning")}else Z("Could not review the legacy coordinator join request. Sharing policy is unchanged; check coordinator recovery status and retry.","warning")}finally{P.joinReviewPendingId="",P.joinReviewPendingAction="",t()}}async function l(d,u,p,f){if($t(P.devicesSnapshotTarget)&&r("status","devices")&&!(!d||P.deviceActionPendingId)){if(f==="disable"||f==="remove"){const m=oc();if(!await hn({title:`${f==="disable"?"Disable":"Remove"} ${p||"this device"}?`,description:f==="disable"?"This device will stay enrolled but can no longer participate until you re-enable it.":"This removes the enrolled device record from the coordinator. The teammate would need a fresh invite or re-enrollment path to come back.",confirmLabel:f==="disable"?"Disable device":"Remove device",cancelLabel:f==="disable"?"Keep device enabled":"Keep device enrolled",tone:"danger"}))return;if(!$t(m)){Z("Coordinator device data changed while confirmation was open. Review the current device and try again.","warning");return}if(!xn(P.recovery,"status","devices")){Z("Coordinator device data changed while confirmation was open. Review the current device and try again.","warning");return}if(!C.lastCoordinatorAdminDevices.find(v=>String(v.device_id||"")===d&&String(v.group_id||"")===u)||P.deviceActionPendingId){Z("Coordinator device data changed while confirmation was open. Review the current device and try again.","warning");return}}P.deviceActionPendingId=d,P.deviceActionPendingKind=f,t();try{const m=f==="rename"?"renamed":f==="disable"?"disabled":f==="enable"?"enabled":"removed";if(f==="rename"){const v=String(P.deviceRenameDrafts.get(d)||"").trim();if(!v){Z("Enter a device name before renaming it.","warning");return}await AC(d,u,v)}f==="disable"&&await xC(d,u),f==="enable"&&await DC(d,u),f==="remove"&&await LC(d,u);try{await n()}catch{Z(`Device ${m}, but coordinator data could not refresh. Check coordinator recovery status before retrying.`,"warning");return}Z(`Device ${m}.`,"success")}catch(m){const v=f==="rename"&&m instanceof Error?LD.get(m.message.trim()):void 0;if(MD(m))try{await n(),Z("This legacy coordinator device no longer exists. Enrolled devices were refreshed.","warning")}catch{Z("This legacy coordinator device no longer exists. Refresh enrolled devices before trying another action.","warning")}else Z(v||`Could not ${f} the legacy coordinator device. Sharing policy is unchanged; check coordinator recovery status and retry.`,"warning")}finally{P.deviceActionPendingId="",P.deviceActionPendingKind="",t()}}}return{createGroupFromAdminPanel:i,runGroupAction:o,createInviteFromAdminPanel:s,reviewJoinRequestFromAdminPanel:c,runDeviceAction:l}}function BD(){C.lastCoordinatorAdminGroups=[],C.lastCoordinatorAdminJoinRequests=[],C.lastCoordinatorAdminDevices=[],C.lastTeamInvite=null,C.coordinatorAdminTargetGroup="",un(P.recovery,"groups",!1),un(P.recovery,"joinRequests",!1),un(P.recovery,"devices",!1),P.joinRequestsSnapshotTarget=null,P.devicesSnapshotTarget=null,P.groupRenameDrafts.clear(),P.groupPresentationAliases.clear(),P.deviceRenameDrafts.clear(),P.deviceRenameServerNames.clear(),P.groupPreferencesOpen.clear(),P.groupPreferencesDrafts.clear(),P.groupScopeManagementOpen.clear(),P.groupScopeManagementDrafts.clear(),P.inviteGroup="",P.teamSetupGuide=null}function qD(){const e=cy();return Vo(P.recovery,"status"),vu(P.recovery,"groups"),vu(P.recovery,"joinRequests"),vu(P.recovery,"devices"),e}async function hb(e){try{const t=await Rl();if(!_u(e))return"superseded";if(!t||typeof t!="object")throw new Error("Invalid status payload");const n=C.lastCoordinatorAdminStatus;return Mn(n?.coordinator_url)!==Mn(t.coordinator_url)&&BD(),C.lastCoordinatorAdminStatus=t,Us(P.recovery,"status"),"fresh"}catch{return _u(e)?(un(P.recovery,"status"),"failed"):"superseded"}}function UD(){const e=C.lastCoordinatorAdminStatus;return e?e.readiness==="ready"?{readiness:"ready",title:"Legacy coordinator administration is ready",detail:"This viewer can manage legacy coordinator groups, invites, join requests, and enrolled devices without exposing the admin secret to the browser."}:e.readiness==="partial"?{readiness:"partial",title:"Legacy coordinator setup is incomplete",detail:e.has_admin_secret===!1?"Set a coordinator admin secret for the viewer server before using legacy invite and device actions.":"Finish configuring the coordinator target and group before using legacy administration actions."}:{readiness:"not_configured",title:"Legacy coordinator administration is not configured",detail:"Set a coordinator URL, group, and admin secret locally to enable remote coordinator administration from this viewer."}:P.recovery.status.availability==="unavailable"?{readiness:"partial",title:"Legacy coordinator status is unavailable",detail:"Current coordinator readiness could not be loaded. Retry before using legacy administration actions."}:{readiness:"partial",title:"Checking legacy coordinator readiness…",detail:"Loading local coordinator administration configuration from the viewer server."}}var{createGroupFromAdminPanel:GD,runGroupAction:HD,createInviteFromAdminPanel:VD,reviewJoinRequestFromAdminPanel:KD,runDeviceAction:zD}=FD({renderShell:()=>Hr(),reloadData:async()=>{await gc()}});function Hr(){const e=document.getElementById("coordinatorAdminMount");if(!e)return;const t=C.lastCoordinatorAdminStatus,n=UD(),r=String(t?.coordinator_url||"").trim(),i=String(t?.active_group||"").trim(),s=!!Gx()?.archived_at,c=xn(P.recovery,"status","groups"),l=c&&!s,d=$t(P.joinRequestsSnapshotTarget),u=$t(P.devicesSnapshotTarget),p=xn(P.recovery,"status","joinRequests")&&d,f=xn(P.recovery,"status","devices")&&u,m=Fn(),v=rr().filter(L=>!L.archived_at).length,g=rr().filter(L=>L.archived_at).length,h=d&&Array.isArray(C.lastCoordinatorAdminJoinRequests)?C.lastCoordinatorAdminJoinRequests.length:0,b=u&&Array.isArray(C.lastCoordinatorAdminDevices)?C.lastCoordinatorAdminDevices.length:0,w=n.readiness!=="ready"?n.detail:s?"The selected coordinator group is archived. Restore it or switch groups before creating legacy invites.":"",_=bu(P.recovery),R=Or(P.recovery,"status"),I=Or(P.recovery,"groups"),T=d&&Or(P.recovery,"joinRequests"),A=u&&Or(P.recovery,"devices"),O=Mi(P.recovery,"groups"),F=Mi(P.recovery,"joinRequests"),N=Mi(P.recovery,"devices");Ue(y("div",{class:"coordinator-admin-shell"},y("div",{class:"card coordinator-admin-header"},y("div",{class:"section-header"},y("h2",null,"Legacy coordinator administration")),y("div",{"aria-atomic":"true","aria-live":"polite",class:_?"coordinator-admin-inline-warning coordinator-admin-recovery-notice":P.recoveryAnnouncement?"peer-meta coordinator-admin-recovery-status":"coordinator-admin-recovery-status",id:"coordinatorAdminRecoveryStatus",role:"status",tabIndex:-1},_?y(z,null,y("div",{class:"coordinator-admin-legacy-notice-copy"},y("h3",null,"Advanced coordinator data needs attention"),P.recoveryAnnouncement?y("p",{class:"peer-submeta"},P.recoveryAnnouncement):null,_.stale.length?y("p",{class:"peer-submeta"},`Stale: ${_.stale.join(", ")}. Previously loaded data is still shown.`):null,_.unavailable.length?y("p",{class:"peer-submeta"},`Unavailable: ${_.unavailable.join(", ")}. No current data is shown for ${_.unavailable.length===1?"that surface":"those surfaces"}.`):null,y("p",{class:"peer-submeta"},"Actions that depend on current coordinator data are disabled. This does not mean coordinator data was deleted.")),y("button",{class:"settings-button",disabled:_.retrying,onClick:()=>{P.recoveryAnnouncement="Retrying coordinator data…",P.recoveryRetryRequested=!0,gc()},type:"button"},_.retrying?"Retrying…":"Retry")):P.recoveryAnnouncement),y("div",{class:"coordinator-admin-summary-grid"},y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Coordinator group target"),y("strong",null,R||I?m||"None selected":"Unavailable")),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Node discovery group"),y("strong",null,R?i||"None":"Unavailable")),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Coordinator groups"),y("strong",null,I?`${v} active${g?` · ${g} archived`:""}`:O?"Setup required":"Unavailable")),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Selected group activity"),y("strong",null,`${T?h:F?"Setup required":"Unavailable"} join requests · ${A?b:N?"Setup required":"Unavailable"} devices`))),w?y("div",{class:"peer-meta coordinator-admin-inline-warning"},w):null,r?y("div",{class:"section-meta coordinator-admin-inline-meta"},`Coordinator: ${r}`):null),y("div",{class:"card coordinator-admin-sections"},y(oy,{ariaLabel:"Legacy coordinator administration sections",listClassName:"coordinator-admin-tabs-list",onValueChange:L=>{P.activeSection=L||"groups",Hr()},tabs:[{value:"groups",label:"Coordinator groups"},{value:"invites",label:"Invites"},{value:"join-requests",label:"Join requests"},{value:"devices",label:"Devices"}],triggerClassName:"coordinator-admin-tab-trigger",value:P.activeSection},AD({summary:n,fresh:c,createGroup:()=>{GD()},runGroup:(L,D,G)=>{HD(L,D,G)},renderShell:Hr,reloadData:()=>{gc()}}),xD({summary:n,fresh:l,createInvite:()=>{VD()},renderShell:Hr}),DD({summary:n,fresh:p,snapshotMatchesTarget:d,reviewJoinRequest:(L,D)=>{KD(L,D)}}),ME({summary:n,fresh:f,snapshotMatchesTarget:u,runDevice:(L,D,G,q)=>{zD(L,D,G,q)}})),y("div",{class:"section-meta coordinator-admin-context-line"},s?"The selected coordinator group is archived. Switch or restore it to enable legacy invite operations.":m?"Actions below apply to the selected coordinator group.":"Select a coordinator group to manage legacy enrollment and Spaces."))),e),P.recoveryFocusPending&&(P.recoveryFocusPending=!1,queueMicrotask(()=>document.getElementById("coordinatorAdminRecoveryStatus")?.focus()))}function WD(){Hr()}var cp=null;function Bt(e){return cp?.generation===e?!1:cp?.operation??!1}function gc(){const e=cy(),t=JD(e);return cp={generation:e,operation:t},t}async function JD(e){const t=()=>_u(e);if(P.recoveryRetryRequested||(P.recoveryAnnouncement=""),Vo(P.recovery,"status"),Vo(P.recovery,"groups"),Vo(P.recovery,"joinRequests"),Vo(P.recovery,"devices"),Hr(),await hb(e)==="superseded")return Bt(e);const n=String(C.lastCoordinatorAdminStatus?.active_group||"").trim();if(zy(),C.lastCoordinatorAdminStatus?.readiness==="ready"&&xn(P.recovery,"status")){try{const o=await Lm();if(!t())return Bt(e);C.lastShareOperations=Array.isArray(o.items)?o.items:[]}catch{if(!t())return Bt(e)}try{const o=await pm(P.showArchivedGroups);if(!t())return Bt(e);if(!Array.isArray(o?.items))throw new Error("Invalid groups payload");C.lastCoordinatorAdminGroups=o.items,Us(P.recovery,"groups"),Ux(),zy()}catch{if(!t())return Bt(e);un(P.recovery,"groups")}const r=Fn(),i=oc();try{if(!i)throw new Error("Missing coordinator administration target");const o=await NC(r||n);if(!t())return Bt(e);if(!Array.isArray(o?.items))throw new Error("Invalid join requests payload");C.lastCoordinatorAdminJoinRequests=o.items,P.joinRequestsSnapshotTarget=i,Us(P.recovery,"joinRequests")}catch{if(!t())return Bt(e);un(P.recovery,"joinRequests",$t(P.joinRequestsSnapshotTarget))}try{if(!i)throw new Error("Missing coordinator administration target");const o=await mm(r||n,!0);if(!t())return Bt(e);if(!Array.isArray(o?.items))throw new Error("Invalid devices payload");C.lastCoordinatorAdminDevices=o.items,P.devicesSnapshotTarget=i,Us(P.recovery,"devices"),Hx()}catch{if(!t())return Bt(e);un(P.recovery,"devices",$t(P.devicesSnapshotTarget))}try{const o=await Va();if(!t())return Bt(e);P.availableProjects=o}catch{if(!t())return Bt(e)}}else P.recovery.status.availability==="fresh"?(yu(P.recovery,"groups"),yu(P.recovery,"joinRequests"),yu(P.recovery,"devices"),P.joinRequestsSnapshotTarget=null,P.devicesSnapshotTarget=null):(un(P.recovery,"groups"),un(P.recovery,"joinRequests",$t(P.joinRequestsSnapshotTarget)),un(P.recovery,"devices",$t(P.devicesSnapshotTarget)));return t()?(ay([...C.lastCoordinatorAdminDevices,...C.lastCoordinatorAdminJoinRequests.map(r=>({device_id:String(r.device_id||"").trim()||`join-request:${String(r.request_id||"").trim()}`,display_name:r.display_name}))],P.unnamedDeviceAliases),Bs(C.lastCoordinatorAdminDevices,P.unnamedDeviceAliases),P.recoveryRetryRequested&&(P.recoveryAnnouncement=bu(P.recovery)?"Retry finished, but some coordinator data still needs attention. Retained data remains unchanged.":C.lastCoordinatorAdminStatus?.readiness==="ready"?"Coordinator data refreshed. Current data is available.":"Coordinator status refreshed. Complete setup to load administration data.",P.recoveryFocusPending=!0),P.recoveryRetryRequested=!1,Hr(),bu(P.recovery)===null):Bt(e)}function lp(e){return e.inventoryUnavailable===!0||e.refreshError===!0}var dp=new WeakMap,gb={active:0,verifying:1,pending:2,waiting:3,needs_attention:4},YD={state:"pending",label:"Recipient policy pending",explanation:"Current access remains in place while this Project is prepared.",deliveredCopiesMayRemain:!0},XD={available:"Available",offline:"Offline",unknown:"Availability unknown"};function QD(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function ZD(e,t){return t.get(e)??YD}function eL(e){return e.reduce((t,n)=>!t||gb[n.state]>gb[t.state]?n:t,null)}function tL(e,t){return t==="needs_attention"?{label:"Review sharing",target:"sharing"}:e!=="available"?{label:"Check device health",target:"health"}:t==="waiting"||t==="pending"||t==="verifying"?{label:"View sharing status",target:"sharing"}:null}function nL(e,t,n,r,i=[]){const o=new Map(e.identities.filter(u=>u.status==="active"&&u.mergedIntoIdentityId===null).map(u=>[u.identityId,u.displayName])),s=new Map(n.map(u=>[u.canonicalProjectIdentity,u.displayName])),c=new Map(r.map(u=>[u.deviceId,u.state])),l=new Map(i.map(u=>[u.deviceId,u])),d=new Map(t.items.map(u=>[u.canonicalProjectIdentity,u]));return{devices:e.identityDevices.filter(u=>u.status==="active"&&o.has(u.identityId)).map(u=>{const p=l.get(u.deviceId),f=QD(e.projectRecipients.filter(_=>_.status==="active"&&_.recipientKind==="identity"&&_.identityId===u.identityId).map(_=>_.canonicalProjectIdentity)),m=_=>{const R=s.get(_);if(!R)return null;const I=ZD(_,d);return{canonicalProjectIdentity:_,displayName:R,state:I.state,statusLabel:I.label,statusCopy:I.explanation,deliveredCopiesMayRemain:I.deliveredCopiesMayRemain}},v=f.flatMap(_=>{const R=m(_);return R?[R]:[]}),g=[],h=[...v,...g],b=eL(h),w=c.get(u.deviceId)??"unknown";return{deviceId:u.deviceId,displayName:u.displayName,identityName:o.get(u.identityId)??"Identity unavailable",availability:w,availabilityLabel:XD[w],isPairedPeer:p!==void 0,reportedRuntimeVersion:p?.runtimeVersion??null,runtimeVersionObservedAt:p?.runtimeVersionObservedAt??null,directProjects:v,inheritedProjects:g,unavailableProjectCount:f.length-v.length,statusState:b?.state??"no_projects",statusLabel:b?.statusLabel??"No directly shared Projects",statusCopy:b?.statusCopy??"Team access is not shown here without authoritative per-device eligibility.",deliveredCopiesMayRemain:h.some(_=>_.deliveredCopiesMayRemain),action:tL(w,b?.state??"no_projects")}}).sort((u,p)=>u.displayName.localeCompare(p.displayName)||u.identityName.localeCompare(p.identityName)),revokedDeviceCount:e.identityDevices.filter(u=>u.status==="revoked"&&o.has(u.identityId)).length}}function vb({empty:e,projects:t}){return t.length===0?a("p",{className:"small",children:e}):a("ul",{children:t.map(n=>a("li",{children:[a("strong",{children:n.displayName}),a("span",{className:"small",children:[" ","— ",n.statusLabel,". ",n.statusCopy]})]},n.canonicalProjectIdentity))})}function ta(e){if(!(e instanceof Tl))return"Identity setup is unavailable. Refresh Devices and try again.";const t={binding_preview_busy:"Identity setup is busy. Wait a moment, then retry.",binding_commit_busy:"Identity setup is busy. Wait a moment, then retry.",binding_evidence_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_retry_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_rebind_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_unchanged_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_write_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",device_pairing_required:"Pair this device before assigning an Identity.",device_rebind_confirmation_required:"Reassignment requires a separate confirmation of the previous and target Identities.",device_inventory_incomplete:"The complete device inventory is unavailable. Refresh after coordinator evidence is available.",device_inventory_truncated:"The complete device inventory is unavailable. Refresh after coordinator evidence is available.",binding_write_conflict:"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.",binding_commit_conflict:"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.",device_evidence_conflict:"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.",target_identity_unavailable:"A selected device or Identity is no longer available. Refresh Devices and choose again.",device_unavailable:"A selected device or Identity is no longer available. Refresh Devices and choose again.",device_not_found:"A selected device or Identity is no longer available. Refresh Devices and choose again.",deciding_identity_unavailable:"The deciding Identity is unavailable. Open Identity administration to restore or replace it, then try again."}[e.errorCode];return t||(e.statusCode===503?"Identity setup is busy. Wait a moment, then retry.":e.statusCode===409?"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.":e.statusCode===404?"A selected device or Identity is no longer available. Refresh Devices and choose again.":"Identity setup could not be completed. Refresh Devices and try again.")}function vc(e,t){return{targetIdentityId:e.state==="setup_required"&&e.suggestedIdentityId&&t.has(e.suggestedIdentityId)?e.suggestedIdentityId:"",selected:!1,explicit:!1,itemSignature:na(e)}}function na(e){return JSON.stringify({deviceId:e.deviceId,evidenceDeviceIds:[...e.evidenceDeviceIds].sort(),state:e.state,identityId:e.identityId,suggestedIdentityId:e.suggestedIdentityId,validatedFingerprint:e.validatedFingerprint,isLocal:e.isLocal,sources:[...e.sources].sort(),conflictCodes:[...e.conflictCodes].sort()})}function yc(e,t,n,r){if(e.status!=="ready"||e.outcomes.length!==t.bindings.length)return!1;const i=new Set;return t.bindings.every(o=>{const s=n.find(l=>l.deviceId===o.deviceId),c=e.outcomes.findIndex((l,d)=>!i.has(d)&&s?.evidenceDeviceIds.includes(l.deviceId)===!0&&l.targetIdentityId===o.targetIdentityId&&l.action===r);return c<0?!1:(i.add(c),!0)})}var yb="devices-commit-status";function Bn(e){const t=document.getElementById(yb);t&&(t.textContent=e)}function rL({intent:e,inventory:t,items:n,options:r}){const i=e.identities.filter($=>$.status==="active"&&$.mergedIntoIdentityId===null),o=new Map(i.map($=>[$.identityId,$.displayName])),s=new Set(o.keys()),[c,l]=x(()=>Object.fromEntries(n.map($=>[$.deviceId,vc($,s)]))),[d,u]=x(null),[p,f]=x(!1),[m,v]=x(!1),[g,h]=x(""),b=B(null),w=B(0),_=r.previewBindings??Nm,R=r.commitBindings??Em,I=lp(r),T=d!==null&&yc(d.preview,d.request,n,"bind"),A=ke(()=>n.filter($=>$.state==="setup_required"&&c[$.deviceId]?.selected),[c,n]),O=JSON.stringify({items:t.items.map(na),coordinatorEvidence:t.coordinatorEvidence,truncated:t.truncated}),F=i.map($=>`${$.identityId}:${$.displayName}`).sort().join("|");V(()=>{d&&b.current?.focus()},[d]),V(()=>{w.current+=1,v(!1),l($=>Object.fromEntries(n.map(E=>{const S=$[E.deviceId];if(!S)return[E.deviceId,vc(E,s)];if(E.state!=="setup_required")return[E.deviceId,vc(E,s)];const M=S.targetIdentityId!==""&&s.has(S.targetIdentityId);return S.itemSignature===na(E)&&M?[E.deviceId,S]:S.explicit&&M?[E.deviceId,{...S,selected:!1,itemSignature:na(E)}]:[E.deviceId,vc(E,s)]}))),u(null),f(!1)},[O,F]);const N=($,E)=>{w.current+=1,v(!1),l(S=>({...S,[$]:{...S[$],...E}})),u(null),f(!1),h(""),Bn("")},L=$=>({bindings:$.map(E=>{const S=c[E.deviceId];return{deviceId:E.deviceId,targetIdentityId:S?.targetIdentityId??"",confirmed:!0}})}),D=async $=>{if(I){h("Refresh Devices before reviewing Identity setup.");return}if($.some(M=>M.state!=="setup_required")){h("Only devices that require Identity setup can be reviewed here.");return}const E=$.find(M=>bs(t,M).blocked);if(E){h(bs(t,E).recovery??"Identity setup is unavailable.");return}if($.length===0||$.some(M=>!c[M.deviceId]?.targetIdentityId)){h("Choose an Identity for every selected device before review.");return}v(!0),h(""),Bn("");const S=w.current;try{const M=L($),H=await _(M);S===w.current&&(yc(H,M,$,"bind")?u({preview:H,request:M}):h("Identity setup preview was incomplete. Refresh and try again."))}catch(M){S===w.current&&h(ta(M))}S===w.current&&v(!1)},G=async()=>{if(!(!d||!p||I||!T)){v(!0),h("");try{await R({...d.request,reviewedInventoryDigest:d.preview.reviewedInventoryDigest}),u(null),f(!1),Bn("Identity setup completed.");const $=await r.onCommitted?.();Bn($===!1?"Identity setup completed, but refreshing Devices and Sharing failed. Refresh to see current state.":$===!0?"Identity setup completed. Devices and Sharing were refreshed.":"Identity setup completed."),document.getElementById("devices-heading")?.focus()}catch($){h(ta($))}v(!1)}},q=n.filter($=>$.state==="setup_required");return n.length===0?null:a(z,{children:[g?a("p",{role:"alert",children:g}):null,q.length>1?a("div",{className:"device-identity-setup-summary",children:[a("strong",{children:[q.length.toLocaleString()," devices need Identity setup"]}),a("button",{className:"settings-button",disabled:m||I||A.length===0,onClick:()=>{D(A)},type:"button",children:["Review ",A.length.toLocaleString()," selected"]})]}):null,a("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:n.map(($,E)=>{const S=c[$.deviceId],M=bs(t,$),H=M.blocked||I,U=`device-inventory-title-${E}`;return a("li",{children:a("article",{"aria-labelledby":U,className:"peer-card peer-card--padded recipient-policy-sharing-card device-identity-setup-card",id:`device-identity-card-${$.deviceId}`,tabIndex:-1,children:[a("div",{className:"peer-title recipient-policy-sharing-card-title",children:[a("h3",{id:U,children:[$.displayName,$.isLocal?" (this device)":""]}),a("span",{className:"badge actor-badge",children:$.state==="setup_required"?"Setup required":$.state==="pairing_required"?"Pairing required":$.state==="conflicted"?"Review required":"Configured"})]}),$.state==="setup_required"?a(z,{children:[a("fieldset",{children:[a("legend",{children:"Assign an existing Identity"}),i.length===0?a("p",{children:"No active Identity is available. Create or restore an Identity before setup."}):null,q.length>1?a("label",{children:[a("input",{"aria-label":`Select for setup: ${$.displayName}`,checked:S?.selected??!1,disabled:H,onInput:re=>N($.deviceId,{selected:re.currentTarget.checked}),type:"checkbox"})," ","Select for setup"]}):null,a("label",{htmlFor:`${U}-identity`,children:"Identity"}),a("select",{"aria-label":`Choose an Identity for ${$.displayName}`,disabled:H,id:`${U}-identity`,onInput:re=>N($.deviceId,{targetIdentityId:re.currentTarget.value,explicit:!0}),value:S?.targetIdentityId??"",children:[a("option",{value:"",children:"Choose Identity…"}),i.map(re=>a("option",{value:re.identityId,children:re.displayName},re.identityId))]}),$.suggestedIdentityId&&o.has($.suggestedIdentityId)?a("p",{className:"small",children:"Suggested from historical device information. Review it before applying setup."}):null,M.recovery?a("p",{className:"small",children:M.recovery}):null]}),a("div",{className:"device-identity-card-actions",children:[i.length===0?a("button",{"aria-label":`Open Identity administration for ${$.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Open Identity administration"}):null,a("button",{"aria-label":`Review this device: ${$.displayName}`,className:"settings-button",disabled:m||H||!S?.targetIdentityId,onClick:()=>{D([$])},type:"button",children:"Review this device"})]})]}):$.state==="pairing_required"?a(z,{children:[a("p",{children:"Pair this device first. Pairing establishes trust but does not choose its Identity."}),a("div",{className:"device-identity-card-actions",children:a("button",{"aria-label":`Go to pairing for ${$.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Go to pairing"})})]}):$.state==="conflicted"?a(z,{children:[a("p",{children:"Device evidence conflicts. Review and repair it before assigning an Identity."}),a("div",{className:"device-identity-card-actions",children:a("button",{"aria-label":`Open Advanced review for ${$.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Open Advanced review"})})]}):null]})},$.deviceId)})}),d?a("section",{"aria-labelledby":"device-identity-review-heading",className:"peer-card peer-card--padded device-identity-review-panel",children:[a("h3",{id:"device-identity-review-heading",ref:b,tabIndex:-1,children:"Review Identity setup"}),a("ul",{children:d.preview.outcomes.map($=>a("li",{children:[a("strong",{children:[$.displayName,":"]})," ",$.previousIdentityId?o.get($.previousIdentityId)??"Unavailable Identity":"No Identity"," ","→ ",o.get($.targetIdentityId)??"Unavailable Identity"]},$.deviceId))}),a("p",{children:"Identity setup records device ownership only. It does not grant Projects, Team membership, or sync access."}),a("label",{children:[a("input",{checked:p,disabled:I,onInput:$=>f($.currentTarget.checked),type:"checkbox"})," ","I reviewed every device and target Identity"]}),a("div",{className:"peer-actions",children:[a("button",{className:"settings-button",disabled:m,onClick:()=>{u(null),f(!1)},type:"button",children:"Back"}),a("button",{className:"settings-button sync-dialog-confirm",disabled:m||I||!p||!T,onClick:()=>{G()},type:"button",children:["Apply setup to ",d.request.bindings.length.toLocaleString()," ",d.request.bindings.length===1?"device":"devices"]})]})]}):null]})}function bb({intent:e,inventory:t,item:n,options:r,previousIdentityName:i}){const o=e.identities.filter(S=>S.status==="active"&&S.mergedIntoIdentityId===null&&S.identityId!==n.identityId),[s,c]=x(!1),[l,d]=x(""),[u,p]=x(!1),[f,m]=x(null),[v,g]=x(!1),[h,b]=x(!1),[w,_]=x(""),R=B(0),I=i,T=new Map(e.identities.map(S=>[S.identityId,S.displayName])),A=f?.preview.status==="ready"&&f.preview.outcomes.length===1?f.preview.outcomes[0]:null,O=f!==null&&yc(f.preview,f.request,[n],"rebind"),F=bs(t,n),N=F.blocked||lp(r),L=`configured-rebind-trigger-${n.deviceId}`,D=o.find(S=>S.identityId===l)?.displayName??"",G=o.map(S=>S.identityId).sort().join("|"),q=na(n);V(()=>{R.current+=1,b(!1),l&&!o.some(S=>S.identityId===l)&&(d(""),p(!1)),m(null),g(!1)},[G,q]);const $=async()=>{if(N){_(F.recovery??"Identity reassignment is unavailable.");return}if(!l||!u){_("Choose a target Identity and confirm the reassignment before review.");return}b(!0),_(""),Bn("");const S=R.current;try{const M={bindings:[{deviceId:n.deviceId,targetIdentityId:l,confirmed:u,allowRebind:!0}]},H=await(r.previewBindings??Nm)(M);S===R.current&&(H.status!=="ready"?_(ta(new Tl(409,H.errorCode??"binding_preview_unavailable",H))):yc(H,M,[n],"rebind")?m({preview:H,request:M}):_("Identity reassignment preview was incomplete. Refresh and try again."))}catch(M){S===R.current&&_(ta(M))}S===R.current&&b(!1)},E=async()=>{if(!(!f||!v||N||!O)){b(!0),_("");try{await(r.commitBindings??Em)({...f.request,reviewedInventoryDigest:f.preview.reviewedInventoryDigest}),c(!1),d(""),p(!1),m(null),g(!1),Bn("Identity reassignment completed.");const S=await r.onCommitted?.();Bn(S===!1?"Identity reassignment completed, but refreshing Devices and Sharing failed. Refresh to see current state.":S===!0?"Identity reassignment completed. Devices and Sharing were refreshed.":"Identity reassignment completed."),(document.getElementById(L)??document.getElementById("devices-heading"))?.focus()}catch(S){_(ta(S))}b(!1)}};return a("div",{className:"device-identity-rebind",children:[a("button",{"aria-expanded":s,className:"settings-button",disabled:N,id:L,onClick:()=>{R.current+=1,b(!1),c(!s),m(null),g(!1),_(""),Bn("")},type:"button",children:"Change Identity…"}),F.recovery?a("p",{className:"small",children:F.recovery}):null,s?a("fieldset",{children:[a("legend",{children:"Reassign this configured device"}),a("p",{children:[a("strong",{children:"Suggested current Identity (unconfirmed):"})," ",I]}),a("label",{htmlFor:`configured-rebind-${n.deviceId}`,children:"Target Identity"}),a("select",{disabled:N,id:`configured-rebind-${n.deviceId}`,onInput:S=>{R.current+=1,b(!1),d(S.currentTarget.value),p(!1),m(null),g(!1)},value:l,children:[a("option",{value:"",children:"Choose a different Identity…"}),o.map(S=>a("option",{value:S.identityId,children:S.displayName},S.identityId))]}),a("label",{children:[a("input",{checked:u,disabled:N||!l,onInput:S=>{R.current+=1,b(!1),p(S.currentTarget.checked),m(null),g(!1)},type:"checkbox"})," ","Confirm reassigning ",n.displayName," to ",D||"the selected Identity"]}),a("button",{className:"settings-button",disabled:h||N,onClick:()=>{$()},type:"button",children:"Review reassignment"}),f?a("div",{className:"device-identity-rebind-review",children:[a("h4",{children:"Review reassignment"}),a("p",{children:[A?.displayName,":"," ",A?.previousIdentityId?T.get(A.previousIdentityId)??"Unavailable Identity":"No Identity"," ","→"," ",T.get(A?.targetIdentityId??"")??"Unavailable Identity"]}),a("p",{className:"small",children:"This changes device ownership only. It does not grant Projects, Team membership, or sync access."}),a("label",{children:[a("input",{checked:v,disabled:N,onInput:S=>g(S.currentTarget.checked),type:"checkbox"})," ","I reviewed the previous and target Identities"]}),a("button",{className:"settings-button sync-dialog-confirm",disabled:h||N||!v||!O,onClick:()=>{E()},type:"button",children:"Reassign Identity"})]}):null,w?a("p",{"aria-live":"assertive",role:"alert",children:w}):null]}):null]})}function iL({intent:e,options:t,projection:n}){if(t.loading)return a(Ug,{label:"Loading Devices"});if(t.loadError)return a("p",{"aria-live":"assertive",role:"alert",children:"Devices are unavailable. Refresh and try again."});const r=t.refreshError?a("p",{"aria-live":"assertive",role:"alert",children:"Refresh failed; showing previous device information. Identity setup is disabled until a refresh succeeds."}):null,i=n.devices.filter(f=>!t.inventory?.items.some(m=>m.state!=="configured"&&m.evidenceDeviceIds.includes(f.deviceId))),o=new Set(i.map(f=>f.deviceId)),s=t.inventoryUnavailable?a("p",{"aria-live":"polite",className:"small",role:"status",children:"Device ownership information is temporarily unavailable. Existing device details remain visible, but Identity setup is disabled until a refresh succeeds."}):null,c=Gg(t.inventory),l=t.inventory?.items.filter(f=>f.state==="configured"&&!f.evidenceDeviceIds.some(m=>o.has(m)))??[],d=t.inventory?a("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:l.map((f,m)=>{const v=`configured-inventory-title-${m}`,g=e.identities.find(h=>h.identityId===f.identityId)?.displayName??"Unavailable Identity";return a("li",{children:a("article",{"aria-labelledby":v,className:"peer-card peer-card--padded recipient-policy-sharing-card",id:`device-identity-card-${f.deviceId}`,tabIndex:-1,children:[a("div",{className:"peer-title recipient-policy-sharing-card-title",children:[a("h3",{id:v,children:f.displayName}),a("span",{className:"badge actor-badge",children:"Configured · Availability unknown"})]}),a("p",{children:[a("strong",{children:"Owning Identity:"})," ",g]}),a(bb,{intent:e,inventory:t.inventory,item:f,options:t,previousIdentityName:g})]})},f.deviceId)})}):null,u=(t.coordinatorEnrollmentIssueCount??0)>0?a("aside",{"aria-labelledby":"devices-coordinator-reconciliation-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[a("h3",{id:"devices-coordinator-reconciliation-heading",children:"Coordinator setup needs attention"}),a("p",{children:[t.coordinatorEnrollmentIssueCount?.toLocaleString()," coordinator enrollment",t.coordinatorEnrollmentIssueCount===1?" could":"s could"," not be safely reconciled with device Identity setup."]}),a("p",{className:"small",children:["No ownership was inferred."," ",c.length>0?"Review the affected device setup or pairing state here, then retry after coordinator data is corrected.":"No device on this page can be corrected from here. Retry after coordinator data is corrected."]})]}):null,p=t.inventory?a(z,{children:[t.inventory.truncated?a("p",{"aria-live":"assertive",role:"alert",children:"The device inventory is incomplete. Identity setup is unavailable until a complete refresh succeeds."}):null,t.inventory.coordinatorEvidence.availability==="unavailable"?a("p",{className:"small",role:"status",children:"Coordinator device information is temporarily unavailable. Local devices remain visible, but some setup actions may require a refresh."}):null,a(rL,{intent:e,inventory:t.inventory,items:c,options:t})]}):null;return i.length===0?a(z,{children:[r,s,u,p,d,a("p",{className:"small",role:"status",children:[l.length>0?"No additional active devices are registered.":c.length>0?"No configured devices are registered.":"No active devices are registered.",n.revokedDeviceCount>0?` ${n.revokedDeviceCount.toLocaleString()} revoked ${n.revokedDeviceCount===1?"device is":"devices are"} not shown.`:""]})]}):a(z,{children:[r,s,u,p,d,a("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:i.map((f,m)=>{const v=`devices-card-title-${m}`,g=f.action,h=t.inventory?.items.find(b=>b.state==="configured"&&b.evidenceDeviceIds.includes(f.deviceId));return a("li",{children:a("article",{"aria-labelledby":v,className:"peer-card peer-card--padded recipient-policy-sharing-card",id:`device-identity-card-${f.deviceId}`,tabIndex:-1,children:[a("div",{className:"peer-title recipient-policy-sharing-card-title",children:[a("h3",{id:v,children:f.displayName}),a("span",{className:"badge actor-badge",children:[lp(t)?"Device":"Configured"," ·"," ",f.availabilityLabel]})]}),a("dl",{className:"recipient-policy-sharing-details",children:[a("div",{children:[a("dt",{children:"Owning Identity"}),a("dd",{children:f.identityName})]}),a("div",{children:[a("dt",{children:"Availability"}),a("dd",{children:f.availabilityLabel})]}),f.isPairedPeer?a("div",{children:[a("dt",{children:"Codemem version"}),a("dd",{children:f.reportedRuntimeVersion??"Not reported"})]}):null,a("div",{children:[a("dt",{children:"Sharing status"}),a("dd",{children:[a("strong",{children:f.statusLabel})," — ",f.statusCopy]})]})]}),a("section",{"aria-labelledby":`${v}-direct`,children:[a("h4",{id:`${v}-direct`,children:"Direct Projects"}),a(vb,{empty:"No Projects are shared directly.",projects:f.directProjects})]}),a("section",{"aria-labelledby":`${v}-teams`,children:[a("h4",{id:`${v}-teams`,children:"Projects through Teams"}),a(vb,{empty:"Per-device Team access is not shown because Team membership alone does not prove this device receives the Team’s Projects.",projects:f.inheritedProjects})]}),f.unavailableProjectCount>0?a("p",{className:"small",role:"status",children:"Some Project names are unavailable and are not shown."}):null,f.deliveredCopiesMayRemain?a("p",{className:"small",children:[a("strong",{children:"Delivered copies:"})," Changing access stops future delivery, but copies already delivered may remain on this device or in backups."]}):null,g&&t.onNavigate?a("button",{"aria-label":`${g.label} for ${f.displayName}`,className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onNavigate?.(g.target),ref:b=>{b&&dp.set(b,{deviceId:f.deviceId,target:g.target})},type:"button",children:g.label}):null,h&&t.inventory?a(bb,{intent:e,inventory:t.inventory,item:h,options:t,previousIdentityName:f.identityName}):null]})},f.deviceId)})}),n.revokedDeviceCount>0?a("p",{className:"small",role:"status",children:[n.revokedDeviceCount.toLocaleString()," revoked"," ",n.revokedDeviceCount===1?"device is":"devices are"," not included in the active list."]}):null]})}function bc(e,t,n,r,i,o={}){const s=document.activeElement,c=s instanceof HTMLElement&&e.contains(s),l=c?dp.get(s):void 0,d=nL(t,n,r,i,o.peerRuntimeMetadata);if(Ue(a("section",{"aria-labelledby":"devices-heading",className:"recipient-policy-sharing recipient-policy-sharing-responsive-surface",children:[a("div",{className:"recipient-policy-sharing-header",children:[a("h2",{id:"devices-heading",tabIndex:-1,children:"Devices"}),a("p",{className:"small",children:"See where Codemem runs and which Projects each active device receives."})]}),a(iL,{intent:t,options:o,projection:d}),a("p",{"aria-live":"polite",id:yb,role:"status"})]}),e),Bn(""),!o.loading&&C.pendingDeviceIdentityFocus!==void 0){const u=C.pendingDeviceIdentityFocus,p=o.inventory?.items.find(m=>m.deviceId===u||m.evidenceDeviceIds.includes(u??"")),f=[...u?[u]:[],...p?[p.deviceId,...p.evidenceDeviceIds]:[]].map(m=>document.getElementById(`device-identity-card-${m}`)).find(m=>m instanceof HTMLElement)??document.getElementById("device-identity-review-heading");if(c)C.pendingDeviceIdentityFocus=void 0;else if(f){C.pendingDeviceIdentityFocus=void 0,f.focus();return}else if(!o.inventoryUnavailable&&!o.refreshError){C.pendingDeviceIdentityFocus=void 0,(document.getElementById("devices-heading")??document.getElementById("tabBtn-devices"))?.focus();return}}l&&([...e.querySelectorAll("button")].find(u=>{const p=dp.get(u);return p?.deviceId===l.deviceId&&p.target===l.target})??document.getElementById("tabBtn-devices"))?.focus()}function oL(e){if(!e)return"n/a";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function Vr(e){if(!e)return"never";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function aL(e){if(!e)return"n/a";const t=new Date(e),n=t.getTime();if(Number.isNaN(n))return String(e);const r=Date.now()-n,i=Math.round(r/1e3);if(i<10)return"just now";if(i<60)return`${i}s ago`;const o=Math.round(i/60);if(o<60)return`${o}m ago`;const s=Math.round(o/60);if(s<24)return`${s}h ago`;const c=Math.round(s/24);return c<14?`${c}d ago`:t.toLocaleDateString()}function zi(e){if(!e)return null;const t=new Date(e).getTime();if(!Number.isFinite(t))return null;const n=Math.floor((Date.now()-t)/1e3);return n>=0?n:0}function sr(e){return e==null?"n/a":e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m`:e<86400?`${Math.floor(e/3600)}h`:`${Math.floor(e/86400)}d`}function _b(e){const t=Number(e);return Number.isFinite(t)?`${Math.round(t*100)}%`:"n/a"}function sL(e,t){const n=Number(e||0),r=Number(t||0);if(!Number.isFinite(n)||!Number.isFinite(r)||r<=0)return"n/a";const i=(n+r)/r;return!Number.isFinite(i)||i<=0?"n/a":`${i.toFixed(i>=10?0:1)}x`}function up(e,t){const n=Number(e||0),r=Number(t||0);if(!Number.isFinite(n)||!Number.isFinite(r))return"n/a";const i=n+r;if(i<=0)return"n/a";const o=n/i;return Number.isFinite(o)?`${Math.round(o*100)}%`:"n/a"}function Wi(e){const t=Number(e||0);if(!Number.isFinite(t))return"n/a";const n=[{threshold:1e9,suffix:"B"},{threshold:1e6,suffix:"M"},{threshold:1e3,suffix:"K"}];let r=n.findIndex(({threshold:i})=>Math.abs(t)>=i);if(r===-1)return`${t.toLocaleString()} tokens`;for(;r>=0;){const{suffix:i,threshold:o}=n[r],s=t/o,c=Number(s.toFixed(s>=10?0:1));if(Math.abs(c)<1e3||r===0)return`${c.toString().replace(/\.0$/,"")}${i} tokens`;r-=1}return`${t.toLocaleString()} tokens`}function cL(e){const t=String(e||"").trim();if(!t.endsWith("%"))return null;const n=Number(t.replace("%",""));return Number.isFinite(n)?n:null}function ra(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function _c(e){if(!e)return[];if(Array.isArray(e))return e;if(typeof e=="string")try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}return[]}function wb(e){const t=String(e||"").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function lL(e){return e.replace(/_/g," ").split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ").trim()}function dL(e,t=2){if(!e.length)return"";const n=e.map(o=>String(o).trim()).filter(Boolean),r=n.slice(0,t),i=n.length>t?` +${n.length-t}`:"";return`${r.join(", ")}${i}`.trim()}function uL(e){if(!e)return"";const t=String(e).trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n).trim()}function pL(e){const t=String(e||"");return t?t.replace(/^\/Users\/[^/]+(?=\/|$)/,"~").replace(/^\/home\/[^/]+(?=\/|$)/,"~").replace(/^[A-Z]:\\Users\\[^\\]+(?=\\|$)/,"~"):""}function fL(e){const t=Number(e||0);if(!Number.isFinite(t)||t<0)return"n/a";if(t<1024)return`${t} B`;const n=["KB","MB","GB","TB","PB"],r=s=>s>=10?Math.round(s):Number(s.toFixed(1));let i=t/1024,o=0;for(;o<n.length-1&&r(i)>=1024;)i/=1024,o+=1;return`${String(r(i)).replace(/\.0$/,"")} ${n[o]}`}function Sb(e){if(e.owned_by_self===!0)return!0;const t=String(e.actor_id||"").trim();return!!(t&&t===C.lastStatsPayload?.identity?.actor_id)}function wc(e){if(!e||typeof e!="object")return{};const t=e,n=t.import_metadata;return n&&typeof n=="object"?{...n,...t}:t}function mL(e){if(!e)return[];const t=String(e).split(`
42
- `).map(n=>n.trim()).filter(Boolean).filter(n=>/^[-*\u2022]\s+/.test(n)||/^\d+\./.test(n));return t.length?t.map(n=>n.replace(/^[-*\u2022]\s+/,"").replace(/^\d+\.\s+/,"")):[]}function hL(e,t=6){const n=String(e||"").trim();if(!n)return[];const r=n.replace(/\s+/g," ").trim().split(/(?<=[.!?])\s+/).map(o=>o.trim()).filter(Boolean),i=[];for(const o of r)if(!(o.length<18)&&(i.push(o),i.length>=t))break;return i}function Cb(e){const t=ra(e.title),n=ra(e.body_text);if(!t&&!n)return!0;const r=n||t;if(r.length<10||t&&n&&t===n&&r.length<40)return!0;const i=t.charAt(0);return!!((i==="└"||i==="›")&&r.length<40||t.startsWith("list ")&&r.length<20||r==="ls"||r==="list ls")}function Rb(e){return String(e.id??e.memory_id??e.observation_id??e.session_id??e.created_at_utc??e.created_at??"")}function Tt(e){return`${String(e.kind||"").toLowerCase()}:${Rb(e)}`}function gL(e){if(e.tags!=null)return _c(e.tags);const t=_c(e.tags_text);return t.length>0?t:typeof e.tags_text!="string"?[]:e.tags_text.trim().split(/\s+/).filter(Boolean)}function vL(e){return e==="mine"?" · my memories":e==="theirs"?" · other people":""}function yL(e){return e==="legacy_unknown"?"legacy provenance":e==="unreviewed"?"unreviewed":e.replace(/_/g," ")}function bL(e){if(Sb(e))return"You";const t=String(e.actor_id||"").trim(),n=Ti(e.resolved_actor_display_name);return n||(t||e.actor_display_name?"Teammate":"Unknown author")}function _L(e,t={}){if(Sb(e)||!String(e.origin_device_id||t.origin_device_id||"").trim())return"";const n=Ti(e.resolved_device_display_name);return n?`Device ${n}`:"Shared device"}function Ib(e,t){const n=new Map;return e.forEach(r=>{n.set(Tt(r),r)}),t.forEach(r=>{n.set(Tt(r),r)}),Array.from(n.values()).sort((r,i)=>new Date(i.created_at||0).getTime()-new Date(r.created_at||0).getTime())}function wL(e,t){const n=new Set(t.map(Tt));return Ib(e.filter(r=>!n.has(Tt(r))),t)}var Q2=560;function SL(){const e=document.documentElement,t=Math.max(e.scrollHeight,document.body.scrollHeight);return window.innerHeight+window.scrollY>=t-560}function Sc(e,t,n){const r=e.pagination?.has_more;return typeof r=="boolean"?r:t>=n}function Cc(e,t){const n=e.pagination?.next_offset;return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:t}function CL(e,t){const n=new Set(t.map(Tt));return e.filter(r=>!n.has(Tt(r))).length}var RL=Object.defineProperty,it=(e,t)=>RL(e,"name",{value:t,configurable:!0}),[pp,Z2]=dt("Tooltip",[tr]),Rc=tr(),IL="TooltipProvider",kL=700,fp="tooltip.open",[TL,mp]=pp(IL),PL=it(e=>{const{__scopeTooltip:t,delayDuration:n=kL,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:o}=e,s=B(!0),c=B(!1),l=B(0);return V(()=>{const d=l.current;return()=>window.clearTimeout(d)},[]),a(TL,{scope:t,isOpenDelayedRef:s,delayDuration:n,onOpen:ae(()=>{r<=0||(window.clearTimeout(l.current),s.current=!1)},[r]),onClose:ae(()=>{r<=0||(window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.current=!0,r))},[r]),isPointerInTransitRef:c,onPointerInTransitChange:ae(d=>{c.current=d},[]),disableHoverableContent:i,children:o})},"TooltipProvider"),hp="Tooltip",[NL,ia]=pp(hp),EL=it(e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:o,disableHoverableContent:s,delayDuration:c}=e,l=mp(hp,e.__scopeTooltip),d=Rc(t),[u,p]=x(null),[f,m]=x(void 0),v=Et(),g=B(0),h=s??l.disableHoverableContent,b=c??l.delayDuration,w=B(!1),[_,R]=At({prop:r,defaultProp:i??!1,onChange:it(N=>{N?(l.onOpen(),document.dispatchEvent(new CustomEvent(fp))):l.onClose(),o?.(N)},"onChange"),caller:hp}),I=ke(()=>_?w.current?"delayed-open":"instant-open":"closed",[_]),T=ae(()=>{window.clearTimeout(g.current),g.current=0,w.current=!1,R(!0)},[R]),A=ae(()=>{window.clearTimeout(g.current),g.current=0,R(!1)},[R]),O=ae(()=>{window.clearTimeout(g.current),g.current=window.setTimeout(()=>{w.current=!0,R(!0),g.current=0},b)},[b,R]);return V(()=>()=>{g.current&&(window.clearTimeout(g.current),g.current=0)},[]),a(nc,{...d,children:a(NL,{scope:t,contentId:f??v,setContentId:m,open:_,stateAttribute:I,trigger:u,onTriggerChange:p,onTriggerEnter:ae(()=>{l.isOpenDelayedRef.current?O():T()},[l.isOpenDelayedRef,O,T]),onTriggerLeave:ae(()=>{h?A():(window.clearTimeout(g.current),g.current=0)},[A,h]),onOpen:T,onClose:A,disableHoverableContent:h,children:n})})},"Tooltip"),kb="TooltipTrigger",AL=J(it(function(t,n){const{__scopeTooltip:r,...i}=t,o=ia(kb,r),s=mp(kb,r),c=Rc(r),l=B(null),d=Re(n,l,o.onTriggerChange),u=B(!1),p=B(!1),f=ae(()=>u.current=!1,[]);return V(()=>()=>document.removeEventListener("pointerup",f),[f]),a(Xo,{asChild:!0,...c,children:a(ye.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...i,ref:d,onPointerMove:te(t.onPointerMove,m=>{m.pointerType!=="touch"&&!p.current&&!s.isPointerInTransitRef.current&&(o.onTriggerEnter(),p.current=!0)}),onPointerLeave:te(t.onPointerLeave,()=>{o.onTriggerLeave(),p.current=!1}),onPointerDown:te(t.onPointerDown,()=>{o.open&&o.onClose(),u.current=!0,document.addEventListener("pointerup",f,{once:!0})}),onFocus:te(t.onFocus,()=>{u.current||o.onOpen()}),onBlur:te(t.onBlur,o.onClose),onClick:te(t.onClick,o.onClose)})})},"TooltipTrigger")),Tb="TooltipPortal",[xL,DL]=pp(Tb,{forceMount:void 0}),LL=it(e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,o=ia(Tb,t);return a(xL,{scope:t,forceMount:n,children:a(kt,{present:n||o.open,children:a(_i,{asChild:!0,container:i,children:r})})})},"TooltipPortal"),oa="TooltipContent",$L=J(it(function(t,n){const r=DL(oa,t.__scopeTooltip),{forceMount:i=r.forceMount,side:o="top",...s}=t,c=ia(oa,t.__scopeTooltip);return a(kt,{present:i||c.open,children:c.disableHoverableContent?a(Pb,{side:o,...s,ref:n}):a(OL,{side:o,...s,ref:n})})},"TooltipContent")),OL=J(it(function(t,n){const r=ia(oa,t.__scopeTooltip),i=mp(oa,t.__scopeTooltip),o=B(null),s=Re(n,o),[c,l]=x(null),{trigger:d,onClose:u}=r,p=o.current,{onPointerInTransitChange:f}=i,m=ae(()=>{l(null),f(!1)},[f]),v=ae((g,h)=>{const b=g.currentTarget,w={x:g.clientX,y:g.clientY},_=Eb(w,Nb(w,b.getBoundingClientRect())),R=Ab(h.getBoundingClientRect()),I=Db([..._,...R]);l(I),f(!0)},[f]);return V(()=>()=>m(),[m]),V(()=>{if(d&&p){const g=it(b=>v(b,p),"handleTriggerLeave"),h=it(b=>v(b,d),"handleContentLeave");return d.addEventListener("pointerleave",g),p.addEventListener("pointerleave",h),()=>{d.removeEventListener("pointerleave",g),p.removeEventListener("pointerleave",h)}}},[d,p,v,m]),V(()=>{if(c){const g=it(h=>{const b=h.target,w={x:h.clientX,y:h.clientY},_=d?.contains(b)||p?.contains(b),R=!xb(w,c);_?m():R&&(m(),u())},"handleTrackPointerGrace");return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[d,p,c,u,m]),a(Pb,{...t,ref:s})},"TooltipContentHoverable")),jL=Wh("TooltipContent"),Pb=J(it(function(t,n){const{__scopeTooltip:r,children:i,"aria-label":o,id:s,onEscapeKeyDown:c,onPointerDownOutside:l,...d}=t,u=ia(oa,r),p=Rc(r),{onClose:f}=u;V(()=>(document.addEventListener(fp,f),()=>document.removeEventListener(fp,f)),[f]),V(()=>{if(u.trigger){const v=it(g=>{g.target instanceof Node&&g.target.contains(u.trigger)&&f()},"handleScroll");return window.addEventListener("scroll",v,{capture:!0}),()=>window.removeEventListener("scroll",v,{capture:!0})}},[u.trigger,f]);const{setContentId:m}=u;return Ze(()=>(m(s),()=>{m(void 0)}),[s,m]),a(bi,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:v=>v.preventDefault(),onDismiss:f,children:a(rc,{"data-state":u.stateAttribute,role:o?void 0:"tooltip",id:o?void 0:u.contentId,...p,...d,ref:n,style:{...d.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[a(jL,{children:i}),o?a(oN,{id:u.contentId,role:"tooltip",children:o}):null]})})},"TooltipContentImpl")),ML=J(it(function(t,n){const{__scopeTooltip:r,...i}=t,o=Rc(r);return a(fx,{...o,...i,ref:n})},"TooltipArrow"));function Nb(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),o=Math.abs(t.left-e.x);switch(Math.min(n,r,i,o)){case o:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}it(Nb,"getExitSideFromRect");function Eb(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n})}return r}it(Eb,"getPaddedExitPoints");function Ab(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}it(Ab,"getPointsFromRect");function xb(e,t){const{x:n,y:r}=e;let i=!1;for(let o=0,s=t.length-1;o<t.length;s=o++){const c=t[o],l=t[s],d=c.x,u=c.y,p=l.x,f=l.y;u>r!=f>r&&n<(p-d)*(r-u)/(f-u)+d&&(i=!i)}return i}it(xb,"isPointInPolygon");function Db(e){const t=e.slice();return t.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),Lb(t)}it(Db,"getHull");function Lb(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const i=e[r];for(;t.length>=2;){const o=t[t.length-1],s=t[t.length-2];if((o.x-s.x)*(i.y-s.y)>=(o.y-s.y)*(i.x-s.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const o=n[n.length-1],s=n[n.length-2];if((o.x-s.x)*(i.y-s.y)>=(o.y-s.y)*(i.x-s.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}it(Lb,"getHullPresorted");var FL=PL,BL=EL,qL=AL,UL=LL,GL=$L,HL=ML;function Ic({children:e,delayDuration:t=400,skipDelayDuration:n=300}){return a(FL,{delayDuration:t,skipDelayDuration:n,children:e})}function kc({children:e,label:t,side:n="top",align:r="center",sideOffset:i=6,asChild:o=!0,disabled:s=!1}){return s?a(z,{children:e}):a(BL,{children:[a(qL,{asChild:o,children:e}),a(UL,{children:a(GL,{align:r,className:"tooltip-content",side:n,sideOffset:i,children:[t,a(HL,{className:"tooltip-arrow"})]})})]})}function VL(e){e.dataset.feedRenderRoot="preact"}function KL(){const e=document.getElementById("tab-feed");e&&(e.dataset.feedRenderBoundary="preact-hybrid")}function zL(e,t){VL(e),Ue(y(Ic,null,t),e)}function WL(e){return e.hasInspectorOverride?e.inspectorQuery:e.feedQuery}function JL(e){return e.split(/\n|,/).map(t=>t.trim()).filter(Boolean)}function gp(e){return JSON.stringify([e.project,e.query.trim(),e.workingSetFiles])}function YL(e){const t=wc(e?.metadata_json),n=String(e?.subtitle||t?.subtitle||"").trim(),r=String(e?.narrative||t?.narrative||e?.body_text||"").trim(),i=ra(n),o=ra(r),s=!!r&&o!==i,c=_c(e?.facts||t?.facts||[]),l=c.length?c:mL(r||n),d=l.length?l:hL(r||n);return{summary:n,narrative:r,facts:d,hasSummary:!!n,hasFacts:d.length>0,hasNarrative:s}}function XL(e){const t=[];return e.hasSummary&&t.push({id:"summary",label:"Summary"}),e.hasFacts&&t.push({id:"facts",label:"Facts"}),e.hasNarrative&&t.push({id:"narrative",label:"Narrative"}),t}function QL(e){return e.hasSummary?"summary":e.hasFacts?"facts":"narrative"}function ZL(e,t){return e==="facts"?!1:e==="summary"?t.summary.length>260:t.narrative.length>320}function e$(e){return e==="summary"?["clamp","clamp-3"]:["clamp","clamp-5"]}function t$(e,t){const n=C.feedTypeFilter==="observations"?" · observations":C.feedTypeFilter==="summaries"?" · session summaries":"",r=vL(C.feedScopeFilter),i=!C.feedQuery.trim()&&C.lastFeedFilteredCount?` · ${C.lastFeedFilteredCount} observations filtered`:"";return`${e} items${n}${r}${C.feedQuery.trim()?` · matching "${C.feedQuery.trim()}"`:""}${i}${t?" · scroll for more":""}`}function Tc({label:e,candidates:t}){return t.length===0?null:y("div",{className:"trace-group"},y("div",{className:"section-meta"},e),y("div",{className:"feed-list"},t.map(n=>y("div",{className:"feed-card",key:`${e}:${n.id}`},y("div",{className:"feed-card-header"},[y("div",{className:"feed-card-title"},`${n.rank}. ${n.title}`),y("div",{className:"feed-card-meta"},`#${n.id} · ${n.kind}${n.section?` · ${n.section}`:""}`)]),y("div",{className:"feed-card-body"},[y("div",null,n.preview||"No preview available."),n.reasons.length?y("div",{className:"section-meta"},`Reasons: ${n.reasons.join(", ")}`):null])))))}function n$({open:e}){const[t,n]=x(()=>String(C.feedQuery||"")),[r,i]=x(!1),[o,s]=x(!1),[c,l]=x(""),[d,u]=x(!1),[p,f]=x(""),[m,v]=x(""),[g,h]=x(null),b=B(0),w=String(C.feedQuery||""),_=String(t||"").trim(),R=C.currentProject||null,I=JL(c),T=gp({project:R,query:_,workingSetFiles:I}),A=g&&gp({project:g.inputs.project,query:g.inputs.query,workingSetFiles:g.inputs.working_set_files})===T?g:null,O=p&&m===T?p:"";V(()=>{b.current+=1,u(!1),f(""),v(""),h(q=>!q||q.inputs.query!==_||q.inputs.project!==R?null:q)},[T]),V(()=>{e&&!r&&(n(WL({feedQuery:w,hasInspectorOverride:o,inspectorQuery:t})),i(!0))},[w,o,r,t,e]);const F=async()=>{const q=_,$=R,E=I,S=gp({project:$,query:q,workingSetFiles:E}),M=b.current+1;if(b.current=M,!q){f("Enter a query to inspect."),v(S),h(null);return}u(!0),f(""),v("");try{const H=await MC({context:q,project:$,working_set_files:E});if(M!==b.current)return;h(H)}catch(H){if(M!==b.current)return;f(H instanceof Error?H.message:String(H)),v(S),h(null)}finally{M===b.current&&u(!1)}},N=A?.retrieval.candidates.filter(q=>q.disposition==="selected")||[],L=A?.retrieval.candidates.filter(q=>q.disposition==="dropped")||[],D=A?.retrieval.candidates.filter(q=>q.disposition==="deduped")||[],G=A?.retrieval.candidates.filter(q=>q.disposition==="trimmed")||[];return e?y("div",{className:"feed-inspector"},y("div",{className:"feed-card",id:"contextInspectorPanel",style:"margin-top:12px;"},[y("div",{className:"feed-card-header"},[y("div",{className:"feed-card-title"},"Context Inspector"),y("div",{className:"feed-card-meta"},o?"Tracing an inspector-specific query":"Seeded from the feed search on first open")]),y("div",{className:"feed-card-body"},[y("input",{className:"feed-search",onInput:q=>{n(String(q.currentTarget.value||"")),s(!0),h(null),f(""),v("")},placeholder:"Trace a pack query…",value:t}),y("div",{className:"section-meta",style:"margin-top:8px;"},o?"Inspector query is independent from the live feed search.":"Inspector query was seeded from the feed search and will stay independent until you change it."),y("textarea",{className:"feed-inspector-files",onInput:q=>l(String(q.currentTarget.value||"")),placeholder:"Optional working-set files, one per line",rows:3,value:c}),y("div",{style:"display:flex; gap:8px; margin-top:8px; align-items:center;"},y("button",{className:"toggle-button active",disabled:d,onClick:()=>{F()},type:"button"},d?"Tracing…":"Run trace"),A?y("span",{className:"section-meta"},`mode=${A.mode.selected} · candidates=${A.retrieval.candidate_count} · tokens=${A.output.estimated_tokens}`):null),g&&!A?y("div",{className:"section-meta",style:"margin-top:8px;"},"Trace inputs changed. Run trace again for the current query, project, and working set."):null,O?y("div",{className:"section-meta",style:"margin-top:8px; color:#d96c6c;"},O):null]),A?y(z,null,[y(Tc,{label:"Selected",candidates:N}),y(Tc,{label:"Dropped",candidates:L}),y(Tc,{label:"Deduped",candidates:D}),y(Tc,{label:"Trimmed",candidates:G}),y("div",{className:"feed-card-body"},[A.assembly.collapsed_groups.length?y("div",{className:"section-meta"},`Collapsed duplicates: ${A.assembly.collapsed_groups.map(q=>`kept #${q.kept} from [${q.dropped.join(", ")}]`).join(" · ")}`):null,A.assembly.trim_reasons.length?y("div",{className:"section-meta"},`Trim reasons: ${A.assembly.trim_reasons.join(", ")}`):null,y("div",{className:"section-meta"},"Final pack"),y("pre",{style:"white-space:pre-wrap; overflow:auto;"},A.output.pack_text)])]):null])):null}var r$={kind:"kind-chip",provenance:"provenance-chip",tag:"tag-chip",badge:"badge",scope:"peer-scope-chip"};function vp({variant:e,tone:t,title:n,children:r}){const i=r$[e],o=t?`${i} ${t}`:i;return a("span",{className:o,title:n,children:r})}function $b(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function i$(e){if(Array.isArray(e))return e}function o$(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,o,s,c=[],l=!0,d=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(l=(r=o.call(n)).done)&&(c.push(r.value),c.length!==t);l=!0);}catch(u){d=!0,i=u}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw i}}return c}}function a$(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
43
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function s$(e,t){return i$(e)||o$(e,t)||c$(e,t)||a$()}function c$(e,t){if(e){if(typeof e=="string")return $b(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?$b(e,t):void 0}}var Ob=Object.entries,jb=Object.setPrototypeOf,l$=Object.isFrozen,d$=Object.getPrototypeOf,u$=Object.getOwnPropertyDescriptor,ot=Object.freeze,st=Object.seal,Ji=Object.create,Mb=typeof Reflect<"u"&&Reflect,yp=Mb.apply,bp=Mb.construct;ot||(ot=function(t){return t}),st||(st=function(t){return t}),yp||(yp=function(t,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),o=2;o<r;o++)i[o-2]=arguments[o];return t.apply(n,i)}),bp||(bp=function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return new t(...r)});var Kr=et(Array.prototype.forEach),p$=et(Array.prototype.lastIndexOf),Fb=et(Array.prototype.pop),aa=et(Array.prototype.push),f$=et(Array.prototype.splice),Yi=Array.isArray,sa=et(String.prototype.toLowerCase),_p=et(String.prototype.toString),Bb=et(String.prototype.match),ca=et(String.prototype.replace),qb=et(String.prototype.indexOf),m$=et(String.prototype.trim),h$=et(Number.prototype.toString),g$=et(Boolean.prototype.toString),Ub=typeof BigInt>"u"?null:et(BigInt.prototype.toString),Gb=typeof Symbol>"u"?null:et(Symbol.prototype.toString),Pt=et(Object.prototype.hasOwnProperty),la=et(Object.prototype.toString),vt=et(RegExp.prototype.test),zr=v$(TypeError);function et(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return yp(e,t,r)}}function v$(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return bp(e,n)}}function Ae(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:sa;if(jb&&jb(e,null),!Yi(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i=="string"){const o=n(i);o!==i&&(l$(t)||(t[r]=o),i=o)}e[i]=!0}return e}function y$(e){for(let t=0;t<e.length;t++)Pt(e,t)||(e[t]=null);return e}function Ot(e){const t=Ji(null);for(const r of Ob(e)){var n=s$(r,2);const i=n[0],o=n[1];Pt(e,i)&&(Yi(o)?t[i]=y$(o):o&&typeof o=="object"&&o.constructor===Object?t[i]=Ot(o):t[i]=o)}return t}function b$(e){switch(typeof e){case"string":return e;case"number":return h$(e);case"boolean":return g$(e);case"bigint":return Ub?Ub(e):"0";case"symbol":return Gb?Gb(e):"Symbol()";case"undefined":return la(e);case"function":case"object":{if(e===null)return la(e);const t=e,n=Zt(t,"toString");if(typeof n=="function"){const r=n(t);return typeof r=="string"?r:la(r)}return la(e)}default:return la(e)}}function Zt(e,t){for(;e!==null;){const r=u$(e,t);if(r){if(r.get)return et(r.get);if(typeof r.value=="function")return et(r.value)}e=d$(e)}function n(){return null}return n}function _$(e){try{return vt(e,""),!0}catch{return!1}}var Hb=ot(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),wp=ot(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Sp=ot(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),w$=ot(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Cp=ot(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),S$=ot(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Vb=ot(["#text"]),Kb=ot(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Rp=ot(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","pointer-events","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","vector-effect","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),zb=ot(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Pc=ot(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),C$=st(/{{[\w\W]*|^[\w\W]*}}/g),R$=st(/<%[\w\W]*|^[\w\W]*%>/g),I$=st(/\${[\w\W]*/g),k$=st(/^data-[\-\w.\u00B7-\uFFFF]+$/),T$=st(/^aria-[\-\w]+$/),Wb=st(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),P$=st(/^(?:\w+script|data):/i),N$=st(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),E$=st(/^html$/i),A$=st(/^[a-z][.\w]*(-[.\w]+)+$/i),Jb=st(/<[/\w!]/g),Yb=st(/<[/\w]/g),x$=st(/<\/no(script|embed|frames)/i),D$=st(/\/>/i),jt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Xb=["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"],L$=ot(Ae({},Xb)),$$=(function(){const e={};return Kr(Xb,t=>{e[t]=st(new RegExp("</"+t+"(?=[\\t\\n\\f\\r />])","i"))}),ot(e)})(),O$=function(){return typeof window>"u"?null:window},j$=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let r=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));const o="dompurify"+(r?"#"+r:"");try{return t.createPolicy(o,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},Qb=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},cr=function(t,n,r,i){return Pt(t,n)&&Yi(t[n])?Ae(i.base?Ot(i.base):{},t[n],i.transform):r},Ip=function(t,n,r){const i=Pt(t,n)?t[n]:void 0;return i&&typeof i=="object"?Ot(i):r()};function Zb(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:O$();const t=Q=>Zb(Q);if(t.version="3.4.14",t.removed=[],!e||!e.document||e.document.nodeType!==jt.document||!e.Element)return t.isSupported=!1,t;let n=e.document;const r=n,i=r.currentScript;e.DocumentFragment;const o=e.HTMLTemplateElement,s=e.Node,c=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const d=e.DOMParser,u=e.trustedTypes,p=c.prototype,f=Zt(p,"cloneNode"),m=Zt(p,"remove"),v=Zt(p,"nextSibling"),g=Zt(p,"childNodes"),h=Zt(p,"parentNode"),b=Zt(p,"shadowRoot"),w=Zt(p,"attributes"),_=s&&s.prototype?Zt(s.prototype,"nodeType"):null,R=s&&s.prototype?Zt(s.prototype,"nodeName"):null,I=s&&s.prototype?Zt(s.prototype,"ownerDocument"):null,T=function(k){return _?_(k):k.nodeType},A=function(k){return R?R(k):k.nodeName};if(typeof o=="function"){const Q=n.createElement("template");Q.content&&Q.content.ownerDocument&&(n=Q.content.ownerDocument)}let O,F="",N,L=!1,D=0;const G=function(){if(D>0)throw zr('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},q=function(k){G(),D++;try{return O.createHTML(k)}finally{D--}},$=function(k){G(),D++;try{return O.createScriptURL(k)}finally{D--}},E=function(){return L||(N=j$(u,i),L=!0),N},S=n,M=S.implementation,H=S.createNodeIterator,U=S.createDocumentFragment,re=S.getElementsByTagName,oe=r.importNode;let ie=Qb();t.isSupported=typeof Ob=="function"&&typeof h=="function"&&M&&M.createHTMLDocument!==void 0;const se=C$,ue=R$,Pe=I$,Ie=k$,le=T$,ve=P$,X=N$,ce=A$;let be=Wb,fe=null;const We=Ae({},[...Hb,...wp,...Sp,...Cp,...Vb]);let he=null;const W=Ae({},[...Kb,...Rp,...zb,...Pc]);let de=Object.seal(Ji(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ne=null,xe=null;const tt=Object.seal(Ji(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let po=!0,Vn=!0,bn=!1,we=!0,Ye=!1,Xe=!0,Kt=!1,Ua=!1,li=null,di=null,ui=!1,lt=!1,_n=!1,fo=!1,WS=!0,JS=!1;const YS="user-content-";let Qf=!0,Zf=!1,mo={},ho=null;const XS=Ae({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let QS=null;const ZS=Ae({},["audio","video","img","source","image","track"]);let eC=null;const tC=Ae({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),gl="http://www.w3.org/1998/Math/MathML",vl="http://www.w3.org/2000/svg",wn="http://www.w3.org/1999/xhtml";let go=wn,em=!1,tm=null;const S2=Ae({},[gl,vl,wn],_p),nC=ot(["mi","mo","mn","ms","mtext"]);let nm=Ae({},nC);const rC=ot(["annotation-xml"]);let rm=Ae({},rC);const C2=Ae({},["title","style","font","a","script"]);let Ga=null;const R2=["application/xhtml+xml","text/html"],I2="text/html";let Qe=null,vo=null;const k2=n.createElement("form"),iC=function(k){return k instanceof RegExp||k instanceof Function},im=function(){let k=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(vo&&vo===k)return;(!k||typeof k!="object")&&(k={}),k=Ot(k),Ga=R2.indexOf(k.PARSER_MEDIA_TYPE)===-1?I2:k.PARSER_MEDIA_TYPE,Qe=Ga==="application/xhtml+xml"?_p:sa,fe=cr(k,"ALLOWED_TAGS",We,{transform:Qe}),he=cr(k,"ALLOWED_ATTR",W,{transform:Qe}),tm=cr(k,"ALLOWED_NAMESPACES",S2,{transform:_p}),eC=cr(k,"ADD_URI_SAFE_ATTR",tC,{transform:Qe,base:tC}),QS=cr(k,"ADD_DATA_URI_TAGS",ZS,{transform:Qe,base:ZS}),ho=cr(k,"FORBID_CONTENTS",XS,{transform:Qe}),ne=cr(k,"FORBID_TAGS",Ot({}),{transform:Qe}),xe=cr(k,"FORBID_ATTR",Ot({}),{transform:Qe}),mo=Pt(k,"USE_PROFILES")?k.USE_PROFILES&&typeof k.USE_PROFILES=="object"?Ot(k.USE_PROFILES):k.USE_PROFILES:!1,po=k.ALLOW_ARIA_ATTR!==!1,Vn=k.ALLOW_DATA_ATTR!==!1,bn=k.ALLOW_UNKNOWN_PROTOCOLS||!1,we=k.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ye=k.SAFE_FOR_TEMPLATES||!1,Xe=k.SAFE_FOR_XML!==!1,Kt=k.WHOLE_DOCUMENT||!1,lt=k.RETURN_DOM||!1,_n=k.RETURN_DOM_FRAGMENT||!1,fo=k.RETURN_TRUSTED_TYPE||!1,ui=k.FORCE_BODY||!1,WS=k.SANITIZE_DOM!==!1,JS=k.SANITIZE_NAMED_PROPS||!1,Qf=k.KEEP_CONTENT!==!1,Zf=k.IN_PLACE||!1,be=_$(k.ALLOWED_URI_REGEXP)?k.ALLOWED_URI_REGEXP:Wb,go=typeof k.NAMESPACE=="string"?k.NAMESPACE:wn,nm=Ip(k,"MATHML_TEXT_INTEGRATION_POINTS",()=>Ae({},nC)),rm=Ip(k,"HTML_INTEGRATION_POINTS",()=>Ae({},rC));const j=Ip(k,"CUSTOM_ELEMENT_HANDLING",()=>Ji(null));if(de=Ji(null),Pt(j,"tagNameCheck")&&iC(j.tagNameCheck)&&(de.tagNameCheck=j.tagNameCheck),Pt(j,"attributeNameCheck")&&iC(j.attributeNameCheck)&&(de.attributeNameCheck=j.attributeNameCheck),Pt(j,"allowCustomizedBuiltInElements")&&typeof j.allowCustomizedBuiltInElements=="boolean"&&(de.allowCustomizedBuiltInElements=j.allowCustomizedBuiltInElements),st(de),Ye&&(Vn=!1),_n&&(lt=!0),mo&&(fe=Ae({},Vb),he=Ji(null),mo.html===!0&&(Ae(fe,Hb),Ae(he,Kb)),mo.svg===!0&&(Ae(fe,wp),Ae(he,Rp),Ae(he,Pc)),mo.svgFilters===!0&&(Ae(fe,Sp),Ae(he,Rp),Ae(he,Pc)),mo.mathMl===!0&&(Ae(fe,Cp),Ae(he,zb),Ae(he,Pc))),tt.tagCheck=null,tt.attributeCheck=null,Pt(k,"ADD_TAGS")&&(typeof k.ADD_TAGS=="function"?tt.tagCheck=k.ADD_TAGS:Yi(k.ADD_TAGS)&&(fe===We&&(fe=Ot(fe)),Ae(fe,k.ADD_TAGS,Qe))),Pt(k,"ADD_ATTR")&&(typeof k.ADD_ATTR=="function"?tt.attributeCheck=k.ADD_ATTR:Yi(k.ADD_ATTR)&&(he===W&&(he=Ot(he)),Ae(he,k.ADD_ATTR,Qe))),Pt(k,"ADD_FORBID_CONTENTS")&&Yi(k.ADD_FORBID_CONTENTS)&&(ho===XS&&(ho=Ot(ho)),Ae(ho,k.ADD_FORBID_CONTENTS,Qe)),Qf&&(fe["#text"]=!0),Kt&&Ae(fe,["html","head","body"]),fe.table&&(Ae(fe,["tbody"]),delete ne.tbody),k.TRUSTED_TYPES_POLICY){if(typeof k.TRUSTED_TYPES_POLICY.createHTML!="function")throw zr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof k.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw zr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const K=O;O=k.TRUSTED_TYPES_POLICY;try{F=q("")}catch(ee){throw O=K,ee}}else k.TRUSTED_TYPES_POLICY===null?(O=void 0,F=""):(O===void 0&&(O=E()),O&&typeof F=="string"&&(F=q("")));ot&&ot(k),vo=k},oC=Ae({},[...wp,...Sp,...w$]),aC=Ae({},[...Cp,...S$]),T2=function(k,j,K){return j.namespaceURI===wn?k==="svg":j.namespaceURI===gl?k==="svg"&&(K==="annotation-xml"||nm[K]):!!oC[k]},P2=function(k,j,K){return j.namespaceURI===wn?k==="math":j.namespaceURI===vl?k==="math"&&rm[K]:!!aC[k]},N2=function(k,j,K){return j.namespaceURI===vl&&!rm[K]||j.namespaceURI===gl&&!nm[K]?!1:!aC[k]&&(C2[k]||!oC[k])},E2=function(k){let j=h(k);(!j||!j.tagName)&&(j={namespaceURI:go,tagName:"template"});const K=sa(k.tagName),ee=sa(j.tagName);return tm[k.namespaceURI]?k.namespaceURI===vl?T2(K,j,ee):k.namespaceURI===gl?P2(K,j,ee):k.namespaceURI===wn?N2(K,j,ee):!!(Ga==="application/xhtml+xml"&&tm[k.namespaceURI]):!1},br=function(k){aa(t.removed,{element:k});try{h(k).removeChild(k)}catch{if(m(k),!h(k))throw zr("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},sC=function(k,j,K){try{k.removeAttributeNode(j)}catch{try{k.removeAttribute(K)}catch{}}},yl=function(k){bl(k);const j=g(k);if(j){const ee=[];Kr(j,pe=>{aa(ee,pe)}),Kr(ee,pe=>{try{m(pe)}catch{}})}const K=w(k);if(K)for(let ee=K.length-1;ee>=0;--ee){const pe=K[ee],_e=pe&&pe.name;typeof _e=="string"&&sC(k,pe,_e)}},pi=function(k,j,K){if(!K)try{K=j.getAttributeNode(k)}catch{K=null}aa(t.removed,{attribute:K||null,from:j});try{K?j.removeAttributeNode(K):j.removeAttribute(k)}catch{try{j.removeAttribute(k)}catch{}}if(k==="is")if(lt||_n)try{br(j)}catch{}else try{j.setAttribute(k,"")}catch{}},A2=function(k){const j=w(k);if(j)for(let K=j.length-1;K>=0;--K){const ee=j[K],pe=ee&&ee.name;typeof pe!="string"||he[Qe(pe)]||sC(k,ee,pe)}},bl=function(k){const j=[k];for(;j.length>0;){const K=j.pop();T(K)===jt.element&&A2(K);const ee=g(K);if(ee)for(let pe=ee.length-1;pe>=0;--pe)j.push(ee[pe])}},cC=function(k,j){return Xe?k==="patchsrc"?!0:k==="for"&&j!=="label"&&j!=="output":!1},x2=function(k){if(!Xe)return;const j=[k];for(;j.length>0;){const K=j.pop(),ee=T(K);if(ee===jt.processingInstruction||ee===jt.comment&&vt(Yb,K.data)){try{m(K)}catch{}continue}if(ee===jt.element){const _e=K,De=Qe(A(K));try{_e.hasAttribute&&_e.hasAttribute("patchsrc")&&_e.removeAttribute("patchsrc"),_e.hasAttribute&&_e.hasAttribute("for")&&cC("for",De)&&_e.removeAttribute("for")}catch{}}const pe=g(K);if(pe)for(let _e=pe.length-1;_e>=0;--_e)j.push(pe[_e])}},lC=function(k){let j=null,K=null;if(ui)k="<remove></remove>"+k;else{const _e=Bb(k,/^[\r\n\t ]+/);K=_e&&_e[0]}Ga==="application/xhtml+xml"&&go===wn&&(k='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+k+"</body></html>");const ee=O?q(k):k;if(go===wn)try{j=new d().parseFromString(ee,Ga)}catch{}if(!j||!j.documentElement){j=M.createDocument(go,"template",null);try{j.documentElement.innerHTML=em?F:ee}catch{}}const pe=j.body||j.documentElement;return k&&K&&pe.insertBefore(n.createTextNode(K),pe.childNodes[0]||null),go===wn?re.call(j,Kt?"html":"body")[0]:Kt?j.documentElement:pe},dC=function(k){const j=I?I(k):k.ownerDocument;return H.call(j||k,k,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},_l=function(k){return k=ca(k,se," "),k=ca(k,ue," "),k=ca(k,Pe," "),k},om=function(k){var j;k.normalize();const K=I?I(k):k.ownerDocument,ee=H.call(K||k,k,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let pe=ee.nextNode();for(;pe;)pe.data=_l(pe.data),pe=ee.nextNode();const _e=(j=k.querySelectorAll)===null||j===void 0?void 0:j.call(k,"template");_e&&Kr(_e,De=>{yo(De.content)&&om(De.content)})},wl=function(k){const j=R?R(k):null;return typeof j!="string"||Qe(j)!=="form"?!1:typeof k.nodeName!="string"||typeof k.textContent!="string"||typeof k.removeChild!="function"||k.attributes!==w(k)||typeof k.removeAttribute!="function"||typeof k.setAttribute!="function"||typeof k.namespaceURI!="string"||typeof k.insertBefore!="function"||typeof k.hasChildNodes!="function"||k.nodeType!==_(k)||k.childNodes!==g(k)},yo=function(k){if(!_||typeof k!="object"||k===null)return!1;try{return _(k)===jt.documentFragment}catch{return!1}},Ha=function(k){if(!_||typeof k!="object"||k===null)return!1;try{return typeof _(k)=="number"}catch{return!1}};function Sn(Q,k,j){Q.length!==0&&Kr(Q,K=>{K.call(t,k,j,vo)})}const D2=function(k,j){return!!(Xe&&k.hasChildNodes()&&!Ha(k.firstElementChild)&&vt(Jb,k.textContent)&&vt(Jb,k.innerHTML)||Xe&&k.namespaceURI===wn&&L$[j]&&(Ha(k.firstElementChild)||typeof k.textContent=="string"&&vt($$[j],k.textContent))||k.nodeType===jt.processingInstruction||Xe&&k.nodeType===jt.comment&&vt(Yb,k.data))},Sl=function(k,j){if(k instanceof RegExp)return vt(k,j);if(k instanceof Function){for(var K=arguments.length,ee=new Array(K>2?K-2:0),pe=2;pe<K;pe++)ee[pe-2]=arguments[pe];return!!k(j,...ee)}return!1},L2=function(k,j,K){if(!ne[j]&&hC(j)&&Sl(de.tagNameCheck,j))return!1;if(Qf&&!ho[j]){const ee=h(k),pe=g(k);if(pe&&ee){const _e=pe.length;for(let De=_e-1;De>=0;--De){const Ct=k===K?f(pe[De],!0):pe[De];ee.insertBefore(Ct,v(k))}}}return br(k),!0},uC=function(k,j,K,ee){return k.length===0?j:j===K||j===ee?Ot(j):j},pC=function(k,j){return k===j||h(k)!==null?!1:(Zf&&bl(k),!0)},fC=function(k,j){if(Sn(ie.beforeSanitizeElements,k,null),pC(k,j))return!0;if(wl(k))return br(k),!0;const K=Qe(A(k));if(fe=uC(ie.uponSanitizeElement,fe,We,li),Sn(ie.uponSanitizeElement,k,{tagName:K,allowedTags:fe}),pC(k,j))return!0;if(D2(k,K))return br(k),!0;if(ne[K]||!(tt.tagCheck instanceof Function&&tt.tagCheck(K))&&!fe[K]){const ee=L2(k,K,j);return ee===!1&&Sn(ie.afterSanitizeElements,k,null),ee}if(T(k)===jt.element&&!E2(k)||(K==="noscript"||K==="noembed"||K==="noframes")&&vt(x$,k.innerHTML))return br(k),!0;if(Ye&&k.nodeType===jt.text){const ee=_l(k.textContent);k.textContent!==ee&&(aa(t.removed,{element:k.cloneNode()}),k.textContent=ee)}return Sn(ie.afterSanitizeElements,k,null),!1},mC=function(k,j,K){if(xe[j]||cC(j,k)||WS&&(j==="id"||j==="name")&&(K in n||K in k2))return!1;const ee=he[j]||tt.attributeCheck instanceof Function&&tt.attributeCheck(j,k);return Vn&&vt(Ie,j)||po&&vt(le,j)?!0:ee?eC[j]||vt(be,ca(K,X,""))||(j==="src"||j==="xlink:href"||j==="href")&&k!=="script"&&qb(K,"data:")===0&&QS[k]||bn&&!vt(ve,ca(K,X,""))?!0:!K:hC(k)&&Sl(de.tagNameCheck,k)&&Sl(de.attributeNameCheck,j,k)||j==="is"&&de.allowCustomizedBuiltInElements&&Sl(de.tagNameCheck,K)},$2=Ae({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),hC=function(k){return!$2[sa(k)]&&vt(ce,k)},O2=function(k,j,K,ee){if(O&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!K)switch(u.getAttributeType(k,j)){case"TrustedHTML":return q(ee);case"TrustedScriptURL":return $(ee)}return ee},j2=function(k,j,K,ee){try{K?k.setAttributeNS(K,j,ee):k.setAttribute(j,ee),wl(k)?br(k):Fb(t.removed)}catch{pi(j,k)}},gC=function(k){Sn(ie.beforeSanitizeAttributes,k,null);const j=k.attributes;if(!j||wl(k))return;he=uC(ie.uponSanitizeAttribute,he,W,di);const K={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:he,forceKeepAttr:void 0};let ee=j.length;const pe=Qe(k.nodeName);for(;ee--;){const _e=j[ee],De=_e.name,Ct=_e.namespaceURI,rn=_e.value,Nt=Qe(De),sm=rn;let Rt=De==="value"?sm:m$(sm);if(K.attrName=Nt,K.attrValue=Rt,K.keepAttr=!0,K.forceKeepAttr=void 0,Sn(ie.uponSanitizeAttribute,k,K),Rt=K.attrValue,JS&&(Nt==="id"||Nt==="name")&&qb(Rt,YS)!==0&&(pi(De,k,_e),Rt=YS+Rt),Xe&&vt(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Rt)){pi(De,k,_e);continue}if(Nt==="attributename"&&Bb(Rt,"href")){pi(De,k,_e);continue}if(!K.forceKeepAttr){if(!K.keepAttr){pi(De,k,_e);continue}if(!we&&vt(D$,Rt)){pi(De,k,_e);continue}if(Ye&&(Rt=_l(Rt)),!mC(pe,Nt,Rt)){pi(De,k,_e);continue}Rt=O2(pe,Nt,Ct,Rt),Rt!==sm&&j2(k,De,Ct,Rt)}}Sn(ie.afterSanitizeAttributes,k,null)},Cl=function(k){let j=null;const K=dC(k);for(Sn(ie.beforeSanitizeShadowDOM,k,null);j=K.nextNode();)if(Sn(ie.uponSanitizeShadowNode,j,null),fC(j,k),gC(j),yo(j.content)&&Cl(j.content),T(j)===jt.element){const ee=b(j);yo(ee)&&(am(ee),Cl(ee))}Sn(ie.afterSanitizeShadowDOM,k,null)},am=function(k){const j=[{node:k,shadow:null}];for(;j.length>0;){const K=j.pop();if(K.shadow){Cl(K.shadow);continue}const ee=K.node,pe=T(ee)===jt.element,_e=g(ee);if(_e)for(let De=_e.length-1;De>=0;--De)j.push({node:_e[De],shadow:null});if(pe){const De=R?R(ee):null;if(typeof De=="string"&&Qe(De)==="template"){const Ct=ee.content;yo(Ct)&&j.push({node:Ct,shadow:null})}}if(pe){const De=b(ee);yo(De)&&j.push({node:null,shadow:De},{node:De,shadow:null})}}};return t.sanitize=function(Q){let k=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},j=null,K=null,ee=null,pe=null;if(em=!Q,em&&(Q="<!-->"),typeof Q!="string"&&!Ha(Q)&&(Q=b$(Q),typeof Q!="string"))throw zr("dirty is not a string, aborting");if(!t.isSupported)return Q;Ua?(fe=li,he=di):im(k),(ie.uponSanitizeElement.length>0||ie.uponSanitizeAttribute.length>0)&&(fe=Ot(fe)),ie.uponSanitizeAttribute.length>0&&(he=Ot(he)),t.removed=[];const _e=Zf&&typeof Q!="string"&&Ha(Q);if(_e){x2(Q);const rn=A(Q);if(typeof rn=="string"){const Nt=Qe(rn);if(!fe[Nt]||ne[Nt])throw yl(Q),zr("root node is forbidden and cannot be sanitized in-place")}if(wl(Q))throw yl(Q),zr("root node is clobbered and cannot be sanitized in-place");try{am(Q)}catch(Nt){throw yl(Q),Nt}}else if(Ha(Q))j=lC("<!---->"),K=j.ownerDocument.importNode(Q,!0),K.nodeType===jt.element&&K.nodeName==="BODY"||K.nodeName==="HTML"?j=K:j.appendChild(K),am(K);else{if(!lt&&!Ye&&!Kt&&Q.indexOf("<")===-1)return O&&fo?q(Q):Q;if(j=lC(Q),!j)return lt?null:fo?F:""}j&&ui&&br(j.firstChild);const De=_e?Q:j;try{const rn=dC(De);for(;ee=rn.nextNode();)fC(ee,De),gC(ee),yo(ee.content)&&Cl(ee.content)}catch(rn){throw _e&&(yl(Q),Kr(t.removed,Nt=>{Nt.element&&bl(Nt.element)})),rn}if(_e)return Kr(t.removed,rn=>{rn.element&&bl(rn.element)}),Ye&&om(Q),Q;if(lt){if(Ye&&om(j),_n)for(pe=U.call(j.ownerDocument);j.firstChild;)pe.appendChild(j.firstChild);else pe=j;return(he.shadowroot||he.shadowrootmode)&&(pe=oe.call(r,pe,!0)),pe}let Ct=Kt?j.outerHTML:j.innerHTML;return Kt&&fe["!doctype"]&&j.ownerDocument&&j.ownerDocument.doctype&&j.ownerDocument.doctype.name&&vt(E$,j.ownerDocument.doctype.name)&&(Ct="<!DOCTYPE "+j.ownerDocument.doctype.name+`>
44
- `+Ct),Ye&&(Ct=_l(Ct)),O&&fo?q(Ct):Ct},t.setConfig=function(){let Q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};im(Q),Ua=!0,li=fe,di=he},t.clearConfig=function(){vo=null,Ua=!1,li=null,di=null,O=N,F=""},t.isValidAttribute=function(Q,k,j){vo||im({});const K=Qe(Q),ee=Qe(k);return mC(K,ee,j)},t.addHook=function(Q,k){typeof k=="function"&&Pt(ie,Q)&&aa(ie[Q],k)},t.removeHook=function(Q,k){if(Pt(ie,Q)){if(k!==void 0){const j=p$(ie[Q],k);return j===-1?void 0:f$(ie[Q],j,1)[0]}return Fb(ie[Q])}},t.removeHooks=function(Q){Pt(ie,Q)&&(ie[Q]=[])},t.removeAllHooks=function(){ie=Qb()},t}var e_=Zb();function kp(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Wr=kp();function t_(e){Wr=e}var Jr={exec:()=>null};function Xi(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function Ne(e,t=""){let n=typeof e=="string"?e:e.source,r={replace:(i,o)=>{let s=typeof o=="string"?o:o.source;return s=s.replace(yt.caret,"$1"),n=n.replace(i,s),r},getRegex:()=>new RegExp(n,t)};return r}var M$=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),yt={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Xi(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Xi(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Xi(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Xi(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Xi(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Xi(e=>new RegExp(`^ {0,${e}}>`))},F$=/^(?:[ \t]*(?:\n|$))+/,B$=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,q$=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,da=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,U$=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Tp=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,n_=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,r_=Ne(n_).replace(/bull/g,Tp).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),G$=Ne(n_).replace(/bull/g,Tp).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Pp=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,H$=/^[^\n]+/,Np=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,V$=Ne(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Np).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),K$=Ne(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Tp).getRegex(),Nc="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Ep=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,z$=Ne("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Ep).replace("tag",Nc).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),i_=e=>Ne(Pp).replace("hr",da).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Nc).getRegex(),W$=i_(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),J$=i_(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Ap={blockquote:Ne(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",J$).getRegex(),code:B$,def:V$,fences:q$,heading:U$,hr:da,html:z$,lheading:r_,list:K$,newline:F$,paragraph:W$,table:Jr,text:H$},o_=Ne("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",da).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Nc).getRegex(),Y$={...Ap,lheading:G$,table:o_,paragraph:Ne(Pp).replace("hr",da).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",o_).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Nc).getRegex()},X$={...Ap,html:Ne(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Ep).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Jr,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Ne(Pp).replace("hr",da).replace("heading",` *#{1,6} *[^
45
- ]`).replace("lheading",r_).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Q$=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Z$=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,a_=/^( {2,}|\\)\n(?!\s*$)/,eO=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,qn=/[\p{P}\p{S}]/u,Qi=/[\s\p{P}\p{S}]/u,ua=/[^\s\p{P}\p{S}]/u,tO=Ne(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Qi).getRegex(),nO=/[\p{Pi}\p{Ps}"']/u,s_=/(?!~)[\p{P}\p{S}]/u,rO=/(?!~)[\s\p{P}\p{S}]/u,iO=/(?:[^\s\p{P}\p{S}]|~)/u,oO=Ne(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",M$?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),c_=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,aO=Ne(c_,"u").replace(/punct/g,qn).getRegex(),sO=Ne(c_,"u").replace(/punct/g,s_).getRegex(),cO=Ne(/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,"u").replace(/openQuote/g,nO).replace(/punct/g,qn).getRegex(),l_="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",lO=Ne(l_,"gu").replace(/notPunctSpace/g,ua).replace(/punctSpace/g,Qi).replace(/punct/g,qn).getRegex(),dO=Ne(l_,"gu").replace(/notPunctSpace/g,iO).replace(/punctSpace/g,rO).replace(/punct/g,s_).getRegex(),uO=Ne("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,ua).replace(/punctSpace/g,Qi).replace(/punct/g,qn).getRegex(),pO=Ne("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ua).replace(/punctSpace/g,Qi).replace(/punct/g,qn).getRegex(),fO=Ne("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,ua).replace(/punctSpace/g,Qi).replace(/punct/g,qn).getRegex(),mO=Ne(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,qn).getRegex(),hO=Ne("^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,ua).replace(/punctSpace/g,Qi).replace(/punct/g,qn).getRegex(),gO=Ne(/\\(punct)/,"gu").replace(/punct/g,qn).getRegex(),vO=Ne(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),yO=Ne(Ep).replace("(?:-->|$)","-->").getRegex(),bO=Ne("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",yO).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ec=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,_O=Ne(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Ec).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),d_=Ne(/^!?\[(label)\]\[(ref)\]/).replace("label",Ec).replace("ref",Np).getRegex(),u_=Ne(/^!?\[(ref)\](?:\[\])?/).replace("ref",Np).getRegex(),wO=Ne("reflink|nolink(?!\\()","g").replace("reflink",d_).replace("nolink",u_).getRegex(),p_=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,xp={_backpedal:Jr,anyPunctuation:gO,autolink:vO,blockSkip:oO,br:a_,code:Z$,del:Jr,delLDelim:Jr,delRDelim:Jr,emStrongLDelim:aO,emStrongRDelimAst:lO,emStrongRDelimUnd:pO,escape:Q$,link:_O,nolink:u_,punctuation:tO,reflink:d_,reflinkSearch:wO,tag:bO,text:eO,url:Jr},SO={...xp,emStrongLDelim:cO,emStrongRDelimAst:uO,emStrongRDelimUnd:fO,link:Ne(/^!?\[(label)\]\((.*?)\)/).replace("label",Ec).getRegex(),reflink:Ne(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Ec).getRegex()},Dp={...xp,emStrongRDelimAst:dO,emStrongLDelim:sO,delLDelim:mO,delRDelim:hO,url:Ne(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",p_).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Ne(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",p_).getRegex()},CO={...Dp,br:Ne(a_).replace("{2,}","*").getRegex(),text:Ne(Dp.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ac={normal:Ap,gfm:Y$,pedantic:X$},pa={normal:xp,gfm:Dp,breaks:CO,pedantic:SO},RO={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},f_=e=>RO[e];function gn(e,t){if(t){if(yt.escapeTest.test(e))return e.replace(yt.escapeReplace,f_)}else if(yt.escapeTestNoEncode.test(e))return e.replace(yt.escapeReplaceNoEncode,f_);return e}function m_(e){try{e=encodeURI(e).replace(yt.percentDecode,"%")}catch{return null}return e}function h_(e,t){let n=e.replace(yt.findPipe,(i,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}).split(yt.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;r<n.length;r++)n[r]=n[r].trim().replace(yt.slashPipe,"|");return n}function lr(e,t,n){let r=e.length;if(r===0)return"";let i=0;for(;i<r;){let o=e.charAt(r-i-1);if(o===t&&!n)i++;else if(o!==t&&n)i++;else break}return e.slice(0,r-i)}function g_(e){let t=e.split(`
41
+ `)},PT=0,xi=[];function NT(e){var t=B([]),n=B([0,0]),r=B(),i=D(PT++)[0],a=D(Qg)[0],s=B(e);V(function(){s.current=e},[e]),V(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var b=Yk([e.lockRef.current],(e.shards||[]).map(av),!0).filter(Boolean);return b.forEach(function(h){return h.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),b.forEach(function(h){return h.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var c=oe(function(b,h){if("touches"in b&&b.touches.length===2||b.type==="wheel"&&b.ctrlKey)return!s.current.allowPinchZoom;var y=Cs(b),w=n.current,_="deltaX"in b?b.deltaX:w[0]-y[0],R="deltaY"in b?b.deltaY:w[1]-y[1],I,T=b.target,A=Math.abs(_)>Math.abs(R)?"h":"v";if("touches"in b&&A==="h"&&T.type==="range")return!1;var L=window.getSelection(),F=L&&L.anchorNode;if(F&&(F===T||F.contains(T)))return!1;var N=tv(A,T);if(!N)return!0;if(N?I=A:(I=A==="v"?"h":"v",N=tv(A,T)),!N)return!1;if(!r.current&&"changedTouches"in b&&(_||R)&&(r.current=I),!I)return!0;var j=r.current||I;return IT(j,h,b,j==="h"?_:R,!0)},[]),l=oe(function(b){var h=b;if(!(!xi.length||xi[xi.length-1]!==a)){var y="deltaY"in h?iv(h):Cs(h),w=t.current.filter(function(R){return R.name===h.type&&(R.target===h.target||h.target===R.shadowParent)&&kT(R.delta,y)})[0];if(w&&w.should){h.cancelable&&h.preventDefault();return}if(!w){var _=(s.current.shards||[]).map(av).filter(Boolean).filter(function(R){return R.contains(h.target)});(_.length>0?c(h,_[0]):!s.current.noIsolation)&&h.cancelable&&h.preventDefault()}}},[]),d=oe(function(b,h,y,w){var _={name:b,delta:h,target:y,should:w,shadowParent:ET(y)};t.current.push(_),setTimeout(function(){t.current=t.current.filter(function(R){return R!==_})},1)},[]),u=oe(function(b){n.current=Cs(b),r.current=void 0},[]),p=oe(function(b){d(b.type,iv(b),b.target,c(b,e.lockRef.current))},[]),f=oe(function(b){d(b.type,Cs(b),b.target,c(b,e.lockRef.current))},[]);V(function(){return xi.push(a),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:f}),document.addEventListener("wheel",l,Ai),document.addEventListener("touchmove",l,Ai),document.addEventListener("touchstart",u,Ai),function(){xi=xi.filter(function(b){return b!==a}),document.removeEventListener("wheel",l,Ai),document.removeEventListener("touchmove",l,Ai),document.removeEventListener("touchstart",u,Ai)}},[]);var m=e.removeScrollBar,v=e.inert;return g(z,null,v?g(a,{styles:TT(i)}):null,m?g(yT,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function ET(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var AT=aT(Yg,NT),Ea=W(function(e,t){return g(ws,un({},e,{ref:t,sideCar:AT}))});Ea.classNames=ws.classNames;var xT=function(e){return typeof document>"u"?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},Di=new WeakMap,Rs=new WeakMap,Is={},Gd=0,ov=function(e){return e&&(e.host||ov(e.parentNode))},DT=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=ov(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},LT=function(e,t,n,r){var i=DT(t,Array.isArray(e)?e:[e]);Is[n]||(Is[n]=new WeakMap);var a=Is[n],s=[],c=new Set,l=new Set(i),d=function(p){!p||c.has(p)||(c.add(p),d(p.parentNode))};i.forEach(d);var u=function(p){!p||l.has(p)||Array.prototype.forEach.call(p.children,function(f){if(c.has(f))u(f);else try{var m=f.getAttribute(r),v=m!==null&&m!=="false",b=(Di.get(f)||0)+1,h=(a.get(f)||0)+1;Di.set(f,b),a.set(f,h),s.push(f),b===1&&v&&Rs.set(f,!0),h===1&&f.setAttribute(n,"true"),v||f.setAttribute(r,"true")}catch(y){console.error("aria-hidden: cannot operate on ",f,y)}})};return u(t),c.clear(),Gd++,function(){s.forEach(function(p){var f=Di.get(p)-1,m=a.get(p)-1;Di.set(p,f),a.set(p,m),f||(Rs.has(p)||p.removeAttribute(r),Rs.delete(p)),m||p.removeAttribute(n)}),Gd--,Gd||(Di=new WeakMap,Di=new WeakMap,Rs=new WeakMap,Is={})}},ks=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=t||xT(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),LT(r,i,n,"aria-hidden")):function(){return null}},$T=Object.defineProperty,pn=(e,t)=>$T(e,"name",{value:t,configurable:!0}),Hd="Dialog",[sv,$H]=dt(Hd),[jT,nr]=sv(Hd),OT=pn(e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:s=!0}=e,c=B(null),l=B(null),[d,u]=Dt({prop:r,defaultProp:i??!1,onChange:a,caller:Hd}),[p,f]=D(0),[m,v]=D(0);return o(jT,{scope:t,triggerRef:c,contentRef:l,contentId:xt(),titleId:xt(),descriptionId:xt(),titlePresent:p>0,descriptionPresent:m>0,setTitleCount:f,setDescriptionCount:v,open:d,onOpenChange:u,onOpenToggle:oe(()=>u(b=>!b),[u]),modal:s,children:n})},"Dialog"),cv="DialogPortal",[MT,lv]=sv(cv,{forceMount:void 0}),FT=pn(e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,a=nr(cv,t);return o(MT,{scope:t,forceMount:n,children:$r.map(r,s=>o(Pt,{present:n||a.open,children:o(Ti,{asChild:!0,container:i,children:s})}))})},"DialogPortal"),Vd="DialogOverlay",BT=W(pn(function(t,n){const r=lv(Vd,t.__scopeDialog),{forceMount:i=r.forceMount,...a}=t,s=nr(Vd,t.__scopeDialog);return s.modal?o(Pt,{present:i||s.open,children:o(UT,{...a,ref:n})}):null},"DialogOverlay")),qT=dn("DialogOverlay.RemoveScroll"),UT=W(pn(function(t,n){const{__scopeDialog:r,...i}=t,a=nr(Vd,r),s=xg(),c=Se(n,s);return o(Ea,{as:qT,allowPinchZoom:!0,shards:[a.contentRef],children:o(ge.div,{"data-state":Kd(a.open),...i,ref:c,style:{pointerEvents:"auto",...i.style}})})},"DialogOverlayImpl")),Aa="DialogContent",GT=W(pn(function(t,n){const r=lv(Aa,t.__scopeDialog),{forceMount:i=r.forceMount,...a}=t,s=nr(Aa,t.__scopeDialog);return o(Pt,{present:i||s.open,children:s.modal?o(HT,{...a,ref:n}):o(VT,{...a,ref:n})})},"DialogContent")),HT=W(pn(function(t,n){const r=nr(Aa,t.__scopeDialog),i=B(null),a=Se(n,r.contentRef,i);return V(()=>{const s=i.current;if(s)return ks(s)},[]),o(dv,{...t,ref:a,trapFocus:r.open,disableOutsidePointerEvents:r.open,onCloseAutoFocus:ne(t.onCloseAutoFocus,s=>{s.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:ne(t.onPointerDownOutside,s=>{const c=s.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0;(c.button===2||l)&&s.preventDefault()}),onFocusOutside:ne(t.onFocusOutside,s=>s.preventDefault())})},"DialogContentModal")),VT=W(pn(function(t,n){const r=nr(Aa,t.__scopeDialog),i=B(!1),a=B(!1);return o(dv,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{t.onCloseAutoFocus?.(s),s.defaultPrevented||(i.current||r.triggerRef.current?.focus(),s.preventDefault()),i.current=!1,a.current=!1},onInteractOutside:s=>{t.onInteractOutside?.(s),s.defaultPrevented||(i.current=!0,s.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const c=s.target;r.triggerRef.current?.contains(c)&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&a.current&&s.preventDefault()}})},"DialogContentNonModal")),dv=W(pn(function(t,n){const{__scopeDialog:r,trapFocus:i,onOpenAutoFocus:a,onCloseAutoFocus:s,...c}=t,l=nr(Aa,r);return Ei(),o(z,{children:o(vs,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:a,onUnmountAutoFocus:s,children:o(ki,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionPresent?l.descriptionId:void 0,"aria-labelledby":l.titlePresent?l.titleId:void 0,"data-state":Kd(l.open),...c,ref:n,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})},"DialogContentImpl")),KT="DialogTitle",zT=W(pn(function(t,n){const{__scopeDialog:r,...i}=t,a=nr(KT,r),{setTitleCount:s}=a;return Xe(()=>(s(c=>c+1),()=>s(c=>c-1)),[s]),o(ge.h2,{id:a.titleId,...i,ref:n})},"DialogTitle"));function Kd(e){return e?"open":"closed"}pn(Kd,"getState");function Ln({ariaDescribedby:e,ariaLabelledby:t,children:n,contentClassName:r,contentId:i,modal:a=!0,onCloseAutoFocus:s,onEscapeKeyDown:c,onInteractOutside:l,onOpenAutoFocus:d,onOpenChange:u,open:p,overlayClassName:f,overlayId:m,slotId:v}){return o(OT,{modal:a,open:p,onOpenChange:u,children:p?o(FT,{children:[o(BT,{asChild:!0,children:o("div",{className:f,id:m})}),o(GT,{"aria-describedby":e,"aria-labelledby":t,asChild:!0,onCloseAutoFocus:s,onEscapeKeyDown:c,onInteractOutside:l,onOpenAutoFocus:d,children:o("div",{role:"dialog",className:r,id:i,onClick:b=>{b.target===b.currentTarget&&u(!1)},tabIndex:-1,children:n??(v?o("div",{id:v}):null)})})]}):null})}function zd(e){return o(zT,{...e})}function WT(e,t){return e.canonicalId<t.canonicalId?-1:e.canonicalId>t.canonicalId?1:0}function xa(e){return e.normalize("NFKC").replace(/\u200B/gu,"").replace(/\s+/gu," ").trim().toLowerCase()}function uv(e){const t=new Map;for(const n of e){const r=t.get(n.canonicalId);(!r||n.displayName<r.displayName)&&t.set(n.canonicalId,n)}return[...t.values()].sort(WT)}function Or(e){const t=new Map;for(const r of uv(e)){const i=xa(r.displayName),a=t.get(i);a?a.push(r):t.set(i,[r])}const n=new Map;for(const r of t.values())for(const[i,a]of r.entries())n.set(a.canonicalId,r.length>1?`${a.displayName} — duplicate name ${i+1} of ${r.length}`:a.displayName);return n}function JT(e){const t=new Map;for(const n of uv(e)){const r=xa(n.displayName),i=t.get(r);i?i.canonicalIds.push(n.canonicalId):t.set(r,{displayName:n.displayName,canonicalIds:[n.canonicalId],firstCanonicalId:n.canonicalId})}return[...t.values()].sort((n,r)=>{const i=xa(n.displayName).localeCompare(xa(r.displayName));return i!==0?i:n.firstCanonicalId<r.firstCanonicalId?-1:n.firstCanonicalId>r.firstCanonicalId?1:0}).map(n=>({displayName:n.displayName,identityCount:n.canonicalIds.length}))}var pv=500,Ts=null,Da=null,La=null;function $a(e){return Da?Da(e)?(La=document.activeElement instanceof HTMLElement?document.activeElement:null,!0):!1:(La=document.activeElement instanceof HTMLElement?document.activeElement:null,Ts=e,!0)}function ut(e){return e.recipientKind==="identity"?`identity:${e.identityId}`:`team:${e.teamId}`}function fv(e){const t=e.indexOf(":"),n=e.slice(0,t),r=e.slice(t+1);return r?n==="identity"?{recipientKind:"identity",identityId:r}:n==="team"?{recipientKind:"team",teamId:r}:null:null}function ja(e){return e.recipientKind==="identity"?ut({recipientKind:"identity",identityId:e.identityId}):ut({recipientKind:"team",teamId:e.teamId})}function YT(e,t){return ja(e)===ut(t)}function Wd(e,t){const n=[...new Set(e)].sort((r,i)=>r<i?-1:r>i?1:0);return new Map(n.map((r,i)=>[r,n.length===1?t:`${t} ${i+1} of ${n.length}`]))}function XT(e,t){if(t?.mode!=="project-manage")return new Map;const n=new Set(e.teams.map(c=>c.teamId)),r=new Set(e.identities.map(c=>c.identityId)),i=e.projectRecipients.filter(c=>c.status==="active"&&c.canonicalProjectIdentity===t.projectId),a=i.flatMap(c=>c.recipientKind==="team"&&!n.has(c.teamId)?[ja(c)]:[]),s=i.flatMap(c=>c.recipientKind==="identity"&&!r.has(c.identityId)?[ja(c)]:[]);return new Map([...Wd(a,"Unavailable Team"),...Wd(s,"Unavailable Identity")])}function QT(e,t,n){if(t?.mode!=="recipient-manage")return new Map;const r=new Set(e.map(i=>i.canonicalProjectIdentity));return Wd(n.filter(i=>!r.has(i)),"Unavailable Project")}function mv(e,t){return e instanceof Zl?"Recipient access changed after this review. Review the refreshed changes before trying again.":t}function hv({checked:e,description:t,disabled:n,label:r,onChange:i}){const a=`recipient-policy-choice-${Dr()}`;return o("label",{className:"sync-dialog-radio-option recipient-policy-management-choice recipient-policy-management-target",htmlFor:a,children:[o("input",{checked:e,disabled:n,id:a,onChange:i,type:"checkbox"}),o("span",{children:[o("strong",{className:"recipient-policy-management-name",children:r}),o("span",{className:"small recipient-policy-management-description",children:t})]})]})}function ZT(e,t,n){const r=e.teamMemberships.filter(c=>c.status==="active"),i=new Map(e.identities.map(c=>[c.identityId,c])),a=[...e.teams.filter(c=>c.status==="active").map(c=>{const l=r.filter(d=>d.teamId===c.teamId).map(d=>i.get(d.identityId)?.displayName).filter(d=>!!d);return{key:ut({recipientKind:"team",teamId:c.teamId}),label:c.displayName,description:`Team · ${l.length.toLocaleString()} current ${l.length===1?"member":"members"}${l.length?`: ${l.join(", ")}`:""}`}}),...e.identities.filter(c=>c.status==="active"||c.status==="pending").map(c=>({key:ut({recipientKind:"identity",identityId:c.identityId}),label:c.displayName,description:`Identity · ${c.status==="pending"?"pending · ":""}locally verified`}))];if(t?.mode!=="project-manage")return a;const s=new Set(a.map(c=>c.key));for(const c of e.projectRecipients){if(c.status!=="active"||c.canonicalProjectIdentity!==t.projectId)continue;const l=ja(c);if(!s.has(l)){if(c.recipientKind==="team"){const d=e.teams.find(p=>p.teamId===c.teamId),u=n.get(l)??"Unavailable Team";a.push({key:l,label:d?.displayName??u,description:`${d?.status==="archived"?"Archived Team":u} · existing access can only be removed`})}else{const d=i.get(c.identityId),u=n.get(l)??"Unavailable Identity";a.push({key:l,label:d?.displayName??u,description:`${d?.status==="merged"?"Merged Identity":u} · existing access can only be removed`})}s.add(l)}}return a}function gv(e){return e.mode==="project-add"?[...new Set(e.projectIds)]:e.mode==="project-manage"?[e.projectId]:[]}function eP(e,t){const n=t.projectRecipients.filter(r=>r.status==="active");return e.mode==="project-add"?[]:e.mode==="project-manage"?n.filter(r=>r.canonicalProjectIdentity===e.projectId).map(ja):n.filter(r=>YT(r,e.recipient)).map(r=>r.canonicalProjectIdentity)}function tP(e,t,n,r){const i=Or(e.map(d=>({canonicalId:d.canonicalProjectIdentity,displayName:d.displayName}))),a=t.mode==="recipient-add"?e.filter(d=>!n.includes(d.canonicalProjectIdentity)):e,s=a.map(d=>({...d,displayName:i.get(d.canonicalProjectIdentity)??d.displayName,description:`${d.existingMemoryCount.toLocaleString()} existing memories`}));if(t.mode!=="recipient-manage")return s;const c=new Set(a.map(d=>d.canonicalProjectIdentity)),l=n.filter(d=>!c.has(d));for(const d of l){const u=r.get(d)??"Unavailable Project";s.push({canonicalProjectIdentity:d,displayName:u,existingMemoryCount:0,description:`${u} · existing access can only be removed`})}return s}function nP(e,t,n){return e.mode==="project-add"?gv(e).flatMap(r=>t.flatMap(i=>{const a=fv(i);return a?[{canonicalProjectIdentity:r,recipient:a,action:"add"}]:[]})):e.mode==="project-manage"?[...new Set([...n,...t])].flatMap(r=>{const i=fv(r);return!i||n.includes(r)===t.includes(r)?[]:[{canonicalProjectIdentity:e.projectId,recipient:i,action:t.includes(r)?"add":"remove"}]}):e.mode==="recipient-add"?t.map(r=>({canonicalProjectIdentity:r,recipient:e.recipient,action:"add"})):[...new Set([...n,...t])].flatMap(r=>n.includes(r)===t.includes(r)?[]:[{canonicalProjectIdentity:r,recipient:e.recipient,action:t.includes(r)?"add":"remove"}])}function rP(e){return e.mode==="project-add"?{title:"Add recipient access",description:"Choose the Teams and Identities that should receive the selected Projects.",legend:"Choose recipients"}:e.mode==="project-manage"?{title:"Manage Project recipients",description:"Choose exactly which Teams and Identities receive this Project.",legend:"Project recipients"}:e.mode==="recipient-add"?{title:"Add Projects",description:"Choose additional Projects for this recipient. Existing access cannot be removed here.",legend:"Additional Projects"}:{title:"Manage recipient Projects",description:"Choose exactly which Projects this recipient receives.",legend:"Recipient Projects"}}function vv(e,t){let n=!1,r=!1,i=!1,a=!1;const s=ut(t);for(const c of e){const{change:l,outcome:d}=c;ut(l.recipient)===s&&(l.action==="add"?(i=!0,d==="added"&&(n=!0)):(a=!0,d==="removed"&&(r=!0)))}return n&&r?"Mixed changes":r?"Removing access":n?"Adding access":i&&!a?"Already has access":a&&!i?"Already without access":"No changes"}function iP(e){const t=new Set(e.selectedRecipients.map(ut)),n=new Map;for(const r of e.normalizedChanges){const i=ut(r.recipient);t.has(i)||n.set(i,r.recipient)}return[...n.values()]}function aP(e){const t=new Set;return e.filter(n=>t.has(n.deviceId)?!1:(t.add(n.deviceId),!0))}function Jd(e,t){const n=t.get(e.canonicalProjectIdentity);return n||(e.displayName!==e.canonicalProjectIdentity?e.displayName:"Unavailable Project")}function oP({preview:e,projectLabels:t,recipientLabels:n}){const r=aP(e.effectiveDevices),i=iP(e);return o("div",{className:"sync-dialog-stack recipient-policy-management-review",children:[o("section",{"aria-labelledby":"recipient-policy-review-projects",children:[o("h3",{id:"recipient-policy-review-projects",children:"Projects affected"}),o("ul",{children:e.projects.map(a=>o("li",{children:[o("strong",{className:"recipient-policy-management-name",children:Jd(a,t)}),o("span",{children:[" ","— Access changes affect ",a.existingMemoryCount.toLocaleString()," existing memories",a.futureMemoriesShared?" and future activity":"; future activity is not included"]})]},a.canonicalProjectIdentity))})]}),o("section",{"aria-labelledby":"recipient-policy-review-recipients",children:[o("h3",{id:"recipient-policy-review-recipients",children:"Recipient changes"}),o("ul",{children:[e.selectedRecipients.map(a=>o("li",{children:[o("strong",{className:"recipient-policy-management-name",children:a.displayName})," ",o("span",{children:["— ",vv(e.outcomes,a)," · "]}),a.recipientKind==="identity"?o("span",{children:"Identity · locally verified"}):o("span",{className:"recipient-policy-management-recipient-context",children:["Team · ",a.currentMembers.length.toLocaleString()," current"," ",a.currentMembers.length===1?"member":"members",a.currentMembers.length?o(z,{children:[":"," ",o("span",{className:"recipient-policy-management-member-names",children:a.currentMembers.map(s=>s.displayName).join(", ")})]}):null,". Future Team members"," ",a.futureMembersInherit?"inherit":"do not inherit"," access."]})]},ut(a))),i.map(a=>o("li",{children:[o("strong",{className:"recipient-policy-management-name",children:n.get(ut(a))??(a.recipientKind==="team"?"Unavailable Team":"Unavailable Identity")})," ",o("span",{children:["— ",vv(e.outcomes,a)," ·"," ",a.recipientKind==="team"?"Team":"Identity"]})]},ut(a)))]})]}),o("section",{"aria-labelledby":"recipient-policy-review-availability",children:[o("h3",{id:"recipient-policy-review-availability",children:"Resulting availability"}),r.length?o(z,{children:[o("p",{children:["After the update, the affected Projects will be available on"," ",r.length.toLocaleString()," current"," ",r.length===1?"device":"devices"," across all recipients."]}),o("ul",{children:r.map(a=>o("li",{className:"recipient-policy-management-name",children:a.displayName},a.deviceId))})]}):o("p",{children:"After the update, no recipient devices will have access to the affected Projects yet — for example, a Team with no current members. Your own access on this device is not affected."})]}),o("details",{className:"recipient-policy-management-details",children:[o("summary",{children:"Change details"}),o("p",{className:"small",children:[e.addCount.toLocaleString()," ",e.addCount===1?"add":"adds"," ·"," ",e.removeCount.toLocaleString()," ",e.removeCount===1?"remove":"removes"," ","· ",e.netWriteCount.toLocaleString()," ",e.netWriteCount===1?"write":"writes"]}),e.unchangedProjects.length?o(z,{children:[o("p",{className:"small recipient-policy-management-detail-label",children:o("strong",{children:"Unchanged Projects"})}),o("ul",{"aria-label":"Unchanged Projects",children:e.unchangedProjects.map(a=>o("li",{className:"recipient-policy-management-name",children:Jd(a,t)},a.canonicalProjectIdentity))})]}):null]})]})}function sP({preview:e,projectLabels:t,recipientLabels:n,result:r}){const i=r.status==="applied"?"Applied":r.status==="not_found"?"Not found":`${r.status.charAt(0).toUpperCase()}${r.status.slice(1)}`;return o("div",{className:"sync-dialog-stack recipient-policy-management-result",children:o("details",{className:"recipient-policy-management-details",children:[o("summary",{children:"Technical details"}),o("p",{children:["Status: ",i,". Writes: ",r.writeCount.toLocaleString(),"."]}),r.errorCode?o("p",{children:["Error code: ",r.errorCode.replaceAll("_"," "),"."]}):null,r.outcomes.length?o("ul",{children:r.outcomes.map(a=>{const s=e.projects.find(d=>d.canonicalProjectIdentity===a.change.canonicalProjectIdentity),c=s?Jd(s,t):t.get(a.change.canonicalProjectIdentity)??"Unavailable Project",l=e.selectedRecipients.find(d=>ut(d)===ut(a.change.recipient))?.displayName??n.get(ut(a.change.recipient))??(a.change.recipient.recipientKind==="team"?"Team":"Identity");return o("li",{children:[a.change.action==="add"?"Add":"Remove"," ",l," ",a.change.action==="add"?"to":"from"," ",c,":"," ",a.outcome.replaceAll("_"," ")]},`${a.change.canonicalProjectIdentity}:${ut(a.change.recipient)}`)})}):null]})})}function cP({intent:e,options:t,projects:n}){const[r,i]=D(null),[a,s]=D([]),[c,l]=D([]),[d,u]=D(null),[p,f]=D(null),[m,v]=D(null),[b,h]=D(""),[y,w]=D(!1),_=B(!1),R=B(new Map),I=B(new Map),T=Ie(()=>XT(e,r),[e,r]),A=Ie(()=>ZT(e,r,T),[e,r,T]),L=Ie(()=>new Map([...e.teams.map(J=>[`team:${J.teamId}`,J.displayName]),...e.identities.map(J=>[`identity:${J.identityId}`,J.displayName]),...T]),[e,T]),F=Ie(()=>QT(n,r,c),[c,n,r]),N=Ie(()=>new Set(n.map(J=>J.canonicalProjectIdentity)),[n]),j=Ie(()=>{const J=Or(n.map(se=>({canonicalId:se.canonicalProjectIdentity,displayName:se.displayName})));return new Map([...J,...F])},[n,F]);if(V(()=>{if(Da=J=>{if(_.current)return!1;const se=eP(J,e);return i(J),l(se),s(J.mode==="recipient-add"?[]:se),u(null),f(null),R.current=new Map,I.current=new Map,v(null),h(""),w(!1),_.current=!1,!0},Ts){const J=Ts;Ts=null,Da(J)}return()=>{Da=null}},[e]),V(()=>{p&&document.getElementById("recipient-policy-management-title")?.focus()},[p]),!r)return null;const x=rP(r),U=gv(r),q=r.mode==="recipient-manage"?!1:U.some(J=>!N.has(J)),$=(r.mode==="recipient-add"||r.mode==="recipient-manage")&&!A.some(J=>J.key===ut(r.recipient)),E=t.loading||t.loadError||q||$,C=nP(r,a,c),O=C.length>pv,H=(r.mode==="project-add"||r.mode==="recipient-add")&&a.length===0,G=r.mode!=="project-add"&&r.mode!=="recipient-add"&&C.length===0,ee=tP(n,r,c,F),Z=p?.status==="applied",ie=p?Z?"Recipient access updated":"Recipient access needs attention":d?"Review recipient access":x.title,fe=p?Z?"The reviewed recipient access changes are applied.":"Some reviewed recipient access changes were not applied. Review the technical details.":d?"Confirm the exact Projects, recipients, and resulting access.":x.description,Ce=()=>{_.current||(i(null),u(null),f(null),R.current=new Map,I.current=new Map,v(null),h(""))},Pe=J=>{s(se=>se.includes(J)?se.filter(ye=>ye!==J):[...se,J]),v(null),h("")},Ne=async()=>{if(!(E||H||G||O||_.current)){_.current=!0,w(!0),v(null),h("Reviewing exact recipient access changes.");try{const J=await bI({version:1,changes:C});R.current=new Map(L),I.current=new Map(j),u(J),h("Review ready. Confirm the exact changes.")}catch(J){v(mv(J,"Unable to review recipient access changes.")),h("")}finally{_.current=!1,w(!1)}}},ce=async()=>{if(!(!d||_.current)){_.current=!0,w(!0),v(null),h("Saving recipient access changes.");try{const J=await _I({version:1,changes:d.normalizedChanges,reviewedPolicyDigest:d.reviewedPolicyDigest});f(J),h("");try{await t.onCommitted?.(J)}catch{v("Recipient access was saved, but this view could not refresh.")}}catch(J){J instanceof Zl&&(u(null),R.current=new Map,I.current=new Map,h("")),v(mv(J,"Unable to save recipient access changes."))}finally{_.current=!1,w(!1)}}};let me=null;return t.loading?me="Loading the complete recipient access inventory…":t.loadError?me="The complete recipient access inventory is unavailable. Refresh and try again.":q?me="One selected Project is no longer available. Refresh and try again.":$&&(me="This recipient is no longer available. Refresh and try again."),o(Ln,{ariaDescribedby:"recipient-policy-management-description",ariaLabelledby:"recipient-policy-management-title",contentClassName:"modal recipient-policy-management-dialog",contentId:"recipientPolicyManagementDialog",onCloseAutoFocus:J=>{J.preventDefault();const se=r.mode.startsWith("project-")?"tabBtn-projects":"tabBtn-sharing",ye=La?.isConnected?La:document.getElementById(se);ye instanceof HTMLElement&&ye.focus(),La=null},onOpenAutoFocus:J=>{const se=document.getElementById("recipient-policy-management-title");se&&(J.preventDefault(),se.focus())},onOpenChange:J=>{J||Ce()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientPolicyManagementDialogBackdrop",children:o("div",{"aria-busy":y||t.loading?"true":"false",className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"recipient-policy-management-title",tabIndex:-1,children:ie}),o(Lr,{ariaLabel:`Close ${ie}`,className:"modal-close-button recipient-policy-management-target",disabled:y,onClick:Ce})]}),o("div",{className:"modal-body recipient-policy-management-selection",children:[o("p",{className:"small",id:"recipient-policy-management-description",children:fe}),me?o("p",{"aria-live":"polite",role:t.loadError?"alert":"status",children:me}):p&&d?o(sP,{preview:d,projectLabels:I.current,recipientLabels:R.current,result:p}):d?o(oP,{preview:d,projectLabels:I.current,recipientLabels:R.current}):r.mode==="recipient-add"||r.mode==="recipient-manage"?o("fieldset",{className:"sync-dialog-radio-list",disabled:y,children:[o("legend",{children:x.legend}),ee.length?ee.map(J=>o(hv,{checked:a.includes(J.canonicalProjectIdentity),description:J.description,disabled:y,label:J.displayName,onChange:()=>Pe(J.canonicalProjectIdentity)},J.canonicalProjectIdentity)):o("p",{className:"small",role:"status",children:r.mode==="recipient-add"?"No additional Projects are available.":"No Projects are available."})]}):o("fieldset",{className:"sync-dialog-radio-list",disabled:y,children:[o("legend",{children:x.legend}),A.length?A.map(J=>o(hv,{checked:a.includes(J.key),description:J.description,disabled:y,label:J.label,onChange:()=>Pe(J.key)},J.key)):o("p",{className:"small",role:"status",children:"No active Teams or Identities are available."})]}),p?null:o("p",{"aria-live":"polite",className:"small recipient-policy-management-status",role:"status",children:b}),m?o("p",{"aria-live":"assertive",role:"alert",children:m}):null,O?o("p",{"aria-live":"assertive",role:"alert",children:["This selection creates ",C.length.toLocaleString()," access changes. Review at most ",pv.toLocaleString()," changes at a time; reduce the selection and try again."]}):null]}),o("div",{className:"modal-footer recipient-policy-management-actions",children:[o("button",{className:"settings-button recipient-policy-management-target",disabled:y,onClick:d&&!p?()=>{u(null),R.current=new Map,I.current=new Map,h("")}:Ce,type:"button",children:p?"Done":d?"Back":"Cancel"}),!p&&!me?o("button",{className:"settings-button sync-dialog-confirm recipient-policy-management-target",disabled:y||!d&&(H||G||O),onClick:()=>{d?ce():Ne()},type:"button",children:y?d?"Saving…":"Reviewing…":d?"Confirm changes":"Review changes"}):null]})]})})}function yv(e,t,n,r={}){Ue(o(cP,{intent:n,options:r,projects:t}),e)}function Ps(e){return e.identity_source!=="unmapped"&&e.read_only!==!0}function lP(e){const t=new Map;for(const n of e)n.read_only_reason==="peer_received"&&t.set(n.workspace_identity,{canonicalProjectIdentity:n.workspace_identity,displayName:n.display_project,existingMemoryCount:n.memory_count??0,latestSessionAt:n.latest_session_at??null});return[...t.values()].sort((n,r)=>n.displayName.localeCompare(r.displayName)||n.canonicalProjectIdentity.localeCompare(r.canonicalProjectIdentity))}function Ns(e){const t=new Map;for(const n of e)Ps(n)&&t.set(n.workspace_identity,{canonicalProjectIdentity:n.workspace_identity,displayName:n.display_project,existingMemoryCount:n.memory_count??0});return[...t.values()].sort((n,r)=>n.displayName.localeCompare(r.displayName)||n.canonicalProjectIdentity.localeCompare(r.canonicalProjectIdentity))}function bv({detailRowCount:e=3,label:t}){return o(z,{children:[o("span",{className:"sr-only",role:"status",children:t}),o("div",{"aria-busy":"true",className:"loading-card-list",children:Array.from({length:2},(n,r)=>o("div",{"aria-hidden":"true",className:"loading-card",children:[o("div",{className:"loading-card-header",children:[o("span",{className:`loading-card-line loading-card-title ${r%2?"w-45":"w-60"}`}),o("span",{className:"loading-card-badge"})]}),o("div",{className:"loading-card-details",children:Array.from({length:e},(i,a)=>o("div",{className:"loading-card-detail",children:[o("span",{className:"loading-card-line loading-card-label"}),o("span",{className:`loading-card-line ${(r+a)%2?"w-45":"w-60"}`})]},a))})]},r))})]})}function dP(e){return e.state!=="configured"}function _v(e){return e?.items.filter(dP)??[]}function Es(e,t){return e.truncated?{blocked:!0,recovery:"Refresh Devices after the complete inventory is available."}:e.coordinatorEvidence.availability==="available"?{blocked:!1,recovery:null}:e.coordinatorEvidence.safeErrorCode==="coordinator_not_configured"&&t.isLocal?{blocked:!1,recovery:null}:{blocked:!0,recovery:"Refresh Devices after coordinator device information is available."}}var uP=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,pP=/^(?:actor|device|identity|local):\S+$/iu,fP=/^(?:actor|device|identity)[_-][a-z0-9][a-z0-9._:-]{4,}$/iu,mP=/^pending[_-]\S+$/iu,hP=/^[a-f0-9]{12,64}$/iu,gP=/^(?=.{1,253}$)(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.){2,}[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?|[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.local)$/iu;function Yd(e){return[uP,pP,fP,mP,hP,gP].some(t=>t.test(e))}function Li(e){if(typeof e!="string"||[...e].some(n=>/[\p{Cc}\p{Cf}]/u.test(n)))return"";const t=e.replace(/\s+/gu," ").trim();return!t||[...t].length>120||Yd(t)?"":t}var $i=null,ji=null;function As(e=[],t=""){if(ji){const n=ji(e,t);return n||($i=null),n}return $i={projectIds:e,teammateName:t},window.location.hash="#projects",!0}function wv(e){return!e.read_only&&e.identity_source!=="unmapped"&&e.memory_count!=null&&!e.guardrail_warnings.some(t=>t.requires_confirmation)}function Sv(e,t){if(!(e instanceof Error))return t;switch(e.message){case"team_sharing_not_configured":return"Set up Team sharing before creating an invitation.";case"team_selection_ambiguous":return"Choose one active Team in settings before creating an invitation.";case"project_selection_ambiguous":return"One selected project has a name collision. Review its project identity first.";case"project_selection_unsupported":case"project_selection_unknown":case"reviewed_project_set_changed":return"The selected projects changed. Review the invitation again.";default:return t}}function vP(e){const t=`share-project-${Dr()}`,n=wv(e.project);return o("label",{className:"sync-dialog-radio-option",htmlFor:t,children:[o("input",{checked:e.selected,disabled:!n,id:t,onChange:()=>e.onToggle(e.project.workspace_identity),type:"checkbox"}),o("span",{children:[o("strong",{children:e.project.display_project}),o("span",{className:"small",children:n?`${(e.project.memory_count??0).toLocaleString()} existing memories`:"Unavailable until this project identity is reviewed"})]})]})}function yP({preview:e}){return o("div",{className:"sync-dialog-stack",children:[o("p",{children:o("strong",{children:[e.teammate.display_name," will receive:"]})}),e.teammate.match==="existing"?o("p",{className:"small",children:"This invitation will use the existing teammate."}):null,o("ul",{children:e.projects.map(t=>o("li",{children:[t.existing_memory_count.toLocaleString()," existing memories and future activity from ",t.display_name]},t.project_id))}),o("p",{children:o("strong",{children:"No other projects will be shared."})})]})}function bP({projects:e,inventoryError:t}){const[n,r]=D(!1),[i,a]=D(""),[s,c]=D([]),[l,d]=D(null),[u,p]=D(null),[f,m]=D(null),[v,b]=D(!1),[h,y]=D(null),[w,_]=D(!1),R=Ie(()=>e.filter(wv),[e]);V(()=>{if(ji=(N,j="")=>{if(t)return!1;const x=[...new Set(N)],U=x.some(q=>!R.some($=>$.workspace_identity===q));return a(j.trim()),c(U?[]:x),_(U),d(null),p(null),m(U?"The original project selection is no longer available. Refresh Projects and try again.":null),y(null),r(!0),!0},$i){const N=$i;$i=null,ji(N.projectIds,N.teammateName)}return()=>{ji=null}},[R,t]),V(()=>{t&&($i=null,r(!1),a(""),c([]),d(null),p(null),m(null),y(null),_(!1))},[t]);const I=()=>{v||r(!1)},T=N=>{c(j=>j.includes(N)?j.filter(x=>x!==N):[...j,N])},A=async()=>{if(m(null),!i.trim()){m("Enter your teammate's name.");return}if(s.length===0){m("Select at least one project.");return}b(!0);try{d(await TI({teammate_name:i.trim(),project_ids:s}))}catch(N){m(Sv(N,"Unable to review this invitation."))}finally{b(!1)}},L=async()=>{if(l){m(null),b(!0);try{p(await PI({teammate_name:l.teammate.display_name,project_ids:l.projects.map(N=>N.project_id),reviewed_project_set_digest:l.reviewed_project_set_digest}))}catch(N){N instanceof Error&&N.message==="reviewed_project_set_changed"&&d(null),m(Sv(N,"Unable to create this invitation."))}finally{b(!1)}}},F=async()=>{if(u){m(null),y(null);try{if(!navigator.clipboard)throw new Error("Clipboard access is unavailable.");await navigator.clipboard.writeText(u.invite.link),y("Invite copied.")}catch(N){m(N instanceof Error?N.message:"Unable to copy the invitation.")}}};return o(z,{children:[o("button",{"aria-describedby":t?"project-share-inventory-error":void 0,className:"settings-button",disabled:t||R.length===0,onClick:()=>ji?.([]),type:"button",children:"Share projects"}),t?o("p",{className:"small",id:"project-share-inventory-error",role:"status",children:"The complete project list is unavailable. Refresh Projects to try again."}):null,n?o(Ln,{ariaDescribedby:"project-share-description",ariaLabelledby:"project-share-title",contentClassName:"modal",contentId:"projectShareDialog",onOpenChange:N=>{N||I()},open:!0,overlayClassName:"modal-backdrop",overlayId:"projectShareDialogBackdrop",children:o("div",{className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"project-share-title",children:"Share projects"}),o("button",{"aria-label":"Close Share projects",disabled:v,onClick:I,type:"button",children:"×"})]}),o("div",{"aria-busy":v,className:"modal-body",children:[o("p",{className:"small",id:"project-share-description",children:"Choose a teammate and the exact projects they may receive after accepting."}),u?o("div",{children:[o("p",{role:"status",children:["Invitation created for ",u.teammate.display_name,"."]}),o("p",{children:["Sharing starts after acceptance:"," ",u.projects.map(N=>N.display_name).join(", "),"."]}),o("p",{className:"small",children:["Invitation expires ",new Date(u.invite.expires_at).toLocaleString(),"."]}),o("button",{className:"settings-button",onClick:()=>{F()},type:"button",children:"Copy invite"}),h?o("p",{role:"status",children:h}):null]}):l?o(yP,{preview:l}):o(z,{children:[o("label",{className:"field",htmlFor:"project-share-teammate",children:[o("span",{children:"Who are you sharing with?"}),o("input",{autoFocus:!0,className:"sync-dialog-input",id:"project-share-teammate",maxLength:120,onInput:N=>a(N.currentTarget.value),type:"text",value:i})]}),o("fieldset",{className:"sync-dialog-radio-list",children:[o("legend",{children:"Select exact projects"}),e.map(N=>o(vP,{onToggle:T,project:N,selected:s.includes(N.workspace_identity)},N.workspace_identity))]})]}),f?o("p",{role:"alert",children:f}):null]}),o("div",{className:"modal-footer",children:[o("button",{className:"settings-button",disabled:v,onClick:I,type:"button",children:u?"Done":"Cancel"}),u?null:o("button",{className:"settings-button sync-dialog-confirm",disabled:v||w,onClick:()=>{l?L():A()},type:"button",children:v?l?"Creating invite…":"Reviewing…":l?"Create invite":"Review sharing"})]})]})}):null]})}function Cv(e,t,n={}){Ue(o(bP,{inventoryError:n.inventoryError===!0,projects:t}),e)}function Xd(e){return Li(String(e??"").trim())}function Oi(e,t){const n=e.trim();return n?[...n].length>120?`${t} must use 120 characters or fewer.`:[...n].some(r=>/[\p{Cc}\p{Cf}]/u.test(r))?`${t} cannot include control or format characters.`:Yd(n)?`${t} must use a human-readable name.`:"":`${t} is required.`}function _P(e){return{...e,status:e.status==="pending_setup"?"pending_setup":void 0,setup_state:e.setup_state==="pending_inviter"||e.setup_state==="restart_required"?e.setup_state:void 0,restart_required:e.restart_required===!0,detail:typeof e.detail=="string"?e.detail:void 0,type:e.type==="project_share"?"project_share":void 0}}function xs(e,t){return e instanceof Error?e instanceof Jm?{device_display_name_invalid:"Enter a human-readable device name instead of an internal identifier.",device_display_name_required:"Enter a device display name.",device_display_name_too_long:"Use a device display name with 120 characters or fewer.",invite_already_bound:"This invitation was accepted by another device. Ask the owner to create a new invitation.",invite_expired:"This invitation expired. Ask the owner to create a new invitation.",invite_identity_conflict:"This invitation does not match this Identity. Ask the owner to create a new invitation for this recipient.",invite_invalid:"This invitation is no longer valid. Ask the owner to create a new invitation.",inviter_identity_invalid:"The owner's device identity could not be verified. Ask the owner to review the share and create a new invitation.",project_invite_acceptance_failed:"The invitation could not be accepted safely. Retry once, then ask the owner to review the share.",project_invite_bootstrap_incomplete:"The owner's device is not ready to establish trust yet. Retry once, then ask the owner to review the share.",project_invite_self_acceptance_forbidden:"The owner cannot accept this recipient invitation on the owner's device.",project_invite_trust_state_invalid:"The owner's trust setup could not be verified. Ask the owner to review the share.",project_sync_enablement_failed:"The invitation was accepted, but Project setup could not be enabled because the codemem config is not writable. Make the config writable, then check Sync to finish setup.",recipient_display_name_invalid:"Enter a human-readable Identity name instead of an internal identifier.",recipient_display_name_required:"Enter an Identity display name.",recipient_display_name_too_long:"Use an Identity display name with 120 characters or fewer."}[e.errorCode]??t:e.message==="reviewed_onboarding_stale"?"Invitation details changed. Review them again before creating it.":e.message==="recipient_invite_review_unavailable"?"The invitation review is unavailable. Ask the owner to create a new invitation.":e.message==="recipient_invite_intent_mismatch"?"The invitation details do not match the reviewed access. Ask the owner to create a new invitation.":e.message==="invite_identity_conflict"?"This device already belongs to a different Identity. Use a fresh device or ask the owner for the correct invitation.":e.message==="recipient_display_name_invalid"?"Enter a human-readable Identity name instead of an internal identifier.":e.message==="recipient_display_name_required"?"Enter an Identity display name before accepting.":e.message==="recipient_display_name_too_long"?"Use an Identity display name with 120 characters or fewer.":t:t}function Oa(e){return`${e.toLocaleString()} existing ${e===1?"memory":"memories"}`}function wP({preview:e}){return e.projects.length===0?o("p",{className:"small",children:"No Projects are currently shared with this Team."}):o("ul",{children:e.projects.map(t=>o("li",{children:[o("strong",{children:t.displayName})," — ",Oa(t.existingMemoryCount)," and future activity"]},t.canonicalProjectIdentity))})}function SP({preview:e}){return o("div",{className:"sync-dialog-stack",children:[o("p",{children:o("strong",{children:["Current Projects for ",e.team?.displayName??"this Team"]})}),o(wP,{preview:e}),o("p",{children:"Future Projects shared with this Team will also be inherited by this member."}),o("p",{children:o("strong",{children:"No other Projects will be shared through this invitation."})})]})}function CP({preview:e}){const t=e.projects.filter(r=>r.sources.some(i=>i.kind==="direct")),n=e.projects.filter(r=>r.sources.some(i=>i.kind==="team"));return o("div",{className:"sync-dialog-stack",children:[o("section",{"aria-labelledby":"add-device-direct-projects",children:[o("h3",{id:"add-device-direct-projects",children:"Direct Projects"}),t.length?o("ul",{children:t.map(r=>o("li",{children:[r.displayName," — ",Oa(r.existingMemoryCount)," and future activity"]},r.canonicalProjectIdentity))}):o("p",{className:"small",children:"No Projects are shared directly."})]}),o("section",{"aria-labelledby":"add-device-team-projects",children:[o("h3",{id:"add-device-team-projects",children:"Projects through Teams"}),n.length?o("ul",{children:n.map(r=>{const i=r.sources.filter(a=>a.kind==="team").map(a=>a.displayName);return o("li",{children:[r.displayName," — ",Oa(r.existingMemoryCount)," and future activity",i.length?` through ${i.join(", ")}`:" through a Team"]},r.canonicalProjectIdentity)})}):o("p",{className:"small",children:"No Projects are inherited through Teams."})]}),o("section",{"aria-labelledby":"add-device-excluded-projects",children:[o("h3",{id:"add-device-excluded-projects",children:"Not included"}),e.excludedProjects.length?o("ul",{children:e.excludedProjects.map(r=>o("li",{children:[r.displayName," — ",Oa(r.existingMemoryCount)]},r.canonicalProjectIdentity))}):o("p",{className:"small",children:"No other Projects are excluded."}),o("p",{className:"small",children:"This device will not receive the Projects listed here."})]}),e.projects.length>0?o("p",{className:"small",role:"note",children:"The lists above describe access, not delivery: Project data does not sync to the invited device until the Project owner’s device completes access setup for it. Until then, shared memories remain on the Identity’s existing devices."}):null]})}function Rv({preview:e}){return e.journey==="team"?o(SP,{preview:e}):o(CP,{preview:e})}function RP({error:e,name:t,onChange:n}){return o("section",{"aria-labelledby":"recipient-onboarding-name-title",children:[o("h3",{id:"recipient-onboarding-name-title",children:"Who will receive access"}),o("label",{className:"field",htmlFor:"recipient-onboarding-name",children:[o("span",{children:"Identity display name"}),o("input",{"aria-describedby":e?"recipient-onboarding-name-error":void 0,"aria-invalid":!!e,id:"recipient-onboarding-name",onInput:r=>n(r.currentTarget.value),placeholder:"Your name — e.g. Alex Rivera",value:t})]}),e?o("p",{className:"small",id:"recipient-onboarding-name-error",role:"alert",children:e}):null]})}function IP({deviceName:e,deviceNameError:t,invite:n,onDeviceNameChange:r,onRecipientNameChange:i,recipientName:a,recipientNameError:s}){const c=n.projects??[];return o("div",{className:"sync-dialog-stack",children:[o("section",{"aria-labelledby":"project-share-invitation-recipient",children:[o("h3",{id:"project-share-invitation-recipient",children:"Who will receive access"}),o("p",{children:"Review these display names before importing the invitation."}),o("label",{className:"field",htmlFor:"project-share-recipient-name",children:[o("span",{children:"Identity display name"}),o("input",{"aria-describedby":s?"project-share-recipient-name-error":void 0,"aria-invalid":!!s,id:"project-share-recipient-name",onInput:l=>i(l.currentTarget.value),placeholder:"Your name — e.g. Alex Rivera",value:a})]}),s?o("p",{className:"small",id:"project-share-recipient-name-error",role:"alert",children:s}):null,o("label",{className:"field",htmlFor:"project-share-device-name",children:[o("span",{children:"Device display name"}),o("input",{"aria-describedby":t?"project-share-device-name-error":void 0,"aria-invalid":!!t,id:"project-share-device-name",onInput:l=>r(l.currentTarget.value),placeholder:"This device — e.g. Work Laptop",value:e})]}),t?o("p",{className:"small",id:"project-share-device-name-error",role:"alert",children:t}):null]}),o("section",{"aria-labelledby":"project-share-invitation-projects",children:[o("h3",{id:"project-share-invitation-projects",tabIndex:-1,children:"Exact Projects shared directly"}),n.inviter_name?o("p",{children:["Invitation from ",n.inviter_name,"."]}):null,o("p",{children:["You will receive ",o("strong",{children:"direct access only"})," to the exact Projects listed below."]}),c.length?o("ul",{children:c.map((l,d)=>o("li",{children:[o("strong",{children:l.display_name})," —"," ",Oa(l.existing_memory_count)," and future activity"]},`${l.display_name}:${d}`))}):o("p",{role:"alert",children:"Project details are unavailable. Ask the owner to create a new invitation before accepting."})]}),o("p",{children:o("strong",{children:"Accepting this invitation does not join a Team."})}),o("p",{children:o("strong",{children:"No other Projects are included."})})]})}function kP({result:e}){const t=e.restart_required===!0||e.setup_state==="restart_required",n=e.type==="project_share"&&e.status==="pending_setup";return o("div",{className:"sync-dialog-stack",children:[o("h3",{id:"project-share-invitation-result",tabIndex:-1,children:"Project invitation accepted"}),t?o("p",{role:"status",children:[o("strong",{children:"Project setup is pending and codemem must be restarted."})," Restart codemem to start the sync service. Access remains pending until setup and the first sync finish."]}):n?o("p",{role:"status",children:[o("strong",{children:"Project setup is pending."})," The owner still needs to finish access setup, and the Projects will appear after the first sync completes."]}):o("p",{role:"status",children:"The invitation was accepted, but Project setup status could not be confirmed. Check Sync before expecting Project data."})]})}function TP({result:e}){const t=e.kind==="team_member"?"Team invitation accepted":"Device added",n=[e.restartRequired?"recipient-invitation-result-detail":null,e.deliveryPending?"recipient-invitation-result-delivery":null].filter(Boolean).join(" ")||void 0;return o("section",{"aria-describedby":n,"aria-labelledby":"recipient-invitation-result-title",className:"recipient-policy-invitation-result",id:"recipient-invitation-result",tabIndex:-1,children:[o("span",{"aria-hidden":"true",className:"recipient-policy-invitation-result-mark",children:"✓"}),o("div",{className:"recipient-policy-invitation-result-copy",children:[o("h3",{id:"recipient-invitation-result-title",children:t}),e.restartRequired?o("p",{id:"recipient-invitation-result-detail",children:e.detail}):null,e.deliveryPending?o("p",{className:"small",id:"recipient-invitation-result-delivery",children:"Existing shared Projects do not sync to this device until the Project owner’s device completes access setup for it."}):null]})]})}function Iv(e,t){return e==="team_member"?{kind:e,policy_team_id:t}:{kind:e,target_identity_id:t}}function PP({intent:e}){const t=e.teams.filter(Q=>Q.status==="active"),n=e.identities.filter(Q=>Q.status==="active"),[r,i]=D(null),[a,s]=D("team_member"),[c,l]=D(t[0]?.teamId??""),[d,u]=D(""),[p,f]=D(null),[m,v]=D(null),[b,h]=D(null),[y,w]=D(null),[_,R]=D(""),[I,T]=D(""),[A,L]=D(""),[F,N]=D(null),[j,x]=D(!1),[U,q]=D(""),[$,E]=D(""),C=B(null),O=B(0),H=B(""),G=B(!1);V(()=>{if(y){document.getElementById("recipient-invitation-result")?.focus();return}if(b){document.getElementById("project-share-invitation-result")?.focus();return}m?.kind==="project_share_invite"&&document.getElementById("project-share-invitation-projects")?.focus()},[m,b,y]);const ee=()=>{O.current+=1,H.current="",G.current=!1,u(""),f(null),v(null),h(null),w(null),R(""),T(""),L(""),N(null),q(""),E("")},Z=(Q,we)=>{ee(),C.current=we,i(Q)},ie=()=>{j||(i(null),ee())},fe=Q=>{O.current+=1,H.current=Q,u(Q)},Ce=Q=>{s(Q),l(Q==="team_member"?t[0]?.teamId??"":n[0]?.identityId??""),ee()},Pe=async()=>{if(c){x(!0),E(""),q("Reviewing invitation…");try{const Q=await wI(Iv(a,c));f(Q.preview),q("Review ready. Confirm the invitation details.")}catch(Q){E(xs(Q,"Unable to review this invitation.")),q("")}finally{x(!1)}}},Ne=async()=>{if(p){x(!0),E(""),q("Creating invitation…");try{const Q=await SI({...Iv(a,c),reviewed_onboarding_digest:p.reviewedOnboardingDigest});N(Q),q("Invitation created.")}catch(Q){Q instanceof Error&&Q.message==="reviewed_onboarding_stale"&&f(null),E(xs(Q,"Unable to create this invitation.")),q("")}finally{x(!1)}}},ce=async()=>{const Q=H.current.trim(),we=O.current;if(!Q){E("Paste an invitation first.");return}const ae=()=>O.current===we&&H.current.trim()===Q;x(!0),E(""),q("Reviewing invitation…");try{const Fe=await Ym(Q);if(!ae())return;v(Fe),Fe.kind==="team_member"?R(Xd(Fe.recipient_name)):Fe.kind==="project_share_invite"&&(T(Xd(Fe.recipient_name)),L(Xd(Fe.device_name))),q(Fe.kind==="add_device"?(Fe.onboarding?.projects?.length??0)>0?"Review ready. Existing shared Projects sync to the invited device only after the owner’s device completes access setup. Confirm before accepting.":"Review ready. Confirm before accepting.":Fe.kind==="team_member"?"Review ready. Confirm before accepting.":Fe.kind==="project_share_invite"?"Review ready. Confirm the exact Projects before accepting.":"Open Advanced, then Sync, to review and import this legacy invitation.")}catch(Fe){if(!ae())return;E(xs(Fe,"Unable to review this invitation.")),q("")}finally{x(!1)}},me=async()=>{if(!(j||G.current||y)&&!(!m||m.kind==="legacy_team_invite")&&!(m.kind==="project_share_invite"&&!(m.projects?.length??0))&&!(m.kind==="project_share_invite"&&(Oi(I,"Identity display name")||Oi(A,"Device display name")))&&!(m.kind==="team_member"&&Oi(_,"Identity display name"))){G.current=!0,x(!0),E(""),q("Accepting invitation…");try{const Q=m.kind==="project_share_invite"?await Yl(d.trim(),{recipient_name:I.trim(),device_name:A.trim()},m.kind):await Yl(d.trim(),{...m.kind==="team_member"?{recipient_name:_.trim()}:{},device_name:m.device_name,reviewed_onboarding_digest:m.onboarding.reviewedOnboardingDigest},m.kind);if(m.kind==="project_share_invite")h(_P(Q)),q("");else{const we=m.kind,ae=Q.restart_required===!0||Q.setup_state==="restart_required";w({kind:we,restartRequired:ae,detail:we==="team_member"?"Restart codemem to finish joining this Team.":"Restart codemem to finish adding this device.",deliveryPending:we==="add_device"&&(m.onboarding?.projects?.length??0)>0}),q("")}}catch(Q){G.current=!1;const we=m.kind==="project_share_invite"?"Unable to accept this Project invitation. Ask the owner to create a new invitation, then try again.":"Unable to accept this invitation.";E(xs(Q,we)),q("")}finally{x(!1)}}},J=async()=>{const Q=F?.invite.link||F?.invite.encoded||"";if(!Q){E("The invitation text is unavailable.");return}try{await navigator.clipboard.writeText(Q),q("Invitation copied.")}catch{E("Unable to copy the invitation.")}},se=m?.kind==="team_member"||m?.kind==="add_device"?m.onboarding:null,ye=m?.kind==="project_share_invite"?m:null,le=m?.kind==="team_member"?Oi(_,"Identity display name"):"",Ee=ye?Oi(I,"Identity display name"):"",re=ye?Oi(A,"Device display name"):"";return o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:[o("article",{className:"peer-card peer-card--padded recipient-policy-sharing-card",children:[o("h3",{children:"Create an invitation"}),o("p",{children:"Invite a Team member, add a device, or share an exact set of Projects."}),o("div",{className:"peer-actions recipient-policy-sharing-responsive-actions",children:[o("button",{className:"settings-button recipient-policy-sharing-target-24",disabled:t.length===0,onClick:Q=>{Ce("team_member"),Z("create",Q.currentTarget)},type:"button",children:"Invite Team member"}),o("button",{className:"settings-button recipient-policy-sharing-target-24",disabled:n.length===0,onClick:Q=>{Ce("add_device"),Z("create",Q.currentTarget)},type:"button",children:"Add a device"}),o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>As(),type:"button",children:"Share exact Projects"})]}),t.length===0&&n.length===0?o("p",{className:"small",role:"status",children:"No active Teams or Identities are available."}):null]}),o("article",{className:"peer-card peer-card--padded recipient-policy-sharing-card",children:[o("h3",{children:"Accept an invitation"}),o("p",{children:"Review Team membership, device access, or exact Project access before accepting."}),o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:Q=>Z("accept",Q.currentTarget),type:"button",children:"Review invitation"}),o("p",{className:"small",children:"Legacy invitation import remains under Advanced, in Sync."})]}),r?o(Ln,{ariaDescribedby:"recipient-invitation-description",ariaLabelledby:"recipient-invitation-title",contentClassName:"modal recipient-policy-invitation-dialog",contentId:"recipientInvitationDialog",onCloseAutoFocus:Q=>{Q.preventDefault(),C.current?.focus(),C.current=null},onOpenAutoFocus:Q=>{Q.preventDefault(),document.getElementById("recipient-invitation-title")?.focus()},onOpenChange:Q=>{Q||ie()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientInvitationDialogBackdrop",children:o("div",{"aria-busy":j,className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"recipient-invitation-title",tabIndex:-1,children:y?"Invitation accepted":r==="create"?"Create invitation":"Review invitation"}),o(Lr,{ariaLabel:"Close invitation",className:"modal-close-button recipient-policy-sharing-target-24",disabled:j,onClick:ie})]}),o("div",{className:"modal-body",children:[o("p",{className:"small",id:"recipient-invitation-description",children:y?"The invitation has been accepted.":"Confirm exactly what this invitation includes before continuing."}),r==="create"&&!p&&!F?o("label",{className:"field",htmlFor:"recipient-invitation-target",children:[o("span",{children:a==="team_member"?"Team":"Identity"}),o("select",{id:"recipient-invitation-target",onChange:Q=>l(Q.currentTarget.value),value:c,children:(a==="team_member"?t:n).map(Q=>o("option",{value:"teamId"in Q?Q.teamId:Q.identityId,children:Q.displayName},"teamId"in Q?Q.teamId:Q.identityId))})]}):r==="accept"&&!m&&!y?o("label",{className:"field",htmlFor:"recipient-invitation-value",children:[o("span",{children:"Invitation"}),o("textarea",{id:"recipient-invitation-value",onInput:Q=>{fe(Q.currentTarget.value),v(null),h(null),q(""),E("")},rows:5,value:d})]}):null,p?o(Rv,{preview:p}):null,se&&!y?o(Rv,{preview:se}):null,m?.kind==="team_member"&&!y?o(RP,{error:le,name:_,onChange:Q=>{R(Q),E("")}}):null,ye&&!b?o(IP,{deviceName:A,deviceNameError:re,invite:ye,onDeviceNameChange:Q=>{L(Q),E("")},onRecipientNameChange:Q=>{T(Q),E("")},recipientName:I,recipientNameError:Ee}):null,b?o(kP,{result:b}):null,y?o(TP,{result:y}):null,F?o("div",{children:[o("p",{children:"Share the invitation with the recipient."}),o("button",{className:"settings-button",onClick:()=>{J()},type:"button",children:"Copy invitation"})]}):null,m?.kind==="legacy_team_invite"?o("p",{children:"Open Advanced, then Sync, to review and import this legacy invitation."}):null,o("p",{"aria-live":"polite",className:"small",role:"status",children:U}),$?o("p",{"aria-live":"assertive",role:"alert",children:$}):null]}),o("div",{className:"modal-footer recipient-policy-sharing-responsive-actions",children:[o("button",{className:"settings-button",disabled:j,onClick:ie,type:"button",children:F||b||y?"Done":"Cancel"}),r==="create"&&!F?o("button",{className:"settings-button sync-dialog-confirm",disabled:j||!c,onClick:()=>{p?Ne():Pe()},type:"button",children:j?"Working…":p?"Create invitation":"Review invitation"}):r==="accept"&&!m&&!y?o("button",{className:"settings-button sync-dialog-confirm",disabled:j,onClick:()=>{ce()},type:"button",children:j?"Reviewing…":"Review invitation"}):se&&!y||ye&&!b?o("button",{className:"settings-button sync-dialog-confirm",disabled:j||!!(m?.kind==="team_member"&&le)||!!(ye&&(!ye.projects?.length||Ee||re)),onClick:()=>{me()},type:"button",children:j?"Accepting…":ye?"Accept Project access":"Accept invitation"}):null]})]})}):null]})}function NP(e){const t=e.trim();return t?[...t].length>120?"Team name must use 120 characters or fewer.":[...t].some(n=>/[\p{Cc}\p{Cf}]/u.test(n))?"Team name cannot include control or format characters.":Yd(t)?"Enter a human-readable Team name.":"":"Team name is required."}function EP(e){return e instanceof rs?e.errorCode==="team_name_invalid"?"Enter a valid human-readable Team name.":e.errorCode==="team_not_found"?"This Team is no longer available. Refresh Sharing and try again.":e.errorCode==="team_rename_stale"?"This Team changed since you opened settings. Refresh Sharing and try again.":e.errorCode==="team_link_stale"?"This Team’s connected setup is no longer configured. Refresh Sharing before renaming it.":e.errorCode==="team_link_ambiguous"?"This Team has conflicting connected setup records. Nothing was changed. Review the Team setup before retrying.":e.errorCode==="team_coordinator_rename_failed"?"The connected Team service could not be updated. Nothing changed locally. Try again.":e.errorCode==="team_local_rename_pending"?"The connected Team service was updated, but Sharing could not save the name locally. Try again to finish.":"The Team could not be renamed safely. Try again.":"The Team could not be renamed. Try again."}function AP({descriptionId:e,disabled:t,displayName:n,onRenamed:r,renameTeam:i=WR,teamId:a}){const[s,c]=D(!1),[l,d]=D(n),[u,p]=D(!1),[f,m]=D(""),[v,b]=D(""),h=B(null),y=B(null),w=B(null);V(()=>{v&&!u&&w.current?.focus()},[u,v]);const _=()=>{u||(c(!1),m(""),b(""))},R=async()=>{const I=NP(l);if(I){m(I);return}if(!u){p(!0),m(""),b("");try{const T=await i({teamId:a,displayName:l,expectedDisplayName:n});d(T.displayName),b(`Team renamed to ${T.displayName}.`);try{await r?.()===!1&&b(`Team renamed to ${T.displayName}, but Sharing could not refresh.`)}catch{b(`Team renamed to ${T.displayName}, but Sharing could not refresh.`)}}catch(T){m(EP(T))}finally{p(!1)}}};return o(z,{children:[o("button",{"aria-describedby":e,"aria-disabled":t?"true":void 0,"aria-label":`Team settings for ${n}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",onClick:()=>{t||(d(n),m(""),b(""),c(!0))},ref:h,type:"button",children:"Team settings"}),o(Ln,{ariaDescribedby:"recipient-policy-team-settings-description",ariaLabelledby:"recipient-policy-team-settings-title",contentClassName:"modal recipient-policy-team-settings-dialog",contentId:"recipientPolicyTeamSettingsDialog",onCloseAutoFocus:I=>{I.preventDefault(),h.current?.focus()},onEscapeKeyDown:I=>{u&&I.preventDefault()},onInteractOutside:I=>{u&&I.preventDefault()},onOpenAutoFocus:I=>{I.preventDefault(),y.current?.focus(),y.current?.select()},onOpenChange:I=>{I||_()},open:s,overlayClassName:"modal-backdrop",overlayId:"recipientPolicyTeamSettingsDialogBackdrop",children:o("div",{"aria-busy":u?"true":"false",className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"recipient-policy-team-settings-title",children:"Team settings"}),o(Lr,{ariaLabel:"Close Team settings",disabled:u,onClick:_})]}),o("div",{className:"modal-body",children:[o("p",{className:"small",id:"recipient-policy-team-settings-description",children:"Change the name shown for this Team in Sharing."}),o("label",{className:"form-field",htmlFor:"recipient-policy-team-settings-name",children:[o("span",{children:"Team name"}),o("input",{disabled:u||!!v,id:"recipient-policy-team-settings-name",maxLength:120,onInput:I=>{d(I.currentTarget.value),m("")},ref:y,value:l})]}),u?o("p",{"aria-live":"polite",role:"status",children:"Saving Team name…"}):null,f?o("p",{"aria-live":"assertive",role:"alert",children:f}):null,v?o("p",{"aria-live":"polite",role:"status",children:v}):null]}),o("div",{className:"modal-footer recipient-policy-team-settings-actions",children:[o("button",{className:"settings-button",disabled:u,onClick:_,ref:w,type:"button",children:v?"Done":"Cancel"}),v?null:o("button",{className:"settings-button sync-dialog-confirm",disabled:u||!l.trim()||l.trim()===n,onClick:()=>{R()},type:"button",children:u?"Saving…":f?"Try again":"Save"})]})]})})]})}var kv={needs_setup:"Ready to review",in_progress:"Migration in progress",stale:"Migration review needs update"},Tv={needs_setup:"needs_attention",in_progress:"suggested",stale:"needs_attention"},Qd={role:"list"},Zd={role:"listitem"};function xP(e){return typeof e=="string"&&Object.hasOwn(kv,e)?kv[e]:"Ready to review"}function DP(e){return typeof e=="string"&&Object.hasOwn(Tv,e)?Tv[e]:"needs_attention"}function LP(e){const t=new Map;for(const n of e){const r=n.displayName.trim().toLowerCase(),i=t.get(r);i?t.set(r,{...i,candidates:[...i.candidates,n]}):t.set(r,{displayName:n.displayName,candidates:[n]})}return[...t.values()].map(n=>({...n,candidates:[...n.candidates].sort((r,i)=>r.candidateRef<i.candidateRef?-1:r.candidateRef>i.candidateRef?1:0)}))}function $P({candidates:e,onOpenTeamSetup:t}){if(e.length===0)return null;const n=LP(e);return o("aside",{"aria-labelledby":"sharing-team-setup-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"sharing-team-setup-heading",children:"Legacy groups to migrate"}),o("p",{children:"Current devices are proposed for review. No Team membership or Project access changes happen until you finish the migration."}),o("ul",{...Qd,className:"recipient-policy-sharing-team-setup-list","aria-label":"Team setup status",children:n.map(r=>g("li",{...Zd,className:"recipient-policy-sharing-team-setup-group",key:r.displayName},r.candidates.length>1?o("div",{className:"recipient-policy-sharing-team-setup-group-title",children:[o("strong",{children:r.displayName}),o("span",{className:"small",children:[r.candidates.length," Teams"]})]}):null,o("div",{className:"recipient-policy-sharing-team-setup-rows",children:r.candidates.map((i,a)=>{const s=`${a+1} of ${r.candidates.length}`,c=`${Yt(i.deviceCount,"device")}, ${Yt(i.projectCount,"Project")}`,l=r.candidates.length>1?`Review and migrate ${r.displayName} ${s}: ${c}`:`Review and migrate ${i.displayName}: ${c}`;return o("div",{className:"recipient-policy-sharing-team-setup-row",children:[o("span",{className:"recipient-policy-sharing-team-setup-label",children:[r.candidates.length>1?o("span",{className:"small",children:["Team ",s," · ",c]}):o(z,{children:[o("strong",{children:i.displayName}),o("span",{className:"small",children:[" · ",c]})]}),o("span",{"aria-hidden":"true",className:"recipient-policy-sharing-team-setup-separator",children:[" ","—"," "]})]}),o("span",{className:"recipient-policy-sharing-team-setup-status",children:o("span",{className:`project-status-badge ${DP(i.status)}`.trim(),children:xP(i.status)})}),o("span",{className:"recipient-policy-sharing-team-setup-action",children:t?o("button",{"aria-label":l,className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t(i.candidateRef),type:"button",children:"Review and migrate"}):null})]},i.candidateRef)})})))})]})}var Mr=[{id:"teams",label:"Teams"},{id:"identities",label:"Identities"},{id:"received",label:"Received"},{id:"invitations",label:"Invitations"}];function Yt(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function jP(e,t){return e.length?e.join(", "):t}var Pv=3;function eu({empty:e,label:t,names:n}){return n.length===0?o(z,{children:e}):n.length<=Pv?o(z,{children:jP(n,e)}):o(z,{children:[n.slice(0,Pv).join(", "),o("span",{"aria-hidden":"true",children:", …"}),o("details",{className:"recipient-policy-sharing-name-details",children:[o("summary",{children:["View all ",Yt(n.length,t)]}),o("ul",{...Qd,"aria-label":`All ${t}s`,children:n.map((r,i)=>g("li",{...Zd,key:`${i}-${r}`},r))})]})]})}function Nv(e,t){return[...new Set(e)].map(n=>({canonicalId:n,displayName:t.get(n)?.displayName??"Unavailable Project"}))}var Ev=3;function Av({empty:e,identities:t,qualifier:n}){if(t.length===0)return o(z,{children:e});const r=JT(t),i=s=>s.identityCount>1?`${s.displayName} (${Yt(s.identityCount,"identity","identities")})`:s.displayName,a=r.slice(0,Ev);return o(z,{children:[Yt(t.length,`${n} Project identity`,`${n} Project identities`)," ","— ",a.map(i).join(", "),r.length>Ev?o(z,{children:[o("span",{"aria-hidden":"true",children:", …"}),o("details",{className:"recipient-policy-sharing-project-details",children:[o("summary",{children:["View all ",Yt(r.length,"Project name group")]}),o("ul",{...Qd,"aria-label":`All ${n} Project identity groups`,children:r.map(s=>g("li",{...Zd,key:s.displayName},i(s)))})]})]}):null]})}function xv({descriptionId:e,disabled:t,displayName:n,recipient:r}){const i=()=>{$a({mode:"recipient-manage",recipient:r})},a=()=>{$a({mode:"recipient-add",recipient:r})};return o(z,{children:[o("div",{className:"peer-actions recipient-policy-sharing-actions recipient-policy-sharing-responsive-actions",children:[o("button",{"aria-describedby":e,"aria-disabled":t?"true":void 0,"aria-label":`Add projects for ${n}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",onClick:()=>{t||a()},type:"button",children:"Add projects"}),o("button",{"aria-describedby":e,"aria-disabled":t?"true":void 0,"aria-label":`Manage projects for ${n}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",onClick:()=>{t||i()},type:"button",children:"Manage projects"})]}),o("p",{className:"small",id:e,children:t?"Team and Identity Project changes are disabled until a refresh succeeds.":"Add projects only adds the selected Projects after you preview the exact changes."})]})}function OP({disableMutations:e,intent:t,onTeamRenamed:n,projects:r,renameTeam:i}){const a=t.teams.filter(l=>l.status==="active"),s=new Map(t.identities.filter(l=>l.status==="active").map(l=>[l.identityId,l])),c=new Map(r.map(l=>[l.canonicalProjectIdentity,l]));return a.length===0?o("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No active Teams are available for Project sharing."}):o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:a.map((l,d)=>{const u=[...new Set(t.teamMemberships.filter(h=>h.status==="active"&&h.teamId===l.teamId&&s.has(h.identityId)).map(h=>h.identityId))],p=u.map(h=>s.get(h)?.displayName??""),f=new Set(t.identityDevices.filter(h=>h.status==="active"&&u.includes(h.identityId)).map(h=>h.deviceId)).size,m=Nv(t.projectRecipients.filter(h=>h.status==="active"&&h.recipientKind==="team"&&h.teamId===l.teamId).map(h=>h.canonicalProjectIdentity),c),v=`recipient-policy-sharing-team-title-${d}`,b=`recipient-policy-sharing-team-add-description-${d}`;return o("article",{"aria-labelledby":v,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-team-card",children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:v,children:l.displayName}),o("span",{className:"badge actor-badge",children:"Team"})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Current members"}),o("dd",{children:[Yt(p.length,"active member")," —"," ",o(eu,{empty:"No active members",label:"member",names:p})]})]}),o("div",{children:[o("dt",{children:"Registered devices"}),o("dd",{children:Yt(f,"active registered device")})]}),o("div",{children:[o("dt",{children:"Shared projects"}),o("dd",{children:o(Av,{empty:"No Projects shared",identities:m,qualifier:"active shared"})})]}),o("div",{children:[o("dt",{children:"Future Team members"}),o("dd",{children:"Yes — future Team members inherit the Team’s shared Projects."})]})]}),o(xv,{descriptionId:b,disabled:e,displayName:l.displayName,recipient:{recipientKind:"team",teamId:l.teamId}}),o("div",{className:"peer-actions recipient-policy-sharing-actions recipient-policy-sharing-responsive-actions",children:o(AP,{descriptionId:b,disabled:e,displayName:l.displayName,onRenamed:n,renameTeam:i,teamId:l.teamId})})]},l.teamId)})})}function MP({disableMutations:e,intent:t,projects:n}){const r=t.identities.filter(s=>s.status==="active"),i=new Map(t.teams.filter(s=>s.status==="active").map(s=>[s.teamId,s])),a=new Map(n.map(s=>[s.canonicalProjectIdentity,s]));return r.length===0?o("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No active Identities are available for Project sharing."}):o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:r.map((s,c)=>{const l=t.identityDevices.filter(m=>m.status==="active"&&m.identityId===s.identityId),d=[...new Set(t.teamMemberships.filter(m=>m.status==="active"&&m.identityId===s.identityId&&i.has(m.teamId)).map(m=>m.teamId))].map(m=>i.get(m)?.displayName??""),u=Nv(t.projectRecipients.filter(m=>m.status==="active"&&m.recipientKind==="identity"&&m.identityId===s.identityId).map(m=>m.canonicalProjectIdentity),a),p=`recipient-policy-sharing-identity-title-${c}`,f=`recipient-policy-sharing-identity-add-description-${c}`;return o("article",{"aria-labelledby":p,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-identity-card",children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:p,children:s.displayName}),o("span",{className:"badge actor-badge local",children:"Local identity"})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Verification"}),o("dd",{children:"Local identity"})]}),o("div",{children:[o("dt",{children:"Registered devices"}),o("dd",{children:[Yt(l.length,"active registered device")," —"," ",o(eu,{empty:"No active devices",label:"device",names:l.map(m=>m.displayName)})]})]}),o("div",{children:[o("dt",{children:"Team memberships"}),o("dd",{children:[Yt(d.length,"active Team membership")," —"," ",o(eu,{empty:"No active Team memberships",label:"Team membership",names:d})]})]}),o("div",{children:[o("dt",{children:"Directly shared projects"}),o("dd",{children:o(Av,{empty:"No Projects shared directly",identities:u,qualifier:"directly shared active"})})]})]}),o("p",{className:"small",children:"Team Projects are shown on Team cards because per-device eligibility cannot be inferred from Identity membership alone."}),o(xv,{descriptionId:f,disabled:e,displayName:s.displayName,recipient:{recipientKind:"identity",identityId:s.identityId}})]},s.identityId)})})}function FP({received:e}){return e.length===0?o("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No received Projects on this device. Accepted invitations appear here once their first sync completes."}):o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:e.map((t,n)=>{const r=`recipient-policy-sharing-received-title-${n}`;return o("article",{"aria-labelledby":r,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-received-card",children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:r,children:t.displayName}),o("span",{className:"badge actor-badge",children:"Received"})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Memories on this device"}),o("dd",{children:Yt(t.existingMemoryCount,"memory","memories")})]}),o("div",{children:[o("dt",{children:"Latest activity"}),o("dd",{children:t.latestSessionAt?new Date(t.latestSessionAt).toLocaleString():"No recent sessions"})]})]}),o("p",{className:"small",children:"This Project is received from another device. Access is managed where the Project is shared from; this device keeps it read-only."})]},t.canonicalProjectIdentity)})})}function BP({intent:e,options:t,projects:n}){const[r,i]=D(()=>e.teams.some(m=>m.status==="active")?"teams":"identities"),a=B(t.loading===!0||t.loadError===!0),s=B([]),c=_v(t.deviceInventory),l=c.length,d=t.coordinatorEnrollmentIssueCount??0,u=e.teams.some(m=>m.status==="active");V(()=>{if(a.current&&!t.loading&&!t.loadError){a.current=!1,i(u?"teams":"identities");return}u||i(m=>m==="teams"?"identities":m)},[u,t.loadError,t.loading]);const p=m=>{const v=Mr[m];v&&(i(v.id),s.current[m]?.focus())},f=(m,v)=>{let b=null;m.key==="ArrowRight"?b=(v+1)%Mr.length:m.key==="ArrowLeft"?b=(v-1+Mr.length)%Mr.length:m.key==="Home"?b=0:m.key==="End"&&(b=Mr.length-1),b!==null&&(m.preventDefault(),p(b))};return o("section",{className:"recipient-policy-sharing recipient-policy-sharing-responsive-surface",children:[o("header",{className:"recipient-policy-sharing-header",children:[o("h2",{children:"Sharing"}),o("p",{className:"small",children:"See who receives Projects, how Team membership carries Project access, and where to make changes."})]}),o($P,{candidates:t.teamSetupSummary?.candidates??[],onOpenTeamSetup:t.onOpenTeamSetup}),t.teamSetupLoading&&!t.teamSetupSummary?o("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:"Team setup status is loading."}):null,t.teamSetupUnavailable?o("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:t.teamSetupSummary?"Team setup status is temporarily unavailable. The previous Team setup status is being shown.":"Team setup status is temporarily unavailable."}):null,t.deviceInventoryUnavailable?o("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:"Device Identity information is unavailable. Devices needing setup or review cannot be shown until a refresh succeeds."}):null,l>0&&!t.deviceInventoryUnavailable?o("aside",{"aria-labelledby":"sharing-device-setup-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"sharing-device-setup-heading",children:"Identity setup needed"}),o("p",{children:[l.toLocaleString()," ",l===1?"device needs":"devices need"," setup, pairing, or review before ownership can be shown accurately."]}),o("p",{className:"small",children:"Identity setup records device ownership only. It does not grant Projects, Team membership, or sync access."}),t.onReviewDevices?o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onReviewDevices?.(c[0]?.deviceId),type:"button",children:"Review devices"}):null]}):null,d>0?o("aside",{"aria-labelledby":"sharing-coordinator-reconciliation-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"sharing-coordinator-reconciliation-heading",children:"Device setup reconciliation needs attention"}),o("p",{children:[d.toLocaleString()," coordinator enrollment",d===1?" could":"s could"," not be safely reconciled. Sharing remains unchanged until the device evidence is valid."]}),o("p",{className:"small",children:"Coordinator groups are discovery boundaries, not policy Teams, and do not prove device ownership."}),t.onReviewDevices?o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onReviewDevices?.(),type:"button",children:"Review devices"}):null]}):null,t.refreshError?o("p",{"aria-live":"assertive",className:"recipient-policy-sharing-state recipient-policy-sharing-error",role:"alert",children:"Refresh failed; showing previous Sharing details. Team and Identity Project changes are disabled until a refresh succeeds."}):null,o("div",{"aria-label":"Sharing views",className:"recipient-policy-sharing-tabs recipient-policy-sharing-responsive-tabs",role:"tablist",children:Mr.map((m,v)=>o("button",{"aria-controls":`recipient-policy-sharing-panel-${m.id}`,"aria-selected":r===m.id,className:`tab-btn recipient-policy-sharing-tab recipient-policy-sharing-target recipient-policy-sharing-target-24${r===m.id?" active":""}`,id:`recipient-policy-sharing-tab-${m.id}`,onClick:()=>i(m.id),onKeyDown:b=>f(b,v),ref:b=>{s.current[v]=b},role:"tab",tabIndex:r===m.id?0:-1,type:"button",children:m.label},m.id))}),Mr.map(m=>o(z,{children:o("div",{"aria-labelledby":`recipient-policy-sharing-tab-${m.id}`,className:"recipient-policy-sharing-panel",hidden:r!==m.id,id:`recipient-policy-sharing-panel-${m.id}`,role:"tabpanel",tabIndex:0,children:t.loading?r===m.id?o(bv,{detailRowCount:4,label:"Loading Sharing details"}):null:t.loadError?r===m.id?o("p",{"aria-live":"assertive",className:"recipient-policy-sharing-state recipient-policy-sharing-error",role:"alert",children:"Sharing details are unavailable. Refresh and try again."}):null:m.id==="teams"?o(OP,{disableMutations:t.refreshError===!0,intent:e,onTeamRenamed:t.onTeamRenamed,projects:n,renameTeam:t.renameTeam}):m.id==="identities"?o(MP,{disableMutations:t.refreshError===!0,intent:e,projects:n}):m.id==="received"?o(FP,{received:t.received??[]}):o(PP,{intent:e})})},m.id))]})}function qP(e,t,n,r={}){Ue(o(BP,{intent:n,options:r,projects:t}),e)}var tu={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]};async function UP(e={}){const t=[];let n=0;for(;;){const r=await Sa({limit:250,offset:n,signal:e.signal});if(t.push(...r.projects),!r.has_more)break;n+=r.limit}return{manageable:Ns(t),received:lP(t)}}var GP={loadDeviceInventory:td,loadIntent:ed,loadProjects:UP,loadSyncStatus:Jl,loadTeamSetupSummary:ah,mountManagement:yv,mountSharing:qP};async function HP(e,t){if(!t.awaitTeamSetupSummary&&!t.requireTeamSetupSummary)return!0;try{return await e.loadTeamSetupSummary({signal:t.signal}),!t.signal?.aborted}catch{return!t.requireTeamSetupSummary&&!t.signal?.aborted}}function VP(e){return!e.options.awaitTeamSetupSummary&&!e.options.requireTeamSetupSummary?e.loadSucceeded:e.teamSetupSummaryPromise.then(t=>e.isCurrent()?e.loadSucceeded&&(!e.options.requireTeamSetupSummary||t):!1)}function KP(e){return e.awaitTeamSetupSummary===!0||e.requireTeamSetupSummary===!0}function zP(e={},t={}){const n={...GP,...e};let r=0,i=null,a=0,s,c,l=!1,d=!1,u=!1,p=!1,f=null;const m=(b={})=>{const h=v(++r,b);return i=h,h};async function v(b,h){const y=document.getElementById("recipientPolicySharingMount");if(!y)return HP(n,h);const w=()=>!h.signal?.aborted&&b===r,_=document.getElementById("recipientPolicyManagementMount");l=!0,d=!1;let R=()=>{const E=f;n.mountSharing(y,E?.inventory.manageable??[],E?.intent??tu,E?{coordinatorEnrollmentIssueCount:a,deviceInventory:s,deviceInventoryUnavailable:p,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,onTeamRenamed:()=>m({requireTeamSetupSummary:!0}),received:E.inventory.received,...u?{refreshError:!0}:{},teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d}:{loading:!0,teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d})};R();const I=Promise.resolve().then(()=>n.loadTeamSetupSummary({signal:h.signal})).then(E=>(w()&&(c=E,l=!1,d=!1,R()),!0),()=>(w()&&(l=!1,d=!0,R()),!1)),[T,A,L,F]=await Promise.allSettled([n.loadProjects({signal:h.signal}),n.loadIntent({signal:h.signal}),n.loadDeviceInventory({signal:h.signal}),n.loadSyncStatus(!1,"",{includeJoinRequests:!1,signal:h.signal})]);if(!w())return h.signal?.aborted?!1:KP(h)?(await I,!1):i??!1;const N=L.status==="rejected";L.status==="fulfilled"&&(s=L.value),F.status==="fulfilled"&&(a=mh(F.value));let j,x,U;const q=T.status==="fulfilled"&&A.status==="fulfilled";if(u=!q,p=N,q){const E=T.value,C=A.value;f={intent:C,inventory:E},j=E.manageable,x=C,U={coordinatorEnrollmentIssueCount:a,deviceInventory:s,deviceInventoryUnavailable:N,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,onTeamRenamed:()=>m({requireTeamSetupSummary:!0}),received:E.received},_&&n.mountManagement(_,E.manageable,C,{onCommitted:async()=>{await m()}})}else if(f){const E=f;j=E.inventory.manageable,x=E.intent,U={coordinatorEnrollmentIssueCount:a,deviceInventory:s,deviceInventoryUnavailable:N,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,onTeamRenamed:()=>m({requireTeamSetupSummary:!0}),received:E.inventory.received,refreshError:!0}}else j=[],x=tu,U={deviceInventoryUnavailable:N,loadError:!0};const $=()=>{n.mountSharing(y,j,x,{...U,teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d})};return $(),R=$,!q&&_&&n.mountManagement(_,[],tu,{loadError:!0}),VP({isCurrent:w,loadSucceeded:q,options:h,teamSetupSummaryPromise:I})}return m}var Dv=["info","warning","error"],Lv=["viewer","observer","capture","sync","storage","maintenance"],WP=["#health","#advanced/sync/diagnostics"],JP=100,YP=128,XP=64,QP=128,ZP=2e3,$v=256,eN=2e3,tN=2e3,nN=2048,jv=class extends Error{status;constructor(e,t){super(`Diagnostics request failed: ${e} ${t}`),this.status=e,this.name="DiagnosticEventsRequestError"}};function rN(e){const t=new URLSearchParams;return typeof e.limit=="number"&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor),e.severity?.length&&t.set("severity",e.severity.join(",")),e.subsystem?.length&&t.set("subsystem",e.subsystem.join(",")),t.set("includeTechnical",e.includeTechnical?"1":"0"),t.toString()}function Ma(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ds(e,t){return Object.keys(e).every(n=>t.includes(n))}function $n(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t}function Ov(e){return $n(e,XP)&&Number.isFinite(Date.parse(e))}function nu(e){return typeof e=="string"&&WP.includes(e)}function iN(e){return!Ma(e)||!Ds(e,["label","href","command"])||!$n(e.label,$v)||e.href!==void 0&&!nu(e.href)?!1:e.command===void 0||$n(e.command,eN)}function aN(e){return!Ma(e)||!Ds(e,["kind","label"])||!$n(e.label,$v)?!1:e.kind==="session"||e.kind==="device"||e.kind==="operation"}function oN(e){return!Ma(e)||!Ds(e,["available","text"])||typeof e.available!="boolean"?!1:e.text===void 0?!0:e.available&&$n(e.text,tN)}function sN(e){return!Ma(e)||!Ds(e,["id","occurred_at","severity","subsystem","code","message","recovery","correlation","technical_detail"])||!$n(e.id,YP)||!Ov(e.occurred_at)||!Dv.includes(e.severity)||!Lv.includes(e.subsystem)||!$n(e.code,QP)||!$n(e.message,ZP)||e.recovery!==void 0&&!iN(e.recovery)||e.correlation!==void 0&&!aN(e.correlation)?!1:e.technical_detail===void 0||oN(e.technical_detail)}function cN(e){if(!Ma(e)||e.contract_version!==1||!Array.isArray(e.items)||e.items.length>JP)return null;let t=null;if(e.next_cursor!==null){if(!$n(e.next_cursor,nN))return null;t=e.next_cursor}return e.redacted!==!0||!Ov(e.generated_at)?null:{contract_version:1,items:e.items.filter(sN),next_cursor:t,redacted:e.redacted,generated_at:e.generated_at}}async function lN(e={}){const t=rN(e),n=await fetch(`/api/diagnostics/events?${t}`,{cache:"no-store",method:"GET",signal:e.signal});if(!n.ok)throw new jv(n.status,n.statusText);const r=cN(await n.json());if(!r)throw new Error("Unsupported diagnostics response");return r}var jH=20,Mv={connection_lost:{code:"viewer_connection_lost",message:"The viewer connection was interrupted. Automatic recovery started.",severity:"warning",subsystem:"viewer"},reconnect_requested:{code:"viewer_reconnect_requested",message:"A viewer reconnection check was requested.",severity:"info",subsystem:"viewer"},connection_restored:{code:"viewer_connection_restored",message:"The viewer connection and page data were restored.",severity:"info",subsystem:"viewer"}},Ls=!1,dN=0,$s=[],ru=new Set;function iu(){return[...$s]}function au(e){if(!Object.hasOwn(Mv,e))return;const t=Mv[e];if(e==="connection_lost"&&Ls||e==="reconnect_requested"&&$s[0]?.code===t.code||e==="connection_restored"&&!Ls)return;const n=new Date().toISOString(),r={id:`viewer-session-${Date.now()}-${++dN}`,occurred_at:n,...t};$s=[r,...$s].slice(0,20),e==="connection_lost"&&(Ls=!0),e==="connection_restored"&&(Ls=!1);for(const i of ru)i(r)}function uN(e){return ru.add(e),()=>ru.delete(e)}var OH=200;function ou(){return{open:!1,severity:"",subsystem:"",includeTechnical:!1,paused:!1,rows:[],sessionRows:[],queuedSessionRows:[],queuedRows:[],queuedNextCursor:void 0,nextCursor:null,generatedAt:null,loading:!1,error:!1,announcement:"",copyStatus:"",hiddenSessionIds:[],queryRevision:0,pollRevision:0}}function su(e){return Lt([...e.sessionRows,...e.rows].filter(t=>Fv(e,t)).sort((t,n)=>Date.parse(n.occurred_at)-Date.parse(t.occurred_at)))}function Fv(e,t){return e.severity&&t.severity!==e.severity?!1:!e.subsystem||t.subsystem===e.subsystem}function pN(e){const t=e.queuedSessionRows.filter(n=>Fv(e,n));return e.queuedRows.length+t.length}function Lt(e,t=200){const n=new Set;return e.filter(r=>n.has(r.id)||n.size>=t?!1:(n.add(r.id),!0))}function fN(e,t,n){const r=t==="older"&&n;return{...e,includeTechnical:t==="technical"?!1:e.includeTechnical,nextCursor:r?null:e.nextCursor,loading:!1,error:!0,announcement:"",queryRevision:r?e.queryRevision+1:e.queryRevision}}function cu(e,t){return{...e,...t,rows:[],queuedRows:[],queuedNextCursor:void 0,nextCursor:null,generatedAt:null,loading:!1,error:!1,announcement:"",copyStatus:"",queryRevision:e.queryRevision+1}}function lu(e,t,n){return t?n?{...t,occurred_at:e.occurred_at}:t:e}function mN(e,t,n){const r=new Map(t.items.map(p=>[p.id,p])),i=new Map(e.rows.map(p=>[p.id,p])),a=t.items.filter(p=>!i.has(p.id));if(!e.rows.length)return{...e,rows:t.items.slice(0,200),queuedNextCursor:void 0,nextCursor:t.next_cursor};if(!n){const p=Lt([...t.items,...e.rows]);return{...e,rows:p,queuedRows:[],queuedNextCursor:void 0,nextCursor:t.next_cursor}}const s=t.items.filter(p=>{const f=i.get(p.id);return f!==void 0&&f.occurred_at!==p.occurred_at}),c=Lt([...a,...s]),l=new Set(c.map(p=>p.id)),d=e.rows.map(p=>lu(p,r.get(p.id),l.has(p.id))),u=Lt([...c,...e.queuedRows]);return{...e,rows:d,queuedRows:u,queuedNextCursor:t.next_cursor,announcement:u.length>0?`${u.length} new diagnostic events are waiting.`:""}}function hN(e,t){const n={...e,generatedAt:t.response.generated_at,loading:!1,error:!1,announcement:""};if(t.mode==="replace")return{...n,rows:t.response.items.slice(0,200),queuedRows:[],queuedNextCursor:void 0,nextCursor:t.response.next_cursor};if(t.mode==="older")return{...n,rows:Lt([...e.rows,...t.response.items]),queuedNextCursor:e.queuedRows.length?e.queuedNextCursor:void 0,nextCursor:t.response.next_cursor};if(t.mode==="technical"){const r=new Map(t.response.items.map(i=>[i.id,i]));return{...n,rows:e.rows.map(i=>lu(i,r.get(i.id),!0)),queuedRows:e.queuedRows.map(i=>lu(i,r.get(i.id),!0)),nextCursor:e.nextCursor}}return mN(n,t.response,t.readingOlder)}function gN(e,t){return t.type==="open"?{...ou(),open:!0,severity:t.severity,subsystem:t.subsystem,sessionRows:t.sessionRows,queryRevision:e.queryRevision+1}:t.type==="close"?ou():t.type==="set_severity"?cu(e,{severity:t.severity}):t.type==="set_subsystem"?cu(e,{subsystem:t.subsystem}):t.type==="reset_filters"?cu(e,{severity:"",subsystem:""}):t.type==="set_paused"?{...e,loading:t.paused?!1:e.loading,paused:t.paused,pollRevision:t.paused?e.pollRevision:e.pollRevision+1}:t.type==="reveal_technical"?{...e,includeTechnical:!0}:null}function vN(e,t){return t.type==="request_started"?{...e,loading:t.mode!=="poll"}:t.type==="request_succeeded"?hN(e,t):t.type==="request_failed"?fN(e,t.mode,t.restartQuery):null}function Bv(e,t,n=!1){if(e.paused||!e.open)return e;const r=t.filter(s=>!e.hiddenSessionIds.includes(s.id));if(!n)return{...e,sessionRows:Lt([...r,...e.queuedSessionRows,...e.sessionRows],20),queuedSessionRows:[]};const i=new Set(e.sessionRows.map(s=>s.id)),a=Lt([...r.filter(s=>!i.has(s.id)),...e.queuedSessionRows],20);return{...e,queuedSessionRows:a}}function yN(e,t){if(t.type==="session_event_recorded")return Bv(e,[t.event],t.readingOlder);if(t.type==="refresh_session_rows")return Bv(e,t.events,t.readingOlder);if(t.type==="clear_view"){const n=[...new Set([...t.sessionEvents.map(r=>r.id),...e.queuedSessionRows.map(r=>r.id),...e.sessionRows.map(r=>r.id),...e.hiddenSessionIds])].slice(0,20);return{...e,rows:[],sessionRows:[],queuedSessionRows:[],queuedRows:[],queuedNextCursor:void 0,nextCursor:null,generatedAt:null,loading:!1,error:!1,announcement:"Diagnostics view cleared.",copyStatus:"",hiddenSessionIds:n}}return t.type==="set_copy_status"?{...e,copyStatus:t.status}:t.type!=="show_queued"?null:bN(e)}function bN(e){const t=Lt([...e.queuedRows,...e.rows],201),n=t.length>200,r=e.queuedNextCursor;return{...e,rows:t.slice(0,200),sessionRows:Lt([...e.queuedSessionRows,...e.sessionRows],20),queuedSessionRows:[],queuedRows:[],queuedNextCursor:void 0,nextCursor:n&&r!==void 0?r:e.nextCursor,announcement:""}}function _N(e,t){const n=gN(e,t);if(n)return n;const r=vN(e,t);return r||(yN(e,t)??e)}var wN=Math.ceil(200/50);async function SN(e){const t=new Map(e.existingRows.map(a=>[a.id,a.occurred_at]));let n=e.request,r=null,i=0;for(;;){const a=await e.loadEvents(n);i+=1;const s=Lt([...r?.items??[],...a.items]);r={...a,items:s};const c=a.items.some(l=>t.get(l.id)===l.occurred_at);if(t.size===0||c){const l=Lt([...s,...e.existingRows],201),d=c&&l.length<=200;return{...r,next_cursor:d?e.existingNextCursor:a.next_cursor}}if(!a.next_cursor||s.length>=200||i>=wN)return r;n={...e.request,cursor:a.next_cursor,limit:Math.min(50,200-s.length)}}}async function CN(e){const t=new Set(e.existingRows.map(a=>a.id));let n=e.request,r=null,i=0;for(;;){const a=await e.loadEvents(n);i+=1;const s=Lt([...r?.items??[],...a.items]);r={...a,items:s};const c=new Set(s.map(l=>l.id));if([...t].every(l=>c.has(l)))return r;if(!a.next_cursor||s.length>=200||i*50>=200)throw new Error("Technical diagnostic history could not be refreshed completely.");n={...e.request,cursor:a.next_cursor,limit:Math.min(50,200-s.length)}}}function RN(e,t,n){const r=200-su(t).length;return{limit:e==="older"?Math.max(1,Math.min(50,r)):50,cursor:e==="older"?t.nextCursor??void 0:void 0,severity:t.severity?[t.severity]:void 0,subsystem:t.subsystem?[t.subsystem]:void 0,includeTechnical:t.includeTechnical,signal:n}}function IN(e,t,n,r){const i=RN(t,n,r);return t==="technical"?CN({loadEvents:e,request:i,existingRows:Lt([...n.queuedRows,...n.rows],n.queuedRows.length+n.rows.length)}):t!=="poll"?e(i):SN({loadEvents:e,request:i,existingRows:n.rows,existingNextCursor:n.nextCursor})}function kN(e,t){return e==="older"&&t instanceof jv&&t.status===400}function du(e){return e.current!==null&&e.current.scrollTop>24}function TN(e){return e instanceof DOMException&&e.name==="AbortError"}var PN=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function qv(e){if(!e?.isConnected||!e.matches(PN)||e.matches(':disabled, [aria-disabled="true"]'))return!1;let t=e;for(;t;){if(t.hidden||t.inert||t.hasAttribute("inert")||t.getAttribute("aria-hidden")==="true")return!1;const n=getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden"||n.visibility==="collapse"||n.opacity==="0")return!1;t=t.parentElement}return!0}function NN(){const e=document.querySelector('.tab-btn[aria-current="page"]');return qv(e)?e:null}function EN(e){const t=e==="#health"?"health":"advanced";return document.getElementById(`tabBtn-${t}`)}function AN(e,t,n){if(e.preventDefault(),n.current){n.current=!1,t.current=null;return}const r=t.current;qv(r)?r.focus():NN()?.focus(),t.current=null}function xN(e){const{dispatch:t,abortRequest:n,openerRef:r,recoveryNavigationRef:i}=e;return{open(a={}){n(),i.current=!1,r.current=a.trigger??document.activeElement,t({type:"open",severity:a.severity??"",subsystem:a.subsystem??"",sessionRows:iu()})},close(){n(),t({type:"close"})},navigateToRecovery(a){n(),i.current=!0,t({type:"close"}),queueMicrotask(()=>{window.location.hash=a,setTimeout(()=>EN(a)?.focus(),0)})},restoreFocus(a){AN(a,r,i)}}}function DN(e){const{state:t,dispatch:n,abortRequest:r}=e;return{setSeverity(i){r(),n({type:"set_severity",severity:i})},setSubsystem(i){r(),n({type:"set_subsystem",subsystem:i})},resetFilters(){r(),n({type:"reset_filters"})},togglePaused(){t.paused||r(),n({type:"set_paused",paused:!t.paused})},revealTechnical(){r(),n({type:"reveal_technical"})}}}async function LN(e,t){if(!globalThis.confirm("Copied diagnostics may contain sensitive operational context. Copy the visible redacted events?"))return;const n=ON(su(e));try{await navigator.clipboard.writeText(n),t({type:"set_copy_status",status:"Visible redacted events copied."})}catch{t({type:"set_copy_status",status:"Visible events could not be copied. Check clipboard permission and try again."})}}function $N(e){const{state:t,dispatch:n,abortRequest:r,listRef:i}=e;return{showQueued(){n({type:"show_queued"}),i.current&&(i.current.scrollTop=0)},clearView(){r(),n({type:"clear_view",sessionEvents:iu()})},copyVisibleEvents:()=>LN(t,n)}}function jN(e){return{...xN(e),refresh:()=>e.runRequest("poll"),retry:()=>e.runRequest(e.state.rows.length>0?"poll":"replace","retry"),loadOlder:()=>e.runRequest("older"),...DN(e),...$N(e)}}function ON(e){return JSON.stringify(e.map(t=>{const n=nu(t.recovery?.href)||!!t.recovery?.command;return{occurred_at:t.occurred_at,severity:t.severity,subsystem:t.subsystem,code:t.code,message:t.message,...n?{recovery_label:t.recovery?.label}:{},...t.correlation?.label?{correlation_label:t.correlation.label}:{}}}),null,2)}function MN(e){const t=B(e),n=B(null),r=B(0);return t.current=e,{stateRef:t,requestRef:n,generationRef:r}}function FN(e,t){const n=B(t);n.current=t,V(()=>{e.open&&n.current("replace")},[e.open,e.queryRevision]),V(()=>{!e.open||e.pollRevision===0||n.current("poll")},[e.open,e.pollRevision]),V(()=>{!e.open||!e.includeTechnical||n.current("technical")},[e.includeTechnical,e.open])}function BN(e){const{state:t,dispatch:n,loadEvents:r,listRef:i}=e,{stateRef:a,requestRef:s,generationRef:c}=MN(t);function l(){c.current+=1,s.current?.controller.abort(),s.current=null}function d(p,f){const m=a.current;return m.open?p!=="poll"?!1:s.current!==null?!0:f==="retry"?!1:m.paused||document.visibilityState==="hidden":!0}async function u(p,f="routine"){if(d(p,f))return;n({type:"refresh_session_rows",events:iu(),readingOlder:du(i)});const m=new AbortController;s.current?.controller.abort();const v=++c.current;s.current={controller:m,generation:v},n({type:"request_started",mode:p});try{const b=a.current,h=await IN(r,p,b,m.signal);if(v!==c.current)return;n({type:"request_succeeded",mode:p,response:h,readingOlder:du(i)})}catch(b){if(v!==c.current||TN(b))return;n({type:"request_failed",mode:p,restartQuery:kN(p,b)})}finally{v===c.current&&(s.current=null)}}return FN(t,u),{abortRequest:l,runRequest:u}}function qN(e){const[t,n]=Nn(_N,ou()),r=B(null),i=B(!1),a=B(null),{abortRequest:s,runRequest:c}=BN({state:t,dispatch:n,loadEvents:e,listRef:a});V(()=>uN(d=>{n({type:"session_event_recorded",event:d,readingOlder:du(a)})}),[]);const l=jN({state:t,dispatch:n,abortRequest:s,runRequest:c,openerRef:r,recoveryNavigationRef:i,listRef:a});return{state:t,visibleRows:su(t),listRef:a,...l}}function uu(e){return e==="error"?{icon:"×",label:"Error"}:e==="warning"?{icon:"!",label:"Warning"}:{icon:"i",label:"Info"}}function UN({event:e,includeTechnical:t,onRecoveryNavigation:n}){const r=uu(e.severity),i=e.recovery?.href;return o("li",{className:`diagnostics-event diagnostics-event--${e.severity}`,children:[o("div",{className:"diagnostics-event-heading",children:[o("span",{className:"diagnostics-severity",children:[o("span",{"aria-hidden":"true",className:"diagnostics-severity-icon",children:r.icon}),r.label]}),o("time",{dateTime:e.occurred_at,children:new Date(e.occurred_at).toLocaleString()})]}),o("div",{className:"diagnostics-event-context",children:[o("span",{children:e.subsystem}),o("code",{children:e.code})]}),o("p",{children:e.message}),e.correlation?o("div",{className:"diagnostics-event-meta",children:[e.correlation.kind,": ",e.correlation.label]}):null,t&&e.technical_detail?.text?o("details",{className:"diagnostics-technical-detail",children:[o("summary",{children:"Technical detail"}),o("pre",{children:e.technical_detail.text})]}):null,nu(i)?o("a",{className:"diagnostics-recovery",href:i,onClick:a=>{a.preventDefault(),n(i)},children:e.recovery?.label}):null,e.recovery?.command?o("div",{className:"diagnostics-recovery-command",children:[o("span",{children:e.recovery.label}),o("code",{children:e.recovery.command})]}):null]})}function GN(){return o("div",{"aria-busy":"true","aria-label":"Loading diagnostics",className:"diagnostics-loading",role:"status",children:["first","second","third"].map(e=>o("div",{className:"diagnostics-loading-row",children:[o("span",{}),o("span",{}),o("span",{})]},e))})}function HN({controller:e}){const{state:t}=e;return o(z,{children:[o("div",{className:"diagnostics-controls",children:[o("label",{children:[o("span",{children:"Severity"}),o("select",{"aria-label":"Diagnostic severity",onChange:n=>e.setSeverity(n.currentTarget.value),value:t.severity,children:[o("option",{value:"",children:"All severities"}),Dv.map(n=>o("option",{value:n,children:uu(n).label},n))]})]}),o("label",{children:[o("span",{children:"Subsystem"}),o("select",{"aria-label":"Diagnostic subsystem",onChange:n=>e.setSubsystem(n.currentTarget.value),value:t.subsystem,children:[o("option",{value:"",children:"All subsystems"}),Lv.map(n=>o("option",{value:n,children:n},n))]})]}),o("button",{className:"settings-button",onClick:e.togglePaused,type:"button",children:t.paused?"Resume updates":"Pause updates"})]}),o("div",{className:"diagnostics-secondary-controls",children:[o("div",{className:"diagnostics-secondary-actions",children:[o("button",{className:"settings-button",disabled:t.includeTechnical||t.loading,onClick:e.revealTechnical,type:"button",children:t.includeTechnical?"Technical details shown":"Reveal technical details"}),o("button",{className:"settings-button",onClick:e.clearView,type:"button",children:"Clear view"}),o("button",{className:"settings-button",disabled:!e.visibleRows.length,onClick:()=>{e.copyVisibleEvents()},type:"button",children:"Copy visible redacted events"})]}),o("span",{className:"diagnostics-generated-at",children:t.generatedAt?`Generated ${new Date(t.generatedAt).toLocaleTimeString()}`:"Not loaded yet"})]})]})}function VN({controller:e}){const{state:t}=e,n=pN(t),r=t.error&&t.rows.length?"Showing stale events.":"";return o(z,{children:[o("div",{"aria-atomic":"true","aria-live":"polite",className:"sr-only",children:t.announcement}),o("div",{"aria-atomic":"true","aria-live":"polite",className:"diagnostics-copy-status",children:t.copyStatus}),t.subsystem||t.severity?o("div",{className:"diagnostics-filter-context",children:["Showing"," ",t.severity?`${uu(t.severity).label.toLowerCase()} `:"",t.subsystem?`${t.subsystem} `:"","events from the recent retained window."]}):null,t.paused?o("div",{className:"diagnostics-notice",role:"status",children:"Updates are paused. Resume when you are ready to fetch newer events."}):null,t.error?o("div",{className:"diagnostics-notice diagnostics-notice--error",role:"alert",children:[o("span",{children:["Diagnostics could not be refreshed. ",r]}),o("button",{className:"settings-button",onClick:()=>{e.retry()},type:"button",children:"Retry"})]}):null,n?o("button",{className:"diagnostics-new-events",onClick:e.showQueued,type:"button",children:["Show ",n," new ",n===1?"event":"events"]}):null]})}function KN({controller:e}){const{state:t}=e,n=e.visibleRows,r=!!(t.severity||t.subsystem),i=!!t.nextCursor&&n.length<200&&!t.loading;return o("div",{className:"diagnostics-event-list",ref:e.listRef,children:[t.loading&&!n.length?o(GN,{}):null,!t.loading&&!t.error&&!n.length?o("div",{className:"diagnostics-empty",children:[o("p",{children:"No events match the recent retained window."}),r?o("button",{className:"settings-button",onClick:e.resetFilters,type:"button",children:"Reset filters"}):null]}):null,n.length?o("ul",{"aria-label":"Diagnostic events",children:n.map(a=>o(UN,{event:a,includeTechnical:t.includeTechnical,onRecoveryNavigation:e.navigateToRecovery},a.id))}):null,i?o("button",{className:"settings-button diagnostics-load-older",onClick:()=>{e.loadOlder()},type:"button",children:"Load older"}):null,n.length>=200?o("div",{className:"diagnostics-limit-note",children:["Showing the newest ",200," events."]}):null]})}function zN({controller:e}){return o(Ln,{ariaDescribedby:"diagnosticsDrawerDescription",ariaLabelledby:"diagnosticsDrawerTitle",contentClassName:"diagnostics-drawer",contentId:"diagnosticsDrawer",onCloseAutoFocus:e.restoreFocus,onOpenAutoFocus:t=>{t.preventDefault(),document.getElementById("diagnosticsDrawerTitle")?.focus()},onOpenChange:t=>{t||e.close()},open:e.state.open,overlayClassName:"diagnostics-drawer-overlay",overlayId:"diagnosticsDrawerOverlay",children:[o("header",{className:"diagnostics-drawer-header",children:[o("div",{children:[o(zd,{id:"diagnosticsDrawerTitle",tabIndex:-1,children:"Diagnostics"}),o("p",{id:"diagnosticsDrawerDescription",children:"Recent redacted operational events. Filters apply only to this drawer."})]}),o(Lr,{ariaLabel:"Close diagnostics",onClick:e.close})]}),o(HN,{controller:e}),o(VN,{controller:e}),o(KN,{controller:e})]})}var Mi=null;function WN({dependencies:e}){const t=qN(e.loadEvents??lN);return V(()=>{const n={open:t.open,refresh:t.refresh,close:t.close};return Mi=n,()=>{Mi===n&&(Mi=null)}},[t.open,t.refresh,t.close]),o(zN,{controller:t})}function JN(e,t={}){Ue(o(WN,{dependencies:t}),e)}function Fr(e={}){Mi?.open(e)}function Uv(e){Mi?.close(),e&&queueMicrotask(e)}async function YN(){await Mi?.refresh()}function XN(){document.getElementById("healthOpenDiagnostics")?.addEventListener("click",e=>{Fr({trigger:e.currentTarget})}),document.getElementById("syncOpenDiagnostics")?.addEventListener("click",e=>{Fr({subsystem:"sync",trigger:e.currentTarget})}),document.getElementById("viewerReconnectDiagnostics")?.addEventListener("click",e=>{Fr({subsystem:"viewer",trigger:e.currentTarget})})}var Gv=null,Hv=null;function QN(e,t){t.current=document.activeElement instanceof HTMLElement?document.activeElement:null;const n=document.getElementById("legacyUpgradeReviewGroups");n&&(e.preventDefault(),n.focus())}function ZN(e,t){e.preventDefault(),t.current?.isConnected&&t.current.focus(),t.current=null}function eE({actions:e}){const[t,n]=D(null),r=B(null);Gv=n,Hv=()=>n(null);const i=()=>{e.onDismiss(),n(null)},a=l=>{e.onDismiss(),n(null),l()},s=t?.groupCount===1?"project needs":"projects need",c=t?`${t.groupCount.toLocaleString()} older ${s} a Sharing domain. They contain ${t.memoryCount.toLocaleString()} older shared memories total; you will review the projects, not individual memories.`:null;return o(Ln,{ariaDescribedby:"legacyUpgradeDescription legacyUpgradeSummary",ariaLabelledby:"legacyUpgradeTitle",contentClassName:"modal legacy-upgrade-modal",contentId:"legacyUpgradeModal",onCloseAutoFocus:l=>ZN(l,r),onInteractOutside:l=>l.preventDefault(),onOpenAutoFocus:l=>QN(l,r),onOpenChange:l=>{l||i()},open:t!=null,overlayClassName:"modal-backdrop",overlayId:"legacyUpgradeModalBackdrop",children:o("div",{className:"modal-card",children:[o("div",{className:"modal-header",children:o(zd,{id:"legacyUpgradeTitle",children:"Choose where older shared memories belong"})}),o("div",{className:"modal-body",children:[o("div",{className:"small",id:"legacyUpgradeDescription",children:"Some memories were shared before codemem had clear Sharing domains. We kept them out of normal sync until you choose which project/domain they belong to."}),o("div",{className:"legacy-upgrade-summary",id:"legacyUpgradeSummary",children:c}),o("div",{className:"small",children:"You’ll review projects, not individual memories. Nothing moves automatically, and this will not erase copies another device may already have received."}),o("label",{className:"field-checkbox",htmlFor:"legacyUpgradeDontShow",children:[o("input",{className:"cm-checkbox",id:"legacyUpgradeDontShow",type:"checkbox"}),o("span",{children:"Don’t show this again"})]})]}),o("div",{className:"modal-footer",children:o("div",{className:"legacy-upgrade-actions",children:[o("button",{className:"settings-button",id:"legacyUpgradeReviewProjects",onClick:()=>a(e.onReviewProjects),type:"button",children:"Manage all projects"}),o("button",{className:"settings-button",id:"legacyUpgradeNotNow",onClick:i,type:"button",children:"Not now"}),o("button",{className:"settings-save",id:"legacyUpgradeReviewGroups",onClick:()=>a(e.onReviewGroups),type:"button",children:"Start review"})]})})]})})}function tE(e,t){Ue(o(eE,{actions:t}),e)}function nE(e){Gv?.(e)}function rE(){Hv?.()}var iE=Symbol.for("preact-signals");function js(){if(jn>1)jn--;else{var e,t=!1;for((function(){var i=Fs;for(Fs=void 0;i!==void 0;){var a=i.S;if(a.v===i.v)for(var s=a.t;s!==void 0;s=s.x)s.i===i.i&&(s.i=a.i);i=i.o}})();Ba!==void 0;){var n=Ba;for(Ba=void 0,Ms++;n!==void 0;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&Kv(n))try{n.c()}catch(i){t||(e=i,t=!0)}n=r}}if(Ms=0,jn--,t)throw e}}function aE(e){if(jn>0)return e();pu=++oE,jn++;try{return e()}finally{js()}}var Fa,Ve=void 0;function Os(e){var t=Ve,n=Fa;Ve=void 0,Fa=void 0;try{return e()}finally{Ve=t,Fa=n}}var Ba=void 0,jn=0,Ms=0,oE=0,pu=0,Fs=void 0,Bs=0;function Vv(e){if(Ve!==void 0){var t=e.n;if(t===void 0||t.t!==Ve)return t={i:0,S:e,p:Ve.s,n:void 0,t:Ve,e:void 0,x:void 0,r:t},Ve.s!==void 0&&(Ve.s.n=t),Ve.s=t,e.n=t,32&Ve.f&&e.S(t),t;if(t.i===-1)return t.i=0,t.n!==void 0&&(t.n.p=t.p,t.p!==void 0&&(t.p.n=t.n),t.p=Ve.s,t.n=void 0,Ve.s.n=t,Ve.s=t),t}}function pt(e,t){this.v=e,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=t?.watched,this.Z=t?.unwatched,this.name=t?.name}pt.prototype.brand=iE,pt.prototype.h=function(){return!0},pt.prototype.S=function(e){var t=this,n=this.t;n!==e&&e.e===void 0&&(e.x=n,this.t=e,n!==void 0?n.e=e:Os(function(){var r;(r=t.W)==null||r.call(t)}))},pt.prototype.U=function(e){var t=this;if(this.t!==void 0){var n=e.e,r=e.x;n!==void 0&&(n.x=r,e.e=void 0),r!==void 0&&(r.e=n,e.x=void 0),e===this.t&&(this.t=r,r===void 0&&Os(function(){var i;(i=t.Z)==null||i.call(t)}))}},pt.prototype.subscribe=function(e){var t=this;return qa(function(){var n=t.value;Os(function(){return e(n)})},{name:"sub"})},pt.prototype.valueOf=function(){return this.value},pt.prototype.toString=function(){return this.value+""},pt.prototype.toJSON=function(){return this.value},pt.prototype.peek=function(){var e=this;return Os(function(){return e.value})},Object.defineProperty(pt.prototype,"value",{get:function(){var e=Vv(this);return e!==void 0&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(Ms>100)throw new Error("Cycle detected");(function(n){jn!==0&&Ms===0&&n.l!==pu&&(n.l=pu,Fs={S:n,v:n.v,i:n.i,o:Fs})})(this),this.v=e,this.i++,Bs++,jn++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{js()}}}});function qs(e,t){return new pt(e,t)}function Kv(e){for(var t=e.s;t!==void 0;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function zv(e){for(var t=e.s;t!==void 0;t=t.n){var n=t.S.n;if(n!==void 0&&(t.r=n),t.S.n=t,t.i=-1,t.n===void 0){e.s=t;break}}}function Wv(e){for(var t=e.s,n=void 0;t!==void 0;){var r=t.p;t.i===-1?(t.S.U(t),r!==void 0&&(r.n=t.n),t.n!==void 0&&(t.n.p=r)):n=t,t.S.n=t.r,t.r!==void 0&&(t.r=void 0),t=r}e.s=n}function Br(e,t){pt.call(this,void 0,t),this.x=e,this.s=void 0,this.g=Bs-1,this.f=4}Br.prototype=new pt,Br.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Bs))return!0;if(this.g=Bs,this.f|=1,this.i>0&&!Kv(this))return this.f&=-2,!0;var e=Ve;try{zv(this),Ve=this;var t=this.x();(16&this.f||this.v!==t||this.i===0)&&(this.v=t,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return Ve=e,Wv(this),this.f&=-2,!0},Br.prototype.S=function(e){if(this.t===void 0){this.f|=36;for(var t=this.s;t!==void 0;t=t.n)t.S.S(t)}pt.prototype.S.call(this,e)},Br.prototype.U=function(e){if(this.t!==void 0&&(pt.prototype.U.call(this,e),this.t===void 0)){this.f&=-33;for(var t=this.s;t!==void 0;t=t.n)t.S.U(t)}},Br.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var e=this.t;e!==void 0;e=e.x)e.t.N()}},Object.defineProperty(Br.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var e=Vv(this);if(this.h(),e!==void 0&&(e.i=this.i),16&this.f)throw this.v;return this.v}});function Jv(e,t){return new Br(e,t)}function Yv(e){var t=e.m;if(e.m=void 0,typeof t=="function"){jn++;var n=Ve;Ve=void 0;try{t()}catch(r){throw e.f&=-2,e.f|=8,fu(e),r}finally{Ve=n,js()}}}function fu(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,Yv(e)}function sE(e){if(Ve!==this)throw new Error("Out-of-order effect");Wv(this),Ve=e,this.f&=-2,8&this.f&&fu(this),js()}function Fi(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=t?.name,Fa&&Fa.push(this)}Fi.prototype.c=function(){var e=this.S();try{if(8&this.f||this.x===void 0)return;var t=this.x();typeof t=="function"&&(this.m=t)}finally{e()}},Fi.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,Yv(this),zv(this),jn++;var e=Ve;return Ve=this,sE.bind(this,e)},Fi.prototype.N=function(){2&this.f||(this.f|=2,this.u=Ba,Ba=this)},Fi.prototype.d=function(){this.f|=8,1&this.f||fu(this)},Fi.prototype.dispose=function(){this.d()};function qa(e,t){var n=new Fi(e,t);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var Xv,mu,Us,cE=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,Qv=[];qa(function(){Xv=this.N})();function Bi(e,t){pe[e]=t.bind(null,pe[e]||function(){})}function Gs(e){if(Us){var t=Us;Us=void 0,t()}Us=e&&e.S()}function Zv(e){var t=this,n=e.data,r=dE(n);r.name="ReactiveDom",r.value=n;var i=Ie(function(){for(var c=t,l=t.__v;l=l.__;)if(l.__c){l.__c.__$f|=4;break}var d=Jv(function(){var m=r.value.value;return m===0?0:m===!0?"":m||""}),u=Jv(function(){return!Array.isArray(d.value)&&!gh(d.value)}),p=qa(function(){if(this.N=ey,u.value){var m=d.value;c.__v&&c.__v.__e&&c.__v.__e.nodeType===3&&(c.__v.__e.data=m)}}),f=t.__$u.d;return t.__$u.d=function(){p(),f.call(this)},[u,d]},[]),a=i[0],s=i[1];return a.value?s.peek():s.value}Zv.displayName="ReactiveTextNode",Object.defineProperties(pt.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Zv},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}}),Bi("__b",function(e,t){if(typeof t.type=="string"){var n,r=t.props;for(var i in r)if(i!=="children"){var a=r[i];a instanceof pt&&(n||(t.__np=n={}),n[i]=a,r[i]=a.peek())}}e(t)}),Bi("__r",function(e,t){if(e(t),t.type!==z){Gs();var n,r=t.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,a){var s;return qa(function(){s=this},{name:a}),s.c=i,s})((function(i){return function(){var a;cE&&((a=this.y)==null||a.call(this)),i.__$f|=1,i.setState({})}})(r),typeof t.type=="function"?t.type.displayName||t.type.name:""))),mu=r,Gs(n)}}),Bi("__e",function(e,t,n,r){Gs(),mu=void 0,e(t,n,r)}),Bi("diffed",function(e,t){Gs(),mu=void 0;var n;if(typeof t.type=="string"&&(n=t.__e)){var r=t.__np,i=t.props,a=n.U;if(a)for(var s in a){var c=a[s];c===void 0||r&&s in r||(c.d(),a[s]=void 0)}if(r){a||(a={},n.U=a);for(var l in r){var d=a[l],u=r[l];d===void 0?(d=lE(n,l,u,i),a[l]=d):d.o(u,i)}}}e(t)});function lE(e,t,n,r){var i=t in e&&e.ownerSVGElement===void 0,a=qs(n);return{o:function(s,c){a.value=s,r=c},d:qa(function(){this.N=ey;var s=a.value.value;r[t]!==s&&(r[t]=s,i?e[t]=s:s!=null&&(s!==!1||t[4]==="-")?e.setAttribute(t,s):e.removeAttribute(t))})}}Bi("unmount",function(e,t){if(typeof t.type=="string"){var n=t.__e;if(n){var r=n.U;if(r){n.U=void 0;for(var i in r){var a=r[i];a&&a.d()}}}var s=t.__np;if(s){var c=t.props;for(var l in s)c[l]=s[l]}t.__np=void 0}else{var d=t.__c;if(d){var u=d.__$u;u&&(d.__$u=void 0,u.d())}}e(t)}),Bi("__h",function(e,t,n,r){r<3&&(t.__$f|=2),e(t,n,r)}),qt.prototype.shouldComponentUpdate=function(e,t){if(this.__R)return!0;var n=this.__$u,r=n&&n.s!==void 0;for(var i in t)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var a=2&this.__$f;if(!(r||a||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var s in e)if(s!=="__source"&&e[s]!==this.props[s])return!0;for(var c in this.props)if(!(c in e))return!0;return!1};function dE(e,t){return Ie(function(){return qs(e,t)},[])}var uE=function(e){queueMicrotask(function(){queueMicrotask(e)})};function pE(){aE(function(){for(var e;e=Qv.shift();)Xv.call(e)})}function ey(){Qv.push(this)===1&&(pe.requestAnimationFrame||uE)(pE)}var fE=Object.defineProperty,ot=(e,t)=>fE(e,"name",{value:t,configurable:!0});function Ua(e){const t=e+"CollectionProvider",[n,r]=dt(t),[i,a]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=ot(b=>{const{scope:h,children:y}=b,w=B(null),_=B(new Map).current;return o(i,{scope:h,itemMap:_,collectionRef:w,children:y})},"CollectionProvider");s.displayName=t;const c=e+"CollectionSlot",l=dn(c),d=W((b,h)=>{const{scope:y,children:w}=b,_=a(c,y),R=Se(h,_.collectionRef);return o(l,{ref:R,children:w})});d.displayName=c;const u=e+"CollectionItemSlot",p="data-radix-collection-item",f=dn(u),m=W((b,h)=>{const{scope:y,children:w,..._}=b,R=B(null),I=Se(h,R),T=a(u,y);return V(()=>(T.itemMap.set(R,{ref:R,..._}),()=>{T.itemMap.delete(R)})),o(f,{[p]:"",ref:I,children:w})});m.displayName=u;function v(b){const h=a(e+"CollectionConsumer",b);return oe(()=>{const y=h.collectionRef.current;if(!y)return[];const w=Array.from(y.querySelectorAll(`[${p}]`));return Array.from(h.itemMap.values()).sort((_,R)=>w.indexOf(_.ref.current)-w.indexOf(R.ref.current))},[h.collectionRef,h.itemMap])}return ot(v,"useCollection"),[{Provider:s,Slot:d,ItemSlot:m},v,r]}ot(Ua,"createCollection");var ty=new WeakMap,hu=class Pr extends Map{static{ot(this,"OrderedDict")}#e;constructor(t){super(t),this.#e=[...super.keys()],ty.set(this,!0)}set(t,n){return ty.get(this)&&(this.has(t)?this.#e[this.#e.indexOf(t)]=t:this.#e.push(t)),super.set(t,n),this}insert(t,n,r){const i=this.has(n),a=this.#e.length,s=gu(t);let c=s>=0?s:a+s;const l=c<0||c>=a?-1:c;if(l===this.size||i&&l===this.size-1||l===-1)return this.set(n,r),this;const d=this.size+(i?0:1);s<0&&c++;const u=[...this.#e];let p,f=!1;for(let m=c;m<d;m++)if(c===m){let v=u[m];u[m]===n&&(v=u[m+1]),i&&this.delete(n),p=this.get(v),this.set(n,r)}else{!f&&u[m-1]===n&&(f=!0);const v=u[f?m:m-1],b=p;p=this.get(v),this.delete(v),this.set(v,b)}return this}with(t,n,r){const i=new Pr(this);return i.insert(t,n,r),i}before(t){const n=this.#e.indexOf(t)-1;if(!(n<0))return this.entryAt(n)}setBefore(t,n,r){const i=this.#e.indexOf(t);return i===-1?this:this.insert(i,n,r)}after(t){let n=this.#e.indexOf(t);if(n=n===-1||n===this.size-1?-1:n+1,n!==-1)return this.entryAt(n)}setAfter(t,n,r){const i=this.#e.indexOf(t);return i===-1?this:this.insert(i+1,n,r)}first(){return this.entryAt(0)}last(){return this.entryAt(-1)}clear(){return this.#e=[],super.clear()}delete(t){const n=super.delete(t);return n&&this.#e.splice(this.#e.indexOf(t),1),n}deleteAt(t){const n=this.keyAt(t);return n!==void 0?this.delete(n):!1}at(t){const n=Hs(this.#e,t);if(n!==void 0)return this.get(n)}entryAt(t){const n=Hs(this.#e,t);if(n!==void 0)return[n,this.get(n)]}indexOf(t){return this.#e.indexOf(t)}keyAt(t){return Hs(this.#e,t)}from(t,n){const r=this.indexOf(t);if(r===-1)return;let i=r+n;return i<0&&(i=0),i>=this.size&&(i=this.size-1),this.at(i)}keyFrom(t,n){const r=this.indexOf(t);if(r===-1)return;let i=r+n;return i<0&&(i=0),i>=this.size&&(i=this.size-1),this.keyAt(i)}find(t,n){let r=0;for(const i of this){if(Reflect.apply(t,n,[i,r,this]))return i;r++}}findIndex(t,n){let r=0;for(const i of this){if(Reflect.apply(t,n,[i,r,this]))return r;r++}return-1}filter(t,n){const r=[];let i=0;for(const a of this)Reflect.apply(t,n,[a,i,this])&&r.push(a),i++;return new Pr(r)}map(t,n){const r=[];let i=0;for(const a of this)r.push([a[0],Reflect.apply(t,n,[a,i,this])]),i++;return new Pr(r)}reduce(...t){const[n,r]=t;let i=0,a=r??this.at(0);for(const s of this)i===0&&t.length===1?a=s:a=Reflect.apply(n,this,[a,s,i,this]),i++;return a}reduceRight(...t){const[n,r]=t;let i=r??this.at(-1);for(let a=this.size-1;a>=0;a--){const s=this.at(a);a===this.size-1&&t.length===1?i=s:i=Reflect.apply(n,this,[i,s,a,this])}return i}toSorted(t){const n=[...this.entries()].sort(t);return new Pr(n)}toReversed(){const t=new Pr;for(let n=this.size-1;n>=0;n--){const r=this.keyAt(n),i=this.get(r);t.set(r,i)}return t}toSpliced(...t){const n=[...this.entries()];return n.splice(...t),new Pr(n)}slice(t,n){const r=new Pr;let i=this.size-1;if(t===void 0)return r;t<0&&(t=t+this.size),n!==void 0&&n>0&&(i=n-1);for(let a=t;a<=i;a++){const s=this.keyAt(a),c=this.get(s);r.set(s,c)}return r}every(t,n){let r=0;for(const i of this){if(!Reflect.apply(t,n,[i,r,this]))return!1;r++}return!0}some(t,n){let r=0;for(const i of this){if(Reflect.apply(t,n,[i,r,this]))return!0;r++}return!1}};function Hs(e,t){if("at"in Array.prototype)return Array.prototype.at.call(e,t);const n=ny(e,t);return n===-1?void 0:e[n]}ot(Hs,"at");function ny(e,t){const n=e.length,r=gu(t),i=r>=0?r:n+r;return i<0||i>=n?-1:i}ot(ny,"toSafeIndex");function gu(e){return e!==e||e===0?0:Math.trunc(e)}ot(gu,"toSafeInteger");function mE(e){const t=e+"CollectionProvider",[n,r]=dt(t),[i,a]=n(t,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new hu,setItemMap:ot(()=>{},"setItemMap")}),s=ot(({state:w,..._})=>w?o(l,{..._,state:w}):o(c,{..._}),"CollectionProvider");s.displayName=t;const c=ot(w=>{const _=h();return o(l,{...w,state:_})},"CollectionInit");c.displayName=t+"Init";const l=ot(w=>{const{scope:_,children:R,state:I}=w,T=B(null),[A,L]=D(null),F=Se(T,L),[N,j]=I;return V(()=>{if(!A)return;const x=ay(()=>{});return x.observe(A,{childList:!0,subtree:!0}),()=>{x.disconnect()}},[A]),o(i,{scope:_,itemMap:N,setItemMap:j,collectionRef:F,collectionRefObject:T,collectionElement:A,children:R})},"CollectionProviderImpl");l.displayName=t+"Impl";const d=e+"CollectionSlot",u=dn(d),p=W((w,_)=>{const{scope:R,children:I}=w,T=a(d,R),A=Se(_,T.collectionRef);return o(u,{ref:A,children:I})});p.displayName=d;const f=e+"CollectionItemSlot",m="data-radix-collection-item",v=dn(f),b=W((w,_)=>{const{scope:R,children:I,...T}=w,A=B(null),[L,F]=D(null),N=Se(_,A,F),{setItemMap:j}=a(f,R),x=B(T);ry(x.current,T)||(x.current=T);const U=x.current;return V(()=>{const q=U;return j($=>L?$.has(L)?$.set(L,{...q,element:L}).toSorted(vu):($.set(L,{...q,element:L}),$.toSorted(vu)):$),()=>{j($=>!L||!$.has(L)?$:($.delete(L),new hu($)))}},[L,U,j]),o(v,{[m]:"",ref:N,children:I})});b.displayName=f;function h(){return D(new hu)}ot(h,"useInitCollection");function y(w){const{itemMap:_}=a(e+"CollectionConsumer",w);return _}return ot(y,"useCollection"),[{Provider:s,Slot:p,ItemSlot:b},{createCollectionScope:r,useCollection:y,useInitCollection:h}]}ot(mE,"createCollection");function ry(e,t){if(e===t)return!0;if(typeof e!="object"||typeof t!="object"||e==null||t==null)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const i of n)if(!Object.prototype.hasOwnProperty.call(t,i)||e[i]!==t[i])return!1;return!0}ot(ry,"shallowEqual");function iy(e,t){return!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_PRECEDING)}ot(iy,"isElementPreceding");function vu(e,t){return!e[1].element||!t[1].element?0:iy(e[1].element,t[1].element)?-1:1}ot(vu,"sortByDocumentPosition");function ay(e){return new MutationObserver(t=>{for(const n of t)if(n.type==="childList"){e();return}})}ot(ay,"getChildListObserver");var hE=Object.defineProperty,gE=(e,t)=>hE(e,"name",{value:t,configurable:!0}),oy=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),yu=W(gE(function(t,n){return o(ge.span,{...t,ref:n,style:{...oy,...t.style}})},"VisuallyHidden")),vE=yu,yE=Object.defineProperty,Ge=(e,t)=>yE(e,"name",{value:t,configurable:!0}),sy="ToastProvider",[bu,cy,bE]=Ua("Toast"),[ly,MH]=dt("Toast",[bE]),[_E,Vs]=ly(sy),wE=Ge(e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:i="right",swipeThreshold:a=50,announcerContainer:s,children:c}=e,[l,d]=D(null),[u,p]=D(0),f=B(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${sy}\`. Expected non-empty \`string\`.`),o(bu.Provider,{scope:t,children:o(_E,{scope:t,label:n,duration:r,swipeDirection:i,swipeThreshold:a,toastCount:u,viewport:l,onViewportChange:d,onToastAdd:oe(()=>p(m=>m+1),[]),onToastRemove:oe(()=>p(m=>m-1),[]),isClosePausedRef:f,announcerContainer:s,children:c})})},"ToastProvider"),SE="ToastViewport",CE=["F8"],_u="toast.viewportPause",wu="toast.viewportResume",RE=W(Ge(function(t,n){const{__scopeToast:r,hotkey:i=CE,label:a="Notifications ({hotkey})",...s}=t,c=Vs(SE,r),l=cy(r),d=B(null),u=B(null),p=B(null),f=B(null),m=Se(n,f,c.onViewportChange),v=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),b=c.toastCount>0;V(()=>{const y=Ge(w=>{i.length!==0&&i.every(_=>w[_]||w.code===_)&&f.current?.focus()},"handleKeyDown");return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[i]),V(()=>{const y=d.current,w=f.current;if(b&&y&&w){const _=Ge(()=>{if(!c.isClosePausedRef.current){const A=new CustomEvent(_u);w.dispatchEvent(A),c.isClosePausedRef.current=!0}},"handlePause"),R=Ge(()=>{if(c.isClosePausedRef.current){const A=new CustomEvent(wu);w.dispatchEvent(A),c.isClosePausedRef.current=!1}},"handleResume"),I=Ge(A=>{y.contains(A.relatedTarget)||R()},"handleFocusOutResume"),T=Ge(()=>{y.contains(document.activeElement)||R()},"handlePointerLeaveResume");return y.addEventListener("focusin",_),y.addEventListener("focusout",I),y.addEventListener("pointermove",_),y.addEventListener("pointerleave",T),window.addEventListener("blur",_),window.addEventListener("focus",R),()=>{y.removeEventListener("focusin",_),y.removeEventListener("focusout",I),y.removeEventListener("pointermove",_),y.removeEventListener("pointerleave",T),window.removeEventListener("blur",_),window.removeEventListener("focus",R)}}},[b,c.isClosePausedRef]);const h=oe(({tabbingDirection:y})=>{const w=l().map(_=>{const R=_.ref.current,I=[R,...my(R)];return y==="forwards"?I:I.reverse()});return(y==="forwards"?w.reverse():w).flat()},[l]);return V(()=>{const y=f.current;if(y){const w=Ge(_=>{const R=_.altKey||_.ctrlKey||_.metaKey;if(_.key==="Tab"&&!R){const I=document.activeElement,T=_.shiftKey;if(_.target===y&&T){u.current?.focus();return}const A=h({tabbingDirection:T?"backwards":"forwards"}),L=A.findIndex(F=>F===I);zs(A.slice(L+1))?_.preventDefault():T?u.current?.focus():p.current?.focus()}},"handleKeyDown");return y.addEventListener("keydown",w),()=>y.removeEventListener("keydown",w)}},[l,h]),o(Gk,{ref:d,role:"region","aria-label":a.replace("{hotkey}",v),tabIndex:-1,style:{pointerEvents:b?void 0:"none"},children:[b&&o(dy,{ref:u,onFocusFromOutsideViewport:()=>{zs(h({tabbingDirection:"forwards"}))}}),o(bu.Slot,{scope:r,children:o(ge.ol,{tabIndex:-1,...s,ref:m})}),b&&o(dy,{ref:p,onFocusFromOutsideViewport:()=>{zs(h({tabbingDirection:"backwards"}))}})]})},"ToastViewport")),IE="ToastFocusProxy",dy=W(Ge(function(t,n){const{__scopeToast:r,onFocusFromOutsideViewport:i,...a}=t,s=Vs(IE,r);return o(yu,{tabIndex:0,...a,ref:n,style:{position:"fixed"},onFocus:c=>{const l=c.relatedTarget;s.viewport?.contains(l)||i()}})},"ToastFocusProxy")),Ks="Toast",kE="toast.swipeStart",TE="toast.swipeMove",PE="toast.swipeCancel",NE="toast.swipeEnd",EE=W(Ge(function(t,n){const{forceMount:r,open:i,defaultOpen:a,onOpenChange:s,...c}=t,[l,d]=Dt({prop:i,defaultProp:a??!0,onChange:s,caller:Ks});return o(Pt,{present:r||l,children:o(DE,{open:l,...c,ref:n,onClose:()=>d(!1),onPause:ht(t.onPause),onResume:ht(t.onResume),onSwipeStart:ne(t.onSwipeStart,u=>{u.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ne(t.onSwipeMove,u=>{const{x:p,y:f}=u.detail.delta;u.currentTarget.setAttribute("data-swipe","move"),u.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${p}px`),u.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${f}px`)}),onSwipeCancel:ne(t.onSwipeCancel,u=>{u.currentTarget.setAttribute("data-swipe","cancel"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),u.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ne(t.onSwipeEnd,u=>{const{x:p,y:f}=u.detail.delta;u.currentTarget.setAttribute("data-swipe","end"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),u.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${p}px`),u.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${f}px`),d(!1)})})})},"Toast")),[AE,xE]=ly(Ks,{onClose(){}}),DE=W(Ge(function(t,n){const{__scopeToast:r,type:i="foreground",duration:a,open:s,onClose:c,onEscapeKeyDown:l,onPause:d,onResume:u,onSwipeStart:p,onSwipeMove:f,onSwipeCancel:m,onSwipeEnd:v,...b}=t,h=Vs(Ks,r),y=cy(r),[w,_]=D(null),R=Se(n,_),I=B(null),T=B(null),A=a||h.duration,L=B(0),F=B(A),N=B(0),{onToastAdd:j,onToastRemove:x}=h,U=ht(()=>{w?.contains(document.activeElement)&&h.viewport?.focus(),c()}),q=oe(E=>{!E||E===1/0||(window.clearTimeout(N.current),L.current=new Date().getTime(),N.current=window.setTimeout(U,E))},[U]);V(()=>{const E=h.viewport;if(E){const C=Ge(()=>{q(F.current),u?.()},"handleResume"),O=Ge(()=>{const H=new Date().getTime()-L.current;F.current=F.current-H,window.clearTimeout(N.current),d?.()},"handlePause");return E.addEventListener(_u,O),E.addEventListener(wu,C),()=>{E.removeEventListener(_u,O),E.removeEventListener(wu,C)}}},[h.viewport,A,d,u,q]),V(()=>{s&&!h.isClosePausedRef.current&&q(A)},[s,A,h.isClosePausedRef,q]),V(()=>()=>{window.clearTimeout(N.current)},[]),V(()=>(j(),()=>x()),[j,x]);const $=Ie(()=>w?Su(w):null,[w]);return h.viewport?o(z,{children:[$&&o(LE,{__scopeToast:r,role:"status","aria-live":i==="foreground"?"assertive":"polite",children:$}),o(AE,{scope:r,onClose:U,children:ln(o(bu.ItemSlot,{scope:r,children:o(Uk,{asChild:!0,onEscapeKeyDown:ne(l,E=>{y().some(C=>C.ref.current?.contains(E.target))||U()}),children:o(ge.li,{tabIndex:0,"data-state":s?"open":"closed","data-swipe-direction":h.swipeDirection,...b,ref:R,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:ne(t.onKeyDown,E=>{E.key==="Escape"&&(l?.(E.nativeEvent),E.nativeEvent.defaultPrevented||U())}),onPointerDown:ne(t.onPointerDown,E=>{E.button===0&&(I.current={x:E.clientX,y:E.clientY})}),onPointerMove:ne(t.onPointerMove,E=>{if(!I.current)return;const C=E.clientX-I.current.x,O=E.clientY-I.current.y,H=!!T.current,G=["left","right"].includes(h.swipeDirection),ee=["left","up"].includes(h.swipeDirection)?Math.min:Math.max,Z=G?ee(0,C):0,ie=G?0:ee(0,O),fe=E.pointerType==="touch"?10:2,Ce={x:Z,y:ie},Pe={originalEvent:E,delta:Ce};H?(T.current=Ce,Ga(TE,f,Pe,{discrete:!1})):uy(Ce,h.swipeDirection,fe)?(T.current=Ce,Ga(kE,p,Pe,{discrete:!1}),E.target.setPointerCapture(E.pointerId)):(Math.abs(C)>fe||Math.abs(O)>fe)&&(I.current=null)}),onPointerUp:ne(t.onPointerUp,E=>{const C=T.current,O=E.target;if(O.hasPointerCapture(E.pointerId)&&O.releasePointerCapture(E.pointerId),T.current=null,I.current=null,C){const H=E.currentTarget,G={originalEvent:E,delta:C};uy(C,h.swipeDirection,h.swipeThreshold)?Ga(NE,v,G,{discrete:!0}):Ga(PE,m,G,{discrete:!0}),H.addEventListener("click",ee=>ee.preventDefault(),{once:!0})}})})})}),h.viewport)})]}):null},"ToastImpl")),LE=Ge(e=>{const{__scopeToast:t,children:n,...r}=e,i=Vs(Ks,t),[a,s]=D(!1),[c,l]=D(!1);return py(()=>s(!0)),V(()=>{const d=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(d)},[]),c?null:o(Ti,{asChild:!0,container:i.announcerContainer||void 0,children:o(yu,{...r,children:a&&o(z,{children:[i.label," ",n]})})})},"ToastAnnounce"),$E=W(Ge(function(t,n){const{__scopeToast:r,...i}=t;return o(ge.div,{...i,ref:n})},"ToastDescription")),jE="ToastClose",OE=W(Ge(function(t,n){const{__scopeToast:r,...i}=t,a=xE(jE,r);return o(ME,{asChild:!0,children:o(ge.button,{type:"button",...i,ref:n,onClick:ne(t.onClick,a.onClose)})})},"ToastClose")),ME=W(Ge(function(t,n){const{__scopeToast:r,altText:i,...a}=t;return o(ge.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":i||void 0,...a,ref:n})},"ToastAnnounceExclude"));function Su(e){const t=[];return Array.from(e.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),fy(n)){const r=n.ariaHidden||n.hidden||n.style.display==="none",i=n.dataset.radixToastAnnounceExclude==="";if(!r)if(i){const a=n.dataset.radixToastAnnounceAlt;a&&t.push(a)}else t.push(...Su(n))}}),t}Ge(Su,"getAnnounceTextContent");function Ga(e,t,n,{discrete:r}){const i=n.originalEvent.currentTarget,a=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?gs(i,a):i.dispatchEvent(a)}Ge(Ga,"handleAndDispatchCustomEvent");var uy=Ge((e,t,n=0)=>{const r=Math.abs(e.x),i=Math.abs(e.y),a=r>i;return t==="left"||t==="right"?a&&r>n:!a&&i>n},"isDeltaInDirection");function py(e=()=>{}){const t=ht(e);Xe(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}Ge(py,"useNextFrame");function fy(e){return e.nodeType===e.ELEMENT_NODE}Ge(fy,"isHTMLElement");function my(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:Ge(r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}Ge(my,"getTabbableCandidates");function zs(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}Ge(zs,"focusFirst");var FE=wE,BE=RE,qE=EE,UE=$E,GE=OE,Ha=qs([]),HE=1;function VE(e,t="success",n=8e3){if(!e)return;const r=HE++;Ha.value=[...Ha.value,{id:r,message:e,variant:t,durationMs:n}]}function KE(e){Ha.value=Ha.value.filter(t=>t.id!==e)}function zE(){const e=Ha.value;return o(FE,{duration:8e3,swipeDirection:"right",children:[e.map(t=>o(qE,{className:`toast-root toast-${t.variant}`,duration:t.durationMs,onOpenChange:n=>{n||KE(t.id)},type:t.variant==="error"||t.variant==="warning"?"foreground":"background",children:[o(UE,{className:"toast-message",children:t.message}),o(GE,{"aria-label":"Dismiss",className:"toast-close",children:"×"})]},t.id)),o(BE,{className:"toast-viewport"})]})}function WE(e){Ue(o(zE,{}),e)}function Ws(e,t,n){const r=document.createElement(e);return t&&(r.className=t),n!=null&&(r.textContent=String(n)),r}function Qe(e){return document.getElementById(e)}function Cu(e){return document.getElementById(e)}function Js(e){return document.getElementById(e)}function hy(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function JE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function YE(e,t){const n=t.trim();if(!n)return hy(e);const r=hy(e);try{const i=new RegExp(`(${JE(n)})`,"ig");return r.replace(i,'<mark class="match">$1</mark>')}catch{return r}}async function Va(e,t){const n=t.textContent;try{await navigator.clipboard.writeText(e),t.textContent="Copied"}catch{t.textContent="Copy failed"}setTimeout(()=>{t.textContent=n||"Copy"},1200)}function XE(e=Hl){let t=0,n=null;const r=i=>{n&&(n.deadline.abort(i),n.deadline.dispose(),n=null)};return{begin:()=>{r();const i=Fm(e),a=++t;return n={deadline:i,generation:a},{generation:a,isCurrent:()=>n?.generation===a&&!i.signal.aborted,isOwned:()=>n?.generation===a,signal:i.signal}},cancel:r,finish:i=>{n?.generation===i.generation&&(n.deadline.dispose(),n=null)},outstanding:()=>n?1:0}}var qr=["feed","projects","sharing","devices","health","advanced"],gy=["sync","coordinator-admin"];function Ys(){return{status:"not_loaded"}}function Xs(e,t=""){if(e.status==="available"||e.status==="stale"){const n=e.snapshot.scopeKey===t?e.snapshot:null;return{status:"loading",previous:n,previousStatus:n?e.status:null}}return e.status==="loading"&&e.previous?.scopeKey===t?e:{status:"loading",previous:null,previousStatus:null}}function QE(e,t=Date.now(),n=""){return{status:"available",snapshot:{data:e,loadedAt:t,scopeKey:n}}}function ZE(e,t){return e.status==="loading"&&e.previous?{status:"stale",snapshot:e.previous,error:t}:e.status==="available"||e.status==="stale"?{status:"stale",snapshot:e.snapshot,error:t}:{status:"failed",error:t}}function On(e,t){return e.status==="available"||e.status==="stale"?t!==void 0&&e.snapshot.scopeKey!==t?null:e.snapshot.data:e.status==="loading"?t!==void 0&&e.previous?.scopeKey!==t?null:e.previous?.data??null:null}function Qs(e,t){return e.status==="stale"?t===void 0||e.snapshot.scopeKey===t:e.status!=="loading"||e.previousStatus!=="stale"?!1:t===void 0||e.previous?.scopeKey===t}var Ru="codemem-tab",vy="codemem-advanced-section",yy="codemem-feed-filter",by="codemem-feed-scope",eA="codemem-sync-diagnostics",_y="codemem-sync-pairing",wy="codemem-sync-redact",Sy=["all","observations","summaries"],Cy=["all","mine","theirs"],S={activeTab:"feed",advancedSection:"sync",currentProject:"",refreshState:"idle",refreshInFlight:!1,refreshQueued:!1,refreshTimer:null,feedTypeFilter:"all",feedScopeFilter:"all",feedQuery:"",lastFeedItems:[],lastFeedFilteredCount:0,lastFeedSignature:"",pendingFeedItems:null,itemViewState:new Map,itemExpandState:new Map,newItemKeys:new Set,healthStats:Ys(),viewerActorId:null,healthUsage:Ys(),healthSession:Ys(),healthRawEvents:Ys(),lastUpdateStatus:null,lastSyncStatus:null,lastDeviceIdentityInventory:null,deviceIdentityInventoryLoadError:!1,pendingDeviceIdentityFocus:void 0,lastSyncActors:[],lastSyncPeers:[],lastShareOperations:[],shareOperationsLoadError:!1,pendingAcceptedSyncPeers:[],lastSyncSharingReview:[],lastSyncLegacySharedReview:null,lastSyncCoordinator:null,lastSyncCoordinatorAdminStatus:null,lastCoordinatorAdminStatus:null,coordinatorAdminTargetGroup:"",knownProjects:[],lastProjectCoordinatorAdminGroups:[],lastCoordinatorAdminGroups:[],lastCoordinatorAdminJoinRequests:[],lastCoordinatorAdminDevices:[],lastSyncJoinRequests:[],lastTeamInvite:null,lastTeamJoin:null,syncJoinFlowFeedback:null,syncPeerFeedbackById:new Map,syncPeersSectionFeedback:null,syncJoinRequestsFeedback:null,syncDiscoveredFeedback:null,pendingCoordinatorApprovalsByDeviceId:new Map,lastSyncAttempts:[],lastSyncLegacyDevices:[],lastSyncViewModel:null,lastSyncDuplicatePersonDecisions:{},pairingPayloadRaw:null,pairingCommandRaw:"",configDefaults:{},configPath:"",syncDiagnosticsOpen:!1,syncPairingOpen:!1};function tA(e){return[...qr]}function Ka(e,t){return e==="sync"||e==="coordinator-admin"?"advanced":qr.includes(e)?e:"feed"}function Iu(e=window.location.hash){const t=e.replace(/^#/,"").split("/")[0];return gy.includes(t)?"advanced":qr.includes(t)?t:null}function ku(e=window.location.hash){const[t,n]=e.replace(/^#/,"").split("/");return t==="sync"?"sync":t==="coordinator-admin"?"teams":t!=="advanced"?null:n==="teams"?"teams":"sync"}function nA(){const e=Iu();if(e)return Ka(e,S.lastCoordinatorAdminStatus);const t=localStorage.getItem(Ru);return t&&(qr.includes(t)||gy.includes(t))?Ka(t,S.lastCoordinatorAdminStatus):"feed"}function rA(){const e=ku();if(e)return e;const t=localStorage.getItem(Ru);return t==="coordinator-admin"?"teams":t==="sync"?"sync":localStorage.getItem(vy)==="teams"?"teams":"sync"}function Tu(e,t=!1){S.advancedSection=e,localStorage.setItem(vy,e),t&&(window.location.hash=`advanced/${e}`)}function Ry(e,t={}){const n=Ka(e,S.lastCoordinatorAdminStatus);S.activeTab=n,localStorage.setItem(Ru,n);const r=Iu();t.canonicalHash?window.location.hash=n:r!==n&&(window.location.hash=n==="advanced"?`advanced/${S.advancedSection}`:n)}function iA(){const e=localStorage.getItem(yy)||"all";return Sy.includes(e)?e:"all"}function aA(){const e=localStorage.getItem(by)||"all";return Cy.includes(e)?e:"all"}function oA(e){S.feedTypeFilter=Sy.includes(e)?e:"all",localStorage.setItem(yy,S.feedTypeFilter)}function Iy(e){S.feedScopeFilter=Cy.includes(e)?e:"all",localStorage.setItem(by,S.feedScopeFilter)}function sA(){return localStorage.getItem(eA)==="1"}function cA(e){S.syncPairingOpen=e;try{localStorage.setItem(_y,e?"1":"0")}catch{}}function za(){return localStorage.getItem(wy)!=="0"}function lA(e){localStorage.setItem(wy,e?"1":"0")}function dA(){S.activeTab=nA(),S.advancedSection=rA(),S.feedTypeFilter=iA(),S.feedScopeFilter=aA(),S.syncDiagnosticsOpen=sA();try{S.syncPairingOpen=localStorage.getItem(_y)==="1"}catch{S.syncPairingOpen=!1}}function uA(e,t,n){t.left>=n.left&&t.right<=n.right||e.scrollIntoView({block:"nearest",inline:"nearest"})}function pA(){let e=null,t=null,n=null,r=null,i=null;return a=>{if(a.hidden)return;const s=a.closest(".tab-bar");if(!s)return;const c=a.getBoundingClientRect(),l=s.getBoundingClientRect(),d=c.left+s.scrollLeft,u=c.right+s.scrollLeft;a===e&&d===t&&u===n&&l.left===r&&l.right===i||(e=a,t=d,n=u,r=l.left,i=l.right,uA(a,c,l))}}var Pu=[{id:"light",label:"Light",mode:"light"},{id:"dark",label:"Dark",mode:"dark"}],ky="codemem-theme";function Ty(e){const t=Pu.find(r=>r.id===e);if(t)return t;const n=e.startsWith("dark")?"dark":"light";return Pu.find(r=>r.id===n)||Pu[0]}function Nu(){const e=localStorage.getItem(ky);return e?Ty(e).id:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Py(e){const t=Ty(e);document.documentElement.setAttribute("data-theme",t.mode),document.documentElement.setAttribute("data-color-mode",t.mode),t.id===t.mode?document.documentElement.removeAttribute("data-theme-variant"):document.documentElement.setAttribute("data-theme-variant",t.id),localStorage.setItem(ky,t.id)}function fA(e){if(!e)return;const t=n=>{const r=n==="dark"?"sun":"moon",i=n==="dark"?"Switch to light theme":"Switch to dark theme";e.setAttribute("aria-label",i),e.textContent="";const a=document.createElement("i");a.setAttribute("data-lucide",r),a.setAttribute("aria-hidden","true"),e.appendChild(a),globalThis.lucide?.createIcons?.()};t(Nu()==="dark"?"dark":"light"),e.addEventListener("click",()=>{const n=Nu()==="dark"?"light":"dark";Py(n),t(n)})}var mA=Object.defineProperty,hA=(e,t)=>mA(e,"name",{value:t,configurable:!0}),gA=Ar(void 0);function qi(e){const t=En(gA);return e||t||"ltr"}hA(qi,"useDirection");var vA=Object.defineProperty,Eu=(e,t)=>vA(e,"name",{value:t,configurable:!0}),Au=!1;function Ny(){const[e,t]=D(Au);return V(()=>{Au||(Au=!0,t(!0))},[]),e}Eu(Ny,"useIsHydrated");var Ey=Ci[" useSyncExternalStore ".trim().toString()];function Ay(){return()=>{}}Eu(Ay,"subscribe");function xy(){return Ey(Ay,()=>!0,()=>!1)}Eu(xy,"useIsHydratedModern");var yA=typeof Ey=="function"?xy:Ny,bA=Object.defineProperty,Ur=(e,t)=>bA(e,"name",{value:t,configurable:!0}),xu="rovingFocusGroup.onEntryFocus",_A={bubbles:!1,cancelable:!0},Zs="RovingFocusGroup",[Du,Dy,wA]=Ua(Zs),[SA,Ui]=dt(Zs,[wA]),[CA,RA]=SA(Zs),IA=W(Ur(function(t,n){return o(Du.Provider,{scope:t.__scopeRovingFocusGroup,children:o(Du.Slot,{scope:t.__scopeRovingFocusGroup,children:o(kA,{...t,ref:n})})})},"RovingFocusGroup")),kA=W(Ur(function(t,n){const{__scopeRovingFocusGroup:r,orientation:i,loop:a=!1,dir:s,currentTabStopId:c,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:d,onEntryFocus:u,preventScrollOnEntryFocus:p=!1,...f}=t,m=B(null),v=Se(n,m),b=qi(s),[h,y]=Dt({prop:c,defaultProp:l??null,onChange:d,caller:Zs}),[w,_]=D(!1),R=ht(u),I=Dy(r),T=B(!1),[A,L]=D(0);return V(()=>{const F=m.current;if(F)return F.addEventListener(xu,R),()=>F.removeEventListener(xu,R)},[R]),o(CA,{scope:r,orientation:i,dir:b,loop:a,currentTabStopId:h,onItemFocus:oe(F=>y(F),[y]),onItemShiftTab:oe(()=>_(!0),[]),onFocusableItemAdd:oe(()=>L(F=>F+1),[]),onFocusableItemRemove:oe(()=>L(F=>F-1),[]),children:o(ge.div,{tabIndex:w||A===0?-1:0,"data-orientation":i,...f,ref:v,style:{outline:"none",...t.style},onMouseDown:ne(t.onMouseDown,()=>{T.current=!0}),onFocus:ne(t.onFocus,F=>{const N=!T.current;if(F.target===F.currentTarget&&N&&!w){const j=new CustomEvent(xu,_A);if(F.currentTarget.dispatchEvent(j),!j.defaultPrevented){const x=I().filter(U=>U.focusable);Lu([x.find(U=>U.active),x.find(U=>U.id===h),...x].filter(Boolean).map(U=>U.ref.current),p)}}T.current=!1}),onBlur:ne(t.onBlur,()=>_(!1))})})},"RovingFocusGroupImpl")),TA="RovingFocusGroupItem",PA=W(Ur(function(t,n){const{__scopeRovingFocusGroup:r,focusable:i=!0,active:a=!1,tabStopId:s,children:c,...l}=t,d=xt(),u=s||d,p=RA(TA,r),f=p.currentTabStopId===u,m=Dy(r),{onFocusableItemAdd:v,onFocusableItemRemove:b,currentTabStopId:h}=p,y=yA();return Xe(()=>{if(!(!y||!i))return v(),()=>b()},[y,i,v,b]),V(()=>{if(!(y||!i))return v(),()=>b()},[y,i,v,b]),o(Du.ItemSlot,{scope:r,id:u,focusable:i,active:a,children:o(ge.span,{tabIndex:f?0:-1,"data-orientation":p.orientation,...l,ref:n,onMouseDown:ne(t.onMouseDown,w=>{i?p.onItemFocus(u):w.preventDefault()}),onFocus:ne(t.onFocus,()=>p.onItemFocus(u)),onKeyDown:ne(t.onKeyDown,w=>{if(w.key==="Tab"&&w.shiftKey){p.onItemShiftTab();return}if(w.target!==w.currentTarget)return;const _=$y(w,p.orientation,p.dir);if(_!==void 0){if(w.metaKey||w.ctrlKey||w.altKey||w.shiftKey)return;w.preventDefault();let R=m().filter(I=>I.focusable).map(I=>I.ref.current);if(_==="last")R.reverse();else if(_==="prev"||_==="next"){_==="prev"&&R.reverse();const I=R.indexOf(w.currentTarget);R=p.loop?jy(R,I+1):R.slice(I+1)}setTimeout(()=>Lu(R))}}),children:typeof c=="function"?c({isCurrentTabStop:f,hasTabStop:h!=null}):c})})},"RovingFocusGroupItem")),NA={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Ly(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}Ur(Ly,"getDirectionAwareKey");function $y(e,t,n){const r=Ly(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return NA[r]}Ur($y,"getFocusIntent");function Lu(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}Ur(Lu,"focusFirst");function jy(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Ur(jy,"wrapArray");var $u=IA,ju=PA,EA=Object.defineProperty,Gi=(e,t)=>EA(e,"name",{value:t,configurable:!0}),Ou="Tabs",[AA,FH]=dt(Ou,[Ui]),Oy=Ui(),[xA,Mu]=AA(Ou),DA=W(Gi(function(t,n){const{__scopeTabs:r,value:i,onValueChange:a,defaultValue:s,orientation:c="horizontal",dir:l,activationMode:d="automatic",...u}=t,p=qi(l),[f,m]=Dt({prop:i,onChange:a,defaultProp:s??"",caller:Ou});return o(xA,{scope:r,baseId:xt(),value:f,onValueChange:m,orientation:c,dir:p,activationMode:d,children:o(ge.div,{dir:p,"data-orientation":c,...u,ref:n})})},"Tabs")),LA="TabsList",$A=W(Gi(function(t,n){const{__scopeTabs:r,loop:i=!0,...a}=t,s=Mu(LA,r),c=Oy(r);return o($u,{asChild:!0,...c,orientation:s.orientation,dir:s.dir,loop:i,children:o(ge.div,{role:"tablist","aria-orientation":s.orientation,...a,ref:n})})},"TabsList")),jA="TabsTrigger",OA=W(Gi(function(t,n){const{__scopeTabs:r,value:i,disabled:a=!1,...s}=t,c=Mu(jA,r),l=Oy(r),d=Fu(c.baseId,i),u=Bu(c.baseId,i),p=i===c.value;return o(ju,{asChild:!0,...l,focusable:!a,active:p,children:o(ge.button,{type:"button",role:"tab","aria-selected":p,"aria-controls":u,"data-state":p?"active":"inactive","data-disabled":a?"":void 0,disabled:a,id:d,...s,ref:n,onMouseDown:ne(t.onMouseDown,f=>{!a&&f.button===0&&f.ctrlKey===!1?c.onValueChange(i):f.preventDefault()}),onKeyDown:ne(t.onKeyDown,f=>{a||f.target!==f.currentTarget||[" ","Enter"].includes(f.key)&&c.onValueChange(i)}),onFocus:ne(t.onFocus,()=>{const f=c.activationMode!=="manual";!p&&!a&&f&&c.onValueChange(i)})})})},"TabsTrigger")),MA="TabsContent",FA=W(Gi(function(t,n){const{__scopeTabs:r,value:i,forceMount:a,children:s,...c}=t,l=Mu(MA,r),d=Fu(l.baseId,i),u=Bu(l.baseId,i),p=i===l.value,f=B(p);return V(()=>{const m=requestAnimationFrame(()=>f.current=!1);return()=>cancelAnimationFrame(m)},[]),o(Pt,{present:a||p,children:({present:m})=>o(ge.div,{"data-state":p?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":d,hidden:!m,id:u,tabIndex:0,...c,ref:n,style:{...t.style,animationDuration:f.current?"0s":void 0},children:m&&s})})},"TabsContent"));function Fu(e,t){return`${e}-trigger-${t}`}Gi(Fu,"makeTriggerId");function Bu(e,t){return`${e}-content-${t}`}Gi(Bu,"makeContentId");var BA=DA,qA=$A,UA=OA,GA=FA;function My({ariaLabel:e,children:t,listClassName:n,onValueChange:r,tabs:i,triggerClassName:a,value:s}){return o(BA,{onValueChange:r,value:s,children:[o(qA,{"aria-label":e,className:n,children:i.map(c=>o(UA,{className:a,disabled:c.disabled,value:c.value,children:c.label},c.value))}),t]})}function Gr({children:e,className:t,forceMount:n=!1,value:r}){return o(GA,{className:t,forceMount:n?!0:void 0,value:r,children:e})}function ke(e){return o("input",{...e})}function ec(){return{aliases:new Map,duplicateDisplayNames:new Map,reservedDisplayNames:new Set}}function Fy(e,t=ec()){for(const a of e){const s=String(a.display_name||"").trim();s&&t.reservedDisplayNames.add(s)}for(const[a,s]of t.aliases)t.reservedDisplayNames.has(s)&&t.aliases.delete(a);const n=new Set([...t.reservedDisplayNames,...t.aliases.values()]),r=e.filter(a=>!String(a.display_name||"").trim()).map(a=>String(a.device_id||"").trim()).filter(Boolean).sort((a,s)=>a.localeCompare(s));let i=Math.max(0,...[...t.aliases.values()].map(a=>{const s=/^Unnamed device (\d+)$/.exec(a);return s?Number(s[1]):0}));for(const a of r){if(t.aliases.has(a))continue;let s;do i+=1,s=`Unnamed device ${i}`;while(n.has(s));t.aliases.set(a,s),n.add(s)}return t.aliases}function tc(e,t=ec()){const n=Fy(e,t),r=new Map,i=new Map,a=new Map,s=new Set;for(const l of e){const d=String(l.device_id||"").trim(),u=String(l.display_name||"").trim();if(!d)continue;if(!u){r.set(d,n.get(d)||"Unnamed device");continue}a.set(d,u),s.add(u);const p=i.get(u)??[];p.push(d),i.set(u,p)}for(const[l,d]of t.duplicateDisplayNames){const u=a.get(l);(u&&u!==d.sourceName||s.has(d.displayName))&&t.duplicateDisplayNames.delete(l)}const c=new Set([...s,...[...t.duplicateDisplayNames.values()].map(l=>l.displayName)]);for(const[l,d]of i)for(const u of d.sort((p,f)=>p.localeCompare(f))){const p=t.duplicateDisplayNames.get(u);if(p?.sourceName===l){r.set(u,p.displayName);continue}if(d.length===1){r.set(u,l);continue}let f=0,m;do f+=1,m=`${l} · Device ${f}`;while(c.has(m));r.set(u,m),t.duplicateDisplayNames.set(u,{displayName:m,sourceName:l}),c.add(m)}return r}function HA(e,t,n=""){const r=String(e.device_id||"").trim(),i=String(e.group_id||t||"").trim(),a=n||String(e.display_name||"").trim()||"Unnamed device",s=e.enabled!==!1&&e.enabled!==0,c=[`Device ID ${r||"unknown"}`];return i&&c.push(`Group ID ${i}`),{advancedDetail:`Advanced: ${c.join(" · ")}`,deviceId:r,displayName:a,statusLabel:s?"Enabled in this coordinator group":"Disabled in this coordinator group",teamId:i}}var By={status:"coordinator status",groups:"coordinator groups",joinRequests:"join requests",devices:"devices"};function nc(){return{availability:"unknown",retrying:!1}}function VA(){return{status:nc(),groups:nc(),joinRequests:nc(),devices:nc()}}function Wa(e,t){e[t]={...e[t],retrying:!0}}function qu(e,t){e[t]={...e[t],retrying:!1}}function rc(e,t){e[t]={availability:"fresh",retrying:!1}}function fn(e,t,n){e[t]={availability:n??(e[t].availability==="fresh"||e[t].availability==="stale")?"stale":"unavailable",retrying:!1}}function Uu(e,t){e[t]={availability:"not_applicable",retrying:!1}}function Hr(e,t){return e[t].availability==="fresh"||e[t].availability==="stale"}function Mn(e,...t){return t.every(n=>e[n].availability==="fresh"&&!e[n].retrying)}function Hi(e,t){return e[t].availability==="not_applicable"}function Gu(e){const t=Object.entries(e),n=t.filter(([,i])=>i.availability==="stale").map(([i])=>By[i]),r=t.filter(([,i])=>i.availability==="unavailable").map(([i])=>By[i]);return n.length===0&&r.length===0?null:{stale:n,unavailable:r,retrying:t.some(([,i])=>i.retrying)}}var KA="codemem-coordinator-admin-target-group",P={recovery:VA(),loadGeneration:0,recoveryAnnouncement:"",recoveryFocusPending:!1,recoveryRetryRequested:!1,activeSection:"groups",inviteGroup:"",inviteTtlHours:"24",invitePolicy:"auto_admit",invitePending:!1,showArchivedGroups:!1,createGroupId:"",createGroupDisplayName:"",groupActionPendingId:"",groupActionPendingKind:"",joinReviewPendingId:"",joinReviewPendingAction:"",deviceActionPendingId:"",deviceActionPendingKind:"",joinRequestsSnapshotTarget:null,devicesSnapshotTarget:null,groupRenameDrafts:new Map,groupPresentationAliases:new Map,deviceRenameDrafts:new Map,deviceRenameServerNames:new Map,unnamedDeviceAliases:ec(),groupPreferencesOpen:new Set,groupPreferencesDrafts:new Map,groupScopeManagementOpen:new Set,groupScopeManagementDrafts:new Map,teamSetupGuide:null,availableProjects:[]};function qy(){return P.loadGeneration+=1,P.loadGeneration}function Hu(e){return P.loadGeneration===e}function zA(e){const{summary:t,fresh:n,runDevice:r,snapshotMatchesTarget:i}=e,a=i&&Hr(P.recovery,"devices"),s=Hi(P.recovery,"devices"),c=a&&Array.isArray(S.lastCoordinatorAdminDevices)?S.lastCoordinatorAdminDevices:[],l=tc(c,P.unnamedDeviceAliases);return g(Gr,{className:"coordinator-admin-panel",value:"devices"},g("h3",null,"Enrolled devices"),g("p",{class:"peer-submeta"},t.readiness==="ready"?"Rename, disable, re-enable, or remove devices from the selected coordinator group. Space transport access is managed below; policy Team membership and Project access stay in Sharing.":"Finish coordinator setup first. Device administration stays disabled until legacy administration is ready."),s?g("div",{class:"peer-meta"},"Complete legacy coordinator setup to load enrolled devices. No device data is expected yet."):a?c.length?g("div",{class:"peer-list"},c.map(d=>{const u=HA(d,String(S.lastCoordinatorAdminStatus?.active_group||""),l.get(String(d.device_id||"").trim())),{deviceId:p,displayName:f,teamId:m}=u,v=P.deviceActionPendingId===p,b=P.deviceRenameDrafts.get(p)??String(d.display_name||""),h=d.enabled!==!1&&d.enabled!==0,y=!n||!p||v;return g("div",{class:"peer-card peer-card--padded",key:p||String(d.fingerprint||"unknown")},g("div",{class:"peer-title"},g("strong",null,f)),g("div",{class:"peer-submeta"},u.statusLabel),g("details",{class:"coordinator-admin-diagnostics"},g("summary",null,"Diagnostics"),g("div",{class:"peer-meta"},u.advancedDetail)),g("form",{class:"coordinator-admin-form",onSubmit:w=>{w.preventDefault(),!y&&r(p,m,f,"rename")}},g("div",{class:"coordinator-admin-form-grid"},g("label",{class:"coordinator-admin-field"},g("span",null,"Display name"),g(ke,{class:"peer-scope-input",disabled:!n||v,onInput:w=>{P.deviceRenameDrafts.set(p,String(w.currentTarget.value||""))},type:"text",value:b}))),g("div",{class:"peer-actions"},g("button",{class:"settings-button",disabled:y,type:"submit"},v&&P.deviceActionPendingKind==="rename"?"Renaming…":"Rename"),h?g("button",{class:"settings-button danger",disabled:y,onClick:()=>r(p,m,f,"disable"),type:"button"},v&&P.deviceActionPendingKind==="disable"?"Disabling…":"Disable"):g("button",{class:"settings-button",disabled:y,onClick:()=>r(p,m,f,"enable"),type:"button"},v&&P.deviceActionPendingKind==="enable"?"Enabling…":"Enable"),g("button",{class:"settings-button danger",disabled:y,onClick:()=>r(p,m,f,"remove"),type:"button"},v&&P.deviceActionPendingKind==="remove"?"Removing…":"Remove"))))})):g("div",{class:"peer-meta"},t.readiness==="ready"?"No enrolled devices found for the active coordinator group.":"Device administration will appear here once setup is complete."):g("div",{class:"peer-meta"},"Enrolled devices are unavailable. Retry to load current devices; no empty result is being assumed."))}var WA=Object.defineProperty,Ja=(e,t)=>WA(e,"name",{value:t,configurable:!0}),Vu="Collapsible",[JA,BH]=dt(Vu),[YA,Ku]=JA(Vu),XA=W(Ja(function(t,n){const{__scopeCollapsible:r,open:i,defaultOpen:a,disabled:s,onOpenChange:c,...l}=t,[d,u]=Dt({prop:i,defaultProp:a??!1,onChange:c,caller:Vu});return o(YA,{scope:r,disabled:s,contentId:xt(),open:d,onOpenToggle:oe(()=>u(p=>!p),[u]),children:o(ge.div,{"data-state":ic(d),"data-disabled":s?"":void 0,...l,ref:n})})},"Collapsible")),QA="CollapsibleTrigger",ZA=W(Ja(function(t,n){const{__scopeCollapsible:r,...i}=t,a=Ku(QA,r);return o(ge.button,{type:"button","aria-controls":a.open?a.contentId:void 0,"aria-expanded":a.open||!1,"data-state":ic(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...i,ref:n,onClick:ne(t.onClick,a.onOpenToggle)})},"CollapsibleTrigger")),Uy="CollapsibleContent",ex=W(Ja(function(t,n){const{forceMount:r,...i}=t,a=Ku(Uy,t.__scopeCollapsible);return o(Pt,{present:r||a.open,children:({present:s})=>o(tx,{...i,ref:n,present:s})})},"CollapsibleContent")),tx=W(Ja(function(t,n){const{__scopeCollapsible:r,present:i,children:a,...s}=t,c=Ku(Uy,r),[l,d]=D(i),u=B(null),p=Se(n,u),f=B(0),m=f.current,v=B(0),b=v.current,h=c.open||l,y=B(h),w=B(void 0);return V(()=>{const _=requestAnimationFrame(()=>y.current=!1);return()=>cancelAnimationFrame(_)},[]),Xe(()=>{const _=u.current;if(_){w.current=w.current||{transitionDuration:_.style.transitionDuration,animationName:_.style.animationName},_.style.transitionDuration="0s",_.style.animationName="none";const R=_.getBoundingClientRect();f.current=R.height,v.current=R.width,y.current||(_.style.transitionDuration=w.current.transitionDuration,_.style.animationName=w.current.animationName),d(i)}},[c.open,i]),o(ge.div,{"data-state":ic(c.open),"data-disabled":c.disabled?"":void 0,id:c.contentId,hidden:!h,...s,ref:p,style:{"--radix-collapsible-content-height":m?`${m}px`:void 0,"--radix-collapsible-content-width":b?`${b}px`:void 0,...t.style},children:h&&a})},"CollapsibleContentImpl"));function ic(e){return e?"open":"closed"}Ja(ic,"getState");var Ya=XA,zu=ZA,Xa=ex,nx=["top","right","bottom","left"],rr=Math.min,$t=Math.max,ac=Math.round,oc=Math.floor,mn=e=>({x:e,y:e}),rx={left:"right",right:"left",bottom:"top",top:"bottom"};function Wu(e,t,n){return $t(e,rr(t,n))}function Fn(e,t){return typeof e=="function"?e(t):e}function Bn(e){return e.split("-")[0]}function Vi(e){return e.split("-")[1]}function Ju(e){return e==="x"?"y":"x"}function Yu(e){return e==="y"?"height":"width"}function hn(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function Xu(e){return Ju(hn(e))}function ix(e,t,n){n===void 0&&(n=!1);const r=Vi(e),i=Xu(e),a=Yu(i);let s=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[a]>t.floating[a]&&(s=sc(s)),[s,sc(s)]}function ax(e){const t=sc(e);return[Qu(e),t,Qu(t)]}function Qu(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}var Gy=["left","right"],Hy=["right","left"],ox=["top","bottom"],sx=["bottom","top"];function cx(e,t,n){switch(e){case"top":case"bottom":return n?t?Hy:Gy:t?Gy:Hy;case"left":case"right":return t?ox:sx;default:return[]}}function lx(e,t,n,r){const i=Vi(e);let a=cx(Bn(e),n==="start",r);return i&&(a=a.map(s=>s+"-"+i),t&&(a=a.concat(a.map(Qu)))),a}function sc(e){const t=Bn(e);return rx[t]+e.slice(t.length)}function dx(e){return{top:0,right:0,bottom:0,left:0,...e}}function Vy(e){return typeof e!="number"?dx(e):{top:e,right:e,bottom:e,left:e}}function cc(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function Ky(e,t,n){let{reference:r,floating:i}=e;const a=hn(t),s=Xu(t),c=Yu(s),l=Bn(t),d=a==="y",u=r.x+r.width/2-i.width/2,p=r.y+r.height/2-i.height/2,f=r[c]/2-i[c]/2;let m;switch(l){case"top":m={x:u,y:r.y-i.height};break;case"bottom":m={x:u,y:r.y+r.height};break;case"right":m={x:r.x+r.width,y:p};break;case"left":m={x:r.x-i.width,y:p};break;default:m={x:r.x,y:r.y}}switch(Vi(t)){case"start":m[s]-=f*(n&&d?-1:1);break;case"end":m[s]+=f*(n&&d?-1:1)}return m}async function ux(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:a,rects:s,elements:c,strategy:l}=e,{boundary:d="clippingAncestors",rootBoundary:u="viewport",elementContext:p="floating",altBoundary:f=!1,padding:m=0}=Fn(t,e),v=Vy(m),b=c[f?p==="floating"?"reference":"floating":p],h=cc(await a.getClippingRect({element:(n=await(a.isElement==null?void 0:a.isElement(b)))==null||n?b:b.contextElement||await(a.getDocumentElement==null?void 0:a.getDocumentElement(c.floating)),boundary:d,rootBoundary:u,strategy:l})),y=p==="floating"?{x:r,y:i,width:s.floating.width,height:s.floating.height}:s.reference,w=await(a.getOffsetParent==null?void 0:a.getOffsetParent(c.floating)),_=await(a.isElement==null?void 0:a.isElement(w))?await(a.getScale==null?void 0:a.getScale(w))||{x:1,y:1}:{x:1,y:1},R=cc(a.convertOffsetParentRelativeRectToViewportRelativeRect?await a.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:y,offsetParent:w,strategy:l}):y);return{top:(h.top-R.top+v.top)/_.y,bottom:(R.bottom-h.bottom+v.bottom)/_.y,left:(h.left-R.left+v.left)/_.x,right:(R.right-h.right+v.right)/_.x}}var px=50,fx=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:a=[],platform:s}=n,c=s.detectOverflow?s:{...s,detectOverflow:ux},l=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:p}=Ky(d,r,l),f=r,m=0;const v={};for(let b=0;b<a.length;b++){const h=a[b];if(!h)continue;const{name:y,fn:w}=h,{x:_,y:R,data:I,reset:T}=await w({x:u,y:p,initialPlacement:r,placement:f,strategy:i,middlewareData:v,rects:d,platform:c,elements:{reference:e,floating:t}});u=_??u,p=R??p,v[y]={...v[y],...I},T&&m<px&&(m++,typeof T=="object"&&(T.placement&&(f=T.placement),T.rects&&(d=T.rects===!0?await s.getElementRects({reference:e,floating:t,strategy:i}):T.rects),{x:u,y:p}=Ky(d,f,l)),b=-1)}return{x:u,y:p,placement:f,strategy:i,middlewareData:v}},mx=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:a,platform:s,elements:c,middlewareData:l}=t,{element:d,padding:u=0}=Fn(e,t)||{};if(d==null)return{};const p=Vy(u),f={x:n,y:r},m=Xu(i),v=Yu(m),b=await s.getDimensions(d),h=m==="y",y=h?"top":"left",w=h?"bottom":"right",_=h?"clientHeight":"clientWidth",R=a.reference[v]+a.reference[m]-f[m]-a.floating[v],I=f[m]-a.reference[m],T=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=T?T[_]:0;(!A||!await(s.isElement==null?void 0:s.isElement(T)))&&(A=c.floating[_]||a.floating[v]);const L=R/2-I/2,F=A/2-b[v]/2-1,N=rr(p[y],F),j=rr(p[w],F),x=N,U=A-b[v]-j,q=A/2-b[v]/2+L,$=Wu(x,q,U),E=!l.arrow&&Vi(i)!=null&&q!==$&&a.reference[v]/2-(q<x?N:j)-b[v]/2<0,C=E?q<x?q-x:q-U:0;return{[m]:f[m]+C,data:{[m]:$,centerOffset:q-$-C,...E&&{alignmentOffset:C}},reset:E}}}),hx=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:a,rects:s,initialPlacement:c,platform:l,elements:d}=t,{mainAxis:u=!0,crossAxis:p=!0,fallbackPlacements:f,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:v="none",flipAlignment:b=!0,...h}=Fn(e,t);if((n=a.arrow)!=null&&n.alignmentOffset)return{};const y=Bn(i),w=hn(c),_=Bn(c)===c,R=await(l.isRTL==null?void 0:l.isRTL(d.floating)),I=f||(_||!b?[sc(c)]:ax(c)),T=v!=="none";!f&&T&&I.push(...lx(c,b,v,R));const A=[c,...I],L=await l.detectOverflow(t,h),F=[];let N=((r=a.flip)==null?void 0:r.overflows)||[];if(u&&F.push(L[y]),p){const q=ix(i,s,R);F.push(L[q[0]],L[q[1]])}if(N=[...N,{placement:i,overflows:F}],!F.every(q=>q<=0)){var j,x;const q=(((j=a.flip)==null?void 0:j.index)||0)+1,$=A[q];if($&&(!(p==="alignment"&&w!==hn($))||N.every(C=>hn(C.placement)===w?C.overflows[0]>0:!0)))return{data:{index:q,overflows:N},reset:{placement:$}};let E=(x=N.filter(C=>C.overflows[0]<=0).sort((C,O)=>C.overflows[1]-O.overflows[1])[0])==null?void 0:x.placement;if(!E)switch(m){case"bestFit":{var U;const C=(U=N.filter(O=>{if(T){const H=hn(O.placement);return H===w||H==="y"}return!0}).map(O=>[O.placement,O.overflows.filter(H=>H>0).reduce((H,G)=>H+G,0)]).sort((O,H)=>O[1]-H[1])[0])==null?void 0:U[0];C&&(E=C);break}case"initialPlacement":E=c}if(i!==E)return{reset:{placement:E}}}return{}}}};function zy(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Wy(e){return nx.some(t=>e[t]>=0)}var gx=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...a}=Fn(e,t);switch(i){case"referenceHidden":{const s=zy(await r.detectOverflow(t,{...a,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:Wy(s)}}}case"escaped":{const s=zy(await r.detectOverflow(t,{...a,altBoundary:!0}),n.floating);return{data:{escapedOffsets:s,escaped:Wy(s)}}}default:return{}}}}},Jy=new Set(["left","top"]);async function vx(e,t){const{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),s=Bn(n),c=Vi(n),l=hn(n)==="y",d=Jy.has(s)?-1:1,u=a&&l?-1:1,p=Fn(t,e);let{mainAxis:f,crossAxis:m,alignmentAxis:v}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return c&&typeof v=="number"&&(m=c==="end"?v*-1:v),l?{x:m*u,y:f*d}:{x:f*d,y:m*u}}var yx=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:a,placement:s,middlewareData:c}=t,l=await vx(t,e);return s===((n=c.offset)==null?void 0:n.placement)&&(r=c.arrow)!=null&&r.alignmentOffset?{}:{x:i+l.x,y:a+l.y,data:{...l,placement:s}}}}},bx=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:a}=t,{mainAxis:s=!0,crossAxis:c=!1,limiter:l={fn:y=>{let{x:w,y:_}=y;return{x:w,y:_}}},...d}=Fn(e,t),u={x:n,y:r},p=await a.detectOverflow(t,d),f=hn(Bn(i)),m=Ju(f);let v=u[m],b=u[f];if(s){const y=m==="y"?"top":"left",w=m==="y"?"bottom":"right",_=v+p[y],R=v-p[w];v=Wu(_,v,R)}if(c){const y=f==="y"?"top":"left",w=f==="y"?"bottom":"right",_=b+p[y],R=b-p[w];b=Wu(_,b,R)}const h=l.fn({...t,[m]:v,[f]:b});return{...h,data:{x:h.x-n,y:h.y-r,enabled:{[m]:s,[f]:c}}}}}},_x=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:i,rects:a,middlewareData:s}=t,{offset:c=0,mainAxis:l=!0,crossAxis:d=!0}=Fn(e,t),u={x:n,y:r},p=hn(i),f=Ju(p);let m=u[f],v=u[p];const b=Fn(c,t),h=typeof b=="number"?{mainAxis:b,crossAxis:0}:{mainAxis:0,crossAxis:0,...b};if(l){const _=f==="y"?"height":"width",R=a.reference[f]-a.floating[_]+h.mainAxis,I=a.reference[f]+a.reference[_]-h.mainAxis;m<R?m=R:m>I&&(m=I)}if(d){var y,w;const _=f==="y"?"width":"height",R=Jy.has(Bn(i)),I=a.reference[p]-a.floating[_]+(R&&((y=s.offset)==null?void 0:y[p])||0)+(R?0:h.crossAxis),T=a.reference[p]+a.reference[_]+(R?0:((w=s.offset)==null?void 0:w[p])||0)-(R?h.crossAxis:0);v<I?v=I:v>T&&(v=T)}return{[f]:m,[p]:v}}}},wx=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:i,rects:a,platform:s,elements:c}=t,{apply:l=()=>{},...d}=Fn(e,t),u=await s.detectOverflow(t,d),p=Bn(i),f=Vi(i),m=hn(i)==="y",{width:v,height:b}=a.floating;let h,y;p==="top"||p==="bottom"?(h=p,y=f===(await(s.isRTL==null?void 0:s.isRTL(c.floating))?"start":"end")?"left":"right"):(y=p,h=f==="end"?"top":"bottom");const w=b-u.top-u.bottom,_=v-u.left-u.right,R=rr(b-u[h],w),I=rr(v-u[y],_),T=!t.middlewareData.shift;let A=R,L=I;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(L=_),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(A=w),T&&!f){const N=$t(u.left,0),j=$t(u.right,0),x=$t(u.top,0),U=$t(u.bottom,0);m?L=v-2*(N!==0||j!==0?N+j:$t(u.left,u.right)):A=b-2*(x!==0||U!==0?x+U:$t(u.top,u.bottom))}await l({...t,availableWidth:L,availableHeight:A});const F=await s.getDimensions(c.floating);return v!==F.width||b!==F.height?{reset:{rects:!0}}:{}}}};function lc(){return typeof window<"u"}function Ki(e){return Yy(e)?(e.nodeName||"").toLowerCase():"#document"}function jt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function gn(e){var t;return(t=(Yy(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Yy(e){return lc()?e instanceof Node||e instanceof jt(e).Node:!1}function Xt(e){return lc()?e instanceof Element||e instanceof jt(e).Element:!1}function qn(e){return lc()?e instanceof HTMLElement||e instanceof jt(e).HTMLElement:!1}function Xy(e){return!lc()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof jt(e).ShadowRoot}function Qa(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Qt(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function Sx(e){return/^(table|td|th)$/.test(Ki(e))}function dc(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}var Cx=/transform|translate|scale|rotate|perspective|filter/,Rx=/paint|layout|strict|content/,Vr=e=>!!e&&e!=="none",Zu;function ep(e){const t=Xt(e)?Qt(e):e;return Vr(t.transform)||Vr(t.translate)||Vr(t.scale)||Vr(t.rotate)||Vr(t.perspective)||!tp()&&(Vr(t.backdropFilter)||Vr(t.filter))||Cx.test(t.willChange||"")||Rx.test(t.contain||"")}function Ix(e){let t=ir(e);for(;qn(t)&&!zi(t);){if(ep(t))return t;if(dc(t))return null;t=ir(t)}return null}function tp(){return Zu==null&&(Zu=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Zu}function zi(e){return/^(html|body|#document)$/.test(Ki(e))}function Qt(e){return jt(e).getComputedStyle(e)}function uc(e){return Xt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function ir(e){if(Ki(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Xy(e)&&e.host||gn(e);return Xy(t)?t.host:t}function Qy(e){const t=ir(e);return zi(t)?e.ownerDocument?e.ownerDocument.body:e.body:qn(t)&&Qa(t)?t:Qy(t)}function Za(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=Qy(e),a=i===((r=e.ownerDocument)==null?void 0:r.body),s=jt(i);if(a){const c=np(s);return t.concat(s,s.visualViewport||[],Qa(i)?i:[],c&&n?Za(c):[])}else return t.concat(i,Za(i,[],n))}function np(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Zy(e){const t=Qt(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=qn(e),a=i?e.offsetWidth:n,s=i?e.offsetHeight:r,c=ac(n)!==a||ac(r)!==s;return c&&(n=a,r=s),{width:n,height:r,$:c}}function rp(e){return Xt(e)?e:e.contextElement}function Wi(e){const t=rp(e);if(!qn(t))return mn(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:a}=Zy(t);let s=(a?ac(n.width):n.width)/r,c=(a?ac(n.height):n.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!c||!Number.isFinite(c))&&(c=1),{x:s,y:c}}var kx=mn(0);function eb(e){const t=jt(e);return!tp()||!t.visualViewport?kx:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Tx(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==jt(e)?!1:t}function Kr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),a=rp(e);let s=mn(1);t&&(r?Xt(r)&&(s=Wi(r)):s=Wi(e));const c=Tx(a,n,r)?eb(a):mn(0);let l=(i.left+c.x)/s.x,d=(i.top+c.y)/s.y,u=i.width/s.x,p=i.height/s.y;if(a){const f=jt(a),m=r&&Xt(r)?jt(r):r;let v=f,b=np(v);for(;b&&r&&m!==v;){const h=Wi(b),y=b.getBoundingClientRect(),w=Qt(b),_=y.left+(b.clientLeft+parseFloat(w.paddingLeft))*h.x,R=y.top+(b.clientTop+parseFloat(w.paddingTop))*h.y;l*=h.x,d*=h.y,u*=h.x,p*=h.y,l+=_,d+=R,v=jt(b),b=np(v)}}return cc({width:u,height:p,x:l,y:d})}function pc(e,t){const n=uc(e).scrollLeft;return t?t.left+n:Kr(gn(e)).left+n}function tb(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-pc(e,n),y:n.top+t.scrollTop}}function Px(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const a=i==="fixed",s=gn(r),c=t?dc(t.floating):!1;if(r===s||c&&a)return n;let l={scrollLeft:0,scrollTop:0},d=mn(1);const u=mn(0),p=qn(r);if((p||!p&&!a)&&((Ki(r)!=="body"||Qa(s))&&(l=uc(r)),p)){const m=Kr(r);d=Wi(r),u.x=m.x+r.clientLeft,u.y=m.y+r.clientTop}const f=s&&!p&&!a?tb(s,l):mn(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-l.scrollLeft*d.x+u.x+f.x,y:n.y*d.y-l.scrollTop*d.y+u.y+f.y}}function Nx(e){return Array.from(e.getClientRects())}function Ex(e){const t=gn(e),n=uc(e),r=e.ownerDocument.body,i=$t(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),a=$t(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+pc(e);const c=-n.scrollTop;return Qt(r).direction==="rtl"&&(s+=$t(t.clientWidth,r.clientWidth)-i),{width:i,height:a,x:s,y:c}}var nb=25;function Ax(e,t){const n=jt(e),r=gn(e),i=n.visualViewport;let a=r.clientWidth,s=r.clientHeight,c=0,l=0;if(i){a=i.width,s=i.height;const u=tp();(!u||u&&t==="fixed")&&(c=i.offsetLeft,l=i.offsetTop)}const d=pc(r);if(d<=0){const u=r.ownerDocument,p=u.body,f=getComputedStyle(p),m=u.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,v=Math.abs(r.clientWidth-p.clientWidth-m);v<=nb&&(a-=v)}else d<=nb&&(a+=d);return{width:a,height:s,x:c,y:l}}function xx(e,t){const n=Kr(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=qn(e)?Wi(e):mn(1);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function rb(e,t,n){let r;if(t==="viewport")r=Ax(e,n);else if(t==="document")r=Ex(gn(e));else if(Xt(t))r=xx(t,n);else{const i=eb(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return cc(r)}function ib(e,t){const n=ir(e);return n===t||!Xt(n)||zi(n)?!1:Qt(n).position==="fixed"||ib(n,t)}function Dx(e,t){const n=t.get(e);if(n)return n;let r=Za(e,[],!1).filter(c=>Xt(c)&&Ki(c)!=="body"),i=null;const a=Qt(e).position==="fixed";let s=a?ir(e):e;for(;Xt(s)&&!zi(s);){const c=Qt(s),l=ep(s);!l&&c.position==="fixed"&&(i=null),(a?!l&&!i:!l&&c.position==="static"&&i&&(i.position==="absolute"||i.position==="fixed")||Qa(s)&&!l&&ib(e,s))?r=r.filter(d=>d!==s):i=c,s=ir(s)}return t.set(e,r),r}function Lx(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const a=[...n==="clippingAncestors"?dc(t)?[]:Dx(t,this._c):[].concat(n),r],s=rb(t,a[0],i);let c=s.top,l=s.right,d=s.bottom,u=s.left;for(let p=1;p<a.length;p++){const f=rb(t,a[p],i);c=$t(f.top,c),l=rr(f.right,l),d=rr(f.bottom,d),u=$t(f.left,u)}return{width:l-u,height:d-c,x:u,y:c}}function $x(e){const{width:t,height:n}=Zy(e);return{width:t,height:n}}function jx(e,t,n){const r=qn(t),i=gn(t),a=n==="fixed",s=Kr(e,!0,a,t);let c={scrollLeft:0,scrollTop:0};const l=mn(0);function d(){l.x=pc(i)}if(r||!r&&!a)if((Ki(t)!=="body"||Qa(i))&&(c=uc(t)),r){const p=Kr(t,!0,a,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else i&&d();a&&!r&&i&&d();const u=i&&!r&&!a?tb(i,c):mn(0);return{x:s.left+c.scrollLeft-l.x-u.x,y:s.top+c.scrollTop-l.y-u.y,width:s.width,height:s.height}}function ip(e){return Qt(e).position==="static"}function ab(e,t){if(!qn(e)||Qt(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return gn(e)===n&&(n=n.ownerDocument.body),n}function ob(e,t){const n=jt(e);if(dc(e))return n;if(!qn(e)){let i=ir(e);for(;i&&!zi(i);){if(Xt(i)&&!ip(i))return i;i=ir(i)}return n}let r=ab(e,t);for(;r&&Sx(r)&&ip(r);)r=ab(r,t);return r&&zi(r)&&ip(r)&&!ep(r)?n:r||Ix(e)||n}var Ox=async function(e){const t=this.getOffsetParent||ob,n=this.getDimensions,r=await n(e.floating);return{reference:jx(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Mx(e){return Qt(e).direction==="rtl"}var Fx={convertOffsetParentRelativeRectToViewportRelativeRect:Px,getDocumentElement:gn,getClippingRect:Lx,getOffsetParent:ob,getElementRects:Ox,getClientRects:Nx,getDimensions:$x,getScale:Wi,isElement:Xt,isRTL:Mx};function sb(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Bx(e,t){let n=null,r;const i=gn(e);function a(){var c;clearTimeout(r),(c=n)==null||c.disconnect(),n=null}function s(c,l){c===void 0&&(c=!1),l===void 0&&(l=1),a();const d=e.getBoundingClientRect(),{left:u,top:p,width:f,height:m}=d;if(c||t(),!f||!m)return;const v=oc(p),b=oc(i.clientWidth-(u+f)),h=oc(i.clientHeight-(p+m)),y=oc(u),w={rootMargin:-v+"px "+-b+"px "+-h+"px "+-y+"px",threshold:$t(0,rr(1,l))||1};let _=!0;function R(I){const T=I[0].intersectionRatio;if(T!==l){if(!_)return s();T?s(!1,T):r=setTimeout(()=>{s(!1,1e-7)},1e3)}T===1&&!sb(d,e.getBoundingClientRect())&&s(),_=!1}try{n=new IntersectionObserver(R,{...w,root:i.ownerDocument})}catch{n=new IntersectionObserver(R,w)}n.observe(e)}return s(!0),a}function qx(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:c=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,d=rp(e),u=i||a?[...d?Za(d):[],...t?Za(t):[]]:[];u.forEach(y=>{i&&y.addEventListener("scroll",n,{passive:!0}),a&&y.addEventListener("resize",n)});const p=d&&c?Bx(d,n):null;let f=-1,m=null;s&&(m=new ResizeObserver(y=>{let[w]=y;w&&w.target===d&&m&&t&&(m.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var _;(_=m)==null||_.observe(t)})),n()}),d&&!l&&m.observe(d),t&&m.observe(t));let v,b=l?Kr(e):null;l&&h();function h(){const y=Kr(e);b&&!sb(b,y)&&n(),b=y,v=requestAnimationFrame(h)}return n(),()=>{var y;u.forEach(w=>{i&&w.removeEventListener("scroll",n),a&&w.removeEventListener("resize",n)}),p?.(),(y=m)==null||y.disconnect(),m=null,l&&cancelAnimationFrame(v)}}var Ux=yx,Gx=bx,Hx=hx,Vx=wx,Kx=gx,cb=mx,zx=_x,Wx=(e,t,n)=>{const r=new Map,i={platform:Fx,...n},a={...i.platform,_c:r};return fx(e,t,{...i,platform:a})},fc=typeof document<"u"?Tt:function(){};function mc(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!mc(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const a=i[r];if(!(a==="_owner"&&e.$$typeof)&&!mc(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}function lb(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function db(e,t){const n=lb(e);return Math.round(t*n)/n}function ap(e){const t=B(e);return fc(()=>{t.current=e}),t}function Jx(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:a,floating:s}={},transform:c=!0,whileElementsMounted:l,open:d}=e,[u,p]=D({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=D(r);mc(f,r)||m(r);const[v,b]=D(null),[h,y]=D(null),w=oe(O=>{O!==T.current&&(T.current=O,b(O))},[]),_=oe(O=>{O!==A.current&&(A.current=O,y(O))},[]),R=a||v,I=s||h,T=B(null),A=B(null),L=B(u),F=l!=null,N=ap(l),j=ap(i),x=ap(d),U=oe(()=>{if(!T.current||!A.current)return;const O={placement:t,strategy:n,middleware:f};j.current&&(O.platform=j.current),Wx(T.current,A.current,O).then(H=>{const G={...H,isPositioned:x.current!==!1};q.current&&!mc(L.current,G)&&(L.current=G,ms(()=>{p(G)}))})},[f,t,n,j,x]);fc(()=>{d===!1&&L.current.isPositioned&&(L.current.isPositioned=!1,p(O=>({...O,isPositioned:!1})))},[d]);const q=B(!1);fc(()=>(q.current=!0,()=>{q.current=!1}),[]),fc(()=>{if(R&&(T.current=R),I&&(A.current=I),R&&I){if(N.current)return N.current(R,I,U);U()}},[R,I,U,N,F]);const $=Ie(()=>({reference:T,floating:A,setReference:w,setFloating:_}),[w,_]),E=Ie(()=>({reference:R,floating:I}),[R,I]),C=Ie(()=>{const O={position:n,left:0,top:0};if(!E.floating)return O;const H=db(E.floating,u.x),G=db(E.floating,u.y);return c?{...O,transform:"translate("+H+"px, "+G+"px)",...lb(E.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:H,top:G}},[n,c,E.floating,u.x,u.y]);return Ie(()=>({...u,update:U,refs:$,elements:E,floatingStyles:C}),[u,U,$,E,C])}var Yx=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?cb({element:r.current,padding:i}).fn(n):{}:r?cb({element:r,padding:i}).fn(n):{}}}},Xx=(e,t)=>{const n=Ux(e);return{name:n.name,fn:n.fn,options:[e,t]}},Qx=(e,t)=>{const n=Gx(e);return{name:n.name,fn:n.fn,options:[e,t]}},Zx=(e,t)=>({fn:zx(e).fn,options:[e,t]}),e0=(e,t)=>{const n=Hx(e);return{name:n.name,fn:n.fn,options:[e,t]}},t0=(e,t)=>{const n=Vx(e);return{name:n.name,fn:n.fn,options:[e,t]}},n0=(e,t)=>{const n=Kx(e);return{name:n.name,fn:n.fn,options:[e,t]}},r0=(e,t)=>{const n=Yx(e);return{name:n.name,fn:n.fn,options:[e,t]}},i0=Object.defineProperty,a0=(e,t)=>i0(e,"name",{value:t,configurable:!0}),o0=W(a0(function(t,n){const{children:r,width:i=10,height:a=5,...s}=t;return o(ge.svg,{...s,ref:n,width:i,height:a,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?r:o("polygon",{points:"0,0 30,0 15,10"})})},"Arrow")),s0=o0,c0=Object.defineProperty,l0=(e,t)=>c0(e,"name",{value:t,configurable:!0});function hc(e){const[t,n]=D(void 0);return Xe(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const a=i[0];let s,c;if("borderBoxSize"in a){const l=a.borderBoxSize,d=Array.isArray(l)?l[0]:l;s=d.inlineSize,c=d.blockSize}else s=e.offsetWidth,c=e.offsetHeight;n({width:s,height:c})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}l0(hc,"useSize");var d0=Object.defineProperty,Un=(e,t)=>d0(e,"name",{value:t,configurable:!0}),ub="Popper",[pb,ar]=dt(ub),[u0,fb]=pb(ub),p0=Un(e=>{const{__scopePopper:t,children:n}=e,[r,i]=D(null),[a,s]=D(void 0);return o(u0,{scope:t,anchor:r,onAnchorChange:i,placementState:a,setPlacementState:s,children:n})},"Popper"),f0="PopperAnchor",m0=W(Un(function(t,n){const{__scopePopper:r,virtualRef:i,...a}=t,s=fb(f0,r),c=B(null),l=s.onAnchorChange,d=oe(b=>{c.current=b,b&&l(b)},[l]),u=Se(n,d),p=B(null);V(()=>{if(!i)return;const b=p.current;p.current=i.current,b!==p.current&&l(p.current)});const f=s.placementState&&gc(s.placementState),m=f?.[0],v=f?.[1];return i?null:o(ge.div,{"data-radix-popper-side":m,"data-radix-popper-align":v,...a,ref:u})},"PopperAnchor")),mb="PopperContent",[h0,g0]=pb(mb),v0=W(Un(function(t,n){const{__scopePopper:r,side:i="bottom",sideOffset:a=0,align:s="center",alignOffset:c=0,arrowPadding:l=0,avoidCollisions:d=!0,collisionBoundary:u=[],collisionPadding:p=0,sticky:f="partial",hideWhenDetached:m=!1,updatePositionStrategy:v="optimized",onPlaced:b,...h}=t,y=fb(mb,r),[w,_]=D(null),R=Se(n,_),[I,T]=D(null),A=hc(I),L=A?.width??0,F=A?.height??0,N=i+(s!=="center"?"-"+s:""),j=typeof p=="number"?p:{top:0,right:0,bottom:0,left:0,...p},x=Array.isArray(u)?u:[u],U=x.length>0,q={padding:j,boundary:x.filter(hb),altBoundary:U},{refs:$,floatingStyles:E,placement:C,isPositioned:O,middlewareData:H}=Jx({strategy:"fixed",placement:N,whileElementsMounted:Un((...me)=>qx(...me,{animationFrame:v==="always"}),"whileElementsMounted"),elements:{reference:y.anchor},middleware:[Xx({mainAxis:a+F,alignmentAxis:c}),d&&Qx({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?Zx():void 0,...q}),d&&e0({...q}),t0({...q,apply:Un(({elements:me,rects:J,availableWidth:se,availableHeight:ye})=>{const{width:le,height:Ee}=J.reference,re=me.floating.style;re.setProperty("--radix-popper-available-width",`${se}px`),re.setProperty("--radix-popper-available-height",`${ye}px`),re.setProperty("--radix-popper-anchor-width",`${le}px`),re.setProperty("--radix-popper-anchor-height",`${Ee}px`)},"apply")}),I&&r0({element:I,padding:l}),w0({arrowWidth:L,arrowHeight:F}),m&&n0({strategy:"referenceHidden",...q,boundary:U?q.boundary:void 0})]}),G=y.setPlacementState;Xe(()=>(G(C),()=>{G(void 0)}),[C,G]);const[ee,Z]=gc(C),ie=ht(b);Xe(()=>{O&&ie?.()},[O,ie]);const fe=H.arrow?.x,Ce=H.arrow?.y,Pe=H.arrow?.centerOffset!==0,[Ne,ce]=D();return Xe(()=>{w&&ce(window.getComputedStyle(w).zIndex)},[w]),o("div",{ref:$.setFloating,"data-radix-popper-content-wrapper":"",style:{...E,transform:O?E.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ne,"--radix-popper-transform-origin":[H.transformOrigin?.x,H.transformOrigin?.y].join(" "),...H.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:o(h0,{scope:r,placedSide:ee,placedAlign:Z,onArrowChange:T,arrowX:fe,arrowY:Ce,shouldHideArrow:Pe,children:o(ge.div,{"data-side":ee,"data-align":Z,...h,ref:R,style:{...h.style,animation:O?h.style?.animation:"none"}})})})},"PopperContent")),y0="PopperArrow",b0={top:"bottom",right:"left",bottom:"top",left:"right"},_0=W(Un(function(t,n){const{__scopePopper:r,...i}=t,a=g0(y0,r),s=b0[a.placedSide];return o("span",{ref:a.onArrowChange,style:{position:"absolute",left:a.arrowX,top:a.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[a.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[a.placedSide],visibility:a.shouldHideArrow?"hidden":void 0},children:o(s0,{...i,ref:n,style:{...i.style,display:"block"}})})},"PopperArrow"));function hb(e){return e!==null}Un(hb,"isNotNull");var w0=Un(e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,a=i.arrow?.centerOffset!==0,s=a?0:e.arrowWidth,c=a?0:e.arrowHeight,[l,d]=gc(n),u={start:"0%",center:"50%",end:"100%"}[d],p=(i.arrow?.x??0)+s/2,f=(i.arrow?.y??0)+c/2;let m="",v="";return l==="bottom"?(m=a?u:`${p}px`,v=`${-c}px`):l==="top"?(m=a?u:`${p}px`,v=`${r.floating.height+c}px`):l==="right"?(m=`${-c}px`,v=a?u:`${f}px`):l==="left"&&(m=`${r.floating.width+c}px`,v=a?u:`${f}px`),{data:{x:m,y:v}}}}),"transformOrigin");function gc(e){const[t,n="center"]=e.split("-");return[t,n]}Un(gc,"getSideAndAlignFromPlacement");var vc=p0,eo=m0,yc=v0,S0=_0,C0=Object.defineProperty,Gn=(e,t)=>C0(e,"name",{value:t,configurable:!0}),op="Popover",[gb,qH]=dt(op,[ar]),bc=ar(),[R0,zr]=gb(op),I0=Gn(e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:s=!1}=e,c=bc(t),l=B(null),[d,u]=D(!1),[p,f]=Dt({prop:r,defaultProp:i??!1,onChange:a,caller:op});return o(vc,{...c,children:o(R0,{scope:t,contentId:xt(),triggerRef:l,open:p,onOpenChange:f,onOpenToggle:oe(()=>f(m=>!m),[f]),hasCustomAnchor:d,onCustomAnchorAdd:oe(()=>u(!0),[]),onCustomAnchorRemove:oe(()=>u(!1),[]),modal:s,children:n})})},"Popover"),k0="PopoverAnchor",T0=W(Gn(function(t,n){const{__scopePopover:r,...i}=t,a=zr(k0,r),s=bc(r),{onCustomAnchorAdd:c,onCustomAnchorRemove:l}=a;return V(()=>(c(),()=>l()),[c,l]),o(eo,{...s,...i,ref:n})},"PopoverAnchor")),P0="PopoverTrigger",N0=W(Gn(function(t,n){const{__scopePopover:r,...i}=t,a=zr(P0,r),s=bc(r),c=Se(n,a.triggerRef),l=o(ge.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":sp(a.open),...i,ref:c,onClick:ne(t.onClick,a.onOpenToggle)});return a.hasCustomAnchor?l:o(eo,{asChild:!0,...s,children:l})},"PopoverTrigger")),vb="PopoverPortal",[E0,A0]=gb(vb,{forceMount:void 0}),x0=Gn(e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,a=zr(vb,t);return o(E0,{scope:t,forceMount:n,children:o(Pt,{present:n||a.open,children:o(Ti,{asChild:!0,container:i,children:r})})})},"PopoverPortal"),to="PopoverContent",D0=W(Gn(function(t,n){const r=A0(to,t.__scopePopover),{forceMount:i=r.forceMount,...a}=t,s=zr(to,t.__scopePopover);return o(Pt,{present:i||s.open,children:s.modal?o($0,{...a,ref:n}):o(j0,{...a,ref:n})})},"PopoverContent")),L0=dn("PopoverContent.RemoveScroll"),$0=W(Gn(function(t,n){const r=zr(to,t.__scopePopover),i=B(null),a=Se(n,i),s=B(!1);return V(()=>{const c=i.current;if(c)return ks(c)},[]),o(Ea,{as:L0,allowPinchZoom:!0,children:o(yb,{...t,ref:a,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ne(t.onCloseAutoFocus,c=>{c.preventDefault(),s.current||r.triggerRef.current?.focus()}),onPointerDownOutside:ne(t.onPointerDownOutside,c=>{const l=c.detail.originalEvent,d=l.button===0&&l.ctrlKey===!0,u=l.button===2||d;s.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:ne(t.onFocusOutside,c=>c.preventDefault(),{checkForDefaultPrevented:!1})})})},"PopoverContentModal")),j0=W(Gn(function(t,n){const r=zr(to,t.__scopePopover),i=B(!1),a=B(!1);return o(yb,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{t.onCloseAutoFocus?.(s),s.defaultPrevented||(i.current||r.triggerRef.current?.focus(),s.preventDefault()),i.current=!1,a.current=!1},onInteractOutside:s=>{t.onInteractOutside?.(s),s.defaultPrevented||(i.current=!0,s.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const c=s.target;r.triggerRef.current?.contains(c)&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&a.current&&s.preventDefault()}})},"PopoverContentNonModal")),yb=W(Gn(function(t,n){const{__scopePopover:r,trapFocus:i,onOpenAutoFocus:a,onCloseAutoFocus:s,disableOutsidePointerEvents:c,onEscapeKeyDown:l,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:p,...f}=t,m=zr(to,r),v=bc(r);return Ei(),o(vs,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:a,onUnmountAutoFocus:s,children:o(ki,{asChild:!0,disableOutsidePointerEvents:c,onInteractOutside:p,onEscapeKeyDown:l,onPointerDownOutside:d,onFocusOutside:u,onDismiss:()=>m.onOpenChange(!1),deferPointerDownOutside:!0,children:o(yc,{"data-state":sp(m.open),role:"dialog",id:m.contentId,...v,...f,ref:n,style:{...f.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})},"PopoverContentImpl"));function sp(e){return e?"open":"closed"}Gn(sp,"getState");var bb=I0,O0=T0,M0=N0,_b=x0,wb=D0;function cp(e){return e.trim()}function Sb({values:e,onValuesChange:t,availableProjects:n,placeholder:r,emptyLabel:i,disabled:a,"aria-labelledby":s}){const[c,l]=D(!1),[d,u]=D(""),[p,f]=D(0),m=B(null),v=Ie(()=>{const N=new Set,j=[];for(const x of[...n,...e]){const U=cp(x);!U||N.has(U)||(N.add(U),j.push(U))}return j.sort((x,U)=>x.localeCompare(U))},[n,e]),b=cp(d),h=b.toLowerCase(),y=Ie(()=>h?v.filter(N=>N.toLowerCase().includes(h)):v,[v,h]),w=b?v.some(N=>N.toLowerCase()===h):!1,_=!!b&&!w,R=y.length+(_?1:0);V(()=>{p>=R&&f(Math.max(0,R-1))},[R,p]),V(()=>{if(!c)return;const N=requestAnimationFrame(()=>m.current?.focus());return()=>cancelAnimationFrame(N)},[c]);const I=N=>{e.includes(N)?t(e.filter(j=>j!==N)):t(Array.from(new Set([...e,N])))},T=N=>{const j=cp(N);j&&(t(Array.from(new Set([...e,j]))),u(""),f(0))},A=N=>{if(N<y.length){const j=y[N];j&&I(j);return}_&&T(b)},L=N=>{if(N.key==="ArrowDown"){N.preventDefault(),f(j=>Math.min(R-1,j+1));return}if(N.key==="ArrowUp"){N.preventDefault(),f(j=>Math.max(0,j-1));return}if(N.key==="Enter"){N.preventDefault(),A(p);return}},F=N=>{t(e.filter(j=>j!==N))};return o("div",{class:"project-scope-picker",children:[o("ul",{"aria-labelledby":s,class:"project-scope-picker-selected",children:e.length===0?o("li",{class:"project-scope-picker-selected-empty",children:i||"No projects selected."}):e.map(N=>o("li",{class:"project-scope-picker-selected-chip",children:[o("span",{children:N}),a?null:o("button",{"aria-label":`Remove ${N}`,class:"project-scope-picker-selected-remove",onClick:()=>F(N),type:"button",children:"×"})]},N))}),o(bb,{onOpenChange:N=>{l(N),N||(u(""),f(0))},open:c,children:[o(M0,{asChild:!0,children:o("button",{class:"project-scope-picker-trigger settings-button",disabled:a,type:"button",children:[o("span",{"aria-hidden":"true",children:"+"}),o("span",{children:r||"Add project"})]})}),o(_b,{children:o(wb,{align:"start",class:"project-scope-picker-popover",sideOffset:6,children:[o("input",{"aria-label":"Search projects",class:"project-scope-picker-search",onInput:N=>{u(N.currentTarget.value),f(0)},onKeyDown:L,placeholder:"Search or create…",ref:m,type:"text",value:d}),o("div",{class:"project-scope-picker-results",role:"listbox",children:[y.length===0&&!_?o("div",{class:"project-scope-picker-empty-row",children:"No projects yet. Type a name to create one."}):null,y.map((N,j)=>{const x=e.includes(N);return o("button",{"aria-selected":x,class:j===p?"project-scope-picker-row project-scope-picker-row--active":"project-scope-picker-row",onClick:()=>{f(j),I(N)},onMouseEnter:()=>f(j),role:"option",type:"button",children:[o("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:x?"✓":""}),o("span",{class:"project-scope-picker-row-label",children:N})]},N)}),_?o("button",{"aria-selected":!1,class:p===y.length?"project-scope-picker-row project-scope-picker-row--create project-scope-picker-row--active":"project-scope-picker-row project-scope-picker-row--create",onClick:()=>T(b),onMouseEnter:()=>f(y.length),role:"option",type:"button",children:[o("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:"+"}),o("span",{class:"project-scope-picker-row-label",children:`Create "${b}"`})]}):null]})]})})]})]})}var F0=Object.defineProperty,or=(e,t)=>F0(e,"name",{value:t,configurable:!0}),lp="Switch",[B0,UH]=dt(lp),[q0,dp]=B0(lp);function Cb(e){const{__scopeSwitch:t,checked:n,children:r,defaultChecked:i,disabled:a,form:s,name:c,onCheckedChange:l,required:d,value:u="on",internal_do_not_use_render:p}=e,[f,m]=Dt({prop:n,defaultProp:i??!1,onChange:l,caller:lp}),[v,b]=D(null),[h,y]=D(null),w=B(!1),[_,R]=Nn(T=>T+1,0),I={checked:f,setChecked:m,disabled:a,control:v,setControl:b,name:c,form:s,value:u,hasConsumerStoppedPropagationRef:w,userInteractionCount:_,onUserInteraction:R,required:d,defaultChecked:i,isFormControl:v?!!s||!!v.closest("form"):!0,bubbleInput:h,setBubbleInput:y};return o(q0,{scope:t,...I,children:Rb(p)?p(I):r})}or(Cb,"SwitchProvider");var U0="SwitchTrigger",G0=W(or(function({__scopeSwitch:t,onClick:n,...r},i){const{control:a,form:s,value:c,disabled:l,checked:d,required:u,setControl:p,setChecked:f,hasConsumerStoppedPropagationRef:m,onUserInteraction:v,isFormControl:b,bubbleInput:h}=dp(U0,t),y=Se(i,p),w=B(d);return V(()=>{const _=s?a?.ownerDocument.getElementById(s):a?.form;if(_ instanceof HTMLFormElement){const R=or(()=>f(w.current),"reset");return _.addEventListener("reset",R),()=>_.removeEventListener("reset",R)}},[a,s,f]),o(ge.button,{type:"button",role:"switch","aria-checked":d,"aria-required":u,"data-state":up(d),"data-disabled":l?"":void 0,disabled:l,value:c,...r,ref:y,onClick:ne(n,_=>{v(),f(R=>!R),h&&b&&(m.current=_.isPropagationStopped(),m.current||_.stopPropagation())})})},"SwitchTrigger")),H0=W(or(function(t,n){const{__scopeSwitch:r,name:i,checked:a,defaultChecked:s,required:c,disabled:l,value:d,onCheckedChange:u,form:p,...f}=t;return o(Cb,{__scopeSwitch:r,checked:a,defaultChecked:s,disabled:l,required:c,onCheckedChange:u,name:i,form:p,value:d,internal_do_not_use_render:({isFormControl:m})=>o(z,{children:[o(G0,{...f,ref:n,__scopeSwitch:r}),m&&o(W0,{__scopeSwitch:r})]})})},"Switch")),V0="SwitchThumb",K0=W(or(function(t,n){const{__scopeSwitch:r,...i}=t,a=dp(V0,r);return o(ge.span,{"data-state":up(a.checked),"data-disabled":a.disabled?"":void 0,...i,ref:n})},"SwitchThumb")),z0="SwitchBubbleInput",W0=W(or(function({__scopeSwitch:t,onClick:n,...r},i){const{control:a,hasConsumerStoppedPropagationRef:s,userInteractionCount:c,checked:l,defaultChecked:d,required:u,disabled:p,name:f,value:m,form:v,bubbleInput:b,setBubbleInput:h}=dp(z0,t),y=Se(i,h),w=hc(a),_=B(!1),R=B(l),I=B(c);V(()=>{const A=b;if(!A)return;const L=window.HTMLInputElement.prototype,F=Object.getOwnPropertyDescriptor(L,"checked").set,N=c!==I.current;I.current=c;const j=R.current!==l;R.current=l;const x=!(N&&s.current);if(j&&F){_.current=!N;const U=new Event("click",{bubbles:x});F.call(A,l),A.dispatchEvent(U),_.current=!1}},[b,l,s,c]);const T=B(l);return o(ge.input,{type:"checkbox","aria-hidden":!0,defaultChecked:d??T.current,required:u,disabled:p,name:f,value:m,form:v,...r,tabIndex:-1,ref:y,onClick:ne(n,A=>{_.current&&A.stopPropagation()}),style:{...r.style,...w,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"SwitchBubbleInput"));function Rb(e){return typeof e=="function"}or(Rb,"isFunction");function up(e){return e?"checked":"unchecked"}or(up,"getState");function Ji({"aria-labelledby":e,checked:t,className:n,disabled:r=!1,id:i,name:a,onCheckedChange:s,thumbClassName:c}){return o(H0,{"aria-labelledby":e,checked:t,className:n,disabled:r,id:i,name:a,onCheckedChange:s,children:o(K0,{className:c})})}function X(e,t="success"){VE(e,t)}function Hn(e){return String(e||"").trim().replace(/\/+$/u,"")}function Ib(e){return`${KA}:${Hn(e)}`}function J0(e){try{return localStorage.getItem(Ib(e))||""}catch{return""}}function Y0(e,t){try{localStorage.setItem(Ib(e),t)}catch{}}function Vn(){return String(S.coordinatorAdminTargetGroup||"").trim()}function _c(){const e=String(S.lastCoordinatorAdminStatus?.coordinator_url||"").trim(),t=Vn()||String(S.lastCoordinatorAdminStatus?.active_group||"").trim()||sr()[0]?.group_id||"";return e&&t?{coordinatorUrl:e,groupId:t}:null}function Ot(e){const t=_c();return!!(e&&t&&Hn(e.coordinatorUrl)===Hn(t.coordinatorUrl)&&e.groupId===t.groupId)}function pp(e){S.coordinatorAdminTargetGroup=e,Y0(S.lastCoordinatorAdminStatus?.coordinator_url||null,e)}function sr(){return(Array.isArray(S.lastCoordinatorAdminGroups)?S.lastCoordinatorAdminGroups:[]).map(e=>({archived_at:e.archived_at??null,display_name:e.display_name??null,group_id:String(e.group_id||"").trim()})).filter(e=>e.group_id)}function fp(e,t){const n=String(t||"").trim(),r=sr(),i=new Set(r.map(l=>String(l.display_name||"").trim()).filter(Boolean));n&&i.add(n);for(const[l,d]of P.groupPresentationAliases)i.has(d)&&P.groupPresentationAliases.delete(l);if(n)return n;const a=P.groupPresentationAliases.get(e);if(a)return a;for(const l of P.groupPresentationAliases.values())i.add(l);let s=1,c=`Unnamed coordinator group ${s}`;for(;i.has(c);)s+=1,c=`Unnamed coordinator group ${s}`;return P.groupPresentationAliases.set(e,c),c}function X0(){const e=new Map;for(const t of sr())e.set(t.group_id,t.display_name||"");P.groupRenameDrafts.clear();for(const[t,n]of e.entries())P.groupRenameDrafts.set(t,n)}function Q0(){const e=Vn();return sr().find(t=>t.group_id===e)||null}function kb(){const e=S.lastCoordinatorAdminStatus,t=sr(),n=String(e?.active_group||"").trim(),r=J0(e?.coordinator_url||null),i=Vn(),a=new Set(t.map(l=>l.group_id)),s=i||r||n||t[0]?.group_id||"",c=s&&(a.size===0||a.has(s))?s:n||t[0]?.group_id||"";return pp(c),c}function Z0(){const e=new Map,t=new Map,n=Array.isArray(S.lastCoordinatorAdminDevices)?S.lastCoordinatorAdminDevices:[];for(const r of n){const i=String(r.device_id||"").trim();if(!i)continue;const a=String(r.display_name||""),s=P.deviceRenameDrafts.get(i),c=P.deviceRenameServerNames.get(i),l=s!==void 0&&(c===void 0||s!==c);e.set(i,l?s:a),t.set(i,a)}P.deviceRenameDrafts.clear();for(const[r,i]of e.entries())P.deviceRenameDrafts.set(r,i);P.deviceRenameServerNames.clear();for(const[r,i]of t.entries())P.deviceRenameServerNames.set(r,i)}function eD(e,t){return t&&t.groupId===e?t:null}function tD(e,t){return e?.loaded&&e.default_space_scope_id?"Configured":e?.loaded?"Not configured":t?.defaultSpaceLabel?t.defaultSpaceLabel:t?.defaultSpaceScopeId?"Configured":"Open legacy group defaults to inspect"}function nD(e,t){return e?.loaded?e.auto_grant_default_space_on_join?"On for the default Space":"Off — Space access stays explicit":t?.autoGrantDefaultSpaceOnJoin===!0?"On for the default Space":t?.autoGrantDefaultSpaceOnJoin===!1?"Off — Space access stays explicit":"Open legacy group defaults to inspect"}function rD(e){return e?.loaded?e.scopes.filter(t=>String(t.status||"active")==="active").length:null}function iD(e){const t=rD(e);return t===null?"Open Spaces to inspect access grants":`${t} active ${t===1?"Space":"Spaces"}`}function aD(e){const t=eD(e.groupId,e.setupGuide);return{autoGrant:nD(e.preferences,t),defaultSpace:tD(e.preferences,t),spaces:iD(e.scopeManagement)}}var mp=null,wc=null,hp=null;function oD(){return mp}function gp(e){wc=e}function Tb(e){hp=e}function sD(e){return hp===e}function cD(e){return e?e.kind==="confirm"?!1:e.kind==="input"?null:{action:"cancel"}:null}function vp(e){return!mp||!wc?!0:(console.warn(`Ignored sync ${e} dialog request because another sync dialog is already open.`),!1)}function Sc(e){mp=e,hp?.(e)}function cr(e){const t=wc;wc=null,Sc(null),t?.(e)}function lD(e){return e==="danger"?"sync-dialog-confirm danger":"sync-dialog-confirm"}var dD=W(function({value:t,onValueChange:n,suggestions:r,onSubmit:i,maxSuggestions:a=20,onKeyDown:s,onFocus:c,onBlur:l,className:d,...u},p){const f=B(null);us(p,()=>f.current,[]);const[m,v]=D(!1),[b,h]=D(-1),y=Ie(()=>{const I=t.trim().toLowerCase();return(I?r.filter(T=>T.toLowerCase().includes(I)):r).slice(0,a)},[t,r,a]);V(()=>{b>=y.length&&h(y.length-1)},[y.length,b]);const w=m&&y.length>0,_=I=>{n(I),v(!1),h(-1),f.current?.focus()};return o(bb,{open:w,onOpenChange:v,children:[o(O0,{asChild:!0,children:o("input",{...u,ref:f,className:d,value:t,onInput:I=>{n(I.currentTarget.value),v(!0),h(-1)},onFocus:I=>{c?.(I)},onBlur:I=>{window.setTimeout(()=>v(!1),120),l?.(I)},onKeyDown:I=>{if(I.key==="ArrowDown"){I.preventDefault(),v(!0),h(T=>y.length===0?-1:Math.min(T+1,y.length-1));return}if(I.key==="ArrowUp"){I.preventDefault(),m||v(!0),h(T=>Math.max(T-1,-1));return}if(I.key==="Escape"&&w){I.preventDefault(),v(!1),h(-1);return}if((I.key==="Tab"||I.key==="Enter")&&b>=0){const T=y[b];if(T){I.preventDefault(),_(T);return}}if(I.key==="Enter"&&i){I.preventDefault(),i();return}s?.(I)},role:"combobox","aria-autocomplete":"list","aria-expanded":w,"aria-controls":"autocompleteListbox","aria-activedescendant":b>=0?`autocomplete-option-${b}`:void 0})}),o(_b,{children:o(wb,{align:"start",className:"autocomplete-popover",onOpenAutoFocus:I=>I.preventDefault(),onCloseAutoFocus:I=>I.preventDefault(),sideOffset:4,style:{width:"var(--radix-popover-trigger-width)"},children:o("div",{className:"autocomplete-listbox",id:"autocompleteListbox",role:"listbox",children:y.map((I,T)=>{const A=T===b;return o("div",{"aria-selected":A,className:A?"autocomplete-option active":"autocomplete-option",id:`autocomplete-option-${T}`,onMouseDown:L=>{L.preventDefault(),_(I)},onMouseEnter:()=>h(T),role:"option",tabIndex:-1,children:I},I)})})})})]})}),uD=Object.defineProperty,gt=(e,t)=>uD(e,"name",{value:t,configurable:!0}),Pb="Radio",[pD,Nb]=dt(Pb),[fD,Cc]=pD(Pb);function Eb(e){const{__scopeRadio:t,checked:n=!1,children:r,disabled:i,form:a,name:s,onCheck:c,required:l,value:d="on",internal_do_not_use_render:u}=e,[p,f]=D(null),[m,v]=D(null),b=B(!1),[h,y]=Nn(_=>_+1,0),w={checked:n,disabled:i,required:l,name:s,form:a,value:d,control:p,setControl:f,hasConsumerStoppedPropagationRef:b,userInteractionCount:h,onUserInteraction:y,isFormControl:p?!!a||!!p.closest("form"):!0,bubbleInput:m,setBubbleInput:v,onCheck:gt(()=>c?.(),"onCheck")};return o(fD,{scope:t,...w,children:Ab(u)?u(w):r})}gt(Eb,"RadioProvider");var mD="RadioTrigger",hD=W(gt(function({__scopeRadio:t,onClick:n,...r},i){const{checked:a,disabled:s,value:c,setControl:l,onCheck:d,hasConsumerStoppedPropagationRef:u,onUserInteraction:p,isFormControl:f,bubbleInput:m}=Cc(mD,t),v=Se(i,l);return o(ge.button,{type:"button",role:"radio","aria-checked":a,"data-state":yp(a),"data-disabled":s?"":void 0,disabled:s,value:c,...r,ref:v,onClick:ne(n,b=>{a||(p(),d()),m&&f&&(u.current=b.isPropagationStopped(),u.current||b.stopPropagation())})})},"RadioTrigger")),gD="RadioIndicator",vD=W(gt(function(t,n){const{__scopeRadio:r,forceMount:i,...a}=t,s=Cc(gD,r);return o(Pt,{present:i||s.checked,children:o(ge.span,{"data-state":yp(s.checked),"data-disabled":s.disabled?"":void 0,...a,ref:n})})},"RadioIndicator")),yD="RadioBubbleInput",bD=W(gt(function({__scopeRadio:t,onClick:n,...r},i){const{control:a,checked:s,required:c,disabled:l,name:d,value:u,form:p,bubbleInput:f,setBubbleInput:m,hasConsumerStoppedPropagationRef:v,userInteractionCount:b}=Cc(yD,t),h=Se(i,m),y=hc(a),w=B(!1),_=B(s),R=B(b);V(()=>{const T=f;if(!T)return;const A=window.HTMLInputElement.prototype,L=Object.getOwnPropertyDescriptor(A,"checked").set,F=b!==R.current;R.current=b;const N=_.current!==s;_.current=s;const j=!(F&&v.current);if(N&&L){w.current=!F;const x=new Event("click",{bubbles:j});L.call(T,s),T.dispatchEvent(x),w.current=!1}},[f,s,v,b]);const I=B(s);return o(ge.input,{type:"radio","aria-hidden":!0,defaultChecked:I.current,required:c,disabled:l,name:d,value:u,form:p,...r,tabIndex:-1,ref:h,onClick:ne(n,T=>{w.current&&T.stopPropagation()}),style:{...r.style,...y,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"RadioBubbleInput"));function Ab(e){return typeof e=="function"}gt(Ab,"isFunction");function yp(e){return e?"checked":"unchecked"}gt(yp,"getState");var _D=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],bp="RadioGroup",[wD,GH]=dt(bp,[Ui,Nb]),xb=Ui(),Rc=Nb(),[SD,CD]=wD(bp),RD=W(gt(function(t,n){const{__scopeRadioGroup:r,name:i,form:a,defaultValue:s,value:c,required:l=!1,disabled:d=!1,orientation:u,dir:p,loop:f=!0,onValueChange:m,...v}=t,b=xb(r),h=qi(p),[y,w]=Dt({prop:c,defaultProp:s??null,onChange:m,caller:bp}),[_,R]=D(null),I=Se(n,R),T=B(y);return V(()=>{const A=a?_?.ownerDocument.getElementById(a):_?.closest("form");if(A instanceof HTMLFormElement){const L=gt(()=>w(T.current),"reset");return A.addEventListener("reset",L),()=>A.removeEventListener("reset",L)}},[_,a,w]),o(SD,{scope:r,name:i,form:a,required:l,disabled:d,value:y,onValueChange:w,children:o($u,{asChild:!0,...b,orientation:u,dir:h,loop:f,children:o(ge.div,{role:"radiogroup","aria-required":l,"aria-orientation":u,"data-disabled":d?"":void 0,dir:h,...v,ref:I})})})},"RadioGroup")),ID="RadioGroupItemProvider",kD="RadioGroupItemTrigger";function Db(e){const{__scopeRadioGroup:t,value:n,disabled:r,children:i,internal_do_not_use_render:a}=e,s=CD(ID,t),c=Rc(t),l=s.disabled||r;return o(Eb,{...c,checked:s.value===n,disabled:l,required:s.required,name:s.name,form:s.form,value:n,onCheck:()=>s.onValueChange(n),internal_do_not_use_render:a,children:i})}gt(Db,"RadioGroupItemProvider");var TD=W(gt(function(t,n){const{__scopeRadioGroup:r,...i}=t,a=xb(r),s=Rc(r),{checked:c,disabled:l}=Cc(kD,s.__scopeRadio),d=B(null),u=Se(n,d),p=B(!1);return V(()=>{const f=gt(v=>{_D.includes(v.key)&&(p.current=!0)},"handleKeyDown"),m=gt(()=>p.current=!1,"handleKeyUp");return document.addEventListener("keydown",f),document.addEventListener("keyup",m),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",m)}},[]),o(ju,{asChild:!0,...a,focusable:!l,active:c,children:o(hD,{...s,...i,ref:u,onKeyDown:ne(i.onKeyDown,f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:ne(i.onFocus,()=>{p.current&&d.current?.click()})})})},"RadioGroupItemTrigger")),PD=W(gt(function(t,n){const{__scopeRadioGroup:r,value:i,disabled:a,...s}=t;return o(Db,{__scopeRadioGroup:r,value:i,disabled:a,internal_do_not_use_render:({isFormControl:c})=>o(z,{children:[o(TD,{...s,ref:n,__scopeRadioGroup:r}),c&&o(ND,{__scopeRadioGroup:r})]})})},"RadioGroupItem")),ND=W(gt(function(t,n){const{__scopeRadioGroup:r,...i}=t,a=Rc(r);return o(bD,{...a,...i,ref:n})},"RadioGroupItemBubbleInput")),ED=W(gt(function(t,n){const{__scopeRadioGroup:r,...i}=t,a=Rc(r);return o(vD,{...a,...i,ref:n})},"RadioGroupIndicator"));function AD({ariaDescribedby:e,ariaLabel:t,autoFocusValue:n,indicatorClassName:r,itemClassName:i,itemLabelClassName:a,name:s,onValueChange:c,options:l,rootClassName:d,value:u}){return o(RD,{"aria-describedby":e,"aria-label":t,className:d,name:s,onValueChange:c,value:u,children:l.map((p,f)=>{const m=`radio-option-input-${f}`,v=`radio-option-label-${f}`;return o("label",{className:i,htmlFor:m,children:[o(PD,{id:m,"aria-labelledby":v,autoFocus:n===p.value,disabled:p.disabled,value:p.value,children:o(ED,{className:r})}),o("span",{className:a,id:v,children:p.label})]},p.value)})})}var xD=Object.defineProperty,DD=(e,t)=>xD(e,"name",{value:t,configurable:!0});function _p(e,[t,n]){return Math.min(n,Math.max(t,e))}DD(_p,"clamp");var LD=Object.defineProperty,$D=(e,t)=>LD(e,"name",{value:t,configurable:!0});function Lb(e){const t=B({value:e,previous:e});return Ie(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}$D(Lb,"usePrevious");var jD=Object.defineProperty,Oe=(e,t)=>jD(e,"name",{value:t,configurable:!0}),OD=[" ","Enter","ArrowUp","ArrowDown"],MD=[" ","Enter"],Yi="Select",[Ic,wp,FD]=Ua(Yi),[Wr,HH]=dt(Yi,[FD,ar]),Sp=ar(),[BD,lr]=Wr(Yi),[qD,UD]=Wr(Yi);function $b(e){const{__scopeSelect:t,children:n,open:r,defaultOpen:i,onOpenChange:a,value:s,defaultValue:c,onValueChange:l,dir:d,name:u,autoComplete:p,disabled:f,required:m,form:v,internal_do_not_use_render:b}=e,h=Sp(t),[y,w]=D(null),[_,R]=D(null),[I,T]=D(!1),A=qi(d),[L,F]=Dt({prop:r,defaultProp:i??!1,onChange:a,caller:Yi}),[N,j]=Dt({prop:s,defaultProp:c,onChange:l,caller:Yi}),x=B(null),U=B(N);V(()=>{const Z=v?y?.ownerDocument.getElementById(v):y?.form;if(Z instanceof HTMLFormElement){const ie=Oe(()=>j(U.current),"reset");return Z.addEventListener("reset",ie),()=>Z.removeEventListener("reset",ie)}},[v,y,j]);const q=y?!!v||!!y.closest("form"):!0,[$,E]=D(new Set),C=xt(),O=Array.from($).map(Z=>Z.props.value).join(";"),H=oe(Z=>{E(ie=>new Set(ie).add(Z))},[]),G=oe(Z=>{E(ie=>{const fe=new Set(ie);return fe.delete(Z),fe})},[]),ee={required:m,trigger:y,onTriggerChange:w,valueNode:_,onValueNodeChange:R,valueNodeHasChildren:I,onValueNodeHasChildrenChange:T,contentId:C,value:N,onValueChange:j,open:L,onOpenChange:F,dir:A,triggerPointerDownPosRef:x,disabled:f,name:u,autoComplete:p,form:v,nativeOptions:$,nativeSelectKey:O,isFormControl:q};return o(vc,{...h,children:o(BD,{scope:t,...ee,children:o(Ic.Provider,{scope:t,children:o(qD,{scope:t,onNativeOptionAdd:H,onNativeOptionRemove:G,children:Bb(b)?b(ee):n})})})})}Oe($b,"SelectProvider");var GD=Oe(e=>{const{__scopeSelect:t,children:n,...r}=e;return o($b,{__scopeSelect:t,...r,internal_do_not_use_render:({isFormControl:i})=>o(z,{children:[n,i?o(pL,{__scopeSelect:t}):null]})})},"Select"),HD="SelectTrigger",VD=W(Oe(function(t,n){const{__scopeSelect:r,disabled:i=!1,...a}=t,s=Sp(r),c=lr(HD,r),l=c.disabled||i,d=Se(n,c.onTriggerChange),u=wp(r),p=B("touch"),[f,m,v]=Rp(h=>{const y=u().filter(_=>!_.disabled),w=Ip(y,h,y.find(_=>_.value===c.value));w!==void 0&&c.onValueChange(w.value)}),b=Oe(h=>{l||(c.onOpenChange(!0),v()),h&&(c.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)})},"handleOpen");return o(eo,{asChild:!0,...s,children:o(ge.button,{type:"button",role:"combobox","aria-controls":c.open?c.contentId:void 0,"aria-expanded":c.open,"aria-required":c.required,"aria-autocomplete":"none",dir:c.dir,"data-state":c.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":no(c.value)?"":void 0,...a,ref:d,onClick:ne(a.onClick,h=>{h.currentTarget.focus(),p.current!=="mouse"&&b(h)}),onPointerDown:ne(a.onPointerDown,h=>{p.current=h.pointerType;const y=h.target;y.hasPointerCapture(h.pointerId)&&y.releasePointerCapture(h.pointerId),h.button===0&&h.ctrlKey===!1&&h.pointerType==="mouse"&&(b(h),h.preventDefault())}),onKeyDown:ne(a.onKeyDown,h=>{const y=f.current!=="";!(h.ctrlKey||h.altKey||h.metaKey)&&h.key.length===1&&m(h.key),!(y&&h.key===" ")&&OD.includes(h.key)&&(b(),h.preventDefault())})})})},"SelectTrigger")),KD="SelectValue",zD=W(Oe(function(t,n){const{__scopeSelect:r,className:i,style:a,children:s,placeholder:c="",...l}=t,d=lr(KD,r),{onValueNodeHasChildrenChange:u}=d,p=s!==void 0,f=Se(n,d.onValueNodeChange);Xe(()=>{u(p)},[u,p]);const m=no(d.value);return o(ge.span,{...l,asChild:m?!1:l.asChild,ref:f,style:{pointerEvents:"none"},children:o(z,{children:m?c:s},m?"placeholder":"value")})},"SelectValue")),WD=W(Oe(function(t,n){const{__scopeSelect:r,children:i,...a}=t;return o(ge.span,{"aria-hidden":!0,...a,ref:n,children:i||"▼"})},"SelectIcon")),[JD,YD]=Wr("SelectPortal",{forceMount:void 0}),XD=Oe(e=>{const{__scopeSelect:t,forceMount:n,...r}=e;return o(JD,{scope:e.__scopeSelect,forceMount:n,children:o(Ti,{asChild:!0,...r})})},"SelectPortal"),Jr="SelectContent",QD=W(Oe(function(t,n){const r=YD(Jr,t.__scopeSelect),{forceMount:i=r.forceMount,...a}=t,s=lr(Jr,t.__scopeSelect),[c,l]=D();return Xe(()=>{l(new DocumentFragment)},[]),o(Pt,{present:i||s.open,children:({present:d})=>d?o(tL,{...a,ref:n}):o(ZD,{...a,fragment:c})})},"SelectContent")),ZD=W(Oe(function(t,n){const{__scopeSelect:r,children:i,fragment:a}=t;return a?ln(o(jb,{scope:r,children:o(Ic.Slot,{scope:r,children:o("div",{ref:n,children:i})})}),a):null},"SelectContentFragment")),Zt=10,[jb,kc]=Wr(Jr),eL=dn("SelectContent.RemoveScroll"),tL=W(Oe(function(t,n){const{__scopeSelect:r}=t,{position:i="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:s,onPointerDownOutside:c,side:l,sideOffset:d,align:u,alignOffset:p,arrowPadding:f,collisionBoundary:m,collisionPadding:v,sticky:b,hideWhenDetached:h,avoidCollisions:y,...w}=t,_=lr(Jr,r),[R,I]=D(null),[T,A]=D(null),L=Se(n,I),[F,N]=D(null),[j,x]=D(null),U=wp(r),[q,$]=D(!1),E=B(!1);V(()=>{if(R)return ks(R)},[R]),Ei();const C=oe(ce=>{const[me,...J]=U().map(le=>le.ref.current),[se]=J.slice(-1),ye=document.activeElement;for(const le of ce)if(le===ye||(le?.scrollIntoView({block:"nearest"}),le===me&&T&&(T.scrollTop=0),le===se&&T&&(T.scrollTop=T.scrollHeight),le?.focus(),document.activeElement!==ye))return},[U,T]),O=oe(()=>C([F,R]),[C,F,R]);V(()=>{q&&O()},[q,O]);const{onOpenChange:H,triggerPointerDownPosRef:G}=_;V(()=>{if(R){let ce={x:0,y:0};const me=Oe(se=>{ce={x:Math.abs(Math.round(se.pageX)-(G.current?.x??0)),y:Math.abs(Math.round(se.pageY)-(G.current?.y??0))}},"handlePointerMove"),J=Oe(se=>{ce.x<=10&&ce.y<=10?se.preventDefault():se.composedPath().includes(R)||H(!1),document.removeEventListener("pointermove",me),G.current=null},"handlePointerUp");return G.current!==null&&(document.addEventListener("pointermove",me),document.addEventListener("pointerup",J,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",me),document.removeEventListener("pointerup",J,{capture:!0})}}},[R,H,G]),V(()=>{const ce=Oe(()=>H(!1),"close");return window.addEventListener("blur",ce),window.addEventListener("resize",ce),()=>{window.removeEventListener("blur",ce),window.removeEventListener("resize",ce)}},[H]);const[ee,Z]=Rp(ce=>{const me=U().filter(se=>!se.disabled),J=Ip(me,ce,me.find(se=>se.ref.current===document.activeElement));J&&setTimeout(()=>J.ref.current?.focus())}),ie=oe((ce,me,J)=>{const se=!E.current&&!J;(_.value!==void 0&&_.value===me||se)&&(N(ce),se&&(E.current=!0))},[_.value]),fe=oe(()=>R?.focus(),[R]),Ce=oe((ce,me,J)=>{const se=!E.current&&!J;(_.value!==void 0&&_.value===me||se)&&x(ce)},[_.value]),Pe=i==="popper"?Ob:nL,Ne=Pe===Ob?{side:l,sideOffset:d,align:u,alignOffset:p,arrowPadding:f,collisionBoundary:m,collisionPadding:v,sticky:b,hideWhenDetached:h,avoidCollisions:y}:{};return o(jb,{scope:r,content:R,viewport:T,onViewportChange:A,itemRefCallback:ie,selectedItem:F,onItemLeave:fe,itemTextRefCallback:Ce,focusSelectedItem:O,selectedItemText:j,position:i,isPositioned:q,searchRef:ee,children:o(Ea,{as:eL,allowPinchZoom:!0,children:o(vs,{asChild:!0,trapped:_.open,onMountAutoFocus:ce=>{ce.preventDefault()},onUnmountAutoFocus:ne(a,ce=>{_.trigger?.focus({preventScroll:!0}),ce.preventDefault()}),children:o(ki,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:c,onFocusOutside:ce=>ce.preventDefault(),onDismiss:()=>_.onOpenChange(!1),children:o(Pe,{role:"listbox",id:_.contentId,"data-state":_.open?"open":"closed",dir:_.dir,onContextMenu:ce=>ce.preventDefault(),...w,...Ne,onPlaced:()=>$(!0),ref:L,style:{display:"flex",flexDirection:"column",outline:"none",...w.style},onKeyDown:ne(w.onKeyDown,ce=>{const me=ce.ctrlKey||ce.altKey||ce.metaKey;if(ce.key==="Tab"&&ce.preventDefault(),!me&&ce.key.length===1&&Z(ce.key),["ArrowUp","ArrowDown","Home","End"].includes(ce.key)){let J=U().filter(se=>!se.disabled).map(se=>se.ref.current);if(["ArrowUp","End"].includes(ce.key)&&(J=J.slice().reverse()),["ArrowUp","ArrowDown"].includes(ce.key)){const se=ce.target,ye=J.indexOf(se);J=J.slice(ye+1)}setTimeout(()=>C(J)),ce.preventDefault()}})})})})})})},"SelectContentImpl")),nL=W(Oe(function(t,n){const{__scopeSelect:r,onPlaced:i,...a}=t,s=lr(Jr,r),c=kc(Jr,r),[l,d]=D(null),[u,p]=D(null),f=Se(n,p),m=wp(r),v=B(!1),b=B(!0),{viewport:h,selectedItem:y,selectedItemText:w,focusSelectedItem:_}=c,R=oe(()=>{if(s.trigger&&s.valueNode&&l&&u&&h&&y&&w){const L=s.trigger.getBoundingClientRect(),F=u.getBoundingClientRect(),N=s.valueNode.getBoundingClientRect(),j=w.getBoundingClientRect();if(s.dir!=="rtl"){const se=j.left-F.left,ye=N.left-se,le=L.left-ye,Ee=L.width+le,re=Math.max(Ee,F.width),Q=window.innerWidth-Zt,we=_p(ye,[Zt,Math.max(Zt,Q-re)]);l.style.minWidth=Ee+"px",l.style.left=we+"px"}else{const se=F.right-j.right,ye=window.innerWidth-N.right-se,le=window.innerWidth-L.right-ye,Ee=L.width+le,re=Math.max(Ee,F.width),Q=window.innerWidth-Zt,we=_p(ye,[Zt,Math.max(Zt,Q-re)]);l.style.minWidth=Ee+"px",l.style.right=we+"px"}const x=m(),U=window.innerHeight-Zt*2,q=h.scrollHeight,$=window.getComputedStyle(u),E=parseInt($.borderTopWidth,10),C=parseInt($.paddingTop,10),O=parseInt($.borderBottomWidth,10),H=parseInt($.paddingBottom,10),G=E+C+q+H+O,ee=Math.min(y.offsetHeight*5,G),Z=window.getComputedStyle(h),ie=parseInt(Z.paddingTop,10),fe=parseInt(Z.paddingBottom,10),Ce=L.top+L.height/2-Zt,Pe=U-Ce,Ne=y.offsetHeight/2,ce=y.offsetTop+Ne,me=E+C+ce,J=G-me;if(me<=Ce){const se=x.length>0&&y===x[x.length-1].ref.current;l.style.bottom="0px";const ye=u.clientHeight-h.offsetTop-h.offsetHeight,le=me+Math.max(Pe,Ne+(se?fe:0)+ye+O);l.style.height=le+"px"}else{const se=x.length>0&&y===x[0].ref.current;l.style.top="0px";const ye=Math.max(Ce,E+h.offsetTop+(se?ie:0)+Ne)+J;l.style.height=ye+"px",h.scrollTop=me-Ce+h.offsetTop}l.style.margin=`${Zt}px 0`,l.style.minHeight=ee+"px",l.style.maxHeight=U+"px",i?.(),requestAnimationFrame(()=>v.current=!0)}},[m,s.trigger,s.valueNode,l,u,h,y,w,s.dir,i]);Xe(()=>R(),[R]);const[I,T]=D();Xe(()=>{u&&T(window.getComputedStyle(u).zIndex)},[u]);const A=oe(L=>{L&&b.current===!0&&(R(),_?.(),b.current=!1)},[R,_]);return o(rL,{scope:r,contentWrapper:l,shouldExpandOnScrollRef:v,onScrollButtonChange:A,children:o("div",{ref:d,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:I},children:o(ge.div,{...a,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})},"SelectItemAlignedPosition")),Ob=W(Oe(function(t,n){const{__scopeSelect:r,align:i="start",collisionPadding:a=Zt,...s}=t,c=Sp(r);return o(yc,{...c,...s,ref:n,align:i,collisionPadding:a,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})},"SelectPopperPosition")),[rL,iL]=Wr(Jr,{}),Mb="SelectViewport",aL=W(Oe(function(t,n){const{__scopeSelect:r,nonce:i,...a}=t,s=kc(Mb,r),c=iL(Mb,r),l=Se(n,s.onViewportChange),d=B(0);return o(z,{children:[o("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:i}),o(Ic.Slot,{scope:r,children:o(ge.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:ne(a.onScroll,u=>{const p=u.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:m}=c;if(m?.current&&f){const v=Math.abs(d.current-p.scrollTop);if(v>0){const b=window.innerHeight-Zt*2,h=parseFloat(f.style.minHeight),y=parseFloat(f.style.height),w=Math.max(h,y);if(w<b){const _=w+v,R=Math.min(b,_),I=_-R;f.style.height=R+"px",f.style.bottom==="0px"&&(p.scrollTop=I>0?I:0,f.style.justifyContent="flex-end")}}}d.current=p.scrollTop})})})]})},"SelectViewport")),[VH,KH]=Wr("SelectGroup"),Cp="SelectItem",[oL,Fb]=Wr(Cp),sL=W(Oe(function(t,n){const{__scopeSelect:r,value:i,disabled:a=!1,textValue:s,...c}=t,l=lr(Cp,r),d=kc(Cp,r),u=l.value===i,[p,f]=D(s??""),[m,v]=D(!1),b=ht(R=>d.itemRefCallback?.(R,i,a)),h=Se(n,b),y=xt(),w=B("touch"),_=Oe(()=>{a||(l.onValueChange(i),l.onOpenChange(!1))},"handleSelect");return o(oL,{scope:r,value:i,disabled:a,textId:y,isSelected:u,onItemTextChange:oe(R=>{f(I=>I||(R?.textContent??"").trim())},[]),children:o(Ic.ItemSlot,{scope:r,value:i,disabled:a,textValue:p,children:o(ge.div,{role:"option","aria-labelledby":y,"data-highlighted":m?"":void 0,"aria-selected":u&&m,"data-state":u?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...c,ref:h,onFocus:ne(c.onFocus,()=>v(!0)),onBlur:ne(c.onBlur,()=>v(!1)),onClick:ne(c.onClick,()=>{w.current!=="mouse"&&_()}),onPointerUp:ne(c.onPointerUp,()=>{w.current==="mouse"&&_()}),onPointerDown:ne(c.onPointerDown,R=>{w.current=R.pointerType}),onPointerMove:ne(c.onPointerMove,R=>{w.current=R.pointerType,a?d.onItemLeave?.():w.current==="mouse"&&R.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ne(c.onPointerLeave,R=>{R.currentTarget===document.activeElement&&d.onItemLeave?.()}),onKeyDown:ne(c.onKeyDown,R=>{a||R.target!==R.currentTarget||d.searchRef?.current!==""&&R.key===" "||(MD.includes(R.key)&&_(),R.key===" "&&R.preventDefault())})})})})},"SelectItem")),Tc="SelectItemText",cL=W(Oe(function(t,n){const{__scopeSelect:r,className:i,style:a,...s}=t,c=lr(Tc,r),l=kc(Tc,r),d=Fb(Tc,r),u=UD(Tc,r),[p,f]=D(null),m=ht(_=>l.itemTextRefCallback?.(_,d.value,d.disabled)),v=Se(n,f,d.onItemTextChange,m),b=p?.textContent,h=Ie(()=>o("option",{value:d.value,disabled:d.disabled,children:b},d.value),[d.disabled,d.value,b]),{onNativeOptionAdd:y,onNativeOptionRemove:w}=u;return Xe(()=>(y(h),()=>w(h)),[y,w,h]),o(z,{children:[o(ge.span,{id:d.textId,...s,ref:v}),d.isSelected&&c.valueNode&&!c.valueNodeHasChildren&&!no(c.value)?ln(s.children,c.valueNode):null]})},"SelectItemText")),lL="SelectItemIndicator",dL=W(Oe(function(t,n){const{__scopeSelect:r,...i}=t;return Fb(lL,r).isSelected?o(ge.span,{"aria-hidden":!0,...i,ref:n}):null},"SelectItemIndicator")),uL="SelectBubbleInput",pL=W(Oe(function({__scopeSelect:t,...n},r){const i=lr(uL,t),{value:a,onValueChange:s,required:c,disabled:l,name:d,autoComplete:u,form:p}=i,{nativeOptions:f,nativeSelectKey:m}=i,v=B(null),b=Se(r,v),h=a??"",y=Lb(h),w=Array.from(f).some(_=>(_.props.value??"")==="");return V(()=>{const _=v.current;if(!_)return;const R=window.HTMLSelectElement.prototype,I=Object.getOwnPropertyDescriptor(R,"value").set;if(y!==h&&I){const T=new Event("change",{bubbles:!0});I.call(_,h),_.dispatchEvent(T)}},[y,h]),o(ge.select,{"aria-hidden":!0,required:c,tabIndex:-1,name:d,autoComplete:u,disabled:l,form:p,onChange:_=>s(_.target.value),...n,style:{...oy,...n.style},ref:b,defaultValue:h,children:[no(a)&&!w?o("option",{value:""}):null,Array.from(f)]},m)},"SelectBubbleInput"));function Bb(e){return typeof e=="function"}Oe(Bb,"isFunction");function no(e){return e===""||e===void 0}Oe(no,"shouldShowPlaceholder");function Rp(e){const t=ht(e),n=B(""),r=B(0),i=oe(s=>{const c=n.current+s;t(c),Oe((function l(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}),"updateSearch")(c)},[t]),a=oe(()=>{n.current="",window.clearTimeout(r.current)},[]);return V(()=>()=>window.clearTimeout(r.current),[]),[n,i,a]}Oe(Rp,"useTypeaheadSearch");function Ip(e,t,n){const r=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let a=qb(e,Math.max(i,0));r.length===1&&(a=a.filter(c=>c!==n));const s=a.find(c=>c.textValue.toLowerCase().startsWith(r.toLowerCase()));return s!==n?s:void 0}Oe(Ip,"findNextItem");function qb(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Oe(qb,"wrapArray");var Ub="__codemem-empty-select__";function fL(){return o("svg",{"aria-hidden":"true",fill:"none",height:"14",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",width:"14",children:[o("title",{children:"Open"}),o("path",{d:"m6 9 6 6 6-6"})]})}function mL(){return o("svg",{"aria-hidden":"true",fill:"none",height:"14",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",width:"14",children:[o("title",{children:"Selected"}),o("path",{d:"M20 6 9 17l-5-5"})]})}function kp(e){return e===""?Ub:e}function hL(e){return e===Ub?"":e}function dr({ariaLabel:e,className:t,contentClassName:n,disabled:r=!1,id:i,itemClassName:a,onValueChange:s,options:c,placeholder:l,triggerClassName:d,value:u,viewportClassName:p}){const f=u?kp(u):void 0;return o(GD,{disabled:r,onValueChange:m=>s(hL(m)),value:f,children:[o(VD,{"aria-label":e,className:d??t,"data-value":u,id:i,type:"button",children:[o(zD,{placeholder:l}),o(WD,{className:"sync-radix-select-icon","aria-hidden":"true",children:o(fL,{})})]}),o(XD,{children:o(QD,{className:n,position:"popper",children:o(aL,{className:p,children:c.map(m=>o(sL,{className:a,disabled:m.disabled,value:kp(m.value),children:[o(cL,{children:m.label}),o(dL,{className:"sync-radix-select-indicator",children:o(mL,{})})]},kp(m.value)))})})})]})}var gL=new Set(["BUTTON","A","SELECT"]),vL=new Set(["button","checkbox","color","file","image","radio","range","reset","submit"]);function yL(e){return!e||typeof e.closest!="function"?!1:e.closest('[data-primary-action-ignore="true"]')!==null}function bL(e){return e?!!(e instanceof HTMLTextAreaElement||"isContentEditable"in e&&e.isContentEditable):!1}function _L(e){return e?gL.has(e.tagName)?!0:e instanceof HTMLInputElement&&vL.has(e.type):!1}function wL(e){return e.metaKey||e.ctrlKey}function ro(e,t){if(t.disabled||e.defaultPrevented||e.isComposing||e.key!=="Enter"&&e.key!=="Escape")return;const n=e.target instanceof HTMLElement?e.target:null;if(!yL(n)){if(e.key==="Escape"){if(!t.onCancel)return;e.preventDefault(),t.onCancel();return}_L(n)||bL(n)&&!wL(e)||(e.preventDefault(),t.onSubmit())}}function SL({descriptionId:e,request:t}){const[n,r]=D("choice"),i=t.actors.find(y=>y.isLocal)?.actorId||t.actors[0]?.actorId||"",[a,s]=D(i),[c,l]=D("");V(()=>{r("choice");const y=t.actors.find(_=>_.isLocal)?.actorId||t.actors[0]?.actorId||"",w=t.actors.find(_=>_.actorId!==y)?.actorId||"";s(y),l(w)},[t]);const d=t.actors.find(y=>y.actorId===a)||t.actors[0],u=t.actors.filter(y=>y.actorId!==a),p=u.find(y=>y.actorId===c)||u[0],f=t.actors.map(y=>({label:o(z,{children:[y.label,y.isLocal?" (You)":""]}),value:y.actorId})),m=u.map(y=>({label:`${y.label}${y.isLocal?" (You)":""}`,value:y.actorId})),v=!!(d?.actorId&&p?.actorId),b=()=>{!d?.actorId||!p?.actorId||cr({action:"merge",primaryActorId:d.actorId,secondaryActorId:p.actorId})},h=y=>{const w=y.target instanceof HTMLElement?y.target:null;y.defaultPrevented||y.isComposing||y.key!=="Enter"||w?.closest(".sync-dialog-radio-list")&&v&&(y.preventDefault(),b())};return n==="choice"?o("div",{className:"sync-dialog-stack",children:o("ul",{className:"sync-dialog-choice-list",children:[o("li",{children:o("button",{autoFocus:!0,className:"settings-button","data-primary-action":"true","data-sync-primary-action":"true",onClick:()=>r("merge"),type:"button",children:"These are both me"})}),o("li",{children:o("button",{className:"settings-button",onClick:()=>cr({action:"different-people"}),type:"button",children:"These are different people"})}),o("li",{children:o("button",{className:"settings-button",onClick:()=>cr({action:"cancel"}),type:"button",children:"Decide later"})})]})}):o("div",{className:"sync-dialog-stack",onKeyDown:y=>{h(y),ro(y,{onSubmit:b,disabled:!v})},children:[o("div",{className:"small",id:e,children:"Choose which person should remain after combining these duplicates."}),o(AD,{ariaDescribedby:e,ariaLabel:"Person to keep after combining duplicates",autoFocusValue:a,indicatorClassName:"sync-dialog-radio-indicator",itemClassName:"sync-dialog-radio-option",itemLabelClassName:"sync-dialog-radio-label",name:"syncDuplicatePrimaryActor",onValueChange:s,options:f,rootClassName:"sync-dialog-radio-list",value:a}),o("div",{className:"field",children:[o("label",{className:"small",htmlFor:"syncDuplicateSecondaryActor",children:"Person to combine into the selected record"}),o(dr,{ariaLabel:"Person to combine into the selected record",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:m.length===0,id:"syncDuplicateSecondaryActor",itemClassName:"sync-radix-select-item",onValueChange:l,options:m,placeholder:"No merge target available",triggerClassName:"sync-radix-select-trigger sync-dialog-input",value:p?.actorId||"",viewportClassName:"sync-radix-select-viewport"})]}),o("div",{className:"sync-dialog-actions",children:[o("button",{className:"settings-button",onClick:()=>r("choice"),type:"button",children:"Back"}),o("button",{className:"settings-button","data-primary-action":"true",disabled:!v,onClick:b,type:"button",children:"Combine people"})]})]})}function CL({descriptionId:e,request:t,titleId:n}){const[r,i]=D(t.kind==="input"&&t.initialValue||""),[a,s]=D(null),c=t.kind!=="duplicate-person",l="syncDialogInputError";V(()=>{t.kind==="input"&&(i(t.initialValue||""),s(null))},[t]);const d=c&&t.cancelLabel||"Cancel",u=c?t.confirmLabel||(t.kind==="confirm"?"Confirm":"Save"):"Confirm",p=()=>{if(t.kind==="confirm"){cr(!0);return}if(t.kind==="duplicate-person")return;const f=r.trim(),m=t.validate?.(f)||null;if(m){s(m);return}cr(f)};return o("div",{className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:n,children:t.title}),o(Lr,{ariaLabel:`Close ${t.title}`,onClick:()=>cr(t.kind==="confirm"?!1:null)})]}),o("div",{className:"modal-body",children:[t.kind!=="duplicate-person"?o("div",{className:"small",id:e,children:t.description}):null,t.kind==="duplicate-person"?o("div",{className:"small",id:e,children:t.summary}):null,t.kind==="input"?o("div",{className:"field",children:[t.suggestions?.length?o(dD,{"aria-describedby":a?`${e} ${l}`:e,autoFocus:!0,className:a?"sync-dialog-input sync-field-error":"sync-dialog-input","data-sync-primary-action":"true",onSubmit:p,onValueChange:f=>{i(f),a&&s(null)},placeholder:t.placeholder,suggestions:t.suggestions,value:r}):o(ke,{"aria-describedby":a?`${e} ${l}`:e,autoFocus:!0,className:a?"sync-dialog-input sync-field-error":"sync-dialog-input","data-sync-primary-action":"true",onInput:f=>{i(f.currentTarget.value),a&&s(null)},onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),p())},placeholder:t.placeholder,type:"text",value:r}),a?o("div",{className:"sync-field-hint",id:l,children:a}):null]}):null,t.kind==="duplicate-person"?o(SL,{descriptionId:e,request:t}):null]}),o("div",{className:"modal-footer",children:[o("div",{className:"small"}),o("div",{className:"sync-dialog-actions",children:[o("button",{className:"settings-button","data-sync-dialog-action":"cancel",onClick:()=>cr(t.kind==="confirm"?!1:null),type:"button",children:d}),t.kind!=="duplicate-person"?o("button",{autoFocus:!0,className:`settings-button ${lD(t.kind==="confirm"?t.tone:void 0)}`,"data-sync-dialog-action":"confirm",onClick:p,type:"button",children:u}):null]})]})]})}function RL(){const[e,t]=D(oD());V(()=>(Tb(t),()=>{sD(t)&&Tb(null)}),[]);const n=!!e,r=Ie(()=>`sync-dialog-title-${e?.kind||"none"}`,[e?.kind]),i=Ie(()=>`sync-dialog-description-${e?.kind||"none"}`,[e?.kind]);return e?o(Ln,{ariaDescribedby:i,ariaLabelledby:r,contentClassName:"modal",contentId:"syncDialog",onInteractOutside:l=>{const d=l.detail?.originalEvent?.target;d instanceof Element&&d.closest(".autocomplete-popover")&&l.preventDefault()},onOpenAutoFocus:l=>{const d=document.querySelector('#syncDialog [data-sync-primary-action="true"]');if(e?.kind==="input"&&d){l.preventDefault(),d.focus();return}const u=(e?.kind==="confirm"?e.autoFocusAction??"confirm":"confirm")==="cancel"?'#syncDialog [data-sync-dialog-action="cancel"]':'#syncDialog [data-sync-dialog-action="confirm"]',p=document.querySelector(u);p&&(l.preventDefault(),p.focus())},onOpenChange:l=>{l||cr(e?.kind==="confirm"?!1:null)},open:n,overlayClassName:"modal-backdrop",overlayId:"syncDialogBackdrop",children:e?o(CL,{descriptionId:i,request:e,titleId:r}):null}):null}var Yr=null;function Pc(){Yr?.isConnected||(Yr=document.getElementById("syncDialogMount"),Yr||(Yr=document.createElement("div"),Yr.id="syncDialogMount",document.body.appendChild(Yr)),Ue(o(RL,{}),Yr))}function vn(e){return Pc(),vp("confirm")?new Promise(t=>{gp(n=>t(!!n)),Sc({kind:"confirm",...e})}):Promise.resolve(!1)}function Tp(e){return Pc(),vp("input")?new Promise(t=>{gp(n=>t(typeof n=="string"?n:null)),Sc({kind:"input",...e})}):Promise.resolve(null)}function IL(e){return Pc(),vp("duplicate-person")?new Promise(t=>{gp(n=>t(n||{action:"cancel"})),Sc({kind:"duplicate-person",...e})}):Promise.resolve(cD({kind:"duplicate-person",...e}))}function kL(e){return e.readiness==="ready"?null:"Legacy Space management needs the coordinator URL, target group, and admin secret before it can list Spaces or change transport memberships."}function TL(e){const t=String(e||"active").trim();return t?t.replaceAll("_"," "):"active"}function Gb(e){const t=String(e.label||"").trim()||"Untitled Space",n=TL(e.status),r=String(e.kind||"user").replaceAll("_"," "),i=String(e.scope_id||"").trim()||"unknown",a=e.membership_epoch==null?"—":String(e.membership_epoch);return{title:t,summary:`${n} Space · ${r}`,advancedDetail:`Space ID ${i} · Membership epoch ${a}`}}function PL(e){const t={active:"Space access active",revoked:"Space access revoked",not_member:"No Space access"},n=e.role.replaceAll("_"," "),r=e.status==="not_member"?t[e.status]:`${t[e.status]} · ${n}`,i=e.membershipEpoch==null?"—":String(e.membershipEpoch);return{statusLabel:t[e.status],detail:r,advancedDetail:`Device ID ${e.deviceId} · Membership epoch ${i}`}}function NL(e,t,n){return`Revoke ${t||"this device"} from ${Gb(e).title}?`}function EL(e,t,n=ec()){const r=tc(e,n),i=new Map(t.map(a=>[String(a.device_id||"").trim(),a]).filter(([a])=>a.length>0));return e.map(a=>{const s=String(a.device_id||"").trim();if(!s)return null;const c=i.get(s),l=String(c?.status||"").trim(),d=c?l==="revoked"?"revoked":"active":"not_member",u=typeof c?.membership_epoch=="number"&&Number.isFinite(c.membership_epoch)?Math.trunc(c.membership_epoch):null;return{deviceId:s,displayName:r.get(s)||"Unnamed device",enabled:a.enabled!==!1&&a.enabled!==0,status:d,role:String(c?.role||"member"),membershipEpoch:u,updatedAt:c?.updated_at?String(c.updated_at):null}}).filter(a=>a!==null).sort((a,s)=>{const c={active:0,revoked:1,not_member:2};return c[a.status]-c[s.status]||a.displayName.localeCompare(s.displayName,void 0,{numeric:!0})})}function AL(e,t,n,r){const i=String(n||"").trim();return r||e.length>0||!i?e:t.filter(a=>String(a.group_id||"").trim()===i)}var zH=8;function xL(){return{loaded:!1,loading:!1,availability:"unknown",error:"",includeInactive:!1,devicesLoaded:!1,scopes:[],membersByScope:new Map,memberAvailabilityByScope:new Map,devices:[],createScopeId:"",createLabel:"",createKind:"team",createPanelOpen:!1,actionPendingKey:"",actionPendingKind:"",loadGeneration:0,recoveryAnnouncement:"",recoveryFocusPending:!1,recoveryRetryRequested:!1}}function Nc(e){if(!e||typeof e!="object")throw new Error("Invalid list payload");const t=e.items;if(!Array.isArray(t))throw new Error("Invalid list payload");return t}function qe(e){let t=P.groupScopeManagementDrafts.get(e);return t||(t=xL(),P.groupScopeManagementDrafts.set(e,t)),t}function Ke(e,t){P.groupScopeManagementDrafts.set(e,t)}function Pp(e,t){const n=e instanceof Error?e.message:"";return n.includes("group_archived")||n.includes("Group is archived")?"Restore this legacy coordinator group before changing Space access.":n.includes("group_not_found")||n.includes("Group not found")?"This legacy coordinator group no longer exists. Refresh Advanced administration.":n.includes("scope_not_found")||n.includes("Scope not found")?"This Space no longer exists. Refresh legacy Spaces before retrying.":n.includes("scope_not_active")||n.includes("Scope is not active")?"Restore this legacy Space before changing its access.":n.includes("scopeId already exists")?"A Space already uses that ID. Choose a different Space ID or refresh legacy Spaces. Sharing policy is unchanged.":n.includes("device_not_enrolled_for_scope_group")||n.includes("device must be enrolled")?"This device is no longer enrolled in the legacy coordinator group. Refresh devices before retrying.":n.includes("membership_not_found")?"This device no longer has access to the Space. Refresh legacy Spaces.":t}function io(){X("Coordinator data changed or is refreshing. Wait for recovery to finish, then try again.","warning")}function Xi(e,t){return e.availability==="fresh"&&!e.loading&&(!t||e.memberAvailabilityByScope.get(t)==="fresh")&&Mn(P.recovery,"status","groups")}async function DL(e,t,n){const r=new Array(e.length);let i=0;async function a(){for(;i<e.length;){const s=i++;r[s]=await n(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>a())),r}async function Xr(e,t,n=qe(e).includeInactive){const r=qe(e),i=r.loadGeneration+1;Ke(e,{...r,loading:!0,error:"",includeInactive:n,loadGeneration:i,recoveryAnnouncement:r.recoveryRetryRequested?r.recoveryAnnouncement:""});const a=()=>P.groupScopeManagementDrafts.get(e)?.loadGeneration===i;t();try{const[l,d]=await Promise.all([mR(e,n),Hm(e,!0)]);if(!a())return;const u=Nc(l),p=Nc(d),f=await DL(u.slice(0,8),4,async w=>{const _=String(w.scope_id||"").trim();if(!_)return{scopeId:_,attempted:!0,members:[]};try{return{scopeId:_,attempted:!0,members:Nc(await Gm(e,_,!0))}}catch{return{scopeId:_,attempted:!0}}});if(!a())return;const m=qe(e),v=[...f,...u.slice(8).map(w=>({scopeId:String(w.scope_id||"").trim(),attempted:!1}))],b=new Map,h=new Map;for(const w of v){if(!w.scopeId)continue;if(w.members){b.set(w.scopeId,w.members),h.set(w.scopeId,"fresh");continue}const _=m.membersByScope.get(w.scopeId),R=m.memberAvailabilityByScope.get(w.scopeId);_&&(R==="fresh"||R==="stale")?(b.set(w.scopeId,_),h.set(w.scopeId,"stale")):h.set(w.scopeId,w.attempted?"unavailable":"deferred")}const y=v.filter(w=>w.attempted&&w.scopeId&&!w.members).length;Ke(e,{...m,loaded:!0,loading:!1,availability:"fresh",recoveryAnnouncement:y?"":m.recoveryAnnouncement,error:y?`Membership details could not be refreshed for ${y} ${y===1?"Space":"Spaces"}. Successfully loaded Space data remains available.`:"",includeInactive:n,devicesLoaded:!0,scopes:u,devices:p,membersByScope:b,memberAvailabilityByScope:h,actionPendingKey:"",actionPendingKind:""})}catch{if(!a())return;const l=qe(e),d=l.availability==="fresh"||l.availability==="stale";Ke(e,{...l,availability:d?"stale":"unavailable",loading:!1,recoveryAnnouncement:"",error:d?"Legacy Spaces could not be refreshed. Previously loaded Space and membership details are still shown.":"Legacy Spaces are unavailable. No empty Space list is being assumed."})}if(!a())return;const s=qe(e);if(s.recoveryRetryRequested&&s.availability==="fresh"&&![...s.memberAvailabilityByScope.values()].some(l=>l==="stale"||l==="unavailable")){const l=[...s.memberAvailabilityByScope.values()].filter(d=>d==="deferred").length;Ke(e,{...s,recoveryAnnouncement:l?`Spaces refreshed. Membership details for ${l} ${l===1?"Space":"Spaces"} can be loaded on demand.`:"Spaces and membership details refreshed.",recoveryFocusPending:!0,recoveryRetryRequested:!1})}else s.recoveryRetryRequested&&Ke(e,{...s,recoveryAnnouncement:"Retry finished, but some Space data still needs attention. Retained details remain unchanged.",recoveryFocusPending:!0,recoveryRetryRequested:!1});t();const c=qe(e);c.recoveryFocusPending&&(Ke(e,{...c,recoveryFocusPending:!1}),queueMicrotask(()=>document.getElementById(`coordinatorAdminSpacesStatus-${e}`)?.focus()))}function Np(e,t){P.groupScopeManagementOpen.add(e),qe(e),t(),Xr(e,t)}function Hb(e,t){P.groupScopeManagementOpen.delete(e),t()}async function LL(e,t,n){const r=qe(e);if(!Xi(r)){io();return}if(r.actionPendingKey)return;const i=r.loadGeneration,a=P.loadGeneration;Ke(e,{...r,actionPendingKey:`load:${t}`,actionPendingKind:"load"}),n();try{const s=await Gm(e,t,!0),c=qe(e);if(c.loadGeneration!==i||P.loadGeneration!==a||!Xi(c)){c.actionPendingKey===`load:${t}`&&(Ke(e,{...c,actionPendingKey:"",actionPendingKind:""}),n()),io();return}const l=new Map(c.membersByScope);l.set(t,Nc(s));const d=new Map(c.memberAvailabilityByScope);d.set(t,"fresh"),Ke(e,{...c,membersByScope:l,memberAvailabilityByScope:d,actionPendingKey:"",actionPendingKind:"",error:""})}catch{const s=qe(e);if(s.loadGeneration!==i)return;const c=new Map(s.memberAvailabilityByScope);c.set(t,s.membersByScope.has(t)?"stale":"unavailable"),Ke(e,{...s,memberAvailabilityByScope:c,actionPendingKey:"",actionPendingKind:"",error:"Membership details could not be loaded. Existing Space data is unchanged."})}n()}async function $L(e,t){const n=qe(e);if(!Xi(n)){io();return}if(n.actionPendingKey)return;const r=n.createScopeId.trim(),i=n.createLabel.trim(),a=n.createKind.trim()||"team";if(!r||!i){X("Enter a Space ID and label before creating a Space.","warning");return}Ke(e,{...n,actionPendingKey:`create:${r}`,actionPendingKind:"create",error:""}),t();try{await hR(e,{scope_id:r,label:i,kind:a});const s=qe(e);Ke(e,{...s,createScopeId:"",createLabel:"",createKind:"team",createPanelOpen:!1,actionPendingKey:"",actionPendingKind:""}),X("Space created. Grant devices explicitly before data can sync."),await Xr(e,t,s.includeInactive),queueMicrotask(()=>document.getElementById(`coordinatorAdminCreateSpaceTrigger-${e}`)?.focus())}catch(s){Ke(e,{...qe(e),actionPendingKey:"",actionPendingKind:"",error:Pp(s,"Could not create the legacy Space. Sharing policy is unchanged; retry after coordinator recovery.")}),t()}}async function jL(e,t,n,r){const i=qe(e);if(!Xi(i,t)){io();return}const a=`grant:${t}:${n}`;if(!i.actionPendingKey){Ke(e,{...i,actionPendingKey:a,actionPendingKind:"grant",error:""}),r();try{await gR(e,t,{device_id:n,role:"member"});const s=qe(e);Ke(e,{...s,actionPendingKey:"",actionPendingKind:""}),X("Device granted access to the Space."),await Xr(e,r,s.includeInactive)}catch(s){Ke(e,{...qe(e),actionPendingKey:"",actionPendingKind:"",error:Pp(s,"Could not grant legacy Space transport access. Sharing policy is unchanged; retry after coordinator recovery.")}),r()}}}async function OL(e,t,n,r,i){const a=String(t.scope_id||"").trim();if(!a)return;const s=qe(e);if(!Xi(s,a)){io();return}const c=s.loadGeneration,l=P.loadGeneration;if(!await vn({title:NL(t,r,n),description:"Revocation blocks future sync for this Space. It does not remove data already copied to the revoked device; offline devices, backups, copied databases, malicious peers, or old versions may retain data.",confirmLabel:"Revoke membership",cancelLabel:"Keep membership",tone:"danger"}))return;const d=qe(e),u=d.scopes.find(m=>String(m.scope_id||"").trim()===a),p=d.membersByScope.get(a)?.find(m=>String(m.device_id||"")===n&&String(m.status||"active")==="active");if(d.loadGeneration!==c||P.loadGeneration!==l||!Xi(d,a)||!u||!p||d.actionPendingKey){X("Space membership data changed while confirmation was open. Review current access and try again.","warning");return}const f=`revoke:${a}:${n}`;Ke(e,{...d,actionPendingKey:f,actionPendingKind:"revoke",error:""}),i();try{await vR(e,a,n);const m=qe(e);Ke(e,{...m,actionPendingKey:"",actionPendingKind:""}),X("Space access revoked. Future sync is blocked for that device."),await Xr(e,i,m.includeInactive)}catch(m){Ke(e,{...qe(e),actionPendingKey:"",actionPendingKind:"",error:Pp(m,"Could not revoke legacy Space transport access. Sharing policy is unchanged; retry after coordinator recovery.")}),i()}}function ML(e,t,n,r,i){const a=String(t.scope_id||"").trim(),s=Ot(P.devicesSnapshotTarget)?S.lastCoordinatorAdminDevices:[],c=AL(n.devices,s,e,n.devicesLoaded),l=EL(c,n.membersByScope.get(a)??[],P.unnamedDeviceAliases);return l.length?g("div",{class:"coordinator-admin-scope-member-list"},l.map(d=>{const u=`${n.actionPendingKind}:${a}:${d.deviceId}`,p=n.actionPendingKey===u,f=d.enabled&&d.status!=="active",m=d.status==="active",v=PL(d);return g("div",{class:"coordinator-admin-scope-member-row",key:d.deviceId},g("div",{class:"coordinator-admin-scope-member-copy"},g("strong",null,d.displayName),g("span",null,v.detail),g("details",{class:"coordinator-admin-diagnostics"},g("summary",null,"Diagnostics"),g("span",{class:"peer-meta"},v.advancedDetail)),d.enabled?null:g("span",null,"Device is disabled in this coordinator group.")),g("div",{class:"peer-actions"},f?g("button",{class:"settings-button",disabled:!r||!!n.actionPendingKey,onClick:()=>{jL(e,a,d.deviceId,i)},type:"button"},p&&n.actionPendingKind==="grant"?"Granting…":"Grant access"):null,m?g("button",{class:"settings-button danger",disabled:!r||!!n.actionPendingKey,onClick:()=>{OL(e,t,d.deviceId,d.displayName,i)},type:"button"},p&&n.actionPendingKind==="revoke"?"Revoking…":"Revoke access"):null))})):g("div",{class:"peer-submeta coordinator-admin-empty-state",role:"status"},"No devices are enrolled in this coordinator group yet. Enroll a device before granting this Space.")}function FL(e,t,n,r,i){const a=String(t.scope_id||"").trim(),s=Gb(t),c=n.memberAvailabilityByScope.get(a),l=n.actionPendingKey===`load:${a}`,d=c==="stale"||c==="unavailable"||c==="deferred";return g("div",{class:"peer-card peer-card--padded coordinator-admin-scope-card",key:a||s.title},g("div",{class:"peer-title"},g("h5",{class:"coordinator-admin-card-title"},s.title),g("span",{class:"badge actor-badge"},"Legacy Space")),g("div",{class:"peer-submeta"},s.summary),g("details",{class:"coordinator-admin-diagnostics"},g("summary",null,"Diagnostics"),g("div",{class:"peer-meta"},s.advancedDetail)),g("div",{class:"peer-submeta"},"Devices below are enrolled in the coordinator group; only active Space members can sync this transport boundary."),c==="stale"?g("div",{class:"peer-submeta coordinator-admin-inline-warning",role:"status"},"Membership refresh failed for this Space. Previously loaded memberships are shown and changes are disabled."):c==="unavailable"?g("div",{class:"peer-submeta coordinator-admin-inline-warning",role:"status"},"Membership details are unavailable for this Space. No empty membership list is being assumed."):c==="deferred"?g("div",{class:"peer-submeta coordinator-admin-inline-warning",role:"status"},"Membership details were deferred to keep this large Space list bounded. Load them before changing access."):null,d?g("button",{class:"settings-button",disabled:!!n.actionPendingKey,onClick:()=>{LL(e,a,i)},type:"button"},l?"Loading membership…":c==="stale"?"Refresh membership":"Load membership"):null,c==="unavailable"||c==="deferred"?null:ML(e,t,n,r&&c==="fresh",i))}function Ep(e,t,n){const r=[...t.memberAvailabilityByScope.values()].filter(s=>s==="stale"||s==="unavailable").length,i=t.availability==="stale"||t.availability==="unavailable"||r>0,a=()=>{const s=qe(e);s.loading||s.actionPendingKey||(Ke(e,{...s,recoveryAnnouncement:"Retrying Spaces and membership details…",recoveryRetryRequested:!0}),Xr(e,n,s.includeInactive))};return g("div",{"aria-atomic":"true","aria-live":"polite",class:i?"coordinator-admin-inline-warning coordinator-admin-recovery-notice":t.recoveryAnnouncement?"peer-meta coordinator-admin-recovery-status":"coordinator-admin-recovery-status",id:`coordinatorAdminSpacesStatus-${e}`,role:"status",tabIndex:-1},i?g(z,null,g("div",{class:"coordinator-admin-legacy-notice-copy"},g("h4",{class:"coordinator-admin-drawer-title"},"Spaces need attention"),t.recoveryAnnouncement?g("p",{class:"peer-submeta"},t.recoveryAnnouncement):null,g("p",{class:"peer-submeta"},t.availability==="unavailable"?"Current Space data could not be loaded. No empty result is being shown, and no data loss is implied.":t.availability==="stale"?"Previously loaded Spaces are shown. Mutations are disabled until a retry succeeds.":`Membership details need recovery for ${r} ${r===1?"Space":"Spaces"}. Successfully loaded Spaces remain current.`)),g("button",{class:"settings-button",disabled:t.loading||!!t.actionPendingKey,onClick:a,type:"button"},t.loading?"Retrying…":"Retry")):t.recoveryAnnouncement)}function BL(e){const{groupId:t,ready:n,summary:r,renderShell:i}=e,a=P.groupScopeManagementDrafts.get(t);if(!a)return null;const s=kL(r);if(s)return g("div",{class:"peer-meta coordinator-admin-inline-warning"},s);if(a.availability==="unavailable")return g(z,null,g("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),g("div",{class:"peer-submeta"},"Coordinator groups discover and enroll devices. Spaces are technical transport boundaries here. These controls do not manage policy Team membership or Project access in Sharing."),Ep(t,a,i));if(!a.loaded)return g(z,null,g("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),g("div",{class:"peer-submeta"},"Coordinator groups discover and enroll devices. Spaces are technical transport boundaries here. These controls do not manage policy Team membership or Project access in Sharing."),Ep(t,a,i),g("div",{"aria-live":"polite",class:"peer-submeta",role:"status"},"Loading Spaces…"));const c=!n||a.availability!=="fresh"||!!a.actionPendingKey||a.loading,l=a.loading||!!a.actionPendingKey,d=`coordinatorAdminCreateSpacePanel-${t}`,u=`coordinatorAdminCreateSpaceTrigger-${t}`,p=`coordinatorAdminCreateSpaceId-${t}`;return g(z,null,g("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),g("div",{class:"peer-submeta"},"Coordinator groups discover and enroll devices. Spaces are technical transport boundaries here. These controls do not manage policy Team membership or Project access in Sharing."),Ep(t,a,i),g(Ya,{onOpenChange:f=>{Ke(t,{...qe(t),createPanelOpen:f}),i(),f&&queueMicrotask(()=>document.getElementById(p)?.focus())},open:a.createPanelOpen},g(z,null,g("div",{class:"section-actions coordinator-admin-space-toolbar"},g("label",{class:"coordinator-admin-inline-filter"},g("span",{class:"section-meta",id:`coord-admin-domain-inactive-${t}`},"Show inactive Spaces"),g(Ji,{"aria-labelledby":`coord-admin-domain-inactive-${t}`,checked:a.includeInactive,className:"coordinator-admin-switch",disabled:l,onCheckedChange:f=>{qe(t).actionPendingKey||Xr(t,i,f)},thumbClassName:"coordinator-admin-switch-thumb"})),g("div",{class:"peer-actions"},g("button",{class:"settings-button",disabled:l,onClick:()=>{qe(t).actionPendingKey||Xr(t,i,a.includeInactive)},type:"button"},a.loading?"Refreshing…":"Refresh"),g(zu,{"aria-controls":d,"aria-expanded":a.createPanelOpen,class:"settings-button coordinator-admin-scope-trigger",id:u,type:"button"},"Create legacy Space"))),g(Xa,{"aria-busy":a.actionPendingKind==="create"?"true":"false","aria-labelledby":u,class:"coordinator-admin-create-space-panel",forceMount:!0,id:d},g("form",{class:"coordinator-admin-form",onSubmit:f=>{f.preventDefault(),!c&&$L(t,i)}},g("p",{class:"peer-submeta"},"Create a Space only for legacy transport or recovery. Team membership and Project access stay in Sharing."),g("div",{class:"coordinator-admin-form-grid"},g("label",{class:"coordinator-admin-field"},g("span",null,"Space ID"),g(ke,{class:"peer-scope-input",disabled:c,id:p,onInput:f=>{const m=qe(t);Ke(t,{...m,createScopeId:String(f.currentTarget.value||"")})},placeholder:"acme-work",type:"text",value:a.createScopeId})),g("label",{class:"coordinator-admin-field"},g("span",null,"Label"),g(ke,{class:"peer-scope-input",disabled:c,onInput:f=>{const m=qe(t);Ke(t,{...m,createLabel:String(f.currentTarget.value||"")})},placeholder:"Acme Work",type:"text",value:a.createLabel})),g("label",{class:"coordinator-admin-field"},g("span",null,"Kind"),g(ke,{class:"peer-scope-input",disabled:c,onInput:f=>{const m=qe(t);Ke(t,{...m,createKind:String(f.currentTarget.value||"")})},placeholder:"team",type:"text",value:a.createKind}))),g("div",{class:"peer-actions"},g("button",{class:"settings-button",disabled:c,type:"submit"},a.actionPendingKind==="create"?"Creating…":"Create Space")))))),a.error?g("div",{"aria-live":"assertive",class:"peer-submeta coordinator-admin-error",role:"alert"},a.error):null,a.scopes.length?g("div",{class:"coordinator-admin-scope-card-list"},a.scopes.map(f=>FL(t,f,a,n&&a.availability==="fresh"&&!a.loading,i))):g("div",{class:"peer-meta coordinator-admin-empty-state",role:"status"},"No Spaces are defined for this coordinator group yet. Create a Space only for legacy transport or recovery, then grant specific devices. Sharing policy remains separate."))}function Vb(){return g("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},g("title",null,"Chevron"),g("path",{d:"m9 18 6-6-6-6"}))}function qL(){return{projects_include:[],projects_exclude:[],auto_seed_scope:!0,default_space_scope_id:"",auto_grant_default_space_on_join:!1,loaded:!1,loading:!1,availability:"unknown",loadGeneration:0,recoveryAnnouncement:"",recoveryFocusPending:!1,recoveryRetryRequested:!1,saving:!1,error:""}}async function Kb(e,t){const n=P.groupPreferencesDrafts.get(e)??qL(),r=n.loadGeneration+1;P.groupPreferencesDrafts.set(e,{...n,loading:!0,error:"",loadGeneration:r,recoveryAnnouncement:n.recoveryRetryRequested?n.recoveryAnnouncement:""});const i=()=>P.groupPreferencesDrafts.get(e)?.loadGeneration===r;t();try{const s=await OI(e);if(!i())return;const c=P.groupPreferencesDrafts.get(e)??n;P.groupPreferencesDrafts.set(e,{...c,projects_include:Array.isArray(s.projects_include)?[...s.projects_include]:[],projects_exclude:Array.isArray(s.projects_exclude)?[...s.projects_exclude]:[],auto_seed_scope:s.auto_seed_scope,default_space_scope_id:s.default_space_scope_id||"",auto_grant_default_space_on_join:s.auto_grant_default_space_on_join===!0,loaded:!0,loading:!1,availability:"fresh",saving:!1,error:"",recoveryAnnouncement:c.recoveryRetryRequested?"Group defaults refreshed. Current values are available.":c.recoveryAnnouncement,recoveryFocusPending:c.recoveryRetryRequested,recoveryRetryRequested:!1})}catch{if(!i())return;const s=P.groupPreferencesDrafts.get(e)??n,c=s.availability==="fresh"||s.availability==="stale",l=s.recoveryRetryRequested;P.groupPreferencesDrafts.set(e,{...s,loading:!1,availability:c?"stale":"unavailable",recoveryAnnouncement:l?"Retry finished, but group defaults are still unavailable. Retained values remain unchanged.":"",recoveryFocusPending:l,recoveryRetryRequested:!1,error:c?"Legacy group defaults could not be refreshed. Previously loaded values are still shown.":"Legacy group defaults are unavailable. No default values are being assumed."})}t();const a=P.groupPreferencesDrafts.get(e);a?.recoveryFocusPending&&(P.groupPreferencesDrafts.set(e,{...a,recoveryFocusPending:!1}),queueMicrotask(()=>document.getElementById(`coord-admin-group-defaults-recovery-${e}`)?.focus()))}async function Ap(e,t){P.groupPreferencesOpen.add(e),t(),await Kb(e,t)}function Ec(e,t){P.groupPreferencesOpen.delete(e),t()}function zb(e,t){const n=P.groupPreferencesDrafts.get(e);n&&(P.groupPreferencesDrafts.set(e,{...n,recoveryAnnouncement:"Retrying group defaults…",recoveryRetryRequested:!0}),Kb(e,t))}async function UL(e,t){const n=P.groupPreferencesDrafts.get(e);if(!n||n.availability!=="fresh"||n.loading||!Mn(P.recovery,"status","groups")||n.saving)return;const r={projects_include:n.projects_include.length>0?[...n.projects_include]:null,projects_exclude:n.projects_exclude.length>0?[...n.projects_exclude]:null,auto_seed_scope:n.auto_seed_scope,default_space_scope_id:n.default_space_scope_id||null,auto_grant_default_space_on_join:n.auto_grant_default_space_on_join};P.groupPreferencesDrafts.set(e,{...n,saving:!0,error:""}),t();try{await MI(e,r),X("Legacy coordinator group defaults saved. Sharing policy and Project access are unchanged."),Ec(e,t)}catch{const i=P.groupPreferencesDrafts.get(e);if(!i)return;P.groupPreferencesDrafts.set(e,{...i,saving:!1,error:"Could not save legacy group defaults. Sharing policy is unchanged; retry after coordinator recovery."}),t()}}function GL(e,t,n){const r=P.groupPreferencesDrafts.get(e);if(!r)return null;const i=`coord-admin-group-defaults-recovery-${e}`;if(!r.loaded&&r.availability!=="unavailable")return g(z,null,g("h4",{class:"coordinator-admin-drawer-title"},"Legacy group defaults"),g("div",{"aria-atomic":"true","aria-live":"polite",id:i,role:"status",tabIndex:-1},"Loading project defaults…"));if(r.availability==="unavailable")return g(z,null,g("h4",{class:"coordinator-admin-drawer-title"},"Legacy group defaults"),g("div",{"aria-atomic":"true","aria-live":"polite",class:"coordinator-admin-inline-warning coordinator-admin-recovery-notice",id:i,role:"status",tabIndex:-1},g("div",{class:"coordinator-admin-legacy-notice-copy"},g("strong",null,"Group defaults are unavailable"),r.recoveryAnnouncement?g("span",{class:"peer-submeta"},r.recoveryAnnouncement):null,g("span",{class:"peer-submeta"},"Current values could not be loaded. No defaults are being assumed or changed.")),g("button",{class:"settings-button",disabled:r.loading,onClick:()=>zb(e,t),type:"button"},r.loading?"Retrying…":"Retry")));const a=`coord-admin-scope-autoseed-${e}`,s=`coord-admin-default-space-autogrant-${e}`,c=`coord-admin-scope-include-${e}`,l=`coord-admin-scope-exclude-${e}`,d=n&&r.availability==="fresh"&&!r.loading,u=!d||r.saving||!r.auto_seed_scope;return g(z,null,g("h4",{class:"coordinator-admin-drawer-title"},"Legacy group defaults"),g("div",{"aria-atomic":"true","aria-live":"polite",class:r.availability==="stale"?"coordinator-admin-inline-warning coordinator-admin-recovery-notice":"coordinator-admin-recovery-status",id:i,role:"status",tabIndex:-1},r.availability==="stale"?g(z,null,g("span",{class:"peer-submeta"},"Previously loaded group defaults are shown. Saving is disabled until refresh succeeds."),r.recoveryAnnouncement?g("span",{class:"peer-submeta"},r.recoveryAnnouncement):null,g("button",{class:"settings-button",disabled:r.loading,onClick:()=>zb(e,t),type:"button"},r.loading?"Retrying…":"Retry")):r.recoveryAnnouncement),g("div",{class:"peer-submeta"},"Space access grants decide what new devices can sync. Advanced sharing rules only narrow future writes after Space access already exists."),g("label",{class:"coordinator-admin-inline-filter"},g("span",{class:"section-meta",id:a},"Auto-apply advanced rules to new devices"),g(Ji,{"aria-labelledby":a,checked:r.auto_seed_scope,className:"coordinator-admin-switch",disabled:!d||r.saving,onCheckedChange:p=>{const f=P.groupPreferencesDrafts.get(e)??r;P.groupPreferencesDrafts.set(e,{...f,auto_seed_scope:p}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),g("label",{class:"coordinator-admin-inline-filter"},g("span",{class:"section-meta",id:s},"Auto-grant default Space on coordinator join"),g(Ji,{"aria-labelledby":s,checked:r.auto_grant_default_space_on_join,className:"coordinator-admin-switch",disabled:!d||r.saving||!r.default_space_scope_id,onCheckedChange:p=>{const f=P.groupPreferencesDrafts.get(e)??r;P.groupPreferencesDrafts.set(e,{...f,auto_grant_default_space_on_join:p}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),r.default_space_scope_id?g("div",{class:"peer-submeta"},"Default Space configured."):g("div",{class:"peer-submeta"},"No default Space has been created yet."),g("div",{class:"coordinator-admin-field"},g("span",{id:c},"Include template"),g(Sb,{"aria-labelledby":c,availableProjects:P.availableProjects,disabled:u,emptyLabel:"All projects allowed.",onValuesChange:p=>{const f=P.groupPreferencesDrafts.get(e)??r;P.groupPreferencesDrafts.set(e,{...f,projects_include:p}),t()},placeholder:"Add project",values:r.projects_include}),g("span",{class:"peer-submeta"},"Leave empty to allow every project inside the granted Space. Type to search or create a new name.")),g("div",{class:"coordinator-admin-field"},g("span",{id:l},"Exclude template"),g(Sb,{"aria-labelledby":l,availableProjects:P.availableProjects,disabled:u,emptyLabel:"Nothing excluded.",onValuesChange:p=>{const f=P.groupPreferencesDrafts.get(e)??r;P.groupPreferencesDrafts.set(e,{...f,projects_exclude:p}),t()},placeholder:"Add project",values:r.projects_exclude})),r.error?g("div",{class:"peer-submeta coordinator-admin-error"},r.error):null,g("div",{class:"peer-actions"},g("button",{class:"settings-button",disabled:!d||r.saving,onClick:()=>{UL(e,t)},type:"button"},r.saving?"Saving…":"Save defaults"),g("button",{class:"settings-button",disabled:r.saving,onClick:()=>Ec(e,t),type:"button"},"Cancel")))}function HL(e){const t=P.teamSetupGuide;if(!t)return null;const n=fp(t.groupId,t.displayName),r={default_space:"default Space setup",default_space_grant:"default Space access grant"}[t.setupWarning?.step||""]||"default Space setup";return g("div",{class:"peer-meta coordinator-admin-empty-state"},g("h4",{class:"coordinator-admin-drawer-title"},`Set up legacy group ${n}`),g("div",{class:"peer-submeta"},"This coordinator group organizes technical discovery and enrollment. It is not a policy Team; use Sharing to manage Team membership and Project access."),t.setupWarning?g("div",{class:"peer-meta coordinator-admin-inline-warning"},`Legacy coordinator group created, but ${r} failed. Automatic repair is not available yet; use Spaces to inspect or create transport access manually. Sharing policy is unchanged.`):g("div",{class:"peer-submeta"},t.defaultSpaceScopeId?t.defaultSpaceLabel?`Default Space ready: ${t.defaultSpaceLabel}. New devices can receive this Space when auto-grant is enabled.`:"Default Space ready. New devices can receive this Space when auto-grant is enabled.":"Default Space status is unknown. Check Spaces before inviting teammates."),g("ol",{class:"peer-submeta"},g("li",null,"Review legacy group defaults and the auto-grant default Space setting."),g("li",null,"Use legacy enrollment only when compatibility or recovery requires it."),g("li",null,"Open Sharing for Team membership and Project access.")),g("div",{class:"peer-actions"},g("button",{class:"settings-button",onClick:()=>{P.groupPreferencesOpen.add(t.groupId),Ap(t.groupId,e)},type:"button"},"Review legacy defaults"),g("button",{class:"settings-button",onClick:()=>{Np(t.groupId,e)},type:"button"},"Check Spaces"),g("button",{class:"settings-button",onClick:()=>{P.inviteGroup=t.groupId,P.activeSection="invites",e()},type:"button"},"Create legacy device invite"),g("button",{class:"settings-button",onClick:()=>{window.location.hash="projects"},type:"button"},"Open Projects"),g("button",{class:"settings-button",onClick:()=>{P.teamSetupGuide=null,e()},type:"button"},"Dismiss")))}function VL(e,t){return t?e?"Unarchiving…":"Archiving…":e?"Unarchive":"Archive"}function KL(e){const{summary:t,fresh:n,createGroup:r,runGroup:i,renderShell:a,reloadData:s}=e,c=Hr(P.recovery,"groups"),l=Hi(P.recovery,"groups"),d=String(S.lastCoordinatorAdminStatus?.active_group||"").trim(),u=Vn(),p=sr(),f=p.filter(y=>!y.archived_at),m=p.filter(y=>y.archived_at),v=P.showArchivedGroups?p:f,b=u?p.some(y=>y.group_id===u):!1,h=[`${f.length} active`];return m.length&&h.push(`${m.length} archived`),g(Gr,{className:"coordinator-admin-panel",value:"groups"},g("h3",null,"Coordinator groups"),g("p",{class:"peer-submeta"},u?`Managing the selected coordinator group${d&&d!==u?" · this node uses a different group for discovery":""}`:d?`This node uses ${d} for discovery. Select a coordinator group below to manage it.`:"No coordinator group selected yet. Create one or select an existing group to manage."),p.length?g("p",{class:"peer-submeta"},h.join(" · ")):null,!b&&u?g("div",{class:"peer-meta coordinator-admin-inline-warning"},"The selected legacy group is configured locally but does not exist in the coordinator yet. Create it below or switch to another coordinator group once one exists."):null,HL(a),(()=>{const y=!n||P.groupActionPendingKind==="create";return g("form",{class:"coordinator-admin-form",onSubmit:w=>{w.preventDefault(),!y&&r()}},g("div",{class:"peer-meta coordinator-admin-inline-warning",role:"note"},"Creating a coordinator group changes legacy discovery and transport setup only. It does not create a policy Team or grant Project access in Sharing."),g("div",{class:"coordinator-admin-form-grid"},g("label",{class:"coordinator-admin-field"},g("span",null,"New coordinator group ID"),g(ke,{class:"peer-scope-input",disabled:y,onInput:w=>{P.createGroupId=String(w.currentTarget.value||"")},placeholder:"group-alpha",type:"text",value:P.createGroupId})),g("label",{class:"coordinator-admin-field"},g("span",null,"Legacy group display name"),g(ke,{class:"peer-scope-input",disabled:y,onInput:w=>{P.createGroupDisplayName=String(w.currentTarget.value||"")},placeholder:"Legacy group Alpha",type:"text",value:P.createGroupDisplayName}))),g("div",{class:"section-actions coordinator-admin-groups-toolbar"},g("div",{class:"coordinator-admin-primary-actions"},g("button",{class:"settings-button",disabled:y,type:"submit"},P.groupActionPendingKind==="create"?"Creating…":"Create coordinator group")),g("div",{class:"coordinator-admin-secondary-actions"},g("label",{class:"coordinator-admin-inline-filter"},g("span",{class:"section-meta",id:"coordinatorAdminShowArchivedLabel"},"Show archived"),g(Ji,{"aria-labelledby":"coordinatorAdminShowArchivedLabel",checked:P.showArchivedGroups,className:"coordinator-admin-switch",onCheckedChange:w=>{P.showArchivedGroups=w,a()},thumbClassName:"coordinator-admin-switch-thumb"})))))})(),l?g("div",{class:"peer-meta"},"Complete legacy coordinator setup before loading coordinator groups. No group list is expected yet."):c?v.length?g("div",{class:"peer-list"},v.map(y=>{const w=y.group_id===u,_=P.groupActionPendingId===y.group_id,R=!!y.archived_at,I=P.groupRenameDrafts.get(y.group_id)??y.display_name??"",T=I.trim()||fp(y.group_id,y.display_name),A=P.groupPreferencesOpen.has(y.group_id),L=P.groupScopeManagementOpen.has(y.group_id),F=R?"unarchive":"archive",N=VL(R,_&&P.groupActionPendingKind===F),j=aD({groupId:y.group_id,preferences:P.groupPreferencesDrafts.get(y.group_id),scopeManagement:P.groupScopeManagementDrafts.get(y.group_id),setupGuide:P.teamSetupGuide});return g("div",{class:"peer-card peer-card--padded",key:y.group_id},g("div",{class:"peer-title"},g("strong",null,T)),g("div",{class:"peer-submeta"},R?"Archived coordinator group":"Active coordinator group"),g("details",{class:"coordinator-admin-diagnostics"},g("summary",null,"Diagnostics"),g("div",{class:"peer-meta"},`Group ID ${y.group_id}`)),g("div",{class:"coordinator-admin-summary-grid"},g("div",{class:"coordinator-admin-summary-card"},g("span",{class:"section-meta"},"Default Space"),g("strong",null,j.defaultSpace)),g("div",{class:"coordinator-admin-summary-card"},g("span",{class:"section-meta"},"Auto-grant"),g("strong",null,j.autoGrant)),g("div",{class:"coordinator-admin-summary-card"},g("span",{class:"section-meta"},"Spaces"),g("strong",null,j.spaces))),d===y.group_id?g("div",{class:"peer-submeta"},"This node uses this coordinator group for discovery."):null,g("label",{class:"coordinator-admin-field"},g("span",null,"Legacy group display name"),g(ke,{class:"peer-scope-input",disabled:!n||_,onInput:x=>{P.groupRenameDrafts.set(y.group_id,String(x.currentTarget.value||""))},type:"text",value:I})),g("div",{class:"peer-actions"},g("button",{class:"settings-button",disabled:!n||w,onClick:()=>{pp(y.group_id),s()},type:"button"},w?"Managing":"Manage group"),g("button",{class:"settings-button",disabled:!n||_,onClick:()=>i(y.group_id,I,"rename"),type:"button"},_&&P.groupActionPendingKind==="rename"?"Renaming…":"Rename group"),g("button",{"aria-expanded":A,"aria-controls":`coord-admin-project-defaults-drawer-${y.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":A?"open":"closed",disabled:_,onClick:()=>{A?Ec(y.group_id,a):Ap(y.group_id,a)},type:"button"},g("span",null,"Legacy group defaults"),g("span",{"aria-hidden":"true",class:"device-row-chevron"},g(Vb,null))),g("button",{"aria-expanded":L,"aria-controls":`coord-admin-spaces-drawer-${y.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":L?"open":"closed",disabled:_,onClick:()=>{L?Hb(y.group_id,a):Np(y.group_id,a)},type:"button"},g("span",null,"Spaces & access"),g("span",{"aria-hidden":"true",class:"device-row-chevron"},g(Vb,null))),g("button",{class:R?"settings-button":"settings-button danger",disabled:!n||_,onClick:()=>i(y.group_id,y.display_name||y.group_id,F),type:"button"},N)),g(Ya,{open:A,onOpenChange:x=>{x?Ap(y.group_id,a):Ec(y.group_id,a)}},g(Xa,{"aria-label":`Project defaults for ${T}`,class:"coordinator-admin-group-preferences",id:`coord-admin-project-defaults-drawer-${y.group_id}`},A?GL(y.group_id,a,n):null)),g(Ya,{open:L,onOpenChange:x=>{x?Np(y.group_id,a):Hb(y.group_id,a)}},g(Xa,{"aria-label":`Spaces for ${T}`,class:"coordinator-admin-group-preferences coordinator-admin-domain-management",id:`coord-admin-spaces-drawer-${y.group_id}`},L?BL({groupId:y.group_id,ready:n,renderShell:a,summary:t}):null)))})):g("div",{class:"peer-meta coordinator-admin-empty-state"},t.readiness==="ready"?P.showArchivedGroups?"No coordinator groups are available yet.":"No active coordinator groups yet. Create one only for legacy discovery or recovery.":"Coordinator group browsing will appear here once setup is complete."):g("div",{class:"peer-meta coordinator-admin-empty-state"},"Coordinator groups are unavailable. Retry to load current groups; no empty result is being assumed."))}function Qi(e){return o("textarea",{...e})}function zL(e){const{summary:t,fresh:n,createInvite:r,renderShell:i}=e,a=S.lastCoordinatorAdminStatus,s=Vn()||String(a?.active_group||"").trim(),c=P.inviteGroup.trim()||s,l=String(S.lastTeamInvite?.encoded||"").trim(),d=Array.isArray(S.lastTeamInvite?.warnings)?S.lastTeamInvite?.warnings:[],u=!n||P.invitePending;return g(Gr,{className:"coordinator-admin-panel",value:"invites"},g("h3",null,"Legacy coordinator invites"),g("p",{class:"peer-submeta"},n?"Legacy coordinator invites enroll a device in the selected group for discovery. They do not add policy Team membership or grant Project access; use Sharing for both.":t.readiness==="ready"?"Legacy invite creation is disabled until current coordinator status and group data are available. Previously generated invites remain available to copy.":"Finish coordinator setup first. Legacy invite creation stays disabled until the local configuration is ready."),g("form",{class:"coordinator-admin-form",onSubmit:p=>{p.preventDefault(),!u&&r()}},g("div",{class:"coordinator-admin-form-grid"},g("label",{class:"coordinator-admin-field"},g("span",null,"Coordinator group"),g(ke,{class:"peer-scope-input",disabled:!n,onInput:p=>{P.inviteGroup=String(p.currentTarget.value||""),i()},placeholder:s||"group-alpha",type:"text",value:P.inviteGroup})),g("label",{class:"coordinator-admin-field"},g("span",null,"Join policy"),g(dr,{ariaLabel:"Invite join policy",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:!n,id:"coordinatorAdminInvitePolicy",itemClassName:"sync-radix-select-item",onValueChange:p=>{P.invitePolicy=p==="approval_required"?"approval_required":"auto_admit",i()},options:[{value:"auto_admit",label:"Auto-admit to coordinator group"},{value:"approval_required",label:"Require approval to join group"}],triggerClassName:"sync-radix-select-trigger sync-actor-select",value:P.invitePolicy,viewportClassName:"sync-radix-select-viewport"})),g("label",{class:"coordinator-admin-field"},g("span",null,"Expires in (hours)"),g(ke,{class:"peer-scope-input",disabled:!n,min:"1",onInput:p=>{P.inviteTtlHours=String(p.currentTarget.value||"")},type:"number",value:P.inviteTtlHours}))),g("div",{class:"section-actions"},g("button",{class:"settings-button",disabled:u,type:"submit"},P.invitePending?"Creating…":"Create legacy coordinator invite"),c?g("span",{class:"peer-submeta"},"Using the selected coordinator group"):null)),l?g("label",{class:"coordinator-admin-field"},g("span",null,"Generated invite"),g(Qi,{class:"feed-search coordinator-admin-output",readOnly:!0,value:l}),g("button",{class:"settings-button sync-action-copy",type:"button",onClick:p=>Va(l,p.currentTarget)},"Copy")):null,d?.length?g("div",{class:"peer-meta coordinator-admin-warning-list"},d.join(" · ")):null,g("h3",null,"Project sharing operations"),g("p",{class:"peer-submeta"},"Read-only status from the project-first sharing flow. Start new sharing from Projects."),S.lastShareOperations.length>0?g("ul",{class:"peer-scope-rejections-list","aria-label":"Project sharing operations"},...S.lastShareOperations.map(p=>g("li",{key:p.operation_id},g("strong",null,p.person.display_name),g("span",null,` — ${p.projects.map(f=>f.display_name).join(", ")} — ${p.lifecycle.label}`)))):g("div",{class:"peer-meta"},"No project sharing operations yet."))}function WL(e){const{summary:t,fresh:n,reviewJoinRequest:r,snapshotMatchesTarget:i}=e,a=i&&Hr(P.recovery,"joinRequests"),s=Hi(P.recovery,"joinRequests"),c=a&&Array.isArray(S.lastCoordinatorAdminJoinRequests)?S.lastCoordinatorAdminJoinRequests:[],l=c.map(u=>({device_id:String(u.device_id||"").trim()||`join-request:${String(u.request_id||"").trim()}`,display_name:u.display_name})),d=tc(l,P.unnamedDeviceAliases);return g(Gr,{className:"coordinator-admin-panel",value:"join-requests"},g("h3",null,"Pending join requests"),g("p",{class:"peer-submeta"},t.readiness==="ready"?"Approve or deny devices that want to join this legacy coordinator group. Space transport access is handled by legacy group defaults and can be reviewed in Spaces; Sharing policy is separate.":"Finish coordinator setup first. Join request review stays disabled until legacy administration is ready."),s?g("div",{class:"peer-meta"},"Complete legacy coordinator setup to load join requests. No join queue is expected yet."):a?c.length?g("div",{class:"peer-list"},c.map(u=>{const p=String(u.request_id||"").trim(),f=String(u.device_id||"").trim(),m=f||`join-request:${p}`,v=d.get(m)||"Unnamed device",b=String(u.fingerprint||"").trim(),h=[`Device ID ${f||"unknown"}`];b&&h.push(`Fingerprint ${b}`);const y=P.joinReviewPendingId===p;return g("div",{class:"peer-card peer-card--padded",key:p||f},g("div",{class:"peer-title"},g("strong",null,v)),g("details",{class:"coordinator-admin-diagnostics"},g("summary",null,"Diagnostics"),g("div",{class:"peer-meta"},`Advanced: ${h.join(" · ")}`)),g("div",{class:"peer-actions"},g("button",{class:"settings-button",disabled:!n||!p||y,onClick:()=>r(p,"approve"),type:"button"},y&&P.joinReviewPendingAction==="approve"?"Approving…":"Approve"),g("button",{class:"settings-button danger",disabled:!n||!p||y,onClick:()=>r(p,"deny"),type:"button"},y&&P.joinReviewPendingAction==="deny"?"Denying…":"Deny")))})):g("div",{class:"peer-meta"},t.readiness==="ready"?"No pending join requests right now.":"Join request review will appear here once setup is complete."):g("div",{class:"peer-meta"},"Join requests are unavailable. Retry to load the current queue; no empty result is being assumed."))}var JL=new Map([["display_name_required","Enter a device name before renaming it."],["display_name_invalid","Enter a valid device name and retry."],["display_name_too_long","The device name is too long. Use a shorter name and retry."]]);function YL(e){const t=e instanceof Error?e.message:"";return t.includes("group_archived")||t.includes("Group is archived")?"This legacy coordinator group is archived. Choose an active group or refresh coordinator groups.":t.includes("group_not_found")||t.includes("Group not found")?"This legacy coordinator group no longer exists. Choose an active group or refresh coordinator groups.":"Could not create the legacy coordinator invite. Sharing policy is unchanged; check coordinator recovery status and retry."}function XL(e){return e instanceof Error?e.message.includes("request_not_found")||e.message.includes("join request not found"):!1}function QL(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("group_not_found")||t.includes("group not found")}function ZL(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("device_not_found")||t.includes("device not found")}function e$(e){const{renderShell:t,reloadData:n}=e,r=(...d)=>Mn(P.recovery,...d)?!0:(X("Coordinator data changed or is refreshing. Wait for recovery to finish, then try again.","warning"),!1);async function i(){if(!r("status","groups")||P.groupActionPendingKind)return;const d=Hn(S.lastCoordinatorAdminStatus?.coordinator_url),u=P.createGroupId.trim();if(!u){X("Enter a coordinator group ID before creating a legacy group.","warning");return}const p=P.createGroupDisplayName.trim();P.groupActionPendingKind="create",t();try{const f=await dR({group_id:u,display_name:p||null});if(Hn(S.lastCoordinatorAdminStatus?.coordinator_url)!==d)return;const m=f.default_space,v=(m&&"scope"in m?m.scope:m)??{},b=m&&"preferences"in m?m.preferences:null,h=String(v?.scope_id||"");P.createGroupId="",P.createGroupDisplayName="",P.teamSetupGuide={groupId:u,displayName:String(f.group?.display_name||p||""),defaultSpaceScopeId:h,defaultSpaceLabel:String(v?.label||""),autoGrantDefaultSpaceOnJoin:typeof b?.auto_grant_default_space_on_join=="boolean"?b.auto_grant_default_space_on_join:null,setupWarning:f.setup_warning||null};try{await n(),pp(u),await n()}catch{X("Legacy coordinator group created, but coordinator data could not refresh. Check coordinator recovery status before retrying.","warning");return}f.setup_warning?X("Legacy coordinator group created, but default Space setup needs repair. Sharing policy is unchanged.","warning"):h?X("Legacy coordinator group created with a default Space. Sharing policy is unchanged.","success"):X("Legacy coordinator group created, but default Space status is unknown. Sharing policy is unchanged.","warning")}catch{X("Could not create the legacy coordinator group. No Sharing policy or Project access changed; check coordinator recovery status and retry.","warning")}finally{P.groupActionPendingKind="",t()}}async function a(d,u,p){if(!r("status","groups")||!d||P.groupActionPendingId)return;const f=u.trim();if(p==="rename"&&!f){X("Enter a legacy group display name before renaming it.","warning");return}const m=S.lastCoordinatorAdminGroups.find(w=>w.group_id===d),v=fp(d,m?.display_name),b=_c();if(!await vn({title:p==="rename"?`Rename ${v}?`:`${p==="archive"?"Archive":"Unarchive"} ${v}?`,description:p==="rename"?`Target: ${v}. New name: ${f}. This renames the technical coordinator group only. It does not rename a policy Team or change membership or Project access in Sharing.`:p==="archive"?`Target: ${v}. The group stays visible and restorable, but coordinator presence, peer discovery, Space grants, legacy invites, and joins stop. Archiving also removes this group from this device's local coordinator configuration. Policy Team membership and Project access in Sharing are separate and unchanged.`:`Target: ${v}. This reactivates the remote coordinator group for devices still configured for it. It does not re-add this group to this device's local coordinator configuration; restore that separately before expecting coordinator presence or peer discovery here. It does not restore or change policy Team membership or Project access in Sharing.`,confirmLabel:p==="rename"?"Rename coordinator group":p==="archive"?"Archive coordinator group":"Unarchive coordinator group",cancelLabel:p==="rename"?"Keep current group name":p==="archive"?"Keep group active":"Keep group archived",tone:p==="archive"?"danger":"default"}))return;if(!Ot(b)){X("Coordinator group data changed while confirmation was open. Review the current group and try again.","warning");return}if(!Mn(P.recovery,"status","groups")){X("Coordinator group data changed while confirmation was open. Review the current group and try again.","warning");return}const h=S.lastCoordinatorAdminGroups.find(w=>String(w.group_id||"")===d);if(!h||P.groupActionPendingId){X("Coordinator group data changed while confirmation was open. Review the current group and try again.","warning");return}const y=P.groupRenameDrafts.get(d)??String(h.display_name||"");P.groupActionPendingId=d,P.groupActionPendingKind=p,t();try{const w=p==="rename"?"renamed":p==="archive"?"archived":"unarchived";p==="rename"&&await uR(d,y),p==="archive"&&await pR(d),p==="unarchive"&&await fR(d);try{await n()}catch{X(`Legacy coordinator group ${w}, but coordinator data could not refresh. Check coordinator recovery status before retrying.`,"warning");return}X(p==="rename"?"Legacy coordinator group renamed. Sharing Team names are unchanged.":p==="archive"?"Legacy coordinator group archived. Sharing policy is unchanged.":"Legacy coordinator group unarchived. This device's local coordinator configuration and Sharing policy are unchanged.","success")}catch(w){if(QL(w))try{await n(),X("This legacy coordinator group changed or no longer exists. Coordinator groups were refreshed.","warning")}catch{X("This legacy coordinator group changed or no longer exists. Refresh coordinator groups before trying another action.","warning")}else X(`Could not ${p} the legacy coordinator group. Sharing policy is unchanged; check coordinator recovery status and retry.`,"warning")}finally{P.groupActionPendingId="",P.groupActionPendingKind="",t()}}async function s(){if(!r("status","groups")||P.invitePending)return;const d=S.lastCoordinatorAdminStatus,u=Hn(d?.coordinator_url),p=Vn()||String(d?.active_group||"").trim(),f=P.inviteGroup.trim()||p,m=Number(P.inviteTtlHours);if(!f){X("Choose a coordinator group before creating a legacy invite.","warning");return}if(!Number.isFinite(m)||m<1){X("Invite lifetime must be at least 1 hour.","warning");return}P.invitePending=!0,t();try{const v=await Vm({group_id:f,policy:P.invitePolicy,ttl_hours:m}),b=S.lastCoordinatorAdminStatus,h=Vn()||String(b?.active_group||"").trim(),y=P.inviteGroup.trim()||h;if(Hn(b?.coordinator_url)!==u||y!==f)return;S.lastTeamInvite=v,P.inviteGroup=f;const w=Array.isArray(v.warnings)?v.warnings:[];X(w.length?`Invite created. Review ${w.length===1?"the warning":`${w.length} warnings`} before sharing it.`:"Legacy coordinator invite created. It does not grant Sharing Project access.",w.length?"warning":"success")}catch(v){X(YL(v),"warning")}finally{P.invitePending=!1,t()}}async function c(d,u){if(!Ot(P.joinRequestsSnapshotTarget)||!r("status","joinRequests")||P.joinReviewPendingId)return;const p=P.joinRequestsSnapshotTarget;P.joinReviewPendingId=d,P.joinReviewPendingAction=u,t();try{const f=await bR(d,u);if(!Ot(p))return;try{await n()}catch{X(`Join request ${u==="approve"?"approved":"denied"}, but pending requests could not refresh. Check coordinator recovery status before reviewing another request.`,"warning");return}u==="approve"&&f.setup_warning?X("Join request approved, but default Space access needs repair.","warning"):X(u==="approve"?"Join request approved.":"Join request denied.","success")}catch(f){if(!Ot(p))return;if(XL(f))try{await n(),X("This legacy coordinator join request no longer exists. Pending requests were refreshed.","warning")}catch{X("This legacy coordinator join request no longer exists. Refresh pending requests before reviewing another request.","warning")}else X("Could not review the legacy coordinator join request. Sharing policy is unchanged; check coordinator recovery status and retry.","warning")}finally{P.joinReviewPendingId="",P.joinReviewPendingAction="",t()}}async function l(d,u,p,f){if(Ot(P.devicesSnapshotTarget)&&r("status","devices")&&!(!d||P.deviceActionPendingId)){if(f==="disable"||f==="remove"){const m=_c();if(!await vn({title:`${f==="disable"?"Disable":"Remove"} ${p||"this device"}?`,description:f==="disable"?"This device will stay enrolled but can no longer participate until you re-enable it.":"This removes the enrolled device record from the coordinator. The teammate would need a fresh invite or re-enrollment path to come back.",confirmLabel:f==="disable"?"Disable device":"Remove device",cancelLabel:f==="disable"?"Keep device enabled":"Keep device enrolled",tone:"danger"}))return;if(!Ot(m)){X("Coordinator device data changed while confirmation was open. Review the current device and try again.","warning");return}if(!Mn(P.recovery,"status","devices")){X("Coordinator device data changed while confirmation was open. Review the current device and try again.","warning");return}if(!S.lastCoordinatorAdminDevices.find(v=>String(v.device_id||"")===d&&String(v.group_id||"")===u)||P.deviceActionPendingId){X("Coordinator device data changed while confirmation was open. Review the current device and try again.","warning");return}}P.deviceActionPendingId=d,P.deviceActionPendingKind=f,t();try{const m=f==="rename"?"renamed":f==="disable"?"disabled":f==="enable"?"enabled":"removed";if(f==="rename"){const v=String(P.deviceRenameDrafts.get(d)||"").trim();if(!v){X("Enter a device name before renaming it.","warning");return}await _R(d,u,v)}f==="disable"&&await wR(d,u),f==="enable"&&await SR(d,u),f==="remove"&&await CR(d,u);try{await n()}catch{X(`Device ${m}, but coordinator data could not refresh. Check coordinator recovery status before retrying.`,"warning");return}X(`Device ${m}.`,"success")}catch(m){const v=f==="rename"&&m instanceof Error?JL.get(m.message.trim()):void 0;if(ZL(m))try{await n(),X("This legacy coordinator device no longer exists. Enrolled devices were refreshed.","warning")}catch{X("This legacy coordinator device no longer exists. Refresh enrolled devices before trying another action.","warning")}else X(v||`Could not ${f} the legacy coordinator device. Sharing policy is unchanged; check coordinator recovery status and retry.`,"warning")}finally{P.deviceActionPendingId="",P.deviceActionPendingKind="",t()}}}return{createGroupFromAdminPanel:i,runGroupAction:a,createInviteFromAdminPanel:s,reviewJoinRequestFromAdminPanel:c,runDeviceAction:l}}function t$(){S.lastCoordinatorAdminGroups=[],S.lastCoordinatorAdminJoinRequests=[],S.lastCoordinatorAdminDevices=[],S.lastTeamInvite=null,S.coordinatorAdminTargetGroup="",fn(P.recovery,"groups",!1),fn(P.recovery,"joinRequests",!1),fn(P.recovery,"devices",!1),P.joinRequestsSnapshotTarget=null,P.devicesSnapshotTarget=null,P.groupRenameDrafts.clear(),P.groupPresentationAliases.clear(),P.deviceRenameDrafts.clear(),P.deviceRenameServerNames.clear(),P.groupPreferencesOpen.clear(),P.groupPreferencesDrafts.clear(),P.groupScopeManagementOpen.clear(),P.groupScopeManagementDrafts.clear(),P.inviteGroup="",P.teamSetupGuide=null}function n$(){const e=qy();return Wa(P.recovery,"status"),qu(P.recovery,"groups"),qu(P.recovery,"joinRequests"),qu(P.recovery,"devices"),e}async function Wb(e,t={}){try{const n=await Kl(t);if(t.signal?.aborted||!Hu(e))return"superseded";if(!n||typeof n!="object")throw new Error("Invalid status payload");const r=S.lastCoordinatorAdminStatus;return Hn(r?.coordinator_url)!==Hn(n.coordinator_url)&&t$(),S.lastCoordinatorAdminStatus=n,rc(P.recovery,"status"),"fresh"}catch{return t.signal?.aborted||!Hu(e)?"superseded":(fn(P.recovery,"status"),"failed")}}function r$(){const e=S.lastCoordinatorAdminStatus;return e?e.readiness==="ready"?{readiness:"ready",title:"Legacy coordinator administration is ready",detail:"This viewer can manage legacy coordinator groups, invites, join requests, and enrolled devices without exposing the admin secret to the browser."}:e.readiness==="partial"?{readiness:"partial",title:"Legacy coordinator setup is incomplete",detail:e.has_admin_secret===!1?"Set a coordinator admin secret for the viewer server before using legacy invite and device actions.":"Finish configuring the coordinator target and group before using legacy administration actions."}:{readiness:"not_configured",title:"Legacy coordinator administration is not configured",detail:"Set a coordinator URL, group, and admin secret locally to enable remote coordinator administration from this viewer."}:P.recovery.status.availability==="unavailable"?{readiness:"partial",title:"Legacy coordinator status is unavailable",detail:"Current coordinator readiness could not be loaded. Retry before using legacy administration actions."}:{readiness:"partial",title:"Checking legacy coordinator readiness…",detail:"Loading local coordinator administration configuration from the viewer server."}}var{createGroupFromAdminPanel:i$,runGroupAction:a$,createInviteFromAdminPanel:o$,reviewJoinRequestFromAdminPanel:s$,runDeviceAction:c$}=e$({renderShell:()=>Qr(),reloadData:async()=>{await Ac()}});function Qr(){const e=document.getElementById("coordinatorAdminMount");if(!e)return;const t=S.lastCoordinatorAdminStatus,n=r$(),r=String(t?.coordinator_url||"").trim(),i=String(t?.active_group||"").trim(),s=!!Q0()?.archived_at,c=Mn(P.recovery,"status","groups"),l=c&&!s,d=Ot(P.joinRequestsSnapshotTarget),u=Ot(P.devicesSnapshotTarget),p=Mn(P.recovery,"status","joinRequests")&&d,f=Mn(P.recovery,"status","devices")&&u,m=Vn(),v=sr().filter(j=>!j.archived_at).length,b=sr().filter(j=>j.archived_at).length,h=d&&Array.isArray(S.lastCoordinatorAdminJoinRequests)?S.lastCoordinatorAdminJoinRequests.length:0,y=u&&Array.isArray(S.lastCoordinatorAdminDevices)?S.lastCoordinatorAdminDevices.length:0,w=n.readiness!=="ready"?n.detail:s?"The selected coordinator group is archived. Restore it or switch groups before creating legacy invites.":"",_=Gu(P.recovery),R=Hr(P.recovery,"status"),I=Hr(P.recovery,"groups"),T=d&&Hr(P.recovery,"joinRequests"),A=u&&Hr(P.recovery,"devices"),L=Hi(P.recovery,"groups"),F=Hi(P.recovery,"joinRequests"),N=Hi(P.recovery,"devices");Ue(g("div",{class:"coordinator-admin-shell"},g("div",{class:"card coordinator-admin-header"},g("div",{class:"section-header"},g("h2",null,"Legacy coordinator administration")),g("div",{"aria-atomic":"true","aria-live":"polite",class:_?"coordinator-admin-inline-warning coordinator-admin-recovery-notice":P.recoveryAnnouncement?"peer-meta coordinator-admin-recovery-status":"coordinator-admin-recovery-status",id:"coordinatorAdminRecoveryStatus",role:"status",tabIndex:-1},_?g(z,null,g("div",{class:"coordinator-admin-legacy-notice-copy"},g("h3",null,"Advanced coordinator data needs attention"),P.recoveryAnnouncement?g("p",{class:"peer-submeta"},P.recoveryAnnouncement):null,_.stale.length?g("p",{class:"peer-submeta"},`Stale: ${_.stale.join(", ")}. Previously loaded data is still shown.`):null,_.unavailable.length?g("p",{class:"peer-submeta"},`Unavailable: ${_.unavailable.join(", ")}. No current data is shown for ${_.unavailable.length===1?"that surface":"those surfaces"}.`):null,g("p",{class:"peer-submeta"},"Actions that depend on current coordinator data are disabled. This does not mean coordinator data was deleted.")),g("button",{class:"settings-button",disabled:_.retrying,onClick:()=>{P.recoveryAnnouncement="Retrying coordinator data…",P.recoveryRetryRequested=!0,Ac()},type:"button"},_.retrying?"Retrying…":"Retry")):P.recoveryAnnouncement),g("div",{class:"coordinator-admin-summary-grid"},g("div",{class:"coordinator-admin-summary-card"},g("span",{class:"section-meta"},"Coordinator group target"),g("strong",null,R||I?m||"None selected":"Unavailable")),g("div",{class:"coordinator-admin-summary-card"},g("span",{class:"section-meta"},"Node discovery group"),g("strong",null,R?i||"None":"Unavailable")),g("div",{class:"coordinator-admin-summary-card"},g("span",{class:"section-meta"},"Coordinator groups"),g("strong",null,I?`${v} active${b?` · ${b} archived`:""}`:L?"Setup required":"Unavailable")),g("div",{class:"coordinator-admin-summary-card"},g("span",{class:"section-meta"},"Selected group activity"),g("strong",null,`${T?h:F?"Setup required":"Unavailable"} join requests · ${A?y:N?"Setup required":"Unavailable"} devices`))),w?g("div",{class:"peer-meta coordinator-admin-inline-warning"},w):null,r?g("div",{class:"section-meta coordinator-admin-inline-meta"},`Coordinator: ${r}`):null),g("div",{class:"card coordinator-admin-sections"},g(My,{ariaLabel:"Legacy coordinator administration sections",listClassName:"coordinator-admin-tabs-list",onValueChange:j=>{P.activeSection=j||"groups",Qr()},tabs:[{value:"groups",label:"Coordinator groups"},{value:"invites",label:"Invites"},{value:"join-requests",label:"Join requests"},{value:"devices",label:"Devices"}],triggerClassName:"coordinator-admin-tab-trigger",value:P.activeSection},KL({summary:n,fresh:c,createGroup:()=>{i$()},runGroup:(j,x,U)=>{a$(j,x,U)},renderShell:Qr,reloadData:()=>{Ac()}}),zL({summary:n,fresh:l,createInvite:()=>{o$()},renderShell:Qr}),WL({summary:n,fresh:p,snapshotMatchesTarget:d,reviewJoinRequest:(j,x)=>{s$(j,x)}}),zA({summary:n,fresh:f,snapshotMatchesTarget:u,runDevice:(j,x,U,q)=>{c$(j,x,U,q)}})),g("div",{class:"section-meta coordinator-admin-context-line"},s?"The selected coordinator group is archived. Switch or restore it to enable legacy invite operations.":m?"Actions below apply to the selected coordinator group.":"Select a coordinator group to manage legacy enrollment and Spaces."))),e),P.recoveryFocusPending&&(P.recoveryFocusPending=!1,queueMicrotask(()=>document.getElementById("coordinatorAdminRecoveryStatus")?.focus()))}function l$(){Qr()}var xp=null;function Gt(e){return xp?.generation===e?!1:xp?.operation??!1}function Ac(e={}){const t=qy(),n=p$(t,e.signal);return xp={generation:t,operation:n},n}function d$(){Fy([...S.lastCoordinatorAdminDevices,...S.lastCoordinatorAdminJoinRequests.map(e=>({device_id:String(e.device_id||"").trim()||`join-request:${String(e.request_id||"").trim()}`,display_name:e.display_name}))],P.unnamedDeviceAliases),tc(S.lastCoordinatorAdminDevices,P.unnamedDeviceAliases)}function u$(){return Gu(P.recovery)?"Retry finished, but some coordinator data still needs attention. Retained data remains unchanged.":S.lastCoordinatorAdminStatus?.readiness==="ready"?"Coordinator data refreshed. Current data is available.":"Coordinator status refreshed. Complete setup to load administration data."}async function p$(e,t){const n=()=>!t?.aborted&&Hu(e);if(P.recoveryRetryRequested||(P.recoveryAnnouncement=""),Wa(P.recovery,"status"),Wa(P.recovery,"groups"),Wa(P.recovery,"joinRequests"),Wa(P.recovery,"devices"),Qr(),await Wb(e,{signal:t})==="superseded")return Gt(e);const r=String(S.lastCoordinatorAdminStatus?.active_group||"").trim();if(kb(),S.lastCoordinatorAdminStatus?.readiness==="ready"&&Mn(P.recovery,"status")){try{const s=await ph({signal:t});if(!n())return Gt(e);S.lastShareOperations=Array.isArray(s.items)?s.items:[]}catch{if(!n())return Gt(e)}try{const s=await Um(P.showArchivedGroups,{signal:t});if(!n())return Gt(e);if(!Array.isArray(s?.items))throw new Error("Invalid groups payload");S.lastCoordinatorAdminGroups=s.items,rc(P.recovery,"groups"),X0(),kb()}catch{if(!n())return Gt(e);fn(P.recovery,"groups")}const i=Vn(),a=_c();try{if(!a)throw new Error("Missing coordinator administration target");const s=await yR(i||r,{signal:t});if(!n())return Gt(e);if(!Array.isArray(s?.items))throw new Error("Invalid join requests payload");S.lastCoordinatorAdminJoinRequests=s.items,P.joinRequestsSnapshotTarget=a,rc(P.recovery,"joinRequests")}catch{if(!n())return Gt(e);fn(P.recovery,"joinRequests",Ot(P.joinRequestsSnapshotTarget))}try{if(!a)throw new Error("Missing coordinator administration target");const s=await Hm(i||r,!0,{signal:t});if(!n())return Gt(e);if(!Array.isArray(s?.items))throw new Error("Invalid devices payload");S.lastCoordinatorAdminDevices=s.items,P.devicesSnapshotTarget=a,rc(P.recovery,"devices"),Z0()}catch{if(!n())return Gt(e);fn(P.recovery,"devices",Ot(P.devicesSnapshotTarget))}try{const s=await es({signal:t});if(!n())return Gt(e);P.availableProjects=s}catch{if(!n())return Gt(e)}}else P.recovery.status.availability==="fresh"?(Uu(P.recovery,"groups"),Uu(P.recovery,"joinRequests"),Uu(P.recovery,"devices"),P.joinRequestsSnapshotTarget=null,P.devicesSnapshotTarget=null):(fn(P.recovery,"groups"),fn(P.recovery,"joinRequests",Ot(P.joinRequestsSnapshotTarget)),fn(P.recovery,"devices",Ot(P.devicesSnapshotTarget)));return n()?(d$(),P.recoveryRetryRequested&&(P.recoveryAnnouncement=u$(),P.recoveryFocusPending=!0),P.recoveryRetryRequested=!1,Qr(),Gu(P.recovery)===null):Gt(e)}function Dp(e){return e.inventoryUnavailable===!0||e.refreshError===!0}var Lp=new WeakMap,Jb={active:0,verifying:1,pending:2,waiting:3,needs_attention:4},f$={state:"pending",label:"Recipient policy pending",explanation:"Current access remains in place while this Project is prepared.",deliveredCopiesMayRemain:!0},m$={available:"Available",offline:"Offline",unknown:"Availability unknown"};function h$(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function g$(e,t){return t.get(e)??f$}function v$(e){return e.reduce((t,n)=>!t||Jb[n.state]>Jb[t.state]?n:t,null)}function y$(e,t){return t==="needs_attention"?{label:"Review sharing",target:"sharing"}:e!=="available"?{label:"Check device health",target:"health"}:t==="waiting"||t==="pending"||t==="verifying"?{label:"View sharing status",target:"sharing"}:null}function b$(e,t,n,r,i=[]){const a=new Map(e.identities.filter(u=>u.status==="active"&&u.mergedIntoIdentityId===null).map(u=>[u.identityId,u.displayName])),s=new Map(n.map(u=>[u.canonicalProjectIdentity,u.displayName])),c=new Map(r.map(u=>[u.deviceId,u.state])),l=new Map(i.map(u=>[u.deviceId,u])),d=new Map(t.items.map(u=>[u.canonicalProjectIdentity,u]));return{devices:e.identityDevices.filter(u=>u.status==="active"&&a.has(u.identityId)).map(u=>{const p=l.get(u.deviceId),f=h$(e.projectRecipients.filter(_=>_.status==="active"&&_.recipientKind==="identity"&&_.identityId===u.identityId).map(_=>_.canonicalProjectIdentity)),m=_=>{const R=s.get(_);if(!R)return null;const I=g$(_,d);return{canonicalProjectIdentity:_,displayName:R,state:I.state,statusLabel:I.label,statusCopy:I.explanation,deliveredCopiesMayRemain:I.deliveredCopiesMayRemain}},v=f.flatMap(_=>{const R=m(_);return R?[R]:[]}),b=[],h=[...v,...b],y=v$(h),w=c.get(u.deviceId)??"unknown";return{deviceId:u.deviceId,displayName:u.displayName,identityName:a.get(u.identityId)??"Identity unavailable",availability:w,availabilityLabel:m$[w],isPairedPeer:p!==void 0,reportedRuntimeVersion:p?.runtimeVersion??null,runtimeVersionObservedAt:p?.runtimeVersionObservedAt??null,directProjects:v,inheritedProjects:b,unavailableProjectCount:f.length-v.length,statusState:y?.state??"no_projects",statusLabel:y?.statusLabel??"No directly shared Projects",statusCopy:y?.statusCopy??"Team access is not shown here without authoritative per-device eligibility.",deliveredCopiesMayRemain:h.some(_=>_.deliveredCopiesMayRemain),action:y$(w,y?.state??"no_projects")}}).sort((u,p)=>u.displayName.localeCompare(p.displayName)||u.identityName.localeCompare(p.identityName)),revokedDeviceCount:e.identityDevices.filter(u=>u.status==="revoked"&&a.has(u.identityId)).length}}function Yb({empty:e,projects:t}){return t.length===0?o("p",{className:"small",children:e}):o("ul",{children:t.map(n=>o("li",{children:[o("strong",{children:n.displayName}),o("span",{className:"small",children:[" ","— ",n.statusLabel,". ",n.statusCopy]})]},n.canonicalProjectIdentity))})}function ao(e){if(!(e instanceof Xl))return"Identity setup is unavailable. Refresh Devices and try again.";const t={binding_preview_busy:"Identity setup is busy. Wait a moment, then retry.",binding_commit_busy:"Identity setup is busy. Wait a moment, then retry.",binding_evidence_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_retry_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_rebind_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_unchanged_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_write_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",device_pairing_required:"Pair this device before assigning an Identity.",device_rebind_confirmation_required:"Reassignment requires a separate confirmation of the previous and target Identities.",device_inventory_incomplete:"The complete device inventory is unavailable. Refresh after coordinator evidence is available.",device_inventory_truncated:"The complete device inventory is unavailable. Refresh after coordinator evidence is available.",binding_write_conflict:"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.",binding_commit_conflict:"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.",device_evidence_conflict:"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.",target_identity_unavailable:"A selected device or Identity is no longer available. Refresh Devices and choose again.",device_unavailable:"A selected device or Identity is no longer available. Refresh Devices and choose again.",device_not_found:"A selected device or Identity is no longer available. Refresh Devices and choose again.",deciding_identity_unavailable:"The deciding Identity is unavailable. Open Identity administration to restore or replace it, then try again."}[e.errorCode];return t||(e.statusCode===503?"Identity setup is busy. Wait a moment, then retry.":e.statusCode===409?"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.":e.statusCode===404?"A selected device or Identity is no longer available. Refresh Devices and choose again.":"Identity setup could not be completed. Refresh Devices and try again.")}function xc(e,t){return{targetIdentityId:e.state==="setup_required"&&e.suggestedIdentityId&&t.has(e.suggestedIdentityId)?e.suggestedIdentityId:"",selected:!1,explicit:!1,itemSignature:oo(e)}}function oo(e){return JSON.stringify({deviceId:e.deviceId,evidenceDeviceIds:[...e.evidenceDeviceIds].sort(),state:e.state,identityId:e.identityId,suggestedIdentityId:e.suggestedIdentityId,validatedFingerprint:e.validatedFingerprint,isLocal:e.isLocal,sources:[...e.sources].sort(),conflictCodes:[...e.conflictCodes].sort()})}function Dc(e,t,n,r){if(e.status!=="ready"||e.outcomes.length!==t.bindings.length)return!1;const i=new Set;return t.bindings.every(a=>{const s=n.find(l=>l.deviceId===a.deviceId),c=e.outcomes.findIndex((l,d)=>!i.has(d)&&s?.evidenceDeviceIds.includes(l.deviceId)===!0&&l.targetIdentityId===a.targetIdentityId&&l.action===r);return c<0?!1:(i.add(c),!0)})}var Xb="devices-commit-status";function Kn(e){const t=document.getElementById(Xb);t&&(t.textContent=e)}function _$({intent:e,inventory:t,items:n,options:r}){const i=e.identities.filter($=>$.status==="active"&&$.mergedIntoIdentityId===null),a=new Map(i.map($=>[$.identityId,$.displayName])),s=new Set(a.keys()),[c,l]=D(()=>Object.fromEntries(n.map($=>[$.deviceId,xc($,s)]))),[d,u]=D(null),[p,f]=D(!1),[m,v]=D(!1),[b,h]=D(""),y=B(null),w=B(0),_=r.previewBindings??sh,R=r.commitBindings??ch,I=Dp(r),T=d!==null&&Dc(d.preview,d.request,n,"bind"),A=Ie(()=>n.filter($=>$.state==="setup_required"&&c[$.deviceId]?.selected),[c,n]),L=JSON.stringify({items:t.items.map(oo),coordinatorEvidence:t.coordinatorEvidence,truncated:t.truncated}),F=i.map($=>`${$.identityId}:${$.displayName}`).sort().join("|");V(()=>{d&&y.current?.focus()},[d]),V(()=>{w.current+=1,v(!1),l($=>Object.fromEntries(n.map(E=>{const C=$[E.deviceId];if(!C)return[E.deviceId,xc(E,s)];if(E.state!=="setup_required")return[E.deviceId,xc(E,s)];const O=C.targetIdentityId!==""&&s.has(C.targetIdentityId);return C.itemSignature===oo(E)&&O?[E.deviceId,C]:C.explicit&&O?[E.deviceId,{...C,selected:!1,itemSignature:oo(E)}]:[E.deviceId,xc(E,s)]}))),u(null),f(!1)},[L,F]);const N=($,E)=>{w.current+=1,v(!1),l(C=>({...C,[$]:{...C[$],...E}})),u(null),f(!1),h(""),Kn("")},j=$=>({bindings:$.map(E=>{const C=c[E.deviceId];return{deviceId:E.deviceId,targetIdentityId:C?.targetIdentityId??"",confirmed:!0}})}),x=async $=>{if(I){h("Refresh Devices before reviewing Identity setup.");return}if($.some(O=>O.state!=="setup_required")){h("Only devices that require Identity setup can be reviewed here.");return}const E=$.find(O=>Es(t,O).blocked);if(E){h(Es(t,E).recovery??"Identity setup is unavailable.");return}if($.length===0||$.some(O=>!c[O.deviceId]?.targetIdentityId)){h("Choose an Identity for every selected device before review.");return}v(!0),h(""),Kn("");const C=w.current;try{const O=j($),H=await _(O);C===w.current&&(Dc(H,O,$,"bind")?u({preview:H,request:O}):h("Identity setup preview was incomplete. Refresh and try again."))}catch(O){C===w.current&&h(ao(O))}C===w.current&&v(!1)},U=async()=>{if(!(!d||!p||I||!T)){v(!0),h("");try{await R({...d.request,reviewedInventoryDigest:d.preview.reviewedInventoryDigest}),u(null),f(!1),Kn("Identity setup completed.");const $=await r.onCommitted?.();Kn($===!1?"Identity setup completed, but refreshing Devices and Sharing failed. Refresh to see current state.":$===!0?"Identity setup completed. Devices and Sharing were refreshed.":"Identity setup completed."),document.getElementById("devices-heading")?.focus()}catch($){h(ao($))}v(!1)}},q=n.filter($=>$.state==="setup_required");return n.length===0?null:o(z,{children:[b?o("p",{role:"alert",children:b}):null,q.length>1?o("div",{className:"device-identity-setup-summary",children:[o("strong",{children:[q.length.toLocaleString()," devices need Identity setup"]}),o("button",{className:"settings-button",disabled:m||I||A.length===0,onClick:()=>{x(A)},type:"button",children:["Review ",A.length.toLocaleString()," selected"]})]}):null,o("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:n.map(($,E)=>{const C=c[$.deviceId],O=Es(t,$),H=O.blocked||I,G=`device-inventory-title-${E}`;return o("li",{children:o("article",{"aria-labelledby":G,className:"peer-card peer-card--padded recipient-policy-sharing-card device-identity-setup-card",id:`device-identity-card-${$.deviceId}`,tabIndex:-1,children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:G,children:[$.displayName,$.isLocal?" (this device)":""]}),o("span",{className:"badge actor-badge",children:$.state==="setup_required"?"Setup required":$.state==="pairing_required"?"Pairing required":$.state==="conflicted"?"Review required":"Configured"})]}),$.state==="setup_required"?o(z,{children:[o("fieldset",{children:[o("legend",{children:"Assign an existing Identity"}),i.length===0?o("p",{children:"No active Identity is available. Create or restore an Identity before setup."}):null,q.length>1?o("label",{children:[o("input",{"aria-label":`Select for setup: ${$.displayName}`,checked:C?.selected??!1,disabled:H,onInput:ee=>N($.deviceId,{selected:ee.currentTarget.checked}),type:"checkbox"})," ","Select for setup"]}):null,o("label",{htmlFor:`${G}-identity`,children:"Identity"}),o("select",{"aria-label":`Choose an Identity for ${$.displayName}`,disabled:H,id:`${G}-identity`,onInput:ee=>N($.deviceId,{targetIdentityId:ee.currentTarget.value,explicit:!0}),value:C?.targetIdentityId??"",children:[o("option",{value:"",children:"Choose Identity…"}),i.map(ee=>o("option",{value:ee.identityId,children:ee.displayName},ee.identityId))]}),$.suggestedIdentityId&&a.has($.suggestedIdentityId)?o("p",{className:"small",children:"Suggested from historical device information. Review it before applying setup."}):null,O.recovery?o("p",{className:"small",children:O.recovery}):null]}),o("div",{className:"device-identity-card-actions",children:[i.length===0?o("button",{"aria-label":`Open Identity administration for ${$.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Open Identity administration"}):null,o("button",{"aria-label":`Review this device: ${$.displayName}`,className:"settings-button",disabled:m||H||!C?.targetIdentityId,onClick:()=>{x([$])},type:"button",children:"Review this device"})]})]}):$.state==="pairing_required"?o(z,{children:[o("p",{children:"Pair this device first. Pairing establishes trust but does not choose its Identity."}),o("div",{className:"device-identity-card-actions",children:o("button",{"aria-label":`Go to pairing for ${$.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Go to pairing"})})]}):$.state==="conflicted"?o(z,{children:[o("p",{children:"Device evidence conflicts. Review and repair it before assigning an Identity."}),o("div",{className:"device-identity-card-actions",children:o("button",{"aria-label":`Open Advanced review for ${$.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Open Advanced review"})})]}):null]})},$.deviceId)})}),d?o("section",{"aria-labelledby":"device-identity-review-heading",className:"peer-card peer-card--padded device-identity-review-panel",children:[o("h3",{id:"device-identity-review-heading",ref:y,tabIndex:-1,children:"Review Identity setup"}),o("ul",{children:d.preview.outcomes.map($=>o("li",{children:[o("strong",{children:[$.displayName,":"]})," ",$.previousIdentityId?a.get($.previousIdentityId)??"Unavailable Identity":"No Identity"," ","→ ",a.get($.targetIdentityId)??"Unavailable Identity"]},$.deviceId))}),o("p",{children:"Identity setup records device ownership only. It does not grant Projects, Team membership, or sync access."}),o("label",{children:[o("input",{checked:p,disabled:I,onInput:$=>f($.currentTarget.checked),type:"checkbox"})," ","I reviewed every device and target Identity"]}),o("div",{className:"peer-actions",children:[o("button",{className:"settings-button",disabled:m,onClick:()=>{u(null),f(!1)},type:"button",children:"Back"}),o("button",{className:"settings-button sync-dialog-confirm",disabled:m||I||!p||!T,onClick:()=>{U()},type:"button",children:["Apply setup to ",d.request.bindings.length.toLocaleString()," ",d.request.bindings.length===1?"device":"devices"]})]})]}):null]})}function Qb({intent:e,inventory:t,item:n,options:r,previousIdentityName:i}){const a=e.identities.filter(C=>C.status==="active"&&C.mergedIntoIdentityId===null&&C.identityId!==n.identityId),[s,c]=D(!1),[l,d]=D(""),[u,p]=D(!1),[f,m]=D(null),[v,b]=D(!1),[h,y]=D(!1),[w,_]=D(""),R=B(0),I=i,T=new Map(e.identities.map(C=>[C.identityId,C.displayName])),A=f?.preview.status==="ready"&&f.preview.outcomes.length===1?f.preview.outcomes[0]:null,L=f!==null&&Dc(f.preview,f.request,[n],"rebind"),F=Es(t,n),N=F.blocked||Dp(r),j=`configured-rebind-trigger-${n.deviceId}`,x=a.find(C=>C.identityId===l)?.displayName??"",U=a.map(C=>C.identityId).sort().join("|"),q=oo(n);V(()=>{R.current+=1,y(!1),l&&!a.some(C=>C.identityId===l)&&(d(""),p(!1)),m(null),b(!1)},[U,q]);const $=async()=>{if(N){_(F.recovery??"Identity reassignment is unavailable.");return}if(!l||!u){_("Choose a target Identity and confirm the reassignment before review.");return}y(!0),_(""),Kn("");const C=R.current;try{const O={bindings:[{deviceId:n.deviceId,targetIdentityId:l,confirmed:u,allowRebind:!0}]},H=await(r.previewBindings??sh)(O);C===R.current&&(H.status!=="ready"?_(ao(new Xl(409,H.errorCode??"binding_preview_unavailable",H))):Dc(H,O,[n],"rebind")?m({preview:H,request:O}):_("Identity reassignment preview was incomplete. Refresh and try again."))}catch(O){C===R.current&&_(ao(O))}C===R.current&&y(!1)},E=async()=>{if(!(!f||!v||N||!L)){y(!0),_("");try{await(r.commitBindings??ch)({...f.request,reviewedInventoryDigest:f.preview.reviewedInventoryDigest}),c(!1),d(""),p(!1),m(null),b(!1),Kn("Identity reassignment completed.");const C=await r.onCommitted?.();Kn(C===!1?"Identity reassignment completed, but refreshing Devices and Sharing failed. Refresh to see current state.":C===!0?"Identity reassignment completed. Devices and Sharing were refreshed.":"Identity reassignment completed."),(document.getElementById(j)??document.getElementById("devices-heading"))?.focus()}catch(C){_(ao(C))}y(!1)}};return o("div",{className:"device-identity-rebind",children:[o("button",{"aria-expanded":s,className:"settings-button",disabled:N,id:j,onClick:()=>{R.current+=1,y(!1),c(!s),m(null),b(!1),_(""),Kn("")},type:"button",children:"Change Identity…"}),F.recovery?o("p",{className:"small",children:F.recovery}):null,s?o("fieldset",{children:[o("legend",{children:"Reassign this configured device"}),o("p",{children:[o("strong",{children:"Suggested current Identity (unconfirmed):"})," ",I]}),o("label",{htmlFor:`configured-rebind-${n.deviceId}`,children:"Target Identity"}),o("select",{disabled:N,id:`configured-rebind-${n.deviceId}`,onInput:C=>{R.current+=1,y(!1),d(C.currentTarget.value),p(!1),m(null),b(!1)},value:l,children:[o("option",{value:"",children:"Choose a different Identity…"}),a.map(C=>o("option",{value:C.identityId,children:C.displayName},C.identityId))]}),o("label",{children:[o("input",{checked:u,disabled:N||!l,onInput:C=>{R.current+=1,y(!1),p(C.currentTarget.checked),m(null),b(!1)},type:"checkbox"})," ","Confirm reassigning ",n.displayName," to ",x||"the selected Identity"]}),o("button",{className:"settings-button",disabled:h||N,onClick:()=>{$()},type:"button",children:"Review reassignment"}),f?o("div",{className:"device-identity-rebind-review",children:[o("h4",{children:"Review reassignment"}),o("p",{children:[A?.displayName,":"," ",A?.previousIdentityId?T.get(A.previousIdentityId)??"Unavailable Identity":"No Identity"," ","→"," ",T.get(A?.targetIdentityId??"")??"Unavailable Identity"]}),o("p",{className:"small",children:"This changes device ownership only. It does not grant Projects, Team membership, or sync access."}),o("label",{children:[o("input",{checked:v,disabled:N,onInput:C=>b(C.currentTarget.checked),type:"checkbox"})," ","I reviewed the previous and target Identities"]}),o("button",{className:"settings-button sync-dialog-confirm",disabled:h||N||!v||!L,onClick:()=>{E()},type:"button",children:"Reassign Identity"})]}):null,w?o("p",{"aria-live":"assertive",role:"alert",children:w}):null]}):null]})}function w$({intent:e,options:t,projection:n}){if(t.loading)return o(bv,{label:"Loading Devices"});if(t.loadError)return o("p",{"aria-live":"assertive",role:"alert",children:"Devices are unavailable. Refresh and try again."});const r=t.refreshError?o("p",{"aria-live":"assertive",role:"alert",children:"Refresh failed; showing previous device information. Identity setup is disabled until a refresh succeeds."}):null,i=n.devices.filter(f=>!t.inventory?.items.some(m=>m.state!=="configured"&&m.evidenceDeviceIds.includes(f.deviceId))),a=new Set(i.map(f=>f.deviceId)),s=t.inventoryUnavailable?o("p",{"aria-live":"polite",className:"small",role:"status",children:"Device ownership information is temporarily unavailable. Existing device details remain visible, but Identity setup is disabled until a refresh succeeds."}):null,c=_v(t.inventory),l=t.inventory?.items.filter(f=>f.state==="configured"&&!f.evidenceDeviceIds.some(m=>a.has(m)))??[],d=t.inventory?o("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:l.map((f,m)=>{const v=`configured-inventory-title-${m}`,b=e.identities.find(h=>h.identityId===f.identityId)?.displayName??"Unavailable Identity";return o("li",{children:o("article",{"aria-labelledby":v,className:"peer-card peer-card--padded recipient-policy-sharing-card",id:`device-identity-card-${f.deviceId}`,tabIndex:-1,children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:v,children:f.displayName}),o("span",{className:"badge actor-badge",children:"Configured · Availability unknown"})]}),o("p",{children:[o("strong",{children:"Owning Identity:"})," ",b]}),o(Qb,{intent:e,inventory:t.inventory,item:f,options:t,previousIdentityName:b})]})},f.deviceId)})}):null,u=(t.coordinatorEnrollmentIssueCount??0)>0?o("aside",{"aria-labelledby":"devices-coordinator-reconciliation-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"devices-coordinator-reconciliation-heading",children:"Coordinator setup needs attention"}),o("p",{children:[t.coordinatorEnrollmentIssueCount?.toLocaleString()," coordinator enrollment",t.coordinatorEnrollmentIssueCount===1?" could":"s could"," not be safely reconciled with device Identity setup."]}),o("p",{className:"small",children:["No ownership was inferred."," ",c.length>0?"Review the affected device setup or pairing state here, then retry after coordinator data is corrected.":"No device on this page can be corrected from here. Retry after coordinator data is corrected."]})]}):null,p=t.inventory?o(z,{children:[t.inventory.truncated?o("p",{"aria-live":"assertive",role:"alert",children:"The device inventory is incomplete. Identity setup is unavailable until a complete refresh succeeds."}):null,t.inventory.coordinatorEvidence.availability==="unavailable"?o("p",{className:"small",role:"status",children:"Coordinator device information is temporarily unavailable. Local devices remain visible, but some setup actions may require a refresh."}):null,o(_$,{intent:e,inventory:t.inventory,items:c,options:t})]}):null;return i.length===0?o(z,{children:[r,s,u,p,d,o("p",{className:"small",role:"status",children:[l.length>0?"No additional active devices are registered.":c.length>0?"No configured devices are registered.":"No active devices are registered.",n.revokedDeviceCount>0?` ${n.revokedDeviceCount.toLocaleString()} revoked ${n.revokedDeviceCount===1?"device is":"devices are"} not shown.`:""]})]}):o(z,{children:[r,s,u,p,d,o("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:i.map((f,m)=>{const v=`devices-card-title-${m}`,b=f.action,h=t.inventory?.items.find(y=>y.state==="configured"&&y.evidenceDeviceIds.includes(f.deviceId));return o("li",{children:o("article",{"aria-labelledby":v,className:"peer-card peer-card--padded recipient-policy-sharing-card",id:`device-identity-card-${f.deviceId}`,tabIndex:-1,children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:v,children:f.displayName}),o("span",{className:"badge actor-badge",children:[Dp(t)?"Device":"Configured"," ·"," ",f.availabilityLabel]})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Owning Identity"}),o("dd",{children:f.identityName})]}),o("div",{children:[o("dt",{children:"Availability"}),o("dd",{children:f.availabilityLabel})]}),f.isPairedPeer?o("div",{children:[o("dt",{children:"Codemem version"}),o("dd",{children:f.reportedRuntimeVersion??"Not reported"})]}):null,o("div",{children:[o("dt",{children:"Sharing status"}),o("dd",{children:[o("strong",{children:f.statusLabel})," — ",f.statusCopy]})]})]}),o("section",{"aria-labelledby":`${v}-direct`,children:[o("h4",{id:`${v}-direct`,children:"Direct Projects"}),o(Yb,{empty:"No Projects are shared directly.",projects:f.directProjects})]}),o("section",{"aria-labelledby":`${v}-teams`,children:[o("h4",{id:`${v}-teams`,children:"Projects through Teams"}),o(Yb,{empty:"Per-device Team access is not shown because Team membership alone does not prove this device receives the Team’s Projects.",projects:f.inheritedProjects})]}),f.unavailableProjectCount>0?o("p",{className:"small",role:"status",children:"Some Project names are unavailable and are not shown."}):null,f.deliveredCopiesMayRemain?o("p",{className:"small",children:[o("strong",{children:"Delivered copies:"})," Changing access stops future delivery, but copies already delivered may remain on this device or in backups."]}):null,b&&t.onNavigate?o("button",{"aria-label":`${b.label} for ${f.displayName}`,className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onNavigate?.(b.target),ref:y=>{y&&Lp.set(y,{deviceId:f.deviceId,target:b.target})},type:"button",children:b.label}):null,h&&t.inventory?o(Qb,{intent:e,inventory:t.inventory,item:h,options:t,previousIdentityName:f.identityName}):null]})},f.deviceId)})}),n.revokedDeviceCount>0?o("p",{className:"small",role:"status",children:[n.revokedDeviceCount.toLocaleString()," revoked"," ",n.revokedDeviceCount===1?"device is":"devices are"," not included in the active list."]}):null]})}function Lc(e,t,n,r,i,a={}){const s=document.activeElement,c=s instanceof HTMLElement&&e.contains(s),l=c?Lp.get(s):void 0,d=b$(t,n,r,i,a.peerRuntimeMetadata);if(Ue(o("section",{"aria-labelledby":"devices-heading",className:"recipient-policy-sharing recipient-policy-sharing-responsive-surface",children:[o("div",{className:"recipient-policy-sharing-header",children:[o("h2",{id:"devices-heading",tabIndex:-1,children:"Devices"}),o("p",{className:"small",children:"See where Codemem runs and which Projects each active device receives."})]}),o(w$,{intent:t,options:a,projection:d}),o("p",{"aria-live":"polite",id:Xb,role:"status"})]}),e),Kn(""),!a.loading&&S.pendingDeviceIdentityFocus!==void 0){const u=S.pendingDeviceIdentityFocus,p=a.inventory?.items.find(m=>m.deviceId===u||m.evidenceDeviceIds.includes(u??"")),f=[...u?[u]:[],...p?[p.deviceId,...p.evidenceDeviceIds]:[]].map(m=>document.getElementById(`device-identity-card-${m}`)).find(m=>m instanceof HTMLElement)??document.getElementById("device-identity-review-heading");if(c)S.pendingDeviceIdentityFocus=void 0;else if(f){S.pendingDeviceIdentityFocus=void 0,f.focus();return}else if(!a.inventoryUnavailable&&!a.refreshError){S.pendingDeviceIdentityFocus=void 0,(document.getElementById("devices-heading")??document.getElementById("tabBtn-devices"))?.focus();return}}l&&([...e.querySelectorAll("button")].find(u=>{const p=Lp.get(u);return p?.deviceId===l.deviceId&&p.target===l.target})??document.getElementById("tabBtn-devices"))?.focus()}function S$(e){if(!e)return"n/a";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function Zr(e){if(!e)return"never";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function C$(e){if(!e)return"n/a";const t=new Date(e),n=t.getTime();if(Number.isNaN(n))return String(e);const r=Date.now()-n,i=Math.round(r/1e3);if(i<10)return"just now";if(i<60)return`${i}s ago`;const a=Math.round(i/60);if(a<60)return`${a}m ago`;const s=Math.round(a/60);if(s<24)return`${s}h ago`;const c=Math.round(s/24);return c<14?`${c}d ago`:t.toLocaleDateString()}function Zi(e){if(!e)return null;const t=new Date(e).getTime();if(!Number.isFinite(t))return null;const n=Math.floor((Date.now()-t)/1e3);return n>=0?n:0}function ur(e){return e==null?"n/a":e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m`:e<86400?`${Math.floor(e/3600)}h`:`${Math.floor(e/86400)}d`}function Zb(e){const t=Number(e);return Number.isFinite(t)?`${Math.round(t*100)}%`:"n/a"}function R$(e,t){const n=Number(e||0),r=Number(t||0);if(!Number.isFinite(n)||!Number.isFinite(r)||r<=0)return"n/a";const i=(n+r)/r;return!Number.isFinite(i)||i<=0?"n/a":`${i.toFixed(i>=10?0:1)}x`}function $p(e,t){const n=Number(e||0),r=Number(t||0);if(!Number.isFinite(n)||!Number.isFinite(r))return"n/a";const i=n+r;if(i<=0)return"n/a";const a=n/i;return Number.isFinite(a)?`${Math.round(a*100)}%`:"n/a"}function so(e){const t=Number(e||0);if(!Number.isFinite(t))return"n/a";const n=[{threshold:1e9,suffix:"B"},{threshold:1e6,suffix:"M"},{threshold:1e3,suffix:"K"}];let r=n.findIndex(({threshold:i})=>Math.abs(t)>=i);if(r===-1)return`${t.toLocaleString()} tokens`;for(;r>=0;){const{suffix:i,threshold:a}=n[r],s=t/a,c=Number(s.toFixed(s>=10?0:1));if(Math.abs(c)<1e3||r===0)return`${c.toString().replace(/\.0$/,"")}${i} tokens`;r-=1}return`${t.toLocaleString()} tokens`}function I$(e){const t=String(e||"").trim();if(!t.endsWith("%"))return null;const n=Number(t.replace("%",""));return Number.isFinite(n)?n:null}function co(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function $c(e){if(!e)return[];if(Array.isArray(e))return e;if(typeof e=="string")try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}return[]}function e_(e){const t=String(e||"").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function k$(e){return e.replace(/_/g," ").split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ").trim()}function T$(e,t=2){if(!e.length)return"";const n=e.map(a=>String(a).trim()).filter(Boolean),r=n.slice(0,t),i=n.length>t?` +${n.length-t}`:"";return`${r.join(", ")}${i}`.trim()}function P$(e){if(!e)return"";const t=String(e).trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n).trim()}function N$(e){const t=String(e||"");return t?t.replace(/^\/Users\/[^/]+(?=\/|$)/,"~").replace(/^\/home\/[^/]+(?=\/|$)/,"~").replace(/^[A-Z]:\\Users\\[^\\]+(?=\\|$)/,"~"):""}function E$(e){const t=Number(e||0);if(!Number.isFinite(t)||t<0)return"n/a";if(t<1024)return`${t} B`;const n=["KB","MB","GB","TB","PB"],r=s=>s>=10?Math.round(s):Number(s.toFixed(1));let i=t/1024,a=0;for(;a<n.length-1&&r(i)>=1024;)i/=1024,a+=1;return`${String(r(i)).replace(/\.0$/,"")} ${n[a]}`}function t_(e){if(e.owned_by_self===!0)return!0;const t=String(e.actor_id||"").trim();return!!(t&&t===S.viewerActorId)}function jc(e){if(!e||typeof e!="object")return{};const t=e,n=t.import_metadata;return n&&typeof n=="object"?{...n,...t}:t}function A$(e){if(!e)return[];const t=String(e).split(`
42
+ `).map(n=>n.trim()).filter(Boolean).filter(n=>/^[-*\u2022]\s+/.test(n)||/^\d+\./.test(n));return t.length?t.map(n=>n.replace(/^[-*\u2022]\s+/,"").replace(/^\d+\.\s+/,"")):[]}function x$(e,t=6){const n=String(e||"").trim();if(!n)return[];const r=n.replace(/\s+/g," ").trim().split(/(?<=[.!?])\s+/).map(a=>a.trim()).filter(Boolean),i=[];for(const a of r)if(!(a.length<18)&&(i.push(a),i.length>=t))break;return i}function n_(e){const t=co(e.title),n=co(e.body_text);if(!t&&!n)return!0;const r=n||t;if(r.length<10||t&&n&&t===n&&r.length<40)return!0;const i=t.charAt(0);return!!((i==="└"||i==="›")&&r.length<40||t.startsWith("list ")&&r.length<20||r==="ls"||r==="list ls")}function r_(e){return String(e.id??e.memory_id??e.observation_id??e.session_id??e.created_at_utc??e.created_at??"")}function Nt(e){return`${String(e.kind||"").toLowerCase()}:${r_(e)}`}function D$(e){if(e.tags!=null)return $c(e.tags);const t=$c(e.tags_text);return t.length>0?t:typeof e.tags_text!="string"?[]:e.tags_text.trim().split(/\s+/).filter(Boolean)}function L$(e){return e==="mine"?" · my memories":e==="theirs"?" · other people":""}function $$(e){return e==="legacy_unknown"?"legacy provenance":e==="unreviewed"?"unreviewed":e.replace(/_/g," ")}function j$(e){if(t_(e))return"You";const t=String(e.actor_id||"").trim(),n=Li(e.resolved_actor_display_name);return n||(t||e.actor_display_name?"Teammate":"Unknown author")}function O$(e,t={}){if(t_(e)||!String(e.origin_device_id||t.origin_device_id||"").trim())return"";const n=Li(e.resolved_device_display_name);return n?`Device ${n}`:"Shared device"}function i_(e,t){const n=new Map;return e.forEach(r=>{n.set(Nt(r),r)}),t.forEach(r=>{n.set(Nt(r),r)}),Array.from(n.values()).sort((r,i)=>new Date(i.created_at||0).getTime()-new Date(r.created_at||0).getTime())}function M$(e,t){const n=new Set(t.map(Nt));return i_(e.filter(r=>!n.has(Nt(r))),t)}var WH=560;function F$(){const e=document.documentElement,t=Math.max(e.scrollHeight,document.body.scrollHeight);return window.innerHeight+window.scrollY>=t-560}function Oc(e,t,n){const r=e.pagination?.has_more;return typeof r=="boolean"?r:t>=n}function Mc(e,t){const n=e.pagination?.next_offset;return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:t}function B$(e,t){const n=new Set(t.map(Nt));return e.filter(r=>!n.has(Nt(r))).length}var q$=Object.defineProperty,it=(e,t)=>q$(e,"name",{value:t,configurable:!0}),[jp,JH]=dt("Tooltip",[ar]),Fc=ar(),U$="TooltipProvider",G$=700,Op="tooltip.open",[H$,Mp]=jp(U$),V$=it(e=>{const{__scopeTooltip:t,delayDuration:n=G$,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:a}=e,s=B(!0),c=B(!1),l=B(0);return V(()=>{const d=l.current;return()=>window.clearTimeout(d)},[]),o(H$,{scope:t,isOpenDelayedRef:s,delayDuration:n,onOpen:oe(()=>{r<=0||(window.clearTimeout(l.current),s.current=!1)},[r]),onClose:oe(()=>{r<=0||(window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.current=!0,r))},[r]),isPointerInTransitRef:c,onPointerInTransitChange:oe(d=>{c.current=d},[]),disableHoverableContent:i,children:a})},"TooltipProvider"),Fp="Tooltip",[K$,lo]=jp(Fp),z$=it(e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:a,disableHoverableContent:s,delayDuration:c}=e,l=Mp(Fp,e.__scopeTooltip),d=Fc(t),[u,p]=D(null),[f,m]=D(void 0),v=xt(),b=B(0),h=s??l.disableHoverableContent,y=c??l.delayDuration,w=B(!1),[_,R]=Dt({prop:r,defaultProp:i??!1,onChange:it(N=>{N?(l.onOpen(),document.dispatchEvent(new CustomEvent(Op))):l.onClose(),a?.(N)},"onChange"),caller:Fp}),I=Ie(()=>_?w.current?"delayed-open":"instant-open":"closed",[_]),T=oe(()=>{window.clearTimeout(b.current),b.current=0,w.current=!1,R(!0)},[R]),A=oe(()=>{window.clearTimeout(b.current),b.current=0,R(!1)},[R]),L=oe(()=>{window.clearTimeout(b.current),b.current=window.setTimeout(()=>{w.current=!0,R(!0),b.current=0},y)},[y,R]);return V(()=>()=>{b.current&&(window.clearTimeout(b.current),b.current=0)},[]),o(vc,{...d,children:o(K$,{scope:t,contentId:f??v,setContentId:m,open:_,stateAttribute:I,trigger:u,onTriggerChange:p,onTriggerEnter:oe(()=>{l.isOpenDelayedRef.current?L():T()},[l.isOpenDelayedRef,L,T]),onTriggerLeave:oe(()=>{h?A():(window.clearTimeout(b.current),b.current=0)},[A,h]),onOpen:T,onClose:A,disableHoverableContent:h,children:n})})},"Tooltip"),a_="TooltipTrigger",W$=W(it(function(t,n){const{__scopeTooltip:r,...i}=t,a=lo(a_,r),s=Mp(a_,r),c=Fc(r),l=B(null),d=Se(n,l,a.onTriggerChange),u=B(!1),p=B(!1),f=oe(()=>u.current=!1,[]);return V(()=>()=>document.removeEventListener("pointerup",f),[f]),o(eo,{asChild:!0,...c,children:o(ge.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...i,ref:d,onPointerMove:ne(t.onPointerMove,m=>{m.pointerType!=="touch"&&!p.current&&!s.isPointerInTransitRef.current&&(a.onTriggerEnter(),p.current=!0)}),onPointerLeave:ne(t.onPointerLeave,()=>{a.onTriggerLeave(),p.current=!1}),onPointerDown:ne(t.onPointerDown,()=>{a.open&&a.onClose(),u.current=!0,document.addEventListener("pointerup",f,{once:!0})}),onFocus:ne(t.onFocus,()=>{u.current||a.onOpen()}),onBlur:ne(t.onBlur,a.onClose),onClick:ne(t.onClick,a.onClose)})})},"TooltipTrigger")),o_="TooltipPortal",[J$,Y$]=jp(o_,{forceMount:void 0}),X$=it(e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,a=lo(o_,t);return o(J$,{scope:t,forceMount:n,children:o(Pt,{present:n||a.open,children:o(Ti,{asChild:!0,container:i,children:r})})})},"TooltipPortal"),uo="TooltipContent",Q$=W(it(function(t,n){const r=Y$(uo,t.__scopeTooltip),{forceMount:i=r.forceMount,side:a="top",...s}=t,c=lo(uo,t.__scopeTooltip);return o(Pt,{present:i||c.open,children:c.disableHoverableContent?o(s_,{side:a,...s,ref:n}):o(Z$,{side:a,...s,ref:n})})},"TooltipContent")),Z$=W(it(function(t,n){const r=lo(uo,t.__scopeTooltip),i=Mp(uo,t.__scopeTooltip),a=B(null),s=Se(n,a),[c,l]=D(null),{trigger:d,onClose:u}=r,p=a.current,{onPointerInTransitChange:f}=i,m=oe(()=>{l(null),f(!1)},[f]),v=oe((b,h)=>{const y=b.currentTarget,w={x:b.clientX,y:b.clientY},_=l_(w,c_(w,y.getBoundingClientRect())),R=d_(h.getBoundingClientRect()),I=p_([..._,...R]);l(I),f(!0)},[f]);return V(()=>()=>m(),[m]),V(()=>{if(d&&p){const b=it(y=>v(y,p),"handleTriggerLeave"),h=it(y=>v(y,d),"handleContentLeave");return d.addEventListener("pointerleave",b),p.addEventListener("pointerleave",h),()=>{d.removeEventListener("pointerleave",b),p.removeEventListener("pointerleave",h)}}},[d,p,v,m]),V(()=>{if(c){const b=it(h=>{const y=h.target,w={x:h.clientX,y:h.clientY},_=d?.contains(y)||p?.contains(y),R=!u_(w,c);_?m():R&&(m(),u())},"handleTrackPointerGrace");return document.addEventListener("pointermove",b),()=>document.removeEventListener("pointermove",b)}},[d,p,c,u,m]),o(s_,{...t,ref:s})},"TooltipContentHoverable")),ej=kg("TooltipContent"),s_=W(it(function(t,n){const{__scopeTooltip:r,children:i,"aria-label":a,id:s,onEscapeKeyDown:c,onPointerDownOutside:l,...d}=t,u=lo(uo,r),p=Fc(r),{onClose:f}=u;V(()=>(document.addEventListener(Op,f),()=>document.removeEventListener(Op,f)),[f]),V(()=>{if(u.trigger){const v=it(b=>{b.target instanceof Node&&b.target.contains(u.trigger)&&f()},"handleScroll");return window.addEventListener("scroll",v,{capture:!0}),()=>window.removeEventListener("scroll",v,{capture:!0})}},[u.trigger,f]);const{setContentId:m}=u;return Xe(()=>(m(s),()=>{m(void 0)}),[s,m]),o(ki,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:v=>v.preventDefault(),onDismiss:f,children:o(yc,{"data-state":u.stateAttribute,role:a?void 0:"tooltip",id:a?void 0:u.contentId,...p,...d,ref:n,style:{...d.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o(ej,{children:i}),a?o(vE,{id:u.contentId,role:"tooltip",children:a}):null]})})},"TooltipContentImpl")),tj=W(it(function(t,n){const{__scopeTooltip:r,...i}=t,a=Fc(r);return o(S0,{...a,...i,ref:n})},"TooltipArrow"));function c_(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),a=Math.abs(t.left-e.x);switch(Math.min(n,r,i,a)){case a:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}it(c_,"getExitSideFromRect");function l_(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n})}return r}it(l_,"getPaddedExitPoints");function d_(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}it(d_,"getPointsFromRect");function u_(e,t){const{x:n,y:r}=e;let i=!1;for(let a=0,s=t.length-1;a<t.length;s=a++){const c=t[a],l=t[s],d=c.x,u=c.y,p=l.x,f=l.y;u>r!=f>r&&n<(p-d)*(r-u)/(f-u)+d&&(i=!i)}return i}it(u_,"isPointInPolygon");function p_(e){const t=e.slice();return t.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),f_(t)}it(p_,"getHull");function f_(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const i=e[r];for(;t.length>=2;){const a=t[t.length-1],s=t[t.length-2];if((a.x-s.x)*(i.y-s.y)>=(a.y-s.y)*(i.x-s.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const a=n[n.length-1],s=n[n.length-2];if((a.x-s.x)*(i.y-s.y)>=(a.y-s.y)*(i.x-s.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}it(f_,"getHullPresorted");var nj=V$,rj=z$,ij=W$,aj=X$,oj=Q$,sj=tj;function Bc({children:e,delayDuration:t=400,skipDelayDuration:n=300}){return o(nj,{delayDuration:t,skipDelayDuration:n,children:e})}function qc({children:e,label:t,side:n="top",align:r="center",sideOffset:i=6,asChild:a=!0,disabled:s=!1}){return s?o(z,{children:e}):o(rj,{children:[o(ij,{asChild:a,children:e}),o(aj,{children:o(oj,{align:r,className:"tooltip-content",side:n,sideOffset:i,children:[t,o(sj,{className:"tooltip-arrow"})]})})]})}function cj(e){e.dataset.feedRenderRoot="preact"}function lj(){const e=document.getElementById("tab-feed");e&&(e.dataset.feedRenderBoundary="preact-hybrid")}function dj(e,t){cj(e),Ue(g(Bc,null,t),e)}function uj(e){return e.hasInspectorOverride?e.inspectorQuery:e.feedQuery}function pj(e){return e.split(/\n|,/).map(t=>t.trim()).filter(Boolean)}function Bp(e){return JSON.stringify([e.project,e.query.trim(),e.workingSetFiles])}function fj(e){const t=jc(e?.metadata_json),n=String(e?.subtitle||t?.subtitle||"").trim(),r=String(e?.narrative||t?.narrative||e?.body_text||"").trim(),i=co(n),a=co(r),s=!!r&&a!==i,c=$c(e?.facts||t?.facts||[]),l=c.length?c:A$(r||n),d=l.length?l:x$(r||n);return{summary:n,narrative:r,facts:d,hasSummary:!!n,hasFacts:d.length>0,hasNarrative:s}}function mj(e){const t=[];return e.hasSummary&&t.push({id:"summary",label:"Summary"}),e.hasFacts&&t.push({id:"facts",label:"Facts"}),e.hasNarrative&&t.push({id:"narrative",label:"Narrative"}),t}function hj(e){return e.hasSummary?"summary":e.hasFacts?"facts":"narrative"}function gj(e,t){return e==="facts"?!1:e==="summary"?t.summary.length>260:t.narrative.length>320}function vj(e){return e==="summary"?["clamp","clamp-3"]:["clamp","clamp-5"]}function yj(e,t){const n=S.feedTypeFilter==="observations"?" · observations":S.feedTypeFilter==="summaries"?" · session summaries":"",r=L$(S.feedScopeFilter),i=!S.feedQuery.trim()&&S.lastFeedFilteredCount?` · ${S.lastFeedFilteredCount} observations filtered`:"";return`${e} items${n}${r}${S.feedQuery.trim()?` · matching "${S.feedQuery.trim()}"`:""}${i}${t?" · scroll for more":""}`}function Uc({label:e,candidates:t}){return t.length===0?null:g("div",{className:"trace-group"},g("div",{className:"section-meta"},e),g("div",{className:"feed-list"},t.map(n=>g("div",{className:"feed-card",key:`${e}:${n.id}`},g("div",{className:"feed-card-header"},[g("div",{className:"feed-card-title"},`${n.rank}. ${n.title}`),g("div",{className:"feed-card-meta"},`#${n.id} · ${n.kind}${n.section?` · ${n.section}`:""}`)]),g("div",{className:"feed-card-body"},[g("div",null,n.preview||"No preview available."),n.reasons.length?g("div",{className:"section-meta"},`Reasons: ${n.reasons.join(", ")}`):null])))))}function bj({open:e}){const[t,n]=D(()=>String(S.feedQuery||"")),[r,i]=D(!1),[a,s]=D(!1),[c,l]=D(""),[d,u]=D(!1),[p,f]=D(""),[m,v]=D(""),[b,h]=D(null),y=B(0),w=String(S.feedQuery||""),_=String(t||"").trim(),R=S.currentProject||null,I=pj(c),T=Bp({project:R,query:_,workingSetFiles:I}),A=b&&Bp({project:b.inputs.project,query:b.inputs.query,workingSetFiles:b.inputs.working_set_files})===T?b:null,L=p&&m===T?p:"";V(()=>{y.current+=1,u(!1),f(""),v(""),h(q=>!q||q.inputs.query!==_||q.inputs.project!==R?null:q)},[T]),V(()=>{e&&!r&&(n(uj({feedQuery:w,hasInspectorOverride:a,inspectorQuery:t})),i(!0))},[w,a,r,t,e]);const F=async()=>{const q=_,$=R,E=I,C=Bp({project:$,query:q,workingSetFiles:E}),O=y.current+1;if(y.current=O,!q){f("Enter a query to inspect."),v(C),h(null);return}u(!0),f(""),v("");try{const H=await TR({context:q,project:$,working_set_files:E});if(O!==y.current)return;h(H)}catch(H){if(O!==y.current)return;f(H instanceof Error?H.message:String(H)),v(C),h(null)}finally{O===y.current&&u(!1)}},N=A?.retrieval.candidates.filter(q=>q.disposition==="selected")||[],j=A?.retrieval.candidates.filter(q=>q.disposition==="dropped")||[],x=A?.retrieval.candidates.filter(q=>q.disposition==="deduped")||[],U=A?.retrieval.candidates.filter(q=>q.disposition==="trimmed")||[];return e?g("div",{className:"feed-inspector"},g("div",{className:"feed-card",id:"contextInspectorPanel",style:"margin-top:12px;"},[g("div",{className:"feed-card-header"},[g("div",{className:"feed-card-title"},"Context Inspector"),g("div",{className:"feed-card-meta"},a?"Tracing an inspector-specific query":"Seeded from the feed search on first open")]),g("div",{className:"feed-card-body"},[g("input",{className:"feed-search",onInput:q=>{n(String(q.currentTarget.value||"")),s(!0),h(null),f(""),v("")},placeholder:"Trace a pack query…",value:t}),g("div",{className:"section-meta",style:"margin-top:8px;"},a?"Inspector query is independent from the live feed search.":"Inspector query was seeded from the feed search and will stay independent until you change it."),g("textarea",{className:"feed-inspector-files",onInput:q=>l(String(q.currentTarget.value||"")),placeholder:"Optional working-set files, one per line",rows:3,value:c}),g("div",{style:"display:flex; gap:8px; margin-top:8px; align-items:center;"},g("button",{className:"toggle-button active",disabled:d,onClick:()=>{F()},type:"button"},d?"Tracing…":"Run trace"),A?g("span",{className:"section-meta"},`mode=${A.mode.selected} · candidates=${A.retrieval.candidate_count} · tokens=${A.output.estimated_tokens}`):null),b&&!A?g("div",{className:"section-meta",style:"margin-top:8px;"},"Trace inputs changed. Run trace again for the current query, project, and working set."):null,L?g("div",{className:"section-meta",style:"margin-top:8px; color:#d96c6c;"},L):null]),A?g(z,null,[g(Uc,{label:"Selected",candidates:N}),g(Uc,{label:"Dropped",candidates:j}),g(Uc,{label:"Deduped",candidates:x}),g(Uc,{label:"Trimmed",candidates:U}),g("div",{className:"feed-card-body"},[A.assembly.collapsed_groups.length?g("div",{className:"section-meta"},`Collapsed duplicates: ${A.assembly.collapsed_groups.map(q=>`kept #${q.kept} from [${q.dropped.join(", ")}]`).join(" · ")}`):null,A.assembly.trim_reasons.length?g("div",{className:"section-meta"},`Trim reasons: ${A.assembly.trim_reasons.join(", ")}`):null,g("div",{className:"section-meta"},"Final pack"),g("pre",{style:"white-space:pre-wrap; overflow:auto;"},A.output.pack_text)])]):null])):null}var _j={kind:"kind-chip",provenance:"provenance-chip",tag:"tag-chip",badge:"badge",scope:"peer-scope-chip"};function qp({variant:e,tone:t,title:n,children:r}){const i=_j[e],a=t?`${i} ${t}`:i;return o("span",{className:a,title:n,children:r})}function m_(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function wj(e){if(Array.isArray(e))return e}function Sj(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,a,s,c=[],l=!0,d=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(l=(r=a.call(n)).done)&&(c.push(r.value),c.length!==t);l=!0);}catch(u){d=!0,i=u}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw i}}return c}}function Cj(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
43
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Rj(e,t){return wj(e)||Sj(e,t)||Ij(e,t)||Cj()}function Ij(e,t){if(e){if(typeof e=="string")return m_(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?m_(e,t):void 0}}var h_=Object.entries,g_=Object.setPrototypeOf,kj=Object.isFrozen,Tj=Object.getPrototypeOf,Pj=Object.getOwnPropertyDescriptor,at=Object.freeze,st=Object.seal,ea=Object.create,v_=typeof Reflect<"u"&&Reflect,Up=v_.apply,Gp=v_.construct;at||(at=function(t){return t}),st||(st=function(t){return t}),Up||(Up=function(t,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),a=2;a<r;a++)i[a-2]=arguments[a];return t.apply(n,i)}),Gp||(Gp=function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return new t(...r)});var ei=Ze(Array.prototype.forEach),Nj=Ze(Array.prototype.lastIndexOf),y_=Ze(Array.prototype.pop),po=Ze(Array.prototype.push),Ej=Ze(Array.prototype.splice),ta=Array.isArray,fo=Ze(String.prototype.toLowerCase),Hp=Ze(String.prototype.toString),b_=Ze(String.prototype.match),mo=Ze(String.prototype.replace),__=Ze(String.prototype.indexOf),Aj=Ze(String.prototype.trim),xj=Ze(Number.prototype.toString),Dj=Ze(Boolean.prototype.toString),w_=typeof BigInt>"u"?null:Ze(BigInt.prototype.toString),S_=typeof Symbol>"u"?null:Ze(Symbol.prototype.toString),Et=Ze(Object.prototype.hasOwnProperty),ho=Ze(Object.prototype.toString),vt=Ze(RegExp.prototype.test),ti=Lj(TypeError);function Ze(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return Up(e,t,r)}}function Lj(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return Gp(e,n)}}function xe(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:fo;if(g_&&g_(e,null),!ta(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i=="string"){const a=n(i);a!==i&&(kj(t)||(t[r]=a),i=a)}e[i]=!0}return e}function $j(e){for(let t=0;t<e.length;t++)Et(e,t)||(e[t]=null);return e}function Mt(e){const t=ea(null);for(const r of h_(e)){var n=Rj(r,2);const i=n[0],a=n[1];Et(e,i)&&(ta(a)?t[i]=$j(a):a&&typeof a=="object"&&a.constructor===Object?t[i]=Mt(a):t[i]=a)}return t}function jj(e){switch(typeof e){case"string":return e;case"number":return xj(e);case"boolean":return Dj(e);case"bigint":return w_?w_(e):"0";case"symbol":return S_?S_(e):"Symbol()";case"undefined":return ho(e);case"function":case"object":{if(e===null)return ho(e);const t=e,n=en(t,"toString");if(typeof n=="function"){const r=n(t);return typeof r=="string"?r:ho(r)}return ho(e)}default:return ho(e)}}function en(e,t){for(;e!==null;){const r=Pj(e,t);if(r){if(r.get)return Ze(r.get);if(typeof r.value=="function")return Ze(r.value)}e=Tj(e)}function n(){return null}return n}function Oj(e){try{return vt(e,""),!0}catch{return!1}}var C_=at(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Vp=at(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Kp=at(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Mj=at(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),zp=at(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Fj=at(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),R_=at(["#text"]),I_=at(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Wp=at(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","pointer-events","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","vector-effect","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),k_=at(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Gc=at(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Bj=st(/{{[\w\W]*|^[\w\W]*}}/g),qj=st(/<%[\w\W]*|^[\w\W]*%>/g),Uj=st(/\${[\w\W]*/g),Gj=st(/^data-[\-\w.\u00B7-\uFFFF]+$/),Hj=st(/^aria-[\-\w]+$/),T_=st(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Vj=st(/^(?:\w+script|data):/i),Kj=st(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),zj=st(/^html$/i),Wj=st(/^[a-z][.\w]*(-[.\w]+)+$/i),P_=st(/<[/\w!]/g),N_=st(/<[/\w]/g),Jj=st(/<\/no(script|embed|frames)/i),Yj=st(/\/>/i),Ft={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},E_=["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"],Xj=at(xe({},E_)),Qj=(function(){const e={};return ei(E_,t=>{e[t]=st(new RegExp("</"+t+"(?=[\\t\\n\\f\\r />])","i"))}),at(e)})(),Zj=function(){return typeof window>"u"?null:window},eO=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let r=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));const a="dompurify"+(r?"#"+r:"");try{return t.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},A_=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},pr=function(t,n,r,i){return Et(t,n)&&ta(t[n])?xe(i.base?Mt(i.base):{},t[n],i.transform):r},Jp=function(t,n,r){const i=Et(t,n)?t[n]:void 0;return i&&typeof i=="object"?Mt(i):r()};function x_(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Zj();const t=Y=>x_(Y);if(t.version="3.4.14",t.removed=[],!e||!e.document||e.document.nodeType!==Ft.document||!e.Element)return t.isSupported=!1,t;let n=e.document;const r=n,i=r.currentScript;e.DocumentFragment;const a=e.HTMLTemplateElement,s=e.Node,c=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const d=e.DOMParser,u=e.trustedTypes,p=c.prototype,f=en(p,"cloneNode"),m=en(p,"remove"),v=en(p,"nextSibling"),b=en(p,"childNodes"),h=en(p,"parentNode"),y=en(p,"shadowRoot"),w=en(p,"attributes"),_=s&&s.prototype?en(s.prototype,"nodeType"):null,R=s&&s.prototype?en(s.prototype,"nodeName"):null,I=s&&s.prototype?en(s.prototype,"ownerDocument"):null,T=function(k){return _?_(k):k.nodeType},A=function(k){return R?R(k):k.nodeName};if(typeof a=="function"){const Y=n.createElement("template");Y.content&&Y.content.ownerDocument&&(n=Y.content.ownerDocument)}let L,F="",N,j=!1,x=0;const U=function(){if(x>0)throw ti('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},q=function(k){U(),x++;try{return L.createHTML(k)}finally{x--}},$=function(k){U(),x++;try{return L.createScriptURL(k)}finally{x--}},E=function(){return j||(N=eO(u,i),j=!0),N},C=n,O=C.implementation,H=C.createNodeIterator,G=C.createDocumentFragment,ee=C.getElementsByTagName,Z=r.importNode;let ie=A_();t.isSupported=typeof h_=="function"&&typeof h=="function"&&O&&O.createHTMLDocument!==void 0;const fe=Bj,Ce=qj,Pe=Uj,Ne=Gj,ce=Hj,me=Vj,J=Kj,se=Wj;let ye=T_,le=null;const Ee=xe({},[...C_,...Vp,...Kp,...zp,...R_]);let re=null;const Q=xe({},[...I_,...Wp,...k_,...Gc]);let we=Object.seal(ea(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ae=null,Fe=null;const Je=Object.seal(ea(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let wn=!0,Sn=!0,kr=!1,Re=!0,et=!1,tt=!0,Cn=!1,Yo=!1,gi=null,vi=null,yi=!1,lt=!1,Rn=!1,ga=!1,OC=!0,MC=!1;const FC="user-content-";let Im=!0,km=!1,va={},ya=null;const BC=xe({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let qC=null;const UC=xe({},["audio","video","img","source","image","track"]);let GC=null;const HC=xe({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),jl="http://www.w3.org/1998/Math/MathML",Ol="http://www.w3.org/2000/svg",In="http://www.w3.org/1999/xhtml";let ba=In,Tm=!1,Pm=null;const vH=xe({},[jl,Ol,In],Hp),VC=at(["mi","mo","mn","ms","mtext"]);let Nm=xe({},VC);const KC=at(["annotation-xml"]);let Em=xe({},KC);const yH=xe({},["title","style","font","a","script"]);let Xo=null;const bH=["application/xhtml+xml","text/html"],_H="text/html";let Ye=null,_a=null;const wH=n.createElement("form"),zC=function(k){return k instanceof RegExp||k instanceof Function},Am=function(){let k=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(_a&&_a===k)return;(!k||typeof k!="object")&&(k={}),k=Mt(k),Xo=bH.indexOf(k.PARSER_MEDIA_TYPE)===-1?_H:k.PARSER_MEDIA_TYPE,Ye=Xo==="application/xhtml+xml"?Hp:fo,le=pr(k,"ALLOWED_TAGS",Ee,{transform:Ye}),re=pr(k,"ALLOWED_ATTR",Q,{transform:Ye}),Pm=pr(k,"ALLOWED_NAMESPACES",vH,{transform:Hp}),GC=pr(k,"ADD_URI_SAFE_ATTR",HC,{transform:Ye,base:HC}),qC=pr(k,"ADD_DATA_URI_TAGS",UC,{transform:Ye,base:UC}),ya=pr(k,"FORBID_CONTENTS",BC,{transform:Ye}),ae=pr(k,"FORBID_TAGS",Mt({}),{transform:Ye}),Fe=pr(k,"FORBID_ATTR",Mt({}),{transform:Ye}),va=Et(k,"USE_PROFILES")?k.USE_PROFILES&&typeof k.USE_PROFILES=="object"?Mt(k.USE_PROFILES):k.USE_PROFILES:!1,wn=k.ALLOW_ARIA_ATTR!==!1,Sn=k.ALLOW_DATA_ATTR!==!1,kr=k.ALLOW_UNKNOWN_PROTOCOLS||!1,Re=k.ALLOW_SELF_CLOSE_IN_ATTR!==!1,et=k.SAFE_FOR_TEMPLATES||!1,tt=k.SAFE_FOR_XML!==!1,Cn=k.WHOLE_DOCUMENT||!1,lt=k.RETURN_DOM||!1,Rn=k.RETURN_DOM_FRAGMENT||!1,ga=k.RETURN_TRUSTED_TYPE||!1,yi=k.FORCE_BODY||!1,OC=k.SANITIZE_DOM!==!1,MC=k.SANITIZE_NAMED_PROPS||!1,Im=k.KEEP_CONTENT!==!1,km=k.IN_PLACE||!1,ye=Oj(k.ALLOWED_URI_REGEXP)?k.ALLOWED_URI_REGEXP:T_,ba=typeof k.NAMESPACE=="string"?k.NAMESPACE:In,Nm=Jp(k,"MATHML_TEXT_INTEGRATION_POINTS",()=>xe({},VC)),Em=Jp(k,"HTML_INTEGRATION_POINTS",()=>xe({},KC));const M=Jp(k,"CUSTOM_ELEMENT_HANDLING",()=>ea(null));if(we=ea(null),Et(M,"tagNameCheck")&&zC(M.tagNameCheck)&&(we.tagNameCheck=M.tagNameCheck),Et(M,"attributeNameCheck")&&zC(M.attributeNameCheck)&&(we.attributeNameCheck=M.attributeNameCheck),Et(M,"allowCustomizedBuiltInElements")&&typeof M.allowCustomizedBuiltInElements=="boolean"&&(we.allowCustomizedBuiltInElements=M.allowCustomizedBuiltInElements),st(we),et&&(Sn=!1),Rn&&(lt=!0),va&&(le=xe({},R_),re=ea(null),va.html===!0&&(xe(le,C_),xe(re,I_)),va.svg===!0&&(xe(le,Vp),xe(re,Wp),xe(re,Gc)),va.svgFilters===!0&&(xe(le,Kp),xe(re,Wp),xe(re,Gc)),va.mathMl===!0&&(xe(le,zp),xe(re,k_),xe(re,Gc))),Je.tagCheck=null,Je.attributeCheck=null,Et(k,"ADD_TAGS")&&(typeof k.ADD_TAGS=="function"?Je.tagCheck=k.ADD_TAGS:ta(k.ADD_TAGS)&&(le===Ee&&(le=Mt(le)),xe(le,k.ADD_TAGS,Ye))),Et(k,"ADD_ATTR")&&(typeof k.ADD_ATTR=="function"?Je.attributeCheck=k.ADD_ATTR:ta(k.ADD_ATTR)&&(re===Q&&(re=Mt(re)),xe(re,k.ADD_ATTR,Ye))),Et(k,"ADD_FORBID_CONTENTS")&&ta(k.ADD_FORBID_CONTENTS)&&(ya===BC&&(ya=Mt(ya)),xe(ya,k.ADD_FORBID_CONTENTS,Ye)),Im&&(le["#text"]=!0),Cn&&xe(le,["html","head","body"]),le.table&&(xe(le,["tbody"]),delete ae.tbody),k.TRUSTED_TYPES_POLICY){if(typeof k.TRUSTED_TYPES_POLICY.createHTML!="function")throw ti('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof k.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ti('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const K=L;L=k.TRUSTED_TYPES_POLICY;try{F=q("")}catch(te){throw L=K,te}}else k.TRUSTED_TYPES_POLICY===null?(L=void 0,F=""):(L===void 0&&(L=E()),L&&typeof F=="string"&&(F=q("")));at&&at(k),_a=k},WC=xe({},[...Vp,...Kp,...Mj]),JC=xe({},[...zp,...Fj]),SH=function(k,M,K){return M.namespaceURI===In?k==="svg":M.namespaceURI===jl?k==="svg"&&(K==="annotation-xml"||Nm[K]):!!WC[k]},CH=function(k,M,K){return M.namespaceURI===In?k==="math":M.namespaceURI===Ol?k==="math"&&Em[K]:!!JC[k]},RH=function(k,M,K){return M.namespaceURI===Ol&&!Em[K]||M.namespaceURI===jl&&!Nm[K]?!1:!JC[k]&&(yH[k]||!WC[k])},IH=function(k){let M=h(k);(!M||!M.tagName)&&(M={namespaceURI:ba,tagName:"template"});const K=fo(k.tagName),te=fo(M.tagName);return Pm[k.namespaceURI]?k.namespaceURI===Ol?SH(K,M,te):k.namespaceURI===jl?CH(K,M,te):k.namespaceURI===In?RH(K,M,te):!!(Xo==="application/xhtml+xml"&&Pm[k.namespaceURI]):!1},Tr=function(k){po(t.removed,{element:k});try{h(k).removeChild(k)}catch{if(m(k),!h(k))throw ti("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},YC=function(k,M,K){try{k.removeAttributeNode(M)}catch{try{k.removeAttribute(K)}catch{}}},Ml=function(k){Fl(k);const M=b(k);if(M){const te=[];ei(M,de=>{po(te,de)}),ei(te,de=>{try{m(de)}catch{}})}const K=w(k);if(K)for(let te=K.length-1;te>=0;--te){const de=K[te],be=de&&de.name;typeof be=="string"&&YC(k,de,be)}},bi=function(k,M,K){if(!K)try{K=M.getAttributeNode(k)}catch{K=null}po(t.removed,{attribute:K||null,from:M});try{K?M.removeAttributeNode(K):M.removeAttribute(k)}catch{try{M.removeAttribute(k)}catch{}}if(k==="is")if(lt||Rn)try{Tr(M)}catch{}else try{M.setAttribute(k,"")}catch{}},kH=function(k){const M=w(k);if(M)for(let K=M.length-1;K>=0;--K){const te=M[K],de=te&&te.name;typeof de!="string"||re[Ye(de)]||YC(k,te,de)}},Fl=function(k){const M=[k];for(;M.length>0;){const K=M.pop();T(K)===Ft.element&&kH(K);const te=b(K);if(te)for(let de=te.length-1;de>=0;--de)M.push(te[de])}},XC=function(k,M){return tt?k==="patchsrc"?!0:k==="for"&&M!=="label"&&M!=="output":!1},TH=function(k){if(!tt)return;const M=[k];for(;M.length>0;){const K=M.pop(),te=T(K);if(te===Ft.processingInstruction||te===Ft.comment&&vt(N_,K.data)){try{m(K)}catch{}continue}if(te===Ft.element){const be=K,De=Ye(A(K));try{be.hasAttribute&&be.hasAttribute("patchsrc")&&be.removeAttribute("patchsrc"),be.hasAttribute&&be.hasAttribute("for")&&XC("for",De)&&be.removeAttribute("for")}catch{}}const de=b(K);if(de)for(let be=de.length-1;be>=0;--be)M.push(de[be])}},QC=function(k){let M=null,K=null;if(yi)k="<remove></remove>"+k;else{const be=b_(k,/^[\r\n\t ]+/);K=be&&be[0]}Xo==="application/xhtml+xml"&&ba===In&&(k='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+k+"</body></html>");const te=L?q(k):k;if(ba===In)try{M=new d().parseFromString(te,Xo)}catch{}if(!M||!M.documentElement){M=O.createDocument(ba,"template",null);try{M.documentElement.innerHTML=Tm?F:te}catch{}}const de=M.body||M.documentElement;return k&&K&&de.insertBefore(n.createTextNode(K),de.childNodes[0]||null),ba===In?ee.call(M,Cn?"html":"body")[0]:Cn?M.documentElement:de},ZC=function(k){const M=I?I(k):k.ownerDocument;return H.call(M||k,k,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Bl=function(k){return k=mo(k,fe," "),k=mo(k,Ce," "),k=mo(k,Pe," "),k},xm=function(k){var M;k.normalize();const K=I?I(k):k.ownerDocument,te=H.call(K||k,k,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let de=te.nextNode();for(;de;)de.data=Bl(de.data),de=te.nextNode();const be=(M=k.querySelectorAll)===null||M===void 0?void 0:M.call(k,"template");be&&ei(be,De=>{wa(De.content)&&xm(De.content)})},ql=function(k){const M=R?R(k):null;return typeof M!="string"||Ye(M)!=="form"?!1:typeof k.nodeName!="string"||typeof k.textContent!="string"||typeof k.removeChild!="function"||k.attributes!==w(k)||typeof k.removeAttribute!="function"||typeof k.setAttribute!="function"||typeof k.namespaceURI!="string"||typeof k.insertBefore!="function"||typeof k.hasChildNodes!="function"||k.nodeType!==_(k)||k.childNodes!==b(k)},wa=function(k){if(!_||typeof k!="object"||k===null)return!1;try{return _(k)===Ft.documentFragment}catch{return!1}},Qo=function(k){if(!_||typeof k!="object"||k===null)return!1;try{return typeof _(k)=="number"}catch{return!1}};function kn(Y,k,M){Y.length!==0&&ei(Y,K=>{K.call(t,k,M,_a)})}const PH=function(k,M){return!!(tt&&k.hasChildNodes()&&!Qo(k.firstElementChild)&&vt(P_,k.textContent)&&vt(P_,k.innerHTML)||tt&&k.namespaceURI===In&&Xj[M]&&(Qo(k.firstElementChild)||typeof k.textContent=="string"&&vt(Qj[M],k.textContent))||k.nodeType===Ft.processingInstruction||tt&&k.nodeType===Ft.comment&&vt(N_,k.data))},Ul=function(k,M){if(k instanceof RegExp)return vt(k,M);if(k instanceof Function){for(var K=arguments.length,te=new Array(K>2?K-2:0),de=2;de<K;de++)te[de-2]=arguments[de];return!!k(M,...te)}return!1},NH=function(k,M,K){if(!ae[M]&&iR(M)&&Ul(we.tagNameCheck,M))return!1;if(Im&&!ya[M]){const te=h(k),de=b(k);if(de&&te){const be=de.length;for(let De=be-1;De>=0;--De){const Rt=k===K?f(de[De],!0):de[De];te.insertBefore(Rt,v(k))}}}return Tr(k),!0},eR=function(k,M,K,te){return k.length===0?M:M===K||M===te?Mt(M):M},tR=function(k,M){return k===M||h(k)!==null?!1:(km&&Fl(k),!0)},nR=function(k,M){if(kn(ie.beforeSanitizeElements,k,null),tR(k,M))return!0;if(ql(k))return Tr(k),!0;const K=Ye(A(k));if(le=eR(ie.uponSanitizeElement,le,Ee,gi),kn(ie.uponSanitizeElement,k,{tagName:K,allowedTags:le}),tR(k,M))return!0;if(PH(k,K))return Tr(k),!0;if(ae[K]||!(Je.tagCheck instanceof Function&&Je.tagCheck(K))&&!le[K]){const te=NH(k,K,M);return te===!1&&kn(ie.afterSanitizeElements,k,null),te}if(T(k)===Ft.element&&!IH(k)||(K==="noscript"||K==="noembed"||K==="noframes")&&vt(Jj,k.innerHTML))return Tr(k),!0;if(et&&k.nodeType===Ft.text){const te=Bl(k.textContent);k.textContent!==te&&(po(t.removed,{element:k.cloneNode()}),k.textContent=te)}return kn(ie.afterSanitizeElements,k,null),!1},rR=function(k,M,K){if(Fe[M]||XC(M,k)||OC&&(M==="id"||M==="name")&&(K in n||K in wH))return!1;const te=re[M]||Je.attributeCheck instanceof Function&&Je.attributeCheck(M,k);return Sn&&vt(Ne,M)||wn&&vt(ce,M)?!0:te?GC[M]||vt(ye,mo(K,J,""))||(M==="src"||M==="xlink:href"||M==="href")&&k!=="script"&&__(K,"data:")===0&&qC[k]||kr&&!vt(me,mo(K,J,""))?!0:!K:iR(k)&&Ul(we.tagNameCheck,k)&&Ul(we.attributeNameCheck,M,k)||M==="is"&&we.allowCustomizedBuiltInElements&&Ul(we.tagNameCheck,K)},EH=xe({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),iR=function(k){return!EH[fo(k)]&&vt(se,k)},AH=function(k,M,K,te){if(L&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!K)switch(u.getAttributeType(k,M)){case"TrustedHTML":return q(te);case"TrustedScriptURL":return $(te)}return te},xH=function(k,M,K,te){try{K?k.setAttributeNS(K,M,te):k.setAttribute(M,te),ql(k)?Tr(k):y_(t.removed)}catch{bi(M,k)}},aR=function(k){kn(ie.beforeSanitizeAttributes,k,null);const M=k.attributes;if(!M||ql(k))return;re=eR(ie.uponSanitizeAttribute,re,Q,vi);const K={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:re,forceKeepAttr:void 0};let te=M.length;const de=Ye(k.nodeName);for(;te--;){const be=M[te],De=be.name,Rt=be.namespaceURI,on=be.value,At=Ye(De),Lm=on;let It=De==="value"?Lm:Aj(Lm);if(K.attrName=At,K.attrValue=It,K.keepAttr=!0,K.forceKeepAttr=void 0,kn(ie.uponSanitizeAttribute,k,K),It=K.attrValue,MC&&(At==="id"||At==="name")&&__(It,FC)!==0&&(bi(De,k,be),It=FC+It),tt&&vt(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,It)){bi(De,k,be);continue}if(At==="attributename"&&b_(It,"href")){bi(De,k,be);continue}if(!K.forceKeepAttr){if(!K.keepAttr){bi(De,k,be);continue}if(!Re&&vt(Yj,It)){bi(De,k,be);continue}if(et&&(It=Bl(It)),!rR(de,At,It)){bi(De,k,be);continue}It=AH(de,At,Rt,It),It!==Lm&&xH(k,De,Rt,It)}}kn(ie.afterSanitizeAttributes,k,null)},Gl=function(k){let M=null;const K=ZC(k);for(kn(ie.beforeSanitizeShadowDOM,k,null);M=K.nextNode();)if(kn(ie.uponSanitizeShadowNode,M,null),nR(M,k),aR(M),wa(M.content)&&Gl(M.content),T(M)===Ft.element){const te=y(M);wa(te)&&(Dm(te),Gl(te))}kn(ie.afterSanitizeShadowDOM,k,null)},Dm=function(k){const M=[{node:k,shadow:null}];for(;M.length>0;){const K=M.pop();if(K.shadow){Gl(K.shadow);continue}const te=K.node,de=T(te)===Ft.element,be=b(te);if(be)for(let De=be.length-1;De>=0;--De)M.push({node:be[De],shadow:null});if(de){const De=R?R(te):null;if(typeof De=="string"&&Ye(De)==="template"){const Rt=te.content;wa(Rt)&&M.push({node:Rt,shadow:null})}}if(de){const De=y(te);wa(De)&&M.push({node:null,shadow:De},{node:De,shadow:null})}}};return t.sanitize=function(Y){let k=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},M=null,K=null,te=null,de=null;if(Tm=!Y,Tm&&(Y="<!-->"),typeof Y!="string"&&!Qo(Y)&&(Y=jj(Y),typeof Y!="string"))throw ti("dirty is not a string, aborting");if(!t.isSupported)return Y;Yo?(le=gi,re=vi):Am(k),(ie.uponSanitizeElement.length>0||ie.uponSanitizeAttribute.length>0)&&(le=Mt(le)),ie.uponSanitizeAttribute.length>0&&(re=Mt(re)),t.removed=[];const be=km&&typeof Y!="string"&&Qo(Y);if(be){TH(Y);const on=A(Y);if(typeof on=="string"){const At=Ye(on);if(!le[At]||ae[At])throw Ml(Y),ti("root node is forbidden and cannot be sanitized in-place")}if(ql(Y))throw Ml(Y),ti("root node is clobbered and cannot be sanitized in-place");try{Dm(Y)}catch(At){throw Ml(Y),At}}else if(Qo(Y))M=QC("<!---->"),K=M.ownerDocument.importNode(Y,!0),K.nodeType===Ft.element&&K.nodeName==="BODY"||K.nodeName==="HTML"?M=K:M.appendChild(K),Dm(K);else{if(!lt&&!et&&!Cn&&Y.indexOf("<")===-1)return L&&ga?q(Y):Y;if(M=QC(Y),!M)return lt?null:ga?F:""}M&&yi&&Tr(M.firstChild);const De=be?Y:M;try{const on=ZC(De);for(;te=on.nextNode();)nR(te,De),aR(te),wa(te.content)&&Gl(te.content)}catch(on){throw be&&(Ml(Y),ei(t.removed,At=>{At.element&&Fl(At.element)})),on}if(be)return ei(t.removed,on=>{on.element&&Fl(on.element)}),et&&xm(Y),Y;if(lt){if(et&&xm(M),Rn)for(de=G.call(M.ownerDocument);M.firstChild;)de.appendChild(M.firstChild);else de=M;return(re.shadowroot||re.shadowrootmode)&&(de=Z.call(r,de,!0)),de}let Rt=Cn?M.outerHTML:M.innerHTML;return Cn&&le["!doctype"]&&M.ownerDocument&&M.ownerDocument.doctype&&M.ownerDocument.doctype.name&&vt(zj,M.ownerDocument.doctype.name)&&(Rt="<!DOCTYPE "+M.ownerDocument.doctype.name+`>
44
+ `+Rt),et&&(Rt=Bl(Rt)),L&&ga?q(Rt):Rt},t.setConfig=function(){let Y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Am(Y),Yo=!0,gi=le,vi=re},t.clearConfig=function(){_a=null,Yo=!1,gi=null,vi=null,L=N,F=""},t.isValidAttribute=function(Y,k,M){_a||Am({});const K=Ye(Y),te=Ye(k);return rR(K,te,M)},t.addHook=function(Y,k){typeof k=="function"&&Et(ie,Y)&&po(ie[Y],k)},t.removeHook=function(Y,k){if(Et(ie,Y)){if(k!==void 0){const M=Nj(ie[Y],k);return M===-1?void 0:Ej(ie[Y],M,1)[0]}return y_(ie[Y])}},t.removeHooks=function(Y){Et(ie,Y)&&(ie[Y]=[])},t.removeAllHooks=function(){ie=A_()},t}var D_=x_();function Yp(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ni=Yp();function L_(e){ni=e}var ri={exec:()=>null};function na(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function Te(e,t=""){let n=typeof e=="string"?e:e.source,r={replace:(i,a)=>{let s=typeof a=="string"?a:a.source;return s=s.replace(yt.caret,"$1"),n=n.replace(i,s),r},getRegex:()=>new RegExp(n,t)};return r}var tO=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),yt={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:na(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:na(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:na(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:na(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:na(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:na(e=>new RegExp(`^ {0,${e}}>`))},nO=/^(?:[ \t]*(?:\n|$))+/,rO=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,iO=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,go=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,aO=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Xp=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,$_=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,j_=Te($_).replace(/bull/g,Xp).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),oO=Te($_).replace(/bull/g,Xp).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Qp=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,sO=/^[^\n]+/,Zp=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,cO=Te(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Zp).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),lO=Te(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Xp).getRegex(),Hc="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",ef=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,dO=Te("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",ef).replace("tag",Hc).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),O_=e=>Te(Qp).replace("hr",go).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Hc).getRegex(),uO=O_(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),pO=O_(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),tf={blockquote:Te(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",pO).getRegex(),code:rO,def:cO,fences:iO,heading:aO,hr:go,html:dO,lheading:j_,list:lO,newline:nO,paragraph:uO,table:ri,text:sO},M_=Te("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",go).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Hc).getRegex(),fO={...tf,lheading:oO,table:M_,paragraph:Te(Qp).replace("hr",go).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",M_).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Hc).getRegex()},mO={...tf,html:Te(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ef).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ri,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Te(Qp).replace("hr",go).replace("heading",` *#{1,6} *[^
45
+ ]`).replace("lheading",j_).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},hO=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,gO=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,F_=/^( {2,}|\\)\n(?!\s*$)/,vO=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,zn=/[\p{P}\p{S}]/u,ra=/[\s\p{P}\p{S}]/u,vo=/[^\s\p{P}\p{S}]/u,yO=Te(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,ra).getRegex(),bO=/[\p{Pi}\p{Ps}"']/u,B_=/(?!~)[\p{P}\p{S}]/u,_O=/(?!~)[\s\p{P}\p{S}]/u,wO=/(?:[^\s\p{P}\p{S}]|~)/u,SO=Te(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",tO?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),q_=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,CO=Te(q_,"u").replace(/punct/g,zn).getRegex(),RO=Te(q_,"u").replace(/punct/g,B_).getRegex(),IO=Te(/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,"u").replace(/openQuote/g,bO).replace(/punct/g,zn).getRegex(),U_="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",kO=Te(U_,"gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,ra).replace(/punct/g,zn).getRegex(),TO=Te(U_,"gu").replace(/notPunctSpace/g,wO).replace(/punctSpace/g,_O).replace(/punct/g,B_).getRegex(),PO=Te("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,ra).replace(/punct/g,zn).getRegex(),NO=Te("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,ra).replace(/punct/g,zn).getRegex(),EO=Te("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,ra).replace(/punct/g,zn).getRegex(),AO=Te(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,zn).getRegex(),xO=Te("^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,ra).replace(/punct/g,zn).getRegex(),DO=Te(/\\(punct)/,"gu").replace(/punct/g,zn).getRegex(),LO=Te(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),$O=Te(ef).replace("(?:-->|$)","-->").getRegex(),jO=Te("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",$O).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Vc=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,OO=Te(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Vc).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),G_=Te(/^!?\[(label)\]\[(ref)\]/).replace("label",Vc).replace("ref",Zp).getRegex(),H_=Te(/^!?\[(ref)\](?:\[\])?/).replace("ref",Zp).getRegex(),MO=Te("reflink|nolink(?!\\()","g").replace("reflink",G_).replace("nolink",H_).getRegex(),V_=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,nf={_backpedal:ri,anyPunctuation:DO,autolink:LO,blockSkip:SO,br:F_,code:gO,del:ri,delLDelim:ri,delRDelim:ri,emStrongLDelim:CO,emStrongRDelimAst:kO,emStrongRDelimUnd:NO,escape:hO,link:OO,nolink:H_,punctuation:yO,reflink:G_,reflinkSearch:MO,tag:jO,text:vO,url:ri},FO={...nf,emStrongLDelim:IO,emStrongRDelimAst:PO,emStrongRDelimUnd:EO,link:Te(/^!?\[(label)\]\((.*?)\)/).replace("label",Vc).getRegex(),reflink:Te(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Vc).getRegex()},rf={...nf,emStrongRDelimAst:TO,emStrongLDelim:RO,delLDelim:AO,delRDelim:xO,url:Te(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",V_).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Te(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",V_).getRegex()},BO={...rf,br:Te(F_).replace("{2,}","*").getRegex(),text:Te(rf.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Kc={normal:tf,gfm:fO,pedantic:mO},yo={normal:nf,gfm:rf,breaks:BO,pedantic:FO},qO={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},K_=e=>qO[e];function yn(e,t){if(t){if(yt.escapeTest.test(e))return e.replace(yt.escapeReplace,K_)}else if(yt.escapeTestNoEncode.test(e))return e.replace(yt.escapeReplaceNoEncode,K_);return e}function z_(e){try{e=encodeURI(e).replace(yt.percentDecode,"%")}catch{return null}return e}function W_(e,t){let n=e.replace(yt.findPipe,(i,a,s)=>{let c=!1,l=a;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}).split(yt.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;r<n.length;r++)n[r]=n[r].trim().replace(yt.slashPipe,"|");return n}function fr(e,t,n){let r=e.length;if(r===0)return"";let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function J_(e){let t=e.split(`
46
46
  `),n=t.length-1;for(;n>=0&&yt.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
47
- `)}function IO(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]==="\\")r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function kO(e,t=0){let n=t,r="";for(let i of e)if(i===" "){let o=4-n%4;r+=" ".repeat(o),n+=o}else r+=i,n++;return r}function v_(e,t,n,r,i){let o=t.href,s=t.title||null,c=e[1].replace(i.other.outputLinkReplace,"$1"),l=e[0].charAt(0)==="!";r.state.inLink=!0;let d=r.state.linkEmitted,u=r.state.inRawBlock;r.state.linkEmitted=!1;let p=r.inlineTokens(c),f=r.state.linkEmitted;if(r.state.linkEmitted=d,r.state.inLink=!1,!l){if(f){r.state.inRawBlock=u;return}r.state.linkEmitted=!0}return{type:l?"image":"link",raw:n,href:o,title:s,text:c,tokens:p}}function TO(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
48
- `).map(o=>{let s=o.match(n.other.beginningSpace);if(s===null)return o;let[c]=s;return c.length>=i.length?o.slice(i.length):o}).join(`
49
- `)}var xc=class{options;rules;lexer;constructor(e){this.options=e||Wr}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:g_(t[0]);return{type:"code",raw:n,codeBlockStyle:"indented",text:n.replace(this.rules.other.codeRemoveIndent,"")}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=TO(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=lr(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:lr(t[0],`
50
- `),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:lr(t[0],`
51
- `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=lr(t[0],`
47
+ `)}function UO(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]==="\\")r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function GO(e,t=0){let n=t,r="";for(let i of e)if(i===" "){let a=4-n%4;r+=" ".repeat(a),n+=a}else r+=i,n++;return r}function Y_(e,t,n,r,i){let a=t.href,s=t.title||null,c=e[1].replace(i.other.outputLinkReplace,"$1"),l=e[0].charAt(0)==="!";r.state.inLink=!0;let d=r.state.linkEmitted,u=r.state.inRawBlock;r.state.linkEmitted=!1;let p=r.inlineTokens(c),f=r.state.linkEmitted;if(r.state.linkEmitted=d,r.state.inLink=!1,!l){if(f){r.state.inRawBlock=u;return}r.state.linkEmitted=!0}return{type:l?"image":"link",raw:n,href:a,title:s,text:c,tokens:p}}function HO(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
48
+ `).map(a=>{let s=a.match(n.other.beginningSpace);if(s===null)return a;let[c]=s;return c.length>=i.length?a.slice(i.length):a}).join(`
49
+ `)}var zc=class{options;rules;lexer;constructor(e){this.options=e||ni}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:J_(t[0]);return{type:"code",raw:n,codeBlockStyle:"indented",text:n.replace(this.rules.other.codeRemoveIndent,"")}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=HO(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=fr(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:fr(t[0],`
50
+ `),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:fr(t[0],`
51
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=fr(t[0],`
52
52
  `).split(`
53
- `),r="",i="",o=[];for(;n.length>0;){let s=!1,c=[],l;for(l=0;l<n.length;l++)if(this.rules.other.blockquoteStart.test(n[l]))c.push(n[l]),s=!0;else if(!s)c.push(n[l]);else break;n=n.slice(l);let d=c.join(`
53
+ `),r="",i="",a=[];for(;n.length>0;){let s=!1,c=[],l;for(l=0;l<n.length;l++)if(this.rules.other.blockquoteStart.test(n[l]))c.push(n[l]),s=!0;else if(!s)c.push(n[l]);else break;n=n.slice(l);let d=c.join(`
54
54
  `),u=d.replace(this.rules.other.blockquoteSetextReplace,`
55
55
  $1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
56
56
  ${d}`:d,i=i?`${i}
57
- ${u}`:u;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,o,!0),this.lexer.state.top=p,n.length===0)break;let f=o.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let m=f,v=n.join(`
58
- `),g=m.raw+`
59
- `+v.replace(this.rules.other.blockquoteSetextReplace2,""),h=this.blockquote(g);o[o.length-1]=h,r=`${r}
57
+ ${u}`:u;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,a,!0),this.lexer.state.top=p,n.length===0)break;let f=a.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let m=f,v=n.join(`
58
+ `),b=m.raw+`
59
+ `+v.replace(this.rules.other.blockquoteSetextReplace2,""),h=this.blockquote(b);a[a.length-1]=h,r=`${r}
60
60
  ${v}`,i=i.substring(0,i.length-m.text.length)+h.text;break}else if(f?.type==="list"){let m=f,v=m.raw+`
61
61
  `+n.join(`
62
- `),g=this.list(v);o[o.length-1]=g,r=r.substring(0,r.length-f.raw.length)+g.raw,i=i.substring(0,i.length-m.raw.length)+g.raw,n=v.substring(o.at(-1).raw.length).split(`
63
- `);continue}}return{type:"blockquote",raw:r,tokens:o,text:i}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let o=this.rules.other.listItemRegex(n),s=!1;for(;e;){let l=!1,d="",u="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;d=t[0],e=e.substring(d.length);let p=kO(t[2].split(`
62
+ `),b=this.list(v);a[a.length-1]=b,r=r.substring(0,r.length-f.raw.length)+b.raw,i=i.substring(0,i.length-m.raw.length)+b.raw,n=v.substring(a.at(-1).raw.length).split(`
63
+ `);continue}}return{type:"blockquote",raw:r,tokens:a,text:i}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let a=this.rules.other.listItemRegex(n),s=!1;for(;e;){let l=!1,d="",u="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;d=t[0],e=e.substring(d.length);let p=GO(t[2].split(`
64
64
  `,1)[0],t[1].length),f=e.split(`
65
65
  `,1)[0],m=!p.trim(),v=0;if(this.options.pedantic?(v=2,u=p.trimStart()):m?v=t[1].length+1:(v=p.search(this.rules.other.nonSpaceChar),v=v>4?1:v,u=p.slice(v),v+=t[1].length),m&&this.rules.other.blankLine.test(f)&&(d+=f+`
66
- `,e=e.substring(f.length+1),l=!0),!l){let g=this.rules.other.nextBulletRegex(v),h=this.rules.other.hrRegex(v),b=this.rules.other.fencesBeginRegex(v),w=this.rules.other.headingBeginRegex(v),_=this.rules.other.htmlBeginRegex(v),R=this.rules.other.blockquoteBeginRegex(v);for(;e;){let I=e.split(`
67
- `,1)[0],T;if(f=I,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),T=f):T=f.replace(this.rules.other.tabCharGlobal," "),b.test(f)||w.test(f)||_.test(f)||R.test(f)||g.test(f)||h.test(f))break;if(T.search(this.rules.other.nonSpaceChar)>=v||!f.trim())u+=`
68
- `+T.slice(v);else{if(m||p.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||b.test(p)||w.test(p)||h.test(p))break;u+=`
66
+ `,e=e.substring(f.length+1),l=!0),!l){let b=this.rules.other.nextBulletRegex(v),h=this.rules.other.hrRegex(v),y=this.rules.other.fencesBeginRegex(v),w=this.rules.other.headingBeginRegex(v),_=this.rules.other.htmlBeginRegex(v),R=this.rules.other.blockquoteBeginRegex(v);for(;e;){let I=e.split(`
67
+ `,1)[0],T;if(f=I,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),T=f):T=f.replace(this.rules.other.tabCharGlobal," "),y.test(f)||w.test(f)||_.test(f)||R.test(f)||b.test(f)||h.test(f))break;if(T.search(this.rules.other.nonSpaceChar)>=v||!f.trim())u+=`
68
+ `+T.slice(v);else{if(m||p.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||y.test(p)||w.test(p)||h.test(p))break;u+=`
69
69
  `+f}m=!f.trim(),d+=I+`
70
- `,e=e.substring(I.length+1),p=T.slice(v)}}i.loose||(s?i.loose=!0:this.rules.other.doubleBlankLine.test(d)&&(s=!0)),i.items.push({type:"list_item",raw:d,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),i.raw+=d}let c=i.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let l of i.items)if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),!i.loose){let d=l.tokens.filter(u=>u.type==="space");i.loose=d.length>0&&d.some(u=>this.rules.other.anyLine.test(u.raw))}for(let l of i.items){let d=l.tokens[0];if(l.task&&(d?.type==="text"||d?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),d.raw=d.raw.replace(this.rules.other.listReplaceTask,""),d.text=d.text.replace(this.rules.other.listReplaceTask,"");for(let p=this.lexer.inlineQueue.length-1;p>=0;p--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[p].src)){this.lexer.inlineQueue[p].src=this.lexer.inlineQueue[p].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(l.raw);if(u){let p={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};l.checked=p.checked,i.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=p.raw+l.tokens[0].raw,l.tokens[0].text=p.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(p)):l.tokens.unshift({type:"paragraph",raw:p.raw,text:p.raw,tokens:[p]}):l.tokens.unshift(p)}}else l.task&&(l.task=!1)}if(i.loose)for(let l of i.items){l.loose=!0;for(let d of l.tokens)d.type==="text"&&(d.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=g_(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:lr(t[0],`
71
- `),href:r,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=h_(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
72
- `):[],o={type:"table",raw:lr(t[0],`
73
- `),header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?o.align.push("right"):this.rules.other.tableAlignCenter.test(s)?o.align.push("center"):this.rules.other.tableAlignLeft.test(s)?o.align.push("left"):o.align.push(null);for(let s=0;s<n.length;s++)o.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:o.align[s]});for(let s of i)o.rows.push(h_(s,o.header.length).map((c,l)=>({text:c,tokens:this.lexer.inline(c),header:!1,align:o.align[l]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:lr(t[0],`
70
+ `,e=e.substring(I.length+1),p=T.slice(v)}}i.loose||(s?i.loose=!0:this.rules.other.doubleBlankLine.test(d)&&(s=!0)),i.items.push({type:"list_item",raw:d,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),i.raw+=d}let c=i.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let l of i.items)if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),!i.loose){let d=l.tokens.filter(u=>u.type==="space");i.loose=d.length>0&&d.some(u=>this.rules.other.anyLine.test(u.raw))}for(let l of i.items){let d=l.tokens[0];if(l.task&&(d?.type==="text"||d?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),d.raw=d.raw.replace(this.rules.other.listReplaceTask,""),d.text=d.text.replace(this.rules.other.listReplaceTask,"");for(let p=this.lexer.inlineQueue.length-1;p>=0;p--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[p].src)){this.lexer.inlineQueue[p].src=this.lexer.inlineQueue[p].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(l.raw);if(u){let p={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};l.checked=p.checked,i.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=p.raw+l.tokens[0].raw,l.tokens[0].text=p.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(p)):l.tokens.unshift({type:"paragraph",raw:p.raw,text:p.raw,tokens:[p]}):l.tokens.unshift(p)}}else l.task&&(l.task=!1)}if(i.loose)for(let l of i.items){l.loose=!0;for(let d of l.tokens)d.type==="text"&&(d.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=J_(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:fr(t[0],`
71
+ `),href:r,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=W_(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
72
+ `):[],a={type:"table",raw:fr(t[0],`
73
+ `),header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?a.align.push("right"):this.rules.other.tableAlignCenter.test(s)?a.align.push("center"):this.rules.other.tableAlignLeft.test(s)?a.align.push("left"):a.align.push(null);for(let s=0;s<n.length;s++)a.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:a.align[s]});for(let s of i)a.rows.push(W_(s,a.header.length).map((c,l)=>({text:c,tokens:this.lexer.inline(c),header:!1,align:a.align[l]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:fr(t[0],`
74
74
  `),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
75
- `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let o=lr(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=IO(t[2],"()");if(o===-2)return;if(o>-1){let s=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,s).trim(),t[3]=""}}let r=t[2],i="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(r);o&&(r=o[1],i=o[3])}else i=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),v_(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let r=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," ").toLowerCase()];if(!r){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return v_(n,r,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,o,s,c=i,l=0,d=r[0][0],u=n===d,p=d==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+i);(r=p.exec(t))!==null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o)continue;if(s=[...o].length,r[3]||r[4]){c+=s;continue}else if(r[5]||r[6]){if(i%3&&!((i+s)%3)){l+=s;continue}if(u)break}if(c-=s,c>0)continue;s=Math.min(s,s+c+l);let f=[...r[0]][0].length,m=e.slice(0,i+r.index+f+s);if(Math.min(i,s)%2){let g=m.slice(1,-1);return{type:"em",raw:m,text:g,tokens:this.lexer.inlineTokens(g)}}let v=m.slice(2,-2);return{type:"strong",raw:m,text:v,tokens:this.lexer.inlineTokens(v)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,o,s,c=i,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+i);(r=l.exec(t))!==null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o||(s=[...o].length,s!==i))continue;if(r[3]||r[4]){c+=s;continue}if(c-=s,c>0)continue;s=Math.min(s,s+c);let d=[...r[0]][0].length,u=e.slice(0,i+r.index+d+s),p=u.slice(i,-i);return{type:"del",raw:u,text:p,tokens:this.lexer.inlineTokens(p)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,r;return t[2]==="@"?(n=t[1],r="mailto:"+n):(n=t[1],r=n),{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,r;if(t[2]==="@")n=t[0],r="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);n=t[0],t[1]==="www."?r="http://"+t[0]:r=t[0]}return{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},en=class cm{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Wr,this.options.tokenizer=this.options.tokenizer||new xc,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let n={other:yt,block:Ac.normal,inline:pa.normal};this.options.pedantic?(n.block=Ac.pedantic,n.inline=pa.pedantic):this.options.gfm&&(n.block=Ac.gfm,this.options.breaks?n.inline=pa.breaks:n.inline=pa.gfm),this.tokenizer.rules=n}static get rules(){return{block:Ac,inline:pa}}static lex(t,n){return new cm(n).lex(t)}static lexInline(t,n){return new cm(n).inlineTokens(t)}lex(t){t=t.replace(yt.carriageReturn,`
76
- `),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],r=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(yt.tabCharGlobal," ").replace(yt.spaceLine,""));let i=1/0;for(;t;){if(t.length<i)i=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(c=>(o=c.call({lexer:this},t,n))?(t=t.substring(o.raw.length),n.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let c=n.at(-1);o.raw.length===1&&c!==void 0?c.raw+=`
77
- `:n.push(o);continue}if(o=this.tokenizer.code(t)){t=t.substring(o.raw.length);let c=n.at(-1);c?.type==="paragraph"||c?.type==="text"?(c.raw+=(c.raw.endsWith(`
75
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let a=fr(n.slice(0,-1),"\\");if((n.length-a.length)%2===0)return}else{let a=UO(t[2],"()");if(a===-2)return;if(a>-1){let s=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,s).trim(),t[3]=""}}let r=t[2],i="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(r);a&&(r=a[1],i=a[3])}else i=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),Y_(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let r=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," ").toLowerCase()];if(!r){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return Y_(n,r,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,a,s,c=i,l=0,d=r[0][0],u=n===d,p=d==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+i);(r=p.exec(t))!==null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a)continue;if(s=[...a].length,r[3]||r[4]){c+=s;continue}else if(r[5]||r[6]){if(i%3&&!((i+s)%3)){l+=s;continue}if(u)break}if(c-=s,c>0)continue;s=Math.min(s,s+c+l);let f=[...r[0]][0].length,m=e.slice(0,i+r.index+f+s);if(Math.min(i,s)%2){let b=m.slice(1,-1);return{type:"em",raw:m,text:b,tokens:this.lexer.inlineTokens(b)}}let v=m.slice(2,-2);return{type:"strong",raw:m,text:v,tokens:this.lexer.inlineTokens(v)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,a,s,c=i,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+i);(r=l.exec(t))!==null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a||(s=[...a].length,s!==i))continue;if(r[3]||r[4]){c+=s;continue}if(c-=s,c>0)continue;s=Math.min(s,s+c);let d=[...r[0]][0].length,u=e.slice(0,i+r.index+d+s),p=u.slice(i,-i);return{type:"del",raw:u,text:p,tokens:this.lexer.inlineTokens(p)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,r;return t[2]==="@"?(n=t[1],r="mailto:"+n):(n=t[1],r=n),{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,r;if(t[2]==="@")n=t[0],r="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);n=t[0],t[1]==="www."?r="http://"+t[0]:r=t[0]}return{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},tn=class $m{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||ni,this.options.tokenizer=this.options.tokenizer||new zc,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let n={other:yt,block:Kc.normal,inline:yo.normal};this.options.pedantic?(n.block=Kc.pedantic,n.inline=yo.pedantic):this.options.gfm&&(n.block=Kc.gfm,this.options.breaks?n.inline=yo.breaks:n.inline=yo.gfm),this.tokenizer.rules=n}static get rules(){return{block:Kc,inline:yo}}static lex(t,n){return new $m(n).lex(t)}static lexInline(t,n){return new $m(n).inlineTokens(t)}lex(t){t=t.replace(yt.carriageReturn,`
76
+ `),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],r=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(yt.tabCharGlobal," ").replace(yt.spaceLine,""));let i=1/0;for(;t;){if(t.length<i)i=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let a;if(this.options.extensions?.block?.some(c=>(a=c.call({lexer:this},t,n))?(t=t.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.space(t)){t=t.substring(a.raw.length);let c=n.at(-1);a.raw.length===1&&c!==void 0?c.raw+=`
77
+ `:n.push(a);continue}if(a=this.tokenizer.code(t)){t=t.substring(a.raw.length);let c=n.at(-1);c?.type==="paragraph"||c?.type==="text"?(c.raw+=(c.raw.endsWith(`
78
78
  `)?"":`
79
- `)+o.raw,c.text+=`
80
- `+o.text,this.inlineQueue.at(-1).src=c.text):n.push(o);continue}if(o=this.tokenizer.fences(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.heading(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.hr(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.blockquote(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.list(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.html(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.def(t)){t=t.substring(o.raw.length);let c=n.at(-1);c?.type==="paragraph"||c?.type==="text"?(c.raw+=(c.raw.endsWith(`
79
+ `)+a.raw,c.text+=`
80
+ `+a.text,this.inlineQueue.at(-1).src=c.text):n.push(a);continue}if(a=this.tokenizer.fences(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.heading(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.hr(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.blockquote(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.list(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.html(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.def(t)){t=t.substring(a.raw.length);let c=n.at(-1);c?.type==="paragraph"||c?.type==="text"?(c.raw+=(c.raw.endsWith(`
81
81
  `)?"":`
82
- `)+o.raw,c.text+=`
83
- `+o.raw,this.inlineQueue.at(-1).src=c.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},n.push(o));continue}if(o=this.tokenizer.table(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.lheading(t)){t=t.substring(o.raw.length),n.push(o);continue}let s=t;if(this.options.extensions?.startBlock){let c=1/0,l=t.slice(1),d;this.options.extensions.startBlock.forEach(u=>{d=u.call({lexer:this},l),typeof d=="number"&&d>=0&&(c=Math.min(c,d))}),c<1/0&&c>=0&&(s=t.substring(0,c+1))}if(this.state.top&&(o=this.tokenizer.paragraph(s))){let c=n.at(-1);r&&c?.type==="paragraph"?(c.raw+=(c.raw.endsWith(`
82
+ `)+a.raw,c.text+=`
83
+ `+a.raw,this.inlineQueue.at(-1).src=c.text):this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title},n.push(a));continue}if(a=this.tokenizer.table(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.lheading(t)){t=t.substring(a.raw.length),n.push(a);continue}let s=t;if(this.options.extensions?.startBlock){let c=1/0,l=t.slice(1),d;this.options.extensions.startBlock.forEach(u=>{d=u.call({lexer:this},l),typeof d=="number"&&d>=0&&(c=Math.min(c,d))}),c<1/0&&c>=0&&(s=t.substring(0,c+1))}if(this.state.top&&(a=this.tokenizer.paragraph(s))){let c=n.at(-1);r&&c?.type==="paragraph"?(c.raw+=(c.raw.endsWith(`
84
84
  `)?"":`
85
- `)+o.raw,c.text+=`
86
- `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(o),r=s.length!==t.length,t=t.substring(o.raw.length);continue}if(o=this.tokenizer.text(t)){t=t.substring(o.raw.length);let c=n.at(-1);c?.type==="text"?(c.raw+=(c.raw.endsWith(`
85
+ `)+a.raw,c.text+=`
86
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(a),r=s.length!==t.length,t=t.substring(a.raw.length);continue}if(a=this.tokenizer.text(t)){t=t.substring(a.raw.length);let c=n.at(-1);c?.type==="text"?(c.raw+=(c.raw.endsWith(`
87
87
  `)?"":`
88
- `)+o.raw,c.text+=`
89
- `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(o);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}linkInText(t){if(!t.includes("["))return!1;let n=this.tokenizer.rules.inline.link;for(let r of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(n.test(r[0])&&t.charAt(r.index-1)!=="!")return!0;for(let r of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let i=r[0],o=i.lastIndexOf("[");if(!(i.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,i.slice(o+1,-1)))&&!(o>1&&this.linkInText(i.slice(1,o-1))))return!0}return!1}inlineTokens(t,n=[]){this.tokenizer.lexer=this;let r=t;if(this.tokens.links&&t.includes("[")){let c=this.tokenizer.rules.inline.reflinkSearch,l=d=>{let u=d.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,d.slice(u+1,-1)))return d;if(u>1&&d.charAt(0)!=="!"){let p=d.slice(1,u-1);if(this.linkInText(p))return"["+p.replace(c,l)+"]["+"a".repeat(d.length-u-2)+"]"}return"["+"a".repeat(d.length-2)+"]"};r=r.replace(c,l)}r=r.replace(this.tokenizer.rules.inline.anyPunctuation,c=>"+".repeat(c.length)),r=r.replace(this.tokenizer.rules.inline.blockSkip,(c,l,d)=>{let u=d?d.length:0;return c.slice(0,u)+"["+"a".repeat(c.length-u-2)+"]"}),r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let i=!1,o="",s=1/0;for(;t;){if(t.length<s)s=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}i||(o=""),i=!1;let c;if(this.options.extensions?.inline?.some(d=>(c=d.call({lexer:this},t,n))?(t=t.substring(c.raw.length),n.push(c),!0):!1))continue;if(c=this.tokenizer.escape(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.tag(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.link(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(c.raw.length);let d=n.at(-1);c.type==="text"&&d?.type==="text"?(d.raw+=c.raw,d.text+=c.text):n.push(c);continue}if(c=this.tokenizer.emStrong(t,r,o)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.codespan(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.br(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.del(t,r,o)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.autolink(t)){t=t.substring(c.raw.length),n.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(t))){t=t.substring(c.raw.length),n.push(c);continue}let l=t;if(this.options.extensions?.startInline){let d=1/0,u=t.slice(1),p;this.options.extensions.startInline.forEach(f=>{p=f.call({lexer:this},u),typeof p=="number"&&p>=0&&(d=Math.min(d,p))}),d<1/0&&d>=0&&(l=t.substring(0,d+1))}if(c=this.tokenizer.inlineText(l)){t=t.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(o=c.raw.slice(-1)),i=!0;let d=n.at(-1);d?.type==="text"?(d.raw+=c.raw,d.text+=c.text):n.push(c);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return n}infiniteLoopError(t){let n="Infinite loop on byte: "+t;if(this.options.silent)console.error(n);else throw new Error(n)}},Dc=class{options;parser;constructor(e){this.options=e||Wr}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(yt.notSpaceStart)?.[0],i=e.replace(yt.endingNewline,"")+`
90
- `;return r?'<pre><code class="language-'+gn(r)+'">'+(n?i:gn(i,!0))+`</code></pre>
91
- `:"<pre><code>"+(n?i:gn(i,!0))+`</code></pre>
88
+ `)+a.raw,c.text+=`
89
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(a);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}linkInText(t){if(!t.includes("["))return!1;let n=this.tokenizer.rules.inline.link;for(let r of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(n.test(r[0])&&t.charAt(r.index-1)!=="!")return!0;for(let r of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let i=r[0],a=i.lastIndexOf("[");if(!(i.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,i.slice(a+1,-1)))&&!(a>1&&this.linkInText(i.slice(1,a-1))))return!0}return!1}inlineTokens(t,n=[]){this.tokenizer.lexer=this;let r=t;if(this.tokens.links&&t.includes("[")){let c=this.tokenizer.rules.inline.reflinkSearch,l=d=>{let u=d.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,d.slice(u+1,-1)))return d;if(u>1&&d.charAt(0)!=="!"){let p=d.slice(1,u-1);if(this.linkInText(p))return"["+p.replace(c,l)+"]["+"a".repeat(d.length-u-2)+"]"}return"["+"a".repeat(d.length-2)+"]"};r=r.replace(c,l)}r=r.replace(this.tokenizer.rules.inline.anyPunctuation,c=>"+".repeat(c.length)),r=r.replace(this.tokenizer.rules.inline.blockSkip,(c,l,d)=>{let u=d?d.length:0;return c.slice(0,u)+"["+"a".repeat(c.length-u-2)+"]"}),r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let i=!1,a="",s=1/0;for(;t;){if(t.length<s)s=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}i||(a=""),i=!1;let c;if(this.options.extensions?.inline?.some(d=>(c=d.call({lexer:this},t,n))?(t=t.substring(c.raw.length),n.push(c),!0):!1))continue;if(c=this.tokenizer.escape(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.tag(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.link(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(c.raw.length);let d=n.at(-1);c.type==="text"&&d?.type==="text"?(d.raw+=c.raw,d.text+=c.text):n.push(c);continue}if(c=this.tokenizer.emStrong(t,r,a)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.codespan(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.br(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.del(t,r,a)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.autolink(t)){t=t.substring(c.raw.length),n.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(t))){t=t.substring(c.raw.length),n.push(c);continue}let l=t;if(this.options.extensions?.startInline){let d=1/0,u=t.slice(1),p;this.options.extensions.startInline.forEach(f=>{p=f.call({lexer:this},u),typeof p=="number"&&p>=0&&(d=Math.min(d,p))}),d<1/0&&d>=0&&(l=t.substring(0,d+1))}if(c=this.tokenizer.inlineText(l)){t=t.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(a=c.raw.slice(-1)),i=!0;let d=n.at(-1);d?.type==="text"?(d.raw+=c.raw,d.text+=c.text):n.push(c);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return n}infiniteLoopError(t){let n="Infinite loop on byte: "+t;if(this.options.silent)console.error(n);else throw new Error(n)}},Wc=class{options;parser;constructor(e){this.options=e||ni}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(yt.notSpaceStart)?.[0],i=e.replace(yt.endingNewline,"")+`
90
+ `;return r?'<pre><code class="language-'+yn(r)+'">'+(n?i:yn(i,!0))+`</code></pre>
91
+ `:"<pre><code>"+(n?i:yn(i,!0))+`</code></pre>
92
92
  `}blockquote({tokens:e}){return`<blockquote>
93
93
  ${this.parser.parse(e)}</blockquote>
94
94
  `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
95
95
  `}hr(e){return`<hr>
96
- `}list(e){let t=e.ordered,n=e.start,r="";for(let s=0;s<e.items.length;s++){let c=e.items[s];r+=this.listitem(c)}let i=t?"ol":"ul",o=t&&n!==1?' start="'+n+'"':"";return"<"+i+o+`>
96
+ `}list(e){let t=e.ordered,n=e.start,r="";for(let s=0;s<e.items.length;s++){let c=e.items[s];r+=this.listitem(c)}let i=t?"ol":"ul",a=t&&n!==1?' start="'+n+'"':"";return"<"+i+a+`>
97
97
  `+r+"</"+i+`>
98
98
  `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
99
99
  `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
100
- `}table(e){let t="",n="";for(let i=0;i<e.header.length;i++)n+=this.tablecell(e.header[i]);t+=this.tablerow({text:n});let r="";for(let i=0;i<e.rows.length;i++){let o=e.rows[i];n="";for(let s=0;s<o.length;s++)n+=this.tablecell(o[s]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
100
+ `}table(e){let t="",n="";for(let i=0;i<e.header.length;i++)n+=this.tablecell(e.header[i]);t+=this.tablerow({text:n});let r="";for(let i=0;i<e.rows.length;i++){let a=e.rows[i];n="";for(let s=0;s<a.length;s++)n+=this.tablecell(a[s]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
101
101
  <thead>
102
102
  `+t+`</thead>
103
103
  `+r+`</table>
104
104
  `}tablerow({text:e}){return`<tr>
105
105
  ${e}</tr>
106
106
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
107
- `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${gn(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=m_(e);if(i===null)return r;e=i;let o='<a href="'+e+'"';return t&&(o+=' title="'+gn(t)+'"'),o+=">"+r+"</a>",o}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=m_(e);if(i===null)return gn(n);e=i;let o=`<img src="${e}" alt="${gn(n)}"`;return t&&(o+=` title="${gn(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:gn(e.text)}},Lp=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},tn=class lm{options;renderer;textRenderer;constructor(t){this.options=t||Wr,this.options.renderer=this.options.renderer||new Dc,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Lp}static parse(t,n){return new lm(n).parse(t)}static parseInline(t,n){return new lm(n).parseInline(t)}parse(t){this.renderer.parser=this;let n="";for(let r=0;r<t.length;r++){let i=t[r];if(this.options.extensions?.renderers?.[i.type]){let s=i,c=this.options.extensions.renderers[s.type].call({parser:this},s);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(s.type)){n+=c||"";continue}}let o=i;switch(o.type){case"space":n+=this.renderer.space(o);break;case"hr":n+=this.renderer.hr(o);break;case"heading":n+=this.renderer.heading(o);break;case"code":n+=this.renderer.code(o);break;case"table":n+=this.renderer.table(o);break;case"blockquote":n+=this.renderer.blockquote(o);break;case"list":n+=this.renderer.list(o);break;case"checkbox":n+=this.renderer.checkbox(o);break;case"html":n+=this.renderer.html(o);break;case"def":n+=this.renderer.def(o);break;case"paragraph":n+=this.renderer.paragraph(o);break;case"text":n+=this.renderer.text(o);break;default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}parseInline(t,n=this.renderer){this.renderer.parser=this;let r="";for(let i=0;i<t.length;i++){let o=t[i];if(this.options.extensions?.renderers?.[o.type]){let c=this.options.extensions.renderers[o.type].call({parser:this},o);if(c!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(o.type)){r+=c||"";continue}}let s=o;switch(s.type){case"escape":r+=n.text(s);break;case"html":r+=n.html(s);break;case"link":r+=n.link(s);break;case"image":r+=n.image(s);break;case"checkbox":r+=n.checkbox(s);break;case"strong":r+=n.strong(s);break;case"em":r+=n.em(s);break;case"codespan":r+=n.codespan(s);break;case"br":r+=n.br(s);break;case"del":r+=n.del(s);break;case"text":r+=n.text(s);break;default:{let c='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return r}},fa=class{options;block;constructor(e){this.options=e||Wr}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?en.lex:en.lexInline}provideParser(e=this.block){return e?tn.parse:tn.parseInline}},PO=class{defaults=kp();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=tn;Renderer=Dc;TextRenderer=Lp;Lexer=en;Tokenizer=xc;Hooks=fa;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case"table":{let i=r;for(let o of i.header)n=n.concat(this.walkTokens(o.tokens,t));for(let o of i.rows)for(let s of o)n=n.concat(this.walkTokens(s.tokens,t));break}case"list":{let i=r;n=n.concat(this.walkTokens(i.items,t));break}default:{let i=r;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(o=>{let s=i[o].flat(1/0);n=n.concat(this.walkTokens(s,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let o=t.renderers[i.name];o?t.renderers[i.name]=function(...s){let c=i.renderer.apply(this,s);return c===!1&&(c=o.apply(this,s)),c}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[i.level];o?o.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),r.extensions=t),n.renderer){let i=this.defaults.renderer||new Dc(this.defaults);for(let o in n.renderer){if(!(o in i))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let s=o,c=n.renderer[s],l=i[s];i[s]=(...d)=>{let u=c.apply(i,d);return u===!1&&(u=l.apply(i,d)),u||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new xc(this.defaults);for(let o in n.tokenizer){if(!(o in i))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let s=o,c=n.tokenizer[s],l=i[s];i[s]=(...d)=>{let u=c.apply(i,d);return u===!1&&(u=l.apply(i,d)),u}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new fa;for(let o in n.hooks){if(!(o in i))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let s=o,c=n.hooks[s],l=i[s];fa.passThroughHooks.has(o)?i[s]=d=>{if(this.defaults.async&&fa.passThroughHooksRespectAsync.has(o))return(async()=>{let p=await c.call(i,d);return l.call(i,p)})();let u=c.call(i,d);return l.call(i,u)}:i[s]=(...d)=>{if(this.defaults.async)return(async()=>{let p=await c.apply(i,d);return p===!1&&(p=await l.apply(i,d)),p})();let u=c.apply(i,d);return u===!1&&(u=l.apply(i,d)),u}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,o=n.walkTokens;r.walkTokens=function(s){let c=[];return c.push(o.call(this,s)),i&&(c=c.concat(i.call(this,s))),c}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return en.lex(e,t??this.defaults)}parser(e,t){return tn.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let s=i.hooks?await i.hooks.preprocess(t):t,c=await(i.hooks?await i.hooks.provideLexer(e):e?en.lex:en.lexInline)(s,i),l=i.hooks?await i.hooks.processAllTokens(c):c;i.walkTokens&&await Promise.all(this.walkTokens(l,i.walkTokens));let d=await(i.hooks?await i.hooks.provideParser(e):e?tn.parse:tn.parseInline)(l,i);return i.hooks?await i.hooks.postprocess(d):d})().catch(o);try{i.hooks&&(t=i.hooks.preprocess(t));let s=(i.hooks?i.hooks.provideLexer(e):e?en.lex:en.lexInline)(t,i);i.hooks&&(s=i.hooks.processAllTokens(s)),i.walkTokens&&this.walkTokens(s,i.walkTokens);let c=(i.hooks?i.hooks.provideParser(e):e?tn.parse:tn.parseInline)(s,i);return i.hooks&&(c=i.hooks.postprocess(c)),c}catch(s){return o(s)}}}onError(e,t){return n=>{if(n.message+=`
108
- Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error occurred:</p><pre>"+gn(n.message+"",!0)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},Yr=new PO;function Fe(e,t){return Yr.parse(e,t)}Fe.options=Fe.setOptions=function(e){return Yr.setOptions(e),Fe.defaults=Yr.defaults,t_(Fe.defaults),Fe},Fe.getDefaults=kp,Fe.defaults=Wr;function NO(...e){return Yr.use(...e),Fe.defaults=Yr.defaults,t_(Fe.defaults),Fe}Fe.use=NO,Fe.walkTokens=function(e,t){return Yr.walkTokens(e,t)},Fe.parseInline=Yr.parseInline,Fe.Parser=tn,Fe.parser=tn.parse,Fe.Renderer=Dc,Fe.TextRenderer=Lp,Fe.Lexer=en,Fe.lexer=en.lex,Fe.Tokenizer=xc,Fe.Hooks=fa,Fe.parse=Fe;var eG=Fe.options,tG=Fe.setOptions,nG=Fe.walkTokens,rG=Fe.parseInline,iG=tn.parse,oG=en.lex,EO={ALLOWED_TAGS:["p","br","strong","em","code","pre","ul","ol","li","blockquote","a","h1","h2","h3","h4","h5","h6","hr"],ALLOWED_ATTR:["href","title"],ALLOW_DATA_ATTR:!1};function AO(e){const t=String(e||"").trim();if(!t)return!1;if(t.startsWith("#")||t.startsWith("/"))return!0;const n=t.toLowerCase();return n.startsWith("http://")||n.startsWith("https://")||n.startsWith("mailto:")}e_.addHook("afterSanitizeAttributes",e=>{e.tagName==="A"&&(AO(e.getAttribute("href")||"")?(e.setAttribute("rel","noopener noreferrer"),e.setAttribute("target","_blank")):e.removeAttribute("href"))});function $p(e){const t=Fe.parse(String(e||""),{async:!1});return e_.sanitize(t,EO)}function xO(e){const t=["request","outcome","plan","completed","learned","investigated","next","next_steps","notes"],n=Object.keys(e);return t.filter(r=>n.includes(r)).map(r=>{const i=String(e[r]||"").trim();return i?y("div",{className:"summary-section",key:r},y("div",{className:"summary-section-label"},lL(r)),y("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:$p(i)}})):null}).filter(Boolean)}function DO(e){const t=e.map(n=>String(n||"").trim()).filter(Boolean);if(!t.length)return null;if(t.every(n=>/.+?:\s+.+/.test(n))){const n=t.map((r,i)=>{const o=r.indexOf(":"),s=r.slice(0,o).trim(),c=r.slice(o+1).trim();return!s||!c?null:y("div",{className:"summary-section",key:`${s}-${i}`},y("div",{className:"summary-section-label"},s),y("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:$p(c)}}))}).filter(Boolean);if(n.length)return y("div",{className:"feed-body facts"},n)}return y("div",{className:"feed-body"},y("ul",null,t.map((n,r)=>y("li",{key:`${n}-${r}`},n))))}function y_(e,t="feed-body"){const n=String(e||"").trim();return n?y("div",{className:t,dangerouslySetInnerHTML:{__html:$p(n)}}):null}function LO(e){const t=["request","outcome","plan","completed","learned","investigated","next","next_steps","notes"],n=s=>{if(!s||typeof s!="object"||Array.isArray(s))return!1;const c=s;return t.some(l=>{const d=c[l];return typeof d=="string"&&d.trim().length>0})},r=e?.summary;if(r&&typeof r=="object"&&!Array.isArray(r)){const s=r.summary;if(n(r))return r;if(n(s))return s}const i=e?.metadata_json;if(n(i))return i;if(i&&n(i.summary))return i.summary;const o=String(e?.body_text||"").trim();if(o.includes("## ")){const s={request:"request",completed:"completed",learned:"learned",investigated:"investigated","next steps":"next_steps",notes:"notes"},c={},l=/(?:^|\n)##\s+([^\n]+)\n([\s\S]*?)(?=\n##\s+|$)/g;for(let d=l.exec(o);d;d=l.exec(o)){const u=s[String(d[1]||"").trim().toLowerCase()],p=String(d[2]||"").trim();u&&p&&(c[u]=p)}if(n(c))return c}return null}function Lc(e,t){return String(e?.kind||"").toLowerCase()==="session_summary"||t?.is_summary===!0?!0:String(t?.source||"").trim().toLowerCase()==="observer_summary"}function $O(e,t){const n=String(e?.kind||"").trim().toLowerCase();return Lc(e,t)?"session_summary":n||"change"}var OO=Object.defineProperty,He=(e,t)=>OO(e,"name",{value:t,configurable:!0}),Op=["Enter"," "],jO=["ArrowDown","PageUp","Home"],b_=["ArrowUp","PageDown","End"],MO=[...jO,...b_],aG={ltr:[...Op,"ArrowRight"],rtl:[...Op,"ArrowLeft"]},$c="Menu",[jp,FO,BO]=Fo($c),[Xr,__]=dt($c,[BO,tr,Oi]),Mp=tr(),w_=Oi(),[qO,ma]=Xr($c),[UO,Fp]=Xr($c),GO=He(e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:o,modal:s=!0}=e,c=Mp(t),[l,d]=x(null),u=B(!1),p=ht(o),f=$i(i);return V(()=>{const m=He(()=>{u.current=!0,document.addEventListener("pointerdown",v,{capture:!0,once:!0}),document.addEventListener("pointermove",v,{capture:!0,once:!0})},"handleKeyDown"),v=He(()=>u.current=!1,"handlePointer");return document.addEventListener("keydown",m,{capture:!0}),()=>{document.removeEventListener("keydown",m,{capture:!0}),document.removeEventListener("pointerdown",v,{capture:!0}),document.removeEventListener("pointermove",v,{capture:!0})}},[]),V(()=>{if(!n)return;const m=He(()=>p(!1),"handleBlur");return window.addEventListener("blur",m),()=>window.removeEventListener("blur",m)},[n,p]),a(nc,{...c,children:a(qO,{scope:t,open:n,onOpenChange:p,content:l,onContentChange:d,children:a(UO,{scope:t,onClose:ae(()=>p(!1),[p]),isUsingKeyboardRef:u,dir:f,modal:s,children:r})})})},"Menu"),HO=J(He(function(t,n){const{__scopeMenu:r,...i}=t,o=Mp(r);return a(Xo,{...o,...i,ref:n})},"MenuAnchor")),S_="MenuPortal",[VO,KO]=Xr(S_,{forceMount:void 0}),zO=He(e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,o=ma(S_,t);return a(VO,{scope:t,forceMount:n,children:a(kt,{present:n||o.open,children:a(_i,{asChild:!0,container:i,children:r})})})},"MenuPortal"),dr="MenuContent",[WO,C_]=Xr(dr),JO=J(He(function(t,n){const r=KO(dr,t.__scopeMenu),{forceMount:i=r.forceMount,...o}=t,s=ma(dr,t.__scopeMenu),c=Fp(dr,t.__scopeMenu);return a(jp.Provider,{scope:t.__scopeMenu,children:a(kt,{present:i||s.open,children:a(jp.Slot,{scope:t.__scopeMenu,children:c.modal?a(YO,{...o,ref:n}):a(XO,{...o,ref:n})})})})},"MenuContent")),YO=J(He(function(t,n){const r=ma(dr,t.__scopeMenu),i=B(null),o=Re(n,i);return V(()=>{const s=i.current;if(s)return hs(s)},[]),a(R_,{...t,ref:o,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:te(t.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})},"MenuRootContentModal")),XO=J(He(function(t,n){const r=ma(dr,t.__scopeMenu);return a(R_,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})},"MenuRootContentNonModal")),QO=cn("MenuContent.ScrollLock"),R_=J(He(function(t,n){const{__scopeMenu:r,loop:i=!1,trapFocus:o,onOpenAutoFocus:s,onCloseAutoFocus:c,disableOutsidePointerEvents:l,onEntryFocus:d,onEscapeKeyDown:u,onPointerDownOutside:p,onFocusOutside:f,onInteractOutside:m,onDismiss:v,disableOutsideScroll:g,...h}=t,b=ma(dr,r),w=Fp(dr,r),_=Mp(r),R=w_(r),I=FO(r),[T,A]=x(null),O=B(null),F=Re(n,O,b.onContentChange),N=B(0),L=B(""),D=B(0),G=B(null),q=B("right"),$=B(0),E=g?To:z,S=g?{as:QO,allowPinchZoom:!0}:void 0,M=He(U=>{const re=L.current+U,oe=I().filter(Ie=>!Ie.disabled),ie=document.activeElement,se=oe.find(Ie=>Ie.ref.current===ie)?.textValue,ue=E_(oe.map(Ie=>Ie.textValue),re,se),Pe=oe.find(Ie=>Ie.textValue===ue)?.ref.current;He((function Ie(le){L.current=le,window.clearTimeout(N.current),le!==""&&(N.current=window.setTimeout(()=>Ie(""),1e3))}),"updateSearch")(re),Pe&&setTimeout(()=>Pe.focus())},"handleTypeaheadSearch");V(()=>()=>window.clearTimeout(N.current),[]),Ci();const H=ae(U=>q.current===G.current?.side&&x_(U,G.current?.area),[]);return a(WO,{scope:r,searchRef:L,onItemEnter:ae(U=>{H(U)&&U.preventDefault()},[H]),onItemLeave:ae(U=>{H(U)||(O.current?.focus(),A(null))},[H]),onTriggerLeave:ae(U=>{H(U)&&U.preventDefault()},[H]),pointerGraceTimerRef:D,onPointerGraceIntentChange:ae(U=>{G.current=U},[]),children:a(E,{...S,children:a(as,{asChild:!0,trapped:o,onMountAutoFocus:te(s,U=>{U.preventDefault(),O.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:c,children:a(bi,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:u,onPointerDownOutside:p,onFocusOutside:f,onInteractOutside:m,onDismiss:v,children:a(uu,{asChild:!0,...R,dir:w.dir,orientation:"vertical",loop:i,currentTabStopId:T,onCurrentTabStopIdChange:A,onEntryFocus:te(d,U=>{w.isUsingKeyboardRef.current||U.preventDefault()}),preventScrollOnEntryFocus:!0,children:a(rc,{role:"menu","aria-orientation":"vertical","data-state":k_(b.open),"data-radix-menu-content":"",dir:w.dir,..._,...h,ref:F,style:{outline:"none",...h.style},onKeyDown:te(h.onKeyDown,U=>{const re=U.target.closest("[data-radix-menu-content]")===U.currentTarget,oe=U.ctrlKey||U.altKey||U.metaKey,ie=U.key.length===1;re&&(U.key==="Tab"&&U.preventDefault(),!oe&&ie&&M(U.key));const se=O.current;if(U.target!==se||!MO.includes(U.key))return;U.preventDefault();const ue=I().filter(Pe=>!Pe.disabled).map(Pe=>Pe.ref.current);b_.includes(U.key)&&ue.reverse(),P_(ue)}),onBlur:te(t.onBlur,U=>{U.currentTarget.contains(U.target)||(window.clearTimeout(N.current),L.current="")}),onPointerMove:te(t.onPointerMove,Oc(U=>{const re=U.target,oe=$.current!==U.clientX;if(U.currentTarget.contains(re)&&oe){const ie=U.clientX>$.current?"right":"left";q.current=ie,$.current=U.clientX}}))})})})})})})},"MenuContentImpl")),Bp="MenuItem",I_="menu.itemSelect",ZO=J(He(function(t,n){const{disabled:r=!1,onSelect:i,...o}=t,s=B(null),c=Fp(Bp,t.__scopeMenu),l=C_(Bp,t.__scopeMenu),d=Re(n,s),u=B(!1),p=He(()=>{const f=s.current;if(!r&&f){const m=new CustomEvent(I_,{bubbles:!0,cancelable:!0});f.addEventListener(I_,v=>i?.(v),{once:!0}),os(f,m),m.defaultPrevented?u.current=!1:c.onClose()}},"handleSelect");return a(ej,{...o,ref:d,disabled:r,onClick:te(t.onClick,p),onPointerDown:f=>{t.onPointerDown?.(f),u.current=!0},onPointerUp:te(t.onPointerUp,f=>{u.current||f.currentTarget?.click()}),onKeyDown:te(t.onKeyDown,f=>{r||f.target!==f.currentTarget||l.searchRef.current!==""&&f.key===" "||Op.includes(f.key)&&(f.currentTarget.click(),f.preventDefault())})})},"MenuItem")),ej=J(He(function(t,n){const{__scopeMenu:r,disabled:i=!1,textValue:o,...s}=t,c=C_(Bp,r),l=w_(r),d=B(null),u=Re(n,d),[p,f]=x(!1),[m,v]=x("");return V(()=>{const g=d.current;g&&v((g.textContent??"").trim())},[s.children]),a(jp.ItemSlot,{scope:r,disabled:i,textValue:o??m,children:a(pu,{asChild:!0,...l,focusable:!i,children:a(ye.div,{role:"menuitem","data-highlighted":p?"":void 0,"aria-disabled":i||void 0,"data-disabled":i?"":void 0,...s,ref:u,onPointerMove:te(t.onPointerMove,Oc(g=>{i?c.onItemLeave(g):(c.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:te(t.onPointerLeave,Oc(g=>c.onItemLeave(g))),onFocus:te(t.onFocus,()=>f(!0)),onBlur:te(t.onBlur,()=>f(!1))})})})},"MenuItemImpl")),[sG,cG]=Xr("MenuRadioGroup",{value:void 0,onValueChange:He(()=>{},"onValueChange")}),tj="MenuItemIndicator",[lG,dG]=Xr(tj,{checked:!1}),nj="MenuSub",[uG,pG]=Xr(nj);function k_(e){return e?"open":"closed"}He(k_,"getOpenState");function T_(e){return e==="indeterminate"}He(T_,"isIndeterminate");function rj(e){return T_(e)?"indeterminate":e?"checked":"unchecked"}He(rj,"getCheckedState");function P_(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}He(P_,"focusFirst");function N_(e,t){return e.map((n,r)=>e[(t+r)%e.length])}He(N_,"wrapArray");function E_(e,t,n){const r=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let o=N_(e,Math.max(i,0));r.length===1&&(o=o.filter(c=>c!==n));const s=o.find(c=>c.toLowerCase().startsWith(r.toLowerCase()));return s!==n?s:void 0}He(E_,"getNextMatch");function A_(e,t){const{x:n,y:r}=e;let i=!1;for(let o=0,s=t.length-1;o<t.length;s=o++){const c=t[o],l=t[s],d=c.x,u=c.y,p=l.x,f=l.y;u>r!=f>r&&n<(p-d)*(r-u)/(f-u)+d&&(i=!i)}return i}He(A_,"isPointInPolygon");function x_(e,t){return t?A_({x:e.clientX,y:e.clientY},t):!1}He(x_,"isPointerInGraceArea");function Oc(e){return t=>t.pointerType==="mouse"?e(t):void 0}He(Oc,"whenMouse");var ij=GO,oj=HO,aj=zO,sj=JO,cj=ZO,lj=Object.defineProperty,ha=(e,t)=>lj(e,"name",{value:t,configurable:!0}),qp="DropdownMenu",[dj,fG]=dt(qp,[__]),ga=__(),[uj,D_]=dj(qp),pj=ha(e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:o,onOpenChange:s,modal:c=!0}=e,l=ga(t),d=B(null),[u,p]=At({prop:i,defaultProp:o??!1,onChange:s,caller:qp});return a(uj,{scope:t,triggerId:Et(),triggerRef:d,contentId:Et(),open:u,onOpenChange:p,onOpenToggle:ae(()=>p(f=>!f),[p]),modal:c,children:a(ij,{...l,open:u,onOpenChange:p,dir:r,modal:c,children:n})})},"DropdownMenu"),fj="DropdownMenuTrigger",mj=J(ha(function(t,n){const{__scopeDropdownMenu:r,disabled:i=!1,...o}=t,s=D_(fj,r),c=ga(r),l=Re(n,s.triggerRef);return a(oj,{asChild:!0,...c,children:a(ye.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":i?"":void 0,disabled:i,...o,ref:l,onPointerDown:te(t.onPointerDown,d=>{!i&&d.button===0&&d.ctrlKey===!1&&(s.onOpenToggle(),s.open||d.preventDefault())}),onKeyDown:te(t.onKeyDown,d=>{i||(["Enter"," "].includes(d.key)&&s.onOpenToggle(),d.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(d.key)&&d.preventDefault())})})})},"DropdownMenuTrigger")),hj=ha(e=>{const{__scopeDropdownMenu:t,...n}=e,r=ga(t);return a(aj,{...r,...n})},"DropdownMenuPortal"),gj="DropdownMenuContent",vj=J(ha(function(t,n){const{__scopeDropdownMenu:r,...i}=t,o=D_(gj,r),s=ga(r),c=B(!1);return a(sj,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...i,ref:n,onCloseAutoFocus:te(t.onCloseAutoFocus,l=>{c.current||o.triggerRef.current?.focus(),c.current=!1,l.preventDefault()}),onInteractOutside:te(t.onInteractOutside,l=>{const d=l.detail.originalEvent,u=d.button===0&&d.ctrlKey===!0,p=d.button===2||u;(!o.modal||p)&&(c.current=!0)}),style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})},"DropdownMenuContent")),yj=J(ha(function(t,n){const{__scopeDropdownMenu:r,...i}=t,o=ga(r);return a(cj,{...o,...i,ref:n})},"DropdownMenuItem")),bj=pj,_j=mj,wj=hj,Sj=vj,L_=yj;function Cj({assignProjectDisabled:e,disabled:t,onAssignProject:n,onForget:r,title:i}){return y(bj,null,y(_j,{asChild:!0},y("button",{"aria-label":`Actions for ${i}`,className:"feed-menu-trigger",type:"button"},"⋯")),y(wj,null,y(Sj,{align:"end",className:"feed-menu-panel",side:"bottom",sideOffset:4},y(L_,{className:"feed-menu-item",disabled:e,onSelect:()=>n()},e?"Moving…":"Assign to project…"),y(L_,{className:"feed-menu-item danger",disabled:t,onSelect:()=>r()},t?"Forgetting…":"Forget memory"))))}function Rj({modes:e,active:t,onSelect:n}){return e.length<=1?null:y("div",{className:"feed-toggle"},e.map(r=>y("button",{key:r.id,className:`toggle-button${r.id===t?" active":""}`,"data-filter":r.id,onClick:()=>n(r.id),type:"button"},r.label)))}function Up({label:e,variant:t=""}){return y(vp,{variant:"provenance",tone:t||void 0},e)}function Ij({tag:e}){const t=uL(e);return t?y(vp,{variant:"tag",title:String(e)},t):null}function kj({item:e,onReplace:t,onRemove:n,onViewRefresh:r,onReload:i}){const o=wc(e?.metadata_json),s=Lc(e,o),c=$O(e,o),l=Tt(e),d=e.title||"(untitled)",u=s&&o?.request?o.request:d,p=e.created_at||e.created_at_utc,f=aL(p),m=gL(e),v=_c(e.files||[]),g=e.project||"",h=bL(e),b=_L(e,o),w=String(e.visibility||o?.visibility||"private").trim(),_=String(e.workspace_kind||o?.workspace_kind||"").trim(),R=String(e.origin_source||o?.origin_source||"").trim(),I=String(e.trust_state||o?.trust_state||"").trim(),T=v.length?` · ${dL(v)}`:"",A=Number(e.id||0),O=A>0?`ID ${A}`:"",[F,N]=x(C.newItemKeys.has(l)),L=s?LO({...e,metadata_json:o}):null,D=s?null:YL({...e,metadata_json:o}),G=D?XL(D):[],q=D?QL(D):"summary",$=C.itemViewState.get(l),E=D&&$&&G.some(we=>we.id===$)?$:q,[S,M]=x(E),H=`${l}:${S}`,[U,re]=x(C.itemExpandState.get(H)===!0),[oe,ie]=x(w==="shared"?"shared":"private"),[se,ue]=x(!1),[Pe,Ie]=x(!1),[le,ve]=x(!1),X=L?xO(L):[];V(()=>{D&&(G.some(we=>we.id===S)||M(q))},[S,q,G,D]),V(()=>{C.itemViewState.set(l,S)},[S,l]),V(()=>{const we=`${l}:${S}`;re(C.itemExpandState.get(we)===!0)},[S,l]),V(()=>{ie(w==="shared"?"shared":"private")},[w]),V(()=>{if(!F)return;const we=window.setTimeout(()=>{C.newItemKeys.delete(l),N(!1)},700);return()=>window.clearTimeout(we)},[F,l]);const ce=oe,be=ce==="shared"?"This memory can sync to peers allowed by your project filters.":"This memory stays on this device unless a matching local assignment allows it to sync.",fe=[g?`Project ${g}`:"No project",f].filter(Boolean).join(" · "),We=[_&&_!==w?`Workspace ${_}`:"",R?`From ${R}`:"",b,I&&I!=="trusted"?yL(I):""].filter(Boolean).join(" · "),he=[T.trim(),We].filter(Boolean).join(" · "),W=!!D&&ZL(S,D),de=[S==="facts"?"feed-body facts":"feed-body",S==="narrative"?"narrative":"",W&&!U?e$(S).join(" "):""].filter(Boolean).join(" "),ne=s?X.length?y("div",{className:"feed-body facts"},X):y_(String(e.body_text||""))||y("div",{className:"feed-body"}):D?S==="facts"?DO(D.facts)||y("div",{className:de}):y_(S==="narrative"?D.narrative:D.summary,de)||y("div",{className:de}):y("div",{className:"feed-body"});async function xe(we){const Ye=ce;ie(we),ue(!0);try{const Xe=await $C(A,we);Xe?.item&&(t(Xe.item),r()),Z(we==="shared"?"Memory will now sync as shared context.":"Memory is private again.")}catch(Xe){ie(Ye),Z(Xe instanceof Error?Xe.message:"Failed to save visibility.","warning")}finally{ue(!1)}}async function tt(){const we=String(e.project||"").trim(),Ye=we,Xe=String(u||"this memory").trim(),Kt=Xe.length>80?`${Xe.slice(0,79).trimEnd()}…`:Xe,Ua=we?`Move "${Kt}" from "${we}" to another project. Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`:`Assign a project to "${Kt}". Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`;let li=[];try{li=(await Va()).filter(lt=>lt&&lt!==we)}catch{}const di=await rp({title:"Assign to project",description:Ua,initialValue:Ye,placeholder:"Pick one or type a new project name",suggestions:li,confirmLabel:"Move",cancelLabel:"Cancel",validate:lt=>{const _n=lt.trim();return _n?_n===we?"Already assigned to this project.":null:"Enter a project name."}});if(di==null)return;const ui=di.trim();if(!(!ui||ui===we)){ve(!0);try{const lt=await OC(A,ui),_n=Number(lt.moved_memory_count||1),fo=_n>1?`Moved ${_n} memories from this session to "${lt.project}".`:`Moved to "${lt.project}".`;Z(fo),await i(),r()}catch(lt){Z(lt instanceof Error?lt.message:"Failed to move memory.","warning")}finally{ve(!1)}}}async function po(){const we=String(u||"this memory").trim(),Ye=we.length>80?`${we.slice(0,79).trimEnd()}…`:we;if(await hn({autoFocusAction:"cancel",title:"Forget this memory?",description:`Forgetting "${Ye}". This removes the memory from active results. The underlying record remains soft-deleted for audit and sync safety.`,confirmLabel:"Forget memory",cancelLabel:"Keep memory",tone:"danger"})){Ie(!0);try{await jC(A),n(A),r(),await i(),Z("Memory forgotten and removed from the active feed.")}catch(Xe){Z(Xe instanceof Error?Xe.message:"Failed to forget memory.","warning")}finally{Ie(!1)}}}const Vn=c.replace(/_/g," "),bn=v.length?y("div",{className:"feed-files"},v.map((we,Ye)=>y("span",{className:"feed-file",key:`${String(we)}-${Ye}`},String(we)))):null;return y("article",{className:`feed-item ${c}${F?" new-item":""}`.trim(),"data-key":l},y("div",{className:"feed-kind-banner"},y(vp,{variant:"kind",tone:c},Vn)),y("div",{className:"feed-card-body"},y("div",{className:"feed-card-header"},y("div",{className:"feed-header"},y("div",{className:"feed-title title",dangerouslySetInnerHTML:{__html:MN(u,C.feedQuery)}}),y("div",{className:"feed-card-subtitle small"},fe)),y("div",{className:"feed-actions"},D?y(Rj,{active:S,modes:G,onSelect:we=>M(we)}):null,y(kc,{label:oL(p),side:"left"},y("div",{className:"small feed-age"},f)),e.owned_by_self&&A>0?y(Cj,{assignProjectDisabled:le,disabled:Pe,onAssignProject:()=>{tt()},onForget:()=>{po()},title:String(u||"memory")}):null)),y("div",{className:"feed-provenance"},y(Up,{label:h,variant:h==="You"?"mine":"author"}),y(Up,{label:w||"private",variant:w||"private"}),O?y(kc,{label:`Memory database id ${A}`,side:"top"},y(Up,{label:O,variant:"memory-id"})):null),he?y("div",{className:"feed-meta"},he):null,ne,y("div",{className:"feed-footer"},y("div",{className:"feed-footer-left"},m.length?y("div",{className:"feed-tags"},m.map((we,Ye)=>y(Ij,{key:`${String(we)}-${Ye}`,tag:we}))):null,e.owned_by_self&&A>0?y("div",{className:"feed-visibility-controls"},y("select",{"aria-label":`Visibility for ${String(e.title||"memory")}`,className:"feed-visibility-select",disabled:se,onChange:we=>{xe(String(we.currentTarget.value)==="shared"?"shared":"private")},value:ce},y("option",{value:"private"},"Only me"),y("option",{value:"shared"},"Share with peers")),y("div",{className:"feed-visibility-note"},be)):null),y("div",{className:"feed-footer-right"},W?y("button",{className:"feed-expand",onClick:()=>{const we=!U;C.itemExpandState.set(H,we),re(we)},type:"button"},U?"Collapse":"Expand"):null)),bn))}function Tj({index:e}){const t=[["w-85","w-65"],["w-85","w-40"],["w-65","w-85"]],[n,r]=t[e%t.length];return y("div",{className:"feed-skeleton-item","aria-hidden":"true"},y("div",{className:"feed-skeleton-banner"}),y("div",{className:"feed-skeleton-body"},y("div",{className:`feed-skeleton-line ${n}`}),y("div",{className:`feed-skeleton-line ${r}`}),y("div",{className:"feed-skeleton-footer"},y("div",{className:"feed-skeleton-chip w-36"}),y("div",{className:"feed-skeleton-chip w-56"}),y("div",{className:"feed-skeleton-chip"}))))}function Pj({items:e,loadingText:t,ops:n}){if(t)return y("div",{className:"feed-skeleton",role:"status","aria-label":t},[0,1,2,3].map(r=>y(Tj,{index:r,key:`skeleton-${r}`})));if(!e.length){const r=!!C.feedQuery.trim()||C.feedTypeFilter!=="all"||C.feedScopeFilter!=="all";return y("div",{className:"small feed-empty-state"},y("strong",null,r?"No memories match the current filters.":"No memories yet."),y("div",null,r?"Try clearing filters, changing the scope, or using a broader search.":"Memories and session summaries will appear here once codemem has something worth keeping."))}return y(z,null,e.map(r=>y(kj,{item:r,key:Tt(r),onReplace:n.replaceFeedItem,onRemove:n.removeFeedItem,onViewRefresh:()=>n.updateFeedView(!0),onReload:n.loadFeedData})))}function $_({id:e,active:t,options:n,onSelect:r}){return y("div",{className:"feed-toggle",id:e},n.map(({value:i,label:o})=>{const s=i===t;return y("button",{"aria-pressed":s?"true":"false",className:`toggle-button${s?" active":""}`,"data-filter":i,key:i,onClick:()=>r(i),type:"button"},o)}))}function Nj({text:e}){return y("div",{"aria-live":"polite",className:"section-meta",id:"feedMeta",role:"status"},e)}function Ej({query:e,onQuery:t}){return y("input",{"aria-label":"Search memories",className:"feed-search",id:"feedSearch",onInput:n=>{t(String(n.currentTarget.value||""))},placeholder:"Search title, body, tags…",type:"search",value:e})}function Aj({errorText:e,items:t,loadingText:n,ops:r}){const[i,o]=x(!1);return y(z,null,y("div",{className:"feed-controls"},y(Nj,{text:n||t$(t.length,r.hasMorePages())}),y("div",{className:"feed-controls-right"},y(Ej,{query:C.feedQuery,onQuery:r.updateFeedQuery}),y($_,{active:C.feedScopeFilter,id:"feedScopeToggle",onSelect:s=>{s!==C.feedScopeFilter&&(Kv(s),r.loadFeedData().catch(()=>{}))},options:[{value:"all",label:"All"},{value:"mine",label:"My memories"},{value:"theirs",label:"Other people"}]}),y($_,{active:C.feedTypeFilter,id:"feedTypeToggle",onSelect:s=>{s!==C.feedTypeFilter&&(XN(s),r.updateFeedView())},options:[{value:"all",label:"All"},{value:"observations",label:"Observations"},{value:"summaries",label:"Summaries"}]}),y("button",{"aria-controls":"contextInspectorPanel","aria-expanded":i,className:"settings-button feed-inspector-button",onClick:()=>o(s=>!s),type:"button"},i?"Hide Context Inspector":"Context Inspector"))),y(n$,{open:i}),y("div",{className:"feed-list",id:"feedList"},y(z,null,e?y("div",{className:"small feed-empty-state",role:"alert"},y("strong",null,e),y("div",null,"Check the viewer connection, then retry the Feed."),y("button",{className:"settings-button",onClick:()=>{r.loadFeedData().catch(()=>{})},type:"button"},"Retry")):null,!e||t.length>0?y(Pj,{items:t,loadingText:n,ops:r}):null)))}function xj(e){return C.feedTypeFilter==="observations"?e.filter(t=>!Lc(t,wc(t?.metadata_json))):C.feedTypeFilter==="summaries"?e.filter(t=>Lc(t,wc(t?.metadata_json))):e}function Dj(e){const t=e.map(n=>`${Rb(n)}:${n.kind||""}:${n.created_at_utc||n.created_at||""}`);return`${C.feedTypeFilter}|${C.feedScopeFilter}|${C.currentProject}|${ra(C.feedQuery)}|${t.join("|")}`}var O_="",va=0,ya=0,Zi=!0,eo=!0,jc=null,Lj=0,qt=null,j_=!1,to=0,Gp="all",M_="",ba=null,no="",mG=250;function F_(e){O_=e,Gp=C.feedScopeFilter,M_=C.feedQuery.trim(),no="",to+=1,va=0,ya=0,Zi=!0,eo=!0,C.lastFeedItems=[],C.pendingFeedItems=null,C.lastFeedFilteredCount=0,C.lastFeedSignature="",C.newItemKeys.clear(),C.itemViewState.clear(),C.itemExpandState.clear()}function Hp(){return Zi||eo}function $j(e){const t=Tt(e);C.lastFeedItems=C.lastFeedItems.map(n=>Tt(n)===t?e:n)}function Oj(e){const t=new Set,n=r=>{const i=Number(r.id||r.memory_id||0)!==e;return i||t.add(Tt(r)),i};C.lastFeedItems=C.lastFeedItems.filter(n),Array.isArray(C.pendingFeedItems)&&(C.pendingFeedItems=C.pendingFeedItems.filter(n));for(const r of t){C.newItemKeys.delete(r),C.itemViewState.delete(r);for(const i of Array.from(C.itemExpandState.keys()))i.startsWith(`${r}:`)&&C.itemExpandState.delete(i)}}async function jj(){if(!Hp())return;const e=to;if(jc===e)return;const t=C.currentProject||"",n=C.feedQuery.trim(),r=va,i=ya;jc=e;try{const[o,s]=await Promise.all([Zi?gm(t,{limit:20,offset:r,scope:C.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:r}}),eo?vm(t,{limit:50,offset:i,scope:C.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:i}})]);if(e!==to||t!==(C.currentProject||"")||n!==C.feedQuery.trim())return;const c=s.items||[],l=o.items||[],d=n?l:l.filter(f=>!Cb(f));C.lastFeedFilteredCount+=l.length-d.length,eo=Sc(s,c.length,50),Zi=Sc(o,l.length,20),ya=Cc(s,i+c.length),va=Cc(o,r+l.length);const u=[...c,...d],p=Ib(C.lastFeedItems,u);C.lastFeedItems=p,Qr()}finally{jc===e&&(jc=null)}}function B_(){C.activeTab==="feed"&&(ba||qt||Hp()&&SL()&&jj())}var Mj={replaceFeedItem:$j,removeFeedItem:Oj,updateFeedView:e=>Qr(e),loadFeedData:()=>zp(),updateFeedQuery:e=>Bj(e),hasMorePages:Hp};function Vp(e,t){const n=document.getElementById("tab-feed");if(!n)return!1;zL(n,y(Aj,{errorText:t?.errorText,items:e,loadingText:t?.loadingText,ops:Mj}));const r=globalThis.lucide;return r&&!t?.loadingText&&r.createIcons(),!0}function Kp(e="Loading selected project..."){Vp([],{loadingText:e})}function Fj(){KL(),Vp(C.lastFeedItems,C.lastFeedItems.length||C.lastFeedSignature?void 0:{loadingText:"Loading memories…"}),j_||(window.addEventListener("scroll",()=>{B_()},{passive:!0}),j_=!0)}function Bj(e){if(e===C.feedQuery)return;const t=C.feedQuery.trim();C.feedQuery=e,e.trim()!==t&&(F_(C.currentProject||""),Kp("Searching memories…"),ba&&clearTimeout(ba),ba=setTimeout(()=>{ba=null,zp().catch(()=>{})},250))}function Qr(e=!1){if(!document.getElementById("tab-feed"))return;const t=window.scrollY,n=xj(C.lastFeedItems),r=Dj(n),i=e||r!==C.lastFeedSignature;C.lastFeedSignature=r,i&&Vp(n,{errorText:no||void 0}),window.scrollTo({top:t}),B_()}async function zp(){const e=C.currentProject||"",t=C.feedScopeFilter!==Gp,n=C.feedQuery.trim(),r=n!==M_;(e!==O_||t||r)&&(F_(e),Kp(r?"Searching memories…":void 0));const i=to,o=++Lj;qt={generation:i,requestId:o};const s=!!no;s&&(no="",C.lastFeedItems.length>0?Qr(!0):Kp(n?"Searching memories…":void 0));try{const[d,u]=await Promise.all([gm(e,{limit:20,offset:0,scope:C.feedScopeFilter,q:n||void 0}),vm(e,{limit:50,offset:0,scope:C.feedScopeFilter,q:n||void 0})]);if(qt?.generation!==i||qt.requestId!==o||i!==to||e!==(C.currentProject||"")||n!==C.feedQuery.trim())return;const p=u.items||[],f=d.items||[],m=n?f:f.filter(w=>!Cb(w)),v=f.length-m.length,g=[...p,...m].sort((w,_)=>new Date(_.created_at||0).getTime()-new Date(w.created_at||0).getTime()),h=wL(C.lastFeedItems,g),b=C.lastFeedItems;if(CL(h,b)&&b.length>0){const w=new Set(b.map(Tt));h.forEach(_=>{w.has(Tt(_))||C.newItemKeys.add(Tt(_))})}C.pendingFeedItems=null,C.lastFeedItems=h,no="",C.lastFeedFilteredCount=Math.max(C.lastFeedFilteredCount,v),eo=Sc(u,p.length,50),Zi=Sc(d,f.length,20),ya=Math.max(ya,Cc(u,p.length)),va=Math.max(va,Cc(d,f.length)),Gp=C.feedScopeFilter,qt?.generation===i&&qt.requestId===o&&(qt=null),Qr(s)}catch(c){throw qt?.generation===i&&qt.requestId===o&&i===to&&e===(C.currentProject||"")&&n===C.feedQuery.trim()&&(Zi=!1,eo=!1,no="Feed unavailable. Refresh and try again.",Qr(!0)),c}finally{qt?.generation===i&&qt.requestId===o&&(qt=null)}}function qj(e){return e.channel==="latest"?"stable":e.channel}function hG(e){return e}function Uj(e){const t=new Date(e.periodStart),n=new Date(e.periodEnd),r=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric"}),i=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",year:"numeric"});return t.getFullYear()===n.getFullYear()?[r.format(t),i.format(n)]:[i.format(t),i.format(n)]}function Gj(e,t){const n=100*e/t,r=Math.round(n);return n>0&&r===0?"<1%":n<100&&r===100?">99%":`${r}%`}function Hj(e){if(e.freshEvaluations===0)return[{label:"Recalls checked",value:0,tooltip:"No automatic recalls were checked for repeated memories in this period.",icon:"activity"},{label:"Not checked",value:e.unmeasuredAttempts,tooltip:`Codemem could not check ${e.unmeasuredAttempts.toLocaleString()} automatic recalls for repeated memories, so savings are unknown.`,icon:"circle-help"}];const t=Gj(e.evaluationsWithDuplicates,e.freshEvaluations),n=e.missingRetainedMetadata>0||e.invalidRetainedMetadata>0||e.packMetadataGaps>0;return[{label:"Recalls with repeats",value:t,tooltip:`Codemem removed repeated memories from ${e.evaluationsWithDuplicates.toLocaleString()} of ${e.freshEvaluations.toLocaleString()} automatic recalls.`,icon:"filter"},{label:"Memories skipped",value:e.duplicatesOmitted,tooltip:`Codemem left out ${e.duplicatesOmitted.toLocaleString()} memories that were already in your conversation, out of ${e.candidateItems.toLocaleString()} considered.`,icon:"minus-circle"},{label:"Repeated tokens removed",value:`~${Wi(e.estimatedTokensAvoided)}`,tooltip:`About ${e.estimatedTokensAvoided.toLocaleString()} tokens were left out because they repeated information already in your conversation.`,icon:"trending-down"},{label:"Recalls checked",value:e.freshEvaluations,tooltip:`Codemem checked ${e.freshEvaluations.toLocaleString()} automatic recalls for repeated memories. ${e.unmeasuredAttempts.toLocaleString()} more could not be checked.${n?" Some results may be incomplete.":""}`,icon:"activity"}]}function Vj(e){if(!e||e.availability==="unavailable")return y("p",{class:"section-meta"},"Automatic recall details aren’t available. Update Codemem and refresh this page.");const[t,n]=Uj(e);return y(z,null,y("div",{class:"grid-2 automatic-recall-grid"},Hj(e).map(r=>y(q_,{...r,key:`${r.label}-${r.icon}`}))),y("p",{class:"automatic-recall-meta"},y("time",{dateTime:e.periodStart},t),"–",y("time",{dateTime:e.periodEnd},n),` · Based on up to ${e.windowLimit.toLocaleString()} recent automatic recalls across all projects.${e.freshEvaluations===0?" No recalls were checked, so savings are unknown.":""}`))}function Kj(e,t){e&&(Ue(y(Ic,null,y("details",{class:"automatic-recall"},y("summary",null,"Automatic recall"),y("section",{"aria-label":"Automatic recall measurements"},Vj(qC(t))))),e),Mc())}function zj(e){if(e.install_kind==="repo-dev")return{title:"Running from repository source",detail:`Package metadata version: ${e.current_version}. Registry releases do not describe the checked-out source revision.`,tone:"current"};if(!e.latest_version)return{title:"Update check unavailable",detail:e.error?`Could not check for updates: ${e.error}`:"Could not check for updates.",tone:"unavailable"};if(e.stale)return{title:e.update_available?`Cached update status: Codemem ${e.latest_version} is available`:`Cached update status for Codemem ${e.current_version}`,detail:e.error?`This result is stale because a fresh check failed: ${e.error}`:"This result is cached and may be stale.",tone:"stale"};if(e.update_available)return{title:`Codemem ${e.latest_version} is available`,detail:`Installed version: ${e.current_version}.`,tone:"available"};const t=qj(e);return t?{title:`Codemem ${e.current_version} is up to date`,detail:`You are running the latest ${t} release.`,tone:"current"}:{title:`Unable to compare Codemem ${e.current_version} with ${e.latest_version}`,detail:"The installed version is not on a supported release channel.",tone:"unavailable"}}function Wj({status:e}){const t=zj(e),n=e.install_kind==="repo-dev"||e.update_available||e.stale||!e.latest_version||!e.channel;return y("section",{class:`health-update-banner health-update-banner--${t.tone}`,role:"status","aria-atomic":"true","aria-label":"Codemem update status"},y("i",{"aria-hidden":"true","data-lucide":"circle-arrow-up",class:"health-update-icon"}),y("div",{class:"health-update-copy"},y("h2",null,t.title),y("p",null,t.detail),n&&e.recommended_action?y("p",{class:"health-update-guidance"},y("span",{class:"health-update-guidance-label"},"Recommended action"),y("code",null,e.recommended_action)):null))}function Jj(e,t){e&&(e.hidden=!t,Ue(t?y(Wj,{status:t}):null,e))}function Yj({label:e,value:t,detail:n,icon:r,className:i,title:o}){const s=y("div",{class:`stat${i?` ${i}`:""}`,style:o?"cursor: help;":void 0},r?y("i",{"data-lucide":r,class:"stat-icon"}):null,y("div",{class:"stat-content"},y("div",{class:"value"},t),y("div",{class:"label"},e),n?y("div",{class:"small"},n):null));return o?y(kc,{label:o},s):s}function Xj({item:e}){let t=null,n=null;const r=e.actionLabel||"Run";async function i(){if(!(!e.action||!t)){t.disabled=!0,t.textContent="Running…";try{await e.action(t)}catch{}t.disabled=!1,t.textContent=r}}function o(){!e.command||!n||Uo(e.command,n)}return y("div",{class:"health-action"},y("div",{class:"health-action-text"},e.label,e.command?y("span",{class:"health-action-command"},e.command):null),y("div",{class:"health-action-buttons"},e.action?y("button",{class:"settings-button",onClick:i,ref:s=>{t=s}},r):null,e.command?y("button",{class:"settings-button health-action-copy",onClick:o,ref:s=>{n=s}},"Copy"):null))}function Qj(e){return typeof e=="number"?e.toLocaleString():e==null?"n/a":String(e)}function q_({label:e,value:t,icon:n,tooltip:r}){const i=y("div",{class:"stat",style:r?"cursor: help;":void 0,tabIndex:r?0:void 0},y("i",{"data-lucide":n,class:"stat-icon"}),y("div",{class:"stat-content"},y("div",{class:"value"},Qj(t)),y("div",{class:"label"},e)));return r?y(kc,{label:r},i):i}function U_(e,t){e&&Ue(y(Ic,null,t.map(n=>y(q_,{...n,key:`${n.label}-${n.icon}`}))),e)}function G_(e,t){e&&Ue(y(z,null,t),e)}function Mc(){const e=globalThis.lucide;e&&typeof e.createIcons=="function"&&e.createIcons()}function Zj(e,t){e&&Ue(y(Ic,null,t.map(n=>y(Yj,{...n,key:n.key??n.label}))),e)}function eM(e,t){if(e){if(!t.length){e.hidden=!0,Ue(null,e);return}e.hidden=!1,Ue(y(z,null,t.slice(0,3).map((n,r)=>y(Xj,{item:n,key:`${n.label}-${r}`}))),e)}}var H_="scope_id_backfill";function tM(e,t){!t||e.length>=3||e.push({label:"Background maintenance failed. Review recent safe failure evidence.",command:"codemem maintenance status",action:n=>Ar({severity:"error",subsystem:"maintenance",trigger:n}),actionLabel:"View diagnostics"})}function V_(){const e=document.getElementById("healthGrid"),t=document.getElementById("healthMeta"),n=document.getElementById("healthActions"),r=document.getElementById("healthDot");if(!e||!t)return;Jj(document.getElementById("healthUpdateBanner"),C.lastUpdateStatus);const i=C.lastStatsPayload||{},o=C.lastUsagePayload||{},s=C.lastRawEventsPayload&&typeof C.lastRawEventsPayload=="object"?C.lastRawEventsPayload:{},c=C.lastSyncStatus||{},l=Array.isArray(i.maintenance_jobs)?i.maintenance_jobs:[],d=l.find(de=>de.kind===H_),u=l.some(de=>de.status==="failed"),p=i.reliability||{},f=p.counts||{},m=p.rates||{},v=i.database||{},g=o.totals_filtered||o.totals||o.totals_global||i.usage?.totals||{},h=Array.isArray(o.recent_packs)?o.recent_packs:[],b=h.length?h[0]?.created_at:null,w=h.length?h[0]?.metadata_json||{}:{},_=Number(w?.exact_duplicates_collapsed||0),R=Number(s.pending||0),I=Number(f.errored_batches||0),T=Number(m.flush_success_rate??1),A=Number(m.dropped_event_rate||0),O=up(g.tokens_saved,g.tokens_read),F=cL(O),N=Number(v.tags_coverage||0),L=String(c.daemon_state||"unknown"),D=L==="offline-peers"?"Offline peers":L==="needs_attention"?"Needs attention":L==="rebootstrapping"?"Rebootstrapping":wb(L),G=Array.isArray(C.lastSyncPeers)?C.lastSyncPeers.length:0,q=L==="disabled"||c.enabled===!1,$=L==="offline-peers",E=!q&&G===0;let S=q?"Disabled":E?"No peers":D;const M=c.last_sync_at||c.last_sync_at_utc||null,H=zi(M),U=zi(b),re=H!==null&&H>7200,oe=H!==null&&H<=300,ie=R>=200;let se=0;const ue=[];R>=1e3?(se+=40,ue.push("high raw-event backlog")):R>=200&&(se+=24,ue.push("growing raw-event backlog")),I>0&&R>=200&&(se+=I>=5?10:6,ue.push("batch errors during backlog pressure")),T<.95&&(se+=20,ue.push("lower flush success")),A>.02?(se+=24,ue.push("high dropped-event rate")):A>.005&&(se+=10,ue.push("non-trivial dropped-event rate")),!q&&!E&&(L==="error"?(se+=36,ue.push("sync daemon reports errors")):L==="needs_attention"?(se+=40,ue.push("sync needs manual attention")):L==="stopped"?(se+=22,ue.push("sync daemon stopped")):L==="degraded"&&!oe&&(se+=20,ue.push("sync daemon degraded")),$?(se+=4,ue.push("all peers currently offline"),re&&(se+=4,ue.push("offline peers and sync not recent"))):re?(se+=26,ue.push("sync looks stale")):H!==null&&H>1800&&(se+=12,ue.push("sync not recent"))),F!==null&&F<10&&(se+=8,ue.push("low retrieval reduction")),U!==null&&U>86400&&(se+=12,ue.push("memory pack activity is old"));let Pe="Healthy",Ie="status-healthy";se>=60?(Pe="Attention",Ie="status-attention"):se>=25&&(Pe="Degraded",Ie="status-degraded");const le=Ie==="status-healthy";r&&(r.className=`health-dot ${Ie}`,r.title=Pe);const ve=`${Number(g.tokens_saved||0).toLocaleString()} saved tokens · ${_.toLocaleString()} deduped in latest pack`,X=R>0?"Queue is actively draining":"Queue is clear",ce=q?"Sync disabled":E?"No peers configured":$?`${G} peers offline · last sync ${sr(H)} ago`:`${G} peers · last sync ${sr(H)} ago`;le&&!q&&!E&&($?S="Peers offline":L==="degraded"&&oe&&(S="Syncing"));const be=`last pack ${sr(U)} ago`,fe=l.map(de=>{const ne=Number(de.progress?.current||0),xe=typeof de.progress?.total=="number"?de.progress.total:null,tt=String(de.progress?.unit||"items"),po=xe&&xe>0?` (${Math.round(100*ne/xe)}%)`:"",Vn=xe&&xe>0?`${ne.toLocaleString()}/${xe.toLocaleString()} ${tt}${po}`:`${ne.toLocaleString()} ${tt}`,bn=de.status==="failed",we=de.status==="completed",Ye=de.kind===H_,Xe=bn?"Failed":we?"Complete":Vn,Kt=bn?String(de.error||"unknown error").trim():we?Ye?`${Vn} · one-time Sharing-domain upgrade finished`:Vn:Ye?"One-time upgrade backfill; totals include memories and replication ops":void 0;return{key:String(de.kind||de.title||"background-maintenance"),label:String(de.title||de.kind||"Background maintenance"),value:Xe,detail:Kt,icon:bn?"alert-triangle":we?"check-circle":"loader",className:bn?"status-attention":void 0,title:bn?`Error: ${de.error||"unknown"}`:we?`${String(de.title||"Maintenance")} finished`:Ye?`${String(de.title||"Maintenance")} in progress; inspect with codemem maintenance status`:`${String(de.title||"Maintenance")} in progress`}}),We=[{key:"overall-health",label:"Overall health",value:Pe,detail:`Weighted score ${se}`,icon:"heart-pulse",className:`health-primary ${Ie}`,title:ue.length?`Main signals: ${ue.join(", ")}`:"No major risk signals detected"},...fe,{key:"pipeline-health",label:"Pipeline health",value:`${R.toLocaleString()} pending`,detail:X,icon:"workflow",title:"Raw-event queue pressure and flush reliability"},{key:"retrieval-impact",label:"Retrieval impact",value:O,detail:ve,icon:"sparkles",title:"Reduction from memory reuse across recent usage"},{key:"sync-health",label:"Sync health",value:S,detail:ce,icon:"refresh-cw",title:"Daemon state and sync recency"},{key:"data-freshness",label:"Data freshness",value:sr(U),detail:be,icon:"clock-3",title:"Recency of last memory pack activity"}];Zj(e,We);const he=async()=>{await xl()},W=[];ie?(W.push({label:"Pipeline needs attention. Check queue health first.",command:"codemem db raw-events-status",action:de=>Ar({subsystem:"capture",trigger:de}),actionLabel:"View diagnostics"}),W.push({label:"Then retry failed batches for impacted sessions.",command:"codemem db raw-events-retry <opencode_session_id>"})):L==="stopped"?W.push({label:"Sync daemon is stopped. Start the background service.",command:"codemem serve start"}):!q&&!E&&!le&&(L==="error"||L==="degraded")?(W.push({label:"Sync is unhealthy. Restart and run one immediate pass.",command:"codemem serve restart",action:he,actionLabel:"Sync now"}),W.push({label:"Then run doctor to see root cause details.",command:"codemem sync doctor"})):!q&&!E&&re&&W.push({label:"Sync is stale. Run one immediate sync pass.",command:"codemem sync once",action:he,actionLabel:"Sync now"}),tM(W,u),N>0&&N<.7&&W.length<2&&W.push({label:"Tag coverage is low. Preview backfill impact.",command:"codemem db backfill-tags --dry-run"}),d&&d.status!=="completed"&&W.length<3&&W.push({label:"Sharing-domain upgrade backfill is expected one-time work. Inspect progress if startup feels busy.",command:"codemem maintenance status"}),eM(n,W),t.textContent=ue.length?`Why this status: ${ue.join(", ")}.`:"Healthy right now. Diagnostics stay available if you want details.",Mc()}function nM(){const e=document.getElementById("sessionGrid"),t=document.getElementById("sessionMeta");if(!e||!t)return;const n=C.lastUsagePayload||{},r=C.currentProject;n?.totals_global||n?.totals;const i=n?.totals_filtered||null,o=!!(r&&i),s=(Array.isArray(n?.events)?n.events:[]).find(I=>I.event==="pack")||null,c=Array.isArray(n?.recent_packs)?n.recent_packs:[],l=c.length?c[0]:null,d=l?.metadata_json||{},u=l?.created_at||"",p=Number(s?.count||0),f=Number(l?.tokens_read||0),m=Number(l?.tokens_saved||0),v=Number(d?.exact_duplicates_collapsed||0),g=!!d?.exact_dedupe_enabled,h=up(m,f),b=p?`${p} packs`:"No packs yet",w=u?`Last pack: ${Vr(u)}`:"",_=o?"Project":"All projects",R=[{label:"Last pack savings",value:l?`${Wi(m)} (${h})`:"n/a",tooltip:l?`Exact: ${m.toLocaleString()} saved`:void 0,icon:"trending-up"},{label:"Last pack size",value:l?Wi(f):"n/a",tooltip:l?`Exact: ${f.toLocaleString()} injected`:void 0,icon:"package"},{label:"Last pack deduped",value:l?v.toLocaleString():"n/a",icon:"copy-check"},{label:"Exact dedupe",value:l?g?"On":"Off":"n/a",icon:"shield-check"},{label:"Packs",value:p||0,icon:"archive"}];G_(t,[_,b,w].filter(Boolean).join(" · ")),U_(e,R),Mc()}function rM(){const e=document.getElementById("statsGrid"),t=document.getElementById("metaLine");if(!e)return;const n=C.lastStatsPayload||{},r=C.lastUsagePayload||{},i=C.lastRawEventsPayload&&typeof C.lastRawEventsPayload=="object"?C.lastRawEventsPayload:{},o=n.database||{},s=C.currentProject,c=r?.totals_global||r?.totals||n.usage?.totals||{},l=r?.totals_filtered||null,d=!!(s&&l),u=d?l:c,p=Number(i.sessions||0),f=Number(i.pending||0),m=d?`
109
- Global: ${Number(c.work_investment_tokens||0).toLocaleString()} invested`:"",v=d?`
110
- Global: ${Number(c.tokens_read||0).toLocaleString()} read`:"",g=d?`
111
- Global: ${Number(c.tokens_saved||0).toLocaleString()} saved`:"",h=[{label:d?"Savings (project)":"Savings",value:Wi(u.tokens_saved||0),tooltip:`Tokens saved by reusing compressed memories. Exact: ${Number(u.tokens_saved||0).toLocaleString()} saved${g}`,icon:"trending-up"},{label:d?"Injected (project)":"Injected",value:Wi(u.tokens_read||0),tooltip:`Tokens injected into context (pack size). Exact: ${Number(u.tokens_read||0).toLocaleString()} injected${v}`,icon:"book-open"},{label:d?"Reduction (project)":"Reduction",value:up(u.tokens_saved,u.tokens_read),tooltip:`Percent reduction from reuse. Factor: ${sL(u.tokens_saved,u.tokens_read)}.`+v+g,icon:"percent"},{label:d?"Work investment (project)":"Work investment",value:Wi(u.work_investment_tokens||0),tooltip:`Token cost of unique discovery groups. Exact: ${Number(u.work_investment_tokens||0).toLocaleString()} invested${m}`,icon:"pencil"},{label:"Active memories",value:o.active_memory_items||0,icon:"check-circle"},{label:"Embedding coverage",value:_b(o.vector_coverage),tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:_b(o.tags_coverage),tooltip:"Share of active memories with tags",icon:"tag"}];if(f>0?h.push({label:"Raw events pending",value:f,tooltip:"Pending raw events waiting to be flushed",icon:"activity"}):p>0&&h.push({label:"Raw sessions",value:p,tooltip:"Sessions with pending raw events",icon:"inbox"}),U_(e,h),t){const b=s?` · project: ${s}`:"",w=pL(o.path||"unknown");G_(t,`DB: ${w} · ${fL(o.size_bytes||0)}${b}`)}Mc()}async function iM(){const e=C.lastStatsPayload?.identity?.actor_id||null,t=C.activeTab==="health"&&!C.lastUpdateStatus?BR().catch(qR):Promise.resolve(C.lastUpdateStatus),[n,r,i,o,s]=await Promise.all([UC(),GC(C.currentProject),HC(C.currentProject),VC(C.currentProject),t]);C.lastStatsPayload=n||{},C.lastUsagePayload=r||{},C.lastRawEventsPayload=o||{},C.lastUpdateStatus=s;const c=C.lastStatsPayload?.identity?.actor_id||null;rM(),Kj(document.getElementById("automaticRecallStats"),C.lastStatsPayload.automatic_recall),nM(),V_(),C.activeTab==="feed"&&e!==c&&Qr(!0)}function Wp(e,t){return`legacy-team-setup-item-error-${e}-${t}`}function K_(e){return[...e].sort((t,n)=>+(n.decision==="unresolved")-+(t.decision==="unresolved"))}function z_(e){return[...e].sort((t,n)=>+(n.resolution==="unresolved")-+(t.resolution==="unresolved"))}var oM={unresolved:"Needs a decision",included:"Included in this Team",excluded:"Excluded from this Team",removed:"Removed from this Team"};function W_(e,t){return t?e.identityChoices.find(n=>n.identityRef===t)?.displayName??"Unavailable person":null}function aM(e){return e.targetIdentityRef??e.existingIdentityRef??""}function sM({blocked:e,blockedDescriptionId:t,blockedDeviceRefs:n,busy:r,detail:i,device:o,index:s,onAssign:c,onClear:l,onDecision:d}){const u=Ir(),p=`${u}-identity`,f=`${u}-evidence`,m=`${u}-assignment-help`,v=aM(o),g=o.targetIdentityRef??"",[h,b]=x(v);V(()=>b(v),[v]);const w=i.identityChoices.some(M=>M.identityRef===h),_=W_(i,o.existingIdentityRef),R=W_(i,o.suggestedIdentityRef),I=n?.has(o.deviceRef)??!1,T=e||I||r,A=T||!o.actions.assignIdentity.enabled,O=o.actions.assignIdentity.blockedReason==="assignment_evidence_inactive",F=!!h&&!w,N=!o.actions.include.enabled||O||F||!g||h!==g,L=T||N,D=A||!h||O||F||h===g,G=!o.enabled||N,q=e?t:I?Wp("device",o.deviceRef):void 0,$=[f,G?m:void 0,q].filter(Boolean).join(" "),E=[f,q].filter(Boolean).join(" "),S=o.decision==="unresolved";return a("fieldset",{"aria-busy":r?"true":"false",className:`legacy-team-device-row${S?" legacy-team-setup-row-needs-attention":""}`,id:`legacy-team-device-row-${s}`,tabIndex:S?-1:void 0,children:[a("legend",{children:o.displayName}),S?a("span",{className:"legacy-team-setup-status",children:"Needs attention"}):null,a("div",{className:"small legacy-team-device-evidence",id:f,children:[a("span",{children:o.enabled?"Current Team device":"Device no longer active on this Team"}),_?a("span",{children:["Current assignment: ",_,o.verifiedEvidenceKind==="active_assignment"?" · verified active assignment":""]}):null,!_&&R?a("span",{children:["Suggested person: ",R]}):null,a("span",{children:["Decision: ",oM[o.decision]]})]}),a("label",{htmlFor:p,children:"Person using this device"}),a("select",{"aria-describedby":$,className:"feed-search legacy-team-device-select",disabled:A,id:p,onChange:M=>b(M.currentTarget.value),value:h,children:[a("option",{value:"",children:"Choose a person"}),h&&!w?a("option",{value:h,children:"Current server assignment"}):null,i.identityChoices.map(M=>a("option",{value:M.identityRef,children:M.displayName},M.identityRef))]}),o.enabled?F?a("p",{className:"small",id:m,children:"This person is no longer available. Choose an available person and save the assignment before including this device."}):O?a("p",{className:"small",id:m,children:"This assignment is inactive. Reconcile this device in Devices or exclude it from this Team."}):!h||!g||h!==g?a("p",{className:"small",id:m,children:h?"Save the selected person assignment before including this device.":"Choose and save a person assignment before including this device."}):null:a("p",{className:"small",id:m,children:"Inactive devices can only be removed from this Team."}),a("div",{className:"legacy-team-device-actions",children:[a("button",{"aria-describedby":$,"aria-disabled":D?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{D||c(o,h)},type:"button",children:"Save assignment"}),o.enabled?a(z,{children:[a("button",{"aria-describedby":$,"aria-disabled":L?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{L||d(o,"included",g)},type:"button",children:"Include"}),a("button",{"aria-describedby":E,"aria-disabled":T||!o.actions.exclude.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&o.actions.exclude.enabled&&d(o,"excluded")},type:"button",children:"Exclude"})]}):a("button",{"aria-describedby":E,"aria-disabled":T||!o.actions.remove.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&o.actions.remove.enabled&&d(o,"removed")},type:"button",children:"Remove"}),o.decision!=="unresolved"?a("button",{"aria-describedby":E,"aria-disabled":T||!o.actions.clearDecision.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&o.actions.clearDecision.enabled&&l(o)},type:"button",children:"Clear decision"}):null]})]})}function cM(e){const t=K_(e.detail.devices);return a("section",{"aria-labelledby":"legacy-team-setup-step-devices",children:[a("h3",{id:"legacy-team-setup-step-devices",tabIndex:-1,children:"Review devices"}),a("p",{children:[e.detail.unresolvedDeviceCount.toLocaleString()," of"," ",e.detail.candidate.deviceCount.toLocaleString()," Team devices still need a decision."]}),a("div",{className:"legacy-team-device-list",children:t.map((n,r)=>y(sM,{...e,busy:e.busyDeviceRefs.has(n.deviceRef),device:n,index:r,key:n.deviceRef}))})]})}function lM(e,t){return e.resolvedProjectRef?t.get(e.resolvedProjectRef)??"Unavailable Project":null}function dM({blocked:e,blockedDescriptionId:t,blockedProjectRefs:n,busy:r,index:i,onMap:o,presentationName:s,project:c}){const l=Ir(),d=`${l}-mapping`,u=`${l}-help`,p=c.resolvedProjectRef??"",f=Nr(c.mappingChoices.map($=>({canonicalId:$.resolvedProjectRef,displayName:$.displayName}))),m=[...new Set(c.mappingChoices.map($=>$.resolvedProjectRef))],v=[...m].sort(($,E)=>$<E?-1:$>E?1:0),g=new Map(v.map(($,E)=>[$,`project-choice-${E+1}`])),h=new Map(c.mappingChoices.map($=>[$.resolvedProjectRef,$])),b=m.flatMap($=>{const E=h.get($);return E?[{...E,label:f.get($)??E.displayName,token:g.get($)??""}]:[]}),w=b.find($=>$.resolvedProjectRef===p)?.token??"",_=JSON.stringify(v),[R,I]=x(w);V(()=>I(w),[w,_]);const T=b.find($=>$.token===R)?.resolvedProjectRef,A=n?.has(c.projectRef)??!1,O=c.actions.map.blockedReason==="mapping_unavailable",F=c.actions.map.enabled&&!R,N=e||A||r||!c.actions.map.enabled,L=N||!T||T===p,D=lM(c,f),G=[O||F?u:void 0,e?t:A?Wp("project",c.projectRef):void 0].filter(Boolean).join(" "),q=c.resolution==="unresolved";return a("fieldset",{"aria-busy":r?"true":"false",className:`legacy-team-project-row${q?" legacy-team-setup-row-needs-attention":""}`,id:`legacy-team-project-row-${i}`,tabIndex:q?-1:void 0,children:[a("legend",{children:s}),a("div",{className:"legacy-team-project-row-content",children:[q?a("span",{className:"legacy-team-setup-status",children:"Needs attention"}):null,c.resolution==="deterministic"?a("p",{className:"small",children:"Mapped automatically from matching Project evidence."}):a(z,{children:[a("p",{className:"small",children:D?`Saved mapping: ${D}`:"This Project still needs a mapping."}),a("label",{htmlFor:d,children:"Canonical Project"}),a("select",{"aria-describedby":G||void 0,className:"feed-search legacy-team-project-select",disabled:N,id:d,onChange:$=>I($.currentTarget.value),value:R,children:[a("option",{value:"",children:"Choose a Project"}),b.map($=>a("option",{value:$.token,children:$.label},$.resolvedProjectRef))]}),O?a("p",{className:"small",id:u,children:"No safe Project mapping is available. Refresh after Project evidence changes."}):F?a("p",{className:"small",id:u,children:"Choose and save one of the server-provided Project mappings."}):null,a("button",{"aria-describedby":G||void 0,"aria-disabled":L?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!L&&T&&o(c,T)},type:"button",children:"Save mapping"})]})]})]})}function uM(e){const t=z_(e.detail.projects),n=Nr(t.map(o=>({canonicalId:o.projectRef,displayName:o.displayName}))),r=e.detail.projects.filter(o=>o.resolution==="deterministic").length,i=Math.max(e.detail.candidate.projectCount,e.detail.projects.length,e.detail.unresolvedProjectCount);return a("section",{"aria-labelledby":"legacy-team-setup-step-projects",children:[a("h3",{id:"legacy-team-setup-step-projects",tabIndex:-1,children:"Review Projects"}),a("p",{children:e.detail.unresolvedProjectCount===0?`All ${i.toLocaleString()} Team Projects are mapped.`:`${e.detail.unresolvedProjectCount.toLocaleString()} of ${i.toLocaleString()} Team Projects need attention.`}),r>0?a("p",{className:"small",children:"Review the automatic mappings below before continuing."}):null,a("div",{className:"legacy-team-project-list",children:t.map((o,s)=>a(dM,{blocked:e.blocked,blockedDescriptionId:e.blockedDescriptionId,blockedProjectRefs:e.blockedProjectRefs,busy:e.busyProjectRefs.has(o.projectRef),index:s,onMap:e.onMap,presentationName:n.get(o.projectRef)??o.displayName,project:o},o.projectRef))}),e.detail.unresolvedProjectCount===0?a("div",{className:"legacy-team-setup-next-action",children:[a("p",{className:"small",id:"legacy-team-project-continue-help",children:"Continue to review the exact people, devices, and Projects that will receive access."}),a("button",{"aria-describedby":["legacy-team-project-continue-help",e.blocked?e.blockedDescriptionId:null].filter(Boolean).join(" "),"aria-disabled":e.blocked?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{e.blocked||e.onContinue()},type:"button",children:"Continue to Review"})]}):null]})}var _a={add:"Add",update:"Update",remove:"Remove"},pM=10;function ft(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function Jp(e,t,n,r){const i=new Map;for(const o of e){const s=t(o),c=r(o),l=`${c}:${No(s)}`,d=n(o),u=i.get(l)??{displayName:s,kind:c,projectRefs:new Set,changeCount:0};u.projectRefs.add(d),u.changeCount+=1,i.set(l,u)}return[...i.values()]}function Yp(e,t){return e.kind==="legacy_default_sharing"?`${e.displayName} — default scope`:e.projectRefs.size>1?`${e.displayName} — ${ft(e.projectRefs.size,t)}`:e.displayName}function wa({empty:e,exactItemName:t,exactItems:n,summaryItems:r,title:i}){const o=!!(r&&r.length<n.length),s=o&&n.length>pM;return a("section",{children:[a("h4",{children:i}),n.length>0?a(z,{children:[o&&r?a("ul",{className:"legacy-team-setup-delta-summary",children:r.map((c,l)=>a("li",{children:c},`${i}-summary-${l}`))}):null,s?a("details",{children:[a("summary",{children:["Show all ",ft(n.length,`exact ${t}`)]}),a(J_,{items:n,title:i})]}):a(J_,{items:n,title:i})]}):a("p",{className:"small",children:e})]})}function J_({items:e,title:t}){return a("ul",{className:"legacy-team-setup-exact-list",children:e.map((n,r)=>a("li",{children:n},`${t}-${r}`))})}function fM({blocked:e,blockedDescriptionId:t,detail:n,finishing:r,onFinish:i}){const o=n.accessDelta,s=JSON.stringify([n.attemptId,n.finishDigest,n.accessDeltaDigest,n.viewerAccessDeltaDigest]),[c,l]=x(null),d=c===s,u=e||!d,p=[d?null:"legacy-team-setup-confirmation-label",e?t:null].filter(Boolean).join(" "),f=o.teamChanges.map(S=>{const M=S.fromDeviceEligibilityMode==="person_all_devices"?"all devices assigned to each person":S.fromDeviceEligibilityMode==="reviewed_allowlist"?"the reviewed device list":"no existing device policy";return`${_a[S.change]} ${S.teamDisplayName}: change device access from ${M} to the reviewed device list.`}),m=o.membershipChanges.map(S=>`${_a[S.change]} ${S.identityDisplayName} ${S.change==="remove"?"from":"to"} ${S.teamDisplayName}.`),v=Nr([...n.projects.map(S=>({canonicalId:S.projectRef,displayName:S.displayName})),...o.projectChanges.map(S=>({canonicalId:S.projectRef,displayName:S.projectDisplayName}))]),g=o.projectChanges.flatMap(S=>[...S.fromResolvedProjectRef&&S.fromResolvedProjectDisplayName?[{canonicalProjectRef:S.fromCanonicalProjectRef,resolvedProjectRef:S.fromResolvedProjectRef,displayName:S.fromResolvedProjectDisplayName}]:[],...S.toResolvedProjectRef&&S.toResolvedProjectDisplayName?[{canonicalProjectRef:S.toCanonicalProjectRef,resolvedProjectRef:S.toResolvedProjectRef,displayName:S.toResolvedProjectDisplayName}]:[]]),h=Nr(g.map(S=>({canonicalId:S.canonicalProjectRef??S.resolvedProjectRef,displayName:S.displayName}))),b=new Map(g.map(S=>[S.resolvedProjectRef,h.get(S.canonicalProjectRef??S.resolvedProjectRef)??S.displayName])),w=Nr([...n.projects.flatMap(S=>S.canonicalProjectRef?[{canonicalId:S.canonicalProjectRef,displayName:S.displayName}]:[]),...[...o.recipientChanges,...o.deviceAccessChanges].filter(S=>S.canonicalProjectKind==="project").map(S=>({canonicalId:S.canonicalProjectRef,displayName:S.canonicalProjectDisplayName}))]),_=o.projectChanges.map(S=>`${_a[S.change]} ${v.get(S.projectRef)??S.projectDisplayName}: ${S.fromResolvedProjectRef?b.get(S.fromResolvedProjectRef)??S.fromResolvedProjectDisplayName??"no Project":"no Project"} to ${S.toResolvedProjectRef?b.get(S.toResolvedProjectRef)??S.toResolvedProjectDisplayName??"no Project":"no Project"}.`),R=o.recipientChanges.map(S=>S.canonicalProjectKind==="legacy_default_sharing"?`${S.change==="remove"?"Stop":"Start"} using legacy default sharing for ${S.recipientDisplayName}.`:`${_a[S.change]} ${S.recipientDisplayName} ${S.change==="remove"?"from":"as"} a recipient for ${w.get(S.canonicalProjectRef)??S.canonicalProjectDisplayName}.`),I=o.deviceAccessChanges.map(S=>S.canonicalProjectKind==="legacy_default_sharing"?`${S.deviceDisplayName} ${S.change==="remove"?"stops":"starts"} inheriting legacy default sharing.`:`${_a[S.change]} ${S.deviceDisplayName} access ${S.change==="remove"?"from":"to"} ${w.get(S.canonicalProjectRef)??S.canonicalProjectDisplayName}.`),T=o.teamChanges.length+o.membershipChanges.length+o.projectChanges.length+o.recipientChanges.length+o.deviceAccessChanges.length,A=Jp(o.projectChanges,S=>S.projectDisplayName,S=>S.projectRef,()=>"project"),O=Jp(o.recipientChanges,S=>S.canonicalProjectDisplayName,S=>S.canonicalProjectRef,S=>S.canonicalProjectKind),F=Jp(o.deviceAccessChanges,S=>S.canonicalProjectDisplayName,S=>S.canonicalProjectRef,S=>S.canonicalProjectKind),N=n.devices.filter(S=>S.decision==="included").length,L=[ft(o.teamChanges.length,"Team policy change"),ft(o.membershipChanges.length,"membership change"),ft(o.projectChanges.length,"Project change"),ft(o.recipientChanges.length,"recipient change"),ft(o.deviceAccessChanges.length,"device-access change")],D=`${ft(n.projects.length,"Project")} included; ${ft(N,"included device")}.`,G=Math.max(n.candidate.projectCount,n.projects.length),q=new Set(o.deviceAccessChanges.map(S=>S.deviceRef)).size,$=[...o.teamChanges,...o.membershipChanges,...o.projectChanges,...o.recipientChanges,...o.deviceAccessChanges].filter(S=>S.change==="remove").length,E=o.teamChanges.length===0&&o.membershipChanges.length===0&&o.projectChanges.length===0&&o.recipientChanges.length>0&&o.recipientChanges.every(S=>S.change==="remove"&&S.canonicalProjectKind==="legacy_default_sharing")&&o.deviceAccessChanges.every(S=>S.change==="remove"&&S.canonicalProjectKind==="legacy_default_sharing")?`No new access will be added. This removes legacy default sharing for ${n.candidate.displayName}.${q>0?` ${ft(q,"device")} will stop receiving memories shared only through that default.`:""} Project-scoped access is unchanged across ${ft(G,"reviewed Project")}.`:`${ft(T,"server-confirmed access change")} will be applied atomically; ${ft($,"removal")} ${$===1?"is":"are"} included.`;return a("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[a("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),a("p",{children:"Review every server-confirmed access change before activating this Team."}),a("section",{"aria-label":"Access review summary",className:"legacy-team-setup-review-summary",children:[a("p",{className:"legacy-team-setup-net-effect",children:[a("strong",{children:"Net effect:"})," ",E]}),a("p",{children:[a("strong",{children:ft(T,"exact access change")})," to review."]}),a("ul",{children:L.map(S=>a("li",{children:S},S))}),a("p",{className:"small",children:["Scope: ",D]})]}),a("div",{className:"legacy-team-setup-delta",children:[a(wa,{empty:"No Team policy changes.",exactItemName:"Team policy change",exactItems:f,title:"Team policy"}),a(wa,{empty:"No membership changes.",exactItemName:"membership change",exactItems:m,title:"Memberships"}),a(wa,{empty:"No Project mapping changes.",exactItemName:"Project change",exactItems:_,summaryItems:A.map(S=>`${Yp(S,"reviewed Project")}, ${ft(S.changeCount,"Project change")}`),title:"Projects"}),a(wa,{empty:"No recipient changes.",exactItemName:"recipient change",exactItems:R,summaryItems:O.map(S=>`${Yp(S,"canonical Project")}, ${ft(S.changeCount,"recipient change")}`),title:"Recipients"}),a(wa,{empty:"No device access changes.",exactItemName:"device-access change",exactItems:I,summaryItems:F.map(S=>`${Yp(S,"canonical Project")}, ${ft(S.changeCount,"device-access change")}`),title:"Device access"})]}),a("label",{className:"legacy-team-setup-confirmation",id:"legacy-team-setup-confirmation-label",children:[a("input",{"aria-disabled":e?"true":void 0,"aria-describedby":e?t:void 0,checked:d,onClick:S=>{e&&S.preventDefault()},onChange:S=>{if(e){S.currentTarget.checked=d;return}l(S.currentTarget.checked?s:null)},type:"checkbox"}),a("span",{children:"I reviewed every access change above and approve activating this Team."})]}),r?a("p",{"aria-live":"polite",className:"legacy-team-setup-finish-progress",role:"status",children:[a("span",{"aria-hidden":"true",className:"legacy-team-setup-spinner"}),"Checking the latest Team roster and applying all reviewed changes atomically. No partial changes will be kept if this cannot finish."]}):null,a("button",{"aria-describedby":p||void 0,"aria-disabled":u?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{u||i(n)},type:"button",children:r?"Finishing Team setup…":"Finish Team setup"})]})}function mM(e){let t=null;return async n=>{try{const r=await hM(n,e,()=>t,i=>{t=i});return{status:"success",generation:n.generation,id:n.id,kind:n.kind,view:r}}catch(r){let i,o;try{i=await gM(n,e,r)}catch(s){o=s}return{status:"failure",generation:n.generation,id:n.id,kind:n.kind,cause:r,...o?{recoveryCause:o}:{},...i?{recoveredView:i}:{}}}}}async function hM(e,t,n,r){switch(e.kind){case"load":return e.refresh?t.refreshCandidate(e.candidateRef):t.loadDetail(e.candidateRef);case"assign_device":return t.saveAssignment(e.candidateRef,e.deviceRef,e.input);case"decide_device":return t.saveDecision(e.candidateRef,e.deviceRef,e.input);case"clear_device":return t.clearDecision(e.candidateRef,e.deviceRef,e.input);case"map_project":return t.saveProjectMapping(e.candidateRef,e.projectRef,e.input);case"refresh":return t.refreshCandidate(e.candidateRef);case"finish":await t.finish(e.candidateRef,e.input);return;case"completion_refresh":{const i=n();if(i?.attemptId===e.attemptId&&i.candidateRef===e.candidateRef){await i.promise;return}const o=Promise.resolve().then(()=>t.onCompleted());r({attemptId:e.attemptId,candidateRef:e.candidateRef,promise:o});try{await o}finally{n()?.promise===o&&r(null)}return}default:throw new Error(`Unhandled Team setup effect: ${String(e)}`)}}async function gM(e,t,n){if(e.kind!=="completion_refresh"&&!(!(n instanceof wt)||!Xp(n.errorCode))&&!(e.kind==="load"&&(e.refresh||e.completionOnly||n.errorCode!=="team_setup_confirmation_stale")))return t.loadDetail(e.candidateRef)}function Xp(e){return["team_setup_roster_changed","team_setup_assignment_changed","team_setup_conflict","team_setup_confirmation_stale"].includes(e)}function Y_(e,t){return{id:e,targetId:`legacy-team-setup-step-${t}`}}function vM(e,t,n){return Q_(e,n>=0?`${t==="devices"?"legacy-team-device-row":"legacy-team-project-row"}-${n}`:`legacy-team-setup-step-${t}`)}function X_(e,t){return Q_(e,t.recovery||t.hasError?"legacy-team-setup-retry":`legacy-team-setup-step-${t.step}`)}function Q_(e,t){return{id:e,targetId:t}}var Z_="Team setup changed since it was last reviewed. Reload the latest details to continue.",ew="Team device details are temporarily unavailable. Check the coordinator connection and settings, then refresh.",yM="Team device details were unavailable, so setup was not finished and no changes were applied. Check the coordinator connection and settings, then refresh.",bM="This device's Project history is too large to finish setup here, so no changes were applied. Retry from a device with less history, or contact support.",_M="Team setup completion could not be checked. Check the coordinator connection and settings, then retry.",tw="Team setup could not be confirmed, and no local changes were applied. Retry to check whether setup completed.",wM="Another device completed this Team with different reviewed details. Retry to load the completed setup.",SM="The completed Team setup could not be verified. Retry, then check the coordinator connection and settings if the problem continues.";function CM(){return{status:"closed",generation:0}}function Qp(e,t){switch(t.type){case"open":return e.status==="open"&&Un(e)?e:RM(e.generation+1,t.candidateRef);case"close":return e.status==="open"&&Un(e)?e:{status:"closed",generation:e.generation+1};case"close_blocked":case"open_blocked":return e.status==="open"?{...e,message:t.message}:e;case"navigate":return IM(e,t.step);case"blocked_navigation":return Fc(e,t.step,t.message);case"retry":return kM(e);case"refresh":return PM(e,"refresh","Refreshing Team setup from the latest server state.");case"assign_device":return Zp(e,t,"assign_device");case"decide_device":return Zp(e,t,"decide_device");case"clear_device":return Zp(e,t,"clear_device");case"map_project":return TM(e,t);case"finish":return NM(e);case"command_started":return GM(e,t.id,n=>({...n,status:"running"}));case"effect_outcome":return EM(e,t.outcome);case"focus_applied":return e.status==="open"&&e.focus?.id===t.id?{...e,focus:null}:e;default:return t}}function RM(e,t){return ur({status:"open",generation:e,candidateRef:t,view:null,step:"devices",projectsVisitedAttemptId:null,commands:[],nextCommandId:1,errors:[],message:"",focus:null,nextFocusId:1},{kind:"load",candidateRef:t,refresh:!1,focusOnOutcome:!1})}function IM(e,t){if(e.status!=="open"||e.step==="completed"||t==="completed")return e;if(t==="projects"&&e.view?.unresolvedDeviceCount)return Fc(e,"devices","Finish the device decisions before mapping Projects.");if(t==="review"&&e.view?.unresolvedDeviceCount)return Fc(e,"devices","Finish the device decisions before reviewing access.");if(t==="review"&&e.view?.unresolvedProjectCount)return Fc(e,"projects","Finish the Project mappings before reviewing access.");const n=t==="projects"&&e.view?e.view.attemptId:e.projectsVisitedAttemptId;return{...e,step:t,projectsVisitedAttemptId:n,focus:Y_(e.nextFocusId,t),nextFocusId:e.nextFocusId+1}}function Fc(e,t,n){if(e.status!=="open"||e.step==="completed"||!e.view)return e;const r=t==="devices"?K_(e.view.devices).findIndex(i=>i.decision==="unresolved"):z_(e.view.projects).findIndex(i=>i.resolution==="unresolved");return{...e,step:t,projectsVisitedAttemptId:t==="projects"?e.view.attemptId:e.projectsVisitedAttemptId,message:n,focus:vM(e.nextFocusId,t,r),nextFocusId:e.nextFocusId+1}}function kM(e){if(e.status!=="open"||e.step==="completed"||Sa(e)||Un(e))return e;const t=Bc(e)?.retry??e.errors.find(n=>n.retry)?.retry??"load";return ur(e,{kind:"load",candidateRef:e.candidateRef,refresh:t==="refresh",completionOnly:t==="completion",focusOnOutcome:!0})}function Zp(e,t,n){if(e.status!=="open"||e.step==="completed"||!ef(e.view)||Bc(e)||Sa(e)||Un(e))return e;const r=e.view.devices.find(c=>c.deviceRef===t.deviceRef);if(!r||!(t.type==="assign_device"?r.actions.assignIdentity:t.type==="clear_device"?r.actions.clearDecision:t.decision==="included"?r.actions.include:t.decision==="excluded"?r.actions.exclude:r.actions.remove).enabled)return e;const i={candidateRef:e.candidateRef,deviceRef:t.deviceRef},o=n==="assign_device"&&t.type==="assign_device"?{kind:n,...i,input:{attemptId:e.view.attemptId,targetIdentityRef:t.targetIdentityRef,expectation:r.expectation}}:n==="clear_device"&&t.type==="clear_device"?{kind:n,...i,input:{attemptId:e.view.attemptId}}:t.type==="decide_device"?{kind:"decide_device",...i,input:t.decision==="included"&&t.targetIdentityRef?{attemptId:e.view.attemptId,decision:"included",expectedTargetIdentityRef:t.targetIdentityRef}:{attemptId:e.view.attemptId,decision:t.decision}}:null;if(!o||t.type==="decide_device"&&t.decision==="included"&&!t.targetIdentityRef)return e;const s=t.type==="assign_device"?`Saving the assignment for ${r.displayName}.`:t.type==="clear_device"?`Clearing the decision for ${r.displayName}.`:`Saving the decision for ${r.displayName}.`;return ur(Zr(e,{kind:"device",itemRef:t.deviceRef}),o,s)}function TM(e,t){if(e.status!=="open"||e.step==="completed"||!ef(e.view)||Bc(e)||Sa(e)||Un(e))return e;const n=e.view.projects.find(r=>r.projectRef===t.projectRef);return!n?.actions.map.enabled||!n.mappingChoices.some(r=>r.resolvedProjectRef===t.resolvedProjectRef)?e:ur(Zr(e,{kind:"project",itemRef:t.projectRef}),{kind:"map_project",candidateRef:e.candidateRef,projectRef:t.projectRef,input:{attemptId:e.view.attemptId,resolvedProjectRef:t.resolvedProjectRef}},`Saving the mapping for ${n.displayName}.`)}function PM(e,t,n){return e.status!=="open"||e.step==="completed"||!e.view?.actions.refresh.enabled||Sa(e)||Un(e)?e:ur(Zr(e,{kind:"global"}),{kind:t,candidateRef:e.candidateRef},n)}function NM(e){return e.status!=="open"||e.step==="completed"||e.view?.state!=="ready_to_finish"||e.commands.length||e.errors.length>0?e:ur(Zr(e,{kind:"global"}),{kind:"finish",candidateRef:e.candidateRef,attemptId:e.view.attemptId,input:{attemptId:e.view.attemptId,finishDigest:e.view.finishDigest,confirmedAccessDeltaDigest:e.view.accessDeltaDigest,confirmedViewerAccessDeltaDigest:e.view.viewerAccessDeltaDigest}},"Finishing Team setup.")}function ur(e,t,n=e.message){const r=`${e.generation}:${e.nextCommandId}`;return{...e,commands:[...e.commands,{...t,generation:e.generation,id:r,status:"pending"}],nextCommandId:e.nextCommandId+1,message:n}}function EM(e,t){if(e.status!=="open"||e.generation!==t.generation)return e;const n=e.commands.find(i=>i.id===t.id);if(!n)return e;const r={...e,commands:e.commands.filter(i=>i.id!==t.id)};return n.kind==="load"&&n.completionOnly&&t.status==="success"&&t.view?.state!=="completed"?nw(r,n,{status:"failure",generation:t.generation,id:t.id,kind:n.kind,cause:new wt(409,"team_setup_confirmation_stale")}):t.status==="failure"?nw(r,n,t):n.kind==="completion_refresh"?{...r,message:"Team setup complete. Sharing and Projects are up to date."}:n.kind==="finish"?xM(r,n.attemptId):t.view?rw({...UM(r,n),message:AM(n,e.view)},t.view,n.kind==="load"&&n.focusOnOutcome):r}function AM(e,t){if(e.kind==="refresh")return"Team setup refreshed.";if(e.kind==="load")return"";if("deviceRef"in e){const n=t?.devices.find(r=>r.deviceRef===e.deviceRef)?.displayName;return n?`${n} saved.`:"Device saved."}if("projectRef"in e){const n=t?.projects.find(r=>r.projectRef===e.projectRef)?.displayName;return n?`${n} saved.`:"Project mapping saved."}return""}function nw(e,t,n){if(t.kind==="completion_refresh")return{...e,message:"Team setup complete. Sharing or Projects could not be refreshed; use that view's Refresh control."};const r=n.recoveredView?rw(e,n.recoveredView,!1):e;if(n.recoveredView?.state==="completed")return r;const i=DM(t,n.cause,n.recoveryCause),o={...r,errors:[...Zr(r,i.scope).errors,i],message:""};return t.kind!=="load"||!t.focusOnOutcome?o:{...o,focus:X_(o.nextFocusId,{hasError:!0,recovery:o.view?.state==="unavailable",step:o.step}),nextFocusId:o.nextFocusId+1}}function rw(e,t,n){const r=BM(t,e.projectsVisitedAttemptId===t.attemptId),i=r==="projects"?t.attemptId:e.projectsVisitedAttemptId,o=t.state==="unavailable"?[{scope:{kind:"global"},message:qM(t.unavailableReason),retry:"refresh"}]:t.state==="completed"?[]:e.errors.filter(l=>{if(l.scope.kind==="device"){const d=l.scope.itemRef;return t.devices.some(u=>u.deviceRef===d)}if(l.scope.kind==="project"){const d=l.scope.itemRef;return t.projects.some(u=>u.projectRef===d)}return!1});let s={...e,view:t,step:r,projectsVisitedAttemptId:i,errors:o,message:t.state==="completed"?"Team setup complete. Sharing and Projects are refreshing.":e.message};const c=o.some(l=>l.scope.kind==="global"||l.scope.kind==="load");return(n||r!==e.step)&&(s={...s,focus:X_(s.nextFocusId,{hasError:c,recovery:t.state==="unavailable",step:r}),nextFocusId:s.nextFocusId+1}),t.state==="completed"&&!sw(s,t.attemptId)&&(s=ur(s,{kind:"completion_refresh",candidateRef:s.candidateRef,attemptId:t.attemptId})),s}function xM(e,t){let n={...e,step:"completed",message:"Team setup complete. Sharing and Projects are refreshing.",focus:Y_(e.nextFocusId,"completed"),nextFocusId:e.nextFocusId+1};return sw(n,t)||(n=ur(n,{kind:"completion_refresh",candidateRef:n.candidateRef,attemptId:t})),n}function DM(e,t,n){const r=t instanceof wt&&Xp(t.errorCode),i=t instanceof wt&&t.errorCode==="team_setup_roster_unavailable",{completionCode:o,message:s,terminalRecoveryCode:c}=jM({command:e,cause:t,recoveryCause:n,changed:r,rosterUnavailable:i});return{scope:LM(e,{globalError:r||i||o!==null}),message:s,retry:$M(e,t,n,{changed:r,rosterUnavailable:i,terminalRecovery:c!==null})}}function LM(e,t){return t.globalError?{kind:"global"}:e.kind==="assign_device"||e.kind==="decide_device"||e.kind==="clear_device"?{kind:"device",itemRef:e.deviceRef}:e.kind==="map_project"?{kind:"project",itemRef:e.projectRef}:e.kind==="load"?{kind:"load"}:{kind:"global"}}function $M(e,t,n,r){return t instanceof wt&&t.errorCode==="team_setup_confirmation_stale"||n instanceof wt&&n.errorCode==="team_setup_confirmation_stale"?e.kind==="load"&&e.refresh?"completion":"refresh":e.kind==="load"&&e.completionOnly?OM(t):r.terminalRecovery?"load":r.changed||r.rosterUnavailable||e.kind==="refresh"||e.kind==="load"&&e.refresh?"refresh":"load"}function OM(e){return e instanceof wt&&qc(e.errorCode)!==null?"completion":"refresh"}function jM(e){const{command:t,cause:n,recoveryCause:r,changed:i,rosterUnavailable:o}=e,s=n instanceof wt?qc(n.errorCode):null,c=FM(r instanceof wt?qc(r.errorCode):null),l=c??s,d=l==="team_setup_completion_unavailable"&&t.kind==="finish"?MM(n):ow(l);if(c)return{completionCode:l,message:d??iw(t.kind),terminalRecoveryCode:c};if(i)return{completionCode:l,message:Z_,terminalRecoveryCode:c};if(o){let u=ew;return t.kind==="finish"&&(u=n instanceof wt&&n.reason==="local_candidate_scan_budget_exceeded"?bM:yM),{completionCode:l,message:u,terminalRecoveryCode:c}}return{completionCode:l,message:d??iw(t.kind),terminalRecoveryCode:c}}function MM(e){return e instanceof wt&&e.reason==="coordinator_route_missing"?`${tw} The coordinator may be running an older version.`:tw}function FM(e){return e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function iw(e){switch(e){case"load":return"Team setup details are temporarily unavailable. Retry to load the latest details.";case"assign_device":case"decide_device":case"clear_device":return"This device change could not be saved. Reload the latest details before trying again.";case"map_project":return"This Project mapping could not be saved. Reload the latest details before trying again.";case"refresh":return"Team setup could not be refreshed. Retry to load the latest server details.";case"finish":return"Team setup could not be finished. Reload the latest details before trying again.";case"completion_refresh":return"Team setup completed, but dependent views could not be refreshed.";default:return e}}function BM(e,t){return e.state==="completed"?"completed":e.unresolvedDeviceCount>0?"devices":!t&&e.projects.length>0||e.unresolvedProjectCount>0?"projects":"review"}function ef(e){return e?.state==="reviewing"||e?.state==="ready_to_finish"}function Un(e){return e.commands.some(t=>t.kind==="load"&&t.refresh||["refresh","assign_device","decide_device","clear_device","map_project","finish"].includes(t.kind))}function Sa(e){return e.commands.some(t=>["load","refresh","finish"].includes(t.kind))}function Bc(e){return e.errors.find(t=>t.scope.kind==="global"||t.scope.kind==="load")??null}function qM(e){if(Xp(e))return Z_;if(e==="team_setup_roster_unavailable")return ew;const t=ow(qc(e));return t||(e==="team_setup_incomplete"?"Team setup needs refreshed server details before review can continue.":"Team setup details are temporarily unavailable. Refresh to load the latest server state.")}function qc(e){return e==="team_setup_completion_unavailable"||e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function ow(e){return e==="team_setup_completion_unavailable"?_M:e==="team_setup_completion_conflict"?wM:e==="team_setup_completion_invalid"?SM:null}function aw(e){return e.kind==="global"||e.kind==="load"}function Zr(e,t){const n=aw(t);return{...e,errors:e.errors.filter(r=>n?!aw(r.scope):r.scope.kind!==t.kind?!0:!("itemRef"in t)||!("itemRef"in r.scope)?!1:r.scope.itemRef!==t.itemRef)}}function UM(e,t){return t.kind==="assign_device"||t.kind==="decide_device"||t.kind==="clear_device"?Zr(e,{kind:"device",itemRef:t.deviceRef}):t.kind==="map_project"?Zr(e,{kind:"project",itemRef:t.projectRef}):{...e,errors:[]}}function GM(e,t,n){return e.status==="open"?{...e,commands:e.commands.map(r=>r.id===t?n(r):r)}:e}function sw(e,t){return e.commands.some(n=>n.kind==="completion_refresh"&&n.attemptId===t)}var HM={role:"list"},VM={role:"listitem"};function KM(e){const t=e.session,n=t.view,r=Bc(t),i=t.commands.some(_=>_.kind==="load"),o=Sa(t)||Un(t),s=t.commands.some(_=>_.kind==="finish"),c=n?.state==="unavailable"||r?.retry==="refresh",l=r!=null&&(!n||c),d=!ef(n)||o||!!r,u=[r?"legacy-team-setup-error":null,o?"legacy-team-setup-operation-status":null,n?.state==="unavailable"?"legacy-team-setup-refresh":null].filter(Boolean).join(" ")||void 0,p=n?`Set up ${n.candidate.displayName}`:"Set up Team",f=t.errors.filter(_=>_.scope.kind==="device"||_.scope.kind==="project"),m=f.length>0,v=f.some(_=>_.retry==="refresh"),g=new Set(f.flatMap(_=>_.scope.kind==="device"?[_.scope.itemRef]:[])),h=new Set(f.flatMap(_=>_.scope.kind==="project"?[_.scope.itemRef]:[])),b=new Set(t.commands.flatMap(_=>"deviceRef"in _?[_.deviceRef]:[])),w=new Set(t.commands.flatMap(_=>"projectRef"in _?[_.projectRef]:[]));return a(Qn,{ariaDescribedby:"legacy-team-setup-description",ariaLabelledby:"legacy-team-setup-title",contentClassName:"modal legacy-team-setup-dialog",contentId:"legacyTeamSetupDialog",onCloseAutoFocus:e.onCloseAutoFocus,onOpenAutoFocus:e.onOpenAutoFocus,onOpenChange:_=>{_||e.onClose()},open:!0,overlayClassName:"modal-backdrop",overlayId:"legacyTeamSetupDialogBackdrop",children:a("div",{"aria-busy":o?"true":"false",className:"modal-card legacy-team-setup-card",children:[a("div",{className:"modal-header",children:[a("div",{id:"legacy-team-setup-title",tabIndex:-1,children:a(Dg,{children:p})}),a(kr,{ariaDisabled:o,ariaLabel:`Close ${p}`,onClick:e.onClose})]}),a("div",{className:"modal-body legacy-team-setup-body",children:[a("p",{className:"small",id:"legacy-team-setup-description",children:"Review device ownership and Project access before this Team can be used for sharing."}),i&&!n?a("p",{role:"status",children:"Loading the latest Team setup details…"}):null,r?a("div",{className:"legacy-team-setup-error legacy-team-setup-recovery",id:"legacy-team-setup-global-error",children:[l?a("strong",{children:"Current setup details are unavailable"}):null,a("p",{"aria-live":"assertive",id:"legacy-team-setup-error",role:"alert",children:r.message}),a("button",{"aria-busy":o?"true":void 0,"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-retry",onClick:()=>{o||e.onRetry()},type:"button",children:i?r.retry==="refresh"?"Refreshing…":"Retrying…":r.retry==="refresh"?"Retry loading current setup":"Retry"})]}):null,m?a("div",{className:"legacy-team-setup-error",id:"legacy-team-setup-item-errors",children:[f.map(_=>a("p",{"aria-live":"assertive",id:"itemRef"in _.scope?Wp(_.scope.kind,_.scope.itemRef):void 0,role:"alert",children:_.message},"itemRef"in _.scope?`${_.scope.kind}:${_.scope.itemRef}`:_.scope.kind)),a("button",{"aria-busy":o?"true":void 0,"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-item-retry",onClick:()=>{o||e.onRetry()},type:"button",children:i?v?"Refreshing…":"Retrying…":v?"Refresh Team setup":"Retry"})]}):null,n?a(z,{children:[t.step!=="completed"&&!l?a(zM,{onNavigate:e.onNavigate,step:t.step,unresolvedDeviceCount:n.unresolvedDeviceCount,unresolvedProjectCount:n.unresolvedProjectCount}):null,i?a("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-refresh-status",role:"status",children:"Refreshing Team setup details…"}):null,a("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-operation-status",role:"status",children:t.message}),l?null:t.step==="devices"?a(cM,{blocked:d,blockedDescriptionId:u,blockedDeviceRefs:g,busyDeviceRefs:b,detail:n,onAssign:e.onAssign,onClear:e.onClear,onDecision:e.onDecide}):t.step==="projects"?a(uM,{blocked:d,blockedDescriptionId:u,blockedProjectRefs:h,busyProjectRefs:w,detail:n,onContinue:()=>e.onNavigate("review"),onMap:e.onMap}):t.step==="review"&&n.state==="ready_to_finish"?a(fM,{blocked:d||m,blockedDescriptionId:m?"legacy-team-setup-item-errors":u,detail:n,finishing:s,onFinish:e.onFinish}):a(WM,{busy:o,canFinish:n.state==="ready_to_finish",onRefresh:e.onRefresh,recoveryRequired:c,step:t.step})]}):null]}),a("div",{className:"modal-footer legacy-team-setup-actions",children:a("button",{"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:e.onClose,type:"button",children:"Close"})})]})})}function zM(e){const t=e.unresolvedDeviceCount>0,n=e.unresolvedProjectCount>0;return a(z,{children:[a("ol",{...HM,"aria-label":"Team setup steps",className:"legacy-team-setup-steps",children:[{label:"Devices",step:"devices"},{label:"Projects",step:"projects"},{label:"Review",step:"review"}].map((i,o)=>{const s=i.step==="projects"?t:i.step==="review"?t||n:!1,c=s?t?"legacy-team-setup-block-devices":"legacy-team-setup-block-projects":void 0;return y("li",{...VM,className:"legacy-team-setup-step",key:i.step},a("span",{"aria-hidden":"true",className:"legacy-team-setup-step-number",children:o+1}),a("button",{"aria-current":e.step===i.step?"step":void 0,"aria-describedby":c,"aria-disabled":s?"true":void 0,"aria-label":`Step ${o+1}: ${i.label}`,className:"settings-button legacy-team-setup-target",onClick:()=>e.onNavigate(i.step),type:"button",children:i.label}))})}),t?a("p",{className:"small",id:"legacy-team-setup-block-devices",children:"Finish the device decisions before mapping Projects or reviewing access."}):null,n?a("p",{className:"small",id:"legacy-team-setup-block-projects",children:"Finish the Project mappings before reviewing access."}):null]})}function WM(e){return e.step==="completed"?a("section",{"aria-labelledby":"legacy-team-setup-step-completed",children:[a("h3",{id:"legacy-team-setup-step-completed",tabIndex:-1,children:"Team setup complete"}),a("p",{children:"This Team is ready for Project sharing."})]}):e.step!=="review"?null:a("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[a("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),a("p",{children:e.canFinish?"The server has confirmed that this Team is ready for final review.":"Final review is waiting for the latest setup details."}),a("p",{className:"small",children:"Next setup action: review the access summary before finishing."}),!e.canFinish&&!e.recoveryRequired?a("button",{"aria-busy":e.busy?"true":void 0,"aria-disabled":e.busy?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{e.busy||e.onRefresh()},type:"button",children:"Refresh Team setup"}):null]})}var JM={clearDecision:fR,finish:gR,loadDetail:dR,onCompleted:()=>{},refreshCandidate:hR,saveAssignment:uR,saveDecision:pR,saveProjectMapping:mR},tf="codemem:open-legacy-team-setup";function cw(e){if(!e)return!1;const t={candidateRef:e,handled:!1,returnFocus:document.activeElement instanceof HTMLElement?document.activeElement:null};return window.dispatchEvent(new CustomEvent(tf,{detail:t})),t.handled}function YM(e){if(!e?.isConnected||e.tabIndex<0||e.matches(":disabled")||e.closest('[hidden], [inert], [aria-hidden="true"]'))return!1;for(let t=e;t;t=t.parentElement){const n=window.getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden"||n.visibility==="collapse")return!1}return!0}function XM({dependencies:e}){const[t,n]=x(CM),r=B(null),i=ke(()=>mM(e),[e]),o=l=>{n(d=>Qp(d,l))};return It(()=>{const l=d=>{const u=d;u.detail.handled=!0,r.current=u.detail.returnFocus,n(p=>p.status==="open"&&Un(p)?Qp(p,{type:"open_blocked",message:"Wait for the current Team setup change to finish before opening another Team."}):Qp(p,{type:"open",candidateRef:u.detail.candidateRef}))};return window.addEventListener(tf,l),()=>{window.removeEventListener(tf,l)}},[]),V(()=>{if(t.status==="open")for(const l of t.commands.filter(d=>d.status==="pending"))o({type:"command_started",id:l.id}),i(l).then(d=>o({type:"effect_outcome",outcome:d}))},[i,t]),V(()=>{if(t.status!=="open"||!t.focus)return;const l=document.getElementById(t.focus.targetId)??document.getElementById("legacy-team-setup-title");l&&(l.focus(),o({type:"focus_applied",id:t.focus.id}))},[t]),t.status==="closed"?null:a(KM,{session:t,onAssign:(l,d)=>o({type:"assign_device",deviceRef:l.deviceRef,targetIdentityRef:d}),onClear:l=>o({type:"clear_device",deviceRef:l.deviceRef}),onClose:()=>{if(Un(t)){o({type:"close_blocked",message:"Team setup will stay open while this change saves. Close it after saving finishes."});return}o({type:"close"})},onCloseAutoFocus:l=>ZM(l,r),onDecide:(l,d,u)=>{if(d==="included"&&!u){o({type:"open_blocked",message:`Save a person assignment before including ${l.displayName}.`});return}o({type:"decide_device",deviceRef:l.deviceRef,decision:d,...u?{targetIdentityRef:u}:{}})},onFinish:()=>o({type:"finish"}),onMap:(l,d)=>o({type:"map_project",projectRef:l.projectRef,resolvedProjectRef:d}),onNavigate:l=>o({type:"navigate",step:l}),onOpenAutoFocus:QM,onRefresh:()=>o({type:"refresh"}),onRetry:()=>o({type:"retry"})})}var QM=e=>{const t=document.getElementById("legacy-team-setup-title");t&&(e.preventDefault(),t.focus())};function ZM(e,t){e.preventDefault();const n=document.querySelector('.tab-btn[aria-current="page"]');(YM(t.current)?t.current:n)?.focus(),t.current=null}function e1(e,t={}){const n={...JM,...t};Ue(a(XM,{dependencies:n}),e)}var Ca=new WeakMap;function pr(e,t=""){const n=document.createElement("p");return t&&(n.className=t),n.textContent=e,n}function lw(e,t){const n=document.createElement("h3");return n.className="recipient-policy-review-heading",n.textContent=`${e} (${t.toLocaleString()})`,n}function t1(e){const t=document.createElement("article");t.className="project-inventory-row recipient-policy-review-item";const n=document.createElement("h4");return n.className="project-inventory-title",n.textContent=e.finding,t.append(n,pr(e.reason,"project-inventory-meta")),t}function n1(e){const t=document.createElement("section");t.className="recipient-policy-review-section recipient-policy-review-decisions",t.append(lw("Review findings",e.reviewItems.length),pr("Access has not changed. These findings are informational because this view has no decision controls. You may use the existing sharing controls below to change access, but those changes do not record a review decision.","section-meta"));const n=document.createElement("div");n.className="project-inventory-list recipient-policy-review-list";for(const r of e.reviewItems)n.appendChild(t1(r));return t.appendChild(n),t}function r1(e,t){const n=document.createElement("section");n.className="recipient-policy-review-section recipient-policy-review-blocked",n.append(lw("Blocked source repairs",e.blockedItems.length),pr("Access has not changed. Action is required before Codemem can safely interpret these records. Next step: repair each source record below.","section-meta project-attention-note"));const r=document.createElement("div");r.className="project-inventory-list recipient-policy-review-list";for(const i of e.blockedItems)r.appendChild(i1(i,t));return n.appendChild(r),n}function i1(e,t){const n=document.createElement("article");n.className="project-inventory-row recipient-policy-blocked-item";const r=document.createElement("div");r.className="project-inventory-row-header";const i=document.createElement("h3");i.className="project-inventory-title",i.textContent=e.finding;const o=document.createElement("span");o.className="project-status-badge needs_attention",o.textContent="Blocked",r.append(i,o);const s=pr(e.repairAction,"settings-note");if(s.id=`recipient-policy-repair-help-${e.blockedItemId}`,n.append(r,pr(e.reason,"project-inventory-meta"),s,pr(`Owner: ${e.ownerLabel}`,"settings-note")),t.onRepair&&(t.isRepairAvailable?.(e.repair)??!0)){const c=document.createElement("button");c.className="settings-button",c.type="button",c.textContent=e.repair.label,c.setAttribute("aria-describedby",s.id),c.addEventListener("click",async()=>{c.disabled=!0;try{await t.onRepair?.(e.repair)}finally{c.disabled=!1}}),n.appendChild(c)}else n.appendChild(pr("Open Projects to repair this item.","settings-note"));return n}function o1(e,t,n={}){const r=t.blockedItems.map(l=>n.onRepair&&(n.isRepairAvailable?.(l.repair)??!0)?"1":"0"),i={blockedItems:t.blockedItems.map(l=>({blockedItemId:l.blockedItemId,finding:l.finding,ownerLabel:l.ownerLabel,reason:l.reason,repair:l.repair,repairAction:l.repairAction})),reviewItems:t.reviewItems.map(l=>({finding:l.finding,reason:l.reason}))},o=`review:${r.join("")}:${JSON.stringify(i)}`;if(Ca.get(e)===o)return;if(t.reviewItems.length===0&&t.blockedItems.length===0){e.replaceChildren(),e.hidden=!0,Ca.set(e,o);return}e.hidden=!1;const s=document.createElement("section");s.className="card recipient-policy-review",s.setAttribute("aria-labelledby","recipientPolicyReviewTitle");const c=document.createElement("h2");c.id="recipientPolicyReviewTitle",c.textContent="Sharing review",s.appendChild(c),t.reviewItems.length>0&&s.appendChild(n1(t)),t.blockedItems.length>0&&s.appendChild(r1(t,n)),e.replaceChildren(s),Ca.set(e,o)}function a1(e,t){const n=t instanceof Error?t.message:"Unable to load recipient migration review.",r=`error:${n}`;if(Ca.get(e)===r)return;e.hidden=!1;const i=document.createElement("section");i.className="card recipient-policy-review";const o=document.createElement("h2");o.textContent="Recipient migration review";const s=pr(n,"settings-note project-attention-note");s.setAttribute("role","status"),i.append(o,s),e.replaceChildren(i),Ca.set(e,r)}var dw=[["","All projects"],["needs_attention","Needs review"],["suggested","Has suggestion"],["local_only","Stays on this device"],["received","Received from peers"],["explicitly_mapped","Already assigned"],["legacy_review","Older shared data"],["unmapped","Missing project identity"]],bt=null,Ut=0,Uc=250,s1=100,nf=[],Gc=new Set,Hc=new Set,Vc=new Map,Kc=new Map,ei=new Map,Ra=new Map,zc=!1,Ia=new Map,ka=!1,fr=!1,ro=0,uw=null,Gn=0,Ta=0,io=null,Pa=null,Gt=new Set,pw=new WeakMap,Wc={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},oo=Wc,mr=!1,rf;function of(e=!1){if(!e&&Pa)return Pa;const t=Tm().then(n=>({ok:!0,summary:n})).catch(()=>({ok:!1}));return Pa=t,t.then(()=>{Pa===t&&(Pa=null)}),t}function $e(e){return document.getElementById(e)}function c1(e){return dw.find(([t])=>t===e)?.[1]??e.replaceAll("_"," ")}function l1(e){switch(e){case"exact_mapping":return"assigned to a Space";case"pattern_mapping":return"assigned by matching rule";case"explicit_override":return"manually assigned";default:return"stays on this device"}}function vn(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function Jc(e){return e.identity_source!=="unmapped"&&!vn(e)}function d1(e){const t=Ia.get(e.workspace_identity);(!t||vn(t)&&!vn(e))&&Ia.set(e.workspace_identity,e)}function af(e){return vn(e)?"Received from peers":Xc(e.resolved_scope_id)}function u1(e){return vn(e)?"source-owned project":l1(e.resolution_reason)}function p1(e){const t=e.person.display_name;switch(e.lifecycle.state){case"waiting_for_acceptance":return`Invitation sent to ${t}`;case"active":return`Shared with ${t}`;case"waiting_for_device":return`Sharing with ${t}`;case"needs_attention":return`Sharing with ${t} needs attention`;case"revoking":return`Removing sharing with ${t}`;case"revoked":return`Previously shared with ${t}`;case"cancelled":return`Invitation to ${t} cancelled`;default:return`Setting up sharing with ${t}`}}function fw(e){if(!e)return"No recent sessions";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function mw(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function ti(){const e=Gt.size,t=$e("projectsShareSelected");t&&(t.textContent=e===0?"Share selected":`Share selected (${e})`,t.disabled=e===0||!fr||!mr,t.classList.add("project-selection-target"));const n=$e("projectsSelectionStatus");n&&(n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.textContent=`${e.toLocaleString()} Project${e===1?"":"s"} selected.`);for(const r of document.querySelectorAll(".project-selection-checkbox")){const i=pw.get(r)??[],o=i.filter(s=>Gt.has(s)).length;r.checked=i.length>0&&o===i.length,r.indeterminate=o>0&&o<i.length}for(const r of document.querySelectorAll(".project-recipient-action"))r.disabled=!fr||!mr}function f1(e){const t=e.every(n=>Gt.has(n));for(const n of e)t?Gt.delete(n):Gt.add(n);ti()}function hw(e,t){const n=mw(e),r=document.createElement("label");r.className="project-selection-control project-selection-target";const i=document.createElement("input");i.className="project-selection-checkbox",i.dataset.projectFocusKey=`select:${n.join("|")}`,i.type="checkbox",i.setAttribute("aria-label",t),pw.set(i,n),i.addEventListener("change",()=>f1(n));const o=document.createElement("span");return o.className="sr-only",o.textContent=t,r.append(i,o),r}function m1(e){if(!mr)return[];const t=new Set(e),n=new Map(oo.teams.filter(o=>o.status==="active").map(o=>[o.teamId,o.displayName])),r=new Map(oo.identities.filter(o=>o.status==="active"||o.status==="pending").map(o=>[o.identityId,o.displayName])),i=new Map;for(const o of oo.projectRecipients)if(!(o.status!=="active"||!t.has(o.canonicalProjectIdentity)))if(o.recipientKind==="team"){const s=n.get(o.teamId);s&&i.set(`team:${o.teamId}`,{key:`team:${o.teamId}`,kind:"Team",displayName:s})}else{const s=r.get(o.identityId);s&&i.set(`identity:${o.identityId}`,{key:`identity:${o.identityId}`,kind:"Identity",displayName:s})}return[...i.values()].sort((o,s)=>`${o.kind}:${o.displayName}`.localeCompare(`${s.kind}:${s.displayName}`))}function gw(e){const t=document.createElement("div");t.className="project-recipient-summary";const n=m1(e),r=document.createElement("div");if(r.className="project-recipient-status",r.textContent=mr?n.length===0?"Not shared with any recipients.":e.length===1?`Shared with ${n.length.toLocaleString()} recipient${n.length===1?"":"s"}.`:`${n.length.toLocaleString()} recipient${n.length===1?"":"s"} across these Project identities.`:"Recipient access is unavailable.",t.appendChild(r),n.length>0){const i=document.createElement("ul");i.className="project-recipient-chips",i.setAttribute("aria-label","Active recipients");for(const o of n){const s=document.createElement("li");s.className=`project-recipient-chip project-recipient-chip-${o.kind.toLowerCase()}`,s.textContent=`${o.kind}: ${o.displayName}`,i.appendChild(s)}t.appendChild(i)}return t}function vw(e,t){const n=document.createElement("button");return n.className="settings-button project-recipient-action project-selection-target",n.type="button",n.disabled=!fr||!mr,e.length===1?(n.textContent="Manage recipients",n.setAttribute("aria-label",`Manage recipients for ${t}`),n.dataset.projectFocusKey=`manage:${e[0]}`,n.addEventListener("click",()=>{xo({mode:"project-manage",projectId:e[0]})})):(n.textContent="Share selected",n.setAttribute("aria-label",`Share selected identities for ${t}`),n.dataset.projectFocusKey=`share:${e.join("|")}`,n.addEventListener("click",()=>{for(const r of e)Gt.add(r);ti(),xo({mode:"project-add",projectIds:[...e].sort()})})),n}function h1(e){return e.git_remote?e.git_remote:e.cwd?e.cwd:e.workspace_identity}function sf(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function cf(e){return e.project||e.display_project||"Unnamed Project"}function yw(e){const t=String(e||"").trim();return t?C.lastProjectCoordinatorAdminGroups.find(n=>String(n.group_id||"").trim()===t&&!n.archived_at)?.display_name||"Team details unavailable":null}function g1(){return new Set(C.lastProjectCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function v1(e){return!ka||e.authority_type!=="coordinator"||!e.group_id?!1:!g1().has(String(e.group_id).trim())}function Yc(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function bw(){zc&&(zc=!1,bt?.())}async function y1(){let e;try{const t=await Rl();e=t&&typeof t=="object"?t:null}catch{C.lastProjectCoordinatorAdminGroups=[],ka=!1;return}if(e?.readiness!=="ready"||!e.has_admin_secret){C.lastProjectCoordinatorAdminGroups=[],ka=!1;return}try{const t=await pm(!1);C.lastProjectCoordinatorAdminGroups=Array.isArray(t?.items)?t.items:[],ka=!0}catch{C.lastProjectCoordinatorAdminGroups=[],ka=!1}}function b1(e){return e.kind==="team_default"}function lf(e){const t=e.label||"Untitled Space";return b1(e)?`${t} (default)`:t}function _1(e,t){const n=lf(e);return t.some(r=>r.scope_id!==e.scope_id&&lf(r)===n)?`${n} · Space ID ${e.scope_id}`:n}function w1(e){const t=yw(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Space":`${e.authority_type||"Other"} Space`}function S1(e){return e?nf.find(t=>t.scope_id===e)??null:null}function Xc(e){const t=S1(e);return e?t?`${lf(t)} · ${w1(t)}`:"Unknown Space":"—"}function df(){return nf.filter(e=>e.scope_id!=="legacy-shared-review"&&!v1(e))}function C1(e){return df().some(t=>t.scope_id===e)}function _w(...e){for(const t of e)if(t&&C1(t))return t;return e.find(t=>!!t)??""}function R1(e){const t=yw(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function I1(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function k1(){const e=new Map;for(const t of df()){const n=I1(t),r=R1(t),i=e.get(n)??{label:r,scopes:[]};e.set(n,{label:i.label,scopes:[...i.scopes,t]})}return[...e.values()]}function ww(e){for(const t of k1()){const n=document.createElement("optgroup");n.label=t.label;for(const r of t.scopes){const i=document.createElement("option");i.value=r.scope_id,i.textContent=_1(r,t.scopes),n.appendChild(i)}e.appendChild(n)}}function T1(e){switch(e.code){case"unknown_project_local_only":return"Current behavior";case"basename_collision_review":return"Name collision";case"scope_reassignment_old_copies":return"Previous copies";case"broad_org_domain_pattern":case"home_directory_org_domain_pattern":return"Broad mapping";default:return"Review item"}}async function uf(e,t,n=[]){try{await PR({...e.mapping_id&&e.resolution_reason==="exact_mapping"?{id:e.mapping_id}:{},...n.length>0?{confirmed_guardrail_tokens:n}:{},project_pattern:e.display_project,scope_id:t,workspace_identity:e.workspace_identity}),ei.delete(e.workspace_identity),Vc.delete(e.workspace_identity),Z("Project Space assignment updated. Device access grants are unchanged."),bt?.()}catch(r){if(r instanceof za){ei.set(e.workspace_identity,{requiredGuardrailTokens:r.requiredGuardrailTokens,scopeId:t,warnings:r.guardrailWarnings}),bt?.();return}Z(r instanceof Error?r.message:"Unable to update project Space.","warning")}}async function P1(e,t){const n=e.filter(Jc);if(n.length!==0)try{await NR({mappings:n.map(r=>({...r.mapping_id&&r.resolution_reason==="exact_mapping"?{id:r.mapping_id}:{},project_pattern:r.display_project,scope_id:t,workspace_identity:r.workspace_identity}))}),Z(`Updated ${n.length} project identit${n.length===1?"y":"ies"}. Device access grants are unchanged.`),Kc.delete(sf(n[0])),bt?.()}catch(r){Z(r instanceof za?"One or more identities in this group need review before bulk assignment. Expand the group and save those identities directly.":r instanceof Error?r.message:"Unable to update project Spaces.","warning")}}async function N1(e){if(e.mapping_id!=null)try{await ER(e.mapping_id),ei.delete(e.workspace_identity),Vc.delete(e.workspace_identity),Z("Project Space assignment removed. The next fallback now applies."),bt?.()}catch(t){Z(t instanceof Error?t.message:"Unable to remove project Space assignment.","warning")}}async function Sw(e,t=!1){try{const n=Ra.get(e.workspace_identity),r=await xR({...t&&n?{confirmation_token:n.confirmationToken}:{},confirmed:t,workspace_identity:e.workspace_identity});Ra.delete(e.workspace_identity),Z(`Forgot ${r.forgotten_memory_count.toLocaleString()} local memor${r.forgotten_memory_count===1?"y":"ies"}. ${r.peer_owned_memory_count.toLocaleString()} peer-owned memor${r.peer_owned_memory_count===1?"y was":"ies were"} left unchanged.`),bt?.()}catch(n){if(n instanceof Sm){Ra.set(e.workspace_identity,{confirmationToken:n.preview.confirmation_token,localOwnedMemoryCount:n.preview.local_owned_memory_count,peerOwnedMemoryCount:n.preview.peer_owned_memory_count}),bt?.();return}Z(n instanceof Error?n.message:"Unable to forget project memories.","warning")}}async function Cw(e){if(e.identity_source==="unmapped")return;const t=String(e.project||e.display_project||"").trim();let n=[];try{n=(await Va()).filter(i=>i&&i!==t)}catch{}const r=await rp({cancelLabel:"Cancel",confirmLabel:"Change project",description:`This will update ${e.session_count} session${e.session_count===1?"":"s"} and ${e.memory_count??0} memor${e.memory_count===1?"y":"ies"} by changing the stored project. Space assignment stays unchanged.`,initialValue:t,placeholder:"Project name",suggestions:n,title:"Change project",validate:i=>{const o=i.trim();return o?o===t?"Already assigned to this project.":null:"Enter a project name."}});if(r!=null)try{const i=await AR({project:r.trim(),workspace_identity:e.workspace_identity});Z(`Changed project to ${i.project} for ${i.moved_session_count} session${i.moved_session_count===1?"":"s"}.`),bt?.()}catch(i){Z(i instanceof Error?i.message:"Unable to change project.","warning")}}async function E1(e){const t=Ia.get(e);if(t&&!vn(t))return{offset:Ut,project:t};try{let n=0,r=0;for(;;){const i=await bo({limit:Uc,offset:n,q:e});r+=1;const o=i.projects.find(c=>c.workspace_identity===e&&!vn(c));if(o)return{offset:i.offset,project:o};if(!i.has_more||i.limit<=0)return null;const s=i.offset+i.limit;if(s<=n||r>=s1)return null;n=s}}catch{return null}}function Rw(e){const t=[...document.querySelectorAll("[data-project-workspace-identity]")].find(o=>o.dataset.projectWorkspaceIdentity===e&&o.dataset.projectRepairable==="true");if(!t)return!1;const n=t.querySelector(".project-inventory-details");if(!n)return!1;const r=t.closest(".project-inventory-cluster"),i=r?.querySelector(":scope > .project-inventory-details");if(i){i.open=!0;const o=r?.dataset.projectClusterKey;o&&Hc.add(o)}return n.open=!0,Gc.add(`${t.dataset.projectRepairable}:${e}`),n.scrollIntoView?.({block:"center",behavior:"smooth"}),n.querySelector("summary")?.focus(),!0}async function A1(e){if(Yc()){Z("Finish the open Space assignment, then try Repair again.","warning");return}const t=Gn,n=$e("projectsSearch")?.value??"",r=$e("projectsStatusFilter")?.value??"",i=Ut,o=await E1(e.projectIdentity);if(Gn!==t||($e("projectsSearch")?.value??"")!==n||($e("projectsStatusFilter")?.value??"")!==r||Ut!==i)return;if(Yc()){Z("Finish the open Space assignment, then try Repair again.","warning");return}if(!o){Z("This Project is not visible in the current inventory. Refresh Projects, then try Repair again.","warning");return}const{project:s}=o;if(e.kind==="reassign_project"){if(s.identity_source==="unmapped"||s.session_count===0){Z("This Project cannot be reassigned yet because it has no local sessions with stable source evidence.","warning");return}await Cw(s);return}if(!Rw(s.workspace_identity)){const c=$e("projectsSearch"),l=c?.value??"",d=s.workspace_identity;c&&(c.value=d);const u=$e("projectsStatusFilter"),p=u?.value??"",f="";u&&(u.value=f);const m=Ut;Ut=o.offset;const v=Gn;if(await Na(),!Rw(s.workspace_identity)){if(Gn!==v||c&&c.value!==d||u&&u.value!==f||Ut!==o.offset)return;c&&(c.value=l),u&&(u.value=p),Ut=m,await Na(),Z("Project administration could not be opened. Refresh Projects and try again.","warning")}}}function x1(e){const t=Gn,n=(io?.catch(()=>{})??Promise.resolve()).then(async()=>{if(Gn===t)try{await A1(e)}catch(r){Z(r instanceof Error?r.message:"Unable to repair this Project.","warning")}});return io=n,n.then(()=>{io===n&&(io=null)},()=>{io===n&&(io=null)}),n}function D1(e){const t=document.createElement("div");if(t.className="project-inventory-actions",Jc(e)&&e.memory_count!=null&&e.guardrail_warnings.every(m=>!m.requires_confirmation)){const m=document.createElement("button");m.className="settings-button",m.type="button",m.textContent="Share",m.disabled=!fr,fr||(m.title="The complete project list is unavailable."),m.addEventListener("click",()=>_s([e.workspace_identity])),t.appendChild(m)}if(vn(e)){const m=document.createElement("div");return m.className="settings-note",m.textContent="This project was received from a peer. Change its project or Space on the source device; this node keeps the received identity read-only.",t.appendChild(m),t}if(e.identity_source==="unmapped"){const m=document.createElement("div");return m.className="settings-note",m.textContent="This project is missing a stable path, git remote, or workspace id. It stays Local only until it has a stable identity.",t.appendChild(m),t}const n=document.createElement("label");n.className="sr-only";const r=`project-domain-${e.workspace_identity.replace(/[^a-z0-9_-]/gi,"-")}`;n.htmlFor=r,n.textContent=`Space for ${e.display_project}`;const i=document.createElement("select");i.id=r,i.className="project-domain-select";const o=df().some(m=>m.scope_id===e.resolved_scope_id);if(!o&&e.resolved_scope_id){const m=document.createElement("option");m.value=e.resolved_scope_id,m.textContent=`${Xc(e.resolved_scope_id)} — not assignable`,m.disabled=!0,i.appendChild(m)}ww(i),i.value=_w(Vc.get(e.workspace_identity),e.suggested_scope_id,e.resolved_scope_id);const s=document.createElement("button");s.className="settings-button",s.type="button",s.textContent=e.suggested_scope_id&&i.value===e.suggested_scope_id?"Confirm suggestion":"Save Space",s.disabled=!i.value||i.value===e.resolved_scope_id&&!o,s.addEventListener("click",()=>{uf(e,i.value)}),i.addEventListener("change",()=>{Vc.set(e.workspace_identity,i.value),ei.delete(e.workspace_identity),t.querySelector(".project-space-guardrail-confirmation")?.remove(),s.textContent="Save Space",s.disabled=!i.value,bt?.()}),i.addEventListener("blur",bw);const c=document.createElement("button");c.className="settings-button",c.type="button",c.textContent="Keep local-only",c.addEventListener("click",()=>{uf(e,"local-default")});const l=document.createElement("button");l.className="settings-button",l.type="button",l.textContent="Remove mapping",l.disabled=e.mapping_id==null||e.resolution_reason!=="exact_mapping",l.addEventListener("click",()=>{N1(e)});const d=document.createElement("button");d.className="settings-button",d.type="button",d.textContent="Change project…",d.disabled=e.session_count===0,d.disabled&&(d.title="No sessions are available to reassign for this saved mapping."),d.addEventListener("click",()=>{Cw(e)});const u=document.createElement("button");u.className="settings-button danger",u.type="button",u.textContent="Forget local memories…",u.disabled=(e.memory_count??0)===0,u.addEventListener("click",()=>{Sw(e)}),t.append(n,i,s,c,l,d,u);const p=ei.get(e.workspace_identity);if(p){const m=document.createElement("div");m.className="settings-note project-guardrail-confirmation project-space-guardrail-confirmation",m.setAttribute("role","alert");const v=document.createElement("strong");v.textContent="Confirmation required before saving this Space.";const g=document.createElement("p");g.textContent="Codemem can save this change after you acknowledge the checks below. Verify the workspace details, then confirm to complete the save.";const h=document.createElement("ul");for(const _ of p.warnings){const R=document.createElement("li"),I=document.createElement("strong");I.textContent=`${T1(_)}: `;const T=document.createElement("span");T.textContent=_.message,R.append(I,T),h.appendChild(R)}const b=document.createElement("button");b.className="settings-button",b.type="button",b.textContent="I understand, save Space",b.addEventListener("click",()=>{const _=ei.get(e.workspace_identity);!_||_.scopeId!==i.value||uf(e,_.scopeId,_.requiredGuardrailTokens)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{ei.delete(e.workspace_identity),bt?.()}),m.append(v,g,h,b,w),t.appendChild(m)}const f=Ra.get(e.workspace_identity);if(f){const m=document.createElement("div");m.className="settings-note project-guardrail-confirmation",m.setAttribute("role","alert");const v=document.createElement("strong");v.textContent="Confirm project memory cleanup.";const g=document.createElement("p");g.textContent=`${f.localOwnedMemoryCount.toLocaleString()} locally owned memor${f.localOwnedMemoryCount===1?"y":"ies"} will be forgotten. ${f.peerOwnedMemoryCount.toLocaleString()} peer-owned memor${f.peerOwnedMemoryCount===1?"y":"ies"} will be left unchanged.`;const h=document.createElement("p");h.textContent="Use this only to clean up wrongly attributed local project inventory; it forgets actual local memories on this device.";const b=document.createElement("button");b.className="settings-button danger",b.type="button",b.textContent="I understand, forget local memories",b.addEventListener("click",()=>{Sw(e,!0)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{Ra.delete(e.workspace_identity),bt?.()}),m.append(v,g,h,b,w),t.appendChild(m)}return t}function Iw(e){const t=document.createElement("article");t.className="project-inventory-row",t.dataset.projectWorkspaceIdentity=e.workspace_identity,t.dataset.projectRepairable=String(Jc(e));const n=`project-title-${e.workspace_identity.replace(/[^a-z0-9_-]/gi,"-")}`;t.setAttribute("aria-labelledby",n);const r=document.createElement("div");r.className="project-inventory-row-header",vs(e)&&r.appendChild(hw([e],`Select ${e.display_project} for recipient sharing`));const i=document.createElement("h3");i.className="project-inventory-title",i.id=n,i.textContent=e.display_project,r.appendChild(i),vs(e)&&r.appendChild(vw([e.workspace_identity],e.display_project)),t.appendChild(r);const o=document.createElement("div");o.className="project-inventory-meta",o.textContent=`${(e.memory_count??0).toLocaleString()} memories · ${e.session_count.toLocaleString()} sessions · ${fw(e.latest_session_at)}`,t.appendChild(o),t.appendChild(gw([e.workspace_identity]));const s=document.createElement("div");s.className="project-advanced-administration";const c=document.createElement("div");c.className="project-inventory-domain",c.textContent=af(e),s.appendChild(c);const l=document.createElement("div");if(l.className="project-inventory-meta",l.textContent=`${u1(e)} · ${e.identity_source} · ${fw(e.latest_session_at)}`,s.appendChild(l),e.sharing&&e.sharing.length>0){const h=document.createElement("div");h.className="settings-note project-sharing-summary";const b=document.createElement("strong");b.textContent="Project sharing";const w=document.createElement("ul");w.setAttribute("aria-label",`People sharing ${e.display_project}`);for(const _ of e.sharing){const R=document.createElement("li"),I=document.createElement("strong");I.textContent=p1(_);const T=document.createElement("span");T.textContent=` — ${_.lifecycle.label}. ${_.lifecycle.explanation}`,R.append(I,T),w.appendChild(R)}h.append(b,w),s.appendChild(h)}if(vn(e)){const h=document.createElement("div");h.className="settings-note",h.textContent="Received memories keep the source device's project and Space assignment. Local reassignment controls are disabled here to avoid split-brain sync state.",s.appendChild(h)}const d=document.createElement("div");if(d.className="project-inventory-signal mono",d.textContent=h1(e),s.appendChild(d),e.suggested_scope_id&&e.suggested_scope_id!==e.resolved_scope_id){const h=document.createElement("div");h.className="settings-note project-suggestion-note",h.textContent=e.suggestion_reason?`Suggestion: ${e.suggestion_reason}`:`Suggestion: assign this project to ${Xc(e.suggested_scope_id)}.`,s.appendChild(h)}const u=(e.guardrail_warnings??[]).filter(h=>h.severity==="warning");if(u.length>0){const h=document.createElement("div");h.className="settings-note project-attention-note",h.textContent=`Needs attention: ${u.map(b=>b.message).join(" ")}`,s.appendChild(h)}if(e.statuses.length>0){const h=document.createElement("div");h.className="project-inventory-badges";for(const b of e.statuses){const w=document.createElement("span");w.className=`project-status-badge ${b}`,w.textContent=c1(b),h.appendChild(w)}s.appendChild(h)}const p=document.createElement("details");p.className="project-inventory-details";const f=`${t.dataset.projectRepairable}:${e.workspace_identity}`;p.open=Gc.has(f),p.addEventListener("toggle",()=>{p.open?Gc.add(f):Gc.delete(f)});const m=document.createElement("summary");m.dataset.projectFocusKey=`admin:${t.dataset.projectRepairable}:${e.workspace_identity}`,m.textContent=u.length>0?`Advanced Project administration — ${u.length.toLocaleString()} item${u.length===1?"":"s"} need attention`:"Advanced Project administration",p.appendChild(m),p.appendChild(s);const v=document.createElement("dl");v.className="project-detail-grid";const g=[["Workspace identity",e.workspace_identity],["Project",e.project],["CWD",e.cwd],["Git remote",e.git_remote],["Git branch",e.git_branch],["Current Space",af(e)],["Suggested Space",e.suggested_scope_id?Xc(e.suggested_scope_id):null],["Advanced: current Space ID",e.resolved_scope_id],["Advanced: suggested Space ID",e.suggested_scope_id],["Suggestion reason",e.suggestion_reason],["Sessions",e.session_count],["Memories",e.memory_count??"count unavailable"]];for(const[h,b]of g){const w=document.createElement("dt");w.textContent=h;const _=document.createElement("dd");_.textContent=b==null||b===""?"—":String(b),v.append(w,_)}return p.appendChild(v),p.appendChild(D1(e)),t.appendChild(p),t}function L1(e){const t=[...new Set(e.map(n=>af(n)))];return t.length===1?t[0]:"Mixed Spaces"}function $1(e){if(e.length===1)return Iw(e[0]);const t=sf(e[0]),n=e.filter(vs),r=mw(n),i=document.createElement("article");i.className="project-inventory-row project-inventory-cluster",i.dataset.projectClusterKey=t;const o=cf(e[0]),s=`project-cluster-title-${t.replace(/[^a-z0-9_-]/gi,"-")}`;i.setAttribute("aria-labelledby",s);const c=document.createElement("div");c.className="project-inventory-row-header",n.length>0&&c.appendChild(hw(n,`Select all identities for ${cf(e[0])}`));const l=document.createElement("h3");l.className="project-inventory-title",l.id=s,l.textContent=o,c.appendChild(l),r.length>0&&c.appendChild(vw(r,o)),i.appendChild(c);const d=document.createElement("div");d.className="project-advanced-administration";const u=document.createElement("div");u.className="project-inventory-domain",u.textContent=L1(e),d.appendChild(u);const p=e.reduce((_,R)=>_+(R.memory_count??0),0),f=e.reduce((_,R)=>_+R.session_count,0),m=document.createElement("div");m.className="project-inventory-meta",m.textContent=`${e.length} identities · ${f.toLocaleString()} sessions · ${p.toLocaleString()} memories`,i.appendChild(m),i.appendChild(gw(r));const v=document.createElement("div");v.className="project-inventory-actions";const g=e.filter(Jc);if(g.length===0){const _=document.createElement("div");_.className="settings-note",_.textContent=e.every(vn)?"These project identities were received from peers. Change project or Space assignments on their source devices.":"These project identities cannot be bulk assigned until they have stable local identities. Expand each identity for details.",v.appendChild(_),d.appendChild(v)}else{const _=g.map(N=>({project:N,warnings:(N.guardrail_warnings??[]).filter(L=>L.requires_confirmation)})),R=_.some(({warnings:N})=>N.length>0),I=new Set(g.map(N=>N.suggested_scope_id).filter(N=>!!N)),T=new Set(g.map(N=>N.resolved_scope_id)),A=document.createElement("select");A.className="project-domain-select",A.setAttribute("aria-label",`Space for ${cf(e[0])} group`);const O=document.createElement("option");O.value="",O.textContent="Choose Space…",A.appendChild(O),ww(A),A.value=_w(Kc.get(t));const F=document.createElement("button");if(F.className="settings-button",F.type="button",F.textContent=`Save Space for ${g.length} identit${g.length===1?"y":"ies"}`,F.disabled=!A.value||R,F.addEventListener("click",()=>{P1(g,A.value)}),A.addEventListener("change",()=>{A.value?Kc.set(t,A.value):Kc.delete(t),F.disabled=!A.value||R}),A.addEventListener("blur",bw),v.append(A,F),I.size>1||T.size>1||R){const N=document.createElement("div");if(N.className="settings-note project-attention-note",N.textContent=R?"One or more identities in this group need individual review before bulk assignment.":"This group has mixed suggestions or current Spaces. Choose a Space explicitly before bulk assignment.",R){const L=document.createElement("ul");for(const{project:D,warnings:G}of _){if(G.length===0)continue;const q=document.createElement("li"),$=document.createElement("strong");$.textContent=`Blocked identity: ${D.workspace_identity}`;const E=document.createElement("span");E.textContent=` — ${G.map(S=>S.message).join(" ")}`,q.append($,E),L.appendChild(q)}N.appendChild(L)}v.appendChild(N)}d.appendChild(v)}const h=document.createElement("details");h.className="project-inventory-details",h.open=Hc.has(t),h.addEventListener("toggle",()=>{h.open?Hc.add(t):Hc.delete(t)});const b=document.createElement("summary"),w=e.reduce((_,R)=>_+(R.guardrail_warnings??[]).filter(I=>I.severity==="warning").length,0);b.textContent=w>0?`Advanced Project administration — ${w.toLocaleString()} item${w===1?"":"s"} need attention`:"Advanced Project administration",h.appendChild(b),h.appendChild(d);for(const _ of e)h.appendChild(Iw(_));return i.appendChild(h),i}function O1(e){const t=new Map;for(const n of e){const r=sf(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function kw(e){const t=$e("projectsInventoryList");if(!t)return;t.textContent="";const n=document.createElement("div");n.className="settings-note",n.textContent=e,t.appendChild(n)}function Tw(){document.getElementById("projectsInventorySkeleton")?.remove()}function Pw(e){const t=$e("projectsInventoryMeta"),n=$e("projectsInventoryList");if(!t||!n)return;const r=document.activeElement instanceof HTMLElement?document.activeElement.dataset.projectFocusKey:void 0;Tw(),Ia.clear();for(const s of e.projects)d1(s);if(n.textContent="",e.projects.length===0)kw("No projects match those filters.");else for(const s of O1(e.projects))n.appendChild($1(s));t.textContent=e.total===0?"0 project identities found":`${e.total} project identit${e.total===1?"y":"ies"} found · showing ${e.offset+1}-${Math.min(e.offset+e.projects.length,e.total)}`;const i=$e("projectsPrevPage"),o=$e("projectsNextPage");i&&(i.disabled=e.offset===0),o&&(o.disabled=!e.has_more),ti(),r&&[...n.querySelectorAll("[data-project-focus-key]")].find(s=>s.dataset.projectFocusKey===r)?.focus()}function j1(e,t){y1().then(()=>{t===ro&&(Yc()||Pw(e))})}async function M1(){const e=new Map;let t=0;for(;;){const n=await bo({limit:250,offset:t});for(const r of n.projects)e.set(r.workspace_identity,r);if(!n.has_more)break;t+=n.limit}return[...e.values()]}function Nw(e,t,n){const r=$e("recipientPolicyManagementMount");r&&qg(r,ys(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&Gt.clear(),ti(),bt?.()}})}function Ew(e,t){const n=t?.candidates??[],r=e.querySelector(":scope > .project-team-setup-entry");r?.querySelector(".project-team-setup-status")?.remove();const i=r?.contains(document.activeElement)&&document.activeElement instanceof HTMLButtonElement?document.activeElement.dataset.teamSetupCandidateRef:void 0;if(n.length===0){r?.remove(),e.hidden=e.querySelector(":scope > .project-recipient-policy-review-content")?.hidden!==!1,i&&$e("projectsSearch")?.focus();return}const o=JSON.stringify(n.map(d=>[d.candidateRef,d.displayName]));if(r?.dataset.teamSetupSignature===o){e.hidden=!1;return}r?.remove(),e.hidden=!1;const s=document.createElement("section");s.className="card project-team-setup-entry",s.dataset.teamSetupSignature=o;const c=document.createElement("h2");c.textContent="Finish setting up this Team";const l=document.createElement("p");l.className="section-meta",l.textContent="Tell Codemem who uses each device before using this Team for Project sharing.",s.append(c,l);for(const d of n){const u=document.createElement("div");u.className="project-inventory-actions";const p=document.createElement("strong");if(p.textContent=d.displayName,u.appendChild(p),rf){const f=document.createElement("button");f.setAttribute("aria-label",`Finish setting up ${d.displayName}`),f.className="settings-button",f.type="button",f.textContent="Finish setting up this Team",f.dataset.teamSetupCandidateRef=d.candidateRef,f.addEventListener("click",()=>rf?.(d.candidateRef)),u.appendChild(f)}s.appendChild(u)}if(e.appendChild(s),i){let d=!1;for(const u of s.querySelectorAll("button"))if(u.dataset.teamSetupCandidateRef===i){u.focus(),d=!0;break}d||$e("projectsSearch")?.focus()}}function Aw(e){const t=e.querySelector(":scope > .project-team-setup-entry");if(!t)return;let n=t.querySelector(".project-team-setup-status");n||(n=document.createElement("p"),n.className="section-meta project-team-setup-status",n.setAttribute("role","status"),t.appendChild(n)),n.textContent="Team setup status is temporarily unavailable. The previous Team setup status is being shown.",e.hidden=!1}function F1(e){const t=e.querySelector(":scope > .project-recipient-policy-review-content");if(t)return t;const n=document.createElement("div");return n.className="project-recipient-policy-review-content",e.prepend(n),n}function Na(e={}){const t=B1(e);return uw=t,t}async function xw(e,t){return e.requireTeamSetupSummary?(await t,!1):uw??!1}async function B1(e){const t=$e("projectsInventoryMeta"),n=$e("projectsInventoryList");if(!t||!n)return e.requireTeamSetupSummary?(await of(!0)).ok:!0;if(Yc()){if(zc=!0,!e.requireTeamSetupSummary)return!0;const o=++Ta,s=await of(!0);if(o!==Ta)return!1;const c=$e("recipientPolicyReviewMount");return s.ok?(c&&Ew(c,s.summary),!0):(c&&Aw(c),!1)}zc=!1;const r=++ro;fr=!1,mr=!1,ti(),t.textContent="Loading project inventory…";let i=null;try{const o=++Ta;i=of(e.requireTeamSetupSummary===!0);const[s,c,l,d,u]=await Promise.all([bo({limit:Uc,offset:Ut,q:$e("projectsSearch")?.value.trim()||void 0,status:$e("projectsStatusFilter")?.value||void 0}),CR(),M1().then(g=>({ok:!0,projects:g})).catch(()=>({ok:!1,projects:[]})),SR().then(g=>({ok:!0,review:g})).catch(g=>({ok:!1,error:g})),El().then(g=>({ok:!0,intent:g})).catch(g=>({ok:!1,error:g}))]);if(r!==ro)return xw(e,i);if(nf=c.scopes,fr=l.ok,mr=u.ok,oo=u.ok?u.intent:Wc,l.ok){const g=new Set(ys(l.projects).map(h=>h.canonicalProjectIdentity));for(const h of Gt)g.has(h)||Gt.delete(h)}const p=$e("projectShareFlowMount");p&&Kg(p,l.projects,{inventoryError:!l.ok});const f=$e("recipientPolicyReviewMount");if(f){const g=F1(f);"review"in d?o1(g,d.review,{isRepairAvailable:h=>!h.projectIdentity.startsWith("unmapped:"),onRepair:x1}):a1(g,d.error),f.hidden=g.hidden&&!f.querySelector(".project-team-setup-entry")}Nw(l.projects,oo,!l.ok||!u.ok),Pw(s),j1(s,r),i.then(g=>{if(r!==ro||o!==Ta)return;const h=$e("recipientPolicyReviewMount");if(h){if(!g.ok){Aw(h);return}Ew(h,g.summary)}});const m=l.ok&&"review"in d&&u.ok;if(!e.requireTeamSetupSummary)return m;const v=await i;return r!==ro||o!==Ta?!1:m&&v.ok}catch(o){if(r!==ro)return xw(e,i);Ia.clear(),fr=!1,mr=!1,oo=Wc;const s=$e("projectShareFlowMount");return s&&Kg(s,[],{inventoryError:!0}),Nw([],Wc,!0),ti(),Tw(),t.textContent="Project inventory failed to load.",kw(o instanceof Error?o.message:"Unable to load project inventory."),!1}}function q1(e,t={}){bt=e,rf=t.onOpenTeamSetup,Gt.clear();const n=$e("projectsStatusFilter");if(n&&n.options.length===0)for(const[o,s]of dw){const c=document.createElement("option");c.value=o,c.textContent=s,n.appendChild(c)}const r=()=>{Gn+=1,Ut=0,bt?.()};$e("projectsSearch")?.addEventListener("input",r),n?.addEventListener("change",r),$e("projectsPrevPage")?.addEventListener("click",()=>{Gn+=1,Ut=Math.max(0,Ut-Uc),bt?.()}),$e("projectsNextPage")?.addEventListener("click",()=>{Gn+=1,Ut+=Uc,bt?.()});const i=$e("projectsShareSelected");i&&i.dataset.recipientPolicyBound!=="true"&&(i.dataset.recipientPolicyBound="true",i.addEventListener("click",()=>{Gt.size!==0&&xo({mode:"project-add",projectIds:[...Gt].sort()})})),ti()}function pf(e,t){const n=e.trim();if(!n)return[];const r=JSON.parse(n);if(!Array.isArray(r)||r.some(o=>typeof o!="string"))throw new Error(`${t.label} must be a JSON string array`);if(!t.normalize&&!t.requireNonEmpty)return r;const i=t.normalize?r.map(o=>o.trim()):r;if(t.requireNonEmpty&&i.some(o=>o.trim()===""))throw new Error(`${t.label} cannot contain empty command tokens`);return i}function U1(e){const t=e.trim();if(!t)return{};const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))throw new Error("observer headers must be a JSON object");const r={};for(const[i,o]of Object.entries(n)){if(typeof i!="string"||!i.trim()||typeof o!="string")throw new Error("observer headers must map string keys to string values");r[i.trim()]=o}return r}var Dw="codemem-settings-advanced",Lw="gpt-5.1-codex-mini",$w="claude-4.5-haiku",G1=[{value:"observer",label:"Connection"},{value:"queue",label:"Processing"},{value:"sync",label:"Device Sync"}],H1={claudeCommand:"claude_command",codexCommand:"codex_command",observerProvider:"observer_provider",observerModel:"observer_model",observerTierRoutingEnabled:"observer_tier_routing_enabled",observerSimpleModel:"observer_simple_model",observerSimpleTemperature:"observer_simple_temperature",observerReasoningEffort:"observer_reasoning_effort",observerReasoningSummary:"observer_reasoning_summary",observerRichModel:"observer_rich_model",observerRichTemperature:"observer_rich_temperature",observerRichReasoningEffort:"observer_rich_reasoning_effort",observerRichReasoningSummary:"observer_rich_reasoning_summary",observerRichMaxOutputTokens:"observer_rich_max_output_tokens",observerRuntime:"observer_runtime",observerAuthSource:"observer_auth_source",observerAuthFile:"observer_auth_file",observerAuthCommand:"observer_auth_command",observerAuthTimeoutMs:"observer_auth_timeout_ms",observerAuthCacheTtlS:"observer_auth_cache_ttl_s",observerHeaders:"observer_headers",observerMaxChars:"observer_max_chars",packObservationLimit:"pack_observation_limit",packSessionLimit:"pack_session_limit",rawEventsSweeperIntervalS:"raw_events_sweeper_interval_s",syncEnabled:"sync_enabled",syncHost:"sync_host",syncPort:"sync_port",syncInterval:"sync_interval_s",syncMdns:"sync_mdns",syncCoordinatorUrl:"sync_coordinator_url",syncCoordinatorGroup:"sync_coordinator_group",syncCoordinatorTimeout:"sync_coordinator_timeout_s",syncCoordinatorPresenceTtl:"sync_coordinator_presence_ttl_s"},V1=new Set(["claude_command","codex_command","observer_base_url","observer_auth_file","observer_auth_command","observer_headers","sync_coordinator_url"]),K1={claudeCommand:"",codexCommand:"",observerProvider:"",observerModel:"",observerTierRoutingEnabled:!1,observerSimpleModel:"",observerSimpleTemperature:"",observerReasoningEffort:"",observerReasoningSummary:"",observerRichModel:"",observerRichTemperature:"",observerRichReasoningEffort:"",observerRichReasoningSummary:"",observerRichMaxOutputTokens:"",observerRuntime:"api_http",observerAuthSource:"auto",observerAuthFile:"",observerAuthCommand:"",observerAuthTimeoutMs:"",observerAuthCacheTtlS:"",observerHeaders:"",observerMaxChars:"",packObservationLimit:"",packSessionLimit:"",rawEventsSweeperIntervalS:"",syncEnabled:!1,syncHost:"",syncPort:"",syncInterval:"",syncMdns:!1,syncCoordinatorUrl:"",syncCoordinatorGroup:"",syncCoordinatorTimeout:"",syncCoordinatorPresenceTtl:""};function z1(){try{return globalThis.localStorage?.getItem(Dw)==="1"}catch{return!1}}function W1(e){try{globalThis.localStorage?.setItem(Dw,e?"1":"0")}catch{}}function Hn(e,t){return typeof e=="object"&&e!==null&&Object.hasOwn(e,t)}function Ee(e,t,n){if(Hn(t,n))return t[n];if(Hn(e,n))return e[n]}function Oe(e){return e==null?"":String(e)}function Qc(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){const t=e.trim().toLowerCase();if(!t||["0","false","no","off"].includes(t))return!1;if(["1","true","yes","on"].includes(t))return!0}return!!e}function J1(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function Y1(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function ct(e){const t=e.trim();return t===""?"":t}function X1(e,t,n){return n?{model:n,source:"Configured"}:e==="claude_sidecar"?{model:$w,source:"Recommended (local Claude session)"}:e==="codex_sidecar"?{model:Lw,source:"Recommended (local Codex session)"}:t==="anthropic"?{model:$w,source:"Recommended (Anthropic provider)"}:t==="opencode"?{model:"opencode/gpt-5.1-codex-mini",source:"Recommended (OpenCode Zen provider)"}:t&&t!=="openai"?{model:"provider default",source:"Recommended (provider default)"}:{model:Lw,source:"Recommended (direct API)"}}function Q1(e,t){const n=e??{};switch(t){case"claude_command":{const r=n.claude_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(o=>{if(typeof o!="string")return;const s=o.trim();s&&i.push(s)}),i}case"codex_command":{const r=n.codex_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(o=>{if(typeof o!="string")return;const s=o.trim();s&&i.push(s)}),i}case"observer_provider":case"observer_model":case"observer_simple_model":case"observer_reasoning_effort":case"observer_reasoning_summary":case"observer_rich_model":case"observer_rich_reasoning_effort":case"observer_rich_reasoning_summary":case"observer_auth_file":case"sync_host":case"sync_coordinator_url":case"sync_coordinator_group":return ct(Oe(n[t]));case"observer_runtime":return ct(Oe(n.observer_runtime));case"observer_auth_source":return ct(Oe(n.observer_auth_source));case"observer_auth_command":{const r=n.observer_auth_command;return Array.isArray(r)?r.filter(i=>typeof i=="string"):[]}case"observer_headers":{const r=n.observer_headers;if(!r||typeof r!="object"||Array.isArray(r))return{};const i={};return Object.entries(r).forEach(([o,s])=>{typeof o=="string"&&o.trim()&&typeof s=="string"&&(i[o.trim()]=s)}),i}case"observer_auth_timeout_ms":case"observer_max_chars":case"observer_simple_temperature":case"observer_rich_temperature":case"observer_rich_max_output_tokens":case"pack_observation_limit":case"pack_session_limit":case"raw_events_sweeper_interval_s":case"sync_port":case"sync_interval_s":{if(!Hn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r!==0?r:""}case"sync_coordinator_timeout_s":case"sync_coordinator_presence_ttl_s":{if(!Hn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r>0?r:""}case"observer_auth_cache_ttl_s":{if(!Hn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)?r:""}case"sync_enabled":case"sync_mdns":case"observer_tier_routing_enabled":return Qc(n[t]);default:return Hn(n,t)?n[t]:""}}function Z1(e,t,n){const r={...e};return Object.keys(n).forEach(i=>{Hn(r,i)&&(r[i]=Q1(t,i))}),r}function eF(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let o=[];try{o=pf(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(R){if(!i||n.has("claude_command"))throw R;const I=r.claude_command;o=Array.isArray(I)?I.filter(T=>typeof T=="string").map(T=>T.trim()).filter(T=>T.length>0):[]}let s=[];try{s=pf(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(R){if(!i||n.has("codex_command"))throw R;const I=r.codex_command;s=Array.isArray(I)?I.filter(T=>typeof T=="string").map(T=>T.trim()).filter(T=>T.length>0):[]}let c=[];try{c=pf(t.observerAuthCommand,{label:"observer auth command"})}catch(R){if(!i||n.has("observer_auth_command"))throw R;const I=r.observer_auth_command;c=Array.isArray(I)?I.filter(T=>typeof T=="string"):[]}let l={};try{l=U1(t.observerHeaders)}catch(R){if(!i||n.has("observer_headers"))throw R;const I=r.observer_headers;I&&typeof I=="object"&&!Array.isArray(I)&&Object.entries(I).forEach(([T,A])=>{typeof T=="string"&&T.trim()&&typeof A=="string"&&(l[T]=A)})}const d=t.observerAuthCacheTtlS.trim(),u=t.observerSimpleTemperature.trim(),p=t.observerRichTemperature.trim(),f=t.observerRichMaxOutputTokens.trim(),m=t.rawEventsSweeperIntervalS.trim(),v=d===""?"":Number(d),g=u===""?"":Number(u),h=p===""?"":Number(p),b=f===""?"":Number(f),w=Number(m),_=m===""?"":w;if(d!==""&&!Number.isFinite(v))throw new Error("observer auth cache ttl must be a number");if(u!==""&&(typeof g!="number"||!Number.isFinite(g)||g<0))throw new Error("simple tier temperature must be a non-negative number");if(p!==""&&(typeof h!="number"||!Number.isFinite(h)||h<0))throw new Error("rich tier temperature must be a non-negative number");if(f!==""&&(typeof b!="number"||!Number.isFinite(b)||b<=0||!Number.isInteger(b)))throw new Error("rich tier max output tokens must be a positive integer");if(m!==""&&(!Number.isFinite(w)||w<=0))throw new Error("raw-event sweeper interval must be a positive number");return{claude_command:o,codex_command:s,observer_provider:ct(t.observerProvider),observer_model:ct(t.observerModel),observer_tier_routing_enabled:t.observerTierRoutingEnabled,observer_simple_model:ct(t.observerSimpleModel),observer_simple_temperature:g,observer_reasoning_effort:ct(t.observerReasoningEffort),observer_reasoning_summary:ct(t.observerReasoningSummary),observer_rich_model:ct(t.observerRichModel),observer_rich_temperature:h,observer_rich_reasoning_effort:ct(t.observerRichReasoningEffort),observer_rich_reasoning_summary:ct(t.observerRichReasoningSummary),observer_rich_max_output_tokens:b,observer_runtime:ct(t.observerRuntime||"api_http")||"api_http",observer_auth_source:ct(t.observerAuthSource||"auto")||"auto",observer_auth_file:ct(t.observerAuthFile),observer_auth_command:c,observer_auth_timeout_ms:Number(t.observerAuthTimeoutMs||0)||"",observer_auth_cache_ttl_s:v,observer_headers:l,observer_max_chars:Number(t.observerMaxChars||0)||"",pack_observation_limit:Number(t.packObservationLimit||0)||"",pack_session_limit:Number(t.packSessionLimit||0)||"",raw_events_sweeper_interval_s:_,sync_enabled:t.syncEnabled,sync_host:ct(t.syncHost),sync_port:Number(t.syncPort||0)||"",sync_interval_s:Number(t.syncInterval||0)||"",sync_mdns:t.syncMdns,sync_coordinator_url:ct(t.syncCoordinatorUrl),sync_coordinator_group:ct(t.syncCoordinatorGroup),sync_coordinator_timeout_s:Number(t.syncCoordinatorTimeout||0)||"",sync_coordinator_presence_ttl_s:Number(t.syncCoordinatorPresenceTtl||0)||""}}function tF(e){const t=e.config||{},n=e.effective||{},r=Ee(t,n,"observer_headers"),i=r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).filter(([p,f])=>typeof p=="string"&&p.trim()&&typeof f=="string")):{},o=Ee(t,n,"claude_command"),s=Array.isArray(o)?o.filter(p=>typeof p=="string"):[],c=Ee(t,n,"codex_command"),l=Array.isArray(c)?c.filter(p=>typeof p=="string"):[],d=Ee(t,n,"observer_auth_command"),u=Array.isArray(d)?d.filter(p=>typeof p=="string"):[];return{claudeCommand:s.length?JSON.stringify(s,null,2):"",codexCommand:l.length?JSON.stringify(l,null,2):"",observerProvider:Oe(Ee(t,n,"observer_provider")),observerModel:Oe(Ee(t,n,"observer_model")),observerTierRoutingEnabled:Qc(Ee(t,n,"observer_tier_routing_enabled")),observerSimpleModel:Oe(Ee(t,n,"observer_simple_model")),observerSimpleTemperature:Oe(Ee(t,n,"observer_simple_temperature")),observerReasoningEffort:Oe(Ee(t,n,"observer_reasoning_effort")),observerReasoningSummary:Oe(Ee(t,n,"observer_reasoning_summary")),observerRichModel:Oe(Ee(t,n,"observer_rich_model")),observerRichTemperature:Oe(Ee(t,n,"observer_rich_temperature")),observerRichReasoningEffort:Oe(Ee(t,n,"observer_rich_reasoning_effort")),observerRichReasoningSummary:Oe(Ee(t,n,"observer_rich_reasoning_summary")),observerRichMaxOutputTokens:Oe(Ee(t,n,"observer_rich_max_output_tokens")),observerRuntime:Oe(Ee(t,n,"observer_runtime"))||"api_http",observerAuthSource:Oe(Ee(t,n,"observer_auth_source"))||"auto",observerAuthFile:Oe(Ee(t,n,"observer_auth_file")),observerAuthCommand:u.length?JSON.stringify(u,null,2):"",observerAuthTimeoutMs:Oe(Ee(t,n,"observer_auth_timeout_ms")),observerAuthCacheTtlS:Oe(Ee(t,n,"observer_auth_cache_ttl_s")),observerHeaders:Object.keys(i).length?JSON.stringify(i,null,2):"",observerMaxChars:Oe(Ee(t,n,"observer_max_chars")),packObservationLimit:Oe(Ee(t,n,"pack_observation_limit")),packSessionLimit:Oe(Ee(t,n,"pack_session_limit")),rawEventsSweeperIntervalS:Oe(Ee(t,n,"raw_events_sweeper_interval_s")),syncEnabled:Qc(Ee(t,n,"sync_enabled")),syncHost:Oe(Ee(t,n,"sync_host")),syncPort:Oe(Ee(t,n,"sync_port")),syncInterval:Oe(Ee(t,n,"sync_interval_s")),syncMdns:Qc(Ee(t,n,"sync_mdns")),syncCoordinatorUrl:Oe(Ee(t,n,"sync_coordinator_url")),syncCoordinatorGroup:Oe(Ee(t,n,"sync_coordinator_group")),syncCoordinatorTimeout:Oe(Ee(t,n,"sync_coordinator_timeout_s")),syncCoordinatorPresenceTtl:Oe(Ee(t,n,"sync_coordinator_presence_ttl_s"))}}function nF(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection now lives in Processing.";const n=X1(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),ct(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>Hn(t,r))?"Env override":n.source}: ${n.model}`}function rF(e){return e.observerTierRoutingEnabled?"On: codemem routes simpler batches to Luna and richer batches to Terra with medium reasoning by default. Official OpenAI and OAuth Codex consumer requests always use Responses. The observer_openai_use_responses=false compatibility setting selects chat completions only for an explicitly configured custom OpenAI-compatible base URL. Sidecar runtimes route both tiers through their local CLI.":"Off: codemem uses the base observer settings from the Connection tab for all batches. Explicit user settings always win over built-in routing defaults."}function iF(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function oF(e){return e.observerTierRoutingEnabled?"Tiered routing is enabled, so Processing controls the simple/rich models. This base model is only a fallback, and explicit settings override built-in defaults.":"Leave blank to use a recommended model for your selected mode/provider."}function aF(e){return e.observerTierRoutingEnabled?"Tiered routing is active. Use this only as a fallback while the Processing tab owns simple/rich model selection and explicit tier settings override built-in defaults.":"Default: `gpt-5.4-mini` for Direct API, `gpt-5.1-codex-mini` for Local Codex session, or `claude-4.5-haiku` for Local Claude session."}function sF(e){return!e}function cF(e,t,n){return t.has(e)||n.has(e)}function lF(e){return`${e} is read-only in the viewer for security. Edit the config file or environment instead.`}var Y={open:!1,previouslyFocused:null,activeTab:"observer",baseline:{},envOverrides:{},touchedKeys:new Set,shellMounted:!1,protectedKeys:new Set,startPolling:null,refresh:null,showAdvanced:z1(),controller:null,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...K1}}};function dF(){Y.controller?.hideTooltip()}function ni(e){if(Y.controller){Y.controller.setRenderState(e);return}Y.renderState={...Y.renderState,...e}}function uF(e){ni({values:{...Y.renderState.values,...e}})}function pF(e){const t=["observer","queue","sync"].includes(e)?e:"observer";Y.activeTab=t,Y.controller?.setActiveTab(t)}function Zc(e,t=!0){C.settingsDirty=e,t&&Y.controller?.setDirty(e)}function fF(e){Y.showAdvanced=e,Y.controller?.setShowAdvanced(e)}function Ow(){return Y.open}function mF(e){return cF(e,Y.protectedKeys,V1)}function jw(e={}){return eF({values:Y.renderState.values,touchedKeys:Y.touchedKeys,baseline:Y.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors})}function hF(e){ni({observerStatus:e&&typeof e=="object"?e:null})}function gF(e){if(!e||typeof e!="object")return;const t=e,n=t.defaults||{},r=t.config||{},i=t.env_overrides&&typeof t.env_overrides=="object"?t.env_overrides:{},o=Array.isArray(t.protected_keys)?t.protected_keys.filter(c=>typeof c=="string"&&c.trim().length>0):[],s=tF(t);Y.envOverrides=i,Y.protectedKeys=new Set(o),C.configDefaults=n,C.configPath=t.path||"",ni({effectiveText:Object.keys(i).length>0?"Some fields are managed by environment settings.":"",overridesVisible:Object.keys(i).length>0,pathText:C.configPath?`Config path: ${C.configPath}`:"Config path: n/a",providers:J1(t.providers),statusText:"No unsaved changes",values:s}),Y.touchedKeys=new Set;try{const c=jw({allowUntouchedParseErrors:!0});Y.baseline=Z1(c,r,i)}catch{Y.baseline={}}Zc(!1)}async function vF(){if(!Y.open)try{const[e,t]=await Promise.all([bC(),yC().catch(()=>null)]);gF(e),hF(t)}catch{}}function ff(e){return String(e||"").replace(/_/g," ")}function mf(e){const t=e.filter(n=>typeof n=="string"&&n.trim());return t.length===0?"":t.length===1?t[0]:t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[t.length-1]}`}function yF(e){switch(e){case"anthropic_consumer":return"OAuth (Claude Max/Pro)";case"codex_consumer":return"OAuth (ChatGPT subscription)";case"sdk_client":return"API key";case"claude_sidecar":return"Local Claude session";case"codex_sidecar":return"Local Codex session";case"opencode_run":return"OpenCode sidecar";default:return e||"none"}}function bF(e){const t=[];return e.oauth&&t.push("OAuth"),e.api_key&&t.push("API key"),e.env_var&&t.push("env var"),t.length?t.join(", "):"none"}function _F(e){if(typeof e!="string"||!e.trim())return"Unknown time";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function wF({onOpenDiagnostics:e}){return e?a("button",{className:"settings-button",onClick:()=>e({severity:"error",subsystem:"observer"}),type:"button",children:"View observer diagnostics"}):null}function SF({status:e,onOpenDiagnostics:t}){if(!e)return a("div",{id:"observerStatusBanner",className:"observer-status-banner",hidden:!0});const n=e.active,r=e.available_credentials||{},i=e.latest_failure,o=Object.entries(r).filter(([,s])=>s&&typeof s=="object");return a("div",{id:"observerStatusBanner",className:"observer-status-banner",children:[n?a(z,{children:[a("div",{className:"status-label",children:"Active observer"}),a("div",{className:"status-active",children:[String(n.provider||"unknown")," → ",String(n.model||"")," via"," ",yF(n.auth?.method||"none")," ",a("span",{"aria-label":n.auth?.token_present===!0?"token present":"token missing",className:n.auth?.token_present===!0?"cred-ok":"cred-none",role:"img",children:a("i",{"aria-hidden":"true","data-lucide":n.auth?.token_present===!0?"check":"x"})})]})]}):a(z,{children:[a("div",{className:"status-label",children:"Observer status"}),a("div",{className:"status-active",children:"Not yet initialized (waiting for first session)"})]}),o.length?a(z,{children:[a("div",{className:"status-label",children:"Available credentials"}),a("div",{children:o.map(([s,c],l)=>{const d=c,u=Object.values(d).some(Boolean);return a("span",{className:"status-cred",children:[l>0?" · ":null,a("span",{"aria-label":u?"credential available":"no credential",className:u?"cred-ok":"cred-none",role:"img",children:u?a("i",{"aria-hidden":"true","data-lucide":"check"}):"–"})," ",String(s),": ",bF(d)]},s)})})]}):null,i&&typeof i=="object"?a(z,{children:[a("div",{className:"status-label",children:"Latest processing issue"}),a("div",{className:"status-issue",children:[a("div",{className:"status-issue-message",children:typeof i.error_message=="string"&&i.error_message.trim()?i.error_message.trim():"Raw-event processing failed."}),a("div",{className:"status-issue-meta",children:[[typeof i.observer_provider=="string"?i.observer_provider.trim():"",typeof i.observer_model=="string"&&i.observer_model.trim()?`→ ${i.observer_model.trim()}`:"",typeof i.observer_runtime=="string"&&i.observer_runtime.trim()?`(${i.observer_runtime.trim()})`:""].filter(Boolean).join(" ").replace(/\s+/g," ").trim(),`Last failure ${_F(i.updated_at)}`,typeof i.attempt_count=="number"&&Number.isFinite(i.attempt_count)?`Attempts ${i.attempt_count}`:""].filter(Boolean).join(" · ")}),typeof i.impact=="string"&&i.impact.trim()?a("div",{className:"status-issue-impact",children:i.impact.trim()}):null,a(wF,{onOpenDiagnostics:t})]})]}):null]})}function Mw(e,t){const n=t.getBoundingClientRect(),r=8,i=8,o=e.offsetWidth,s=e.offsetHeight;let c=n.left+n.width/2-o/2;c=Math.max(r,Math.min(c,globalThis.innerWidth-o-r));let l=n.bottom+i;l+s>globalThis.innerHeight-r&&(l=n.top-s-i),l=Math.max(r,l),e.style.left=`${Math.round(c)}px`,e.style.top=`${Math.round(l)}px`}function Ea(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function CF(e){if(!e)return[];const t=["button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[href]",'[tabindex]:not([tabindex="-1"])'].join(",");return Array.from(e.querySelectorAll(t)).filter(n=>{const r=n;return!r.hidden&&r.offsetParent!==null})}function RF(){const e=Le("settingsModal");(CF(e)[0]||e)?.focus()}function IF(){const[e,t]=x({anchor:null,content:"",visible:!1}),n=B(null);return V(()=>{const r=u=>{const p=u.dataset.tooltip?.trim();p&&t({anchor:u,content:p,visible:!0})},i=()=>{t(u=>!u.visible&&!u.anchor&&!u.content?u:{anchor:null,content:"",visible:!1})},o=u=>{const p=Ea(u.target);p&&r(p)},s=u=>{const p=Ea(u.target);if(!p)return;const f=u.relatedTarget;f instanceof Element&&p.contains(f)||i()},c=u=>{const p=Ea(u.target);p&&r(p)},l=u=>{Ea(u.target)&&i()},d=u=>{const p=Ea(u.target);p&&(u.preventDefault(),t(f=>{if(f.anchor===p&&f.visible)return{anchor:null,content:"",visible:!1};const m=p.dataset.tooltip?.trim()||"";return m?{anchor:p,content:m,visible:!0}:f}))};return document.addEventListener("pointerover",o),document.addEventListener("pointerout",s),document.addEventListener("focusin",c),document.addEventListener("focusout",l),document.addEventListener("click",d),()=>{document.removeEventListener("pointerover",o),document.removeEventListener("pointerout",s),document.removeEventListener("focusin",c),document.removeEventListener("focusout",l),document.removeEventListener("click",d)}},[]),It(()=>{if(!e.visible||!e.anchor||!n.current)return;const r=requestAnimationFrame(()=>{n.current&&e.anchor&&Mw(n.current,e.anchor)});return()=>{cancelAnimationFrame(r)}},[e.anchor,e.content,e.visible]),V(()=>{if(!e.visible||!e.anchor)return;const r=()=>{n.current&&e.anchor&&Mw(n.current,e.anchor)};return globalThis.addEventListener("resize",r),document.addEventListener("scroll",r,!0),()=>{globalThis.removeEventListener("resize",r),document.removeEventListener("scroll",r,!0)}},[e.anchor,e.visible]),{tooltipPortal:ke(()=>typeof document>"u"?null:sn(a("div",{className:`help-tooltip${e.visible?" visible":""}`,hidden:!e.visible,ref:n,children:e.content}),document.body),[e.content,e.visible]),setTooltip:t}}function kF({DialogContent:e,onClose:t}){const[n,r]=x(Y.open),[i,o]=x(["observer","queue","sync"].includes(Y.activeTab)?Y.activeTab:"observer"),[s,c]=x(C.settingsDirty),[l,d]=x(Y.renderState),[u,p]=x(Y.showAdvanced),{tooltipPortal:f,setTooltip:m}=IF();Y.open=n,Y.activeTab=i,C.settingsDirty=s,Y.renderState=l,Y.showAdvanced=u,V(()=>(Y.controller={hideTooltip:()=>{m({anchor:null,content:"",visible:!1})},setActiveTab:g=>{const h=["observer","queue","sync"].includes(g)?g:"observer";Y.activeTab=h,o(h)},setDirty:g=>{C.settingsDirty=g,c(g)},setOpen:g=>{Y.open=g,r(g)},setRenderState:g=>{const h={...Y.renderState,...g};Y.renderState=h,d(h)},setShowAdvanced:g=>{Y.showAdvanced=g,W1(g),p(g)}},()=>{Y.controller&&(Y.controller=null)}),[]),V(()=>{n&&globalThis.lucide?.createIcons?.()},[n]);const v=ae(()=>{Y.startPolling&&Y.refresh&&t(Y.startPolling,Y.refresh)},[t]);return a(z,{children:[a(Qn,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:g=>{g.preventDefault()},onOpenAutoFocus:g=>{g.preventDefault(),RF()},onOpenChange:g=>{if(g){r(!0);return}v()},open:n,overlayClassName:"modal-backdrop",overlayId:"settingsBackdrop",children:a(e,{})}),f]})}function ze({children:e,className:t="field",hidden:n=!1,id:r}){return a("div",{className:t,hidden:n,id:r,children:e})}function Aa({children:e,hidden:t=!1}){return a("div",{className:"settings-note",hidden:t,children:e})}function hf({detail:e,title:t}){return a("div",{className:"settings-section-intro",children:[a("div",{className:"settings-section-intro-title",children:t}),a("div",{className:"small settings-section-intro-detail",children:e})]})}function TF({values:e,observerMaxCharsDefault:t,providerOptions:n,showAuthFile:r,showAuthCommand:i,hiddenUnlessAdvanced:o,onTextInput:s,onSelectValueChange:c,getObserverModelLabel:l,getObserverModelTooltip:d,getObserverModelDescription:u,getObserverModelHint:p,protectedConfigHelp:f,observerStatusBannerSlot:m}){return a(z,{children:[a(hf,{detail:"Set how codemem reaches your model provider and where it should look for credentials.",title:"Connection and credentials"}),m,a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Connection"}),a(ze,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerProvider",children:"Model provider"}),a("button",{"aria-label":"About model provider",className:"help-icon","data-tooltip":"Choose where model requests are sent. Use auto for recommended defaults.",type:"button",children:"?"})]}),a(ar,{ariaLabel:"Model provider",contentClassName:"settings-select-content",id:"observerProvider",itemClassName:"settings-select-item",onValueChange:c("observerProvider"),options:[{label:"auto (default)",value:""},...n],placeholder:"auto (default)",triggerClassName:"settings-select-trigger",value:e.observerProvider,viewportClassName:"settings-select-viewport"}),a("div",{className:"small",children:"Use `auto` unless you need to pin a specific provider."})]}),a(ze,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerModel",children:l()}),a("button",{"aria-label":"About model defaults",className:"help-icon","data-tooltip":d(),type:"button",children:"?"})]}),a(Te,{id:"observerModel",onInput:s("observerModel"),placeholder:"leave empty for default",value:e.observerModel}),a("div",{className:"small",children:u()}),a("div",{className:"small",id:"observerModelHint",children:p()})]}),a(ze,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerRuntime",children:"Connection mode"}),a("button",{"aria-label":"About connection mode",className:"help-icon","data-tooltip":"Direct API uses provider credentials. Local sessions use the selected Claude or Codex CLI login.",type:"button",children:"?"})]}),a(ar,{ariaLabel:"Connection mode",contentClassName:"settings-select-content",id:"observerRuntime",itemClassName:"settings-select-item",onValueChange:c("observerRuntime"),options:[{label:"Direct API (default)",value:"api_http"},{label:"Local Claude session",value:"claude_sidecar"},{label:"Local Codex session",value:"codex_sidecar"}],triggerClassName:"settings-select-trigger",value:e.observerRuntime,viewportClassName:"settings-select-viewport"}),a("div",{className:"small",children:"Switch between provider API credentials and local Claude or Codex CLI auth."})]}),a(ze,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"codexCommand",children:"Codex command (JSON argv)"}),a(Ki,{disabled:!0,id:"codexCommand",placeholder:'["codex"]',rows:2,value:e.codexCommand}),a("div",{className:"small",children:f("codex_command")})]}),a(ze,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"claudeCommand",children:"Claude command (JSON argv)"}),a(Ki,{disabled:!0,id:"claudeCommand",placeholder:'["claude"]',rows:2,value:e.claudeCommand}),a("div",{className:"small",children:f("claude_command")})]}),a(ze,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerMaxChars",children:"Request size limit (chars)"}),a(Te,{id:"observerMaxChars",min:"1",onInput:s("observerMaxChars"),type:"number",value:e.observerMaxChars}),a("div",{className:"small",id:"observerMaxCharsHint",children:t?`Default: ${t}`:""})]})]}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Authentication"}),a(ze,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerAuthSource",children:"Authentication method"}),a("button",{"aria-label":"About authentication method",className:"help-icon","data-tooltip":"Choose how credentials are resolved: environment, file, command, or none.",type:"button",children:"?"})]}),a(ar,{ariaLabel:"Authentication method",contentClassName:"settings-select-content",id:"observerAuthSource",itemClassName:"settings-select-item",onValueChange:c("observerAuthSource"),options:[{label:"auto (default)",value:"auto"},{label:"env",value:"env"},{label:"file",value:"file"},{label:"command",value:"command"},{label:"none",value:"none"}],triggerClassName:"settings-select-trigger",value:e.observerAuthSource,viewportClassName:"settings-select-viewport"}),a("div",{className:"small",children:"Use `auto` unless you need to force a file or command-based token source."})]}),a(ze,{hidden:!r,id:"observerAuthFileField",children:[a("label",{htmlFor:"observerAuthFile",children:"Token file path"}),a(Te,{disabled:!0,id:"observerAuthFile",placeholder:"~/.codemem/work-token.txt",value:e.observerAuthFile}),a("div",{className:"small",children:f("observer_auth_file")})]}),a(ze,{hidden:!i,id:"observerAuthCommandField",children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerAuthCommand",children:"Token command"}),a("button",{"aria-label":"About token command",className:"help-icon","data-tooltip":"Runs this command and uses stdout as the token. JSON argv only, no shell parsing.",type:"button",children:"?"})]}),a(Ki,{disabled:!0,id:"observerAuthCommand",placeholder:'["iap-auth", "--audience", "gateway"]',rows:3,value:e.observerAuthCommand}),a("div",{className:"small",children:f("observer_auth_command")})]}),a("div",{className:"small",hidden:!i,id:"observerAuthCommandNote",children:'Command format: JSON string array, e.g. `["iap-auth", "--audience", "gateway"]`.'}),a(Aa,{hidden:o(),children:"These advanced credential overrides only matter when you need custom command timing, cached tokens, or extra request headers."}),a(ze,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerAuthTimeoutMs",children:"Token command timeout (ms)"}),a(Te,{id:"observerAuthTimeoutMs",min:"1",onInput:s("observerAuthTimeoutMs"),type:"number",value:e.observerAuthTimeoutMs})]}),a(ze,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerAuthCacheTtlS",children:"Token cache time (s)"}),a(Te,{id:"observerAuthCacheTtlS",min:"0",onInput:s("observerAuthCacheTtlS"),type:"number",value:e.observerAuthCacheTtlS})]}),a(ze,{className:"field settings-advanced",hidden:o(),children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerHeaders",children:"Request headers (JSON)"}),a("button",{"aria-label":"About request headers",className:"help-icon","data-tooltip":"Optional extra headers. Supports templates like ${auth.token}, ${auth.type}, ${auth.source}.",type:"button",children:"?"})]}),a(Ki,{disabled:!0,id:"observerHeaders",placeholder:'{"Authorization":"Bearer ${auth.token}"}',rows:4,value:e.observerHeaders}),a("div",{className:"small",children:f("observer_headers")})]})]})]})}function el({checked:e,className:t,disabled:n=!1,hidden:r=!1,id:i,label:o,onCheckedChange:s}){const c=`${i}Label`;return a("div",{className:t?`field-checkbox settings-switch-row ${t}`:"field-checkbox settings-switch-row",hidden:r,children:[a("label",{className:"settings-switch-copy",htmlFor:i,id:c,children:o}),a(Gi,{"aria-labelledby":c,checked:e,className:"settings-switch",disabled:n,id:i,onCheckedChange:s,thumbClassName:"settings-switch-thumb"})]})}function PF({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r,onSwitchInput:i,getTieredRoutingHelperText:o}){return a(z,{children:[a(hf,{detail:"Control how often codemem processes queued work and, if needed, how it routes lighter vs richer model requests.",title:"Processing and routing"}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Processing"}),a(ze,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"rawEventsSweeperIntervalS",children:"Background processing interval (seconds)"}),a("button",{"aria-label":"About background processing interval",className:"help-icon","data-tooltip":"How often codemem checks for queued events to process in the background.",type:"button",children:"?"})]}),a(Te,{id:"rawEventsSweeperIntervalS",min:"1",onInput:r("rawEventsSweeperIntervalS"),type:"number",value:e.rawEventsSweeperIntervalS}),a("div",{className:"small",children:"How often codemem checks for queued raw events in the background."})]})]}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Tiered observer routing"}),a(el,{checked:e.observerTierRoutingEnabled,className:"field",id:"observerTierRoutingEnabled",label:"Enable tiered routing",onCheckedChange:i("observerTierRoutingEnabled")}),a("div",{className:"small",children:o()}),a(Aa,{hidden:!t||n(),children:"These advanced routing values are only useful when you are tuning model cost, latency, or output quality for a known workload. If a selected path cannot honor the requested tier settings, codemem falls back visibly instead of silently pretending it worked."}),a("div",{hidden:!t,children:[a("h4",{children:"Simple tier"}),a(ze,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerSimpleModel",children:"Model"}),a("button",{"aria-label":"About simple tier model",className:"help-icon","data-tooltip":"Used for lighter replay batches. Leave blank to keep codemem's routing defaults. Explicit simple-tier values override the built-in defaults.",type:"button",children:"?"})]}),a(Te,{id:"observerSimpleModel",onInput:r("observerSimpleModel"),placeholder:"leave empty for default",value:e.observerSimpleModel}),a("div",{className:"small",children:"Used when a batch falls below rich-routing thresholds."})]}),a(ze,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerSimpleTemperature",children:"Temperature"}),a(Te,{id:"observerSimpleTemperature",min:"0",onInput:r("observerSimpleTemperature"),step:"0.1",type:"number",value:e.observerSimpleTemperature})]})]}),a("div",{className:"settings-advanced",hidden:!t||n(),children:[a("h4",{children:"Shared reasoning defaults"}),a("div",{className:"small",children:"Applied to OpenAI Responses requests in both tiers unless a rich-tier override is set."}),a(ze,{className:"field settings-advanced",children:[a("label",{htmlFor:"observerReasoningEffort",children:"Reasoning effort"}),a(Te,{id:"observerReasoningEffort",onInput:r("observerReasoningEffort"),placeholder:"leave empty for provider default",value:e.observerReasoningEffort})]}),a(ze,{className:"field settings-advanced",children:[a("label",{htmlFor:"observerReasoningSummary",children:"Reasoning summary"}),a(Te,{id:"observerReasoningSummary",onInput:r("observerReasoningSummary"),placeholder:"leave empty for provider default",value:e.observerReasoningSummary})]})]}),a("div",{hidden:!t,children:[a("h4",{children:"Rich tier"}),a(ze,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerRichModel",children:"Model"}),a("button",{"aria-label":"About rich tier model",className:"help-icon","data-tooltip":"Used for larger or more complex replay batches. Leave blank to keep codemem's rich-tier defaults. Explicit rich-tier values override the built-in defaults.",type:"button",children:"?"})]}),a(Te,{id:"observerRichModel",onInput:r("observerRichModel"),placeholder:"leave empty for default",value:e.observerRichModel}),a("div",{className:"small",children:"Used when routing detects a richer replay batch."})]}),a(ze,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichTemperature",children:"Temperature"}),a(Te,{id:"observerRichTemperature",min:"0",onInput:r("observerRichTemperature"),step:"0.1",type:"number",value:e.observerRichTemperature})]}),a(ze,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichReasoningEffort",children:"Reasoning effort override"}),a(Te,{id:"observerRichReasoningEffort",onInput:r("observerRichReasoningEffort"),placeholder:"inherits shared reasoning effort",value:e.observerRichReasoningEffort})]}),a(ze,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichReasoningSummary",children:"Reasoning summary override"}),a(Te,{id:"observerRichReasoningSummary",onInput:r("observerRichReasoningSummary"),placeholder:"inherits shared reasoning summary",value:e.observerRichReasoningSummary})]}),a(ze,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichMaxOutputTokens",children:"Max output tokens"}),a(Te,{id:"observerRichMaxOutputTokens",min:"1",onInput:r("observerRichMaxOutputTokens"),step:"1",type:"number",value:e.observerRichMaxOutputTokens})]})]})]}),a("div",{className:"settings-group settings-advanced",hidden:n(),children:[a("h3",{className:"settings-group-title",children:"Pack limits"}),a(Aa,{hidden:n(),children:"Most users can keep these defaults. Change them only when you need smaller or larger default context packs."}),a(ze,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packObservationLimit",children:"Observation limit"}),a(Te,{id:"packObservationLimit",min:"1",onInput:r("packObservationLimit"),type:"number",value:e.packObservationLimit}),a("div",{className:"small",children:"Default number of observations to include in a pack."})]}),a(ze,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packSessionLimit",children:"Session summary limit"}),a(Te,{id:"packSessionLimit",min:"1",onInput:r("packSessionLimit"),type:"number",value:e.packSessionLimit}),a("div",{className:"small",children:"Default number of session summaries to include in a pack."})]})]})]})}function NF({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return a(z,{children:[a(hf,{detail:"Choose whether this device syncs at all, how often it checks peers, and which coordinator group it should join.",title:"Device sync"}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Device Sync"}),a(el,{checked:e.syncEnabled,className:"field",id:"syncEnabled",label:"Enable sync",onCheckedChange:r("syncEnabled")}),a("div",{className:"field",children:[a("label",{htmlFor:"syncInterval",children:"Sync interval (seconds)"}),a(Te,{id:"syncInterval",min:"10",onInput:n("syncInterval"),type:"number",value:e.syncInterval}),a("div",{className:"small",children:"How often this device checks for sync work when sync is enabled."})]}),a("div",{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncHost",children:"Sync host"}),a(Te,{id:"syncHost",onInput:n("syncHost"),placeholder:"127.0.0.1",value:e.syncHost})]}),a("div",{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncPort",children:"Sync port"}),a(Te,{id:"syncPort",min:"1",onInput:n("syncPort"),type:"number",value:e.syncPort})]}),a(el,{checked:e.syncMdns,className:"field settings-advanced",hidden:t(),id:"syncMdns",label:"Enable mDNS discovery",onCheckedChange:r("syncMdns")}),a("div",{className:"field",children:[a("label",{htmlFor:"syncCoordinatorUrl",children:"Coordinator URL"}),a(Te,{disabled:!0,id:"syncCoordinatorUrl",placeholder:"https://coord.example.com",value:e.syncCoordinatorUrl}),a("div",{className:"small",children:i("sync_coordinator_url")})]}),a("div",{className:"field",children:[a("label",{htmlFor:"syncCoordinatorGroup",children:"Coordinator group"}),a(Te,{id:"syncCoordinatorGroup",onInput:n("syncCoordinatorGroup"),placeholder:"team-alpha",value:e.syncCoordinatorGroup}),a("div",{className:"small",children:"Discovery namespace for peers using the same coordinator."})]}),a("div",{className:"field settings-advanced",hidden:t(),children:a(Aa,{hidden:t(),children:"These network overrides are for unusual local-network setups. Leave them alone unless you know this device needs non-default sync discovery or coordinator timing."})}),a("div",{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncCoordinatorTimeout",children:"Coordinator timeout (seconds)"}),a(Te,{id:"syncCoordinatorTimeout",min:"1",onInput:n("syncCoordinatorTimeout"),type:"number",value:e.syncCoordinatorTimeout})]}),a("div",{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncCoordinatorPresenceTtl",children:"Presence TTL (seconds)"}),a(Te,{id:"syncCoordinatorPresenceTtl",min:"1",onInput:n("syncCoordinatorPresenceTtl"),type:"number",value:e.syncCoordinatorPresenceTtl})]})]})]})}function EF({panelProps:e,activeTab:t,showAdvanced:n,renderState:r,settingsDirty:i,onClose:o,onSave:s,onActiveTabChange:c,onAdvancedToggle:l,observerStatusBannerSlot:d}){const u=!i||r.isSaving;return a("div",{className:"modal-card",onKeyDown:p=>Li(p,{onSubmit:s,disabled:u}),children:[a("div",{className:"modal-header",children:[a("h2",{id:"settingsTitle",children:"Settings"}),a(kr,{ariaLabel:"Close settings",className:"modal-close-button",onClick:o})]}),a("div",{className:"modal-body",children:[a("div",{className:"small",id:"settingsDescription",children:"Tune how codemem connects, processes work, and syncs with other devices."}),a("div",{className:"settings-advanced-toolbar",children:[a(el,{checked:n,id:"settingsAdvancedToggle",label:"Show advanced controls",onCheckedChange:l}),a("button",{"aria-label":"About advanced controls",className:"help-icon","data-tooltip":"Advanced controls include JSON fields, tuning values, and network overrides.",type:"button",children:a("i",{"aria-hidden":"true","data-lucide":"help-circle"})})]}),a(Aa,{hidden:!n,children:"Advanced controls are visible. Leave JSON fields, tuning values, and network overrides alone unless you are debugging or matching a known deployment setup."}),a(oy,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:c,tabs:G1,triggerClassName:"settings-tab",value:t,children:[a($r,{className:"settings-panel",forceMount:!0,value:"observer",children:a(TF,{...e,observerStatusBannerSlot:d})}),a($r,{className:"settings-panel",forceMount:!0,value:"queue",children:a(PF,{...e})}),a($r,{className:"settings-panel",forceMount:!0,value:"sync",children:a(NF,{...e})})]}),a("div",{className:"small mono",id:"settingsPath",children:r.pathText}),a("div",{className:"small",id:"settingsEffective",children:r.effectiveText}),a("div",{className:"settings-note",hidden:!r.overridesVisible,id:"settingsOverrides",children:"Some values are controlled outside this screen and take priority."}),a("div",{className:"settings-note",hidden:n,children:"Advanced controls are hidden right now to keep this screen focused on everyday settings."})]}),a("div",{className:"modal-footer",children:[a("div",{className:"small",id:"settingsStatus",children:r.statusText}),a("button",{className:"settings-save","data-primary-action":"true",disabled:u,id:"settingsSave",onClick:s,type:"button",children:r.isSaving?"Saving…":"Save changes"})]})]})}function AF(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:o}=e,s={};return Object.entries(t).forEach(([c,l])=>{o(c)||Hn(r,c)&&!i.has(c)||Y1(l,n[c])||(s[c]=l)}),s}function xF(e){const t=s=>{const c=H1[s];c&&e.getTouchedKeys().add(c)},n=(s,c)=>{t(s),e.updateFormState({[s]:c}),e.setDirty(!0)};return{markFieldTouched:t,updateField:n,onTextInput:s=>c=>{n(s,c.currentTarget.value)},onSelectValueChange:s=>c=>{n(s,c)},onSwitchInput:s=>c=>{n(s,c)}}}function DF(e){const t=e?.effects,n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},r=Array.isArray(n.hot_reloaded_keys)?n.hot_reloaded_keys.map(p=>ff(String(p))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(p=>ff(String(p))):[],o=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(p=>ff(String(p))):[],s=Array.isArray(n.warnings)?n.warnings.filter(p=>typeof p=="string"&&p.trim().length>0):[],c=Array.isArray(n.manual_actions)?n.manual_actions:[],l=n.sync&&typeof n.sync=="object"?n.sync:{},d=[];r.length&&d.push(`Applied now: ${mf(r)}.`),i.length&&d.push(`Live settings updated: ${mf(i)}.`),l.attempted&&typeof l.message=="string"&&l.message?d.push(`Sync: ${l.message}.`):Array.isArray(l.affected_keys)&&l.affected_keys.length&&typeof l.reason=="string"&&l.reason&&d.push(`Sync: ${l.reason}.`),o.length&&d.push(`Restart required for ${mf(o)}. Run: codemem serve restart`),s.forEach(p=>{d.push(p)}),c.forEach(p=>{p&&typeof p.command=="string"&&p.command.trim()&&d.push(`If needed: ${p.command}.`)}),d.length||d.push("Saved.");const u=o.length>0||s.length>0||l.ok===!1;return{message:d.join(" "),type:u?"warning":"success"}}var LF=()=>nF(Y.renderState.values,Y.envOverrides),$F=()=>rF(Y.renderState.values),OF=()=>iF(Y.renderState.values),jF=()=>oF(Y.renderState.values),MF=()=>aF(Y.renderState.values),FF=()=>sF(Y.showAdvanced),{onTextInput:BF,onSelectValueChange:qF,onSwitchInput:UF}=xF({getTouchedKeys:()=>Y.touchedKeys,getValues:()=>Y.renderState.values,updateFormState:uF,setDirty:e=>Zc(e)});function GF(){const e=Y.renderState.observerStatus;return a(SF,{status:e,onOpenDiagnostics:HF})}function HF(e){if(!Y.startPolling||!Y.refresh||(xa(Y.startPolling,Y.refresh),Y.open))return;const t=js("settingsButton");queueMicrotask(()=>Ar({...e,trigger:t}))}function VF(){const e=Y.renderState.values,t=String(C.configDefaults?.observer_max_chars||""),n=e.observerAuthSource==="file",r=e.observerAuthSource==="command",i=e.observerTierRoutingEnabled,o={values:e,observerMaxCharsDefault:t,providerOptions:Array.from(new Set(Y.renderState.providers.concat(e.observerProvider?[e.observerProvider]:[]))).sort((s,c)=>s.localeCompare(c)).map(s=>({label:s,value:s})),showAuthFile:n,showAuthCommand:r,showTieredRouting:i,hiddenUnlessAdvanced:FF,onTextInput:BF,onSelectValueChange:qF,onSwitchInput:UF,getObserverModelLabel:OF,getObserverModelTooltip:jF,getObserverModelDescription:MF,getObserverModelHint:LF,getTieredRoutingHelperText:$F,protectedConfigHelp:lF};return a(EF,{panelProps:o,activeTab:Y.activeTab,showAdvanced:Y.showAdvanced,renderState:Y.renderState,settingsDirty:C.settingsDirty,onClose:()=>{Y.startPolling&&Y.refresh&&xa(Y.startPolling,Y.refresh)},onSave:()=>{Y.startPolling&&Y.refresh&&JF(Y.startPolling,Y.refresh)},onActiveTabChange:pF,onAdvancedToggle:fF,observerStatusBannerSlot:a(GF,{})})}function KF(){return a(kF,{DialogContent:VF,onClose:xa})}function zF(){const e=Le("settingsDialogMount");e&&Ue(a(KF,{}),e)}function Fw(){Le("settingsDialogMount")&&(Y.shellMounted||(zF(),Y.shellMounted=!0))}function WF(e){Y.shellMounted||Fw(),Y.open=!0,Y.previouslyFocused=document.activeElement,e(),Y.controller?.setOpen(!0)}function xa(e,t){if(C.settingsDirty&&!globalThis.confirm("Discard unsaved changes?")){Y.controller?.setOpen(!0);return}Y.open=!1,Y.controller?.setOpen(!1),dF(),(Y.previouslyFocused&&typeof Y.previouslyFocused.focus=="function"?Y.previouslyFocused:js("settingsButton"))?.focus(),Y.previouslyFocused=null,Y.touchedKeys=new Set,e(),t()}async function JF(e,t){if(!Y.renderState.isSaving){ni({isSaving:!0,statusText:"Saving changes…"});try{const n=jw({allowUntouchedParseErrors:!0}),r=AF({current:n,baseline:Y.baseline,envOverrides:Y.envOverrides,touchedKeys:Y.touchedKeys,isProtected:mF});if(Object.keys(r).length===0){ni({isSaving:!1,statusText:"No unsaved changes"}),Zc(!1),xa(e,t);return}const i=await _C(r),o=DF(i);ni({isSaving:!1,statusText:"Saved changes"}),Zc(!1),xa(e,t),Z(o.message,o.type)}catch(n){const r=n instanceof Error?n.message:"unknown error";ni({isSaving:!1,statusText:`Save failed: ${r}`})}}}function YF(e,t,n){Y.startPolling=t,Y.refresh=n,Fw(),js("settingsButton")?.addEventListener("click",()=>WF(e))}function XF(e){e.dataset.syncRenderRoot="preact"}function QF(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function mt(e,t){XF(e),Ue(t,e)}function ao(e){e.dataset.syncRenderRoot==="preact"&&Ue(null,e)}function ZF(e){const t=Object.values(e||{}).map(n=>!n||typeof n!="object"?"":String(n.last_ping_at||"").trim()).filter(Boolean).sort();return t[t.length-1]??null}function eB(e){return typeof e=="object"&&e!==null}function tB(e,t){return C.pairingCommandRaw="",{payloadText:e,hintText:t}}function nB(e){if(!eB(e))return tB("Pairing not available","Enable sync and retry.");const t=e,n={...t,addresses:Array.isArray(t.addresses)?t.addresses:[]},r=JSON.stringify(n),i=`echo '${btoa(r)}' | base64 -d | codemem sync pair --accept-file -`;return C.pairingCommandRaw=i,{payloadText:i,hintText:"Copy this command and run it on the other device. Use --include/--exclude to control which projects sync."}}function rB(){return{title:"Diagnostics still loading.",detail:"Wait a moment for local sync status. If it stays blank, refresh the page or check whether sync is enabled on this device."}}function iB(){return{title:"Diagnostics unavailable right now.",detail:"The viewer could not load sync status. Refresh this page, or check that the local codemem sync service is reachable before retrying."}}function oB(){const e=C.lastSyncStatus;return{title:"No recent sync attempts yet.",detail:e?.daemon_state==="disabled"||e?.enabled===!1?"Turn on sync in Settings → Device Sync first. Recent attempts will appear here after this device can actually run sync work.":"Trigger a sync pass or pair another device to generate activity here when you need low-level troubleshooting."}}function aB(){return{title:"Recent attempts unavailable right now.",detail:"Attempt history could not be loaded because sync diagnostics failed. Refresh the page after local sync status is reachable again."}}function sB(e,t){return e==="offline-peers"&&t?"Some recent failures may have happened before all peers went offline. Sync will resume automatically when a peer becomes reachable.":""}function cB({items:e}){return a(z,{children:e.map((t,n)=>a("div",{class:"stat",children:a("div",{class:"stat-content",children:[a("div",{class:"value",children:t.value}),a("div",{class:"label",children:t.label})]})},`${t.label}-${n}`))})}function lB({attempts:e,note:t}){return a(z,{children:[t?a("div",{class:"small",children:t}):null,e.map((n,r)=>a("div",{class:"diag-line",children:[a("div",{class:"left",children:[a("div",{children:[n.peerLabel," — ",n.status]}),n.detail?a("div",{class:"small",children:n.detail}):null,n.actionHref&&n.actionLabel?a("a",{class:"small",href:n.actionHref,children:n.actionLabel}):null,n.action?a("button",{className:"settings-button small",onClick:i=>n.action?.(i.currentTarget),type:"button",children:"View sync diagnostics"}):null]}),a("div",{class:"right",children:n.startedAt})]},`${n.startedAt}-${n.peerLabel}-${r}`))]})}function Bw({text:e}){return a(z,{children:e})}function dB({title:e,detail:t}){return a("div",{class:"sync-empty-state",children:[a("strong",{children:e}),a("span",{children:t})]})}function uB(e,t){if(!t.length){ao(e);return}mt(e,a(cB,{items:t}))}function pB(e,t,n){if(!t.length){ao(e);return}mt(e,a(lB,{attempts:t,note:n}))}function ri(e,t){mt(e,a(dB,{...t}))}function qw(e,t,n){mt(e,a(Bw,{text:n.payloadText})),t&&mt(t,a(Bw,{text:n.hintText}))}function Uw({open:e,onOpenChange:t,triggerId:n,triggerClassName:r,closedLabel:i,openLabel:o,contentId:s,contentClassName:c,contentHost:l=null,children:d}){const u=B(null),p=B(null),f=B(!1);It(()=>{u.current&&(u.current.id=n,u.current.setAttribute("aria-controls",s)),p.current&&(p.current.id=s)},[s,n,e]),V(()=>{if(!e){f.current=!1;return}f.current||(f.current=!0,queueMicrotask(()=>{p.current?.querySelector('button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')?.focus()}))},[e]);const m=a(Wo,{forceMount:!0,asChild:!0,children:a("div",{ref:p,id:s,className:c,hidden:!e,children:d})});return a(zo,{open:e,onOpenChange:t,children:[a(Cu,{asChild:!0,children:a("button",{ref:u,type:"button",className:r,id:n,"aria-controls":s,children:e?o:i})}),l?sn(m,l):m]})}function fB({open:e,onOpenChange:t}){return a(Uw,{open:e,onOpenChange:t,triggerId:"syncToggleAdmin",triggerClassName:"sync-toggle-admin",closedLabel:"Set up a new team instead…",openLabel:"Hide team setup",contentId:"syncInvitePanel",children:[a("h3",{className:"settings-group-title",style:{marginTop:"12px"},children:"Create a team"}),a("div",{className:"section-meta",children:"Generate an invite to share with teammates."}),a("div",{className:"actor-create-row",children:[a("label",{htmlFor:"syncInviteGroup",className:"sr-only",children:"Team name"}),a(Te,{className:"peer-scope-input",id:"syncInviteGroup",placeholder:"Team name (e.g. my-team)",type:"text"}),a("label",{htmlFor:"syncInvitePolicy",className:"sr-only",children:"Join policy"}),a("div",{className:"sync-radix-select-host sync-actor-select-host",id:"syncInvitePolicyMount"}),a("div",{className:"sync-ttl-group",children:[a("label",{htmlFor:"syncInviteTtl",children:"Expires in"}),a(Te,{className:"peer-scope-input",defaultValue:"24",id:"syncInviteTtl",min:"1",style:{width:"64px"},type:"number"}),a("span",{children:"hours"})]}),a("button",{className:"settings-button",id:"syncCreateInviteButton",type:"button",children:"Create invite"})]}),a("label",{htmlFor:"syncInviteOutput",className:"sr-only",children:"Generated invite"}),a(Ki,{className:"feed-search",id:"syncInviteOutput",placeholder:"Invite will appear here",readOnly:!0,hidden:!0}),a("div",{className:"peer-meta",id:"syncInviteAdminHint"}),a("div",{className:"peer-meta",id:"syncInviteWarnings",hidden:!0})]})}function mB({contentHost:e,open:t,onOpenChange:n}){return a(Uw,{open:t,onOpenChange:n,triggerId:"syncPairingToggle",triggerClassName:"settings-button",closedLabel:"Show pairing command",openLabel:"Hide pairing command",contentId:"syncPairing",contentClassName:"pairing-card",contentHost:e,children:[a("div",{className:"peer-title",children:[a("strong",{children:"Pairing command"}),a("div",{className:"peer-actions",children:a("button",{className:"settings-button",id:"pairingCopy",type:"button",children:"Copy command"})})]}),a("div",{className:"pairing-body",children:a("pre",{id:"pairingPayload",style:{userSelect:"all"}})}),a("div",{className:"peer-meta",id:"pairingHint"})]})}function hB(e,t){mt(e,a(fB,{...t}))}function gB(e,t){mt(e,a(mB,{...t}))}function me(e){return String(e??"").trim()}function vB(e){return me(e).replace(/\s+/g," ").toLowerCase()}function yB(e){const t=me(e);return t?t.slice(0,8):"Unnamed device"}function Gw(e){return me(e?.last_error).toLowerCase()}function Hw(e){return e.includes("401")&&e.includes("unauthorized")}function Vw(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var bB={scope_filter:"sharing-domain membership",visibility_filter:"visibility",project_filter:"project filter"};function Kw(e){return e.device?.needs_local_approval?{state:"needs-your-approval",badgeLabel:"Needs your approval",description:"Another device already approved this pairing. Approve it here to finish the connection on both sides.",actionLabel:"Approve on this device"}:e.device?.waiting_for_peer_approval?{state:"waiting-for-other-device",badgeLabel:"Waiting on other device",description:"You already approved this pairing here. The other device still needs to approve this one before sync can work both ways.",actionLabel:null}:{state:"none",badgeLabel:null,description:null,actionLabel:null}}function _B(e){const t=Kw(e);return!me(e.device?.device_id)||e.device?.stale||e.hasAmbiguousCoordinatorGroup?!1:e.pairedLocally?t.state==="needs-your-approval":!0}function zw(e){const t=Array.isArray(e?.items)?e.items:[];if(!t.length)return{ok:!0,message:"Sync pass completed with no eligible devices.",warning:!1};const n=t.filter(i=>i&&i.ok===!1),r=t.filter(i=>Math.max(0,Number(i.opsSkipped??0))>0);if(!n.length){if(r.length){const i=r.reduce((s,c)=>s+Math.max(0,Number(c.opsSkipped??0)),0),o=RB(r.map(s=>s.skipped_out??null));return{ok:!0,message:`${i.toLocaleString()} outbound op${i===1?" was":"s were"} filtered: ${o}. No payload was sent for filtered data.`,warning:!0}}return{ok:!0,message:`Sync pass finished for ${t.length} device${t.length===1?"":"s"}.`,warning:!1}}return n.filter(i=>Ww(i)==="trust").length===n.length?{ok:!1,message:"This device no longer has two-way trust with the peer. Pair it again from the other device, or remove the stale local record if it should be gone.",warning:!0}:n.filter(i=>Ww(i)==="scope").length===n.length?{ok:!1,message:"Sync ran, but the peer is not authorized for one or more Spaces. Review legacy Space access for this device in Coordinator Administration, then sync again.",warning:!0}:n.length<t.length?{ok:!1,message:`${n.length} of ${t.length} device sync attempts failed. Open the affected device cards for the specific errors.`,warning:!0}:{ok:!1,message:me(n[0]?.error)||"Sync failed for at least one device.",warning:!0}}function Ww(e){if(e.failureCategory)return e.failureCategory;const t=Array.isArray(e.perScopeResults)?e.perScopeResults.filter(r=>r&&r.ok===!1).map(r=>r.failureCategory).filter(r=>!!r):[];if(t.length)return new Set(t).size===1?t[0]:"other";const n=me(e.error);return wB(n)?"trust":SB(n)?"scope":null}function wB(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function SB(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function CB(e){const t=me(e?.reason);return bB[t]??(t.replaceAll("_"," ")||"sync filters")}function RB(e){const t=new Map;for(const n of e){const r=CB(n),i=Math.max(0,Number(n?.skipped_count??0));i!==0&&t.set(r,(t.get(r)??0)+i)}return t.size?Array.from(t.entries()).sort((n,r)=>r[1]-n[1]||n[0].localeCompare(r[0])).map(([n,r])=>`${r.toLocaleString()} by ${n}`).join(", "):"sync filters"}function Jw(e){const t=me(e.localName);if(t)return t;const n=me(e.coordinatorName);return n||yB(me(e.deviceId))}function IB(e){const t=me(e.localName),n=me(e.coordinatorName);return t||n?!1:!!me(e.deviceId)}function kB(e){const t=Math.max(0,Number(e?.recent_ops?.in??0)),n=Math.max(0,Number(e?.recent_ops?.out??0));return t>0&&n>0?"bidirectional":n>0?"publishing":t>0?"subscribed":"none"}function Da(e){const t=me(e?.status?.peer_state);if(t==="offline"||t==="stale")return"offline";const n=Gw(e);return Hw(n)?"needs-repair":Vw(n)?"offline":e?.has_error||t==="degraded"?"needs-repair":t==="online"||e?.status?.fresh?"connected":"waiting"}function so(e){const t=e?.status||{},n=me(t.peer_state),r=Gw(e),i=me(t.sync_status)==="ok"||me(t.ping_status)==="ok";return n==="offline"||n==="stale"?{state:"offline",badgeLabel:"Offline",description:"This device was paired before, but it is offline right now.",isWarning:!0}:Hw(r)?{state:"needs-repairing",badgeLabel:"Needs re-pairing",description:"This device no longer accepts this one. Pair again from the other device, or remove this local record if it no longer belongs here.",isWarning:!0}:Vw(r)?{state:"offline",badgeLabel:"Offline",description:"This device is saved here, but none of its last known addresses are responding right now.",isWarning:!0}:i||n==="online"?{state:"mutual-trust",badgeLabel:"Two-way trust",description:"Both devices trust each other and sync can run in both directions.",isWarning:!1}:e?.has_error||n==="degraded"?{state:"needs-review",badgeLabel:"Needs review",description:"This device has a sync problem that needs review before you trust the current state again.",isWarning:!0}:{state:"trusted-by-you",badgeLabel:"Waiting on other device",description:"This device is already trusted here. Finish setup on the other device before sync can run both ways.",isWarning:!1}}var TB={missing_scope:"Missing scope id",sender_not_member:"Sender not a scope member",receiver_not_member:"Receiver not a scope member",stale_epoch:"Stale or revoked membership",scope_mismatch:"Scope mismatch",visibility_filter:"Visibility filter",project_filter:"Project filter"};function PB(e){const t=e?.scope_rejections,n=Math.max(0,Number(t?.total??0));if(!t||n===0)return{total:0,badgeLabel:null,reasons:[],lastAt:null};const r=[];for(const[i,o]of Object.entries(t.by_reason??{})){const s=Math.max(0,Number(o??0));if(s===0)continue;const c=i;r.push({reason:c,label:TB[c]??i,count:s})}return r.sort((i,o)=>o.count-i.count||i.label.localeCompare(o.label)),{total:n,badgeLabel:n===1?"1 sync rejection":`${n.toLocaleString()} sync rejections`,reasons:r,lastAt:t.last_at??null}}function Yw(e){return Array.isArray(e)?e.map(t=>me(t)).filter(t=>!!t):[]}function Xw(e,t){if(e.length===0)return t;const n=e.slice(0,3).join(", "),r=e.length-3;return r>0?`${n} +${r.toLocaleString()} more`:n}function tl(e,t){return e?e.replaceAll("_"," "):t}function NB(e){const t=(Array.isArray(e.authorized_scopes)?e.authorized_scopes:[]).map(r=>{const i=me(r.scope_id),o=me(r.label);if(!i&&!o)return null;const s=o||"Untitled Space",c=[tl(me(r.kind),"user"),tl(me(r.authority_type),"local"),`${tl(me(r.role),"member")} role`].filter(Boolean).join(" · ");return{scopeId:i||s,label:s,detail:c}}).filter(r=>r!=null),n=t.length;return{total:n,badgeLabel:n===1?"1 Space":n>1?`${n} Spaces`:"No Space access",isWarning:n===0,domains:t,emptyMessage:"No Space access grants exist for this device yet. Advanced project filters cannot send data by themselves."}}function Qw(e){const t=(Array.isArray(e.per_scope_sync)?e.per_scope_sync:[]).map(n=>{const r=me(n.scope_id),i=me(n.label);if(!r&&!i)return null;const o=i||"Untitled Space",s=me(n.last_applied_cursor),c=me(n.last_acked_cursor),l=n.bootstrapped===!0||s?"received":"pending",d=tl(me(n.authority_type),"local"),u=Number(n.membership_epoch??0),p=[`Scope id: ${r||"unknown"}`,`${d} authority`,Number.isFinite(u)?`membership epoch ${u}`:null,s?`last applied ${s}`:null,c?`last acknowledged ${c}`:null].filter(f=>!!f).join(" · ");return{scopeId:r||o,label:o,status:l,badgeLabel:l==="received"?"Received":"Pending",detail:p}}).filter(n=>n!=null);return{total:t.length,rows:t,emptyMessage:"No per-Space sync progress is available yet. Run sync after both devices have Space access."}}var EB=["personal","private","home","mine","me"],AB=["oss","open source","opensource","community","public"],xB=["work","client"],DB=["local","legacy","review"];function LB(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>me(t)??"").join(" ").toLowerCase()}function $B(e){return[e.scope_id,e.label,e.kind].map(t=>me(t)??"").join(" ").toLowerCase()}function Zw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gf(e,t){const n=LB(e);return t.some(r=>{const i=Zw(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function eS(e){return gf(e,EB)||gf(e,AB)}function OB(e){const t=$B(e);return DB.some(n=>{const r=Zw(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function jB(e){return!eS(e)&&(!OB(e)||gf(e,xB))}function MB(e){const t=Array.isArray(e.authorized_scopes)?e.authorized_scopes:[];if(!(me(e.discovered_via_group_id)||me(e.discovered_via_coordinator_id))||t.length===0)return{badgeLabel:null,detail:"",isVisible:!1,message:"",title:""};const n=t.some(eS),r=t.some(jB);return!n||r?{badgeLabel:null,detail:"",isVisible:!1,message:"",title:""}:{badgeLabel:"Review Space fit",detail:"Team discovery helps find the device, and advanced project filters only narrow already-authorized Spaces. Neither one grants missing work/client Space access.",isVisible:!0,message:"This Team-discovered device has personal or OSS Space access, but no separate work/client-like Space access. If this device is meant for work/client sync, grant that Space explicitly before treating sync as validated.",title:"Check this device's Space access"}}function FB(e,t){const n=e.map(r=>r.trim()).filter(Boolean);return n.length>0&&!n.includes("*")||t.length>0}function BB(e){const t=Yw(e?.effective_include),n=Yw(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${Xw(t,"all projects")}`,o=`Exclude filter: ${Xw(n,"no exclusions")}`,s=FB(t,n);return{hasAdvancedFilters:s,statusLabel:s?"Advanced filters active":"No advanced filters",sourceLabel:r,includeLabel:i,excludeLabel:o,summary:`${r}. ${i}; ${o}.`,note:"Advanced filters only narrow data after Space access; they never grant access to another Space."}}function qB(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=me(n?.display_name),i=me(n?.actor_id),o=vB(r);if(!r||!i||!o)return;const s=t.get(o)??{displayName:r,actorIds:[],includesLocal:!1};s.actorIds=[...s.actorIds,i],s.includesLocal=s.includesLocal||!!n?.is_local,t.set(o,s)}),[...t.values()].filter(n=>n.actorIds.length>1).sort((n,r)=>n.displayName.localeCompare(r.displayName))}function tS(e){const t=Array.isArray(e.actors)?e.actors:[],n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.duplicatePeople)?e.duplicatePeople:[],i=new Map;n.forEach(s=>{const c=me(s?.actor_id);c&&i.set(c,(i.get(c)??0)+1)});const o=new Set;return r.forEach(s=>{s.includesLocal&&s.actorIds.forEach(c=>{const l=t.find(d=>me(d?.actor_id)===c);!l||l.is_local||(i.get(c)??0)>0||o.add(c)})}),{visibleActors:t.filter(s=>!o.has(me(s?.actor_id))),hiddenLocalDuplicateCount:o.size}}var UB=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),GB=new Set(["pending","verifying","waiting"]);function HB(e){return(Array.isArray(e?.groups)?e.groups.map(t=>me(t)).filter(Boolean):[]).join(", ")||"none"}function VB(e){return me(e?.projects?.[0]?.display_name)||"the shared Project"}function KB(e,t){return t?.discovered_devices?.some(n=>n.needs_local_approval||n.waiting_for_peer_approval)?!0:e.some(n=>{const r=so(n).state;return r==="trusted-by-you"||r==="needs-repairing"})}function zB(e,t){return t?.enabled!==!0||t.daemon_state!=="ok"||t.daemon_running===!1?!1:e.some(n=>n.status?.sync_status==="ok"&&so(n).state==="mutual-trust"&&!Qw(n).rows.some(r=>r.status==="pending"))}function WB(e){return e.some(t=>me(t.status?.peer_state)==="online"&&so(t).state==="mutual-trust")}function JB(e,t){return t?.daemon_state==="offline-peers"||t?.daemon_state==="stale"||t?.daemon_state==="degraded"?!0:e.some(n=>{const r=me(n.status?.peer_state),i=so(n).state;return n.has_error===!0&&i!=="needs-repairing"||i==="offline"||i==="needs-review"||r==="offline"||r==="stale"||r==="degraded"})}function YB(e){if(e?.daemon_running===!1)return!0;const t=e?.daemon_state;return t!==void 0&&t!=="ok"&&t!=="offline-peers"&&t!=="stale"&&t!=="degraded"}function nS(e){const t=e.coordinator,n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.shareOperations)?e.shareOperations:[],i=Array.isArray(e.reconciliation?.items)?e.reconciliation.items:[],o=HB(t);if(e.status?.enabled===!1||t?.sync_enabled===!1)return{state:"disabled",badgeLabel:"Sync off",meta:`Team: ${o}. Coordinator presence does not move Project data while sync is off.`,nextAction:"Open Settings and turn on sync before expecting Team or Project data to update."};if(e.shareOperationsLoadError)return{state:"needs-attention",badgeLabel:"Refresh needed",meta:`Team: ${o}. Device diagnostics are available, but Project sharing status could not be refreshed.`,nextAction:"Refresh Team sync to retry loading Project sharing status."};const s=r.find(p=>p.lifecycle?.state==="needs_attention"),c=i.find(p=>p.state==="needs_attention");if(s)return{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${o}. A Project access update stopped and needs a retry.`,nextAction:"Retry the stopped Project access update below."};if(c)return{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${o}. Team access needs review before it can continue.`,nextAction:"Open Sharing, review Project access, then sync again."};const l=r.find(p=>{const f=p.lifecycle?.state;return f!==void 0&&UB.has(f)}),d=i.find(p=>{const f=p.state;return f!==void 0&&GB.has(f)});if(l||d){const p=l?VB(l):"the shared Project",f=l?.lifecycle?.primary_action?.kind,m=l?.lifecycle?.state==="revoking";return{state:"pending-setup",badgeLabel:m?"Removal pending":"Setup pending",meta:m?`Team: ${o}. Future access removal for ${p} is still pending.`:`Team: ${o}. Exact-Project setup is still pending and data delivery is not confirmed.`,nextAction:m?`Keep both devices online, then sync again to finish removing future access for ${p}.`:f==="retry_setup"?`Open Project sharing below and retry setup for ${p}.`:f==="copy_invite"?`Copy the invitation for ${p} and send it to the recipient.`:`Keep both devices online, then sync again to finish setup for ${p}.`}}if(YB(e.status))return{state:"needs-attention",badgeLabel:"Sync needs attention",meta:`Team: ${o}. The local sync service is not healthy, so Project data delivery is not confirmed.`,nextAction:"Review the sync status below, restart codemem if needed, then run Sync now again."};if(KB(n,t))return{state:"trust-blocked",badgeLabel:"Pairing needed",meta:`Team: ${o}. A device still needs two-way trust before Project data can sync.`,nextAction:"Review the device below and finish pairing or approval on both devices."};const u=me(t?.presence_status);return u==="not_enrolled"?{state:"not-enrolled",badgeLabel:"Not enrolled",meta:`Team: ${o}. This device is not enrolled with the coordinator.`,nextAction:"Paste a Team invite below, or ask a Team admin to enroll this device."}:u!=="posted"?{state:"unreachable",badgeLabel:t?.configured?"Unreachable":"Setup needed",meta:t?.configured?`Team: ${o}. The coordinator is not currently reachable and no healthy data-plane sync is confirmed.`:"Configure or join a Team before expecting Project data to sync.",nextAction:t?.configured?"Check the coordinator connection, then refresh Team sync.":"Paste a Team invite below, or set a coordinator URL in Settings → Device Sync."}:JB(n,e.status)?{state:"reachable",badgeLabel:"Check devices",meta:`Team: ${o}. The coordinator is reachable, but one or more paired devices are offline or degraded.`,nextAction:"Bring the paired devices online, check their sync errors, then run Sync now again."}:t?.sync_enabled===!0&&zB(n,e.status)?{state:"healthy",badgeLabel:"Healthy",meta:`Team: ${o}. Sync is enabled and a trusted device has a healthy data-plane connection.`,nextAction:null}:WB(n)?{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${o}. The coordinator and a paired device are reachable, but successful Project sync is not confirmed.`,nextAction:"Run Sync now, then review the device sync status below if delivery is still pending."}:{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${o}. The coordinator is reachable, but healthy Project data sync is not confirmed.`,nextAction:"Pair and approve a device, then run Sync now to confirm data delivery."}}function XB(e){return e.discovered?.stale?e.peer?Da(e.peer)!=="connected":!0:!1}function rS(e){return{id:`repair:${e.id}`,kind:"device-needs-repair",priority:10,title:e.title||`${e.name} needs attention`,summary:e.summary,actionLabel:"Open device",deviceId:e.id}}function vf(e){return{id:`review:${e.id}:${e.key||"default"}`,kind:"review-team-device",priority:20,title:`${e.name} is available to review`,summary:e.summary,actionLabel:"Open device",deviceId:e.id}}function QB(e){return{id:`name:${e.id}`,kind:"name-device",priority:30,title:`Name ${e.name}`,summary:e.summary,actionLabel:"Go to name field",deviceId:e.id}}function ZB(e){const t=me(e?.coordinator_url),n=Array.isArray(e?.groups)?e.groups:[];return t?n.some(r=>me(r))?e?.sync_enabled===!1?{reason:"sync_disabled",message:"Enable sync before pairing team devices."}:null:{reason:"coordinator_groups_empty",message:"Join or configure a team before pairing team devices."}:{reason:"coordinator_url_missing",message:"Configure a coordinator URL before pairing team devices."}}function eq(e,t){const n=new Map,r=i=>{const o=n.get(i)??{deviceId:i,localName:"",coordinatorName:"",peer:null,discovered:null};return n.set(i,o),o};return e.forEach(i=>{const o=me(i?.peer_device_id);if(!o)return;const s=r(o);s.peer=i,s.localName=me(i?.name)}),t.forEach(i=>{const o=me(i?.device_id);if(!o)return;const s=r(o);s.discovered=i,s.coordinatorName=me(i?.display_name)}),[...n.values()]}function tq(e){const t=Array.isArray(e.actors)?e.actors:[],n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.coordinator?.discovered_devices)?e.coordinator.discovered_devices:[],i=eq(n,r),o=e.duplicatePersonDecisions??{},s=qB(t).filter(l=>!o[[...l.actorIds].sort().join("::")]),c=[];return s.forEach(l=>{c.push({id:`duplicate:${l.actorIds.join(":")}`,kind:"possible-duplicate-person",priority:l.includesLocal?5:15,title:`Possible duplicate person: ${l.displayName}`,summary:l.includesLocal?"At least one entry is marked as you. Confirm whether these records represent the same person.":"Multiple people share this name. Confirm whether they should stay separate or be combined.",actionLabel:"Go to people",actorIds:l.actorIds})}),i.forEach(l=>{const d=Jw({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId}),u=l.peer?Da(l.peer):"waiting",p=l.peer?so(l.peer):null,f=me(l.discovered?.fingerprint),m=me(l.peer?.fingerprint);if(l.peer&&f&&m&&f!==m){c.push(rS({id:l.deviceId,name:d,title:`${d} needs review`,summary:"This device identity changed. Remove the older local record before reconnecting it."}));return}if(l.peer&&u==="needs-repair"){const v=p?.description||me(l.peer?.last_error)||"Sync needs review.";c.push(rS({id:l.deviceId,name:d,title:p?.state==="needs-repairing"?`${d} needs re-pairing`:`${d} needs review`,summary:v}))}l.peer&&p?.state==="trusted-by-you"&&c.push(vf({id:l.deviceId,key:"other-device-trust",name:d,summary:"You accepted this device. Finish onboarding on the other device so it trusts this one too."})),!l.peer&&l.discovered?.stale&&c.push(vf({id:l.deviceId,key:"stale-discovery",name:d,summary:"This device is no longer advertising fresh coordinator presence. Wait for it to check in again before connecting it here."})),!l.peer&&Array.isArray(l.discovered?.groups)&&l.discovered.groups.length>1&&c.push(vf({id:l.deviceId,key:"ambiguous-groups",name:d,summary:"This device appears in multiple coordinator groups. Review the team setup before approving it here."})),l.peer&&IB({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId})&&c.push(QB({id:l.deviceId,name:d,summary:"Give this device a friendly name so it is easier to recognize later."}))}),{primaryStatus:nS({status:e.status,coordinator:e.coordinator,peers:n,shareOperations:e.shareOperations,shareOperationsLoadError:e.shareOperationsLoadError,reconciliation:e.reconciliation}),summary:{connectedDeviceCount:n.filter(l=>Da(l)==="connected").length,seenOnTeamCount:r.length,offlineTeamDeviceCount:i.filter(l=>XB(l)).length},duplicatePeople:s,attentionItems:c.sort((l,d)=>l.priority-d.priority||l.title.localeCompare(d.title))}}var iS={actor:"person",actors:"people",actorAssignment:"person assignment",localActor:"you",peer:"device",peers:"devices",pairedLocally:"Connected on this device",discovered:"Seen on team",conflicts:"Needs review"};function hr(e){const t=document.getElementById(e);t&&t.remove()}var oS=!1;function nq(e){oS=e}var yf=!1;function rq(e){yf=e}var bf=!1;function iq(e){bf=e}var oq=new Set,_f=new Set,wf=new Set,aS="codemem-sync-duplicate-person-decisions";function aq(e){const t=String(e||"").trim();t&&(_f.add(t),wf.add(t),oq.add(t))}function Sf(e){const t=String(e||"").trim();return!!t&&_f.has(t)}function sq(e){const t=String(e||"").trim();t&&_f.delete(t)}function cq(e){const t=String(e||"").trim();return!t||!wf.has(t)?!1:(wf.delete(t),!0)}function Cf(){try{const e=localStorage.getItem(aS);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function sS(e){try{localStorage.setItem(aS,JSON.stringify(e))}catch{}}function cS(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function lq(){return Cf()}function dq(e,t){const n=cS(e);if(!n)return;const r=Cf();r[n]=t,sS(r)}function uq(e){const t=cS(e);if(!t)return;const n=Cf();delete n[t],sS(n)}function lS(e){return e.replace(/\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b/g,"$1.#.#")}function dS(e){const t=String(e||"");return t?lS(t):""}function pq(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function fq(e,t){const n=String(e?.relatedPeerDeviceId??"").trim();return n?t.some(r=>String(r?.peer_device_id??"").trim()===n):!1}function nl(e){if(!e||typeof e!="object")return"Unknown person";const t=String(e.display_name||"").trim();return t||String(e.actor_id||"Unknown person")}function Rf(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":nl(e)}function mq(e){return(Array.isArray(C.lastSyncPeers)?C.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function hq(){return tS({actors:C.lastSyncActors,peers:C.lastSyncPeers,duplicatePeople:C.lastSyncViewModel?.duplicatePeople}).visibleActors}function uS(e){return hq().filter(t=>String(t?.actor_id||"")!==e)}function gq(e,t){const n=uS(t).find(r=>String(r?.actor_id||"")===e);return!e||!n?"Choose which person should keep these devices.":`Merge into ${Rf(n)}. Assigned devices move now; existing memories keep their current provenance.`}function If(e,t){if(e){if(e.textContent="",!t.length){e.hidden=!0;return}e.hidden=!1,t.slice(0,2).forEach(n=>{const r=Os("div","sync-action"),i=Os("div","sync-action-text");i.textContent=n.label,i.appendChild(Os("span","sync-action-command",n.command));const o=Os("button","settings-button sync-action-copy","Copy");o.addEventListener("click",()=>Uo(n.command,o)),r.append(i,o),e.appendChild(r)})}}function pS(e,t){return t&&e.error_redacted===!0}function vq(e){return e?{action:t=>Ar({severity:"error",subsystem:"sync",trigger:t})}:{}}function fS(){const e=document.getElementById("syncAttempts");if(!e)return;const t=C.lastSyncAttempts,n=String(C.lastSyncStatus?.daemon_state||"").trim();if(!Array.isArray(t)||!t.length){ri(e,oB());return}const r=sB(n,t.slice(0,5).some(o=>o.status==="error")),i=t.slice(0,5).map(o=>{const s=o.started_at||o.started_at_utc||"",c=String(o.peer_device_id||"").trim(),l=Array.isArray(C.lastSyncPeers)?C.lastSyncPeers.find(m=>String(m?.peer_device_id||"")===c):null,d=String(l?.name||"").trim()||(c?c.slice(0,8):"unknown"),u=o.status==="error",p=[],f=Ho();if(u&&o.error){const m=String(o.error);p.push(f?lS(m):m),pS(o,f)&&p.push("Turn off Redact in Advanced diagnostics to reveal the full error.")}return!u&&(o.ops_in||o.ops_out)&&p.push(`${o.ops_in??0} in · ${o.ops_out??0} out`),!f&&o.address&&p.push(o.address),{status:o.status||"unknown",peerLabel:d,detail:p.join(" · "),startedAt:s?Vr(s):"",...vq(u),...pS(o,f)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}});pB(e,i,r)}function yq(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncAttempts"),n=document.getElementById("syncMeta"),r=document.getElementById("syncActions");e&&ri(e,iB()),t&&ri(t,aB()),n&&(n.textContent="Advanced diagnostics are unavailable right now. Refresh the page first. If that still fails, verify the local sync service and retry once it responds again."),If(r,[])}function co(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function bq(e){const t=String(e?.state??"clear"),n=e?.stale_peer_rows??{},r=e?.access_cleanup_ops??{},i=co(n.would_remove),o=co(n.ambiguous),s=co(r.applied),c=co(r.source_authored);return t==="cleanup_pending"||i>0?`${i} pending removal`:t==="needs_review"||o>0?`${o} needs review`:t==="cleanup_applied"||s>0?`${s} applied`:t==="cleanup_announced"||c>0?`${c} announced`:"Clear"}function mS(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncMeta"),n=document.getElementById("syncActions");if(!e)return;hr("syncDiagSkeleton");const r=C.lastSyncStatus;if(!r){ri(e,rB()),If(n,[]),t&&(t.textContent="Loading advanced sync diagnostics…");return}const i=r.peers||{},o=r.ping||{},s=r.sync||{},c=r.last_sync_at||r.last_sync_at_utc||null,l=o.last_ping_at||r.last_ping_at||ZF(i)||null,d=r.last_sync_error||"",u=r.last_ping_error||"",p=Number(r.pending||0),f=String(r.daemon_detail||""),m=String(r.daemon_state||"unknown"),v=r.retention||{},g=r.cleanup_diagnostics,h=g?.stale_peer_rows??{},b=co(h.would_remove),w=co(h.ambiguous),_=v.enabled===!0,R=Number(v.last_deleted_ops||0),I=v.last_run_at||null,T=String(v.last_error||""),A=m==="offline-peers"?"Offline peers":m==="needs_attention"?"Needs attention":m==="rebootstrapping"?"Rebootstrapping":wb(m),O=m==="disabled"||r.enabled===!1,F=Object.keys(i).length,N=!O&&F===0;if(t){const G=O?["Advanced sync is off on this device","Turn on sync in Settings → Device Sync when you want pairing payloads, peer status, and recent attempt details here"]:N?["Advanced sync is ready but idle","Use Show pairing command under People & devices to connect another device, then this panel will start showing live peer status and recent attempts"]:[`Advanced state: ${A}`,`Peers: ${F}`,c?`Last sync: ${sr(zi(c))} ago`:"Last sync: never"];m==="offline-peers"&&G.push("All peers are currently offline; sync will resume automatically"),f&&m==="stopped"&&G.push(`Detail: ${f}`),f&&(m==="needs_attention"||m==="rebootstrapping")&&G.push(`Detail: ${f}`),_&&G.push(I?`Retention last ran ${sr(zi(I))} ago (approx oldest-first)`:"Retention enabled"),b>0?G.push(`${b.toLocaleString()} stale peer rows pending cleanup`):w>0&&G.push(`${w.toLocaleString()} stale peer rows retained because safe cleanup could not be proven`),t.textContent=G.join(" · ")}const L=O?[{label:"State",value:"Disabled"},{label:"Mode",value:"Optional"},{label:"Pending events",value:p},{label:"Last sync",value:"Not running"}]:N?[{label:"State",value:"No peers"},{label:"Mode",value:"Ready to pair"},{label:"Pending events",value:p},{label:"Last sync",value:"Waiting for first peer"}]:[{label:"State",value:A},{label:"Pending events",value:p},{label:"Last sync",value:c?`${sr(zi(c))} ago`:"never"},{label:"Last peer ping",value:l?`${sr(zi(l))} ago`:"never"},{label:"Retention",value:_?I?`${R.toLocaleString()} ops last run (approx)`:"Enabled":"Disabled"}];!O&&!N&&(d||u)&&L.push({label:[d,u].filter(Boolean).join(" · "),value:"Errors"}),!O&&!N&&s.seconds_since_last&&L.push({label:"Since last sync",value:`${s.seconds_since_last}s`}),!O&&!N&&o.seconds_since_last&&L.push({label:"Since last peer ping",value:`${o.seconds_since_last}s`}),!O&&_&&T&&L.push({label:T,value:"Retention"}),!O&&!N&&g&&L.push({label:"Cleanup",value:bq(g)}),uB(e,L);const D=[];N||m==="offline-peers"||(m==="stopped"?(D.push({label:"Sync daemon is stopped. Start it.",command:"codemem serve start"}),D.push({label:"Run one sync pass now.",command:"codemem sync once"})):m==="needs_attention"?D.push({label:"Sync needs manual attention before reset can continue.",command:"codemem sync doctor"}):m==="rebootstrapping"?D.push({label:"Sync is rebuilding state in the background.",command:"codemem sync status"}):d||u||m==="error"?(D.push({label:"Sync reports errors. Restart now.",command:"codemem serve restart && codemem sync once"}),D.push({label:"Run doctor for the root cause.",command:"codemem sync doctor"})):!O&&!N&&p>0&&D.push({label:"Pending sync work detected. Run one pass now.",command:"codemem sync once"})),!O&&w>0?D.push({label:"Some stale peer rows were retained because cleanup was ambiguous.",command:"codemem sync doctor"}):!O&&b>0&&D.push({label:"Stale peer rows are eligible for cleanup. Run one sync pass now.",command:"codemem sync once"}),If(n,D)}var _q="syncRedactMount",wq="syncRedactLabel",hS=()=>{};function Sq(e){hS=e}var kf=()=>{};function Tf(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;gB(e,{contentHost:t,open:C.syncPairingOpen,onOpenChange:r=>{if(ZN(r),Tf(),r){const i=document.getElementById("pairingPayload"),o=document.getElementById("pairingHint");i&&qw(i,o,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}kf()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=C.pairingCommandRaw;r&&await Uo(r,n)})}function Pf(){Tf();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;qw(e,t,nB(C.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!C.pairingCommandRaw)}function gS(){const e=document.getElementById(_q);e&&mt(e,y(Gi,{"aria-labelledby":wq,checked:Ho(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{eE(t),gS(),kf(),mS(),hS(),fS(),Pf()},thumbClassName:"sync-redact-switch-thumb"}))}function Cq(e){kf=e,Tf(),gS()}function Rq(e){e.classList.add("sync-shake"),e.addEventListener("animationend",()=>e.classList.remove("sync-shake"),{once:!0})}function lo(e,t){e.classList.add("sync-field-error");const n=e.parentElement?.querySelector(".sync-field-hint");n&&n.remove();const r=document.createElement("div");return r.className="sync-field-hint",r.textContent=t,e.insertAdjacentElement("afterend",r),Rq(e),e.addEventListener("input",()=>La(e),{once:!0}),!1}function La(e){e.classList.remove("sync-field-error");const t=e.parentElement?.querySelector(".sync-field-hint");t&&t.remove()}function _t(e,t){if(e instanceof Error){const n=e.message;return n.includes("fetch")||n.includes("network")||n.includes("Failed to fetch")?"Network error — check your connection and try again.":n}return t}var ii=new Map,Nf=null,Iq={operation_device_binding_missing:"The accepted device has not been linked yet.",operation_not_found:"This sharing operation is no longer available.",operation_scope_mismatch:"The invitation no longer matches the reviewed project access.",operation_state_invalid:"The invitation is no longer in a recoverable state.",reassign_capability_required:"A participating device must be updated before setup can continue."};function kq(e){const t=e instanceof Error?e.message:String(e);return Iq[t]??"Setup could not be retried. Review diagnostics for details."}function Tq(e){const t=new Map;for(const n of e){const r=n.person.actor_id;t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function Pq(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function Ef(e){switch(e){case"waiting_for_acceptance":return"Invitation pending";case"active":return"Sharing";case"revoking":return"Removing sharing";case"revoked":return"Previously shared";case"cancelled":return"Invitation cancelled";default:return"Sharing setup"}}function Nq({operation:e,onAdvance:t,onLoadOperation:n,onReload:r,copyText:i}){const[o,s]=x(!1),[c,l]=x(()=>ii.get(e.operation_id)??null),d=B(null),u=e.lifecycle.primary_action;V(()=>{Nf!==e.operation_id||!d.current||(Nf=null,d.current.focus())},[c?.message,e.operation_id]);async function p(g){s(!0);try{let h=g;if(!h&&n){const w=(await n(e.operation_id)).lifecycle.primary_action;w?.kind==="copy_invite"&&(h=w.invite_link)}if(!h)throw new Error("Invitation is no longer available. Refresh the status.");await(i??(w=>navigator.clipboard.writeText(w)))(h);const b={message:"Invite copied.",tone:"success"};ii.set(e.operation_id,b),l(b)}catch(h){const b={message:h instanceof Error?h.message:"Invite could not be copied.",tone:"warning"};ii.set(e.operation_id,b),l(b)}finally{s(!1)}}async function f(){s(!0);try{const g=await t(e.operation_id),h=g.lifecycle.state==="active"?{message:"Setup complete.",tone:"success"}:g.lifecycle.state==="needs_attention"?{message:"Setup still needs attention.",tone:"warning"}:{message:`Retry started. ${g.lifecycle.label}.`,tone:"success"};ii.set(e.operation_id,h),Nf=e.operation_id,l(h),await r()}catch(g){const h={message:kq(g),tone:"warning"};ii.set(e.operation_id,h),l(h),queueMicrotask(()=>d.current?.focus())}finally{s(!1)}}function m(){const g=e.projects.map(h=>h.project_id?.trim()).filter(h=>!!h);if(g.length!==e.projects.length){const h={message:"The original project selection is unavailable. Refresh Projects and try again.",tone:"warning"};ii.set(e.operation_id,h),l(h);return}if(!_s(g,e.person.display_name)){const h={message:"Project sharing is unavailable. Refresh Projects and try again.",tone:"warning"};ii.set(e.operation_id,h),l(h)}}function v(){if(u){if(u.kind==="copy_invite"){p(u.invite_link);return}if(u.kind==="retry_setup"){f();return}m()}}return a("section",{"aria-label":`${Ef(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[a("div",{className:"peer-scope-summary",children:Ef(e.lifecycle.state)}),a("ul",{"aria-label":`${Ef(e.lifecycle.state)} projects`,className:"peer-scope-chips",children:e.projects.map((g,h)=>a("li",{className:"peer-scope-chip",children:g.display_name},`${g.display_name}:${h}`))}),a("div",{className:"peer-scope-summary",children:e.lifecycle.label}),a("div",{className:"peer-meta",role:e.lifecycle.state==="needs_attention"?"alert":void 0,children:e.lifecycle.explanation}),u?a("div",{className:"peer-actions",children:a("button",{"aria-busy":o,className:"settings-button",disabled:o,type:"button",onClick:v,children:o?u.kind==="copy_invite"?"Copying…":"Retrying…":u.label})}):null,c?a("div",{ref:d,className:`settings-note ${c.tone==="warning"?"project-attention-note":""}`,role:"status",tabIndex:-1,children:c.message}):null]})}function Eq({operations:e,...t}){const n=e[0].person,r=Pq(e);return a("article",{"aria-label":`Project sharing with ${n.display_name}`,className:"peer-card project-share-person-group",children:[a("h3",{className:"device-row-name",children:n.display_name}),r.length>0?a("ul",{"aria-label":`Devices for ${n.display_name}`,className:"peer-scope-rejections-list",children:r.map(i=>a("li",{children:i.display_name},i.device_id))}):null,e.map(i=>a(Nq,{operation:i,...t},i.operation_id))]})}function Aq(e){return e.operations.length===0?null:a("div",{className:"project-share-person-groups",children:Tq(e.operations).map(t=>a(Eq,{...e,operations:t},t[0].person.actor_id))})}function xq(e,t){mt(e,a(Aq,{...t}))}function vS({title:e,detail:t}){return a("div",{className:"sync-empty-state",role:"status","aria-live":"polite","aria-atomic":"true",children:[a("strong",{children:e}),a("span",{children:t})]})}function Dq(e){return e<=0?"Represents you across your own devices.":`Represents you across your own devices. ${e} unresolved duplicate ${e===1?"entry is":"entries are"} hidden until reviewed in Needs attention.`}function Lq({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const o=String(e.actor_id||""),s=nl(e),c=mq(o),l=uS(o),d=l.map(D=>String(D.actor_id||"")).join("|"),[u,p]=x(s),[f,m]=x(!1),[v,g]=x("Rename"),[h,b]=x(!1),[w,_]=x("Merge into selected person"),[R,I]=x(""),[T,A]=x(!1);V(()=>{p(s),m(!1),g("Rename"),b(!1),_("Merge into selected person"),I(""),A(!1)},[o,c,t,s,d]);const O=l.length?gq(R,o):"No other people are available yet. Create another person first if you need to merge duplicates.",F=[{label:"Merge into person",value:""},...l.map(D=>{const G=String(D.actor_id||"");return{label:D.is_local?Rf(D):nl(D),value:G}})];async function N(){const D=u.trim();if(!D)return;m(!0),g("Saving…");let G=!1;try{await n(o,D),G=!0}catch{g("Retry rename")}finally{m(!1),G&&g("Rename")}}async function L(){if(!R)return;const D=l.find(q=>String(q.actor_id||"")===R);if(!D||!await hn({title:`Merge ${s} into ${nl(D)}?`,description:"Assigned devices move now, but older memories keep their current stamped provenance for now.",confirmLabel:"Merge people",cancelLabel:"Keep separate",tone:"danger"}))return;b(!0),_("Merging…");let G=!1;try{await r(R,o),G=!0}catch{_("Retry merge")}finally{b(!1),G&&_("Merge into selected person")}}return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:[a("div",{className:"actor-title",children:[a("strong",{children:Rf(e)}),a("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?Dq(t):void 0,children:e.is_local?"You":`${c} device${c===1?"":"s"}`})]}),e.is_local?null:a("div",{className:"peer-meta",children:[c," assigned device",c===1?"":"s"]})]}),a("div",{className:"actor-actions",children:e.is_local?a("div",{className:"peer-meta",children:"Rename yourself in config"}):a(z,{children:[a(Te,{"aria-label":`Rename ${s}`,className:"peer-scope-input actor-name-input",disabled:f||h,type:"text",value:u,onInput:D=>p(D.currentTarget.value),onKeyDown:D=>Li(D,{onSubmit:()=>{N()},disabled:f||h||!u.trim()})}),a("button",{type:"button",className:"settings-button","data-primary-action":"true",disabled:f||h,onClick:()=>{N()},children:v}),a("button",{type:"button",className:"settings-button danger",disabled:f||h,onClick:async()=>{await hn({title:`Remove ${s}?`,description:"This deactivates the person and unassigns their devices. Existing memories keep their current attribution.",confirmLabel:"Remove person",cancelLabel:"Keep",tone:"danger"})&&await i(o)},children:"Remove"}),a("button",{type:"button",className:"settings-button",disabled:f||h,onClick:()=>A(D=>!D),children:T?"Hide duplicate cleanup":"Show duplicate cleanup"}),T?a(z,{children:[a("div",{className:"peer-meta actor-merge-note",children:"Use this only when combining duplicate people into one."}),a("div",{className:"actor-merge-controls",children:[a(ar,{ariaLabel:`Merge ${s} into another person`,contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:h||l.length===0,itemClassName:"sync-radix-select-item",onValueChange:I,options:F,placeholder:"Merge into person",triggerClassName:"sync-radix-select-trigger sync-actor-select actor-merge-select",value:R,viewportClassName:"sync-radix-select-viewport"}),a("button",{type:"button",className:"settings-button",disabled:h||l.length===0||!R,onClick:()=>{L()},children:w})]}),a("div",{className:"peer-meta actor-merge-note",children:O})]}):null]})})]})}function $q({actors:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){return e.length?a(z,{children:e.map(o=>{const s=String(o.actor_id||o.display_name||o.is_local||"");return a(Lq,{actor:o,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):a(vS,{detail:"Create a named person here for legacy provenance, then confirm device Identity ownership in Devices.",title:"No people set up yet."})}function Oq(e,t){mt(e,a($q,{...t}))}function jq(e){return e.filter(t=>String(t.origin_device_id||"").trim())}function Mq(e){const t=e.find(n=>String(n.last_seen_at||"").trim());return t?.last_seen_at?`Detected from older synced memories. Latest memory: ${Vr(String(t.last_seen_at).trim())}`:"Detected from older synced memories not yet attached to a current device."}function Fq({devices:e}){return a(z,{children:Mq(e)})}function Bq(e){const t=String(e.origin_device_id||"").trim(),n=Number(e.memory_count||0);return{label:n>0?`${t} (${n} memories)`:t,value:t}}function qq(e){const t=jq(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),ao(e.mount),ao(e.meta);return}const n=t.map(Bq),r=n.some(i=>i.value===e.value)?e.value:n[0]?.value||"";r!==e.value&&e.onValueChange(r),e.panel.hidden=!1,mt(e.mount,a(ar,{ariaLabel:"Legacy device",contentClassName:"sync-radix-select-content sync-legacy-select-content",id:"syncLegacyDeviceSelect",itemClassName:"sync-radix-select-item",onValueChange:e.onValueChange,options:n,triggerClassName:"sync-radix-select-trigger sync-legacy-select",value:r,viewportClassName:"sync-radix-select-viewport"})),mt(e.meta,a(Fq,{devices:t}))}var Uq={online:"Online",offline:"Offline",degraded:"Degraded",attention:"Action required",syncing:"Syncing",unknown:"Status unknown"};function Gq({state:e,size:t=8,"aria-label":n}){const r=n??Uq[e];return a("span",{"aria-label":r,className:`presence-pip presence-pip--${e}`,role:"img",style:`--presence-pip-size: ${t}px`})}function oi({feedback:e}){return e?.message?a("div",{className:`sync-inline-feedback ${e.tone}`,role:e.tone==="warning"?"alert":"status","aria-live":e.tone==="warning"?"assertive":"polite","aria-atomic":"true",children:e.message}):null}function Hq(){return a("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[a("title",{children:"Chevron"}),a("path",{d:"m9 18 6-6-6-6"})]})}function Vq(e){switch(Da(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var rl=null,yS=0,Af=new Set;function bS(e){if(rl!==e){rl=e,yS+=1;for(const t of Af)t(yS)}}function Kq(){const[,e]=x(0);return V(()=>(Af.add(e),()=>{Af.delete(e)}),[]),rl}var zq={bidirectional:{glyph:"↕",label:"Bidirectional sync in the last 24 hours"},publishing:{glyph:"↑",label:"Publishing only in the last 24 hours"},subscribed:{glyph:"↓",label:"Subscribed only in the last 24 hours"},none:null};function _S(e,t){if(!e)return"the selected Identity";const n=t.find(r=>r.actor_id===e);return String(n?.display_name||n?.actor_display_name||"the selected Identity")}function Wq(e,t,n,r=!1,i=!1,o=!1){if(i)return{status:"unavailable",summary:"Authoritative Identity status is unavailable because the inventory is incomplete.",detail:"This installation has more device evidence than Advanced can safely classify. Ownership is not shown from a partial inventory.",actionLabel:"Review Identity inventory in Devices"};if(r||o&&!e)return{status:"unavailable",summary:"Authoritative Identity status is temporarily unavailable.",detail:"Refresh before relying on ownership details. Advanced actor_id values remain suggestions or provenance only.",actionLabel:"Review Identity in Devices"};if(e?.state==="configured")return{status:"configured",summary:`Authoritative Identity: ${_S(e.identityId,n)}.`,detail:"This result comes from an active identity_devices binding. Advanced actor_id values are not authoritative ownership.",actionLabel:"Review or rebind in Devices"};if(e?.state==="pairing_required")return{status:"pairing_required",summary:"Identity setup is blocked until pairing is complete.",detail:"Pairing establishes sync trust; it does not establish device ownership.",actionLabel:"Review setup in Devices"};if(e?.state==="conflicted")return{status:"conflicted",summary:"Identity ownership needs review.",detail:"Conflicting device evidence failed closed. Advanced actor_id values cannot resolve ownership.",actionLabel:"Review conflict in Devices"};const s=e?.suggestedIdentityId??t;return{status:e?.state??"unavailable",summary:s?`Suggested Identity: ${_S(s,n)}.`:"No authoritative Identity binding is configured.",detail:"sync_peers.actor_id is only a suggestion or hint until you confirm an identity_devices binding in Devices.",actionLabel:"Set up Identity in Devices"}}function Jq(e){C.pendingDeviceIdentityFocus=e?.trim()||null,window.location.hash="devices"}function Yq(e){return e?e.authorized?"Private same-person sync is limited to your personal Space. Team and org Spaces do not carry your private memories.":"Private same-person sync is blocked until this device is granted an allowed personal Space.":"Private same-person sync is limited to an allowed personal Space; team or org Spaces do not carry your private memories."}function Xq(){window.location.hash="advanced/teams"}function xf(e=C.lastSyncCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function Qq({peer:e,onRemove:t,onRename:n,onSync:r}){const i=String(e.peer_device_id||""),o=e.name||(i?i.slice(0,8):"unknown"),s=e.name||i||o,c=so(e),l=zq[kB(e)],d=e.status||{},u=NB(e),p=Sf(i),f=p&&u.total===0,m=MB(e),v=PB(e),g=Qw(e),h=e.project_scope||{},b=BB(h),w=pq(e.addresses),_=Array.isArray(e.addresses)?Array.from(new Set(e.addresses.filter(Boolean).map(ne=>String(ne)))):[],R=Number(e.address_count??0),I=Number.isFinite(R)&&R>0?R:0,T=_.length?_.map(ne=>Ho()?dS(ne):ne).join(" · "):I>0?`${I} ${I===1?"address":"addresses"} hidden`:"No addresses",A=C.lastDeviceIdentityInventory?.items.find(ne=>ne.deviceId===i||ne.evidenceDeviceIds.includes(i)),O=Wq(A,String(e.actor_id||"")||null,C.lastSyncActors,C.deviceIdentityInventoryLoadError,C.lastDeviceIdentityInventory?.truncated===!0,C.lastDeviceIdentityInventory?.coordinatorEvidence.availability==="unavailable"),F=String(d.last_sync_at||d.last_sync_at_utc||""),N=String(d.last_ping_at||d.last_ping_at_utc||""),L=e.discovered_via_group_id?`Discovery: seen through coordinator group ${e.discovered_via_group_id}. Discovery helps find devices; Space access above decides data access.`:e.discovered_via_coordinator_id?`Discovery: seen through coordinator ${e.discovered_via_coordinator_id}. Discovery helps find devices; Space access above decides data access.`:null,D=cq(i),G=B(null),[q,$]=x(o),[E,S]=x(()=>C.syncPeerFeedbackById.get(i)??null),[M,H]=x(!1),[U,re]=x("Save name"),[oe,ie]=x(!1),[se,ue]=x(!1),[Pe,Ie]=x("Remove device");V(()=>{p&&u.total>0&&sq(i)},[u.total,i,p]),V(()=>{$(o),S(C.syncPeerFeedbackById.get(i)??null),H(!1),re("Save name"),ie(!1),ue(!1),Ie("Remove device")},[o,e.actor_id,i]),V(()=>{!D||!G.current||queueMicrotask(()=>G.current?.scrollIntoView({block:"center",behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}))},[D]);async function le(){if(!i)return;const ne=q.trim();if(!ne){const xe={message:"Enter a friendly name for this device.",tone:"warning"};S(xe),C.syncPeerFeedbackById.set(i,xe),document.querySelector(`[data-device-name-input="${CSS.escape(i)}"]`)?.focus();return}H(!0),re("Saving…");try{const xe=await n(i,ne);S(xe),C.syncPeerFeedbackById.set(i,xe),re("Save name")}catch{re("Retry")}finally{H(!1)}}async function ve(){if(f){const ne=xf();if(!await hn({title:`Sync ${o} before advanced rule review?`,description:ne?"This manual sync will use the current legacy Space access and advanced filters until you review them in Coordinator Administration.":"This manual sync will use the current legacy Space access and advanced filters until a coordinator operator reviews them in Coordinator Administration.",confirmLabel:"Sync anyway",cancelLabel:ne?"Review legacy Team/Space setup first":"Cancel"}))return}ie(!0);try{const ne=await r(e,w);S(ne),ne&&C.syncPeerFeedbackById.set(i,ne)}finally{ie(!1)}}async function X(){if(!i||!await hn({title:`Remove device ${s}?`,description:"This removes the local record for this paired device on this machine.",confirmLabel:"Remove device",cancelLabel:"Keep device",tone:"danger"}))return;ue(!0),Ie("Removing…");let ne=!1;try{await t(i,s),ne=!0}catch{Ie("Retry remove")}finally{ue(!1),ne&&Ie("Remove device")}}const ce=Kq()===i&&i!=="",be=`device-drawer-${i||"unknown"}`,fe=Vq(e),We=F?`Sync: ${Vr(F)}`:"Sync: never",he=xf(),W=`${ce?"Collapse":"Expand"} device ${o}`;return a(zo,{asChild:!0,open:ce,onOpenChange:ne=>{ne?bS(i):rl===i&&bS(null)},children:a("div",{ref:G,className:"peer-card","data-peer-device-id":i||void 0,children:[a(Cu,{asChild:!0,children:a("button",{"aria-label":W,className:"device-row-head device-row-head--trigger",type:"button",children:[a(Gq,{state:fe}),a("span",{className:"device-row-name",title:i||void 0,children:o}),l?a("span",{"aria-label":l.label,className:"peer-direction",role:"img",title:l.label,children:l.glyph}):null,a("span",{className:"device-row-chips",children:[a("span",{className:`badge ${c.isWarning?"badge-offline":"badge-online"}`,children:c.badgeLabel}),f?a("span",{className:"badge actor-badge",children:"Review advanced rules"}):null,a("span",{className:`badge ${u.isWarning?"badge-offline":"actor-badge"}`,title:"Spaces are the hard access boundary; advanced filters only narrow inside them.",children:u.badgeLabel}),v.badgeLabel?a("span",{className:"badge badge-offline",title:"Inbound ops rejected by the sharing-domain scope gate. Expand for reason codes.",children:v.badgeLabel}):null,m.badgeLabel?a("span",{className:"badge badge-offline",title:"Review whether explicit Space access matches this device's intended role.",children:m.badgeLabel}):null,e.discovered_via_group_id?a("span",{className:"badge actor-badge",title:`Discovered through coordinator group ${e.discovered_via_group_id}`,children:`via ${e.discovered_via_group_id}`}):null]}),a("span",{className:"device-row-meta",children:We}),a("span",{"aria-hidden":"true",className:"device-row-chevron",children:a(Hq,{})})]})}),a(Wo,{"aria-label":`Device actions for ${o}`,className:"device-row-drawer",id:be,children:[a("div",{className:"peer-actions",children:[a("button",{type:"button",className:"settings-button",disabled:oe,onClick:()=>{ve()},title:w?void 0:"Address details are hidden; sync will target this device by ID.",children:oe?"Syncing…":"Sync now"}),a("div",{className:"sync-labeled-field",children:[a("label",{className:"sync-labeled-field-caption",htmlFor:`device-name-${i||"unknown"}`,children:"Device name"}),a(Te,{"aria-label":`Friendly name for ${o}`,className:"peer-scope-input","data-device-name-input":i||void 0,disabled:M,id:`device-name-${i||"unknown"}`,placeholder:"Friendly device name",type:"text",value:q,onInput:ne=>$(ne.currentTarget.value)})]}),a("button",{type:"button",className:"settings-button",disabled:M,onClick:()=>{le()},children:U}),a("button",{type:"button",className:"settings-button danger",disabled:se,onClick:()=>{X()},children:Pe})]}),a("div",{className:"peer-scope",children:[D?a("div",{className:"peer-meta",children:he?"Review this device's legacy Space access and advanced rules in Coordinator Administration if the defaults are too broad.":"A coordinator operator can review this device's legacy Space access and advanced rules in Coordinator Administration if the defaults are too broad."}):f?a("div",{className:"peer-meta",children:"Advanced rule review is still pending for this device."}):null,a("div",{className:"peer-scope-summary",children:"Device details"}),a("div",{className:"peer-addresses",children:T}),L?a("div",{className:"peer-meta",children:L}):null,a("div",{className:"peer-meta",children:[F?`Sync: ${Vr(F)}`:"Sync: never",N?`Ping: ${Vr(N)}`:"Ping: never"].join(" · ")}),a("div",{className:"peer-scope-summary",children:"Space access"}),a("div",{className:"peer-meta",children:u.total>0?"These Spaces are the hard access boundary for this device.":u.emptyMessage}),u.domains.length>0?a("ul",{className:"peer-scope-chips","aria-label":"Authorized Spaces",children:u.domains.map(ne=>a("li",{className:"peer-scope-chip",title:ne.detail,children:ne.label},ne.scopeId))}):null,m.isVisible?a("div",{className:"settings-note",role:"status",children:[a("strong",{children:m.title}),a("div",{children:m.message}),a("div",{children:m.detail})]}):null,a("div",{className:"peer-meta",children:b.note}),a("div",{className:"peer-scope-summary",children:"Space sync progress"}),a("div",{className:"peer-meta",children:g.total>0?"Per-Space progress for this device. Open details to see technical identifiers.":g.emptyMessage}),g.rows.length>0?a("ul",{className:"peer-scope-rejections-list","aria-label":"Per-Space sync progress",children:g.rows.map(ne=>a("li",{title:ne.detail,children:[a("span",{className:"peer-scope-rejection-label",children:ne.label}),a("span",{className:`badge ${ne.status==="received"?"badge-online":"actor-badge"}`,children:ne.badgeLabel})]},ne.scopeId))}):null,v.total>0?a("div",{className:"peer-scope-rejections","data-peer-rejection-count":v.total,children:[a("div",{className:"peer-scope-summary",children:"Sharing-rule rejections (24h)"}),a("div",{className:"peer-meta",children:"Inbound ops the local fail-closed gate refused. Diagnostics never expose op payloads."}),a("ul",{className:"peer-scope-rejections-list",children:v.reasons.map(ne=>a("li",{children:[a("span",{className:"peer-scope-rejection-label",children:ne.label}),a("span",{className:"peer-scope-rejection-count",children:ne.count.toLocaleString()})]},ne.reason))}),v.lastAt?a("div",{className:"peer-meta",children:["Last rejected ",Vr(v.lastAt)]}):null]}):null,a("div",{className:"peer-scope-summary",children:"Authoritative Identity ownership"}),a("div",{className:"peer-meta",children:O.summary}),a("div",{className:"peer-meta",children:O.detail}),e.claimed_local_actor?a("div",{className:"peer-meta",children:Yq(e.claimed_local_actor_scope)}):null,a("div",{className:"peer-actor-row",children:a("button",{type:"button",className:"settings-button",onClick:()=>Jq(A?.deviceId??i),children:O.actionLabel})}),a("div",{className:"peer-scope-summary",children:"Advanced sharing rules"}),a("div",{className:"peer-meta",children:[b.statusLabel,". ",b.summary," ",b.note]}),he?a("div",{className:"peer-actions",children:a("button",{type:"button",className:"settings-button",onClick:Xq,children:"Open Coordinator Administration"})}):a("div",{className:"peer-meta",children:"Legacy Space access is managed in Coordinator Administration by a coordinator operator."}),a(oi,{feedback:E})]})]})]})})}function Zq(e){const t=C.syncPeersSectionFeedback,n=C.lastSyncStatus,r=n?.daemon_state==="disabled"||n?.enabled===!1;return e.peers.length?a(z,{children:[a(oi,{feedback:t}),e.peers.map(i=>{const o=String(i.peer_device_id||i.name||"unknown-peer");return a(Qq,{peer:i,...e},o)})]}):a(z,{children:[a(oi,{feedback:t}),a(vS,{detail:r?"Turn on sync in Settings → Device Sync first. Then use Invite a teammate or Paste an invite above to connect another device.":"Use Invite a teammate above to share a join code, or Paste an invite to enroll this device on an existing team.",title:"No teammates yet"})]})}function eU(e,t){mt(e,a(Zq,{...t}))}var gr=async()=>{},il="";function Df(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function tU(e){gr=e}function nU(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;hr("syncActorsSkeleton"),Df(!1);const n=tS({actors:C.lastSyncActors,peers:C.lastSyncPeers,duplicatePeople:C.lastSyncViewModel?.duplicatePeople}),r=n.visibleActors;t&&(t.textContent=r.length?"Manage Identity names here. Confirm authoritative device ownership in Devices.":"No named people yet. Create an Identity here, then confirm device ownership in Devices.",n.hiddenLocalDuplicateCount>0&&(t.textContent+=` ${n.hiddenLocalDuplicateCount} unresolved duplicate ${n.hiddenLocalDuplicateCount===1?"entry is":"entries are"} hidden here until reviewed in Needs attention.`)),Oq(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,o)=>{await jR(i,o),await gr()},onMerge:async(i,o)=>{try{await $m(i,o),Z("People combined. Assigned devices moved to the selected person."),await gr()}catch(s){throw Z(_t(s,"Failed to combine people."),"warning"),s}},onDeactivate:async i=>{try{await MR(i),Z("Person removed. Assigned devices have been unassigned."),await gr()}catch(o){throw Z(_t(o,"Failed to remove person."),"warning"),o}}})}function rU(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");Df(!0),t&&(t.textContent="People controls are temporarily unavailable. Refresh this page to retry. Device status and sync health are still available below while this recovers."),e&&ri(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. When the people endpoint responds again, named people will reload here."})}function iU(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;xq(e,{operations:C.lastShareOperations,onAdvance:n=>TR(n),onLoadOperation:n=>kR(n),onReload:gr});const t=document.getElementById("syncProjectShareOperationsMeta");t&&(t.textContent=C.shareOperationsLoadError?"Project sharing status could not be refreshed. Existing device diagnostics remain available below.":C.lastShareOperations.length>0?"Project access is grouped by Person. Devices appear after invitation acceptance.":"Share a project from Projects to invite a teammate.")}function Lf(){const e=document.getElementById("syncPeers");if(!e)return;hr("syncPeersSkeleton");const t=C.lastSyncPeers,n=Array.isArray(t)?t:[];fq(C.syncPeersSectionFeedback,n)&&(C.syncPeersSectionFeedback=null),eU(e,{peers:n,onRename:async(r,i)=>{try{return await wm(r,i),await gr(),{message:"Device name saved.",tone:"success"}}catch(o){return{message:_t(o,"Failed to save device name."),tone:"warning"}}},onSync:async(r,i)=>{try{const o=String(r?.peer_device_id||""),s=await xl({address:i,peerDeviceId:o||void 0}),c=zw(s);let l;c.ok?o&&Sf(o)?l={message:`Triggered sync for ${r?.name||(o?o.slice(0,8):"unknown")}. ${xf()?"Review legacy Space access and advanced rules in Coordinator Administration if this device needs tighter sharing.":"A coordinator operator can review legacy Space access and advanced rules in Coordinator Administration if this device needs tighter sharing."}`,tone:"warning"}:l={message:c.message,tone:"success"}:l={message:c.message,tone:"warning"};try{await gr()}catch{l={message:"Sync started, but this view has not refreshed yet. Refresh the page or use Sync now again before retrying.",tone:"warning"}}return l}catch(o){return{message:_t(o,"Failed to trigger sync."),tone:"warning"}}},onRemove:async(r,i)=>{try{await _m(r);const o={message:`Removed peer ${i}.`,tone:"success"};return C.syncPeerFeedbackById.delete(r),C.syncPeersSectionFeedback={...o,relatedPeerDeviceId:r},await gr(),o}catch(o){return{message:_t(o,"Failed to remove peer. The local peer entry is still here."),tone:"warning"}}}})}function oU(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");Df(!0),t&&(t.textContent="People and device details are unavailable right now. Refresh this page to retry once local sync status is reachable again."),e&&ri(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. Named people will reload here once the local sync status endpoint responds again."}),n&&ri(n,{title:"Devices unavailable right now.",detail:"Refresh this page to retry. When sync is reachable again, paired devices will reload here so you can rename, inspect, or re-pair them."})}function wS(){const e=document.getElementById("syncLegacyClaims"),t=document.getElementById("syncLegacyDeviceSelectMount"),n=document.getElementById("syncLegacyClaimsMeta");if(!e||!t||!n)return;const r=Array.isArray(C.lastSyncLegacyDevices)?C.lastSyncLegacyDevices:[];qq({devices:r,meta:n,mount:t,onValueChange:i=>{i!==il&&(il=i,wS())},panel:e,value:il})}function aU(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput"),r=document.getElementById("syncLegacyClaimButton");n?.addEventListener("keydown",i=>{Li(i,{onSubmit:()=>t?.click(),disabled:!t||t.disabled})}),t?.addEventListener("click",async()=>{if(!t||!n)return;const i=String(n.value||"").trim();if(!i){lo(n,"Enter a name for the person.");return}La(n),t.disabled=!0,n.disabled=!0,t.textContent="Creating…";try{await OR(i),Z("Person created."),n.value="",await e()}catch(o){Z(_t(o,"Failed to create person."),"warning"),t.textContent="Retry",t.disabled=!1,n.disabled=!1;return}t.textContent="Create person",t.disabled=!1,n.disabled=!1}),r?.addEventListener("click",async()=>{const i=String(il||"").trim();if(!i||!r||!await hn({title:`Attach history from ${i}?`,description:"This updates legacy provenance so the older device history is attached to you on this device.",confirmLabel:"Attach history",cancelLabel:"Cancel",tone:"danger"}))return;r.disabled=!0;const o=r.textContent||"Attach device history";r.textContent="Attaching…";try{await FR(i),Z("Old device history attached to you."),await e()}catch(s){Z(_t(s,"Failed to attach old device history."),"warning"),r.textContent="Retry",r.disabled=!1;return}r.textContent=o,r.disabled=!1})}function sU(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function $f(e=sU()){const t=document.getElementById("syncMainView"),n=document.getElementById("syncDiagnosticsView");!t||!n||(e==="diagnostics"?(t.hidden=!0,n.hidden=!1):(t.hidden=!1,n.hidden=!0))}var SS=!1;function cU(){SS||(SS=!0,window.addEventListener("hashchange",()=>{$f()}))}var yn={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function lU(e){yn.loadSyncData=e}var dU=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function uU(){const e=document.getElementById("syncCreateInviteButton"),t=document.getElementById("syncInviteAdminHint");if(!e||!t)return;const n=C.lastSyncCoordinatorAdminStatus?.readiness;if(n==="ready"){e.disabled=!1,t.hidden=!1,t.textContent="Legacy Team/Space setup is ready. Technical controls are in Coordinator Administration.";return}const r=n==="partial"?"Finish legacy Team/Space setup before creating remote invites. Use Coordinator Administration to check what is missing.":"Configure a coordinator URL, group, and admin secret before creating remote invites. Use Coordinator Administration to finish legacy Team/Space setup.";e.disabled=!0,t.hidden=!1,t.textContent=r}function Of(){const e=document.getElementById("syncAdminDisclosureMount");e&&hB(e,{open:oS,onOpenChange:t=>{nq(t),Of(),al(),jf()}})}function pU(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function jf(){const e=document.getElementById("syncInviteOutput"),t=document.getElementById("syncInviteWarnings");if(!e)return;const n=String(C.lastTeamInvite?.encoded||"").trim();if(e.value=n,e.hidden=!n,t){const r=Array.isArray(C.lastTeamInvite?.warnings)?C.lastTeamInvite.warnings:[];t.textContent=r.join(" · "),t.hidden=r.length===0}}function ol(){const e=document.getElementById("syncJoinFeedback");if(!e)return;const t=C.syncJoinFlowFeedback;e.textContent=t?.message||"",e.hidden=!t?.message,e.setAttribute("role",t?.tone==="warning"?"alert":"status"),e.setAttribute("aria-live",t?.tone==="warning"?"assertive":"polite"),e.className=`peer-meta${t?` ${t.tone==="warning"?"sync-inline-feedback warning":"sync-inline-feedback success"}`:""}`}function al(){const e=document.getElementById("syncInvitePolicyMount");e&&mt(e,y(ar,{ariaLabel:"Join policy",contentClassName:"sync-radix-select-content sync-actor-select-content",id:"syncInvitePolicy",itemClassName:"sync-radix-select-item",onValueChange:t=>{const n=t==="approval_required"?"approval_required":"auto_admit";n!==yn.invitePolicy&&(yn.invitePolicy=n,al())},options:dU,triggerClassName:"sync-radix-select-trigger sync-actor-select",value:yn.invitePolicy,viewportClassName:"sync-radix-select-viewport"}))}function fU(e,t){Of(),al();const n=document.getElementById("syncNowButton"),r=document.getElementById("syncShareProjectsButton"),i=document.getElementById("syncCreateInviteButton"),o=document.getElementById("syncInviteGroup"),s=document.getElementById("syncInviteTtl"),c=document.getElementById("syncInviteOutput"),l=document.getElementById("syncJoinButton"),d=document.getElementById("syncJoinInvite"),u=document.getElementById("syncProjectInviteReview"),p=document.getElementById("syncProjectInviteContext"),f=document.getElementById("syncProjectInviteReviewHeading"),m=document.getElementById("syncRecipientName"),v=document.getElementById("syncRecipientDeviceName");let g="",h,b=0;r?.addEventListener("click",()=>{_s()||Z("Project sharing is unavailable. Refresh Projects and try again.","warning")});const w=async(_,R)=>{if(!u||!m||!v)return"other";const I=await bm(_);if(R!==b||d?.value.trim()!==_)return"stale";if(h=I.kind,I.kind!=="project_share_invite")return"other";const T=(I.projects??[]).map(A=>`${A.display_name} (${A.existing_memory_count} existing ${A.existing_memory_count===1?"memory":"memories"})`).join(", ");return p&&(p.textContent=`${I.inviter_name||"A teammate"} invited you${I.team_name?` through ${I.team_name}`:""} to share ${T||"selected projects"}.`),m.value=Ti(I.recipient_name),v.value=Ti(I.device_name),u.hidden=!1,g=_,l&&(l.textContent="Accept and start syncing"),f?.focus(),"project"};d?.addEventListener("input",()=>{b+=1,d.value.trim()!==g&&(g="",h=void 0,u&&(u.hidden=!0),l&&(l.textContent="Review invite"))}),i?.addEventListener("click",async()=>{if(!i||!o||!s||!c||i.disabled)return;const _=o.value.trim(),R=Number(s.value);let I=!0;if(_?La(o):I=lo(o,"Team name is required."),!R||R<1?I=lo(s,"Must be at least 1 hour."):La(s),!!I){i.disabled=!0,i.textContent="Creating…";try{const T=await hm({group_id:_,policy:yn.invitePolicy,ttl_hours:R||24});C.lastTeamInvite=T,jf(),c.value=String(T.encoded||""),c.hidden=!1,c.focus(),c.select();const A=Array.isArray(T.warnings)?T.warnings:[];Z(A.length?`Invite created. Copy it above and review ${A.length===1?"1 warning":`${A.length} warnings`}.`:"Invite created. Copy the text above and share it with your teammate.",A.length?"warning":"success")}catch(T){Z(_t(T,"Failed to create invite. Check the team name, invite lifetime, and coordinator reachability, then try again."),"warning"),i.textContent="Retry",i.disabled=!1;return}finally{i.disabled&&(i.disabled=!1,i.textContent="Create invite")}}}),d?.addEventListener("keydown",_=>{Li(_,{onSubmit:()=>l?.click(),disabled:!l||l.disabled})}),l?.addEventListener("click",async()=>{if(!l||!d)return;const _=d.value.trim();if(!_){lo(d,"Paste a team invite or pairing payload.");return}if(La(d),g!==_){const I=b;try{const T=await w(_,I);if(T==="project"||T==="stale")return}catch{}if(I!==b||d.value.trim()!==_)return;g=_,l.textContent="Accept invite";return}const R=u&&!u.hidden?{recipient_name:m?.value.trim()??"",device_name:v?.value.trim()??""}:void 0;if(R){const I=T=>Ti(T)==="";if(I(R.recipient_name)){m&&lo(m,"Enter a human-readable name using 120 characters or fewer.");return}if(I(R.device_name)){v&&lo(v,"Enter a human-readable device name using 120 characters or fewer.");return}}l.disabled=!0,l.textContent="Accepting…";try{const I=await kl(_,R,h);C.lastTeamJoin=I;const T=I,A=typeof T.type=="string"?T.type:"team_join";let O;if(A==="pair"){const F=String(I.peer_device_id??"").trim();O={message:F?`Paired with device ${F.slice(0,8)}. It will appear in People & devices.`:"Paired the device. It will appear in People & devices.",tone:"success"}}else if(A==="project_share"){const F=T.restart_required===!0||T.setup_state==="pending_inviter"||I.status==="pending_setup",N=typeof T.detail=="string"?T.detail.trim():"";O=F?{message:N||(T.restart_required===!0?"Project invitation accepted. Restart codemem to finish setup.":T.setup_state==="pending_inviter"?"Project invitation accepted. Waiting for the inviter to finish setup.":"Project invitation accepted. Setup is still pending."),tone:"warning"}:{message:"Project invitation accepted.",tone:"success"}}else O={message:I.status==="pending"?"Join request sent. Waiting for admin approval.":"Joined the team.",tone:"success"};C.syncJoinFlowFeedback=O,ol(),d.value="",g="",u&&(u.hidden=!0);try{await t()}catch(F){O={message:_t(F,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},C.syncJoinFlowFeedback=O,ol()}}catch(I){C.syncJoinFlowFeedback={message:_t(I,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},ol(),l.textContent="Retry",l.disabled=!1;return}finally{l.disabled&&(l.disabled=!1,l.textContent="Review invite")}}),n?.addEventListener("click",async()=>{if(n){n.disabled=!0,n.textContent="Syncing…";try{const _=await xl(),R=zw(_);Z(R.message,R.warning?"warning":void 0)}catch(_){Z(_t(_,"Failed to start sync. Retry once, then run codemem sync doctor if the problem keeps coming back."),"warning"),n.textContent="Retry",n.disabled=!1;return}n.disabled=!1,n.textContent="Sync now",e()}})}function Mf({element:e,hidden:t=!1,restoreParent:n=null}){const r=B(null);return It(()=>{e&&(e.hidden=t)},[e,t]),It(()=>{const i=r.current;if(!(!i||!e))return e.parentElement!==i&&i.appendChild(e),()=>{!n||e.parentElement!==i||n.appendChild(e)}},[e,n]),a("div",{ref:r})}function mU({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:r}){return a(z,{children:[a("div",{className:"sync-action",children:[a("div",{className:"sync-action-text",children:["Invite a teammate.",a("span",{className:"sync-action-command",children:"Generate an invite when you want someone else to join this team from their device."})]}),a("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide invite form":"Invite a teammate"})]}),e?a(Mf,{element:e,hidden:!t,restoreParent:n}):null]})}function hU(){return a("div",{className:"sync-action",children:[a("div",{className:"sync-action-text",children:["Pair another device.",a("span",{className:"sync-action-command",children:"Copy a pairing command when you want to connect another one of your own devices."})]}),a("button",{type:"button",className:"settings-button sync-action-copy",onClick:e=>Uo("codemem sync pair --payload-only",e.currentTarget),children:"Copy pairing command"})]})}function gU({joinPanel:e,joinPanelOpen:t,joinRestoreParent:n,onToggle:r}){return a(z,{children:[a("div",{className:"sync-action",children:[a("div",{className:"sync-action-text",children:["Accept an invite or pairing.",a("span",{className:"sync-action-command",children:"Paste a team invite to join another team, or a pairing payload to connect another device."})]}),a("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide paste form":"Paste invite or pairing"})]}),e?a(Mf,{element:e,hidden:!t,restoreParent:n}):null]})}function vU({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,joinPanel:r,joinPanelOpen:i,joinRestoreParent:o,onToggleInvitePanel:s,onToggleJoinPanel:c,pairedPeerCount:l,presenceStatus:d}){const u=d==="not_enrolled";return a(z,{children:[u?a(z,{children:[a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:["Join this device.",a("span",{className:"sync-action-command",children:"Paste a team invite or pairing payload below to join an existing team or connect another of your devices."})]})}),r?a(Mf,{element:r,hidden:!1,restoreParent:o}):null,a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0}),a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:["This device is not on the team yet.",a("span",{className:"sync-action-command",children:"Use Join this device above, or ask an admin to enroll it first."})]})})]}):a(z,{children:[a(gU,{joinPanel:r,joinPanelOpen:i,joinRestoreParent:o,onToggle:c}),a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),u?null:a(mU,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:s}),!l&&d==="posted"?a(hU,{}):null]})}function sl({count:e,label:t}){return a("div",{className:"sync-section-heading",children:[a("div",{className:"sync-action-text sync-section-label",children:t}),e?a("span",{className:"badge actor-badge sync-section-count",children:e}):null]})}function cl({children:e}){return a("div",{className:"section-meta sync-section-note",children:e})}function yU({item:e,onAction:t}){const[n,r]=x(!1);return a("div",{className:"sync-action",children:[a("div",{className:"sync-action-text",children:[e.title,a("span",{className:"sync-action-command",children:e.summary})]}),a("button",{type:"button",className:"settings-button",disabled:n,onClick:async()=>{r(!0);try{await t(e)}finally{r(!1)}},children:e.actionLabel||"Review"})]})}function bU({request:e,onApprove:t,onDeny:n}){const[r,i]=x(null),[o,s]=x(null),[c,l]=x("Approve"),[d,u]=x("Deny");return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:a("div",{className:"actor-title",title:e.requestId||void 0,children:e.displayName})}),a("div",{className:"actor-actions",children:[a("button",{type:"button",className:"settings-button","aria-label":`${c} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("approve"),l("Approving…");try{s(await t(e)||null),l("Approve")}catch{l("Retry")}finally{i(null)}},children:c}),a("button",{type:"button",className:"settings-button","aria-label":`${d} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("deny"),u("Denying…");try{s(await n(e)||null),u("Deny")}catch{u("Retry")}finally{i(null)}},children:d})]}),a(oi,{feedback:o})]})}function _U({row:e,onInspectConflict:t,onRemoveConflict:n,onReview:r}){const[i,o]=x(null),[s,c]=x(null),l=e.actionLabel||"Pair with this device",[d,u]=x(l),[p,f]=x("Remove broken device record");return a("div",{className:"peer-card peer-card--padded","data-discovered-device-id":e.deviceId,children:[a("div",{className:"peer-title",children:[a("strong",{title:e.displayTitle||void 0,children:e.displayName}),a("span",{className:`badge actor-badge${e.availabilityLabel==="Offline"?"":" local"}`,children:e.availabilityLabel}),a("span",{className:"badge actor-badge",children:e.connectionLabel}),e.approvalBadgeLabel?a("span",{className:"badge actor-badge",children:e.approvalBadgeLabel}):null]}),a("div",{className:"peer-meta",children:e.note}),a("div",{className:"peer-actions",children:[e.mode==="accept"?a("button",{type:"button",className:"settings-button","aria-label":`${d} for ${e.displayName}`,disabled:i!==null,onClick:async()=>{o("review"),u("Pairing…"),c({message:`Pairing ${e.displayName}. Keep this page open while the device is approved and refreshed.`,tone:"success"});try{const m=await r(e)||null;c(m),u(m?.tone==="warning"?"Retry":e.actionLabel||l)}catch{c({message:`Pairing ${e.displayName} failed. Try again.`,tone:"warning"}),u("Retry")}finally{o(null)}},children:d}):null,(e.mode==="stale"||e.mode==="approval-pending"||e.mode==="ambiguous"||e.mode==="scope-pending"||e.mode==="setup-blocked")&&e.actionMessage?a("div",{className:"peer-meta",children:e.actionMessage}):null,e.mode==="paired"&&e.pairedMessage?a("div",{className:"peer-meta",children:e.pairedMessage}):null,e.mode==="conflict"?a(z,{children:[a("button",{type:"button",className:"settings-button","aria-label":`Open details for ${e.displayName}`,disabled:i!==null,onClick:()=>t(e),children:"Open device details"}),a("button",{type:"button",className:"settings-button danger","aria-label":`${p} for ${e.displayName}`,disabled:i!==null,onClick:async()=>{o("remove"),f("Removing…");try{c(await n(e)||null),f("Remove broken device record")}catch{f("Retry")}finally{o(null)}},children:p})]}):null]}),a(oi,{feedback:s})]})}function wU(e){const t=e.actionItems.length>0,n=e.actionableCount>e.actionItems.length,r=t||n||e.primaryStatus.state!=="healthy";return a(z,{children:[r?a(sl,{label:"Needs attention"}):null,r?a(cl,{children:"Start here when something needs review, re-pairing, or approval."}):null,e.primaryStatus.nextAction?a("div",{className:"sync-action","data-primary-sync-state":e.primaryStatus.state,children:a("div",{className:"sync-action-text",children:[e.primaryStatus.badgeLabel,a("span",{className:"sync-action-command",children:e.primaryStatus.nextAction})]})}):null,t?e.actionItems.map(i=>a(yU,{item:i,onAction:e.onAttentionAction},i.id)):null,!t&&!n&&e.primaryStatus.state==="healthy"?a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:"No urgent team work right now."})}):null,!t&&n?a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:"More team follow-up is listed below when you are ready."})}):null]})}function SU({children:e}){return e?a(z,{children:[a(sl,{label:"Add devices & teammates"}),a(cl,{children:"Use these flows when you are enrolling, inviting, or pairing something new."}),e]}):null}function CU({mount:e,rows:t,onInspectConflict:n,onRemoveConflict:r,onReview:i}){return!e||!t.length&&!C.syncDiscoveredFeedback?null:sn(a(z,{children:[a(sl,{count:t.length||void 0,label:"Devices waiting for review"}),a(cl,{children:"Review team devices here when they still need trust, re-pairing, or approval on this machine."}),a(oi,{feedback:C.syncDiscoveredFeedback}),t.map(o=>a(_U,{row:o,onInspectConflict:n,onRemoveConflict:r,onReview:i},`${o.deviceId}:${o.incomingRequestId}:${o.fingerprint}`))]}),e)}function RU({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!C.syncJoinRequestsFeedback?null:sn(a(z,{children:[a(sl,{count:t.length||void 0,label:"Join requests to review"}),a(cl,{children:"Approve or deny requests here before those devices become part of the team."}),a(oi,{feedback:C.syncJoinRequestsFeedback}),t.map(i=>a(bU,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function CS(e){return a(z,{children:[a(wU,{...e}),a(SU,{children:e.children}),a(RU,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),a(CU,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function RS(e){e&&(e.textContent="")}function ll(e){e instanceof HTMLElement&&(e.classList.remove("sync-attention-target"),e.offsetWidth,e.classList.add("sync-attention-target"),window.setTimeout(()=>e.classList.remove("sync-attention-target"),900))}function IU(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function $a(){return IU()?"auto":"smooth"}var Ff="syncTeamActionsMount",kU="Approval sent for this device. This screen may take up to 30 seconds to confirm two-way trust.";function TU(e,t,n=!1){return e.length>1&&(!t||n)}function PU(e,t,n){e.hidden=!1,e.textContent=n.badgeLabel,t.textContent=n.meta,n.state==="healthy"?e.className="sync-online-badge":n.state==="disabled"||n.state==="pending-setup"||n.state==="not-enrolled"||n.state==="reachable"?e.className="sync-online-badge sync-online-offline":e.className="sync-online-badge sync-online-error"}function NU(e,t){const n=document.createElement("div");n.id=Ff,e.appendChild(n),mt(n,y(CS,{actionItems:[],actionableCount:0,discoveredListMount:null,discoveredRows:[],joinRequestsMount:null,onApproveJoinRequest:async()=>null,onAttentionAction:async()=>{},onDenyJoinRequest:async()=>null,onInspectConflict:()=>{},onRemoveConflict:async()=>null,onReviewDiscoveredDevice:async()=>null,pendingJoinRequests:[],presenceStatus:"unknown",primaryStatus:t}))}function IS(e,t){const n=document.getElementById(Ff);n&&(ao(n),n.remove()),RS(e),t.forEach(r=>{RS(r)})}function Oa(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;Of(),al(),jf(),ol(),uU();const r=document.getElementById("syncInvitePanel"),i=document.getElementById("syncAdminSection"),o=document.getElementById("syncJoinPanel"),s=document.getElementById("syncJoinSection"),c=document.getElementById("syncJoinRequests"),l=document.getElementById("syncCoordinatorDiscovered"),d=document.getElementById("syncCoordinatorDiscoveredMeta"),u=document.getElementById("syncCoordinatorDiscoveredList");hr("syncTeamSkeleton"),pU();const p=C.lastSyncCoordinator,f=C.lastSyncViewModel||{primaryStatus:nS({status:C.lastSyncStatus,coordinator:p,peers:C.lastSyncPeers,shareOperations:C.lastShareOperations,shareOperationsLoadError:C.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]},m=E=>{if(E.kind==="possible-duplicate-person"){const U=document.getElementById("syncActorsList");U instanceof HTMLElement&&(U.scrollIntoView({block:"center",behavior:$a()}),ll(U));return}const S=String(E.deviceId||"").trim();if(!S)return;if(E.kind==="name-device"){const U=document.querySelector(`[data-device-name-input="${CSS.escape(S)}"]`);if(U instanceof HTMLInputElement){U.scrollIntoView({block:"center",behavior:$a()}),U.focus(),U.select(),ll(U);return}}const M=document.querySelector(`[data-peer-device-id="${CSS.escape(S)}"]`);if(M instanceof HTMLElement){M.scrollIntoView({block:"center",behavior:$a()}),ll(M);return}const H=document.querySelector(`[data-discovered-device-id="${CSS.escape(S)}"]`);H instanceof HTMLElement&&(H.scrollIntoView({block:"center",behavior:$a()}),ll(H))},v=async E=>{const S=Array.isArray(E.actorIds)?E.actorIds.map(oe=>String(oe||"").trim()).filter(Boolean):[],M=(Array.isArray(C.lastSyncActors)?C.lastSyncActors:[]).filter(oe=>S.includes(String(oe?.actor_id||"").trim()));if(M.length<2){Z("This duplicate review is outdated. Refresh the card and review the remaining people entries.","warning");return}const H=await dD({title:"Review possible duplicate people",summary:E.title.replace(/^Possible duplicate person:\s*/,""),actors:M.map(oe=>({actorId:String(oe?.actor_id||""),label:String(oe?.display_name||oe?.actor_id||"Unknown person"),isLocal:!!oe?.is_local}))});if(H.action==="different-people"){dq(S,"different-people"),Z("Okay. I will keep these people separate on this device."),await yn.loadSyncData();return}if(H.action!=="merge")return;const U=M.find(oe=>String(oe?.actor_id||"")===H.primaryActorId),re=M.find(oe=>String(oe?.actor_id||"")===H.secondaryActorId);if(!U?.actor_id||!re?.actor_id){Z("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await $m(String(U.actor_id),String(re.actor_id)),uq(S),Z(`Combined duplicate people into ${String(U.display_name||U.actor_id)}.`),await yn.loadSyncData()}catch(oe){try{await yn.loadSyncData()}catch{}Z(_t(oe,"Failed to combine these people."),"warning")}},g=async E=>await rp({title:"Pair with this device",description:"Choose a friendly name for this device before pairing it on this machine.",initialValue:E,placeholder:"Desk Mini",confirmLabel:"Pair",cancelLabel:"Cancel",validate:S=>S.trim()?null:"Enter a device name to pair this device."}),h=!!p?.configured,b=ZB(p);e.title=h?String(p.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?PU(w,e,f.primaryStatus):e.textContent=f.primaryStatus.meta,!h){IS(n,[c,u]),t.hidden=!1,n.hidden=!1,NU(n,f.primaryStatus),c&&(c.hidden=!0),l&&(l.hidden=!0);return}t.hidden=!0,n.hidden=!1;const _=String(p.presence_status||""),R=Array.isArray(C.lastSyncPeers)?C.lastSyncPeers:[],I=Array.isArray(f.attentionItems)?f.attentionItems:[],T=Array.isArray(p.discovered_devices)?p.discovered_devices:[],A=String(p.coordinator_url||"").trim(),O=T.map(E=>{const S=String(E.device_id||"").trim(),M=String(E.display_name||"").trim(),H=Jw({coordinatorName:M,deviceId:S})||"Discovered device",U=S&&H!==S?S:null,re=String(E.fingerprint||"").trim(),oe=String(E.incoming_reciprocal_request_id||"").trim(),ie=Array.isArray(E.groups)?E.groups.map(tt=>String(tt||"").trim()).filter(Boolean):[],se=R.find(tt=>String(tt?.peer_device_id||"")===S),ue=TU(ie,!!se,E.needs_local_approval===!0),Pe=Kw({device:E,pairedLocally:!!se}),Ie=String(se?.fingerprint||"").trim(),le=!!se&&!!re&&!!Ie&&Ie!==re,ve=C.pendingCoordinatorApprovalsByDeviceId.get(S),X=E.needs_local_approval===!0&&ve?.coordinatorUrl===A&&ve?.incomingRequestId===oe,ce=X?"approval-pending":E.needs_local_approval===!0?"needs-local-approval":"not-required",be=!X&&!b&&_B({device:E,hasAmbiguousCoordinatorGroup:ue,pairedLocally:!!se}),fe=Array.isArray(E.addresses)?E.addresses:[],We=Number(E.address_count??0),he=Number.isFinite(We)&&We>0?We:0,W=[fe.length?fe.map(tt=>Ho()?dS(String(tt||"")):String(tt||"")).filter(Boolean).join(" · "):he>0?`${he} ${E.stale?"last-known":"fresh"} ${he===1?"address":"addresses"} hidden`:"No fresh addresses"];!fe.length&&U&&W.push(`device id: ${S}`);let de=null,ne=be?"accept":"none",xe=null;return le?ne="conflict":X?(de="Waiting for refreshed coordinator status. You do not need to approve again.",ne="approval-pending"):b&&(!se||Pe.state==="needs-your-approval")?(de=b.message,ne="setup-blocked"):ue?(de="This device appears in multiple coordinator groups. Review legacy Team/Space setup before approving it here.",ne="ambiguous"):se&&Sf(S)?(de="Review this device's legacy Space access and advanced rules in Coordinator Administration before you sync it.",ne="scope-pending"):se?.last_error?(W.push(`error: ${String(se.last_error)}`),be||(ne="paired")):se?.status?.peer_state?(W.push(`status: ${String(se.status.peer_state)}`),be||(ne="paired")):!se&&E.stale?(de="Wait for a fresh coordinator presence update, then review this device again here.",ne="stale"):se&&!be&&(ne="paired"),ne==="paired"&&(xe=Pe.state==="waiting-for-other-device"?Pe.description||"Waiting on the other device.":String(se?.last_error||"").toLowerCase().includes("401")&&String(se?.last_error||"").toLowerCase().includes("unauthorized")?"Waiting for the other device to trust this one before sync can work.":null),{actionMessage:de,actionLabel:Pe.actionLabel||(se?"Review device":"Pair with this device"),approvalBadgeLabel:X?"Approval sent":Pe.badgeLabel,approvalState:ce,availabilityLabel:E.stale?"Offline":"Available",connectionLabel:le?iS.conflicts:se?iS.pairedLocally:"Not connected on this device",coordinatorUrl:A,deviceId:S,displayName:H,displayTitle:U,fingerprint:re,groupId:ie[0]??"",incomingRequestId:oe,mode:ne,note:W.join(" · "),pairedMessage:xe}}),F=new Set(O.filter(E=>E.approvalState==="approval-pending").map(E=>E.deviceId)),N=I.filter(E=>!E.deviceId||!F.has(E.deviceId)),L=[],D=O.filter(E=>E.mode!=="paired"&&E.mode!=="none"&&E.mode!=="scope-pending"),G=O.filter(E=>E.mode==="accept"||E.mode==="scope-pending").length,q=N.length+L.length+G;l&&(l.hidden=D.length===0&&!C.syncDiscoveredFeedback),d&&(d.textContent=D.length?"Pair with a teammate's device to see it appear in People & devices and start syncing.":""),c&&(c.hidden=L.length===0&&!C.syncJoinRequestsFeedback),IS(n,[c,u]);const $=document.createElement("div");$.id=Ff,n.appendChild($),mt($,y(CS,{actionItems:N,actionableCount:q,children:y(vU,{invitePanel:r,invitePanelOpen:yf,inviteRestoreParent:i,joinPanel:o,joinPanelOpen:bf,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(rq(!yf),Oa())},onToggleJoinPanel:()=>{o&&(iq(!bf),Oa())},pairedPeerCount:Number(p.paired_peer_count||0),presenceStatus:_}),discoveredListMount:u,discoveredRows:D,joinRequestsMount:c,onApproveJoinRequest:async()=>null,onAttentionAction:async E=>{if(E.kind==="possible-duplicate-person"){await v(E);return}m(E)},onDenyJoinRequest:async()=>null,onInspectConflict:E=>{const S=document.querySelector(`[data-peer-device-id="${CSS.escape(E.deviceId)}"]`);if(S instanceof HTMLElement){S.scrollIntoView({block:"center",behavior:$a()}),Z(`Opened the conflicting local device record for ${E.displayName}.`,"warning");return}Z("The conflicting local device record is not visible yet. Scroll to People & devices and try again.","warning")},onRemoveConflict:async E=>{if(!await hn({title:`Remove ${E.displayName}?`,description:"This deletes the broken local device record. You can review this device again after the screen refreshes.",confirmLabel:"Remove device record",cancelLabel:"Keep device record",tone:"danger"}))return null;try{await _m(E.deviceId);const S={message:`Removed the broken local device record for ${E.displayName}. If it is still available, review it again from Next steps or Devices seen on team.`,tone:"success"};return C.syncDiscoveredFeedback=S,await yn.loadSyncData(),S}catch(S){return{message:_t(S,"Failed to remove the broken local device record. The old local record is still present in People & devices."),tone:"warning"}}},onReviewDiscoveredDevice:async E=>{try{const S=await g(E.displayName);return S?await EU(E,S):null}catch(S){return{message:_t(S,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:L,presenceStatus:_,primaryStatus:f.primaryStatus}))}async function EU(e,t){const n=e.approvalState==="needs-local-approval",r=e.deviceId.trim(),i=e.coordinatorUrl.trim(),o=e.groupId.trim(),s=e.incomingRequestId.trim();if(n&&(!r||!i||!o||!s))throw new Error("Device identity is incomplete. Refresh the screen and try approval again.");const c=await XC(e.deviceId,{fingerprint:e.fingerprint,expectedGroupId:o||void 0,expectedIncomingRequestId:n?s:void 0}),l=String(c?.name||e.displayName||"").trim()||e.displayName;n&&C.pendingCoordinatorApprovalsByDeviceId.set(r,{coordinatorUrl:i,incomingRequestId:s});const d=Array.isArray(C.pendingAcceptedSyncPeers)?C.pendingAcceptedSyncPeers.filter(p=>String(p?.peer_device_id||"").trim()!==e.deviceId):[];C.pendingAcceptedSyncPeers=[...d,{peer_device_id:e.deviceId,name:l,fingerprint:e.fingerprint,addresses:[],claimed_local_actor:!1,status:{peer_state:"degraded"},last_error:"Waiting for the other device to approve this one."}],aq(e.deviceId);let u=n?{message:kU,tone:"success"}:{message:`Step 1 complete on this device for ${e.displayName}. Finish onboarding on the other device so both sides trust each other for sync.`,tone:"success"};C.syncDiscoveredFeedback=u,n&&Oa();try{t.trim()!==l.trim()&&(await wm(e.deviceId,t.trim()),C.pendingAcceptedSyncPeers=C.pendingAcceptedSyncPeers.map(p=>String(p?.peer_device_id||"").trim()===e.deviceId?{...p,name:t.trim()}:p),n||(u={message:`Connected ${t.trim()} and saved its name.`,tone:"success"}))}catch(p){u={message:n?"Approval was sent, but naming did not finish. You do not need to approve again.":_t(p,"Device connected, but naming did not finish."),tone:"warning"}}C.syncDiscoveredFeedback=u;try{await yn.loadSyncData()}catch(p){u={message:n?"Approval was sent. Confirmation may take up to 30 seconds, and you do not need to approve again.":_t(p,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},C.syncDiscoveredFeedback=u}return u}function AU(e){switch(e){case"cwd":return"Matched by folder";case"git_remote":return"Matched by git remote";case"workspace_id":return"Matched by workspace";case"project":return"Matched by project name";case"unmapped":return"Missing project identity";default:return`Matched by ${e.replace(/_/g," ")}`}}function uo(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function kS(e){return uo(e)?"Unclear project identity":e.displayProject}function Ht(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function xU(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function DU(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function LU(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function $U(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function OU(e){if(!e)return"date unavailable";const t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat("en-US",{day:"numeric",month:"short",timeZone:"UTC",year:"numeric"}).format(t)}function jU(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function MU({group:e}){const t=e.memorySamples??[],n=t.length;return a("details",{className:"legacy-review-samples",children:[a("summary",{children:["Inspect affected memories",n?` (${n} sample${n===1?"":"s"})`:""]}),a("div",{className:"legacy-review-cleanup-note",children:"Showing representative memories from this project group before reassignment. Local memories can be reassigned; peer-owned memories stay in review on this device."}),t.length>0?a("ul",{className:"legacy-review-sample-list",children:t.map(r=>a("li",{className:"legacy-review-sample",children:[a("div",{className:"legacy-review-sample-title",children:r.title}),a("div",{className:"legacy-review-group-meta",children:[r.kind||"memory"," · ",OU(r.updatedAt??r.createdAt)," ","·"," ",r.ownership==="local"?"local, reassignable":"peer-owned, stays in review"]}),r.bodyPreview?a("div",{className:"legacy-review-sample-body",children:r.bodyPreview}):null,a("div",{className:"legacy-review-group-meta mono",children:jU(r)})]},r.id))}):a("div",{className:"legacy-review-cleanup-note",children:"No samples are available for this group. Refresh Sync and try again before reassigning."})]})}function TS(e,t,n){let r=(e instanceof Error?e.message:"Unable to reassign legacy review memories.").replace(/sharing domain/gi,"Space");return t&&(r=r.replace(new RegExp(`\\b${DU(t)}\\b`,"g"),LU(t,n))),r}function FU(e,t){const n=e.suggestedScopeId?t.find(r=>r.scopeId===e.suggestedScopeId)?.label:"";return[e.displayProject,e.identitySource,e.suggestedScopeId??"",n??"",e.suggestionReason??"",e.workspaceIdentity].join(" ").toLowerCase()}function BU({item:e,onReview:t}){return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:[a("div",{className:"actor-title",children:[a("strong",{children:e.peerName}),a("span",{className:"badge actor-badge",children:["person: ",e.actorDisplayName||e.actorId]})]}),a("div",{className:"peer-meta",children:[e.shareableCount," share by default · ",e.privateCount," marked Only me ·"," ",e.scopeLabel]})]}),a("div",{className:"actor-actions",children:a("button",{type:"button",className:"settings-button",onClick:t,children:"Review my memories in Feed"})})]})}function qU({item:e,onReassign:t,onReview:n}){const r=e.groups??[],i=e.targetScopes??[],o=Object.fromEntries(r.map(S=>[S.workspaceIdentity,S.suggestedScopeId??""])),[s,c]=x({}),[l,d]=x({}),[u,p]=x(o),[f,m]=x({}),[v,g]=x("all"),[h,b]=x(""),[w,_]=x(null),R=r.length,I=e.totalGroupCount??R,T=r.filter(uo).length,A=r.filter(S=>S.suggestedScopeId&&!uo(S)&&Ht(S)).length,O=r.filter(S=>f[S.workspaceIdentity]&&Ht(S)).length,F=r.filter(S=>f[S.workspaceIdentity]&&Ht(S)&&!!u[S.workspaceIdentity]).length,N=r.filter(S=>{const M=uo(S);return v==="suggested"&&(!S.suggestedScopeId||M)||v==="cleanup"&&!M||v==="no-suggestion"&&(S.suggestedScopeId||M)||v==="selected"&&!f[S.workspaceIdentity]?!1:!h.trim()||FU(S,i).includes(h.trim().toLowerCase())});async function L(S){const M=u[S.workspaceIdentity]||S.suggestedScopeId||"";if(!(!M||!t||w)){_(S.workspaceIdentity),d(H=>{const U={...H};return delete U[S.workspaceIdentity],U});try{const H=await t(S,M,!!s[S.workspaceIdentity],s[S.workspaceIdentity]?.confirmation_token);c(H?U=>({...U,[S.workspaceIdentity]:H}):U=>{const re={...U};return delete re[S.workspaceIdentity],re})}catch(H){d(U=>({...U,[S.workspaceIdentity]:TS(H,M,i)}))}finally{_(null)}}}function D(S,M){p(H=>({...H,[S.workspaceIdentity]:M})),c(H=>{const U={...H};return delete U[S.workspaceIdentity],U}),d(H=>{const U={...H};return delete U[S.workspaceIdentity],U})}function G(S,M){m(H=>({...H,[S.workspaceIdentity]:M}))}function q(S){m(M=>({...M,...Object.fromEntries(N.filter(Ht).map(H=>[H.workspaceIdentity,S]))}))}function $(){m(S=>({...S,...Object.fromEntries(r.filter(M=>M.suggestedScopeId&&!uo(M)&&Ht(M)).map(M=>[M.workspaceIdentity,!0]))}))}async function E(){if(!t||w||F===0)return;const S=r.filter(M=>f[M.workspaceIdentity]&&Ht(M)&&!!u[M.workspaceIdentity]);if(!S.every(M=>s[M.workspaceIdentity])){_("bulk");try{for(const M of S){if(s[M.workspaceIdentity])continue;const H=u[M.workspaceIdentity]||M.suggestedScopeId||"";if(H)try{const U=await t(M,H,!1);d(re=>{const oe={...re};return delete oe[M.workspaceIdentity],oe}),U&&c(re=>({...re,[M.workspaceIdentity]:U}))}catch(U){d(re=>({...re,[M.workspaceIdentity]:TS(U,H,i)}))}}}finally{_(null)}}}return a("div",{className:"legacy-review-card",children:[a("div",{className:"legacy-review-header",children:[a("div",{children:[a("div",{className:"actor-title",children:[a("strong",{children:"Legacy shared review"}),a("span",{className:"badge badge-offline",children:"Needs project review"})]}),a("div",{className:"peer-meta legacy-review-summary",children:[I.toLocaleString()," older"," ",I===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",R<I?` Showing ${R.toLocaleString()} projects; open Projects to review the rest.`:""]}),a("div",{className:"peer-meta legacy-review-warning",children:"Fix peer-owned projects on their source device. Reassignment updates future sync authorization; online compatible peers should converge after syncing, but offline devices, backups, copied databases, malicious peers, or old versions may retain old copies."})]}),a("div",{className:"actor-actions",children:a("button",{type:"button",className:"settings-button",onClick:n,children:"Manage all projects"})})]}),a("div",{className:"legacy-review-toolbar",children:[a("div",{className:"legacy-review-filter-row",children:[["all",`Showing ${R.toLocaleString()}`],["suggested",`Suggested ${A.toLocaleString()}`],["cleanup",`Needs cleanup ${T.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${F.toLocaleString()}`]].map(([S,M])=>a("button",{className:v===S?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>g(S),type:"button",children:M},S))}),a("div",{className:"legacy-review-bulk-row",children:[a("input",{"aria-label":"Search legacy project groups",className:"peer-scope-input legacy-review-search",onInput:S=>b(S.currentTarget.value),placeholder:"Search project, signal, or destination…",value:h}),a("button",{className:"settings-button",onClick:()=>q(!0),type:"button",children:"Select visible"}),a("button",{className:"settings-button",onClick:$,type:"button",children:"Select suggested"}),a("button",{className:"settings-button",onClick:()=>q(!1),type:"button",children:"Clear visible"}),t&&i.length>0?a("button",{className:"settings-save",disabled:w!=null||F===0||r.filter(S=>f[S.workspaceIdentity]&&Ht(S)&&!!u[S.workspaceIdentity]).every(S=>s[S.workspaceIdentity]),onClick:()=>{E()},type:"button",children:w==="bulk"?"Previewing…":`Preview ${F.toLocaleString()} selected`}):t&&O>0?a("span",{className:"legacy-review-cleanup-note",children:"Add or join a Space before bulk reassignment."}):null,F>0&&r.filter(S=>f[S.workspaceIdentity]&&Ht(S)&&!!u[S.workspaceIdentity]).every(S=>s[S.workspaceIdentity])?a("span",{className:"legacy-review-cleanup-note",children:"Bulk actions only preview. Confirm each project individually to avoid partial reassignment."}):null]})]}),r.length>0?a("ul",{className:"legacy-review-groups","aria-label":"Legacy shared review project groups",children:N.map(S=>a("li",{className:"legacy-review-group",children:[a("div",{className:"legacy-review-group-main",children:[a("div",{className:"legacy-review-title-wrap",children:[a("input",{"aria-label":`Select ${kS(S)}`,checked:!!f[S.workspaceIdentity],className:"cm-checkbox",disabled:!Ht(S),onChange:M=>G(S,M.currentTarget.checked),type:"checkbox"}),a("div",{children:[a("div",{className:"legacy-review-group-title",children:kS(S)}),a("div",{className:"legacy-review-group-meta",children:[AU(S.identitySource),xU(S,i)]}),Ht(S)?S.peerOwnedMemoryCount?a("div",{className:"legacy-review-cleanup-note",children:[(S.reassignableMemoryCount??S.memoryCount).toLocaleString()," ","local memor",(S.reassignableMemoryCount??S.memoryCount)===1?"y":"ies"," ","can be reassigned; ",S.peerOwnedMemoryCount.toLocaleString()," peer-owned memor",S.peerOwnedMemoryCount===1?"y":"ies"," will stay in review."]}):null:a("div",{className:"legacy-review-cleanup-note",children:"Peer-owned only. These older memories were received from another device, so this device cannot reassign them to a Space. Assign this project to a Space on the source device; after sync, this review should clear here."}),uo(S)?a("div",{className:"legacy-review-cleanup-note",children:"Inspect or correct the project identity before assigning old shared data to a Space."}):null]})]}),a("span",{className:"legacy-review-count",children:[S.memoryCount.toLocaleString()," memor",S.memoryCount===1?"y":"ies"]})]}),S.suggestionReason?a("div",{className:"legacy-review-reason",children:S.suggestionReason}):null,l[S.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:l[S.workspaceIdentity]}):null,s[S.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:[s[S.workspaceIdentity].warning," This will reassign"," ",s[S.workspaceIdentity].reassignable_memory_count.toLocaleString()," of"," ",s[S.workspaceIdentity].memory_count.toLocaleString()," memories",s[S.workspaceIdentity].skipped_memory_count?`; ${s[S.workspaceIdentity].skipped_memory_count.toLocaleString()} peer-owned copies will be left unchanged`:"","."]}):null,a(MU,{group:S}),i.length>0&&t&&Ht(S)?a("label",{className:"legacy-review-target",children:[a("span",{children:"Destination Space"}),a("select",{className:"peer-scope-input",disabled:w!=null,onChange:M=>D(S,M.currentTarget.value),value:u[S.workspaceIdentity]||"",children:[a("option",{value:"",children:"Choose Space…"}),i.map(M=>a("option",{value:M.scopeId,children:[M.label," · ",$U(M.authorityType),M.scopeId===S.suggestedScopeId?" · suggested":""]},M.scopeId))]})]}):null,i.length>0&&t&&Ht(S)?a("div",{className:"legacy-review-actions",children:a("button",{type:"button",className:"settings-button",disabled:w!=null||!u[S.workspaceIdentity],onClick:()=>{L(S)},children:w===S.workspaceIdentity?s[S.workspaceIdentity]?"Reassigning…":"Previewing…":s[S.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},S.workspaceIdentity))}):null]})}function UU({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return a(z,{children:[t?a(qU,{item:t,onReassign:n,onReview:r??i}):null,e.map(o=>a(BU,{item:o,onReview:i},`${o.peerName}:${o.actorId}:${o.scopeLabel}`))]})}function GU(){Kv("mine"),C.feedQuery="",window.location.hash="feed"}function HU(){window.location.hash="projects"}async function VU(e,t,n,r){try{const i=await DR({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return C.lastSyncLegacySharedReview=i.legacy_shared_review??null,Z(`Reassigned ${i.reassigned_memory_count.toLocaleString()} legacy review memor${i.reassigned_memory_count===1?"y":"ies"} to ${i.target_scope_label}.`),PS(),null}catch(i){if(i instanceof Cm)return i.preview;const o=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw Z(o,"warning"),new Error(o)}}function PS(){const e=document.getElementById("syncSharingReview"),t=document.getElementById("syncSharingReviewMeta"),n=document.getElementById("syncSharingReviewList");if(!e||!t||!n)return;const r=e.querySelector(".settings-group-title"),i=Array.isArray(C.lastSyncSharingReview)?C.lastSyncSharingReview:[],o=C.lastSyncLegacySharedReview,s=Math.max(0,Number(o?.memory_count??0)),c=o?.has_data?{groups:Array.isArray(o.groups)?o.groups.map(u=>{const p=u;return{displayProject:String(p.display_project||p.project||"Unknown project"),identitySource:String(p.identity_source||"unknown"),lastUpdatedAt:typeof p.last_updated_at=="string"?p.last_updated_at:null,memoryCount:Number(p.memory_count||0),memorySamples:Array.isArray(p.memory_samples)?p.memory_samples.map(f=>{const m=f,v=m.ownership==="peer"?"peer":"local";return{bodyPreview:typeof m.body_preview=="string"?m.body_preview:null,createdAt:typeof m.created_at=="string"?m.created_at:null,cwd:typeof m.cwd=="string"?m.cwd:null,gitRemote:typeof m.git_remote=="string"?m.git_remote:null,id:Number(m.id||0),kind:typeof m.kind=="string"?m.kind:null,ownership:v,project:typeof m.project=="string"?m.project:null,title:String(m.title||`Memory ${Number(m.id||0)}`),updatedAt:typeof m.updated_at=="string"?m.updated_at:null}}):[],peerOwnedMemoryCount:Number(p.peer_owned_memory_count||0),reassignableMemoryCount:Number(p.reassignable_memory_count||0),suggestedScopeId:typeof p.suggested_scope_id=="string"?p.suggested_scope_id:null,suggestionReason:typeof p.suggestion_reason=="string"?p.suggestion_reason:null,workspaceIdentity:String(p.workspace_identity||p.display_project||"unknown")}}):[],memoryCount:s,scopeId:String(o.scope_id||"legacy-shared-review"),totalGroupCount:Number(o.total_group_count||o.groups?.length||0),targetScopes:Array.isArray(o.target_scopes)?o.target_scopes.map(u=>{const p=u;return{authorityType:String(p.authority_type||"unknown"),label:String(p.label||p.scope_id||"Unknown domain"),scopeId:String(p.scope_id||"")}}).filter(u=>u.scopeId):[]}:null;if(!i.length&&!c){ao(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=C.currentProject?`current project (${C.currentProject})`:"all allowed projects";t.textContent=c?`Review conservative upgrade state before promoting historical shared data. Teammates receive memories from ${l} by default once Sharing-domain grants allow it.`:`Teammates receive memories from ${l} by default. Use Only me on a memory when it should stay local.`;const d=i.map(u=>({actorDisplayName:String(u.actor_display_name||u.actor_id||"unknown"),actorId:String(u.actor_id||"unknown"),peerName:String(u.peer_name||u.peer_device_id||"Device"),privateCount:Number(u.private_count||0),scopeLabel:String(u.scope_label||"All allowed projects"),shareableCount:Number(u.shareable_count||0)}));mt(n,y(UU,{items:d,legacyReview:c,onLegacyReassign:VU,onLegacyReview:HU,onReview:GU}))}var dl="";function KU(e){if(!e)return;const t=String(e?.coordinator_url||"").trim(),n=!!(e.lookup_error||e.reciprocal_approval_error),r=Array.isArray(e?.discovered_devices)?e.discovered_devices:[],i=new Map;for(const o of r){const s=String(o.device_id||"").trim();s&&i.set(s,[...i.get(s)||[],o])}for(const[o,s]of C.pendingCoordinatorApprovalsByDeviceId){if(s.coordinatorUrl!==t){C.pendingCoordinatorApprovalsByDeviceId.delete(o);continue}if(n)continue;const c=i.get(o);c&&(c.some(l=>String(l.incoming_reciprocal_request_id||"").trim()===s.incomingRequestId&&l.needs_local_approval===!0)||C.pendingCoordinatorApprovalsByDeviceId.delete(o))}}function zU(){return[...C.pendingCoordinatorApprovalsByDeviceId].map(([e,t])=>[e,t.coordinatorUrl,t.incomingRequestId]).sort(([e],[t])=>e.localeCompare(t))}var ja=null,Bf=0,qf=null,Uf=0,Gf=null,WU=15e3;function NS(e){return`project:${e||""}|includeJoinRequests:false`}function JU(e){const t=NS(e);return!ja||ja.key!==t||Date.now()>=ja.expiresAtMs?null:ja.payload}function YU(e,t){ja={key:NS(e),expiresAtMs:Date.now()+WU,payload:t}}function XU(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function QU(){const e=document.getElementById("syncSharingReview"),t=document.getElementById("syncSharingReviewList"),n=document.getElementById("syncSharingReviewMeta"),r=document.getElementById("syncLegacyClaims"),i=document.getElementById("syncLegacyClaimsMeta");e&&(e.hidden=!0),t&&(t.textContent=""),n&&(n.textContent=""),r&&(r.hidden=!0),i&&(i.textContent="")}async function ZU(e,t){if(C.activeTab==="health"&&!t.requireFreshSyncStatus){const r=JU(e);if(r)return{payload:r,fetchedFreshSyncStatus:!1}}const n=!Ho();return{payload:await Il(n,e,{includeJoinRequests:!1}),fetchedFreshSyncStatus:!0}}function e2(e){return e.requiredSurface!=="all"?!0:e.actorLoadError||e.coordinatorAdminLoadError||e.shareOperationsLoadError?!1:!e.requiresDeviceIdentityInventory||!e.deviceIdentityInventoryLoadError}function ul(e={}){const t=t2(++Bf,{requiredSurface:e.requiredSurface??"all",requireFreshSyncStatus:e.requireFreshSyncStatus??!1});return qf=t,t}async function t2(e,t){try{const n=C.currentProject||"",{payload:r,fetchedFreshSyncStatus:i}=await ZU(n,t);let o=null,s=null,c=C.lastDeviceIdentityInventory,l=C.lastShareOperations,d=!1,u=!1,p=C.deviceIdentityInventoryLoadError,f=!1;const m=lq();try{o=await JC()}catch{d=!0}try{s=await Rl()}catch{u=!0}if(C.activeTab==="advanced"){p=!1;try{c=await Al()}catch{p=!0}}try{const R=await Lm();l=Array.isArray(R.items)?R.items:[]}catch{f=!0}if(e!==Bf)return qf??!1;const v=e2({requiredSurface:t.requiredSurface,actorLoadError:d,coordinatorAdminLoadError:u,shareOperationsLoadError:f,requiresDeviceIdentityInventory:C.activeTab==="advanced",deviceIdentityInventoryLoadError:p});i&&YU(n,XU(r)),KU(r.coordinator);const g=JSON.stringify([r,o,s,c,p,l,f,m,zU()]);if(g===dl)return v;dl=g;const h=r.status&&typeof r.status=="object"?r.status:null;h&&(C.lastSyncStatus=h),Array.isArray(o?.items)?C.lastSyncActors=o.items:C.lastSyncActors=[];const b=Array.isArray(r.peers)?r.peers:[],w=new Set(b.map(R=>String(R?.peer_device_id||"").trim()).filter(Boolean)),_=Array.isArray(C.pendingAcceptedSyncPeers)?C.pendingAcceptedSyncPeers.filter(R=>{const I=String(R?.peer_device_id||"").trim();return I&&!w.has(I)}):[];return C.pendingAcceptedSyncPeers=_,C.lastSyncPeers=[...b,..._],p||(C.lastDeviceIdentityInventory=c),C.deviceIdentityInventoryLoadError=p,C.lastShareOperations=l,C.shareOperationsLoadError=f,C.lastSyncSharingReview=r.sharing_review||[],C.lastSyncLegacySharedReview=r.legacy_shared_review&&typeof r.legacy_shared_review=="object"?r.legacy_shared_review:null,C.lastSyncCoordinator=r.coordinator||null,C.lastSyncCoordinatorAdminStatus=s&&typeof s=="object"?s:null,C.lastSyncJoinRequests=Array.isArray(r.join_requests)?r.join_requests:[],C.lastSyncAttempts=r.attempts||[],C.lastSyncLegacyDevices=r.legacy_devices||[],C.lastSyncDuplicatePersonDecisions=m,C.lastSyncViewModel=tq({actors:C.lastSyncActors,peers:C.lastSyncPeers,coordinator:C.lastSyncCoordinator,status:h,shareOperations:C.lastShareOperations,shareOperationsLoadError:f,reconciliation:r.recipient_policy_reconciliation,duplicatePersonDecisions:C.lastSyncDuplicatePersonDecisions}),mS(),Oa(),nU(),iU(),PS(),Lf(),wS(),fS(),V_(),d&&rU(),u&&(C.lastSyncCoordinatorAdminStatus=null,Oa()),v}catch{return e!==Bf?qf??!1:(dl="",C.deviceIdentityInventoryLoadError=!0,hr("syncTeamSkeleton"),hr("syncActorsSkeleton"),hr("syncPeersSkeleton"),hr("syncDiagSkeleton"),QU(),oU(),yq(),!1)}}function n2(){dl="",C.lastSyncPeers?.length&&Lf()}async function pl(){await ul()}function r2(){const e=i2(++Uf);return Gf=e,e}async function i2(e){try{const t=await YC();return e!==Uf?Gf??!1:(C.pairingPayloadRaw=t||null,Pf(),!0)}catch{return e!==Uf?Gf??!1:(C.pairingPayloadRaw=null,Pf(),!1)}}function o2(e){QF(),fc(),lU(pl),tU(pl),Sq(Lf),fU(e,pl),aU(pl),Cq(e),$f(),cU()}function a2(e,t){const n=Le("runtimeLabel");n&&(n.textContent=t?`v${e} (${t})`:`v${e}`,n.title=t?`codemem ${e} (${t})`:`codemem ${e}`,n.hidden=!1)}async function s2(){try{const e=await BC();if(!e?.version)return;a2(e.version,"35079ac")}catch{}}var Hf=null,ES=1500,AS="codemem-legacy-upgrade-notice-dismissed",vr=null,nn=!1,fl=!1,Vf=!1,Ma=null;function xS(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function DS(e){if(!e||typeof e!="object")return null;const t=e.legacy_shared_review??e;if(!t||typeof t!="object")return null;const n=t;if(n.has_data!==!0)return null;const r=Array.isArray(n.groups)?n.groups:[],i=xS(n.total_group_count,r.length),o=xS(n.memory_count);return i<=0||o<=0?null:{groupCount:i,memoryCount:o}}function LS(){try{return localStorage.getItem(AS)==="1"}catch{return!1}}function ml(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(AS,"1")}catch{}}function $S(){const e=Le("legacyUpgradeModal");return!e||e.hidden?[]:Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(t=>!t.hidden&&t.offsetParent!==null)}function c2(){const e=$S(),t=Le("legacyUpgradeReviewGroups");(t&&e.includes(t)?t:e[0])?.focus()}function OS(e){const t=Le("legacyUpgradeModal");if(!t||t.hidden)return;if(e.key==="Escape"){e.preventDefault(),ml(),Fa(!1);return}if(e.key==="Enter"){const o=Le("legacyUpgradeReviewGroups");Li(e,{onSubmit:()=>o?.click(),disabled:!o||o.disabled});return}if(e.key!=="Tab")return;const n=$S();if(n.length===0)return;const r=n[0],i=n[n.length-1];if(e.shiftKey&&document.activeElement===r){e.preventDefault(),i.focus();return}!e.shiftKey&&document.activeElement===i&&(e.preventDefault(),r.focus())}function jS(e){for(const t of document.querySelectorAll("header, .tab-bar, .tab-panel, #toastRoot, #viewerReconnectOverlay, #settingsDialogMount"))t.id==="viewerReconnectOverlay"&&t.hidden||(t.inert=e,e?t.setAttribute("aria-hidden","true"):t.removeAttribute("aria-hidden"))}function Fa(e,t){const n=Le("legacyUpgradeModalBackdrop"),r=Le("legacyUpgradeModal"),i=Le("legacyUpgradeSummary");if(!(!n||!r||!i)){if(t&&(i.textContent=`${t.groupCount.toLocaleString()} older ${t.groupCount===1?"project needs":"projects need"} a Sharing domain. They contain ${t.memoryCount.toLocaleString()} older shared memories total; you will review the projects, not individual memories.`),n.hidden=!e,r.hidden=!e,e){Ma=document.activeElement,document.addEventListener("keydown",OS),c2(),jS(!0);return}jS(!1),document.removeEventListener("keydown",OS),Ma&&document.contains(Ma)&&Ma.focus(),Ma=null}}function MS(e){!e||Vf||LS()||(Vf=!0,uv(()=>Fa(!0,e)))}async function l2(){if(!(Vf||LS()))try{MS(DS(await Il(!1,"",{includeJoinRequests:!1})))}catch{}}function ai(e,t){const n=Le("viewerReconnectOverlay"),r=Le("viewerReconnectDetail");!n||!r||(n.hidden=!e,r.textContent=t||"Trying again automatically while the viewer comes back.")}async function Kf(){try{return await FC(),!0}catch{return!1}}function d2(){return document.visibilityState!=="hidden"&&!Ow()}function FS(){return`${C.activeTab}:${C.advancedSection}:${C.syncPairingOpen}`}function u2(e){C.refreshQueued||e.surface!==FS()||!e.refreshSucceeded||!fl||nn||(fl=!1,Ld("connection_restored"))}function BS(){if(nn)return;nn=!0,fl=!0,Ld("connection_lost"),zf(),uv(),si("error","(reconnecting)"),ai(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await Kf()){if(vr&&(clearTimeout(vr),vr=null),nn=!1,ai(!0,"Viewer responded. Restoring your session…"),d2()){si("refreshing"),Ba();try{await hl()}catch{}}else si("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");nn||ai(!1);return}ai(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),vr=setTimeout(e,ES)};vr=setTimeout(e,ES)}function si(e,t){C.refreshState=e;const n=Le("refreshStatus");if(!n)return;n.dataset.refreshState=e;const r=o=>{const s=Le("refreshAnnouncer");!s||Hf===e||(s.textContent=o,Hf=e)};if(e==="refreshing"){n.textContent="refreshing…";return}if(e==="paused"){n.textContent="paused",r("Auto refresh paused.");return}if(e==="error"&&t==="(reconnecting)"){n.textContent="reconnecting…",r("Viewer reconnecting.");return}if(e==="error"){n.textContent="refresh failed",r("Refresh failed.");return}const i=t?` ${t}`:"";n.textContent=`updated ${new Date().toLocaleTimeString()}${i}`,Hf=null}function zf(){C.refreshTimer&&(clearInterval(C.refreshTimer),C.refreshTimer=null)}function Ba(){C.refreshTimer||(C.refreshTimer=setInterval(()=>yr(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(zf(),si("paused","(tab hidden)")):!Ow()&&!nn&&(Ba(),yr())});function qS(){const e=C.advancedSection==="sync",t=Le("advancedSyncContent"),n=Le("advancedTeamsContent");t&&(t.hidden=!e),n&&(n.hidden=e);const r=Le("advancedSyncButton"),i=Le("advancedTeamsButton");r?.setAttribute("aria-pressed",String(e)),i?.setAttribute("aria-pressed",String(!e)),queueMicrotask(()=>{const o=window.location.hash.replace(/^#/,"");$f(o==="sync/diagnostics"||o==="advanced/sync/diagnostics"?"diagnostics":"main")})}var p2=rE();function US(e){const t=new Set(KN(C.lastCoordinatorAdminStatus));Dr.forEach(r=>{const i=Le(`tab-${r}`);i&&(i.hidden=r!==e||!t.has(r))}),Dr.forEach(r=>{const i=Le(`tabBtn-${r}`);if(!i)return;i.hidden=!t.has(r);const o=r===e&&t.has(r);i.classList.toggle("active",o),o?i.setAttribute("aria-current","page"):i.removeAttribute("aria-current")});const n=Le(`tabBtn-${e}`);n&&p2(n),qS()}function ci(e,t={}){const n=Go(e,C.lastCoordinatorAdminStatus);n==="advanced"&&ru(t.advancedSection??nu()??C.advancedSection),Vv(n,t.canonicalHash?{canonicalHash:!0}:{}),US(n),yr()}function f2(){Dr.forEach(e=>{Le(`tabBtn-${e}`)?.addEventListener("click",()=>ci(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),Le("advancedSyncButton")?.addEventListener("click",()=>ru("sync",!0)),Le("advancedTeamsButton")?.addEventListener("click",()=>{ru("teams",!0),qS(),queueMicrotask(()=>document.getElementById("coordinatorAdminLegacyNoticeTitle")?.focus())}),Le("coordinatorAdminOpenSharing")?.addEventListener("click",()=>{ci("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),window.addEventListener("hashchange",()=>{const e=tu();if(e){const t=nu();ci(e,t?{advancedSection:t}:{}),e==="advanced"&&t==="teams"&&queueMicrotask(()=>document.getElementById("coordinatorAdminLegacyNoticeTitle")?.focus())}}),ci(C.activeTab)}async function m2(){try{const e=await Va();C.knownProjects=e,n2();const t=Zd("projectFilter");if(!t)return;t.textContent="";const n=document.createElement("option");n.value="",n.textContent="All Projects",t.appendChild(n),e.forEach(r=>{const i=document.createElement("option");i.value=r,i.textContent=r,t.appendChild(i)})}catch{}}function h2(e){C.pendingDeviceIdentityFocus=e?.trim()||null,ci("devices",{canonicalHash:!0})}var qa=qT({},{onOpenTeamSetup:cw,onReviewDevices:h2}),GS={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Wf=0,Jf=null,Vt=null;async function g2(){const e=[];let t=0;for(;;){const n=await bo({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return ys(e)}function v2(){const e=new Map,t={unknown:0,offline:1,available:2},n=(r,i)=>{!r||t[i]<=t[e.get(r)??"unknown"]||e.set(r,i)};for(const r of C.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"offline":"available");for(const r of C.lastSyncPeers){const i=String(r.peer_device_id??"").trim(),o=Da(r);n(i,o==="connected"||o==="available"?"available":o==="offline"?"offline":"unknown")}return[...e].map(([r,i])=>({deviceId:r,state:i}))}function y2(){return C.lastSyncPeers.flatMap(e=>{const t=String(e.peer_device_id??"").trim();return t?[{deviceId:t,runtimeVersion:e.runtime_version??null,runtimeVersionObservedAt:e.runtime_version_observed_at??null}]:[]})}function HS(e){if(e==="advanced_sync"){ci("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("tabBtn-advanced")?.focus());return}ci(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}function Yf(){const e=document.getElementById("devicesMount");if(!e)return Promise.resolve(!0);const t=b2(e,++Wf);return Jf=t,t}async function b2(e,t){Vt||bc(e,GS,{version:1,items:[]},[],[],{loading:!0});try{const[n,r,i,o,s]=await Promise.all([g2(),El(),vR(),Al().then(u=>({inventory:u,unavailable:!1})).catch(()=>({inventory:Vt?.inventory,unavailable:!0})),ul({requiredSurface:"devices"})]);if(t!==Wf)return Jf??!1;const c=v2(),l=y2(),d=Om(C.lastSyncStatus);return!o.unavailable&&o.inventory&&(C.lastDeviceIdentityInventory=o.inventory),C.deviceIdentityInventoryLoadError=o.unavailable,bc(e,r,i,n,c,{inventory:o.inventory,inventoryUnavailable:o.unavailable,coordinatorEnrollmentIssueCount:d,onCommitted:async()=>{const[u,p]=await Promise.all([Yf(),qa()]);return u&&p},onNavigate:HS,peerRuntimeMetadata:l}),Vt={projects:n,intent:r,reconciliation:i,availability:c,peerRuntimeMetadata:l,inventory:o.inventory,inventoryUnavailable:o.unavailable,coordinatorEnrollmentIssueCount:d},s}catch{return t!==Wf?Jf??!1:(Vt?bc(e,Vt.intent,Vt.reconciliation,Vt.projects,Vt.availability,{coordinatorEnrollmentIssueCount:Vt.coordinatorEnrollmentIssueCount,inventory:Vt.inventory,inventoryUnavailable:Vt.inventoryUnavailable,onCommitted:async()=>{const[n,r]=await Promise.all([Yf(),qa()]);return n&&r},onNavigate:HS,peerRuntimeMetadata:Vt.peerRuntimeMetadata,refreshError:!0}):bc(e,GS,{version:1,items:[]},[],[],{loadError:!0}),!1)}}Zd("projectFilter")?.addEventListener("change",()=>{C.currentProject=Zd("projectFilter")?.value||"",Qr(!0),yr()});var Xf=null;async function _2(){await Promise.all([iM(),vF(),HP().catch(()=>{})])}function w2(e,t,n){if(t==="feed"){const o=qD();e.push(hb(o),zp())}if(t==="projects"&&e.push(Na().then(n)),t==="sharing"&&e.push(qa().then(n)),t==="devices"&&e.push(Yf().then(n)),t==="health"&&e.push(ul({requiredSurface:"health",requireFreshSyncStatus:fl}).then(n)),t==="advanced"&&C.advancedSection==="sync"&&e.push(ul().then(n)),t==="advanced"&&C.advancedSection==="teams"&&e.push(gc().then(n)),!C.syncPairingOpen)return;const r=t==="advanced"&&C.advancedSection==="sync",i=r2();e.push(r?i.then(n):i)}async function yr(){nn||(Xf&&clearTimeout(Xf),Xf=setTimeout(()=>hl(),80))}async function hl(){if(!nn){if(C.refreshInFlight){C.refreshQueued=!0;return}C.refreshInFlight=!0;try{si("refreshing");const e=C.activeTab,t=FS(),n=[_2()];let r=!0;w2(n,e,o=>{r=r&&o}),await Promise.all(n),MS(DS(C.lastSyncLegacySharedReview));const i=Go(C.activeTab,C.lastCoordinatorAdminStatus);i!==C.activeTab&&Vv(i),US(C.activeTab),si(r?"idle":"error"),u2({refreshSucceeded:r,surface:t})}catch{await Kf()?si("error"):BS()}finally{C.refreshInFlight=!1,C.refreshQueued&&!nn&&(C.refreshQueued=!1,hl())}}}tE();var VS=document.getElementById("toastRoot");VS&&ON(VS);var KS=document.getElementById("diagnosticsDrawerMount");KS&&GP(KS);var zS=document.getElementById("legacyTeamSetupMount");zS&&e1(zS,{onCompleted:async()=>{let e,t;const n={requireTeamSetupSummary:!0};if(C.activeTab==="sharing"?(t=await Na(n),e=await qa(n)):(e=await qa(n),t=await Na(n)),!e||!t)throw new Error("team_setup_refresh_failed")}}),iE(js("themeToggle")),Jv(ou()),f2(),Fj(),VP(),q1(()=>yr(),{onOpenTeamSetup:cw}),o2(()=>yr()),WD(),YF(zf,Ba,()=>yr()),m2(),Le("viewerReconnectRetry")?.addEventListener("click",async()=>{if(Ld("reconnect_requested"),ai(!0,"Checking whether the viewer server is back…"),!await Kf()){BS();return}vr&&(clearTimeout(vr),vr=null),nn=!1,ai(!0,"Viewer responded. Restoring your session…"),Ba();try{await hl()}catch{}nn||ai(!1)}),Le("legacyUpgradeReviewGroups")?.addEventListener("click",()=>{ml(),Fa(!1),window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)}),Le("legacyUpgradeReviewProjects")?.addEventListener("click",()=>{ml(),Fa(!1),window.location.hash="projects"}),Le("legacyUpgradeNotNow")?.addEventListener("click",()=>{ml(),Fa(!1)}),s2(),l2(),yr(),Ba()})();
107
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${yn(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=z_(e);if(i===null)return r;e=i;let a='<a href="'+e+'"';return t&&(a+=' title="'+yn(t)+'"'),a+=">"+r+"</a>",a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=z_(e);if(i===null)return yn(n);e=i;let a=`<img src="${e}" alt="${yn(n)}"`;return t&&(a+=` title="${yn(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:yn(e.text)}},af=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},nn=class jm{options;renderer;textRenderer;constructor(t){this.options=t||ni,this.options.renderer=this.options.renderer||new Wc,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new af}static parse(t,n){return new jm(n).parse(t)}static parseInline(t,n){return new jm(n).parseInline(t)}parse(t){this.renderer.parser=this;let n="";for(let r=0;r<t.length;r++){let i=t[r];if(this.options.extensions?.renderers?.[i.type]){let s=i,c=this.options.extensions.renderers[s.type].call({parser:this},s);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(s.type)){n+=c||"";continue}}let a=i;switch(a.type){case"space":n+=this.renderer.space(a);break;case"hr":n+=this.renderer.hr(a);break;case"heading":n+=this.renderer.heading(a);break;case"code":n+=this.renderer.code(a);break;case"table":n+=this.renderer.table(a);break;case"blockquote":n+=this.renderer.blockquote(a);break;case"list":n+=this.renderer.list(a);break;case"checkbox":n+=this.renderer.checkbox(a);break;case"html":n+=this.renderer.html(a);break;case"def":n+=this.renderer.def(a);break;case"paragraph":n+=this.renderer.paragraph(a);break;case"text":n+=this.renderer.text(a);break;default:{let s='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}parseInline(t,n=this.renderer){this.renderer.parser=this;let r="";for(let i=0;i<t.length;i++){let a=t[i];if(this.options.extensions?.renderers?.[a.type]){let c=this.options.extensions.renderers[a.type].call({parser:this},a);if(c!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(a.type)){r+=c||"";continue}}let s=a;switch(s.type){case"escape":r+=n.text(s);break;case"html":r+=n.html(s);break;case"link":r+=n.link(s);break;case"image":r+=n.image(s);break;case"checkbox":r+=n.checkbox(s);break;case"strong":r+=n.strong(s);break;case"em":r+=n.em(s);break;case"codespan":r+=n.codespan(s);break;case"br":r+=n.br(s);break;case"del":r+=n.del(s);break;case"text":r+=n.text(s);break;default:{let c='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return r}},bo=class{options;block;constructor(e){this.options=e||ni}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?tn.lex:tn.lexInline}provideParser(e=this.block){return e?nn.parse:nn.parseInline}},VO=class{defaults=Yp();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=nn;Renderer=Wc;TextRenderer=af;Lexer=tn;Tokenizer=zc;Hooks=bo;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case"table":{let i=r;for(let a of i.header)n=n.concat(this.walkTokens(a.tokens,t));for(let a of i.rows)for(let s of a)n=n.concat(this.walkTokens(s.tokens,t));break}case"list":{let i=r;n=n.concat(this.walkTokens(i.items,t));break}default:{let i=r;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(a=>{let s=i[a].flat(1/0);n=n.concat(this.walkTokens(s,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let a=t.renderers[i.name];a?t.renderers[i.name]=function(...s){let c=i.renderer.apply(this,s);return c===!1&&(c=a.apply(this,s)),c}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=t[i.level];a?a.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),r.extensions=t),n.renderer){let i=this.defaults.renderer||new Wc(this.defaults);for(let a in n.renderer){if(!(a in i))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let s=a,c=n.renderer[s],l=i[s];i[s]=(...d)=>{let u=c.apply(i,d);return u===!1&&(u=l.apply(i,d)),u||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new zc(this.defaults);for(let a in n.tokenizer){if(!(a in i))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let s=a,c=n.tokenizer[s],l=i[s];i[s]=(...d)=>{let u=c.apply(i,d);return u===!1&&(u=l.apply(i,d)),u}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new bo;for(let a in n.hooks){if(!(a in i))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let s=a,c=n.hooks[s],l=i[s];bo.passThroughHooks.has(a)?i[s]=d=>{if(this.defaults.async&&bo.passThroughHooksRespectAsync.has(a))return(async()=>{let p=await c.call(i,d);return l.call(i,p)})();let u=c.call(i,d);return l.call(i,u)}:i[s]=(...d)=>{if(this.defaults.async)return(async()=>{let p=await c.apply(i,d);return p===!1&&(p=await l.apply(i,d)),p})();let u=c.apply(i,d);return u===!1&&(u=l.apply(i,d)),u}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,a=n.walkTokens;r.walkTokens=function(s){let c=[];return c.push(a.call(this,s)),i&&(c=c.concat(i.call(this,s))),c}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return tn.lex(e,t??this.defaults)}parser(e,t){return nn.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let s=i.hooks?await i.hooks.preprocess(t):t,c=await(i.hooks?await i.hooks.provideLexer(e):e?tn.lex:tn.lexInline)(s,i),l=i.hooks?await i.hooks.processAllTokens(c):c;i.walkTokens&&await Promise.all(this.walkTokens(l,i.walkTokens));let d=await(i.hooks?await i.hooks.provideParser(e):e?nn.parse:nn.parseInline)(l,i);return i.hooks?await i.hooks.postprocess(d):d})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let s=(i.hooks?i.hooks.provideLexer(e):e?tn.lex:tn.lexInline)(t,i);i.hooks&&(s=i.hooks.processAllTokens(s)),i.walkTokens&&this.walkTokens(s,i.walkTokens);let c=(i.hooks?i.hooks.provideParser(e):e?nn.parse:nn.parseInline)(s,i);return i.hooks&&(c=i.hooks.postprocess(c)),c}catch(s){return a(s)}}}onError(e,t){return n=>{if(n.message+=`
108
+ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error occurred:</p><pre>"+yn(n.message+"",!0)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},ii=new VO;function Me(e,t){return ii.parse(e,t)}Me.options=Me.setOptions=function(e){return ii.setOptions(e),Me.defaults=ii.defaults,L_(Me.defaults),Me},Me.getDefaults=Yp,Me.defaults=ni;function KO(...e){return ii.use(...e),Me.defaults=ii.defaults,L_(Me.defaults),Me}Me.use=KO,Me.walkTokens=function(e,t){return ii.walkTokens(e,t)},Me.parseInline=ii.parseInline,Me.Parser=nn,Me.parser=nn.parse,Me.Renderer=Wc,Me.TextRenderer=af,Me.Lexer=tn,Me.lexer=tn.lex,Me.Tokenizer=zc,Me.Hooks=bo,Me.parse=Me;var YH=Me.options,XH=Me.setOptions,QH=Me.walkTokens,ZH=Me.parseInline,eV=nn.parse,tV=tn.lex,zO={ALLOWED_TAGS:["p","br","strong","em","code","pre","ul","ol","li","blockquote","a","h1","h2","h3","h4","h5","h6","hr"],ALLOWED_ATTR:["href","title"],ALLOW_DATA_ATTR:!1};function WO(e){const t=String(e||"").trim();if(!t)return!1;if(t.startsWith("#")||t.startsWith("/"))return!0;const n=t.toLowerCase();return n.startsWith("http://")||n.startsWith("https://")||n.startsWith("mailto:")}D_.addHook("afterSanitizeAttributes",e=>{e.tagName==="A"&&(WO(e.getAttribute("href")||"")?(e.setAttribute("rel","noopener noreferrer"),e.setAttribute("target","_blank")):e.removeAttribute("href"))});function of(e){const t=Me.parse(String(e||""),{async:!1});return D_.sanitize(t,zO)}function JO(e){const t=["request","outcome","plan","completed","learned","investigated","next","next_steps","notes"],n=Object.keys(e);return t.filter(r=>n.includes(r)).map(r=>{const i=String(e[r]||"").trim();return i?g("div",{className:"summary-section",key:r},g("div",{className:"summary-section-label"},k$(r)),g("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:of(i)}})):null}).filter(Boolean)}function YO(e){const t=e.map(n=>String(n||"").trim()).filter(Boolean);if(!t.length)return null;if(t.every(n=>/.+?:\s+.+/.test(n))){const n=t.map((r,i)=>{const a=r.indexOf(":"),s=r.slice(0,a).trim(),c=r.slice(a+1).trim();return!s||!c?null:g("div",{className:"summary-section",key:`${s}-${i}`},g("div",{className:"summary-section-label"},s),g("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:of(c)}}))}).filter(Boolean);if(n.length)return g("div",{className:"feed-body facts"},n)}return g("div",{className:"feed-body"},g("ul",null,t.map((n,r)=>g("li",{key:`${n}-${r}`},n))))}function X_(e,t="feed-body"){const n=String(e||"").trim();return n?g("div",{className:t,dangerouslySetInnerHTML:{__html:of(n)}}):null}function XO(e){const t=["request","outcome","plan","completed","learned","investigated","next","next_steps","notes"],n=s=>{if(!s||typeof s!="object"||Array.isArray(s))return!1;const c=s;return t.some(l=>{const d=c[l];return typeof d=="string"&&d.trim().length>0})},r=e?.summary;if(r&&typeof r=="object"&&!Array.isArray(r)){const s=r.summary;if(n(r))return r;if(n(s))return s}const i=e?.metadata_json;if(n(i))return i;if(i&&n(i.summary))return i.summary;const a=String(e?.body_text||"").trim();if(a.includes("## ")){const s={request:"request",completed:"completed",learned:"learned",investigated:"investigated","next steps":"next_steps",notes:"notes"},c={},l=/(?:^|\n)##\s+([^\n]+)\n([\s\S]*?)(?=\n##\s+|$)/g;for(let d=l.exec(a);d;d=l.exec(a)){const u=s[String(d[1]||"").trim().toLowerCase()],p=String(d[2]||"").trim();u&&p&&(c[u]=p)}if(n(c))return c}return null}function Jc(e,t){return String(e?.kind||"").toLowerCase()==="session_summary"||t?.is_summary===!0?!0:String(t?.source||"").trim().toLowerCase()==="observer_summary"}function QO(e,t){const n=String(e?.kind||"").trim().toLowerCase();return Jc(e,t)?"session_summary":n||"change"}var ZO=Object.defineProperty,He=(e,t)=>ZO(e,"name",{value:t,configurable:!0}),sf=["Enter"," "],eM=["ArrowDown","PageUp","Home"],Q_=["ArrowUp","PageDown","End"],tM=[...eM,...Q_],nV={ltr:[...sf,"ArrowRight"],rtl:[...sf,"ArrowLeft"]},Yc="Menu",[cf,nM,rM]=Ua(Yc),[ai,Z_]=dt(Yc,[rM,ar,Ui]),lf=ar(),ew=Ui(),[iM,_o]=ai(Yc),[aM,df]=ai(Yc),oM=He(e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:a,modal:s=!0}=e,c=lf(t),[l,d]=D(null),u=B(!1),p=ht(a),f=qi(i);return V(()=>{const m=He(()=>{u.current=!0,document.addEventListener("pointerdown",v,{capture:!0,once:!0}),document.addEventListener("pointermove",v,{capture:!0,once:!0})},"handleKeyDown"),v=He(()=>u.current=!1,"handlePointer");return document.addEventListener("keydown",m,{capture:!0}),()=>{document.removeEventListener("keydown",m,{capture:!0}),document.removeEventListener("pointerdown",v,{capture:!0}),document.removeEventListener("pointermove",v,{capture:!0})}},[]),V(()=>{if(!n)return;const m=He(()=>p(!1),"handleBlur");return window.addEventListener("blur",m),()=>window.removeEventListener("blur",m)},[n,p]),o(vc,{...c,children:o(iM,{scope:t,open:n,onOpenChange:p,content:l,onContentChange:d,children:o(aM,{scope:t,onClose:oe(()=>p(!1),[p]),isUsingKeyboardRef:u,dir:f,modal:s,children:r})})})},"Menu"),sM=W(He(function(t,n){const{__scopeMenu:r,...i}=t,a=lf(r);return o(eo,{...a,...i,ref:n})},"MenuAnchor")),tw="MenuPortal",[cM,lM]=ai(tw,{forceMount:void 0}),dM=He(e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,a=_o(tw,t);return o(cM,{scope:t,forceMount:n,children:o(Pt,{present:n||a.open,children:o(Ti,{asChild:!0,container:i,children:r})})})},"MenuPortal"),mr="MenuContent",[uM,nw]=ai(mr),pM=W(He(function(t,n){const r=lM(mr,t.__scopeMenu),{forceMount:i=r.forceMount,...a}=t,s=_o(mr,t.__scopeMenu),c=df(mr,t.__scopeMenu);return o(cf.Provider,{scope:t.__scopeMenu,children:o(Pt,{present:i||s.open,children:o(cf.Slot,{scope:t.__scopeMenu,children:c.modal?o(fM,{...a,ref:n}):o(mM,{...a,ref:n})})})})},"MenuContent")),fM=W(He(function(t,n){const r=_o(mr,t.__scopeMenu),i=B(null),a=Se(n,i);return V(()=>{const s=i.current;if(s)return ks(s)},[]),o(rw,{...t,ref:a,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:ne(t.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})},"MenuRootContentModal")),mM=W(He(function(t,n){const r=_o(mr,t.__scopeMenu);return o(rw,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})},"MenuRootContentNonModal")),hM=dn("MenuContent.ScrollLock"),rw=W(He(function(t,n){const{__scopeMenu:r,loop:i=!1,trapFocus:a,onOpenAutoFocus:s,onCloseAutoFocus:c,disableOutsidePointerEvents:l,onEntryFocus:d,onEscapeKeyDown:u,onPointerDownOutside:p,onFocusOutside:f,onInteractOutside:m,onDismiss:v,disableOutsideScroll:b,...h}=t,y=_o(mr,r),w=df(mr,r),_=lf(r),R=ew(r),I=nM(r),[T,A]=D(null),L=B(null),F=Se(n,L,y.onContentChange),N=B(0),j=B(""),x=B(0),U=B(null),q=B("right"),$=B(0),E=b?Ea:z,C=b?{as:hM,allowPinchZoom:!0}:void 0,O=He(G=>{const ee=j.current+G,Z=I().filter(Ne=>!Ne.disabled),ie=document.activeElement,fe=Z.find(Ne=>Ne.ref.current===ie)?.textValue,Ce=lw(Z.map(Ne=>Ne.textValue),ee,fe),Pe=Z.find(Ne=>Ne.textValue===Ce)?.ref.current;He((function Ne(ce){j.current=ce,window.clearTimeout(N.current),ce!==""&&(N.current=window.setTimeout(()=>Ne(""),1e3))}),"updateSearch")(ee),Pe&&setTimeout(()=>Pe.focus())},"handleTypeaheadSearch");V(()=>()=>window.clearTimeout(N.current),[]),Ei();const H=oe(G=>q.current===U.current?.side&&uw(G,U.current?.area),[]);return o(uM,{scope:r,searchRef:j,onItemEnter:oe(G=>{H(G)&&G.preventDefault()},[H]),onItemLeave:oe(G=>{H(G)||(L.current?.focus(),A(null))},[H]),onTriggerLeave:oe(G=>{H(G)&&G.preventDefault()},[H]),pointerGraceTimerRef:x,onPointerGraceIntentChange:oe(G=>{U.current=G},[]),children:o(E,{...C,children:o(vs,{asChild:!0,trapped:a,onMountAutoFocus:ne(s,G=>{G.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:c,children:o(ki,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:u,onPointerDownOutside:p,onFocusOutside:f,onInteractOutside:m,onDismiss:v,children:o($u,{asChild:!0,...R,dir:w.dir,orientation:"vertical",loop:i,currentTabStopId:T,onCurrentTabStopIdChange:A,onEntryFocus:ne(d,G=>{w.isUsingKeyboardRef.current||G.preventDefault()}),preventScrollOnEntryFocus:!0,children:o(yc,{role:"menu","aria-orientation":"vertical","data-state":aw(y.open),"data-radix-menu-content":"",dir:w.dir,..._,...h,ref:F,style:{outline:"none",...h.style},onKeyDown:ne(h.onKeyDown,G=>{const ee=G.target.closest("[data-radix-menu-content]")===G.currentTarget,Z=G.ctrlKey||G.altKey||G.metaKey,ie=G.key.length===1;ee&&(G.key==="Tab"&&G.preventDefault(),!Z&&ie&&O(G.key));const fe=L.current;if(G.target!==fe||!tM.includes(G.key))return;G.preventDefault();const Ce=I().filter(Pe=>!Pe.disabled).map(Pe=>Pe.ref.current);Q_.includes(G.key)&&Ce.reverse(),sw(Ce)}),onBlur:ne(t.onBlur,G=>{G.currentTarget.contains(G.target)||(window.clearTimeout(N.current),j.current="")}),onPointerMove:ne(t.onPointerMove,Xc(G=>{const ee=G.target,Z=$.current!==G.clientX;if(G.currentTarget.contains(ee)&&Z){const ie=G.clientX>$.current?"right":"left";q.current=ie,$.current=G.clientX}}))})})})})})})},"MenuContentImpl")),uf="MenuItem",iw="menu.itemSelect",gM=W(He(function(t,n){const{disabled:r=!1,onSelect:i,...a}=t,s=B(null),c=df(uf,t.__scopeMenu),l=nw(uf,t.__scopeMenu),d=Se(n,s),u=B(!1),p=He(()=>{const f=s.current;if(!r&&f){const m=new CustomEvent(iw,{bubbles:!0,cancelable:!0});f.addEventListener(iw,v=>i?.(v),{once:!0}),gs(f,m),m.defaultPrevented?u.current=!1:c.onClose()}},"handleSelect");return o(vM,{...a,ref:d,disabled:r,onClick:ne(t.onClick,p),onPointerDown:f=>{t.onPointerDown?.(f),u.current=!0},onPointerUp:ne(t.onPointerUp,f=>{u.current||f.currentTarget?.click()}),onKeyDown:ne(t.onKeyDown,f=>{r||f.target!==f.currentTarget||l.searchRef.current!==""&&f.key===" "||sf.includes(f.key)&&(f.currentTarget.click(),f.preventDefault())})})},"MenuItem")),vM=W(He(function(t,n){const{__scopeMenu:r,disabled:i=!1,textValue:a,...s}=t,c=nw(uf,r),l=ew(r),d=B(null),u=Se(n,d),[p,f]=D(!1),[m,v]=D("");return V(()=>{const b=d.current;b&&v((b.textContent??"").trim())},[s.children]),o(cf.ItemSlot,{scope:r,disabled:i,textValue:a??m,children:o(ju,{asChild:!0,...l,focusable:!i,children:o(ge.div,{role:"menuitem","data-highlighted":p?"":void 0,"aria-disabled":i||void 0,"data-disabled":i?"":void 0,...s,ref:u,onPointerMove:ne(t.onPointerMove,Xc(b=>{i?c.onItemLeave(b):(c.onItemEnter(b),b.defaultPrevented||b.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:ne(t.onPointerLeave,Xc(b=>c.onItemLeave(b))),onFocus:ne(t.onFocus,()=>f(!0)),onBlur:ne(t.onBlur,()=>f(!1))})})})},"MenuItemImpl")),[rV,iV]=ai("MenuRadioGroup",{value:void 0,onValueChange:He(()=>{},"onValueChange")}),yM="MenuItemIndicator",[aV,oV]=ai(yM,{checked:!1}),bM="MenuSub",[sV,cV]=ai(bM);function aw(e){return e?"open":"closed"}He(aw,"getOpenState");function ow(e){return e==="indeterminate"}He(ow,"isIndeterminate");function _M(e){return ow(e)?"indeterminate":e?"checked":"unchecked"}He(_M,"getCheckedState");function sw(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}He(sw,"focusFirst");function cw(e,t){return e.map((n,r)=>e[(t+r)%e.length])}He(cw,"wrapArray");function lw(e,t,n){const r=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let a=cw(e,Math.max(i,0));r.length===1&&(a=a.filter(c=>c!==n));const s=a.find(c=>c.toLowerCase().startsWith(r.toLowerCase()));return s!==n?s:void 0}He(lw,"getNextMatch");function dw(e,t){const{x:n,y:r}=e;let i=!1;for(let a=0,s=t.length-1;a<t.length;s=a++){const c=t[a],l=t[s],d=c.x,u=c.y,p=l.x,f=l.y;u>r!=f>r&&n<(p-d)*(r-u)/(f-u)+d&&(i=!i)}return i}He(dw,"isPointInPolygon");function uw(e,t){return t?dw({x:e.clientX,y:e.clientY},t):!1}He(uw,"isPointerInGraceArea");function Xc(e){return t=>t.pointerType==="mouse"?e(t):void 0}He(Xc,"whenMouse");var wM=oM,SM=sM,CM=dM,RM=pM,IM=gM,kM=Object.defineProperty,wo=(e,t)=>kM(e,"name",{value:t,configurable:!0}),pf="DropdownMenu",[TM,lV]=dt(pf,[Z_]),So=Z_(),[PM,pw]=TM(pf),NM=wo(e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:a,onOpenChange:s,modal:c=!0}=e,l=So(t),d=B(null),[u,p]=Dt({prop:i,defaultProp:a??!1,onChange:s,caller:pf});return o(PM,{scope:t,triggerId:xt(),triggerRef:d,contentId:xt(),open:u,onOpenChange:p,onOpenToggle:oe(()=>p(f=>!f),[p]),modal:c,children:o(wM,{...l,open:u,onOpenChange:p,dir:r,modal:c,children:n})})},"DropdownMenu"),EM="DropdownMenuTrigger",AM=W(wo(function(t,n){const{__scopeDropdownMenu:r,disabled:i=!1,...a}=t,s=pw(EM,r),c=So(r),l=Se(n,s.triggerRef);return o(SM,{asChild:!0,...c,children:o(ge.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":i?"":void 0,disabled:i,...a,ref:l,onPointerDown:ne(t.onPointerDown,d=>{!i&&d.button===0&&d.ctrlKey===!1&&(s.onOpenToggle(),s.open||d.preventDefault())}),onKeyDown:ne(t.onKeyDown,d=>{i||(["Enter"," "].includes(d.key)&&s.onOpenToggle(),d.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(d.key)&&d.preventDefault())})})})},"DropdownMenuTrigger")),xM=wo(e=>{const{__scopeDropdownMenu:t,...n}=e,r=So(t);return o(CM,{...r,...n})},"DropdownMenuPortal"),DM="DropdownMenuContent",LM=W(wo(function(t,n){const{__scopeDropdownMenu:r,...i}=t,a=pw(DM,r),s=So(r),c=B(!1);return o(RM,{id:a.contentId,"aria-labelledby":a.triggerId,...s,...i,ref:n,onCloseAutoFocus:ne(t.onCloseAutoFocus,l=>{c.current||a.triggerRef.current?.focus(),c.current=!1,l.preventDefault()}),onInteractOutside:ne(t.onInteractOutside,l=>{const d=l.detail.originalEvent,u=d.button===0&&d.ctrlKey===!0,p=d.button===2||u;(!a.modal||p)&&(c.current=!0)}),style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})},"DropdownMenuContent")),$M=W(wo(function(t,n){const{__scopeDropdownMenu:r,...i}=t,a=So(r);return o(IM,{...a,...i,ref:n})},"DropdownMenuItem")),jM=NM,OM=AM,MM=xM,FM=LM,fw=$M;function BM({assignProjectDisabled:e,disabled:t,onAssignProject:n,onForget:r,title:i}){return g(jM,null,g(OM,{asChild:!0},g("button",{"aria-label":`Actions for ${i}`,className:"feed-menu-trigger",type:"button"},"⋯")),g(MM,null,g(FM,{align:"end",className:"feed-menu-panel",side:"bottom",sideOffset:4},g(fw,{className:"feed-menu-item",disabled:e,onSelect:()=>n()},e?"Moving…":"Assign to project…"),g(fw,{className:"feed-menu-item danger",disabled:t,onSelect:()=>r()},t?"Forgetting…":"Forget memory"))))}function qM({modes:e,active:t,onSelect:n}){return e.length<=1?null:g("div",{className:"feed-toggle"},e.map(r=>g("button",{key:r.id,className:`toggle-button${r.id===t?" active":""}`,"data-filter":r.id,onClick:()=>n(r.id),type:"button"},r.label)))}function ff({label:e,variant:t=""}){return g(qp,{variant:"provenance",tone:t||void 0},e)}function UM({tag:e}){const t=P$(e);return t?g(qp,{variant:"tag",title:String(e)},t):null}function GM({item:e,onReplace:t,onRemove:n,onViewRefresh:r,onReload:i}){const a=jc(e?.metadata_json),s=Jc(e,a),c=QO(e,a),l=Nt(e),d=e.title||"(untitled)",u=s&&a?.request?a.request:d,p=e.created_at||e.created_at_utc,f=C$(p),m=D$(e),v=$c(e.files||[]),b=e.project||"",h=j$(e),y=O$(e,a),w=String(e.visibility||a?.visibility||"private").trim(),_=String(e.workspace_kind||a?.workspace_kind||"").trim(),R=String(e.origin_source||a?.origin_source||"").trim(),I=String(e.trust_state||a?.trust_state||"").trim(),T=v.length?` · ${T$(v)}`:"",A=Number(e.id||0),L=A>0?`ID ${A}`:"",[F,N]=D(S.newItemKeys.has(l)),j=s?XO({...e,metadata_json:a}):null,x=s?null:fj({...e,metadata_json:a}),U=x?mj(x):[],q=x?hj(x):"summary",$=S.itemViewState.get(l),E=x&&$&&U.some(Re=>Re.id===$)?$:q,[C,O]=D(E),H=`${l}:${C}`,[G,ee]=D(S.itemExpandState.get(H)===!0),[Z,ie]=D(w==="shared"?"shared":"private"),[fe,Ce]=D(!1),[Pe,Ne]=D(!1),[ce,me]=D(!1),J=j?JO(j):[];V(()=>{x&&(U.some(Re=>Re.id===C)||O(q))},[C,q,U,x]),V(()=>{S.itemViewState.set(l,C)},[C,l]),V(()=>{const Re=`${l}:${C}`;ee(S.itemExpandState.get(Re)===!0)},[C,l]),V(()=>{ie(w==="shared"?"shared":"private")},[w]),V(()=>{if(!F)return;const Re=window.setTimeout(()=>{S.newItemKeys.delete(l),N(!1)},700);return()=>window.clearTimeout(Re)},[F,l]);const se=Z,ye=se==="shared"?"This memory can sync to peers allowed by your project filters.":"This memory stays on this device unless a matching local assignment allows it to sync.",le=[b?`Project ${b}`:"No project",f].filter(Boolean).join(" · "),Ee=[_&&_!==w?`Workspace ${_}`:"",R?`From ${R}`:"",y,I&&I!=="trusted"?$$(I):""].filter(Boolean).join(" · "),re=[T.trim(),Ee].filter(Boolean).join(" · "),Q=x?gj(C,x):!1,we=[C==="facts"?"feed-body facts":"feed-body",C==="narrative"?"narrative":"",Q&&!G?vj(C).join(" "):""].filter(Boolean).join(" "),ae=s?J.length?g("div",{className:"feed-body facts"},J):X_(String(e.body_text||""))||g("div",{className:"feed-body"}):x?C==="facts"?YO(x.facts)||g("div",{className:we}):X_(C==="narrative"?x.narrative:x.summary,we)||g("div",{className:we}):g("div",{className:"feed-body"});async function Fe(Re){const et=se;ie(Re),Ce(!0);try{const tt=await RR(A,Re);tt?.item&&(t(tt.item),r()),X(Re==="shared"?"Memory will now sync as shared context.":"Memory is private again.")}catch(tt){ie(et),X(tt instanceof Error?tt.message:"Failed to save visibility.","warning")}finally{Ce(!1)}}async function Je(){const Re=String(e.project||"").trim(),et=Re,tt=String(u||"this memory").trim(),Cn=tt.length>80?`${tt.slice(0,79).trimEnd()}…`:tt,Yo=Re?`Move "${Cn}" from "${Re}" to another project. Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`:`Assign a project to "${Cn}". Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`;let gi=[];try{gi=(await es()).filter(lt=>lt&&lt!==Re)}catch{}const vi=await Tp({title:"Assign to project",description:Yo,initialValue:et,placeholder:"Pick one or type a new project name",suggestions:gi,confirmLabel:"Move",cancelLabel:"Cancel",validate:lt=>{const Rn=lt.trim();return Rn?Rn===Re?"Already assigned to this project.":null:"Enter a project name."}});if(vi==null)return;const yi=vi.trim();if(!(!yi||yi===Re)){me(!0);try{const lt=await IR(A,yi),Rn=Number(lt.moved_memory_count||1),ga=Rn>1?`Moved ${Rn} memories from this session to "${lt.project}".`:`Moved to "${lt.project}".`;X(ga),await i(),r()}catch(lt){X(lt instanceof Error?lt.message:"Failed to move memory.","warning")}finally{me(!1)}}}async function wn(){const Re=String(u||"this memory").trim(),et=Re.length>80?`${Re.slice(0,79).trimEnd()}…`:Re;if(await vn({autoFocusAction:"cancel",title:"Forget this memory?",description:`Forgetting "${et}". This removes the memory from active results. The underlying record remains soft-deleted for audit and sync safety.`,confirmLabel:"Forget memory",cancelLabel:"Keep memory",tone:"danger"})){Ne(!0);try{await kR(A),n(A),r(),await i(),X("Memory forgotten and removed from the active feed.")}catch(tt){X(tt instanceof Error?tt.message:"Failed to forget memory.","warning")}finally{Ne(!1)}}}const Sn=c.replace(/_/g," "),kr=v.length?g("div",{className:"feed-files"},v.map((Re,et)=>g("span",{className:"feed-file",key:`${String(Re)}-${et}`},String(Re)))):null;return g("article",{className:`feed-item ${c}${F?" new-item":""}`.trim(),"data-key":l},g("div",{className:"feed-kind-banner"},g(qp,{variant:"kind",tone:c},Sn)),g("div",{className:"feed-card-body"},g("div",{className:"feed-card-header"},g("div",{className:"feed-header"},g("div",{className:"feed-title title",dangerouslySetInnerHTML:{__html:YE(u,S.feedQuery)}}),g("div",{className:"feed-card-subtitle small"},le)),g("div",{className:"feed-actions"},x?g(qM,{active:C,modes:U,onSelect:Re=>O(Re)}):null,g(qc,{label:S$(p),side:"left"},g("div",{className:"small feed-age"},f)),e.owned_by_self&&A>0?g(BM,{assignProjectDisabled:ce,disabled:Pe,onAssignProject:()=>{Je()},onForget:()=>{wn()},title:String(u||"memory")}):null)),g("div",{className:"feed-provenance"},g(ff,{label:h,variant:h==="You"?"mine":"author"}),g(ff,{label:w||"private",variant:w||"private"}),L?g(qc,{label:`Memory database id ${A}`,side:"top"},g(ff,{label:L,variant:"memory-id"})):null),re?g("div",{className:"feed-meta"},re):null,ae,g("div",{className:"feed-footer"},g("div",{className:"feed-footer-left"},m.length?g("div",{className:"feed-tags"},m.map((Re,et)=>g(UM,{key:`${String(Re)}-${et}`,tag:Re}))):null,e.owned_by_self&&A>0?g("div",{className:"feed-visibility-controls"},g("select",{"aria-label":`Visibility for ${String(e.title||"memory")}`,className:"feed-visibility-select",disabled:fe,onChange:Re=>{Fe(String(Re.currentTarget.value)==="shared"?"shared":"private")},value:se},g("option",{value:"private"},"Only me"),g("option",{value:"shared"},"Share with peers")),g("div",{className:"feed-visibility-note"},ye)):null),g("div",{className:"feed-footer-right"},Q?g("button",{className:"feed-expand",onClick:()=>{const Re=!G;S.itemExpandState.set(H,Re),ee(Re)},type:"button"},G?"Collapse":"Expand"):null)),kr))}function HM({index:e}){const t=[["w-85","w-65"],["w-85","w-40"],["w-65","w-85"]],[n,r]=t[e%t.length];return g("div",{className:"feed-skeleton-item","aria-hidden":"true"},g("div",{className:"feed-skeleton-banner"}),g("div",{className:"feed-skeleton-body"},g("div",{className:`feed-skeleton-line ${n}`}),g("div",{className:`feed-skeleton-line ${r}`}),g("div",{className:"feed-skeleton-footer"},g("div",{className:"feed-skeleton-chip w-36"}),g("div",{className:"feed-skeleton-chip w-56"}),g("div",{className:"feed-skeleton-chip"}))))}function VM({items:e,loadingText:t,ops:n}){if(t)return g("div",{className:"feed-skeleton",role:"status","aria-label":t},[0,1,2,3].map(r=>g(HM,{index:r,key:`skeleton-${r}`})));if(!e.length){const r=!!S.feedQuery.trim()||S.feedTypeFilter!=="all"||S.feedScopeFilter!=="all";return g("div",{className:"small feed-empty-state"},g("strong",null,r?"No memories match the current filters.":"No memories yet."),g("div",null,r?"Try clearing filters, changing the scope, or using a broader search.":"Memories and session summaries will appear here once codemem has something worth keeping."))}return g(z,null,e.map(r=>g(GM,{item:r,key:Nt(r),onReplace:n.replaceFeedItem,onRemove:n.removeFeedItem,onViewRefresh:()=>n.updateFeedView(!0),onReload:n.loadFeedData})))}function mw({id:e,active:t,options:n,onSelect:r}){return g("div",{className:"feed-toggle",id:e},n.map(({value:i,label:a})=>{const s=i===t;return g("button",{"aria-pressed":s?"true":"false",className:`toggle-button${s?" active":""}`,"data-filter":i,key:i,onClick:()=>r(i),type:"button"},a)}))}function KM({text:e}){return g("div",{"aria-live":"polite",className:"section-meta",id:"feedMeta",role:"status"},e)}function zM({query:e,onQuery:t}){return g("input",{"aria-label":"Search memories",className:"feed-search",id:"feedSearch",onInput:n=>{t(String(n.currentTarget.value||""))},placeholder:"Search title, body, tags…",type:"search",value:e})}function WM({errorText:e,items:t,loadingText:n,ops:r}){const[i,a]=D(!1);return g(z,null,g("div",{className:"feed-controls"},g(KM,{text:n||yj(t.length,r.hasMorePages())}),g("div",{className:"feed-controls-right"},g(zM,{query:S.feedQuery,onQuery:r.updateFeedQuery}),g(mw,{active:S.feedScopeFilter,id:"feedScopeToggle",onSelect:s=>{s!==S.feedScopeFilter&&(Iy(s),r.loadFeedData().catch(()=>{}))},options:[{value:"all",label:"All"},{value:"mine",label:"My memories"},{value:"theirs",label:"Other people"}]}),g(mw,{active:S.feedTypeFilter,id:"feedTypeToggle",onSelect:s=>{s!==S.feedTypeFilter&&(oA(s),r.updateFeedView())},options:[{value:"all",label:"All"},{value:"observations",label:"Observations"},{value:"summaries",label:"Summaries"}]}),g("button",{"aria-controls":"contextInspectorPanel","aria-expanded":i,className:"settings-button feed-inspector-button",onClick:()=>a(s=>!s),type:"button"},i?"Hide Context Inspector":"Context Inspector"))),g(bj,{open:i}),g("div",{className:"feed-list",id:"feedList"},g(z,null,e?g("div",{className:"small feed-empty-state",role:"alert"},g("strong",null,e),g("div",null,"Check the viewer connection, then retry the Feed."),g("button",{className:"settings-button",onClick:()=>{r.loadFeedData().catch(()=>{})},type:"button"},"Retry")):null,!e||t.length>0?g(VM,{items:t,loadingText:n,ops:r}):null)))}function JM(e){return S.feedTypeFilter==="observations"?e.filter(t=>!Jc(t,jc(t?.metadata_json))):S.feedTypeFilter==="summaries"?e.filter(t=>Jc(t,jc(t?.metadata_json))):e}function YM(e){const t=e.map(n=>`${r_(n)}:${n.kind||""}:${n.created_at_utc||n.created_at||""}:${String(n.owned_by_self??"")}`);return`${S.feedTypeFilter}|${S.feedScopeFilter}|${S.currentProject}|${S.viewerActorId??""}|${co(S.feedQuery)}|${t.join("|")}`}var hw="",Co=0,Ro=0,ia=!0,aa=!0,Qc=null,XM=0,hr=null,gw=!1,Io=0,mf="all",vw="",ko=null,oa="",dV=250;function yw(e){hw=e,mf=S.feedScopeFilter,vw=S.feedQuery.trim(),oa="",Io+=1,Co=0,Ro=0,ia=!0,aa=!0,S.lastFeedItems=[],S.pendingFeedItems=null,S.lastFeedFilteredCount=0,S.lastFeedSignature="",S.newItemKeys.clear(),S.itemViewState.clear(),S.itemExpandState.clear()}function hf(){return ia||aa}function QM(e){const t=Nt(e);S.lastFeedItems=S.lastFeedItems.map(n=>Nt(n)===t?e:n)}function ZM(e){const t=new Set,n=r=>{const i=Number(r.id||r.memory_id||0)!==e;return i||t.add(Nt(r)),i};S.lastFeedItems=S.lastFeedItems.filter(n),Array.isArray(S.pendingFeedItems)&&(S.pendingFeedItems=S.pendingFeedItems.filter(n));for(const r of t){S.newItemKeys.delete(r),S.itemViewState.delete(r);for(const i of Array.from(S.itemExpandState.keys()))i.startsWith(`${r}:`)&&S.itemExpandState.delete(i)}}async function e1(){if(!hf())return;const e=Io;if(Qc===e)return;const t=S.currentProject||"",n=S.feedQuery.trim(),r=Co,i=Ro;Qc=e;try{const[a,s]=await Promise.all([ia?Km(t,{limit:20,offset:r,scope:S.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:r}}),aa?zm(t,{limit:50,offset:i,scope:S.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:i}})]);if(e!==Io||t!==(S.currentProject||"")||n!==S.feedQuery.trim())return;const c=s.items||[],l=a.items||[],d=n?l:l.filter(f=>!n_(f));S.lastFeedFilteredCount+=l.length-d.length,aa=Oc(s,c.length,50),ia=Oc(a,l.length,20),Ro=Mc(s,i+c.length),Co=Mc(a,r+l.length);const u=[...c,...d],p=i_(S.lastFeedItems,u);S.lastFeedItems=p,oi()}finally{Qc===e&&(Qc=null)}}function bw(){S.activeTab==="feed"&&(ko||hr||hf()&&F$()&&e1())}var t1={replaceFeedItem:QM,removeFeedItem:ZM,updateFeedView:e=>oi(e),loadFeedData:()=>yf(),updateFeedQuery:e=>r1(e),hasMorePages:hf};function gf(e,t){const n=document.getElementById("tab-feed");if(!n)return!1;dj(n,g(WM,{errorText:t?.errorText,items:e,loadingText:t?.loadingText,ops:t1}));const r=globalThis.lucide;return r&&!t?.loadingText&&r.createIcons(),!0}function vf(e="Loading selected project..."){gf([],{loadingText:e})}function n1(){lj(),gf(S.lastFeedItems,S.lastFeedItems.length||S.lastFeedSignature?void 0:{loadingText:"Loading memories…"}),gw||(window.addEventListener("scroll",()=>{bw()},{passive:!0}),gw=!0)}function r1(e){if(e===S.feedQuery)return;const t=S.feedQuery.trim();S.feedQuery=e,e.trim()!==t&&(yw(S.currentProject||""),vf("Searching memories…"),ko&&clearTimeout(ko),ko=setTimeout(()=>{ko=null,yf().catch(()=>{})},250))}function oi(e=!1){if(!document.getElementById("tab-feed"))return;const t=window.scrollY,n=JM(S.lastFeedItems),r=YM(n),i=e||r!==S.lastFeedSignature;S.lastFeedSignature=r,i&&gf(n,{errorText:oa||void 0}),window.scrollTo({top:t}),bw()}function _w(e,t,n,r){return ww(e,t)&&e===Io&&n===(S.currentProject||"")&&r===S.feedQuery.trim()}function ww(e,t){return hr?.generation===e&&hr.requestId===t}async function yf(e={}){const t=S.currentProject||"",n=S.feedScopeFilter!==mf,r=S.feedQuery.trim(),i=r!==vw;(t!==hw||n||i)&&(yw(t),vf(i?"Searching memories…":void 0));const a=Io,s=++XM;hr={generation:a,requestId:s};const c=!!oa;c&&(oa="",S.lastFeedItems.length>0?oi(!0):vf(r?"Searching memories…":void 0));try{const[u,p]=await Promise.all([Km(t,{limit:20,offset:0,scope:S.feedScopeFilter,q:r||void 0,signal:e.signal}),zm(t,{limit:50,offset:0,scope:S.feedScopeFilter,q:r||void 0,signal:e.signal})]);if(e.signal?.aborted||!_w(a,s,t,r))return;const f=p.items||[],m=u.items||[],v=r?m:m.filter(_=>!n_(_)),b=m.length-v.length,h=[...f,...v].sort((_,R)=>new Date(R.created_at||0).getTime()-new Date(_.created_at||0).getTime()),y=M$(S.lastFeedItems,h),w=S.lastFeedItems;if(B$(y,w)&&w.length>0){const _=new Set(w.map(Nt));y.forEach(R=>{_.has(Nt(R))||S.newItemKeys.add(Nt(R))})}S.pendingFeedItems=null,S.lastFeedItems=y,oa="",S.lastFeedFilteredCount=Math.max(S.lastFeedFilteredCount,b),aa=Oc(p,f.length,50),ia=Oc(u,m.length,20),Ro=Math.max(Ro,Mc(p,f.length)),Co=Math.max(Co,Mc(u,m.length)),mf=S.feedScopeFilter,hr?.generation===a&&hr.requestId===s&&(hr=null),oi(c)}catch(l){if(e.signal?.aborted)return;throw _w(a,s,t,r)&&(ia=!1,aa=!1,oa="Feed unavailable. Refresh and try again.",oi(!0)),l}finally{ww(a,s)&&(hr=null)}}function i1(e){return e.channel==="latest"?"stable":e.channel}function uV(e){return e}function a1(e){const t=new Date(e.periodStart),n=new Date(e.periodEnd),r=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric"}),i=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",year:"numeric"});return t.getFullYear()===n.getFullYear()?[r.format(t),i.format(n)]:[i.format(t),i.format(n)]}function o1(e,t){const n=100*e/t,r=Math.round(n);return n>0&&r===0?"<1%":n<100&&r===100?">99%":`${r}%`}function s1(e){if(e.freshEvaluations===0)return[{label:"Recalls checked",value:0,tooltip:"No automatic recalls were checked for repeated memories in this period.",icon:"activity"},{label:"Not checked",value:e.unmeasuredAttempts,tooltip:`Codemem could not check ${e.unmeasuredAttempts.toLocaleString()} automatic recalls for repeated memories, so savings are unknown.`,icon:"circle-help"}];const t=o1(e.evaluationsWithDuplicates,e.freshEvaluations),n=e.missingRetainedMetadata>0||e.invalidRetainedMetadata>0||e.packMetadataGaps>0;return[{label:"Recalls with repeats",value:t,tooltip:`Codemem removed repeated memories from ${e.evaluationsWithDuplicates.toLocaleString()} of ${e.freshEvaluations.toLocaleString()} automatic recalls.`,icon:"filter"},{label:"Memories skipped",value:e.duplicatesOmitted,tooltip:`Codemem left out ${e.duplicatesOmitted.toLocaleString()} memories that were already in your conversation, out of ${e.candidateItems.toLocaleString()} considered.`,icon:"minus-circle"},{label:"Repeated tokens removed",value:`~${so(e.estimatedTokensAvoided)}`,tooltip:`About ${e.estimatedTokensAvoided.toLocaleString()} tokens were left out because they repeated information already in your conversation.`,icon:"trending-down"},{label:"Recalls checked",value:e.freshEvaluations,tooltip:`Codemem checked ${e.freshEvaluations.toLocaleString()} automatic recalls for repeated memories. ${e.unmeasuredAttempts.toLocaleString()} more could not be checked.${n?" Some results may be incomplete.":""}`,icon:"activity"}]}function c1(e){if(!e||e.availability==="unavailable")return g("p",{class:"section-meta"},"Automatic recall details aren’t available. Update Codemem and refresh this page.");const[t,n]=a1(e);return g(z,null,g("div",{class:"grid-2 automatic-recall-grid"},s1(e).map(r=>g(Sw,{...r,key:`${r.label}-${r.icon}`}))),g("p",{class:"automatic-recall-meta"},g("time",{dateTime:e.periodStart},t),"–",g("time",{dateTime:e.periodEnd},n),` · Based on up to ${e.windowLimit.toLocaleString()} recent automatic recalls across all projects.${e.freshEvaluations===0?" No recalls were checked, so savings are unknown.":""}`))}function l1(e,t){e&&(Ue(g(Bc,null,g("details",{class:"automatic-recall"},g("summary",null,"Automatic recall"),g("section",{"aria-label":"Automatic recall measurements"},c1(Wm(t))))),e),Po())}function d1(e){if(e.install_kind==="repo-dev")return{title:"Running from repository source",detail:`Package metadata version: ${e.current_version}. Registry releases do not describe the checked-out source revision.`,tone:"current"};if(!e.latest_version)return{title:"Update check unavailable",detail:e.error?`Could not check for updates: ${e.error}`:"Could not check for updates.",tone:"unavailable"};if(e.stale)return{title:e.update_available?`Cached update status: Codemem ${e.latest_version} is available`:`Cached update status for Codemem ${e.current_version}`,detail:e.error?`This result is stale because a fresh check failed: ${e.error}`:"This result is cached and may be stale.",tone:"stale"};if(e.update_available)return{title:`Codemem ${e.latest_version} is available`,detail:`Installed version: ${e.current_version}.`,tone:"available"};const t=i1(e);return t?{title:`Codemem ${e.current_version} is up to date`,detail:`You are running the latest ${t} release.`,tone:"current"}:{title:`Unable to compare Codemem ${e.current_version} with ${e.latest_version}`,detail:"The installed version is not on a supported release channel.",tone:"unavailable"}}function u1({status:e}){const t=d1(e),n=e.install_kind==="repo-dev"||e.update_available||e.stale||!e.latest_version||!e.channel;return g("section",{class:`health-update-banner health-update-banner--${t.tone}`,role:"status","aria-atomic":"true","aria-label":"Codemem update status"},g("i",{"aria-hidden":"true","data-lucide":"circle-arrow-up",class:"health-update-icon"}),g("div",{class:"health-update-copy"},g("h2",null,t.title),g("p",null,t.detail),n&&e.recommended_action?g("p",{class:"health-update-guidance"},g("span",{class:"health-update-guidance-label"},"Recommended action"),g("code",null,e.recommended_action)):null))}function p1(e,t){e&&(e.hidden=!t,Ue(t?g(u1,{status:t}):null,e))}function f1({label:e,value:t,detail:n,icon:r,className:i,title:a}){const s=g("div",{class:`stat${i?` ${i}`:""}`,style:a?"cursor: help;":void 0},r?g("i",{"data-lucide":r,class:"stat-icon"}):null,g("div",{class:"stat-content"},g("div",{class:"value"},t),g("div",{class:"label"},e),n?g("div",{class:"small"},n):null));return a?g(qc,{label:a},s):s}function m1({item:e}){let t=null,n=null;const r=e.actionLabel||"Run";async function i(){if(!(!e.action||!t)){t.disabled=!0,t.textContent="Running…";try{await e.action(t)}catch{}t.disabled=!1,t.textContent=r}}function a(){!e.command||!n||Va(e.command,n)}return g("div",{class:"health-action"},g("div",{class:"health-action-text"},e.label,e.command?g("span",{class:"health-action-command"},e.command):null),g("div",{class:"health-action-buttons"},e.action?g("button",{class:"settings-button",onClick:i,ref:s=>{t=s}},r):null,e.command?g("button",{class:"settings-button health-action-copy",onClick:a,ref:s=>{n=s}},"Copy"):null))}function h1(e){return typeof e=="number"?e.toLocaleString():e==null?"n/a":String(e)}function Sw({label:e,value:t,icon:n,tooltip:r}){const i=g("div",{class:"stat",style:r?"cursor: help;":void 0,tabIndex:r?0:void 0},g("i",{"data-lucide":n,class:"stat-icon"}),g("div",{class:"stat-content"},g("div",{class:"value"},h1(t)),g("div",{class:"label"},e)));return r?g(qc,{label:r},i):i}function Cw(e,t){e&&Ue(g(Bc,null,t.map(n=>g(Sw,{...n,key:`${n.label}-${n.icon}`}))),e)}function To(e,t){e&&Ue(g(z,null,t),e)}function Po(){const e=globalThis.lucide;e&&typeof e.createIcons=="function"&&e.createIcons()}function Rw(e,t){e&&Ue(g(Bc,null,t.map(n=>g(f1,{...n,key:n.key??n.label}))),e)}function Iw(e,t){if(e){if(!t.length){e.hidden=!0,Ue(null,e);return}e.hidden=!1,Ue(g(z,null,t.slice(0,3).map((n,r)=>g(m1,{item:n,key:`${n.label}-${r}`}))),e)}}function bf(e,t){let n=e.events_global;return t&&(n=e.events_filtered??e.events),n.find(r=>r.event==="pack")??null}var kw="scope_id_backfill";function Tw(){const e=document.getElementById("healthDot");e&&(e.className="health-dot status-unknown",e.title="Open Health to check status");const t=document.getElementById("metaLine");t&&To(t,"")}function g1(e,t){!t||e.length>=3||e.push({label:"Background maintenance failed. Review recent safe failure evidence.",command:"codemem maintenance status",action:n=>Fr({severity:"error",subsystem:"maintenance",trigger:n}),actionLabel:"View diagnostics"})}function v1(e,t,n){if(t){e.textContent=n.length?`Some Health data is stale. Last known risks: ${n.join(", ")}.`:"Some Health data is stale. Showing the last successful snapshot.";return}if(n.length){e.textContent=`Why this status: ${n.join(", ")}.`;return}e.textContent="Healthy right now. Diagnostics stay available if you want details."}function y1(e,t){return e>=60?{label:"Attention",className:"status-attention"}:e>=25?{label:"Degraded",className:"status-degraded"}:t?{label:"Stale",className:"status-unknown"}:{label:"Healthy",className:"status-healthy"}}function Pw(){const e=document.getElementById("healthGrid"),t=document.getElementById("healthMeta"),n=document.getElementById("healthActions"),r=document.getElementById("healthDot");if(!e||!t)return;p1(document.getElementById("healthUpdateBanner"),S.lastUpdateStatus);const i=On(S.healthStats),a=On(S.healthUsage,S.currentProject),s=On(S.healthRawEvents);if(!i||!a||!s){b1({healthGrid:e,healthMeta:t,healthActions:n,healthDot:r});return}const c=S.lastSyncStatus||{},l=i.maintenance_jobs,d=l.find(re=>re.kind===kw),u=l.some(re=>re.status==="failed"),p=i.database,f=a.recent_packs,m=bf(a,a.events_filtered!=null),v=f.length?f[0]?.created_at:null,b=f.length?f[0]?.metadata_json||{}:{},h=Number(b?.exact_duplicates_collapsed||0),y=s.pending,w=i.reliability?.counts.errored_batches??0,_=i.reliability?.rates.flush_success_rate??1,R=i.reliability?.rates.dropped_event_rate??0,I=m?$p(m.total_tokens_saved,m.total_tokens_read):"n/a",T=I$(I),A=p.tags_coverage,L=String(c.daemon_state||"unknown"),F=L==="offline-peers"?"Offline peers":L==="needs_attention"?"Needs attention":L==="rebootstrapping"?"Rebootstrapping":e_(L),N=Array.isArray(S.lastSyncPeers)?S.lastSyncPeers.length:0,j=L==="disabled"||c.enabled===!1,x=L==="offline-peers",U=!j&&N===0;let q=j?"Disabled":U?"No peers":F;const $=c.last_sync_at||c.last_sync_at_utc||null,E=Zi($),C=Zi(v),O=E!==null&&E>7200,H=E!==null&&E<=300,G=y>=200;let ee=0;const Z=[];y>=1e3?(ee+=40,Z.push("high raw-event backlog")):y>=200&&(ee+=24,Z.push("growing raw-event backlog")),w>0&&y>=200&&(ee+=w>=5?10:6,Z.push("batch errors during backlog pressure")),_<.95&&(ee+=20,Z.push("lower flush success")),R>.02?(ee+=24,Z.push("high dropped-event rate")):R>.005&&(ee+=10,Z.push("non-trivial dropped-event rate")),!j&&!U&&(L==="error"?(ee+=36,Z.push("sync daemon reports errors")):L==="needs_attention"?(ee+=40,Z.push("sync needs manual attention")):L==="stopped"?(ee+=22,Z.push("sync daemon stopped")):L==="degraded"&&!H&&(ee+=20,Z.push("sync daemon degraded")),x?(ee+=4,Z.push("all peers currently offline"),O&&(ee+=4,Z.push("offline peers and sync not recent"))):O?(ee+=26,Z.push("sync looks stale")):E!==null&&E>1800&&(ee+=12,Z.push("sync not recent"))),T!==null&&T<10&&(ee+=8,Z.push("low retrieval reduction")),C!==null&&C>86400&&(ee+=12,Z.push("memory pack activity is old"));const ie=[S.healthStats,S.healthUsage,S.healthRawEvents].some(re=>Qs(re)),{label:fe,className:Ce}=y1(ee,ie),Pe=Ce==="status-healthy";r&&(r.className=`health-dot ${Ce}`,r.title=fe);const Ne=m?`${m.total_tokens_saved.toLocaleString()} estimated saved tokens · ${h.toLocaleString()} deduped in latest pack`:"No pack usage is available",ce=y>0?"Queue is actively draining":"Queue is clear",me=j?"Sync disabled":U?"No peers configured":x?`${N} peers offline · last sync ${ur(E)} ago`:`${N} peers · last sync ${ur(E)} ago`;Pe&&!j&&!U&&(x?q="Peers offline":L==="degraded"&&H&&(q="Syncing"));const J=`last pack ${ur(C)} ago`,se=l.map(re=>{const Q=Number(re.progress?.current||0),we=typeof re.progress?.total=="number"?re.progress.total:null,ae=String(re.progress?.unit||"items"),Fe=we&&we>0?` (${Math.round(100*Q/we)}%)`:"",Je=we&&we>0?`${Q.toLocaleString()}/${we.toLocaleString()} ${ae}${Fe}`:`${Q.toLocaleString()} ${ae}`,wn=re.status==="failed",Sn=re.status==="completed",kr=re.kind===kw,Re=wn?"Failed":Sn?"Complete":Je,et=wn?String(re.error||"unknown error").trim():Sn?kr?`${Je} · one-time Sharing-domain upgrade finished`:Je:kr?"One-time upgrade backfill; totals include memories and replication ops":void 0;return{key:String(re.kind||re.title||"background-maintenance"),label:String(re.title||re.kind||"Background maintenance"),value:Re,detail:et,icon:wn?"alert-triangle":Sn?"check-circle":"loader",className:wn?"status-attention":void 0,title:wn?`Error: ${re.error||"unknown"}`:Sn?`${String(re.title||"Maintenance")} finished`:kr?`${String(re.title||"Maintenance")} in progress; inspect with codemem maintenance status`:`${String(re.title||"Maintenance")} in progress`}}),ye=[{key:"overall-health",label:"Overall health",value:fe,detail:`Weighted score ${ee}`,icon:"heart-pulse",className:`health-primary ${Ce}`,title:Z.length?`Main signals: ${Z.join(", ")}`:"No major risk signals detected"},...se,{key:"pipeline-health",label:"Pipeline health",value:`${y.toLocaleString()} pending`,detail:ce,icon:"workflow",title:"Raw-event queue pressure and flush reliability"},{key:"retrieval-impact",label:"Retrieval impact",value:I,detail:Ne,icon:"sparkles",title:"Reduction from memory reuse across recent usage"},{key:"sync-health",label:"Sync health",value:q,detail:me,icon:"refresh-cw",title:"Daemon state and sync recency"},{key:"data-freshness",label:"Data freshness",value:ur(C),detail:J,icon:"clock-3",title:"Recency of last memory pack activity"}];Rw(e,ye);const le=async()=>{await nd()},Ee=[];G?(Ee.push({label:"Pipeline needs attention. Check queue health first.",command:"codemem db raw-events-status",action:re=>Fr({subsystem:"capture",trigger:re}),actionLabel:"View diagnostics"}),Ee.push({label:"Then retry failed batches for impacted sessions.",command:"codemem db raw-events-retry <opencode_session_id>"})):L==="stopped"?Ee.push({label:"Sync daemon is stopped. Start the background service.",command:"codemem serve start"}):!j&&!U&&!Pe&&(L==="error"||L==="degraded")?(Ee.push({label:"Sync is unhealthy. Restart and run one immediate pass.",command:"codemem serve restart",action:le,actionLabel:"Sync now"}),Ee.push({label:"Then run doctor to see root cause details.",command:"codemem sync doctor"})):!j&&!U&&O&&Ee.push({label:"Sync is stale. Run one immediate sync pass.",command:"codemem sync once",action:le,actionLabel:"Sync now"}),g1(Ee,u),A>0&&A<.7&&Ee.length<2&&Ee.push({label:"Tag coverage is low. Preview backfill impact.",command:"codemem db backfill-tags --dry-run"}),d&&d.status!=="completed"&&Ee.length<3&&Ee.push({label:"Sharing-domain upgrade backfill is expected one-time work. Inspect progress if startup feels busy.",command:"codemem maintenance status"}),Iw(n,Ee),v1(t,ie,Z),Po()}function b1({healthGrid:e,healthMeta:t,healthActions:n,healthDot:r}){const i=[S.healthStats,S.healthUsage,S.healthRawEvents],a=i.some(d=>d.status==="failed"),s=i.some(d=>d.status==="loading");let c="Not loaded",l="Open or refresh Health to load status.";a?(c="Unavailable",l="Some health data failed to load. Refresh Health to try again."):s&&(c="Loading",l="Loading health data…"),Rw(e,[{key:"overall-health",label:"Overall health",value:c,detail:"Health requires stats, usage, and queue data",icon:a?"triangle-alert":"loader",className:"health-primary status-unknown"}]),Iw(n,[]),To(t,l),r&&(r.className="health-dot status-unknown",r.title=c),Po()}function _1(){const e=document.getElementById("sessionGrid"),t=document.getElementById("sessionMeta");if(!e||!t)return;const n=On(S.healthUsage,S.currentProject),r=On(S.healthSession,S.currentProject),{latestPack:i,packCount:a,packLine:s}=w1(n),c=i?.created_at||"",l=c?`Last pack: ${Zr(c)}`:"",d=S.currentProject?"Project":"All projects",u=S1(r,S.healthSession.status==="failed"),p=R1(i,a),f=C1(n,r)?"Showing stale data":"";To(t,[d,s,l,u,f].filter(Boolean).join(" · ")),Cw(e,p),Po()}function w1(e){if(!e)return{latestPack:null,packCount:null,packLine:"Pack totals unavailable"};const t=e.events.find(n=>n.event==="pack")?.count??0;return{latestPack:e.recent_packs[0]??null,packCount:t,packLine:t?`${t} packs`:"No packs yet"}}function S1(e,t){return e?`${e.total.toLocaleString()} stored items`:t?"Stored-item totals unavailable":""}function C1(e,t){return!!e&&Qs(S.healthUsage,S.currentProject)||!!t&&Qs(S.healthSession,S.currentProject)}function R1(e,t){const n=e?.metadata_json||{},r=e?.tokens_read??0,i=e?.tokens_saved??0,a=n.exact_duplicates_collapsed??0,s=$p(i,r);let c="n/a";return e&&(c=n.exact_dedupe_enabled?"On":"Off"),[{label:"Last pack savings",value:e?`${so(i)} (${s})`:"n/a",tooltip:e?`Estimate: ${i.toLocaleString()} saved`:void 0,icon:"trending-up"},{label:"Last pack size",value:e?so(r):"n/a",tooltip:e?`Estimate: ${r.toLocaleString()} injected`:void 0,icon:"package"},{label:"Last pack deduped",value:e?a.toLocaleString():"n/a",icon:"copy-check"},{label:"Exact dedupe",value:c,icon:"shield-check"},{label:"Packs",value:t??"n/a",icon:"archive"}]}function I1(e,t,n){if(t>0){e.push({label:"Raw events pending",value:t,tooltip:"Pending raw events waiting to be flushed",icon:"activity"});return}n>0&&e.push({label:"Raw sessions",value:n,tooltip:"Sessions with pending raw events",icon:"inbox"})}function k1(){const e=document.getElementById("statsGrid"),t=document.getElementById("metaLine");if(!e)return;const n=On(S.healthStats),r=On(S.healthUsage,S.currentProject),i=On(S.healthRawEvents),a=n?.database,s=S.currentProject,c=r?.totals_filtered??null,l=!!(s&&c),d=r?bf(r,!1):null,u=r?bf(r,l):null,p=i?.sessions??0,f=i?.pending??0,m=l&&d?`
109
+ Global: ${d.total_tokens_read.toLocaleString()} estimated injected`:"",v=l&&d?`
110
+ Global: ${d.total_tokens_saved.toLocaleString()} estimated saved`:"",b=[{label:l?"Savings (project)":"Savings",value:u?so(u.total_tokens_saved):"n/a",tooltip:u?`Estimated tokens saved by reusing compressed memories: ${u.total_tokens_saved.toLocaleString()}${v}`:"Usage data is unavailable",icon:"trending-up"},{label:l?"Injected (project)":"Injected",value:u?so(u.total_tokens_read):"n/a",tooltip:u?`Estimated tokens injected into context (pack size): ${u.total_tokens_read.toLocaleString()}${m}`:"Usage data is unavailable",icon:"book-open"},{label:l?"Reduction (project)":"Reduction",value:u?$p(u.total_tokens_saved,u.total_tokens_read):"n/a",tooltip:u?`Estimated percent reduction from reuse. Factor: ${R$(u.total_tokens_saved,u.total_tokens_read)}.${m}${v}`:"Usage data is unavailable",icon:"percent"},{label:l?"Work investment (project)":"Work investment",value:"n/a",tooltip:"Work-investment data is unavailable",icon:"pencil"},{label:"Active memories",value:a?.active_memory_items??"n/a",icon:"check-circle"},{label:"Embedding coverage",value:a?Zb(a.vector_coverage):"n/a",tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:a?Zb(a.tags_coverage):"n/a",tooltip:"Share of active memories with tags",icon:"tag"}];i&&I1(b,f,p),Cw(e,b),t&&T1(t,a,s),Po()}function T1(e,t,n){if(!t){To(e,P1(S.healthStats,"Database metrics"));return}const r=n?` · project: ${n}`:"",i=Qs(S.healthStats)?" · showing stale data":"",a=N$(t.path);To(e,`DB: ${a} · ${E$(t.size_bytes)}${r}${i}`)}function P1(e,t){return e.status==="loading"?`Loading ${t.toLowerCase()}…`:e.status==="failed"?`${t} failed to load`:`${t} not loaded`}async function N1(e={}){const t=S.viewerActorId,n=await ER(e);e.signal?.aborted||(S.viewerActorId=n.identity.actor_id,t!==S.viewerActorId&&oi(!0))}async function E1(e={}){const t=S.currentProject;S.healthStats=Xs(S.healthStats),S.healthUsage=Xs(S.healthUsage,t),S.healthSession=Xs(S.healthSession,t),S.healthRawEvents=Xs(S.healthRawEvents),Nw();const n=S.activeTab==="health"&&!S.lastUpdateStatus?GI(e).catch(HI):Promise.resolve(S.lastUpdateStatus),[r,i,a,s,c]=await Promise.all([Zc(qR(e)),Zc(UR(t,e)),Zc(GR(t,e)),Zc(HR(t,e)),n]);e.signal?.aborted||(S.healthStats=el(S.healthStats,r),S.healthUsage=el(S.healthUsage,i,t),S.healthSession=el(S.healthSession,a,t),S.healthRawEvents=el(S.healthRawEvents,s),S.lastUpdateStatus=c,Nw())}function Nw(){k1(),l1(document.getElementById("automaticRecallStats"),On(S.healthStats)?.automatic_recall),_1(),Pw()}async function Zc(e){try{return{ok:!0,data:await e}}catch(t){return{ok:!1,error:t instanceof Error?t.message:"Health request failed"}}}function el(e,t,n=""){return"data"in t?QE(t.data,Date.now(),n):ZE(e,t.error)}function _f(e,t){return`legacy-team-setup-item-error-${e}-${t}`}function Ew(e){return[...e].sort((t,n)=>+(n.decision==="unresolved")-+(t.decision==="unresolved"))}function Aw(e){return[...e].sort((t,n)=>+(n.resolution==="unresolved")-+(t.resolution==="unresolved"))}var A1={unresolved:"Needs a decision",included:"Included in this Team",excluded:"Excluded from this Team",removed:"Removed from this Team"};function xw(e,t){return t?e.identityChoices.find(n=>n.identityRef===t)?.displayName??"Unavailable person":null}function x1(e){return e.targetIdentityRef??e.existingIdentityRef??""}function D1({blocked:e,blockedDescriptionId:t,blockedDeviceRefs:n,busy:r,detail:i,device:a,index:s,onAssign:c,onClear:l,onDecision:d}){const u=Dr(),p=`${u}-identity`,f=`${u}-evidence`,m=`${u}-assignment-help`,v=x1(a),b=a.targetIdentityRef??"",[h,y]=D(v);V(()=>y(v),[v]);const w=i.identityChoices.some(O=>O.identityRef===h),_=xw(i,a.existingIdentityRef),R=xw(i,a.suggestedIdentityRef),I=n?.has(a.deviceRef)??!1,T=e||I||r,A=T||!a.actions.assignIdentity.enabled,L=a.actions.assignIdentity.blockedReason==="assignment_evidence_inactive",F=!!h&&!w,N=!a.actions.include.enabled||L||F||!b||h!==b,j=T||N,x=A||!h||L||F||h===b,U=!a.enabled||N,q=e?t:I?_f("device",a.deviceRef):void 0,$=[f,U?m:void 0,q].filter(Boolean).join(" "),E=[f,q].filter(Boolean).join(" "),C=a.decision==="unresolved";return o("fieldset",{"aria-busy":r?"true":"false",className:`legacy-team-device-row${C?" legacy-team-setup-row-needs-attention":""}`,id:`legacy-team-device-row-${s}`,tabIndex:C?-1:void 0,children:[o("legend",{children:a.displayName}),C?o("span",{className:"legacy-team-setup-status",children:"Needs attention"}):null,o("div",{className:"small legacy-team-device-evidence",id:f,children:[o("span",{children:a.enabled?"Current Team device":"Device no longer active on this Team"}),_?o("span",{children:["Current assignment: ",_,a.verifiedEvidenceKind==="active_assignment"?" · verified active assignment":""]}):null,!_&&R?o("span",{children:["Suggested person: ",R]}):null,o("span",{children:["Decision: ",A1[a.decision]]})]}),o("label",{htmlFor:p,children:"Person using this device"}),o("select",{"aria-describedby":$,className:"feed-search legacy-team-device-select",disabled:A,id:p,onChange:O=>y(O.currentTarget.value),value:h,children:[o("option",{value:"",children:"Choose a person"}),h&&!w?o("option",{value:h,children:"Current server assignment"}):null,i.identityChoices.map(O=>o("option",{value:O.identityRef,children:O.displayName},O.identityRef))]}),a.enabled?F?o("p",{className:"small",id:m,children:"This person is no longer available. Choose an available person and save the assignment before including this device."}):L?o("p",{className:"small",id:m,children:"This assignment is inactive. Reconcile this device in Devices or exclude it from this Team."}):!h||!b||h!==b?o("p",{className:"small",id:m,children:h?"Save the selected person assignment before including this device.":"Choose and save a person assignment before including this device."}):null:o("p",{className:"small",id:m,children:"Inactive devices can only be removed from this Team."}),o("div",{className:"legacy-team-device-actions",children:[o("button",{"aria-describedby":$,"aria-disabled":x?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{x||c(a,h)},type:"button",children:"Save assignment"}),a.enabled?o(z,{children:[o("button",{"aria-describedby":$,"aria-disabled":j?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{j||d(a,"included",b)},type:"button",children:"Include"}),o("button",{"aria-describedby":E,"aria-disabled":T||!a.actions.exclude.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&a.actions.exclude.enabled&&d(a,"excluded")},type:"button",children:"Exclude"})]}):o("button",{"aria-describedby":E,"aria-disabled":T||!a.actions.remove.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&a.actions.remove.enabled&&d(a,"removed")},type:"button",children:"Remove"}),a.decision!=="unresolved"?o("button",{"aria-describedby":E,"aria-disabled":T||!a.actions.clearDecision.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&a.actions.clearDecision.enabled&&l(a)},type:"button",children:"Clear decision"}):null]})]})}function L1(e){const t=Ew(e.detail.devices);return o("section",{"aria-labelledby":"legacy-team-setup-step-devices",children:[o("h3",{id:"legacy-team-setup-step-devices",tabIndex:-1,children:"Review devices"}),o("p",{children:[e.detail.unresolvedDeviceCount.toLocaleString()," of"," ",e.detail.candidate.deviceCount.toLocaleString()," Team devices still need a decision."]}),o("div",{className:"legacy-team-device-list",children:t.map((n,r)=>g(D1,{...e,busy:e.busyDeviceRefs.has(n.deviceRef),device:n,index:r,key:n.deviceRef}))})]})}function $1(e,t){return e.resolvedProjectRef?t.get(e.resolvedProjectRef)??"Unavailable Project":null}function j1({blocked:e,blockedDescriptionId:t,blockedProjectRefs:n,busy:r,index:i,onMap:a,presentationName:s,project:c}){const l=Dr(),d=`${l}-mapping`,u=`${l}-help`,p=c.resolvedProjectRef??"",f=Or(c.mappingChoices.map($=>({canonicalId:$.resolvedProjectRef,displayName:$.displayName}))),m=[...new Set(c.mappingChoices.map($=>$.resolvedProjectRef))],v=[...m].sort(($,E)=>$<E?-1:$>E?1:0),b=new Map(v.map(($,E)=>[$,`project-choice-${E+1}`])),h=new Map(c.mappingChoices.map($=>[$.resolvedProjectRef,$])),y=m.flatMap($=>{const E=h.get($);return E?[{...E,label:f.get($)??E.displayName,token:b.get($)??""}]:[]}),w=y.find($=>$.resolvedProjectRef===p)?.token??"",_=JSON.stringify(v),[R,I]=D(w);V(()=>I(w),[w,_]);const T=y.find($=>$.token===R)?.resolvedProjectRef,A=n?.has(c.projectRef)??!1,L=c.actions.map.blockedReason==="mapping_unavailable",F=c.actions.map.enabled&&!R,N=e||A||r||!c.actions.map.enabled,j=N||!T||T===p,x=$1(c,f),U=[L||F?u:void 0,e?t:A?_f("project",c.projectRef):void 0].filter(Boolean).join(" "),q=c.resolution==="unresolved";return o("fieldset",{"aria-busy":r?"true":"false",className:`legacy-team-project-row${q?" legacy-team-setup-row-needs-attention":""}`,id:`legacy-team-project-row-${i}`,tabIndex:q?-1:void 0,children:[o("legend",{children:s}),o("div",{className:"legacy-team-project-row-content",children:[q?o("span",{className:"legacy-team-setup-status",children:"Needs attention"}):null,c.resolution==="deterministic"?o("p",{className:"small",children:"Mapped automatically from matching Project evidence."}):o(z,{children:[o("p",{className:"small",children:x?`Saved mapping: ${x}`:"This Project still needs a mapping."}),o("label",{htmlFor:d,children:"Canonical Project"}),o("select",{"aria-describedby":U||void 0,className:"feed-search legacy-team-project-select",disabled:N,id:d,onChange:$=>I($.currentTarget.value),value:R,children:[o("option",{value:"",children:"Choose a Project"}),y.map($=>o("option",{value:$.token,children:$.label},$.resolvedProjectRef))]}),L?o("p",{className:"small",id:u,children:"No safe Project mapping is available. Refresh after Project evidence changes."}):F?o("p",{className:"small",id:u,children:"Choose and save one of the server-provided Project mappings."}):null,o("button",{"aria-describedby":U||void 0,"aria-disabled":j?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!j&&T&&a(c,T)},type:"button",children:"Save mapping"})]})]})]})}function O1(e){const t=Aw(e.detail.projects),n=Or(t.map(a=>({canonicalId:a.projectRef,displayName:a.displayName}))),r=e.detail.projects.filter(a=>a.resolution==="deterministic").length,i=Math.max(e.detail.candidate.projectCount,e.detail.projects.length,e.detail.unresolvedProjectCount);return o("section",{"aria-labelledby":"legacy-team-setup-step-projects",children:[o("h3",{id:"legacy-team-setup-step-projects",tabIndex:-1,children:"Review Projects"}),o("p",{children:e.detail.unresolvedProjectCount===0?`All ${i.toLocaleString()} Team Projects are mapped.`:`${e.detail.unresolvedProjectCount.toLocaleString()} of ${i.toLocaleString()} Team Projects need attention.`}),r>0?o("p",{className:"small",children:"Review the automatic mappings below before continuing."}):null,o("div",{className:"legacy-team-project-list",children:t.map((a,s)=>o(j1,{blocked:e.blocked,blockedDescriptionId:e.blockedDescriptionId,blockedProjectRefs:e.blockedProjectRefs,busy:e.busyProjectRefs.has(a.projectRef),index:s,onMap:e.onMap,presentationName:n.get(a.projectRef)??a.displayName,project:a},a.projectRef))}),e.detail.unresolvedProjectCount===0?o("div",{className:"legacy-team-setup-next-action",children:[o("p",{className:"small",id:"legacy-team-project-continue-help",children:"Continue to review the exact people, devices, and Projects that will receive access."}),o("button",{"aria-describedby":["legacy-team-project-continue-help",e.blocked?e.blockedDescriptionId:null].filter(Boolean).join(" "),"aria-disabled":e.blocked?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{e.blocked||e.onContinue()},type:"button",children:"Continue to Review"})]}):null]})}var No={add:"Add",update:"Update",remove:"Remove"},M1=10;function ft(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function wf(e,t,n,r){const i=new Map;for(const a of e){const s=t(a),c=r(a),l=`${c}:${xa(s)}`,d=n(a),u=i.get(l)??{displayName:s,kind:c,projectRefs:new Set,changeCount:0};u.projectRefs.add(d),u.changeCount+=1,i.set(l,u)}return[...i.values()]}function Sf(e,t){return e.kind==="legacy_default_sharing"?`${e.displayName} — default scope`:e.projectRefs.size>1?`${e.displayName} — ${ft(e.projectRefs.size,t)}`:e.displayName}function Eo({empty:e,exactItemName:t,exactItems:n,summaryItems:r,title:i}){const a=!!(r&&r.length<n.length),s=a&&n.length>M1;return o("section",{children:[o("h4",{children:i}),n.length>0?o(z,{children:[a&&r?o("ul",{className:"legacy-team-setup-delta-summary",children:r.map((c,l)=>o("li",{children:c},`${i}-summary-${l}`))}):null,s?o("details",{children:[o("summary",{children:["Show all ",ft(n.length,`exact ${t}`)]}),o(Dw,{items:n,title:i})]}):o(Dw,{items:n,title:i})]}):o("p",{className:"small",children:e})]})}function Dw({items:e,title:t}){return o("ul",{className:"legacy-team-setup-exact-list",children:e.map((n,r)=>o("li",{children:n},`${t}-${r}`))})}function F1({blocked:e,blockedDescriptionId:t,detail:n,finishing:r,onFinish:i}){const a=n.accessDelta,s=JSON.stringify([n.attemptId,n.finishDigest,n.accessDeltaDigest,n.viewerAccessDeltaDigest]),[c,l]=D(null),d=c===s,u=e||!d,p=[d?null:"legacy-team-setup-confirmation-label",e?t:null].filter(Boolean).join(" "),f=a.teamChanges.map(C=>{const O=C.fromDeviceEligibilityMode==="person_all_devices"?"all devices assigned to each person":C.fromDeviceEligibilityMode==="reviewed_allowlist"?"the reviewed device list":"no existing device policy";return`${No[C.change]} ${C.teamDisplayName}: change device access from ${O} to the reviewed device list.`}),m=a.membershipChanges.map(C=>`${No[C.change]} ${C.identityDisplayName} ${C.change==="remove"?"from":"to"} ${C.teamDisplayName}.`),v=Or([...n.projects.map(C=>({canonicalId:C.projectRef,displayName:C.displayName})),...a.projectChanges.map(C=>({canonicalId:C.projectRef,displayName:C.projectDisplayName}))]),b=a.projectChanges.flatMap(C=>[...C.fromResolvedProjectRef&&C.fromResolvedProjectDisplayName?[{canonicalProjectRef:C.fromCanonicalProjectRef,resolvedProjectRef:C.fromResolvedProjectRef,displayName:C.fromResolvedProjectDisplayName}]:[],...C.toResolvedProjectRef&&C.toResolvedProjectDisplayName?[{canonicalProjectRef:C.toCanonicalProjectRef,resolvedProjectRef:C.toResolvedProjectRef,displayName:C.toResolvedProjectDisplayName}]:[]]),h=Or(b.map(C=>({canonicalId:C.canonicalProjectRef??C.resolvedProjectRef,displayName:C.displayName}))),y=new Map(b.map(C=>[C.resolvedProjectRef,h.get(C.canonicalProjectRef??C.resolvedProjectRef)??C.displayName])),w=Or([...n.projects.flatMap(C=>C.canonicalProjectRef?[{canonicalId:C.canonicalProjectRef,displayName:C.displayName}]:[]),...[...a.recipientChanges,...a.deviceAccessChanges].filter(C=>C.canonicalProjectKind==="project").map(C=>({canonicalId:C.canonicalProjectRef,displayName:C.canonicalProjectDisplayName}))]),_=a.projectChanges.map(C=>`${No[C.change]} ${v.get(C.projectRef)??C.projectDisplayName}: ${C.fromResolvedProjectRef?y.get(C.fromResolvedProjectRef)??C.fromResolvedProjectDisplayName??"no Project":"no Project"} to ${C.toResolvedProjectRef?y.get(C.toResolvedProjectRef)??C.toResolvedProjectDisplayName??"no Project":"no Project"}.`),R=a.recipientChanges.map(C=>C.canonicalProjectKind==="legacy_default_sharing"?`${C.change==="remove"?"Stop":"Start"} using legacy default sharing for ${C.recipientDisplayName}.`:`${No[C.change]} ${C.recipientDisplayName} ${C.change==="remove"?"from":"as"} a recipient for ${w.get(C.canonicalProjectRef)??C.canonicalProjectDisplayName}.`),I=a.deviceAccessChanges.map(C=>C.canonicalProjectKind==="legacy_default_sharing"?`${C.deviceDisplayName} ${C.change==="remove"?"stops":"starts"} inheriting legacy default sharing.`:`${No[C.change]} ${C.deviceDisplayName} access ${C.change==="remove"?"from":"to"} ${w.get(C.canonicalProjectRef)??C.canonicalProjectDisplayName}.`),T=a.teamChanges.length+a.membershipChanges.length+a.projectChanges.length+a.recipientChanges.length+a.deviceAccessChanges.length,A=wf(a.projectChanges,C=>C.projectDisplayName,C=>C.projectRef,()=>"project"),L=wf(a.recipientChanges,C=>C.canonicalProjectDisplayName,C=>C.canonicalProjectRef,C=>C.canonicalProjectKind),F=wf(a.deviceAccessChanges,C=>C.canonicalProjectDisplayName,C=>C.canonicalProjectRef,C=>C.canonicalProjectKind),N=n.devices.filter(C=>C.decision==="included").length,j=[ft(a.teamChanges.length,"Team policy change"),ft(a.membershipChanges.length,"membership change"),ft(a.projectChanges.length,"Project change"),ft(a.recipientChanges.length,"recipient change"),ft(a.deviceAccessChanges.length,"device-access change")],x=`${ft(n.projects.length,"Project")} included; ${ft(N,"included device")}.`,U=Math.max(n.candidate.projectCount,n.projects.length),q=new Set(a.deviceAccessChanges.map(C=>C.deviceRef)).size,$=[...a.teamChanges,...a.membershipChanges,...a.projectChanges,...a.recipientChanges,...a.deviceAccessChanges].filter(C=>C.change==="remove").length,E=a.teamChanges.length===0&&a.membershipChanges.length===0&&a.projectChanges.length===0&&a.recipientChanges.length>0&&a.recipientChanges.every(C=>C.change==="remove"&&C.canonicalProjectKind==="legacy_default_sharing")&&a.deviceAccessChanges.every(C=>C.change==="remove"&&C.canonicalProjectKind==="legacy_default_sharing")?`No new access will be added. This removes legacy default sharing for ${n.candidate.displayName}.${q>0?` ${ft(q,"device")} will stop receiving memories shared only through that default.`:""} Project-scoped access is unchanged across ${ft(U,"reviewed Project")}.`:`${ft(T,"server-confirmed access change")} will be applied atomically; ${ft($,"removal")} ${$===1?"is":"are"} included.`;return o("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[o("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),o("p",{children:"Review every server-confirmed access change before activating this Team."}),o("section",{"aria-label":"Access review summary",className:"legacy-team-setup-review-summary",children:[o("p",{className:"legacy-team-setup-net-effect",children:[o("strong",{children:"Net effect:"})," ",E]}),o("p",{children:[o("strong",{children:ft(T,"exact access change")})," to review."]}),o("ul",{children:j.map(C=>o("li",{children:C},C))}),o("p",{className:"small",children:["Scope: ",x]})]}),o("div",{className:"legacy-team-setup-delta",children:[o(Eo,{empty:"No Team policy changes.",exactItemName:"Team policy change",exactItems:f,title:"Team policy"}),o(Eo,{empty:"No membership changes.",exactItemName:"membership change",exactItems:m,title:"Memberships"}),o(Eo,{empty:"No Project mapping changes.",exactItemName:"Project change",exactItems:_,summaryItems:A.map(C=>`${Sf(C,"reviewed Project")}, ${ft(C.changeCount,"Project change")}`),title:"Projects"}),o(Eo,{empty:"No recipient changes.",exactItemName:"recipient change",exactItems:R,summaryItems:L.map(C=>`${Sf(C,"canonical Project")}, ${ft(C.changeCount,"recipient change")}`),title:"Recipients"}),o(Eo,{empty:"No device access changes.",exactItemName:"device-access change",exactItems:I,summaryItems:F.map(C=>`${Sf(C,"canonical Project")}, ${ft(C.changeCount,"device-access change")}`),title:"Device access"})]}),o("label",{className:"legacy-team-setup-confirmation",id:"legacy-team-setup-confirmation-label",children:[o("input",{"aria-disabled":e?"true":void 0,"aria-describedby":e?t:void 0,checked:d,onClick:C=>{e&&C.preventDefault()},onChange:C=>{if(e){C.currentTarget.checked=d;return}l(C.currentTarget.checked?s:null)},type:"checkbox"}),o("span",{children:"I reviewed every access change above and approve activating this Team."})]}),r?o("p",{"aria-live":"polite",className:"legacy-team-setup-finish-progress",role:"status",children:[o("span",{"aria-hidden":"true",className:"legacy-team-setup-spinner"}),"Checking the latest Team roster and applying all reviewed changes atomically. No partial changes will be kept if this cannot finish."]}):null,o("button",{"aria-describedby":p||void 0,"aria-disabled":u?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{u||i(n)},type:"button",children:r?"Finishing Team setup…":"Finish Team setup"})]})}function B1(e){let t=null;return async n=>{try{const r=await q1(n,e,()=>t,i=>{t=i});return{status:"success",generation:n.generation,id:n.id,kind:n.kind,view:r}}catch(r){let i,a;try{i=await U1(n,e,r)}catch(s){a=s}return{status:"failure",generation:n.generation,id:n.id,kind:n.kind,cause:r,...a?{recoveryCause:a}:{},...i?{recoveredView:i}:{}}}}}async function q1(e,t,n,r){switch(e.kind){case"load":return e.refresh?t.refreshCandidate(e.candidateRef):t.loadDetail(e.candidateRef);case"assign_device":return t.saveAssignment(e.candidateRef,e.deviceRef,e.input);case"decide_device":return t.saveDecision(e.candidateRef,e.deviceRef,e.input);case"clear_device":return t.clearDecision(e.candidateRef,e.deviceRef,e.input);case"map_project":return t.saveProjectMapping(e.candidateRef,e.projectRef,e.input);case"refresh":return t.refreshCandidate(e.candidateRef);case"finish":await t.finish(e.candidateRef,e.input);return;case"completion_refresh":{const i=n();if(i?.attemptId===e.attemptId&&i.candidateRef===e.candidateRef){await i.promise;return}const a=Promise.resolve().then(()=>t.onCompleted());r({attemptId:e.attemptId,candidateRef:e.candidateRef,promise:a});try{await a}finally{n()?.promise===a&&r(null)}return}default:throw new Error(`Unhandled Team setup effect: ${String(e)}`)}}async function U1(e,t,n){if(e.kind!=="completion_refresh"&&!(!(n instanceof St)||!Cf(n.errorCode))&&!(e.kind==="load"&&(e.refresh||e.completionOnly||n.errorCode!=="team_setup_confirmation_stale")))return t.loadDetail(e.candidateRef)}function Cf(e){return["team_setup_roster_changed","team_setup_assignment_changed","team_setup_conflict","team_setup_confirmation_stale"].includes(e)}function Lw(e,t){return{id:e,targetId:`legacy-team-setup-step-${t}`}}function G1(e,t,n){return jw(e,n>=0?`${t==="devices"?"legacy-team-device-row":"legacy-team-project-row"}-${n}`:`legacy-team-setup-step-${t}`)}function $w(e,t){return jw(e,t.recovery||t.hasError?"legacy-team-setup-retry":`legacy-team-setup-step-${t.step}`)}function jw(e,t){return{id:e,targetId:t}}var Ow="Team setup changed since it was last reviewed. Reload the latest details to continue.",Mw="Team device details are temporarily unavailable. Check the coordinator connection and settings, then refresh.",H1="Team device details were unavailable, so setup was not finished and no changes were applied. Check the coordinator connection and settings, then refresh.",V1="This device's Project history is too large to finish setup here, so no changes were applied. Retry from a device with less history, or contact support.",K1="Team setup completion could not be checked. Check the coordinator connection and settings, then retry.",Fw="Team setup could not be confirmed, and no local changes were applied. Retry to check whether setup completed.",z1="Another device completed this Team with different reviewed details. Retry to load the completed setup.",W1="The completed Team setup could not be verified. Retry, then check the coordinator connection and settings if the problem continues.";function J1(){return{status:"closed",generation:0}}function Rf(e,t){switch(t.type){case"open":return e.status==="open"&&Wn(e)?e:Y1(e.generation+1,t.candidateRef);case"close":return e.status==="open"&&Wn(e)?e:{status:"closed",generation:e.generation+1};case"close_blocked":case"open_blocked":return e.status==="open"?{...e,message:t.message}:e;case"navigate":return X1(e,t.step);case"blocked_navigation":return tl(e,t.step,t.message);case"retry":return Q1(e);case"refresh":return eF(e,"refresh","Refreshing Team setup from the latest server state.");case"assign_device":return If(e,t,"assign_device");case"decide_device":return If(e,t,"decide_device");case"clear_device":return If(e,t,"clear_device");case"map_project":return Z1(e,t);case"finish":return tF(e);case"command_started":return hF(e,t.id,n=>({...n,status:"running"}));case"effect_outcome":return nF(e,t.outcome);case"focus_applied":return e.status==="open"&&e.focus?.id===t.id?{...e,focus:null}:e;default:return t}}function Y1(e,t){return gr({status:"open",generation:e,candidateRef:t,view:null,step:"devices",projectsVisitedAttemptId:null,commands:[],nextCommandId:1,errors:[],message:"",focus:null,nextFocusId:1},{kind:"load",candidateRef:t,refresh:!1,focusOnOutcome:!1})}function X1(e,t){if(e.status!=="open"||e.step==="completed"||t==="completed")return e;if(t==="projects"&&e.view?.unresolvedDeviceCount)return tl(e,"devices","Finish the device decisions before mapping Projects.");if(t==="review"&&e.view?.unresolvedDeviceCount)return tl(e,"devices","Finish the device decisions before reviewing access.");if(t==="review"&&e.view?.unresolvedProjectCount)return tl(e,"projects","Finish the Project mappings before reviewing access.");const n=t==="projects"&&e.view?e.view.attemptId:e.projectsVisitedAttemptId;return{...e,step:t,projectsVisitedAttemptId:n,focus:Lw(e.nextFocusId,t),nextFocusId:e.nextFocusId+1}}function tl(e,t,n){if(e.status!=="open"||e.step==="completed"||!e.view)return e;const r=t==="devices"?Ew(e.view.devices).findIndex(i=>i.decision==="unresolved"):Aw(e.view.projects).findIndex(i=>i.resolution==="unresolved");return{...e,step:t,projectsVisitedAttemptId:t==="projects"?e.view.attemptId:e.projectsVisitedAttemptId,message:n,focus:G1(e.nextFocusId,t,r),nextFocusId:e.nextFocusId+1}}function Q1(e){if(e.status!=="open"||e.step==="completed"||Ao(e)||Wn(e))return e;const t=nl(e)?.retry??e.errors.find(n=>n.retry)?.retry??"load";return gr(e,{kind:"load",candidateRef:e.candidateRef,refresh:t==="refresh",completionOnly:t==="completion",focusOnOutcome:!0})}function If(e,t,n){if(e.status!=="open"||e.step==="completed"||!kf(e.view)||nl(e)||Ao(e)||Wn(e))return e;const r=e.view.devices.find(c=>c.deviceRef===t.deviceRef);if(!r||!(t.type==="assign_device"?r.actions.assignIdentity:t.type==="clear_device"?r.actions.clearDecision:t.decision==="included"?r.actions.include:t.decision==="excluded"?r.actions.exclude:r.actions.remove).enabled)return e;const i={candidateRef:e.candidateRef,deviceRef:t.deviceRef},a=n==="assign_device"&&t.type==="assign_device"?{kind:n,...i,input:{attemptId:e.view.attemptId,targetIdentityRef:t.targetIdentityRef,expectation:r.expectation}}:n==="clear_device"&&t.type==="clear_device"?{kind:n,...i,input:{attemptId:e.view.attemptId}}:t.type==="decide_device"?{kind:"decide_device",...i,input:t.decision==="included"&&t.targetIdentityRef?{attemptId:e.view.attemptId,decision:"included",expectedTargetIdentityRef:t.targetIdentityRef}:{attemptId:e.view.attemptId,decision:t.decision}}:null;if(!a||t.type==="decide_device"&&t.decision==="included"&&!t.targetIdentityRef)return e;const s=t.type==="assign_device"?`Saving the assignment for ${r.displayName}.`:t.type==="clear_device"?`Clearing the decision for ${r.displayName}.`:`Saving the decision for ${r.displayName}.`;return gr(si(e,{kind:"device",itemRef:t.deviceRef}),a,s)}function Z1(e,t){if(e.status!=="open"||e.step==="completed"||!kf(e.view)||nl(e)||Ao(e)||Wn(e))return e;const n=e.view.projects.find(r=>r.projectRef===t.projectRef);return!n?.actions.map.enabled||!n.mappingChoices.some(r=>r.resolvedProjectRef===t.resolvedProjectRef)?e:gr(si(e,{kind:"project",itemRef:t.projectRef}),{kind:"map_project",candidateRef:e.candidateRef,projectRef:t.projectRef,input:{attemptId:e.view.attemptId,resolvedProjectRef:t.resolvedProjectRef}},`Saving the mapping for ${n.displayName}.`)}function eF(e,t,n){return e.status!=="open"||e.step==="completed"||!e.view?.actions.refresh.enabled||Ao(e)||Wn(e)?e:gr(si(e,{kind:"global"}),{kind:t,candidateRef:e.candidateRef},n)}function tF(e){return e.status!=="open"||e.step==="completed"||e.view?.state!=="ready_to_finish"||e.commands.length||e.errors.length>0?e:gr(si(e,{kind:"global"}),{kind:"finish",candidateRef:e.candidateRef,attemptId:e.view.attemptId,input:{attemptId:e.view.attemptId,finishDigest:e.view.finishDigest,confirmedAccessDeltaDigest:e.view.accessDeltaDigest,confirmedViewerAccessDeltaDigest:e.view.viewerAccessDeltaDigest}},"Finishing Team setup.")}function gr(e,t,n=e.message){const r=`${e.generation}:${e.nextCommandId}`;return{...e,commands:[...e.commands,{...t,generation:e.generation,id:r,status:"pending"}],nextCommandId:e.nextCommandId+1,message:n}}function nF(e,t){if(e.status!=="open"||e.generation!==t.generation)return e;const n=e.commands.find(i=>i.id===t.id);if(!n)return e;const r={...e,commands:e.commands.filter(i=>i.id!==t.id)};return n.kind==="load"&&n.completionOnly&&t.status==="success"&&t.view?.state!=="completed"?Bw(r,n,{status:"failure",generation:t.generation,id:t.id,kind:n.kind,cause:new St(409,"team_setup_confirmation_stale")}):t.status==="failure"?Bw(r,n,t):n.kind==="completion_refresh"?{...r,message:"Team setup complete. Sharing and Projects are up to date."}:n.kind==="finish"?iF(r,n.attemptId):t.view?qw({...mF(r,n),message:rF(n,e.view)},t.view,n.kind==="load"&&n.focusOnOutcome):r}function rF(e,t){if(e.kind==="refresh")return"Team setup refreshed.";if(e.kind==="load")return"";if("deviceRef"in e){const n=t?.devices.find(r=>r.deviceRef===e.deviceRef)?.displayName;return n?`${n} saved.`:"Device saved."}if("projectRef"in e){const n=t?.projects.find(r=>r.projectRef===e.projectRef)?.displayName;return n?`${n} saved.`:"Project mapping saved."}return""}function Bw(e,t,n){if(t.kind==="completion_refresh")return{...e,message:"Team setup complete. Sharing or Projects could not be refreshed; use that view's Refresh control."};const r=n.recoveredView?qw(e,n.recoveredView,!1):e;if(n.recoveredView?.state==="completed")return r;const i=aF(t,n.cause,n.recoveryCause),a={...r,errors:[...si(r,i.scope).errors,i],message:""};return t.kind!=="load"||!t.focusOnOutcome?a:{...a,focus:$w(a.nextFocusId,{hasError:!0,recovery:a.view?.state==="unavailable",step:a.step}),nextFocusId:a.nextFocusId+1}}function qw(e,t,n){const r=pF(t,e.projectsVisitedAttemptId===t.attemptId),i=r==="projects"?t.attemptId:e.projectsVisitedAttemptId,a=t.state==="unavailable"?[{scope:{kind:"global"},message:fF(t.unavailableReason),retry:"refresh"}]:t.state==="completed"?[]:e.errors.filter(l=>{if(l.scope.kind==="device"){const d=l.scope.itemRef;return t.devices.some(u=>u.deviceRef===d)}if(l.scope.kind==="project"){const d=l.scope.itemRef;return t.projects.some(u=>u.projectRef===d)}return!1});let s={...e,view:t,step:r,projectsVisitedAttemptId:i,errors:a,message:t.state==="completed"?"Team setup complete. Sharing and Projects are refreshing.":e.message};const c=a.some(l=>l.scope.kind==="global"||l.scope.kind==="load");return(n||r!==e.step)&&(s={...s,focus:$w(s.nextFocusId,{hasError:c,recovery:t.state==="unavailable",step:r}),nextFocusId:s.nextFocusId+1}),t.state==="completed"&&!Vw(s,t.attemptId)&&(s=gr(s,{kind:"completion_refresh",candidateRef:s.candidateRef,attemptId:t.attemptId})),s}function iF(e,t){let n={...e,step:"completed",message:"Team setup complete. Sharing and Projects are refreshing.",focus:Lw(e.nextFocusId,"completed"),nextFocusId:e.nextFocusId+1};return Vw(n,t)||(n=gr(n,{kind:"completion_refresh",candidateRef:n.candidateRef,attemptId:t})),n}function aF(e,t,n){const r=t instanceof St&&Cf(t.errorCode),i=t instanceof St&&t.errorCode==="team_setup_roster_unavailable",{completionCode:a,message:s,terminalRecoveryCode:c}=lF({command:e,cause:t,recoveryCause:n,changed:r,rosterUnavailable:i});return{scope:oF(e,{globalError:r||i||a!==null}),message:s,retry:sF(e,t,n,{changed:r,rosterUnavailable:i,terminalRecovery:c!==null})}}function oF(e,t){return t.globalError?{kind:"global"}:e.kind==="assign_device"||e.kind==="decide_device"||e.kind==="clear_device"?{kind:"device",itemRef:e.deviceRef}:e.kind==="map_project"?{kind:"project",itemRef:e.projectRef}:e.kind==="load"?{kind:"load"}:{kind:"global"}}function sF(e,t,n,r){return t instanceof St&&t.errorCode==="team_setup_confirmation_stale"||n instanceof St&&n.errorCode==="team_setup_confirmation_stale"?e.kind==="load"&&e.refresh?"completion":"refresh":e.kind==="load"&&e.completionOnly?cF(t):r.terminalRecovery?"load":r.changed||r.rosterUnavailable||e.kind==="refresh"||e.kind==="load"&&e.refresh?"refresh":"load"}function cF(e){return e instanceof St&&rl(e.errorCode)!==null?"completion":"refresh"}function lF(e){const{command:t,cause:n,recoveryCause:r,changed:i,rosterUnavailable:a}=e,s=n instanceof St?rl(n.errorCode):null,c=uF(r instanceof St?rl(r.errorCode):null),l=c??s,d=l==="team_setup_completion_unavailable"&&t.kind==="finish"?dF(n):Gw(l);if(c)return{completionCode:l,message:d??Uw(t.kind),terminalRecoveryCode:c};if(i)return{completionCode:l,message:Ow,terminalRecoveryCode:c};if(a){let u=Mw;return t.kind==="finish"&&(u=n instanceof St&&n.reason==="local_candidate_scan_budget_exceeded"?V1:H1),{completionCode:l,message:u,terminalRecoveryCode:c}}return{completionCode:l,message:d??Uw(t.kind),terminalRecoveryCode:c}}function dF(e){return e instanceof St&&e.reason==="coordinator_route_missing"?`${Fw} The coordinator may be running an older version.`:Fw}function uF(e){return e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function Uw(e){switch(e){case"load":return"Team setup details are temporarily unavailable. Retry to load the latest details.";case"assign_device":case"decide_device":case"clear_device":return"This device change could not be saved. Reload the latest details before trying again.";case"map_project":return"This Project mapping could not be saved. Reload the latest details before trying again.";case"refresh":return"Team setup could not be refreshed. Retry to load the latest server details.";case"finish":return"Team setup could not be finished. Reload the latest details before trying again.";case"completion_refresh":return"Team setup completed, but dependent views could not be refreshed.";default:return e}}function pF(e,t){return e.state==="completed"?"completed":e.unresolvedDeviceCount>0?"devices":!t&&e.projects.length>0||e.unresolvedProjectCount>0?"projects":"review"}function kf(e){return e?.state==="reviewing"||e?.state==="ready_to_finish"}function Wn(e){return e.commands.some(t=>t.kind==="load"&&t.refresh||["refresh","assign_device","decide_device","clear_device","map_project","finish"].includes(t.kind))}function Ao(e){return e.commands.some(t=>["load","refresh","finish"].includes(t.kind))}function nl(e){return e.errors.find(t=>t.scope.kind==="global"||t.scope.kind==="load")??null}function fF(e){if(Cf(e))return Ow;if(e==="team_setup_roster_unavailable")return Mw;const t=Gw(rl(e));return t||(e==="team_setup_incomplete"?"Team setup needs refreshed server details before review can continue.":"Team setup details are temporarily unavailable. Refresh to load the latest server state.")}function rl(e){return e==="team_setup_completion_unavailable"||e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function Gw(e){return e==="team_setup_completion_unavailable"?K1:e==="team_setup_completion_conflict"?z1:e==="team_setup_completion_invalid"?W1:null}function Hw(e){return e.kind==="global"||e.kind==="load"}function si(e,t){const n=Hw(t);return{...e,errors:e.errors.filter(r=>n?!Hw(r.scope):r.scope.kind!==t.kind?!0:!("itemRef"in t)||!("itemRef"in r.scope)?!1:r.scope.itemRef!==t.itemRef)}}function mF(e,t){return t.kind==="assign_device"||t.kind==="decide_device"||t.kind==="clear_device"?si(e,{kind:"device",itemRef:t.deviceRef}):t.kind==="map_project"?si(e,{kind:"project",itemRef:t.projectRef}):{...e,errors:[]}}function hF(e,t,n){return e.status==="open"?{...e,commands:e.commands.map(r=>r.id===t?n(r):r)}:e}function Vw(e,t){return e.commands.some(n=>n.kind==="completion_refresh"&&n.attemptId===t)}var gF={role:"list"},vF={role:"listitem"};function yF(e){const t=e.session,n=t.view,r=nl(t),i=t.commands.some(_=>_.kind==="load"),a=Ao(t)||Wn(t),s=t.commands.some(_=>_.kind==="finish"),c=n?.state==="unavailable"||r?.retry==="refresh",l=r!=null&&(!n||c),d=!kf(n)||a||!!r,u=[r?"legacy-team-setup-error":null,a?"legacy-team-setup-operation-status":null,n?.state==="unavailable"?"legacy-team-setup-refresh":null].filter(Boolean).join(" ")||void 0,p=n?`Set up ${n.candidate.displayName}`:"Set up Team",f=t.errors.filter(_=>_.scope.kind==="device"||_.scope.kind==="project"),m=f.length>0,v=f.some(_=>_.retry==="refresh"),b=new Set(f.flatMap(_=>_.scope.kind==="device"?[_.scope.itemRef]:[])),h=new Set(f.flatMap(_=>_.scope.kind==="project"?[_.scope.itemRef]:[])),y=new Set(t.commands.flatMap(_=>"deviceRef"in _?[_.deviceRef]:[])),w=new Set(t.commands.flatMap(_=>"projectRef"in _?[_.projectRef]:[]));return o(Ln,{ariaDescribedby:"legacy-team-setup-description",ariaLabelledby:"legacy-team-setup-title",contentClassName:"modal legacy-team-setup-dialog",contentId:"legacyTeamSetupDialog",onCloseAutoFocus:e.onCloseAutoFocus,onOpenAutoFocus:e.onOpenAutoFocus,onOpenChange:_=>{_||e.onClose()},open:!0,overlayClassName:"modal-backdrop",overlayId:"legacyTeamSetupDialogBackdrop",children:o("div",{"aria-busy":a?"true":"false",className:"modal-card legacy-team-setup-card",children:[o("div",{className:"modal-header",children:[o("div",{id:"legacy-team-setup-title",tabIndex:-1,children:o(zd,{children:p})}),o(Lr,{ariaDisabled:a,ariaLabel:`Close ${p}`,onClick:e.onClose})]}),o("div",{className:"modal-body legacy-team-setup-body",children:[o("p",{className:"small",id:"legacy-team-setup-description",children:"Review device ownership and Project access before this Team can be used for sharing."}),i&&!n?o("p",{role:"status",children:"Loading the latest Team setup details…"}):null,r?o("div",{className:"legacy-team-setup-error legacy-team-setup-recovery",id:"legacy-team-setup-global-error",children:[l?o("strong",{children:"Current setup details are unavailable"}):null,o("p",{"aria-live":"assertive",id:"legacy-team-setup-error",role:"alert",children:r.message}),o("button",{"aria-busy":a?"true":void 0,"aria-disabled":a?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-retry",onClick:()=>{a||e.onRetry()},type:"button",children:i?r.retry==="refresh"?"Refreshing…":"Retrying…":r.retry==="refresh"?"Retry loading current setup":"Retry"})]}):null,m?o("div",{className:"legacy-team-setup-error",id:"legacy-team-setup-item-errors",children:[f.map(_=>o("p",{"aria-live":"assertive",id:"itemRef"in _.scope?_f(_.scope.kind,_.scope.itemRef):void 0,role:"alert",children:_.message},"itemRef"in _.scope?`${_.scope.kind}:${_.scope.itemRef}`:_.scope.kind)),o("button",{"aria-busy":a?"true":void 0,"aria-disabled":a?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-item-retry",onClick:()=>{a||e.onRetry()},type:"button",children:i?v?"Refreshing…":"Retrying…":v?"Refresh Team setup":"Retry"})]}):null,n?o(z,{children:[t.step!=="completed"&&!l?o(bF,{onNavigate:e.onNavigate,step:t.step,unresolvedDeviceCount:n.unresolvedDeviceCount,unresolvedProjectCount:n.unresolvedProjectCount}):null,i?o("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-refresh-status",role:"status",children:"Refreshing Team setup details…"}):null,o("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-operation-status",role:"status",children:t.message}),l?null:t.step==="devices"?o(L1,{blocked:d,blockedDescriptionId:u,blockedDeviceRefs:b,busyDeviceRefs:y,detail:n,onAssign:e.onAssign,onClear:e.onClear,onDecision:e.onDecide}):t.step==="projects"?o(O1,{blocked:d,blockedDescriptionId:u,blockedProjectRefs:h,busyProjectRefs:w,detail:n,onContinue:()=>e.onNavigate("review"),onMap:e.onMap}):t.step==="review"&&n.state==="ready_to_finish"?o(F1,{blocked:d||m,blockedDescriptionId:m?"legacy-team-setup-item-errors":u,detail:n,finishing:s,onFinish:e.onFinish}):o(_F,{busy:a,canFinish:n.state==="ready_to_finish",onRefresh:e.onRefresh,recoveryRequired:c,step:t.step})]}):null]}),o("div",{className:"modal-footer legacy-team-setup-actions",children:o("button",{"aria-disabled":a?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:e.onClose,type:"button",children:"Close"})})]})})}function bF(e){const t=e.unresolvedDeviceCount>0,n=e.unresolvedProjectCount>0;return o(z,{children:[o("ol",{...gF,"aria-label":"Team setup steps",className:"legacy-team-setup-steps",children:[{label:"Devices",step:"devices"},{label:"Projects",step:"projects"},{label:"Review",step:"review"}].map((i,a)=>{const s=i.step==="projects"?t:i.step==="review"?t||n:!1,c=s?t?"legacy-team-setup-block-devices":"legacy-team-setup-block-projects":void 0;return g("li",{...vF,className:"legacy-team-setup-step",key:i.step},o("span",{"aria-hidden":"true",className:"legacy-team-setup-step-number",children:a+1}),o("button",{"aria-current":e.step===i.step?"step":void 0,"aria-describedby":c,"aria-disabled":s?"true":void 0,"aria-label":`Step ${a+1}: ${i.label}`,className:"settings-button legacy-team-setup-target",onClick:()=>e.onNavigate(i.step),type:"button",children:i.label}))})}),t?o("p",{className:"small",id:"legacy-team-setup-block-devices",children:"Finish the device decisions before mapping Projects or reviewing access."}):null,n?o("p",{className:"small",id:"legacy-team-setup-block-projects",children:"Finish the Project mappings before reviewing access."}):null]})}function _F(e){return e.step==="completed"?o("section",{"aria-labelledby":"legacy-team-setup-step-completed",children:[o("h3",{id:"legacy-team-setup-step-completed",tabIndex:-1,children:"Team setup complete"}),o("p",{children:"This Team is ready for Project sharing."})]}):e.step!=="review"?null:o("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[o("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),o("p",{children:e.canFinish?"The server has confirmed that this Team is ready for final review.":"Final review is waiting for the latest setup details."}),o("p",{className:"small",children:"Next setup action: review the access summary before finishing."}),!e.canFinish&&!e.recoveryRequired?o("button",{"aria-busy":e.busy?"true":void 0,"aria-disabled":e.busy?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{e.busy||e.onRefresh()},type:"button",children:"Refresh Team setup"}):null]})}var wF={clearDecision:mI,finish:vI,loadDetail:uI,onCompleted:()=>{},refreshCandidate:gI,saveAssignment:pI,saveDecision:fI,saveProjectMapping:hI},Tf="codemem:open-legacy-team-setup";function Kw(e){if(!e)return!1;const t={candidateRef:e,handled:!1,returnFocus:document.activeElement instanceof HTMLElement?document.activeElement:null};return window.dispatchEvent(new CustomEvent(Tf,{detail:t})),t.handled}function SF(e){if(!e?.isConnected||e.tabIndex<0||e.matches(":disabled")||e.closest('[hidden], [inert], [aria-hidden="true"]'))return!1;for(let t=e;t;t=t.parentElement){const n=window.getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden"||n.visibility==="collapse")return!1}return!0}function CF({dependencies:e}){const[t,n]=D(J1),r=B(null),i=Ie(()=>B1(e),[e]),a=l=>{n(d=>Rf(d,l))};return Tt(()=>{const l=d=>{const u=d;u.detail.handled=!0,r.current=u.detail.returnFocus,n(p=>p.status==="open"&&Wn(p)?Rf(p,{type:"open_blocked",message:"Wait for the current Team setup change to finish before opening another Team."}):Rf(p,{type:"open",candidateRef:u.detail.candidateRef}))};return window.addEventListener(Tf,l),()=>{window.removeEventListener(Tf,l)}},[]),V(()=>{if(t.status==="open")for(const l of t.commands.filter(d=>d.status==="pending"))a({type:"command_started",id:l.id}),i(l).then(d=>a({type:"effect_outcome",outcome:d}))},[i,t]),V(()=>{if(t.status!=="open"||!t.focus)return;const l=document.getElementById(t.focus.targetId)??document.getElementById("legacy-team-setup-title");l&&(l.focus(),a({type:"focus_applied",id:t.focus.id}))},[t]),t.status==="closed"?null:o(yF,{session:t,onAssign:(l,d)=>a({type:"assign_device",deviceRef:l.deviceRef,targetIdentityRef:d}),onClear:l=>a({type:"clear_device",deviceRef:l.deviceRef}),onClose:()=>{if(Wn(t)){a({type:"close_blocked",message:"Team setup will stay open while this change saves. Close it after saving finishes."});return}a({type:"close"})},onCloseAutoFocus:l=>IF(l,r),onDecide:(l,d,u)=>{if(d==="included"&&!u){a({type:"open_blocked",message:`Save a person assignment before including ${l.displayName}.`});return}a({type:"decide_device",deviceRef:l.deviceRef,decision:d,...u?{targetIdentityRef:u}:{}})},onFinish:()=>a({type:"finish"}),onMap:(l,d)=>a({type:"map_project",projectRef:l.projectRef,resolvedProjectRef:d}),onNavigate:l=>a({type:"navigate",step:l}),onOpenAutoFocus:RF,onRefresh:()=>a({type:"refresh"}),onRetry:()=>a({type:"retry"})})}var RF=e=>{const t=document.getElementById("legacy-team-setup-title");t&&(e.preventDefault(),t.focus())};function IF(e,t){e.preventDefault();const n=document.querySelector('.tab-btn[aria-current="page"]');(SF(t.current)?t.current:n)?.focus(),t.current=null}function kF(e,t={}){const n={...wF,...t};Ue(o(CF,{dependencies:n}),e)}var xo=new WeakMap,Do=new Set,il=new Set,zw=100,vr="";function rn(e,t=""){const n=document.createElement("p");return t&&(n.className=t),n.textContent=e,n}function Ww(e,t){const n=document.createElement("h3");return n.className="recipient-policy-review-heading",n.textContent=`${e} (${t.toLocaleString()})`,n}function TF(e){const t=new Map;for(const n of e){const r=`${n.projectGroup.identity}\0${n.conditionCode}`,i=t.get(r);if(i){i.items.push(n);continue}t.set(r,{key:r,displayName:n.projectGroup.displayName,items:[n]})}return[...t.values()]}function Pf(e,t){return e.options.find(n=>n.decision===t)}function PF(e){const t=e.items[0];return t?Pf(t,t.recommendedDecision)?.label??t.recommendedDecision.replaceAll("_"," "):""}function Jw(e,t){const n=document.createElement("div");n.className="recipient-policy-preview-list";const r=document.createElement("strong");r.textContent=e;const i=document.createElement("ul");for(const a of t){const s=document.createElement("li");s.textContent=a,i.appendChild(s)}return n.append(r,i),n}function Yw(e){return[...new Map(e.map(t=>[t.id,t.label])).values()]}function NF(e){const t=new Map;for(const n of e)for(const r of n.preview.projects){const i=t.get(r.canonicalIdentity)??0;t.set(r.canonicalIdentity,Math.max(i,n.preview.affectedMemoryCount))}return[...t.values()].reduce((n,r)=>n+r,0)}function EF(e,t){const n=e.items.flatMap(l=>{const d=Pf(l,t);return d?[d]:[]}),r=Yw(n.flatMap(l=>l.preview.projects.map(d=>({id:d.canonicalIdentity,label:`${d.displayName} — ${d.canonicalIdentity}`})))),i=Yw(n.flatMap(l=>l.preview.effectiveDevices.map(d=>({id:d.deviceId,label:`${d.displayName} (${d.assignment})`})))),a=NF(n),s=document.createElement("div");s.className="recipient-policy-preview settings-note";const c=document.createElement("strong");return c.textContent=`Affected: ${r.length.toLocaleString()} Project${r.length===1?"":"s"} · ${a.toLocaleString()} memor${a===1?"y":"ies"} · ${i.length.toLocaleString()} device${i.length===1?"":"s"}`,s.append(c,Jw("Projects and paths",r)),i.length>0&&s.appendChild(Jw("Devices",i)),s}function AF(e){return e==="unassigned_effective_device"?"This decision needs Identity or device details. Complete that setup first, then return to this review.":"This decision needs recipient details. Use the Project sharing controls below, then return to this review."}async function xF(e,t){const n=e.items.map(a=>({decision:t,reviewItemId:a.reviewItemId,sourceFingerprint:a.sourceFingerprint}));if(n.length===1)try{return await RI(n[0]),{stale:!1,failed:!1}}catch(a){if(!(a instanceof th))throw a;return il.add(n[0].reviewItemId),{stale:!0,failed:!1}}let r=!1,i=!1;for(let a=0;a<n.length;a+=zw){const s=n.slice(a,a+zw),c=await II(s);for(const l of c.results)l.status==="stale"?(il.add(l.reviewItemId),r=!0):l.status!=="applied"&&(i=!0)}return{stale:r,failed:i}}function Xw(e){return e.items.length>1?"Apply to all worktrees":"Apply decision"}function Nf(e,t){const n=e.items[0];if(!n)return;const r=t.select.value,i=e.items.map(c=>Pf(c,r)),a=i.some(c=>c?.preview.requiresDecisionInput),s=i.some(c=>!c);t.previewMount.replaceChildren(EF(e,r)),t.deferred.textContent=a?AF(n.conditionCode):"",t.deferred.hidden=!a,t.submit.disabled=a||s||Do.has(e.key)}function DF(e,t){if(t.failed)return"Some review items could not be updated. Review the remaining items and try again.";if(t.stale)return"Source state changed. Review the refreshed choices before trying again.";for(const n of e.items)il.delete(n.reviewItemId);return"Decision applied. Review items refreshed."}function Qw(e,t){t.select.disabled=!1,t.submit.textContent=Xw(e),Nf(e,t)}async function LF(e,t,n,r){if(t.submit.disabled||Do.has(e.key))return;const i=t.select.value;Do.add(e.key),t.select.disabled=!0,t.submit.disabled=!0,t.submit.textContent="Applying…",n.textContent="Applying review decision…";try{const a=await xF(e,i);vr=DF(e,a),n.textContent=vr,Do.delete(e.key),(a.failed||a.stale)&&Qw(e,t),await r.onRefresh?.()}catch(a){vr=a instanceof Error?a.message:"Unable to apply decision.",n.textContent=vr,Do.delete(e.key),Qw(e,t);try{await r.onRefresh?.()}catch(s){const c=s instanceof Error?s.message:"Unable to refresh review items.";vr=`${vr} Refresh failed: ${c}`,n.textContent=vr}}}function $F(e,t,n,r){const i=e.items[0];if(!i)throw new Error("Review group must contain at least one item.");const a=document.createElement("div");a.className="project-inventory-actions";const s=document.createElement("label");s.htmlFor=`recipient-policy-decision-${t}`,s.textContent="Decision";const c=document.createElement("select");c.id=s.htmlFor,c.className="project-filter recipient-policy-review-select",c.dataset.reviewControl="decision";for(const f of i.options){const m=document.createElement("option");m.value=f.decision,m.textContent=f.label,c.appendChild(m)}c.value=i.recommendedDecision;const l=document.createElement("button");l.className="settings-button",l.type="button",l.textContent=Xw(e),l.dataset.reviewControl="apply";const d=rn("","settings-note recipient-policy-deferred"),u=document.createElement("div");u.className="recipient-policy-preview-mount",u.setAttribute("aria-live","polite");const p={container:a,deferred:d,previewMount:u,select:c,submit:l};return c.addEventListener("change",()=>Nf(e,p)),l.addEventListener("click",()=>LF(e,p,n,r)),Nf(e,p),a.append(s,c,l),p}function jF(e,t,n,r){const i=e.items[0];if(!i)throw new Error("Review group must contain at least one item.");const a=document.createElement("article");a.className="project-inventory-row recipient-policy-review-item",a.dataset.reviewGroup=e.key;const s=document.createElement("h4");s.className="project-inventory-title",s.textContent=`${e.displayName}: ${i.finding}`;const c=rn(i.reason,"project-inventory-meta"),l=rn(`Recommended: ${PF(e)}`,"settings-note");a.append(s,c,l),e.items.some(u=>il.has(u.reviewItemId))&&a.appendChild(rn("Source state changed while this decision was being reviewed. Review the refreshed choices before trying again.","settings-note project-attention-note"));const d=$F(e,t,n,r);return a.append(d.container,d.deferred,d.previewMount),a}function OF(e,t,n){const r=TF(e.reviewItems),i=document.createElement("section");i.className="recipient-policy-review-section recipient-policy-review-decisions",i.append(Ww("Review findings",r.length),rn("Review each repository before Codemem records how its older sharing state should be represented. Access stays unchanged until you apply a decision.","section-meta"));const a=document.createElement("div");return a.className="project-inventory-list recipient-policy-review-list",r.forEach((s,c)=>{a.appendChild(jF(s,c,t,n))}),i.appendChild(a),i}function MF(e,t){const n=document.createElement("article");n.className="project-inventory-row recipient-policy-blocked-item";const r=document.createElement("div");r.className="project-inventory-row-header";const i=document.createElement("h3");i.className="project-inventory-title",i.textContent=e.finding;const a=document.createElement("span");a.className="project-status-badge needs_attention",a.textContent="Blocked",r.append(i,a);const s=rn(e.repairAction,"settings-note");if(s.id=`recipient-policy-repair-help-${e.blockedItemId}`,n.append(r,rn(e.reason,"project-inventory-meta"),s,rn(`Owner: ${e.ownerLabel}`,"settings-note")),t.onRepair&&(t.isRepairAvailable?.(e.repair)??!0)){const c=document.createElement("button");c.className="settings-button",c.type="button",c.textContent=e.repair.label,c.setAttribute("aria-describedby",s.id),c.addEventListener("click",async()=>{c.disabled=!0;try{await t.onRepair?.(e.repair)}finally{c.disabled=!1}}),n.appendChild(c)}else n.appendChild(rn("Open Projects to repair this item.","settings-note"));return n}function FF(e,t){const n=document.createElement("section");n.className="recipient-policy-review-section recipient-policy-review-blocked",n.append(Ww("Blocked source repairs",e.blockedItems.length),rn("Access has not changed. Repair each source record before Codemem can safely interpret it.","section-meta project-attention-note"));const r=document.createElement("div");r.className="project-inventory-list recipient-policy-review-list";for(const i of e.blockedItems)r.appendChild(MF(i,t));return n.appendChild(r),n}function BF(e){const t=document.activeElement;if(!(t instanceof HTMLElement)||!e.contains(t))return null;const n=t.closest("[data-review-group]")?.dataset.reviewGroup,r=t.dataset.reviewControl;return n&&r?{group:n,control:r}:null}function qF(e,t){if(t){for(const n of e.querySelectorAll("[data-review-group]"))if(n.dataset.reviewGroup===t.group){n.querySelector(`[data-review-control="${t.control}"]`)?.focus();return}}}function UF(e,t,n={}){const r=t.blockedItems.map(u=>n.onRepair&&(n.isRepairAvailable?.(u.repair)??!0)?"1":"0"),i={blockedItems:t.blockedItems,reviewItems:t.reviewItems},a=`review:${r.join("")}:${JSON.stringify(i)}`;if(xo.get(e)===a)return;if(t.reviewItems.length===0&&t.blockedItems.length===0){e.replaceChildren(),e.hidden=!0,xo.set(e,a);return}const s=BF(e);e.hidden=!1;const c=document.createElement("section");c.className="card recipient-policy-review",c.setAttribute("aria-labelledby","recipientPolicyReviewTitle");const l=document.createElement("h2");l.id="recipientPolicyReviewTitle",l.textContent="Sharing review";const d=document.createElement("div");d.className="section-meta recipient-policy-review-status",d.setAttribute("role","status"),d.setAttribute("aria-live","polite"),d.textContent=vr,c.append(l,d),t.reviewItems.length>0&&c.appendChild(OF(t,d,n)),t.blockedItems.length>0&&c.appendChild(FF(t,n)),e.replaceChildren(c),qF(e,s),xo.set(e,a)}function GF(e,t){const n=t instanceof Error?t.message:"Unable to load recipient migration review.",r=`error:${n}`;if(xo.get(e)===r)return;e.hidden=!1;const i=document.createElement("section");i.className="card recipient-policy-review";const a=document.createElement("h2");a.textContent="Sharing review";const s=rn(n,"settings-note project-attention-note");s.setAttribute("role","status"),i.append(a,s),e.replaceChildren(i),xo.set(e,r)}var Zw=[["","All projects"],["needs_attention","Needs review"],["suggested","Has suggestion"],["local_only","Stays on this device"],["received","Received from peers"],["explicitly_mapped","Already assigned"],["legacy_review","Older shared data"],["unmapped","Missing project identity"]],bt=null,Ht=0,al=250,HF=100,Ef=[],ol=new Set,sl=new Set,cl=new Map,ll=new Map,ci=new Map,Lo=new Map,dl=!1,$o=new Map,jo=!1,yr=!1,Af=0,eS=null,Jn=0,Oo=0,sa=null,Mo=null,Vt=new Set,tS=new WeakMap,ul={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},ca=ul,br=!1,xf;function VF(e=!1,t={}){if(!e&&Mo)return Mo;const n=ah(t).then(r=>({ok:!0,summary:r})).catch(()=>({ok:!1}));return Mo=n,n.then(()=>{Mo===n&&(Mo=null)}),n}function Df(e){return VF(e.awaitTeamSetupSummary===!0||e.requireTeamSetupSummary===!0,e)}function Le(e){return document.getElementById(e)}function KF(e){return Zw.find(([t])=>t===e)?.[1]??e.replaceAll("_"," ")}function zF(e){switch(e){case"exact_mapping":return"assigned to a Space";case"pattern_mapping":return"assigned by matching rule";case"explicit_override":return"manually assigned";default:return"stays on this device"}}function bn(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function pl(e){return e.identity_source!=="unmapped"&&!bn(e)}function WF(e){const t=$o.get(e.workspace_identity);(!t||bn(t)&&!bn(e))&&$o.set(e.workspace_identity,e)}function Lf(e){return bn(e)?"Received from peers":ml(e.resolved_scope_id)}function JF(e){return bn(e)?"source-owned project":zF(e.resolution_reason)}function YF(e){const t=e.person.display_name;switch(e.lifecycle.state){case"waiting_for_acceptance":return`Invitation sent to ${t}`;case"active":return`Shared with ${t}`;case"waiting_for_device":return`Sharing with ${t}`;case"needs_attention":return`Sharing with ${t} needs attention`;case"revoking":return`Removing sharing with ${t}`;case"revoked":return`Previously shared with ${t}`;case"cancelled":return`Invitation to ${t} cancelled`;default:return`Setting up sharing with ${t}`}}function nS(e){if(!e)return"No recent sessions";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function rS(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function li(){const e=Vt.size,t=Le("projectsShareSelected");t&&(t.textContent=e===0?"Share selected":`Share selected (${e})`,t.disabled=e===0||!yr||!br,t.classList.add("project-selection-target"));const n=Le("projectsSelectionStatus");n&&(n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.textContent=`${e.toLocaleString()} Project${e===1?"":"s"} selected.`);for(const r of document.querySelectorAll(".project-selection-checkbox")){const i=tS.get(r)??[],a=i.filter(s=>Vt.has(s)).length;r.checked=i.length>0&&a===i.length,r.indeterminate=a>0&&a<i.length}for(const r of document.querySelectorAll(".project-recipient-action"))r.disabled=!yr||!br}function XF(e){const t=e.every(n=>Vt.has(n));for(const n of e)t?Vt.delete(n):Vt.add(n);li()}function iS(e,t){const n=rS(e),r=document.createElement("label");r.className="project-selection-control project-selection-target";const i=document.createElement("input");i.className="project-selection-checkbox",i.dataset.projectFocusKey=`select:${n.join("|")}`,i.type="checkbox",i.setAttribute("aria-label",t),tS.set(i,n),i.addEventListener("change",()=>XF(n));const a=document.createElement("span");return a.className="sr-only",a.textContent=t,r.append(i,a),r}function QF(e){if(!br)return[];const t=new Set(e),n=new Map(ca.teams.filter(a=>a.status==="active").map(a=>[a.teamId,a.displayName])),r=new Map(ca.identities.filter(a=>a.status==="active"||a.status==="pending").map(a=>[a.identityId,a.displayName])),i=new Map;for(const a of ca.projectRecipients)if(!(a.status!=="active"||!t.has(a.canonicalProjectIdentity)))if(a.recipientKind==="team"){const s=n.get(a.teamId);s&&i.set(`team:${a.teamId}`,{key:`team:${a.teamId}`,kind:"Team",displayName:s})}else{const s=r.get(a.identityId);s&&i.set(`identity:${a.identityId}`,{key:`identity:${a.identityId}`,kind:"Identity",displayName:s})}return[...i.values()].sort((a,s)=>`${a.kind}:${a.displayName}`.localeCompare(`${s.kind}:${s.displayName}`))}function aS(e){const t=document.createElement("div");t.className="project-recipient-summary";const n=QF(e),r=document.createElement("div");if(r.className="project-recipient-status",r.textContent=br?n.length===0?"Not shared with any recipients.":e.length===1?`Shared with ${n.length.toLocaleString()} recipient${n.length===1?"":"s"}.`:`${n.length.toLocaleString()} recipient${n.length===1?"":"s"} across these Project identities.`:"Recipient access is unavailable.",t.appendChild(r),n.length>0){const i=document.createElement("ul");i.className="project-recipient-chips",i.setAttribute("aria-label","Active recipients");for(const a of n){const s=document.createElement("li");s.className=`project-recipient-chip project-recipient-chip-${a.kind.toLowerCase()}`,s.textContent=`${a.kind}: ${a.displayName}`,i.appendChild(s)}t.appendChild(i)}return t}function oS(e,t){const n=document.createElement("button");return n.className="settings-button project-recipient-action project-selection-target",n.type="button",n.disabled=!yr||!br,e.length===1?(n.textContent="Manage recipients",n.setAttribute("aria-label",`Manage recipients for ${t}`),n.dataset.projectFocusKey=`manage:${e[0]}`,n.addEventListener("click",()=>{$a({mode:"project-manage",projectId:e[0]})})):(n.textContent="Share selected",n.setAttribute("aria-label",`Share selected identities for ${t}`),n.dataset.projectFocusKey=`share:${e.join("|")}`,n.addEventListener("click",()=>{for(const r of e)Vt.add(r);li(),$a({mode:"project-add",projectIds:[...e].sort()})})),n}function ZF(e){return e.git_remote?e.git_remote:e.cwd?e.cwd:e.workspace_identity}function $f(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function jf(e){return e.project||e.display_project||"Unnamed Project"}function sS(e){const t=String(e||"").trim();return t?S.lastProjectCoordinatorAdminGroups.find(n=>String(n.group_id||"").trim()===t&&!n.archived_at)?.display_name||"Team details unavailable":null}function eB(){return new Set(S.lastProjectCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function tB(e){return!jo||e.authority_type!=="coordinator"||!e.group_id?!1:!eB().has(String(e.group_id).trim())}function fl(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function cS(){dl&&(dl=!1,bt?.())}async function nB(){let e;try{const t=await Kl();e=t&&typeof t=="object"?t:null}catch{S.lastProjectCoordinatorAdminGroups=[],jo=!1;return}if(e?.readiness!=="ready"||!e.has_admin_secret){S.lastProjectCoordinatorAdminGroups=[],jo=!1;return}try{const t=await Um(!1);S.lastProjectCoordinatorAdminGroups=Array.isArray(t?.items)?t.items:[],jo=!0}catch{S.lastProjectCoordinatorAdminGroups=[],jo=!1}}function rB(e){return e.kind==="team_default"}function Of(e){const t=e.label||"Untitled Space";return rB(e)?`${t} (default)`:t}function iB(e,t){const n=Of(e);return t.some(r=>r.scope_id!==e.scope_id&&Of(r)===n)?`${n} · Space ID ${e.scope_id}`:n}function aB(e){const t=sS(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Space":`${e.authority_type||"Other"} Space`}function oB(e){return e?Ef.find(t=>t.scope_id===e)??null:null}function ml(e){const t=oB(e);return e?t?`${Of(t)} · ${aB(t)}`:"Unknown Space":"—"}function Mf(){return Ef.filter(e=>e.scope_id!=="legacy-shared-review"&&!tB(e))}function sB(e){return Mf().some(t=>t.scope_id===e)}function lS(...e){for(const t of e)if(t&&sB(t))return t;return e.find(t=>!!t)??""}function cB(e){const t=sS(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function lB(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function dB(){const e=new Map;for(const t of Mf()){const n=lB(t),r=cB(t),i=e.get(n)??{label:r,scopes:[]};e.set(n,{label:i.label,scopes:[...i.scopes,t]})}return[...e.values()]}function dS(e){for(const t of dB()){const n=document.createElement("optgroup");n.label=t.label;for(const r of t.scopes){const i=document.createElement("option");i.value=r.scope_id,i.textContent=iB(r,t.scopes),n.appendChild(i)}e.appendChild(n)}}function uB(e){switch(e.code){case"unknown_project_local_only":return"Current behavior";case"basename_collision_review":return"Name collision";case"scope_reassignment_old_copies":return"Previous copies";case"broad_org_domain_pattern":case"home_directory_org_domain_pattern":return"Broad mapping";default:return"Review item"}}async function Ff(e,t,n=[]){try{await AI({...e.mapping_id&&e.resolution_reason==="exact_mapping"?{id:e.mapping_id}:{},...n.length>0?{confirmed_guardrail_tokens:n}:{},project_pattern:e.display_project,scope_id:t,workspace_identity:e.workspace_identity}),ci.delete(e.workspace_identity),cl.delete(e.workspace_identity),X("Project Space assignment updated. Device access grants are unchanged."),bt?.()}catch(r){if(r instanceof is){ci.set(e.workspace_identity,{requiredGuardrailTokens:r.requiredGuardrailTokens,scopeId:t,warnings:r.guardrailWarnings}),bt?.();return}X(r instanceof Error?r.message:"Unable to update project Space.","warning")}}async function pB(e,t){const n=e.filter(pl);if(n.length!==0)try{await xI({mappings:n.map(r=>({...r.mapping_id&&r.resolution_reason==="exact_mapping"?{id:r.mapping_id}:{},project_pattern:r.display_project,scope_id:t,workspace_identity:r.workspace_identity}))}),X(`Updated ${n.length} project identit${n.length===1?"y":"ies"}. Device access grants are unchanged.`),ll.delete($f(n[0])),bt?.()}catch(r){X(r instanceof is?"One or more identities in this group need review before bulk assignment. Expand the group and save those identities directly.":r instanceof Error?r.message:"Unable to update project Spaces.","warning")}}async function fB(e){if(e.mapping_id!=null)try{await DI(e.mapping_id),ci.delete(e.workspace_identity),cl.delete(e.workspace_identity),X("Project Space assignment removed. The next fallback now applies."),bt?.()}catch(t){X(t instanceof Error?t.message:"Unable to remove project Space assignment.","warning")}}async function uS(e,t=!1){try{const n=Lo.get(e.workspace_identity),r=await $I({...t&&n?{confirmation_token:n.confirmationToken}:{},confirmed:t,workspace_identity:e.workspace_identity});Lo.delete(e.workspace_identity),X(`Forgot ${r.forgotten_memory_count.toLocaleString()} local memor${r.forgotten_memory_count===1?"y":"ies"}. ${r.peer_owned_memory_count.toLocaleString()} peer-owned memor${r.peer_owned_memory_count===1?"y was":"ies were"} left unchanged.`),bt?.()}catch(n){if(n instanceof Zm){Lo.set(e.workspace_identity,{confirmationToken:n.preview.confirmation_token,localOwnedMemoryCount:n.preview.local_owned_memory_count,peerOwnedMemoryCount:n.preview.peer_owned_memory_count}),bt?.();return}X(n instanceof Error?n.message:"Unable to forget project memories.","warning")}}async function pS(e){if(e.identity_source==="unmapped")return;const t=String(e.project||e.display_project||"").trim();let n=[];try{n=(await es()).filter(i=>i&&i!==t)}catch{}const r=await Tp({cancelLabel:"Cancel",confirmLabel:"Change project",description:`This will update ${e.session_count} session${e.session_count===1?"":"s"} and ${e.memory_count??0} memor${e.memory_count===1?"y":"ies"} by changing the stored project. Space assignment stays unchanged.`,initialValue:t,placeholder:"Project name",suggestions:n,title:"Change project",validate:i=>{const a=i.trim();return a?a===t?"Already assigned to this project.":null:"Enter a project name."}});if(r!=null)try{const i=await LI({project:r.trim(),workspace_identity:e.workspace_identity});X(`Changed project to ${i.project} for ${i.moved_session_count} session${i.moved_session_count===1?"":"s"}.`),bt?.()}catch(i){X(i instanceof Error?i.message:"Unable to change project.","warning")}}async function mB(e){const t=$o.get(e);if(t&&!bn(t))return{offset:Ht,project:t};try{let n=0,r=0;for(;;){const i=await Sa({limit:al,offset:n,q:e});r+=1;const a=i.projects.find(c=>c.workspace_identity===e&&!bn(c));if(a)return{offset:i.offset,project:a};if(!i.has_more||i.limit<=0)return null;const s=i.offset+i.limit;if(s<=n||r>=HF)return null;n=s}}catch{return null}}function fS(e){const t=[...document.querySelectorAll("[data-project-workspace-identity]")].find(a=>a.dataset.projectWorkspaceIdentity===e&&a.dataset.projectRepairable==="true");if(!t)return!1;const n=t.querySelector(".project-inventory-details");if(!n)return!1;const r=t.closest(".project-inventory-cluster"),i=r?.querySelector(":scope > .project-inventory-details");if(i){i.open=!0;const a=r?.dataset.projectClusterKey;a&&sl.add(a)}return n.open=!0,ol.add(`${t.dataset.projectRepairable}:${e}`),n.scrollIntoView?.({block:"center",behavior:"smooth"}),n.querySelector("summary")?.focus(),!0}async function hB(e){if(fl()){X("Finish the open Space assignment, then try Repair again.","warning");return}const t=Jn,n=Le("projectsSearch")?.value??"",r=Le("projectsStatusFilter")?.value??"",i=Ht,a=await mB(e.projectIdentity);if(Jn!==t||(Le("projectsSearch")?.value??"")!==n||(Le("projectsStatusFilter")?.value??"")!==r||Ht!==i)return;if(fl()){X("Finish the open Space assignment, then try Repair again.","warning");return}if(!a){X("This Project is not visible in the current inventory. Refresh Projects, then try Repair again.","warning");return}const{project:s}=a;if(e.kind==="reassign_project"){if(s.identity_source==="unmapped"||s.session_count===0){X("This Project cannot be reassigned yet because it has no local sessions with stable source evidence.","warning");return}await pS(s);return}if(!fS(s.workspace_identity)){const c=Le("projectsSearch"),l=c?.value??"",d=s.workspace_identity;c&&(c.value=d);const u=Le("projectsStatusFilter"),p=u?.value??"",f="";u&&(u.value=f);const m=Ht;Ht=a.offset;const v=Jn;if(await la(),!fS(s.workspace_identity)){if(Jn!==v||c&&c.value!==d||u&&u.value!==f||Ht!==a.offset)return;c&&(c.value=l),u&&(u.value=p),Ht=m,await la(),X("Project administration could not be opened. Refresh Projects and try again.","warning")}}}function gB(e){const t=Jn,n=(sa?.catch(()=>{})??Promise.resolve()).then(async()=>{if(Jn===t)try{await hB(e)}catch(r){X(r instanceof Error?r.message:"Unable to repair this Project.","warning")}});return sa=n,n.then(()=>{sa===n&&(sa=null)},()=>{sa===n&&(sa=null)}),n}function vB(e){const t=document.createElement("div");if(t.className="project-inventory-actions",pl(e)&&e.memory_count!=null&&e.guardrail_warnings.every(m=>!m.requires_confirmation)){const m=document.createElement("button");m.className="settings-button",m.type="button",m.textContent="Share",m.disabled=!yr,yr||(m.title="The complete project list is unavailable."),m.addEventListener("click",()=>As([e.workspace_identity])),t.appendChild(m)}if(bn(e)){const m=document.createElement("div");return m.className="settings-note",m.textContent="This project was received from a peer. Change its project or Space on the source device; this node keeps the received identity read-only.",t.appendChild(m),t}if(e.identity_source==="unmapped"){const m=document.createElement("div");return m.className="settings-note",m.textContent="This project is missing a stable path, git remote, or workspace id. It stays Local only until it has a stable identity.",t.appendChild(m),t}const n=document.createElement("label");n.className="sr-only";const r=`project-domain-${e.workspace_identity.replace(/[^a-z0-9_-]/gi,"-")}`;n.htmlFor=r,n.textContent=`Space for ${e.display_project}`;const i=document.createElement("select");i.id=r,i.className="project-domain-select";const a=Mf().some(m=>m.scope_id===e.resolved_scope_id);if(!a&&e.resolved_scope_id){const m=document.createElement("option");m.value=e.resolved_scope_id,m.textContent=`${ml(e.resolved_scope_id)} — not assignable`,m.disabled=!0,i.appendChild(m)}dS(i),i.value=lS(cl.get(e.workspace_identity),e.suggested_scope_id,e.resolved_scope_id);const s=document.createElement("button");s.className="settings-button",s.type="button",s.textContent=e.suggested_scope_id&&i.value===e.suggested_scope_id?"Confirm suggestion":"Save Space",s.disabled=!i.value||i.value===e.resolved_scope_id&&!a,s.addEventListener("click",()=>{Ff(e,i.value)}),i.addEventListener("change",()=>{cl.set(e.workspace_identity,i.value),ci.delete(e.workspace_identity),t.querySelector(".project-space-guardrail-confirmation")?.remove(),s.textContent="Save Space",s.disabled=!i.value,bt?.()}),i.addEventListener("blur",cS);const c=document.createElement("button");c.className="settings-button",c.type="button",c.textContent="Keep local-only",c.addEventListener("click",()=>{Ff(e,"local-default")});const l=document.createElement("button");l.className="settings-button",l.type="button",l.textContent="Remove mapping",l.disabled=e.mapping_id==null||e.resolution_reason!=="exact_mapping",l.addEventListener("click",()=>{fB(e)});const d=document.createElement("button");d.className="settings-button",d.type="button",d.textContent="Change project…",d.disabled=e.session_count===0,d.disabled&&(d.title="No sessions are available to reassign for this saved mapping."),d.addEventListener("click",()=>{pS(e)});const u=document.createElement("button");u.className="settings-button danger",u.type="button",u.textContent="Forget local memories…",u.disabled=(e.memory_count??0)===0,u.addEventListener("click",()=>{uS(e)}),t.append(n,i,s,c,l,d,u);const p=ci.get(e.workspace_identity);if(p){const m=document.createElement("div");m.className="settings-note project-guardrail-confirmation project-space-guardrail-confirmation",m.setAttribute("role","alert");const v=document.createElement("strong");v.textContent="Confirmation required before saving this Space.";const b=document.createElement("p");b.textContent="Codemem can save this change after you acknowledge the checks below. Verify the workspace details, then confirm to complete the save.";const h=document.createElement("ul");for(const _ of p.warnings){const R=document.createElement("li"),I=document.createElement("strong");I.textContent=`${uB(_)}: `;const T=document.createElement("span");T.textContent=_.message,R.append(I,T),h.appendChild(R)}const y=document.createElement("button");y.className="settings-button",y.type="button",y.textContent="I understand, save Space",y.addEventListener("click",()=>{const _=ci.get(e.workspace_identity);!_||_.scopeId!==i.value||Ff(e,_.scopeId,_.requiredGuardrailTokens)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{ci.delete(e.workspace_identity),bt?.()}),m.append(v,b,h,y,w),t.appendChild(m)}const f=Lo.get(e.workspace_identity);if(f){const m=document.createElement("div");m.className="settings-note project-guardrail-confirmation",m.setAttribute("role","alert");const v=document.createElement("strong");v.textContent="Confirm project memory cleanup.";const b=document.createElement("p");b.textContent=`${f.localOwnedMemoryCount.toLocaleString()} locally owned memor${f.localOwnedMemoryCount===1?"y":"ies"} will be forgotten. ${f.peerOwnedMemoryCount.toLocaleString()} peer-owned memor${f.peerOwnedMemoryCount===1?"y":"ies"} will be left unchanged.`;const h=document.createElement("p");h.textContent="Use this only to clean up wrongly attributed local project inventory; it forgets actual local memories on this device.";const y=document.createElement("button");y.className="settings-button danger",y.type="button",y.textContent="I understand, forget local memories",y.addEventListener("click",()=>{uS(e,!0)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{Lo.delete(e.workspace_identity),bt?.()}),m.append(v,b,h,y,w),t.appendChild(m)}return t}function mS(e){const t=document.createElement("article");t.className="project-inventory-row",t.dataset.projectWorkspaceIdentity=e.workspace_identity,t.dataset.projectRepairable=String(pl(e));const n=`project-title-${e.workspace_identity.replace(/[^a-z0-9_-]/gi,"-")}`;t.setAttribute("aria-labelledby",n);const r=document.createElement("div");r.className="project-inventory-row-header",Ps(e)&&r.appendChild(iS([e],`Select ${e.display_project} for recipient sharing`));const i=document.createElement("h3");i.className="project-inventory-title",i.id=n,i.textContent=e.display_project,r.appendChild(i),Ps(e)&&r.appendChild(oS([e.workspace_identity],e.display_project)),t.appendChild(r);const a=document.createElement("div");a.className="project-inventory-meta",a.textContent=`${(e.memory_count??0).toLocaleString()} memories · ${e.session_count.toLocaleString()} sessions · ${nS(e.latest_session_at)}`,t.appendChild(a),t.appendChild(aS([e.workspace_identity]));const s=document.createElement("div");s.className="project-advanced-administration";const c=document.createElement("div");c.className="project-inventory-domain",c.textContent=Lf(e),s.appendChild(c);const l=document.createElement("div");if(l.className="project-inventory-meta",l.textContent=`${JF(e)} · ${e.identity_source} · ${nS(e.latest_session_at)}`,s.appendChild(l),e.sharing&&e.sharing.length>0){const h=document.createElement("div");h.className="settings-note project-sharing-summary";const y=document.createElement("strong");y.textContent="Project sharing";const w=document.createElement("ul");w.setAttribute("aria-label",`People sharing ${e.display_project}`);for(const _ of e.sharing){const R=document.createElement("li"),I=document.createElement("strong");I.textContent=YF(_);const T=document.createElement("span");T.textContent=` — ${_.lifecycle.label}. ${_.lifecycle.explanation}`,R.append(I,T),w.appendChild(R)}h.append(y,w),s.appendChild(h)}if(bn(e)){const h=document.createElement("div");h.className="settings-note",h.textContent="Received memories keep the source device's project and Space assignment. Local reassignment controls are disabled here to avoid split-brain sync state.",s.appendChild(h)}const d=document.createElement("div");if(d.className="project-inventory-signal mono",d.textContent=ZF(e),s.appendChild(d),e.suggested_scope_id&&e.suggested_scope_id!==e.resolved_scope_id){const h=document.createElement("div");h.className="settings-note project-suggestion-note",h.textContent=e.suggestion_reason?`Suggestion: ${e.suggestion_reason}`:`Suggestion: assign this project to ${ml(e.suggested_scope_id)}.`,s.appendChild(h)}const u=(e.guardrail_warnings??[]).filter(h=>h.severity==="warning");if(u.length>0){const h=document.createElement("div");h.className="settings-note project-attention-note",h.textContent=`Needs attention: ${u.map(y=>y.message).join(" ")}`,s.appendChild(h)}if(e.statuses.length>0){const h=document.createElement("div");h.className="project-inventory-badges";for(const y of e.statuses){const w=document.createElement("span");w.className=`project-status-badge ${y}`,w.textContent=KF(y),h.appendChild(w)}s.appendChild(h)}const p=document.createElement("details");p.className="project-inventory-details";const f=`${t.dataset.projectRepairable}:${e.workspace_identity}`;p.open=ol.has(f),p.addEventListener("toggle",()=>{p.open?ol.add(f):ol.delete(f)});const m=document.createElement("summary");m.dataset.projectFocusKey=`admin:${t.dataset.projectRepairable}:${e.workspace_identity}`,m.textContent=u.length>0?`Advanced Project administration — ${u.length.toLocaleString()} item${u.length===1?"":"s"} need attention`:"Advanced Project administration",p.appendChild(m),p.appendChild(s);const v=document.createElement("dl");v.className="project-detail-grid";const b=[["Workspace identity",e.workspace_identity],["Project",e.project],["CWD",e.cwd],["Git remote",e.git_remote],["Git branch",e.git_branch],["Current Space",Lf(e)],["Suggested Space",e.suggested_scope_id?ml(e.suggested_scope_id):null],["Advanced: current Space ID",e.resolved_scope_id],["Advanced: suggested Space ID",e.suggested_scope_id],["Suggestion reason",e.suggestion_reason],["Sessions",e.session_count],["Memories",e.memory_count??"count unavailable"]];for(const[h,y]of b){const w=document.createElement("dt");w.textContent=h;const _=document.createElement("dd");_.textContent=y==null||y===""?"—":String(y),v.append(w,_)}return p.appendChild(v),p.appendChild(vB(e)),t.appendChild(p),t}function yB(e){const t=[...new Set(e.map(n=>Lf(n)))];return t.length===1?t[0]:"Mixed Spaces"}function bB(e){if(e.length===1)return mS(e[0]);const t=$f(e[0]),n=e.filter(Ps),r=rS(n),i=document.createElement("article");i.className="project-inventory-row project-inventory-cluster",i.dataset.projectClusterKey=t;const a=jf(e[0]),s=`project-cluster-title-${t.replace(/[^a-z0-9_-]/gi,"-")}`;i.setAttribute("aria-labelledby",s);const c=document.createElement("div");c.className="project-inventory-row-header",n.length>0&&c.appendChild(iS(n,`Select all identities for ${jf(e[0])}`));const l=document.createElement("h3");l.className="project-inventory-title",l.id=s,l.textContent=a,c.appendChild(l),r.length>0&&c.appendChild(oS(r,a)),i.appendChild(c);const d=document.createElement("div");d.className="project-advanced-administration";const u=document.createElement("div");u.className="project-inventory-domain",u.textContent=yB(e),d.appendChild(u);const p=e.reduce((_,R)=>_+(R.memory_count??0),0),f=e.reduce((_,R)=>_+R.session_count,0),m=document.createElement("div");m.className="project-inventory-meta",m.textContent=`${e.length} identities · ${f.toLocaleString()} sessions · ${p.toLocaleString()} memories`,i.appendChild(m),i.appendChild(aS(r));const v=document.createElement("div");v.className="project-inventory-actions";const b=e.filter(pl);if(b.length===0){const _=document.createElement("div");_.className="settings-note",_.textContent=e.every(bn)?"These project identities were received from peers. Change project or Space assignments on their source devices.":"These project identities cannot be bulk assigned until they have stable local identities. Expand each identity for details.",v.appendChild(_),d.appendChild(v)}else{const _=b.map(N=>({project:N,warnings:(N.guardrail_warnings??[]).filter(j=>j.requires_confirmation)})),R=_.some(({warnings:N})=>N.length>0),I=new Set(b.map(N=>N.suggested_scope_id).filter(N=>!!N)),T=new Set(b.map(N=>N.resolved_scope_id)),A=document.createElement("select");A.className="project-domain-select",A.setAttribute("aria-label",`Space for ${jf(e[0])} group`);const L=document.createElement("option");L.value="",L.textContent="Choose Space…",A.appendChild(L),dS(A),A.value=lS(ll.get(t));const F=document.createElement("button");if(F.className="settings-button",F.type="button",F.textContent=`Save Space for ${b.length} identit${b.length===1?"y":"ies"}`,F.disabled=!A.value||R,F.addEventListener("click",()=>{pB(b,A.value)}),A.addEventListener("change",()=>{A.value?ll.set(t,A.value):ll.delete(t),F.disabled=!A.value||R}),A.addEventListener("blur",cS),v.append(A,F),I.size>1||T.size>1||R){const N=document.createElement("div");if(N.className="settings-note project-attention-note",N.textContent=R?"One or more identities in this group need individual review before bulk assignment.":"This group has mixed suggestions or current Spaces. Choose a Space explicitly before bulk assignment.",R){const j=document.createElement("ul");for(const{project:x,warnings:U}of _){if(U.length===0)continue;const q=document.createElement("li"),$=document.createElement("strong");$.textContent=`Blocked identity: ${x.workspace_identity}`;const E=document.createElement("span");E.textContent=` — ${U.map(C=>C.message).join(" ")}`,q.append($,E),j.appendChild(q)}N.appendChild(j)}v.appendChild(N)}d.appendChild(v)}const h=document.createElement("details");h.className="project-inventory-details",h.open=sl.has(t),h.addEventListener("toggle",()=>{h.open?sl.add(t):sl.delete(t)});const y=document.createElement("summary"),w=e.reduce((_,R)=>_+(R.guardrail_warnings??[]).filter(I=>I.severity==="warning").length,0);y.textContent=w>0?`Advanced Project administration — ${w.toLocaleString()} item${w===1?"":"s"} need attention`:"Advanced Project administration",h.appendChild(y),h.appendChild(d);for(const _ of e)h.appendChild(mS(_));return i.appendChild(h),i}function _B(e){const t=new Map;for(const n of e){const r=$f(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function hS(e){const t=Le("projectsInventoryList");if(!t)return;t.textContent="";const n=document.createElement("div");n.className="settings-note",n.textContent=e,t.appendChild(n)}function gS(){document.getElementById("projectsInventorySkeleton")?.remove()}function vS(e){const t=Le("projectsInventoryMeta"),n=Le("projectsInventoryList");if(!t||!n)return;const r=document.activeElement instanceof HTMLElement?document.activeElement.dataset.projectFocusKey:void 0;gS(),$o.clear();for(const s of e.projects)WF(s);if(n.textContent="",e.projects.length===0)hS("No projects match those filters.");else for(const s of _B(e.projects))n.appendChild(bB(s));t.textContent=e.total===0?"0 project identities found":`${e.total} project identit${e.total===1?"y":"ies"} found · showing ${e.offset+1}-${Math.min(e.offset+e.projects.length,e.total)}`;const i=Le("projectsPrevPage"),a=Le("projectsNextPage");i&&(i.disabled=e.offset===0),a&&(a.disabled=!e.has_more),li(),r&&[...n.querySelectorAll("[data-project-focus-key]")].find(s=>s.dataset.projectFocusKey===r)?.focus()}function wB(e,t){nB().then(()=>{t===Af&&(fl()||vS(e))})}async function SB(e={}){const t=new Map;let n=0;for(;;){const r=await Sa({limit:250,offset:n,signal:e.signal});for(const i of r.projects)t.set(i.workspace_identity,i);if(!r.has_more)break;n+=r.limit}return[...t.values()]}function CB(e){return Sa({limit:al,offset:Ht,q:Le("projectsSearch")?.value.trim()||void 0,status:Le("projectsStatusFilter")?.value||void 0,signal:e.signal})}function yS(e,t,n){const r=Le("recipientPolicyManagementMount");r&&yv(r,Ns(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&Vt.clear(),li(),bt?.()}})}function bS(e,t){const n=t?.candidates??[],r=e.querySelector(":scope > .project-team-setup-entry");r?.querySelector(".project-team-setup-status")?.remove();const i=r?.contains(document.activeElement)&&document.activeElement instanceof HTMLButtonElement?document.activeElement.dataset.teamSetupCandidateRef:void 0;if(n.length===0){r?.remove(),e.hidden=e.querySelector(":scope > .project-recipient-policy-review-content")?.hidden!==!1,i&&Le("projectsSearch")?.focus();return}const a=JSON.stringify(n.map(d=>[d.candidateRef,d.displayName]));if(r?.dataset.teamSetupSignature===a){e.hidden=!1;return}r?.remove(),e.hidden=!1;const s=document.createElement("section");s.className="card project-team-setup-entry",s.dataset.teamSetupSignature=a;const c=document.createElement("h2");c.textContent="Finish setting up this Team";const l=document.createElement("p");l.className="section-meta",l.textContent="Tell Codemem who uses each device before using this Team for Project sharing.",s.append(c,l);for(const d of n){const u=document.createElement("div");u.className="project-inventory-actions";const p=document.createElement("strong");if(p.textContent=d.displayName,u.appendChild(p),xf){const f=document.createElement("button");f.setAttribute("aria-label",`Finish setting up ${d.displayName}`),f.className="settings-button",f.type="button",f.textContent="Finish setting up this Team",f.dataset.teamSetupCandidateRef=d.candidateRef,f.addEventListener("click",()=>xf?.(d.candidateRef)),u.appendChild(f)}s.appendChild(u)}if(e.appendChild(s),i){let d=!1;for(const u of s.querySelectorAll("button"))if(u.dataset.teamSetupCandidateRef===i){u.focus(),d=!0;break}d||Le("projectsSearch")?.focus()}}function _S(e){const t=e.querySelector(":scope > .project-team-setup-entry");if(!t)return;let n=t.querySelector(".project-team-setup-status");n||(n=document.createElement("p"),n.className="section-meta project-team-setup-status",n.setAttribute("role","status"),t.appendChild(n)),n.textContent="Team setup status is temporarily unavailable. The previous Team setup status is being shown.",e.hidden=!1}function RB(e){const t=e.querySelector(":scope > .project-recipient-policy-review-content");if(t)return t;const n=document.createElement("div");return n.className="project-recipient-policy-review-content",e.prepend(n),n}function la(e={}){const t=EB(e);return eS=t,t}async function wS(e,t){return e.signal?.aborted?!1:!e.awaitTeamSetupSummary&&!e.requireTeamSetupSummary?eS??!1:(await t,!1)}function hl(e,t){return!t.signal?.aborted&&e===Af}function gl(e){return e.awaitTeamSetupSummary===!0||e.requireTeamSetupSummary===!0}async function IB(e){if(!gl(e))return!0;const t=await Df(e);return e.signal?.aborted?!1:!e.requireTeamSetupSummary||t.ok}async function kB(e){if(dl=!0,!gl(e))return!0;const t=++Oo,n=await Df(e);if(e.signal?.aborted||t!==Oo)return!1;const r=Le("recipientPolicyReviewMount");return n.ok?(r&&bS(r,n.summary),!0):(r&&_S(r),!e.requireTeamSetupSummary)}function TB(e){return gl(e.options)?e.teamSetupSummaryPromise.then(t=>!hl(e.loadGeneration,e.options)||e.entryLoadGeneration!==Oo?!1:e.requiredLoadSucceeded&&(!e.options.requireTeamSetupSummary||t.ok)):e.requiredLoadSucceeded}async function PB(e,t){return gl(e)&&await t,!1}function NB(e){const t=Le("recipientPolicyReviewMount");if(!t)return;const n=RB(t);"review"in e?UF(n,e.review,{isRepairAvailable:r=>!r.projectIdentity.startsWith("unmapped:"),onRefresh:async()=>{await la()},onRepair:gB}):GF(n,e.error),t.hidden=n.hidden&&!t.querySelector(".project-team-setup-entry")}async function EB(e){const t=Le("projectsInventoryMeta"),n=Le("projectsInventoryList");if(!t||!n)return IB(e);if(fl())return kB(e);dl=!1;const r=++Af;yr=!1,br=!1,li(),t.textContent="Loading project inventory…";let i=null;try{const a=++Oo;i=Df(e);const[s,c,l,d,u]=await Promise.all([CB(e),kI(e),SB(e).then(f=>({ok:!0,projects:f})).catch(()=>({ok:!1,projects:[]})),CI(e).then(f=>({ok:!0,review:f})).catch(f=>({ok:!1,error:f})),ed(e).then(f=>({ok:!0,intent:f})).catch(f=>({ok:!1,error:f}))]);if(!hl(r,e))return wS(e,i);if(Ef=c.scopes,yr=l.ok,br=u.ok,ca=u.ok?u.intent:ul,l.ok){const f=new Set(Ns(l.projects).map(m=>m.canonicalProjectIdentity));for(const m of Vt)f.has(m)||Vt.delete(m)}const p=Le("projectShareFlowMount");return p&&Cv(p,l.projects,{inventoryError:!l.ok}),NB(d),yS(l.projects,ca,!l.ok||!u.ok),vS(s),wB(s,r),i.then(f=>{if(!hl(r,e)||a!==Oo)return;const m=Le("recipientPolicyReviewMount");if(m){if(!f.ok){_S(m);return}bS(m,f.summary)}}),TB({entryLoadGeneration:a,loadGeneration:r,options:e,requiredLoadSucceeded:l.ok&&"review"in d&&u.ok,teamSetupSummaryPromise:i})}catch(a){if(!hl(r,e))return wS(e,i);$o.clear(),yr=!1,br=!1,ca=ul;const s=Le("projectShareFlowMount");return s&&Cv(s,[],{inventoryError:!0}),yS([],ul,!0),li(),gS(),t.textContent="Project inventory failed to load.",hS(a instanceof Error?a.message:"Unable to load project inventory."),PB(e,i)}}function AB(e,t={}){bt=e,xf=t.onOpenTeamSetup,Vt.clear();const n=Le("projectsStatusFilter");if(n&&n.options.length===0)for(const[a,s]of Zw){const c=document.createElement("option");c.value=a,c.textContent=s,n.appendChild(c)}const r=()=>{Jn+=1,Ht=0,bt?.()};Le("projectsSearch")?.addEventListener("input",r),n?.addEventListener("change",r),Le("projectsPrevPage")?.addEventListener("click",()=>{Jn+=1,Ht=Math.max(0,Ht-al),bt?.()}),Le("projectsNextPage")?.addEventListener("click",()=>{Jn+=1,Ht+=al,bt?.()});const i=Le("projectsShareSelected");i&&i.dataset.recipientPolicyBound!=="true"&&(i.dataset.recipientPolicyBound="true",i.addEventListener("click",()=>{Vt.size!==0&&$a({mode:"project-add",projectIds:[...Vt].sort()})})),li()}function Bf(e,t){const n=e.trim();if(!n)return[];const r=JSON.parse(n);if(!Array.isArray(r)||r.some(a=>typeof a!="string"))throw new Error(`${t.label} must be a JSON string array`);if(!t.normalize&&!t.requireNonEmpty)return r;const i=t.normalize?r.map(a=>a.trim()):r;if(t.requireNonEmpty&&i.some(a=>a.trim()===""))throw new Error(`${t.label} cannot contain empty command tokens`);return i}function xB(e){const t=e.trim();if(!t)return{};const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))throw new Error("observer headers must be a JSON object");const r={};for(const[i,a]of Object.entries(n)){if(typeof i!="string"||!i.trim()||typeof a!="string")throw new Error("observer headers must map string keys to string values");r[i.trim()]=a}return r}var SS="codemem-settings-advanced",CS="gpt-5.1-codex-mini",RS="claude-4.5-haiku",DB=[{value:"observer",label:"Connection"},{value:"queue",label:"Processing"},{value:"sync",label:"Device Sync"}],LB={claudeCommand:"claude_command",codexCommand:"codex_command",observerProvider:"observer_provider",observerModel:"observer_model",observerTierRoutingEnabled:"observer_tier_routing_enabled",observerSimpleModel:"observer_simple_model",observerSimpleTemperature:"observer_simple_temperature",observerReasoningEffort:"observer_reasoning_effort",observerReasoningSummary:"observer_reasoning_summary",observerRichModel:"observer_rich_model",observerRichTemperature:"observer_rich_temperature",observerRichReasoningEffort:"observer_rich_reasoning_effort",observerRichReasoningSummary:"observer_rich_reasoning_summary",observerRichMaxOutputTokens:"observer_rich_max_output_tokens",observerRuntime:"observer_runtime",observerAuthSource:"observer_auth_source",observerAuthFile:"observer_auth_file",observerAuthCommand:"observer_auth_command",observerAuthTimeoutMs:"observer_auth_timeout_ms",observerAuthCacheTtlS:"observer_auth_cache_ttl_s",observerHeaders:"observer_headers",observerMaxChars:"observer_max_chars",packObservationLimit:"pack_observation_limit",packSessionLimit:"pack_session_limit",rawEventsSweeperIntervalS:"raw_events_sweeper_interval_s",syncEnabled:"sync_enabled",syncHost:"sync_host",syncPort:"sync_port",syncInterval:"sync_interval_s",syncMdns:"sync_mdns",syncCoordinatorUrl:"sync_coordinator_url",syncCoordinatorGroup:"sync_coordinator_group",syncCoordinatorTimeout:"sync_coordinator_timeout_s",syncCoordinatorPresenceTtl:"sync_coordinator_presence_ttl_s"},$B=new Set(["claude_command","codex_command","observer_base_url","observer_auth_file","observer_auth_command","observer_headers","sync_coordinator_url"]),jB={claudeCommand:"",codexCommand:"",observerProvider:"",observerModel:"",observerTierRoutingEnabled:!1,observerSimpleModel:"",observerSimpleTemperature:"",observerReasoningEffort:"",observerReasoningSummary:"",observerRichModel:"",observerRichTemperature:"",observerRichReasoningEffort:"",observerRichReasoningSummary:"",observerRichMaxOutputTokens:"",observerRuntime:"api_http",observerAuthSource:"auto",observerAuthFile:"",observerAuthCommand:"",observerAuthTimeoutMs:"",observerAuthCacheTtlS:"",observerHeaders:"",observerMaxChars:"",packObservationLimit:"",packSessionLimit:"",rawEventsSweeperIntervalS:"",syncEnabled:!1,syncHost:"",syncPort:"",syncInterval:"",syncMdns:!1,syncCoordinatorUrl:"",syncCoordinatorGroup:"",syncCoordinatorTimeout:"",syncCoordinatorPresenceTtl:""};function OB(){try{return globalThis.localStorage?.getItem(SS)==="1"}catch{return!1}}function MB(e){try{globalThis.localStorage?.setItem(SS,e?"1":"0")}catch{}}function Yn(e,t){return typeof e=="object"&&e!==null&&Object.hasOwn(e,t)}function Ae(e,t,n){if(Yn(t,n))return t[n];if(Yn(e,n))return e[n]}function $e(e){return e==null?"":String(e)}function vl(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){const t=e.trim().toLowerCase();if(!t||["0","false","no","off"].includes(t))return!1;if(["1","true","yes","on"].includes(t))return!0}return!!e}function FB(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function BB(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function ct(e){const t=e.trim();return t===""?"":t}function qB(e,t,n){return n?{model:n,source:"Configured"}:e==="claude_sidecar"?{model:RS,source:"Recommended (local Claude session)"}:e==="codex_sidecar"?{model:CS,source:"Recommended (local Codex session)"}:t==="anthropic"?{model:RS,source:"Recommended (Anthropic provider)"}:t==="opencode"?{model:"opencode/gpt-5.1-codex-mini",source:"Recommended (OpenCode Zen provider)"}:t&&t!=="openai"?{model:"provider default",source:"Recommended (provider default)"}:{model:CS,source:"Recommended (direct API)"}}function UB(e,t){const n=e??{};switch(t){case"claude_command":{const r=n.claude_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(a=>{if(typeof a!="string")return;const s=a.trim();s&&i.push(s)}),i}case"codex_command":{const r=n.codex_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(a=>{if(typeof a!="string")return;const s=a.trim();s&&i.push(s)}),i}case"observer_provider":case"observer_model":case"observer_simple_model":case"observer_reasoning_effort":case"observer_reasoning_summary":case"observer_rich_model":case"observer_rich_reasoning_effort":case"observer_rich_reasoning_summary":case"observer_auth_file":case"sync_host":case"sync_coordinator_url":case"sync_coordinator_group":return ct($e(n[t]));case"observer_runtime":return ct($e(n.observer_runtime));case"observer_auth_source":return ct($e(n.observer_auth_source));case"observer_auth_command":{const r=n.observer_auth_command;return Array.isArray(r)?r.filter(i=>typeof i=="string"):[]}case"observer_headers":{const r=n.observer_headers;if(!r||typeof r!="object"||Array.isArray(r))return{};const i={};return Object.entries(r).forEach(([a,s])=>{typeof a=="string"&&a.trim()&&typeof s=="string"&&(i[a.trim()]=s)}),i}case"observer_auth_timeout_ms":case"observer_max_chars":case"observer_simple_temperature":case"observer_rich_temperature":case"observer_rich_max_output_tokens":case"pack_observation_limit":case"pack_session_limit":case"raw_events_sweeper_interval_s":case"sync_port":case"sync_interval_s":{if(!Yn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r!==0?r:""}case"sync_coordinator_timeout_s":case"sync_coordinator_presence_ttl_s":{if(!Yn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r>0?r:""}case"observer_auth_cache_ttl_s":{if(!Yn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)?r:""}case"sync_enabled":case"sync_mdns":case"observer_tier_routing_enabled":return vl(n[t]);default:return Yn(n,t)?n[t]:""}}function GB(e,t,n){const r={...e};return Object.keys(n).forEach(i=>{Yn(r,i)&&(r[i]=UB(t,i))}),r}function HB(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let a=[];try{a=Bf(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(R){if(!i||n.has("claude_command"))throw R;const I=r.claude_command;a=Array.isArray(I)?I.filter(T=>typeof T=="string").map(T=>T.trim()).filter(T=>T.length>0):[]}let s=[];try{s=Bf(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(R){if(!i||n.has("codex_command"))throw R;const I=r.codex_command;s=Array.isArray(I)?I.filter(T=>typeof T=="string").map(T=>T.trim()).filter(T=>T.length>0):[]}let c=[];try{c=Bf(t.observerAuthCommand,{label:"observer auth command"})}catch(R){if(!i||n.has("observer_auth_command"))throw R;const I=r.observer_auth_command;c=Array.isArray(I)?I.filter(T=>typeof T=="string"):[]}let l={};try{l=xB(t.observerHeaders)}catch(R){if(!i||n.has("observer_headers"))throw R;const I=r.observer_headers;I&&typeof I=="object"&&!Array.isArray(I)&&Object.entries(I).forEach(([T,A])=>{typeof T=="string"&&T.trim()&&typeof A=="string"&&(l[T]=A)})}const d=t.observerAuthCacheTtlS.trim(),u=t.observerSimpleTemperature.trim(),p=t.observerRichTemperature.trim(),f=t.observerRichMaxOutputTokens.trim(),m=t.rawEventsSweeperIntervalS.trim(),v=d===""?"":Number(d),b=u===""?"":Number(u),h=p===""?"":Number(p),y=f===""?"":Number(f),w=Number(m),_=m===""?"":w;if(d!==""&&!Number.isFinite(v))throw new Error("observer auth cache ttl must be a number");if(u!==""&&(typeof b!="number"||!Number.isFinite(b)||b<0))throw new Error("simple tier temperature must be a non-negative number");if(p!==""&&(typeof h!="number"||!Number.isFinite(h)||h<0))throw new Error("rich tier temperature must be a non-negative number");if(f!==""&&(typeof y!="number"||!Number.isFinite(y)||y<=0||!Number.isInteger(y)))throw new Error("rich tier max output tokens must be a positive integer");if(m!==""&&(!Number.isFinite(w)||w<=0))throw new Error("raw-event sweeper interval must be a positive number");return{claude_command:a,codex_command:s,observer_provider:ct(t.observerProvider),observer_model:ct(t.observerModel),observer_tier_routing_enabled:t.observerTierRoutingEnabled,observer_simple_model:ct(t.observerSimpleModel),observer_simple_temperature:b,observer_reasoning_effort:ct(t.observerReasoningEffort),observer_reasoning_summary:ct(t.observerReasoningSummary),observer_rich_model:ct(t.observerRichModel),observer_rich_temperature:h,observer_rich_reasoning_effort:ct(t.observerRichReasoningEffort),observer_rich_reasoning_summary:ct(t.observerRichReasoningSummary),observer_rich_max_output_tokens:y,observer_runtime:ct(t.observerRuntime||"api_http")||"api_http",observer_auth_source:ct(t.observerAuthSource||"auto")||"auto",observer_auth_file:ct(t.observerAuthFile),observer_auth_command:c,observer_auth_timeout_ms:Number(t.observerAuthTimeoutMs||0)||"",observer_auth_cache_ttl_s:v,observer_headers:l,observer_max_chars:Number(t.observerMaxChars||0)||"",pack_observation_limit:Number(t.packObservationLimit||0)||"",pack_session_limit:Number(t.packSessionLimit||0)||"",raw_events_sweeper_interval_s:_,sync_enabled:t.syncEnabled,sync_host:ct(t.syncHost),sync_port:Number(t.syncPort||0)||"",sync_interval_s:Number(t.syncInterval||0)||"",sync_mdns:t.syncMdns,sync_coordinator_url:ct(t.syncCoordinatorUrl),sync_coordinator_group:ct(t.syncCoordinatorGroup),sync_coordinator_timeout_s:Number(t.syncCoordinatorTimeout||0)||"",sync_coordinator_presence_ttl_s:Number(t.syncCoordinatorPresenceTtl||0)||""}}function VB(e){const t=e.config||{},n=e.effective||{},r=Ae(t,n,"observer_headers"),i=r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).filter(([p,f])=>typeof p=="string"&&p.trim()&&typeof f=="string")):{},a=Ae(t,n,"claude_command"),s=Array.isArray(a)?a.filter(p=>typeof p=="string"):[],c=Ae(t,n,"codex_command"),l=Array.isArray(c)?c.filter(p=>typeof p=="string"):[],d=Ae(t,n,"observer_auth_command"),u=Array.isArray(d)?d.filter(p=>typeof p=="string"):[];return{claudeCommand:s.length?JSON.stringify(s,null,2):"",codexCommand:l.length?JSON.stringify(l,null,2):"",observerProvider:$e(Ae(t,n,"observer_provider")),observerModel:$e(Ae(t,n,"observer_model")),observerTierRoutingEnabled:vl(Ae(t,n,"observer_tier_routing_enabled")),observerSimpleModel:$e(Ae(t,n,"observer_simple_model")),observerSimpleTemperature:$e(Ae(t,n,"observer_simple_temperature")),observerReasoningEffort:$e(Ae(t,n,"observer_reasoning_effort")),observerReasoningSummary:$e(Ae(t,n,"observer_reasoning_summary")),observerRichModel:$e(Ae(t,n,"observer_rich_model")),observerRichTemperature:$e(Ae(t,n,"observer_rich_temperature")),observerRichReasoningEffort:$e(Ae(t,n,"observer_rich_reasoning_effort")),observerRichReasoningSummary:$e(Ae(t,n,"observer_rich_reasoning_summary")),observerRichMaxOutputTokens:$e(Ae(t,n,"observer_rich_max_output_tokens")),observerRuntime:$e(Ae(t,n,"observer_runtime"))||"api_http",observerAuthSource:$e(Ae(t,n,"observer_auth_source"))||"auto",observerAuthFile:$e(Ae(t,n,"observer_auth_file")),observerAuthCommand:u.length?JSON.stringify(u,null,2):"",observerAuthTimeoutMs:$e(Ae(t,n,"observer_auth_timeout_ms")),observerAuthCacheTtlS:$e(Ae(t,n,"observer_auth_cache_ttl_s")),observerHeaders:Object.keys(i).length?JSON.stringify(i,null,2):"",observerMaxChars:$e(Ae(t,n,"observer_max_chars")),packObservationLimit:$e(Ae(t,n,"pack_observation_limit")),packSessionLimit:$e(Ae(t,n,"pack_session_limit")),rawEventsSweeperIntervalS:$e(Ae(t,n,"raw_events_sweeper_interval_s")),syncEnabled:vl(Ae(t,n,"sync_enabled")),syncHost:$e(Ae(t,n,"sync_host")),syncPort:$e(Ae(t,n,"sync_port")),syncInterval:$e(Ae(t,n,"sync_interval_s")),syncMdns:vl(Ae(t,n,"sync_mdns")),syncCoordinatorUrl:$e(Ae(t,n,"sync_coordinator_url")),syncCoordinatorGroup:$e(Ae(t,n,"sync_coordinator_group")),syncCoordinatorTimeout:$e(Ae(t,n,"sync_coordinator_timeout_s")),syncCoordinatorPresenceTtl:$e(Ae(t,n,"sync_coordinator_presence_ttl_s"))}}function KB(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection now lives in Processing.";const n=qB(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),ct(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>Yn(t,r))?"Env override":n.source}: ${n.model}`}function zB(e){return e.observerTierRoutingEnabled?"On: codemem routes simpler batches to Luna and richer batches to Terra with medium reasoning by default. Official OpenAI and OAuth Codex consumer requests always use Responses. The observer_openai_use_responses=false compatibility setting selects chat completions only for an explicitly configured custom OpenAI-compatible base URL. Sidecar runtimes route both tiers through their local CLI.":"Off: codemem uses the base observer settings from the Connection tab for all batches. Explicit user settings always win over built-in routing defaults."}function WB(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function JB(e){return e.observerTierRoutingEnabled?"Tiered routing is enabled, so Processing controls the simple/rich models. This base model is only a fallback, and explicit settings override built-in defaults.":"Leave blank to use a recommended model for your selected mode/provider."}function YB(e){return e.observerTierRoutingEnabled?"Tiered routing is active. Use this only as a fallback while the Processing tab owns simple/rich model selection and explicit tier settings override built-in defaults.":"Default: `gpt-5.4-mini` for Direct API, `gpt-5.1-codex-mini` for Local Codex session, or `claude-4.5-haiku` for Local Claude session."}function XB(e){return!e}function QB(e,t,n){return t.has(e)||n.has(e)}function ZB(e){return`${e} is read-only in the viewer for security. Edit the config file or environment instead.`}var ve={previouslyFocused:null,baseline:{},envOverrides:{},touchedKeys:new Set,shellMounted:!1,protectedKeys:new Set,startPolling:null,refresh:null,hideTooltip:null},_r=qs({open:!1,activeTab:"observer",dirty:!1,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...jB}},showAdvanced:OB()});function Bt(){return _r.value}function Fo(e){_r.value={..._r.value,...e}}function eq(){ve.hideTooltip?.()}function di(e){Fo({renderState:{..._r.value.renderState,...e}})}function tq(e){di({values:{..._r.value.renderState.values,...e}})}function nq(e){Fo({activeTab:["observer","queue","sync"].includes(e)?e:"observer"})}function yl(e){Fo({dirty:e})}function bl(e){Fo({open:e})}function rq(e){MB(e),Fo({showAdvanced:e})}function IS(){return Bt().open}function iq(e){return QB(e,ve.protectedKeys,$B)}function kS(e={}){return HB({values:Bt().renderState.values,touchedKeys:ve.touchedKeys,baseline:ve.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors})}function aq(e){di({observerStatus:e&&typeof e=="object"?e:null})}function oq(e){if(!e||typeof e!="object")return;const t=e,n=t.defaults||{},r=t.config||{},i=t.env_overrides&&typeof t.env_overrides=="object"?t.env_overrides:{},a=Array.isArray(t.protected_keys)?t.protected_keys.filter(c=>typeof c=="string"&&c.trim().length>0):[],s=VB(t);ve.envOverrides=i,ve.protectedKeys=new Set(a),S.configDefaults=n,S.configPath=t.path||"",di({effectiveText:Object.keys(i).length>0?"Some fields are managed by environment settings.":"",overridesVisible:Object.keys(i).length>0,pathText:S.configPath?`Config path: ${S.configPath}`:"Config path: n/a",providers:FB(t.providers),statusText:"No unsaved changes",values:s}),ve.touchedKeys=new Set;try{const c=kS({allowUntouchedParseErrors:!0});ve.baseline=GB(c,r,i)}catch{ve.baseline={}}yl(!1)}async function sq(e={}){if(!Bt().open)try{const[t,n]=await Promise.all([cR(e),sR(e).catch(()=>null)]);if(e.signal?.aborted)return;oq(t),aq(n)}catch{}}function qf(e){return String(e||"").replace(/_/g," ")}function Uf(e){const t=e.filter(n=>typeof n=="string"&&n.trim());return t.length===0?"":t.length===1?t[0]:t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[t.length-1]}`}function cq(e){switch(e){case"anthropic_consumer":return"OAuth (Claude Max/Pro)";case"codex_consumer":return"OAuth (ChatGPT subscription)";case"sdk_client":return"API key";case"claude_sidecar":return"Local Claude session";case"codex_sidecar":return"Local Codex session";case"opencode_run":return"OpenCode sidecar";default:return e||"none"}}function lq(e){const t=[];return e.oauth&&t.push("OAuth"),e.api_key&&t.push("API key"),e.env_var&&t.push("env var"),t.length?t.join(", "):"none"}function dq(e){if(typeof e!="string"||!e.trim())return"Unknown time";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function uq({onOpenDiagnostics:e}){return e?o("button",{className:"settings-button",onClick:()=>e({severity:"error",subsystem:"observer"}),type:"button",children:"View observer diagnostics"}):null}function pq({status:e,onOpenDiagnostics:t}){if(!e)return o("div",{id:"observerStatusBanner",className:"observer-status-banner",hidden:!0});const n=e.active,r=e.available_credentials||{},i=e.latest_failure,a=Object.entries(r).filter(([,s])=>s&&typeof s=="object");return o("div",{id:"observerStatusBanner",className:"observer-status-banner",children:[n?o(z,{children:[o("div",{className:"status-label",children:"Active observer"}),o("div",{className:"status-active",children:[String(n.provider||"unknown")," → ",String(n.model||"")," via"," ",cq(n.auth?.method||"none")," ",o("span",{"aria-label":n.auth?.token_present===!0?"token present":"token missing",className:n.auth?.token_present===!0?"cred-ok":"cred-none",role:"img",children:o("i",{"aria-hidden":"true","data-lucide":n.auth?.token_present===!0?"check":"x"})})]})]}):o(z,{children:[o("div",{className:"status-label",children:"Observer status"}),o("div",{className:"status-active",children:"Not yet initialized (waiting for first session)"})]}),a.length?o(z,{children:[o("div",{className:"status-label",children:"Available credentials"}),o("div",{children:a.map(([s,c],l)=>{const d=c,u=Object.values(d).some(Boolean);return o("span",{className:"status-cred",children:[l>0?" · ":null,o("span",{"aria-label":u?"credential available":"no credential",className:u?"cred-ok":"cred-none",role:"img",children:u?o("i",{"aria-hidden":"true","data-lucide":"check"}):"–"})," ",String(s),": ",lq(d)]},s)})})]}):null,i&&typeof i=="object"?o(z,{children:[o("div",{className:"status-label",children:"Latest processing issue"}),o("div",{className:"status-issue",children:[o("div",{className:"status-issue-message",children:typeof i.error_message=="string"&&i.error_message.trim()?i.error_message.trim():"Raw-event processing failed."}),o("div",{className:"status-issue-meta",children:[[typeof i.observer_provider=="string"?i.observer_provider.trim():"",typeof i.observer_model=="string"&&i.observer_model.trim()?`→ ${i.observer_model.trim()}`:"",typeof i.observer_runtime=="string"&&i.observer_runtime.trim()?`(${i.observer_runtime.trim()})`:""].filter(Boolean).join(" ").replace(/\s+/g," ").trim(),`Last failure ${dq(i.updated_at)}`,typeof i.attempt_count=="number"&&Number.isFinite(i.attempt_count)?`Attempts ${i.attempt_count}`:""].filter(Boolean).join(" · ")}),typeof i.impact=="string"&&i.impact.trim()?o("div",{className:"status-issue-impact",children:i.impact.trim()}):null,o(uq,{onOpenDiagnostics:t})]})]}):null]})}function TS(e,t){const n=t.getBoundingClientRect(),r=8,i=8,a=e.offsetWidth,s=e.offsetHeight;let c=n.left+n.width/2-a/2;c=Math.max(r,Math.min(c,globalThis.innerWidth-a-r));let l=n.bottom+i;l+s>globalThis.innerHeight-r&&(l=n.top-s-i),l=Math.max(r,l),e.style.left=`${Math.round(c)}px`,e.style.top=`${Math.round(l)}px`}function Bo(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function fq(e){if(!e)return[];const t=["button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[href]",'[tabindex]:not([tabindex="-1"])'].join(",");return Array.from(e.querySelectorAll(t)).filter(n=>{const r=n;return!r.hidden&&r.offsetParent!==null})}function mq(){const e=Qe("settingsModal");(fq(e)[0]||e)?.focus()}function hq(){const[e,t]=D({anchor:null,content:"",visible:!1}),n=B(null);return V(()=>{const r=u=>{const p=u.dataset.tooltip?.trim();p&&t({anchor:u,content:p,visible:!0})},i=()=>{t(u=>!u.visible&&!u.anchor&&!u.content?u:{anchor:null,content:"",visible:!1})},a=u=>{const p=Bo(u.target);p&&r(p)},s=u=>{const p=Bo(u.target);if(!p)return;const f=u.relatedTarget;f instanceof Element&&p.contains(f)||i()},c=u=>{const p=Bo(u.target);p&&r(p)},l=u=>{Bo(u.target)&&i()},d=u=>{const p=Bo(u.target);p&&(u.preventDefault(),t(f=>{if(f.anchor===p&&f.visible)return{anchor:null,content:"",visible:!1};const m=p.dataset.tooltip?.trim()||"";return m?{anchor:p,content:m,visible:!0}:f}))};return document.addEventListener("pointerover",a),document.addEventListener("pointerout",s),document.addEventListener("focusin",c),document.addEventListener("focusout",l),document.addEventListener("click",d),()=>{document.removeEventListener("pointerover",a),document.removeEventListener("pointerout",s),document.removeEventListener("focusin",c),document.removeEventListener("focusout",l),document.removeEventListener("click",d)}},[]),Tt(()=>{if(!e.visible||!e.anchor||!n.current)return;const r=requestAnimationFrame(()=>{n.current&&e.anchor&&TS(n.current,e.anchor)});return()=>{cancelAnimationFrame(r)}},[e.anchor,e.content,e.visible]),V(()=>{if(!e.visible||!e.anchor)return;const r=()=>{n.current&&e.anchor&&TS(n.current,e.anchor)};return globalThis.addEventListener("resize",r),document.addEventListener("scroll",r,!0),()=>{globalThis.removeEventListener("resize",r),document.removeEventListener("scroll",r,!0)}},[e.anchor,e.visible]),{tooltipPortal:Ie(()=>typeof document>"u"?null:ln(o("div",{className:`help-tooltip${e.visible?" visible":""}`,hidden:!e.visible,ref:n,children:e.content}),document.body),[e.content,e.visible]),setTooltip:t}}function gq({DialogContent:e,onClose:t}){const{open:n}=_r.value,{tooltipPortal:r,setTooltip:i}=hq();V(()=>{const s=()=>i({anchor:null,content:"",visible:!1});return ve.hideTooltip=s,()=>{ve.hideTooltip===s&&(ve.hideTooltip=null)}},[]),V(()=>{n&&globalThis.lucide?.createIcons?.()},[n]);const a=oe(()=>{ve.startPolling&&ve.refresh&&t(ve.startPolling,ve.refresh)},[t]);return o(z,{children:[o(Ln,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:s=>{s.preventDefault()},onOpenAutoFocus:s=>{s.preventDefault(),mq()},onOpenChange:s=>{if(s){bl(!0);return}a()},open:n,overlayClassName:"modal-backdrop",overlayId:"settingsBackdrop",children:o(e,{})}),r]})}function ze({children:e,className:t="field",hidden:n=!1,id:r}){return o("div",{className:t,hidden:n,id:r,children:e})}function qo({children:e,hidden:t=!1}){return o("div",{className:"settings-note",hidden:t,children:e})}function Gf({detail:e,title:t}){return o("div",{className:"settings-section-intro",children:[o("div",{className:"settings-section-intro-title",children:t}),o("div",{className:"small settings-section-intro-detail",children:e})]})}function vq({values:e,observerMaxCharsDefault:t,providerOptions:n,showAuthFile:r,showAuthCommand:i,hiddenUnlessAdvanced:a,onTextInput:s,onSelectValueChange:c,getObserverModelLabel:l,getObserverModelTooltip:d,getObserverModelDescription:u,getObserverModelHint:p,protectedConfigHelp:f,observerStatusBannerSlot:m}){return o(z,{children:[o(Gf,{detail:"Set how codemem reaches your model provider and where it should look for credentials.",title:"Connection and credentials"}),m,o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Connection"}),o(ze,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerProvider",children:"Model provider"}),o("button",{"aria-label":"About model provider",className:"help-icon","data-tooltip":"Choose where model requests are sent. Use auto for recommended defaults.",type:"button",children:"?"})]}),o(dr,{ariaLabel:"Model provider",contentClassName:"settings-select-content",id:"observerProvider",itemClassName:"settings-select-item",onValueChange:c("observerProvider"),options:[{label:"auto (default)",value:""},...n],placeholder:"auto (default)",triggerClassName:"settings-select-trigger",value:e.observerProvider,viewportClassName:"settings-select-viewport"}),o("div",{className:"small",children:"Use `auto` unless you need to pin a specific provider."})]}),o(ze,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerModel",children:l()}),o("button",{"aria-label":"About model defaults",className:"help-icon","data-tooltip":d(),type:"button",children:"?"})]}),o(ke,{id:"observerModel",onInput:s("observerModel"),placeholder:"leave empty for default",value:e.observerModel}),o("div",{className:"small",children:u()}),o("div",{className:"small",id:"observerModelHint",children:p()})]}),o(ze,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerRuntime",children:"Connection mode"}),o("button",{"aria-label":"About connection mode",className:"help-icon","data-tooltip":"Direct API uses provider credentials. Local sessions use the selected Claude or Codex CLI login.",type:"button",children:"?"})]}),o(dr,{ariaLabel:"Connection mode",contentClassName:"settings-select-content",id:"observerRuntime",itemClassName:"settings-select-item",onValueChange:c("observerRuntime"),options:[{label:"Direct API (default)",value:"api_http"},{label:"Local Claude session",value:"claude_sidecar"},{label:"Local Codex session",value:"codex_sidecar"}],triggerClassName:"settings-select-trigger",value:e.observerRuntime,viewportClassName:"settings-select-viewport"}),o("div",{className:"small",children:"Switch between provider API credentials and local Claude or Codex CLI auth."})]}),o(ze,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"codexCommand",children:"Codex command (JSON argv)"}),o(Qi,{disabled:!0,id:"codexCommand",placeholder:'["codex"]',rows:2,value:e.codexCommand}),o("div",{className:"small",children:f("codex_command")})]}),o(ze,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"claudeCommand",children:"Claude command (JSON argv)"}),o(Qi,{disabled:!0,id:"claudeCommand",placeholder:'["claude"]',rows:2,value:e.claudeCommand}),o("div",{className:"small",children:f("claude_command")})]}),o(ze,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"observerMaxChars",children:"Request size limit (chars)"}),o(ke,{id:"observerMaxChars",min:"1",onInput:s("observerMaxChars"),type:"number",value:e.observerMaxChars}),o("div",{className:"small",id:"observerMaxCharsHint",children:t?`Default: ${t}`:""})]})]}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Authentication"}),o(ze,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerAuthSource",children:"Authentication method"}),o("button",{"aria-label":"About authentication method",className:"help-icon","data-tooltip":"Choose how credentials are resolved: environment, file, command, or none.",type:"button",children:"?"})]}),o(dr,{ariaLabel:"Authentication method",contentClassName:"settings-select-content",id:"observerAuthSource",itemClassName:"settings-select-item",onValueChange:c("observerAuthSource"),options:[{label:"auto (default)",value:"auto"},{label:"env",value:"env"},{label:"file",value:"file"},{label:"command",value:"command"},{label:"none",value:"none"}],triggerClassName:"settings-select-trigger",value:e.observerAuthSource,viewportClassName:"settings-select-viewport"}),o("div",{className:"small",children:"Use `auto` unless you need to force a file or command-based token source."})]}),o(ze,{hidden:!r,id:"observerAuthFileField",children:[o("label",{htmlFor:"observerAuthFile",children:"Token file path"}),o(ke,{disabled:!0,id:"observerAuthFile",placeholder:"~/.codemem/work-token.txt",value:e.observerAuthFile}),o("div",{className:"small",children:f("observer_auth_file")})]}),o(ze,{hidden:!i,id:"observerAuthCommandField",children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerAuthCommand",children:"Token command"}),o("button",{"aria-label":"About token command",className:"help-icon","data-tooltip":"Runs this command and uses stdout as the token. JSON argv only, no shell parsing.",type:"button",children:"?"})]}),o(Qi,{disabled:!0,id:"observerAuthCommand",placeholder:'["iap-auth", "--audience", "gateway"]',rows:3,value:e.observerAuthCommand}),o("div",{className:"small",children:f("observer_auth_command")})]}),o("div",{className:"small",hidden:!i,id:"observerAuthCommandNote",children:'Command format: JSON string array, e.g. `["iap-auth", "--audience", "gateway"]`.'}),o(qo,{hidden:a(),children:"These advanced credential overrides only matter when you need custom command timing, cached tokens, or extra request headers."}),o(ze,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"observerAuthTimeoutMs",children:"Token command timeout (ms)"}),o(ke,{id:"observerAuthTimeoutMs",min:"1",onInput:s("observerAuthTimeoutMs"),type:"number",value:e.observerAuthTimeoutMs})]}),o(ze,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"observerAuthCacheTtlS",children:"Token cache time (s)"}),o(ke,{id:"observerAuthCacheTtlS",min:"0",onInput:s("observerAuthCacheTtlS"),type:"number",value:e.observerAuthCacheTtlS})]}),o(ze,{className:"field settings-advanced",hidden:a(),children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerHeaders",children:"Request headers (JSON)"}),o("button",{"aria-label":"About request headers",className:"help-icon","data-tooltip":"Optional extra headers. Supports templates like ${auth.token}, ${auth.type}, ${auth.source}.",type:"button",children:"?"})]}),o(Qi,{disabled:!0,id:"observerHeaders",placeholder:'{"Authorization":"Bearer ${auth.token}"}',rows:4,value:e.observerHeaders}),o("div",{className:"small",children:f("observer_headers")})]})]})]})}function _l({checked:e,className:t,disabled:n=!1,hidden:r=!1,id:i,label:a,onCheckedChange:s}){const c=`${i}Label`;return o("div",{className:t?`field-checkbox settings-switch-row ${t}`:"field-checkbox settings-switch-row",hidden:r,children:[o("label",{className:"settings-switch-copy",htmlFor:i,id:c,children:a}),o(Ji,{"aria-labelledby":c,checked:e,className:"settings-switch",disabled:n,id:i,onCheckedChange:s,thumbClassName:"settings-switch-thumb"})]})}function yq({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r,onSwitchInput:i,getTieredRoutingHelperText:a}){return o(z,{children:[o(Gf,{detail:"Control how often codemem processes queued work and, if needed, how it routes lighter vs richer model requests.",title:"Processing and routing"}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Processing"}),o(ze,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"rawEventsSweeperIntervalS",children:"Background processing interval (seconds)"}),o("button",{"aria-label":"About background processing interval",className:"help-icon","data-tooltip":"How often codemem checks for queued events to process in the background.",type:"button",children:"?"})]}),o(ke,{id:"rawEventsSweeperIntervalS",min:"1",onInput:r("rawEventsSweeperIntervalS"),type:"number",value:e.rawEventsSweeperIntervalS}),o("div",{className:"small",children:"How often codemem checks for queued raw events in the background."})]})]}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Tiered observer routing"}),o(_l,{checked:e.observerTierRoutingEnabled,className:"field",id:"observerTierRoutingEnabled",label:"Enable tiered routing",onCheckedChange:i("observerTierRoutingEnabled")}),o("div",{className:"small",children:a()}),o(qo,{hidden:!t||n(),children:"These advanced routing values are only useful when you are tuning model cost, latency, or output quality for a known workload. If a selected path cannot honor the requested tier settings, codemem falls back visibly instead of silently pretending it worked."}),o("div",{hidden:!t,children:[o("h4",{children:"Simple tier"}),o(ze,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerSimpleModel",children:"Model"}),o("button",{"aria-label":"About simple tier model",className:"help-icon","data-tooltip":"Used for lighter replay batches. Leave blank to keep codemem's routing defaults. Explicit simple-tier values override the built-in defaults.",type:"button",children:"?"})]}),o(ke,{id:"observerSimpleModel",onInput:r("observerSimpleModel"),placeholder:"leave empty for default",value:e.observerSimpleModel}),o("div",{className:"small",children:"Used when a batch falls below rich-routing thresholds."})]}),o(ze,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerSimpleTemperature",children:"Temperature"}),o(ke,{id:"observerSimpleTemperature",min:"0",onInput:r("observerSimpleTemperature"),step:"0.1",type:"number",value:e.observerSimpleTemperature})]})]}),o("div",{className:"settings-advanced",hidden:!t||n(),children:[o("h4",{children:"Shared reasoning defaults"}),o("div",{className:"small",children:"Applied to OpenAI Responses requests in both tiers unless a rich-tier override is set."}),o(ze,{className:"field settings-advanced",children:[o("label",{htmlFor:"observerReasoningEffort",children:"Reasoning effort"}),o(ke,{id:"observerReasoningEffort",onInput:r("observerReasoningEffort"),placeholder:"leave empty for provider default",value:e.observerReasoningEffort})]}),o(ze,{className:"field settings-advanced",children:[o("label",{htmlFor:"observerReasoningSummary",children:"Reasoning summary"}),o(ke,{id:"observerReasoningSummary",onInput:r("observerReasoningSummary"),placeholder:"leave empty for provider default",value:e.observerReasoningSummary})]})]}),o("div",{hidden:!t,children:[o("h4",{children:"Rich tier"}),o(ze,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerRichModel",children:"Model"}),o("button",{"aria-label":"About rich tier model",className:"help-icon","data-tooltip":"Used for larger or more complex replay batches. Leave blank to keep codemem's rich-tier defaults. Explicit rich-tier values override the built-in defaults.",type:"button",children:"?"})]}),o(ke,{id:"observerRichModel",onInput:r("observerRichModel"),placeholder:"leave empty for default",value:e.observerRichModel}),o("div",{className:"small",children:"Used when routing detects a richer replay batch."})]}),o(ze,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichTemperature",children:"Temperature"}),o(ke,{id:"observerRichTemperature",min:"0",onInput:r("observerRichTemperature"),step:"0.1",type:"number",value:e.observerRichTemperature})]}),o(ze,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichReasoningEffort",children:"Reasoning effort override"}),o(ke,{id:"observerRichReasoningEffort",onInput:r("observerRichReasoningEffort"),placeholder:"inherits shared reasoning effort",value:e.observerRichReasoningEffort})]}),o(ze,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichReasoningSummary",children:"Reasoning summary override"}),o(ke,{id:"observerRichReasoningSummary",onInput:r("observerRichReasoningSummary"),placeholder:"inherits shared reasoning summary",value:e.observerRichReasoningSummary})]}),o(ze,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichMaxOutputTokens",children:"Max output tokens"}),o(ke,{id:"observerRichMaxOutputTokens",min:"1",onInput:r("observerRichMaxOutputTokens"),step:"1",type:"number",value:e.observerRichMaxOutputTokens})]})]})]}),o("div",{className:"settings-group settings-advanced",hidden:n(),children:[o("h3",{className:"settings-group-title",children:"Pack limits"}),o(qo,{hidden:n(),children:"Most users can keep these defaults. Change them only when you need smaller or larger default context packs."}),o(ze,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"packObservationLimit",children:"Observation limit"}),o(ke,{id:"packObservationLimit",min:"1",onInput:r("packObservationLimit"),type:"number",value:e.packObservationLimit}),o("div",{className:"small",children:"Default number of observations to include in a pack."})]}),o(ze,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"packSessionLimit",children:"Session summary limit"}),o(ke,{id:"packSessionLimit",min:"1",onInput:r("packSessionLimit"),type:"number",value:e.packSessionLimit}),o("div",{className:"small",children:"Default number of session summaries to include in a pack."})]})]})]})}function bq({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return o(z,{children:[o(Gf,{detail:"Choose whether this device syncs at all, how often it checks peers, and which coordinator group it should join.",title:"Device sync"}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Device Sync"}),o(_l,{checked:e.syncEnabled,className:"field",id:"syncEnabled",label:"Enable sync",onCheckedChange:r("syncEnabled")}),o("div",{className:"field",children:[o("label",{htmlFor:"syncInterval",children:"Sync interval (seconds)"}),o(ke,{id:"syncInterval",min:"10",onInput:n("syncInterval"),type:"number",value:e.syncInterval}),o("div",{className:"small",children:"How often this device checks for sync work when sync is enabled."})]}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncHost",children:"Sync host"}),o(ke,{id:"syncHost",onInput:n("syncHost"),placeholder:"127.0.0.1",value:e.syncHost})]}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncPort",children:"Sync port"}),o(ke,{id:"syncPort",min:"1",onInput:n("syncPort"),type:"number",value:e.syncPort})]}),o(_l,{checked:e.syncMdns,className:"field settings-advanced",hidden:t(),id:"syncMdns",label:"Enable mDNS discovery",onCheckedChange:r("syncMdns")}),o("div",{className:"field",children:[o("label",{htmlFor:"syncCoordinatorUrl",children:"Coordinator URL"}),o(ke,{disabled:!0,id:"syncCoordinatorUrl",placeholder:"https://coord.example.com",value:e.syncCoordinatorUrl}),o("div",{className:"small",children:i("sync_coordinator_url")})]}),o("div",{className:"field",children:[o("label",{htmlFor:"syncCoordinatorGroup",children:"Coordinator group"}),o(ke,{id:"syncCoordinatorGroup",onInput:n("syncCoordinatorGroup"),placeholder:"team-alpha",value:e.syncCoordinatorGroup}),o("div",{className:"small",children:"Discovery namespace for peers using the same coordinator."})]}),o("div",{className:"field settings-advanced",hidden:t(),children:o(qo,{hidden:t(),children:"These network overrides are for unusual local-network setups. Leave them alone unless you know this device needs non-default sync discovery or coordinator timing."})}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncCoordinatorTimeout",children:"Coordinator timeout (seconds)"}),o(ke,{id:"syncCoordinatorTimeout",min:"1",onInput:n("syncCoordinatorTimeout"),type:"number",value:e.syncCoordinatorTimeout})]}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncCoordinatorPresenceTtl",children:"Presence TTL (seconds)"}),o(ke,{id:"syncCoordinatorPresenceTtl",min:"1",onInput:n("syncCoordinatorPresenceTtl"),type:"number",value:e.syncCoordinatorPresenceTtl})]})]})]})}function _q({panelProps:e,activeTab:t,showAdvanced:n,renderState:r,settingsDirty:i,onClose:a,onSave:s,onActiveTabChange:c,onAdvancedToggle:l,observerStatusBannerSlot:d}){const u=!i||r.isSaving;return o("div",{className:"modal-card",onKeyDown:p=>ro(p,{onSubmit:s,disabled:u}),children:[o("div",{className:"modal-header",children:[o("h2",{id:"settingsTitle",children:"Settings"}),o(Lr,{ariaLabel:"Close settings",className:"modal-close-button",onClick:a})]}),o("div",{className:"modal-body",children:[o("div",{className:"small",id:"settingsDescription",children:"Tune how codemem connects, processes work, and syncs with other devices."}),o("div",{className:"settings-advanced-toolbar",children:[o(_l,{checked:n,id:"settingsAdvancedToggle",label:"Show advanced controls",onCheckedChange:l}),o("button",{"aria-label":"About advanced controls",className:"help-icon","data-tooltip":"Advanced controls include JSON fields, tuning values, and network overrides.",type:"button",children:o("i",{"aria-hidden":"true","data-lucide":"help-circle"})})]}),o(qo,{hidden:!n,children:"Advanced controls are visible. Leave JSON fields, tuning values, and network overrides alone unless you are debugging or matching a known deployment setup."}),o(My,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:c,tabs:DB,triggerClassName:"settings-tab",value:t,children:[o(Gr,{className:"settings-panel",forceMount:!0,value:"observer",children:o(vq,{...e,observerStatusBannerSlot:d})}),o(Gr,{className:"settings-panel",forceMount:!0,value:"queue",children:o(yq,{...e})}),o(Gr,{className:"settings-panel",forceMount:!0,value:"sync",children:o(bq,{...e})})]}),o("div",{className:"small mono",id:"settingsPath",children:r.pathText}),o("div",{className:"small",id:"settingsEffective",children:r.effectiveText}),o("div",{className:"settings-note",hidden:!r.overridesVisible,id:"settingsOverrides",children:"Some values are controlled outside this screen and take priority."}),o("div",{className:"settings-note",hidden:n,children:"Advanced controls are hidden right now to keep this screen focused on everyday settings."})]}),o("div",{className:"modal-footer",children:[o("div",{className:"small",id:"settingsStatus",children:r.statusText}),o("button",{className:"settings-save","data-primary-action":"true",disabled:u,id:"settingsSave",onClick:s,type:"button",children:r.isSaving?"Saving…":"Save changes"})]})]})}function wq(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:a}=e,s={};return Object.entries(t).forEach(([c,l])=>{a(c)||Yn(r,c)&&!i.has(c)||BB(l,n[c])||(s[c]=l)}),s}function Sq(e){const t=s=>{const c=LB[s];c&&e.getTouchedKeys().add(c)},n=(s,c)=>{t(s),e.updateFormState({[s]:c}),e.setDirty(!0)};return{markFieldTouched:t,updateField:n,onTextInput:s=>c=>{n(s,c.currentTarget.value)},onSelectValueChange:s=>c=>{n(s,c)},onSwitchInput:s=>c=>{n(s,c)}}}function Cq(e){const t=e?.effects,n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},r=Array.isArray(n.hot_reloaded_keys)?n.hot_reloaded_keys.map(p=>qf(String(p))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(p=>qf(String(p))):[],a=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(p=>qf(String(p))):[],s=Array.isArray(n.warnings)?n.warnings.filter(p=>typeof p=="string"&&p.trim().length>0):[],c=Array.isArray(n.manual_actions)?n.manual_actions:[],l=n.sync&&typeof n.sync=="object"?n.sync:{},d=[];r.length&&d.push(`Applied now: ${Uf(r)}.`),i.length&&d.push(`Live settings updated: ${Uf(i)}.`),l.attempted&&typeof l.message=="string"&&l.message?d.push(`Sync: ${l.message}.`):Array.isArray(l.affected_keys)&&l.affected_keys.length&&typeof l.reason=="string"&&l.reason&&d.push(`Sync: ${l.reason}.`),a.length&&d.push(`Restart required for ${Uf(a)}. Run: codemem serve restart`),s.forEach(p=>{d.push(p)}),c.forEach(p=>{p&&typeof p.command=="string"&&p.command.trim()&&d.push(`If needed: ${p.command}.`)}),d.length||d.push("Saved.");const u=a.length>0||s.length>0||l.ok===!1;return{message:d.join(" "),type:u?"warning":"success"}}var Rq=()=>KB(Bt().renderState.values,ve.envOverrides),Iq=()=>zB(Bt().renderState.values),kq=()=>WB(Bt().renderState.values),Tq=()=>JB(Bt().renderState.values),Pq=()=>YB(Bt().renderState.values),Nq=()=>XB(Bt().showAdvanced),{onTextInput:Eq,onSelectValueChange:Aq,onSwitchInput:xq}=Sq({getTouchedKeys:()=>ve.touchedKeys,getValues:()=>Bt().renderState.values,updateFormState:tq,setDirty:e=>yl(e)});function Dq(){const e=_r.value.renderState.observerStatus;return o(pq,{status:e,onOpenDiagnostics:Lq})}function Lq(e){if(!ve.startPolling||!ve.refresh||(Uo(ve.startPolling,ve.refresh),Bt().open))return;const t=Js("settingsButton");queueMicrotask(()=>Fr({...e,trigger:t}))}function $q(){const e=_r.value,t=e.renderState.values,n=String(S.configDefaults?.observer_max_chars||""),r=t.observerAuthSource==="file",i=t.observerAuthSource==="command",a=t.observerTierRoutingEnabled,s={values:t,observerMaxCharsDefault:n,providerOptions:Array.from(new Set(e.renderState.providers.concat(t.observerProvider?[t.observerProvider]:[]))).sort((c,l)=>c.localeCompare(l)).map(c=>({label:c,value:c})),showAuthFile:r,showAuthCommand:i,showTieredRouting:a,hiddenUnlessAdvanced:Nq,onTextInput:Eq,onSelectValueChange:Aq,onSwitchInput:xq,getObserverModelLabel:kq,getObserverModelTooltip:Tq,getObserverModelDescription:Pq,getObserverModelHint:Rq,getTieredRoutingHelperText:Iq,protectedConfigHelp:ZB};return o(_q,{panelProps:s,activeTab:e.activeTab,showAdvanced:e.showAdvanced,renderState:e.renderState,settingsDirty:e.dirty,onClose:()=>{ve.startPolling&&ve.refresh&&Uo(ve.startPolling,ve.refresh)},onSave:()=>{ve.startPolling&&ve.refresh&&Fq(ve.startPolling,ve.refresh)},onActiveTabChange:nq,onAdvancedToggle:rq,observerStatusBannerSlot:o(Dq,{})})}function jq(){return o(gq,{DialogContent:$q,onClose:Uo})}function Oq(){const e=Qe("settingsDialogMount");e&&Ue(o(jq,{}),e)}function PS(){Qe("settingsDialogMount")&&(ve.shellMounted||(Oq(),ve.shellMounted=!0))}function Mq(e){ve.shellMounted||PS(),bl(!0),ve.previouslyFocused=document.activeElement,e()}function Uo(e,t){if(Bt().dirty&&!globalThis.confirm("Discard unsaved changes?")){bl(!0);return}bl(!1),eq(),(ve.previouslyFocused&&typeof ve.previouslyFocused.focus=="function"?ve.previouslyFocused:Js("settingsButton"))?.focus(),ve.previouslyFocused=null,ve.touchedKeys=new Set,e(),t()}async function Fq(e,t){if(!Bt().renderState.isSaving){di({isSaving:!0,statusText:"Saving changes…"});try{const n=kS({allowUntouchedParseErrors:!0}),r=wq({current:n,baseline:ve.baseline,envOverrides:ve.envOverrides,touchedKeys:ve.touchedKeys,isProtected:iq});if(Object.keys(r).length===0){di({isSaving:!1,statusText:"No unsaved changes"}),yl(!1),Uo(e,t);return}const i=await lR(r),a=Cq(i);di({isSaving:!1,statusText:"Saved changes"}),yl(!1),Uo(e,t),X(a.message,a.type)}catch(n){const r=n instanceof Error?n.message:"unknown error";di({isSaving:!1,statusText:`Save failed: ${r}`})}}}function Bq(e,t,n){ve.startPolling=t,ve.refresh=n,PS(),Js("settingsButton")?.addEventListener("click",()=>Mq(e))}function qq(e){e.dataset.syncRenderRoot="preact"}function Uq(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function mt(e,t){qq(e),Ue(t,e)}function da(e){e.dataset.syncRenderRoot==="preact"&&Ue(null,e)}function Gq(e){const t=Object.values(e||{}).map(n=>!n||typeof n!="object"?"":String(n.last_ping_at||"").trim()).filter(Boolean).sort();return t[t.length-1]??null}function Hq(e){return typeof e=="object"&&e!==null}function Vq(e,t){return S.pairingCommandRaw="",{payloadText:e,hintText:t}}function Kq(e){if(!Hq(e))return Vq("Pairing not available","Enable sync and retry.");const t=e,n={...t,addresses:Array.isArray(t.addresses)?t.addresses:[]},r=JSON.stringify(n),i=`echo '${btoa(r)}' | base64 -d | codemem sync pair --accept-file -`;return S.pairingCommandRaw=i,{payloadText:i,hintText:"Copy this command and run it on the other device. Use --include/--exclude to control which projects sync."}}function zq(){return{title:"Diagnostics still loading.",detail:"Wait a moment for local sync status. If it stays blank, refresh the page or check whether sync is enabled on this device."}}function Wq(){return{title:"Diagnostics unavailable right now.",detail:"The viewer could not load sync status. Refresh this page, or check that the local codemem sync service is reachable before retrying."}}function Jq(){const e=S.lastSyncStatus;return{title:"No recent sync attempts yet.",detail:e?.daemon_state==="disabled"||e?.enabled===!1?"Turn on sync in Settings → Device Sync first. Recent attempts will appear here after this device can actually run sync work.":"Trigger a sync pass or pair another device to generate activity here when you need low-level troubleshooting."}}function Yq(){return{title:"Recent attempts unavailable right now.",detail:"Attempt history could not be loaded because sync diagnostics failed. Refresh the page after local sync status is reachable again."}}function Xq(e,t){return e==="offline-peers"&&t?"Some recent failures may have happened before all peers went offline. Sync will resume automatically when a peer becomes reachable.":""}function Qq({items:e}){return o(z,{children:e.map((t,n)=>o("div",{class:"stat",children:o("div",{class:"stat-content",children:[o("div",{class:"value",children:t.value}),o("div",{class:"label",children:t.label})]})},`${t.label}-${n}`))})}function Zq({attempts:e,note:t}){return o(z,{children:[t?o("div",{class:"small",children:t}):null,e.map((n,r)=>o("div",{class:"diag-line",children:[o("div",{class:"left",children:[o("div",{children:[n.peerLabel," — ",n.status]}),n.detail?o("div",{class:"small",children:n.detail}):null,n.actionHref&&n.actionLabel?o("a",{class:"small",href:n.actionHref,children:n.actionLabel}):null,n.action?o("button",{className:"settings-button small",onClick:i=>n.action?.(i.currentTarget),type:"button",children:"View sync diagnostics"}):null]}),o("div",{class:"right",children:n.startedAt})]},`${n.startedAt}-${n.peerLabel}-${r}`))]})}function NS({text:e}){return o(z,{children:e})}function eU({title:e,detail:t}){return o("div",{class:"sync-empty-state",children:[o("strong",{children:e}),o("span",{children:t})]})}function tU(e,t){if(!t.length){da(e);return}mt(e,o(Qq,{items:t}))}function nU(e,t,n){if(!t.length){da(e);return}mt(e,o(Zq,{attempts:t,note:n}))}function ui(e,t){mt(e,o(eU,{...t}))}function ES(e,t,n){mt(e,o(NS,{text:n.payloadText})),t&&mt(t,o(NS,{text:n.hintText}))}function AS({open:e,onOpenChange:t,triggerId:n,triggerClassName:r,closedLabel:i,openLabel:a,contentId:s,contentClassName:c,contentHost:l=null,children:d}){const u=B(null),p=B(null),f=B(!1);Tt(()=>{u.current&&(u.current.id=n,u.current.setAttribute("aria-controls",s)),p.current&&(p.current.id=s)},[s,n,e]),V(()=>{if(!e){f.current=!1;return}f.current||(f.current=!0,queueMicrotask(()=>{p.current?.querySelector('button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')?.focus()}))},[e]);const m=o(Xa,{forceMount:!0,asChild:!0,children:o("div",{ref:p,id:s,className:c,hidden:!e,children:d})});return o(Ya,{open:e,onOpenChange:t,children:[o(zu,{asChild:!0,children:o("button",{ref:u,type:"button",className:r,id:n,"aria-controls":s,children:e?a:i})}),l?ln(m,l):m]})}function rU({open:e,onOpenChange:t}){return o(AS,{open:e,onOpenChange:t,triggerId:"syncToggleAdmin",triggerClassName:"sync-toggle-admin",closedLabel:"Set up a new team instead…",openLabel:"Hide team setup",contentId:"syncInvitePanel",children:[o("h3",{className:"settings-group-title",style:{marginTop:"12px"},children:"Create a team"}),o("div",{className:"section-meta",children:"Generate an invite to share with teammates."}),o("div",{className:"actor-create-row",children:[o("label",{htmlFor:"syncInviteGroup",className:"sr-only",children:"Team name"}),o(ke,{className:"peer-scope-input",id:"syncInviteGroup",placeholder:"Team name (e.g. my-team)",type:"text"}),o("label",{htmlFor:"syncInvitePolicy",className:"sr-only",children:"Join policy"}),o("div",{className:"sync-radix-select-host sync-actor-select-host",id:"syncInvitePolicyMount"}),o("div",{className:"sync-ttl-group",children:[o("label",{htmlFor:"syncInviteTtl",children:"Expires in"}),o(ke,{className:"peer-scope-input",defaultValue:"24",id:"syncInviteTtl",min:"1",style:{width:"64px"},type:"number"}),o("span",{children:"hours"})]}),o("button",{className:"settings-button",id:"syncCreateInviteButton",type:"button",children:"Create invite"})]}),o("label",{htmlFor:"syncInviteOutput",className:"sr-only",children:"Generated invite"}),o(Qi,{className:"feed-search",id:"syncInviteOutput",placeholder:"Invite will appear here",readOnly:!0,hidden:!0}),o("div",{className:"peer-meta",id:"syncInviteAdminHint"}),o("div",{className:"peer-meta",id:"syncInviteWarnings",hidden:!0})]})}function iU({contentHost:e,open:t,onOpenChange:n}){return o(AS,{open:t,onOpenChange:n,triggerId:"syncPairingToggle",triggerClassName:"settings-button",closedLabel:"Show pairing command",openLabel:"Hide pairing command",contentId:"syncPairing",contentClassName:"pairing-card",contentHost:e,children:[o("div",{className:"peer-title",children:[o("strong",{children:"Pairing command"}),o("div",{className:"peer-actions",children:o("button",{className:"settings-button",id:"pairingCopy",type:"button",children:"Copy command"})})]}),o("div",{className:"pairing-body",children:o("pre",{id:"pairingPayload",style:{userSelect:"all"}})}),o("div",{className:"peer-meta",id:"pairingHint"})]})}function aU(e,t){mt(e,o(rU,{...t}))}function oU(e,t){mt(e,o(iU,{...t}))}function ue(e){return String(e??"").trim()}function sU(e){return ue(e).replace(/\s+/g," ").toLowerCase()}function cU(e){const t=ue(e);return t?t.slice(0,8):"Unnamed device"}function xS(e){return ue(e?.last_error).toLowerCase()}function DS(e){return e.includes("401")&&e.includes("unauthorized")}function LS(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var lU={scope_filter:"sharing-domain membership",visibility_filter:"visibility",project_filter:"project filter"};function $S(e){return e.device?.needs_local_approval?{state:"needs-your-approval",badgeLabel:"Needs your approval",description:"Another device already approved this pairing. Approve it here to finish the connection on both sides.",actionLabel:"Approve on this device"}:e.device?.waiting_for_peer_approval?{state:"waiting-for-other-device",badgeLabel:"Waiting on other device",description:"You already approved this pairing here. The other device still needs to approve this one before sync can work both ways.",actionLabel:null}:{state:"none",badgeLabel:null,description:null,actionLabel:null}}function dU(e){const t=$S(e);return!ue(e.device?.device_id)||e.device?.stale||e.hasAmbiguousCoordinatorGroup?!1:e.pairedLocally?t.state==="needs-your-approval":!0}function jS(e){const t=Array.isArray(e?.items)?e.items:[];if(!t.length)return{ok:!0,message:"Sync pass completed with no eligible devices.",warning:!1};const n=t.filter(i=>i&&i.ok===!1),r=t.filter(i=>Math.max(0,Number(i.opsSkipped??0))>0);if(!n.length){if(r.length){const i=r.reduce((s,c)=>s+Math.max(0,Number(c.opsSkipped??0)),0),a=mU(r.map(s=>s.skipped_out??null));return{ok:!0,message:`${i.toLocaleString()} outbound op${i===1?" was":"s were"} filtered: ${a}. No payload was sent for filtered data.`,warning:!0}}return{ok:!0,message:`Sync pass finished for ${t.length} device${t.length===1?"":"s"}.`,warning:!1}}return n.filter(i=>OS(i)==="trust").length===n.length?{ok:!1,message:"This device no longer has two-way trust with the peer. Pair it again from the other device, or remove the stale local record if it should be gone.",warning:!0}:n.filter(i=>OS(i)==="scope").length===n.length?{ok:!1,message:"Sync ran, but the peer is not authorized for one or more Spaces. Review legacy Space access for this device in Coordinator Administration, then sync again.",warning:!0}:n.length<t.length?{ok:!1,message:`${n.length} of ${t.length} device sync attempts failed. Open the affected device cards for the specific errors.`,warning:!0}:{ok:!1,message:ue(n[0]?.error)||"Sync failed for at least one device.",warning:!0}}function OS(e){if(e.failureCategory)return e.failureCategory;const t=Array.isArray(e.perScopeResults)?e.perScopeResults.filter(r=>r&&r.ok===!1).map(r=>r.failureCategory).filter(r=>!!r):[];if(t.length)return new Set(t).size===1?t[0]:"other";const n=ue(e.error);return uU(n)?"trust":pU(n)?"scope":null}function uU(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function pU(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function fU(e){const t=ue(e?.reason);return lU[t]??(t.replaceAll("_"," ")||"sync filters")}function mU(e){const t=new Map;for(const n of e){const r=fU(n),i=Math.max(0,Number(n?.skipped_count??0));i!==0&&t.set(r,(t.get(r)??0)+i)}return t.size?Array.from(t.entries()).sort((n,r)=>r[1]-n[1]||n[0].localeCompare(r[0])).map(([n,r])=>`${r.toLocaleString()} by ${n}`).join(", "):"sync filters"}function MS(e){const t=ue(e.localName);if(t)return t;const n=ue(e.coordinatorName);return n||cU(ue(e.deviceId))}function hU(e){const t=ue(e.localName),n=ue(e.coordinatorName);return t||n?!1:!!ue(e.deviceId)}function gU(e){const t=Math.max(0,Number(e?.recent_ops?.in??0)),n=Math.max(0,Number(e?.recent_ops?.out??0));return t>0&&n>0?"bidirectional":n>0?"publishing":t>0?"subscribed":"none"}function Go(e){const t=ue(e?.status?.peer_state);if(t==="offline"||t==="stale")return"offline";const n=xS(e);return DS(n)?"needs-repair":LS(n)?"offline":e?.has_error||t==="degraded"?"needs-repair":t==="online"||e?.status?.fresh?"connected":"waiting"}function ua(e){const t=e?.status||{},n=ue(t.peer_state),r=xS(e),i=ue(t.sync_status)==="ok"||ue(t.ping_status)==="ok";return n==="offline"||n==="stale"?{state:"offline",badgeLabel:"Offline",description:"This device was paired before, but it is offline right now.",isWarning:!0}:DS(r)?{state:"needs-repairing",badgeLabel:"Needs re-pairing",description:"This device no longer accepts this one. Pair again from the other device, or remove this local record if it no longer belongs here.",isWarning:!0}:LS(r)?{state:"offline",badgeLabel:"Offline",description:"This device is saved here, but none of its last known addresses are responding right now.",isWarning:!0}:i||n==="online"?{state:"mutual-trust",badgeLabel:"Two-way trust",description:"Both devices trust each other and sync can run in both directions.",isWarning:!1}:e?.has_error||n==="degraded"?{state:"needs-review",badgeLabel:"Needs review",description:"This device has a sync problem that needs review before you trust the current state again.",isWarning:!0}:{state:"trusted-by-you",badgeLabel:"Waiting on other device",description:"This device is already trusted here. Finish setup on the other device before sync can run both ways.",isWarning:!1}}var vU={missing_scope:"Missing scope id",sender_not_member:"Sender not a scope member",receiver_not_member:"Receiver not a scope member",stale_epoch:"Stale or revoked membership",scope_mismatch:"Scope mismatch",visibility_filter:"Visibility filter",project_filter:"Project filter"};function yU(e){const t=e?.scope_rejections,n=Math.max(0,Number(t?.total??0));if(!t||n===0)return{total:0,badgeLabel:null,reasons:[],lastAt:null};const r=[];for(const[i,a]of Object.entries(t.by_reason??{})){const s=Math.max(0,Number(a??0));if(s===0)continue;const c=i;r.push({reason:c,label:vU[c]??i,count:s})}return r.sort((i,a)=>a.count-i.count||i.label.localeCompare(a.label)),{total:n,badgeLabel:n===1?"1 sync rejection":`${n.toLocaleString()} sync rejections`,reasons:r,lastAt:t.last_at??null}}function FS(e){return Array.isArray(e)?e.map(t=>ue(t)).filter(t=>!!t):[]}function BS(e,t){if(e.length===0)return t;const n=e.slice(0,3).join(", "),r=e.length-3;return r>0?`${n} +${r.toLocaleString()} more`:n}function wl(e,t){return e?e.replaceAll("_"," "):t}function bU(e){const t=(Array.isArray(e.authorized_scopes)?e.authorized_scopes:[]).map(r=>{const i=ue(r.scope_id),a=ue(r.label);if(!i&&!a)return null;const s=a||"Untitled Space",c=[wl(ue(r.kind),"user"),wl(ue(r.authority_type),"local"),`${wl(ue(r.role),"member")} role`].filter(Boolean).join(" · ");return{scopeId:i||s,label:s,detail:c}}).filter(r=>r!=null),n=t.length;return{total:n,badgeLabel:n===1?"1 Space":n>1?`${n} Spaces`:"No Space access",isWarning:n===0,domains:t,emptyMessage:"No Space access grants exist for this device yet. Advanced project filters cannot send data by themselves."}}function qS(e){const t=(Array.isArray(e.per_scope_sync)?e.per_scope_sync:[]).map(n=>{const r=ue(n.scope_id),i=ue(n.label);if(!r&&!i)return null;const a=i||"Untitled Space",s=ue(n.last_applied_cursor),c=ue(n.last_acked_cursor),l=n.bootstrapped===!0||s?"received":"pending",d=wl(ue(n.authority_type),"local"),u=Number(n.membership_epoch??0),p=[`Scope id: ${r||"unknown"}`,`${d} authority`,Number.isFinite(u)?`membership epoch ${u}`:null,s?`last applied ${s}`:null,c?`last acknowledged ${c}`:null].filter(f=>!!f).join(" · ");return{scopeId:r||a,label:a,status:l,badgeLabel:l==="received"?"Received":"Pending",detail:p}}).filter(n=>n!=null);return{total:t.length,rows:t,emptyMessage:"No per-Space sync progress is available yet. Run sync after both devices have Space access."}}var _U=["personal","private","home","mine","me"],wU=["oss","open source","opensource","community","public"],SU=["work","client"],CU=["local","legacy","review"];function RU(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>ue(t)??"").join(" ").toLowerCase()}function IU(e){return[e.scope_id,e.label,e.kind].map(t=>ue(t)??"").join(" ").toLowerCase()}function US(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hf(e,t){const n=RU(e);return t.some(r=>{const i=US(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function GS(e){return Hf(e,_U)||Hf(e,wU)}function kU(e){const t=IU(e);return CU.some(n=>{const r=US(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function TU(e){return!GS(e)&&(!kU(e)||Hf(e,SU))}function PU(e){const t=Array.isArray(e.authorized_scopes)?e.authorized_scopes:[];if(!(ue(e.discovered_via_group_id)||ue(e.discovered_via_coordinator_id))||t.length===0)return{badgeLabel:null,detail:"",isVisible:!1,message:"",title:""};const n=t.some(GS),r=t.some(TU);return!n||r?{badgeLabel:null,detail:"",isVisible:!1,message:"",title:""}:{badgeLabel:"Review Space fit",detail:"Team discovery helps find the device, and advanced project filters only narrow already-authorized Spaces. Neither one grants missing work/client Space access.",isVisible:!0,message:"This Team-discovered device has personal or OSS Space access, but no separate work/client-like Space access. If this device is meant for work/client sync, grant that Space explicitly before treating sync as validated.",title:"Check this device's Space access"}}function NU(e,t){const n=e.map(r=>r.trim()).filter(Boolean);return n.length>0&&!n.includes("*")||t.length>0}function EU(e){const t=FS(e?.effective_include),n=FS(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${BS(t,"all projects")}`,a=`Exclude filter: ${BS(n,"no exclusions")}`,s=NU(t,n);return{hasAdvancedFilters:s,statusLabel:s?"Advanced filters active":"No advanced filters",sourceLabel:r,includeLabel:i,excludeLabel:a,summary:`${r}. ${i}; ${a}.`,note:"Advanced filters only narrow data after Space access; they never grant access to another Space."}}function AU(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=ue(n?.display_name),i=ue(n?.actor_id),a=sU(r);if(!r||!i||!a)return;const s=t.get(a)??{displayName:r,actorIds:[],includesLocal:!1};s.actorIds=[...s.actorIds,i],s.includesLocal=s.includesLocal||!!n?.is_local,t.set(a,s)}),[...t.values()].filter(n=>n.actorIds.length>1).sort((n,r)=>n.displayName.localeCompare(r.displayName))}function HS(e){const t=Array.isArray(e.actors)?e.actors:[],n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.duplicatePeople)?e.duplicatePeople:[],i=new Map;n.forEach(s=>{const c=ue(s?.actor_id);c&&i.set(c,(i.get(c)??0)+1)});const a=new Set;return r.forEach(s=>{s.includesLocal&&s.actorIds.forEach(c=>{const l=t.find(d=>ue(d?.actor_id)===c);!l||l.is_local||(i.get(c)??0)>0||a.add(c)})}),{visibleActors:t.filter(s=>!a.has(ue(s?.actor_id))),hiddenLocalDuplicateCount:a.size}}var xU=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),DU=new Set(["pending","verifying","waiting"]);function LU(e){return(Array.isArray(e?.groups)?e.groups.map(t=>ue(t)).filter(Boolean):[]).join(", ")||"none"}function $U(e){return ue(e?.projects?.[0]?.display_name)||"the shared Project"}function jU(e,t){return t?.discovered_devices?.some(n=>n.needs_local_approval||n.waiting_for_peer_approval)?!0:e.some(n=>{const r=ua(n).state;return r==="trusted-by-you"||r==="needs-repairing"})}function OU(e,t){return t?.enabled!==!0||t.daemon_state!=="ok"||t.daemon_running===!1?!1:e.some(n=>n.status?.sync_status==="ok"&&ua(n).state==="mutual-trust"&&!qS(n).rows.some(r=>r.status==="pending"))}function MU(e){return e.some(t=>ue(t.status?.peer_state)==="online"&&ua(t).state==="mutual-trust")}function FU(e,t){return t?.daemon_state==="offline-peers"||t?.daemon_state==="stale"||t?.daemon_state==="degraded"?!0:e.some(n=>{const r=ue(n.status?.peer_state),i=ua(n).state;return n.has_error===!0&&i!=="needs-repairing"||i==="offline"||i==="needs-review"||r==="offline"||r==="stale"||r==="degraded"})}function BU(e){if(e?.daemon_running===!1)return!0;const t=e?.daemon_state;return t!==void 0&&t!=="ok"&&t!=="offline-peers"&&t!=="stale"&&t!=="degraded"}function VS(e){const t=e.coordinator,n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.shareOperations)?e.shareOperations:[],i=Array.isArray(e.reconciliation?.items)?e.reconciliation.items:[],a=LU(t);if(e.status?.enabled===!1||t?.sync_enabled===!1)return{state:"disabled",badgeLabel:"Sync off",meta:`Team: ${a}. Coordinator presence does not move Project data while sync is off.`,nextAction:"Open Settings and turn on sync before expecting Team or Project data to update."};if(e.shareOperationsLoadError)return{state:"needs-attention",badgeLabel:"Refresh needed",meta:`Team: ${a}. Device diagnostics are available, but Project sharing status could not be refreshed.`,nextAction:"Refresh Team sync to retry loading Project sharing status."};const s=r.find(p=>p.lifecycle?.state==="needs_attention"),c=i.find(p=>p.state==="needs_attention");if(s)return{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${a}. A Project access update stopped and needs a retry.`,nextAction:"Retry the stopped Project access update below."};if(c)return{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${a}. Team access needs review before it can continue.`,nextAction:"Open Sharing, review Project access, then sync again."};const l=r.find(p=>{const f=p.lifecycle?.state;return f!==void 0&&xU.has(f)}),d=i.find(p=>{const f=p.state;return f!==void 0&&DU.has(f)});if(l||d){const p=l?$U(l):"the shared Project",f=l?.lifecycle?.primary_action?.kind,m=l?.lifecycle?.state==="revoking";return{state:"pending-setup",badgeLabel:m?"Removal pending":"Setup pending",meta:m?`Team: ${a}. Future access removal for ${p} is still pending.`:`Team: ${a}. Exact-Project setup is still pending and data delivery is not confirmed.`,nextAction:m?`Keep both devices online, then sync again to finish removing future access for ${p}.`:f==="retry_setup"?`Open Project sharing below and retry setup for ${p}.`:f==="copy_invite"?`Copy the invitation for ${p} and send it to the recipient.`:`Keep both devices online, then sync again to finish setup for ${p}.`}}if(BU(e.status))return{state:"needs-attention",badgeLabel:"Sync needs attention",meta:`Team: ${a}. The local sync service is not healthy, so Project data delivery is not confirmed.`,nextAction:"Review the sync status below, restart codemem if needed, then run Sync now again."};if(jU(n,t))return{state:"trust-blocked",badgeLabel:"Pairing needed",meta:`Team: ${a}. A device still needs two-way trust before Project data can sync.`,nextAction:"Review the device below and finish pairing or approval on both devices."};const u=ue(t?.presence_status);return u==="not_enrolled"?{state:"not-enrolled",badgeLabel:"Not enrolled",meta:`Team: ${a}. This device is not enrolled with the coordinator.`,nextAction:"Paste a Team invite below, or ask a Team admin to enroll this device."}:u!=="posted"?{state:"unreachable",badgeLabel:t?.configured?"Unreachable":"Setup needed",meta:t?.configured?`Team: ${a}. The coordinator is not currently reachable and no healthy data-plane sync is confirmed.`:"Configure or join a Team before expecting Project data to sync.",nextAction:t?.configured?"Check the coordinator connection, then refresh Team sync.":"Paste a Team invite below, or set a coordinator URL in Settings → Device Sync."}:FU(n,e.status)?{state:"reachable",badgeLabel:"Check devices",meta:`Team: ${a}. The coordinator is reachable, but one or more paired devices are offline or degraded.`,nextAction:"Bring the paired devices online, check their sync errors, then run Sync now again."}:t?.sync_enabled===!0&&OU(n,e.status)?{state:"healthy",badgeLabel:"Healthy",meta:`Team: ${a}. Sync is enabled and a trusted device has a healthy data-plane connection.`,nextAction:null}:MU(n)?{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${a}. The coordinator and a paired device are reachable, but successful Project sync is not confirmed.`,nextAction:"Run Sync now, then review the device sync status below if delivery is still pending."}:{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${a}. The coordinator is reachable, but healthy Project data sync is not confirmed.`,nextAction:"Pair and approve a device, then run Sync now to confirm data delivery."}}function qU(e){return e.discovered?.stale?e.peer?Go(e.peer)!=="connected":!0:!1}function KS(e){return{id:`repair:${e.id}`,kind:"device-needs-repair",priority:10,title:e.title||`${e.name} needs attention`,summary:e.summary,actionLabel:"Open device",deviceId:e.id}}function Vf(e){return{id:`review:${e.id}:${e.key||"default"}`,kind:"review-team-device",priority:20,title:`${e.name} is available to review`,summary:e.summary,actionLabel:"Open device",deviceId:e.id}}function UU(e){return{id:`name:${e.id}`,kind:"name-device",priority:30,title:`Name ${e.name}`,summary:e.summary,actionLabel:"Go to name field",deviceId:e.id}}function GU(e){const t=ue(e?.coordinator_url),n=Array.isArray(e?.groups)?e.groups:[];return t?n.some(r=>ue(r))?e?.sync_enabled===!1?{reason:"sync_disabled",message:"Enable sync before pairing team devices."}:null:{reason:"coordinator_groups_empty",message:"Join or configure a team before pairing team devices."}:{reason:"coordinator_url_missing",message:"Configure a coordinator URL before pairing team devices."}}function HU(e,t){const n=new Map,r=i=>{const a=n.get(i)??{deviceId:i,localName:"",coordinatorName:"",peer:null,discovered:null};return n.set(i,a),a};return e.forEach(i=>{const a=ue(i?.peer_device_id);if(!a)return;const s=r(a);s.peer=i,s.localName=ue(i?.name)}),t.forEach(i=>{const a=ue(i?.device_id);if(!a)return;const s=r(a);s.discovered=i,s.coordinatorName=ue(i?.display_name)}),[...n.values()]}function VU(e){const t=Array.isArray(e.actors)?e.actors:[],n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.coordinator?.discovered_devices)?e.coordinator.discovered_devices:[],i=HU(n,r),a=e.duplicatePersonDecisions??{},s=AU(t).filter(l=>!a[[...l.actorIds].sort().join("::")]),c=[];return s.forEach(l=>{c.push({id:`duplicate:${l.actorIds.join(":")}`,kind:"possible-duplicate-person",priority:l.includesLocal?5:15,title:`Possible duplicate person: ${l.displayName}`,summary:l.includesLocal?"At least one entry is marked as you. Confirm whether these records represent the same person.":"Multiple people share this name. Confirm whether they should stay separate or be combined.",actionLabel:"Go to people",actorIds:l.actorIds})}),i.forEach(l=>{const d=MS({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId}),u=l.peer?Go(l.peer):"waiting",p=l.peer?ua(l.peer):null,f=ue(l.discovered?.fingerprint),m=ue(l.peer?.fingerprint);if(l.peer&&f&&m&&f!==m){c.push(KS({id:l.deviceId,name:d,title:`${d} needs review`,summary:"This device identity changed. Remove the older local record before reconnecting it."}));return}if(l.peer&&u==="needs-repair"){const v=p?.description||ue(l.peer?.last_error)||"Sync needs review.";c.push(KS({id:l.deviceId,name:d,title:p?.state==="needs-repairing"?`${d} needs re-pairing`:`${d} needs review`,summary:v}))}l.peer&&p?.state==="trusted-by-you"&&c.push(Vf({id:l.deviceId,key:"other-device-trust",name:d,summary:"You accepted this device. Finish onboarding on the other device so it trusts this one too."})),!l.peer&&l.discovered?.stale&&c.push(Vf({id:l.deviceId,key:"stale-discovery",name:d,summary:"This device is no longer advertising fresh coordinator presence. Wait for it to check in again before connecting it here."})),!l.peer&&Array.isArray(l.discovered?.groups)&&l.discovered.groups.length>1&&c.push(Vf({id:l.deviceId,key:"ambiguous-groups",name:d,summary:"This device appears in multiple coordinator groups. Review the team setup before approving it here."})),l.peer&&hU({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId})&&c.push(UU({id:l.deviceId,name:d,summary:"Give this device a friendly name so it is easier to recognize later."}))}),{primaryStatus:VS({status:e.status,coordinator:e.coordinator,peers:n,shareOperations:e.shareOperations,shareOperationsLoadError:e.shareOperationsLoadError,reconciliation:e.reconciliation}),summary:{connectedDeviceCount:n.filter(l=>Go(l)==="connected").length,seenOnTeamCount:r.length,offlineTeamDeviceCount:i.filter(l=>qU(l)).length},duplicatePeople:s,attentionItems:c.sort((l,d)=>l.priority-d.priority||l.title.localeCompare(d.title))}}var zS={actor:"person",actors:"people",actorAssignment:"person assignment",localActor:"you",peer:"device",peers:"devices",pairedLocally:"Connected on this device",discovered:"Seen on team",conflicts:"Needs review"};function wr(e){const t=document.getElementById(e);t&&t.remove()}var WS=!1;function KU(e){WS=e}var Kf=!1;function zU(e){Kf=e}var zf=!1;function WU(e){zf=e}var JU=new Set,Wf=new Set,Jf=new Set,JS="codemem-sync-duplicate-person-decisions";function YU(e){const t=String(e||"").trim();t&&(Wf.add(t),Jf.add(t),JU.add(t))}function Yf(e){const t=String(e||"").trim();return!!t&&Wf.has(t)}function XU(e){const t=String(e||"").trim();t&&Wf.delete(t)}function QU(e){const t=String(e||"").trim();return!t||!Jf.has(t)?!1:(Jf.delete(t),!0)}function Xf(){try{const e=localStorage.getItem(JS);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function YS(e){try{localStorage.setItem(JS,JSON.stringify(e))}catch{}}function XS(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function ZU(){return Xf()}function e2(e,t){const n=XS(e);if(!n)return;const r=Xf();r[n]=t,YS(r)}function t2(e){const t=XS(e);if(!t)return;const n=Xf();delete n[t],YS(n)}function QS(e){return e.replace(/\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b/g,"$1.#.#")}function ZS(e){const t=String(e||"");return t?QS(t):""}function n2(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function r2(e,t){const n=String(e?.relatedPeerDeviceId??"").trim();return n?t.some(r=>String(r?.peer_device_id??"").trim()===n):!1}function Sl(e){if(!e||typeof e!="object")return"Unknown person";const t=String(e.display_name||"").trim();return t||String(e.actor_id||"Unknown person")}function Qf(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":Sl(e)}function i2(e){return(Array.isArray(S.lastSyncPeers)?S.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function a2(){return HS({actors:S.lastSyncActors,peers:S.lastSyncPeers,duplicatePeople:S.lastSyncViewModel?.duplicatePeople}).visibleActors}function eC(e){return a2().filter(t=>String(t?.actor_id||"")!==e)}function o2(e,t){const n=eC(t).find(r=>String(r?.actor_id||"")===e);return!e||!n?"Choose which person should keep these devices.":`Merge into ${Qf(n)}. Assigned devices move now; existing memories keep their current provenance.`}function Zf(e,t){if(e){if(e.textContent="",!t.length){e.hidden=!0;return}e.hidden=!1,t.slice(0,2).forEach(n=>{const r=Ws("div","sync-action"),i=Ws("div","sync-action-text");i.textContent=n.label,i.appendChild(Ws("span","sync-action-command",n.command));const a=Ws("button","settings-button sync-action-copy","Copy");a.addEventListener("click",()=>Va(n.command,a)),r.append(i,a),e.appendChild(r)})}}function tC(e,t){return t&&e.error_redacted===!0}function s2(e){return e?{action:t=>Fr({severity:"error",subsystem:"sync",trigger:t})}:{}}function nC(){const e=document.getElementById("syncAttempts");if(!e)return;const t=S.lastSyncAttempts,n=String(S.lastSyncStatus?.daemon_state||"").trim();if(!Array.isArray(t)||!t.length){ui(e,Jq());return}const r=Xq(n,t.slice(0,5).some(a=>a.status==="error")),i=t.slice(0,5).map(a=>{const s=a.started_at||a.started_at_utc||"",c=String(a.peer_device_id||"").trim(),l=Array.isArray(S.lastSyncPeers)?S.lastSyncPeers.find(m=>String(m?.peer_device_id||"")===c):null,d=String(l?.name||"").trim()||(c?c.slice(0,8):"unknown"),u=a.status==="error",p=[],f=za();if(u&&a.error){const m=String(a.error);p.push(f?QS(m):m),tC(a,f)&&p.push("Turn off Redact in Advanced diagnostics to reveal the full error.")}return!u&&(a.ops_in||a.ops_out)&&p.push(`${a.ops_in??0} in · ${a.ops_out??0} out`),!f&&a.address&&p.push(a.address),{status:a.status||"unknown",peerLabel:d,detail:p.join(" · "),startedAt:s?Zr(s):"",...s2(u),...tC(a,f)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}});nU(e,i,r)}function c2(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncAttempts"),n=document.getElementById("syncMeta"),r=document.getElementById("syncActions");e&&ui(e,Wq()),t&&ui(t,Yq()),n&&(n.textContent="Advanced diagnostics are unavailable right now. Refresh the page first. If that still fails, verify the local sync service and retry once it responds again."),Zf(r,[])}function pa(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function l2(e){const t=String(e?.state??"clear"),n=e?.stale_peer_rows??{},r=e?.access_cleanup_ops??{},i=pa(n.would_remove),a=pa(n.ambiguous),s=pa(r.applied),c=pa(r.source_authored);return t==="cleanup_pending"||i>0?`${i} pending removal`:t==="needs_review"||a>0?`${a} needs review`:t==="cleanup_applied"||s>0?`${s} applied`:t==="cleanup_announced"||c>0?`${c} announced`:"Clear"}function rC(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncMeta"),n=document.getElementById("syncActions");if(!e)return;wr("syncDiagSkeleton");const r=S.lastSyncStatus;if(!r){ui(e,zq()),Zf(n,[]),t&&(t.textContent="Loading advanced sync diagnostics…");return}const i=r.peers||{},a=r.ping||{},s=r.sync||{},c=r.last_sync_at||r.last_sync_at_utc||null,l=a.last_ping_at||r.last_ping_at||Gq(i)||null,d=r.last_sync_error||"",u=r.last_ping_error||"",p=Number(r.pending||0),f=String(r.daemon_detail||""),m=String(r.daemon_state||"unknown"),v=r.retention||{},b=r.cleanup_diagnostics,h=b?.stale_peer_rows??{},y=pa(h.would_remove),w=pa(h.ambiguous),_=v.enabled===!0,R=Number(v.last_deleted_ops||0),I=v.last_run_at||null,T=String(v.last_error||""),A=m==="offline-peers"?"Offline peers":m==="needs_attention"?"Needs attention":m==="rebootstrapping"?"Rebootstrapping":e_(m),L=m==="disabled"||r.enabled===!1,F=Object.keys(i).length,N=!L&&F===0;if(t){const U=L?["Advanced sync is off on this device","Turn on sync in Settings → Device Sync when you want pairing payloads, peer status, and recent attempt details here"]:N?["Advanced sync is ready but idle","Use Show pairing command under People & devices to connect another device, then this panel will start showing live peer status and recent attempts"]:[`Advanced state: ${A}`,`Peers: ${F}`,c?`Last sync: ${ur(Zi(c))} ago`:"Last sync: never"];m==="offline-peers"&&U.push("All peers are currently offline; sync will resume automatically"),f&&m==="stopped"&&U.push(`Detail: ${f}`),f&&(m==="needs_attention"||m==="rebootstrapping")&&U.push(`Detail: ${f}`),_&&U.push(I?`Retention last ran ${ur(Zi(I))} ago (approx oldest-first)`:"Retention enabled"),y>0?U.push(`${y.toLocaleString()} stale peer rows pending cleanup`):w>0&&U.push(`${w.toLocaleString()} stale peer rows retained because safe cleanup could not be proven`),t.textContent=U.join(" · ")}const j=L?[{label:"State",value:"Disabled"},{label:"Mode",value:"Optional"},{label:"Pending events",value:p},{label:"Last sync",value:"Not running"}]:N?[{label:"State",value:"No peers"},{label:"Mode",value:"Ready to pair"},{label:"Pending events",value:p},{label:"Last sync",value:"Waiting for first peer"}]:[{label:"State",value:A},{label:"Pending events",value:p},{label:"Last sync",value:c?`${ur(Zi(c))} ago`:"never"},{label:"Last peer ping",value:l?`${ur(Zi(l))} ago`:"never"},{label:"Retention",value:_?I?`${R.toLocaleString()} ops last run (approx)`:"Enabled":"Disabled"}];!L&&!N&&(d||u)&&j.push({label:[d,u].filter(Boolean).join(" · "),value:"Errors"}),!L&&!N&&s.seconds_since_last&&j.push({label:"Since last sync",value:`${s.seconds_since_last}s`}),!L&&!N&&a.seconds_since_last&&j.push({label:"Since last peer ping",value:`${a.seconds_since_last}s`}),!L&&_&&T&&j.push({label:T,value:"Retention"}),!L&&!N&&b&&j.push({label:"Cleanup",value:l2(b)}),tU(e,j);const x=[];N||m==="offline-peers"||(m==="stopped"?(x.push({label:"Sync daemon is stopped. Start it.",command:"codemem serve start"}),x.push({label:"Run one sync pass now.",command:"codemem sync once"})):m==="needs_attention"?x.push({label:"Sync needs manual attention before reset can continue.",command:"codemem sync doctor"}):m==="rebootstrapping"?x.push({label:"Sync is rebuilding state in the background.",command:"codemem sync status"}):d||u||m==="error"?(x.push({label:"Sync reports errors. Restart now.",command:"codemem serve restart && codemem sync once"}),x.push({label:"Run doctor for the root cause.",command:"codemem sync doctor"})):!L&&!N&&p>0&&x.push({label:"Pending sync work detected. Run one pass now.",command:"codemem sync once"})),!L&&w>0?x.push({label:"Some stale peer rows were retained because cleanup was ambiguous.",command:"codemem sync doctor"}):!L&&y>0&&x.push({label:"Stale peer rows are eligible for cleanup. Run one sync pass now.",command:"codemem sync once"}),Zf(n,x)}var d2="syncRedactMount",u2="syncRedactLabel",iC=()=>{};function p2(e){iC=e}var em=()=>{};function tm(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;oU(e,{contentHost:t,open:S.syncPairingOpen,onOpenChange:r=>{if(cA(r),tm(),r){const i=document.getElementById("pairingPayload"),a=document.getElementById("pairingHint");i&&ES(i,a,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}em()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=S.pairingCommandRaw;r&&await Va(r,n)})}function nm(){tm();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;ES(e,t,Kq(S.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!S.pairingCommandRaw)}function aC(){const e=document.getElementById(d2);e&&mt(e,g(Ji,{"aria-labelledby":u2,checked:za(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{lA(t),aC(),em(),rC(),iC(),nC(),nm()},thumbClassName:"sync-redact-switch-thumb"}))}function f2(e){em=e,tm(),aC()}function m2(e){e.classList.add("sync-shake"),e.addEventListener("animationend",()=>e.classList.remove("sync-shake"),{once:!0})}function fa(e,t){e.classList.add("sync-field-error");const n=e.parentElement?.querySelector(".sync-field-hint");n&&n.remove();const r=document.createElement("div");return r.className="sync-field-hint",r.textContent=t,e.insertAdjacentElement("afterend",r),m2(e),e.addEventListener("input",()=>Ho(e),{once:!0}),!1}function Ho(e){e.classList.remove("sync-field-error");const t=e.parentElement?.querySelector(".sync-field-hint");t&&t.remove()}function _t(e,t){if(e instanceof Error){const n=e.message;return n.includes("fetch")||n.includes("network")||n.includes("Failed to fetch")?"Network error — check your connection and try again.":n}return t}var pi=new Map,rm=null,h2={operation_device_binding_missing:"The accepted device has not been linked yet.",operation_not_found:"This sharing operation is no longer available.",operation_scope_mismatch:"The invitation no longer matches the reviewed project access.",operation_state_invalid:"The invitation is no longer in a recoverable state.",reassign_capability_required:"A participating device must be updated before setup can continue."};function g2(e){const t=e instanceof Error?e.message:String(e);return h2[t]??"Setup could not be retried. Review diagnostics for details."}function v2(e){const t=new Map;for(const n of e){const r=n.person.actor_id;t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function y2(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function im(e){switch(e){case"waiting_for_acceptance":return"Invitation pending";case"active":return"Sharing";case"revoking":return"Removing sharing";case"revoked":return"Previously shared";case"cancelled":return"Invitation cancelled";default:return"Sharing setup"}}function b2({operation:e,onAdvance:t,onLoadOperation:n,onReload:r,copyText:i}){const[a,s]=D(!1),[c,l]=D(()=>pi.get(e.operation_id)??null),d=B(null),u=e.lifecycle.primary_action;V(()=>{rm!==e.operation_id||!d.current||(rm=null,d.current.focus())},[c?.message,e.operation_id]);async function p(b){s(!0);try{let h=b;if(!h&&n){const w=(await n(e.operation_id)).lifecycle.primary_action;w?.kind==="copy_invite"&&(h=w.invite_link)}if(!h)throw new Error("Invitation is no longer available. Refresh the status.");await(i??(w=>navigator.clipboard.writeText(w)))(h);const y={message:"Invite copied.",tone:"success"};pi.set(e.operation_id,y),l(y)}catch(h){const y={message:h instanceof Error?h.message:"Invite could not be copied.",tone:"warning"};pi.set(e.operation_id,y),l(y)}finally{s(!1)}}async function f(){s(!0);try{const b=await t(e.operation_id),h=b.lifecycle.state==="active"?{message:"Setup complete.",tone:"success"}:b.lifecycle.state==="needs_attention"?{message:"Setup still needs attention.",tone:"warning"}:{message:`Retry started. ${b.lifecycle.label}.`,tone:"success"};pi.set(e.operation_id,h),rm=e.operation_id,l(h),await r()}catch(b){const h={message:g2(b),tone:"warning"};pi.set(e.operation_id,h),l(h),queueMicrotask(()=>d.current?.focus())}finally{s(!1)}}function m(){const b=e.projects.map(h=>h.project_id?.trim()).filter(h=>!!h);if(b.length!==e.projects.length){const h={message:"The original project selection is unavailable. Refresh Projects and try again.",tone:"warning"};pi.set(e.operation_id,h),l(h);return}if(!As(b,e.person.display_name)){const h={message:"Project sharing is unavailable. Refresh Projects and try again.",tone:"warning"};pi.set(e.operation_id,h),l(h)}}function v(){if(u){if(u.kind==="copy_invite"){p(u.invite_link);return}if(u.kind==="retry_setup"){f();return}m()}}return o("section",{"aria-label":`${im(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[o("div",{className:"peer-scope-summary",children:im(e.lifecycle.state)}),o("ul",{"aria-label":`${im(e.lifecycle.state)} projects`,className:"peer-scope-chips",children:e.projects.map((b,h)=>o("li",{className:"peer-scope-chip",children:b.display_name},`${b.display_name}:${h}`))}),o("div",{className:"peer-scope-summary",children:e.lifecycle.label}),o("div",{className:"peer-meta",role:e.lifecycle.state==="needs_attention"?"alert":void 0,children:e.lifecycle.explanation}),u?o("div",{className:"peer-actions",children:o("button",{"aria-busy":a,className:"settings-button",disabled:a,type:"button",onClick:v,children:a?u.kind==="copy_invite"?"Copying…":"Retrying…":u.label})}):null,c?o("div",{ref:d,className:`settings-note ${c.tone==="warning"?"project-attention-note":""}`,role:"status",tabIndex:-1,children:c.message}):null]})}function _2({operations:e,...t}){const n=e[0].person,r=y2(e);return o("article",{"aria-label":`Project sharing with ${n.display_name}`,className:"peer-card project-share-person-group",children:[o("h3",{className:"device-row-name",children:n.display_name}),r.length>0?o("ul",{"aria-label":`Devices for ${n.display_name}`,className:"peer-scope-rejections-list",children:r.map(i=>o("li",{children:i.display_name},i.device_id))}):null,e.map(i=>o(b2,{operation:i,...t},i.operation_id))]})}function w2(e){return e.operations.length===0?null:o("div",{className:"project-share-person-groups",children:v2(e.operations).map(t=>o(_2,{...e,operations:t},t[0].person.actor_id))})}function S2(e,t){mt(e,o(w2,{...t}))}function oC({title:e,detail:t}){return o("div",{className:"sync-empty-state",role:"status","aria-live":"polite","aria-atomic":"true",children:[o("strong",{children:e}),o("span",{children:t})]})}function C2(e){return e<=0?"Represents you across your own devices.":`Represents you across your own devices. ${e} unresolved duplicate ${e===1?"entry is":"entries are"} hidden until reviewed in Needs attention.`}function R2({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const a=String(e.actor_id||""),s=Sl(e),c=i2(a),l=eC(a),d=l.map(x=>String(x.actor_id||"")).join("|"),[u,p]=D(s),[f,m]=D(!1),[v,b]=D("Rename"),[h,y]=D(!1),[w,_]=D("Merge into selected person"),[R,I]=D(""),[T,A]=D(!1);V(()=>{p(s),m(!1),b("Rename"),y(!1),_("Merge into selected person"),I(""),A(!1)},[a,c,t,s,d]);const L=l.length?o2(R,a):"No other people are available yet. Create another person first if you need to merge duplicates.",F=[{label:"Merge into person",value:""},...l.map(x=>{const U=String(x.actor_id||"");return{label:x.is_local?Qf(x):Sl(x),value:U}})];async function N(){const x=u.trim();if(!x)return;m(!0),b("Saving…");let U=!1;try{await n(a,x),U=!0}catch{b("Retry rename")}finally{m(!1),U&&b("Rename")}}async function j(){if(!R)return;const x=l.find(q=>String(q.actor_id||"")===R);if(!x||!await vn({title:`Merge ${s} into ${Sl(x)}?`,description:"Assigned devices move now, but older memories keep their current stamped provenance for now.",confirmLabel:"Merge people",cancelLabel:"Keep separate",tone:"danger"}))return;y(!0),_("Merging…");let U=!1;try{await r(R,a),U=!0}catch{_("Retry merge")}finally{y(!1),U&&_("Merge into selected person")}}return o("div",{className:"actor-row",children:[o("div",{className:"actor-details",children:[o("div",{className:"actor-title",children:[o("strong",{children:Qf(e)}),o("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?C2(t):void 0,children:e.is_local?"You":`${c} device${c===1?"":"s"}`})]}),e.is_local?null:o("div",{className:"peer-meta",children:[c," assigned device",c===1?"":"s"]})]}),o("div",{className:"actor-actions",children:e.is_local?o("div",{className:"peer-meta",children:"Rename yourself in config"}):o(z,{children:[o(ke,{"aria-label":`Rename ${s}`,className:"peer-scope-input actor-name-input",disabled:f||h,type:"text",value:u,onInput:x=>p(x.currentTarget.value),onKeyDown:x=>ro(x,{onSubmit:()=>{N()},disabled:f||h||!u.trim()})}),o("button",{type:"button",className:"settings-button","data-primary-action":"true",disabled:f||h,onClick:()=>{N()},children:v}),o("button",{type:"button",className:"settings-button danger",disabled:f||h,onClick:async()=>{await vn({title:`Remove ${s}?`,description:"This deactivates the person and unassigns their devices. Existing memories keep their current attribution.",confirmLabel:"Remove person",cancelLabel:"Keep",tone:"danger"})&&await i(a)},children:"Remove"}),o("button",{type:"button",className:"settings-button",disabled:f||h,onClick:()=>A(x=>!x),children:T?"Hide duplicate cleanup":"Show duplicate cleanup"}),T?o(z,{children:[o("div",{className:"peer-meta actor-merge-note",children:"Use this only when combining duplicate people into one."}),o("div",{className:"actor-merge-controls",children:[o(dr,{ariaLabel:`Merge ${s} into another person`,contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:h||l.length===0,itemClassName:"sync-radix-select-item",onValueChange:I,options:F,placeholder:"Merge into person",triggerClassName:"sync-radix-select-trigger sync-actor-select actor-merge-select",value:R,viewportClassName:"sync-radix-select-viewport"}),o("button",{type:"button",className:"settings-button",disabled:h||l.length===0||!R,onClick:()=>{j()},children:w})]}),o("div",{className:"peer-meta actor-merge-note",children:L})]}):null]})})]})}function I2({actors:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){return e.length?o(z,{children:e.map(a=>{const s=String(a.actor_id||a.display_name||a.is_local||"");return o(R2,{actor:a,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):o(oC,{detail:"Create a named person here for legacy provenance, then confirm device Identity ownership in Devices.",title:"No people set up yet."})}function k2(e,t){mt(e,o(I2,{...t}))}function T2(e){return e.filter(t=>String(t.origin_device_id||"").trim())}function P2(e){const t=e.find(n=>String(n.last_seen_at||"").trim());return t?.last_seen_at?`Detected from older synced memories. Latest memory: ${Zr(String(t.last_seen_at).trim())}`:"Detected from older synced memories not yet attached to a current device."}function N2({devices:e}){return o(z,{children:P2(e)})}function E2(e){const t=String(e.origin_device_id||"").trim(),n=Number(e.memory_count||0);return{label:n>0?`${t} (${n} memories)`:t,value:t}}function A2(e){const t=T2(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),da(e.mount),da(e.meta);return}const n=t.map(E2),r=n.some(i=>i.value===e.value)?e.value:n[0]?.value||"";r!==e.value&&e.onValueChange(r),e.panel.hidden=!1,mt(e.mount,o(dr,{ariaLabel:"Legacy device",contentClassName:"sync-radix-select-content sync-legacy-select-content",id:"syncLegacyDeviceSelect",itemClassName:"sync-radix-select-item",onValueChange:e.onValueChange,options:n,triggerClassName:"sync-radix-select-trigger sync-legacy-select",value:r,viewportClassName:"sync-radix-select-viewport"})),mt(e.meta,o(N2,{devices:t}))}var x2={online:"Online",offline:"Offline",degraded:"Degraded",attention:"Action required",syncing:"Syncing",unknown:"Status unknown"};function D2({state:e,size:t=8,"aria-label":n}){const r=n??x2[e];return o("span",{"aria-label":r,className:`presence-pip presence-pip--${e}`,role:"img",style:`--presence-pip-size: ${t}px`})}function fi({feedback:e}){return e?.message?o("div",{className:`sync-inline-feedback ${e.tone}`,role:e.tone==="warning"?"alert":"status","aria-live":e.tone==="warning"?"assertive":"polite","aria-atomic":"true",children:e.message}):null}function L2(){return o("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[o("title",{children:"Chevron"}),o("path",{d:"m9 18 6-6-6-6"})]})}function $2(e){switch(Go(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var Cl=null,sC=0,am=new Set;function cC(e){if(Cl!==e){Cl=e,sC+=1;for(const t of am)t(sC)}}function j2(){const[,e]=D(0);return V(()=>(am.add(e),()=>{am.delete(e)}),[]),Cl}var O2={bidirectional:{glyph:"↕",label:"Bidirectional sync in the last 24 hours"},publishing:{glyph:"↑",label:"Publishing only in the last 24 hours"},subscribed:{glyph:"↓",label:"Subscribed only in the last 24 hours"},none:null};function lC(e,t){if(!e)return"the selected Identity";const n=t.find(r=>r.actor_id===e);return String(n?.display_name||n?.actor_display_name||"the selected Identity")}function M2(e,t,n,r=!1,i=!1,a=!1){if(i)return{status:"unavailable",summary:"Authoritative Identity status is unavailable because the inventory is incomplete.",detail:"This installation has more device evidence than Advanced can safely classify. Ownership is not shown from a partial inventory.",actionLabel:"Review Identity inventory in Devices"};if(r||a&&!e)return{status:"unavailable",summary:"Authoritative Identity status is temporarily unavailable.",detail:"Refresh before relying on ownership details. Advanced actor_id values remain suggestions or provenance only.",actionLabel:"Review Identity in Devices"};if(e?.state==="configured")return{status:"configured",summary:`Authoritative Identity: ${lC(e.identityId,n)}.`,detail:"This result comes from an active identity_devices binding. Advanced actor_id values are not authoritative ownership.",actionLabel:"Review or rebind in Devices"};if(e?.state==="pairing_required")return{status:"pairing_required",summary:"Identity setup is blocked until pairing is complete.",detail:"Pairing establishes sync trust; it does not establish device ownership.",actionLabel:"Review setup in Devices"};if(e?.state==="conflicted")return{status:"conflicted",summary:"Identity ownership needs review.",detail:"Conflicting device evidence failed closed. Advanced actor_id values cannot resolve ownership.",actionLabel:"Review conflict in Devices"};const s=e?.suggestedIdentityId??t;return{status:e?.state??"unavailable",summary:s?`Suggested Identity: ${lC(s,n)}.`:"No authoritative Identity binding is configured.",detail:"sync_peers.actor_id is only a suggestion or hint until you confirm an identity_devices binding in Devices.",actionLabel:"Set up Identity in Devices"}}function F2(e){S.pendingDeviceIdentityFocus=e?.trim()||null,window.location.hash="devices"}function B2(e){return e?e.authorized?"Private same-person sync is limited to your personal Space. Team and org Spaces do not carry your private memories.":"Private same-person sync is blocked until this device is granted an allowed personal Space.":"Private same-person sync is limited to an allowed personal Space; team or org Spaces do not carry your private memories."}function q2(){window.location.hash="advanced/teams"}function om(e=S.lastSyncCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function U2({peer:e,onRemove:t,onRename:n,onSync:r}){const i=String(e.peer_device_id||""),a=e.name||(i?i.slice(0,8):"unknown"),s=e.name||i||a,c=ua(e),l=O2[gU(e)],d=e.status||{},u=bU(e),p=Yf(i),f=p&&u.total===0,m=PU(e),v=yU(e),b=qS(e),h=e.project_scope||{},y=EU(h),w=n2(e.addresses),_=Array.isArray(e.addresses)?Array.from(new Set(e.addresses.filter(Boolean).map(ae=>String(ae)))):[],R=Number(e.address_count??0),I=Number.isFinite(R)&&R>0?R:0,T=_.length?_.map(ae=>za()?ZS(ae):ae).join(" · "):I>0?`${I} ${I===1?"address":"addresses"} hidden`:"No addresses",A=S.lastDeviceIdentityInventory?.items.find(ae=>ae.deviceId===i||ae.evidenceDeviceIds.includes(i)),L=M2(A,String(e.actor_id||"")||null,S.lastSyncActors,S.deviceIdentityInventoryLoadError,S.lastDeviceIdentityInventory?.truncated===!0,S.lastDeviceIdentityInventory?.coordinatorEvidence.availability==="unavailable"),F=String(d.last_sync_at||d.last_sync_at_utc||""),N=String(d.last_ping_at||d.last_ping_at_utc||""),j=e.discovered_via_group_id?`Discovery: seen through coordinator group ${e.discovered_via_group_id}. Discovery helps find devices; Space access above decides data access.`:e.discovered_via_coordinator_id?`Discovery: seen through coordinator ${e.discovered_via_coordinator_id}. Discovery helps find devices; Space access above decides data access.`:null,x=QU(i),U=B(null),[q,$]=D(a),[E,C]=D(()=>S.syncPeerFeedbackById.get(i)??null),[O,H]=D(!1),[G,ee]=D("Save name"),[Z,ie]=D(!1),[fe,Ce]=D(!1),[Pe,Ne]=D("Remove device");V(()=>{p&&u.total>0&&XU(i)},[u.total,i,p]),V(()=>{$(a),C(S.syncPeerFeedbackById.get(i)??null),H(!1),ee("Save name"),ie(!1),Ce(!1),Ne("Remove device")},[a,e.actor_id,i]),V(()=>{!x||!U.current||queueMicrotask(()=>U.current?.scrollIntoView({block:"center",behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}))},[x]);async function ce(){if(!i)return;const ae=q.trim();if(!ae){const Fe={message:"Enter a friendly name for this device.",tone:"warning"};C(Fe),S.syncPeerFeedbackById.set(i,Fe),document.querySelector(`[data-device-name-input="${CSS.escape(i)}"]`)?.focus();return}H(!0),ee("Saving…");try{const Fe=await n(i,ae);C(Fe),S.syncPeerFeedbackById.set(i,Fe),ee("Save name")}catch{ee("Retry")}finally{H(!1)}}async function me(){if(f){const ae=om();if(!await vn({title:`Sync ${a} before advanced rule review?`,description:ae?"This manual sync will use the current legacy Space access and advanced filters until you review them in Coordinator Administration.":"This manual sync will use the current legacy Space access and advanced filters until a coordinator operator reviews them in Coordinator Administration.",confirmLabel:"Sync anyway",cancelLabel:ae?"Review legacy Team/Space setup first":"Cancel"}))return}ie(!0);try{const ae=await r(e,w);C(ae),ae&&S.syncPeerFeedbackById.set(i,ae)}finally{ie(!1)}}async function J(){if(!i||!await vn({title:`Remove device ${s}?`,description:"This removes the local record for this paired device on this machine.",confirmLabel:"Remove device",cancelLabel:"Keep device",tone:"danger"}))return;Ce(!0),Ne("Removing…");let ae=!1;try{await t(i,s),ae=!0}catch{Ne("Retry remove")}finally{Ce(!1),ae&&Ne("Remove device")}}const se=j2()===i&&i!=="",ye=`device-drawer-${i||"unknown"}`,le=$2(e),Ee=F?`Sync: ${Zr(F)}`:"Sync: never",re=om(),Q=`${se?"Collapse":"Expand"} device ${a}`;return o(Ya,{asChild:!0,open:se,onOpenChange:ae=>{ae?cC(i):Cl===i&&cC(null)},children:o("div",{ref:U,className:"peer-card","data-peer-device-id":i||void 0,children:[o(zu,{asChild:!0,children:o("button",{"aria-label":Q,className:"device-row-head device-row-head--trigger",type:"button",children:[o(D2,{state:le}),o("span",{className:"device-row-name",title:i||void 0,children:a}),l?o("span",{"aria-label":l.label,className:"peer-direction",role:"img",title:l.label,children:l.glyph}):null,o("span",{className:"device-row-chips",children:[o("span",{className:`badge ${c.isWarning?"badge-offline":"badge-online"}`,children:c.badgeLabel}),f?o("span",{className:"badge actor-badge",children:"Review advanced rules"}):null,o("span",{className:`badge ${u.isWarning?"badge-offline":"actor-badge"}`,title:"Spaces are the hard access boundary; advanced filters only narrow inside them.",children:u.badgeLabel}),v.badgeLabel?o("span",{className:"badge badge-offline",title:"Inbound ops rejected by the sharing-domain scope gate. Expand for reason codes.",children:v.badgeLabel}):null,m.badgeLabel?o("span",{className:"badge badge-offline",title:"Review whether explicit Space access matches this device's intended role.",children:m.badgeLabel}):null,e.discovered_via_group_id?o("span",{className:"badge actor-badge",title:`Discovered through coordinator group ${e.discovered_via_group_id}`,children:`via ${e.discovered_via_group_id}`}):null]}),o("span",{className:"device-row-meta",children:Ee}),o("span",{"aria-hidden":"true",className:"device-row-chevron",children:o(L2,{})})]})}),o(Xa,{"aria-label":`Device actions for ${a}`,className:"device-row-drawer",id:ye,children:[o("div",{className:"peer-actions",children:[o("button",{type:"button",className:"settings-button",disabled:Z,onClick:()=>{me()},title:w?void 0:"Address details are hidden; sync will target this device by ID.",children:Z?"Syncing…":"Sync now"}),o("div",{className:"sync-labeled-field",children:[o("label",{className:"sync-labeled-field-caption",htmlFor:`device-name-${i||"unknown"}`,children:"Device name"}),o(ke,{"aria-label":`Friendly name for ${a}`,className:"peer-scope-input","data-device-name-input":i||void 0,disabled:O,id:`device-name-${i||"unknown"}`,placeholder:"Friendly device name",type:"text",value:q,onInput:ae=>$(ae.currentTarget.value)})]}),o("button",{type:"button",className:"settings-button",disabled:O,onClick:()=>{ce()},children:G}),o("button",{type:"button",className:"settings-button danger",disabled:fe,onClick:()=>{J()},children:Pe})]}),o("div",{className:"peer-scope",children:[x?o("div",{className:"peer-meta",children:re?"Review this device's legacy Space access and advanced rules in Coordinator Administration if the defaults are too broad.":"A coordinator operator can review this device's legacy Space access and advanced rules in Coordinator Administration if the defaults are too broad."}):f?o("div",{className:"peer-meta",children:"Advanced rule review is still pending for this device."}):null,o("div",{className:"peer-scope-summary",children:"Device details"}),o("div",{className:"peer-addresses",children:T}),j?o("div",{className:"peer-meta",children:j}):null,o("div",{className:"peer-meta",children:[F?`Sync: ${Zr(F)}`:"Sync: never",N?`Ping: ${Zr(N)}`:"Ping: never"].join(" · ")}),o("div",{className:"peer-scope-summary",children:"Space access"}),o("div",{className:"peer-meta",children:u.total>0?"These Spaces are the hard access boundary for this device.":u.emptyMessage}),u.domains.length>0?o("ul",{className:"peer-scope-chips","aria-label":"Authorized Spaces",children:u.domains.map(ae=>o("li",{className:"peer-scope-chip",title:ae.detail,children:ae.label},ae.scopeId))}):null,m.isVisible?o("div",{className:"settings-note",role:"status",children:[o("strong",{children:m.title}),o("div",{children:m.message}),o("div",{children:m.detail})]}):null,o("div",{className:"peer-meta",children:y.note}),o("div",{className:"peer-scope-summary",children:"Space sync progress"}),o("div",{className:"peer-meta",children:b.total>0?"Per-Space progress for this device. Open details to see technical identifiers.":b.emptyMessage}),b.rows.length>0?o("ul",{className:"peer-scope-rejections-list","aria-label":"Per-Space sync progress",children:b.rows.map(ae=>o("li",{title:ae.detail,children:[o("span",{className:"peer-scope-rejection-label",children:ae.label}),o("span",{className:`badge ${ae.status==="received"?"badge-online":"actor-badge"}`,children:ae.badgeLabel})]},ae.scopeId))}):null,v.total>0?o("div",{className:"peer-scope-rejections","data-peer-rejection-count":v.total,children:[o("div",{className:"peer-scope-summary",children:"Sharing-rule rejections (24h)"}),o("div",{className:"peer-meta",children:"Inbound ops the local fail-closed gate refused. Diagnostics never expose op payloads."}),o("ul",{className:"peer-scope-rejections-list",children:v.reasons.map(ae=>o("li",{children:[o("span",{className:"peer-scope-rejection-label",children:ae.label}),o("span",{className:"peer-scope-rejection-count",children:ae.count.toLocaleString()})]},ae.reason))}),v.lastAt?o("div",{className:"peer-meta",children:["Last rejected ",Zr(v.lastAt)]}):null]}):null,o("div",{className:"peer-scope-summary",children:"Authoritative Identity ownership"}),o("div",{className:"peer-meta",children:L.summary}),o("div",{className:"peer-meta",children:L.detail}),e.claimed_local_actor?o("div",{className:"peer-meta",children:B2(e.claimed_local_actor_scope)}):null,o("div",{className:"peer-actor-row",children:o("button",{type:"button",className:"settings-button",onClick:()=>F2(A?.deviceId??i),children:L.actionLabel})}),o("div",{className:"peer-scope-summary",children:"Advanced sharing rules"}),o("div",{className:"peer-meta",children:[y.statusLabel,". ",y.summary," ",y.note]}),re?o("div",{className:"peer-actions",children:o("button",{type:"button",className:"settings-button",onClick:q2,children:"Open Coordinator Administration"})}):o("div",{className:"peer-meta",children:"Legacy Space access is managed in Coordinator Administration by a coordinator operator."}),o(fi,{feedback:E})]})]})]})})}function G2(e){const t=S.syncPeersSectionFeedback,n=S.lastSyncStatus,r=n?.daemon_state==="disabled"||n?.enabled===!1;return e.peers.length?o(z,{children:[o(fi,{feedback:t}),e.peers.map(i=>{const a=String(i.peer_device_id||i.name||"unknown-peer");return o(U2,{peer:i,...e},a)})]}):o(z,{children:[o(fi,{feedback:t}),o(oC,{detail:r?"Turn on sync in Settings → Device Sync first. Then use Invite a teammate or Paste an invite above to connect another device.":"Use Invite a teammate above to share a join code, or Paste an invite to enroll this device on an existing team.",title:"No teammates yet"})]})}function H2(e,t){mt(e,o(G2,{...t}))}var Sr=async()=>{},Rl="";function sm(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function V2(e){Sr=e}function K2(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;wr("syncActorsSkeleton"),sm(!1);const n=HS({actors:S.lastSyncActors,peers:S.lastSyncPeers,duplicatePeople:S.lastSyncViewModel?.duplicatePeople}),r=n.visibleActors;t&&(t.textContent=r.length?"Manage Identity names here. Confirm authoritative device ownership in Devices.":"No named people yet. Create an Identity here, then confirm device ownership in Devices.",n.hiddenLocalDuplicateCount>0&&(t.textContent+=` ${n.hiddenLocalDuplicateCount} unresolved duplicate ${n.hiddenLocalDuplicateCount===1?"entry is":"entries are"} hidden here until reviewed in Needs attention.`)),k2(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,a)=>{await BI(i,a),await Sr()},onMerge:async(i,a)=>{try{await fh(i,a),X("People combined. Assigned devices moved to the selected person."),await Sr()}catch(s){throw X(_t(s,"Failed to combine people."),"warning"),s}},onDeactivate:async i=>{try{await qI(i),X("Person removed. Assigned devices have been unassigned."),await Sr()}catch(a){throw X(_t(a,"Failed to remove person."),"warning"),a}}})}function z2(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");sm(!0),t&&(t.textContent="People controls are temporarily unavailable. Refresh this page to retry. Device status and sync health are still available below while this recovers."),e&&ui(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. When the people endpoint responds again, named people will reload here."})}function W2(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;S2(e,{operations:S.lastShareOperations,onAdvance:n=>EI(n),onLoadOperation:n=>NI(n),onReload:Sr});const t=document.getElementById("syncProjectShareOperationsMeta");t&&(t.textContent=S.shareOperationsLoadError?"Project sharing status could not be refreshed. Existing device diagnostics remain available below.":S.lastShareOperations.length>0?"Project access is grouped by Person. Devices appear after invitation acceptance.":"Share a project from Projects to invite a teammate.")}function cm(){const e=document.getElementById("syncPeers");if(!e)return;wr("syncPeersSkeleton");const t=S.lastSyncPeers,n=Array.isArray(t)?t:[];r2(S.syncPeersSectionFeedback,n)&&(S.syncPeersSectionFeedback=null),H2(e,{peers:n,onRename:async(r,i)=>{try{return await Qm(r,i),await Sr(),{message:"Device name saved.",tone:"success"}}catch(a){return{message:_t(a,"Failed to save device name."),tone:"warning"}}},onSync:async(r,i)=>{try{const a=String(r?.peer_device_id||""),s=await nd({address:i,peerDeviceId:a||void 0}),c=jS(s);let l;c.ok?a&&Yf(a)?l={message:`Triggered sync for ${r?.name||(a?a.slice(0,8):"unknown")}. ${om()?"Review legacy Space access and advanced rules in Coordinator Administration if this device needs tighter sharing.":"A coordinator operator can review legacy Space access and advanced rules in Coordinator Administration if this device needs tighter sharing."}`,tone:"warning"}:l={message:c.message,tone:"success"}:l={message:c.message,tone:"warning"};try{await Sr()}catch{l={message:"Sync started, but this view has not refreshed yet. Refresh the page or use Sync now again before retrying.",tone:"warning"}}return l}catch(a){return{message:_t(a,"Failed to trigger sync."),tone:"warning"}}},onRemove:async(r,i)=>{try{await Xm(r);const a={message:`Removed peer ${i}.`,tone:"success"};return S.syncPeerFeedbackById.delete(r),S.syncPeersSectionFeedback={...a,relatedPeerDeviceId:r},await Sr(),a}catch(a){return{message:_t(a,"Failed to remove peer. The local peer entry is still here."),tone:"warning"}}}})}function J2(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");sm(!0),t&&(t.textContent="People and device details are unavailable right now. Refresh this page to retry once local sync status is reachable again."),e&&ui(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. Named people will reload here once the local sync status endpoint responds again."}),n&&ui(n,{title:"Devices unavailable right now.",detail:"Refresh this page to retry. When sync is reachable again, paired devices will reload here so you can rename, inspect, or re-pair them."})}function dC(){const e=document.getElementById("syncLegacyClaims"),t=document.getElementById("syncLegacyDeviceSelectMount"),n=document.getElementById("syncLegacyClaimsMeta");if(!e||!t||!n)return;const r=Array.isArray(S.lastSyncLegacyDevices)?S.lastSyncLegacyDevices:[];A2({devices:r,meta:n,mount:t,onValueChange:i=>{i!==Rl&&(Rl=i,dC())},panel:e,value:Rl})}function Y2(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput"),r=document.getElementById("syncLegacyClaimButton");n?.addEventListener("keydown",i=>{ro(i,{onSubmit:()=>t?.click(),disabled:!t||t.disabled})}),t?.addEventListener("click",async()=>{if(!t||!n)return;const i=String(n.value||"").trim();if(!i){fa(n,"Enter a name for the person.");return}Ho(n),t.disabled=!0,n.disabled=!0,t.textContent="Creating…";try{await FI(i),X("Person created."),n.value="",await e()}catch(a){X(_t(a,"Failed to create person."),"warning"),t.textContent="Retry",t.disabled=!1,n.disabled=!1;return}t.textContent="Create person",t.disabled=!1,n.disabled=!1}),r?.addEventListener("click",async()=>{const i=String(Rl||"").trim();if(!i||!r||!await vn({title:`Attach history from ${i}?`,description:"This updates legacy provenance so the older device history is attached to you on this device.",confirmLabel:"Attach history",cancelLabel:"Cancel",tone:"danger"}))return;r.disabled=!0;const a=r.textContent||"Attach device history";r.textContent="Attaching…";try{await UI(i),X("Old device history attached to you."),await e()}catch(s){X(_t(s,"Failed to attach old device history."),"warning"),r.textContent="Retry",r.disabled=!1;return}r.textContent=a,r.disabled=!1})}function X2(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function lm(e=X2()){const t=document.getElementById("syncMainView"),n=document.getElementById("syncDiagnosticsView");!t||!n||(e==="diagnostics"?(t.hidden=!0,n.hidden=!1):(t.hidden=!1,n.hidden=!0))}var uC=!1;function Q2(){uC||(uC=!0,window.addEventListener("hashchange",()=>{lm()}))}var _n={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function Z2(e){_n.loadSyncData=e}var eG=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function tG(){const e=document.getElementById("syncCreateInviteButton"),t=document.getElementById("syncInviteAdminHint");if(!e||!t)return;const n=S.lastSyncCoordinatorAdminStatus?.readiness;if(n==="ready"){e.disabled=!1,t.hidden=!1,t.textContent="Legacy Team/Space setup is ready. Technical controls are in Coordinator Administration.";return}const r=n==="partial"?"Finish legacy Team/Space setup before creating remote invites. Use Coordinator Administration to check what is missing.":"Configure a coordinator URL, group, and admin secret before creating remote invites. Use Coordinator Administration to finish legacy Team/Space setup.";e.disabled=!0,t.hidden=!1,t.textContent=r}function dm(){const e=document.getElementById("syncAdminDisclosureMount");e&&aU(e,{open:WS,onOpenChange:t=>{KU(t),dm(),kl(),um()}})}function nG(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function um(){const e=document.getElementById("syncInviteOutput"),t=document.getElementById("syncInviteWarnings");if(!e)return;const n=String(S.lastTeamInvite?.encoded||"").trim();if(e.value=n,e.hidden=!n,t){const r=Array.isArray(S.lastTeamInvite?.warnings)?S.lastTeamInvite.warnings:[];t.textContent=r.join(" · "),t.hidden=r.length===0}}function Il(){const e=document.getElementById("syncJoinFeedback");if(!e)return;const t=S.syncJoinFlowFeedback;e.textContent=t?.message||"",e.hidden=!t?.message,e.setAttribute("role",t?.tone==="warning"?"alert":"status"),e.setAttribute("aria-live",t?.tone==="warning"?"assertive":"polite"),e.className=`peer-meta${t?` ${t.tone==="warning"?"sync-inline-feedback warning":"sync-inline-feedback success"}`:""}`}function kl(){const e=document.getElementById("syncInvitePolicyMount");e&&mt(e,g(dr,{ariaLabel:"Join policy",contentClassName:"sync-radix-select-content sync-actor-select-content",id:"syncInvitePolicy",itemClassName:"sync-radix-select-item",onValueChange:t=>{const n=t==="approval_required"?"approval_required":"auto_admit";n!==_n.invitePolicy&&(_n.invitePolicy=n,kl())},options:eG,triggerClassName:"sync-radix-select-trigger sync-actor-select",value:_n.invitePolicy,viewportClassName:"sync-radix-select-viewport"}))}function rG(e,t){dm(),kl();const n=document.getElementById("syncNowButton"),r=document.getElementById("syncShareProjectsButton"),i=document.getElementById("syncCreateInviteButton"),a=document.getElementById("syncInviteGroup"),s=document.getElementById("syncInviteTtl"),c=document.getElementById("syncInviteOutput"),l=document.getElementById("syncJoinButton"),d=document.getElementById("syncJoinInvite"),u=document.getElementById("syncProjectInviteReview"),p=document.getElementById("syncProjectInviteContext"),f=document.getElementById("syncProjectInviteReviewHeading"),m=document.getElementById("syncRecipientName"),v=document.getElementById("syncRecipientDeviceName");let b="",h,y=0;r?.addEventListener("click",()=>{As()||X("Project sharing is unavailable. Refresh Projects and try again.","warning")});const w=async(_,R)=>{if(!u||!m||!v)return"other";const I=await Ym(_);if(R!==y||d?.value.trim()!==_)return"stale";if(h=I.kind,I.kind!=="project_share_invite")return"other";const T=(I.projects??[]).map(A=>`${A.display_name} (${A.existing_memory_count} existing ${A.existing_memory_count===1?"memory":"memories"})`).join(", ");return p&&(p.textContent=`${I.inviter_name||"A teammate"} invited you${I.team_name?` through ${I.team_name}`:""} to share ${T||"selected projects"}.`),m.value=Li(I.recipient_name),v.value=Li(I.device_name),u.hidden=!1,b=_,l&&(l.textContent="Accept and start syncing"),f?.focus(),"project"};d?.addEventListener("input",()=>{y+=1,d.value.trim()!==b&&(b="",h=void 0,u&&(u.hidden=!0),l&&(l.textContent="Review invite"))}),i?.addEventListener("click",async()=>{if(!i||!a||!s||!c||i.disabled)return;const _=a.value.trim(),R=Number(s.value);let I=!0;if(_?Ho(a):I=fa(a,"Team name is required."),!R||R<1?I=fa(s,"Must be at least 1 hour."):Ho(s),!!I){i.disabled=!0,i.textContent="Creating…";try{const T=await Vm({group_id:_,policy:_n.invitePolicy,ttl_hours:R||24});S.lastTeamInvite=T,um(),c.value=String(T.encoded||""),c.hidden=!1,c.focus(),c.select();const A=Array.isArray(T.warnings)?T.warnings:[];X(A.length?`Invite created. Copy it above and review ${A.length===1?"1 warning":`${A.length} warnings`}.`:"Invite created. Copy the text above and share it with your teammate.",A.length?"warning":"success")}catch(T){X(_t(T,"Failed to create invite. Check the team name, invite lifetime, and coordinator reachability, then try again."),"warning"),i.textContent="Retry",i.disabled=!1;return}finally{i.disabled&&(i.disabled=!1,i.textContent="Create invite")}}}),d?.addEventListener("keydown",_=>{ro(_,{onSubmit:()=>l?.click(),disabled:!l||l.disabled})}),l?.addEventListener("click",async()=>{if(!l||!d)return;const _=d.value.trim();if(!_){fa(d,"Paste a team invite or pairing payload.");return}if(Ho(d),b!==_){const I=y;try{const T=await w(_,I);if(T==="project"||T==="stale")return}catch{}if(I!==y||d.value.trim()!==_)return;b=_,l.textContent="Accept invite";return}const R=u&&!u.hidden?{recipient_name:m?.value.trim()??"",device_name:v?.value.trim()??""}:void 0;if(R){const I=T=>Li(T)==="";if(I(R.recipient_name)){m&&fa(m,"Enter a human-readable name using 120 characters or fewer.");return}if(I(R.device_name)){v&&fa(v,"Enter a human-readable device name using 120 characters or fewer.");return}}l.disabled=!0,l.textContent="Accepting…";try{const I=await Yl(_,R,h);S.lastTeamJoin=I;const T=I,A=typeof T.type=="string"?T.type:"team_join";let L;if(A==="pair"){const F=String(I.peer_device_id??"").trim();L={message:F?`Paired with device ${F.slice(0,8)}. It will appear in People & devices.`:"Paired the device. It will appear in People & devices.",tone:"success"}}else if(A==="project_share"){const F=T.restart_required===!0||T.setup_state==="pending_inviter"||I.status==="pending_setup",N=typeof T.detail=="string"?T.detail.trim():"";L=F?{message:N||(T.restart_required===!0?"Project invitation accepted. Restart codemem to finish setup.":T.setup_state==="pending_inviter"?"Project invitation accepted. Waiting for the inviter to finish setup.":"Project invitation accepted. Setup is still pending."),tone:"warning"}:{message:"Project invitation accepted.",tone:"success"}}else L={message:I.status==="pending"?"Join request sent. Waiting for admin approval.":"Joined the team.",tone:"success"};S.syncJoinFlowFeedback=L,Il(),d.value="",b="",u&&(u.hidden=!0);try{await t()}catch(F){L={message:_t(F,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},S.syncJoinFlowFeedback=L,Il()}}catch(I){S.syncJoinFlowFeedback={message:_t(I,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},Il(),l.textContent="Retry",l.disabled=!1;return}finally{l.disabled&&(l.disabled=!1,l.textContent="Review invite")}}),n?.addEventListener("click",async()=>{if(n){n.disabled=!0,n.textContent="Syncing…";try{const _=await nd(),R=jS(_);X(R.message,R.warning?"warning":void 0)}catch(_){X(_t(_,"Failed to start sync. Retry once, then run codemem sync doctor if the problem keeps coming back."),"warning"),n.textContent="Retry",n.disabled=!1;return}n.disabled=!1,n.textContent="Sync now",e()}})}function pm({element:e,hidden:t=!1,restoreParent:n=null}){const r=B(null);return Tt(()=>{e&&(e.hidden=t)},[e,t]),Tt(()=>{const i=r.current;if(!(!i||!e))return e.parentElement!==i&&i.appendChild(e),()=>{!n||e.parentElement!==i||n.appendChild(e)}},[e,n]),o("div",{ref:r})}function iG({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:r}){return o(z,{children:[o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:["Invite a teammate.",o("span",{className:"sync-action-command",children:"Generate an invite when you want someone else to join this team from their device."})]}),o("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide invite form":"Invite a teammate"})]}),e?o(pm,{element:e,hidden:!t,restoreParent:n}):null]})}function aG(){return o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:["Pair another device.",o("span",{className:"sync-action-command",children:"Copy a pairing command when you want to connect another one of your own devices."})]}),o("button",{type:"button",className:"settings-button sync-action-copy",onClick:e=>Va("codemem sync pair --payload-only",e.currentTarget),children:"Copy pairing command"})]})}function oG({joinPanel:e,joinPanelOpen:t,joinRestoreParent:n,onToggle:r}){return o(z,{children:[o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:["Accept an invite or pairing.",o("span",{className:"sync-action-command",children:"Paste a team invite to join another team, or a pairing payload to connect another device."})]}),o("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide paste form":"Paste invite or pairing"})]}),e?o(pm,{element:e,hidden:!t,restoreParent:n}):null]})}function sG({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,joinPanel:r,joinPanelOpen:i,joinRestoreParent:a,onToggleInvitePanel:s,onToggleJoinPanel:c,pairedPeerCount:l,presenceStatus:d}){const u=d==="not_enrolled";return o(z,{children:[u?o(z,{children:[o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:["Join this device.",o("span",{className:"sync-action-command",children:"Paste a team invite or pairing payload below to join an existing team or connect another of your devices."})]})}),r?o(pm,{element:r,hidden:!1,restoreParent:a}):null,o("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0}),o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:["This device is not on the team yet.",o("span",{className:"sync-action-command",children:"Use Join this device above, or ask an admin to enroll it first."})]})})]}):o(z,{children:[o(oG,{joinPanel:r,joinPanelOpen:i,joinRestoreParent:a,onToggle:c}),o("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),u?null:o(iG,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:s}),!l&&d==="posted"?o(aG,{}):null]})}function Tl({count:e,label:t}){return o("div",{className:"sync-section-heading",children:[o("div",{className:"sync-action-text sync-section-label",children:t}),e?o("span",{className:"badge actor-badge sync-section-count",children:e}):null]})}function Pl({children:e}){return o("div",{className:"section-meta sync-section-note",children:e})}function cG({item:e,onAction:t}){const[n,r]=D(!1);return o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:[e.title,o("span",{className:"sync-action-command",children:e.summary})]}),o("button",{type:"button",className:"settings-button",disabled:n,onClick:async()=>{r(!0);try{await t(e)}finally{r(!1)}},children:e.actionLabel||"Review"})]})}function lG({request:e,onApprove:t,onDeny:n}){const[r,i]=D(null),[a,s]=D(null),[c,l]=D("Approve"),[d,u]=D("Deny");return o("div",{className:"actor-row",children:[o("div",{className:"actor-details",children:o("div",{className:"actor-title",title:e.requestId||void 0,children:e.displayName})}),o("div",{className:"actor-actions",children:[o("button",{type:"button",className:"settings-button","aria-label":`${c} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("approve"),l("Approving…");try{s(await t(e)||null),l("Approve")}catch{l("Retry")}finally{i(null)}},children:c}),o("button",{type:"button",className:"settings-button","aria-label":`${d} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("deny"),u("Denying…");try{s(await n(e)||null),u("Deny")}catch{u("Retry")}finally{i(null)}},children:d})]}),o(fi,{feedback:a})]})}function dG({row:e,onInspectConflict:t,onRemoveConflict:n,onReview:r}){const[i,a]=D(null),[s,c]=D(null),l=e.actionLabel||"Pair with this device",[d,u]=D(l),[p,f]=D("Remove broken device record");return o("div",{className:"peer-card peer-card--padded","data-discovered-device-id":e.deviceId,children:[o("div",{className:"peer-title",children:[o("strong",{title:e.displayTitle||void 0,children:e.displayName}),o("span",{className:`badge actor-badge${e.availabilityLabel==="Offline"?"":" local"}`,children:e.availabilityLabel}),o("span",{className:"badge actor-badge",children:e.connectionLabel}),e.approvalBadgeLabel?o("span",{className:"badge actor-badge",children:e.approvalBadgeLabel}):null]}),o("div",{className:"peer-meta",children:e.note}),o("div",{className:"peer-actions",children:[e.mode==="accept"?o("button",{type:"button",className:"settings-button","aria-label":`${d} for ${e.displayName}`,disabled:i!==null,onClick:async()=>{a("review"),u("Pairing…"),c({message:`Pairing ${e.displayName}. Keep this page open while the device is approved and refreshed.`,tone:"success"});try{const m=await r(e)||null;c(m),u(m?.tone==="warning"?"Retry":e.actionLabel||l)}catch{c({message:`Pairing ${e.displayName} failed. Try again.`,tone:"warning"}),u("Retry")}finally{a(null)}},children:d}):null,(e.mode==="stale"||e.mode==="approval-pending"||e.mode==="ambiguous"||e.mode==="scope-pending"||e.mode==="setup-blocked")&&e.actionMessage?o("div",{className:"peer-meta",children:e.actionMessage}):null,e.mode==="paired"&&e.pairedMessage?o("div",{className:"peer-meta",children:e.pairedMessage}):null,e.mode==="conflict"?o(z,{children:[o("button",{type:"button",className:"settings-button","aria-label":`Open details for ${e.displayName}`,disabled:i!==null,onClick:()=>t(e),children:"Open device details"}),o("button",{type:"button",className:"settings-button danger","aria-label":`${p} for ${e.displayName}`,disabled:i!==null,onClick:async()=>{a("remove"),f("Removing…");try{c(await n(e)||null),f("Remove broken device record")}catch{f("Retry")}finally{a(null)}},children:p})]}):null]}),o(fi,{feedback:s})]})}function uG(e){const t=e.actionItems.length>0,n=e.actionableCount>e.actionItems.length,r=t||n||e.primaryStatus.state!=="healthy";return o(z,{children:[r?o(Tl,{label:"Needs attention"}):null,r?o(Pl,{children:"Start here when something needs review, re-pairing, or approval."}):null,e.primaryStatus.nextAction?o("div",{className:"sync-action","data-primary-sync-state":e.primaryStatus.state,children:o("div",{className:"sync-action-text",children:[e.primaryStatus.badgeLabel,o("span",{className:"sync-action-command",children:e.primaryStatus.nextAction})]})}):null,t?e.actionItems.map(i=>o(cG,{item:i,onAction:e.onAttentionAction},i.id)):null,!t&&!n&&e.primaryStatus.state==="healthy"?o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:"No urgent team work right now."})}):null,!t&&n?o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:"More team follow-up is listed below when you are ready."})}):null]})}function pG({children:e}){return e?o(z,{children:[o(Tl,{label:"Add devices & teammates"}),o(Pl,{children:"Use these flows when you are enrolling, inviting, or pairing something new."}),e]}):null}function fG({mount:e,rows:t,onInspectConflict:n,onRemoveConflict:r,onReview:i}){return!e||!t.length&&!S.syncDiscoveredFeedback?null:ln(o(z,{children:[o(Tl,{count:t.length||void 0,label:"Devices waiting for review"}),o(Pl,{children:"Review team devices here when they still need trust, re-pairing, or approval on this machine."}),o(fi,{feedback:S.syncDiscoveredFeedback}),t.map(a=>o(dG,{row:a,onInspectConflict:n,onRemoveConflict:r,onReview:i},`${a.deviceId}:${a.incomingRequestId}:${a.fingerprint}`))]}),e)}function mG({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!S.syncJoinRequestsFeedback?null:ln(o(z,{children:[o(Tl,{count:t.length||void 0,label:"Join requests to review"}),o(Pl,{children:"Approve or deny requests here before those devices become part of the team."}),o(fi,{feedback:S.syncJoinRequestsFeedback}),t.map(i=>o(lG,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function pC(e){return o(z,{children:[o(uG,{...e}),o(pG,{children:e.children}),o(mG,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),o(fG,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function fC(e){e&&(e.textContent="")}function Nl(e){e instanceof HTMLElement&&(e.classList.remove("sync-attention-target"),e.offsetWidth,e.classList.add("sync-attention-target"),window.setTimeout(()=>e.classList.remove("sync-attention-target"),900))}function hG(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Vo(){return hG()?"auto":"smooth"}var fm="syncTeamActionsMount",gG="Approval sent for this device. This screen may take up to 30 seconds to confirm two-way trust.";function vG(e,t,n=!1){return e.length>1&&(!t||n)}function yG(e,t,n){e.hidden=!1,e.textContent=n.badgeLabel,t.textContent=n.meta,n.state==="healthy"?e.className="sync-online-badge":n.state==="disabled"||n.state==="pending-setup"||n.state==="not-enrolled"||n.state==="reachable"?e.className="sync-online-badge sync-online-offline":e.className="sync-online-badge sync-online-error"}function bG(e,t){const n=document.createElement("div");n.id=fm,e.appendChild(n),mt(n,g(pC,{actionItems:[],actionableCount:0,discoveredListMount:null,discoveredRows:[],joinRequestsMount:null,onApproveJoinRequest:async()=>null,onAttentionAction:async()=>{},onDenyJoinRequest:async()=>null,onInspectConflict:()=>{},onRemoveConflict:async()=>null,onReviewDiscoveredDevice:async()=>null,pendingJoinRequests:[],presenceStatus:"unknown",primaryStatus:t}))}function mC(e,t){const n=document.getElementById(fm);n&&(da(n),n.remove()),fC(e),t.forEach(r=>{fC(r)})}function Ko(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;dm(),kl(),um(),Il(),tG();const r=document.getElementById("syncInvitePanel"),i=document.getElementById("syncAdminSection"),a=document.getElementById("syncJoinPanel"),s=document.getElementById("syncJoinSection"),c=document.getElementById("syncJoinRequests"),l=document.getElementById("syncCoordinatorDiscovered"),d=document.getElementById("syncCoordinatorDiscoveredMeta"),u=document.getElementById("syncCoordinatorDiscoveredList");wr("syncTeamSkeleton"),nG();const p=S.lastSyncCoordinator,f=S.lastSyncViewModel||{primaryStatus:VS({status:S.lastSyncStatus,coordinator:p,peers:S.lastSyncPeers,shareOperations:S.lastShareOperations,shareOperationsLoadError:S.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]},m=E=>{if(E.kind==="possible-duplicate-person"){const G=document.getElementById("syncActorsList");G instanceof HTMLElement&&(G.scrollIntoView({block:"center",behavior:Vo()}),Nl(G));return}const C=String(E.deviceId||"").trim();if(!C)return;if(E.kind==="name-device"){const G=document.querySelector(`[data-device-name-input="${CSS.escape(C)}"]`);if(G instanceof HTMLInputElement){G.scrollIntoView({block:"center",behavior:Vo()}),G.focus(),G.select(),Nl(G);return}}const O=document.querySelector(`[data-peer-device-id="${CSS.escape(C)}"]`);if(O instanceof HTMLElement){O.scrollIntoView({block:"center",behavior:Vo()}),Nl(O);return}const H=document.querySelector(`[data-discovered-device-id="${CSS.escape(C)}"]`);H instanceof HTMLElement&&(H.scrollIntoView({block:"center",behavior:Vo()}),Nl(H))},v=async E=>{const C=Array.isArray(E.actorIds)?E.actorIds.map(Z=>String(Z||"").trim()).filter(Boolean):[],O=(Array.isArray(S.lastSyncActors)?S.lastSyncActors:[]).filter(Z=>C.includes(String(Z?.actor_id||"").trim()));if(O.length<2){X("This duplicate review is outdated. Refresh the card and review the remaining people entries.","warning");return}const H=await IL({title:"Review possible duplicate people",summary:E.title.replace(/^Possible duplicate person:\s*/,""),actors:O.map(Z=>({actorId:String(Z?.actor_id||""),label:String(Z?.display_name||Z?.actor_id||"Unknown person"),isLocal:!!Z?.is_local}))});if(H.action==="different-people"){e2(C,"different-people"),X("Okay. I will keep these people separate on this device."),await _n.loadSyncData();return}if(H.action!=="merge")return;const G=O.find(Z=>String(Z?.actor_id||"")===H.primaryActorId),ee=O.find(Z=>String(Z?.actor_id||"")===H.secondaryActorId);if(!G?.actor_id||!ee?.actor_id){X("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await fh(String(G.actor_id),String(ee.actor_id)),t2(C),X(`Combined duplicate people into ${String(G.display_name||G.actor_id)}.`),await _n.loadSyncData()}catch(Z){try{await _n.loadSyncData()}catch{}X(_t(Z,"Failed to combine these people."),"warning")}},b=async E=>await Tp({title:"Pair with this device",description:"Choose a friendly name for this device before pairing it on this machine.",initialValue:E,placeholder:"Desk Mini",confirmLabel:"Pair",cancelLabel:"Cancel",validate:C=>C.trim()?null:"Enter a device name to pair this device."}),h=!!p?.configured,y=GU(p);e.title=h?String(p.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?yG(w,e,f.primaryStatus):e.textContent=f.primaryStatus.meta,!h){mC(n,[c,u]),t.hidden=!1,n.hidden=!1,bG(n,f.primaryStatus),c&&(c.hidden=!0),l&&(l.hidden=!0);return}t.hidden=!0,n.hidden=!1;const _=String(p.presence_status||""),R=Array.isArray(S.lastSyncPeers)?S.lastSyncPeers:[],I=Array.isArray(f.attentionItems)?f.attentionItems:[],T=Array.isArray(p.discovered_devices)?p.discovered_devices:[],A=String(p.coordinator_url||"").trim(),L=T.map(E=>{const C=String(E.device_id||"").trim(),O=String(E.display_name||"").trim(),H=MS({coordinatorName:O,deviceId:C})||"Discovered device",G=C&&H!==C?C:null,ee=String(E.fingerprint||"").trim(),Z=String(E.incoming_reciprocal_request_id||"").trim(),ie=Array.isArray(E.groups)?E.groups.map(Je=>String(Je||"").trim()).filter(Boolean):[],fe=R.find(Je=>String(Je?.peer_device_id||"")===C),Ce=vG(ie,!!fe,E.needs_local_approval===!0),Pe=$S({device:E,pairedLocally:!!fe}),Ne=String(fe?.fingerprint||"").trim(),ce=!!fe&&!!ee&&!!Ne&&Ne!==ee,me=S.pendingCoordinatorApprovalsByDeviceId.get(C),J=E.needs_local_approval===!0&&me?.coordinatorUrl===A&&me?.incomingRequestId===Z,se=J?"approval-pending":E.needs_local_approval===!0?"needs-local-approval":"not-required",ye=!J&&!y&&dU({device:E,hasAmbiguousCoordinatorGroup:Ce,pairedLocally:!!fe}),le=Array.isArray(E.addresses)?E.addresses:[],Ee=Number(E.address_count??0),re=Number.isFinite(Ee)&&Ee>0?Ee:0,Q=[le.length?le.map(Je=>za()?ZS(String(Je||"")):String(Je||"")).filter(Boolean).join(" · "):re>0?`${re} ${E.stale?"last-known":"fresh"} ${re===1?"address":"addresses"} hidden`:"No fresh addresses"];!le.length&&G&&Q.push(`device id: ${C}`);let we=null,ae=ye?"accept":"none",Fe=null;return ce?ae="conflict":J?(we="Waiting for refreshed coordinator status. You do not need to approve again.",ae="approval-pending"):y&&(!fe||Pe.state==="needs-your-approval")?(we=y.message,ae="setup-blocked"):Ce?(we="This device appears in multiple coordinator groups. Review legacy Team/Space setup before approving it here.",ae="ambiguous"):fe&&Yf(C)?(we="Review this device's legacy Space access and advanced rules in Coordinator Administration before you sync it.",ae="scope-pending"):fe?.last_error?(Q.push(`error: ${String(fe.last_error)}`),ye||(ae="paired")):fe?.status?.peer_state?(Q.push(`status: ${String(fe.status.peer_state)}`),ye||(ae="paired")):!fe&&E.stale?(we="Wait for a fresh coordinator presence update, then review this device again here.",ae="stale"):fe&&!ye&&(ae="paired"),ae==="paired"&&(Fe=Pe.state==="waiting-for-other-device"?Pe.description||"Waiting on the other device.":String(fe?.last_error||"").toLowerCase().includes("401")&&String(fe?.last_error||"").toLowerCase().includes("unauthorized")?"Waiting for the other device to trust this one before sync can work.":null),{actionMessage:we,actionLabel:Pe.actionLabel||(fe?"Review device":"Pair with this device"),approvalBadgeLabel:J?"Approval sent":Pe.badgeLabel,approvalState:se,availabilityLabel:E.stale?"Offline":"Available",connectionLabel:ce?zS.conflicts:fe?zS.pairedLocally:"Not connected on this device",coordinatorUrl:A,deviceId:C,displayName:H,displayTitle:G,fingerprint:ee,groupId:ie[0]??"",incomingRequestId:Z,mode:ae,note:Q.join(" · "),pairedMessage:Fe}}),F=new Set(L.filter(E=>E.approvalState==="approval-pending").map(E=>E.deviceId)),N=I.filter(E=>!E.deviceId||!F.has(E.deviceId)),j=[],x=L.filter(E=>E.mode!=="paired"&&E.mode!=="none"&&E.mode!=="scope-pending"),U=L.filter(E=>E.mode==="accept"||E.mode==="scope-pending").length,q=N.length+j.length+U;l&&(l.hidden=x.length===0&&!S.syncDiscoveredFeedback),d&&(d.textContent=x.length?"Pair with a teammate's device to see it appear in People & devices and start syncing.":""),c&&(c.hidden=j.length===0&&!S.syncJoinRequestsFeedback),mC(n,[c,u]);const $=document.createElement("div");$.id=fm,n.appendChild($),mt($,g(pC,{actionItems:N,actionableCount:q,children:g(sG,{invitePanel:r,invitePanelOpen:Kf,inviteRestoreParent:i,joinPanel:a,joinPanelOpen:zf,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(zU(!Kf),Ko())},onToggleJoinPanel:()=>{a&&(WU(!zf),Ko())},pairedPeerCount:Number(p.paired_peer_count||0),presenceStatus:_}),discoveredListMount:u,discoveredRows:x,joinRequestsMount:c,onApproveJoinRequest:async()=>null,onAttentionAction:async E=>{if(E.kind==="possible-duplicate-person"){await v(E);return}m(E)},onDenyJoinRequest:async()=>null,onInspectConflict:E=>{const C=document.querySelector(`[data-peer-device-id="${CSS.escape(E.deviceId)}"]`);if(C instanceof HTMLElement){C.scrollIntoView({block:"center",behavior:Vo()}),X(`Opened the conflicting local device record for ${E.displayName}.`,"warning");return}X("The conflicting local device record is not visible yet. Scroll to People & devices and try again.","warning")},onRemoveConflict:async E=>{if(!await vn({title:`Remove ${E.displayName}?`,description:"This deletes the broken local device record. You can review this device again after the screen refreshes.",confirmLabel:"Remove device record",cancelLabel:"Keep device record",tone:"danger"}))return null;try{await Xm(E.deviceId);const C={message:`Removed the broken local device record for ${E.displayName}. If it is still available, review it again from Next steps or Devices seen on team.`,tone:"success"};return S.syncDiscoveredFeedback=C,await _n.loadSyncData(),C}catch(C){return{message:_t(C,"Failed to remove the broken local device record. The old local record is still present in People & devices."),tone:"warning"}}},onReviewDiscoveredDevice:async E=>{try{const C=await b(E.displayName);return C?await _G(E,C):null}catch(C){return{message:_t(C,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:j,presenceStatus:_,primaryStatus:f.primaryStatus}))}async function _G(e,t){const n=e.approvalState==="needs-local-approval",r=e.deviceId.trim(),i=e.coordinatorUrl.trim(),a=e.groupId.trim(),s=e.incomingRequestId.trim();if(n&&(!r||!i||!a||!s))throw new Error("Device identity is incomplete. Refresh the screen and try approval again.");const c=await QR(e.deviceId,{fingerprint:e.fingerprint,expectedGroupId:a||void 0,expectedIncomingRequestId:n?s:void 0}),l=String(c?.name||e.displayName||"").trim()||e.displayName;n&&S.pendingCoordinatorApprovalsByDeviceId.set(r,{coordinatorUrl:i,incomingRequestId:s});const d=Array.isArray(S.pendingAcceptedSyncPeers)?S.pendingAcceptedSyncPeers.filter(p=>String(p?.peer_device_id||"").trim()!==e.deviceId):[];S.pendingAcceptedSyncPeers=[...d,{peer_device_id:e.deviceId,name:l,fingerprint:e.fingerprint,addresses:[],claimed_local_actor:!1,status:{peer_state:"degraded"},last_error:"Waiting for the other device to approve this one."}],YU(e.deviceId);let u=n?{message:gG,tone:"success"}:{message:`Step 1 complete on this device for ${e.displayName}. Finish onboarding on the other device so both sides trust each other for sync.`,tone:"success"};S.syncDiscoveredFeedback=u,n&&Ko();try{t.trim()!==l.trim()&&(await Qm(e.deviceId,t.trim()),S.pendingAcceptedSyncPeers=S.pendingAcceptedSyncPeers.map(p=>String(p?.peer_device_id||"").trim()===e.deviceId?{...p,name:t.trim()}:p),n||(u={message:`Connected ${t.trim()} and saved its name.`,tone:"success"}))}catch(p){u={message:n?"Approval was sent, but naming did not finish. You do not need to approve again.":_t(p,"Device connected, but naming did not finish."),tone:"warning"}}S.syncDiscoveredFeedback=u;try{await _n.loadSyncData()}catch(p){u={message:n?"Approval was sent. Confirmation may take up to 30 seconds, and you do not need to approve again.":_t(p,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},S.syncDiscoveredFeedback=u}return u}function wG(e){switch(e){case"cwd":return"Matched by folder";case"git_remote":return"Matched by git remote";case"workspace_id":return"Matched by workspace";case"project":return"Matched by project name";case"unmapped":return"Missing project identity";default:return`Matched by ${e.replace(/_/g," ")}`}}function ma(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function hC(e){return ma(e)?"Unclear project identity":e.displayProject}function Kt(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function SG(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function CG(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function RG(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function IG(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function kG(e){if(!e)return"date unavailable";const t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat("en-US",{day:"numeric",month:"short",timeZone:"UTC",year:"numeric"}).format(t)}function TG(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function PG({group:e}){const t=e.memorySamples??[],n=t.length;return o("details",{className:"legacy-review-samples",children:[o("summary",{children:["Inspect affected memories",n?` (${n} sample${n===1?"":"s"})`:""]}),o("div",{className:"legacy-review-cleanup-note",children:"Showing representative memories from this project group before reassignment. Local memories can be reassigned; peer-owned memories stay in review on this device."}),t.length>0?o("ul",{className:"legacy-review-sample-list",children:t.map(r=>o("li",{className:"legacy-review-sample",children:[o("div",{className:"legacy-review-sample-title",children:r.title}),o("div",{className:"legacy-review-group-meta",children:[r.kind||"memory"," · ",kG(r.updatedAt??r.createdAt)," ","·"," ",r.ownership==="local"?"local, reassignable":"peer-owned, stays in review"]}),r.bodyPreview?o("div",{className:"legacy-review-sample-body",children:r.bodyPreview}):null,o("div",{className:"legacy-review-group-meta mono",children:TG(r)})]},r.id))}):o("div",{className:"legacy-review-cleanup-note",children:"No samples are available for this group. Refresh Sync and try again before reassigning."})]})}function gC(e,t,n){let r=(e instanceof Error?e.message:"Unable to reassign legacy review memories.").replace(/sharing domain/gi,"Space");return t&&(r=r.replace(new RegExp(`\\b${CG(t)}\\b`,"g"),RG(t,n))),r}function NG(e,t){const n=e.suggestedScopeId?t.find(r=>r.scopeId===e.suggestedScopeId)?.label:"";return[e.displayProject,e.identitySource,e.suggestedScopeId??"",n??"",e.suggestionReason??"",e.workspaceIdentity].join(" ").toLowerCase()}function EG({item:e,onReview:t}){return o("div",{className:"actor-row",children:[o("div",{className:"actor-details",children:[o("div",{className:"actor-title",children:[o("strong",{children:e.peerName}),o("span",{className:"badge actor-badge",children:["person: ",e.actorDisplayName||e.actorId]})]}),o("div",{className:"peer-meta",children:[e.shareableCount," share by default · ",e.privateCount," marked Only me ·"," ",e.scopeLabel]})]}),o("div",{className:"actor-actions",children:o("button",{type:"button",className:"settings-button",onClick:t,children:"Review my memories in Feed"})})]})}function AG({item:e,onReassign:t,onReview:n}){const r=e.groups??[],i=e.targetScopes??[],a=Object.fromEntries(r.map(C=>[C.workspaceIdentity,C.suggestedScopeId??""])),[s,c]=D({}),[l,d]=D({}),[u,p]=D(a),[f,m]=D({}),[v,b]=D("all"),[h,y]=D(""),[w,_]=D(null),R=r.length,I=e.totalGroupCount??R,T=r.filter(ma).length,A=r.filter(C=>C.suggestedScopeId&&!ma(C)&&Kt(C)).length,L=r.filter(C=>f[C.workspaceIdentity]&&Kt(C)).length,F=r.filter(C=>f[C.workspaceIdentity]&&Kt(C)&&!!u[C.workspaceIdentity]).length,N=r.filter(C=>{const O=ma(C);return v==="suggested"&&(!C.suggestedScopeId||O)||v==="cleanup"&&!O||v==="no-suggestion"&&(C.suggestedScopeId||O)||v==="selected"&&!f[C.workspaceIdentity]?!1:!h.trim()||NG(C,i).includes(h.trim().toLowerCase())});async function j(C){const O=u[C.workspaceIdentity]||C.suggestedScopeId||"";if(!(!O||!t||w)){_(C.workspaceIdentity),d(H=>{const G={...H};return delete G[C.workspaceIdentity],G});try{const H=await t(C,O,!!s[C.workspaceIdentity],s[C.workspaceIdentity]?.confirmation_token);c(H?G=>({...G,[C.workspaceIdentity]:H}):G=>{const ee={...G};return delete ee[C.workspaceIdentity],ee})}catch(H){d(G=>({...G,[C.workspaceIdentity]:gC(H,O,i)}))}finally{_(null)}}}function x(C,O){p(H=>({...H,[C.workspaceIdentity]:O})),c(H=>{const G={...H};return delete G[C.workspaceIdentity],G}),d(H=>{const G={...H};return delete G[C.workspaceIdentity],G})}function U(C,O){m(H=>({...H,[C.workspaceIdentity]:O}))}function q(C){m(O=>({...O,...Object.fromEntries(N.filter(Kt).map(H=>[H.workspaceIdentity,C]))}))}function $(){m(C=>({...C,...Object.fromEntries(r.filter(O=>O.suggestedScopeId&&!ma(O)&&Kt(O)).map(O=>[O.workspaceIdentity,!0]))}))}async function E(){if(!t||w||F===0)return;const C=r.filter(O=>f[O.workspaceIdentity]&&Kt(O)&&!!u[O.workspaceIdentity]);if(!C.every(O=>s[O.workspaceIdentity])){_("bulk");try{for(const O of C){if(s[O.workspaceIdentity])continue;const H=u[O.workspaceIdentity]||O.suggestedScopeId||"";if(H)try{const G=await t(O,H,!1);d(ee=>{const Z={...ee};return delete Z[O.workspaceIdentity],Z}),G&&c(ee=>({...ee,[O.workspaceIdentity]:G}))}catch(G){d(ee=>({...ee,[O.workspaceIdentity]:gC(G,H,i)}))}}}finally{_(null)}}}return o("div",{className:"legacy-review-card",children:[o("div",{className:"legacy-review-header",children:[o("div",{children:[o("div",{className:"actor-title",children:[o("strong",{children:"Legacy shared review"}),o("span",{className:"badge badge-offline",children:"Needs project review"})]}),o("div",{className:"peer-meta legacy-review-summary",children:[I.toLocaleString()," older"," ",I===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",R<I?` Showing ${R.toLocaleString()} projects; open Projects to review the rest.`:""]}),o("div",{className:"peer-meta legacy-review-warning",children:"Fix peer-owned projects on their source device. Reassignment updates future sync authorization; online compatible peers should converge after syncing, but offline devices, backups, copied databases, malicious peers, or old versions may retain old copies."})]}),o("div",{className:"actor-actions",children:o("button",{type:"button",className:"settings-button",onClick:n,children:"Manage all projects"})})]}),o("div",{className:"legacy-review-toolbar",children:[o("div",{className:"legacy-review-filter-row",children:[["all",`Showing ${R.toLocaleString()}`],["suggested",`Suggested ${A.toLocaleString()}`],["cleanup",`Needs cleanup ${T.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${F.toLocaleString()}`]].map(([C,O])=>o("button",{className:v===C?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>b(C),type:"button",children:O},C))}),o("div",{className:"legacy-review-bulk-row",children:[o("input",{"aria-label":"Search legacy project groups",className:"peer-scope-input legacy-review-search",onInput:C=>y(C.currentTarget.value),placeholder:"Search project, signal, or destination…",value:h}),o("button",{className:"settings-button",onClick:()=>q(!0),type:"button",children:"Select visible"}),o("button",{className:"settings-button",onClick:$,type:"button",children:"Select suggested"}),o("button",{className:"settings-button",onClick:()=>q(!1),type:"button",children:"Clear visible"}),t&&i.length>0?o("button",{className:"settings-save",disabled:w!=null||F===0||r.filter(C=>f[C.workspaceIdentity]&&Kt(C)&&!!u[C.workspaceIdentity]).every(C=>s[C.workspaceIdentity]),onClick:()=>{E()},type:"button",children:w==="bulk"?"Previewing…":`Preview ${F.toLocaleString()} selected`}):t&&L>0?o("span",{className:"legacy-review-cleanup-note",children:"Add or join a Space before bulk reassignment."}):null,F>0&&r.filter(C=>f[C.workspaceIdentity]&&Kt(C)&&!!u[C.workspaceIdentity]).every(C=>s[C.workspaceIdentity])?o("span",{className:"legacy-review-cleanup-note",children:"Bulk actions only preview. Confirm each project individually to avoid partial reassignment."}):null]})]}),r.length>0?o("ul",{className:"legacy-review-groups","aria-label":"Legacy shared review project groups",children:N.map(C=>o("li",{className:"legacy-review-group",children:[o("div",{className:"legacy-review-group-main",children:[o("div",{className:"legacy-review-title-wrap",children:[o("input",{"aria-label":`Select ${hC(C)}`,checked:!!f[C.workspaceIdentity],className:"cm-checkbox",disabled:!Kt(C),onChange:O=>U(C,O.currentTarget.checked),type:"checkbox"}),o("div",{children:[o("div",{className:"legacy-review-group-title",children:hC(C)}),o("div",{className:"legacy-review-group-meta",children:[wG(C.identitySource),SG(C,i)]}),Kt(C)?C.peerOwnedMemoryCount?o("div",{className:"legacy-review-cleanup-note",children:[(C.reassignableMemoryCount??C.memoryCount).toLocaleString()," ","local memor",(C.reassignableMemoryCount??C.memoryCount)===1?"y":"ies"," ","can be reassigned; ",C.peerOwnedMemoryCount.toLocaleString()," peer-owned memor",C.peerOwnedMemoryCount===1?"y":"ies"," will stay in review."]}):null:o("div",{className:"legacy-review-cleanup-note",children:"Peer-owned only. These older memories were received from another device, so this device cannot reassign them to a Space. Assign this project to a Space on the source device; after sync, this review should clear here."}),ma(C)?o("div",{className:"legacy-review-cleanup-note",children:"Inspect or correct the project identity before assigning old shared data to a Space."}):null]})]}),o("span",{className:"legacy-review-count",children:[C.memoryCount.toLocaleString()," memor",C.memoryCount===1?"y":"ies"]})]}),C.suggestionReason?o("div",{className:"legacy-review-reason",children:C.suggestionReason}):null,l[C.workspaceIdentity]?o("div",{className:"legacy-review-confirmation",role:"alert",children:l[C.workspaceIdentity]}):null,s[C.workspaceIdentity]?o("div",{className:"legacy-review-confirmation",role:"alert",children:[s[C.workspaceIdentity].warning," This will reassign"," ",s[C.workspaceIdentity].reassignable_memory_count.toLocaleString()," of"," ",s[C.workspaceIdentity].memory_count.toLocaleString()," memories",s[C.workspaceIdentity].skipped_memory_count?`; ${s[C.workspaceIdentity].skipped_memory_count.toLocaleString()} peer-owned copies will be left unchanged`:"","."]}):null,o(PG,{group:C}),i.length>0&&t&&Kt(C)?o("label",{className:"legacy-review-target",children:[o("span",{children:"Destination Space"}),o("select",{className:"peer-scope-input",disabled:w!=null,onChange:O=>x(C,O.currentTarget.value),value:u[C.workspaceIdentity]||"",children:[o("option",{value:"",children:"Choose Space…"}),i.map(O=>o("option",{value:O.scopeId,children:[O.label," · ",IG(O.authorityType),O.scopeId===C.suggestedScopeId?" · suggested":""]},O.scopeId))]})]}):null,i.length>0&&t&&Kt(C)?o("div",{className:"legacy-review-actions",children:o("button",{type:"button",className:"settings-button",disabled:w!=null||!u[C.workspaceIdentity],onClick:()=>{j(C)},children:w===C.workspaceIdentity?s[C.workspaceIdentity]?"Reassigning…":"Previewing…":s[C.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},C.workspaceIdentity))}):null]})}function xG({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return o(z,{children:[t?o(AG,{item:t,onReassign:n,onReview:r??i}):null,e.map(a=>o(EG,{item:a,onReview:i},`${a.peerName}:${a.actorId}:${a.scopeLabel}`))]})}function DG(){Iy("mine"),S.feedQuery="",window.location.hash="feed"}function LG(){window.location.hash="projects"}async function $G(e,t,n,r){try{const i=await jI({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return S.lastSyncLegacySharedReview=i.legacy_shared_review??null,X(`Reassigned ${i.reassigned_memory_count.toLocaleString()} legacy review memor${i.reassigned_memory_count===1?"y":"ies"} to ${i.target_scope_label}.`),vC(),null}catch(i){if(i instanceof eh)return i.preview;const a=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw X(a,"warning"),new Error(a)}}function vC(){const e=document.getElementById("syncSharingReview"),t=document.getElementById("syncSharingReviewMeta"),n=document.getElementById("syncSharingReviewList");if(!e||!t||!n)return;const r=e.querySelector(".settings-group-title"),i=Array.isArray(S.lastSyncSharingReview)?S.lastSyncSharingReview:[],a=S.lastSyncLegacySharedReview,s=Math.max(0,Number(a?.memory_count??0)),c=a?.has_data?{groups:Array.isArray(a.groups)?a.groups.map(u=>{const p=u;return{displayProject:String(p.display_project||p.project||"Unknown project"),identitySource:String(p.identity_source||"unknown"),lastUpdatedAt:typeof p.last_updated_at=="string"?p.last_updated_at:null,memoryCount:Number(p.memory_count||0),memorySamples:Array.isArray(p.memory_samples)?p.memory_samples.map(f=>{const m=f,v=m.ownership==="peer"?"peer":"local";return{bodyPreview:typeof m.body_preview=="string"?m.body_preview:null,createdAt:typeof m.created_at=="string"?m.created_at:null,cwd:typeof m.cwd=="string"?m.cwd:null,gitRemote:typeof m.git_remote=="string"?m.git_remote:null,id:Number(m.id||0),kind:typeof m.kind=="string"?m.kind:null,ownership:v,project:typeof m.project=="string"?m.project:null,title:String(m.title||`Memory ${Number(m.id||0)}`),updatedAt:typeof m.updated_at=="string"?m.updated_at:null}}):[],peerOwnedMemoryCount:Number(p.peer_owned_memory_count||0),reassignableMemoryCount:Number(p.reassignable_memory_count||0),suggestedScopeId:typeof p.suggested_scope_id=="string"?p.suggested_scope_id:null,suggestionReason:typeof p.suggestion_reason=="string"?p.suggestion_reason:null,workspaceIdentity:String(p.workspace_identity||p.display_project||"unknown")}}):[],memoryCount:s,scopeId:String(a.scope_id||"legacy-shared-review"),totalGroupCount:Number(a.total_group_count||a.groups?.length||0),targetScopes:Array.isArray(a.target_scopes)?a.target_scopes.map(u=>{const p=u;return{authorityType:String(p.authority_type||"unknown"),label:String(p.label||p.scope_id||"Unknown domain"),scopeId:String(p.scope_id||"")}}).filter(u=>u.scopeId):[]}:null;if(!i.length&&!c){da(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=S.currentProject?`current project (${S.currentProject})`:"all allowed projects";t.textContent=c?`Review conservative upgrade state before promoting historical shared data. Teammates receive memories from ${l} by default once Sharing-domain grants allow it.`:`Teammates receive memories from ${l} by default. Use Only me on a memory when it should stay local.`;const d=i.map(u=>({actorDisplayName:String(u.actor_display_name||u.actor_id||"unknown"),actorId:String(u.actor_id||"unknown"),peerName:String(u.peer_name||u.peer_device_id||"Device"),privateCount:Number(u.private_count||0),scopeLabel:String(u.scope_label||"All allowed projects"),shareableCount:Number(u.shareable_count||0)}));mt(n,g(xG,{items:d,legacyReview:c,onLegacyReassign:$G,onLegacyReview:LG,onReview:DG}))}var El="";function jG(e){if(!e)return;const t=String(e?.coordinator_url||"").trim(),n=!!(e.lookup_error||e.reciprocal_approval_error),r=Array.isArray(e?.discovered_devices)?e.discovered_devices:[],i=new Map;for(const a of r){const s=String(a.device_id||"").trim();s&&i.set(s,[...i.get(s)||[],a])}for(const[a,s]of S.pendingCoordinatorApprovalsByDeviceId){if(s.coordinatorUrl!==t){S.pendingCoordinatorApprovalsByDeviceId.delete(a);continue}if(n)continue;const c=i.get(a);c&&(c.some(l=>String(l.incoming_reciprocal_request_id||"").trim()===s.incomingRequestId&&l.needs_local_approval===!0)||S.pendingCoordinatorApprovalsByDeviceId.delete(a))}}function OG(){return[...S.pendingCoordinatorApprovalsByDeviceId].map(([e,t])=>[e,t.coordinatorUrl,t.incomingRequestId]).sort(([e],[t])=>e.localeCompare(t))}var zo=null,mm=0,hm=null,gm=0,vm=null,MG=15e3;function yC(e){return`project:${e||""}|includeJoinRequests:false`}function FG(e){const t=yC(e);return!zo||zo.key!==t||Date.now()>=zo.expiresAtMs?null:zo.payload}function BG(e,t){zo={key:yC(e),expiresAtMs:Date.now()+MG,payload:t}}function qG(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function UG(){const e=document.getElementById("syncSharingReview"),t=document.getElementById("syncSharingReviewList"),n=document.getElementById("syncSharingReviewMeta"),r=document.getElementById("syncLegacyClaims"),i=document.getElementById("syncLegacyClaimsMeta");e&&(e.hidden=!0),t&&(t.textContent=""),n&&(n.textContent=""),r&&(r.hidden=!0),i&&(i.textContent="")}async function GG(e,t){if(S.activeTab==="health"&&!t.requireFreshSyncStatus){const r=FG(e);if(r)return{payload:r,fetchedFreshSyncStatus:!1}}const n=!za();return{payload:await Jl(n,e,{includeJoinRequests:!1,signal:t.signal}),fetchedFreshSyncStatus:!0}}function HG(e){return e.requiredSurface!=="all"?!0:e.actorLoadError||e.coordinatorAdminLoadError||e.shareOperationsLoadError?!1:!e.requiresDeviceIdentityInventory||!e.deviceIdentityInventoryLoadError}async function VG(e){const t=ZU();let n=null,r=null,i=S.lastDeviceIdentityInventory,a=S.lastShareOperations,s=!1,c=!1,l=S.deviceIdentityInventoryLoadError,d=!1;try{n=await YR({signal:e.signal})}catch{s=!0}try{r=await Kl({signal:e.signal})}catch{c=!0}if(S.activeTab==="advanced"){l=!1;try{i=await td({signal:e.signal})}catch{l=!0}}try{const u=await ph({signal:e.signal});a=Array.isArray(u.items)?u.items:[]}catch{d=!0}return{actorsPayload:n,coordinatorAdminStatus:r,deviceIdentityInventory:i,shareOperations:a,actorLoadError:s,coordinatorAdminLoadError:c,deviceIdentityInventoryLoadError:l,shareOperationsLoadError:d,duplicatePersonDecisions:t}}function Al(e={}){const t=KG(++mm,{requiredSurface:e.requiredSurface??"all",requireFreshSyncStatus:e.requireFreshSyncStatus??!1,signal:e.signal});return hm=t,t}async function KG(e,t){try{const n=S.currentProject||"",{payload:r,fetchedFreshSyncStatus:i}=await GG(n,t);if(t.signal?.aborted)return!1;const{actorsPayload:a,coordinatorAdminStatus:s,deviceIdentityInventory:c,shareOperations:l,actorLoadError:d,coordinatorAdminLoadError:u,deviceIdentityInventoryLoadError:p,shareOperationsLoadError:f,duplicatePersonDecisions:m}=await VG(t);if(e!==mm)return hm??!1;if(t.signal?.aborted)return!1;const v=HG({requiredSurface:t.requiredSurface,actorLoadError:d,coordinatorAdminLoadError:u,shareOperationsLoadError:f,requiresDeviceIdentityInventory:S.activeTab==="advanced",deviceIdentityInventoryLoadError:p});i&&BG(n,qG(r)),jG(r.coordinator);const b=JSON.stringify([r,a,s,c,p,l,f,m,OG()]);if(b===El)return v;El=b;const h=r.status&&typeof r.status=="object"?r.status:null;h&&(S.lastSyncStatus=h),Array.isArray(a?.items)?S.lastSyncActors=a.items:S.lastSyncActors=[];const y=Array.isArray(r.peers)?r.peers:[],w=new Set(y.map(R=>String(R?.peer_device_id||"").trim()).filter(Boolean)),_=Array.isArray(S.pendingAcceptedSyncPeers)?S.pendingAcceptedSyncPeers.filter(R=>{const I=String(R?.peer_device_id||"").trim();return I&&!w.has(I)}):[];return S.pendingAcceptedSyncPeers=_,S.lastSyncPeers=[...y,..._],p||(S.lastDeviceIdentityInventory=c),S.deviceIdentityInventoryLoadError=p,S.lastShareOperations=l,S.shareOperationsLoadError=f,S.lastSyncSharingReview=r.sharing_review||[],S.lastSyncLegacySharedReview=r.legacy_shared_review&&typeof r.legacy_shared_review=="object"?r.legacy_shared_review:null,S.lastSyncCoordinator=r.coordinator||null,S.lastSyncCoordinatorAdminStatus=s&&typeof s=="object"?s:null,S.lastSyncJoinRequests=Array.isArray(r.join_requests)?r.join_requests:[],S.lastSyncAttempts=r.attempts||[],S.lastSyncLegacyDevices=r.legacy_devices||[],S.lastSyncDuplicatePersonDecisions=m,S.lastSyncViewModel=VU({actors:S.lastSyncActors,peers:S.lastSyncPeers,coordinator:S.lastSyncCoordinator,status:h,shareOperations:S.lastShareOperations,shareOperationsLoadError:f,reconciliation:r.recipient_policy_reconciliation,duplicatePersonDecisions:S.lastSyncDuplicatePersonDecisions}),rC(),Ko(),K2(),W2(),vC(),cm(),dC(),nC(),zG(),d&&z2(),u&&(S.lastSyncCoordinatorAdminStatus=null,Ko()),v}catch{return t.signal?.aborted?!1:e!==mm?hm??!1:(El="",S.deviceIdentityInventoryLoadError=!0,wr("syncTeamSkeleton"),wr("syncActorsSkeleton"),wr("syncPeersSkeleton"),wr("syncDiagSkeleton"),UG(),J2(),c2(),!1)}}function zG(){if(S.activeTab==="health"){Pw();return}Tw()}function WG(){El="",S.lastSyncPeers?.length&&cm()}async function xl(){await Al()}function JG(e={}){const t=YG(++gm,e.signal);return vm=t,t}async function YG(e,t){try{const n=await XR(!1,{signal:t});return t?.aborted?!1:e!==gm?vm??!1:(S.pairingPayloadRaw=n||null,nm(),!0)}catch{return t?.aborted?!1:e!==gm?vm??!1:(S.pairingPayloadRaw=null,nm(),!1)}}function XG(e){Uq(),Pc(),Z2(xl),V2(xl),p2(cm),rG(e,xl),Y2(xl),f2(e),lm(),Q2()}function QG(e,t){const n=Qe("runtimeLabel");n&&(n.textContent=t?`v${e} (${t})`:`v${e}`,n.title=t?`codemem ${e} (${t})`:`codemem ${e}`,n.hidden=!1)}async function ZG(){try{const e=await NR();if(!e?.version)return;QG(e.version,"18b9611")}catch{}}var ym=null,bC=1500,Wo=XE(),_C="codemem-legacy-upgrade-notice-dismissed",Cr=null,an=!1,Dl=!1,bm=!1;function wC(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function SC(e){if(!e||typeof e!="object")return null;const t=e.legacy_shared_review??e;if(!t||typeof t!="object")return null;const n=t;if(n.has_data!==!0)return null;const r=Array.isArray(n.groups)?n.groups:[],i=wC(n.total_group_count,r.length),a=wC(n.memory_count);return i<=0||a<=0?null:{groupCount:i,memoryCount:a}}function CC(){try{return localStorage.getItem(_C)==="1"}catch{return!1}}function eH(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(_C,"1")}catch{}}function tH(e,t){e&&t?nE(t):rE()}function RC(e){!e||bm||CC()||(bm=!0,Uv(()=>tH(!0,e)))}async function nH(){if(!(bm||CC()))try{RC(SC(await Jl(!1,"",{includeJoinRequests:!1})))}catch{}}function mi(e,t){const n=Qe("viewerReconnectOverlay"),r=Qe("viewerReconnectDetail");!n||!r||(n.hidden=!e,r.textContent=t||"Trying again automatically while the viewer comes back.")}async function _m(){try{return await PR(),!0}catch{return!1}}function wm(){return document.visibilityState!=="hidden"&&!IS()}function IC(){return`${S.activeTab}:${S.advancedSection}:${S.syncPairingOpen}`}function rH(e){S.refreshQueued||e.surface!==IC()||!e.refreshSucceeded||!Dl||an||(Dl=!1,au("connection_restored"))}function kC(){if(an)return;an=!0,Dl=!0,au("connection_lost"),Sm(),Uv(),Rr("error","(reconnecting)"),mi(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await _m()){if(Cr&&(clearTimeout(Cr),Cr=null),an=!1,mi(!0,"Viewer responded. Restoring your session…"),wm()){Rr("refreshing"),Jo();try{await $l()}catch{}}else Rr("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");an||mi(!1);return}mi(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),Cr=setTimeout(e,bC)};Cr=setTimeout(e,bC)}function Rr(e,t){S.refreshState=e;const n=Qe("refreshStatus");if(!n)return;n.dataset.refreshState=e;const r=a=>{const s=Qe("refreshAnnouncer");!s||ym===e||(s.textContent=a,ym=e)};if(e==="refreshing"){n.textContent="refreshing…";return}if(e==="paused"){n.textContent="paused",r("Auto refresh paused.");return}if(e==="error"&&t==="(reconnecting)"){n.textContent="reconnecting…",r("Viewer reconnecting.");return}if(e==="error"){n.textContent="refresh failed",r("Refresh failed.");return}const i=t?` ${t}`:"";n.textContent=`updated ${new Date().toLocaleTimeString()}${i}`,ym=null}function Sm(){Wo.cancel(),ha&&(clearTimeout(ha),ha=null),S.refreshQueued=!1,S.refreshTimer&&(clearInterval(S.refreshTimer),S.refreshTimer=null)}function iH(){Sm(),Rr("paused")}function Jo(){S.refreshTimer||(S.refreshTimer=setInterval(()=>Ir(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(Sm(),Rr("paused","(tab hidden)")):!IS()&&!an&&(Jo(),Ir())});function TC(){const e=S.advancedSection==="sync",t=Qe("advancedSyncContent"),n=Qe("advancedTeamsContent");t&&(t.hidden=!e),n&&(n.hidden=e);const r=Qe("advancedSyncButton"),i=Qe("advancedTeamsButton");r?.setAttribute("aria-pressed",String(e)),i?.setAttribute("aria-pressed",String(!e)),queueMicrotask(()=>{const a=window.location.hash.replace(/^#/,"");lm(a==="sync/diagnostics"||a==="advanced/sync/diagnostics"?"diagnostics":"main")})}var aH=pA();function PC(e){const t=new Set(tA(S.lastCoordinatorAdminStatus));qr.forEach(r=>{const i=Qe(`tab-${r}`);i&&(i.hidden=r!==e||!t.has(r))}),qr.forEach(r=>{const i=Qe(`tabBtn-${r}`);if(!i)return;i.hidden=!t.has(r);const a=r===e&&t.has(r);i.classList.toggle("active",a),a?i.setAttribute("aria-current","page"):i.removeAttribute("aria-current")});const n=Qe(`tabBtn-${e}`);n&&aH(n),TC()}function hi(e,t={}){Wo.cancel();const n=Ka(e,S.lastCoordinatorAdminStatus);n==="advanced"&&Tu(t.advancedSection??ku()??S.advancedSection),Ry(n,t.canonicalHash?{canonicalHash:!0}:{}),PC(n),Ir()}function oH(){qr.forEach(e=>{Qe(`tabBtn-${e}`)?.addEventListener("click",()=>hi(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),Qe("advancedSyncButton")?.addEventListener("click",()=>Tu("sync",!0)),Qe("advancedTeamsButton")?.addEventListener("click",()=>{Tu("teams",!0),TC(),queueMicrotask(()=>document.getElementById("coordinatorAdminLegacyNoticeTitle")?.focus())}),Qe("coordinatorAdminOpenSharing")?.addEventListener("click",()=>{hi("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),window.addEventListener("hashchange",()=>{const e=Iu();if(e){const t=ku();hi(e,t?{advancedSection:t}:{}),e==="advanced"&&t==="teams"&&queueMicrotask(()=>document.getElementById("coordinatorAdminLegacyNoticeTitle")?.focus())}}),hi(S.activeTab)}async function sH(){try{const e=await es();S.knownProjects=e,WG();const t=Cu("projectFilter");if(!t)return;t.textContent="";const n=document.createElement("option");n.value="",n.textContent="All Projects",t.appendChild(n),e.forEach(r=>{const i=document.createElement("option");i.value=r,i.textContent=r,t.appendChild(i)})}catch{}}function cH(e){S.pendingDeviceIdentityFocus=e?.trim()||null,hi("devices",{canonicalHash:!0})}var Ll=zP({},{onOpenTeamSetup:Kw,onReviewDevices:cH}),NC={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Cm=0,Rm=null,zt=null;async function lH(e={}){const t=[];let n=0;for(;;){const r=await Sa({limit:250,offset:n,signal:e.signal});if(t.push(...r.projects),!r.has_more)break;n+=r.limit}return Ns(t)}function dH(){const e=new Map,t={unknown:0,offline:1,available:2},n=(r,i)=>{!r||t[i]<=t[e.get(r)??"unknown"]||e.set(r,i)};for(const r of S.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"offline":"available");for(const r of S.lastSyncPeers){const i=String(r.peer_device_id??"").trim(),a=Go(r);n(i,a==="connected"||a==="available"?"available":a==="offline"?"offline":"unknown")}return[...e].map(([r,i])=>({deviceId:r,state:i}))}function uH(){return S.lastSyncPeers.flatMap(e=>{const t=String(e.peer_device_id??"").trim();return t?[{deviceId:t,runtimeVersion:e.runtime_version??null,runtimeVersionObservedAt:e.runtime_version_observed_at??null}]:[]})}function EC(e){if(e==="advanced_sync"){hi("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("tabBtn-advanced")?.focus());return}hi(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}function AC(e={}){const t=document.getElementById("devicesMount");if(!t)return Promise.resolve(!0);const n=pH(t,++Cm,e);return Rm=n,n}async function xC(){const[e,t]=await Promise.all([AC(),Ll()]);return e&&t}async function pH(e,t,n){zt||Lc(e,NC,{version:1,items:[]},[],[],{loading:!0});try{const[r,i,a,s,c]=await Promise.all([lH(n),ed(n),yI(n),td(n).then(p=>({inventory:p,unavailable:!1})).catch(()=>({inventory:zt?.inventory,unavailable:!0})),Al({requiredSurface:"devices",signal:n.signal})]);if(n.signal?.aborted)return!1;if(t!==Cm)return Rm??!1;const l=dH(),d=uH(),u=mh(S.lastSyncStatus);return!s.unavailable&&s.inventory&&(S.lastDeviceIdentityInventory=s.inventory),S.deviceIdentityInventoryLoadError=s.unavailable,Lc(e,i,a,r,l,{inventory:s.inventory,inventoryUnavailable:s.unavailable,coordinatorEnrollmentIssueCount:u,onCommitted:xC,onNavigate:EC,peerRuntimeMetadata:d}),zt={projects:r,intent:i,reconciliation:a,availability:l,peerRuntimeMetadata:d,inventory:s.inventory,inventoryUnavailable:s.unavailable,coordinatorEnrollmentIssueCount:u},c}catch{return n.signal?.aborted?!1:t!==Cm?Rm??!1:(zt?Lc(e,zt.intent,zt.reconciliation,zt.projects,zt.availability,{coordinatorEnrollmentIssueCount:zt.coordinatorEnrollmentIssueCount,inventory:zt.inventory,inventoryUnavailable:zt.inventoryUnavailable,onCommitted:xC,onNavigate:EC,peerRuntimeMetadata:zt.peerRuntimeMetadata,refreshError:!0}):Lc(e,NC,{version:1,items:[]},[],[],{loadError:!0}),!1)}}Cu("projectFilter")?.addEventListener("change",()=>{Wo.cancel(),S.currentProject=Cu("projectFilter")?.value||"",oi(!0),Ir()});var ha=null;async function fH(e){await Promise.all([N1({signal:e.signal}),sq({signal:e.signal}),YN().catch(()=>{})])}function mH(e,t,n,r){if(t!=="health"&&Tw(),t==="feed"){const s=n$();e.push(Wb(s,{signal:r.signal}),yf({signal:r.signal}))}if(t==="projects"&&e.push(la({awaitTeamSetupSummary:!0,signal:r.signal}).then(n)),t==="sharing"&&e.push(Ll({awaitTeamSetupSummary:!0,signal:r.signal}).then(n)),t==="devices"&&e.push(AC({signal:r.signal}).then(n)),t==="health"&&e.push(E1({signal:r.signal}),Al({requiredSurface:"health",requireFreshSyncStatus:Dl,signal:r.signal}).then(n)),t==="advanced"&&S.advancedSection==="sync"&&e.push(Al({signal:r.signal}).then(n)),t==="advanced"&&S.advancedSection==="teams"&&e.push(Ac({signal:r.signal}).then(n)),!S.syncPairingOpen)return;const i=t==="advanced"&&S.advancedSection==="sync",a=JG({signal:r.signal});e.push(i?a.then(n):a)}async function Ir(){an||(ha&&clearTimeout(ha),ha=setTimeout(()=>$l(),80))}async function hH(e,t){if(!t.isCurrent()&&!Bm(e))return;const n=await _m();t.isOwned()&&(n?Rr("error"):kC())}function gH(e){Wo.finish(e),S.refreshInFlight=!1,!(!S.refreshQueued||an||!wm())&&(S.refreshQueued=!1,$l())}async function $l(){if(an||!wm())return;if(S.refreshInFlight){S.refreshQueued=!0;return}S.refreshInFlight=!0;const e=Wo.begin();try{Rr("refreshing");const t=S.activeTab,n=IC(),r=[fH(e)];let i=!0;if(mH(r,t,s=>{i=i&&s},e),await Zo(Promise.all(r),e.signal),!e.isCurrent()){if(Bm(e.signal.reason))throw e.signal.reason;return}RC(SC(S.lastSyncLegacySharedReview));const a=Ka(S.activeTab,S.lastCoordinatorAdminStatus);a!==S.activeTab&&Ry(a),PC(S.activeTab),Rr(i?"idle":"error"),rH({refreshSucceeded:i,surface:n})}catch(t){await hH(t,e)}finally{gH(e)}}dA();var DC=document.getElementById("toastRoot");DC&&WE(DC);var LC=document.getElementById("diagnosticsDrawerMount");LC&&JN(LC);var $C=document.getElementById("legacyTeamSetupMount");$C&&kF($C,{onCompleted:async()=>{let e,t;const n={requireTeamSetupSummary:!0};if(S.activeTab==="sharing"?(t=await la(n),e=await Ll(n)):(e=await Ll(n),t=await la(n)),!e||!t)throw new Error("team_setup_refresh_failed")}});var jC=document.getElementById("legacyUpgradeDialogMount");jC&&tE(jC,{onDismiss:eH,onReviewGroups:()=>{window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)},onReviewProjects:()=>{window.location.hash="projects"}}),fA(Js("themeToggle")),Py(Nu()),oH(),n1(),XN(),AB(()=>Ir(),{onOpenTeamSetup:Kw}),XG(()=>Ir()),l$(),Bq(iH,Jo,()=>Ir()),sH(),Qe("viewerReconnectRetry")?.addEventListener("click",async()=>{if(au("reconnect_requested"),mi(!0,"Checking whether the viewer server is back…"),!await _m()){kC();return}Cr&&(clearTimeout(Cr),Cr=null),an=!1,mi(!0,"Viewer responded. Restoring your session…"),Jo();try{await $l()}catch{}an||mi(!1)}),ZG(),nH(),Ir(),Jo()})();