@codemem/server 0.41.0 → 0.42.0

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,9 +1,9 @@
1
- (function(){var xu=Object.defineProperty,b_=(e,t)=>{let n={};for(var r in e)xu(n,r,{get:e[r],enumerable:!0});return t||xu(n,Symbol.toStringTag,{value:"Module"}),n};function ve(e){if(!e||typeof e!="object")return;const t=e.error;return typeof t=="string"?t:void 0}async function De(e){const t=await fetch(e);if(!t.ok)throw new Error(`${e}: ${t.status} ${t.statusText}`);return t.json()}async function ye(e){const t=await e.text();try{return{text:t,payload:t?JSON.parse(t):{}}}catch{return{text:t,payload:{}}}}function Pu(e,t,n,r){const i=new URLSearchParams;return i.set("project",e||""),typeof t=="number"&&i.set("limit",String(t)),typeof n=="number"&&i.set("offset",String(n)),r&&i.set("scope",r),i.toString()}async function __(){return De("/api/observer-status")}async function w_(){return De("/api/config")}async function S_(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=ve(r)||n||"request failed";throw new Error(i)}return r}async function To(){return De("/api/coordinator/admin/status")}async function Au(e){return De(`/api/coordinator/admin/groups${e?"?include_archived=1":""}`)}async function C_(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 ye(t);if(!t.ok)throw new Error(ve(r)||n||"request failed");return r}async function T_(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 ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");return i}async function k_(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/archive`,{method:"POST"}),{text:n,payload:r}=await ye(t);if(!t.ok)throw new Error(ve(r)||n||"request failed");return r}async function N_(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/unarchive`,{method:"POST"}),{text:n,payload:r}=await ye(t);if(!t.ok)throw new Error(ve(r)||n||"request failed");return r}async function x_(e,t=!1){const n=new URLSearchParams;t&&n.set("include_inactive","1");const r=n.size?`?${n.toString()}`:"";return De(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes${r}`)}async function P_(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 ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");return i}async function A_(e,t,n=!1){const r=new URLSearchParams;n&&r.set("include_revoked","1");const i=r.size?`?${r.toString()}`:"";return De(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members${i}`)}async function E_(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 ye(r);if(!r.ok)throw new Error(ve(o)||i||"request failed");return o}async function I_(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 ye(i);if(!i.ok)throw new Error(ve(s)||o||"request failed");return s}async function R_(e){const t=new URLSearchParams;return e&&t.set("group_id",e),De(`/api/coordinator/admin/join-requests${t.size?`?${t.toString()}`:""}`)}async function Eu(e,t=!0){const n=new URLSearchParams;return e&&n.set("group_id",e),t&&n.set("include_disabled","1"),De(`/api/coordinator/admin/devices${n.size?`?${n.toString()}`:""}`)}async function D_(e,t){const n=await fetch(`/api/coordinator/admin/join-requests/${encodeURIComponent(e)}/${t}`,{method:"POST"}),{text:r,payload:i}=await ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");return i}async function L_(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 ye(r);if(!r.ok)throw new Error(ve(o)||i||"request failed");return o}async function $_(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/disable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");return i}async function M_(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/enable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");return i}async function O_(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/remove?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");return i}async function Iu(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 ye(t);if(!t.ok)throw new Error(ve(r)||n||"request failed");return r}async function Ru(e,t){return De(`/api/observations?${Pu(e,t?.limit,t?.offset,t?.scope)}`)}async function j_(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 ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");return i}async function F_(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 ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");return i}async function B_(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 ye(t);if(!t.ok)throw new Error(ve(r)||n||"request failed");return r}async function Du(e,t){return De(`/api/summaries?${Pu(e,t?.limit,t?.offset,t?.scope)}`)}async function U_(e){const t=await fetch("/api/pack/trace",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await ye(t);if(!t.ok)throw new Error(ve(r)||n||"request failed");return r}async function G_(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 H_(){return De("/api/runtime")}async function ko(){return(await De("/api/projects")).projects||[]}async function K_(){return De("/api/stats")}async function V_(e){return De(`/api/usage?project=${encodeURIComponent(e)}`)}async function W_(e){return De(`/api/session?project=${encodeURIComponent(e)}`)}async function q_(e){return De(`/api/raw-events?project=${encodeURIComponent(e)}`)}async function js(e,t="",n){const r=new URLSearchParams;return e&&r.set("includeDiagnostics","1"),t&&r.set("project",t),n?.includeJoinRequests&&r.set("includeJoinRequests","1"),De(`/api/sync/status${r.size?`?${r.toString()}`:""}`)}async function Fs(e,t){const n=await fetch("/api/sync/invites/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({invite:e,...t})}),{text:r,payload:i}=await ye(n);if(!n.ok){const o=typeof i?.detail=="string"?i.detail.trim():"";throw new Error(o||ve(i)||r||"request failed")}return i}async function Lu(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 ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");return i}async function z_(){return De("/api/sync/actors")}async function J_(e=!1){return De(`/api/sync/pairing${e?"?includeDiagnostics=1":""}`)}async function Y_(e,t){const n=await fetch("/api/sync/peers/identity",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({peer_device_id:e,actor_id:t})}),{text:r,payload:i}=await ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");return i}async function $u(e){const t=await fetch(`/api/sync/peers/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await ye(t);if(!t.ok)throw new Error(ve(r)||n||"request failed");return r}async function Mu(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 ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");return i}async function X_(e,t){const n={peer_device_id:e};t&&(n.fingerprint=t);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||ve(o)||i||"request failed");return o}var Ou=class extends Error{preview;constructor(e){super("Project forget confirmation required"),this.name="ProjectForgetConfirmationError",this.preview=e}},No=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??[]}},ju=class extends Error{preview;constructor(e){super("Legacy shared review confirmation required"),this.name="LegacySharedReviewConfirmationError",this.preview=e}},Bs=class extends Error{result;constructor(e){super("Recipient policy changed after review"),this.name="RecipientPolicyEdgesStaleError",this.result=e}};function Us(){return De("/api/sync/recipient-policy/v1/intent")}function Z_(){return De("/api/sync/recipient-policy/v1/reconciliation-status")}async function Fu(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await ye(n);if(!n.ok){if(n.status===409&&i&&typeof i=="object"&&i.status==="stale")throw new Bs(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||ve(i)||r||"request failed")}return i}function Q_(e){return Fu("/api/sync/recipient-policy/v1/edges/preview",e)}function ew(e){return Fu("/api/sync/recipient-policy/v1/edges/commit",e)}async function Bu(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");return i}function tw(e){return Bu("/api/sync/recipient-policy/v1/invites/preview",e)}function nw(e){return Bu("/api/sync/recipient-policy/v1/invites",e)}async function rw(){const e=await De("/api/sync/recipient-policy/v1/review");return e.continuity!==void 0?{...e,continuity:e.continuity}:{...e,continuity:e.reviewItems.length>0?{state:"legacy_access_preserved",findingCount:e.reviewItems.length}:null}}async function iw(){return De("/api/sync/sharing-domains/settings")}async function xo(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 De(`/api/sync/projects${n?`?${n}`:""}`)}async function Uu(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");return i}function ow(e){return Uu("/api/sync/project-invites/preview",e)}function aw(e){return Uu("/api/sync/project-invites",e)}function Gu(){return De("/api/sync/share-operations")}function sw(e){return De(`/api/sync/share-operations/${encodeURIComponent(e)}`)}async function cw(e){const t=await fetch(`/api/sync/share-operations/${encodeURIComponent(e)}/advance`,{method:"POST"}),{text:n,payload:r}=await ye(t);if(!t.ok)throw new Error(ve(r)||n||"request failed");if(!r?.operation)throw new Error("response missing share operation");return r.operation}async function lw(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 ye(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new No(r):new Error(ve(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 dw(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 ye(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new No(r):new Error(ve(r)||n||"request failed");if(!Array.isArray(r?.mappings))throw new Error("response missing mappings");return r.mappings}async function uw(e){const t=await fetch(`/api/sync/sharing-domains/project-mappings/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await ye(t);if(!t.ok)throw new Error(ve(r)||n||"request failed");return!!r?.deleted}async function pw(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 ye(t);if(!t.ok)throw new Error(ve(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project reassignment");return r}async function mw(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 ye(t);if(!t.ok)throw r?.error==="project_forget_confirmation_required"&&r.preview?new Ou(r.preview):new Error(ve(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project forget result");return r}async function fw(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 ye(t);if(!t.ok)throw r?.error==="legacy_review_confirmation_required"&&r.preview?new ju(r.preview):new Error(ve(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing legacy review reassignment");return r}async function hw(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/preferences`),{text:n,payload:r}=await ye(t);if(!t.ok)throw new Error(ve(r)||n||"request failed");const i=r?.preferences;if(!i)throw new Error("response missing preferences");return i}async function gw(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 ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");const o=i?.preferences;if(!o)throw new Error("response missing preferences");return o}async function vw(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 ye(t);if(!t.ok)throw new Error(ve(r)||n||"request failed");return r}async function yw(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 ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");return i}async function Hu(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 ye(n);if(!n.ok)throw new Error(ve(i)||r||"request failed");return i}async function bw(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 ye(t);if(!t.ok)throw new Error(ve(r)||n||"request failed");return r}async function _w(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 ye(t);if(!t.ok)throw new Error(ve(r)||n||"request failed");return r}async function Gs(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 ye(i);if(!i.ok)throw new Error(ve(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 ww(){return De("/api/update-status")}function Sw(e){return{current_version:"unknown",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."}}var ci,fe,Ku,Vu,hn,Wu,qu,zu,Hs,Po,li,Ju,Ks,Vs,Ws,Yu,Ao={},Eo=[],Cw=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,di=Array.isArray;function jt(e,t){for(var n in t)e[n]=t[n];return e}function qs(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function v(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?ci.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 ui(e,s,r,i,null)}function ui(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??++Ku,__i:-1,__u:0};return i==null&&fe.vnode!=null&&fe.vnode(o),o}function Xu(){return{current:null}}function te(e){return e.children}function _t(e,t){this.props=e,this.context=t}function wr(e,t){if(t==null)return e.__?wr(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"?wr(e):null}function Tw(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],i=[],o=jt({},t);o.__v=t.__v+1,fe.vnode&&fe.vnode(o),Js(e.__P,o,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??wr(t),!!(32&t.__u),i),o.__v=t.__v,o.__.__k[o.__i]=o,rp(r,o,i),t.__e=t.__=null,o.__e!=n&&Zu(o)}}function Zu(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}),Zu(e)}function zs(e){(!e.__d&&(e.__d=!0)&&hn.push(e)&&!Io.__r++||Wu!=fe.debounceRendering)&&((Wu=fe.debounceRendering)||qu)(Io)}function Io(){try{for(var e,t=1;hn.length;)hn.length>t&&hn.sort(zu),e=hn.shift(),t=hn.length,Tw(e)}finally{hn.length=Io.__r=0}}function Qu(e,t,n,r,i,o,s,c,l,d,u){var p,m,f,y,h,g,_,w=r&&r.__k||Eo,S=t.length;for(l=kw(n,t,w,l,S),p=0;p<S;p++)(f=n.__k[p])!=null&&(m=f.__i!=-1&&w[f.__i]||Ao,f.__i=p,g=Js(e,f,m,i,o,s,c,l,d,u),y=f.__e,f.ref&&m.ref!=f.ref&&(m.ref&&Xs(m.ref,null,f),u.push(f.ref,f.__c||y,f)),h==null&&y!=null&&(h=y),(_=!!(4&f.__u))||m.__k===f.__k?(l=ep(f,l,e,_),_&&m.__e&&(m.__e=null)):typeof f.type=="function"&&g!==void 0?l=g:y&&(l=y.nextSibling),f.__u&=-7);return n.__e=h,l}function kw(e,t,n,r,i){var o,s,c,l,d,u=n.length,p=u,m=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]=ui(null,s,null,null,null):di(s)?s=e.__k[o]=ui(te,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[o]=ui(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[o]=s,l=o+m,s.__=e,s.__b=e.__b+1,c=null,(d=s.__i=Nw(s,n,l,p))!=-1&&(p--,(c=n[d])&&(c.__u|=2)),c==null||c.__v==null?(d==-1&&(i>u?m--:i<u&&m++),typeof s.type!="function"&&(s.__u|=4)):d!=l&&(d==l-1?m--:d==l+1?m++:(d>l?m--:m++,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=wr(c)),op(c,c));return r}function ep(e,t,n,r){var i,o;if(typeof e.type=="function"){for(i=e.__k,o=0;i&&o<i.length;o++)i[o]&&(i[o].__=e,t=ep(i[o],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=wr(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function Zt(e,t){return t=t||[],e==null||typeof e=="boolean"||(di(e)?e.some(function(n){Zt(n,t)}):t.push(e)),t}function Nw(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 tp(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||Cw.test(t)?n:n+"px"}function Ro(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||tp(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||tp(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")o=t!=(t=t.replace(Ju,"$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[li]=r[li]:(n[li]=Ks,e.addEventListener(t,o?Ws:Vs,o)):e.removeEventListener(t,o?Ws:Vs,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 np(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[Po]==null)t[Po]=Ks++;else if(t[Po]<n[li])return;return n(fe.event?fe.event(t):t)}}}function Js(e,t,n,r,i,o,s,c,l,d){var u,p,m,f,y,h,g,_,w,S,T,k,P,E,M,U=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),o=[c=t.__e=n.__e]),(u=fe.__b)&&u(t);e:if(typeof U=="function")try{if(_=t.props,w=U.prototype&&U.prototype.render,S=(u=U.contextType)&&r[u.__c],T=u?S?S.props.value:u.__:r,n.__c?g=(p=t.__c=n.__c).__=p.__E:(w?t.__c=p=new U(_,T):(t.__c=p=new _t(_,T),p.constructor=U,p.render=Pw),S&&S.sub(p),p.state||(p.state={}),p.__n=r,m=p.__d=!0,p.__h=[],p._sb=[]),w&&p.__s==null&&(p.__s=p.state),w&&U.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=jt({},p.__s)),jt(p.__s,U.getDerivedStateFromProps(_,p.__s))),f=p.props,y=p.state,p.__v=t,m)w&&U.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),w&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(w&&U.getDerivedStateFromProps==null&&_!==f&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(_,T),t.__v==n.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(_,p.__s,T)===!1){t.__v!=n.__v&&(p.props=_,p.state=p.__s,p.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(N){N&&(N.__=t)}),Eo.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&s.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(_,p.__s,T),w&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(f,y,h)})}if(p.context=T,p.props=_,p.__P=e,p.__e=!1,k=fe.__r,P=0,w)p.state=p.__s,p.__d=!1,k&&k(t),u=p.render(p.props,p.state,p.context),Eo.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,k&&k(t),u=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++P<25);p.state=p.__s,p.getChildContext!=null&&(r=jt(jt({},r),p.getChildContext())),w&&!m&&p.getSnapshotBeforeUpdate!=null&&(h=p.getSnapshotBeforeUpdate(f,y)),E=u!=null&&u.type===te&&u.key==null?ip(u.props.children):u,c=Qu(e,di(E)?E:[E],t,n,r,i,o,s,c,l,d),p.base=t.__e,t.__u&=-161,p.__h.length&&s.push(p),g&&(p.__E=p.__=null)}catch(N){if(t.__v=null,l||o!=null)if(N.then){for(t.__u|=l?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;o[o.indexOf(c)]=null,t.__e=c}else{for(M=o.length;M--;)qs(o[M]);Ys(t)}else t.__e=n.__e,t.__k=n.__k,N.then||Ys(t);fe.__e(N,t,n)}else o==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=xw(n.__e,t,n,r,i,o,s,l,d);return(u=fe.diffed)&&u(t),128&t.__u?void 0:c}function Ys(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Ys))}function rp(e,t,n){for(var r=0;r<n.length;r++)Xs(n[r],n[++r],n[++r]);fe.__c&&fe.__c(t,e),e.some(function(i){try{e=i.__h,i.__h=[],e.some(function(o){o.call(i)})}catch(o){fe.__e(o,i.__v)}})}function ip(e){return typeof e!="object"||e==null||e.__b>0?e:di(e)?e.map(ip):e.constructor!==void 0?null:jt({},e)}function xw(e,t,n,r,i,o,s,c,l){var d,u,p,m,f,y,h,g=n.props||Ao,_=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((f=o[d])&&"setAttribute"in f==!!w&&(w?f.localName==w:f.nodeType==3)){e=f,o[d]=null;break}}if(e==null){if(w==null)return document.createTextNode(_);e=document.createElementNS(i,w,_.is&&_),c&&(fe.__m&&fe.__m(t,o),c=!1),o=null}if(w==null)g===_||c&&e.data==_||(e.data=_);else{if(o=w=="textarea"&&_.defaultValue!=null?null:o&&ci.call(e.childNodes),!c&&o!=null)for(g={},d=0;d<e.attributes.length;d++)g[(f=e.attributes[d]).name]=f.value;for(d in g)f=g[d],d=="dangerouslySetInnerHTML"?p=f:d=="children"||d in _||d=="value"&&"defaultValue"in _||d=="checked"&&"defaultChecked"in _||Ro(e,d,null,f,i);for(d in _)f=_[d],d=="children"?m=f:d=="dangerouslySetInnerHTML"?u=f:d=="value"?y=f:d=="checked"?h=f:c&&typeof f!="function"||g[d]===f||Ro(e,d,f,g[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=""),Qu(t.type=="template"?e.content:e,di(m)?m:[m],t,n,r,w=="foreignObject"?"http://www.w3.org/1999/xhtml":i,o,s,o?o[0]:n.__k&&wr(n,0),c,l),o!=null)for(d=o.length;d--;)qs(o[d]);c&&w!="textarea"||(d="value",w=="progress"&&y==null?e.removeAttribute("value"):y!=null&&(y!==e[d]||w=="progress"&&!y||w=="option"&&y!=g[d])&&Ro(e,d,y,g[d],i),d="checked",h!=null&&h!=e[d]&&Ro(e,d,h,g[d],i))}return e}function Xs(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){fe.__e(i,n)}}function op(e,t,n){var r,i;if(fe.unmount&&fe.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||Xs(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(o){fe.__e(o,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&op(r[i],t,n||typeof e.type!="function");n||qs(e.__e),e.__c=e.__=e.__e=void 0}function Pw(e,t,n){return this.constructor(e,n)}function Be(e,t,n){var r,i,o,s;t==document&&(t=document.documentElement),fe.__&&fe.__(e,t),i=(r=typeof n=="function")?null:n&&n.__k||t.__k,o=[],s=[],Js(t,e=(!r&&n||t).__k=v(te,null,[e]),i||Ao,Ao,t.namespaceURI,!r&&n?[n]:i?null:t.firstChild?ci.call(t.childNodes):null,o,!r&&n?n:i?i.__e:t.firstChild,r,s),rp(o,e,s)}function ap(e,t){Be(e,t,ap)}function Aw(e,t,n){var r,i,o,s,c=jt({},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?ci.call(arguments,2):n),ui(e.type,c,r||e.key,i||e.ref,null)}function Fn(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,zs(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"+Yu++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}ci=Eo.slice,fe={__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}},Ku=0,Vu=function(e){return e!=null&&e.constructor===void 0},_t.prototype.setState=function(e,t){var n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=jt({},this.state);typeof e=="function"&&(e=e(jt({},n),this.props)),e&&jt(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),zs(this))},_t.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),zs(this))},_t.prototype.render=te,hn=[],qu=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,zu=function(e,t){return e.__v.__b-t.__v.__b},Io.__r=0,Hs=Math.random().toString(8),Po="__d"+Hs,li="__a"+Hs,Ju=/(PointerCapture)$|Capture$/i,Ks=0,Vs=np(!1),Ws=np(!0),Yu=0;var Qt,Le,Zs,sp,Sr=0,cp=[],Fe=fe,lp=Fe.__b,dp=Fe.__r,up=Fe.diffed,pp=Fe.__c,mp=Fe.unmount,fp=Fe.__;function Bn(e,t){Fe.__h&&Fe.__h(Le,e,Sr||t),Sr=0;var n=Le.__H||(Le.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function I(e){return Sr=1,pi(gp,e)}function pi(e,t,n){var r=Bn(Qt++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):gp(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=Le,!Le.__f)){var i=function(c,l,d){if(!r.__c.__H)return!0;var u=r.__c.__H.__.filter(function(m){return m.__c});if(u.every(function(m){return!m.__N}))return!o||o.call(this,c,l,d);var p=r.__c.props!==c;return u.some(function(m){if(m.__N){var f=m.__[0];m.__=m.__N,m.__N=void 0,f!==m.__[0]&&(p=!0)}}),o&&o.call(this,c,l,d)||p};Le.__f=!0;var o=Le.shouldComponentUpdate,s=Le.componentWillUpdate;Le.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)},Le.shouldComponentUpdate=i}return r.__N||r.__}function K(e,t){var n=Bn(Qt++,3);!Fe.__s&&tc(n.__H,t)&&(n.__=e,n.u=t,Le.__H.__h.push(n))}function gt(e,t){var n=Bn(Qt++,4);!Fe.__s&&tc(n.__H,t)&&(n.__=e,n.u=t,Le.__h.push(n))}function F(e){return Sr=5,Pe(function(){return{current:e}},[])}function Do(e,t,n){Sr=6,gt(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 Pe(e,t){var n=Bn(Qt++,7);return tc(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function re(e,t){return Sr=8,Pe(function(){return e},t)}function gn(e){var t=Le.context[e.__c],n=Bn(Qt++,9);return n.c=e,t?(n.__??(n.__=!0,t.sub(Le)),t.props.value):e.__}function Qs(e,t){Fe.useDebugValue&&Fe.useDebugValue(t?t(e):e)}function Ew(e){var t=Bn(Qt++,10),n=I();return t.__=e,Le.componentDidCatch||(Le.componentDidCatch=function(r,i){t.__&&t.__(r,i),n[1](r)}),[n[0],function(){n[1](void 0)}]}function mi(){var e=Bn(Qt++,11);if(!e.__){for(var t=Le.__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 Iw(){for(var e;e=cp.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Lo),t.__h.some(ec),t.__h=[]}catch(n){t.__h=[],Fe.__e(n,e.__v)}}}Fe.__b=function(e){Le=null,lp&&lp(e)},Fe.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),fp&&fp(e,t)},Fe.__r=function(e){dp&&dp(e),Qt=0;var t=(Le=e.__c).__H;t&&(Zs===Le?(t.__h=[],Le.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(Lo),t.__h.some(ec),t.__h=[],Qt=0)),Zs=Le},Fe.diffed=function(e){up&&up(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(cp.push(t)!==1&&sp===Fe.requestAnimationFrame||((sp=Fe.requestAnimationFrame)||Rw)(Iw)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Zs=Le=null},Fe.__c=function(e,t){t.some(function(n){try{n.__h.some(Lo),n.__h=n.__h.filter(function(r){return!r.__||ec(r)})}catch(r){t.some(function(i){i.__h&&(i.__h=[])}),t=[],Fe.__e(r,n.__v)}}),pp&&pp(e,t)},Fe.unmount=function(e){mp&&mp(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{Lo(r)}catch(i){t=i}}),n.__H=void 0,t&&Fe.__e(t,n.__v))};var hp=typeof requestAnimationFrame=="function";function Rw(e){var t,n=function(){clearTimeout(r),hp&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);hp&&(t=requestAnimationFrame(n))}function Lo(e){var t=Le,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),Le=t}function ec(e){var t=Le;e.__c=e.__(),Le=t}function tc(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function gp(e,t){return typeof t=="function"?t(e):t}var DO=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Dw=0,LO=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:--Dw,__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 fe.vnode&&fe.vnode(d),d}function $o({ariaLabel:e,className:t="modal-close-button",disabled:n=!1,onClick:r,label:i="Close"}){return a("button",{"aria-label":e,className:t,disabled:n,onClick:r,type:"button",children:[a("i",{"aria-hidden":"true",className:"modal-close-button-icon","data-lucide":"x"}),a("span",{className:"modal-close-button-label",children:i})]})}var vp=b_({Children:()=>Ft,Component:()=>_t,Fragment:()=>te,PureComponent:()=>Mo,StrictMode:()=>te,Suspense:()=>fi,SuspenseList:()=>Cr,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:()=>$p,cloneElement:()=>Tr,createContext:()=>Fn,createElement:()=>v,createFactory:()=>Mp,createPortal:()=>en,createRef:()=>Xu,default:()=>nn,findDOMNode:()=>Bp,flushSync:()=>Oo,forwardRef:()=>j,hydrate:()=>Ep,isElement:()=>Gp,isFragment:()=>Op,isMemo:()=>jp,isValidElement:()=>tn,lazy:()=>Np,memo:()=>bp,render:()=>Ap,startTransition:()=>oc,unmountComponentAtNode:()=>Fp,unstable_batchedUpdates:()=>Up,useCallback:()=>re,useContext:()=>gn,useDebugValue:()=>Qs,useDeferredValue:()=>ac,useEffect:()=>K,useErrorBoundary:()=>Ew,useId:()=>mi,useImperativeHandle:()=>Do,useInsertionEffect:()=>cc,useLayoutEffect:()=>gt,useMemo:()=>Pe,useReducer:()=>pi,useRef:()=>F,useState:()=>I,useSyncExternalStore:()=>rc,useTransition:()=>sc,version:()=>Kw});function yp(e,t){for(var n in t)e[n]=t[n];return e}function nc(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 rc(e,t){var n=t(),r=I({t:{__:n,u:t}}),i=r[0].t,o=r[1];return gt(function(){i.__=n,i.u=t,ic(i)&&o({t:i})},[e,n,t]),K(function(){return ic(i)&&o({t:i}),e(function(){ic(i)&&o({t:i})})},[e]),n}function ic(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 oc(e){e()}function ac(e){return e}function sc(){return[!1,oc]}var cc=gt;function Mo(e,t){this.props=e,this.context=t}function bp(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:nc(this.props,i)}function r(i){return this.shouldComponentUpdate=n,v(e,i)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(Mo.prototype=new _t).isPureReactComponent=!0,Mo.prototype.shouldComponentUpdate=function(e,t){return nc(this.props,e)||nc(this.state,t)};var _p=fe.__b;fe.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),_p&&_p(e)};var Lw=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function j(e){function t(n){var r=yp({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=Lw,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var wp=function(e,t){return e==null?null:Zt(Zt(e).map(t))},Ft={map:wp,forEach:wp,count:function(e){return e?Zt(e).length:0},only:function(e){var t=Zt(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:Zt},$w=fe.__e;fe.__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)}$w(e,t,n,r)};var Sp=fe.unmount;function Cp(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=yp({},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 Cp(r,t,n)})),e}function Tp(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return Tp(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 fi(){this.__u=0,this.o=null,this.__b=null}function kp(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function Np(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?v(i,s):null}return o.displayName="Lazy",o.__f=!0,o}function Cr(){this.i=null,this.l=null}fe.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Sp&&Sp(e)},(fi.prototype=new _t).__c=function(e,t){var n=t.__c,r=this;r.o??=[],r.o.push(n);var i=kp(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]=Tp(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)},fi.prototype.componentWillUnmount=function(){this.o=[]},fi.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]=Cp(this.__b,n,r.__O=r.__P)}this.__b=null}var i=t.__a&&v(te,null,e.fallback);return i&&(i.__u&=-33),[v(te,null,t.__a?null:e.children),i]};var xp=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 Mw(e){return this.getChildContext=function(){return e.context},e.children}function Ow(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Be(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)}}}Be(v(Mw,{context:t.context},e.__v),t.v)}function en(e,t){var n=v(Ow,{__v:e,h:t});return n.containerInfo=t,n}(Cr.prototype=new _t).__a=function(e){var t=this,n=kp(t.__v),r=t.l.get(e);return r[0]++,function(i){var o=function(){t.props.revealOrder?(r.push(i),xp(t,e,r)):i()};n?n(o):o()}},Cr.prototype.render=function(e){this.i=null,this.l=new Map;var t=Zt(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},Cr.prototype.componentDidUpdate=Cr.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){xp(e,n,t)})};var Pp=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,jw=/^(?: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]/,Fw=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Bw=/[A-Z0-9]/g,Uw=typeof document<"u",Gw=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function Ap(e,t,n){return t.__k??(t.textContent=""),Be(e,t),typeof n=="function"&&n(),e?e.__c:null}function Ep(e,t,n){return ap(e,t),typeof n=="function"&&n(),e?e.__c:null}_t.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(_t.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var Ip=fe.event;fe.event=function(e){return Ip&&(e=Ip(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var lc,Hw={configurable:!0,get:function(){return this.class}},Rp=fe.vnode;fe.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||Uw&&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"||Gw(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":Fw.test(s)&&(s=l):l=s="oninput":o&&jw.test(s)?s=s.replace(Bw,"-$&").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=Zt(n.children).forEach(function(d){d.props.selected=i.value.indexOf(d.props.value)!=-1})),i.defaultValue!=null&&(i.value=Zt(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",Hw)):n.className&&(i.class=i.className=n.className),t.props=i})(e),e.$$typeof=Pp,Rp&&Rp(e)};var Dp=fe.__r;fe.__r=function(e){Dp&&Dp(e),lc=e.__c};var Lp=fe.diffed;fe.diffed=function(e){Lp&&Lp(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),lc=null};var $p={ReactCurrentDispatcher:{current:{readContext:function(e){return lc.__n[e.__c].props.value},useCallback:re,useContext:gn,useDebugValue:Qs,useDeferredValue:ac,useEffect:K,useId:mi,useImperativeHandle:Do,useInsertionEffect:cc,useLayoutEffect:gt,useMemo:Pe,useReducer:pi,useRef:F,useState:I,useSyncExternalStore:rc,useTransition:sc}}},Kw="18.3.1";function Mp(e){return v.bind(null,e)}function tn(e){return!!e&&e.$$typeof===Pp}function Op(e){return tn(e)&&e.type===te}function jp(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Tr(e){return tn(e)?Aw.apply(null,arguments):e}function Fp(e){return!!e.__k&&(Be(null,e),!0)}function Bp(e){return e&&(e.base||e.nodeType===1&&e)||null}var Up=function(e,t){return e(t)},Oo=function(e,t){var n=fe.debounceRendering;fe.debounceRendering=function(i){return i()};var r=e(t);return fe.debounceRendering=n,r},Gp=tn,nn={useState:I,useId:mi,useReducer:pi,useEffect:K,useLayoutEffect:gt,useInsertionEffect:cc,useTransition:sc,useDeferredValue:ac,useSyncExternalStore:rc,startTransition:oc,useRef:F,useImperativeHandle:Do,useMemo:Pe,useCallback:re,useContext:gn,useDebugValue:Qs,version:"18.3.1",Children:Ft,render:Ap,hydrate:Ep,unmountComponentAtNode:Fp,createPortal:en,createElement:v,createContext:Fn,createFactory:Mp,cloneElement:Tr,createRef:Xu,Fragment:te,isValidElement:tn,isElement:Gp,isFragment:Op,isMemo:jp,findDOMNode:Bp,Component:_t,PureComponent:Mo,memo:bp,forwardRef:j,flushSync:Oo,unstable_batchedUpdates:Up,StrictMode:te,Suspense:fi,SuspenseList:Cr,lazy:Np,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:$p},$O=!!(typeof window<"u"&&window.document&&window.document.createElement);function z(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i.defaultPrevented)return t?.(i)}}function Hp(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function jo(...e){return t=>{let n=!1;const r=e.map(i=>{const o=Hp(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():Hp(e[i],null)}}}}function _e(...e){return re(jo(...e),e)}function Vw(e,t){const n=Fn(t),r=o=>{const{children:s,...c}=o,l=Pe(()=>c,Object.values(c));return a(n.Provider,{value:l,children:s})};r.displayName=e+"Provider";function i(o){const s=gn(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${o}\` must be used within \`${e}\``)}return[r,i]}function st(e,t=[]){let n=[];function r(o,s){const c=Fn(s),l=n.length;n=[...n,s];const d=p=>{const{scope:m,children:f,...y}=p,h=m?.[e]?.[l]||c,g=Pe(()=>y,Object.values(y));return a(h.Provider,{value:g,children:f})};d.displayName=o+"Provider";function u(p,m){const f=m?.[e]?.[l]||c,y=gn(f);if(y)return y;if(s!==void 0)return s;throw new Error(`\`${p}\` must be used within \`${o}\``)}return[d,u]}const i=()=>{const o=n.map(s=>Fn(s));return function(c){const l=c?.[e]||o;return Pe(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return i.scopeName=e,[r,Ww(i,...t)]}function Ww(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(o){const s=r.reduce((c,{useScope:l,scopeName:d})=>{const u=l(o)[`__scope${d}`];return{...c,...u}},{});return Pe(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}var We=globalThis?.document?gt:()=>{},qw=vp[" useId ".trim().toString()]||(()=>{}),zw=0;function ct(e){const[t,n]=I(qw());return We(()=>{e||n(r=>r??String(zw++))},[e]),e||(t?`radix-${t}`:"")}var Jw=vp[" useInsertionEffect ".trim().toString()]||We;function wt({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,o,s]=Yw({defaultProp:t,onChange:n}),c=e!==void 0,l=c?e:i;{const d=F(e!==void 0);K(()=>{const u=d.current;u!==c&&console.warn(`${r} is changing from ${u?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=c},[c,r])}return[l,re(d=>{if(c){const u=Xw(d)?d(e):d;u!==e&&s.current?.(u)}else o(d)},[c,e,o,s])]}function Yw({defaultProp:e,onChange:t}){const[n,r]=I(e),i=F(n),o=F(t);return Jw(()=>{o.current=t},[t]),K(()=>{i.current!==n&&(o.current?.(n),i.current=n)},[n,i]),[n,r,o]}function Xw(e){return typeof e=="function"}function Un(e){const t=Zw(e),n=j((r,i)=>{const{children:o,...s}=r,c=Ft.toArray(o),l=c.find(eS);if(l){const d=l.props.children,u=c.map(p=>p===l?Ft.count(d)>1?Ft.only(null):tn(d)?d.props.children:null:p);return a(t,{...s,ref:i,children:tn(d)?Tr(d,void 0,u):null})}return a(t,{...s,ref:i,children:o})});return n.displayName=`${e}.Slot`,n}function Zw(e){const t=j((n,r)=>{const{children:i,...o}=n;if(tn(i)){const s=nS(i),c=tS(o,i.props);return i.type!==te&&(c.ref=r?jo(r,s):s),Tr(i,c)}return Ft.count(i)>1?Ft.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Kp=Symbol("radix.slottable");function Qw(e){const t=({children:n})=>a(te,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=Kp,t}function eS(e){return tn(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Kp}function tS(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}}function nS(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)}var se=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const n=Un(`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 dc(e,t){e&&Oo(()=>e.dispatchEvent(t))}function lt(e){const t=F(e);return K(()=>{t.current=e}),Pe(()=>(...n)=>t.current?.(...n),[])}function rS(e,t=globalThis?.document){const n=lt(e);K(()=>{const r=i=>{i.key==="Escape"&&n(i)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var iS="DismissableLayer",uc="dismissableLayer.update",oS="dismissableLayer.pointerDownOutside",aS="dismissableLayer.focusOutside",Vp,Wp=Fn({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Gn=j((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:i,onFocusOutside:o,onInteractOutside:s,onDismiss:c,...l}=e,d=gn(Wp),[u,p]=I(null),m=u?.ownerDocument??globalThis?.document,[,f]=I({}),y=_e(t,E=>p(E)),h=Array.from(d.layers),[g]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),_=h.indexOf(g),w=u?h.indexOf(u):-1,S=d.layersWithOutsidePointerEventsDisabled.size>0,T=w>=_,k=cS(E=>{const M=E.target,U=[...d.branches].some(N=>N.contains(M));!T||U||(i?.(E),s?.(E),E.defaultPrevented||c?.())},m),P=lS(E=>{const M=E.target;[...d.branches].some(U=>U.contains(M))||(o?.(E),s?.(E),E.defaultPrevented||c?.())},m);return rS(E=>{w===d.layers.size-1&&(r?.(E),!E.defaultPrevented&&c&&(E.preventDefault(),c()))},m),K(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(Vp=m.body.style.pointerEvents,m.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),zp(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(m.body.style.pointerEvents=Vp)}},[u,m,n,d]),K(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),zp())},[u,d]),K(()=>{const E=()=>f({});return document.addEventListener(uc,E),()=>document.removeEventListener(uc,E)},[]),a(se.div,{...l,ref:y,style:{pointerEvents:S?T?"auto":"none":void 0,...e.style},onFocusCapture:z(e.onFocusCapture,P.onFocusCapture),onBlurCapture:z(e.onBlurCapture,P.onBlurCapture),onPointerDownCapture:z(e.onPointerDownCapture,k.onPointerDownCapture)})});Gn.displayName=iS;var sS="DismissableLayerBranch",qp=j((e,t)=>{const n=gn(Wp),r=F(null),i=_e(t,r);return K(()=>{const o=r.current;if(o)return n.branches.add(o),()=>{n.branches.delete(o)}},[n.branches]),a(se.div,{...e,ref:i})});qp.displayName=sS;function cS(e,t=globalThis?.document){const n=lt(e),r=F(!1),i=F(()=>{});return K(()=>{const o=c=>{if(c.target&&!r.current){let l=function(){Jp(oS,n,d,{discrete:!0})};const d={originalEvent:c};c.pointerType==="touch"?(t.removeEventListener("click",i.current),i.current=l,t.addEventListener("click",i.current,{once:!0})):l()}else t.removeEventListener("click",i.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",o),t.removeEventListener("click",i.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function lS(e,t=globalThis?.document){const n=lt(e),r=F(!1);return K(()=>{const i=o=>{o.target&&!r.current&&Jp(aS,n,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function zp(){const e=new CustomEvent(uc);document.dispatchEvent(e)}function Jp(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?dc(i,o):i.dispatchEvent(o)}var dS=Gn,uS=qp,pc="focusScope.autoFocusOnMount",mc="focusScope.autoFocusOnUnmount",Yp={bubbles:!1,cancelable:!0},pS="FocusScope",hi=j((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:o,...s}=e,[c,l]=I(null),d=lt(i),u=lt(o),p=F(null),m=_e(t,h=>l(h)),f=F({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;K(()=>{if(r){let h=function(S){if(f.paused||!c)return;const T=S.target;c.contains(T)?p.current=T:vn(p.current,{select:!0})},g=function(S){if(f.paused||!c)return;const T=S.relatedTarget;T!==null&&(c.contains(T)||vn(p.current,{select:!0}))},_=function(S){if(document.activeElement===document.body)for(const T of S)T.removedNodes.length>0&&vn(c)};document.addEventListener("focusin",h),document.addEventListener("focusout",g);const w=new MutationObserver(_);return c&&w.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",h),document.removeEventListener("focusout",g),w.disconnect()}}},[r,c,f.paused]),K(()=>{if(c){Qp.add(f);const h=document.activeElement;if(!c.contains(h)){const g=new CustomEvent(pc,Yp);c.addEventListener(pc,d),c.dispatchEvent(g),g.defaultPrevented||(mS(yS(Xp(c)),{select:!0}),document.activeElement===h&&vn(c))}return()=>{c.removeEventListener(pc,d),setTimeout(()=>{const g=new CustomEvent(mc,Yp);c.addEventListener(mc,u),c.dispatchEvent(g),g.defaultPrevented||vn(h??document.body,{select:!0}),c.removeEventListener(mc,u),Qp.remove(f)},0)}}},[c,d,u,f]);const y=re(h=>{if(!n&&!r||f.paused)return;const g=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,_=document.activeElement;if(g&&_){const w=h.currentTarget,[S,T]=fS(w);S&&T?!h.shiftKey&&_===T?(h.preventDefault(),n&&vn(S,{select:!0})):h.shiftKey&&_===S&&(h.preventDefault(),n&&vn(T,{select:!0})):_===w&&h.preventDefault()}},[n,r,f.paused]);return a(se.div,{tabIndex:-1,...s,ref:m,onKeyDown:y})});hi.displayName=pS;function mS(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(vn(r,{select:t}),document.activeElement!==n)return}function fS(e){const t=Xp(e);return[Zp(t,e),Zp(t.reverse(),e)]}function Xp(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode: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}});for(;n.nextNode();)t.push(n.currentNode);return t}function Zp(e,t){for(const n of e)if(!hS(n,{upTo:t}))return n}function hS(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}function gS(e){return e instanceof HTMLInputElement&&"select"in e}function vn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&gS(e)&&t&&e.select()}}var Qp=vS();function vS(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=em(e,t),e.unshift(t)},remove(t){e=em(e,t),e[0]?.resume()}}}function em(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function yS(e){return e.filter(t=>t.tagName!=="A")}var bS="Portal",Hn=j((e,t)=>{const{container:n,...r}=e,[i,o]=I(!1);We(()=>o(!0),[]);const s=n||i&&globalThis?.document?.body;return s?nn.createPortal(a(se.div,{...r,ref:t}),s):null});Hn.displayName=bS;function _S(e,t){return pi((n,r)=>t[n][r]??n,e)}var rt=e=>{const{present:t,children:n}=e,r=wS(t),i=typeof n=="function"?n({present:r.isPresent}):Ft.only(n),o=_e(r.ref,SS(i));return typeof n=="function"||r.isPresent?Tr(i,{ref:o}):null};rt.displayName="Presence";function wS(e){const[t,n]=I(),r=F(null),i=F(e),o=F("none"),[s,c]=_S(e?"mounted":"unmounted",{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return K(()=>{const l=Fo(r.current);o.current=s==="mounted"?l:"none"},[s]),We(()=>{const l=r.current,d=i.current;if(d!==e){const u=o.current,p=Fo(l);e?c("MOUNT"):p==="none"||l?.display==="none"?c("UNMOUNT"):c(d&&u!==p?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,c]),We(()=>{if(t){let l;const d=t.ownerDocument.defaultView??window,u=m=>{const f=Fo(r.current).includes(CSS.escape(m.animationName));if(m.target===t&&f&&(c("ANIMATION_END"),!i.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",l=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},p=m=>{m.target===t&&(o.current=Fo(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{d.clearTimeout(l),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(s),ref:re(l=>{r.current=l?getComputedStyle(l):null,n(l)},[])}}function Fo(e){return e?.animationName||"none"}function SS(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)}var fc=0;function Bo(){K(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??tm()),document.body.insertAdjacentElement("beforeend",e[1]??tm()),fc++,()=>{fc===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),fc--}},[])}function tm(){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}var Bt=function(){return Bt=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},Bt.apply(this,arguments)};function nm(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 CS(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 Uo="right-scroll-bar-position",Go="width-before-scroll-bar",TS="with-scroll-bars-hidden",kS="--removed-body-scroll-bar-size";function hc(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function NS(e,t){var n=I(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 xS=typeof window<"u"?gt:K,rm=new WeakMap;function PS(e,t){var n=NS(t||null,function(r){return e.forEach(function(i){return hc(i,r)})});return xS(function(){var r=rm.get(n);if(r){var i=new Set(r),o=new Set(e),s=n.current;i.forEach(function(c){o.has(c)||hc(c,null)}),o.forEach(function(c){i.has(c)||hc(c,s)})}rm.set(n,e)},[e]),n}function AS(e){return e}function ES(e,t){t===void 0&&(t=AS);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 IS(e){e===void 0&&(e={});var t=ES(null);return t.options=Bt({async:!0,ssr:!1},e),t}var im=function(e){var t=e.sideCar,n=nm(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 v(r,Bt({},n))};im.isSideCarExport=!0;function RS(e,t){return e.useMedium(t),im}var om=IS(),gc=function(){},Ho=j(function(e,t){var n=F(null),r=I({onScrollCapture:gc,onWheelCapture:gc,onTouchMoveCapture:gc}),i=r[0],o=r[1],s=e.forwardProps,c=e.children,l=e.className,d=e.removeScrollBar,u=e.enabled,p=e.shards,m=e.sideCar,f=e.noRelative,y=e.noIsolation,h=e.inert,g=e.allowPinchZoom,_=e.as,w=_===void 0?"div":_,S=e.gapMode,T=nm(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=m,P=PS([n,t]),E=Bt(Bt({},T),i);return v(te,null,u&&v(k,{sideCar:om,removeScrollBar:d,shards:p,noRelative:f,noIsolation:y,inert:h,setCallbacks:o,allowPinchZoom:!!g,lockRef:n,gapMode:S}),s?Tr(Ft.only(c),Bt(Bt({},E),{ref:P})):v(w,Bt({},E,{className:l,ref:P}),c))});Ho.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Ho.classNames={fullWidth:Go,zeroRight:Uo};var am,DS=function(){if(am)return am;if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function LS(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=DS();return t&&e.setAttribute("nonce",t),e}function $S(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function MS(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}var OS=function(){var e=0,t=null;return{add:function(n){e==0&&(t=LS())&&($S(t,n),MS(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},jS=function(){var e=OS();return function(t,n){K(function(){return e.add(t),function(){e.remove()}},[t&&n])}},sm=function(){var e=jS(),t=function(n){var r=n.styles,i=n.dynamic;return e(r,i),null};return t},FS={left:0,top:0,right:0,gap:0},vc=function(e){return parseInt(e||"",10)||0},BS=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[vc(n),vc(r),vc(i)]},US=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return FS;var t=BS(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])}},GS=sm(),gi="data-scroll-locked",HS=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(TS,` {
1
+ (function(){var zu=Object.defineProperty,J_=(e,t)=>{let n={};for(var r in e)zu(n,r,{get:e[r],enumerable:!0});return t||zu(n,Symbol.toStringTag,{value:"Module"}),n};function ge(e){if(!e||typeof e!="object")return;const t=e.error;return typeof t=="string"?t:void 0}async function De(e){const t=await fetch(e);if(!t.ok)throw new Error(`${e}: ${t.status} ${t.statusText}`);return t.json()}async function ye(e){const t=await e.text();try{return{text:t,payload:t?JSON.parse(t):{}}}catch{return{text:t,payload:{}}}}function Ju(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 Y_(){return De("/api/observer-status")}async function X_(){return De("/api/config")}async function Q_(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=ge(r)||n||"request failed";throw new Error(i)}return r}async function Do(){return De("/api/coordinator/admin/status")}async function Yu(e){return De(`/api/coordinator/admin/groups${e?"?include_archived=1":""}`)}async function Z_(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 ye(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function ew(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 ye(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function tw(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/archive`,{method:"POST"}),{text:n,payload:r}=await ye(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function nw(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/unarchive`,{method:"POST"}),{text:n,payload:r}=await ye(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function rw(e,t=!1){const n=new URLSearchParams;t&&n.set("include_inactive","1");const r=n.size?`?${n.toString()}`:"";return De(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes${r}`)}async function iw(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 ye(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function ow(e,t,n=!1){const r=new URLSearchParams;n&&r.set("include_revoked","1");const i=r.size?`?${r.toString()}`:"";return De(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members${i}`)}async function aw(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 ye(r);if(!r.ok)throw new Error(ge(o)||i||"request failed");return o}async function sw(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 ye(i);if(!i.ok)throw new Error(ge(s)||o||"request failed");return s}async function cw(e){const t=new URLSearchParams;return e&&t.set("group_id",e),De(`/api/coordinator/admin/join-requests${t.size?`?${t.toString()}`:""}`)}async function Xu(e,t=!0){const n=new URLSearchParams;return e&&n.set("group_id",e),t&&n.set("include_disabled","1"),De(`/api/coordinator/admin/devices${n.size?`?${n.toString()}`:""}`)}async function lw(e,t){const n=await fetch(`/api/coordinator/admin/join-requests/${encodeURIComponent(e)}/${t}`,{method:"POST"}),{text:r,payload:i}=await ye(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function dw(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 ye(r);if(!r.ok)throw new Error(ge(o)||i||"request failed");return o}async function uw(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/disable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await ye(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function pw(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/enable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await ye(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function fw(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/remove?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await ye(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function Qu(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 ye(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function Zu(e,t){return De(`/api/observations?${Ju(e,t?.limit,t?.offset,t?.scope,t?.q)}`)}async function mw(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 ye(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function hw(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 ye(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function vw(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 ye(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function ep(e,t){return De(`/api/summaries?${Ju(e,t?.limit,t?.offset,t?.scope,t?.q)}`)}async function gw(e){const t=await fetch("/api/pack/trace",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await ye(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function yw(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 bw(){return De("/api/runtime")}async function Lo(){return(await De("/api/projects")).projects||[]}async function _w(){return De("/api/stats")}async function ww(e){return De(`/api/usage?project=${encodeURIComponent(e)}`)}async function Sw(e){return De(`/api/session?project=${encodeURIComponent(e)}`)}async function Cw(e){return De(`/api/raw-events?project=${encodeURIComponent(e)}`)}async function $o(e,t="",n){const r=new URLSearchParams;return e&&r.set("includeDiagnostics","1"),t&&r.set("project",t),n?.includeJoinRequests&&r.set("includeJoinRequests","1"),De(`/api/sync/status${r.size?`?${r.toString()}`:""}`)}async function Ys(e,t){const n=await fetch("/api/sync/invites/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({invite:e,...t})}),{text:r,payload:i}=await ye(n);if(!n.ok){const o=typeof i?.detail=="string"?i.detail.trim():"";throw new Error(o||ge(i)||r||"request failed")}return i}async function tp(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 ye(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function Nw(){return De("/api/sync/actors")}async function kw(e=!1){return De(`/api/sync/pairing${e?"?includeDiagnostics=1":""}`)}async function np(e){const t=await fetch(`/api/sync/peers/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await ye(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function rp(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 ye(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function Tw(e,t){const n={peer_device_id:e};t&&(n.fingerprint=t);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||ge(o)||i||"request failed");return o}var ip=class extends Error{preview;constructor(e){super("Project forget confirmation required"),this.name="ProjectForgetConfirmationError",this.preview=e}},Mo=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??[]}},op=class extends Error{preview;constructor(e){super("Legacy shared review confirmation required"),this.name="LegacySharedReviewConfirmationError",this.preview=e}},Xs=class extends Error{statusCode;errorCode;result;constructor(e,t,n){super(t),this.statusCode=e,this.errorCode=t,this.result=n,this.name="DeviceIdentityBindingApiError"}},Qs=class extends Error{result;constructor(e){super("Recipient policy changed after review"),this.name="RecipientPolicyEdgesStaleError",this.result=e}};function Zs(){return De("/api/sync/recipient-policy/v1/intent")}function ec(){return De("/api/sync/recipient-policy/v1/device-inventory")}async function ap(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await ye(n);if(!n.ok){const o=i?.errorCode||i?.error||ge(i)||r||"request_failed",s=i&&"status"in i?i:null;throw new Xs(n.status,o,s)}return i}function sp(e){return ap("/api/sync/recipient-policy/v1/device-bindings/preview",e)}function cp(e){return ap("/api/sync/recipient-policy/v1/device-bindings/commit",e)}function Iw(){return De("/api/sync/recipient-policy/v1/reconciliation-status")}async function lp(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await ye(n);if(!n.ok){if(n.status===409&&i&&typeof i=="object"&&i.status==="stale")throw new Qs(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||ge(i)||r||"request failed")}return i}function Ew(e){return lp("/api/sync/recipient-policy/v1/edges/preview",e)}function xw(e){return lp("/api/sync/recipient-policy/v1/edges/commit",e)}async function dp(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await ye(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}function Pw(e){return dp("/api/sync/recipient-policy/v1/invites/preview",e)}function Aw(e){return dp("/api/sync/recipient-policy/v1/invites",e)}async function Rw(){const e=await De("/api/sync/recipient-policy/v1/review");return e.continuity!==void 0?{...e,continuity:e.continuity}:{...e,continuity:e.reviewItems.length>0?{state:"legacy_access_preserved",findingCount:e.reviewItems.length}:null}}async function Dw(){return De("/api/sync/sharing-domains/settings")}async function Oo(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 De(`/api/sync/projects${n?`?${n}`:""}`)}async function up(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await ye(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}function Lw(e){return up("/api/sync/project-invites/preview",e)}function $w(e){return up("/api/sync/project-invites",e)}function pp(){return De("/api/sync/share-operations")}function Mw(e){return De(`/api/sync/share-operations/${encodeURIComponent(e)}`)}async function Ow(e){const t=await fetch(`/api/sync/share-operations/${encodeURIComponent(e)}/advance`,{method:"POST"}),{text:n,payload:r}=await ye(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");if(!r?.operation)throw new Error("response missing share operation");return r.operation}async function jw(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 ye(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new Mo(r):new Error(ge(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 Fw(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 ye(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new Mo(r):new Error(ge(r)||n||"request failed");if(!Array.isArray(r?.mappings))throw new Error("response missing mappings");return r.mappings}async function Bw(e){const t=await fetch(`/api/sync/sharing-domains/project-mappings/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await ye(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return!!r?.deleted}async function Uw(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 ye(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project reassignment");return r}async function Gw(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 ye(t);if(!t.ok)throw r?.error==="project_forget_confirmation_required"&&r.preview?new ip(r.preview):new Error(ge(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project forget result");return r}async function Hw(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 ye(t);if(!t.ok)throw r?.error==="legacy_review_confirmation_required"&&r.preview?new op(r.preview):new Error(ge(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing legacy review reassignment");return r}async function qw(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/preferences`),{text:n,payload:r}=await ye(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");const i=r?.preferences;if(!i)throw new Error("response missing preferences");return i}async function Kw(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 ye(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");const o=i?.preferences;if(!o)throw new Error("response missing preferences");return o}async function Vw(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 ye(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function Ww(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 ye(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function fp(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 ye(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function zw(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 ye(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function Jw(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 ye(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function tc(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 ye(i);if(!i.ok)throw new Error(ge(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 Yw(){return De("/api/update-status")}function Xw(e){return{current_version:"unknown",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 jo(e){return e!==null&&typeof e=="object"?e:null}function mp(e){const t=jo(e),n=jo(t?.status),r=jo(jo(t?.coordinator_enrollment_reconciliation_issues??n?.coordinator_enrollment_reconciliation_issues)?.counts)?.open;return typeof r=="number"&&Number.isSafeInteger(r)&&r>0?r:0}var gi,me,hp,vp,hn,gp,yp,bp,nc,Fo,yi,_p,rc,ic,oc,wp,Bo={},Uo=[],Qw=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,bi=Array.isArray;function Ot(e,t){for(var n in t)e[n]=t[n];return e}function ac(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?gi.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 _i(e,s,r,i,null)}function _i(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??++hp,__i:-1,__u:0};return i==null&&me.vnode!=null&&me.vnode(o),o}function Sp(){return{current:null}}function Z(e){return e.children}function St(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 Zw(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],i=[],o=Ot({},t);o.__v=t.__v+1,me.vnode&&me.vnode(o),cc(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,Ep(r,o,i),t.__e=t.__=null,o.__e!=n&&Cp(o)}}function Cp(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}),Cp(e)}function sc(e){(!e.__d&&(e.__d=!0)&&hn.push(e)&&!Go.__r++||gp!=me.debounceRendering)&&((gp=me.debounceRendering)||yp)(Go)}function Go(){try{for(var e,t=1;hn.length;)hn.length>t&&hn.sort(bp),e=hn.shift(),t=hn.length,Zw(e)}finally{hn.length=Go.__r=0}}function Np(e,t,n,r,i,o,s,c,l,d,u){var p,f,m,v,h,g,_,w=r&&r.__k||Uo,S=t.length;for(l=eS(n,t,w,l,S),p=0;p<S;p++)(m=n.__k[p])!=null&&(f=m.__i!=-1&&w[m.__i]||Bo,m.__i=p,g=cc(e,m,f,i,o,s,c,l,d,u),v=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&dc(f.ref,null,m),u.push(m.ref,m.__c||v,m)),h==null&&v!=null&&(h=v),(_=!!(4&m.__u))||f.__k===m.__k?(l=kp(m,l,e,_),_&&f.__e&&(f.__e=null)):typeof m.type=="function"&&g!==void 0?l=g:v&&(l=v.nextSibling),m.__u&=-7);return n.__e=h,l}function eS(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]=_i(null,s,null,null,null):bi(s)?s=e.__k[o]=_i(Z,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[o]=_i(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=tS(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)),Pp(c,c));return r}function kp(e,t,n,r){var i,o;if(typeof e.type=="function"){for(i=e.__k,o=0;i&&o<i.length;o++)i[o]&&(i[o].__=e,t=kp(i[o],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=Sr(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function Qt(e,t){return t=t||[],e==null||typeof e=="boolean"||(bi(e)?e.some(function(n){Qt(n,t)}):t.push(e)),t}function tS(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 Tp(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||Qw.test(t)?n:n+"px"}function Ho(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||Tp(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Tp(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")o=t!=(t=t.replace(_p,"$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[yi]=r[yi]:(n[yi]=rc,e.addEventListener(t,o?oc:ic,o)):e.removeEventListener(t,o?oc:ic,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 Ip(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[Fo]==null)t[Fo]=rc++;else if(t[Fo]<n[yi])return;return n(me.event?me.event(t):t)}}}function cc(e,t,n,r,i,o,s,c,l,d){var u,p,f,m,v,h,g,_,w,S,N,k,E,R,j,q=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),o=[c=t.__e=n.__e]),(u=me.__b)&&u(t);e:if(typeof q=="function")try{if(_=t.props,w=q.prototype&&q.prototype.render,S=(u=q.contextType)&&r[u.__c],N=u?S?S.props.value:u.__:r,n.__c?g=(p=t.__c=n.__c).__=p.__E:(w?t.__c=p=new q(_,N):(t.__c=p=new St(_,N),p.constructor=q,p.render=rS),S&&S.sub(p),p.state||(p.state={}),p.__n=r,f=p.__d=!0,p.__h=[],p._sb=[]),w&&p.__s==null&&(p.__s=p.state),w&&q.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Ot({},p.__s)),Ot(p.__s,q.getDerivedStateFromProps(_,p.__s))),m=p.props,v=p.state,p.__v=t,f)w&&q.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),w&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(w&&q.getDerivedStateFromProps==null&&_!==m&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(_,N),t.__v==n.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(_,p.__s,N)===!1){t.__v!=n.__v&&(p.props=_,p.state=p.__s,p.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(I){I&&(I.__=t)}),Uo.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&s.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(_,p.__s,N),w&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(m,v,h)})}if(p.context=N,p.props=_,p.__P=e,p.__e=!1,k=me.__r,E=0,w)p.state=p.__s,p.__d=!1,k&&k(t),u=p.render(p.props,p.state,p.context),Uo.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,k&&k(t),u=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++E<25);p.state=p.__s,p.getChildContext!=null&&(r=Ot(Ot({},r),p.getChildContext())),w&&!f&&p.getSnapshotBeforeUpdate!=null&&(h=p.getSnapshotBeforeUpdate(m,v)),R=u!=null&&u.type===Z&&u.key==null?xp(u.props.children):u,c=Np(e,bi(R)?R:[R],t,n,r,i,o,s,c,l,d),p.base=t.__e,t.__u&=-161,p.__h.length&&s.push(p),g&&(p.__E=p.__=null)}catch(I){if(t.__v=null,l||o!=null)if(I.then){for(t.__u|=l?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;o[o.indexOf(c)]=null,t.__e=c}else{for(j=o.length;j--;)ac(o[j]);lc(t)}else t.__e=n.__e,t.__k=n.__k,I.then||lc(t);me.__e(I,t,n)}else o==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=nS(n.__e,t,n,r,i,o,s,l,d);return(u=me.diffed)&&u(t),128&t.__u?void 0:c}function lc(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(lc))}function Ep(e,t,n){for(var r=0;r<n.length;r++)dc(n[r],n[++r],n[++r]);me.__c&&me.__c(t,e),e.some(function(i){try{e=i.__h,i.__h=[],e.some(function(o){o.call(i)})}catch(o){me.__e(o,i.__v)}})}function xp(e){return typeof e!="object"||e==null||e.__b>0?e:bi(e)?e.map(xp):e.constructor!==void 0?null:Ot({},e)}function nS(e,t,n,r,i,o,s,c,l){var d,u,p,f,m,v,h,g=n.props||Bo,_=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(_);e=document.createElementNS(i,w,_.is&&_),c&&(me.__m&&me.__m(t,o),c=!1),o=null}if(w==null)g===_||c&&e.data==_||(e.data=_);else{if(o=w=="textarea"&&_.defaultValue!=null?null:o&&gi.call(e.childNodes),!c&&o!=null)for(g={},d=0;d<e.attributes.length;d++)g[(m=e.attributes[d]).name]=m.value;for(d in g)m=g[d],d=="dangerouslySetInnerHTML"?p=m:d=="children"||d in _||d=="value"&&"defaultValue"in _||d=="checked"&&"defaultChecked"in _||Ho(e,d,null,m,i);for(d in _)m=_[d],d=="children"?f=m:d=="dangerouslySetInnerHTML"?u=m:d=="value"?v=m:d=="checked"?h=m:c&&typeof m!="function"||g[d]===m||Ho(e,d,m,g[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=""),Np(t.type=="template"?e.content:e,bi(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--;)ac(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!=g[d])&&Ho(e,d,v,g[d],i),d="checked",h!=null&&h!=e[d]&&Ho(e,d,h,g[d],i))}return e}function dc(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){me.__e(i,n)}}function Pp(e,t,n){var r,i;if(me.unmount&&me.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||dc(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(o){me.__e(o,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&Pp(r[i],t,n||typeof e.type!="function");n||ac(e.__e),e.__c=e.__=e.__e=void 0}function rS(e,t,n){return this.constructor(e,n)}function Be(e,t,n){var r,i,o,s;t==document&&(t=document.documentElement),me.__&&me.__(e,t),i=(r=typeof n=="function")?null:n&&n.__k||t.__k,o=[],s=[],cc(t,e=(!r&&n||t).__k=y(Z,null,[e]),i||Bo,Bo,t.namespaceURI,!r&&n?[n]:i?null:t.firstChild?gi.call(t.childNodes):null,o,!r&&n?n:i?i.__e:t.firstChild,r,s),Ep(o,e,s)}function Ap(e,t){Be(e,t,Ap)}function iS(e,t,n){var r,i,o,s,c=Ot({},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?gi.call(arguments,2):n),_i(e.type,c,r||e.key,i||e.ref,null)}function Bn(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,sc(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"+wp++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}gi=Uo.slice,me={__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}},hp=0,vp=function(e){return e!=null&&e.constructor===void 0},St.prototype.setState=function(e,t){var n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Ot({},this.state);typeof e=="function"&&(e=e(Ot({},n),this.props)),e&&Ot(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),sc(this))},St.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),sc(this))},St.prototype.render=Z,hn=[],yp=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,bp=function(e,t){return e.__v.__b-t.__v.__b},Go.__r=0,nc=Math.random().toString(8),Fo="__d"+nc,yi="__a"+nc,_p=/(PointerCapture)$|Capture$/i,rc=0,ic=Ip(!1),oc=Ip(!0),wp=0;var Zt,$e,uc,Rp,Cr=0,Dp=[],Fe=me,Lp=Fe.__b,$p=Fe.__r,Mp=Fe.diffed,Op=Fe.__c,jp=Fe.unmount,Fp=Fe.__;function Un(e,t){Fe.__h&&Fe.__h($e,e,Cr||t),Cr=0;var n=$e.__H||($e.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function D(e){return Cr=1,wi(Up,e)}function wi(e,t,n){var r=Un(Zt++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Up(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=$e,!$e.__f)){var i=function(c,l,d){if(!r.__c.__H)return!0;var u=r.__c.__H.__.filter(function(f){return f.__c});if(u.every(function(f){return!f.__N}))return!o||o.call(this,c,l,d);var p=r.__c.props!==c;return u.some(function(f){if(f.__N){var m=f.__[0];f.__=f.__N,f.__N=void 0,m!==f.__[0]&&(p=!0)}}),o&&o.call(this,c,l,d)||p};$e.__f=!0;var o=$e.shouldComponentUpdate,s=$e.componentWillUpdate;$e.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)},$e.shouldComponentUpdate=i}return r.__N||r.__}function K(e,t){var n=Un(Zt++,3);!Fe.__s&&mc(n.__H,t)&&(n.__=e,n.u=t,$e.__H.__h.push(n))}function gt(e,t){var n=Un(Zt++,4);!Fe.__s&&mc(n.__H,t)&&(n.__=e,n.u=t,$e.__h.push(n))}function U(e){return Cr=5,Ee(function(){return{current:e}},[])}function qo(e,t,n){Cr=6,gt(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 Ee(e,t){var n=Un(Zt++,7);return mc(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function ie(e,t){return Cr=8,Ee(function(){return e},t)}function vn(e){var t=$e.context[e.__c],n=Un(Zt++,9);return n.c=e,t?(n.__??(n.__=!0,t.sub($e)),t.props.value):e.__}function pc(e,t){Fe.useDebugValue&&Fe.useDebugValue(t?t(e):e)}function oS(e){var t=Un(Zt++,10),n=D();return t.__=e,$e.componentDidCatch||($e.componentDidCatch=function(r,i){t.__&&t.__(r,i),n[1](r)}),[n[0],function(){n[1](void 0)}]}function Si(){var e=Un(Zt++,11);if(!e.__){for(var t=$e.__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 aS(){for(var e;e=Dp.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Ko),t.__h.some(fc),t.__h=[]}catch(n){t.__h=[],Fe.__e(n,e.__v)}}}Fe.__b=function(e){$e=null,Lp&&Lp(e)},Fe.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Fp&&Fp(e,t)},Fe.__r=function(e){$p&&$p(e),Zt=0;var t=($e=e.__c).__H;t&&(uc===$e?(t.__h=[],$e.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(Ko),t.__h.some(fc),t.__h=[],Zt=0)),uc=$e},Fe.diffed=function(e){Mp&&Mp(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Dp.push(t)!==1&&Rp===Fe.requestAnimationFrame||((Rp=Fe.requestAnimationFrame)||sS)(aS)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),uc=$e=null},Fe.__c=function(e,t){t.some(function(n){try{n.__h.some(Ko),n.__h=n.__h.filter(function(r){return!r.__||fc(r)})}catch(r){t.some(function(i){i.__h&&(i.__h=[])}),t=[],Fe.__e(r,n.__v)}}),Op&&Op(e,t)},Fe.unmount=function(e){jp&&jp(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{Ko(r)}catch(i){t=i}}),n.__H=void 0,t&&Fe.__e(t,n.__v))};var Bp=typeof requestAnimationFrame=="function";function sS(e){var t,n=function(){clearTimeout(r),Bp&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Bp&&(t=requestAnimationFrame(n))}function Ko(e){var t=$e,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),$e=t}function fc(e){var t=$e;e.__c=e.__(),$e=t}function mc(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function Up(e,t){return typeof t=="function"?t(e):t}var yj=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,cS=0,bj=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:--cS,__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 me.vnode&&me.vnode(d),d}function Vo({ariaLabel:e,className:t="modal-close-button",disabled:n=!1,onClick:r,label:i="Close"}){return a("button",{"aria-label":e,className:t,disabled:n,onClick:r,type:"button",children:[a("i",{"aria-hidden":"true",className:"modal-close-button-icon","data-lucide":"x"}),a("span",{className:"modal-close-button-label",children:i})]})}var Gp=J_({Children:()=>jt,Component:()=>St,Fragment:()=>Z,PureComponent:()=>Wo,StrictMode:()=>Z,Suspense:()=>Ci,SuspenseList:()=>Nr,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:()=>sf,cloneElement:()=>kr,createContext:()=>Bn,createElement:()=>y,createFactory:()=>cf,createPortal:()=>en,createRef:()=>Sp,default:()=>nn,findDOMNode:()=>pf,flushSync:()=>zo,forwardRef:()=>H,hydrate:()=>tf,isElement:()=>mf,isFragment:()=>lf,isMemo:()=>df,isValidElement:()=>tn,lazy:()=>Xp,memo:()=>qp,render:()=>ef,startTransition:()=>yc,unmountComponentAtNode:()=>uf,unstable_batchedUpdates:()=>ff,useCallback:()=>ie,useContext:()=>vn,useDebugValue:()=>pc,useDeferredValue:()=>bc,useEffect:()=>K,useErrorBoundary:()=>oS,useId:()=>Si,useImperativeHandle:()=>qo,useInsertionEffect:()=>wc,useLayoutEffect:()=>gt,useMemo:()=>Ee,useReducer:()=>wi,useRef:()=>U,useState:()=>D,useSyncExternalStore:()=>vc,useTransition:()=>_c,version:()=>bS});function Hp(e,t){for(var n in t)e[n]=t[n];return e}function hc(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 vc(e,t){var n=t(),r=D({t:{__:n,u:t}}),i=r[0].t,o=r[1];return gt(function(){i.__=n,i.u=t,gc(i)&&o({t:i})},[e,n,t]),K(function(){return gc(i)&&o({t:i}),e(function(){gc(i)&&o({t:i})})},[e]),n}function gc(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 yc(e){e()}function bc(e){return e}function _c(){return[!1,yc]}var wc=gt;function Wo(e,t){this.props=e,this.context=t}function qp(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:hc(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}(Wo.prototype=new St).isPureReactComponent=!0,Wo.prototype.shouldComponentUpdate=function(e,t){return hc(this.props,e)||hc(this.state,t)};var Kp=me.__b;me.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Kp&&Kp(e)};var lS=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function H(e){function t(n){var r=Hp({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=lS,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Vp=function(e,t){return e==null?null:Qt(Qt(e).map(t))},jt={map:Vp,forEach:Vp,count:function(e){return e?Qt(e).length:0},only:function(e){var t=Qt(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:Qt},dS=me.__e;me.__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)}dS(e,t,n,r)};var Wp=me.unmount;function zp(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=Hp({},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 zp(r,t,n)})),e}function Jp(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return Jp(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 Ci(){this.__u=0,this.o=null,this.__b=null}function Yp(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function Xp(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 Nr(){this.i=null,this.l=null}me.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Wp&&Wp(e)},(Ci.prototype=new St).__c=function(e,t){var n=t.__c,r=this;r.o??=[],r.o.push(n);var i=Yp(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]=Jp(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)},Ci.prototype.componentWillUnmount=function(){this.o=[]},Ci.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]=zp(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 Qp=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 uS(e){return this.getChildContext=function(){return e.context},e.children}function pS(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Be(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)}}}Be(y(uS,{context:t.context},e.__v),t.v)}function en(e,t){var n=y(pS,{__v:e,h:t});return n.containerInfo=t,n}(Nr.prototype=new St).__a=function(e){var t=this,n=Yp(t.__v),r=t.l.get(e);return r[0]++,function(i){var o=function(){t.props.revealOrder?(r.push(i),Qp(t,e,r)):i()};n?n(o):o()}},Nr.prototype.render=function(e){this.i=null,this.l=new Map;var t=Qt(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},Nr.prototype.componentDidUpdate=Nr.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Qp(e,n,t)})};var Zp=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,fS=/^(?: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]/,mS=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,hS=/[A-Z0-9]/g,vS=typeof document<"u",gS=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function ef(e,t,n){return t.__k??(t.textContent=""),Be(e,t),typeof n=="function"&&n(),e?e.__c:null}function tf(e,t,n){return Ap(e,t),typeof n=="function"&&n(),e?e.__c:null}St.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(St.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var nf=me.event;me.event=function(e){return nf&&(e=nf(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var Sc,yS={configurable:!0,get:function(){return this.class}},rf=me.vnode;me.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||vS&&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"||gS(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":mS.test(s)&&(s=l):l=s="oninput":o&&fS.test(s)?s=s.replace(hS,"-$&").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=Qt(n.children).forEach(function(d){d.props.selected=i.value.indexOf(d.props.value)!=-1})),i.defaultValue!=null&&(i.value=Qt(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",yS)):n.className&&(i.class=i.className=n.className),t.props=i})(e),e.$$typeof=Zp,rf&&rf(e)};var of=me.__r;me.__r=function(e){of&&of(e),Sc=e.__c};var af=me.diffed;me.diffed=function(e){af&&af(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),Sc=null};var sf={ReactCurrentDispatcher:{current:{readContext:function(e){return Sc.__n[e.__c].props.value},useCallback:ie,useContext:vn,useDebugValue:pc,useDeferredValue:bc,useEffect:K,useId:Si,useImperativeHandle:qo,useInsertionEffect:wc,useLayoutEffect:gt,useMemo:Ee,useReducer:wi,useRef:U,useState:D,useSyncExternalStore:vc,useTransition:_c}}},bS="18.3.1";function cf(e){return y.bind(null,e)}function tn(e){return!!e&&e.$$typeof===Zp}function lf(e){return tn(e)&&e.type===Z}function df(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function kr(e){return tn(e)?iS.apply(null,arguments):e}function uf(e){return!!e.__k&&(Be(null,e),!0)}function pf(e){return e&&(e.base||e.nodeType===1&&e)||null}var ff=function(e,t){return e(t)},zo=function(e,t){var n=me.debounceRendering;me.debounceRendering=function(i){return i()};var r=e(t);return me.debounceRendering=n,r},mf=tn,nn={useState:D,useId:Si,useReducer:wi,useEffect:K,useLayoutEffect:gt,useInsertionEffect:wc,useTransition:_c,useDeferredValue:bc,useSyncExternalStore:vc,startTransition:yc,useRef:U,useImperativeHandle:qo,useMemo:Ee,useCallback:ie,useContext:vn,useDebugValue:pc,version:"18.3.1",Children:jt,render:ef,hydrate:tf,unmountComponentAtNode:uf,createPortal:en,createElement:y,createContext:Bn,createFactory:cf,cloneElement:kr,createRef:Sp,Fragment:Z,isValidElement:tn,isElement:mf,isFragment:lf,isMemo:df,findDOMNode:pf,Component:St,PureComponent:Wo,memo:qp,forwardRef:H,flushSync:zo,unstable_batchedUpdates:ff,StrictMode:Z,Suspense:Ci,SuspenseList:Nr,lazy:Xp,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:sf},_j=!!(typeof window<"u"&&window.document&&window.document.createElement);function z(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i.defaultPrevented)return t?.(i)}}function hf(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Jo(...e){return t=>{let n=!1;const r=e.map(i=>{const o=hf(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():hf(e[i],null)}}}}function _e(...e){return ie(Jo(...e),e)}function _S(e,t){const n=Bn(t),r=o=>{const{children:s,...c}=o,l=Ee(()=>c,Object.values(c));return a(n.Provider,{value:l,children:s})};r.displayName=e+"Provider";function i(o){const s=vn(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${o}\` must be used within \`${e}\``)}return[r,i]}function ot(e,t=[]){let n=[];function r(o,s){const c=Bn(s),l=n.length;n=[...n,s];const d=p=>{const{scope:f,children:m,...v}=p,h=f?.[e]?.[l]||c,g=Ee(()=>v,Object.values(v));return a(h.Provider,{value:g,children:m})};d.displayName=o+"Provider";function u(p,f){const m=f?.[e]?.[l]||c,v=vn(m);if(v)return v;if(s!==void 0)return s;throw new Error(`\`${p}\` must be used within \`${o}\``)}return[d,u]}const i=()=>{const o=n.map(s=>Bn(s));return function(c){const l=c?.[e]||o;return Ee(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return i.scopeName=e,[r,wS(i,...t)]}function wS(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(o){const s=r.reduce((c,{useScope:l,scopeName:d})=>{const u=l(o)[`__scope${d}`];return{...c,...u}},{});return Ee(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}var Ve=globalThis?.document?gt:()=>{},SS=Gp[" useId ".trim().toString()]||(()=>{}),CS=0;function at(e){const[t,n]=D(SS());return Ve(()=>{e||n(r=>r??String(CS++))},[e]),e||(t?`radix-${t}`:"")}var NS=Gp[" useInsertionEffect ".trim().toString()]||Ve;function Ct({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,o,s]=kS({defaultProp:t,onChange:n}),c=e!==void 0,l=c?e:i;{const d=U(e!==void 0);K(()=>{const u=d.current;u!==c&&console.warn(`${r} is changing from ${u?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=c},[c,r])}return[l,ie(d=>{if(c){const u=TS(d)?d(e):d;u!==e&&s.current?.(u)}else o(d)},[c,e,o,s])]}function kS({defaultProp:e,onChange:t}){const[n,r]=D(e),i=U(n),o=U(t);return NS(()=>{o.current=t},[t]),K(()=>{i.current!==n&&(o.current?.(n),i.current=n)},[n,i]),[n,r,o]}function TS(e){return typeof e=="function"}function Gn(e){const t=IS(e),n=H((r,i)=>{const{children:o,...s}=r,c=jt.toArray(o),l=c.find(xS);if(l){const d=l.props.children,u=c.map(p=>p===l?jt.count(d)>1?jt.only(null):tn(d)?d.props.children:null:p);return a(t,{...s,ref:i,children:tn(d)?kr(d,void 0,u):null})}return a(t,{...s,ref:i,children:o})});return n.displayName=`${e}.Slot`,n}function IS(e){const t=H((n,r)=>{const{children:i,...o}=n;if(tn(i)){const s=AS(i),c=PS(o,i.props);return i.type!==Z&&(c.ref=r?Jo(r,s):s),kr(i,c)}return jt.count(i)>1?jt.only(null):null});return t.displayName=`${e}.SlotClone`,t}var vf=Symbol("radix.slottable");function ES(e){const t=({children:n})=>a(Z,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=vf,t}function xS(e){return tn(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===vf}function PS(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}}function AS(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)}var se=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const n=Gn(`Primitive.${t}`),r=H((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 Cc(e,t){e&&zo(()=>e.dispatchEvent(t))}function st(e){const t=U(e);return K(()=>{t.current=e}),Ee(()=>(...n)=>t.current?.(...n),[])}function RS(e,t=globalThis?.document){const n=st(e);K(()=>{const r=i=>{i.key==="Escape"&&n(i)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var DS="DismissableLayer",Nc="dismissableLayer.update",LS="dismissableLayer.pointerDownOutside",$S="dismissableLayer.focusOutside",gf,yf=Bn({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Hn=H((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:i,onFocusOutside:o,onInteractOutside:s,onDismiss:c,...l}=e,d=vn(yf),[u,p]=D(null),f=u?.ownerDocument??globalThis?.document,[,m]=D({}),v=_e(t,R=>p(R)),h=Array.from(d.layers),[g]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),_=h.indexOf(g),w=u?h.indexOf(u):-1,S=d.layersWithOutsidePointerEventsDisabled.size>0,N=w>=_,k=OS(R=>{const j=R.target,q=[...d.branches].some(I=>I.contains(j));!N||q||(i?.(R),s?.(R),R.defaultPrevented||c?.())},f),E=jS(R=>{const j=R.target;[...d.branches].some(q=>q.contains(j))||(o?.(R),s?.(R),R.defaultPrevented||c?.())},f);return RS(R=>{w===d.layers.size-1&&(r?.(R),!R.defaultPrevented&&c&&(R.preventDefault(),c()))},f),K(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(gf=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),_f(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=gf)}},[u,f,n,d]),K(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),_f())},[u,d]),K(()=>{const R=()=>m({});return document.addEventListener(Nc,R),()=>document.removeEventListener(Nc,R)},[]),a(se.div,{...l,ref:v,style:{pointerEvents:S?N?"auto":"none":void 0,...e.style},onFocusCapture:z(e.onFocusCapture,E.onFocusCapture),onBlurCapture:z(e.onBlurCapture,E.onBlurCapture),onPointerDownCapture:z(e.onPointerDownCapture,k.onPointerDownCapture)})});Hn.displayName=DS;var MS="DismissableLayerBranch",bf=H((e,t)=>{const n=vn(yf),r=U(null),i=_e(t,r);return K(()=>{const o=r.current;if(o)return n.branches.add(o),()=>{n.branches.delete(o)}},[n.branches]),a(se.div,{...e,ref:i})});bf.displayName=MS;function OS(e,t=globalThis?.document){const n=st(e),r=U(!1),i=U(()=>{});return K(()=>{const o=c=>{if(c.target&&!r.current){let l=function(){wf(LS,n,d,{discrete:!0})};const d={originalEvent:c};c.pointerType==="touch"?(t.removeEventListener("click",i.current),i.current=l,t.addEventListener("click",i.current,{once:!0})):l()}else t.removeEventListener("click",i.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",o),t.removeEventListener("click",i.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function jS(e,t=globalThis?.document){const n=st(e),r=U(!1);return K(()=>{const i=o=>{o.target&&!r.current&&wf($S,n,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function _f(){const e=new CustomEvent(Nc);document.dispatchEvent(e)}function wf(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?Cc(i,o):i.dispatchEvent(o)}var FS=Hn,BS=bf,kc="focusScope.autoFocusOnMount",Tc="focusScope.autoFocusOnUnmount",Sf={bubbles:!1,cancelable:!0},US="FocusScope",Ni=H((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:o,...s}=e,[c,l]=D(null),d=st(i),u=st(o),p=U(null),f=_e(t,h=>l(h)),m=U({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;K(()=>{if(r){let h=function(S){if(m.paused||!c)return;const N=S.target;c.contains(N)?p.current=N:gn(p.current,{select:!0})},g=function(S){if(m.paused||!c)return;const N=S.relatedTarget;N!==null&&(c.contains(N)||gn(p.current,{select:!0}))},_=function(S){if(document.activeElement===document.body)for(const N of S)N.removedNodes.length>0&&gn(c)};document.addEventListener("focusin",h),document.addEventListener("focusout",g);const w=new MutationObserver(_);return c&&w.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",h),document.removeEventListener("focusout",g),w.disconnect()}}},[r,c,m.paused]),K(()=>{if(c){kf.add(m);const h=document.activeElement;if(!c.contains(h)){const g=new CustomEvent(kc,Sf);c.addEventListener(kc,d),c.dispatchEvent(g),g.defaultPrevented||(GS(WS(Cf(c)),{select:!0}),document.activeElement===h&&gn(c))}return()=>{c.removeEventListener(kc,d),setTimeout(()=>{const g=new CustomEvent(Tc,Sf);c.addEventListener(Tc,u),c.dispatchEvent(g),g.defaultPrevented||gn(h??document.body,{select:!0}),c.removeEventListener(Tc,u),kf.remove(m)},0)}}},[c,d,u,m]);const v=ie(h=>{if(!n&&!r||m.paused)return;const g=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,_=document.activeElement;if(g&&_){const w=h.currentTarget,[S,N]=HS(w);S&&N?!h.shiftKey&&_===N?(h.preventDefault(),n&&gn(S,{select:!0})):h.shiftKey&&_===S&&(h.preventDefault(),n&&gn(N,{select:!0})):_===w&&h.preventDefault()}},[n,r,m.paused]);return a(se.div,{tabIndex:-1,...s,ref:f,onKeyDown:v})});Ni.displayName=US;function GS(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(gn(r,{select:t}),document.activeElement!==n)return}function HS(e){const t=Cf(e);return[Nf(t,e),Nf(t.reverse(),e)]}function Cf(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode: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}});for(;n.nextNode();)t.push(n.currentNode);return t}function Nf(e,t){for(const n of e)if(!qS(n,{upTo:t}))return n}function qS(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}function KS(e){return e instanceof HTMLInputElement&&"select"in e}function gn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&KS(e)&&t&&e.select()}}var kf=VS();function VS(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Tf(e,t),e.unshift(t)},remove(t){e=Tf(e,t),e[0]?.resume()}}}function Tf(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function WS(e){return e.filter(t=>t.tagName!=="A")}var zS="Portal",qn=H((e,t)=>{const{container:n,...r}=e,[i,o]=D(!1);Ve(()=>o(!0),[]);const s=n||i&&globalThis?.document?.body;return s?nn.createPortal(a(se.div,{...r,ref:t}),s):null});qn.displayName=zS;function JS(e,t){return wi((n,r)=>t[n][r]??n,e)}var et=e=>{const{present:t,children:n}=e,r=YS(t),i=typeof n=="function"?n({present:r.isPresent}):jt.only(n),o=_e(r.ref,XS(i));return typeof n=="function"||r.isPresent?kr(i,{ref:o}):null};et.displayName="Presence";function YS(e){const[t,n]=D(),r=U(null),i=U(e),o=U("none"),[s,c]=JS(e?"mounted":"unmounted",{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return K(()=>{const l=Yo(r.current);o.current=s==="mounted"?l:"none"},[s]),Ve(()=>{const l=r.current,d=i.current;if(d!==e){const u=o.current,p=Yo(l);e?c("MOUNT"):p==="none"||l?.display==="none"?c("UNMOUNT"):c(d&&u!==p?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,c]),Ve(()=>{if(t){let l;const d=t.ownerDocument.defaultView??window,u=f=>{const m=Yo(r.current).includes(CSS.escape(f.animationName));if(f.target===t&&m&&(c("ANIMATION_END"),!i.current)){const v=t.style.animationFillMode;t.style.animationFillMode="forwards",l=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=v)})}},p=f=>{f.target===t&&(o.current=Yo(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{d.clearTimeout(l),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(s),ref:ie(l=>{r.current=l?getComputedStyle(l):null,n(l)},[])}}function Yo(e){return e?.animationName||"none"}function XS(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)}var Ic=0;function Xo(){K(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??If()),document.body.insertAdjacentElement("beforeend",e[1]??If()),Ic++,()=>{Ic===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Ic--}},[])}function If(){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}var Ft=function(){return Ft=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},Ft.apply(this,arguments)};function Ef(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 QS(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 Qo="right-scroll-bar-position",Zo="width-before-scroll-bar",ZS="with-scroll-bars-hidden",eC="--removed-body-scroll-bar-size";function Ec(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function tC(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 nC=typeof window<"u"?gt:K,xf=new WeakMap;function rC(e,t){var n=tC(t||null,function(r){return e.forEach(function(i){return Ec(i,r)})});return nC(function(){var r=xf.get(n);if(r){var i=new Set(r),o=new Set(e),s=n.current;i.forEach(function(c){o.has(c)||Ec(c,null)}),o.forEach(function(c){i.has(c)||Ec(c,s)})}xf.set(n,e)},[e]),n}function iC(e){return e}function oC(e,t){t===void 0&&(t=iC);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 aC(e){e===void 0&&(e={});var t=oC(null);return t.options=Ft({async:!0,ssr:!1},e),t}var Pf=function(e){var t=e.sideCar,n=Ef(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,Ft({},n))};Pf.isSideCarExport=!0;function sC(e,t){return e.useMedium(t),Pf}var Af=aC(),xc=function(){},ea=H(function(e,t){var n=U(null),r=D({onScrollCapture:xc,onWheelCapture:xc,onTouchMoveCapture:xc}),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,h=e.inert,g=e.allowPinchZoom,_=e.as,w=_===void 0?"div":_,S=e.gapMode,N=Ef(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=f,E=rC([n,t]),R=Ft(Ft({},N),i);return y(Z,null,u&&y(k,{sideCar:Af,removeScrollBar:d,shards:p,noRelative:m,noIsolation:v,inert:h,setCallbacks:o,allowPinchZoom:!!g,lockRef:n,gapMode:S}),s?kr(jt.only(c),Ft(Ft({},R),{ref:E})):y(w,Ft({},R,{className:l,ref:E}),c))});ea.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},ea.classNames={fullWidth:Zo,zeroRight:Qo};var Rf,cC=function(){if(Rf)return Rf;if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function lC(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=cC();return t&&e.setAttribute("nonce",t),e}function dC(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function uC(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}var pC=function(){var e=0,t=null;return{add:function(n){e==0&&(t=lC())&&(dC(t,n),uC(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},fC=function(){var e=pC();return function(t,n){K(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Df=function(){var e=fC(),t=function(n){var r=n.styles,i=n.dynamic;return e(r,i),null};return t},mC={left:0,top:0,right:0,gap:0},Pc=function(e){return parseInt(e||"",10)||0},hC=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[Pc(n),Pc(r),Pc(i)]},vC=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return mC;var t=hC(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])}},gC=Df(),ki="data-scroll-locked",yC=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(ZS,` {
3
3
  overflow: hidden `).concat(r,`;
4
4
  padding-right: `).concat(c,"px ").concat(r,`;
5
5
  }
6
- body[`).concat(gi,`] {
6
+ body[`).concat(ki,`] {
7
7
  overflow: hidden `).concat(r,`;
8
8
  overscroll-behavior: contain;
9
9
  `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&`
@@ -16,67 +16,67 @@
16
16
  `),n==="padding"&&"padding-right: ".concat(c,"px ").concat(r,";")].filter(Boolean).join(""),`
17
17
  }
18
18
 
19
- .`).concat(Uo,` {
19
+ .`).concat(Qo,` {
20
20
  right: `).concat(c,"px ").concat(r,`;
21
21
  }
22
22
 
23
- .`).concat(Go,` {
23
+ .`).concat(Zo,` {
24
24
  margin-right: `).concat(c,"px ").concat(r,`;
25
25
  }
26
26
 
27
- .`).concat(Uo," .").concat(Uo,` {
27
+ .`).concat(Qo," .").concat(Qo,` {
28
28
  right: 0 `).concat(r,`;
29
29
  }
30
30
 
31
- .`).concat(Go," .").concat(Go,` {
31
+ .`).concat(Zo," .").concat(Zo,` {
32
32
  margin-right: 0 `).concat(r,`;
33
33
  }
34
34
 
35
- body[`).concat(gi,`] {
36
- `).concat(kS,": ").concat(c,`px;
35
+ body[`).concat(ki,`] {
36
+ `).concat(eC,": ").concat(c,`px;
37
37
  }
38
- `)},cm=function(){var e=parseInt(document.body.getAttribute("data-scroll-locked")||"0",10);return isFinite(e)?e:0},KS=function(){K(function(){return document.body.setAttribute(gi,(cm()+1).toString()),function(){var e=cm()-1;e<=0?document.body.removeAttribute(gi):document.body.setAttribute(gi,e.toString())}},[])},VS=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;KS();var o=Pe(function(){return US(i)},[i]);return v(GS,{styles:HS(o,!t,i,n?"":"!important")})},yc=!1;if(typeof window<"u")try{var Ko=Object.defineProperty({},"passive",{get:function(){return yc=!0,!0}});window.addEventListener("test",Ko,Ko),window.removeEventListener("test",Ko,Ko)}catch{yc=!1}var kr=yc?{passive:!1}:!1,WS=function(e){return e.tagName==="TEXTAREA"},lm=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!WS(e)&&n[t]==="visible")},qS=function(e){return lm(e,"overflowY")},zS=function(e){return lm(e,"overflowX")},dm=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host),um(e,r)){var i=pm(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},JS=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},YS=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},um=function(e,t){return e==="v"?qS(t):zS(t)},pm=function(e,t){return e==="v"?JS(t):YS(t)},XS=function(e,t){return e==="h"&&t==="rtl"?-1:1},ZS=function(e,t,n,r,i){var o=XS(e,window.getComputedStyle(t).direction),s=o*r,c=n.target,l=t.contains(c),d=!1,u=s>0,p=0,m=0;do{if(!c)break;var f=pm(e,c),y=f[0],h=f[1]-f[2]-o*y;(y||h)&&um(e,c)&&(p+=h,m+=y);var g=c.parentNode;c=g&&g.nodeType===Node.DOCUMENT_FRAGMENT_NODE?g.host:g}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(m)<1||!i&&-s>m))&&(d=!0),d},Vo=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},mm=function(e){return[e.deltaX,e.deltaY]},fm=function(e){return e&&"current"in e?e.current:e},QS=function(e,t){return e[0]===t[0]&&e[1]===t[1]},eC=function(e){return`
38
+ `)},Lf=function(){var e=parseInt(document.body.getAttribute("data-scroll-locked")||"0",10);return isFinite(e)?e:0},bC=function(){K(function(){return document.body.setAttribute(ki,(Lf()+1).toString()),function(){var e=Lf()-1;e<=0?document.body.removeAttribute(ki):document.body.setAttribute(ki,e.toString())}},[])},_C=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;bC();var o=Ee(function(){return vC(i)},[i]);return y(gC,{styles:yC(o,!t,i,n?"":"!important")})},Ac=!1;if(typeof window<"u")try{var ta=Object.defineProperty({},"passive",{get:function(){return Ac=!0,!0}});window.addEventListener("test",ta,ta),window.removeEventListener("test",ta,ta)}catch{Ac=!1}var Tr=Ac?{passive:!1}:!1,wC=function(e){return e.tagName==="TEXTAREA"},$f=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!wC(e)&&n[t]==="visible")},SC=function(e){return $f(e,"overflowY")},CC=function(e){return $f(e,"overflowX")},Mf=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host),Of(e,r)){var i=jf(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},NC=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},kC=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},Of=function(e,t){return e==="v"?SC(t):CC(t)},jf=function(e,t){return e==="v"?NC(t):kC(t)},TC=function(e,t){return e==="h"&&t==="rtl"?-1:1},IC=function(e,t,n,r,i){var o=TC(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=jf(e,c),v=m[0],h=m[1]-m[2]-o*v;(v||h)&&Of(e,c)&&(p+=h,f+=v);var g=c.parentNode;c=g&&g.nodeType===Node.DOCUMENT_FRAGMENT_NODE?g.host:g}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},na=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Ff=function(e){return[e.deltaX,e.deltaY]},Bf=function(e){return e&&"current"in e?e.current:e},EC=function(e,t){return e[0]===t[0]&&e[1]===t[1]},xC=function(e){return`
39
39
  .block-interactivity-`.concat(e,` {pointer-events: none;}
40
40
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
41
- `)},tC=0,Nr=[];function nC(e){var t=F([]),n=F([0,0]),r=F(),i=I(tC++)[0],o=I(sm)[0],s=F(e);K(function(){s.current=e},[e]),K(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var h=CS([e.lockRef.current],(e.shards||[]).map(fm),!0).filter(Boolean);return h.forEach(function(g){return g.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),h.forEach(function(g){return g.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var c=re(function(h,g){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!s.current.allowPinchZoom;var _=Vo(h),w=n.current,S="deltaX"in h?h.deltaX:w[0]-_[0],T="deltaY"in h?h.deltaY:w[1]-_[1],k,P=h.target,E=Math.abs(S)>Math.abs(T)?"h":"v";if("touches"in h&&E==="h"&&P.type==="range")return!1;var M=window.getSelection(),U=M&&M.anchorNode;if(U&&(U===P||U.contains(P)))return!1;var N=dm(E,P);if(!N)return!0;if(N?k=E:(k=E==="v"?"h":"v",N=dm(E,P)),!N)return!1;if(!r.current&&"changedTouches"in h&&(S||T)&&(r.current=k),!k)return!0;var G=r.current||k;return ZS(G,g,h,G==="h"?S:T,!0)},[]),l=re(function(h){var g=h;if(!(!Nr.length||Nr[Nr.length-1]!==o)){var _="deltaY"in g?mm(g):Vo(g),w=t.current.filter(function(T){return T.name===g.type&&(T.target===g.target||g.target===T.shadowParent)&&QS(T.delta,_)})[0];if(w&&w.should){g.cancelable&&g.preventDefault();return}if(!w){var S=(s.current.shards||[]).map(fm).filter(Boolean).filter(function(T){return T.contains(g.target)});(S.length>0?c(g,S[0]):!s.current.noIsolation)&&g.cancelable&&g.preventDefault()}}},[]),d=re(function(h,g,_,w){var S={name:h,delta:g,target:_,should:w,shadowParent:rC(_)};t.current.push(S),setTimeout(function(){t.current=t.current.filter(function(T){return T!==S})},1)},[]),u=re(function(h){n.current=Vo(h),r.current=void 0},[]),p=re(function(h){d(h.type,mm(h),h.target,c(h,e.lockRef.current))},[]),m=re(function(h){d(h.type,Vo(h),h.target,c(h,e.lockRef.current))},[]);K(function(){return Nr.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:m}),document.addEventListener("wheel",l,kr),document.addEventListener("touchmove",l,kr),document.addEventListener("touchstart",u,kr),function(){Nr=Nr.filter(function(h){return h!==o}),document.removeEventListener("wheel",l,kr),document.removeEventListener("touchmove",l,kr),document.removeEventListener("touchstart",u,kr)}},[]);var f=e.removeScrollBar,y=e.inert;return v(te,null,y?v(o,{styles:eC(i)}):null,f?v(VS,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function rC(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var iC=RS(om,nC),vi=j(function(e,t){return v(Ho,Bt({},e,{ref:t,sideCar:iC}))});vi.classNames=Ho.classNames;var oC=function(e){return typeof document>"u"?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},xr=new WeakMap,Wo=new WeakMap,qo={},bc=0,hm=function(e){return e&&(e.host||hm(e.parentNode))},aC=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=hm(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})},sC=function(e,t,n,r){var i=aC(t,Array.isArray(e)?e:[e]);qo[n]||(qo[n]=new WeakMap);var o=qo[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(m){if(c.has(m))u(m);else try{var f=m.getAttribute(r),y=f!==null&&f!=="false",h=(xr.get(m)||0)+1,g=(o.get(m)||0)+1;xr.set(m,h),o.set(m,g),s.push(m),h===1&&y&&Wo.set(m,!0),g===1&&m.setAttribute(n,"true"),y||m.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",m,_)}})};return u(t),c.clear(),bc++,function(){s.forEach(function(p){var m=xr.get(p)-1,f=o.get(p)-1;xr.set(p,m),o.set(p,f),m||(Wo.has(p)||p.removeAttribute(r),Wo.delete(p)),f||p.removeAttribute(n)}),bc--,bc||(xr=new WeakMap,xr=new WeakMap,Wo=new WeakMap,qo={})}},zo=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=t||oC(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),sC(r,i,n,"aria-hidden")):function(){return null}},Jo="Dialog",[gm,MO]=st(Jo),[cC,xt]=gm(Jo),vm=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:o,modal:s=!0}=e,c=F(null),l=F(null),[d,u]=wt({prop:r,defaultProp:i??!1,onChange:o,caller:Jo});return a(cC,{scope:t,triggerRef:c,contentRef:l,contentId:ct(),titleId:ct(),descriptionId:ct(),open:d,onOpenChange:u,onOpenToggle:re(()=>u(p=>!p),[u]),modal:s,children:n})};vm.displayName=Jo;var ym="DialogTrigger",lC=j((e,t)=>{const{__scopeDialog:n,...r}=e,i=xt(ym,n),o=_e(t,i.triggerRef);return a(se.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":Sc(i.open),...r,ref:o,onClick:z(e.onClick,i.onOpenToggle)})});lC.displayName=ym;var _c="DialogPortal",[dC,bm]=gm(_c,{forceMount:void 0}),_m=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,o=xt(_c,t);return a(dC,{scope:t,forceMount:n,children:Ft.map(r,s=>a(rt,{present:n||o.open,children:a(Hn,{asChild:!0,container:i,children:s})}))})};_m.displayName=_c;var Yo="DialogOverlay",wm=j((e,t)=>{const n=bm(Yo,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,o=xt(Yo,e.__scopeDialog);return o.modal?a(rt,{present:r||o.open,children:a(pC,{...i,ref:t})}):null});wm.displayName=Yo;var uC=Un("DialogOverlay.RemoveScroll"),pC=j((e,t)=>{const{__scopeDialog:n,...r}=e,i=xt(Yo,n);return a(vi,{as:uC,allowPinchZoom:!0,shards:[i.contentRef],children:a(se.div,{"data-state":Sc(i.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Kn="DialogContent",Sm=j((e,t)=>{const n=bm(Kn,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,o=xt(Kn,e.__scopeDialog);return a(rt,{present:r||o.open,children:o.modal?a(mC,{...i,ref:t}):a(fC,{...i,ref:t})})});Sm.displayName=Kn;var mC=j((e,t)=>{const n=xt(Kn,e.__scopeDialog),r=F(null),i=_e(t,n.contentRef,r);return K(()=>{const o=r.current;if(o)return zo(o)},[]),a(Cm,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:z(e.onCloseAutoFocus,o=>{o.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:z(e.onPointerDownOutside,o=>{const s=o.detail.originalEvent,c=s.button===0&&s.ctrlKey===!0;(s.button===2||c)&&o.preventDefault()}),onFocusOutside:z(e.onFocusOutside,o=>o.preventDefault())})}),fC=j((e,t)=>{const n=xt(Kn,e.__scopeDialog),r=F(!1),i=F(!1);return a(Cm,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(r.current||n.triggerRef.current?.focus(),o.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const s=o.target;n.triggerRef.current?.contains(s)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),Cm=j((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:o,...s}=e,c=xt(Kn,n),l=F(null),d=_e(t,l);return Bo(),a(te,{children:[a(hi,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:o,children:a(Gn,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":Sc(c.open),...s,ref:d,onDismiss:()=>c.onOpenChange(!1)})}),a(te,{children:[a(yC,{titleId:c.titleId}),a(_C,{contentRef:l,descriptionId:c.descriptionId})]})]})}),wc="DialogTitle",hC=j((e,t)=>{const{__scopeDialog:n,...r}=e,i=xt(wc,n);return a(se.h2,{id:i.titleId,...r,ref:t})});hC.displayName=wc;var Tm="DialogDescription",gC=j((e,t)=>{const{__scopeDialog:n,...r}=e,i=xt(Tm,n);return a(se.p,{id:i.descriptionId,...r,ref:t})});gC.displayName=Tm;var km="DialogClose",vC=j((e,t)=>{const{__scopeDialog:n,...r}=e,i=xt(km,n);return a(se.button,{type:"button",...r,ref:t,onClick:z(e.onClick,()=>i.onOpenChange(!1))})});vC.displayName=km;function Sc(e){return e?"open":"closed"}var Nm="DialogTitleWarning",[OO,xm]=Vw(Nm,{contentName:Kn,titleName:wc,docsSlug:"dialog"}),yC=({titleId:e})=>{const t=xm(Nm),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
41
+ `)},PC=0,Ir=[];function AC(e){var t=U([]),n=U([0,0]),r=U(),i=D(PC++)[0],o=D(Df)[0],s=U(e);K(function(){s.current=e},[e]),K(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var h=QS([e.lockRef.current],(e.shards||[]).map(Bf),!0).filter(Boolean);return h.forEach(function(g){return g.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),h.forEach(function(g){return g.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var c=ie(function(h,g){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!s.current.allowPinchZoom;var _=na(h),w=n.current,S="deltaX"in h?h.deltaX:w[0]-_[0],N="deltaY"in h?h.deltaY:w[1]-_[1],k,E=h.target,R=Math.abs(S)>Math.abs(N)?"h":"v";if("touches"in h&&R==="h"&&E.type==="range")return!1;var j=window.getSelection(),q=j&&j.anchorNode;if(q&&(q===E||q.contains(E)))return!1;var I=Mf(R,E);if(!I)return!0;if(I?k=R:(k=R==="v"?"h":"v",I=Mf(R,E)),!I)return!1;if(!r.current&&"changedTouches"in h&&(S||N)&&(r.current=k),!k)return!0;var G=r.current||k;return IC(G,g,h,G==="h"?S:N,!0)},[]),l=ie(function(h){var g=h;if(!(!Ir.length||Ir[Ir.length-1]!==o)){var _="deltaY"in g?Ff(g):na(g),w=t.current.filter(function(N){return N.name===g.type&&(N.target===g.target||g.target===N.shadowParent)&&EC(N.delta,_)})[0];if(w&&w.should){g.cancelable&&g.preventDefault();return}if(!w){var S=(s.current.shards||[]).map(Bf).filter(Boolean).filter(function(N){return N.contains(g.target)});(S.length>0?c(g,S[0]):!s.current.noIsolation)&&g.cancelable&&g.preventDefault()}}},[]),d=ie(function(h,g,_,w){var S={name:h,delta:g,target:_,should:w,shadowParent:RC(_)};t.current.push(S),setTimeout(function(){t.current=t.current.filter(function(N){return N!==S})},1)},[]),u=ie(function(h){n.current=na(h),r.current=void 0},[]),p=ie(function(h){d(h.type,Ff(h),h.target,c(h,e.lockRef.current))},[]),f=ie(function(h){d(h.type,na(h),h.target,c(h,e.lockRef.current))},[]);K(function(){return Ir.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:f}),document.addEventListener("wheel",l,Tr),document.addEventListener("touchmove",l,Tr),document.addEventListener("touchstart",u,Tr),function(){Ir=Ir.filter(function(h){return h!==o}),document.removeEventListener("wheel",l,Tr),document.removeEventListener("touchmove",l,Tr),document.removeEventListener("touchstart",u,Tr)}},[]);var m=e.removeScrollBar,v=e.inert;return y(Z,null,v?y(o,{styles:xC(i)}):null,m?y(_C,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function RC(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var DC=sC(Af,AC),Ti=H(function(e,t){return y(ea,Ft({},e,{ref:t,sideCar:DC}))});Ti.classNames=ea.classNames;var LC=function(e){return typeof document>"u"?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},Er=new WeakMap,ra=new WeakMap,ia={},Rc=0,Uf=function(e){return e&&(e.host||Uf(e.parentNode))},$C=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=Uf(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})},MC=function(e,t,n,r){var i=$C(t,Array.isArray(e)?e:[e]);ia[n]||(ia[n]=new WeakMap);var o=ia[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",h=(Er.get(f)||0)+1,g=(o.get(f)||0)+1;Er.set(f,h),o.set(f,g),s.push(f),h===1&&v&&ra.set(f,!0),g===1&&f.setAttribute(n,"true"),v||f.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",f,_)}})};return u(t),c.clear(),Rc++,function(){s.forEach(function(p){var f=Er.get(p)-1,m=o.get(p)-1;Er.set(p,f),o.set(p,m),f||(ra.has(p)||p.removeAttribute(r),ra.delete(p)),m||p.removeAttribute(n)}),Rc--,Rc||(Er=new WeakMap,Er=new WeakMap,ra=new WeakMap,ia={})}},oa=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=t||LC(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),MC(r,i,n,"aria-hidden")):function(){return null}},aa="Dialog",[Gf,wj]=ot(aa),[OC,Pt]=Gf(aa),Hf=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:o,modal:s=!0}=e,c=U(null),l=U(null),[d,u]=Ct({prop:r,defaultProp:i??!1,onChange:o,caller:aa});return a(OC,{scope:t,triggerRef:c,contentRef:l,contentId:at(),titleId:at(),descriptionId:at(),open:d,onOpenChange:u,onOpenToggle:ie(()=>u(p=>!p),[u]),modal:s,children:n})};Hf.displayName=aa;var qf="DialogTrigger",jC=H((e,t)=>{const{__scopeDialog:n,...r}=e,i=Pt(qf,n),o=_e(t,i.triggerRef);return a(se.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":$c(i.open),...r,ref:o,onClick:z(e.onClick,i.onOpenToggle)})});jC.displayName=qf;var Dc="DialogPortal",[FC,Kf]=Gf(Dc,{forceMount:void 0}),Vf=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,o=Pt(Dc,t);return a(FC,{scope:t,forceMount:n,children:jt.map(r,s=>a(et,{present:n||o.open,children:a(qn,{asChild:!0,container:i,children:s})}))})};Vf.displayName=Dc;var sa="DialogOverlay",Wf=H((e,t)=>{const n=Kf(sa,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,o=Pt(sa,e.__scopeDialog);return o.modal?a(et,{present:r||o.open,children:a(UC,{...i,ref:t})}):null});Wf.displayName=sa;var BC=Gn("DialogOverlay.RemoveScroll"),UC=H((e,t)=>{const{__scopeDialog:n,...r}=e,i=Pt(sa,n);return a(Ti,{as:BC,allowPinchZoom:!0,shards:[i.contentRef],children:a(se.div,{"data-state":$c(i.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Kn="DialogContent",zf=H((e,t)=>{const n=Kf(Kn,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,o=Pt(Kn,e.__scopeDialog);return a(et,{present:r||o.open,children:o.modal?a(GC,{...i,ref:t}):a(HC,{...i,ref:t})})});zf.displayName=Kn;var GC=H((e,t)=>{const n=Pt(Kn,e.__scopeDialog),r=U(null),i=_e(t,n.contentRef,r);return K(()=>{const o=r.current;if(o)return oa(o)},[]),a(Jf,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:z(e.onCloseAutoFocus,o=>{o.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:z(e.onPointerDownOutside,o=>{const s=o.detail.originalEvent,c=s.button===0&&s.ctrlKey===!0;(s.button===2||c)&&o.preventDefault()}),onFocusOutside:z(e.onFocusOutside,o=>o.preventDefault())})}),HC=H((e,t)=>{const n=Pt(Kn,e.__scopeDialog),r=U(!1),i=U(!1);return a(Jf,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(r.current||n.triggerRef.current?.focus(),o.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const s=o.target;n.triggerRef.current?.contains(s)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),Jf=H((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:o,...s}=e,c=Pt(Kn,n),l=U(null),d=_e(t,l);return Xo(),a(Z,{children:[a(Ni,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:o,children:a(Hn,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":$c(c.open),...s,ref:d,onDismiss:()=>c.onOpenChange(!1)})}),a(Z,{children:[a(WC,{titleId:c.titleId}),a(JC,{contentRef:l,descriptionId:c.descriptionId})]})]})}),Lc="DialogTitle",qC=H((e,t)=>{const{__scopeDialog:n,...r}=e,i=Pt(Lc,n);return a(se.h2,{id:i.titleId,...r,ref:t})});qC.displayName=Lc;var Yf="DialogDescription",KC=H((e,t)=>{const{__scopeDialog:n,...r}=e,i=Pt(Yf,n);return a(se.p,{id:i.descriptionId,...r,ref:t})});KC.displayName=Yf;var Xf="DialogClose",VC=H((e,t)=>{const{__scopeDialog:n,...r}=e,i=Pt(Xf,n);return a(se.button,{type:"button",...r,ref:t,onClick:z(e.onClick,()=>i.onOpenChange(!1))})});VC.displayName=Xf;function $c(e){return e?"open":"closed"}var Qf="DialogTitleWarning",[Sj,Zf]=_S(Qf,{contentName:Kn,titleName:Lc,docsSlug:"dialog"}),WC=({titleId:e})=>{const t=Zf(Qf),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
42
42
 
43
43
  If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
44
44
 
45
- For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return K(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},bC="DialogDescriptionWarning",_C=({contentRef:e,descriptionId:t})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${xm(bC).contentName}}.`;return K(()=>{const r=e.current?.getAttribute("aria-describedby");t&&r&&(document.getElementById(t)||console.warn(n))},[n,e,t]),null},wC=vm,SC=_m,CC=wm,TC=Sm;function yi({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:m,overlayId:f,slotId:y}){return a(wC,{modal:o,open:p,onOpenChange:u,children:p?a(SC,{children:[a(CC,{asChild:!0,children:a("div",{className:m,id:f})}),a(TC,{"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:h=>{h.target===h.currentTarget&&u(!1)},tabIndex:-1,children:n??(y?a("div",{id:y}):null)})})]}):null})}var Pm=500,Xo=null,bi=null,_i=null;function wi(e){return bi?bi(e)?(_i=document.activeElement instanceof HTMLElement?document.activeElement:null,!0):!1:(_i=document.activeElement instanceof HTMLElement?document.activeElement:null,Xo=e,!0)}function it(e){return e.recipientKind==="identity"?`identity:${e.identityId}`:`team:${e.teamId}`}function Am(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 Cc(e){return e.recipientKind==="identity"?it({recipientKind:"identity",identityId:e.identityId}):it({recipientKind:"team",teamId:e.teamId})}function kC(e,t){return Cc(e)===it(t)}function Em(e,t){return e instanceof Bs?"Recipient access changed after this review. Review the refreshed changes before trying again.":t}function Im({checked:e,description:t,disabled:n,label:r,onChange:i}){const o=`recipient-policy-choice-${mi()}`;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 NC(e,t){const n=e.teamMemberships.filter(s=>s.status==="active"),r=new Map(e.identities.map(s=>[s.identityId,s])),i=[...e.teams.filter(s=>s.status==="active").map(s=>{const c=n.filter(l=>l.teamId===s.teamId).map(l=>r.get(l.identityId)?.displayName).filter(l=>!!l);return{key:it({recipientKind:"team",teamId:s.teamId}),label:s.displayName,description:`Team · ${c.length.toLocaleString()} current ${c.length===1?"member":"members"}${c.length?`: ${c.join(", ")}`:""}`}}),...e.identities.filter(s=>s.status==="active"||s.status==="pending").map(s=>({key:it({recipientKind:"identity",identityId:s.identityId}),label:s.displayName,description:`Identity · ${s.status==="pending"?"pending · ":""}locally verified`}))];if(t?.mode!=="project-manage")return i;const o=new Set(i.map(s=>s.key));for(const s of e.projectRecipients){if(s.status!=="active"||s.canonicalProjectIdentity!==t.projectId)continue;const c=Cc(s);if(!o.has(c)){if(s.recipientKind==="team"){const l=e.teams.find(d=>d.teamId===s.teamId);i.push({key:c,label:l?.displayName??"Unavailable Team",description:`${l?.status==="archived"?"Archived Team":"Unavailable Team"} · existing access can only be removed`})}else{const l=r.get(s.identityId);i.push({key:c,label:l?.displayName??"Unavailable Identity",description:`${l?.status==="merged"?"Merged Identity":"Unavailable Identity"} · existing access can only be removed`})}o.add(c)}}return i}function Rm(e){return e.mode==="project-add"?[...new Set(e.projectIds)]:e.mode==="project-manage"?[e.projectId]:[]}function xC(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(Cc):n.filter(r=>kC(r,e.recipient)).map(r=>r.canonicalProjectIdentity)}function PC(e,t,n){const r=t.mode==="recipient-add"?e.filter(s=>!n.includes(s.canonicalProjectIdentity)):e,i=r.map(s=>({...s,description:`${s.existingMemoryCount.toLocaleString()} existing memories`}));if(t.mode!=="recipient-manage")return i;const o=new Set(r.map(s=>s.canonicalProjectIdentity));for(const s of n)o.has(s)||i.push({canonicalProjectIdentity:s,displayName:s,existingMemoryCount:0,description:"Unavailable Project · existing access can only be removed"});return i}function AC(e,t,n){return e.mode==="project-add"?Rm(e).flatMap(r=>t.flatMap(i=>{const o=Am(i);return o?[{canonicalProjectIdentity:r,recipient:o,action:"add"}]:[]})):e.mode==="project-manage"?[...new Set([...n,...t])].flatMap(r=>{const i=Am(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 EC(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 Dm(e,t){let n=!1,r=!1,i=!1,o=!1;const s=it(t);for(const c of e){const{change:l,outcome:d}=c;it(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 IC(e){const t=new Set(e.selectedRecipients.map(it)),n=new Map;for(const r of e.normalizedChanges){const i=it(r.recipient);t.has(i)||n.set(i,r.recipient)}return[...n.values()]}function RC(e){const t=new Set;return e.filter(n=>t.has(n.deviceId)?!1:(t.add(n.deviceId),!0))}function DC({preview:e,recipientLabels:t}){const n=RC(e.effectiveDevices),r=IC(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(i=>a("li",{children:[a("strong",{className:"recipient-policy-management-name",children:i.displayName}),a("span",{children:[" ","— Access changes affect ",i.existingMemoryCount.toLocaleString()," existing memories",i.futureMemoriesShared?" and future activity":"; future activity is not included"]})]},i.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(i=>a("li",{children:[a("strong",{className:"recipient-policy-management-name",children:i.displayName})," ",a("span",{children:["— ",Dm(e.outcomes,i)," · "]}),i.recipientKind==="identity"?a("span",{children:"Identity · locally verified"}):a("span",{className:"recipient-policy-management-recipient-context",children:["Team · ",i.currentMembers.length.toLocaleString()," current"," ",i.currentMembers.length===1?"member":"members",i.currentMembers.length?a(te,{children:[":"," ",a("span",{className:"recipient-policy-management-member-names",children:i.currentMembers.map(o=>o.displayName).join(", ")})]}):null,". Future Team members"," ",i.futureMembersInherit?"inherit":"do not inherit"," access."]})]},it(i))),r.map(i=>a("li",{children:[a("strong",{className:"recipient-policy-management-name",children:t.get(it(i))??(i.recipientKind==="team"?i.teamId:i.identityId)})," ",a("span",{children:["— ",Dm(e.outcomes,i)," ·"," ",i.recipientKind==="team"?"Team":"Identity"]})]},it(i)))]})]}),a("section",{"aria-labelledby":"recipient-policy-review-availability",children:[a("h3",{id:"recipient-policy-review-availability",children:"Resulting availability"}),n.length?a(te,{children:[a("p",{children:["After the update, the affected Projects will be available on"," ",n.length.toLocaleString()," current"," ",n.length===1?"device":"devices"," across all recipients."]}),a("ul",{children:n.map(i=>a("li",{className:"recipient-policy-management-name",children:i.displayName},i.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(te,{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(i=>a("li",{className:"recipient-policy-management-name",children:i.displayName},i.canonicalProjectIdentity))})]}):null]})]})}function LC({preview:e,result:t}){const n=t.status==="applied"?"Applied":t.status==="not_found"?"Not found":`${t.status.charAt(0).toUpperCase()}${t.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: ",n,". Writes: ",t.writeCount.toLocaleString(),"."]}),t.errorCode?a("p",{children:["Error code: ",t.errorCode.replaceAll("_"," "),"."]}):null,t.outcomes.length?a("ul",{children:t.outcomes.map(r=>{const i=e.projects.find(s=>s.canonicalProjectIdentity===r.change.canonicalProjectIdentity)?.displayName??"Selected Project",o=e.selectedRecipients.find(s=>it(s)===it(r.change.recipient))?.displayName??(r.change.recipient.recipientKind==="team"?"Team":"Identity");return a("li",{children:[r.change.action==="add"?"Add":"Remove"," ",o," ",r.change.action==="add"?"to":"from"," ",i,":"," ",r.outcome.replaceAll("_"," ")]},`${r.change.canonicalProjectIdentity}:${it(r.change.recipient)}`)})}):null]})})}function $C({intent:e,options:t,projects:n}){const[r,i]=I(null),[o,s]=I([]),[c,l]=I([]),[d,u]=I(null),[p,m]=I(null),[f,y]=I(null),[h,g]=I(""),[_,w]=I(!1),S=F(!1),T=Pe(()=>NC(e,r),[e,r]),k=Pe(()=>new Map([...e.teams.map(Y=>[`team:${Y.teamId}`,Y.displayName]),...e.identities.map(Y=>[`identity:${Y.identityId}`,Y.displayName])]),[e]),P=Pe(()=>new Set(n.map(Y=>Y.canonicalProjectIdentity)),[n]);if(K(()=>{if(bi=Y=>{if(S.current)return!1;const ge=xC(Y,e);return i(Y),l(ge),s(Y.mode==="recipient-add"?[]:ge),u(null),m(null),y(null),g(""),w(!1),S.current=!1,!0},Xo){const Y=Xo;Xo=null,bi(Y)}return()=>{bi=null}},[e]),K(()=>{p&&document.getElementById("recipient-policy-management-title")?.focus()},[p]),!r)return null;const E=EC(r),M=Rm(r),U=r.mode==="recipient-manage"?!1:M.some(Y=>!P.has(Y)),N=(r.mode==="recipient-add"||r.mode==="recipient-manage")&&!T.some(Y=>Y.key===it(r.recipient)),G=t.loading||t.loadError||U||N,A=AC(r,o,c),$=A.length>Pm,L=(r.mode==="project-add"||r.mode==="recipient-add")&&o.length===0,J=r.mode!=="project-add"&&r.mode!=="recipient-add"&&A.length===0,H=PC(n,r,c),x=p?.status==="applied",R=p?x?"Recipient access updated":"Recipient access needs attention":d?"Review recipient access":E.title,B=p?x?"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.":E.description,V=()=>{S.current||(i(null),u(null),m(null),y(null),g(""))},he=Y=>{s(ge=>ge.includes(Y)?ge.filter(Z=>Z!==Y):[...ge,Y]),y(null),g("")},ue=async()=>{if(!(G||L||J||$||S.current)){S.current=!0,w(!0),y(null),g("Reviewing exact recipient access changes.");try{u(await Q_({version:1,changes:A})),g("Review ready. Confirm the exact changes.")}catch(Y){y(Em(Y,"Unable to review recipient access changes.")),g("")}finally{S.current=!1,w(!1)}}},ce=async()=>{if(!(!d||S.current)){S.current=!0,w(!0),y(null),g("Saving recipient access changes.");try{const Y=await ew({version:1,changes:d.normalizedChanges,reviewedPolicyDigest:d.reviewedPolicyDigest});m(Y),g("");try{await t.onCommitted?.(Y)}catch{y("Recipient access was saved, but this view could not refresh.")}}catch(Y){Y instanceof Bs&&(u(null),g("")),y(Em(Y,"Unable to save recipient access changes."))}finally{S.current=!1,w(!1)}}};let be=null;return t.loading?be="Loading the complete recipient access inventory…":t.loadError?be="The complete recipient access inventory is unavailable. Refresh and try again.":U?be="One selected Project is no longer available. Refresh and try again.":N&&(be="This recipient is no longer available. Refresh and try again."),a(yi,{ariaDescribedby:"recipient-policy-management-description",ariaLabelledby:"recipient-policy-management-title",contentClassName:"modal recipient-policy-management-dialog",contentId:"recipientPolicyManagementDialog",onCloseAutoFocus:Y=>{Y.preventDefault();const ge=r.mode.startsWith("project-")?"tabBtn-projects":"tabBtn-sharing",Z=_i?.isConnected?_i:document.getElementById(ge);Z instanceof HTMLElement&&Z.focus(),_i=null},onOpenAutoFocus:Y=>{const ge=document.getElementById("recipient-policy-management-title");ge&&(Y.preventDefault(),ge.focus())},onOpenChange:Y=>{Y||V()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientPolicyManagementDialogBackdrop",children:a("div",{"aria-busy":_||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:R}),a($o,{ariaLabel:`Close ${R}`,className:"modal-close-button recipient-policy-management-target",disabled:_,onClick:V})]}),a("div",{className:"modal-body recipient-policy-management-selection",children:[a("p",{className:"small",id:"recipient-policy-management-description",children:B}),be?a("p",{"aria-live":"polite",role:t.loadError?"alert":"status",children:be}):p&&d?a(LC,{preview:d,result:p}):d?a(DC,{preview:d,recipientLabels:k}):r.mode==="recipient-add"||r.mode==="recipient-manage"?a("fieldset",{className:"sync-dialog-radio-list",disabled:_,children:[a("legend",{children:E.legend}),H.length?H.map(Y=>a(Im,{checked:o.includes(Y.canonicalProjectIdentity),description:Y.description,disabled:_,label:Y.displayName,onChange:()=>he(Y.canonicalProjectIdentity)},Y.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:_,children:[a("legend",{children:E.legend}),T.length?T.map(Y=>a(Im,{checked:o.includes(Y.key),description:Y.description,disabled:_,label:Y.label,onChange:()=>he(Y.key)},Y.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:h}),f?a("p",{"aria-live":"assertive",role:"alert",children:f}):null,$?a("p",{"aria-live":"assertive",role:"alert",children:["This selection creates ",A.length.toLocaleString()," access changes. Review at most ",Pm.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:_,onClick:d&&!p?()=>{u(null),g("")}:V,type:"button",children:p?"Done":d?"Back":"Cancel"}),!p&&!be?a("button",{className:"settings-button sync-dialog-confirm recipient-policy-management-target",disabled:_||!d&&(L||J||$),onClick:()=>{d?ce():ue()},type:"button",children:_?d?"Saving…":"Reviewing…":d?"Confirm changes":"Review changes"}):null]})]})})}function Lm(e,t,n,r={}){Be(a($C,{intent:n,options:r,projects:t}),e)}function Zo(e){return e.identity_source!=="unmapped"&&e.read_only!==!0}function MC(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 Qo(e){const t=new Map;for(const n of e)Zo(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))}var Pr=null,Ar=null;function ea(e=[],t=""){if(Ar){const n=Ar(e,t);return n||(Pr=null),n}return Pr={projectIds:e,teammateName:t},window.location.hash="#projects",!0}function $m(e){return!e.read_only&&e.identity_source!=="unmapped"&&e.memory_count!=null&&!e.guardrail_warnings.some(t=>t.requires_confirmation)}function Mm(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 OC(e){const t=`share-project-${mi()}`,n=$m(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 jC({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 FC({projects:e,inventoryError:t}){const[n,r]=I(!1),[i,o]=I(""),[s,c]=I([]),[l,d]=I(null),[u,p]=I(null),[m,f]=I(null),[y,h]=I(!1),[g,_]=I(null),[w,S]=I(!1),T=Pe(()=>e.filter($m),[e]);K(()=>{if(Ar=(N,G="")=>{if(t)return!1;const A=[...new Set(N)],$=A.some(L=>!T.some(J=>J.workspace_identity===L));return o(G.trim()),c($?[]:A),S($),d(null),p(null),f($?"The original project selection is no longer available. Refresh Projects and try again.":null),_(null),r(!0),!0},Pr){const N=Pr;Pr=null,Ar(N.projectIds,N.teammateName)}return()=>{Ar=null}},[T,t]),K(()=>{t&&(Pr=null,r(!1),o(""),c([]),d(null),p(null),f(null),_(null),S(!1))},[t]);const k=()=>{y||r(!1)},P=N=>{c(G=>G.includes(N)?G.filter(A=>A!==N):[...G,N])},E=async()=>{if(f(null),!i.trim()){f("Enter your teammate's name.");return}if(s.length===0){f("Select at least one project.");return}h(!0);try{d(await ow({teammate_name:i.trim(),project_ids:s}))}catch(N){f(Mm(N,"Unable to review this invitation."))}finally{h(!1)}},M=async()=>{if(l){f(null),h(!0);try{p(await aw({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),f(Mm(N,"Unable to create this invitation."))}finally{h(!1)}}},U=async()=>{if(u){f(null),_(null);try{if(!navigator.clipboard)throw new Error("Clipboard access is unavailable.");await navigator.clipboard.writeText(u.invite.link),_("Invite copied.")}catch(N){f(N instanceof Error?N.message:"Unable to copy the invitation.")}}};return a(te,{children:[a("button",{"aria-describedby":t?"project-share-inventory-error":void 0,className:"settings-button",disabled:t||T.length===0,onClick:()=>Ar?.([]),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(yi,{ariaDescribedby:"project-share-description",ariaLabelledby:"project-share-title",contentClassName:"modal",contentId:"projectShareDialog",onOpenChange:N=>{N||k()},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:y,onClick:k,type:"button",children:"×"})]}),a("div",{"aria-busy":y,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:()=>{U()},type:"button",children:"Copy invite"}),g?a("p",{role:"status",children:g}):null]}):l?a(jC,{preview:l}):a(te,{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(OC,{onToggle:P,project:N,selected:s.includes(N.workspace_identity)},N.workspace_identity))]})]}),m?a("p",{role:"alert",children:m}):null]}),a("div",{className:"modal-footer",children:[a("button",{className:"settings-button",disabled:y,onClick:k,type:"button",children:u?"Done":"Cancel"}),u?null:a("button",{className:"settings-button sync-dialog-confirm",disabled:y||w,onClick:()=>{l?M():E()},type:"button",children:y?l?"Creating invite…":"Reviewing…":l?"Create invite":"Review sharing"})]})]})}):null]})}function Om(e,t,n={}){Be(a(FC,{inventoryError:n.inventoryError===!0,projects:t}),e)}var BC=/^(?:local:|identity:|pending_)/iu,UC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,GC=/^[0-9a-f]{12,}$/iu;function jm(e){const t=String(e??"").trim();return!t||BC.test(t)||UC.test(t)||GC.test(t)?"":t}function ta(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.`:"":`${t} is required.`}function HC(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 na(e,t){return e instanceof Error?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.":t:t}function Si(e){return`${e.toLocaleString()} existing ${e===1?"memory":"memories"}`}function KC({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})," — ",Si(t.existingMemoryCount)," and future activity"]},t.canonicalProjectIdentity))})}function VC({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(KC,{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 WC({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," — ",Si(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," — ",Si(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," — ",Si(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 Fm({preview:e}){return e.journey==="team"?a(VC,{preview:e}):a(WC,{preview:e})}function qC({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})," —"," ",Si(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 zC({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 JC({result:e}){const t=e.kind==="team_member"?"Team invitation accepted":"Device added";return a("section",{"aria-describedby":[e.restartRequired?"recipient-invitation-result-detail":null,e.deliveryPending?"recipient-invitation-result-delivery":null].filter(Boolean).join(" ")||void 0,"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 Bm(e,t){return e==="team_member"?{kind:e,policy_team_id:t}:{kind:e,target_identity_id:t}}function YC({intent:e}){const t=e.teams.filter(W=>W.status==="active"),n=e.identities.filter(W=>W.status==="active"),[r,i]=I(null),[o,s]=I("team_member"),[c,l]=I(t[0]?.teamId??""),[d,u]=I(""),[p,m]=I(null),[f,y]=I(null),[h,g]=I(null),[_,w]=I(null),[S,T]=I(""),[k,P]=I(""),[E,M]=I(null),[U,N]=I(!1),[G,A]=I(""),[$,L]=I(""),J=F(null),H=F(0),x=F(""),R=F(!1);K(()=>{if(_){document.getElementById("recipient-invitation-result")?.focus();return}if(h){document.getElementById("project-share-invitation-result")?.focus();return}f?.kind==="project_share_invite"&&document.getElementById("project-share-invitation-projects")?.focus()},[f,h,_]);const B=()=>{H.current+=1,x.current="",R.current=!1,u(""),m(null),y(null),g(null),w(null),T(""),P(""),M(null),A(""),L("")},V=(W,oe)=>{B(),J.current=oe,i(W)},he=()=>{U||(i(null),B())},ue=W=>{H.current+=1,x.current=W,u(W)},ce=W=>{s(W),l(W==="team_member"?t[0]?.teamId??"":n[0]?.identityId??""),B()},be=async()=>{if(c){N(!0),L(""),A("Reviewing invitation…");try{m((await tw(Bm(o,c))).preview),A("Review ready. Confirm the invitation details.")}catch(W){L(na(W,"Unable to review this invitation.")),A("")}finally{N(!1)}}},Y=async()=>{if(p){N(!0),L(""),A("Creating invitation…");try{M(await nw({...Bm(o,c),reviewed_onboarding_digest:p.reviewedOnboardingDigest})),A("Invitation created.")}catch(W){W instanceof Error&&W.message==="reviewed_onboarding_stale"&&m(null),L(na(W,"Unable to create this invitation.")),A("")}finally{N(!1)}}},ge=async()=>{const W=x.current.trim(),oe=H.current;if(!W){L("Paste an invitation first.");return}const Ve=()=>H.current===oe&&x.current.trim()===W;N(!0),L(""),A("Reviewing invitation…");try{const Me=await Lu(W);if(!Ve())return;y(Me),Me.kind==="project_share_invite"&&(T(jm(Me.recipient_name)),P(jm(Me.device_name))),A(Me.kind==="add_device"?(Me.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.":Me.kind==="team_member"?"Review ready. Confirm before accepting.":Me.kind==="project_share_invite"?"Review ready. Confirm the exact Projects before accepting.":"Open Advanced Team administration to continue with this invitation.")}catch(Me){if(!Ve())return;L(na(Me,"Unable to review this invitation.")),A("")}finally{N(!1)}},Z=async()=>{if(!(U||R.current||_)&&!(!f||f.kind==="legacy_team_invite")&&!(f.kind==="project_share_invite"&&!(f.projects?.length??0))&&!(f.kind==="project_share_invite"&&(ta(S,"Identity display name")||ta(k,"Device display name")))){R.current=!0,N(!0),L(""),A("Accepting invitation…");try{const W=f.kind==="project_share_invite"?await Fs(d.trim(),{recipient_name:S.trim(),device_name:k.trim()}):await Fs(d.trim(),{recipient_name:f.recipient_name,device_name:f.device_name,reviewed_onboarding_digest:f.onboarding.reviewedOnboardingDigest});if(f.kind==="project_share_invite")g(HC(W)),A("");else{const oe=f.kind;w({kind:oe,restartRequired:W.restart_required===!0||W.setup_state==="restart_required",detail:(typeof W.detail=="string"?W.detail.trim():"")||"Restart codemem before continuing.",deliveryPending:oe==="add_device"&&(f.onboarding?.projects?.length??0)>0}),A("")}}catch(W){R.current=!1;const oe=W instanceof Error?W.message.trim():"";L(na(W,f.kind==="project_share_invite"&&oe?oe:"Unable to accept this invitation.")),A("")}finally{N(!1)}}},Ce=async()=>{const W=E?.invite.link||E?.invite.encoded||"";if(!W){L("The invitation text is unavailable.");return}try{await navigator.clipboard.writeText(W),A("Invitation copied.")}catch{L("Unable to copy the invitation.")}},le=f?.kind==="team_member"||f?.kind==="add_device"?f.onboarding:null,ee=f?.kind==="project_share_invite"?f:null,xe=ee?ta(S,"Identity display name"):"",pe=ee?ta(k,"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=>{ce("team_member"),V("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=>{ce("add_device"),V("create",W.currentTarget)},type:"button",children:"Add a device"}),a("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>ea(),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=>V("accept",W.currentTarget),type:"button",children:"Review invitation"}),a("p",{className:"small",children:"Legacy invitation import remains under Advanced Team administration."})]}),r?a(yi,{ariaDescribedby:"recipient-invitation-description",ariaLabelledby:"recipient-invitation-title",contentClassName:"modal recipient-policy-invitation-dialog",contentId:"recipientInvitationDialog",onCloseAutoFocus:W=>{W.preventDefault(),J.current?.focus(),J.current=null},onOpenAutoFocus:W=>{W.preventDefault(),document.getElementById("recipient-invitation-title")?.focus()},onOpenChange:W=>{W||he()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientInvitationDialogBackdrop",children:a("div",{"aria-busy":U,className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:"recipient-invitation-title",tabIndex:-1,children:_?"Invitation accepted":r==="create"?"Create invitation":"Review invitation"}),a($o,{ariaLabel:"Close invitation",className:"modal-close-button recipient-policy-sharing-target-24",disabled:U,onClick:he})]}),a("div",{className:"modal-body",children:[a("p",{className:"small",id:"recipient-invitation-description",children:_?"The invitation has been accepted.":"Confirm exactly what this invitation includes before continuing."}),r==="create"&&!p&&!E?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"&&!f&&!_?a("label",{className:"field",htmlFor:"recipient-invitation-value",children:[a("span",{children:"Invitation"}),a("textarea",{id:"recipient-invitation-value",onInput:W=>{ue(W.currentTarget.value),y(null),g(null),A(""),L("")},rows:5,value:d})]}):null,p?a(Fm,{preview:p}):null,le&&!_?a(Fm,{preview:le}):null,ee&&!h?a(qC,{deviceName:k,deviceNameError:pe,invite:ee,onDeviceNameChange:W=>{P(W),L("")},onRecipientNameChange:W=>{T(W),L("")},recipientName:S,recipientNameError:xe}):null,h?a(zC,{result:h}):null,_?a(JC,{result:_}):null,E?a("div",{children:[a("p",{children:"Share the invitation with the recipient."}),a("button",{className:"settings-button",onClick:()=>{Ce()},type:"button",children:"Copy invitation"})]}):null,f?.kind==="legacy_team_invite"?a("p",{children:"Use Advanced Team administration to review and import this 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:U,onClick:he,type:"button",children:E||h||_?"Done":"Cancel"}),r==="create"&&!E?a("button",{className:"settings-button sync-dialog-confirm",disabled:U||!c,onClick:()=>{p?Y():be()},type:"button",children:U?"Working…":p?"Create invitation":"Review invitation"}):r==="accept"&&!f&&!_?a("button",{className:"settings-button sync-dialog-confirm",disabled:U,onClick:()=>{ge()},type:"button",children:U?"Reviewing…":"Review invitation"}):le&&!_||ee&&!h?a("button",{className:"settings-button sync-dialog-confirm",disabled:U||!!(ee&&(!ee.projects?.length||xe||pe)),onClick:()=>{Z()},type:"button",children:U?"Accepting…":ee?"Accept Project access":"Accept invitation"}):null]})]})}):null]})}var Vn=[{id:"teams",label:"Teams"},{id:"identities",label:"Identities"},{id:"received",label:"Received"},{id:"invitations",label:"Invitations"}];function Wn(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function Ci(e,t){return e.length?e.join(", "):t}function Um(e,t){return[...new Set(e)].flatMap(n=>{const r=t.get(n);return r?[r.displayName]:[]})}function Gm({descriptionId:e,displayName:t,recipient:n}){const r=()=>{wi({mode:"recipient-manage",recipient:n})},i=()=>{wi({mode:"recipient-add",recipient:n})};return a(te,{children:[a("div",{className:"peer-actions recipient-policy-sharing-actions recipient-policy-sharing-responsive-actions",children:[a("button",{"aria-describedby":e,"aria-label":`Add Projects for ${t}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",onClick:i,type:"button",children:"Add projects"}),a("button",{"aria-label":`Manage Projects for ${t}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",onClick:r,type:"button",children:"Manage projects"})]}),a("p",{className:"small",id:e,children:"Add projects only adds the selected Projects after you preview the exact changes."})]})}function XC({intent:e,projects:t}){const n=e.teams.filter(o=>o.status==="active"),r=new Map(e.identities.filter(o=>o.status==="active").map(o=>[o.identityId,o])),i=new Map(t.map(o=>[o.canonicalProjectIdentity,o]));return n.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:n.map((o,s)=>{const c=[...new Set(e.teamMemberships.filter(f=>f.status==="active"&&f.teamId===o.teamId&&r.has(f.identityId)).map(f=>f.identityId))],l=c.map(f=>r.get(f)?.displayName??""),d=new Set(e.identityDevices.filter(f=>f.status==="active"&&c.includes(f.identityId)).map(f=>f.deviceId)).size,u=Um(e.projectRecipients.filter(f=>f.status==="active"&&f.recipientKind==="team"&&f.teamId===o.teamId).map(f=>f.canonicalProjectIdentity),i),p=`recipient-policy-sharing-team-title-${s}`,m=`recipient-policy-sharing-team-add-description-${s}`;return a("article",{"aria-labelledby":p,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:p,children:o.displayName}),a("span",{className:"badge actor-badge",children:"Team"})]}),a("dl",{className:"recipient-policy-sharing-details",children:[a("div",{children:[a("dt",{children:"Current member Identities"}),a("dd",{children:[Wn(l.length,"active member")," —"," ",Ci(l,"No active members")]})]}),a("div",{children:[a("dt",{children:"Registered devices"}),a("dd",{children:Wn(d,"active registered device")})]}),a("div",{children:[a("dt",{children:"Shared Projects"}),a("dd",{children:[Wn(u.length,"active shared Project")," —"," ",Ci(u,"No Projects shared")]})]}),a("div",{children:[a("dt",{children:"Future Team members"}),a("dd",{children:"Yes — future Team members inherit the Team’s shared Projects."})]})]}),a(Gm,{descriptionId:m,displayName:o.displayName,recipient:{recipientKind:"team",teamId:o.teamId}})]},o.teamId)})})}function ZC({intent:e,projects:t}){const n=e.identities.filter(o=>o.status==="active"),r=new Map(e.teams.filter(o=>o.status==="active").map(o=>[o.teamId,o])),i=new Map(t.map(o=>[o.canonicalProjectIdentity,o]));return n.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:n.map((o,s)=>{const c=e.identityDevices.filter(m=>m.status==="active"&&m.identityId===o.identityId),l=[...new Set(e.teamMemberships.filter(m=>m.status==="active"&&m.identityId===o.identityId&&r.has(m.teamId)).map(m=>m.teamId))].map(m=>r.get(m)?.displayName??""),d=Um(e.projectRecipients.filter(m=>m.status==="active"&&m.recipientKind==="identity"&&m.identityId===o.identityId).map(m=>m.canonicalProjectIdentity),i),u=`recipient-policy-sharing-identity-title-${s}`,p=`recipient-policy-sharing-identity-add-description-${s}`;return a("article",{"aria-labelledby":u,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:u,children:o.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:[Wn(c.length,"active registered device")," —"," ",Ci(c.map(m=>m.displayName),"No active devices")]})]}),a("div",{children:[a("dt",{children:"Team memberships"}),a("dd",{children:[Wn(l.length,"active Team membership")," —"," ",Ci(l,"No active Team memberships")]})]}),a("div",{children:[a("dt",{children:"Directly shared Projects"}),a("dd",{children:[Wn(d.length,"directly shared active Project")," —"," ",Ci(d,"No Projects shared directly")]})]})]}),a("p",{className:"small",children:"Team Projects are shown on Team cards because per-device eligibility cannot be inferred from Identity membership alone."}),a(Gm,{descriptionId:p,displayName:o.displayName,recipient:{recipientKind:"identity",identityId:o.identityId}})]},o.identityId)})})}function QC({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:Wn(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 eT({intent:e,options:t,projects:n}){const[r,i]=I("teams"),o=F([]),s=l=>{const d=Vn[l];d&&(i(d.id),o.current[l]?.focus())},c=(l,d)=>{let u=null;l.key==="ArrowRight"?u=(d+1)%Vn.length:l.key==="ArrowLeft"?u=(d-1+Vn.length)%Vn.length:l.key==="Home"?u=0:l.key==="End"&&(u=Vn.length-1),u!==null&&(l.preventDefault(),s(u))};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("div",{"aria-label":"Sharing views",className:"recipient-policy-sharing-tabs recipient-policy-sharing-responsive-tabs",role:"tablist",children:Vn.map((l,d)=>a("button",{"aria-controls":`recipient-policy-sharing-panel-${l.id}`,"aria-selected":r===l.id,className:`tab-btn recipient-policy-sharing-tab recipient-policy-sharing-target recipient-policy-sharing-target-24${r===l.id?" active":""}`,id:`recipient-policy-sharing-tab-${l.id}`,onClick:()=>i(l.id),onKeyDown:u=>c(u,d),ref:u=>{o.current[d]=u},role:"tab",tabIndex:r===l.id?0:-1,type:"button",children:l.label},l.id))}),Vn.map(l=>a("div",{"aria-labelledby":`recipient-policy-sharing-tab-${l.id}`,className:"recipient-policy-sharing-panel",hidden:r!==l.id,id:`recipient-policy-sharing-panel-${l.id}`,role:"tabpanel",children:t.loading?a("p",{"aria-live":"polite",className:"small",role:"status",children:"Loading Sharing details…"}):t.loadError?a("p",{"aria-live":"assertive",role:"alert",children:"Sharing details are unavailable. Refresh and try again."}):l.id==="teams"?a(XC,{intent:e,projects:n}):l.id==="identities"?a(ZC,{intent:e,projects:n}):l.id==="received"?a(QC,{received:t.received??[]}):a(YC,{intent:e})},l.id))]})}function tT(e,t,n,r={}){Be(a(eT,{intent:n,options:r,projects:t}),e)}var Tc={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]};async function nT(){const e=[];let t=0;for(;;){const n=await xo({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return{manageable:Qo(e),received:MC(e)}}var rT={loadIntent:Us,loadProjects:nT,mountManagement:Lm,mountSharing:tT};function iT(e={}){const t={...rT,...e};let n=!1;return async function r(){const i=document.getElementById("recipientPolicySharingMount");if(!i)return;const o=document.getElementById("recipientPolicyManagementMount");n||t.mountSharing(i,[],Tc,{loading:!0});try{const[s,c]=await Promise.all([t.loadProjects(),t.loadIntent()]);t.mountSharing(i,s.manageable,c,{received:s.received}),n=!0,o&&t.mountManagement(o,s.manageable,c,{onCommitted:r})}catch{t.mountSharing(i,[],Tc,{loadError:!0}),o&&t.mountManagement(o,[],Tc,{loadError:!0})}}}var oT=Symbol.for("preact-signals");function ra(){if(rn>1)rn--;else{var e,t=!1;for((function(){var i=oa;for(oa=void 0;i!==void 0;)i.S.v===i.v&&(i.S.i=i.i),i=i.o})();Ti!==void 0;){var n=Ti;for(Ti=void 0,ia++;n!==void 0;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&Vm(n))try{n.c()}catch(i){t||(e=i,t=!0)}n=r}}if(ia=0,rn--,t)throw e}}function aT(e){if(rn>0)return e();Nc=++sT,rn++;try{return e()}finally{ra()}}var $e=void 0;function kc(e){var t=$e;$e=void 0;try{return e()}finally{$e=t}}var Hm,Ti=void 0,rn=0,ia=0,sT=0,Nc=0,oa=void 0,aa=0;function Km(e){if($e!==void 0){var t=e.n;if(t===void 0||t.t!==$e)return t={i:0,S:e,p:$e.s,n:void 0,t:$e,e:void 0,x:void 0,r:t},$e.s!==void 0&&($e.s.n=t),$e.s=t,e.n=t,32&$e.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=$e.s,t.n=void 0,$e.s.n=t,$e.s=t),t}}function Je(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}Je.prototype.brand=oT,Je.prototype.h=function(){return!0},Je.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:kc(function(){var r;(r=t.W)==null||r.call(t)}))},Je.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&&kc(function(){var i;(i=t.Z)==null||i.call(t)}))}},Je.prototype.subscribe=function(e){var t=this;return ki(function(){var n=t.value,r=$e;$e=void 0;try{e(n)}finally{$e=r}},{name:"sub"})},Je.prototype.valueOf=function(){return this.value},Je.prototype.toString=function(){return this.value+""},Je.prototype.toJSON=function(){return this.value},Je.prototype.peek=function(){var e=this;return kc(function(){return e.value})},Object.defineProperty(Je.prototype,"value",{get:function(){var e=Km(this);return e!==void 0&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(ia>100)throw new Error("Cycle detected");(function(n){rn!==0&&ia===0&&n.l!==Nc&&(n.l=Nc,oa={S:n,v:n.v,i:n.i,o:oa})})(this),this.v=e,this.i++,aa++,rn++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{ra()}}}});function xc(e,t){return new Je(e,t)}function Vm(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 Wm(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 qm(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 qn(e,t){Je.call(this,void 0),this.x=e,this.s=void 0,this.g=aa-1,this.f=4,this.W=t?.watched,this.Z=t?.unwatched,this.name=t?.name}qn.prototype=new Je,qn.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===aa))return!0;if(this.g=aa,this.f|=1,this.i>0&&!Vm(this))return this.f&=-2,!0;var e=$e;try{Wm(this),$e=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 $e=e,qm(this),this.f&=-2,!0},qn.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)}Je.prototype.S.call(this,e)},qn.prototype.U=function(e){if(this.t!==void 0&&(Je.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)}},qn.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(qn.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var e=Km(this);if(this.h(),e!==void 0&&(e.i=this.i),16&this.f)throw this.v;return this.v}});function zm(e,t){return new qn(e,t)}function Jm(e){var t=e.m;if(e.m=void 0,typeof t=="function"){rn++;var n=$e;$e=void 0;try{t()}catch(r){throw e.f&=-2,e.f|=8,Pc(e),r}finally{$e=n,ra()}}}function Pc(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,Jm(e)}function cT(e){if($e!==this)throw new Error("Out-of-order effect");qm(this),$e=e,this.f&=-2,8&this.f&&Pc(this),ra()}function Er(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=t?.name,Hm&&Hm.push(this)}Er.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()}},Er.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,Jm(this),Wm(this),rn++;var e=$e;return $e=this,cT.bind(this,e)},Er.prototype.N=function(){2&this.f||(this.f|=2,this.u=Ti,Ti=this)},Er.prototype.d=function(){this.f|=8,1&this.f||Pc(this)},Er.prototype.dispose=function(){this.d()};function ki(e,t){var n=new Er(e,t);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var Ym,Ac,sa,lT=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,jO=[],Xm=[];ki(function(){Ym=this.N})();function Ir(e,t){fe[e]=t.bind(null,fe[e]||function(){})}function ca(e){if(sa){var t=sa;sa=void 0,t()}sa=e&&e.S()}function Zm(e){var t=this,n=e.data,r=uT(n);r.value=n;var i=Pe(function(){for(var c=t,l=t.__v;l=l.__;)if(l.__c){l.__c.__$f|=4;break}var d=zm(function(){var f=r.value.value;return f===0?0:f===!0?"":f||""}),u=zm(function(){return!Array.isArray(d.value)&&!Vu(d.value)}),p=ki(function(){if(this.N=Qm,u.value){var f=d.value;c.__v&&c.__v.__e&&c.__v.__e.nodeType===3&&(c.__v.__e.data=f)}}),m=t.__$u.d;return t.__$u.d=function(){p(),m.call(this)},[u,d]},[]),o=i[0],s=i[1];return o.value?s.peek():s.value}Zm.displayName="ReactiveTextNode",Object.defineProperties(Je.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Zm},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}}),Ir("__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 Je&&(n||(t.__np=n={}),n[i]=o,r[i]=o.peek())}}e(t)}),Ir("__r",function(e,t){if(e(t),t.type!==te){ca();var n,r=t.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,o){var s;return ki(function(){s=this},{name:o}),s.c=i,s})(function(){var i;lT&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof t.type=="function"?t.type.displayName||t.type.name:""))),Ac=r,ca(n)}}),Ir("__e",function(e,t,n,r){ca(),Ac=void 0,e(t,n,r)}),Ir("diffed",function(e,t){ca(),Ac=void 0;var n;if(typeof t.type=="string"&&(n=t.__e)){var r=t.__np,i=t.props;if(r){var o=n.U;if(o)for(var s in o){var c=o[s];c!==void 0&&!(s in r)&&(c.d(),o[s]=void 0)}else o={},n.U=o;for(var l in r){var d=o[l],u=r[l];d===void 0?(d=dT(n,l,u),o[l]=d):d.o(u,i)}}}e(t)});function dT(e,t,n,r){var i=t in e&&e.ownerSVGElement===void 0,o=xc(n),s=n.peek();return{o:function(c,l){o.value=c,s=c.peek()},d:ki(function(){this.N=Qm;var c=o.value.value;s!==c?(s=void 0,i?e[t]=c:c!=null&&(c!==!1||t[4]==="-")?e.setAttribute(t,c):e.removeAttribute(t)):s=void 0})}}Ir("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)}),Ir("__h",function(e,t,n,r){(r<3||r===9)&&(t.__$f|=2),e(t,n,r)}),_t.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 uT(e,t){return Pe(function(){return xc(e,t)},[])}var FO=typeof requestAnimationFrame>"u"?setTimeout:function(e){var t=function(){clearTimeout(n),cancelAnimationFrame(r),e()},n=setTimeout(t,35),r=requestAnimationFrame(t)},pT=function(e){queueMicrotask(function(){queueMicrotask(e)})};function mT(){aT(function(){for(var e;e=Xm.shift();)Ym.call(e)})}function Qm(){Xm.push(this)===1&&(fe.requestAnimationFrame||pT)(mT)}function la(e){const t=e+"CollectionProvider",[n,r]=st(t),[i,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=h=>{const{scope:g,children:_}=h,w=nn.useRef(null),S=nn.useRef(new Map).current;return a(i,{scope:g,itemMap:S,collectionRef:w,children:_})};s.displayName=t;const c=e+"CollectionSlot",l=Un(c),d=nn.forwardRef((h,g)=>{const{scope:_,children:w}=h;return a(l,{ref:_e(g,o(c,_).collectionRef),children:w})});d.displayName=c;const u=e+"CollectionItemSlot",p="data-radix-collection-item",m=Un(u),f=nn.forwardRef((h,g)=>{const{scope:_,children:w,...S}=h,T=nn.useRef(null),k=_e(g,T),P=o(u,_);return nn.useEffect(()=>(P.itemMap.set(T,{ref:T,...S}),()=>{P.itemMap.delete(T)})),a(m,{[p]:"",ref:k,children:w})});f.displayName=u;function y(h){const g=o(e+"CollectionConsumer",h);return nn.useCallback(()=>{const _=g.collectionRef.current;if(!_)return[];const w=Array.from(_.querySelectorAll(`[${p}]`));return Array.from(g.itemMap.values()).sort((S,T)=>w.indexOf(S.ref.current)-w.indexOf(T.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:s,Slot:d,ItemSlot:f},y,r]}var ef=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"}),fT="VisuallyHidden",da=j((e,t)=>a(se.span,{...e,ref:t,style:{...ef,...e.style}}));da.displayName=fT;var hT=da,Ec="ToastProvider",[Ic,gT,vT]=la("Toast"),[tf,BO]=st("Toast",[vT]),[yT,ua]=tf(Ec),nf=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:i="right",swipeThreshold:o=50,children:s}=e,[c,l]=I(null),[d,u]=I(0),p=F(!1),m=F(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${Ec}\`. Expected non-empty \`string\`.`),a(Ic.Provider,{scope:t,children:a(yT,{scope:t,label:n,duration:r,swipeDirection:i,swipeThreshold:o,toastCount:d,viewport:c,onViewportChange:l,onToastAdd:re(()=>u(f=>f+1),[]),onToastRemove:re(()=>u(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:p,isClosePausedRef:m,children:s})})};nf.displayName=Ec;var rf="ToastViewport",bT=["F8"],Rc="toast.viewportPause",Dc="toast.viewportResume",of=j((e,t)=>{const{__scopeToast:n,hotkey:r=bT,label:i="Notifications ({hotkey})",...o}=e,s=ua(rf,n),c=gT(n),l=F(null),d=F(null),u=F(null),p=F(null),m=_e(t,p,s.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),y=s.toastCount>0;K(()=>{const g=_=>{r.length!==0&&r.every(w=>_[w]||_.code===w)&&p.current?.focus()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[r]),K(()=>{const g=l.current,_=p.current;if(y&&g&&_){const w=()=>{if(!s.isClosePausedRef.current){const P=new CustomEvent(Rc);_.dispatchEvent(P),s.isClosePausedRef.current=!0}},S=()=>{if(s.isClosePausedRef.current){const P=new CustomEvent(Dc);_.dispatchEvent(P),s.isClosePausedRef.current=!1}},T=P=>{g.contains(P.relatedTarget)||S()},k=()=>{g.contains(document.activeElement)||S()};return g.addEventListener("focusin",w),g.addEventListener("focusout",T),g.addEventListener("pointermove",w),g.addEventListener("pointerleave",k),window.addEventListener("blur",w),window.addEventListener("focus",S),()=>{g.removeEventListener("focusin",w),g.removeEventListener("focusout",T),g.removeEventListener("pointermove",w),g.removeEventListener("pointerleave",k),window.removeEventListener("blur",w),window.removeEventListener("focus",S)}}},[y,s.isClosePausedRef]);const h=re(({tabbingDirection:g})=>{const _=c().map(w=>{const S=w.ref.current,T=[S,...LT(S)];return g==="forwards"?T:T.reverse()});return(g==="forwards"?_.reverse():_).flat()},[c]);return K(()=>{const g=p.current;if(g){const _=w=>{const S=w.altKey||w.ctrlKey||w.metaKey;if(w.key==="Tab"&&!S){const T=document.activeElement,k=w.shiftKey;if(w.target===g&&k){d.current?.focus();return}const P=h({tabbingDirection:k?"backwards":"forwards"}),E=P.findIndex(M=>M===T);Mc(P.slice(E+1))?w.preventDefault():k?d.current?.focus():u.current?.focus()}};return g.addEventListener("keydown",_),()=>g.removeEventListener("keydown",_)}},[c,h]),a(uS,{ref:l,role:"region","aria-label":i.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:y?void 0:"none"},children:[y&&a(Lc,{ref:d,onFocusFromOutsideViewport:()=>{Mc(h({tabbingDirection:"forwards"}))}}),a(Ic.Slot,{scope:n,children:a(se.ol,{tabIndex:-1,...o,ref:m})}),y&&a(Lc,{ref:u,onFocusFromOutsideViewport:()=>{Mc(h({tabbingDirection:"backwards"}))}})]})});of.displayName=rf;var af="ToastFocusProxy",Lc=j((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...i}=e,o=ua(af,n);return a(da,{tabIndex:0,...i,ref:t,style:{position:"fixed"},onFocus:s=>{const c=s.relatedTarget;o.viewport?.contains(c)||r()}})});Lc.displayName=af;var Ni="Toast",_T="toast.swipeStart",wT="toast.swipeMove",ST="toast.swipeCancel",CT="toast.swipeEnd",sf=j((e,t)=>{const{forceMount:n,open:r,defaultOpen:i,onOpenChange:o,...s}=e,[c,l]=wt({prop:r,defaultProp:i??!0,onChange:o,caller:Ni});return a(rt,{present:n||c,children:a(NT,{open:c,...s,ref:t,onClose:()=>l(!1),onPause:lt(e.onPause),onResume:lt(e.onResume),onSwipeStart:z(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:z(e.onSwipeMove,d=>{const{x:u,y:p}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${p}px`)}),onSwipeCancel:z(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:z(e.onSwipeEnd,d=>{const{x:u,y:p}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${p}px`),l(!1)})})})});sf.displayName=Ni;var[TT,kT]=tf(Ni,{onClose(){}}),NT=j((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:i,open:o,onClose:s,onEscapeKeyDown:c,onPause:l,onResume:d,onSwipeStart:u,onSwipeMove:p,onSwipeCancel:m,onSwipeEnd:f,...y}=e,h=ua(Ni,n),[g,_]=I(null),w=_e(t,L=>_(L)),S=F(null),T=F(null),k=i||h.duration,P=F(0),E=F(k),M=F(0),{onToastAdd:U,onToastRemove:N}=h,G=lt(()=>{g?.contains(document.activeElement)&&h.viewport?.focus(),s()}),A=re(L=>{!L||L===1/0||(window.clearTimeout(M.current),P.current=new Date().getTime(),M.current=window.setTimeout(G,L))},[G]);K(()=>{const L=h.viewport;if(L){const J=()=>{A(E.current),d?.()},H=()=>{const x=new Date().getTime()-P.current;E.current=E.current-x,window.clearTimeout(M.current),l?.()};return L.addEventListener(Rc,H),L.addEventListener(Dc,J),()=>{L.removeEventListener(Rc,H),L.removeEventListener(Dc,J)}}},[h.viewport,k,l,d,A]),K(()=>{o&&!h.isClosePausedRef.current&&A(k)},[o,k,h.isClosePausedRef,A]),K(()=>(U(),()=>N()),[U,N]);const $=Pe(()=>g?pf(g):null,[g]);return h.viewport?a(te,{children:[$&&a(xT,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite",children:$}),a(TT,{scope:n,onClose:G,children:en(a(Ic.ItemSlot,{scope:n,children:a(dS,{asChild:!0,onEscapeKeyDown:z(c,()=>{h.isFocusedToastEscapeKeyDownRef.current||G(),h.isFocusedToastEscapeKeyDownRef.current=!1}),children:a(se.li,{tabIndex:0,"data-state":o?"open":"closed","data-swipe-direction":h.swipeDirection,...y,ref:w,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:z(e.onKeyDown,L=>{L.key==="Escape"&&(c?.(L.nativeEvent),L.nativeEvent.defaultPrevented||(h.isFocusedToastEscapeKeyDownRef.current=!0,G()))}),onPointerDown:z(e.onPointerDown,L=>{L.button===0&&(S.current={x:L.clientX,y:L.clientY})}),onPointerMove:z(e.onPointerMove,L=>{if(!S.current)return;const J=L.clientX-S.current.x,H=L.clientY-S.current.y,x=!!T.current,R=["left","right"].includes(h.swipeDirection),B=["left","up"].includes(h.swipeDirection)?Math.min:Math.max,V=R?B(0,J):0,he=R?0:B(0,H),ue=L.pointerType==="touch"?10:2,ce={x:V,y:he},be={originalEvent:L,delta:ce};x?(T.current=ce,pa(wT,p,be,{discrete:!1})):mf(ce,h.swipeDirection,ue)?(T.current=ce,pa(_T,u,be,{discrete:!1}),L.target.setPointerCapture(L.pointerId)):(Math.abs(J)>ue||Math.abs(H)>ue)&&(S.current=null)}),onPointerUp:z(e.onPointerUp,L=>{const J=T.current,H=L.target;if(H.hasPointerCapture(L.pointerId)&&H.releasePointerCapture(L.pointerId),T.current=null,S.current=null,J){const x=L.currentTarget,R={originalEvent:L,delta:J};mf(J,h.swipeDirection,h.swipeThreshold)?pa(CT,f,R,{discrete:!0}):pa(ST,m,R,{discrete:!0}),x.addEventListener("click",B=>B.preventDefault(),{once:!0})}})})})}),h.viewport)})]}):null}),xT=e=>{const{__scopeToast:t,children:n,...r}=e,i=ua(Ni,t),[o,s]=I(!1),[c,l]=I(!1);return RT(()=>s(!0)),K(()=>{const d=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(d)},[]),c?null:a(Hn,{asChild:!0,children:a(da,{...r,children:o&&a(te,{children:[i.label," ",n]})})})},PT="ToastTitle",AT=j((e,t)=>{const{__scopeToast:n,...r}=e;return a(se.div,{...r,ref:t})});AT.displayName=PT;var ET="ToastDescription",cf=j((e,t)=>{const{__scopeToast:n,...r}=e;return a(se.div,{...r,ref:t})});cf.displayName=ET;var lf="ToastAction",IT=j((e,t)=>{const{altText:n,...r}=e;return n.trim()?a(uf,{altText:n,asChild:!0,children:a($c,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${lf}\`. Expected non-empty \`string\`.`),null)});IT.displayName=lf;var df="ToastClose",$c=j((e,t)=>{const{__scopeToast:n,...r}=e,i=kT(df,n);return a(uf,{asChild:!0,children:a(se.button,{type:"button",...r,ref:t,onClick:z(e.onClick,i.onClose)})})});$c.displayName=df;var uf=j((e,t)=>{const{__scopeToast:n,altText:r,...i}=e;return a(se.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...i,ref:t})});function pf(e){const t=[];return Array.from(e.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),DT(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(...pf(n))}}),t}function pa(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?dc(i,o):i.dispatchEvent(o)}var mf=(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};function RT(e=()=>{}){const t=lt(e);We(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function DT(e){return e.nodeType===e.ELEMENT_NODE}function LT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode: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}});for(;n.nextNode();)t.push(n.currentNode);return t}function Mc(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var $T=nf,MT=of,OT=sf,jT=cf,FT=$c,xi=xc([]),BT=1;function UT(e,t="success",n=8e3){if(!e)return;const r=BT++;xi.value=[...xi.value,{id:r,message:e,variant:t,durationMs:n}]}function GT(e){xi.value=xi.value.filter(t=>t.id!==e)}function HT(){const e=xi.value;return a($T,{duration:8e3,swipeDirection:"right",children:[e.map(t=>a(OT,{className:`toast-root toast-${t.variant}`,duration:t.durationMs,onOpenChange:n=>{n||GT(t.id)},type:t.variant==="error"||t.variant==="warning"?"foreground":"background",children:[a(jT,{className:"toast-message",children:t.message}),a(FT,{"aria-label":"Dismiss",className:"toast-close",children:"×"})]},t.id)),a(MT,{className:"toast-viewport"})]})}function KT(e){Be(a(HT,{}),e)}function ma(e,t,n){const r=document.createElement(e);return t&&(r.className=t),n!=null&&(r.textContent=String(n)),r}function Re(e){return document.getElementById(e)}function Oc(e){return document.getElementById(e)}function jc(e){return document.getElementById(e)}function ff(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function VT(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function WT(e,t){const n=t.trim();if(!n)return ff(e);const r=ff(e);try{const i=new RegExp(`(${VT(n)})`,"ig");return r.replace(i,'<mark class="match">$1</mark>')}catch{return r}}async function Pi(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 qT=new Set(["BUTTON","A","SELECT"]),zT=new Set(["button","checkbox","color","file","image","radio","range","reset","submit"]);function JT(e){return!e||typeof e.closest!="function"?!1:e.closest('[data-primary-action-ignore="true"]')!==null}function YT(e){return e?!!(e instanceof HTMLTextAreaElement||"isContentEditable"in e&&e.isContentEditable):!1}function XT(e){return e?qT.has(e.tagName)?!0:e instanceof HTMLInputElement&&zT.has(e.type):!1}function ZT(e){return e.metaKey||e.ctrlKey}function Rr(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(!JT(n)){if(e.key==="Escape"){if(!t.onCancel)return;e.preventDefault(),t.onCancel();return}XT(n)||YT(n)&&!ZT(e)||(e.preventDefault(),t.onSubmit())}}var zn=["feed","projects","sharing","devices","health","advanced"],hf=["sync","coordinator-admin"],Fc="codemem-tab",gf="codemem-advanced-section",vf="codemem-feed-filter",yf="codemem-feed-scope",QT="codemem-sync-diagnostics",bf="codemem-sync-pairing",_f="codemem-sync-redact",wf=["all","observations","summaries"],Sf=["all","mine","theirs"],b={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,lastSyncActors:[],lastSyncPeers:[],lastShareOperations:[],shareOperationsLoadError:!1,pendingAcceptedSyncPeers:[],lastSyncSharingReview:[],lastSyncLegacySharedReview:null,lastSyncCoordinator:null,lastCoordinatorAdminStatus:null,coordinatorAdminTargetGroup:"",knownProjects:[],lastCoordinatorAdminGroups:[],lastCoordinatorAdminJoinRequests:[],lastCoordinatorAdminDevices:[],lastSyncJoinRequests:[],lastTeamInvite:null,lastTeamJoin:null,syncJoinFlowFeedback:null,syncPeerFeedbackById:new Map,syncPeersSectionFeedback:null,syncJoinRequestsFeedback:null,syncDiscoveredFeedback:null,lastSyncAttempts:[],lastSyncLegacyDevices:[],lastSyncViewModel:null,lastSyncDuplicatePersonDecisions:{},pairingPayloadRaw:null,pairingCommandRaw:"",configDefaults:{},configPath:"",settingsDirty:!1,syncDiagnosticsOpen:!1,syncPairingOpen:!1};function ek(e){return[...zn]}function Ai(e,t){return e==="sync"||e==="coordinator-admin"?"advanced":zn.includes(e)?e:"feed"}function Bc(e=window.location.hash){const t=e.replace(/^#/,"").split("/")[0];return hf.includes(t)?"advanced":zn.includes(t)?t:null}function Uc(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 tk(){const e=Bc();if(e)return Ai(e,b.lastCoordinatorAdminStatus);const t=localStorage.getItem(Fc);return t&&(zn.includes(t)||hf.includes(t))?Ai(t,b.lastCoordinatorAdminStatus):"feed"}function nk(){const e=Uc();if(e)return e;const t=localStorage.getItem(Fc);return t==="coordinator-admin"?"teams":t==="sync"?"sync":localStorage.getItem(gf)==="teams"?"teams":"sync"}function Gc(e,t=!1){b.advancedSection=e,localStorage.setItem(gf,e),t&&(window.location.hash=`advanced/${e}`)}function Cf(e,t={}){const n=Ai(e,b.lastCoordinatorAdminStatus);b.activeTab=n,localStorage.setItem(Fc,n);const r=Bc();t.canonicalHash?window.location.hash=n:r!==n&&(window.location.hash=n==="advanced"?`advanced/${b.advancedSection}`:n)}function rk(){const e=localStorage.getItem(vf)||"all";return wf.includes(e)?e:"all"}function ik(){const e=localStorage.getItem(yf)||"all";return Sf.includes(e)?e:"all"}function ok(e){b.feedTypeFilter=wf.includes(e)?e:"all",localStorage.setItem(vf,b.feedTypeFilter)}function Tf(e){b.feedScopeFilter=Sf.includes(e)?e:"all",localStorage.setItem(yf,b.feedScopeFilter)}function ak(){return localStorage.getItem(QT)==="1"}function sk(e){b.syncPairingOpen=e;try{localStorage.setItem(bf,e?"1":"0")}catch{}}function Ei(){return localStorage.getItem(_f)!=="0"}function ck(e){localStorage.setItem(_f,e?"1":"0")}function lk(){b.activeTab=tk(),b.advancedSection=nk(),b.feedTypeFilter=rk(),b.feedScopeFilter=ik(),b.syncDiagnosticsOpen=ak();try{b.syncPairingOpen=localStorage.getItem(bf)==="1"}catch{b.syncPairingOpen=!1}}var Hc=[{id:"light",label:"Light",mode:"light"},{id:"dark",label:"Dark",mode:"dark"}],kf="codemem-theme";function Nf(e){const t=Hc.find(r=>r.id===e);if(t)return t;const n=e.startsWith("dark")?"dark":"light";return Hc.find(r=>r.id===n)||Hc[0]}function Kc(){const e=localStorage.getItem(kf);return e?Nf(e).id:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function xf(e){const t=Nf(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(kf,t.id)}function dk(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(Kc()==="dark"?"dark":"light"),e.addEventListener("click",()=>{const n=Kc()==="dark"?"light":"dark";xf(n),t(n)})}var uk=Fn(void 0);function Ii(e){const t=gn(uk);return e||t||"ltr"}var Vc="rovingFocusGroup.onEntryFocus",pk={bubbles:!1,cancelable:!0},Ri="RovingFocusGroup",[Wc,Pf,mk]=la(Ri),[fk,Dr]=st(Ri,[mk]),[hk,gk]=fk(Ri),Af=j((e,t)=>a(Wc.Provider,{scope:e.__scopeRovingFocusGroup,children:a(Wc.Slot,{scope:e.__scopeRovingFocusGroup,children:a(vk,{...e,ref:t})})}));Af.displayName=Ri;var vk=j((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:o,currentTabStopId:s,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:l,onEntryFocus:d,preventScrollOnEntryFocus:u=!1,...p}=e,m=F(null),f=_e(t,m),y=Ii(o),[h,g]=wt({prop:s,defaultProp:c??null,onChange:l,caller:Ri}),[_,w]=I(!1),S=lt(d),T=Pf(n),k=F(!1),[P,E]=I(0);return K(()=>{const M=m.current;if(M)return M.addEventListener(Vc,S),()=>M.removeEventListener(Vc,S)},[S]),a(hk,{scope:n,orientation:r,dir:y,loop:i,currentTabStopId:h,onItemFocus:re(M=>g(M),[g]),onItemShiftTab:re(()=>w(!0),[]),onFocusableItemAdd:re(()=>E(M=>M+1),[]),onFocusableItemRemove:re(()=>E(M=>M-1),[]),children:a(se.div,{tabIndex:_||P===0?-1:0,"data-orientation":r,...p,ref:f,style:{outline:"none",...e.style},onMouseDown:z(e.onMouseDown,()=>{k.current=!0}),onFocus:z(e.onFocus,M=>{const U=!k.current;if(M.target===M.currentTarget&&U&&!_){const N=new CustomEvent(Vc,pk);if(M.currentTarget.dispatchEvent(N),!N.defaultPrevented){const G=T().filter(A=>A.focusable);Rf([G.find(A=>A.active),G.find(A=>A.id===h),...G].filter(Boolean).map(A=>A.ref.current),u)}}k.current=!1}),onBlur:z(e.onBlur,()=>w(!1))})})}),Ef="RovingFocusGroupItem",If=j((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:o,children:s,...c}=e,l=ct(),d=o||l,u=gk(Ef,n),p=u.currentTabStopId===d,m=Pf(n),{onFocusableItemAdd:f,onFocusableItemRemove:y,currentTabStopId:h}=u;return K(()=>{if(r)return f(),()=>y()},[r,f,y]),a(Wc.ItemSlot,{scope:n,id:d,focusable:r,active:i,children:a(se.span,{tabIndex:p?0:-1,"data-orientation":u.orientation,...c,ref:t,onMouseDown:z(e.onMouseDown,g=>{r?u.onItemFocus(d):g.preventDefault()}),onFocus:z(e.onFocus,()=>u.onItemFocus(d)),onKeyDown:z(e.onKeyDown,g=>{if(g.key==="Tab"&&g.shiftKey){u.onItemShiftTab();return}if(g.target!==g.currentTarget)return;const _=_k(g,u.orientation,u.dir);if(_!==void 0){if(g.metaKey||g.ctrlKey||g.altKey||g.shiftKey)return;g.preventDefault();let w=m().filter(S=>S.focusable).map(S=>S.ref.current);if(_==="last")w.reverse();else if(_==="prev"||_==="next"){_==="prev"&&w.reverse();const S=w.indexOf(g.currentTarget);w=u.loop?wk(w,S+1):w.slice(S+1)}setTimeout(()=>Rf(w))}}),children:typeof s=="function"?s({isCurrentTabStop:p,hasTabStop:h!=null}):s})})});If.displayName=Ef;var yk={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function bk(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function _k(e,t,n){const r=bk(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return yk[r]}function Rf(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function wk(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var qc=Af,zc=If,fa="Tabs",[Sk,UO]=st(fa,[Dr]),Df=Dr(),[Ck,Jc]=Sk(fa),Lf=j((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:i,defaultValue:o,orientation:s="horizontal",dir:c,activationMode:l="automatic",...d}=e,u=Ii(c),[p,m]=wt({prop:r,onChange:i,defaultProp:o??"",caller:fa});return a(Ck,{scope:n,baseId:ct(),value:p,onValueChange:m,orientation:s,dir:u,activationMode:l,children:a(se.div,{dir:u,"data-orientation":s,...d,ref:t})})});Lf.displayName=fa;var $f="TabsList",Mf=j((e,t)=>{const{__scopeTabs:n,loop:r=!0,...i}=e,o=Jc($f,n),s=Df(n);return a(qc,{asChild:!0,...s,orientation:o.orientation,dir:o.dir,loop:r,children:a(se.div,{role:"tablist","aria-orientation":o.orientation,...i,ref:t})})});Mf.displayName=$f;var Of="TabsTrigger",jf=j((e,t)=>{const{__scopeTabs:n,value:r,disabled:i=!1,...o}=e,s=Jc(Of,n),c=Df(n),l=Uf(s.baseId,r),d=Gf(s.baseId,r),u=r===s.value;return a(zc,{asChild:!0,...c,focusable:!i,active:u,children:a(se.button,{type:"button",role:"tab","aria-selected":u,"aria-controls":d,"data-state":u?"active":"inactive","data-disabled":i?"":void 0,disabled:i,id:l,...o,ref:t,onMouseDown:z(e.onMouseDown,p=>{!i&&p.button===0&&p.ctrlKey===!1?s.onValueChange(r):p.preventDefault()}),onKeyDown:z(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&s.onValueChange(r)}),onFocus:z(e.onFocus,()=>{const p=s.activationMode!=="manual";!u&&!i&&p&&s.onValueChange(r)})})})});jf.displayName=Of;var Ff="TabsContent",Bf=j((e,t)=>{const{__scopeTabs:n,value:r,forceMount:i,children:o,...s}=e,c=Jc(Ff,n),l=Uf(c.baseId,r),d=Gf(c.baseId,r),u=r===c.value,p=F(u);return K(()=>{const m=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(m)},[]),a(rt,{present:i||u,children:({present:m})=>a(se.div,{"data-state":u?"active":"inactive","data-orientation":c.orientation,role:"tabpanel","aria-labelledby":l,hidden:!m,id:d,tabIndex:0,...s,ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0},children:m&&o})})});Bf.displayName=Ff;function Uf(e,t){return`${e}-trigger-${t}`}function Gf(e,t){return`${e}-content-${t}`}var Tk=Lf,kk=Mf,Nk=jf,xk=Bf;function Hf({ariaLabel:e,children:t,listClassName:n,onValueChange:r,tabs:i,triggerClassName:o,value:s}){return a(Tk,{onValueChange:r,value:s,children:[a(kk,{"aria-label":e,className:n,children:i.map(c=>a(Nk,{className:o,disabled:c.disabled,value:c.value,children:c.label},c.value))}),t]})}function Jn({children:e,className:t,forceMount:n=!1,value:r}){return a(xk,{className:t,forceMount:n?!0:void 0,value:r,children:e})}function we(e){return a("input",{...e})}function Pk(e,t){const n=String(e.device_id||"").trim(),r=String(e.group_id||t||"").trim(),i=String(e.display_name||n||"Unnamed device"),o=e.enabled!==!1&&e.enabled!==0,s=[`Device ID ${n||"unknown"}`];return r&&s.push(`Team ID ${r}`),{advancedDetail:`Advanced: ${s.join(" · ")}`,deviceId:n,displayName:i,statusLabel:o?"Enabled in this Team":"Disabled in this Team",teamId:r}}var Ak="codemem-coordinator-admin-target-group",O={activeSection:"groups",inviteGroup:"",inviteTtlHours:"24",invitePolicy:"auto_admit",invitePending:!1,showArchivedGroups:!1,createGroupId:"",createGroupDisplayName:"",groupActionPendingId:"",groupActionPendingKind:"",joinReviewPendingId:"",joinReviewPendingAction:"",deviceActionPendingId:"",deviceActionPendingKind:"",groupRenameDrafts:new Map,deviceRenameDrafts:new Map,deviceRenameServerNames:new Map,groupPreferencesOpen:new Set,groupPreferencesDrafts:new Map,groupScopeManagementOpen:new Set,groupScopeManagementDrafts:new Map,teamSetupGuide:null,availableProjects:[]};function Ek(e){const{summary:t,runDevice:n}=e,r=Array.isArray(b.lastCoordinatorAdminDevices)?b.lastCoordinatorAdminDevices:[];return v(Jn,{className:"coordinator-admin-panel",value:"devices"},v("h3",null,"Enrolled devices"),v("p",{class:"peer-submeta"},t.readiness==="ready"?"Rename, disable, re-enable, or remove Team devices here. Space access is granted from Spaces below; Team membership alone does not share memories.":"Finish setup first. Device administration stays disabled until Teams is ready."),r.length?v("div",{class:"peer-list"},r.map(i=>{const o=Pk(i,String(b.lastCoordinatorAdminStatus?.active_group||"")),{deviceId:s,displayName:c,teamId:l}=o,d=O.deviceActionPendingId===s,u=O.deviceRenameDrafts.get(s)??String(i.display_name||""),p=i.enabled!==!1&&i.enabled!==0,m=!s||d||t.readiness!=="ready";return v("div",{class:"peer-card peer-card--padded",key:s||String(i.fingerprint||"unknown")},v("div",{class:"peer-title"},v("strong",null,c)),v("div",{class:"peer-submeta"},o.statusLabel),v("div",{class:"peer-meta"},o.advancedDetail),v("form",{class:"coordinator-admin-form",onSubmit:f=>{f.preventDefault(),!m&&n(s,l,c,"rename")}},v("div",{class:"coordinator-admin-form-grid"},v("label",{class:"coordinator-admin-field"},v("span",null,"Display name"),v(we,{class:"peer-scope-input",disabled:t.readiness!=="ready"||d,onInput:f=>{O.deviceRenameDrafts.set(s,String(f.currentTarget.value||""))},type:"text",value:u}))),v("div",{class:"peer-actions"},v("button",{class:"settings-button",disabled:m,type:"submit"},d&&O.deviceActionPendingKind==="rename"?"Renaming…":"Rename"),p?v("button",{class:"settings-button danger",disabled:m,onClick:()=>n(s,l,c,"disable"),type:"button"},d&&O.deviceActionPendingKind==="disable"?"Disabling…":"Disable"):v("button",{class:"settings-button",disabled:m,onClick:()=>n(s,l,c,"enable"),type:"button"},d&&O.deviceActionPendingKind==="enable"?"Enabling…":"Enable"),v("button",{class:"settings-button danger",disabled:m,onClick:()=>n(s,l,c,"remove"),type:"button"},d&&O.deviceActionPendingKind==="remove"?"Removing…":"Remove"))))})):v("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."))}var ha="Collapsible",[Ik,GO]=st(ha),[Rk,Yc]=Ik(ha),Kf=j((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:i,disabled:o,onOpenChange:s,...c}=e,[l,d]=wt({prop:r,defaultProp:i??!1,onChange:s,caller:ha});return a(Rk,{scope:n,disabled:o,contentId:ct(),open:l,onOpenToggle:re(()=>d(u=>!u),[d]),children:a(se.div,{"data-state":Zc(l),"data-disabled":o?"":void 0,...c,ref:t})})});Kf.displayName=ha;var Vf="CollapsibleTrigger",Wf=j((e,t)=>{const{__scopeCollapsible:n,...r}=e,i=Yc(Vf,n);return a(se.button,{type:"button","aria-controls":i.contentId,"aria-expanded":i.open||!1,"data-state":Zc(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...r,ref:t,onClick:z(e.onClick,i.onOpenToggle)})});Wf.displayName=Vf;var Xc="CollapsibleContent",qf=j((e,t)=>{const{forceMount:n,...r}=e,i=Yc(Xc,e.__scopeCollapsible);return a(rt,{present:n||i.open,children:({present:o})=>a(Dk,{...r,ref:t,present:o})})});qf.displayName=Xc;var Dk=j((e,t)=>{const{__scopeCollapsible:n,present:r,children:i,...o}=e,s=Yc(Xc,n),[c,l]=I(r),d=F(null),u=_e(t,d),p=F(0),m=p.current,f=F(0),y=f.current,h=s.open||c,g=F(h),_=F(void 0);return K(()=>{const w=requestAnimationFrame(()=>g.current=!1);return()=>cancelAnimationFrame(w)},[]),We(()=>{const w=d.current;if(w){_.current=_.current||{transitionDuration:w.style.transitionDuration,animationName:w.style.animationName},w.style.transitionDuration="0s",w.style.animationName="none";const S=w.getBoundingClientRect();p.current=S.height,f.current=S.width,g.current||(w.style.transitionDuration=_.current.transitionDuration,w.style.animationName=_.current.animationName),l(r)}},[s.open,r]),a(se.div,{"data-state":Zc(s.open),"data-disabled":s.disabled?"":void 0,id:s.contentId,hidden:!h,...o,ref:u,style:{"--radix-collapsible-content-height":m?`${m}px`:void 0,"--radix-collapsible-content-width":y?`${y}px`:void 0,...e.style},children:h&&i})});function Zc(e){return e?"open":"closed"}var ga=Kf,zf=Wf,va=qf,Lk=["top","right","bottom","left"],yn=Math.min,vt=Math.max,ya=Math.round,ba=Math.floor,Ut=e=>({x:e,y:e}),$k={left:"right",right:"left",bottom:"top",top:"bottom"};function Qc(e,t,n){return vt(e,yn(t,n))}function on(e,t){return typeof e=="function"?e(t):e}function an(e){return e.split("-")[0]}function Lr(e){return e.split("-")[1]}function el(e){return e==="x"?"y":"x"}function tl(e){return e==="y"?"height":"width"}function Gt(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function nl(e){return el(Gt(e))}function Mk(e,t,n){n===void 0&&(n=!1);const r=Lr(e),i=nl(e),o=tl(i);let s=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(s=_a(s)),[s,_a(s)]}function Ok(e){const t=_a(e);return[rl(e),t,rl(t)]}function rl(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}var Jf=["left","right"],Yf=["right","left"],jk=["top","bottom"],Fk=["bottom","top"];function Bk(e,t,n){switch(e){case"top":case"bottom":return n?t?Yf:Jf:t?Jf:Yf;case"left":case"right":return t?jk:Fk;default:return[]}}function Uk(e,t,n,r){const i=Lr(e);let o=Bk(an(e),n==="start",r);return i&&(o=o.map(s=>s+"-"+i),t&&(o=o.concat(o.map(rl)))),o}function _a(e){const t=an(e);return $k[t]+e.slice(t.length)}function Gk(e){return{top:0,right:0,bottom:0,left:0,...e}}function Xf(e){return typeof e!="number"?Gk(e):{top:e,right:e,bottom:e,left:e}}function wa(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 Zf(e,t,n){let{reference:r,floating:i}=e;const o=Gt(t),s=nl(t),c=tl(s),l=an(t),d=o==="y",u=r.x+r.width/2-i.width/2,p=r.y+r.height/2-i.height/2,m=r[c]/2-i[c]/2;let f;switch(l){case"top":f={x:u,y:r.y-i.height};break;case"bottom":f={x:u,y:r.y+r.height};break;case"right":f={x:r.x+r.width,y:p};break;case"left":f={x:r.x-i.width,y:p};break;default:f={x:r.x,y:r.y}}switch(Lr(t)){case"start":f[s]-=m*(n&&d?-1:1);break;case"end":f[s]+=m*(n&&d?-1:1);break}return f}async function Hk(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:m=!1,padding:f=0}=on(t,e),y=Xf(f),h=c[m?p==="floating"?"reference":"floating":p],g=wa(await o.getClippingRect({element:(n=await(o.isElement==null?void 0:o.isElement(h)))==null||n?h:h.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(c.floating)),boundary:d,rootBoundary:u,strategy:l})),_=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)),S=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},T=wa(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:_,offsetParent:w,strategy:l}):_);return{top:(g.top-T.top+y.top)/S.y,bottom:(T.bottom-g.bottom+y.bottom)/S.y,left:(g.left-T.left+y.left)/S.x,right:(T.right-g.right+y.right)/S.x}}var Kk=50,Vk=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:s}=n,c=s.detectOverflow?s:{...s,detectOverflow:Hk},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}=Zf(d,r,l),m=r,f=0;const y={};for(let h=0;h<o.length;h++){const g=o[h];if(!g)continue;const{name:_,fn:w}=g,{x:S,y:T,data:k,reset:P}=await w({x:u,y:p,initialPlacement:r,placement:m,strategy:i,middlewareData:y,rects:d,platform:c,elements:{reference:e,floating:t}});u=S??u,p=T??p,y[_]={...y[_],...k},P&&f<Kk&&(f++,typeof P=="object"&&(P.placement&&(m=P.placement),P.rects&&(d=P.rects===!0?await s.getElementRects({reference:e,floating:t,strategy:i}):P.rects),{x:u,y:p}=Zf(d,m,l)),h=-1)}return{x:u,y:p,placement:m,strategy:i,middlewareData:y}},Wk=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}=on(e,t)||{};if(d==null)return{};const p=Xf(u),m={x:n,y:r},f=nl(i),y=tl(f),h=await s.getDimensions(d),g=f==="y",_=g?"top":"left",w=g?"bottom":"right",S=g?"clientHeight":"clientWidth",T=o.reference[y]+o.reference[f]-m[f]-o.floating[y],k=m[f]-o.reference[f],P=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let E=P?P[S]:0;(!E||!await(s.isElement==null?void 0:s.isElement(P)))&&(E=c.floating[S]||o.floating[y]);const M=T/2-k/2,U=E/2-h[y]/2-1,N=yn(p[_],U),G=yn(p[w],U),A=N,$=E-h[y]-G,L=E/2-h[y]/2+M,J=Qc(A,L,$),H=!l.arrow&&Lr(i)!=null&&L!==J&&o.reference[y]/2-(L<A?N:G)-h[y]/2<0,x=H?L<A?L-A:L-$:0;return{[f]:m[f]+x,data:{[f]:J,centerOffset:L-J-x,...H&&{alignmentOffset:x}},reset:H}}}),qk=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:m,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:y="none",flipAlignment:h=!0,...g}=on(e,t);if((n=o.arrow)!=null&&n.alignmentOffset)return{};const _=an(i),w=Gt(c),S=an(c)===c,T=await(l.isRTL==null?void 0:l.isRTL(d.floating)),k=m||(S||!h?[_a(c)]:Ok(c)),P=y!=="none";!m&&P&&k.push(...Uk(c,h,y,T));const E=[c,...k],M=await l.detectOverflow(t,g),U=[];let N=((r=o.flip)==null?void 0:r.overflows)||[];if(u&&U.push(M[_]),p){const L=Mk(i,s,T);U.push(M[L[0]],M[L[1]])}if(N=[...N,{placement:i,overflows:U}],!U.every(L=>L<=0)){var G,A;const L=(((G=o.flip)==null?void 0:G.index)||0)+1,J=E[L];if(J&&(!(p==="alignment"&&w!==Gt(J))||N.every(x=>Gt(x.placement)===w?x.overflows[0]>0:!0)))return{data:{index:L,overflows:N},reset:{placement:J}};let H=(A=N.filter(x=>x.overflows[0]<=0).sort((x,R)=>x.overflows[1]-R.overflows[1])[0])==null?void 0:A.placement;if(!H)switch(f){case"bestFit":{var $;const x=($=N.filter(R=>{if(P){const B=Gt(R.placement);return B===w||B==="y"}return!0}).map(R=>[R.placement,R.overflows.filter(B=>B>0).reduce((B,V)=>B+V,0)]).sort((R,B)=>R[1]-B[1])[0])==null?void 0:$[0];x&&(H=x);break}case"initialPlacement":H=c;break}if(i!==H)return{reset:{placement:H}}}return{}}}};function Qf(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function eh(e){return Lk.some(t=>e[t]>=0)}var zk=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...o}=on(e,t);switch(i){case"referenceHidden":{const s=Qf(await r.detectOverflow(t,{...o,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:eh(s)}}}case"escaped":{const s=Qf(await r.detectOverflow(t,{...o,altBoundary:!0}),n.floating);return{data:{escapedOffsets:s,escaped:eh(s)}}}default:return{}}}}},th=new Set(["left","top"]);async function Jk(e,t){const{placement:n,platform:r,elements:i}=e,o=await(r.isRTL==null?void 0:r.isRTL(i.floating)),s=an(n),c=Lr(n),l=Gt(n)==="y",d=th.has(s)?-1:1,u=o&&l?-1:1,p=on(t,e);let{mainAxis:m,crossAxis:f,alignmentAxis:y}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return c&&typeof y=="number"&&(f=c==="end"?y*-1:y),l?{x:f*u,y:m*d}:{x:m*d,y:f*u}}var Yk=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 Jk(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}}}}},Xk=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:_=>{let{x:w,y:S}=_;return{x:w,y:S}}},...d}=on(e,t),u={x:n,y:r},p=await o.detectOverflow(t,d),m=Gt(an(i)),f=el(m);let y=u[f],h=u[m];if(s){const _=f==="y"?"top":"left",w=f==="y"?"bottom":"right",S=y+p[_],T=y-p[w];y=Qc(S,y,T)}if(c){const _=m==="y"?"top":"left",w=m==="y"?"bottom":"right",S=h+p[_],T=h-p[w];h=Qc(S,h,T)}const g=l.fn({...t,[f]:y,[m]:h});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[f]:s,[m]:c}}}}}},Zk=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}=on(e,t),u={x:n,y:r},p=Gt(i),m=el(p);let f=u[m],y=u[p];const h=on(c,t),g=typeof h=="number"?{mainAxis:h,crossAxis:0}:{mainAxis:0,crossAxis:0,...h};if(l){const S=m==="y"?"height":"width",T=o.reference[m]-o.floating[S]+g.mainAxis,k=o.reference[m]+o.reference[S]-g.mainAxis;f<T?f=T:f>k&&(f=k)}if(d){var _,w;const S=m==="y"?"width":"height",T=th.has(an(i)),k=o.reference[p]-o.floating[S]+(T&&((_=s.offset)==null?void 0:_[p])||0)+(T?0:g.crossAxis),P=o.reference[p]+o.reference[S]+(T?0:((w=s.offset)==null?void 0:w[p])||0)-(T?g.crossAxis:0);y<k?y=k:y>P&&(y=P)}return{[m]:f,[p]:y}}}},Qk=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}=on(e,t),u=await s.detectOverflow(t,d),p=an(i),m=Lr(i),f=Gt(i)==="y",{width:y,height:h}=o.floating;let g,_;p==="top"||p==="bottom"?(g=p,_=m===(await(s.isRTL==null?void 0:s.isRTL(c.floating))?"start":"end")?"left":"right"):(_=p,g=m==="end"?"top":"bottom");const w=h-u.top-u.bottom,S=y-u.left-u.right,T=yn(h-u[g],w),k=yn(y-u[_],S),P=!t.middlewareData.shift;let E=T,M=k;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(M=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=w),P&&!m){const N=vt(u.left,0),G=vt(u.right,0),A=vt(u.top,0),$=vt(u.bottom,0);f?M=y-2*(N!==0||G!==0?N+G:vt(u.left,u.right)):E=h-2*(A!==0||$!==0?A+$:vt(u.top,u.bottom))}await l({...t,availableWidth:M,availableHeight:E});const U=await s.getDimensions(c.floating);return y!==U.width||h!==U.height?{reset:{rects:!0}}:{}}}};function Sa(){return typeof window<"u"}function $r(e){return nh(e)?(e.nodeName||"").toLowerCase():"#document"}function yt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ht(e){var t;return(t=(nh(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function nh(e){return Sa()?e instanceof Node||e instanceof yt(e).Node:!1}function Pt(e){return Sa()?e instanceof Element||e instanceof yt(e).Element:!1}function sn(e){return Sa()?e instanceof HTMLElement||e instanceof yt(e).HTMLElement:!1}function rh(e){return!Sa()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof yt(e).ShadowRoot}function Di(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=At(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function eN(e){return/^(table|td|th)$/.test($r(e))}function Ca(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}var tN=/transform|translate|scale|rotate|perspective|filter/,nN=/paint|layout|strict|content/,Yn=e=>!!e&&e!=="none",il;function ol(e){const t=Pt(e)?At(e):e;return Yn(t.transform)||Yn(t.translate)||Yn(t.scale)||Yn(t.rotate)||Yn(t.perspective)||!al()&&(Yn(t.backdropFilter)||Yn(t.filter))||tN.test(t.willChange||"")||nN.test(t.contain||"")}function rN(e){let t=bn(e);for(;sn(t)&&!Mr(t);){if(ol(t))return t;if(Ca(t))return null;t=bn(t)}return null}function al(){return il==null&&(il=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),il}function Mr(e){return/^(html|body|#document)$/.test($r(e))}function At(e){return yt(e).getComputedStyle(e)}function Ta(e){return Pt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function bn(e){if($r(e)==="html")return e;const t=e.assignedSlot||e.parentNode||rh(e)&&e.host||Ht(e);return rh(t)?t.host:t}function ih(e){const t=bn(e);return Mr(t)?e.ownerDocument?e.ownerDocument.body:e.body:sn(t)&&Di(t)?t:ih(t)}function Li(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=ih(e),o=i===((r=e.ownerDocument)==null?void 0:r.body),s=yt(i);if(o){const c=sl(s);return t.concat(s,s.visualViewport||[],Di(i)?i:[],c&&n?Li(c):[])}else return t.concat(i,Li(i,[],n))}function sl(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function oh(e){const t=At(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=sn(e),o=i?e.offsetWidth:n,s=i?e.offsetHeight:r,c=ya(n)!==o||ya(r)!==s;return c&&(n=o,r=s),{width:n,height:r,$:c}}function cl(e){return Pt(e)?e:e.contextElement}function Or(e){const t=cl(e);if(!sn(t))return Ut(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=oh(t);let s=(o?ya(n.width):n.width)/r,c=(o?ya(n.height):n.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!c||!Number.isFinite(c))&&(c=1),{x:s,y:c}}var iN=Ut(0);function ah(e){const t=yt(e);return!al()||!t.visualViewport?iN:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function oN(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==yt(e)?!1:t}function Xn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),o=cl(e);let s=Ut(1);t&&(r?Pt(r)&&(s=Or(r)):s=Or(e));const c=oN(o,n,r)?ah(o):Ut(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 m=yt(o),f=r&&Pt(r)?yt(r):r;let y=m,h=sl(y);for(;h&&r&&f!==y;){const g=Or(h),_=h.getBoundingClientRect(),w=At(h),S=_.left+(h.clientLeft+parseFloat(w.paddingLeft))*g.x,T=_.top+(h.clientTop+parseFloat(w.paddingTop))*g.y;l*=g.x,d*=g.y,u*=g.x,p*=g.y,l+=S,d+=T,y=yt(h),h=sl(y)}}return wa({width:u,height:p,x:l,y:d})}function ka(e,t){const n=Ta(e).scrollLeft;return t?t.left+n:Xn(Ht(e)).left+n}function sh(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-ka(e,n),y:n.top+t.scrollTop}}function aN(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o=i==="fixed",s=Ht(r),c=t?Ca(t.floating):!1;if(r===s||c&&o)return n;let l={scrollLeft:0,scrollTop:0},d=Ut(1);const u=Ut(0),p=sn(r);if((p||!p&&!o)&&(($r(r)!=="body"||Di(s))&&(l=Ta(r)),p)){const f=Xn(r);d=Or(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}const m=s&&!p&&!o?sh(s,l):Ut(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-l.scrollLeft*d.x+u.x+m.x,y:n.y*d.y-l.scrollTop*d.y+u.y+m.y}}function sN(e){return Array.from(e.getClientRects())}function cN(e){const t=Ht(e),n=Ta(e),r=e.ownerDocument.body,i=vt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),o=vt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+ka(e);const c=-n.scrollTop;return At(r).direction==="rtl"&&(s+=vt(t.clientWidth,r.clientWidth)-i),{width:i,height:o,x:s,y:c}}var ch=25;function lN(e,t){const n=yt(e),r=Ht(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=al();(!u||u&&t==="fixed")&&(c=i.offsetLeft,l=i.offsetTop)}const d=ka(r);if(d<=0){const u=r.ownerDocument,p=u.body,m=getComputedStyle(p),f=u.compatMode==="CSS1Compat"&&parseFloat(m.marginLeft)+parseFloat(m.marginRight)||0,y=Math.abs(r.clientWidth-p.clientWidth-f);y<=ch&&(o-=y)}else d<=ch&&(o+=d);return{width:o,height:s,x:c,y:l}}function dN(e,t){const n=Xn(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=sn(e)?Or(e):Ut(1);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}function lh(e,t,n){let r;if(t==="viewport")r=lN(e,n);else if(t==="document")r=cN(Ht(e));else if(Pt(t))r=dN(t,n);else{const i=ah(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return wa(r)}function dh(e,t){const n=bn(e);return n===t||!Pt(n)||Mr(n)?!1:At(n).position==="fixed"||dh(n,t)}function uN(e,t){const n=t.get(e);if(n)return n;let r=Li(e,[],!1).filter(c=>Pt(c)&&$r(c)!=="body"),i=null;const o=At(e).position==="fixed";let s=o?bn(e):e;for(;Pt(s)&&!Mr(s);){const c=At(s),l=ol(s);!l&&c.position==="fixed"&&(i=null),(o?!l&&!i:!l&&c.position==="static"&&i&&(i.position==="absolute"||i.position==="fixed")||Di(s)&&!l&&dh(e,s))?r=r.filter(d=>d!==s):i=c,s=bn(s)}return t.set(e,r),r}function pN(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[...n==="clippingAncestors"?Ca(t)?[]:uN(t,this._c):[].concat(n),r],s=lh(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 m=lh(t,o[p],i);c=vt(m.top,c),l=yn(m.right,l),d=yn(m.bottom,d),u=vt(m.left,u)}return{width:l-u,height:d-c,x:u,y:c}}function mN(e){const{width:t,height:n}=oh(e);return{width:t,height:n}}function fN(e,t,n){const r=sn(t),i=Ht(t),o=n==="fixed",s=Xn(e,!0,o,t);let c={scrollLeft:0,scrollTop:0};const l=Ut(0);function d(){l.x=ka(i)}if(r||!r&&!o)if(($r(t)!=="body"||Di(i))&&(c=Ta(t)),r){const p=Xn(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?sh(i,c):Ut(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 ll(e){return At(e).position==="static"}function uh(e,t){if(!sn(e)||At(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Ht(e)===n&&(n=n.ownerDocument.body),n}function ph(e,t){const n=yt(e);if(Ca(e))return n;if(!sn(e)){let i=bn(e);for(;i&&!Mr(i);){if(Pt(i)&&!ll(i))return i;i=bn(i)}return n}let r=uh(e,t);for(;r&&eN(r)&&ll(r);)r=uh(r,t);return r&&Mr(r)&&ll(r)&&!ol(r)?n:r||rN(e)||n}var hN=async function(e){const t=this.getOffsetParent||ph,n=this.getDimensions,r=await n(e.floating);return{reference:fN(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function gN(e){return At(e).direction==="rtl"}var vN={convertOffsetParentRelativeRectToViewportRelativeRect:aN,getDocumentElement:Ht,getClippingRect:pN,getOffsetParent:ph,getElementRects:hN,getClientRects:sN,getDimensions:mN,getScale:Or,isElement:Pt,isRTL:gN};function mh(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function yN(e,t){let n=null,r;const i=Ht(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:m,height:f}=d;if(c||t(),!m||!f)return;const y=ba(p),h=ba(i.clientWidth-(u+m)),g=ba(i.clientHeight-(p+f)),_=ba(u),w={rootMargin:-y+"px "+-h+"px "+-g+"px "+-_+"px",threshold:vt(0,yn(1,l))||1};let S=!0;function T(k){const P=k[0].intersectionRatio;if(P!==l){if(!S)return s();P?s(!1,P):r=setTimeout(()=>{s(!1,1e-7)},1e3)}P===1&&!mh(d,e.getBoundingClientRect())&&s(),S=!1}try{n=new IntersectionObserver(T,{...w,root:i.ownerDocument})}catch{n=new IntersectionObserver(T,w)}n.observe(e)}return s(!0),o}function bN(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=cl(e),u=i||o?[...d?Li(d):[],...t?Li(t):[]]:[];u.forEach(_=>{i&&_.addEventListener("scroll",n,{passive:!0}),o&&_.addEventListener("resize",n)});const p=d&&c?yN(d,n):null;let m=-1,f=null;s&&(f=new ResizeObserver(_=>{let[w]=_;w&&w.target===d&&f&&t&&(f.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var S;(S=f)==null||S.observe(t)})),n()}),d&&!l&&f.observe(d),t&&f.observe(t));let y,h=l?Xn(e):null;l&&g();function g(){const _=Xn(e);h&&!mh(h,_)&&n(),h=_,y=requestAnimationFrame(g)}return n(),()=>{var _;u.forEach(w=>{i&&w.removeEventListener("scroll",n),o&&w.removeEventListener("resize",n)}),p?.(),(_=f)==null||_.disconnect(),f=null,l&&cancelAnimationFrame(y)}}var _N=Yk,wN=Xk,SN=qk,CN=Qk,TN=zk,fh=Wk,kN=Zk,NN=(e,t,n)=>{const r=new Map,i={platform:vN,...n},o={...i.platform,_c:r};return Vk(e,t,{...i,platform:o})},Na=typeof document<"u"?gt:function(){};function xa(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(!xa(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)&&!xa(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function hh(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function gh(e,t){const n=hh(e);return Math.round(t*n)/n}function dl(e){const t=F(e);return Na(()=>{t.current=e}),t}function xN(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]=I({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,f]=I(r);xa(m,r)||f(r);const[y,h]=I(null),[g,_]=I(null),w=re(R=>{R!==P.current&&(P.current=R,h(R))},[]),S=re(R=>{R!==E.current&&(E.current=R,_(R))},[]),T=o||y,k=s||g,P=F(null),E=F(null),M=F(u),U=l!=null,N=dl(l),G=dl(i),A=dl(d),$=re(()=>{if(!P.current||!E.current)return;const R={placement:t,strategy:n,middleware:m};G.current&&(R.platform=G.current),NN(P.current,E.current,R).then(B=>{const V={...B,isPositioned:A.current!==!1};L.current&&!xa(M.current,V)&&(M.current=V,Oo(()=>{p(V)}))})},[m,t,n,G,A]);Na(()=>{d===!1&&M.current.isPositioned&&(M.current.isPositioned=!1,p(R=>({...R,isPositioned:!1})))},[d]);const L=F(!1);Na(()=>(L.current=!0,()=>{L.current=!1}),[]),Na(()=>{if(T&&(P.current=T),k&&(E.current=k),T&&k){if(N.current)return N.current(T,k,$);$()}},[T,k,$,N,U]);const J=Pe(()=>({reference:P,floating:E,setReference:w,setFloating:S}),[w,S]),H=Pe(()=>({reference:T,floating:k}),[T,k]),x=Pe(()=>{const R={position:n,left:0,top:0};if(!H.floating)return R;const B=gh(H.floating,u.x),V=gh(H.floating,u.y);return c?{...R,transform:"translate("+B+"px, "+V+"px)",...hh(H.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:B,top:V}},[n,c,H.floating,u.x,u.y]);return Pe(()=>({...u,update:$,refs:J,elements:H,floatingStyles:x}),[u,$,J,H,x])}var PN=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?fh({element:r.current,padding:i}).fn(n):{}:r?fh({element:r,padding:i}).fn(n):{}}}},AN=(e,t)=>{const n=_N(e);return{name:n.name,fn:n.fn,options:[e,t]}},EN=(e,t)=>{const n=wN(e);return{name:n.name,fn:n.fn,options:[e,t]}},IN=(e,t)=>({fn:kN(e).fn,options:[e,t]}),RN=(e,t)=>{const n=SN(e);return{name:n.name,fn:n.fn,options:[e,t]}},DN=(e,t)=>{const n=CN(e);return{name:n.name,fn:n.fn,options:[e,t]}},LN=(e,t)=>{const n=TN(e);return{name:n.name,fn:n.fn,options:[e,t]}},$N=(e,t)=>{const n=PN(e);return{name:n.name,fn:n.fn,options:[e,t]}},MN="Arrow",vh=j((e,t)=>{const{children:n,width:r=10,height:i=5,...o}=e;return a(se.svg,{...o,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:a("polygon",{points:"0,0 30,0 15,10"})})});vh.displayName=MN;var ON=vh;function ul(e){const[t,n]=I(void 0);return We(()=>{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}var pl="Popper",[yh,_n]=st(pl),[jN,bh]=yh(pl),_h=e=>{const{__scopePopper:t,children:n}=e,[r,i]=I(null);return a(jN,{scope:t,anchor:r,onAnchorChange:i,children:n})};_h.displayName=pl;var wh="PopperAnchor",Sh=j((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,o=bh(wh,n),s=F(null),c=_e(t,s),l=F(null);return K(()=>{const d=l.current;l.current=r?.current||s.current,d!==l.current&&o.onAnchorChange(l.current)}),r?null:a(se.div,{...i,ref:c})});Sh.displayName=wh;var ml="PopperContent",[FN,BN]=yh(ml),Ch=j((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:o="center",alignOffset:s=0,arrowPadding:c=0,avoidCollisions:l=!0,collisionBoundary:d=[],collisionPadding:u=0,sticky:p="partial",hideWhenDetached:m=!1,updatePositionStrategy:f="optimized",onPlaced:y,...h}=e,g=bh(ml,n),[_,w]=I(null),S=_e(t,Z=>w(Z)),[T,k]=I(null),P=ul(T),E=P?.width??0,M=P?.height??0,U=r+(o!=="center"?"-"+o:""),N=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},G=Array.isArray(d)?d:[d],A=G.length>0,$={padding:N,boundary:G.filter(GN),altBoundary:A},{refs:L,floatingStyles:J,placement:H,isPositioned:x,middlewareData:R}=xN({strategy:"fixed",placement:U,whileElementsMounted:(...Z)=>bN(...Z,{animationFrame:f==="always"}),elements:{reference:g.anchor},middleware:[AN({mainAxis:i+M,alignmentAxis:s}),l&&EN({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?IN():void 0,...$}),l&&RN({...$}),DN({...$,apply:({elements:Z,rects:Ce,availableWidth:le,availableHeight:ee})=>{const{width:xe,height:pe}=Ce.reference,W=Z.floating.style;W.setProperty("--radix-popper-available-width",`${le}px`),W.setProperty("--radix-popper-available-height",`${ee}px`),W.setProperty("--radix-popper-anchor-width",`${xe}px`),W.setProperty("--radix-popper-anchor-height",`${pe}px`)}}),T&&$N({element:T,padding:c}),HN({arrowWidth:E,arrowHeight:M}),m&&LN({strategy:"referenceHidden",...$})]}),[B,V]=Nh(H),he=lt(y);We(()=>{x&&he?.()},[x,he]);const ue=R.arrow?.x,ce=R.arrow?.y,be=R.arrow?.centerOffset!==0,[Y,ge]=I();return We(()=>{_&&ge(window.getComputedStyle(_).zIndex)},[_]),a("div",{ref:L.setFloating,"data-radix-popper-content-wrapper":"",style:{...J,transform:x?J.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Y,"--radix-popper-transform-origin":[R.transformOrigin?.x,R.transformOrigin?.y].join(" "),...R.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:a(FN,{scope:n,placedSide:B,onArrowChange:k,arrowX:ue,arrowY:ce,shouldHideArrow:be,children:a(se.div,{"data-side":B,"data-align":V,...h,ref:S,style:{...h.style,animation:x?void 0:"none"}})})})});Ch.displayName=ml;var Th="PopperArrow",UN={top:"bottom",right:"left",bottom:"top",left:"right"},kh=j(function(t,n){const{__scopePopper:r,...i}=t,o=BN(Th,r),s=UN[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(ON,{...i,ref:n,style:{...i.style,display:"block"}})})});kh.displayName=Th;function GN(e){return e!==null}var HN=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]=Nh(n),u={start:"0%",center:"50%",end:"100%"}[d],p=(i.arrow?.x??0)+s/2,m=(i.arrow?.y??0)+c/2;let f="",y="";return l==="bottom"?(f=o?u:`${p}px`,y=`${-c}px`):l==="top"?(f=o?u:`${p}px`,y=`${r.floating.height+c}px`):l==="right"?(f=`${-c}px`,y=o?u:`${m}px`):l==="left"&&(f=`${r.floating.width+c}px`,y=o?u:`${m}px`),{data:{x:f,y}}}});function Nh(e){const[t,n="center"]=e.split("-");return[t,n]}var $i=_h,Mi=Sh,Pa=Ch,Aa=kh,Ea="Popover",[xh,HO]=st(Ea,[_n]),Oi=_n(),[KN,wn]=xh(Ea),Ph=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:o,modal:s=!1}=e,c=Oi(t),l=F(null),[d,u]=I(!1),[p,m]=wt({prop:r,defaultProp:i??!1,onChange:o,caller:Ea});return a($i,{...c,children:a(KN,{scope:t,contentId:ct(),triggerRef:l,open:p,onOpenChange:m,onOpenToggle:re(()=>m(f=>!f),[m]),hasCustomAnchor:d,onCustomAnchorAdd:re(()=>u(!0),[]),onCustomAnchorRemove:re(()=>u(!1),[]),modal:s,children:n})})};Ph.displayName=Ea;var Ah="PopoverAnchor",Eh=j((e,t)=>{const{__scopePopover:n,...r}=e,i=wn(Ah,n),o=Oi(n),{onCustomAnchorAdd:s,onCustomAnchorRemove:c}=i;return K(()=>(s(),()=>c()),[s,c]),a(Mi,{...o,...r,ref:t})});Eh.displayName=Ah;var Ih="PopoverTrigger",Rh=j((e,t)=>{const{__scopePopover:n,...r}=e,i=wn(Ih,n),o=Oi(n),s=_e(t,i.triggerRef),c=a(se.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":Oh(i.open),...r,ref:s,onClick:z(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?c:a(Mi,{asChild:!0,...o,children:c})});Rh.displayName=Ih;var fl="PopoverPortal",[VN,WN]=xh(fl,{forceMount:void 0}),Dh=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,o=wn(fl,t);return a(VN,{scope:t,forceMount:n,children:a(rt,{present:n||o.open,children:a(Hn,{asChild:!0,container:i,children:r})})})};Dh.displayName=fl;var jr="PopoverContent",Lh=j((e,t)=>{const n=WN(jr,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,o=wn(jr,e.__scopePopover);return a(rt,{present:r||o.open,children:o.modal?a(zN,{...i,ref:t}):a(JN,{...i,ref:t})})});Lh.displayName=jr;var qN=Un("PopoverContent.RemoveScroll"),zN=j((e,t)=>{const n=wn(jr,e.__scopePopover),r=F(null),i=_e(t,r),o=F(!1);return K(()=>{const s=r.current;if(s)return zo(s)},[]),a(vi,{as:qN,allowPinchZoom:!0,children:a($h,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:z(e.onCloseAutoFocus,s=>{s.preventDefault(),o.current||n.triggerRef.current?.focus()}),onPointerDownOutside:z(e.onPointerDownOutside,s=>{const c=s.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0;o.current=c.button===2||l},{checkForDefaultPrevented:!1}),onFocusOutside:z(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})})}),JN=j((e,t)=>{const n=wn(jr,e.__scopePopover),r=F(!1),i=F(!1);return a($h,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(r.current||n.triggerRef.current?.focus(),o.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const s=o.target;n.triggerRef.current?.contains(s)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),$h=j((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:s,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:d,onInteractOutside:u,...p}=e,m=wn(jr,n),f=Oi(n);return Bo(),a(hi,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:o,children:a(Gn,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:d,onDismiss:()=>m.onOpenChange(!1),children:a(Pa,{"data-state":Oh(m.open),role:"dialog",id:m.contentId,...f,...p,ref:t,style:{...p.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)"}})})})}),Mh="PopoverClose",YN=j((e,t)=>{const{__scopePopover:n,...r}=e,i=wn(Mh,n);return a(se.button,{type:"button",...r,ref:t,onClick:z(e.onClick,()=>i.onOpenChange(!1))})});YN.displayName=Mh;var XN="PopoverArrow",ZN=j((e,t)=>{const{__scopePopover:n,...r}=e,i=Oi(n);return a(Aa,{...i,...r,ref:t})});ZN.displayName=XN;function Oh(e){return e?"open":"closed"}var jh=Ph,QN=Eh,ex=Rh,Fh=Dh,Bh=Lh;function hl(e){return e.trim()}function Uh({values:e,onValuesChange:t,availableProjects:n,placeholder:r,emptyLabel:i,disabled:o,"aria-labelledby":s}){const[c,l]=I(!1),[d,u]=I(""),[p,m]=I(0),f=F(null),y=Pe(()=>{const N=new Set,G=[];for(const A of[...n,...e]){const $=hl(A);!$||N.has($)||(N.add($),G.push($))}return G.sort((A,$)=>A.localeCompare($))},[n,e]),h=hl(d),g=h.toLowerCase(),_=Pe(()=>g?y.filter(N=>N.toLowerCase().includes(g)):y,[y,g]),w=h?y.some(N=>N.toLowerCase()===g):!1,S=!!h&&!w,T=_.length+(S?1:0);K(()=>{p>=T&&m(Math.max(0,T-1))},[T,p]),K(()=>{if(!c)return;const N=requestAnimationFrame(()=>f.current?.focus());return()=>cancelAnimationFrame(N)},[c]);const k=N=>{e.includes(N)?t(e.filter(G=>G!==N)):t(Array.from(new Set([...e,N])))},P=N=>{const G=hl(N);G&&(t(Array.from(new Set([...e,G]))),u(""),m(0))},E=N=>{if(N<_.length){const G=_[N];G&&k(G);return}S&&P(h)},M=N=>{if(N.key==="ArrowDown"){N.preventDefault(),m(G=>Math.min(T-1,G+1));return}if(N.key==="ArrowUp"){N.preventDefault(),m(G=>Math.max(0,G-1));return}if(N.key==="Enter"){N.preventDefault(),E(p);return}},U=N=>{t(e.filter(G=>G!==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:()=>U(N),type:"button",children:"×"})]},N))}),a(jh,{onOpenChange:N=>{l(N),N||(u(""),m(0))},open:c,children:[a(ex,{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(Fh,{children:a(Bh,{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),m(0)},onKeyDown:M,placeholder:"Search or create…",ref:f,type:"text",value:d}),a("div",{class:"project-scope-picker-results",role:"listbox",children:[_.length===0&&!S?a("div",{class:"project-scope-picker-empty-row",children:"No projects yet. Type a name to create one."}):null,_.map((N,G)=>{const A=e.includes(N);return a("button",{"aria-selected":A,class:G===p?"project-scope-picker-row project-scope-picker-row--active":"project-scope-picker-row",onClick:()=>{m(G),k(N)},onMouseEnter:()=>m(G),role:"option",type:"button",children:[a("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:A?"✓":""}),a("span",{class:"project-scope-picker-row-label",children:N})]},N)}),S?a("button",{"aria-selected":!1,class:p===_.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:()=>P(h),onMouseEnter:()=>m(_.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 "${h}"`})]}):null]})]})})]})]})}function gl(e){const t=F({value:e,previous:e});return Pe(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Ia="Switch",[tx,KO]=st(Ia),[nx,rx]=tx(Ia),Gh=j((e,t)=>{const{__scopeSwitch:n,name:r,checked:i,defaultChecked:o,required:s,disabled:c,value:l="on",onCheckedChange:d,form:u,...p}=e,[m,f]=I(null),y=_e(t,S=>f(S)),h=F(!1),g=m?u||!!m.closest("form"):!0,[_,w]=wt({prop:i,defaultProp:o??!1,onChange:d,caller:Ia});return a(nx,{scope:n,checked:_,disabled:c,children:[a(se.button,{type:"button",role:"switch","aria-checked":_,"aria-required":s,"data-state":Wh(_),"data-disabled":c?"":void 0,disabled:c,value:l,...p,ref:y,onClick:z(e.onClick,S=>{w(T=>!T),g&&(h.current=S.isPropagationStopped(),h.current||S.stopPropagation())})}),g&&a(Vh,{control:m,bubbles:!h.current,name:r,value:l,checked:_,required:s,disabled:c,form:u,style:{transform:"translateX(-100%)"}})]})});Gh.displayName=Ia;var Hh="SwitchThumb",Kh=j((e,t)=>{const{__scopeSwitch:n,...r}=e,i=rx(Hh,n);return a(se.span,{"data-state":Wh(i.checked),"data-disabled":i.disabled?"":void 0,...r,ref:t})});Kh.displayName=Hh;var ix="SwitchBubbleInput",Vh=j(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...i},o)=>{const s=F(null),c=_e(s,o),l=gl(n),d=ul(t);return K(()=>{const u=s.current;if(!u)return;const p=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(p,"checked").set;if(l!==n&&m){const f=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(f)}},[l,n,r]),a("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...i,tabIndex:-1,ref:c,style:{...i.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Vh.displayName=ix;function Wh(e){return e?"checked":"unchecked"}var ox=Gh,ax=Kh;function Fr({"aria-labelledby":e,checked:t,className:n,disabled:r=!1,id:i,name:o,onCheckedChange:s,thumbClassName:c}){return a(ox,{"aria-labelledby":e,checked:t,className:n,disabled:r,id:i,name:o,onCheckedChange:s,children:a(ax,{className:c})})}function ne(e,t="success"){UT(e,t)}function qh(e){return`${Ak}:${String(e||"").trim()}`}function sx(e){try{return localStorage.getItem(qh(e))||""}catch{return""}}function cx(e,t){try{localStorage.setItem(qh(e),t)}catch{}}function Zn(){return String(b.coordinatorAdminTargetGroup||"").trim()}function vl(e){b.coordinatorAdminTargetGroup=e,cx(b.lastCoordinatorAdminStatus?.coordinator_url||null,e)}function Br(){return(Array.isArray(b.lastCoordinatorAdminGroups)?b.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 lx(){const e=new Map;for(const t of Br())e.set(t.group_id,t.display_name||t.group_id);O.groupRenameDrafts.clear();for(const[t,n]of e.entries())O.groupRenameDrafts.set(t,n)}function dx(){const e=Zn();return Br().find(t=>t.group_id===e)||null}function zh(){const e=b.lastCoordinatorAdminStatus,t=Br(),n=String(e?.active_group||"").trim(),r=sx(e?.coordinator_url||null),i=Zn(),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 vl(c),c}function ux(){const e=new Map,t=new Map,n=Array.isArray(b.lastCoordinatorAdminDevices)?b.lastCoordinatorAdminDevices:[];for(const r of n){const i=String(r.device_id||"").trim();if(!i)continue;const o=String(r.display_name||""),s=O.deviceRenameDrafts.get(i),c=O.deviceRenameServerNames.get(i),l=s!==void 0&&(c===void 0||s!==c);e.set(i,l?s:o),t.set(i,o)}O.deviceRenameDrafts.clear();for(const[r,i]of e.entries())O.deviceRenameDrafts.set(r,i);O.deviceRenameServerNames.clear();for(const[r,i]of t.entries())O.deviceRenameServerNames.set(r,i)}function px(e,t){return t&&t.groupId===e?t:null}function mx(e,t){return e?.loaded&&e.default_space_scope_id?"Configured":e?.loaded?"Not configured":t?.defaultSpaceLabel?t.defaultSpaceLabel:t?.defaultSpaceScopeId?"Configured":"Open Team defaults to inspect"}function fx(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 Team defaults to inspect"}function hx(e){return e?.loaded?e.scopes.filter(t=>String(t.status||"active")==="active").length:null}function gx(e){const t=hx(e);return t===null?"Open Spaces to inspect access grants":`${t} active ${t===1?"Space":"Spaces"}`}function vx(e){const t=px(e.groupId,e.setupGuide);return{autoGrant:fx(e.preferences,t),defaultSpace:mx(e.preferences,t),spaces:gx(e.scopeManagement)}}var yl=null,Ra=null,bl=null;function yx(){return yl}function _l(e){Ra=e}function Jh(e){bl=e}function bx(e){return bl===e}function _x(e){return e?e.kind==="confirm"?!1:e.kind==="input"?null:{action:"cancel"}:null}function wl(e){return!yl||!Ra?!0:(console.warn(`Ignored sync ${e} dialog request because another sync dialog is already open.`),!1)}function Da(e){yl=e,bl?.(e)}function Sn(e){const t=Ra;Ra=null,Da(null),t?.(e)}function wx(e){return e==="danger"?"sync-dialog-confirm danger":"sync-dialog-confirm"}var Sx=j(function({value:t,onValueChange:n,suggestions:r,onSubmit:i,maxSuggestions:o=20,onKeyDown:s,onFocus:c,onBlur:l,className:d,...u},p){const m=F(null);Do(p,()=>m.current,[]);const[f,y]=I(!1),[h,g]=I(-1),_=Pe(()=>{const k=t.trim().toLowerCase();return(k?r.filter(P=>P.toLowerCase().includes(k)):r).slice(0,o)},[t,r,o]);K(()=>{h>=_.length&&g(_.length-1)},[_.length,h]);const w=f&&_.length>0,S=k=>{n(k),y(!1),g(-1),m.current?.focus()};return a(jh,{open:w,onOpenChange:y,children:[a(QN,{asChild:!0,children:a("input",{...u,ref:m,className:d,value:t,onInput:k=>{n(k.currentTarget.value),y(!0),g(-1)},onFocus:k=>{c?.(k)},onBlur:k=>{window.setTimeout(()=>y(!1),120),l?.(k)},onKeyDown:k=>{if(k.key==="ArrowDown"){k.preventDefault(),y(!0),g(P=>_.length===0?-1:Math.min(P+1,_.length-1));return}if(k.key==="ArrowUp"){k.preventDefault(),f||y(!0),g(P=>Math.max(P-1,-1));return}if(k.key==="Escape"&&w){k.preventDefault(),y(!1),g(-1);return}if((k.key==="Tab"||k.key==="Enter")&&h>=0){const P=_[h];if(P){k.preventDefault(),S(P);return}}if(k.key==="Enter"&&i){k.preventDefault(),i();return}s?.(k)},role:"combobox","aria-autocomplete":"list","aria-expanded":w,"aria-controls":"autocompleteListbox","aria-activedescendant":h>=0?`autocomplete-option-${h}`:void 0})}),a(Fh,{children:a(Bh,{align:"start",className:"autocomplete-popover",onOpenAutoFocus:k=>k.preventDefault(),onCloseAutoFocus:k=>k.preventDefault(),sideOffset:4,style:{width:"var(--radix-popover-trigger-width)"},children:a("div",{className:"autocomplete-listbox",id:"autocompleteListbox",role:"listbox",children:_.map((k,P)=>{const E=P===h;return a("div",{"aria-selected":E,className:E?"autocomplete-option active":"autocomplete-option",id:`autocomplete-option-${P}`,onMouseDown:M=>{M.preventDefault(),S(k)},onMouseEnter:()=>g(P),role:"option",tabIndex:-1,children:k},k)})})})})]})}),Sl="Radio",[Cx,Yh]=st(Sl),[Tx,kx]=Cx(Sl),Xh=j((e,t)=>{const{__scopeRadio:n,name:r,checked:i=!1,required:o,disabled:s,value:c="on",onCheck:l,form:d,...u}=e,[p,m]=I(null),f=_e(t,g=>m(g)),y=F(!1),h=p?d||!!p.closest("form"):!0;return a(Tx,{scope:n,checked:i,disabled:s,children:[a(se.button,{type:"button",role:"radio","aria-checked":i,"data-state":tg(i),"data-disabled":s?"":void 0,disabled:s,value:c,...u,ref:f,onClick:z(e.onClick,g=>{i||l?.(),h&&(y.current=g.isPropagationStopped(),y.current||g.stopPropagation())})}),h&&a(eg,{control:p,bubbles:!y.current,name:r,value:c,checked:i,required:o,disabled:s,form:d,style:{transform:"translateX(-100%)"}})]})});Xh.displayName=Sl;var Zh="RadioIndicator",Qh=j((e,t)=>{const{__scopeRadio:n,forceMount:r,...i}=e,o=kx(Zh,n);return a(rt,{present:r||o.checked,children:a(se.span,{"data-state":tg(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:t})})});Qh.displayName=Zh;var Nx="RadioBubbleInput",eg=j(({__scopeRadio:e,control:t,checked:n,bubbles:r=!0,...i},o)=>{const s=F(null),c=_e(s,o),l=gl(n),d=ul(t);return K(()=>{const u=s.current;if(!u)return;const p=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(p,"checked").set;if(l!==n&&m){const f=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(f)}},[l,n,r]),a(se.input,{type:"radio","aria-hidden":!0,defaultChecked:n,...i,tabIndex:-1,ref:c,style:{...i.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});eg.displayName=Nx;function tg(e){return e?"checked":"unchecked"}var xx=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],La="RadioGroup",[Px,VO]=st(La,[Dr,Yh]),ng=Dr(),rg=Yh(),[Ax,Ex]=Px(La),ig=j((e,t)=>{const{__scopeRadioGroup:n,name:r,defaultValue:i,value:o,required:s=!1,disabled:c=!1,orientation:l,dir:d,loop:u=!0,onValueChange:p,...m}=e,f=ng(n),y=Ii(d),[h,g]=wt({prop:o,defaultProp:i??null,onChange:p,caller:La});return a(Ax,{scope:n,name:r,required:s,disabled:c,value:h,onValueChange:g,children:a(qc,{asChild:!0,...f,orientation:l,dir:y,loop:u,children:a(se.div,{role:"radiogroup","aria-required":s,"aria-orientation":l,"data-disabled":c?"":void 0,dir:y,...m,ref:t})})})});ig.displayName=La;var og="RadioGroupItem",ag=j((e,t)=>{const{__scopeRadioGroup:n,disabled:r,...i}=e,o=Ex(og,n),s=o.disabled||r,c=ng(n),l=rg(n),d=F(null),u=_e(t,d),p=o.value===i.value,m=F(!1);return K(()=>{const f=h=>{xx.includes(h.key)&&(m.current=!0)},y=()=>m.current=!1;return document.addEventListener("keydown",f),document.addEventListener("keyup",y),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",y)}},[]),a(zc,{asChild:!0,...c,focusable:!s,active:p,children:a(Xh,{disabled:s,required:o.required,checked:p,...l,...i,name:o.name,ref:u,onCheck:()=>o.onValueChange(i.value),onKeyDown:z(f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:z(i.onFocus,()=>{m.current&&d.current?.click()})})})});ag.displayName=og;var Ix="RadioGroupIndicator",sg=j((e,t)=>{const{__scopeRadioGroup:n,...r}=e;return a(Qh,{...rg(n),...r,ref:t})});sg.displayName=Ix;var Rx=ig,Dx=ag,Lx=sg;function $x({ariaDescribedby:e,ariaLabel:t,autoFocusValue:n,indicatorClassName:r,itemClassName:i,itemLabelClassName:o,name:s,onValueChange:c,options:l,rootClassName:d,value:u}){return a(Rx,{"aria-describedby":e,"aria-label":t,className:d,name:s,onValueChange:c,value:u,children:l.map((p,m)=>{const f=`radio-option-input-${m}`,y=`radio-option-label-${m}`;return a("label",{className:i,htmlFor:f,children:[a(Dx,{id:f,"aria-labelledby":y,autoFocus:n===p.value,disabled:p.disabled,value:p.value,children:a(Lx,{className:r})}),a("span",{className:o,id:y,children:p.label})]},p.value)})})}function cg(e,[t,n]){return Math.min(n,Math.max(t,e))}var Mx=[" ","Enter","ArrowUp","ArrowDown"],Ox=[" ","Enter"],Qn="Select",[$a,Ma,jx]=la(Qn),[Ur,WO]=st(Qn,[jx,_n]),Oa=_n(),[Fx,Cn]=Ur(Qn),[Bx,Ux]=Ur(Qn),lg=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:m,required:f,form:y}=e,h=Oa(t),[g,_]=I(null),[w,S]=I(null),[T,k]=I(!1),P=Ii(d),[E,M]=wt({prop:r,defaultProp:i??!1,onChange:o,caller:Qn}),[U,N]=wt({prop:s,defaultProp:c,onChange:l,caller:Qn}),G=F(null),A=g?y||!!g.closest("form"):!0,[$,L]=I(new Set),J=Array.from($).map(H=>H.props.value).join(";");return a($i,{...h,children:a(Fx,{required:f,scope:t,trigger:g,onTriggerChange:_,valueNode:w,onValueNodeChange:S,valueNodeHasChildren:T,onValueNodeHasChildrenChange:k,contentId:ct(),value:U,onValueChange:N,open:E,onOpenChange:M,dir:P,triggerPointerDownPosRef:G,disabled:m,children:[a($a.Provider,{scope:t,children:a(Bx,{scope:e.__scopeSelect,onNativeOptionAdd:re(H=>{L(x=>new Set(x).add(H))},[]),onNativeOptionRemove:re(H=>{L(x=>{const R=new Set(x);return R.delete(H),R})},[]),children:n})}),A?a(Ag,{"aria-hidden":!0,required:f,tabIndex:-1,name:u,autoComplete:p,value:U,onChange:H=>N(H.target.value),disabled:m,form:y,children:[U===void 0?a("option",{value:""}):null,Array.from($)]},J):null]})})};lg.displayName=Qn;var dg="SelectTrigger",ug=j((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...i}=e,o=Oa(n),s=Cn(dg,n),c=s.disabled||r,l=_e(t,s.onTriggerChange),d=Ma(n),u=F("touch"),[p,m,f]=Ig(h=>{const g=d().filter(w=>!w.disabled),_=Rg(g,h,g.find(w=>w.value===s.value));_!==void 0&&s.onValueChange(_.value)}),y=h=>{c||(s.onOpenChange(!0),f()),h&&(s.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)})};return a(Mi,{asChild:!0,...o,children:a(se.button,{type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:c,"data-disabled":c?"":void 0,"data-placeholder":Eg(s.value)?"":void 0,...i,ref:l,onClick:z(i.onClick,h=>{h.currentTarget.focus(),u.current!=="mouse"&&y(h)}),onPointerDown:z(i.onPointerDown,h=>{u.current=h.pointerType;const g=h.target;g.hasPointerCapture(h.pointerId)&&g.releasePointerCapture(h.pointerId),h.button===0&&h.ctrlKey===!1&&h.pointerType==="mouse"&&(y(h),h.preventDefault())}),onKeyDown:z(i.onKeyDown,h=>{const g=p.current!=="";!(h.ctrlKey||h.altKey||h.metaKey)&&h.key.length===1&&m(h.key),!(g&&h.key===" ")&&Mx.includes(h.key)&&(y(),h.preventDefault())})})})});ug.displayName=dg;var pg="SelectValue",mg=j((e,t)=>{const{__scopeSelect:n,className:r,style:i,children:o,placeholder:s="",...c}=e,l=Cn(pg,n),{onValueNodeHasChildrenChange:d}=l,u=o!==void 0,p=_e(t,l.onValueNodeChange);return We(()=>{d(u)},[d,u]),a(se.span,{...c,ref:p,style:{pointerEvents:"none"},children:Eg(l.value)?a(te,{children:s}):o})});mg.displayName=pg;var Gx="SelectIcon",fg=j((e,t)=>{const{__scopeSelect:n,children:r,...i}=e;return a(se.span,{"aria-hidden":!0,...i,ref:t,children:r||"▼"})});fg.displayName=Gx;var Hx="SelectPortal",hg=e=>a(Hn,{asChild:!0,...e});hg.displayName=Hx;var er="SelectContent",gg=j((e,t)=>{const n=Cn(er,e.__scopeSelect),[r,i]=I();if(We(()=>{i(new DocumentFragment)},[]),!n.open){const o=r;return o?en(a(vg,{scope:e.__scopeSelect,children:a($a.Slot,{scope:e.__scopeSelect,children:a("div",{children:e.children})})}),o):null}return a(yg,{...e,ref:t})});gg.displayName=er;var Et=10,[vg,Tn]=Ur(er),Kx="SelectContentImpl",Vx=Un("SelectContent.RemoveScroll"),yg=j((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:o,onPointerDownOutside:s,side:c,sideOffset:l,align:d,alignOffset:u,arrowPadding:p,collisionBoundary:m,collisionPadding:f,sticky:y,hideWhenDetached:h,avoidCollisions:g,..._}=e,w=Cn(er,n),[S,T]=I(null),[k,P]=I(null),E=_e(t,Z=>T(Z)),[M,U]=I(null),[N,G]=I(null),A=Ma(n),[$,L]=I(!1),J=F(!1);K(()=>{if(S)return zo(S)},[S]),Bo();const H=re(Z=>{const[Ce,...le]=A().map(pe=>pe.ref.current),[ee]=le.slice(-1),xe=document.activeElement;for(const pe of Z)if(pe===xe||(pe?.scrollIntoView({block:"nearest"}),pe===Ce&&k&&(k.scrollTop=0),pe===ee&&k&&(k.scrollTop=k.scrollHeight),pe?.focus(),document.activeElement!==xe))return},[A,k]),x=re(()=>H([M,S]),[H,M,S]);K(()=>{$&&x()},[$,x]);const{onOpenChange:R,triggerPointerDownPosRef:B}=w;K(()=>{if(S){let Z={x:0,y:0};const Ce=ee=>{Z={x:Math.abs(Math.round(ee.pageX)-(B.current?.x??0)),y:Math.abs(Math.round(ee.pageY)-(B.current?.y??0))}},le=ee=>{Z.x<=10&&Z.y<=10?ee.preventDefault():S.contains(ee.target)||R(!1),document.removeEventListener("pointermove",Ce),B.current=null};return B.current!==null&&(document.addEventListener("pointermove",Ce),document.addEventListener("pointerup",le,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Ce),document.removeEventListener("pointerup",le,{capture:!0})}}},[S,R,B]),K(()=>{const Z=()=>R(!1);return window.addEventListener("blur",Z),window.addEventListener("resize",Z),()=>{window.removeEventListener("blur",Z),window.removeEventListener("resize",Z)}},[R]);const[V,he]=Ig(Z=>{const Ce=A().filter(ee=>!ee.disabled),le=Rg(Ce,Z,Ce.find(ee=>ee.ref.current===document.activeElement));le&&setTimeout(()=>le.ref.current.focus())}),ue=re((Z,Ce,le)=>{const ee=!J.current&&!le;(w.value!==void 0&&w.value===Ce||ee)&&(U(Z),ee&&(J.current=!0))},[w.value]),ce=re(()=>S?.focus(),[S]),be=re((Z,Ce,le)=>{const ee=!J.current&&!le;(w.value!==void 0&&w.value===Ce||ee)&&G(Z)},[w.value]),Y=r==="popper"?Cl:bg,ge=Y===Cl?{side:c,sideOffset:l,align:d,alignOffset:u,arrowPadding:p,collisionBoundary:m,collisionPadding:f,sticky:y,hideWhenDetached:h,avoidCollisions:g}:{};return a(vg,{scope:n,content:S,viewport:k,onViewportChange:P,itemRefCallback:ue,selectedItem:M,onItemLeave:ce,itemTextRefCallback:be,focusSelectedItem:x,selectedItemText:N,position:r,isPositioned:$,searchRef:V,children:a(vi,{as:Vx,allowPinchZoom:!0,children:a(hi,{asChild:!0,trapped:w.open,onMountAutoFocus:Z=>{Z.preventDefault()},onUnmountAutoFocus:z(i,Z=>{w.trigger?.focus({preventScroll:!0}),Z.preventDefault()}),children:a(Gn,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:Z=>Z.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:a(Y,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:Z=>Z.preventDefault(),..._,...ge,onPlaced:()=>L(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",..._.style},onKeyDown:z(_.onKeyDown,Z=>{const Ce=Z.ctrlKey||Z.altKey||Z.metaKey;if(Z.key==="Tab"&&Z.preventDefault(),!Ce&&Z.key.length===1&&he(Z.key),["ArrowUp","ArrowDown","Home","End"].includes(Z.key)){let le=A().filter(ee=>!ee.disabled).map(ee=>ee.ref.current);if(["ArrowUp","End"].includes(Z.key)&&(le=le.slice().reverse()),["ArrowUp","ArrowDown"].includes(Z.key)){const ee=Z.target,xe=le.indexOf(ee);le=le.slice(xe+1)}setTimeout(()=>H(le)),Z.preventDefault()}})})})})})})});yg.displayName=Kx;var Wx="SelectItemAlignedPosition",bg=j((e,t)=>{const{__scopeSelect:n,onPlaced:r,...i}=e,o=Cn(er,n),s=Tn(er,n),[c,l]=I(null),[d,u]=I(null),p=_e(t,P=>u(P)),m=Ma(n),f=F(!1),y=F(!0),{viewport:h,selectedItem:g,selectedItemText:_,focusSelectedItem:w}=s,S=re(()=>{if(o.trigger&&o.valueNode&&c&&d&&h&&g&&_){const P=o.trigger.getBoundingClientRect(),E=d.getBoundingClientRect(),M=o.valueNode.getBoundingClientRect(),U=_.getBoundingClientRect();if(o.dir!=="rtl"){const le=U.left-E.left,ee=M.left-le,xe=P.left-ee,pe=P.width+xe,W=Math.max(pe,E.width),oe=window.innerWidth-Et,Ve=cg(ee,[Et,Math.max(Et,oe-W)]);c.style.minWidth=pe+"px",c.style.left=Ve+"px"}else{const le=E.right-U.right,ee=window.innerWidth-M.right-le,xe=window.innerWidth-P.right-ee,pe=P.width+xe,W=Math.max(pe,E.width),oe=window.innerWidth-Et,Ve=cg(ee,[Et,Math.max(Et,oe-W)]);c.style.minWidth=pe+"px",c.style.right=Ve+"px"}const N=m(),G=window.innerHeight-Et*2,A=h.scrollHeight,$=window.getComputedStyle(d),L=parseInt($.borderTopWidth,10),J=parseInt($.paddingTop,10),H=parseInt($.borderBottomWidth,10),x=parseInt($.paddingBottom,10),R=L+J+A+x+H,B=Math.min(g.offsetHeight*5,R),V=window.getComputedStyle(h),he=parseInt(V.paddingTop,10),ue=parseInt(V.paddingBottom,10),ce=P.top+P.height/2-Et,be=G-ce,Y=g.offsetHeight/2,ge=g.offsetTop+Y,Z=L+J+ge,Ce=R-Z;if(Z<=ce){const le=N.length>0&&g===N[N.length-1].ref.current;c.style.bottom="0px";const ee=d.clientHeight-h.offsetTop-h.offsetHeight,xe=Z+Math.max(be,Y+(le?ue:0)+ee+H);c.style.height=xe+"px"}else{const le=N.length>0&&g===N[0].ref.current;c.style.top="0px";const ee=Math.max(ce,L+h.offsetTop+(le?he:0)+Y)+Ce;c.style.height=ee+"px",h.scrollTop=Z-ce+h.offsetTop}c.style.margin=`${Et}px 0`,c.style.minHeight=B+"px",c.style.maxHeight=G+"px",r?.(),requestAnimationFrame(()=>f.current=!0)}},[m,o.trigger,o.valueNode,c,d,h,g,_,o.dir,r]);We(()=>S(),[S]);const[T,k]=I();return We(()=>{d&&k(window.getComputedStyle(d).zIndex)},[d]),a(zx,{scope:n,contentWrapper:c,shouldExpandOnScrollRef:f,onScrollButtonChange:re(P=>{P&&y.current===!0&&(S(),w?.(),y.current=!1)},[S,w]),children:a("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:T},children:a(se.div,{...i,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});bg.displayName=Wx;var qx="SelectPopperPosition",Cl=j((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:i=Et,...o}=e,s=Oa(n);return a(Pa,{...s,...o,ref:t,align:r,collisionPadding:i,style:{boxSizing:"border-box",...o.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)"}})});Cl.displayName=qx;var[zx,Tl]=Ur(er,{}),kl="SelectViewport",_g=j((e,t)=>{const{__scopeSelect:n,nonce:r,...i}=e,o=Tn(kl,n),s=Tl(kl,n),c=_e(t,o.onViewportChange),l=F(0);return a(te,{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:r}),a($a.Slot,{scope:n,children:a(se.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:c,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:z(i.onScroll,d=>{const u=d.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:m}=s;if(m?.current&&p){const f=Math.abs(l.current-u.scrollTop);if(f>0){const y=window.innerHeight-Et*2,h=parseFloat(p.style.minHeight),g=parseFloat(p.style.height),_=Math.max(h,g);if(_<y){const w=_+f,S=Math.min(y,w),T=w-S;p.style.height=S+"px",p.style.bottom==="0px"&&(u.scrollTop=T>0?T:0,p.style.justifyContent="flex-end")}}}l.current=u.scrollTop})})})]})});_g.displayName=kl;var wg="SelectGroup",[Jx,Yx]=Ur(wg),Xx=j((e,t)=>{const{__scopeSelect:n,...r}=e,i=ct();return a(Jx,{scope:n,id:i,children:a(se.div,{role:"group","aria-labelledby":i,...r,ref:t})})});Xx.displayName=wg;var Sg="SelectLabel",Zx=j((e,t)=>{const{__scopeSelect:n,...r}=e,i=Yx(Sg,n);return a(se.div,{id:i.id,...r,ref:t})});Zx.displayName=Sg;var ja="SelectItem",[Qx,Cg]=Ur(ja),Tg=j((e,t)=>{const{__scopeSelect:n,value:r,disabled:i=!1,textValue:o,...s}=e,c=Cn(ja,n),l=Tn(ja,n),d=c.value===r,[u,p]=I(o??""),[m,f]=I(!1),y=_e(t,w=>l.itemRefCallback?.(w,r,i)),h=ct(),g=F("touch"),_=()=>{i||(c.onValueChange(r),c.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return a(Qx,{scope:n,value:r,disabled:i,textId:h,isSelected:d,onItemTextChange:re(w=>{p(S=>S||(w?.textContent??"").trim())},[]),children:a($a.ItemSlot,{scope:n,value:r,disabled:i,textValue:u,children:a(se.div,{role:"option","aria-labelledby":h,"data-highlighted":m?"":void 0,"aria-selected":d&&m,"data-state":d?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...s,ref:y,onFocus:z(s.onFocus,()=>f(!0)),onBlur:z(s.onBlur,()=>f(!1)),onClick:z(s.onClick,()=>{g.current!=="mouse"&&_()}),onPointerUp:z(s.onPointerUp,()=>{g.current==="mouse"&&_()}),onPointerDown:z(s.onPointerDown,w=>{g.current=w.pointerType}),onPointerMove:z(s.onPointerMove,w=>{g.current=w.pointerType,i?l.onItemLeave?.():g.current==="mouse"&&w.currentTarget.focus({preventScroll:!0})}),onPointerLeave:z(s.onPointerLeave,w=>{w.currentTarget===document.activeElement&&l.onItemLeave?.()}),onKeyDown:z(s.onKeyDown,w=>{l.searchRef?.current!==""&&w.key===" "||(Ox.includes(w.key)&&_(),w.key===" "&&w.preventDefault())})})})})});Tg.displayName=ja;var ji="SelectItemText",kg=j((e,t)=>{const{__scopeSelect:n,className:r,style:i,...o}=e,s=Cn(ji,n),c=Tn(ji,n),l=Cg(ji,n),d=Ux(ji,n),[u,p]=I(null),m=_e(t,_=>p(_),l.onItemTextChange,_=>c.itemTextRefCallback?.(_,l.value,l.disabled)),f=u?.textContent,y=Pe(()=>a("option",{value:l.value,disabled:l.disabled,children:f},l.value),[l.disabled,l.value,f]),{onNativeOptionAdd:h,onNativeOptionRemove:g}=d;return We(()=>(h(y),()=>g(y)),[h,g,y]),a(te,{children:[a(se.span,{id:l.textId,...o,ref:m}),l.isSelected&&s.valueNode&&!s.valueNodeHasChildren?en(o.children,s.valueNode):null]})});kg.displayName=ji;var Ng="SelectItemIndicator",xg=j((e,t)=>{const{__scopeSelect:n,...r}=e;return Cg(Ng,n).isSelected?a(se.span,{"aria-hidden":!0,...r,ref:t}):null});xg.displayName=Ng;var Nl="SelectScrollUpButton",eP=j((e,t)=>{const n=Tn(Nl,e.__scopeSelect),r=Tl(Nl,e.__scopeSelect),[i,o]=I(!1),s=_e(t,r.onScrollButtonChange);return We(()=>{if(n.viewport&&n.isPositioned){let c=function(){o(l.scrollTop>0)};const l=n.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),i?a(Pg,{...e,ref:s,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop-l.offsetHeight)}}):null});eP.displayName=Nl;var xl="SelectScrollDownButton",tP=j((e,t)=>{const n=Tn(xl,e.__scopeSelect),r=Tl(xl,e.__scopeSelect),[i,o]=I(!1),s=_e(t,r.onScrollButtonChange);return We(()=>{if(n.viewport&&n.isPositioned){let c=function(){const d=l.scrollHeight-l.clientHeight;o(Math.ceil(l.scrollTop)<d)};const l=n.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),i?a(Pg,{...e,ref:s,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop+l.offsetHeight)}}):null});tP.displayName=xl;var Pg=j((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...i}=e,o=Tn("SelectScrollButton",n),s=F(null),c=Ma(n),l=re(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return K(()=>()=>l(),[l]),We(()=>{c().find(d=>d.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[c]),a(se.div,{"aria-hidden":!0,...i,ref:t,style:{flexShrink:0,...i.style},onPointerDown:z(i.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:z(i.onPointerMove,()=>{o.onItemLeave?.(),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:z(i.onPointerLeave,()=>{l()})})}),nP="SelectSeparator",rP=j((e,t)=>{const{__scopeSelect:n,...r}=e;return a(se.div,{"aria-hidden":!0,...r,ref:t})});rP.displayName=nP;var Pl="SelectArrow",iP=j((e,t)=>{const{__scopeSelect:n,...r}=e,i=Oa(n),o=Cn(Pl,n),s=Tn(Pl,n);return o.open&&s.position==="popper"?a(Aa,{...i,...r,ref:t}):null});iP.displayName=Pl;var oP="SelectBubbleInput",Ag=j(({__scopeSelect:e,value:t,...n},r)=>{const i=F(null),o=_e(r,i),s=gl(t);return K(()=>{const c=i.current;if(!c)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(s!==t&&d){const u=new Event("change",{bubbles:!0});d.call(c,t),c.dispatchEvent(u)}},[s,t]),a(se.select,{...n,style:{...ef,...n.style},ref:o,defaultValue:t})});Ag.displayName=oP;function Eg(e){return e===""||e===void 0}function Ig(e){const t=lt(e),n=F(""),r=F(0),i=re(s=>{const c=n.current+s;t(c),(function l(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>l(""),1e3))})(c)},[t]),o=re(()=>{n.current="",window.clearTimeout(r.current)},[]);return K(()=>()=>window.clearTimeout(r.current),[]),[n,i,o]}function Rg(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=aP(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}function aP(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var sP=lg,cP=ug,lP=mg,dP=fg,uP=hg,pP=gg,mP=_g,fP=Tg,hP=kg,gP=xg,Dg="__codemem-empty-select__";function vP(){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 yP(){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 Al(e){return e===""?Dg:e}function bP(e){return e===Dg?"":e}function cn({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 m=u?Al(u):void 0;return a(sP,{disabled:r,onValueChange:f=>s(bP(f)),value:m,children:[a(cP,{"aria-label":e,className:d??t,"data-value":u,id:i,type:"button",children:[a(lP,{placeholder:l}),a(dP,{className:"sync-radix-select-icon","aria-hidden":"true",children:a(vP,{})})]}),a(uP,{children:a(pP,{className:n,position:"popper",children:a(mP,{className:p,children:c.map(f=>a(fP,{className:o,disabled:f.disabled,value:Al(f.value),children:[a(hP,{children:f.label}),a(gP,{className:"sync-radix-select-indicator",children:a(yP,{})})]},Al(f.value)))})})})]})}function _P({descriptionId:e,request:t}){const[n,r]=I("choice"),[i,o]=I(t.actors.find(g=>g.isLocal)?.actorId||t.actors[0]?.actorId||""),[s,c]=I("");K(()=>{r("choice");const g=t.actors.find(w=>w.isLocal)?.actorId||t.actors[0]?.actorId||"",_=t.actors.find(w=>w.actorId!==g)?.actorId||"";o(g),c(_)},[t]);const l=t.actors.find(g=>g.actorId===i)||t.actors[0],d=t.actors.filter(g=>g.actorId!==i),u=d.find(g=>g.actorId===s)||d[0],p=t.actors.map(g=>({label:a(te,{children:[g.label,g.isLocal?" (You)":""]}),value:g.actorId})),m=d.map(g=>({label:`${g.label}${g.isLocal?" (You)":""}`,value:g.actorId})),f=!!(l?.actorId&&u?.actorId),y=()=>{!l?.actorId||!u?.actorId||Sn({action:"merge",primaryActorId:l.actorId,secondaryActorId:u.actorId})},h=g=>{const _=g.target instanceof HTMLElement?g.target:null;g.defaultPrevented||g.isComposing||g.key!=="Enter"||_?.closest(".sync-dialog-radio-list")&&f&&(g.preventDefault(),y())};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:()=>Sn({action:"different-people"}),type:"button",children:"These are different people"})}),a("li",{children:a("button",{className:"settings-button",onClick:()=>Sn({action:"cancel"}),type:"button",children:"Decide later"})})]})}):a("div",{className:"sync-dialog-stack",onKeyDown:g=>{h(g),Rr(g,{onSubmit:y,disabled:!f})},children:[a("div",{className:"small",id:e,children:"Choose which person should remain after combining these duplicates."}),a($x,{ariaDescribedby:e,ariaLabel:"Person to keep after combining duplicates",autoFocusValue:i,indicatorClassName:"sync-dialog-radio-indicator",itemClassName:"sync-dialog-radio-option",itemLabelClassName:"sync-dialog-radio-label",name:"syncDuplicatePrimaryActor",onValueChange:o,options:p,rootClassName:"sync-dialog-radio-list",value:i}),a("div",{className:"field",children:[a("label",{className:"small",htmlFor:"syncDuplicateSecondaryActor",children:"Person to combine into the selected record"}),a(cn,{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:c,options:m,placeholder:"No merge target available",triggerClassName:"sync-radix-select-trigger sync-dialog-input",value:u?.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:!f,onClick:y,type:"button",children:"Combine people"})]})]})}function wP({descriptionId:e,request:t,titleId:n}){const[r,i]=I(t.kind==="input"&&t.initialValue||""),[o,s]=I(null),c=t.kind!=="duplicate-person",l="syncDialogInputError";K(()=>{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"){Sn(!0);return}if(t.kind==="duplicate-person")return;const m=r.trim(),f=t.validate?.(m)||null;if(f){s(f);return}Sn(m)};return a("div",{className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:n,children:t.title}),a($o,{ariaLabel:`Close ${t.title}`,onClick:()=>Sn(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(Sx,{"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:m=>{i(m),o&&s(null)},placeholder:t.placeholder,suggestions:t.suggestions,value:r}):a(we,{"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:m=>{i(m.currentTarget.value),o&&s(null)},onKeyDown:m=>{m.key==="Enter"&&(m.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(_P,{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:()=>Sn(t.kind==="confirm"?!1:null),type:"button",children:d}),t.kind!=="duplicate-person"?a("button",{autoFocus:!0,className:`settings-button ${wx(t.kind==="confirm"?t.tone:void 0)}`,"data-sync-dialog-action":"confirm",onClick:p,type:"button",children:u}):null]})]})]})}function SP(){const[e,t]=I(yx());K(()=>(Jh(t),()=>{bx(t)&&Jh(null)}),[]);const n=!!e,r=Pe(()=>`sync-dialog-title-${e?.kind||"none"}`,[e?.kind]),i=Pe(()=>`sync-dialog-description-${e?.kind||"none"}`,[e?.kind]);return e?a(yi,{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||Sn(e?.kind==="confirm"?!1:null)},open:n,overlayClassName:"modal-backdrop",overlayId:"syncDialogBackdrop",children:e?a(wP,{descriptionId:i,request:e,titleId:r}):null}):null}var tr=null;function Fa(){tr?.isConnected||(tr=document.getElementById("syncDialogMount"),tr||(tr=document.createElement("div"),tr.id="syncDialogMount",document.body.appendChild(tr)),Be(a(SP,{}),tr))}function Kt(e){return Fa(),wl("confirm")?new Promise(t=>{_l(n=>t(!!n)),Da({kind:"confirm",...e})}):Promise.resolve(!1)}function El(e){return Fa(),wl("input")?new Promise(t=>{_l(n=>t(typeof n=="string"?n:null)),Da({kind:"input",...e})}):Promise.resolve(null)}function CP(e){return Fa(),wl("duplicate-person")?new Promise(t=>{_l(n=>t(n||{action:"cancel"})),Da({kind:"duplicate-person",...e})}):Promise.resolve(_x({kind:"duplicate-person",...e}))}function TP(e){return e.readiness==="ready"?null:"Space management needs the coordinator URL, target Team, and admin secret before it can list Spaces or change memberships."}function kP(e){const t=String(e||"active").trim();return t?t.replaceAll("_"," "):"active"}function Lg(e){const t=String(e.label||"").trim()||"Untitled Space",n=kP(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:`Advanced: Space ID ${i} · Membership epoch ${o}`}}function NP(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:`Advanced: membership epoch ${i}`}}function xP(e,t,n){return`Revoke ${t||n||"this device"} from ${Lg(e).title}?`}function PP(e,t){const n=new Map(t.map(r=>[String(r.device_id||"").trim(),r]).filter(([r])=>r.length>0));return e.map(r=>{const i=String(r.device_id||"").trim();if(!i)return null;const o=n.get(i),s=String(o?.status||"").trim(),c=o?s==="revoked"?"revoked":"active":"not_member",l=typeof o?.membership_epoch=="number"&&Number.isFinite(o.membership_epoch)?Math.trunc(o.membership_epoch):null;return{deviceId:i,displayName:String(r.display_name||i||"Unnamed device"),enabled:r.enabled!==!1&&r.enabled!==0,status:c,role:String(o?.role||"member"),membershipEpoch:l,updatedAt:o?.updated_at?String(o.updated_at):null}}).filter(r=>r!==null).sort((r,i)=>{const o={active:0,revoked:1,not_member:2};return o[r.status]-o[i.status]||r.displayName.localeCompare(i.displayName)})}function AP(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)}function EP(){return{loaded:!1,loading:!1,error:"",includeInactive:!1,devicesLoaded:!1,scopes:[],membersByScope:new Map,devices:[],createScopeId:"",createLabel:"",createKind:"team",actionPendingKey:"",actionPendingKind:""}}function Il(e){if(!e||typeof e!="object")return[];const t=e.items;return Array.isArray(t)?t:[]}function dt(e){let t=O.groupScopeManagementDrafts.get(e);return t||(t=EP(),O.groupScopeManagementDrafts.set(e,t)),t}function bt(e,t){O.groupScopeManagementDrafts.set(e,t)}async function Gr(e,t,n=dt(e).includeInactive){bt(e,{...dt(e),loading:!0,error:"",includeInactive:n}),t();try{const[r,i]=await Promise.all([x_(e,n),Eu(e,!0)]),o=Il(r),s=Il(i),c=await Promise.all(o.map(async l=>{const d=String(l.scope_id||"").trim();return d?[d,Il(await A_(e,d,!0))]:[d,[]]}));bt(e,{...dt(e),loaded:!0,loading:!1,error:"",includeInactive:n,devicesLoaded:!0,scopes:o,devices:s,membersByScope:new Map(c.filter(([l])=>l.length>0)),actionPendingKey:"",actionPendingKind:""})}catch(r){bt(e,{...dt(e),loaded:!0,loading:!1,error:r instanceof Error?r.message:"Failed to load Spaces."})}t()}function Rl(e,t){O.groupScopeManagementOpen.add(e),dt(e),t(),Gr(e,t)}function $g(e,t){O.groupScopeManagementOpen.delete(e),O.groupScopeManagementDrafts.delete(e),t()}async function IP(e,t){const n=dt(e);if(n.actionPendingKey)return;const r=n.createScopeId.trim(),i=n.createLabel.trim(),o=n.createKind.trim()||"team";if(!r||!i){ne("Enter a Space id and label before creating a Space.","warning");return}bt(e,{...n,actionPendingKey:`create:${r}`,actionPendingKind:"create",error:""}),t();try{await P_(e,{scope_id:r,label:i,kind:o});const s=dt(e);bt(e,{...s,createScopeId:"",createLabel:"",createKind:"team",actionPendingKey:"",actionPendingKind:""}),ne("Space created. Grant devices explicitly before data can sync."),await Gr(e,t,s.includeInactive)}catch(s){bt(e,{...dt(e),actionPendingKey:"",actionPendingKind:"",error:s instanceof Error?s.message:"Failed to create Space."}),t()}}async function RP(e,t,n,r){const i=dt(e),o=`grant:${t}:${n}`;if(!i.actionPendingKey){bt(e,{...i,actionPendingKey:o,actionPendingKind:"grant",error:""}),r();try{await E_(e,t,{device_id:n,role:"member"}),ne("Device granted access to the Space."),await Gr(e,r,i.includeInactive)}catch(s){bt(e,{...dt(e),actionPendingKey:"",actionPendingKind:"",error:s instanceof Error?s.message:"Failed to grant Space access."}),r()}}}async function DP(e,t,n,r,i){const o=String(t.scope_id||"").trim();if(!o||!await Kt({title:xP(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 s=dt(e),c=`revoke:${o}:${n}`;if(!s.actionPendingKey){bt(e,{...s,actionPendingKey:c,actionPendingKind:"revoke",error:""}),i();try{await I_(e,o,n),ne("Space access revoked. Future sync is blocked for that device."),await Gr(e,i,s.includeInactive)}catch(l){bt(e,{...dt(e),actionPendingKey:"",actionPendingKind:"",error:l instanceof Error?l.message:"Failed to revoke Space access."}),i()}}}function LP(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=PP(AP(n.devices,b.lastCoordinatorAdminDevices,e,n.devicesLoaded),n.membersByScope.get(o)??[]);return s.length?v("div",{class:"coordinator-admin-scope-member-list"},s.map(c=>{const l=`${n.actionPendingKind}:${o}:${c.deviceId}`,d=n.actionPendingKey===l,u=c.enabled&&c.status!=="active",p=c.status==="active",m=NP(c);return v("div",{class:"coordinator-admin-scope-member-row",key:c.deviceId},v("div",{class:"coordinator-admin-scope-member-copy"},v("strong",null,c.displayName),v("span",null,m.detail),v("span",{class:"peer-meta"},m.advancedDetail),c.enabled?null:v("span",null,"Device is disabled in this Team.")),v("div",{class:"peer-actions"},u?v("button",{class:"settings-button",disabled:!r||!!n.actionPendingKey,onClick:()=>{RP(e,o,c.deviceId,i)},type:"button"},d&&n.actionPendingKind==="grant"?"Granting…":"Grant access"):null,p?v("button",{class:"settings-button danger",disabled:!r||!!n.actionPendingKey,onClick:()=>{DP(e,t,c.deviceId,c.displayName,i)},type:"button"},d&&n.actionPendingKind==="revoke"?"Revoking…":"Revoke access"):null))})):v("div",{class:"peer-submeta coordinator-admin-empty-state"},"No enrolled devices in this Team yet. Enroll a device before granting this Space.")}function $P(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=Lg(t);return v("div",{class:"peer-card peer-card--padded coordinator-admin-scope-card",key:o||s.title},v("div",{class:"peer-title"},v("strong",null,s.title)),v("div",{class:"peer-submeta"},s.summary),v("div",{class:"peer-meta"},s.advancedDetail),v("div",{class:"peer-submeta"},"Devices below are enrolled in the Team; only active Space members can sync this data boundary."),LP(e,t,n,r,i))}function MP(e){const{groupId:t,ready:n,summary:r,renderShell:i}=e,o=O.groupScopeManagementDrafts.get(t);if(!o)return null;const s=TP(r);if(s)return v("div",{class:"peer-meta coordinator-admin-inline-warning"},s);if(!o.loaded)return v("div",{class:"peer-submeta"},"Loading Spaces…");const c=!n||!!o.actionPendingKey||o.loading;return v(te,null,v("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),v("div",{class:"peer-submeta"},"Teams discover and enroll devices. Spaces grant data access. Granting a device here is explicit; Team membership alone does not share memories."),v("label",{class:"coordinator-admin-inline-filter"},v("span",{class:"section-meta",id:`coord-admin-domain-inactive-${t}`},"Show inactive Spaces"),v(Fr,{"aria-labelledby":`coord-admin-domain-inactive-${t}`,checked:o.includeInactive,className:"coordinator-admin-switch",disabled:c,onCheckedChange:l=>{Gr(t,i,l)},thumbClassName:"coordinator-admin-switch-thumb"})),v("form",{class:"coordinator-admin-form",onSubmit:l=>{l.preventDefault(),!c&&IP(t,i)}},v("div",{class:"coordinator-admin-form-grid"},v("label",{class:"coordinator-admin-field"},v("span",null,"New Space id"),v(we,{class:"peer-scope-input",disabled:c,onInput:l=>{bt(t,{...dt(t),createScopeId:String(l.currentTarget.value||"")})},placeholder:"acme-work",type:"text",value:o.createScopeId})),v("label",{class:"coordinator-admin-field"},v("span",null,"Label"),v(we,{class:"peer-scope-input",disabled:c,onInput:l=>{bt(t,{...dt(t),createLabel:String(l.currentTarget.value||"")})},placeholder:"Acme Work",type:"text",value:o.createLabel})),v("label",{class:"coordinator-admin-field"},v("span",null,"Kind"),v(we,{class:"peer-scope-input",disabled:c,onInput:l=>{bt(t,{...dt(t),createKind:String(l.currentTarget.value||"")})},placeholder:"team",type:"text",value:o.createKind}))),v("div",{class:"peer-actions"},v("button",{class:"settings-button",disabled:c,type:"submit"},o.actionPendingKind==="create"?"Creating…":"Create Space"),v("button",{class:"settings-button",disabled:c,onClick:()=>{Gr(t,i,o.includeInactive)},type:"button"},o.loading?"Refreshing…":"Refresh"))),o.error?v("div",{class:"peer-submeta coordinator-admin-error"},o.error):null,o.scopes.length?v("div",{class:"coordinator-admin-scope-card-list"},o.scopes.map(l=>$P(t,l,o,n,i))):v("div",{class:"peer-meta coordinator-admin-empty-state"},"No Spaces are defined for this Team yet. Create a Space, then grant specific devices. Projects stay local-only until assigned to a Space."))}function Mg(){return v("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"},v("title",null,"Chevron"),v("path",{d:"m9 18 6-6-6-6"}))}function OP(){return{projects_include:[],projects_exclude:[],auto_seed_scope:!0,default_space_scope_id:"",auto_grant_default_space_on_join:!1,loaded:!1,saving:!1,error:""}}async function Dl(e,t){const n=OP();O.groupPreferencesDrafts.set(e,n),O.groupPreferencesOpen.add(e),t();try{const r=await hw(e);O.groupPreferencesDrafts.set(e,{projects_include:Array.isArray(r.projects_include)?[...r.projects_include]:[],projects_exclude:Array.isArray(r.projects_exclude)?[...r.projects_exclude]:[],auto_seed_scope:r.auto_seed_scope,default_space_scope_id:r.default_space_scope_id||"",auto_grant_default_space_on_join:r.auto_grant_default_space_on_join===!0,loaded:!0,saving:!1,error:""})}catch(r){O.groupPreferencesDrafts.set(e,{...n,loaded:!0,error:r instanceof Error?r.message:"Failed to load preferences."})}t()}function Ba(e,t){O.groupPreferencesOpen.delete(e),O.groupPreferencesDrafts.delete(e),t()}async function jP(e,t){const n=O.groupPreferencesDrafts.get(e);if(!n||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};O.groupPreferencesDrafts.set(e,{...n,saving:!0,error:""}),t();try{await gw(e,r),ne("Team defaults saved. New devices use these filters and Space settings."),Ba(e,t)}catch(i){const o=O.groupPreferencesDrafts.get(e);if(!o)return;O.groupPreferencesDrafts.set(e,{...o,saving:!1,error:i instanceof Error?i.message:"Failed to save preferences."}),t()}}function FP(e,t,n){const r=O.groupPreferencesDrafts.get(e);if(!r)return null;if(!r.loaded)return v("div",{class:"peer-submeta"},"Loading project defaults…");const i=`coord-admin-scope-autoseed-${e}`,o=`coord-admin-default-space-autogrant-${e}`,s=`coord-admin-scope-include-${e}`,c=`coord-admin-scope-exclude-${e}`,l=!n||r.saving||!r.auto_seed_scope;return v(te,null,v("h4",{class:"coordinator-admin-drawer-title"},"Team defaults"),v("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."),v("label",{class:"coordinator-admin-inline-filter"},v("span",{class:"section-meta",id:i},"Auto-apply advanced rules to new devices"),v(Fr,{"aria-labelledby":i,checked:r.auto_seed_scope,className:"coordinator-admin-switch",disabled:!n||r.saving,onCheckedChange:d=>{const u=O.groupPreferencesDrafts.get(e)??r;O.groupPreferencesDrafts.set(e,{...u,auto_seed_scope:d}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),v("label",{class:"coordinator-admin-inline-filter"},v("span",{class:"section-meta",id:o},"Auto-grant default Space on join"),v(Fr,{"aria-labelledby":o,checked:r.auto_grant_default_space_on_join,className:"coordinator-admin-switch",disabled:!n||r.saving||!r.default_space_scope_id,onCheckedChange:d=>{const u=O.groupPreferencesDrafts.get(e)??r;O.groupPreferencesDrafts.set(e,{...u,auto_grant_default_space_on_join:d}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),r.default_space_scope_id?v("div",{class:"peer-submeta"},"Default Space configured."):v("div",{class:"peer-submeta"},"No default Space has been created yet."),v("div",{class:"coordinator-admin-field"},v("span",{id:s},"Include template"),v(Uh,{"aria-labelledby":s,availableProjects:O.availableProjects,disabled:l,emptyLabel:"All projects allowed.",onValuesChange:d=>{const u=O.groupPreferencesDrafts.get(e)??r;O.groupPreferencesDrafts.set(e,{...u,projects_include:d}),t()},placeholder:"Add project",values:r.projects_include}),v("span",{class:"peer-submeta"},"Leave empty to allow every project inside the granted Space. Type to search or create a new name.")),v("div",{class:"coordinator-admin-field"},v("span",{id:c},"Exclude template"),v(Uh,{"aria-labelledby":c,availableProjects:O.availableProjects,disabled:l,emptyLabel:"Nothing excluded.",onValuesChange:d=>{const u=O.groupPreferencesDrafts.get(e)??r;O.groupPreferencesDrafts.set(e,{...u,projects_exclude:d}),t()},placeholder:"Add project",values:r.projects_exclude})),r.error?v("div",{class:"peer-submeta coordinator-admin-error"},r.error):null,v("div",{class:"peer-actions"},v("button",{class:"settings-button",disabled:!n||r.saving,onClick:()=>{jP(e,t)},type:"button"},r.saving?"Saving…":"Save defaults"),v("button",{class:"settings-button",disabled:r.saving,onClick:()=>Ba(e,t),type:"button"},"Cancel")))}function BP(e){const t=O.teamSetupGuide;if(!t)return null;const n=t.displayName||t.groupId,r={default_space:"default Space setup",default_space_grant:"default Space access grant"}[t.setupWarning?.step||""]||"default Space setup";return v("div",{class:"peer-meta coordinator-admin-empty-state"},v("h4",{class:"coordinator-admin-drawer-title"},`Set up ${n}`),v("div",{class:"peer-submeta"},"A Team organizes people and devices. The default Space is the memory boundary; Team membership only grants data access when default Space auto-grant is enabled."),t.setupWarning?v("div",{class:"peer-meta coordinator-admin-inline-warning"},`Team created, but ${r} failed. Automatic repair is not available yet; use Spaces to inspect or create access manually before inviting teammates.`):v("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."),v("ol",{class:"peer-submeta"},v("li",null,"Review Team defaults and the auto-grant default Space setting."),v("li",null,"Invite teammates or other devices."),v("li",null,"Assign projects to Spaces from the Projects tab.")),v("div",{class:"peer-actions"},v("button",{class:"settings-button",onClick:()=>{O.groupPreferencesOpen.add(t.groupId),Dl(t.groupId,e)},type:"button"},"Review Team defaults"),v("button",{class:"settings-button",onClick:()=>{Rl(t.groupId,e)},type:"button"},"Check Spaces"),v("button",{class:"settings-button",onClick:()=>{O.inviteGroup=t.groupId,O.activeSection="invites",e()},type:"button"},"Invite devices"),v("button",{class:"settings-button",onClick:()=>{window.location.hash="projects"},type:"button"},"Assign projects"),v("button",{class:"settings-button",onClick:()=>{O.teamSetupGuide=null,e()},type:"button"},"Dismiss")))}function UP(e,t){return t?e?"Restoring…":"Archiving…":e?"Unarchive":"Archive"}function GP(e){const{summary:t,createGroup:n,runGroup:r,renderShell:i,reloadData:o}=e,s=String(b.lastCoordinatorAdminStatus?.active_group||"").trim(),c=Zn(),l=Br(),d=l.filter(y=>!y.archived_at),u=l.filter(y=>y.archived_at),p=O.showArchivedGroups?l:d,m=c?l.some(y=>y.group_id===c):!1,f=[`${d.length} active`];return u.length&&f.push(`${u.length} archived`),v(Jn,{className:"coordinator-admin-panel",value:"groups"},v("h3",null,"Teams"),v("p",{class:"peer-submeta"},c?`Managing ${c}${s&&s!==c?` · this node uses ${s} for discovery`:""}`:s?`This node uses ${s} for discovery. Select a Team below to manage it.`:"No Team selected yet. Create one or select an existing Team to manage."),l.length?v("p",{class:"peer-submeta"},f.join(" · ")):null,!m&&c?v("div",{class:"peer-meta coordinator-admin-inline-warning"},`The selected Team (${c}) is configured locally but does not exist in the coordinator yet. Create it below or switch to another Team once one exists.`):null,BP(i),(()=>{const y=t.readiness!=="ready"||O.groupActionPendingKind==="create";return v("form",{class:"coordinator-admin-form",onSubmit:h=>{h.preventDefault(),!y&&n()}},v("div",{class:"coordinator-admin-form-grid"},v("label",{class:"coordinator-admin-field"},v("span",null,"New Team id"),v(we,{class:"peer-scope-input",disabled:y,onInput:h=>{O.createGroupId=String(h.currentTarget.value||"")},placeholder:"team-alpha",type:"text",value:O.createGroupId})),v("label",{class:"coordinator-admin-field"},v("span",null,"Display name"),v(we,{class:"peer-scope-input",disabled:y,onInput:h=>{O.createGroupDisplayName=String(h.currentTarget.value||"")},placeholder:"Team Alpha",type:"text",value:O.createGroupDisplayName}))),v("div",{class:"section-actions coordinator-admin-groups-toolbar"},v("div",{class:"coordinator-admin-primary-actions"},v("button",{class:"settings-button",disabled:y,type:"submit"},O.groupActionPendingKind==="create"?"Creating…":"Create Team")),v("div",{class:"coordinator-admin-secondary-actions"},v("label",{class:"coordinator-admin-inline-filter"},v("span",{class:"section-meta",id:"coordinatorAdminShowArchivedLabel"},"Show archived"),v(Fr,{"aria-labelledby":"coordinatorAdminShowArchivedLabel",checked:O.showArchivedGroups,className:"coordinator-admin-switch",disabled:t.readiness!=="ready",onCheckedChange:h=>{O.showArchivedGroups=h,i()},thumbClassName:"coordinator-admin-switch-thumb"})))))})(),p.length?v("div",{class:"peer-list"},p.map(y=>{const h=y.group_id===c,g=O.groupActionPendingId===y.group_id,_=!!y.archived_at,w=O.groupRenameDrafts.get(y.group_id)??y.display_name??y.group_id,S=O.groupPreferencesOpen.has(y.group_id),T=O.groupScopeManagementOpen.has(y.group_id),k=_?"unarchive":"archive",P=UP(_,g&&O.groupActionPendingKind===k),E=vx({groupId:y.group_id,preferences:O.groupPreferencesDrafts.get(y.group_id),scopeManagement:O.groupScopeManagementDrafts.get(y.group_id),setupGuide:O.teamSetupGuide});return v("div",{class:"peer-card peer-card--padded",key:y.group_id},v("div",{class:"peer-title"},v("strong",null,w)),v("div",{class:"peer-submeta"},_?"Archived Team":"Active Team"),v("div",{class:"peer-meta"},`Advanced: Team ID ${y.group_id}`),v("div",{class:"coordinator-admin-summary-grid"},v("div",{class:"coordinator-admin-summary-card"},v("span",{class:"section-meta"},"Default Space"),v("strong",null,E.defaultSpace)),v("div",{class:"coordinator-admin-summary-card"},v("span",{class:"section-meta"},"Auto-grant"),v("strong",null,E.autoGrant)),v("div",{class:"coordinator-admin-summary-card"},v("span",{class:"section-meta"},"Spaces"),v("strong",null,E.spaces))),s===y.group_id?v("div",{class:"peer-submeta"},"This node uses this Team for coordinator-backed discovery."):null,v("label",{class:"coordinator-admin-field"},v("span",null,"Display name"),v(we,{class:"peer-scope-input",disabled:t.readiness!=="ready"||g,onInput:M=>{O.groupRenameDrafts.set(y.group_id,String(M.currentTarget.value||""))},type:"text",value:w})),v("div",{class:"peer-actions"},v("button",{class:"settings-button",disabled:t.readiness!=="ready"||h,onClick:()=>{vl(y.group_id),o()},type:"button"},h?"Managing":"Manage Team"),v("button",{class:"settings-button",disabled:t.readiness!=="ready"||g,onClick:()=>r(y.group_id,w,"rename"),type:"button"},g&&O.groupActionPendingKind==="rename"?"Renaming…":"Rename"),v("button",{"aria-expanded":S,"aria-controls":`coord-admin-project-defaults-drawer-${y.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":S?"open":"closed",disabled:t.readiness!=="ready"||g,onClick:()=>{S?Ba(y.group_id,i):Dl(y.group_id,i)},type:"button"},v("span",null,"Team defaults"),v("span",{"aria-hidden":"true",class:"device-row-chevron"},v(Mg,null))),v("button",{"aria-expanded":T,"aria-controls":`coord-admin-spaces-drawer-${y.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":T?"open":"closed",disabled:t.readiness!=="ready"||g,onClick:()=>{T?$g(y.group_id,i):Rl(y.group_id,i)},type:"button"},v("span",null,"Spaces & access"),v("span",{"aria-hidden":"true",class:"device-row-chevron"},v(Mg,null))),v("button",{class:_?"settings-button":"settings-button danger",disabled:t.readiness!=="ready"||g,onClick:()=>r(y.group_id,y.display_name||y.group_id,k),type:"button"},P)),v(ga,{open:S,onOpenChange:M=>{M?Dl(y.group_id,i):Ba(y.group_id,i)}},v(va,{"aria-label":`Project defaults for ${w}`,class:"coordinator-admin-group-preferences",id:`coord-admin-project-defaults-drawer-${y.group_id}`},S?FP(y.group_id,i,t.readiness==="ready"):null)),v(ga,{open:T,onOpenChange:M=>{M?Rl(y.group_id,i):$g(y.group_id,i)}},v(va,{"aria-label":`Spaces for ${w}`,class:"coordinator-admin-group-preferences coordinator-admin-domain-management",id:`coord-admin-spaces-drawer-${y.group_id}`},T?MP({groupId:y.group_id,ready:t.readiness==="ready",renderShell:i,summary:t}):null)))})):v("div",{class:"peer-meta coordinator-admin-empty-state"},t.readiness==="ready"?O.showArchivedGroups?"No Teams are available yet.":"No active Teams yet. Create one to get started.":"Team browsing will appear here once setup is complete."))}function Hr(e){return a("textarea",{...e})}function HP(e){const{summary:t,createInvite:n,renderShell:r}=e,i=b.lastCoordinatorAdminStatus,o=Zn()||String(i?.active_group||"").trim(),s=O.inviteGroup.trim()||o,c=String(b.lastTeamInvite?.encoded||"").trim(),l=Array.isArray(b.lastTeamInvite?.warnings)?b.lastTeamInvite?.warnings:[],d=t.readiness!=="ready"||O.invitePending;return v(Jn,{className:"coordinator-admin-panel",value:"invites"},v("h3",null,"Legacy Team invites"),v("p",{class:"peer-submeta"},t.readiness==="ready"?"Legacy Team invites enroll a device in the selected Team. They do not grant project access; share projects from Projects instead.":"Finish setup first. Invite creation stays disabled until the local Teams configuration is ready."),v("form",{class:"coordinator-admin-form",onSubmit:u=>{u.preventDefault(),!d&&n()}},v("div",{class:"coordinator-admin-form-grid"},v("label",{class:"coordinator-admin-field"},v("span",null,"Team"),v(we,{class:"peer-scope-input",disabled:t.readiness!=="ready",onInput:u=>{O.inviteGroup=String(u.currentTarget.value||""),r()},placeholder:o||"team-alpha",type:"text",value:O.inviteGroup})),v("label",{class:"coordinator-admin-field"},v("span",null,"Join policy"),v(cn,{ariaLabel:"Invite join policy",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:t.readiness!=="ready",id:"coordinatorAdminInvitePolicy",itemClassName:"sync-radix-select-item",onValueChange:u=>{O.invitePolicy=u==="approval_required"?"approval_required":"auto_admit",r()},options:[{value:"auto_admit",label:"Auto-admit to Team"},{value:"approval_required",label:"Require approval to join Team"}],triggerClassName:"sync-radix-select-trigger sync-actor-select",value:O.invitePolicy,viewportClassName:"sync-radix-select-viewport"})),v("label",{class:"coordinator-admin-field"},v("span",null,"Expires in (hours)"),v(we,{class:"peer-scope-input",disabled:t.readiness!=="ready",min:"1",onInput:u=>{O.inviteTtlHours=String(u.currentTarget.value||"")},type:"number",value:O.inviteTtlHours}))),v("div",{class:"section-actions"},v("button",{class:"settings-button",disabled:d,type:"submit"},O.invitePending?"Creating…":"Create legacy Team invite"),s?v("span",{class:"peer-submeta"},`Using Team ${s}`):null)),c?v("label",{class:"coordinator-admin-field"},v("span",null,"Generated invite"),v(Hr,{class:"feed-search coordinator-admin-output",readOnly:!0,value:c}),v("button",{class:"settings-button sync-action-copy",type:"button",onClick:u=>Pi(c,u.currentTarget)},"Copy")):null,l?.length?v("div",{class:"peer-meta coordinator-admin-warning-list"},l.join(" · ")):null,v("h3",null,"Project sharing operations"),v("p",{class:"peer-submeta"},"Read-only status from the project-first sharing flow. Start new sharing from Projects."),b.lastShareOperations.length>0?v("ul",{class:"peer-scope-rejections-list","aria-label":"Project sharing operations"},...b.lastShareOperations.map(u=>v("li",{key:u.operation_id},v("strong",null,u.person.display_name),v("span",null,` — ${u.projects.map(p=>p.display_name).join(", ")} — ${u.lifecycle.label}`)))):v("div",{class:"peer-meta"},"No project sharing operations yet."))}function KP(e){const{summary:t,reviewJoinRequest:n}=e,r=Array.isArray(b.lastCoordinatorAdminJoinRequests)?b.lastCoordinatorAdminJoinRequests:[];return v(Jn,{className:"coordinator-admin-panel",value:"join-requests"},v("h3",null,"Pending join requests"),v("p",{class:"peer-submeta"},t.readiness==="ready"?"Approve or deny devices that want to join this Team. Default Space access is handled by Team defaults and can be reviewed in Spaces.":"Finish setup first. Join request review stays disabled until Teams is ready."),r.length?v("div",{class:"peer-list"},r.map(i=>{const o=String(i.request_id||"").trim(),s=String(i.device_id||"unknown-device"),c=String(i.display_name||s).trim()||s,l=String(i.fingerprint||"").trim(),d=[`Device ID ${s}`];l&&d.push(`Fingerprint ${l}`);const u=O.joinReviewPendingId===o;return v("div",{class:"peer-card peer-card--padded",key:o||s},v("div",{class:"peer-title"},v("strong",null,c)),v("div",{class:"peer-meta"},`Advanced: ${d.join(" · ")}`),v("div",{class:"peer-actions"},v("button",{class:"settings-button",disabled:!o||u,onClick:()=>n(o,"approve"),type:"button"},u&&O.joinReviewPendingAction==="approve"?"Approving…":"Approve"),v("button",{class:"settings-button danger",disabled:!o||u,onClick:()=>n(o,"deny"),type:"button"},u&&O.joinReviewPendingAction==="deny"?"Denying…":"Deny")))})):v("div",{class:"peer-meta"},t.readiness==="ready"?"No pending join requests right now.":"Join request review will appear here once setup is complete."))}function VP(e){const{renderShell:t,reloadData:n}=e;async function r(){if(O.groupActionPendingKind)return;const l=O.createGroupId.trim();if(!l){ne("Enter a Team id before creating a Team.","warning");return}const d=O.createGroupDisplayName.trim();O.groupActionPendingKind="create",t();try{const u=await C_({group_id:l,display_name:d||null}),p=u.default_space,m=(p&&"scope"in p?p.scope:p)??{},f=p&&"preferences"in p?p.preferences:null,y=String(m?.scope_id||"");O.createGroupId="",O.createGroupDisplayName="",O.teamSetupGuide={groupId:l,displayName:String(u.group?.display_name||d||l),defaultSpaceScopeId:y,defaultSpaceLabel:String(m?.label||""),autoGrantDefaultSpaceOnJoin:typeof f?.auto_grant_default_space_on_join=="boolean"?f.auto_grant_default_space_on_join:null,setupWarning:u.setup_warning||null},await n(),vl(l),await n(),u.setup_warning?ne("Team created, but default Space setup needs repair.","warning"):y?ne("Team created with a default Space.","success"):ne("Team created, but default Space status is unknown.","warning")}catch(u){ne(u instanceof Error?u.message:"Failed to create Team.","warning")}finally{O.groupActionPendingKind="",t()}}async function i(l,d,u){if(!(!l||O.groupActionPendingId)&&!((u==="archive"||u==="unarchive")&&!await Kt({title:`${u==="archive"?"Archive":"Unarchive"} ${d||l}?`,description:u==="archive"?"Archived Teams stay visible and restorable, but they stop being operational for new invites and joins.":"This Team will become operational again for invites and coordinator-backed joins.",confirmLabel:u==="archive"?"Archive Team":"Unarchive Team",cancelLabel:u==="archive"?"Keep Team active":"Keep Team archived",tone:"danger"}))){O.groupActionPendingId=l,O.groupActionPendingKind=u,t();try{u==="rename"&&(await T_(l,d),ne("Team renamed.","success")),u==="archive"&&(await k_(l),ne("Team archived.","success")),u==="unarchive"&&(await N_(l),ne("Team unarchived.","success")),await n()}catch(p){ne(p instanceof Error?p.message:`Failed to ${u} Team.`,"warning")}finally{O.groupActionPendingId="",O.groupActionPendingKind="",t()}}}async function o(){if(O.invitePending)return;const l=b.lastCoordinatorAdminStatus,d=Zn()||String(l?.active_group||"").trim(),u=O.inviteGroup.trim()||d,p=Number(O.inviteTtlHours);if(!u){ne("Choose a Team before creating an invite.","warning");return}if(!Number.isFinite(p)||p<1){ne("Invite lifetime must be at least 1 hour.","warning");return}O.invitePending=!0,t();try{const m=await Iu({group_id:u,policy:O.invitePolicy,ttl_hours:p});b.lastTeamInvite=m,O.inviteGroup=u;const f=Array.isArray(m.warnings)?m.warnings:[];ne(f.length?`Invite created. Review ${f.length===1?"the warning":`${f.length} warnings`} before sharing it.`:"Invite created. Copy it from Teams and share it with your teammate.",f.length?"warning":"success")}catch(m){ne(m instanceof Error?m.message:"Failed to create invite.","warning")}finally{O.invitePending=!1,t()}}async function s(l,d){if(!O.joinReviewPendingId){O.joinReviewPendingId=l,O.joinReviewPendingAction=d,t();try{const u=await D_(l,d);d==="approve"&&u.setup_warning?ne("Join request approved, but default Space access needs repair.","warning"):ne(d==="approve"?"Join request approved.":"Join request denied.","success"),await n()}catch(u){ne(u instanceof Error?u.message:"Failed to review join request.","warning")}finally{O.joinReviewPendingId="",O.joinReviewPendingAction="",t()}}}async function c(l,d,u,p){if(!(!l||O.deviceActionPendingId)&&!((p==="disable"||p==="remove")&&!await Kt({title:`${p==="disable"?"Disable":"Remove"} ${u||l}?`,description:p==="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:p==="disable"?"Disable device":"Remove device",cancelLabel:p==="disable"?"Keep device enabled":"Keep device enrolled",tone:"danger"}))){O.deviceActionPendingId=l,O.deviceActionPendingKind=p,t();try{if(p==="rename"){const m=String(O.deviceRenameDrafts.get(l)||"").trim();if(!m){ne("Enter a device name before renaming it.","warning");return}await L_(l,d,m),ne("Device renamed.","success")}p==="disable"&&(await $_(l,d),ne("Device disabled.","success")),p==="enable"&&(await M_(l,d),ne("Device enabled.","success")),p==="remove"&&(await O_(l,d),ne("Device removed.","success")),await n()}catch(m){ne(m instanceof Error?m.message:`Failed to ${p} device.`,"warning")}finally{O.deviceActionPendingId="",O.deviceActionPendingKind="",t()}}}return{createGroupFromAdminPanel:r,runGroupAction:i,createInviteFromAdminPanel:o,reviewJoinRequestFromAdminPanel:s,runDeviceAction:c}}function WP(){const e=b.lastCoordinatorAdminStatus;return e?e.readiness==="ready"?{readiness:"ready",title:"Teams is ready",detail:"This viewer can use the local Teams admin configuration to manage invites, join requests, and enrolled devices without exposing the admin secret to the browser."}:e.readiness==="partial"?{readiness:"partial",title:"Teams setup is incomplete",detail:e.has_admin_secret===!1?"Set a coordinator admin secret for the viewer server before using Teams invite and device actions.":"Finish configuring the coordinator target and Team before using Teams actions."}:{readiness:"not_configured",title:"Teams is not configured",detail:"Set a coordinator URL, Team, and admin secret locally to enable remote Teams administration from this viewer."}:{readiness:"partial",title:"Checking Teams readiness…",detail:"Loading local Teams configuration from the viewer server."}}var{createGroupFromAdminPanel:qP,runGroupAction:zP,createInviteFromAdminPanel:JP,reviewJoinRequestFromAdminPanel:YP,runDeviceAction:XP}=VP({renderShell:()=>nr(),reloadData:()=>Ll()});function nr(){const e=document.getElementById("coordinatorAdminMount");if(!e)return;const t=b.lastCoordinatorAdminStatus,n=WP(),r=String(t?.coordinator_url||"").trim(),i=String(t?.active_group||"").trim(),s=!!dx()?.archived_at,c=n.readiness==="ready",l=n.readiness==="ready"&&!s,d=n.readiness==="ready",u=n.readiness==="ready",p=Zn(),m=Br().filter(_=>!_.archived_at).length,f=Br().filter(_=>_.archived_at).length,y=Array.isArray(b.lastCoordinatorAdminJoinRequests)?b.lastCoordinatorAdminJoinRequests.length:0,h=Array.isArray(b.lastCoordinatorAdminDevices)?b.lastCoordinatorAdminDevices.length:0,g=n.readiness!=="ready"?n.detail:s?"The selected Team is archived. Restore it or switch Teams before creating invites.":"";(O.activeSection==="invites"&&!l||O.activeSection==="groups"&&!c||O.activeSection==="join-requests"&&!d||O.activeSection==="devices"&&!u)&&(O.activeSection=n.readiness==="ready"?"groups":"invites"),Be(v("div",{class:"coordinator-admin-shell"},v("div",{class:"card coordinator-admin-header"},v("div",{class:"section-header"},v("h2",null,"Teams")),v("div",{class:"coordinator-admin-summary-grid"},v("div",{class:"coordinator-admin-summary-card"},v("span",{class:"section-meta"},"Team admin target"),v("strong",null,p||"None selected")),v("div",{class:"coordinator-admin-summary-card"},v("span",{class:"section-meta"},"Node discovery Team"),v("strong",null,i||"None")),v("div",{class:"coordinator-admin-summary-card"},v("span",{class:"section-meta"},"Teams"),v("strong",null,`${m} active${f?` · ${f} archived`:""}`)),v("div",{class:"coordinator-admin-summary-card"},v("span",{class:"section-meta"},"Selected Team activity"),v("strong",null,`${y} join requests · ${h} devices`))),g?v("div",{class:"peer-meta coordinator-admin-inline-warning"},g):null,r?v("div",{class:"section-meta coordinator-admin-inline-meta"},`Coordinator: ${r}`):null),v("div",{class:"card coordinator-admin-sections"},v(Hf,{ariaLabel:"Teams sections",listClassName:"coordinator-admin-tabs-list",onValueChange:_=>{O.activeSection=_||"groups",nr()},tabs:[{value:"groups",label:"Teams",disabled:!c},{value:"invites",label:"Invites",disabled:!l},{value:"join-requests",label:"Join requests",disabled:!d},{value:"devices",label:"Devices",disabled:!u}],triggerClassName:"coordinator-admin-tab-trigger",value:O.activeSection},GP({summary:n,createGroup:()=>{qP()},runGroup:(_,w,S)=>{zP(_,w,S)},renderShell:nr,reloadData:()=>{Ll()}}),HP({summary:n,createInvite:()=>{JP()},renderShell:nr}),KP({summary:n,reviewJoinRequest:(_,w)=>{YP(_,w)}}),Ek({summary:n,runDevice:(_,w,S,T)=>{XP(_,w,S,T)}})),v("div",{class:"section-meta coordinator-admin-context-line"},s?`Selected Team ${p||"—"} is archived. Switch or restore it to enable invite operations.`:p?`Actions below apply to ${p}.`:"Select a Team to start managing people, Spaces, and access."))),e)}function ZP(){nr()}async function Ll(){try{b.lastCoordinatorAdminStatus=await To()}catch{b.lastCoordinatorAdminStatus=null,b.lastCoordinatorAdminJoinRequests=[],b.lastCoordinatorAdminDevices=[],O.deviceRenameDrafts.clear(),O.deviceRenameServerNames.clear(),nr();return}const e=String(b.lastCoordinatorAdminStatus?.active_group||"").trim();if(zh(),b.lastCoordinatorAdminStatus?.readiness==="ready"){try{const n=await Gu();b.lastShareOperations=Array.isArray(n.items)?n.items:[]}catch{}try{const n=await Au(O.showArchivedGroups);b.lastCoordinatorAdminGroups=Array.isArray(n?.items)?n.items:[],lx(),zh()}catch{b.lastCoordinatorAdminGroups=[],O.groupRenameDrafts.clear()}const t=Zn();try{const n=await R_(t||e);b.lastCoordinatorAdminJoinRequests=Array.isArray(n?.items)?n.items:[]}catch{b.lastCoordinatorAdminJoinRequests=[]}try{const n=await Eu(t||e,!0);b.lastCoordinatorAdminDevices=Array.isArray(n?.items)?n.items:[],ux()}catch{b.lastCoordinatorAdminDevices=[]}try{O.availableProjects=await ko()}catch{O.availableProjects=[]}}else b.lastCoordinatorAdminGroups=[],O.groupRenameDrafts.clear(),b.lastCoordinatorAdminJoinRequests=[],b.lastCoordinatorAdminDevices=[],O.deviceRenameDrafts.clear(),O.deviceRenameServerNames.clear();nr()}var $l=new WeakMap,Og={active:0,verifying:1,pending:2,waiting:3,needs_attention:4},QP={state:"pending",label:"Recipient policy pending",explanation:"Current access remains in place while this Project is prepared.",deliveredCopiesMayRemain:!0},eA={available:"Available",offline:"Offline",unknown:"Availability unknown"};function tA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function nA(e,t){return t.get(e)??QP}function rA(e){return e.reduce((t,n)=>!t||Og[n.state]>Og[t.state]?n:t,null)}function iA(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 oA(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),m=tA(e.projectRecipients.filter(S=>S.status==="active"&&S.recipientKind==="identity"&&S.identityId===u.identityId).map(S=>S.canonicalProjectIdentity)),f=S=>{const T=s.get(S);if(!T)return null;const k=nA(S,d);return{canonicalProjectIdentity:S,displayName:T,state:k.state,statusLabel:k.label,statusCopy:k.explanation,deliveredCopiesMayRemain:k.deliveredCopiesMayRemain}},y=m.flatMap(S=>{const T=f(S);return T?[T]:[]}),h=[],g=[...y,...h],_=rA(g),w=c.get(u.deviceId)??"unknown";return{deviceId:u.deviceId,displayName:u.displayName,identityName:o.get(u.identityId)??"Identity unavailable",availability:w,availabilityLabel:eA[w],isPairedPeer:p!==void 0,reportedRuntimeVersion:p?.runtimeVersion??null,runtimeVersionObservedAt:p?.runtimeVersionObservedAt??null,directProjects:y,inheritedProjects:h,unavailableProjectCount:m.length-y.length,statusState:_?.state??"no_projects",statusLabel:_?.statusLabel??"No directly shared Projects",statusCopy:_?.statusCopy??"Team access is not shown here without authoritative per-device eligibility.",deliveredCopiesMayRemain:g.some(S=>S.deliveredCopiesMayRemain),action:iA(w,_?.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 jg({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 aA({options:e,projection:t}){if(e.loading)return a("p",{"aria-live":"polite",className:"small",role:"status",children:"Loading Devices…"});if(e.loadError)return a("p",{"aria-live":"assertive",role:"alert",children:"Devices are unavailable. Refresh and try again."});const n=e.refreshError?a("p",{"aria-live":"assertive",role:"alert",children:"Refresh failed; showing previous device information."}):null;return t.devices.length===0?a(te,{children:[n,a("p",{className:"small",role:"status",children:["No active devices are registered.",t.revokedDeviceCount>0?` ${t.revokedDeviceCount.toLocaleString()} revoked ${t.revokedDeviceCount===1?"device is":"devices are"} not shown.`:""]})]}):a(te,{children:[n,a("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:t.devices.map((r,i)=>{const o=`devices-card-title-${i}`,s=r.action;return a("li",{children:a("article",{"aria-labelledby":o,className:"peer-card peer-card--padded recipient-policy-sharing-card",children:[a("div",{className:"peer-title recipient-policy-sharing-card-title",children:[a("h3",{id:o,children:r.displayName}),a("span",{className:"badge actor-badge",children:r.availabilityLabel})]}),a("dl",{className:"recipient-policy-sharing-details",children:[a("div",{children:[a("dt",{children:"Owning Identity"}),a("dd",{children:r.identityName})]}),a("div",{children:[a("dt",{children:"Availability"}),a("dd",{children:r.availabilityLabel})]}),r.isPairedPeer?a("div",{children:[a("dt",{children:"Codemem version"}),a("dd",{children:r.reportedRuntimeVersion??"Not reported"})]}):null,a("div",{children:[a("dt",{children:"Sharing status"}),a("dd",{children:[a("strong",{children:r.statusLabel})," — ",r.statusCopy]})]})]}),a("section",{"aria-labelledby":`${o}-direct`,children:[a("h4",{id:`${o}-direct`,children:"Direct Projects"}),a(jg,{empty:"No Projects are shared directly.",projects:r.directProjects})]}),a("section",{"aria-labelledby":`${o}-teams`,children:[a("h4",{id:`${o}-teams`,children:"Projects through Teams"}),a(jg,{empty:"Per-device Team access is not shown because Team membership alone does not prove this device receives the Team’s Projects.",projects:r.inheritedProjects})]}),r.unavailableProjectCount>0?a("p",{className:"small",role:"status",children:"Some Project names are unavailable and are not shown."}):null,r.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,s&&e.onNavigate?a("button",{"aria-label":`${s.label} for ${r.displayName}`,className:"settings-button recipient-policy-sharing-target-24",onClick:()=>e.onNavigate?.(s.target),ref:c=>{c&&$l.set(c,{deviceId:r.deviceId,target:s.target})},type:"button",children:s.label}):null]})},r.deviceId)})}),t.revokedDeviceCount>0?a("p",{className:"small",role:"status",children:[t.revokedDeviceCount.toLocaleString()," revoked"," ",t.revokedDeviceCount===1?"device is":"devices are"," not included in the active list."]}):null]})}function Ua(e,t,n,r,i,o={}){const s=document.activeElement,c=s instanceof HTMLElement&&e.contains(s)?$l.get(s):void 0,l=oA(t,n,r,i,o.peerRuntimeMetadata);Be(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",children:"Devices"}),a("p",{className:"small",children:"See where Codemem runs and which Projects each active device receives."})]}),a(aA,{options:o,projection:l})]}),e),c&&([...e.querySelectorAll("button")].find(d=>{const u=$l.get(d);return u?.deviceId===c.deviceId&&u.target===c.target})??document.getElementById("tabBtn-devices"))?.focus()}function sA(e){if(!e)return"n/a";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function rr(e){if(!e)return"never";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function cA(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 Kr(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 kn(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 Fg(e){const t=Number(e);return Number.isFinite(t)?`${Math.round(t*100)}%`:"n/a"}function lA(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 Ml(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 Fi(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 dA(e){const t=String(e||"").trim();if(!t.endsWith("%"))return null;const n=Number(t.replace("%",""));return Number.isFinite(n)?n:null}function It(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function Ga(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 Bg(e){const t=String(e||"").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function uA(e){return e.replace(/_/g," ").split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ").trim()}function pA(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 Ug(e){if(!e)return"";const t=String(e).trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n).trim()}function mA(e){const t=String(e||"");return t?t.replace(/^\/Users\/[^/]+(?=\/|$)/,"~").replace(/^\/home\/[^/]+(?=\/|$)/,"~").replace(/^[A-Z]:\\Users\\[^\\]+(?=\\|$)/,"~"):""}function fA(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 Ha(e){if(!e||typeof e!="object")return{};const t=e,n=t.import_metadata;return n&&typeof n=="object"?{...n,...t}:t}function hA(e){if(!e)return[];const t=String(e).split(`
46
- `).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 gA(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 Gg(e){const t=It(e.title),n=It(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 Hg(e){return String(e.id??e.memory_id??e.observation_id??e.session_id??e.created_at_utc??e.created_at??"")}function ft(e){return`${String(e.kind||"").toLowerCase()}:${Hg(e)}`}function vA(e){return e==="mine"?" · my memories":e==="theirs"?" · other people":""}function yA(e){return e==="legacy_unknown"?"legacy provenance":e==="unreviewed"?"unreviewed":e.replace(/_/g," ")}function bA(e){if(e?.owned_by_self===!0)return"You";const t=String(e.actor_id||"").trim(),n=String(e.actor_display_name||"").trim();return t&&t===b.lastStatsPayload?.identity?.actor_id?"You":n||t||"Unknown author"}function Kg(e,t){const n=new Map;return e.forEach(r=>{n.set(ft(r),r)}),t.forEach(r=>{n.set(ft(r),r)}),Array.from(n.values()).sort((r,i)=>new Date(i.created_at||0).getTime()-new Date(r.created_at||0).getTime())}function _A(e,t){const n=new Set(t.map(ft));return Kg(e.filter(r=>!n.has(ft(r))),t)}var qO=560;function wA(){const e=document.documentElement,t=Math.max(e.scrollHeight,document.body.scrollHeight);return window.innerHeight+window.scrollY>=t-560}function Ka(e,t,n){const r=e.pagination?.has_more;return typeof r=="boolean"?r:t>=n}function Va(e,t){const n=e.pagination?.next_offset;return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:t}function SA(e,t){const n=new Set(t.map(ft));return e.filter(r=>!n.has(ft(r))).length}var[Wa,zO]=st("Tooltip",[_n]),qa=_n(),Vg="TooltipProvider",CA=700,Ol="tooltip.open",[TA,jl]=Wa(Vg),Wg=e=>{const{__scopeTooltip:t,delayDuration:n=CA,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:o}=e,s=F(!0),c=F(!1),l=F(0);return K(()=>{const d=l.current;return()=>window.clearTimeout(d)},[]),a(TA,{scope:t,isOpenDelayedRef:s,delayDuration:n,onOpen:re(()=>{window.clearTimeout(l.current),s.current=!1},[]),onClose:re(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.current=!0,r)},[r]),isPointerInTransitRef:c,onPointerInTransitChange:re(d=>{c.current=d},[]),disableHoverableContent:i,children:o})};Wg.displayName=Vg;var Bi="Tooltip",[kA,Ui]=Wa(Bi),qg=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:o,disableHoverableContent:s,delayDuration:c}=e,l=jl(Bi,e.__scopeTooltip),d=qa(t),[u,p]=I(null),m=ct(),f=F(0),y=s??l.disableHoverableContent,h=c??l.delayDuration,g=F(!1),[_,w]=wt({prop:r,defaultProp:i??!1,onChange:E=>{E?(l.onOpen(),document.dispatchEvent(new CustomEvent(Ol))):l.onClose(),o?.(E)},caller:Bi}),S=Pe(()=>_?g.current?"delayed-open":"instant-open":"closed",[_]),T=re(()=>{window.clearTimeout(f.current),f.current=0,g.current=!1,w(!0)},[w]),k=re(()=>{window.clearTimeout(f.current),f.current=0,w(!1)},[w]),P=re(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>{g.current=!0,w(!0),f.current=0},h)},[h,w]);return K(()=>()=>{f.current&&(window.clearTimeout(f.current),f.current=0)},[]),a($i,{...d,children:a(kA,{scope:t,contentId:m,open:_,stateAttribute:S,trigger:u,onTriggerChange:p,onTriggerEnter:re(()=>{l.isOpenDelayedRef.current?P():T()},[l.isOpenDelayedRef,P,T]),onTriggerLeave:re(()=>{y?k():(window.clearTimeout(f.current),f.current=0)},[k,y]),onOpen:T,onClose:k,disableHoverableContent:y,children:n})})};qg.displayName=Bi;var Fl="TooltipTrigger",zg=j((e,t)=>{const{__scopeTooltip:n,...r}=e,i=Ui(Fl,n),o=jl(Fl,n),s=qa(n),c=_e(t,F(null),i.onTriggerChange),l=F(!1),d=F(!1),u=re(()=>l.current=!1,[]);return K(()=>()=>document.removeEventListener("pointerup",u),[u]),a(Mi,{asChild:!0,...s,children:a(se.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:c,onPointerMove:z(e.onPointerMove,p=>{p.pointerType!=="touch"&&!d.current&&!o.isPointerInTransitRef.current&&(i.onTriggerEnter(),d.current=!0)}),onPointerLeave:z(e.onPointerLeave,()=>{i.onTriggerLeave(),d.current=!1}),onPointerDown:z(e.onPointerDown,()=>{i.open&&i.onClose(),l.current=!0,document.addEventListener("pointerup",u,{once:!0})}),onFocus:z(e.onFocus,()=>{l.current||i.onOpen()}),onBlur:z(e.onBlur,i.onClose),onClick:z(e.onClick,i.onClose)})})});zg.displayName=Fl;var Bl="TooltipPortal",[NA,xA]=Wa(Bl,{forceMount:void 0}),Jg=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,o=Ui(Bl,t);return a(NA,{scope:t,forceMount:n,children:a(rt,{present:n||o.open,children:a(Hn,{asChild:!0,container:i,children:r})})})};Jg.displayName=Bl;var Vr="TooltipContent",Yg=j((e,t)=>{const n=xA(Vr,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...o}=e,s=Ui(Vr,e.__scopeTooltip);return a(rt,{present:r||s.open,children:s.disableHoverableContent?a(Xg,{side:i,...o,ref:t}):a(PA,{side:i,...o,ref:t})})}),PA=j((e,t)=>{const n=Ui(Vr,e.__scopeTooltip),r=jl(Vr,e.__scopeTooltip),i=F(null),o=_e(t,i),[s,c]=I(null),{trigger:l,onClose:d}=n,u=i.current,{onPointerInTransitChange:p}=r,m=re(()=>{c(null),p(!1)},[p]),f=re((y,h)=>{const g=y.currentTarget,_={x:y.clientX,y:y.clientY},w=DA(_,RA(_,g.getBoundingClientRect())),S=LA(h.getBoundingClientRect());c(MA([...w,...S])),p(!0)},[p]);return K(()=>()=>m(),[m]),K(()=>{if(l&&u){const y=g=>f(g,u),h=g=>f(g,l);return l.addEventListener("pointerleave",y),u.addEventListener("pointerleave",h),()=>{l.removeEventListener("pointerleave",y),u.removeEventListener("pointerleave",h)}}},[l,u,f,m]),K(()=>{if(s){const y=h=>{const g=h.target,_={x:h.clientX,y:h.clientY},w=l?.contains(g)||u?.contains(g),S=!$A(_,s);w?m():S&&(m(),d())};return document.addEventListener("pointermove",y),()=>document.removeEventListener("pointermove",y)}},[l,u,s,d,m]),a(Xg,{...e,ref:o})}),[AA,EA]=Wa(Bi,{isInside:!1}),IA=Qw("TooltipContent"),Xg=j((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:o,onPointerDownOutside:s,...c}=e,l=Ui(Vr,n),d=qa(n),{onClose:u}=l;return K(()=>(document.addEventListener(Ol,u),()=>document.removeEventListener(Ol,u)),[u]),K(()=>{if(l.trigger){const p=m=>{m.target?.contains(l.trigger)&&u()};return window.addEventListener("scroll",p,{capture:!0}),()=>window.removeEventListener("scroll",p,{capture:!0})}},[l.trigger,u]),a(Gn,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:p=>p.preventDefault(),onDismiss:u,children:a(Pa,{"data-state":l.stateAttribute,...d,...c,ref:t,style:{...c.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(IA,{children:r}),a(AA,{scope:n,isInside:!0,children:a(hT,{id:l.contentId,role:"tooltip",children:i||r})})]})})});Yg.displayName=Vr;var Zg="TooltipArrow",Qg=j((e,t)=>{const{__scopeTooltip:n,...r}=e,i=qa(n);return EA(Zg,n).isInside?null:a(Aa,{...i,...r,ref:t})});Qg.displayName=Zg;function RA(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")}}function DA(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});break}return r}function LA(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}]}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,m=l.y;u>r!=m>r&&n<(p-d)*(r-u)/(m-u)+d&&(i=!i)}return i}function MA(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),OA(t)}function OA(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)}var jA=Wg,FA=qg,BA=zg,UA=Jg,GA=Yg,HA=Qg;function Ul({children:e,delayDuration:t=400,skipDelayDuration:n=300}){return a(jA,{delayDuration:t,skipDelayDuration:n,children:e})}function za({children:e,label:t,side:n="top",align:r="center",sideOffset:i=6,asChild:o=!0,disabled:s=!1}){return s?a(te,{children:e}):a(FA,{children:[a(BA,{asChild:o,children:e}),a(UA,{children:a(GA,{align:r,className:"tooltip-content",side:n,sideOffset:i,children:[t,a(HA,{className:"tooltip-arrow"})]})})]})}function KA(e){e.dataset.feedRenderRoot="preact"}function VA(){const e=document.getElementById("tab-feed");e&&(e.dataset.feedRenderBoundary="preact-hybrid")}function WA(e,t){KA(e),Be(v(Ul,null,t),e)}function qA(e){return e.hasInspectorOverride?e.inspectorQuery:e.feedQuery}function zA(e){return e.split(/\n|,/).map(t=>t.trim()).filter(Boolean)}function Gl(e){return JSON.stringify([e.project,e.query.trim(),e.workingSetFiles])}function JA(e){const t=Ha(e?.metadata_json),n=String(e?.subtitle||t?.subtitle||"").trim(),r=String(e?.narrative||t?.narrative||e?.body_text||"").trim(),i=It(n),o=It(r),s=!!r&&o!==i,c=Ga(e?.facts||t?.facts||[]),l=c.length?c:hA(r||n),d=l.length?l:gA(r||n);return{summary:n,narrative:r,facts:d,hasSummary:!!n,hasFacts:d.length>0,hasNarrative:s}}function YA(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 XA(e){return e.hasSummary?"summary":e.hasFacts?"facts":"narrative"}function ZA(e,t){return e==="facts"?!1:e==="summary"?t.summary.length>260:t.narrative.length>320}function QA(e){return e==="summary"?["clamp","clamp-3"]:["clamp","clamp-5"]}function eE(e,t){const n=b.feedTypeFilter==="observations"?" · observations":b.feedTypeFilter==="summaries"?" · session summaries":"",r=vA(b.feedScopeFilter),i=!b.feedQuery.trim()&&b.lastFeedFilteredCount?` · ${b.lastFeedFilteredCount} observations filtered`:"";return`${e} items${n}${r}${b.feedQuery.trim()?` · matching "${b.feedQuery.trim()}"`:""}${i}${t?" · scroll for more":""}`}function Ja({label:e,candidates:t}){return t.length===0?null:v("div",{className:"trace-group"},v("div",{className:"section-meta"},e),v("div",{className:"feed-list"},t.map(n=>v("div",{className:"feed-card",key:`${e}:${n.id}`},v("div",{className:"feed-card-header"},[v("div",{className:"feed-card-title"},`${n.rank}. ${n.title}`),v("div",{className:"feed-card-meta"},`#${n.id} · ${n.kind}${n.section?` · ${n.section}`:""}`)]),v("div",{className:"feed-card-body"},[v("div",null,n.preview||"No preview available."),n.reasons.length?v("div",{className:"section-meta"},`Reasons: ${n.reasons.join(", ")}`):null])))))}function tE({open:e}){const[t,n]=I(()=>String(b.feedQuery||"")),[r,i]=I(!1),[o,s]=I(!1),[c,l]=I(""),[d,u]=I(!1),[p,m]=I(""),[f,y]=I(""),[h,g]=I(null),_=F(0),w=String(b.feedQuery||""),S=String(t||"").trim(),T=b.currentProject||null,k=zA(c),P=Gl({project:T,query:S,workingSetFiles:k}),E=h&&Gl({project:h.inputs.project,query:h.inputs.query,workingSetFiles:h.inputs.working_set_files})===P?h:null,M=p&&f===P?p:"";K(()=>{_.current+=1,u(!1),m(""),y(""),g(L=>!L||L.inputs.query!==S||L.inputs.project!==T?null:L)},[P]),K(()=>{e&&!r&&(n(qA({feedQuery:w,hasInspectorOverride:o,inspectorQuery:t})),i(!0))},[w,o,r,t,e]);const U=async()=>{const L=S,J=T,H=k,x=Gl({project:J,query:L,workingSetFiles:H}),R=_.current+1;if(_.current=R,!L){m("Enter a query to inspect."),y(x),g(null);return}u(!0),m(""),y("");try{const B=await U_({context:L,project:J,working_set_files:H});if(R!==_.current)return;g(B)}catch(B){if(R!==_.current)return;m(B instanceof Error?B.message:String(B)),y(x),g(null)}finally{R===_.current&&u(!1)}},N=E?.retrieval.candidates.filter(L=>L.disposition==="selected")||[],G=E?.retrieval.candidates.filter(L=>L.disposition==="dropped")||[],A=E?.retrieval.candidates.filter(L=>L.disposition==="deduped")||[],$=E?.retrieval.candidates.filter(L=>L.disposition==="trimmed")||[];return e?v("div",{className:"feed-inspector"},v("div",{className:"feed-card",id:"contextInspectorPanel",style:"margin-top:12px;"},[v("div",{className:"feed-card-header"},[v("div",{className:"feed-card-title"},"Context Inspector"),v("div",{className:"feed-card-meta"},o?"Tracing an inspector-specific query":"Seeded from the feed search on first open")]),v("div",{className:"feed-card-body"},[v("input",{className:"feed-search",onInput:L=>{n(String(L.currentTarget.value||"")),s(!0),g(null),m(""),y("")},placeholder:"Trace a pack query…",value:t}),v("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."),v("textarea",{className:"feed-inspector-files",onInput:L=>l(String(L.currentTarget.value||"")),placeholder:"Optional working-set files, one per line",rows:3,value:c}),v("div",{style:"display:flex; gap:8px; margin-top:8px; align-items:center;"},v("button",{className:"toggle-button active",disabled:d,onClick:()=>{U()},type:"button"},d?"Tracing…":"Run trace"),E?v("span",{className:"section-meta"},`mode=${E.mode.selected} · candidates=${E.retrieval.candidate_count} · tokens=${E.output.estimated_tokens}`):null),h&&!E?v("div",{className:"section-meta",style:"margin-top:8px;"},"Trace inputs changed. Run trace again for the current query, project, and working set."):null,M?v("div",{className:"section-meta",style:"margin-top:8px; color:#d96c6c;"},M):null]),E?v(te,null,[v(Ja,{label:"Selected",candidates:N}),v(Ja,{label:"Dropped",candidates:G}),v(Ja,{label:"Deduped",candidates:A}),v(Ja,{label:"Trimmed",candidates:$}),v("div",{className:"feed-card-body"},[E.assembly.collapsed_groups.length?v("div",{className:"section-meta"},`Collapsed duplicates: ${E.assembly.collapsed_groups.map(L=>`kept #${L.kept} from [${L.dropped.join(", ")}]`).join(" · ")}`):null,E.assembly.trim_reasons.length?v("div",{className:"section-meta"},`Trim reasons: ${E.assembly.trim_reasons.join(", ")}`):null,v("div",{className:"section-meta"},"Final pack"),v("pre",{style:"white-space:pre-wrap; overflow:auto;"},E.output.pack_text)])]):null])):null}var nE={kind:"kind-chip",provenance:"provenance-chip",tag:"tag-chip",badge:"badge",scope:"peer-scope-chip"};function Hl({variant:e,tone:t,title:n,children:r}){const i=nE[e];return a("span",{className:t?`${i} ${t}`:i,title:n,children:r})}function ev(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 rE(e){if(Array.isArray(e))return e}function iE(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 oE(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
47
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function aE(e,t){return rE(e)||iE(e,t)||sE(e,t)||oE()}function sE(e,t){if(e){if(typeof e=="string")return ev(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)?ev(e,t):void 0}}var tv=Object.entries,nv=Object.setPrototypeOf,cE=Object.isFrozen,lE=Object.getPrototypeOf,dE=Object.getOwnPropertyDescriptor,Ye=Object.freeze,Xe=Object.seal,Wr=Object.create,rv=typeof Reflect<"u"&&Reflect,Kl=rv.apply,Vl=rv.construct;Ye||(Ye=function(t){return t}),Xe||(Xe=function(t){return t}),Kl||(Kl=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)}),Vl||(Vl=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 Gi=He(Array.prototype.forEach),uE=He(Array.prototype.lastIndexOf),iv=He(Array.prototype.pop),qr=He(Array.prototype.push),pE=He(Array.prototype.splice),Nn=Array.isArray,Hi=He(String.prototype.toLowerCase),Wl=He(String.prototype.toString),ov=He(String.prototype.match),Ki=He(String.prototype.replace),av=He(String.prototype.indexOf),mE=He(String.prototype.trim),fE=He(Number.prototype.toString),hE=He(Boolean.prototype.toString),sv=typeof BigInt>"u"?null:He(BigInt.prototype.toString),cv=typeof Symbol>"u"?null:He(Symbol.prototype.toString),qe=He(Object.prototype.hasOwnProperty),Vi=He(Object.prototype.toString),Ze=He(RegExp.prototype.test),ir=gE(TypeError);function He(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 Kl(e,t,r)}}function gE(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return Vl(e,n)}}function Te(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Hi;if(nv&&nv(e,null),!Nn(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i=="string"){const o=n(i);o!==i&&(cE(t)||(t[r]=o),i=o)}e[i]=!0}return e}function vE(e){for(let t=0;t<e.length;t++)qe(e,t)||(e[t]=null);return e}function ut(e){const t=Wr(null);for(const r of tv(e)){var n=aE(r,2);const i=n[0],o=n[1];qe(e,i)&&(Nn(o)?t[i]=vE(o):o&&typeof o=="object"&&o.constructor===Object?t[i]=ut(o):t[i]=o)}return t}function yE(e){switch(typeof e){case"string":return e;case"number":return fE(e);case"boolean":return hE(e);case"bigint":return sv?sv(e):"0";case"symbol":return cv?cv(e):"Symbol()";case"undefined":return Vi(e);case"function":case"object":{if(e===null)return Vi(e);const t=e,n=Vt(t,"toString");if(typeof n=="function"){const r=n(t);return typeof r=="string"?r:Vi(r)}return Vi(e)}default:return Vi(e)}}function Vt(e,t){for(;e!==null;){const r=dE(e,t);if(r){if(r.get)return He(r.get);if(typeof r.value=="function")return He(r.value)}e=lE(e)}function n(){return null}return n}function bE(e){try{return Ze(e,""),!0}catch{return!1}}var lv=Ye(["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"]),ql=Ye(["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"]),zl=Ye(["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"]),_E=Ye(["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"]),Jl=Ye(["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"]),wE=Ye(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),dv=Ye(["#text"]),uv=Ye(["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"]),Yl=Ye(["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","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","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-rendering","textlength","type","u1","u2","unicode","values","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"]),pv=Ye(["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"]),Ya=Ye(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),SE=Xe(/{{[\w\W]*|^[\w\W]*}}/g),CE=Xe(/<%[\w\W]*|^[\w\W]*%>/g),TE=Xe(/\${[\w\W]*/g),kE=Xe(/^data-[\-\w.\u00B7-\uFFFF]+$/),NE=Xe(/^aria-[\-\w]+$/),mv=Xe(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),xE=Xe(/^(?:\w+script|data):/i),PE=Xe(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),AE=Xe(/^html$/i),EE=Xe(/^[a-z][.\w]*(-[.\w]+)+$/i),fv=Xe(/<[/\w!]/g),IE=Xe(/<[/\w]/g),RE=Xe(/<\/no(script|embed|frames)/i),DE=Xe(/\/>/i),Wt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},LE=function(){return typeof window>"u"?null:window},$E=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}},hv=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},xn=function(t,n,r,i){return qe(t,n)&&Nn(t[n])?Te(i.base?ut(i.base):{},t[n],i.transform):r};function gv(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:LE();const t=Q=>gv(Q);if(t.version="3.4.11",t.removed=[],!e||!e.document||e.document.nodeType!==Wt.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,m=Vt(p,"cloneNode"),f=Vt(p,"remove"),y=Vt(p,"nextSibling"),h=Vt(p,"childNodes"),g=Vt(p,"parentNode"),_=Vt(p,"shadowRoot"),w=Vt(p,"attributes"),S=s&&s.prototype?Vt(s.prototype,"nodeType"):null,T=s&&s.prototype?Vt(s.prototype,"nodeName"):null;if(typeof o=="function"){const Q=n.createElement("template");Q.content&&Q.content.ownerDocument&&(n=Q.content.ownerDocument)}let k,P="",E,M=!1,U=0;const N=function(){if(U>0)throw ir('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.')},G=function(C){N(),U++;try{return k.createHTML(C)}finally{U--}},A=function(C){N(),U++;try{return k.createScriptURL(C)}finally{U--}},$=function(){return M||(E=$E(u,i),M=!0),E},L=n,J=L.implementation,H=L.createNodeIterator,x=L.createDocumentFragment,R=L.getElementsByTagName,B=r.importNode;let V=hv();t.isSupported=typeof tv=="function"&&typeof g=="function"&&J&&J.createHTMLDocument!==void 0;const he=SE,ue=CE,ce=TE,be=kE,Y=NE,ge=xE,Z=PE,Ce=EE;let le=mv,ee=null;const xe=Te({},[...lv,...ql,...zl,...Jl,...dv]);let pe=null;const W=Te({},[...uv,...Yl,...pv,...Ya]);let oe=Object.seal(Wr(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}})),Ve=null,Me=null;const tt=Object.seal(Wr(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let un=!0,Lt=!0,kt=!1,$t=!0,nt=!1,Mt=!0,me=!1,ae=!1,Ge=null,$n=null,wo=!1,pn=!1,br=!1,Mn=!1,ht=!0,On=!1;const r_="user-content-";let mu=!0,fu=!1,ii={},Yt=null;const hu=Te({},["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 i_=null;const o_=Te({},["audio","video","img","source","image","track"]);let gu=null;const a_=Te({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ds="http://www.w3.org/1998/Math/MathML",Ls="http://www.w3.org/2000/svg",Xt="http://www.w3.org/1999/xhtml";let oi=Xt,vu=!1,yu=null;const vO=Te({},[Ds,Ls,Xt],Wl),s_=Ye(["mi","mo","mn","ms","mtext"]);let bu=Te({},s_);const c_=Ye(["annotation-xml"]);let _u=Te({},c_);const yO=Te({},["title","style","font","a","script"]);let So=null;const bO=["application/xhtml+xml","text/html"],_O="text/html";let Ue=null,ai=null;const wO=n.createElement("form"),l_=function(C){return C instanceof RegExp||C instanceof Function},wu=function(){let C=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(ai&&ai===C)return;(!C||typeof C!="object")&&(C={}),C=ut(C),So=bO.indexOf(C.PARSER_MEDIA_TYPE)===-1?_O:C.PARSER_MEDIA_TYPE,Ue=So==="application/xhtml+xml"?Wl:Hi,ee=xn(C,"ALLOWED_TAGS",xe,{transform:Ue}),pe=xn(C,"ALLOWED_ATTR",W,{transform:Ue}),yu=xn(C,"ALLOWED_NAMESPACES",vO,{transform:Wl}),gu=xn(C,"ADD_URI_SAFE_ATTR",a_,{transform:Ue,base:a_}),i_=xn(C,"ADD_DATA_URI_TAGS",o_,{transform:Ue,base:o_}),Yt=xn(C,"FORBID_CONTENTS",hu,{transform:Ue}),Ve=xn(C,"FORBID_TAGS",ut({}),{transform:Ue}),Me=xn(C,"FORBID_ATTR",ut({}),{transform:Ue}),ii=qe(C,"USE_PROFILES")?C.USE_PROFILES&&typeof C.USE_PROFILES=="object"?ut(C.USE_PROFILES):C.USE_PROFILES:!1,un=C.ALLOW_ARIA_ATTR!==!1,Lt=C.ALLOW_DATA_ATTR!==!1,kt=C.ALLOW_UNKNOWN_PROTOCOLS||!1,$t=C.ALLOW_SELF_CLOSE_IN_ATTR!==!1,nt=C.SAFE_FOR_TEMPLATES||!1,Mt=C.SAFE_FOR_XML!==!1,me=C.WHOLE_DOCUMENT||!1,pn=C.RETURN_DOM||!1,br=C.RETURN_DOM_FRAGMENT||!1,Mn=C.RETURN_TRUSTED_TYPE||!1,wo=C.FORCE_BODY||!1,ht=C.SANITIZE_DOM!==!1,On=C.SANITIZE_NAMED_PROPS||!1,mu=C.KEEP_CONTENT!==!1,fu=C.IN_PLACE||!1,le=bE(C.ALLOWED_URI_REGEXP)?C.ALLOWED_URI_REGEXP:mv,oi=typeof C.NAMESPACE=="string"?C.NAMESPACE:Xt,bu=qe(C,"MATHML_TEXT_INTEGRATION_POINTS")&&C.MATHML_TEXT_INTEGRATION_POINTS&&typeof C.MATHML_TEXT_INTEGRATION_POINTS=="object"?ut(C.MATHML_TEXT_INTEGRATION_POINTS):Te({},s_),_u=qe(C,"HTML_INTEGRATION_POINTS")&&C.HTML_INTEGRATION_POINTS&&typeof C.HTML_INTEGRATION_POINTS=="object"?ut(C.HTML_INTEGRATION_POINTS):Te({},c_);const D=qe(C,"CUSTOM_ELEMENT_HANDLING")&&C.CUSTOM_ELEMENT_HANDLING&&typeof C.CUSTOM_ELEMENT_HANDLING=="object"?ut(C.CUSTOM_ELEMENT_HANDLING):Wr(null);if(oe=Wr(null),qe(D,"tagNameCheck")&&l_(D.tagNameCheck)&&(oe.tagNameCheck=D.tagNameCheck),qe(D,"attributeNameCheck")&&l_(D.attributeNameCheck)&&(oe.attributeNameCheck=D.attributeNameCheck),qe(D,"allowCustomizedBuiltInElements")&&typeof D.allowCustomizedBuiltInElements=="boolean"&&(oe.allowCustomizedBuiltInElements=D.allowCustomizedBuiltInElements),Xe(oe),nt&&(Lt=!1),br&&(pn=!0),ii&&(ee=Te({},dv),pe=Wr(null),ii.html===!0&&(Te(ee,lv),Te(pe,uv)),ii.svg===!0&&(Te(ee,ql),Te(pe,Yl),Te(pe,Ya)),ii.svgFilters===!0&&(Te(ee,zl),Te(pe,Yl),Te(pe,Ya)),ii.mathMl===!0&&(Te(ee,Jl),Te(pe,pv),Te(pe,Ya))),tt.tagCheck=null,tt.attributeCheck=null,qe(C,"ADD_TAGS")&&(typeof C.ADD_TAGS=="function"?tt.tagCheck=C.ADD_TAGS:Nn(C.ADD_TAGS)&&(ee===xe&&(ee=ut(ee)),Te(ee,C.ADD_TAGS,Ue))),qe(C,"ADD_ATTR")&&(typeof C.ADD_ATTR=="function"?tt.attributeCheck=C.ADD_ATTR:Nn(C.ADD_ATTR)&&(pe===W&&(pe=ut(pe)),Te(pe,C.ADD_ATTR,Ue))),qe(C,"ADD_URI_SAFE_ATTR")&&Nn(C.ADD_URI_SAFE_ATTR)&&Te(gu,C.ADD_URI_SAFE_ATTR,Ue),qe(C,"FORBID_CONTENTS")&&Nn(C.FORBID_CONTENTS)&&(Yt===hu&&(Yt=ut(Yt)),Te(Yt,C.FORBID_CONTENTS,Ue)),qe(C,"ADD_FORBID_CONTENTS")&&Nn(C.ADD_FORBID_CONTENTS)&&(Yt===hu&&(Yt=ut(Yt)),Te(Yt,C.ADD_FORBID_CONTENTS,Ue)),mu&&(ee["#text"]=!0),me&&Te(ee,["html","head","body"]),ee.table&&(Te(ee,["tbody"]),delete Ve.tbody),C.TRUSTED_TYPES_POLICY){if(typeof C.TRUSTED_TYPES_POLICY.createHTML!="function")throw ir('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof C.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ir('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const X=k;k=C.TRUSTED_TYPES_POLICY;try{P=G("")}catch(ie){throw k=X,ie}}else C.TRUSTED_TYPES_POLICY===null?(k=void 0,P=""):(k===void 0&&(k=$()),k&&typeof P=="string"&&(P=G("")));Ye&&Ye(C),ai=C},d_=Te({},[...ql,...zl,..._E]),u_=Te({},[...Jl,...wE]),SO=function(C,D,X){return D.namespaceURI===Xt?C==="svg":D.namespaceURI===Ds?C==="svg"&&(X==="annotation-xml"||bu[X]):!!d_[C]},CO=function(C,D,X){return D.namespaceURI===Xt?C==="math":D.namespaceURI===Ls?C==="math"&&_u[X]:!!u_[C]},TO=function(C,D,X){return D.namespaceURI===Ls&&!_u[X]||D.namespaceURI===Ds&&!bu[X]?!1:!u_[C]&&(yO[C]||!d_[C])},kO=function(C){let D=g(C);(!D||!D.tagName)&&(D={namespaceURI:oi,tagName:"template"});const X=Hi(C.tagName),ie=Hi(D.tagName);return yu[C.namespaceURI]?C.namespaceURI===Ls?SO(X,D,ie):C.namespaceURI===Ds?CO(X,D,ie):C.namespaceURI===Xt?TO(X,D,ie):!!(So==="application/xhtml+xml"&&yu[C.namespaceURI]):!1},jn=function(C){qr(t.removed,{element:C});try{g(C).removeChild(C)}catch{if(f(C),!g(C))throw ir("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},p_=function(C){const D=h(C);if(D){const ie=[];Gi(D,Se=>{qr(ie,Se)}),Gi(ie,Se=>{try{f(Se)}catch{}})}const X=w(C);if(X)for(let ie=X.length-1;ie>=0;--ie){const Se=X[ie],Ie=Se&&Se.name;if(typeof Ie=="string")try{C.removeAttribute(Ie)}catch{}}},_r=function(C,D){try{qr(t.removed,{attribute:D.getAttributeNode(C),from:D})}catch{qr(t.removed,{attribute:null,from:D})}if(D.removeAttribute(C),C==="is")if(pn||br)try{jn(D)}catch{}else try{D.setAttribute(C,"")}catch{}},NO=function(C){const D=w(C);if(D)for(let X=D.length-1;X>=0;--X){const ie=D[X],Se=ie&&ie.name;if(!(typeof Se!="string"||pe[Ue(Se)]))try{C.removeAttribute(Se)}catch{}}},xO=function(C){const D=[C];for(;D.length>0;){const X=D.pop();(S?S(X):X.nodeType)===Wt.element&&NO(X);const ie=h(X);if(ie)for(let Se=ie.length-1;Se>=0;--Se)D.push(ie[Se])}},m_=function(C){let D=null,X=null;if(wo)C="<remove></remove>"+C;else{const Ie=ov(C,/^[\r\n\t ]+/);X=Ie&&Ie[0]}So==="application/xhtml+xml"&&oi===Xt&&(C='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+C+"</body></html>");const ie=k?G(C):C;if(oi===Xt)try{D=new d().parseFromString(ie,So)}catch{}if(!D||!D.documentElement){D=J.createDocument(oi,"template",null);try{D.documentElement.innerHTML=vu?P:ie}catch{}}const Se=D.body||D.documentElement;return C&&X&&Se.insertBefore(n.createTextNode(X),Se.childNodes[0]||null),oi===Xt?R.call(D,me?"html":"body")[0]:me?D.documentElement:Se},f_=function(C){return H.call(C.ownerDocument||C,C,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},$s=function(C){return C=Ki(C,he," "),C=Ki(C,ue," "),C=Ki(C,ce," "),C},Su=function(C){var D;C.normalize();const X=H.call(C.ownerDocument||C,C,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let ie=X.nextNode();for(;ie;)ie.data=$s(ie.data),ie=X.nextNode();const Se=(D=C.querySelectorAll)===null||D===void 0?void 0:D.call(C,"template");Se&&Gi(Se,Ie=>{si(Ie.content)&&Su(Ie.content)})},Ms=function(C){const D=T?T(C):null;return typeof D!="string"||Ue(D)!=="form"?!1:typeof C.nodeName!="string"||typeof C.textContent!="string"||typeof C.removeChild!="function"||C.attributes!==w(C)||typeof C.removeAttribute!="function"||typeof C.setAttribute!="function"||typeof C.namespaceURI!="string"||typeof C.insertBefore!="function"||typeof C.hasChildNodes!="function"||C.nodeType!==S(C)||C.childNodes!==h(C)},si=function(C){if(!S||typeof C!="object"||C===null)return!1;try{return S(C)===Wt.documentFragment}catch{return!1}},Co=function(C){if(!S||typeof C!="object"||C===null)return!1;try{return typeof S(C)=="number"}catch{return!1}};function mn(Q,C,D){Q.length!==0&&Gi(Q,X=>{X.call(t,C,D,ai)})}const PO=function(C,D){return!!(Mt&&C.hasChildNodes()&&!Co(C.firstElementChild)&&Ze(fv,C.textContent)&&Ze(fv,C.innerHTML)||Mt&&C.namespaceURI===Xt&&D==="style"&&Co(C.firstElementChild)||C.nodeType===Wt.processingInstruction||Mt&&C.nodeType===Wt.comment&&Ze(IE,C.data))},AO=function(C,D){if(!Ve[D]&&v_(D)&&(oe.tagNameCheck instanceof RegExp&&Ze(oe.tagNameCheck,D)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(D)))return!1;if(mu&&!Yt[D]){const X=g(C),ie=h(C);if(ie&&X){const Se=ie.length;for(let Ie=Se-1;Ie>=0;--Ie){const Oe=fu?ie[Ie]:m(ie[Ie],!0);X.insertBefore(Oe,y(C))}}}return jn(C),!0},h_=function(C){if(mn(V.beforeSanitizeElements,C,null),Ms(C))return jn(C),!0;const D=Ue(T?T(C):C.nodeName);if(mn(V.uponSanitizeElement,C,{tagName:D,allowedTags:ee}),PO(C,D))return jn(C),!0;if(Ve[D]||!(tt.tagCheck instanceof Function&&tt.tagCheck(D))&&!ee[D])return AO(C,D);if((S?S(C):C.nodeType)===Wt.element&&!kO(C)||(D==="noscript"||D==="noembed"||D==="noframes")&&Ze(RE,C.innerHTML))return jn(C),!0;if(nt&&C.nodeType===Wt.text){const X=$s(C.textContent);C.textContent!==X&&(qr(t.removed,{element:C.cloneNode()}),C.textContent=X)}return mn(V.afterSanitizeElements,C,null),!1},g_=function(C,D,X){if(Me[D]||ht&&(D==="id"||D==="name")&&(X in n||X in wO))return!1;const ie=pe[D]||tt.attributeCheck instanceof Function&&tt.attributeCheck(D,C);if(!(Lt&&Ze(be,D))){if(!(un&&Ze(Y,D))){if(ie){if(!gu[D]){if(!Ze(le,Ki(X,Z,""))){if(!((D==="src"||D==="xlink:href"||D==="href")&&C!=="script"&&av(X,"data:")===0&&i_[C])){if(!(kt&&!Ze(ge,Ki(X,Z,"")))){if(X)return!1}}}}}else if(!(v_(C)&&(oe.tagNameCheck instanceof RegExp&&Ze(oe.tagNameCheck,C)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(C))&&(oe.attributeNameCheck instanceof RegExp&&Ze(oe.attributeNameCheck,D)||oe.attributeNameCheck instanceof Function&&oe.attributeNameCheck(D,C))||D==="is"&&oe.allowCustomizedBuiltInElements&&(oe.tagNameCheck instanceof RegExp&&Ze(oe.tagNameCheck,X)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(X))))return!1}}return!0},EO=Te({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),v_=function(C){return!EO[Hi(C)]&&Ze(Ce,C)},IO=function(C,D,X,ie){if(k&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!X)switch(u.getAttributeType(C,D)){case"TrustedHTML":return G(ie);case"TrustedScriptURL":return A(ie)}return ie},RO=function(C,D,X,ie){try{X?C.setAttributeNS(X,D,ie):C.setAttribute(D,ie),Ms(C)?jn(C):iv(t.removed)}catch{_r(D,C)}},y_=function(C){mn(V.beforeSanitizeAttributes,C,null);const D=C.attributes;if(!D||Ms(C))return;const X={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:pe,forceKeepAttr:void 0};let ie=D.length;const Se=Ue(C.nodeName);for(;ie--;){const Ie=D[ie],Oe=Ie.name,Nt=Ie.namespaceURI,fn=Ie.value,Ot=Ue(Oe),Tu=fn;let mt=Oe==="value"?Tu:mE(Tu);if(X.attrName=Ot,X.attrValue=mt,X.keepAttr=!0,X.forceKeepAttr=void 0,mn(V.uponSanitizeAttribute,C,X),mt=X.attrValue,On&&(Ot==="id"||Ot==="name")&&av(mt,r_)!==0&&(_r(Oe,C),mt=r_+mt),Mt&&Ze(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,mt)){_r(Oe,C);continue}if(Ot==="attributename"&&ov(mt,"href")){_r(Oe,C);continue}if(!X.forceKeepAttr){if(!X.keepAttr){_r(Oe,C);continue}if(!$t&&Ze(DE,mt)){_r(Oe,C);continue}if(nt&&(mt=$s(mt)),!g_(Se,Ot,mt)){_r(Oe,C);continue}mt=IO(Se,Ot,Nt,mt),mt!==Tu&&RO(C,Oe,Nt,mt)}}mn(V.afterSanitizeAttributes,C,null)},Os=function(C){let D=null;const X=f_(C);for(mn(V.beforeSanitizeShadowDOM,C,null);D=X.nextNode();)if(mn(V.uponSanitizeShadowNode,D,null),h_(D),y_(D),si(D.content)&&Os(D.content),(S?S(D):D.nodeType)===Wt.element){const ie=_(D);si(ie)&&(Cu(ie),Os(ie))}mn(V.afterSanitizeShadowDOM,C,null)},Cu=function(C){const D=[{node:C,shadow:null}];for(;D.length>0;){const X=D.pop();if(X.shadow){Os(X.shadow);continue}const ie=X.node,Se=(S?S(ie):ie.nodeType)===Wt.element,Ie=h(ie);if(Ie)for(let Oe=Ie.length-1;Oe>=0;--Oe)D.push({node:Ie[Oe],shadow:null});if(Se){const Oe=T?T(ie):null;if(typeof Oe=="string"&&Ue(Oe)==="template"){const Nt=ie.content;si(Nt)&&D.push({node:Nt,shadow:null})}}if(Se){const Oe=_(ie);si(Oe)&&D.push({node:null,shadow:Oe},{node:Oe,shadow:null})}}};return t.sanitize=function(Q){let C=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},D=null,X=null,ie=null,Se=null;if(vu=!Q,vu&&(Q="<!-->"),typeof Q!="string"&&!Co(Q)&&(Q=yE(Q),typeof Q!="string"))throw ir("dirty is not a string, aborting");if(!t.isSupported)return Q;ae?(ee=Ge,pe=$n):wu(C),(V.uponSanitizeElement.length>0||V.uponSanitizeAttribute.length>0)&&(ee=ut(ee)),V.uponSanitizeAttribute.length>0&&(pe=ut(pe)),t.removed=[];const Ie=fu&&typeof Q!="string"&&Co(Q);if(Ie){const fn=T?T(Q):Q.nodeName;if(typeof fn=="string"){const Ot=Ue(fn);if(!ee[Ot]||Ve[Ot])throw ir("root node is forbidden and cannot be sanitized in-place")}if(Ms(Q))throw ir("root node is clobbered and cannot be sanitized in-place");try{Cu(Q)}catch(Ot){throw p_(Q),Ot}}else if(Co(Q))D=m_("<!---->"),X=D.ownerDocument.importNode(Q,!0),X.nodeType===Wt.element&&X.nodeName==="BODY"||X.nodeName==="HTML"?D=X:D.appendChild(X),Cu(X);else{if(!pn&&!nt&&!me&&Q.indexOf("<")===-1)return k&&Mn?G(Q):Q;if(D=m_(Q),!D)return pn?null:Mn?P:""}D&&wo&&jn(D.firstChild);const Oe=f_(Ie?Q:D);try{for(;ie=Oe.nextNode();)h_(ie),y_(ie),si(ie.content)&&Os(ie.content)}catch(fn){throw Ie&&p_(Q),fn}if(Ie)return Gi(t.removed,fn=>{fn.element&&xO(fn.element)}),nt&&Su(Q),Q;if(pn){if(nt&&Su(D),br)for(Se=x.call(D.ownerDocument);D.firstChild;)Se.appendChild(D.firstChild);else Se=D;return(pe.shadowroot||pe.shadowrootmode)&&(Se=B.call(r,Se,!0)),Se}let Nt=me?D.outerHTML:D.innerHTML;return me&&ee["!doctype"]&&D.ownerDocument&&D.ownerDocument.doctype&&D.ownerDocument.doctype.name&&Ze(AE,D.ownerDocument.doctype.name)&&(Nt="<!DOCTYPE "+D.ownerDocument.doctype.name+`>
48
- `+Nt),nt&&(Nt=$s(Nt)),k&&Mn?G(Nt):Nt},t.setConfig=function(){wu(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),ae=!0,Ge=ee,$n=pe},t.clearConfig=function(){ai=null,ae=!1,Ge=null,$n=null,k=E,P=""},t.isValidAttribute=function(Q,C,D){return ai||wu({}),g_(Ue(Q),Ue(C),D)},t.addHook=function(Q,C){typeof C=="function"&&qe(V,Q)&&qr(V[Q],C)},t.removeHook=function(Q,C){if(qe(V,Q)){if(C!==void 0){const D=uE(V[Q],C);return D===-1?void 0:pE(V[Q],D,1)[0]}return iv(V[Q])}},t.removeHooks=function(Q){qe(V,Q)&&(V[Q]=[])},t.removeAllHooks=function(){V=hv()},t}var vv=gv();function Xl(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var or=Xl();function yv(e){or=e}var ar={exec:()=>null};function zr(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 ke(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(ot.caret,"$1"),n=n.replace(i,s),r},getRegex:()=>new RegExp(n,t)};return r}var ME=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),ot={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:zr(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:zr(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:zr(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:zr(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:zr(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:zr(e=>new RegExp(`^ {0,${e}}>`))},OE=/^(?:[ \t]*(?:\n|$))+/,jE=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,FE=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Wi=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,BE=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Zl=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,bv=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_v=ke(bv).replace(/bull/g,Zl).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),UE=ke(bv).replace(/bull/g,Zl).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Ql=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,GE=/^[^\n]+/,ed=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,HE=ke(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ed).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),KE=ke(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Zl).getRegex(),Xa="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",td=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,VE=ke("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\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",td).replace("tag",Xa).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),wv=ke(Ql).replace("hr",Wi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Xa).getRegex(),nd={blockquote:ke(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",wv).getRegex(),code:jE,def:HE,fences:FE,heading:BE,hr:Wi,html:VE,lheading:_v,list:KE,newline:OE,paragraph:wv,table:ar,text:GE},Sv=ke("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Wi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Xa).getRegex(),WE={...nd,lheading:UE,table:Sv,paragraph:ke(Ql).replace("hr",Wi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Sv).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Xa).getRegex()},qE={...nd,html:ke(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",td).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:ar,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:ke(Ql).replace("hr",Wi).replace("heading",` *#{1,6} *[^
49
- ]`).replace("lheading",_v).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},zE=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,JE=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Cv=/^( {2,}|\\)\n(?!\s*$)/,YE=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Jr=/[\p{P}\p{S}]/u,Za=/[\s\p{P}\p{S}]/u,rd=/[^\s\p{P}\p{S}]/u,XE=ke(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Za).getRegex(),Tv=/(?!~)[\p{P}\p{S}]/u,ZE=/(?!~)[\s\p{P}\p{S}]/u,QE=/(?:[^\s\p{P}\p{S}]|~)/u,eI=ke(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",ME?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),kv=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,tI=ke(kv,"u").replace(/punct/g,Jr).getRegex(),nI=ke(kv,"u").replace(/punct/g,Tv).getRegex(),Nv="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",rI=ke(Nv,"gu").replace(/notPunctSpace/g,rd).replace(/punctSpace/g,Za).replace(/punct/g,Jr).getRegex(),iI=ke(Nv,"gu").replace(/notPunctSpace/g,QE).replace(/punctSpace/g,ZE).replace(/punct/g,Tv).getRegex(),oI=ke("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,rd).replace(/punctSpace/g,Za).replace(/punct/g,Jr).getRegex(),aI=ke(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Jr).getRegex(),sI=ke("^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,rd).replace(/punctSpace/g,Za).replace(/punct/g,Jr).getRegex(),cI=ke(/\\(punct)/,"gu").replace(/punct/g,Jr).getRegex(),lI=ke(/^<(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(),dI=ke(td).replace("(?:-->|$)","-->").getRegex(),uI=ke("^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",dI).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Qa=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,pI=ke(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Qa).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),xv=ke(/^!?\[(label)\]\[(ref)\]/).replace("label",Qa).replace("ref",ed).getRegex(),Pv=ke(/^!?\[(ref)\](?:\[\])?/).replace("ref",ed).getRegex(),mI=ke("reflink|nolink(?!\\()","g").replace("reflink",xv).replace("nolink",Pv).getRegex(),Av=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,id={_backpedal:ar,anyPunctuation:cI,autolink:lI,blockSkip:eI,br:Cv,code:JE,del:ar,delLDelim:ar,delRDelim:ar,emStrongLDelim:tI,emStrongRDelimAst:rI,emStrongRDelimUnd:oI,escape:zE,link:pI,nolink:Pv,punctuation:XE,reflink:xv,reflinkSearch:mI,tag:uI,text:YE,url:ar},fI={...id,link:ke(/^!?\[(label)\]\((.*?)\)/).replace("label",Qa).getRegex(),reflink:ke(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Qa).getRegex()},od={...id,emStrongRDelimAst:iI,emStrongLDelim:nI,delLDelim:aI,delRDelim:sI,url:ke(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Av).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:ke(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Av).getRegex()},hI={...od,br:ke(Cv).replace("{2,}","*").getRegex(),text:ke(od.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},es={normal:nd,gfm:WE,pedantic:qE},qi={normal:id,gfm:od,breaks:hI,pedantic:fI},gI={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Ev=e=>gI[e];function qt(e,t){if(t){if(ot.escapeTest.test(e))return e.replace(ot.escapeReplace,Ev)}else if(ot.escapeTestNoEncode.test(e))return e.replace(ot.escapeReplaceNoEncode,Ev);return e}function Iv(e){try{e=encodeURI(e).replace(ot.percentDecode,"%")}catch{return null}return e}function Rv(e,t){let n=e.replace(ot.findPipe,(i,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}).split(ot.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(ot.slashPipe,"|");return n}function Pn(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 Dv(e){let t=e.split(`
50
- `),n=t.length-1;for(;n>=0&&ot.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
51
- `)}function vI(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 yI(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 Lv(e,t,n,r,i){let o=t.href,s=t.title||null,c=e[1].replace(i.other.outputLinkReplace,"$1");r.state.inLink=!0;let l={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:o,title:s,text:c,tokens:r.inlineTokens(c)};return r.state.inLink=!1,l}function bI(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
45
+ For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return K(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},zC="DialogDescriptionWarning",JC=({contentRef:e,descriptionId:t})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Zf(zC).contentName}}.`;return K(()=>{const r=e.current?.getAttribute("aria-describedby");t&&r&&(document.getElementById(t)||console.warn(n))},[n,e,t]),null},YC=Hf,XC=Vf,QC=Wf,ZC=zf;function Ii({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(YC,{modal:o,open:p,onOpenChange:u,children:p?a(XC,{children:[a(QC,{asChild:!0,children:a("div",{className:f,id:m})}),a(ZC,{"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:h=>{h.target===h.currentTarget&&u(!1)},tabIndex:-1,children:n??(v?a("div",{id:v}):null)})})]}):null})}var em=500,ca=null,Ei=null,xi=null;function Pi(e){return Ei?Ei(e)?(xi=document.activeElement instanceof HTMLElement?document.activeElement:null,!0):!1:(xi=document.activeElement instanceof HTMLElement?document.activeElement:null,ca=e,!0)}function tt(e){return e.recipientKind==="identity"?`identity:${e.identityId}`:`team:${e.teamId}`}function tm(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 Mc(e){return e.recipientKind==="identity"?tt({recipientKind:"identity",identityId:e.identityId}):tt({recipientKind:"team",teamId:e.teamId})}function eN(e,t){return Mc(e)===tt(t)}function nm(e,t){return e instanceof Qs?"Recipient access changed after this review. Review the refreshed changes before trying again.":t}function rm({checked:e,description:t,disabled:n,label:r,onChange:i}){const o=`recipient-policy-choice-${Si()}`;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 tN(e,t){const n=e.teamMemberships.filter(s=>s.status==="active"),r=new Map(e.identities.map(s=>[s.identityId,s])),i=[...e.teams.filter(s=>s.status==="active").map(s=>{const c=n.filter(l=>l.teamId===s.teamId).map(l=>r.get(l.identityId)?.displayName).filter(l=>!!l);return{key:tt({recipientKind:"team",teamId:s.teamId}),label:s.displayName,description:`Team · ${c.length.toLocaleString()} current ${c.length===1?"member":"members"}${c.length?`: ${c.join(", ")}`:""}`}}),...e.identities.filter(s=>s.status==="active"||s.status==="pending").map(s=>({key:tt({recipientKind:"identity",identityId:s.identityId}),label:s.displayName,description:`Identity · ${s.status==="pending"?"pending · ":""}locally verified`}))];if(t?.mode!=="project-manage")return i;const o=new Set(i.map(s=>s.key));for(const s of e.projectRecipients){if(s.status!=="active"||s.canonicalProjectIdentity!==t.projectId)continue;const c=Mc(s);if(!o.has(c)){if(s.recipientKind==="team"){const l=e.teams.find(d=>d.teamId===s.teamId);i.push({key:c,label:l?.displayName??"Unavailable Team",description:`${l?.status==="archived"?"Archived Team":"Unavailable Team"} · existing access can only be removed`})}else{const l=r.get(s.identityId);i.push({key:c,label:l?.displayName??"Unavailable Identity",description:`${l?.status==="merged"?"Merged Identity":"Unavailable Identity"} · existing access can only be removed`})}o.add(c)}}return i}function im(e){return e.mode==="project-add"?[...new Set(e.projectIds)]:e.mode==="project-manage"?[e.projectId]:[]}function nN(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(Mc):n.filter(r=>eN(r,e.recipient)).map(r=>r.canonicalProjectIdentity)}function rN(e,t,n){const r=t.mode==="recipient-add"?e.filter(s=>!n.includes(s.canonicalProjectIdentity)):e,i=r.map(s=>({...s,description:`${s.existingMemoryCount.toLocaleString()} existing memories`}));if(t.mode!=="recipient-manage")return i;const o=new Set(r.map(s=>s.canonicalProjectIdentity));for(const s of n)o.has(s)||i.push({canonicalProjectIdentity:s,displayName:s,existingMemoryCount:0,description:"Unavailable Project · existing access can only be removed"});return i}function iN(e,t,n){return e.mode==="project-add"?im(e).flatMap(r=>t.flatMap(i=>{const o=tm(i);return o?[{canonicalProjectIdentity:r,recipient:o,action:"add"}]:[]})):e.mode==="project-manage"?[...new Set([...n,...t])].flatMap(r=>{const i=tm(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 oN(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 om(e,t){let n=!1,r=!1,i=!1,o=!1;const s=tt(t);for(const c of e){const{change:l,outcome:d}=c;tt(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 aN(e){const t=new Set(e.selectedRecipients.map(tt)),n=new Map;for(const r of e.normalizedChanges){const i=tt(r.recipient);t.has(i)||n.set(i,r.recipient)}return[...n.values()]}function sN(e){const t=new Set;return e.filter(n=>t.has(n.deviceId)?!1:(t.add(n.deviceId),!0))}function cN({preview:e,recipientLabels:t}){const n=sN(e.effectiveDevices),r=aN(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(i=>a("li",{children:[a("strong",{className:"recipient-policy-management-name",children:i.displayName}),a("span",{children:[" ","— Access changes affect ",i.existingMemoryCount.toLocaleString()," existing memories",i.futureMemoriesShared?" and future activity":"; future activity is not included"]})]},i.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(i=>a("li",{children:[a("strong",{className:"recipient-policy-management-name",children:i.displayName})," ",a("span",{children:["— ",om(e.outcomes,i)," · "]}),i.recipientKind==="identity"?a("span",{children:"Identity · locally verified"}):a("span",{className:"recipient-policy-management-recipient-context",children:["Team · ",i.currentMembers.length.toLocaleString()," current"," ",i.currentMembers.length===1?"member":"members",i.currentMembers.length?a(Z,{children:[":"," ",a("span",{className:"recipient-policy-management-member-names",children:i.currentMembers.map(o=>o.displayName).join(", ")})]}):null,". Future Team members"," ",i.futureMembersInherit?"inherit":"do not inherit"," access."]})]},tt(i))),r.map(i=>a("li",{children:[a("strong",{className:"recipient-policy-management-name",children:t.get(tt(i))??(i.recipientKind==="team"?i.teamId:i.identityId)})," ",a("span",{children:["— ",om(e.outcomes,i)," ·"," ",i.recipientKind==="team"?"Team":"Identity"]})]},tt(i)))]})]}),a("section",{"aria-labelledby":"recipient-policy-review-availability",children:[a("h3",{id:"recipient-policy-review-availability",children:"Resulting availability"}),n.length?a(Z,{children:[a("p",{children:["After the update, the affected Projects will be available on"," ",n.length.toLocaleString()," current"," ",n.length===1?"device":"devices"," across all recipients."]}),a("ul",{children:n.map(i=>a("li",{className:"recipient-policy-management-name",children:i.displayName},i.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(i=>a("li",{className:"recipient-policy-management-name",children:i.displayName},i.canonicalProjectIdentity))})]}):null]})]})}function lN({preview:e,result:t}){const n=t.status==="applied"?"Applied":t.status==="not_found"?"Not found":`${t.status.charAt(0).toUpperCase()}${t.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: ",n,". Writes: ",t.writeCount.toLocaleString(),"."]}),t.errorCode?a("p",{children:["Error code: ",t.errorCode.replaceAll("_"," "),"."]}):null,t.outcomes.length?a("ul",{children:t.outcomes.map(r=>{const i=e.projects.find(s=>s.canonicalProjectIdentity===r.change.canonicalProjectIdentity)?.displayName??"Selected Project",o=e.selectedRecipients.find(s=>tt(s)===tt(r.change.recipient))?.displayName??(r.change.recipient.recipientKind==="team"?"Team":"Identity");return a("li",{children:[r.change.action==="add"?"Add":"Remove"," ",o," ",r.change.action==="add"?"to":"from"," ",i,":"," ",r.outcome.replaceAll("_"," ")]},`${r.change.canonicalProjectIdentity}:${tt(r.change.recipient)}`)})}):null]})})}function dN({intent:e,options:t,projects:n}){const[r,i]=D(null),[o,s]=D([]),[c,l]=D([]),[d,u]=D(null),[p,f]=D(null),[m,v]=D(null),[h,g]=D(""),[_,w]=D(!1),S=U(!1),N=Ee(()=>tN(e,r),[e,r]),k=Ee(()=>new Map([...e.teams.map(J=>[`team:${J.teamId}`,J.displayName]),...e.identities.map(J=>[`identity:${J.identityId}`,J.displayName])]),[e]),E=Ee(()=>new Set(n.map(J=>J.canonicalProjectIdentity)),[n]);if(K(()=>{if(Ei=J=>{if(S.current)return!1;const ve=nN(J,e);return i(J),l(ve),s(J.mode==="recipient-add"?[]:ve),u(null),f(null),v(null),g(""),w(!1),S.current=!1,!0},ca){const J=ca;ca=null,Ei(J)}return()=>{Ei=null}},[e]),K(()=>{p&&document.getElementById("recipient-policy-management-title")?.focus()},[p]),!r)return null;const R=oN(r),j=im(r),q=r.mode==="recipient-manage"?!1:j.some(J=>!E.has(J)),I=(r.mode==="recipient-add"||r.mode==="recipient-manage")&&!N.some(J=>J.key===tt(r.recipient)),G=t.loading||t.loadError||q||I,A=iN(r,o,c),M=A.length>em,L=(r.mode==="project-add"||r.mode==="recipient-add")&&o.length===0,x=r.mode!=="project-add"&&r.mode!=="recipient-add"&&A.length===0,O=rN(n,r,c),T=p?.status==="applied",P=p?T?"Recipient access updated":"Recipient access needs attention":d?"Review recipient access":R.title,B=p?T?"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.":R.description,V=()=>{S.current||(i(null),u(null),f(null),v(null),g(""))},le=J=>{s(ve=>ve.includes(J)?ve.filter(ee=>ee!==J):[...ve,J]),v(null),g("")},de=async()=>{if(!(G||L||x||M||S.current)){S.current=!0,w(!0),v(null),g("Reviewing exact recipient access changes.");try{u(await Ew({version:1,changes:A})),g("Review ready. Confirm the exact changes.")}catch(J){v(nm(J,"Unable to review recipient access changes.")),g("")}finally{S.current=!1,w(!1)}}},ae=async()=>{if(!(!d||S.current)){S.current=!0,w(!0),v(null),g("Saving recipient access changes.");try{const J=await xw({version:1,changes:d.normalizedChanges,reviewedPolicyDigest:d.reviewedPolicyDigest});f(J),g("");try{await t.onCommitted?.(J)}catch{v("Recipient access was saved, but this view could not refresh.")}}catch(J){J instanceof Qs&&(u(null),g("")),v(nm(J,"Unable to save recipient access changes."))}finally{S.current=!1,w(!1)}}};let be=null;return t.loading?be="Loading the complete recipient access inventory…":t.loadError?be="The complete recipient access inventory is unavailable. Refresh and try again.":q?be="One selected Project is no longer available. Refresh and try again.":I&&(be="This recipient is no longer available. Refresh and try again."),a(Ii,{ariaDescribedby:"recipient-policy-management-description",ariaLabelledby:"recipient-policy-management-title",contentClassName:"modal recipient-policy-management-dialog",contentId:"recipientPolicyManagementDialog",onCloseAutoFocus:J=>{J.preventDefault();const ve=r.mode.startsWith("project-")?"tabBtn-projects":"tabBtn-sharing",ee=xi?.isConnected?xi:document.getElementById(ve);ee instanceof HTMLElement&&ee.focus(),xi=null},onOpenAutoFocus:J=>{const ve=document.getElementById("recipient-policy-management-title");ve&&(J.preventDefault(),ve.focus())},onOpenChange:J=>{J||V()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientPolicyManagementDialogBackdrop",children:a("div",{"aria-busy":_||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:P}),a(Vo,{ariaLabel:`Close ${P}`,className:"modal-close-button recipient-policy-management-target",disabled:_,onClick:V})]}),a("div",{className:"modal-body recipient-policy-management-selection",children:[a("p",{className:"small",id:"recipient-policy-management-description",children:B}),be?a("p",{"aria-live":"polite",role:t.loadError?"alert":"status",children:be}):p&&d?a(lN,{preview:d,result:p}):d?a(cN,{preview:d,recipientLabels:k}):r.mode==="recipient-add"||r.mode==="recipient-manage"?a("fieldset",{className:"sync-dialog-radio-list",disabled:_,children:[a("legend",{children:R.legend}),O.length?O.map(J=>a(rm,{checked:o.includes(J.canonicalProjectIdentity),description:J.description,disabled:_,label:J.displayName,onChange:()=>le(J.canonicalProjectIdentity)},J.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:_,children:[a("legend",{children:R.legend}),N.length?N.map(J=>a(rm,{checked:o.includes(J.key),description:J.description,disabled:_,label:J.label,onChange:()=>le(J.key)},J.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:h}),m?a("p",{"aria-live":"assertive",role:"alert",children:m}):null,M?a("p",{"aria-live":"assertive",role:"alert",children:["This selection creates ",A.length.toLocaleString()," access changes. Review at most ",em.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:_,onClick:d&&!p?()=>{u(null),g("")}:V,type:"button",children:p?"Done":d?"Back":"Cancel"}),!p&&!be?a("button",{className:"settings-button sync-dialog-confirm recipient-policy-management-target",disabled:_||!d&&(L||x||M),onClick:()=>{d?ae():de()},type:"button",children:_?d?"Saving…":"Reviewing…":d?"Confirm changes":"Review changes"}):null]})]})})}function am(e,t,n,r={}){Be(a(dN,{intent:n,options:r,projects:t}),e)}function la(e){return e.identity_source!=="unmapped"&&e.read_only!==!0}function uN(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 da(e){const t=new Map;for(const n of e)la(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 sm({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 pN(e){return e.state!=="configured"}function cm(e){return e?.items.filter(pN)??[]}function ua(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 fN=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,mN=/^(?:actor|device|identity|local):\S+$/iu,hN=/^(?:actor|device|identity)[_-][a-z0-9][a-z0-9._:-]{4,}$/iu,vN=/^pending[_-]\S+$/iu,gN=/^[a-f0-9]{12,64}$/iu;function lm(e){return[fN,mN,hN,vN,gN].some(t=>t.test(e))}function xr(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||lm(t)?"":t}var Pr=null,Ar=null;function pa(e=[],t=""){if(Ar){const n=Ar(e,t);return n||(Pr=null),n}return Pr={projectIds:e,teammateName:t},window.location.hash="#projects",!0}function dm(e){return!e.read_only&&e.identity_source!=="unmapped"&&e.memory_count!=null&&!e.guardrail_warnings.some(t=>t.requires_confirmation)}function um(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 yN(e){const t=`share-project-${Si()}`,n=dm(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 bN({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 _N({projects:e,inventoryError:t}){const[n,r]=D(!1),[i,o]=D(""),[s,c]=D([]),[l,d]=D(null),[u,p]=D(null),[f,m]=D(null),[v,h]=D(!1),[g,_]=D(null),[w,S]=D(!1),N=Ee(()=>e.filter(dm),[e]);K(()=>{if(Ar=(I,G="")=>{if(t)return!1;const A=[...new Set(I)],M=A.some(L=>!N.some(x=>x.workspace_identity===L));return o(G.trim()),c(M?[]:A),S(M),d(null),p(null),m(M?"The original project selection is no longer available. Refresh Projects and try again.":null),_(null),r(!0),!0},Pr){const I=Pr;Pr=null,Ar(I.projectIds,I.teammateName)}return()=>{Ar=null}},[N,t]),K(()=>{t&&(Pr=null,r(!1),o(""),c([]),d(null),p(null),m(null),_(null),S(!1))},[t]);const k=()=>{v||r(!1)},E=I=>{c(G=>G.includes(I)?G.filter(A=>A!==I):[...G,I])},R=async()=>{if(m(null),!i.trim()){m("Enter your teammate's name.");return}if(s.length===0){m("Select at least one project.");return}h(!0);try{d(await Lw({teammate_name:i.trim(),project_ids:s}))}catch(I){m(um(I,"Unable to review this invitation."))}finally{h(!1)}},j=async()=>{if(l){m(null),h(!0);try{p(await $w({teammate_name:l.teammate.display_name,project_ids:l.projects.map(I=>I.project_id),reviewed_project_set_digest:l.reviewed_project_set_digest}))}catch(I){I instanceof Error&&I.message==="reviewed_project_set_changed"&&d(null),m(um(I,"Unable to create this invitation."))}finally{h(!1)}}},q=async()=>{if(u){m(null),_(null);try{if(!navigator.clipboard)throw new Error("Clipboard access is unavailable.");await navigator.clipboard.writeText(u.invite.link),_("Invite copied.")}catch(I){m(I instanceof Error?I.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||N.length===0,onClick:()=>Ar?.([]),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(Ii,{ariaDescribedby:"project-share-description",ariaLabelledby:"project-share-title",contentClassName:"modal",contentId:"projectShareDialog",onOpenChange:I=>{I||k()},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:k,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(I=>I.display_name).join(", "),"."]}),a("p",{className:"small",children:["Invitation expires ",new Date(u.invite.expires_at).toLocaleString(),"."]}),a("button",{className:"settings-button",onClick:()=>{q()},type:"button",children:"Copy invite"}),g?a("p",{role:"status",children:g}):null]}):l?a(bN,{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:I=>o(I.currentTarget.value),type:"text",value:i})]}),a("fieldset",{className:"sync-dialog-radio-list",children:[a("legend",{children:"Select exact projects"}),e.map(I=>a(yN,{onToggle:E,project:I,selected:s.includes(I.workspace_identity)},I.workspace_identity))]})]}),f?a("p",{role:"alert",children:f}):null]}),a("div",{className:"modal-footer",children:[a("button",{className:"settings-button",disabled:v,onClick:k,type:"button",children:u?"Done":"Cancel"}),u?null:a("button",{className:"settings-button sync-dialog-confirm",disabled:v||w,onClick:()=>{l?j():R()},type:"button",children:v?l?"Creating invite…":"Reviewing…":l?"Create invite":"Review sharing"})]})]})}):null]})}function pm(e,t,n={}){Be(a(_N,{inventoryError:n.inventoryError===!0,projects:t}),e)}function Oc(e){return xr(String(e??"").trim())}function Rr(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.`:lm(n)?`${t} must use a human-readable name.`:"":`${t} is required.`}function wN(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 fa(e,t){return e instanceof Error?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 Ai(e){return`${e.toLocaleString()} existing ${e===1?"memory":"memories"}`}function SN({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})," — ",Ai(t.existingMemoryCount)," and future activity"]},t.canonicalProjectIdentity))})}function CN({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(SN,{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 NN({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," — ",Ai(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," — ",Ai(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," — ",Ai(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 fm({preview:e}){return e.journey==="team"?a(CN,{preview:e}):a(NN,{preview:e})}function kN({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 TN({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})," —"," ",Ai(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 IN({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 EN({result:e}){const t=e.kind==="team_member"?"Team invitation accepted":"Device added";return a("section",{"aria-describedby":[e.restartRequired?"recipient-invitation-result-detail":null,e.deliveryPending?"recipient-invitation-result-delivery":null].filter(Boolean).join(" ")||void 0,"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 mm(e,t){return e==="team_member"?{kind:e,policy_team_id:t}:{kind:e,target_identity_id:t}}function xN({intent:e}){const t=e.teams.filter(Q=>Q.status==="active"),n=e.identities.filter(Q=>Q.status==="active"),[r,i]=D(null),[o,s]=D("team_member"),[c,l]=D(t[0]?.teamId??""),[d,u]=D(""),[p,f]=D(null),[m,v]=D(null),[h,g]=D(null),[_,w]=D(null),[S,N]=D(""),[k,E]=D(""),[R,j]=D(""),[q,I]=D(null),[G,A]=D(!1),[M,L]=D(""),[x,O]=D(""),T=U(null),P=U(0),B=U(""),V=U(!1);K(()=>{if(_){document.getElementById("recipient-invitation-result")?.focus();return}if(h){document.getElementById("project-share-invitation-result")?.focus();return}m?.kind==="project_share_invite"&&document.getElementById("project-share-invitation-projects")?.focus()},[m,h,_]);const le=()=>{P.current+=1,B.current="",V.current=!1,u(""),f(null),v(null),g(null),w(null),N(""),E(""),j(""),I(null),L(""),O("")},de=(Q,re)=>{le(),T.current=re,i(Q)},ae=()=>{G||(i(null),le())},be=Q=>{P.current+=1,B.current=Q,u(Q)},J=Q=>{s(Q),l(Q==="team_member"?t[0]?.teamId??"":n[0]?.identityId??""),le()},ve=async()=>{if(c){A(!0),O(""),L("Reviewing invitation…");try{f((await Pw(mm(o,c))).preview),L("Review ready. Confirm the invitation details.")}catch(Q){O(fa(Q,"Unable to review this invitation.")),L("")}finally{A(!1)}}},ee=async()=>{if(p){A(!0),O(""),L("Creating invitation…");try{I(await Aw({...mm(o,c),reviewed_onboarding_digest:p.reviewedOnboardingDigest})),L("Invitation created.")}catch(Q){Q instanceof Error&&Q.message==="reviewed_onboarding_stale"&&f(null),O(fa(Q,"Unable to create this invitation.")),L("")}finally{A(!1)}}},Te=async()=>{const Q=B.current.trim(),re=P.current;if(!Q){O("Paste an invitation first.");return}const ut=()=>P.current===re&&B.current.trim()===Q;A(!0),O(""),L("Reviewing invitation…");try{const Ue=await tp(Q);if(!ut())return;v(Ue),Ue.kind==="team_member"?N(Oc(Ue.recipient_name)):Ue.kind==="project_share_invite"&&(E(Oc(Ue.recipient_name)),j(Oc(Ue.device_name))),L(Ue.kind==="add_device"?(Ue.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.":Ue.kind==="team_member"?"Review ready. Confirm before accepting.":Ue.kind==="project_share_invite"?"Review ready. Confirm the exact Projects before accepting.":"Open Advanced Team administration to continue with this invitation.")}catch(Ue){if(!ut())return;O(fa(Ue,"Unable to review this invitation.")),L("")}finally{A(!1)}},fe=async()=>{if(!(G||V.current||_)&&!(!m||m.kind==="legacy_team_invite")&&!(m.kind==="project_share_invite"&&!(m.projects?.length??0))&&!(m.kind==="project_share_invite"&&(Rr(k,"Identity display name")||Rr(R,"Device display name")))&&!(m.kind==="team_member"&&Rr(S,"Identity display name"))){V.current=!0,A(!0),O(""),L("Accepting invitation…");try{const Q=m.kind==="project_share_invite"?await Ys(d.trim(),{recipient_name:k.trim(),device_name:R.trim()}):await Ys(d.trim(),{...m.kind==="team_member"?{recipient_name:S.trim()}:{},device_name:m.device_name,reviewed_onboarding_digest:m.onboarding.reviewedOnboardingDigest});if(m.kind==="project_share_invite")g(wN(Q)),L("");else{const re=m.kind;w({kind:re,restartRequired:Q.restart_required===!0||Q.setup_state==="restart_required",detail:(typeof Q.detail=="string"?Q.detail.trim():"")||"Restart codemem before continuing.",deliveryPending:re==="add_device"&&(m.onboarding?.projects?.length??0)>0}),L("")}}catch(Q){V.current=!1;const re=Q instanceof Error?Q.message.trim():"";O(fa(Q,m.kind==="project_share_invite"&&re?re:"Unable to accept this invitation.")),L("")}finally{A(!1)}}},te=async()=>{const Q=q?.invite.link||q?.invite.encoded||"";if(!Q){O("The invitation text is unavailable.");return}try{await navigator.clipboard.writeText(Q),L("Invitation copied.")}catch{O("Unable to copy the invitation.")}},Ie=m?.kind==="team_member"||m?.kind==="add_device"?m.onboarding:null,ce=m?.kind==="project_share_invite"?m:null,Ae=m?.kind==="team_member"?Rr(S,"Identity display name"):"",ue=ce?Rr(k,"Identity display name"):"",Ke=ce?Rr(R,"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:Q=>{J("team_member"),de("create",Q.currentTarget)},type:"button",children:"Invite Team member"}),a("button",{className:"settings-button recipient-policy-sharing-target-24",disabled:n.length===0,onClick:Q=>{J("add_device"),de("create",Q.currentTarget)},type:"button",children:"Add a device"}),a("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>pa(),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:Q=>de("accept",Q.currentTarget),type:"button",children:"Review invitation"}),a("p",{className:"small",children:"Legacy invitation import remains under Advanced Team administration."})]}),r?a(Ii,{ariaDescribedby:"recipient-invitation-description",ariaLabelledby:"recipient-invitation-title",contentClassName:"modal recipient-policy-invitation-dialog",contentId:"recipientInvitationDialog",onCloseAutoFocus:Q=>{Q.preventDefault(),T.current?.focus(),T.current=null},onOpenAutoFocus:Q=>{Q.preventDefault(),document.getElementById("recipient-invitation-title")?.focus()},onOpenChange:Q=>{Q||ae()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientInvitationDialogBackdrop",children:a("div",{"aria-busy":G,className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:"recipient-invitation-title",tabIndex:-1,children:_?"Invitation accepted":r==="create"?"Create invitation":"Review invitation"}),a(Vo,{ariaLabel:"Close invitation",className:"modal-close-button recipient-policy-sharing-target-24",disabled:G,onClick:ae})]}),a("div",{className:"modal-body",children:[a("p",{className:"small",id:"recipient-invitation-description",children:_?"The invitation has been accepted.":"Confirm exactly what this invitation includes before continuing."}),r==="create"&&!p&&!q?a("label",{className:"field",htmlFor:"recipient-invitation-target",children:[a("span",{children:o==="team_member"?"Team":"Identity"}),a("select",{id:"recipient-invitation-target",onChange:Q=>l(Q.currentTarget.value),value:c,children:(o==="team_member"?t:n).map(Q=>a("option",{value:"teamId"in Q?Q.teamId:Q.identityId,children:Q.displayName},"teamId"in Q?Q.teamId:Q.identityId))})]}):r==="accept"&&!m&&!_?a("label",{className:"field",htmlFor:"recipient-invitation-value",children:[a("span",{children:"Invitation"}),a("textarea",{id:"recipient-invitation-value",onInput:Q=>{be(Q.currentTarget.value),v(null),g(null),L(""),O("")},rows:5,value:d})]}):null,p?a(fm,{preview:p}):null,Ie&&!_?a(fm,{preview:Ie}):null,m?.kind==="team_member"&&!_?a(kN,{error:Ae,name:S,onChange:Q=>{N(Q),O("")}}):null,ce&&!h?a(TN,{deviceName:R,deviceNameError:Ke,invite:ce,onDeviceNameChange:Q=>{j(Q),O("")},onRecipientNameChange:Q=>{E(Q),O("")},recipientName:k,recipientNameError:ue}):null,h?a(IN,{result:h}):null,_?a(EN,{result:_}):null,q?a("div",{children:[a("p",{children:"Share the invitation with the recipient."}),a("button",{className:"settings-button",onClick:()=>{te()},type:"button",children:"Copy invitation"})]}):null,m?.kind==="legacy_team_invite"?a("p",{children:"Use Advanced Team administration to review and import this invitation."}):null,a("p",{"aria-live":"polite",className:"small",role:"status",children:M}),x?a("p",{"aria-live":"assertive",role:"alert",children:x}):null]}),a("div",{className:"modal-footer recipient-policy-sharing-responsive-actions",children:[a("button",{className:"settings-button",disabled:G,onClick:ae,type:"button",children:q||h||_?"Done":"Cancel"}),r==="create"&&!q?a("button",{className:"settings-button sync-dialog-confirm",disabled:G||!c,onClick:()=>{p?ee():ve()},type:"button",children:G?"Working…":p?"Create invitation":"Review invitation"}):r==="accept"&&!m&&!_?a("button",{className:"settings-button sync-dialog-confirm",disabled:G,onClick:()=>{Te()},type:"button",children:G?"Reviewing…":"Review invitation"}):Ie&&!_||ce&&!h?a("button",{className:"settings-button sync-dialog-confirm",disabled:G||!!(m?.kind==="team_member"&&Ae)||!!(ce&&(!ce.projects?.length||ue||Ke)),onClick:()=>{fe()},type:"button",children:G?"Accepting…":ce?"Accept Project access":"Accept invitation"}):null]})]})}):null]})}var Vn=[{id:"teams",label:"Teams"},{id:"identities",label:"Identities"},{id:"received",label:"Received"},{id:"invitations",label:"Invitations"}];function Wn(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function Ri(e,t){return e.length?e.join(", "):t}function hm(e,t){return[...new Set(e)].flatMap(n=>{const r=t.get(n);return r?[r.displayName]:[]})}function vm({descriptionId:e,disabled:t,displayName:n,recipient:r}){const i=()=>{Pi({mode:"recipient-manage",recipient:r})},o=()=>{Pi({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-label":`Add Projects for ${n}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",disabled:t,onClick:o,type:"button",children:"Add projects"}),a("button",{"aria-label":`Manage Projects for ${n}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",disabled:t,onClick: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 PN({disableMutations:e,intent:t,projects:n}){const r=t.teams.filter(s=>s.status==="active"),i=new Map(t.identities.filter(s=>s.status==="active").map(s=>[s.identityId,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 Teams are available for Project sharing."}):a("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:r.map((s,c)=>{const l=[...new Set(t.teamMemberships.filter(v=>v.status==="active"&&v.teamId===s.teamId&&i.has(v.identityId)).map(v=>v.identityId))],d=l.map(v=>i.get(v)?.displayName??""),u=new Set(t.identityDevices.filter(v=>v.status==="active"&&l.includes(v.identityId)).map(v=>v.deviceId)).size,p=hm(t.projectRecipients.filter(v=>v.status==="active"&&v.recipientKind==="team"&&v.teamId===s.teamId).map(v=>v.canonicalProjectIdentity),o),f=`recipient-policy-sharing-team-title-${c}`,m=`recipient-policy-sharing-team-add-description-${c}`;return a("article",{"aria-labelledby":f,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:f,children:s.displayName}),a("span",{className:"badge actor-badge",children:"Team"})]}),a("dl",{className:"recipient-policy-sharing-details",children:[a("div",{children:[a("dt",{children:"Current member Identities"}),a("dd",{children:[Wn(d.length,"active member")," —"," ",Ri(d,"No active members")]})]}),a("div",{children:[a("dt",{children:"Registered devices"}),a("dd",{children:Wn(u,"active registered device")})]}),a("div",{children:[a("dt",{children:"Shared Projects"}),a("dd",{children:[Wn(p.length,"active shared Project")," —"," ",Ri(p,"No Projects shared")]})]}),a("div",{children:[a("dt",{children:"Future Team members"}),a("dd",{children:"Yes — future Team members inherit the Team’s shared Projects."})]})]}),a(vm,{descriptionId:m,disabled:e,displayName:s.displayName,recipient:{recipientKind:"team",teamId:s.teamId}})]},s.teamId)})})}function AN({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=hm(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:[Wn(l.length,"active registered device")," —"," ",Ri(l.map(m=>m.displayName),"No active devices")]})]}),a("div",{children:[a("dt",{children:"Team memberships"}),a("dd",{children:[Wn(d.length,"active Team membership")," —"," ",Ri(d,"No active Team memberships")]})]}),a("div",{children:[a("dt",{children:"Directly shared Projects"}),a("dd",{children:[Wn(u.length,"directly shared active Project")," —"," ",Ri(u,"No Projects shared directly")]})]})]}),a("p",{className:"small",children:"Team Projects are shown on Team cards because per-device eligibility cannot be inferred from Identity membership alone."}),a(vm,{descriptionId:f,disabled:e,displayName:s.displayName,recipient:{recipientKind:"identity",identityId:s.identityId}})]},s.identityId)})})}function RN({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:Wn(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 DN({intent:e,options:t,projects:n}){const[r,i]=D(()=>e.teams.some(m=>m.status==="active")?"teams":"identities"),o=U(t.loading===!0||t.loadError===!0),s=U([]),c=cm(t.deviceInventory),l=c.length,d=t.coordinatorEnrollmentIssueCount??0,u=e.teams.some(m=>m.status==="active");K(()=>{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=Vn[m];v&&(i(v.id),s.current[m]?.focus())},f=(m,v)=>{let h=null;m.key==="ArrowRight"?h=(v+1)%Vn.length:m.key==="ArrowLeft"?h=(v-1+Vn.length)%Vn.length:m.key==="Home"?h=0:m.key==="End"&&(h=Vn.length-1),h!==null&&(m.preventDefault(),p(h))};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."})]}),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",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:Vn.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:h=>f(h,v),ref:h=>{s.current[v]=h},role:"tab",tabIndex:r===m.id?0:-1,type:"button",children:m.label},m.id))}),Vn.map(m=>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",children:t.loading?r===m.id?a(sm,{detailRowCount:4,label:"Loading Sharing details"}):null:t.loadError?r===m.id?a("p",{"aria-live":"assertive",role:"alert",children:"Sharing details are unavailable. Refresh and try again."}):null:m.id==="teams"?a(PN,{disableMutations:t.refreshError===!0,intent:e,projects:n}):m.id==="identities"?a(AN,{disableMutations:t.refreshError===!0,intent:e,projects:n}):m.id==="received"?a(RN,{received:t.received??[]}):a(xN,{intent:e})},m.id))]})}function LN(e,t,n,r={}){Be(a(DN,{intent:n,options:r,projects:t}),e)}var jc={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]};async function $N(){const e=[];let t=0;for(;;){const n=await Oo({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return{manageable:da(e),received:uN(e)}}var MN={loadDeviceInventory:ec,loadIntent:Zs,loadProjects:$N,loadSyncStatus:$o,mountManagement:am,mountSharing:LN};function ON(e={},t={}){const n={...MN,...e};let r=0,i=null,o=0,s,c=null;const l=()=>{const u=d(++r);return i=u,u};async function d(u){const p=document.getElementById("recipientPolicySharingMount");if(!p)return!0;const f=document.getElementById("recipientPolicyManagementMount");c||n.mountSharing(p,[],jc,{loading:!0});const[m,v,h,g]=await Promise.allSettled([n.loadProjects(),n.loadIntent(),n.loadDeviceInventory(),n.loadSyncStatus(!1,"",{includeJoinRequests:!1})]);if(u!==r)return i??!1;const _=h.status==="rejected";if(h.status==="fulfilled"&&(s=h.value),g.status==="fulfilled"&&(o=mp(g.value)),m.status==="fulfilled"&&v.status==="fulfilled"){const w=m.value,S=v.value;return c={intent:S,inventory:w},n.mountSharing(p,w.manageable,S,{coordinatorEnrollmentIssueCount:o,deviceInventory:s,deviceInventoryUnavailable:_,onReviewDevices:t.onReviewDevices,received:w.received}),f&&n.mountManagement(f,w.manageable,S,{onCommitted:async()=>{await l()}}),!0}return c?n.mountSharing(p,c.inventory.manageable,c.intent,{coordinatorEnrollmentIssueCount:o,deviceInventory:s,deviceInventoryUnavailable:_,onReviewDevices:t.onReviewDevices,received:c.inventory.received,refreshError:!0}):n.mountSharing(p,[],jc,{deviceInventoryUnavailable:_,loadError:!0}),f&&n.mountManagement(f,[],jc,{loadError:!0}),!1}return l}var jN=Symbol.for("preact-signals");function ma(){if(rn>1)rn--;else{var e,t=!1;for((function(){var i=va;for(va=void 0;i!==void 0;)i.S.v===i.v&&(i.S.i=i.i),i=i.o})();Di!==void 0;){var n=Di;for(Di=void 0,ha++;n!==void 0;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&bm(n))try{n.c()}catch(i){t||(e=i,t=!0)}n=r}}if(ha=0,rn--,t)throw e}}function FN(e){if(rn>0)return e();Bc=++BN,rn++;try{return e()}finally{ma()}}var Me=void 0;function Fc(e){var t=Me;Me=void 0;try{return e()}finally{Me=t}}var gm,Di=void 0,rn=0,ha=0,BN=0,Bc=0,va=void 0,ga=0;function ym(e){if(Me!==void 0){var t=e.n;if(t===void 0||t.t!==Me)return t={i:0,S:e,p:Me.s,n:void 0,t:Me,e:void 0,x:void 0,r:t},Me.s!==void 0&&(Me.s.n=t),Me.s=t,e.n=t,32&Me.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=Me.s,t.n=void 0,Me.s.n=t,Me.s=t),t}}function Je(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}Je.prototype.brand=jN,Je.prototype.h=function(){return!0},Je.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:Fc(function(){var r;(r=t.W)==null||r.call(t)}))},Je.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&&Fc(function(){var i;(i=t.Z)==null||i.call(t)}))}},Je.prototype.subscribe=function(e){var t=this;return Li(function(){var n=t.value,r=Me;Me=void 0;try{e(n)}finally{Me=r}},{name:"sub"})},Je.prototype.valueOf=function(){return this.value},Je.prototype.toString=function(){return this.value+""},Je.prototype.toJSON=function(){return this.value},Je.prototype.peek=function(){var e=this;return Fc(function(){return e.value})},Object.defineProperty(Je.prototype,"value",{get:function(){var e=ym(this);return e!==void 0&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(ha>100)throw new Error("Cycle detected");(function(n){rn!==0&&ha===0&&n.l!==Bc&&(n.l=Bc,va={S:n,v:n.v,i:n.i,o:va})})(this),this.v=e,this.i++,ga++,rn++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{ma()}}}});function Uc(e,t){return new Je(e,t)}function bm(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 _m(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 wm(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 zn(e,t){Je.call(this,void 0),this.x=e,this.s=void 0,this.g=ga-1,this.f=4,this.W=t?.watched,this.Z=t?.unwatched,this.name=t?.name}zn.prototype=new Je,zn.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===ga))return!0;if(this.g=ga,this.f|=1,this.i>0&&!bm(this))return this.f&=-2,!0;var e=Me;try{_m(this),Me=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 Me=e,wm(this),this.f&=-2,!0},zn.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)}Je.prototype.S.call(this,e)},zn.prototype.U=function(e){if(this.t!==void 0&&(Je.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)}},zn.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(zn.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var e=ym(this);if(this.h(),e!==void 0&&(e.i=this.i),16&this.f)throw this.v;return this.v}});function Sm(e,t){return new zn(e,t)}function Cm(e){var t=e.m;if(e.m=void 0,typeof t=="function"){rn++;var n=Me;Me=void 0;try{t()}catch(r){throw e.f&=-2,e.f|=8,Gc(e),r}finally{Me=n,ma()}}}function Gc(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,Cm(e)}function UN(e){if(Me!==this)throw new Error("Out-of-order effect");wm(this),Me=e,this.f&=-2,8&this.f&&Gc(this),ma()}function Dr(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=t?.name,gm&&gm.push(this)}Dr.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()}},Dr.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,Cm(this),_m(this),rn++;var e=Me;return Me=this,UN.bind(this,e)},Dr.prototype.N=function(){2&this.f||(this.f|=2,this.u=Di,Di=this)},Dr.prototype.d=function(){this.f|=8,1&this.f||Gc(this)},Dr.prototype.dispose=function(){this.d()};function Li(e,t){var n=new Dr(e,t);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var Nm,Hc,ya,GN=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,Cj=[],km=[];Li(function(){Nm=this.N})();function Lr(e,t){me[e]=t.bind(null,me[e]||function(){})}function ba(e){if(ya){var t=ya;ya=void 0,t()}ya=e&&e.S()}function Tm(e){var t=this,n=e.data,r=qN(n);r.value=n;var i=Ee(function(){for(var c=t,l=t.__v;l=l.__;)if(l.__c){l.__c.__$f|=4;break}var d=Sm(function(){var m=r.value.value;return m===0?0:m===!0?"":m||""}),u=Sm(function(){return!Array.isArray(d.value)&&!vp(d.value)}),p=Li(function(){if(this.N=Im,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}Tm.displayName="ReactiveTextNode",Object.defineProperties(Je.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Tm},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}}),Lr("__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 Je&&(n||(t.__np=n={}),n[i]=o,r[i]=o.peek())}}e(t)}),Lr("__r",function(e,t){if(e(t),t.type!==Z){ba();var n,r=t.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,o){var s;return Li(function(){s=this},{name:o}),s.c=i,s})(function(){var i;GN&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof t.type=="function"?t.type.displayName||t.type.name:""))),Hc=r,ba(n)}}),Lr("__e",function(e,t,n,r){ba(),Hc=void 0,e(t,n,r)}),Lr("diffed",function(e,t){ba(),Hc=void 0;var n;if(typeof t.type=="string"&&(n=t.__e)){var r=t.__np,i=t.props;if(r){var o=n.U;if(o)for(var s in o){var c=o[s];c!==void 0&&!(s in r)&&(c.d(),o[s]=void 0)}else o={},n.U=o;for(var l in r){var d=o[l],u=r[l];d===void 0?(d=HN(n,l,u),o[l]=d):d.o(u,i)}}}e(t)});function HN(e,t,n,r){var i=t in e&&e.ownerSVGElement===void 0,o=Uc(n),s=n.peek();return{o:function(c,l){o.value=c,s=c.peek()},d:Li(function(){this.N=Im;var c=o.value.value;s!==c?(s=void 0,i?e[t]=c:c!=null&&(c!==!1||t[4]==="-")?e.setAttribute(t,c):e.removeAttribute(t)):s=void 0})}}Lr("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)}),Lr("__h",function(e,t,n,r){(r<3||r===9)&&(t.__$f|=2),e(t,n,r)}),St.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 qN(e,t){return Ee(function(){return Uc(e,t)},[])}var Nj=typeof requestAnimationFrame>"u"?setTimeout:function(e){var t=function(){clearTimeout(n),cancelAnimationFrame(r),e()},n=setTimeout(t,35),r=requestAnimationFrame(t)},KN=function(e){queueMicrotask(function(){queueMicrotask(e)})};function VN(){FN(function(){for(var e;e=km.shift();)Nm.call(e)})}function Im(){km.push(this)===1&&(me.requestAnimationFrame||KN)(VN)}function _a(e){const t=e+"CollectionProvider",[n,r]=ot(t),[i,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=h=>{const{scope:g,children:_}=h,w=nn.useRef(null),S=nn.useRef(new Map).current;return a(i,{scope:g,itemMap:S,collectionRef:w,children:_})};s.displayName=t;const c=e+"CollectionSlot",l=Gn(c),d=nn.forwardRef((h,g)=>{const{scope:_,children:w}=h;return a(l,{ref:_e(g,o(c,_).collectionRef),children:w})});d.displayName=c;const u=e+"CollectionItemSlot",p="data-radix-collection-item",f=Gn(u),m=nn.forwardRef((h,g)=>{const{scope:_,children:w,...S}=h,N=nn.useRef(null),k=_e(g,N),E=o(u,_);return nn.useEffect(()=>(E.itemMap.set(N,{ref:N,...S}),()=>{E.itemMap.delete(N)})),a(f,{[p]:"",ref:k,children:w})});m.displayName=u;function v(h){const g=o(e+"CollectionConsumer",h);return nn.useCallback(()=>{const _=g.collectionRef.current;if(!_)return[];const w=Array.from(_.querySelectorAll(`[${p}]`));return Array.from(g.itemMap.values()).sort((S,N)=>w.indexOf(S.ref.current)-w.indexOf(N.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:s,Slot:d,ItemSlot:m},v,r]}var Em=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"}),WN="VisuallyHidden",wa=H((e,t)=>a(se.span,{...e,ref:t,style:{...Em,...e.style}}));wa.displayName=WN;var zN=wa,qc="ToastProvider",[Kc,JN,YN]=_a("Toast"),[xm,kj]=ot("Toast",[YN]),[XN,Sa]=xm(qc),Pm=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:i="right",swipeThreshold:o=50,children:s}=e,[c,l]=D(null),[d,u]=D(0),p=U(!1),f=U(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${qc}\`. Expected non-empty \`string\`.`),a(Kc.Provider,{scope:t,children:a(XN,{scope:t,label:n,duration:r,swipeDirection:i,swipeThreshold:o,toastCount:d,viewport:c,onViewportChange:l,onToastAdd:ie(()=>u(m=>m+1),[]),onToastRemove:ie(()=>u(m=>m-1),[]),isFocusedToastEscapeKeyDownRef:p,isClosePausedRef:f,children:s})})};Pm.displayName=qc;var Am="ToastViewport",QN=["F8"],Vc="toast.viewportPause",Wc="toast.viewportResume",Rm=H((e,t)=>{const{__scopeToast:n,hotkey:r=QN,label:i="Notifications ({hotkey})",...o}=e,s=Sa(Am,n),c=JN(n),l=U(null),d=U(null),u=U(null),p=U(null),f=_e(t,p,s.onViewportChange),m=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),v=s.toastCount>0;K(()=>{const g=_=>{r.length!==0&&r.every(w=>_[w]||_.code===w)&&p.current?.focus()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[r]),K(()=>{const g=l.current,_=p.current;if(v&&g&&_){const w=()=>{if(!s.isClosePausedRef.current){const E=new CustomEvent(Vc);_.dispatchEvent(E),s.isClosePausedRef.current=!0}},S=()=>{if(s.isClosePausedRef.current){const E=new CustomEvent(Wc);_.dispatchEvent(E),s.isClosePausedRef.current=!1}},N=E=>{g.contains(E.relatedTarget)||S()},k=()=>{g.contains(document.activeElement)||S()};return g.addEventListener("focusin",w),g.addEventListener("focusout",N),g.addEventListener("pointermove",w),g.addEventListener("pointerleave",k),window.addEventListener("blur",w),window.addEventListener("focus",S),()=>{g.removeEventListener("focusin",w),g.removeEventListener("focusout",N),g.removeEventListener("pointermove",w),g.removeEventListener("pointerleave",k),window.removeEventListener("blur",w),window.removeEventListener("focus",S)}}},[v,s.isClosePausedRef]);const h=ie(({tabbingDirection:g})=>{const _=c().map(w=>{const S=w.ref.current,N=[S,...fk(S)];return g==="forwards"?N:N.reverse()});return(g==="forwards"?_.reverse():_).flat()},[c]);return K(()=>{const g=p.current;if(g){const _=w=>{const S=w.altKey||w.ctrlKey||w.metaKey;if(w.key==="Tab"&&!S){const N=document.activeElement,k=w.shiftKey;if(w.target===g&&k){d.current?.focus();return}const E=h({tabbingDirection:k?"backwards":"forwards"}),R=E.findIndex(j=>j===N);Yc(E.slice(R+1))?w.preventDefault():k?d.current?.focus():u.current?.focus()}};return g.addEventListener("keydown",_),()=>g.removeEventListener("keydown",_)}},[c,h]),a(BS,{ref:l,role:"region","aria-label":i.replace("{hotkey}",m),tabIndex:-1,style:{pointerEvents:v?void 0:"none"},children:[v&&a(zc,{ref:d,onFocusFromOutsideViewport:()=>{Yc(h({tabbingDirection:"forwards"}))}}),a(Kc.Slot,{scope:n,children:a(se.ol,{tabIndex:-1,...o,ref:f})}),v&&a(zc,{ref:u,onFocusFromOutsideViewport:()=>{Yc(h({tabbingDirection:"backwards"}))}})]})});Rm.displayName=Am;var Dm="ToastFocusProxy",zc=H((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...i}=e,o=Sa(Dm,n);return a(wa,{tabIndex:0,...i,ref:t,style:{position:"fixed"},onFocus:s=>{const c=s.relatedTarget;o.viewport?.contains(c)||r()}})});zc.displayName=Dm;var $i="Toast",ZN="toast.swipeStart",ek="toast.swipeMove",tk="toast.swipeCancel",nk="toast.swipeEnd",Lm=H((e,t)=>{const{forceMount:n,open:r,defaultOpen:i,onOpenChange:o,...s}=e,[c,l]=Ct({prop:r,defaultProp:i??!0,onChange:o,caller:$i});return a(et,{present:n||c,children:a(ok,{open:c,...s,ref:t,onClose:()=>l(!1),onPause:st(e.onPause),onResume:st(e.onResume),onSwipeStart:z(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:z(e.onSwipeMove,d=>{const{x:u,y:p}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${p}px`)}),onSwipeCancel:z(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:z(e.onSwipeEnd,d=>{const{x:u,y:p}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${p}px`),l(!1)})})})});Lm.displayName=$i;var[rk,ik]=xm($i,{onClose(){}}),ok=H((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:i,open:o,onClose:s,onEscapeKeyDown:c,onPause:l,onResume:d,onSwipeStart:u,onSwipeMove:p,onSwipeCancel:f,onSwipeEnd:m,...v}=e,h=Sa($i,n),[g,_]=D(null),w=_e(t,L=>_(L)),S=U(null),N=U(null),k=i||h.duration,E=U(0),R=U(k),j=U(0),{onToastAdd:q,onToastRemove:I}=h,G=st(()=>{g?.contains(document.activeElement)&&h.viewport?.focus(),s()}),A=ie(L=>{!L||L===1/0||(window.clearTimeout(j.current),E.current=new Date().getTime(),j.current=window.setTimeout(G,L))},[G]);K(()=>{const L=h.viewport;if(L){const x=()=>{A(R.current),d?.()},O=()=>{const T=new Date().getTime()-E.current;R.current=R.current-T,window.clearTimeout(j.current),l?.()};return L.addEventListener(Vc,O),L.addEventListener(Wc,x),()=>{L.removeEventListener(Vc,O),L.removeEventListener(Wc,x)}}},[h.viewport,k,l,d,A]),K(()=>{o&&!h.isClosePausedRef.current&&A(k)},[o,k,h.isClosePausedRef,A]),K(()=>(q(),()=>I()),[q,I]);const M=Ee(()=>g?Fm(g):null,[g]);return h.viewport?a(Z,{children:[M&&a(ak,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite",children:M}),a(rk,{scope:n,onClose:G,children:en(a(Kc.ItemSlot,{scope:n,children:a(FS,{asChild:!0,onEscapeKeyDown:z(c,()=>{h.isFocusedToastEscapeKeyDownRef.current||G(),h.isFocusedToastEscapeKeyDownRef.current=!1}),children:a(se.li,{tabIndex:0,"data-state":o?"open":"closed","data-swipe-direction":h.swipeDirection,...v,ref:w,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:z(e.onKeyDown,L=>{L.key==="Escape"&&(c?.(L.nativeEvent),L.nativeEvent.defaultPrevented||(h.isFocusedToastEscapeKeyDownRef.current=!0,G()))}),onPointerDown:z(e.onPointerDown,L=>{L.button===0&&(S.current={x:L.clientX,y:L.clientY})}),onPointerMove:z(e.onPointerMove,L=>{if(!S.current)return;const x=L.clientX-S.current.x,O=L.clientY-S.current.y,T=!!N.current,P=["left","right"].includes(h.swipeDirection),B=["left","up"].includes(h.swipeDirection)?Math.min:Math.max,V=P?B(0,x):0,le=P?0:B(0,O),de=L.pointerType==="touch"?10:2,ae={x:V,y:le},be={originalEvent:L,delta:ae};T?(N.current=ae,Ca(ek,p,be,{discrete:!1})):Bm(ae,h.swipeDirection,de)?(N.current=ae,Ca(ZN,u,be,{discrete:!1}),L.target.setPointerCapture(L.pointerId)):(Math.abs(x)>de||Math.abs(O)>de)&&(S.current=null)}),onPointerUp:z(e.onPointerUp,L=>{const x=N.current,O=L.target;if(O.hasPointerCapture(L.pointerId)&&O.releasePointerCapture(L.pointerId),N.current=null,S.current=null,x){const T=L.currentTarget,P={originalEvent:L,delta:x};Bm(x,h.swipeDirection,h.swipeThreshold)?Ca(nk,m,P,{discrete:!0}):Ca(tk,f,P,{discrete:!0}),T.addEventListener("click",B=>B.preventDefault(),{once:!0})}})})})}),h.viewport)})]}):null}),ak=e=>{const{__scopeToast:t,children:n,...r}=e,i=Sa($i,t),[o,s]=D(!1),[c,l]=D(!1);return uk(()=>s(!0)),K(()=>{const d=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(d)},[]),c?null:a(qn,{asChild:!0,children:a(wa,{...r,children:o&&a(Z,{children:[i.label," ",n]})})})},sk="ToastTitle",ck=H((e,t)=>{const{__scopeToast:n,...r}=e;return a(se.div,{...r,ref:t})});ck.displayName=sk;var lk="ToastDescription",$m=H((e,t)=>{const{__scopeToast:n,...r}=e;return a(se.div,{...r,ref:t})});$m.displayName=lk;var Mm="ToastAction",dk=H((e,t)=>{const{altText:n,...r}=e;return n.trim()?a(jm,{altText:n,asChild:!0,children:a(Jc,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${Mm}\`. Expected non-empty \`string\`.`),null)});dk.displayName=Mm;var Om="ToastClose",Jc=H((e,t)=>{const{__scopeToast:n,...r}=e,i=ik(Om,n);return a(jm,{asChild:!0,children:a(se.button,{type:"button",...r,ref:t,onClick:z(e.onClick,i.onClose)})})});Jc.displayName=Om;var jm=H((e,t)=>{const{__scopeToast:n,altText:r,...i}=e;return a(se.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...i,ref:t})});function Fm(e){const t=[];return Array.from(e.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),pk(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(...Fm(n))}}),t}function Ca(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?Cc(i,o):i.dispatchEvent(o)}var Bm=(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};function uk(e=()=>{}){const t=st(e);Ve(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function pk(e){return e.nodeType===e.ELEMENT_NODE}function fk(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode: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}});for(;n.nextNode();)t.push(n.currentNode);return t}function Yc(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var mk=Pm,hk=Rm,vk=Lm,gk=$m,yk=Jc,Mi=Uc([]),bk=1;function _k(e,t="success",n=8e3){if(!e)return;const r=bk++;Mi.value=[...Mi.value,{id:r,message:e,variant:t,durationMs:n}]}function wk(e){Mi.value=Mi.value.filter(t=>t.id!==e)}function Sk(){const e=Mi.value;return a(mk,{duration:8e3,swipeDirection:"right",children:[e.map(t=>a(vk,{className:`toast-root toast-${t.variant}`,duration:t.durationMs,onOpenChange:n=>{n||wk(t.id)},type:t.variant==="error"||t.variant==="warning"?"foreground":"background",children:[a(gk,{className:"toast-message",children:t.message}),a(yk,{"aria-label":"Dismiss",className:"toast-close",children:"×"})]},t.id)),a(hk,{className:"toast-viewport"})]})}function Ck(e){Be(a(Sk,{}),e)}function Na(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 Xc(e){return document.getElementById(e)}function Qc(e){return document.getElementById(e)}function Um(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Nk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kk(e,t){const n=t.trim();if(!n)return Um(e);const r=Um(e);try{const i=new RegExp(`(${Nk(n)})`,"ig");return r.replace(i,'<mark class="match">$1</mark>')}catch{return r}}async function Oi(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 Tk=new Set(["BUTTON","A","SELECT"]),Ik=new Set(["button","checkbox","color","file","image","radio","range","reset","submit"]);function Ek(e){return!e||typeof e.closest!="function"?!1:e.closest('[data-primary-action-ignore="true"]')!==null}function xk(e){return e?!!(e instanceof HTMLTextAreaElement||"isContentEditable"in e&&e.isContentEditable):!1}function Pk(e){return e?Tk.has(e.tagName)?!0:e instanceof HTMLInputElement&&Ik.has(e.type):!1}function Ak(e){return e.metaKey||e.ctrlKey}function $r(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(!Ek(n)){if(e.key==="Escape"){if(!t.onCancel)return;e.preventDefault(),t.onCancel();return}Pk(n)||xk(n)&&!Ak(e)||(e.preventDefault(),t.onSubmit())}}var Jn=["feed","projects","sharing","devices","health","advanced"],Gm=["sync","coordinator-admin"],Zc="codemem-tab",Hm="codemem-advanced-section",qm="codemem-feed-filter",Km="codemem-feed-scope",Rk="codemem-sync-diagnostics",Vm="codemem-sync-pairing",Wm="codemem-sync-redact",zm=["all","observations","summaries"],Jm=["all","mine","theirs"],b={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,lastCoordinatorAdminStatus:null,coordinatorAdminTargetGroup:"",knownProjects:[],lastCoordinatorAdminGroups:[],lastCoordinatorAdminJoinRequests:[],lastCoordinatorAdminDevices:[],lastSyncJoinRequests:[],lastTeamInvite:null,lastTeamJoin:null,syncJoinFlowFeedback:null,syncPeerFeedbackById:new Map,syncPeersSectionFeedback:null,syncJoinRequestsFeedback:null,syncDiscoveredFeedback:null,lastSyncAttempts:[],lastSyncLegacyDevices:[],lastSyncViewModel:null,lastSyncDuplicatePersonDecisions:{},pairingPayloadRaw:null,pairingCommandRaw:"",configDefaults:{},configPath:"",settingsDirty:!1,syncDiagnosticsOpen:!1,syncPairingOpen:!1};function Dk(e){return[...Jn]}function ji(e,t){return e==="sync"||e==="coordinator-admin"?"advanced":Jn.includes(e)?e:"feed"}function el(e=window.location.hash){const t=e.replace(/^#/,"").split("/")[0];return Gm.includes(t)?"advanced":Jn.includes(t)?t:null}function tl(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 Lk(){const e=el();if(e)return ji(e,b.lastCoordinatorAdminStatus);const t=localStorage.getItem(Zc);return t&&(Jn.includes(t)||Gm.includes(t))?ji(t,b.lastCoordinatorAdminStatus):"feed"}function $k(){const e=tl();if(e)return e;const t=localStorage.getItem(Zc);return t==="coordinator-admin"?"teams":t==="sync"?"sync":localStorage.getItem(Hm)==="teams"?"teams":"sync"}function nl(e,t=!1){b.advancedSection=e,localStorage.setItem(Hm,e),t&&(window.location.hash=`advanced/${e}`)}function Ym(e,t={}){const n=ji(e,b.lastCoordinatorAdminStatus);b.activeTab=n,localStorage.setItem(Zc,n);const r=el();t.canonicalHash?window.location.hash=n:r!==n&&(window.location.hash=n==="advanced"?`advanced/${b.advancedSection}`:n)}function Mk(){const e=localStorage.getItem(qm)||"all";return zm.includes(e)?e:"all"}function Ok(){const e=localStorage.getItem(Km)||"all";return Jm.includes(e)?e:"all"}function jk(e){b.feedTypeFilter=zm.includes(e)?e:"all",localStorage.setItem(qm,b.feedTypeFilter)}function Xm(e){b.feedScopeFilter=Jm.includes(e)?e:"all",localStorage.setItem(Km,b.feedScopeFilter)}function Fk(){return localStorage.getItem(Rk)==="1"}function Bk(e){b.syncPairingOpen=e;try{localStorage.setItem(Vm,e?"1":"0")}catch{}}function Fi(){return localStorage.getItem(Wm)!=="0"}function Uk(e){localStorage.setItem(Wm,e?"1":"0")}function Gk(){b.activeTab=Lk(),b.advancedSection=$k(),b.feedTypeFilter=Mk(),b.feedScopeFilter=Ok(),b.syncDiagnosticsOpen=Fk();try{b.syncPairingOpen=localStorage.getItem(Vm)==="1"}catch{b.syncPairingOpen=!1}}var rl=[{id:"light",label:"Light",mode:"light"},{id:"dark",label:"Dark",mode:"dark"}],Qm="codemem-theme";function Zm(e){const t=rl.find(r=>r.id===e);if(t)return t;const n=e.startsWith("dark")?"dark":"light";return rl.find(r=>r.id===n)||rl[0]}function il(){const e=localStorage.getItem(Qm);return e?Zm(e).id:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function eh(e){const t=Zm(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(Qm,t.id)}function Hk(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(il()==="dark"?"dark":"light"),e.addEventListener("click",()=>{const n=il()==="dark"?"light":"dark";eh(n),t(n)})}var qk=Bn(void 0);function Bi(e){const t=vn(qk);return e||t||"ltr"}var ol="rovingFocusGroup.onEntryFocus",Kk={bubbles:!1,cancelable:!0},Ui="RovingFocusGroup",[al,th,Vk]=_a(Ui),[Wk,Mr]=ot(Ui,[Vk]),[zk,Jk]=Wk(Ui),nh=H((e,t)=>a(al.Provider,{scope:e.__scopeRovingFocusGroup,children:a(al.Slot,{scope:e.__scopeRovingFocusGroup,children:a(Yk,{...e,ref:t})})}));nh.displayName=Ui;var Yk=H((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:o,currentTabStopId:s,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:l,onEntryFocus:d,preventScrollOnEntryFocus:u=!1,...p}=e,f=U(null),m=_e(t,f),v=Bi(o),[h,g]=Ct({prop:s,defaultProp:c??null,onChange:l,caller:Ui}),[_,w]=D(!1),S=st(d),N=th(n),k=U(!1),[E,R]=D(0);return K(()=>{const j=f.current;if(j)return j.addEventListener(ol,S),()=>j.removeEventListener(ol,S)},[S]),a(zk,{scope:n,orientation:r,dir:v,loop:i,currentTabStopId:h,onItemFocus:ie(j=>g(j),[g]),onItemShiftTab:ie(()=>w(!0),[]),onFocusableItemAdd:ie(()=>R(j=>j+1),[]),onFocusableItemRemove:ie(()=>R(j=>j-1),[]),children:a(se.div,{tabIndex:_||E===0?-1:0,"data-orientation":r,...p,ref:m,style:{outline:"none",...e.style},onMouseDown:z(e.onMouseDown,()=>{k.current=!0}),onFocus:z(e.onFocus,j=>{const q=!k.current;if(j.target===j.currentTarget&&q&&!_){const I=new CustomEvent(ol,Kk);if(j.currentTarget.dispatchEvent(I),!I.defaultPrevented){const G=N().filter(A=>A.focusable);oh([G.find(A=>A.active),G.find(A=>A.id===h),...G].filter(Boolean).map(A=>A.ref.current),u)}}k.current=!1}),onBlur:z(e.onBlur,()=>w(!1))})})}),rh="RovingFocusGroupItem",ih=H((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:o,children:s,...c}=e,l=at(),d=o||l,u=Jk(rh,n),p=u.currentTabStopId===d,f=th(n),{onFocusableItemAdd:m,onFocusableItemRemove:v,currentTabStopId:h}=u;return K(()=>{if(r)return m(),()=>v()},[r,m,v]),a(al.ItemSlot,{scope:n,id:d,focusable:r,active:i,children:a(se.span,{tabIndex:p?0:-1,"data-orientation":u.orientation,...c,ref:t,onMouseDown:z(e.onMouseDown,g=>{r?u.onItemFocus(d):g.preventDefault()}),onFocus:z(e.onFocus,()=>u.onItemFocus(d)),onKeyDown:z(e.onKeyDown,g=>{if(g.key==="Tab"&&g.shiftKey){u.onItemShiftTab();return}if(g.target!==g.currentTarget)return;const _=Zk(g,u.orientation,u.dir);if(_!==void 0){if(g.metaKey||g.ctrlKey||g.altKey||g.shiftKey)return;g.preventDefault();let w=f().filter(S=>S.focusable).map(S=>S.ref.current);if(_==="last")w.reverse();else if(_==="prev"||_==="next"){_==="prev"&&w.reverse();const S=w.indexOf(g.currentTarget);w=u.loop?eT(w,S+1):w.slice(S+1)}setTimeout(()=>oh(w))}}),children:typeof s=="function"?s({isCurrentTabStop:p,hasTabStop:h!=null}):s})})});ih.displayName=rh;var Xk={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Qk(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Zk(e,t,n){const r=Qk(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Xk[r]}function oh(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function eT(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var sl=nh,cl=ih,ka="Tabs",[tT,Tj]=ot(ka,[Mr]),ah=Mr(),[nT,ll]=tT(ka),sh=H((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:i,defaultValue:o,orientation:s="horizontal",dir:c,activationMode:l="automatic",...d}=e,u=Bi(c),[p,f]=Ct({prop:r,onChange:i,defaultProp:o??"",caller:ka});return a(nT,{scope:n,baseId:at(),value:p,onValueChange:f,orientation:s,dir:u,activationMode:l,children:a(se.div,{dir:u,"data-orientation":s,...d,ref:t})})});sh.displayName=ka;var ch="TabsList",lh=H((e,t)=>{const{__scopeTabs:n,loop:r=!0,...i}=e,o=ll(ch,n),s=ah(n);return a(sl,{asChild:!0,...s,orientation:o.orientation,dir:o.dir,loop:r,children:a(se.div,{role:"tablist","aria-orientation":o.orientation,...i,ref:t})})});lh.displayName=ch;var dh="TabsTrigger",uh=H((e,t)=>{const{__scopeTabs:n,value:r,disabled:i=!1,...o}=e,s=ll(dh,n),c=ah(n),l=mh(s.baseId,r),d=hh(s.baseId,r),u=r===s.value;return a(cl,{asChild:!0,...c,focusable:!i,active:u,children:a(se.button,{type:"button",role:"tab","aria-selected":u,"aria-controls":d,"data-state":u?"active":"inactive","data-disabled":i?"":void 0,disabled:i,id:l,...o,ref:t,onMouseDown:z(e.onMouseDown,p=>{!i&&p.button===0&&p.ctrlKey===!1?s.onValueChange(r):p.preventDefault()}),onKeyDown:z(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&s.onValueChange(r)}),onFocus:z(e.onFocus,()=>{const p=s.activationMode!=="manual";!u&&!i&&p&&s.onValueChange(r)})})})});uh.displayName=dh;var ph="TabsContent",fh=H((e,t)=>{const{__scopeTabs:n,value:r,forceMount:i,children:o,...s}=e,c=ll(ph,n),l=mh(c.baseId,r),d=hh(c.baseId,r),u=r===c.value,p=U(u);return K(()=>{const f=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(f)},[]),a(et,{present:i||u,children:({present:f})=>a(se.div,{"data-state":u?"active":"inactive","data-orientation":c.orientation,role:"tabpanel","aria-labelledby":l,hidden:!f,id:d,tabIndex:0,...s,ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0},children:f&&o})})});fh.displayName=ph;function mh(e,t){return`${e}-trigger-${t}`}function hh(e,t){return`${e}-content-${t}`}var rT=sh,iT=lh,oT=uh,aT=fh;function vh({ariaLabel:e,children:t,listClassName:n,onValueChange:r,tabs:i,triggerClassName:o,value:s}){return a(rT,{onValueChange:r,value:s,children:[a(iT,{"aria-label":e,className:n,children:i.map(c=>a(oT,{className:o,disabled:c.disabled,value:c.value,children:c.label},c.value))}),t]})}function Yn({children:e,className:t,forceMount:n=!1,value:r}){return a(aT,{className:t,forceMount:n?!0:void 0,value:r,children:e})}function we(e){return a("input",{...e})}function sT(e,t){const n=String(e.device_id||"").trim(),r=String(e.group_id||t||"").trim(),i=String(e.display_name||n||"Unnamed device"),o=e.enabled!==!1&&e.enabled!==0,s=[`Device ID ${n||"unknown"}`];return r&&s.push(`Team ID ${r}`),{advancedDetail:`Advanced: ${s.join(" · ")}`,deviceId:n,displayName:i,statusLabel:o?"Enabled in this Team":"Disabled in this Team",teamId:r}}var cT="codemem-coordinator-admin-target-group",F={activeSection:"groups",inviteGroup:"",inviteTtlHours:"24",invitePolicy:"auto_admit",invitePending:!1,showArchivedGroups:!1,createGroupId:"",createGroupDisplayName:"",groupActionPendingId:"",groupActionPendingKind:"",joinReviewPendingId:"",joinReviewPendingAction:"",deviceActionPendingId:"",deviceActionPendingKind:"",groupRenameDrafts:new Map,deviceRenameDrafts:new Map,deviceRenameServerNames:new Map,groupPreferencesOpen:new Set,groupPreferencesDrafts:new Map,groupScopeManagementOpen:new Set,groupScopeManagementDrafts:new Map,teamSetupGuide:null,availableProjects:[]};function lT(e){const{summary:t,runDevice:n}=e,r=Array.isArray(b.lastCoordinatorAdminDevices)?b.lastCoordinatorAdminDevices:[];return y(Yn,{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 Team devices here. Space access is granted from Spaces below; Team membership alone does not share memories.":"Finish setup first. Device administration stays disabled until Teams is ready."),r.length?y("div",{class:"peer-list"},r.map(i=>{const o=sT(i,String(b.lastCoordinatorAdminStatus?.active_group||"")),{deviceId:s,displayName:c,teamId:l}=o,d=F.deviceActionPendingId===s,u=F.deviceRenameDrafts.get(s)??String(i.display_name||""),p=i.enabled!==!1&&i.enabled!==0,f=!s||d||t.readiness!=="ready";return y("div",{class:"peer-card peer-card--padded",key:s||String(i.fingerprint||"unknown")},y("div",{class:"peer-title"},y("strong",null,c)),y("div",{class:"peer-submeta"},o.statusLabel),y("div",{class:"peer-meta"},o.advancedDetail),y("form",{class:"coordinator-admin-form",onSubmit:m=>{m.preventDefault(),!f&&n(s,l,c,"rename")}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"Display name"),y(we,{class:"peer-scope-input",disabled:t.readiness!=="ready"||d,onInput:m=>{F.deviceRenameDrafts.set(s,String(m.currentTarget.value||""))},type:"text",value:u}))),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:f,type:"submit"},d&&F.deviceActionPendingKind==="rename"?"Renaming…":"Rename"),p?y("button",{class:"settings-button danger",disabled:f,onClick:()=>n(s,l,c,"disable"),type:"button"},d&&F.deviceActionPendingKind==="disable"?"Disabling…":"Disable"):y("button",{class:"settings-button",disabled:f,onClick:()=>n(s,l,c,"enable"),type:"button"},d&&F.deviceActionPendingKind==="enable"?"Enabling…":"Enable"),y("button",{class:"settings-button danger",disabled:f,onClick:()=>n(s,l,c,"remove"),type:"button"},d&&F.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."))}var Ta="Collapsible",[dT,Ij]=ot(Ta),[uT,dl]=dT(Ta),gh=H((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:i,disabled:o,onOpenChange:s,...c}=e,[l,d]=Ct({prop:r,defaultProp:i??!1,onChange:s,caller:Ta});return a(uT,{scope:n,disabled:o,contentId:at(),open:l,onOpenToggle:ie(()=>d(u=>!u),[d]),children:a(se.div,{"data-state":pl(l),"data-disabled":o?"":void 0,...c,ref:t})})});gh.displayName=Ta;var yh="CollapsibleTrigger",bh=H((e,t)=>{const{__scopeCollapsible:n,...r}=e,i=dl(yh,n);return a(se.button,{type:"button","aria-controls":i.contentId,"aria-expanded":i.open||!1,"data-state":pl(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...r,ref:t,onClick:z(e.onClick,i.onOpenToggle)})});bh.displayName=yh;var ul="CollapsibleContent",_h=H((e,t)=>{const{forceMount:n,...r}=e,i=dl(ul,e.__scopeCollapsible);return a(et,{present:n||i.open,children:({present:o})=>a(pT,{...r,ref:t,present:o})})});_h.displayName=ul;var pT=H((e,t)=>{const{__scopeCollapsible:n,present:r,children:i,...o}=e,s=dl(ul,n),[c,l]=D(r),d=U(null),u=_e(t,d),p=U(0),f=p.current,m=U(0),v=m.current,h=s.open||c,g=U(h),_=U(void 0);return K(()=>{const w=requestAnimationFrame(()=>g.current=!1);return()=>cancelAnimationFrame(w)},[]),Ve(()=>{const w=d.current;if(w){_.current=_.current||{transitionDuration:w.style.transitionDuration,animationName:w.style.animationName},w.style.transitionDuration="0s",w.style.animationName="none";const S=w.getBoundingClientRect();p.current=S.height,m.current=S.width,g.current||(w.style.transitionDuration=_.current.transitionDuration,w.style.animationName=_.current.animationName),l(r)}},[s.open,r]),a(se.div,{"data-state":pl(s.open),"data-disabled":s.disabled?"":void 0,id:s.contentId,hidden:!h,...o,ref:u,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":v?`${v}px`:void 0,...e.style},children:h&&i})});function pl(e){return e?"open":"closed"}var Ia=gh,wh=bh,Ea=_h,fT=["top","right","bottom","left"],yn=Math.min,yt=Math.max,xa=Math.round,Pa=Math.floor,Bt=e=>({x:e,y:e}),mT={left:"right",right:"left",bottom:"top",top:"bottom"};function fl(e,t,n){return yt(e,yn(t,n))}function on(e,t){return typeof e=="function"?e(t):e}function an(e){return e.split("-")[0]}function Or(e){return e.split("-")[1]}function ml(e){return e==="x"?"y":"x"}function hl(e){return e==="y"?"height":"width"}function Ut(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function vl(e){return ml(Ut(e))}function hT(e,t,n){n===void 0&&(n=!1);const r=Or(e),i=vl(e),o=hl(i);let s=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(s=Aa(s)),[s,Aa(s)]}function vT(e){const t=Aa(e);return[gl(e),t,gl(t)]}function gl(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}var Sh=["left","right"],Ch=["right","left"],gT=["top","bottom"],yT=["bottom","top"];function bT(e,t,n){switch(e){case"top":case"bottom":return n?t?Ch:Sh:t?Sh:Ch;case"left":case"right":return t?gT:yT;default:return[]}}function _T(e,t,n,r){const i=Or(e);let o=bT(an(e),n==="start",r);return i&&(o=o.map(s=>s+"-"+i),t&&(o=o.concat(o.map(gl)))),o}function Aa(e){const t=an(e);return mT[t]+e.slice(t.length)}function wT(e){return{top:0,right:0,bottom:0,left:0,...e}}function Nh(e){return typeof e!="number"?wT(e):{top:e,right:e,bottom:e,left:e}}function Ra(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 kh(e,t,n){let{reference:r,floating:i}=e;const o=Ut(t),s=vl(t),c=hl(s),l=an(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(Or(t)){case"start":m[s]-=f*(n&&d?-1:1);break;case"end":m[s]+=f*(n&&d?-1:1);break}return m}async function ST(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}=on(t,e),v=Nh(m),h=c[f?p==="floating"?"reference":"floating":p],g=Ra(await o.getClippingRect({element:(n=await(o.isElement==null?void 0:o.isElement(h)))==null||n?h:h.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(c.floating)),boundary:d,rootBoundary:u,strategy:l})),_=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)),S=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},N=Ra(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:_,offsetParent:w,strategy:l}):_);return{top:(g.top-N.top+v.top)/S.y,bottom:(N.bottom-g.bottom+v.bottom)/S.y,left:(g.left-N.left+v.left)/S.x,right:(N.right-g.right+v.right)/S.x}}var CT=50,NT=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:s}=n,c=s.detectOverflow?s:{...s,detectOverflow:ST},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}=kh(d,r,l),f=r,m=0;const v={};for(let h=0;h<o.length;h++){const g=o[h];if(!g)continue;const{name:_,fn:w}=g,{x:S,y:N,data:k,reset:E}=await w({x:u,y:p,initialPlacement:r,placement:f,strategy:i,middlewareData:v,rects:d,platform:c,elements:{reference:e,floating:t}});u=S??u,p=N??p,v[_]={...v[_],...k},E&&m<CT&&(m++,typeof E=="object"&&(E.placement&&(f=E.placement),E.rects&&(d=E.rects===!0?await s.getElementRects({reference:e,floating:t,strategy:i}):E.rects),{x:u,y:p}=kh(d,f,l)),h=-1)}return{x:u,y:p,placement:f,strategy:i,middlewareData:v}},kT=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}=on(e,t)||{};if(d==null)return{};const p=Nh(u),f={x:n,y:r},m=vl(i),v=hl(m),h=await s.getDimensions(d),g=m==="y",_=g?"top":"left",w=g?"bottom":"right",S=g?"clientHeight":"clientWidth",N=o.reference[v]+o.reference[m]-f[m]-o.floating[v],k=f[m]-o.reference[m],E=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let R=E?E[S]:0;(!R||!await(s.isElement==null?void 0:s.isElement(E)))&&(R=c.floating[S]||o.floating[v]);const j=N/2-k/2,q=R/2-h[v]/2-1,I=yn(p[_],q),G=yn(p[w],q),A=I,M=R-h[v]-G,L=R/2-h[v]/2+j,x=fl(A,L,M),O=!l.arrow&&Or(i)!=null&&L!==x&&o.reference[v]/2-(L<A?I:G)-h[v]/2<0,T=O?L<A?L-A:L-M:0;return{[m]:f[m]+T,data:{[m]:x,centerOffset:L-x-T,...O&&{alignmentOffset:T}},reset:O}}}),TT=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:h=!0,...g}=on(e,t);if((n=o.arrow)!=null&&n.alignmentOffset)return{};const _=an(i),w=Ut(c),S=an(c)===c,N=await(l.isRTL==null?void 0:l.isRTL(d.floating)),k=f||(S||!h?[Aa(c)]:vT(c)),E=v!=="none";!f&&E&&k.push(..._T(c,h,v,N));const R=[c,...k],j=await l.detectOverflow(t,g),q=[];let I=((r=o.flip)==null?void 0:r.overflows)||[];if(u&&q.push(j[_]),p){const L=hT(i,s,N);q.push(j[L[0]],j[L[1]])}if(I=[...I,{placement:i,overflows:q}],!q.every(L=>L<=0)){var G,A;const L=(((G=o.flip)==null?void 0:G.index)||0)+1,x=R[L];if(x&&(!(p==="alignment"&&w!==Ut(x))||I.every(T=>Ut(T.placement)===w?T.overflows[0]>0:!0)))return{data:{index:L,overflows:I},reset:{placement:x}};let O=(A=I.filter(T=>T.overflows[0]<=0).sort((T,P)=>T.overflows[1]-P.overflows[1])[0])==null?void 0:A.placement;if(!O)switch(m){case"bestFit":{var M;const T=(M=I.filter(P=>{if(E){const B=Ut(P.placement);return B===w||B==="y"}return!0}).map(P=>[P.placement,P.overflows.filter(B=>B>0).reduce((B,V)=>B+V,0)]).sort((P,B)=>P[1]-B[1])[0])==null?void 0:M[0];T&&(O=T);break}case"initialPlacement":O=c;break}if(i!==O)return{reset:{placement:O}}}return{}}}};function Th(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Ih(e){return fT.some(t=>e[t]>=0)}var IT=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...o}=on(e,t);switch(i){case"referenceHidden":{const s=Th(await r.detectOverflow(t,{...o,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:Ih(s)}}}case"escaped":{const s=Th(await r.detectOverflow(t,{...o,altBoundary:!0}),n.floating);return{data:{escapedOffsets:s,escaped:Ih(s)}}}default:return{}}}}},Eh=new Set(["left","top"]);async function ET(e,t){const{placement:n,platform:r,elements:i}=e,o=await(r.isRTL==null?void 0:r.isRTL(i.floating)),s=an(n),c=Or(n),l=Ut(n)==="y",d=Eh.has(s)?-1:1,u=o&&l?-1:1,p=on(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 xT=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 ET(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}}}}},PT=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:_=>{let{x:w,y:S}=_;return{x:w,y:S}}},...d}=on(e,t),u={x:n,y:r},p=await o.detectOverflow(t,d),f=Ut(an(i)),m=ml(f);let v=u[m],h=u[f];if(s){const _=m==="y"?"top":"left",w=m==="y"?"bottom":"right",S=v+p[_],N=v-p[w];v=fl(S,v,N)}if(c){const _=f==="y"?"top":"left",w=f==="y"?"bottom":"right",S=h+p[_],N=h-p[w];h=fl(S,h,N)}const g=l.fn({...t,[m]:v,[f]:h});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[m]:s,[f]:c}}}}}},AT=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}=on(e,t),u={x:n,y:r},p=Ut(i),f=ml(p);let m=u[f],v=u[p];const h=on(c,t),g=typeof h=="number"?{mainAxis:h,crossAxis:0}:{mainAxis:0,crossAxis:0,...h};if(l){const S=f==="y"?"height":"width",N=o.reference[f]-o.floating[S]+g.mainAxis,k=o.reference[f]+o.reference[S]-g.mainAxis;m<N?m=N:m>k&&(m=k)}if(d){var _,w;const S=f==="y"?"width":"height",N=Eh.has(an(i)),k=o.reference[p]-o.floating[S]+(N&&((_=s.offset)==null?void 0:_[p])||0)+(N?0:g.crossAxis),E=o.reference[p]+o.reference[S]+(N?0:((w=s.offset)==null?void 0:w[p])||0)-(N?g.crossAxis:0);v<k?v=k:v>E&&(v=E)}return{[f]:m,[p]:v}}}},RT=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}=on(e,t),u=await s.detectOverflow(t,d),p=an(i),f=Or(i),m=Ut(i)==="y",{width:v,height:h}=o.floating;let g,_;p==="top"||p==="bottom"?(g=p,_=f===(await(s.isRTL==null?void 0:s.isRTL(c.floating))?"start":"end")?"left":"right"):(_=p,g=f==="end"?"top":"bottom");const w=h-u.top-u.bottom,S=v-u.left-u.right,N=yn(h-u[g],w),k=yn(v-u[_],S),E=!t.middlewareData.shift;let R=N,j=k;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(j=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(R=w),E&&!f){const I=yt(u.left,0),G=yt(u.right,0),A=yt(u.top,0),M=yt(u.bottom,0);m?j=v-2*(I!==0||G!==0?I+G:yt(u.left,u.right)):R=h-2*(A!==0||M!==0?A+M:yt(u.top,u.bottom))}await l({...t,availableWidth:j,availableHeight:R});const q=await s.getDimensions(c.floating);return v!==q.width||h!==q.height?{reset:{rects:!0}}:{}}}};function Da(){return typeof window<"u"}function jr(e){return xh(e)?(e.nodeName||"").toLowerCase():"#document"}function bt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Gt(e){var t;return(t=(xh(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function xh(e){return Da()?e instanceof Node||e instanceof bt(e).Node:!1}function At(e){return Da()?e instanceof Element||e instanceof bt(e).Element:!1}function sn(e){return Da()?e instanceof HTMLElement||e instanceof bt(e).HTMLElement:!1}function Ph(e){return!Da()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof bt(e).ShadowRoot}function Gi(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Rt(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function DT(e){return/^(table|td|th)$/.test(jr(e))}function La(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}var LT=/transform|translate|scale|rotate|perspective|filter/,$T=/paint|layout|strict|content/,Xn=e=>!!e&&e!=="none",yl;function bl(e){const t=At(e)?Rt(e):e;return Xn(t.transform)||Xn(t.translate)||Xn(t.scale)||Xn(t.rotate)||Xn(t.perspective)||!_l()&&(Xn(t.backdropFilter)||Xn(t.filter))||LT.test(t.willChange||"")||$T.test(t.contain||"")}function MT(e){let t=bn(e);for(;sn(t)&&!Fr(t);){if(bl(t))return t;if(La(t))return null;t=bn(t)}return null}function _l(){return yl==null&&(yl=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),yl}function Fr(e){return/^(html|body|#document)$/.test(jr(e))}function Rt(e){return bt(e).getComputedStyle(e)}function $a(e){return At(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function bn(e){if(jr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Ph(e)&&e.host||Gt(e);return Ph(t)?t.host:t}function Ah(e){const t=bn(e);return Fr(t)?e.ownerDocument?e.ownerDocument.body:e.body:sn(t)&&Gi(t)?t:Ah(t)}function Hi(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=Ah(e),o=i===((r=e.ownerDocument)==null?void 0:r.body),s=bt(i);if(o){const c=wl(s);return t.concat(s,s.visualViewport||[],Gi(i)?i:[],c&&n?Hi(c):[])}else return t.concat(i,Hi(i,[],n))}function wl(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Rh(e){const t=Rt(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=sn(e),o=i?e.offsetWidth:n,s=i?e.offsetHeight:r,c=xa(n)!==o||xa(r)!==s;return c&&(n=o,r=s),{width:n,height:r,$:c}}function Sl(e){return At(e)?e:e.contextElement}function Br(e){const t=Sl(e);if(!sn(t))return Bt(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=Rh(t);let s=(o?xa(n.width):n.width)/r,c=(o?xa(n.height):n.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!c||!Number.isFinite(c))&&(c=1),{x:s,y:c}}var OT=Bt(0);function Dh(e){const t=bt(e);return!_l()||!t.visualViewport?OT:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function jT(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==bt(e)?!1:t}function Qn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),o=Sl(e);let s=Bt(1);t&&(r?At(r)&&(s=Br(r)):s=Br(e));const c=jT(o,n,r)?Dh(o):Bt(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=bt(o),m=r&&At(r)?bt(r):r;let v=f,h=wl(v);for(;h&&r&&m!==v;){const g=Br(h),_=h.getBoundingClientRect(),w=Rt(h),S=_.left+(h.clientLeft+parseFloat(w.paddingLeft))*g.x,N=_.top+(h.clientTop+parseFloat(w.paddingTop))*g.y;l*=g.x,d*=g.y,u*=g.x,p*=g.y,l+=S,d+=N,v=bt(h),h=wl(v)}}return Ra({width:u,height:p,x:l,y:d})}function Ma(e,t){const n=$a(e).scrollLeft;return t?t.left+n:Qn(Gt(e)).left+n}function Lh(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Ma(e,n),y:n.top+t.scrollTop}}function FT(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o=i==="fixed",s=Gt(r),c=t?La(t.floating):!1;if(r===s||c&&o)return n;let l={scrollLeft:0,scrollTop:0},d=Bt(1);const u=Bt(0),p=sn(r);if((p||!p&&!o)&&((jr(r)!=="body"||Gi(s))&&(l=$a(r)),p)){const m=Qn(r);d=Br(r),u.x=m.x+r.clientLeft,u.y=m.y+r.clientTop}const f=s&&!p&&!o?Lh(s,l):Bt(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 BT(e){return Array.from(e.getClientRects())}function UT(e){const t=Gt(e),n=$a(e),r=e.ownerDocument.body,i=yt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),o=yt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+Ma(e);const c=-n.scrollTop;return Rt(r).direction==="rtl"&&(s+=yt(t.clientWidth,r.clientWidth)-i),{width:i,height:o,x:s,y:c}}var $h=25;function GT(e,t){const n=bt(e),r=Gt(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=_l();(!u||u&&t==="fixed")&&(c=i.offsetLeft,l=i.offsetTop)}const d=Ma(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<=$h&&(o-=v)}else d<=$h&&(o+=d);return{width:o,height:s,x:c,y:l}}function HT(e,t){const n=Qn(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=sn(e)?Br(e):Bt(1);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}function Mh(e,t,n){let r;if(t==="viewport")r=GT(e,n);else if(t==="document")r=UT(Gt(e));else if(At(t))r=HT(t,n);else{const i=Dh(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Ra(r)}function Oh(e,t){const n=bn(e);return n===t||!At(n)||Fr(n)?!1:Rt(n).position==="fixed"||Oh(n,t)}function qT(e,t){const n=t.get(e);if(n)return n;let r=Hi(e,[],!1).filter(c=>At(c)&&jr(c)!=="body"),i=null;const o=Rt(e).position==="fixed";let s=o?bn(e):e;for(;At(s)&&!Fr(s);){const c=Rt(s),l=bl(s);!l&&c.position==="fixed"&&(i=null),(o?!l&&!i:!l&&c.position==="static"&&i&&(i.position==="absolute"||i.position==="fixed")||Gi(s)&&!l&&Oh(e,s))?r=r.filter(d=>d!==s):i=c,s=bn(s)}return t.set(e,r),r}function KT(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[...n==="clippingAncestors"?La(t)?[]:qT(t,this._c):[].concat(n),r],s=Mh(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=Mh(t,o[p],i);c=yt(f.top,c),l=yn(f.right,l),d=yn(f.bottom,d),u=yt(f.left,u)}return{width:l-u,height:d-c,x:u,y:c}}function VT(e){const{width:t,height:n}=Rh(e);return{width:t,height:n}}function WT(e,t,n){const r=sn(t),i=Gt(t),o=n==="fixed",s=Qn(e,!0,o,t);let c={scrollLeft:0,scrollTop:0};const l=Bt(0);function d(){l.x=Ma(i)}if(r||!r&&!o)if((jr(t)!=="body"||Gi(i))&&(c=$a(t)),r){const p=Qn(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?Lh(i,c):Bt(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 Cl(e){return Rt(e).position==="static"}function jh(e,t){if(!sn(e)||Rt(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Gt(e)===n&&(n=n.ownerDocument.body),n}function Fh(e,t){const n=bt(e);if(La(e))return n;if(!sn(e)){let i=bn(e);for(;i&&!Fr(i);){if(At(i)&&!Cl(i))return i;i=bn(i)}return n}let r=jh(e,t);for(;r&&DT(r)&&Cl(r);)r=jh(r,t);return r&&Fr(r)&&Cl(r)&&!bl(r)?n:r||MT(e)||n}var zT=async function(e){const t=this.getOffsetParent||Fh,n=this.getDimensions,r=await n(e.floating);return{reference:WT(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function JT(e){return Rt(e).direction==="rtl"}var YT={convertOffsetParentRelativeRectToViewportRelativeRect:FT,getDocumentElement:Gt,getClippingRect:KT,getOffsetParent:Fh,getElementRects:zT,getClientRects:BT,getDimensions:VT,getScale:Br,isElement:At,isRTL:JT};function Bh(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function XT(e,t){let n=null,r;const i=Gt(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=Pa(p),h=Pa(i.clientWidth-(u+f)),g=Pa(i.clientHeight-(p+m)),_=Pa(u),w={rootMargin:-v+"px "+-h+"px "+-g+"px "+-_+"px",threshold:yt(0,yn(1,l))||1};let S=!0;function N(k){const E=k[0].intersectionRatio;if(E!==l){if(!S)return s();E?s(!1,E):r=setTimeout(()=>{s(!1,1e-7)},1e3)}E===1&&!Bh(d,e.getBoundingClientRect())&&s(),S=!1}try{n=new IntersectionObserver(N,{...w,root:i.ownerDocument})}catch{n=new IntersectionObserver(N,w)}n.observe(e)}return s(!0),o}function QT(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=Sl(e),u=i||o?[...d?Hi(d):[],...t?Hi(t):[]]:[];u.forEach(_=>{i&&_.addEventListener("scroll",n,{passive:!0}),o&&_.addEventListener("resize",n)});const p=d&&c?XT(d,n):null;let f=-1,m=null;s&&(m=new ResizeObserver(_=>{let[w]=_;w&&w.target===d&&m&&t&&(m.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var S;(S=m)==null||S.observe(t)})),n()}),d&&!l&&m.observe(d),t&&m.observe(t));let v,h=l?Qn(e):null;l&&g();function g(){const _=Qn(e);h&&!Bh(h,_)&&n(),h=_,v=requestAnimationFrame(g)}return n(),()=>{var _;u.forEach(w=>{i&&w.removeEventListener("scroll",n),o&&w.removeEventListener("resize",n)}),p?.(),(_=m)==null||_.disconnect(),m=null,l&&cancelAnimationFrame(v)}}var ZT=xT,eI=PT,tI=TT,nI=RT,rI=IT,Uh=kT,iI=AT,oI=(e,t,n)=>{const r=new Map,i={platform:YT,...n},o={...i.platform,_c:r};return NT(e,t,{...i,platform:o})},Oa=typeof document<"u"?gt:function(){};function ja(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(!ja(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)&&!ja(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function Gh(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Hh(e,t){const n=Gh(e);return Math.round(t*n)/n}function Nl(e){const t=U(e);return Oa(()=>{t.current=e}),t}function aI(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]=D({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=D(r);ja(f,r)||m(r);const[v,h]=D(null),[g,_]=D(null),w=ie(P=>{P!==E.current&&(E.current=P,h(P))},[]),S=ie(P=>{P!==R.current&&(R.current=P,_(P))},[]),N=o||v,k=s||g,E=U(null),R=U(null),j=U(u),q=l!=null,I=Nl(l),G=Nl(i),A=Nl(d),M=ie(()=>{if(!E.current||!R.current)return;const P={placement:t,strategy:n,middleware:f};G.current&&(P.platform=G.current),oI(E.current,R.current,P).then(B=>{const V={...B,isPositioned:A.current!==!1};L.current&&!ja(j.current,V)&&(j.current=V,zo(()=>{p(V)}))})},[f,t,n,G,A]);Oa(()=>{d===!1&&j.current.isPositioned&&(j.current.isPositioned=!1,p(P=>({...P,isPositioned:!1})))},[d]);const L=U(!1);Oa(()=>(L.current=!0,()=>{L.current=!1}),[]),Oa(()=>{if(N&&(E.current=N),k&&(R.current=k),N&&k){if(I.current)return I.current(N,k,M);M()}},[N,k,M,I,q]);const x=Ee(()=>({reference:E,floating:R,setReference:w,setFloating:S}),[w,S]),O=Ee(()=>({reference:N,floating:k}),[N,k]),T=Ee(()=>{const P={position:n,left:0,top:0};if(!O.floating)return P;const B=Hh(O.floating,u.x),V=Hh(O.floating,u.y);return c?{...P,transform:"translate("+B+"px, "+V+"px)",...Gh(O.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:B,top:V}},[n,c,O.floating,u.x,u.y]);return Ee(()=>({...u,update:M,refs:x,elements:O,floatingStyles:T}),[u,M,x,O,T])}var sI=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?Uh({element:r.current,padding:i}).fn(n):{}:r?Uh({element:r,padding:i}).fn(n):{}}}},cI=(e,t)=>{const n=ZT(e);return{name:n.name,fn:n.fn,options:[e,t]}},lI=(e,t)=>{const n=eI(e);return{name:n.name,fn:n.fn,options:[e,t]}},dI=(e,t)=>({fn:iI(e).fn,options:[e,t]}),uI=(e,t)=>{const n=tI(e);return{name:n.name,fn:n.fn,options:[e,t]}},pI=(e,t)=>{const n=nI(e);return{name:n.name,fn:n.fn,options:[e,t]}},fI=(e,t)=>{const n=rI(e);return{name:n.name,fn:n.fn,options:[e,t]}},mI=(e,t)=>{const n=sI(e);return{name:n.name,fn:n.fn,options:[e,t]}},hI="Arrow",qh=H((e,t)=>{const{children:n,width:r=10,height:i=5,...o}=e;return a(se.svg,{...o,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:a("polygon",{points:"0,0 30,0 15,10"})})});qh.displayName=hI;var vI=qh;function kl(e){const[t,n]=D(void 0);return Ve(()=>{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}var Tl="Popper",[Kh,_n]=ot(Tl),[gI,Vh]=Kh(Tl),Wh=e=>{const{__scopePopper:t,children:n}=e,[r,i]=D(null);return a(gI,{scope:t,anchor:r,onAnchorChange:i,children:n})};Wh.displayName=Tl;var zh="PopperAnchor",Jh=H((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,o=Vh(zh,n),s=U(null),c=_e(t,s),l=U(null);return K(()=>{const d=l.current;l.current=r?.current||s.current,d!==l.current&&o.onAnchorChange(l.current)}),r?null:a(se.div,{...i,ref:c})});Jh.displayName=zh;var Il="PopperContent",[yI,bI]=Kh(Il),Yh=H((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:o="center",alignOffset:s=0,arrowPadding:c=0,avoidCollisions:l=!0,collisionBoundary:d=[],collisionPadding:u=0,sticky:p="partial",hideWhenDetached:f=!1,updatePositionStrategy:m="optimized",onPlaced:v,...h}=e,g=Vh(Il,n),[_,w]=D(null),S=_e(t,ee=>w(ee)),[N,k]=D(null),E=kl(N),R=E?.width??0,j=E?.height??0,q=r+(o!=="center"?"-"+o:""),I=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},G=Array.isArray(d)?d:[d],A=G.length>0,M={padding:I,boundary:G.filter(wI),altBoundary:A},{refs:L,floatingStyles:x,placement:O,isPositioned:T,middlewareData:P}=aI({strategy:"fixed",placement:q,whileElementsMounted:(...ee)=>QT(...ee,{animationFrame:m==="always"}),elements:{reference:g.anchor},middleware:[cI({mainAxis:i+j,alignmentAxis:s}),l&&lI({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?dI():void 0,...M}),l&&uI({...M}),pI({...M,apply:({elements:ee,rects:Te,availableWidth:fe,availableHeight:te})=>{const{width:Ie,height:ce}=Te.reference,Ae=ee.floating.style;Ae.setProperty("--radix-popper-available-width",`${fe}px`),Ae.setProperty("--radix-popper-available-height",`${te}px`),Ae.setProperty("--radix-popper-anchor-width",`${Ie}px`),Ae.setProperty("--radix-popper-anchor-height",`${ce}px`)}}),N&&mI({element:N,padding:c}),SI({arrowWidth:R,arrowHeight:j}),f&&fI({strategy:"referenceHidden",...M})]}),[B,V]=Zh(O),le=st(v);Ve(()=>{T&&le?.()},[T,le]);const de=P.arrow?.x,ae=P.arrow?.y,be=P.arrow?.centerOffset!==0,[J,ve]=D();return Ve(()=>{_&&ve(window.getComputedStyle(_).zIndex)},[_]),a("div",{ref:L.setFloating,"data-radix-popper-content-wrapper":"",style:{...x,transform:T?x.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:J,"--radix-popper-transform-origin":[P.transformOrigin?.x,P.transformOrigin?.y].join(" "),...P.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:a(yI,{scope:n,placedSide:B,onArrowChange:k,arrowX:de,arrowY:ae,shouldHideArrow:be,children:a(se.div,{"data-side":B,"data-align":V,...h,ref:S,style:{...h.style,animation:T?void 0:"none"}})})})});Yh.displayName=Il;var Xh="PopperArrow",_I={top:"bottom",right:"left",bottom:"top",left:"right"},Qh=H(function(t,n){const{__scopePopper:r,...i}=t,o=bI(Xh,r),s=_I[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(vI,{...i,ref:n,style:{...i.style,display:"block"}})})});Qh.displayName=Xh;function wI(e){return e!==null}var SI=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]=Zh(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}}}});function Zh(e){const[t,n="center"]=e.split("-");return[t,n]}var qi=Wh,Ki=Jh,Fa=Yh,Ba=Qh,Ua="Popover",[ev,Ej]=ot(Ua,[_n]),Vi=_n(),[CI,wn]=ev(Ua),tv=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:o,modal:s=!1}=e,c=Vi(t),l=U(null),[d,u]=D(!1),[p,f]=Ct({prop:r,defaultProp:i??!1,onChange:o,caller:Ua});return a(qi,{...c,children:a(CI,{scope:t,contentId:at(),triggerRef:l,open:p,onOpenChange:f,onOpenToggle:ie(()=>f(m=>!m),[f]),hasCustomAnchor:d,onCustomAnchorAdd:ie(()=>u(!0),[]),onCustomAnchorRemove:ie(()=>u(!1),[]),modal:s,children:n})})};tv.displayName=Ua;var nv="PopoverAnchor",rv=H((e,t)=>{const{__scopePopover:n,...r}=e,i=wn(nv,n),o=Vi(n),{onCustomAnchorAdd:s,onCustomAnchorRemove:c}=i;return K(()=>(s(),()=>c()),[s,c]),a(Ki,{...o,...r,ref:t})});rv.displayName=nv;var iv="PopoverTrigger",ov=H((e,t)=>{const{__scopePopover:n,...r}=e,i=wn(iv,n),o=Vi(n),s=_e(t,i.triggerRef),c=a(se.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":dv(i.open),...r,ref:s,onClick:z(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?c:a(Ki,{asChild:!0,...o,children:c})});ov.displayName=iv;var El="PopoverPortal",[NI,kI]=ev(El,{forceMount:void 0}),av=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,o=wn(El,t);return a(NI,{scope:t,forceMount:n,children:a(et,{present:n||o.open,children:a(qn,{asChild:!0,container:i,children:r})})})};av.displayName=El;var Ur="PopoverContent",sv=H((e,t)=>{const n=kI(Ur,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,o=wn(Ur,e.__scopePopover);return a(et,{present:r||o.open,children:o.modal?a(II,{...i,ref:t}):a(EI,{...i,ref:t})})});sv.displayName=Ur;var TI=Gn("PopoverContent.RemoveScroll"),II=H((e,t)=>{const n=wn(Ur,e.__scopePopover),r=U(null),i=_e(t,r),o=U(!1);return K(()=>{const s=r.current;if(s)return oa(s)},[]),a(Ti,{as:TI,allowPinchZoom:!0,children:a(cv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:z(e.onCloseAutoFocus,s=>{s.preventDefault(),o.current||n.triggerRef.current?.focus()}),onPointerDownOutside:z(e.onPointerDownOutside,s=>{const c=s.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0;o.current=c.button===2||l},{checkForDefaultPrevented:!1}),onFocusOutside:z(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})})}),EI=H((e,t)=>{const n=wn(Ur,e.__scopePopover),r=U(!1),i=U(!1);return a(cv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(r.current||n.triggerRef.current?.focus(),o.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const s=o.target;n.triggerRef.current?.contains(s)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),cv=H((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:s,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:d,onInteractOutside:u,...p}=e,f=wn(Ur,n),m=Vi(n);return Xo(),a(Ni,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:o,children:a(Hn,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:d,onDismiss:()=>f.onOpenChange(!1),children:a(Fa,{"data-state":dv(f.open),role:"dialog",id:f.contentId,...m,...p,ref:t,style:{...p.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)"}})})})}),lv="PopoverClose",xI=H((e,t)=>{const{__scopePopover:n,...r}=e,i=wn(lv,n);return a(se.button,{type:"button",...r,ref:t,onClick:z(e.onClick,()=>i.onOpenChange(!1))})});xI.displayName=lv;var PI="PopoverArrow",AI=H((e,t)=>{const{__scopePopover:n,...r}=e,i=Vi(n);return a(Ba,{...i,...r,ref:t})});AI.displayName=PI;function dv(e){return e?"open":"closed"}var uv=tv,RI=rv,DI=ov,pv=av,fv=sv;function xl(e){return e.trim()}function mv({values:e,onValuesChange:t,availableProjects:n,placeholder:r,emptyLabel:i,disabled:o,"aria-labelledby":s}){const[c,l]=D(!1),[d,u]=D(""),[p,f]=D(0),m=U(null),v=Ee(()=>{const I=new Set,G=[];for(const A of[...n,...e]){const M=xl(A);!M||I.has(M)||(I.add(M),G.push(M))}return G.sort((A,M)=>A.localeCompare(M))},[n,e]),h=xl(d),g=h.toLowerCase(),_=Ee(()=>g?v.filter(I=>I.toLowerCase().includes(g)):v,[v,g]),w=h?v.some(I=>I.toLowerCase()===g):!1,S=!!h&&!w,N=_.length+(S?1:0);K(()=>{p>=N&&f(Math.max(0,N-1))},[N,p]),K(()=>{if(!c)return;const I=requestAnimationFrame(()=>m.current?.focus());return()=>cancelAnimationFrame(I)},[c]);const k=I=>{e.includes(I)?t(e.filter(G=>G!==I)):t(Array.from(new Set([...e,I])))},E=I=>{const G=xl(I);G&&(t(Array.from(new Set([...e,G]))),u(""),f(0))},R=I=>{if(I<_.length){const G=_[I];G&&k(G);return}S&&E(h)},j=I=>{if(I.key==="ArrowDown"){I.preventDefault(),f(G=>Math.min(N-1,G+1));return}if(I.key==="ArrowUp"){I.preventDefault(),f(G=>Math.max(0,G-1));return}if(I.key==="Enter"){I.preventDefault(),R(p);return}},q=I=>{t(e.filter(G=>G!==I))};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(I=>a("li",{class:"project-scope-picker-selected-chip",children:[a("span",{children:I}),o?null:a("button",{"aria-label":`Remove ${I}`,class:"project-scope-picker-selected-remove",onClick:()=>q(I),type:"button",children:"×"})]},I))}),a(uv,{onOpenChange:I=>{l(I),I||(u(""),f(0))},open:c,children:[a(DI,{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(pv,{children:a(fv,{align:"start",class:"project-scope-picker-popover",sideOffset:6,children:[a("input",{"aria-label":"Search projects",class:"project-scope-picker-search",onInput:I=>{u(I.currentTarget.value),f(0)},onKeyDown:j,placeholder:"Search or create…",ref:m,type:"text",value:d}),a("div",{class:"project-scope-picker-results",role:"listbox",children:[_.length===0&&!S?a("div",{class:"project-scope-picker-empty-row",children:"No projects yet. Type a name to create one."}):null,_.map((I,G)=>{const A=e.includes(I);return a("button",{"aria-selected":A,class:G===p?"project-scope-picker-row project-scope-picker-row--active":"project-scope-picker-row",onClick:()=>{f(G),k(I)},onMouseEnter:()=>f(G),role:"option",type:"button",children:[a("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:A?"✓":""}),a("span",{class:"project-scope-picker-row-label",children:I})]},I)}),S?a("button",{"aria-selected":!1,class:p===_.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:()=>E(h),onMouseEnter:()=>f(_.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 "${h}"`})]}):null]})]})})]})]})}function Pl(e){const t=U({value:e,previous:e});return Ee(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Ga="Switch",[LI,xj]=ot(Ga),[$I,MI]=LI(Ga),hv=H((e,t)=>{const{__scopeSwitch:n,name:r,checked:i,defaultChecked:o,required:s,disabled:c,value:l="on",onCheckedChange:d,form:u,...p}=e,[f,m]=D(null),v=_e(t,S=>m(S)),h=U(!1),g=f?u||!!f.closest("form"):!0,[_,w]=Ct({prop:i,defaultProp:o??!1,onChange:d,caller:Ga});return a($I,{scope:n,checked:_,disabled:c,children:[a(se.button,{type:"button",role:"switch","aria-checked":_,"aria-required":s,"data-state":bv(_),"data-disabled":c?"":void 0,disabled:c,value:l,...p,ref:v,onClick:z(e.onClick,S=>{w(N=>!N),g&&(h.current=S.isPropagationStopped(),h.current||S.stopPropagation())})}),g&&a(yv,{control:f,bubbles:!h.current,name:r,value:l,checked:_,required:s,disabled:c,form:u,style:{transform:"translateX(-100%)"}})]})});hv.displayName=Ga;var vv="SwitchThumb",gv=H((e,t)=>{const{__scopeSwitch:n,...r}=e,i=MI(vv,n);return a(se.span,{"data-state":bv(i.checked),"data-disabled":i.disabled?"":void 0,...r,ref:t})});gv.displayName=vv;var OI="SwitchBubbleInput",yv=H(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...i},o)=>{const s=U(null),c=_e(s,o),l=Pl(n),d=kl(t);return K(()=>{const u=s.current;if(!u)return;const p=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(p,"checked").set;if(l!==n&&f){const m=new Event("click",{bubbles:r});f.call(u,n),u.dispatchEvent(m)}},[l,n,r]),a("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...i,tabIndex:-1,ref:c,style:{...i.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});yv.displayName=OI;function bv(e){return e?"checked":"unchecked"}var jI=hv,FI=gv;function Gr({"aria-labelledby":e,checked:t,className:n,disabled:r=!1,id:i,name:o,onCheckedChange:s,thumbClassName:c}){return a(jI,{"aria-labelledby":e,checked:t,className:n,disabled:r,id:i,name:o,onCheckedChange:s,children:a(FI,{className:c})})}function ne(e,t="success"){_k(e,t)}function _v(e){return`${cT}:${String(e||"").trim()}`}function BI(e){try{return localStorage.getItem(_v(e))||""}catch{return""}}function UI(e,t){try{localStorage.setItem(_v(e),t)}catch{}}function Zn(){return String(b.coordinatorAdminTargetGroup||"").trim()}function Al(e){b.coordinatorAdminTargetGroup=e,UI(b.lastCoordinatorAdminStatus?.coordinator_url||null,e)}function Hr(){return(Array.isArray(b.lastCoordinatorAdminGroups)?b.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 GI(){const e=new Map;for(const t of Hr())e.set(t.group_id,t.display_name||t.group_id);F.groupRenameDrafts.clear();for(const[t,n]of e.entries())F.groupRenameDrafts.set(t,n)}function HI(){const e=Zn();return Hr().find(t=>t.group_id===e)||null}function wv(){const e=b.lastCoordinatorAdminStatus,t=Hr(),n=String(e?.active_group||"").trim(),r=BI(e?.coordinator_url||null),i=Zn(),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 Al(c),c}function qI(){const e=new Map,t=new Map,n=Array.isArray(b.lastCoordinatorAdminDevices)?b.lastCoordinatorAdminDevices:[];for(const r of n){const i=String(r.device_id||"").trim();if(!i)continue;const o=String(r.display_name||""),s=F.deviceRenameDrafts.get(i),c=F.deviceRenameServerNames.get(i),l=s!==void 0&&(c===void 0||s!==c);e.set(i,l?s:o),t.set(i,o)}F.deviceRenameDrafts.clear();for(const[r,i]of e.entries())F.deviceRenameDrafts.set(r,i);F.deviceRenameServerNames.clear();for(const[r,i]of t.entries())F.deviceRenameServerNames.set(r,i)}function KI(e,t){return t&&t.groupId===e?t:null}function VI(e,t){return e?.loaded&&e.default_space_scope_id?"Configured":e?.loaded?"Not configured":t?.defaultSpaceLabel?t.defaultSpaceLabel:t?.defaultSpaceScopeId?"Configured":"Open Team defaults to inspect"}function WI(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 Team defaults to inspect"}function zI(e){return e?.loaded?e.scopes.filter(t=>String(t.status||"active")==="active").length:null}function JI(e){const t=zI(e);return t===null?"Open Spaces to inspect access grants":`${t} active ${t===1?"Space":"Spaces"}`}function YI(e){const t=KI(e.groupId,e.setupGuide);return{autoGrant:WI(e.preferences,t),defaultSpace:VI(e.preferences,t),spaces:JI(e.scopeManagement)}}var Rl=null,Ha=null,Dl=null;function XI(){return Rl}function Ll(e){Ha=e}function Sv(e){Dl=e}function QI(e){return Dl===e}function ZI(e){return e?e.kind==="confirm"?!1:e.kind==="input"?null:{action:"cancel"}:null}function $l(e){return!Rl||!Ha?!0:(console.warn(`Ignored sync ${e} dialog request because another sync dialog is already open.`),!1)}function qa(e){Rl=e,Dl?.(e)}function Sn(e){const t=Ha;Ha=null,qa(null),t?.(e)}function eE(e){return e==="danger"?"sync-dialog-confirm danger":"sync-dialog-confirm"}var tE=H(function({value:t,onValueChange:n,suggestions:r,onSubmit:i,maxSuggestions:o=20,onKeyDown:s,onFocus:c,onBlur:l,className:d,...u},p){const f=U(null);qo(p,()=>f.current,[]);const[m,v]=D(!1),[h,g]=D(-1),_=Ee(()=>{const k=t.trim().toLowerCase();return(k?r.filter(E=>E.toLowerCase().includes(k)):r).slice(0,o)},[t,r,o]);K(()=>{h>=_.length&&g(_.length-1)},[_.length,h]);const w=m&&_.length>0,S=k=>{n(k),v(!1),g(-1),f.current?.focus()};return a(uv,{open:w,onOpenChange:v,children:[a(RI,{asChild:!0,children:a("input",{...u,ref:f,className:d,value:t,onInput:k=>{n(k.currentTarget.value),v(!0),g(-1)},onFocus:k=>{c?.(k)},onBlur:k=>{window.setTimeout(()=>v(!1),120),l?.(k)},onKeyDown:k=>{if(k.key==="ArrowDown"){k.preventDefault(),v(!0),g(E=>_.length===0?-1:Math.min(E+1,_.length-1));return}if(k.key==="ArrowUp"){k.preventDefault(),m||v(!0),g(E=>Math.max(E-1,-1));return}if(k.key==="Escape"&&w){k.preventDefault(),v(!1),g(-1);return}if((k.key==="Tab"||k.key==="Enter")&&h>=0){const E=_[h];if(E){k.preventDefault(),S(E);return}}if(k.key==="Enter"&&i){k.preventDefault(),i();return}s?.(k)},role:"combobox","aria-autocomplete":"list","aria-expanded":w,"aria-controls":"autocompleteListbox","aria-activedescendant":h>=0?`autocomplete-option-${h}`:void 0})}),a(pv,{children:a(fv,{align:"start",className:"autocomplete-popover",onOpenAutoFocus:k=>k.preventDefault(),onCloseAutoFocus:k=>k.preventDefault(),sideOffset:4,style:{width:"var(--radix-popover-trigger-width)"},children:a("div",{className:"autocomplete-listbox",id:"autocompleteListbox",role:"listbox",children:_.map((k,E)=>{const R=E===h;return a("div",{"aria-selected":R,className:R?"autocomplete-option active":"autocomplete-option",id:`autocomplete-option-${E}`,onMouseDown:j=>{j.preventDefault(),S(k)},onMouseEnter:()=>g(E),role:"option",tabIndex:-1,children:k},k)})})})})]})}),Ml="Radio",[nE,Cv]=ot(Ml),[rE,iE]=nE(Ml),Nv=H((e,t)=>{const{__scopeRadio:n,name:r,checked:i=!1,required:o,disabled:s,value:c="on",onCheck:l,form:d,...u}=e,[p,f]=D(null),m=_e(t,g=>f(g)),v=U(!1),h=p?d||!!p.closest("form"):!0;return a(rE,{scope:n,checked:i,disabled:s,children:[a(se.button,{type:"button",role:"radio","aria-checked":i,"data-state":Ev(i),"data-disabled":s?"":void 0,disabled:s,value:c,...u,ref:m,onClick:z(e.onClick,g=>{i||l?.(),h&&(v.current=g.isPropagationStopped(),v.current||g.stopPropagation())})}),h&&a(Iv,{control:p,bubbles:!v.current,name:r,value:c,checked:i,required:o,disabled:s,form:d,style:{transform:"translateX(-100%)"}})]})});Nv.displayName=Ml;var kv="RadioIndicator",Tv=H((e,t)=>{const{__scopeRadio:n,forceMount:r,...i}=e,o=iE(kv,n);return a(et,{present:r||o.checked,children:a(se.span,{"data-state":Ev(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:t})})});Tv.displayName=kv;var oE="RadioBubbleInput",Iv=H(({__scopeRadio:e,control:t,checked:n,bubbles:r=!0,...i},o)=>{const s=U(null),c=_e(s,o),l=Pl(n),d=kl(t);return K(()=>{const u=s.current;if(!u)return;const p=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(p,"checked").set;if(l!==n&&f){const m=new Event("click",{bubbles:r});f.call(u,n),u.dispatchEvent(m)}},[l,n,r]),a(se.input,{type:"radio","aria-hidden":!0,defaultChecked:n,...i,tabIndex:-1,ref:c,style:{...i.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Iv.displayName=oE;function Ev(e){return e?"checked":"unchecked"}var aE=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Ka="RadioGroup",[sE,Pj]=ot(Ka,[Mr,Cv]),xv=Mr(),Pv=Cv(),[cE,lE]=sE(Ka),Av=H((e,t)=>{const{__scopeRadioGroup:n,name:r,defaultValue:i,value:o,required:s=!1,disabled:c=!1,orientation:l,dir:d,loop:u=!0,onValueChange:p,...f}=e,m=xv(n),v=Bi(d),[h,g]=Ct({prop:o,defaultProp:i??null,onChange:p,caller:Ka});return a(cE,{scope:n,name:r,required:s,disabled:c,value:h,onValueChange:g,children:a(sl,{asChild:!0,...m,orientation:l,dir:v,loop:u,children:a(se.div,{role:"radiogroup","aria-required":s,"aria-orientation":l,"data-disabled":c?"":void 0,dir:v,...f,ref:t})})})});Av.displayName=Ka;var Rv="RadioGroupItem",Dv=H((e,t)=>{const{__scopeRadioGroup:n,disabled:r,...i}=e,o=lE(Rv,n),s=o.disabled||r,c=xv(n),l=Pv(n),d=U(null),u=_e(t,d),p=o.value===i.value,f=U(!1);return K(()=>{const m=h=>{aE.includes(h.key)&&(f.current=!0)},v=()=>f.current=!1;return document.addEventListener("keydown",m),document.addEventListener("keyup",v),()=>{document.removeEventListener("keydown",m),document.removeEventListener("keyup",v)}},[]),a(cl,{asChild:!0,...c,focusable:!s,active:p,children:a(Nv,{disabled:s,required:o.required,checked:p,...l,...i,name:o.name,ref:u,onCheck:()=>o.onValueChange(i.value),onKeyDown:z(m=>{m.key==="Enter"&&m.preventDefault()}),onFocus:z(i.onFocus,()=>{f.current&&d.current?.click()})})})});Dv.displayName=Rv;var dE="RadioGroupIndicator",Lv=H((e,t)=>{const{__scopeRadioGroup:n,...r}=e;return a(Tv,{...Pv(n),...r,ref:t})});Lv.displayName=dE;var uE=Av,pE=Dv,fE=Lv;function mE({ariaDescribedby:e,ariaLabel:t,autoFocusValue:n,indicatorClassName:r,itemClassName:i,itemLabelClassName:o,name:s,onValueChange:c,options:l,rootClassName:d,value:u}){return a(uE,{"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(pE,{id:m,"aria-labelledby":v,autoFocus:n===p.value,disabled:p.disabled,value:p.value,children:a(fE,{className:r})}),a("span",{className:o,id:v,children:p.label})]},p.value)})})}function $v(e,[t,n]){return Math.min(n,Math.max(t,e))}var hE=[" ","Enter","ArrowUp","ArrowDown"],vE=[" ","Enter"],er="Select",[Va,Wa,gE]=_a(er),[qr,Aj]=ot(er,[gE,_n]),za=_n(),[yE,Cn]=qr(er),[bE,_E]=qr(er),Mv=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}=e,h=za(t),[g,_]=D(null),[w,S]=D(null),[N,k]=D(!1),E=Bi(d),[R,j]=Ct({prop:r,defaultProp:i??!1,onChange:o,caller:er}),[q,I]=Ct({prop:s,defaultProp:c,onChange:l,caller:er}),G=U(null),A=g?v||!!g.closest("form"):!0,[M,L]=D(new Set),x=Array.from(M).map(O=>O.props.value).join(";");return a(qi,{...h,children:a(yE,{required:m,scope:t,trigger:g,onTriggerChange:_,valueNode:w,onValueNodeChange:S,valueNodeHasChildren:N,onValueNodeHasChildrenChange:k,contentId:at(),value:q,onValueChange:I,open:R,onOpenChange:j,dir:E,triggerPointerDownPosRef:G,disabled:f,children:[a(Va.Provider,{scope:t,children:a(bE,{scope:e.__scopeSelect,onNativeOptionAdd:ie(O=>{L(T=>new Set(T).add(O))},[]),onNativeOptionRemove:ie(O=>{L(T=>{const P=new Set(T);return P.delete(O),P})},[]),children:n})}),A?a(ng,{"aria-hidden":!0,required:m,tabIndex:-1,name:u,autoComplete:p,value:q,onChange:O=>I(O.target.value),disabled:f,form:v,children:[q===void 0?a("option",{value:""}):null,Array.from(M)]},x):null]})})};Mv.displayName=er;var Ov="SelectTrigger",jv=H((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...i}=e,o=za(n),s=Cn(Ov,n),c=s.disabled||r,l=_e(t,s.onTriggerChange),d=Wa(n),u=U("touch"),[p,f,m]=ig(h=>{const g=d().filter(w=>!w.disabled),_=og(g,h,g.find(w=>w.value===s.value));_!==void 0&&s.onValueChange(_.value)}),v=h=>{c||(s.onOpenChange(!0),m()),h&&(s.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)})};return a(Ki,{asChild:!0,...o,children:a(se.button,{type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:c,"data-disabled":c?"":void 0,"data-placeholder":rg(s.value)?"":void 0,...i,ref:l,onClick:z(i.onClick,h=>{h.currentTarget.focus(),u.current!=="mouse"&&v(h)}),onPointerDown:z(i.onPointerDown,h=>{u.current=h.pointerType;const g=h.target;g.hasPointerCapture(h.pointerId)&&g.releasePointerCapture(h.pointerId),h.button===0&&h.ctrlKey===!1&&h.pointerType==="mouse"&&(v(h),h.preventDefault())}),onKeyDown:z(i.onKeyDown,h=>{const g=p.current!=="";!(h.ctrlKey||h.altKey||h.metaKey)&&h.key.length===1&&f(h.key),!(g&&h.key===" ")&&hE.includes(h.key)&&(v(),h.preventDefault())})})})});jv.displayName=Ov;var Fv="SelectValue",Bv=H((e,t)=>{const{__scopeSelect:n,className:r,style:i,children:o,placeholder:s="",...c}=e,l=Cn(Fv,n),{onValueNodeHasChildrenChange:d}=l,u=o!==void 0,p=_e(t,l.onValueNodeChange);return Ve(()=>{d(u)},[d,u]),a(se.span,{...c,ref:p,style:{pointerEvents:"none"},children:rg(l.value)?a(Z,{children:s}):o})});Bv.displayName=Fv;var wE="SelectIcon",Uv=H((e,t)=>{const{__scopeSelect:n,children:r,...i}=e;return a(se.span,{"aria-hidden":!0,...i,ref:t,children:r||"▼"})});Uv.displayName=wE;var SE="SelectPortal",Gv=e=>a(qn,{asChild:!0,...e});Gv.displayName=SE;var tr="SelectContent",Hv=H((e,t)=>{const n=Cn(tr,e.__scopeSelect),[r,i]=D();if(Ve(()=>{i(new DocumentFragment)},[]),!n.open){const o=r;return o?en(a(qv,{scope:e.__scopeSelect,children:a(Va.Slot,{scope:e.__scopeSelect,children:a("div",{children:e.children})})}),o):null}return a(Kv,{...e,ref:t})});Hv.displayName=tr;var Dt=10,[qv,Nn]=qr(tr),CE="SelectContentImpl",NE=Gn("SelectContent.RemoveScroll"),Kv=H((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:o,onPointerDownOutside:s,side:c,sideOffset:l,align:d,alignOffset:u,arrowPadding:p,collisionBoundary:f,collisionPadding:m,sticky:v,hideWhenDetached:h,avoidCollisions:g,..._}=e,w=Cn(tr,n),[S,N]=D(null),[k,E]=D(null),R=_e(t,ee=>N(ee)),[j,q]=D(null),[I,G]=D(null),A=Wa(n),[M,L]=D(!1),x=U(!1);K(()=>{if(S)return oa(S)},[S]),Xo();const O=ie(ee=>{const[Te,...fe]=A().map(ce=>ce.ref.current),[te]=fe.slice(-1),Ie=document.activeElement;for(const ce of ee)if(ce===Ie||(ce?.scrollIntoView({block:"nearest"}),ce===Te&&k&&(k.scrollTop=0),ce===te&&k&&(k.scrollTop=k.scrollHeight),ce?.focus(),document.activeElement!==Ie))return},[A,k]),T=ie(()=>O([j,S]),[O,j,S]);K(()=>{M&&T()},[M,T]);const{onOpenChange:P,triggerPointerDownPosRef:B}=w;K(()=>{if(S){let ee={x:0,y:0};const Te=te=>{ee={x:Math.abs(Math.round(te.pageX)-(B.current?.x??0)),y:Math.abs(Math.round(te.pageY)-(B.current?.y??0))}},fe=te=>{ee.x<=10&&ee.y<=10?te.preventDefault():S.contains(te.target)||P(!1),document.removeEventListener("pointermove",Te),B.current=null};return B.current!==null&&(document.addEventListener("pointermove",Te),document.addEventListener("pointerup",fe,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Te),document.removeEventListener("pointerup",fe,{capture:!0})}}},[S,P,B]),K(()=>{const ee=()=>P(!1);return window.addEventListener("blur",ee),window.addEventListener("resize",ee),()=>{window.removeEventListener("blur",ee),window.removeEventListener("resize",ee)}},[P]);const[V,le]=ig(ee=>{const Te=A().filter(te=>!te.disabled),fe=og(Te,ee,Te.find(te=>te.ref.current===document.activeElement));fe&&setTimeout(()=>fe.ref.current.focus())}),de=ie((ee,Te,fe)=>{const te=!x.current&&!fe;(w.value!==void 0&&w.value===Te||te)&&(q(ee),te&&(x.current=!0))},[w.value]),ae=ie(()=>S?.focus(),[S]),be=ie((ee,Te,fe)=>{const te=!x.current&&!fe;(w.value!==void 0&&w.value===Te||te)&&G(ee)},[w.value]),J=r==="popper"?Ol:Vv,ve=J===Ol?{side:c,sideOffset:l,align:d,alignOffset:u,arrowPadding:p,collisionBoundary:f,collisionPadding:m,sticky:v,hideWhenDetached:h,avoidCollisions:g}:{};return a(qv,{scope:n,content:S,viewport:k,onViewportChange:E,itemRefCallback:de,selectedItem:j,onItemLeave:ae,itemTextRefCallback:be,focusSelectedItem:T,selectedItemText:I,position:r,isPositioned:M,searchRef:V,children:a(Ti,{as:NE,allowPinchZoom:!0,children:a(Ni,{asChild:!0,trapped:w.open,onMountAutoFocus:ee=>{ee.preventDefault()},onUnmountAutoFocus:z(i,ee=>{w.trigger?.focus({preventScroll:!0}),ee.preventDefault()}),children:a(Hn,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:ee=>ee.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:a(J,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:ee=>ee.preventDefault(),..._,...ve,onPlaced:()=>L(!0),ref:R,style:{display:"flex",flexDirection:"column",outline:"none",..._.style},onKeyDown:z(_.onKeyDown,ee=>{const Te=ee.ctrlKey||ee.altKey||ee.metaKey;if(ee.key==="Tab"&&ee.preventDefault(),!Te&&ee.key.length===1&&le(ee.key),["ArrowUp","ArrowDown","Home","End"].includes(ee.key)){let fe=A().filter(te=>!te.disabled).map(te=>te.ref.current);if(["ArrowUp","End"].includes(ee.key)&&(fe=fe.slice().reverse()),["ArrowUp","ArrowDown"].includes(ee.key)){const te=ee.target,Ie=fe.indexOf(te);fe=fe.slice(Ie+1)}setTimeout(()=>O(fe)),ee.preventDefault()}})})})})})})});Kv.displayName=CE;var kE="SelectItemAlignedPosition",Vv=H((e,t)=>{const{__scopeSelect:n,onPlaced:r,...i}=e,o=Cn(tr,n),s=Nn(tr,n),[c,l]=D(null),[d,u]=D(null),p=_e(t,E=>u(E)),f=Wa(n),m=U(!1),v=U(!0),{viewport:h,selectedItem:g,selectedItemText:_,focusSelectedItem:w}=s,S=ie(()=>{if(o.trigger&&o.valueNode&&c&&d&&h&&g&&_){const E=o.trigger.getBoundingClientRect(),R=d.getBoundingClientRect(),j=o.valueNode.getBoundingClientRect(),q=_.getBoundingClientRect();if(o.dir!=="rtl"){const fe=q.left-R.left,te=j.left-fe,Ie=E.left-te,ce=E.width+Ie,Ae=Math.max(ce,R.width),ue=window.innerWidth-Dt,Ke=$v(te,[Dt,Math.max(Dt,ue-Ae)]);c.style.minWidth=ce+"px",c.style.left=Ke+"px"}else{const fe=R.right-q.right,te=window.innerWidth-j.right-fe,Ie=window.innerWidth-E.right-te,ce=E.width+Ie,Ae=Math.max(ce,R.width),ue=window.innerWidth-Dt,Ke=$v(te,[Dt,Math.max(Dt,ue-Ae)]);c.style.minWidth=ce+"px",c.style.right=Ke+"px"}const I=f(),G=window.innerHeight-Dt*2,A=h.scrollHeight,M=window.getComputedStyle(d),L=parseInt(M.borderTopWidth,10),x=parseInt(M.paddingTop,10),O=parseInt(M.borderBottomWidth,10),T=parseInt(M.paddingBottom,10),P=L+x+A+T+O,B=Math.min(g.offsetHeight*5,P),V=window.getComputedStyle(h),le=parseInt(V.paddingTop,10),de=parseInt(V.paddingBottom,10),ae=E.top+E.height/2-Dt,be=G-ae,J=g.offsetHeight/2,ve=g.offsetTop+J,ee=L+x+ve,Te=P-ee;if(ee<=ae){const fe=I.length>0&&g===I[I.length-1].ref.current;c.style.bottom="0px";const te=d.clientHeight-h.offsetTop-h.offsetHeight,Ie=ee+Math.max(be,J+(fe?de:0)+te+O);c.style.height=Ie+"px"}else{const fe=I.length>0&&g===I[0].ref.current;c.style.top="0px";const te=Math.max(ae,L+h.offsetTop+(fe?le:0)+J)+Te;c.style.height=te+"px",h.scrollTop=ee-ae+h.offsetTop}c.style.margin=`${Dt}px 0`,c.style.minHeight=B+"px",c.style.maxHeight=G+"px",r?.(),requestAnimationFrame(()=>m.current=!0)}},[f,o.trigger,o.valueNode,c,d,h,g,_,o.dir,r]);Ve(()=>S(),[S]);const[N,k]=D();return Ve(()=>{d&&k(window.getComputedStyle(d).zIndex)},[d]),a(IE,{scope:n,contentWrapper:c,shouldExpandOnScrollRef:m,onScrollButtonChange:ie(E=>{E&&v.current===!0&&(S(),w?.(),v.current=!1)},[S,w]),children:a("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:N},children:a(se.div,{...i,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});Vv.displayName=kE;var TE="SelectPopperPosition",Ol=H((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:i=Dt,...o}=e,s=za(n);return a(Fa,{...s,...o,ref:t,align:r,collisionPadding:i,style:{boxSizing:"border-box",...o.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)"}})});Ol.displayName=TE;var[IE,jl]=qr(tr,{}),Fl="SelectViewport",Wv=H((e,t)=>{const{__scopeSelect:n,nonce:r,...i}=e,o=Nn(Fl,n),s=jl(Fl,n),c=_e(t,o.onViewportChange),l=U(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:r}),a(Va.Slot,{scope:n,children:a(se.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:c,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:z(i.onScroll,d=>{const u=d.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:f}=s;if(f?.current&&p){const m=Math.abs(l.current-u.scrollTop);if(m>0){const v=window.innerHeight-Dt*2,h=parseFloat(p.style.minHeight),g=parseFloat(p.style.height),_=Math.max(h,g);if(_<v){const w=_+m,S=Math.min(v,w),N=w-S;p.style.height=S+"px",p.style.bottom==="0px"&&(u.scrollTop=N>0?N:0,p.style.justifyContent="flex-end")}}}l.current=u.scrollTop})})})]})});Wv.displayName=Fl;var zv="SelectGroup",[EE,xE]=qr(zv),PE=H((e,t)=>{const{__scopeSelect:n,...r}=e,i=at();return a(EE,{scope:n,id:i,children:a(se.div,{role:"group","aria-labelledby":i,...r,ref:t})})});PE.displayName=zv;var Jv="SelectLabel",AE=H((e,t)=>{const{__scopeSelect:n,...r}=e,i=xE(Jv,n);return a(se.div,{id:i.id,...r,ref:t})});AE.displayName=Jv;var Ja="SelectItem",[RE,Yv]=qr(Ja),Xv=H((e,t)=>{const{__scopeSelect:n,value:r,disabled:i=!1,textValue:o,...s}=e,c=Cn(Ja,n),l=Nn(Ja,n),d=c.value===r,[u,p]=D(o??""),[f,m]=D(!1),v=_e(t,w=>l.itemRefCallback?.(w,r,i)),h=at(),g=U("touch"),_=()=>{i||(c.onValueChange(r),c.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return a(RE,{scope:n,value:r,disabled:i,textId:h,isSelected:d,onItemTextChange:ie(w=>{p(S=>S||(w?.textContent??"").trim())},[]),children:a(Va.ItemSlot,{scope:n,value:r,disabled:i,textValue:u,children:a(se.div,{role:"option","aria-labelledby":h,"data-highlighted":f?"":void 0,"aria-selected":d&&f,"data-state":d?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...s,ref:v,onFocus:z(s.onFocus,()=>m(!0)),onBlur:z(s.onBlur,()=>m(!1)),onClick:z(s.onClick,()=>{g.current!=="mouse"&&_()}),onPointerUp:z(s.onPointerUp,()=>{g.current==="mouse"&&_()}),onPointerDown:z(s.onPointerDown,w=>{g.current=w.pointerType}),onPointerMove:z(s.onPointerMove,w=>{g.current=w.pointerType,i?l.onItemLeave?.():g.current==="mouse"&&w.currentTarget.focus({preventScroll:!0})}),onPointerLeave:z(s.onPointerLeave,w=>{w.currentTarget===document.activeElement&&l.onItemLeave?.()}),onKeyDown:z(s.onKeyDown,w=>{l.searchRef?.current!==""&&w.key===" "||(vE.includes(w.key)&&_(),w.key===" "&&w.preventDefault())})})})})});Xv.displayName=Ja;var Wi="SelectItemText",Qv=H((e,t)=>{const{__scopeSelect:n,className:r,style:i,...o}=e,s=Cn(Wi,n),c=Nn(Wi,n),l=Yv(Wi,n),d=_E(Wi,n),[u,p]=D(null),f=_e(t,_=>p(_),l.onItemTextChange,_=>c.itemTextRefCallback?.(_,l.value,l.disabled)),m=u?.textContent,v=Ee(()=>a("option",{value:l.value,disabled:l.disabled,children:m},l.value),[l.disabled,l.value,m]),{onNativeOptionAdd:h,onNativeOptionRemove:g}=d;return Ve(()=>(h(v),()=>g(v)),[h,g,v]),a(Z,{children:[a(se.span,{id:l.textId,...o,ref:f}),l.isSelected&&s.valueNode&&!s.valueNodeHasChildren?en(o.children,s.valueNode):null]})});Qv.displayName=Wi;var Zv="SelectItemIndicator",eg=H((e,t)=>{const{__scopeSelect:n,...r}=e;return Yv(Zv,n).isSelected?a(se.span,{"aria-hidden":!0,...r,ref:t}):null});eg.displayName=Zv;var Bl="SelectScrollUpButton",DE=H((e,t)=>{const n=Nn(Bl,e.__scopeSelect),r=jl(Bl,e.__scopeSelect),[i,o]=D(!1),s=_e(t,r.onScrollButtonChange);return Ve(()=>{if(n.viewport&&n.isPositioned){let c=function(){o(l.scrollTop>0)};const l=n.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),i?a(tg,{...e,ref:s,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop-l.offsetHeight)}}):null});DE.displayName=Bl;var Ul="SelectScrollDownButton",LE=H((e,t)=>{const n=Nn(Ul,e.__scopeSelect),r=jl(Ul,e.__scopeSelect),[i,o]=D(!1),s=_e(t,r.onScrollButtonChange);return Ve(()=>{if(n.viewport&&n.isPositioned){let c=function(){const d=l.scrollHeight-l.clientHeight;o(Math.ceil(l.scrollTop)<d)};const l=n.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),i?a(tg,{...e,ref:s,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop+l.offsetHeight)}}):null});LE.displayName=Ul;var tg=H((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...i}=e,o=Nn("SelectScrollButton",n),s=U(null),c=Wa(n),l=ie(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return K(()=>()=>l(),[l]),Ve(()=>{c().find(d=>d.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[c]),a(se.div,{"aria-hidden":!0,...i,ref:t,style:{flexShrink:0,...i.style},onPointerDown:z(i.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:z(i.onPointerMove,()=>{o.onItemLeave?.(),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:z(i.onPointerLeave,()=>{l()})})}),$E="SelectSeparator",ME=H((e,t)=>{const{__scopeSelect:n,...r}=e;return a(se.div,{"aria-hidden":!0,...r,ref:t})});ME.displayName=$E;var Gl="SelectArrow",OE=H((e,t)=>{const{__scopeSelect:n,...r}=e,i=za(n),o=Cn(Gl,n),s=Nn(Gl,n);return o.open&&s.position==="popper"?a(Ba,{...i,...r,ref:t}):null});OE.displayName=Gl;var jE="SelectBubbleInput",ng=H(({__scopeSelect:e,value:t,...n},r)=>{const i=U(null),o=_e(r,i),s=Pl(t);return K(()=>{const c=i.current;if(!c)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(s!==t&&d){const u=new Event("change",{bubbles:!0});d.call(c,t),c.dispatchEvent(u)}},[s,t]),a(se.select,{...n,style:{...Em,...n.style},ref:o,defaultValue:t})});ng.displayName=jE;function rg(e){return e===""||e===void 0}function ig(e){const t=st(e),n=U(""),r=U(0),i=ie(s=>{const c=n.current+s;t(c),(function l(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>l(""),1e3))})(c)},[t]),o=ie(()=>{n.current="",window.clearTimeout(r.current)},[]);return K(()=>()=>window.clearTimeout(r.current),[]),[n,i,o]}function og(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=FE(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}function FE(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var BE=Mv,UE=jv,GE=Bv,HE=Uv,qE=Gv,KE=Hv,VE=Wv,WE=Xv,zE=Qv,JE=eg,ag="__codemem-empty-select__";function YE(){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 XE(){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 Hl(e){return e===""?ag:e}function QE(e){return e===ag?"":e}function kn({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?Hl(u):void 0;return a(BE,{disabled:r,onValueChange:m=>s(QE(m)),value:f,children:[a(UE,{"aria-label":e,className:d??t,"data-value":u,id:i,type:"button",children:[a(GE,{placeholder:l}),a(HE,{className:"sync-radix-select-icon","aria-hidden":"true",children:a(YE,{})})]}),a(qE,{children:a(KE,{className:n,position:"popper",children:a(VE,{className:p,children:c.map(m=>a(WE,{className:o,disabled:m.disabled,value:Hl(m.value),children:[a(zE,{children:m.label}),a(JE,{className:"sync-radix-select-indicator",children:a(XE,{})})]},Hl(m.value)))})})})]})}function ZE({descriptionId:e,request:t}){const[n,r]=D("choice"),[i,o]=D(t.actors.find(g=>g.isLocal)?.actorId||t.actors[0]?.actorId||""),[s,c]=D("");K(()=>{r("choice");const g=t.actors.find(w=>w.isLocal)?.actorId||t.actors[0]?.actorId||"",_=t.actors.find(w=>w.actorId!==g)?.actorId||"";o(g),c(_)},[t]);const l=t.actors.find(g=>g.actorId===i)||t.actors[0],d=t.actors.filter(g=>g.actorId!==i),u=d.find(g=>g.actorId===s)||d[0],p=t.actors.map(g=>({label:a(Z,{children:[g.label,g.isLocal?" (You)":""]}),value:g.actorId})),f=d.map(g=>({label:`${g.label}${g.isLocal?" (You)":""}`,value:g.actorId})),m=!!(l?.actorId&&u?.actorId),v=()=>{!l?.actorId||!u?.actorId||Sn({action:"merge",primaryActorId:l.actorId,secondaryActorId:u.actorId})},h=g=>{const _=g.target instanceof HTMLElement?g.target:null;g.defaultPrevented||g.isComposing||g.key!=="Enter"||_?.closest(".sync-dialog-radio-list")&&m&&(g.preventDefault(),v())};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:()=>Sn({action:"different-people"}),type:"button",children:"These are different people"})}),a("li",{children:a("button",{className:"settings-button",onClick:()=>Sn({action:"cancel"}),type:"button",children:"Decide later"})})]})}):a("div",{className:"sync-dialog-stack",onKeyDown:g=>{h(g),$r(g,{onSubmit:v,disabled:!m})},children:[a("div",{className:"small",id:e,children:"Choose which person should remain after combining these duplicates."}),a(mE,{ariaDescribedby:e,ariaLabel:"Person to keep after combining duplicates",autoFocusValue:i,indicatorClassName:"sync-dialog-radio-indicator",itemClassName:"sync-dialog-radio-option",itemLabelClassName:"sync-dialog-radio-label",name:"syncDuplicatePrimaryActor",onValueChange:o,options:p,rootClassName:"sync-dialog-radio-list",value:i}),a("div",{className:"field",children:[a("label",{className:"small",htmlFor:"syncDuplicateSecondaryActor",children:"Person to combine into the selected record"}),a(kn,{ariaLabel:"Person to combine into the selected record",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:f.length===0,id:"syncDuplicateSecondaryActor",itemClassName:"sync-radix-select-item",onValueChange:c,options:f,placeholder:"No merge target available",triggerClassName:"sync-radix-select-trigger sync-dialog-input",value:u?.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:!m,onClick:v,type:"button",children:"Combine people"})]})]})}function ex({descriptionId:e,request:t,titleId:n}){const[r,i]=D(t.kind==="input"&&t.initialValue||""),[o,s]=D(null),c=t.kind!=="duplicate-person",l="syncDialogInputError";K(()=>{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"){Sn(!0);return}if(t.kind==="duplicate-person")return;const f=r.trim(),m=t.validate?.(f)||null;if(m){s(m);return}Sn(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(Vo,{ariaLabel:`Close ${t.title}`,onClick:()=>Sn(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(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",onSubmit:p,onValueChange:f=>{i(f),o&&s(null)},placeholder:t.placeholder,suggestions:t.suggestions,value:r}):a(we,{"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(ZE,{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:()=>Sn(t.kind==="confirm"?!1:null),type:"button",children:d}),t.kind!=="duplicate-person"?a("button",{autoFocus:!0,className:`settings-button ${eE(t.kind==="confirm"?t.tone:void 0)}`,"data-sync-dialog-action":"confirm",onClick:p,type:"button",children:u}):null]})]})]})}function tx(){const[e,t]=D(XI());K(()=>(Sv(t),()=>{QI(t)&&Sv(null)}),[]);const n=!!e,r=Ee(()=>`sync-dialog-title-${e?.kind||"none"}`,[e?.kind]),i=Ee(()=>`sync-dialog-description-${e?.kind||"none"}`,[e?.kind]);return e?a(Ii,{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||Sn(e?.kind==="confirm"?!1:null)},open:n,overlayClassName:"modal-backdrop",overlayId:"syncDialogBackdrop",children:e?a(ex,{descriptionId:i,request:e,titleId:r}):null}):null}var nr=null;function Ya(){nr?.isConnected||(nr=document.getElementById("syncDialogMount"),nr||(nr=document.createElement("div"),nr.id="syncDialogMount",document.body.appendChild(nr)),Be(a(tx,{}),nr))}function Ht(e){return Ya(),$l("confirm")?new Promise(t=>{Ll(n=>t(!!n)),qa({kind:"confirm",...e})}):Promise.resolve(!1)}function ql(e){return Ya(),$l("input")?new Promise(t=>{Ll(n=>t(typeof n=="string"?n:null)),qa({kind:"input",...e})}):Promise.resolve(null)}function nx(e){return Ya(),$l("duplicate-person")?new Promise(t=>{Ll(n=>t(n||{action:"cancel"})),qa({kind:"duplicate-person",...e})}):Promise.resolve(ZI({kind:"duplicate-person",...e}))}function rx(e){return e.readiness==="ready"?null:"Space management needs the coordinator URL, target Team, and admin secret before it can list Spaces or change memberships."}function ix(e){const t=String(e||"active").trim();return t?t.replaceAll("_"," "):"active"}function sg(e){const t=String(e.label||"").trim()||"Untitled Space",n=ix(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:`Advanced: Space ID ${i} · Membership epoch ${o}`}}function ox(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:`Advanced: membership epoch ${i}`}}function ax(e,t,n){return`Revoke ${t||n||"this device"} from ${sg(e).title}?`}function sx(e,t){const n=new Map(t.map(r=>[String(r.device_id||"").trim(),r]).filter(([r])=>r.length>0));return e.map(r=>{const i=String(r.device_id||"").trim();if(!i)return null;const o=n.get(i),s=String(o?.status||"").trim(),c=o?s==="revoked"?"revoked":"active":"not_member",l=typeof o?.membership_epoch=="number"&&Number.isFinite(o.membership_epoch)?Math.trunc(o.membership_epoch):null;return{deviceId:i,displayName:String(r.display_name||i||"Unnamed device"),enabled:r.enabled!==!1&&r.enabled!==0,status:c,role:String(o?.role||"member"),membershipEpoch:l,updatedAt:o?.updated_at?String(o.updated_at):null}}).filter(r=>r!==null).sort((r,i)=>{const o={active:0,revoked:1,not_member:2};return o[r.status]-o[i.status]||r.displayName.localeCompare(i.displayName)})}function cx(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)}function lx(){return{loaded:!1,loading:!1,error:"",includeInactive:!1,devicesLoaded:!1,scopes:[],membersByScope:new Map,devices:[],createScopeId:"",createLabel:"",createKind:"team",actionPendingKey:"",actionPendingKind:""}}function Kl(e){if(!e||typeof e!="object")return[];const t=e.items;return Array.isArray(t)?t:[]}function ct(e){let t=F.groupScopeManagementDrafts.get(e);return t||(t=lx(),F.groupScopeManagementDrafts.set(e,t)),t}function _t(e,t){F.groupScopeManagementDrafts.set(e,t)}async function Kr(e,t,n=ct(e).includeInactive){_t(e,{...ct(e),loading:!0,error:"",includeInactive:n}),t();try{const[r,i]=await Promise.all([rw(e,n),Xu(e,!0)]),o=Kl(r),s=Kl(i),c=await Promise.all(o.map(async l=>{const d=String(l.scope_id||"").trim();return d?[d,Kl(await ow(e,d,!0))]:[d,[]]}));_t(e,{...ct(e),loaded:!0,loading:!1,error:"",includeInactive:n,devicesLoaded:!0,scopes:o,devices:s,membersByScope:new Map(c.filter(([l])=>l.length>0)),actionPendingKey:"",actionPendingKind:""})}catch(r){_t(e,{...ct(e),loaded:!0,loading:!1,error:r instanceof Error?r.message:"Failed to load Spaces."})}t()}function Vl(e,t){F.groupScopeManagementOpen.add(e),ct(e),t(),Kr(e,t)}function cg(e,t){F.groupScopeManagementOpen.delete(e),F.groupScopeManagementDrafts.delete(e),t()}async function dx(e,t){const n=ct(e);if(n.actionPendingKey)return;const r=n.createScopeId.trim(),i=n.createLabel.trim(),o=n.createKind.trim()||"team";if(!r||!i){ne("Enter a Space id and label before creating a Space.","warning");return}_t(e,{...n,actionPendingKey:`create:${r}`,actionPendingKind:"create",error:""}),t();try{await iw(e,{scope_id:r,label:i,kind:o});const s=ct(e);_t(e,{...s,createScopeId:"",createLabel:"",createKind:"team",actionPendingKey:"",actionPendingKind:""}),ne("Space created. Grant devices explicitly before data can sync."),await Kr(e,t,s.includeInactive)}catch(s){_t(e,{...ct(e),actionPendingKey:"",actionPendingKind:"",error:s instanceof Error?s.message:"Failed to create Space."}),t()}}async function ux(e,t,n,r){const i=ct(e),o=`grant:${t}:${n}`;if(!i.actionPendingKey){_t(e,{...i,actionPendingKey:o,actionPendingKind:"grant",error:""}),r();try{await aw(e,t,{device_id:n,role:"member"}),ne("Device granted access to the Space."),await Kr(e,r,i.includeInactive)}catch(s){_t(e,{...ct(e),actionPendingKey:"",actionPendingKind:"",error:s instanceof Error?s.message:"Failed to grant Space access."}),r()}}}async function px(e,t,n,r,i){const o=String(t.scope_id||"").trim();if(!o||!await Ht({title:ax(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 s=ct(e),c=`revoke:${o}:${n}`;if(!s.actionPendingKey){_t(e,{...s,actionPendingKey:c,actionPendingKind:"revoke",error:""}),i();try{await sw(e,o,n),ne("Space access revoked. Future sync is blocked for that device."),await Kr(e,i,s.includeInactive)}catch(l){_t(e,{...ct(e),actionPendingKey:"",actionPendingKind:"",error:l instanceof Error?l.message:"Failed to revoke Space access."}),i()}}}function fx(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=sx(cx(n.devices,b.lastCoordinatorAdminDevices,e,n.devicesLoaded),n.membersByScope.get(o)??[]);return s.length?y("div",{class:"coordinator-admin-scope-member-list"},s.map(c=>{const l=`${n.actionPendingKind}:${o}:${c.deviceId}`,d=n.actionPendingKey===l,u=c.enabled&&c.status!=="active",p=c.status==="active",f=ox(c);return y("div",{class:"coordinator-admin-scope-member-row",key:c.deviceId},y("div",{class:"coordinator-admin-scope-member-copy"},y("strong",null,c.displayName),y("span",null,f.detail),y("span",{class:"peer-meta"},f.advancedDetail),c.enabled?null:y("span",null,"Device is disabled in this Team.")),y("div",{class:"peer-actions"},u?y("button",{class:"settings-button",disabled:!r||!!n.actionPendingKey,onClick:()=>{ux(e,o,c.deviceId,i)},type:"button"},d&&n.actionPendingKind==="grant"?"Granting…":"Grant access"):null,p?y("button",{class:"settings-button danger",disabled:!r||!!n.actionPendingKey,onClick:()=>{px(e,t,c.deviceId,c.displayName,i)},type:"button"},d&&n.actionPendingKind==="revoke"?"Revoking…":"Revoke access"):null))})):y("div",{class:"peer-submeta coordinator-admin-empty-state"},"No enrolled devices in this Team yet. Enroll a device before granting this Space.")}function mx(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=sg(t);return y("div",{class:"peer-card peer-card--padded coordinator-admin-scope-card",key:o||s.title},y("div",{class:"peer-title"},y("strong",null,s.title)),y("div",{class:"peer-submeta"},s.summary),y("div",{class:"peer-meta"},s.advancedDetail),y("div",{class:"peer-submeta"},"Devices below are enrolled in the Team; only active Space members can sync this data boundary."),fx(e,t,n,r,i))}function hx(e){const{groupId:t,ready:n,summary:r,renderShell:i}=e,o=F.groupScopeManagementDrafts.get(t);if(!o)return null;const s=rx(r);if(s)return y("div",{class:"peer-meta coordinator-admin-inline-warning"},s);if(!o.loaded)return y("div",{class:"peer-submeta"},"Loading Spaces…");const c=!n||!!o.actionPendingKey||o.loading;return y(Z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),y("div",{class:"peer-submeta"},"Teams discover and enroll devices. Spaces grant data access. Granting a device here is explicit; Team membership alone does not share memories."),y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:`coord-admin-domain-inactive-${t}`},"Show inactive Spaces"),y(Gr,{"aria-labelledby":`coord-admin-domain-inactive-${t}`,checked:o.includeInactive,className:"coordinator-admin-switch",disabled:c,onCheckedChange:l=>{Kr(t,i,l)},thumbClassName:"coordinator-admin-switch-thumb"})),y("form",{class:"coordinator-admin-form",onSubmit:l=>{l.preventDefault(),!c&&dx(t,i)}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"New Space id"),y(we,{class:"peer-scope-input",disabled:c,onInput:l=>{_t(t,{...ct(t),createScopeId:String(l.currentTarget.value||"")})},placeholder:"acme-work",type:"text",value:o.createScopeId})),y("label",{class:"coordinator-admin-field"},y("span",null,"Label"),y(we,{class:"peer-scope-input",disabled:c,onInput:l=>{_t(t,{...ct(t),createLabel:String(l.currentTarget.value||"")})},placeholder:"Acme Work",type:"text",value:o.createLabel})),y("label",{class:"coordinator-admin-field"},y("span",null,"Kind"),y(we,{class:"peer-scope-input",disabled:c,onInput:l=>{_t(t,{...ct(t),createKind:String(l.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"),y("button",{class:"settings-button",disabled:c,onClick:()=>{Kr(t,i,o.includeInactive)},type:"button"},o.loading?"Refreshing…":"Refresh"))),o.error?y("div",{class:"peer-submeta coordinator-admin-error"},o.error):null,o.scopes.length?y("div",{class:"coordinator-admin-scope-card-list"},o.scopes.map(l=>mx(t,l,o,n,i))):y("div",{class:"peer-meta coordinator-admin-empty-state"},"No Spaces are defined for this Team yet. Create a Space, then grant specific devices. Projects stay local-only until assigned to a Space."))}function lg(){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 vx(){return{projects_include:[],projects_exclude:[],auto_seed_scope:!0,default_space_scope_id:"",auto_grant_default_space_on_join:!1,loaded:!1,saving:!1,error:""}}async function Wl(e,t){const n=vx();F.groupPreferencesDrafts.set(e,n),F.groupPreferencesOpen.add(e),t();try{const r=await qw(e);F.groupPreferencesDrafts.set(e,{projects_include:Array.isArray(r.projects_include)?[...r.projects_include]:[],projects_exclude:Array.isArray(r.projects_exclude)?[...r.projects_exclude]:[],auto_seed_scope:r.auto_seed_scope,default_space_scope_id:r.default_space_scope_id||"",auto_grant_default_space_on_join:r.auto_grant_default_space_on_join===!0,loaded:!0,saving:!1,error:""})}catch(r){F.groupPreferencesDrafts.set(e,{...n,loaded:!0,error:r instanceof Error?r.message:"Failed to load preferences."})}t()}function Xa(e,t){F.groupPreferencesOpen.delete(e),F.groupPreferencesDrafts.delete(e),t()}async function gx(e,t){const n=F.groupPreferencesDrafts.get(e);if(!n||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};F.groupPreferencesDrafts.set(e,{...n,saving:!0,error:""}),t();try{await Kw(e,r),ne("Team defaults saved. New devices use these filters and Space settings."),Xa(e,t)}catch(i){const o=F.groupPreferencesDrafts.get(e);if(!o)return;F.groupPreferencesDrafts.set(e,{...o,saving:!1,error:i instanceof Error?i.message:"Failed to save preferences."}),t()}}function yx(e,t,n){const r=F.groupPreferencesDrafts.get(e);if(!r)return null;if(!r.loaded)return y("div",{class:"peer-submeta"},"Loading project defaults…");const i=`coord-admin-scope-autoseed-${e}`,o=`coord-admin-default-space-autogrant-${e}`,s=`coord-admin-scope-include-${e}`,c=`coord-admin-scope-exclude-${e}`,l=!n||r.saving||!r.auto_seed_scope;return y(Z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Team defaults"),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:i},"Auto-apply advanced rules to new devices"),y(Gr,{"aria-labelledby":i,checked:r.auto_seed_scope,className:"coordinator-admin-switch",disabled:!n||r.saving,onCheckedChange:d=>{const u=F.groupPreferencesDrafts.get(e)??r;F.groupPreferencesDrafts.set(e,{...u,auto_seed_scope:d}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:o},"Auto-grant default Space on join"),y(Gr,{"aria-labelledby":o,checked:r.auto_grant_default_space_on_join,className:"coordinator-admin-switch",disabled:!n||r.saving||!r.default_space_scope_id,onCheckedChange:d=>{const u=F.groupPreferencesDrafts.get(e)??r;F.groupPreferencesDrafts.set(e,{...u,auto_grant_default_space_on_join:d}),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:s},"Include template"),y(mv,{"aria-labelledby":s,availableProjects:F.availableProjects,disabled:l,emptyLabel:"All projects allowed.",onValuesChange:d=>{const u=F.groupPreferencesDrafts.get(e)??r;F.groupPreferencesDrafts.set(e,{...u,projects_include:d}),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:c},"Exclude template"),y(mv,{"aria-labelledby":c,availableProjects:F.availableProjects,disabled:l,emptyLabel:"Nothing excluded.",onValuesChange:d=>{const u=F.groupPreferencesDrafts.get(e)??r;F.groupPreferencesDrafts.set(e,{...u,projects_exclude:d}),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:!n||r.saving,onClick:()=>{gx(e,t)},type:"button"},r.saving?"Saving…":"Save defaults"),y("button",{class:"settings-button",disabled:r.saving,onClick:()=>Xa(e,t),type:"button"},"Cancel")))}function bx(e){const t=F.teamSetupGuide;if(!t)return null;const n=t.displayName||t.groupId,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 ${n}`),y("div",{class:"peer-submeta"},"A Team organizes people and devices. The default Space is the memory boundary; Team membership only grants data access when default Space auto-grant is enabled."),t.setupWarning?y("div",{class:"peer-meta coordinator-admin-inline-warning"},`Team created, but ${r} failed. Automatic repair is not available yet; use Spaces to inspect or create access manually before inviting teammates.`):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 Team defaults and the auto-grant default Space setting."),y("li",null,"Invite teammates or other devices."),y("li",null,"Assign projects to Spaces from the Projects tab.")),y("div",{class:"peer-actions"},y("button",{class:"settings-button",onClick:()=>{F.groupPreferencesOpen.add(t.groupId),Wl(t.groupId,e)},type:"button"},"Review Team defaults"),y("button",{class:"settings-button",onClick:()=>{Vl(t.groupId,e)},type:"button"},"Check Spaces"),y("button",{class:"settings-button",onClick:()=>{F.inviteGroup=t.groupId,F.activeSection="invites",e()},type:"button"},"Invite devices"),y("button",{class:"settings-button",onClick:()=>{window.location.hash="projects"},type:"button"},"Assign projects"),y("button",{class:"settings-button",onClick:()=>{F.teamSetupGuide=null,e()},type:"button"},"Dismiss")))}function _x(e,t){return t?e?"Restoring…":"Archiving…":e?"Unarchive":"Archive"}function wx(e){const{summary:t,createGroup:n,runGroup:r,renderShell:i,reloadData:o}=e,s=String(b.lastCoordinatorAdminStatus?.active_group||"").trim(),c=Zn(),l=Hr(),d=l.filter(v=>!v.archived_at),u=l.filter(v=>v.archived_at),p=F.showArchivedGroups?l:d,f=c?l.some(v=>v.group_id===c):!1,m=[`${d.length} active`];return u.length&&m.push(`${u.length} archived`),y(Yn,{className:"coordinator-admin-panel",value:"groups"},y("h3",null,"Teams"),y("p",{class:"peer-submeta"},c?`Managing ${c}${s&&s!==c?` · this node uses ${s} for discovery`:""}`:s?`This node uses ${s} for discovery. Select a Team below to manage it.`:"No Team selected yet. Create one or select an existing Team to manage."),l.length?y("p",{class:"peer-submeta"},m.join(" · ")):null,!f&&c?y("div",{class:"peer-meta coordinator-admin-inline-warning"},`The selected Team (${c}) is configured locally but does not exist in the coordinator yet. Create it below or switch to another Team once one exists.`):null,bx(i),(()=>{const v=t.readiness!=="ready"||F.groupActionPendingKind==="create";return y("form",{class:"coordinator-admin-form",onSubmit:h=>{h.preventDefault(),!v&&n()}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"New Team id"),y(we,{class:"peer-scope-input",disabled:v,onInput:h=>{F.createGroupId=String(h.currentTarget.value||"")},placeholder:"team-alpha",type:"text",value:F.createGroupId})),y("label",{class:"coordinator-admin-field"},y("span",null,"Display name"),y(we,{class:"peer-scope-input",disabled:v,onInput:h=>{F.createGroupDisplayName=String(h.currentTarget.value||"")},placeholder:"Team Alpha",type:"text",value:F.createGroupDisplayName}))),y("div",{class:"section-actions coordinator-admin-groups-toolbar"},y("div",{class:"coordinator-admin-primary-actions"},y("button",{class:"settings-button",disabled:v,type:"submit"},F.groupActionPendingKind==="create"?"Creating…":"Create Team")),y("div",{class:"coordinator-admin-secondary-actions"},y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:"coordinatorAdminShowArchivedLabel"},"Show archived"),y(Gr,{"aria-labelledby":"coordinatorAdminShowArchivedLabel",checked:F.showArchivedGroups,className:"coordinator-admin-switch",disabled:t.readiness!=="ready",onCheckedChange:h=>{F.showArchivedGroups=h,i()},thumbClassName:"coordinator-admin-switch-thumb"})))))})(),p.length?y("div",{class:"peer-list"},p.map(v=>{const h=v.group_id===c,g=F.groupActionPendingId===v.group_id,_=!!v.archived_at,w=F.groupRenameDrafts.get(v.group_id)??v.display_name??v.group_id,S=F.groupPreferencesOpen.has(v.group_id),N=F.groupScopeManagementOpen.has(v.group_id),k=_?"unarchive":"archive",E=_x(_,g&&F.groupActionPendingKind===k),R=YI({groupId:v.group_id,preferences:F.groupPreferencesDrafts.get(v.group_id),scopeManagement:F.groupScopeManagementDrafts.get(v.group_id),setupGuide:F.teamSetupGuide});return y("div",{class:"peer-card peer-card--padded",key:v.group_id},y("div",{class:"peer-title"},y("strong",null,w)),y("div",{class:"peer-submeta"},_?"Archived Team":"Active Team"),y("div",{class:"peer-meta"},`Advanced: Team ID ${v.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,R.defaultSpace)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Auto-grant"),y("strong",null,R.autoGrant)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Spaces"),y("strong",null,R.spaces))),s===v.group_id?y("div",{class:"peer-submeta"},"This node uses this Team for coordinator-backed discovery."):null,y("label",{class:"coordinator-admin-field"},y("span",null,"Display name"),y(we,{class:"peer-scope-input",disabled:t.readiness!=="ready"||g,onInput:j=>{F.groupRenameDrafts.set(v.group_id,String(j.currentTarget.value||""))},type:"text",value:w})),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:t.readiness!=="ready"||h,onClick:()=>{Al(v.group_id),o()},type:"button"},h?"Managing":"Manage Team"),y("button",{class:"settings-button",disabled:t.readiness!=="ready"||g,onClick:()=>r(v.group_id,w,"rename"),type:"button"},g&&F.groupActionPendingKind==="rename"?"Renaming…":"Rename"),y("button",{"aria-expanded":S,"aria-controls":`coord-admin-project-defaults-drawer-${v.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":S?"open":"closed",disabled:t.readiness!=="ready"||g,onClick:()=>{S?Xa(v.group_id,i):Wl(v.group_id,i)},type:"button"},y("span",null,"Team defaults"),y("span",{"aria-hidden":"true",class:"device-row-chevron"},y(lg,null))),y("button",{"aria-expanded":N,"aria-controls":`coord-admin-spaces-drawer-${v.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":N?"open":"closed",disabled:t.readiness!=="ready"||g,onClick:()=>{N?cg(v.group_id,i):Vl(v.group_id,i)},type:"button"},y("span",null,"Spaces & access"),y("span",{"aria-hidden":"true",class:"device-row-chevron"},y(lg,null))),y("button",{class:_?"settings-button":"settings-button danger",disabled:t.readiness!=="ready"||g,onClick:()=>r(v.group_id,v.display_name||v.group_id,k),type:"button"},E)),y(Ia,{open:S,onOpenChange:j=>{j?Wl(v.group_id,i):Xa(v.group_id,i)}},y(Ea,{"aria-label":`Project defaults for ${w}`,class:"coordinator-admin-group-preferences",id:`coord-admin-project-defaults-drawer-${v.group_id}`},S?yx(v.group_id,i,t.readiness==="ready"):null)),y(Ia,{open:N,onOpenChange:j=>{j?Vl(v.group_id,i):cg(v.group_id,i)}},y(Ea,{"aria-label":`Spaces for ${w}`,class:"coordinator-admin-group-preferences coordinator-admin-domain-management",id:`coord-admin-spaces-drawer-${v.group_id}`},N?hx({groupId:v.group_id,ready:t.readiness==="ready",renderShell:i,summary:t}):null)))})):y("div",{class:"peer-meta coordinator-admin-empty-state"},t.readiness==="ready"?F.showArchivedGroups?"No Teams are available yet.":"No active Teams yet. Create one to get started.":"Team browsing will appear here once setup is complete."))}function Vr(e){return a("textarea",{...e})}function Sx(e){const{summary:t,createInvite:n,renderShell:r}=e,i=b.lastCoordinatorAdminStatus,o=Zn()||String(i?.active_group||"").trim(),s=F.inviteGroup.trim()||o,c=String(b.lastTeamInvite?.encoded||"").trim(),l=Array.isArray(b.lastTeamInvite?.warnings)?b.lastTeamInvite?.warnings:[],d=t.readiness!=="ready"||F.invitePending;return y(Yn,{className:"coordinator-admin-panel",value:"invites"},y("h3",null,"Legacy Team invites"),y("p",{class:"peer-submeta"},t.readiness==="ready"?"Legacy Team invites enroll a device in the selected Team. They do not grant project access; share projects from Projects instead.":"Finish setup first. Invite creation stays disabled until the local Teams configuration is ready."),y("form",{class:"coordinator-admin-form",onSubmit:u=>{u.preventDefault(),!d&&n()}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"Team"),y(we,{class:"peer-scope-input",disabled:t.readiness!=="ready",onInput:u=>{F.inviteGroup=String(u.currentTarget.value||""),r()},placeholder:o||"team-alpha",type:"text",value:F.inviteGroup})),y("label",{class:"coordinator-admin-field"},y("span",null,"Join policy"),y(kn,{ariaLabel:"Invite join policy",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:t.readiness!=="ready",id:"coordinatorAdminInvitePolicy",itemClassName:"sync-radix-select-item",onValueChange:u=>{F.invitePolicy=u==="approval_required"?"approval_required":"auto_admit",r()},options:[{value:"auto_admit",label:"Auto-admit to Team"},{value:"approval_required",label:"Require approval to join Team"}],triggerClassName:"sync-radix-select-trigger sync-actor-select",value:F.invitePolicy,viewportClassName:"sync-radix-select-viewport"})),y("label",{class:"coordinator-admin-field"},y("span",null,"Expires in (hours)"),y(we,{class:"peer-scope-input",disabled:t.readiness!=="ready",min:"1",onInput:u=>{F.inviteTtlHours=String(u.currentTarget.value||"")},type:"number",value:F.inviteTtlHours}))),y("div",{class:"section-actions"},y("button",{class:"settings-button",disabled:d,type:"submit"},F.invitePending?"Creating…":"Create legacy Team invite"),s?y("span",{class:"peer-submeta"},`Using Team ${s}`):null)),c?y("label",{class:"coordinator-admin-field"},y("span",null,"Generated invite"),y(Vr,{class:"feed-search coordinator-admin-output",readOnly:!0,value:c}),y("button",{class:"settings-button sync-action-copy",type:"button",onClick:u=>Oi(c,u.currentTarget)},"Copy")):null,l?.length?y("div",{class:"peer-meta coordinator-admin-warning-list"},l.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."),b.lastShareOperations.length>0?y("ul",{class:"peer-scope-rejections-list","aria-label":"Project sharing operations"},...b.lastShareOperations.map(u=>y("li",{key:u.operation_id},y("strong",null,u.person.display_name),y("span",null,` — ${u.projects.map(p=>p.display_name).join(", ")} — ${u.lifecycle.label}`)))):y("div",{class:"peer-meta"},"No project sharing operations yet."))}function Cx(e){const{summary:t,reviewJoinRequest:n}=e,r=Array.isArray(b.lastCoordinatorAdminJoinRequests)?b.lastCoordinatorAdminJoinRequests:[];return y(Yn,{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 Team. Default Space access is handled by Team defaults and can be reviewed in Spaces.":"Finish setup first. Join request review stays disabled until Teams is ready."),r.length?y("div",{class:"peer-list"},r.map(i=>{const o=String(i.request_id||"").trim(),s=String(i.device_id||"unknown-device"),c=String(i.display_name||s).trim()||s,l=String(i.fingerprint||"").trim(),d=[`Device ID ${s}`];l&&d.push(`Fingerprint ${l}`);const u=F.joinReviewPendingId===o;return y("div",{class:"peer-card peer-card--padded",key:o||s},y("div",{class:"peer-title"},y("strong",null,c)),y("div",{class:"peer-meta"},`Advanced: ${d.join(" · ")}`),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:!o||u,onClick:()=>n(o,"approve"),type:"button"},u&&F.joinReviewPendingAction==="approve"?"Approving…":"Approve"),y("button",{class:"settings-button danger",disabled:!o||u,onClick:()=>n(o,"deny"),type:"button"},u&&F.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."))}function Nx(e){const{renderShell:t,reloadData:n}=e;async function r(){if(F.groupActionPendingKind)return;const l=F.createGroupId.trim();if(!l){ne("Enter a Team id before creating a Team.","warning");return}const d=F.createGroupDisplayName.trim();F.groupActionPendingKind="create",t();try{const u=await Z_({group_id:l,display_name:d||null}),p=u.default_space,f=(p&&"scope"in p?p.scope:p)??{},m=p&&"preferences"in p?p.preferences:null,v=String(f?.scope_id||"");F.createGroupId="",F.createGroupDisplayName="",F.teamSetupGuide={groupId:l,displayName:String(u.group?.display_name||d||l),defaultSpaceScopeId:v,defaultSpaceLabel:String(f?.label||""),autoGrantDefaultSpaceOnJoin:typeof m?.auto_grant_default_space_on_join=="boolean"?m.auto_grant_default_space_on_join:null,setupWarning:u.setup_warning||null},await n(),Al(l),await n(),u.setup_warning?ne("Team created, but default Space setup needs repair.","warning"):v?ne("Team created with a default Space.","success"):ne("Team created, but default Space status is unknown.","warning")}catch(u){ne(u instanceof Error?u.message:"Failed to create Team.","warning")}finally{F.groupActionPendingKind="",t()}}async function i(l,d,u){if(!(!l||F.groupActionPendingId)&&!((u==="archive"||u==="unarchive")&&!await Ht({title:`${u==="archive"?"Archive":"Unarchive"} ${d||l}?`,description:u==="archive"?"Archived Teams stay visible and restorable, but they stop being operational for new invites and joins.":"This Team will become operational again for invites and coordinator-backed joins.",confirmLabel:u==="archive"?"Archive Team":"Unarchive Team",cancelLabel:u==="archive"?"Keep Team active":"Keep Team archived",tone:"danger"}))){F.groupActionPendingId=l,F.groupActionPendingKind=u,t();try{u==="rename"&&(await ew(l,d),ne("Team renamed.","success")),u==="archive"&&(await tw(l),ne("Team archived.","success")),u==="unarchive"&&(await nw(l),ne("Team unarchived.","success")),await n()}catch(p){ne(p instanceof Error?p.message:`Failed to ${u} Team.`,"warning")}finally{F.groupActionPendingId="",F.groupActionPendingKind="",t()}}}async function o(){if(F.invitePending)return;const l=b.lastCoordinatorAdminStatus,d=Zn()||String(l?.active_group||"").trim(),u=F.inviteGroup.trim()||d,p=Number(F.inviteTtlHours);if(!u){ne("Choose a Team before creating an invite.","warning");return}if(!Number.isFinite(p)||p<1){ne("Invite lifetime must be at least 1 hour.","warning");return}F.invitePending=!0,t();try{const f=await Qu({group_id:u,policy:F.invitePolicy,ttl_hours:p});b.lastTeamInvite=f,F.inviteGroup=u;const m=Array.isArray(f.warnings)?f.warnings:[];ne(m.length?`Invite created. Review ${m.length===1?"the warning":`${m.length} warnings`} before sharing it.`:"Invite created. Copy it from Teams and share it with your teammate.",m.length?"warning":"success")}catch(f){ne(f instanceof Error?f.message:"Failed to create invite.","warning")}finally{F.invitePending=!1,t()}}async function s(l,d){if(!F.joinReviewPendingId){F.joinReviewPendingId=l,F.joinReviewPendingAction=d,t();try{const u=await lw(l,d);d==="approve"&&u.setup_warning?ne("Join request approved, but default Space access needs repair.","warning"):ne(d==="approve"?"Join request approved.":"Join request denied.","success"),await n()}catch(u){ne(u instanceof Error?u.message:"Failed to review join request.","warning")}finally{F.joinReviewPendingId="",F.joinReviewPendingAction="",t()}}}async function c(l,d,u,p){if(!(!l||F.deviceActionPendingId)&&!((p==="disable"||p==="remove")&&!await Ht({title:`${p==="disable"?"Disable":"Remove"} ${u||l}?`,description:p==="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:p==="disable"?"Disable device":"Remove device",cancelLabel:p==="disable"?"Keep device enabled":"Keep device enrolled",tone:"danger"}))){F.deviceActionPendingId=l,F.deviceActionPendingKind=p,t();try{if(p==="rename"){const f=String(F.deviceRenameDrafts.get(l)||"").trim();if(!f){ne("Enter a device name before renaming it.","warning");return}await dw(l,d,f),ne("Device renamed.","success")}p==="disable"&&(await uw(l,d),ne("Device disabled.","success")),p==="enable"&&(await pw(l,d),ne("Device enabled.","success")),p==="remove"&&(await fw(l,d),ne("Device removed.","success")),await n()}catch(f){ne(f instanceof Error?f.message:`Failed to ${p} device.`,"warning")}finally{F.deviceActionPendingId="",F.deviceActionPendingKind="",t()}}}return{createGroupFromAdminPanel:r,runGroupAction:i,createInviteFromAdminPanel:o,reviewJoinRequestFromAdminPanel:s,runDeviceAction:c}}function kx(){const e=b.lastCoordinatorAdminStatus;return e?e.readiness==="ready"?{readiness:"ready",title:"Teams is ready",detail:"This viewer can use the local Teams admin configuration to manage invites, join requests, and enrolled devices without exposing the admin secret to the browser."}:e.readiness==="partial"?{readiness:"partial",title:"Teams setup is incomplete",detail:e.has_admin_secret===!1?"Set a coordinator admin secret for the viewer server before using Teams invite and device actions.":"Finish configuring the coordinator target and Team before using Teams actions."}:{readiness:"not_configured",title:"Teams is not configured",detail:"Set a coordinator URL, Team, and admin secret locally to enable remote Teams administration from this viewer."}:{readiness:"partial",title:"Checking Teams readiness…",detail:"Loading local Teams configuration from the viewer server."}}var{createGroupFromAdminPanel:Tx,runGroupAction:Ix,createInviteFromAdminPanel:Ex,reviewJoinRequestFromAdminPanel:xx,runDeviceAction:Px}=Nx({renderShell:()=>rr(),reloadData:()=>zl()});function rr(){const e=document.getElementById("coordinatorAdminMount");if(!e)return;const t=b.lastCoordinatorAdminStatus,n=kx(),r=String(t?.coordinator_url||"").trim(),i=String(t?.active_group||"").trim(),s=!!HI()?.archived_at,c=n.readiness==="ready",l=n.readiness==="ready"&&!s,d=n.readiness==="ready",u=n.readiness==="ready",p=Zn(),f=Hr().filter(_=>!_.archived_at).length,m=Hr().filter(_=>_.archived_at).length,v=Array.isArray(b.lastCoordinatorAdminJoinRequests)?b.lastCoordinatorAdminJoinRequests.length:0,h=Array.isArray(b.lastCoordinatorAdminDevices)?b.lastCoordinatorAdminDevices.length:0,g=n.readiness!=="ready"?n.detail:s?"The selected Team is archived. Restore it or switch Teams before creating invites.":"";(F.activeSection==="invites"&&!l||F.activeSection==="groups"&&!c||F.activeSection==="join-requests"&&!d||F.activeSection==="devices"&&!u)&&(F.activeSection=n.readiness==="ready"?"groups":"invites"),Be(y("div",{class:"coordinator-admin-shell"},y("div",{class:"card coordinator-admin-header"},y("div",{class:"section-header"},y("h2",null,"Teams")),y("div",{class:"coordinator-admin-summary-grid"},y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Team admin target"),y("strong",null,p||"None selected")),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Node discovery Team"),y("strong",null,i||"None")),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Teams"),y("strong",null,`${f} active${m?` · ${m} archived`:""}`)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Selected Team activity"),y("strong",null,`${v} join requests · ${h} devices`))),g?y("div",{class:"peer-meta coordinator-admin-inline-warning"},g):null,r?y("div",{class:"section-meta coordinator-admin-inline-meta"},`Coordinator: ${r}`):null),y("div",{class:"card coordinator-admin-sections"},y(vh,{ariaLabel:"Teams sections",listClassName:"coordinator-admin-tabs-list",onValueChange:_=>{F.activeSection=_||"groups",rr()},tabs:[{value:"groups",label:"Teams",disabled:!c},{value:"invites",label:"Invites",disabled:!l},{value:"join-requests",label:"Join requests",disabled:!d},{value:"devices",label:"Devices",disabled:!u}],triggerClassName:"coordinator-admin-tab-trigger",value:F.activeSection},wx({summary:n,createGroup:()=>{Tx()},runGroup:(_,w,S)=>{Ix(_,w,S)},renderShell:rr,reloadData:()=>{zl()}}),Sx({summary:n,createInvite:()=>{Ex()},renderShell:rr}),Cx({summary:n,reviewJoinRequest:(_,w)=>{xx(_,w)}}),lT({summary:n,runDevice:(_,w,S,N)=>{Px(_,w,S,N)}})),y("div",{class:"section-meta coordinator-admin-context-line"},s?`Selected Team ${p||"—"} is archived. Switch or restore it to enable invite operations.`:p?`Actions below apply to ${p}.`:"Select a Team to start managing people, Spaces, and access."))),e)}function Ax(){rr()}async function zl(){try{b.lastCoordinatorAdminStatus=await Do()}catch{b.lastCoordinatorAdminStatus=null,b.lastCoordinatorAdminJoinRequests=[],b.lastCoordinatorAdminDevices=[],F.deviceRenameDrafts.clear(),F.deviceRenameServerNames.clear(),rr();return}const e=String(b.lastCoordinatorAdminStatus?.active_group||"").trim();if(wv(),b.lastCoordinatorAdminStatus?.readiness==="ready"){try{const n=await pp();b.lastShareOperations=Array.isArray(n.items)?n.items:[]}catch{}try{const n=await Yu(F.showArchivedGroups);b.lastCoordinatorAdminGroups=Array.isArray(n?.items)?n.items:[],GI(),wv()}catch{b.lastCoordinatorAdminGroups=[],F.groupRenameDrafts.clear()}const t=Zn();try{const n=await cw(t||e);b.lastCoordinatorAdminJoinRequests=Array.isArray(n?.items)?n.items:[]}catch{b.lastCoordinatorAdminJoinRequests=[]}try{const n=await Xu(t||e,!0);b.lastCoordinatorAdminDevices=Array.isArray(n?.items)?n.items:[],qI()}catch{b.lastCoordinatorAdminDevices=[]}try{F.availableProjects=await Lo()}catch{F.availableProjects=[]}}else b.lastCoordinatorAdminGroups=[],F.groupRenameDrafts.clear(),b.lastCoordinatorAdminJoinRequests=[],b.lastCoordinatorAdminDevices=[],F.deviceRenameDrafts.clear(),F.deviceRenameServerNames.clear();rr()}function Jl(e){return e.inventoryUnavailable===!0||e.refreshError===!0}var Yl=new WeakMap,dg={active:0,verifying:1,pending:2,waiting:3,needs_attention:4},Rx={state:"pending",label:"Recipient policy pending",explanation:"Current access remains in place while this Project is prepared.",deliveredCopiesMayRemain:!0},Dx={available:"Available",offline:"Offline",unknown:"Availability unknown"};function Lx(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function $x(e,t){return t.get(e)??Rx}function Mx(e){return e.reduce((t,n)=>!t||dg[n.state]>dg[t.state]?n:t,null)}function Ox(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 jx(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=Lx(e.projectRecipients.filter(S=>S.status==="active"&&S.recipientKind==="identity"&&S.identityId===u.identityId).map(S=>S.canonicalProjectIdentity)),m=S=>{const N=s.get(S);if(!N)return null;const k=$x(S,d);return{canonicalProjectIdentity:S,displayName:N,state:k.state,statusLabel:k.label,statusCopy:k.explanation,deliveredCopiesMayRemain:k.deliveredCopiesMayRemain}},v=f.flatMap(S=>{const N=m(S);return N?[N]:[]}),h=[],g=[...v,...h],_=Mx(g),w=c.get(u.deviceId)??"unknown";return{deviceId:u.deviceId,displayName:u.displayName,identityName:o.get(u.identityId)??"Identity unavailable",availability:w,availabilityLabel:Dx[w],isPairedPeer:p!==void 0,reportedRuntimeVersion:p?.runtimeVersion??null,runtimeVersionObservedAt:p?.runtimeVersionObservedAt??null,directProjects:v,inheritedProjects:h,unavailableProjectCount:f.length-v.length,statusState:_?.state??"no_projects",statusLabel:_?.statusLabel??"No directly shared Projects",statusCopy:_?.statusCopy??"Team access is not shown here without authoritative per-device eligibility.",deliveredCopiesMayRemain:g.some(S=>S.deliveredCopiesMayRemain),action:Ox(w,_?.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 ug({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 zi(e){if(!(e instanceof Xs))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 Qa(e,t){return{targetIdentityId:e.state==="setup_required"&&e.suggestedIdentityId&&t.has(e.suggestedIdentityId)?e.suggestedIdentityId:"",selected:!1,explicit:!1,itemSignature:Ji(e)}}function Ji(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 Za(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 pg="devices-commit-status";function cn(e){const t=document.getElementById(pg);t&&(t.textContent=e)}function Fx({intent:e,inventory:t,items:n,options:r}){const i=e.identities.filter(x=>x.status==="active"&&x.mergedIntoIdentityId===null),o=new Map(i.map(x=>[x.identityId,x.displayName])),s=new Set(o.keys()),[c,l]=D(()=>Object.fromEntries(n.map(x=>[x.deviceId,Qa(x,s)]))),[d,u]=D(null),[p,f]=D(!1),[m,v]=D(!1),[h,g]=D(""),_=U(null),w=U(0),S=r.previewBindings??sp,N=r.commitBindings??cp,k=Jl(r),E=d!==null&&Za(d.preview,d.request,n,"bind"),R=Ee(()=>n.filter(x=>x.state==="setup_required"&&c[x.deviceId]?.selected),[c,n]),j=JSON.stringify({items:t.items.map(Ji),coordinatorEvidence:t.coordinatorEvidence,truncated:t.truncated}),q=i.map(x=>`${x.identityId}:${x.displayName}`).sort().join("|");K(()=>{d&&_.current?.focus()},[d]),K(()=>{w.current+=1,v(!1),l(x=>Object.fromEntries(n.map(O=>{const T=x[O.deviceId];if(!T)return[O.deviceId,Qa(O,s)];if(O.state!=="setup_required")return[O.deviceId,Qa(O,s)];const P=T.targetIdentityId!==""&&s.has(T.targetIdentityId);return T.itemSignature===Ji(O)&&P?[O.deviceId,T]:T.explicit&&P?[O.deviceId,{...T,selected:!1,itemSignature:Ji(O)}]:[O.deviceId,Qa(O,s)]}))),u(null),f(!1)},[j,q]);const I=(x,O)=>{w.current+=1,v(!1),l(T=>({...T,[x]:{...T[x],...O}})),u(null),f(!1),g(""),cn("")},G=x=>({bindings:x.map(O=>{const T=c[O.deviceId];return{deviceId:O.deviceId,targetIdentityId:T?.targetIdentityId??"",confirmed:!0}})}),A=async x=>{if(k){g("Refresh Devices before reviewing Identity setup.");return}if(x.some(P=>P.state!=="setup_required")){g("Only devices that require Identity setup can be reviewed here.");return}const O=x.find(P=>ua(t,P).blocked);if(O){g(ua(t,O).recovery??"Identity setup is unavailable.");return}if(x.length===0||x.some(P=>!c[P.deviceId]?.targetIdentityId)){g("Choose an Identity for every selected device before review.");return}v(!0),g(""),cn("");const T=w.current;try{const P=G(x),B=await S(P);T===w.current&&(Za(B,P,x,"bind")?u({preview:B,request:P}):g("Identity setup preview was incomplete. Refresh and try again."))}catch(P){T===w.current&&g(zi(P))}T===w.current&&v(!1)},M=async()=>{if(!(!d||!p||k||!E)){v(!0),g("");try{await N({...d.request,reviewedInventoryDigest:d.preview.reviewedInventoryDigest}),u(null),f(!1),cn("Identity setup completed.");const x=await r.onCommitted?.();cn(x===!1?"Identity setup completed, but refreshing Devices and Sharing failed. Refresh to see current state.":x===!0?"Identity setup completed. Devices and Sharing were refreshed.":"Identity setup completed."),document.getElementById("devices-heading")?.focus()}catch(x){g(zi(x))}v(!1)}},L=n.filter(x=>x.state==="setup_required");return n.length===0?null:a(Z,{children:[h?a("p",{role:"alert",children:h}):null,L.length>1?a("div",{className:"device-identity-setup-summary",children:[a("strong",{children:[L.length.toLocaleString()," devices need Identity setup"]}),a("button",{className:"settings-button",disabled:m||k||R.length===0,onClick:()=>{A(R)},type:"button",children:["Review ",R.length.toLocaleString()," selected"]})]}):null,a("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:n.map((x,O)=>{const T=c[x.deviceId],P=ua(t,x),B=P.blocked||k,V=`device-inventory-title-${O}`;return a("li",{children:a("article",{"aria-labelledby":V,className:"peer-card peer-card--padded recipient-policy-sharing-card device-identity-setup-card",id:`device-identity-card-${x.deviceId}`,tabIndex:-1,children:[a("div",{className:"peer-title recipient-policy-sharing-card-title",children:[a("h3",{id:V,children:[x.displayName,x.isLocal?" (this device)":""]}),a("span",{className:"badge actor-badge",children:x.state==="setup_required"?"Setup required":x.state==="pairing_required"?"Pairing required":x.state==="conflicted"?"Review required":"Configured"})]}),x.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,L.length>1?a("label",{children:[a("input",{"aria-label":`Select for setup: ${x.displayName}`,checked:T?.selected??!1,disabled:B,onInput:le=>I(x.deviceId,{selected:le.currentTarget.checked}),type:"checkbox"})," ","Select for setup"]}):null,a("label",{htmlFor:`${V}-identity`,children:"Identity"}),a("select",{"aria-label":`Choose an Identity for ${x.displayName}`,disabled:B,id:`${V}-identity`,onInput:le=>I(x.deviceId,{targetIdentityId:le.currentTarget.value,explicit:!0}),value:T?.targetIdentityId??"",children:[a("option",{value:"",children:"Choose Identity…"}),i.map(le=>a("option",{value:le.identityId,children:le.displayName},le.identityId))]}),x.suggestedIdentityId&&o.has(x.suggestedIdentityId)?a("p",{className:"small",children:"Suggested from historical device information. Review it before applying setup."}):null,P.recovery?a("p",{className:"small",children:P.recovery}):null]}),a("div",{className:"device-identity-card-actions",children:[i.length===0?a("button",{"aria-label":`Open Identity administration for ${x.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Open Identity administration"}):null,a("button",{"aria-label":`Review this device: ${x.displayName}`,className:"settings-button",disabled:m||B||!T?.targetIdentityId,onClick:()=>{A([x])},type:"button",children:"Review this device"})]})]}):x.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 ${x.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Go to pairing"})})]}):x.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 ${x.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Open Advanced review"})})]}):null]})},x.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:_,tabIndex:-1,children:"Review Identity setup"}),a("ul",{children:d.preview.outcomes.map(x=>a("li",{children:[a("strong",{children:[x.displayName,":"]})," ",x.previousIdentityId?o.get(x.previousIdentityId)??"Unavailable Identity":"No Identity"," ","→ ",o.get(x.targetIdentityId)??"Unavailable Identity"]},x.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:k,onInput:x=>f(x.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||k||!p||!E,onClick:()=>{M()},type:"button",children:["Apply setup to ",d.request.bindings.length.toLocaleString()," ",d.request.bindings.length===1?"device":"devices"]})]})]}):null]})}function fg({intent:e,inventory:t,item:n,options:r,previousIdentityName:i}){const o=e.identities.filter(x=>x.status==="active"&&x.mergedIntoIdentityId===null&&x.identityId!==n.identityId),[s,c]=D(!1),[l,d]=D(""),[u,p]=D(!1),[f,m]=D(null),[v,h]=D(!1),[g,_]=D(!1),[w,S]=D(""),N=U(0),k=i,E=new Map(e.identities.map(x=>[x.identityId,x.displayName])),R=f?.preview.status==="ready"&&f.preview.outcomes.length===1?f.preview.outcomes[0]:null,j=f!==null&&Za(f.preview,f.request,[n],"rebind"),q=ua(t,n),I=q.blocked||Jl(r),G=`configured-rebind-trigger-${n.deviceId}`,A=o.find(x=>x.identityId===l)?.displayName??"";K(()=>{N.current+=1,_(!1),l&&!o.some(x=>x.identityId===l)&&(d(""),p(!1)),m(null),h(!1)},[o.map(x=>x.identityId).sort().join("|"),Ji(n)]);const M=async()=>{if(I){S(q.recovery??"Identity reassignment is unavailable.");return}if(!l||!u){S("Choose a target Identity and confirm the reassignment before review.");return}_(!0),S(""),cn("");const x=N.current;try{const O={bindings:[{deviceId:n.deviceId,targetIdentityId:l,confirmed:u,allowRebind:!0}]},T=await(r.previewBindings??sp)(O);x===N.current&&(T.status!=="ready"?S(zi(new Xs(409,T.errorCode??"binding_preview_unavailable",T))):Za(T,O,[n],"rebind")?m({preview:T,request:O}):S("Identity reassignment preview was incomplete. Refresh and try again."))}catch(O){x===N.current&&S(zi(O))}x===N.current&&_(!1)},L=async()=>{if(!(!f||!v||I||!j)){_(!0),S("");try{await(r.commitBindings??cp)({...f.request,reviewedInventoryDigest:f.preview.reviewedInventoryDigest}),c(!1),d(""),p(!1),m(null),h(!1),cn("Identity reassignment completed.");const x=await r.onCommitted?.();cn(x===!1?"Identity reassignment completed, but refreshing Devices and Sharing failed. Refresh to see current state.":x===!0?"Identity reassignment completed. Devices and Sharing were refreshed.":"Identity reassignment completed."),(document.getElementById(G)??document.getElementById("devices-heading"))?.focus()}catch(x){S(zi(x))}_(!1)}};return a("div",{className:"device-identity-rebind",children:[a("button",{"aria-expanded":s,className:"settings-button",disabled:I,id:G,onClick:()=>{N.current+=1,_(!1),c(!s),m(null),h(!1),S(""),cn("")},type:"button",children:"Change Identity…"}),q.recovery?a("p",{className:"small",children:q.recovery}):null,s?a("fieldset",{children:[a("legend",{children:"Reassign this configured device"}),a("p",{children:[a("strong",{children:"Suggested current Identity (unconfirmed):"})," ",k]}),a("label",{htmlFor:`configured-rebind-${n.deviceId}`,children:"Target Identity"}),a("select",{disabled:I,id:`configured-rebind-${n.deviceId}`,onInput:x=>{N.current+=1,_(!1),d(x.currentTarget.value),p(!1),m(null),h(!1)},value:l,children:[a("option",{value:"",children:"Choose a different Identity…"}),o.map(x=>a("option",{value:x.identityId,children:x.displayName},x.identityId))]}),a("label",{children:[a("input",{checked:u,disabled:I||!l,onInput:x=>{N.current+=1,_(!1),p(x.currentTarget.checked),m(null),h(!1)},type:"checkbox"})," ","Confirm reassigning ",n.displayName," to ",A||"the selected Identity"]}),a("button",{className:"settings-button",disabled:g||I,onClick:()=>{M()},type:"button",children:"Review reassignment"}),f?a("div",{className:"device-identity-rebind-review",children:[a("h4",{children:"Review reassignment"}),a("p",{children:[R?.displayName,":"," ",R?.previousIdentityId?E.get(R.previousIdentityId)??"Unavailable Identity":"No Identity"," ","→"," ",E.get(R?.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:I,onInput:x=>h(x.currentTarget.checked),type:"checkbox"})," ","I reviewed the previous and target Identities"]}),a("button",{className:"settings-button sync-dialog-confirm",disabled:g||I||!v||!j,onClick:()=>{L()},type:"button",children:"Reassign Identity"})]}):null,w?a("p",{"aria-live":"assertive",role:"alert",children:w}):null]}):null]})}function Bx({intent:e,options:t,projection:n}){if(t.loading)return a(sm,{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=cm(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}`,h=e.identities.find(g=>g.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:"})," ",h]}),a(fg,{intent:e,inventory:t.inventory,item:f,options:t,previousIdentityName:h})]})},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(Fx,{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}`,h=f.action,g=t.inventory?.items.find(_=>_.state==="configured"&&_.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:[Jl(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(ug,{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(ug,{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,h&&t.onNavigate?a("button",{"aria-label":`${h.label} for ${f.displayName}`,className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onNavigate?.(h.target),ref:_=>{_&&Yl.set(_,{deviceId:f.deviceId,target:h.target})},type:"button",children:h.label}):null,g&&t.inventory?a(fg,{intent:e,inventory:t.inventory,item:g,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 es(e,t,n,r,i,o={}){const s=document.activeElement,c=s instanceof HTMLElement&&e.contains(s),l=c?Yl.get(s):void 0,d=jx(t,n,r,i,o.peerRuntimeMetadata);if(Be(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(Bx,{intent:t,options:o,projection:d}),a("p",{"aria-live":"polite",id:pg,role:"status"})]}),e),cn(""),!o.loading&&b.pendingDeviceIdentityFocus!==void 0){const u=b.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)b.pendingDeviceIdentityFocus=void 0;else if(f){b.pendingDeviceIdentityFocus=void 0,f.focus();return}else if(!o.inventoryUnavailable&&!o.refreshError){b.pendingDeviceIdentityFocus=void 0,(document.getElementById("devices-heading")??document.getElementById("tabBtn-devices"))?.focus();return}}l&&([...e.querySelectorAll("button")].find(u=>{const p=Yl.get(u);return p?.deviceId===l.deviceId&&p.target===l.target})??document.getElementById("tabBtn-devices"))?.focus()}function Ux(e){if(!e)return"n/a";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function ir(e){if(!e)return"never";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function Gx(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 Wr(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 Tn(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 mg(e){const t=Number(e);return Number.isFinite(t)?`${Math.round(t*100)}%`:"n/a"}function Hx(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 Xl(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 Yi(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 qx(e){const t=String(e||"").trim();if(!t.endsWith("%"))return null;const n=Number(t.replace("%",""));return Number.isFinite(n)?n:null}function Xi(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function ts(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 hg(e){const t=String(e||"").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function Kx(e){return e.replace(/_/g," ").split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ").trim()}function Vx(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 vg(e){if(!e)return"";const t=String(e).trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n).trim()}function Wx(e){const t=String(e||"");return t?t.replace(/^\/Users\/[^/]+(?=\/|$)/,"~").replace(/^\/home\/[^/]+(?=\/|$)/,"~").replace(/^[A-Z]:\\Users\\[^\\]+(?=\\|$)/,"~"):""}function zx(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 gg(e){if(e.owned_by_self===!0)return!0;const t=String(e.actor_id||"").trim();return!!(t&&t===b.lastStatsPayload?.identity?.actor_id)}function ns(e){if(!e||typeof e!="object")return{};const t=e,n=t.import_metadata;return n&&typeof n=="object"?{...n,...t}:t}function Jx(e){if(!e)return[];const t=String(e).split(`
46
+ `).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 Yx(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 yg(e){const t=Xi(e.title),n=Xi(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 bg(e){return String(e.id??e.memory_id??e.observation_id??e.session_id??e.created_at_utc??e.created_at??"")}function ft(e){return`${String(e.kind||"").toLowerCase()}:${bg(e)}`}function Xx(e){if(e.tags!=null)return ts(e.tags);const t=ts(e.tags_text);return t.length>0?t:typeof e.tags_text!="string"?[]:e.tags_text.trim().split(/\s+/).filter(Boolean)}function Qx(e){return e==="mine"?" · my memories":e==="theirs"?" · other people":""}function Zx(e){return e==="legacy_unknown"?"legacy provenance":e==="unreviewed"?"unreviewed":e.replace(/_/g," ")}function eP(e){if(gg(e))return"You";const t=String(e.actor_id||"").trim(),n=xr(e.resolved_actor_display_name);return n||(t||e.actor_display_name?"Teammate":"Unknown author")}function tP(e,t={}){if(gg(e)||!String(e.origin_device_id||t.origin_device_id||"").trim())return"";const n=xr(e.resolved_device_display_name);return n?`Device ${n}`:"Shared device"}function _g(e,t){const n=new Map;return e.forEach(r=>{n.set(ft(r),r)}),t.forEach(r=>{n.set(ft(r),r)}),Array.from(n.values()).sort((r,i)=>new Date(i.created_at||0).getTime()-new Date(r.created_at||0).getTime())}function nP(e,t){const n=new Set(t.map(ft));return _g(e.filter(r=>!n.has(ft(r))),t)}var Rj=560;function rP(){const e=document.documentElement,t=Math.max(e.scrollHeight,document.body.scrollHeight);return window.innerHeight+window.scrollY>=t-560}function rs(e,t,n){const r=e.pagination?.has_more;return typeof r=="boolean"?r:t>=n}function is(e,t){const n=e.pagination?.next_offset;return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:t}function iP(e,t){const n=new Set(t.map(ft));return e.filter(r=>!n.has(ft(r))).length}var[os,Dj]=ot("Tooltip",[_n]),as=_n(),wg="TooltipProvider",oP=700,Ql="tooltip.open",[aP,Zl]=os(wg),Sg=e=>{const{__scopeTooltip:t,delayDuration:n=oP,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:o}=e,s=U(!0),c=U(!1),l=U(0);return K(()=>{const d=l.current;return()=>window.clearTimeout(d)},[]),a(aP,{scope:t,isOpenDelayedRef:s,delayDuration:n,onOpen:ie(()=>{window.clearTimeout(l.current),s.current=!1},[]),onClose:ie(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.current=!0,r)},[r]),isPointerInTransitRef:c,onPointerInTransitChange:ie(d=>{c.current=d},[]),disableHoverableContent:i,children:o})};Sg.displayName=wg;var Qi="Tooltip",[sP,Zi]=os(Qi),Cg=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:o,disableHoverableContent:s,delayDuration:c}=e,l=Zl(Qi,e.__scopeTooltip),d=as(t),[u,p]=D(null),f=at(),m=U(0),v=s??l.disableHoverableContent,h=c??l.delayDuration,g=U(!1),[_,w]=Ct({prop:r,defaultProp:i??!1,onChange:R=>{R?(l.onOpen(),document.dispatchEvent(new CustomEvent(Ql))):l.onClose(),o?.(R)},caller:Qi}),S=Ee(()=>_?g.current?"delayed-open":"instant-open":"closed",[_]),N=ie(()=>{window.clearTimeout(m.current),m.current=0,g.current=!1,w(!0)},[w]),k=ie(()=>{window.clearTimeout(m.current),m.current=0,w(!1)},[w]),E=ie(()=>{window.clearTimeout(m.current),m.current=window.setTimeout(()=>{g.current=!0,w(!0),m.current=0},h)},[h,w]);return K(()=>()=>{m.current&&(window.clearTimeout(m.current),m.current=0)},[]),a(qi,{...d,children:a(sP,{scope:t,contentId:f,open:_,stateAttribute:S,trigger:u,onTriggerChange:p,onTriggerEnter:ie(()=>{l.isOpenDelayedRef.current?E():N()},[l.isOpenDelayedRef,E,N]),onTriggerLeave:ie(()=>{v?k():(window.clearTimeout(m.current),m.current=0)},[k,v]),onOpen:N,onClose:k,disableHoverableContent:v,children:n})})};Cg.displayName=Qi;var ed="TooltipTrigger",Ng=H((e,t)=>{const{__scopeTooltip:n,...r}=e,i=Zi(ed,n),o=Zl(ed,n),s=as(n),c=_e(t,U(null),i.onTriggerChange),l=U(!1),d=U(!1),u=ie(()=>l.current=!1,[]);return K(()=>()=>document.removeEventListener("pointerup",u),[u]),a(Ki,{asChild:!0,...s,children:a(se.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:c,onPointerMove:z(e.onPointerMove,p=>{p.pointerType!=="touch"&&!d.current&&!o.isPointerInTransitRef.current&&(i.onTriggerEnter(),d.current=!0)}),onPointerLeave:z(e.onPointerLeave,()=>{i.onTriggerLeave(),d.current=!1}),onPointerDown:z(e.onPointerDown,()=>{i.open&&i.onClose(),l.current=!0,document.addEventListener("pointerup",u,{once:!0})}),onFocus:z(e.onFocus,()=>{l.current||i.onOpen()}),onBlur:z(e.onBlur,i.onClose),onClick:z(e.onClick,i.onClose)})})});Ng.displayName=ed;var td="TooltipPortal",[cP,lP]=os(td,{forceMount:void 0}),kg=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,o=Zi(td,t);return a(cP,{scope:t,forceMount:n,children:a(et,{present:n||o.open,children:a(qn,{asChild:!0,container:i,children:r})})})};kg.displayName=td;var zr="TooltipContent",Tg=H((e,t)=>{const n=lP(zr,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...o}=e,s=Zi(zr,e.__scopeTooltip);return a(et,{present:r||s.open,children:s.disableHoverableContent?a(Ig,{side:i,...o,ref:t}):a(dP,{side:i,...o,ref:t})})}),dP=H((e,t)=>{const n=Zi(zr,e.__scopeTooltip),r=Zl(zr,e.__scopeTooltip),i=U(null),o=_e(t,i),[s,c]=D(null),{trigger:l,onClose:d}=n,u=i.current,{onPointerInTransitChange:p}=r,f=ie(()=>{c(null),p(!1)},[p]),m=ie((v,h)=>{const g=v.currentTarget,_={x:v.clientX,y:v.clientY},w=hP(_,mP(_,g.getBoundingClientRect())),S=vP(h.getBoundingClientRect());c(yP([...w,...S])),p(!0)},[p]);return K(()=>()=>f(),[f]),K(()=>{if(l&&u){const v=g=>m(g,u),h=g=>m(g,l);return l.addEventListener("pointerleave",v),u.addEventListener("pointerleave",h),()=>{l.removeEventListener("pointerleave",v),u.removeEventListener("pointerleave",h)}}},[l,u,m,f]),K(()=>{if(s){const v=h=>{const g=h.target,_={x:h.clientX,y:h.clientY},w=l?.contains(g)||u?.contains(g),S=!gP(_,s);w?f():S&&(f(),d())};return document.addEventListener("pointermove",v),()=>document.removeEventListener("pointermove",v)}},[l,u,s,d,f]),a(Ig,{...e,ref:o})}),[uP,pP]=os(Qi,{isInside:!1}),fP=ES("TooltipContent"),Ig=H((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:o,onPointerDownOutside:s,...c}=e,l=Zi(zr,n),d=as(n),{onClose:u}=l;return K(()=>(document.addEventListener(Ql,u),()=>document.removeEventListener(Ql,u)),[u]),K(()=>{if(l.trigger){const p=f=>{f.target?.contains(l.trigger)&&u()};return window.addEventListener("scroll",p,{capture:!0}),()=>window.removeEventListener("scroll",p,{capture:!0})}},[l.trigger,u]),a(Hn,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:p=>p.preventDefault(),onDismiss:u,children:a(Fa,{"data-state":l.stateAttribute,...d,...c,ref:t,style:{...c.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(fP,{children:r}),a(uP,{scope:n,isInside:!0,children:a(zN,{id:l.contentId,role:"tooltip",children:i||r})})]})})});Tg.displayName=zr;var Eg="TooltipArrow",xg=H((e,t)=>{const{__scopeTooltip:n,...r}=e,i=as(n);return pP(Eg,n).isInside?null:a(Ba,{...i,...r,ref:t})});xg.displayName=Eg;function mP(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")}}function hP(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});break}return r}function vP(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}]}function gP(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}function yP(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),bP(t)}function bP(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)}var _P=Sg,wP=Cg,SP=Ng,CP=kg,NP=Tg,kP=xg;function nd({children:e,delayDuration:t=400,skipDelayDuration:n=300}){return a(_P,{delayDuration:t,skipDelayDuration:n,children:e})}function ss({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(wP,{children:[a(SP,{asChild:o,children:e}),a(CP,{children:a(NP,{align:r,className:"tooltip-content",side:n,sideOffset:i,children:[t,a(kP,{className:"tooltip-arrow"})]})})]})}function TP(e){e.dataset.feedRenderRoot="preact"}function IP(){const e=document.getElementById("tab-feed");e&&(e.dataset.feedRenderBoundary="preact-hybrid")}function EP(e,t){TP(e),Be(y(nd,null,t),e)}function xP(e){return e.hasInspectorOverride?e.inspectorQuery:e.feedQuery}function PP(e){return e.split(/\n|,/).map(t=>t.trim()).filter(Boolean)}function rd(e){return JSON.stringify([e.project,e.query.trim(),e.workingSetFiles])}function AP(e){const t=ns(e?.metadata_json),n=String(e?.subtitle||t?.subtitle||"").trim(),r=String(e?.narrative||t?.narrative||e?.body_text||"").trim(),i=Xi(n),o=Xi(r),s=!!r&&o!==i,c=ts(e?.facts||t?.facts||[]),l=c.length?c:Jx(r||n),d=l.length?l:Yx(r||n);return{summary:n,narrative:r,facts:d,hasSummary:!!n,hasFacts:d.length>0,hasNarrative:s}}function RP(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 DP(e){return e.hasSummary?"summary":e.hasFacts?"facts":"narrative"}function LP(e,t){return e==="facts"?!1:e==="summary"?t.summary.length>260:t.narrative.length>320}function $P(e){return e==="summary"?["clamp","clamp-3"]:["clamp","clamp-5"]}function MP(e,t){const n=b.feedTypeFilter==="observations"?" · observations":b.feedTypeFilter==="summaries"?" · session summaries":"",r=Qx(b.feedScopeFilter),i=!b.feedQuery.trim()&&b.lastFeedFilteredCount?` · ${b.lastFeedFilteredCount} observations filtered`:"";return`${e} items${n}${r}${b.feedQuery.trim()?` · matching "${b.feedQuery.trim()}"`:""}${i}${t?" · scroll for more":""}`}function cs({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 OP({open:e}){const[t,n]=D(()=>String(b.feedQuery||"")),[r,i]=D(!1),[o,s]=D(!1),[c,l]=D(""),[d,u]=D(!1),[p,f]=D(""),[m,v]=D(""),[h,g]=D(null),_=U(0),w=String(b.feedQuery||""),S=String(t||"").trim(),N=b.currentProject||null,k=PP(c),E=rd({project:N,query:S,workingSetFiles:k}),R=h&&rd({project:h.inputs.project,query:h.inputs.query,workingSetFiles:h.inputs.working_set_files})===E?h:null,j=p&&m===E?p:"";K(()=>{_.current+=1,u(!1),f(""),v(""),g(L=>!L||L.inputs.query!==S||L.inputs.project!==N?null:L)},[E]),K(()=>{e&&!r&&(n(xP({feedQuery:w,hasInspectorOverride:o,inspectorQuery:t})),i(!0))},[w,o,r,t,e]);const q=async()=>{const L=S,x=N,O=k,T=rd({project:x,query:L,workingSetFiles:O}),P=_.current+1;if(_.current=P,!L){f("Enter a query to inspect."),v(T),g(null);return}u(!0),f(""),v("");try{const B=await gw({context:L,project:x,working_set_files:O});if(P!==_.current)return;g(B)}catch(B){if(P!==_.current)return;f(B instanceof Error?B.message:String(B)),v(T),g(null)}finally{P===_.current&&u(!1)}},I=R?.retrieval.candidates.filter(L=>L.disposition==="selected")||[],G=R?.retrieval.candidates.filter(L=>L.disposition==="dropped")||[],A=R?.retrieval.candidates.filter(L=>L.disposition==="deduped")||[],M=R?.retrieval.candidates.filter(L=>L.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:L=>{n(String(L.currentTarget.value||"")),s(!0),g(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:L=>l(String(L.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:()=>{q()},type:"button"},d?"Tracing…":"Run trace"),R?y("span",{className:"section-meta"},`mode=${R.mode.selected} · candidates=${R.retrieval.candidate_count} · tokens=${R.output.estimated_tokens}`):null),h&&!R?y("div",{className:"section-meta",style:"margin-top:8px;"},"Trace inputs changed. Run trace again for the current query, project, and working set."):null,j?y("div",{className:"section-meta",style:"margin-top:8px; color:#d96c6c;"},j):null]),R?y(Z,null,[y(cs,{label:"Selected",candidates:I}),y(cs,{label:"Dropped",candidates:G}),y(cs,{label:"Deduped",candidates:A}),y(cs,{label:"Trimmed",candidates:M}),y("div",{className:"feed-card-body"},[R.assembly.collapsed_groups.length?y("div",{className:"section-meta"},`Collapsed duplicates: ${R.assembly.collapsed_groups.map(L=>`kept #${L.kept} from [${L.dropped.join(", ")}]`).join(" · ")}`):null,R.assembly.trim_reasons.length?y("div",{className:"section-meta"},`Trim reasons: ${R.assembly.trim_reasons.join(", ")}`):null,y("div",{className:"section-meta"},"Final pack"),y("pre",{style:"white-space:pre-wrap; overflow:auto;"},R.output.pack_text)])]):null])):null}var jP={kind:"kind-chip",provenance:"provenance-chip",tag:"tag-chip",badge:"badge",scope:"peer-scope-chip"};function id({variant:e,tone:t,title:n,children:r}){const i=jP[e];return a("span",{className:t?`${i} ${t}`:i,title:n,children:r})}function Pg(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 FP(e){if(Array.isArray(e))return e}function BP(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 UP(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
47
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function GP(e,t){return FP(e)||BP(e,t)||HP(e,t)||UP()}function HP(e,t){if(e){if(typeof e=="string")return Pg(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)?Pg(e,t):void 0}}var Ag=Object.entries,Rg=Object.setPrototypeOf,qP=Object.isFrozen,KP=Object.getPrototypeOf,VP=Object.getOwnPropertyDescriptor,Ye=Object.freeze,Xe=Object.seal,Jr=Object.create,Dg=typeof Reflect<"u"&&Reflect,od=Dg.apply,ad=Dg.construct;Ye||(Ye=function(t){return t}),Xe||(Xe=function(t){return t}),od||(od=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)}),ad||(ad=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 eo=He(Array.prototype.forEach),WP=He(Array.prototype.lastIndexOf),Lg=He(Array.prototype.pop),Yr=He(Array.prototype.push),zP=He(Array.prototype.splice),In=Array.isArray,to=He(String.prototype.toLowerCase),sd=He(String.prototype.toString),$g=He(String.prototype.match),no=He(String.prototype.replace),Mg=He(String.prototype.indexOf),JP=He(String.prototype.trim),YP=He(Number.prototype.toString),XP=He(Boolean.prototype.toString),Og=typeof BigInt>"u"?null:He(BigInt.prototype.toString),jg=typeof Symbol>"u"?null:He(Symbol.prototype.toString),We=He(Object.prototype.hasOwnProperty),ro=He(Object.prototype.toString),Qe=He(RegExp.prototype.test),or=QP(TypeError);function He(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 od(e,t,r)}}function QP(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return ad(e,n)}}function Ce(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:to;if(Rg&&Rg(e,null),!In(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i=="string"){const o=n(i);o!==i&&(qP(t)||(t[r]=o),i=o)}e[i]=!0}return e}function ZP(e){for(let t=0;t<e.length;t++)We(e,t)||(e[t]=null);return e}function lt(e){const t=Jr(null);for(const r of Ag(e)){var n=GP(r,2);const i=n[0],o=n[1];We(e,i)&&(In(o)?t[i]=ZP(o):o&&typeof o=="object"&&o.constructor===Object?t[i]=lt(o):t[i]=o)}return t}function eA(e){switch(typeof e){case"string":return e;case"number":return YP(e);case"boolean":return XP(e);case"bigint":return Og?Og(e):"0";case"symbol":return jg?jg(e):"Symbol()";case"undefined":return ro(e);case"function":case"object":{if(e===null)return ro(e);const t=e,n=qt(t,"toString");if(typeof n=="function"){const r=n(t);return typeof r=="string"?r:ro(r)}return ro(e)}default:return ro(e)}}function qt(e,t){for(;e!==null;){const r=VP(e,t);if(r){if(r.get)return He(r.get);if(typeof r.value=="function")return He(r.value)}e=KP(e)}function n(){return null}return n}function tA(e){try{return Qe(e,""),!0}catch{return!1}}var Fg=Ye(["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"]),cd=Ye(["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"]),ld=Ye(["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"]),nA=Ye(["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"]),dd=Ye(["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"]),rA=Ye(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Bg=Ye(["#text"]),Ug=Ye(["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"]),ud=Ye(["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","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","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-rendering","textlength","type","u1","u2","unicode","values","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"]),Gg=Ye(["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"]),ls=Ye(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),iA=Xe(/{{[\w\W]*|^[\w\W]*}}/g),oA=Xe(/<%[\w\W]*|^[\w\W]*%>/g),aA=Xe(/\${[\w\W]*/g),sA=Xe(/^data-[\-\w.\u00B7-\uFFFF]+$/),cA=Xe(/^aria-[\-\w]+$/),Hg=Xe(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),lA=Xe(/^(?:\w+script|data):/i),dA=Xe(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),uA=Xe(/^html$/i),pA=Xe(/^[a-z][.\w]*(-[.\w]+)+$/i),qg=Xe(/<[/\w!]/g),fA=Xe(/<[/\w]/g),mA=Xe(/<\/no(script|embed|frames)/i),hA=Xe(/\/>/i),Kt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},vA=function(){return typeof window>"u"?null:window},gA=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}},Kg=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},En=function(t,n,r,i){return We(t,n)&&In(t[n])?Ce(i.base?lt(i.base):{},t[n],i.transform):r};function Vg(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:vA();const t=X=>Vg(X);if(t.version="3.4.11",t.removed=[],!e||!e.document||e.document.nodeType!==Kt.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=qt(p,"cloneNode"),m=qt(p,"remove"),v=qt(p,"nextSibling"),h=qt(p,"childNodes"),g=qt(p,"parentNode"),_=qt(p,"shadowRoot"),w=qt(p,"attributes"),S=s&&s.prototype?qt(s.prototype,"nodeType"):null,N=s&&s.prototype?qt(s.prototype,"nodeName"):null;if(typeof o=="function"){const X=n.createElement("template");X.content&&X.content.ownerDocument&&(n=X.content.ownerDocument)}let k,E="",R,j=!1,q=0;const I=function(){if(q>0)throw or('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.')},G=function(C){I(),q++;try{return k.createHTML(C)}finally{q--}},A=function(C){I(),q++;try{return k.createScriptURL(C)}finally{q--}},M=function(){return j||(R=gA(u,i),j=!0),R},L=n,x=L.implementation,O=L.createNodeIterator,T=L.createDocumentFragment,P=L.getElementsByTagName,B=r.importNode;let V=Kg();t.isSupported=typeof Ag=="function"&&typeof g=="function"&&x&&x.createHTMLDocument!==void 0;const le=iA,de=oA,ae=aA,be=sA,J=cA,ve=lA,ee=dA,Te=pA;let fe=Hg,te=null;const Ie=Ce({},[...Fg,...cd,...ld,...dd,...Bg]);let ce=null;const Ae=Ce({},[...Ug,...ud,...Gg,...ls]);let ue=Object.seal(Jr(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}})),Ke=null,Q=null;const re=Object.seal(Jr(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ut=!0,Ue=!0,Jt=!1,dn=!0,mt=!1,un=!0,he=!1,ht=!1,wt=null,pi=null,Po=!1,pn=!1,_r=!1,On=!1,vt=!0,jn=!1;const D_="user-content-";let Lu=!0,$u=!1,fi={},Yt=null;const Mu=Ce({},["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 L_=null;const $_=Ce({},["audio","video","img","source","image","track"]);let Ou=null;const M_=Ce({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ks="http://www.w3.org/1998/Math/MathML",Vs="http://www.w3.org/2000/svg",Xt="http://www.w3.org/1999/xhtml";let mi=Xt,ju=!1,Fu=null;const nj=Ce({},[Ks,Vs,Xt],sd),O_=Ye(["mi","mo","mn","ms","mtext"]);let Bu=Ce({},O_);const j_=Ye(["annotation-xml"]);let Uu=Ce({},j_);const rj=Ce({},["title","style","font","a","script"]);let Ao=null;const ij=["application/xhtml+xml","text/html"],oj="text/html";let Ge=null,hi=null;const aj=n.createElement("form"),F_=function(C){return C instanceof RegExp||C instanceof Function},Gu=function(){let C=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(hi&&hi===C)return;(!C||typeof C!="object")&&(C={}),C=lt(C),Ao=ij.indexOf(C.PARSER_MEDIA_TYPE)===-1?oj:C.PARSER_MEDIA_TYPE,Ge=Ao==="application/xhtml+xml"?sd:to,te=En(C,"ALLOWED_TAGS",Ie,{transform:Ge}),ce=En(C,"ALLOWED_ATTR",Ae,{transform:Ge}),Fu=En(C,"ALLOWED_NAMESPACES",nj,{transform:sd}),Ou=En(C,"ADD_URI_SAFE_ATTR",M_,{transform:Ge,base:M_}),L_=En(C,"ADD_DATA_URI_TAGS",$_,{transform:Ge,base:$_}),Yt=En(C,"FORBID_CONTENTS",Mu,{transform:Ge}),Ke=En(C,"FORBID_TAGS",lt({}),{transform:Ge}),Q=En(C,"FORBID_ATTR",lt({}),{transform:Ge}),fi=We(C,"USE_PROFILES")?C.USE_PROFILES&&typeof C.USE_PROFILES=="object"?lt(C.USE_PROFILES):C.USE_PROFILES:!1,ut=C.ALLOW_ARIA_ATTR!==!1,Ue=C.ALLOW_DATA_ATTR!==!1,Jt=C.ALLOW_UNKNOWN_PROTOCOLS||!1,dn=C.ALLOW_SELF_CLOSE_IN_ATTR!==!1,mt=C.SAFE_FOR_TEMPLATES||!1,un=C.SAFE_FOR_XML!==!1,he=C.WHOLE_DOCUMENT||!1,pn=C.RETURN_DOM||!1,_r=C.RETURN_DOM_FRAGMENT||!1,On=C.RETURN_TRUSTED_TYPE||!1,Po=C.FORCE_BODY||!1,vt=C.SANITIZE_DOM!==!1,jn=C.SANITIZE_NAMED_PROPS||!1,Lu=C.KEEP_CONTENT!==!1,$u=C.IN_PLACE||!1,fe=tA(C.ALLOWED_URI_REGEXP)?C.ALLOWED_URI_REGEXP:Hg,mi=typeof C.NAMESPACE=="string"?C.NAMESPACE:Xt,Bu=We(C,"MATHML_TEXT_INTEGRATION_POINTS")&&C.MATHML_TEXT_INTEGRATION_POINTS&&typeof C.MATHML_TEXT_INTEGRATION_POINTS=="object"?lt(C.MATHML_TEXT_INTEGRATION_POINTS):Ce({},O_),Uu=We(C,"HTML_INTEGRATION_POINTS")&&C.HTML_INTEGRATION_POINTS&&typeof C.HTML_INTEGRATION_POINTS=="object"?lt(C.HTML_INTEGRATION_POINTS):Ce({},j_);const $=We(C,"CUSTOM_ELEMENT_HANDLING")&&C.CUSTOM_ELEMENT_HANDLING&&typeof C.CUSTOM_ELEMENT_HANDLING=="object"?lt(C.CUSTOM_ELEMENT_HANDLING):Jr(null);if(ue=Jr(null),We($,"tagNameCheck")&&F_($.tagNameCheck)&&(ue.tagNameCheck=$.tagNameCheck),We($,"attributeNameCheck")&&F_($.attributeNameCheck)&&(ue.attributeNameCheck=$.attributeNameCheck),We($,"allowCustomizedBuiltInElements")&&typeof $.allowCustomizedBuiltInElements=="boolean"&&(ue.allowCustomizedBuiltInElements=$.allowCustomizedBuiltInElements),Xe(ue),mt&&(Ue=!1),_r&&(pn=!0),fi&&(te=Ce({},Bg),ce=Jr(null),fi.html===!0&&(Ce(te,Fg),Ce(ce,Ug)),fi.svg===!0&&(Ce(te,cd),Ce(ce,ud),Ce(ce,ls)),fi.svgFilters===!0&&(Ce(te,ld),Ce(ce,ud),Ce(ce,ls)),fi.mathMl===!0&&(Ce(te,dd),Ce(ce,Gg),Ce(ce,ls))),re.tagCheck=null,re.attributeCheck=null,We(C,"ADD_TAGS")&&(typeof C.ADD_TAGS=="function"?re.tagCheck=C.ADD_TAGS:In(C.ADD_TAGS)&&(te===Ie&&(te=lt(te)),Ce(te,C.ADD_TAGS,Ge))),We(C,"ADD_ATTR")&&(typeof C.ADD_ATTR=="function"?re.attributeCheck=C.ADD_ATTR:In(C.ADD_ATTR)&&(ce===Ae&&(ce=lt(ce)),Ce(ce,C.ADD_ATTR,Ge))),We(C,"ADD_URI_SAFE_ATTR")&&In(C.ADD_URI_SAFE_ATTR)&&Ce(Ou,C.ADD_URI_SAFE_ATTR,Ge),We(C,"FORBID_CONTENTS")&&In(C.FORBID_CONTENTS)&&(Yt===Mu&&(Yt=lt(Yt)),Ce(Yt,C.FORBID_CONTENTS,Ge)),We(C,"ADD_FORBID_CONTENTS")&&In(C.ADD_FORBID_CONTENTS)&&(Yt===Mu&&(Yt=lt(Yt)),Ce(Yt,C.ADD_FORBID_CONTENTS,Ge)),Lu&&(te["#text"]=!0),he&&Ce(te,["html","head","body"]),te.table&&(Ce(te,["tbody"]),delete Ke.tbody),C.TRUSTED_TYPES_POLICY){if(typeof C.TRUSTED_TYPES_POLICY.createHTML!="function")throw or('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof C.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw or('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const Y=k;k=C.TRUSTED_TYPES_POLICY;try{E=G("")}catch(oe){throw k=Y,oe}}else C.TRUSTED_TYPES_POLICY===null?(k=void 0,E=""):(k===void 0&&(k=M()),k&&typeof E=="string"&&(E=G("")));Ye&&Ye(C),hi=C},B_=Ce({},[...cd,...ld,...nA]),U_=Ce({},[...dd,...rA]),sj=function(C,$,Y){return $.namespaceURI===Xt?C==="svg":$.namespaceURI===Ks?C==="svg"&&(Y==="annotation-xml"||Bu[Y]):!!B_[C]},cj=function(C,$,Y){return $.namespaceURI===Xt?C==="math":$.namespaceURI===Vs?C==="math"&&Uu[Y]:!!U_[C]},lj=function(C,$,Y){return $.namespaceURI===Vs&&!Uu[Y]||$.namespaceURI===Ks&&!Bu[Y]?!1:!U_[C]&&(rj[C]||!B_[C])},dj=function(C){let $=g(C);(!$||!$.tagName)&&($={namespaceURI:mi,tagName:"template"});const Y=to(C.tagName),oe=to($.tagName);return Fu[C.namespaceURI]?C.namespaceURI===Vs?sj(Y,$,oe):C.namespaceURI===Ks?cj(Y,$,oe):C.namespaceURI===Xt?lj(Y,$,oe):!!(Ao==="application/xhtml+xml"&&Fu[C.namespaceURI]):!1},Fn=function(C){Yr(t.removed,{element:C});try{g(C).removeChild(C)}catch{if(m(C),!g(C))throw or("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},G_=function(C){const $=h(C);if($){const oe=[];eo($,Se=>{Yr(oe,Se)}),eo(oe,Se=>{try{m(Se)}catch{}})}const Y=w(C);if(Y)for(let oe=Y.length-1;oe>=0;--oe){const Se=Y[oe],Re=Se&&Se.name;if(typeof Re=="string")try{C.removeAttribute(Re)}catch{}}},wr=function(C,$){try{Yr(t.removed,{attribute:$.getAttributeNode(C),from:$})}catch{Yr(t.removed,{attribute:null,from:$})}if($.removeAttribute(C),C==="is")if(pn||_r)try{Fn($)}catch{}else try{$.setAttribute(C,"")}catch{}},uj=function(C){const $=w(C);if($)for(let Y=$.length-1;Y>=0;--Y){const oe=$[Y],Se=oe&&oe.name;if(!(typeof Se!="string"||ce[Ge(Se)]))try{C.removeAttribute(Se)}catch{}}},pj=function(C){const $=[C];for(;$.length>0;){const Y=$.pop();(S?S(Y):Y.nodeType)===Kt.element&&uj(Y);const oe=h(Y);if(oe)for(let Se=oe.length-1;Se>=0;--Se)$.push(oe[Se])}},H_=function(C){let $=null,Y=null;if(Po)C="<remove></remove>"+C;else{const Re=$g(C,/^[\r\n\t ]+/);Y=Re&&Re[0]}Ao==="application/xhtml+xml"&&mi===Xt&&(C='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+C+"</body></html>");const oe=k?G(C):C;if(mi===Xt)try{$=new d().parseFromString(oe,Ao)}catch{}if(!$||!$.documentElement){$=x.createDocument(mi,"template",null);try{$.documentElement.innerHTML=ju?E:oe}catch{}}const Se=$.body||$.documentElement;return C&&Y&&Se.insertBefore(n.createTextNode(Y),Se.childNodes[0]||null),mi===Xt?P.call($,he?"html":"body")[0]:he?$.documentElement:Se},q_=function(C){return O.call(C.ownerDocument||C,C,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Ws=function(C){return C=no(C,le," "),C=no(C,de," "),C=no(C,ae," "),C},Hu=function(C){var $;C.normalize();const Y=O.call(C.ownerDocument||C,C,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let oe=Y.nextNode();for(;oe;)oe.data=Ws(oe.data),oe=Y.nextNode();const Se=($=C.querySelectorAll)===null||$===void 0?void 0:$.call(C,"template");Se&&eo(Se,Re=>{vi(Re.content)&&Hu(Re.content)})},zs=function(C){const $=N?N(C):null;return typeof $!="string"||Ge($)!=="form"?!1:typeof C.nodeName!="string"||typeof C.textContent!="string"||typeof C.removeChild!="function"||C.attributes!==w(C)||typeof C.removeAttribute!="function"||typeof C.setAttribute!="function"||typeof C.namespaceURI!="string"||typeof C.insertBefore!="function"||typeof C.hasChildNodes!="function"||C.nodeType!==S(C)||C.childNodes!==h(C)},vi=function(C){if(!S||typeof C!="object"||C===null)return!1;try{return S(C)===Kt.documentFragment}catch{return!1}},Ro=function(C){if(!S||typeof C!="object"||C===null)return!1;try{return typeof S(C)=="number"}catch{return!1}};function fn(X,C,$){X.length!==0&&eo(X,Y=>{Y.call(t,C,$,hi)})}const fj=function(C,$){return!!(un&&C.hasChildNodes()&&!Ro(C.firstElementChild)&&Qe(qg,C.textContent)&&Qe(qg,C.innerHTML)||un&&C.namespaceURI===Xt&&$==="style"&&Ro(C.firstElementChild)||C.nodeType===Kt.processingInstruction||un&&C.nodeType===Kt.comment&&Qe(fA,C.data))},mj=function(C,$){if(!Ke[$]&&W_($)&&(ue.tagNameCheck instanceof RegExp&&Qe(ue.tagNameCheck,$)||ue.tagNameCheck instanceof Function&&ue.tagNameCheck($)))return!1;if(Lu&&!Yt[$]){const Y=g(C),oe=h(C);if(oe&&Y){const Se=oe.length;for(let Re=Se-1;Re>=0;--Re){const Oe=$u?oe[Re]:f(oe[Re],!0);Y.insertBefore(Oe,v(C))}}}return Fn(C),!0},K_=function(C){if(fn(V.beforeSanitizeElements,C,null),zs(C))return Fn(C),!0;const $=Ge(N?N(C):C.nodeName);if(fn(V.uponSanitizeElement,C,{tagName:$,allowedTags:te}),fj(C,$))return Fn(C),!0;if(Ke[$]||!(re.tagCheck instanceof Function&&re.tagCheck($))&&!te[$])return mj(C,$);if((S?S(C):C.nodeType)===Kt.element&&!dj(C)||($==="noscript"||$==="noembed"||$==="noframes")&&Qe(mA,C.innerHTML))return Fn(C),!0;if(mt&&C.nodeType===Kt.text){const Y=Ws(C.textContent);C.textContent!==Y&&(Yr(t.removed,{element:C.cloneNode()}),C.textContent=Y)}return fn(V.afterSanitizeElements,C,null),!1},V_=function(C,$,Y){if(Q[$]||vt&&($==="id"||$==="name")&&(Y in n||Y in aj))return!1;const oe=ce[$]||re.attributeCheck instanceof Function&&re.attributeCheck($,C);if(!(Ue&&Qe(be,$))){if(!(ut&&Qe(J,$))){if(oe){if(!Ou[$]){if(!Qe(fe,no(Y,ee,""))){if(!(($==="src"||$==="xlink:href"||$==="href")&&C!=="script"&&Mg(Y,"data:")===0&&L_[C])){if(!(Jt&&!Qe(ve,no(Y,ee,"")))){if(Y)return!1}}}}}else if(!(W_(C)&&(ue.tagNameCheck instanceof RegExp&&Qe(ue.tagNameCheck,C)||ue.tagNameCheck instanceof Function&&ue.tagNameCheck(C))&&(ue.attributeNameCheck instanceof RegExp&&Qe(ue.attributeNameCheck,$)||ue.attributeNameCheck instanceof Function&&ue.attributeNameCheck($,C))||$==="is"&&ue.allowCustomizedBuiltInElements&&(ue.tagNameCheck instanceof RegExp&&Qe(ue.tagNameCheck,Y)||ue.tagNameCheck instanceof Function&&ue.tagNameCheck(Y))))return!1}}return!0},hj=Ce({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),W_=function(C){return!hj[to(C)]&&Qe(Te,C)},vj=function(C,$,Y,oe){if(k&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!Y)switch(u.getAttributeType(C,$)){case"TrustedHTML":return G(oe);case"TrustedScriptURL":return A(oe)}return oe},gj=function(C,$,Y,oe){try{Y?C.setAttributeNS(Y,$,oe):C.setAttribute($,oe),zs(C)?Fn(C):Lg(t.removed)}catch{wr($,C)}},z_=function(C){fn(V.beforeSanitizeAttributes,C,null);const $=C.attributes;if(!$||zs(C))return;const Y={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ce,forceKeepAttr:void 0};let oe=$.length;const Se=Ge(C.nodeName);for(;oe--;){const Re=$[oe],Oe=Re.name,xt=Re.namespaceURI,mn=Re.value,Mt=Ge(Oe),Ku=mn;let pt=Oe==="value"?Ku:JP(Ku);if(Y.attrName=Mt,Y.attrValue=pt,Y.keepAttr=!0,Y.forceKeepAttr=void 0,fn(V.uponSanitizeAttribute,C,Y),pt=Y.attrValue,jn&&(Mt==="id"||Mt==="name")&&Mg(pt,D_)!==0&&(wr(Oe,C),pt=D_+pt),un&&Qe(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,pt)){wr(Oe,C);continue}if(Mt==="attributename"&&$g(pt,"href")){wr(Oe,C);continue}if(!Y.forceKeepAttr){if(!Y.keepAttr){wr(Oe,C);continue}if(!dn&&Qe(hA,pt)){wr(Oe,C);continue}if(mt&&(pt=Ws(pt)),!V_(Se,Mt,pt)){wr(Oe,C);continue}pt=vj(Se,Mt,xt,pt),pt!==Ku&&gj(C,Oe,xt,pt)}}fn(V.afterSanitizeAttributes,C,null)},Js=function(C){let $=null;const Y=q_(C);for(fn(V.beforeSanitizeShadowDOM,C,null);$=Y.nextNode();)if(fn(V.uponSanitizeShadowNode,$,null),K_($),z_($),vi($.content)&&Js($.content),(S?S($):$.nodeType)===Kt.element){const oe=_($);vi(oe)&&(qu(oe),Js(oe))}fn(V.afterSanitizeShadowDOM,C,null)},qu=function(C){const $=[{node:C,shadow:null}];for(;$.length>0;){const Y=$.pop();if(Y.shadow){Js(Y.shadow);continue}const oe=Y.node,Se=(S?S(oe):oe.nodeType)===Kt.element,Re=h(oe);if(Re)for(let Oe=Re.length-1;Oe>=0;--Oe)$.push({node:Re[Oe],shadow:null});if(Se){const Oe=N?N(oe):null;if(typeof Oe=="string"&&Ge(Oe)==="template"){const xt=oe.content;vi(xt)&&$.push({node:xt,shadow:null})}}if(Se){const Oe=_(oe);vi(Oe)&&$.push({node:null,shadow:Oe},{node:Oe,shadow:null})}}};return t.sanitize=function(X){let C=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},$=null,Y=null,oe=null,Se=null;if(ju=!X,ju&&(X="<!-->"),typeof X!="string"&&!Ro(X)&&(X=eA(X),typeof X!="string"))throw or("dirty is not a string, aborting");if(!t.isSupported)return X;ht?(te=wt,ce=pi):Gu(C),(V.uponSanitizeElement.length>0||V.uponSanitizeAttribute.length>0)&&(te=lt(te)),V.uponSanitizeAttribute.length>0&&(ce=lt(ce)),t.removed=[];const Re=$u&&typeof X!="string"&&Ro(X);if(Re){const mn=N?N(X):X.nodeName;if(typeof mn=="string"){const Mt=Ge(mn);if(!te[Mt]||Ke[Mt])throw or("root node is forbidden and cannot be sanitized in-place")}if(zs(X))throw or("root node is clobbered and cannot be sanitized in-place");try{qu(X)}catch(Mt){throw G_(X),Mt}}else if(Ro(X))$=H_("<!---->"),Y=$.ownerDocument.importNode(X,!0),Y.nodeType===Kt.element&&Y.nodeName==="BODY"||Y.nodeName==="HTML"?$=Y:$.appendChild(Y),qu(Y);else{if(!pn&&!mt&&!he&&X.indexOf("<")===-1)return k&&On?G(X):X;if($=H_(X),!$)return pn?null:On?E:""}$&&Po&&Fn($.firstChild);const Oe=q_(Re?X:$);try{for(;oe=Oe.nextNode();)K_(oe),z_(oe),vi(oe.content)&&Js(oe.content)}catch(mn){throw Re&&G_(X),mn}if(Re)return eo(t.removed,mn=>{mn.element&&pj(mn.element)}),mt&&Hu(X),X;if(pn){if(mt&&Hu($),_r)for(Se=T.call($.ownerDocument);$.firstChild;)Se.appendChild($.firstChild);else Se=$;return(ce.shadowroot||ce.shadowrootmode)&&(Se=B.call(r,Se,!0)),Se}let xt=he?$.outerHTML:$.innerHTML;return he&&te["!doctype"]&&$.ownerDocument&&$.ownerDocument.doctype&&$.ownerDocument.doctype.name&&Qe(uA,$.ownerDocument.doctype.name)&&(xt="<!DOCTYPE "+$.ownerDocument.doctype.name+`>
48
+ `+xt),mt&&(xt=Ws(xt)),k&&On?G(xt):xt},t.setConfig=function(){Gu(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),ht=!0,wt=te,pi=ce},t.clearConfig=function(){hi=null,ht=!1,wt=null,pi=null,k=R,E=""},t.isValidAttribute=function(X,C,$){return hi||Gu({}),V_(Ge(X),Ge(C),$)},t.addHook=function(X,C){typeof C=="function"&&We(V,X)&&Yr(V[X],C)},t.removeHook=function(X,C){if(We(V,X)){if(C!==void 0){const $=WP(V[X],C);return $===-1?void 0:zP(V[X],$,1)[0]}return Lg(V[X])}},t.removeHooks=function(X){We(V,X)&&(V[X]=[])},t.removeAllHooks=function(){V=Kg()},t}var Wg=Vg();function pd(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ar=pd();function zg(e){ar=e}var sr={exec:()=>null};function Xr(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(nt.caret,"$1"),n=n.replace(i,s),r},getRegex:()=>new RegExp(n,t)};return r}var yA=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),nt={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:Xr(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Xr(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Xr(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Xr(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Xr(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Xr(e=>new RegExp(`^ {0,${e}}>`))},bA=/^(?:[ \t]*(?:\n|$))+/,_A=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,wA=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,io=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,SA=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,fd=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Jg=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Yg=Ne(Jg).replace(/bull/g,fd).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),CA=Ne(Jg).replace(/bull/g,fd).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),md=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,NA=/^[^\n]+/,hd=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,kA=Ne(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",hd).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),TA=Ne(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,fd).getRegex(),ds="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",vd=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,IA=Ne("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\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",vd).replace("tag",ds).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Xg=Ne(md).replace("hr",io).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ds).getRegex(),gd={blockquote:Ne(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Xg).getRegex(),code:_A,def:kA,fences:wA,heading:SA,hr:io,html:IA,lheading:Yg,list:TA,newline:bA,paragraph:Xg,table:sr,text:NA},Qg=Ne("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",io).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ds).getRegex(),EA={...gd,lheading:CA,table:Qg,paragraph:Ne(md).replace("hr",io).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Qg).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ds).getRegex()},xA={...gd,html:Ne(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",vd).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:sr,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Ne(md).replace("hr",io).replace("heading",` *#{1,6} *[^
49
+ ]`).replace("lheading",Yg).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},PA=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,AA=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Zg=/^( {2,}|\\)\n(?!\s*$)/,RA=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Qr=/[\p{P}\p{S}]/u,us=/[\s\p{P}\p{S}]/u,yd=/[^\s\p{P}\p{S}]/u,DA=Ne(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,us).getRegex(),ey=/(?!~)[\p{P}\p{S}]/u,LA=/(?!~)[\s\p{P}\p{S}]/u,$A=/(?:[^\s\p{P}\p{S}]|~)/u,MA=Ne(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",yA?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ty=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,OA=Ne(ty,"u").replace(/punct/g,Qr).getRegex(),jA=Ne(ty,"u").replace(/punct/g,ey).getRegex(),ny="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",FA=Ne(ny,"gu").replace(/notPunctSpace/g,yd).replace(/punctSpace/g,us).replace(/punct/g,Qr).getRegex(),BA=Ne(ny,"gu").replace(/notPunctSpace/g,$A).replace(/punctSpace/g,LA).replace(/punct/g,ey).getRegex(),UA=Ne("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,yd).replace(/punctSpace/g,us).replace(/punct/g,Qr).getRegex(),GA=Ne(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Qr).getRegex(),HA=Ne("^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,yd).replace(/punctSpace/g,us).replace(/punct/g,Qr).getRegex(),qA=Ne(/\\(punct)/,"gu").replace(/punct/g,Qr).getRegex(),KA=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(),VA=Ne(vd).replace("(?:-->|$)","-->").getRegex(),WA=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",VA).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ps=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,zA=Ne(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",ps).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ry=Ne(/^!?\[(label)\]\[(ref)\]/).replace("label",ps).replace("ref",hd).getRegex(),iy=Ne(/^!?\[(ref)\](?:\[\])?/).replace("ref",hd).getRegex(),JA=Ne("reflink|nolink(?!\\()","g").replace("reflink",ry).replace("nolink",iy).getRegex(),oy=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,bd={_backpedal:sr,anyPunctuation:qA,autolink:KA,blockSkip:MA,br:Zg,code:AA,del:sr,delLDelim:sr,delRDelim:sr,emStrongLDelim:OA,emStrongRDelimAst:FA,emStrongRDelimUnd:UA,escape:PA,link:zA,nolink:iy,punctuation:DA,reflink:ry,reflinkSearch:JA,tag:WA,text:RA,url:sr},YA={...bd,link:Ne(/^!?\[(label)\]\((.*?)\)/).replace("label",ps).getRegex(),reflink:Ne(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ps).getRegex()},_d={...bd,emStrongRDelimAst:BA,emStrongLDelim:jA,delLDelim:GA,delRDelim:HA,url:Ne(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",oy).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",oy).getRegex()},XA={..._d,br:Ne(Zg).replace("{2,}","*").getRegex(),text:Ne(_d.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},fs={normal:gd,gfm:EA,pedantic:xA},oo={normal:bd,gfm:_d,breaks:XA,pedantic:YA},QA={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},ay=e=>QA[e];function Vt(e,t){if(t){if(nt.escapeTest.test(e))return e.replace(nt.escapeReplace,ay)}else if(nt.escapeTestNoEncode.test(e))return e.replace(nt.escapeReplaceNoEncode,ay);return e}function sy(e){try{e=encodeURI(e).replace(nt.percentDecode,"%")}catch{return null}return e}function cy(e,t){let n=e.replace(nt.findPipe,(i,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}).split(nt.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(nt.slashPipe,"|");return n}function xn(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 ly(e){let t=e.split(`
50
+ `),n=t.length-1;for(;n>=0&&nt.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
51
+ `)}function ZA(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 eR(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 dy(e,t,n,r,i){let o=t.href,s=t.title||null,c=e[1].replace(i.other.outputLinkReplace,"$1");r.state.inLink=!0;let l={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:o,title:s,text:c,tokens:r.inlineTokens(c)};return r.state.inLink=!1,l}function tR(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
52
52
  `).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(`
53
- `)}var ts=class{options;rules;lexer;constructor(e){this.options=e||or}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]:Dv(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=bI(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=Pn(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:Pn(t[0],`
54
- `),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:Pn(t[0],`
55
- `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=Pn(t[0],`
53
+ `)}var ms=class{options;rules;lexer;constructor(e){this.options=e||ar}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]:ly(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=tR(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=xn(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:xn(t[0],`
54
+ `),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:xn(t[0],`
55
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=xn(t[0],`
56
56
  `).split(`
57
57
  `),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(`
58
58
  `),u=d.replace(this.rules.other.blockquoteSetextReplace,`
59
59
  $1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
60
60
  ${d}`:d,i=i?`${i}
61
- ${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 m=o.at(-1);if(m?.type==="code")break;if(m?.type==="blockquote"){let f=m,y=f.raw+`
61
+ ${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=m.raw+`
62
62
  `+n.join(`
63
- `),h=this.blockquote(y);o[o.length-1]=h,r=r.substring(0,r.length-f.raw.length)+h.raw,i=i.substring(0,i.length-f.text.length)+h.text;break}else if(m?.type==="list"){let f=m,y=f.raw+`
63
+ `),h=this.blockquote(v);o[o.length-1]=h,r=r.substring(0,r.length-m.raw.length)+h.raw,i=i.substring(0,i.length-m.text.length)+h.text;break}else if(f?.type==="list"){let m=f,v=m.raw+`
64
64
  `+n.join(`
65
- `),h=this.list(y);o[o.length-1]=h,r=r.substring(0,r.length-m.raw.length)+h.raw,i=i.substring(0,i.length-f.raw.length)+h.raw,n=y.substring(o.at(-1).raw.length).split(`
66
- `);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=yI(t[2].split(`
67
- `,1)[0],t[1].length),m=e.split(`
68
- `,1)[0],f=!p.trim(),y=0;if(this.options.pedantic?(y=2,u=p.trimStart()):f?y=t[1].length+1:(y=p.search(this.rules.other.nonSpaceChar),y=y>4?1:y,u=p.slice(y),y+=t[1].length),f&&this.rules.other.blankLine.test(m)&&(d+=m+`
69
- `,e=e.substring(m.length+1),l=!0),!l){let h=this.rules.other.nextBulletRegex(y),g=this.rules.other.hrRegex(y),_=this.rules.other.fencesBeginRegex(y),w=this.rules.other.headingBeginRegex(y),S=this.rules.other.htmlBeginRegex(y),T=this.rules.other.blockquoteBeginRegex(y);for(;e;){let k=e.split(`
70
- `,1)[0],P;if(m=k,this.options.pedantic?(m=m.replace(this.rules.other.listReplaceNesting," "),P=m):P=m.replace(this.rules.other.tabCharGlobal," "),_.test(m)||w.test(m)||S.test(m)||T.test(m)||h.test(m)||g.test(m))break;if(P.search(this.rules.other.nonSpaceChar)>=y||!m.trim())u+=`
71
- `+P.slice(y);else{if(f||p.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||_.test(p)||w.test(p)||g.test(p))break;u+=`
72
- `+m}f=!m.trim(),d+=k+`
73
- `,e=e.substring(k.length+1),p=P.slice(y)}}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){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);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){let u=l.tokens.filter(p=>p.type==="space");i.loose=u.length>0&&u.some(p=>this.rules.other.anyLine.test(p.raw))}}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=Dv(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:Pn(t[0],`
74
- `),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=Rv(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
75
- `):[],o={type:"table",raw:Pn(t[0],`
76
- `),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(Rv(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:Pn(t[0],`
65
+ `),h=this.list(v);o[o.length-1]=h,r=r.substring(0,r.length-f.raw.length)+h.raw,i=i.substring(0,i.length-m.raw.length)+h.raw,n=v.substring(o.at(-1).raw.length).split(`
66
+ `);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=eR(t[2].split(`
67
+ `,1)[0],t[1].length),f=e.split(`
68
+ `,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+`
69
+ `,e=e.substring(f.length+1),l=!0),!l){let h=this.rules.other.nextBulletRegex(v),g=this.rules.other.hrRegex(v),_=this.rules.other.fencesBeginRegex(v),w=this.rules.other.headingBeginRegex(v),S=this.rules.other.htmlBeginRegex(v),N=this.rules.other.blockquoteBeginRegex(v);for(;e;){let k=e.split(`
70
+ `,1)[0],E;if(f=k,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),E=f):E=f.replace(this.rules.other.tabCharGlobal," "),_.test(f)||w.test(f)||S.test(f)||N.test(f)||h.test(f)||g.test(f))break;if(E.search(this.rules.other.nonSpaceChar)>=v||!f.trim())u+=`
71
+ `+E.slice(v);else{if(m||p.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||_.test(p)||w.test(p)||g.test(p))break;u+=`
72
+ `+f}m=!f.trim(),d+=k+`
73
+ `,e=e.substring(k.length+1),p=E.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){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);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){let u=l.tokens.filter(p=>p.type==="space");i.loose=u.length>0&&u.some(p=>this.rules.other.anyLine.test(p.raw))}}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=ly(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:xn(t[0],`
74
+ `),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=cy(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
75
+ `):[],o={type:"table",raw:xn(t[0],`
76
+ `),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(cy(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:xn(t[0],`
77
77
  `),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)===`
78
- `?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=Pn(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=vI(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)),Lv(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 Lv(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]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+i);(r=d.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])&&i%3&&!((i+s)%3)){l+=s;continue}if(c-=s,c>0)continue;s=Math.min(s,s+c+l);let u=[...r[0]][0].length,p=e.slice(0,i+r.index+u+s);if(Math.min(i,s)%2){let f=p.slice(1,-1);return{type:"em",raw:p,text:f,tokens:this.lexer.inlineTokens(f)}}let m=p.slice(2,-2);return{type:"strong",raw:p,text:m,tokens:this.lexer.inlineTokens(m)}}}}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}}}},Rt=class ku{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||or,this.options.tokenizer=this.options.tokenizer||new ts,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:ot,block:es.normal,inline:qi.normal};this.options.pedantic?(n.block=es.pedantic,n.inline=qi.pedantic):this.options.gfm&&(n.block=es.gfm,this.options.breaks?n.inline=qi.breaks:n.inline=qi.gfm),this.tokenizer.rules=n}static get rules(){return{block:es,inline:qi}}static lex(t,n){return new ku(n).lex(t)}static lexInline(t,n){return new ku(n).inlineTokens(t)}lex(t){t=t.replace(ot.carriageReturn,`
79
- `),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(ot.tabCharGlobal," ").replace(ot.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+=`
78
+ `?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=xn(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=ZA(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)),dy(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 dy(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]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+i);(r=d.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])&&i%3&&!((i+s)%3)){l+=s;continue}if(c-=s,c>0)continue;s=Math.min(s,s+c+l);let u=[...r[0]][0].length,p=e.slice(0,i+r.index+u+s);if(Math.min(i,s)%2){let m=p.slice(1,-1);return{type:"em",raw:p,text:m,tokens:this.lexer.inlineTokens(m)}}let f=p.slice(2,-2);return{type:"strong",raw:p,text:f,tokens:this.lexer.inlineTokens(f)}}}}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}}}},Lt=class Vu{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||ar,this.options.tokenizer=this.options.tokenizer||new ms,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:nt,block:fs.normal,inline:oo.normal};this.options.pedantic?(n.block=fs.pedantic,n.inline=oo.pedantic):this.options.gfm&&(n.block=fs.gfm,this.options.breaks?n.inline=oo.breaks:n.inline=oo.gfm),this.tokenizer.rules=n}static get rules(){return{block:fs,inline:oo}}static lex(t,n){return new Vu(n).lex(t)}static lexInline(t,n){return new Vu(n).inlineTokens(t)}lex(t){t=t.replace(nt.carriageReturn,`
79
+ `),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(nt.tabCharGlobal," ").replace(nt.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+=`
80
80
  `: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(`
81
81
  `)?"":`
82
82
  `)+o.raw,c.text+=`
@@ -89,9 +89,9 @@ ${u}`:u;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
89
89
  `+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(`
90
90
  `)?"":`
91
91
  `)+o.raw,c.text+=`
92
- `+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}inlineTokens(t,n=[]){this.tokenizer.lexer=this;let r=t,i=null;if(this.tokens.links){let d=Object.keys(this.tokens.links);if(d.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(r))!==null;)d.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(r))!==null;)r=r.slice(0,i.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(r))!==null;)o=i[2]?i[2].length:0,r=r.slice(0,i.index+o)+"["+"a".repeat(i[0].length-o-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let s=!1,c="",l=1/0;for(;t;){if(t.length<l)l=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}s||(c=""),s=!1;let d;if(this.options.extensions?.inline?.some(p=>(d=p.call({lexer:this},t,n))?(t=t.substring(d.raw.length),n.push(d),!0):!1))continue;if(d=this.tokenizer.escape(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.tag(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.link(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(d.raw.length);let p=n.at(-1);d.type==="text"&&p?.type==="text"?(p.raw+=d.raw,p.text+=d.text):n.push(d);continue}if(d=this.tokenizer.emStrong(t,r,c)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.codespan(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.br(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.del(t,r,c)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.autolink(t)){t=t.substring(d.raw.length),n.push(d);continue}if(!this.state.inLink&&(d=this.tokenizer.url(t))){t=t.substring(d.raw.length),n.push(d);continue}let u=t;if(this.options.extensions?.startInline){let p=1/0,m=t.slice(1),f;this.options.extensions.startInline.forEach(y=>{f=y.call({lexer:this},m),typeof f=="number"&&f>=0&&(p=Math.min(p,f))}),p<1/0&&p>=0&&(u=t.substring(0,p+1))}if(d=this.tokenizer.inlineText(u)){t=t.substring(d.raw.length),d.raw.slice(-1)!=="_"&&(c=d.raw.slice(-1)),s=!0;let p=n.at(-1);p?.type==="text"?(p.raw+=d.raw,p.text+=d.text):n.push(d);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)}},ns=class{options;parser;constructor(e){this.options=e||or}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(ot.notSpaceStart)?.[0],i=e.replace(ot.endingNewline,"")+`
93
- `;return r?'<pre><code class="language-'+qt(r)+'">'+(n?i:qt(i,!0))+`</code></pre>
94
- `:"<pre><code>"+(n?i:qt(i,!0))+`</code></pre>
92
+ `+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}inlineTokens(t,n=[]){this.tokenizer.lexer=this;let r=t,i=null;if(this.tokens.links){let d=Object.keys(this.tokens.links);if(d.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(r))!==null;)d.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(r))!==null;)r=r.slice(0,i.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(r))!==null;)o=i[2]?i[2].length:0,r=r.slice(0,i.index+o)+"["+"a".repeat(i[0].length-o-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let s=!1,c="",l=1/0;for(;t;){if(t.length<l)l=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}s||(c=""),s=!1;let d;if(this.options.extensions?.inline?.some(p=>(d=p.call({lexer:this},t,n))?(t=t.substring(d.raw.length),n.push(d),!0):!1))continue;if(d=this.tokenizer.escape(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.tag(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.link(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(d.raw.length);let p=n.at(-1);d.type==="text"&&p?.type==="text"?(p.raw+=d.raw,p.text+=d.text):n.push(d);continue}if(d=this.tokenizer.emStrong(t,r,c)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.codespan(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.br(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.del(t,r,c)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.autolink(t)){t=t.substring(d.raw.length),n.push(d);continue}if(!this.state.inLink&&(d=this.tokenizer.url(t))){t=t.substring(d.raw.length),n.push(d);continue}let u=t;if(this.options.extensions?.startInline){let p=1/0,f=t.slice(1),m;this.options.extensions.startInline.forEach(v=>{m=v.call({lexer:this},f),typeof m=="number"&&m>=0&&(p=Math.min(p,m))}),p<1/0&&p>=0&&(u=t.substring(0,p+1))}if(d=this.tokenizer.inlineText(u)){t=t.substring(d.raw.length),d.raw.slice(-1)!=="_"&&(c=d.raw.slice(-1)),s=!0;let p=n.at(-1);p?.type==="text"?(p.raw+=d.raw,p.text+=d.text):n.push(d);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)}},hs=class{options;parser;constructor(e){this.options=e||ar}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(nt.notSpaceStart)?.[0],i=e.replace(nt.endingNewline,"")+`
93
+ `;return r?'<pre><code class="language-'+Vt(r)+'">'+(n?i:Vt(i,!0))+`</code></pre>
94
+ `:"<pre><code>"+(n?i:Vt(i,!0))+`</code></pre>
95
95
  `}blockquote({tokens:e}){return`<blockquote>
96
96
  ${this.parser.parse(e)}</blockquote>
97
97
  `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
@@ -107,8 +107,8 @@ ${this.parser.parse(e)}</blockquote>
107
107
  `}tablerow({text:e}){return`<tr>
108
108
  ${e}</tr>
109
109
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
110
- `}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>${qt(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=Iv(e);if(i===null)return r;e=i;let o='<a href="'+e+'"';return t&&(o+=' title="'+qt(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=Iv(e);if(i===null)return qt(n);e=i;let o=`<img src="${e}" alt="${qt(n)}"`;return t&&(o+=` title="${qt(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:qt(e.text)}},ad=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}},Dt=class Nu{options;renderer;textRenderer;constructor(t){this.options=t||or,this.options.renderer=this.options.renderer||new ns,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new ad}static parse(t,n){return new Nu(n).parse(t)}static parseInline(t,n){return new Nu(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","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","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}},zi=class{options;block;constructor(e){this.options=e||or}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?Rt.lex:Rt.lexInline}provideParser(e=this.block){return e?Dt.parse:Dt.parseInline}},_I=class{defaults=Xl();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Dt;Renderer=ns;TextRenderer=ad;Lexer=Rt;Tokenizer=ts;Hooks=zi;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 ns(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 ts(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 zi;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];zi.passThroughHooks.has(o)?i[s]=d=>{if(this.defaults.async&&zi.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 Rt.lex(e,t??this.defaults)}parser(e,t){return Dt.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?Rt.lex:Rt.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?Dt.parse:Dt.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?Rt.lex:Rt.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?Dt.parse:Dt.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+=`
111
- Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error occurred:</p><pre>"+qt(n.message+"",!0)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},sr=new _I;function Ae(e,t){return sr.parse(e,t)}Ae.options=Ae.setOptions=function(e){return sr.setOptions(e),Ae.defaults=sr.defaults,yv(Ae.defaults),Ae},Ae.getDefaults=Xl,Ae.defaults=or,Ae.use=function(...e){return sr.use(...e),Ae.defaults=sr.defaults,yv(Ae.defaults),Ae},Ae.walkTokens=function(e,t){return sr.walkTokens(e,t)},Ae.parseInline=sr.parseInline,Ae.Parser=Dt,Ae.parser=Dt.parse,Ae.Renderer=ns,Ae.TextRenderer=ad,Ae.Lexer=Rt,Ae.lexer=Rt.lex,Ae.Tokenizer=ts,Ae.Hooks=zi,Ae.parse=Ae;var JO=Ae.options,YO=Ae.setOptions,XO=Ae.use,ZO=Ae.walkTokens,QO=Ae.parseInline,ej=Ae,tj=Dt.parse,nj=Rt.lex,wI={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 SI(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:")}vv.addHook("afterSanitizeAttributes",e=>{e.tagName==="A"&&(SI(e.getAttribute("href")||"")?(e.setAttribute("rel","noopener noreferrer"),e.setAttribute("target","_blank")):e.removeAttribute("href"))});function sd(e){const t=Ae.parse(String(e||""),{async:!1});return vv.sanitize(t,wI)}function CI(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?v("div",{className:"summary-section",key:r},v("div",{className:"summary-section-label"},uA(r)),v("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:sd(i)}})):null}).filter(Boolean)}function TI(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:v("div",{className:"summary-section",key:`${s}-${i}`},v("div",{className:"summary-section-label"},s),v("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:sd(c)}}))}).filter(Boolean);if(n.length)return v("div",{className:"feed-body facts"},n)}return v("div",{className:"feed-body"},v("ul",null,t.map((n,r)=>v("li",{key:`${n}-${r}`},n))))}function $v(e,t="feed-body"){const n=String(e||"").trim();return n?v("div",{className:t,dangerouslySetInnerHTML:{__html:sd(n)}}):null}function kI(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 rs(e,t){return String(e?.kind||"").toLowerCase()==="session_summary"||t?.is_summary===!0?!0:String(t?.source||"").trim().toLowerCase()==="observer_summary"}function NI(e,t){const n=String(e?.kind||"").trim().toLowerCase();return rs(e,t)?"session_summary":n||"change"}var cd=["Enter"," "],xI=["ArrowDown","PageUp","Home"],Mv=["ArrowUp","PageDown","End"],PI=[...xI,...Mv],AI={ltr:[...cd,"ArrowRight"],rtl:[...cd,"ArrowLeft"]},EI={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Ji="Menu",[Yi,II,RI]=la(Ji),[cr,Ov]=st(Ji,[RI,_n,Dr]),Xi=_n(),jv=Dr(),[Fv,An]=cr(Ji),[DI,Zi]=cr(Ji),Bv=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:o,modal:s=!0}=e,c=Xi(t),[l,d]=I(null),u=F(!1),p=lt(o),m=Ii(i);return K(()=>{const f=()=>{u.current=!0,document.addEventListener("pointerdown",y,{capture:!0,once:!0}),document.addEventListener("pointermove",y,{capture:!0,once:!0})},y=()=>u.current=!1;return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",y,{capture:!0}),document.removeEventListener("pointermove",y,{capture:!0})}},[]),a($i,{...c,children:a(Fv,{scope:t,open:n,onOpenChange:p,content:l,onContentChange:d,children:a(DI,{scope:t,onClose:re(()=>p(!1),[p]),isUsingKeyboardRef:u,dir:m,modal:s,children:r})})})};Bv.displayName=Ji;var LI="MenuAnchor",ld=j((e,t)=>{const{__scopeMenu:n,...r}=e,i=Xi(n);return a(Mi,{...i,...r,ref:t})});ld.displayName=LI;var dd="MenuPortal",[$I,Uv]=cr(dd,{forceMount:void 0}),Gv=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,o=An(dd,t);return a($I,{scope:t,forceMount:n,children:a(rt,{present:n||o.open,children:a(Hn,{asChild:!0,container:i,children:r})})})};Gv.displayName=dd;var St="MenuContent",[MI,ud]=cr(St),Hv=j((e,t)=>{const n=Uv(St,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,o=An(St,e.__scopeMenu),s=Zi(St,e.__scopeMenu);return a(Yi.Provider,{scope:e.__scopeMenu,children:a(rt,{present:r||o.open,children:a(Yi.Slot,{scope:e.__scopeMenu,children:s.modal?a(OI,{...i,ref:t}):a(jI,{...i,ref:t})})})})}),OI=j((e,t)=>{const n=An(St,e.__scopeMenu),r=F(null),i=_e(t,r);return K(()=>{const o=r.current;if(o)return zo(o)},[]),a(pd,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:z(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),jI=j((e,t)=>{const n=An(St,e.__scopeMenu);return a(pd,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),FI=Un("MenuContent.ScrollLock"),pd=j((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:s,disableOutsidePointerEvents:c,onEntryFocus:l,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:p,onInteractOutside:m,onDismiss:f,disableOutsideScroll:y,...h}=e,g=An(St,n),_=Zi(St,n),w=Xi(n),S=jv(n),T=II(n),[k,P]=I(null),E=F(null),M=_e(t,E,g.onContentChange),U=F(0),N=F(""),G=F(0),A=F(null),$=F("right"),L=F(0),J=y?vi:te,H=y?{as:FI,allowPinchZoom:!0}:void 0,x=B=>{const V=N.current+B,he=T().filter(ge=>!ge.disabled),ue=document.activeElement,ce=he.find(ge=>ge.ref.current===ue)?.textValue,be=ZI(he.map(ge=>ge.textValue),V,ce),Y=he.find(ge=>ge.textValue===be)?.ref.current;(function ge(Z){N.current=Z,window.clearTimeout(U.current),Z!==""&&(U.current=window.setTimeout(()=>ge(""),1e3))})(V),Y&&setTimeout(()=>Y.focus())};K(()=>()=>window.clearTimeout(U.current),[]),Bo();const R=re(B=>$.current===A.current?.side&&eR(B,A.current?.area),[]);return a(MI,{scope:n,searchRef:N,onItemEnter:re(B=>{R(B)&&B.preventDefault()},[R]),onItemLeave:re(B=>{R(B)||(E.current?.focus(),P(null))},[R]),onTriggerLeave:re(B=>{R(B)&&B.preventDefault()},[R]),pointerGraceTimerRef:G,onPointerGraceIntentChange:re(B=>{A.current=B},[]),children:a(J,{...H,children:a(hi,{asChild:!0,trapped:i,onMountAutoFocus:z(o,B=>{B.preventDefault(),E.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:s,children:a(Gn,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:p,onInteractOutside:m,onDismiss:f,children:a(qc,{asChild:!0,...S,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:k,onCurrentTabStopIdChange:P,onEntryFocus:z(l,B=>{_.isUsingKeyboardRef.current||B.preventDefault()}),preventScrollOnEntryFocus:!0,children:a(Pa,{role:"menu","aria-orientation":"vertical","data-state":ay(g.open),"data-radix-menu-content":"",dir:_.dir,...w,...h,ref:M,style:{outline:"none",...h.style},onKeyDown:z(h.onKeyDown,B=>{const V=B.target.closest("[data-radix-menu-content]")===B.currentTarget,he=B.ctrlKey||B.altKey||B.metaKey,ue=B.key.length===1;V&&(B.key==="Tab"&&B.preventDefault(),!he&&ue&&x(B.key));const ce=E.current;if(B.target!==ce||!PI.includes(B.key))return;B.preventDefault();const be=T().filter(Y=>!Y.disabled).map(Y=>Y.ref.current);Mv.includes(B.key)&&be.reverse(),YI(be)}),onBlur:z(e.onBlur,B=>{B.currentTarget.contains(B.target)||(window.clearTimeout(U.current),N.current="")}),onPointerMove:z(e.onPointerMove,eo(B=>{const V=B.target,he=L.current!==B.clientX;B.currentTarget.contains(V)&&he&&($.current=B.clientX>L.current?"right":"left",L.current=B.clientX)}))})})})})})})});Hv.displayName=St;var BI="MenuGroup",md=j((e,t)=>{const{__scopeMenu:n,...r}=e;return a(se.div,{role:"group",...r,ref:t})});md.displayName=BI;var UI="MenuLabel",Kv=j((e,t)=>{const{__scopeMenu:n,...r}=e;return a(se.div,{...r,ref:t})});Kv.displayName=UI;var is="MenuItem",Vv="menu.itemSelect",os=j((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,o=F(null),s=Zi(is,e.__scopeMenu),c=ud(is,e.__scopeMenu),l=_e(t,o),d=F(!1),u=()=>{const p=o.current;if(!n&&p){const m=new CustomEvent(Vv,{bubbles:!0,cancelable:!0});p.addEventListener(Vv,f=>r?.(f),{once:!0}),dc(p,m),m.defaultPrevented?d.current=!1:s.onClose()}};return a(Wv,{...i,ref:l,disabled:n,onClick:z(e.onClick,u),onPointerDown:p=>{e.onPointerDown?.(p),d.current=!0},onPointerUp:z(e.onPointerUp,p=>{d.current||p.currentTarget?.click()}),onKeyDown:z(e.onKeyDown,p=>{const m=c.searchRef.current!=="";n||m&&p.key===" "||cd.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});os.displayName=is;var Wv=j((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...o}=e,s=ud(is,n),c=jv(n),l=F(null),d=_e(t,l),[u,p]=I(!1),[m,f]=I("");return K(()=>{const y=l.current;y&&f((y.textContent??"").trim())},[o.children]),a(Yi.ItemSlot,{scope:n,disabled:r,textValue:i??m,children:a(zc,{asChild:!0,...c,focusable:!r,children:a(se.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...o,ref:d,onPointerMove:z(e.onPointerMove,eo(y=>{r?s.onItemLeave(y):(s.onItemEnter(y),y.defaultPrevented||y.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:z(e.onPointerLeave,eo(y=>s.onItemLeave(y))),onFocus:z(e.onFocus,()=>p(!0)),onBlur:z(e.onBlur,()=>p(!1))})})})}),GI="MenuCheckboxItem",qv=j((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return a(Zv,{scope:e.__scopeMenu,checked:n,children:a(os,{role:"menuitemcheckbox","aria-checked":as(n)?"mixed":n,...i,ref:t,"data-state":gd(n),onSelect:z(i.onSelect,()=>r?.(as(n)?!0:!n),{checkForDefaultPrevented:!1})})})});qv.displayName=GI;var zv="MenuRadioGroup",[HI,KI]=cr(zv,{value:void 0,onValueChange:()=>{}}),Jv=j((e,t)=>{const{value:n,onValueChange:r,...i}=e,o=lt(r);return a(HI,{scope:e.__scopeMenu,value:n,onValueChange:o,children:a(md,{...i,ref:t})})});Jv.displayName=zv;var Yv="MenuRadioItem",Xv=j((e,t)=>{const{value:n,...r}=e,i=KI(Yv,e.__scopeMenu),o=n===i.value;return a(Zv,{scope:e.__scopeMenu,checked:o,children:a(os,{role:"menuitemradio","aria-checked":o,...r,ref:t,"data-state":gd(o),onSelect:z(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});Xv.displayName=Yv;var fd="MenuItemIndicator",[Zv,VI]=cr(fd,{checked:!1}),Qv=j((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,o=VI(fd,n);return a(rt,{present:r||as(o.checked)||o.checked===!0,children:a(se.span,{...i,ref:t,"data-state":gd(o.checked)})})});Qv.displayName=fd;var WI="MenuSeparator",ey=j((e,t)=>{const{__scopeMenu:n,...r}=e;return a(se.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});ey.displayName=WI;var qI="MenuArrow",ty=j((e,t)=>{const{__scopeMenu:n,...r}=e,i=Xi(n);return a(Aa,{...i,...r,ref:t})});ty.displayName=qI;var hd="MenuSub",[zI,ny]=cr(hd),JI=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:i}=e,o=An(hd,t),s=Xi(t),[c,l]=I(null),[d,u]=I(null),p=lt(i);return K(()=>(o.open===!1&&p(!1),()=>p(!1)),[o.open,p]),a($i,{...s,children:a(Fv,{scope:t,open:r,onOpenChange:p,content:d,onContentChange:u,children:a(zI,{scope:t,contentId:ct(),triggerId:ct(),trigger:c,onTriggerChange:l,children:n})})})};JI.displayName=hd;var Qi="MenuSubTrigger",ry=j((e,t)=>{const n=An(Qi,e.__scopeMenu),r=Zi(Qi,e.__scopeMenu),i=ny(Qi,e.__scopeMenu),o=ud(Qi,e.__scopeMenu),s=F(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:l}=o,d={__scopeMenu:e.__scopeMenu},u=re(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return K(()=>u,[u]),K(()=>{const p=c.current;return()=>{window.clearTimeout(p),l(null)}},[c,l]),a(ld,{asChild:!0,...d,children:a(Wv,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":ay(n.open),...e,ref:jo(t,i.onTriggerChange),onClick:p=>{e.onClick?.(p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:z(e.onPointerMove,eo(p=>{o.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(o.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:z(e.onPointerLeave,eo(p=>{u();const m=n.content?.getBoundingClientRect();if(m){const f=n.content?.dataset.side,y=f==="right",h=y?-5:5,g=m[y?"left":"right"],_=m[y?"right":"left"];o.onPointerGraceIntentChange({area:[{x:p.clientX+h,y:p.clientY},{x:g,y:m.top},{x:_,y:m.top},{x:_,y:m.bottom},{x:g,y:m.bottom}],side:f}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(p),p.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:z(e.onKeyDown,p=>{const m=o.searchRef.current!=="";e.disabled||m&&p.key===" "||AI[r.dir].includes(p.key)&&(n.onOpenChange(!0),n.content?.focus(),p.preventDefault())})})})});ry.displayName=Qi;var iy="MenuSubContent",oy=j((e,t)=>{const n=Uv(St,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,o=An(St,e.__scopeMenu),s=Zi(St,e.__scopeMenu),c=ny(iy,e.__scopeMenu),l=F(null),d=_e(t,l);return a(Yi.Provider,{scope:e.__scopeMenu,children:a(rt,{present:r||o.open,children:a(Yi.Slot,{scope:e.__scopeMenu,children:a(pd,{id:c.contentId,"aria-labelledby":c.triggerId,...i,ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{s.isUsingKeyboardRef.current&&l.current?.focus(),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:z(e.onFocusOutside,u=>{u.target!==c.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:z(e.onEscapeKeyDown,u=>{s.onClose(),u.preventDefault()}),onKeyDown:z(e.onKeyDown,u=>{const p=u.currentTarget.contains(u.target),m=EI[s.dir].includes(u.key);p&&m&&(o.onOpenChange(!1),c.trigger?.focus(),u.preventDefault())})})})})})});oy.displayName=iy;function ay(e){return e?"open":"closed"}function as(e){return e==="indeterminate"}function gd(e){return as(e)?"indeterminate":e?"checked":"unchecked"}function YI(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function XI(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function ZI(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=XI(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}function QI(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,m=l.y;u>r!=m>r&&n<(p-d)*(r-u)/(m-u)+d&&(i=!i)}return i}function eR(e,t){return t?QI({x:e.clientX,y:e.clientY},t):!1}function eo(e){return t=>t.pointerType==="mouse"?e(t):void 0}var tR=Bv,nR=ld,rR=Gv,iR=Hv,oR=md,aR=Kv,sR=os,cR=qv,lR=Jv,dR=Xv,uR=Qv,pR=ey,mR=ty,fR=ry,hR=oy,ss="DropdownMenu",[gR,rj]=st(ss,[Ov]),pt=Ov(),[vR,sy]=gR(ss),cy=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:o,onOpenChange:s,modal:c=!0}=e,l=pt(t),d=F(null),[u,p]=wt({prop:i,defaultProp:o??!1,onChange:s,caller:ss});return a(vR,{scope:t,triggerId:ct(),triggerRef:d,contentId:ct(),open:u,onOpenChange:p,onOpenToggle:re(()=>p(m=>!m),[p]),modal:c,children:a(tR,{...l,open:u,onOpenChange:p,dir:r,modal:c,children:n})})};cy.displayName=ss;var ly="DropdownMenuTrigger",dy=j((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,o=sy(ly,n),s=pt(n);return a(nR,{asChild:!0,...s,children:a(se.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:jo(t,o.triggerRef),onPointerDown:z(e.onPointerDown,c=>{!r&&c.button===0&&c.ctrlKey===!1&&(o.onOpenToggle(),o.open||c.preventDefault())}),onKeyDown:z(e.onKeyDown,c=>{r||(["Enter"," "].includes(c.key)&&o.onOpenToggle(),c.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(c.key)&&c.preventDefault())})})})});dy.displayName=ly;var yR="DropdownMenuPortal",uy=e=>{const{__scopeDropdownMenu:t,...n}=e,r=pt(t);return a(rR,{...r,...n})};uy.displayName=yR;var py="DropdownMenuContent",my=j((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=sy(py,n),o=pt(n),s=F(!1);return a(iR,{id:i.contentId,"aria-labelledby":i.triggerId,...o,...r,ref:t,onCloseAutoFocus:z(e.onCloseAutoFocus,c=>{s.current||i.triggerRef.current?.focus(),s.current=!1,c.preventDefault()}),onInteractOutside:z(e.onInteractOutside,c=>{const l=c.detail.originalEvent,d=l.button===0&&l.ctrlKey===!0,u=l.button===2||d;(!i.modal||u)&&(s.current=!0)}),style:{...e.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)"}})});my.displayName=py;var bR="DropdownMenuGroup",_R=j((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(oR,{...i,...r,ref:t})});_R.displayName=bR;var wR="DropdownMenuLabel",SR=j((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(aR,{...i,...r,ref:t})});SR.displayName=wR;var CR="DropdownMenuItem",fy=j((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(sR,{...i,...r,ref:t})});fy.displayName=CR;var TR="DropdownMenuCheckboxItem",kR=j((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(cR,{...i,...r,ref:t})});kR.displayName=TR;var NR="DropdownMenuRadioGroup",xR=j((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(lR,{...i,...r,ref:t})});xR.displayName=NR;var PR="DropdownMenuRadioItem",AR=j((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(dR,{...i,...r,ref:t})});AR.displayName=PR;var ER="DropdownMenuItemIndicator",IR=j((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(uR,{...i,...r,ref:t})});IR.displayName=ER;var RR="DropdownMenuSeparator",DR=j((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(pR,{...i,...r,ref:t})});DR.displayName=RR;var LR="DropdownMenuArrow",$R=j((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(mR,{...i,...r,ref:t})});$R.displayName=LR;var MR="DropdownMenuSubTrigger",OR=j((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(fR,{...i,...r,ref:t})});OR.displayName=MR;var jR="DropdownMenuSubContent",FR=j((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(hR,{...i,...r,ref:t,style:{...e.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)"}})});FR.displayName=jR;var BR=cy,UR=dy,GR=uy,HR=my,hy=fy;function KR({assignProjectDisabled:e,disabled:t,onAssignProject:n,onForget:r,title:i}){return v(BR,null,v(UR,{asChild:!0},v("button",{"aria-label":`Actions for ${i}`,className:"feed-menu-trigger",type:"button"},"⋯")),v(GR,null,v(HR,{align:"end",className:"feed-menu-panel",side:"bottom",sideOffset:4},v(hy,{className:"feed-menu-item",disabled:e,onSelect:()=>n()},e?"Moving…":"Assign to project…"),v(hy,{className:"feed-menu-item danger",disabled:t,onSelect:()=>r()},t?"Forgetting…":"Forget memory"))))}function VR({modes:e,active:t,onSelect:n}){return e.length<=1?null:v("div",{className:"feed-toggle"},e.map(r=>v("button",{key:r.id,className:`toggle-button${r.id===t?" active":""}`,"data-filter":r.id,onClick:()=>n(r.id),type:"button"},r.label)))}function vd({label:e,variant:t=""}){return v(Hl,{variant:"provenance",tone:t||void 0},e)}function WR({tag:e}){const t=Ug(e);return t?v(Hl,{variant:"tag",title:String(e)},t):null}function qR({item:e,onReplace:t,onRemove:n,onViewRefresh:r,onReload:i}){const o=Ha(e?.metadata_json),s=rs(e,o),c=NI(e,o),l=ft(e),d=e.title||"(untitled)",u=s&&o?.request?o.request:d,p=e.created_at||e.created_at_utc,m=cA(p),f=Ga(e.tags||[]),y=Ga(e.files||[]),h=e.project||"",g=bA(e),_=String(e.visibility||o?.visibility||"private").trim(),w=String(e.workspace_kind||o?.workspace_kind||"").trim(),S=String(e.origin_source||o?.origin_source||"").trim(),T=String(e.origin_device_id||o?.origin_device_id||"").trim(),k=String(e.trust_state||o?.trust_state||"").trim(),P=f.length?` · ${f.map(me=>Ug(me)).join(", ")}`:"",E=y.length?` · ${pA(y)}`:"",M=Number(e.id||0),U=M>0?`ID ${M}`:"",[N,G]=I(b.newItemKeys.has(l)),A=s?kI({...e,metadata_json:o}):null,$=s?null:JA({...e,metadata_json:o}),L=$?YA($):[],J=$?XA($):"summary",H=b.itemViewState.get(l),[x,R]=I($&&H&&L.some(me=>me.id===H)?H:J),B=`${l}:${x}`,[V,he]=I(b.itemExpandState.get(B)===!0),[ue,ce]=I(_==="shared"?"shared":"private"),[be,Y]=I(!1),[ge,Z]=I(!1),[Ce,le]=I(!1),ee=A?CI(A):[];K(()=>{$&&(L.some(me=>me.id===x)||R(J))},[x,J,L,$]),K(()=>{b.itemViewState.set(l,x)},[x,l]),K(()=>{const me=`${l}:${x}`;he(b.itemExpandState.get(me)===!0)},[x,l]),K(()=>{ce(_==="shared"?"shared":"private")},[_]),K(()=>{if(!N)return;const me=window.setTimeout(()=>{b.newItemKeys.delete(l),G(!1)},700);return()=>window.clearTimeout(me)},[N,l]);const xe=ue,pe=xe==="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.",W=[h?`Project ${h}`:"No project",m].filter(Boolean).join(" · "),oe=[w&&w!==_?`Workspace ${w}`:"",S?`From ${S}`:"",T&&g!=="You"?`Device ${T}`:"",k&&k!=="trusted"?yA(k):""].filter(Boolean).join(" · "),Ve=[`${P}${E}`.trim(),oe].filter(Boolean).join(" · "),Me=!!$&&ZA(x,$),tt=[x==="facts"?"feed-body facts":"feed-body",Me&&!V?QA(x).join(" "):""].filter(Boolean).join(" "),un=s?ee.length?v("div",{className:"feed-body facts"},ee):$v(String(e.body_text||""))||v("div",{className:"feed-body"}):$?x==="facts"?TI($.facts)||v("div",{className:tt}):$v(x==="narrative"?$.narrative:$.summary,tt)||v("div",{className:tt}):v("div",{className:"feed-body"});async function Lt(me){const ae=xe;ce(me),Y(!0);try{const Ge=await j_(M,me);Ge?.item&&(t(Ge.item),r()),ne(me==="shared"?"Memory will now sync as shared context.":"Memory is private again.")}catch(Ge){ce(ae),ne(Ge instanceof Error?Ge.message:"Failed to save visibility.","warning")}finally{Y(!1)}}async function kt(){const me=String(e.project||"").trim(),ae=me,Ge=String(u||"this memory").trim(),$n=Ge.length>80?`${Ge.slice(0,79).trimEnd()}…`:Ge,wo=me?`Move "${$n}" from "${me}" 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 "${$n}". Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`;let pn=[];try{pn=(await ko()).filter(ht=>ht&&ht!==me)}catch{}const br=await El({title:"Assign to project",description:wo,initialValue:ae,placeholder:"Pick one or type a new project name",suggestions:pn,confirmLabel:"Move",cancelLabel:"Cancel",validate:ht=>{const On=ht.trim();return On?On===me?"Already assigned to this project.":null:"Enter a project name."}});if(br==null)return;const Mn=br.trim();if(!(!Mn||Mn===me)){le(!0);try{const ht=await F_(M,Mn),On=Number(ht.moved_memory_count||1);ne(On>1?`Moved ${On} memories from this session to "${ht.project}".`:`Moved to "${ht.project}".`),await i(),r()}catch(ht){ne(ht instanceof Error?ht.message:"Failed to move memory.","warning")}finally{le(!1)}}}async function $t(){const me=String(u||"this memory").trim();if(await Kt({autoFocusAction:"cancel",title:"Forget this memory?",description:`Forgetting "${me.length>80?`${me.slice(0,79).trimEnd()}…`:me}". 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"})){Z(!0);try{await B_(M),n(M),r(),await i(),ne("Memory forgotten and removed from the active feed.")}catch(ae){ne(ae instanceof Error?ae.message:"Failed to forget memory.","warning")}finally{Z(!1)}}}const nt=c.replace(/_/g," "),Mt=y.length?v("div",{className:"feed-files"},y.map((me,ae)=>v("span",{className:"feed-file",key:`${String(me)}-${ae}`},String(me)))):null;return v("article",{className:`feed-item ${c}${N?" new-item":""}`.trim(),"data-key":l},v("div",{className:"feed-kind-banner"},v(Hl,{variant:"kind",tone:c},nt)),v("div",{className:"feed-card-body"},v("div",{className:"feed-card-header"},v("div",{className:"feed-header"},v("div",{className:"feed-title title",dangerouslySetInnerHTML:{__html:WT(u,b.feedQuery)}}),v("div",{className:"feed-card-subtitle small"},W)),v("div",{className:"feed-actions"},$?v(VR,{active:x,modes:L,onSelect:me=>R(me)}):null,v(za,{label:sA(p),side:"left"},v("div",{className:"small feed-age"},m)),e.owned_by_self&&M>0?v(KR,{assignProjectDisabled:Ce,disabled:ge,onAssignProject:()=>{kt()},onForget:()=>{$t()},title:String(u||"memory")}):null)),v("div",{className:"feed-provenance"},v(vd,{label:g,variant:g==="You"?"mine":"author"}),v(vd,{label:_||"private",variant:_||"private"}),U?v(za,{label:`Memory database id ${M}`,side:"top"},v(vd,{label:U,variant:"memory-id"})):null),v("div",{className:"feed-meta"},Ve||"No tags, files, or provenance details attached."),un,v("div",{className:"feed-footer"},v("div",{className:"feed-footer-left"},f.length?v("div",{className:"feed-tags"},f.map((me,ae)=>v(WR,{key:`${String(me)}-${ae}`,tag:me}))):null,e.owned_by_self&&M>0?v("div",{className:"feed-visibility-controls"},v("select",{"aria-label":`Visibility for ${String(e.title||"memory")}`,className:"feed-visibility-select",disabled:be,onChange:me=>{Lt(String(me.currentTarget.value)==="shared"?"shared":"private")},value:xe},v("option",{value:"private"},"Only me"),v("option",{value:"shared"},"Share with peers")),v("div",{className:"feed-visibility-note"},pe)):null),v("div",{className:"feed-footer-right"},Me?v("button",{className:"feed-expand",onClick:()=>{const me=!V;b.itemExpandState.set(B,me),he(me)},type:"button"},V?"Collapse":"Expand"):null)),Mt))}function zR({index:e}){const t=[["w-85","w-65"],["w-85","w-40"],["w-65","w-85"]],[n,r]=t[e%t.length];return v("div",{className:"feed-skeleton-item","aria-hidden":"true"},v("div",{className:"feed-skeleton-banner"}),v("div",{className:"feed-skeleton-body"},v("div",{className:`feed-skeleton-line ${n}`}),v("div",{className:`feed-skeleton-line ${r}`}),v("div",{className:"feed-skeleton-footer"},v("div",{className:"feed-skeleton-chip w-36"}),v("div",{className:"feed-skeleton-chip w-56"}),v("div",{className:"feed-skeleton-chip"}))))}function JR({items:e,loadingText:t,ops:n}){if(t)return v("div",{className:"feed-skeleton",role:"status","aria-label":t},[0,1,2,3].map(r=>v(zR,{index:r,key:`skeleton-${r}`})));if(!e.length){const r=!!b.feedQuery.trim()||b.feedTypeFilter!=="all"||b.feedScopeFilter!=="all";return v("div",{className:"small feed-empty-state"},v("strong",null,r?"No memories match the current filters.":"No memories yet."),v("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 v(te,null,e.map(r=>v(qR,{item:r,key:ft(r),onReplace:n.replaceFeedItem,onRemove:n.removeFeedItem,onViewRefresh:()=>n.updateFeedView(!0),onReload:n.loadFeedData})))}function gy({id:e,active:t,options:n,onSelect:r}){return v("div",{className:"feed-toggle",id:e},n.map(({value:i,label:o})=>{const s=i===t;return v("button",{"aria-pressed":s?"true":"false",className:`toggle-button${s?" active":""}`,"data-filter":i,key:i,onClick:()=>r(i),type:"button"},o)}))}function YR({items:e,loadingText:t,ops:n}){const[r,i]=I(!1);return v(te,null,v("div",{className:"feed-controls"},v("div",{className:"section-meta",id:"feedMeta"},t||eE(e.length,n.hasMorePages())),v("div",{className:"feed-controls-right"},v("input",{className:"feed-search",id:"feedSearch",onInput:o=>{b.feedQuery=String(o.currentTarget.value||""),n.updateFeedView()},placeholder:"Search title, body, tags…",value:b.feedQuery}),v(gy,{active:b.feedScopeFilter,id:"feedScopeToggle",onSelect:o=>{o!==b.feedScopeFilter&&(Tf(o),n.loadFeedData())},options:[{value:"all",label:"All"},{value:"mine",label:"My memories"},{value:"theirs",label:"Other people"}]}),v(gy,{active:b.feedTypeFilter,id:"feedTypeToggle",onSelect:o=>{o!==b.feedTypeFilter&&(ok(o),n.updateFeedView())},options:[{value:"all",label:"All"},{value:"observations",label:"Observations"},{value:"summaries",label:"Summaries"}]}),v("button",{"aria-controls":"contextInspectorPanel","aria-expanded":r,className:"settings-button feed-inspector-button",onClick:()=>i(o=>!o),type:"button"},r?"Hide Context Inspector":"Context Inspector"))),v(tE,{open:r}),v("div",{className:"feed-list",id:"feedList"},v(JR,{items:e,loadingText:t,ops:n})))}function XR(e){return b.feedTypeFilter==="observations"?e.filter(t=>!rs(t,Ha(t?.metadata_json))):b.feedTypeFilter==="summaries"?e.filter(t=>rs(t,Ha(t?.metadata_json))):e}function ZR(e){const t=It(b.feedQuery);return t?e.filter(n=>[It(n?.title),It(n?.body_text),It(n?.kind),Ga(n?.tags||[]).map(r=>It(r)).join(" "),It(n?.project)].join(" ").trim().includes(t)):e}function QR(e){const t=e.map(n=>`${Hg(n)}:${n.kind||""}:${n.created_at_utc||n.created_at||""}`);return`${b.feedTypeFilter}|${b.feedScopeFilter}|${b.currentProject}|${It(b.feedQuery)}|${t.join("|")}`}var vy="",to=0,no=0,ro=!0,io=!0,yd=!1,yy=!1,oo=0,bd="all";function e0(e){vy=e,bd=b.feedScopeFilter,oo+=1,to=0,no=0,ro=!0,io=!0,b.lastFeedItems=[],b.pendingFeedItems=null,b.lastFeedFilteredCount=0,b.lastFeedSignature="",b.newItemKeys.clear(),b.itemViewState.clear(),b.itemExpandState.clear()}function _d(){return ro||io}function t0(e){const t=ft(e);b.lastFeedItems=b.lastFeedItems.map(n=>ft(n)===t?e:n)}function n0(e){const t=new Set,n=r=>{const i=Number(r.id||r.memory_id||0)!==e;return i||t.add(ft(r)),i};b.lastFeedItems=b.lastFeedItems.filter(n),Array.isArray(b.pendingFeedItems)&&(b.pendingFeedItems=b.pendingFeedItems.filter(n));for(const r of t){b.newItemKeys.delete(r),b.itemViewState.delete(r);for(const i of Array.from(b.itemExpandState.keys()))i.startsWith(`${r}:`)&&b.itemExpandState.delete(i)}}async function r0(){if(yd||!_d())return;const e=b.currentProject||"",t=oo,n=to,r=no;yd=!0;try{const[i,o]=await Promise.all([ro?Ru(e,{limit:20,offset:n,scope:b.feedScopeFilter}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:n}}),io?Du(e,{limit:50,offset:r,scope:b.feedScopeFilter}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:r}})]);if(t!==oo||e!==(b.currentProject||""))return;const s=o.items||[],c=i.items||[],l=c.filter(u=>!Gg(u));b.lastFeedFilteredCount+=c.length-l.length,io=Ka(o,s.length,50),ro=Ka(i,c.length,20),no=Va(o,r+s.length),to=Va(i,n+c.length);const d=[...s,...l];b.lastFeedItems=Kg(b.lastFeedItems,d),ao()}finally{yd=!1}}function by(){b.activeTab==="feed"&&_d()&&wA()&&r0()}var i0={replaceFeedItem:t0,removeFeedItem:n0,updateFeedView:e=>ao(e),loadFeedData:()=>_y(),hasMorePages:_d};function wd(e,t){const n=document.getElementById("tab-feed");if(!n)return!1;WA(n,v(YR,{items:e,loadingText:t?.loadingText,ops:i0}));const r=globalThis.lucide;return r&&!t?.loadingText&&r.createIcons(),!0}function o0(){wd([],{loadingText:"Loading selected project..."})}function a0(){VA(),wd(b.lastFeedItems,b.lastFeedItems.length||b.lastFeedSignature?void 0:{loadingText:"Loading memories…"}),yy||(window.addEventListener("scroll",()=>{by()},{passive:!0}),yy=!0)}function ao(e=!1){if(!document.getElementById("tab-feed"))return;const t=window.scrollY,n=ZR(XR(b.lastFeedItems)),r=QR(n),i=e||r!==b.lastFeedSignature;b.lastFeedSignature=r,i&&wd(n),window.scrollTo({top:t}),by()}async function _y(){const e=b.currentProject||"",t=b.feedScopeFilter!==bd;(e!==vy||t)&&(e0(e),o0());const n=oo,r=20,i=50,[o,s]=await Promise.all([Ru(e,{limit:r,offset:0,scope:b.feedScopeFilter}),Du(e,{limit:i,offset:0,scope:b.feedScopeFilter})]);if(n!==oo||e!==(b.currentProject||""))return;const c=s.items||[],l=o.items||[],d=l.filter(y=>!Gg(y)),u=l.length-d.length,p=[...c,...d].sort((y,h)=>new Date(h.created_at||0).getTime()-new Date(y.created_at||0).getTime()),m=_A(b.lastFeedItems,p),f=b.lastFeedItems;if(SA(m,f)&&f.length>0){const y=new Set(f.map(ft));m.forEach(h=>{y.has(ft(h))||b.newItemKeys.add(ft(h))})}b.pendingFeedItems=null,b.lastFeedItems=m,b.lastFeedFilteredCount=Math.max(b.lastFeedFilteredCount,u),io=Ka(s,c.length,i),ro=Ka(o,l.length,r),no=Math.max(no,Va(s,c.length)),to=Math.max(to,Va(o,l.length)),bd=b.feedScopeFilter,ao()}var s0=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function wy(e){return!!s0.exec(e)?.slice(1,4).map(Number).every(Number.isSafeInteger)}function ij(e){return e}function c0(e){return e.latest_version?e.stale?{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"}:e.update_available?{title:`Codemem ${e.latest_version} is available`,detail:`Installed version: ${e.current_version}.`,tone:"available"}:wy(e.current_version)?{title:`Codemem ${e.current_version} is up to date`,detail:"You are running the latest stable release.",tone:"current"}:{title:`Unable to compare Codemem ${e.current_version} with ${e.latest_version}`,detail:"The installed version is not a stable semantic version.",tone:"unavailable"}:{title:"Update check unavailable",detail:e.error?`Could not check for updates: ${e.error}`:"Could not check for updates.",tone:"unavailable"}}function l0({status:e}){const t=c0(e),n=e.update_available||e.stale||!e.latest_version||!wy(e.current_version);return v("section",{class:`health-update-banner health-update-banner--${t.tone}`,role:"status","aria-atomic":"true","aria-label":"Codemem update status"},v("i",{"aria-hidden":"true","data-lucide":"circle-arrow-up",class:"health-update-icon"}),v("div",{class:"health-update-copy"},v("h2",null,t.title),v("p",null,t.detail),n&&e.recommended_action?v("p",{class:"health-update-guidance"},v("span",{class:"health-update-guidance-label"},"Recommended action"),v("code",null,e.recommended_action)):null))}function d0(e,t){e&&(e.hidden=!t,Be(t?v(l0,{status:t}):null,e))}function u0({label:e,value:t,detail:n,icon:r,className:i,title:o}){const s=v("div",{class:`stat${i?` ${i}`:""}`,style:o?"cursor: help;":void 0},r?v("i",{"data-lucide":r,class:"stat-icon"}):null,v("div",{class:"stat-content"},v("div",{class:"value"},t),v("div",{class:"label"},e),n?v("div",{class:"small"},n):null));return o?v(za,{label:o},s):s}function p0({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()}catch{}t.disabled=!1,t.textContent=r}}function o(){!e.command||!n||Pi(e.command,n)}return v("div",{class:"health-action"},v("div",{class:"health-action-text"},e.label,e.command?v("span",{class:"health-action-command"},e.command):null),v("div",{class:"health-action-buttons"},e.action?v("button",{class:"settings-button",onClick:i,ref:s=>{t=s}},r):null,e.command?v("button",{class:"settings-button health-action-copy",onClick:o,ref:s=>{n=s}},"Copy"):null))}function m0(e){return typeof e=="number"?e.toLocaleString():e==null?"n/a":String(e)}function f0({label:e,value:t,icon:n,tooltip:r}){const i=v("div",{class:"stat",style:r?"cursor: help;":void 0},v("i",{"data-lucide":n,class:"stat-icon"}),v("div",{class:"stat-content"},v("div",{class:"value"},m0(t)),v("div",{class:"label"},e)));return r?v(za,{label:r},i):i}function Sy(e,t){e&&Be(v(Ul,null,t.map(n=>v(f0,{...n,key:`${n.label}-${n.icon}`}))),e)}function Cy(e,t){e&&Be(v(te,null,t),e)}function Sd(){const e=globalThis.lucide;e&&typeof e.createIcons=="function"&&e.createIcons()}function h0(e,t){e&&Be(v(Ul,null,t.map(n=>v(u0,{...n,key:n.key??n.label}))),e)}function g0(e,t){if(e){if(!t.length){e.hidden=!0,Be(null,e);return}e.hidden=!1,Be(v(te,null,t.slice(0,3).map((n,r)=>v(p0,{item:n,key:`${n.label}-${r}`}))),e)}}var Ty="scope_id_backfill";function ky(){const e=document.getElementById("healthGrid"),t=document.getElementById("healthMeta"),n=document.getElementById("healthActions"),r=document.getElementById("healthDot");if(!e||!t)return;d0(document.getElementById("healthUpdateBanner"),b.lastUpdateStatus);const i=b.lastStatsPayload||{},o=b.lastUsagePayload||{},s=b.lastRawEventsPayload&&typeof b.lastRawEventsPayload=="object"?b.lastRawEventsPayload:{},c=b.lastSyncStatus||{},l=Array.isArray(i.maintenance_jobs)?i.maintenance_jobs:[],d=l.find(oe=>oe.kind===Ty),u=i.reliability||{},p=u.counts||{},m=u.rates||{},f=i.database||{},y=o.totals_filtered||o.totals||o.totals_global||i.usage?.totals||{},h=Array.isArray(o.recent_packs)?o.recent_packs:[],g=h.length?h[0]?.created_at:null,_=h.length?h[0]?.metadata_json||{}:{},w=Number(_?.exact_duplicates_collapsed||0),S=Number(s.pending||0),T=Number(p.errored_batches||0),k=Number(m.flush_success_rate??1),P=Number(m.dropped_event_rate||0),E=Ml(y.tokens_saved,y.tokens_read),M=dA(E),U=Number(f.tags_coverage||0),N=String(c.daemon_state||"unknown"),G=N==="offline-peers"?"Offline peers":N==="needs_attention"?"Needs attention":N==="rebootstrapping"?"Rebootstrapping":Bg(N),A=Array.isArray(b.lastSyncPeers)?b.lastSyncPeers.length:0,$=N==="disabled"||c.enabled===!1,L=N==="offline-peers",J=!$&&A===0;let H=$?"Disabled":J?"No peers":G;const x=Kr(c.last_sync_at||c.last_sync_at_utc||null),R=Kr(g),B=x!==null&&x>7200,V=x!==null&&x<=300,he=S>=200;let ue=0;const ce=[];S>=1e3?(ue+=40,ce.push("high raw-event backlog")):S>=200&&(ue+=24,ce.push("growing raw-event backlog")),T>0&&S>=200&&(ue+=T>=5?10:6,ce.push("batch errors during backlog pressure")),k<.95&&(ue+=20,ce.push("lower flush success")),P>.02?(ue+=24,ce.push("high dropped-event rate")):P>.005&&(ue+=10,ce.push("non-trivial dropped-event rate")),!$&&!J&&(N==="error"?(ue+=36,ce.push("sync daemon reports errors")):N==="needs_attention"?(ue+=40,ce.push("sync needs manual attention")):N==="stopped"?(ue+=22,ce.push("sync daemon stopped")):N==="degraded"&&!V&&(ue+=20,ce.push("sync daemon degraded")),L?(ue+=4,ce.push("all peers currently offline"),B&&(ue+=4,ce.push("offline peers and sync not recent"))):B?(ue+=26,ce.push("sync looks stale")):x!==null&&x>1800&&(ue+=12,ce.push("sync not recent"))),M!==null&&M<10&&(ue+=8,ce.push("low retrieval reduction")),R!==null&&R>86400&&(ue+=12,ce.push("memory pack activity is old"));let be="Healthy",Y="status-healthy";ue>=60?(be="Attention",Y="status-attention"):ue>=25&&(be="Degraded",Y="status-degraded");const ge=Y==="status-healthy";r&&(r.className=`health-dot ${Y}`,r.title=be);const Z=`${Number(y.tokens_saved||0).toLocaleString()} saved tokens · ${w.toLocaleString()} deduped in latest pack`,Ce=S>0?"Queue is actively draining":"Queue is clear",le=$?"Sync disabled":J?"No peers configured":L?`${A} peers offline · last sync ${kn(x)} ago`:`${A} peers · last sync ${kn(x)} ago`;ge&&!$&&!J&&(L?H="Peers offline":N==="degraded"&&V&&(H="Syncing"));const ee=`last pack ${kn(R)} ago`,xe=l.map(oe=>{const Ve=Number(oe.progress?.current||0),Me=typeof oe.progress?.total=="number"?oe.progress.total:null,tt=String(oe.progress?.unit||"items"),un=Me&&Me>0?` (${Math.round(100*Ve/Me)}%)`:"",Lt=Me&&Me>0?`${Ve.toLocaleString()}/${Me.toLocaleString()} ${tt}${un}`:`${Ve.toLocaleString()} ${tt}`,kt=oe.status==="failed",$t=oe.status==="completed",nt=oe.kind===Ty,Mt=kt?"Failed":$t?"Complete":Lt,me=kt?String(oe.error||"unknown error").trim():$t?nt?`${Lt} · one-time Sharing-domain upgrade finished`:Lt:nt?"One-time upgrade backfill; totals include memories and replication ops":void 0;return{key:String(oe.kind||oe.title||"background-maintenance"),label:String(oe.title||oe.kind||"Background maintenance"),value:Mt,detail:me,icon:kt?"alert-triangle":$t?"check-circle":"loader",className:kt?"status-attention":void 0,title:kt?`Error: ${oe.error||"unknown"}`:$t?`${String(oe.title||"Maintenance")} finished`:nt?`${String(oe.title||"Maintenance")} in progress; inspect with codemem maintenance status`:`${String(oe.title||"Maintenance")} in progress`}});h0(e,[{key:"overall-health",label:"Overall health",value:be,detail:`Weighted score ${ue}`,icon:"heart-pulse",className:`health-primary ${Y}`,title:ce.length?`Main signals: ${ce.join(", ")}`:"No major risk signals detected"},...xe,{key:"pipeline-health",label:"Pipeline health",value:`${S.toLocaleString()} pending`,detail:Ce,icon:"workflow",title:"Raw-event queue pressure and flush reliability"},{key:"retrieval-impact",label:"Retrieval impact",value:E,detail:Z,icon:"sparkles",title:"Reduction from memory reuse across recent usage"},{key:"sync-health",label:"Sync health",value:H,detail:le,icon:"refresh-cw",title:"Daemon state and sync recency"},{key:"data-freshness",label:"Data freshness",value:kn(R),detail:ee,icon:"clock-3",title:"Recency of last memory pack activity"}]);const pe=async()=>{await Gs()},W=[];he?(W.push({label:"Pipeline needs attention. Check queue health first.",command:"codemem db raw-events-status"}),W.push({label:"Then retry failed batches for impacted sessions.",command:"codemem db raw-events-retry <opencode_session_id>"})):N==="stopped"?W.push({label:"Sync daemon is stopped. Start the background service.",command:"codemem serve start"}):!$&&!J&&!ge&&(N==="error"||N==="degraded")?(W.push({label:"Sync is unhealthy. Restart and run one immediate pass.",command:"codemem serve restart",action:pe,actionLabel:"Sync now"}),W.push({label:"Then run doctor to see root cause details.",command:"codemem sync doctor"})):!$&&!J&&B&&W.push({label:"Sync is stale. Run one immediate sync pass.",command:"codemem sync once",action:pe,actionLabel:"Sync now"}),U>0&&U<.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"}),g0(n,W),t.textContent=ce.length?`Why this status: ${ce.join(", ")}.`:"Healthy right now. Diagnostics stay available if you want details.",Sd()}function v0(){const e=document.getElementById("sessionGrid"),t=document.getElementById("sessionMeta");if(!e||!t)return;const n=b.lastUsagePayload||{},r=b.currentProject;n?.totals_global||n?.totals;const i=n?.totals_filtered||null,o=!!(r&&i),s=(Array.isArray(n?.events)?n.events:[]).find(k=>k.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),m=Number(l?.tokens_read||0),f=Number(l?.tokens_saved||0),y=Number(d?.exact_duplicates_collapsed||0),h=!!d?.exact_dedupe_enabled,g=Ml(f,m),_=p?`${p} packs`:"No packs yet",w=u?`Last pack: ${rr(u)}`:"",S=o?"Project":"All projects",T=[{label:"Last pack savings",value:l?`${Fi(f)} (${g})`:"n/a",tooltip:l?`Exact: ${f.toLocaleString()} saved`:void 0,icon:"trending-up"},{label:"Last pack size",value:l?Fi(m):"n/a",tooltip:l?`Exact: ${m.toLocaleString()} injected`:void 0,icon:"package"},{label:"Last pack deduped",value:l?y.toLocaleString():"n/a",icon:"copy-check"},{label:"Exact dedupe",value:l?h?"On":"Off":"n/a",icon:"shield-check"},{label:"Packs",value:p||0,icon:"archive"}];Cy(t,[S,_,w].filter(Boolean).join(" · ")),Sy(e,T),Sd()}function y0(){const e=document.getElementById("statsGrid"),t=document.getElementById("metaLine");if(!e)return;const n=b.lastStatsPayload||{},r=b.lastUsagePayload||{},i=b.lastRawEventsPayload&&typeof b.lastRawEventsPayload=="object"?b.lastRawEventsPayload:{},o=n.database||{},s=b.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),m=Number(i.pending||0),f=d?`
112
- Global: ${Number(c.work_investment_tokens||0).toLocaleString()} invested`:"",y=d?`
110
+ `}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>${Vt(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=sy(e);if(i===null)return r;e=i;let o='<a href="'+e+'"';return t&&(o+=' title="'+Vt(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=sy(e);if(i===null)return Vt(n);e=i;let o=`<img src="${e}" alt="${Vt(n)}"`;return t&&(o+=` title="${Vt(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Vt(e.text)}},wd=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}},$t=class Wu{options;renderer;textRenderer;constructor(t){this.options=t||ar,this.options.renderer=this.options.renderer||new hs,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new wd}static parse(t,n){return new Wu(n).parse(t)}static parseInline(t,n){return new Wu(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","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","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}},ao=class{options;block;constructor(e){this.options=e||ar}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?Lt.lex:Lt.lexInline}provideParser(e=this.block){return e?$t.parse:$t.parseInline}},nR=class{defaults=pd();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=$t;Renderer=hs;TextRenderer=wd;Lexer=Lt;Tokenizer=ms;Hooks=ao;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 hs(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 ms(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 ao;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];ao.passThroughHooks.has(o)?i[s]=d=>{if(this.defaults.async&&ao.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 Lt.lex(e,t??this.defaults)}parser(e,t){return $t.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?Lt.lex:Lt.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?$t.parse:$t.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?Lt.lex:Lt.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?$t.parse:$t.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+=`
111
+ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error occurred:</p><pre>"+Vt(n.message+"",!0)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},cr=new nR;function xe(e,t){return cr.parse(e,t)}xe.options=xe.setOptions=function(e){return cr.setOptions(e),xe.defaults=cr.defaults,zg(xe.defaults),xe},xe.getDefaults=pd,xe.defaults=ar,xe.use=function(...e){return cr.use(...e),xe.defaults=cr.defaults,zg(xe.defaults),xe},xe.walkTokens=function(e,t){return cr.walkTokens(e,t)},xe.parseInline=cr.parseInline,xe.Parser=$t,xe.parser=$t.parse,xe.Renderer=hs,xe.TextRenderer=wd,xe.Lexer=Lt,xe.lexer=Lt.lex,xe.Tokenizer=ms,xe.Hooks=ao,xe.parse=xe;var Lj=xe.options,$j=xe.setOptions,Mj=xe.use,Oj=xe.walkTokens,jj=xe.parseInline,Fj=xe,Bj=$t.parse,Uj=Lt.lex,rR={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 iR(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:")}Wg.addHook("afterSanitizeAttributes",e=>{e.tagName==="A"&&(iR(e.getAttribute("href")||"")?(e.setAttribute("rel","noopener noreferrer"),e.setAttribute("target","_blank")):e.removeAttribute("href"))});function Sd(e){const t=xe.parse(String(e||""),{async:!1});return Wg.sanitize(t,rR)}function oR(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"},Kx(r)),y("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:Sd(i)}})):null}).filter(Boolean)}function aR(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:Sd(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 uy(e,t="feed-body"){const n=String(e||"").trim();return n?y("div",{className:t,dangerouslySetInnerHTML:{__html:Sd(n)}}):null}function sR(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 vs(e,t){return String(e?.kind||"").toLowerCase()==="session_summary"||t?.is_summary===!0?!0:String(t?.source||"").trim().toLowerCase()==="observer_summary"}function cR(e,t){const n=String(e?.kind||"").trim().toLowerCase();return vs(e,t)?"session_summary":n||"change"}var Cd=["Enter"," "],lR=["ArrowDown","PageUp","Home"],py=["ArrowUp","PageDown","End"],dR=[...lR,...py],uR={ltr:[...Cd,"ArrowRight"],rtl:[...Cd,"ArrowLeft"]},pR={ltr:["ArrowLeft"],rtl:["ArrowRight"]},so="Menu",[co,fR,mR]=_a(so),[lr,fy]=ot(so,[mR,_n,Mr]),lo=_n(),my=Mr(),[hy,Pn]=lr(so),[hR,uo]=lr(so),vy=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:o,modal:s=!0}=e,c=lo(t),[l,d]=D(null),u=U(!1),p=st(o),f=Bi(i);return K(()=>{const m=()=>{u.current=!0,document.addEventListener("pointerdown",v,{capture:!0,once:!0}),document.addEventListener("pointermove",v,{capture:!0,once:!0})},v=()=>u.current=!1;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})}},[]),a(qi,{...c,children:a(hy,{scope:t,open:n,onOpenChange:p,content:l,onContentChange:d,children:a(hR,{scope:t,onClose:ie(()=>p(!1),[p]),isUsingKeyboardRef:u,dir:f,modal:s,children:r})})})};vy.displayName=so;var vR="MenuAnchor",Nd=H((e,t)=>{const{__scopeMenu:n,...r}=e,i=lo(n);return a(Ki,{...i,...r,ref:t})});Nd.displayName=vR;var kd="MenuPortal",[gR,gy]=lr(kd,{forceMount:void 0}),yy=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,o=Pn(kd,t);return a(gR,{scope:t,forceMount:n,children:a(et,{present:n||o.open,children:a(qn,{asChild:!0,container:i,children:r})})})};yy.displayName=kd;var Nt="MenuContent",[yR,Td]=lr(Nt),by=H((e,t)=>{const n=gy(Nt,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,o=Pn(Nt,e.__scopeMenu),s=uo(Nt,e.__scopeMenu);return a(co.Provider,{scope:e.__scopeMenu,children:a(et,{present:r||o.open,children:a(co.Slot,{scope:e.__scopeMenu,children:s.modal?a(bR,{...i,ref:t}):a(_R,{...i,ref:t})})})})}),bR=H((e,t)=>{const n=Pn(Nt,e.__scopeMenu),r=U(null),i=_e(t,r);return K(()=>{const o=r.current;if(o)return oa(o)},[]),a(Id,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:z(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),_R=H((e,t)=>{const n=Pn(Nt,e.__scopeMenu);return a(Id,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),wR=Gn("MenuContent.ScrollLock"),Id=H((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:s,disableOutsidePointerEvents:c,onEntryFocus:l,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:p,onInteractOutside:f,onDismiss:m,disableOutsideScroll:v,...h}=e,g=Pn(Nt,n),_=uo(Nt,n),w=lo(n),S=my(n),N=fR(n),[k,E]=D(null),R=U(null),j=_e(t,R,g.onContentChange),q=U(0),I=U(""),G=U(0),A=U(null),M=U("right"),L=U(0),x=v?Ti:Z,O=v?{as:wR,allowPinchZoom:!0}:void 0,T=B=>{const V=I.current+B,le=N().filter(ve=>!ve.disabled),de=document.activeElement,ae=le.find(ve=>ve.ref.current===de)?.textValue,be=LR(le.map(ve=>ve.textValue),V,ae),J=le.find(ve=>ve.textValue===be)?.ref.current;(function ve(ee){I.current=ee,window.clearTimeout(q.current),ee!==""&&(q.current=window.setTimeout(()=>ve(""),1e3))})(V),J&&setTimeout(()=>J.focus())};K(()=>()=>window.clearTimeout(q.current),[]),Xo();const P=ie(B=>M.current===A.current?.side&&MR(B,A.current?.area),[]);return a(yR,{scope:n,searchRef:I,onItemEnter:ie(B=>{P(B)&&B.preventDefault()},[P]),onItemLeave:ie(B=>{P(B)||(R.current?.focus(),E(null))},[P]),onTriggerLeave:ie(B=>{P(B)&&B.preventDefault()},[P]),pointerGraceTimerRef:G,onPointerGraceIntentChange:ie(B=>{A.current=B},[]),children:a(x,{...O,children:a(Ni,{asChild:!0,trapped:i,onMountAutoFocus:z(o,B=>{B.preventDefault(),R.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:s,children:a(Hn,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:p,onInteractOutside:f,onDismiss:m,children:a(sl,{asChild:!0,...S,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:k,onCurrentTabStopIdChange:E,onEntryFocus:z(l,B=>{_.isUsingKeyboardRef.current||B.preventDefault()}),preventScrollOnEntryFocus:!0,children:a(Fa,{role:"menu","aria-orientation":"vertical","data-state":My(g.open),"data-radix-menu-content":"",dir:_.dir,...w,...h,ref:j,style:{outline:"none",...h.style},onKeyDown:z(h.onKeyDown,B=>{const V=B.target.closest("[data-radix-menu-content]")===B.currentTarget,le=B.ctrlKey||B.altKey||B.metaKey,de=B.key.length===1;V&&(B.key==="Tab"&&B.preventDefault(),!le&&de&&T(B.key));const ae=R.current;if(B.target!==ae||!dR.includes(B.key))return;B.preventDefault();const be=N().filter(J=>!J.disabled).map(J=>J.ref.current);py.includes(B.key)&&be.reverse(),RR(be)}),onBlur:z(e.onBlur,B=>{B.currentTarget.contains(B.target)||(window.clearTimeout(q.current),I.current="")}),onPointerMove:z(e.onPointerMove,fo(B=>{const V=B.target,le=L.current!==B.clientX;B.currentTarget.contains(V)&&le&&(M.current=B.clientX>L.current?"right":"left",L.current=B.clientX)}))})})})})})})});by.displayName=Nt;var SR="MenuGroup",Ed=H((e,t)=>{const{__scopeMenu:n,...r}=e;return a(se.div,{role:"group",...r,ref:t})});Ed.displayName=SR;var CR="MenuLabel",_y=H((e,t)=>{const{__scopeMenu:n,...r}=e;return a(se.div,{...r,ref:t})});_y.displayName=CR;var gs="MenuItem",wy="menu.itemSelect",ys=H((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,o=U(null),s=uo(gs,e.__scopeMenu),c=Td(gs,e.__scopeMenu),l=_e(t,o),d=U(!1),u=()=>{const p=o.current;if(!n&&p){const f=new CustomEvent(wy,{bubbles:!0,cancelable:!0});p.addEventListener(wy,m=>r?.(m),{once:!0}),Cc(p,f),f.defaultPrevented?d.current=!1:s.onClose()}};return a(Sy,{...i,ref:l,disabled:n,onClick:z(e.onClick,u),onPointerDown:p=>{e.onPointerDown?.(p),d.current=!0},onPointerUp:z(e.onPointerUp,p=>{d.current||p.currentTarget?.click()}),onKeyDown:z(e.onKeyDown,p=>{const f=c.searchRef.current!=="";n||f&&p.key===" "||Cd.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});ys.displayName=gs;var Sy=H((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...o}=e,s=Td(gs,n),c=my(n),l=U(null),d=_e(t,l),[u,p]=D(!1),[f,m]=D("");return K(()=>{const v=l.current;v&&m((v.textContent??"").trim())},[o.children]),a(co.ItemSlot,{scope:n,disabled:r,textValue:i??f,children:a(cl,{asChild:!0,...c,focusable:!r,children:a(se.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...o,ref:d,onPointerMove:z(e.onPointerMove,fo(v=>{r?s.onItemLeave(v):(s.onItemEnter(v),v.defaultPrevented||v.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:z(e.onPointerLeave,fo(v=>s.onItemLeave(v))),onFocus:z(e.onFocus,()=>p(!0)),onBlur:z(e.onBlur,()=>p(!1))})})})}),NR="MenuCheckboxItem",Cy=H((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return a(Ey,{scope:e.__scopeMenu,checked:n,children:a(ys,{role:"menuitemcheckbox","aria-checked":bs(n)?"mixed":n,...i,ref:t,"data-state":Ad(n),onSelect:z(i.onSelect,()=>r?.(bs(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Cy.displayName=NR;var Ny="MenuRadioGroup",[kR,TR]=lr(Ny,{value:void 0,onValueChange:()=>{}}),ky=H((e,t)=>{const{value:n,onValueChange:r,...i}=e,o=st(r);return a(kR,{scope:e.__scopeMenu,value:n,onValueChange:o,children:a(Ed,{...i,ref:t})})});ky.displayName=Ny;var Ty="MenuRadioItem",Iy=H((e,t)=>{const{value:n,...r}=e,i=TR(Ty,e.__scopeMenu),o=n===i.value;return a(Ey,{scope:e.__scopeMenu,checked:o,children:a(ys,{role:"menuitemradio","aria-checked":o,...r,ref:t,"data-state":Ad(o),onSelect:z(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});Iy.displayName=Ty;var xd="MenuItemIndicator",[Ey,IR]=lr(xd,{checked:!1}),xy=H((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,o=IR(xd,n);return a(et,{present:r||bs(o.checked)||o.checked===!0,children:a(se.span,{...i,ref:t,"data-state":Ad(o.checked)})})});xy.displayName=xd;var ER="MenuSeparator",Py=H((e,t)=>{const{__scopeMenu:n,...r}=e;return a(se.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Py.displayName=ER;var xR="MenuArrow",Ay=H((e,t)=>{const{__scopeMenu:n,...r}=e,i=lo(n);return a(Ba,{...i,...r,ref:t})});Ay.displayName=xR;var Pd="MenuSub",[PR,Ry]=lr(Pd),AR=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:i}=e,o=Pn(Pd,t),s=lo(t),[c,l]=D(null),[d,u]=D(null),p=st(i);return K(()=>(o.open===!1&&p(!1),()=>p(!1)),[o.open,p]),a(qi,{...s,children:a(hy,{scope:t,open:r,onOpenChange:p,content:d,onContentChange:u,children:a(PR,{scope:t,contentId:at(),triggerId:at(),trigger:c,onTriggerChange:l,children:n})})})};AR.displayName=Pd;var po="MenuSubTrigger",Dy=H((e,t)=>{const n=Pn(po,e.__scopeMenu),r=uo(po,e.__scopeMenu),i=Ry(po,e.__scopeMenu),o=Td(po,e.__scopeMenu),s=U(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:l}=o,d={__scopeMenu:e.__scopeMenu},u=ie(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return K(()=>u,[u]),K(()=>{const p=c.current;return()=>{window.clearTimeout(p),l(null)}},[c,l]),a(Nd,{asChild:!0,...d,children:a(Sy,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":My(n.open),...e,ref:Jo(t,i.onTriggerChange),onClick:p=>{e.onClick?.(p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:z(e.onPointerMove,fo(p=>{o.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(o.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:z(e.onPointerLeave,fo(p=>{u();const f=n.content?.getBoundingClientRect();if(f){const m=n.content?.dataset.side,v=m==="right",h=v?-5:5,g=f[v?"left":"right"],_=f[v?"right":"left"];o.onPointerGraceIntentChange({area:[{x:p.clientX+h,y:p.clientY},{x:g,y:f.top},{x:_,y:f.top},{x:_,y:f.bottom},{x:g,y:f.bottom}],side:m}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(p),p.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:z(e.onKeyDown,p=>{const f=o.searchRef.current!=="";e.disabled||f&&p.key===" "||uR[r.dir].includes(p.key)&&(n.onOpenChange(!0),n.content?.focus(),p.preventDefault())})})})});Dy.displayName=po;var Ly="MenuSubContent",$y=H((e,t)=>{const n=gy(Nt,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,o=Pn(Nt,e.__scopeMenu),s=uo(Nt,e.__scopeMenu),c=Ry(Ly,e.__scopeMenu),l=U(null),d=_e(t,l);return a(co.Provider,{scope:e.__scopeMenu,children:a(et,{present:r||o.open,children:a(co.Slot,{scope:e.__scopeMenu,children:a(Id,{id:c.contentId,"aria-labelledby":c.triggerId,...i,ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{s.isUsingKeyboardRef.current&&l.current?.focus(),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:z(e.onFocusOutside,u=>{u.target!==c.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:z(e.onEscapeKeyDown,u=>{s.onClose(),u.preventDefault()}),onKeyDown:z(e.onKeyDown,u=>{const p=u.currentTarget.contains(u.target),f=pR[s.dir].includes(u.key);p&&f&&(o.onOpenChange(!1),c.trigger?.focus(),u.preventDefault())})})})})})});$y.displayName=Ly;function My(e){return e?"open":"closed"}function bs(e){return e==="indeterminate"}function Ad(e){return bs(e)?"indeterminate":e?"checked":"unchecked"}function RR(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function DR(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function LR(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=DR(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}function $R(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}function MR(e,t){return t?$R({x:e.clientX,y:e.clientY},t):!1}function fo(e){return t=>t.pointerType==="mouse"?e(t):void 0}var OR=vy,jR=Nd,FR=yy,BR=by,UR=Ed,GR=_y,HR=ys,qR=Cy,KR=ky,VR=Iy,WR=xy,zR=Py,JR=Ay,YR=Dy,XR=$y,_s="DropdownMenu",[QR,Gj]=ot(_s,[fy]),dt=fy(),[ZR,Oy]=QR(_s),jy=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:o,onOpenChange:s,modal:c=!0}=e,l=dt(t),d=U(null),[u,p]=Ct({prop:i,defaultProp:o??!1,onChange:s,caller:_s});return a(ZR,{scope:t,triggerId:at(),triggerRef:d,contentId:at(),open:u,onOpenChange:p,onOpenToggle:ie(()=>p(f=>!f),[p]),modal:c,children:a(OR,{...l,open:u,onOpenChange:p,dir:r,modal:c,children:n})})};jy.displayName=_s;var Fy="DropdownMenuTrigger",By=H((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,o=Oy(Fy,n),s=dt(n);return a(jR,{asChild:!0,...s,children:a(se.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:Jo(t,o.triggerRef),onPointerDown:z(e.onPointerDown,c=>{!r&&c.button===0&&c.ctrlKey===!1&&(o.onOpenToggle(),o.open||c.preventDefault())}),onKeyDown:z(e.onKeyDown,c=>{r||(["Enter"," "].includes(c.key)&&o.onOpenToggle(),c.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(c.key)&&c.preventDefault())})})})});By.displayName=Fy;var e0="DropdownMenuPortal",Uy=e=>{const{__scopeDropdownMenu:t,...n}=e,r=dt(t);return a(FR,{...r,...n})};Uy.displayName=e0;var Gy="DropdownMenuContent",Hy=H((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Oy(Gy,n),o=dt(n),s=U(!1);return a(BR,{id:i.contentId,"aria-labelledby":i.triggerId,...o,...r,ref:t,onCloseAutoFocus:z(e.onCloseAutoFocus,c=>{s.current||i.triggerRef.current?.focus(),s.current=!1,c.preventDefault()}),onInteractOutside:z(e.onInteractOutside,c=>{const l=c.detail.originalEvent,d=l.button===0&&l.ctrlKey===!0,u=l.button===2||d;(!i.modal||u)&&(s.current=!0)}),style:{...e.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)"}})});Hy.displayName=Gy;var t0="DropdownMenuGroup",n0=H((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=dt(n);return a(UR,{...i,...r,ref:t})});n0.displayName=t0;var r0="DropdownMenuLabel",i0=H((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=dt(n);return a(GR,{...i,...r,ref:t})});i0.displayName=r0;var o0="DropdownMenuItem",qy=H((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=dt(n);return a(HR,{...i,...r,ref:t})});qy.displayName=o0;var a0="DropdownMenuCheckboxItem",s0=H((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=dt(n);return a(qR,{...i,...r,ref:t})});s0.displayName=a0;var c0="DropdownMenuRadioGroup",l0=H((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=dt(n);return a(KR,{...i,...r,ref:t})});l0.displayName=c0;var d0="DropdownMenuRadioItem",u0=H((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=dt(n);return a(VR,{...i,...r,ref:t})});u0.displayName=d0;var p0="DropdownMenuItemIndicator",f0=H((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=dt(n);return a(WR,{...i,...r,ref:t})});f0.displayName=p0;var m0="DropdownMenuSeparator",h0=H((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=dt(n);return a(zR,{...i,...r,ref:t})});h0.displayName=m0;var v0="DropdownMenuArrow",g0=H((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=dt(n);return a(JR,{...i,...r,ref:t})});g0.displayName=v0;var y0="DropdownMenuSubTrigger",b0=H((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=dt(n);return a(YR,{...i,...r,ref:t})});b0.displayName=y0;var _0="DropdownMenuSubContent",w0=H((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=dt(n);return a(XR,{...i,...r,ref:t,style:{...e.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)"}})});w0.displayName=_0;var S0=jy,C0=By,N0=Uy,k0=Hy,Ky=qy;function T0({assignProjectDisabled:e,disabled:t,onAssignProject:n,onForget:r,title:i}){return y(S0,null,y(C0,{asChild:!0},y("button",{"aria-label":`Actions for ${i}`,className:"feed-menu-trigger",type:"button"},"⋯")),y(N0,null,y(k0,{align:"end",className:"feed-menu-panel",side:"bottom",sideOffset:4},y(Ky,{className:"feed-menu-item",disabled:e,onSelect:()=>n()},e?"Moving…":"Assign to project…"),y(Ky,{className:"feed-menu-item danger",disabled:t,onSelect:()=>r()},t?"Forgetting…":"Forget memory"))))}function I0({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 Rd({label:e,variant:t=""}){return y(id,{variant:"provenance",tone:t||void 0},e)}function E0({tag:e}){const t=vg(e);return t?y(id,{variant:"tag",title:String(e)},t):null}function x0({item:e,onReplace:t,onRemove:n,onViewRefresh:r,onReload:i}){const o=ns(e?.metadata_json),s=vs(e,o),c=cR(e,o),l=ft(e),d=e.title||"(untitled)",u=s&&o?.request?o.request:d,p=e.created_at||e.created_at_utc,f=Gx(p),m=Xx(e),v=ts(e.files||[]),h=e.project||"",g=eP(e),_=tP(e,o),w=String(e.visibility||o?.visibility||"private").trim(),S=String(e.workspace_kind||o?.workspace_kind||"").trim(),N=String(e.origin_source||o?.origin_source||"").trim(),k=String(e.trust_state||o?.trust_state||"").trim(),E=m.length?` · ${m.map(he=>vg(he)).join(", ")}`:"",R=v.length?` · ${Vx(v)}`:"",j=Number(e.id||0),q=j>0?`ID ${j}`:"",[I,G]=D(b.newItemKeys.has(l)),A=s?sR({...e,metadata_json:o}):null,M=s?null:AP({...e,metadata_json:o}),L=M?RP(M):[],x=M?DP(M):"summary",O=b.itemViewState.get(l),[T,P]=D(M&&O&&L.some(he=>he.id===O)?O:x),B=`${l}:${T}`,[V,le]=D(b.itemExpandState.get(B)===!0),[de,ae]=D(w==="shared"?"shared":"private"),[be,J]=D(!1),[ve,ee]=D(!1),[Te,fe]=D(!1),te=A?oR(A):[];K(()=>{M&&(L.some(he=>he.id===T)||P(x))},[T,x,L,M]),K(()=>{b.itemViewState.set(l,T)},[T,l]),K(()=>{const he=`${l}:${T}`;le(b.itemExpandState.get(he)===!0)},[T,l]),K(()=>{ae(w==="shared"?"shared":"private")},[w]),K(()=>{if(!I)return;const he=window.setTimeout(()=>{b.newItemKeys.delete(l),G(!1)},700);return()=>window.clearTimeout(he)},[I,l]);const Ie=de,ce=Ie==="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.",Ae=[h?`Project ${h}`:"No project",f].filter(Boolean).join(" · "),ue=[S&&S!==w?`Workspace ${S}`:"",N?`From ${N}`:"",_,k&&k!=="trusted"?Zx(k):""].filter(Boolean).join(" · "),Ke=[`${E}${R}`.trim(),ue].filter(Boolean).join(" · "),Q=!!M&&LP(T,M),re=[T==="facts"?"feed-body facts":"feed-body",Q&&!V?$P(T).join(" "):""].filter(Boolean).join(" "),ut=s?te.length?y("div",{className:"feed-body facts"},te):uy(String(e.body_text||""))||y("div",{className:"feed-body"}):M?T==="facts"?aR(M.facts)||y("div",{className:re}):uy(T==="narrative"?M.narrative:M.summary,re)||y("div",{className:re}):y("div",{className:"feed-body"});async function Ue(he){const ht=Ie;ae(he),J(!0);try{const wt=await mw(j,he);wt?.item&&(t(wt.item),r()),ne(he==="shared"?"Memory will now sync as shared context.":"Memory is private again.")}catch(wt){ae(ht),ne(wt instanceof Error?wt.message:"Failed to save visibility.","warning")}finally{J(!1)}}async function Jt(){const he=String(e.project||"").trim(),ht=he,wt=String(u||"this memory").trim(),pi=wt.length>80?`${wt.slice(0,79).trimEnd()}…`:wt,Po=he?`Move "${pi}" from "${he}" 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 "${pi}". Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`;let pn=[];try{pn=(await Lo()).filter(vt=>vt&&vt!==he)}catch{}const _r=await ql({title:"Assign to project",description:Po,initialValue:ht,placeholder:"Pick one or type a new project name",suggestions:pn,confirmLabel:"Move",cancelLabel:"Cancel",validate:vt=>{const jn=vt.trim();return jn?jn===he?"Already assigned to this project.":null:"Enter a project name."}});if(_r==null)return;const On=_r.trim();if(!(!On||On===he)){fe(!0);try{const vt=await hw(j,On),jn=Number(vt.moved_memory_count||1);ne(jn>1?`Moved ${jn} memories from this session to "${vt.project}".`:`Moved to "${vt.project}".`),await i(),r()}catch(vt){ne(vt instanceof Error?vt.message:"Failed to move memory.","warning")}finally{fe(!1)}}}async function dn(){const he=String(u||"this memory").trim();if(await Ht({autoFocusAction:"cancel",title:"Forget this memory?",description:`Forgetting "${he.length>80?`${he.slice(0,79).trimEnd()}…`:he}". 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"})){ee(!0);try{await vw(j),n(j),r(),await i(),ne("Memory forgotten and removed from the active feed.")}catch(ht){ne(ht instanceof Error?ht.message:"Failed to forget memory.","warning")}finally{ee(!1)}}}const mt=c.replace(/_/g," "),un=v.length?y("div",{className:"feed-files"},v.map((he,ht)=>y("span",{className:"feed-file",key:`${String(he)}-${ht}`},String(he)))):null;return y("article",{className:`feed-item ${c}${I?" new-item":""}`.trim(),"data-key":l},y("div",{className:"feed-kind-banner"},y(id,{variant:"kind",tone:c},mt)),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:kk(u,b.feedQuery)}}),y("div",{className:"feed-card-subtitle small"},Ae)),y("div",{className:"feed-actions"},M?y(I0,{active:T,modes:L,onSelect:he=>P(he)}):null,y(ss,{label:Ux(p),side:"left"},y("div",{className:"small feed-age"},f)),e.owned_by_self&&j>0?y(T0,{assignProjectDisabled:Te,disabled:ve,onAssignProject:()=>{Jt()},onForget:()=>{dn()},title:String(u||"memory")}):null)),y("div",{className:"feed-provenance"},y(Rd,{label:g,variant:g==="You"?"mine":"author"}),y(Rd,{label:w||"private",variant:w||"private"}),q?y(ss,{label:`Memory database id ${j}`,side:"top"},y(Rd,{label:q,variant:"memory-id"})):null),y("div",{className:"feed-meta"},Ke||"No tags, files, or provenance details attached."),ut,y("div",{className:"feed-footer"},y("div",{className:"feed-footer-left"},m.length?y("div",{className:"feed-tags"},m.map((he,ht)=>y(E0,{key:`${String(he)}-${ht}`,tag:he}))):null,e.owned_by_self&&j>0?y("div",{className:"feed-visibility-controls"},y("select",{"aria-label":`Visibility for ${String(e.title||"memory")}`,className:"feed-visibility-select",disabled:be,onChange:he=>{Ue(String(he.currentTarget.value)==="shared"?"shared":"private")},value:Ie},y("option",{value:"private"},"Only me"),y("option",{value:"shared"},"Share with peers")),y("div",{className:"feed-visibility-note"},ce)):null),y("div",{className:"feed-footer-right"},Q?y("button",{className:"feed-expand",onClick:()=>{const he=!V;b.itemExpandState.set(B,he),le(he)},type:"button"},V?"Collapse":"Expand"):null)),un))}function P0({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 A0({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(P0,{index:r,key:`skeleton-${r}`})));if(!e.length){const r=!!b.feedQuery.trim()||b.feedTypeFilter!=="all"||b.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(x0,{item:r,key:ft(r),onReplace:n.replaceFeedItem,onRemove:n.removeFeedItem,onViewRefresh:()=>n.updateFeedView(!0),onReload:n.loadFeedData})))}function Vy({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 R0({text:e}){return y("div",{"aria-live":"polite",className:"section-meta",id:"feedMeta",role:"status"},e)}function D0({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 L0({errorText:e,items:t,loadingText:n,ops:r}){const[i,o]=D(!1);return y(Z,null,y("div",{className:"feed-controls"},y(R0,{text:n||MP(t.length,r.hasMorePages())}),y("div",{className:"feed-controls-right"},y(D0,{query:b.feedQuery,onQuery:r.updateFeedQuery}),y(Vy,{active:b.feedScopeFilter,id:"feedScopeToggle",onSelect:s=>{s!==b.feedScopeFilter&&(Xm(s),r.loadFeedData().catch(()=>{}))},options:[{value:"all",label:"All"},{value:"mine",label:"My memories"},{value:"theirs",label:"Other people"}]}),y(Vy,{active:b.feedTypeFilter,id:"feedTypeToggle",onSelect:s=>{s!==b.feedTypeFilter&&(jk(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(OP,{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(A0,{items:t,loadingText:n,ops:r}):null)))}function $0(e){return b.feedTypeFilter==="observations"?e.filter(t=>!vs(t,ns(t?.metadata_json))):b.feedTypeFilter==="summaries"?e.filter(t=>vs(t,ns(t?.metadata_json))):e}function M0(e){const t=e.map(n=>`${bg(n)}:${n.kind||""}:${n.created_at_utc||n.created_at||""}`);return`${b.feedTypeFilter}|${b.feedScopeFilter}|${b.currentProject}|${Xi(b.feedQuery)}|${t.join("|")}`}var Wy="",mo=0,ho=0,Zr=!0,ei=!0,ws=null,O0=0,kt=null,zy=!1,ti=0,Dd="all",Jy="",vo=null,ni="",Hj=250;function Yy(e){Wy=e,Dd=b.feedScopeFilter,Jy=b.feedQuery.trim(),ni="",ti+=1,mo=0,ho=0,Zr=!0,ei=!0,b.lastFeedItems=[],b.pendingFeedItems=null,b.lastFeedFilteredCount=0,b.lastFeedSignature="",b.newItemKeys.clear(),b.itemViewState.clear(),b.itemExpandState.clear()}function Ld(){return Zr||ei}function j0(e){const t=ft(e);b.lastFeedItems=b.lastFeedItems.map(n=>ft(n)===t?e:n)}function F0(e){const t=new Set,n=r=>{const i=Number(r.id||r.memory_id||0)!==e;return i||t.add(ft(r)),i};b.lastFeedItems=b.lastFeedItems.filter(n),Array.isArray(b.pendingFeedItems)&&(b.pendingFeedItems=b.pendingFeedItems.filter(n));for(const r of t){b.newItemKeys.delete(r),b.itemViewState.delete(r);for(const i of Array.from(b.itemExpandState.keys()))i.startsWith(`${r}:`)&&b.itemExpandState.delete(i)}}async function B0(){if(!Ld())return;const e=ti;if(ws===e)return;const t=b.currentProject||"",n=b.feedQuery.trim(),r=mo,i=ho;ws=e;try{const[o,s]=await Promise.all([Zr?Zu(t,{limit:20,offset:r,scope:b.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:r}}),ei?ep(t,{limit:50,offset:i,scope:b.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:i}})]);if(e!==ti||t!==(b.currentProject||"")||n!==b.feedQuery.trim())return;const c=s.items||[],l=o.items||[],d=n?l:l.filter(p=>!yg(p));b.lastFeedFilteredCount+=l.length-d.length,ei=rs(s,c.length,50),Zr=rs(o,l.length,20),ho=is(s,i+c.length),mo=is(o,r+l.length);const u=[...c,...d];b.lastFeedItems=_g(b.lastFeedItems,u),dr()}finally{ws===e&&(ws=null)}}function Xy(){b.activeTab==="feed"&&(vo||kt||Ld()&&rP()&&B0())}var U0={replaceFeedItem:j0,removeFeedItem:F0,updateFeedView:e=>dr(e),loadFeedData:()=>Od(),updateFeedQuery:e=>H0(e),hasMorePages:Ld};function $d(e,t){const n=document.getElementById("tab-feed");if(!n)return!1;EP(n,y(L0,{errorText:t?.errorText,items:e,loadingText:t?.loadingText,ops:U0}));const r=globalThis.lucide;return r&&!t?.loadingText&&r.createIcons(),!0}function Md(e="Loading selected project..."){$d([],{loadingText:e})}function G0(){IP(),$d(b.lastFeedItems,b.lastFeedItems.length||b.lastFeedSignature?void 0:{loadingText:"Loading memories…"}),zy||(window.addEventListener("scroll",()=>{Xy()},{passive:!0}),zy=!0)}function H0(e){if(e===b.feedQuery)return;const t=b.feedQuery.trim();b.feedQuery=e,e.trim()!==t&&(Yy(b.currentProject||""),Md("Searching memories…"),vo&&clearTimeout(vo),vo=setTimeout(()=>{vo=null,Od().catch(()=>{})},250))}function dr(e=!1){if(!document.getElementById("tab-feed"))return;const t=window.scrollY,n=$0(b.lastFeedItems),r=M0(n),i=e||r!==b.lastFeedSignature;b.lastFeedSignature=r,i&&$d(n,{errorText:ni||void 0}),window.scrollTo({top:t}),Xy()}async function Od(){const e=b.currentProject||"",t=b.feedScopeFilter!==Dd,n=b.feedQuery.trim(),r=n!==Jy;(e!==Wy||t||r)&&(Yy(e),Md(r?"Searching memories…":void 0));const i=ti,o=++O0;kt={generation:i,requestId:o};const s=!!ni;s&&(ni="",b.lastFeedItems.length>0?dr(!0):Md(n?"Searching memories…":void 0));try{const[d,u]=await Promise.all([Zu(e,{limit:20,offset:0,scope:b.feedScopeFilter,q:n||void 0}),ep(e,{limit:50,offset:0,scope:b.feedScopeFilter,q:n||void 0})]);if(kt?.generation!==i||kt.requestId!==o||i!==ti||e!==(b.currentProject||"")||n!==b.feedQuery.trim())return;const p=u.items||[],f=d.items||[],m=n?f:f.filter(w=>!yg(w)),v=f.length-m.length,h=[...p,...m].sort((w,S)=>new Date(S.created_at||0).getTime()-new Date(w.created_at||0).getTime()),g=nP(b.lastFeedItems,h),_=b.lastFeedItems;if(iP(g,_)&&_.length>0){const w=new Set(_.map(ft));g.forEach(S=>{w.has(ft(S))||b.newItemKeys.add(ft(S))})}b.pendingFeedItems=null,b.lastFeedItems=g,ni="",b.lastFeedFilteredCount=Math.max(b.lastFeedFilteredCount,v),ei=rs(u,p.length,50),Zr=rs(d,f.length,20),ho=Math.max(ho,is(u,p.length)),mo=Math.max(mo,is(d,f.length)),Dd=b.feedScopeFilter,kt?.generation===i&&kt.requestId===o&&(kt=null),dr(s)}catch(c){throw kt?.generation===i&&kt.requestId===o&&i===ti&&e===(b.currentProject||"")&&n===b.feedQuery.trim()&&(Zr=!1,ei=!1,ni="Feed unavailable. Refresh and try again.",dr(!0)),c}finally{kt?.generation===i&&kt.requestId===o&&(kt=null)}}var q0=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function Qy(e){return!!q0.exec(e)?.slice(1,4).map(Number).every(Number.isSafeInteger)}function qj(e){return e}function K0(e){return e.latest_version?e.stale?{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"}:e.update_available?{title:`Codemem ${e.latest_version} is available`,detail:`Installed version: ${e.current_version}.`,tone:"available"}:Qy(e.current_version)?{title:`Codemem ${e.current_version} is up to date`,detail:"You are running the latest stable release.",tone:"current"}:{title:`Unable to compare Codemem ${e.current_version} with ${e.latest_version}`,detail:"The installed version is not a stable semantic version.",tone:"unavailable"}:{title:"Update check unavailable",detail:e.error?`Could not check for updates: ${e.error}`:"Could not check for updates.",tone:"unavailable"}}function V0({status:e}){const t=K0(e),n=e.update_available||e.stale||!e.latest_version||!Qy(e.current_version);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 W0(e,t){e&&(e.hidden=!t,Be(t?y(V0,{status:t}):null,e))}function z0({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(ss,{label:o},s):s}function J0({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()}catch{}t.disabled=!1,t.textContent=r}}function o(){!e.command||!n||Oi(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 Y0(e){return typeof e=="number"?e.toLocaleString():e==null?"n/a":String(e)}function X0({label:e,value:t,icon:n,tooltip:r}){const i=y("div",{class:"stat",style:r?"cursor: help;":void 0},y("i",{"data-lucide":n,class:"stat-icon"}),y("div",{class:"stat-content"},y("div",{class:"value"},Y0(t)),y("div",{class:"label"},e)));return r?y(ss,{label:r},i):i}function Zy(e,t){e&&Be(y(nd,null,t.map(n=>y(X0,{...n,key:`${n.label}-${n.icon}`}))),e)}function eb(e,t){e&&Be(y(Z,null,t),e)}function jd(){const e=globalThis.lucide;e&&typeof e.createIcons=="function"&&e.createIcons()}function Q0(e,t){e&&Be(y(nd,null,t.map(n=>y(z0,{...n,key:n.key??n.label}))),e)}function Z0(e,t){if(e){if(!t.length){e.hidden=!0,Be(null,e);return}e.hidden=!1,Be(y(Z,null,t.slice(0,3).map((n,r)=>y(J0,{item:n,key:`${n.label}-${r}`}))),e)}}var tb="scope_id_backfill";function nb(){const e=document.getElementById("healthGrid"),t=document.getElementById("healthMeta"),n=document.getElementById("healthActions"),r=document.getElementById("healthDot");if(!e||!t)return;W0(document.getElementById("healthUpdateBanner"),b.lastUpdateStatus);const i=b.lastStatsPayload||{},o=b.lastUsagePayload||{},s=b.lastRawEventsPayload&&typeof b.lastRawEventsPayload=="object"?b.lastRawEventsPayload:{},c=b.lastSyncStatus||{},l=Array.isArray(i.maintenance_jobs)?i.maintenance_jobs:[],d=l.find(ue=>ue.kind===tb),u=i.reliability||{},p=u.counts||{},f=u.rates||{},m=i.database||{},v=o.totals_filtered||o.totals||o.totals_global||i.usage?.totals||{},h=Array.isArray(o.recent_packs)?o.recent_packs:[],g=h.length?h[0]?.created_at:null,_=h.length?h[0]?.metadata_json||{}:{},w=Number(_?.exact_duplicates_collapsed||0),S=Number(s.pending||0),N=Number(p.errored_batches||0),k=Number(f.flush_success_rate??1),E=Number(f.dropped_event_rate||0),R=Xl(v.tokens_saved,v.tokens_read),j=qx(R),q=Number(m.tags_coverage||0),I=String(c.daemon_state||"unknown"),G=I==="offline-peers"?"Offline peers":I==="needs_attention"?"Needs attention":I==="rebootstrapping"?"Rebootstrapping":hg(I),A=Array.isArray(b.lastSyncPeers)?b.lastSyncPeers.length:0,M=I==="disabled"||c.enabled===!1,L=I==="offline-peers",x=!M&&A===0;let O=M?"Disabled":x?"No peers":G;const T=Wr(c.last_sync_at||c.last_sync_at_utc||null),P=Wr(g),B=T!==null&&T>7200,V=T!==null&&T<=300,le=S>=200;let de=0;const ae=[];S>=1e3?(de+=40,ae.push("high raw-event backlog")):S>=200&&(de+=24,ae.push("growing raw-event backlog")),N>0&&S>=200&&(de+=N>=5?10:6,ae.push("batch errors during backlog pressure")),k<.95&&(de+=20,ae.push("lower flush success")),E>.02?(de+=24,ae.push("high dropped-event rate")):E>.005&&(de+=10,ae.push("non-trivial dropped-event rate")),!M&&!x&&(I==="error"?(de+=36,ae.push("sync daemon reports errors")):I==="needs_attention"?(de+=40,ae.push("sync needs manual attention")):I==="stopped"?(de+=22,ae.push("sync daemon stopped")):I==="degraded"&&!V&&(de+=20,ae.push("sync daemon degraded")),L?(de+=4,ae.push("all peers currently offline"),B&&(de+=4,ae.push("offline peers and sync not recent"))):B?(de+=26,ae.push("sync looks stale")):T!==null&&T>1800&&(de+=12,ae.push("sync not recent"))),j!==null&&j<10&&(de+=8,ae.push("low retrieval reduction")),P!==null&&P>86400&&(de+=12,ae.push("memory pack activity is old"));let be="Healthy",J="status-healthy";de>=60?(be="Attention",J="status-attention"):de>=25&&(be="Degraded",J="status-degraded");const ve=J==="status-healthy";r&&(r.className=`health-dot ${J}`,r.title=be);const ee=`${Number(v.tokens_saved||0).toLocaleString()} saved tokens · ${w.toLocaleString()} deduped in latest pack`,Te=S>0?"Queue is actively draining":"Queue is clear",fe=M?"Sync disabled":x?"No peers configured":L?`${A} peers offline · last sync ${Tn(T)} ago`:`${A} peers · last sync ${Tn(T)} ago`;ve&&!M&&!x&&(L?O="Peers offline":I==="degraded"&&V&&(O="Syncing"));const te=`last pack ${Tn(P)} ago`,Ie=l.map(ue=>{const Ke=Number(ue.progress?.current||0),Q=typeof ue.progress?.total=="number"?ue.progress.total:null,re=String(ue.progress?.unit||"items"),ut=Q&&Q>0?` (${Math.round(100*Ke/Q)}%)`:"",Ue=Q&&Q>0?`${Ke.toLocaleString()}/${Q.toLocaleString()} ${re}${ut}`:`${Ke.toLocaleString()} ${re}`,Jt=ue.status==="failed",dn=ue.status==="completed",mt=ue.kind===tb,un=Jt?"Failed":dn?"Complete":Ue,he=Jt?String(ue.error||"unknown error").trim():dn?mt?`${Ue} · one-time Sharing-domain upgrade finished`:Ue:mt?"One-time upgrade backfill; totals include memories and replication ops":void 0;return{key:String(ue.kind||ue.title||"background-maintenance"),label:String(ue.title||ue.kind||"Background maintenance"),value:un,detail:he,icon:Jt?"alert-triangle":dn?"check-circle":"loader",className:Jt?"status-attention":void 0,title:Jt?`Error: ${ue.error||"unknown"}`:dn?`${String(ue.title||"Maintenance")} finished`:mt?`${String(ue.title||"Maintenance")} in progress; inspect with codemem maintenance status`:`${String(ue.title||"Maintenance")} in progress`}});Q0(e,[{key:"overall-health",label:"Overall health",value:be,detail:`Weighted score ${de}`,icon:"heart-pulse",className:`health-primary ${J}`,title:ae.length?`Main signals: ${ae.join(", ")}`:"No major risk signals detected"},...Ie,{key:"pipeline-health",label:"Pipeline health",value:`${S.toLocaleString()} pending`,detail:Te,icon:"workflow",title:"Raw-event queue pressure and flush reliability"},{key:"retrieval-impact",label:"Retrieval impact",value:R,detail:ee,icon:"sparkles",title:"Reduction from memory reuse across recent usage"},{key:"sync-health",label:"Sync health",value:O,detail:fe,icon:"refresh-cw",title:"Daemon state and sync recency"},{key:"data-freshness",label:"Data freshness",value:Tn(P),detail:te,icon:"clock-3",title:"Recency of last memory pack activity"}]);const ce=async()=>{await tc()},Ae=[];le?(Ae.push({label:"Pipeline needs attention. Check queue health first.",command:"codemem db raw-events-status"}),Ae.push({label:"Then retry failed batches for impacted sessions.",command:"codemem db raw-events-retry <opencode_session_id>"})):I==="stopped"?Ae.push({label:"Sync daemon is stopped. Start the background service.",command:"codemem serve start"}):!M&&!x&&!ve&&(I==="error"||I==="degraded")?(Ae.push({label:"Sync is unhealthy. Restart and run one immediate pass.",command:"codemem serve restart",action:ce,actionLabel:"Sync now"}),Ae.push({label:"Then run doctor to see root cause details.",command:"codemem sync doctor"})):!M&&!x&&B&&Ae.push({label:"Sync is stale. Run one immediate sync pass.",command:"codemem sync once",action:ce,actionLabel:"Sync now"}),q>0&&q<.7&&Ae.length<2&&Ae.push({label:"Tag coverage is low. Preview backfill impact.",command:"codemem db backfill-tags --dry-run"}),d&&d.status!=="completed"&&Ae.length<3&&Ae.push({label:"Sharing-domain upgrade backfill is expected one-time work. Inspect progress if startup feels busy.",command:"codemem maintenance status"}),Z0(n,Ae),t.textContent=ae.length?`Why this status: ${ae.join(", ")}.`:"Healthy right now. Diagnostics stay available if you want details.",jd()}function eD(){const e=document.getElementById("sessionGrid"),t=document.getElementById("sessionMeta");if(!e||!t)return;const n=b.lastUsagePayload||{},r=b.currentProject;n?.totals_global||n?.totals;const i=n?.totals_filtered||null,o=!!(r&&i),s=(Array.isArray(n?.events)?n.events:[]).find(k=>k.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),h=!!d?.exact_dedupe_enabled,g=Xl(m,f),_=p?`${p} packs`:"No packs yet",w=u?`Last pack: ${ir(u)}`:"",S=o?"Project":"All projects",N=[{label:"Last pack savings",value:l?`${Yi(m)} (${g})`:"n/a",tooltip:l?`Exact: ${m.toLocaleString()} saved`:void 0,icon:"trending-up"},{label:"Last pack size",value:l?Yi(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?h?"On":"Off":"n/a",icon:"shield-check"},{label:"Packs",value:p||0,icon:"archive"}];eb(t,[S,_,w].filter(Boolean).join(" · ")),Zy(e,N),jd()}function tD(){const e=document.getElementById("statsGrid"),t=document.getElementById("metaLine");if(!e)return;const n=b.lastStatsPayload||{},r=b.lastUsagePayload||{},i=b.lastRawEventsPayload&&typeof b.lastRawEventsPayload=="object"?b.lastRawEventsPayload:{},o=n.database||{},s=b.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?`
112
+ Global: ${Number(c.work_investment_tokens||0).toLocaleString()} invested`:"",v=d?`
113
113
  Global: ${Number(c.tokens_read||0).toLocaleString()} read`:"",h=d?`
114
- Global: ${Number(c.tokens_saved||0).toLocaleString()} saved`:"",g=[{label:d?"Savings (project)":"Savings",value:Fi(u.tokens_saved||0),tooltip:`Tokens saved by reusing compressed memories. Exact: ${Number(u.tokens_saved||0).toLocaleString()} saved${h}`,icon:"trending-up"},{label:d?"Injected (project)":"Injected",value:Fi(u.tokens_read||0),tooltip:`Tokens injected into context (pack size). Exact: ${Number(u.tokens_read||0).toLocaleString()} injected${y}`,icon:"book-open"},{label:d?"Reduction (project)":"Reduction",value:Ml(u.tokens_saved,u.tokens_read),tooltip:`Percent reduction from reuse. Factor: ${lA(u.tokens_saved,u.tokens_read)}.`+y+h,icon:"percent"},{label:d?"Work investment (project)":"Work investment",value:Fi(u.work_investment_tokens||0),tooltip:`Token cost of unique discovery groups. Exact: ${Number(u.work_investment_tokens||0).toLocaleString()} invested${f}`,icon:"pencil"},{label:"Active memories",value:o.active_memory_items||0,icon:"check-circle"},{label:"Embedding coverage",value:Fg(o.vector_coverage),tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:Fg(o.tags_coverage),tooltip:"Share of active memories with tags",icon:"tag"}];if(m>0?g.push({label:"Raw events pending",value:m,tooltip:"Pending raw events waiting to be flushed",icon:"activity"}):p>0&&g.push({label:"Raw sessions",value:p,tooltip:"Sessions with pending raw events",icon:"inbox"}),Sy(e,g),t){const _=s?` · project: ${s}`:"";Cy(t,`DB: ${mA(o.path||"unknown")} · ${fA(o.size_bytes||0)}${_}`)}Sd()}async function b0(){const e=b.lastStatsPayload?.identity?.actor_id||null,t=b.activeTab==="health"&&!b.lastUpdateStatus?ww().catch(Sw):Promise.resolve(b.lastUpdateStatus),[n,r,i,o,s]=await Promise.all([K_(),V_(b.currentProject),W_(b.currentProject),q_(b.currentProject),t]);b.lastStatsPayload=n||{},b.lastUsagePayload=r||{},b.lastRawEventsPayload=o||{},b.lastUpdateStatus=s;const c=b.lastStatsPayload?.identity?.actor_id||null;y0(),v0(),ky(),b.activeTab==="feed"&&e!==c&&ao(!0)}var so=new WeakMap;function lr(e,t=""){const n=document.createElement("p");return t&&(n.className=t),n.textContent=e,n}function _0(e){const t=document.createElement("article");t.className="project-inventory-row recipient-policy-blocked-item";const n=document.createElement("div");n.className="project-inventory-row-header";const r=document.createElement("h3");r.className="project-inventory-title",r.textContent=e.finding;const i=document.createElement("span");return i.className="project-status-badge needs_attention",i.textContent="Blocked",n.append(r,i),t.append(n,lr(e.reason,"project-inventory-meta"),lr(`Owner: ${e.ownerLabel}`,"settings-note"),lr(`Repair: ${e.repairAction}`,"settings-note")),t}function w0(e,t){const n=`review:${JSON.stringify(t)}`;if(so.get(e)===n)return;if(!t.continuity&&t.blockedItems.length===0){e.replaceChildren(),e.hidden=!0,so.set(e,n);return}e.hidden=!1;const r=document.createElement("section");r.className="card recipient-policy-review",r.setAttribute("aria-labelledby","recipientPolicyReviewTitle");const i=document.createElement("h2");if(i.id="recipientPolicyReviewTitle",i.textContent=t.blockedItems.length>0?"Sharing needs repair":"Existing sharing kept as-is",r.appendChild(i),t.continuity){const o=t.continuity.findingCount,s=lr(`${o.toLocaleString()} older sharing finding${o===1?" was":"s were"} not changed because Codemem could not safely translate ${o===1?"it":"them"} automatically.`,"settings-note");s.setAttribute("role","status"),s.setAttribute("aria-live","polite"),t.blockedItems.length===0&&r.appendChild(lr("No action is required for this update. Codemem did not change your existing Team or local sharing configuration.","section-meta")),r.appendChild(s)}if(t.blockedItems.length>0){const o=lr("Codemem did not change access for these items, but their current availability cannot be confirmed until these source-state problems are repaired.","section-meta project-attention-note"),s=document.createElement("h3");s.className="recipient-policy-blocked-heading",s.textContent="Needs repair";const c=document.createElement("div");c.className="project-inventory-list recipient-policy-review-list";for(const l of t.blockedItems)c.appendChild(_0(l));r.append(o,s,c)}e.replaceChildren(r),so.set(e,n)}function S0(e,t){const n=t instanceof Error?t.message:"Unable to load recipient migration review.",r=`error:${n}`;if(so.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=lr(n,"settings-note project-attention-note");s.setAttribute("role","status"),i.append(o,s),e.replaceChildren(i),so.set(e,r)}var Ny=[["","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"]],at=null,co=0,Cd=250,Td=[],kd=new Set,Nd=new Set,cs=new Map,ls=new Map,dr=new Map,lo=new Map,ds=!1,uo=!1,En=!1,us=0,Ct=new Set,xy=new WeakMap,ps={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Yr=ps,In=!1;function Ke(e){return document.getElementById(e)}function C0(e){return Ny.find(([t])=>t===e)?.[1]??e.replaceAll("_"," ")}function T0(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 Xr(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function xd(e){return e.identity_source!=="unmapped"&&!Xr(e)}function Pd(e){return Xr(e)?"Received from peers":ms(e.resolved_scope_id)}function k0(e){return Xr(e)?"source-owned project":T0(e.resolution_reason)}function N0(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 Py(e){if(!e)return"No recent sessions";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function Ay(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function ur(){const e=Ct.size,t=Ke("projectsShareSelected");t&&(t.textContent=e===0?"Share selected":`Share selected (${e})`,t.disabled=e===0||!En||!In,t.classList.add("project-selection-target"));const n=Ke("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=xy.get(r)??[],o=i.filter(s=>Ct.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=!En||!In}function x0(e){const t=e.every(n=>Ct.has(n));for(const n of e)t?Ct.delete(n):Ct.add(n);ur()}function Ey(e,t){const n=Ay(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),xy.set(i,n),i.addEventListener("change",()=>x0(n));const o=document.createElement("span");return o.className="sr-only",o.textContent=t,r.append(i,o),r}function P0(e){if(!In)return[];const t=new Set(e),n=new Map(Yr.teams.filter(o=>o.status==="active").map(o=>[o.teamId,o.displayName])),r=new Map(Yr.identities.filter(o=>o.status==="active"||o.status==="pending").map(o=>[o.identityId,o.displayName])),i=new Map;for(const o of Yr.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 Iy(e){const t=document.createElement("div");t.className="project-recipient-summary";const n=P0(e),r=document.createElement("div");if(r.className="project-recipient-status",r.textContent=In?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 Ry(e,t){const n=document.createElement("button");return n.className="settings-button project-recipient-action project-selection-target",n.type="button",n.disabled=!En||!In,e.length===1?(n.textContent="Manage recipients",n.setAttribute("aria-label",`Manage recipients for ${t}`),n.dataset.projectFocusKey=`manage:${e[0]}`,n.addEventListener("click",()=>{wi({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)Ct.add(r);ur(),wi({mode:"project-add",projectIds:[...e].sort()})})),n}function A0(e){return e.git_remote?e.git_remote:e.cwd?e.cwd:e.workspace_identity}function Ad(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function Ed(e){return e.project||e.display_project||"Unnamed Project"}function Dy(e){const t=String(e||"").trim();return t?b.lastCoordinatorAdminGroups.find(n=>String(n.group_id||"").trim()===t&&!n.archived_at)?.display_name||"Team details unavailable":null}function E0(){return new Set(b.lastCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function I0(e){return!uo||e.authority_type!=="coordinator"||!e.group_id?!1:!E0().has(String(e.group_id).trim())}function Ly(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function $y(){ds&&(ds=!1,at?.())}async function R0(){try{const e=await To();b.lastCoordinatorAdminStatus=e&&typeof e=="object"?e:null}catch{b.lastCoordinatorAdminStatus=null,b.lastCoordinatorAdminGroups=[],uo=!1;return}if(b.lastCoordinatorAdminStatus?.readiness!=="ready"||!b.lastCoordinatorAdminStatus.has_admin_secret){b.lastCoordinatorAdminGroups=[],uo=!1;return}try{const e=await Au(!1);b.lastCoordinatorAdminGroups=Array.isArray(e?.items)?e.items:[],uo=!0}catch{b.lastCoordinatorAdminGroups=[],uo=!1}}function D0(e){return e.kind==="team_default"}function Id(e){const t=e.label||"Untitled Space";return D0(e)?`${t} (default)`:t}function L0(e,t){const n=Id(e);return t.some(r=>r.scope_id!==e.scope_id&&Id(r)===n)?`${n} · Space ID ${e.scope_id}`:n}function $0(e){const t=Dy(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 M0(e){return e?Td.find(t=>t.scope_id===e)??null:null}function ms(e){const t=M0(e);return e?t?`${Id(t)} · ${$0(t)}`:"Unknown Space":"—"}function Rd(){return Td.filter(e=>e.scope_id!=="legacy-shared-review"&&!I0(e))}function O0(e){return Rd().some(t=>t.scope_id===e)}function My(...e){for(const t of e)if(t&&O0(t))return t;return e.find(t=>!!t)??""}function j0(e){const t=Dy(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function F0(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function B0(){const e=new Map;for(const t of Rd()){const n=F0(t),r=j0(t),i=e.get(n)??{label:r,scopes:[]};e.set(n,{label:i.label,scopes:[...i.scopes,t]})}return[...e.values()]}function Oy(e){for(const t of B0()){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=L0(r,t.scopes),n.appendChild(i)}e.appendChild(n)}}function U0(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 Dd(e,t,n=[]){try{await lw({...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}),dr.delete(e.workspace_identity),cs.delete(e.workspace_identity),ne("Project Space assignment updated. Device access grants are unchanged."),at?.()}catch(r){if(r instanceof No){dr.set(e.workspace_identity,{requiredGuardrailTokens:r.requiredGuardrailTokens,scopeId:t,warnings:r.guardrailWarnings}),at?.();return}ne(r instanceof Error?r.message:"Unable to update project Space.","warning")}}async function G0(e,t){const n=e.filter(xd);if(n.length!==0)try{await dw({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}))}),ne(`Updated ${n.length} project identit${n.length===1?"y":"ies"}. Device access grants are unchanged.`),ls.delete(Ad(n[0])),at?.()}catch(r){ne(r instanceof No?"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 H0(e){if(e.mapping_id!=null)try{await uw(e.mapping_id),dr.delete(e.workspace_identity),cs.delete(e.workspace_identity),ne("Project Space assignment removed. The next fallback now applies."),at?.()}catch(t){ne(t instanceof Error?t.message:"Unable to remove project Space assignment.","warning")}}async function jy(e,t=!1){try{const n=lo.get(e.workspace_identity),r=await mw({...t&&n?{confirmation_token:n.confirmationToken}:{},confirmed:t,workspace_identity:e.workspace_identity});lo.delete(e.workspace_identity),ne(`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.`),at?.()}catch(n){if(n instanceof Ou){lo.set(e.workspace_identity,{confirmationToken:n.preview.confirmation_token,localOwnedMemoryCount:n.preview.local_owned_memory_count,peerOwnedMemoryCount:n.preview.peer_owned_memory_count}),at?.();return}ne(n instanceof Error?n.message:"Unable to forget project memories.","warning")}}async function K0(e){if(e.identity_source==="unmapped")return;const t=String(e.project||e.display_project||"").trim();let n=[];try{n=(await ko()).filter(i=>i&&i!==t)}catch{}const r=await El({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 pw({project:r.trim(),workspace_identity:e.workspace_identity});ne(`Changed project to ${i.project} for ${i.moved_session_count} session${i.moved_session_count===1?"":"s"}.`),at?.()}catch(i){ne(i instanceof Error?i.message:"Unable to change project.","warning")}}function V0(e){const t=document.createElement("div");if(t.className="project-inventory-actions",xd(e)&&e.memory_count!=null&&e.guardrail_warnings.every(f=>!f.requires_confirmation)){const f=document.createElement("button");f.className="settings-button",f.type="button",f.textContent="Share",f.disabled=!En,En||(f.title="The complete project list is unavailable."),f.addEventListener("click",()=>ea([e.workspace_identity])),t.appendChild(f)}if(Xr(e)){const f=document.createElement("div");return f.className="settings-note",f.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(f),t}if(e.identity_source==="unmapped"){const f=document.createElement("div");return f.className="settings-note",f.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(f),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=Rd().some(f=>f.scope_id===e.resolved_scope_id);if(!o&&e.resolved_scope_id){const f=document.createElement("option");f.value=e.resolved_scope_id,f.textContent=`${ms(e.resolved_scope_id)} — not assignable`,f.disabled=!0,i.appendChild(f)}Oy(i),i.value=My(cs.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",()=>{Dd(e,i.value)}),i.addEventListener("change",()=>{cs.set(e.workspace_identity,i.value),dr.delete(e.workspace_identity),t.querySelector(".project-space-guardrail-confirmation")?.remove(),s.textContent="Save Space",s.disabled=!i.value,at?.()}),i.addEventListener("blur",$y);const c=document.createElement("button");c.className="settings-button",c.type="button",c.textContent="Keep local-only",c.addEventListener("click",()=>{Dd(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",()=>{H0(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",()=>{K0(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",()=>{jy(e)}),t.append(n,i,s,c,l,d,u);const p=dr.get(e.workspace_identity);if(p){const f=document.createElement("div");f.className="settings-note project-guardrail-confirmation project-space-guardrail-confirmation",f.setAttribute("role","alert");const y=document.createElement("strong");y.textContent="Confirmation required before saving this Space.";const h=document.createElement("p");h.textContent="Codemem can save this change after you acknowledge the checks below. Verify the workspace details, then confirm to complete the save.";const g=document.createElement("ul");for(const S of p.warnings){const T=document.createElement("li"),k=document.createElement("strong");k.textContent=`${U0(S)}: `;const P=document.createElement("span");P.textContent=S.message,T.append(k,P),g.appendChild(T)}const _=document.createElement("button");_.className="settings-button",_.type="button",_.textContent="I understand, save Space",_.addEventListener("click",()=>{const S=dr.get(e.workspace_identity);!S||S.scopeId!==i.value||Dd(e,S.scopeId,S.requiredGuardrailTokens)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{dr.delete(e.workspace_identity),at?.()}),f.append(y,h,g,_,w),t.appendChild(f)}const m=lo.get(e.workspace_identity);if(m){const f=document.createElement("div");f.className="settings-note project-guardrail-confirmation",f.setAttribute("role","alert");const y=document.createElement("strong");y.textContent="Confirm project memory cleanup.";const h=document.createElement("p");h.textContent=`${m.localOwnedMemoryCount.toLocaleString()} locally owned memor${m.localOwnedMemoryCount===1?"y":"ies"} will be forgotten. ${m.peerOwnedMemoryCount.toLocaleString()} peer-owned memor${m.peerOwnedMemoryCount===1?"y":"ies"} will be left unchanged.`;const g=document.createElement("p");g.textContent="Use this only to clean up wrongly attributed local project inventory; it forgets actual local memories on this device.";const _=document.createElement("button");_.className="settings-button danger",_.type="button",_.textContent="I understand, forget local memories",_.addEventListener("click",()=>{jy(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),at?.()}),f.append(y,h,g,_,w),t.appendChild(f)}return t}function Fy(e){const t=document.createElement("article");t.className="project-inventory-row";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",Zo(e)&&r.appendChild(Ey([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),Zo(e)&&r.appendChild(Ry([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 · ${Py(e.latest_session_at)}`,t.appendChild(o),t.appendChild(Iy([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=Pd(e),s.appendChild(c);const l=document.createElement("div");if(l.className="project-inventory-meta",l.textContent=`${k0(e)} · ${e.identity_source} · ${Py(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 g=document.createElement("strong");g.textContent="Project sharing";const _=document.createElement("ul");_.setAttribute("aria-label",`People sharing ${e.display_project}`);for(const w of e.sharing){const S=document.createElement("li"),T=document.createElement("strong");T.textContent=N0(w);const k=document.createElement("span");k.textContent=` — ${w.lifecycle.label}. ${w.lifecycle.explanation}`,S.append(T,k),_.appendChild(S)}h.append(g,_),s.appendChild(h)}if(Xr(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=A0(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 ${ms(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(g=>g.message).join(" ")}`,s.appendChild(h)}if(e.statuses.length>0){const h=document.createElement("div");h.className="project-inventory-badges";for(const g of e.statuses){const _=document.createElement("span");_.className=`project-status-badge ${g}`,_.textContent=C0(g),h.appendChild(_)}s.appendChild(h)}const p=document.createElement("details");p.className="project-inventory-details",p.open=kd.has(e.workspace_identity),p.addEventListener("toggle",()=>{p.open?kd.add(e.workspace_identity):kd.delete(e.workspace_identity)});const m=document.createElement("summary");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 f=document.createElement("dl");f.className="project-detail-grid";const y=[["Workspace identity",e.workspace_identity],["Project",e.project],["CWD",e.cwd],["Git remote",e.git_remote],["Git branch",e.git_branch],["Current Space",Pd(e)],["Suggested Space",e.suggested_scope_id?ms(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,g]of y){const _=document.createElement("dt");_.textContent=h;const w=document.createElement("dd");w.textContent=g==null||g===""?"—":String(g),f.append(_,w)}return p.appendChild(f),p.appendChild(V0(e)),t.appendChild(p),t}function W0(e){const t=[...new Set(e.map(n=>Pd(n)))];return t.length===1?t[0]:"Mixed Spaces"}function q0(e){if(e.length===1)return Fy(e[0]);const t=Ad(e[0]),n=e.filter(Zo),r=Ay(n),i=document.createElement("article");i.className="project-inventory-row project-inventory-cluster";const o=Ed(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(Ey(n,`Select all identities for ${Ed(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(Ry(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=W0(e),d.appendChild(u);const p=e.reduce((S,T)=>S+(T.memory_count??0),0),m=e.reduce((S,T)=>S+T.session_count,0),f=document.createElement("div");f.className="project-inventory-meta",f.textContent=`${e.length} identities · ${m.toLocaleString()} sessions · ${p.toLocaleString()} memories`,i.appendChild(f),i.appendChild(Iy(r));const y=document.createElement("div");y.className="project-inventory-actions";const h=e.filter(xd);if(h.length===0){const S=document.createElement("div");S.className="settings-note",S.textContent=e.every(Xr)?"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.",y.appendChild(S),d.appendChild(y)}else{const S=h.map(N=>({project:N,warnings:(N.guardrail_warnings??[]).filter(G=>G.requires_confirmation)})),T=S.some(({warnings:N})=>N.length>0),k=new Set(h.map(N=>N.suggested_scope_id).filter(N=>!!N)),P=new Set(h.map(N=>N.resolved_scope_id)),E=document.createElement("select");E.className="project-domain-select",E.setAttribute("aria-label",`Space for ${Ed(e[0])} group`);const M=document.createElement("option");M.value="",M.textContent="Choose Space…",E.appendChild(M),Oy(E),E.value=My(ls.get(t));const U=document.createElement("button");if(U.className="settings-button",U.type="button",U.textContent=`Save Space for ${h.length} identit${h.length===1?"y":"ies"}`,U.disabled=!E.value||T,U.addEventListener("click",()=>{G0(h,E.value)}),E.addEventListener("change",()=>{E.value?ls.set(t,E.value):ls.delete(t),U.disabled=!E.value||T}),E.addEventListener("blur",$y),y.append(E,U),k.size>1||P.size>1||T){const N=document.createElement("div");if(N.className="settings-note project-attention-note",N.textContent=T?"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.",T){const G=document.createElement("ul");for(const{project:A,warnings:$}of S){if($.length===0)continue;const L=document.createElement("li"),J=document.createElement("strong");J.textContent=`Blocked identity: ${A.workspace_identity}`;const H=document.createElement("span");H.textContent=` — ${$.map(x=>x.message).join(" ")}`,L.append(J,H),G.appendChild(L)}N.appendChild(G)}y.appendChild(N)}d.appendChild(y)}const g=document.createElement("details");g.className="project-inventory-details",g.open=Nd.has(t),g.addEventListener("toggle",()=>{g.open?Nd.add(t):Nd.delete(t)});const _=document.createElement("summary"),w=e.reduce((S,T)=>S+(T.guardrail_warnings??[]).filter(k=>k.severity==="warning").length,0);_.textContent=w>0?`Advanced Project administration — ${w.toLocaleString()} item${w===1?"":"s"} need attention`:"Advanced Project administration",g.appendChild(_),g.appendChild(d);for(const S of e)g.appendChild(Fy(S));return i.appendChild(g),i}function z0(e){const t=new Map;for(const n of e){const r=Ad(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function By(e){const t=Ke("projectsInventoryList");if(!t)return;t.textContent="";const n=document.createElement("div");n.className="settings-note",n.textContent=e,t.appendChild(n)}function Uy(){document.getElementById("projectsInventorySkeleton")?.remove()}function Gy(e){const t=Ke("projectsInventoryMeta"),n=Ke("projectsInventoryList");if(!t||!n)return;const r=document.activeElement instanceof HTMLElement?document.activeElement.dataset.projectFocusKey:void 0;if(Uy(),n.textContent="",e.projects.length===0)By("No projects match those filters.");else for(const s of z0(e.projects))n.appendChild(q0(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=Ke("projectsPrevPage"),o=Ke("projectsNextPage");i&&(i.disabled=e.offset===0),o&&(o.disabled=!e.has_more),ur(),r&&[...n.querySelectorAll("[data-project-focus-key]")].find(s=>s.dataset.projectFocusKey===r)?.focus()}function J0(e,t){R0().then(()=>{t===us&&(Ly()||Gy(e))})}async function Y0(){const e=new Map;let t=0;for(;;){const n=await xo({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 Hy(e,t,n){const r=Ke("recipientPolicyManagementMount");r&&Lm(r,Qo(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&Ct.clear(),ur(),at?.()}})}async function X0(){const e=Ke("projectsInventoryMeta"),t=Ke("projectsInventoryList");if(!e||!t)return;if(Ly()){ds=!0;return}ds=!1;const n=++us;En=!1,In=!1,ur(),e.textContent="Loading project inventory…";try{const[r,i,o,s,c]=await Promise.all([xo({limit:Cd,offset:co,q:Ke("projectsSearch")?.value.trim()||void 0,status:Ke("projectsStatusFilter")?.value||void 0}),iw(),Y0().then(u=>({ok:!0,projects:u})).catch(()=>({ok:!1,projects:[]})),rw().then(u=>({ok:!0,review:u})).catch(u=>({ok:!1,error:u})),Us().then(u=>({ok:!0,intent:u})).catch(u=>({ok:!1,error:u}))]);if(n!==us)return;if(Td=i.scopes,En=o.ok,In=c.ok,Yr=c.ok?c.intent:ps,o.ok){const u=new Set(Qo(o.projects).map(p=>p.canonicalProjectIdentity));for(const p of Ct)u.has(p)||Ct.delete(p)}const l=Ke("projectShareFlowMount");l&&Om(l,o.projects,{inventoryError:!o.ok});const d=Ke("recipientPolicyReviewMount");d&&("review"in s?w0(d,s.review):S0(d,s.error)),Hy(o.projects,Yr,!o.ok||!c.ok),Gy(r),J0(r,n)}catch(r){if(n!==us)return;En=!1,In=!1,Yr=ps;const i=Ke("projectShareFlowMount");i&&Om(i,[],{inventoryError:!0}),Hy([],ps,!0),ur(),Uy(),e.textContent="Project inventory failed to load.",By(r instanceof Error?r.message:"Unable to load project inventory.")}}function Z0(e){at=e,Ct.clear();const t=Ke("projectsStatusFilter");if(t&&t.options.length===0)for(const[i,o]of Ny){const s=document.createElement("option");s.value=i,s.textContent=o,t.appendChild(s)}const n=()=>{co=0,at?.()};Ke("projectsSearch")?.addEventListener("input",n),t?.addEventListener("change",n),Ke("projectsPrevPage")?.addEventListener("click",()=>{co=Math.max(0,co-Cd),at?.()}),Ke("projectsNextPage")?.addEventListener("click",()=>{co+=Cd,at?.()});const r=Ke("projectsShareSelected");r&&r.dataset.recipientPolicyBound!=="true"&&(r.dataset.recipientPolicyBound="true",r.addEventListener("click",()=>{Ct.size!==0&&wi({mode:"project-add",projectIds:[...Ct].sort()})})),ur()}function Ld(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 Q0(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 Ky="codemem-settings-advanced",Vy="gpt-5.1-codex-mini",Wy="claude-4.5-haiku",eD=[{value:"observer",label:"Connection"},{value:"queue",label:"Processing"},{value:"sync",label:"Device Sync"}],tD={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"},nD=new Set(["claude_command","codex_command","observer_base_url","observer_auth_file","observer_auth_command","observer_headers","sync_coordinator_url"]),rD={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 iD(){try{return globalThis.localStorage?.getItem(Ky)==="1"}catch{return!1}}function oD(e){try{globalThis.localStorage?.setItem(Ky,e?"1":"0")}catch{}}function ln(e,t){return typeof e=="object"&&e!==null&&Object.hasOwn(e,t)}function Ne(e,t,n){if(ln(t,n))return t[n];if(ln(e,n))return e[n]}function Ee(e){return e==null?"":String(e)}function fs(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 aD(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function sD(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function ze(e){const t=e.trim();return t===""?"":t}function cD(e,t,n){return n?{model:n,source:"Configured"}:e==="claude_sidecar"?{model:Wy,source:"Recommended (local Claude session)"}:e==="codex_sidecar"?{model:Vy,source:"Recommended (local Codex session)"}:t==="anthropic"?{model:Wy,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:Vy,source:"Recommended (direct API)"}}function lD(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 ze(Ee(n[t]));case"observer_runtime":return ze(Ee(n.observer_runtime));case"observer_auth_source":return ze(Ee(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(!ln(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(!ln(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r>0?r:""}case"observer_auth_cache_ttl_s":{if(!ln(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 fs(n[t]);default:return ln(n,t)?n[t]:""}}function dD(e,t,n){const r={...e};return Object.keys(n).forEach(i=>{ln(r,i)&&(r[i]=lD(t,i))}),r}function uD(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let o=[];try{o=Ld(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(T){if(!i||n.has("claude_command"))throw T;const k=r.claude_command;o=Array.isArray(k)?k.filter(P=>typeof P=="string").map(P=>P.trim()).filter(P=>P.length>0):[]}let s=[];try{s=Ld(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(T){if(!i||n.has("codex_command"))throw T;const k=r.codex_command;s=Array.isArray(k)?k.filter(P=>typeof P=="string").map(P=>P.trim()).filter(P=>P.length>0):[]}let c=[];try{c=Ld(t.observerAuthCommand,{label:"observer auth command"})}catch(T){if(!i||n.has("observer_auth_command"))throw T;const k=r.observer_auth_command;c=Array.isArray(k)?k.filter(P=>typeof P=="string"):[]}let l={};try{l=Q0(t.observerHeaders)}catch(T){if(!i||n.has("observer_headers"))throw T;const k=r.observer_headers;k&&typeof k=="object"&&!Array.isArray(k)&&Object.entries(k).forEach(([P,E])=>{typeof P=="string"&&P.trim()&&typeof E=="string"&&(l[P]=E)})}const d=t.observerAuthCacheTtlS.trim(),u=t.observerSimpleTemperature.trim(),p=t.observerRichTemperature.trim(),m=t.observerRichMaxOutputTokens.trim(),f=t.rawEventsSweeperIntervalS.trim(),y=d===""?"":Number(d),h=u===""?"":Number(u),g=p===""?"":Number(p),_=m===""?"":Number(m),w=Number(f),S=f===""?"":w;if(d!==""&&!Number.isFinite(y))throw new Error("observer auth cache ttl must be a number");if(u!==""&&(typeof h!="number"||!Number.isFinite(h)||h<0))throw new Error("simple tier temperature must be a non-negative number");if(p!==""&&(typeof g!="number"||!Number.isFinite(g)||g<0))throw new Error("rich tier temperature must be a non-negative number");if(m!==""&&(typeof _!="number"||!Number.isFinite(_)||_<=0||!Number.isInteger(_)))throw new Error("rich tier max output tokens must be a positive integer");if(f!==""&&(!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:ze(t.observerProvider),observer_model:ze(t.observerModel),observer_tier_routing_enabled:t.observerTierRoutingEnabled,observer_simple_model:ze(t.observerSimpleModel),observer_simple_temperature:h,observer_reasoning_effort:ze(t.observerReasoningEffort),observer_reasoning_summary:ze(t.observerReasoningSummary),observer_rich_model:ze(t.observerRichModel),observer_rich_temperature:g,observer_rich_reasoning_effort:ze(t.observerRichReasoningEffort),observer_rich_reasoning_summary:ze(t.observerRichReasoningSummary),observer_rich_max_output_tokens:_,observer_runtime:ze(t.observerRuntime||"api_http")||"api_http",observer_auth_source:ze(t.observerAuthSource||"auto")||"auto",observer_auth_file:ze(t.observerAuthFile),observer_auth_command:c,observer_auth_timeout_ms:Number(t.observerAuthTimeoutMs||0)||"",observer_auth_cache_ttl_s:y,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:S,sync_enabled:t.syncEnabled,sync_host:ze(t.syncHost),sync_port:Number(t.syncPort||0)||"",sync_interval_s:Number(t.syncInterval||0)||"",sync_mdns:t.syncMdns,sync_coordinator_url:ze(t.syncCoordinatorUrl),sync_coordinator_group:ze(t.syncCoordinatorGroup),sync_coordinator_timeout_s:Number(t.syncCoordinatorTimeout||0)||"",sync_coordinator_presence_ttl_s:Number(t.syncCoordinatorPresenceTtl||0)||""}}function pD(e){const t=e.config||{},n=e.effective||{},r=Ne(t,n,"observer_headers"),i=r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).filter(([p,m])=>typeof p=="string"&&p.trim()&&typeof m=="string")):{},o=Ne(t,n,"claude_command"),s=Array.isArray(o)?o.filter(p=>typeof p=="string"):[],c=Ne(t,n,"codex_command"),l=Array.isArray(c)?c.filter(p=>typeof p=="string"):[],d=Ne(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:Ee(Ne(t,n,"observer_provider")),observerModel:Ee(Ne(t,n,"observer_model")),observerTierRoutingEnabled:fs(Ne(t,n,"observer_tier_routing_enabled")),observerSimpleModel:Ee(Ne(t,n,"observer_simple_model")),observerSimpleTemperature:Ee(Ne(t,n,"observer_simple_temperature")),observerReasoningEffort:Ee(Ne(t,n,"observer_reasoning_effort")),observerReasoningSummary:Ee(Ne(t,n,"observer_reasoning_summary")),observerRichModel:Ee(Ne(t,n,"observer_rich_model")),observerRichTemperature:Ee(Ne(t,n,"observer_rich_temperature")),observerRichReasoningEffort:Ee(Ne(t,n,"observer_rich_reasoning_effort")),observerRichReasoningSummary:Ee(Ne(t,n,"observer_rich_reasoning_summary")),observerRichMaxOutputTokens:Ee(Ne(t,n,"observer_rich_max_output_tokens")),observerRuntime:Ee(Ne(t,n,"observer_runtime"))||"api_http",observerAuthSource:Ee(Ne(t,n,"observer_auth_source"))||"auto",observerAuthFile:Ee(Ne(t,n,"observer_auth_file")),observerAuthCommand:u.length?JSON.stringify(u,null,2):"",observerAuthTimeoutMs:Ee(Ne(t,n,"observer_auth_timeout_ms")),observerAuthCacheTtlS:Ee(Ne(t,n,"observer_auth_cache_ttl_s")),observerHeaders:Object.keys(i).length?JSON.stringify(i,null,2):"",observerMaxChars:Ee(Ne(t,n,"observer_max_chars")),packObservationLimit:Ee(Ne(t,n,"pack_observation_limit")),packSessionLimit:Ee(Ne(t,n,"pack_session_limit")),rawEventsSweeperIntervalS:Ee(Ne(t,n,"raw_events_sweeper_interval_s")),syncEnabled:fs(Ne(t,n,"sync_enabled")),syncHost:Ee(Ne(t,n,"sync_host")),syncPort:Ee(Ne(t,n,"sync_port")),syncInterval:Ee(Ne(t,n,"sync_interval_s")),syncMdns:fs(Ne(t,n,"sync_mdns")),syncCoordinatorUrl:Ee(Ne(t,n,"sync_coordinator_url")),syncCoordinatorGroup:Ee(Ne(t,n,"sync_coordinator_group")),syncCoordinatorTimeout:Ee(Ne(t,n,"sync_coordinator_timeout_s")),syncCoordinatorPresenceTtl:Ee(Ne(t,n,"sync_coordinator_presence_ttl_s"))}}function mD(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection now lives in Processing.";const n=cD(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),ze(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>ln(t,r))?"Env override":n.source}: ${n.model}`}function fD(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 hD(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function gD(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 vD(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 yD(e){return!e}function bD(e,t,n){return t.has(e)||n.has(e)}function _D(e){return`${e} is read-only in the viewer for security. Edit the config file or environment instead.`}var q={open:!1,previouslyFocused:null,activeTab:"observer",baseline:{},envOverrides:{},touchedKeys:new Set,shellMounted:!1,protectedKeys:new Set,startPolling:null,refresh:null,showAdvanced:iD(),controller:null,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...rD}}};function wD(){q.controller?.hideTooltip()}function pr(e){if(q.controller){q.controller.setRenderState(e);return}q.renderState={...q.renderState,...e}}function SD(e){pr({values:{...q.renderState.values,...e}})}function CD(e){const t=["observer","queue","sync"].includes(e)?e:"observer";q.activeTab=t,q.controller?.setActiveTab(t)}function hs(e,t=!0){b.settingsDirty=e,t&&q.controller?.setDirty(e)}function TD(e){q.showAdvanced=e,q.controller?.setShowAdvanced(e)}function qy(){return q.open}function kD(e){return bD(e,q.protectedKeys,nD)}function zy(e={}){return uD({values:q.renderState.values,touchedKeys:q.touchedKeys,baseline:q.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors})}function ND(e){pr({observerStatus:e&&typeof e=="object"?e:null})}function xD(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=pD(t);q.envOverrides=i,q.protectedKeys=new Set(o),b.configDefaults=n,b.configPath=t.path||"",pr({effectiveText:Object.keys(i).length>0?"Some fields are managed by environment settings.":"",overridesVisible:Object.keys(i).length>0,pathText:b.configPath?`Config path: ${b.configPath}`:"Config path: n/a",providers:aD(t.providers),statusText:"No unsaved changes",values:s}),q.touchedKeys=new Set;try{q.baseline=dD(zy({allowUntouchedParseErrors:!0}),r,i)}catch{q.baseline={}}hs(!1)}async function PD(){if(!q.open)try{const[e,t]=await Promise.all([w_(),__().catch(()=>null)]);xD(e),ND(t)}catch{}}function $d(e){return String(e||"").replace(/_/g," ")}function Md(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 AD(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 ED(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 ID(e){if(typeof e!="string"||!e.trim())return"Unknown time";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function RD({status:e}){if(!e)return a("div",{id:"observerStatusBanner",className:"observer-status-banner",hidden:!0});const t=e.active,n=e.available_credentials||{},r=e.latest_failure,i=Object.entries(n).filter(([,o])=>o&&typeof o=="object");return a("div",{id:"observerStatusBanner",className:"observer-status-banner",children:[t?a(te,{children:[a("div",{className:"status-label",children:"Active observer"}),a("div",{className:"status-active",children:[String(t.provider||"unknown")," → ",String(t.model||"")," via"," ",AD(t.auth?.method||"none")," ",a("span",{"aria-label":t.auth?.token_present===!0?"token present":"token missing",className:t.auth?.token_present===!0?"cred-ok":"cred-none",role:"img",children:a("i",{"aria-hidden":"true","data-lucide":t.auth?.token_present===!0?"check":"x"})})]})]}):a(te,{children:[a("div",{className:"status-label",children:"Observer status"}),a("div",{className:"status-active",children:"Not yet initialized (waiting for first session)"})]}),i.length?a(te,{children:[a("div",{className:"status-label",children:"Available credentials"}),a("div",{children:i.map(([o,s],c)=>{const l=s,d=Object.values(l).some(Boolean);return a("span",{className:"status-cred",children:[c>0?" · ":null,a("span",{"aria-label":d?"credential available":"no credential",className:d?"cred-ok":"cred-none",role:"img",children:d?a("i",{"aria-hidden":"true","data-lucide":"check"}):"–"})," ",String(o),": ",ED(l)]},o)})})]}):null,r&&typeof r=="object"?a(te,{children:[a("div",{className:"status-label",children:"Latest processing issue"}),a("div",{className:"status-issue",children:[a("div",{className:"status-issue-message",children:typeof r.error_message=="string"&&r.error_message.trim()?r.error_message.trim():"Raw-event processing failed."}),a("div",{className:"status-issue-meta",children:[[typeof r.observer_provider=="string"?r.observer_provider.trim():"",typeof r.observer_model=="string"&&r.observer_model.trim()?`→ ${r.observer_model.trim()}`:"",typeof r.observer_runtime=="string"&&r.observer_runtime.trim()?`(${r.observer_runtime.trim()})`:""].filter(Boolean).join(" ").replace(/\s+/g," ").trim(),`Last failure ${ID(r.updated_at)}`,typeof r.attempt_count=="number"&&Number.isFinite(r.attempt_count)?`Attempts ${r.attempt_count}`:""].filter(Boolean).join(" · ")}),typeof r.impact=="string"&&r.impact.trim()?a("div",{className:"status-issue-impact",children:r.impact.trim()}):null]})]}):null]})}function Jy(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 po(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function DD(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 LD(){const e=Re("settingsModal");(DD(e)[0]||e)?.focus()}function $D(){const[e,t]=I({anchor:null,content:"",visible:!1}),n=F(null);return K(()=>{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=po(u.target);p&&r(p)},s=u=>{const p=po(u.target);if(!p)return;const m=u.relatedTarget;m instanceof Element&&p.contains(m)||i()},c=u=>{const p=po(u.target);p&&r(p)},l=u=>{po(u.target)&&i()},d=u=>{const p=po(u.target);p&&(u.preventDefault(),t(m=>{if(m.anchor===p&&m.visible)return{anchor:null,content:"",visible:!1};const f=p.dataset.tooltip?.trim()||"";return f?{anchor:p,content:f,visible:!0}:m}))};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)}},[]),gt(()=>{if(!e.visible||!e.anchor||!n.current)return;const r=requestAnimationFrame(()=>{n.current&&e.anchor&&Jy(n.current,e.anchor)});return()=>{cancelAnimationFrame(r)}},[e.anchor,e.content,e.visible]),K(()=>{if(!e.visible||!e.anchor)return;const r=()=>{n.current&&e.anchor&&Jy(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:Pe(()=>typeof document>"u"?null:en(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 MD({DialogContent:e,onClose:t}){const[n,r]=I(q.open),[i,o]=I(["observer","queue","sync"].includes(q.activeTab)?q.activeTab:"observer"),[s,c]=I(b.settingsDirty),[l,d]=I(q.renderState),[u,p]=I(q.showAdvanced),{tooltipPortal:m,setTooltip:f}=$D();q.open=n,q.activeTab=i,b.settingsDirty=s,q.renderState=l,q.showAdvanced=u,K(()=>(q.controller={hideTooltip:()=>{f({anchor:null,content:"",visible:!1})},setActiveTab:h=>{const g=["observer","queue","sync"].includes(h)?h:"observer";q.activeTab=g,o(g)},setDirty:h=>{b.settingsDirty=h,c(h)},setOpen:h=>{q.open=h,r(h)},setRenderState:h=>{const g={...q.renderState,...h};q.renderState=g,d(g)},setShowAdvanced:h=>{q.showAdvanced=h,oD(h),p(h)}},()=>{q.controller&&(q.controller=null)}),[]),K(()=>{n&&globalThis.lucide?.createIcons?.()},[n]);const y=re(()=>{q.startPolling&&q.refresh&&t(q.startPolling,q.refresh)},[t]);return a(te,{children:[a(yi,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:h=>{h.preventDefault()},onOpenAutoFocus:h=>{h.preventDefault(),LD()},onOpenChange:h=>{if(h){r(!0);return}y()},open:n,overlayClassName:"modal-backdrop",overlayId:"settingsBackdrop",children:a(e,{})}),m]})}function je({children:e,className:t="field",hidden:n=!1,id:r}){return a("div",{className:t,hidden:n,id:r,children:e})}function mo({children:e,hidden:t=!1}){return a("div",{className:"settings-note",hidden:t,children:e})}function Od({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 OD({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:m,observerStatusBannerSlot:f}){return a(te,{children:[a(Od,{detail:"Set how codemem reaches your model provider and where it should look for credentials.",title:"Connection and credentials"}),f,a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Connection"}),a(je,{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(cn,{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(je,{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(we,{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(je,{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(cn,{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(je,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"codexCommand",children:"Codex command (JSON argv)"}),a(Hr,{disabled:!0,id:"codexCommand",placeholder:'["codex"]',rows:2,value:e.codexCommand}),a("div",{className:"small",children:m("codex_command")})]}),a(je,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"claudeCommand",children:"Claude command (JSON argv)"}),a(Hr,{disabled:!0,id:"claudeCommand",placeholder:'["claude"]',rows:2,value:e.claudeCommand}),a("div",{className:"small",children:m("claude_command")})]}),a(je,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerMaxChars",children:"Request size limit (chars)"}),a(we,{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(je,{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(cn,{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(je,{hidden:!r,id:"observerAuthFileField",children:[a("label",{htmlFor:"observerAuthFile",children:"Token file path"}),a(we,{disabled:!0,id:"observerAuthFile",placeholder:"~/.codemem/work-token.txt",value:e.observerAuthFile}),a("div",{className:"small",children:m("observer_auth_file")})]}),a(je,{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(Hr,{disabled:!0,id:"observerAuthCommand",placeholder:'["iap-auth", "--audience", "gateway"]',rows:3,value:e.observerAuthCommand}),a("div",{className:"small",children:m("observer_auth_command")})]}),a("div",{className:"small",hidden:!i,id:"observerAuthCommandNote",children:'Command format: JSON string array, e.g. `["iap-auth", "--audience", "gateway"]`.'}),a(mo,{hidden:o(),children:"These advanced credential overrides only matter when you need custom command timing, cached tokens, or extra request headers."}),a(je,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerAuthTimeoutMs",children:"Token command timeout (ms)"}),a(we,{id:"observerAuthTimeoutMs",min:"1",onInput:s("observerAuthTimeoutMs"),type:"number",value:e.observerAuthTimeoutMs})]}),a(je,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerAuthCacheTtlS",children:"Token cache time (s)"}),a(we,{id:"observerAuthCacheTtlS",min:"0",onInput:s("observerAuthCacheTtlS"),type:"number",value:e.observerAuthCacheTtlS})]}),a(je,{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(Hr,{disabled:!0,id:"observerHeaders",placeholder:'{"Authorization":"Bearer ${auth.token}"}',rows:4,value:e.observerHeaders}),a("div",{className:"small",children:m("observer_headers")})]})]})]})}function gs({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(Fr,{"aria-labelledby":c,checked:e,className:"settings-switch",disabled:n,id:i,onCheckedChange:s,thumbClassName:"settings-switch-thumb"})]})}function jD({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r,onSwitchInput:i,getTieredRoutingHelperText:o}){return a(te,{children:[a(Od,{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(je,{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(we,{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(gs,{checked:e.observerTierRoutingEnabled,className:"field",id:"observerTierRoutingEnabled",label:"Enable tiered routing",onCheckedChange:i("observerTierRoutingEnabled")}),a("div",{className:"small",children:o()}),a(mo,{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(je,{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(we,{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(je,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerSimpleTemperature",children:"Temperature"}),a(we,{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(je,{className:"field settings-advanced",children:[a("label",{htmlFor:"observerReasoningEffort",children:"Reasoning effort"}),a(we,{id:"observerReasoningEffort",onInput:r("observerReasoningEffort"),placeholder:"leave empty for provider default",value:e.observerReasoningEffort})]}),a(je,{className:"field settings-advanced",children:[a("label",{htmlFor:"observerReasoningSummary",children:"Reasoning summary"}),a(we,{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(je,{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(we,{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(je,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichTemperature",children:"Temperature"}),a(we,{id:"observerRichTemperature",min:"0",onInput:r("observerRichTemperature"),step:"0.1",type:"number",value:e.observerRichTemperature})]}),a(je,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichReasoningEffort",children:"Reasoning effort override"}),a(we,{id:"observerRichReasoningEffort",onInput:r("observerRichReasoningEffort"),placeholder:"inherits shared reasoning effort",value:e.observerRichReasoningEffort})]}),a(je,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichReasoningSummary",children:"Reasoning summary override"}),a(we,{id:"observerRichReasoningSummary",onInput:r("observerRichReasoningSummary"),placeholder:"inherits shared reasoning summary",value:e.observerRichReasoningSummary})]}),a(je,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichMaxOutputTokens",children:"Max output tokens"}),a(we,{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(mo,{hidden:n(),children:"Most users can keep these defaults. Change them only when you need smaller or larger default context packs."}),a(je,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packObservationLimit",children:"Observation limit"}),a(we,{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(je,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packSessionLimit",children:"Session summary limit"}),a(we,{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 FD({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return a(te,{children:[a(Od,{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(gs,{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(we,{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(we,{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(we,{id:"syncPort",min:"1",onInput:n("syncPort"),type:"number",value:e.syncPort})]}),a(gs,{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(we,{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(we,{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(mo,{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(we,{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(we,{id:"syncCoordinatorPresenceTtl",min:"1",onInput:n("syncCoordinatorPresenceTtl"),type:"number",value:e.syncCoordinatorPresenceTtl})]})]})]})}function BD({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=>Rr(p,{onSubmit:s,disabled:u}),children:[a("div",{className:"modal-header",children:[a("h2",{id:"settingsTitle",children:"Settings"}),a($o,{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(gs,{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(mo,{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(Hf,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:c,tabs:eD,triggerClassName:"settings-tab",value:t,children:[a(Jn,{className:"settings-panel",forceMount:!0,value:"observer",children:a(OD,{...e,observerStatusBannerSlot:d})}),a(Jn,{className:"settings-panel",forceMount:!0,value:"queue",children:a(jD,{...e})}),a(Jn,{className:"settings-panel",forceMount:!0,value:"sync",children:a(FD,{...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 UD(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:o}=e,s={};return Object.entries(t).forEach(([c,l])=>{o(c)||ln(r,c)&&!i.has(c)||sD(l,n[c])||(s[c]=l)}),s}function GD(e){const t=s=>{const c=tD[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 HD(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=>$d(String(p))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(p=>$d(String(p))):[],o=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(p=>$d(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: ${Md(r)}.`),i.length&&d.push(`Live settings updated: ${Md(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 ${Md(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 KD=()=>mD(q.renderState.values,q.envOverrides),VD=()=>fD(q.renderState.values),WD=()=>hD(q.renderState.values),qD=()=>gD(q.renderState.values),zD=()=>vD(q.renderState.values),JD=()=>yD(q.showAdvanced),{onTextInput:YD,onSelectValueChange:XD,onSwitchInput:ZD}=GD({getTouchedKeys:()=>q.touchedKeys,getValues:()=>q.renderState.values,updateFormState:SD,setDirty:e=>hs(e)});function QD(){const e=q.renderState.observerStatus;return a(RD,{status:e})}function eL(){const e=q.renderState.values,t=String(b.configDefaults?.observer_max_chars||""),n=e.observerAuthSource==="file",r=e.observerAuthSource==="command",i=e.observerTierRoutingEnabled;return a(BD,{panelProps:{values:e,observerMaxCharsDefault:t,providerOptions:Array.from(new Set(q.renderState.providers.concat(e.observerProvider?[e.observerProvider]:[]))).sort((o,s)=>o.localeCompare(s)).map(o=>({label:o,value:o})),showAuthFile:n,showAuthCommand:r,showTieredRouting:i,hiddenUnlessAdvanced:JD,onTextInput:YD,onSelectValueChange:XD,onSwitchInput:ZD,getObserverModelLabel:WD,getObserverModelTooltip:qD,getObserverModelDescription:zD,getObserverModelHint:KD,getTieredRoutingHelperText:VD,protectedConfigHelp:_D},activeTab:q.activeTab,showAdvanced:q.showAdvanced,renderState:q.renderState,settingsDirty:b.settingsDirty,onClose:()=>{q.startPolling&&q.refresh&&vs(q.startPolling,q.refresh)},onSave:()=>{q.startPolling&&q.refresh&&iL(q.startPolling,q.refresh)},onActiveTabChange:CD,onAdvancedToggle:TD,observerStatusBannerSlot:a(QD,{})})}function tL(){return a(MD,{DialogContent:eL,onClose:vs})}function nL(){const e=Re("settingsDialogMount");e&&Be(a(tL,{}),e)}function Yy(){Re("settingsDialogMount")&&(q.shellMounted||(nL(),q.shellMounted=!0))}function rL(e){q.shellMounted||Yy(),q.open=!0,q.previouslyFocused=document.activeElement,e(),q.controller?.setOpen(!0)}function vs(e,t){if(b.settingsDirty&&!globalThis.confirm("Discard unsaved changes?")){q.controller?.setOpen(!0);return}q.open=!1,q.controller?.setOpen(!1),wD(),(q.previouslyFocused&&typeof q.previouslyFocused.focus=="function"?q.previouslyFocused:jc("settingsButton"))?.focus(),q.previouslyFocused=null,q.touchedKeys=new Set,e(),t()}async function iL(e,t){if(!q.renderState.isSaving){pr({isSaving:!0,statusText:"Saving changes…"});try{const n=UD({current:zy({allowUntouchedParseErrors:!0}),baseline:q.baseline,envOverrides:q.envOverrides,touchedKeys:q.touchedKeys,isProtected:kD});if(Object.keys(n).length===0){pr({isSaving:!1,statusText:"No unsaved changes"}),hs(!1),vs(e,t);return}const r=HD(await S_(n));pr({isSaving:!1,statusText:"Saved changes"}),hs(!1),vs(e,t),ne(r.message,r.type)}catch(n){pr({isSaving:!1,statusText:`Save failed: ${n instanceof Error?n.message:"unknown error"}`})}}}function oL(e,t,n){q.startPolling=t,q.refresh=n,Yy(),jc("settingsButton")?.addEventListener("click",()=>rL(e))}function aL(e){e.dataset.syncRenderRoot="preact"}function sL(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function Qe(e,t){aL(e),Be(t,e)}function Zr(e){e.dataset.syncRenderRoot==="preact"&&Be(null,e)}function cL(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 lL(e){return typeof e=="object"&&e!==null}function dL(e,t){return b.pairingCommandRaw="",{payloadText:e,hintText:t}}function uL(e){if(!lL(e))return dL("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 b.pairingCommandRaw=i,{payloadText:i,hintText:"Copy this command and run it on the other device. Use --include/--exclude to control which projects sync."}}function pL(){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 mL(){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 fL(){const e=b.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 hL(){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 gL(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 vL({items:e}){return a(te,{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 yL({attempts:e,note:t}){return a(te,{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]}),a("div",{class:"right",children:n.startedAt})]},`${n.startedAt}-${n.peerLabel}-${r}`))]})}function Xy({text:e}){return a(te,{children:e})}function bL({title:e,detail:t}){return a("div",{class:"sync-empty-state",children:[a("strong",{children:e}),a("span",{children:t})]})}function _L(e,t){if(!t.length){Zr(e);return}Qe(e,a(vL,{items:t}))}function wL(e,t,n){if(!t.length){Zr(e);return}Qe(e,a(yL,{attempts:t,note:n}))}function mr(e,t){Qe(e,a(bL,{...t}))}function Zy(e,t,n){Qe(e,a(Xy,{text:n.payloadText})),t&&Qe(t,a(Xy,{text:n.hintText}))}function Qy({open:e,onOpenChange:t,triggerId:n,triggerClassName:r,closedLabel:i,openLabel:o,contentId:s,contentClassName:c,contentHost:l=null,children:d}){const u=F(null),p=F(null),m=F(!1);gt(()=>{u.current&&(u.current.id=n,u.current.setAttribute("aria-controls",s)),p.current&&(p.current.id=s)},[s,n,e]),K(()=>{if(!e){m.current=!1;return}m.current||(m.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 f=a(va,{forceMount:!0,asChild:!0,children:a("div",{ref:p,id:s,className:c,hidden:!e,children:d})});return a(ga,{open:e,onOpenChange:t,children:[a(zf,{asChild:!0,children:a("button",{ref:u,type:"button",className:r,id:n,"aria-controls":s,children:e?o:i})}),l?en(f,l):f]})}function SL({open:e,onOpenChange:t}){return a(Qy,{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(we,{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(we,{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(Hr,{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 CL({contentHost:e,open:t,onOpenChange:n}){return a(Qy,{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 TL(e,t){Qe(e,a(SL,{...t}))}function kL(e,t){Qe(e,a(CL,{...t}))}function de(e){return String(e??"").trim()}function NL(e){return de(e).replace(/\s+/g," ").toLowerCase()}function xL(e){const t=de(e);return t?t.slice(0,8):"Unnamed device"}function eb(e){return de(e?.last_error).toLowerCase()}function tb(e){return e.includes("401")&&e.includes("unauthorized")}function nb(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var PL={scope_filter:"sharing-domain membership",visibility_filter:"visibility",project_filter:"project filter"};function rb(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 AL(e){const t=rb(e);return!de(e.device?.device_id)||e.device?.stale||e.hasAmbiguousCoordinatorGroup?!1:e.pairedLocally?t.state==="needs-your-approval":!0}function ib(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=DL(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=>ob(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=>ob(i)==="scope").length===n.length?{ok:!1,message:"Sync ran, but the peer is not authorized for one or more Spaces. Review Space access for this device in Teams, 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:de(n[0]?.error)||"Sync failed for at least one device.",warning:!0}}function ob(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=de(e.error);return EL(n)?"trust":IL(n)?"scope":null}function EL(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function IL(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function RL(e){const t=de(e?.reason);return PL[t]??(t.replaceAll("_"," ")||"sync filters")}function DL(e){const t=new Map;for(const n of e){const r=RL(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 ab(e){const t=de(e.localName);if(t)return t;const n=de(e.coordinatorName);return n||xL(de(e.deviceId))}function LL(e){const t=de(e.localName),n=de(e.coordinatorName);return t||n?!1:!!de(e.deviceId)}function $L(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 fo(e){const t=de(e?.status?.peer_state);if(t==="offline"||t==="stale")return"offline";const n=eb(e);return tb(n)?"needs-repair":nb(n)?"offline":e?.has_error||t==="degraded"?"needs-repair":t==="online"||e?.status?.fresh?"connected":"waiting"}function Qr(e){const t=e?.status||{},n=de(t.peer_state),r=eb(e),i=de(t.sync_status)==="ok"||de(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}:tb(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}:nb(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 ML={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 OL(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:ML[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 sb(e){return Array.isArray(e)?e.map(t=>de(t)).filter(t=>!!t):[]}function cb(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 ys(e,t){return e?e.replaceAll("_"," "):t}function jL(e){const t=(Array.isArray(e.authorized_scopes)?e.authorized_scopes:[]).map(r=>{const i=de(r.scope_id),o=de(r.label);if(!i&&!o)return null;const s=o||"Untitled Space",c=[ys(de(r.kind),"user"),ys(de(r.authority_type),"local"),`${ys(de(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 lb(e){const t=(Array.isArray(e.per_scope_sync)?e.per_scope_sync:[]).map(n=>{const r=de(n.scope_id),i=de(n.label);if(!r&&!i)return null;const o=i||"Untitled Space",s=de(n.last_applied_cursor),c=de(n.last_acked_cursor),l=n.bootstrapped===!0||s?"received":"pending",d=ys(de(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(m=>!!m).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 FL=["personal","private","home","mine","me"],BL=["oss","open source","opensource","community","public"],UL=["work","client"],GL=["local","legacy","review"];function HL(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>de(t)??"").join(" ").toLowerCase()}function KL(e){return[e.scope_id,e.label,e.kind].map(t=>de(t)??"").join(" ").toLowerCase()}function db(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jd(e,t){const n=HL(e);return t.some(r=>{const i=db(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function ub(e){return jd(e,FL)||jd(e,BL)}function VL(e){const t=KL(e);return GL.some(n=>{const r=db(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function WL(e){return!ub(e)&&(!VL(e)||jd(e,UL))}function qL(e){const t=Array.isArray(e.authorized_scopes)?e.authorized_scopes:[];if(!(de(e.discovered_via_group_id)||de(e.discovered_via_coordinator_id))||t.length===0)return{badgeLabel:null,detail:"",isVisible:!1,message:"",title:""};const n=t.some(ub),r=t.some(WL);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 zL(e,t){const n=e.map(r=>r.trim()).filter(Boolean);return n.length>0&&!n.includes("*")||t.length>0}function JL(e){const t=sb(e?.effective_include),n=sb(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${cb(t,"all projects")}`,o=`Exclude filter: ${cb(n,"no exclusions")}`,s=zL(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 YL(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=de(n?.display_name),i=de(n?.actor_id),o=NL(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 pb(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=de(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=>de(d?.actor_id)===c);!l||l.is_local||(i.get(c)??0)>0||o.add(c)})}),{visibleActors:t.filter(s=>!o.has(de(s?.actor_id))),hiddenLocalDuplicateCount:o.size}}var XL=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),ZL=new Set(["pending","verifying","waiting"]);function QL(e){return(Array.isArray(e?.groups)?e.groups.map(t=>de(t)).filter(Boolean):[]).join(", ")||"none"}function mb(e){return de(e?.projects?.[0]?.display_name)||"the shared Project"}function e$(e){const t=e?.items?.find(n=>n.state!=="active");return de(t?.canonicalProjectIdentity)||"the shared Project"}function t$(e,t){return t?.discovered_devices?.some(n=>n.needs_local_approval||n.waiting_for_peer_approval)?!0:e.some(n=>{const r=Qr(n).state;return r==="trusted-by-you"||r==="needs-repairing"})}function n$(e,t){return t?.enabled!==!0||t.daemon_state!=="ok"||t.daemon_running===!1?!1:e.some(n=>n.status?.sync_status==="ok"&&Qr(n).state==="mutual-trust"&&!lb(n).rows.some(r=>r.status==="pending"))}function r$(e){return e.some(t=>de(t.status?.peer_state)==="online"&&Qr(t).state==="mutual-trust")}function i$(e,t){return t?.daemon_state==="offline-peers"||t?.daemon_state==="stale"||t?.daemon_state==="degraded"?!0:e.some(n=>{const r=de(n.status?.peer_state),i=Qr(n).state;return n.has_error===!0&&i!=="needs-repairing"||i==="offline"||i==="needs-review"||r==="offline"||r==="stale"||r==="degraded"})}function o$(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 fb(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=QL(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){const p=mb(s);return{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${o}. Exact-Project setup has not converged, so coordinator presence is not a healthy sync signal.`,nextAction:`Open Project sharing below and retry setup for ${p}.`}}if(c)return{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${o}. Recipient access has not converged, so coordinator presence is not a healthy sync signal.`,nextAction:"Open Sharing and use Manage projects for the affected recipient, then run Sync now again."};const l=r.find(p=>{const m=p.lifecycle?.state;return m!==void 0&&XL.has(m)}),d=i.find(p=>{const m=p.state;return m!==void 0&&ZL.has(m)});if(l||d){const p=l?mb(l):e$(e.reconciliation??void 0),m=l?.lifecycle?.primary_action?.kind,f=l?.lifecycle?.state==="revoking";return{state:"pending-setup",badgeLabel:f?"Removal pending":"Setup pending",meta:f?`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:f?`Keep both devices online, then sync again to finish removing future access for ${p}.`:m==="retry_setup"?`Open Project sharing below and retry setup for ${p}.`:m==="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(o$(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(t$(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=de(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 configure a coordinator in Advanced settings."}:i$(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&&n$(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}:r$(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 a$(e){return e.discovered?.stale?e.peer?fo(e.peer)!=="connected":!0:!1}function hb(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 Fd(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 s$(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 c$(e){const t=de(e?.coordinator_url),n=Array.isArray(e?.groups)?e.groups:[];return t?n.some(r=>de(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 l$(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=de(i?.peer_device_id);if(!o)return;const s=r(o);s.peer=i,s.localName=de(i?.name)}),t.forEach(i=>{const o=de(i?.device_id);if(!o)return;const s=r(o);s.discovered=i,s.coordinatorName=de(i?.display_name)}),[...n.values()]}function d$(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=l$(n,r),o=e.duplicatePersonDecisions??{},s=YL(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=ab({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId}),u=l.peer?fo(l.peer):"waiting",p=l.peer?Qr(l.peer):null,m=de(l.discovered?.fingerprint),f=de(l.peer?.fingerprint);if(l.peer&&m&&f&&m!==f){c.push(hb({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 y=p?.description||de(l.peer?.last_error)||"Sync needs review.";c.push(hb({id:l.deviceId,name:d,title:p?.state==="needs-repairing"?`${d} needs re-pairing`:`${d} needs review`,summary:y}))}l.peer&&p?.state==="trusted-by-you"&&c.push(Fd({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(Fd({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(Fd({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&&LL({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId})&&c.push(s$({id:l.deviceId,name:d,summary:"Give this device a friendly name so it is easier to recognize later."}))}),{primaryStatus:fb({status:e.status,coordinator:e.coordinator,peers:n,shareOperations:e.shareOperations,shareOperationsLoadError:e.shareOperationsLoadError,reconciliation:e.reconciliation}),summary:{connectedDeviceCount:n.filter(l=>fo(l)==="connected").length,seenOnTeamCount:r.length,offlineTeamDeviceCount:i.filter(l=>a$(l)).length},duplicatePeople:s,attentionItems:c.sort((l,d)=>l.priority-d.priority||l.title.localeCompare(d.title))}}var gb={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 Rn(e){const t=document.getElementById(e);t&&t.remove()}var vb=!1;function u$(e){vb=e}var Bd=!1;function p$(e){Bd=e}var Ud=!1;function m$(e){Ud=e}var f$=new Set,Gd=new Set,Hd=new Set,yb="codemem-sync-duplicate-person-decisions";function h$(e){const t=String(e||"").trim();t&&(Gd.add(t),Hd.add(t),f$.add(t))}function Kd(e){const t=String(e||"").trim();return!!t&&Gd.has(t)}function g$(e){const t=String(e||"").trim();t&&Gd.delete(t)}function v$(e){const t=String(e||"").trim();return!t||!Hd.has(t)?!1:(Hd.delete(t),!0)}function Vd(){try{const e=localStorage.getItem(yb);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function bb(e){try{localStorage.setItem(yb,JSON.stringify(e))}catch{}}function _b(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function y$(){return Vd()}function b$(e,t){const n=_b(e);if(!n)return;const r=Vd();r[n]=t,bb(r)}function _$(e){const t=_b(e);if(!t)return;const n=Vd();delete n[t],bb(n)}function wb(e){return e.replace(/\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b/g,"$1.#.#")}function Sb(e){const t=String(e||"");return t?wb(t):""}function w$(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function S$(e,t){const n=String(e?.relatedPeerDeviceId??"").trim();return n?t.some(r=>String(r?.peer_device_id??"").trim()===n):!1}function bs(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 _s(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":bs(e)}function C$(e){return(Array.isArray(b.lastSyncPeers)?b.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function Cb(){return pb({actors:b.lastSyncActors,peers:b.lastSyncPeers,duplicatePeople:b.lastSyncViewModel?.duplicatePeople}).visibleActors}function T$(e=""){const t=[{value:"",label:"No person assigned"}],n=Cb(),r=(Array.isArray(b.lastSyncActors)?b.lastSyncActors:[]).find(i=>String(i?.actor_id||"")===e);return(r&&!n.some(i=>String(i?.actor_id||"")===e)?[...n,r]:n).forEach(i=>{const o=String(i?.actor_id||"").trim();o&&t.push({value:o,label:_s(i)})}),t.filter((i,o,s)=>o===s.findIndex(c=>c.value===i.value))}function Tb(e){return Cb().filter(t=>String(t?.actor_id||"")!==e)}function k$(e,t){const n=Tb(t).find(r=>String(r?.actor_id||"")===e);return!e||!n?"Choose which person should keep these devices.":`Merge into ${_s(n)}. Assigned devices move now; existing memories keep their current provenance.`}function Wd(e,t){if(e){if(e.textContent="",!t.length){e.hidden=!0;return}e.hidden=!1,t.slice(0,2).forEach(n=>{const r=ma("div","sync-action"),i=ma("div","sync-action-text");i.textContent=n.label,i.appendChild(ma("span","sync-action-command",n.command));const o=ma("button","settings-button sync-action-copy","Copy");o.addEventListener("click",()=>Pi(n.command,o)),r.append(i,o),e.appendChild(r)})}}function kb(e,t){return t&&e.error_redacted===!0}function Nb(){const e=document.getElementById("syncAttempts");if(!e)return;const t=b.lastSyncAttempts,n=String(b.lastSyncStatus?.daemon_state||"").trim();if(!Array.isArray(t)||!t.length){mr(e,fL());return}const r=gL(n,t.slice(0,5).some(i=>i.status==="error"));wL(e,t.slice(0,5).map(i=>{const o=i.started_at||i.started_at_utc||"",s=String(i.peer_device_id||"").trim(),c=Array.isArray(b.lastSyncPeers)?b.lastSyncPeers.find(m=>String(m?.peer_device_id||"")===s):null,l=String(c?.name||"").trim()||(s?s.slice(0,8):"unknown"),d=i.status==="error",u=[],p=Ei();if(d&&i.error){const m=String(i.error);u.push(p?wb(m):m),kb(i,p)&&u.push("Turn off Redact in Advanced diagnostics to reveal the full error.")}return!d&&(i.ops_in||i.ops_out)&&u.push(`${i.ops_in??0} in · ${i.ops_out??0} out`),!p&&i.address&&u.push(i.address),{status:i.status||"unknown",peerLabel:l,detail:u.join(" · "),startedAt:o?rr(o):"",...kb(i,p)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}}),r)}function N$(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncAttempts"),n=document.getElementById("syncMeta"),r=document.getElementById("syncActions");e&&mr(e,mL()),t&&mr(t,hL()),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."),Wd(r,[])}function ei(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function x$(e){const t=String(e?.state??"clear"),n=e?.stale_peer_rows??{},r=e?.access_cleanup_ops??{},i=ei(n.would_remove),o=ei(n.ambiguous),s=ei(r.applied),c=ei(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 xb(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncMeta"),n=document.getElementById("syncActions");if(!e)return;Rn("syncDiagSkeleton");const r=b.lastSyncStatus;if(!r){mr(e,pL()),Wd(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||cL(i)||null,d=r.last_sync_error||"",u=r.last_ping_error||"",p=Number(r.pending||0),m=String(r.daemon_detail||""),f=String(r.daemon_state||"unknown"),y=r.retention||{},h=r.cleanup_diagnostics,g=h?.stale_peer_rows??{},_=ei(g.would_remove),w=ei(g.ambiguous),S=y.enabled===!0,T=Number(y.last_deleted_ops||0),k=y.last_run_at||null,P=String(y.last_error||""),E=f==="offline-peers"?"Offline peers":f==="needs_attention"?"Needs attention":f==="rebootstrapping"?"Rebootstrapping":Bg(f),M=f==="disabled"||r.enabled===!1,U=Object.keys(i).length,N=!M&&U===0;if(t){const $=M?["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: ${E}`,`Peers: ${U}`,c?`Last sync: ${kn(Kr(c))} ago`:"Last sync: never"];f==="offline-peers"&&$.push("All peers are currently offline; sync will resume automatically"),m&&f==="stopped"&&$.push(`Detail: ${m}`),m&&(f==="needs_attention"||f==="rebootstrapping")&&$.push(`Detail: ${m}`),S&&$.push(k?`Retention last ran ${kn(Kr(k))} ago (approx oldest-first)`:"Retention enabled"),_>0?$.push(`${_.toLocaleString()} stale peer rows pending cleanup`):w>0&&$.push(`${w.toLocaleString()} stale peer rows retained because safe cleanup could not be proven`),t.textContent=$.join(" · ")}const G=M?[{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:E},{label:"Pending events",value:p},{label:"Last sync",value:c?`${kn(Kr(c))} ago`:"never"},{label:"Last peer ping",value:l?`${kn(Kr(l))} ago`:"never"},{label:"Retention",value:S?k?`${T.toLocaleString()} ops last run (approx)`:"Enabled":"Disabled"}];!M&&!N&&(d||u)&&G.push({label:[d,u].filter(Boolean).join(" · "),value:"Errors"}),!M&&!N&&s.seconds_since_last&&G.push({label:"Since last sync",value:`${s.seconds_since_last}s`}),!M&&!N&&o.seconds_since_last&&G.push({label:"Since last peer ping",value:`${o.seconds_since_last}s`}),!M&&S&&P&&G.push({label:P,value:"Retention"}),!M&&!N&&h&&G.push({label:"Cleanup",value:x$(h)}),_L(e,G);const A=[];N||f==="offline-peers"||(f==="stopped"?(A.push({label:"Sync daemon is stopped. Start it.",command:"codemem serve start"}),A.push({label:"Run one sync pass now.",command:"codemem sync once"})):f==="needs_attention"?A.push({label:"Sync needs manual attention before reset can continue.",command:"codemem sync doctor"}):f==="rebootstrapping"?A.push({label:"Sync is rebuilding state in the background.",command:"codemem sync status"}):d||u||f==="error"?(A.push({label:"Sync reports errors. Restart now.",command:"codemem serve restart && codemem sync once"}),A.push({label:"Run doctor for the root cause.",command:"codemem sync doctor"})):!M&&!N&&p>0&&A.push({label:"Pending sync work detected. Run one pass now.",command:"codemem sync once"})),!M&&w>0?A.push({label:"Some stale peer rows were retained because cleanup was ambiguous.",command:"codemem sync doctor"}):!M&&_>0&&A.push({label:"Stale peer rows are eligible for cleanup. Run one sync pass now.",command:"codemem sync once"}),Wd(n,A)}var P$="syncRedactMount",A$="syncRedactLabel",Pb=()=>{};function E$(e){Pb=e}var qd=()=>{};function zd(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;kL(e,{contentHost:t,open:b.syncPairingOpen,onOpenChange:r=>{if(sk(r),zd(),r){const i=document.getElementById("pairingPayload"),o=document.getElementById("pairingHint");i&&Zy(i,o,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}qd()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=b.pairingCommandRaw;r&&await Pi(r,n)})}function Jd(){zd();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;Zy(e,t,uL(b.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!b.pairingCommandRaw)}function Ab(){const e=document.getElementById(P$);e&&Qe(e,v(Fr,{"aria-labelledby":A$,checked:Ei(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{ck(t),Ab(),qd(),xb(),Pb(),Nb(),Jd()},thumbClassName:"sync-redact-switch-thumb"}))}function I$(e){qd=e,zd(),Ab()}function R$(e){e.classList.add("sync-shake"),e.addEventListener("animationend",()=>e.classList.remove("sync-shake"),{once:!0})}function ti(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),R$(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 et(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 fr=new Map,Yd=null,D$={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 L$(e){return D$[e instanceof Error?e.message:String(e)]??"Setup could not be retried. Review diagnostics for details."}function $$(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 M$(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function Xd(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 O$({operation:e,onAdvance:t,onLoadOperation:n,onReload:r,copyText:i}){const[o,s]=I(!1),[c,l]=I(()=>fr.get(e.operation_id)??null),d=F(null),u=e.lifecycle.primary_action;K(()=>{Yd!==e.operation_id||!d.current||(Yd=null,d.current.focus())},[c?.message,e.operation_id]);async function p(h){s(!0);try{let g=h;if(!g&&n){const w=(await n(e.operation_id)).lifecycle.primary_action;w?.kind==="copy_invite"&&(g=w.invite_link)}if(!g)throw new Error("Invitation is no longer available. Refresh the status.");await(i??(w=>navigator.clipboard.writeText(w)))(g);const _={message:"Invite copied.",tone:"success"};fr.set(e.operation_id,_),l(_)}catch(g){const _={message:g instanceof Error?g.message:"Invite could not be copied.",tone:"warning"};fr.set(e.operation_id,_),l(_)}finally{s(!1)}}async function m(){s(!0);try{const h=await t(e.operation_id),g=h.lifecycle.state==="active"?{message:"Setup complete.",tone:"success"}:h.lifecycle.state==="needs_attention"?{message:"Setup still needs attention.",tone:"warning"}:{message:`Retry started. ${h.lifecycle.label}.`,tone:"success"};fr.set(e.operation_id,g),Yd=e.operation_id,l(g),await r()}catch(h){const g={message:L$(h),tone:"warning"};fr.set(e.operation_id,g),l(g),queueMicrotask(()=>d.current?.focus())}finally{s(!1)}}function f(){const h=e.projects.map(g=>g.project_id?.trim()).filter(g=>!!g);if(h.length!==e.projects.length){const g={message:"The original project selection is unavailable. Refresh Projects and try again.",tone:"warning"};fr.set(e.operation_id,g),l(g);return}if(!ea(h,e.person.display_name)){const g={message:"Project sharing is unavailable. Refresh Projects and try again.",tone:"warning"};fr.set(e.operation_id,g),l(g)}}function y(){if(u){if(u.kind==="copy_invite"){p(u.invite_link);return}if(u.kind==="retry_setup"){m();return}f()}}return a("section",{"aria-label":`${Xd(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[a("div",{className:"peer-scope-summary",children:Xd(e.lifecycle.state)}),a("ul",{"aria-label":`${Xd(e.lifecycle.state)} projects`,className:"peer-scope-chips",children:e.projects.map((h,g)=>a("li",{className:"peer-scope-chip",children:h.display_name},`${h.display_name}:${g}`))}),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:y,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 j$({operations:e,...t}){const n=e[0].person,r=M$(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(O$,{operation:i,...t},i.operation_id))]})}function F$(e){return e.operations.length===0?null:a("div",{className:"project-share-person-groups",children:$$(e.operations).map(t=>a(j$,{...e,operations:t},t[0].person.actor_id))})}function B$(e,t){Qe(e,a(F$,{...t}))}function Eb({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 U$(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 G$({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const o=String(e.actor_id||""),s=bs(e),c=C$(o),l=Tb(o),d=l.map(A=>String(A.actor_id||"")).join("|"),[u,p]=I(s),[m,f]=I(!1),[y,h]=I("Rename"),[g,_]=I(!1),[w,S]=I("Merge into selected person"),[T,k]=I(""),[P,E]=I(!1);K(()=>{p(s),f(!1),h("Rename"),_(!1),S("Merge into selected person"),k(""),E(!1)},[o,c,t,s,d]);const M=l.length?k$(T,o):"No other people are available yet. Create another person first if you need to merge duplicates.",U=[{label:"Merge into person",value:""},...l.map(A=>{const $=String(A.actor_id||"");return{label:A.is_local?_s(A):bs(A),value:$}})];async function N(){const A=u.trim();if(!A)return;f(!0),h("Saving…");let $=!1;try{await n(o,A),$=!0}catch{h("Retry rename")}finally{f(!1),$&&h("Rename")}}async function G(){if(!T)return;const A=l.find(L=>String(L.actor_id||"")===T);if(!A||!await Kt({title:`Merge ${s} into ${bs(A)}?`,description:"Assigned devices move now, but older memories keep their current stamped provenance for now.",confirmLabel:"Merge people",cancelLabel:"Keep separate",tone:"danger"}))return;_(!0),S("Merging…");let $=!1;try{await r(T,o),$=!0}catch{S("Retry merge")}finally{_(!1),$&&S("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:_s(e)}),a("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?U$(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(te,{children:[a(we,{"aria-label":`Rename ${s}`,className:"peer-scope-input actor-name-input",disabled:m||g,type:"text",value:u,onInput:A=>p(A.currentTarget.value),onKeyDown:A=>Rr(A,{onSubmit:()=>{N()},disabled:m||g||!u.trim()})}),a("button",{type:"button",className:"settings-button","data-primary-action":"true",disabled:m||g,onClick:()=>{N()},children:y}),a("button",{type:"button",className:"settings-button danger",disabled:m||g,onClick:async()=>{await Kt({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:m||g,onClick:()=>E(A=>!A),children:P?"Hide duplicate cleanup":"Show duplicate cleanup"}),P?a(te,{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(cn,{ariaLabel:`Merge ${s} into another person`,contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:g||l.length===0,itemClassName:"sync-radix-select-item",onValueChange:k,options:U,placeholder:"Merge into person",triggerClassName:"sync-radix-select-trigger sync-actor-select actor-merge-select",value:T,viewportClassName:"sync-radix-select-viewport"}),a("button",{type:"button",className:"settings-button",disabled:g||l.length===0||!T,onClick:()=>{G()},children:w})]}),a("div",{className:"peer-meta actor-merge-note",children:M})]}):null]})})]})}function H$({actors:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){return e.length?a(te,{children:e.map(o=>{const s=String(o.actor_id||o.display_name||o.is_local||"");return a(G$,{actor:o,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):a(Eb,{detail:"Create a named person here, then assign devices below so team ownership stays readable.",title:"No people set up yet."})}function K$(e,t){Qe(e,a(H$,{...t}))}function V$(e){return e.filter(t=>String(t.origin_device_id||"").trim())}function W$(e){const t=e.find(n=>String(n.last_seen_at||"").trim());return t?.last_seen_at?`Detected from older synced memories. Latest memory: ${rr(String(t.last_seen_at).trim())}`:"Detected from older synced memories not yet attached to a current device."}function q$({devices:e}){return a(te,{children:W$(e)})}function z$(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 J$(e){const t=V$(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),Zr(e.mount),Zr(e.meta);return}const n=t.map(z$),r=n.some(i=>i.value===e.value)?e.value:n[0]?.value||"";r!==e.value&&e.onValueChange(r),e.panel.hidden=!1,Qe(e.mount,a(cn,{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"})),Qe(e.meta,a(q$,{devices:t}))}var Y$={online:"Online",offline:"Offline",degraded:"Degraded",attention:"Action required",syncing:"Syncing",unknown:"Status unknown"};function X$({state:e,size:t=8,"aria-label":n}){return a("span",{"aria-label":n??Y$[e],className:`presence-pip presence-pip--${e}`,role:"img",style:`--presence-pip-size: ${t}px`})}function hr({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 Z$(){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 Q$(e){switch(fo(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var ws=null,Ib=0,Zd=new Set;function Rb(e){if(ws!==e){ws=e,Ib+=1;for(const t of Zd)t(Ib)}}function eM(){const[,e]=I(0);return K(()=>(Zd.add(e),()=>{Zd.delete(e)}),[]),ws}var tM={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 nM(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 rM(){window.location.hash="coordinator-admin"}function Qd(e=b.lastCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function iM({peer:e,onAssignActor:t,onRemove:n,onRename:r,onSync:i}){const o=String(e.peer_device_id||""),s=e.name||(o?o.slice(0,8):"unknown"),c=e.name||o||s,l=Qr(e),d=tM[$L(e)],u=e.status||{},p=jL(e),m=Kd(o),f=m&&p.total===0,y=qL(e),h=OL(e),g=lb(e),_=JL(e.project_scope||{}),w=w$(e.addresses),S=Array.isArray(e.addresses)?Array.from(new Set(e.addresses.filter(Boolean).map(ae=>String(ae)))):[],T=Number(e.address_count??0),k=Number.isFinite(T)&&T>0?T:0,P=S.length?S.map(ae=>Ei()?Sb(ae):ae).join(" · "):k>0?`${k} ${k===1?"address":"addresses"} hidden`:"No addresses",E=e.actor_display_name?`This device belongs to ${e.claimed_local_actor?"you":String(e.actor_display_name)}.`:"This device is not assigned to anyone yet.",M=String(u.last_sync_at||u.last_sync_at_utc||""),U=String(u.last_ping_at||u.last_ping_at_utc||""),N=e.discovered_via_group_id?`Discovery: seen through Team ${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,G=v$(o),A=F(null),[$,L]=I(s),[J,H]=I(()=>b.syncPeerFeedbackById.get(o)??null),[x,R]=I(!1),[B,V]=I("Save name"),[he,ue]=I(!1),[ce,be]=I(!1),[Y,ge]=I("Remove device"),[Z,Ce]=I(String(e.actor_id||"")),[le,ee]=I(!1),[xe,pe]=I("Save assignment"),W=Pe(()=>{const ae=T$(Z),Ge=ae.some($n=>$n.value===Z);return Z&&!Ge&&ae.push({value:Z,label:e.claimed_local_actor?"You":String(e.actor_display_name||"Current assignment")}),ae},[e.actor_display_name,e.claimed_local_actor,Z,b.lastSyncActors,b.lastSyncPeers,b.lastSyncViewModel]);K(()=>{m&&p.total>0&&g$(o)},[p.total,o,m]),K(()=>{L(s),H(b.syncPeerFeedbackById.get(o)??null),R(!1),V("Save name"),ue(!1),be(!1),ge("Remove device"),Ce(String(e.actor_id||"")),ee(!1),pe("Save assignment")},[s,e.actor_id,o]),K(()=>{!G||!A.current||queueMicrotask(()=>A.current?.scrollIntoView({block:"center",behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}))},[G]);async function oe(){if(!o)return;const ae=$.trim();if(!ae){const Ge={message:"Enter a friendly name for this device.",tone:"warning"};H(Ge),b.syncPeerFeedbackById.set(o,Ge),document.querySelector(`[data-device-name-input="${CSS.escape(o)}"]`)?.focus();return}R(!0),V("Saving…");try{const Ge=await r(o,ae);H(Ge),b.syncPeerFeedbackById.set(o,Ge),V("Save name")}catch{V("Retry")}finally{R(!1)}}async function Ve(){if(f){const ae=Qd();if(!await Kt({title:`Sync ${s} before advanced rule review?`,description:ae?"This manual sync will use the current Space access and advanced filters until you review them in Teams.":"This manual sync will use the current Space access and advanced filters until a coordinator or manager reviews them in Teams.",confirmLabel:"Sync anyway",cancelLabel:ae?"Review in Teams first":"Cancel"}))return}ue(!0);try{const ae=await i(e,w);H(ae),ae&&b.syncPeerFeedbackById.set(o,ae)}finally{ue(!1)}}async function Me(){if(!o||!await Kt({title:`Remove device ${c}?`,description:"This removes the local record for this paired device on this machine.",confirmLabel:"Remove device",cancelLabel:"Keep device",tone:"danger"}))return;be(!0),ge("Removing…");let ae=!1;try{await n(o,c),ae=!0}catch{ge("Retry remove")}finally{be(!1),ae&&ge("Remove device")}}async function tt(){if(o){ee(!0),pe("Saving…");try{const ae=await t(o,Z||null);H(ae),b.syncPeerFeedbackById.set(o,ae),pe("Save assignment")}catch{pe("Retry")}finally{ee(!1)}}}const un=eM()===o&&o!=="",Lt=`device-drawer-${o||"unknown"}`,kt=Q$(e),$t=M?`Sync: ${rr(M)}`:"Sync: never",nt=Qd(),Mt=`${un?"Collapse":"Expand"} device ${s}`;return a(ga,{asChild:!0,open:un,onOpenChange:ae=>{ae?Rb(o):ws===o&&Rb(null)},children:a("div",{ref:A,className:"peer-card","data-peer-device-id":o||void 0,children:[a(zf,{asChild:!0,children:a("button",{"aria-label":Mt,className:"device-row-head device-row-head--trigger",type:"button",children:[a(X$,{state:kt}),a("span",{className:"device-row-name",title:o||void 0,children:s}),d?a("span",{"aria-label":d.label,className:"peer-direction",role:"img",title:d.label,children:d.glyph}):null,a("span",{className:"device-row-chips",children:[a("span",{className:`badge ${l.isWarning?"badge-offline":"badge-online"}`,children:l.badgeLabel}),f?a("span",{className:"badge actor-badge",children:"Review advanced rules"}):null,a("span",{className:`badge ${p.isWarning?"badge-offline":"actor-badge"}`,title:"Spaces are the hard access boundary; advanced filters only narrow inside them.",children:p.badgeLabel}),h.badgeLabel?a("span",{className:"badge badge-offline",title:"Inbound ops rejected by the sharing-domain scope gate. Expand for reason codes.",children:h.badgeLabel}):null,y.badgeLabel?a("span",{className:"badge badge-offline",title:"Review whether explicit Space access matches this device's intended role.",children:y.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:$t}),a("span",{"aria-hidden":"true",className:"device-row-chevron",children:a(Z$,{})})]})}),a(va,{"aria-label":`Device actions for ${s}`,className:"device-row-drawer",id:Lt,children:[a("div",{className:"peer-actions",children:[a("button",{type:"button",className:"settings-button",disabled:he,onClick:()=>{Ve()},title:w?void 0:"Address details are hidden; sync will target this device by ID.",children:he?"Syncing…":"Sync now"}),a("div",{className:"sync-labeled-field",children:[a("label",{className:"sync-labeled-field-caption",htmlFor:`device-name-${o||"unknown"}`,children:"Device name"}),a(we,{"aria-label":`Friendly name for ${s}`,className:"peer-scope-input","data-device-name-input":o||void 0,disabled:x,id:`device-name-${o||"unknown"}`,placeholder:"Friendly device name",type:"text",value:$,onInput:ae=>L(ae.currentTarget.value)})]}),a("button",{type:"button",className:"settings-button",disabled:x,onClick:()=>{oe()},children:B}),a("button",{type:"button",className:"settings-button danger",disabled:ce,onClick:()=>{Me()},children:Y})]}),a("div",{className:"peer-scope",children:[G?a("div",{className:"peer-meta",children:nt?"Review this device's Space access and advanced rules in Teams if the defaults are too broad.":"A coordinator or manager can review this device's Space access and advanced rules in Teams 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:P}),N?a("div",{className:"peer-meta",children:N}):null,a("div",{className:"peer-meta",children:[M?`Sync: ${rr(M)}`:"Sync: never",U?`Ping: ${rr(U)}`:"Ping: never"].join(" · ")}),a("div",{className:"peer-scope-summary",children:"Space access"}),a("div",{className:"peer-meta",children:p.total>0?"These Spaces are the hard access boundary for this device.":p.emptyMessage}),p.domains.length>0?a("ul",{className:"peer-scope-chips","aria-label":"Authorized Spaces",children:p.domains.map(ae=>a("li",{className:"peer-scope-chip",title:ae.detail,children:ae.label},ae.scopeId))}):null,y.isVisible?a("div",{className:"settings-note",role:"status",children:[a("strong",{children:y.title}),a("div",{children:y.message}),a("div",{children:y.detail})]}):null,a("div",{className:"peer-meta",children:_.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(ae=>a("li",{title:ae.detail,children:[a("span",{className:"peer-scope-rejection-label",children:ae.label}),a("span",{className:`badge ${ae.status==="received"?"badge-online":"actor-badge"}`,children:ae.badgeLabel})]},ae.scopeId))}):null,h.total>0?a("div",{className:"peer-scope-rejections","data-peer-rejection-count":h.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:h.reasons.map(ae=>a("li",{children:[a("span",{className:"peer-scope-rejection-label",children:ae.label}),a("span",{className:"peer-scope-rejection-count",children:ae.count.toLocaleString()})]},ae.reason))}),h.lastAt?a("div",{className:"peer-meta",children:["Last rejected ",rr(h.lastAt)]}):null]}):null,a("div",{className:"peer-scope-summary",children:"Who this device belongs to"}),a("div",{className:"peer-meta",children:E}),e.claimed_local_actor?a("div",{className:"peer-meta",children:nM(e.claimed_local_actor_scope)}):null,a("div",{className:"peer-actor-row",children:[a("div",{className:"sync-radix-select-host sync-actor-select-host",children:a(cn,{ariaLabel:`Assigned person for ${s}`,contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:le,itemClassName:"sync-radix-select-item",onValueChange:Ce,options:W,placeholder:"No person assigned yet",triggerClassName:"sync-radix-select-trigger sync-actor-select",value:Z,viewportClassName:"sync-radix-select-viewport"})}),a("button",{type:"button",className:"settings-button",disabled:le,onClick:()=>{tt()},children:xe})]}),a("div",{className:"peer-scope-summary",children:"Advanced sharing rules"}),a("div",{className:"peer-meta",children:[_.statusLabel,". ",_.summary," ",_.note]}),nt?a("div",{className:"peer-actions",children:a("button",{type:"button",className:"settings-button",onClick:rM,children:"Manage Spaces in Teams"})}):a("div",{className:"peer-meta",children:"Space access is managed in Teams by a coordinator or manager."}),a(hr,{feedback:J})]})]})]})})}function oM(e){const t=b.syncPeersSectionFeedback,n=b.lastSyncStatus,r=n?.daemon_state==="disabled"||n?.enabled===!1;return e.peers.length?a(te,{children:[a(hr,{feedback:t}),e.peers.map(i=>{const o=String(i.peer_device_id||i.name||"unknown-peer");return a(iM,{peer:i,...e},o)})]}):a(te,{children:[a(hr,{feedback:t}),a(Eb,{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 aM(e,t){Qe(e,a(oM,{...t}))}var dn=async()=>{},Ss="";function eu(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function sM(e){dn=e}function cM(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;Rn("syncActorsSkeleton"),eu(!1);const n=pb({actors:b.lastSyncActors,peers:b.lastSyncPeers,duplicatePeople:b.lastSyncViewModel?.duplicatePeople}),r=n.visibleActors;t&&(t.textContent=r.length?"Manage people here, then assign devices below.":"No named people yet. Create a person here, then assign devices below so sync ownership is easier to review.",n.hiddenLocalDuplicateCount>0&&(t.textContent+=` ${n.hiddenLocalDuplicateCount} unresolved duplicate ${n.hiddenLocalDuplicateCount===1?"entry is":"entries are"} hidden here until reviewed in Needs attention.`)),K$(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,o)=>{await yw(i,o),await dn()},onMerge:async(i,o)=>{try{await Hu(i,o),ne("People combined. Assigned devices moved to the selected person."),await dn()}catch(s){throw ne(et(s,"Failed to combine people."),"warning"),s}},onDeactivate:async i=>{try{await bw(i),ne("Person removed. Assigned devices have been unassigned."),await dn()}catch(o){throw ne(et(o,"Failed to remove person."),"warning"),o}}})}function lM(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");eu(!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&&mr(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. When the people endpoint responds again, named people will reload here."})}function dM(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;B$(e,{operations:b.lastShareOperations,onAdvance:n=>cw(n),onLoadOperation:n=>sw(n),onReload:dn});const t=document.getElementById("syncProjectShareOperationsMeta");t&&(t.textContent=b.shareOperationsLoadError?"Project sharing status could not be refreshed. Existing device diagnostics remain available below.":b.lastShareOperations.length>0?"Project access is grouped by Person. Devices appear after invitation acceptance.":"Share a project from Projects to invite a teammate.")}function tu(){const e=document.getElementById("syncPeers");if(!e)return;Rn("syncPeersSkeleton");const t=b.lastSyncPeers,n=Array.isArray(t)?t:[];S$(b.syncPeersSectionFeedback,n)&&(b.syncPeersSectionFeedback=null),aM(e,{peers:n,onRename:async(r,i)=>{try{return await Mu(r,i),await dn(),{message:"Device name saved.",tone:"success"}}catch(o){return{message:et(o,"Failed to save device name."),tone:"warning"}}},onSync:async(r,i)=>{try{const o=String(r?.peer_device_id||""),s=ib(await Gs({address:i,peerDeviceId:o||void 0}));let c;s.ok?o&&Kd(o)?c={message:`Triggered sync for ${r?.name||(o?o.slice(0,8):"unknown")}. ${Qd()?"Review Space access and advanced rules in Teams if this device needs tighter sharing.":"A coordinator or manager can review Space access and advanced rules in Teams if this device needs tighter sharing."}`,tone:"warning"}:c={message:s.message,tone:"success"}:c={message:s.message,tone:"warning"};try{await dn()}catch{c={message:"Sync started, but this view has not refreshed yet. Refresh the page or use Sync now again before retrying.",tone:"warning"}}return c}catch(o){return{message:et(o,"Failed to trigger sync."),tone:"warning"}}},onRemove:async(r,i)=>{try{await $u(r);const o={message:`Removed peer ${i}.`,tone:"success"};return b.syncPeerFeedbackById.delete(r),b.syncPeersSectionFeedback={...o,relatedPeerDeviceId:r},await dn(),o}catch(o){return{message:et(o,"Failed to remove peer. The local peer entry is still here."),tone:"warning"}}},onAssignActor:async(r,i)=>{try{return await Y_(r,i),await dn(),{message:i?"Device assignment updated.":"Device assignment cleared.",tone:"success"}}catch(o){return{message:et(o,"Failed to update device assignment. The current assignment is unchanged."),tone:"warning"}}}})}function uM(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");eu(!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&&mr(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&&mr(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, assign, or re-pair them."})}function Db(){const e=document.getElementById("syncLegacyClaims"),t=document.getElementById("syncLegacyDeviceSelectMount"),n=document.getElementById("syncLegacyClaimsMeta");!e||!t||!n||J$({devices:Array.isArray(b.lastSyncLegacyDevices)?b.lastSyncLegacyDevices:[],meta:n,mount:t,onValueChange:r=>{r!==Ss&&(Ss=r,Db())},panel:e,value:Ss})}function pM(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput"),r=document.getElementById("syncLegacyClaimButton");n?.addEventListener("keydown",i=>{Rr(i,{onSubmit:()=>t?.click(),disabled:!t||t.disabled})}),t?.addEventListener("click",async()=>{if(!t||!n)return;const i=String(n.value||"").trim();if(!i){ti(n,"Enter a name for the person.");return}ho(n),t.disabled=!0,n.disabled=!0,t.textContent="Creating…";try{await vw(i),ne("Person created."),n.value="",await e()}catch(o){ne(et(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(Ss||"").trim();if(!i||!r||!await Kt({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 _w(i),ne("Old device history attached to you."),await e()}catch(s){ne(et(s,"Failed to attach old device history."),"warning"),r.textContent="Retry",r.disabled=!1;return}r.textContent=o,r.disabled=!1})}function mM(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function nu(e=mM()){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 Lb=!1;function fM(){Lb||(Lb=!0,window.addEventListener("hashchange",()=>{nu()}))}var zt={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function hM(e){zt.loadSyncData=e}var gM=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function vM(){const e=document.getElementById("syncCreateInviteButton"),t=document.getElementById("syncInviteAdminHint");if(!e||!t)return;const n=b.lastCoordinatorAdminStatus?.readiness,r=String(b.lastCoordinatorAdminStatus?.active_group||"").trim();if(n==="ready"){e.disabled=!1,t.hidden=!1,t.textContent=r?`Teams is ready for ${r}. Advanced admin tools now live in Teams.`:"Teams is ready. Advanced admin tools now live in Teams.";return}const i=n==="partial"?"Finish Teams setup before creating remote invites. Use Teams to check what is missing.":"Configure a coordinator URL, Team, and admin secret before creating remote invites. Use Teams to finish setup.";e.disabled=!0,t.hidden=!1,t.textContent=i}function ru(){const e=document.getElementById("syncAdminDisclosureMount");e&&TL(e,{open:vb,onOpenChange:t=>{u$(t),ru(),Ts(),iu()}})}function yM(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function iu(){const e=document.getElementById("syncInviteOutput"),t=document.getElementById("syncInviteWarnings");if(!e)return;const n=String(b.lastTeamInvite?.encoded||"").trim();if(e.value=n,e.hidden=!n,t){const r=Array.isArray(b.lastTeamInvite?.warnings)?b.lastTeamInvite.warnings:[];t.textContent=r.join(" · "),t.hidden=r.length===0}}function Cs(){const e=document.getElementById("syncJoinFeedback");if(!e)return;const t=b.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 Ts(){const e=document.getElementById("syncInvitePolicyMount");e&&Qe(e,v(cn,{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!==zt.invitePolicy&&(zt.invitePolicy=n,Ts())},options:gM,triggerClassName:"sync-radix-select-trigger sync-actor-select",value:zt.invitePolicy,viewportClassName:"sync-radix-select-viewport"}))}function bM(e,t){ru(),Ts();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"),m=document.getElementById("syncProjectInviteReviewHeading"),f=document.getElementById("syncRecipientName"),y=document.getElementById("syncRecipientDeviceName");let h="",g=0;r?.addEventListener("click",()=>{ea()||ne("Project sharing is unavailable. Refresh Projects and try again.","warning")});const _=async(w,S)=>{if(!u||!f||!y)return"other";const T=await Lu(w);if(S!==g||d?.value.trim()!==w)return"stale";if(T.kind!=="project_share_invite")return"other";const k=(T.projects??[]).map(P=>`${P.display_name} (${P.existing_memory_count} existing ${P.existing_memory_count===1?"memory":"memories"})`).join(", ");return p&&(p.textContent=`${T.inviter_name||"A teammate"} invited you${T.team_name?` through ${T.team_name}`:""} to share ${k||"selected projects"}.`),f.value=T.recipient_name??"",y.value=T.device_name??"",u.hidden=!1,h=w,l&&(l.textContent="Accept and start syncing"),m?.focus(),"project"};d?.addEventListener("input",()=>{g+=1,d.value.trim()!==h&&(h="",u&&(u.hidden=!0),l&&(l.textContent="Review invite"))}),i?.addEventListener("click",async()=>{if(!i||!o||!s||!c||i.disabled)return;const w=o.value.trim(),S=Number(s.value);let T=!0;if(w?ho(o):T=ti(o,"Team name is required."),!S||S<1?T=ti(s,"Must be at least 1 hour."):ho(s),!!T){i.disabled=!0,i.textContent="Creating…";try{const k=await Iu({group_id:w,policy:zt.invitePolicy,ttl_hours:S||24});b.lastTeamInvite=k,iu(),c.value=String(k.encoded||""),c.hidden=!1,c.focus(),c.select();const P=Array.isArray(k.warnings)?k.warnings:[];ne(P.length?`Invite created. Copy it above and review ${P.length===1?"1 warning":`${P.length} warnings`}.`:"Invite created. Copy the text above and share it with your teammate.",P.length?"warning":"success")}catch(k){ne(et(k,"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",w=>{Rr(w,{onSubmit:()=>l?.click(),disabled:!l||l.disabled})}),l?.addEventListener("click",async()=>{if(!l||!d)return;const w=d.value.trim();if(!w){ti(d,"Paste a team invite or pairing payload.");return}if(ho(d),h!==w){const T=g;try{const k=await _(w,T);if(k==="project"||k==="stale")return}catch{}if(T!==g||d.value.trim()!==w)return;h=w,l.textContent="Accept invite";return}const S=u&&!u.hidden?{recipient_name:f?.value.trim()??"",device_name:y?.value.trim()??""}:void 0;if(S){const T=k=>!k||[...k].length>120||[...k].some(P=>/[\p{Cc}\p{Cf}]/u.test(P));if(T(S.recipient_name)){f&&ti(f,"Enter a valid name using 120 characters or fewer.");return}if(T(S.device_name)){y&&ti(y,"Enter a valid device name using 120 characters or fewer.");return}}l.disabled=!0,l.textContent="Accepting…";try{const T=await Fs(w,S);b.lastTeamJoin=T;const k=T,P=typeof k.type=="string"?k.type:"team_join";let E;if(P==="pair"){const M=String(T.peer_device_id??"").trim();E={message:M?`Paired with device ${M.slice(0,8)}. It will appear in People & devices.`:"Paired the device. It will appear in People & devices.",tone:"success"}}else if(P==="project_share"){const M=k.restart_required===!0||k.setup_state==="pending_inviter"||T.status==="pending_setup",U=typeof k.detail=="string"?k.detail.trim():"";E=M?{message:U||(k.restart_required===!0?"Project invitation accepted. Restart codemem to finish setup.":k.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 E={message:T.status==="pending"?"Join request sent. Waiting for admin approval.":"Joined the team.",tone:"success"};b.syncJoinFlowFeedback=E,Cs(),d.value="",h="",u&&(u.hidden=!0);try{await t()}catch(M){E={message:et(M,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},b.syncJoinFlowFeedback=E,Cs()}}catch(T){b.syncJoinFlowFeedback={message:et(T,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},Cs(),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 w=ib(await Gs());ne(w.message,w.warning?"warning":void 0)}catch(w){ne(et(w,"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 ou({element:e,hidden:t=!1,restoreParent:n=null}){const r=F(null);return gt(()=>{e&&(e.hidden=t)},[e,t]),gt(()=>{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 _M({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:r}){return a(te,{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(ou,{element:e,hidden:!t,restoreParent:n}):null]})}function wM(){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=>Pi("codemem sync pair --payload-only",e.currentTarget),children:"Copy pairing command"})]})}function SM({joinPanel:e,joinPanelOpen:t,joinRestoreParent:n,onToggle:r}){return a(te,{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(ou,{element:e,hidden:!t,restoreParent:n}):null]})}function CM({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(te,{children:[u?a(te,{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(ou,{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(te,{children:[a(SM,{joinPanel:r,joinPanelOpen:i,joinRestoreParent:o,onToggle:c}),a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),u?null:a(_M,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:s}),!l&&d==="posted"?a(wM,{}):null]})}function ks({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 Ns({children:e}){return a("div",{className:"section-meta sync-section-note",children:e})}function TM({item:e,onAction:t}){const[n,r]=I(!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 kM({request:e,onApprove:t,onDeny:n}){const[r,i]=I(null),[o,s]=I(null),[c,l]=I("Approve"),[d,u]=I("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(hr,{feedback:o})]})}function NM({row:e,onInspectConflict:t,onRemoveConflict:n,onReview:r}){const[i,o]=I(null),[s,c]=I(null),l=e.actionLabel||"Pair with this device",[d,u]=I(l),[p,m]=I("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{c(await r(e)||null),u(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==="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(te,{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"),m("Removing…");try{c(await n(e)||null),m("Remove broken device record")}catch{m("Retry")}finally{o(null)}},children:p})]}):null]}),a(hr,{feedback:s})]})}function xM(e){const t=e.actionItems.length>0,n=e.actionableCount>e.actionItems.length,r=t||n||e.primaryStatus.state!=="healthy";return a(te,{children:[r?a(ks,{label:"Needs attention"}):null,r?a(Ns,{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(TM,{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 PM({children:e}){return e?a(te,{children:[a(ks,{label:"Add devices & teammates"}),a(Ns,{children:"Use these flows when you are enrolling, inviting, or pairing something new."}),e]}):null}function AM({mount:e,rows:t,onInspectConflict:n,onRemoveConflict:r,onReview:i}){return!e||!t.length&&!b.syncDiscoveredFeedback?null:en(a(te,{children:[a(ks,{count:t.length||void 0,label:"Devices waiting for review"}),a(Ns,{children:"Review team devices here when they still need trust, re-pairing, or approval on this machine."}),a(hr,{feedback:b.syncDiscoveredFeedback}),t.map(o=>a(NM,{row:o,onInspectConflict:n,onRemoveConflict:r,onReview:i},o.deviceId))]}),e)}function EM({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!b.syncJoinRequestsFeedback?null:en(a(te,{children:[a(ks,{count:t.length||void 0,label:"Join requests to review"}),a(Ns,{children:"Approve or deny requests here before those devices become part of the team."}),a(hr,{feedback:b.syncJoinRequestsFeedback}),t.map(i=>a(kM,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function $b(e){return a(te,{children:[a(xM,{...e}),a(PM,{children:e.children}),a(EM,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),a(AM,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function Mb(e){e&&(e.textContent="")}function xs(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 IM(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function go(){return IM()?"auto":"smooth"}var au="syncTeamActionsMount";function RM(e,t,n=!1){return e.length>1&&(!t||n)}function DM(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 LM(e,t){const n=document.createElement("div");n.id=au,e.appendChild(n),Qe(n,v($b,{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 Ob(e,t){const n=document.getElementById(au);n&&(Zr(n),n.remove()),Mb(e),t.forEach(r=>{Mb(r)})}function Ps(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;ru(),Ts(),iu(),Cs(),vM();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");Rn("syncTeamSkeleton"),yM();const p=b.lastSyncCoordinator,m=b.lastSyncViewModel||{primaryStatus:fb({status:b.lastSyncStatus,coordinator:p,peers:b.lastSyncPeers,shareOperations:b.lastShareOperations,shareOperationsLoadError:b.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]},f=A=>{if(A.kind==="possible-duplicate-person"){const H=document.getElementById("syncActorsList");H instanceof HTMLElement&&(H.scrollIntoView({block:"center",behavior:go()}),xs(H));return}const $=String(A.deviceId||"").trim();if(!$)return;if(A.kind==="name-device"){const H=document.querySelector(`[data-device-name-input="${CSS.escape($)}"]`);if(H instanceof HTMLInputElement){H.scrollIntoView({block:"center",behavior:go()}),H.focus(),H.select(),xs(H);return}}const L=document.querySelector(`[data-peer-device-id="${CSS.escape($)}"]`);if(L instanceof HTMLElement){L.scrollIntoView({block:"center",behavior:go()}),xs(L);return}const J=document.querySelector(`[data-discovered-device-id="${CSS.escape($)}"]`);J instanceof HTMLElement&&(J.scrollIntoView({block:"center",behavior:go()}),xs(J))},y=async A=>{const $=Array.isArray(A.actorIds)?A.actorIds.map(R=>String(R||"").trim()).filter(Boolean):[],L=(Array.isArray(b.lastSyncActors)?b.lastSyncActors:[]).filter(R=>$.includes(String(R?.actor_id||"").trim()));if(L.length<2){ne("This duplicate review is outdated. Refresh the card and review the remaining people entries.","warning");return}const J=await CP({title:"Review possible duplicate people",summary:A.title.replace(/^Possible duplicate person:\s*/,""),actors:L.map(R=>({actorId:String(R?.actor_id||""),label:String(R?.display_name||R?.actor_id||"Unknown person"),isLocal:!!R?.is_local}))});if(J.action==="different-people"){b$($,"different-people"),ne("Okay. I will keep these people separate on this device."),await zt.loadSyncData();return}if(J.action!=="merge")return;const H=L.find(R=>String(R?.actor_id||"")===J.primaryActorId),x=L.find(R=>String(R?.actor_id||"")===J.secondaryActorId);if(!H?.actor_id||!x?.actor_id){ne("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await Hu(String(H.actor_id),String(x.actor_id)),_$($),ne(`Combined duplicate people into ${String(H.display_name||H.actor_id)}.`),await zt.loadSyncData()}catch(R){try{await zt.loadSyncData()}catch{}ne(et(R,"Failed to combine these people."),"warning")}},h=async A=>await El({title:"Pair with this device",description:"Choose a friendly name for this device before pairing it on this machine.",initialValue:A,placeholder:"Desk Mini",confirmLabel:"Pair",cancelLabel:"Cancel",validate:$=>$.trim()?null:"Enter a device name to pair this device."}),g=!!p?.configured,_=c$(p);e.title=g?String(p.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?DM(w,e,m.primaryStatus):e.textContent=m.primaryStatus.meta,!g){Ob(n,[c,u]),t.hidden=!1,n.hidden=!1,LM(n,m.primaryStatus),c&&(c.hidden=!0),l&&(l.hidden=!0);return}t.hidden=!0,n.hidden=!1;const S=String(p.presence_status||""),T=Array.isArray(b.lastSyncPeers)?b.lastSyncPeers:[],k=Array.isArray(m.attentionItems)?m.attentionItems:[],P=(Array.isArray(p.discovered_devices)?p.discovered_devices:[]).map(A=>{const $=String(A.device_id||"").trim(),L=ab({coordinatorName:String(A.display_name||"").trim(),deviceId:$})||"Discovered device",J=$&&L!==$?$:null,H=String(A.fingerprint||"").trim(),x=Array.isArray(A.groups)?A.groups.map(xe=>String(xe||"").trim()).filter(Boolean):[],R=T.find(xe=>String(xe?.peer_device_id||"")===$),B=RM(x,!!R,A.needs_local_approval===!0),V=rb({device:A,pairedLocally:!!R}),he=String(R?.fingerprint||"").trim(),ue=!!R&&!!H&&!!he&&he!==H,ce=!_&&AL({device:A,hasAmbiguousCoordinatorGroup:B,pairedLocally:!!R}),be=Array.isArray(A.addresses)?A.addresses:[],Y=Number(A.address_count??0),ge=Number.isFinite(Y)&&Y>0?Y:0,Z=[be.length?be.map(xe=>Ei()?Sb(String(xe||"")):String(xe||"")).filter(Boolean).join(" · "):ge>0?`${ge} ${A.stale?"last-known":"fresh"} ${ge===1?"address":"addresses"} hidden`:"No fresh addresses"];!be.length&&J&&Z.push(`device id: ${$}`);let Ce=null,le=ce?"accept":"none",ee=null;return ue?le="conflict":_&&(!R||V.state==="needs-your-approval")?(Ce=_.message,le="setup-blocked"):B?(Ce="This device appears in multiple coordinator groups. Review the Team setup before approving it here.",le="ambiguous"):R&&Kd($)?(Ce="Review this device's Space access and advanced rules in Teams before you sync it.",le="scope-pending"):R?.last_error?(Z.push(`error: ${String(R.last_error)}`),ce||(le="paired")):R?.status?.peer_state?(Z.push(`status: ${String(R.status.peer_state)}`),ce||(le="paired")):!R&&A.stale?(Ce="Wait for a fresh coordinator presence update, then review this device again here.",le="stale"):R&&!ce&&(le="paired"),le==="paired"&&(ee=V.state==="waiting-for-other-device"?V.description||"Waiting on the other device.":String(R?.last_error||"").toLowerCase().includes("401")&&String(R?.last_error||"").toLowerCase().includes("unauthorized")?"Waiting for the other device to trust this one before sync can work.":null),{actionMessage:Ce,actionLabel:V.actionLabel||(R?"Review device":"Pair with this device"),approvalBadgeLabel:V.badgeLabel,availabilityLabel:A.stale?"Offline":"Available",connectionLabel:ue?gb.conflicts:R?gb.pairedLocally:"Not connected on this device",deviceId:$,displayName:L,displayTitle:J,fingerprint:H,mode:le,note:Z.join(" · "),pairedMessage:ee}}),E=[],M=P.filter(A=>A.mode!=="paired"&&A.mode!=="none"&&A.mode!=="scope-pending"),U=P.filter(A=>A.mode==="accept"||A.mode==="scope-pending").length,N=k.length+E.length+U;l&&(l.hidden=M.length===0&&!b.syncDiscoveredFeedback),d&&(d.textContent=M.length?"Pair with a teammate's device to see it appear in People & devices and start syncing.":""),c&&(c.hidden=E.length===0&&!b.syncJoinRequestsFeedback),Ob(n,[c,u]);const G=document.createElement("div");G.id=au,n.appendChild(G),Qe(G,v($b,{actionItems:k,actionableCount:N,children:v(CM,{invitePanel:r,invitePanelOpen:Bd,inviteRestoreParent:i,joinPanel:o,joinPanelOpen:Ud,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(p$(!Bd),Ps())},onToggleJoinPanel:()=>{o&&(m$(!Ud),Ps())},pairedPeerCount:Number(p.paired_peer_count||0),presenceStatus:S}),discoveredListMount:u,discoveredRows:M,joinRequestsMount:c,onApproveJoinRequest:async()=>null,onAttentionAction:async A=>{if(A.kind==="possible-duplicate-person"){await y(A);return}f(A)},onDenyJoinRequest:async()=>null,onInspectConflict:A=>{const $=document.querySelector(`[data-peer-device-id="${CSS.escape(A.deviceId)}"]`);if($ instanceof HTMLElement){$.scrollIntoView({block:"center",behavior:go()}),ne(`Opened the conflicting local device record for ${A.displayName}.`,"warning");return}ne("The conflicting local device record is not visible yet. Scroll to People & devices and try again.","warning")},onRemoveConflict:async A=>{if(!await Kt({title:`Remove ${A.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 $u(A.deviceId);const $={message:`Removed the broken local device record for ${A.displayName}. If it is still available, review it again from Next steps or Devices seen on team.`,tone:"success"};return b.syncDiscoveredFeedback=$,await zt.loadSyncData(),$}catch($){return{message:et($,"Failed to remove the broken local device record. The old local record is still present in People & devices."),tone:"warning"}}},onReviewDiscoveredDevice:async A=>{try{const $=await h(A.displayName);if(!$)return null;const L=await X_(A.deviceId,A.fingerprint),J=String(L?.name||A.displayName||"").trim()||A.displayName;b.pendingAcceptedSyncPeers=[...Array.isArray(b.pendingAcceptedSyncPeers)?b.pendingAcceptedSyncPeers.filter(x=>String(x?.peer_device_id||"").trim()!==A.deviceId):[],{peer_device_id:A.deviceId,name:J,fingerprint:A.fingerprint,addresses:[],claimed_local_actor:!1,status:{peer_state:"degraded"},last_error:"Waiting for the other device to approve this one."}],h$(A.deviceId);let H={message:A.approvalBadgeLabel==="Needs your approval"?`Approved ${A.displayName} on this device. Two-way trust should be ready once both devices refresh.`:`Step 1 complete on this device for ${A.displayName}. Finish onboarding on the other device so both sides trust each other for sync.`,tone:"success"};try{$.trim()!==J.trim()&&(await Mu(A.deviceId,$.trim()),b.pendingAcceptedSyncPeers=b.pendingAcceptedSyncPeers.map(x=>String(x?.peer_device_id||"").trim()===A.deviceId?{...x,name:$.trim()}:x),H={message:`Connected ${$.trim()} and saved its name.`,tone:"success"})}catch(x){H={message:et(x,"Device connected, but naming did not finish."),tone:"warning"}}b.syncDiscoveredFeedback=H;try{await zt.loadSyncData()}catch(x){H={message:et(x,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},b.syncDiscoveredFeedback=H}return H}catch($){return{message:et($,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:E,presenceStatus:S,primaryStatus:m.primaryStatus}))}function $M(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 ni(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function jb(e){return ni(e)?"Unclear project identity":e.displayProject}function Tt(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function MM(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function OM(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jM(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function FM(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function BM(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 UM(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function GM({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"," · ",BM(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:UM(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 Fb(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${OM(t)}\\b`,"g"),jM(t,n))),r}function HM(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 KM({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 VM({item:e,onReassign:t,onReview:n}){const r=e.groups??[],i=e.targetScopes??[],o=Object.fromEntries(r.map(x=>[x.workspaceIdentity,x.suggestedScopeId??""])),[s,c]=I({}),[l,d]=I({}),[u,p]=I(o),[m,f]=I({}),[y,h]=I("all"),[g,_]=I(""),[w,S]=I(null),T=r.length,k=e.totalGroupCount??T,P=r.filter(ni).length,E=r.filter(x=>x.suggestedScopeId&&!ni(x)&&Tt(x)).length,M=r.filter(x=>m[x.workspaceIdentity]&&Tt(x)).length,U=r.filter(x=>m[x.workspaceIdentity]&&Tt(x)&&!!u[x.workspaceIdentity]).length,N=r.filter(x=>{const R=ni(x);return y==="suggested"&&(!x.suggestedScopeId||R)||y==="cleanup"&&!R||y==="no-suggestion"&&(x.suggestedScopeId||R)||y==="selected"&&!m[x.workspaceIdentity]?!1:!g.trim()||HM(x,i).includes(g.trim().toLowerCase())});async function G(x){const R=u[x.workspaceIdentity]||x.suggestedScopeId||"";if(!(!R||!t||w)){S(x.workspaceIdentity),d(B=>{const V={...B};return delete V[x.workspaceIdentity],V});try{const B=await t(x,R,!!s[x.workspaceIdentity],s[x.workspaceIdentity]?.confirmation_token);c(B?V=>({...V,[x.workspaceIdentity]:B}):V=>{const he={...V};return delete he[x.workspaceIdentity],he})}catch(B){d(V=>({...V,[x.workspaceIdentity]:Fb(B,R,i)}))}finally{S(null)}}}function A(x,R){p(B=>({...B,[x.workspaceIdentity]:R})),c(B=>{const V={...B};return delete V[x.workspaceIdentity],V}),d(B=>{const V={...B};return delete V[x.workspaceIdentity],V})}function $(x,R){f(B=>({...B,[x.workspaceIdentity]:R}))}function L(x){f(R=>({...R,...Object.fromEntries(N.filter(Tt).map(B=>[B.workspaceIdentity,x]))}))}function J(){f(x=>({...x,...Object.fromEntries(r.filter(R=>R.suggestedScopeId&&!ni(R)&&Tt(R)).map(R=>[R.workspaceIdentity,!0]))}))}async function H(){if(!t||w||U===0)return;const x=r.filter(R=>m[R.workspaceIdentity]&&Tt(R)&&!!u[R.workspaceIdentity]);if(!x.every(R=>s[R.workspaceIdentity])){S("bulk");try{for(const R of x){if(s[R.workspaceIdentity])continue;const B=u[R.workspaceIdentity]||R.suggestedScopeId||"";if(B)try{const V=await t(R,B,!1);d(he=>{const ue={...he};return delete ue[R.workspaceIdentity],ue}),V&&c(he=>({...he,[R.workspaceIdentity]:V}))}catch(V){d(he=>({...he,[R.workspaceIdentity]:Fb(V,B,i)}))}}}finally{S(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:[k.toLocaleString()," older"," ",k===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",T<k?` Showing ${T.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 ${T.toLocaleString()}`],["suggested",`Suggested ${E.toLocaleString()}`],["cleanup",`Needs cleanup ${P.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${U.toLocaleString()}`]].map(([x,R])=>a("button",{className:y===x?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>h(x),type:"button",children:R},x))}),a("div",{className:"legacy-review-bulk-row",children:[a("input",{"aria-label":"Search legacy project groups",className:"peer-scope-input legacy-review-search",onInput:x=>_(x.currentTarget.value),placeholder:"Search project, signal, or destination…",value:g}),a("button",{className:"settings-button",onClick:()=>L(!0),type:"button",children:"Select visible"}),a("button",{className:"settings-button",onClick:J,type:"button",children:"Select suggested"}),a("button",{className:"settings-button",onClick:()=>L(!1),type:"button",children:"Clear visible"}),t&&i.length>0?a("button",{className:"settings-save",disabled:w!=null||U===0||r.filter(x=>m[x.workspaceIdentity]&&Tt(x)&&!!u[x.workspaceIdentity]).every(x=>s[x.workspaceIdentity]),onClick:()=>{H()},type:"button",children:w==="bulk"?"Previewing…":`Preview ${U.toLocaleString()} selected`}):t&&M>0?a("span",{className:"legacy-review-cleanup-note",children:"Add or join a Space before bulk reassignment."}):null,U>0&&r.filter(x=>m[x.workspaceIdentity]&&Tt(x)&&!!u[x.workspaceIdentity]).every(x=>s[x.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(x=>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 ${jb(x)}`,checked:!!m[x.workspaceIdentity],className:"cm-checkbox",disabled:!Tt(x),onChange:R=>$(x,R.currentTarget.checked),type:"checkbox"}),a("div",{children:[a("div",{className:"legacy-review-group-title",children:jb(x)}),a("div",{className:"legacy-review-group-meta",children:[$M(x.identitySource),MM(x,i)]}),Tt(x)?x.peerOwnedMemoryCount?a("div",{className:"legacy-review-cleanup-note",children:[(x.reassignableMemoryCount??x.memoryCount).toLocaleString()," ","local memor",(x.reassignableMemoryCount??x.memoryCount)===1?"y":"ies"," ","can be reassigned; ",x.peerOwnedMemoryCount.toLocaleString()," peer-owned memor",x.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."}),ni(x)?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:[x.memoryCount.toLocaleString()," memor",x.memoryCount===1?"y":"ies"]})]}),x.suggestionReason?a("div",{className:"legacy-review-reason",children:x.suggestionReason}):null,l[x.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:l[x.workspaceIdentity]}):null,s[x.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:[s[x.workspaceIdentity].warning," This will reassign"," ",s[x.workspaceIdentity].reassignable_memory_count.toLocaleString()," of"," ",s[x.workspaceIdentity].memory_count.toLocaleString()," memories",s[x.workspaceIdentity].skipped_memory_count?`; ${s[x.workspaceIdentity].skipped_memory_count.toLocaleString()} peer-owned copies will be left unchanged`:"","."]}):null,a(GM,{group:x}),i.length>0&&t&&Tt(x)?a("label",{className:"legacy-review-target",children:[a("span",{children:"Destination Space"}),a("select",{className:"peer-scope-input",disabled:w!=null,onChange:R=>A(x,R.currentTarget.value),value:u[x.workspaceIdentity]||"",children:[a("option",{value:"",children:"Choose Space…"}),i.map(R=>a("option",{value:R.scopeId,children:[R.label," · ",FM(R.authorityType),R.scopeId===x.suggestedScopeId?" · suggested":""]},R.scopeId))]})]}):null,i.length>0&&t&&Tt(x)?a("div",{className:"legacy-review-actions",children:a("button",{type:"button",className:"settings-button",disabled:w!=null||!u[x.workspaceIdentity],onClick:()=>{G(x)},children:w===x.workspaceIdentity?s[x.workspaceIdentity]?"Reassigning…":"Previewing…":s[x.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},x.workspaceIdentity))}):null]})}function WM({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return a(te,{children:[t?a(VM,{item:t,onReassign:n,onReview:r??i}):null,e.map(o=>a(KM,{item:o,onReview:i},`${o.peerName}:${o.actorId}:${o.scopeLabel}`))]})}function qM(){Tf("mine"),b.feedQuery="",window.location.hash="feed"}function zM(){window.location.hash="projects"}async function JM(e,t,n,r){try{const i=await fw({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return b.lastSyncLegacySharedReview=i.legacy_shared_review??null,ne(`Reassigned ${i.reassigned_memory_count.toLocaleString()} legacy review memor${i.reassigned_memory_count===1?"y":"ies"} to ${i.target_scope_label}.`),Bb(),null}catch(i){if(i instanceof ju)return i.preview;const o=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw ne(o,"warning"),new Error(o)}}function Bb(){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(b.lastSyncSharingReview)?b.lastSyncSharingReview:[],o=b.lastSyncLegacySharedReview,s=Math.max(0,Number(o?.memory_count??0)),c=o?.has_data?{groups:Array.isArray(o.groups)?o.groups.map(d=>{const u=d;return{displayProject:String(u.display_project||u.project||"Unknown project"),identitySource:String(u.identity_source||"unknown"),lastUpdatedAt:typeof u.last_updated_at=="string"?u.last_updated_at:null,memoryCount:Number(u.memory_count||0),memorySamples:Array.isArray(u.memory_samples)?u.memory_samples.map(p=>{const m=p,f=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:f,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(u.peer_owned_memory_count||0),reassignableMemoryCount:Number(u.reassignable_memory_count||0),suggestedScopeId:typeof u.suggested_scope_id=="string"?u.suggested_scope_id:null,suggestionReason:typeof u.suggestion_reason=="string"?u.suggestion_reason:null,workspaceIdentity:String(u.workspace_identity||u.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(d=>{const u=d;return{authorityType:String(u.authority_type||"unknown"),label:String(u.label||u.scope_id||"Unknown domain"),scopeId:String(u.scope_id||"")}}).filter(d=>d.scopeId):[]}:null;if(!i.length&&!c){Zr(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=b.currentProject?`current project (${b.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.`,Qe(n,v(WM,{items:i.map(d=>({actorDisplayName:String(d.actor_display_name||d.actor_id||"unknown"),actorId:String(d.actor_id||"unknown"),peerName:String(d.peer_name||d.peer_device_id||"Device"),privateCount:Number(d.private_count||0),scopeLabel:String(d.scope_label||"All allowed projects"),shareableCount:Number(d.shareable_count||0)})),legacyReview:c,onLegacyReassign:JM,onLegacyReview:zM,onReview:qM}))}var As="",vo=null,su=0,YM=15e3;function Ub(e){return`project:${e||""}|includeJoinRequests:false`}function XM(e){const t=Ub(e);return!vo||vo.key!==t||Date.now()>=vo.expiresAtMs?null:vo.payload}function ZM(e,t){vo={key:Ub(e),expiresAtMs:Date.now()+YM,payload:t}}function QM(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function eO(){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 ri(){const e=++su;try{const t=b.currentProject||"",n=!1,r=b.activeTab==="health";let i=!1;const o=!Ei();let s;r?(s=XM(t),s||(s=await js(o,t,{includeJoinRequests:!1}),i=!0)):(s=await js(o,t,{includeJoinRequests:n}),i=!0);let c=null,l=null,d=b.lastShareOperations,u=!1,p=!1,m=!1;const f=y$();try{c=await z_()}catch{u=!0}try{l=await To()}catch{p=!0}try{const S=await Gu();d=Array.isArray(S.items)?S.items:[]}catch{m=!0}if(e!==su)return;i&&ZM(t,QM(s));const y=JSON.stringify([s,c,l,d,m,f]);if(y===As)return;As=y;const h=s.status&&typeof s.status=="object"?s.status:null;h&&(b.lastSyncStatus=h),Array.isArray(c?.items)?b.lastSyncActors=c.items:b.lastSyncActors=[];const g=Array.isArray(s.peers)?s.peers:[],_=new Set(g.map(S=>String(S?.peer_device_id||"").trim()).filter(Boolean)),w=Array.isArray(b.pendingAcceptedSyncPeers)?b.pendingAcceptedSyncPeers.filter(S=>{const T=String(S?.peer_device_id||"").trim();return T&&!_.has(T)}):[];b.pendingAcceptedSyncPeers=w,b.lastSyncPeers=[...g,...w],b.lastShareOperations=d,b.shareOperationsLoadError=m,b.lastSyncSharingReview=s.sharing_review||[],b.lastSyncLegacySharedReview=s.legacy_shared_review&&typeof s.legacy_shared_review=="object"?s.legacy_shared_review:null,b.lastSyncCoordinator=s.coordinator||null,b.lastCoordinatorAdminStatus=l&&typeof l=="object"?l:null,b.lastSyncJoinRequests=Array.isArray(s.join_requests)?s.join_requests:[],b.lastSyncAttempts=s.attempts||[],b.lastSyncLegacyDevices=s.legacy_devices||[],b.lastSyncDuplicatePersonDecisions=f,b.lastSyncViewModel=d$({actors:b.lastSyncActors,peers:b.lastSyncPeers,coordinator:b.lastSyncCoordinator,status:h,shareOperations:b.lastShareOperations,shareOperationsLoadError:m,reconciliation:s.recipient_policy_reconciliation,duplicatePersonDecisions:b.lastSyncDuplicatePersonDecisions}),xb(),Ps(),cM(),dM(),Bb(),tu(),Db(),Nb(),ky(),u&&lM(),p&&(b.lastCoordinatorAdminStatus=null,Ps())}catch{if(e!==su)return;As="",Rn("syncTeamSkeleton"),Rn("syncActorsSkeleton"),Rn("syncPeersSkeleton"),Rn("syncDiagSkeleton"),eO(),uM(),N$()}}function tO(){As="",b.lastSyncPeers?.length&&tu()}async function nO(){try{b.pairingPayloadRaw=await J_()||null,Jd()}catch{b.pairingPayloadRaw=null,Jd()}}function rO(e){sL(),Fa(),hM(ri),sM(ri),E$(tu),bM(e,ri),pM(ri),I$(e),nu(),fM()}function iO(e,t){const n=Re("runtimeLabel");n&&(n.textContent=t?`v${e} (${t})`:`v${e}`,n.title=t?`codemem ${e} (${t})`:`codemem ${e}`,n.hidden=!1)}async function oO(){try{const e=await H_();if(!e?.version)return;iO(e.version,"5acb479")}catch{}}var cu=null,Gb=1500,Hb="codemem-legacy-upgrade-notice-dismissed",Dn=null,Jt=!1,lu=!1,yo=null;function Kb(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function Vb(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=Kb(n.total_group_count,r.length),o=Kb(n.memory_count);return i<=0||o<=0?null:{groupCount:i,memoryCount:o}}function Wb(){try{return localStorage.getItem(Hb)==="1"}catch{return!1}}function Es(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(Hb,"1")}catch{}}function qb(){const e=Re("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 aO(){const e=qb(),t=Re("legacyUpgradeReviewGroups");(t&&e.includes(t)?t:e[0])?.focus()}function zb(e){const t=Re("legacyUpgradeModal");if(!t||t.hidden)return;if(e.key==="Escape"){e.preventDefault(),Es(),bo(!1);return}if(e.key==="Enter"){const o=Re("legacyUpgradeReviewGroups");Rr(e,{onSubmit:()=>o?.click(),disabled:!o||o.disabled});return}if(e.key!=="Tab")return;const n=qb();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 Jb(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 bo(e,t){const n=Re("legacyUpgradeModalBackdrop"),r=Re("legacyUpgradeModal"),i=Re("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){yo=document.activeElement,document.addEventListener("keydown",zb),aO(),Jb(!0);return}Jb(!1),document.removeEventListener("keydown",zb),yo&&document.contains(yo)&&yo.focus(),yo=null}}function Yb(e){!e||lu||Wb()||(lu=!0,bo(!0,e))}async function sO(){if(!(lu||Wb()))try{Yb(Vb(await js(!1,"",{includeJoinRequests:!1})))}catch{}}function gr(e,t){const n=Re("viewerReconnectOverlay"),r=Re("viewerReconnectDetail");!n||!r||(n.hidden=!e,r.textContent=t||"Trying again automatically while the viewer comes back.")}async function du(){try{return await G_(),!0}catch{return!1}}function cO(){return document.visibilityState!=="hidden"&&!qy()}function Xb(){if(Jt)return;Jt=!0,uu(),vr("error","(reconnecting)"),gr(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await du()){if(Dn&&(clearTimeout(Dn),Dn=null),Jt=!1,gr(!0,"Viewer responded. Restoring your session…"),cO()){vr("refreshing"),_o();try{await Rs()}catch{}}else vr("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");Jt||gr(!1);return}gr(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),Dn=setTimeout(e,Gb)};Dn=setTimeout(e,Gb)}function vr(e,t){b.refreshState=e;const n=Re("refreshStatus");if(!n)return;const r=o=>{const s=Re("refreshAnnouncer");!s||cu===e||(s.textContent=o,cu=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}`,cu=null}function uu(){b.refreshTimer&&(clearInterval(b.refreshTimer),b.refreshTimer=null)}function _o(){b.refreshTimer||(b.refreshTimer=setInterval(()=>Ln(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(uu(),vr("paused","(tab hidden)")):!qy()&&!Jt&&(_o(),Ln())});function lO(){const e=b.advancedSection==="sync",t=Re("advancedSyncContent"),n=Re("advancedTeamsContent");t&&(t.hidden=!e),n&&(n.hidden=e);const r=Re("advancedSyncButton"),i=Re("advancedTeamsButton");r?.setAttribute("aria-pressed",String(e)),i?.setAttribute("aria-pressed",String(!e)),queueMicrotask(()=>{const o=window.location.hash.replace(/^#/,"");nu(o==="sync/diagnostics"||o==="advanced/sync/diagnostics"?"diagnostics":"main")})}function Zb(e){const t=new Set(ek(b.lastCoordinatorAdminStatus));zn.forEach(n=>{const r=Re(`tab-${n}`);r&&(r.hidden=n!==e||!t.has(n))}),zn.forEach(n=>{const r=Re(`tabBtn-${n}`);if(!r)return;r.hidden=!t.has(n);const i=n===e&&t.has(n);r.classList.toggle("active",i),i?r.setAttribute("aria-current","page"):r.removeAttribute("aria-current")}),lO()}function Is(e,t={}){const n=Ai(e,b.lastCoordinatorAdminStatus);n==="advanced"&&Gc(t.advancedSection??Uc()??b.advancedSection),Cf(n,t.canonicalHash?{canonicalHash:!0}:{}),Zb(n),Ln()}function dO(){zn.forEach(e=>{Re(`tabBtn-${e}`)?.addEventListener("click",()=>Is(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),Re("advancedSyncButton")?.addEventListener("click",()=>Gc("sync",!0)),Re("advancedTeamsButton")?.addEventListener("click",()=>Gc("teams",!0)),window.addEventListener("hashchange",()=>{const e=Bc();if(e){const t=Uc();Is(e,t?{advancedSection:t}:{})}}),Is(b.activeTab)}async function uO(){try{const e=await ko();b.knownProjects=e,tO();const t=Oc("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{}}var pO=iT(),Qb={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},e_=!1,yr=null;async function mO(){const e=[];let t=0;for(;;){const n=await xo({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return Qo(e)}function fO(){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 b.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"offline":"available");for(const r of b.lastSyncPeers){const i=String(r.peer_device_id??"").trim(),o=fo(r);n(i,o==="connected"||o==="available"?"available":o==="offline"?"offline":"unknown")}return[...e].map(([r,i])=>({deviceId:r,state:i}))}function hO(){return b.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 t_(e){Is(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}async function gO(){const e=document.getElementById("devicesMount");if(!e)return!0;e_||Ua(e,Qb,{version:1,items:[]},[],[],{loading:!0});try{const[t,n,r]=await Promise.all([mO(),Us(),Z_(),ri()]),i=fO(),o=hO();return Ua(e,n,r,t,i,{onNavigate:t_,peerRuntimeMetadata:o}),yr={projects:t,intent:n,reconciliation:r,availability:i,peerRuntimeMetadata:o},e_=!0,!0}catch{return yr?Ua(e,yr.intent,yr.reconciliation,yr.projects,yr.availability,{onNavigate:t_,peerRuntimeMetadata:yr.peerRuntimeMetadata,refreshError:!0}):Ua(e,Qb,{version:1,items:[]},[],[],{loadError:!0}),!1}}Oc("projectFilter")?.addEventListener("change",()=>{b.currentProject=Oc("projectFilter")?.value||"",ao(!0),Ln()});var pu=null;async function Ln(){Jt||(pu&&clearTimeout(pu),pu=setTimeout(()=>Rs(),80))}async function Rs(){if(!Jt){if(b.refreshInFlight){b.refreshQueued=!0;return}b.refreshInFlight=!0;try{vr("refreshing");const e=b.activeTab,t=[b0(),PD()];let n=!0;e==="feed"&&t.push(To().then(i=>{b.lastCoordinatorAdminStatus=i&&typeof i=="object"?i:null}).catch(()=>{b.lastCoordinatorAdminStatus=null})),e==="feed"&&t.push(_y()),e==="projects"&&t.push(X0()),e==="sharing"&&t.push(pO()),e==="devices"&&t.push(gO().then(i=>{n=i})),(e==="advanced"&&b.advancedSection==="sync"||e==="health")&&t.push(ri()),e==="advanced"&&b.advancedSection==="teams"&&t.push(Ll()),b.syncPairingOpen&&t.push(nO()),await Promise.all(t),Yb(Vb(b.lastSyncLegacySharedReview));const r=Ai(b.activeTab,b.lastCoordinatorAdminStatus);r!==b.activeTab&&Cf(r),Zb(b.activeTab),vr(n?"idle":"error")}catch{await du()?vr("error"):Xb()}finally{b.refreshInFlight=!1,b.refreshQueued&&!Jt&&(b.refreshQueued=!1,Rs())}}}lk();var n_=document.getElementById("toastRoot");n_&&KT(n_),dk(jc("themeToggle")),xf(Kc()),dO(),a0(),Z0(()=>Ln()),rO(()=>Ln()),ZP(),oL(uu,_o,()=>Ln()),uO(),Re("viewerReconnectRetry")?.addEventListener("click",async()=>{if(gr(!0,"Checking whether the viewer server is back…"),!await du()){Xb();return}Dn&&(clearTimeout(Dn),Dn=null),Jt=!1,gr(!0,"Viewer responded. Restoring your session…"),_o();try{await Rs()}catch{}Jt||gr(!1)}),Re("legacyUpgradeReviewGroups")?.addEventListener("click",()=>{Es(),bo(!1),window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)}),Re("legacyUpgradeReviewProjects")?.addEventListener("click",()=>{Es(),bo(!1),window.location.hash="projects"}),Re("legacyUpgradeNotNow")?.addEventListener("click",()=>{Es(),bo(!1)}),oO(),sO(),Ln(),_o()})();
114
+ Global: ${Number(c.tokens_saved||0).toLocaleString()} saved`:"",g=[{label:d?"Savings (project)":"Savings",value:Yi(u.tokens_saved||0),tooltip:`Tokens saved by reusing compressed memories. Exact: ${Number(u.tokens_saved||0).toLocaleString()} saved${h}`,icon:"trending-up"},{label:d?"Injected (project)":"Injected",value:Yi(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:Xl(u.tokens_saved,u.tokens_read),tooltip:`Percent reduction from reuse. Factor: ${Hx(u.tokens_saved,u.tokens_read)}.`+v+h,icon:"percent"},{label:d?"Work investment (project)":"Work investment",value:Yi(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:mg(o.vector_coverage),tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:mg(o.tags_coverage),tooltip:"Share of active memories with tags",icon:"tag"}];if(f>0?g.push({label:"Raw events pending",value:f,tooltip:"Pending raw events waiting to be flushed",icon:"activity"}):p>0&&g.push({label:"Raw sessions",value:p,tooltip:"Sessions with pending raw events",icon:"inbox"}),Zy(e,g),t){const _=s?` · project: ${s}`:"";eb(t,`DB: ${Wx(o.path||"unknown")} · ${zx(o.size_bytes||0)}${_}`)}jd()}async function nD(){const e=b.lastStatsPayload?.identity?.actor_id||null,t=b.activeTab==="health"&&!b.lastUpdateStatus?Yw().catch(Xw):Promise.resolve(b.lastUpdateStatus),[n,r,i,o,s]=await Promise.all([_w(),ww(b.currentProject),Sw(b.currentProject),Cw(b.currentProject),t]);b.lastStatsPayload=n||{},b.lastUsagePayload=r||{},b.lastRawEventsPayload=o||{},b.lastUpdateStatus=s;const c=b.lastStatsPayload?.identity?.actor_id||null;tD(),eD(),nb(),b.activeTab==="feed"&&e!==c&&dr(!0)}var go=new WeakMap;function ur(e,t=""){const n=document.createElement("p");return t&&(n.className=t),n.textContent=e,n}function rD(e){const t=document.createElement("article");t.className="project-inventory-row recipient-policy-blocked-item";const n=document.createElement("div");n.className="project-inventory-row-header";const r=document.createElement("h3");r.className="project-inventory-title",r.textContent=e.finding;const i=document.createElement("span");return i.className="project-status-badge needs_attention",i.textContent="Blocked",n.append(r,i),t.append(n,ur(e.reason,"project-inventory-meta"),ur(`Owner: ${e.ownerLabel}`,"settings-note"),ur(`Repair: ${e.repairAction}`,"settings-note")),t}function iD(e,t){const n=`review:${JSON.stringify(t)}`;if(go.get(e)===n)return;if(!t.continuity&&t.blockedItems.length===0){e.replaceChildren(),e.hidden=!0,go.set(e,n);return}e.hidden=!1;const r=document.createElement("section");r.className="card recipient-policy-review",r.setAttribute("aria-labelledby","recipientPolicyReviewTitle");const i=document.createElement("h2");if(i.id="recipientPolicyReviewTitle",i.textContent=t.blockedItems.length>0?"Sharing needs repair":"Existing sharing kept as-is",r.appendChild(i),t.continuity){const o=t.continuity.findingCount,s=ur(`${o.toLocaleString()} older sharing finding${o===1?" was":"s were"} not changed because Codemem could not safely translate ${o===1?"it":"them"} automatically.`,"settings-note");s.setAttribute("role","status"),s.setAttribute("aria-live","polite"),t.blockedItems.length===0&&r.appendChild(ur("No action is required for this update. Codemem did not change your existing Team or local sharing configuration.","section-meta")),r.appendChild(s)}if(t.blockedItems.length>0){const o=ur("Codemem did not change access for these items, but their current availability cannot be confirmed until these source-state problems are repaired.","section-meta project-attention-note"),s=document.createElement("h3");s.className="recipient-policy-blocked-heading",s.textContent="Needs repair";const c=document.createElement("div");c.className="project-inventory-list recipient-policy-review-list";for(const l of t.blockedItems)c.appendChild(rD(l));r.append(o,s,c)}e.replaceChildren(r),go.set(e,n)}function oD(e,t){const n=t instanceof Error?t.message:"Unable to load recipient migration review.",r=`error:${n}`;if(go.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=ur(n,"settings-note project-attention-note");s.setAttribute("role","status"),i.append(o,s),e.replaceChildren(i),go.set(e,r)}var rb=[["","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"]],rt=null,yo=0,Fd=250,Bd=[],Ud=new Set,Gd=new Set,Ss=new Map,Cs=new Map,pr=new Map,bo=new Map,Ns=!1,_o=!1,An=!1,ks=0,Tt=new Set,ib=new WeakMap,Ts={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},ri=Ts,Rn=!1;function qe(e){return document.getElementById(e)}function aD(e){return rb.find(([t])=>t===e)?.[1]??e.replaceAll("_"," ")}function sD(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 ii(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function Hd(e){return e.identity_source!=="unmapped"&&!ii(e)}function qd(e){return ii(e)?"Received from peers":Is(e.resolved_scope_id)}function cD(e){return ii(e)?"source-owned project":sD(e.resolution_reason)}function lD(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 ob(e){if(!e)return"No recent sessions";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function ab(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function fr(){const e=Tt.size,t=qe("projectsShareSelected");t&&(t.textContent=e===0?"Share selected":`Share selected (${e})`,t.disabled=e===0||!An||!Rn,t.classList.add("project-selection-target"));const n=qe("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=ib.get(r)??[],o=i.filter(s=>Tt.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=!An||!Rn}function dD(e){const t=e.every(n=>Tt.has(n));for(const n of e)t?Tt.delete(n):Tt.add(n);fr()}function sb(e,t){const n=ab(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),ib.set(i,n),i.addEventListener("change",()=>dD(n));const o=document.createElement("span");return o.className="sr-only",o.textContent=t,r.append(i,o),r}function uD(e){if(!Rn)return[];const t=new Set(e),n=new Map(ri.teams.filter(o=>o.status==="active").map(o=>[o.teamId,o.displayName])),r=new Map(ri.identities.filter(o=>o.status==="active"||o.status==="pending").map(o=>[o.identityId,o.displayName])),i=new Map;for(const o of ri.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 cb(e){const t=document.createElement("div");t.className="project-recipient-summary";const n=uD(e),r=document.createElement("div");if(r.className="project-recipient-status",r.textContent=Rn?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 lb(e,t){const n=document.createElement("button");return n.className="settings-button project-recipient-action project-selection-target",n.type="button",n.disabled=!An||!Rn,e.length===1?(n.textContent="Manage recipients",n.setAttribute("aria-label",`Manage recipients for ${t}`),n.dataset.projectFocusKey=`manage:${e[0]}`,n.addEventListener("click",()=>{Pi({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)Tt.add(r);fr(),Pi({mode:"project-add",projectIds:[...e].sort()})})),n}function pD(e){return e.git_remote?e.git_remote:e.cwd?e.cwd:e.workspace_identity}function Kd(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function Vd(e){return e.project||e.display_project||"Unnamed Project"}function db(e){const t=String(e||"").trim();return t?b.lastCoordinatorAdminGroups.find(n=>String(n.group_id||"").trim()===t&&!n.archived_at)?.display_name||"Team details unavailable":null}function fD(){return new Set(b.lastCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function mD(e){return!_o||e.authority_type!=="coordinator"||!e.group_id?!1:!fD().has(String(e.group_id).trim())}function ub(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function pb(){Ns&&(Ns=!1,rt?.())}async function hD(){try{const e=await Do();b.lastCoordinatorAdminStatus=e&&typeof e=="object"?e:null}catch{b.lastCoordinatorAdminStatus=null,b.lastCoordinatorAdminGroups=[],_o=!1;return}if(b.lastCoordinatorAdminStatus?.readiness!=="ready"||!b.lastCoordinatorAdminStatus.has_admin_secret){b.lastCoordinatorAdminGroups=[],_o=!1;return}try{const e=await Yu(!1);b.lastCoordinatorAdminGroups=Array.isArray(e?.items)?e.items:[],_o=!0}catch{b.lastCoordinatorAdminGroups=[],_o=!1}}function vD(e){return e.kind==="team_default"}function Wd(e){const t=e.label||"Untitled Space";return vD(e)?`${t} (default)`:t}function gD(e,t){const n=Wd(e);return t.some(r=>r.scope_id!==e.scope_id&&Wd(r)===n)?`${n} · Space ID ${e.scope_id}`:n}function yD(e){const t=db(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 bD(e){return e?Bd.find(t=>t.scope_id===e)??null:null}function Is(e){const t=bD(e);return e?t?`${Wd(t)} · ${yD(t)}`:"Unknown Space":"—"}function zd(){return Bd.filter(e=>e.scope_id!=="legacy-shared-review"&&!mD(e))}function _D(e){return zd().some(t=>t.scope_id===e)}function fb(...e){for(const t of e)if(t&&_D(t))return t;return e.find(t=>!!t)??""}function wD(e){const t=db(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function SD(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function CD(){const e=new Map;for(const t of zd()){const n=SD(t),r=wD(t),i=e.get(n)??{label:r,scopes:[]};e.set(n,{label:i.label,scopes:[...i.scopes,t]})}return[...e.values()]}function mb(e){for(const t of CD()){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=gD(r,t.scopes),n.appendChild(i)}e.appendChild(n)}}function ND(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 Jd(e,t,n=[]){try{await jw({...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}),pr.delete(e.workspace_identity),Ss.delete(e.workspace_identity),ne("Project Space assignment updated. Device access grants are unchanged."),rt?.()}catch(r){if(r instanceof Mo){pr.set(e.workspace_identity,{requiredGuardrailTokens:r.requiredGuardrailTokens,scopeId:t,warnings:r.guardrailWarnings}),rt?.();return}ne(r instanceof Error?r.message:"Unable to update project Space.","warning")}}async function kD(e,t){const n=e.filter(Hd);if(n.length!==0)try{await Fw({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}))}),ne(`Updated ${n.length} project identit${n.length===1?"y":"ies"}. Device access grants are unchanged.`),Cs.delete(Kd(n[0])),rt?.()}catch(r){ne(r instanceof Mo?"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 TD(e){if(e.mapping_id!=null)try{await Bw(e.mapping_id),pr.delete(e.workspace_identity),Ss.delete(e.workspace_identity),ne("Project Space assignment removed. The next fallback now applies."),rt?.()}catch(t){ne(t instanceof Error?t.message:"Unable to remove project Space assignment.","warning")}}async function hb(e,t=!1){try{const n=bo.get(e.workspace_identity),r=await Gw({...t&&n?{confirmation_token:n.confirmationToken}:{},confirmed:t,workspace_identity:e.workspace_identity});bo.delete(e.workspace_identity),ne(`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.`),rt?.()}catch(n){if(n instanceof ip){bo.set(e.workspace_identity,{confirmationToken:n.preview.confirmation_token,localOwnedMemoryCount:n.preview.local_owned_memory_count,peerOwnedMemoryCount:n.preview.peer_owned_memory_count}),rt?.();return}ne(n instanceof Error?n.message:"Unable to forget project memories.","warning")}}async function ID(e){if(e.identity_source==="unmapped")return;const t=String(e.project||e.display_project||"").trim();let n=[];try{n=(await Lo()).filter(i=>i&&i!==t)}catch{}const r=await ql({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 Uw({project:r.trim(),workspace_identity:e.workspace_identity});ne(`Changed project to ${i.project} for ${i.moved_session_count} session${i.moved_session_count===1?"":"s"}.`),rt?.()}catch(i){ne(i instanceof Error?i.message:"Unable to change project.","warning")}}function ED(e){const t=document.createElement("div");if(t.className="project-inventory-actions",Hd(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=!An,An||(m.title="The complete project list is unavailable."),m.addEventListener("click",()=>pa([e.workspace_identity])),t.appendChild(m)}if(ii(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=zd().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=`${Is(e.resolved_scope_id)} — not assignable`,m.disabled=!0,i.appendChild(m)}mb(i),i.value=fb(Ss.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",()=>{Jd(e,i.value)}),i.addEventListener("change",()=>{Ss.set(e.workspace_identity,i.value),pr.delete(e.workspace_identity),t.querySelector(".project-space-guardrail-confirmation")?.remove(),s.textContent="Save Space",s.disabled=!i.value,rt?.()}),i.addEventListener("blur",pb);const c=document.createElement("button");c.className="settings-button",c.type="button",c.textContent="Keep local-only",c.addEventListener("click",()=>{Jd(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",()=>{TD(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",()=>{ID(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",()=>{hb(e)}),t.append(n,i,s,c,l,d,u);const p=pr.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 h=document.createElement("p");h.textContent="Codemem can save this change after you acknowledge the checks below. Verify the workspace details, then confirm to complete the save.";const g=document.createElement("ul");for(const S of p.warnings){const N=document.createElement("li"),k=document.createElement("strong");k.textContent=`${ND(S)}: `;const E=document.createElement("span");E.textContent=S.message,N.append(k,E),g.appendChild(N)}const _=document.createElement("button");_.className="settings-button",_.type="button",_.textContent="I understand, save Space",_.addEventListener("click",()=>{const S=pr.get(e.workspace_identity);!S||S.scopeId!==i.value||Jd(e,S.scopeId,S.requiredGuardrailTokens)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{pr.delete(e.workspace_identity),rt?.()}),m.append(v,h,g,_,w),t.appendChild(m)}const f=bo.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 h=document.createElement("p");h.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 g=document.createElement("p");g.textContent="Use this only to clean up wrongly attributed local project inventory; it forgets actual local memories on this device.";const _=document.createElement("button");_.className="settings-button danger",_.type="button",_.textContent="I understand, forget local memories",_.addEventListener("click",()=>{hb(e,!0)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{bo.delete(e.workspace_identity),rt?.()}),m.append(v,h,g,_,w),t.appendChild(m)}return t}function vb(e){const t=document.createElement("article");t.className="project-inventory-row";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",la(e)&&r.appendChild(sb([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),la(e)&&r.appendChild(lb([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 · ${ob(e.latest_session_at)}`,t.appendChild(o),t.appendChild(cb([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=qd(e),s.appendChild(c);const l=document.createElement("div");if(l.className="project-inventory-meta",l.textContent=`${cD(e)} · ${e.identity_source} · ${ob(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 g=document.createElement("strong");g.textContent="Project sharing";const _=document.createElement("ul");_.setAttribute("aria-label",`People sharing ${e.display_project}`);for(const w of e.sharing){const S=document.createElement("li"),N=document.createElement("strong");N.textContent=lD(w);const k=document.createElement("span");k.textContent=` — ${w.lifecycle.label}. ${w.lifecycle.explanation}`,S.append(N,k),_.appendChild(S)}h.append(g,_),s.appendChild(h)}if(ii(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=pD(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 ${Is(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(g=>g.message).join(" ")}`,s.appendChild(h)}if(e.statuses.length>0){const h=document.createElement("div");h.className="project-inventory-badges";for(const g of e.statuses){const _=document.createElement("span");_.className=`project-status-badge ${g}`,_.textContent=aD(g),h.appendChild(_)}s.appendChild(h)}const p=document.createElement("details");p.className="project-inventory-details",p.open=Ud.has(e.workspace_identity),p.addEventListener("toggle",()=>{p.open?Ud.add(e.workspace_identity):Ud.delete(e.workspace_identity)});const f=document.createElement("summary");f.textContent=u.length>0?`Advanced Project administration — ${u.length.toLocaleString()} item${u.length===1?"":"s"} need attention`:"Advanced Project administration",p.appendChild(f),p.appendChild(s);const m=document.createElement("dl");m.className="project-detail-grid";const v=[["Workspace identity",e.workspace_identity],["Project",e.project],["CWD",e.cwd],["Git remote",e.git_remote],["Git branch",e.git_branch],["Current Space",qd(e)],["Suggested Space",e.suggested_scope_id?Is(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,g]of v){const _=document.createElement("dt");_.textContent=h;const w=document.createElement("dd");w.textContent=g==null||g===""?"—":String(g),m.append(_,w)}return p.appendChild(m),p.appendChild(ED(e)),t.appendChild(p),t}function xD(e){const t=[...new Set(e.map(n=>qd(n)))];return t.length===1?t[0]:"Mixed Spaces"}function PD(e){if(e.length===1)return vb(e[0]);const t=Kd(e[0]),n=e.filter(la),r=ab(n),i=document.createElement("article");i.className="project-inventory-row project-inventory-cluster";const o=Vd(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(sb(n,`Select all identities for ${Vd(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(lb(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=xD(e),d.appendChild(u);const p=e.reduce((S,N)=>S+(N.memory_count??0),0),f=e.reduce((S,N)=>S+N.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(cb(r));const v=document.createElement("div");v.className="project-inventory-actions";const h=e.filter(Hd);if(h.length===0){const S=document.createElement("div");S.className="settings-note",S.textContent=e.every(ii)?"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(S),d.appendChild(v)}else{const S=h.map(I=>({project:I,warnings:(I.guardrail_warnings??[]).filter(G=>G.requires_confirmation)})),N=S.some(({warnings:I})=>I.length>0),k=new Set(h.map(I=>I.suggested_scope_id).filter(I=>!!I)),E=new Set(h.map(I=>I.resolved_scope_id)),R=document.createElement("select");R.className="project-domain-select",R.setAttribute("aria-label",`Space for ${Vd(e[0])} group`);const j=document.createElement("option");j.value="",j.textContent="Choose Space…",R.appendChild(j),mb(R),R.value=fb(Cs.get(t));const q=document.createElement("button");if(q.className="settings-button",q.type="button",q.textContent=`Save Space for ${h.length} identit${h.length===1?"y":"ies"}`,q.disabled=!R.value||N,q.addEventListener("click",()=>{kD(h,R.value)}),R.addEventListener("change",()=>{R.value?Cs.set(t,R.value):Cs.delete(t),q.disabled=!R.value||N}),R.addEventListener("blur",pb),v.append(R,q),k.size>1||E.size>1||N){const I=document.createElement("div");if(I.className="settings-note project-attention-note",I.textContent=N?"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.",N){const G=document.createElement("ul");for(const{project:A,warnings:M}of S){if(M.length===0)continue;const L=document.createElement("li"),x=document.createElement("strong");x.textContent=`Blocked identity: ${A.workspace_identity}`;const O=document.createElement("span");O.textContent=` — ${M.map(T=>T.message).join(" ")}`,L.append(x,O),G.appendChild(L)}I.appendChild(G)}v.appendChild(I)}d.appendChild(v)}const g=document.createElement("details");g.className="project-inventory-details",g.open=Gd.has(t),g.addEventListener("toggle",()=>{g.open?Gd.add(t):Gd.delete(t)});const _=document.createElement("summary"),w=e.reduce((S,N)=>S+(N.guardrail_warnings??[]).filter(k=>k.severity==="warning").length,0);_.textContent=w>0?`Advanced Project administration — ${w.toLocaleString()} item${w===1?"":"s"} need attention`:"Advanced Project administration",g.appendChild(_),g.appendChild(d);for(const S of e)g.appendChild(vb(S));return i.appendChild(g),i}function AD(e){const t=new Map;for(const n of e){const r=Kd(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function gb(e){const t=qe("projectsInventoryList");if(!t)return;t.textContent="";const n=document.createElement("div");n.className="settings-note",n.textContent=e,t.appendChild(n)}function yb(){document.getElementById("projectsInventorySkeleton")?.remove()}function bb(e){const t=qe("projectsInventoryMeta"),n=qe("projectsInventoryList");if(!t||!n)return;const r=document.activeElement instanceof HTMLElement?document.activeElement.dataset.projectFocusKey:void 0;if(yb(),n.textContent="",e.projects.length===0)gb("No projects match those filters.");else for(const s of AD(e.projects))n.appendChild(PD(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=qe("projectsPrevPage"),o=qe("projectsNextPage");i&&(i.disabled=e.offset===0),o&&(o.disabled=!e.has_more),fr(),r&&[...n.querySelectorAll("[data-project-focus-key]")].find(s=>s.dataset.projectFocusKey===r)?.focus()}function RD(e,t){hD().then(()=>{t===ks&&(ub()||bb(e))})}async function DD(){const e=new Map;let t=0;for(;;){const n=await Oo({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 _b(e,t,n){const r=qe("recipientPolicyManagementMount");r&&am(r,da(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&Tt.clear(),fr(),rt?.()}})}async function LD(){const e=qe("projectsInventoryMeta"),t=qe("projectsInventoryList");if(!e||!t)return;if(ub()){Ns=!0;return}Ns=!1;const n=++ks;An=!1,Rn=!1,fr(),e.textContent="Loading project inventory…";try{const[r,i,o,s,c]=await Promise.all([Oo({limit:Fd,offset:yo,q:qe("projectsSearch")?.value.trim()||void 0,status:qe("projectsStatusFilter")?.value||void 0}),Dw(),DD().then(u=>({ok:!0,projects:u})).catch(()=>({ok:!1,projects:[]})),Rw().then(u=>({ok:!0,review:u})).catch(u=>({ok:!1,error:u})),Zs().then(u=>({ok:!0,intent:u})).catch(u=>({ok:!1,error:u}))]);if(n!==ks)return;if(Bd=i.scopes,An=o.ok,Rn=c.ok,ri=c.ok?c.intent:Ts,o.ok){const u=new Set(da(o.projects).map(p=>p.canonicalProjectIdentity));for(const p of Tt)u.has(p)||Tt.delete(p)}const l=qe("projectShareFlowMount");l&&pm(l,o.projects,{inventoryError:!o.ok});const d=qe("recipientPolicyReviewMount");d&&("review"in s?iD(d,s.review):oD(d,s.error)),_b(o.projects,ri,!o.ok||!c.ok),bb(r),RD(r,n)}catch(r){if(n!==ks)return;An=!1,Rn=!1,ri=Ts;const i=qe("projectShareFlowMount");i&&pm(i,[],{inventoryError:!0}),_b([],Ts,!0),fr(),yb(),e.textContent="Project inventory failed to load.",gb(r instanceof Error?r.message:"Unable to load project inventory.")}}function $D(e){rt=e,Tt.clear();const t=qe("projectsStatusFilter");if(t&&t.options.length===0)for(const[i,o]of rb){const s=document.createElement("option");s.value=i,s.textContent=o,t.appendChild(s)}const n=()=>{yo=0,rt?.()};qe("projectsSearch")?.addEventListener("input",n),t?.addEventListener("change",n),qe("projectsPrevPage")?.addEventListener("click",()=>{yo=Math.max(0,yo-Fd),rt?.()}),qe("projectsNextPage")?.addEventListener("click",()=>{yo+=Fd,rt?.()});const r=qe("projectsShareSelected");r&&r.dataset.recipientPolicyBound!=="true"&&(r.dataset.recipientPolicyBound="true",r.addEventListener("click",()=>{Tt.size!==0&&Pi({mode:"project-add",projectIds:[...Tt].sort()})})),fr()}function Yd(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 MD(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 wb="codemem-settings-advanced",Sb="gpt-5.1-codex-mini",Cb="claude-4.5-haiku",OD=[{value:"observer",label:"Connection"},{value:"queue",label:"Processing"},{value:"sync",label:"Device Sync"}],jD={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"},FD=new Set(["claude_command","codex_command","observer_base_url","observer_auth_file","observer_auth_command","observer_headers","sync_coordinator_url"]),BD={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 UD(){try{return globalThis.localStorage?.getItem(wb)==="1"}catch{return!1}}function GD(e){try{globalThis.localStorage?.setItem(wb,e?"1":"0")}catch{}}function ln(e,t){return typeof e=="object"&&e!==null&&Object.hasOwn(e,t)}function ke(e,t,n){if(ln(t,n))return t[n];if(ln(e,n))return e[n]}function Pe(e){return e==null?"":String(e)}function Es(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 HD(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function qD(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function ze(e){const t=e.trim();return t===""?"":t}function KD(e,t,n){return n?{model:n,source:"Configured"}:e==="claude_sidecar"?{model:Cb,source:"Recommended (local Claude session)"}:e==="codex_sidecar"?{model:Sb,source:"Recommended (local Codex session)"}:t==="anthropic"?{model:Cb,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:Sb,source:"Recommended (direct API)"}}function VD(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 ze(Pe(n[t]));case"observer_runtime":return ze(Pe(n.observer_runtime));case"observer_auth_source":return ze(Pe(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(!ln(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(!ln(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r>0?r:""}case"observer_auth_cache_ttl_s":{if(!ln(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 Es(n[t]);default:return ln(n,t)?n[t]:""}}function WD(e,t,n){const r={...e};return Object.keys(n).forEach(i=>{ln(r,i)&&(r[i]=VD(t,i))}),r}function zD(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let o=[];try{o=Yd(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(N){if(!i||n.has("claude_command"))throw N;const k=r.claude_command;o=Array.isArray(k)?k.filter(E=>typeof E=="string").map(E=>E.trim()).filter(E=>E.length>0):[]}let s=[];try{s=Yd(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(N){if(!i||n.has("codex_command"))throw N;const k=r.codex_command;s=Array.isArray(k)?k.filter(E=>typeof E=="string").map(E=>E.trim()).filter(E=>E.length>0):[]}let c=[];try{c=Yd(t.observerAuthCommand,{label:"observer auth command"})}catch(N){if(!i||n.has("observer_auth_command"))throw N;const k=r.observer_auth_command;c=Array.isArray(k)?k.filter(E=>typeof E=="string"):[]}let l={};try{l=MD(t.observerHeaders)}catch(N){if(!i||n.has("observer_headers"))throw N;const k=r.observer_headers;k&&typeof k=="object"&&!Array.isArray(k)&&Object.entries(k).forEach(([E,R])=>{typeof E=="string"&&E.trim()&&typeof R=="string"&&(l[E]=R)})}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),h=u===""?"":Number(u),g=p===""?"":Number(p),_=f===""?"":Number(f),w=Number(m),S=m===""?"":w;if(d!==""&&!Number.isFinite(v))throw new Error("observer auth cache ttl must be a number");if(u!==""&&(typeof h!="number"||!Number.isFinite(h)||h<0))throw new Error("simple tier temperature must be a non-negative number");if(p!==""&&(typeof g!="number"||!Number.isFinite(g)||g<0))throw new Error("rich tier temperature must be a non-negative number");if(f!==""&&(typeof _!="number"||!Number.isFinite(_)||_<=0||!Number.isInteger(_)))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:ze(t.observerProvider),observer_model:ze(t.observerModel),observer_tier_routing_enabled:t.observerTierRoutingEnabled,observer_simple_model:ze(t.observerSimpleModel),observer_simple_temperature:h,observer_reasoning_effort:ze(t.observerReasoningEffort),observer_reasoning_summary:ze(t.observerReasoningSummary),observer_rich_model:ze(t.observerRichModel),observer_rich_temperature:g,observer_rich_reasoning_effort:ze(t.observerRichReasoningEffort),observer_rich_reasoning_summary:ze(t.observerRichReasoningSummary),observer_rich_max_output_tokens:_,observer_runtime:ze(t.observerRuntime||"api_http")||"api_http",observer_auth_source:ze(t.observerAuthSource||"auto")||"auto",observer_auth_file:ze(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:S,sync_enabled:t.syncEnabled,sync_host:ze(t.syncHost),sync_port:Number(t.syncPort||0)||"",sync_interval_s:Number(t.syncInterval||0)||"",sync_mdns:t.syncMdns,sync_coordinator_url:ze(t.syncCoordinatorUrl),sync_coordinator_group:ze(t.syncCoordinatorGroup),sync_coordinator_timeout_s:Number(t.syncCoordinatorTimeout||0)||"",sync_coordinator_presence_ttl_s:Number(t.syncCoordinatorPresenceTtl||0)||""}}function JD(e){const t=e.config||{},n=e.effective||{},r=ke(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=ke(t,n,"claude_command"),s=Array.isArray(o)?o.filter(p=>typeof p=="string"):[],c=ke(t,n,"codex_command"),l=Array.isArray(c)?c.filter(p=>typeof p=="string"):[],d=ke(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:Pe(ke(t,n,"observer_provider")),observerModel:Pe(ke(t,n,"observer_model")),observerTierRoutingEnabled:Es(ke(t,n,"observer_tier_routing_enabled")),observerSimpleModel:Pe(ke(t,n,"observer_simple_model")),observerSimpleTemperature:Pe(ke(t,n,"observer_simple_temperature")),observerReasoningEffort:Pe(ke(t,n,"observer_reasoning_effort")),observerReasoningSummary:Pe(ke(t,n,"observer_reasoning_summary")),observerRichModel:Pe(ke(t,n,"observer_rich_model")),observerRichTemperature:Pe(ke(t,n,"observer_rich_temperature")),observerRichReasoningEffort:Pe(ke(t,n,"observer_rich_reasoning_effort")),observerRichReasoningSummary:Pe(ke(t,n,"observer_rich_reasoning_summary")),observerRichMaxOutputTokens:Pe(ke(t,n,"observer_rich_max_output_tokens")),observerRuntime:Pe(ke(t,n,"observer_runtime"))||"api_http",observerAuthSource:Pe(ke(t,n,"observer_auth_source"))||"auto",observerAuthFile:Pe(ke(t,n,"observer_auth_file")),observerAuthCommand:u.length?JSON.stringify(u,null,2):"",observerAuthTimeoutMs:Pe(ke(t,n,"observer_auth_timeout_ms")),observerAuthCacheTtlS:Pe(ke(t,n,"observer_auth_cache_ttl_s")),observerHeaders:Object.keys(i).length?JSON.stringify(i,null,2):"",observerMaxChars:Pe(ke(t,n,"observer_max_chars")),packObservationLimit:Pe(ke(t,n,"pack_observation_limit")),packSessionLimit:Pe(ke(t,n,"pack_session_limit")),rawEventsSweeperIntervalS:Pe(ke(t,n,"raw_events_sweeper_interval_s")),syncEnabled:Es(ke(t,n,"sync_enabled")),syncHost:Pe(ke(t,n,"sync_host")),syncPort:Pe(ke(t,n,"sync_port")),syncInterval:Pe(ke(t,n,"sync_interval_s")),syncMdns:Es(ke(t,n,"sync_mdns")),syncCoordinatorUrl:Pe(ke(t,n,"sync_coordinator_url")),syncCoordinatorGroup:Pe(ke(t,n,"sync_coordinator_group")),syncCoordinatorTimeout:Pe(ke(t,n,"sync_coordinator_timeout_s")),syncCoordinatorPresenceTtl:Pe(ke(t,n,"sync_coordinator_presence_ttl_s"))}}function YD(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection now lives in Processing.";const n=KD(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),ze(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>ln(t,r))?"Env override":n.source}: ${n.model}`}function XD(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 QD(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function ZD(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 eL(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 tL(e){return!e}function nL(e,t,n){return t.has(e)||n.has(e)}function rL(e){return`${e} is read-only in the viewer for security. Edit the config file or environment instead.`}var W={open:!1,previouslyFocused:null,activeTab:"observer",baseline:{},envOverrides:{},touchedKeys:new Set,shellMounted:!1,protectedKeys:new Set,startPolling:null,refresh:null,showAdvanced:UD(),controller:null,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...BD}}};function iL(){W.controller?.hideTooltip()}function mr(e){if(W.controller){W.controller.setRenderState(e);return}W.renderState={...W.renderState,...e}}function oL(e){mr({values:{...W.renderState.values,...e}})}function aL(e){const t=["observer","queue","sync"].includes(e)?e:"observer";W.activeTab=t,W.controller?.setActiveTab(t)}function xs(e,t=!0){b.settingsDirty=e,t&&W.controller?.setDirty(e)}function sL(e){W.showAdvanced=e,W.controller?.setShowAdvanced(e)}function Nb(){return W.open}function cL(e){return nL(e,W.protectedKeys,FD)}function kb(e={}){return zD({values:W.renderState.values,touchedKeys:W.touchedKeys,baseline:W.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors})}function lL(e){mr({observerStatus:e&&typeof e=="object"?e:null})}function dL(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=JD(t);W.envOverrides=i,W.protectedKeys=new Set(o),b.configDefaults=n,b.configPath=t.path||"",mr({effectiveText:Object.keys(i).length>0?"Some fields are managed by environment settings.":"",overridesVisible:Object.keys(i).length>0,pathText:b.configPath?`Config path: ${b.configPath}`:"Config path: n/a",providers:HD(t.providers),statusText:"No unsaved changes",values:s}),W.touchedKeys=new Set;try{W.baseline=WD(kb({allowUntouchedParseErrors:!0}),r,i)}catch{W.baseline={}}xs(!1)}async function uL(){if(!W.open)try{const[e,t]=await Promise.all([X_(),Y_().catch(()=>null)]);dL(e),lL(t)}catch{}}function Xd(e){return String(e||"").replace(/_/g," ")}function Qd(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 pL(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 fL(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 mL(e){if(typeof e!="string"||!e.trim())return"Unknown time";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function hL({status:e}){if(!e)return a("div",{id:"observerStatusBanner",className:"observer-status-banner",hidden:!0});const t=e.active,n=e.available_credentials||{},r=e.latest_failure,i=Object.entries(n).filter(([,o])=>o&&typeof o=="object");return a("div",{id:"observerStatusBanner",className:"observer-status-banner",children:[t?a(Z,{children:[a("div",{className:"status-label",children:"Active observer"}),a("div",{className:"status-active",children:[String(t.provider||"unknown")," → ",String(t.model||"")," via"," ",pL(t.auth?.method||"none")," ",a("span",{"aria-label":t.auth?.token_present===!0?"token present":"token missing",className:t.auth?.token_present===!0?"cred-ok":"cred-none",role:"img",children:a("i",{"aria-hidden":"true","data-lucide":t.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)"})]}),i.length?a(Z,{children:[a("div",{className:"status-label",children:"Available credentials"}),a("div",{children:i.map(([o,s],c)=>{const l=s,d=Object.values(l).some(Boolean);return a("span",{className:"status-cred",children:[c>0?" · ":null,a("span",{"aria-label":d?"credential available":"no credential",className:d?"cred-ok":"cred-none",role:"img",children:d?a("i",{"aria-hidden":"true","data-lucide":"check"}):"–"})," ",String(o),": ",fL(l)]},o)})})]}):null,r&&typeof r=="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 r.error_message=="string"&&r.error_message.trim()?r.error_message.trim():"Raw-event processing failed."}),a("div",{className:"status-issue-meta",children:[[typeof r.observer_provider=="string"?r.observer_provider.trim():"",typeof r.observer_model=="string"&&r.observer_model.trim()?`→ ${r.observer_model.trim()}`:"",typeof r.observer_runtime=="string"&&r.observer_runtime.trim()?`(${r.observer_runtime.trim()})`:""].filter(Boolean).join(" ").replace(/\s+/g," ").trim(),`Last failure ${mL(r.updated_at)}`,typeof r.attempt_count=="number"&&Number.isFinite(r.attempt_count)?`Attempts ${r.attempt_count}`:""].filter(Boolean).join(" · ")}),typeof r.impact=="string"&&r.impact.trim()?a("div",{className:"status-issue-impact",children:r.impact.trim()}):null]})]}):null]})}function Tb(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 wo(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function vL(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 gL(){const e=Le("settingsModal");(vL(e)[0]||e)?.focus()}function yL(){const[e,t]=D({anchor:null,content:"",visible:!1}),n=U(null);return K(()=>{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=wo(u.target);p&&r(p)},s=u=>{const p=wo(u.target);if(!p)return;const f=u.relatedTarget;f instanceof Element&&p.contains(f)||i()},c=u=>{const p=wo(u.target);p&&r(p)},l=u=>{wo(u.target)&&i()},d=u=>{const p=wo(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)}},[]),gt(()=>{if(!e.visible||!e.anchor||!n.current)return;const r=requestAnimationFrame(()=>{n.current&&e.anchor&&Tb(n.current,e.anchor)});return()=>{cancelAnimationFrame(r)}},[e.anchor,e.content,e.visible]),K(()=>{if(!e.visible||!e.anchor)return;const r=()=>{n.current&&e.anchor&&Tb(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:Ee(()=>typeof document>"u"?null:en(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 bL({DialogContent:e,onClose:t}){const[n,r]=D(W.open),[i,o]=D(["observer","queue","sync"].includes(W.activeTab)?W.activeTab:"observer"),[s,c]=D(b.settingsDirty),[l,d]=D(W.renderState),[u,p]=D(W.showAdvanced),{tooltipPortal:f,setTooltip:m}=yL();W.open=n,W.activeTab=i,b.settingsDirty=s,W.renderState=l,W.showAdvanced=u,K(()=>(W.controller={hideTooltip:()=>{m({anchor:null,content:"",visible:!1})},setActiveTab:h=>{const g=["observer","queue","sync"].includes(h)?h:"observer";W.activeTab=g,o(g)},setDirty:h=>{b.settingsDirty=h,c(h)},setOpen:h=>{W.open=h,r(h)},setRenderState:h=>{const g={...W.renderState,...h};W.renderState=g,d(g)},setShowAdvanced:h=>{W.showAdvanced=h,GD(h),p(h)}},()=>{W.controller&&(W.controller=null)}),[]),K(()=>{n&&globalThis.lucide?.createIcons?.()},[n]);const v=ie(()=>{W.startPolling&&W.refresh&&t(W.startPolling,W.refresh)},[t]);return a(Z,{children:[a(Ii,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:h=>{h.preventDefault()},onOpenAutoFocus:h=>{h.preventDefault(),gL()},onOpenChange:h=>{if(h){r(!0);return}v()},open:n,overlayClassName:"modal-backdrop",overlayId:"settingsBackdrop",children:a(e,{})}),f]})}function je({children:e,className:t="field",hidden:n=!1,id:r}){return a("div",{className:t,hidden:n,id:r,children:e})}function So({children:e,hidden:t=!1}){return a("div",{className:"settings-note",hidden:t,children:e})}function Zd({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 _L({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(Zd,{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(je,{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(kn,{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(je,{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(we,{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(je,{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(kn,{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(je,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"codexCommand",children:"Codex command (JSON argv)"}),a(Vr,{disabled:!0,id:"codexCommand",placeholder:'["codex"]',rows:2,value:e.codexCommand}),a("div",{className:"small",children:f("codex_command")})]}),a(je,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"claudeCommand",children:"Claude command (JSON argv)"}),a(Vr,{disabled:!0,id:"claudeCommand",placeholder:'["claude"]',rows:2,value:e.claudeCommand}),a("div",{className:"small",children:f("claude_command")})]}),a(je,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerMaxChars",children:"Request size limit (chars)"}),a(we,{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(je,{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(kn,{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(je,{hidden:!r,id:"observerAuthFileField",children:[a("label",{htmlFor:"observerAuthFile",children:"Token file path"}),a(we,{disabled:!0,id:"observerAuthFile",placeholder:"~/.codemem/work-token.txt",value:e.observerAuthFile}),a("div",{className:"small",children:f("observer_auth_file")})]}),a(je,{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(Vr,{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(So,{hidden:o(),children:"These advanced credential overrides only matter when you need custom command timing, cached tokens, or extra request headers."}),a(je,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerAuthTimeoutMs",children:"Token command timeout (ms)"}),a(we,{id:"observerAuthTimeoutMs",min:"1",onInput:s("observerAuthTimeoutMs"),type:"number",value:e.observerAuthTimeoutMs})]}),a(je,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerAuthCacheTtlS",children:"Token cache time (s)"}),a(we,{id:"observerAuthCacheTtlS",min:"0",onInput:s("observerAuthCacheTtlS"),type:"number",value:e.observerAuthCacheTtlS})]}),a(je,{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(Vr,{disabled:!0,id:"observerHeaders",placeholder:'{"Authorization":"Bearer ${auth.token}"}',rows:4,value:e.observerHeaders}),a("div",{className:"small",children:f("observer_headers")})]})]})]})}function Ps({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(Gr,{"aria-labelledby":c,checked:e,className:"settings-switch",disabled:n,id:i,onCheckedChange:s,thumbClassName:"settings-switch-thumb"})]})}function wL({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r,onSwitchInput:i,getTieredRoutingHelperText:o}){return a(Z,{children:[a(Zd,{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(je,{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(we,{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(Ps,{checked:e.observerTierRoutingEnabled,className:"field",id:"observerTierRoutingEnabled",label:"Enable tiered routing",onCheckedChange:i("observerTierRoutingEnabled")}),a("div",{className:"small",children:o()}),a(So,{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(je,{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(we,{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(je,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerSimpleTemperature",children:"Temperature"}),a(we,{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(je,{className:"field settings-advanced",children:[a("label",{htmlFor:"observerReasoningEffort",children:"Reasoning effort"}),a(we,{id:"observerReasoningEffort",onInput:r("observerReasoningEffort"),placeholder:"leave empty for provider default",value:e.observerReasoningEffort})]}),a(je,{className:"field settings-advanced",children:[a("label",{htmlFor:"observerReasoningSummary",children:"Reasoning summary"}),a(we,{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(je,{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(we,{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(je,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichTemperature",children:"Temperature"}),a(we,{id:"observerRichTemperature",min:"0",onInput:r("observerRichTemperature"),step:"0.1",type:"number",value:e.observerRichTemperature})]}),a(je,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichReasoningEffort",children:"Reasoning effort override"}),a(we,{id:"observerRichReasoningEffort",onInput:r("observerRichReasoningEffort"),placeholder:"inherits shared reasoning effort",value:e.observerRichReasoningEffort})]}),a(je,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichReasoningSummary",children:"Reasoning summary override"}),a(we,{id:"observerRichReasoningSummary",onInput:r("observerRichReasoningSummary"),placeholder:"inherits shared reasoning summary",value:e.observerRichReasoningSummary})]}),a(je,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichMaxOutputTokens",children:"Max output tokens"}),a(we,{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(So,{hidden:n(),children:"Most users can keep these defaults. Change them only when you need smaller or larger default context packs."}),a(je,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packObservationLimit",children:"Observation limit"}),a(we,{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(je,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packSessionLimit",children:"Session summary limit"}),a(we,{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 SL({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return a(Z,{children:[a(Zd,{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(Ps,{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(we,{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(we,{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(we,{id:"syncPort",min:"1",onInput:n("syncPort"),type:"number",value:e.syncPort})]}),a(Ps,{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(we,{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(we,{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(So,{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(we,{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(we,{id:"syncCoordinatorPresenceTtl",min:"1",onInput:n("syncCoordinatorPresenceTtl"),type:"number",value:e.syncCoordinatorPresenceTtl})]})]})]})}function CL({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=>$r(p,{onSubmit:s,disabled:u}),children:[a("div",{className:"modal-header",children:[a("h2",{id:"settingsTitle",children:"Settings"}),a(Vo,{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(Ps,{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(So,{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(vh,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:c,tabs:OD,triggerClassName:"settings-tab",value:t,children:[a(Yn,{className:"settings-panel",forceMount:!0,value:"observer",children:a(_L,{...e,observerStatusBannerSlot:d})}),a(Yn,{className:"settings-panel",forceMount:!0,value:"queue",children:a(wL,{...e})}),a(Yn,{className:"settings-panel",forceMount:!0,value:"sync",children:a(SL,{...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 NL(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:o}=e,s={};return Object.entries(t).forEach(([c,l])=>{o(c)||ln(r,c)&&!i.has(c)||qD(l,n[c])||(s[c]=l)}),s}function kL(e){const t=s=>{const c=jD[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 TL(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=>Xd(String(p))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(p=>Xd(String(p))):[],o=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(p=>Xd(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: ${Qd(r)}.`),i.length&&d.push(`Live settings updated: ${Qd(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 ${Qd(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 IL=()=>YD(W.renderState.values,W.envOverrides),EL=()=>XD(W.renderState.values),xL=()=>QD(W.renderState.values),PL=()=>ZD(W.renderState.values),AL=()=>eL(W.renderState.values),RL=()=>tL(W.showAdvanced),{onTextInput:DL,onSelectValueChange:LL,onSwitchInput:$L}=kL({getTouchedKeys:()=>W.touchedKeys,getValues:()=>W.renderState.values,updateFormState:oL,setDirty:e=>xs(e)});function ML(){const e=W.renderState.observerStatus;return a(hL,{status:e})}function OL(){const e=W.renderState.values,t=String(b.configDefaults?.observer_max_chars||""),n=e.observerAuthSource==="file",r=e.observerAuthSource==="command",i=e.observerTierRoutingEnabled;return a(CL,{panelProps:{values:e,observerMaxCharsDefault:t,providerOptions:Array.from(new Set(W.renderState.providers.concat(e.observerProvider?[e.observerProvider]:[]))).sort((o,s)=>o.localeCompare(s)).map(o=>({label:o,value:o})),showAuthFile:n,showAuthCommand:r,showTieredRouting:i,hiddenUnlessAdvanced:RL,onTextInput:DL,onSelectValueChange:LL,onSwitchInput:$L,getObserverModelLabel:xL,getObserverModelTooltip:PL,getObserverModelDescription:AL,getObserverModelHint:IL,getTieredRoutingHelperText:EL,protectedConfigHelp:rL},activeTab:W.activeTab,showAdvanced:W.showAdvanced,renderState:W.renderState,settingsDirty:b.settingsDirty,onClose:()=>{W.startPolling&&W.refresh&&As(W.startPolling,W.refresh)},onSave:()=>{W.startPolling&&W.refresh&&UL(W.startPolling,W.refresh)},onActiveTabChange:aL,onAdvancedToggle:sL,observerStatusBannerSlot:a(ML,{})})}function jL(){return a(bL,{DialogContent:OL,onClose:As})}function FL(){const e=Le("settingsDialogMount");e&&Be(a(jL,{}),e)}function Ib(){Le("settingsDialogMount")&&(W.shellMounted||(FL(),W.shellMounted=!0))}function BL(e){W.shellMounted||Ib(),W.open=!0,W.previouslyFocused=document.activeElement,e(),W.controller?.setOpen(!0)}function As(e,t){if(b.settingsDirty&&!globalThis.confirm("Discard unsaved changes?")){W.controller?.setOpen(!0);return}W.open=!1,W.controller?.setOpen(!1),iL(),(W.previouslyFocused&&typeof W.previouslyFocused.focus=="function"?W.previouslyFocused:Qc("settingsButton"))?.focus(),W.previouslyFocused=null,W.touchedKeys=new Set,e(),t()}async function UL(e,t){if(!W.renderState.isSaving){mr({isSaving:!0,statusText:"Saving changes…"});try{const n=NL({current:kb({allowUntouchedParseErrors:!0}),baseline:W.baseline,envOverrides:W.envOverrides,touchedKeys:W.touchedKeys,isProtected:cL});if(Object.keys(n).length===0){mr({isSaving:!1,statusText:"No unsaved changes"}),xs(!1),As(e,t);return}const r=TL(await Q_(n));mr({isSaving:!1,statusText:"Saved changes"}),xs(!1),As(e,t),ne(r.message,r.type)}catch(n){mr({isSaving:!1,statusText:`Save failed: ${n instanceof Error?n.message:"unknown error"}`})}}}function GL(e,t,n){W.startPolling=t,W.refresh=n,Ib(),Qc("settingsButton")?.addEventListener("click",()=>BL(e))}function HL(e){e.dataset.syncRenderRoot="preact"}function qL(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function Ze(e,t){HL(e),Be(t,e)}function oi(e){e.dataset.syncRenderRoot==="preact"&&Be(null,e)}function KL(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 VL(e){return typeof e=="object"&&e!==null}function WL(e,t){return b.pairingCommandRaw="",{payloadText:e,hintText:t}}function zL(e){if(!VL(e))return WL("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 b.pairingCommandRaw=i,{payloadText:i,hintText:"Copy this command and run it on the other device. Use --include/--exclude to control which projects sync."}}function JL(){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 YL(){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 XL(){const e=b.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 QL(){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 ZL(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 e$({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 t$({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]}),a("div",{class:"right",children:n.startedAt})]},`${n.startedAt}-${n.peerLabel}-${r}`))]})}function Eb({text:e}){return a(Z,{children:e})}function n$({title:e,detail:t}){return a("div",{class:"sync-empty-state",children:[a("strong",{children:e}),a("span",{children:t})]})}function r$(e,t){if(!t.length){oi(e);return}Ze(e,a(e$,{items:t}))}function i$(e,t,n){if(!t.length){oi(e);return}Ze(e,a(t$,{attempts:t,note:n}))}function hr(e,t){Ze(e,a(n$,{...t}))}function xb(e,t,n){Ze(e,a(Eb,{text:n.payloadText})),t&&Ze(t,a(Eb,{text:n.hintText}))}function Pb({open:e,onOpenChange:t,triggerId:n,triggerClassName:r,closedLabel:i,openLabel:o,contentId:s,contentClassName:c,contentHost:l=null,children:d}){const u=U(null),p=U(null),f=U(!1);gt(()=>{u.current&&(u.current.id=n,u.current.setAttribute("aria-controls",s)),p.current&&(p.current.id=s)},[s,n,e]),K(()=>{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(Ea,{forceMount:!0,asChild:!0,children:a("div",{ref:p,id:s,className:c,hidden:!e,children:d})});return a(Ia,{open:e,onOpenChange:t,children:[a(wh,{asChild:!0,children:a("button",{ref:u,type:"button",className:r,id:n,"aria-controls":s,children:e?o:i})}),l?en(m,l):m]})}function o$({open:e,onOpenChange:t}){return a(Pb,{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(we,{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(we,{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(Vr,{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 a$({contentHost:e,open:t,onOpenChange:n}){return a(Pb,{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 s$(e,t){Ze(e,a(o$,{...t}))}function c$(e,t){Ze(e,a(a$,{...t}))}function pe(e){return String(e??"").trim()}function l$(e){return pe(e).replace(/\s+/g," ").toLowerCase()}function d$(e){const t=pe(e);return t?t.slice(0,8):"Unnamed device"}function Ab(e){return pe(e?.last_error).toLowerCase()}function Rb(e){return e.includes("401")&&e.includes("unauthorized")}function Db(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var u$={scope_filter:"sharing-domain membership",visibility_filter:"visibility",project_filter:"project filter"};function Lb(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 p$(e){const t=Lb(e);return!pe(e.device?.device_id)||e.device?.stale||e.hasAmbiguousCoordinatorGroup?!1:e.pairedLocally?t.state==="needs-your-approval":!0}function $b(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=v$(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=>Mb(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=>Mb(i)==="scope").length===n.length?{ok:!1,message:"Sync ran, but the peer is not authorized for one or more Spaces. Review Space access for this device in Teams, 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:pe(n[0]?.error)||"Sync failed for at least one device.",warning:!0}}function Mb(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=pe(e.error);return f$(n)?"trust":m$(n)?"scope":null}function f$(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function m$(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function h$(e){const t=pe(e?.reason);return u$[t]??(t.replaceAll("_"," ")||"sync filters")}function v$(e){const t=new Map;for(const n of e){const r=h$(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 Ob(e){const t=pe(e.localName);if(t)return t;const n=pe(e.coordinatorName);return n||d$(pe(e.deviceId))}function g$(e){const t=pe(e.localName),n=pe(e.coordinatorName);return t||n?!1:!!pe(e.deviceId)}function y$(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 Co(e){const t=pe(e?.status?.peer_state);if(t==="offline"||t==="stale")return"offline";const n=Ab(e);return Rb(n)?"needs-repair":Db(n)?"offline":e?.has_error||t==="degraded"?"needs-repair":t==="online"||e?.status?.fresh?"connected":"waiting"}function ai(e){const t=e?.status||{},n=pe(t.peer_state),r=Ab(e),i=pe(t.sync_status)==="ok"||pe(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}:Rb(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}:Db(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 b$={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 _$(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:b$[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 jb(e){return Array.isArray(e)?e.map(t=>pe(t)).filter(t=>!!t):[]}function Fb(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 Rs(e,t){return e?e.replaceAll("_"," "):t}function w$(e){const t=(Array.isArray(e.authorized_scopes)?e.authorized_scopes:[]).map(r=>{const i=pe(r.scope_id),o=pe(r.label);if(!i&&!o)return null;const s=o||"Untitled Space",c=[Rs(pe(r.kind),"user"),Rs(pe(r.authority_type),"local"),`${Rs(pe(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 Bb(e){const t=(Array.isArray(e.per_scope_sync)?e.per_scope_sync:[]).map(n=>{const r=pe(n.scope_id),i=pe(n.label);if(!r&&!i)return null;const o=i||"Untitled Space",s=pe(n.last_applied_cursor),c=pe(n.last_acked_cursor),l=n.bootstrapped===!0||s?"received":"pending",d=Rs(pe(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 S$=["personal","private","home","mine","me"],C$=["oss","open source","opensource","community","public"],N$=["work","client"],k$=["local","legacy","review"];function T$(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>pe(t)??"").join(" ").toLowerCase()}function I$(e){return[e.scope_id,e.label,e.kind].map(t=>pe(t)??"").join(" ").toLowerCase()}function Ub(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function eu(e,t){const n=T$(e);return t.some(r=>{const i=Ub(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function Gb(e){return eu(e,S$)||eu(e,C$)}function E$(e){const t=I$(e);return k$.some(n=>{const r=Ub(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function x$(e){return!Gb(e)&&(!E$(e)||eu(e,N$))}function P$(e){const t=Array.isArray(e.authorized_scopes)?e.authorized_scopes:[];if(!(pe(e.discovered_via_group_id)||pe(e.discovered_via_coordinator_id))||t.length===0)return{badgeLabel:null,detail:"",isVisible:!1,message:"",title:""};const n=t.some(Gb),r=t.some(x$);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 A$(e,t){const n=e.map(r=>r.trim()).filter(Boolean);return n.length>0&&!n.includes("*")||t.length>0}function R$(e){const t=jb(e?.effective_include),n=jb(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${Fb(t,"all projects")}`,o=`Exclude filter: ${Fb(n,"no exclusions")}`,s=A$(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 D$(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=pe(n?.display_name),i=pe(n?.actor_id),o=l$(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 Hb(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=pe(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=>pe(d?.actor_id)===c);!l||l.is_local||(i.get(c)??0)>0||o.add(c)})}),{visibleActors:t.filter(s=>!o.has(pe(s?.actor_id))),hiddenLocalDuplicateCount:o.size}}var L$=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),$$=new Set(["pending","verifying","waiting"]);function M$(e){return(Array.isArray(e?.groups)?e.groups.map(t=>pe(t)).filter(Boolean):[]).join(", ")||"none"}function qb(e){return pe(e?.projects?.[0]?.display_name)||"the shared Project"}function O$(e){const t=e?.items?.find(n=>n.state!=="active");return pe(t?.canonicalProjectIdentity)||"the shared Project"}function j$(e,t){return t?.discovered_devices?.some(n=>n.needs_local_approval||n.waiting_for_peer_approval)?!0:e.some(n=>{const r=ai(n).state;return r==="trusted-by-you"||r==="needs-repairing"})}function F$(e,t){return t?.enabled!==!0||t.daemon_state!=="ok"||t.daemon_running===!1?!1:e.some(n=>n.status?.sync_status==="ok"&&ai(n).state==="mutual-trust"&&!Bb(n).rows.some(r=>r.status==="pending"))}function B$(e){return e.some(t=>pe(t.status?.peer_state)==="online"&&ai(t).state==="mutual-trust")}function U$(e,t){return t?.daemon_state==="offline-peers"||t?.daemon_state==="stale"||t?.daemon_state==="degraded"?!0:e.some(n=>{const r=pe(n.status?.peer_state),i=ai(n).state;return n.has_error===!0&&i!=="needs-repairing"||i==="offline"||i==="needs-review"||r==="offline"||r==="stale"||r==="degraded"})}function G$(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 Kb(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=M$(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){const p=qb(s);return{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${o}. Exact-Project setup has not converged, so coordinator presence is not a healthy sync signal.`,nextAction:`Open Project sharing below and retry setup for ${p}.`}}if(c)return{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${o}. Recipient access has not converged, so coordinator presence is not a healthy sync signal.`,nextAction:"Open Sharing and use Manage projects for the affected recipient, then run Sync now again."};const l=r.find(p=>{const f=p.lifecycle?.state;return f!==void 0&&L$.has(f)}),d=i.find(p=>{const f=p.state;return f!==void 0&&$$.has(f)});if(l||d){const p=l?qb(l):O$(e.reconciliation??void 0),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(G$(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(j$(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=pe(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 configure a coordinator in Advanced settings."}:U$(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&&F$(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}:B$(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 H$(e){return e.discovered?.stale?e.peer?Co(e.peer)!=="connected":!0:!1}function Vb(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 tu(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 q$(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 K$(e){const t=pe(e?.coordinator_url),n=Array.isArray(e?.groups)?e.groups:[];return t?n.some(r=>pe(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 V$(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=pe(i?.peer_device_id);if(!o)return;const s=r(o);s.peer=i,s.localName=pe(i?.name)}),t.forEach(i=>{const o=pe(i?.device_id);if(!o)return;const s=r(o);s.discovered=i,s.coordinatorName=pe(i?.display_name)}),[...n.values()]}function W$(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=V$(n,r),o=e.duplicatePersonDecisions??{},s=D$(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=Ob({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId}),u=l.peer?Co(l.peer):"waiting",p=l.peer?ai(l.peer):null,f=pe(l.discovered?.fingerprint),m=pe(l.peer?.fingerprint);if(l.peer&&f&&m&&f!==m){c.push(Vb({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||pe(l.peer?.last_error)||"Sync needs review.";c.push(Vb({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(tu({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(tu({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(tu({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&&g$({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId})&&c.push(q$({id:l.deviceId,name:d,summary:"Give this device a friendly name so it is easier to recognize later."}))}),{primaryStatus:Kb({status:e.status,coordinator:e.coordinator,peers:n,shareOperations:e.shareOperations,shareOperationsLoadError:e.shareOperationsLoadError,reconciliation:e.reconciliation}),summary:{connectedDeviceCount:n.filter(l=>Co(l)==="connected").length,seenOnTeamCount:r.length,offlineTeamDeviceCount:i.filter(l=>H$(l)).length},duplicatePeople:s,attentionItems:c.sort((l,d)=>l.priority-d.priority||l.title.localeCompare(d.title))}}var Wb={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 Dn(e){const t=document.getElementById(e);t&&t.remove()}var zb=!1;function z$(e){zb=e}var nu=!1;function J$(e){nu=e}var ru=!1;function Y$(e){ru=e}var X$=new Set,iu=new Set,ou=new Set,Jb="codemem-sync-duplicate-person-decisions";function Q$(e){const t=String(e||"").trim();t&&(iu.add(t),ou.add(t),X$.add(t))}function au(e){const t=String(e||"").trim();return!!t&&iu.has(t)}function Z$(e){const t=String(e||"").trim();t&&iu.delete(t)}function eM(e){const t=String(e||"").trim();return!t||!ou.has(t)?!1:(ou.delete(t),!0)}function su(){try{const e=localStorage.getItem(Jb);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Yb(e){try{localStorage.setItem(Jb,JSON.stringify(e))}catch{}}function Xb(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function tM(){return su()}function nM(e,t){const n=Xb(e);if(!n)return;const r=su();r[n]=t,Yb(r)}function rM(e){const t=Xb(e);if(!t)return;const n=su();delete n[t],Yb(n)}function Qb(e){return e.replace(/\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b/g,"$1.#.#")}function Zb(e){const t=String(e||"");return t?Qb(t):""}function iM(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function oM(e,t){const n=String(e?.relatedPeerDeviceId??"").trim();return n?t.some(r=>String(r?.peer_device_id??"").trim()===n):!1}function Ds(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 cu(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":Ds(e)}function aM(e){return(Array.isArray(b.lastSyncPeers)?b.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function sM(){return Hb({actors:b.lastSyncActors,peers:b.lastSyncPeers,duplicatePeople:b.lastSyncViewModel?.duplicatePeople}).visibleActors}function e_(e){return sM().filter(t=>String(t?.actor_id||"")!==e)}function cM(e,t){const n=e_(t).find(r=>String(r?.actor_id||"")===e);return!e||!n?"Choose which person should keep these devices.":`Merge into ${cu(n)}. Assigned devices move now; existing memories keep their current provenance.`}function lu(e,t){if(e){if(e.textContent="",!t.length){e.hidden=!0;return}e.hidden=!1,t.slice(0,2).forEach(n=>{const r=Na("div","sync-action"),i=Na("div","sync-action-text");i.textContent=n.label,i.appendChild(Na("span","sync-action-command",n.command));const o=Na("button","settings-button sync-action-copy","Copy");o.addEventListener("click",()=>Oi(n.command,o)),r.append(i,o),e.appendChild(r)})}}function t_(e,t){return t&&e.error_redacted===!0}function n_(){const e=document.getElementById("syncAttempts");if(!e)return;const t=b.lastSyncAttempts,n=String(b.lastSyncStatus?.daemon_state||"").trim();if(!Array.isArray(t)||!t.length){hr(e,XL());return}const r=ZL(n,t.slice(0,5).some(i=>i.status==="error"));i$(e,t.slice(0,5).map(i=>{const o=i.started_at||i.started_at_utc||"",s=String(i.peer_device_id||"").trim(),c=Array.isArray(b.lastSyncPeers)?b.lastSyncPeers.find(f=>String(f?.peer_device_id||"")===s):null,l=String(c?.name||"").trim()||(s?s.slice(0,8):"unknown"),d=i.status==="error",u=[],p=Fi();if(d&&i.error){const f=String(i.error);u.push(p?Qb(f):f),t_(i,p)&&u.push("Turn off Redact in Advanced diagnostics to reveal the full error.")}return!d&&(i.ops_in||i.ops_out)&&u.push(`${i.ops_in??0} in · ${i.ops_out??0} out`),!p&&i.address&&u.push(i.address),{status:i.status||"unknown",peerLabel:l,detail:u.join(" · "),startedAt:o?ir(o):"",...t_(i,p)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}}),r)}function lM(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncAttempts"),n=document.getElementById("syncMeta"),r=document.getElementById("syncActions");e&&hr(e,YL()),t&&hr(t,QL()),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."),lu(r,[])}function si(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function dM(e){const t=String(e?.state??"clear"),n=e?.stale_peer_rows??{},r=e?.access_cleanup_ops??{},i=si(n.would_remove),o=si(n.ambiguous),s=si(r.applied),c=si(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 r_(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncMeta"),n=document.getElementById("syncActions");if(!e)return;Dn("syncDiagSkeleton");const r=b.lastSyncStatus;if(!r){hr(e,JL()),lu(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||KL(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||{},h=r.cleanup_diagnostics,g=h?.stale_peer_rows??{},_=si(g.would_remove),w=si(g.ambiguous),S=v.enabled===!0,N=Number(v.last_deleted_ops||0),k=v.last_run_at||null,E=String(v.last_error||""),R=m==="offline-peers"?"Offline peers":m==="needs_attention"?"Needs attention":m==="rebootstrapping"?"Rebootstrapping":hg(m),j=m==="disabled"||r.enabled===!1,q=Object.keys(i).length,I=!j&&q===0;if(t){const M=j?["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"]:I?["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: ${R}`,`Peers: ${q}`,c?`Last sync: ${Tn(Wr(c))} ago`:"Last sync: never"];m==="offline-peers"&&M.push("All peers are currently offline; sync will resume automatically"),f&&m==="stopped"&&M.push(`Detail: ${f}`),f&&(m==="needs_attention"||m==="rebootstrapping")&&M.push(`Detail: ${f}`),S&&M.push(k?`Retention last ran ${Tn(Wr(k))} ago (approx oldest-first)`:"Retention enabled"),_>0?M.push(`${_.toLocaleString()} stale peer rows pending cleanup`):w>0&&M.push(`${w.toLocaleString()} stale peer rows retained because safe cleanup could not be proven`),t.textContent=M.join(" · ")}const G=j?[{label:"State",value:"Disabled"},{label:"Mode",value:"Optional"},{label:"Pending events",value:p},{label:"Last sync",value:"Not running"}]:I?[{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:R},{label:"Pending events",value:p},{label:"Last sync",value:c?`${Tn(Wr(c))} ago`:"never"},{label:"Last peer ping",value:l?`${Tn(Wr(l))} ago`:"never"},{label:"Retention",value:S?k?`${N.toLocaleString()} ops last run (approx)`:"Enabled":"Disabled"}];!j&&!I&&(d||u)&&G.push({label:[d,u].filter(Boolean).join(" · "),value:"Errors"}),!j&&!I&&s.seconds_since_last&&G.push({label:"Since last sync",value:`${s.seconds_since_last}s`}),!j&&!I&&o.seconds_since_last&&G.push({label:"Since last peer ping",value:`${o.seconds_since_last}s`}),!j&&S&&E&&G.push({label:E,value:"Retention"}),!j&&!I&&h&&G.push({label:"Cleanup",value:dM(h)}),r$(e,G);const A=[];I||m==="offline-peers"||(m==="stopped"?(A.push({label:"Sync daemon is stopped. Start it.",command:"codemem serve start"}),A.push({label:"Run one sync pass now.",command:"codemem sync once"})):m==="needs_attention"?A.push({label:"Sync needs manual attention before reset can continue.",command:"codemem sync doctor"}):m==="rebootstrapping"?A.push({label:"Sync is rebuilding state in the background.",command:"codemem sync status"}):d||u||m==="error"?(A.push({label:"Sync reports errors. Restart now.",command:"codemem serve restart && codemem sync once"}),A.push({label:"Run doctor for the root cause.",command:"codemem sync doctor"})):!j&&!I&&p>0&&A.push({label:"Pending sync work detected. Run one pass now.",command:"codemem sync once"})),!j&&w>0?A.push({label:"Some stale peer rows were retained because cleanup was ambiguous.",command:"codemem sync doctor"}):!j&&_>0&&A.push({label:"Stale peer rows are eligible for cleanup. Run one sync pass now.",command:"codemem sync once"}),lu(n,A)}var uM="syncRedactMount",pM="syncRedactLabel",i_=()=>{};function fM(e){i_=e}var du=()=>{};function uu(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;c$(e,{contentHost:t,open:b.syncPairingOpen,onOpenChange:r=>{if(Bk(r),uu(),r){const i=document.getElementById("pairingPayload"),o=document.getElementById("pairingHint");i&&xb(i,o,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}du()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=b.pairingCommandRaw;r&&await Oi(r,n)})}function pu(){uu();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;xb(e,t,zL(b.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!b.pairingCommandRaw)}function o_(){const e=document.getElementById(uM);e&&Ze(e,y(Gr,{"aria-labelledby":pM,checked:Fi(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{Uk(t),o_(),du(),r_(),i_(),n_(),pu()},thumbClassName:"sync-redact-switch-thumb"}))}function mM(e){du=e,uu(),o_()}function hM(e){e.classList.add("sync-shake"),e.addEventListener("animationend",()=>e.classList.remove("sync-shake"),{once:!0})}function ci(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),hM(e),e.addEventListener("input",()=>No(e),{once:!0}),!1}function No(e){e.classList.remove("sync-field-error");const t=e.parentElement?.querySelector(".sync-field-hint");t&&t.remove()}function it(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 vr=new Map,fu=null,vM={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 gM(e){return vM[e instanceof Error?e.message:String(e)]??"Setup could not be retried. Review diagnostics for details."}function yM(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 bM(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function mu(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 _M({operation:e,onAdvance:t,onLoadOperation:n,onReload:r,copyText:i}){const[o,s]=D(!1),[c,l]=D(()=>vr.get(e.operation_id)??null),d=U(null),u=e.lifecycle.primary_action;K(()=>{fu!==e.operation_id||!d.current||(fu=null,d.current.focus())},[c?.message,e.operation_id]);async function p(h){s(!0);try{let g=h;if(!g&&n){const w=(await n(e.operation_id)).lifecycle.primary_action;w?.kind==="copy_invite"&&(g=w.invite_link)}if(!g)throw new Error("Invitation is no longer available. Refresh the status.");await(i??(w=>navigator.clipboard.writeText(w)))(g);const _={message:"Invite copied.",tone:"success"};vr.set(e.operation_id,_),l(_)}catch(g){const _={message:g instanceof Error?g.message:"Invite could not be copied.",tone:"warning"};vr.set(e.operation_id,_),l(_)}finally{s(!1)}}async function f(){s(!0);try{const h=await t(e.operation_id),g=h.lifecycle.state==="active"?{message:"Setup complete.",tone:"success"}:h.lifecycle.state==="needs_attention"?{message:"Setup still needs attention.",tone:"warning"}:{message:`Retry started. ${h.lifecycle.label}.`,tone:"success"};vr.set(e.operation_id,g),fu=e.operation_id,l(g),await r()}catch(h){const g={message:gM(h),tone:"warning"};vr.set(e.operation_id,g),l(g),queueMicrotask(()=>d.current?.focus())}finally{s(!1)}}function m(){const h=e.projects.map(g=>g.project_id?.trim()).filter(g=>!!g);if(h.length!==e.projects.length){const g={message:"The original project selection is unavailable. Refresh Projects and try again.",tone:"warning"};vr.set(e.operation_id,g),l(g);return}if(!pa(h,e.person.display_name)){const g={message:"Project sharing is unavailable. Refresh Projects and try again.",tone:"warning"};vr.set(e.operation_id,g),l(g)}}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":`${mu(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[a("div",{className:"peer-scope-summary",children:mu(e.lifecycle.state)}),a("ul",{"aria-label":`${mu(e.lifecycle.state)} projects`,className:"peer-scope-chips",children:e.projects.map((h,g)=>a("li",{className:"peer-scope-chip",children:h.display_name},`${h.display_name}:${g}`))}),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 wM({operations:e,...t}){const n=e[0].person,r=bM(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(_M,{operation:i,...t},i.operation_id))]})}function SM(e){return e.operations.length===0?null:a("div",{className:"project-share-person-groups",children:yM(e.operations).map(t=>a(wM,{...e,operations:t},t[0].person.actor_id))})}function CM(e,t){Ze(e,a(SM,{...t}))}function a_({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 NM(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 kM({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const o=String(e.actor_id||""),s=Ds(e),c=aM(o),l=e_(o),d=l.map(A=>String(A.actor_id||"")).join("|"),[u,p]=D(s),[f,m]=D(!1),[v,h]=D("Rename"),[g,_]=D(!1),[w,S]=D("Merge into selected person"),[N,k]=D(""),[E,R]=D(!1);K(()=>{p(s),m(!1),h("Rename"),_(!1),S("Merge into selected person"),k(""),R(!1)},[o,c,t,s,d]);const j=l.length?cM(N,o):"No other people are available yet. Create another person first if you need to merge duplicates.",q=[{label:"Merge into person",value:""},...l.map(A=>{const M=String(A.actor_id||"");return{label:A.is_local?cu(A):Ds(A),value:M}})];async function I(){const A=u.trim();if(!A)return;m(!0),h("Saving…");let M=!1;try{await n(o,A),M=!0}catch{h("Retry rename")}finally{m(!1),M&&h("Rename")}}async function G(){if(!N)return;const A=l.find(L=>String(L.actor_id||"")===N);if(!A||!await Ht({title:`Merge ${s} into ${Ds(A)}?`,description:"Assigned devices move now, but older memories keep their current stamped provenance for now.",confirmLabel:"Merge people",cancelLabel:"Keep separate",tone:"danger"}))return;_(!0),S("Merging…");let M=!1;try{await r(N,o),M=!0}catch{S("Retry merge")}finally{_(!1),M&&S("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:cu(e)}),a("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?NM(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(we,{"aria-label":`Rename ${s}`,className:"peer-scope-input actor-name-input",disabled:f||g,type:"text",value:u,onInput:A=>p(A.currentTarget.value),onKeyDown:A=>$r(A,{onSubmit:()=>{I()},disabled:f||g||!u.trim()})}),a("button",{type:"button",className:"settings-button","data-primary-action":"true",disabled:f||g,onClick:()=>{I()},children:v}),a("button",{type:"button",className:"settings-button danger",disabled:f||g,onClick:async()=>{await Ht({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||g,onClick:()=>R(A=>!A),children:E?"Hide duplicate cleanup":"Show duplicate cleanup"}),E?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(kn,{ariaLabel:`Merge ${s} into another person`,contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:g||l.length===0,itemClassName:"sync-radix-select-item",onValueChange:k,options:q,placeholder:"Merge into person",triggerClassName:"sync-radix-select-trigger sync-actor-select actor-merge-select",value:N,viewportClassName:"sync-radix-select-viewport"}),a("button",{type:"button",className:"settings-button",disabled:g||l.length===0||!N,onClick:()=>{G()},children:w})]}),a("div",{className:"peer-meta actor-merge-note",children:j})]}):null]})})]})}function TM({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(kM,{actor:o,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):a(a_,{detail:"Create a named person here for legacy provenance, then confirm device Identity ownership in Devices.",title:"No people set up yet."})}function IM(e,t){Ze(e,a(TM,{...t}))}function EM(e){return e.filter(t=>String(t.origin_device_id||"").trim())}function xM(e){const t=e.find(n=>String(n.last_seen_at||"").trim());return t?.last_seen_at?`Detected from older synced memories. Latest memory: ${ir(String(t.last_seen_at).trim())}`:"Detected from older synced memories not yet attached to a current device."}function PM({devices:e}){return a(Z,{children:xM(e)})}function AM(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 RM(e){const t=EM(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),oi(e.mount),oi(e.meta);return}const n=t.map(AM),r=n.some(i=>i.value===e.value)?e.value:n[0]?.value||"";r!==e.value&&e.onValueChange(r),e.panel.hidden=!1,Ze(e.mount,a(kn,{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"})),Ze(e.meta,a(PM,{devices:t}))}var DM={online:"Online",offline:"Offline",degraded:"Degraded",attention:"Action required",syncing:"Syncing",unknown:"Status unknown"};function LM({state:e,size:t=8,"aria-label":n}){return a("span",{"aria-label":n??DM[e],className:`presence-pip presence-pip--${e}`,role:"img",style:`--presence-pip-size: ${t}px`})}function gr({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 $M(){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 MM(e){switch(Co(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var Ls=null,s_=0,hu=new Set;function c_(e){if(Ls!==e){Ls=e,s_+=1;for(const t of hu)t(s_)}}function OM(){const[,e]=D(0);return K(()=>(hu.add(e),()=>{hu.delete(e)}),[]),Ls}var jM={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 l_(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 FM(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: ${l_(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: ${l_(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 BM(e){b.pendingDeviceIdentityFocus=e?.trim()||null,window.location.hash="devices"}function UM(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 GM(){window.location.hash="coordinator-admin"}function vu(e=b.lastCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function HM({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=ai(e),l=jM[y$(e)],d=e.status||{},u=w$(e),p=au(i),f=p&&u.total===0,m=P$(e),v=_$(e),h=Bb(e),g=R$(e.project_scope||{}),_=iM(e.addresses),w=Array.isArray(e.addresses)?Array.from(new Set(e.addresses.filter(Boolean).map(re=>String(re)))):[],S=Number(e.address_count??0),N=Number.isFinite(S)&&S>0?S:0,k=w.length?w.map(re=>Fi()?Zb(re):re).join(" · "):N>0?`${N} ${N===1?"address":"addresses"} hidden`:"No addresses",E=b.lastDeviceIdentityInventory?.items.find(re=>re.deviceId===i||re.evidenceDeviceIds.includes(i)),R=FM(E,String(e.actor_id||"")||null,b.lastSyncActors,b.deviceIdentityInventoryLoadError,b.lastDeviceIdentityInventory?.truncated===!0,b.lastDeviceIdentityInventory?.coordinatorEvidence.availability==="unavailable"),j=String(d.last_sync_at||d.last_sync_at_utc||""),q=String(d.last_ping_at||d.last_ping_at_utc||""),I=e.discovered_via_group_id?`Discovery: seen through Team ${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,G=eM(i),A=U(null),[M,L]=D(o),[x,O]=D(()=>b.syncPeerFeedbackById.get(i)??null),[T,P]=D(!1),[B,V]=D("Save name"),[le,de]=D(!1),[ae,be]=D(!1),[J,ve]=D("Remove device");K(()=>{p&&u.total>0&&Z$(i)},[u.total,i,p]),K(()=>{L(o),O(b.syncPeerFeedbackById.get(i)??null),P(!1),V("Save name"),de(!1),be(!1),ve("Remove device")},[o,e.actor_id,i]),K(()=>{!G||!A.current||queueMicrotask(()=>A.current?.scrollIntoView({block:"center",behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}))},[G]);async function ee(){if(!i)return;const re=M.trim();if(!re){const ut={message:"Enter a friendly name for this device.",tone:"warning"};O(ut),b.syncPeerFeedbackById.set(i,ut),document.querySelector(`[data-device-name-input="${CSS.escape(i)}"]`)?.focus();return}P(!0),V("Saving…");try{const ut=await n(i,re);O(ut),b.syncPeerFeedbackById.set(i,ut),V("Save name")}catch{V("Retry")}finally{P(!1)}}async function Te(){if(f){const re=vu();if(!await Ht({title:`Sync ${o} before advanced rule review?`,description:re?"This manual sync will use the current Space access and advanced filters until you review them in Teams.":"This manual sync will use the current Space access and advanced filters until a coordinator or manager reviews them in Teams.",confirmLabel:"Sync anyway",cancelLabel:re?"Review in Teams first":"Cancel"}))return}de(!0);try{const re=await r(e,_);O(re),re&&b.syncPeerFeedbackById.set(i,re)}finally{de(!1)}}async function fe(){if(!i||!await Ht({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;be(!0),ve("Removing…");let re=!1;try{await t(i,s),re=!0}catch{ve("Retry remove")}finally{be(!1),re&&ve("Remove device")}}const te=OM()===i&&i!=="",Ie=`device-drawer-${i||"unknown"}`,ce=MM(e),Ae=j?`Sync: ${ir(j)}`:"Sync: never",ue=vu(),Ke=`${te?"Collapse":"Expand"} device ${o}`;return a(Ia,{asChild:!0,open:te,onOpenChange:re=>{re?c_(i):Ls===i&&c_(null)},children:a("div",{ref:A,className:"peer-card","data-peer-device-id":i||void 0,children:[a(wh,{asChild:!0,children:a("button",{"aria-label":Ke,className:"device-row-head device-row-head--trigger",type:"button",children:[a(LM,{state:ce}),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:Ae}),a("span",{"aria-hidden":"true",className:"device-row-chevron",children:a($M,{})})]})}),a(Ea,{"aria-label":`Device actions for ${o}`,className:"device-row-drawer",id:Ie,children:[a("div",{className:"peer-actions",children:[a("button",{type:"button",className:"settings-button",disabled:le,onClick:()=>{Te()},title:_?void 0:"Address details are hidden; sync will target this device by ID.",children:le?"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(we,{"aria-label":`Friendly name for ${o}`,className:"peer-scope-input","data-device-name-input":i||void 0,disabled:T,id:`device-name-${i||"unknown"}`,placeholder:"Friendly device name",type:"text",value:M,onInput:re=>L(re.currentTarget.value)})]}),a("button",{type:"button",className:"settings-button",disabled:T,onClick:()=>{ee()},children:B}),a("button",{type:"button",className:"settings-button danger",disabled:ae,onClick:()=>{fe()},children:J})]}),a("div",{className:"peer-scope",children:[G?a("div",{className:"peer-meta",children:ue?"Review this device's Space access and advanced rules in Teams if the defaults are too broad.":"A coordinator or manager can review this device's Space access and advanced rules in Teams 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:k}),I?a("div",{className:"peer-meta",children:I}):null,a("div",{className:"peer-meta",children:[j?`Sync: ${ir(j)}`:"Sync: never",q?`Ping: ${ir(q)}`:"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(re=>a("li",{className:"peer-scope-chip",title:re.detail,children:re.label},re.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:g.note}),a("div",{className:"peer-scope-summary",children:"Space sync progress"}),a("div",{className:"peer-meta",children:h.total>0?"Per-Space progress for this device. Open details to see technical identifiers.":h.emptyMessage}),h.rows.length>0?a("ul",{className:"peer-scope-rejections-list","aria-label":"Per-Space sync progress",children:h.rows.map(re=>a("li",{title:re.detail,children:[a("span",{className:"peer-scope-rejection-label",children:re.label}),a("span",{className:`badge ${re.status==="received"?"badge-online":"actor-badge"}`,children:re.badgeLabel})]},re.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(re=>a("li",{children:[a("span",{className:"peer-scope-rejection-label",children:re.label}),a("span",{className:"peer-scope-rejection-count",children:re.count.toLocaleString()})]},re.reason))}),v.lastAt?a("div",{className:"peer-meta",children:["Last rejected ",ir(v.lastAt)]}):null]}):null,a("div",{className:"peer-scope-summary",children:"Authoritative Identity ownership"}),a("div",{className:"peer-meta",children:R.summary}),a("div",{className:"peer-meta",children:R.detail}),e.claimed_local_actor?a("div",{className:"peer-meta",children:UM(e.claimed_local_actor_scope)}):null,a("div",{className:"peer-actor-row",children:a("button",{type:"button",className:"settings-button",onClick:()=>BM(E?.deviceId??i),children:R.actionLabel})}),a("div",{className:"peer-scope-summary",children:"Advanced sharing rules"}),a("div",{className:"peer-meta",children:[g.statusLabel,". ",g.summary," ",g.note]}),ue?a("div",{className:"peer-actions",children:a("button",{type:"button",className:"settings-button",onClick:GM,children:"Manage Spaces in Teams"})}):a("div",{className:"peer-meta",children:"Space access is managed in Teams by a coordinator or manager."}),a(gr,{feedback:x})]})]})]})})}function qM(e){const t=b.syncPeersSectionFeedback,n=b.lastSyncStatus,r=n?.daemon_state==="disabled"||n?.enabled===!1;return e.peers.length?a(Z,{children:[a(gr,{feedback:t}),e.peers.map(i=>{const o=String(i.peer_device_id||i.name||"unknown-peer");return a(HM,{peer:i,...e},o)})]}):a(Z,{children:[a(gr,{feedback:t}),a(a_,{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 KM(e,t){Ze(e,a(qM,{...t}))}var Ln=async()=>{},$s="";function gu(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function VM(e){Ln=e}function WM(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;Dn("syncActorsSkeleton"),gu(!1);const n=Hb({actors:b.lastSyncActors,peers:b.lastSyncPeers,duplicatePeople:b.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.`)),IM(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,o)=>{await Ww(i,o),await Ln()},onMerge:async(i,o)=>{try{await fp(i,o),ne("People combined. Assigned devices moved to the selected person."),await Ln()}catch(s){throw ne(it(s,"Failed to combine people."),"warning"),s}},onDeactivate:async i=>{try{await zw(i),ne("Person removed. Assigned devices have been unassigned."),await Ln()}catch(o){throw ne(it(o,"Failed to remove person."),"warning"),o}}})}function zM(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");gu(!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&&hr(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. When the people endpoint responds again, named people will reload here."})}function JM(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;CM(e,{operations:b.lastShareOperations,onAdvance:n=>Ow(n),onLoadOperation:n=>Mw(n),onReload:Ln});const t=document.getElementById("syncProjectShareOperationsMeta");t&&(t.textContent=b.shareOperationsLoadError?"Project sharing status could not be refreshed. Existing device diagnostics remain available below.":b.lastShareOperations.length>0?"Project access is grouped by Person. Devices appear after invitation acceptance.":"Share a project from Projects to invite a teammate.")}function yu(){const e=document.getElementById("syncPeers");if(!e)return;Dn("syncPeersSkeleton");const t=b.lastSyncPeers,n=Array.isArray(t)?t:[];oM(b.syncPeersSectionFeedback,n)&&(b.syncPeersSectionFeedback=null),KM(e,{peers:n,onRename:async(r,i)=>{try{return await rp(r,i),await Ln(),{message:"Device name saved.",tone:"success"}}catch(o){return{message:it(o,"Failed to save device name."),tone:"warning"}}},onSync:async(r,i)=>{try{const o=String(r?.peer_device_id||""),s=$b(await tc({address:i,peerDeviceId:o||void 0}));let c;s.ok?o&&au(o)?c={message:`Triggered sync for ${r?.name||(o?o.slice(0,8):"unknown")}. ${vu()?"Review Space access and advanced rules in Teams if this device needs tighter sharing.":"A coordinator or manager can review Space access and advanced rules in Teams if this device needs tighter sharing."}`,tone:"warning"}:c={message:s.message,tone:"success"}:c={message:s.message,tone:"warning"};try{await Ln()}catch{c={message:"Sync started, but this view has not refreshed yet. Refresh the page or use Sync now again before retrying.",tone:"warning"}}return c}catch(o){return{message:it(o,"Failed to trigger sync."),tone:"warning"}}},onRemove:async(r,i)=>{try{await np(r);const o={message:`Removed peer ${i}.`,tone:"success"};return b.syncPeerFeedbackById.delete(r),b.syncPeersSectionFeedback={...o,relatedPeerDeviceId:r},await Ln(),o}catch(o){return{message:it(o,"Failed to remove peer. The local peer entry is still here."),tone:"warning"}}}})}function YM(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");gu(!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&&hr(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&&hr(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 d_(){const e=document.getElementById("syncLegacyClaims"),t=document.getElementById("syncLegacyDeviceSelectMount"),n=document.getElementById("syncLegacyClaimsMeta");!e||!t||!n||RM({devices:Array.isArray(b.lastSyncLegacyDevices)?b.lastSyncLegacyDevices:[],meta:n,mount:t,onValueChange:r=>{r!==$s&&($s=r,d_())},panel:e,value:$s})}function XM(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput"),r=document.getElementById("syncLegacyClaimButton");n?.addEventListener("keydown",i=>{$r(i,{onSubmit:()=>t?.click(),disabled:!t||t.disabled})}),t?.addEventListener("click",async()=>{if(!t||!n)return;const i=String(n.value||"").trim();if(!i){ci(n,"Enter a name for the person.");return}No(n),t.disabled=!0,n.disabled=!0,t.textContent="Creating…";try{await Vw(i),ne("Person created."),n.value="",await e()}catch(o){ne(it(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($s||"").trim();if(!i||!r||!await Ht({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 Jw(i),ne("Old device history attached to you."),await e()}catch(s){ne(it(s,"Failed to attach old device history."),"warning"),r.textContent="Retry",r.disabled=!1;return}r.textContent=o,r.disabled=!1})}function QM(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function bu(e=QM()){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 u_=!1;function ZM(){u_||(u_=!0,window.addEventListener("hashchange",()=>{bu()}))}var Wt={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function eO(e){Wt.loadSyncData=e}var tO=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function nO(){const e=document.getElementById("syncCreateInviteButton"),t=document.getElementById("syncInviteAdminHint");if(!e||!t)return;const n=b.lastCoordinatorAdminStatus?.readiness,r=String(b.lastCoordinatorAdminStatus?.active_group||"").trim();if(n==="ready"){e.disabled=!1,t.hidden=!1,t.textContent=r?`Teams is ready for ${r}. Advanced admin tools now live in Teams.`:"Teams is ready. Advanced admin tools now live in Teams.";return}const i=n==="partial"?"Finish Teams setup before creating remote invites. Use Teams to check what is missing.":"Configure a coordinator URL, Team, and admin secret before creating remote invites. Use Teams to finish setup.";e.disabled=!0,t.hidden=!1,t.textContent=i}function _u(){const e=document.getElementById("syncAdminDisclosureMount");e&&s$(e,{open:zb,onOpenChange:t=>{z$(t),_u(),Os(),wu()}})}function rO(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function wu(){const e=document.getElementById("syncInviteOutput"),t=document.getElementById("syncInviteWarnings");if(!e)return;const n=String(b.lastTeamInvite?.encoded||"").trim();if(e.value=n,e.hidden=!n,t){const r=Array.isArray(b.lastTeamInvite?.warnings)?b.lastTeamInvite.warnings:[];t.textContent=r.join(" · "),t.hidden=r.length===0}}function Ms(){const e=document.getElementById("syncJoinFeedback");if(!e)return;const t=b.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 Os(){const e=document.getElementById("syncInvitePolicyMount");e&&Ze(e,y(kn,{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!==Wt.invitePolicy&&(Wt.invitePolicy=n,Os())},options:tO,triggerClassName:"sync-radix-select-trigger sync-actor-select",value:Wt.invitePolicy,viewportClassName:"sync-radix-select-viewport"}))}function iO(e,t){_u(),Os();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 h="",g=0;r?.addEventListener("click",()=>{pa()||ne("Project sharing is unavailable. Refresh Projects and try again.","warning")});const _=async(w,S)=>{if(!u||!m||!v)return"other";const N=await tp(w);if(S!==g||d?.value.trim()!==w)return"stale";if(N.kind!=="project_share_invite")return"other";const k=(N.projects??[]).map(E=>`${E.display_name} (${E.existing_memory_count} existing ${E.existing_memory_count===1?"memory":"memories"})`).join(", ");return p&&(p.textContent=`${N.inviter_name||"A teammate"} invited you${N.team_name?` through ${N.team_name}`:""} to share ${k||"selected projects"}.`),m.value=xr(N.recipient_name),v.value=xr(N.device_name),u.hidden=!1,h=w,l&&(l.textContent="Accept and start syncing"),f?.focus(),"project"};d?.addEventListener("input",()=>{g+=1,d.value.trim()!==h&&(h="",u&&(u.hidden=!0),l&&(l.textContent="Review invite"))}),i?.addEventListener("click",async()=>{if(!i||!o||!s||!c||i.disabled)return;const w=o.value.trim(),S=Number(s.value);let N=!0;if(w?No(o):N=ci(o,"Team name is required."),!S||S<1?N=ci(s,"Must be at least 1 hour."):No(s),!!N){i.disabled=!0,i.textContent="Creating…";try{const k=await Qu({group_id:w,policy:Wt.invitePolicy,ttl_hours:S||24});b.lastTeamInvite=k,wu(),c.value=String(k.encoded||""),c.hidden=!1,c.focus(),c.select();const E=Array.isArray(k.warnings)?k.warnings:[];ne(E.length?`Invite created. Copy it above and review ${E.length===1?"1 warning":`${E.length} warnings`}.`:"Invite created. Copy the text above and share it with your teammate.",E.length?"warning":"success")}catch(k){ne(it(k,"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",w=>{$r(w,{onSubmit:()=>l?.click(),disabled:!l||l.disabled})}),l?.addEventListener("click",async()=>{if(!l||!d)return;const w=d.value.trim();if(!w){ci(d,"Paste a team invite or pairing payload.");return}if(No(d),h!==w){const N=g;try{const k=await _(w,N);if(k==="project"||k==="stale")return}catch{}if(N!==g||d.value.trim()!==w)return;h=w,l.textContent="Accept invite";return}const S=u&&!u.hidden?{recipient_name:m?.value.trim()??"",device_name:v?.value.trim()??""}:void 0;if(S){const N=k=>xr(k)==="";if(N(S.recipient_name)){m&&ci(m,"Enter a human-readable name using 120 characters or fewer.");return}if(N(S.device_name)){v&&ci(v,"Enter a human-readable device name using 120 characters or fewer.");return}}l.disabled=!0,l.textContent="Accepting…";try{const N=await Ys(w,S);b.lastTeamJoin=N;const k=N,E=typeof k.type=="string"?k.type:"team_join";let R;if(E==="pair"){const j=String(N.peer_device_id??"").trim();R={message:j?`Paired with device ${j.slice(0,8)}. It will appear in People & devices.`:"Paired the device. It will appear in People & devices.",tone:"success"}}else if(E==="project_share"){const j=k.restart_required===!0||k.setup_state==="pending_inviter"||N.status==="pending_setup",q=typeof k.detail=="string"?k.detail.trim():"";R=j?{message:q||(k.restart_required===!0?"Project invitation accepted. Restart codemem to finish setup.":k.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 R={message:N.status==="pending"?"Join request sent. Waiting for admin approval.":"Joined the team.",tone:"success"};b.syncJoinFlowFeedback=R,Ms(),d.value="",h="",u&&(u.hidden=!0);try{await t()}catch(j){R={message:it(j,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},b.syncJoinFlowFeedback=R,Ms()}}catch(N){b.syncJoinFlowFeedback={message:it(N,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},Ms(),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 w=$b(await tc());ne(w.message,w.warning?"warning":void 0)}catch(w){ne(it(w,"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 Su({element:e,hidden:t=!1,restoreParent:n=null}){const r=U(null);return gt(()=>{e&&(e.hidden=t)},[e,t]),gt(()=>{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 oO({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(Su,{element:e,hidden:!t,restoreParent:n}):null]})}function aO(){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=>Oi("codemem sync pair --payload-only",e.currentTarget),children:"Copy pairing command"})]})}function sO({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(Su,{element:e,hidden:!t,restoreParent:n}):null]})}function cO({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(Su,{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(sO,{joinPanel:r,joinPanelOpen:i,joinRestoreParent:o,onToggle:c}),a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),u?null:a(oO,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:s}),!l&&d==="posted"?a(aO,{}):null]})}function js({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 Fs({children:e}){return a("div",{className:"section-meta sync-section-note",children:e})}function lO({item:e,onAction:t}){const[n,r]=D(!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 dO({request:e,onApprove:t,onDeny:n}){const[r,i]=D(null),[o,s]=D(null),[c,l]=D("Approve"),[d,u]=D("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(gr,{feedback:o})]})}function uO({row:e,onInspectConflict:t,onRemoveConflict:n,onReview:r}){const[i,o]=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 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{c(await r(e)||null),u(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==="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(gr,{feedback:s})]})}function pO(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(js,{label:"Needs attention"}):null,r?a(Fs,{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(lO,{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 fO({children:e}){return e?a(Z,{children:[a(js,{label:"Add devices & teammates"}),a(Fs,{children:"Use these flows when you are enrolling, inviting, or pairing something new."}),e]}):null}function mO({mount:e,rows:t,onInspectConflict:n,onRemoveConflict:r,onReview:i}){return!e||!t.length&&!b.syncDiscoveredFeedback?null:en(a(Z,{children:[a(js,{count:t.length||void 0,label:"Devices waiting for review"}),a(Fs,{children:"Review team devices here when they still need trust, re-pairing, or approval on this machine."}),a(gr,{feedback:b.syncDiscoveredFeedback}),t.map(o=>a(uO,{row:o,onInspectConflict:n,onRemoveConflict:r,onReview:i},o.deviceId))]}),e)}function hO({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!b.syncJoinRequestsFeedback?null:en(a(Z,{children:[a(js,{count:t.length||void 0,label:"Join requests to review"}),a(Fs,{children:"Approve or deny requests here before those devices become part of the team."}),a(gr,{feedback:b.syncJoinRequestsFeedback}),t.map(i=>a(dO,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function p_(e){return a(Z,{children:[a(pO,{...e}),a(fO,{children:e.children}),a(hO,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),a(mO,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function f_(e){e&&(e.textContent="")}function Bs(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 vO(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function ko(){return vO()?"auto":"smooth"}var Cu="syncTeamActionsMount";function gO(e,t,n=!1){return e.length>1&&(!t||n)}function yO(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 bO(e,t){const n=document.createElement("div");n.id=Cu,e.appendChild(n),Ze(n,y(p_,{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 m_(e,t){const n=document.getElementById(Cu);n&&(oi(n),n.remove()),f_(e),t.forEach(r=>{f_(r)})}function Us(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;_u(),Os(),wu(),Ms(),nO();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");Dn("syncTeamSkeleton"),rO();const p=b.lastSyncCoordinator,f=b.lastSyncViewModel||{primaryStatus:Kb({status:b.lastSyncStatus,coordinator:p,peers:b.lastSyncPeers,shareOperations:b.lastShareOperations,shareOperationsLoadError:b.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]},m=A=>{if(A.kind==="possible-duplicate-person"){const O=document.getElementById("syncActorsList");O instanceof HTMLElement&&(O.scrollIntoView({block:"center",behavior:ko()}),Bs(O));return}const M=String(A.deviceId||"").trim();if(!M)return;if(A.kind==="name-device"){const O=document.querySelector(`[data-device-name-input="${CSS.escape(M)}"]`);if(O instanceof HTMLInputElement){O.scrollIntoView({block:"center",behavior:ko()}),O.focus(),O.select(),Bs(O);return}}const L=document.querySelector(`[data-peer-device-id="${CSS.escape(M)}"]`);if(L instanceof HTMLElement){L.scrollIntoView({block:"center",behavior:ko()}),Bs(L);return}const x=document.querySelector(`[data-discovered-device-id="${CSS.escape(M)}"]`);x instanceof HTMLElement&&(x.scrollIntoView({block:"center",behavior:ko()}),Bs(x))},v=async A=>{const M=Array.isArray(A.actorIds)?A.actorIds.map(P=>String(P||"").trim()).filter(Boolean):[],L=(Array.isArray(b.lastSyncActors)?b.lastSyncActors:[]).filter(P=>M.includes(String(P?.actor_id||"").trim()));if(L.length<2){ne("This duplicate review is outdated. Refresh the card and review the remaining people entries.","warning");return}const x=await nx({title:"Review possible duplicate people",summary:A.title.replace(/^Possible duplicate person:\s*/,""),actors:L.map(P=>({actorId:String(P?.actor_id||""),label:String(P?.display_name||P?.actor_id||"Unknown person"),isLocal:!!P?.is_local}))});if(x.action==="different-people"){nM(M,"different-people"),ne("Okay. I will keep these people separate on this device."),await Wt.loadSyncData();return}if(x.action!=="merge")return;const O=L.find(P=>String(P?.actor_id||"")===x.primaryActorId),T=L.find(P=>String(P?.actor_id||"")===x.secondaryActorId);if(!O?.actor_id||!T?.actor_id){ne("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await fp(String(O.actor_id),String(T.actor_id)),rM(M),ne(`Combined duplicate people into ${String(O.display_name||O.actor_id)}.`),await Wt.loadSyncData()}catch(P){try{await Wt.loadSyncData()}catch{}ne(it(P,"Failed to combine these people."),"warning")}},h=async A=>await ql({title:"Pair with this device",description:"Choose a friendly name for this device before pairing it on this machine.",initialValue:A,placeholder:"Desk Mini",confirmLabel:"Pair",cancelLabel:"Cancel",validate:M=>M.trim()?null:"Enter a device name to pair this device."}),g=!!p?.configured,_=K$(p);e.title=g?String(p.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?yO(w,e,f.primaryStatus):e.textContent=f.primaryStatus.meta,!g){m_(n,[c,u]),t.hidden=!1,n.hidden=!1,bO(n,f.primaryStatus),c&&(c.hidden=!0),l&&(l.hidden=!0);return}t.hidden=!0,n.hidden=!1;const S=String(p.presence_status||""),N=Array.isArray(b.lastSyncPeers)?b.lastSyncPeers:[],k=Array.isArray(f.attentionItems)?f.attentionItems:[],E=(Array.isArray(p.discovered_devices)?p.discovered_devices:[]).map(A=>{const M=String(A.device_id||"").trim(),L=Ob({coordinatorName:String(A.display_name||"").trim(),deviceId:M})||"Discovered device",x=M&&L!==M?M:null,O=String(A.fingerprint||"").trim(),T=Array.isArray(A.groups)?A.groups.map(Ie=>String(Ie||"").trim()).filter(Boolean):[],P=N.find(Ie=>String(Ie?.peer_device_id||"")===M),B=gO(T,!!P,A.needs_local_approval===!0),V=Lb({device:A,pairedLocally:!!P}),le=String(P?.fingerprint||"").trim(),de=!!P&&!!O&&!!le&&le!==O,ae=!_&&p$({device:A,hasAmbiguousCoordinatorGroup:B,pairedLocally:!!P}),be=Array.isArray(A.addresses)?A.addresses:[],J=Number(A.address_count??0),ve=Number.isFinite(J)&&J>0?J:0,ee=[be.length?be.map(Ie=>Fi()?Zb(String(Ie||"")):String(Ie||"")).filter(Boolean).join(" · "):ve>0?`${ve} ${A.stale?"last-known":"fresh"} ${ve===1?"address":"addresses"} hidden`:"No fresh addresses"];!be.length&&x&&ee.push(`device id: ${M}`);let Te=null,fe=ae?"accept":"none",te=null;return de?fe="conflict":_&&(!P||V.state==="needs-your-approval")?(Te=_.message,fe="setup-blocked"):B?(Te="This device appears in multiple coordinator groups. Review the Team setup before approving it here.",fe="ambiguous"):P&&au(M)?(Te="Review this device's Space access and advanced rules in Teams before you sync it.",fe="scope-pending"):P?.last_error?(ee.push(`error: ${String(P.last_error)}`),ae||(fe="paired")):P?.status?.peer_state?(ee.push(`status: ${String(P.status.peer_state)}`),ae||(fe="paired")):!P&&A.stale?(Te="Wait for a fresh coordinator presence update, then review this device again here.",fe="stale"):P&&!ae&&(fe="paired"),fe==="paired"&&(te=V.state==="waiting-for-other-device"?V.description||"Waiting on the other device.":String(P?.last_error||"").toLowerCase().includes("401")&&String(P?.last_error||"").toLowerCase().includes("unauthorized")?"Waiting for the other device to trust this one before sync can work.":null),{actionMessage:Te,actionLabel:V.actionLabel||(P?"Review device":"Pair with this device"),approvalBadgeLabel:V.badgeLabel,availabilityLabel:A.stale?"Offline":"Available",connectionLabel:de?Wb.conflicts:P?Wb.pairedLocally:"Not connected on this device",deviceId:M,displayName:L,displayTitle:x,fingerprint:O,mode:fe,note:ee.join(" · "),pairedMessage:te}}),R=[],j=E.filter(A=>A.mode!=="paired"&&A.mode!=="none"&&A.mode!=="scope-pending"),q=E.filter(A=>A.mode==="accept"||A.mode==="scope-pending").length,I=k.length+R.length+q;l&&(l.hidden=j.length===0&&!b.syncDiscoveredFeedback),d&&(d.textContent=j.length?"Pair with a teammate's device to see it appear in People & devices and start syncing.":""),c&&(c.hidden=R.length===0&&!b.syncJoinRequestsFeedback),m_(n,[c,u]);const G=document.createElement("div");G.id=Cu,n.appendChild(G),Ze(G,y(p_,{actionItems:k,actionableCount:I,children:y(cO,{invitePanel:r,invitePanelOpen:nu,inviteRestoreParent:i,joinPanel:o,joinPanelOpen:ru,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(J$(!nu),Us())},onToggleJoinPanel:()=>{o&&(Y$(!ru),Us())},pairedPeerCount:Number(p.paired_peer_count||0),presenceStatus:S}),discoveredListMount:u,discoveredRows:j,joinRequestsMount:c,onApproveJoinRequest:async()=>null,onAttentionAction:async A=>{if(A.kind==="possible-duplicate-person"){await v(A);return}m(A)},onDenyJoinRequest:async()=>null,onInspectConflict:A=>{const M=document.querySelector(`[data-peer-device-id="${CSS.escape(A.deviceId)}"]`);if(M instanceof HTMLElement){M.scrollIntoView({block:"center",behavior:ko()}),ne(`Opened the conflicting local device record for ${A.displayName}.`,"warning");return}ne("The conflicting local device record is not visible yet. Scroll to People & devices and try again.","warning")},onRemoveConflict:async A=>{if(!await Ht({title:`Remove ${A.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 np(A.deviceId);const M={message:`Removed the broken local device record for ${A.displayName}. If it is still available, review it again from Next steps or Devices seen on team.`,tone:"success"};return b.syncDiscoveredFeedback=M,await Wt.loadSyncData(),M}catch(M){return{message:it(M,"Failed to remove the broken local device record. The old local record is still present in People & devices."),tone:"warning"}}},onReviewDiscoveredDevice:async A=>{try{const M=await h(A.displayName);if(!M)return null;const L=await Tw(A.deviceId,A.fingerprint),x=String(L?.name||A.displayName||"").trim()||A.displayName;b.pendingAcceptedSyncPeers=[...Array.isArray(b.pendingAcceptedSyncPeers)?b.pendingAcceptedSyncPeers.filter(T=>String(T?.peer_device_id||"").trim()!==A.deviceId):[],{peer_device_id:A.deviceId,name:x,fingerprint:A.fingerprint,addresses:[],claimed_local_actor:!1,status:{peer_state:"degraded"},last_error:"Waiting for the other device to approve this one."}],Q$(A.deviceId);let O={message:A.approvalBadgeLabel==="Needs your approval"?`Approved ${A.displayName} on this device. Two-way trust should be ready once both devices refresh.`:`Step 1 complete on this device for ${A.displayName}. Finish onboarding on the other device so both sides trust each other for sync.`,tone:"success"};try{M.trim()!==x.trim()&&(await rp(A.deviceId,M.trim()),b.pendingAcceptedSyncPeers=b.pendingAcceptedSyncPeers.map(T=>String(T?.peer_device_id||"").trim()===A.deviceId?{...T,name:M.trim()}:T),O={message:`Connected ${M.trim()} and saved its name.`,tone:"success"})}catch(T){O={message:it(T,"Device connected, but naming did not finish."),tone:"warning"}}b.syncDiscoveredFeedback=O;try{await Wt.loadSyncData()}catch(T){O={message:it(T,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},b.syncDiscoveredFeedback=O}return O}catch(M){return{message:it(M,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:R,presenceStatus:S,primaryStatus:f.primaryStatus}))}function _O(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 li(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function h_(e){return li(e)?"Unclear project identity":e.displayProject}function It(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function wO(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function SO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function CO(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function NO(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function kO(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 TO(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function IO({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"," · ",kO(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:TO(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 v_(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${SO(t)}\\b`,"g"),CO(t,n))),r}function EO(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 xO({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 PO({item:e,onReassign:t,onReview:n}){const r=e.groups??[],i=e.targetScopes??[],o=Object.fromEntries(r.map(T=>[T.workspaceIdentity,T.suggestedScopeId??""])),[s,c]=D({}),[l,d]=D({}),[u,p]=D(o),[f,m]=D({}),[v,h]=D("all"),[g,_]=D(""),[w,S]=D(null),N=r.length,k=e.totalGroupCount??N,E=r.filter(li).length,R=r.filter(T=>T.suggestedScopeId&&!li(T)&&It(T)).length,j=r.filter(T=>f[T.workspaceIdentity]&&It(T)).length,q=r.filter(T=>f[T.workspaceIdentity]&&It(T)&&!!u[T.workspaceIdentity]).length,I=r.filter(T=>{const P=li(T);return v==="suggested"&&(!T.suggestedScopeId||P)||v==="cleanup"&&!P||v==="no-suggestion"&&(T.suggestedScopeId||P)||v==="selected"&&!f[T.workspaceIdentity]?!1:!g.trim()||EO(T,i).includes(g.trim().toLowerCase())});async function G(T){const P=u[T.workspaceIdentity]||T.suggestedScopeId||"";if(!(!P||!t||w)){S(T.workspaceIdentity),d(B=>{const V={...B};return delete V[T.workspaceIdentity],V});try{const B=await t(T,P,!!s[T.workspaceIdentity],s[T.workspaceIdentity]?.confirmation_token);c(B?V=>({...V,[T.workspaceIdentity]:B}):V=>{const le={...V};return delete le[T.workspaceIdentity],le})}catch(B){d(V=>({...V,[T.workspaceIdentity]:v_(B,P,i)}))}finally{S(null)}}}function A(T,P){p(B=>({...B,[T.workspaceIdentity]:P})),c(B=>{const V={...B};return delete V[T.workspaceIdentity],V}),d(B=>{const V={...B};return delete V[T.workspaceIdentity],V})}function M(T,P){m(B=>({...B,[T.workspaceIdentity]:P}))}function L(T){m(P=>({...P,...Object.fromEntries(I.filter(It).map(B=>[B.workspaceIdentity,T]))}))}function x(){m(T=>({...T,...Object.fromEntries(r.filter(P=>P.suggestedScopeId&&!li(P)&&It(P)).map(P=>[P.workspaceIdentity,!0]))}))}async function O(){if(!t||w||q===0)return;const T=r.filter(P=>f[P.workspaceIdentity]&&It(P)&&!!u[P.workspaceIdentity]);if(!T.every(P=>s[P.workspaceIdentity])){S("bulk");try{for(const P of T){if(s[P.workspaceIdentity])continue;const B=u[P.workspaceIdentity]||P.suggestedScopeId||"";if(B)try{const V=await t(P,B,!1);d(le=>{const de={...le};return delete de[P.workspaceIdentity],de}),V&&c(le=>({...le,[P.workspaceIdentity]:V}))}catch(V){d(le=>({...le,[P.workspaceIdentity]:v_(V,B,i)}))}}}finally{S(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:[k.toLocaleString()," older"," ",k===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",N<k?` Showing ${N.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 ${N.toLocaleString()}`],["suggested",`Suggested ${R.toLocaleString()}`],["cleanup",`Needs cleanup ${E.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${q.toLocaleString()}`]].map(([T,P])=>a("button",{className:v===T?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>h(T),type:"button",children:P},T))}),a("div",{className:"legacy-review-bulk-row",children:[a("input",{"aria-label":"Search legacy project groups",className:"peer-scope-input legacy-review-search",onInput:T=>_(T.currentTarget.value),placeholder:"Search project, signal, or destination…",value:g}),a("button",{className:"settings-button",onClick:()=>L(!0),type:"button",children:"Select visible"}),a("button",{className:"settings-button",onClick:x,type:"button",children:"Select suggested"}),a("button",{className:"settings-button",onClick:()=>L(!1),type:"button",children:"Clear visible"}),t&&i.length>0?a("button",{className:"settings-save",disabled:w!=null||q===0||r.filter(T=>f[T.workspaceIdentity]&&It(T)&&!!u[T.workspaceIdentity]).every(T=>s[T.workspaceIdentity]),onClick:()=>{O()},type:"button",children:w==="bulk"?"Previewing…":`Preview ${q.toLocaleString()} selected`}):t&&j>0?a("span",{className:"legacy-review-cleanup-note",children:"Add or join a Space before bulk reassignment."}):null,q>0&&r.filter(T=>f[T.workspaceIdentity]&&It(T)&&!!u[T.workspaceIdentity]).every(T=>s[T.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:I.map(T=>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 ${h_(T)}`,checked:!!f[T.workspaceIdentity],className:"cm-checkbox",disabled:!It(T),onChange:P=>M(T,P.currentTarget.checked),type:"checkbox"}),a("div",{children:[a("div",{className:"legacy-review-group-title",children:h_(T)}),a("div",{className:"legacy-review-group-meta",children:[_O(T.identitySource),wO(T,i)]}),It(T)?T.peerOwnedMemoryCount?a("div",{className:"legacy-review-cleanup-note",children:[(T.reassignableMemoryCount??T.memoryCount).toLocaleString()," ","local memor",(T.reassignableMemoryCount??T.memoryCount)===1?"y":"ies"," ","can be reassigned; ",T.peerOwnedMemoryCount.toLocaleString()," peer-owned memor",T.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."}),li(T)?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:[T.memoryCount.toLocaleString()," memor",T.memoryCount===1?"y":"ies"]})]}),T.suggestionReason?a("div",{className:"legacy-review-reason",children:T.suggestionReason}):null,l[T.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:l[T.workspaceIdentity]}):null,s[T.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:[s[T.workspaceIdentity].warning," This will reassign"," ",s[T.workspaceIdentity].reassignable_memory_count.toLocaleString()," of"," ",s[T.workspaceIdentity].memory_count.toLocaleString()," memories",s[T.workspaceIdentity].skipped_memory_count?`; ${s[T.workspaceIdentity].skipped_memory_count.toLocaleString()} peer-owned copies will be left unchanged`:"","."]}):null,a(IO,{group:T}),i.length>0&&t&&It(T)?a("label",{className:"legacy-review-target",children:[a("span",{children:"Destination Space"}),a("select",{className:"peer-scope-input",disabled:w!=null,onChange:P=>A(T,P.currentTarget.value),value:u[T.workspaceIdentity]||"",children:[a("option",{value:"",children:"Choose Space…"}),i.map(P=>a("option",{value:P.scopeId,children:[P.label," · ",NO(P.authorityType),P.scopeId===T.suggestedScopeId?" · suggested":""]},P.scopeId))]})]}):null,i.length>0&&t&&It(T)?a("div",{className:"legacy-review-actions",children:a("button",{type:"button",className:"settings-button",disabled:w!=null||!u[T.workspaceIdentity],onClick:()=>{G(T)},children:w===T.workspaceIdentity?s[T.workspaceIdentity]?"Reassigning…":"Previewing…":s[T.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},T.workspaceIdentity))}):null]})}function AO({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return a(Z,{children:[t?a(PO,{item:t,onReassign:n,onReview:r??i}):null,e.map(o=>a(xO,{item:o,onReview:i},`${o.peerName}:${o.actorId}:${o.scopeLabel}`))]})}function RO(){Xm("mine"),b.feedQuery="",window.location.hash="feed"}function DO(){window.location.hash="projects"}async function LO(e,t,n,r){try{const i=await Hw({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return b.lastSyncLegacySharedReview=i.legacy_shared_review??null,ne(`Reassigned ${i.reassigned_memory_count.toLocaleString()} legacy review memor${i.reassigned_memory_count===1?"y":"ies"} to ${i.target_scope_label}.`),g_(),null}catch(i){if(i instanceof op)return i.preview;const o=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw ne(o,"warning"),new Error(o)}}function g_(){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(b.lastSyncSharingReview)?b.lastSyncSharingReview:[],o=b.lastSyncLegacySharedReview,s=Math.max(0,Number(o?.memory_count??0)),c=o?.has_data?{groups:Array.isArray(o.groups)?o.groups.map(d=>{const u=d;return{displayProject:String(u.display_project||u.project||"Unknown project"),identitySource:String(u.identity_source||"unknown"),lastUpdatedAt:typeof u.last_updated_at=="string"?u.last_updated_at:null,memoryCount:Number(u.memory_count||0),memorySamples:Array.isArray(u.memory_samples)?u.memory_samples.map(p=>{const f=p,m=f.ownership==="peer"?"peer":"local";return{bodyPreview:typeof f.body_preview=="string"?f.body_preview:null,createdAt:typeof f.created_at=="string"?f.created_at:null,cwd:typeof f.cwd=="string"?f.cwd:null,gitRemote:typeof f.git_remote=="string"?f.git_remote:null,id:Number(f.id||0),kind:typeof f.kind=="string"?f.kind:null,ownership:m,project:typeof f.project=="string"?f.project:null,title:String(f.title||`Memory ${Number(f.id||0)}`),updatedAt:typeof f.updated_at=="string"?f.updated_at:null}}):[],peerOwnedMemoryCount:Number(u.peer_owned_memory_count||0),reassignableMemoryCount:Number(u.reassignable_memory_count||0),suggestedScopeId:typeof u.suggested_scope_id=="string"?u.suggested_scope_id:null,suggestionReason:typeof u.suggestion_reason=="string"?u.suggestion_reason:null,workspaceIdentity:String(u.workspace_identity||u.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(d=>{const u=d;return{authorityType:String(u.authority_type||"unknown"),label:String(u.label||u.scope_id||"Unknown domain"),scopeId:String(u.scope_id||"")}}).filter(d=>d.scopeId):[]}:null;if(!i.length&&!c){oi(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=b.currentProject?`current project (${b.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.`,Ze(n,y(AO,{items:i.map(d=>({actorDisplayName:String(d.actor_display_name||d.actor_id||"unknown"),actorId:String(d.actor_id||"unknown"),peerName:String(d.peer_name||d.peer_device_id||"Device"),privateCount:Number(d.private_count||0),scopeLabel:String(d.scope_label||"All allowed projects"),shareableCount:Number(d.shareable_count||0)})),legacyReview:c,onLegacyReassign:LO,onLegacyReview:DO,onReview:RO}))}var Gs="",To=null,Nu=0,$O=15e3;function y_(e){return`project:${e||""}|includeJoinRequests:false`}function MO(e){const t=y_(e);return!To||To.key!==t||Date.now()>=To.expiresAtMs?null:To.payload}function OO(e,t){To={key:y_(e),expiresAtMs:Date.now()+$O,payload:t}}function jO(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function FO(){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 di(){const e=++Nu;try{const t=b.currentProject||"",n=!1,r=b.activeTab==="health";let i=!1;const o=!Fi();let s;r?(s=MO(t),s||(s=await $o(o,t,{includeJoinRequests:!1}),i=!0)):(s=await $o(o,t,{includeJoinRequests:n}),i=!0);let c=null,l=null,d=b.lastDeviceIdentityInventory,u=b.lastShareOperations,p=!1,f=!1,m=b.deviceIdentityInventoryLoadError,v=!1;const h=tM();try{c=await Nw()}catch{p=!0}try{l=await Do()}catch{f=!0}if(b.activeTab==="advanced"){m=!1;try{d=await ec()}catch{m=!0}}try{const k=await pp();u=Array.isArray(k.items)?k.items:[]}catch{v=!0}if(e!==Nu)return;i&&OO(t,jO(s));const g=JSON.stringify([s,c,l,d,m,u,v,h]);if(g===Gs)return;Gs=g;const _=s.status&&typeof s.status=="object"?s.status:null;_&&(b.lastSyncStatus=_),Array.isArray(c?.items)?b.lastSyncActors=c.items:b.lastSyncActors=[];const w=Array.isArray(s.peers)?s.peers:[],S=new Set(w.map(k=>String(k?.peer_device_id||"").trim()).filter(Boolean)),N=Array.isArray(b.pendingAcceptedSyncPeers)?b.pendingAcceptedSyncPeers.filter(k=>{const E=String(k?.peer_device_id||"").trim();return E&&!S.has(E)}):[];b.pendingAcceptedSyncPeers=N,b.lastSyncPeers=[...w,...N],m||(b.lastDeviceIdentityInventory=d),b.deviceIdentityInventoryLoadError=m,b.lastShareOperations=u,b.shareOperationsLoadError=v,b.lastSyncSharingReview=s.sharing_review||[],b.lastSyncLegacySharedReview=s.legacy_shared_review&&typeof s.legacy_shared_review=="object"?s.legacy_shared_review:null,b.lastSyncCoordinator=s.coordinator||null,b.lastCoordinatorAdminStatus=l&&typeof l=="object"?l:null,b.lastSyncJoinRequests=Array.isArray(s.join_requests)?s.join_requests:[],b.lastSyncAttempts=s.attempts||[],b.lastSyncLegacyDevices=s.legacy_devices||[],b.lastSyncDuplicatePersonDecisions=h,b.lastSyncViewModel=W$({actors:b.lastSyncActors,peers:b.lastSyncPeers,coordinator:b.lastSyncCoordinator,status:_,shareOperations:b.lastShareOperations,shareOperationsLoadError:v,reconciliation:s.recipient_policy_reconciliation,duplicatePersonDecisions:b.lastSyncDuplicatePersonDecisions}),r_(),Us(),WM(),JM(),g_(),yu(),d_(),n_(),nb(),p&&zM(),f&&(b.lastCoordinatorAdminStatus=null,Us())}catch{if(e!==Nu)return;Gs="",b.deviceIdentityInventoryLoadError=!0,Dn("syncTeamSkeleton"),Dn("syncActorsSkeleton"),Dn("syncPeersSkeleton"),Dn("syncDiagSkeleton"),FO(),YM(),lM()}}function BO(){Gs="",b.lastSyncPeers?.length&&yu()}async function UO(){try{b.pairingPayloadRaw=await kw()||null,pu()}catch{b.pairingPayloadRaw=null,pu()}}function GO(e){qL(),Ya(),eO(di),VM(di),fM(yu),iO(e,di),XM(di),mM(e),bu(),ZM()}function HO(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 qO(){try{const e=await bw();if(!e?.version)return;HO(e.version,"bafd78c")}catch{}}var ku=null,b_=1500,__="codemem-legacy-upgrade-notice-dismissed",$n=null,zt=!1,Tu=!1,Io=null;function w_(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function S_(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=w_(n.total_group_count,r.length),o=w_(n.memory_count);return i<=0||o<=0?null:{groupCount:i,memoryCount:o}}function C_(){try{return localStorage.getItem(__)==="1"}catch{return!1}}function Hs(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(__,"1")}catch{}}function N_(){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 KO(){const e=N_(),t=Le("legacyUpgradeReviewGroups");(t&&e.includes(t)?t:e[0])?.focus()}function k_(e){const t=Le("legacyUpgradeModal");if(!t||t.hidden)return;if(e.key==="Escape"){e.preventDefault(),Hs(),Eo(!1);return}if(e.key==="Enter"){const o=Le("legacyUpgradeReviewGroups");$r(e,{onSubmit:()=>o?.click(),disabled:!o||o.disabled});return}if(e.key!=="Tab")return;const n=N_();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 T_(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 Eo(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){Io=document.activeElement,document.addEventListener("keydown",k_),KO(),T_(!0);return}T_(!1),document.removeEventListener("keydown",k_),Io&&document.contains(Io)&&Io.focus(),Io=null}}function I_(e){!e||Tu||C_()||(Tu=!0,Eo(!0,e))}async function VO(){if(!(Tu||C_()))try{I_(S_(await $o(!1,"",{includeJoinRequests:!1})))}catch{}}function yr(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 Iu(){try{return await yw(),!0}catch{return!1}}function WO(){return document.visibilityState!=="hidden"&&!Nb()}function E_(){if(zt)return;zt=!0,Eu(),br("error","(reconnecting)"),yr(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await Iu()){if($n&&(clearTimeout($n),$n=null),zt=!1,yr(!0,"Viewer responded. Restoring your session…"),WO()){br("refreshing"),xo();try{await qs()}catch{}}else br("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");zt||yr(!1);return}yr(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),$n=setTimeout(e,b_)};$n=setTimeout(e,b_)}function br(e,t){b.refreshState=e;const n=Le("refreshStatus");if(!n)return;const r=o=>{const s=Le("refreshAnnouncer");!s||ku===e||(s.textContent=o,ku=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}`,ku=null}function Eu(){b.refreshTimer&&(clearInterval(b.refreshTimer),b.refreshTimer=null)}function xo(){b.refreshTimer||(b.refreshTimer=setInterval(()=>Mn(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(Eu(),br("paused","(tab hidden)")):!Nb()&&!zt&&(xo(),Mn())});function zO(){const e=b.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(/^#/,"");bu(o==="sync/diagnostics"||o==="advanced/sync/diagnostics"?"diagnostics":"main")})}function x_(e){const t=new Set(Dk(b.lastCoordinatorAdminStatus));Jn.forEach(n=>{const r=Le(`tab-${n}`);r&&(r.hidden=n!==e||!t.has(n))}),Jn.forEach(n=>{const r=Le(`tabBtn-${n}`);if(!r)return;r.hidden=!t.has(n);const i=n===e&&t.has(n);r.classList.toggle("active",i),i?r.setAttribute("aria-current","page"):r.removeAttribute("aria-current")}),zO()}function ui(e,t={}){const n=ji(e,b.lastCoordinatorAdminStatus);n==="advanced"&&nl(t.advancedSection??tl()??b.advancedSection),Ym(n,t.canonicalHash?{canonicalHash:!0}:{}),x_(n),Mn()}function JO(){Jn.forEach(e=>{Le(`tabBtn-${e}`)?.addEventListener("click",()=>ui(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),Le("advancedSyncButton")?.addEventListener("click",()=>nl("sync",!0)),Le("advancedTeamsButton")?.addEventListener("click",()=>nl("teams",!0)),window.addEventListener("hashchange",()=>{const e=el();if(e){const t=tl();ui(e,t?{advancedSection:t}:{})}}),ui(b.activeTab)}async function YO(){try{const e=await Lo();b.knownProjects=e,BO();const t=Xc("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 XO(e){b.pendingDeviceIdentityFocus=e?.trim()||null,ui("devices",{canonicalHash:!0})}var xu=ON({},{onReviewDevices:XO}),P_={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Pu=0,Au=null,Et=null;async function QO(){const e=[];let t=0;for(;;){const n=await Oo({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return da(e)}function ZO(){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 b.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"offline":"available");for(const r of b.lastSyncPeers){const i=String(r.peer_device_id??"").trim(),o=Co(r);n(i,o==="connected"||o==="available"?"available":o==="offline"?"offline":"unknown")}return[...e].map(([r,i])=>({deviceId:r,state:i}))}function ej(){return b.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 A_(e){if(e==="advanced_sync"){ui("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("tabBtn-advanced")?.focus());return}ui(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}function Ru(){const e=document.getElementById("devicesMount");if(!e)return Promise.resolve(!0);const t=tj(e,++Pu);return Au=t,t}async function tj(e,t){Et||es(e,P_,{version:1,items:[]},[],[],{loading:!0});try{const[n,r,i,o]=await Promise.all([QO(),Zs(),Iw(),ec().then(d=>({inventory:d,unavailable:!1})).catch(()=>({inventory:Et?.inventory,unavailable:!0})),di()]);if(t!==Pu)return Au??!1;const s=ZO(),c=ej(),l=mp(b.lastSyncStatus);return!o.unavailable&&o.inventory&&(b.lastDeviceIdentityInventory=o.inventory),b.deviceIdentityInventoryLoadError=o.unavailable,es(e,r,i,n,s,{inventory:o.inventory,inventoryUnavailable:o.unavailable,coordinatorEnrollmentIssueCount:l,onCommitted:async()=>{const[d,u]=await Promise.all([Ru(),xu()]);return d&&u},onNavigate:A_,peerRuntimeMetadata:c}),Et={projects:n,intent:r,reconciliation:i,availability:s,peerRuntimeMetadata:c,inventory:o.inventory,inventoryUnavailable:o.unavailable,coordinatorEnrollmentIssueCount:l},!0}catch{return t!==Pu?Au??!1:(Et?es(e,Et.intent,Et.reconciliation,Et.projects,Et.availability,{coordinatorEnrollmentIssueCount:Et.coordinatorEnrollmentIssueCount,inventory:Et.inventory,inventoryUnavailable:Et.inventoryUnavailable,onCommitted:async()=>{const[n,r]=await Promise.all([Ru(),xu()]);return n&&r},onNavigate:A_,peerRuntimeMetadata:Et.peerRuntimeMetadata,refreshError:!0}):es(e,P_,{version:1,items:[]},[],[],{loadError:!0}),!1)}}Xc("projectFilter")?.addEventListener("change",()=>{b.currentProject=Xc("projectFilter")?.value||"",dr(!0),Mn()});var Du=null;async function Mn(){zt||(Du&&clearTimeout(Du),Du=setTimeout(()=>qs(),80))}async function qs(){if(!zt){if(b.refreshInFlight){b.refreshQueued=!0;return}b.refreshInFlight=!0;try{br("refreshing");const e=b.activeTab,t=[nD(),uL()];let n=!0;e==="feed"&&t.push(Do().then(i=>{b.lastCoordinatorAdminStatus=i&&typeof i=="object"?i:null}).catch(()=>{b.lastCoordinatorAdminStatus=null})),e==="feed"&&t.push(Od()),e==="projects"&&t.push(LD()),e==="sharing"&&t.push(xu()),e==="devices"&&t.push(Ru().then(i=>{n=i})),(e==="advanced"&&b.advancedSection==="sync"||e==="health")&&t.push(di()),e==="advanced"&&b.advancedSection==="teams"&&t.push(zl()),b.syncPairingOpen&&t.push(UO()),await Promise.all(t),I_(S_(b.lastSyncLegacySharedReview));const r=ji(b.activeTab,b.lastCoordinatorAdminStatus);r!==b.activeTab&&Ym(r),x_(b.activeTab),br(n?"idle":"error")}catch{await Iu()?br("error"):E_()}finally{b.refreshInFlight=!1,b.refreshQueued&&!zt&&(b.refreshQueued=!1,qs())}}}Gk();var R_=document.getElementById("toastRoot");R_&&Ck(R_),Hk(Qc("themeToggle")),eh(il()),JO(),G0(),$D(()=>Mn()),GO(()=>Mn()),Ax(),GL(Eu,xo,()=>Mn()),YO(),Le("viewerReconnectRetry")?.addEventListener("click",async()=>{if(yr(!0,"Checking whether the viewer server is back…"),!await Iu()){E_();return}$n&&(clearTimeout($n),$n=null),zt=!1,yr(!0,"Viewer responded. Restoring your session…"),xo();try{await qs()}catch{}zt||yr(!1)}),Le("legacyUpgradeReviewGroups")?.addEventListener("click",()=>{Hs(),Eo(!1),window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)}),Le("legacyUpgradeReviewProjects")?.addEventListener("click",()=>{Hs(),Eo(!1),window.location.hash="projects"}),Le("legacyUpgradeNotNow")?.addEventListener("click",()=>{Hs(),Eo(!1)}),qO(),VO(),Mn(),xo()})();